@expo/cli 1.0.0-canary-20250404-42b6263 → 1.0.0-canary-20250404-3c3b5fd
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +26 -5
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/metroErrorInterface.js +26 -15
- package/build/src/start/server/metro/metroErrorInterface.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +11 -0
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/serverLogLikeMetro.js +53 -0
- package/build/src/start/server/serverLogLikeMetro.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/package.json +13 -13
package/build/bin/cli
CHANGED
|
@@ -123,7 +123,7 @@ const args = (0, _arg().default)({
|
|
|
123
123
|
});
|
|
124
124
|
if (args['--version']) {
|
|
125
125
|
// Version is added in the build script.
|
|
126
|
-
console.log("1.0.0-canary-20250404-
|
|
126
|
+
console.log("1.0.0-canary-20250404-3c3b5fd");
|
|
127
127
|
process.exit(0);
|
|
128
128
|
}
|
|
129
129
|
if (args['--non-interactive']) {
|
|
@@ -45,6 +45,7 @@ function _interop_require_default(obj) {
|
|
|
45
45
|
default: obj
|
|
46
46
|
};
|
|
47
47
|
}
|
|
48
|
+
const debug = require('debug')('expo:metro:logger');
|
|
48
49
|
const MAX_PROGRESS_BAR_CHAR_WIDTH = 16;
|
|
49
50
|
const DARK_BLOCK_CHAR = '\u2593';
|
|
50
51
|
const LIGHT_BLOCK_CHAR = '\u2591';
|
|
@@ -60,14 +61,34 @@ class MetroTerminalReporter extends _TerminalReporter.TerminalReporter {
|
|
|
60
61
|
return;
|
|
61
62
|
}
|
|
62
63
|
const { level } = event;
|
|
64
|
+
if (!level) {
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
63
67
|
const mode = event.mode === 'NOBRIDGE' ? '' : event.mode ?? '';
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
+
// @ts-expect-error
|
|
69
|
+
if (level === 'warn' || level === 'error') {
|
|
70
|
+
// Quick check to see if an unsymbolicated stack is being logged.
|
|
71
|
+
const msg = event.data.join('\n');
|
|
72
|
+
if (msg.includes('.bundle//&platform=')) {
|
|
73
|
+
const parsed = (0, _serverLogLikeMetro.parseErrorStringToObject)(msg);
|
|
74
|
+
if (parsed) {
|
|
75
|
+
(0, _serverLogLikeMetro.maybeSymbolicateAndFormatReactErrorLogAsync)(this.projectRoot, level, parsed).then((res)=>{
|
|
76
|
+
// Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.
|
|
77
|
+
(0, _serverLogLikeMetro.logLikeMetro)(this.terminal.log.bind(this.terminal), level, mode, res);
|
|
78
|
+
}).catch((e)=>{
|
|
79
|
+
// Fallback on the original error message if we can't symbolicate the stack.
|
|
80
|
+
debug('Error formatting stack', e);
|
|
81
|
+
// Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.
|
|
82
|
+
(0, _serverLogLikeMetro.logLikeMetro)(this.terminal.log.bind(this.terminal), level, mode, ...event.data);
|
|
83
|
+
});
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
68
87
|
}
|
|
88
|
+
// Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.
|
|
89
|
+
(0, _serverLogLikeMetro.logLikeMetro)(this.terminal.log.bind(this.terminal), level, mode, ...event.data);
|
|
90
|
+
return;
|
|
69
91
|
}
|
|
70
|
-
break;
|
|
71
92
|
}
|
|
72
93
|
return super._log(event);
|
|
73
94
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { learnMore } from '../../../utils/link';\nimport { logLikeMetro } from '../serverLogLikeMetro';\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n _log(event: TerminalReportableEvent): void {\n switch (event.type) {\n case 'client_log':\n {\n if (this.shouldFilterClientLog(event)) {\n return;\n }\n\n const { level } = event;\n\n const mode = event.mode === 'NOBRIDGE' ? '' : (event.mode ?? '');\n\n if (level) {\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, ...event.data);\n return;\n }\n }\n break;\n }\n return super._log(event);\n }\n\n // Used for testing\n _getElapsedTime(startTime: bigint): bigint {\n return process.hrtime.bigint() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n let localPath: string;\n\n if (\n typeof progress.bundleDetails?.customTransformOptions?.dom === 'string' &&\n progress.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ) {\n // Because we use a generated entry file for DOM components, we need to adjust the logging path so it\n // shows a unique path for each component.\n // Here, we take the relative import path and remove all the starting slashes.\n localPath = progress.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '');\n } else {\n const inputFile = progress.bundleDetails.entryFile;\n\n localPath = path.isAbsolute(inputFile)\n ? path.relative(this.projectRoot, inputFile)\n : inputFile;\n }\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n\n let time: string = '';\n\n if (startTime != null) {\n const elapsed: bigint = this._getElapsedTime(startTime);\n const micro = Number(elapsed) / 1000;\n const converted = Number(elapsed) / 1e6;\n // If the milliseconds are < 0.5 then it will display as 0, so we display in microseconds.\n if (converted <= 0.5) {\n const tenthFractionOfMicro = ((micro * 10) / 1000).toFixed(0);\n // Format as microseconds to nearest tenth\n time = chalk.cyan.bold(`0.${tenthFractionOfMicro}ms`);\n } else {\n time = chalk.dim(converted.toFixed(0) + 'ms');\n }\n }\n\n // iOS Bundled 150ms\n const plural = progress.totalFileCount === 1 ? '' : 's';\n return (\n color(platform + status) +\n time +\n chalk.reset.dim(` ${localPath} (${progress.totalFileCount} module${plural})`)\n );\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}${path.sep}`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log(chalk.dim('Starting Metro Bundler'));\n }\n\n shouldFilterClientLog(event: { type: 'client_log'; data: unknown[] }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return null;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n } else if (env === 'react-server') {\n return chalk.bold(`RSC(${getPlatformTagForBuildDetails(bundleDetails).trim()})`) + ' ';\n }\n\n if (\n bundleDetails?.customTransformOptions?.dom &&\n typeof bundleDetails?.customTransformOptions?.dom === 'string'\n ) {\n return chalk.bold(`DOM`) + ' ';\n }\n\n return '';\n}\n"],"names":["MetroTerminalReporter","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","projectRoot","terminal","_log","event","type","shouldFilterClientLog","level","mode","logLikeMetro","log","bind","data","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","includes","path","sep","replace","inputFile","entryFile","isAbsolute","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","elapsed","micro","Number","converted","tenthFractionOfMicro","toFixed","cyan","bold","dim","plural","totalFileCount","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","padStart","transformedFileCount","toString","length","dirname","basename","_logInitializing","port","hasReducedPerformance","isAppRegistryStartupMessage","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","environment","trim"],"mappings":";;;;;;;;;;;IAuBaA,qBAAqB;eAArBA;;IAiLGC,mCAAmC;eAAnCA;;IAwCAC,sBAAsB;eAAtBA;;IAkBAC,cAAc;eAAdA;;;;gEAlQE;;;;;;;gEAED;;;;;;kCAE4B;2BAQT;sBACV;oCACG;;;;;;AAE7B,MAAMC,8BAA8B;AACpC,MAAMC,kBAAkB;AACxB,MAAMC,mBAAmB;AAKlB,MAAMN,8BAA8BO,kCAAgB;IACzDC,YACE,AAAOC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,gBAHCD,cAAAA;IAIT;IAEAE,KAAKC,KAA8B,EAAQ;QACzC,OAAQA,MAAMC,IAAI;YAChB,KAAK;gBACH;oBACE,IAAI,IAAI,CAACC,qBAAqB,CAACF,QAAQ;wBACrC;oBACF;oBAEA,MAAM,EAAEG,KAAK,EAAE,GAAGH;oBAElB,MAAMI,OAAOJ,MAAMI,IAAI,KAAK,aAAa,KAAMJ,MAAMI,IAAI,IAAI;oBAE7D,IAAID,OAAO;wBACT,kHAAkH;wBAClHE,IAAAA,gCAAY,EAAC,IAAI,CAACP,QAAQ,CAACQ,GAAG,CAACC,IAAI,CAAC,IAAI,CAACT,QAAQ,GAAGK,OAAOC,SAASJ,MAAMQ,IAAI;wBAC9E;oBACF;gBACF;gBACA;QACJ;QACA,OAAO,KAAK,CAACT,KAAKC;IACpB;IAEA,mBAAmB;IACnBS,gBAAgBC,SAAiB,EAAU;QACzC,OAAOC,QAAQC,MAAM,CAACC,MAAM,KAAKH;IACnC;IACA;;;;GAIC,GACDI,wBAAwBC,QAAwB,EAAEC,KAAiB,EAAU;YAQlED,gDAAAA;QAPT,MAAME,MAAMC,8BAA8BH,SAASI,aAAa;QAChE,MAAMC,WAAWH,OAAOI,8BAA8BN,SAASI,aAAa;QAC5E,MAAMG,aAAaN,UAAU;QAE7B,IAAIO;QAEJ,IACE,SAAOR,0BAAAA,SAAS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3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { learnMore } from '../../../utils/link';\nimport {\n logLikeMetro,\n maybeSymbolicateAndFormatReactErrorLogAsync,\n parseErrorStringToObject,\n} from '../serverLogLikeMetro';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n _log(event: TerminalReportableEvent): void {\n switch (event.type) {\n case 'client_log': {\n if (this.shouldFilterClientLog(event)) {\n return;\n }\n const { level } = event;\n\n if (!level) {\n break;\n }\n\n const mode = event.mode === 'NOBRIDGE' ? '' : (event.mode ?? '');\n // @ts-expect-error\n if (level === 'warn' || level === 'error') {\n // Quick check to see if an unsymbolicated stack is being logged.\n const msg = event.data.join('\\n');\n if (msg.includes('.bundle//&platform=')) {\n const parsed = parseErrorStringToObject(msg);\n if (parsed) {\n maybeSymbolicateAndFormatReactErrorLogAsync(this.projectRoot, level, parsed)\n .then((res) => {\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, res);\n })\n .catch((e) => {\n // Fallback on the original error message if we can't symbolicate the stack.\n debug('Error formatting stack', e);\n\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, ...event.data);\n });\n\n return;\n }\n }\n }\n\n // Overwrite the Metro terminal logging so we can improve the warnings, symbolicate stacks, and inject extra info.\n logLikeMetro(this.terminal.log.bind(this.terminal), level, mode, ...event.data);\n return;\n }\n }\n return super._log(event);\n }\n\n // Used for testing\n _getElapsedTime(startTime: bigint): bigint {\n return process.hrtime.bigint() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n let localPath: string;\n\n if (\n typeof progress.bundleDetails?.customTransformOptions?.dom === 'string' &&\n progress.bundleDetails.customTransformOptions.dom.includes(path.sep)\n ) {\n // Because we use a generated entry file for DOM components, we need to adjust the logging path so it\n // shows a unique path for each component.\n // Here, we take the relative import path and remove all the starting slashes.\n localPath = progress.bundleDetails.customTransformOptions.dom.replace(/^(\\.?\\.[\\\\/])+/, '');\n } else {\n const inputFile = progress.bundleDetails.entryFile;\n\n localPath = path.isAbsolute(inputFile)\n ? path.relative(this.projectRoot, inputFile)\n : inputFile;\n }\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n\n let time: string = '';\n\n if (startTime != null) {\n const elapsed: bigint = this._getElapsedTime(startTime);\n const micro = Number(elapsed) / 1000;\n const converted = Number(elapsed) / 1e6;\n // If the milliseconds are < 0.5 then it will display as 0, so we display in microseconds.\n if (converted <= 0.5) {\n const tenthFractionOfMicro = ((micro * 10) / 1000).toFixed(0);\n // Format as microseconds to nearest tenth\n time = chalk.cyan.bold(`0.${tenthFractionOfMicro}ms`);\n } else {\n time = chalk.dim(converted.toFixed(0) + 'ms');\n }\n }\n\n // iOS Bundled 150ms\n const plural = progress.totalFileCount === 1 ? '' : 's';\n return (\n color(platform + status) +\n time +\n chalk.reset.dim(` ${localPath} (${progress.totalFileCount} module${plural})`)\n );\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}${path.sep}`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log(chalk.dim('Starting Metro Bundler'));\n }\n\n shouldFilterClientLog(event: { type: 'client_log'; data: unknown[] }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return null;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n } else if (env === 'react-server') {\n return chalk.bold(`RSC(${getPlatformTagForBuildDetails(bundleDetails).trim()})`) + ' ';\n }\n\n if (\n bundleDetails?.customTransformOptions?.dom &&\n typeof bundleDetails?.customTransformOptions?.dom === 'string'\n ) {\n return chalk.bold(`DOM`) + ' ';\n }\n\n return '';\n}\n"],"names":["MetroTerminalReporter","formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","debug","require","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","TerminalReporter","constructor","projectRoot","terminal","_log","event","type","shouldFilterClientLog","level","mode","msg","data","join","includes","parsed","parseErrorStringToObject","maybeSymbolicateAndFormatReactErrorLogAsync","then","res","logLikeMetro","log","bind","catch","e","_getElapsedTime","startTime","process","hrtime","bigint","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","customTransformOptions","dom","path","sep","replace","inputFile","entryFile","isAbsolute","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","elapsed","micro","Number","converted","tenthFractionOfMicro","toFixed","cyan","bold","dim","plural","totalFileCount","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","padStart","transformedFileCount","toString","length","dirname","basename","_logInitializing","port","hasReducedPerformance","isAppRegistryStartupMessage","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","environment","trim"],"mappings":";;;;;;;;;;;IA6BaA,qBAAqB;eAArBA;;IAwMGC,mCAAmC;eAAnCA;;IAwCAC,sBAAsB;eAAtBA;;IAkBAC,cAAc;eAAdA;;;;gEA/RE;;;;;;;gEAED;;;;;;kCAE4B;2BAQT;sBACV;oCAKnB;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,8BAA8B;AACpC,MAAMC,kBAAkB;AACxB,MAAMC,mBAAmB;AAKlB,MAAMR,8BAA8BS,kCAAgB;IACzDC,YACE,AAAOC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,gBAHCD,cAAAA;IAIT;IAEAE,KAAKC,KAA8B,EAAQ;QACzC,OAAQA,MAAMC,IAAI;YAChB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,IACEzF,CAAAA,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,KAC1C,QAAON,kCAAAA,yCAAAA,cAAeK,sBAAsB,qBAArCL,uCAAuCM,GAAG,MAAK,UACtD;QACA,OAAOU,gBAAK,CAACc,IAAI,CAAC,CAAC,GAAG,CAAC,IAAI;IAC7B;IAEA,OAAO;AACT"}
|
|
@@ -20,6 +20,9 @@ _export(exports, {
|
|
|
20
20
|
getErrorOverlayHtmlAsync: function() {
|
|
21
21
|
return getErrorOverlayHtmlAsync;
|
|
22
22
|
},
|
|
23
|
+
getStackAsFormattedLog: function() {
|
|
24
|
+
return getStackAsFormattedLog;
|
|
25
|
+
},
|
|
23
26
|
logMetroError: function() {
|
|
24
27
|
return logMetroError;
|
|
25
28
|
},
|
|
@@ -76,6 +79,7 @@ const _LogBoxLog = require("./log-box/LogBoxLog");
|
|
|
76
79
|
const _formatProjectFilePath = require("./log-box/formatProjectFilePath");
|
|
77
80
|
const _log = require("../../../log");
|
|
78
81
|
const _ansi = require("../../../utils/ansi");
|
|
82
|
+
const _env = require("../../../utils/env");
|
|
79
83
|
const _errors = require("../../../utils/errors");
|
|
80
84
|
const _getStaticRenderFunctions = require("../getStaticRenderFunctions");
|
|
81
85
|
function _interop_require_default(obj) {
|
|
@@ -105,9 +109,18 @@ async function logMetroErrorWithStack(projectRoot, { stack, codeFrame, error })
|
|
|
105
109
|
if (error instanceof _errors.CommandError) {
|
|
106
110
|
return;
|
|
107
111
|
}
|
|
112
|
+
_log.Log.log(getStackAsFormattedLog(projectRoot, {
|
|
113
|
+
stack,
|
|
114
|
+
codeFrame,
|
|
115
|
+
error,
|
|
116
|
+
showCollapsedFrames: true
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
function getStackAsFormattedLog(projectRoot, { stack, codeFrame, error, showCollapsedFrames = _env.env.EXPO_DEBUG }) {
|
|
120
|
+
const logs = [];
|
|
108
121
|
if (codeFrame) {
|
|
109
122
|
var _codeFrame_location;
|
|
110
|
-
const maxWarningLineLength = Math.max(
|
|
123
|
+
const maxWarningLineLength = Math.max(800, process.stdout.columns);
|
|
111
124
|
const lineText = codeFrame.content;
|
|
112
125
|
const isPreviewTooLong = codeFrame.content.split('\n').some((line)=>line.length > maxWarningLineLength);
|
|
113
126
|
const column = (_codeFrame_location = codeFrame.location) == null ? void 0 : _codeFrame_location.column;
|
|
@@ -143,16 +156,10 @@ async function logMetroErrorWithStack(projectRoot, { stack, codeFrame, error })
|
|
|
143
156
|
}
|
|
144
157
|
// If the column property could be found, then use that to fix the cursor location which is often broken in regex.
|
|
145
158
|
cursorLine = (column == null ? '' : fill(column) + _chalk().default.reset('^')).slice(minBounds);
|
|
146
|
-
|
|
147
|
-
formattedPath,
|
|
148
|
-
'',
|
|
149
|
-
previewLine,
|
|
150
|
-
cursorLine,
|
|
151
|
-
_chalk().default.dim('(error truncated)')
|
|
152
|
-
].join('\n'));
|
|
159
|
+
logs.push(formattedPath, '', previewLine, cursorLine, _chalk().default.dim('(error truncated)'));
|
|
153
160
|
}
|
|
154
161
|
} else {
|
|
155
|
-
|
|
162
|
+
logs.push(codeFrame.content);
|
|
156
163
|
}
|
|
157
164
|
}
|
|
158
165
|
if (stack == null ? void 0 : stack.length) {
|
|
@@ -165,6 +172,9 @@ async function logMetroErrorWithStack(projectRoot, { stack, codeFrame, error })
|
|
|
165
172
|
});
|
|
166
173
|
const stackLines = [];
|
|
167
174
|
stackProps.forEach((frame)=>{
|
|
175
|
+
if (frame.collapse && !showCollapsedFrames) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
168
178
|
const position = _terminallink().default.isSupported ? (0, _terminallink().default)(frame.subtitle, frame.subtitle) : frame.subtitle;
|
|
169
179
|
let lineItem = _chalk().default.gray(` ${frame.title} (${position})`);
|
|
170
180
|
if (frame.collapse) {
|
|
@@ -175,16 +185,17 @@ async function logMetroErrorWithStack(projectRoot, { stack, codeFrame, error })
|
|
|
175
185
|
stackLines.push(lineItem);
|
|
176
186
|
}
|
|
177
187
|
});
|
|
178
|
-
|
|
179
|
-
|
|
188
|
+
logs.push('');
|
|
189
|
+
logs.push(_chalk().default.bold`Call Stack`);
|
|
180
190
|
if (!stackLines.length) {
|
|
181
|
-
|
|
191
|
+
logs.push(_chalk().default.gray(' No stack trace available.'));
|
|
182
192
|
} else {
|
|
183
|
-
|
|
193
|
+
logs.push(stackLines.join('\n'));
|
|
184
194
|
}
|
|
185
|
-
} else {
|
|
186
|
-
|
|
195
|
+
} else if (error) {
|
|
196
|
+
logs.push(_chalk().default.gray(` ${error.stack}`));
|
|
187
197
|
}
|
|
198
|
+
return logs.join('\n');
|
|
188
199
|
}
|
|
189
200
|
const IS_METRO_BUNDLE_ERROR_SYMBOL = Symbol('_isMetroBundleError');
|
|
190
201
|
const HAS_LOGGED_SYMBOL = Symbol('_hasLoggedInCLI');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/metroErrorInterface.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport chalk from 'chalk';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\nimport { parse, StackFrame } from 'stacktrace-parser';\nimport terminalLink from 'terminal-link';\n\nimport { LogBoxLog } from './log-box/LogBoxLog';\nimport type { CodeFrame, StackFrame as MetroStackFrame } from './log-box/LogBoxSymbolication';\nimport { getStackFormattedLocation } from './log-box/formatProjectFilePath';\nimport { Log } from '../../../log';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { CommandError, SilentError } from '../../../utils/errors';\nimport { createMetroEndpointAsync } from '../getStaticRenderFunctions';\n\nfunction fill(width: number): string {\n return Array(width).join(' ');\n}\n\nfunction formatPaths(config: { filePath: string | null; line?: number; col?: number }) {\n const filePath = chalk.reset(config.filePath);\n return (\n chalk.dim('(') +\n filePath +\n chalk.dim(`:${[config.line, config.col].filter(Boolean).join(':')})`)\n );\n}\n\nexport async function logMetroErrorWithStack(\n projectRoot: string,\n {\n stack,\n codeFrame,\n error,\n }: {\n stack: MetroStackFrame[];\n codeFrame?: CodeFrame;\n error: Error;\n }\n) {\n if (error instanceof SilentError) {\n return;\n }\n\n // process.stdout.write('\\u001b[0m'); // Reset attributes\n // process.stdout.write('\\u001bc'); // Reset the terminal\n\n Log.log();\n Log.log(chalk.red('Metro error: ') + error.message);\n Log.log();\n\n if (error instanceof CommandError) {\n return;\n }\n\n if (codeFrame) {\n const maxWarningLineLength = Math.max(200, process.stdout.columns);\n\n const lineText = codeFrame.content;\n const isPreviewTooLong = codeFrame.content\n .split('\\n')\n .some((line) => line.length > maxWarningLineLength);\n const column = codeFrame.location?.column;\n // When the preview is too long, we skip reading the file and attempting to apply\n // code coloring, this is because it can get very slow.\n if (isPreviewTooLong) {\n let previewLine = '';\n let cursorLine = '';\n\n const formattedPath = formatPaths({\n filePath: codeFrame.fileName,\n line: codeFrame.location?.row,\n col: codeFrame.location?.column,\n });\n // Create a curtailed preview line like:\n // `...transition:'fade'},k._updatePropsStack=function(){clearImmediate(k._updateImmediate),k._updateImmediate...`\n // If there is no text preview or column number, we can't do anything.\n if (lineText && column != null) {\n const rangeWindow = Math.round(\n Math.max(codeFrame.fileName?.length ?? 0, Math.max(80, process.stdout.columns)) / 2\n );\n let minBounds = Math.max(0, column - rangeWindow);\n const maxBounds = Math.min(minBounds + rangeWindow * 2, lineText.length);\n previewLine = lineText.slice(minBounds, maxBounds);\n\n // If we splice content off the start, then we should append `...`.\n // This is unlikely to happen since we limit the activation size.\n if (minBounds > 0) {\n // Adjust the min bounds so the cursor is aligned after we add the \"...\"\n minBounds -= 3;\n previewLine = chalk.dim('...') + previewLine;\n }\n if (maxBounds < lineText.length) {\n previewLine += chalk.dim('...');\n }\n\n // If the column property could be found, then use that to fix the cursor location which is often broken in regex.\n cursorLine = (column == null ? '' : fill(column) + chalk.reset('^')).slice(minBounds);\n\n Log.log(\n [formattedPath, '', previewLine, cursorLine, chalk.dim('(error truncated)')].join('\\n')\n );\n }\n } else {\n Log.log(codeFrame.content);\n }\n }\n\n if (stack?.length) {\n const stackProps = stack.map((frame) => {\n return {\n title: frame.methodName,\n subtitle: getStackFormattedLocation(projectRoot, frame),\n collapse: frame.collapse,\n };\n });\n\n const stackLines: string[] = [];\n\n stackProps.forEach((frame) => {\n const position = terminalLink.isSupported\n ? terminalLink(frame.subtitle, frame.subtitle)\n : frame.subtitle;\n let lineItem = chalk.gray(` ${frame.title} (${position})`);\n if (frame.collapse) {\n lineItem = chalk.dim(lineItem);\n }\n // Never show the internal module system.\n if (!frame.subtitle.match(/\\/metro-require\\/require\\.js/)) {\n stackLines.push(lineItem);\n }\n });\n\n Log.log();\n Log.log(chalk.bold`Call Stack`);\n if (!stackLines.length) {\n Log.log(chalk.gray(' No stack trace available.'));\n } else {\n Log.log(stackLines.join('\\n'));\n }\n } else {\n Log.log(chalk.gray(` ${error.stack}`));\n }\n}\n\nexport const IS_METRO_BUNDLE_ERROR_SYMBOL = Symbol('_isMetroBundleError');\nconst HAS_LOGGED_SYMBOL = Symbol('_hasLoggedInCLI');\n\nexport async function logMetroError(\n projectRoot: string,\n {\n error,\n }: {\n error: Error & {\n [HAS_LOGGED_SYMBOL]?: boolean;\n };\n }\n) {\n if (error instanceof SilentError || error[HAS_LOGGED_SYMBOL]) {\n return;\n }\n error[HAS_LOGGED_SYMBOL] = true;\n\n const stack = parseErrorStack(projectRoot, error.stack);\n\n const log = new LogBoxLog({\n level: 'static',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack,\n category: 'static',\n componentStack: [],\n });\n\n await new Promise((res) => log.symbolicate('stack', res));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n}\n\nfunction isTransformError(\n error: any\n): error is { type: 'TransformError'; filename: string; lineNumber: number; column: number } {\n return error.type === 'TransformError';\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nfunction logFromError({ error, projectRoot }: { error: Error; projectRoot: string }) {\n // Remap direct Metro Node.js errors to a format that will appear more client-friendly in the logbox UI.\n let stack: MetroStackFrame[] | undefined;\n if (isTransformError(error) && error.filename) {\n // Syntax errors in static rendering.\n stack = [\n {\n file: path.join(projectRoot, error.filename),\n methodName: '<unknown>',\n arguments: [],\n // TODO: Import stack\n lineNumber: error.lineNumber,\n column: error.column,\n },\n ];\n } else if ('originModulePath' in error && typeof error.originModulePath === 'string') {\n // TODO: Use import stack here when the error is resolution based.\n stack = [\n {\n file: error.originModulePath,\n methodName: '<unknown>',\n arguments: [],\n // TODO: Import stack\n lineNumber: 0,\n column: 0,\n },\n ];\n } else {\n stack = parseErrorStack(projectRoot, error.stack);\n }\n\n return new LogBoxLog({\n level: 'static',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack,\n category: 'static',\n componentStack: [],\n });\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nexport async function logMetroErrorAsync({\n error,\n projectRoot,\n}: {\n error: Error;\n projectRoot: string;\n}) {\n const log = logFromError({ projectRoot, error });\n\n await new Promise<void>((res) => log.symbolicate('stack', () => res()));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nexport async function getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot,\n}: {\n error: Error;\n projectRoot: string;\n routerRoot: string;\n}) {\n const log = logFromError({ projectRoot, error });\n\n await new Promise<void>((res) => log.symbolicate('stack', () => res()));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n\n if ('message' in log && 'content' in log.message && typeof log.message.content === 'string') {\n log.message.content = stripAnsi(log.message.content)!;\n }\n\n const logBoxContext = {\n selectedLogIndex: 0,\n isDisabled: false,\n logs: [log],\n };\n const html = `<html><head><style>#root,body,html{height:100%}body{overflow:hidden}#root{display:flex}</style></head><body><div id=\"root\"></div><script id=\"_expo-static-error\" type=\"application/json\">${JSON.stringify(\n logBoxContext\n )}</script></body></html>`;\n\n const errorOverlayEntry = await createMetroEndpointAsync(\n projectRoot,\n // Keep the URL relative\n '',\n resolveFrom(projectRoot, 'expo-router/_error'),\n {\n mode: 'development',\n platform: 'web',\n minify: false,\n optimize: false,\n usedExports: false,\n baseUrl: '',\n routerRoot,\n isExporting: false,\n reactCompiler: false,\n }\n );\n\n const htmlWithJs = html.replace('</body>', `<script src=${errorOverlayEntry}></script></body>`);\n return htmlWithJs;\n}\n\nfunction parseErrorStack(\n projectRoot: string,\n stack?: string\n): (StackFrame & { collapse?: boolean })[] {\n if (stack == null) {\n return [];\n }\n if (Array.isArray(stack)) {\n return stack;\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n\n return parse(stack)\n .map((frame) => {\n // frame.file will mostly look like `http://localhost:8081/index.bundle?platform=web&dev=true&hot=false`\n\n if (frame.file) {\n // SSR will sometimes have absolute paths followed by `.bundle?...`, we need to try and make them relative paths and append a dev server URL.\n if (frame.file.startsWith('/') && frame.file.includes('bundle?') && !canParse(frame.file)) {\n // Malformed stack file from SSR. Attempt to repair.\n frame.file = 'https://localhost:8081/' + path.relative(serverRoot, frame.file);\n }\n }\n\n return {\n ...frame,\n column: frame.column != null ? frame.column - 1 : null,\n };\n })\n .filter((frame) => frame.file && !frame.file.includes('node_modules'));\n}\n\nfunction canParse(url: string): boolean {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["IS_METRO_BUNDLE_ERROR_SYMBOL","getErrorOverlayHtmlAsync","logMetroError","logMetroErrorAsync","logMetroErrorWithStack","fill","width","Array","join","formatPaths","config","filePath","chalk","reset","dim","line","col","filter","Boolean","projectRoot","stack","codeFrame","error","SilentError","Log","log","red","message","CommandError","maxWarningLineLength","Math","max","process","stdout","columns","lineText","content","isPreviewTooLong","split","some","length","column","location","previewLine","cursorLine","formattedPath","fileName","row","rangeWindow","round","minBounds","maxBounds","min","slice","stackProps","map","frame","title","methodName","subtitle","getStackFormattedLocation","collapse","stackLines","forEach","position","terminalLink","isSupported","lineItem","gray","match","push","bold","Symbol","HAS_LOGGED_SYMBOL","parseErrorStack","LogBoxLog","level","substitutions","isComponentError","category","componentStack","Promise","res","symbolicate","symbolicated","isTransformError","type","logFromError","filename","file","path","arguments","lineNumber","originModulePath","routerRoot","stripAnsi","logBoxContext","selectedLogIndex","isDisabled","logs","html","JSON","stringify","errorOverlayEntry","createMetroEndpointAsync","resolveFrom","mode","platform","minify","optimize","usedExports","baseUrl","isExporting","reactCompiler","htmlWithJs","replace","isArray","serverRoot","getMetroServerRoot","parse","startsWith","includes","canParse","relative","url","URL"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAkJYA,4BAA4B;eAA5BA;;IAgHSC,wBAAwB;eAAxBA;;IA7GAC,aAAa;eAAbA;;IA0FAC,kBAAkB;eAAlBA;;IAlNAC,sBAAsB;eAAtBA;;;;yBA5Ba;;;;;;;gEACjB;;;;;;;gEACD;;;;;;;gEACO;;;;;;;yBACU;;;;;;;gEACT;;;;;;2BAEC;uCAEgB;qBACtB;sBACM;wBACgB;0CACD;;;;;;AAEzC,SAASC,KAAKC,KAAa;IACzB,OAAOC,MAAMD,OAAOE,IAAI,CAAC;AAC3B;AAEA,SAASC,YAAYC,MAAgE;IACnF,MAAMC,WAAWC,gBAAK,CAACC,KAAK,CAACH,OAAOC,QAAQ;IAC5C,OACEC,gBAAK,CAACE,GAAG,CAAC,OACVH,WACAC,gBAAK,CAACE,GAAG,CAAC,CAAC,CAAC,EAAE;QAACJ,OAAOK,IAAI;QAAEL,OAAOM,GAAG;KAAC,CAACC,MAAM,CAACC,SAASV,IAAI,CAAC,KAAK,CAAC,CAAC;AAExE;AAEO,eAAeJ,uBACpBe,WAAm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EAAEZ,kBAAkB,iBAAiB,CAAC;IAC9F,OAAOW;AACT;AAEA,SAASxC,gBACPvD,WAAmB,EACnBC,KAAc;IAEd,IAAIA,SAAS,MAAM;QACjB,OAAO,EAAE;IACX;IACA,IAAIb,MAAM6G,OAAO,CAAChG,QAAQ;QACxB,OAAOA;IACT;IAEA,MAAMiG,aAAaC,IAAAA,2BAAkB,EAACnG;IAEtC,OAAOoG,IAAAA,yBAAK,EAACnG,OACVmC,GAAG,CAAC,CAACC;QACJ,wGAAwG;QAExG,IAAIA,MAAMiC,IAAI,EAAE;YACd,6IAA6I;YAC7I,IAAIjC,MAAMiC,IAAI,CAAC+B,UAAU,CAAC,QAAQhE,MAAMiC,IAAI,CAACgC,QAAQ,CAAC,cAAc,CAACC,SAASlE,MAAMiC,IAAI,GAAG;gBACzF,oDAAoD;gBACpDjC,MAAMiC,IAAI,GAAG,4BAA4BC,eAAI,CAACiC,QAAQ,CAACN,YAAY7D,MAAMiC,IAAI;YAC/E;QACF;QAEA,OAAO;YACL,GAAGjC,KAAK;YACRf,QAAQe,MAAMf,MAAM,IAAI,OAAOe,MAAMf,MAAM,GAAG,IAAI;QACpD;IACF,GACCxB,MAAM,CAAC,CAACuC,QAAUA,MAAMiC,IAAI,IAAI,CAACjC,MAAMiC,IAAI,CAACgC,QAAQ,CAAC;AAC1D;AAEA,SAASC,SAASE,GAAW;IAC3B,IAAI;QACF,kCAAkC;QAClC,IAAIC,IAAID;QACR,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/metroErrorInterface.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport chalk from 'chalk';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\nimport { parse, StackFrame } from 'stacktrace-parser';\nimport terminalLink from 'terminal-link';\n\nimport { LogBoxLog } from './log-box/LogBoxLog';\nimport type { CodeFrame, StackFrame as MetroStackFrame } from './log-box/LogBoxSymbolication';\nimport { getStackFormattedLocation } from './log-box/formatProjectFilePath';\nimport { Log } from '../../../log';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { env } from '../../../utils/env';\nimport { CommandError, SilentError } from '../../../utils/errors';\nimport { createMetroEndpointAsync } from '../getStaticRenderFunctions';\n\nfunction fill(width: number): string {\n return Array(width).join(' ');\n}\n\nfunction formatPaths(config: { filePath: string | null; line?: number; col?: number }) {\n const filePath = chalk.reset(config.filePath);\n return (\n chalk.dim('(') +\n filePath +\n chalk.dim(`:${[config.line, config.col].filter(Boolean).join(':')})`)\n );\n}\n\nexport async function logMetroErrorWithStack(\n projectRoot: string,\n {\n stack,\n codeFrame,\n error,\n }: {\n stack: MetroStackFrame[];\n codeFrame?: CodeFrame;\n error: Error;\n }\n) {\n if (error instanceof SilentError) {\n return;\n }\n\n // process.stdout.write('\\u001b[0m'); // Reset attributes\n // process.stdout.write('\\u001bc'); // Reset the terminal\n\n Log.log();\n Log.log(chalk.red('Metro error: ') + error.message);\n Log.log();\n\n if (error instanceof CommandError) {\n return;\n }\n\n Log.log(\n getStackAsFormattedLog(projectRoot, { stack, codeFrame, error, showCollapsedFrames: true })\n );\n}\n\nexport function getStackAsFormattedLog(\n projectRoot: string,\n {\n stack,\n codeFrame,\n error,\n showCollapsedFrames = env.EXPO_DEBUG,\n }: {\n stack: MetroStackFrame[];\n codeFrame?: CodeFrame;\n error?: Error;\n showCollapsedFrames?: boolean;\n }\n): string {\n const logs: string[] = [];\n if (codeFrame) {\n const maxWarningLineLength = Math.max(800, process.stdout.columns);\n\n const lineText = codeFrame.content;\n const isPreviewTooLong = codeFrame.content\n .split('\\n')\n .some((line) => line.length > maxWarningLineLength);\n const column = codeFrame.location?.column;\n // When the preview is too long, we skip reading the file and attempting to apply\n // code coloring, this is because it can get very slow.\n if (isPreviewTooLong) {\n let previewLine = '';\n let cursorLine = '';\n\n const formattedPath = formatPaths({\n filePath: codeFrame.fileName,\n line: codeFrame.location?.row,\n col: codeFrame.location?.column,\n });\n // Create a curtailed preview line like:\n // `...transition:'fade'},k._updatePropsStack=function(){clearImmediate(k._updateImmediate),k._updateImmediate...`\n // If there is no text preview or column number, we can't do anything.\n if (lineText && column != null) {\n const rangeWindow = Math.round(\n Math.max(codeFrame.fileName?.length ?? 0, Math.max(80, process.stdout.columns)) / 2\n );\n let minBounds = Math.max(0, column - rangeWindow);\n const maxBounds = Math.min(minBounds + rangeWindow * 2, lineText.length);\n previewLine = lineText.slice(minBounds, maxBounds);\n\n // If we splice content off the start, then we should append `...`.\n // This is unlikely to happen since we limit the activation size.\n if (minBounds > 0) {\n // Adjust the min bounds so the cursor is aligned after we add the \"...\"\n minBounds -= 3;\n previewLine = chalk.dim('...') + previewLine;\n }\n if (maxBounds < lineText.length) {\n previewLine += chalk.dim('...');\n }\n\n // If the column property could be found, then use that to fix the cursor location which is often broken in regex.\n cursorLine = (column == null ? '' : fill(column) + chalk.reset('^')).slice(minBounds);\n\n logs.push(formattedPath, '', previewLine, cursorLine, chalk.dim('(error truncated)'));\n }\n } else {\n logs.push(codeFrame.content);\n }\n }\n\n if (stack?.length) {\n const stackProps = stack.map((frame) => {\n return {\n title: frame.methodName,\n subtitle: getStackFormattedLocation(projectRoot, frame),\n collapse: frame.collapse,\n };\n });\n\n const stackLines: string[] = [];\n\n stackProps.forEach((frame) => {\n if (frame.collapse && !showCollapsedFrames) {\n return;\n }\n\n const position = terminalLink.isSupported\n ? terminalLink(frame.subtitle, frame.subtitle)\n : frame.subtitle;\n let lineItem = chalk.gray(` ${frame.title} (${position})`);\n\n if (frame.collapse) {\n lineItem = chalk.dim(lineItem);\n }\n // Never show the internal module system.\n if (!frame.subtitle.match(/\\/metro-require\\/require\\.js/)) {\n stackLines.push(lineItem);\n }\n });\n\n logs.push('');\n logs.push(chalk.bold`Call Stack`);\n\n if (!stackLines.length) {\n logs.push(chalk.gray(' No stack trace available.'));\n } else {\n logs.push(stackLines.join('\\n'));\n }\n } else if (error) {\n logs.push(chalk.gray(` ${error.stack}`));\n }\n return logs.join('\\n');\n}\n\nexport const IS_METRO_BUNDLE_ERROR_SYMBOL = Symbol('_isMetroBundleError');\nconst HAS_LOGGED_SYMBOL = Symbol('_hasLoggedInCLI');\n\nexport async function logMetroError(\n projectRoot: string,\n {\n error,\n }: {\n error: Error & {\n [HAS_LOGGED_SYMBOL]?: boolean;\n };\n }\n) {\n if (error instanceof SilentError || error[HAS_LOGGED_SYMBOL]) {\n return;\n }\n error[HAS_LOGGED_SYMBOL] = true;\n\n const stack = parseErrorStack(projectRoot, error.stack);\n\n const log = new LogBoxLog({\n level: 'static',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack,\n category: 'static',\n componentStack: [],\n });\n\n await new Promise((res) => log.symbolicate('stack', res));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n}\n\nfunction isTransformError(\n error: any\n): error is { type: 'TransformError'; filename: string; lineNumber: number; column: number } {\n return error.type === 'TransformError';\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nfunction logFromError({ error, projectRoot }: { error: Error; projectRoot: string }) {\n // Remap direct Metro Node.js errors to a format that will appear more client-friendly in the logbox UI.\n let stack: MetroStackFrame[] | undefined;\n if (isTransformError(error) && error.filename) {\n // Syntax errors in static rendering.\n stack = [\n {\n file: path.join(projectRoot, error.filename),\n methodName: '<unknown>',\n arguments: [],\n // TODO: Import stack\n lineNumber: error.lineNumber,\n column: error.column,\n },\n ];\n } else if ('originModulePath' in error && typeof error.originModulePath === 'string') {\n // TODO: Use import stack here when the error is resolution based.\n stack = [\n {\n file: error.originModulePath,\n methodName: '<unknown>',\n arguments: [],\n // TODO: Import stack\n lineNumber: 0,\n column: 0,\n },\n ];\n } else {\n stack = parseErrorStack(projectRoot, error.stack);\n }\n\n return new LogBoxLog({\n level: 'static',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack,\n category: 'static',\n componentStack: [],\n });\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nexport async function logMetroErrorAsync({\n error,\n projectRoot,\n}: {\n error: Error;\n projectRoot: string;\n}) {\n const log = logFromError({ projectRoot, error });\n\n await new Promise<void>((res) => log.symbolicate('stack', () => res()));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n}\n\n/** @returns the html required to render the static metro error as an SPA. */\nexport async function getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot,\n}: {\n error: Error;\n projectRoot: string;\n routerRoot: string;\n}) {\n const log = logFromError({ projectRoot, error });\n\n await new Promise<void>((res) => log.symbolicate('stack', () => res()));\n\n logMetroErrorWithStack(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n error,\n });\n\n if ('message' in log && 'content' in log.message && typeof log.message.content === 'string') {\n log.message.content = stripAnsi(log.message.content)!;\n }\n\n const logBoxContext = {\n selectedLogIndex: 0,\n isDisabled: false,\n logs: [log],\n };\n const html = `<html><head><style>#root,body,html{height:100%}body{overflow:hidden}#root{display:flex}</style></head><body><div id=\"root\"></div><script id=\"_expo-static-error\" type=\"application/json\">${JSON.stringify(\n logBoxContext\n )}</script></body></html>`;\n\n const errorOverlayEntry = await createMetroEndpointAsync(\n projectRoot,\n // Keep the URL relative\n '',\n resolveFrom(projectRoot, 'expo-router/_error'),\n {\n mode: 'development',\n platform: 'web',\n minify: false,\n optimize: false,\n usedExports: false,\n baseUrl: '',\n routerRoot,\n isExporting: false,\n reactCompiler: false,\n }\n );\n\n const htmlWithJs = html.replace('</body>', `<script src=${errorOverlayEntry}></script></body>`);\n return htmlWithJs;\n}\n\nfunction parseErrorStack(\n projectRoot: string,\n stack?: string\n): (StackFrame & { collapse?: boolean })[] {\n if (stack == null) {\n return [];\n }\n if (Array.isArray(stack)) {\n return stack;\n }\n\n const serverRoot = getMetroServerRoot(projectRoot);\n\n return parse(stack)\n .map((frame) => {\n // frame.file will mostly look like `http://localhost:8081/index.bundle?platform=web&dev=true&hot=false`\n\n if (frame.file) {\n // SSR will sometimes have absolute paths followed by `.bundle?...`, we need to try and make them relative paths and append a dev server URL.\n if (frame.file.startsWith('/') && frame.file.includes('bundle?') && !canParse(frame.file)) {\n // Malformed stack file from SSR. Attempt to repair.\n frame.file = 'https://localhost:8081/' + path.relative(serverRoot, frame.file);\n }\n }\n\n return {\n ...frame,\n column: frame.column != null ? frame.column - 1 : null,\n };\n })\n .filter((frame) => frame.file && !frame.file.includes('node_modules'));\n}\n\nfunction canParse(url: string): boolean {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["IS_METRO_BUNDLE_ERROR_SYMBOL","getErrorOverlayHtmlAsync","getStackAsFormattedLog","logMetroError","logMetroErrorAsync","logMetroErrorWithStack","fill","width","Array","join","formatPaths","config","filePath","chalk","reset","dim","line","col","filter","Boolean","projectRoot","stack","codeFrame","error","SilentError","Log","log","red","message","CommandError","showCollapsedFrames","env","EXPO_DEBUG","logs","maxWarningLineLength","Math","max","process","stdout","columns","lineText","content","isPreviewTooLong","split","some","length","column","location","previewLine","cursorLine","formattedPath","fileName","row","rangeWindow","round","minBounds","maxBounds","min","slice","push","stackProps","map","frame","title","methodName","subtitle","getStackFormattedLocation","collapse","stackLines","forEach","position","terminalLink","isSupported","lineItem","gray","match","bold","Symbol","HAS_LOGGED_SYMBOL","parseErrorStack","LogBoxLog","level","substitutions","isComponentError","category","componentStack","Promise","res","symbolicate","symbolicated","isTransformError","type","logFromError","filename","file","path","arguments","lineNumber","originModulePath","routerRoot","stripAnsi","logBoxContext","selectedLogIndex","isDisabled","html","JSON","stringify","errorOverlayEntry","createMetroEndpointAsync","resolveFrom","mode","platform","minify","optimize","usedExports","baseUrl","isExporting","reactCompiler","htmlWithJs","replace","isArray","serverRoot","getMetroServerRoot","parse","startsWith","includes","canParse","relative","url","URL"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA4KYA,4BAA4B;eAA5BA;;IAgHSC,wBAAwB;eAAxBA;;IA9NNC,sBAAsB;eAAtBA;;IAiHMC,aAAa;eAAbA;;IA0FAC,kBAAkB;eAAlBA;;IA3OAC,sBAAsB;eAAtBA;;;;yBA7Ba;;;;;;;gEACjB;;;;;;;gEACD;;;;;;;gEACO;;;;;;;yBACU;;;;;;;gEACT;;;;;;2BAEC;uCAEgB;qBACtB;sBACM;qBACN;wBACsB;0CACD;;;;;;AAEzC,SAASC,KAAKC,KAAa;IACzB,OAAOC,MAAMD,OAAOE,IAAI,CAAC;AAC3B;AAEA,SAASC,YAAYC,MAAgE;IACnF,MAAMC,WAAWC,gBAAK,CAACC,KAAK,CAACH,OAAOC,QAAQ;IAC5C,OACEC,gBAAK,CAACE,GAAG,CAAC,OACVH,WACAC,gBAAK,CAACE,GAAG,CAAC,CAAC,CAAC,EAAE;QAACJ,OAAOK,IAAI;QAAEL,OAAOM,GAAG;KAAC,CAACC,MAAM,CAACC,SAASV,IAAI,CAAC,KAAK,CAAC,CAAC;AAExE;AAEO,eAAeJ,uBACpBe,WAAmB,EACnB,EACEC,KAAK,EACLC,SAAS,EACTC,KAAK,EAKN;IAED,IAAIA,iBAAiBC,mBAAW,EAAE;QAChC;IACF;IAEA,yDAAyD;IACzD,yDAAyD;IAEzDC,QAAG,CAACC,GAAG;IACPD,QAAG,CAACC,GAAG,CAACb,gBAAK,CAACc,GAAG,CAAC,mBAAmBJ,MAAMK,OAAO;IAClDH,QAAG,CAACC,GAAG;IAEP,IAAIH,iBAAiBM,oBAAY,EAAE;QACjC;IACF;IAEAJ,QAAG,CAACC,GAAG,CACLxB,uBAAuBkB,aAAa;QAAEC;QAAOC;QAAWC;QAAOO,qBAAqB;IAAK;AAE7F;AAEO,SAAS5B,uBACdkB,WAAmB,EACnB,EAC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X;IACA,IAAIb,MAAMgH,OAAO,CAACnG,QAAQ;QACxB,OAAOA;IACT;IAEA,MAAMoG,aAAaC,IAAAA,2BAAkB,EAACtG;IAEtC,OAAOuG,IAAAA,yBAAK,EAACtG,OACVwC,GAAG,CAAC,CAACC;QACJ,wGAAwG;QAExG,IAAIA,MAAMgC,IAAI,EAAE;YACd,6IAA6I;YAC7I,IAAIhC,MAAMgC,IAAI,CAAC8B,UAAU,CAAC,QAAQ9D,MAAMgC,IAAI,CAAC+B,QAAQ,CAAC,cAAc,CAACC,SAAShE,MAAMgC,IAAI,GAAG;gBACzF,oDAAoD;gBACpDhC,MAAMgC,IAAI,GAAG,4BAA4BC,eAAI,CAACgC,QAAQ,CAACN,YAAY3D,MAAMgC,IAAI;YAC/E;QACF;QAEA,OAAO;YACL,GAAGhC,KAAK;YACRhB,QAAQgB,MAAMhB,MAAM,IAAI,OAAOgB,MAAMhB,MAAM,GAAG,IAAI;QACpD;IACF,GACC5B,MAAM,CAAC,CAAC4C,QAAUA,MAAMgC,IAAI,IAAI,CAAChC,MAAMgC,IAAI,CAAC+B,QAAQ,CAAC;AAC1D;AAEA,SAASC,SAASE,GAAW;IAC3B,IAAI;QACF,kCAAkC;QAClC,IAAIC,IAAID;QACR,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
|
@@ -593,6 +593,15 @@ function withExtendedResolver(config, { tsconfig, isTsconfigPathsEnabled, isFast
|
|
|
593
593
|
_path().default.join(require.resolve('@expo/cli/package.json'), '../static/canary-full')
|
|
594
594
|
];
|
|
595
595
|
}
|
|
596
|
+
// HACK:
|
|
597
|
+
if (moduleName.match(/^@react-navigation\//)) {
|
|
598
|
+
// Force to use the ESM versions of react-navigation to prevent Metro behavior where it changes the
|
|
599
|
+
// resolution based on if a module is `import`ing or `require`ing it.
|
|
600
|
+
context.unstable_conditionNames = [
|
|
601
|
+
'import',
|
|
602
|
+
'require'
|
|
603
|
+
];
|
|
604
|
+
}
|
|
596
605
|
if ((0, _metroOptions.isServerEnvironment)((_context_customResolverOptions = context.customResolverOptions) == null ? void 0 : _context_customResolverOptions.environment)) {
|
|
597
606
|
var _context_customResolverOptions1, _context_customResolverOptions2;
|
|
598
607
|
// Adjust nodejs source extensions to sort mjs after js, including platform variants.
|
|
@@ -684,6 +693,8 @@ async function withMetroMultiPlatformAsync(projectRoot, { config, exp, platformB
|
|
|
684
693
|
}
|
|
685
694
|
// @ts-expect-error: watchFolders is readonly
|
|
686
695
|
config.watchFolders.push(_path().default.join(require.resolve('metro-runtime/package.json'), '../..'));
|
|
696
|
+
// @ts-expect-error: watchFolders is readonly
|
|
697
|
+
config.watchFolders.push(_path().default.join(require.resolve('@expo/metro-config/package.json'), '../..'));
|
|
687
698
|
if (isReactCanaryEnabled) {
|
|
688
699
|
// @ts-expect-error: watchFolders is readonly
|
|
689
700
|
config.watchFolders.push(_path().default.join(require.resolve('@expo/cli/package.json'), '..'));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { ExpoConfig, Platform } from '@expo/config';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport Bundler from 'metro/src/Bundler';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { createFastResolver, FailedToResolvePathError } from './createExpoMetroResolver';\nimport { isNodeExternal, shouldCreateVirtualCanary, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { isServerEnvironment } from '../middleware/metroOptions';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nexport type StrictResolver = (moduleName: string) => Resolution;\nexport type StrictResolverFactory = (\n context: ResolutionContext,\n platform: string | null\n) => StrictResolver;\n\nconst ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(\n config: ConfigT,\n {\n getMetroBundler,\n }: {\n getMetroBundler: () => Bundler;\n }\n): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform?: string | null }): readonly string[] => {\n const virtualEnvVarId = `\\0polyfill:environment-variables`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualEnvVarId,\n (() => {\n return `//`;\n })()\n );\n\n const virtualModuleId = `\\0polyfill:external-require`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n (() => {\n if (ctx.platform === 'web') {\n return `global.$$require_external = typeof window === \"undefined\" ? require : () => null;`;\n } else {\n // Wrap in try/catch to support Android.\n return 'try { global.$$require_external = typeof expo === \"undefined\" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';\n }\n })()\n );\n\n if (ctx.platform === 'web') {\n return [\n virtualModuleId,\n virtualEnvVarId,\n // Ensure that the error-guard polyfill is included in the web polyfills to\n // make metro-runtime work correctly.\n // TODO: This module is pretty big for a function that simply re-throws an error that doesn't need to be caught.\n require.resolve('@react-native/js-polyfills/error-guard'),\n ];\n }\n\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n return [...polyfills, virtualModuleId, virtualEnvVarId];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n * - Alias react-native renderer code to a vendored React canary build on native.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\n if (isReactCanaryEnabled) {\n Log.warn(`Experimental React 19 canary is enabled.`);\n }\n if (isFastResolverEnabled) {\n Log.log(chalk.dim`Fast resolver is enabled.`);\n }\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: true,\n blockList: !config.resolver?.blockList\n ? []\n : Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n 'react-native/Libraries/Image/resolveAssetSource': 'expo-asset/build/resolveAssetSource',\n },\n };\n\n let _universalAliases: [RegExp, string][] | null;\n\n function getUniversalAliases() {\n if (_universalAliases) {\n return _universalAliases;\n }\n\n _universalAliases = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n _universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n if (isReactServerComponentsEnabled) {\n if (resolveFrom.silent(config.projectRoot, 'expo-router/rsc')) {\n debug('Enabling bridge alias: expo-router -> expo-router/rsc');\n _universalAliases.push([/^expo-router$/, 'expo-router/rsc']);\n // Bridge the internal entry point which is a standalone import to ensure package.json resolution works as expected.\n _universalAliases.push([/^expo-router\\/entry-classic$/, 'expo-router/rsc/entry']);\n }\n }\n return _universalAliases;\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve =\n isTsconfigPathsEnabled && (tsconfig?.paths || tsconfig?.baseUrl != null)\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const getStrictResolver: StrictResolverFactory = (\n { resolveRequest, ...context },\n platform\n ): StrictResolver => {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n };\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n // TODO: This is a hack to get resolveWeak working.\n const idFactory = (config.serializer?.createModuleIdFactory?.() ??\n ((id: number | string, context: { platform: string; environment?: string }): number | string =>\n id)) as (\n id: number | string,\n context: { platform: string; environment?: string }\n ) => number | string;\n\n const getAssetRegistryModule = () => {\n const virtualModuleId = `\\0polyfill:assets-registry`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n ASSET_REGISTRY_SRC\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n } as const;\n };\n\n // If Node.js pass-through, then remap to a module like `module.exports = $$require_external(<module>)`.\n // If module should be shimmed, remap to an empty module.\n const externals: {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => boolean;\n replace: 'empty' | 'node' | 'weak';\n }[] = [\n {\n match: (context: ResolutionContext, moduleName: string) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for Node.js environments.\n !isServerEnvironment(context.customResolverOptions?.environment)\n ) {\n return false;\n }\n\n if (context.customResolverOptions?.environment === 'react-server') {\n // Ensure these non-react-server modules are excluded when bundling for React Server Components in development.\n return /^(source-map-support(\\/.*)?|@babel\\/runtime\\/.+|debug|metro-runtime\\/src\\/modules\\/HMRClient|metro|acorn-loose|acorn|chalk|ws|ansi-styles|supports-color|color-convert|has-flag|utf-8-validate|color-name|react-refresh\\/runtime|@remix-run\\/node\\/.+)$/.test(\n moduleName\n );\n }\n\n // TODO: Windows doesn't support externals somehow.\n if (process.platform === 'win32') {\n return /^(source-map-support(\\/.*)?)$/.test(moduleName);\n }\n\n // Extern these modules in standard Node.js environments in development to prevent API routes side-effects\n // from leaking into the dev server process.\n return /^(source-map-support(\\/.*)?|react|@radix-ui\\/.+|@babel\\/runtime\\/.+|react-dom(\\/.+)?|debug|acorn-loose|acorn|css-in-js-utils\\/lib\\/.+|hyphenate-style-name|color|color-string|color-convert|color-name|fontfaceobserver|fast-deep-equal|query-string|escape-string-regexp|invariant|postcss-value-parser|memoize-one|nullthrows|strict-uri-encode|decode-uri-component|split-on-first|filter-obj|warn-once|simple-swizzle|is-arrayish|inline-style-prefixer\\/.+)$/.test(\n moduleName\n );\n },\n replace: 'node',\n },\n // Externals to speed up async split chunks by extern-ing common packages that appear in the root client chunk.\n {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for client environments.\n isServerEnvironment(context.customResolverOptions?.environment) ||\n // Only enable for client boundaries\n !context.customResolverOptions.clientboundary\n ) {\n return false;\n }\n\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return false;\n }\n\n const isExternal = // Extern these modules in standard Node.js environments.\n /^(deprecated-react-native-prop-types|react|react\\/jsx-dev-runtime|scheduler|react-native|react-dom(\\/.+)?|metro-runtime(\\/.+)?)$/.test(\n moduleName\n ) ||\n // TODO: Add more\n /^@babel\\/runtime\\/helpers\\/(wrapNativeSuper)$/.test(moduleName);\n\n return isExternal;\n },\n replace: 'weak',\n },\n ];\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // Mock out production react imports in development.\n function requestDevMockProdReact(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // This resolution is dev-only to prevent bundling the production React packages in development.\n if (!context.dev) return null;\n\n if (\n // Match react-native renderers.\n (platform !== 'web' &&\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/]react-native[\\\\/]/) &&\n moduleName.match(/([\\\\/]ReactFabric|ReactNativeRenderer)-prod/)) ||\n // Match react production imports.\n (moduleName.match(/\\.production(\\.min)?\\.js$/) &&\n // Match if the import originated from a react package.\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/](react[-\\\\/]|scheduler[\\\\/])/))\n ) {\n debug(`Skipping production module: ${moduleName}`);\n // /Users/path/to/expo/node_modules/react/index.js ./cjs/react.production.min.js\n // /Users/path/to/expo/node_modules/react/jsx-dev-runtime.js ./cjs/react-jsx-dev-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n // /Users/path/to/expo/node_modules/react-refresh/runtime.js ./cjs/react-refresh-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/scheduler/index.native.js ./cjs/scheduler.native.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n return {\n type: 'empty',\n };\n }\n return null;\n },\n // tsconfig paths\n function requestTsconfigPaths(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n function requestNodeExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n !isServer\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n\n if (!result && platform !== 'web') {\n // Preserve previous behavior where native throws an error on node.js internals.\n return null;\n }\n\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n const contents = `module.exports=$$require_external('node:${moduleId}');`;\n debug(`Virtualizing Node.js \"${moduleId}\"`);\n const virtualModuleId = `\\0node:${moduleId}`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n },\n\n // Custom externals support\n function requestCustomExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return null;\n }\n // Skip applying JS externals for CSS files.\n if (/\\.(s?css|sass)$/.test(context.originModulePath)) {\n return null;\n }\n\n const environment = context.customResolverOptions?.environment;\n\n const strictResolve = getStrictResolver(context, platform);\n\n for (const external of externals) {\n if (external.match(context, moduleName, platform)) {\n if (external.replace === 'empty') {\n debug(`Redirecting external \"${moduleName}\" to \"${external.replace}\"`);\n return {\n type: external.replace,\n };\n } else if (external.replace === 'weak') {\n // TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.\n const realModule = strictResolve(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment,\n });\n\n const contents =\n typeof opaqueId === 'number'\n ? `module.exports=/*${moduleName}*/__r(${opaqueId})`\n : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;\n // const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;\n // const generatedModuleId = fastHashMemoized(contents);\n const virtualModuleId = `\\0weak:${opaqueId}`;\n debug('Virtualizing module:', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else if (external.replace === 'node') {\n const contents = `module.exports=$$require_external('${moduleName}')`;\n const virtualModuleId = `\\0node:${moduleName}`;\n debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else {\n throw new CommandError(\n `Invalid external alias type: \"${external.replace}\" for module \"${moduleName}\" (platform: ${platform}, originModulePath: ${context.originModulePath})`\n );\n }\n }\n }\n return null;\n },\n\n // Basic moduleId aliases\n function requestAlias(context: ResolutionContext, moduleName: string, platform: string | null) {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of getUniversalAliases()) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // Polyfill for asset registry\n function requestStableAssetRegistry(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (/^@react-native\\/assets-registry\\/registry(\\.js)?$/.test(moduleName)) {\n return getAssetRegistryModule();\n }\n\n if (\n platform === 'web' &&\n context.originModulePath.match(/node_modules[\\\\/]react-native-web[\\\\/]/) &&\n moduleName.includes('/modules/AssetRegistry')\n ) {\n return getAssetRegistryModule();\n }\n\n return null;\n },\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n function requestPostRewrites(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // // Disallow importing confusing native modules on web\n if (moduleName.includes('react-native/Libraries/Utilities/codegenNativeCommands')) {\n throw new FailedToResolvePathError(\n `Importing native-only module \"${moduleName}\" on web from: ${context.originModulePath}`\n );\n }\n\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimFile = shouldCreateVirtualShim(normalName);\n if (shimFile) {\n const virtualId = `\\0shim:${normalName}`;\n const bundler = getMetroBundlerWithVirtualModules(getMetroBundler());\n if (!bundler.hasVirtualModule(virtualId)) {\n bundler.setVirtualModule(virtualId, fs.readFileSync(shimFile, 'utf8'));\n }\n debug(`Redirecting module \"${result.filePath}\" to shim`);\n\n return {\n ...result,\n filePath: virtualId,\n };\n }\n }\n } else {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n // react-native/Libraries/Core/InitializeCore\n const normal = normalizeSlashes(result.filePath);\n\n // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n if (normal.endsWith('react-native/Libraries/Core/InitializeCore.js')) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return {\n type: 'empty',\n };\n }\n }\n\n // When server components are enabled, redirect React Native's renderer to the canary build\n // this will enable the use hook and other requisite features from React 19.\n if (isReactCanaryEnabled && result.filePath.includes('node_modules')) {\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const canaryFile = shouldCreateVirtualCanary(normalName);\n if (canaryFile) {\n debug(`Redirecting React Native module \"${result.filePath}\" to canary build`);\n return {\n ...result,\n filePath: canaryFile,\n };\n }\n }\n }\n\n return result;\n },\n\n // If at this point, we haven't resolved a module yet, if it's a module specifier for a known dependency\n // of either `expo` or `expo-router`, attempt to resolve it from these origin modules instead\n createFallbackModuleResolver({\n originModuleNames: ['expo', 'expo-router'],\n getStrictResolver,\n }),\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context: Mutable<CustomResolutionContext> = {\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n };\n\n // TODO: Remove this when we have React 19 in the expo/expo monorepo.\n if (\n isReactCanaryEnabled &&\n // Change the node modules path for react and react-dom to use the vendor in Expo CLI.\n /^(react|react\\/.*|react-dom|react-dom\\/.*)$/.test(moduleName)\n ) {\n context.nodeModulesPaths = [\n path.join(require.resolve('@expo/cli/package.json'), '../static/canary-full'),\n ];\n }\n\n if (isServerEnvironment(context.customResolverOptions?.environment)) {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionsByPlatform = {};\n\n const isReactServerComponents =\n context.customResolverOptions?.environment === 'react-server';\n\n if (isReactServerComponents) {\n // NOTE: Align the behavior across server and client. This is a breaking change so we'll just roll it out with React Server Components.\n // This ensures that react-server and client code both resolve `module` and `main` in the same order.\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['module', 'main'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'module', 'main'];\n }\n } else {\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'main', 'module'];\n }\n }\n\n // Enable react-server import conditions.\n if (context.customResolverOptions?.environment === 'react-server') {\n context.unstable_conditionNames = ['node', 'react-server', 'workerd'];\n } else {\n context.unstable_conditionNames = ['node'];\n }\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n return context;\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isNamedRequiresEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled: boolean;\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isNamedRequiresEnabled) {\n debug('Using Expo metro require runtime.');\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n require('metro-config/src/defaults/defaults').moduleSystem = require.resolve(\n '@expo/cli/build/metro-require/require'\n );\n }\n\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n if (isReactCanaryEnabled) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('@expo/cli/package.json'), '..'));\n }\n }\n\n // TODO: Remove this\n // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.\n config.transformer._expoRouterPath = resolveFrom.silent(projectRoot, 'expo-router');\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n return withExtendedResolver(config, {\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n });\n}\n\nfunction isDirectoryIn(targetPath: string, rootPath: string) {\n return targetPath.startsWith(rootPath) && targetPath.length >= rootPath.length;\n}\n"],"names":["getNodejsExtensions","shouldAliasModule","withExtendedResolver","withMetroMultiPlatformAsync","ASSET_REGISTRY_SRC","debug","require","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","resolve","polyfills","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","isReactCanaryEnabled","isReactServerComponentsEnabled","Log","warn","log","chalk","dim","defaultResolver","metroResolver","resolver","createFastResolver","preserveSymlinks","blockList","Array","isArray","aliases","web","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","getAssetRegistryModule","type","filePath","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","strictResolve","external","realModule","realPath","opaqueId","JSON","stringify","CommandError","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableAssetRegistry","includes","requestPostRewrites","FailedToResolvePathError","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","normal","canaryFile","shouldCreateVirtualCanary","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","nodeModulesPaths","path","join","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","input","output","exp","platformBundlers","isNamedRequiresEnabled","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterPath","expoConfigPlatforms","entries","platforms","map","Set","concat","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA6GeA,mBAAmB;eAAnBA;;IAkpBAC,iBAAiB;eAAjBA;;IA5nBAC,oBAAoB;eAApBA;;IA4oBMC,2BAA2B;eAA3BA;;;;gEA7wBJ;;;;;;;gEACH;;;;;;;iEAIgB;;;;;;;gEACd;;;;;;;gEACO;;;;;;4CAEqB;yCACgB;2BACsB;6BACZ;qCACrB;oCAK3C;qBACa;8BACS;qBACT;wBACS;sBACI;6BACH;mCACwB;0CACb;8BACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWpC,MAAMC,qBAA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W2B,iBAAAA,IAAIY,SAAS,qBAAbZ,eAAelC,QAAQ,CAACtH;OAEzEqK,GAAG,CAAC,CAAC,CAACrK,SAAS,GAAKA;IAEvB,IAAIkC,MAAMC,OAAO,CAAC9C,OAAOyC,QAAQ,CAACsI,SAAS,GAAG;QAC5CF,sBAAsB;eAAI,IAAII,IAAIJ,oBAAoBK,MAAM,CAAClL,OAAOyC,QAAQ,CAACsI,SAAS;SAAG;IAC3F;IAEA,yCAAyC;IACzC/K,OAAOyC,QAAQ,CAACsI,SAAS,GAAGF;IAE5B7K,SAASD,iBAAiBC,QAAQ;QAAEC;IAAgB;IAEpD,OAAOP,qBAAqBM,QAAQ;QAClC4B;QACAG;QACAF;QACAC;QACAE;QACAC;QACAhC;IACF;AACF;AAEA,SAASuK,cAAcW,UAAkB,EAAEC,QAAgB;IACzD,OAAOD,WAAWE,UAAU,CAACD,aAAaD,WAAW7G,MAAM,IAAI8G,SAAS9G,MAAM;AAChF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/withMetroMultiPlatform.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { ExpoConfig, Platform } from '@expo/config';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport Bundler from 'metro/src/Bundler';\nimport { ConfigT } from 'metro-config';\nimport { Resolution, ResolutionContext, CustomResolutionContext } from 'metro-resolver';\nimport * as metroResolver from 'metro-resolver';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { createFallbackModuleResolver } from './createExpoFallbackResolver';\nimport { createFastResolver, FailedToResolvePathError } from './createExpoMetroResolver';\nimport { isNodeExternal, shouldCreateVirtualCanary, shouldCreateVirtualShim } from './externals';\nimport { isFailedToResolveNameError, isFailedToResolvePathError } from './metroErrors';\nimport { getMetroBundlerWithVirtualModules } from './metroVirtualModules';\nimport {\n withMetroErrorReportingResolver,\n withMetroMutatedResolverContext,\n withMetroResolvers,\n} from './withMetroResolvers';\nimport { Log } from '../../../log';\nimport { FileNotifier } from '../../../utils/FileNotifier';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { loadTsConfigPathsAsync, TsConfigPaths } from '../../../utils/tsconfig/loadTsConfigPaths';\nimport { resolveWithTsConfigPaths } from '../../../utils/tsconfig/resolveWithTsConfigPaths';\nimport { isServerEnvironment } from '../middleware/metroOptions';\nimport { PlatformBundlers } from '../platformBundlers';\n\ntype Mutable<T> = { -readonly [K in keyof T]: T[K] };\n\nexport type StrictResolver = (moduleName: string) => Resolution;\nexport type StrictResolverFactory = (\n context: ResolutionContext,\n platform: string | null\n) => StrictResolver;\n\nconst ASSET_REGISTRY_SRC = `const assets=[];module.exports={registerAsset:s=>assets.push(s),getAssetByID:s=>assets[s-1]};`;\n\nconst debug = require('debug')('expo:start:server:metro:multi-platform') as typeof console.log;\n\nfunction withWebPolyfills(\n config: ConfigT,\n {\n getMetroBundler,\n }: {\n getMetroBundler: () => Bundler;\n }\n): ConfigT {\n const originalGetPolyfills = config.serializer.getPolyfills\n ? config.serializer.getPolyfills.bind(config.serializer)\n : () => [];\n\n const getPolyfills = (ctx: { platform?: string | null }): readonly string[] => {\n const virtualEnvVarId = `\\0polyfill:environment-variables`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualEnvVarId,\n (() => {\n return `//`;\n })()\n );\n\n const virtualModuleId = `\\0polyfill:external-require`;\n\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n (() => {\n if (ctx.platform === 'web') {\n return `global.$$require_external = typeof window === \"undefined\" ? require : () => null;`;\n } else {\n // Wrap in try/catch to support Android.\n return 'try { global.$$require_external = typeof expo === \"undefined\" ? require : (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} } catch { global.$$require_external = (moduleId) => { throw new Error(`Node.js standard library module ${moduleId} is not available in this JavaScript environment`);} }';\n }\n })()\n );\n\n if (ctx.platform === 'web') {\n return [\n virtualModuleId,\n virtualEnvVarId,\n // Ensure that the error-guard polyfill is included in the web polyfills to\n // make metro-runtime work correctly.\n // TODO: This module is pretty big for a function that simply re-throws an error that doesn't need to be caught.\n require.resolve('@react-native/js-polyfills/error-guard'),\n ];\n }\n\n // Generally uses `rn-get-polyfills`\n const polyfills = originalGetPolyfills(ctx);\n return [...polyfills, virtualModuleId, virtualEnvVarId];\n };\n\n return {\n ...config,\n serializer: {\n ...config.serializer,\n getPolyfills,\n },\n };\n}\n\nfunction normalizeSlashes(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nexport function getNodejsExtensions(srcExts: readonly string[]): string[] {\n const mjsExts = srcExts.filter((ext) => /mjs$/.test(ext));\n const nodejsSourceExtensions = srcExts.filter((ext) => !/mjs$/.test(ext));\n // find index of last `*.js` extension\n const jsIndex = nodejsSourceExtensions.reduce((index, ext, i) => {\n return /jsx?$/.test(ext) ? i : index;\n }, -1);\n\n // insert `*.mjs` extensions after `*.js` extensions\n nodejsSourceExtensions.splice(jsIndex + 1, 0, ...mjsExts);\n\n return nodejsSourceExtensions;\n}\n\n/**\n * Apply custom resolvers to do the following:\n * - Disable `.native.js` extensions on web.\n * - Alias `react-native` to `react-native-web` on web.\n * - Redirect `react-native-web/dist/modules/AssetRegistry/index.js` to `@react-native/assets/registry.js` on web.\n * - Add support for `tsconfig.json`/`jsconfig.json` aliases via `compilerOptions.paths`.\n * - Alias react-native renderer code to a vendored React canary build on native.\n */\nexport function withExtendedResolver(\n config: ConfigT,\n {\n tsconfig,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n isTsconfigPathsEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled?: boolean;\n isReactServerComponentsEnabled?: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isReactServerComponentsEnabled) {\n Log.warn(`React Server Components (beta) is enabled.`);\n }\n if (isReactCanaryEnabled) {\n Log.warn(`Experimental React 19 canary is enabled.`);\n }\n if (isFastResolverEnabled) {\n Log.log(chalk.dim`Fast resolver is enabled.`);\n }\n\n const defaultResolver = metroResolver.resolve;\n const resolver = isFastResolverEnabled\n ? createFastResolver({\n preserveSymlinks: true,\n blockList: !config.resolver?.blockList\n ? []\n : Array.isArray(config.resolver?.blockList)\n ? config.resolver?.blockList\n : [config.resolver?.blockList],\n })\n : defaultResolver;\n\n const aliases: { [key: string]: Record<string, string> } = {\n web: {\n 'react-native': 'react-native-web',\n 'react-native/index': 'react-native-web',\n 'react-native/Libraries/Image/resolveAssetSource': 'expo-asset/build/resolveAssetSource',\n },\n };\n\n let _universalAliases: [RegExp, string][] | null;\n\n function getUniversalAliases() {\n if (_universalAliases) {\n return _universalAliases;\n }\n\n _universalAliases = [];\n\n // This package is currently always installed as it is included in the `expo` package.\n if (resolveFrom.silent(config.projectRoot, '@expo/vector-icons')) {\n debug('Enabling alias: react-native-vector-icons -> @expo/vector-icons');\n _universalAliases.push([/^react-native-vector-icons(\\/.*)?/, '@expo/vector-icons$1']);\n }\n if (isReactServerComponentsEnabled) {\n if (resolveFrom.silent(config.projectRoot, 'expo-router/rsc')) {\n debug('Enabling bridge alias: expo-router -> expo-router/rsc');\n _universalAliases.push([/^expo-router$/, 'expo-router/rsc']);\n // Bridge the internal entry point which is a standalone import to ensure package.json resolution works as expected.\n _universalAliases.push([/^expo-router\\/entry-classic$/, 'expo-router/rsc/entry']);\n }\n }\n return _universalAliases;\n }\n\n const preferredMainFields: { [key: string]: string[] } = {\n // Defaults from Expo Webpack. Most packages using `react-native` don't support web\n // in the `react-native` field, so we should prefer the `browser` field.\n // https://github.com/expo/router/issues/37\n web: ['browser', 'module', 'main'],\n };\n\n let tsConfigResolve =\n isTsconfigPathsEnabled && (tsconfig?.paths || tsconfig?.baseUrl != null)\n ? resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsconfig.paths ?? {},\n baseUrl: tsconfig.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsconfig.baseUrl,\n })\n : null;\n\n // TODO: Move this to be a transform key for invalidation.\n if (!isExporting && isInteractive()) {\n if (isTsconfigPathsEnabled) {\n // TODO: We should track all the files that used imports and invalidate them\n // currently the user will need to save all the files that use imports to\n // use the new aliases.\n const configWatcher = new FileNotifier(config.projectRoot, [\n './tsconfig.json',\n './jsconfig.json',\n ]);\n configWatcher.startObserving(() => {\n debug('Reloading tsconfig.json');\n loadTsConfigPathsAsync(config.projectRoot).then((tsConfigPaths) => {\n if (tsConfigPaths?.paths && !!Object.keys(tsConfigPaths.paths).length) {\n debug('Enabling tsconfig.json paths support');\n tsConfigResolve = resolveWithTsConfigPaths.bind(resolveWithTsConfigPaths, {\n paths: tsConfigPaths.paths ?? {},\n baseUrl: tsConfigPaths.baseUrl ?? config.projectRoot,\n hasBaseUrl: !!tsConfigPaths.baseUrl,\n });\n } else {\n debug('Disabling tsconfig.json paths support');\n tsConfigResolve = null;\n }\n });\n });\n\n // TODO: This probably prevents the process from exiting.\n installExitHooks(() => {\n configWatcher.stopObserving();\n });\n } else {\n debug('Skipping tsconfig.json paths support');\n }\n }\n\n let nodejsSourceExtensions: string[] | null = null;\n\n const getStrictResolver: StrictResolverFactory = (\n { resolveRequest, ...context },\n platform\n ): StrictResolver => {\n return function doResolve(moduleName: string): Resolution {\n return resolver(context, moduleName, platform);\n };\n };\n\n function getOptionalResolver(context: ResolutionContext, platform: string | null) {\n const doResolve = getStrictResolver(context, platform);\n return function optionalResolve(moduleName: string): Resolution | null {\n try {\n return doResolve(moduleName);\n } catch (error) {\n // If the error is directly related to a resolver not being able to resolve a module, then\n // we can ignore the error and try the next resolver. Otherwise, we should throw the error.\n const isResolutionError =\n isFailedToResolveNameError(error) || isFailedToResolvePathError(error);\n if (!isResolutionError) {\n throw error;\n }\n }\n return null;\n };\n }\n\n // TODO: This is a hack to get resolveWeak working.\n const idFactory = (config.serializer?.createModuleIdFactory?.() ??\n ((id: number | string, context: { platform: string; environment?: string }): number | string =>\n id)) as (\n id: number | string,\n context: { platform: string; environment?: string }\n ) => number | string;\n\n const getAssetRegistryModule = () => {\n const virtualModuleId = `\\0polyfill:assets-registry`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n ASSET_REGISTRY_SRC\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n } as const;\n };\n\n // If Node.js pass-through, then remap to a module like `module.exports = $$require_external(<module>)`.\n // If module should be shimmed, remap to an empty module.\n const externals: {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => boolean;\n replace: 'empty' | 'node' | 'weak';\n }[] = [\n {\n match: (context: ResolutionContext, moduleName: string) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for Node.js environments.\n !isServerEnvironment(context.customResolverOptions?.environment)\n ) {\n return false;\n }\n\n if (context.customResolverOptions?.environment === 'react-server') {\n // Ensure these non-react-server modules are excluded when bundling for React Server Components in development.\n return /^(source-map-support(\\/.*)?|@babel\\/runtime\\/.+|debug|metro-runtime\\/src\\/modules\\/HMRClient|metro|acorn-loose|acorn|chalk|ws|ansi-styles|supports-color|color-convert|has-flag|utf-8-validate|color-name|react-refresh\\/runtime|@remix-run\\/node\\/.+)$/.test(\n moduleName\n );\n }\n\n // TODO: Windows doesn't support externals somehow.\n if (process.platform === 'win32') {\n return /^(source-map-support(\\/.*)?)$/.test(moduleName);\n }\n\n // Extern these modules in standard Node.js environments in development to prevent API routes side-effects\n // from leaking into the dev server process.\n return /^(source-map-support(\\/.*)?|react|@radix-ui\\/.+|@babel\\/runtime\\/.+|react-dom(\\/.+)?|debug|acorn-loose|acorn|css-in-js-utils\\/lib\\/.+|hyphenate-style-name|color|color-string|color-convert|color-name|fontfaceobserver|fast-deep-equal|query-string|escape-string-regexp|invariant|postcss-value-parser|memoize-one|nullthrows|strict-uri-encode|decode-uri-component|split-on-first|filter-obj|warn-once|simple-swizzle|is-arrayish|inline-style-prefixer\\/.+)$/.test(\n moduleName\n );\n },\n replace: 'node',\n },\n // Externals to speed up async split chunks by extern-ing common packages that appear in the root client chunk.\n {\n match: (context: ResolutionContext, moduleName: string, platform: string | null) => {\n if (\n // Disable internal externals when exporting for production.\n context.customResolverOptions.exporting ||\n // These externals are only for client environments.\n isServerEnvironment(context.customResolverOptions?.environment) ||\n // Only enable for client boundaries\n !context.customResolverOptions.clientboundary\n ) {\n return false;\n }\n\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return false;\n }\n\n const isExternal = // Extern these modules in standard Node.js environments.\n /^(deprecated-react-native-prop-types|react|react\\/jsx-dev-runtime|scheduler|react-native|react-dom(\\/.+)?|metro-runtime(\\/.+)?)$/.test(\n moduleName\n ) ||\n // TODO: Add more\n /^@babel\\/runtime\\/helpers\\/(wrapNativeSuper)$/.test(moduleName);\n\n return isExternal;\n },\n replace: 'weak',\n },\n ];\n\n const metroConfigWithCustomResolver = withMetroResolvers(config, [\n // Mock out production react imports in development.\n function requestDevMockProdReact(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // This resolution is dev-only to prevent bundling the production React packages in development.\n if (!context.dev) return null;\n\n if (\n // Match react-native renderers.\n (platform !== 'web' &&\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/]react-native[\\\\/]/) &&\n moduleName.match(/([\\\\/]ReactFabric|ReactNativeRenderer)-prod/)) ||\n // Match react production imports.\n (moduleName.match(/\\.production(\\.min)?\\.js$/) &&\n // Match if the import originated from a react package.\n context.originModulePath.match(/[\\\\/]node_modules[\\\\/](react[-\\\\/]|scheduler[\\\\/])/))\n ) {\n debug(`Skipping production module: ${moduleName}`);\n // /Users/path/to/expo/node_modules/react/index.js ./cjs/react.production.min.js\n // /Users/path/to/expo/node_modules/react/jsx-dev-runtime.js ./cjs/react-jsx-dev-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n // /Users/path/to/expo/node_modules/react-refresh/runtime.js ./cjs/react-refresh-runtime.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/scheduler/index.native.js ./cjs/scheduler.native.production.min.js\n // /Users/path/to/expo/node_modules/react-native/node_modules/react-is/index.js ./cjs/react-is.production.min.js\n return {\n type: 'empty',\n };\n }\n return null;\n },\n // tsconfig paths\n function requestTsconfigPaths(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n return (\n tsConfigResolve?.(\n {\n originModulePath: context.originModulePath,\n moduleName,\n },\n getOptionalResolver(context, platform)\n ) ?? null\n );\n },\n\n // Node.js externals support\n function requestNodeExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n const moduleId = isNodeExternal(moduleName);\n if (!moduleId) {\n return null;\n }\n\n if (\n // In browser runtimes, we want to either resolve a local node module by the same name, or shim the module to\n // prevent crashing when Node.js built-ins are imported.\n !isServer\n ) {\n // Perform optional resolve first. If the module doesn't exist (no module in the node_modules)\n // then we can mock the file to use an empty module.\n const result = getOptionalResolver(context, platform)(moduleName);\n\n if (!result && platform !== 'web') {\n // Preserve previous behavior where native throws an error on node.js internals.\n return null;\n }\n\n return (\n result ?? {\n // In this case, mock the file to use an empty module.\n type: 'empty',\n }\n );\n }\n const contents = `module.exports=$$require_external('node:${moduleId}');`;\n debug(`Virtualizing Node.js \"${moduleId}\"`);\n const virtualModuleId = `\\0node:${moduleId}`;\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n },\n\n // Custom externals support\n function requestCustomExternals(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n // We don't support this in the resolver at the moment.\n if (moduleName.endsWith('/package.json')) {\n return null;\n }\n // Skip applying JS externals for CSS files.\n if (/\\.(s?css|sass)$/.test(context.originModulePath)) {\n return null;\n }\n\n const environment = context.customResolverOptions?.environment;\n\n const strictResolve = getStrictResolver(context, platform);\n\n for (const external of externals) {\n if (external.match(context, moduleName, platform)) {\n if (external.replace === 'empty') {\n debug(`Redirecting external \"${moduleName}\" to \"${external.replace}\"`);\n return {\n type: external.replace,\n };\n } else if (external.replace === 'weak') {\n // TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.\n const realModule = strictResolve(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment,\n });\n\n const contents =\n typeof opaqueId === 'number'\n ? `module.exports=/*${moduleName}*/__r(${opaqueId})`\n : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;\n // const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;\n // const generatedModuleId = fastHashMemoized(contents);\n const virtualModuleId = `\\0weak:${opaqueId}`;\n debug('Virtualizing module:', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else if (external.replace === 'node') {\n const contents = `module.exports=$$require_external('${moduleName}')`;\n const virtualModuleId = `\\0node:${moduleName}`;\n debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);\n getMetroBundlerWithVirtualModules(getMetroBundler()).setVirtualModule(\n virtualModuleId,\n contents\n );\n return {\n type: 'sourceFile',\n filePath: virtualModuleId,\n };\n } else {\n throw new CommandError(\n `Invalid external alias type: \"${external.replace}\" for module \"${moduleName}\" (platform: ${platform}, originModulePath: ${context.originModulePath})`\n );\n }\n }\n }\n return null;\n },\n\n // Basic moduleId aliases\n function requestAlias(context: ResolutionContext, moduleName: string, platform: string | null) {\n // Conditionally remap `react-native` to `react-native-web` on web in\n // a way that doesn't require Babel to resolve the alias.\n if (platform && platform in aliases && aliases[platform][moduleName]) {\n const redirectedModuleName = aliases[platform][moduleName];\n return getStrictResolver(context, platform)(redirectedModuleName);\n }\n\n for (const [matcher, alias] of getUniversalAliases()) {\n const match = moduleName.match(matcher);\n if (match) {\n const aliasedModule = alias.replace(\n /\\$(\\d+)/g,\n (_, index) => match[parseInt(index, 10)] ?? ''\n );\n const doResolve = getStrictResolver(context, platform);\n debug(`Alias \"${moduleName}\" to \"${aliasedModule}\"`);\n return doResolve(aliasedModule);\n }\n }\n\n return null;\n },\n\n // Polyfill for asset registry\n function requestStableAssetRegistry(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n if (/^@react-native\\/assets-registry\\/registry(\\.js)?$/.test(moduleName)) {\n return getAssetRegistryModule();\n }\n\n if (\n platform === 'web' &&\n context.originModulePath.match(/node_modules[\\\\/]react-native-web[\\\\/]/) &&\n moduleName.includes('/modules/AssetRegistry')\n ) {\n return getAssetRegistryModule();\n }\n\n return null;\n },\n\n // TODO: Reduce these as much as possible in the future.\n // Complex post-resolution rewrites.\n function requestPostRewrites(\n context: ResolutionContext,\n moduleName: string,\n platform: string | null\n ) {\n const doResolve = getStrictResolver(context, platform);\n\n const result = doResolve(moduleName);\n\n if (result.type !== 'sourceFile') {\n return result;\n }\n\n if (platform === 'web') {\n if (result.filePath.includes('node_modules')) {\n // // Disallow importing confusing native modules on web\n if (moduleName.includes('react-native/Libraries/Utilities/codegenNativeCommands')) {\n throw new FailedToResolvePathError(\n `Importing native-only module \"${moduleName}\" on web from: ${context.originModulePath}`\n );\n }\n\n // Replace with static shims\n\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const shimFile = shouldCreateVirtualShim(normalName);\n if (shimFile) {\n const virtualId = `\\0shim:${normalName}`;\n const bundler = getMetroBundlerWithVirtualModules(getMetroBundler());\n if (!bundler.hasVirtualModule(virtualId)) {\n bundler.setVirtualModule(virtualId, fs.readFileSync(shimFile, 'utf8'));\n }\n debug(`Redirecting module \"${result.filePath}\" to shim`);\n\n return {\n ...result,\n filePath: virtualId,\n };\n }\n }\n } else {\n const isServer =\n context.customResolverOptions?.environment === 'node' ||\n context.customResolverOptions?.environment === 'react-server';\n\n // react-native/Libraries/Core/InitializeCore\n const normal = normalizeSlashes(result.filePath);\n\n // Shim out React Native native runtime globals in server mode for native.\n if (isServer) {\n if (normal.endsWith('react-native/Libraries/Core/InitializeCore.js')) {\n debug('Shimming out InitializeCore for React Native in native SSR bundle');\n return {\n type: 'empty',\n };\n }\n }\n\n // When server components are enabled, redirect React Native's renderer to the canary build\n // this will enable the use hook and other requisite features from React 19.\n if (isReactCanaryEnabled && result.filePath.includes('node_modules')) {\n const normalName = normalizeSlashes(result.filePath)\n // Drop everything up until the `node_modules` folder.\n .replace(/.*node_modules\\//, '');\n\n const canaryFile = shouldCreateVirtualCanary(normalName);\n if (canaryFile) {\n debug(`Redirecting React Native module \"${result.filePath}\" to canary build`);\n return {\n ...result,\n filePath: canaryFile,\n };\n }\n }\n }\n\n return result;\n },\n\n // If at this point, we haven't resolved a module yet, if it's a module specifier for a known dependency\n // of either `expo` or `expo-router`, attempt to resolve it from these origin modules instead\n createFallbackModuleResolver({\n originModuleNames: ['expo', 'expo-router'],\n getStrictResolver,\n }),\n ]);\n\n // Ensure we mutate the resolution context to include the custom resolver options for server and web.\n const metroConfigWithCustomContext = withMetroMutatedResolverContext(\n metroConfigWithCustomResolver,\n (\n immutableContext: CustomResolutionContext,\n moduleName: string,\n platform: string | null\n ): CustomResolutionContext => {\n const context: Mutable<CustomResolutionContext> = {\n ...immutableContext,\n preferNativePlatform: platform !== 'web',\n };\n\n // TODO: Remove this when we have React 19 in the expo/expo monorepo.\n if (\n isReactCanaryEnabled &&\n // Change the node modules path for react and react-dom to use the vendor in Expo CLI.\n /^(react|react\\/.*|react-dom|react-dom\\/.*)$/.test(moduleName)\n ) {\n context.nodeModulesPaths = [\n path.join(require.resolve('@expo/cli/package.json'), '../static/canary-full'),\n ];\n }\n\n // HACK:\n if (moduleName.match(/^@react-navigation\\//)) {\n // Force to use the ESM versions of react-navigation to prevent Metro behavior where it changes the\n // resolution based on if a module is `import`ing or `require`ing it.\n context.unstable_conditionNames = ['import', 'require'];\n }\n\n if (isServerEnvironment(context.customResolverOptions?.environment)) {\n // Adjust nodejs source extensions to sort mjs after js, including platform variants.\n if (nodejsSourceExtensions === null) {\n nodejsSourceExtensions = getNodejsExtensions(context.sourceExts);\n }\n context.sourceExts = nodejsSourceExtensions;\n\n context.unstable_enablePackageExports = true;\n context.unstable_conditionsByPlatform = {};\n\n const isReactServerComponents =\n context.customResolverOptions?.environment === 'react-server';\n\n if (isReactServerComponents) {\n // NOTE: Align the behavior across server and client. This is a breaking change so we'll just roll it out with React Server Components.\n // This ensures that react-server and client code both resolve `module` and `main` in the same order.\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['module', 'main'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'module', 'main'];\n }\n } else {\n if (platform === 'web') {\n // Node.js runtimes should only be importing main at the moment.\n // This is a temporary fix until we can support the package.json exports.\n context.mainFields = ['main', 'module'];\n } else {\n // In Node.js + native, use the standard main fields.\n context.mainFields = ['react-native', 'main', 'module'];\n }\n }\n\n // Enable react-server import conditions.\n if (context.customResolverOptions?.environment === 'react-server') {\n context.unstable_conditionNames = ['node', 'react-server', 'workerd'];\n } else {\n context.unstable_conditionNames = ['node'];\n }\n } else {\n // Non-server changes\n\n if (!env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE && platform && platform in preferredMainFields) {\n context.mainFields = preferredMainFields[platform];\n }\n }\n\n return context;\n }\n );\n\n return withMetroErrorReportingResolver(metroConfigWithCustomContext);\n}\n\n/** @returns `true` if the incoming resolution should be swapped. */\nexport function shouldAliasModule(\n input: {\n platform: string | null;\n result: Resolution;\n },\n alias: { platform: string; output: string }\n): boolean {\n return (\n input.platform === alias.platform &&\n input.result?.type === 'sourceFile' &&\n typeof input.result?.filePath === 'string' &&\n normalizeSlashes(input.result.filePath).endsWith(alias.output)\n );\n}\n\n/** Add support for `react-native-web` and the Web platform. */\nexport async function withMetroMultiPlatformAsync(\n projectRoot: string,\n {\n config,\n exp,\n platformBundlers,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isNamedRequiresEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled: boolean;\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n if (isNamedRequiresEnabled) {\n debug('Using Expo metro require runtime.');\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n require('metro-config/src/defaults/defaults').moduleSystem = require.resolve(\n '@expo/cli/build/metro-require/require'\n );\n }\n\n if (!config.projectRoot) {\n // @ts-expect-error: read-only types\n config.projectRoot = projectRoot;\n }\n\n // Required for @expo/metro-runtime to format paths in the web LogBox.\n process.env.EXPO_PUBLIC_PROJECT_ROOT = process.env.EXPO_PUBLIC_PROJECT_ROOT ?? projectRoot;\n\n // This is used for running Expo CLI in development against projects outside the monorepo.\n if (!isDirectoryIn(__dirname, projectRoot)) {\n if (!config.watchFolders) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders = [];\n }\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('metro-runtime/package.json'), '../..'));\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(\n path.join(require.resolve('@expo/metro-config/package.json'), '../..')\n );\n if (isReactCanaryEnabled) {\n // @ts-expect-error: watchFolders is readonly\n config.watchFolders.push(path.join(require.resolve('@expo/cli/package.json'), '..'));\n }\n }\n\n // TODO: Remove this\n // @ts-expect-error: Invalidate the cache when the location of expo-router changes on-disk.\n config.transformer._expoRouterPath = resolveFrom.silent(projectRoot, 'expo-router');\n\n let tsconfig: null | TsConfigPaths = null;\n\n if (isTsconfigPathsEnabled) {\n tsconfig = await loadTsConfigPathsAsync(projectRoot);\n }\n\n let expoConfigPlatforms = Object.entries(platformBundlers)\n .filter(\n ([platform, bundler]) => bundler === 'metro' && exp.platforms?.includes(platform as Platform)\n )\n .map(([platform]) => platform);\n\n if (Array.isArray(config.resolver.platforms)) {\n expoConfigPlatforms = [...new Set(expoConfigPlatforms.concat(config.resolver.platforms))];\n }\n\n // @ts-expect-error: typed as `readonly`.\n config.resolver.platforms = expoConfigPlatforms;\n\n config = withWebPolyfills(config, { getMetroBundler });\n\n return withExtendedResolver(config, {\n tsconfig,\n isExporting,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n });\n}\n\nfunction isDirectoryIn(targetPath: string, rootPath: string) {\n return targetPath.startsWith(rootPath) && targetPath.length >= rootPath.length;\n}\n"],"names":["getNodejsExtensions","shouldAliasModule","withExtendedResolver","withMetroMultiPlatformAsync","ASSET_REGISTRY_SRC","debug","require","withWebPolyfills","config","getMetroBundler","originalGetPolyfills","serializer","getPolyfills","bind","ctx","virtualEnvVarId","getMetroBundlerWithVirtualModules","setVirtualModule","virtualModuleId","platform","resolve","polyfills","normalizeSlashes","p","replace","srcExts","mjsExts","filter","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","isReactCanaryEnabled","isReactServerComponentsEnabled","Log","warn","log","chalk","dim","defaultResolver","metroResolver","resolver","createFastResolver","preserveSymlinks","blockList","Array","isArray","aliases","web","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","preferredMainFields","tsConfigResolve","paths","baseUrl","resolveWithTsConfigPaths","hasBaseUrl","isInteractive","configWatcher","FileNotifier","startObserving","loadTsConfigPathsAsync","then","tsConfigPaths","Object","keys","length","installExitHooks","stopObserving","getStrictResolver","resolveRequest","context","doResolve","moduleName","getOptionalResolver","optionalResolve","error","isResolutionError","isFailedToResolveNameError","isFailedToResolvePathError","idFactory","createModuleIdFactory","id","getAssetRegistryModule","type","filePath","externals","match","customResolverOptions","exporting","isServerEnvironment","environment","process","clientboundary","endsWith","isExternal","metroConfigWithCustomResolver","withMetroResolvers","requestDevMockProdReact","dev","originModulePath","requestTsconfigPaths","requestNodeExternals","isServer","moduleId","isNodeExternal","result","contents","requestCustomExternals","strictResolve","external","realModule","realPath","opaqueId","JSON","stringify","CommandError","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableAssetRegistry","includes","requestPostRewrites","FailedToResolvePathError","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","normal","canaryFile","shouldCreateVirtualCanary","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","nodeModulesPaths","path","join","unstable_conditionNames","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","input","output","exp","platformBundlers","isNamedRequiresEnabled","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","transformer","_expoRouterPath","expoConfigPlatforms","entries","platforms","map","Set","concat","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA6GeA,mBAAmB;eAAnBA;;IAypBAC,iBAAiB;eAAjBA;;IAnoBAC,oBAAoB;eAApBA;;IAmpBMC,2BAA2B;eAA3BA;;;;gEApxBJ;;;;;;;gEACH;;;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LogAsync: function() {
|
|
27
|
+
return maybeSymbolicateAndFormatReactErrorLogAsync;
|
|
28
|
+
},
|
|
29
|
+
parseErrorStringToObject: function() {
|
|
30
|
+
return parseErrorStringToObject;
|
|
25
31
|
}
|
|
26
32
|
});
|
|
27
33
|
function _metroconfig() {
|
|
@@ -62,6 +68,8 @@ function _stacktraceparser() {
|
|
|
62
68
|
const _LogBoxSymbolication = require("./metro/log-box/LogBoxSymbolication");
|
|
63
69
|
const _env = require("../../utils/env");
|
|
64
70
|
const _fn = require("../../utils/fn");
|
|
71
|
+
const _LogBoxLog = require("./metro/log-box/LogBoxLog");
|
|
72
|
+
const _metroErrorInterface = require("./metro/metroErrorInterface");
|
|
65
73
|
function _interop_require_default(obj) {
|
|
66
74
|
return obj && obj.__esModule ? obj : {
|
|
67
75
|
default: obj
|
|
@@ -108,6 +116,7 @@ function _interop_require_wildcard(obj, nodeInterop) {
|
|
|
108
116
|
}
|
|
109
117
|
return newObj;
|
|
110
118
|
}
|
|
119
|
+
const debug = require('debug')('expo:metro:logger');
|
|
111
120
|
const groupStack = [];
|
|
112
121
|
let collapsedGuardTimer;
|
|
113
122
|
function logLikeMetro(originalLogFunction, level, platform, ...data) {
|
|
@@ -146,6 +155,50 @@ function logLikeMetro(originalLogFunction, level, platform, ...data) {
|
|
|
146
155
|
}
|
|
147
156
|
const escapedPathSep = _path().default.sep === '\\' ? '\\\\' : _path().default.sep;
|
|
148
157
|
const SERVER_STACK_MATCHER = new RegExp(`${escapedPathSep}(react-dom|metro-runtime|expo-router)${escapedPathSep}`);
|
|
158
|
+
async function maybeSymbolicateAndFormatReactErrorLogAsync(projectRoot, level, error) {
|
|
159
|
+
var _log_symbolicated_stack, _log_symbolicated;
|
|
160
|
+
const log = new _LogBoxLog.LogBoxLog({
|
|
161
|
+
level: level,
|
|
162
|
+
message: {
|
|
163
|
+
content: error.message,
|
|
164
|
+
substitutions: []
|
|
165
|
+
},
|
|
166
|
+
isComponentError: false,
|
|
167
|
+
stack: error.stack,
|
|
168
|
+
category: 'static',
|
|
169
|
+
componentStack: []
|
|
170
|
+
});
|
|
171
|
+
await new Promise((res)=>log.symbolicate('stack', res));
|
|
172
|
+
const symbolicatedErrorMessageAndStackLog = [
|
|
173
|
+
log.message.content,
|
|
174
|
+
(0, _metroErrorInterface.getStackAsFormattedLog)(projectRoot, {
|
|
175
|
+
stack: ((_log_symbolicated = log.symbolicated) == null ? void 0 : (_log_symbolicated_stack = _log_symbolicated.stack) == null ? void 0 : _log_symbolicated_stack.stack) ?? [],
|
|
176
|
+
codeFrame: log.codeFrame
|
|
177
|
+
})
|
|
178
|
+
].join('\n\n');
|
|
179
|
+
return symbolicatedErrorMessageAndStackLog;
|
|
180
|
+
}
|
|
181
|
+
function parseErrorStringToObject(errorString) {
|
|
182
|
+
// Find the first line of the possible stack trace
|
|
183
|
+
const stackStartIndex = errorString.indexOf('\n at ');
|
|
184
|
+
if (stackStartIndex === -1) {
|
|
185
|
+
// No stack trace found, return the original error string
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
const message = errorString.slice(0, stackStartIndex).trim();
|
|
189
|
+
const stack = errorString.slice(stackStartIndex + 1);
|
|
190
|
+
try {
|
|
191
|
+
const parsedStack = (0, _LogBoxSymbolication.parseErrorStack)(stack);
|
|
192
|
+
return {
|
|
193
|
+
message,
|
|
194
|
+
stack: parsedStack
|
|
195
|
+
};
|
|
196
|
+
} catch (e) {
|
|
197
|
+
// If parsing fails, return the original error string
|
|
198
|
+
debug('Failed to parse error stack:', e);
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
149
202
|
function augmentLogsInternal(projectRoot) {
|
|
150
203
|
const augmentLog = (name, fn)=>{
|
|
151
204
|
// @ts-expect-error: TypeScript doesn't know about polyfilled functions.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/start/server/serverLogLikeMetro.ts"],"sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { INTERNAL_CALLSITES_REGEX } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport path from 'path';\n// @ts-expect-error\nimport { mapSourcePosition } from 'source-map-support';\nimport * as stackTraceParser from 'stacktrace-parser';\n\nimport { parseErrorStack } from './metro/log-box/LogBoxSymbolication';\nimport { env } from '../../utils/env';\nimport { memoize } from '../../utils/fn';\n\nconst groupStack: any = [];\nlet collapsedGuardTimer: ReturnType<typeof setTimeout> | undefined;\n\nexport function logLikeMetro(\n originalLogFunction: (...args: any[]) => void,\n level: string,\n platform: string,\n ...data: any[]\n) {\n // @ts-expect-error\n const logFunction = console[level] && level !== 'trace' ? level : 'log';\n const color =\n level === 'error'\n ? chalk.inverse.red\n : level === 'warn'\n ? chalk.inverse.yellow\n : chalk.inverse.white;\n\n if (level === 'group') {\n groupStack.push(level);\n } else if (level === 'groupCollapsed') {\n groupStack.push(level);\n clearTimeout(collapsedGuardTimer);\n // Inform users that logs get swallowed if they forget to call `groupEnd`.\n collapsedGuardTimer = setTimeout(() => {\n if (groupStack.includes('groupCollapsed')) {\n originalLogFunction(\n chalk.inverse.yellow.bold(' WARN '),\n 'Expected `console.groupEnd` to be called after `console.groupCollapsed`.'\n );\n groupStack.length = 0;\n }\n }, 3000);\n return;\n } else if (level === 'groupEnd') {\n groupStack.pop();\n if (!groupStack.length) {\n clearTimeout(collapsedGuardTimer);\n }\n return;\n }\n\n if (!groupStack.includes('groupCollapsed')) {\n // Remove excess whitespace at the end of a log message, if possible.\n const lastItem = data[data.length - 1];\n if (typeof lastItem === 'string') {\n data[data.length - 1] = lastItem.trimEnd();\n }\n\n const modePrefix = platform === '' ? '' : chalk.bold`${platform} `;\n originalLogFunction(\n modePrefix +\n color.bold(` ${logFunction.toUpperCase()} `) +\n ''.padEnd(groupStack.length * 2, ' '),\n ...data\n );\n }\n}\n\nconst escapedPathSep = path.sep === '\\\\' ? '\\\\\\\\' : path.sep;\nconst SERVER_STACK_MATCHER = new RegExp(\n `${escapedPathSep}(react-dom|metro-runtime|expo-router)${escapedPathSep}`\n);\n\nfunction augmentLogsInternal(projectRoot: string) {\n const augmentLog = (name: string, fn: typeof console.log) => {\n // @ts-expect-error: TypeScript doesn't know about polyfilled functions.\n if (fn.__polyfilled) {\n return fn;\n }\n const originalFn = fn.bind(console);\n function logWithStack(...args: any[]) {\n const stack = new Error().stack;\n // Check if the log originates from the server.\n const isServerLog = !!stack?.match(SERVER_STACK_MATCHER);\n\n if (isServerLog) {\n if (name === 'error' || name === 'warn') {\n if (\n args.length === 2 &&\n typeof args[1] === 'string' &&\n args[1].trim().startsWith('at ')\n ) {\n // react-dom custom stacks which are always broken.\n // A stack string like:\n // at div\n // at http://localhost:8081/node_modules/expo-router/node/render.bundle?platform=web&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app&resolver.environment=node&transform.environment=node:38008:27\n // at Background (http://localhost:8081/node_modules/expo-router/node/render.bundle?platform=web&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app&resolver.environment=node&transform.environment=node:151009:7)\n const customStack = args[1];\n\n try {\n const parsedStack = parseErrorStack(customStack);\n const symbolicatedStack = parsedStack.map((line: any) => {\n const mapped = mapSourcePosition({\n source: line.file,\n line: line.lineNumber,\n column: line.column,\n }) as {\n // '/Users/evanbacon/Documents/GitHub/lab/sdk51-beta/node_modules/react-native-web/dist/exports/View/index.js',\n source: string;\n line: number;\n column: number;\n // 'hrefAttrs'\n name: string | null;\n };\n\n const fallbackName = mapped.name ?? '<unknown>';\n return {\n file: mapped.source,\n lineNumber: mapped.line,\n column: mapped.column,\n // Attempt to preserve the react component name if possible.\n methodName: line.methodName\n ? line.methodName === '<unknown>'\n ? fallbackName\n : line.methodName\n : fallbackName,\n arguments: line.arguments ?? [],\n };\n });\n\n // Replace args[1] with the formatted stack.\n args[1] = '\\n' + formatParsedStackLikeMetro(projectRoot, symbolicatedStack, true);\n } catch {\n // If symbolication fails, log the original stack.\n args.push('\\n' + formatStackLikeMetro(projectRoot, customStack));\n }\n } else {\n args.push('\\n' + formatStackLikeMetro(projectRoot, stack!));\n }\n }\n\n logLikeMetro(originalFn, name, 'λ', ...args);\n } else {\n originalFn(...args);\n }\n }\n logWithStack.__polyfilled = true;\n return logWithStack;\n };\n\n ['trace', 'info', 'error', 'warn', 'log', 'group', 'groupCollapsed', 'groupEnd', 'debug'].forEach(\n (name) => {\n // @ts-expect-error\n console[name] = augmentLog(name, console[name]);\n }\n );\n}\n\nexport function formatStackLikeMetro(projectRoot: string, stack: string) {\n // Remove `Error: ` from the beginning of the stack trace.\n // Dim traces that match `INTERNAL_CALLSITES_REGEX`\n\n const stackTrace = stackTraceParser.parse(stack);\n return formatParsedStackLikeMetro(projectRoot, stackTrace);\n}\n\nfunction formatParsedStackLikeMetro(\n projectRoot: string,\n stackTrace: stackTraceParser.StackFrame[],\n isComponentStack = false\n) {\n // Remove `Error: ` from the beginning of the stack trace.\n // Dim traces that match `INTERNAL_CALLSITES_REGEX`\n\n return stackTrace\n .filter(\n (line) =>\n line.file &&\n // Ignore unsymbolicated stack frames. It's not clear how this is possible but it sometimes happens when the graph changes.\n !/^https?:\\/\\//.test(line.file) &&\n (isComponentStack ? true : line.file !== '<anonymous>')\n )\n .map((line) => {\n // Use the same regex we use in Metro config to filter out traces:\n const isCollapsed = INTERNAL_CALLSITES_REGEX.test(line.file!);\n if (!isComponentStack && isCollapsed && !env.EXPO_DEBUG) {\n return null;\n }\n // If a file is collapsed, print it with dim styling.\n const style = isCollapsed ? chalk.dim : chalk.gray;\n // Use the `at` prefix to match Node.js\n let fileName = line.file!;\n if (fileName.startsWith(path.sep)) {\n fileName = path.relative(projectRoot, fileName);\n }\n if (line.lineNumber != null) {\n fileName += `:${line.lineNumber}`;\n if (line.column != null) {\n fileName += `:${line.column}`;\n }\n }\n\n return style(` ${line.methodName} (${fileName})`);\n })\n .filter(Boolean)\n .join('\\n');\n}\n\n/** Augment console logs to check the stack trace and format like Metro logs if we think the log came from the SSR renderer or an API route. */\nexport const augmentLogs = memoize(augmentLogsInternal);\n"],"names":["augmentLogs","formatStackLikeMetro","logLikeMetro","groupStack","collapsedGuardTimer","originalLogFunction","level","platform","data","logFunction","console","color","chalk","inverse","red","yellow","white","push","clearTimeout","setTimeout","includes","bold","length","pop","lastItem","trimEnd","modePrefix","toUpperCase","padEnd","escapedPathSep","path","sep","SERVER_STACK_MATCHER","RegExp","augmentLogsInternal","projectRoot","augmentLog","name","fn","__polyfilled","originalFn","bind","logWithStack","args","stack","Error","isServerLog","match","trim","startsWith","customStack","parsedStack","parseErrorStack","symbolicatedStack","map","line","mapped","mapSourcePosition","source","file","lineNumber","column","fallbackName","methodName","arguments","formatParsedStackLikeMetro","forEach","stackTrace","stackTraceParser","parse","isComponentStack","filter","test","isCollapsed","INTERNAL_CALLSITES_REGEX","env","EXPO_DEBUG","style","dim","gray","fileName","relative","Boolean","join","memoize"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAoNYA,WAAW;eAAXA;;IAnDGC,oBAAoB;eAApBA;;IAlJAC,YAAY;eAAZA;;;;yBAdyB;;;;;;;gEACvB;;;;;;;gEACD;;;;;;;yBAEiB;;;;;;;iEACA;;;;;;qCAEF;qBACZ;oBACI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,MAAMC,aAAkB,EAAE;AAC1B,IAAIC;AAEG,SAASF,aACdG,mBAA6C,EAC7CC,KAAa,EACbC,QAAgB,EAChB,GAAGC,IAAW;IAEd,mBAAmB;IACnB,MAAMC,cAAcC,OAAO,CAACJ,MAAM,IAAIA,UAAU,UAAUA,QAAQ;IAClE,MAAMK,QACJL,UAAU,UACNM,gBAAK,CAACC,OAAO,CAACC,GAAG,GACjBR,UAAU,SACRM,gBAAK,CAACC,OAAO,CAACE,MAAM,GACpBH,gBAAK,CAACC,OAAO,CAACG,KAAK;IAE3B,IAAIV,UAAU,SAAS;QACrBH,WAAWc,IAAI,CAACX;IAClB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AM;YAC3BoB,YAAY,CAAC,CAAC,EAAEzB,KAAKK,UAAU,EAAE;YACjC,IAAIL,KAAKM,MAAM,IAAI,MAAM;gBACvBmB,YAAY,CAAC,CAAC,EAAEzB,KAAKM,MAAM,EAAE;YAC/B;QACF;QAEA,OAAOgB,MAAM,CAAC,EAAE,EAAEtB,KAAKQ,UAAU,CAAC,EAAE,EAAEiB,SAAS,CAAC,CAAC;IACnD,GACCT,MAAM,CAACW,SACPC,IAAI,CAAC;AACV;AAGO,MAAMnF,cAAcoF,IAAAA,WAAO,EAAClD"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/start/server/serverLogLikeMetro.ts"],"sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { INTERNAL_CALLSITES_REGEX } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport path from 'path';\n// @ts-expect-error\nimport { mapSourcePosition } from 'source-map-support';\nimport * as stackTraceParser from 'stacktrace-parser';\n\nimport { parseErrorStack, StackFrame } from './metro/log-box/LogBoxSymbolication';\nimport { env } from '../../utils/env';\nimport { memoize } from '../../utils/fn';\nimport { LogBoxLog } from './metro/log-box/LogBoxLog';\nimport { getStackAsFormattedLog } from './metro/metroErrorInterface';\n\nconst debug = require('debug')('expo:metro:logger') as typeof console.log;\n\nconst groupStack: any = [];\nlet collapsedGuardTimer: ReturnType<typeof setTimeout> | undefined;\n\nexport function logLikeMetro(\n originalLogFunction: (...args: any[]) => void,\n level: string,\n platform: string,\n ...data: any[]\n) {\n // @ts-expect-error\n const logFunction = console[level] && level !== 'trace' ? level : 'log';\n const color =\n level === 'error'\n ? chalk.inverse.red\n : level === 'warn'\n ? chalk.inverse.yellow\n : chalk.inverse.white;\n\n if (level === 'group') {\n groupStack.push(level);\n } else if (level === 'groupCollapsed') {\n groupStack.push(level);\n clearTimeout(collapsedGuardTimer);\n // Inform users that logs get swallowed if they forget to call `groupEnd`.\n collapsedGuardTimer = setTimeout(() => {\n if (groupStack.includes('groupCollapsed')) {\n originalLogFunction(\n chalk.inverse.yellow.bold(' WARN '),\n 'Expected `console.groupEnd` to be called after `console.groupCollapsed`.'\n );\n groupStack.length = 0;\n }\n }, 3000);\n return;\n } else if (level === 'groupEnd') {\n groupStack.pop();\n if (!groupStack.length) {\n clearTimeout(collapsedGuardTimer);\n }\n return;\n }\n\n if (!groupStack.includes('groupCollapsed')) {\n // Remove excess whitespace at the end of a log message, if possible.\n const lastItem = data[data.length - 1];\n if (typeof lastItem === 'string') {\n data[data.length - 1] = lastItem.trimEnd();\n }\n\n const modePrefix = platform === '' ? '' : chalk.bold`${platform} `;\n originalLogFunction(\n modePrefix +\n color.bold(` ${logFunction.toUpperCase()} `) +\n ''.padEnd(groupStack.length * 2, ' '),\n ...data\n );\n }\n}\n\nconst escapedPathSep = path.sep === '\\\\' ? '\\\\\\\\' : path.sep;\nconst SERVER_STACK_MATCHER = new RegExp(\n `${escapedPathSep}(react-dom|metro-runtime|expo-router)${escapedPathSep}`\n);\n\nexport async function maybeSymbolicateAndFormatReactErrorLogAsync(\n projectRoot: string,\n level: 'error' | 'warn',\n error: {\n message: string;\n stack: StackFrame[];\n }\n): Promise<string> {\n const log = new LogBoxLog({\n level: level as 'error' | 'warn',\n message: {\n content: error.message,\n substitutions: [],\n },\n isComponentError: false,\n stack: error.stack,\n category: 'static',\n componentStack: [],\n });\n\n await new Promise((res) => log.symbolicate('stack', res));\n\n const symbolicatedErrorMessageAndStackLog = [\n log.message.content,\n getStackAsFormattedLog(projectRoot, {\n stack: log.symbolicated?.stack?.stack ?? [],\n codeFrame: log.codeFrame,\n }),\n ].join('\\n\\n');\n\n return symbolicatedErrorMessageAndStackLog;\n}\n\n/** Attempt to parse an error message string to an unsymbolicated stack. */\nexport function parseErrorStringToObject(errorString: string) {\n // Find the first line of the possible stack trace\n const stackStartIndex = errorString.indexOf('\\n at ');\n if (stackStartIndex === -1) {\n // No stack trace found, return the original error string\n return null;\n }\n const message = errorString.slice(0, stackStartIndex).trim();\n const stack = errorString.slice(stackStartIndex + 1);\n\n try {\n const parsedStack = parseErrorStack(stack);\n\n return {\n message,\n stack: parsedStack,\n };\n } catch (e) {\n // If parsing fails, return the original error string\n debug('Failed to parse error stack:', e);\n return null;\n }\n}\n\nfunction augmentLogsInternal(projectRoot: string) {\n const augmentLog = (name: string, fn: typeof console.log) => {\n // @ts-expect-error: TypeScript doesn't know about polyfilled functions.\n if (fn.__polyfilled) {\n return fn;\n }\n const originalFn = fn.bind(console);\n function logWithStack(...args: any[]) {\n const stack = new Error().stack;\n // Check if the log originates from the server.\n const isServerLog = !!stack?.match(SERVER_STACK_MATCHER);\n\n if (isServerLog) {\n if (name === 'error' || name === 'warn') {\n if (\n args.length === 2 &&\n typeof args[1] === 'string' &&\n args[1].trim().startsWith('at ')\n ) {\n // react-dom custom stacks which are always broken.\n // A stack string like:\n // at div\n // at http://localhost:8081/node_modules/expo-router/node/render.bundle?platform=web&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app&resolver.environment=node&transform.environment=node:38008:27\n // at Background (http://localhost:8081/node_modules/expo-router/node/render.bundle?platform=web&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app&resolver.environment=node&transform.environment=node:151009:7)\n const customStack = args[1];\n\n try {\n const parsedStack = parseErrorStack(customStack);\n const symbolicatedStack = parsedStack.map((line: any) => {\n const mapped = mapSourcePosition({\n source: line.file,\n line: line.lineNumber,\n column: line.column,\n }) as {\n // '/Users/evanbacon/Documents/GitHub/lab/sdk51-beta/node_modules/react-native-web/dist/exports/View/index.js',\n source: string;\n line: number;\n column: number;\n // 'hrefAttrs'\n name: string | null;\n };\n\n const fallbackName = mapped.name ?? '<unknown>';\n return {\n file: mapped.source,\n lineNumber: mapped.line,\n column: mapped.column,\n // Attempt to preserve the react component name if possible.\n methodName: line.methodName\n ? line.methodName === '<unknown>'\n ? fallbackName\n : line.methodName\n : fallbackName,\n arguments: line.arguments ?? [],\n };\n });\n\n // Replace args[1] with the formatted stack.\n args[1] = '\\n' + formatParsedStackLikeMetro(projectRoot, symbolicatedStack, true);\n } catch {\n // If symbolication fails, log the original stack.\n args.push('\\n' + formatStackLikeMetro(projectRoot, customStack));\n }\n } else {\n args.push('\\n' + formatStackLikeMetro(projectRoot, stack!));\n }\n }\n\n logLikeMetro(originalFn, name, 'λ', ...args);\n } else {\n originalFn(...args);\n }\n }\n logWithStack.__polyfilled = true;\n return logWithStack;\n };\n\n ['trace', 'info', 'error', 'warn', 'log', 'group', 'groupCollapsed', 'groupEnd', 'debug'].forEach(\n (name) => {\n // @ts-expect-error\n console[name] = augmentLog(name, console[name]);\n }\n );\n}\n\nexport function formatStackLikeMetro(projectRoot: string, stack: string) {\n // Remove `Error: ` from the beginning of the stack trace.\n // Dim traces that match `INTERNAL_CALLSITES_REGEX`\n\n const stackTrace = stackTraceParser.parse(stack);\n return formatParsedStackLikeMetro(projectRoot, stackTrace);\n}\n\nfunction formatParsedStackLikeMetro(\n projectRoot: string,\n stackTrace: stackTraceParser.StackFrame[],\n isComponentStack = false\n) {\n // Remove `Error: ` from the beginning of the stack trace.\n // Dim traces that match `INTERNAL_CALLSITES_REGEX`\n\n return stackTrace\n .filter(\n (line) =>\n line.file &&\n // Ignore unsymbolicated stack frames. It's not clear how this is possible but it sometimes happens when the graph changes.\n !/^https?:\\/\\//.test(line.file) &&\n (isComponentStack ? true : line.file !== '<anonymous>')\n )\n .map((line) => {\n // Use the same regex we use in Metro config to filter out traces:\n const isCollapsed = INTERNAL_CALLSITES_REGEX.test(line.file!);\n if (!isComponentStack && isCollapsed && !env.EXPO_DEBUG) {\n return null;\n }\n // If a file is collapsed, print it with dim styling.\n const style = isCollapsed ? chalk.dim : chalk.gray;\n // Use the `at` prefix to match Node.js\n let fileName = line.file!;\n if (fileName.startsWith(path.sep)) {\n fileName = path.relative(projectRoot, fileName);\n }\n if (line.lineNumber != null) {\n fileName += `:${line.lineNumber}`;\n if (line.column != null) {\n fileName += `:${line.column}`;\n }\n }\n\n return style(` ${line.methodName} (${fileName})`);\n })\n .filter(Boolean)\n .join('\\n');\n}\n\n/** Augment console logs to check the stack trace and format like Metro logs if we think the log came from the SSR renderer or an API route. */\nexport const augmentLogs = memoize(augmentLogsInternal);\n"],"names":["augmentLogs","formatStackLikeMetro","logLikeMetro","maybeSymbolicateAndFormatReactErrorLogAsync","parseErrorStringToObject","debug","require","groupStack","collapsedGuardTimer","originalLogFunction","level","platform","data","logFunction","console","color","chalk","inverse","red","yellow","white","push","clearTimeout","setTimeout","includes","bold","length","pop","lastItem","trimEnd","modePrefix","toUpperCase","padEnd","escapedPathSep","path","sep","SERVER_STACK_MATCHER","RegExp","projectRoot","error","log","LogBoxLog","message","content","substitutions","isComponentError","stack","category","componentStack","Promise","res","symbolicate","symbolicatedErrorMessageAndStackLog","getStackAsFormattedLog","symbolicated","codeFrame","join","errorString","stackStartIndex","indexOf","slice","trim","parsedStack","parseErrorStack","e","augmentLogsInternal","augmentLog","name","fn","__polyfilled","originalFn","bind","logWithStack","args","Error","isServerLog","match","startsWith","customStack","symbolicatedStack","map","line","mapped","mapSourcePosition","source","file","lineNumber","column","fallbackName","methodName","arguments","formatParsedStackLikeMetro","forEach","stackTrace","stackTraceParser","parse","isComponentStack","filter","test","isCollapsed","INTERNAL_CALLSITES_REGEX","env","EXPO_DEBUG","style","dim","gray","fileName","relative","Boolean","memoize"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAkRYA,WAAW;eAAXA;;IAnDGC,oBAAoB;eAApBA;;IA5MAC,YAAY;eAAZA;;IA6DMC,2CAA2C;eAA3CA;;IAkCNC,wBAAwB;eAAxBA;;;;yBAjHyB;;;;;;;gEACvB;;;;;;;gEACD;;;;;;;yBAEiB;;;;;;;iEACA;;;;;;qCAEU;qBACxB;oBACI;2BACE;qCACa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEvC,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MA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AcnF,gBAAK,CAACwF,GAAG,GAAGxF,gBAAK,CAACyF,IAAI;QAClD,uCAAuC;QACvC,IAAIC,WAAWzB,KAAKI,IAAI;QACxB,IAAIqB,SAAS7B,UAAU,CAAC3C,eAAI,CAACC,GAAG,GAAG;YACjCuE,WAAWxE,eAAI,CAACyE,QAAQ,CAACrE,aAAaoE;QACxC;QACA,IAAIzB,KAAKK,UAAU,IAAI,MAAM;YAC3BoB,YAAY,CAAC,CAAC,EAAEzB,KAAKK,UAAU,EAAE;YACjC,IAAIL,KAAKM,MAAM,IAAI,MAAM;gBACvBmB,YAAY,CAAC,CAAC,EAAEzB,KAAKM,MAAM,EAAE;YAC/B;QACF;QAEA,OAAOgB,MAAM,CAAC,EAAE,EAAEtB,KAAKQ,UAAU,CAAC,EAAE,EAAEiB,SAAS,CAAC,CAAC;IACnD,GACCT,MAAM,CAACW,SACPpD,IAAI,CAAC;AACV;AAGO,MAAMxD,cAAc6G,IAAAA,WAAO,EAAC5C"}
|
|
@@ -33,7 +33,7 @@ class FetchClient {
|
|
|
33
33
|
this.headers = {
|
|
34
34
|
accept: 'application/json',
|
|
35
35
|
'content-type': 'application/json',
|
|
36
|
-
'user-agent': `expo-cli/${"1.0.0-canary-20250404-
|
|
36
|
+
'user-agent': `expo-cli/${"1.0.0-canary-20250404-3c3b5fd"}`,
|
|
37
37
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
38
38
|
};
|
|
39
39
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "1.0.0-canary-20250404-
|
|
3
|
+
"version": "1.0.0-canary-20250404-3c3b5fd",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -42,17 +42,17 @@
|
|
|
42
42
|
"@0no-co/graphql.web": "^1.0.8",
|
|
43
43
|
"@babel/runtime": "^7.20.0",
|
|
44
44
|
"@expo/code-signing-certificates": "^0.0.5",
|
|
45
|
-
"@expo/config": "11.0.0-canary-20250404-
|
|
46
|
-
"@expo/config-plugins": "9.1.0-canary-20250404-
|
|
45
|
+
"@expo/config": "11.0.0-canary-20250404-3c3b5fd",
|
|
46
|
+
"@expo/config-plugins": "9.1.0-canary-20250404-3c3b5fd",
|
|
47
47
|
"@expo/devcert": "^1.1.2",
|
|
48
|
-
"@expo/env": "1.0.1-canary-20250404-
|
|
49
|
-
"@expo/image-utils": "0.6.6-canary-20250404-
|
|
50
|
-
"@expo/json-file": "9.0.3-canary-20250404-
|
|
51
|
-
"@expo/metro-config": "0.20.0-canary-20250404-
|
|
52
|
-
"@expo/osascript": "2.1.7-canary-20250404-
|
|
53
|
-
"@expo/package-manager": "1.6.2-canary-20250404-
|
|
54
|
-
"@expo/plist": "0.2.3-canary-20250404-
|
|
55
|
-
"@expo/prebuild-config": "9.0.0-canary-20250404-
|
|
48
|
+
"@expo/env": "1.0.1-canary-20250404-3c3b5fd",
|
|
49
|
+
"@expo/image-utils": "0.6.6-canary-20250404-3c3b5fd",
|
|
50
|
+
"@expo/json-file": "9.0.3-canary-20250404-3c3b5fd",
|
|
51
|
+
"@expo/metro-config": "0.20.0-canary-20250404-3c3b5fd",
|
|
52
|
+
"@expo/osascript": "2.1.7-canary-20250404-3c3b5fd",
|
|
53
|
+
"@expo/package-manager": "1.6.2-canary-20250404-3c3b5fd",
|
|
54
|
+
"@expo/plist": "0.2.3-canary-20250404-3c3b5fd",
|
|
55
|
+
"@expo/prebuild-config": "9.0.0-canary-20250404-3c3b5fd",
|
|
56
56
|
"@expo/spawn-async": "^1.7.2",
|
|
57
57
|
"@expo/ws-tunnel": "^1.0.1",
|
|
58
58
|
"@expo/xcpretty": "^4.3.0",
|
|
@@ -109,7 +109,7 @@
|
|
|
109
109
|
"devDependencies": {
|
|
110
110
|
"@expo/multipart-body-parser": "^1.0.0",
|
|
111
111
|
"@expo/ngrok": "4.1.3",
|
|
112
|
-
"@expo/server": "0.6.0-canary-20250404-
|
|
112
|
+
"@expo/server": "0.6.0-canary-20250404-3c3b5fd",
|
|
113
113
|
"@graphql-codegen/cli": "^2.16.3",
|
|
114
114
|
"@graphql-codegen/typescript": "^2.8.7",
|
|
115
115
|
"@graphql-codegen/typescript-operations": "^2.5.12",
|
|
@@ -139,7 +139,7 @@
|
|
|
139
139
|
"@types/ws": "^8.5.4",
|
|
140
140
|
"devtools-protocol": "^0.0.1113120",
|
|
141
141
|
"expo-atlas": "^0.4.0",
|
|
142
|
-
"expo-module-scripts": "4.0.6-canary-20250404-
|
|
142
|
+
"expo-module-scripts": "4.0.6-canary-20250404-3c3b5fd",
|
|
143
143
|
"find-process": "^1.4.7",
|
|
144
144
|
"jest-runner-tsd": "^6.0.0",
|
|
145
145
|
"klaw-sync": "^6.0.0",
|