feat(blog): add file-based blog with dynamic slugs, MDX content and layout shell

- Introduced blog routing using Next.js App Router
- Implemented dynamic [slug] pages for blog posts
- Added MDX-based content loading via lib/posts
- Integrated shared TopBar layout with navigation
- Established clear content, lib and component separation
This commit is contained in:
PascalSchattenburg
2026-01-22 14:14:15 +01:00
parent b717952234
commit d147843c76
10412 changed files with 2475583 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
import { DetachedPromise } from './detached-promise';
/**
* A wrapper for a function that will only allow one call to the function to
* execute at a time.
*/ export class Batcher {
constructor(cacheKeyFn, /**
* A function that will be called to schedule the wrapped function to be
* executed. This defaults to a function that will execute the function
* immediately.
*/ schedulerFn = (fn)=>fn()){
this.cacheKeyFn = cacheKeyFn;
this.schedulerFn = schedulerFn;
this.pending = new Map();
}
static create(options) {
return new Batcher(options == null ? void 0 : options.cacheKeyFn, options == null ? void 0 : options.schedulerFn);
}
/**
* Wraps a function in a promise that will be resolved or rejected only once
* for a given key. This will allow multiple calls to the function to be
* made, but only one will be executed at a time. The result of the first
* call will be returned to all callers.
*
* @param key the key to use for the cache
* @param fn the function to wrap
* @returns a promise that resolves to the result of the function
*/ async batch(key, fn) {
const cacheKey = this.cacheKeyFn ? await this.cacheKeyFn(key) : key;
if (cacheKey === null) {
return fn({
resolve: (value)=>Promise.resolve(value),
key
});
}
const pending = this.pending.get(cacheKey);
if (pending) return pending;
const { promise, resolve, reject } = new DetachedPromise();
this.pending.set(cacheKey, promise);
this.schedulerFn(async ()=>{
try {
const result = await fn({
resolve,
key
});
// Resolving a promise multiple times is a no-op, so we can safely
// resolve all pending promises with the same result.
resolve(result);
} catch (err) {
reject(err);
} finally{
this.pending.delete(cacheKey);
}
});
return promise;
}
}
//# sourceMappingURL=batcher.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/batcher.ts"],"sourcesContent":["import type { SchedulerFn } from './scheduler'\n\nimport { DetachedPromise } from './detached-promise'\n\ntype CacheKeyFn<K, C extends string | number | null> = (\n key: K\n) => PromiseLike<C> | C\n\ntype BatcherOptions<K, C extends string | number | null> = {\n cacheKeyFn?: CacheKeyFn<K, C>\n schedulerFn?: SchedulerFn<void>\n}\n\ntype WorkFnContext<V, K> = {\n resolve: (value: V | PromiseLike<V>) => void\n key: K\n}\n\ntype WorkFn<V, K> = (context: WorkFnContext<V, K>) => Promise<V>\n\n/**\n * A wrapper for a function that will only allow one call to the function to\n * execute at a time.\n */\nexport class Batcher<K, V, C extends string | number | null> {\n private readonly pending = new Map<C, Promise<V>>()\n\n protected constructor(\n private readonly cacheKeyFn?: CacheKeyFn<K, C>,\n /**\n * A function that will be called to schedule the wrapped function to be\n * executed. This defaults to a function that will execute the function\n * immediately.\n */\n private readonly schedulerFn: SchedulerFn<void> = (fn) => fn()\n ) {}\n\n /**\n * Creates a new instance of PendingWrapper. If the key extends a string or\n * number, the key will be used as the cache key. If the key is an object, a\n * cache key function must be provided.\n */\n public static create<K extends string | number | null, V>(\n options?: BatcherOptions<K, K>\n ): Batcher<K, V, K>\n public static create<K, V, C extends string | number | null>(\n options: BatcherOptions<K, C> &\n Required<Pick<BatcherOptions<K, C>, 'cacheKeyFn'>>\n ): Batcher<K, V, C>\n public static create<K, V, C extends string | number | null>(\n options?: BatcherOptions<K, C>\n ): Batcher<K, V, C> {\n return new Batcher<K, V, C>(options?.cacheKeyFn, options?.schedulerFn)\n }\n\n /**\n * Wraps a function in a promise that will be resolved or rejected only once\n * for a given key. This will allow multiple calls to the function to be\n * made, but only one will be executed at a time. The result of the first\n * call will be returned to all callers.\n *\n * @param key the key to use for the cache\n * @param fn the function to wrap\n * @returns a promise that resolves to the result of the function\n */\n public async batch(key: K, fn: WorkFn<V, K>): Promise<V> {\n const cacheKey = (this.cacheKeyFn ? await this.cacheKeyFn(key) : key) as C\n if (cacheKey === null) {\n return fn({ resolve: (value) => Promise.resolve(value), key })\n }\n\n const pending = this.pending.get(cacheKey)\n if (pending) return pending\n\n const { promise, resolve, reject } = new DetachedPromise<V>()\n this.pending.set(cacheKey, promise)\n\n this.schedulerFn(async () => {\n try {\n const result = await fn({ resolve, key })\n\n // Resolving a promise multiple times is a no-op, so we can safely\n // resolve all pending promises with the same result.\n resolve(result)\n } catch (err) {\n reject(err)\n } finally {\n this.pending.delete(cacheKey)\n }\n })\n\n return promise\n }\n}\n"],"names":["DetachedPromise","Batcher","cacheKeyFn","schedulerFn","fn","pending","Map","create","options","batch","key","cacheKey","resolve","value","Promise","get","promise","reject","set","result","err","delete"],"mappings":"AAEA,SAASA,eAAe,QAAQ,qBAAoB;AAkBpD;;;CAGC,GACD,OAAO,MAAMC;IAGX,YACE,AAAiBC,UAA6B,EAC9C;;;;KAIC,GACD,AAAiBC,cAAiC,CAACC,KAAOA,IAAI,CAC9D;aAPiBF,aAAAA;aAMAC,cAAAA;aATFE,UAAU,IAAIC;IAU5B;IAcH,OAAcC,OACZC,OAA8B,EACZ;QAClB,OAAO,IAAIP,QAAiBO,2BAAAA,QAASN,UAAU,EAAEM,2BAAAA,QAASL,WAAW;IACvE;IAEA;;;;;;;;;GASC,GACD,MAAaM,MAAMC,GAAM,EAAEN,EAAgB,EAAc;QACvD,MAAMO,WAAY,IAAI,CAACT,UAAU,GAAG,MAAM,IAAI,CAACA,UAAU,CAACQ,OAAOA;QACjE,IAAIC,aAAa,MAAM;YACrB,OAAOP,GAAG;gBAAEQ,SAAS,CAACC,QAAUC,QAAQF,OAAO,CAACC;gBAAQH;YAAI;QAC9D;QAEA,MAAML,UAAU,IAAI,CAACA,OAAO,CAACU,GAAG,CAACJ;QACjC,IAAIN,SAAS,OAAOA;QAEpB,MAAM,EAAEW,OAAO,EAAEJ,OAAO,EAAEK,MAAM,EAAE,GAAG,IAAIjB;QACzC,IAAI,CAACK,OAAO,CAACa,GAAG,CAACP,UAAUK;QAE3B,IAAI,CAACb,WAAW,CAAC;YACf,IAAI;gBACF,MAAMgB,SAAS,MAAMf,GAAG;oBAAEQ;oBAASF;gBAAI;gBAEvC,kEAAkE;gBAClE,qDAAqD;gBACrDE,QAAQO;YACV,EAAE,OAAOC,KAAK;gBACZH,OAAOG;YACT,SAAU;gBACR,IAAI,CAACf,OAAO,CAACgB,MAAM,CAACV;YACtB;QACF;QAEA,OAAOK;IACT;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,36 @@
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp';
import { normalizeRouteRegex } from './load-custom-routes';
import { getRedirectStatus, modifyRouteRegex } from './redirect-status';
export function buildCustomRoute(type, route, restrictedRedirectPaths) {
const compiled = pathToRegexp(route.source, [], {
strict: true,
sensitive: false,
delimiter: '/'
});
// If this is an internal rewrite and it already provides a regex, use it
// otherwise, normalize the source to a regex.
let regex;
if (!route.internal || type !== 'rewrite' || !('regex' in route) || typeof route.regex !== 'string') {
let source = compiled.source;
if (!route.internal) {
source = modifyRouteRegex(source, type === 'redirect' ? restrictedRedirectPaths : undefined);
}
regex = normalizeRouteRegex(source);
} else {
regex = route.regex;
}
if (type !== 'redirect') {
return {
...route,
regex
};
}
return {
...route,
statusCode: getRedirectStatus(route),
permanent: undefined,
regex
};
}
//# sourceMappingURL=build-custom-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/build-custom-route.ts"],"sourcesContent":["import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'\nimport type {\n ManifestHeaderRoute,\n ManifestRedirectRoute,\n ManifestRewriteRoute,\n} from '../build'\nimport {\n normalizeRouteRegex,\n type Header,\n type Redirect,\n type Rewrite,\n type RouteType,\n} from './load-custom-routes'\nimport { getRedirectStatus, modifyRouteRegex } from './redirect-status'\n\nexport function buildCustomRoute(\n type: 'header',\n route: Header\n): ManifestHeaderRoute\nexport function buildCustomRoute(\n type: 'rewrite',\n route: Rewrite\n): ManifestRewriteRoute\nexport function buildCustomRoute(\n type: 'redirect',\n route: Redirect,\n restrictedRedirectPaths: string[]\n): ManifestRedirectRoute\nexport function buildCustomRoute(\n type: RouteType,\n route: Redirect | Rewrite | Header,\n restrictedRedirectPaths?: string[]\n): ManifestHeaderRoute | ManifestRewriteRoute | ManifestRedirectRoute {\n const compiled = pathToRegexp(route.source, [], {\n strict: true,\n sensitive: false,\n delimiter: '/', // default is `/#?`, but Next does not pass query info\n })\n\n // If this is an internal rewrite and it already provides a regex, use it\n // otherwise, normalize the source to a regex.\n let regex: string\n if (\n !route.internal ||\n type !== 'rewrite' ||\n !('regex' in route) ||\n typeof route.regex !== 'string'\n ) {\n let source = compiled.source\n if (!route.internal) {\n source = modifyRouteRegex(\n source,\n type === 'redirect' ? restrictedRedirectPaths : undefined\n )\n }\n\n regex = normalizeRouteRegex(source)\n } else {\n regex = route.regex\n }\n\n if (type !== 'redirect') {\n return { ...route, regex }\n }\n\n return {\n ...route,\n statusCode: getRedirectStatus(route as Redirect),\n permanent: undefined,\n regex,\n }\n}\n"],"names":["pathToRegexp","normalizeRouteRegex","getRedirectStatus","modifyRouteRegex","buildCustomRoute","type","route","restrictedRedirectPaths","compiled","source","strict","sensitive","delimiter","regex","internal","undefined","statusCode","permanent"],"mappings":"AAAA,SAASA,YAAY,QAAQ,oCAAmC;AAMhE,SACEC,mBAAmB,QAKd,uBAAsB;AAC7B,SAASC,iBAAiB,EAAEC,gBAAgB,QAAQ,oBAAmB;AAevE,OAAO,SAASC,iBACdC,IAAe,EACfC,KAAkC,EAClCC,uBAAkC;IAElC,MAAMC,WAAWR,aAAaM,MAAMG,MAAM,EAAE,EAAE,EAAE;QAC9CC,QAAQ;QACRC,WAAW;QACXC,WAAW;IACb;IAEA,yEAAyE;IACzE,8CAA8C;IAC9C,IAAIC;IACJ,IACE,CAACP,MAAMQ,QAAQ,IACfT,SAAS,aACT,CAAE,CAAA,WAAWC,KAAI,KACjB,OAAOA,MAAMO,KAAK,KAAK,UACvB;QACA,IAAIJ,SAASD,SAASC,MAAM;QAC5B,IAAI,CAACH,MAAMQ,QAAQ,EAAE;YACnBL,SAASN,iBACPM,QACAJ,SAAS,aAAaE,0BAA0BQ;QAEpD;QAEAF,QAAQZ,oBAAoBQ;IAC9B,OAAO;QACLI,QAAQP,MAAMO,KAAK;IACrB;IAEA,IAAIR,SAAS,YAAY;QACvB,OAAO;YAAE,GAAGC,KAAK;YAAEO;QAAM;IAC3B;IAEA,OAAO;QACL,GAAGP,KAAK;QACRU,YAAYd,kBAAkBI;QAC9BW,WAAWF;QACXF;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,83 @@
/// Utilties for configuring the bundler to use.
export var Bundler = /*#__PURE__*/ function(Bundler) {
Bundler[Bundler["Turbopack"] = 0] = "Turbopack";
Bundler[Bundler["Webpack"] = 1] = "Webpack";
Bundler[Bundler["Rspack"] = 2] = "Rspack";
return Bundler;
}({});
/**
* Parse the bundler arguments and potentially sets the `TURBOPACK` environment variable.
*
* NOTE: rspack is configured via next config which is chaotic so it is possible for this to be overridden later.
*
* @param options The options to parse.
* @returns The bundler that was configured
*/ export function parseBundlerArgs(options) {
const bundlerFlags = new Map();
const setBundlerFlag = (bundler, flag)=>{
bundlerFlags.set(bundler, (bundlerFlags.get(bundler) ?? []).concat(flag));
};
// What turbo flag was set? We allow multiple to be set, which is silly but not ambiguous, just pick the most relevant one.
if (options.turbopack) {
setBundlerFlag(0, '--turbopack');
}
if (options.turbo) {
setBundlerFlag(0, '--turbo');
} else if (process.env.TURBOPACK) {
// We don't really want to support this but it is trivial and not really confusing.
// If we don't support it and someone sets it, we would have inconsistent behavior
// since some parts of next would read the return value of this function and other
// parts will read the env variable.
setBundlerFlag(0, `TURBOPACK=${process.env.TURBOPACK}`);
} else if (process.env.IS_TURBOPACK_TEST) {
setBundlerFlag(0, `IS_TURBOPACK_TEST=${process.env.IS_TURBOPACK_TEST}`);
}
if (options.webpack) {
setBundlerFlag(1, '--webpack');
}
if (process.env.IS_WEBPACK_TEST) {
setBundlerFlag(1, `IS_WEBPACK_TEST=${process.env.IS_WEBPACK_TEST}`);
}
// Mostly this is set via the NextConfig but it can also be set via the command line which is
// common for testing.
if (process.env.NEXT_RSPACK) {
setBundlerFlag(2, `NEXT_RSPACK=${process.env.NEXT_RSPACK}`);
}
if (process.env.NEXT_TEST_USE_RSPACK) {
setBundlerFlag(2, `NEXT_TEST_USE_RSPACK=${process.env.NEXT_TEST_USE_RSPACK}`);
}
if (bundlerFlags.size > 1) {
console.error(`Multiple bundler flags set: ${Array.from(bundlerFlags.values()).flat().join(', ')}.
Edit your command or your package.json script to configure only one bundler.`);
process.exit(1);
}
// The default is turbopack when nothing is configured.
if (bundlerFlags.size === 0) {
process.env.TURBOPACK = 'auto';
return 0;
}
if (bundlerFlags.has(0)) {
// Only conditionally assign to the environment variable, preserving already set values.
// If it was set to 'auto' because no flag was set and this function is called a second time we
// would upgrade to '1' but we don't really want that.
process.env.TURBOPACK ??= '1';
return 0;
}
// Otherwise it is one of rspack or webpack. At this point there must be exactly one key in the map.
return bundlerFlags.keys().next().value;
}
/**
* Finalize the bundler based on the config.
*
* Rspack is configured via next config by setting an environment variable (yay, side effects)
* so this should only be called after parsing the config.
*/ export function finalizeBundlerFromConfig(fromOptions) {
// Reading the next config can set NEXT_RSPACK environment variables.
if (process.env.NEXT_RSPACK) {
return 2;
}
return fromOptions;
}
//# sourceMappingURL=bundler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,24 @@
import { extractInfoFromServerReferenceId } from '../shared/lib/server-reference-info';
export function isServerReference(value) {
return value.$$typeof === Symbol.for('react.server.reference');
}
export function isUseCacheFunction(value) {
if (!isServerReference(value)) {
return false;
}
const { type } = extractInfoFromServerReferenceId(value.$$id);
return type === 'use-cache';
}
export function getUseCacheFunctionInfo(value) {
if (!isServerReference(value)) {
return null;
}
const info = extractInfoFromServerReferenceId(value.$$id);
return info.type === 'use-cache' ? info : null;
}
export function isClientReference(mod) {
const defaultExport = (mod == null ? void 0 : mod.default) || mod;
return (defaultExport == null ? void 0 : defaultExport.$$typeof) === Symbol.for('react.client.reference');
}
//# sourceMappingURL=client-and-server-references.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/client-and-server-references.ts"],"sourcesContent":["import {\n extractInfoFromServerReferenceId,\n type ServerReferenceInfo,\n} from '../shared/lib/server-reference-info'\n\n// Only contains the properties we're interested in.\nexport interface ServerReference {\n $$typeof: Symbol\n $$id: string\n}\n\nexport type ServerFunction = ServerReference &\n ((...args: unknown[]) => Promise<unknown>)\n\nexport function isServerReference<T>(\n value: T & Partial<ServerReference>\n): value is T & ServerFunction {\n return value.$$typeof === Symbol.for('react.server.reference')\n}\n\nexport function isUseCacheFunction<T>(\n value: T & Partial<ServerReference>\n): value is T & ServerFunction {\n if (!isServerReference(value)) {\n return false\n }\n\n const { type } = extractInfoFromServerReferenceId(value.$$id)\n\n return type === 'use-cache'\n}\n\nexport function getUseCacheFunctionInfo<T>(\n value: T & Partial<ServerReference>\n): ServerReferenceInfo | null {\n if (!isServerReference(value)) {\n return null\n }\n\n const info = extractInfoFromServerReferenceId(value.$$id)\n\n return info.type === 'use-cache' ? info : null\n}\n\nexport function isClientReference(mod: any): boolean {\n const defaultExport = mod?.default || mod\n return defaultExport?.$$typeof === Symbol.for('react.client.reference')\n}\n"],"names":["extractInfoFromServerReferenceId","isServerReference","value","$$typeof","Symbol","for","isUseCacheFunction","type","$$id","getUseCacheFunctionInfo","info","isClientReference","mod","defaultExport","default"],"mappings":"AAAA,SACEA,gCAAgC,QAE3B,sCAAqC;AAW5C,OAAO,SAASC,kBACdC,KAAmC;IAEnC,OAAOA,MAAMC,QAAQ,KAAKC,OAAOC,GAAG,CAAC;AACvC;AAEA,OAAO,SAASC,mBACdJ,KAAmC;IAEnC,IAAI,CAACD,kBAAkBC,QAAQ;QAC7B,OAAO;IACT;IAEA,MAAM,EAAEK,IAAI,EAAE,GAAGP,iCAAiCE,MAAMM,IAAI;IAE5D,OAAOD,SAAS;AAClB;AAEA,OAAO,SAASE,wBACdP,KAAmC;IAEnC,IAAI,CAACD,kBAAkBC,QAAQ;QAC7B,OAAO;IACT;IAEA,MAAMQ,OAAOV,iCAAiCE,MAAMM,IAAI;IAExD,OAAOE,KAAKH,IAAI,KAAK,cAAcG,OAAO;AAC5C;AAEA,OAAO,SAASC,kBAAkBC,GAAQ;IACxC,MAAMC,gBAAgBD,CAAAA,uBAAAA,IAAKE,OAAO,KAAIF;IACtC,OAAOC,CAAAA,iCAAAA,cAAeV,QAAQ,MAAKC,OAAOC,GAAG,CAAC;AAChD","ignoreList":[0]}

View File

@@ -0,0 +1,29 @@
const globalInvokeCache = new Map();
export function withCoalescedInvoke(func) {
return async function(key, args) {
const entry = globalInvokeCache.get(key);
if (entry) {
return entry.then((res)=>({
isOrigin: false,
value: res.value
}));
}
async function __wrapper() {
return await func.apply(undefined, args);
}
const future = __wrapper().then((res)=>{
globalInvokeCache.delete(key);
return {
isOrigin: true,
value: res
};
}).catch((err)=>{
globalInvokeCache.delete(key);
return Promise.reject(err);
});
globalInvokeCache.set(key, future);
return future;
};
}
//# sourceMappingURL=coalesced-function.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/coalesced-function.ts"],"sourcesContent":["type CoalescedInvoke<T> = {\n isOrigin: boolean\n value: T\n}\n\nexport type UnwrapPromise<T> = T extends Promise<infer U> ? U : T\n\nconst globalInvokeCache = new Map<string, Promise<CoalescedInvoke<unknown>>>()\n\nexport function withCoalescedInvoke<F extends (...args: any) => any>(\n func: F\n): (\n key: string,\n args: Parameters<F>\n) => Promise<CoalescedInvoke<UnwrapPromise<ReturnType<F>>>> {\n return async function (key: string, args: Parameters<F>) {\n const entry = globalInvokeCache.get(key)\n if (entry) {\n return entry.then((res) => ({\n isOrigin: false,\n value: res.value as UnwrapPromise<ReturnType<F>>,\n }))\n }\n\n async function __wrapper() {\n return await func.apply(undefined, args)\n }\n\n const future = __wrapper()\n .then((res) => {\n globalInvokeCache.delete(key)\n return { isOrigin: true, value: res as UnwrapPromise<ReturnType<F>> }\n })\n .catch((err) => {\n globalInvokeCache.delete(key)\n return Promise.reject(err)\n })\n globalInvokeCache.set(key, future)\n return future\n }\n}\n"],"names":["globalInvokeCache","Map","withCoalescedInvoke","func","key","args","entry","get","then","res","isOrigin","value","__wrapper","apply","undefined","future","delete","catch","err","Promise","reject","set"],"mappings":"AAOA,MAAMA,oBAAoB,IAAIC;AAE9B,OAAO,SAASC,oBACdC,IAAO;IAKP,OAAO,eAAgBC,GAAW,EAAEC,IAAmB;QACrD,MAAMC,QAAQN,kBAAkBO,GAAG,CAACH;QACpC,IAAIE,OAAO;YACT,OAAOA,MAAME,IAAI,CAAC,CAACC,MAAS,CAAA;oBAC1BC,UAAU;oBACVC,OAAOF,IAAIE,KAAK;gBAClB,CAAA;QACF;QAEA,eAAeC;YACb,OAAO,MAAMT,KAAKU,KAAK,CAACC,WAAWT;QACrC;QAEA,MAAMU,SAASH,YACZJ,IAAI,CAAC,CAACC;YACLT,kBAAkBgB,MAAM,CAACZ;YACzB,OAAO;gBAAEM,UAAU;gBAAMC,OAAOF;YAAoC;QACtE,GACCQ,KAAK,CAAC,CAACC;YACNlB,kBAAkBgB,MAAM,CAACZ;YACzB,OAAOe,QAAQC,MAAM,CAACF;QACxB;QACFlB,kBAAkBqB,GAAG,CAACjB,KAAKW;QAC3B,OAAOA;IACT;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,4 @@
export class CompileError extends Error {
}
//# sourceMappingURL=compile-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/compile-error.ts"],"sourcesContent":["export class CompileError extends Error {}\n"],"names":["CompileError","Error"],"mappings":"AAAA,OAAO,MAAMA,qBAAqBC;AAAO","ignoreList":[0]}

View File

@@ -0,0 +1,171 @@
export const TEXT_PLAIN_CONTENT_TYPE_HEADER = 'text/plain';
export const HTML_CONTENT_TYPE_HEADER = 'text/html; charset=utf-8';
export const JSON_CONTENT_TYPE_HEADER = 'application/json; charset=utf-8';
export const NEXT_QUERY_PARAM_PREFIX = 'nxtP';
export const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI';
export const MATCHED_PATH_HEADER = 'x-matched-path';
export const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate';
export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER = 'x-prerender-revalidate-if-generated';
export const RSC_SEGMENTS_DIR_SUFFIX = '.segments';
export const RSC_SEGMENT_SUFFIX = '.segment.rsc';
export const RSC_SUFFIX = '.rsc';
export const ACTION_SUFFIX = '.action';
export const NEXT_DATA_SUFFIX = '.json';
export const NEXT_META_SUFFIX = '.meta';
export const NEXT_BODY_SUFFIX = '.body';
export const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags';
export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags';
export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER = 'x-next-revalidate-tag-token';
export const NEXT_RESUME_HEADER = 'next-resume';
// if these change make sure we update the related
// documentation as well
export const NEXT_CACHE_TAG_MAX_ITEMS = 128;
export const NEXT_CACHE_TAG_MAX_LENGTH = 256;
export const NEXT_CACHE_SOFT_TAG_MAX_LENGTH = 1024;
export const NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_';
// in seconds
export const CACHE_ONE_YEAR = 31536000;
// in seconds, represents revalidate=false. I.e. never revaliate.
// We use this value since it can be represented as a V8 SMI for optimal performance.
// It can also be serialized as JSON if it ever leaks accidentally as an actual value.
export const INFINITE_CACHE = 0xfffffffe;
// Patterns to detect middleware files
export const MIDDLEWARE_FILENAME = 'middleware';
export const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`;
// Patterns to detect proxy files (replacement for middleware)
export const PROXY_FILENAME = 'proxy';
export const PROXY_LOCATION_REGEXP = `(?:src/)?${PROXY_FILENAME}`;
// Pattern to detect instrumentation hooks file
export const INSTRUMENTATION_HOOK_FILENAME = 'instrumentation';
// Because on Windows absolute paths in the generated code can break because of numbers, eg 1 in the path,
// we have to use a private alias
export const PAGES_DIR_ALIAS = 'private-next-pages';
export const DOT_NEXT_ALIAS = 'private-dot-next';
export const ROOT_DIR_ALIAS = 'private-next-root-dir';
export const APP_DIR_ALIAS = 'private-next-app-dir';
export const RSC_MOD_REF_PROXY_ALIAS = 'private-next-rsc-mod-ref-proxy';
export const RSC_ACTION_VALIDATE_ALIAS = 'private-next-rsc-action-validate';
export const RSC_ACTION_PROXY_ALIAS = 'private-next-rsc-server-reference';
export const RSC_CACHE_WRAPPER_ALIAS = 'private-next-rsc-cache-wrapper';
export const RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS = 'private-next-rsc-track-dynamic-import';
export const RSC_ACTION_ENCRYPTION_ALIAS = 'private-next-rsc-action-encryption';
export const RSC_ACTION_CLIENT_WRAPPER_ALIAS = 'private-next-rsc-action-client-wrapper';
export const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`;
export const SSG_GET_INITIAL_PROPS_CONFLICT = `You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps`;
export const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.`;
export const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps`;
export const STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR = `can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props`;
export const SERVER_PROPS_EXPORT_ERROR = `pages with \`getServerSideProps\` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export`;
export const GSP_NO_RETURNED_VALUE = 'Your `getStaticProps` function did not return an object. Did you forget to add a `return`?';
export const GSSP_NO_RETURNED_VALUE = 'Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?';
export const UNSTABLE_REVALIDATE_RENAME_ERROR = 'The `unstable_revalidate` property is available for general use.\n' + 'Please use `revalidate` instead.';
export const GSSP_COMPONENT_MEMBER_ERROR = `can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member`;
export const NON_STANDARD_NODE_ENV = `You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env`;
export const SSG_FALLBACK_EXPORT_ERROR = `Pages with \`fallback\` enabled in \`getStaticPaths\` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export`;
export const ESLINT_DEFAULT_DIRS = [
'app',
'pages',
'components',
'lib',
'src'
];
export const SERVER_RUNTIME = {
edge: 'edge',
experimentalEdge: 'experimental-edge',
nodejs: 'nodejs'
};
export const WEB_SOCKET_MAX_RECONNECTIONS = 12;
/**
* The names of the webpack layers. These layers are the primitives for the
* webpack chunks.
*/ const WEBPACK_LAYERS_NAMES = {
/**
* The layer for the shared code between the client and server bundles.
*/ shared: 'shared',
/**
* The layer for server-only runtime and picking up `react-server` export conditions.
* Including app router RSC pages and app router custom routes and metadata routes.
*/ reactServerComponents: 'rsc',
/**
* Server Side Rendering layer for app (ssr).
*/ serverSideRendering: 'ssr',
/**
* The browser client bundle layer for actions.
*/ actionBrowser: 'action-browser',
/**
* The Node.js bundle layer for the API routes.
*/ apiNode: 'api-node',
/**
* The Edge Lite bundle layer for the API routes.
*/ apiEdge: 'api-edge',
/**
* The layer for the middleware code.
*/ middleware: 'middleware',
/**
* The layer for the instrumentation hooks.
*/ instrument: 'instrument',
/**
* The layer for assets on the edge.
*/ edgeAsset: 'edge-asset',
/**
* The browser client bundle layer for App directory.
*/ appPagesBrowser: 'app-pages-browser',
/**
* The browser client bundle layer for Pages directory.
*/ pagesDirBrowser: 'pages-dir-browser',
/**
* The Edge Lite bundle layer for Pages directory.
*/ pagesDirEdge: 'pages-dir-edge',
/**
* The Node.js bundle layer for Pages directory.
*/ pagesDirNode: 'pages-dir-node'
};
const WEBPACK_LAYERS = {
...WEBPACK_LAYERS_NAMES,
GROUP: {
builtinReact: [
WEBPACK_LAYERS_NAMES.reactServerComponents,
WEBPACK_LAYERS_NAMES.actionBrowser
],
serverOnly: [
WEBPACK_LAYERS_NAMES.reactServerComponents,
WEBPACK_LAYERS_NAMES.actionBrowser,
WEBPACK_LAYERS_NAMES.instrument,
WEBPACK_LAYERS_NAMES.middleware
],
neutralTarget: [
// pages api
WEBPACK_LAYERS_NAMES.apiNode,
WEBPACK_LAYERS_NAMES.apiEdge
],
clientOnly: [
WEBPACK_LAYERS_NAMES.serverSideRendering,
WEBPACK_LAYERS_NAMES.appPagesBrowser
],
bundled: [
WEBPACK_LAYERS_NAMES.reactServerComponents,
WEBPACK_LAYERS_NAMES.actionBrowser,
WEBPACK_LAYERS_NAMES.serverSideRendering,
WEBPACK_LAYERS_NAMES.appPagesBrowser,
WEBPACK_LAYERS_NAMES.shared,
WEBPACK_LAYERS_NAMES.instrument,
WEBPACK_LAYERS_NAMES.middleware
],
appPages: [
// app router pages and layouts
WEBPACK_LAYERS_NAMES.reactServerComponents,
WEBPACK_LAYERS_NAMES.serverSideRendering,
WEBPACK_LAYERS_NAMES.appPagesBrowser,
WEBPACK_LAYERS_NAMES.actionBrowser
]
}
};
const WEBPACK_RESOURCE_QUERIES = {
edgeSSREntry: '__next_edge_ssr_entry__',
metadata: '__next_metadata__',
metadataRoute: '__next_metadata_route__',
metadataImageMeta: '__next_metadata_image_meta__'
};
export { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES };
//# sourceMappingURL=constants.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,57 @@
import { BloomFilter } from '../shared/lib/bloom-filter';
import { isDynamicRoute } from '../shared/lib/router/utils';
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash';
import { tryToParsePath } from './try-to-parse-path';
import { extractInterceptionRouteInformation, isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes';
export function createClientRouterFilter(paths, redirects, allowedErrorRate) {
const staticPaths = new Set();
const dynamicPaths = new Set();
for (let path of paths){
if (isDynamicRoute(path)) {
if (isInterceptionRouteAppPath(path)) {
path = extractInterceptionRouteInformation(path).interceptedRoute;
}
let subPath = '';
const pathParts = path.split('/');
// start at 1 since we split on '/' and the path starts
// with this so the first entry is an empty string
for(let i = 1; i < pathParts.length; i++){
const curPart = pathParts[i];
if (curPart.startsWith('[')) {
break;
}
subPath = `${subPath}/${curPart}`;
}
if (subPath) {
dynamicPaths.add(subPath);
}
} else {
staticPaths.add(path);
}
}
for (const redirect of redirects){
const { source } = redirect;
const path = removeTrailingSlash(source);
let tokens = [];
try {
tokens = tryToParsePath(source).tokens || [];
} catch {}
if (tokens.every((token)=>typeof token === 'string')) {
// only include static redirects initially
staticPaths.add(path);
}
}
const staticFilter = BloomFilter.from([
...staticPaths
], allowedErrorRate);
const dynamicFilter = BloomFilter.from([
...dynamicPaths
], allowedErrorRate);
const data = {
staticFilter: staticFilter.export(),
dynamicFilter: dynamicFilter.export()
};
return data;
}
//# sourceMappingURL=create-client-router-filter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/create-client-router-filter.ts"],"sourcesContent":["import type { Token } from 'next/dist/compiled/path-to-regexp'\nimport { BloomFilter } from '../shared/lib/bloom-filter'\nimport { isDynamicRoute } from '../shared/lib/router/utils'\nimport { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport type { Redirect } from './load-custom-routes'\nimport { tryToParsePath } from './try-to-parse-path'\nimport {\n extractInterceptionRouteInformation,\n isInterceptionRouteAppPath,\n} from '../shared/lib/router/utils/interception-routes'\n\nexport function createClientRouterFilter(\n paths: string[],\n redirects: Redirect[],\n allowedErrorRate?: number\n): {\n staticFilter: ReturnType<BloomFilter['export']>\n dynamicFilter: ReturnType<BloomFilter['export']>\n} {\n const staticPaths = new Set<string>()\n const dynamicPaths = new Set<string>()\n\n for (let path of paths) {\n if (isDynamicRoute(path)) {\n if (isInterceptionRouteAppPath(path)) {\n path = extractInterceptionRouteInformation(path).interceptedRoute\n }\n\n let subPath = ''\n const pathParts = path.split('/')\n\n // start at 1 since we split on '/' and the path starts\n // with this so the first entry is an empty string\n for (let i = 1; i < pathParts.length; i++) {\n const curPart = pathParts[i]\n\n if (curPart.startsWith('[')) {\n break\n }\n subPath = `${subPath}/${curPart}`\n }\n\n if (subPath) {\n dynamicPaths.add(subPath)\n }\n } else {\n staticPaths.add(path)\n }\n }\n\n for (const redirect of redirects) {\n const { source } = redirect\n const path = removeTrailingSlash(source)\n let tokens: Token[] = []\n\n try {\n tokens = tryToParsePath(source).tokens || []\n } catch {}\n\n if (tokens.every((token) => typeof token === 'string')) {\n // only include static redirects initially\n staticPaths.add(path)\n }\n }\n\n const staticFilter = BloomFilter.from([...staticPaths], allowedErrorRate)\n\n const dynamicFilter = BloomFilter.from([...dynamicPaths], allowedErrorRate)\n const data = {\n staticFilter: staticFilter.export(),\n dynamicFilter: dynamicFilter.export(),\n }\n return data\n}\n"],"names":["BloomFilter","isDynamicRoute","removeTrailingSlash","tryToParsePath","extractInterceptionRouteInformation","isInterceptionRouteAppPath","createClientRouterFilter","paths","redirects","allowedErrorRate","staticPaths","Set","dynamicPaths","path","interceptedRoute","subPath","pathParts","split","i","length","curPart","startsWith","add","redirect","source","tokens","every","token","staticFilter","from","dynamicFilter","data","export"],"mappings":"AACA,SAASA,WAAW,QAAQ,6BAA4B;AACxD,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,mBAAmB,QAAQ,mDAAkD;AAEtF,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SACEC,mCAAmC,EACnCC,0BAA0B,QACrB,iDAAgD;AAEvD,OAAO,SAASC,yBACdC,KAAe,EACfC,SAAqB,EACrBC,gBAAyB;IAKzB,MAAMC,cAAc,IAAIC;IACxB,MAAMC,eAAe,IAAID;IAEzB,KAAK,IAAIE,QAAQN,MAAO;QACtB,IAAIN,eAAeY,OAAO;YACxB,IAAIR,2BAA2BQ,OAAO;gBACpCA,OAAOT,oCAAoCS,MAAMC,gBAAgB;YACnE;YAEA,IAAIC,UAAU;YACd,MAAMC,YAAYH,KAAKI,KAAK,CAAC;YAE7B,uDAAuD;YACvD,kDAAkD;YAClD,IAAK,IAAIC,IAAI,GAAGA,IAAIF,UAAUG,MAAM,EAAED,IAAK;gBACzC,MAAME,UAAUJ,SAAS,CAACE,EAAE;gBAE5B,IAAIE,QAAQC,UAAU,CAAC,MAAM;oBAC3B;gBACF;gBACAN,UAAU,GAAGA,QAAQ,CAAC,EAAEK,SAAS;YACnC;YAEA,IAAIL,SAAS;gBACXH,aAAaU,GAAG,CAACP;YACnB;QACF,OAAO;YACLL,YAAYY,GAAG,CAACT;QAClB;IACF;IAEA,KAAK,MAAMU,YAAYf,UAAW;QAChC,MAAM,EAAEgB,MAAM,EAAE,GAAGD;QACnB,MAAMV,OAAOX,oBAAoBsB;QACjC,IAAIC,SAAkB,EAAE;QAExB,IAAI;YACFA,SAAStB,eAAeqB,QAAQC,MAAM,IAAI,EAAE;QAC9C,EAAE,OAAM,CAAC;QAET,IAAIA,OAAOC,KAAK,CAAC,CAACC,QAAU,OAAOA,UAAU,WAAW;YACtD,0CAA0C;YAC1CjB,YAAYY,GAAG,CAACT;QAClB;IACF;IAEA,MAAMe,eAAe5B,YAAY6B,IAAI,CAAC;WAAInB;KAAY,EAAED;IAExD,MAAMqB,gBAAgB9B,YAAY6B,IAAI,CAAC;WAAIjB;KAAa,EAAEH;IAC1D,MAAMsB,OAAO;QACXH,cAAcA,aAAaI,MAAM;QACjCF,eAAeA,cAAcE,MAAM;IACrC;IACA,OAAOD;AACT","ignoreList":[0]}

View File

@@ -0,0 +1 @@
["geist"]

View File

@@ -0,0 +1,22 @@
/**
* A `Promise.withResolvers` implementation that exposes the `resolve` and
* `reject` functions on a `Promise`.
*
* @see https://tc39.es/proposal-promise-with-resolvers/
*/ export class DetachedPromise {
constructor(){
let resolve;
let reject;
// Create the promise and assign the resolvers to the object.
this.promise = new Promise((res, rej)=>{
resolve = res;
reject = rej;
});
// We know that resolvers is defined because the Promise constructor runs
// synchronously.
this.resolve = resolve;
this.reject = reject;
}
}
//# sourceMappingURL=detached-promise.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/detached-promise.ts"],"sourcesContent":["/**\n * A `Promise.withResolvers` implementation that exposes the `resolve` and\n * `reject` functions on a `Promise`.\n *\n * @see https://tc39.es/proposal-promise-with-resolvers/\n */\nexport class DetachedPromise<T = any> {\n public readonly resolve: (value: T | PromiseLike<T>) => void\n public readonly reject: (reason: any) => void\n public readonly promise: Promise<T>\n\n constructor() {\n let resolve: (value: T | PromiseLike<T>) => void\n let reject: (reason: any) => void\n\n // Create the promise and assign the resolvers to the object.\n this.promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n\n // We know that resolvers is defined because the Promise constructor runs\n // synchronously.\n this.resolve = resolve!\n this.reject = reject!\n }\n}\n"],"names":["DetachedPromise","constructor","resolve","reject","promise","Promise","res","rej"],"mappings":"AAAA;;;;;CAKC,GACD,OAAO,MAAMA;IAKXC,aAAc;QACZ,IAAIC;QACJ,IAAIC;QAEJ,6DAA6D;QAC7D,IAAI,CAACC,OAAO,GAAG,IAAIC,QAAW,CAACC,KAAKC;YAClCL,UAAUI;YACVH,SAASI;QACX;QAEA,yEAAyE;QACzE,iBAAiB;QACjB,IAAI,CAACL,OAAO,GAAGA;QACf,IAAI,CAACC,MAAM,GAAGA;IAChB;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,41 @@
// the minimum number of operations required to convert string a to string b.
function minDistance(a, b, threshold) {
const m = a.length;
const n = b.length;
if (m < n) {
return minDistance(b, a, threshold);
}
if (n === 0) {
return m;
}
let previousRow = Array.from({
length: n + 1
}, (_, i)=>i);
for(let i = 0; i < m; i++){
const s1 = a[i];
let currentRow = [
i + 1
];
for(let j = 0; j < n; j++){
const s2 = b[j];
const insertions = previousRow[j + 1] + 1;
const deletions = currentRow[j] + 1;
const substitutions = previousRow[j] + Number(s1 !== s2);
currentRow.push(Math.min(insertions, deletions, substitutions));
}
previousRow = currentRow;
}
return previousRow[previousRow.length - 1];
}
export function detectTypo(input, options, threshold = 2) {
const potentialTypos = options.map((o)=>({
option: o,
distance: minDistance(o, input, threshold)
})).filter(({ distance })=>distance <= threshold && distance > 0).sort((a, b)=>a.distance - b.distance);
if (potentialTypos.length) {
return potentialTypos[0].option;
}
return null;
}
//# sourceMappingURL=detect-typo.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/detect-typo.ts"],"sourcesContent":["// the minimum number of operations required to convert string a to string b.\nfunction minDistance(a: string, b: string, threshold: number): number {\n const m = a.length\n const n = b.length\n\n if (m < n) {\n return minDistance(b, a, threshold)\n }\n\n if (n === 0) {\n return m\n }\n\n let previousRow = Array.from({ length: n + 1 }, (_, i) => i)\n\n for (let i = 0; i < m; i++) {\n const s1 = a[i]\n let currentRow = [i + 1]\n for (let j = 0; j < n; j++) {\n const s2 = b[j]\n const insertions = previousRow[j + 1] + 1\n const deletions = currentRow[j] + 1\n const substitutions = previousRow[j] + Number(s1 !== s2)\n currentRow.push(Math.min(insertions, deletions, substitutions))\n }\n previousRow = currentRow\n }\n return previousRow[previousRow.length - 1]\n}\n\nexport function detectTypo(input: string, options: string[], threshold = 2) {\n const potentialTypos = options\n .map((o) => ({\n option: o,\n distance: minDistance(o, input, threshold),\n }))\n .filter(({ distance }) => distance <= threshold && distance > 0)\n .sort((a, b) => a.distance - b.distance)\n\n if (potentialTypos.length) {\n return potentialTypos[0].option\n }\n return null\n}\n"],"names":["minDistance","a","b","threshold","m","length","n","previousRow","Array","from","_","i","s1","currentRow","j","s2","insertions","deletions","substitutions","Number","push","Math","min","detectTypo","input","options","potentialTypos","map","o","option","distance","filter","sort"],"mappings":"AAAA,6EAA6E;AAC7E,SAASA,YAAYC,CAAS,EAAEC,CAAS,EAAEC,SAAiB;IAC1D,MAAMC,IAAIH,EAAEI,MAAM;IAClB,MAAMC,IAAIJ,EAAEG,MAAM;IAElB,IAAID,IAAIE,GAAG;QACT,OAAON,YAAYE,GAAGD,GAAGE;IAC3B;IAEA,IAAIG,MAAM,GAAG;QACX,OAAOF;IACT;IAEA,IAAIG,cAAcC,MAAMC,IAAI,CAAC;QAAEJ,QAAQC,IAAI;IAAE,GAAG,CAACI,GAAGC,IAAMA;IAE1D,IAAK,IAAIA,IAAI,GAAGA,IAAIP,GAAGO,IAAK;QAC1B,MAAMC,KAAKX,CAAC,CAACU,EAAE;QACf,IAAIE,aAAa;YAACF,IAAI;SAAE;QACxB,IAAK,IAAIG,IAAI,GAAGA,IAAIR,GAAGQ,IAAK;YAC1B,MAAMC,KAAKb,CAAC,CAACY,EAAE;YACf,MAAME,aAAaT,WAAW,CAACO,IAAI,EAAE,GAAG;YACxC,MAAMG,YAAYJ,UAAU,CAACC,EAAE,GAAG;YAClC,MAAMI,gBAAgBX,WAAW,CAACO,EAAE,GAAGK,OAAOP,OAAOG;YACrDF,WAAWO,IAAI,CAACC,KAAKC,GAAG,CAACN,YAAYC,WAAWC;QAClD;QACAX,cAAcM;IAChB;IACA,OAAON,WAAW,CAACA,YAAYF,MAAM,GAAG,EAAE;AAC5C;AAEA,OAAO,SAASkB,WAAWC,KAAa,EAAEC,OAAiB,EAAEtB,YAAY,CAAC;IACxE,MAAMuB,iBAAiBD,QACpBE,GAAG,CAAC,CAACC,IAAO,CAAA;YACXC,QAAQD;YACRE,UAAU9B,YAAY4B,GAAGJ,OAAOrB;QAClC,CAAA,GACC4B,MAAM,CAAC,CAAC,EAAED,QAAQ,EAAE,GAAKA,YAAY3B,aAAa2B,WAAW,GAC7DE,IAAI,CAAC,CAAC/B,GAAGC,IAAMD,EAAE6B,QAAQ,GAAG5B,EAAE4B,QAAQ;IAEzC,IAAIJ,eAAerB,MAAM,EAAE;QACzB,OAAOqB,cAAc,CAAC,EAAE,CAACG,MAAM;IACjC;IACA,OAAO;AACT","ignoreList":[0]}

View File

@@ -0,0 +1,115 @@
import fs from 'fs';
import path from 'path';
import * as Log from '../build/output/log';
import tar from 'next/dist/compiled/tar';
const { WritableStream } = require('node:stream/web');
import { getRegistry } from './helpers/get-registry';
import { getCacheDirectory } from './helpers/get-cache-directory';
const MAX_VERSIONS_TO_CACHE = 8;
async function extractBinary(outputDirectory, pkgName, tarFileName) {
const cacheDirectory = getCacheDirectory('next-swc', process.env['NEXT_SWC_PATH']);
const extractFromTar = ()=>tar.x({
file: path.join(cacheDirectory, tarFileName),
cwd: outputDirectory,
strip: 1
});
if (!fs.existsSync(path.join(cacheDirectory, tarFileName))) {
Log.info(`Downloading swc package ${pkgName}... to ${cacheDirectory}`);
await fs.promises.mkdir(cacheDirectory, {
recursive: true
});
const tempFile = path.join(cacheDirectory, `${tarFileName}.temp-${Date.now()}`);
const registry = getRegistry();
const downloadUrl = `${registry}${pkgName}/-/${tarFileName}`;
await fetch(downloadUrl).then((res)=>{
const { ok, body } = res;
if (!ok || !body) {
Log.error(`Failed to download swc package from ${downloadUrl}`);
}
if (!ok) {
throw Object.defineProperty(new Error(`request failed with status ${res.status}`), "__NEXT_ERROR_CODE", {
value: "E109",
enumerable: false,
configurable: true
});
}
if (!body) {
throw Object.defineProperty(new Error('request failed with empty body'), "__NEXT_ERROR_CODE", {
value: "E143",
enumerable: false,
configurable: true
});
}
const cacheWriteStream = fs.createWriteStream(tempFile);
return body.pipeTo(new WritableStream({
write (chunk) {
return new Promise((resolve, reject)=>cacheWriteStream.write(chunk, (error)=>{
if (error) {
reject(error);
return;
}
resolve();
}));
},
close () {
return new Promise((resolve, reject)=>cacheWriteStream.close((error)=>{
if (error) {
reject(error);
return;
}
resolve();
}));
}
}));
});
await fs.promises.access(tempFile) // ensure the temp file existed
;
await fs.promises.rename(tempFile, path.join(cacheDirectory, tarFileName));
} else {
Log.info(`Using cached swc package ${pkgName}...`);
}
await extractFromTar();
const cacheFiles = await fs.promises.readdir(cacheDirectory);
if (cacheFiles.length > MAX_VERSIONS_TO_CACHE) {
cacheFiles.sort((a, b)=>{
if (a.length < b.length) return -1;
return a.localeCompare(b);
});
// prune oldest versions in cache
for(let i = 0; i++; i < cacheFiles.length - MAX_VERSIONS_TO_CACHE){
await fs.promises.unlink(path.join(cacheDirectory, cacheFiles[i])).catch(()=>{});
}
}
}
export async function downloadNativeNextSwc(version, bindingsDirectory, triplesABI) {
for (const triple of triplesABI){
const pkgName = `@next/swc-${triple}`;
const tarFileName = `${pkgName.substring(6)}-${version}.tgz`;
const outputDirectory = path.join(bindingsDirectory, pkgName);
if (fs.existsSync(outputDirectory)) {
// if the package is already downloaded a different
// failure occurred than not being present
return;
}
await fs.promises.mkdir(outputDirectory, {
recursive: true
});
await extractBinary(outputDirectory, pkgName, tarFileName);
}
}
export async function downloadWasmSwc(version, wasmDirectory, variant = 'nodejs') {
const pkgName = `@next/swc-wasm-${variant}`;
const tarFileName = `${pkgName.substring(6)}-${version}.tgz`;
const outputDirectory = path.join(wasmDirectory, pkgName);
if (fs.existsSync(outputDirectory)) {
// if the package is already downloaded a different
// failure occurred than not being present
return;
}
await fs.promises.mkdir(outputDirectory, {
recursive: true
});
await extractBinary(outputDirectory, pkgName, tarFileName);
}
//# sourceMappingURL=download-swc.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
const ERROR_CODE_DELIMITER = '@';
/**
* Augments the digest field of errors thrown in React Server Components (RSC) with an error code.
* Since RSC errors can only be serialized through the digest field, this provides a way to include
* an additional error code that can be extracted client-side via `extractNextErrorCode`.
*
* The error code is appended to the digest string with a semicolon separator, allowing it to be
* parsed out later while preserving the original digest value.
*/ export const createDigestWithErrorCode = (thrownValue, originalDigest)=>{
if (typeof thrownValue === 'object' && thrownValue !== null && '__NEXT_ERROR_CODE' in thrownValue) {
return `${originalDigest}${ERROR_CODE_DELIMITER}${thrownValue.__NEXT_ERROR_CODE}`;
}
return originalDigest;
};
export const extractNextErrorCode = (error)=>{
if (typeof error === 'object' && error !== null && '__NEXT_ERROR_CODE' in error && typeof error.__NEXT_ERROR_CODE === 'string') {
return error.__NEXT_ERROR_CODE;
}
if (typeof error === 'object' && error !== null && 'digest' in error && typeof error.digest === 'string') {
const segments = error.digest.split(ERROR_CODE_DELIMITER);
const errorCode = segments.find((segment)=>segment.startsWith('E'));
return errorCode;
}
return undefined;
};
//# sourceMappingURL=error-telemetry-utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/error-telemetry-utils.ts"],"sourcesContent":["const ERROR_CODE_DELIMITER = '@'\n\n/**\n * Augments the digest field of errors thrown in React Server Components (RSC) with an error code.\n * Since RSC errors can only be serialized through the digest field, this provides a way to include\n * an additional error code that can be extracted client-side via `extractNextErrorCode`.\n *\n * The error code is appended to the digest string with a semicolon separator, allowing it to be\n * parsed out later while preserving the original digest value.\n */\nexport const createDigestWithErrorCode = (\n thrownValue: unknown,\n originalDigest: string\n): string => {\n if (\n typeof thrownValue === 'object' &&\n thrownValue !== null &&\n '__NEXT_ERROR_CODE' in thrownValue\n ) {\n return `${originalDigest}${ERROR_CODE_DELIMITER}${thrownValue.__NEXT_ERROR_CODE}`\n }\n return originalDigest\n}\n\nexport const extractNextErrorCode = (error: unknown): string | undefined => {\n if (\n typeof error === 'object' &&\n error !== null &&\n '__NEXT_ERROR_CODE' in error &&\n typeof error.__NEXT_ERROR_CODE === 'string'\n ) {\n return error.__NEXT_ERROR_CODE\n }\n\n if (\n typeof error === 'object' &&\n error !== null &&\n 'digest' in error &&\n typeof error.digest === 'string'\n ) {\n const segments = error.digest.split(ERROR_CODE_DELIMITER)\n const errorCode = segments.find((segment) => segment.startsWith('E'))\n return errorCode\n }\n\n return undefined\n}\n"],"names":["ERROR_CODE_DELIMITER","createDigestWithErrorCode","thrownValue","originalDigest","__NEXT_ERROR_CODE","extractNextErrorCode","error","digest","segments","split","errorCode","find","segment","startsWith","undefined"],"mappings":"AAAA,MAAMA,uBAAuB;AAE7B;;;;;;;CAOC,GACD,OAAO,MAAMC,4BAA4B,CACvCC,aACAC;IAEA,IACE,OAAOD,gBAAgB,YACvBA,gBAAgB,QAChB,uBAAuBA,aACvB;QACA,OAAO,GAAGC,iBAAiBH,uBAAuBE,YAAYE,iBAAiB,EAAE;IACnF;IACA,OAAOD;AACT,EAAC;AAED,OAAO,MAAME,uBAAuB,CAACC;IACnC,IACE,OAAOA,UAAU,YACjBA,UAAU,QACV,uBAAuBA,SACvB,OAAOA,MAAMF,iBAAiB,KAAK,UACnC;QACA,OAAOE,MAAMF,iBAAiB;IAChC;IAEA,IACE,OAAOE,UAAU,YACjBA,UAAU,QACV,YAAYA,SACZ,OAAOA,MAAMC,MAAM,KAAK,UACxB;QACA,MAAMC,WAAWF,MAAMC,MAAM,CAACE,KAAK,CAACT;QACpC,MAAMU,YAAYF,SAASG,IAAI,CAAC,CAACC,UAAYA,QAAQC,UAAU,CAAC;QAChE,OAAOH;IACT;IAEA,OAAOI;AACT,EAAC","ignoreList":[0]}

View File

@@ -0,0 +1,80 @@
/**
* Describes the different fallback modes that a given page can have.
*/ export var FallbackMode = /*#__PURE__*/ function(FallbackMode) {
/**
* A BLOCKING_STATIC_RENDER fallback will block the request until the page is
* generated. No fallback page will be rendered, and users will have to wait
* to render the page.
*/ FallbackMode["BLOCKING_STATIC_RENDER"] = "BLOCKING_STATIC_RENDER";
/**
* When set to PRERENDER, a fallback page will be sent to users in place of
* forcing them to wait for the page to be generated. This allows the user to
* see a rendered page earlier.
*/ FallbackMode["PRERENDER"] = "PRERENDER";
/**
* When set to NOT_FOUND, pages that are not already prerendered will result
* in a not found response.
*/ FallbackMode["NOT_FOUND"] = "NOT_FOUND";
return FallbackMode;
}({});
/**
* Parses the fallback field from the prerender manifest.
*
* @param fallbackField The fallback field from the prerender manifest.
* @returns The fallback mode.
*/ export function parseFallbackField(fallbackField) {
if (typeof fallbackField === 'string') {
return "PRERENDER";
} else if (fallbackField === null) {
return "BLOCKING_STATIC_RENDER";
} else if (fallbackField === false) {
return "NOT_FOUND";
} else if (fallbackField === undefined) {
return undefined;
} else {
throw Object.defineProperty(new Error(`Invalid fallback option: ${fallbackField}. Fallback option must be a string, null, undefined, or false.`), "__NEXT_ERROR_CODE", {
value: "E285",
enumerable: false,
configurable: true
});
}
}
export function fallbackModeToFallbackField(fallback, page) {
switch(fallback){
case "BLOCKING_STATIC_RENDER":
return null;
case "NOT_FOUND":
return false;
case "PRERENDER":
if (!page) {
throw Object.defineProperty(new Error(`Invariant: expected a page to be provided when fallback mode is "${fallback}"`), "__NEXT_ERROR_CODE", {
value: "E422",
enumerable: false,
configurable: true
});
}
return page;
default:
throw Object.defineProperty(new Error(`Invalid fallback mode: ${fallback}`), "__NEXT_ERROR_CODE", {
value: "E254",
enumerable: false,
configurable: true
});
}
}
/**
* Parses the fallback from the static paths result.
*
* @param result The result from the static paths function.
* @returns The fallback mode.
*/ export function parseStaticPathsResult(result) {
if (result === true) {
return "PRERENDER";
} else if (result === 'blocking') {
return "BLOCKING_STATIC_RENDER";
} else {
return "NOT_FOUND";
}
}
//# sourceMappingURL=fallback.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/fallback.ts"],"sourcesContent":["/**\n * Describes the different fallback modes that a given page can have.\n */\nexport const enum FallbackMode {\n /**\n * A BLOCKING_STATIC_RENDER fallback will block the request until the page is\n * generated. No fallback page will be rendered, and users will have to wait\n * to render the page.\n */\n BLOCKING_STATIC_RENDER = 'BLOCKING_STATIC_RENDER',\n\n /**\n * When set to PRERENDER, a fallback page will be sent to users in place of\n * forcing them to wait for the page to be generated. This allows the user to\n * see a rendered page earlier.\n */\n PRERENDER = 'PRERENDER',\n\n /**\n * When set to NOT_FOUND, pages that are not already prerendered will result\n * in a not found response.\n */\n NOT_FOUND = 'NOT_FOUND',\n}\n\n/**\n * The fallback value returned from the `getStaticPaths` function.\n */\nexport type GetStaticPathsFallback = boolean | 'blocking'\n\n/**\n * Parses the fallback field from the prerender manifest.\n *\n * @param fallbackField The fallback field from the prerender manifest.\n * @returns The fallback mode.\n */\nexport function parseFallbackField(\n fallbackField: string | boolean | null | undefined\n): FallbackMode | undefined {\n if (typeof fallbackField === 'string') {\n return FallbackMode.PRERENDER\n } else if (fallbackField === null) {\n return FallbackMode.BLOCKING_STATIC_RENDER\n } else if (fallbackField === false) {\n return FallbackMode.NOT_FOUND\n } else if (fallbackField === undefined) {\n return undefined\n } else {\n throw new Error(\n `Invalid fallback option: ${fallbackField}. Fallback option must be a string, null, undefined, or false.`\n )\n }\n}\n\nexport function fallbackModeToFallbackField(\n fallback: FallbackMode,\n page: string | undefined\n): string | false | null {\n switch (fallback) {\n case FallbackMode.BLOCKING_STATIC_RENDER:\n return null\n case FallbackMode.NOT_FOUND:\n return false\n case FallbackMode.PRERENDER:\n if (!page) {\n throw new Error(\n `Invariant: expected a page to be provided when fallback mode is \"${fallback}\"`\n )\n }\n\n return page\n default:\n throw new Error(`Invalid fallback mode: ${fallback}`)\n }\n}\n\n/**\n * Parses the fallback from the static paths result.\n *\n * @param result The result from the static paths function.\n * @returns The fallback mode.\n */\nexport function parseStaticPathsResult(\n result: GetStaticPathsFallback\n): FallbackMode {\n if (result === true) {\n return FallbackMode.PRERENDER\n } else if (result === 'blocking') {\n return FallbackMode.BLOCKING_STATIC_RENDER\n } else {\n return FallbackMode.NOT_FOUND\n }\n}\n"],"names":["FallbackMode","parseFallbackField","fallbackField","undefined","Error","fallbackModeToFallbackField","fallback","page","parseStaticPathsResult","result"],"mappings":"AAAA;;CAEC,GACD,OAAO,IAAA,AAAWA,sCAAAA;IAChB;;;;GAIC;IAGD;;;;GAIC;IAGD;;;GAGC;WAlBeA;MAoBjB;AAOD;;;;;CAKC,GACD,OAAO,SAASC,mBACdC,aAAkD;IAElD,IAAI,OAAOA,kBAAkB,UAAU;QACrC;IACF,OAAO,IAAIA,kBAAkB,MAAM;QACjC;IACF,OAAO,IAAIA,kBAAkB,OAAO;QAClC;IACF,OAAO,IAAIA,kBAAkBC,WAAW;QACtC,OAAOA;IACT,OAAO;QACL,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,yBAAyB,EAAEF,cAAc,8DAA8D,CAAC,GADrG,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;AACF;AAEA,OAAO,SAASG,4BACdC,QAAsB,EACtBC,IAAwB;IAExB,OAAQD;QACN;YACE,OAAO;QACT;YACE,OAAO;QACT;YACE,IAAI,CAACC,MAAM;gBACT,MAAM,qBAEL,CAFK,IAAIH,MACR,CAAC,iEAAiE,EAAEE,SAAS,CAAC,CAAC,GAD3E,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF;YAEA,OAAOC;QACT;YACE,MAAM,qBAA+C,CAA/C,IAAIH,MAAM,CAAC,uBAAuB,EAAEE,UAAU,GAA9C,qBAAA;uBAAA;4BAAA;8BAAA;YAA8C;IACxD;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASE,uBACdC,MAA8B;IAE9B,IAAIA,WAAW,MAAM;QACnB;IACF,OAAO,IAAIA,WAAW,YAAY;QAChC;IACF,OAAO;QACL;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,4 @@
export class FatalError extends Error {
}
//# sourceMappingURL=fatal-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/fatal-error.ts"],"sourcesContent":["export class FatalError extends Error {}\n"],"names":["FatalError","Error"],"mappings":"AAAA,OAAO,MAAMA,mBAAmBC;AAAO","ignoreList":[0]}

View File

@@ -0,0 +1,26 @@
import { existsSync, promises } from 'fs';
import isError from './is-error';
export var FileType = /*#__PURE__*/ function(FileType) {
FileType["File"] = "file";
FileType["Directory"] = "directory";
return FileType;
}({});
export async function fileExists(fileName, type) {
try {
if (type === "file") {
const stats = await promises.stat(fileName);
return stats.isFile();
} else if (type === "directory") {
const stats = await promises.stat(fileName);
return stats.isDirectory();
}
return existsSync(fileName);
} catch (err) {
if (isError(err) && (err.code === 'ENOENT' || err.code === 'ENAMETOOLONG')) {
return false;
}
throw err;
}
}
//# sourceMappingURL=file-exists.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/file-exists.ts"],"sourcesContent":["import { existsSync, promises } from 'fs'\nimport isError from './is-error'\n\nexport enum FileType {\n File = 'file',\n Directory = 'directory',\n}\n\nexport async function fileExists(\n fileName: string,\n type?: FileType\n): Promise<boolean> {\n try {\n if (type === FileType.File) {\n const stats = await promises.stat(fileName)\n return stats.isFile()\n } else if (type === FileType.Directory) {\n const stats = await promises.stat(fileName)\n return stats.isDirectory()\n }\n\n return existsSync(fileName)\n } catch (err) {\n if (\n isError(err) &&\n (err.code === 'ENOENT' || err.code === 'ENAMETOOLONG')\n ) {\n return false\n }\n throw err\n }\n}\n"],"names":["existsSync","promises","isError","FileType","fileExists","fileName","type","stats","stat","isFile","isDirectory","err","code"],"mappings":"AAAA,SAASA,UAAU,EAAEC,QAAQ,QAAQ,KAAI;AACzC,OAAOC,aAAa,aAAY;AAEhC,OAAO,IAAA,AAAKC,kCAAAA;;;WAAAA;MAGX;AAED,OAAO,eAAeC,WACpBC,QAAgB,EAChBC,IAAe;IAEf,IAAI;QACF,IAAIA,iBAAwB;YAC1B,MAAMC,QAAQ,MAAMN,SAASO,IAAI,CAACH;YAClC,OAAOE,MAAME,MAAM;QACrB,OAAO,IAAIH,sBAA6B;YACtC,MAAMC,QAAQ,MAAMN,SAASO,IAAI,CAACH;YAClC,OAAOE,MAAMG,WAAW;QAC1B;QAEA,OAAOV,WAAWK;IACpB,EAAE,OAAOM,KAAK;QACZ,IACET,QAAQS,QACPA,CAAAA,IAAIC,IAAI,KAAK,YAAYD,IAAIC,IAAI,KAAK,cAAa,GACpD;YACA,OAAO;QACT;QACA,MAAMD;IACR;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,78 @@
import findUp from 'next/dist/compiled/find-up';
import { readFile } from 'fs/promises';
import JSON5 from 'next/dist/compiled/json5';
import { pathToFileURL } from 'url';
export function findConfigPath(dir, key) {
// If we didn't find the configuration in `package.json`, we should look for
// known filenames.
return findUp([
`.${key}rc.json`,
`${key}.config.json`,
`.${key}rc.js`,
`${key}.config.js`,
`${key}.config.mjs`,
`${key}.config.cjs`
], {
cwd: dir
});
}
// We'll allow configuration to be typed, but we force everything provided to
// become optional. We do not perform any schema validation. We should maybe
// force all the types to be `unknown` as well.
export async function findConfig(directory, key, _returnFile) {
// `package.json` configuration always wins. Let's check that first.
const packageJsonPath = await findUp('package.json', {
cwd: directory
});
let isESM = false;
if (packageJsonPath) {
try {
const packageJsonStr = await readFile(packageJsonPath, 'utf8');
const packageJson = JSON.parse(packageJsonStr);
if (typeof packageJson !== 'object') {
throw new Error() // Stop processing and continue
;
}
if (packageJson.type === 'module') {
isESM = true;
}
if (packageJson[key] != null && typeof packageJson[key] === 'object') {
return packageJson[key];
}
} catch {
// Ignore error and continue
}
}
const filePath = await findConfigPath(directory, key);
const esmImport = (path)=>{
// Skip mapping to absolute url with pathToFileURL on windows if it's jest
// https://github.com/nodejs/node/issues/31710#issuecomment-587345749
if (process.platform === 'win32' && !process.env.JEST_WORKER_ID) {
// on windows import("C:\\path\\to\\file") is not valid, so we need to
// use file:// URLs
return import(pathToFileURL(path).toString());
} else {
return import(path);
}
};
if (filePath) {
if (filePath.endsWith('.js')) {
if (isESM) {
return (await esmImport(filePath)).default;
} else {
return require(filePath);
}
} else if (filePath.endsWith('.mjs')) {
return (await esmImport(filePath)).default;
} else if (filePath.endsWith('.cjs')) {
return require(filePath);
}
// We load JSON contents with JSON5 to allow users to comment in their
// configuration file. This pattern was popularized by TypeScript.
const fileContents = await readFile(filePath, 'utf8');
return JSON5.parse(fileContents);
}
return null;
}
//# sourceMappingURL=find-config.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,38 @@
import fs from 'fs';
import path from 'path';
export function findDir(dir, name) {
// prioritize ./${name} over ./src/${name}
let curDir = path.join(dir, name);
if (fs.existsSync(curDir)) return curDir;
curDir = path.join(dir, 'src', name);
if (fs.existsSync(curDir)) return curDir;
return null;
}
export function findPagesDir(dir) {
const pagesDir = findDir(dir, 'pages') || undefined;
const appDir = findDir(dir, 'app') || undefined;
if (appDir == null && pagesDir == null) {
throw Object.defineProperty(new Error("> Couldn't find any `pages` or `app` directory. Please create one under the project root"), "__NEXT_ERROR_CODE", {
value: "E144",
enumerable: false,
configurable: true
});
}
if (pagesDir && appDir) {
const pagesParent = path.dirname(pagesDir);
const appParent = path.dirname(appDir);
if (pagesParent !== appParent) {
throw Object.defineProperty(new Error('> `pages` and `app` directories should be under the same folder'), "__NEXT_ERROR_CODE", {
value: "E801",
enumerable: false,
configurable: true
});
}
}
return {
pagesDir,
appDir
};
}
//# sourceMappingURL=find-pages-dir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/find-pages-dir.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\n\nexport function findDir(dir: string, name: 'pages' | 'app'): string | null {\n // prioritize ./${name} over ./src/${name}\n let curDir = path.join(dir, name)\n if (fs.existsSync(curDir)) return curDir\n\n curDir = path.join(dir, 'src', name)\n if (fs.existsSync(curDir)) return curDir\n\n return null\n}\n\nexport function findPagesDir(dir: string): {\n pagesDir: string | undefined\n appDir: string | undefined\n} {\n const pagesDir = findDir(dir, 'pages') || undefined\n const appDir = findDir(dir, 'app') || undefined\n\n if (appDir == null && pagesDir == null) {\n throw new Error(\n \"> Couldn't find any `pages` or `app` directory. Please create one under the project root\"\n )\n }\n\n if (pagesDir && appDir) {\n const pagesParent = path.dirname(pagesDir)\n const appParent = path.dirname(appDir)\n if (pagesParent !== appParent) {\n throw new Error(\n '> `pages` and `app` directories should be under the same folder'\n )\n }\n }\n\n return {\n pagesDir,\n appDir,\n }\n}\n"],"names":["fs","path","findDir","dir","name","curDir","join","existsSync","findPagesDir","pagesDir","undefined","appDir","Error","pagesParent","dirname","appParent"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AAEvB,OAAO,SAASC,QAAQC,GAAW,EAAEC,IAAqB;IACxD,0CAA0C;IAC1C,IAAIC,SAASJ,KAAKK,IAAI,CAACH,KAAKC;IAC5B,IAAIJ,GAAGO,UAAU,CAACF,SAAS,OAAOA;IAElCA,SAASJ,KAAKK,IAAI,CAACH,KAAK,OAAOC;IAC/B,IAAIJ,GAAGO,UAAU,CAACF,SAAS,OAAOA;IAElC,OAAO;AACT;AAEA,OAAO,SAASG,aAAaL,GAAW;IAItC,MAAMM,WAAWP,QAAQC,KAAK,YAAYO;IAC1C,MAAMC,SAAST,QAAQC,KAAK,UAAUO;IAEtC,IAAIC,UAAU,QAAQF,YAAY,MAAM;QACtC,MAAM,qBAEL,CAFK,IAAIG,MACR,6FADI,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,IAAIH,YAAYE,QAAQ;QACtB,MAAME,cAAcZ,KAAKa,OAAO,CAACL;QACjC,MAAMM,YAAYd,KAAKa,OAAO,CAACH;QAC/B,IAAIE,gBAAgBE,WAAW;YAC7B,MAAM,qBAEL,CAFK,IAAIH,MACR,oEADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;IACF;IAEA,OAAO;QACLH;QACAE;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,50 @@
import { dirname } from 'path';
import findUp from 'next/dist/compiled/find-up';
import * as Log from '../build/output/log';
export function findRootLockFile(cwd) {
return findUp.sync([
'pnpm-lock.yaml',
'package-lock.json',
'yarn.lock',
'bun.lock',
'bun.lockb'
], {
cwd
});
}
export function findRootDirAndLockFiles(cwd) {
const lockFile = findRootLockFile(cwd);
if (!lockFile) return {
lockFiles: [],
rootDir: cwd
};
const lockFiles = [
lockFile
];
while(true){
const lastLockFile = lockFiles[lockFiles.length - 1];
const currentDir = dirname(lastLockFile);
const parentDir = dirname(currentDir);
// dirname('/')==='/' so if we happen to reach the FS root (as might happen in a container we need to quit to avoid looping forever
if (parentDir === currentDir) break;
const newLockFile = findRootLockFile(parentDir);
if (!newLockFile) break;
lockFiles.push(newLockFile);
}
return {
lockFiles,
rootDir: dirname(lockFiles[lockFiles.length - 1])
};
}
export function warnDuplicatedLockFiles(lockFiles) {
if (lockFiles.length > 1) {
const additionalLockFiles = lockFiles.slice(0, -1).map((str)=>`\n * ${str}`).join('');
if (process.env.TURBOPACK) {
Log.warnOnce(`Warning: Next.js inferred your workspace root, but it may not be correct.\n` + ` We detected multiple lockfiles and selected the directory of ${lockFiles[lockFiles.length - 1]} as the root directory.\n` + ` To silence this warning, set \`turbopack.root\` in your Next.js config, or consider ` + `removing one of the lockfiles if it's not needed.\n` + ` See https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#root-directory for more information.\n` + ` Detected additional lockfiles: ${additionalLockFiles}\n`);
} else {
Log.warnOnce(`Warning: Next.js inferred your workspace root, but it may not be correct.\n` + ` We detected multiple lockfiles and selected the directory of ${lockFiles[lockFiles.length - 1]} as the root directory.\n` + ` To silence this warning, set \`outputFileTracingRoot\` in your Next.js config, or consider ` + `removing one of the lockfiles if it's not needed.\n` + ` See https://nextjs.org/docs/app/api-reference/config/next-config-js/output#caveats for more information.\n` + ` Detected additional lockfiles: ${additionalLockFiles}\n`);
}
}
}
//# sourceMappingURL=find-root.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/find-root.ts"],"sourcesContent":["import { dirname } from 'path'\nimport findUp from 'next/dist/compiled/find-up'\nimport * as Log from '../build/output/log'\n\nexport function findRootLockFile(cwd: string) {\n return findUp.sync(\n [\n 'pnpm-lock.yaml',\n 'package-lock.json',\n 'yarn.lock',\n 'bun.lock',\n 'bun.lockb',\n ],\n {\n cwd,\n }\n )\n}\n\nexport function findRootDirAndLockFiles(cwd: string): {\n lockFiles: string[]\n rootDir: string\n} {\n const lockFile = findRootLockFile(cwd)\n if (!lockFile)\n return {\n lockFiles: [],\n rootDir: cwd,\n }\n\n const lockFiles = [lockFile]\n while (true) {\n const lastLockFile = lockFiles[lockFiles.length - 1]\n const currentDir = dirname(lastLockFile)\n const parentDir = dirname(currentDir)\n\n // dirname('/')==='/' so if we happen to reach the FS root (as might happen in a container we need to quit to avoid looping forever\n if (parentDir === currentDir) break\n\n const newLockFile = findRootLockFile(parentDir)\n\n if (!newLockFile) break\n\n lockFiles.push(newLockFile)\n }\n\n return {\n lockFiles,\n rootDir: dirname(lockFiles[lockFiles.length - 1]),\n }\n}\n\nexport function warnDuplicatedLockFiles(lockFiles: string[]) {\n if (lockFiles.length > 1) {\n const additionalLockFiles = lockFiles\n .slice(0, -1)\n .map((str) => `\\n * ${str}`)\n .join('')\n\n if (process.env.TURBOPACK) {\n Log.warnOnce(\n `Warning: Next.js inferred your workspace root, but it may not be correct.\\n` +\n ` We detected multiple lockfiles and selected the directory of ${lockFiles[lockFiles.length - 1]} as the root directory.\\n` +\n ` To silence this warning, set \\`turbopack.root\\` in your Next.js config, or consider ` +\n `removing one of the lockfiles if it's not needed.\\n` +\n ` See https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopack#root-directory for more information.\\n` +\n ` Detected additional lockfiles: ${additionalLockFiles}\\n`\n )\n } else {\n Log.warnOnce(\n `Warning: Next.js inferred your workspace root, but it may not be correct.\\n` +\n ` We detected multiple lockfiles and selected the directory of ${lockFiles[lockFiles.length - 1]} as the root directory.\\n` +\n ` To silence this warning, set \\`outputFileTracingRoot\\` in your Next.js config, or consider ` +\n `removing one of the lockfiles if it's not needed.\\n` +\n ` See https://nextjs.org/docs/app/api-reference/config/next-config-js/output#caveats for more information.\\n` +\n ` Detected additional lockfiles: ${additionalLockFiles}\\n`\n )\n }\n }\n}\n"],"names":["dirname","findUp","Log","findRootLockFile","cwd","sync","findRootDirAndLockFiles","lockFile","lockFiles","rootDir","lastLockFile","length","currentDir","parentDir","newLockFile","push","warnDuplicatedLockFiles","additionalLockFiles","slice","map","str","join","process","env","TURBOPACK","warnOnce"],"mappings":"AAAA,SAASA,OAAO,QAAQ,OAAM;AAC9B,OAAOC,YAAY,6BAA4B;AAC/C,YAAYC,SAAS,sBAAqB;AAE1C,OAAO,SAASC,iBAAiBC,GAAW;IAC1C,OAAOH,OAAOI,IAAI,CAChB;QACE;QACA;QACA;QACA;QACA;KACD,EACD;QACED;IACF;AAEJ;AAEA,OAAO,SAASE,wBAAwBF,GAAW;IAIjD,MAAMG,WAAWJ,iBAAiBC;IAClC,IAAI,CAACG,UACH,OAAO;QACLC,WAAW,EAAE;QACbC,SAASL;IACX;IAEF,MAAMI,YAAY;QAACD;KAAS;IAC5B,MAAO,KAAM;QACX,MAAMG,eAAeF,SAAS,CAACA,UAAUG,MAAM,GAAG,EAAE;QACpD,MAAMC,aAAaZ,QAAQU;QAC3B,MAAMG,YAAYb,QAAQY;QAE1B,mIAAmI;QACnI,IAAIC,cAAcD,YAAY;QAE9B,MAAME,cAAcX,iBAAiBU;QAErC,IAAI,CAACC,aAAa;QAElBN,UAAUO,IAAI,CAACD;IACjB;IAEA,OAAO;QACLN;QACAC,SAAST,QAAQQ,SAAS,CAACA,UAAUG,MAAM,GAAG,EAAE;IAClD;AACF;AAEA,OAAO,SAASK,wBAAwBR,SAAmB;IACzD,IAAIA,UAAUG,MAAM,GAAG,GAAG;QACxB,MAAMM,sBAAsBT,UACzBU,KAAK,CAAC,GAAG,CAAC,GACVC,GAAG,CAAC,CAACC,MAAQ,CAAC,OAAO,EAAEA,KAAK,EAC5BC,IAAI,CAAC;QAER,IAAIC,QAAQC,GAAG,CAACC,SAAS,EAAE;YACzBtB,IAAIuB,QAAQ,CACV,CAAC,2EAA2E,CAAC,GAC3E,CAAC,8DAA8D,EAAEjB,SAAS,CAACA,UAAUG,MAAM,GAAG,EAAE,CAAC,yBAAyB,CAAC,GAC3H,CAAC,qFAAqF,CAAC,GACvF,CAAC,mDAAmD,CAAC,GACrD,CAAC,uHAAuH,CAAC,GACzH,CAAC,gCAAgC,EAAEM,oBAAoB,EAAE,CAAC;QAEhE,OAAO;YACLf,IAAIuB,QAAQ,CACV,CAAC,2EAA2E,CAAC,GAC3E,CAAC,8DAA8D,EAAEjB,SAAS,CAACA,UAAUG,MAAM,GAAG,EAAE,CAAC,yBAAyB,CAAC,GAC3H,CAAC,4FAA4F,CAAC,GAC9F,CAAC,mDAAmD,CAAC,GACrD,CAAC,6GAA6G,CAAC,GAC/G,CAAC,gCAAgC,EAAEM,oBAAoB,EAAE,CAAC;QAEhE;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,75 @@
import { bold } from '../lib/picocolors';
// Copy-pasted from Commander's Help class -> formatHelp().
// TL;DR, we're overriding the built-in help to add a few niceties.
// Link: https://github.com/tj/commander.js/blob/master/lib/help.js
const formatCliHelpOutput = (cmd, helper)=>{
const termWidth = helper.padWidth(cmd, helper);
const helpWidth = helper.helpWidth || 80;
const itemIndentWidth = 2;
const itemSeparatorWidth = 2 // between term and description
;
function formatItem(term, description) {
let value = term;
if (description) {
if (term === 'directory') {
value = `[${term}]`;
}
const fullText = `${value.padEnd(termWidth + itemSeparatorWidth)}${description}`;
return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
}
return term;
}
function formatList(textArray) {
return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
}
// Usage
let output = [
`${bold('Usage:')} ${helper.commandUsage(cmd)}`,
''
];
// Description
const commandDescription = helper.commandDescription(cmd);
if (commandDescription.length > 0) {
output = output.concat([
helper.wrap(commandDescription, helpWidth, 0),
''
]);
}
// Arguments
const argumentList = helper.visibleArguments(cmd).map((argument)=>{
return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
});
if (argumentList.length > 0) {
output = output.concat([
`${bold('Arguments:')}`,
formatList(argumentList),
''
]);
}
// Options
const optionList = helper.visibleOptions(cmd).map((option)=>{
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
});
if (optionList.length > 0) {
output = output.concat([
`${bold('Options:')}`,
formatList(optionList),
''
]);
}
// Commands
const commandList = helper.visibleCommands(cmd).map((subCmd)=>{
return formatItem(helper.subcommandTerm(subCmd), helper.subcommandDescription(subCmd));
});
if (commandList.length > 0) {
output = output.concat([
`${bold('Commands:')}`,
formatList(commandList),
''
]);
}
return output.join('\n');
};
export { formatCliHelpOutput };
//# sourceMappingURL=format-cli-help-output.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/format-cli-help-output.ts"],"sourcesContent":["import type { Command, Help } from 'next/dist/compiled/commander'\nimport { bold } from '../lib/picocolors'\n\n// Copy-pasted from Commander's Help class -> formatHelp().\n// TL;DR, we're overriding the built-in help to add a few niceties.\n// Link: https://github.com/tj/commander.js/blob/master/lib/help.js\nconst formatCliHelpOutput = (cmd: Command, helper: Help) => {\n const termWidth = helper.padWidth(cmd, helper)\n const helpWidth = helper.helpWidth || 80\n const itemIndentWidth = 2\n const itemSeparatorWidth = 2 // between term and description\n\n function formatItem(term: string, description: string) {\n let value = term\n\n if (description) {\n if (term === 'directory') {\n value = `[${term}]`\n }\n\n const fullText = `${value.padEnd(\n termWidth + itemSeparatorWidth\n )}${description}`\n\n return helper.wrap(\n fullText,\n helpWidth - itemIndentWidth,\n termWidth + itemSeparatorWidth\n )\n }\n\n return term\n }\n\n function formatList(textArray: string[]) {\n return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth))\n }\n\n // Usage\n let output = [`${bold('Usage:')} ${helper.commandUsage(cmd)}`, '']\n\n // Description\n const commandDescription = helper.commandDescription(cmd)\n\n if (commandDescription.length > 0) {\n output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ''])\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return formatItem(\n helper.argumentTerm(argument),\n helper.argumentDescription(argument)\n )\n })\n\n if (argumentList.length > 0) {\n output = output.concat([\n `${bold('Arguments:')}`,\n formatList(argumentList),\n '',\n ])\n }\n\n // Options\n const optionList = helper.visibleOptions(cmd).map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option)\n )\n })\n\n if (optionList.length > 0) {\n output = output.concat([`${bold('Options:')}`, formatList(optionList), ''])\n }\n\n // Commands\n const commandList = helper.visibleCommands(cmd).map((subCmd) => {\n return formatItem(\n helper.subcommandTerm(subCmd),\n helper.subcommandDescription(subCmd)\n )\n })\n\n if (commandList.length > 0) {\n output = output.concat([\n `${bold('Commands:')}`,\n formatList(commandList),\n '',\n ])\n }\n\n return output.join('\\n')\n}\n\nexport { formatCliHelpOutput }\n"],"names":["bold","formatCliHelpOutput","cmd","helper","termWidth","padWidth","helpWidth","itemIndentWidth","itemSeparatorWidth","formatItem","term","description","value","fullText","padEnd","wrap","formatList","textArray","join","replace","repeat","output","commandUsage","commandDescription","length","concat","argumentList","visibleArguments","map","argument","argumentTerm","argumentDescription","optionList","visibleOptions","option","optionTerm","optionDescription","commandList","visibleCommands","subCmd","subcommandTerm","subcommandDescription"],"mappings":"AACA,SAASA,IAAI,QAAQ,oBAAmB;AAExC,2DAA2D;AAC3D,mEAAmE;AACnE,mEAAmE;AACnE,MAAMC,sBAAsB,CAACC,KAAcC;IACzC,MAAMC,YAAYD,OAAOE,QAAQ,CAACH,KAAKC;IACvC,MAAMG,YAAYH,OAAOG,SAAS,IAAI;IACtC,MAAMC,kBAAkB;IACxB,MAAMC,qBAAqB,EAAE,+BAA+B;;IAE5D,SAASC,WAAWC,IAAY,EAAEC,WAAmB;QACnD,IAAIC,QAAQF;QAEZ,IAAIC,aAAa;YACf,IAAID,SAAS,aAAa;gBACxBE,QAAQ,CAAC,CAAC,EAAEF,KAAK,CAAC,CAAC;YACrB;YAEA,MAAMG,WAAW,GAAGD,MAAME,MAAM,CAC9BV,YAAYI,sBACVG,aAAa;YAEjB,OAAOR,OAAOY,IAAI,CAChBF,UACAP,YAAYC,iBACZH,YAAYI;QAEhB;QAEA,OAAOE;IACT;IAEA,SAASM,WAAWC,SAAmB;QACrC,OAAOA,UAAUC,IAAI,CAAC,MAAMC,OAAO,CAAC,OAAO,IAAIC,MAAM,CAACb;IACxD;IAEA,QAAQ;IACR,IAAIc,SAAS;QAAC,GAAGrB,KAAK,UAAU,CAAC,EAAEG,OAAOmB,YAAY,CAACpB,MAAM;QAAE;KAAG;IAElE,cAAc;IACd,MAAMqB,qBAAqBpB,OAAOoB,kBAAkB,CAACrB;IAErD,IAAIqB,mBAAmBC,MAAM,GAAG,GAAG;QACjCH,SAASA,OAAOI,MAAM,CAAC;YAACtB,OAAOY,IAAI,CAACQ,oBAAoBjB,WAAW;YAAI;SAAG;IAC5E;IAEA,YAAY;IACZ,MAAMoB,eAAevB,OAAOwB,gBAAgB,CAACzB,KAAK0B,GAAG,CAAC,CAACC;QACrD,OAAOpB,WACLN,OAAO2B,YAAY,CAACD,WACpB1B,OAAO4B,mBAAmB,CAACF;IAE/B;IAEA,IAAIH,aAAaF,MAAM,GAAG,GAAG;QAC3BH,SAASA,OAAOI,MAAM,CAAC;YACrB,GAAGzB,KAAK,eAAe;YACvBgB,WAAWU;YACX;SACD;IACH;IAEA,UAAU;IACV,MAAMM,aAAa7B,OAAO8B,cAAc,CAAC/B,KAAK0B,GAAG,CAAC,CAACM;QACjD,OAAOzB,WACLN,OAAOgC,UAAU,CAACD,SAClB/B,OAAOiC,iBAAiB,CAACF;IAE7B;IAEA,IAAIF,WAAWR,MAAM,GAAG,GAAG;QACzBH,SAASA,OAAOI,MAAM,CAAC;YAAC,GAAGzB,KAAK,aAAa;YAAEgB,WAAWgB;YAAa;SAAG;IAC5E;IAEA,WAAW;IACX,MAAMK,cAAclC,OAAOmC,eAAe,CAACpC,KAAK0B,GAAG,CAAC,CAACW;QACnD,OAAO9B,WACLN,OAAOqC,cAAc,CAACD,SACtBpC,OAAOsC,qBAAqB,CAACF;IAEjC;IAEA,IAAIF,YAAYb,MAAM,GAAG,GAAG;QAC1BH,SAASA,OAAOI,MAAM,CAAC;YACrB,GAAGzB,KAAK,cAAc;YACtBgB,WAAWqB;YACX;SACD;IACH;IAEA,OAAOhB,OAAOH,IAAI,CAAC;AACrB;AAEA,SAASjB,mBAAmB,GAAE","ignoreList":[0]}

View File

@@ -0,0 +1,16 @@
import path from 'path';
import { pathToFileURL } from 'url';
/**
* The path for a dynamic route must be URLs with a valid scheme.
*
* When an absolute Windows path is passed to it, it interprets the beginning of the path as a protocol (`C:`).
* Therefore, it is important to always construct a complete path.
* @param dir File directory
* @param filePath Absolute or relative path
*/ export const formatDynamicImportPath = (dir, filePath)=>{
const absoluteFilePath = path.isAbsolute(filePath) ? filePath : path.join(dir, filePath);
const formattedFilePath = pathToFileURL(absoluteFilePath).toString();
return formattedFilePath;
};
//# sourceMappingURL=format-dynamic-import-path.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/format-dynamic-import-path.ts"],"sourcesContent":["import path from 'path'\nimport { pathToFileURL } from 'url'\n\n/**\n * The path for a dynamic route must be URLs with a valid scheme.\n *\n * When an absolute Windows path is passed to it, it interprets the beginning of the path as a protocol (`C:`).\n * Therefore, it is important to always construct a complete path.\n * @param dir File directory\n * @param filePath Absolute or relative path\n */\nexport const formatDynamicImportPath = (dir: string, filePath: string) => {\n const absoluteFilePath = path.isAbsolute(filePath)\n ? filePath\n : path.join(dir, filePath)\n const formattedFilePath = pathToFileURL(absoluteFilePath).toString()\n\n return formattedFilePath\n}\n"],"names":["path","pathToFileURL","formatDynamicImportPath","dir","filePath","absoluteFilePath","isAbsolute","join","formattedFilePath","toString"],"mappings":"AAAA,OAAOA,UAAU,OAAM;AACvB,SAASC,aAAa,QAAQ,MAAK;AAEnC;;;;;;;CAOC,GACD,OAAO,MAAMC,0BAA0B,CAACC,KAAaC;IACnD,MAAMC,mBAAmBL,KAAKM,UAAU,CAACF,YACrCA,WACAJ,KAAKO,IAAI,CAACJ,KAAKC;IACnB,MAAMI,oBAAoBP,cAAcI,kBAAkBI,QAAQ;IAElE,OAAOD;AACT,EAAC","ignoreList":[0]}

View File

@@ -0,0 +1,61 @@
const invalidServerComponentReactHooks = [
'useDeferredValue',
'useEffect',
'useImperativeHandle',
'useInsertionEffect',
'useLayoutEffect',
'useReducer',
'useRef',
'useState',
'useSyncExternalStore',
'useTransition',
'experimental_useOptimistic',
'useOptimistic'
];
function setMessage(error, message) {
error.message = message;
if (error.stack) {
const lines = error.stack.split('\n');
lines[0] = message;
error.stack = lines.join('\n');
}
}
/**
* Input:
* Error: Something went wrong
at funcName (/path/to/file.js:10:5)
at anotherFunc (/path/to/file.js:15:10)
* Output:
at funcName (/path/to/file.js:10:5)
at anotherFunc (/path/to/file.js:15:10)
*/ export function getStackWithoutErrorMessage(error) {
const stack = error.stack;
if (!stack) return '';
return stack.replace(/^[^\n]*\n/, '');
}
export function formatServerError(error) {
if (typeof (error == null ? void 0 : error.message) !== 'string') return;
if (error.message.includes('Class extends value undefined is not a constructor or null')) {
const addedMessage = 'This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component';
// If this error instance already has the message, don't add it again
if (error.message.includes(addedMessage)) return;
setMessage(error, `${error.message}
${addedMessage}`);
return;
}
if (error.message.includes('createContext is not a function')) {
setMessage(error, 'createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component');
return;
}
for (const clientHook of invalidServerComponentReactHooks){
const regex = new RegExp(`\\b${clientHook}\\b.*is not a function`);
if (regex.test(error.message)) {
setMessage(error, `${clientHook} only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`);
return;
}
}
}
//# sourceMappingURL=format-server-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/format-server-error.ts"],"sourcesContent":["const invalidServerComponentReactHooks = [\n 'useDeferredValue',\n 'useEffect',\n 'useImperativeHandle',\n 'useInsertionEffect',\n 'useLayoutEffect',\n 'useReducer',\n 'useRef',\n 'useState',\n 'useSyncExternalStore',\n 'useTransition',\n 'experimental_useOptimistic',\n 'useOptimistic',\n]\n\nfunction setMessage(error: Error, message: string): void {\n error.message = message\n if (error.stack) {\n const lines = error.stack.split('\\n')\n lines[0] = message\n error.stack = lines.join('\\n')\n }\n}\n\n/**\n * Input:\n * Error: Something went wrong\n at funcName (/path/to/file.js:10:5)\n at anotherFunc (/path/to/file.js:15:10)\n \n * Output:\n at funcName (/path/to/file.js:10:5)\n at anotherFunc (/path/to/file.js:15:10) \n */\nexport function getStackWithoutErrorMessage(error: Error): string {\n const stack = error.stack\n if (!stack) return ''\n return stack.replace(/^[^\\n]*\\n/, '')\n}\n\nexport function formatServerError(error: Error): void {\n if (typeof error?.message !== 'string') return\n\n if (\n error.message.includes(\n 'Class extends value undefined is not a constructor or null'\n )\n ) {\n const addedMessage =\n 'This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component'\n\n // If this error instance already has the message, don't add it again\n if (error.message.includes(addedMessage)) return\n\n setMessage(\n error,\n `${error.message}\n\n${addedMessage}`\n )\n return\n }\n\n if (error.message.includes('createContext is not a function')) {\n setMessage(\n error,\n 'createContext only works in Client Components. Add the \"use client\" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component'\n )\n return\n }\n\n for (const clientHook of invalidServerComponentReactHooks) {\n const regex = new RegExp(`\\\\b${clientHook}\\\\b.*is not a function`)\n if (regex.test(error.message)) {\n setMessage(\n error,\n `${clientHook} only works in Client Components. Add the \"use client\" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`\n )\n return\n }\n }\n}\n"],"names":["invalidServerComponentReactHooks","setMessage","error","message","stack","lines","split","join","getStackWithoutErrorMessage","replace","formatServerError","includes","addedMessage","clientHook","regex","RegExp","test"],"mappings":"AAAA,MAAMA,mCAAmC;IACvC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,SAASC,WAAWC,KAAY,EAAEC,OAAe;IAC/CD,MAAMC,OAAO,GAAGA;IAChB,IAAID,MAAME,KAAK,EAAE;QACf,MAAMC,QAAQH,MAAME,KAAK,CAACE,KAAK,CAAC;QAChCD,KAAK,CAAC,EAAE,GAAGF;QACXD,MAAME,KAAK,GAAGC,MAAME,IAAI,CAAC;IAC3B;AACF;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,4BAA4BN,KAAY;IACtD,MAAME,QAAQF,MAAME,KAAK;IACzB,IAAI,CAACA,OAAO,OAAO;IACnB,OAAOA,MAAMK,OAAO,CAAC,aAAa;AACpC;AAEA,OAAO,SAASC,kBAAkBR,KAAY;IAC5C,IAAI,QAAOA,yBAAAA,MAAOC,OAAO,MAAK,UAAU;IAExC,IACED,MAAMC,OAAO,CAACQ,QAAQ,CACpB,+DAEF;QACA,MAAMC,eACJ;QAEF,qEAAqE;QACrE,IAAIV,MAAMC,OAAO,CAACQ,QAAQ,CAACC,eAAe;QAE1CX,WACEC,OACA,GAAGA,MAAMC,OAAO,CAAC;;AAEvB,EAAES,cAAc;QAEZ;IACF;IAEA,IAAIV,MAAMC,OAAO,CAACQ,QAAQ,CAAC,oCAAoC;QAC7DV,WACEC,OACA;QAEF;IACF;IAEA,KAAK,MAAMW,cAAcb,iCAAkC;QACzD,MAAMc,QAAQ,IAAIC,OAAO,CAAC,GAAG,EAAEF,WAAW,sBAAsB,CAAC;QACjE,IAAIC,MAAME,IAAI,CAACd,MAAMC,OAAO,GAAG;YAC7BF,WACEC,OACA,GAAGW,WAAW,oLAAoL,CAAC;YAErM;QACF;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,32 @@
'use client';
import { METADATA_BOUNDARY_NAME, VIEWPORT_BOUNDARY_NAME, OUTLET_BOUNDARY_NAME, ROOT_LAYOUT_BOUNDARY_NAME } from './boundary-constants';
// We use a namespace object to allow us to recover the name of the function
// at runtime even when production bundling/minification is used.
const NameSpace = {
[METADATA_BOUNDARY_NAME]: function({ children }) {
return children;
},
[VIEWPORT_BOUNDARY_NAME]: function({ children }) {
return children;
},
[OUTLET_BOUNDARY_NAME]: function({ children }) {
return children;
},
[ROOT_LAYOUT_BOUNDARY_NAME]: function({ children }) {
return children;
}
};
export const MetadataBoundary = // We use slice(0) to trick the bundler into not inlining/minifying the function
// so it retains the name inferred from the namespace object
NameSpace[METADATA_BOUNDARY_NAME.slice(0)];
export const ViewportBoundary = // We use slice(0) to trick the bundler into not inlining/minifying the function
// so it retains the name inferred from the namespace object
NameSpace[VIEWPORT_BOUNDARY_NAME.slice(0)];
export const OutletBoundary = // We use slice(0) to trick the bundler into not inlining/minifying the function
// so it retains the name inferred from the namespace object
NameSpace[OUTLET_BOUNDARY_NAME.slice(0)];
export const RootLayoutBoundary = // We use slice(0) to trick the bundler into not inlining/minifying the function
// so it retains the name inferred from the namespace object
NameSpace[ROOT_LAYOUT_BOUNDARY_NAME.slice(0)];
//# sourceMappingURL=boundary-components.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/framework/boundary-components.tsx"],"sourcesContent":["'use client'\n\nimport type { ReactNode } from 'react'\nimport {\n METADATA_BOUNDARY_NAME,\n VIEWPORT_BOUNDARY_NAME,\n OUTLET_BOUNDARY_NAME,\n ROOT_LAYOUT_BOUNDARY_NAME,\n} from './boundary-constants'\n\n// We use a namespace object to allow us to recover the name of the function\n// at runtime even when production bundling/minification is used.\nconst NameSpace = {\n [METADATA_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [VIEWPORT_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [OUTLET_BOUNDARY_NAME]: function ({ children }: { children: ReactNode }) {\n return children\n },\n [ROOT_LAYOUT_BOUNDARY_NAME]: function ({\n children,\n }: {\n children: ReactNode\n }) {\n return children\n },\n}\n\nexport const MetadataBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[METADATA_BOUNDARY_NAME.slice(0) as typeof METADATA_BOUNDARY_NAME]\n\nexport const ViewportBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[VIEWPORT_BOUNDARY_NAME.slice(0) as typeof VIEWPORT_BOUNDARY_NAME]\n\nexport const OutletBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[OUTLET_BOUNDARY_NAME.slice(0) as typeof OUTLET_BOUNDARY_NAME]\n\nexport const RootLayoutBoundary =\n // We use slice(0) to trick the bundler into not inlining/minifying the function\n // so it retains the name inferred from the namespace object\n NameSpace[\n ROOT_LAYOUT_BOUNDARY_NAME.slice(0) as typeof ROOT_LAYOUT_BOUNDARY_NAME\n ]\n"],"names":["METADATA_BOUNDARY_NAME","VIEWPORT_BOUNDARY_NAME","OUTLET_BOUNDARY_NAME","ROOT_LAYOUT_BOUNDARY_NAME","NameSpace","children","MetadataBoundary","slice","ViewportBoundary","OutletBoundary","RootLayoutBoundary"],"mappings":"AAAA;AAGA,SACEA,sBAAsB,EACtBC,sBAAsB,EACtBC,oBAAoB,EACpBC,yBAAyB,QACpB,uBAAsB;AAE7B,4EAA4E;AAC5E,iEAAiE;AACjE,MAAMC,YAAY;IAChB,CAACJ,uBAAuB,EAAE,SAAU,EAAEK,QAAQ,EAA2B;QACvE,OAAOA;IACT;IACA,CAACJ,uBAAuB,EAAE,SAAU,EAAEI,QAAQ,EAA2B;QACvE,OAAOA;IACT;IACA,CAACH,qBAAqB,EAAE,SAAU,EAAEG,QAAQ,EAA2B;QACrE,OAAOA;IACT;IACA,CAACF,0BAA0B,EAAE,SAAU,EACrCE,QAAQ,EAGT;QACC,OAAOA;IACT;AACF;AAEA,OAAO,MAAMC,mBACX,gFAAgF;AAChF,4DAA4D;AAC5DF,SAAS,CAACJ,uBAAuBO,KAAK,CAAC,GAAoC,CAAA;AAE7E,OAAO,MAAMC,mBACX,gFAAgF;AAChF,4DAA4D;AAC5DJ,SAAS,CAACH,uBAAuBM,KAAK,CAAC,GAAoC,CAAA;AAE7E,OAAO,MAAME,iBACX,gFAAgF;AAChF,4DAA4D;AAC5DL,SAAS,CAACF,qBAAqBK,KAAK,CAAC,GAAkC,CAAA;AAEzE,OAAO,MAAMG,qBACX,gFAAgF;AAChF,4DAA4D;AAC5DN,SAAS,CACPD,0BAA0BI,KAAK,CAAC,GACjC,CAAA","ignoreList":[0]}

View File

@@ -0,0 +1,6 @@
export const METADATA_BOUNDARY_NAME = '__next_metadata_boundary__';
export const VIEWPORT_BOUNDARY_NAME = '__next_viewport_boundary__';
export const OUTLET_BOUNDARY_NAME = '__next_outlet_boundary__';
export const ROOT_LAYOUT_BOUNDARY_NAME = '__next_root_layout_boundary__';
//# sourceMappingURL=boundary-constants.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/framework/boundary-constants.tsx"],"sourcesContent":["export const METADATA_BOUNDARY_NAME = '__next_metadata_boundary__'\nexport const VIEWPORT_BOUNDARY_NAME = '__next_viewport_boundary__'\nexport const OUTLET_BOUNDARY_NAME = '__next_outlet_boundary__'\nexport const ROOT_LAYOUT_BOUNDARY_NAME = '__next_root_layout_boundary__'\n"],"names":["METADATA_BOUNDARY_NAME","VIEWPORT_BOUNDARY_NAME","OUTLET_BOUNDARY_NAME","ROOT_LAYOUT_BOUNDARY_NAME"],"mappings":"AAAA,OAAO,MAAMA,yBAAyB,6BAA4B;AAClE,OAAO,MAAMC,yBAAyB,6BAA4B;AAClE,OAAO,MAAMC,uBAAuB,2BAA0B;AAC9D,OAAO,MAAMC,4BAA4B,gCAA+B","ignoreList":[0]}

View File

@@ -0,0 +1,81 @@
/*
MIT License
Copyright (c) 2015 - present Microsoft Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/ // This file is based on https://github.com/microsoft/vscode/blob/f860fcf11022f10a992440fd54c6e45674e39617/src/vs/base/node/pfs.ts
// See the LICENSE at the top of the file
import { renameSync as fsRenameSync, statSync } from 'node:fs';
/**
* A drop-in replacement for `fs.rename` that:
* - allows to move across multiple disks
* - attempts to retry the operation for certain error codes on Windows
*/ export function renameSync(source, target, windowsRetryTimeout = 60000 /* matches graceful-fs */ ) {
if (source === target) {
return; // simulate node.js behaviour here and do a no-op if paths match
}
if (process.platform === 'win32' && typeof windowsRetryTimeout === 'number') {
// On Windows, a rename can fail when either source or target
// is locked by AV software. We do leverage graceful-fs to iron
// out these issues, however in case the target file exists,
// graceful-fs will immediately return without retry for fs.rename().
renameSyncWithRetry(source, target, Date.now(), windowsRetryTimeout);
} else {
fsRenameSync(source, target);
}
}
function renameSyncWithRetry(source, target, startTime, retryTimeout, attempt = 0) {
try {
return fsRenameSync(source, target);
} catch (error) {
if (error.code !== 'EACCES' && error.code !== 'EPERM' && error.code !== 'EBUSY') {
throw error // only for errors we think are temporary
;
}
if (Date.now() - startTime >= retryTimeout) {
console.error(`Node.js fs rename failed after ${attempt} retries with error: ${error}`);
throw error // give up after configurable timeout
;
}
if (attempt > 100) {
console.error(`Node.js fs rename failed after ${attempt} retries with error ${error}`);
throw error;
}
if (attempt === 0) {
let abortRetry = false;
try {
const statTarget = statSync(target);
if (!statTarget.isFile()) {
abortRetry = true // if target is not a file, EPERM error may be raised and we should not attempt to retry
;
}
} catch (e) {
// Ignore
}
if (abortRetry) {
throw error;
}
}
// Attempt again
return renameSyncWithRetry(source, target, startTime, retryTimeout, attempt + 1);
}
}
//# sourceMappingURL=rename.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
import { unlinkSync, writeFileSync } from 'fs';
import { renameSync } from './rename';
export function writeFileAtomic(filePath, content) {
const tempPath = filePath + '.tmp.' + Math.random().toString(36).slice(2);
try {
writeFileSync(tempPath, content, 'utf-8');
renameSync(tempPath, filePath);
} catch (e) {
try {
unlinkSync(tempPath);
} catch {
// ignore
}
throw e;
}
}
//# sourceMappingURL=write-atomic.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/fs/write-atomic.ts"],"sourcesContent":["import { unlinkSync, writeFileSync } from 'fs'\nimport { renameSync } from './rename'\n\nexport function writeFileAtomic(filePath: string, content: string): void {\n const tempPath = filePath + '.tmp.' + Math.random().toString(36).slice(2)\n try {\n writeFileSync(tempPath, content, 'utf-8')\n renameSync(tempPath, filePath)\n } catch (e) {\n try {\n unlinkSync(tempPath)\n } catch {\n // ignore\n }\n throw e\n }\n}\n"],"names":["unlinkSync","writeFileSync","renameSync","writeFileAtomic","filePath","content","tempPath","Math","random","toString","slice","e"],"mappings":"AAAA,SAASA,UAAU,EAAEC,aAAa,QAAQ,KAAI;AAC9C,SAASC,UAAU,QAAQ,WAAU;AAErC,OAAO,SAASC,gBAAgBC,QAAgB,EAAEC,OAAe;IAC/D,MAAMC,WAAWF,WAAW,UAAUG,KAAKC,MAAM,GAAGC,QAAQ,CAAC,IAAIC,KAAK,CAAC;IACvE,IAAI;QACFT,cAAcK,UAAUD,SAAS;QACjCH,WAAWI,UAAUF;IACvB,EAAE,OAAOO,GAAG;QACV,IAAI;YACFX,WAAWM;QACb,EAAE,OAAM;QACN,SAAS;QACX;QACA,MAAMK;IACR;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,47 @@
import { NEXT_URL } from '../client/components/app-router-headers';
import { extractInterceptionRouteInformation, isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes';
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex';
export function generateInterceptionRoutesRewrites(appPaths, basePath = '') {
const rewrites = [];
for (const appPath of appPaths){
if (isInterceptionRouteAppPath(appPath)) {
const { interceptingRoute, interceptedRoute } = extractInterceptionRouteInformation(appPath);
const destination = getNamedRouteRegex(basePath + appPath, {
prefixRouteKeys: true
});
const header = getNamedRouteRegex(interceptingRoute, {
prefixRouteKeys: true,
reference: destination.reference
});
const source = getNamedRouteRegex(basePath + interceptedRoute, {
prefixRouteKeys: true,
reference: header.reference
});
const headerRegex = header.namedRegex// Strip ^ and $ anchors since matchHas() will add them automatically
.replace(/^\^/, '').replace(/\$$/, '')// Replace matching the `/` with matching any route segment.
.replace(/^\/\(\?:\/\)\?$/, '/.*')// Replace the optional trailing with slash capture group with one that
// will match any descendants.
.replace(/\(\?:\/\)\?$/, '(?:/.*)?');
rewrites.push({
source: source.pathToRegexpPattern,
destination: destination.pathToRegexpPattern,
has: [
{
type: 'header',
key: NEXT_URL,
value: headerRegex
}
],
regex: source.namedRegex
});
}
}
return rewrites;
}
export function isInterceptionRouteRewrite(route) {
var _route_has_, _route_has;
// When we generate interception rewrites in the above implementation, we always do so with only a single `has` condition.
return ((_route_has = route.has) == null ? void 0 : (_route_has_ = _route_has[0]) == null ? void 0 : _route_has_.key) === NEXT_URL;
}
//# sourceMappingURL=generate-interception-routes-rewrites.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/generate-interception-routes-rewrites.ts"],"sourcesContent":["import { NEXT_URL } from '../client/components/app-router-headers'\nimport {\n extractInterceptionRouteInformation,\n isInterceptionRouteAppPath,\n} from '../shared/lib/router/utils/interception-routes'\nimport type { Rewrite } from './load-custom-routes'\nimport type { DeepReadonly } from '../shared/lib/deep-readonly'\nimport { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'\n\nexport function generateInterceptionRoutesRewrites(\n appPaths: string[],\n basePath = ''\n): Rewrite[] {\n const rewrites: Rewrite[] = []\n\n for (const appPath of appPaths) {\n if (isInterceptionRouteAppPath(appPath)) {\n const { interceptingRoute, interceptedRoute } =\n extractInterceptionRouteInformation(appPath)\n\n const destination = getNamedRouteRegex(basePath + appPath, {\n prefixRouteKeys: true,\n })\n\n const header = getNamedRouteRegex(interceptingRoute, {\n prefixRouteKeys: true,\n reference: destination.reference,\n })\n\n const source = getNamedRouteRegex(basePath + interceptedRoute, {\n prefixRouteKeys: true,\n reference: header.reference,\n })\n\n const headerRegex = header.namedRegex\n // Strip ^ and $ anchors since matchHas() will add them automatically\n .replace(/^\\^/, '')\n .replace(/\\$$/, '')\n // Replace matching the `/` with matching any route segment.\n .replace(/^\\/\\(\\?:\\/\\)\\?$/, '/.*')\n // Replace the optional trailing with slash capture group with one that\n // will match any descendants.\n .replace(/\\(\\?:\\/\\)\\?$/, '(?:/.*)?')\n\n rewrites.push({\n source: source.pathToRegexpPattern,\n destination: destination.pathToRegexpPattern,\n has: [\n {\n type: 'header',\n key: NEXT_URL,\n value: headerRegex,\n },\n ],\n regex: source.namedRegex,\n })\n }\n }\n\n return rewrites\n}\n\nexport function isInterceptionRouteRewrite(route: DeepReadonly<Rewrite>) {\n // When we generate interception rewrites in the above implementation, we always do so with only a single `has` condition.\n return route.has?.[0]?.key === NEXT_URL\n}\n"],"names":["NEXT_URL","extractInterceptionRouteInformation","isInterceptionRouteAppPath","getNamedRouteRegex","generateInterceptionRoutesRewrites","appPaths","basePath","rewrites","appPath","interceptingRoute","interceptedRoute","destination","prefixRouteKeys","header","reference","source","headerRegex","namedRegex","replace","push","pathToRegexpPattern","has","type","key","value","regex","isInterceptionRouteRewrite","route"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,0CAAyC;AAClE,SACEC,mCAAmC,EACnCC,0BAA0B,QACrB,iDAAgD;AAGvD,SAASC,kBAAkB,QAAQ,yCAAwC;AAE3E,OAAO,SAASC,mCACdC,QAAkB,EAClBC,WAAW,EAAE;IAEb,MAAMC,WAAsB,EAAE;IAE9B,KAAK,MAAMC,WAAWH,SAAU;QAC9B,IAAIH,2BAA2BM,UAAU;YACvC,MAAM,EAAEC,iBAAiB,EAAEC,gBAAgB,EAAE,GAC3CT,oCAAoCO;YAEtC,MAAMG,cAAcR,mBAAmBG,WAAWE,SAAS;gBACzDI,iBAAiB;YACnB;YAEA,MAAMC,SAASV,mBAAmBM,mBAAmB;gBACnDG,iBAAiB;gBACjBE,WAAWH,YAAYG,SAAS;YAClC;YAEA,MAAMC,SAASZ,mBAAmBG,WAAWI,kBAAkB;gBAC7DE,iBAAiB;gBACjBE,WAAWD,OAAOC,SAAS;YAC7B;YAEA,MAAME,cAAcH,OAAOI,UAAU,AACnC,qEAAqE;aACpEC,OAAO,CAAC,OAAO,IACfA,OAAO,CAAC,OAAO,GAChB,4DAA4D;aAC3DA,OAAO,CAAC,mBAAmB,MAC5B,uEAAuE;YACvE,8BAA8B;aAC7BA,OAAO,CAAC,gBAAgB;YAE3BX,SAASY,IAAI,CAAC;gBACZJ,QAAQA,OAAOK,mBAAmB;gBAClCT,aAAaA,YAAYS,mBAAmB;gBAC5CC,KAAK;oBACH;wBACEC,MAAM;wBACNC,KAAKvB;wBACLwB,OAAOR;oBACT;iBACD;gBACDS,OAAOV,OAAOE,UAAU;YAC1B;QACF;IACF;IAEA,OAAOV;AACT;AAEA,OAAO,SAASmB,2BAA2BC,KAA4B;QAE9DA,aAAAA;IADP,0HAA0H;IAC1H,OAAOA,EAAAA,aAAAA,MAAMN,GAAG,sBAATM,cAAAA,UAAW,CAAC,EAAE,qBAAdA,YAAgBJ,GAAG,MAAKvB;AACjC","ignoreList":[0]}

View File

@@ -0,0 +1,18 @@
import { join } from 'path';
import fs from 'fs/promises';
export async function getFilesInDir(path) {
const dir = await fs.opendir(path);
const results = new Set();
for await (const file of dir){
let resolvedFile = file;
if (file.isSymbolicLink()) {
resolvedFile = await fs.stat(join(path, file.name));
}
if (resolvedFile.isFile()) {
results.add(file.name);
}
}
return results;
}
//# sourceMappingURL=get-files-in-dir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/get-files-in-dir.ts"],"sourcesContent":["import { join } from 'path'\nimport fs from 'fs/promises'\nimport type { Dirent, StatsBase } from 'fs'\n\nexport async function getFilesInDir(path: string): Promise<Set<string>> {\n const dir = await fs.opendir(path)\n const results = new Set<string>()\n\n for await (const file of dir) {\n let resolvedFile: Dirent | StatsBase<number> = file\n\n if (file.isSymbolicLink()) {\n resolvedFile = await fs.stat(join(path, file.name))\n }\n\n if (resolvedFile.isFile()) {\n results.add(file.name)\n }\n }\n\n return results\n}\n"],"names":["join","fs","getFilesInDir","path","dir","opendir","results","Set","file","resolvedFile","isSymbolicLink","stat","name","isFile","add"],"mappings":"AAAA,SAASA,IAAI,QAAQ,OAAM;AAC3B,OAAOC,QAAQ,cAAa;AAG5B,OAAO,eAAeC,cAAcC,IAAY;IAC9C,MAAMC,MAAM,MAAMH,GAAGI,OAAO,CAACF;IAC7B,MAAMG,UAAU,IAAIC;IAEpB,WAAW,MAAMC,QAAQJ,IAAK;QAC5B,IAAIK,eAA2CD;QAE/C,IAAIA,KAAKE,cAAc,IAAI;YACzBD,eAAe,MAAMR,GAAGU,IAAI,CAACX,KAAKG,MAAMK,KAAKI,IAAI;QACnD;QAEA,IAAIH,aAAaI,MAAM,IAAI;YACzBP,QAAQQ,GAAG,CAACN,KAAKI,IAAI;QACvB;IACF;IAEA,OAAON;AACT","ignoreList":[0]}

View File

@@ -0,0 +1,29 @@
import os from 'os';
function getNetworkHosts(family) {
const interfaces = os.networkInterfaces();
const hosts = [];
Object.keys(interfaces).forEach((key)=>{
var _interfaces_key;
(_interfaces_key = interfaces[key]) == null ? void 0 : _interfaces_key.filter((networkInterface)=>{
switch(networkInterface.family){
case 'IPv6':
return family === 'IPv6' && networkInterface.scopeid === 0 && networkInterface.address !== '::1';
case 'IPv4':
return family === 'IPv4' && networkInterface.address !== '127.0.0.1';
default:
return false;
}
}).forEach((networkInterface)=>{
if (networkInterface.address) {
hosts.push(networkInterface.address);
}
});
});
return hosts;
}
export function getNetworkHost(family) {
const hosts = getNetworkHosts(family);
return hosts[0] ?? null;
}
//# sourceMappingURL=get-network-host.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/get-network-host.ts"],"sourcesContent":["import os from 'os'\n\nfunction getNetworkHosts(family: 'IPv4' | 'IPv6'): string[] {\n const interfaces = os.networkInterfaces()\n const hosts: string[] = []\n\n Object.keys(interfaces).forEach((key) => {\n interfaces[key]\n ?.filter((networkInterface) => {\n switch (networkInterface.family) {\n case 'IPv6':\n return (\n family === 'IPv6' &&\n networkInterface.scopeid === 0 &&\n networkInterface.address !== '::1'\n )\n case 'IPv4':\n return family === 'IPv4' && networkInterface.address !== '127.0.0.1'\n default:\n return false\n }\n })\n .forEach((networkInterface) => {\n if (networkInterface.address) {\n hosts.push(networkInterface.address)\n }\n })\n })\n\n return hosts\n}\n\nexport function getNetworkHost(family: 'IPv4' | 'IPv6'): string | null {\n const hosts = getNetworkHosts(family)\n return hosts[0] ?? null\n}\n"],"names":["os","getNetworkHosts","family","interfaces","networkInterfaces","hosts","Object","keys","forEach","key","filter","networkInterface","scopeid","address","push","getNetworkHost"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AAEnB,SAASC,gBAAgBC,MAAuB;IAC9C,MAAMC,aAAaH,GAAGI,iBAAiB;IACvC,MAAMC,QAAkB,EAAE;IAE1BC,OAAOC,IAAI,CAACJ,YAAYK,OAAO,CAAC,CAACC;YAC/BN;SAAAA,kBAAAA,UAAU,CAACM,IAAI,qBAAfN,gBACIO,MAAM,CAAC,CAACC;YACR,OAAQA,iBAAiBT,MAAM;gBAC7B,KAAK;oBACH,OACEA,WAAW,UACXS,iBAAiBC,OAAO,KAAK,KAC7BD,iBAAiBE,OAAO,KAAK;gBAEjC,KAAK;oBACH,OAAOX,WAAW,UAAUS,iBAAiBE,OAAO,KAAK;gBAC3D;oBACE,OAAO;YACX;QACF,GACCL,OAAO,CAAC,CAACG;YACR,IAAIA,iBAAiBE,OAAO,EAAE;gBAC5BR,MAAMS,IAAI,CAACH,iBAAiBE,OAAO;YACrC;QACF;IACJ;IAEA,OAAOR;AACT;AAEA,OAAO,SAASU,eAAeb,MAAuB;IACpD,MAAMG,QAAQJ,gBAAgBC;IAC9B,OAAOG,KAAK,CAAC,EAAE,IAAI;AACrB","ignoreList":[0]}

View File

@@ -0,0 +1,50 @@
import { promises as fs } from 'fs';
import findUp from 'next/dist/compiled/find-up';
import JSON5 from 'next/dist/compiled/json5';
import * as path from 'path';
let cachedDeps;
export function getDependencies({ cwd }) {
if (cachedDeps) {
return cachedDeps;
}
return cachedDeps = (async ()=>{
const configurationPath = await findUp('package.json', {
cwd
});
if (!configurationPath) {
return {
dependencies: {},
devDependencies: {}
};
}
const content = await fs.readFile(configurationPath, 'utf-8');
const packageJson = JSON5.parse(content);
const { dependencies = {}, devDependencies = {} } = packageJson || {};
return {
dependencies,
devDependencies
};
})();
}
export async function getPackageVersion({ cwd, name }) {
const { dependencies, devDependencies } = await getDependencies({
cwd
});
if (!(dependencies[name] || devDependencies[name])) {
return null;
}
const cwd2 = cwd.endsWith(path.posix.sep) || cwd.endsWith(path.win32.sep) ? cwd : `${cwd}/`;
try {
const targetPath = require.resolve(`${name}/package.json`, {
paths: [
cwd2
]
});
const targetContent = await fs.readFile(targetPath, 'utf-8');
return JSON5.parse(targetContent).version ?? null;
} catch {
return null;
}
}
//# sourceMappingURL=get-package-version.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/get-package-version.ts"],"sourcesContent":["import { promises as fs } from 'fs'\nimport findUp from 'next/dist/compiled/find-up'\nimport JSON5 from 'next/dist/compiled/json5'\nimport * as path from 'path'\n\ntype PackageJsonDependencies = {\n dependencies: Record<string, string>\n devDependencies: Record<string, string>\n}\n\nlet cachedDeps: Promise<PackageJsonDependencies>\n\nexport function getDependencies({\n cwd,\n}: {\n cwd: string\n}): Promise<PackageJsonDependencies> {\n if (cachedDeps) {\n return cachedDeps\n }\n\n return (cachedDeps = (async () => {\n const configurationPath: string | undefined = await findUp('package.json', {\n cwd,\n })\n if (!configurationPath) {\n return { dependencies: {}, devDependencies: {} }\n }\n\n const content = await fs.readFile(configurationPath, 'utf-8')\n const packageJson: any = JSON5.parse(content)\n\n const { dependencies = {}, devDependencies = {} } = packageJson || {}\n return { dependencies, devDependencies }\n })())\n}\n\nexport async function getPackageVersion({\n cwd,\n name,\n}: {\n cwd: string\n name: string\n}): Promise<string | null> {\n const { dependencies, devDependencies } = await getDependencies({ cwd })\n if (!(dependencies[name] || devDependencies[name])) {\n return null\n }\n\n const cwd2 =\n cwd.endsWith(path.posix.sep) || cwd.endsWith(path.win32.sep)\n ? cwd\n : `${cwd}/`\n\n try {\n const targetPath = require.resolve(`${name}/package.json`, {\n paths: [cwd2],\n })\n const targetContent = await fs.readFile(targetPath, 'utf-8')\n return JSON5.parse(targetContent).version ?? null\n } catch {\n return null\n }\n}\n"],"names":["promises","fs","findUp","JSON5","path","cachedDeps","getDependencies","cwd","configurationPath","dependencies","devDependencies","content","readFile","packageJson","parse","getPackageVersion","name","cwd2","endsWith","posix","sep","win32","targetPath","require","resolve","paths","targetContent","version"],"mappings":"AAAA,SAASA,YAAYC,EAAE,QAAQ,KAAI;AACnC,OAAOC,YAAY,6BAA4B;AAC/C,OAAOC,WAAW,2BAA0B;AAC5C,YAAYC,UAAU,OAAM;AAO5B,IAAIC;AAEJ,OAAO,SAASC,gBAAgB,EAC9BC,GAAG,EAGJ;IACC,IAAIF,YAAY;QACd,OAAOA;IACT;IAEA,OAAQA,aAAa,AAAC,CAAA;QACpB,MAAMG,oBAAwC,MAAMN,OAAO,gBAAgB;YACzEK;QACF;QACA,IAAI,CAACC,mBAAmB;YACtB,OAAO;gBAAEC,cAAc,CAAC;gBAAGC,iBAAiB,CAAC;YAAE;QACjD;QAEA,MAAMC,UAAU,MAAMV,GAAGW,QAAQ,CAACJ,mBAAmB;QACrD,MAAMK,cAAmBV,MAAMW,KAAK,CAACH;QAErC,MAAM,EAAEF,eAAe,CAAC,CAAC,EAAEC,kBAAkB,CAAC,CAAC,EAAE,GAAGG,eAAe,CAAC;QACpE,OAAO;YAAEJ;YAAcC;QAAgB;IACzC,CAAA;AACF;AAEA,OAAO,eAAeK,kBAAkB,EACtCR,GAAG,EACHS,IAAI,EAIL;IACC,MAAM,EAAEP,YAAY,EAAEC,eAAe,EAAE,GAAG,MAAMJ,gBAAgB;QAAEC;IAAI;IACtE,IAAI,CAAEE,CAAAA,YAAY,CAACO,KAAK,IAAIN,eAAe,CAACM,KAAK,AAAD,GAAI;QAClD,OAAO;IACT;IAEA,MAAMC,OACJV,IAAIW,QAAQ,CAACd,KAAKe,KAAK,CAACC,GAAG,KAAKb,IAAIW,QAAQ,CAACd,KAAKiB,KAAK,CAACD,GAAG,IACvDb,MACA,GAAGA,IAAI,CAAC,CAAC;IAEf,IAAI;QACF,MAAMe,aAAaC,QAAQC,OAAO,CAAC,GAAGR,KAAK,aAAa,CAAC,EAAE;YACzDS,OAAO;gBAACR;aAAK;QACf;QACA,MAAMS,gBAAgB,MAAMzB,GAAGW,QAAQ,CAACU,YAAY;QACpD,OAAOnB,MAAMW,KAAK,CAACY,eAAeC,OAAO,IAAI;IAC/C,EAAE,OAAM;QACN,OAAO;IACT;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,36 @@
import path from 'path';
import { warn } from '../build/output/log';
import { detectTypo } from './detect-typo';
import { realpathSync } from './realpath';
import { printAndExit } from '../server/lib/utils';
export function getProjectDir(dir, exitOnEnoent = true) {
const resolvedDir = path.resolve(dir || '.');
try {
const realDir = realpathSync(resolvedDir);
if (resolvedDir !== realDir && resolvedDir.toLowerCase() === realDir.toLowerCase()) {
warn(`Invalid casing detected for project dir, received ${resolvedDir} actual path ${realDir}, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing`);
}
return realDir;
} catch (err) {
if (err.code === 'ENOENT' && exitOnEnoent) {
if (typeof dir === 'string') {
const detectedTypo = detectTypo(dir, [
'build',
'dev',
'info',
'lint',
'start',
'telemetry',
'experimental-test'
]);
if (detectedTypo) {
return printAndExit(`"next ${dir}" does not exist. Did you mean "next ${detectedTypo}"?`);
}
}
return printAndExit(`Invalid project directory provided, no such directory: ${resolvedDir}`);
}
throw err;
}
}
//# sourceMappingURL=get-project-dir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/get-project-dir.ts"],"sourcesContent":["import path from 'path'\nimport { warn } from '../build/output/log'\nimport { detectTypo } from './detect-typo'\nimport { realpathSync } from './realpath'\nimport { printAndExit } from '../server/lib/utils'\n\nexport function getProjectDir(dir?: string, exitOnEnoent = true) {\n const resolvedDir = path.resolve(dir || '.')\n try {\n const realDir = realpathSync(resolvedDir)\n\n if (\n resolvedDir !== realDir &&\n resolvedDir.toLowerCase() === realDir.toLowerCase()\n ) {\n warn(\n `Invalid casing detected for project dir, received ${resolvedDir} actual path ${realDir}, see more info here https://nextjs.org/docs/messages/invalid-project-dir-casing`\n )\n }\n\n return realDir\n } catch (err: any) {\n if (err.code === 'ENOENT' && exitOnEnoent) {\n if (typeof dir === 'string') {\n const detectedTypo = detectTypo(dir, [\n 'build',\n 'dev',\n 'info',\n 'lint',\n 'start',\n 'telemetry',\n 'experimental-test',\n ])\n\n if (detectedTypo) {\n return printAndExit(\n `\"next ${dir}\" does not exist. Did you mean \"next ${detectedTypo}\"?`\n )\n }\n }\n\n return printAndExit(\n `Invalid project directory provided, no such directory: ${resolvedDir}`\n )\n }\n throw err\n }\n}\n"],"names":["path","warn","detectTypo","realpathSync","printAndExit","getProjectDir","dir","exitOnEnoent","resolvedDir","resolve","realDir","toLowerCase","err","code","detectedTypo"],"mappings":"AAAA,OAAOA,UAAU,OAAM;AACvB,SAASC,IAAI,QAAQ,sBAAqB;AAC1C,SAASC,UAAU,QAAQ,gBAAe;AAC1C,SAASC,YAAY,QAAQ,aAAY;AACzC,SAASC,YAAY,QAAQ,sBAAqB;AAElD,OAAO,SAASC,cAAcC,GAAY,EAAEC,eAAe,IAAI;IAC7D,MAAMC,cAAcR,KAAKS,OAAO,CAACH,OAAO;IACxC,IAAI;QACF,MAAMI,UAAUP,aAAaK;QAE7B,IACEA,gBAAgBE,WAChBF,YAAYG,WAAW,OAAOD,QAAQC,WAAW,IACjD;YACAV,KACE,CAAC,kDAAkD,EAAEO,YAAY,aAAa,EAAEE,QAAQ,gFAAgF,CAAC;QAE7K;QAEA,OAAOA;IACT,EAAE,OAAOE,KAAU;QACjB,IAAIA,IAAIC,IAAI,KAAK,YAAYN,cAAc;YACzC,IAAI,OAAOD,QAAQ,UAAU;gBAC3B,MAAMQ,eAAeZ,WAAWI,KAAK;oBACnC;oBACA;oBACA;oBACA;oBACA;oBACA;oBACA;iBACD;gBAED,IAAIQ,cAAc;oBAChB,OAAOV,aACL,CAAC,MAAM,EAAEE,IAAI,qCAAqC,EAAEQ,aAAa,EAAE,CAAC;gBAExE;YACF;YAEA,OAAOV,aACL,CAAC,uDAAuD,EAAEI,aAAa;QAE3E;QACA,MAAMI;IACR;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,39 @@
import { existsSync, realpathSync } from 'fs';
import { resolveFrom } from './resolve-from';
import { dirname, join, relative } from 'path';
export function hasNecessaryDependencies(baseDir, requiredPackages) {
let resolutions = new Map();
const missingPackages = [];
for (const p of requiredPackages){
try {
const pkgPath = realpathSync(resolveFrom(baseDir, `${p.pkg}/package.json`));
const pkgDir = dirname(pkgPath);
resolutions.set(join(p.pkg, 'package.json'), pkgPath);
if (p.exportsRestrict) {
const fileNameToVerify = relative(p.pkg, p.file);
if (fileNameToVerify) {
const fileToVerify = join(pkgDir, fileNameToVerify);
if (existsSync(fileToVerify)) {
resolutions.set(p.pkg, fileToVerify);
} else {
missingPackages.push(p);
continue;
}
} else {
resolutions.set(p.pkg, pkgPath);
}
} else {
resolutions.set(p.pkg, resolveFrom(baseDir, p.file));
}
} catch (_) {
missingPackages.push(p);
continue;
}
}
return {
resolved: resolutions,
missing: missingPackages
};
}
//# sourceMappingURL=has-necessary-dependencies.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/has-necessary-dependencies.ts"],"sourcesContent":["import { existsSync, realpathSync } from 'fs'\nimport { resolveFrom } from './resolve-from'\nimport { dirname, join, relative } from 'path'\n\nexport interface MissingDependency {\n file: string\n /**\n * The package's package.json (e.g. require(`${pkg}/package.json`)) MUST resolve.\n * If `exportsRestrict` is false, `${file}` MUST also resolve.\n */\n pkg: string\n /**\n * If true, the pkg's package.json needs to be resolvable.\n * If true, will resolve `file` relative to the real path of the package.json.\n *\n * For example, `{ file: '@types/react/index.d.ts', pkg: '@types/react', exportsRestrict: true }`\n * will try to resolve '@types/react/package.json' first and then assume `@types/react/index.d.ts`\n * resolves to `path.join(dirname(resolvedPackageJsonPath), 'index.d.ts')`.\n *\n * If false, will resolve `file` relative to the baseDir.\n * ForFor example, `{ file: '@types/react/index.d.ts', pkg: '@types/react', exportsRestrict: true }`\n * will try to resolve `@types/react/index.d.ts` directly.\n */\n exportsRestrict: boolean\n}\n\nexport type NecessaryDependencies = {\n resolved: Map<string, string>\n missing: MissingDependency[]\n}\n\nexport function hasNecessaryDependencies(\n baseDir: string,\n requiredPackages: MissingDependency[]\n): NecessaryDependencies {\n let resolutions = new Map<string, string>()\n const missingPackages: MissingDependency[] = []\n\n for (const p of requiredPackages) {\n try {\n const pkgPath = realpathSync(\n resolveFrom(baseDir, `${p.pkg}/package.json`)\n )\n const pkgDir = dirname(pkgPath)\n\n resolutions.set(join(p.pkg, 'package.json'), pkgPath)\n\n if (p.exportsRestrict) {\n const fileNameToVerify = relative(p.pkg, p.file)\n if (fileNameToVerify) {\n const fileToVerify = join(pkgDir, fileNameToVerify)\n if (existsSync(fileToVerify)) {\n resolutions.set(p.pkg, fileToVerify)\n } else {\n missingPackages.push(p)\n continue\n }\n } else {\n resolutions.set(p.pkg, pkgPath)\n }\n } else {\n resolutions.set(p.pkg, resolveFrom(baseDir, p.file))\n }\n } catch (_) {\n missingPackages.push(p)\n continue\n }\n }\n\n return {\n resolved: resolutions,\n missing: missingPackages,\n }\n}\n"],"names":["existsSync","realpathSync","resolveFrom","dirname","join","relative","hasNecessaryDependencies","baseDir","requiredPackages","resolutions","Map","missingPackages","p","pkgPath","pkg","pkgDir","set","exportsRestrict","fileNameToVerify","file","fileToVerify","push","_","resolved","missing"],"mappings":"AAAA,SAASA,UAAU,EAAEC,YAAY,QAAQ,KAAI;AAC7C,SAASC,WAAW,QAAQ,iBAAgB;AAC5C,SAASC,OAAO,EAAEC,IAAI,EAAEC,QAAQ,QAAQ,OAAM;AA6B9C,OAAO,SAASC,yBACdC,OAAe,EACfC,gBAAqC;IAErC,IAAIC,cAAc,IAAIC;IACtB,MAAMC,kBAAuC,EAAE;IAE/C,KAAK,MAAMC,KAAKJ,iBAAkB;QAChC,IAAI;YACF,MAAMK,UAAUZ,aACdC,YAAYK,SAAS,GAAGK,EAAEE,GAAG,CAAC,aAAa,CAAC;YAE9C,MAAMC,SAASZ,QAAQU;YAEvBJ,YAAYO,GAAG,CAACZ,KAAKQ,EAAEE,GAAG,EAAE,iBAAiBD;YAE7C,IAAID,EAAEK,eAAe,EAAE;gBACrB,MAAMC,mBAAmBb,SAASO,EAAEE,GAAG,EAAEF,EAAEO,IAAI;gBAC/C,IAAID,kBAAkB;oBACpB,MAAME,eAAehB,KAAKW,QAAQG;oBAClC,IAAIlB,WAAWoB,eAAe;wBAC5BX,YAAYO,GAAG,CAACJ,EAAEE,GAAG,EAAEM;oBACzB,OAAO;wBACLT,gBAAgBU,IAAI,CAACT;wBACrB;oBACF;gBACF,OAAO;oBACLH,YAAYO,GAAG,CAACJ,EAAEE,GAAG,EAAED;gBACzB;YACF,OAAO;gBACLJ,YAAYO,GAAG,CAACJ,EAAEE,GAAG,EAAEZ,YAAYK,SAASK,EAAEO,IAAI;YACpD;QACF,EAAE,OAAOG,GAAG;YACVX,gBAAgBU,IAAI,CAACT;YACrB;QACF;IACF;IAEA,OAAO;QACLW,UAAUd;QACVe,SAASb;IACX;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,53 @@
import os from 'os';
import path from 'path';
import fs from 'fs';
// get platform specific cache directory adapted from playwright's handling
// https://github.com/microsoft/playwright/blob/7d924470d397975a74a19184c136b3573a974e13/packages/playwright-core/src/utils/registry.ts#L141
export function getCacheDirectory(fileDirectory, envPath) {
let result;
if (envPath) {
result = envPath;
} else {
let systemCacheDirectory;
if (process.platform === 'linux') {
systemCacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');
} else if (process.platform === 'darwin') {
systemCacheDirectory = path.join(os.homedir(), 'Library', 'Caches');
} else if (process.platform === 'win32') {
systemCacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
} else {
/// Attempt to use generic tmp location for un-handled platform
if (!systemCacheDirectory) {
for (const dir of [
path.join(os.homedir(), '.cache'),
path.join(os.tmpdir())
]){
if (fs.existsSync(dir)) {
systemCacheDirectory = dir;
break;
}
}
}
if (!systemCacheDirectory) {
console.error(Object.defineProperty(new Error('Unsupported platform: ' + process.platform), "__NEXT_ERROR_CODE", {
value: "E141",
enumerable: false,
configurable: true
}));
process.exit(0);
}
}
result = path.join(systemCacheDirectory, fileDirectory);
}
if (!path.isAbsolute(result)) {
// It is important to resolve to the absolute path:
// - for unzipping to work correctly;
// - so that registry directory matches between installation and execution.
// INIT_CWD points to the root of `npm/yarn install` and is probably what
// the user meant when typing the relative path.
result = path.resolve(process.env['INIT_CWD'] || process.cwd(), result);
}
return result;
}
//# sourceMappingURL=get-cache-directory.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/helpers/get-cache-directory.ts"],"sourcesContent":["import os from 'os'\nimport path from 'path'\nimport fs from 'fs'\n\n// get platform specific cache directory adapted from playwright's handling\n// https://github.com/microsoft/playwright/blob/7d924470d397975a74a19184c136b3573a974e13/packages/playwright-core/src/utils/registry.ts#L141\nexport function getCacheDirectory(fileDirectory: string, envPath?: string) {\n let result\n\n if (envPath) {\n result = envPath\n } else {\n let systemCacheDirectory\n if (process.platform === 'linux') {\n systemCacheDirectory =\n process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache')\n } else if (process.platform === 'darwin') {\n systemCacheDirectory = path.join(os.homedir(), 'Library', 'Caches')\n } else if (process.platform === 'win32') {\n systemCacheDirectory =\n process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local')\n } else {\n /// Attempt to use generic tmp location for un-handled platform\n if (!systemCacheDirectory) {\n for (const dir of [\n path.join(os.homedir(), '.cache'),\n path.join(os.tmpdir()),\n ]) {\n if (fs.existsSync(dir)) {\n systemCacheDirectory = dir\n break\n }\n }\n }\n\n if (!systemCacheDirectory) {\n console.error(new Error('Unsupported platform: ' + process.platform))\n process.exit(0)\n }\n }\n result = path.join(systemCacheDirectory, fileDirectory)\n }\n\n if (!path.isAbsolute(result)) {\n // It is important to resolve to the absolute path:\n // - for unzipping to work correctly;\n // - so that registry directory matches between installation and execution.\n // INIT_CWD points to the root of `npm/yarn install` and is probably what\n // the user meant when typing the relative path.\n result = path.resolve(process.env['INIT_CWD'] || process.cwd(), result)\n }\n return result\n}\n"],"names":["os","path","fs","getCacheDirectory","fileDirectory","envPath","result","systemCacheDirectory","process","platform","env","XDG_CACHE_HOME","join","homedir","LOCALAPPDATA","dir","tmpdir","existsSync","console","error","Error","exit","isAbsolute","resolve","cwd"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,OAAOC,QAAQ,KAAI;AAEnB,2EAA2E;AAC3E,4IAA4I;AAC5I,OAAO,SAASC,kBAAkBC,aAAqB,EAAEC,OAAgB;IACvE,IAAIC;IAEJ,IAAID,SAAS;QACXC,SAASD;IACX,OAAO;QACL,IAAIE;QACJ,IAAIC,QAAQC,QAAQ,KAAK,SAAS;YAChCF,uBACEC,QAAQE,GAAG,CAACC,cAAc,IAAIV,KAAKW,IAAI,CAACZ,GAAGa,OAAO,IAAI;QAC1D,OAAO,IAAIL,QAAQC,QAAQ,KAAK,UAAU;YACxCF,uBAAuBN,KAAKW,IAAI,CAACZ,GAAGa,OAAO,IAAI,WAAW;QAC5D,OAAO,IAAIL,QAAQC,QAAQ,KAAK,SAAS;YACvCF,uBACEC,QAAQE,GAAG,CAACI,YAAY,IAAIb,KAAKW,IAAI,CAACZ,GAAGa,OAAO,IAAI,WAAW;QACnE,OAAO;YACL,+DAA+D;YAC/D,IAAI,CAACN,sBAAsB;gBACzB,KAAK,MAAMQ,OAAO;oBAChBd,KAAKW,IAAI,CAACZ,GAAGa,OAAO,IAAI;oBACxBZ,KAAKW,IAAI,CAACZ,GAAGgB,MAAM;iBACpB,CAAE;oBACD,IAAId,GAAGe,UAAU,CAACF,MAAM;wBACtBR,uBAAuBQ;wBACvB;oBACF;gBACF;YACF;YAEA,IAAI,CAACR,sBAAsB;gBACzBW,QAAQC,KAAK,CAAC,qBAAsD,CAAtD,IAAIC,MAAM,2BAA2BZ,QAAQC,QAAQ,GAArD,qBAAA;2BAAA;gCAAA;kCAAA;gBAAqD;gBACnED,QAAQa,IAAI,CAAC;YACf;QACF;QACAf,SAASL,KAAKW,IAAI,CAACL,sBAAsBH;IAC3C;IAEA,IAAI,CAACH,KAAKqB,UAAU,CAAChB,SAAS;QAC5B,mDAAmD;QACnD,uCAAuC;QACvC,6EAA6E;QAC7E,yEAAyE;QACzE,gDAAgD;QAChDA,SAASL,KAAKsB,OAAO,CAACf,QAAQE,GAAG,CAAC,WAAW,IAAIF,QAAQgB,GAAG,IAAIlB;IAClE;IACA,OAAOA;AACT","ignoreList":[0]}

View File

@@ -0,0 +1,19 @@
import { execSync } from 'child_process';
import { getPkgManager } from './get-pkg-manager';
export function getNpxCommand(baseDir) {
const pkgManager = getPkgManager(baseDir);
let command = 'npx --yes';
if (pkgManager === 'pnpm') {
command = 'pnpm --silent dlx';
} else if (pkgManager === 'yarn') {
try {
execSync('yarn dlx --help', {
stdio: 'ignore'
});
command = 'yarn --quiet dlx';
} catch {}
}
return command;
}
//# sourceMappingURL=get-npx-command.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/helpers/get-npx-command.ts"],"sourcesContent":["import { execSync } from 'child_process'\nimport { getPkgManager } from './get-pkg-manager'\n\nexport function getNpxCommand(baseDir: string) {\n const pkgManager = getPkgManager(baseDir)\n let command = 'npx --yes'\n if (pkgManager === 'pnpm') {\n command = 'pnpm --silent dlx'\n } else if (pkgManager === 'yarn') {\n try {\n execSync('yarn dlx --help', { stdio: 'ignore' })\n command = 'yarn --quiet dlx'\n } catch {}\n }\n\n return command\n}\n"],"names":["execSync","getPkgManager","getNpxCommand","baseDir","pkgManager","command","stdio"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAe;AACxC,SAASC,aAAa,QAAQ,oBAAmB;AAEjD,OAAO,SAASC,cAAcC,OAAe;IAC3C,MAAMC,aAAaH,cAAcE;IACjC,IAAIE,UAAU;IACd,IAAID,eAAe,QAAQ;QACzBC,UAAU;IACZ,OAAO,IAAID,eAAe,QAAQ;QAChC,IAAI;YACFJ,SAAS,mBAAmB;gBAAEM,OAAO;YAAS;YAC9CD,UAAU;QACZ,EAAE,OAAM,CAAC;IACX;IAEA,OAAOA;AACT","ignoreList":[0]}

View File

@@ -0,0 +1,35 @@
import { execSync } from 'child_process';
import dns from 'dns/promises';
function getProxy() {
if (process.env.https_proxy) {
return process.env.https_proxy;
}
try {
const httpsProxy = execSync('npm config get https-proxy', {
encoding: 'utf8'
}).trim();
return httpsProxy !== 'null' ? httpsProxy : undefined;
} catch (e) {
return;
}
}
export async function getOnline() {
try {
await dns.lookup('registry.yarnpkg.com');
return true;
} catch {
const proxy = getProxy();
if (!proxy) {
return false;
}
try {
const { hostname } = new URL(proxy);
await dns.lookup(hostname);
return true;
} catch {
return false;
}
}
}
//# sourceMappingURL=get-online.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/helpers/get-online.ts"],"sourcesContent":["import { execSync } from 'child_process'\nimport dns from 'dns/promises'\n\nfunction getProxy(): string | undefined {\n if (process.env.https_proxy) {\n return process.env.https_proxy\n }\n\n try {\n const httpsProxy = execSync('npm config get https-proxy', {\n encoding: 'utf8',\n }).trim()\n return httpsProxy !== 'null' ? httpsProxy : undefined\n } catch (e) {\n return\n }\n}\n\nexport async function getOnline(): Promise<boolean> {\n try {\n await dns.lookup('registry.yarnpkg.com')\n return true\n } catch {\n const proxy = getProxy()\n if (!proxy) {\n return false\n }\n\n try {\n const { hostname } = new URL(proxy)\n await dns.lookup(hostname)\n return true\n } catch {\n return false\n }\n }\n}\n"],"names":["execSync","dns","getProxy","process","env","https_proxy","httpsProxy","encoding","trim","undefined","e","getOnline","lookup","proxy","hostname","URL"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAe;AACxC,OAAOC,SAAS,eAAc;AAE9B,SAASC;IACP,IAAIC,QAAQC,GAAG,CAACC,WAAW,EAAE;QAC3B,OAAOF,QAAQC,GAAG,CAACC,WAAW;IAChC;IAEA,IAAI;QACF,MAAMC,aAAaN,SAAS,8BAA8B;YACxDO,UAAU;QACZ,GAAGC,IAAI;QACP,OAAOF,eAAe,SAASA,aAAaG;IAC9C,EAAE,OAAOC,GAAG;QACV;IACF;AACF;AAEA,OAAO,eAAeC;IACpB,IAAI;QACF,MAAMV,IAAIW,MAAM,CAAC;QACjB,OAAO;IACT,EAAE,OAAM;QACN,MAAMC,QAAQX;QACd,IAAI,CAACW,OAAO;YACV,OAAO;QACT;QAEA,IAAI;YACF,MAAM,EAAEC,QAAQ,EAAE,GAAG,IAAIC,IAAIF;YAC7B,MAAMZ,IAAIW,MAAM,CAACE;YACjB,OAAO;QACT,EAAE,OAAM;YACN,OAAO;QACT;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,48 @@
import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
export function getPkgManager(baseDir) {
try {
for (const { lockFile, packageManager } of [
{
lockFile: 'yarn.lock',
packageManager: 'yarn'
},
{
lockFile: 'pnpm-lock.yaml',
packageManager: 'pnpm'
},
{
lockFile: 'package-lock.json',
packageManager: 'npm'
}
]){
if (fs.existsSync(path.join(baseDir, lockFile))) {
return packageManager;
}
}
const userAgent = process.env.npm_config_user_agent;
if (userAgent) {
if (userAgent.startsWith('yarn')) {
return 'yarn';
} else if (userAgent.startsWith('pnpm')) {
return 'pnpm';
}
}
try {
execSync('yarn --version', {
stdio: 'ignore'
});
return 'yarn';
} catch {
execSync('pnpm --version', {
stdio: 'ignore'
});
return 'pnpm';
}
} catch {
return 'npm';
}
}
//# sourceMappingURL=get-pkg-manager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/helpers/get-pkg-manager.ts"],"sourcesContent":["import fs from 'fs'\nimport path from 'path'\nimport { execSync } from 'child_process'\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn'\n\nexport function getPkgManager(baseDir: string): PackageManager {\n try {\n for (const { lockFile, packageManager } of [\n { lockFile: 'yarn.lock', packageManager: 'yarn' },\n { lockFile: 'pnpm-lock.yaml', packageManager: 'pnpm' },\n { lockFile: 'package-lock.json', packageManager: 'npm' },\n ]) {\n if (fs.existsSync(path.join(baseDir, lockFile))) {\n return packageManager as PackageManager\n }\n }\n const userAgent = process.env.npm_config_user_agent\n if (userAgent) {\n if (userAgent.startsWith('yarn')) {\n return 'yarn'\n } else if (userAgent.startsWith('pnpm')) {\n return 'pnpm'\n }\n }\n try {\n execSync('yarn --version', { stdio: 'ignore' })\n return 'yarn'\n } catch {\n execSync('pnpm --version', { stdio: 'ignore' })\n return 'pnpm'\n }\n } catch {\n return 'npm'\n }\n}\n"],"names":["fs","path","execSync","getPkgManager","baseDir","lockFile","packageManager","existsSync","join","userAgent","process","env","npm_config_user_agent","startsWith","stdio"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,QAAQ,QAAQ,gBAAe;AAIxC,OAAO,SAASC,cAAcC,OAAe;IAC3C,IAAI;QACF,KAAK,MAAM,EAAEC,QAAQ,EAAEC,cAAc,EAAE,IAAI;YACzC;gBAAED,UAAU;gBAAaC,gBAAgB;YAAO;YAChD;gBAAED,UAAU;gBAAkBC,gBAAgB;YAAO;YACrD;gBAAED,UAAU;gBAAqBC,gBAAgB;YAAM;SACxD,CAAE;YACD,IAAIN,GAAGO,UAAU,CAACN,KAAKO,IAAI,CAACJ,SAASC,YAAY;gBAC/C,OAAOC;YACT;QACF;QACA,MAAMG,YAAYC,QAAQC,GAAG,CAACC,qBAAqB;QACnD,IAAIH,WAAW;YACb,IAAIA,UAAUI,UAAU,CAAC,SAAS;gBAChC,OAAO;YACT,OAAO,IAAIJ,UAAUI,UAAU,CAAC,SAAS;gBACvC,OAAO;YACT;QACF;QACA,IAAI;YACFX,SAAS,kBAAkB;gBAAEY,OAAO;YAAS;YAC7C,OAAO;QACT,EAAE,OAAM;YACNZ,SAAS,kBAAkB;gBAAEY,OAAO;YAAS;YAC7C,OAAO;QACT;IACF,EAAE,OAAM;QACN,OAAO;IACT;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,39 @@
import { execSync } from 'child_process';
import { getPkgManager } from './get-pkg-manager';
import { getFormattedNodeOptionsWithoutInspect } from '../../server/lib/utils';
/**
* Returns the package registry using the user's package manager.
* The URL will have a trailing slash.
* @default https://registry.npmjs.org/
*/ export function getRegistry(baseDir = process.cwd()) {
const pkgManager = getPkgManager(baseDir);
// Since `npm config` command fails in npm workspace to prevent workspace config conflicts,
// add `--no-workspaces` flag to run under the context of the root project only.
// Safe for non-workspace projects as it's equivalent to default `--workspaces=false`.
// x-ref: https://github.com/vercel/next.js/issues/47121#issuecomment-1499044345
// x-ref: https://github.com/npm/statusboard/issues/371#issue-920669998
const resolvedFlags = pkgManager === 'npm' ? '--no-workspaces' : '';
let registry = `https://registry.npmjs.org/`;
try {
const output = execSync(`${pkgManager} config get registry ${resolvedFlags}`, {
env: {
...process.env,
NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect()
}
}).toString().trim();
if (output.startsWith('http')) {
registry = output.endsWith('/') ? output : `${output}/`;
}
} catch (err) {
throw Object.defineProperty(new Error(`Failed to get registry from "${pkgManager}".`, {
cause: err
}), "__NEXT_ERROR_CODE", {
value: "E508",
enumerable: false,
configurable: true
});
}
return registry;
}
//# sourceMappingURL=get-registry.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/helpers/get-registry.ts"],"sourcesContent":["import { execSync } from 'child_process'\nimport { getPkgManager } from './get-pkg-manager'\nimport { getFormattedNodeOptionsWithoutInspect } from '../../server/lib/utils'\n\n/**\n * Returns the package registry using the user's package manager.\n * The URL will have a trailing slash.\n * @default https://registry.npmjs.org/\n */\nexport function getRegistry(baseDir: string = process.cwd()) {\n const pkgManager = getPkgManager(baseDir)\n // Since `npm config` command fails in npm workspace to prevent workspace config conflicts,\n // add `--no-workspaces` flag to run under the context of the root project only.\n // Safe for non-workspace projects as it's equivalent to default `--workspaces=false`.\n // x-ref: https://github.com/vercel/next.js/issues/47121#issuecomment-1499044345\n // x-ref: https://github.com/npm/statusboard/issues/371#issue-920669998\n const resolvedFlags = pkgManager === 'npm' ? '--no-workspaces' : ''\n let registry = `https://registry.npmjs.org/`\n\n try {\n const output = execSync(\n `${pkgManager} config get registry ${resolvedFlags}`,\n {\n env: {\n ...process.env,\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n }\n )\n .toString()\n .trim()\n\n if (output.startsWith('http')) {\n registry = output.endsWith('/') ? output : `${output}/`\n }\n } catch (err) {\n throw new Error(`Failed to get registry from \"${pkgManager}\".`, {\n cause: err,\n })\n }\n\n return registry\n}\n"],"names":["execSync","getPkgManager","getFormattedNodeOptionsWithoutInspect","getRegistry","baseDir","process","cwd","pkgManager","resolvedFlags","registry","output","env","NODE_OPTIONS","toString","trim","startsWith","endsWith","err","Error","cause"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,gBAAe;AACxC,SAASC,aAAa,QAAQ,oBAAmB;AACjD,SAASC,qCAAqC,QAAQ,yBAAwB;AAE9E;;;;CAIC,GACD,OAAO,SAASC,YAAYC,UAAkBC,QAAQC,GAAG,EAAE;IACzD,MAAMC,aAAaN,cAAcG;IACjC,2FAA2F;IAC3F,gFAAgF;IAChF,sFAAsF;IACtF,gFAAgF;IAChF,uEAAuE;IACvE,MAAMI,gBAAgBD,eAAe,QAAQ,oBAAoB;IACjE,IAAIE,WAAW,CAAC,2BAA2B,CAAC;IAE5C,IAAI;QACF,MAAMC,SAASV,SACb,GAAGO,WAAW,qBAAqB,EAAEC,eAAe,EACpD;YACEG,KAAK;gBACH,GAAGN,QAAQM,GAAG;gBACdC,cAAcV;YAChB;QACF,GAECW,QAAQ,GACRC,IAAI;QAEP,IAAIJ,OAAOK,UAAU,CAAC,SAAS;YAC7BN,WAAWC,OAAOM,QAAQ,CAAC,OAAON,SAAS,GAAGA,OAAO,CAAC,CAAC;QACzD;IACF,EAAE,OAAOO,KAAK;QACZ,MAAM,qBAEJ,CAFI,IAAIC,MAAM,CAAC,6BAA6B,EAAEX,WAAW,EAAE,CAAC,EAAE;YAC9DY,OAAOF;QACT,IAFM,qBAAA;mBAAA;wBAAA;0BAAA;QAEL;IACH;IAEA,OAAOR;AACT","ignoreList":[0]}

View File

@@ -0,0 +1,90 @@
/** https://fetch.spec.whatwg.org/#port-blocking */ export const KNOWN_RESERVED_PORTS = {
1: 'tcpmux',
7: 'echo',
9: 'discard',
11: 'systat',
13: 'daytime',
15: 'netstat',
17: 'qotd',
19: 'chargen',
20: 'ftp-data',
21: 'ftp',
22: 'ssh',
23: 'telnet',
25: 'smtp',
37: 'time',
42: 'name',
43: 'nicname',
53: 'domain',
69: 'tftp',
77: 'rje',
79: 'finger',
87: 'link',
95: 'supdup',
101: 'hostname',
102: 'iso-tsap',
103: 'gppitnp',
104: 'acr-nema',
109: 'pop2',
110: 'pop3',
111: 'sunrpc',
113: 'auth',
115: 'sftp',
117: 'uucp-path',
119: 'nntp',
123: 'ntp',
135: 'epmap',
137: 'netbios-ns',
139: 'netbios-ssn',
143: 'imap',
161: 'snmp',
179: 'bgp',
389: 'ldap',
427: 'svrloc',
465: 'submissions',
512: 'exec',
513: 'login',
514: 'shell',
515: 'printer',
526: 'tempo',
530: 'courier',
531: 'chat',
532: 'netnews',
540: 'uucp',
548: 'afp',
554: 'rtsp',
556: 'remotefs',
563: 'nntps',
587: 'submission',
601: 'syslog-conn',
636: 'ldaps',
989: 'ftps-data',
990: 'ftps',
993: 'imaps',
995: 'pop3s',
1719: 'h323gatestat',
1720: 'h323hostcall',
1723: 'pptp',
2049: 'nfs',
3659: 'apple-sasl',
4045: 'npp',
5060: 'sip',
5061: 'sips',
6000: 'x11',
6566: 'sane-port',
6665: 'ircu',
6666: 'ircu',
6667: 'ircu',
6668: 'ircu',
6669: 'ircu',
6697: 'ircs-u',
10080: 'amanda'
};
export function isPortIsReserved(port) {
return port in KNOWN_RESERVED_PORTS;
}
export function getReservedPortExplanation(port) {
return `Bad port: "${port}" is reserved for ${KNOWN_RESERVED_PORTS[port]}\n` + 'Read more: https://nextjs.org/docs/messages/reserved-port';
}
//# sourceMappingURL=get-reserved-port.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/helpers/get-reserved-port.ts"],"sourcesContent":["/** https://fetch.spec.whatwg.org/#port-blocking */\nexport const KNOWN_RESERVED_PORTS = {\n 1: 'tcpmux',\n 7: 'echo',\n 9: 'discard',\n 11: 'systat',\n 13: 'daytime',\n 15: 'netstat',\n 17: 'qotd',\n 19: 'chargen',\n 20: 'ftp-data',\n 21: 'ftp',\n 22: 'ssh',\n 23: 'telnet',\n 25: 'smtp',\n 37: 'time',\n 42: 'name',\n 43: 'nicname',\n 53: 'domain',\n 69: 'tftp',\n 77: 'rje',\n 79: 'finger',\n 87: 'link',\n 95: 'supdup',\n 101: 'hostname',\n 102: 'iso-tsap',\n 103: 'gppitnp',\n 104: 'acr-nema',\n 109: 'pop2',\n 110: 'pop3',\n 111: 'sunrpc',\n 113: 'auth',\n 115: 'sftp',\n 117: 'uucp-path',\n 119: 'nntp',\n 123: 'ntp',\n 135: 'epmap',\n 137: 'netbios-ns',\n 139: 'netbios-ssn',\n 143: 'imap',\n 161: 'snmp',\n 179: 'bgp',\n 389: 'ldap',\n 427: 'svrloc',\n 465: 'submissions',\n 512: 'exec',\n 513: 'login',\n 514: 'shell',\n 515: 'printer',\n 526: 'tempo',\n 530: 'courier',\n 531: 'chat',\n 532: 'netnews',\n 540: 'uucp',\n 548: 'afp',\n 554: 'rtsp',\n 556: 'remotefs',\n 563: 'nntps',\n 587: 'submission',\n 601: 'syslog-conn',\n 636: 'ldaps',\n 989: 'ftps-data',\n 990: 'ftps',\n 993: 'imaps',\n 995: 'pop3s',\n 1719: 'h323gatestat',\n 1720: 'h323hostcall',\n 1723: 'pptp',\n 2049: 'nfs',\n 3659: 'apple-sasl',\n 4045: 'npp',\n 5060: 'sip',\n 5061: 'sips',\n 6000: 'x11',\n 6566: 'sane-port',\n 6665: 'ircu',\n 6666: 'ircu',\n 6667: 'ircu',\n 6668: 'ircu',\n 6669: 'ircu',\n 6697: 'ircs-u',\n 10080: 'amanda',\n} as const\n\ntype ReservedPort = keyof typeof KNOWN_RESERVED_PORTS\n\nexport function isPortIsReserved(port: number): port is ReservedPort {\n return port in KNOWN_RESERVED_PORTS\n}\n\nexport function getReservedPortExplanation(port: ReservedPort): string {\n return (\n `Bad port: \"${port}\" is reserved for ${KNOWN_RESERVED_PORTS[port]}\\n` +\n 'Read more: https://nextjs.org/docs/messages/reserved-port'\n )\n}\n"],"names":["KNOWN_RESERVED_PORTS","isPortIsReserved","port","getReservedPortExplanation"],"mappings":"AAAA,iDAAiD,GACjD,OAAO,MAAMA,uBAAuB;IAClC,GAAG;IACH,GAAG;IACH,GAAG;IACH,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,IAAI;IACJ,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,MAAM;IACN,OAAO;AACT,EAAU;AAIV,OAAO,SAASC,iBAAiBC,IAAY;IAC3C,OAAOA,QAAQF;AACjB;AAEA,OAAO,SAASG,2BAA2BD,IAAkB;IAC3D,OACE,CAAC,WAAW,EAAEA,KAAK,kBAAkB,EAAEF,oBAAoB,CAACE,KAAK,CAAC,EAAE,CAAC,GACrE;AAEJ","ignoreList":[0]}

View File

@@ -0,0 +1,72 @@
import { yellow } from '../picocolors';
import spawn from 'next/dist/compiled/cross-spawn';
/**
* Spawn a package manager installation with either npm, pnpm, or yarn.
*
* @returns A Promise that resolves once the installation is finished.
*/ export function install(root, dependencies, { packageManager, isOnline, devDependencies }) {
let args = [];
if (dependencies.length > 0) {
if (packageManager === 'yarn') {
args = [
'add',
'--exact'
];
if (devDependencies) args.push('--dev');
} else if (packageManager === 'pnpm') {
args = [
'add',
'--save-exact'
];
args.push(devDependencies ? '--save-dev' : '--save-prod');
} else {
// npm
args = [
'install',
'--save-exact'
];
args.push(devDependencies ? '--save-dev' : '--save');
}
args.push(...dependencies);
} else {
args = [
'install'
] // npm, pnpm, and yarn all support `install`
;
if (!isOnline) {
args.push('--offline');
console.log(yellow('You appear to be offline.'));
if (packageManager !== 'npm') {
console.log(yellow(`Falling back to the local ${packageManager} cache.`));
}
console.log();
}
}
return new Promise((resolve, reject)=>{
/**
* Spawn the installation process.
*/ const child = spawn(packageManager, args, {
cwd: root,
stdio: 'inherit',
env: {
...process.env,
ADBLOCK: '1',
// we set NODE_ENV to development as pnpm skips dev
// dependencies when production
NODE_ENV: 'development',
DISABLE_OPENCOLLECTIVE: '1'
}
});
child.on('close', (code)=>{
if (code !== 0) {
reject({
command: `${packageManager} ${args.join(' ')}`
});
return;
}
resolve();
});
});
}
//# sourceMappingURL=install.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/lib/helpers/install.ts"],"sourcesContent":["import { yellow } from '../picocolors'\nimport spawn from 'next/dist/compiled/cross-spawn'\nimport type { PackageManager } from './get-pkg-manager'\n\ninterface InstallArgs {\n /**\n * Indicate whether to install packages using npm, pnpm, or yarn.\n */\n packageManager: PackageManager\n /**\n * Indicate whether there is an active internet connection.\n */\n isOnline: boolean\n /**\n * Indicate whether the given dependencies are devDependencies.\n */\n devDependencies?: boolean\n}\n\n/**\n * Spawn a package manager installation with either npm, pnpm, or yarn.\n *\n * @returns A Promise that resolves once the installation is finished.\n */\nexport function install(\n root: string,\n dependencies: string[],\n { packageManager, isOnline, devDependencies }: InstallArgs\n): Promise<void> {\n let args: string[] = []\n\n if (dependencies.length > 0) {\n if (packageManager === 'yarn') {\n args = ['add', '--exact']\n if (devDependencies) args.push('--dev')\n } else if (packageManager === 'pnpm') {\n args = ['add', '--save-exact']\n args.push(devDependencies ? '--save-dev' : '--save-prod')\n } else {\n // npm\n args = ['install', '--save-exact']\n args.push(devDependencies ? '--save-dev' : '--save')\n }\n\n args.push(...dependencies)\n } else {\n args = ['install'] // npm, pnpm, and yarn all support `install`\n\n if (!isOnline) {\n args.push('--offline')\n console.log(yellow('You appear to be offline.'))\n if (packageManager !== 'npm') {\n console.log(\n yellow(`Falling back to the local ${packageManager} cache.`)\n )\n }\n console.log()\n }\n }\n\n return new Promise((resolve, reject) => {\n /**\n * Spawn the installation process.\n */\n const child = spawn(packageManager, args, {\n cwd: root,\n stdio: 'inherit',\n env: {\n ...process.env,\n ADBLOCK: '1',\n // we set NODE_ENV to development as pnpm skips dev\n // dependencies when production\n NODE_ENV: 'development',\n DISABLE_OPENCOLLECTIVE: '1',\n },\n })\n child.on('close', (code) => {\n if (code !== 0) {\n reject({ command: `${packageManager} ${args.join(' ')}` })\n return\n }\n resolve()\n })\n })\n}\n"],"names":["yellow","spawn","install","root","dependencies","packageManager","isOnline","devDependencies","args","length","push","console","log","Promise","resolve","reject","child","cwd","stdio","env","process","ADBLOCK","NODE_ENV","DISABLE_OPENCOLLECTIVE","on","code","command","join"],"mappings":"AAAA,SAASA,MAAM,QAAQ,gBAAe;AACtC,OAAOC,WAAW,iCAAgC;AAkBlD;;;;CAIC,GACD,OAAO,SAASC,QACdC,IAAY,EACZC,YAAsB,EACtB,EAAEC,cAAc,EAAEC,QAAQ,EAAEC,eAAe,EAAe;IAE1D,IAAIC,OAAiB,EAAE;IAEvB,IAAIJ,aAAaK,MAAM,GAAG,GAAG;QAC3B,IAAIJ,mBAAmB,QAAQ;YAC7BG,OAAO;gBAAC;gBAAO;aAAU;YACzB,IAAID,iBAAiBC,KAAKE,IAAI,CAAC;QACjC,OAAO,IAAIL,mBAAmB,QAAQ;YACpCG,OAAO;gBAAC;gBAAO;aAAe;YAC9BA,KAAKE,IAAI,CAACH,kBAAkB,eAAe;QAC7C,OAAO;YACL,MAAM;YACNC,OAAO;gBAAC;gBAAW;aAAe;YAClCA,KAAKE,IAAI,CAACH,kBAAkB,eAAe;QAC7C;QAEAC,KAAKE,IAAI,IAAIN;IACf,OAAO;QACLI,OAAO;YAAC;SAAU,CAAC,4CAA4C;;QAE/D,IAAI,CAACF,UAAU;YACbE,KAAKE,IAAI,CAAC;YACVC,QAAQC,GAAG,CAACZ,OAAO;YACnB,IAAIK,mBAAmB,OAAO;gBAC5BM,QAAQC,GAAG,CACTZ,OAAO,CAAC,0BAA0B,EAAEK,eAAe,OAAO,CAAC;YAE/D;YACAM,QAAQC,GAAG;QACb;IACF;IAEA,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3B;;KAEC,GACD,MAAMC,QAAQf,MAAMI,gBAAgBG,MAAM;YACxCS,KAAKd;YACLe,OAAO;YACPC,KAAK;gBACH,GAAGC,QAAQD,GAAG;gBACdE,SAAS;gBACT,mDAAmD;gBACnD,+BAA+B;gBAC/BC,UAAU;gBACVC,wBAAwB;YAC1B;QACF;QACAP,MAAMQ,EAAE,CAAC,SAAS,CAACC;YACjB,IAAIA,SAAS,GAAG;gBACdV,OAAO;oBAAEW,SAAS,GAAGrB,eAAe,CAAC,EAAEG,KAAKmB,IAAI,CAAC,MAAM;gBAAC;gBACxD;YACF;YACAb;QACF;IACF;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,5 @@
var _module_parent;
import * as Log from '../build/output/log';
Log.warn(`"next" should not be imported directly, imported in ${(_module_parent = module.parent) == null ? void 0 : _module_parent.filename}\nSee more info here: https://nextjs.org/docs/messages/import-next`);
//# sourceMappingURL=import-next-warning.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/import-next-warning.ts"],"sourcesContent":["import * as Log from '../build/output/log'\n\nLog.warn(\n `\"next\" should not be imported directly, imported in ${module.parent?.filename}\\nSee more info here: https://nextjs.org/docs/messages/import-next`\n)\n"],"names":["module","Log","warn","parent","filename"],"mappings":"IAGyDA;AAHzD,YAAYC,SAAS,sBAAqB;AAE1CA,IAAIC,IAAI,CACN,CAAC,oDAAoD,GAAEF,iBAAAA,OAAOG,MAAM,qBAAbH,eAAeI,QAAQ,CAAC,kEAAkE,CAAC","ignoreList":[0]}

View File

@@ -0,0 +1,97 @@
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { promisify } from 'util';
import globOriginal from 'next/dist/compiled/glob';
import { Sema } from 'next/dist/compiled/async-sema';
import { getNextConfigEnv, getStaticEnv } from './static-env';
const glob = promisify(globOriginal);
export async function inlineStaticEnv({ distDir, config }) {
const nextConfigEnv = getNextConfigEnv(config);
const staticEnv = getStaticEnv(config, config.deploymentId);
const serverDir = path.join(distDir, 'server');
const serverChunks = await glob('**/*.{js,json,js.map}', {
cwd: serverDir
});
const clientDir = path.join(distDir, 'static');
const clientChunks = await glob('**/*.{js,json,js.map}', {
cwd: clientDir
});
const manifestChunks = await glob('*.{js,json,js.map}', {
cwd: distDir
});
const inlineSema = new Sema(8);
const nextConfigEnvKeys = Object.keys(nextConfigEnv).map((item)=>item.split('process.env.').pop());
const builtRegEx = new RegExp(`[\\w]{1,}(\\.env)?\\.(?:NEXT_PUBLIC_[\\w]{1,}${nextConfigEnvKeys.length ? '|' + nextConfigEnvKeys.join('|') : ''})`, 'g');
const changedClientFiles = [];
const filesToCheck = new Set(manifestChunks.map((f)=>path.join(distDir, f)));
for (const [parentDir, files] of [
[
serverDir,
serverChunks
],
[
clientDir,
clientChunks
]
]){
await Promise.all(files.map(async (file)=>{
await inlineSema.acquire();
const filepath = path.join(parentDir, file);
const content = await fs.promises.readFile(filepath, 'utf8');
const newContent = content.replace(builtRegEx, (match)=>{
let normalizedMatch = `process.env.${match.split('.').pop()}`;
if (staticEnv[normalizedMatch]) {
return JSON.stringify(staticEnv[normalizedMatch]);
}
return match;
});
await fs.promises.writeFile(filepath, newContent);
if (content !== newContent && parentDir === clientDir) {
changedClientFiles.push({
file,
content: newContent
});
}
filesToCheck.add(filepath);
inlineSema.release();
}));
}
const hashChanges = [];
// hashes need updating for any changed client files
for (const { file, content } of changedClientFiles){
var _file_match;
// hash is 16 chars currently for all client chunks
const originalHash = ((_file_match = file.match(/([a-z0-9]{16})\./)) == null ? void 0 : _file_match[1]) || '';
if (!originalHash) {
throw Object.defineProperty(new Error(`Invariant: client chunk changed but failed to detect hash ${file}`), "__NEXT_ERROR_CODE", {
value: "E663",
enumerable: false,
configurable: true
});
}
const newHash = crypto.createHash('sha256').update(content).digest('hex').substring(0, 16);
hashChanges.push({
originalHash,
newHash
});
const filepath = path.join(clientDir, file);
const newFilepath = filepath.replace(originalHash, newHash);
filesToCheck.delete(filepath);
filesToCheck.add(newFilepath);
await fs.promises.rename(filepath, newFilepath);
}
// update build-manifest and webpack-runtime with new hashes
for (let file of filesToCheck){
const content = await fs.promises.readFile(file, 'utf-8');
let newContent = content;
for (const { originalHash, newHash } of hashChanges){
newContent = newContent.replaceAll(originalHash, newHash);
}
if (content !== newContent) {
await fs.promises.writeFile(file, newContent);
}
}
}
//# sourceMappingURL=inline-static-env.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,25 @@
import { cyan } from './picocolors';
import path from 'path';
import { getPkgManager } from './helpers/get-pkg-manager';
import { install } from './helpers/install';
import { getOnline } from './helpers/get-online';
export async function installDependencies(baseDir, deps, dev = false) {
const packageManager = getPkgManager(baseDir);
const isOnline = await getOnline();
if (deps.length) {
console.log();
console.log(`Installing ${dev ? 'devDependencies' : 'dependencies'} (${packageManager}):`);
for (const dep of deps){
console.log(`- ${cyan(dep.pkg)}`);
}
console.log();
await install(path.resolve(baseDir), deps.map((dep)=>dep.pkg), {
devDependencies: dev,
isOnline,
packageManager
});
console.log();
}
}
//# sourceMappingURL=install-dependencies.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/install-dependencies.ts"],"sourcesContent":["import { cyan } from './picocolors'\nimport path from 'path'\n\nimport type { MissingDependency } from './has-necessary-dependencies'\nimport { getPkgManager } from './helpers/get-pkg-manager'\nimport { install } from './helpers/install'\nimport { getOnline } from './helpers/get-online'\n\nexport type Dependencies = {\n resolved: Map<string, string>\n}\n\nexport async function installDependencies(\n baseDir: string,\n deps: any,\n dev: boolean = false\n) {\n const packageManager = getPkgManager(baseDir)\n const isOnline = await getOnline()\n\n if (deps.length) {\n console.log()\n console.log(\n `Installing ${\n dev ? 'devDependencies' : 'dependencies'\n } (${packageManager}):`\n )\n for (const dep of deps) {\n console.log(`- ${cyan(dep.pkg)}`)\n }\n console.log()\n\n await install(\n path.resolve(baseDir),\n deps.map((dep: MissingDependency) => dep.pkg),\n { devDependencies: dev, isOnline, packageManager }\n )\n console.log()\n }\n}\n"],"names":["cyan","path","getPkgManager","install","getOnline","installDependencies","baseDir","deps","dev","packageManager","isOnline","length","console","log","dep","pkg","resolve","map","devDependencies"],"mappings":"AAAA,SAASA,IAAI,QAAQ,eAAc;AACnC,OAAOC,UAAU,OAAM;AAGvB,SAASC,aAAa,QAAQ,4BAA2B;AACzD,SAASC,OAAO,QAAQ,oBAAmB;AAC3C,SAASC,SAAS,QAAQ,uBAAsB;AAMhD,OAAO,eAAeC,oBACpBC,OAAe,EACfC,IAAS,EACTC,MAAe,KAAK;IAEpB,MAAMC,iBAAiBP,cAAcI;IACrC,MAAMI,WAAW,MAAMN;IAEvB,IAAIG,KAAKI,MAAM,EAAE;QACfC,QAAQC,GAAG;QACXD,QAAQC,GAAG,CACT,CAAC,WAAW,EACVL,MAAM,oBAAoB,eAC3B,EAAE,EAAEC,eAAe,EAAE,CAAC;QAEzB,KAAK,MAAMK,OAAOP,KAAM;YACtBK,QAAQC,GAAG,CAAC,CAAC,EAAE,EAAEb,KAAKc,IAAIC,GAAG,GAAG;QAClC;QACAH,QAAQC,GAAG;QAEX,MAAMV,QACJF,KAAKe,OAAO,CAACV,UACbC,KAAKU,GAAG,CAAC,CAACH,MAA2BA,IAAIC,GAAG,GAC5C;YAAEG,iBAAiBV;YAAKE;YAAUD;QAAe;QAEnDG,QAAQC,GAAG;IACb;AACF","ignoreList":[0]}

View File

@@ -0,0 +1,5 @@
export function interopDefault(mod) {
return mod.default || mod;
}
//# sourceMappingURL=interop-default.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/interop-default.ts"],"sourcesContent":["export function interopDefault(mod: any) {\n return mod.default || mod\n}\n"],"names":["interopDefault","mod","default"],"mappings":"AAAA,OAAO,SAASA,eAAeC,GAAQ;IACrC,OAAOA,IAAIC,OAAO,IAAID;AACxB","ignoreList":[0]}

View File

@@ -0,0 +1,5 @@
export function isAPIRoute(value) {
return value === '/api' || Boolean(value == null ? void 0 : value.startsWith('/api/'));
}
//# sourceMappingURL=is-api-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/is-api-route.ts"],"sourcesContent":["export function isAPIRoute(value?: string) {\n return value === '/api' || Boolean(value?.startsWith('/api/'))\n}\n"],"names":["isAPIRoute","value","Boolean","startsWith"],"mappings":"AAAA,OAAO,SAASA,WAAWC,KAAc;IACvC,OAAOA,UAAU,UAAUC,QAAQD,yBAAAA,MAAOE,UAAU,CAAC;AACvD","ignoreList":[0]}

View File

@@ -0,0 +1,5 @@
export function isAppPageRoute(route) {
return route.endsWith('/page');
}
//# sourceMappingURL=is-app-page-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/is-app-page-route.ts"],"sourcesContent":["export function isAppPageRoute(route: string): boolean {\n return route.endsWith('/page')\n}\n"],"names":["isAppPageRoute","route","endsWith"],"mappings":"AAAA,OAAO,SAASA,eAAeC,KAAa;IAC1C,OAAOA,MAAMC,QAAQ,CAAC;AACxB","ignoreList":[0]}

View File

@@ -0,0 +1,5 @@
export function isAppRouteRoute(route) {
return route.endsWith('/route');
}
//# sourceMappingURL=is-app-route-route.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/is-app-route-route.ts"],"sourcesContent":["export function isAppRouteRoute(route: string): boolean {\n return route.endsWith('/route')\n}\n"],"names":["isAppRouteRoute","route","endsWith"],"mappings":"AAAA,OAAO,SAASA,gBAAgBC,KAAa;IAC3C,OAAOA,MAAMC,QAAQ,CAAC;AACxB","ignoreList":[0]}

View File

@@ -0,0 +1,6 @@
import { SERVER_RUNTIME } from './constants';
export function isEdgeRuntime(value) {
return value === SERVER_RUNTIME.experimentalEdge || value === SERVER_RUNTIME.edge;
}
//# sourceMappingURL=is-edge-runtime.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/is-edge-runtime.ts"],"sourcesContent":["import type { ServerRuntime } from '../types'\nimport { SERVER_RUNTIME } from './constants'\n\nexport function isEdgeRuntime(value?: string): value is ServerRuntime {\n return (\n value === SERVER_RUNTIME.experimentalEdge || value === SERVER_RUNTIME.edge\n )\n}\n"],"names":["SERVER_RUNTIME","isEdgeRuntime","value","experimentalEdge","edge"],"mappings":"AACA,SAASA,cAAc,QAAQ,cAAa;AAE5C,OAAO,SAASC,cAAcC,KAAc;IAC1C,OACEA,UAAUF,eAAeG,gBAAgB,IAAID,UAAUF,eAAeI,IAAI;AAE9E","ignoreList":[0]}

View File

@@ -0,0 +1,56 @@
import { isPlainObject } from '../shared/lib/is-plain-object';
/**
* This is a safe stringify function that handles circular references.
* We're using a simpler version here to avoid introducing
* the dependency `safe-stable-stringify` into production bundle.
*
* This helper is used both in development and production.
*/ function safeStringifyLite(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (_key, value)=>{
// If value is an object and already seen, replace with "[Circular]"
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
}
return value;
});
}
/**
* Checks whether the given value is a NextError.
* This can be used to print a more detailed error message with properties like `code` & `digest`.
*/ export default function isError(err) {
return typeof err === 'object' && err !== null && 'name' in err && 'message' in err;
}
export function getProperError(err) {
if (isError(err)) {
return err;
}
if (process.env.NODE_ENV === 'development') {
// provide better error for case where `throw undefined`
// is called in development
if (typeof err === 'undefined') {
return Object.defineProperty(new Error('An undefined error was thrown, ' + 'see here for more info: https://nextjs.org/docs/messages/threw-undefined'), "__NEXT_ERROR_CODE", {
value: "E98",
enumerable: false,
configurable: true
});
}
if (err === null) {
return Object.defineProperty(new Error('A null error was thrown, ' + 'see here for more info: https://nextjs.org/docs/messages/threw-undefined'), "__NEXT_ERROR_CODE", {
value: "E336",
enumerable: false,
configurable: true
});
}
}
return Object.defineProperty(new Error(isPlainObject(err) ? safeStringifyLite(err) : err + ''), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
//# sourceMappingURL=is-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/is-error.ts"],"sourcesContent":["import { isPlainObject } from '../shared/lib/is-plain-object'\n\n// We allow some additional attached properties for Next.js errors\nexport interface NextError extends Error {\n type?: string\n page?: string\n code?: string | number\n cancelled?: boolean\n digest?: number\n}\n\n/**\n * This is a safe stringify function that handles circular references.\n * We're using a simpler version here to avoid introducing\n * the dependency `safe-stable-stringify` into production bundle.\n *\n * This helper is used both in development and production.\n */\nfunction safeStringifyLite(obj: any) {\n const seen = new WeakSet()\n\n return JSON.stringify(obj, (_key, value) => {\n // If value is an object and already seen, replace with \"[Circular]\"\n if (typeof value === 'object' && value !== null) {\n if (seen.has(value)) {\n return '[Circular]'\n }\n seen.add(value)\n }\n return value\n })\n}\n\n/**\n * Checks whether the given value is a NextError.\n * This can be used to print a more detailed error message with properties like `code` & `digest`.\n */\nexport default function isError(err: unknown): err is NextError {\n return (\n typeof err === 'object' && err !== null && 'name' in err && 'message' in err\n )\n}\n\nexport function getProperError(err: unknown): Error {\n if (isError(err)) {\n return err\n }\n\n if (process.env.NODE_ENV === 'development') {\n // provide better error for case where `throw undefined`\n // is called in development\n if (typeof err === 'undefined') {\n return new Error(\n 'An undefined error was thrown, ' +\n 'see here for more info: https://nextjs.org/docs/messages/threw-undefined'\n )\n }\n\n if (err === null) {\n return new Error(\n 'A null error was thrown, ' +\n 'see here for more info: https://nextjs.org/docs/messages/threw-undefined'\n )\n }\n }\n\n return new Error(isPlainObject(err) ? safeStringifyLite(err) : err + '')\n}\n"],"names":["isPlainObject","safeStringifyLite","obj","seen","WeakSet","JSON","stringify","_key","value","has","add","isError","err","getProperError","process","env","NODE_ENV","Error"],"mappings":"AAAA,SAASA,aAAa,QAAQ,gCAA+B;AAW7D;;;;;;CAMC,GACD,SAASC,kBAAkBC,GAAQ;IACjC,MAAMC,OAAO,IAAIC;IAEjB,OAAOC,KAAKC,SAAS,CAACJ,KAAK,CAACK,MAAMC;QAChC,oEAAoE;QACpE,IAAI,OAAOA,UAAU,YAAYA,UAAU,MAAM;YAC/C,IAAIL,KAAKM,GAAG,CAACD,QAAQ;gBACnB,OAAO;YACT;YACAL,KAAKO,GAAG,CAACF;QACX;QACA,OAAOA;IACT;AACF;AAEA;;;CAGC,GACD,eAAe,SAASG,QAAQC,GAAY;IAC1C,OACE,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,UAAUA,OAAO,aAAaA;AAE7E;AAEA,OAAO,SAASC,eAAeD,GAAY;IACzC,IAAID,QAAQC,MAAM;QAChB,OAAOA;IACT;IAEA,IAAIE,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QAC1C,wDAAwD;QACxD,2BAA2B;QAC3B,IAAI,OAAOJ,QAAQ,aAAa;YAC9B,OAAO,qBAGN,CAHM,IAAIK,MACT,oCACE,6EAFG,qBAAA;uBAAA;4BAAA;8BAAA;YAGP;QACF;QAEA,IAAIL,QAAQ,MAAM;YAChB,OAAO,qBAGN,CAHM,IAAIK,MACT,8BACE,6EAFG,qBAAA;uBAAA;4BAAA;8BAAA;YAGP;QACF;IACF;IAEA,OAAO,qBAAiE,CAAjE,IAAIA,MAAMjB,cAAcY,OAAOX,kBAAkBW,OAAOA,MAAM,KAA9D,qBAAA;eAAA;oBAAA;sBAAA;IAAgE;AACzE","ignoreList":[0]}

View File

@@ -0,0 +1,14 @@
export function isInternalComponent(pathname) {
switch(pathname){
case 'next/dist/pages/_app':
case 'next/dist/pages/_document':
return true;
default:
return false;
}
}
export function isNonRoutePagesPage(pathname) {
return pathname === '/_app' || pathname === '/_document';
}
//# sourceMappingURL=is-internal-component.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/lib/is-internal-component.ts"],"sourcesContent":["export function isInternalComponent(pathname: string): boolean {\n switch (pathname) {\n case 'next/dist/pages/_app':\n case 'next/dist/pages/_document':\n return true\n default:\n return false\n }\n}\n\nexport function isNonRoutePagesPage(pathname: string): boolean {\n return pathname === '/_app' || pathname === '/_document'\n}\n"],"names":["isInternalComponent","pathname","isNonRoutePagesPage"],"mappings":"AAAA,OAAO,SAASA,oBAAoBC,QAAgB;IAClD,OAAQA;QACN,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF;AAEA,OAAO,SAASC,oBAAoBD,QAAgB;IAClD,OAAOA,aAAa,WAAWA,aAAa;AAC9C","ignoreList":[0]}

View File

@@ -0,0 +1,84 @@
import { isPlainObject, getObjectClassLabel } from '../shared/lib/is-plain-object';
const regexpPlainIdentifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
export class SerializableError extends Error {
constructor(page, method, path, message){
super(path ? `Error serializing \`${path}\` returned from \`${method}\` in "${page}".\nReason: ${message}` : `Error serializing props returned from \`${method}\` in "${page}".\nReason: ${message}`);
}
}
export function isSerializableProps(page, method, input) {
if (!isPlainObject(input)) {
throw Object.defineProperty(new SerializableError(page, method, '', `Props must be returned as a plain object from ${method}: \`{ props: { ... } }\` (received: \`${getObjectClassLabel(input)}\`).`), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
function visit(visited, value, path) {
if (visited.has(value)) {
throw Object.defineProperty(new SerializableError(page, method, path, `Circular references cannot be expressed in JSON (references: \`${visited.get(value) || '(self)'}\`).`), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
visited.set(value, path);
}
function isSerializable(refs, value, path) {
const type = typeof value;
if (// `null` can be serialized, but not `undefined`.
value === null || // n.b. `bigint`, `function`, `symbol`, and `undefined` cannot be
// serialized.
//
// `object` is special-cased below, as it may represent `null`, an Array,
// a plain object, a class, et al.
type === 'boolean' || type === 'number' || type === 'string') {
return true;
}
if (type === 'undefined') {
throw Object.defineProperty(new SerializableError(page, method, path, '`undefined` cannot be serialized as JSON. Please use `null` or omit this value.'), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
if (isPlainObject(value)) {
visit(refs, value, path);
if (Object.entries(value).every(([key, nestedValue])=>{
const nextPath = regexpPlainIdentifier.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
const newRefs = new Map(refs);
return isSerializable(newRefs, key, nextPath) && isSerializable(newRefs, nestedValue, nextPath);
})) {
return true;
}
throw Object.defineProperty(new SerializableError(page, method, path, `invariant: Unknown error encountered in Object.`), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
if (Array.isArray(value)) {
visit(refs, value, path);
if (value.every((nestedValue, index)=>{
const newRefs = new Map(refs);
return isSerializable(newRefs, nestedValue, `${path}[${index}]`);
})) {
return true;
}
throw Object.defineProperty(new SerializableError(page, method, path, `invariant: Unknown error encountered in Array.`), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
// None of these can be expressed as JSON:
// const type: "bigint" | "symbol" | "object" | "function"
throw Object.defineProperty(new SerializableError(page, method, path, '`' + type + '`' + (type === 'object' ? ` ("${Object.prototype.toString.call(value)}")` : '') + ' cannot be serialized as JSON. Please only return JSON serializable data types.'), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
return isSerializable(new Map(), input, '');
}
//# sourceMappingURL=is-serializable-props.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
["function-bind"]

Some files were not shown because too many files have changed in this diff Show More