@expo/cli 1.0.0-canary-20250722-599a28f → 54.0.0
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/metro-require/require.js +24 -13
- package/build/src/api/getExpoSchema.js +8 -7
- package/build/src/api/getExpoSchema.js.map +1 -1
- package/build/src/expoUpdatesExports.js +28 -0
- package/build/src/expoUpdatesExports.js.map +1 -0
- package/build/src/export/embed/exportEmbedAsync.js +26 -25
- package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
- package/build/src/export/embed/resolveOptions.js +1 -1
- package/build/src/export/embed/resolveOptions.js.map +1 -1
- package/build/src/export/exportApp.js +7 -4
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/export/exportAssets.js +20 -4
- package/build/src/export/exportAssets.js.map +1 -1
- package/build/src/export/exportAsync.js +2 -2
- package/build/src/export/exportAsync.js.map +1 -1
- package/build/src/export/exportHermes.js +34 -9
- package/build/src/export/exportHermes.js.map +1 -1
- package/build/src/export/exportStaticAsync.js +23 -2
- package/build/src/export/exportStaticAsync.js.map +1 -1
- package/build/src/export/index.js +1 -0
- package/build/src/export/index.js.map +1 -1
- package/build/src/export/metroAssetLocalPath.js.map +1 -1
- package/build/src/export/persistMetroAssets.js.map +1 -1
- package/build/src/export/resolveOptions.js +1 -0
- package/build/src/export/resolveOptions.js.map +1 -1
- package/build/src/export/saveAssets.js +12 -0
- package/build/src/export/saveAssets.js.map +1 -1
- package/build/src/install/checkPackages.js +9 -1
- package/build/src/install/checkPackages.js.map +1 -1
- package/build/src/lint/lintAsync.js +2 -0
- package/build/src/lint/lintAsync.js.map +1 -1
- package/build/src/prebuild/prebuildAsync.js +18 -0
- package/build/src/prebuild/prebuildAsync.js.map +1 -1
- package/build/src/prebuild/resolveLocalTemplate.js +42 -0
- package/build/src/prebuild/resolveLocalTemplate.js.map +1 -0
- package/build/src/prebuild/resolveTemplate.js +17 -7
- package/build/src/prebuild/resolveTemplate.js.map +1 -1
- package/build/src/prebuild/updateFromTemplate.js +1 -0
- package/build/src/prebuild/updateFromTemplate.js.map +1 -1
- package/build/src/prebuild/updatePackageJson.js +5 -3
- package/build/src/prebuild/updatePackageJson.js.map +1 -1
- package/build/src/run/android/resolveOptions.js +2 -2
- package/build/src/run/android/resolveOptions.js.map +1 -1
- package/build/src/run/ios/options/resolveOptions.js +2 -2
- package/build/src/run/ios/options/resolveOptions.js.map +1 -1
- package/build/src/run/ios/runIosAsync.js +3 -0
- package/build/src/run/ios/runIosAsync.js.map +1 -1
- package/build/src/serve/serveAsync.js +5 -2
- package/build/src/serve/serveAsync.js.map +1 -1
- package/build/src/start/platforms/ExpoGoInstaller.js +1 -1
- package/build/src/start/platforms/ExpoGoInstaller.js.map +1 -1
- package/build/src/start/server/DevToolsPluginManager.js +7 -35
- package/build/src/start/server/DevToolsPluginManager.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +88 -56
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +66 -25
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/TerminalReporter.js +6 -6
- package/build/src/start/server/metro/TerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/createExpoAutolinkingResolver.js +121 -0
- package/build/src/start/server/metro/createExpoAutolinkingResolver.js.map +1 -0
- package/build/src/start/server/metro/createExpoFallbackResolver.js +1 -0
- package/build/src/start/server/metro/createExpoFallbackResolver.js.map +1 -1
- package/build/src/start/server/metro/createExpoMetroResolver.js.map +1 -1
- package/build/src/start/server/metro/createJResolver.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +4 -4
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js +54 -8
- package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
- package/build/src/start/server/metro/debugging/attachAtlas.js +2 -0
- package/build/src/start/server/metro/debugging/attachAtlas.js.map +1 -1
- package/build/src/start/server/metro/dev-server/createMetroMiddleware.js +1 -1
- package/build/src/start/server/metro/dev-server/createMetroMiddleware.js.map +1 -1
- package/build/src/start/server/metro/fetchRouterManifest.js +1 -0
- package/build/src/start/server/metro/fetchRouterManifest.js.map +1 -1
- package/build/src/start/server/metro/formatFileCandidates.js.map +1 -1
- package/build/src/start/server/metro/getCssModulesFromBundler.js +10 -9
- package/build/src/start/server/metro/getCssModulesFromBundler.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +44 -40
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/metroErrorInterface.js +79 -12
- package/build/src/start/server/metro/metroErrorInterface.js.map +1 -1
- package/build/src/start/server/metro/metroVirtualModules.js.map +1 -1
- package/build/src/start/server/metro/metroWatchTypeScriptFiles.js.map +1 -1
- package/build/src/start/server/metro/router.js +75 -0
- package/build/src/start/server/metro/router.js.map +1 -1
- package/build/src/start/server/metro/runServer-fork.js +19 -19
- package/build/src/start/server/metro/runServer-fork.js.map +1 -1
- package/build/src/start/server/metro/serializeHtml.js +45 -5
- package/build/src/start/server/metro/serializeHtml.js.map +1 -1
- package/build/src/start/server/metro/waitForMetroToObserveTypeScriptFile.js.map +1 -1
- package/build/src/start/server/metro/withMetroErrorReportingResolver.js +267 -0
- package/build/src/start/server/metro/withMetroErrorReportingResolver.js.map +1 -0
- package/build/src/start/server/metro/withMetroMultiPlatform.js +58 -82
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/metro/withMetroResolvers.js +2 -219
- package/build/src/start/server/metro/withMetroResolvers.js.map +1 -1
- package/build/src/start/server/metro/withMetroSupervisingTransformWorker.js +63 -0
- package/build/src/start/server/metro/withMetroSupervisingTransformWorker.js.map +1 -0
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js +1 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js.map +1 -1
- package/build/src/start/server/middleware/metroOptions.js +7 -2
- package/build/src/start/server/middleware/metroOptions.js.map +1 -1
- package/build/src/start/server/middleware/resolvePlatform.js +3 -0
- package/build/src/start/server/middleware/resolvePlatform.js.map +1 -1
- package/build/src/start/server/serverLogLikeMetro.js +13 -11
- package/build/src/start/server/serverLogLikeMetro.js.map +1 -1
- package/build/src/start/server/type-generation/routes.js.map +1 -1
- package/build/src/start/server/type-generation/startTypescriptTypeGeneration.js.map +1 -1
- package/build/src/types.d.ts +2 -0
- package/build/src/utils/build-cache-providers/index.js.map +1 -1
- package/build/src/utils/dir.js +7 -0
- package/build/src/utils/dir.js.map +1 -1
- package/build/src/utils/env.js +9 -4
- package/build/src/utils/env.js.map +1 -1
- package/build/src/utils/errors.js +1 -1
- package/build/src/utils/errors.js.map +1 -1
- package/build/src/utils/git.js +2 -2
- package/build/src/utils/git.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/build/src/utils/tsconfig/resolveWithTsConfigPaths.js.map +1 -1
- package/internal/unstable-expo-updates-exports.d.ts +31 -0
- package/internal/unstable-expo-updates-exports.js +3 -0
- package/package.json +33 -17
- package/static/template/[...rsc]+api.ts +1 -1
- package/build/src/start/server/metro/createExpoStickyResolver.js +0 -137
- package/build/src/start/server/metro/createExpoStickyResolver.js.map +0 -1
- package/build/src/start/server/metro/metroPrivateServer.js +0 -28
- package/build/src/start/server/metro/metroPrivateServer.js.map +0 -1
- package/build/src/utils/jsonSchemaDeref.js +0 -150
- package/build/src/utils/jsonSchemaDeref.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createExpoMetroResolver.ts"],"sourcesContent":["/**\n * Copyright © 2023 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 fs from 'fs';\nimport { Resolution, ResolutionContext } from 'metro-resolver';\nimport path from 'path';\n\nimport jestResolver from './createJResolver';\nimport { isNodeExternal } from './externals';\nimport { formatFileCandidates } from './formatFileCandidates';\nimport { isServerEnvironment } from '../middleware/metroOptions';\n\nexport class FailedToResolvePathError extends Error {\n // Added to ensure the error is matched by our tooling.\n // TODO: Test that this matches `isFailedToResolvePathError`\n candidates = {};\n}\n\nclass ShimModuleError extends Error {}\n\nconst debug = require('debug')('expo:metro:resolve') as typeof console.log;\n\nconst realpathFS =\n process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function'\n ? fs.realpathSync.native\n : fs.realpathSync;\n\nfunction realpathSync(x: string) {\n try {\n return realpathFS(x);\n } catch (realpathErr: any) {\n if (realpathErr.code !== 'ENOENT') {\n throw realpathErr;\n }\n }\n return x;\n}\n\nexport function createFastResolver({\n preserveSymlinks,\n blockList,\n}: {\n preserveSymlinks: boolean;\n blockList: RegExp[];\n}) {\n debug('Creating with settings:', { preserveSymlinks, blockList });\n const cachedExtensions: Map<string, readonly string[]> = new Map();\n\n function getAdjustedExtensions({\n metroSourceExtensions,\n platform,\n isNative,\n }: {\n metroSourceExtensions: readonly string[];\n platform: string | null;\n isNative: boolean;\n }): readonly string[] {\n const key = JSON.stringify({ metroSourceExtensions, platform, isNative });\n if (cachedExtensions.has(key)) {\n return cachedExtensions.get(key)!;\n }\n\n let output = metroSourceExtensions;\n if (platform) {\n const nextOutput: string[] = [];\n\n output.forEach((ext) => {\n nextOutput.push(`${platform}.${ext}`);\n if (isNative) {\n nextOutput.push(`native.${ext}`);\n }\n nextOutput.push(ext);\n });\n\n output = nextOutput;\n }\n\n output = Array.from(new Set<string>(output));\n\n // resolve expects these to start with a dot.\n output = output.map((ext) => `.${ext}`);\n\n cachedExtensions.set(key, output);\n\n return output;\n }\n\n function fastResolve(\n context: Pick<\n ResolutionContext,\n | 'unstable_enablePackageExports'\n | 'customResolverOptions'\n | 'sourceExts'\n | 'preferNativePlatform'\n | 'originModulePath'\n | 'getPackage'\n | 'nodeModulesPaths'\n | 'mainFields'\n | 'resolveAsset'\n | 'unstable_conditionNames'\n | 'unstable_conditionsByPlatform'\n | 'fileSystemLookup'\n | 'isESMImport'\n >,\n moduleName: string,\n platform: string | null\n ): Resolution {\n const environment = context.customResolverOptions?.environment;\n const isServer = isServerEnvironment(environment);\n\n const extensions = getAdjustedExtensions({\n metroSourceExtensions: context.sourceExts,\n platform,\n isNative: context.preferNativePlatform,\n }) as string[];\n\n let fp: string;\n\n const conditions = context.unstable_enablePackageExports\n ? [\n ...new Set([\n 'default',\n context.isESMImport === true ? 'import' : 'require',\n ...context.unstable_conditionNames,\n ...(platform != null ? (context.unstable_conditionsByPlatform[platform] ?? []) : []),\n ]),\n ]\n : [];\n\n // NOTE(cedric): metro@0.81.0 ships with `fileSystemLookup`, while `metro@0.80.12` ships as unstable\n const fileSystemLookup = (\n 'unstable_fileSystemLookup' in context\n ? context.unstable_fileSystemLookup\n : context.fileSystemLookup\n ) as ResolutionContext['fileSystemLookup'] | undefined;\n\n if (!fileSystemLookup) {\n throw new Error('Metro API fileSystemLookup is required for fast resolver');\n }\n\n try {\n fp = jestResolver(moduleName, {\n blockList,\n enablePackageExports: context.unstable_enablePackageExports,\n basedir: path.dirname(context.originModulePath),\n paths: context.nodeModulesPaths.length ? (context.nodeModulesPaths as string[]) : undefined,\n extensions,\n conditions,\n realpathSync(file: string): string {\n let metroRealPath: string | null = null;\n\n const res = fileSystemLookup(file);\n if (res?.exists) {\n metroRealPath = res.realPath;\n }\n\n if (metroRealPath == null && preserveSymlinks) {\n return realpathSync(file);\n }\n return metroRealPath ?? file;\n },\n isDirectory(file: string): boolean {\n const res = fileSystemLookup(file);\n return res.exists && res.type === 'd';\n },\n isFile(file: string): boolean {\n const res = fileSystemLookup(file);\n return res.exists && res.type === 'f';\n },\n pathExists(file: string): boolean {\n return fileSystemLookup(file).exists;\n },\n packageFilter(pkg) {\n // set the pkg.main to the first available field in context.mainFields\n for (const field of context.mainFields) {\n if (\n pkg[field] &&\n // object-inspect uses browser: {} in package.json\n typeof pkg[field] === 'string'\n ) {\n return {\n ...pkg,\n main: pkg[field],\n };\n }\n }\n return pkg;\n },\n // Used to ensure files trace to packages instead of node_modules in expo/expo. This is how Metro works and\n // the app doesn't finish without it.\n preserveSymlinks,\n readPackageSync(readFileSync, pkgFile) {\n return context.getPackage(pkgFile) ?? JSON.parse(fs.readFileSync(pkgFile, 'utf8'));\n },\n includeCoreModules: isServer,\n\n pathFilter:\n // Disable `browser` field for server environments.\n isServer\n ? undefined\n : // Enable `browser` field support\n (pkg: any, _resolvedPath: string, relativePathIn: string): string => {\n let relativePath = relativePathIn;\n if (relativePath[0] !== '.') {\n relativePath = `./${relativePath}`;\n }\n\n const replacements = pkg.browser;\n if (replacements === undefined) {\n return '';\n }\n\n // TODO: Probably use a better extension matching system here.\n // This was added for `uuid/v4` -> `./lib/rng` -> `./lib/rng-browser.js`\n const mappedPath = replacements[relativePath] ?? replacements[relativePath + '.js'];\n if (mappedPath === false) {\n throw new ShimModuleError();\n }\n return mappedPath;\n },\n });\n } catch (error: any) {\n if (error instanceof ShimModuleError) {\n return {\n type: 'empty',\n };\n }\n\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n if (isNodeExternal(moduleName)) {\n // In this case, mock the file to use an empty module.\n return {\n type: 'empty',\n };\n }\n\n debug({ moduleName, platform, conditions, isServer, preserveSymlinks }, context);\n\n throw new FailedToResolvePathError(\n 'The module could not be resolved because no file or module matched the pattern:\\n' +\n ` ${formatFileCandidates(\n {\n type: 'sourceFile',\n filePathPrefix: moduleName,\n candidateExts: extensions,\n },\n true\n )}\\n\\nFrom:\\n ${context.originModulePath}\\n`\n );\n }\n throw error;\n }\n\n if (context.sourceExts.some((ext) => fp.endsWith(ext))) {\n return {\n type: 'sourceFile',\n filePath: fp,\n };\n }\n\n if (isNodeExternal(fp)) {\n if (isServer) {\n return {\n type: 'sourceFile',\n filePath: fp,\n };\n }\n // NOTE: This shouldn't happen, the module should throw.\n // Mock non-server built-in modules to empty.\n return {\n type: 'empty',\n };\n }\n\n // NOTE: platform extensions may not be supported on assets.\n\n if (platform === 'web') {\n // Skip multi-resolution on web/server bundles. Only consideration here is that\n // we may still need it in case the only image is a multi-resolution image.\n return {\n type: 'assetFiles',\n filePaths: [fp],\n };\n }\n\n const dirPath = path.dirname(fp);\n const extension = path.extname(fp);\n const basename = path.basename(fp, extension);\n return {\n type: 'assetFiles',\n // Support multi-resolution asset extensions...\n filePaths: context.resolveAsset(dirPath, basename, extension) ?? [fp],\n };\n }\n\n return fastResolve;\n}\n"],"names":["FailedToResolvePathError","createFastResolver","Error","candidates","ShimModuleError","debug","require","realpathFS","process","platform","fs","realpathSync","native","x","realpathErr","code","preserveSymlinks","blockList","cachedExtensions","Map","getAdjustedExtensions","metroSourceExtensions","isNative","key","JSON","stringify","has","get","output","nextOutput","forEach","ext","push","Array","from","Set","map","set","fastResolve","context","moduleName","environment","customResolverOptions","isServer","isServerEnvironment","extensions","sourceExts","preferNativePlatform","fp","conditions","unstable_enablePackageExports","isESMImport","unstable_conditionNames","unstable_conditionsByPlatform","fileSystemLookup","unstable_fileSystemLookup","jestResolver","enablePackageExports","basedir","path","dirname","originModulePath","paths","nodeModulesPaths","length","undefined","file","metroRealPath","res","exists","realPath","isDirectory","type","isFile","pathExists","packageFilter","pkg","field","mainFields","main","readPackageSync","readFileSync","pkgFile","getPackage","parse","includeCoreModules","pathFilter","_resolvedPath","relativePathIn","relativePath","replacements","browser","mappedPath","error","isNodeExternal","formatFileCandidates","filePathPrefix","candidateExts","some","endsWith","filePath","filePaths","dirPath","extension","extname","basename","resolveAsset"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAUYA,wBAAwB;eAAxBA;;IA0BGC,kBAAkB;eAAlBA;;;;gEAnCD;;;;;;;gEAEE;;;;;;wEAEQ;2BACM;sCACM;8BACD;;;;;;AAE7B,MAAMD,iCAAiCE;;QAAvC,gBACL,uDAAuD;QACvD,4DAA4D;aAC5DC,aAAa,CA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SAASG,UAAUF,cAAc;gBAACvD;aAAG;QACvE;IACF;IAEA,OAAOV;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createExpoMetroResolver.ts"],"sourcesContent":["/**\n * Copyright © 2023 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 { Resolution, ResolutionContext } from '@expo/metro/metro-resolver';\nimport fs from 'fs';\nimport path from 'path';\n\nimport jestResolver from './createJResolver';\nimport { isNodeExternal } from './externals';\nimport { formatFileCandidates } from './formatFileCandidates';\nimport { isServerEnvironment } from '../middleware/metroOptions';\n\nexport class FailedToResolvePathError extends Error {\n // Added to ensure the error is matched by our tooling.\n // TODO: Test that this matches `isFailedToResolvePathError`\n candidates = {};\n}\n\nclass ShimModuleError extends Error {}\n\nconst debug = require('debug')('expo:metro:resolve') as typeof console.log;\n\nconst realpathFS =\n process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function'\n ? fs.realpathSync.native\n : fs.realpathSync;\n\nfunction realpathSync(x: string) {\n try {\n return realpathFS(x);\n } catch (realpathErr: any) {\n if (realpathErr.code !== 'ENOENT') {\n throw realpathErr;\n }\n }\n return x;\n}\n\nexport function createFastResolver({\n preserveSymlinks,\n blockList,\n}: {\n preserveSymlinks: boolean;\n blockList: RegExp[];\n}) {\n debug('Creating with settings:', { preserveSymlinks, blockList });\n const cachedExtensions: Map<string, readonly string[]> = new Map();\n\n function getAdjustedExtensions({\n metroSourceExtensions,\n platform,\n isNative,\n }: {\n metroSourceExtensions: readonly string[];\n platform: string | null;\n isNative: boolean;\n }): readonly string[] {\n const key = JSON.stringify({ metroSourceExtensions, platform, isNative });\n if (cachedExtensions.has(key)) {\n return cachedExtensions.get(key)!;\n }\n\n let output = metroSourceExtensions;\n if (platform) {\n const nextOutput: string[] = [];\n\n output.forEach((ext) => {\n nextOutput.push(`${platform}.${ext}`);\n if (isNative) {\n nextOutput.push(`native.${ext}`);\n }\n nextOutput.push(ext);\n });\n\n output = nextOutput;\n }\n\n output = Array.from(new Set<string>(output));\n\n // resolve expects these to start with a dot.\n output = output.map((ext) => `.${ext}`);\n\n cachedExtensions.set(key, output);\n\n return output;\n }\n\n function fastResolve(\n context: Pick<\n ResolutionContext,\n | 'unstable_enablePackageExports'\n | 'customResolverOptions'\n | 'sourceExts'\n | 'preferNativePlatform'\n | 'originModulePath'\n | 'getPackage'\n | 'nodeModulesPaths'\n | 'mainFields'\n | 'resolveAsset'\n | 'unstable_conditionNames'\n | 'unstable_conditionsByPlatform'\n | 'fileSystemLookup'\n | 'isESMImport'\n >,\n moduleName: string,\n platform: string | null\n ): Resolution {\n const environment = context.customResolverOptions?.environment;\n const isServer = isServerEnvironment(environment);\n\n const extensions = getAdjustedExtensions({\n metroSourceExtensions: context.sourceExts,\n platform,\n isNative: context.preferNativePlatform,\n }) as string[];\n\n let fp: string;\n\n const conditions = context.unstable_enablePackageExports\n ? [\n ...new Set([\n 'default',\n context.isESMImport === true ? 'import' : 'require',\n ...context.unstable_conditionNames,\n ...(platform != null ? (context.unstable_conditionsByPlatform[platform] ?? []) : []),\n ]),\n ]\n : [];\n\n // NOTE(cedric): metro@0.81.0 ships with `fileSystemLookup`, while `metro@0.80.12` ships as unstable\n const fileSystemLookup = (\n 'unstable_fileSystemLookup' in context\n ? context.unstable_fileSystemLookup\n : context.fileSystemLookup\n ) as ResolutionContext['fileSystemLookup'] | undefined;\n\n if (!fileSystemLookup) {\n throw new Error('Metro API fileSystemLookup is required for fast resolver');\n }\n\n try {\n fp = jestResolver(moduleName, {\n blockList,\n enablePackageExports: context.unstable_enablePackageExports,\n basedir: path.dirname(context.originModulePath),\n paths: context.nodeModulesPaths.length ? (context.nodeModulesPaths as string[]) : undefined,\n extensions,\n conditions,\n realpathSync(file: string): string {\n let metroRealPath: string | null = null;\n\n const res = fileSystemLookup(file);\n if (res?.exists) {\n metroRealPath = res.realPath;\n }\n\n if (metroRealPath == null && preserveSymlinks) {\n return realpathSync(file);\n }\n return metroRealPath ?? file;\n },\n isDirectory(file: string): boolean {\n const res = fileSystemLookup(file);\n return res.exists && res.type === 'd';\n },\n isFile(file: string): boolean {\n const res = fileSystemLookup(file);\n return res.exists && res.type === 'f';\n },\n pathExists(file: string): boolean {\n return fileSystemLookup(file).exists;\n },\n packageFilter(pkg) {\n // set the pkg.main to the first available field in context.mainFields\n for (const field of context.mainFields) {\n if (\n pkg[field] &&\n // object-inspect uses browser: {} in package.json\n typeof pkg[field] === 'string'\n ) {\n return {\n ...pkg,\n main: pkg[field],\n };\n }\n }\n return pkg;\n },\n // Used to ensure files trace to packages instead of node_modules in expo/expo. This is how Metro works and\n // the app doesn't finish without it.\n preserveSymlinks,\n readPackageSync(readFileSync, pkgFile) {\n return context.getPackage(pkgFile) ?? JSON.parse(fs.readFileSync(pkgFile, 'utf8'));\n },\n includeCoreModules: isServer,\n\n pathFilter:\n // Disable `browser` field for server environments.\n isServer\n ? undefined\n : // Enable `browser` field support\n (pkg: any, _resolvedPath: string, relativePathIn: string): string => {\n let relativePath = relativePathIn;\n if (relativePath[0] !== '.') {\n relativePath = `./${relativePath}`;\n }\n\n const replacements = pkg.browser;\n if (replacements === undefined) {\n return '';\n }\n\n // TODO: Probably use a better extension matching system here.\n // This was added for `uuid/v4` -> `./lib/rng` -> `./lib/rng-browser.js`\n const mappedPath = replacements[relativePath] ?? replacements[relativePath + '.js'];\n if (mappedPath === false) {\n throw new ShimModuleError();\n }\n return mappedPath;\n },\n });\n } catch (error: any) {\n if (error instanceof ShimModuleError) {\n return {\n type: 'empty',\n };\n }\n\n if ('code' in error && error.code === 'MODULE_NOT_FOUND') {\n if (isNodeExternal(moduleName)) {\n // In this case, mock the file to use an empty module.\n return {\n type: 'empty',\n };\n }\n\n debug({ moduleName, platform, conditions, isServer, preserveSymlinks }, context);\n\n throw new FailedToResolvePathError(\n 'The module could not be resolved because no file or module matched the pattern:\\n' +\n ` ${formatFileCandidates(\n {\n type: 'sourceFile',\n filePathPrefix: moduleName,\n candidateExts: extensions,\n },\n true\n )}\\n\\nFrom:\\n ${context.originModulePath}\\n`\n );\n }\n throw error;\n }\n\n if (context.sourceExts.some((ext) => fp.endsWith(ext))) {\n return {\n type: 'sourceFile',\n filePath: fp,\n };\n }\n\n if (isNodeExternal(fp)) {\n if (isServer) {\n return {\n type: 'sourceFile',\n filePath: fp,\n };\n }\n // NOTE: This shouldn't happen, the module should throw.\n // Mock non-server built-in modules to empty.\n return {\n type: 'empty',\n };\n }\n\n // NOTE: platform extensions may not be supported on assets.\n\n if (platform === 'web') {\n // Skip multi-resolution on web/server bundles. Only consideration here is that\n // we may still need it in case the only image is a multi-resolution image.\n return {\n type: 'assetFiles',\n filePaths: [fp],\n };\n }\n\n const dirPath = path.dirname(fp);\n const extension = path.extname(fp);\n const basename = path.basename(fp, extension);\n return {\n type: 'assetFiles',\n // Support multi-resolution asset extensions...\n filePaths: context.resolveAsset(dirPath, basename, extension) ?? [fp],\n };\n }\n\n return fastResolve;\n}\n"],"names":["FailedToResolvePathError","createFastResolver","Error","candidates","ShimModuleError","debug","require","realpathFS","process","platform","fs","realpathSync","native","x","realpathErr","code","preserveSymlinks","blockList","cachedExtensions","Map","getAdjustedExtensions","metroSourceExtensions","isNative","key","JSON","stringify","has","get","output","nextOutput","forEach","ext","push","Array","from","Set","map","set","fastResolve","context","moduleName","environment","customResolverOptions","isServer","isServerEnvironment","extensions","sourceExts","preferNativePlatform","fp","conditions","unstable_enablePackageExports","isESMImport","unstable_conditionNames","unstable_conditionsByPlatform","fileSystemLookup","unstable_fileSystemLookup","jestResolver","enablePackageExports","basedir","path","dirname","originModulePath","paths","nodeModulesPaths","length","undefined","file","metroRealPath","res","exists","realPath","isDirectory","type","isFile","pathExists","packageFilter","pkg","field","mainFields","main","readPackageSync","readFileSync","pkgFile","getPackage","parse","includeCoreModules","pathFilter","_resolvedPath","relativePathIn","relativePath","replacements","browser","mappedPath","error","isNodeExternal","formatFileCandidates","filePathPrefix","candidateExts","some","ends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AW;oBAACrD;iBAAG;YACjB;QACF;QAEA,MAAMsD,UAAU3C,eAAI,CAACC,OAAO,CAACZ;QAC7B,MAAMuD,YAAY5C,eAAI,CAAC6C,OAAO,CAACxD;QAC/B,MAAMyD,WAAW9C,eAAI,CAAC8C,QAAQ,CAACzD,IAAIuD;QACnC,OAAO;YACL/B,MAAM;YACN,+CAA+C;YAC/C6B,WAAW9D,QAAQmE,YAAY,CAACJ,SAASG,UAAUF,cAAc;gBAACvD;aAAG;QACvE;IACF;IAEA,OAAOV;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createJResolver.ts"],"sourcesContent":["/**\n * Copyright © 2023 650 Industries.\n * Copyright (c) Meta Platforms, Inc. and affiliates.\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 * Fork of the jest resolver but with additional settings for Metro and pnp removed.\n * https://github.com/jestjs/jest/blob/d1a2ed7fea4bdc19836274cd810c8360e3ab62f3/packages/jest-resolve/src/defaultResolver.ts#L1\n */\nimport type { JSONObject as PackageJSON } from '@expo/json-file';\nimport assert from 'assert';\nimport { dirname, isAbsolute, resolve as pathResolve } from 'path';\nimport { sync as resolveSync, SyncOpts as UpstreamResolveOptions } from 'resolve';\nimport * as resolve from 'resolve.exports';\n\n/**\n * Allows transforming parsed `package.json` contents.\n *\n * @param pkg - Parsed `package.json` contents.\n * @param file - Path to `package.json` file.\n * @param dir - Directory that contains the `package.json`.\n *\n * @returns Transformed `package.json` contents.\n */\ntype PackageFilter = (pkg: PackageJSON, file: string, dir: string) => PackageJSON;\n\n/**\n * Allows transforming a path within a package.\n *\n * @param pkg - Parsed `package.json` contents.\n * @param path - Path being resolved.\n * @param relativePath - Path relative from the `package.json` location.\n *\n * @returns Relative path that will be joined from the `package.json` location.\n */\ntype PathFilter = (pkg: PackageJSON, path: string, relativePath: string) => string;\n\ntype ResolverOptions = {\n /** Directory to begin resolving from. */\n basedir: string;\n /** List of export conditions. */\n conditions?: string[];\n /** Instance of default resolver. */\n defaultResolver: typeof defaultResolver;\n /** List of file extensions to search in order. */\n extensions?: string[];\n /**\n * List of directory names to be looked up for modules recursively.\n *\n * @defaultValue\n * The default is `['node_modules']`.\n */\n moduleDirectory?: string[];\n /**\n * List of `require.paths` to use if nothing is found in `node_modules`.\n *\n * @defaultValue\n * The default is `undefined`.\n */\n paths?: string[];\n /** Allows transforming parsed `package.json` contents. */\n packageFilter?: PackageFilter;\n /** Allows transforms a path within a package. */\n pathFilter?: PathFilter;\n /** Current root directory. */\n rootDir?: string;\n\n enablePackageExports?: boolean;\n\n blockList: RegExp[];\n\n getPackageForModule: import('metro-resolver').CustomResolutionContext['getPackageForModule'];\n} & Pick<\n UpstreamResolveOptions,\n | 'readPackageSync'\n | 'realpathSync'\n | 'moduleDirectory'\n | 'extensions'\n | 'preserveSymlinks'\n | 'includeCoreModules'\n>;\n\ntype UpstreamResolveOptionsWithConditions = UpstreamResolveOptions &\n ResolverOptions & {\n pathExists: (file: string) => boolean;\n };\n\nconst defaultResolver = (\n path: string,\n {\n enablePackageExports,\n blockList = [],\n ...options\n }: Omit<ResolverOptions, 'defaultResolver' | 'getPackageForModule'> & {\n isDirectory: (file: string) => boolean;\n isFile: (file: string) => boolean;\n pathExists: (file: string) => boolean;\n }\n): string => {\n // @ts-expect-error\n const resolveOptions: UpstreamResolveOptionsWithConditions = {\n ...options,\n preserveSymlinks: options.preserveSymlinks,\n defaultResolver,\n };\n\n // resolveSync dereferences symlinks to ensure we don't create a separate\n // module instance depending on how it was referenced.\n const result = resolveSync(enablePackageExports ? getPathInModule(path, resolveOptions) : path, {\n ...resolveOptions,\n preserveSymlinks: !options.preserveSymlinks,\n });\n\n return result;\n};\n\nexport default defaultResolver;\n\n/*\n * helper functions\n */\n\nfunction getPathInModule(path: string, options: UpstreamResolveOptionsWithConditions): string {\n if (shouldIgnoreRequestForExports(path)) {\n return path;\n }\n\n const segments = path.split('/');\n\n let moduleName = segments.shift();\n\n if (!moduleName) {\n return path;\n }\n\n if (moduleName.startsWith('@')) {\n moduleName = `${moduleName}/${segments.shift()}`;\n }\n\n // self-reference\n const closestPackageJson = findClosestPackageJson(options.basedir, options);\n if (closestPackageJson) {\n const pkg = options.readPackageSync!(options.readFileSync!, closestPackageJson);\n assert(pkg, 'package.json should be read by `readPackageSync`');\n\n // Added support for the package.json \"imports\" field (#-prefixed paths)\n if (path.startsWith('#')) {\n const resolved = resolve.imports(pkg, path, createResolveOptions(options.conditions));\n if (resolved) {\n // TODO: Should we attempt to resolve every path in the array?\n return pathResolve(dirname(closestPackageJson), resolved[0]);\n }\n // NOTE: resolve.imports would have thrown by this point.\n return path;\n }\n\n if (pkg.name === moduleName) {\n const resolved = resolve.exports(\n pkg,\n (segments.join('/') || '.') as resolve.Exports.Entry,\n createResolveOptions(options.conditions)\n );\n\n if (resolved) {\n return pathResolve(dirname(closestPackageJson), resolved[0]);\n }\n\n if (pkg.exports) {\n throw new Error(\n \"`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Report an issue: https://github.com/expo/expo/issues\"\n );\n }\n }\n }\n\n let packageJsonPath = '';\n\n try {\n packageJsonPath = resolveSync(`${moduleName}/package.json`, options);\n } catch {\n // ignore if package.json cannot be found\n }\n\n if (!packageJsonPath) {\n return path;\n }\n\n const pkg = options.readPackageSync!(options.readFileSync!, packageJsonPath);\n assert(pkg, 'package.json should be read by `readPackageSync`');\n\n const resolved = resolve.exports(\n pkg,\n (segments.join('/') || '.') as resolve.Exports.Entry,\n createResolveOptions(options.conditions)\n );\n\n if (resolved) {\n return pathResolve(dirname(packageJsonPath), resolved[0]);\n }\n\n if (pkg.exports) {\n throw new Error(\n \"`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Report an issue: https://github.com/expo/expo/issues\"\n );\n }\n\n return path;\n}\n\nfunction createResolveOptions(conditions: string[] | undefined): resolve.Options {\n return conditions\n ? { conditions, unsafe: true }\n : // no conditions were passed - let's assume this is Jest internal and it should be `require`\n { browser: false, require: true };\n}\n\n// if it's a relative import or an absolute path, imports/exports are ignored\nconst shouldIgnoreRequestForExports = (path: string) => path.startsWith('.') || isAbsolute(path);\n\n// adapted from\n// https://github.com/lukeed/escalade/blob/2477005062cdbd8407afc90d3f48f4930354252b/src/sync.js\nfunction findClosestPackageJson(\n start: string,\n options: UpstreamResolveOptionsWithConditions\n): string | undefined {\n let dir = pathResolve('.', start);\n if (!options.isDirectory!(dir)) {\n dir = dirname(dir);\n }\n\n while (true) {\n const pkgJsonFile = pathResolve(dir, './package.json');\n const hasPackageJson = options.pathExists!(pkgJsonFile);\n\n if (hasPackageJson) {\n return pkgJsonFile;\n }\n\n const prevDir = dir;\n dir = dirname(dir);\n\n if (prevDir === dir) {\n return undefined;\n }\n }\n}\n"],"names":["defaultResolver","path","enablePackageExports","blockList","options","resolveOptions","preserveSymlinks","result","resolveSync","getPathInModule","shouldIgnoreRequestForExports","segments","split","moduleName","shift","startsWith","closestPackageJson","findClosestPackageJson","basedir","pkg","readPackageSync","readFileSync","assert","resolved","resolve","imports","createResolveOptions","conditions","pathResolve","dirname","name","exports","join","Error","packageJsonPath","unsafe","browser","require","isAbsolute","start","dir","isDirectory","pkgJsonFile","hasPackageJson","pathExists","prevDir","undefined"],"mappings":"AAAA;;;;;;;;;CASC;;;;+BA4GD;;;eAAA;;;;gEA1GmB;;;;;;;yBACyC;;;;;;;yBACY;;;;;;;iEAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EzB,MAAMA,kBAAkB,CACtBC,MACA,EACEC,oBAAoB,EACpBC,YAAY,EAAE,EACd,GAAGC,SAKJ;IAED,mBAAmB;IACnB,MAAMC,iBAAuD;QAC3D,GAAGD,OAAO;QACVE,kBAAkBF,QAAQE,gBAAgB;QAC1CN;IACF;IAEA,yEAAyE;IACzE,sDAAsD;IACtD,MAAMO,SAASC,IAAAA,eAAW,EAACN,uBAAuBO,gBAAgBR,MAAMI,kB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AMX,IAAAA,eAAO,EAACW;QAEd,IAAIK,YAAYL,KAAK;YACnB,OAAOM;QACT;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createJResolver.ts"],"sourcesContent":["/**\n * Copyright © 2023 650 Industries.\n * Copyright (c) Meta Platforms, Inc. and affiliates.\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 * Fork of the jest resolver but with additional settings for Metro and pnp removed.\n * https://github.com/jestjs/jest/blob/d1a2ed7fea4bdc19836274cd810c8360e3ab62f3/packages/jest-resolve/src/defaultResolver.ts#L1\n */\nimport type { JSONObject as PackageJSON } from '@expo/json-file';\nimport type { CustomResolutionContext } from '@expo/metro/metro-resolver';\nimport assert from 'assert';\nimport { dirname, isAbsolute, resolve as pathResolve } from 'path';\nimport { sync as resolveSync, SyncOpts as UpstreamResolveOptions } from 'resolve';\nimport * as resolve from 'resolve.exports';\n\n/**\n * Allows transforming parsed `package.json` contents.\n *\n * @param pkg - Parsed `package.json` contents.\n * @param file - Path to `package.json` file.\n * @param dir - Directory that contains the `package.json`.\n *\n * @returns Transformed `package.json` contents.\n */\ntype PackageFilter = (pkg: PackageJSON, file: string, dir: string) => PackageJSON;\n\n/**\n * Allows transforming a path within a package.\n *\n * @param pkg - Parsed `package.json` contents.\n * @param path - Path being resolved.\n * @param relativePath - Path relative from the `package.json` location.\n *\n * @returns Relative path that will be joined from the `package.json` location.\n */\ntype PathFilter = (pkg: PackageJSON, path: string, relativePath: string) => string;\n\n// TODO(@kitten): This probably has overlap with an @expo/metro type\ntype ResolverOptions = {\n /** Directory to begin resolving from. */\n basedir: string;\n /** List of export conditions. */\n conditions?: string[];\n /** Instance of default resolver. */\n defaultResolver: typeof defaultResolver;\n /** List of file extensions to search in order. */\n extensions?: string[];\n /**\n * List of directory names to be looked up for modules recursively.\n *\n * @defaultValue\n * The default is `['node_modules']`.\n */\n moduleDirectory?: string[];\n /**\n * List of `require.paths` to use if nothing is found in `node_modules`.\n *\n * @defaultValue\n * The default is `undefined`.\n */\n paths?: string[];\n /** Allows transforming parsed `package.json` contents. */\n packageFilter?: PackageFilter;\n /** Allows transforms a path within a package. */\n pathFilter?: PathFilter;\n /** Current root directory. */\n rootDir?: string;\n\n enablePackageExports?: boolean;\n\n blockList: RegExp[];\n\n getPackageForModule: CustomResolutionContext['getPackageForModule'];\n} & Pick<\n UpstreamResolveOptions,\n | 'readPackageSync'\n | 'realpathSync'\n | 'moduleDirectory'\n | 'extensions'\n | 'preserveSymlinks'\n | 'includeCoreModules'\n>;\n\ntype UpstreamResolveOptionsWithConditions = UpstreamResolveOptions &\n ResolverOptions & {\n pathExists: (file: string) => boolean;\n };\n\nconst defaultResolver = (\n path: string,\n {\n enablePackageExports,\n blockList = [],\n ...options\n }: Omit<ResolverOptions, 'defaultResolver' | 'getPackageForModule'> & {\n isDirectory: (file: string) => boolean;\n isFile: (file: string) => boolean;\n pathExists: (file: string) => boolean;\n }\n): string => {\n // @ts-expect-error\n const resolveOptions: UpstreamResolveOptionsWithConditions = {\n ...options,\n preserveSymlinks: options.preserveSymlinks,\n defaultResolver,\n };\n\n // resolveSync dereferences symlinks to ensure we don't create a separate\n // module instance depending on how it was referenced.\n const result = resolveSync(enablePackageExports ? getPathInModule(path, resolveOptions) : path, {\n ...resolveOptions,\n preserveSymlinks: !options.preserveSymlinks,\n });\n\n return result;\n};\n\nexport default defaultResolver;\n\n/*\n * helper functions\n */\n\nfunction getPathInModule(path: string, options: UpstreamResolveOptionsWithConditions): string {\n if (shouldIgnoreRequestForExports(path)) {\n return path;\n }\n\n const segments = path.split('/');\n\n let moduleName = segments.shift();\n\n if (!moduleName) {\n return path;\n }\n\n if (moduleName.startsWith('@')) {\n moduleName = `${moduleName}/${segments.shift()}`;\n }\n\n // self-reference\n const closestPackageJson = findClosestPackageJson(options.basedir, options);\n if (closestPackageJson) {\n const pkg = options.readPackageSync!(options.readFileSync!, closestPackageJson);\n assert(pkg, 'package.json should be read by `readPackageSync`');\n\n // Added support for the package.json \"imports\" field (#-prefixed paths)\n if (path.startsWith('#')) {\n const resolved = resolve.imports(pkg, path, createResolveOptions(options.conditions));\n if (resolved) {\n // TODO: Should we attempt to resolve every path in the array?\n return pathResolve(dirname(closestPackageJson), resolved[0]);\n }\n // NOTE: resolve.imports would have thrown by this point.\n return path;\n }\n\n if (pkg.name === moduleName) {\n const resolved = resolve.exports(\n pkg,\n (segments.join('/') || '.') as resolve.Exports.Entry,\n createResolveOptions(options.conditions)\n );\n\n if (resolved) {\n return pathResolve(dirname(closestPackageJson), resolved[0]);\n }\n\n if (pkg.exports) {\n throw new Error(\n \"`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Report an issue: https://github.com/expo/expo/issues\"\n );\n }\n }\n }\n\n let packageJsonPath = '';\n\n try {\n packageJsonPath = resolveSync(`${moduleName}/package.json`, options);\n } catch {\n // ignore if package.json cannot be found\n }\n\n if (!packageJsonPath) {\n return path;\n }\n\n const pkg = options.readPackageSync!(options.readFileSync!, packageJsonPath);\n assert(pkg, 'package.json should be read by `readPackageSync`');\n\n const resolved = resolve.exports(\n pkg,\n (segments.join('/') || '.') as resolve.Exports.Entry,\n createResolveOptions(options.conditions)\n );\n\n if (resolved) {\n return pathResolve(dirname(packageJsonPath), resolved[0]);\n }\n\n if (pkg.exports) {\n throw new Error(\n \"`exports` exists, but no results - this is a bug in Expo CLI's Metro resolver. Report an issue: https://github.com/expo/expo/issues\"\n );\n }\n\n return path;\n}\n\nfunction createResolveOptions(conditions: string[] | undefined): resolve.Options {\n return conditions\n ? { conditions, unsafe: true }\n : // no conditions were passed - let's assume this is Jest internal and it should be `require`\n { browser: false, require: true };\n}\n\n// if it's a relative import or an absolute path, imports/exports are ignored\nconst shouldIgnoreRequestForExports = (path: string) => path.startsWith('.') || isAbsolute(path);\n\n// adapted from\n// https://github.com/lukeed/escalade/blob/2477005062cdbd8407afc90d3f48f4930354252b/src/sync.js\nfunction findClosestPackageJson(\n start: string,\n options: UpstreamResolveOptionsWithConditions\n): string | undefined {\n let dir = pathResolve('.', start);\n if (!options.isDirectory!(dir)) {\n dir = dirname(dir);\n }\n\n while (true) {\n const pkgJsonFile = pathResolve(dir, './package.json');\n const hasPackageJson = options.pathExists!(pkgJsonFile);\n\n if (hasPackageJson) {\n return pkgJsonFile;\n }\n\n const prevDir = dir;\n dir = dirname(dir);\n\n if (prevDir === dir) {\n return undefined;\n }\n }\n}\n"],"names":["defaultResolver","path","enablePackageExports","blockList","options","resolveOptions","preserveSymlinks","result","resolveSync","getPathInModule","shouldIgnoreRequestForExports","segments","split","moduleName","shift","startsWith","closestPackageJson","findClosestPackageJson","basedir","pkg","readPackageSync","readFileSync","assert","resolved","resolve","imports","createResolveOptions","conditions","pathResolve","dirname","name","exports","join","Error","packageJsonPath","unsafe","browser","require","isAbsolute","start","dir","isDirectory","pkgJsonFile","hasPackageJson","pathExists","prevDir","undefined"],"mappings":"AAAA;;;;;;;;;CASC;;;;+BA8GD;;;eAAA;;;;gEA3GmB;;;;;;;yBACyC;;;;;;;yBACY;;;;;;;iEAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EzB,MAAMA,kBAAkB,CACtBC,MACA,EACEC,oBAAoB,EACpBC,YAAY,EAAE,EACd,GAAGC,SAKJ;IAED,mBAAmB;IACnB,MAAMC,iBAAuD;QAC3D,GAAGD,OAAO;QACVE,kBAAkBF,QAAQE,gBAAgB;QAC1CN;IACF;IAEA,yEAAyE;IACzE,sDAAsD;IACtD,MAAMO,SAASC,IAAAA,eAAW,EAACN,uBAAuBO,gBAAgBR,MAAMI,kBAAkBJ,MAAM;QAC9F,GAAGI,cAAc;QACjBC,kBAAkB,CAACF,QAAQE,gBAAgB;IAC7C;IAEA,OAAOC;AACT;MAEA,WAAeP;AAEf;;CAEC,GAED,SAASS,gBAAgBR,IAAY,EAAEG,OAA6C;IAClF,IAAIM,8BAA8BT,OAAO;QACvC,OAAOA;IACT;IA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|
|
31
|
+
function _private() {
|
|
32
|
+
const data = require("@expo/server/private");
|
|
33
|
+
_private = function() {
|
|
34
34
|
return data;
|
|
35
35
|
};
|
|
36
36
|
return data;
|
|
@@ -74,7 +74,7 @@ const debug = require('debug')('expo:rsc');
|
|
|
74
74
|
const getMetroServerRootMemo = (0, _fn.memoize)(_paths().getMetroServerRoot);
|
|
75
75
|
function createServerComponentsMiddleware(projectRoot, { rscPath, instanceMetroOptions, ssrLoadModule, ssrLoadModuleArtifacts, useClientRouter, createModuleId, routerOptions }) {
|
|
76
76
|
const routerModule = useClientRouter ? 'expo-router/build/rsc/router/noopRouter' : 'expo-router/build/rsc/router/expo-definedRouter';
|
|
77
|
-
const rscMiddleware = (0,
|
|
77
|
+
const rscMiddleware = (0, _private().getRscMiddleware)({
|
|
78
78
|
config: {},
|
|
79
79
|
// Disabled in development
|
|
80
80
|
baseUrl: '',
|
|
@@ -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 { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/build/middleware/rsc';\nimport assert from 'assert';\nimport { 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 { 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 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;;;;;;;gEACd;;;;;;;gEA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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 { 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;;;;;;;gEACd;;;;;;;gEAEF;;;;;;;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,eAAe,EACfC,cAAc,EACdC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
@@ -49,7 +49,7 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
49
49
|
if (!_resolvefrom().default.silent(projectRoot, 'expo-router')) {
|
|
50
50
|
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 'static' in your app.json.`);
|
|
51
51
|
}
|
|
52
|
-
const { createRequestHandler } = require('@expo/server/
|
|
52
|
+
const { createRequestHandler } = require('@expo/server/adapter/http');
|
|
53
53
|
return createRequestHandler({
|
|
54
54
|
build: ''
|
|
55
55
|
}, {
|
|
@@ -103,12 +103,13 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
105
|
},
|
|
106
|
-
|
|
107
|
-
(
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
106
|
+
async handleRouteError (error) {
|
|
107
|
+
const { ExpoError } = require('@expo/server');
|
|
108
|
+
if (ExpoError.isExpoError(error)) {
|
|
109
|
+
// TODO(@krystofwoldrich): Can we show code snippet of the handler?
|
|
110
|
+
// NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.
|
|
111
|
+
delete error.stack;
|
|
112
|
+
}
|
|
112
113
|
const htmlServerError = await (0, _metroErrorInterface.getErrorOverlayHtmlAsync)({
|
|
113
114
|
error,
|
|
114
115
|
projectRoot,
|
|
@@ -137,7 +138,7 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
137
138
|
basedir: options.appDir
|
|
138
139
|
});
|
|
139
140
|
try {
|
|
140
|
-
debug(`Bundling
|
|
141
|
+
debug(`Bundling API route at: ${resolvedFunctionPath}`);
|
|
141
142
|
return await options.bundleApiRoute(resolvedFunctionPath);
|
|
142
143
|
} catch (error) {
|
|
143
144
|
return new Response('Failed to load API Route: ' + resolvedFunctionPath + '\n\n' + error.message, {
|
|
@@ -147,6 +148,51 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
147
148
|
}
|
|
148
149
|
});
|
|
149
150
|
}
|
|
151
|
+
},
|
|
152
|
+
async getMiddleware (route) {
|
|
153
|
+
var _exp_web;
|
|
154
|
+
const { exp } = options.config;
|
|
155
|
+
if (!options.unstable_useServerMiddleware) {
|
|
156
|
+
return {
|
|
157
|
+
default: ()=>{
|
|
158
|
+
throw new _errors.CommandError('Server middleware is not enabled. Add unstable_useServerMiddleware: true to your `expo-router` plugin config.');
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
if (((_exp_web = exp.web) == null ? void 0 : _exp_web.output) !== 'server') {
|
|
163
|
+
(0, _router.warnInvalidMiddlewareOutput)();
|
|
164
|
+
return {
|
|
165
|
+
default: ()=>{
|
|
166
|
+
console.warn('Server middleware is only supported when web.output is set to "server" in your app config');
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const resolvedFunctionPath = await resolveAsync(route.file, {
|
|
171
|
+
extensions: [
|
|
172
|
+
'.js',
|
|
173
|
+
'.jsx',
|
|
174
|
+
'.ts',
|
|
175
|
+
'.tsx'
|
|
176
|
+
],
|
|
177
|
+
basedir: options.appDir
|
|
178
|
+
});
|
|
179
|
+
try {
|
|
180
|
+
var _middlewareModule_unstable_settings;
|
|
181
|
+
debug(`Bundling middleware at: ${resolvedFunctionPath}`);
|
|
182
|
+
const middlewareModule = await options.bundleApiRoute(resolvedFunctionPath);
|
|
183
|
+
if ((_middlewareModule_unstable_settings = middlewareModule.unstable_settings) == null ? void 0 : _middlewareModule_unstable_settings.matcher) {
|
|
184
|
+
var _middlewareModule_unstable_settings1;
|
|
185
|
+
(0, _router.warnInvalidMiddlewareMatcherSettings)((_middlewareModule_unstable_settings1 = middlewareModule.unstable_settings) == null ? void 0 : _middlewareModule_unstable_settings1.matcher);
|
|
186
|
+
}
|
|
187
|
+
return middlewareModule;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
return new Response('Failed to load middleware: ' + resolvedFunctionPath + '\n\n' + error.message, {
|
|
190
|
+
status: 500,
|
|
191
|
+
headers: {
|
|
192
|
+
'Content-Type': 'text/html'
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
}
|
|
150
196
|
}
|
|
151
197
|
});
|
|
152
198
|
}
|
|
@@ -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 resolve from 'resolve';\nimport resolveFrom from 'resolve-from';\nimport { promisify } from 'util';\n\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync, logMetroError } from './metroErrorInterface';\nimport { warnInvalidWebOutput } 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 'static' in your app.json.`\n );\n }\n\n const { createRequestHandler } =\n require('@expo/server/build/vendor/http') as typeof import('@expo/server/build/vendor/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 logApiRouteExecutionError(error) {\n logMetroError(projectRoot, { error });\n },\n async handleApiRouteError(error) {\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 middleware 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 }\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","logApiRouteExecutionError","logMetroError","handleApiRouteError","htmlServerError","getApiRoute","route","exp","config","web","output","warnInvalidWebOutput","resolvedFunctionPath","extensions","basedir","appDir","bundleApiRoute"],"mappings":"AAAA;;;;;CAKC;;;;+BAmBeA;;;eAAAA;;;;gEAhBI;;;;;;;gEACI;;;;;;;yBACE;;;;;;qCAEI;qCAC0B;wBACnB;wBACR;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,eAAeC,IAAAA,iBAAS,EAACC,kBAAO;AAK/B,SAASL,6BACdM,WAAmB,EACnBC,OAQuD;IAEvD,IAAI,CAACC,sBAAW,CAACC,MAAM,CAACH,aAAa,gBAAgB;QACnD,MAAM,IAAII,oBAAY,CACpB,CAAC,yLAAyL,CAAC;IAE/L;IAEA,MAAM,EAAEC,oBAAoB,EAAE,GAC5BT,QAAQ;IAEV,OAAOS,qBACL;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;iBACD;gBACDC,WAAW,EAAE;gBACbC,gBAAgB,EAAE;gBAClBC,WAAW,EAAE;gBACbC,UAAU,EAAE;YACd;QAEJ;QACA,MAAMC,SAAQC,OAAO;YACnB,IAAI;gBACF,MAAM,EAAEC,OAAO,EAAE,GAAG,MAAMpB,QAAQqB,kBAAkB,CAACF,QAAQG,GAAG;g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OnB,OAAY;gBACnB,OAAO,IAAIC,SACT,+BAA+BkB,uBAAuB,SAASnB,MAAMO,OAAO,EAC5E;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 { 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 'static' 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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ZJ,MAAM,EAAEA,GAAG,EAAE,GAAGtC,QAAQuC,MAAM;YAE9B,IAAI,CAACvC,QAAQiD,4BAA4B,EAAE;gBACzC,OAAO;oBACLC,SAAS;wBACP,MAAM,IAAI/C,oBAAY,CACpB;oBAEJ;gBACF;YACF;YAEA,IAAImC,EAAAA,WAAAA,IAAIE,GAAG,qBAAPF,SAASG,MAAM,MAAK,UAAU;gBAChCU,IAAAA,mCAA2B;gBAC3B,OAAO;oBACLD,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"}
|
|
@@ -40,6 +40,7 @@ async function attachAtlasAsync(options) {
|
|
|
40
40
|
if (!atlas) {
|
|
41
41
|
return debug('Atlas is not installed in the project, skipping initialization');
|
|
42
42
|
}
|
|
43
|
+
// TODO(@kitten): Atlas' typings don't match @expo/metro yet
|
|
43
44
|
const instance = atlas.createExpoAtlasMiddleware(options.metroConfig);
|
|
44
45
|
options.middleware.use('/_expo/atlas', instance.middleware);
|
|
45
46
|
debug('Attached Atlas middleware for development on: /_expo/atlas');
|
|
@@ -69,6 +70,7 @@ function importAtlasForDev(projectRoot) {
|
|
|
69
70
|
const filePath = await atlas.resetExpoAtlasFile(options.projectRoot);
|
|
70
71
|
debug('(Re)created Atlas file at:', filePath);
|
|
71
72
|
}
|
|
73
|
+
// TODO(@kitten): Atlas' typings don't match @expo/metro yet
|
|
72
74
|
atlas.withExpoAtlas(options.metroConfig);
|
|
73
75
|
debug('Attached Atlas to Metro config for exporting');
|
|
74
76
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/attachAtlas.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/start/server/metro/debugging/attachAtlas.ts"],"sourcesContent":["import type { ConfigT as MetroConfig } from '@expo/metro/metro-config';\nimport type { Server as ConnectServer } from 'connect';\n\nimport { AtlasPrerequisite } from './AtlasPrerequisite';\nimport { env } from '../../../../utils/env';\nimport { type EnsureDependenciesOptions } from '../../../doctor/dependencies/ensureDependenciesAsync';\n\nconst debug = require('debug')('expo:metro:debugging:attachAtlas') as typeof console.log;\n\ntype AttachAtlasOptions = Pick<EnsureDependenciesOptions, 'exp'> & {\n isExporting: boolean;\n projectRoot: string;\n middleware?: ConnectServer;\n metroConfig: MetroConfig;\n resetAtlasFile?: boolean;\n};\n\nexport async function attachAtlasAsync(\n options: AttachAtlasOptions\n): Promise<void | ReturnType<typeof import('expo-atlas/cli').createExpoAtlasMiddleware>> {\n if (!env.EXPO_ATLAS) {\n return;\n }\n\n debug('Atlas is enabled, initializing for this project...');\n await new AtlasPrerequisite(options.projectRoot).bootstrapAsync({ exp: options.exp });\n\n return !options.isExporting\n ? attachAtlasToDevServer(options)\n : await attachAtlasToExport(options);\n}\n\n/**\n * Attach Atlas to the Metro bundler for development mode.\n * This includes attaching to Metro's middleware stack to host the Atlas UI.\n */\nfunction attachAtlasToDevServer(\n options: Pick<AttachAtlasOptions, 'projectRoot' | 'middleware' | 'metroConfig'>\n): void | ReturnType<typeof import('expo-atlas/cli').createExpoAtlasMiddleware> {\n if (!options.middleware) {\n throw new Error(\n 'Expected middleware to be provided for Atlas when running in development mode'\n );\n }\n\n const atlas = importAtlasForDev(options.projectRoot);\n if (!atlas) {\n return debug('Atlas is not installed in the project, skipping initialization');\n }\n\n // TODO(@kitten): Atlas' typings don't match @expo/metro yet\n const instance = atlas.createExpoAtlasMiddleware(options.metroConfig as any);\n options.middleware.use('/_expo/atlas', instance.middleware);\n debug('Attached Atlas middleware for development on: /_expo/atlas');\n return instance;\n}\n\nfunction importAtlasForDev(projectRoot: string): null | typeof import('expo-atlas/cli') {\n try {\n return require(require.resolve('expo-atlas/cli', { paths: [projectRoot] }));\n } catch (error: any) {\n debug('Failed to load Atlas from project:', error);\n return null;\n }\n}\n\n/**\n * Attach Atlas to the Metro bundler for exporting mode.\n * This only includes attaching the custom serializer to the Metro config.\n */\nasync function attachAtlasToExport(\n options: Pick<AttachAtlasOptions, 'projectRoot' | 'metroConfig' | 'resetAtlasFile'>\n): Promise<void> {\n const atlas = importAtlasForExport(options.projectRoot);\n if (!atlas) {\n return debug('Atlas is not installed in the project, skipping initialization');\n }\n\n if (options.resetAtlasFile) {\n const filePath = await atlas.resetExpoAtlasFile(options.projectRoot);\n debug('(Re)created Atlas file at:', filePath);\n }\n\n // TODO(@kitten): Atlas' typings don't match @expo/metro yet\n atlas.withExpoAtlas(options.metroConfig as any);\n debug('Attached Atlas to Metro config for exporting');\n}\n\nfunction importAtlasForExport(projectRoot: string): null | typeof import('expo-atlas/metro') {\n try {\n return require(require.resolve('expo-atlas/metro', { paths: [projectRoot] }));\n } catch (error: any) {\n debug('Failed to load Atlas from project:', error);\n return null;\n }\n}\n\n/**\n * Wait until the Atlas file has all data written.\n * Note, this is a workaround whenever `process.exit` is required, avoid if possible.\n * @internal\n */\nexport async function waitUntilAtlasExportIsReadyAsync(projectRoot: string) {\n if (!env.EXPO_ATLAS) return;\n\n const atlas = importAtlasForExport(projectRoot);\n\n if (!atlas) {\n return debug('Atlas is not loaded, cannot wait for export to finish');\n }\n if (typeof atlas.waitUntilAtlasFileReady !== 'function') {\n return debug('Atlas is outdated, cannot wait for export to finish');\n }\n\n debug('Waiting for Atlas to finish exporting...');\n await atlas.waitUntilAtlasFileReady();\n debug('Atlas export is ready');\n}\n"],"names":["attachAtlasAsync","waitUntilAtlasExportIsReadyAsync","debug","require","options","env","EXPO_ATLAS","AtlasPrerequisite","projectRoot","bootstrapAsync","exp","isExporting","attachAtlasToDevServer","attachAtlasToExport","middleware","Error","atlas","importAtlasForDev","instance","createExpoAtlasMiddleware","metroConfig","use","resolve","paths","error","importAtlasForExport","resetAtlasFile","filePath","resetExpoAtlasFile","withExpoAtlas","waitUntilAtlasFileReady"],"mappings":";;;;;;;;;;;IAiBsBA,gBAAgB;eAAhBA;;IAqFAC,gCAAgC;eAAhCA;;;mCAnGY;qBACd;AAGpB,MAAMC,QAAQC,QAAQ,SAAS;AAUxB,eAAeH,iBACpBI,OAA2B;IAE3B,IAAI,CAACC,QAAG,CAACC,UAAU,EAAE;QACnB;IACF;IAEAJ,MAAM;IACN,MAAM,IAAIK,oCAAiB,CAACH,QAAQI,WAAW,EAAEC,cAAc,CAAC;QAAEC,KAAKN,QAAQM,GAAG;IAAC;IAEnF,OAAO,CAACN,QAAQO,WAAW,GACvBC,uBAAuBR,WACvB,MAAMS,oBAAoBT;AAChC;AAEA;;;CAGC,GACD,SAASQ,uBACPR,OAA+E;IAE/E,IAAI,CAACA,QAAQU,UAAU,EAAE;QACvB,MAAM,IAAIC,MACR;IAEJ;IAEA,MAAMC,QAAQC,kBAAkBb,QAAQI,WAAW;IACnD,IAAI,CAACQ,OAAO;QACV,OAAOd,MAAM;IACf;IAEA,4DAA4D;IAC5D,MAAMgB,WAAWF,MAAMG,yBAAyB,CAACf,QAAQgB,WAAW;IACpEhB,QAAQU,UAAU,CAACO,GAAG,CAAC,gBAAgBH,SAASJ,UAAU;IAC1DZ,MAAM;IACN,OAAOgB;AACT;AAEA,SAASD,kBAAkBT,WAAmB;IAC5C,IAAI;QACF,OAAOL,QAAQA,QAAQmB,OAAO,CAAC,kBAAkB;YAAEC,OAAO;gBAACf;aAAY;QAAC;IAC1E,EAAE,OAAOgB,OAAY;QACnBtB,MAAM,sCAAsCsB;QAC5C,OAAO;IACT;AACF;AAEA;;;CAGC,GACD,eAAeX,oBACbT,OAAmF;IAEnF,MAAMY,QAAQS,qBAAqBrB,QAAQI,WAAW;IACtD,IAAI,CAACQ,OAAO;QACV,OAAOd,MAAM;IACf;IAEA,IAAIE,QAAQsB,cAAc,EAAE;QAC1B,MAAMC,WAAW,MAAMX,MAAMY,kBAAkB,CAACxB,QAAQI,WAAW;QACnEN,MAAM,8BAA8ByB;IACtC;IAEA,4DAA4D;IAC5DX,MAAMa,aAAa,CAACzB,QAAQgB,WAAW;IACvClB,MAAM;AACR;AAEA,SAASuB,qBAAqBjB,WAAmB;IAC/C,IAAI;QACF,OAAOL,QAAQA,QAAQmB,OAAO,CAAC,oBAAoB;YAAEC,OAAO;gBAACf;aAAY;QAAC;IAC5E,EAAE,OAAOgB,OAAY;QACnBtB,MAAM,sCAAsCsB;QAC5C,OAAO;IACT;AACF;AAOO,eAAevB,iCAAiCO,WAAmB;IACxE,IAAI,CAACH,QAAG,CAACC,UAAU,EAAE;IAErB,MAAMU,QAAQS,qBAAqBjB;IAEnC,IAAI,CAACQ,OAAO;QACV,OAAOd,MAAM;IACf;IACA,IAAI,OAAOc,MAAMc,uBAAuB,KAAK,YAAY;QACvD,OAAO5B,MAAM;IACf;IAEAA,MAAM;IACN,MAAMc,MAAMc,uBAAuB;IACnC5B,MAAM;AACR"}
|
|
@@ -72,7 +72,7 @@ const metroOpenStackFrameMiddleware = (req, res, next)=>{
|
|
|
72
72
|
};
|
|
73
73
|
function createMetroStatusMiddleware(metroConfig) {
|
|
74
74
|
return (_req, res)=>{
|
|
75
|
-
res.setHeader('X-React-Native-Project-Root', metroConfig.projectRoot);
|
|
75
|
+
res.setHeader('X-React-Native-Project-Root', encodeURI(metroConfig.projectRoot));
|
|
76
76
|
res.end('packager-status:running');
|
|
77
77
|
};
|
|
78
78
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../src/start/server/metro/dev-server/createMetroMiddleware.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../../../../../src/start/server/metro/dev-server/createMetroMiddleware.ts"],"sourcesContent":["import type { MetroConfig } from '@expo/metro/metro';\nimport connect from 'connect';\n\nimport { createEventsSocket } from './createEventSocket';\nimport { createMessagesSocket } from './createMessageSocket';\nimport { Log } from '../../../../log';\nimport { openInEditorAsync } from '../../../../utils/editor';\n\nconst compression = require('compression');\n\nexport function createMetroMiddleware(metroConfig: Pick<MetroConfig, 'projectRoot'>) {\n const messages = createMessagesSocket({ logger: Log });\n const events = createEventsSocket(messages);\n\n const middleware = connect()\n .use(noCacheMiddleware)\n .use(compression())\n // Support opening stack frames from clients directly in the editor\n .use('/open-stack-frame', rawBodyMiddleware)\n .use('/open-stack-frame', metroOpenStackFrameMiddleware)\n // Support the symbolication endpoint of Metro\n // See: https://github.com/facebook/metro/blob/a792d85ffde3c21c3fbf64ac9404ab0afe5ff957/packages/metro/src/Server.js#L1266\n .use('/symbolicate', rawBodyMiddleware)\n // Support status check to detect if the packager needs to be started from the native side\n .use('/status', createMetroStatusMiddleware(metroConfig));\n\n return {\n middleware,\n messagesSocket: messages,\n eventsSocket: events,\n websocketEndpoints: {\n [messages.endpoint]: messages.server,\n [events.endpoint]: events.server,\n },\n };\n}\n\nconst noCacheMiddleware: connect.NextHandleFunction = (req, res, next) => {\n res.setHeader('Surrogate-Control', 'no-store');\n res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');\n res.setHeader('Pragma', 'no-cache');\n res.setHeader('Expires', '0');\n next();\n};\n\nconst rawBodyMiddleware: connect.NextHandleFunction = (req, _res, next) => {\n const reqWithBody = req as typeof req & { rawBody: string };\n reqWithBody.setEncoding('utf8');\n reqWithBody.rawBody = '';\n reqWithBody.on('data', (chunk) => (reqWithBody.rawBody += chunk));\n reqWithBody.on('end', next);\n};\n\nconst metroOpenStackFrameMiddleware: connect.NextHandleFunction = (req, res, next) => {\n // Only accept POST requests\n if (req.method !== 'POST') return next();\n // Only handle requests with a raw body\n if (!('rawBody' in req) || !req.rawBody) {\n res.statusCode = 406;\n return res.end('Open stack frame requires the JSON stack frame as request body');\n }\n\n const frame = JSON.parse(req.rawBody as string);\n openInEditorAsync(frame.file, frame.lineNumber).finally(() => res.end('OK'));\n};\n\nfunction createMetroStatusMiddleware(\n metroConfig: Pick<MetroConfig, 'projectRoot'>\n): connect.NextHandleFunction {\n return (_req, res) => {\n res.setHeader('X-React-Native-Project-Root', encodeURI(metroConfig.projectRoot!));\n res.end('packager-status:running');\n };\n}\n"],"names":["createMetroMiddleware","compression","require","metroConfig","messages","createMessagesSocket","logger","Log","events","createEventsSocket","middleware","connect","use","noCacheMiddleware","rawBodyMiddleware","metroOpenStackFrameMiddleware","createMetroStatusMiddleware","messagesSocket","eventsSocket","websocketEndpoints","endpoint","server","req","res","next","setHeader","_res","reqWithBody","setEncoding","rawBody","on","chunk","method","statusCode","end","frame","JSON","parse","openInEditorAsync","file","lineNumber","finally","_req","encodeURI","projectRoot"],"mappings":";;;;+BAUgBA;;;eAAAA;;;;gEATI;;;;;;mCAEe;qCACE;qBACjB;wBACc;;;;;;AAElC,MAAMC,cAAcC,QAAQ;AAErB,SAASF,sBAAsBG,WAA6C;IACjF,MAAMC,WAAWC,IAAAA,yCAAoB,EAAC;QAAEC,QAAQC,QAAG;IAAC;IACpD,MAAMC,SAASC,IAAAA,qCAAkB,EAACL;IAElC,MAAMM,aAAaC,IAAAA,kBAAO,IACvBC,GAAG,CAACC,mBACJD,GAAG,CAACX,cACL,mEAAmE;KAClEW,GAAG,CAAC,qBAAqBE,mBACzBF,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E,SAAS,CAAC,+BAA+BkB,UAAUxC,YAAYyC,WAAW;QAC9ErB,IAAIW,GAAG,CAAC;IACV;AACF"}
|
|
@@ -59,6 +59,7 @@ function inflateManifest(json) {
|
|
|
59
59
|
var _json_htmlRoutes, _json_apiRoutes, _json_notFoundRoutes, _json_redirects, _json_rewrites;
|
|
60
60
|
return {
|
|
61
61
|
...json,
|
|
62
|
+
middleware: json.middleware,
|
|
62
63
|
htmlRoutes: (_json_htmlRoutes = json.htmlRoutes) == null ? void 0 : _json_htmlRoutes.map((value)=>{
|
|
63
64
|
return {
|
|
64
65
|
...value,
|