@expo/cli 54.0.9 → 54.0.11
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/export/exportStaticAsync.js +15 -1
- package/build/src/export/exportStaticAsync.js.map +1 -1
- package/build/src/serve/serveAsync.js +7 -7
- package/build/src/serve/serveAsync.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +6 -6
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js +10 -4
- package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
- package/build/src/start/server/metro/fetchRouterManifest.js.map +1 -1
- package/build/src/start/server/metro/router.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +20 -7
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js +1 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.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 +6 -6
- package/static/template/[...rsc]+api.ts +1 -1
package/build/bin/cli
CHANGED
|
@@ -98,11 +98,23 @@ function injectScriptTags(html, scriptTags) {
|
|
|
98
98
|
var _name_match;
|
|
99
99
|
return (_name_match = name.match(/^\(([^/]+?)\)$/)) == null ? void 0 : _name_match[1];
|
|
100
100
|
}
|
|
101
|
-
async function getFilesToExportFromServerAsync(projectRoot, { manifest, renderAsync, // Servers can handle group routes automatically and therefore
|
|
101
|
+
async function getFilesToExportFromServerAsync(projectRoot, { manifest, serverManifest, renderAsync, // Servers can handle group routes automatically and therefore
|
|
102
102
|
// don't require the build-time generation of every possible group
|
|
103
103
|
// variation.
|
|
104
104
|
exportServer, // name : contents
|
|
105
105
|
files = new Map() }) {
|
|
106
|
+
if (!exportServer && serverManifest) {
|
|
107
|
+
// When we're not exporting a `server` output, we provide a `_expo/.routes.json` for
|
|
108
|
+
// EAS Hosting to recognize the `headers` and `redirects` configs
|
|
109
|
+
const subsetServerManifest = {
|
|
110
|
+
headers: serverManifest.headers,
|
|
111
|
+
redirects: serverManifest.redirects
|
|
112
|
+
};
|
|
113
|
+
files.set('_expo/.routes.json', {
|
|
114
|
+
contents: JSON.stringify(subsetServerManifest, null, 2),
|
|
115
|
+
targetDomain: 'client'
|
|
116
|
+
});
|
|
117
|
+
}
|
|
106
118
|
await Promise.all(getHtmlFiles({
|
|
107
119
|
manifest,
|
|
108
120
|
includeGroupVariations: !exportServer
|
|
@@ -192,6 +204,7 @@ async function exportFromServerAsync(projectRoot, devServer, { outputDir, baseUr
|
|
|
192
204
|
await getFilesToExportFromServerAsync(projectRoot, {
|
|
193
205
|
files,
|
|
194
206
|
manifest,
|
|
207
|
+
serverManifest,
|
|
195
208
|
exportServer,
|
|
196
209
|
async renderAsync ({ pathname, route }) {
|
|
197
210
|
const template = await renderAsync(pathname);
|
|
@@ -388,6 +401,7 @@ async function exportApiRoutesStandaloneAsync(devServer, { files = new Map(), pl
|
|
|
388
401
|
// TODO: Export an HTML entry for each file. This is a temporary solution until we have SSR/SSG for RSC.
|
|
389
402
|
await getFilesToExportFromServerAsync(devServer.projectRoot, {
|
|
390
403
|
manifest: htmlManifest,
|
|
404
|
+
serverManifest,
|
|
391
405
|
exportServer: true,
|
|
392
406
|
files,
|
|
393
407
|
renderAsync: async ({ pathname, filePath })=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/export/exportStaticAsync.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 } from '@expo/config';\nimport chalk from 'chalk';\nimport { RouteNode } from 'expo-router/build/Route';\nimport { stripGroupSegmentsFromPath } from 'expo-router/build/matchers';\nimport { shouldLinkExternally } from 'expo-router/build/utils/url';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\nimport { inspect } from 'util';\n\nimport { getVirtualFaviconAssetsAsync } from './favicon';\nimport { persistMetroAssetsAsync } from './persistMetroAssets';\nimport { ExportAssetMap, getFilesFromSerialAssets } from './saveAssets';\nimport { Log } from '../log';\nimport {\n ExpoRouterRuntimeManifest,\n MetroBundlerDevServer,\n} from '../start/server/metro/MetroBundlerDevServer';\nimport { ExpoRouterServerManifestV1 } from '../start/server/metro/fetchRouterManifest';\nimport { logMetroErrorAsync } from '../start/server/metro/metroErrorInterface';\nimport { getApiRoutesForDirectory, getMiddlewareForDirectory } from '../start/server/metro/router';\nimport { serializeHtmlWithAssets } from '../start/server/metro/serializeHtml';\nimport { learnMore } from '../utils/link';\n\nconst debug = require('debug')('expo:export:generateStaticRoutes') as typeof console.log;\n\ntype ExtraScriptTag = {\n platform: string;\n src: string;\n};\n\ntype Options = {\n mode: 'production' | 'development';\n files?: ExportAssetMap;\n outputDir: string;\n minify: boolean;\n exportServer: boolean;\n baseUrl: string;\n includeSourceMaps: boolean;\n entryPoint?: string;\n clear: boolean;\n routerRoot: string;\n reactCompiler: boolean;\n maxWorkers?: number;\n isExporting: boolean;\n exp?: ExpoConfig;\n // <script type=\"type/expo\" data-platform=\"ios\" src=\"...\" />\n scriptTags?: ExtraScriptTag[];\n};\n\ntype HtmlRequestLocation = {\n /** The output file path name to use relative to the static folder. */\n filePath: string;\n /** The pathname to make requests to in order to fetch the HTML. */\n pathname: string;\n /** The runtime route node object, used to associate async modules with the static HTML. */\n route: RouteNode;\n};\n\nexport function injectScriptTags(html: string, scriptTags: ExtraScriptTag[]): string {\n const scriptTagsHtml = scriptTags\n .map((tag) =>\n tag.platform === 'web'\n ? `<script src=\"${tag.src}\"></script>`\n : `<script type=\"type/expo\" src=\"${tag.src}\" data-platform=\"${tag.platform}\"></script>`\n )\n .join('\\n');\n html = html.replace('</head>', `${scriptTagsHtml}\\n</head>`);\n return html;\n}\n\n/** Match `(page)` -> `page` */\nfunction matchGroupName(name: string): string | undefined {\n return name.match(/^\\(([^/]+?)\\)$/)?.[1];\n}\n\nexport async function getFilesToExportFromServerAsync(\n projectRoot: string,\n {\n manifest,\n renderAsync,\n // Servers can handle group routes automatically and therefore\n // don't require the build-time generation of every possible group\n // variation.\n exportServer,\n // name : contents\n files = new Map(),\n }: {\n manifest: ExpoRouterRuntimeManifest;\n renderAsync: (requestLocation: HtmlRequestLocation) => Promise<string>;\n exportServer?: boolean;\n files?: ExportAssetMap;\n }\n): Promise<ExportAssetMap> {\n await Promise.all(\n getHtmlFiles({ manifest, includeGroupVariations: !exportServer }).map(\n async ({ route, filePath, pathname }) => {\n // Rewrite routes should not be statically generated\n if (route.type === 'rewrite') {\n return;\n }\n\n try {\n const targetDomain = exportServer ? 'server' : 'client';\n files.set(filePath, { contents: '', targetDomain });\n const data = await renderAsync({ route, filePath, pathname });\n files.set(filePath, {\n contents: data,\n routeId: pathname,\n targetDomain,\n });\n } catch (e: any) {\n await logMetroErrorAsync({ error: e, projectRoot });\n throw new Error('Failed to statically export route: ' + pathname);\n }\n }\n )\n );\n\n return files;\n}\n\nfunction modifyRouteNodeInRuntimeManifest(\n manifest: ExpoRouterRuntimeManifest,\n callback: (route: RouteNode) => any\n) {\n const iterateScreens = (screens: ExpoRouterRuntimeManifest['screens']) => {\n Object.values(screens).map((value) => {\n if (typeof value !== 'string') {\n if (value._route) callback(value._route);\n iterateScreens(value.screens);\n }\n });\n };\n\n iterateScreens(manifest.screens);\n}\n\n// TODO: Do this earlier in the process.\nfunction makeRuntimeEntryPointsAbsolute(manifest: ExpoRouterRuntimeManifest, appDir: string) {\n modifyRouteNodeInRuntimeManifest(manifest, (route) => {\n if (Array.isArray(route.entryPoints)) {\n route.entryPoints = route.entryPoints.map((entryPoint) => {\n // TODO(@hassankhan): ENG-16577\n if (shouldLinkExternally(entryPoint)) {\n return entryPoint;\n }\n\n if (entryPoint.startsWith('.')) {\n return path.resolve(appDir, entryPoint);\n } else if (!path.isAbsolute(entryPoint)) {\n return resolveFrom(appDir, entryPoint);\n }\n return entryPoint;\n });\n }\n });\n}\n\n/** Perform all fs commits */\nexport async function exportFromServerAsync(\n projectRoot: string,\n devServer: MetroBundlerDevServer,\n {\n outputDir,\n baseUrl,\n exportServer,\n includeSourceMaps,\n routerRoot,\n files = new Map(),\n exp,\n scriptTags,\n }: Options\n): Promise<ExportAssetMap> {\n Log.log(\n `Static rendering is enabled. ` +\n learnMore('https://docs.expo.dev/router/reference/static-rendering/')\n );\n\n const platform = 'web';\n const isExporting = true;\n const appDir = path.join(projectRoot, routerRoot);\n const injectFaviconTag = await getVirtualFaviconAssetsAsync(projectRoot, {\n outputDir,\n baseUrl,\n files,\n exp,\n });\n\n const [resources, { manifest, serverManifest, renderAsync }] = await Promise.all([\n devServer.getStaticResourcesAsync({\n includeSourceMaps,\n }),\n devServer.getStaticRenderFunctionAsync(),\n ]);\n\n makeRuntimeEntryPointsAbsolute(manifest, appDir);\n\n debug('Routes:\\n', inspect(manifest, { colors: true, depth: null }));\n\n await getFilesToExportFromServerAsync(projectRoot, {\n files,\n manifest,\n exportServer,\n async renderAsync({ pathname, route }) {\n const template = await renderAsync(pathname);\n let html = await serializeHtmlWithAssets({\n isExporting,\n resources: resources.artifacts,\n template,\n baseUrl,\n route,\n hydrate: true,\n });\n\n if (injectFaviconTag) {\n html = injectFaviconTag(html);\n }\n\n if (scriptTags) {\n // Inject script tags into the HTML.\n // <script type=\"type/expo\" data-platform=\"ios\" src=\"...\" />\n html = injectScriptTags(html, scriptTags);\n }\n\n return html;\n },\n });\n\n getFilesFromSerialAssets(resources.artifacts, {\n platform,\n includeSourceMaps,\n files,\n isServerHosted: true,\n });\n\n if (resources.assets) {\n // TODO: Collect files without writing to disk.\n // NOTE(kitten): Re. above, this is now using `files` except for iOS catalog output, which isn't used here\n await persistMetroAssetsAsync(projectRoot, resources.assets, {\n files,\n platform,\n outputDirectory: outputDir,\n baseUrl,\n });\n }\n\n if (exportServer) {\n const apiRoutes = await exportApiRoutesAsync({\n platform: 'web',\n server: devServer,\n manifest: serverManifest,\n // NOTE(kitten): For now, we always output source maps for API route exports\n includeSourceMaps: true,\n });\n\n // Add the api routes to the files to export.\n for (const [route, contents] of apiRoutes) {\n files.set(route, contents);\n }\n } else {\n warnPossibleInvalidExportType(appDir);\n }\n\n return files;\n}\n\nexport function getHtmlFiles({\n manifest,\n includeGroupVariations,\n}: {\n manifest: ExpoRouterRuntimeManifest;\n includeGroupVariations?: boolean;\n}): HtmlRequestLocation[] {\n const htmlFiles = new Set<Omit<HtmlRequestLocation, 'pathname'>>();\n\n function traverseScreens(\n screens: ExpoRouterRuntimeManifest['screens'],\n route: RouteNode | null,\n baseUrl = ''\n ) {\n for (const [key, value] of Object.entries(screens)) {\n let leaf: string | null = null;\n if (typeof value === 'string') {\n leaf = value;\n } else if (value.screens && Object.keys(value.screens).length === 0) {\n // Ensure the trailing index is accounted for.\n if (key === value.path + '/index') {\n leaf = key;\n } else {\n leaf = value.path;\n }\n\n route = value._route ?? null;\n }\n\n if (leaf != null) {\n let filePath = baseUrl + leaf;\n\n if (leaf === '') {\n filePath =\n baseUrl === ''\n ? 'index'\n : baseUrl.endsWith('/')\n ? baseUrl + 'index'\n : baseUrl.slice(0, -1);\n } else if (\n // If the path is a collection of group segments leading to an index route, append `/index`.\n stripGroupSegmentsFromPath(filePath) === ''\n ) {\n filePath += '/index';\n }\n\n // This should never happen, the type of `string | object` originally comes from React Navigation.\n if (!route) {\n throw new Error(\n `Internal error: Route not found for \"${filePath}\" while collecting static export paths.`\n );\n }\n\n if (includeGroupVariations) {\n // TODO: Dedupe requests for alias routes.\n addOptionalGroups(filePath, route);\n } else {\n htmlFiles.add({\n filePath,\n route,\n });\n }\n } else if (typeof value === 'object' && value?.screens) {\n // The __root slot has no path.\n const newPath = value.path ? baseUrl + value.path + '/' : baseUrl;\n traverseScreens(value.screens, value._route ?? null, newPath);\n }\n }\n }\n\n function addOptionalGroups(path: string, route: RouteNode) {\n const variations = getPathVariations(path);\n for (const variation of variations) {\n htmlFiles.add({ filePath: variation, route });\n }\n }\n\n traverseScreens(manifest.screens, null);\n\n return uniqueBy(Array.from(htmlFiles), (value) => value.filePath).map((value) => {\n const parts = value.filePath.split('/');\n // Replace `:foo` with `[foo]` and `*foo` with `[...foo]`\n const partsWithGroups = parts.map((part) => {\n if (part === '*not-found') {\n return `+not-found`;\n } else if (part.startsWith(':')) {\n return `[${part.slice(1)}]`;\n } else if (part.startsWith('*')) {\n return `[...${part.slice(1)}]`;\n }\n return part;\n });\n const filePathLocation = partsWithGroups.join('/');\n const filePath = filePathLocation + '.html';\n return {\n ...value,\n filePath,\n pathname: filePathLocation.replace(/(\\/?index)?$/, ''),\n };\n });\n}\n\nfunction uniqueBy<T>(array: T[], key: (value: T) => string): T[] {\n const seen = new Set<string>();\n const result: T[] = [];\n for (const value of array) {\n const id = key(value);\n if (!seen.has(id)) {\n seen.add(id);\n result.push(value);\n }\n }\n return result;\n}\n\n// Given a route like `(foo)/bar/(baz)`, return all possible variations of the route.\n// e.g. `(foo)/bar/(baz)`, `(foo)/bar/baz`, `foo/bar/(baz)`, `foo/bar/baz`,\nexport function getPathVariations(routePath: string): string[] {\n const variations = new Set<string>();\n const segments = routePath.split('/');\n\n function generateVariations(segments: string[], current = ''): void {\n if (segments.length === 0) {\n if (current) variations.add(current);\n return;\n }\n\n const [head, ...rest] = segments;\n\n if (matchGroupName(head)) {\n const groups = head.slice(1, -1).split(',');\n\n if (groups.length > 1) {\n for (const group of groups) {\n // If there are multiple groups, recurse on each group.\n generateVariations([`(${group.trim()})`, ...rest], current);\n }\n return;\n } else {\n // Start a fork where this group is included\n generateVariations(rest, current ? `${current}/(${groups[0]})` : `(${groups[0]})`);\n // This code will continue and add paths without this group included`\n }\n } else if (current) {\n current = `${current}/${head}`;\n } else {\n current = head;\n }\n\n generateVariations(rest, current);\n }\n\n generateVariations(segments);\n\n return Array.from(variations);\n}\n\nexport async function exportApiRoutesStandaloneAsync(\n devServer: MetroBundlerDevServer,\n {\n files = new Map(),\n platform,\n apiRoutesOnly,\n templateHtml,\n }: {\n files?: ExportAssetMap;\n platform: string;\n apiRoutesOnly: boolean;\n templateHtml?: string;\n }\n) {\n const { serverManifest, htmlManifest } = await devServer.getServerManifestAsync();\n\n const apiRoutes = await exportApiRoutesAsync({\n server: devServer,\n manifest: serverManifest,\n // NOTE(kitten): For now, we always output source maps for API route exports\n includeSourceMaps: true,\n platform,\n apiRoutesOnly,\n });\n\n // Add the api routes to the files to export.\n for (const [route, contents] of apiRoutes) {\n files.set(route, contents);\n }\n\n if (templateHtml && devServer.isReactServerComponentsEnabled) {\n // TODO: Export an HTML entry for each file. This is a temporary solution until we have SSR/SSG for RSC.\n await getFilesToExportFromServerAsync(devServer.projectRoot, {\n manifest: htmlManifest,\n exportServer: true,\n files,\n renderAsync: async ({ pathname, filePath }) => {\n files.set(filePath, {\n contents: templateHtml!,\n routeId: pathname,\n targetDomain: 'server',\n });\n return templateHtml!;\n },\n });\n }\n\n return files;\n}\n\nasync function exportApiRoutesAsync({\n includeSourceMaps,\n server,\n platform,\n apiRoutesOnly,\n ...props\n}: Pick<Options, 'includeSourceMaps'> & {\n server: MetroBundlerDevServer;\n manifest: ExpoRouterServerManifestV1;\n platform: string;\n apiRoutesOnly?: boolean;\n}): Promise<ExportAssetMap> {\n const { manifest, files } = await server.exportExpoRouterApiRoutesAsync({\n outputDir: '_expo/functions',\n prerenderManifest: props.manifest,\n includeSourceMaps,\n platform,\n });\n\n // HACK: Clear out the HTML and 404 routes if we're only exporting API routes. This is used for native apps that are using API routes but haven't implemented web support yet.\n if (apiRoutesOnly) {\n manifest.htmlRoutes = [];\n manifest.notFoundRoutes = [];\n }\n\n files.set('_expo/routes.json', {\n contents: JSON.stringify(manifest, null, 2),\n targetDomain: 'server',\n });\n\n return files;\n}\n\nfunction warnPossibleInvalidExportType(appDir: string) {\n const apiRoutes = getApiRoutesForDirectory(appDir);\n if (apiRoutes.length) {\n // TODO: Allow API Routes for native-only.\n Log.warn(\n chalk.yellow`Skipping export for API routes because \\`web.output\\` is not \"server\". You may want to remove the routes: ${apiRoutes\n .map((v) => path.relative(appDir, v))\n .join(', ')}`\n );\n }\n\n const middlewareFile = getMiddlewareForDirectory(appDir);\n if (middlewareFile) {\n Log.warn(\n chalk.yellow`Skipping export for middleware because \\`web.output\\` is not \"server\". You may want to remove ${path.relative(appDir, middlewareFile)}`\n );\n }\n}\n"],"names":["exportApiRoutesStandaloneAsync","exportFromServerAsync","getFilesToExportFromServerAsync","getHtmlFiles","getPathVariations","injectScriptTags","debug","require","html","scriptTags","scriptTagsHtml","map","tag","platform","src","join","replace","matchGroupName","name","match","projectRoot","manifest","renderAsync","exportServer","files","Map","Promise","all","includeGroupVariations","route","filePath","pathname","type","targetDomain","set","contents","data","routeId","e","logMetroErrorAsync","error","Error","modifyRouteNodeInRuntimeManifest","callback","iterateScreens","screens","Object","values","value","_route","makeRuntimeEntryPointsAbsolute","appDir","Array","isArray","entryPoints","entryPoint","shouldLinkExternally","startsWith","path","resolve","isAbsolute","resolveFrom","devServer","outputDir","baseUrl","includeSourceMaps","routerRoot","exp","Log","log","learnMore","isExporting","injectFaviconTag","getVirtualFaviconAssetsAsync","resources","serverManifest","getStaticResourcesAsync","getStaticRenderFunctionAsync","inspect","colors","depth","template","serializeHtmlWithAssets","artifacts","hydrate","getFilesFromSerialAssets","isServerHosted","assets","persistMetroAssetsAsync","outputDirectory","apiRoutes","exportApiRoutesAsync","server","warnPossibleInvalidExportType","htmlFiles","Set","traverseScreens","key","entries","leaf","keys","length","endsWith","slice","stripGroupSegmentsFromPath","addOptionalGroups","add","newPath","variations","variation","uniqueBy","from","parts","split","partsWithGroups","part","filePathLocation","array","seen","result","id","has","push","routePath","segments","generateVariations","current","head","rest","groups","group","trim","apiRoutesOnly","templateHtml","htmlManifest","getServerManifestAsync","isReactServerComponentsEnabled","props","exportExpoRouterApiRoutesAsync","prerenderManifest","htmlRoutes","notFoundRoutes","JSON","stringify","getApiRoutesForDirectory","warn","chalk","yellow","v","relative","middlewareFile","getMiddlewareForDirectory"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAwaqBA,8BAA8B;eAA9BA;;IAxQAC,qBAAqB;eAArBA;;IApFAC,+BAA+B;eAA/BA;;IA+LNC,YAAY;eAAZA;;IAqHAC,iBAAiB;eAAjBA;;IArUAC,gBAAgB;eAAhBA;;;;gEAzDE;;;;;;;yBAEyB;;;;;;;yBACN;;;;;;;gEACpB;;;;;;;gEACO;;;;;;;yBACA;;;;;;yBAEqB;oCACL;4BACiB;qBACrC;qCAMe;wBACiC;+BAC5B;sBACd;;;;;;AAE1B,MAAMC,QAAQC,QAAQ,SAAS;AAmCxB,SAASF,iBAAiBG,IAAY,EAAEC,UAA4B;IACzE,MAAMC,iBAAiBD,WACpBE,GAAG,CAAC,CAACC,MACJA,IAAIC,QAAQ,KAAK,QACb,CAAC,aAAa,EAAED,IAAIE,GAAG,CAAC,WAAW,CAAC,GACpC,CAAC,8BAA8B,EAAEF,IAAIE,GAAG,CAAC,iBAAiB,EAAEF,IAAIC,QAAQ,CAAC,WAAW,CAAC,EAE1FE,IAAI,CAAC;IACRP,OAAOA,KAAKQ,OAAO,CAAC,WAAW,GAAGN,eAAe,SAAS,CAAC;IAC3D,OAAOF;AACT;AAEA,6BAA6B,GAC7B,SAASS,eAAeC,IAAY;QAC3BA;IAAP,QAAOA,cAAAA,KAAKC,KAAK,CAAC,sCAAXD,WAA8B,CAAC,EAAE;AAC1C;AAEO,eAAehB,gCACpBkB,WAAmB,EACnB,EACEC,QAAQ,EACRC,WAAW,EACX,8DAA8D;AAC9D,kEAAkE;AAClE,aAAa;AACbC,YAAY,EACZ,kBAAkB;AAClBC,QAAQ,IAAIC,KAAK,EAMlB;IAED,MAAMC,QAAQC,GAAG,CACfxB,aAAa;QAAEkB;QAAUO,wBAAwB,CAACL;IAAa,GAAGZ,GAAG,CACnE,OAAO,EAAEkB,KAAK,EAAEC,QAA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AEA,OAAO7G;AACT;AAEA,eAAemE,qBAAqB,EAClC1B,iBAAiB,EACjB2B,MAAM,EACN/E,QAAQ,EACRuH,aAAa,EACb,GAAGK,OAMJ;IACC,MAAM,EAAEpH,QAAQ,EAAEG,KAAK,EAAE,GAAG,MAAMoE,OAAO8C,8BAA8B,CAAC;QACtE3E,WAAW;QACX4E,mBAAmBF,MAAMpH,QAAQ;QACjC4C;QACApD;IACF;IAEA,8KAA8K;IAC9K,IAAIuH,eAAe;QACjB/G,SAASuH,UAAU,GAAG,EAAE;QACxBvH,SAASwH,cAAc,GAAG,EAAE;IAC9B;IAEArH,MAAMU,GAAG,CAAC,qBAAqB;QAC7BC,UAAU2G,KAAKC,SAAS,CAAC1H,UAAU,MAAM;QACzCY,cAAc;IAChB;IAEA,OAAOT;AACT;AAEA,SAASqE,8BAA8B1C,MAAc;IACnD,MAAMuC,YAAYsD,IAAAA,gCAAwB,EAAC7F;IAC3C,IAAIuC,UAAUW,MAAM,EAAE;QACpB,0CAA0C;QAC1CjC,QAAG,CAAC6E,IAAI,CACNC,gBAAK,CAACC,MAAM,CAAC,0GAA0G,EAAEzD,UACtH/E,GAAG,CAAC,CAACyI,IAAM1F,eAAI,CAAC2F,QAAQ,CAAClG,QAAQiG,IACjCrI,IAAI,CAAC,MAAM,CAAC;IAEnB;IAEA,MAAMuI,iBAAiBC,IAAAA,iCAAyB,EAACpG;IACjD,IAAImG,gBAAgB;QAClBlF,QAAG,CAAC6E,IAAI,CACNC,gBAAK,CAACC,MAAM,CAAC,8FAA8F,EAAEzF,eAAI,CAAC2F,QAAQ,CAAClG,QAAQmG,gBAAgB,CAAC;IAExJ;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/export/exportStaticAsync.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 } from '@expo/config';\nimport chalk from 'chalk';\nimport { RouteNode } from 'expo-router/build/Route';\nimport { stripGroupSegmentsFromPath } from 'expo-router/build/matchers';\nimport { shouldLinkExternally } from 'expo-router/build/utils/url';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\nimport { inspect } from 'util';\n\nimport { getVirtualFaviconAssetsAsync } from './favicon';\nimport { persistMetroAssetsAsync } from './persistMetroAssets';\nimport { ExportAssetMap, getFilesFromSerialAssets } from './saveAssets';\nimport { Log } from '../log';\nimport {\n ExpoRouterRuntimeManifest,\n MetroBundlerDevServer,\n} from '../start/server/metro/MetroBundlerDevServer';\nimport { ExpoRouterServerManifestV1 } from '../start/server/metro/fetchRouterManifest';\nimport { logMetroErrorAsync } from '../start/server/metro/metroErrorInterface';\nimport { getApiRoutesForDirectory, getMiddlewareForDirectory } from '../start/server/metro/router';\nimport { serializeHtmlWithAssets } from '../start/server/metro/serializeHtml';\nimport { learnMore } from '../utils/link';\n\nconst debug = require('debug')('expo:export:generateStaticRoutes') as typeof console.log;\n\ntype ExtraScriptTag = {\n platform: string;\n src: string;\n};\n\ntype Options = {\n mode: 'production' | 'development';\n files?: ExportAssetMap;\n outputDir: string;\n minify: boolean;\n exportServer: boolean;\n baseUrl: string;\n includeSourceMaps: boolean;\n entryPoint?: string;\n clear: boolean;\n routerRoot: string;\n reactCompiler: boolean;\n maxWorkers?: number;\n isExporting: boolean;\n exp?: ExpoConfig;\n // <script type=\"type/expo\" data-platform=\"ios\" src=\"...\" />\n scriptTags?: ExtraScriptTag[];\n};\n\ntype HtmlRequestLocation = {\n /** The output file path name to use relative to the static folder. */\n filePath: string;\n /** The pathname to make requests to in order to fetch the HTML. */\n pathname: string;\n /** The runtime route node object, used to associate async modules with the static HTML. */\n route: RouteNode;\n};\n\nexport function injectScriptTags(html: string, scriptTags: ExtraScriptTag[]): string {\n const scriptTagsHtml = scriptTags\n .map((tag) =>\n tag.platform === 'web'\n ? `<script src=\"${tag.src}\"></script>`\n : `<script type=\"type/expo\" src=\"${tag.src}\" data-platform=\"${tag.platform}\"></script>`\n )\n .join('\\n');\n html = html.replace('</head>', `${scriptTagsHtml}\\n</head>`);\n return html;\n}\n\n/** Match `(page)` -> `page` */\nfunction matchGroupName(name: string): string | undefined {\n return name.match(/^\\(([^/]+?)\\)$/)?.[1];\n}\n\nexport async function getFilesToExportFromServerAsync(\n projectRoot: string,\n {\n manifest,\n serverManifest,\n renderAsync,\n // Servers can handle group routes automatically and therefore\n // don't require the build-time generation of every possible group\n // variation.\n exportServer,\n // name : contents\n files = new Map(),\n }: {\n manifest: ExpoRouterRuntimeManifest;\n serverManifest: ExpoRouterServerManifestV1;\n renderAsync: (requestLocation: HtmlRequestLocation) => Promise<string>;\n exportServer?: boolean;\n files?: ExportAssetMap;\n }\n): Promise<ExportAssetMap> {\n if (!exportServer && serverManifest) {\n // When we're not exporting a `server` output, we provide a `_expo/.routes.json` for\n // EAS Hosting to recognize the `headers` and `redirects` configs\n const subsetServerManifest = {\n headers: serverManifest.headers,\n redirects: serverManifest.redirects,\n };\n files.set('_expo/.routes.json', {\n contents: JSON.stringify(subsetServerManifest, null, 2),\n targetDomain: 'client',\n });\n }\n\n await Promise.all(\n getHtmlFiles({ manifest, includeGroupVariations: !exportServer }).map(\n async ({ route, filePath, pathname }) => {\n // Rewrite routes should not be statically generated\n if (route.type === 'rewrite') {\n return;\n }\n\n try {\n const targetDomain = exportServer ? 'server' : 'client';\n files.set(filePath, { contents: '', targetDomain });\n const data = await renderAsync({ route, filePath, pathname });\n files.set(filePath, {\n contents: data,\n routeId: pathname,\n targetDomain,\n });\n } catch (e: any) {\n await logMetroErrorAsync({ error: e, projectRoot });\n throw new Error('Failed to statically export route: ' + pathname);\n }\n }\n )\n );\n\n return files;\n}\n\nfunction modifyRouteNodeInRuntimeManifest(\n manifest: ExpoRouterRuntimeManifest,\n callback: (route: RouteNode) => any\n) {\n const iterateScreens = (screens: ExpoRouterRuntimeManifest['screens']) => {\n Object.values(screens).map((value) => {\n if (typeof value !== 'string') {\n if (value._route) callback(value._route);\n iterateScreens(value.screens);\n }\n });\n };\n\n iterateScreens(manifest.screens);\n}\n\n// TODO: Do this earlier in the process.\nfunction makeRuntimeEntryPointsAbsolute(manifest: ExpoRouterRuntimeManifest, appDir: string) {\n modifyRouteNodeInRuntimeManifest(manifest, (route) => {\n if (Array.isArray(route.entryPoints)) {\n route.entryPoints = route.entryPoints.map((entryPoint) => {\n // TODO(@hassankhan): ENG-16577\n if (shouldLinkExternally(entryPoint)) {\n return entryPoint;\n }\n\n if (entryPoint.startsWith('.')) {\n return path.resolve(appDir, entryPoint);\n } else if (!path.isAbsolute(entryPoint)) {\n return resolveFrom(appDir, entryPoint);\n }\n return entryPoint;\n });\n }\n });\n}\n\n/** Perform all fs commits */\nexport async function exportFromServerAsync(\n projectRoot: string,\n devServer: MetroBundlerDevServer,\n {\n outputDir,\n baseUrl,\n exportServer,\n includeSourceMaps,\n routerRoot,\n files = new Map(),\n exp,\n scriptTags,\n }: Options\n): Promise<ExportAssetMap> {\n Log.log(\n `Static rendering is enabled. ` +\n learnMore('https://docs.expo.dev/router/reference/static-rendering/')\n );\n\n const platform = 'web';\n const isExporting = true;\n const appDir = path.join(projectRoot, routerRoot);\n const injectFaviconTag = await getVirtualFaviconAssetsAsync(projectRoot, {\n outputDir,\n baseUrl,\n files,\n exp,\n });\n\n const [resources, { manifest, serverManifest, renderAsync }] = await Promise.all([\n devServer.getStaticResourcesAsync({\n includeSourceMaps,\n }),\n devServer.getStaticRenderFunctionAsync(),\n ]);\n\n makeRuntimeEntryPointsAbsolute(manifest, appDir);\n\n debug('Routes:\\n', inspect(manifest, { colors: true, depth: null }));\n\n await getFilesToExportFromServerAsync(projectRoot, {\n files,\n manifest,\n serverManifest,\n exportServer,\n async renderAsync({ pathname, route }) {\n const template = await renderAsync(pathname);\n let html = await serializeHtmlWithAssets({\n isExporting,\n resources: resources.artifacts,\n template,\n baseUrl,\n route,\n hydrate: true,\n });\n\n if (injectFaviconTag) {\n html = injectFaviconTag(html);\n }\n\n if (scriptTags) {\n // Inject script tags into the HTML.\n // <script type=\"type/expo\" data-platform=\"ios\" src=\"...\" />\n html = injectScriptTags(html, scriptTags);\n }\n\n return html;\n },\n });\n\n getFilesFromSerialAssets(resources.artifacts, {\n platform,\n includeSourceMaps,\n files,\n isServerHosted: true,\n });\n\n if (resources.assets) {\n // TODO: Collect files without writing to disk.\n // NOTE(kitten): Re. above, this is now using `files` except for iOS catalog output, which isn't used here\n await persistMetroAssetsAsync(projectRoot, resources.assets, {\n files,\n platform,\n outputDirectory: outputDir,\n baseUrl,\n });\n }\n\n if (exportServer) {\n const apiRoutes = await exportApiRoutesAsync({\n platform: 'web',\n server: devServer,\n manifest: serverManifest,\n // NOTE(kitten): For now, we always output source maps for API route exports\n includeSourceMaps: true,\n });\n\n // Add the api routes to the files to export.\n for (const [route, contents] of apiRoutes) {\n files.set(route, contents);\n }\n } else {\n warnPossibleInvalidExportType(appDir);\n }\n\n return files;\n}\n\nexport function getHtmlFiles({\n manifest,\n includeGroupVariations,\n}: {\n manifest: ExpoRouterRuntimeManifest;\n includeGroupVariations?: boolean;\n}): HtmlRequestLocation[] {\n const htmlFiles = new Set<Omit<HtmlRequestLocation, 'pathname'>>();\n\n function traverseScreens(\n screens: ExpoRouterRuntimeManifest['screens'],\n route: RouteNode | null,\n baseUrl = ''\n ) {\n for (const [key, value] of Object.entries(screens)) {\n let leaf: string | null = null;\n if (typeof value === 'string') {\n leaf = value;\n } else if (value.screens && Object.keys(value.screens).length === 0) {\n // Ensure the trailing index is accounted for.\n if (key === value.path + '/index') {\n leaf = key;\n } else {\n leaf = value.path;\n }\n\n route = value._route ?? null;\n }\n\n if (leaf != null) {\n let filePath = baseUrl + leaf;\n\n if (leaf === '') {\n filePath =\n baseUrl === ''\n ? 'index'\n : baseUrl.endsWith('/')\n ? baseUrl + 'index'\n : baseUrl.slice(0, -1);\n } else if (\n // If the path is a collection of group segments leading to an index route, append `/index`.\n stripGroupSegmentsFromPath(filePath) === ''\n ) {\n filePath += '/index';\n }\n\n // This should never happen, the type of `string | object` originally comes from React Navigation.\n if (!route) {\n throw new Error(\n `Internal error: Route not found for \"${filePath}\" while collecting static export paths.`\n );\n }\n\n if (includeGroupVariations) {\n // TODO: Dedupe requests for alias routes.\n addOptionalGroups(filePath, route);\n } else {\n htmlFiles.add({\n filePath,\n route,\n });\n }\n } else if (typeof value === 'object' && value?.screens) {\n // The __root slot has no path.\n const newPath = value.path ? baseUrl + value.path + '/' : baseUrl;\n traverseScreens(value.screens, value._route ?? null, newPath);\n }\n }\n }\n\n function addOptionalGroups(path: string, route: RouteNode) {\n const variations = getPathVariations(path);\n for (const variation of variations) {\n htmlFiles.add({ filePath: variation, route });\n }\n }\n\n traverseScreens(manifest.screens, null);\n\n return uniqueBy(Array.from(htmlFiles), (value) => value.filePath).map((value) => {\n const parts = value.filePath.split('/');\n // Replace `:foo` with `[foo]` and `*foo` with `[...foo]`\n const partsWithGroups = parts.map((part) => {\n if (part === '*not-found') {\n return `+not-found`;\n } else if (part.startsWith(':')) {\n return `[${part.slice(1)}]`;\n } else if (part.startsWith('*')) {\n return `[...${part.slice(1)}]`;\n }\n return part;\n });\n const filePathLocation = partsWithGroups.join('/');\n const filePath = filePathLocation + '.html';\n return {\n ...value,\n filePath,\n pathname: filePathLocation.replace(/(\\/?index)?$/, ''),\n };\n });\n}\n\nfunction uniqueBy<T>(array: T[], key: (value: T) => string): T[] {\n const seen = new Set<string>();\n const result: T[] = [];\n for (const value of array) {\n const id = key(value);\n if (!seen.has(id)) {\n seen.add(id);\n result.push(value);\n }\n }\n return result;\n}\n\n// Given a route like `(foo)/bar/(baz)`, return all possible variations of the route.\n// e.g. `(foo)/bar/(baz)`, `(foo)/bar/baz`, `foo/bar/(baz)`, `foo/bar/baz`,\nexport function getPathVariations(routePath: string): string[] {\n const variations = new Set<string>();\n const segments = routePath.split('/');\n\n function generateVariations(segments: string[], current = ''): void {\n if (segments.length === 0) {\n if (current) variations.add(current);\n return;\n }\n\n const [head, ...rest] = segments;\n\n if (matchGroupName(head)) {\n const groups = head.slice(1, -1).split(',');\n\n if (groups.length > 1) {\n for (const group of groups) {\n // If there are multiple groups, recurse on each group.\n generateVariations([`(${group.trim()})`, ...rest], current);\n }\n return;\n } else {\n // Start a fork where this group is included\n generateVariations(rest, current ? `${current}/(${groups[0]})` : `(${groups[0]})`);\n // This code will continue and add paths without this group included`\n }\n } else if (current) {\n current = `${current}/${head}`;\n } else {\n current = head;\n }\n\n generateVariations(rest, current);\n }\n\n generateVariations(segments);\n\n return Array.from(variations);\n}\n\nexport async function exportApiRoutesStandaloneAsync(\n devServer: MetroBundlerDevServer,\n {\n files = new Map(),\n platform,\n apiRoutesOnly,\n templateHtml,\n }: {\n files?: ExportAssetMap;\n platform: string;\n apiRoutesOnly: boolean;\n templateHtml?: string;\n }\n) {\n const { serverManifest, htmlManifest } = await devServer.getServerManifestAsync();\n\n const apiRoutes = await exportApiRoutesAsync({\n server: devServer,\n manifest: serverManifest,\n // NOTE(kitten): For now, we always output source maps for API route exports\n includeSourceMaps: true,\n platform,\n apiRoutesOnly,\n });\n\n // Add the api routes to the files to export.\n for (const [route, contents] of apiRoutes) {\n files.set(route, contents);\n }\n\n if (templateHtml && devServer.isReactServerComponentsEnabled) {\n // TODO: Export an HTML entry for each file. This is a temporary solution until we have SSR/SSG for RSC.\n await getFilesToExportFromServerAsync(devServer.projectRoot, {\n manifest: htmlManifest,\n serverManifest,\n exportServer: true,\n files,\n renderAsync: async ({ pathname, filePath }) => {\n files.set(filePath, {\n contents: templateHtml!,\n routeId: pathname,\n targetDomain: 'server',\n });\n return templateHtml!;\n },\n });\n }\n\n return files;\n}\n\nasync function exportApiRoutesAsync({\n includeSourceMaps,\n server,\n platform,\n apiRoutesOnly,\n ...props\n}: Pick<Options, 'includeSourceMaps'> & {\n server: MetroBundlerDevServer;\n manifest: ExpoRouterServerManifestV1;\n platform: string;\n apiRoutesOnly?: boolean;\n}): Promise<ExportAssetMap> {\n const { manifest, files } = await server.exportExpoRouterApiRoutesAsync({\n outputDir: '_expo/functions',\n prerenderManifest: props.manifest,\n includeSourceMaps,\n platform,\n });\n\n // HACK: Clear out the HTML and 404 routes if we're only exporting API routes. This is used for native apps that are using API routes but haven't implemented web support yet.\n if (apiRoutesOnly) {\n manifest.htmlRoutes = [];\n manifest.notFoundRoutes = [];\n }\n\n files.set('_expo/routes.json', {\n contents: JSON.stringify(manifest, null, 2),\n targetDomain: 'server',\n });\n\n return files;\n}\n\nfunction warnPossibleInvalidExportType(appDir: string) {\n const apiRoutes = getApiRoutesForDirectory(appDir);\n if (apiRoutes.length) {\n // TODO: Allow API Routes for native-only.\n Log.warn(\n chalk.yellow`Skipping export for API routes because \\`web.output\\` is not \"server\". You may want to remove the routes: ${apiRoutes\n .map((v) => path.relative(appDir, v))\n .join(', ')}`\n );\n }\n\n const middlewareFile = getMiddlewareForDirectory(appDir);\n if (middlewareFile) {\n Log.warn(\n chalk.yellow`Skipping export for middleware because \\`web.output\\` is not \"server\". You may want to remove ${path.relative(appDir, middlewareFile)}`\n );\n }\n}\n"],"names":["exportApiRoutesStandaloneAsync","exportFromServerAsync","getFilesToExportFromServerAsync","getHtmlFiles","getPathVariations","injectScriptTags","debug","require","html","scriptTags","scriptTagsHtml","map","tag","platform","src","join","replace","matchGroupName","name","match","projectRoot","manifest","serverManifest","renderAsync","exportServer","files","Map","subsetServerManifest","headers","redirects","set","contents","JSON","stringify","targetDomain","Promise","all","includeGroupVariations","route","filePath","pathname","type","data","routeId","e","logMetroErrorAsync","error","Error","modifyRouteNodeInRuntimeManifest","callback","iterateScreens","screens","Object","values","value","_route","makeRuntimeEntryPointsAbsolute","appDir","Array","isArray","entryPoints","entryPoint","shouldLinkExternally","startsWith","path","resolve","isAbsolute","resolveFrom","devServer","outputDir","baseUrl","includeSourceMaps","routerRoot","exp","Log","log","learnMore","isExporting","injectFaviconTag","getVirtualFaviconAssetsAsync","resources","getStaticResourcesAsync","getStaticRenderFunctionAsync","inspect","colors","depth","template","serializeHtmlWithAssets","artifacts","hydrate","getFilesFromSerialAssets","isServerHosted","assets","persistMetroAssetsAsync","outputDirectory","apiRoutes","exportApiRoutesAsync","server","warnPossibleInvalidExportType","htmlFiles","Set","traverseScreens","key","entries","leaf","keys","length","endsWith","slice","stripGroupSegmentsFromPath","addOptionalGroups","add","newPath","variations","variation","uniqueBy","from","parts","split","partsWithGroups","part","filePathLocation","array","seen","result","id","has","push","routePath","segments","generateVariations","current","head","rest","groups","group","trim","apiRoutesOnly","templateHtml","htmlManifest","getServerManifestAsync","isReactServerComponentsEnabled","props","exportExpoRouterApiRoutesAsync","prerenderManifest","htmlRoutes","notFoundRoutes","getApiRoutesForDirectory","warn","chalk","yellow","v","relative","middlewareFile","getMiddlewareForDirectory"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAwbqBA,8BAA8B;eAA9BA;;IAzQAC,qBAAqB;eAArBA;;IAnGAC,+BAA+B;eAA/BA;;IA+MNC,YAAY;eAAZA;;IAqHAC,iBAAiB;eAAjBA;;IArVAC,gBAAgB;eAAhBA;;;;gEAzDE;;;;;;;yBAEyB;;;;;;;yBACN;;;;;;;gEACpB;;;;;;;gEACO;;;;;;;yBACA;;;;;;yBAEqB;oCACL;4BACiB;qBACrC;qCAMe;wBACiC;+BAC5B;sBACd;;;;;;AAE1B,MAAMC,QAAQC,QAAQ,SAAS;AAmCxB,SAASF,iBAAiBG,IAAY,EAAEC,UAA4B;IACzE,MAAMC,iBAAiBD,WACpBE,GAAG,CAAC,CAACC,MACJA,IAAIC,QAAQ,KAAK,QACb,CAAC,aAAa,EAAED,IAAIE,GAAG,CAAC,WAAW,CAAC,GACpC,CAAC,8BAA8B,EAAEF,IAAIE,GAAG,CAAC,iBAAiB,EAAEF,IAAIC,QAAQ,CAAC,WAAW,CAAC,EAE1FE,IAAI,CAAC;IACRP,OAAOA,KAAKQ,OAAO,CAAC,WAAW,GAAGN,eAAe,SAAS,CAAC;IAC3D,OAAOF;AACT;AAEA,6BAA6B,GAC7B,SAASS,eAAeC,IAAY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AAwB,EAAC1F;IAC3C,IAAIsC,UAAUW,MAAM,EAAE;QACpB,0CAA0C;QAC1ChC,QAAG,CAAC0E,IAAI,CACNC,gBAAK,CAACC,MAAM,CAAC,0GAA0G,EAAEvD,UACtHpF,GAAG,CAAC,CAAC4I,IAAMvF,eAAI,CAACwF,QAAQ,CAAC/F,QAAQ8F,IACjCxI,IAAI,CAAC,MAAM,CAAC;IAEnB;IAEA,MAAM0I,iBAAiBC,IAAAA,iCAAyB,EAACjG;IACjD,IAAIgG,gBAAgB;QAClB/E,QAAG,CAAC0E,IAAI,CACNC,gBAAK,CAACC,MAAM,CAAC,8FAA8F,EAAEtF,eAAI,CAACwF,QAAQ,CAAC/F,QAAQgG,gBAAgB,CAAC;IAExJ;AACF"}
|
|
@@ -8,13 +8,6 @@ Object.defineProperty(exports, "serveAsync", {
|
|
|
8
8
|
return serveAsync;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
|
-
function _http() {
|
|
12
|
-
const data = require("@expo/server/adapter/http");
|
|
13
|
-
_http = function() {
|
|
14
|
-
return data;
|
|
15
|
-
};
|
|
16
|
-
return data;
|
|
17
|
-
}
|
|
18
11
|
function _chalk() {
|
|
19
12
|
const data = /*#__PURE__*/ _interop_require_default(require("chalk"));
|
|
20
13
|
_chalk = function() {
|
|
@@ -29,6 +22,13 @@ function _connect() {
|
|
|
29
22
|
};
|
|
30
23
|
return data;
|
|
31
24
|
}
|
|
25
|
+
function _http() {
|
|
26
|
+
const data = require("expo-server/adapter/http");
|
|
27
|
+
_http = function() {
|
|
28
|
+
return data;
|
|
29
|
+
};
|
|
30
|
+
return data;
|
|
31
|
+
}
|
|
32
32
|
function _http1() {
|
|
33
33
|
const data = /*#__PURE__*/ _interop_require_default(require("http"));
|
|
34
34
|
_http1 = function() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/serve/serveAsync.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../../src/serve/serveAsync.ts"],"sourcesContent":["import chalk from 'chalk';\nimport connect from 'connect';\nimport { createRequestHandler } from 'expo-server/adapter/http';\nimport http from 'http';\nimport path from 'path';\nimport send from 'send';\n\nimport * as Log from '../log';\nimport { directoryExistsAsync, fileExistsAsync } from '../utils/dir';\nimport { CommandError } from '../utils/errors';\nimport { findUpProjectRootOrAssert } from '../utils/findUp';\nimport { setNodeEnv } from '../utils/nodeEnv';\nimport { resolvePortAsync } from '../utils/port';\n\ntype Options = {\n port?: number;\n isDefaultDirectory: boolean;\n};\n\nconst debug = require('debug')('expo:serve') as typeof console.log;\n\n// Start a basic http server\nexport async function serveAsync(inputDir: string, options: Options) {\n const projectRoot = findUpProjectRootOrAssert(inputDir);\n\n setNodeEnv('production');\n require('@expo/env').load(projectRoot);\n\n const port = await resolvePortAsync(projectRoot, {\n defaultPort: options.port,\n fallbackPort: 8081,\n });\n\n if (port == null) {\n throw new CommandError('Could not start server. Port is not available.');\n }\n options.port = port;\n\n const serverDist = options.isDefaultDirectory ? path.join(inputDir, 'dist') : inputDir;\n // TODO: `.expo/server/ios`, `.expo/server/android`, etc.\n\n if (!(await directoryExistsAsync(serverDist))) {\n throw new CommandError(\n `The server directory ${serverDist} does not exist. Run \\`npx expo export\\` first.`\n );\n }\n\n const isStatic = await isStaticExportAsync(serverDist);\n\n Log.log(chalk.dim(`Starting ${isStatic ? 'static ' : ''}server in ${serverDist}`));\n\n if (isStatic) {\n await startStaticServerAsync(serverDist, options);\n } else {\n await startDynamicServerAsync(serverDist, options);\n }\n Log.log(`Server running at http://localhost:${options.port}`);\n // Detect the type of server we need to setup:\n}\n\nasync function startStaticServerAsync(dist: string, options: Options) {\n const server = http.createServer((req, res) => {\n // Remove query strings and decode URI\n const filePath = decodeURI(req.url?.split('?')[0] ?? '');\n\n send(req, filePath, {\n root: dist,\n index: 'index.html',\n extensions: ['html'],\n })\n .on('error', (err: any) => {\n if (err.status === 404) {\n res.statusCode = 404;\n res.end('Not Found');\n return;\n }\n res.statusCode = err.status || 500;\n res.end('Internal Server Error');\n })\n .pipe(res);\n });\n\n server.listen(options.port!);\n}\n\nasync function startDynamicServerAsync(dist: string, options: Options) {\n const middleware = connect();\n\n const staticDirectory = path.join(dist, 'client');\n const serverDirectory = path.join(dist, 'server');\n\n const serverHandler = createRequestHandler({ build: serverDirectory });\n\n // DOM component CORS support\n middleware.use((req, res, next) => {\n // TODO: Only when origin is `file://` (iOS), and Android equivalent.\n\n // Required for DOM components security in release builds.\n\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.setHeader(\n 'Access-Control-Allow-Headers',\n 'Origin, X-Requested-With, Content-Type, Accept, expo-platform'\n );\n\n // Handle OPTIONS preflight requests\n if (req.method === 'OPTIONS') {\n res.statusCode = 200;\n res.end();\n return;\n }\n next();\n });\n\n middleware.use((req, res, next) => {\n if (!req?.url || (req.method !== 'GET' && req.method !== 'HEAD')) {\n return next();\n }\n\n const pathname = canParseURL(req.url) ? new URL(req.url).pathname : req.url;\n if (!pathname) {\n return next();\n }\n\n debug(`Maybe serve static:`, pathname);\n\n const stream = send(req, pathname, {\n root: staticDirectory,\n extensions: ['html'],\n });\n\n // add file listener for fallthrough\n let forwardError = false;\n stream.on('file', function onFile() {\n // once file is determined, always forward error\n forwardError = true;\n });\n\n // forward errors\n stream.on('error', function error(err: any) {\n if (forwardError || !(err.statusCode < 500)) {\n next(err);\n return;\n }\n\n next();\n });\n\n // pipe\n stream.pipe(res);\n });\n\n middleware.use(serverHandler);\n\n middleware.listen(options.port!);\n}\n\nfunction canParseURL(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\nasync function isStaticExportAsync(dist: string): Promise<boolean> {\n const routesFile = path.join(dist, `server/_expo/routes.json`);\n return !(await fileExistsAsync(routesFile));\n}\n"],"names":["serveAsync","debug","require","inputDir","options","projectRoot","findUpProjectRootOrAssert","setNodeEnv","load","port","resolvePortAsync","defaultPort","fallbackPort","CommandError","serverDist","isDefaultDirectory","path","join","directoryExistsAsync","isStatic","isStaticExportAsync","Log","log","chalk","dim","startStaticServerAsync","startDynamicServerAsync","dist","server","http","createServer","req","res","filePath","decodeURI","url","split","send","root","index","extensions","on","err","status","statusCode","end","pipe","listen","middleware","connect","staticDirectory","serverDirectory","serverHandler","createRequestHandler","build","use","next","setHeader","method","pathname","canParseURL","URL","stream","forwardError","onFile","error","routesFile","fileExistsAsync"],"mappings":";;;;+BAsBsBA;;;eAAAA;;;;gEAtBJ;;;;;;;gEACE;;;;;;;yBACiB;;;;;;;gEACpB;;;;;;;gEACA;;;;;;;gEACA;;;;;;6DAEI;qBACiC;wBACzB;wBACa;yBACf;sBACM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOjC,MAAMC,QAAQC,QAAQ,SAAS;AAGxB,eAAeF,WAAWG,QAAgB,EAAEC,OAAgB;IACjE,MAAMC,cAAcC,IAAAA,iCAAyB,EAACH;IAE9CI,IAAAA,mBAAU,EAAC;IACXL,QAAQ,aAAaM,IAAI,CAACH;IAE1B,MAAMI,OAAO,MAAMC,IAAAA,sBAAgB,EAACL,aAAa;QAC/CM,aAAaP,QAAQK,IAAI;QACzBG,cAAc;IAChB;IAEA,IAAIH,QAAQ,MAAM;QAChB,MAAM,IAAII,oBAAY,CAAC;IACzB;IACAT,QAAQK,IAAI,GAAGA;IAEf,MAAMK,aAAaV,QAAQW,kBAAkB,GAAGC,eAAI,CAACC,IAAI,CAACd,UAAU,UAAUA;IAC9E,0DAA0D;IAE1D,IAAI,CAAE,MAAMe,IAAAA,yBAAoB,EAACJ,aAAc;QAC7C,MAAM,IAAID,oBAAY,CACpB,CAAC,qBAAqB,EAAEC,WAAW,+CAA+C,CAAC;IAEvF;IAEA,MAAMK,WAAW,MAAMC,oBAAoBN;IAE3CO,KAAIC,GAAG,CAACC,gBAAK,CAACC,GAAG,CAAC,CAAC,SAAS,EAAEL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AoBO,IAAY;IAC7C,MAAMuC,aAAalD,eAAI,CAACC,IAAI,CAACU,MAAM,CAAC,wBAAwB,CAAC;IAC7D,OAAO,CAAE,MAAMwC,IAAAA,oBAAe,EAACD;AACjC"}
|
|
@@ -28,16 +28,16 @@ function _paths() {
|
|
|
28
28
|
};
|
|
29
29
|
return data;
|
|
30
30
|
}
|
|
31
|
-
function
|
|
32
|
-
const data = require("
|
|
33
|
-
|
|
31
|
+
function _assert() {
|
|
32
|
+
const data = /*#__PURE__*/ _interop_require_default(require("assert"));
|
|
33
|
+
_assert = function() {
|
|
34
34
|
return data;
|
|
35
35
|
};
|
|
36
36
|
return data;
|
|
37
37
|
}
|
|
38
|
-
function
|
|
39
|
-
const data =
|
|
40
|
-
|
|
38
|
+
function _private() {
|
|
39
|
+
const data = require("expo-server/private");
|
|
40
|
+
_private = function() {
|
|
41
41
|
return data;
|
|
42
42
|
};
|
|
43
43
|
return data;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.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 type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/private';\nimport assert from 'assert';\nimport type { EntriesDev } from 'expo-router/build/rsc/server';\nimport path from 'path';\nimport url from 'url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? 'expo-router/build/rsc/router/noopRouter'\n : 'expo-router/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('expo-router/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\n );\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\n );\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAomBHC,iBAAiB;eAAjBA;;;;yBA1oBsB;;;;;;;yBAEF;;;;;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E,MAAM;IAClB;IACA,IAAI+E,MAAMvD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI+E,MAAMV,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO+E,QAAQ;AACjB;AAEA,SAASrE,WAAWuG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.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 type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport type { EntriesDev } from 'expo-router/build/rsc/server';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'path';\nimport url from 'url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? 'expo-router/build/rsc/router/noopRouter'\n : 'expo-router/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('expo-router/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\n );\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\n );\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAomBHC,iBAAiB;eAAjBA;;;;yBA1oBsB;;;;;;;gEAEhB;;;;;;;yBAEc;;;;;;;gEAChB;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,e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,oBAAoB;AACzC"}
|
|
@@ -13,6 +13,13 @@ Object.defineProperty(exports, "createRouteHandlerMiddleware", {
|
|
|
13
13
|
return createRouteHandlerMiddleware;
|
|
14
14
|
}
|
|
15
15
|
});
|
|
16
|
+
function _http() {
|
|
17
|
+
const data = require("expo-server/adapter/http");
|
|
18
|
+
_http = function() {
|
|
19
|
+
return data;
|
|
20
|
+
};
|
|
21
|
+
return data;
|
|
22
|
+
}
|
|
16
23
|
function _resolve() {
|
|
17
24
|
const data = /*#__PURE__*/ _interop_require_default(require("resolve"));
|
|
18
25
|
_resolve = function() {
|
|
@@ -49,8 +56,7 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
49
56
|
if (!_resolvefrom().default.silent(projectRoot, 'expo-router')) {
|
|
50
57
|
throw new _errors.CommandError(`static and server rendering requires the expo-router package to be installed in your project. Either install the expo-router package or change 'web.output' to 'single' in your app.json.`);
|
|
51
58
|
}
|
|
52
|
-
|
|
53
|
-
return createRequestHandler({
|
|
59
|
+
return (0, _http().createRequestHandler)({
|
|
54
60
|
build: ''
|
|
55
61
|
}, {
|
|
56
62
|
async getRoutesManifest () {
|
|
@@ -104,8 +110,8 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
104
110
|
}
|
|
105
111
|
},
|
|
106
112
|
async handleRouteError (error) {
|
|
107
|
-
|
|
108
|
-
if (ExpoError
|
|
113
|
+
// NOTE(@kitten): ExpoError is currently not exposed by expo-server just yet
|
|
114
|
+
if (error && typeof error === 'object' && error.name === 'ExpoError') {
|
|
109
115
|
// TODO(@krystofwoldrich): Can we show code snippet of the handler?
|
|
110
116
|
// NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.
|
|
111
117
|
delete error.stack;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createServerRouteMiddleware.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 */\n\nimport type { ProjectConfig } from '@expo/config';\nimport { MiddlewareModule } from '@expo/server/build/types';\nimport resolve from 'resolve';\nimport resolveFrom from 'resolve-from';\nimport { promisify } from 'util';\n\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync, logMetroError } from './metroErrorInterface';\nimport {\n warnInvalidWebOutput,\n warnInvalidMiddlewareOutput,\n warnInvalidMiddlewareMatcherSettings,\n} from './router';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n appDir: string;\n routerRoot: string;\n getStaticPageAsync: (pathname: string) => Promise<{ content: string }>;\n bundleApiRoute: (\n functionFilePath: string\n ) => Promise<null | Record<string, Function> | Response>;\n config: ProjectConfig;\n } & import('expo-router/build/routes-manifest').Options\n) {\n if (!resolveFrom.silent(projectRoot, 'expo-router')) {\n throw new CommandError(\n `static and server rendering requires the expo-router package to be installed in your project. Either install the expo-router package or change 'web.output' to 'single' in your app.json.`\n );\n }\n\n const { createRequestHandler } =\n require('@expo/server/adapter/http') as typeof import('@expo/server/adapter/http');\n\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n redirects: [],\n rewrites: [],\n }\n );\n },\n async getHtml(request) {\n try {\n const { content } = await options.getStaticPageAsync(request.url);\n return content;\n } catch (error: any) {\n // Forward the Metro server response as-is. It won't be pretty, but at least it will be accurate.\n\n try {\n return new Response(\n await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot,\n }),\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n } catch (staticError: any) {\n debug('Failed to render static error overlay:', staticError);\n // Fallback error for when Expo Router is misconfigured in the project.\n return new Response(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>',\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n }\n },\n async handleRouteError(error) {\n const { ExpoError } = require('@expo/server') as typeof import('@expo/server');\n\n if (ExpoError.isExpoError(error)) {\n // TODO(@krystofwoldrich): Can we show code snippet of the handler?\n // NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.\n delete error.stack;\n }\n\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n },\n async getApiRoute(route) {\n const { exp } = options.config;\n if (exp.web?.output !== 'server') {\n warnInvalidWebOutput();\n }\n\n const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\n try {\n debug(`Bundling API route at: ${resolvedFunctionPath}`);\n return await options.bundleApiRoute(resolvedFunctionPath!);\n } catch (error: any) {\n return new Response(\n 'Failed to load API Route: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n async getMiddleware(route) {\n const { exp } = options.config;\n\n if (!options.unstable_useServerMiddleware) {\n return {\n default: () => {\n throw new CommandError(\n 'Server middleware is not enabled. Add unstable_useServerMiddleware: true to your `expo-router` plugin config.'\n );\n },\n };\n }\n\n if (exp.web?.output !== 'server') {\n warnInvalidMiddlewareOutput();\n return {\n default: () => {\n console.warn(\n 'Server middleware is only supported when web.output is set to \"server\" in your app config'\n );\n },\n };\n }\n\n const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n const middlewareModule = (await options.bundleApiRoute(\n resolvedFunctionPath!\n )) as unknown as MiddlewareModule;\n\n if (middlewareModule.unstable_settings?.matcher) {\n warnInvalidMiddlewareMatcherSettings(middlewareModule.unstable_settings?.matcher);\n }\n\n return middlewareModule;\n } catch (error: any) {\n return new Response(\n 'Failed to load middleware: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n }\n );\n}\n"],"names":["createRouteHandlerMiddleware","debug","require","resolveAsync","promisify","resolve","projectRoot","options","resolveFrom","silent","CommandError","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","redirects","rewrites","getHtml","request","content","getStaticPageAsync","url","error","Response","getErrorOverlayHtmlAsync","routerRoot","status","headers","staticError","message","handleRouteError","ExpoError","isExpoError","stack","htmlServerError","getApiRoute","route","exp","config","web","output","warnInvalidWebOutput","resolvedFunctionPath","extensions","basedir","appDir","bundleApiRoute","getMiddleware","unstable_useServerMiddleware","default","warnInvalidMiddlewareOutput","console","warn","middlewareModule","unstable_settings","matcher","warnInvalidMiddlewareMatcherSettings"],"mappings":"AAAA;;;;;CAKC;;;;+BAwBeA;;;eAAAA;;;;gEApBI;;;;;;;gEACI;;;;;;;yBACE;;;;;;qCAEI;qCAC0B;wBAKjD;wBACsB;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,eAAeC,IAAAA,iBAAS,EAACC,kBAAO;AAK/B,SAASL,6BACdM,WAAmB,EACnBC,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SAAS;wBACPE,QAAQC,IAAI,CACV;oBAEJ;gBACF;YACF;YAEA,MAAMV,uBAAuB,MAAM/C,aAAayC,MAAM3B,IAAI,EAAE;gBAC1DkC,YAAY;oBAAC;oBAAO;oBAAQ;oBAAO;iBAAO;gBAC1CC,SAAS7C,QAAQ8C,MAAM;YACzB;YAEA,IAAI;oBAMEQ;gBALJ5D,MAAM,CAAC,wBAAwB,EAAEiD,sBAAsB;gBACvD,MAAMW,mBAAoB,MAAMtD,QAAQ+C,cAAc,CACpDJ;gBAGF,KAAIW,sCAAAA,iBAAiBC,iBAAiB,qBAAlCD,oCAAoCE,OAAO,EAAE;wBACVF;oBAArCG,IAAAA,4CAAoC,GAACH,uCAAAA,iBAAiBC,iBAAiB,qBAAlCD,qCAAoCE,OAAO;gBAClF;gBAEA,OAAOF;YACT,EAAE,OAAO/B,OAAY;gBACnB,OAAO,IAAIC,SACT,gCAAgCmB,uBAAuB,SAASpB,MAAMO,OAAO,EAC7E;oBACEH,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ;QACF;IACF;AAEJ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createServerRouteMiddleware.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 */\n\nimport type { ProjectConfig } from '@expo/config';\nimport type { MiddlewareSettings } from 'expo-server';\nimport { createRequestHandler } from 'expo-server/adapter/http';\nimport resolve from 'resolve';\nimport resolveFrom from 'resolve-from';\nimport { promisify } from 'util';\n\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync } from './metroErrorInterface';\nimport {\n warnInvalidWebOutput,\n warnInvalidMiddlewareOutput,\n warnInvalidMiddlewareMatcherSettings,\n} from './router';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n appDir: string;\n routerRoot: string;\n getStaticPageAsync: (pathname: string) => Promise<{ content: string }>;\n bundleApiRoute: (\n functionFilePath: string\n ) => Promise<null | Record<string, Function> | Response>;\n config: ProjectConfig;\n headers: Record<string, string | string[]>;\n } & import('expo-router/build/routes-manifest').Options\n) {\n if (!resolveFrom.silent(projectRoot, 'expo-router')) {\n throw new CommandError(\n `static and server rendering requires the expo-router package to be installed in your project. Either install the expo-router package or change 'web.output' to 'single' in your app.json.`\n );\n }\n\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n redirects: [],\n rewrites: [],\n }\n );\n },\n async getHtml(request) {\n try {\n const { content } = await options.getStaticPageAsync(request.url);\n return content;\n } catch (error: any) {\n // Forward the Metro server response as-is. It won't be pretty, but at least it will be accurate.\n\n try {\n return new Response(\n await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot,\n }),\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n } catch (staticError: any) {\n debug('Failed to render static error overlay:', staticError);\n // Fallback error for when Expo Router is misconfigured in the project.\n return new Response(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>',\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n }\n },\n async handleRouteError(error) {\n // NOTE(@kitten): ExpoError is currently not exposed by expo-server just yet\n if (error && typeof error === 'object' && error.name === 'ExpoError') {\n // TODO(@krystofwoldrich): Can we show code snippet of the handler?\n // NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.\n delete error.stack;\n }\n\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n },\n async getApiRoute(route) {\n const { exp } = options.config;\n if (exp.web?.output !== 'server') {\n warnInvalidWebOutput();\n }\n\n const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\n try {\n debug(`Bundling API route at: ${resolvedFunctionPath}`);\n return await options.bundleApiRoute(resolvedFunctionPath!);\n } catch (error: any) {\n return new Response(\n 'Failed to load API Route: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n async getMiddleware(route) {\n const { exp } = options.config;\n\n if (!options.unstable_useServerMiddleware) {\n return {\n default: () => {\n throw new CommandError(\n 'Server middleware is not enabled. Add unstable_useServerMiddleware: true to your `expo-router` plugin config.'\n );\n },\n };\n }\n\n if (exp.web?.output !== 'server') {\n warnInvalidMiddlewareOutput();\n return {\n default: () => {\n console.warn(\n 'Server middleware is only supported when web.output is set to \"server\" in your app config'\n );\n },\n };\n }\n\n const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n const middlewareModule = (await options.bundleApiRoute(resolvedFunctionPath!)) as any;\n\n if ((middlewareModule.unstable_settings as MiddlewareSettings)?.matcher) {\n warnInvalidMiddlewareMatcherSettings(middlewareModule.unstable_settings?.matcher);\n }\n\n return middlewareModule;\n } catch (error: any) {\n return new Response(\n 'Failed to load middleware: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n }\n );\n}\n"],"names":["createRouteHandlerMiddleware","debug","require","resolveAsync","promisify","resolve","projectRoot","options","resolveFrom","silent","CommandError","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","redirects","rewrites","getHtml","request","content","getStaticPageAsync","url","error","Response","getErrorOverlayHtmlAsync","routerRoot","status","headers","staticError","message","handleRouteError","name","stack","htmlServerError","getApiRoute","route","exp","config","web","output","warnInvalidWebOutput","resolvedFunctionPath","extensions","basedir","appDir","bundleApiRoute","getMiddleware","unstable_useServerMiddleware","default","warnInvalidMiddlewareOutput","console","warn","middlewareModule","unstable_settings","matcher","warnInvalidMiddlewareMatcherSettings"],"mappings":"AAAA;;;;;CAKC;;;;+BAyBeA;;;eAAAA;;;;yBArBqB;;;;;;;gEACjB;;;;;;;gEACI;;;;;;;yBACE;;;;;;qCAEI;qCACW;wBAKlC;wBACsB;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,eAAeC,IAAAA,iBAAS,EAACC,kBAAO;AAK/B,SAASL,6BACdM,WAAmB,EACnBC,OASuD;IAEvD,IAAI,CAACC,sBAAW,CAACC,MAAM,CAACH,aAAa,gBAAgB;QACnD,MAAM,IAAII,oBAAY,CACpB,CAAC,yLAAyL,CAAC;IAE/L;IAEA,OAAOC,IAAAA,4BAAoB,EACzB;QAAEC,OAAO;IAAG,GACZ;QACE,MAAMC;YACJ,MAAMC,WAAW,MAAMC,IAAAA,kCAAa,EAAST,aAAaC;YAC1DN,MAAM,YAAYa;YAClB,2BAA2B;YAC3B,6BAA6B;YAC7B,OACEA,YAAY;gBACV,uDAAuD;gBACvDE,YAAY;oBACV;wBACEC,MAAM;wBACNC,MAAM;wBACNC,WAAW,CAAC;wBACZC,YAAY;oBACd;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AiB,qBAAlCD,qCAAoCE,OAAO;gBAClF;gBAEA,OAAOF;YACT,EAAE,OAAO9B,OAAY;gBACnB,OAAO,IAAIC,SACT,gCAAgCkB,uBAAuB,SAASnB,MAAMO,OAAO,EAC7E;oBACEH,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ;QACF;IACF;AAEJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/fetchRouterManifest.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 resolveFrom from 'resolve-from';\n\nimport { getRoutePaths } from './router';\n\nexport type ExpoRouterServerManifestV1Route<TRegex = string> = {\n file: string;\n page: string;\n routeKeys: Record<string, string>;\n namedRegex: TRegex;\n generated?: boolean;\n};\n\nexport type ExpoRouterServerManifestV1Middleware = {\n /**\n * Path to the module that contains the middleware function as a default export.\n *\n * @example _expo/functions/+middleware.js\n */\n file: string;\n};\n\nexport type ExpoRouterServerManifestV1<TRegex = string> = {\n middleware?: ExpoRouterServerManifestV1Middleware;\n apiRoutes: ExpoRouterServerManifestV1Route<TRegex>[];\n htmlRoutes: ExpoRouterServerManifestV1Route<TRegex>[];\n notFoundRoutes: ExpoRouterServerManifestV1Route<TRegex>[];\n redirects: ExpoRouterServerManifestV1Route<TRegex>[];\n rewrites: ExpoRouterServerManifestV1Route<TRegex>[];\n};\n\nfunction getExpoRouteManifestBuilderAsync(projectRoot: string) {\n return require(resolveFrom(projectRoot, 'expo-router/build/routes-manifest'))\n .createRoutesManifest as typeof import('expo-router/build/routes-manifest').createRoutesManifest;\n}\n\n// TODO: Simplify this now that we use Node.js directly, no need for the Metro bundler caching layer.\nexport async function fetchManifest<TRegex = string>(\n projectRoot: string,\n options: {\n asJson?: boolean;\n appDir: string;\n } & import('expo-router/build/routes-manifest').Options\n): Promise<ExpoRouterServerManifestV1<TRegex> | null> {\n const getManifest = getExpoRouteManifestBuilderAsync(projectRoot);\n const paths = getRoutePaths(options.appDir);\n // Get the serialized manifest\n const jsonManifest = getManifest(paths, options);\n\n if (!jsonManifest) {\n return null;\n }\n\n if (!jsonManifest.htmlRoutes || !jsonManifest.apiRoutes) {\n throw new Error('Routes manifest is malformed: ' + JSON.stringify(jsonManifest, null, 2));\n }\n\n if (!options.asJson) {\n // @ts-expect-error\n return inflateManifest(jsonManifest);\n }\n // @ts-expect-error\n return jsonManifest;\n}\n\n// Convert the serialized manifest to a usable format\nexport function inflateManifest(\n json: ExpoRouterServerManifestV1<string>\n): ExpoRouterServerManifestV1<RegExp> {\n return {\n ...json,\n middleware: json.middleware,\n htmlRoutes: json.htmlRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n apiRoutes: json.apiRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n notFoundRoutes: json.notFoundRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n redirects: json.redirects?.map((value: any) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n rewrites: json.rewrites?.map((value: any) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n };\n}\n"],"names":["fetchManifest","inflateManifest","getExpoRouteManifestBuilderAsync","projectRoot","require","resolveFrom","createRoutesManifest","options","getManifest","paths","getRoutePaths","appDir","jsonManifest","htmlRoutes","apiRoutes","Error","JSON","stringify","asJson","json","middleware","map","value","namedRegex","RegExp","notFoundRoutes","redirects","rewrites"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/fetchRouterManifest.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 resolveFrom from 'resolve-from';\n\nimport { getRoutePaths } from './router';\n\nexport type ExpoRouterServerManifestV1Route<TRegex = string> = {\n file: string;\n page: string;\n routeKeys: Record<string, string>;\n namedRegex: TRegex;\n generated?: boolean;\n};\n\nexport type ExpoRouterServerManifestV1Middleware = {\n /**\n * Path to the module that contains the middleware function as a default export.\n *\n * @example _expo/functions/+middleware.js\n */\n file: string;\n};\n\nexport type ExpoRouterServerManifestV1<TRegex = string> = {\n middleware?: ExpoRouterServerManifestV1Middleware;\n headers?: Record<string, string | string[]>;\n apiRoutes: ExpoRouterServerManifestV1Route<TRegex>[];\n htmlRoutes: ExpoRouterServerManifestV1Route<TRegex>[];\n notFoundRoutes: ExpoRouterServerManifestV1Route<TRegex>[];\n redirects: ExpoRouterServerManifestV1Route<TRegex>[];\n rewrites: ExpoRouterServerManifestV1Route<TRegex>[];\n};\n\nfunction getExpoRouteManifestBuilderAsync(projectRoot: string) {\n return require(resolveFrom(projectRoot, 'expo-router/build/routes-manifest'))\n .createRoutesManifest as typeof import('expo-router/build/routes-manifest').createRoutesManifest;\n}\n\n// TODO: Simplify this now that we use Node.js directly, no need for the Metro bundler caching layer.\nexport async function fetchManifest<TRegex = string>(\n projectRoot: string,\n options: {\n asJson?: boolean;\n appDir: string;\n } & import('expo-router/build/routes-manifest').Options\n): Promise<ExpoRouterServerManifestV1<TRegex> | null> {\n const getManifest = getExpoRouteManifestBuilderAsync(projectRoot);\n const paths = getRoutePaths(options.appDir);\n // Get the serialized manifest\n const jsonManifest = getManifest(paths, options);\n\n if (!jsonManifest) {\n return null;\n }\n\n if (!jsonManifest.htmlRoutes || !jsonManifest.apiRoutes) {\n throw new Error('Routes manifest is malformed: ' + JSON.stringify(jsonManifest, null, 2));\n }\n\n if (!options.asJson) {\n // @ts-expect-error\n return inflateManifest(jsonManifest);\n }\n // @ts-expect-error\n return jsonManifest;\n}\n\n// Convert the serialized manifest to a usable format\nexport function inflateManifest(\n json: ExpoRouterServerManifestV1<string>\n): ExpoRouterServerManifestV1<RegExp> {\n return {\n ...json,\n middleware: json.middleware,\n htmlRoutes: json.htmlRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n apiRoutes: json.apiRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n notFoundRoutes: json.notFoundRoutes?.map((value) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n redirects: json.redirects?.map((value: any) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n rewrites: json.rewrites?.map((value: any) => {\n return {\n ...value,\n namedRegex: new RegExp(value.namedRegex),\n };\n }),\n };\n}\n"],"names":["fetchManifest","inflateManifest","getExpoRouteManifestBuilderAsync","projectRoot","require","resolveFrom","createRoutesManifest","options","getManifest","paths","getRoutePaths","appDir","jsonManifest","htmlRoutes","apiRoutes","Error","JSON","stringify","asJson","json","middleware","map","value","namedRegex","RegExp","notFoundRoutes","redirects","rewrites"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAsCqBA,aAAa;eAAbA;;IA6BNC,eAAe;eAAfA;;;;gEAlEQ;;;;;;wBAEM;;;;;;AA6B9B,SAASC,iCAAiCC,WAAmB;IAC3D,OAAOC,QAAQC,IAAAA,sBAAW,EAACF,aAAa,sCACrCG,oBAAoB;AACzB;AAGO,eAAeN,cACpBG,WAAmB,EACnBI,OAGuD;IAEvD,MAAMC,cAAcN,iCAAiCC;IACrD,MAAMM,QAAQC,IAAAA,qBAAa,EAACH,QAAQI,MAAM;IAC1C,8BAA8B;IAC9B,MAAMC,eAAeJ,YAAYC,OAAOF;IAExC,IAAI,CAACK,cAAc;QACjB,OAAO;IACT;IAEA,IAAI,CAACA,aAAaC,UAAU,IAAI,CAACD,aAAaE,SAAS,EAAE;QACvD,MAAM,IAAIC,MAAM,mCAAmCC,KAAKC,SAAS,CAACL,cAAc,MAAM;IACxF;IAEA,IAAI,CAACL,QAAQW,MAAM,EAAE;QACnB,mBAAmB;QACnB,OAAOjB,gBAAgBW;IACzB;IACA,mBAAmB;IACnB,OAAOA;AACT;AAGO,SAASX,gBACdkB,IAAwC;QAK1BA,kBAMDA,iBAMKA,sBAMLA,iBAMDA;IA3BZ,OAAO;QACL,GAAGA,IAAI;QACPC,YAAYD,KAAKC,UAAU;QAC3BP,UAAU,GAAEM,mBAAAA,KAAKN,UAAU,qBAAfM,iBAAiBE,GAAG,CAAC,CAACC;YAChC,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;QACAT,SAAS,GAAEK,kBAAAA,KAAKL,SAAS,qBAAdK,gBAAgBE,GAAG,CAAC,CAACC;YAC9B,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;QACAE,cAAc,GAAEN,uBAAAA,KAAKM,cAAc,qBAAnBN,qBAAqBE,GAAG,CAAC,CAACC;YACxC,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;QACAG,SAAS,GAAEP,kBAAAA,KAAKO,SAAS,qBAAdP,gBAAgBE,GAAG,CAAC,CAACC;YAC9B,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;QACAI,QAAQ,GAAER,iBAAAA,KAAKQ,QAAQ,qBAAbR,eAAeE,GAAG,CAAC,CAACC;YAC5B,OAAO;gBACL,GAAGA,KAAK;gBACRC,YAAY,IAAIC,OAAOF,MAAMC,UAAU;YACzC;QACF;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/router.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport type { MiddlewareMatcher } from '@expo/server/build/types';\nimport chalk from 'chalk';\nimport { sync as globSync } from 'glob';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { directoryExistsSync } from '../../../utils/dir';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { learnMore } from '../../../utils/link';\n\nconst debug = require('debug')('expo:start:server:metro:router') as typeof console.log;\n\n/**\n * Get the relative path for requiring the `/app` folder relative to the `expo-router/entry` file.\n * This mechanism does require the server to restart after the `expo-router` package is installed.\n */\nexport function getAppRouterRelativeEntryPath(\n projectRoot: string,\n routerDirectory: string = getRouterDirectory(projectRoot)\n): string | undefined {\n // Auto pick App entry\n const routerEntry =\n resolveFrom.silent(projectRoot, 'expo-router/entry') ?? getFallbackEntryRoot(projectRoot);\n if (!routerEntry) {\n return undefined;\n }\n // It doesn't matter if the app folder exists.\n const appFolder = path.join(projectRoot, routerDirectory);\n const appRoot = path.relative(path.dirname(routerEntry), appFolder);\n debug('expo-router entry', routerEntry, appFolder, appRoot);\n return appRoot;\n}\n\n/** If the `expo-router` package is not installed, then use the `expo` package to determine where the node modules are relative to the project. */\nfunction getFallbackEntryRoot(projectRoot: string): string {\n const expoRoot = resolveFrom.silent(projectRoot, 'expo/package.json');\n if (expoRoot) {\n return path.join(path.dirname(path.dirname(expoRoot)), 'expo-router/entry');\n }\n return path.join(projectRoot, 'node_modules/expo-router/entry');\n}\n\nexport function getRouterDirectoryModuleIdWithManifest(\n projectRoot: string,\n exp: ExpoConfig\n): string {\n return toPosixPath(exp.extra?.router?.root ?? getRouterDirectory(projectRoot));\n}\n\nlet hasWarnedAboutSrcDir = false;\nconst logSrcDir = () => {\n if (hasWarnedAboutSrcDir) return;\n hasWarnedAboutSrcDir = true;\n Log.log(chalk.gray('Using src/app as the root directory for Expo Router.'));\n};\n\nexport function getRouterDirectory(projectRoot: string): string {\n // more specific directories first\n if (directoryExistsSync(path.join(projectRoot, 'src', 'app'))) {\n logSrcDir();\n return path.join('src', 'app');\n }\n\n debug('Using app as the root directory for Expo Router.');\n return 'app';\n}\n\nexport function isApiRouteConvention(name: string): boolean {\n return /\\+api\\.[tj]sx?$/.test(name);\n}\n\nexport function getApiRoutesForDirectory(cwd: string) {\n return globSync('**/*+api.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n}\n\n/**\n * Gets the +middleware file for a given directory. In\n * @param cwd\n */\nexport function getMiddlewareForDirectory(cwd: string): string | null {\n const files = globSync('+middleware.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n\n if (files.length === 0) return null;\n\n if (files.length > 1) {\n // In development, throw an error if there are multiple root-level middleware files\n if (process.env.NODE_ENV !== 'production') {\n const relativePaths = files.map((f) => './' + path.relative(cwd, f)).sort();\n throw new Error(\n `Only one middleware file is allowed. Keep one of the conflicting files: ${relativePaths.map((p) => `\"${p}\"`).join(' or ')}`\n );\n }\n }\n\n return files[0];\n}\n\n// Used to emulate a context module, but way faster. TODO: May need to adjust the extensions to stay in sync with Metro.\nexport function getRoutePaths(cwd: string) {\n return globSync('**/*.@(ts|tsx|js|jsx)', {\n cwd,\n dot: true,\n }).map((p) => './' + normalizePaths(p));\n}\n\nfunction normalizePaths(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nlet hasWarnedAboutApiRouteOutput = false;\nlet hasWarnedAboutMiddlewareOutput = false;\n\nexport function hasWarnedAboutApiRoutes() {\n return hasWarnedAboutApiRouteOutput;\n}\n\nexport function hasWarnedAboutMiddleware() {\n return hasWarnedAboutMiddlewareOutput;\n}\n\nexport function warnInvalidWebOutput() {\n if (!hasWarnedAboutApiRouteOutput) {\n Log.warn(\n chalk.yellow`Using API routes requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutApiRouteOutput = true;\n}\n\nexport function warnInvalidMiddlewareOutput() {\n if (!hasWarnedAboutMiddlewareOutput) {\n Log.warn(\n chalk.yellow`Using middleware requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutMiddlewareOutput = true;\n}\n\nexport function warnInvalidMiddlewareMatcherSettings(matcher: MiddlewareMatcher) {\n const validMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];\n\n // Ensure methods are valid HTTP methods\n if (matcher.methods) {\n if (!Array.isArray(matcher.methods)) {\n Log.error(\n chalk.red`Middleware matcher methods must be an array of valid HTTP methods. Supported methods are: ${validMethods.join(', ')}`\n );\n } else {\n for (const method of matcher.methods) {\n if (!validMethods.includes(method)) {\n Log.error(\n chalk.red`Invalid middleware HTTP method: ${method}. Supported methods are: ${validMethods.join(', ')}`\n );\n }\n }\n }\n }\n\n // Ensure patterns are either a string or RegExp\n if (matcher.patterns) {\n const patterns = Array.isArray(matcher.patterns) ? matcher.patterns : [matcher.patterns];\n for (const pattern of patterns) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n Log.error(\n chalk.red`Middleware matcher patterns must be strings or regular expressions. Received: ${String(\n pattern\n )}`\n );\n }\n\n if (typeof pattern === 'string' && !pattern.startsWith('/')) {\n Log.error(\n chalk.red`String patterns in middleware matcher must start with '/'. Received: ${pattern}`\n );\n }\n }\n }\n}\n"],"names":["getApiRoutesForDirectory","getAppRouterRelativeEntryPath","getMiddlewareForDirectory","getRoutePaths","getRouterDirectory","getRouterDirectoryModuleIdWithManifest","hasWarnedAboutApiRoutes","hasWarnedAboutMiddleware","isApiRouteConvention","warnInvalidMiddlewareMatcherSettings","warnInvalidMiddlewareOutput","warnInvalidWebOutput","debug","require","projectRoot","routerDirectory","routerEntry","resolveFrom","silent","getFallbackEntryRoot","undefined","appFolder","path","join","appRoot","relative","dirname","expoRoot","exp","toPosixPath","extra","router","root","hasWarnedAboutSrcDir","logSrcDir","Log","log","chalk","gray","directoryExistsSync","name","test","cwd","globSync","absolute","dot","files","length","process","env","NODE_ENV","relativePaths","map","f","sort","Error","p","normalizePaths","replace","hasWarnedAboutApiRouteOutput","hasWarnedAboutMiddlewareOutput","warn","yellow","learnMore","matcher","validMethods","methods","Array","isArray","error","red","method","includes","patterns","pattern","RegExp","String","startsWith"],"mappings":";;;;;;;;;;;IAyEgBA,wBAAwB;eAAxBA;;IAvDAC,6BAA6B;eAA7BA;;IAmEAC,yBAAyB;eAAzBA;;IAuBAC,aAAa;eAAbA;;IAlDAC,kBAAkB;eAAlBA;;IAdAC,sCAAsC;eAAtCA;;IA8EAC,uBAAuB;eAAvBA;;IAIAC,wBAAwB;eAAxBA;;IAzDAC,oBAAoB;eAApBA;;IAqFAC,oCAAoC;eAApCA;;IAZAC,2BAA2B;eAA3BA;;IAZAC,oBAAoB;eAApBA;;;;gEAhIE;;;;;;;yBACe;;;;;;;gEAChB;;;;;;;gEACO;;;;;;qBAEJ;qBACgB;0BACR;sBACF;;;;;;AAE1B,MAAMC,QAAQC,QAAQ,SAAS;AAMxB,SAASZ,8BACda,WAAmB,EACnBC,kBAA0BX,mBAAmBU,YAAY;IAEzD,sBAAsB;IACtB,MAAME,cACJC,sBAAW,CAACC,MAAM,CAACJ,aAAa,wBAAwBK,qBAAqBL;IAC/E,IAAI,CAACE,aAAa;QAChB,OAAOI;IACT;IACA,8CAA8C;IAC9C,MAAMC,YAAYC,eAAI,CAACC,IAAI,CAACT,aAAaC;IACzC,MAAMS,UAAUF,eAAI,CAACG,QAAQ,CAACH,eAAI,CAACI,OAAO,CAACV,cAAcK;IACzDT,MAAM,qBAAqBI,aAAaK,WAAWG;IACnD,OAAOA;AACT;AAEA,gJAAgJ,GAChJ,SAASL,qBAAqBL,WAAmB;IAC/C,MAAMa,WAAWV,sBAAW,CAACC,MAAM,CAACJ,aAAa;IACjD,IAAIa,UAAU;QACZ,OAAOL,eAAI,CAACC,IAAI,CAACD,eAAI,CAACI,OAAO,CAACJ,eAAI,CAACI,OAAO,CAACC,YAAY;IACzD;IACA,OAAOL,eAAI,CAACC,IAAI,CAACT,aAAa;AAChC;AAEO,SAAST,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EAAEC,OAAO,yBAAyB,EAAEN,aAAa1C,IAAI,CAAC,MAAM,CAAC;gBAE3G;YACF;QACF;IACF;IAEA,gDAAgD;IAChD,IAAIyC,QAAQS,QAAQ,EAAE;QACpB,MAAMA,WAAWN,MAAMC,OAAO,CAACJ,QAAQS,QAAQ,IAAIT,QAAQS,QAAQ,GAAG;YAACT,QAAQS,QAAQ;SAAC;QACxF,KAAK,MAAMC,WAAWD,SAAU;YAC9B,IAAI,OAAOC,YAAY,YAAY,CAAEA,CAAAA,mBAAmBC,MAAK,GAAI;gBAC/DxC,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,8EAA8E,EAAEM,OACxFF,SACA,CAAC;YAEP;YAEA,IAAI,OAAOA,YAAY,YAAY,CAACA,QAAQG,UAAU,CAAC,MAAM;gBAC3D1C,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,qEAAqE,EAAEI,QAAQ,CAAC;YAE9F;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/router.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport chalk from 'chalk';\nimport type { MiddlewareMatcher } from 'expo-server';\nimport { sync as globSync } from 'glob';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { directoryExistsSync } from '../../../utils/dir';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { learnMore } from '../../../utils/link';\n\nconst debug = require('debug')('expo:start:server:metro:router') as typeof console.log;\n\n/**\n * Get the relative path for requiring the `/app` folder relative to the `expo-router/entry` file.\n * This mechanism does require the server to restart after the `expo-router` package is installed.\n */\nexport function getAppRouterRelativeEntryPath(\n projectRoot: string,\n routerDirectory: string = getRouterDirectory(projectRoot)\n): string | undefined {\n // Auto pick App entry\n const routerEntry =\n resolveFrom.silent(projectRoot, 'expo-router/entry') ?? getFallbackEntryRoot(projectRoot);\n if (!routerEntry) {\n return undefined;\n }\n // It doesn't matter if the app folder exists.\n const appFolder = path.join(projectRoot, routerDirectory);\n const appRoot = path.relative(path.dirname(routerEntry), appFolder);\n debug('expo-router entry', routerEntry, appFolder, appRoot);\n return appRoot;\n}\n\n/** If the `expo-router` package is not installed, then use the `expo` package to determine where the node modules are relative to the project. */\nfunction getFallbackEntryRoot(projectRoot: string): string {\n const expoRoot = resolveFrom.silent(projectRoot, 'expo/package.json');\n if (expoRoot) {\n return path.join(path.dirname(path.dirname(expoRoot)), 'expo-router/entry');\n }\n return path.join(projectRoot, 'node_modules/expo-router/entry');\n}\n\nexport function getRouterDirectoryModuleIdWithManifest(\n projectRoot: string,\n exp: ExpoConfig\n): string {\n return toPosixPath(exp.extra?.router?.root ?? getRouterDirectory(projectRoot));\n}\n\nlet hasWarnedAboutSrcDir = false;\nconst logSrcDir = () => {\n if (hasWarnedAboutSrcDir) return;\n hasWarnedAboutSrcDir = true;\n Log.log(chalk.gray('Using src/app as the root directory for Expo Router.'));\n};\n\nexport function getRouterDirectory(projectRoot: string): string {\n // more specific directories first\n if (directoryExistsSync(path.join(projectRoot, 'src', 'app'))) {\n logSrcDir();\n return path.join('src', 'app');\n }\n\n debug('Using app as the root directory for Expo Router.');\n return 'app';\n}\n\nexport function isApiRouteConvention(name: string): boolean {\n return /\\+api\\.[tj]sx?$/.test(name);\n}\n\nexport function getApiRoutesForDirectory(cwd: string) {\n return globSync('**/*+api.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n}\n\n/**\n * Gets the +middleware file for a given directory. In\n * @param cwd\n */\nexport function getMiddlewareForDirectory(cwd: string): string | null {\n const files = globSync('+middleware.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n\n if (files.length === 0) return null;\n\n if (files.length > 1) {\n // In development, throw an error if there are multiple root-level middleware files\n if (process.env.NODE_ENV !== 'production') {\n const relativePaths = files.map((f) => './' + path.relative(cwd, f)).sort();\n throw new Error(\n `Only one middleware file is allowed. Keep one of the conflicting files: ${relativePaths.map((p) => `\"${p}\"`).join(' or ')}`\n );\n }\n }\n\n return files[0];\n}\n\n// Used to emulate a context module, but way faster. TODO: May need to adjust the extensions to stay in sync with Metro.\nexport function getRoutePaths(cwd: string) {\n return globSync('**/*.@(ts|tsx|js|jsx)', {\n cwd,\n dot: true,\n }).map((p) => './' + normalizePaths(p));\n}\n\nfunction normalizePaths(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nlet hasWarnedAboutApiRouteOutput = false;\nlet hasWarnedAboutMiddlewareOutput = false;\n\nexport function hasWarnedAboutApiRoutes() {\n return hasWarnedAboutApiRouteOutput;\n}\n\nexport function hasWarnedAboutMiddleware() {\n return hasWarnedAboutMiddlewareOutput;\n}\n\nexport function warnInvalidWebOutput() {\n if (!hasWarnedAboutApiRouteOutput) {\n Log.warn(\n chalk.yellow`Using API routes requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutApiRouteOutput = true;\n}\n\nexport function warnInvalidMiddlewareOutput() {\n if (!hasWarnedAboutMiddlewareOutput) {\n Log.warn(\n chalk.yellow`Using middleware requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutMiddlewareOutput = true;\n}\n\nexport function warnInvalidMiddlewareMatcherSettings(matcher: MiddlewareMatcher) {\n const validMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];\n\n // Ensure methods are valid HTTP methods\n if (matcher.methods) {\n if (!Array.isArray(matcher.methods)) {\n Log.error(\n chalk.red`Middleware matcher methods must be an array of valid HTTP methods. Supported methods are: ${validMethods.join(', ')}`\n );\n } else {\n for (const method of matcher.methods) {\n if (!validMethods.includes(method)) {\n Log.error(\n chalk.red`Invalid middleware HTTP method: ${method}. Supported methods are: ${validMethods.join(', ')}`\n );\n }\n }\n }\n }\n\n // Ensure patterns are either a string or RegExp\n if (matcher.patterns) {\n const patterns = Array.isArray(matcher.patterns) ? matcher.patterns : [matcher.patterns];\n for (const pattern of patterns) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n Log.error(\n chalk.red`Middleware matcher patterns must be strings or regular expressions. Received: ${String(\n pattern\n )}`\n );\n }\n\n if (typeof pattern === 'string' && !pattern.startsWith('/')) {\n Log.error(\n chalk.red`String patterns in middleware matcher must start with '/'. Received: ${pattern}`\n );\n }\n }\n }\n}\n"],"names":["getApiRoutesForDirectory","getAppRouterRelativeEntryPath","getMiddlewareForDirectory","getRoutePaths","getRouterDirectory","getRouterDirectoryModuleIdWithManifest","hasWarnedAboutApiRoutes","hasWarnedAboutMiddleware","isApiRouteConvention","warnInvalidMiddlewareMatcherSettings","warnInvalidMiddlewareOutput","warnInvalidWebOutput","debug","require","projectRoot","routerDirectory","routerEntry","resolveFrom","silent","getFallbackEntryRoot","undefined","appFolder","path","join","appRoot","relative","dirname","expoRoot","exp","toPosixPath","extra","router","root","hasWarnedAboutSrcDir","logSrcDir","Log","log","chalk","gray","directoryExistsSync","name","test","cwd","globSync","absolute","dot","files","length","process","env","NODE_ENV","relativePaths","map","f","sort","Error","p","normalizePaths","replace","hasWarnedAboutApiRouteOutput","hasWarnedAboutMiddlewareOutput","warn","yellow","learnMore","matcher","validMethods","methods","Array","isArray","error","red","method","includes","patterns","pattern","RegExp","String","startsWith"],"mappings":";;;;;;;;;;;IAyEgBA,wBAAwB;eAAxBA;;IAvDAC,6BAA6B;eAA7BA;;IAmEAC,yBAAyB;eAAzBA;;IAuBAC,aAAa;eAAbA;;IAlDAC,kBAAkB;eAAlBA;;IAdAC,sCAAsC;eAAtCA;;IA8EAC,uBAAuB;eAAvBA;;IAIAC,wBAAwB;eAAxBA;;IAzDAC,oBAAoB;eAApBA;;IAqFAC,oCAAoC;eAApCA;;IAZAC,2BAA2B;eAA3BA;;IA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AAEM,OACxFF,SACA,CAAC;YAEP;YAEA,IAAI,OAAOA,YAAY,YAAY,CAACA,QAAQG,UAAU,CAAC,MAAM;gBAC3D1C,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,qEAAqE,EAAEI,QAAQ,CAAC;YAE9F;QACF;IACF;AACF"}
|
|
@@ -74,7 +74,6 @@ const _withMetroSupervisingTransformWorker = require("./withMetroSupervisingTran
|
|
|
74
74
|
const _log = require("../../../log");
|
|
75
75
|
const _FileNotifier = require("../../../utils/FileNotifier");
|
|
76
76
|
const _env = require("../../../utils/env");
|
|
77
|
-
const _errors = require("../../../utils/errors");
|
|
78
77
|
const _exit = require("../../../utils/exit");
|
|
79
78
|
const _interactive = require("../../../utils/interactive");
|
|
80
79
|
const _loadTsConfigPaths = require("../../../utils/tsconfig/loadTsConfigPaths");
|
|
@@ -220,6 +219,8 @@ function withExtendedResolver(config, { tsconfig, autolinkingModuleResolverInput
|
|
|
220
219
|
}
|
|
221
220
|
return _universalAliases;
|
|
222
221
|
}
|
|
222
|
+
// used to resolve externals in `requestCustomExternals` from the project root
|
|
223
|
+
const projectRootOriginPath = _path().default.join(config.projectRoot, 'package.json');
|
|
223
224
|
const preferredMainFields = {
|
|
224
225
|
// Defaults from Expo Webpack. Most packages using `react-native` don't support web
|
|
225
226
|
// in the `react-native` field, so we should prefer the `browser` field.
|
|
@@ -410,7 +411,6 @@ function withExtendedResolver(config, { tsconfig, autolinkingModuleResolverInput
|
|
|
410
411
|
},
|
|
411
412
|
// Custom externals support
|
|
412
413
|
function requestCustomExternals(context, moduleName, platform) {
|
|
413
|
-
var _context_customResolverOptions;
|
|
414
414
|
// We don't support this in the resolver at the moment.
|
|
415
415
|
if (moduleName.endsWith('/package.json')) {
|
|
416
416
|
return null;
|
|
@@ -419,8 +419,6 @@ function withExtendedResolver(config, { tsconfig, autolinkingModuleResolverInput
|
|
|
419
419
|
if (/\.(s?css|sass)$/.test(context.originModulePath)) {
|
|
420
420
|
return null;
|
|
421
421
|
}
|
|
422
|
-
const environment = (_context_customResolverOptions = context.customResolverOptions) == null ? void 0 : _context_customResolverOptions.environment;
|
|
423
|
-
const strictResolve = getStrictResolver(context, platform);
|
|
424
422
|
for (const external of externals){
|
|
425
423
|
if (external.match(context, moduleName, platform)) {
|
|
426
424
|
if (external.replace === 'empty') {
|
|
@@ -429,12 +427,13 @@ function withExtendedResolver(config, { tsconfig, autolinkingModuleResolverInput
|
|
|
429
427
|
type: external.replace
|
|
430
428
|
};
|
|
431
429
|
} else if (external.replace === 'weak') {
|
|
430
|
+
var _context_customResolverOptions;
|
|
432
431
|
// TODO: Make this use require.resolveWeak again. Previously this was just resolving to the same path.
|
|
433
|
-
const realModule =
|
|
432
|
+
const realModule = getStrictResolver(context, platform)(moduleName);
|
|
434
433
|
const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;
|
|
435
434
|
const opaqueId = idFactory(realPath, {
|
|
436
435
|
platform: platform,
|
|
437
|
-
environment
|
|
436
|
+
environment: (_context_customResolverOptions = context.customResolverOptions) == null ? void 0 : _context_customResolverOptions.environment
|
|
438
437
|
});
|
|
439
438
|
const contents = typeof opaqueId === 'number' ? `module.exports=/*${moduleName}*/__r(${opaqueId})` : `module.exports=/*${moduleName}*/__r(${JSON.stringify(opaqueId)})`;
|
|
440
439
|
// const contents = `module.exports=/*${moduleName}*/__r(require.resolveWeak('${moduleName}'))`;
|
|
@@ -447,6 +446,20 @@ function withExtendedResolver(config, { tsconfig, autolinkingModuleResolverInput
|
|
|
447
446
|
filePath: virtualModuleId
|
|
448
447
|
};
|
|
449
448
|
} else if (external.replace === 'node') {
|
|
449
|
+
// TODO(@kitten): Temporary workaround. Our externals logic here isn't generic and only works
|
|
450
|
+
// for development and not exports. We never intend to use it in exported production bundles,
|
|
451
|
+
// however, this is still a dangerous implementation. To protect us from externalizing modules
|
|
452
|
+
// that aren't available to the app, we force any resolution to happen via the project root
|
|
453
|
+
const projectRootContext = {
|
|
454
|
+
...context,
|
|
455
|
+
nodeModulesPaths: [],
|
|
456
|
+
originModulePath: projectRootOriginPath,
|
|
457
|
+
disableHierarchicalLookup: false
|
|
458
|
+
};
|
|
459
|
+
const externModule = getStrictResolver(projectRootContext, platform)(moduleName);
|
|
460
|
+
if (externModule.type !== 'sourceFile') {
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
450
463
|
const contents = `module.exports=$$require_external('${moduleName}')`;
|
|
451
464
|
const virtualModuleId = `\0node:${moduleName}`;
|
|
452
465
|
debug('Virtualizing Node.js (custom):', moduleName, '->', virtualModuleId);
|
|
@@ -456,7 +469,7 @@ function withExtendedResolver(config, { tsconfig, autolinkingModuleResolverInput
|
|
|
456
469
|
filePath: virtualModuleId
|
|
457
470
|
};
|
|
458
471
|
} else {
|
|
459
|
-
|
|
472
|
+
external.replace;
|
|
460
473
|
}
|
|
461
474
|
}
|
|
462
475
|
}
|
|
@@ -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 type { ExpoConfig, Platform } from '@expo/config';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport type {\n Resolution,\n ResolutionContext,\n CustomResolutionContext,\n} from '@expo/metro/metro-resolver';\nimport { resolve as metroResolver } from '@expo/metro/metro-resolver';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n createAutolinkingModuleResolverInput,\n createAutolinkingModuleResolver,\n AutolinkingModuleResolverInput,\n} from './createExpoAutolinkingResolver';\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 { withMetroErrorReportingResolver } from './withMetroErrorReportingResolver';\nimport { withMetroMutatedResolverContext, withMetroResolvers } from './withMetroResolvers';\nimport { withMetroSupervisingTransformWorker } from './withMetroSupervisingTransformWorker';\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 require !== \"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 const virtualModulesPolyfills = [virtualModuleId, virtualEnvVarId];\n\n if (ctx.platform === 'web') {\n try {\n const rnGetPolyfills: () => string[] = require('react-native/rn-get-polyfills');\n return [\n ...virtualModulesPolyfills,\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 // NOTE(@kitten): This is technically the public API to get polyfills rather than resolving directly into\n // `@react-native/js-polyfills`. We should really just start vendoring these, but for now, this exclusion works\n ...rnGetPolyfills().filter((x: string) => !x.includes('/console')),\n ];\n } catch (error: any) {\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n // If react-native is not installed, because we're targeting web, we still continue\n // This should be rare, but we add it so we don't unnecessarily have a fixed peer dependency on react-native\n debug(\n 'Skipping react-native/rn-get-polyfills from getPolyfills. react-native is not installed.'\n );\n return virtualModulesPolyfills;\n } else {\n throw error;\n }\n }\n }\n\n // Generally uses `@expo/metro-config`'s `getPolyfills` function, unless overridden\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n ...virtualModulesPolyfills,\n // Removed on server platforms during the transform.\n require.resolve('expo/virtual/streams.js'),\n ];\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 autolinkingModuleResolverInput,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n autolinkingModuleResolverInput?: AutolinkingModuleResolverInput;\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;\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 // The vendored canary modules live inside /static/canary-full/node_modules\n // Adding the `index.js` allows us to add this path as `originModulePath` to\n // resolve the nested `node_modules` folder properly.\n const canaryModulesPath = path.join(\n require.resolve('@expo/cli/package.json'),\n '../static/canary-full/index.js'\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 createAutolinkingModuleResolver(autolinkingModuleResolverInput, {\n getStrictResolver,\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 (\n [\n 'react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore',\n 'react-native/Libraries/Utilities/codegenNativeCommands',\n 'react-native/Libraries/Utilities/codegenNativeComponent',\n ].some((matcher) =>\n // Support absolute and modules with .js extensions.\n moduleName.includes(matcher)\n )\n ) {\n throw new FailedToResolvePathError(\n `Importing native-only module \"${moduleName}\" on web from: ${path.relative(config.projectRoot, 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 projectRoot: config.projectRoot,\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 // Modifying the origin module path changes the starting Node module resolution path to this folder\n context.originModulePath = canaryModulesPath;\n // Hierarchical lookup has to be enabled for this to work\n context.disableHierarchicalLookup = false;\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(\n withMetroSupervisingTransformWorker(metroConfigWithCustomContext)\n );\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 isAutolinkingResolverEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isAutolinkingResolverEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled: boolean;\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n // NOTE(@kitten): This is now always active and EXPO_USE_METRO_REQUIRE / isNamedRequiresEnabled is disregarded\n const metroDefaults: Mutable<\n typeof import('@expo/metro/metro-config/defaults/defaults')\n > = require('@expo/metro/metro-config/defaults/defaults');\n metroDefaults.moduleSystem = require.resolve('@expo/cli/build/metro-require/require');\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 // TODO(@kitten): Remove ts-export-errors here and replace with cast for type safety\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 // For virtual modules\n path.join(require.resolve('expo/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 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 let autolinkingModuleResolverInput: AutolinkingModuleResolverInput | undefined;\n if (isAutolinkingResolverEnabled) {\n autolinkingModuleResolverInput = await createAutolinkingModuleResolverInput({\n platforms: expoConfigPlatforms,\n projectRoot,\n });\n }\n\n return withExtendedResolver(config, {\n autolinkingModuleResolverInput,\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","virtualModulesPolyfills","rnGetPolyfills","filter","x","includes","error","code","polyfills","resolve","normalizeSlashes","p","replace","srcExts","mjsExts","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","autolinkingModuleResolverInput","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","isReactCanaryEnabled","isReactServerComponentsEnabled","Log","warn","log","chalk","dim","defaultResolver","metroResolver","resolver","createFastResolver","preserveSymlinks","blockList","Array","isArray","aliases","web","canaryModulesPath","path","join","_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","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","createAutolinkingModuleResolver","requestPostRewrites","some","FailedToResolvePathError","relative","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","normal","canaryFile","shouldCreateVirtualCanary","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","disableHierarchicalLookup","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","withMetroSupervisingTransformWorker","input","output","exp","platformBundlers","isAutolinkingResolverEnabled","metroDefaults","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","expoConfigPlatforms","entries","platforms","map","Set","concat","createAutolinkingModuleResolverInput","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;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7J,QAAQ,CAACL;OAEzE8K,GAAG,CAAC,CAAC,CAAC9K,SAAS,GAAKA;IAEvB,IAAIyC,MAAMC,OAAO,CAACrD,OAAOgD,QAAQ,CAACwI,SAAS,GAAG;QAC5CF,sBAAsB;eAAI,IAAII,IAAIJ,oBAAoBK,MAAM,CAAC3L,OAAOgD,QAAQ,CAACwI,SAAS;SAAG;IAC3F;IAEA,yCAAyC;IACzCxL,OAAOgD,QAAQ,CAACwI,SAAS,GAAGF;IAE5BtL,SAASD,iBAAiBC,QAAQ;QAAEC;IAAgB;IAEpD,IAAIkC;IACJ,IAAI4I,8BAA8B;QAChC5I,iCAAiC,MAAMyJ,IAAAA,mEAAoC,EAAC;YAC1EJ,WAAWF;YACXvH;QACF;IACF;IAEA,OAAOrE,qBAAqBM,QAAQ;QAClCmC;QACAD;QACAI;QACAF;QACAC;QACAE;QACAC;QACAvC;IACF;AACF;AAEA,SAASkL,cAAcU,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 type { ExpoConfig, Platform } from '@expo/config';\nimport type Bundler from '@expo/metro/metro/Bundler';\nimport type { ConfigT } from '@expo/metro/metro-config';\nimport type {\n Resolution,\n ResolutionContext,\n CustomResolutionContext,\n} from '@expo/metro/metro-resolver';\nimport { resolve as metroResolver } from '@expo/metro/metro-resolver';\nimport chalk from 'chalk';\nimport fs from 'fs';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport {\n createAutolinkingModuleResolverInput,\n createAutolinkingModuleResolver,\n AutolinkingModuleResolverInput,\n} from './createExpoAutolinkingResolver';\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 { withMetroErrorReportingResolver } from './withMetroErrorReportingResolver';\nimport { withMetroMutatedResolverContext, withMetroResolvers } from './withMetroResolvers';\nimport { withMetroSupervisingTransformWorker } from './withMetroSupervisingTransformWorker';\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 require !== \"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 const virtualModulesPolyfills = [virtualModuleId, virtualEnvVarId];\n\n if (ctx.platform === 'web') {\n try {\n const rnGetPolyfills: () => string[] = require('react-native/rn-get-polyfills');\n return [\n ...virtualModulesPolyfills,\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 // NOTE(@kitten): This is technically the public API to get polyfills rather than resolving directly into\n // `@react-native/js-polyfills`. We should really just start vendoring these, but for now, this exclusion works\n ...rnGetPolyfills().filter((x: string) => !x.includes('/console')),\n ];\n } catch (error: any) {\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n // If react-native is not installed, because we're targeting web, we still continue\n // This should be rare, but we add it so we don't unnecessarily have a fixed peer dependency on react-native\n debug(\n 'Skipping react-native/rn-get-polyfills from getPolyfills. react-native is not installed.'\n );\n return virtualModulesPolyfills;\n } else {\n throw error;\n }\n }\n }\n\n // Generally uses `@expo/metro-config`'s `getPolyfills` function, unless overridden\n const polyfills = originalGetPolyfills(ctx);\n return [\n ...polyfills,\n ...virtualModulesPolyfills,\n // Removed on server platforms during the transform.\n require.resolve('expo/virtual/streams.js'),\n ];\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 autolinkingModuleResolverInput,\n isTsconfigPathsEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n tsconfig: TsConfigPaths | null;\n autolinkingModuleResolverInput?: AutolinkingModuleResolverInput;\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;\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 // The vendored canary modules live inside /static/canary-full/node_modules\n // Adding the `index.js` allows us to add this path as `originModulePath` to\n // resolve the nested `node_modules` folder properly.\n const canaryModulesPath = path.join(\n require.resolve('@expo/cli/package.json'),\n '../static/canary-full/index.js'\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 // used to resolve externals in `requestCustomExternals` from the project root\n const projectRootOriginPath = path.join(config.projectRoot, 'package.json');\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 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 = getStrictResolver(context, platform)(moduleName);\n const realPath = realModule.type === 'sourceFile' ? realModule.filePath : moduleName;\n const opaqueId = idFactory(realPath, {\n platform: platform!,\n environment: context.customResolverOptions?.environment,\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 // TODO(@kitten): Temporary workaround. Our externals logic here isn't generic and only works\n // for development and not exports. We never intend to use it in exported production bundles,\n // however, this is still a dangerous implementation. To protect us from externalizing modules\n // that aren't available to the app, we force any resolution to happen via the project root\n const projectRootContext: ResolutionContext = {\n ...context,\n nodeModulesPaths: [],\n originModulePath: projectRootOriginPath,\n disableHierarchicalLookup: false,\n };\n const externModule = getStrictResolver(projectRootContext, platform)(moduleName);\n if (externModule.type !== 'sourceFile') {\n return null;\n }\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 external.replace satisfies never;\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 createAutolinkingModuleResolver(autolinkingModuleResolverInput, {\n getStrictResolver,\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 (\n [\n 'react-native/Libraries/ReactPrivate/ReactNativePrivateInitializeCore',\n 'react-native/Libraries/Utilities/codegenNativeCommands',\n 'react-native/Libraries/Utilities/codegenNativeComponent',\n ].some((matcher) =>\n // Support absolute and modules with .js extensions.\n moduleName.includes(matcher)\n )\n ) {\n throw new FailedToResolvePathError(\n `Importing native-only module \"${moduleName}\" on web from: ${path.relative(config.projectRoot, 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 projectRoot: config.projectRoot,\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 // Modifying the origin module path changes the starting Node module resolution path to this folder\n context.originModulePath = canaryModulesPath;\n // Hierarchical lookup has to be enabled for this to work\n context.disableHierarchicalLookup = false;\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(\n withMetroSupervisingTransformWorker(metroConfigWithCustomContext)\n );\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 isAutolinkingResolverEnabled,\n isFastResolverEnabled,\n isExporting,\n isReactCanaryEnabled,\n isReactServerComponentsEnabled,\n getMetroBundler,\n }: {\n config: ConfigT;\n exp: ExpoConfig;\n isTsconfigPathsEnabled: boolean;\n platformBundlers: PlatformBundlers;\n isAutolinkingResolverEnabled?: boolean;\n isFastResolverEnabled?: boolean;\n isExporting?: boolean;\n isReactCanaryEnabled: boolean;\n isReactServerComponentsEnabled: boolean;\n isNamedRequiresEnabled: boolean;\n getMetroBundler: () => Bundler;\n }\n) {\n // Change the default metro-runtime to a custom one that supports bundle splitting.\n // NOTE(@kitten): This is now always active and EXPO_USE_METRO_REQUIRE / isNamedRequiresEnabled is disregarded\n const metroDefaults: Mutable<\n typeof import('@expo/metro/metro-config/defaults/defaults')\n > = require('@expo/metro/metro-config/defaults/defaults');\n metroDefaults.moduleSystem = require.resolve('@expo/cli/build/metro-require/require');\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 // TODO(@kitten): Remove ts-export-errors here and replace with cast for type safety\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 // For virtual modules\n path.join(require.resolve('expo/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 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 let autolinkingModuleResolverInput: AutolinkingModuleResolverInput | undefined;\n if (isAutolinkingResolverEnabled) {\n autolinkingModuleResolverInput = await createAutolinkingModuleResolverInput({\n platforms: expoConfigPlatforms,\n projectRoot,\n });\n }\n\n return withExtendedResolver(config, {\n autolinkingModuleResolverInput,\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","virtualModulesPolyfills","rnGetPolyfills","filter","x","includes","error","code","polyfills","resolve","normalizeSlashes","p","replace","srcExts","mjsExts","ext","test","nodejsSourceExtensions","jsIndex","reduce","index","i","splice","tsconfig","autolinkingModuleResolverInput","isTsconfigPathsEnabled","isFastResolverEnabled","isExporting","isReactCanaryEnabled","isReactServerComponentsEnabled","Log","warn","log","chalk","dim","defaultResolver","metroResolver","resolver","createFastResolver","preserveSymlinks","blockList","Array","isArray","aliases","web","canaryModulesPath","path","join","_universalAliases","getUniversalAliases","resolveFrom","silent","projectRoot","push","projectRootOriginPath","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","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","external","realModule","realPath","opaqueId","JSON","stringify","projectRootContext","nodeModulesPaths","disableHierarchicalLookup","externModule","requestAlias","redirectedModuleName","matcher","alias","aliasedModule","_","parseInt","requestStableAssetRegistry","createAutolinkingModuleResolver","requestPostRewrites","some","FailedToResolvePathError","relative","normalName","shimFile","shouldCreateVirtualShim","virtualId","bundler","hasVirtualModule","fs","readFileSync","normal","canaryFile","shouldCreateVirtualCanary","createFallbackModuleResolver","originModuleNames","metroConfigWithCustomContext","withMetroMutatedResolverContext","immutableContext","preferNativePlatform","sourceExts","unstable_enablePackageExports","unstable_conditionsByPlatform","isReactServerComponents","mainFields","unstable_conditionNames","env","EXPO_METRO_NO_MAIN_FIELD_OVERRIDE","withMetroErrorReportingResolver","withMetroSupervisingTransformWorker","input","output","exp","platformBundlers","isAutolinkingResolverEnabled","metroDefaults","moduleSystem","EXPO_PUBLIC_PROJECT_ROOT","isDirectoryIn","__dirname","watchFolders","expoConfigPlatforms","entries","platforms","map","Set","concat","createAutolinkingModuleResolverInput","targetPath","rootPath","startsWith"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IA0IeA,mBAAmB;eAAnBA;;IAurBAC,iBAAiB;eAAjBA;;IAjqBAC,oBAAoB;eAApBA;;IAirBMC,2BAA2B;eAA3BA;;;;yBAx0BmB;;;;;;;gEACvB;;;;;;;gEACH;;;;;;;gEACE;;;;;;;gEACO;;;;;;+CAMjB;4CACsC;yCACgB;2BACsB;6BACZ;qCACrB;iDACF;oCACoB;qDAChB;qBAChC;8BACS;qBACT;sBAEa;6BACH;mCACwB;0CACb;8BACL;;;;;;AAWpC,MAAMC,qBAAqB,CAAC,6FAA6F,CAAC;AAE1H,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,SAASC,iBACPC,MAAe,EACf,EACEC,eAAe,EAGhB;IAED,MAAMC,uBAAuBF,OAAOG,UAAU,CAACC,YAAY,GACvDJ,OAAOG,UAAU,CAACC,YAAY,CAACC,IAAI,CAACL,OAAOG,UAAU,IACrD,IAAM,EAAE;IAEZ,MAAMC,eAAe,CAACE;QACpB,MAAMC,kBAAkB,CAAC,gCAAgC,CAAC;QAE1DC,IAAAA,sDAAiC,EAACP,mBAAmBQ,gBAAgB,CACnEF,iBACA,AAAC,CAAA;YACC,OAAO,CAAC,EAAE,CAAC;QACb,CAAA;QAGF,MAAMG,kBAAkB,CAAC,2BAA2B,CAAC;QAErDF,IAAAA,sDAAiC,EAACP,mBAAmBQ,gBAA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aD,WAAW9G,MAAM,IAAI+G,SAAS/G,MAAM;AAChF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/createBuiltinAPIRequestHandler.ts"],"sourcesContent":["import { convertRequest, RequestHandler, respond } from '
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/createBuiltinAPIRequestHandler.ts"],"sourcesContent":["import { convertRequest, RequestHandler, respond } from 'expo-server/adapter/http';\n\nimport type { ServerNext, ServerRequest, ServerResponse } from './server.types';\n\nexport function createBuiltinAPIRequestHandler(\n matchRequest: (request: Request) => boolean,\n handlers: Record<string, (req: Request) => Promise<Response>>\n): RequestHandler {\n return createRequestHandler((req) => {\n if (!matchRequest(req)) {\n winterNext();\n }\n const handler = handlers[req.method];\n if (!handler) {\n notAllowed();\n }\n return handler(req);\n });\n}\n\n/**\n * Returns a request handler for http that serves the response using Remix.\n */\nexport function createRequestHandler(\n handleRequest: (request: Request) => Promise<Response>\n): RequestHandler {\n return async (req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n if (!req?.url || !req.method) {\n return next();\n }\n // These headers (added by other middleware) break the browser preview of RSC.\n res.removeHeader('X-Content-Type-Options');\n res.removeHeader('Cache-Control');\n res.removeHeader('Expires');\n res.removeHeader('Surrogate-Control');\n\n try {\n const request = convertRequest(req, res);\n const response = await handleRequest(request);\n return await respond(res, response);\n } catch (error: unknown) {\n if (error instanceof Error) {\n return await respond(\n res,\n new Response('Internal Server Error: ' + error.message, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n })\n );\n } else if (error instanceof Response) {\n return await respond(res, error);\n }\n // http doesn't support async functions, so we have to pass along the\n // error manually using next().\n // @ts-expect-error\n next(error);\n }\n };\n}\n\nfunction notAllowed(): never {\n throw new Response('Method Not Allowed', {\n status: 405,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n}\n\nexport function winterNext(): never {\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n"],"names":["createBuiltinAPIRequestHandler","createRequestHandler","winterNext","matchRequest","handlers","req","handler","method","notAllowed","handleRequest","res","next","url","removeHeader","request","convertRequest","response","respond","error","Error","Response","message","status","headers","undefined"],"mappings":";;;;;;;;;;;IAIgBA,8BAA8B;eAA9BA;;IAmBAC,oBAAoB;eAApBA;;IAgDAC,UAAU;eAAVA;;;;yBAvEwC;;;;;;AAIjD,SAASF,+BACdG,YAA2C,EAC3CC,QAA6D;IAE7D,OAAOH,qBAAqB,CAACI;QAC3B,IAAI,CAACF,aAAaE,MAAM;YACtBH;QACF;QACA,MAAMI,UAAUF,QAAQ,CAACC,IAAIE,MAAM,CAAC;QACpC,IAAI,CAACD,SAAS;YACZE;QACF;QACA,OAAOF,QAAQD;IACjB;AACF;AAKO,SAASJ,qBACdQ,aAAsD;IAEtD,OAAO,OAAOJ,KAAoBK,KAAqBC;QACrD,IAAI,EAACN,uBAAAA,IAAKO,GAAG,KAAI,CAACP,IAAIE,MAAM,EAAE;YAC5B,OAAOI;QACT;QACA,8EAA8E;QAC9ED,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QAEjB,IAAI;YACF,MAAMC,UAAUC,IAAAA,sBAAc,EAACV,KAAKK;YACpC,MAAMM,WAAW,MAAMP,cAAcK;YACrC,OAAO,MAAMG,IAAAA,eAAO,EAACP,KAAKM;QAC5B,EAAE,OAAOE,OAAgB;YACvB,IAAIA,iBAAiBC,OAAO;gBAC1B,OAAO,MAAMF,IAAAA,eAAO,EAClBP,KACA,IAAIU,SAAS,4BAA4BF,MAAMG,OAAO,EAAE;oBACtDC,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ,OAAO,IAAIL,iBAAiBE,UAAU;gBACpC,OAAO,MAAMH,IAAAA,eAAO,EAACP,KAAKQ;YAC5B;YACA,qEAAqE;YACrE,+BAA+B;YAC/B,mBAAmB;YACnBP,KAAKO;QACP;IACF;AACF;AAEA,SAASV;IACP,MAAM,IAAIY,SAAS,sBAAsB;QACvCE,QAAQ;QACRC,SAAS;YACP,gBAAgB;QAClB;IACF;AACF;AAEO,SAASrB;IACd,4CAA4C;IAC5C,MAAMsB;AACR"}
|
|
@@ -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/${"54.0.
|
|
36
|
+
'user-agent': `expo-cli/${"54.0.11"}`,
|
|
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": "54.0.
|
|
3
|
+
"version": "54.0.11",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@0no-co/graphql.web": "^1.0.8",
|
|
45
45
|
"@expo/code-signing-certificates": "^0.0.5",
|
|
46
|
-
"@expo/config": "~12.0.
|
|
46
|
+
"@expo/config": "~12.0.10",
|
|
47
47
|
"@expo/config-plugins": "~54.0.2",
|
|
48
48
|
"@expo/devcert": "^1.1.2",
|
|
49
49
|
"@expo/env": "~2.0.7",
|
|
@@ -51,13 +51,12 @@
|
|
|
51
51
|
"@expo/json-file": "^10.0.7",
|
|
52
52
|
"@expo/mcp-tunnel": "~0.0.7",
|
|
53
53
|
"@expo/metro": "~54.0.0",
|
|
54
|
-
"@expo/metro-config": "~54.0.
|
|
54
|
+
"@expo/metro-config": "~54.0.6",
|
|
55
55
|
"@expo/osascript": "^2.3.7",
|
|
56
56
|
"@expo/package-manager": "^1.9.8",
|
|
57
57
|
"@expo/plist": "^0.4.7",
|
|
58
|
-
"@expo/prebuild-config": "^54.0.
|
|
58
|
+
"@expo/prebuild-config": "^54.0.5",
|
|
59
59
|
"@expo/schema-utils": "^0.1.7",
|
|
60
|
-
"@expo/server": "^0.7.5",
|
|
61
60
|
"@expo/spawn-async": "^1.7.2",
|
|
62
61
|
"@expo/ws-tunnel": "^1.0.1",
|
|
63
62
|
"@expo/xcpretty": "^4.3.0",
|
|
@@ -75,6 +74,7 @@
|
|
|
75
74
|
"connect": "^3.7.0",
|
|
76
75
|
"debug": "^4.3.4",
|
|
77
76
|
"env-editor": "^0.4.1",
|
|
77
|
+
"expo-server": "^1.0.1",
|
|
78
78
|
"freeport-async": "^2.0.0",
|
|
79
79
|
"getenv": "^2.0.0",
|
|
80
80
|
"glob": "^10.4.2",
|
|
@@ -169,5 +169,5 @@
|
|
|
169
169
|
"tree-kill": "^1.2.2",
|
|
170
170
|
"tsd": "^0.28.1"
|
|
171
171
|
},
|
|
172
|
-
"gitHead": "
|
|
172
|
+
"gitHead": "a2c8477a3fc5744980494805ae46f20dda94c852"
|
|
173
173
|
}
|