@expo/cli 54.0.8 → 54.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +1 -1
- package/build/src/serve/serveAsync.js +7 -7
- package/build/src/serve/serveAsync.js.map +1 -1
- package/build/src/start/doctor/dependencies/getVersionedPackages.js +0 -4
- package/build/src/start/doctor/dependencies/getVersionedPackages.js.map +1 -1
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js +3 -0
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js.map +1 -1
- package/build/src/start/server/metro/createServerComponentsMiddleware.js +6 -6
- package/build/src/start/server/metro/createServerComponentsMiddleware.js.map +1 -1
- package/build/src/start/server/metro/createServerRouteMiddleware.js +11 -5
- package/build/src/start/server/metro/createServerRouteMiddleware.js.map +1 -1
- package/build/src/start/server/metro/router.js.map +1 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js +1 -1
- package/build/src/start/server/middleware/createBuiltinAPIRequestHandler.js.map +1 -1
- package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
- package/build/src/utils/telemetry/utils/context.js +1 -1
- package/package.json +7 -7
- package/static/template/[...rsc]+api.ts +1 -1
package/build/bin/cli
CHANGED
|
@@ -8,13 +8,6 @@ Object.defineProperty(exports, "serveAsync", {
|
|
|
8
8
|
return serveAsync;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
|
-
function _http() {
|
|
12
|
-
const data = require("@expo/server/adapter/http");
|
|
13
|
-
_http = function() {
|
|
14
|
-
return data;
|
|
15
|
-
};
|
|
16
|
-
return data;
|
|
17
|
-
}
|
|
18
11
|
function _chalk() {
|
|
19
12
|
const data = /*#__PURE__*/ _interop_require_default(require("chalk"));
|
|
20
13
|
_chalk = function() {
|
|
@@ -29,6 +22,13 @@ function _connect() {
|
|
|
29
22
|
};
|
|
30
23
|
return data;
|
|
31
24
|
}
|
|
25
|
+
function _http() {
|
|
26
|
+
const data = require("expo-server/adapter/http");
|
|
27
|
+
_http = function() {
|
|
28
|
+
return data;
|
|
29
|
+
};
|
|
30
|
+
return data;
|
|
31
|
+
}
|
|
32
32
|
function _http1() {
|
|
33
33
|
const data = /*#__PURE__*/ _interop_require_default(require("http"));
|
|
34
34
|
_http1 = function() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/serve/serveAsync.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../../src/serve/serveAsync.ts"],"sourcesContent":["import chalk from 'chalk';\nimport connect from 'connect';\nimport { createRequestHandler } from 'expo-server/adapter/http';\nimport http from 'http';\nimport path from 'path';\nimport send from 'send';\n\nimport * as Log from '../log';\nimport { directoryExistsAsync, fileExistsAsync } from '../utils/dir';\nimport { CommandError } from '../utils/errors';\nimport { findUpProjectRootOrAssert } from '../utils/findUp';\nimport { setNodeEnv } from '../utils/nodeEnv';\nimport { resolvePortAsync } from '../utils/port';\n\ntype Options = {\n port?: number;\n isDefaultDirectory: boolean;\n};\n\nconst debug = require('debug')('expo:serve') as typeof console.log;\n\n// Start a basic http server\nexport async function serveAsync(inputDir: string, options: Options) {\n const projectRoot = findUpProjectRootOrAssert(inputDir);\n\n setNodeEnv('production');\n require('@expo/env').load(projectRoot);\n\n const port = await resolvePortAsync(projectRoot, {\n defaultPort: options.port,\n fallbackPort: 8081,\n });\n\n if (port == null) {\n throw new CommandError('Could not start server. Port is not available.');\n }\n options.port = port;\n\n const serverDist = options.isDefaultDirectory ? path.join(inputDir, 'dist') : inputDir;\n // TODO: `.expo/server/ios`, `.expo/server/android`, etc.\n\n if (!(await directoryExistsAsync(serverDist))) {\n throw new CommandError(\n `The server directory ${serverDist} does not exist. Run \\`npx expo export\\` first.`\n );\n }\n\n const isStatic = await isStaticExportAsync(serverDist);\n\n Log.log(chalk.dim(`Starting ${isStatic ? 'static ' : ''}server in ${serverDist}`));\n\n if (isStatic) {\n await startStaticServerAsync(serverDist, options);\n } else {\n await startDynamicServerAsync(serverDist, options);\n }\n Log.log(`Server running at http://localhost:${options.port}`);\n // Detect the type of server we need to setup:\n}\n\nasync function startStaticServerAsync(dist: string, options: Options) {\n const server = http.createServer((req, res) => {\n // Remove query strings and decode URI\n const filePath = decodeURI(req.url?.split('?')[0] ?? '');\n\n send(req, filePath, {\n root: dist,\n index: 'index.html',\n extensions: ['html'],\n })\n .on('error', (err: any) => {\n if (err.status === 404) {\n res.statusCode = 404;\n res.end('Not Found');\n return;\n }\n res.statusCode = err.status || 500;\n res.end('Internal Server Error');\n })\n .pipe(res);\n });\n\n server.listen(options.port!);\n}\n\nasync function startDynamicServerAsync(dist: string, options: Options) {\n const middleware = connect();\n\n const staticDirectory = path.join(dist, 'client');\n const serverDirectory = path.join(dist, 'server');\n\n const serverHandler = createRequestHandler({ build: serverDirectory });\n\n // DOM component CORS support\n middleware.use((req, res, next) => {\n // TODO: Only when origin is `file://` (iOS), and Android equivalent.\n\n // Required for DOM components security in release builds.\n\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');\n res.setHeader(\n 'Access-Control-Allow-Headers',\n 'Origin, X-Requested-With, Content-Type, Accept, expo-platform'\n );\n\n // Handle OPTIONS preflight requests\n if (req.method === 'OPTIONS') {\n res.statusCode = 200;\n res.end();\n return;\n }\n next();\n });\n\n middleware.use((req, res, next) => {\n if (!req?.url || (req.method !== 'GET' && req.method !== 'HEAD')) {\n return next();\n }\n\n const pathname = canParseURL(req.url) ? new URL(req.url).pathname : req.url;\n if (!pathname) {\n return next();\n }\n\n debug(`Maybe serve static:`, pathname);\n\n const stream = send(req, pathname, {\n root: staticDirectory,\n extensions: ['html'],\n });\n\n // add file listener for fallthrough\n let forwardError = false;\n stream.on('file', function onFile() {\n // once file is determined, always forward error\n forwardError = true;\n });\n\n // forward errors\n stream.on('error', function error(err: any) {\n if (forwardError || !(err.statusCode < 500)) {\n next(err);\n return;\n }\n\n next();\n });\n\n // pipe\n stream.pipe(res);\n });\n\n middleware.use(serverHandler);\n\n middleware.listen(options.port!);\n}\n\nfunction canParseURL(url: string): boolean {\n try {\n // eslint-disable-next-line no-new\n new URL(url);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function isStaticExportAsync(dist: string): Promise<boolean> {\n const routesFile = path.join(dist, `server/_expo/routes.json`);\n return !(await fileExistsAsync(routesFile));\n}\n"],"names":["serveAsync","debug","require","inputDir","options","projectRoot","findUpProjectRootOrAssert","setNodeEnv","load","port","resolvePortAsync","defaultPort","fallbackPort","CommandError","serverDist","isDefaultDirectory","path","join","directoryExistsAsync","isStatic","isStaticExportAsync","Log","log","chalk","dim","startStaticServerAsync","startDynamicServerAsync","dist","server","http","createServer","req","res","filePath","decodeURI","url","split","send","root","index","extensions","on","err","status","statusCode","end","pipe","listen","middleware","connect","staticDirectory","serverDirectory","serverHandler","createRequestHandler","build","use","next","setHeader","method","pathname","canParseURL","URL","stream","forwardError","onFile","error","routesFile","fileExistsAsync"],"mappings":";;;;+BAsBsBA;;;eAAAA;;;;gEAtBJ;;;;;;;gEACE;;;;;;;yBACiB;;;;;;;gEACpB;;;;;;;gEACA;;;;;;;gEACA;;;;;;6DAEI;qBACiC;wBACzB;wBACa;yBACf;sBACM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOjC,MAAMC,QAAQC,QAAQ,SAAS;AAGxB,eAAeF,WAAWG,QAAgB,EAAEC,OAAgB;IACjE,MAAMC,cAAcC,IAAAA,iCAAyB,EAACH;IAE9CI,IAAAA,mBAAU,EAAC;IACXL,QAAQ,aAAaM,IAAI,CAACH;IAE1B,MAAMI,OAAO,MAAMC,IAAAA,sBAAgB,EAACL,aAAa;QAC/CM,aAAaP,QAAQK,IAAI;QACzBG,cAAc;IAChB;IAEA,IAAIH,QAAQ,MAAM;QAChB,MAAM,IAAII,oBAAY,CAAC;IACzB;IACAT,QAAQK,IAAI,GAAGA;IAEf,MAAMK,aAAaV,QAAQW,kBAA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,GAAI;gBAC3CY,KAAKd;gBACL;YACF;YAEAc;QACF;QAEA,OAAO;QACPM,OAAOhB,IAAI,CAACd;IACd;IAEAgB,WAAWO,GAAG,CAACH;IAEfJ,WAAWD,MAAM,CAAC3C,QAAQK,IAAI;AAChC;AAEA,SAASmD,YAAYzB,GAAW;IAC9B,IAAI;QACF,kCAAkC;QAClC,IAAI0B,IAAI1B;QACR,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,eAAef,oBAAoBO,IAAY;IAC7C,MAAMuC,aAAalD,eAAI,CAACC,IAAI,CAACU,MAAM,CAAC,wBAAwB,CAAC;IAC7D,OAAO,CAAE,MAAMwC,IAAAA,oBAAe,EAACD;AACjC"}
|
|
@@ -65,10 +65,6 @@ async function getCombinedKnownVersionsAsync({ projectRoot, sdkVersion, skipCach
|
|
|
65
65
|
if (skipRemoteVersions) {
|
|
66
66
|
_log.Log.warn('Dependency validation might be unreliable when using canary SDK versions');
|
|
67
67
|
}
|
|
68
|
-
if (_env.env.EXPO_NO_DEPENDENCY_VALIDATION) {
|
|
69
|
-
debug('Dependency validation is disabled through EXPO_NO_DEPENDENCY_VALIDATION=1');
|
|
70
|
-
return {};
|
|
71
|
-
}
|
|
72
68
|
const bundledNativeModules = sdkVersion ? await (0, _bundledNativeModules.getVersionedNativeModulesAsync)(projectRoot, sdkVersion, {
|
|
73
69
|
skipRemoteVersions
|
|
74
70
|
}) : {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/doctor/dependencies/getVersionedPackages.ts"],"sourcesContent":["import { PackageJSONConfig } from '@expo/config';\nimport npmPackageArg from 'npm-package-arg';\n\nimport { getVersionedNativeModulesAsync } from './bundledNativeModules';\nimport { hasExpoCanaryAsync } from './resolvePackages';\nimport { getVersionsAsync, SDKVersion } from '../../../api/getVersions';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')(\n 'expo:doctor:dependencies:getVersionedPackages'\n) as typeof console.log;\n\nexport type DependencyList = Record<string, string>;\n\n/** Adds `react-dom`, `react`, and `react-native` to the list of known package versions (`relatedPackages`) */\nfunction normalizeSdkVersionObject(version?: SDKVersion): Record<string, string> {\n if (!version) {\n return {};\n }\n const { relatedPackages, facebookReactVersion, facebookReactNativeVersion, expoVersion } =\n version;\n\n const reactVersion = facebookReactVersion\n ? {\n react: facebookReactVersion,\n 'react-dom': facebookReactVersion,\n }\n : undefined;\n\n const expoVersionIfAvailable = expoVersion ? { expo: expoVersion } : undefined;\n\n return {\n ...relatedPackages,\n ...reactVersion,\n ...expoVersionIfAvailable,\n 'react-native': facebookReactNativeVersion,\n };\n}\n\n/** Get the known versions for a given SDK, combines all sources. */\nexport async function getCombinedKnownVersionsAsync({\n projectRoot,\n sdkVersion,\n skipCache,\n}: {\n projectRoot: string;\n sdkVersion?: string;\n skipCache?: boolean;\n}) {\n const skipRemoteVersions = await hasExpoCanaryAsync(projectRoot);\n if (skipRemoteVersions) {\n Log.warn('Dependency validation might be unreliable when using canary SDK versions');\n }\n\n if (env.EXPO_NO_DEPENDENCY_VALIDATION) {\n debug('Dependency validation is disabled through EXPO_NO_DEPENDENCY_VALIDATION=1');\n return {};\n }\n\n const bundledNativeModules = sdkVersion\n ? await getVersionedNativeModulesAsync(projectRoot, sdkVersion, { skipRemoteVersions })\n : {};\n const versionsForSdk = !skipRemoteVersions\n ? await getRemoteVersionsForSdkAsync({ sdkVersion, skipCache })\n : {};\n return {\n ...bundledNativeModules,\n // Prefer the remote versions over the bundled versions, this enables us to push\n // emergency fixes that users can access without having to update the `expo` package.\n ...versionsForSdk,\n };\n}\n\n/** @returns a key/value list of known dependencies and their version (including range). */\nexport async function getRemoteVersionsForSdkAsync({\n sdkVersion,\n skipCache,\n}: { sdkVersion?: string; skipCache?: boolean } = {}): Promise<DependencyList> {\n if (env.EXPO_OFFLINE) {\n Log.warn('Dependency validation is unreliable in offline-mode');\n return {};\n }\n\n try {\n const { sdkVersions } = await getVersionsAsync({ skipCache });\n\n // We only want versioned dependencies so skip if they cannot be found.\n if (!sdkVersion || !(sdkVersion in sdkVersions)) {\n debug(\n `Skipping versioned dependencies because the SDK version is not found. (sdkVersion: ${sdkVersion}, available: ${Object.keys(\n sdkVersions\n ).join(', ')})`\n );\n return {};\n }\n\n const version = sdkVersions[sdkVersion as keyof typeof sdkVersions] as unknown as SDKVersion;\n\n return normalizeSdkVersionObject(version);\n } catch (error: any) {\n if (error instanceof CommandError && error.code === 'OFFLINE') {\n return getRemoteVersionsForSdkAsync({ sdkVersion, skipCache });\n }\n throw error;\n }\n}\n\ntype ExcludedNativeModules = {\n name: string;\n bundledNativeVersion: string;\n isExcludedFromValidation: boolean;\n specifiedVersion?: string; // e.g. 1.2.3, latest\n};\n\n/**\n * Versions a list of `packages` against a given `sdkVersion` based on local and remote versioning resources.\n *\n * @param projectRoot\n * @param param1\n * @returns\n */\nexport async function getVersionedPackagesAsync(\n projectRoot: string,\n {\n packages,\n sdkVersion,\n pkg,\n }: {\n /** List of npm packages to process. */\n packages: string[];\n /** Target SDK Version number to version the `packages` for. */\n sdkVersion: string;\n pkg: PackageJSONConfig;\n }\n): Promise<{\n packages: string[];\n messages: string[];\n excludedNativeModules: ExcludedNativeModules[];\n}> {\n const versionsForSdk = await getCombinedKnownVersionsAsync({\n projectRoot,\n sdkVersion,\n skipCache: true,\n });\n\n let nativeModulesCount = 0;\n let othersCount = 0;\n const excludedNativeModules: ExcludedNativeModules[] = [];\n\n const versionedPackages = packages.map((arg) => {\n const { name, type, raw, rawSpec } = npmPackageArg(arg);\n\n if (['tag', 'version', 'range'].includes(type) && name && versionsForSdk[name]) {\n // Unimodule packages from npm registry are modified to use the bundled version.\n // Some packages have the recommended version listed in https://exp.host/--/api/v2/versions.\n const isExcludedFromValidation = pkg?.expo?.install?.exclude?.includes(name);\n const hasSpecifiedExactVersion = rawSpec !== '' && rawSpec !== '*';\n if (isExcludedFromValidation || hasSpecifiedExactVersion) {\n othersCount++;\n excludedNativeModules.push({\n name,\n bundledNativeVersion: versionsForSdk[name],\n isExcludedFromValidation,\n specifiedVersion: hasSpecifiedExactVersion ? rawSpec : '',\n });\n return raw;\n }\n nativeModulesCount++;\n return `${name}@${versionsForSdk[name]}`;\n } else {\n // Other packages are passed through unmodified.\n othersCount++;\n return raw;\n }\n });\n\n const messages = getOperationLog({\n othersCount,\n nativeModulesCount,\n sdkVersion,\n });\n\n return {\n packages: versionedPackages,\n messages,\n excludedNativeModules,\n };\n}\n\n/** Craft a set of messages regarding the install operations. */\nexport function getOperationLog({\n nativeModulesCount,\n sdkVersion,\n othersCount,\n}: {\n nativeModulesCount: number;\n othersCount: number;\n sdkVersion: string;\n}): string[] {\n return [\n nativeModulesCount > 0 &&\n `${nativeModulesCount} SDK ${sdkVersion} compatible native ${\n nativeModulesCount === 1 ? 'module' : 'modules'\n }`,\n othersCount > 0 && `${othersCount} other ${othersCount === 1 ? 'package' : 'packages'}`,\n ].filter(Boolean) as string[];\n}\n"],"names":["getCombinedKnownVersionsAsync","getOperationLog","getRemoteVersionsForSdkAsync","getVersionedPackagesAsync","debug","require","normalizeSdkVersionObject","version","relatedPackages","facebookReactVersion","facebookReactNativeVersion","expoVersion","reactVersion","react","undefined","expoVersionIfAvailable","expo","projectRoot","sdkVersion","skipCache","skipRemoteVersions","hasExpoCanaryAsync","Log","warn","env","EXPO_NO_DEPENDENCY_VALIDATION","bundledNativeModules","getVersionedNativeModulesAsync","versionsForSdk","EXPO_OFFLINE","sdkVersions","getVersionsAsync","Object","keys","join","error","CommandError","code","packages","pkg","nativeModulesCount","othersCount","excludedNativeModules","versionedPackages","map","arg","name","type","raw","rawSpec","npmPackageArg","includes","isExcludedFromValidation","install","exclude","hasSpecifiedExactVersion","push","bundledNativeVersion","specifiedVersion","messages","filter","Boolean"],"mappings":";;;;;;;;;;;IA0CsBA,6BAA6B;eAA7BA;;IAsJNC,eAAe;eAAfA;;IApHMC,4BAA4B;eAA5BA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;YAC/D,IAAIG,4BAA4BG,0BAA0B;gBACxDd;gBACAC,sBAAsBc,IAAI,CAAC;oBACzBV;oBACAW,sBAAsB7B,cAAc,CAACkB,KAAK;oBAC1CM;oBACAM,kBAAkBH,2BAA2BN,UAAU;gBACzD;gBACA,OAAOD;YACT;YACAR;YACA,OAAO,GAAGM,KAAK,CAAC,EAAElB,cAAc,CAACkB,KAAK,EAAE;QAC1C,OAAO;YACL,gDAAgD;YAChDL;YACA,OAAOO;QACT;IACF;IAEA,MAAMW,WAAW1D,gBAAgB;QAC/BwC;QACAD;QACAtB;IACF;IAEA,OAAO;QACLoB,UAAUK;QACVgB;QACAjB;IACF;AACF;AAGO,SAASzC,gBAAgB,EAC9BuC,kBAAkB,EAClBtB,UAAU,EACVuB,WAAW,EAKZ;IACC,OAAO;QACLD,qBAAqB,KACnB,GAAGA,mBAAmB,KAAK,EAAEtB,WAAW,mBAAmB,EACzDsB,uBAAuB,IAAI,WAAW,WACtC;QACJC,cAAc,KAAK,GAAGA,YAAY,OAAO,EAAEA,gBAAgB,IAAI,YAAY,YAAY;KACxF,CAACmB,MAAM,CAACC;AACX"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/doctor/dependencies/getVersionedPackages.ts"],"sourcesContent":["import { PackageJSONConfig } from '@expo/config';\nimport npmPackageArg from 'npm-package-arg';\n\nimport { getVersionedNativeModulesAsync } from './bundledNativeModules';\nimport { hasExpoCanaryAsync } from './resolvePackages';\nimport { getVersionsAsync, SDKVersion } from '../../../api/getVersions';\nimport { Log } from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')(\n 'expo:doctor:dependencies:getVersionedPackages'\n) as typeof console.log;\n\nexport type DependencyList = Record<string, string>;\n\n/** Adds `react-dom`, `react`, and `react-native` to the list of known package versions (`relatedPackages`) */\nfunction normalizeSdkVersionObject(version?: SDKVersion): Record<string, string> {\n if (!version) {\n return {};\n }\n const { relatedPackages, facebookReactVersion, facebookReactNativeVersion, expoVersion } =\n version;\n\n const reactVersion = facebookReactVersion\n ? {\n react: facebookReactVersion,\n 'react-dom': facebookReactVersion,\n }\n : undefined;\n\n const expoVersionIfAvailable = expoVersion ? { expo: expoVersion } : undefined;\n\n return {\n ...relatedPackages,\n ...reactVersion,\n ...expoVersionIfAvailable,\n 'react-native': facebookReactNativeVersion,\n };\n}\n\n/** Get the known versions for a given SDK, combines all sources. */\nexport async function getCombinedKnownVersionsAsync({\n projectRoot,\n sdkVersion,\n skipCache,\n}: {\n projectRoot: string;\n sdkVersion?: string;\n skipCache?: boolean;\n}) {\n const skipRemoteVersions = await hasExpoCanaryAsync(projectRoot);\n if (skipRemoteVersions) {\n Log.warn('Dependency validation might be unreliable when using canary SDK versions');\n }\n\n const bundledNativeModules = sdkVersion\n ? await getVersionedNativeModulesAsync(projectRoot, sdkVersion, { skipRemoteVersions })\n : {};\n const versionsForSdk = !skipRemoteVersions\n ? await getRemoteVersionsForSdkAsync({ sdkVersion, skipCache })\n : {};\n return {\n ...bundledNativeModules,\n // Prefer the remote versions over the bundled versions, this enables us to push\n // emergency fixes that users can access without having to update the `expo` package.\n ...versionsForSdk,\n };\n}\n\n/** @returns a key/value list of known dependencies and their version (including range). */\nexport async function getRemoteVersionsForSdkAsync({\n sdkVersion,\n skipCache,\n}: { sdkVersion?: string; skipCache?: boolean } = {}): Promise<DependencyList> {\n if (env.EXPO_OFFLINE) {\n Log.warn('Dependency validation is unreliable in offline-mode');\n return {};\n }\n\n try {\n const { sdkVersions } = await getVersionsAsync({ skipCache });\n\n // We only want versioned dependencies so skip if they cannot be found.\n if (!sdkVersion || !(sdkVersion in sdkVersions)) {\n debug(\n `Skipping versioned dependencies because the SDK version is not found. (sdkVersion: ${sdkVersion}, available: ${Object.keys(\n sdkVersions\n ).join(', ')})`\n );\n return {};\n }\n\n const version = sdkVersions[sdkVersion as keyof typeof sdkVersions] as unknown as SDKVersion;\n\n return normalizeSdkVersionObject(version);\n } catch (error: any) {\n if (error instanceof CommandError && error.code === 'OFFLINE') {\n return getRemoteVersionsForSdkAsync({ sdkVersion, skipCache });\n }\n throw error;\n }\n}\n\ntype ExcludedNativeModules = {\n name: string;\n bundledNativeVersion: string;\n isExcludedFromValidation: boolean;\n specifiedVersion?: string; // e.g. 1.2.3, latest\n};\n\n/**\n * Versions a list of `packages` against a given `sdkVersion` based on local and remote versioning resources.\n *\n * @param projectRoot\n * @param param1\n * @returns\n */\nexport async function getVersionedPackagesAsync(\n projectRoot: string,\n {\n packages,\n sdkVersion,\n pkg,\n }: {\n /** List of npm packages to process. */\n packages: string[];\n /** Target SDK Version number to version the `packages` for. */\n sdkVersion: string;\n pkg: PackageJSONConfig;\n }\n): Promise<{\n packages: string[];\n messages: string[];\n excludedNativeModules: ExcludedNativeModules[];\n}> {\n const versionsForSdk = await getCombinedKnownVersionsAsync({\n projectRoot,\n sdkVersion,\n skipCache: true,\n });\n\n let nativeModulesCount = 0;\n let othersCount = 0;\n const excludedNativeModules: ExcludedNativeModules[] = [];\n\n const versionedPackages = packages.map((arg) => {\n const { name, type, raw, rawSpec } = npmPackageArg(arg);\n\n if (['tag', 'version', 'range'].includes(type) && name && versionsForSdk[name]) {\n // Unimodule packages from npm registry are modified to use the bundled version.\n // Some packages have the recommended version listed in https://exp.host/--/api/v2/versions.\n const isExcludedFromValidation = pkg?.expo?.install?.exclude?.includes(name);\n const hasSpecifiedExactVersion = rawSpec !== '' && rawSpec !== '*';\n if (isExcludedFromValidation || hasSpecifiedExactVersion) {\n othersCount++;\n excludedNativeModules.push({\n name,\n bundledNativeVersion: versionsForSdk[name],\n isExcludedFromValidation,\n specifiedVersion: hasSpecifiedExactVersion ? rawSpec : '',\n });\n return raw;\n }\n nativeModulesCount++;\n return `${name}@${versionsForSdk[name]}`;\n } else {\n // Other packages are passed through unmodified.\n othersCount++;\n return raw;\n }\n });\n\n const messages = getOperationLog({\n othersCount,\n nativeModulesCount,\n sdkVersion,\n });\n\n return {\n packages: versionedPackages,\n messages,\n excludedNativeModules,\n };\n}\n\n/** Craft a set of messages regarding the install operations. */\nexport function getOperationLog({\n nativeModulesCount,\n sdkVersion,\n othersCount,\n}: {\n nativeModulesCount: number;\n othersCount: number;\n sdkVersion: string;\n}): string[] {\n return [\n nativeModulesCount > 0 &&\n `${nativeModulesCount} SDK ${sdkVersion} compatible native ${\n nativeModulesCount === 1 ? 'module' : 'modules'\n }`,\n othersCount > 0 && `${othersCount} other ${othersCount === 1 ? 'package' : 'packages'}`,\n ].filter(Boolean) as string[];\n}\n"],"names":["getCombinedKnownVersionsAsync","getOperationLog","getRemoteVersionsForSdkAsync","getVersionedPackagesAsync","debug","require","normalizeSdkVersionObject","version","relatedPackages","facebookReactVersion","facebookReactNativeVersion","expoVersion","reactVersion","react","undefined","expoVersionIfAvailable","expo","projectRoot","sdkVersion","skipCache","skipRemoteVersions","hasExpoCanaryAsync","Log","warn","bundledNativeModules","getVersionedNativeModulesAsync","versionsForSdk","env","EXPO_OFFLINE","sdkVersions","getVersionsAsync","Object","keys","join","error","CommandError","code","packages","pkg","nativeModulesCount","othersCount","excludedNativeModules","versionedPackages","map","arg","name","type","raw","rawSpec","npmPackageArg","includes","isExcludedFromValidation","install","exclude","hasSpecifiedExactVersion","push","bundledNativeVersion","specifiedVersion","messages","filter","Boolean"],"mappings":";;;;;;;;;;;IA0CsBA,6BAA6B;eAA7BA;;IAiJNC,eAAe;eAAfA;;IApHMC,4BAA4B;eAA5BA;;IA+CAC,yBAAyB;eAAzBA;;;;gEArHI;;;;;;sCAEqB;iCACZ;6BACU;qBACzB;qBACA;wBACS;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SACpB;AAKF,4GAA4G,GAC5G,SAASC,0BAA0BC,OAAoB;IACrD,IAAI,CAACA,SAAS;QACZ,OAAO,CAAC;IACV;IACA,MAAM,EAAEC,eAAe,EAAEC,oBAAoB,EAAEC,0BAA0B,EAAEC,WAAW,EAAE,GACtFJ;IAEF,MAAMK,eAAeH,uBACjB;QACEI,O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AAGO,SAASxC,gBAAgB,EAC9BsC,kBAAkB,EAClBrB,UAAU,EACVsB,WAAW,EAKZ;IACC,OAAO;QACLD,qBAAqB,KACnB,GAAGA,mBAAmB,KAAK,EAAErB,WAAW,mBAAmB,EACzDqB,uBAAuB,IAAI,WAAW,WACtC;QACJC,cAAc,KAAK,GAAGA,YAAY,OAAO,EAAEA,gBAAgB,IAAI,YAAY,YAAY;KACxF,CAACmB,MAAM,CAACC;AACX"}
|
|
@@ -112,6 +112,9 @@ async function validateDependenciesVersionsAsync(projectRoot, exp, pkg, packages
|
|
|
112
112
|
if (_env.env.EXPO_OFFLINE) {
|
|
113
113
|
_log.warn('Skipping dependency validation in offline mode');
|
|
114
114
|
return null;
|
|
115
|
+
} else if (_env.env.EXPO_NO_DEPENDENCY_VALIDATION) {
|
|
116
|
+
debug('Dependency validation is disabled through EXPO_NO_DEPENDENCY_VALIDATION=1');
|
|
117
|
+
return null;
|
|
115
118
|
}
|
|
116
119
|
const incorrectDeps = await getVersionedDependenciesAsync(projectRoot, exp, pkg, packagesToCheck);
|
|
117
120
|
return logIncorrectDependencies(incorrectDeps);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/doctor/dependencies/validateDependenciesVersions.ts"],"sourcesContent":["import { ExpoConfig, PackageJSONConfig } from '@expo/config';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport npmPackageArg from 'npm-package-arg';\nimport semver from 'semver';\nimport semverRangeSubset from 'semver/ranges/subset';\n\nimport { BundledNativeModules } from './bundledNativeModules';\nimport { getCombinedKnownVersionsAsync } from './getVersionedPackages';\nimport { resolveAllPackageVersionsAsync } from './resolvePackages';\nimport * as Log from '../../../log';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:doctor:dependencies:validate') as typeof console.log;\n\ntype IncorrectDependency = {\n packageName: string;\n packageType: 'dependencies' | 'devDependencies';\n expectedVersionOrRange: string;\n actualVersion: string;\n};\n\ntype DependenciesToCheck = { known: string[]; unknown: string[] };\n\n/**\n * Print a list of incorrect dependency versions.\n * This only checks dependencies when not running in offline mode.\n *\n * @param projectRoot Expo project root.\n * @param exp Expo project config.\n * @param pkg Project's `package.json`.\n * @param packagesToCheck A list of packages to check, if undefined or empty, all will be checked.\n * @returns `true` if there are no incorrect dependencies.\n */\nexport async function validateDependenciesVersionsAsync(\n projectRoot: string,\n exp: Pick<ExpoConfig, 'sdkVersion'>,\n pkg: PackageJSONConfig,\n packagesToCheck?: string[]\n): Promise<boolean | null> {\n if (env.EXPO_OFFLINE) {\n Log.warn('Skipping dependency validation in offline mode');\n return null;\n }\n\n const incorrectDeps = await getVersionedDependenciesAsync(projectRoot, exp, pkg, packagesToCheck);\n return logIncorrectDependencies(incorrectDeps);\n}\n\nfunction logInvalidDependency({\n packageName,\n expectedVersionOrRange,\n actualVersion,\n}: IncorrectDependency) {\n Log.warn(\n chalk` {bold ${packageName}}{cyan @}{red ${actualVersion}} - expected version: {green ${expectedVersionOrRange}}`\n );\n}\n\nexport function logIncorrectDependencies(incorrectDeps: IncorrectDependency[]) {\n if (!incorrectDeps.length) {\n return true;\n }\n\n Log.warn(\n chalk`The following packages should be updated for best compatibility with the installed {bold expo} version:`\n );\n incorrectDeps.forEach((dep) => logInvalidDependency(dep));\n\n Log.warn(\n 'Your project may not work correctly until you install the expected versions of the packages.'\n );\n\n return false;\n}\n\n/**\n * Return a list of versioned dependencies for the project SDK version.\n *\n * @param projectRoot Expo project root.\n * @param exp Expo project config.\n * @param pkg Project's `package.json`.\n * @param packagesToCheck A list of packages to check, if undefined or empty, all will be checked.\n * @returns A list of incorrect dependencies.\n */\nexport async function getVersionedDependenciesAsync(\n projectRoot: string,\n exp: Pick<ExpoConfig, 'sdkVersion'>,\n pkg: PackageJSONConfig,\n packagesToCheck?: string[]\n): Promise<IncorrectDependency[]> {\n // This should never happen under normal circumstances since\n // the CLI is versioned in the `expo` package.\n assert(exp.sdkVersion, 'SDK Version is missing');\n\n // Get from both endpoints and combine the known package versions.\n const combinedKnownPackages = await getCombinedKnownVersionsAsync({\n projectRoot,\n sdkVersion: exp.sdkVersion,\n });\n // debug(`Known dependencies: %O`, combinedKnownPackages);\n\n const resolvedDependencies = packagesToCheck?.length\n ? // Diff the provided packages to ensure we only check against installed packages.\n getFilteredObject(packagesToCheck, { ...pkg.dependencies, ...pkg.devDependencies })\n : // If no packages are provided, check against the `package.json` `dependencies` + `devDependencies` object.\n { ...pkg.dependencies, ...pkg.devDependencies };\n debug(`Checking dependencies for ${exp.sdkVersion}: %O`, resolvedDependencies);\n\n // intersection of packages from package.json and bundled native modules\n const { known: resolvedPackagesToCheck, unknown } = getPackagesToCheck(\n combinedKnownPackages,\n resolvedDependencies\n );\n debug(`Comparing known versions: %O`, resolvedPackagesToCheck);\n debug(`Skipping packages that cannot be versioned automatically: %O`, unknown);\n // read package versions from the file system (node_modules)\n const packageVersions = await resolveAllPackageVersionsAsync(\n projectRoot,\n resolvedPackagesToCheck\n );\n debug(`Package versions: %O`, packageVersions);\n // find incorrect dependencies by comparing the actual package versions with the bundled native module version ranges\n let incorrectDeps = findIncorrectDependencies(pkg, packageVersions, combinedKnownPackages);\n debug(`Incorrect dependencies: %O`, incorrectDeps);\n\n if (pkg?.expo?.install?.exclude) {\n const packagesToExclude = pkg.expo.install.exclude;\n\n // Parse the exclude list to ensure we can factor in any specified version ranges\n const parsedPackagesToExclude = packagesToExclude.reduce(\n (acc: Record<string, npmPackageArg.Result>, packageName: string) => {\n const npaResult = npmPackageArg(packageName);\n if (typeof npaResult.name === 'string') {\n acc[npaResult.name] = npaResult;\n } else {\n acc[packageName] = npaResult;\n }\n return acc;\n },\n {}\n );\n\n const incorrectAndExcludedDeps = incorrectDeps\n .filter((dep) => {\n if (parsedPackagesToExclude[dep.packageName]) {\n const { name, raw, rawSpec, type } = parsedPackagesToExclude[dep.packageName];\n const suggestedRange = combinedKnownPackages[name];\n\n // If only the package name itself is specified, then we keep it in the exclude list\n if (name === raw) {\n return true;\n } else if (type === 'version') {\n return suggestedRange === rawSpec;\n } else if (type === 'range') {\n // Fall through exclusions if the suggested range is invalid\n if (!semver.validRange(suggestedRange)) {\n debug(\n `Invalid semver range in combined known packages for package ${name} in expo.install.exclude: %O`,\n suggestedRange\n );\n return false;\n }\n\n return semverRangeSubset(suggestedRange, rawSpec);\n } else {\n debug(\n `Unsupported npm package argument type for package ${name} in expo.install.exclude: %O`,\n type\n );\n }\n }\n\n return false;\n })\n .map((dep) => dep.packageName);\n\n debug(\n `Incorrect dependency warnings filtered out by expo.install.exclude: %O`,\n incorrectAndExcludedDeps\n );\n incorrectDeps = incorrectDeps.filter(\n (dep) => !incorrectAndExcludedDeps.includes(dep.packageName)\n );\n }\n\n return incorrectDeps;\n}\n\nfunction getFilteredObject(keys: string[], object: Record<string, string>) {\n return keys.reduce<Record<string, string>>((acc, key) => {\n acc[key] = object[key];\n return acc;\n }, {});\n}\n\nfunction getPackagesToCheck(\n bundledNativeModules: BundledNativeModules,\n dependencies?: Record<string, string> | null\n): DependenciesToCheck {\n const dependencyNames = Object.keys(dependencies ?? {});\n const known: string[] = [];\n const unknown: string[] = [];\n for (const dependencyName of dependencyNames) {\n if (dependencyName in bundledNativeModules) {\n known.push(dependencyName);\n } else {\n unknown.push(dependencyName);\n }\n }\n return { known, unknown };\n}\n\nfunction findIncorrectDependencies(\n pkg: PackageJSONConfig,\n packageVersions: Record<string, string>,\n bundledNativeModules: BundledNativeModules\n): IncorrectDependency[] {\n const packages = Object.keys(packageVersions);\n const incorrectDeps: IncorrectDependency[] = [];\n for (const packageName of packages) {\n const expectedVersionOrRange = bundledNativeModules[packageName];\n const actualVersion = packageVersions[packageName];\n if (isDependencyVersionIncorrect(packageName, actualVersion, expectedVersionOrRange)) {\n incorrectDeps.push({\n packageName,\n packageType: findDependencyType(pkg, packageName),\n expectedVersionOrRange,\n actualVersion,\n });\n }\n }\n return incorrectDeps;\n}\n\nexport function isDependencyVersionIncorrect(\n packageName: string,\n actualVersion: string,\n expectedVersionOrRange?: string\n) {\n if (!expectedVersionOrRange) {\n return false;\n }\n\n // we never want to go backwards with the expo patch version\n if (packageName === 'expo') {\n return semver.ltr(actualVersion, expectedVersionOrRange);\n }\n\n // For all other packages, check if the actual version satisfies the expected range\n const satisfies = semver.satisfies(actualVersion, expectedVersionOrRange, {\n includePrerelease: true,\n });\n\n return !satisfies;\n}\n\nfunction findDependencyType(\n pkg: PackageJSONConfig,\n packageName: string\n): IncorrectDependency['packageType'] {\n if (pkg.devDependencies && packageName in pkg.devDependencies) {\n return 'devDependencies';\n }\n\n return 'dependencies';\n}\n"],"names":["getVersionedDependenciesAsync","isDependencyVersionIncorrect","logIncorrectDependencies","validateDependenciesVersionsAsync","debug","require","projectRoot","exp","pkg","packagesToCheck","env","EXPO_OFFLINE","Log","warn","incorrectDeps","logInvalidDependency","packageName","expectedVersionOrRange","actualVersion","chalk","length","forEach","dep","assert","sdkVersion","combinedKnownPackages","getCombinedKnownVersionsAsync","resolvedDependencies","getFilteredObject","dependencies","devDependencies","known","resolvedPackagesToCheck","unknown","getPackagesToCheck","packageVersions","resolveAllPackageVersionsAsync","findIncorrectDependencies","expo","install","exclude","packagesToExclude","parsedPackagesToExclude","reduce","acc","npaResult","npmPackageArg","name","incorrectAndExcludedDeps","filter","raw","rawSpec","type","suggestedRange","semver","validRange","semverRangeSubset","map","includes","keys","object","key","bundledNativeModules","dependencyNames","Object","dependencyName","push","packages","packageType","findDependencyType","ltr","satisfies","includePrerelease"],"mappings":";;;;;;;;;;;IAqFsBA,6BAA6B;eAA7BA;;IAsJNC,4BAA4B;eAA5BA;;IAhLAC,wBAAwB;eAAxBA;;IAzBMC,iCAAiC;eAAjCA;;;;gEAjCH;;;;;;;gEACD;;;;;;;gEACQ;;;;;;;gEACP;;;;;;;gEACW;;;;;;sCAGgB;iCACC;6DAC1B;qBACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpB,MAAMC,QAAQC,QAAQ,SAAS;AAqBx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1C,MAAMK,WAAWH,OAAOL,IAAI,CAACxB;IAC7B,MAAMrB,gBAAuC,EAAE;IAC/C,KAAK,MAAME,eAAemD,SAAU;QAClC,MAAMlD,yBAAyB6C,oBAAoB,CAAC9C,YAAY;QAChE,MAAME,gBAAgBiB,eAAe,CAACnB,YAAY;QAClD,IAAIf,6BAA6Be,aAAaE,eAAeD,yBAAyB;YACpFH,cAAcoD,IAAI,CAAC;gBACjBlD;gBACAoD,aAAaC,mBAAmB7D,KAAKQ;gBACrCC;gBACAC;YACF;QACF;IACF;IACA,OAAOJ;AACT;AAEO,SAASb,6BACde,WAAmB,EACnBE,aAAqB,EACrBD,sBAA+B;IAE/B,IAAI,CAACA,wBAAwB;QAC3B,OAAO;IACT;IAEA,4DAA4D;IAC5D,IAAID,gBAAgB,QAAQ;QAC1B,OAAOsC,iBAAM,CAACgB,GAAG,CAACpD,eAAeD;IACnC;IAEA,mFAAmF;IACnF,MAAMsD,YAAYjB,iBAAM,CAACiB,SAAS,CAACrD,eAAeD,wBAAwB;QACxEuD,mBAAmB;IACrB;IAEA,OAAO,CAACD;AACV;AAEA,SAASF,mBACP7D,GAAsB,EACtBQ,WAAmB;IAEnB,IAAIR,IAAIsB,eAAe,IAAId,eAAeR,IAAIsB,eAAe,EAAE;QAC7D,OAAO;IACT;IAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/doctor/dependencies/validateDependenciesVersions.ts"],"sourcesContent":["import { ExpoConfig, PackageJSONConfig } from '@expo/config';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport npmPackageArg from 'npm-package-arg';\nimport semver from 'semver';\nimport semverRangeSubset from 'semver/ranges/subset';\n\nimport { BundledNativeModules } from './bundledNativeModules';\nimport { getCombinedKnownVersionsAsync } from './getVersionedPackages';\nimport { resolveAllPackageVersionsAsync } from './resolvePackages';\nimport * as Log from '../../../log';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:doctor:dependencies:validate') as typeof console.log;\n\ntype IncorrectDependency = {\n packageName: string;\n packageType: 'dependencies' | 'devDependencies';\n expectedVersionOrRange: string;\n actualVersion: string;\n};\n\ntype DependenciesToCheck = { known: string[]; unknown: string[] };\n\n/**\n * Print a list of incorrect dependency versions.\n * This only checks dependencies when not running in offline mode.\n *\n * @param projectRoot Expo project root.\n * @param exp Expo project config.\n * @param pkg Project's `package.json`.\n * @param packagesToCheck A list of packages to check, if undefined or empty, all will be checked.\n * @returns `true` if there are no incorrect dependencies.\n */\nexport async function validateDependenciesVersionsAsync(\n projectRoot: string,\n exp: Pick<ExpoConfig, 'sdkVersion'>,\n pkg: PackageJSONConfig,\n packagesToCheck?: string[]\n): Promise<boolean | null> {\n if (env.EXPO_OFFLINE) {\n Log.warn('Skipping dependency validation in offline mode');\n return null;\n } else if (env.EXPO_NO_DEPENDENCY_VALIDATION) {\n debug('Dependency validation is disabled through EXPO_NO_DEPENDENCY_VALIDATION=1');\n return null;\n }\n\n const incorrectDeps = await getVersionedDependenciesAsync(projectRoot, exp, pkg, packagesToCheck);\n return logIncorrectDependencies(incorrectDeps);\n}\n\nfunction logInvalidDependency({\n packageName,\n expectedVersionOrRange,\n actualVersion,\n}: IncorrectDependency) {\n Log.warn(\n chalk` {bold ${packageName}}{cyan @}{red ${actualVersion}} - expected version: {green ${expectedVersionOrRange}}`\n );\n}\n\nexport function logIncorrectDependencies(incorrectDeps: IncorrectDependency[]) {\n if (!incorrectDeps.length) {\n return true;\n }\n\n Log.warn(\n chalk`The following packages should be updated for best compatibility with the installed {bold expo} version:`\n );\n incorrectDeps.forEach((dep) => logInvalidDependency(dep));\n\n Log.warn(\n 'Your project may not work correctly until you install the expected versions of the packages.'\n );\n\n return false;\n}\n\n/**\n * Return a list of versioned dependencies for the project SDK version.\n *\n * @param projectRoot Expo project root.\n * @param exp Expo project config.\n * @param pkg Project's `package.json`.\n * @param packagesToCheck A list of packages to check, if undefined or empty, all will be checked.\n * @returns A list of incorrect dependencies.\n */\nexport async function getVersionedDependenciesAsync(\n projectRoot: string,\n exp: Pick<ExpoConfig, 'sdkVersion'>,\n pkg: PackageJSONConfig,\n packagesToCheck?: string[]\n): Promise<IncorrectDependency[]> {\n // This should never happen under normal circumstances since\n // the CLI is versioned in the `expo` package.\n assert(exp.sdkVersion, 'SDK Version is missing');\n\n // Get from both endpoints and combine the known package versions.\n const combinedKnownPackages = await getCombinedKnownVersionsAsync({\n projectRoot,\n sdkVersion: exp.sdkVersion,\n });\n // debug(`Known dependencies: %O`, combinedKnownPackages);\n\n const resolvedDependencies = packagesToCheck?.length\n ? // Diff the provided packages to ensure we only check against installed packages.\n getFilteredObject(packagesToCheck, { ...pkg.dependencies, ...pkg.devDependencies })\n : // If no packages are provided, check against the `package.json` `dependencies` + `devDependencies` object.\n { ...pkg.dependencies, ...pkg.devDependencies };\n debug(`Checking dependencies for ${exp.sdkVersion}: %O`, resolvedDependencies);\n\n // intersection of packages from package.json and bundled native modules\n const { known: resolvedPackagesToCheck, unknown } = getPackagesToCheck(\n combinedKnownPackages,\n resolvedDependencies\n );\n debug(`Comparing known versions: %O`, resolvedPackagesToCheck);\n debug(`Skipping packages that cannot be versioned automatically: %O`, unknown);\n // read package versions from the file system (node_modules)\n const packageVersions = await resolveAllPackageVersionsAsync(\n projectRoot,\n resolvedPackagesToCheck\n );\n debug(`Package versions: %O`, packageVersions);\n // find incorrect dependencies by comparing the actual package versions with the bundled native module version ranges\n let incorrectDeps = findIncorrectDependencies(pkg, packageVersions, combinedKnownPackages);\n debug(`Incorrect dependencies: %O`, incorrectDeps);\n\n if (pkg?.expo?.install?.exclude) {\n const packagesToExclude = pkg.expo.install.exclude;\n\n // Parse the exclude list to ensure we can factor in any specified version ranges\n const parsedPackagesToExclude = packagesToExclude.reduce(\n (acc: Record<string, npmPackageArg.Result>, packageName: string) => {\n const npaResult = npmPackageArg(packageName);\n if (typeof npaResult.name === 'string') {\n acc[npaResult.name] = npaResult;\n } else {\n acc[packageName] = npaResult;\n }\n return acc;\n },\n {}\n );\n\n const incorrectAndExcludedDeps = incorrectDeps\n .filter((dep) => {\n if (parsedPackagesToExclude[dep.packageName]) {\n const { name, raw, rawSpec, type } = parsedPackagesToExclude[dep.packageName];\n const suggestedRange = combinedKnownPackages[name];\n\n // If only the package name itself is specified, then we keep it in the exclude list\n if (name === raw) {\n return true;\n } else if (type === 'version') {\n return suggestedRange === rawSpec;\n } else if (type === 'range') {\n // Fall through exclusions if the suggested range is invalid\n if (!semver.validRange(suggestedRange)) {\n debug(\n `Invalid semver range in combined known packages for package ${name} in expo.install.exclude: %O`,\n suggestedRange\n );\n return false;\n }\n\n return semverRangeSubset(suggestedRange, rawSpec);\n } else {\n debug(\n `Unsupported npm package argument type for package ${name} in expo.install.exclude: %O`,\n type\n );\n }\n }\n\n return false;\n })\n .map((dep) => dep.packageName);\n\n debug(\n `Incorrect dependency warnings filtered out by expo.install.exclude: %O`,\n incorrectAndExcludedDeps\n );\n incorrectDeps = incorrectDeps.filter(\n (dep) => !incorrectAndExcludedDeps.includes(dep.packageName)\n );\n }\n\n return incorrectDeps;\n}\n\nfunction getFilteredObject(keys: string[], object: Record<string, string>) {\n return keys.reduce<Record<string, string>>((acc, key) => {\n acc[key] = object[key];\n return acc;\n }, {});\n}\n\nfunction getPackagesToCheck(\n bundledNativeModules: BundledNativeModules,\n dependencies?: Record<string, string> | null\n): DependenciesToCheck {\n const dependencyNames = Object.keys(dependencies ?? {});\n const known: string[] = [];\n const unknown: string[] = [];\n for (const dependencyName of dependencyNames) {\n if (dependencyName in bundledNativeModules) {\n known.push(dependencyName);\n } else {\n unknown.push(dependencyName);\n }\n }\n return { known, unknown };\n}\n\nfunction findIncorrectDependencies(\n pkg: PackageJSONConfig,\n packageVersions: Record<string, string>,\n bundledNativeModules: BundledNativeModules\n): IncorrectDependency[] {\n const packages = Object.keys(packageVersions);\n const incorrectDeps: IncorrectDependency[] = [];\n for (const packageName of packages) {\n const expectedVersionOrRange = bundledNativeModules[packageName];\n const actualVersion = packageVersions[packageName];\n if (isDependencyVersionIncorrect(packageName, actualVersion, expectedVersionOrRange)) {\n incorrectDeps.push({\n packageName,\n packageType: findDependencyType(pkg, packageName),\n expectedVersionOrRange,\n actualVersion,\n });\n }\n }\n return incorrectDeps;\n}\n\nexport function isDependencyVersionIncorrect(\n packageName: string,\n actualVersion: string,\n expectedVersionOrRange?: string\n) {\n if (!expectedVersionOrRange) {\n return false;\n }\n\n // we never want to go backwards with the expo patch version\n if (packageName === 'expo') {\n return semver.ltr(actualVersion, expectedVersionOrRange);\n }\n\n // For all other packages, check if the actual version satisfies the expected range\n const satisfies = semver.satisfies(actualVersion, expectedVersionOrRange, {\n includePrerelease: true,\n });\n\n return !satisfies;\n}\n\nfunction findDependencyType(\n pkg: PackageJSONConfig,\n packageName: string\n): IncorrectDependency['packageType'] {\n if (pkg.devDependencies && packageName in pkg.devDependencies) {\n return 'devDependencies';\n }\n\n return 'dependencies';\n}\n"],"names":["getVersionedDependenciesAsync","isDependencyVersionIncorrect","logIncorrectDependencies","validateDependenciesVersionsAsync","debug","require","projectRoot","exp","pkg","packagesToCheck","env","EXPO_OFFLINE","Log","warn","EXPO_NO_DEPENDENCY_VALIDATION","incorrectDeps","logInvalidDependency","packageName","expectedVersionOrRange","actualVersion","chalk","length","forEach","dep","assert","sdkVersion","combinedKnownPackages","getCombinedKnownVersionsAsync","resolvedDependencies","getFilteredObject","dependencies","devDependencies","known","resolvedPackagesToCheck","unknown","getPackagesToCheck","packageVersions","resolveAllPackageVersionsAsync","findIncorrectDependencies","expo","install","exclude","packagesToExclude","parsedPackagesToExclude","reduce","acc","npaResult","npmPackageArg","name","incorrectAndExcludedDeps","filter","raw","rawSpec","type","suggestedRange","semver","validRange","semverRangeSubset","map","includes","keys","object","key","bundledNativeModules","dependencyNames","Object","dependencyName","push","packages","packageType","findDependencyType","ltr","satisfies","includePrerelease"],"mappings":";;;;;;;;;;;IAwFsBA,6BAA6B;eAA7BA;;IAsJNC,4BAA4B;eAA5BA;;IAhLAC,wBAAwB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
32
|
-
const data = require("
|
|
33
|
-
|
|
31
|
+
function _assert() {
|
|
32
|
+
const data = /*#__PURE__*/ _interop_require_default(require("assert"));
|
|
33
|
+
_assert = function() {
|
|
34
34
|
return data;
|
|
35
35
|
};
|
|
36
36
|
return data;
|
|
37
37
|
}
|
|
38
|
-
function
|
|
39
|
-
const data =
|
|
40
|
-
|
|
38
|
+
function _private() {
|
|
39
|
+
const data = require("expo-server/private");
|
|
40
|
+
_private = function() {
|
|
41
41
|
return data;
|
|
42
42
|
};
|
|
43
43
|
return data;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport { getRscMiddleware } from '@expo/server/private';\nimport assert from 'assert';\nimport type { EntriesDev } from 'expo-router/build/rsc/server';\nimport path from 'path';\nimport url from 'url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? 'expo-router/build/rsc/router/noopRouter'\n : 'expo-router/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('expo-router/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\n );\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\n );\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAomBHC,iBAAiB;eAAjBA;;;;yBA1oBsB;;;;;;;yBAEF;;;;;;;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,E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D;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createServerComponentsMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { getMetroServerRoot } from '@expo/config/paths';\nimport type { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport type { EntriesDev } from 'expo-router/build/rsc/server';\nimport { getRscMiddleware } from 'expo-server/private';\nimport path from 'path';\nimport url from 'url';\n\nimport { IS_METRO_BUNDLE_ERROR_SYMBOL, logMetroError } from './metroErrorInterface';\nimport { isPossiblyUnableToResolveError } from '../../../export/embed/xcodeCompilerLogger';\nimport type { ExportAssetMap } from '../../../export/saveAssets';\nimport { stripAnsi } from '../../../utils/ansi';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { memoize } from '../../../utils/fn';\nimport { getIpAddress } from '../../../utils/ip';\nimport { streamToStringAsync } from '../../../utils/stream';\nimport { createBuiltinAPIRequestHandler } from '../middleware/createBuiltinAPIRequestHandler';\nimport {\n createBundleUrlSearchParams,\n type ExpoMetroOptions,\n getMetroOptionsFromUrl,\n} from '../middleware/metroOptions';\n\nconst debug = require('debug')('expo:rsc') as typeof console.log;\n\ntype SSRLoadModuleArtifactsFunc = (\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>\n) => Promise<{ artifacts: SerialAsset[]; src: string }>;\n\ntype SSRLoadModuleFunc = <T extends Record<string, any>>(\n filePath: string,\n specificOptions?: Partial<ExpoMetroOptions>,\n extras?: { hot?: boolean }\n) => Promise<T>;\n\nconst getMetroServerRootMemo = memoize(getMetroServerRoot);\n\nexport function createServerComponentsMiddleware(\n projectRoot: string,\n {\n rscPath,\n instanceMetroOptions,\n ssrLoadModule,\n ssrLoadModuleArtifacts,\n useClientRouter,\n createModuleId,\n routerOptions,\n }: {\n rscPath: string;\n instanceMetroOptions: Partial<ExpoMetroOptions>;\n ssrLoadModule: SSRLoadModuleFunc;\n ssrLoadModuleArtifacts: SSRLoadModuleArtifactsFunc;\n useClientRouter: boolean;\n createModuleId: (\n filePath: string,\n context: { platform: string; environment: string }\n ) => string | number;\n routerOptions: Record<string, any>;\n }\n) {\n const routerModule = useClientRouter\n ? 'expo-router/build/rsc/router/noopRouter'\n : 'expo-router/build/rsc/router/expo-definedRouter';\n\n const rscMiddleware = getRscMiddleware({\n config: {},\n // Disabled in development\n baseUrl: '',\n rscPath,\n onError: console.error,\n renderRsc: async (args) => {\n // In development we should add simulated versions of common production headers.\n if (args.headers['x-real-ip'] == null) {\n args.headers['x-real-ip'] = getIpAddress();\n }\n if (args.headers['x-forwarded-for'] == null) {\n args.headers['x-forwarded-for'] = args.headers['x-real-ip'];\n }\n if (args.headers['x-forwarded-proto'] == null) {\n args.headers['x-forwarded-proto'] = 'http';\n }\n\n // Dev server-only implementation.\n try {\n return await renderRscToReadableStream({\n ...args,\n headers: new Headers(args.headers),\n body: args.body!,\n routerOptions,\n });\n } catch (error: any) {\n // If you get a codeFrame error during SSR like when using a Class component in React Server Components, then this\n // will throw with:\n // {\n // rawObject: {\n // type: 'TransformError',\n // lineNumber: 0,\n // errors: [ [Object] ],\n // name: 'SyntaxError',\n // message: '...',\n // }\n // }\n\n // TODO: Revisit all error handling now that we do direct metro bundling...\n await logMetroError(projectRoot, { error });\n\n if (error[IS_METRO_BUNDLE_ERROR_SYMBOL]) {\n throw new Response(JSON.stringify(error), {\n status: isPossiblyUnableToResolveError(error) ? 404 : 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n }\n\n const sanitizedServerMessage = stripAnsi(error.message) ?? error.message;\n throw new Response(sanitizedServerMessage, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n }\n },\n });\n\n let rscPathPrefix = rscPath;\n if (rscPathPrefix !== '/') {\n rscPathPrefix += '/';\n }\n\n async function exportServerActionsAsync(\n {\n platform,\n entryPoints,\n domRoot,\n }: { platform: string; entryPoints: string[]; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n clientBoundaries: string[];\n manifest: Record<string, [string, string]>;\n }> {\n const uniqueEntryPoints = [...new Set(entryPoints)];\n // TODO: Support multiple entry points in a single split server bundle...\n const manifest: Record<string, [string, string]> = {};\n const nestedClientBoundaries: string[] = [];\n const nestedServerBoundaries: string[] = [];\n const processedEntryPoints = new Set<string>();\n async function processEntryPoint(entryPoint: string) {\n processedEntryPoints.add(entryPoint);\n\n const contents = await ssrLoadModuleArtifacts(entryPoint, {\n environment: 'react-server',\n platform,\n // Ignore the metro runtime to avoid overwriting the original in the API route.\n modulesOnly: true,\n // Required\n runModule: true,\n // Required to ensure assets load as client boundaries.\n domRoot,\n });\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactClientReferences) {\n nestedClientBoundaries.push(...reactClientReferences!);\n }\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (reactServerReferences) {\n nestedServerBoundaries.push(...reactServerReferences!);\n }\n\n // Naive check to ensure the module runtime is not included in the server action bundle.\n if (contents.src.includes('The experimental Metro feature')) {\n throw new Error(\n 'Internal error: module runtime should not be included in server action bundles: ' +\n entryPoint\n );\n }\n\n const relativeName = createModuleId(entryPoint, {\n platform,\n environment: 'react-server',\n });\n const safeName = path.basename(contents.artifacts.find((a) => a.type === 'js')!.filename!);\n\n const outputName = `_expo/rsc/${platform}/${safeName}`;\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(outputName, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n // Match babel plugin.\n const publicModuleId = './' + toPosixPath(path.relative(projectRoot, entryPoint));\n\n // Import relative to `dist/server/_expo/rsc/web/router.js`\n manifest[publicModuleId] = [String(relativeName), outputName];\n }\n\n async function processEntryPoints(entryPoints: string[], recursions = 0) {\n // Arbitrary recursion limit to prevent infinite loops.\n if (recursions > 10) {\n throw new Error('Recursion limit exceeded while processing server boundaries');\n }\n\n for (const entryPoint of entryPoints) {\n await processEntryPoint(entryPoint);\n }\n\n // When a server action has other server actions inside of it, we need to process those as well to ensure all entry points are in the manifest and accounted for.\n let uniqueNestedServerBoundaries = [...new Set(nestedServerBoundaries)];\n // Filter out values that have already been processed.\n uniqueNestedServerBoundaries = uniqueNestedServerBoundaries.filter(\n (value) => !processedEntryPoints.has(value)\n );\n if (uniqueNestedServerBoundaries.length) {\n debug('bundling nested server action boundaries', uniqueNestedServerBoundaries);\n return processEntryPoints(uniqueNestedServerBoundaries, recursions + 1);\n }\n }\n\n await processEntryPoints(uniqueEntryPoints);\n\n // Save the SSR manifest so we can perform more replacements in the server renderer and with server actions.\n files.set(`_expo/rsc/${platform}/action-manifest.js`, {\n targetDomain: 'server',\n contents: 'module.exports = ' + JSON.stringify(manifest),\n });\n\n return { manifest, clientBoundaries: nestedClientBoundaries };\n }\n\n async function getExpoRouterClientReferencesAsync(\n { platform, domRoot }: { platform: string; domRoot?: string },\n files: ExportAssetMap\n ): Promise<{\n reactClientReferences: string[];\n reactServerReferences: string[];\n cssModules: SerialAsset[];\n }> {\n const contents = await ssrLoadModuleArtifacts(routerModule, {\n environment: 'react-server',\n platform,\n modulesOnly: true,\n domRoot,\n });\n\n // Extract the global CSS modules that are imported from the router.\n // These will be injected in the head of the HTML document for the website.\n const cssModules = contents.artifacts.filter((a) => a.type.startsWith('css'));\n\n const reactServerReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactServerReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactServerReferences) {\n throw new Error(\n 'Static server action references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactServerReferences);\n\n const reactClientReferences = contents.artifacts\n .filter((a) => a.type === 'js')[0]\n .metadata.reactClientReferences?.map((ref) => fileURLToFilePath(ref));\n\n if (!reactClientReferences) {\n throw new Error(\n 'Static client references were not returned from the Metro SSR bundle for definedRouter'\n );\n }\n debug('React client boundaries:', reactClientReferences);\n\n // While we're here, export the router for the server to dynamically render RSC.\n files.set(`_expo/rsc/${platform}/router.js`, {\n targetDomain: 'server',\n contents: wrapBundle(contents.src),\n });\n\n return { reactClientReferences, reactServerReferences, cssModules };\n }\n\n const routerCache = new Map<string, EntriesDev>();\n\n async function getExpoRouterRscEntriesGetterAsync({\n platform,\n routerOptions,\n }: {\n platform: string;\n routerOptions: Record<string, any>;\n }) {\n await ensureMemo();\n // We can only cache this if we're using the client router since it doesn't change or use HMR\n if (routerCache.has(platform) && useClientRouter) {\n return routerCache.get(platform)!;\n }\n\n const router = await ssrLoadModule<\n typeof import('expo-router/build/rsc/router/expo-definedRouter')\n >(\n routerModule,\n {\n environment: 'react-server',\n modulesOnly: true,\n platform,\n },\n {\n hot: !useClientRouter,\n }\n );\n\n const entries = router.default({\n redirects: routerOptions?.redirects,\n rewrites: routerOptions?.rewrites,\n });\n\n routerCache.set(platform, entries);\n return entries;\n }\n\n function getResolveClientEntry(context: {\n platform: string;\n engine?: 'hermes' | null;\n ssrManifest?: Map<string, string>;\n }): (\n file: string,\n isServer: boolean\n ) => {\n id: string;\n chunks: string[];\n } {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n const {\n mode,\n minify = false,\n isExporting,\n baseUrl,\n routerRoot,\n asyncRoutes,\n preserveEnvVars,\n reactCompiler,\n lazy,\n } = instanceMetroOptions;\n\n assert(\n isExporting != null &&\n baseUrl != null &&\n mode != null &&\n routerRoot != null &&\n asyncRoutes != null,\n `The server must be started. (isExporting: ${isExporting}, baseUrl: ${baseUrl}, mode: ${mode}, routerRoot: ${routerRoot}, asyncRoutes: ${asyncRoutes})`\n );\n\n return (file: string, isServer: boolean) => {\n const filePath = path.join(\n projectRoot,\n file.startsWith('file://') ? fileURLToFilePath(file) : file\n );\n\n if (isExporting) {\n assert(context.ssrManifest, 'SSR manifest must exist when exporting');\n\n const relativeFilePath = toPosixPath(path.relative(serverRoot, filePath));\n\n assert(\n context.ssrManifest.has(relativeFilePath),\n `SSR manifest is missing client boundary \"${relativeFilePath}\"`\n );\n\n const chunk = context.ssrManifest.get(relativeFilePath);\n\n return {\n id: String(\n createModuleId(filePath, { platform: context.platform, environment: 'client' })\n ),\n chunks: chunk != null ? [chunk] : [],\n };\n }\n\n const environment = isServer ? 'react-server' : 'client';\n const searchParams = createBundleUrlSearchParams({\n mainModuleName: '',\n platform: context.platform,\n mode,\n minify,\n lazy,\n preserveEnvVars,\n asyncRoutes,\n baseUrl,\n routerRoot,\n isExporting,\n reactCompiler: !!reactCompiler,\n engine: context.engine ?? undefined,\n bytecode: false,\n clientBoundaries: [],\n inlineSourceMap: false,\n environment,\n modulesOnly: true,\n runModule: false,\n });\n\n searchParams.set('resolver.clientboundary', String(true));\n\n const clientReferenceUrl = new URL('http://a');\n\n // TICKLE: Handshake 1\n searchParams.set('xRSC', '1');\n\n clientReferenceUrl.search = searchParams.toString();\n\n const relativeFilePath = path.relative(serverRoot, filePath);\n\n clientReferenceUrl.pathname = relativeFilePath;\n\n // Ensure url.pathname ends with '.bundle'\n if (!clientReferenceUrl.pathname.endsWith('.bundle')) {\n clientReferenceUrl.pathname += '.bundle';\n }\n\n // Return relative URLs to help Android fetch from wherever it was loaded from since it doesn't support localhost.\n const chunkName = clientReferenceUrl.pathname + clientReferenceUrl.search;\n\n return {\n id: String(createModuleId(filePath, { platform: context.platform, environment })),\n chunks: [chunkName],\n };\n };\n }\n\n const rscRendererCache = new Map<string, typeof import('expo-router/build/rsc/rsc-renderer')>();\n\n let ensurePromise: Promise<any> | null = null;\n async function ensureSSRReady() {\n // TODO: Extract CSS Modules / Assets from the bundler process\n const runtime = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'metro-runtime/src/modules/empty-module.js',\n {\n environment: 'react-server',\n platform: 'web',\n }\n );\n return runtime;\n }\n const ensureMemo = () => {\n ensurePromise ??= ensureSSRReady();\n return ensurePromise;\n };\n\n async function getRscRendererAsync(platform: string) {\n await ensureMemo();\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRendererCache.has(platform)) {\n return rscRendererCache.get(platform)!;\n }\n\n // TODO: Extract CSS Modules / Assets from the bundler process\n const renderer = await ssrLoadModule<typeof import('expo-router/build/rsc/rsc-renderer')>(\n 'expo-router/build/rsc/rsc-renderer',\n {\n environment: 'react-server',\n platform,\n }\n );\n\n rscRendererCache.set(platform, renderer);\n return renderer;\n }\n\n const rscRenderContext = new Map<string, any>();\n\n function getRscRenderContext(platform: string) {\n // NOTE(EvanBacon): We memoize this now that there's a persistent server storage cache for Server Actions.\n if (rscRenderContext.has(platform)) {\n return rscRenderContext.get(platform)!;\n }\n\n const context = {};\n\n rscRenderContext.set(platform, context);\n return context;\n }\n\n async function renderRscToReadableStream(\n {\n input,\n headers,\n method,\n platform,\n body,\n engine,\n contentType,\n ssrManifest,\n decodedBody,\n routerOptions,\n }: {\n input: string;\n headers: Headers;\n method: 'POST' | 'GET';\n platform: string;\n body?: ReadableStream<Uint8Array>;\n engine?: 'hermes' | null;\n contentType?: string;\n ssrManifest?: Map<string, string>;\n decodedBody?: unknown;\n routerOptions: Record<string, any>;\n },\n isExporting: boolean | undefined = instanceMetroOptions.isExporting\n ) {\n assert(\n isExporting != null,\n 'The server must be started before calling renderRscToReadableStream.'\n );\n\n if (method === 'POST') {\n assert(body, 'Server request must be provided when method is POST (server actions)');\n }\n\n const context = getRscRenderContext(platform);\n\n context['__expo_requestHeaders'] = headers;\n\n const { renderRsc } = await getRscRendererAsync(platform);\n\n return renderRsc(\n {\n body,\n decodedBody,\n context,\n config: {},\n input,\n contentType,\n },\n {\n isExporting,\n entries: await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions }),\n resolveClientEntry: getResolveClientEntry({ platform, engine, ssrManifest }),\n async loadServerModuleRsc(urlFragment) {\n const serverRoot = getMetroServerRootMemo(projectRoot);\n\n debug('[SSR] loadServerModuleRsc:', urlFragment);\n\n const options = getMetroOptionsFromUrl(urlFragment);\n\n return ssrLoadModule(\n path.join(serverRoot, options.mainModuleName),\n\n options,\n {\n hot: true,\n }\n );\n },\n }\n );\n }\n\n return {\n // Get the static client boundaries (no dead code elimination allowed) for the production export.\n getExpoRouterClientReferencesAsync,\n exportServerActionsAsync,\n\n async exportRoutesAsync(\n {\n platform,\n ssrManifest,\n routerOptions,\n }: {\n platform: string;\n ssrManifest: Map<string, string>;\n routerOptions: Record<string, any>;\n },\n files: ExportAssetMap\n ) {\n // TODO: When we add web SSR support, we need to extract CSS Modules / Assets from the bundler process to prevent FLOUC.\n const { getBuildConfig } = (\n await getExpoRouterRscEntriesGetterAsync({ platform, routerOptions })\n ).default;\n\n // Get all the routes to render.\n const buildConfig = await getBuildConfig!(async () =>\n // TODO: Rework prefetching code to use Metro runtime.\n []\n );\n\n await Promise.all(\n Array.from(buildConfig).map(async ({ entries }) => {\n for (const { input, isStatic } of entries || []) {\n if (!isStatic) {\n debug('Skipping static export for route', { input });\n continue;\n }\n const destRscFile = path.join('_flight', platform, encodeInput(input));\n\n const pipe = await renderRscToReadableStream(\n {\n input,\n method: 'GET',\n platform,\n headers: new Headers(),\n ssrManifest,\n routerOptions,\n },\n true\n );\n\n const rsc = await streamToStringAsync(pipe);\n debug('RSC Payload', { platform, input, rsc });\n\n files.set(destRscFile, {\n contents: rsc,\n targetDomain: 'client',\n rscId: input,\n });\n }\n })\n );\n },\n\n middleware: createBuiltinAPIRequestHandler(\n // Match `/_flight/[platform]/[...path]`\n (req) => {\n return getFullUrl(req.url).pathname.startsWith(rscPathPrefix);\n },\n rscMiddleware\n ),\n onReloadRscEvent: (platform: string) => {\n // NOTE: We cannot clear the renderer context because it would break the mounted context state.\n\n rscRendererCache.delete(platform);\n routerCache.delete(platform);\n },\n };\n}\n\nconst getFullUrl = (url: string) => {\n try {\n return new URL(url);\n } catch {\n return new URL(url, 'http://localhost:0');\n }\n};\n\nexport const fileURLToFilePath = (fileURL: string) => {\n try {\n return url.fileURLToPath(fileURL);\n } catch (error) {\n if (error instanceof TypeError) {\n throw Error(`Invalid URL: ${fileURL}`, { cause: error });\n }\n throw error;\n }\n};\n\nconst encodeInput = (input: string) => {\n if (input === '') {\n return 'index.txt';\n }\n if (input === 'index') {\n throw new Error('Input should not be `index`');\n }\n if (input.startsWith('/')) {\n throw new Error('Input should not start with `/`');\n }\n if (input.endsWith('/')) {\n throw new Error('Input should not end with `/`');\n }\n return input + '.txt';\n};\n\nfunction wrapBundle(str: string) {\n // Skip the metro runtime so debugging is a bit easier.\n // Replace the __r() call with an export statement.\n // Use gm to apply to the last require line. This is needed when the bundle has side-effects.\n return str.replace(/^(__r\\(.*\\);)$/gm, 'module.exports = $1');\n}\n"],"names":["createServerComponentsMiddleware","fileURLToFilePath","debug","require","getMetroServerRootMemo","memoize","getMetroServerRoot","projectRoot","rscPath","instanceMetroOptions","ssrLoadModule","ssrLoadModuleArtifacts","useClientRouter","createModuleId","routerOptions","routerModule","rscMiddleware","getRscMiddleware","config","baseUrl","onError","console","error","renderRsc","args","headers","getIpAddress","renderRscToReadableStream","Headers","body","logMetroError","IS_METRO_BUNDLE_ERROR_SYMBOL","Response","JSON","stringify","status","isPossiblyUnableToResolveError","sanitizedServerMessage","stripAnsi","message","rscPathPrefix","exportServerActionsAsync","platform","entryPoints","domRoot","files","uniqueEntryPoints","Set","manifest","nestedClientBoundaries","nestedServerBoundaries","processedEntryPoints","processEntryPoint","entryPoint","contents","add","environment","modulesOnly","runModule","reactClientReferences","artifacts","filter","a","type","metadata","map","ref","push","reactServerReferences","src","includes","Error","relativeName","safeName","path","basename","find","filename","outputName","set","targetDomain","wrapBundle","publicModuleId","toPosixPath","relative","String","processEntryPoints","recursions","uniqueNestedServerBoundaries","value","has","length","clientBoundaries","getExpoRouterClientReferencesAsync","cssModules","startsWith","routerCache","Map","getExpoRouterRscEntriesGetterAsync","ensureMemo","get","router","hot","entries","default","redirects","rewrites","getResolveClientEntry","context","serverRoot","mode","minify","isExporting","routerRoot","asyncRoutes","preserveEnvVars","reactCompiler","lazy","assert","file","isServer","filePath","join","ssrManifest","relativeFilePath","chunk","id","chunks","searchParams","createBundleUrlSearchParams","mainModuleName","engine","undefined","bytecode","inlineSourceMap","clientReferenceUrl","URL","search","toString","pathname","endsWith","chunkName","rscRendererCache","ensurePromise","ensureSSRReady","runtime","getRscRendererAsync","renderer","rscRenderContext","getRscRenderContext","input","method","contentType","decodedBody","resolveClientEntry","loadServerModuleRsc","urlFragment","options","getMetroOptionsFromUrl","exportRoutesAsync","getBuildConfig","buildConfig","Promise","all","Array","from","isStatic","destRscFile","encodeInput","pipe","rsc","streamToStringAsync","rscId","middleware","createBuiltinAPIRequestHandler","req","getFullUrl","url","onReloadRscEvent","delete","fileURL","fileURLToPath","TypeError","cause","str","replace"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;IAuCeA,gCAAgC;eAAhCA;;IAomBHC,iBAAiB;eAAjBA;;;;yBA1oBsB;;;;;;;gEAEhB;;;;;;;yBAEc;;;;;;;gEAChB;;;;;;;gEACD;;;;;;qCAE4C;qCACb;sBAErB;0BACE;oBACJ;oBACK;wBACO;gDACW;8BAKxC;;;;;;AAEP,MAAMC,QAAQC,QAAQ,SAAS;AAa/B,MAAMC,yBAAyBC,IAAAA,WAAO,EAACC,2BAAkB;AAElD,SAASN,iCACdO,WAAmB,EACnB,EACEC,OAAO,EACPC,oBAAoB,EACpBC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,EACfC,cAAc,EACdC,aAAa,EAYd;IAED,MAAMC,eAAeH,kBACjB,4CACA;IAEJ,MAAMI,gBAAgBC,IAAAA,2BAAgB,EAAC;QACrCC,QAAQ,CAAC;QACT,0BAA0B;QAC1BC,SAAS;QACTX;QACAY,SAASC,QAAQC,KAAK;QACtBC,WAAW,OAAOC;YAChB,gFAAgF;YAChF,IAAIA,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CAAwC;QACxC,CAACC;YACC,OAAOC,WAAWD,IAAIE,GAAG,EAAEtC,QAAQ,CAAC5C,UAAU,CAACvD;QACjD,GACAxB;QAEFkK,kBAAkB,CAACxI;YACjB,+FAA+F;YAE/FoG,iBAAiBqC,MAAM,CAACzI;YACxBsD,YAAYmF,MAAM,CAACzI;QACrB;IACF;AACF;AAEA,MAAMsI,aAAa,CAACC;IAClB,IAAI;QACF,OAAO,IAAIzC,IAAIyC;IACjB,EAAE,OAAM;QACN,OAAO,IAAIzC,IAAIyC,KAAK;IACtB;AACF;AAEO,MAAMhL,oBAAoB,CAACmL;IAChC,IAAI;QACF,OAAOH,cAAG,CAACI,aAAa,CAACD;IAC3B,EAAE,OAAO9J,OAAO;QACd,IAAIA,iBAAiBgK,WAAW;YAC9B,MAAM/G,MAAM,CAAC,aAAa,EAAE6G,SAAS,EAAE;gBAAEG,OAAOjK;YAAM;QACxD;QACA,MAAMA;IACR;AACF;AAEA,MAAMkJ,cAAc,CAAClB;IACnB,IAAIA,UAAU,IAAI;QAChB,OAAO;IACT;IACA,IAAIA,UAAU,SAAS;QACrB,MAAM,IAAI/E,MAAM;IAClB;IACA,IAAI+E,MAAMvD,UAAU,CAAC,MAAM;QACzB,MAAM,IAAIxB,MAAM;IAClB;IACA,IAAI+E,MAAMV,QAAQ,CAAC,MAAM;QACvB,MAAM,IAAIrE,MAAM;IAClB;IACA,OAAO+E,QAAQ;AACjB;AAEA,SAASrE,WAAWuG,GAAW;IAC7B,uDAAuD;IACvD,mDAAmD;IACnD,6FAA6F;IAC7F,OAAOA,IAAIC,OAAO,CAAC,oBAAoB;AACzC"}
|
|
@@ -13,6 +13,13 @@ Object.defineProperty(exports, "createRouteHandlerMiddleware", {
|
|
|
13
13
|
return createRouteHandlerMiddleware;
|
|
14
14
|
}
|
|
15
15
|
});
|
|
16
|
+
function _http() {
|
|
17
|
+
const data = require("expo-server/adapter/http");
|
|
18
|
+
_http = function() {
|
|
19
|
+
return data;
|
|
20
|
+
};
|
|
21
|
+
return data;
|
|
22
|
+
}
|
|
16
23
|
function _resolve() {
|
|
17
24
|
const data = /*#__PURE__*/ _interop_require_default(require("resolve"));
|
|
18
25
|
_resolve = function() {
|
|
@@ -47,10 +54,9 @@ const debug = require('debug')('expo:start:server:metro');
|
|
|
47
54
|
const resolveAsync = (0, _util().promisify)(_resolve().default);
|
|
48
55
|
function createRouteHandlerMiddleware(projectRoot, options) {
|
|
49
56
|
if (!_resolvefrom().default.silent(projectRoot, 'expo-router')) {
|
|
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 '
|
|
57
|
+
throw new _errors.CommandError(`static and server rendering requires the expo-router package to be installed in your project. Either install the expo-router package or change 'web.output' to 'single' in your app.json.`);
|
|
51
58
|
}
|
|
52
|
-
|
|
53
|
-
return createRequestHandler({
|
|
59
|
+
return (0, _http().createRequestHandler)({
|
|
54
60
|
build: ''
|
|
55
61
|
}, {
|
|
56
62
|
async getRoutesManifest () {
|
|
@@ -104,8 +110,8 @@ function createRouteHandlerMiddleware(projectRoot, options) {
|
|
|
104
110
|
}
|
|
105
111
|
},
|
|
106
112
|
async handleRouteError (error) {
|
|
107
|
-
|
|
108
|
-
if (ExpoError
|
|
113
|
+
// NOTE(@kitten): ExpoError is currently not exposed by expo-server just yet
|
|
114
|
+
if (error && typeof error === 'object' && error.name === 'ExpoError') {
|
|
109
115
|
// TODO(@krystofwoldrich): Can we show code snippet of the handler?
|
|
110
116
|
// NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.
|
|
111
117
|
delete error.stack;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/createServerRouteMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport type { ProjectConfig } from '@expo/config';\nimport { MiddlewareModule } from '@expo/server/build/types';\nimport resolve from 'resolve';\nimport resolveFrom from 'resolve-from';\nimport { promisify } from 'util';\n\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync, logMetroError } from './metroErrorInterface';\nimport {\n warnInvalidWebOutput,\n warnInvalidMiddlewareOutput,\n warnInvalidMiddlewareMatcherSettings,\n} from './router';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n appDir: string;\n routerRoot: string;\n getStaticPageAsync: (pathname: string) => Promise<{ content: string }>;\n bundleApiRoute: (\n functionFilePath: string\n ) => Promise<null | Record<string, Function> | Response>;\n config: ProjectConfig;\n } & import('expo-router/build/routes-manifest').Options\n) {\n if (!resolveFrom.silent(projectRoot, 'expo-router')) {\n throw new CommandError(\n `static and server rendering requires the expo-router package to be installed in your project. Either install the expo-router package or change 'web.output' to '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","middlewareModule","unstable_settings","matcher","warnInvalidMiddlewareMatcherSettings"],"mappings":"AAAA;;;;;CAKC;;;;+BAwBeA;;;eAAAA;;;;gEApBI;;;;;;;gEACI;;;;;;;yBACE;;;;;;qCAEI;qCAC0B;wBAKjD;wBACsB;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,eAAeC,IAAAA,iBAAS,EAACC,kBAAO;AAK/B,SAASL,6BACdM,WAAmB,EACnBC,OAQuD;IAEvD,IAAI,CAACC,sBAAW,CAACC,MAAM,CAACH,aAAa,gBAAgB;QACnD,MAAM,IA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aAAayC,MAAM3B,IAAI,EAAE;gBAC1DkC,YAAY;oBAAC;oBAAO;oBAAQ;oBAAO;iBAAO;gBAC1CC,SAAS7C,QAAQ8C,MAAM;YACzB;YAEA,IAAI;oBAMEQ;gBALJ5D,MAAM,CAAC,wBAAwB,EAAEiD,sBAAsB;gBACvD,MAAMW,mBAAoB,MAAMtD,QAAQ+C,cAAc,CACpDJ;gBAGF,KAAIW,sCAAAA,iBAAiBC,iBAAiB,qBAAlCD,oCAAoCE,OAAO,EAAE;wBACVF;oBAArCG,IAAAA,4CAAoC,GAACH,uCAAAA,iBAAiBC,iBAAiB,qBAAlCD,qCAAoCE,OAAO;gBAClF;gBAEA,OAAOF;YACT,EAAE,OAAO/B,OAAY;gBACnB,OAAO,IAAIC,SACT,gCAAgCmB,uBAAuB,SAASpB,MAAMO,OAAO,EAC7E;oBACEH,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ;QACF;IACF;AAEJ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/createServerRouteMiddleware.ts"],"sourcesContent":["/**\n * Copyright © 2022 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport type { ProjectConfig } from '@expo/config';\nimport type { MiddlewareSettings } from 'expo-server';\nimport { createRequestHandler } from 'expo-server/adapter/http';\nimport resolve from 'resolve';\nimport resolveFrom from 'resolve-from';\nimport { promisify } from 'util';\n\nimport { fetchManifest } from './fetchRouterManifest';\nimport { getErrorOverlayHtmlAsync } from './metroErrorInterface';\nimport {\n warnInvalidWebOutput,\n warnInvalidMiddlewareOutput,\n warnInvalidMiddlewareMatcherSettings,\n} from './router';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\nconst resolveAsync = promisify(resolve) as any as (\n id: string,\n opts: resolve.AsyncOpts\n) => Promise<string | null>;\n\nexport function createRouteHandlerMiddleware(\n projectRoot: string,\n options: {\n appDir: string;\n routerRoot: string;\n getStaticPageAsync: (pathname: string) => Promise<{ content: string }>;\n bundleApiRoute: (\n functionFilePath: string\n ) => Promise<null | Record<string, Function> | Response>;\n config: ProjectConfig;\n } & import('expo-router/build/routes-manifest').Options\n) {\n if (!resolveFrom.silent(projectRoot, 'expo-router')) {\n throw new CommandError(\n `static and server rendering requires the expo-router package to be installed in your project. Either install the expo-router package or change 'web.output' to 'single' in your app.json.`\n );\n }\n\n return createRequestHandler(\n { build: '' },\n {\n async getRoutesManifest() {\n const manifest = await fetchManifest<RegExp>(projectRoot, options);\n debug('manifest', manifest);\n // NOTE: no app dir if null\n // TODO: Redirect to 404 page\n return (\n manifest ?? {\n // Support the onboarding screen if there's no manifest\n htmlRoutes: [\n {\n file: 'index.js',\n page: '/index',\n routeKeys: {},\n namedRegex: /^\\/(?:index)?\\/?$/i,\n },\n ],\n apiRoutes: [],\n notFoundRoutes: [],\n redirects: [],\n rewrites: [],\n }\n );\n },\n async getHtml(request) {\n try {\n const { content } = await options.getStaticPageAsync(request.url);\n return content;\n } catch (error: any) {\n // Forward the Metro server response as-is. It won't be pretty, but at least it will be accurate.\n\n try {\n return new Response(\n await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot,\n }),\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n } catch (staticError: any) {\n debug('Failed to render static error overlay:', staticError);\n // Fallback error for when Expo Router is misconfigured in the project.\n return new Response(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>',\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n }\n },\n async handleRouteError(error) {\n // NOTE(@kitten): ExpoError is currently not exposed by expo-server just yet\n if (error && typeof error === 'object' && error.name === 'ExpoError') {\n // TODO(@krystofwoldrich): Can we show code snippet of the handler?\n // NOTE(@krystofwoldrich): Removing stack since to avoid confusion. The error is not in the server code.\n delete error.stack;\n }\n\n const htmlServerError = await getErrorOverlayHtmlAsync({\n error,\n projectRoot,\n routerRoot: options.routerRoot!,\n });\n\n return new Response(htmlServerError, {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n });\n },\n async getApiRoute(route) {\n const { exp } = options.config;\n if (exp.web?.output !== 'server') {\n warnInvalidWebOutput();\n }\n\n const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\n try {\n debug(`Bundling API route at: ${resolvedFunctionPath}`);\n return await options.bundleApiRoute(resolvedFunctionPath!);\n } catch (error: any) {\n return new Response(\n 'Failed to load API Route: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n async getMiddleware(route) {\n const { exp } = options.config;\n\n if (!options.unstable_useServerMiddleware) {\n return {\n default: () => {\n throw new CommandError(\n 'Server middleware is not enabled. Add unstable_useServerMiddleware: true to your `expo-router` plugin config.'\n );\n },\n };\n }\n\n if (exp.web?.output !== 'server') {\n warnInvalidMiddlewareOutput();\n return {\n default: () => {\n console.warn(\n 'Server middleware is only supported when web.output is set to \"server\" in your app config'\n );\n },\n };\n }\n\n const resolvedFunctionPath = await resolveAsync(route.file, {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n basedir: options.appDir,\n })!;\n\n try {\n debug(`Bundling middleware at: ${resolvedFunctionPath}`);\n const middlewareModule = (await options.bundleApiRoute(resolvedFunctionPath!)) as any;\n\n if ((middlewareModule.unstable_settings as MiddlewareSettings)?.matcher) {\n warnInvalidMiddlewareMatcherSettings(middlewareModule.unstable_settings?.matcher);\n }\n\n return middlewareModule;\n } catch (error: any) {\n return new Response(\n 'Failed to load middleware: ' + resolvedFunctionPath + '\\n\\n' + error.message,\n {\n status: 500,\n headers: {\n 'Content-Type': 'text/html',\n },\n }\n );\n }\n },\n }\n );\n}\n"],"names":["createRouteHandlerMiddleware","debug","require","resolveAsync","promisify","resolve","projectRoot","options","resolveFrom","silent","CommandError","createRequestHandler","build","getRoutesManifest","manifest","fetchManifest","htmlRoutes","file","page","routeKeys","namedRegex","apiRoutes","notFoundRoutes","redirects","rewrites","getHtml","request","content","getStaticPageAsync","url","error","Response","getErrorOverlayHtmlAsync","routerRoot","status","headers","staticError","message","handleRouteError","name","stack","htmlServerError","getApiRoute","route","exp","config","web","output","warnInvalidWebOutput","resolvedFunctionPath","extensions","basedir","appDir","bundleApiRoute","getMiddleware","unstable_useServerMiddleware","default","warnInvalidMiddlewareOutput","console","warn","middlewareModule","unstable_settings","matcher","warnInvalidMiddlewareMatcherSettings"],"mappings":"AAAA;;;;;CAKC;;;;+BAyBeA;;;eAAAA;;;;yBArBqB;;;;;;;gEACjB;;;;;;;gEACI;;;;;;;yBACE;;;;;;qCAEI;qCACW;wBAKlC;wBACsB;;;;;;AAE7B,MAAMC,QAAQC,QAAQ,SAAS;AAE/B,MAAMC,eAAeC,IAAAA,iBAAS,EAACC,kBAAO;AAK/B,SAASL,6BACdM,WAAmB,EACnBC,OAQuD;IAEvD,IAAI,CAACC,sBAAW,CAACC,MAAM,CAACH,aAAa,gBAAgB;QACnD,MAAM,IAAII,oBAAY,CACpB,CAAC,yLAAyL,CAAC;IAE/L;IAEA,OAAOC,IAAAA,4BAAoB,EACzB;QAAEC,OAAO;IAAG,GACZ;QACE,MAAMC;YACJ,MAAMC,WAAW,MAAMC,IAAAA,kCAAa,EAAST,aAAaC;YAC1DN,MAAM,YAAYa;YAClB,2BAA2B;YAC3B,6BAA6B;YAC7B,OACEA,YAAY;gBACV,uDAAuD;gBACvDE,YAAY;oBACV;wBACEC,MAAM;wBACNC,MAAM;wBACNC,WAAW,CAAC;wBACZC,YAAY;oBACd;iBACD;gBACDC,WAAW,EAAE;gBACbC,gBAAgB,EAAE;gBAClBC,WAAW,EAAE;gBACbC,UAAU,EAAE;YACd;QAEJ;Q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T,gCAAgCkB,uBAAuB,SAASnB,MAAMO,OAAO,EAC7E;oBACEH,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ;QACF;IACF;AAEJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/router.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport type { MiddlewareMatcher } from '@expo/server/build/types';\nimport chalk from 'chalk';\nimport { sync as globSync } from 'glob';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { directoryExistsSync } from '../../../utils/dir';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { learnMore } from '../../../utils/link';\n\nconst debug = require('debug')('expo:start:server:metro:router') as typeof console.log;\n\n/**\n * Get the relative path for requiring the `/app` folder relative to the `expo-router/entry` file.\n * This mechanism does require the server to restart after the `expo-router` package is installed.\n */\nexport function getAppRouterRelativeEntryPath(\n projectRoot: string,\n routerDirectory: string = getRouterDirectory(projectRoot)\n): string | undefined {\n // Auto pick App entry\n const routerEntry =\n resolveFrom.silent(projectRoot, 'expo-router/entry') ?? getFallbackEntryRoot(projectRoot);\n if (!routerEntry) {\n return undefined;\n }\n // It doesn't matter if the app folder exists.\n const appFolder = path.join(projectRoot, routerDirectory);\n const appRoot = path.relative(path.dirname(routerEntry), appFolder);\n debug('expo-router entry', routerEntry, appFolder, appRoot);\n return appRoot;\n}\n\n/** If the `expo-router` package is not installed, then use the `expo` package to determine where the node modules are relative to the project. */\nfunction getFallbackEntryRoot(projectRoot: string): string {\n const expoRoot = resolveFrom.silent(projectRoot, 'expo/package.json');\n if (expoRoot) {\n return path.join(path.dirname(path.dirname(expoRoot)), 'expo-router/entry');\n }\n return path.join(projectRoot, 'node_modules/expo-router/entry');\n}\n\nexport function getRouterDirectoryModuleIdWithManifest(\n projectRoot: string,\n exp: ExpoConfig\n): string {\n return toPosixPath(exp.extra?.router?.root ?? getRouterDirectory(projectRoot));\n}\n\nlet hasWarnedAboutSrcDir = false;\nconst logSrcDir = () => {\n if (hasWarnedAboutSrcDir) return;\n hasWarnedAboutSrcDir = true;\n Log.log(chalk.gray('Using src/app as the root directory for Expo Router.'));\n};\n\nexport function getRouterDirectory(projectRoot: string): string {\n // more specific directories first\n if (directoryExistsSync(path.join(projectRoot, 'src', 'app'))) {\n logSrcDir();\n return path.join('src', 'app');\n }\n\n debug('Using app as the root directory for Expo Router.');\n return 'app';\n}\n\nexport function isApiRouteConvention(name: string): boolean {\n return /\\+api\\.[tj]sx?$/.test(name);\n}\n\nexport function getApiRoutesForDirectory(cwd: string) {\n return globSync('**/*+api.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n}\n\n/**\n * Gets the +middleware file for a given directory. In\n * @param cwd\n */\nexport function getMiddlewareForDirectory(cwd: string): string | null {\n const files = globSync('+middleware.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n\n if (files.length === 0) return null;\n\n if (files.length > 1) {\n // In development, throw an error if there are multiple root-level middleware files\n if (process.env.NODE_ENV !== 'production') {\n const relativePaths = files.map((f) => './' + path.relative(cwd, f)).sort();\n throw new Error(\n `Only one middleware file is allowed. Keep one of the conflicting files: ${relativePaths.map((p) => `\"${p}\"`).join(' or ')}`\n );\n }\n }\n\n return files[0];\n}\n\n// Used to emulate a context module, but way faster. TODO: May need to adjust the extensions to stay in sync with Metro.\nexport function getRoutePaths(cwd: string) {\n return globSync('**/*.@(ts|tsx|js|jsx)', {\n cwd,\n dot: true,\n }).map((p) => './' + normalizePaths(p));\n}\n\nfunction normalizePaths(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nlet hasWarnedAboutApiRouteOutput = false;\nlet hasWarnedAboutMiddlewareOutput = false;\n\nexport function hasWarnedAboutApiRoutes() {\n return hasWarnedAboutApiRouteOutput;\n}\n\nexport function hasWarnedAboutMiddleware() {\n return hasWarnedAboutMiddlewareOutput;\n}\n\nexport function warnInvalidWebOutput() {\n if (!hasWarnedAboutApiRouteOutput) {\n Log.warn(\n chalk.yellow`Using API routes requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutApiRouteOutput = true;\n}\n\nexport function warnInvalidMiddlewareOutput() {\n if (!hasWarnedAboutMiddlewareOutput) {\n Log.warn(\n chalk.yellow`Using middleware requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutMiddlewareOutput = true;\n}\n\nexport function warnInvalidMiddlewareMatcherSettings(matcher: MiddlewareMatcher) {\n const validMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];\n\n // Ensure methods are valid HTTP methods\n if (matcher.methods) {\n if (!Array.isArray(matcher.methods)) {\n Log.error(\n chalk.red`Middleware matcher methods must be an array of valid HTTP methods. Supported methods are: ${validMethods.join(', ')}`\n );\n } else {\n for (const method of matcher.methods) {\n if (!validMethods.includes(method)) {\n Log.error(\n chalk.red`Invalid middleware HTTP method: ${method}. Supported methods are: ${validMethods.join(', ')}`\n );\n }\n }\n }\n }\n\n // Ensure patterns are either a string or RegExp\n if (matcher.patterns) {\n const patterns = Array.isArray(matcher.patterns) ? matcher.patterns : [matcher.patterns];\n for (const pattern of patterns) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n Log.error(\n chalk.red`Middleware matcher patterns must be strings or regular expressions. Received: ${String(\n pattern\n )}`\n );\n }\n\n if (typeof pattern === 'string' && !pattern.startsWith('/')) {\n Log.error(\n chalk.red`String patterns in middleware matcher must start with '/'. Received: ${pattern}`\n );\n }\n }\n }\n}\n"],"names":["getApiRoutesForDirectory","getAppRouterRelativeEntryPath","getMiddlewareForDirectory","getRoutePaths","getRouterDirectory","getRouterDirectoryModuleIdWithManifest","hasWarnedAboutApiRoutes","hasWarnedAboutMiddleware","isApiRouteConvention","warnInvalidMiddlewareMatcherSettings","warnInvalidMiddlewareOutput","warnInvalidWebOutput","debug","require","projectRoot","routerDirectory","routerEntry","resolveFrom","silent","getFallbackEntryRoot","undefined","appFolder","path","join","appRoot","relative","dirname","expoRoot","exp","toPosixPath","extra","router","root","hasWarnedAboutSrcDir","logSrcDir","Log","log","chalk","gray","directoryExistsSync","name","test","cwd","globSync","absolute","dot","files","length","process","env","NODE_ENV","relativePaths","map","f","sort","Error","p","normalizePaths","replace","hasWarnedAboutApiRouteOutput","hasWarnedAboutMiddlewareOutput","warn","yellow","learnMore","matcher","validMethods","methods","Array","isArray","error","red","method","includes","patterns","pattern","RegExp","String","startsWith"],"mappings":";;;;;;;;;;;IAyEgBA,wBAAwB;eAAxBA;;IAvDAC,6BAA6B;eAA7BA;;IAmEAC,yBAAyB;eAAzBA;;IAuBAC,aAAa;eAAbA;;IAlDAC,kBAAkB;eAAlBA;;IAdAC,sCAAsC;eAAtCA;;IA8EAC,uBAAuB;eAAvBA;;IAIAC,wBAAwB;eAAxBA;;IAzDAC,oBAAoB;eAApBA;;IAqFAC,oCAAoC;eAApCA;;IAZAC,2BAA2B;eAA3BA;;IAZAC,oBAAoB;eAApBA;;;;gEAhIE;;;;;;;yBACe;;;;;;;gEAChB;;;;;;;gEACO;;;;;;qBAEJ;qBACgB;0BACR;sBACF;;;;;;AAE1B,MAAMC,QAAQC,QAAQ,SAAS;AAMxB,SAASZ,8BACda,WAAmB,EACnBC,kBAA0BX,mBAAmBU,YAAY;IAEzD,sBAAsB;IACtB,MAAME,cACJC,sBAAW,CAACC,MAAM,CAACJ,aAAa,wBAAwBK,qBAAqBL;IAC/E,IAAI,CAACE,aAAa;QAChB,OAAOI;IACT;IACA,8CAA8C;IAC9C,MAAMC,YAAYC,eAAI,CAACC,IAAI,CAACT,aAAaC;IACzC,MAAMS,UAAUF,eAAI,CAACG,QAAQ,CAACH,eAAI,CAACI,OAAO,CA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;QACnB,IAAI,CAACC,MAAMC,OAAO,CAACJ,QAAQE,OAAO,GAAG;YACnC/B,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,0FAA0F,EAAEL,aAAa1C,IAAI,CAAC,MAAM,CAAC;QAEnI,OAAO;YACL,KAAK,MAAMgD,UAAUP,QAAQE,OAAO,CAAE;gBACpC,IAAI,CAACD,aAAaO,QAAQ,CAACD,SAAS;oBAClCpC,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,gCAAgC,EAAEC,OAAO,yBAAyB,EAAEN,aAAa1C,IAAI,CAAC,MAAM,CAAC;gBAE3G;YACF;QACF;IACF;IAEA,gDAAgD;IAChD,IAAIyC,QAAQS,QAAQ,EAAE;QACpB,MAAMA,WAAWN,MAAMC,OAAO,CAACJ,QAAQS,QAAQ,IAAIT,QAAQS,QAAQ,GAAG;YAACT,QAAQS,QAAQ;SAAC;QACxF,KAAK,MAAMC,WAAWD,SAAU;YAC9B,IAAI,OAAOC,YAAY,YAAY,CAAEA,CAAAA,mBAAmBC,MAAK,GAAI;gBAC/DxC,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,8EAA8E,EAAEM,OACxFF,SACA,CAAC;YAEP;YAEA,IAAI,OAAOA,YAAY,YAAY,CAACA,QAAQG,UAAU,CAAC,MAAM;gBAC3D1C,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,qEAAqE,EAAEI,QAAQ,CAAC;YAE9F;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/router.ts"],"sourcesContent":["import { ExpoConfig } from '@expo/config';\nimport chalk from 'chalk';\nimport type { MiddlewareMatcher } from 'expo-server';\nimport { sync as globSync } from 'glob';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\n\nimport { Log } from '../../../log';\nimport { directoryExistsSync } from '../../../utils/dir';\nimport { toPosixPath } from '../../../utils/filePath';\nimport { learnMore } from '../../../utils/link';\n\nconst debug = require('debug')('expo:start:server:metro:router') as typeof console.log;\n\n/**\n * Get the relative path for requiring the `/app` folder relative to the `expo-router/entry` file.\n * This mechanism does require the server to restart after the `expo-router` package is installed.\n */\nexport function getAppRouterRelativeEntryPath(\n projectRoot: string,\n routerDirectory: string = getRouterDirectory(projectRoot)\n): string | undefined {\n // Auto pick App entry\n const routerEntry =\n resolveFrom.silent(projectRoot, 'expo-router/entry') ?? getFallbackEntryRoot(projectRoot);\n if (!routerEntry) {\n return undefined;\n }\n // It doesn't matter if the app folder exists.\n const appFolder = path.join(projectRoot, routerDirectory);\n const appRoot = path.relative(path.dirname(routerEntry), appFolder);\n debug('expo-router entry', routerEntry, appFolder, appRoot);\n return appRoot;\n}\n\n/** If the `expo-router` package is not installed, then use the `expo` package to determine where the node modules are relative to the project. */\nfunction getFallbackEntryRoot(projectRoot: string): string {\n const expoRoot = resolveFrom.silent(projectRoot, 'expo/package.json');\n if (expoRoot) {\n return path.join(path.dirname(path.dirname(expoRoot)), 'expo-router/entry');\n }\n return path.join(projectRoot, 'node_modules/expo-router/entry');\n}\n\nexport function getRouterDirectoryModuleIdWithManifest(\n projectRoot: string,\n exp: ExpoConfig\n): string {\n return toPosixPath(exp.extra?.router?.root ?? getRouterDirectory(projectRoot));\n}\n\nlet hasWarnedAboutSrcDir = false;\nconst logSrcDir = () => {\n if (hasWarnedAboutSrcDir) return;\n hasWarnedAboutSrcDir = true;\n Log.log(chalk.gray('Using src/app as the root directory for Expo Router.'));\n};\n\nexport function getRouterDirectory(projectRoot: string): string {\n // more specific directories first\n if (directoryExistsSync(path.join(projectRoot, 'src', 'app'))) {\n logSrcDir();\n return path.join('src', 'app');\n }\n\n debug('Using app as the root directory for Expo Router.');\n return 'app';\n}\n\nexport function isApiRouteConvention(name: string): boolean {\n return /\\+api\\.[tj]sx?$/.test(name);\n}\n\nexport function getApiRoutesForDirectory(cwd: string) {\n return globSync('**/*+api.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n}\n\n/**\n * Gets the +middleware file for a given directory. In\n * @param cwd\n */\nexport function getMiddlewareForDirectory(cwd: string): string | null {\n const files = globSync('+middleware.@(ts|tsx|js|jsx)', {\n cwd,\n absolute: true,\n dot: true,\n });\n\n if (files.length === 0) return null;\n\n if (files.length > 1) {\n // In development, throw an error if there are multiple root-level middleware files\n if (process.env.NODE_ENV !== 'production') {\n const relativePaths = files.map((f) => './' + path.relative(cwd, f)).sort();\n throw new Error(\n `Only one middleware file is allowed. Keep one of the conflicting files: ${relativePaths.map((p) => `\"${p}\"`).join(' or ')}`\n );\n }\n }\n\n return files[0];\n}\n\n// Used to emulate a context module, but way faster. TODO: May need to adjust the extensions to stay in sync with Metro.\nexport function getRoutePaths(cwd: string) {\n return globSync('**/*.@(ts|tsx|js|jsx)', {\n cwd,\n dot: true,\n }).map((p) => './' + normalizePaths(p));\n}\n\nfunction normalizePaths(p: string) {\n return p.replace(/\\\\/g, '/');\n}\n\nlet hasWarnedAboutApiRouteOutput = false;\nlet hasWarnedAboutMiddlewareOutput = false;\n\nexport function hasWarnedAboutApiRoutes() {\n return hasWarnedAboutApiRouteOutput;\n}\n\nexport function hasWarnedAboutMiddleware() {\n return hasWarnedAboutMiddlewareOutput;\n}\n\nexport function warnInvalidWebOutput() {\n if (!hasWarnedAboutApiRouteOutput) {\n Log.warn(\n chalk.yellow`Using API routes requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutApiRouteOutput = true;\n}\n\nexport function warnInvalidMiddlewareOutput() {\n if (!hasWarnedAboutMiddlewareOutput) {\n Log.warn(\n chalk.yellow`Using middleware requires the {bold web.output} to be set to {bold \"server\"} in the project {bold app.json}. ${learnMore(\n 'https://docs.expo.dev/router/reference/api-routes/'\n )}`\n );\n }\n\n hasWarnedAboutMiddlewareOutput = true;\n}\n\nexport function warnInvalidMiddlewareMatcherSettings(matcher: MiddlewareMatcher) {\n const validMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];\n\n // Ensure methods are valid HTTP methods\n if (matcher.methods) {\n if (!Array.isArray(matcher.methods)) {\n Log.error(\n chalk.red`Middleware matcher methods must be an array of valid HTTP methods. Supported methods are: ${validMethods.join(', ')}`\n );\n } else {\n for (const method of matcher.methods) {\n if (!validMethods.includes(method)) {\n Log.error(\n chalk.red`Invalid middleware HTTP method: ${method}. Supported methods are: ${validMethods.join(', ')}`\n );\n }\n }\n }\n }\n\n // Ensure patterns are either a string or RegExp\n if (matcher.patterns) {\n const patterns = Array.isArray(matcher.patterns) ? matcher.patterns : [matcher.patterns];\n for (const pattern of patterns) {\n if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {\n Log.error(\n chalk.red`Middleware matcher patterns must be strings or regular expressions. Received: ${String(\n pattern\n )}`\n );\n }\n\n if (typeof pattern === 'string' && !pattern.startsWith('/')) {\n Log.error(\n chalk.red`String patterns in middleware matcher must start with '/'. Received: ${pattern}`\n );\n }\n }\n }\n}\n"],"names":["getApiRoutesForDirectory","getAppRouterRelativeEntryPath","getMiddlewareForDirectory","getRoutePaths","getRouterDirectory","getRouterDirectoryModuleIdWithManifest","hasWarnedAboutApiRoutes","hasWarnedAboutMiddleware","isApiRouteConvention","warnInvalidMiddlewareMatcherSettings","warnInvalidMiddlewareOutput","warnInvalidWebOutput","debug","require","projectRoot","routerDirectory","routerEntry","resolveFrom","silent","getFallbackEntryRoot","undefined","appFolder","path","join","appRoot","relative","dirname","expoRoot","exp","toPosixPath","extra","router","root","hasWarnedAboutSrcDir","logSrcDir","Log","log","chalk","gray","directoryExistsSync","name","test","cwd","globSync","absolute","dot","files","length","process","env","NODE_ENV","relativePaths","map","f","sort","Error","p","normalizePaths","replace","hasWarnedAboutApiRouteOutput","hasWarnedAboutMiddlewareOutput","warn","yellow","learnMore","matcher","validMethods","methods","Array","isArray","error","red","method","includes","patterns","pattern","RegExp","String","startsWith"],"mappings":";;;;;;;;;;;IAyEgBA,wBAAwB;eAAxBA;;IAvDAC,6BAA6B;eAA7BA;;IAmEAC,yBAAyB;eAAzBA;;IAuBAC,aAAa;eAAbA;;IAlDAC,kBAAkB;eAAlBA;;IAdAC,sCAAsC;eAAtCA;;IA8EAC,uBAAuB;eAAvBA;;IAIAC,wBAAwB;eAAxBA;;IAzDAC,oBAAoB;eAApBA;;IAqFAC,oCAAoC;eAApCA;;IAZAC,2BAA2B;eAA3BA;;IAZAC,oBAAoB;eAApBA;;;;gEAjIE;;;;;;;yBAEe;;;;;;;gEAChB;;;;;;;gEACO;;;;;;qBAEJ;qBACgB;0BACR;sBACF;;;;;;AAE1B,MAAMC,QAAQC,QAAQ,SAAS;AAMxB,SAASZ,8BACda,WAAmB,EACnBC,kBAA0BX,mBAAmBU,YAAY;IAEzD,sBAAsB;IACtB,MAAME,cACJC,sBAAW,CAACC,MAAM,CAACJ,aAAa,wBAAwBK,qBAAqBL;IAC/E,IAAI,CAACE,aAAa;QAChB,OAAOI;IACT;IACA,8CAA8C;IAC9C,MAAMC,YAAYC,eAAI,CAACC,IAAI,CAACT,aAAaC;IACzC,MAAMS,UAAUF,eAAI,CAACG,QAAQ,CAACH,eAAI,CAACI,OAAO,CAACV,cAAcK;IACzDT,MAAM,qBAAqBI,aAAaK,WAAWG;IACnD,OAAOA;AACT;AAEA,gJAAgJ,GAChJ,SAASL,qBAAqBL,WAAmB;IAC/C,MAAMa,WAAWV,sBAAW,CAACC,MAAM,CAACJ,aAAa;IACjD,IAAIa,UAAU;QACZ,OAAOL,eAAI,CAACC,IAAI,CAACD,eAAI,CAACI,OAAO,CAACJ,eAAI,CAACI,OAAO,CAACC,YAAY;IACzD;IACA,OAAOL,eAAI,CAACC,IAAI,CAACT,aAAa;AAChC;AAEO,SAAST,uCACdS,WAAmB,EACnBc,GAAe;QAEIA,mBAAAA;IAAnB,OAAOC,IAAAA,qBAAW,E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;QACF;IACF;IAEA,gDAAgD;IAChD,IAAIyC,QAAQS,QAAQ,EAAE;QACpB,MAAMA,WAAWN,MAAMC,OAAO,CAACJ,QAAQS,QAAQ,IAAIT,QAAQS,QAAQ,GAAG;YAACT,QAAQS,QAAQ;SAAC;QACxF,KAAK,MAAMC,WAAWD,SAAU;YAC9B,IAAI,OAAOC,YAAY,YAAY,CAAEA,CAAAA,mBAAmBC,MAAK,GAAI;gBAC/DxC,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,8EAA8E,EAAEM,OACxFF,SACA,CAAC;YAEP;YAEA,IAAI,OAAOA,YAAY,YAAY,CAACA,QAAQG,UAAU,CAAC,MAAM;gBAC3D1C,QAAG,CAACkC,KAAK,CACPhC,gBAAK,CAACiC,GAAG,CAAC,qEAAqE,EAAEI,QAAQ,CAAC;YAE9F;QACF;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/createBuiltinAPIRequestHandler.ts"],"sourcesContent":["import { convertRequest, RequestHandler, respond } from '
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/createBuiltinAPIRequestHandler.ts"],"sourcesContent":["import { convertRequest, RequestHandler, respond } from 'expo-server/adapter/http';\n\nimport type { ServerNext, ServerRequest, ServerResponse } from './server.types';\n\nexport function createBuiltinAPIRequestHandler(\n matchRequest: (request: Request) => boolean,\n handlers: Record<string, (req: Request) => Promise<Response>>\n): RequestHandler {\n return createRequestHandler((req) => {\n if (!matchRequest(req)) {\n winterNext();\n }\n const handler = handlers[req.method];\n if (!handler) {\n notAllowed();\n }\n return handler(req);\n });\n}\n\n/**\n * Returns a request handler for http that serves the response using Remix.\n */\nexport function createRequestHandler(\n handleRequest: (request: Request) => Promise<Response>\n): RequestHandler {\n return async (req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n if (!req?.url || !req.method) {\n return next();\n }\n // These headers (added by other middleware) break the browser preview of RSC.\n res.removeHeader('X-Content-Type-Options');\n res.removeHeader('Cache-Control');\n res.removeHeader('Expires');\n res.removeHeader('Surrogate-Control');\n\n try {\n const request = convertRequest(req, res);\n const response = await handleRequest(request);\n return await respond(res, response);\n } catch (error: unknown) {\n if (error instanceof Error) {\n return await respond(\n res,\n new Response('Internal Server Error: ' + error.message, {\n status: 500,\n headers: {\n 'Content-Type': 'text/plain',\n },\n })\n );\n } else if (error instanceof Response) {\n return await respond(res, error);\n }\n // http doesn't support async functions, so we have to pass along the\n // error manually using next().\n // @ts-expect-error\n next(error);\n }\n };\n}\n\nfunction notAllowed(): never {\n throw new Response('Method Not Allowed', {\n status: 405,\n headers: {\n 'Content-Type': 'text/plain',\n },\n });\n}\n\nexport function winterNext(): never {\n // eslint-disable-next-line no-throw-literal\n throw undefined;\n}\n"],"names":["createBuiltinAPIRequestHandler","createRequestHandler","winterNext","matchRequest","handlers","req","handler","method","notAllowed","handleRequest","res","next","url","removeHeader","request","convertRequest","response","respond","error","Error","Response","message","status","headers","undefined"],"mappings":";;;;;;;;;;;IAIgBA,8BAA8B;eAA9BA;;IAmBAC,oBAAoB;eAApBA;;IAgDAC,UAAU;eAAVA;;;;yBAvEwC;;;;;;AAIjD,SAASF,+BACdG,YAA2C,EAC3CC,QAA6D;IAE7D,OAAOH,qBAAqB,CAACI;QAC3B,IAAI,CAACF,aAAaE,MAAM;YACtBH;QACF;QACA,MAAMI,UAAUF,QAAQ,CAACC,IAAIE,MAAM,CAAC;QACpC,IAAI,CAACD,SAAS;YACZE;QACF;QACA,OAAOF,QAAQD;IACjB;AACF;AAKO,SAASJ,qBACdQ,aAAsD;IAEtD,OAAO,OAAOJ,KAAoBK,KAAqBC;QACrD,IAAI,EAACN,uBAAAA,IAAKO,GAAG,KAAI,CAACP,IAAIE,MAAM,EAAE;YAC5B,OAAOI;QACT;QACA,8EAA8E;QAC9ED,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QACjBH,IAAIG,YAAY,CAAC;QAEjB,IAAI;YACF,MAAMC,UAAUC,IAAAA,sBAAc,EAACV,KAAKK;YACpC,MAAMM,WAAW,MAAMP,cAAcK;YACrC,OAAO,MAAMG,IAAAA,eAAO,EAACP,KAAKM;QAC5B,EAAE,OAAOE,OAAgB;YACvB,IAAIA,iBAAiBC,OAAO;gBAC1B,OAAO,MAAMF,IAAAA,eAAO,EAClBP,KACA,IAAIU,SAAS,4BAA4BF,MAAMG,OAAO,EAAE;oBACtDC,QAAQ;oBACRC,SAAS;wBACP,gBAAgB;oBAClB;gBACF;YAEJ,OAAO,IAAIL,iBAAiBE,UAAU;gBACpC,OAAO,MAAMH,IAAAA,eAAO,EAACP,KAAKQ;YAC5B;YACA,qEAAqE;YACrE,+BAA+B;YAC/B,mBAAmB;YACnBP,KAAKO;QACP;IACF;AACF;AAEA,SAASV;IACP,MAAM,IAAIY,SAAS,sBAAsB;QACvCE,QAAQ;QACRC,SAAS;YACP,gBAAgB;QAClB;IACF;AACF;AAEO,SAASrB;IACd,4CAA4C;IAC5C,MAAMsB;AACR"}
|
|
@@ -33,7 +33,7 @@ class FetchClient {
|
|
|
33
33
|
this.headers = {
|
|
34
34
|
accept: 'application/json',
|
|
35
35
|
'content-type': 'application/json',
|
|
36
|
-
'user-agent': `expo-cli/${"54.0.
|
|
36
|
+
'user-agent': `expo-cli/${"54.0.10"}`,
|
|
37
37
|
authorization: 'Basic ' + _nodebuffer().Buffer.from(`${target}:`).toString('base64')
|
|
38
38
|
};
|
|
39
39
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "54.0.
|
|
3
|
+
"version": "54.0.10",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -43,21 +43,20 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@0no-co/graphql.web": "^1.0.8",
|
|
45
45
|
"@expo/code-signing-certificates": "^0.0.5",
|
|
46
|
-
"@expo/config": "~12.0.
|
|
47
|
-
"@expo/config-plugins": "~54.0.
|
|
46
|
+
"@expo/config": "~12.0.10",
|
|
47
|
+
"@expo/config-plugins": "~54.0.2",
|
|
48
48
|
"@expo/devcert": "^1.1.2",
|
|
49
49
|
"@expo/env": "~2.0.7",
|
|
50
50
|
"@expo/image-utils": "^0.8.7",
|
|
51
51
|
"@expo/json-file": "^10.0.7",
|
|
52
52
|
"@expo/mcp-tunnel": "~0.0.7",
|
|
53
53
|
"@expo/metro": "~54.0.0",
|
|
54
|
-
"@expo/metro-config": "~54.0.
|
|
54
|
+
"@expo/metro-config": "~54.0.6",
|
|
55
55
|
"@expo/osascript": "^2.3.7",
|
|
56
56
|
"@expo/package-manager": "^1.9.8",
|
|
57
57
|
"@expo/plist": "^0.4.7",
|
|
58
|
-
"@expo/prebuild-config": "^54.0.
|
|
58
|
+
"@expo/prebuild-config": "^54.0.4",
|
|
59
59
|
"@expo/schema-utils": "^0.1.7",
|
|
60
|
-
"@expo/server": "^0.7.5",
|
|
61
60
|
"@expo/spawn-async": "^1.7.2",
|
|
62
61
|
"@expo/ws-tunnel": "^1.0.1",
|
|
63
62
|
"@expo/xcpretty": "^4.3.0",
|
|
@@ -75,6 +74,7 @@
|
|
|
75
74
|
"connect": "^3.7.0",
|
|
76
75
|
"debug": "^4.3.4",
|
|
77
76
|
"env-editor": "^0.4.1",
|
|
77
|
+
"expo-server": "^1.0.0",
|
|
78
78
|
"freeport-async": "^2.0.0",
|
|
79
79
|
"getenv": "^2.0.0",
|
|
80
80
|
"glob": "^10.4.2",
|
|
@@ -169,5 +169,5 @@
|
|
|
169
169
|
"tree-kill": "^1.2.2",
|
|
170
170
|
"tsd": "^0.28.1"
|
|
171
171
|
},
|
|
172
|
-
"gitHead": "
|
|
172
|
+
"gitHead": "73d9bc0ee4f1e28cfda349dc36ee53d16fad0c5d"
|
|
173
173
|
}
|