@expo/cli 56.1.3 → 56.1.5
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/api/endpoint.js +1 -1
- package/build/src/api/endpoint.js.map +1 -1
- package/build/src/api/user/actions.js +7 -0
- package/build/src/api/user/actions.js.map +1 -1
- package/build/src/api/user/expoSsoLauncher.js +76 -24
- package/build/src/api/user/expoSsoLauncher.js.map +1 -1
- package/build/src/api/user/user.js +12 -0
- package/build/src/api/user/user.js.map +1 -1
- package/build/src/customize/typescript.js.map +1 -1
- package/build/src/events/index.js +1 -1
- package/build/src/start/platforms/ios/simctl.js +4 -0
- package/build/src/start/platforms/ios/simctl.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +57 -45
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/debugging/createDebugMiddleware.js +1 -1
- package/build/src/start/server/metro/debugging/createDebugMiddleware.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +2 -1
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/runServer-fork.js +10 -1
- package/build/src/start/server/metro/runServer-fork.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +8 -4
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/serverLogLikeMetro.js +2 -2
- package/build/src/start/server/serverLogLikeMetro.js.map +1 -1
- package/build/src/start/server/type-generation/routes.js +1 -3
- package/build/src/start/server/type-generation/routes.js.map +1 -1
- package/build/src/utils/open.js +243 -11
- package/build/src/utils/open.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 +17 -18
- package/static/loading-page/index.html +35 -1
|
@@ -16,9 +16,9 @@ function _ws() {
|
|
|
16
16
|
return data;
|
|
17
17
|
}
|
|
18
18
|
const _createHandlersFactory = require("./createHandlersFactory");
|
|
19
|
+
const _NetworkResponse = require("./messageHandlers/NetworkResponse");
|
|
19
20
|
const _env = require("../../../../utils/env");
|
|
20
21
|
const _net = require("../../../../utils/net");
|
|
21
|
-
const _NetworkResponse = require("./messageHandlers/NetworkResponse");
|
|
22
22
|
const debug = require('debug')('expo:metro:debugging:middleware');
|
|
23
23
|
function createDebugMiddleware({ serverBaseUrl, reporter }) {
|
|
24
24
|
// Load the React Native debugging tools from project
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/createDebugMiddleware.ts"],"sourcesContent":["import type { NextHandleFunction } from 'connect';\nimport { WebSocketServer } from 'ws';\n\nimport { createHandlersFactory } from './createHandlersFactory';\nimport { env, envIsHeadless } from '../../../../utils/env';\nimport { isLocalSocket, isMatchingOrigin } from '../../../../utils/net';\nimport type { TerminalReporter } from '../TerminalReporter';\
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/createDebugMiddleware.ts"],"sourcesContent":["import type { NextHandleFunction } from 'connect';\nimport { WebSocketServer } from 'ws';\n\nimport { createHandlersFactory } from './createHandlersFactory';\nimport { NETWORK_RESPONSE_STORAGE } from './messageHandlers/NetworkResponse';\nimport { env, envIsHeadless } from '../../../../utils/env';\nimport { isLocalSocket, isMatchingOrigin } from '../../../../utils/net';\nimport type { TerminalReporter } from '../TerminalReporter';\n\nconst debug = require('debug')('expo:metro:debugging:middleware') as typeof console.log;\n\ninterface DebugMiddleware {\n debugMiddleware: NextHandleFunction;\n debugWebsocketEndpoints: Record<string, WebSocketServer>;\n}\n\ninterface DebugMiddlewareParams {\n serverBaseUrl: string;\n reporter: TerminalReporter;\n}\n\nexport function createDebugMiddleware({\n serverBaseUrl,\n reporter,\n}: DebugMiddlewareParams): DebugMiddleware {\n // Load the React Native debugging tools from project\n // TODO: check if this works with isolated modules\n const { createDevMiddleware } =\n require('@react-native/dev-middleware') as typeof import('@react-native/dev-middleware');\n\n const { middleware, websocketEndpoints } = createDevMiddleware({\n // TODO: Check with cedric why this can be removed\n // https://github.com/facebook/react-native/pull/53921\n // projectRoot: metroBundler.projectRoot,\n serverBaseUrl,\n logger: createLogger(reporter),\n unstable_customInspectorMessageHandler: createHandlersFactory(),\n // TODO: Forward all events to the shared Metro log reporter. Do this when we have opinions on how all logs should be presented.\n // unstable_eventReporter: {\n // logEvent(event) {\n // reporter.update(event);\n // },\n // },\n unstable_experiments: {\n // Enable the Network tab in React Native DevTools\n enableNetworkInspector: true,\n // Only enable opening the browser version of React Native DevTools when debugging.\n // This is useful when debugging the React Native DevTools by going to `/open-debugger` in the browser.\n enableOpenDebuggerRedirect: env.EXPO_DEBUG,\n // The standalone fusebox shell (@react-native/debugger-shell) starts installing almost\n // immediately in the background when the dev middleware is created, which we don't\n // always want to happen\n enableStandaloneFuseboxShell: !envIsHeadless(),\n },\n });\n\n const debuggerWebsocketEndpoint = websocketEndpoints['/inspector/debug'] as WebSocketServer;\n\n // NOTE(cedric): add a temporary websocket to handle Network-related CDP events\n websocketEndpoints['/inspector/network'] = createNetworkWebsocket(debuggerWebsocketEndpoint);\n\n // Explicitly limit debugger websocket to loopback requests\n debuggerWebsocketEndpoint.on('connection', (socket, request) => {\n if (!isLocalSocket(request.socket) || !isMatchingOrigin(request, serverBaseUrl)) {\n // NOTE: `socket.close` nicely closes the websocket, which will still allow incoming messages\n // `socket.terminate` instead forcefully closes down the socket\n socket.terminate();\n }\n });\n\n return {\n debugMiddleware(req, res, next) {\n // The debugger middleware is skipped entirely if the connection isn't a loopback request\n if (isLocalSocket(req.socket)) {\n return middleware(req, res, next);\n } else {\n return next();\n }\n },\n debugWebsocketEndpoints: websocketEndpoints,\n };\n}\n\nfunction createLogger(\n reporter: TerminalReporter\n): Parameters<typeof import('@react-native/dev-middleware').createDevMiddleware>[0]['logger'] {\n return {\n info: makeLogger(reporter, 'info'),\n warn: makeLogger(reporter, 'warn'),\n error: makeLogger(reporter, 'error'),\n };\n}\n\nfunction makeLogger(reporter: TerminalReporter, level: 'info' | 'warn' | 'error') {\n return (...data: any[]) =>\n reporter.update({\n type: 'unstable_server_log',\n level,\n data,\n });\n}\n\n/**\n * This adds a dedicated websocket connection that handles Network-related CDP events.\n * It's a temporary solution until Fusebox either implements the Network CDP domain,\n * or allows external domain agents that can send messages over the CDP socket to the debugger.\n * The Network websocket rebroadcasts events on the debugger CDP connections.\n */\nfunction createNetworkWebsocket(debuggerWebsocket: WebSocketServer) {\n const wss = new WebSocketServer({\n noServer: true,\n perMessageDeflate: true,\n // Don't crash on exceptionally large messages - assume the device is\n // well-behaved and the debugger is prepared to handle large messages.\n maxPayload: 0,\n });\n\n wss.on('connection', (networkSocket) => {\n networkSocket.on('message', (data) => {\n try {\n // Parse the network message, to determine how the message should be handled\n const message = JSON.parse(data.toString());\n\n if (message.method === 'Expo(Network.receivedResponseBody)' && message.params) {\n // If its a response body, write it to the global storage\n const { requestId, ...requestInfo } = message.params;\n NETWORK_RESPONSE_STORAGE.set(requestId, requestInfo);\n } else if (message.method.startsWith('Network.')) {\n // Otherwise, directly re-broadcast the Network events to all connected debuggers\n debuggerWebsocket.clients.forEach((debuggerSocket) => {\n if (debuggerSocket.readyState === debuggerSocket.OPEN) {\n debuggerSocket.send(data.toString());\n }\n });\n }\n } catch (error) {\n debug('Failed to handle Network CDP event', error);\n }\n });\n });\n\n return wss;\n}\n"],"names":["createDebugMiddleware","debug","require","serverBaseUrl","reporter","createDevMiddleware","middleware","websocketEndpoints","logger","createLogger","unstable_customInspectorMessageHandler","createHandlersFactory","unstable_experiments","enableNetworkInspector","enableOpenDebuggerRedirect","env","EXPO_DEBUG","enableStandaloneFuseboxShell","envIsHeadless","debuggerWebsocketEndpoint","createNetworkWebsocket","on","socket","request","isLocalSocket","isMatchingOrigin","terminate","debugMiddleware","req","res","next","debugWebsocketEndpoints","info","makeLogger","warn","error","level","data","update","type","debuggerWebsocket","wss","WebSocketServer","noServer","perMessageDeflate","maxPayload","networkSocket","message","JSON","parse","toString","method","params","requestId","requestInfo","NETWORK_RESPONSE_STORAGE","set","startsWith","clients","forEach","debuggerSocket","readyState","OPEN","send"],"mappings":";;;;+BAqBgBA;;;eAAAA;;;;yBApBgB;;;;;;uCAEM;iCACG;qBACN;qBACa;AAGhD,MAAMC,QAAQC,QAAQ,SAAS;AAYxB,SAASF,sBAAsB,EACpCG,aAAa,EACbC,QAAQ,EACc;IACtB,qDAAqD;IACrD,kDAAkD;IAClD,MAAM,EAAEC,mBAAmB,EAAE,GAC3BH,QAAQ;IAEV,MAAM,EAAEI,UAAU,EAAEC,kBAAkB,EAAE,GAAGF,oBAAoB;QAC7D,kDAAkD;QAClD,sDAAsD;QACtD,yCAAyC;QACzCF;QACAK,QAAQC,aAAaL;QACrBM,wCAAwCC,IAAAA,4CAAqB;QAC7D,gIAAgI;QAChI,4BAA4B;QAC5B,sBAAsB;QACtB,8BAA8B;QAC9B,OAAO;QACP,KAAK;QACLC,sBAAsB;YACpB,kDAAkD;YAClDC,wBAAwB;YACxB,mFAAmF;YACnF,uGAAuG;YACvGC,4BAA4BC,QAAG,CAACC,UAAU;YAC1C,uFAAuF;YACvF,mFAAmF;YACnF,wBAAwB;YACxBC,8BAA8B,CAACC,IAAAA,kBAAa;QAC9C;IACF;IAEA,MAAMC,4BAA4BZ,kBAAkB,CAAC,mBAAmB;IAExE,+EAA+E;IAC/EA,kBAAkB,CAAC,qBAAqB,GAAGa,uBAAuBD;IAElE,2DAA2D;IAC3DA,0BAA0BE,EAAE,CAAC,cAAc,CAACC,QAAQC;QAClD,IAAI,CAACC,IAAAA,kBAAa,EAACD,QAAQD,MAAM,KAAK,CAACG,IAAAA,qBAAgB,EAACF,SAASpB,gBAAgB;YAC/E,6FAA6F;YAC7F,+DAA+D;YAC/DmB,OAAOI,SAAS;QAClB;IACF;IAEA,OAAO;QACLC,iBAAgBC,GAAG,EAAEC,GAAG,EAAEC,IAAI;YAC5B,yFAAyF;YACzF,IAAIN,IAAAA,kB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kC;YAC9C;QACF;IACF;IAEA,OAAOM;AACT"}
|
|
@@ -533,7 +533,8 @@ async function instantiateMetroAsync(metroBundler, options, { isExporting, exp =
|
|
|
533
533
|
hmrServer,
|
|
534
534
|
server,
|
|
535
535
|
middleware,
|
|
536
|
-
messageSocket: messagesSocket
|
|
536
|
+
messageSocket: messagesSocket,
|
|
537
|
+
address
|
|
537
538
|
};
|
|
538
539
|
}
|
|
539
540
|
// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport type { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport type MetroHmrServer from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { mergeConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport type { createStableModuleIdFactory } from '@expo/metro-config';\nimport { getDefaultConfig } from '@expo/metro-config';\nimport { patchTransformFileForPackedMaps } from '@expo/metro-config/build/serializer/packedMap';\nimport { patchMetroSourceMapStringForPackedMaps } from '@expo/metro-config/build/serializer/sourceMap';\nimport { resolveBabelrcName } from '@expo/metro-config/exports';\nimport chalk from 'chalk';\nimport type http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport type { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { replaceMetroFileMap } from './createFileMap-fork';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer, type SecureServerOptions } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { events, shouldReduceLogs } from '../../../events';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'config', {\n serverRoot: string;\n projectRoot: string;\n exporting: boolean;\n flags: {\n autolinkingModuleResolution: boolean;\n serverActions: boolean;\n serverComponents: boolean;\n reactCompiler: boolean;\n optimizeGraph?: boolean;\n treeshaking?: boolean;\n logbox?: boolean;\n };\n }>(),\n t.event<'instantiate', {\n atlas: boolean;\n workers: number | null;\n host: string | null;\n port: number | null;\n }>(),\n]);\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n/**\n * Extends Metro's Terminal to intercept all console methods so they don't\n * corrupt the progress bar status lines.\n *\n * console.log/info are routed through terminal.log() (stdout, managed).\n * console.warn/error are routed through logStderr() which clears the\n * status from stdout before writing to stderr, then restores it.\n * Without this, unmanaged stderr writes shift the cursor and cause\n * progress bars to get stuck as permanent output.\n */\nclass LogRespectingTerminal extends Terminal {\n #stderrQueue: string[] = [];\n #drainingStderr = false;\n\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n const sendStderr = (...msg: any[]) => {\n if (!msg.length) {\n this.logStderr('');\n } else {\n const [format, ...args] = msg;\n this.logStderr(require('util').format(format, ...args));\n }\n };\n\n console.log = sendLog;\n console.info = sendLog;\n console.warn = sendStderr;\n console.error = sendStderr;\n\n // NOTE(@kitten): We flush the stderr queue immediately when we're about to exit\n process.on('exit', () => {\n if (!this.#drainingStderr && this.#stderrQueue.length) {\n this.#drainingStderr = true;\n this.status('');\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n }\n });\n }\n\n /** Write to stderr without corrupting Terminal's cursor tracking. */\n logStderr(line: string): void {\n if (!(process.stdout as any).isTTY) {\n process.stderr.write(line + '\\n');\n return;\n }\n this.#stderrQueue.push(line);\n this.#drainStderr();\n }\n\n async #drainStderr(): Promise<void> {\n if (this.#drainingStderr) return;\n this.#drainingStderr = true;\n\n while (this.#stderrQueue.length > 0) {\n // Clear status, flush to ensure it's removed from screen\n const prev = this.status('');\n await this.flush();\n\n // Write to stderr while status is cleared\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n\n // Restore status\n this.status(prev);\n }\n\n this.#drainingStderr = false;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Autolinking Module Resolution will be enabled by default when we're in a monorepo\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? isWorkspace;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n const serverComponentsEnabled = !!exp.experiments?.reactServerComponentRoutes;\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (serverComponentsEnabled || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n const configPath = env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;\n const resolvedConfig = await resolveConfig(configPath, projectRoot);\n const defaultConfig = getDefaultConfig(projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // NOTE(@kitten): Pass a hint to the transformer on where to find the Babel config\n asWritable(config.transformer).extendsBabelConfigPath =\n config.transformer.enableBabelRCLookup !== false ? resolveBabelrcName(projectRoot) : undefined;\n\n // On-Demand Filesystem is enabled by default\n // TODO(@kitten): Add to config-types JSON schema\n const onDemandFilesystem = exp.experiments?.onDemandFilesystem ?? true;\n asWritable(config.resolver).unstable_onDemandFilesystem = onDemandFilesystem;\n\n // NOTE(@kitten): `useWatchman` is currently enabled by default, but it also disables `forceNodeFilesystemAPI`.\n // If we instead set it to the special value `null`, it gets enables but also bypasses the \"native find\" codepath,\n // which is slower than just using the Node filesystem API\n // See: https://github.com/facebook/metro/blob/b9c243f/packages/metro-file-map/src/index.js#L326\n // See: https://github.com/facebook/metro/blob/b9c243f/packages/metro/src/node-haste/DependencyGraph/createFileMap.js#L109\n if (config.resolver.useWatchman === true) {\n asWritable(config.resolver).useWatchman = null as any;\n }\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n const reduceLogs = shouldReduceLogs();\n\n const reactCompilerEnabled = !!exp.experiments?.reactCompiler;\n if (!reduceLogs && reactCompilerEnabled) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (!reduceLogs && autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (!reduceLogs && env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n\n if (!reduceLogs && serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n serverRoot,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: serverComponentsEnabled,\n getMetroBundler,\n });\n\n event('config', {\n serverRoot: event.path(serverRoot),\n projectRoot: event.path(projectRoot),\n exporting: isExporting,\n flags: {\n autolinkingModuleResolution: autolinkingModuleResolutionEnabled,\n serverActions: serverActionsEnabled,\n serverComponents: serverComponentsEnabled,\n reactCompiler: reactCompilerEnabled,\n optimizeGraph: env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH,\n treeshaking: env.EXPO_UNSTABLE_TREE_SHAKING,\n logbox: env.EXPO_UNSTABLE_LOG_BOX,\n },\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n const getMetroBundler = () => metro.getBundler().getBundler();\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler,\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } = createMetroMiddleware(\n metroConfig,\n { getMetroBundler }\n );\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n // Support HTTPS based on the metro's tls server config\n // TODO(@kitten): Remove cast once `@expo/metro` is updated to a Metro version that supports the tls config\n const tls = (metroConfig.server as typeof metroConfig.server & { tls?: SecureServerOptions })\n ?.tls;\n const secureServerOptions = tls\n ? {\n key: tls.key,\n cert: tls.cert,\n ca: tls.ca,\n requestCert: tls.requestCert,\n }\n : undefined;\n\n const watch = !isExporting && isWatchEnabled();\n\n const { address, server, hmrServer, metro } = await replaceMetroFileMap(() => {\n return runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch,\n secureServerOptions,\n },\n {\n mockServer: isExporting,\n }\n );\n });\n\n event('instantiate', {\n atlas: env.EXPO_ATLAS,\n workers: metroConfig.maxWorkers ?? null,\n host: address?.address ?? null,\n port: address?.port ?? null,\n });\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n // Layered on top of the prune patch above. Both fresh worker results\n // and cache hits flow through `Bundler.transformFile`, so wrapping\n // here covers both.\n patchTransformFileForPackedMaps(metro.getBundler().getBundler());\n patchMetroSourceMapStringForPackedMaps();\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["event","instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","events","t","asWritable","input","LogRespectingTerminal","Terminal","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","sendStderr","logStderr","require","console","info","warn","error","process","on","status","lines","splice","stderr","write","join","line","stdout","isTTY","push","prev","terminal","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverRoot","getMetroServerRoot","isWorkspace","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","serverComponentsEnabled","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","terminalReporter","MetroTerminalReporter","configPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resolvedConfig","resolveConfig","defaultConfig","getDefaultConfig","isEmpty","mergeConfig","resetCache","maxWorkers","server","port","watchFolders","includes","reporter","update","transformer","extendsBabelConfigPath","enableBabelRCLookup","resolveBabelrcName","onDemandFilesystem","resolver","unstable_onDemandFilesystem","useWatchman","globalThis","__requireCycleIgnorePatterns","requireCycleIgnorePatterns","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reduceLogs","shouldReduceLogs","reactCompilerEnabled","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","path","exporting","flags","serverActions","serverComponents","optimizeGraph","treeshaking","logbox","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","tls","secureServerOptions","key","cert","ca","requestCert","watch","address","hmrServer","replaceMetroFileMap","runServer","host","mockServer","atlas","EXPO_ATLAS","workers","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","patchTransformFileForPackedMaps","patchMetroSourceMapStringForPackedMaps","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","sort","a","b","hmrJSBundle","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","formattedError","messageSocket","split","sep","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;QAyCaA;eAAAA;;QA8TSC;eAAAA;;QAuUNC;eAAAA;;QAxfMC;eAAAA;;;;yBAtLqB;;;;;;;yBACR;;;;;;;gEAOD;;;;;;;gEAEF;;;;;;;yBACyB;;;;;;;yBAChC;;;;;;;yBAEQ;;;;;;;yBACe;;;;;;;yBACO;;;;;;;yBACpB;;;;;;;gEACjB;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;mCACF;6BACH;uCACK;uCACA;+BACc;wCACR;wBACH;qBACrB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAG7B,MAAMH,QAAQI,IAAAA,cAAM,EAAC,SAAS,CAACC,IAAM;QAC1CA,EAAEL,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AAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAC7C,QAAG,CAACiM,EAAE;AAChB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/instantiateMetro.ts"],"sourcesContent":["import { type ExpoConfig, getConfig } from '@expo/config';\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { Reporter } from '@expo/metro/metro';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ReadOnlyGraph } from '@expo/metro/metro/DeltaBundler';\nimport type { TransformOptions } from '@expo/metro/metro/DeltaBundler/Worker';\nimport type { Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport type MetroHmrServer from '@expo/metro/metro/HmrServer';\nimport RevisionNotFoundError from '@expo/metro/metro/IncrementalBundler/RevisionNotFoundError';\nimport type MetroServer from '@expo/metro/metro/Server';\nimport formatBundlingError from '@expo/metro/metro/lib/formatBundlingError';\nimport { mergeConfig, resolveConfig, type ConfigT } from '@expo/metro/metro-config';\nimport { Terminal } from '@expo/metro/metro-core';\nimport type { createStableModuleIdFactory } from '@expo/metro-config';\nimport { getDefaultConfig } from '@expo/metro-config';\nimport { patchTransformFileForPackedMaps } from '@expo/metro-config/build/serializer/packedMap';\nimport { patchMetroSourceMapStringForPackedMaps } from '@expo/metro-config/build/serializer/sourceMap';\nimport { resolveBabelrcName } from '@expo/metro-config/exports';\nimport chalk from 'chalk';\nimport type http from 'http';\nimport path from 'path';\n\nimport { createDevToolsPluginWebsocketEndpoint } from './DevToolsPluginWebsocketEndpoint';\nimport type { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { MetroTerminalReporter } from './MetroTerminalReporter';\nimport { replaceMetroFileMap } from './createFileMap-fork';\nimport { attachAtlasAsync } from './debugging/attachAtlas';\nimport { createDebugMiddleware } from './debugging/createDebugMiddleware';\nimport { createMetroMiddleware } from './dev-server/createMetroMiddleware';\nimport { runServer, type ServerAddressInfo, type SecureServerOptions } from './runServer-fork';\nimport { withMetroMultiPlatformAsync } from './withMetroMultiPlatform';\nimport { events, shouldReduceLogs } from '../../../events';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { createCorsMiddleware } from '../middleware/CorsMiddleware';\nimport { createJsInspectorMiddleware } from '../middleware/inspector/createJsInspectorMiddleware';\nimport { prependMiddleware } from '../middleware/mutations';\nimport { getPlatformBundlers } from '../platformBundlers';\n\n// prettier-ignore\nexport const event = events('metro', (t) => [\n t.event<'config', {\n serverRoot: string;\n projectRoot: string;\n exporting: boolean;\n flags: {\n autolinkingModuleResolution: boolean;\n serverActions: boolean;\n serverComponents: boolean;\n reactCompiler: boolean;\n optimizeGraph?: boolean;\n treeshaking?: boolean;\n logbox?: boolean;\n };\n }>(),\n t.event<'instantiate', {\n atlas: boolean;\n workers: number | null;\n host: string | null;\n port: number | null;\n }>(),\n]);\n\n// NOTE(@kitten): We pass a custom createStableModuleIdFactory function into the Metro module ID factory sometimes\ninterface MetroServerWithModuleIdMod extends MetroServer {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\ninterface MetroHmrServerWithModuleIdMod extends MetroHmrServer<MetroHmrClient> {\n _createModuleId: ReturnType<typeof createStableModuleIdFactory> & ((path: string) => number);\n}\n\n// From expo/dev-server but with ability to use custom logger.\ntype MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\n// TODO(@kitten): We assign this here to run server-side code bundled by metro\n// It's not isolated into a worker thread yet\n// Check `metro-require/require.ts` for how this setting is used\ndeclare namespace globalThis {\n let __requireCycleIgnorePatterns: readonly RegExp[] | undefined;\n}\n\nfunction asWritable<T>(input: T): { -readonly [K in keyof T]: T[K] } {\n return input;\n}\n\n/**\n * Extends Metro's Terminal to intercept all console methods so they don't\n * corrupt the progress bar status lines.\n *\n * console.log/info are routed through terminal.log() (stdout, managed).\n * console.warn/error are routed through logStderr() which clears the\n * status from stdout before writing to stderr, then restores it.\n * Without this, unmanaged stderr writes shift the cursor and cause\n * progress bars to get stuck as permanent output.\n */\nclass LogRespectingTerminal extends Terminal {\n #stderrQueue: string[] = [];\n #drainingStderr = false;\n\n constructor(stream: import('node:net').Socket | import('node:stream').Writable) {\n super(stream, { ttyPrint: true });\n\n const sendLog = (...msg: any[]) => {\n if (!msg.length) {\n this.log('');\n } else {\n const [format, ...args] = msg;\n this.log(format, ...args);\n }\n // Flush the logs to the terminal immediately so logs at the end of the process are not lost.\n this.flush();\n };\n\n const sendStderr = (...msg: any[]) => {\n if (!msg.length) {\n this.logStderr('');\n } else {\n const [format, ...args] = msg;\n this.logStderr(require('util').format(format, ...args));\n }\n };\n\n console.log = sendLog;\n console.info = sendLog;\n console.warn = sendStderr;\n console.error = sendStderr;\n\n // NOTE(@kitten): We flush the stderr queue immediately when we're about to exit\n process.on('exit', () => {\n if (!this.#drainingStderr && this.#stderrQueue.length) {\n this.#drainingStderr = true;\n this.status('');\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n }\n });\n }\n\n /** Write to stderr without corrupting Terminal's cursor tracking. */\n logStderr(line: string): void {\n if (!(process.stdout as any).isTTY) {\n process.stderr.write(line + '\\n');\n return;\n }\n this.#stderrQueue.push(line);\n this.#drainStderr();\n }\n\n async #drainStderr(): Promise<void> {\n if (this.#drainingStderr) return;\n this.#drainingStderr = true;\n\n while (this.#stderrQueue.length > 0) {\n // Clear status, flush to ensure it's removed from screen\n const prev = this.status('');\n await this.flush();\n\n // Write to stderr while status is cleared\n const lines = this.#stderrQueue.splice(0);\n process.stderr.write(lines.join('\\n') + '\\n');\n\n // Restore status\n this.status(prev);\n }\n\n this.#drainingStderr = false;\n }\n}\n\n// Share one instance of Terminal for all instances of Metro.\nconst terminal = new LogRespectingTerminal(process.stdout);\n\ninterface LoadMetroConfigOptions {\n maxWorkers?: number;\n port?: number;\n reporter?: Reporter;\n resetCache?: boolean;\n}\n\nexport async function loadMetroConfigAsync(\n projectRoot: string,\n options: LoadMetroConfigOptions,\n {\n exp,\n isExporting,\n getMetroBundler,\n }: { exp: ExpoConfig; isExporting: boolean; getMetroBundler: () => Bundler }\n) {\n let reportEvent: ((event: any) => void) | undefined;\n\n // We're resolving a monorepo root, higher up than the `projectRoot`. If this\n // folder is different (presumably a parent) we're in a monorepo\n const serverRoot = getMetroServerRoot(projectRoot);\n const isWorkspace = serverRoot !== projectRoot;\n\n // Autolinking Module Resolution will be enabled by default when we're in a monorepo\n const autolinkingModuleResolutionEnabled =\n exp.experiments?.autolinkingModuleResolution ?? isWorkspace;\n\n const serverActionsEnabled =\n exp.experiments?.reactServerFunctions ?? env.EXPO_UNSTABLE_SERVER_FUNCTIONS;\n const serverComponentsEnabled = !!exp.experiments?.reactServerComponentRoutes;\n if (serverActionsEnabled) {\n process.env.EXPO_UNSTABLE_SERVER_FUNCTIONS = '1';\n }\n\n // NOTE: Enable all the experimental Metro flags when RSC is enabled.\n if (serverComponentsEnabled || serverActionsEnabled) {\n process.env.EXPO_USE_METRO_REQUIRE = '1';\n }\n\n if (exp.experiments?.reactCanary) {\n Log.warn(`React 19 is enabled by default. Remove unused experiments.reactCanary flag.`);\n }\n\n const terminalReporter = new MetroTerminalReporter(serverRoot, terminal);\n\n // NOTE: Allow external tools to override the metro config. This is considered internal and unstable\n const configPath = env.EXPO_OVERRIDE_METRO_CONFIG ?? undefined;\n const resolvedConfig = await resolveConfig(configPath, projectRoot);\n const defaultConfig = getDefaultConfig(projectRoot);\n\n let config: ConfigT = resolvedConfig.isEmpty\n ? defaultConfig\n : await mergeConfig(defaultConfig, resolvedConfig.config);\n\n // Set the watchfolders to include the projectRoot, as Metro assumes this\n // Force-override the reporter\n config = {\n ...config,\n\n // See: `overrideConfigWithArguments` https://github.com/facebook/metro/blob/5059e26/packages/metro-config/src/loadConfig.js#L274-L339\n // Compare to `LoadOptions` type (disregard `reporter` as we don't expose this)\n resetCache: !!options.resetCache,\n maxWorkers: options.maxWorkers ?? config.maxWorkers,\n server: {\n ...config.server,\n port: options.port ?? config.server.port,\n },\n\n watchFolders: !config.watchFolders.includes(config.projectRoot)\n ? [config.projectRoot, ...config.watchFolders]\n : config.watchFolders,\n reporter: {\n update(event) {\n terminalReporter.update(event);\n if (reportEvent) {\n reportEvent(event);\n }\n },\n },\n };\n\n // NOTE(@kitten): Pass a hint to the transformer on where to find the Babel config\n asWritable(config.transformer).extendsBabelConfigPath =\n config.transformer.enableBabelRCLookup !== false ? resolveBabelrcName(projectRoot) : undefined;\n\n // On-Demand Filesystem is enabled by default\n // TODO(@kitten): Add to config-types JSON schema\n const onDemandFilesystem = exp.experiments?.onDemandFilesystem ?? true;\n asWritable(config.resolver).unstable_onDemandFilesystem = onDemandFilesystem;\n\n // NOTE(@kitten): `useWatchman` is currently enabled by default, but it also disables `forceNodeFilesystemAPI`.\n // If we instead set it to the special value `null`, it gets enables but also bypasses the \"native find\" codepath,\n // which is slower than just using the Node filesystem API\n // See: https://github.com/facebook/metro/blob/b9c243f/packages/metro-file-map/src/index.js#L326\n // See: https://github.com/facebook/metro/blob/b9c243f/packages/metro/src/node-haste/DependencyGraph/createFileMap.js#L109\n if (config.resolver.useWatchman === true) {\n asWritable(config.resolver).useWatchman = null as any;\n }\n\n globalThis.__requireCycleIgnorePatterns = config.resolver?.requireCycleIgnorePatterns;\n\n if (isExporting) {\n // This token will be used in the asset plugin to ensure the path is correct for writing locally.\n asWritable(config.transformer).publicPath = `/assets?export_path=${\n (exp.experiments?.baseUrl ?? '') + '/assets'\n }`;\n } else {\n asWritable(config.transformer).publicPath = '/assets/?unstable_path=.';\n }\n\n const platformBundlers = getPlatformBundlers(projectRoot, exp);\n const reduceLogs = shouldReduceLogs();\n\n const reactCompilerEnabled = !!exp.experiments?.reactCompiler;\n if (!reduceLogs && reactCompilerEnabled) {\n Log.log(chalk.gray`React Compiler enabled`);\n }\n\n if (!reduceLogs && autolinkingModuleResolutionEnabled) {\n Log.log(chalk.gray`Expo Autolinking module resolution enabled`);\n }\n\n if (env.EXPO_UNSTABLE_TREE_SHAKING && !env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n throw new CommandError(\n 'EXPO_UNSTABLE_TREE_SHAKING requires EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH to be enabled.'\n );\n }\n\n if (!reduceLogs && env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH) {\n Log.warn(`Experimental bundle optimization is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_TREE_SHAKING) {\n Log.warn(`Experimental tree shaking is enabled.`);\n }\n if (!reduceLogs && env.EXPO_UNSTABLE_LOG_BOX) {\n Log.warn(`Experimental Expo LogBox is enabled.`);\n }\n\n if (!reduceLogs && serverActionsEnabled) {\n Log.warn(\n `React Server Functions (beta) are enabled. Route rendering mode: ${exp.experiments?.reactServerComponentRoutes ? 'server' : 'client'}`\n );\n }\n\n config = await withMetroMultiPlatformAsync(projectRoot, {\n config,\n exp,\n platformBundlers,\n serverRoot,\n isTsconfigPathsEnabled: exp.experiments?.tsconfigPaths ?? true,\n isAutolinkingResolverEnabled: autolinkingModuleResolutionEnabled,\n isExporting,\n isNamedRequiresEnabled: env.EXPO_USE_METRO_REQUIRE,\n isReactServerComponentsEnabled: serverComponentsEnabled,\n getMetroBundler,\n });\n\n event('config', {\n serverRoot: event.path(serverRoot),\n projectRoot: event.path(projectRoot),\n exporting: isExporting,\n flags: {\n autolinkingModuleResolution: autolinkingModuleResolutionEnabled,\n serverActions: serverActionsEnabled,\n serverComponents: serverComponentsEnabled,\n reactCompiler: reactCompilerEnabled,\n optimizeGraph: env.EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH,\n treeshaking: env.EXPO_UNSTABLE_TREE_SHAKING,\n logbox: env.EXPO_UNSTABLE_LOG_BOX,\n },\n });\n\n return {\n config,\n setEventReporter: (logger: (event: any) => void) => (reportEvent = logger),\n reporter: terminalReporter,\n };\n}\n\ninterface InstantiateMetroConfigOptions extends LoadMetroConfigOptions {\n host?: string;\n}\n\n/** The most generic possible setup for Metro bundler. */\nexport async function instantiateMetroAsync(\n metroBundler: MetroBundlerDevServer,\n options: InstantiateMetroConfigOptions,\n {\n isExporting,\n exp = getConfig(metroBundler.projectRoot, {\n skipSDKVersionRequirement: true,\n }).exp,\n }: { isExporting: boolean; exp?: ExpoConfig }\n): Promise<{\n metro: MetroServer;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n server: http.Server;\n address: ServerAddressInfo | null;\n middleware: any;\n messageSocket: MessageSocket;\n}> {\n const projectRoot = metroBundler.projectRoot;\n const getMetroBundler = () => metro.getBundler().getBundler();\n\n const {\n config: metroConfig,\n setEventReporter,\n reporter,\n } = await loadMetroConfigAsync(projectRoot, options, {\n exp,\n isExporting,\n getMetroBundler,\n });\n\n // Create the core middleware stack for Metro, including websocket listeners\n const { middleware, messagesSocket, eventsSocket, websocketEndpoints } = createMetroMiddleware(\n metroConfig,\n { getMetroBundler }\n );\n\n // Get local URL to Metro bundler server (typically configured as 127.0.0.1:8081)\n const serverBaseUrl = metroBundler\n .getUrlCreator()\n .constructUrl({ scheme: 'http', hostType: 'localhost' });\n\n if (!isExporting) {\n // Enable correct CORS headers for Expo Router features\n prependMiddleware(middleware, createCorsMiddleware(exp));\n\n // Enable debug middleware for CDP-related debugging\n const { debugMiddleware, debugWebsocketEndpoints } = createDebugMiddleware({\n serverBaseUrl,\n reporter,\n });\n Object.assign(websocketEndpoints, debugWebsocketEndpoints);\n middleware.use(debugMiddleware);\n middleware.use('/_expo/debugger', createJsInspectorMiddleware());\n\n // TODO(cedric): `enhanceMiddleware` is deprecated, but is currently used to unify the middleware stacks\n // See: https://github.com/facebook/metro/commit/22e85fde85ec454792a1b70eba4253747a2587a9\n // See: https://github.com/facebook/metro/commit/d0d554381f119bb80ab09dbd6a1d310b54737e52\n const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;\n asWritable(metroConfig.server).enhanceMiddleware = (\n metroMiddleware: any,\n server: MetroServer\n ) => {\n if (customEnhanceMiddleware) {\n metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);\n }\n return middleware.use(metroMiddleware);\n };\n\n const devtoolsWebsocketEndpoints = createDevToolsPluginWebsocketEndpoint();\n Object.assign(websocketEndpoints, devtoolsWebsocketEndpoints);\n }\n\n // Attach Expo Atlas if enabled\n await attachAtlasAsync({\n isExporting,\n exp,\n projectRoot,\n middleware,\n metroConfig,\n // NOTE(cedric): reset the Atlas file once, and reuse it for static exports\n resetAtlasFile: isExporting,\n });\n\n // Support HTTPS based on the metro's tls server config\n // TODO(@kitten): Remove cast once `@expo/metro` is updated to a Metro version that supports the tls config\n const tls = (metroConfig.server as typeof metroConfig.server & { tls?: SecureServerOptions })\n ?.tls;\n const secureServerOptions = tls\n ? {\n key: tls.key,\n cert: tls.cert,\n ca: tls.ca,\n requestCert: tls.requestCert,\n }\n : undefined;\n\n const watch = !isExporting && isWatchEnabled();\n\n const { address, server, hmrServer, metro } = await replaceMetroFileMap(() => {\n return runServer(\n metroBundler,\n metroConfig,\n {\n host: options.host,\n websocketEndpoints,\n watch,\n secureServerOptions,\n },\n {\n mockServer: isExporting,\n }\n );\n });\n\n event('instantiate', {\n atlas: env.EXPO_ATLAS,\n workers: metroConfig.maxWorkers ?? null,\n host: address?.address ?? null,\n port: address?.port ?? null,\n });\n\n // Patch transform file to remove inconvenient customTransformOptions which are only used in single well-known files.\n const originalTransformFile = metro\n .getBundler()\n .getBundler()\n .transformFile.bind(metro.getBundler().getBundler());\n\n metro.getBundler().getBundler().transformFile = async function (\n filePath: string,\n transformOptions: TransformOptions,\n fileBuffer?: Buffer\n ) {\n return originalTransformFile(\n filePath,\n pruneCustomTransformOptions(\n projectRoot,\n filePath,\n // Clone the options so we don't mutate the original.\n {\n ...transformOptions,\n customTransformOptions: {\n __proto__: null,\n ...transformOptions.customTransformOptions,\n },\n }\n ),\n fileBuffer\n );\n };\n\n // Layered on top of the prune patch above. Both fresh worker results\n // and cache hits flow through `Bundler.transformFile`, so wrapping\n // here covers both.\n patchTransformFileForPackedMaps(metro.getBundler().getBundler());\n patchMetroSourceMapStringForPackedMaps();\n\n setEventReporter(eventsSocket.reportMetroEvent);\n\n // This function ensures that modules in source maps are sorted in the same\n // order as in a plain JS bundle.\n metro._getSortedModules = function (this: MetroServerWithModuleIdMod, graph: ReadOnlyGraph) {\n const modules = [...graph.dependencies.values()];\n\n const ctx = {\n // TODO(@kitten): Increase type-safety here\n platform: graph.transformOptions.platform!,\n environment: graph.transformOptions.customTransformOptions?.environment,\n };\n // Assign IDs to modules in a consistent order\n for (const module of modules) {\n this._createModuleId(module.path, ctx);\n }\n // Sort by IDs\n return modules.sort(\n (a, b) => this._createModuleId(a.path, ctx) - this._createModuleId(b.path, ctx)\n );\n };\n\n if (hmrServer) {\n let hmrJSBundle:\n | typeof import('@expo/metro-config/build/serializer/fork/hmrJSBundle').default\n | typeof import('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle').default;\n\n try {\n hmrJSBundle = require('@expo/metro-config/build/serializer/fork/hmrJSBundle').default;\n } catch {\n // TODO: Add fallback for monorepo tests up until the fork is merged.\n Log.warn('Failed to load HMR serializer from @expo/metro-config, using fallback version.');\n hmrJSBundle = require('@expo/metro/metro/DeltaBundler/Serializers/hmrJSBundle');\n }\n\n // Patch HMR Server to send more info to the `_createModuleId` function for deterministic module IDs and add support for serializing HMR updates the same as all other bundles.\n hmrServer._prepareMessage = async function (\n this: MetroHmrServerWithModuleIdMod,\n group,\n options,\n changeEvent\n ) {\n // Fork of https://github.com/facebook/metro/blob/3b3e0aaf725cfa6907bf2c8b5fbc0da352d29efe/packages/metro/src/HmrServer.js#L327-L393\n // with patch for `_createModuleId`.\n const logger = !options.isInitialUpdate ? changeEvent?.logger : null;\n try {\n const revPromise = this._bundler.getRevision(group.revisionId);\n if (!revPromise) {\n return {\n type: 'error',\n body: formatBundlingError(new RevisionNotFoundError(group.revisionId)),\n };\n }\n logger?.point('updateGraph_start');\n const { revision, delta } = await this._bundler.updateGraph(await revPromise, false);\n logger?.point('updateGraph_end');\n this._clientGroups.delete(group.revisionId);\n group.revisionId = revision.id;\n for (const client of group.clients) {\n client.revisionIds = client.revisionIds.filter(\n (revisionId) => revisionId !== group.revisionId\n );\n client.revisionIds.push(revision.id);\n }\n this._clientGroups.set(group.revisionId, group);\n logger?.point('serialize_start');\n // NOTE(EvanBacon): This is the patch\n const moduleIdContext = {\n // TODO(@kitten): Increase type-safety here\n platform: revision.graph.transformOptions.platform!,\n environment: revision.graph.transformOptions.customTransformOptions?.environment,\n };\n const hmrUpdate = hmrJSBundle(delta, revision.graph, {\n clientUrl: group.clientUrl,\n // NOTE(EvanBacon): This is also the patch\n createModuleId: (moduleId: string) => {\n return this._createModuleId(moduleId, moduleIdContext);\n },\n includeAsyncPaths: group.graphOptions.lazy,\n projectRoot: this._config.projectRoot,\n serverRoot: this._config.server.unstable_serverRoot ?? this._config.projectRoot,\n });\n logger?.point('serialize_end');\n return {\n type: 'update',\n body: {\n revisionId: revision.id,\n isInitialUpdate: options.isInitialUpdate,\n ...hmrUpdate,\n },\n };\n } catch (error: any) {\n const formattedError = formatBundlingError(error);\n this._config.reporter.update({\n type: 'bundling_error',\n error,\n });\n return {\n type: 'error',\n body: formattedError,\n };\n }\n };\n }\n\n return {\n metro,\n hmrServer,\n server,\n middleware,\n messageSocket: messagesSocket,\n address,\n };\n}\n\n// TODO: Fork the entire transform function so we can simply regex the file contents for keywords instead.\nfunction pruneCustomTransformOptions(\n projectRoot: string,\n filePath: string,\n transformOptions: TransformOptions\n): TransformOptions {\n // Normalize the filepath for cross platform checking.\n filePath = filePath.split(path.sep).join('/');\n\n if (\n transformOptions.customTransformOptions?.dom &&\n // The only generated file that needs the dom root is `expo/dom/entry.js`\n !filePath.match(/expo\\/dom\\/entry\\.js$/)\n ) {\n // Clear the dom root option if we aren't transforming the magic entry file, this ensures\n // that cached artifacts from other DOM component bundles can be reused.\n transformOptions.customTransformOptions.dom = 'true';\n }\n\n const routerRoot = transformOptions.customTransformOptions?.routerRoot;\n if (typeof routerRoot === 'string') {\n const isRouterEntry = /\\/expo-router\\/_ctx/.test(filePath);\n // The router root is used all over expo-router (`process.env.EXPO_ROUTER_ABS_APP_ROOT`, `process.env.EXPO_ROUTER_APP_ROOT`) so we'll just ignore the entire package.\n const isRouterModule = /\\/expo-router\\/build\\//.test(filePath);\n // Any page/router inside the expo-router app folder may access the `routerRoot` option to determine whether it's in the app folder\n const resolvedRouterRoot = path.resolve(projectRoot, routerRoot).split(path.sep).join('/');\n const isRouterRoute = path.isAbsolute(filePath) && filePath.startsWith(resolvedRouterRoot);\n\n // In any other file than the above, we enforce that we mustn't use `routerRoot`, and set it to an arbitrary value here (the default)\n // to ensure that the cache never invalidates when this value is changed\n if (!isRouterEntry && !isRouterModule && !isRouterRoute) {\n transformOptions.customTransformOptions!.routerRoot = 'app';\n }\n }\n\n if (\n transformOptions.customTransformOptions?.asyncRoutes &&\n // The async routes settings are also used in `expo-router/_ctx.ios.js` (and other platform variants) via `process.env.EXPO_ROUTER_IMPORT_MODE`\n !(filePath.match(/\\/expo-router\\/_ctx/) || filePath.match(/\\/expo-router\\/build\\//))\n ) {\n delete transformOptions.customTransformOptions.asyncRoutes;\n }\n\n if (\n transformOptions.customTransformOptions?.clientBoundaries &&\n // The client boundaries are only used in `expo/virtual/rsc.js` for production RSC exports.\n !filePath.match(/\\/expo\\/virtual\\/rsc\\.js$/)\n ) {\n delete transformOptions.customTransformOptions.clientBoundaries;\n }\n\n return transformOptions;\n}\n\n/**\n * Simplify and communicate if Metro is running without watching file updates,.\n * Exposed for testing.\n */\nexport function isWatchEnabled() {\n if (env.CI) {\n Log.log(\n chalk`Metro is running in CI mode, reloads are disabled. Remove {bold CI=true} to enable watch mode.`\n );\n }\n\n return !env.CI;\n}\n"],"names":["event","instantiateMetroAsync","isWatchEnabled","loadMetroConfigAsync","events","t","asWritable","input","LogRespectingTerminal","Terminal","stream","ttyPrint","sendLog","msg","length","log","format","args","flush","sendStderr","logStderr","require","console","info","warn","error","process","on","status","lines","splice","stderr","write","join","line","stdout","isTTY","push","prev","terminal","projectRoot","options","exp","isExporting","getMetroBundler","config","reportEvent","serverRoot","getMetroServerRoot","isWorkspace","autolinkingModuleResolutionEnabled","experiments","autolinkingModuleResolution","serverActionsEnabled","reactServerFunctions","env","EXPO_UNSTABLE_SERVER_FUNCTIONS","serverComponentsEnabled","reactServerComponentRoutes","EXPO_USE_METRO_REQUIRE","reactCanary","Log","terminalReporter","MetroTerminalReporter","configPath","EXPO_OVERRIDE_METRO_CONFIG","undefined","resolvedConfig","resolveConfig","defaultConfig","getDefaultConfig","isEmpty","mergeConfig","resetCache","maxWorkers","server","port","watchFolders","includes","reporter","update","transformer","extendsBabelConfigPath","enableBabelRCLookup","resolveBabelrcName","onDemandFilesystem","resolver","unstable_onDemandFilesystem","useWatchman","globalThis","__requireCycleIgnorePatterns","requireCycleIgnorePatterns","publicPath","baseUrl","platformBundlers","getPlatformBundlers","reduceLogs","shouldReduceLogs","reactCompilerEnabled","reactCompiler","chalk","gray","EXPO_UNSTABLE_TREE_SHAKING","EXPO_UNSTABLE_METRO_OPTIMIZE_GRAPH","CommandError","EXPO_UNSTABLE_LOG_BOX","withMetroMultiPlatformAsync","isTsconfigPathsEnabled","tsconfigPaths","isAutolinkingResolverEnabled","isNamedRequiresEnabled","isReactServerComponentsEnabled","path","exporting","flags","serverActions","serverComponents","optimizeGraph","treeshaking","logbox","setEventReporter","logger","metroBundler","getConfig","skipSDKVersionRequirement","metroConfig","metro","getBundler","middleware","messagesSocket","eventsSocket","websocketEndpoints","createMetroMiddleware","serverBaseUrl","getUrlCreator","constructUrl","scheme","hostType","prependMiddleware","createCorsMiddleware","debugMiddleware","debugWebsocketEndpoints","createDebugMiddleware","Object","assign","use","createJsInspectorMiddleware","customEnhanceMiddleware","enhanceMiddleware","metroMiddleware","devtoolsWebsocketEndpoints","createDevToolsPluginWebsocketEndpoint","attachAtlasAsync","resetAtlasFile","tls","secureServerOptions","key","cert","ca","requestCert","watch","address","hmrServer","replaceMetroFileMap","runServer","host","mockServer","atlas","EXPO_ATLAS","workers","originalTransformFile","transformFile","bind","filePath","transformOptions","fileBuffer","pruneCustomTransformOptions","customTransformOptions","__proto__","patchTransformFileForPackedMaps","patchMetroSourceMapStringForPackedMaps","reportMetroEvent","_getSortedModules","graph","modules","dependencies","values","ctx","platform","environment","module","_createModuleId","sort","a","b","hmrJSBundle","default","_prepareMessage","group","changeEvent","isInitialUpdate","revision","revPromise","_bundler","getRevision","revisionId","type","body","formatBundlingError","RevisionNotFoundError","point","delta","updateGraph","_clientGroups","delete","id","client","clients","revisionIds","filter","set","moduleIdContext","hmrUpdate","clientUrl","createModuleId","moduleId","includeAsyncPaths","graphOptions","lazy","_config","unstable_serverRoot","formattedError","messageSocket","split","sep","dom","match","routerRoot","isRouterEntry","test","isRouterModule","resolvedRouterRoot","resolve","isRouterRoute","isAbsolute","startsWith","asyncRoutes","clientBoundaries","CI"],"mappings":";;;;;;;;;;;QAyCaA;eAAAA;;QA8TSC;eAAAA;;QAyUNC;eAAAA;;QA1fMC;eAAAA;;;;yBAtLqB;;;;;;;yBACR;;;;;;;gEAOD;;;;;;;gEAEF;;;;;;;yBACyB;;;;;;;yBAChC;;;;;;;yBAEQ;;;;;;;yBACe;;;;;;;yBACO;;;;;;;yBACpB;;;;;;;gEACjB;;;;;;;gEAED;;;;;;iDAEqC;uCAEhB;mCACF;6BACH;uCACK;uCACA;+BACsC;wCAChC;wBACH;qBACrB;qBACA;wBACS;gCACQ;6CACO;2BACV;kCACE;;;;;;AAG7B,MAAMH,QAAQI,IAAAA,cAAM,EAAC,SAAS,CAACC,IAAM;QAC1CA,EAAEL,KAAK;QAcPK,EAAEL,KAAK;KAMR;AAsBD,SAASM,WAAcC,KAAQ;IAC7B,OAAOA;AACT;AAEA;;;;;;;;;CASC,GACD,MAAMC,8BAA8BC,qBAAQ;IAC1C,CAAA,WAAY,CAAgB;IAC5B,CAAA,cAAe,CAAS;IAExB,YAAYC,MAAkE,CAAE;QAC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AAI,OAAOA,eAAe,UAAU;QAClC,MAAMC,gBAAgB,sBAAsBC,IAAI,CAAClE;QACjD,qKAAqK;QACrK,MAAMmE,iBAAiB,yBAAyBD,IAAI,CAAClE;QACrD,mIAAmI;QACnI,MAAMoE,qBAAqBjI,eAAI,CAACkI,OAAO,CAAC1M,aAAaqM,YAAYJ,KAAK,CAACzH,eAAI,CAAC0H,GAAG,EAAEzM,IAAI,CAAC;QACtF,MAAMkN,gBAAgBnI,eAAI,CAACoI,UAAU,CAACvE,aAAaA,SAASwE,UAAU,CAACJ;QAEvE,qIAAqI;QACrI,wEAAwE;QACxE,IAAI,CAACH,iBAAiB,CAACE,kBAAkB,CAACG,eAAe;YACvDrE,iBAAiBG,sBAAsB,CAAE4D,UAAU,GAAG;QACxD;IACF;IAEA,IACE/D,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCwE,WAAW,KACpD,+IAA+I;IAC/I,CAAEzE,CAAAA,SAAS+D,KAAK,CAAC,0BAA0B/D,SAAS+D,KAAK,CAAC,yBAAwB,GAClF;QACA,OAAO9D,iBAAiBG,sBAAsB,CAACqE,WAAW;IAC5D;IAEA,IACExE,EAAAA,4CAAAA,iBAAiBG,sBAAsB,qBAAvCH,0CAAyCyE,gBAAgB,KACzD,2FAA2F;IAC3F,CAAC1E,SAAS+D,KAAK,CAAC,8BAChB;QACA,OAAO9D,iBAAiBG,sBAAsB,CAACsE,gBAAgB;IACjE;IAEA,OAAOzE;AACT;AAMO,SAAS5K;IACd,IAAIqD,QAAG,CAACiM,EAAE,EAAE;QACV3L,QAAG,CAAC9C,GAAG,CACLqF,IAAAA,gBAAK,CAAA,CAAC,8FAA8F,CAAC;IAEzG;IAEA,OAAO,CAAC7C,QAAG,CAACiM,EAAE;AAChB"}
|
|
@@ -82,9 +82,12 @@ const runServer = async (_metroBundler, config, { hasReducedPerformance = false,
|
|
|
82
82
|
}
|
|
83
83
|
const serverApp = middleware;
|
|
84
84
|
let httpServer;
|
|
85
|
+
let protocol;
|
|
85
86
|
if (secureServerOptions != null) {
|
|
87
|
+
protocol = 'https';
|
|
86
88
|
httpServer = _https().default.createServer(secureServerOptions, serverApp);
|
|
87
89
|
} else {
|
|
90
|
+
protocol = 'http';
|
|
88
91
|
httpServer = _http().default.createServer(serverApp);
|
|
89
92
|
}
|
|
90
93
|
httpServer.on('error', (error)=>{
|
|
@@ -160,8 +163,14 @@ const runServer = async (_metroBundler, config, { hasReducedPerformance = false,
|
|
|
160
163
|
}
|
|
161
164
|
});
|
|
162
165
|
const address = httpServer.address();
|
|
166
|
+
(0, _assert().default)(address == null || typeof address === 'object', 'Expected httpServer.address() to be an object');
|
|
163
167
|
resolve({
|
|
164
|
-
address:
|
|
168
|
+
address: {
|
|
169
|
+
protocol,
|
|
170
|
+
address: (address == null ? void 0 : address.address) ?? host ?? 'localhost',
|
|
171
|
+
family: (address == null ? void 0 : address.family) ?? 'ipv4',
|
|
172
|
+
port: (address == null ? void 0 : address.port) ?? config.server.port
|
|
173
|
+
},
|
|
165
174
|
server: httpServer,
|
|
166
175
|
hmrServer,
|
|
167
176
|
metro: metroServer
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/runServer-fork.ts"],"sourcesContent":["// Copyright © 2023 650 Industries.\n// Copyright (c) Meta Platforms, Inc. and affiliates.\n//\n// Forks https://github.com/facebook/metro/blob/b80d9a0f638ee9fb82ff69cd3c8d9f4309ca1da2/packages/metro/src/index.flow.js#L57\n// and adds the ability to access the bundler instance.\nimport { createConnectMiddleware } from '@expo/metro/metro';\nimport type { RunServerOptions } from '@expo/metro/metro';\nimport MetroHmrServer, { type Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport type Server from '@expo/metro/metro/Server';\nimport createWebsocketServer from '@expo/metro/metro/lib/createWebsocketServer';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport assert from 'assert';\nimport http from 'http';\nimport https from 'https';\nimport type { AddressInfo } from 'net';\nimport type { WebSocketServer } from 'ws';\n\nimport type { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { Log } from '../../../log';\nimport type { ConnectAppType } from '../middleware/server.types';\n\nexport interface SecureServerOptions {\n readonly key: string | Buffer;\n readonly cert: string | Buffer;\n readonly ca: string | Buffer;\n readonly requestCert: boolean;\n}\n\ninterface RunServerOptionsFork {\n hasReducedPerformance?: boolean;\n host?: string;\n onError?($$PARAM_0$$: Error & { code?: string }): void;\n onReady?(server: http.Server | https.Server): void;\n onClose?(): void;\n websocketEndpoints?: RunServerOptions['websocketEndpoints'];\n secureServerOptions?: SecureServerOptions;\n waitForBundler?: boolean;\n watch?: boolean;\n}\n\nexport const runServer = async (\n _metroBundler: MetroBundlerDevServer,\n config: ConfigT,\n {\n hasReducedPerformance = false,\n host,\n onError,\n onReady,\n secureServerOptions,\n websocketEndpoints = {},\n watch,\n waitForBundler = !!watch,\n }: RunServerOptionsFork,\n {\n mockServer,\n }: {\n // Use a mock server object instead of creating a real server, this is used in export cases where we want to reuse codepaths but not actually start a server.\n mockServer: boolean;\n }\n): Promise<{\n address: AddressInfo | null;\n server: http.Server | https.Server;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n metro: Server;\n}> => {\n // await earlyPortCheck(host, config.server.port);\n\n // if (secure != null || secureCert != null || secureKey != null) {\n // // eslint-disable-next-line no-console\n // console.warn(\n // chalk.inverse.yellow.bold(' DEPRECATED '),\n // 'The `secure`, `secureCert`, and `secureKey` options are now deprecated. ' +\n // 'Use the `secureServerOptions` object instead to pass options to ' +\n // \"Metro's https development server.\",\n // );\n // }\n\n const { middleware, end, metroServer } = await createConnectMiddleware(config, {\n hasReducedPerformance,\n waitForBundler,\n watch,\n });\n\n if (!mockServer) {\n assert(typeof (middleware as any).use === 'function');\n }\n const serverApp = middleware as ConnectAppType;\n\n let httpServer: http.Server | https.Server;\n\n if (secureServerOptions != null) {\n httpServer = https.createServer(secureServerOptions, serverApp);\n } else {\n httpServer = http.createServer(serverApp);\n }\n\n httpServer.on('error', (error) => {\n if ('code' in error && error.code === 'EADDRINUSE') {\n // If `Error: listen EADDRINUSE: address already in use :::8081` then print additional info\n // about the process before throwing.\n const { getRunningProcess } =\n require('../../../utils/getRunningProcess') as typeof import('../../../utils/getRunningProcess');\n getRunningProcess(config.server.port).then((info) => {\n if (info) {\n Log.error(\n `Port ${config.server.port} is busy running ${info.command} in: ${info.directory}`\n );\n }\n });\n }\n\n if (onError) {\n onError(error);\n }\n end();\n });\n\n // Disable any kind of automatic timeout behavior for incoming\n // requests in case it takes the packager more than the default\n // timeout of 120 seconds to respond to a request.\n httpServer.timeout = 0;\n\n // Extend the close method to ensure all websocket servers are closed, and connections are terminated\n const originalClose = httpServer.close.bind(httpServer);\n\n httpServer.close = function closeHttpServer(callback) {\n originalClose((err?: Error) => {\n // Always call end() to clean up Metro workers, even if the server wasn't started.\n // The 'close' event doesn't fire for servers that were never started (mockServer case),\n // so we need to call end() explicitly here.\n end();\n callback?.(err);\n });\n\n // Close all websocket servers, including possible client connections (see: https://github.com/websockets/ws/issues/2137#issuecomment-1507469375)\n for (const endpoint of Object.values(websocketEndpoints) as WebSocketServer[]) {\n endpoint.close();\n endpoint.clients.forEach((client) => client.terminate());\n }\n\n // Forcibly close active connections\n this.closeAllConnections();\n return this;\n };\n\n if (mockServer) {\n return { address: null, server: httpServer, hmrServer: null, metro: metroServer };\n }\n\n return new Promise((resolve, reject) => {\n httpServer.on('error', (error) => {\n reject(error);\n });\n\n httpServer.listen(config.server.port, host, () => {\n if (onReady) {\n onReady(httpServer);\n }\n\n const hmrServer = new MetroHmrServer(\n metroServer.getBundler(),\n metroServer.getCreateModuleId(),\n config\n );\n\n Object.assign(websocketEndpoints, {\n '/hot': createWebsocketServer({\n websocketServer: hmrServer,\n }),\n });\n\n httpServer.on('upgrade', (request, socket, head) => {\n const { pathname } = new URL(request.url!, 'http://localhost');\n if (pathname != null && websocketEndpoints[pathname]) {\n websocketEndpoints[pathname].handleUpgrade(request, socket, head, (ws) => {\n websocketEndpoints[pathname]?.emit('connection', ws, request);\n });\n } else {\n socket.destroy();\n }\n });\n\n const address = httpServer.address();\n\n resolve({\n address: address && typeof address === 'object' ? address : null,\n server: httpServer,\n hmrServer,\n metro: metroServer,\n });\n });\n });\n};\n"],"names":["runServer","_metroBundler","config","hasReducedPerformance","host","onError","onReady","secureServerOptions","websocketEndpoints","watch","waitForBundler","mockServer","middleware","end","metroServer","createConnectMiddleware","assert","use","serverApp","httpServer","https","createServer","http","on","error","code","getRunningProcess","require","server","port","then","info","Log","command","directory","timeout","originalClose","close","bind","closeHttpServer","callback","err","endpoint","Object","values","clients","forEach","client","terminate","closeAllConnections","address","hmrServer","metro","Promise","resolve","reject","listen","MetroHmrServer","getBundler","getCreateModuleId","assign","createWebsocketServer","websocketServer","request","socket","head","pathname","URL","url","handleUpgrade","ws","emit","destroy"],"mappings":"AAAA,mCAAmC;AACnC,qDAAqD;AACrD,EAAE;AACF,6HAA6H;AAC7H,uDAAuD;;;;;+BAoC1CA;;;eAAAA;;;;yBAnC2B;;;;;;;gEAEsB;;;;;;;gEAE5B;;;;;;;gEAEf;;;;;;;gEACF;;;;;;;gEACC;;;;;;qBAKE;;;;;;AAsBb,MAAMA,YAAY,OACvBC,eACAC,QACA,EACEC,wBAAwB,KAAK,EAC7BC,IAAI,EACJC,OAAO,EACPC,OAAO,EACPC,mBAAmB,EACnBC,qBAAqB,CAAC,CAAC,EACvBC,KAAK,EACLC,iBAAiB,CAAC,CAACD,KAAK,EACH,EACvB,EACEE,UAAU,EAIX;IAOD,kDAAkD;IAElD,mEAAmE;IACnE,2CAA2C;IAC3C,kBAAkB;IAClB,iDAAiD;IACjD,mFAAmF;IACnF,6EAA6E;IAC7E,6CAA6C;IAC7C,OAAO;IACP,IAAI;IAEJ,MAAM,EAAEC,UAAU,EAAEC,GAAG,EAAEC,WAAW,EAAE,GAAG,MAAMC,IAAAA,gCAAuB,EAACb,QAAQ;QAC7EC;QACAO;QACAD;IACF;IAEA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QACxB,OAAO,IAAI;IACb;IAEA,IAAItC,YAAY;QACd,OAAO;YAAEuC,SAAS;YAAMtB,QAAQT;YAAYgC,WAAW;YAAMC,OAAOtC;QAAY;IAClF;IAEA,OAAO,IAAIuC,QAAQ,CAACC,SAASC;QAC3BpC,WAAWI,EAAE,CAAC,SAAS,CAACC;YACtB+B,OAAO/B;QACT;QAEAL,WAAWqC,MAAM,CAACtD,OAAO0B,MAAM,CAACC,IAAI,EAAEzB,MAAM;YAC1C,IAAIE,SAAS;gBACXA,QAAQa;YACV;YAEA,MAAMgC,YAAY,IAAIM,CAAAA,YAAa,SAAC,CAClC3C,YAAY4C,UAAU,IACtB5C,YAAY6C,iBAAiB,IAC7BzD;YAGFyC,OAAOiB,MAAM,CAACpD,oBAAoB;gBAChC,QAAQqD,IAAAA,gCAAqB,EAAC;oBAC5BC,iBAAiBX;gBACnB;YACF;YAEAhC,WAAWI,EAAE,CAAC,WAAW,CAACwC,SAASC,QAAQC;gBACzC,MAAM,EAAEC,QAAQ,EAAE,GAAG,IAAIC,IAAIJ,QAAQK,GAAG,EAAG;gBAC3C,IAAIF,YAAY,QAAQ1D,kBAAkB,CAAC0D,SAAS,EAAE;oBACpD1D,kBAAkB,CAAC0D,SAAS,CAACG,aAAa,CAACN,SAASC,QAAQC,MAAM,CAACK;4BACjE9D;yBAAAA,+BAAAA,kBAAkB,CAAC0D,SAAS,qBAA5B1D,6BAA8B+D,IAAI,CAAC,cAAcD,IAAIP;oBACvD;gBACF,OAAO;oBACLC,OAAOQ,OAAO;gBAChB;YACF;YAEA,MAAMtB,UAAU/B,WAAW+B,OAAO;YAElCI,QAAQ;gBACNJ,SAASA,WAAW,OAAOA,YAAY,WAAWA,UAAU;gBAC5DtB,QAAQT;gBACRgC;gBACAC,OAAOtC;YACT;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/runServer-fork.ts"],"sourcesContent":["// Copyright © 2023 650 Industries.\n// Copyright (c) Meta Platforms, Inc. and affiliates.\n//\n// Forks https://github.com/facebook/metro/blob/b80d9a0f638ee9fb82ff69cd3c8d9f4309ca1da2/packages/metro/src/index.flow.js#L57\n// and adds the ability to access the bundler instance.\nimport { createConnectMiddleware } from '@expo/metro/metro';\nimport type { RunServerOptions } from '@expo/metro/metro';\nimport MetroHmrServer, { type Client as MetroHmrClient } from '@expo/metro/metro/HmrServer';\nimport type Server from '@expo/metro/metro/Server';\nimport createWebsocketServer from '@expo/metro/metro/lib/createWebsocketServer';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport assert from 'assert';\nimport http from 'http';\nimport https from 'https';\nimport type { WebSocketServer } from 'ws';\n\nimport type { MetroBundlerDevServer } from './MetroBundlerDevServer';\nimport { Log } from '../../../log';\nimport type { ConnectAppType } from '../middleware/server.types';\n\nexport interface SecureServerOptions {\n readonly key: string | Buffer;\n readonly cert: string | Buffer;\n readonly ca: string | Buffer;\n readonly requestCert: boolean;\n}\n\nexport interface ServerAddressInfo {\n protocol: 'http' | 'https';\n address: string;\n family: string;\n port: number;\n}\n\ninterface RunServerOptionsFork {\n hasReducedPerformance?: boolean;\n host?: string;\n onError?($$PARAM_0$$: Error & { code?: string }): void;\n onReady?(server: http.Server | https.Server): void;\n onClose?(): void;\n websocketEndpoints?: RunServerOptions['websocketEndpoints'];\n secureServerOptions?: SecureServerOptions;\n waitForBundler?: boolean;\n watch?: boolean;\n}\n\nexport const runServer = async (\n _metroBundler: MetroBundlerDevServer,\n config: ConfigT,\n {\n hasReducedPerformance = false,\n host,\n onError,\n onReady,\n secureServerOptions,\n websocketEndpoints = {},\n watch,\n waitForBundler = !!watch,\n }: RunServerOptionsFork,\n {\n mockServer,\n }: {\n // Use a mock server object instead of creating a real server, this is used in export cases where we want to reuse codepaths but not actually start a server.\n mockServer: boolean;\n }\n): Promise<{\n address: ServerAddressInfo | null;\n server: http.Server | https.Server;\n hmrServer: MetroHmrServer<MetroHmrClient> | null;\n metro: Server;\n}> => {\n // await earlyPortCheck(host, config.server.port);\n\n // if (secure != null || secureCert != null || secureKey != null) {\n // // eslint-disable-next-line no-console\n // console.warn(\n // chalk.inverse.yellow.bold(' DEPRECATED '),\n // 'The `secure`, `secureCert`, and `secureKey` options are now deprecated. ' +\n // 'Use the `secureServerOptions` object instead to pass options to ' +\n // \"Metro's https development server.\",\n // );\n // }\n\n const { middleware, end, metroServer } = await createConnectMiddleware(config, {\n hasReducedPerformance,\n waitForBundler,\n watch,\n });\n\n if (!mockServer) {\n assert(typeof (middleware as any).use === 'function');\n }\n const serverApp = middleware as ConnectAppType;\n\n let httpServer: http.Server | https.Server;\n let protocol: 'http' | 'https';\n\n if (secureServerOptions != null) {\n protocol = 'https';\n httpServer = https.createServer(secureServerOptions, serverApp);\n } else {\n protocol = 'http';\n httpServer = http.createServer(serverApp);\n }\n\n httpServer.on('error', (error) => {\n if ('code' in error && error.code === 'EADDRINUSE') {\n // If `Error: listen EADDRINUSE: address already in use :::8081` then print additional info\n // about the process before throwing.\n const { getRunningProcess } =\n require('../../../utils/getRunningProcess') as typeof import('../../../utils/getRunningProcess');\n getRunningProcess(config.server.port).then((info) => {\n if (info) {\n Log.error(\n `Port ${config.server.port} is busy running ${info.command} in: ${info.directory}`\n );\n }\n });\n }\n\n if (onError) {\n onError(error);\n }\n end();\n });\n\n // Disable any kind of automatic timeout behavior for incoming\n // requests in case it takes the packager more than the default\n // timeout of 120 seconds to respond to a request.\n httpServer.timeout = 0;\n\n // Extend the close method to ensure all websocket servers are closed, and connections are terminated\n const originalClose = httpServer.close.bind(httpServer);\n\n httpServer.close = function closeHttpServer(callback) {\n originalClose((err?: Error) => {\n // Always call end() to clean up Metro workers, even if the server wasn't started.\n // The 'close' event doesn't fire for servers that were never started (mockServer case),\n // so we need to call end() explicitly here.\n end();\n callback?.(err);\n });\n\n // Close all websocket servers, including possible client connections (see: https://github.com/websockets/ws/issues/2137#issuecomment-1507469375)\n for (const endpoint of Object.values(websocketEndpoints) as WebSocketServer[]) {\n endpoint.close();\n endpoint.clients.forEach((client) => client.terminate());\n }\n\n // Forcibly close active connections\n this.closeAllConnections();\n return this;\n };\n\n if (mockServer) {\n return { address: null, server: httpServer, hmrServer: null, metro: metroServer };\n }\n\n return new Promise((resolve, reject) => {\n httpServer.on('error', (error) => {\n reject(error);\n });\n\n httpServer.listen(config.server.port, host, () => {\n if (onReady) {\n onReady(httpServer);\n }\n\n const hmrServer = new MetroHmrServer(\n metroServer.getBundler(),\n metroServer.getCreateModuleId(),\n config\n );\n\n Object.assign(websocketEndpoints, {\n '/hot': createWebsocketServer({\n websocketServer: hmrServer,\n }),\n });\n\n httpServer.on('upgrade', (request, socket, head) => {\n const { pathname } = new URL(request.url!, 'http://localhost');\n if (pathname != null && websocketEndpoints[pathname]) {\n websocketEndpoints[pathname].handleUpgrade(request, socket, head, (ws) => {\n websocketEndpoints[pathname]?.emit('connection', ws, request);\n });\n } else {\n socket.destroy();\n }\n });\n\n const address = httpServer.address();\n assert(\n address == null || typeof address === 'object',\n 'Expected httpServer.address() to be an object'\n );\n\n resolve({\n address: {\n protocol,\n address: address?.address ?? host ?? 'localhost',\n family: address?.family ?? 'ipv4',\n port: address?.port ?? config.server.port,\n },\n server: httpServer,\n hmrServer,\n metro: metroServer,\n });\n });\n });\n};\n"],"names":["runServer","_metroBundler","config","hasReducedPerformance","host","onError","onReady","secureServerOptions","websocketEndpoints","watch","waitForBundler","mockServer","middleware","end","metroServer","createConnectMiddleware","assert","use","serverApp","httpServer","protocol","https","createServer","http","on","error","code","getRunningProcess","require","server","port","then","info","Log","command","directory","timeout","originalClose","close","bind","closeHttpServer","callback","err","endpoint","Object","values","clients","forEach","client","terminate","closeAllConnections","address","hmrServer","metro","Promise","resolve","reject","listen","MetroHmrServer","getBundler","getCreateModuleId","assign","createWebsocketServer","websocketServer","request","socket","head","pathname","URL","url","handleUpgrade","ws","emit","destroy","family"],"mappings":"AAAA,mCAAmC;AACnC,qDAAqD;AACrD,EAAE;AACF,6HAA6H;AAC7H,uDAAuD;;;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,WAAW,CAACwC,SAASC,QAAQC;gBACzC,MAAM,EAAEC,QAAQ,EAAE,GAAG,IAAIC,IAAIJ,QAAQK,GAAG,EAAG;gBAC3C,IAAIF,YAAY,QAAQ3D,kBAAkB,CAAC2D,SAAS,EAAE;oBACpD3D,kBAAkB,CAAC2D,SAAS,CAACG,aAAa,CAACN,SAASC,QAAQC,MAAM,CAACK;4BACjE/D;yBAAAA,+BAAAA,kBAAkB,CAAC2D,SAAS,qBAA5B3D,6BAA8BgE,IAAI,CAAC,cAAcD,IAAIP;oBACvD;gBACF,OAAO;oBACLC,OAAOQ,OAAO;gBAChB;YACF;YAEA,MAAMtB,UAAUhC,WAAWgC,OAAO;YAClCnC,IAAAA,iBAAM,EACJmC,WAAW,QAAQ,OAAOA,YAAY,UACtC;YAGFI,QAAQ;gBACNJ,SAAS;oBACP/B;oBACA+B,SAASA,CAAAA,2BAAAA,QAASA,OAAO,KAAI/C,QAAQ;oBACrCsE,QAAQvB,CAAAA,2BAAAA,QAASuB,MAAM,KAAI;oBAC3B5C,MAAMqB,CAAAA,2BAAAA,QAASrB,IAAI,KAAI5B,OAAO2B,MAAM,CAACC,IAAI;gBAC3C;gBACAD,QAAQV;gBACRiC;gBACAC,OAAOvC;YACT;QACF;IACF;AACF"}
|
|
@@ -301,6 +301,10 @@ function withExtendedResolver(config, { autolinkingModuleResolverInput, isTsconf
|
|
|
301
301
|
replace: 'weak'
|
|
302
302
|
}
|
|
303
303
|
];
|
|
304
|
+
const skipMetroMainFieldOverride = _env.env.EXPO_METRO_NO_MAIN_FIELD_OVERRIDE;
|
|
305
|
+
const useExpoUnstableWebModule = _env.env.EXPO_UNSTABLE_WEB_MODAL;
|
|
306
|
+
const useExpoUnstableLogBox = _env.env.EXPO_UNSTABLE_LOG_BOX;
|
|
307
|
+
const disableReactNavigationCheck = _env.env.EXPO_ROUTER_DISABLE_RN_NAVIGATION_CHECK;
|
|
304
308
|
const metroConfigWithCustomResolver = (0, _withMetroResolvers.withMetroResolvers)(config, [
|
|
305
309
|
// Mock out production react imports in development.
|
|
306
310
|
function requestDevMockProdReact(context, moduleName, platform) {
|
|
@@ -480,14 +484,14 @@ function withExtendedResolver(config, { autolinkingModuleResolverInput, isTsconf
|
|
|
480
484
|
const doReplaceStrict = (from, to)=>doReplace(from, to, {
|
|
481
485
|
throws: true
|
|
482
486
|
});
|
|
483
|
-
if (
|
|
487
|
+
if (useExpoUnstableWebModule) {
|
|
484
488
|
const webModalModule = doReplace('expo-router/build/layouts/_web-modal.js', 'expo-router/build/layouts/ExperimentalModalStack.js');
|
|
485
489
|
if (webModalModule) {
|
|
486
490
|
debug('Using `_unstable-web-modal` implementation.');
|
|
487
491
|
return webModalModule;
|
|
488
492
|
}
|
|
489
493
|
}
|
|
490
|
-
if (!
|
|
494
|
+
if (!disableReactNavigationCheck) {
|
|
491
495
|
// TODO(@ubax): Remove this rewrite once we published migration guide for library authors
|
|
492
496
|
if (isExpoRouterInstalled && moduleName.startsWith('@react-navigation/')) {
|
|
493
497
|
const filePath = context.originModulePath;
|
|
@@ -554,7 +558,7 @@ function withExtendedResolver(config, { autolinkingModuleResolverInput, isTsconf
|
|
|
554
558
|
}
|
|
555
559
|
const hmrModule = doReplaceStrict('react-native/Libraries/Utilities/HMRClient.js', 'expo/src/async-require/hmr.ts');
|
|
556
560
|
if (hmrModule) return hmrModule;
|
|
557
|
-
if (
|
|
561
|
+
if (useExpoUnstableLogBox) {
|
|
558
562
|
const logBoxModule = doReplace('react-native/Libraries/LogBox/LogBoxInspectorContainer.js', '@expo/log-box/swap-rn-logbox.js');
|
|
559
563
|
if (logBoxModule) return logBoxModule;
|
|
560
564
|
const logBoxParserModule = doReplace('react-native/Libraries/LogBox/Data/parseLogBoxLog.js', '@expo/log-box/swap-rn-logbox-parser.js');
|
|
@@ -640,7 +644,7 @@ function withExtendedResolver(config, { autolinkingModuleResolverInput, isTsconf
|
|
|
640
644
|
}
|
|
641
645
|
} else {
|
|
642
646
|
// Non-server changes
|
|
643
|
-
if (!
|
|
647
|
+
if (!skipMetroMainFieldOverride && platform && platform in preferredMainFields) {
|
|
644
648
|
context.mainFields = preferredMainFields[platform];
|
|
645
649
|
}
|
|
646
650
|
}
|