@expo/cli 0.17.4 → 0.17.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +2 -2
- package/build/src/start/server/AsyncNgrok.js +1 -5
- package/build/src/start/server/AsyncNgrok.js.map +1 -1
- package/build/src/start/server/UrlCreator.js +2 -2
- package/build/src/start/server/UrlCreator.js.map +1 -1
- package/build/src/start/server/getStaticRenderFunctions.js +3 -11
- package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +3 -3
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +2 -1
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ManifestMiddleware.js +5 -4
- package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
- package/build/src/start/server/serverLogLikeMetro.js +147 -0
- package/build/src/start/server/serverLogLikeMetro.js.map +1 -0
- package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js.map +1 -1
- package/build/src/utils/analytics/rudderstackClient.js +2 -2
- package/build/src/utils/createFileTransform.js +1 -0
- package/build/src/utils/createFileTransform.js.map +1 -1
- package/package.json +3 -2
package/build/bin/cli
CHANGED
|
@@ -137,7 +137,7 @@ const args = (0, _arg).default({
|
|
|
137
137
|
});
|
|
138
138
|
if (args["--version"]) {
|
|
139
139
|
// Version is added in the build script.
|
|
140
|
-
console.log("0.17.
|
|
140
|
+
console.log("0.17.5");
|
|
141
141
|
process.exit(0);
|
|
142
142
|
}
|
|
143
143
|
if (args["--non-interactive"]) {
|
|
@@ -272,7 +272,7 @@ commands[command]().then((exec)=>{
|
|
|
272
272
|
logEventAsync("action", {
|
|
273
273
|
action: `expo ${command}`,
|
|
274
274
|
source: "expo/cli",
|
|
275
|
-
source_version: "0.17.
|
|
275
|
+
source_version: "0.17.5"
|
|
276
276
|
});
|
|
277
277
|
}
|
|
278
278
|
});
|
|
@@ -72,10 +72,7 @@ class AsyncNgrok {
|
|
|
72
72
|
];
|
|
73
73
|
}
|
|
74
74
|
/** Exposed for testing. */ async _getProjectHostnameAsync() {
|
|
75
|
-
return
|
|
76
|
-
...await this._getIdentifyingUrlSegmentsAsync(),
|
|
77
|
-
NGROK_CONFIG.domain
|
|
78
|
-
].join(".");
|
|
75
|
+
return `${(await this._getIdentifyingUrlSegmentsAsync()).join("-")}.${NGROK_CONFIG.domain}`;
|
|
79
76
|
}
|
|
80
77
|
/** Exposed for testing. */ async _getProjectSubdomainAsync() {
|
|
81
78
|
return (await this._getIdentifyingUrlSegmentsAsync()).join("-");
|
|
@@ -157,7 +154,6 @@ class AsyncNgrok {
|
|
|
157
154
|
const url = await instance.connect({
|
|
158
155
|
...urlProps,
|
|
159
156
|
authtoken: NGROK_CONFIG.authToken,
|
|
160
|
-
proto: "http",
|
|
161
157
|
configPath,
|
|
162
158
|
onStatusChange (status) {
|
|
163
159
|
if (status === "closed") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/start/server/AsyncNgrok.ts"],"sourcesContent":["import chalk from 'chalk';\nimport crypto from 'crypto';\nimport * as path from 'path';\nimport slugify from 'slugify';\n\nimport UserSettings from '../../api/user/UserSettings';\nimport { getActorDisplayName, getUserAsync } from '../../api/user/user';\nimport * as Log from '../../log';\nimport { delayAsync, resolveWithTimeout } from '../../utils/delay';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { isNgrokClientError, NgrokInstance, NgrokResolver } from '../doctor/ngrok/NgrokResolver';\nimport { hasAdbReverseAsync, startAdbReverseAsync } from '../platforms/android/adbReverse';\nimport { ProjectSettings } from '../project/settings';\n\nconst debug = require('debug')('expo:start:server:ngrok') as typeof console.log;\n\nconst NGROK_CONFIG = {\n authToken: '5W1bR67GNbWcXqmxZzBG1_56GezNeaX6sSRvn8npeQ8',\n domain: 'exp.direct',\n};\n\nconst TUNNEL_TIMEOUT = 10 * 1000;\n\nexport class AsyncNgrok {\n /** Resolves the best instance of ngrok, exposed for testing. */\n resolver: NgrokResolver;\n\n /** Info about the currently running instance of ngrok. */\n private serverUrl: string | null = null;\n\n constructor(\n private projectRoot: string,\n private port: number\n ) {\n this.resolver = new NgrokResolver(projectRoot);\n }\n\n public getActiveUrl(): string | null {\n return this.serverUrl;\n }\n\n /** Exposed for testing. */\n async _getIdentifyingUrlSegmentsAsync(): Promise<string[]> {\n const user = await getUserAsync();\n if (user?.__typename === 'Robot') {\n throw new CommandError('NGROK_ROBOT', 'Cannot use ngrok with a robot user.');\n }\n const username = getActorDisplayName(user);\n\n return [\n // NOTE: https://github.com/expo/expo/pull/16556#discussion_r822944286\n await this.getProjectRandomnessAsync(),\n slugify(username),\n // Use the port to distinguish between multiple tunnels (webpack, metro).\n String(this.port),\n ];\n }\n\n /** Exposed for testing. */\n async _getProjectHostnameAsync(): Promise<string> {\n return [...(await this._getIdentifyingUrlSegmentsAsync()), NGROK_CONFIG.domain].join('.');\n }\n\n /** Exposed for testing. */\n async _getProjectSubdomainAsync(): Promise<string> {\n return (await this._getIdentifyingUrlSegmentsAsync()).join('-');\n }\n\n /** Start ngrok on the given port for the project. */\n async startAsync({ timeout }: { timeout?: number } = {}): Promise<void> {\n // Ensure the instance is loaded first, this can linger so we should run it before the timeout.\n await this.resolver.resolveAsync({\n // For now, prefer global install since the package has native code (harder to install) and doesn't change very often.\n prefersGlobalInstall: true,\n });\n\n // NOTE(EvanBacon): If the user doesn't have ADB installed,\n // then skip attempting to reverse the port.\n if (hasAdbReverseAsync()) {\n // Ensure ADB reverse is running.\n if (!(await startAdbReverseAsync([this.port]))) {\n // TODO: Better error message.\n throw new CommandError(\n 'NGROK_ADB',\n `Cannot start tunnel URL because \\`adb reverse\\` failed for the connected Android device(s).`\n );\n }\n }\n\n this.serverUrl = await this._connectToNgrokAsync({ timeout });\n\n debug('Tunnel URL:', this.serverUrl);\n Log.log('Tunnel ready.');\n }\n\n /** Stop the ngrok process if it's running. */\n public async stopAsync(): Promise<void> {\n debug('Stopping Tunnel');\n\n await this.resolver.get()?.kill?.();\n this.serverUrl = null;\n }\n\n /** Exposed for testing. */\n async _connectToNgrokAsync(\n options: { timeout?: number } = {},\n attempts: number = 0\n ): Promise<string> {\n // Attempt to stop any hanging processes, this increases the chances of a successful connection.\n await this.stopAsync();\n\n // Get the instance quietly or assert otherwise.\n const instance = await this.resolver.resolveAsync({\n shouldPrompt: false,\n autoInstall: false,\n });\n\n // TODO(Bacon): Consider dropping the timeout functionality:\n // https://github.com/expo/expo/pull/16556#discussion_r822307373\n const results = await resolveWithTimeout(\n () => this.connectToNgrokInternalAsync(instance, attempts),\n {\n timeout: options.timeout ?? TUNNEL_TIMEOUT,\n errorMessage: 'ngrok tunnel took too long to connect.',\n }\n );\n if (typeof results === 'string') {\n return results;\n }\n\n // Wait 100ms and then try again\n await delayAsync(100);\n\n return this._connectToNgrokAsync(options, attempts + 1);\n }\n\n private async _getConnectionPropsAsync(): Promise<{ hostname?: string; subdomain?: string }> {\n const userDefinedSubdomain = env.EXPO_TUNNEL_SUBDOMAIN;\n if (userDefinedSubdomain) {\n const subdomain =\n typeof userDefinedSubdomain === 'string'\n ? userDefinedSubdomain\n : await this._getProjectSubdomainAsync();\n debug('Subdomain:', subdomain);\n return { subdomain };\n } else {\n const hostname = await this._getProjectHostnameAsync();\n debug('Hostname:', hostname);\n return { hostname };\n }\n }\n\n private async connectToNgrokInternalAsync(\n instance: NgrokInstance,\n attempts: number = 0\n ): Promise<string | false> {\n try {\n // Global config path.\n const configPath = path.join(UserSettings.getDirectory(), 'ngrok.yml');\n debug('Global config path:', configPath);\n const urlProps = await this._getConnectionPropsAsync();\n\n const url = await instance.connect({\n ...urlProps,\n authtoken: NGROK_CONFIG.authToken,\n proto: 'http',\n configPath,\n onStatusChange(status) {\n if (status === 'closed') {\n Log.error(\n chalk.red(\n 'Tunnel connection has been closed. This is often related to intermittent connection problems with the Ngrok servers. Restart the dev server to try connecting to Ngrok again.'\n ) + chalk.gray('\\nCheck the Ngrok status page for outages: https://status.ngrok.com/')\n );\n } else if (status === 'connected') {\n Log.log('Tunnel connected.');\n }\n },\n port: this.port,\n });\n return url;\n } catch (error: any) {\n const assertNgrok = () => {\n if (isNgrokClientError(error)) {\n throw new CommandError(\n 'NGROK_CONNECT',\n [\n error.body.msg,\n error.body.details?.err,\n chalk.gray('Check the Ngrok status page for outages: https://status.ngrok.com/'),\n ]\n .filter(Boolean)\n .join('\\n\\n')\n );\n }\n throw new CommandError(\n 'NGROK_CONNECT',\n error.toString() +\n chalk.gray('\\nCheck the Ngrok status page for outages: https://status.ngrok.com/')\n );\n };\n\n // Attempt to connect 3 times\n if (attempts >= 2) {\n assertNgrok();\n }\n\n // Attempt to fix the issue\n if (isNgrokClientError(error) && error.body.error_code === 103) {\n // Assert early if a custom subdomain is used since it cannot\n // be changed and retried. If the tunnel subdomain is a boolean\n // then we can reset the randomness and try again.\n if (typeof env.EXPO_TUNNEL_SUBDOMAIN === 'string') {\n assertNgrok();\n }\n // Change randomness to avoid conflict if killing ngrok doesn't help\n await this._resetProjectRandomnessAsync();\n }\n\n return false;\n }\n }\n\n private async getProjectRandomnessAsync() {\n const { urlRandomness: randomness } = await ProjectSettings.readAsync(this.projectRoot);\n if (randomness) {\n return randomness;\n }\n return await this._resetProjectRandomnessAsync();\n }\n\n async _resetProjectRandomnessAsync() {\n const randomness = crypto.randomBytes(5).toString('base64url');\n await ProjectSettings.setAsync(this.projectRoot, { urlRandomness: randomness });\n debug('Resetting project randomness:', randomness);\n return randomness;\n }\n}\n"],"names":["path","Log","debug","require","NGROK_CONFIG","authToken","domain","TUNNEL_TIMEOUT","AsyncNgrok","constructor","projectRoot","port","serverUrl","resolver","NgrokResolver","getActiveUrl","_getIdentifyingUrlSegmentsAsync","user","getUserAsync","__typename","CommandError","username","getActorDisplayName","getProjectRandomnessAsync","slugify","String","_getProjectHostnameAsync","join","_getProjectSubdomainAsync","startAsync","timeout","resolveAsync","prefersGlobalInstall","hasAdbReverseAsync","startAdbReverseAsync","_connectToNgrokAsync","log","stopAsync","get","kill","options","attempts","instance","shouldPrompt","autoInstall","results","resolveWithTimeout","connectToNgrokInternalAsync","errorMessage","delayAsync","_getConnectionPropsAsync","userDefinedSubdomain","env","EXPO_TUNNEL_SUBDOMAIN","subdomain","hostname","configPath","UserSettings","getDirectory","urlProps","url","connect","authtoken","proto","onStatusChange","status","error","chalk","red","gray","assertNgrok","isNgrokClientError","body","msg","details","err","filter","Boolean","toString","error_code","_resetProjectRandomnessAsync","urlRandomness","randomness","ProjectSettings","readAsync","crypto","randomBytes","setAsync"],"mappings":"AAAA;;;;AAAkB,IAAA,MAAO,kCAAP,OAAO,EAAA;AACN,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACfA,IAAAA,IAAI,mCAAM,MAAM,EAAZ;AACI,IAAA,QAAS,kCAAT,SAAS,EAAA;AAEJ,IAAA,aAA6B,kCAA7B,6BAA6B,EAAA;AACJ,IAAA,KAAqB,WAArB,qBAAqB,CAAA;AAC3DC,IAAAA,GAAG,mCAAM,WAAW,EAAjB;AACgC,IAAA,MAAmB,WAAnB,mBAAmB,CAAA;AAC9C,IAAA,IAAiB,WAAjB,iBAAiB,CAAA;AACR,IAAA,OAAoB,WAApB,oBAAoB,CAAA;AACgB,IAAA,cAA+B,WAA/B,+BAA+B,CAAA;AACvC,IAAA,WAAiC,WAAjC,iCAAiC,CAAA;AAC1D,IAAA,SAAqB,WAArB,qBAAqB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErD,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,yBAAyB,CAAC,AAAsB,AAAC;AAEhF,MAAMC,YAAY,GAAG;IACnBC,SAAS,EAAE,6CAA6C;IACxDC,MAAM,EAAE,YAAY;CACrB,AAAC;AAEF,MAAMC,cAAc,GAAG,EAAE,GAAG,IAAI,AAAC;AAE1B,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QAC/D,MAAMK,SAAe,gBAAA,CAACI,QAAQ,CAAC,IAAI,CAAC7E,WAAW,EAAE;YAAEuE,aAAa,EAAEC,UAAU;SAAE,CAAC,CAAC;QAChFhF,KAAK,CAAC,+BAA+B,EAAEgF,UAAU,CAAC,CAAC;QACnD,OAAOA,UAAU,CAAC;KACnB;CACF;QAtNY1E,UAAU,GAAVA,UAAU"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/start/server/AsyncNgrok.ts"],"sourcesContent":["import chalk from 'chalk';\nimport crypto from 'crypto';\nimport * as path from 'path';\nimport slugify from 'slugify';\n\nimport UserSettings from '../../api/user/UserSettings';\nimport { getActorDisplayName, getUserAsync } from '../../api/user/user';\nimport * as Log from '../../log';\nimport { delayAsync, resolveWithTimeout } from '../../utils/delay';\nimport { env } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { isNgrokClientError, NgrokInstance, NgrokResolver } from '../doctor/ngrok/NgrokResolver';\nimport { hasAdbReverseAsync, startAdbReverseAsync } from '../platforms/android/adbReverse';\nimport { ProjectSettings } from '../project/settings';\n\nconst debug = require('debug')('expo:start:server:ngrok') as typeof console.log;\n\nconst NGROK_CONFIG = {\n authToken: '5W1bR67GNbWcXqmxZzBG1_56GezNeaX6sSRvn8npeQ8',\n domain: 'exp.direct',\n};\n\nconst TUNNEL_TIMEOUT = 10 * 1000;\n\nexport class AsyncNgrok {\n /** Resolves the best instance of ngrok, exposed for testing. */\n resolver: NgrokResolver;\n\n /** Info about the currently running instance of ngrok. */\n private serverUrl: string | null = null;\n\n constructor(\n private projectRoot: string,\n private port: number\n ) {\n this.resolver = new NgrokResolver(projectRoot);\n }\n\n public getActiveUrl(): string | null {\n return this.serverUrl;\n }\n\n /** Exposed for testing. */\n async _getIdentifyingUrlSegmentsAsync(): Promise<string[]> {\n const user = await getUserAsync();\n if (user?.__typename === 'Robot') {\n throw new CommandError('NGROK_ROBOT', 'Cannot use ngrok with a robot user.');\n }\n const username = getActorDisplayName(user);\n\n return [\n // NOTE: https://github.com/expo/expo/pull/16556#discussion_r822944286\n await this.getProjectRandomnessAsync(),\n slugify(username),\n // Use the port to distinguish between multiple tunnels (webpack, metro).\n String(this.port),\n ];\n }\n\n /** Exposed for testing. */\n async _getProjectHostnameAsync(): Promise<string> {\n return `${(await this._getIdentifyingUrlSegmentsAsync()).join('-')}.${NGROK_CONFIG.domain}`;\n }\n\n /** Exposed for testing. */\n async _getProjectSubdomainAsync(): Promise<string> {\n return (await this._getIdentifyingUrlSegmentsAsync()).join('-');\n }\n\n /** Start ngrok on the given port for the project. */\n async startAsync({ timeout }: { timeout?: number } = {}): Promise<void> {\n // Ensure the instance is loaded first, this can linger so we should run it before the timeout.\n await this.resolver.resolveAsync({\n // For now, prefer global install since the package has native code (harder to install) and doesn't change very often.\n prefersGlobalInstall: true,\n });\n\n // NOTE(EvanBacon): If the user doesn't have ADB installed,\n // then skip attempting to reverse the port.\n if (hasAdbReverseAsync()) {\n // Ensure ADB reverse is running.\n if (!(await startAdbReverseAsync([this.port]))) {\n // TODO: Better error message.\n throw new CommandError(\n 'NGROK_ADB',\n `Cannot start tunnel URL because \\`adb reverse\\` failed for the connected Android device(s).`\n );\n }\n }\n\n this.serverUrl = await this._connectToNgrokAsync({ timeout });\n\n debug('Tunnel URL:', this.serverUrl);\n Log.log('Tunnel ready.');\n }\n\n /** Stop the ngrok process if it's running. */\n public async stopAsync(): Promise<void> {\n debug('Stopping Tunnel');\n\n await this.resolver.get()?.kill?.();\n this.serverUrl = null;\n }\n\n /** Exposed for testing. */\n async _connectToNgrokAsync(\n options: { timeout?: number } = {},\n attempts: number = 0\n ): Promise<string> {\n // Attempt to stop any hanging processes, this increases the chances of a successful connection.\n await this.stopAsync();\n\n // Get the instance quietly or assert otherwise.\n const instance = await this.resolver.resolveAsync({\n shouldPrompt: false,\n autoInstall: false,\n });\n\n // TODO(Bacon): Consider dropping the timeout functionality:\n // https://github.com/expo/expo/pull/16556#discussion_r822307373\n const results = await resolveWithTimeout(\n () => this.connectToNgrokInternalAsync(instance, attempts),\n {\n timeout: options.timeout ?? TUNNEL_TIMEOUT,\n errorMessage: 'ngrok tunnel took too long to connect.',\n }\n );\n if (typeof results === 'string') {\n return results;\n }\n\n // Wait 100ms and then try again\n await delayAsync(100);\n\n return this._connectToNgrokAsync(options, attempts + 1);\n }\n\n private async _getConnectionPropsAsync(): Promise<{ hostname?: string; subdomain?: string }> {\n const userDefinedSubdomain = env.EXPO_TUNNEL_SUBDOMAIN;\n if (userDefinedSubdomain) {\n const subdomain =\n typeof userDefinedSubdomain === 'string'\n ? userDefinedSubdomain\n : await this._getProjectSubdomainAsync();\n debug('Subdomain:', subdomain);\n return { subdomain };\n } else {\n const hostname = await this._getProjectHostnameAsync();\n debug('Hostname:', hostname);\n return { hostname };\n }\n }\n\n private async connectToNgrokInternalAsync(\n instance: NgrokInstance,\n attempts: number = 0\n ): Promise<string | false> {\n try {\n // Global config path.\n const configPath = path.join(UserSettings.getDirectory(), 'ngrok.yml');\n debug('Global config path:', configPath);\n const urlProps = await this._getConnectionPropsAsync();\n\n const url = await instance.connect({\n ...urlProps,\n authtoken: NGROK_CONFIG.authToken,\n configPath,\n onStatusChange(status) {\n if (status === 'closed') {\n Log.error(\n chalk.red(\n 'Tunnel connection has been closed. This is often related to intermittent connection problems with the Ngrok servers. Restart the dev server to try connecting to Ngrok again.'\n ) + chalk.gray('\\nCheck the Ngrok status page for outages: https://status.ngrok.com/')\n );\n } else if (status === 'connected') {\n Log.log('Tunnel connected.');\n }\n },\n port: this.port,\n });\n return url;\n } catch (error: any) {\n const assertNgrok = () => {\n if (isNgrokClientError(error)) {\n throw new CommandError(\n 'NGROK_CONNECT',\n [\n error.body.msg,\n error.body.details?.err,\n chalk.gray('Check the Ngrok status page for outages: https://status.ngrok.com/'),\n ]\n .filter(Boolean)\n .join('\\n\\n')\n );\n }\n throw new CommandError(\n 'NGROK_CONNECT',\n error.toString() +\n chalk.gray('\\nCheck the Ngrok status page for outages: https://status.ngrok.com/')\n );\n };\n\n // Attempt to connect 3 times\n if (attempts >= 2) {\n assertNgrok();\n }\n\n // Attempt to fix the issue\n if (isNgrokClientError(error) && error.body.error_code === 103) {\n // Assert early if a custom subdomain is used since it cannot\n // be changed and retried. If the tunnel subdomain is a boolean\n // then we can reset the randomness and try again.\n if (typeof env.EXPO_TUNNEL_SUBDOMAIN === 'string') {\n assertNgrok();\n }\n // Change randomness to avoid conflict if killing ngrok doesn't help\n await this._resetProjectRandomnessAsync();\n }\n\n return false;\n }\n }\n\n private async getProjectRandomnessAsync() {\n const { urlRandomness: randomness } = await ProjectSettings.readAsync(this.projectRoot);\n if (randomness) {\n return randomness;\n }\n return await this._resetProjectRandomnessAsync();\n }\n\n async _resetProjectRandomnessAsync() {\n const randomness = crypto.randomBytes(5).toString('base64url');\n await ProjectSettings.setAsync(this.projectRoot, { urlRandomness: randomness });\n debug('Resetting project randomness:', randomness);\n return randomness;\n }\n}\n"],"names":["path","Log","debug","require","NGROK_CONFIG","authToken","domain","TUNNEL_TIMEOUT","AsyncNgrok","constructor","projectRoot","port","serverUrl","resolver","NgrokResolver","getActiveUrl","_getIdentifyingUrlSegmentsAsync","user","getUserAsync","__typename","CommandError","username","getActorDisplayName","getProjectRandomnessAsync","slugify","String","_getProjectHostnameAsync","join","_getProjectSubdomainAsync","startAsync","timeout","resolveAsync","prefersGlobalInstall","hasAdbReverseAsync","startAdbReverseAsync","_connectToNgrokAsync","log","stopAsync","get","kill","options","attempts","instance","shouldPrompt","autoInstall","results","resolveWithTimeout","connectToNgrokInternalAsync","errorMessage","delayAsync","_getConnectionPropsAsync","userDefinedSubdomain","env","EXPO_TUNNEL_SUBDOMAIN","subdomain","hostname","configPath","UserSettings","getDirectory","urlProps","url","connect","authtoken","onStatusChange","status","error","chalk","red","gray","assertNgrok","isNgrokClientError","body","msg","details","err","filter","Boolean","toString","error_code","_resetProjectRandomnessAsync","urlRandomness","randomness","ProjectSettings","readAsync","crypto","randomBytes","setAsync"],"mappings":"AAAA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CAAC;aACf;YAED,2BAA2B;YAC3B,IAAIC,CAAAA,GAAAA,cAAkB,AAAO,CAAA,mBAAP,CAACL,KAAK,CAAC,IAAIA,KAAK,CAACM,IAAI,CAACO,UAAU,KAAK,GAAG,EAAE;gBAC9D,6DAA6D;gBAC7D,+DAA+D;gBAC/D,kDAAkD;gBAClD,IAAI,OAAO1B,IAAG,IAAA,CAACC,qBAAqB,KAAK,QAAQ,EAAE;oBACjDgB,WAAW,EAAE,CAAC;iBACf;gBACD,oEAAoE;gBACpE,MAAM,IAAI,CAACU,4BAA4B,EAAE,CAAC;aAC3C;YAED,OAAO,KAAK,CAAC;SACd;KACF;IAED,MAAcxD,yBAAyB,GAAG;QACxC,MAAM,EAAEyD,aAAa,EAAEC,UAAU,CAAA,EAAE,GAAG,MAAMC,SAAe,gBAAA,CAACC,SAAS,CAAC,IAAI,CAACzE,WAAW,CAAC,AAAC;QACxF,IAAIuE,UAAU,EAAE;YACd,OAAOA,UAAU,CAAC;SACnB;QACD,OAAO,MAAM,IAAI,CAACF,4BAA4B,EAAE,CAAC;KAClD;IAED,MAAMA,4BAA4B,GAAG;QACnC,MAAME,UAAU,GAAGG,OAAM,QAAA,CAACC,WAAW,CAAC,CAAC,CAAC,CAACR,QAAQ,CAAC,WAAW,CAAC,AAAC;QAC/D,MAAMK,SAAe,gBAAA,CAACI,QAAQ,CAAC,IAAI,CAAC5E,WAAW,EAAE;YAAEsE,aAAa,EAAEC,UAAU;SAAE,CAAC,CAAC;QAChF/E,KAAK,CAAC,+BAA+B,EAAE+E,UAAU,CAAC,CAAC;QACnD,OAAOA,UAAU,CAAC;KACnB;CACF;QArNYzE,UAAU,GAAVA,UAAU"}
|
|
@@ -62,7 +62,7 @@ class UrlCreator {
|
|
|
62
62
|
return loadingUrl;
|
|
63
63
|
}
|
|
64
64
|
/** Create a URI for launching in a native dev client. Returns `null` when no `scheme` can be resolved. */ constructDevClientUrl(options) {
|
|
65
|
-
var ref;
|
|
65
|
+
var ref, ref1;
|
|
66
66
|
const protocol = (options == null ? void 0 : options.scheme) || ((ref = this.defaults) == null ? void 0 : ref.scheme);
|
|
67
67
|
if (!protocol || // Prohibit the use of http(s) in dev client URIs since they'll never be valid.
|
|
68
68
|
[
|
|
@@ -74,7 +74,7 @@ class UrlCreator {
|
|
|
74
74
|
}
|
|
75
75
|
const manifestUrl = this.constructUrl({
|
|
76
76
|
...options,
|
|
77
|
-
scheme: "http"
|
|
77
|
+
scheme: ((ref1 = this.defaults) == null ? void 0 : ref1.hostType) === "tunnel" ? "https" : "http"
|
|
78
78
|
});
|
|
79
79
|
const devClientUrl = `${protocol}://expo-development-client/?url=${encodeURIComponent(manifestUrl)}`;
|
|
80
80
|
debug(`Dev client URL: ${devClientUrl} -- manifestUrl: ${manifestUrl} -- %O`, options);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/start/server/UrlCreator.ts"],"sourcesContent":["import assert from 'assert';\nimport { URL } from 'url';\n\nimport * as Log from '../../log';\nimport { getIpAddress } from '../../utils/ip';\n\nconst debug = require('debug')('expo:start:server:urlCreator') as typeof console.log;\n\nexport interface CreateURLOptions {\n /** URL scheme to use when opening apps in custom runtimes. */\n scheme?: string | null;\n /** Type of dev server host to use. */\n hostType?: 'localhost' | 'lan' | 'tunnel';\n /** Requested hostname. */\n hostname?: string | null;\n}\n\ninterface UrlComponents {\n port: string;\n hostname: string;\n protocol: string;\n}\nexport class UrlCreator {\n constructor(\n public defaults: CreateURLOptions | undefined,\n private bundlerInfo: { port: number; getTunnelUrl?: () => string | null }\n ) {}\n\n /**\n * Return a URL for the \"loading\" interstitial page that is used to disambiguate which\n * native runtime to open the dev server with.\n *\n * @param options options for creating the URL\n * @param platform when opening the URL from the CLI to a connected device we can specify the platform as a query parameter, otherwise it will be inferred from the unsafe user agent sniffing.\n *\n * @returns URL like `http://localhost:8081/_expo/loading?platform=ios`\n * @returns URL like `http://localhost:8081/_expo/loading` when no platform is provided.\n */\n public constructLoadingUrl(options: CreateURLOptions, platform: string | null): string {\n const url = new URL('_expo/loading', this.constructUrl({ scheme: 'http', ...options }));\n if (platform) {\n url.search = new URLSearchParams({ platform }).toString();\n }\n const loadingUrl = url.toString();\n debug(`Loading URL: ${loadingUrl}`);\n return loadingUrl;\n }\n\n /** Create a URI for launching in a native dev client. Returns `null` when no `scheme` can be resolved. */\n public constructDevClientUrl(options?: CreateURLOptions): null | string {\n const protocol = options?.scheme || this.defaults?.scheme;\n\n if (\n !protocol ||\n // Prohibit the use of http(s) in dev client URIs since they'll never be valid.\n ['http', 'https'].includes(protocol.toLowerCase()) ||\n // Prohibit the use of `_` characters in the protocol, Node will throw an error when parsing these URLs\n protocol.includes('_')\n ) {\n return null;\n }\n\n const manifestUrl = this.constructUrl({ ...options, scheme: 'http' });\n const devClientUrl = `${protocol}://expo-development-client/?url=${encodeURIComponent(\n manifestUrl\n )}`;\n debug(`Dev client URL: ${devClientUrl} -- manifestUrl: ${manifestUrl} -- %O`, options);\n return devClientUrl;\n }\n\n /** Create a generic URL. */\n public constructUrl(options?: Partial<CreateURLOptions> | null): string {\n const urlComponents = this.getUrlComponents({\n ...this.defaults,\n ...options,\n });\n const url = joinUrlComponents(urlComponents);\n debug(`URL: ${url}`);\n return url;\n }\n\n /** Get the URL components from the Ngrok server URL. */\n private getTunnelUrlComponents(options: Pick<CreateURLOptions, 'scheme'>): UrlComponents | null {\n const tunnelUrl = this.bundlerInfo.getTunnelUrl?.();\n if (!tunnelUrl) {\n return null;\n }\n const parsed = new URL(tunnelUrl);\n return {\n port: parsed.port,\n hostname: parsed.hostname,\n protocol: options.scheme ?? 'http',\n };\n }\n\n private getUrlComponents(options: CreateURLOptions): UrlComponents {\n // Proxy comes first.\n const proxyURL = getProxyUrl();\n if (proxyURL) {\n return getUrlComponentsFromProxyUrl(options, proxyURL);\n }\n\n // Ngrok.\n if (options.hostType === 'tunnel') {\n const components = this.getTunnelUrlComponents(options);\n if (components) {\n return components;\n }\n Log.warn('Tunnel URL not found (it might not be ready yet), falling back to LAN URL.');\n } else if (options.hostType === 'localhost' && !options.hostname) {\n options.hostname = 'localhost';\n }\n\n return {\n hostname: getDefaultHostname(options),\n port: this.bundlerInfo.port.toString(),\n protocol: options.scheme ?? 'http',\n };\n }\n}\n\nfunction getUrlComponentsFromProxyUrl(\n options: Pick<CreateURLOptions, 'scheme'>,\n url: string\n): UrlComponents {\n const parsedProxyUrl = new URL(url);\n let protocol = options.scheme ?? 'http';\n if (parsedProxyUrl.protocol === 'https:') {\n if (protocol === 'http') {\n protocol = 'https';\n }\n if (!parsedProxyUrl.port) {\n parsedProxyUrl.port = '443';\n }\n }\n return {\n port: parsedProxyUrl.port,\n hostname: parsedProxyUrl.hostname,\n protocol,\n };\n}\n\nfunction getDefaultHostname(options: Pick<CreateURLOptions, 'hostname'>) {\n // TODO: Drop REACT_NATIVE_PACKAGER_HOSTNAME\n if (process.env.REACT_NATIVE_PACKAGER_HOSTNAME) {\n return process.env.REACT_NATIVE_PACKAGER_HOSTNAME.trim();\n } else if (options.hostname === 'localhost') {\n // Restrict the use of `localhost`\n // TODO: Note why we do this.\n return '127.0.0.1';\n }\n\n return options.hostname || getIpAddress();\n}\n\nfunction joinUrlComponents({ protocol, hostname, port }: Partial<UrlComponents>): string {\n assert(hostname, 'hostname cannot be inferred.');\n const validProtocol = protocol ? `${protocol}://` : '';\n\n const url = `${validProtocol}${hostname}`;\n\n if (port) {\n return url + `:${port}`;\n }\n\n return url;\n}\n\n/** @deprecated */\nfunction getProxyUrl(): string | undefined {\n return process.env.EXPO_PACKAGER_PROXY_URL;\n}\n\n// TODO: Drop the undocumented env variables:\n// REACT_NATIVE_PACKAGER_HOSTNAME\n// EXPO_PACKAGER_PROXY_URL\n"],"names":["Log","debug","require","UrlCreator","constructor","defaults","bundlerInfo","constructLoadingUrl","options","platform","url","URL","constructUrl","scheme","search","URLSearchParams","toString","loadingUrl","constructDevClientUrl","protocol","includes","toLowerCase","manifestUrl","devClientUrl","encodeURIComponent","urlComponents","getUrlComponents","joinUrlComponents","getTunnelUrlComponents","tunnelUrl","getTunnelUrl","parsed","port","hostname","proxyURL","getProxyUrl","getUrlComponentsFromProxyUrl","hostType","components","warn","getDefaultHostname","parsedProxyUrl","process","env","REACT_NATIVE_PACKAGER_HOSTNAME","trim","getIpAddress","assert","validProtocol","EXPO_PACKAGER_PROXY_URL"],"mappings":"AAAA;;;;AAAmB,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACP,IAAA,IAAK,WAAL,KAAK,CAAA;AAEbA,IAAAA,GAAG,mCAAM,WAAW,EAAjB;AACc,IAAA,GAAgB,WAAhB,gBAAgB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE7C,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,8BAA8B,CAAC,AAAsB,AAAC;AAgB9E,MAAMC,UAAU;IACrBC,YACSC,QAAsC,EACrCC,WAAiE,CACzE;aAFOD,QAAsC,GAAtCA,QAAsC;aACrCC,WAAiE,GAAjEA,WAAiE;KACvE;IAEJ;;;;;;;;;KASG,CACH,AAAOC,mBAAmB,CAACC,OAAyB,EAAEC,QAAuB,EAAU;QACrF,MAAMC,GAAG,GAAG,IAAIC,IAAG,IAAA,CAAC,eAAe,EAAE,IAAI,CAACC,YAAY,CAAC;YAAEC,MAAM,EAAE,MAAM;YAAE,GAAGL,OAAO;SAAE,CAAC,CAAC,AAAC;QACxF,IAAIC,QAAQ,EAAE;YACZC,GAAG,CAACI,MAAM,GAAG,IAAIC,eAAe,CAAC;gBAAEN,QAAQ;aAAE,CAAC,CAACO,QAAQ,EAAE,CAAC;SAC3D;QACD,MAAMC,UAAU,GAAGP,GAAG,CAACM,QAAQ,EAAE,AAAC;QAClCf,KAAK,CAAC,CAAC,aAAa,EAAEgB,UAAU,CAAC,CAAC,CAAC,CAAC;QACpC,OAAOA,UAAU,CAAC;KACnB;IAED,0GAA0G,CAC1G,AAAOC,qBAAqB,CAACV,OAA0B,EAAiB;YAClC,GA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A,EAAED,IAAI,CAAA,EAA0B,EAAU;IACvFe,CAAAA,GAAAA,OAAM,AAA0C,CAAA,QAA1C,CAACd,QAAQ,EAAE,8BAA8B,CAAC,CAAC;IACjD,MAAMe,aAAa,GAAG7B,QAAQ,GAAG,CAAC,EAAEA,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,AAAC;IAEvD,MAAMT,GAAG,GAAG,CAAC,EAAEsC,aAAa,CAAC,EAAEf,QAAQ,CAAC,CAAC,AAAC;IAE1C,IAAID,IAAI,EAAE;QACR,OAAOtB,GAAG,GAAG,CAAC,CAAC,EAAEsB,IAAI,CAAC,CAAC,CAAC;KACzB;IAED,OAAOtB,GAAG,CAAC;CACZ;AAED,kBAAkB,CAClB,SAASyB,WAAW,GAAuB;IACzC,OAAOO,OAAO,CAACC,GAAG,CAACM,uBAAuB,CAAC;CAC5C,CAED,6CAA6C;CAC7C,iCAAiC;CACjC,0BAA0B"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/start/server/UrlCreator.ts"],"sourcesContent":["import assert from 'assert';\nimport { URL } from 'url';\n\nimport * as Log from '../../log';\nimport { getIpAddress } from '../../utils/ip';\n\nconst debug = require('debug')('expo:start:server:urlCreator') as typeof console.log;\n\nexport interface CreateURLOptions {\n /** URL scheme to use when opening apps in custom runtimes. */\n scheme?: string | null;\n /** Type of dev server host to use. */\n hostType?: 'localhost' | 'lan' | 'tunnel';\n /** Requested hostname. */\n hostname?: string | null;\n}\n\ninterface UrlComponents {\n port: string;\n hostname: string;\n protocol: string;\n}\nexport class UrlCreator {\n constructor(\n public defaults: CreateURLOptions | undefined,\n private bundlerInfo: { port: number; getTunnelUrl?: () => string | null }\n ) {}\n\n /**\n * Return a URL for the \"loading\" interstitial page that is used to disambiguate which\n * native runtime to open the dev server with.\n *\n * @param options options for creating the URL\n * @param platform when opening the URL from the CLI to a connected device we can specify the platform as a query parameter, otherwise it will be inferred from the unsafe user agent sniffing.\n *\n * @returns URL like `http://localhost:8081/_expo/loading?platform=ios`\n * @returns URL like `http://localhost:8081/_expo/loading` when no platform is provided.\n */\n public constructLoadingUrl(options: CreateURLOptions, platform: string | null): string {\n const url = new URL('_expo/loading', this.constructUrl({ scheme: 'http', ...options }));\n if (platform) {\n url.search = new URLSearchParams({ platform }).toString();\n }\n const loadingUrl = url.toString();\n debug(`Loading URL: ${loadingUrl}`);\n return loadingUrl;\n }\n\n /** Create a URI for launching in a native dev client. Returns `null` when no `scheme` can be resolved. */\n public constructDevClientUrl(options?: CreateURLOptions): null | string {\n const protocol = options?.scheme || this.defaults?.scheme;\n\n if (\n !protocol ||\n // Prohibit the use of http(s) in dev client URIs since they'll never be valid.\n ['http', 'https'].includes(protocol.toLowerCase()) ||\n // Prohibit the use of `_` characters in the protocol, Node will throw an error when parsing these URLs\n protocol.includes('_')\n ) {\n return null;\n }\n\n const manifestUrl = this.constructUrl({\n ...options,\n scheme: this.defaults?.hostType === 'tunnel' ? 'https' : 'http',\n });\n const devClientUrl = `${protocol}://expo-development-client/?url=${encodeURIComponent(\n manifestUrl\n )}`;\n debug(`Dev client URL: ${devClientUrl} -- manifestUrl: ${manifestUrl} -- %O`, options);\n return devClientUrl;\n }\n\n /** Create a generic URL. */\n public constructUrl(options?: Partial<CreateURLOptions> | null): string {\n const urlComponents = this.getUrlComponents({\n ...this.defaults,\n ...options,\n });\n const url = joinUrlComponents(urlComponents);\n debug(`URL: ${url}`);\n return url;\n }\n\n /** Get the URL components from the Ngrok server URL. */\n private getTunnelUrlComponents(options: Pick<CreateURLOptions, 'scheme'>): UrlComponents | null {\n const tunnelUrl = this.bundlerInfo.getTunnelUrl?.();\n if (!tunnelUrl) {\n return null;\n }\n const parsed = new URL(tunnelUrl);\n return {\n port: parsed.port,\n hostname: parsed.hostname,\n protocol: options.scheme ?? 'http',\n };\n }\n\n private getUrlComponents(options: CreateURLOptions): UrlComponents {\n // Proxy comes first.\n const proxyURL = getProxyUrl();\n if (proxyURL) {\n return getUrlComponentsFromProxyUrl(options, proxyURL);\n }\n\n // Ngrok.\n if (options.hostType === 'tunnel') {\n const components = this.getTunnelUrlComponents(options);\n if (components) {\n return components;\n }\n Log.warn('Tunnel URL not found (it might not be ready yet), falling back to LAN URL.');\n } else if (options.hostType === 'localhost' && !options.hostname) {\n options.hostname = 'localhost';\n }\n\n return {\n hostname: getDefaultHostname(options),\n port: this.bundlerInfo.port.toString(),\n protocol: options.scheme ?? 'http',\n };\n }\n}\n\nfunction getUrlComponentsFromProxyUrl(\n options: Pick<CreateURLOptions, 'scheme'>,\n url: string\n): UrlComponents {\n const parsedProxyUrl = new URL(url);\n let protocol = options.scheme ?? 'http';\n if (parsedProxyUrl.protocol === 'https:') {\n if (protocol === 'http') {\n protocol = 'https';\n }\n if (!parsedProxyUrl.port) {\n parsedProxyUrl.port = '443';\n }\n }\n return {\n port: parsedProxyUrl.port,\n hostname: parsedProxyUrl.hostname,\n protocol,\n };\n}\n\nfunction getDefaultHostname(options: Pick<CreateURLOptions, 'hostname'>) {\n // TODO: Drop REACT_NATIVE_PACKAGER_HOSTNAME\n if (process.env.REACT_NATIVE_PACKAGER_HOSTNAME) {\n return process.env.REACT_NATIVE_PACKAGER_HOSTNAME.trim();\n } else if (options.hostname === 'localhost') {\n // Restrict the use of `localhost`\n // TODO: Note why we do this.\n return '127.0.0.1';\n }\n\n return options.hostname || getIpAddress();\n}\n\nfunction joinUrlComponents({ protocol, hostname, port }: Partial<UrlComponents>): string {\n assert(hostname, 'hostname cannot be inferred.');\n const validProtocol = protocol ? `${protocol}://` : '';\n\n const url = `${validProtocol}${hostname}`;\n\n if (port) {\n return url + `:${port}`;\n }\n\n return url;\n}\n\n/** @deprecated */\nfunction getProxyUrl(): string | undefined {\n return process.env.EXPO_PACKAGER_PROXY_URL;\n}\n\n// TODO: Drop the undocumented env variables:\n// REACT_NATIVE_PACKAGER_HOSTNAME\n// EXPO_PACKAGER_PROXY_URL\n"],"names":["Log","debug","require","UrlCreator","constructor","defaults","bundlerInfo","constructLoadingUrl","options","platform","url","URL","constructUrl","scheme","search","URLSearchParams","toString","loadingUrl","constructDevClientUrl","protocol","includes","toLowerCase","manifestUrl","hostType","devClientUrl","encodeURIComponent","urlComponents","getUrlComponents","joinUrlComponents","getTunnelUrlComponents","tunnelUrl","getTunnelUrl","parsed","port","hostname","proxyURL","getProxyUrl","getUrlComponentsFromProxyUrl","components","warn","getDefaultHostname","parsedProxyUrl","process","env","REACT_NATIVE_PACKAGER_HOSTNAME","trim","getIpAddress","assert","validProtocol","EXPO_PACKAGER_PROXY_URL"],"mappings":"AAAA;;;;AAAmB,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACP,IAAA,IAAK,WAAL,KAAK,CAAA;AAEbA,IAAAA,GAAG,mCAAM,WAAW,EAAjB;AACc,IAAA,GAAgB,WAAhB,gBAAgB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE7C,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,8BAA8B,CAAC,AAAsB,AAAC;AAgB9E,MAAMC,UAAU;IACrBC,YACSC,QAAsC,EACrCC,WAAiE,CACzE;aAFOD,QAAsC,GAAtCA,QAAsC;aACrCC,WAAiE,GAAjEA,WAAiE;KACvE;IAEJ;;;;;;;;;KASG,CACH,AAAOC,mBAAmB,CAACC,OAAyB,EAAEC,QAAuB,EAAU;QACrF,MAAMC,GAAG,GAAG,IAAIC,IAAG,IAAA,CAAC,eAAe,EAAE,IAAI,CAACC,YAAY,CAAC;YAAEC,MAAM,EAAE,MAAM;YAAE,GAAGL,OAAO;SAAE,CAAC,CAAC,AAAC;QACxF,IAAIC,QAAQ,EAAE;YACZC,GAAG,CAACI,MAAM,GAAG,IAAIC,eAAe,CAAC;gBAAEN,QAAQ;aAAE,CAAC,CAACO,QAAQ,EAAE,CAAC;SAC3D;QACD,MAAMC,UAAU,GAAGP,GAAG,CAACM,QAAQ,EAAE,AAAC;QAClCf,KAAK,CAAC,CAAC,aAAa,EAAEgB,UAAU,CAAC,CAAC,CAAC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,QAAQ,KAAK,WAAW,EAAE;QAC3C,kCAAkC;QAClC,6BAA6B;QAC7B,OAAO,WAAW,CAAC;KACpB;IAED,OAAO1B,OAAO,CAAC0B,QAAQ,IAAIY,CAAAA,GAAAA,GAAY,AAAE,CAAA,aAAF,EAAE,CAAC;CAC3C;AAED,SAASlB,iBAAiB,CAAC,EAAET,QAAQ,CAAA,EAAEe,QAAQ,CAAA,EAAED,IAAI,CAAA,EAA0B,EAAU;IACvFc,CAAAA,GAAAA,OAAM,AAA0C,CAAA,QAA1C,CAACb,QAAQ,EAAE,8BAA8B,CAAC,CAAC;IACjD,MAAMc,aAAa,GAAG7B,QAAQ,GAAG,CAAC,EAAEA,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,AAAC;IAEvD,MAAMT,GAAG,GAAG,CAAC,EAAEsC,aAAa,CAAC,EAAEd,QAAQ,CAAC,CAAC,AAAC;IAE1C,IAAID,IAAI,EAAE;QACR,OAAOvB,GAAG,GAAG,CAAC,CAAC,EAAEuB,IAAI,CAAC,CAAC,CAAC;KACzB;IAED,OAAOvB,GAAG,CAAC;CACZ;AAED,kBAAkB,CAClB,SAAS0B,WAAW,GAAuB;IACzC,OAAOM,OAAO,CAACC,GAAG,CAACM,uBAAuB,CAAC;CAC5C,CAED,6CAA6C;CAC7C,iCAAiC;CACjC,0BAA0B"}
|
|
@@ -13,6 +13,7 @@ var _resolveFrom = _interopRequireDefault(require("resolve-from"));
|
|
|
13
13
|
var _metroErrorInterface = require("./metro/metroErrorInterface");
|
|
14
14
|
var _manifestMiddleware = require("./middleware/ManifestMiddleware");
|
|
15
15
|
var _metroOptions = require("./middleware/metroOptions");
|
|
16
|
+
var _serverLogLikeMetro = require("./serverLogLikeMetro");
|
|
16
17
|
var _ansi = require("../../utils/ansi");
|
|
17
18
|
var _delay = require("../../utils/delay");
|
|
18
19
|
var _errors = require("../../utils/errors");
|
|
@@ -186,11 +187,7 @@ function evalMetroAndWrapFunctions(projectRoot, script, filename) {
|
|
|
186
187
|
}, {});
|
|
187
188
|
}
|
|
188
189
|
function evalMetro(projectRoot, src, filename) {
|
|
189
|
-
|
|
190
|
-
log: console.log,
|
|
191
|
-
warn: console.warn,
|
|
192
|
-
error: console.error
|
|
193
|
-
};
|
|
190
|
+
(0, _serverLogLikeMetro).augmentLogs(projectRoot);
|
|
194
191
|
try {
|
|
195
192
|
return (0, _profile).profile(_requireFromString.default, "eval-metro-bundle")(src, filename);
|
|
196
193
|
} catch (error) {
|
|
@@ -206,12 +203,7 @@ function evalMetro(projectRoot, src, filename) {
|
|
|
206
203
|
} else {
|
|
207
204
|
throw error;
|
|
208
205
|
}
|
|
209
|
-
} finally{
|
|
210
|
-
// Restore the original console in case it was modified.
|
|
211
|
-
console.log = originalConsole.log;
|
|
212
|
-
console.warn = originalConsole.warn;
|
|
213
|
-
console.error = originalConsole.error;
|
|
214
|
-
}
|
|
206
|
+
} finally{}
|
|
215
207
|
}
|
|
216
208
|
|
|
217
209
|
//# sourceMappingURL=getStaticRenderFunctions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/start/server/getStaticRenderFunctions.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 fs from 'fs';\nimport fetch from 'node-fetch';\nimport path from 'path';\nimport requireString from 'require-from-string';\nimport resolveFrom from 'resolve-from';\n\nimport { logMetroError, logMetroErrorAsync } from './metro/metroErrorInterface';\nimport { getMetroServerRoot } from './middleware/ManifestMiddleware';\nimport { createBundleUrlPath } from './middleware/metroOptions';\nimport { stripAnsi } from '../../utils/ansi';\nimport { delayAsync } from '../../utils/delay';\nimport { SilentError } from '../../utils/errors';\nimport { memoize } from '../../utils/fn';\nimport { profile } from '../../utils/profile';\n\ntype StaticRenderOptions = {\n // Ensure the style format is `css-xxxx` (prod) instead of `css-view-xxxx` (dev)\n dev?: boolean;\n minify?: boolean;\n platform?: string;\n environment?: 'node';\n engine?: 'hermes';\n baseUrl: string;\n routerRoot: string;\n};\n\nclass MetroNodeError extends Error {\n constructor(\n message: string,\n public rawObject: any\n ) {\n super(message);\n }\n}\n\nconst debug = require('debug')('expo:start:server:node-renderer') as typeof console.log;\n\nconst cachedSourceMaps: Map<string, { url: string; map: string }> = new Map();\n\n// Support unhandled rejections\nrequire('source-map-support').install({\n retrieveSourceMap(source: string) {\n if (cachedSourceMaps.has(source)) {\n return cachedSourceMaps.get(source);\n }\n return null;\n },\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\n// TODO(EvanBacon): Group all the code together and version.\nconst getRenderModuleId = (projectRoot: string): string => {\n const moduleId = resolveFrom.silent(projectRoot, 'expo-router/node/render.js');\n if (!moduleId) {\n throw new Error(\n `A version of expo-router with Node.js support is not installed in the project.`\n );\n }\n\n return moduleId;\n};\n\nconst moveStaticRenderFunction = memoize(async (projectRoot: string, requiredModuleId: string) => {\n // Copy the file into the project to ensure it works in monorepos.\n // This means the file cannot have any relative imports.\n const tempDir = path.join(projectRoot, '.expo/static');\n await fs.promises.mkdir(tempDir, { recursive: true });\n const moduleId = path.join(tempDir, 'render.js');\n await fs.promises.writeFile(moduleId, await fs.promises.readFile(requiredModuleId, 'utf8'));\n // Sleep to give watchman time to register the file.\n await delayAsync(50);\n return moduleId;\n});\n\n/** @returns the js file contents required to generate the static generation function. */\nasync function getStaticRenderFunctionsContentAsync(\n projectRoot: string,\n devServerUrl: string,\n { dev = false, minify = false, environment, baseUrl, routerRoot }: StaticRenderOptions\n): Promise<{ src: string; filename: string }> {\n const root = getMetroServerRoot(projectRoot);\n const requiredModuleId = getRenderModuleId(root);\n let moduleId = requiredModuleId;\n\n // Cannot be accessed using Metro's server API, we need to move the file\n // into the project root and try again.\n if (path.relative(root, moduleId).startsWith('..')) {\n moduleId = await moveStaticRenderFunction(projectRoot, requiredModuleId);\n }\n\n return requireFileContentsWithMetro(root, devServerUrl, moduleId, {\n dev,\n minify,\n environment,\n baseUrl,\n routerRoot,\n });\n}\n\nasync function ensureFileInRootDirectory(projectRoot: string, otherFile: string) {\n // Cannot be accessed using Metro's server API, we need to move the file\n // into the project root and try again.\n if (!path.relative(projectRoot, otherFile).startsWith('..' + path.sep)) {\n return otherFile;\n }\n\n // Copy the file into the project to ensure it works in monorepos.\n // This means the file cannot have any relative imports.\n const tempDir = path.join(projectRoot, '.expo/static-tmp');\n await fs.promises.mkdir(tempDir, { recursive: true });\n const moduleId = path.join(tempDir, path.basename(otherFile));\n await fs.promises.writeFile(moduleId, await fs.promises.readFile(otherFile, 'utf8'));\n // Sleep to give watchman time to register the file.\n await delayAsync(50);\n return moduleId;\n}\n\nexport async function createMetroEndpointAsync(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n {\n dev = false,\n platform = 'web',\n minify = false,\n environment,\n engine = 'hermes',\n baseUrl,\n routerRoot,\n }: StaticRenderOptions\n): Promise<string> {\n const root = getMetroServerRoot(projectRoot);\n const safeOtherFile = await ensureFileInRootDirectory(projectRoot, absoluteFilePath);\n const serverPath = path.relative(root, safeOtherFile).replace(/\\.[jt]sx?$/, '');\n\n const urlFragment = createBundleUrlPath({\n platform,\n mode: dev ? 'development' : 'production',\n mainModuleName: serverPath,\n engine,\n environment,\n lazy: false,\n minify,\n baseUrl,\n isExporting: true,\n asyncRoutes: false,\n routerRoot,\n inlineSourceMap: false,\n });\n\n let url: string;\n if (devServerUrl) {\n url = new URL(urlFragment.replace(/^\\//, ''), devServerUrl).toString();\n } else {\n url = '/' + urlFragment.replace(/^\\/+/, '');\n }\n debug('fetching from Metro:', root, serverPath, url);\n return url;\n}\n\nexport async function requireFileContentsWithMetro(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n props: StaticRenderOptions\n): Promise<{ src: string; filename: string }> {\n const url = await createMetroEndpointAsync(projectRoot, devServerUrl, absoluteFilePath, props);\n\n const res = await fetch(url);\n\n // TODO: Improve error handling\n if (res.status === 500) {\n const text = await res.text();\n if (text.startsWith('{\"originModulePath\"') || text.startsWith('{\"type\":\"TransformError\"')) {\n const errorObject = JSON.parse(text);\n\n throw new MetroNodeError(stripAnsi(errorObject.message) ?? errorObject.message, errorObject);\n }\n throw new Error(`[${res.status}]: ${res.statusText}\\n${text}`);\n }\n\n if (!res.ok) {\n throw new Error(`Error fetching bundle for static rendering: ${res.status} ${res.statusText}`);\n }\n\n const content = await res.text();\n\n const map = await fetch(url.replace('.bundle?', '.map?')).then((r) => r.json());\n cachedSourceMaps.set(url, { url: projectRoot, map });\n\n return { src: wrapBundle(content), filename: url };\n}\n\nexport async function getStaticRenderFunctions(\n projectRoot: string,\n devServerUrl: string,\n options: StaticRenderOptions\n): Promise<Record<string, (...args: any[]) => Promise<any>>> {\n const { src: scriptContents, filename } = await getStaticRenderFunctionsContentAsync(\n projectRoot,\n devServerUrl,\n options\n );\n\n return evalMetroAndWrapFunctions(projectRoot, scriptContents, filename);\n}\n\nfunction evalMetroAndWrapFunctions<T = Record<string, (...args: any[]) => Promise<any>>>(\n projectRoot: string,\n script: string,\n filename: string\n): Promise<T> {\n const contents = evalMetro(projectRoot, script, filename);\n\n // wrap each function with a try/catch that uses Metro's error formatter\n return Object.keys(contents).reduce((acc, key) => {\n const fn = contents[key];\n if (typeof fn !== 'function') {\n return { ...acc, [key]: fn };\n }\n\n acc[key] = async function (...props: any[]) {\n try {\n return await fn.apply(this, props);\n } catch (error: any) {\n await logMetroError(projectRoot, { error });\n throw new SilentError(error);\n }\n };\n return acc;\n }, {} as any);\n}\n\nfunction evalMetro(projectRoot: string, src: string, filename: string) {\n const originalConsole = {\n log: console.log,\n warn: console.warn,\n error: console.error,\n };\n try {\n return profile(requireString, 'eval-metro-bundle')(src, filename);\n } catch (error: any) {\n // Format any errors that were thrown in the global scope of the evaluation.\n if (error instanceof Error) {\n logMetroErrorAsync({ projectRoot, error }).catch((internalError) => {\n debug('Failed to log metro error:', internalError);\n throw error;\n });\n } else {\n throw error;\n }\n } finally {\n // Restore the original console in case it was modified.\n console.log = originalConsole.log;\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n }\n}\n"],"names":["createMetroEndpointAsync","requireFileContentsWithMetro","getStaticRenderFunctions","MetroNodeError","Error","constructor","message","rawObject","debug","require","cachedSourceMaps","Map","install","retrieveSourceMap","source","has","get","wrapBundle","str","replace","getRenderModuleId","projectRoot","moduleId","resolveFrom","silent","moveStaticRenderFunction","memoize","requiredModuleId","tempDir","path","join","fs","promises","mkdir","recursive","writeFile","readFile","delayAsync","getStaticRenderFunctionsContentAsync","devServerUrl","dev","minify","environment","baseUrl","routerRoot","root","getMetroServerRoot","relative","startsWith","ensureFileInRootDirectory","otherFile","sep","basename","absoluteFilePath","platform","engine","safeOtherFile","serverPath","urlFragment","createBundleUrlPath","mode","mainModuleName","lazy","isExporting","asyncRoutes","inlineSourceMap","url","URL","toString","props","res","fetch","status","text","errorObject","JSON","parse","stripAnsi","statusText","ok","content","map","then","r","json","set","src","filename","options","scriptContents","evalMetroAndWrapFunctions","script","contents","evalMetro","Object","keys","reduce","acc","key","fn","apply","error","logMetroError","SilentError","originalConsole","log","console","warn","profile","requireString","logMetroErrorAsync","catch","internalError"],"mappings":"AAMA;;;;QA2HsBA,wBAAwB,GAAxBA,wBAAwB;QA2CxBC,4BAA4B,GAA5BA,4BAA4B;QAiC5BC,wBAAwB,GAAxBA,wBAAwB;AAvM/B,IAAA,GAAI,kCAAJ,IAAI,EAAA;AACD,IAAA,UAAY,kCAAZ,YAAY,EAAA;AACb,IAAA,KAAM,kCAAN,MAAM,EAAA;AACG,IAAA,kBAAqB,kCAArB,qBAAqB,EAAA;AACvB,IAAA,YAAc,kCAAd,cAAc,EAAA;AAEY,IAAA,oBAA6B,WAA7B,6BAA6B,CAAA;AAC5C,IAAA,mBAAiC,WAAjC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R,wDAAwD;QACxDK,OAAO,CAACD,GAAG,GAAGD,eAAe,CAACC,GAAG,CAAC;QAClCC,OAAO,CAACC,IAAI,GAAGH,eAAe,CAACG,IAAI,CAAC;QACpCD,OAAO,CAACL,KAAK,GAAGG,eAAe,CAACH,KAAK,CAAC;KACvC;CACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/start/server/getStaticRenderFunctions.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 fs from 'fs';\nimport fetch from 'node-fetch';\nimport path from 'path';\nimport requireString from 'require-from-string';\nimport resolveFrom from 'resolve-from';\n\nimport { logMetroError, logMetroErrorAsync } from './metro/metroErrorInterface';\nimport { getMetroServerRoot } from './middleware/ManifestMiddleware';\nimport { createBundleUrlPath } from './middleware/metroOptions';\nimport { augmentLogs } from './serverLogLikeMetro';\nimport { stripAnsi } from '../../utils/ansi';\nimport { delayAsync } from '../../utils/delay';\nimport { SilentError } from '../../utils/errors';\nimport { memoize } from '../../utils/fn';\nimport { profile } from '../../utils/profile';\n\ntype StaticRenderOptions = {\n // Ensure the style format is `css-xxxx` (prod) instead of `css-view-xxxx` (dev)\n dev?: boolean;\n minify?: boolean;\n platform?: string;\n environment?: 'node';\n engine?: 'hermes';\n baseUrl: string;\n routerRoot: string;\n};\n\nclass MetroNodeError extends Error {\n constructor(\n message: string,\n public rawObject: any\n ) {\n super(message);\n }\n}\n\nconst debug = require('debug')('expo:start:server:node-renderer') as typeof console.log;\n\nconst cachedSourceMaps: Map<string, { url: string; map: string }> = new Map();\n\n// Support unhandled rejections\nrequire('source-map-support').install({\n retrieveSourceMap(source: string) {\n if (cachedSourceMaps.has(source)) {\n return cachedSourceMaps.get(source);\n }\n return null;\n },\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\n// TODO(EvanBacon): Group all the code together and version.\nconst getRenderModuleId = (projectRoot: string): string => {\n const moduleId = resolveFrom.silent(projectRoot, 'expo-router/node/render.js');\n if (!moduleId) {\n throw new Error(\n `A version of expo-router with Node.js support is not installed in the project.`\n );\n }\n\n return moduleId;\n};\n\nconst moveStaticRenderFunction = memoize(async (projectRoot: string, requiredModuleId: string) => {\n // Copy the file into the project to ensure it works in monorepos.\n // This means the file cannot have any relative imports.\n const tempDir = path.join(projectRoot, '.expo/static');\n await fs.promises.mkdir(tempDir, { recursive: true });\n const moduleId = path.join(tempDir, 'render.js');\n await fs.promises.writeFile(moduleId, await fs.promises.readFile(requiredModuleId, 'utf8'));\n // Sleep to give watchman time to register the file.\n await delayAsync(50);\n return moduleId;\n});\n\n/** @returns the js file contents required to generate the static generation function. */\nasync function getStaticRenderFunctionsContentAsync(\n projectRoot: string,\n devServerUrl: string,\n { dev = false, minify = false, environment, baseUrl, routerRoot }: StaticRenderOptions\n): Promise<{ src: string; filename: string }> {\n const root = getMetroServerRoot(projectRoot);\n const requiredModuleId = getRenderModuleId(root);\n let moduleId = requiredModuleId;\n\n // Cannot be accessed using Metro's server API, we need to move the file\n // into the project root and try again.\n if (path.relative(root, moduleId).startsWith('..')) {\n moduleId = await moveStaticRenderFunction(projectRoot, requiredModuleId);\n }\n\n return requireFileContentsWithMetro(root, devServerUrl, moduleId, {\n dev,\n minify,\n environment,\n baseUrl,\n routerRoot,\n });\n}\n\nasync function ensureFileInRootDirectory(projectRoot: string, otherFile: string) {\n // Cannot be accessed using Metro's server API, we need to move the file\n // into the project root and try again.\n if (!path.relative(projectRoot, otherFile).startsWith('..' + path.sep)) {\n return otherFile;\n }\n\n // Copy the file into the project to ensure it works in monorepos.\n // This means the file cannot have any relative imports.\n const tempDir = path.join(projectRoot, '.expo/static-tmp');\n await fs.promises.mkdir(tempDir, { recursive: true });\n const moduleId = path.join(tempDir, path.basename(otherFile));\n await fs.promises.writeFile(moduleId, await fs.promises.readFile(otherFile, 'utf8'));\n // Sleep to give watchman time to register the file.\n await delayAsync(50);\n return moduleId;\n}\n\nexport async function createMetroEndpointAsync(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n {\n dev = false,\n platform = 'web',\n minify = false,\n environment,\n engine = 'hermes',\n baseUrl,\n routerRoot,\n }: StaticRenderOptions\n): Promise<string> {\n const root = getMetroServerRoot(projectRoot);\n const safeOtherFile = await ensureFileInRootDirectory(projectRoot, absoluteFilePath);\n const serverPath = path.relative(root, safeOtherFile).replace(/\\.[jt]sx?$/, '');\n\n const urlFragment = createBundleUrlPath({\n platform,\n mode: dev ? 'development' : 'production',\n mainModuleName: serverPath,\n engine,\n environment,\n lazy: false,\n minify,\n baseUrl,\n isExporting: true,\n asyncRoutes: false,\n routerRoot,\n inlineSourceMap: false,\n });\n\n let url: string;\n if (devServerUrl) {\n url = new URL(urlFragment.replace(/^\\//, ''), devServerUrl).toString();\n } else {\n url = '/' + urlFragment.replace(/^\\/+/, '');\n }\n debug('fetching from Metro:', root, serverPath, url);\n return url;\n}\n\nexport async function requireFileContentsWithMetro(\n projectRoot: string,\n devServerUrl: string,\n absoluteFilePath: string,\n props: StaticRenderOptions\n): Promise<{ src: string; filename: string }> {\n const url = await createMetroEndpointAsync(projectRoot, devServerUrl, absoluteFilePath, props);\n\n const res = await fetch(url);\n\n // TODO: Improve error handling\n if (res.status === 500) {\n const text = await res.text();\n if (text.startsWith('{\"originModulePath\"') || text.startsWith('{\"type\":\"TransformError\"')) {\n const errorObject = JSON.parse(text);\n\n throw new MetroNodeError(stripAnsi(errorObject.message) ?? errorObject.message, errorObject);\n }\n throw new Error(`[${res.status}]: ${res.statusText}\\n${text}`);\n }\n\n if (!res.ok) {\n throw new Error(`Error fetching bundle for static rendering: ${res.status} ${res.statusText}`);\n }\n\n const content = await res.text();\n\n const map = await fetch(url.replace('.bundle?', '.map?')).then((r) => r.json());\n cachedSourceMaps.set(url, { url: projectRoot, map });\n\n return { src: wrapBundle(content), filename: url };\n}\n\nexport async function getStaticRenderFunctions(\n projectRoot: string,\n devServerUrl: string,\n options: StaticRenderOptions\n): Promise<Record<string, (...args: any[]) => Promise<any>>> {\n const { src: scriptContents, filename } = await getStaticRenderFunctionsContentAsync(\n projectRoot,\n devServerUrl,\n options\n );\n\n return evalMetroAndWrapFunctions(projectRoot, scriptContents, filename);\n}\n\nfunction evalMetroAndWrapFunctions<T = Record<string, (...args: any[]) => Promise<any>>>(\n projectRoot: string,\n script: string,\n filename: string\n): Promise<T> {\n const contents = evalMetro(projectRoot, script, filename);\n\n // wrap each function with a try/catch that uses Metro's error formatter\n return Object.keys(contents).reduce((acc, key) => {\n const fn = contents[key];\n if (typeof fn !== 'function') {\n return { ...acc, [key]: fn };\n }\n\n acc[key] = async function (...props: any[]) {\n try {\n return await fn.apply(this, props);\n } catch (error: any) {\n await logMetroError(projectRoot, { error });\n throw new SilentError(error);\n }\n };\n return acc;\n }, {} as any);\n}\n\nfunction evalMetro(projectRoot: string, src: string, filename: string) {\n augmentLogs(projectRoot);\n try {\n return profile(requireString, 'eval-metro-bundle')(src, filename);\n } catch (error: any) {\n // Format any errors that were thrown in the global scope of the evaluation.\n if (error instanceof Error) {\n logMetroErrorAsync({ projectRoot, error }).catch((internalError) => {\n debug('Failed to log metro error:', internalError);\n throw error;\n });\n } else {\n throw error;\n }\n } finally {\n }\n}\n"],"names":["createMetroEndpointAsync","requireFileContentsWithMetro","getStaticRenderFunctions","MetroNodeError","Error","constructor","message","rawObject","debug","require","cachedSourceMaps","Map","install","retrieveSourceMap","source","has","get","wrapBundle","str","replace","getRenderModuleId","projectRoot","moduleId","resolveFrom","silent","moveStaticRenderFunction","memoize","requiredModuleId","tempDir","path","join","fs","promises","mkdir","recursive","writeFile","readFile","delayAsync","getStaticRenderFunctionsContentAsync","devServerUrl","dev","minify","environment","baseUrl","routerRoot","root","getMetroServerRoot","relative","startsWith","ensureFileInRootDirectory","otherFile","sep","basename","absoluteFilePath","platform","engine","safeOtherFile","serverPath","urlFragment","createBundleUrlPath","mode","mainModuleName","lazy","isExporting","asyncRoutes","inlineSourceMap","url","URL","toString","props","res","fetch","status","text","errorObject","JSON","parse","stripAnsi","statusText","ok","content","map","then","r","json","set","src","filename","options","scriptContents","evalMetroAndWrapFunctions","script","contents","evalMetro","Object","keys","reduce","acc","key","fn","apply","error","logMetroError","SilentError","augmentLogs","profile","requireString","logMetroErrorAsync","catch","internalError"],"mappings":"AAMA;;;;QA4HsBA,wBAAwB,GAAxBA,wBAAwB;QA2CxBC,4BAA4B,GAA5BA,4BAA4B;QAiC5BC,wBAAwB,GAAxBA,wBAAwB;AAxM/B,IAAA,GAAI,kCAAJ,IAAI,EAAA;AACD,IAAA,UAAY,kCAAZ,YAAY,EAAA;AACb,IAAA,KAAM,kCAAN,MAAM,EAAA;AACG,IAAA,kBAAqB,kCAArB,qBAAqB,EAAA;AACvB,IAAA,YAAc,kCAAd,cAAc,EAAA;AAEY,IAAA,oBAA6B,WAA7B,6BAA6B,CAAA;AAC5C,IAAA,mBAAiC,WAAjC,iCAAiC,CAAA;AAChC,IAAA,aAA2B,WAA3B,2BAA2B,CAAA;AACnC,IAAA,mBAAsB,WAAtB,sBAAsB,CAAA;AACxB,IAAA,KAAkB,WAAlB,kBAAkB,CAAA;AACjB,IAAA,MAAmB,WAAnB,mBAAmB,CAAA;AAClB,IAAA,OAAoB,WAApB,oBAAoB,CAAA;AACxB,IAAA,GAAgB,WAAhB,gBAAgB,CAAA;AAChB,IAAA,QAAqB,WAArB,qBAAqB,CAAA;;;;;;AAa7C,MAAMC,cAAc,SAASC,KAAK;IAChCC,YACEC,OAAe,EACRC,SAAc,CACrB;QACA,KAAK,CAACD,OAAO,CAAC,CAAC;aAFRC,SAAc,GAAdA,SAAc;KAGtB;CACF;AAED,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,iCAAiC,CAAC,AAAsB,AAAC;AAExF,M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ASJ,SAAS,CAACxE,WAAmB,EAAEiE,GAAW,EAAEC,QAAgB,EAAE;IACrEiB,CAAAA,GAAAA,mBAAW,AAAa,CAAA,YAAb,CAACnF,WAAW,CAAC,CAAC;IACzB,IAAI;QACF,OAAOoF,CAAAA,GAAAA,QAAO,AAAoC,CAAA,QAApC,CAACC,kBAAa,QAAA,EAAE,mBAAmB,CAAC,CAACpB,GAAG,EAAEC,QAAQ,CAAC,CAAC;KACnE,CAAC,OAAOc,KAAK,EAAO;QACnB,4EAA4E;QAC5E,IAAIA,KAAK,YAAYjG,KAAK,EAAE;YAC1BuG,CAAAA,GAAAA,oBAAkB,AAAwB,CAAA,mBAAxB,CAAC;gBAAEtF,WAAW;gBAAEgF,KAAK;aAAE,CAAC,CAACO,KAAK,CAAC,CAACC,aAAa,GAAK;gBAClErG,KAAK,CAAC,4BAA4B,EAAEqG,aAAa,CAAC,CAAC;gBACnD,MAAMR,KAAK,CAAC;aACb,CAAC,CAAC;SACJ,MAAM;YACL,MAAMA,KAAK,CAAC;SACb;KACF,QAAS,EACT;CACF"}
|
|
@@ -37,11 +37,11 @@ class MetroTerminalReporter extends _terminalReporter.TerminalReporter {
|
|
|
37
37
|
const inProgress = phase === "in_progress";
|
|
38
38
|
const localPath = progress.bundleDetails.entryFile.startsWith(_path.default.sep) ? _path.default.relative(this.projectRoot, progress.bundleDetails.entryFile) : progress.bundleDetails.entryFile;
|
|
39
39
|
if (!inProgress) {
|
|
40
|
-
const status = phase === "done" ? `
|
|
40
|
+
const status = phase === "done" ? `Bundled ` : `Bundling failed `;
|
|
41
41
|
const color = phase === "done" ? _chalk.default.green : _chalk.default.red;
|
|
42
42
|
const startTime = this._bundleTimers.get(progress.bundleDetails.buildID);
|
|
43
43
|
const time = startTime != null ? _chalk.default.dim(this._getElapsedTime(startTime) + "ms") : "";
|
|
44
|
-
// iOS
|
|
44
|
+
// iOS Bundled 150ms
|
|
45
45
|
return color(platform + status) + time + _chalk.default.reset.dim(" (" + localPath + ")");
|
|
46
46
|
}
|
|
47
47
|
const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);
|
|
@@ -161,7 +161,7 @@ function stripMetroInfo(errorMessage) {
|
|
|
161
161
|
// Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.
|
|
162
162
|
const env = (ref1 = bundleDetails == null ? void 0 : (ref = bundleDetails.customTransformOptions) == null ? void 0 : ref.environment) != null ? ref1 : null;
|
|
163
163
|
if (env === "node") {
|
|
164
|
-
return
|
|
164
|
+
return _chalk.default.bold("\u03BB") + " ";
|
|
165
165
|
}
|
|
166
166
|
return "";
|
|
167
167
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { learnMore } from '../../../utils/link';\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n // Used for testing\n _getElapsedTime(startTime: number): number {\n return Date.now() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n const localPath = progress.bundleDetails.entryFile.startsWith(path.sep)\n ? path.relative(this.projectRoot, progress.bundleDetails.entryFile)\n : progress.bundleDetails.entryFile;\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundling complete ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n const time = startTime != null ? chalk.dim(this._getElapsedTime(startTime) + 'ms') : '';\n // iOS Bundling complete 150ms\n return color(platform + status) + time + chalk.reset.dim(' (' + localPath + ')');\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}/`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log('Starting Metro Bundler');\n }\n\n shouldFilterClientLog(event: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return null;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return `${chalk.bold('Server')} `;\n }\n\n return '';\n}\n"],"names":["formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","MetroTerminalReporter","TerminalReporter","constructor","projectRoot","terminal","_getElapsedTime","startTime","Date","now","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","entryFile","startsWith","path","sep","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","dim","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","bold","toFixed","padStart","transformedFileCount","toString","totalFileCount","length","dirname","basename","_logInitializing","port","hasReducedPerformance","log","shouldFilterClientLog","event","isAppRegistryStartupMessage","data","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","includes","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","customTransformOptions","environment"],"mappings":"AAAA;;;;QAiJgBA,mCAAmC,GAAnCA,mCAAmC;QAwCnCC,sBAAsB,GAAtBA,sBAAsB;QAkBtBC,cAAc,GAAdA,cAAc;AA3MZ,IAAA,MAAO,kCAAP,OAAO,EAAA;AAER,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEsB,IAAA,iBAAoB,WAApB,oBAAoB,CAAA;AAQ7B,IAAA,UAAa,WAAb,aAAa,CAAA;AACvB,IAAA,KAAqB,WAArB,qBAAqB,CAAA;;;;;;AAE/C,MAAMC,2BAA2B,GAAG,EAAE,AAAC;AACvC,MAAMC,eAAe,GAAG,QAAQ,AAAC;AACjC,MAAMC,gBAAgB,GAAG,QAAQ,AAAC;AAK3B,MAAMC,qBAAqB,SAASC,iBAAgB,iBAAA;IACzDC,YACSC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,QAAQ,CAAC,CAAC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CA,aAAa,CAAEmF,sBAAsB,SAAA,GAArCnF,KAAAA,CAAqC,GAArCA,GAAqC,CAAEoF,WAAW,AAAb,YAArCpF,IAAkD,GAAI,IAAI,AAAC;IACvE,IAAIF,GAAG,KAAK,MAAM,EAAE;QAClB,OAAO,CAAC,EAAEc,MAAK,QAAA,CAACkB,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;KACnC;IAED,OAAO,EAAE,CAAC;CACX"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/metro/MetroTerminalReporter.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { Terminal } from 'metro-core';\nimport path from 'path';\n\nimport { logWarning, TerminalReporter } from './TerminalReporter';\nimport {\n BuildPhase,\n BundleDetails,\n BundleProgress,\n SnippetError,\n TerminalReportableEvent,\n} from './TerminalReporter.types';\nimport { NODE_STDLIB_MODULES } from './externals';\nimport { learnMore } from '../../../utils/link';\n\nconst MAX_PROGRESS_BAR_CHAR_WIDTH = 16;\nconst DARK_BLOCK_CHAR = '\\u2593';\nconst LIGHT_BLOCK_CHAR = '\\u2591';\n/**\n * Extends the default Metro logger and adds some additional features.\n * Also removes the giant Metro logo from the output.\n */\nexport class MetroTerminalReporter extends TerminalReporter {\n constructor(\n public projectRoot: string,\n terminal: Terminal\n ) {\n super(terminal);\n }\n\n // Used for testing\n _getElapsedTime(startTime: number): number {\n return Date.now() - startTime;\n }\n /**\n * Extends the bundle progress to include the current platform that we're bundling.\n *\n * @returns `iOS path/to/bundle.js ▓▓▓▓▓░░░░░░░░░░░ 36.6% (4790/7922)`\n */\n _getBundleStatusMessage(progress: BundleProgress, phase: BuildPhase): string {\n const env = getEnvironmentForBuildDetails(progress.bundleDetails);\n const platform = env || getPlatformTagForBuildDetails(progress.bundleDetails);\n const inProgress = phase === 'in_progress';\n\n const localPath = progress.bundleDetails.entryFile.startsWith(path.sep)\n ? path.relative(this.projectRoot, progress.bundleDetails.entryFile)\n : progress.bundleDetails.entryFile;\n\n if (!inProgress) {\n const status = phase === 'done' ? `Bundled ` : `Bundling failed `;\n const color = phase === 'done' ? chalk.green : chalk.red;\n\n const startTime = this._bundleTimers.get(progress.bundleDetails.buildID!);\n const time = startTime != null ? chalk.dim(this._getElapsedTime(startTime) + 'ms') : '';\n // iOS Bundled 150ms\n return color(platform + status) + time + chalk.reset.dim(' (' + localPath + ')');\n }\n\n const filledBar = Math.floor(progress.ratio * MAX_PROGRESS_BAR_CHAR_WIDTH);\n\n const _progress = inProgress\n ? chalk.green.bgGreen(DARK_BLOCK_CHAR.repeat(filledBar)) +\n chalk.bgWhite.white(LIGHT_BLOCK_CHAR.repeat(MAX_PROGRESS_BAR_CHAR_WIDTH - filledBar)) +\n chalk.bold(` ${(100 * progress.ratio).toFixed(1).padStart(4)}% `) +\n chalk.dim(\n `(${progress.transformedFileCount\n .toString()\n .padStart(progress.totalFileCount.toString().length)}/${progress.totalFileCount})`\n )\n : '';\n\n return (\n platform +\n chalk.reset.dim(`${path.dirname(localPath)}/`) +\n chalk.bold(path.basename(localPath)) +\n ' ' +\n _progress\n );\n }\n\n _logInitializing(port: number, hasReducedPerformance: boolean): void {\n // Don't print a giant logo...\n this.terminal.log('Starting Metro Bundler');\n }\n\n shouldFilterClientLog(event: {\n type: 'client_log';\n level: 'trace' | 'info' | 'warn' | 'log' | 'group' | 'groupCollapsed' | 'groupEnd' | 'debug';\n data: unknown[];\n }): boolean {\n return isAppRegistryStartupMessage(event.data);\n }\n\n shouldFilterBundleEvent(event: TerminalReportableEvent): boolean {\n return 'bundleDetails' in event && event.bundleDetails?.bundleType === 'map';\n }\n\n /** Print the cache clear message. */\n transformCacheReset(): void {\n logWarning(\n this.terminal,\n chalk`Bundler cache is empty, rebuilding {dim (this may take a minute)}`\n );\n }\n\n /** One of the first logs that will be printed */\n dependencyGraphLoading(hasReducedPerformance: boolean): void {\n // this.terminal.log('Dependency graph is loading...');\n if (hasReducedPerformance) {\n // Extends https://github.com/facebook/metro/blob/347b1d7ed87995d7951aaa9fd597c04b06013dac/packages/metro/src/lib/TerminalReporter.js#L283-L290\n this.terminal.log(\n chalk.red(\n [\n 'Metro is operating with reduced performance.',\n 'Please fix the problem above and restart Metro.',\n ].join('\\n')\n )\n );\n }\n }\n\n _logBundlingError(error: SnippetError): void {\n const moduleResolutionError = formatUsingNodeStandardLibraryError(this.projectRoot, error);\n const cause = error.cause as undefined | { _expoImportStack?: string };\n if (moduleResolutionError) {\n let message = maybeAppendCodeFrame(moduleResolutionError, error.message);\n if (cause?._expoImportStack) {\n message += `\\n\\n${cause?._expoImportStack}`;\n }\n return this.terminal.log(message);\n }\n if (cause?._expoImportStack) {\n error.message += `\\n\\n${cause._expoImportStack}`;\n }\n return super._logBundlingError(error);\n }\n}\n\n/**\n * Formats an error where the user is attempting to import a module from the Node.js standard library.\n * Exposed for testing.\n *\n * @param error\n * @returns error message or null if not a module resolution error\n */\nexport function formatUsingNodeStandardLibraryError(\n projectRoot: string,\n error: SnippetError\n): string | null {\n if (!error.message) {\n return null;\n }\n const { targetModuleName, originModulePath } = error;\n if (!targetModuleName || !originModulePath) {\n return null;\n }\n const relativePath = path.relative(projectRoot, originModulePath);\n\n const DOCS_PAGE_URL =\n 'https://docs.expo.dev/workflow/using-libraries/#using-third-party-libraries';\n\n if (isNodeStdLibraryModule(targetModuleName)) {\n if (originModulePath.includes('node_modules')) {\n return [\n `The package at \"${chalk.bold(\n relativePath\n )}\" attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n } else {\n return [\n `You attempted to import the Node standard library module \"${chalk.bold(\n targetModuleName\n )}\" from \"${chalk.bold(relativePath)}\".`,\n `It failed because the native React runtime does not include the Node standard library.`,\n learnMore(DOCS_PAGE_URL),\n ].join('\\n');\n }\n }\n return `Unable to resolve \"${targetModuleName}\" from \"${relativePath}\"`;\n}\n\nexport function isNodeStdLibraryModule(moduleName: string): boolean {\n return /^node:/.test(moduleName) || NODE_STDLIB_MODULES.includes(moduleName);\n}\n\n/** If the code frame can be found then append it to the existing message. */\nfunction maybeAppendCodeFrame(message: string, rawMessage: string): string {\n const codeFrame = stripMetroInfo(rawMessage);\n if (codeFrame) {\n message += '\\n' + codeFrame;\n }\n return message;\n}\n\n/**\n * Remove the Metro cache clearing steps if they exist.\n * In future versions we won't need this.\n * Returns the remaining code frame logs.\n */\nexport function stripMetroInfo(errorMessage: string): string | null {\n // Newer versions of Metro don't include the list.\n if (!errorMessage.includes('4. Remove the cache')) {\n return null;\n }\n const lines = errorMessage.split('\\n');\n const index = lines.findIndex((line) => line.includes('4. Remove the cache'));\n if (index === -1) {\n return null;\n }\n return lines.slice(index + 1).join('\\n');\n}\n\n/** @returns if the message matches the initial startup log */\nfunction isAppRegistryStartupMessage(body: any[]): boolean {\n return (\n body.length === 1 &&\n (/^Running application \"main\" with appParams:/.test(body[0]) ||\n /^Running \"main\" with \\{/.test(body[0]))\n );\n}\n\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getPlatformTagForBuildDetails(bundleDetails?: BundleDetails | null): string {\n const platform = bundleDetails?.platform ?? null;\n if (platform) {\n const formatted = { ios: 'iOS', android: 'Android', web: 'Web' }[platform] || platform;\n return `${chalk.bold(formatted)} `;\n }\n\n return '';\n}\n/** @returns platform specific tag for a `BundleDetails` object */\nfunction getEnvironmentForBuildDetails(bundleDetails?: BundleDetails | null): string {\n // Expo CLI will pass `customTransformOptions.environment = 'node'` when bundling for the server.\n const env = bundleDetails?.customTransformOptions?.environment ?? null;\n if (env === 'node') {\n return chalk.bold('λ') + ' ';\n }\n\n return '';\n}\n"],"names":["formatUsingNodeStandardLibraryError","isNodeStdLibraryModule","stripMetroInfo","MAX_PROGRESS_BAR_CHAR_WIDTH","DARK_BLOCK_CHAR","LIGHT_BLOCK_CHAR","MetroTerminalReporter","TerminalReporter","constructor","projectRoot","terminal","_getElapsedTime","startTime","Date","now","_getBundleStatusMessage","progress","phase","env","getEnvironmentForBuildDetails","bundleDetails","platform","getPlatformTagForBuildDetails","inProgress","localPath","entryFile","startsWith","path","sep","relative","status","color","chalk","green","red","_bundleTimers","get","buildID","time","dim","reset","filledBar","Math","floor","ratio","_progress","bgGreen","repeat","bgWhite","white","bold","toFixed","padStart","transformedFileCount","toString","totalFileCount","length","dirname","basename","_logInitializing","port","hasReducedPerformance","log","shouldFilterClientLog","event","isAppRegistryStartupMessage","data","shouldFilterBundleEvent","bundleType","transformCacheReset","logWarning","dependencyGraphLoading","join","_logBundlingError","error","moduleResolutionError","cause","message","maybeAppendCodeFrame","_expoImportStack","targetModuleName","originModulePath","relativePath","DOCS_PAGE_URL","includes","learnMore","moduleName","test","NODE_STDLIB_MODULES","rawMessage","codeFrame","errorMessage","lines","split","index","findIndex","line","slice","body","formatted","ios","android","web","customTransformOptions","environment"],"mappings":"AAAA;;;;QAiJgBA,mCAAmC,GAAnCA,mCAAmC;QAwCnCC,sBAAsB,GAAtBA,sBAAsB;QAkBtBC,cAAc,GAAdA,cAAc;AA3MZ,IAAA,MAAO,kCAAP,OAAO,EAAA;AAER,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEsB,IAAA,iBAAoB,WAApB,oBAAoB,CAAA;AAQ7B,IAAA,UAAa,WAAb,aAAa,CAAA;AACvB,IAAA,KAAqB,WAArB,qBAAqB,CAAA;;;;;;AAE/C,MAAMC,2BAA2B,GAAG,EAAE,AAAC;AACvC,MAAMC,eAAe,GAAG,QAAQ,AAAC;AACjC,MAAMC,gBAAgB,GAAG,QAAQ,AAAC;AAK3B,MAAMC,qBAAqB,SAASC,iBAAgB,iBAAA;IACzDC,YACSC,WAAmB,EAC1BC,QAAkB,CAClB;QACA,KAAK,CAACA,QAAQ,CAAC,CAAC;aAHTD,WAAmB,GAAnBA,WAAmB;KAI3B;IAED,mBAAmB;IACnBE,eAAe,CAACC,SAAiB,EAAU;QACzC,OAAOC,IAAI,CAACC,GAAG,EAAE,GAAGF,SAAS,CAAC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KAAK,MAAM,EAAE;QAClB,OAAOc,MAAK,QAAA,CAACkB,IAAI,CAAC,QAAG,CAAC,GAAG,GAAG,CAAC;KAC9B;IAED,OAAO,EAAE,CAAC;CACX"}
|
|
@@ -70,7 +70,8 @@ class ExpoGoManifestHandlerMiddleware extends _manifestMiddleware.ManifestMiddle
|
|
|
70
70
|
responseContentType,
|
|
71
71
|
platform,
|
|
72
72
|
expectSignature: expectSignature ? String(expectSignature) : null,
|
|
73
|
-
hostname: (0, _url).stripPort(req.headers["host"])
|
|
73
|
+
hostname: (0, _url).stripPort(req.headers["host"]),
|
|
74
|
+
protocol: req.headers["x-forwarded-proto"]
|
|
74
75
|
};
|
|
75
76
|
}
|
|
76
77
|
getDefaultResponseHeaders() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/ExpoGoManifestHandlerMiddleware.ts"],"sourcesContent":["import { ExpoUpdatesManifest } from '@expo/config';\nimport { Updates } from '@expo/config-plugins';\nimport accepts from 'accepts';\nimport crypto from 'crypto';\nimport FormData from 'form-data';\nimport { serializeDictionary, Dictionary } from 'structured-headers';\n\nimport { ManifestMiddleware, ManifestRequestInfo } from './ManifestMiddleware';\nimport { assertRuntimePlatform, parsePlatformHeader } from './resolvePlatform';\nimport { ServerHeaders, ServerRequest } from './server.types';\nimport UserSettings from '../../../api/user/UserSettings';\nimport { ANONYMOUS_USERNAME } from '../../../api/user/user';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport {\n CodeSigningInfo,\n getCodeSigningInfoAsync,\n signManifestString,\n} from '../../../utils/codesigning';\nimport { CommandError } from '../../../utils/errors';\nimport { stripPort } from '../../../utils/url';\n\nconst debug = require('debug')('expo:start:server:middleware:ExpoGoManifestHandlerMiddleware');\n\nexport enum ResponseContentType {\n TEXT_PLAIN,\n APPLICATION_JSON,\n APPLICATION_EXPO_JSON,\n MULTIPART_MIXED,\n}\n\ninterface ExpoGoManifestRequestInfo extends ManifestRequestInfo {\n responseContentType: ResponseContentType;\n expectSignature: string | null;\n}\n\nexport class ExpoGoManifestHandlerMiddleware extends ManifestMiddleware<ExpoGoManifestRequestInfo> {\n public getParsedHeaders(req: ServerRequest): ExpoGoManifestRequestInfo {\n let platform = parsePlatformHeader(req);\n\n if (!platform) {\n debug(\n `No \"expo-platform\" header or \"platform\" query parameter specified. Falling back to \"ios\".`\n );\n platform = 'ios';\n }\n\n assertRuntimePlatform(platform);\n\n // Expo Updates clients explicitly accept \"multipart/mixed\" responses while browsers implicitly\n // accept them with \"accept: */*\". To make it easier to debug manifest responses by visiting their\n // URLs in a browser, we denote the response as \"text/plain\" if the user agent appears not to be\n // an Expo Updates client.\n const accept = accepts(req);\n const acceptedType = accept.types([\n 'unknown/unknown',\n 'multipart/mixed',\n 'application/json',\n 'application/expo+json',\n 'text/plain',\n ]);\n\n let responseContentType;\n switch (acceptedType) {\n case 'multipart/mixed':\n responseContentType = ResponseContentType.MULTIPART_MIXED;\n break;\n case 'application/json':\n responseContentType = ResponseContentType.APPLICATION_JSON;\n break;\n case 'application/expo+json':\n responseContentType = ResponseContentType.APPLICATION_EXPO_JSON;\n break;\n default:\n responseContentType = ResponseContentType.TEXT_PLAIN;\n break;\n }\n\n const expectSignature = req.headers['expo-expect-signature'];\n\n return {\n responseContentType,\n platform,\n expectSignature: expectSignature ? String(expectSignature) : null,\n hostname: stripPort(req.headers['host']),\n };\n }\n\n private getDefaultResponseHeaders(): ServerHeaders {\n const headers = new Map<string, number | string | readonly string[]>();\n // set required headers for Expo Updates manifest specification\n headers.set('expo-protocol-version', 0);\n headers.set('expo-sfv-version', 0);\n headers.set('cache-control', 'private, max-age=0');\n return headers;\n }\n\n public async _getManifestResponseAsync(requestOptions: ExpoGoManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }> {\n const { exp, hostUri, expoGoConfig, bundleUrl } =\n await this._resolveProjectSettingsAsync(requestOptions);\n\n const runtimeVersion = await Updates.getRuntimeVersionAsync(\n this.projectRoot,\n { ...exp, runtimeVersion: exp.runtimeVersion ?? { policy: 'sdkVersion' } },\n requestOptions.platform\n );\n if (!runtimeVersion) {\n throw new CommandError(\n 'MANIFEST_MIDDLEWARE',\n `Unable to determine runtime version for platform '${requestOptions.platform}'`\n );\n }\n\n const codeSigningInfo = await getCodeSigningInfoAsync(\n exp,\n requestOptions.expectSignature,\n this.options.privateKeyPath\n );\n\n const easProjectId = exp.extra?.eas?.projectId as string | undefined | null;\n const scopeKey = await ExpoGoManifestHandlerMiddleware.getScopeKeyAsync({\n slug: exp.slug,\n codeSigningInfo,\n });\n\n const expoUpdatesManifest: ExpoUpdatesManifest = {\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n runtimeVersion,\n launchAsset: {\n key: 'bundle',\n contentType: 'application/javascript',\n url: bundleUrl,\n },\n assets: [], // assets are not used in development\n metadata: {}, // required for the client to detect that this is an expo-updates manifest\n extra: {\n eas: {\n projectId: easProjectId ?? undefined,\n },\n expoClient: {\n ...exp,\n hostUri,\n },\n expoGo: expoGoConfig,\n scopeKey,\n },\n };\n\n const stringifiedManifest = JSON.stringify(expoUpdatesManifest);\n\n let manifestPartHeaders: { 'expo-signature': string } | null = null;\n let certificateChainBody: string | null = null;\n if (codeSigningInfo) {\n const signature = signManifestString(stringifiedManifest, codeSigningInfo);\n manifestPartHeaders = {\n 'expo-signature': serializeDictionary(\n convertToDictionaryItemsRepresentation({\n keyid: codeSigningInfo.keyId,\n sig: signature,\n alg: 'rsa-v1_5-sha256',\n })\n ),\n };\n certificateChainBody = codeSigningInfo.certificateChainForResponse.join('\\n');\n }\n\n const headers = this.getDefaultResponseHeaders();\n\n switch (requestOptions.responseContentType) {\n case ResponseContentType.MULTIPART_MIXED: {\n const form = this.getFormData({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n });\n headers.set('content-type', `multipart/mixed; boundary=${form.getBoundary()}`);\n return {\n body: form.getBuffer().toString(),\n version: runtimeVersion,\n headers,\n };\n }\n case ResponseContentType.APPLICATION_EXPO_JSON:\n case ResponseContentType.APPLICATION_JSON:\n case ResponseContentType.TEXT_PLAIN: {\n headers.set(\n 'content-type',\n ExpoGoManifestHandlerMiddleware.getContentTypeForResponseContentType(\n requestOptions.responseContentType\n )\n );\n if (manifestPartHeaders) {\n Object.entries(manifestPartHeaders).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n return {\n body: stringifiedManifest,\n version: runtimeVersion,\n headers,\n };\n }\n }\n }\n\n private static getContentTypeForResponseContentType(\n responseContentType: ResponseContentType\n ): string {\n switch (responseContentType) {\n case ResponseContentType.MULTIPART_MIXED:\n return 'multipart/mixed';\n case ResponseContentType.APPLICATION_EXPO_JSON:\n return 'application/expo+json';\n case ResponseContentType.APPLICATION_JSON:\n return 'application/json';\n case ResponseContentType.TEXT_PLAIN:\n return 'text/plain';\n }\n }\n\n private getFormData({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n }: {\n stringifiedManifest: string;\n manifestPartHeaders: { 'expo-signature': string } | null;\n certificateChainBody: string | null;\n }): FormData {\n const form = new FormData();\n form.append('manifest', stringifiedManifest, {\n contentType: 'application/json',\n header: {\n ...manifestPartHeaders,\n },\n });\n if (certificateChainBody && certificateChainBody.length > 0) {\n form.append('certificate_chain', certificateChainBody, {\n contentType: 'application/x-pem-file',\n });\n }\n return form;\n }\n\n protected trackManifest(version?: string) {\n logEventAsync('Serve Expo Updates Manifest', {\n runtimeVersion: version,\n });\n }\n\n private static async getScopeKeyAsync({\n slug,\n codeSigningInfo,\n }: {\n slug: string;\n codeSigningInfo: CodeSigningInfo | null;\n }): Promise<string> {\n const scopeKeyFromCodeSigningInfo = codeSigningInfo?.scopeKey;\n if (scopeKeyFromCodeSigningInfo) {\n return scopeKeyFromCodeSigningInfo;\n }\n\n // Log.warn(\n // env.EXPO_OFFLINE\n // ? 'Using anonymous scope key in manifest for offline mode.'\n // : 'Using anonymous scope key in manifest.'\n // );\n return await getAnonymousScopeKeyAsync(slug);\n }\n}\n\nasync function getAnonymousScopeKeyAsync(slug: string): Promise<string> {\n const userAnonymousIdentifier = await UserSettings.getAnonymousIdentifierAsync();\n return `@${ANONYMOUS_USERNAME}/${slug}-${userAnonymousIdentifier}`;\n}\n\nfunction convertToDictionaryItemsRepresentation(obj: { [key: string]: string }): Dictionary {\n return new Map(\n Object.entries(obj).map(([k, v]) => {\n return [k, [v, new Map()]];\n })\n );\n}\n"],"names":["debug","require","ResponseContentType","TEXT_PLAIN","APPLICATION_JSON","APPLICATION_EXPO_JSON","MULTIPART_MIXED","ExpoGoManifestHandlerMiddleware","ManifestMiddleware","getParsedHeaders","req","platform","parsePlatformHeader","assertRuntimePlatform","accept","accepts","acceptedType","types","responseContentType","expectSignature","headers","String","hostname","stripPort","getDefaultResponseHeaders","Map","set","_getManifestResponseAsync","requestOptions","exp","hostUri","expoGoConfig","bundleUrl","_resolveProjectSettingsAsync","runtimeVersion","Updates","getRuntimeVersionAsync","projectRoot","policy","CommandError","codeSigningInfo","getCodeSigningInfoAsync","options","privateKeyPath","easProjectId","extra","eas","projectId","scopeKey","getScopeKeyAsync","slug","expoUpdatesManifest","id","crypto","randomUUID","createdAt","Date","toISOString","launchAsset","key","contentType","url","assets","metadata","undefined","expoClient","expoGo","stringifiedManifest","JSON","stringify","manifestPartHeaders","certificateChainBody","signature","signManifestString","serializeDictionary","convertToDictionaryItemsRepresentation","keyid","keyId","sig","alg","certificateChainForResponse","join","form","getFormData","getBoundary","body","getBuffer","toString","version","getContentTypeForResponseContentType","Object","entries","forEach","value","FormData","append","header","length","trackManifest","logEventAsync","scopeKeyFromCodeSigningInfo","getAnonymousScopeKeyAsync","userAnonymousIdentifier","UserSettings","getAnonymousIdentifierAsync","ANONYMOUS_USERNAME","obj","map","k","v"],"mappings":"AAAA;;;;;AACwB,IAAA,cAAsB,WAAtB,sBAAsB,CAAA;AAC1B,IAAA,QAAS,kCAAT,SAAS,EAAA;AACV,IAAA,OAAQ,kCAAR,QAAQ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AAAC;IACjF,OAAO,CAAC,CAAC,EAAEC,KAAkB,mBAAA,CAAC,CAAC,EAAEvD,IAAI,CAAC,CAAC,EAAEoD,uBAAuB,CAAC,CAAC,CAAC;CACpE;AAED,SAAS3B,sCAAsC,CAAC+B,GAA8B,EAAc;IAC1F,OAAO,IAAIjF,GAAG,CACZiE,MAAM,CAACC,OAAO,CAACe,GAAG,CAAC,CAACC,GAAG,CAAC,CAAC,CAACC,CAAC,EAAEC,CAAC,CAAC,GAAK;QAClC,OAAO;YAACD,CAAC;YAAE;gBAACC,CAAC;gBAAE,IAAIpF,GAAG,EAAE;aAAC;SAAC,CAAC;KAC5B,CAAC,CACH,CAAC;CACH"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/ExpoGoManifestHandlerMiddleware.ts"],"sourcesContent":["import { ExpoUpdatesManifest } from '@expo/config';\nimport { Updates } from '@expo/config-plugins';\nimport accepts from 'accepts';\nimport crypto from 'crypto';\nimport FormData from 'form-data';\nimport { serializeDictionary, Dictionary } from 'structured-headers';\n\nimport { ManifestMiddleware, ManifestRequestInfo } from './ManifestMiddleware';\nimport { assertRuntimePlatform, parsePlatformHeader } from './resolvePlatform';\nimport { ServerHeaders, ServerRequest } from './server.types';\nimport UserSettings from '../../../api/user/UserSettings';\nimport { ANONYMOUS_USERNAME } from '../../../api/user/user';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport {\n CodeSigningInfo,\n getCodeSigningInfoAsync,\n signManifestString,\n} from '../../../utils/codesigning';\nimport { CommandError } from '../../../utils/errors';\nimport { stripPort } from '../../../utils/url';\n\nconst debug = require('debug')('expo:start:server:middleware:ExpoGoManifestHandlerMiddleware');\n\nexport enum ResponseContentType {\n TEXT_PLAIN,\n APPLICATION_JSON,\n APPLICATION_EXPO_JSON,\n MULTIPART_MIXED,\n}\n\ninterface ExpoGoManifestRequestInfo extends ManifestRequestInfo {\n responseContentType: ResponseContentType;\n expectSignature: string | null;\n}\n\nexport class ExpoGoManifestHandlerMiddleware extends ManifestMiddleware<ExpoGoManifestRequestInfo> {\n public getParsedHeaders(req: ServerRequest): ExpoGoManifestRequestInfo {\n let platform = parsePlatformHeader(req);\n\n if (!platform) {\n debug(\n `No \"expo-platform\" header or \"platform\" query parameter specified. Falling back to \"ios\".`\n );\n platform = 'ios';\n }\n\n assertRuntimePlatform(platform);\n\n // Expo Updates clients explicitly accept \"multipart/mixed\" responses while browsers implicitly\n // accept them with \"accept: */*\". To make it easier to debug manifest responses by visiting their\n // URLs in a browser, we denote the response as \"text/plain\" if the user agent appears not to be\n // an Expo Updates client.\n const accept = accepts(req);\n const acceptedType = accept.types([\n 'unknown/unknown',\n 'multipart/mixed',\n 'application/json',\n 'application/expo+json',\n 'text/plain',\n ]);\n\n let responseContentType;\n switch (acceptedType) {\n case 'multipart/mixed':\n responseContentType = ResponseContentType.MULTIPART_MIXED;\n break;\n case 'application/json':\n responseContentType = ResponseContentType.APPLICATION_JSON;\n break;\n case 'application/expo+json':\n responseContentType = ResponseContentType.APPLICATION_EXPO_JSON;\n break;\n default:\n responseContentType = ResponseContentType.TEXT_PLAIN;\n break;\n }\n\n const expectSignature = req.headers['expo-expect-signature'];\n\n return {\n responseContentType,\n platform,\n expectSignature: expectSignature ? String(expectSignature) : null,\n hostname: stripPort(req.headers['host']),\n protocol: req.headers['x-forwarded-proto'] as 'http' | 'https' | undefined,\n };\n }\n\n private getDefaultResponseHeaders(): ServerHeaders {\n const headers = new Map<string, number | string | readonly string[]>();\n // set required headers for Expo Updates manifest specification\n headers.set('expo-protocol-version', 0);\n headers.set('expo-sfv-version', 0);\n headers.set('cache-control', 'private, max-age=0');\n return headers;\n }\n\n public async _getManifestResponseAsync(requestOptions: ExpoGoManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }> {\n const { exp, hostUri, expoGoConfig, bundleUrl } =\n await this._resolveProjectSettingsAsync(requestOptions);\n\n const runtimeVersion = await Updates.getRuntimeVersionAsync(\n this.projectRoot,\n { ...exp, runtimeVersion: exp.runtimeVersion ?? { policy: 'sdkVersion' } },\n requestOptions.platform\n );\n if (!runtimeVersion) {\n throw new CommandError(\n 'MANIFEST_MIDDLEWARE',\n `Unable to determine runtime version for platform '${requestOptions.platform}'`\n );\n }\n\n const codeSigningInfo = await getCodeSigningInfoAsync(\n exp,\n requestOptions.expectSignature,\n this.options.privateKeyPath\n );\n\n const easProjectId = exp.extra?.eas?.projectId as string | undefined | null;\n const scopeKey = await ExpoGoManifestHandlerMiddleware.getScopeKeyAsync({\n slug: exp.slug,\n codeSigningInfo,\n });\n\n const expoUpdatesManifest: ExpoUpdatesManifest = {\n id: crypto.randomUUID(),\n createdAt: new Date().toISOString(),\n runtimeVersion,\n launchAsset: {\n key: 'bundle',\n contentType: 'application/javascript',\n url: bundleUrl,\n },\n assets: [], // assets are not used in development\n metadata: {}, // required for the client to detect that this is an expo-updates manifest\n extra: {\n eas: {\n projectId: easProjectId ?? undefined,\n },\n expoClient: {\n ...exp,\n hostUri,\n },\n expoGo: expoGoConfig,\n scopeKey,\n },\n };\n\n const stringifiedManifest = JSON.stringify(expoUpdatesManifest);\n\n let manifestPartHeaders: { 'expo-signature': string } | null = null;\n let certificateChainBody: string | null = null;\n if (codeSigningInfo) {\n const signature = signManifestString(stringifiedManifest, codeSigningInfo);\n manifestPartHeaders = {\n 'expo-signature': serializeDictionary(\n convertToDictionaryItemsRepresentation({\n keyid: codeSigningInfo.keyId,\n sig: signature,\n alg: 'rsa-v1_5-sha256',\n })\n ),\n };\n certificateChainBody = codeSigningInfo.certificateChainForResponse.join('\\n');\n }\n\n const headers = this.getDefaultResponseHeaders();\n\n switch (requestOptions.responseContentType) {\n case ResponseContentType.MULTIPART_MIXED: {\n const form = this.getFormData({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n });\n headers.set('content-type', `multipart/mixed; boundary=${form.getBoundary()}`);\n return {\n body: form.getBuffer().toString(),\n version: runtimeVersion,\n headers,\n };\n }\n case ResponseContentType.APPLICATION_EXPO_JSON:\n case ResponseContentType.APPLICATION_JSON:\n case ResponseContentType.TEXT_PLAIN: {\n headers.set(\n 'content-type',\n ExpoGoManifestHandlerMiddleware.getContentTypeForResponseContentType(\n requestOptions.responseContentType\n )\n );\n if (manifestPartHeaders) {\n Object.entries(manifestPartHeaders).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n return {\n body: stringifiedManifest,\n version: runtimeVersion,\n headers,\n };\n }\n }\n }\n\n private static getContentTypeForResponseContentType(\n responseContentType: ResponseContentType\n ): string {\n switch (responseContentType) {\n case ResponseContentType.MULTIPART_MIXED:\n return 'multipart/mixed';\n case ResponseContentType.APPLICATION_EXPO_JSON:\n return 'application/expo+json';\n case ResponseContentType.APPLICATION_JSON:\n return 'application/json';\n case ResponseContentType.TEXT_PLAIN:\n return 'text/plain';\n }\n }\n\n private getFormData({\n stringifiedManifest,\n manifestPartHeaders,\n certificateChainBody,\n }: {\n stringifiedManifest: string;\n manifestPartHeaders: { 'expo-signature': string } | null;\n certificateChainBody: string | null;\n }): FormData {\n const form = new FormData();\n form.append('manifest', stringifiedManifest, {\n contentType: 'application/json',\n header: {\n ...manifestPartHeaders,\n },\n });\n if (certificateChainBody && certificateChainBody.length > 0) {\n form.append('certificate_chain', certificateChainBody, {\n contentType: 'application/x-pem-file',\n });\n }\n return form;\n }\n\n protected trackManifest(version?: string) {\n logEventAsync('Serve Expo Updates Manifest', {\n runtimeVersion: version,\n });\n }\n\n private static async getScopeKeyAsync({\n slug,\n codeSigningInfo,\n }: {\n slug: string;\n codeSigningInfo: CodeSigningInfo | null;\n }): Promise<string> {\n const scopeKeyFromCodeSigningInfo = codeSigningInfo?.scopeKey;\n if (scopeKeyFromCodeSigningInfo) {\n return scopeKeyFromCodeSigningInfo;\n }\n\n // Log.warn(\n // env.EXPO_OFFLINE\n // ? 'Using anonymous scope key in manifest for offline mode.'\n // : 'Using anonymous scope key in manifest.'\n // );\n return await getAnonymousScopeKeyAsync(slug);\n }\n}\n\nasync function getAnonymousScopeKeyAsync(slug: string): Promise<string> {\n const userAnonymousIdentifier = await UserSettings.getAnonymousIdentifierAsync();\n return `@${ANONYMOUS_USERNAME}/${slug}-${userAnonymousIdentifier}`;\n}\n\nfunction convertToDictionaryItemsRepresentation(obj: { [key: string]: string }): Dictionary {\n return new Map(\n Object.entries(obj).map(([k, v]) => {\n return [k, [v, new Map()]];\n })\n );\n}\n"],"names":["debug","require","ResponseContentType","TEXT_PLAIN","APPLICATION_JSON","APPLICATION_EXPO_JSON","MULTIPART_MIXED","ExpoGoManifestHandlerMiddleware","ManifestMiddleware","getParsedHeaders","req","platform","parsePlatformHeader","assertRuntimePlatform","accept","accepts","acceptedType","types","responseContentType","expectSignature","headers","String","hostname","stripPort","protocol","getDefaultResponseHeaders","Map","set","_getManifestResponseAsync","requestOptions","exp","hostUri","expoGoConfig","bundleUrl","_resolveProjectSettingsAsync","runtimeVersion","Updates","getRuntimeVersionAsync","projectRoot","policy","CommandError","codeSigningInfo","getCodeSigningInfoAsync","options","privateKeyPath","easProjectId","extra","eas","projectId","scopeKey","getScopeKeyAsync","slug","expoUpdatesManifest","id","crypto","randomUUID","createdAt","Date","toISOString","launchAsset","key","contentType","url","assets","metadata","undefined","expoClient","expoGo","stringifiedManifest","JSON","stringify","manifestPartHeaders","certificateChainBody","signature","signManifestString","serializeDictionary","convertToDictionaryItemsRepresentation","keyid","keyId","sig","alg","certificateChainForResponse","join","form","getFormData","getBoundary","body","getBuffer","toString","version","getContentTypeForResponseContentType","Object","entries","forEach","value","FormData","append","header","length","trackManifest","logEventAsync","scopeKeyFromCodeSigningInfo","getAnonymousScopeKeyAsync","userAnonymousIdentifier","UserSettings","getAnonymousIdentifierAsync","ANONYMOUS_USERNAME","obj","map","k","v"],"mappings":"AAAA;;;;;AACwB,IAAA,cAAsB,WAAtB,sBAAsB,CAAA;AAC1B,IAAA,QAAS,kCAAT,SAAS,EAAA;AACV,IAAA,OAAQ,kCAAR,QAAQ,EAAA;A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AuB,GAAG,MAAMC,aAAY,QAAA,CAACC,2BAA2B,EAAE,AAAC;IACjF,OAAO,CAAC,CAAC,EAAEC,KAAkB,mBAAA,CAAC,CAAC,EAAEvD,IAAI,CAAC,CAAC,EAAEoD,uBAAuB,CAAC,CAAC,CAAC;CACpE;AAED,SAAS3B,sCAAsC,CAAC+B,GAA8B,EAAc;IAC1F,OAAO,IAAIjF,GAAG,CACZiE,MAAM,CAACC,OAAO,CAACe,GAAG,CAAC,CAACC,GAAG,CAAC,CAAC,CAACC,CAAC,EAAEC,CAAC,CAAC,GAAK;QAClC,OAAO;YAACD,CAAC;YAAE;gBAACC,CAAC;gBAAE,IAAIpF,GAAG,EAAE;aAAC;SAAC,CAAC;KAC5B,CAAC,CACH,CAAC;CACH"}
|
|
@@ -102,7 +102,7 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
|
|
|
102
102
|
this.initialProjectConfig = (0, _config).getConfig(projectRoot);
|
|
103
103
|
this.platformBundlers = (0, _platformBundlers).getPlatformBundlers(projectRoot, this.initialProjectConfig.exp);
|
|
104
104
|
}
|
|
105
|
-
/** Exposed for testing. */ async _resolveProjectSettingsAsync({ platform , hostname }) {
|
|
105
|
+
/** Exposed for testing. */ async _resolveProjectSettingsAsync({ platform , hostname , protocol }) {
|
|
106
106
|
// Read the config
|
|
107
107
|
const projectConfig = (0, _config).getConfig(this.projectRoot);
|
|
108
108
|
// Read from headers
|
|
@@ -128,7 +128,8 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
|
|
|
128
128
|
engine: isHermesEnabled ? "hermes" : undefined,
|
|
129
129
|
baseUrl: (0, _metroOptions).getBaseUrlFromExpoConfig(projectConfig.exp),
|
|
130
130
|
asyncRoutes: (0, _metroOptions).getAsyncRoutesFromExpoConfig(projectConfig.exp, (_mode = this.options.mode) != null ? _mode : "development", platform),
|
|
131
|
-
routerRoot: (0, _router).getRouterDirectoryModuleIdWithManifest(this.projectRoot, projectConfig.exp)
|
|
131
|
+
routerRoot: (0, _router).getRouterDirectoryModuleIdWithManifest(this.projectRoot, projectConfig.exp),
|
|
132
|
+
protocol
|
|
132
133
|
});
|
|
133
134
|
// Resolve all assets and set them on the manifest as URLs
|
|
134
135
|
await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);
|
|
@@ -161,7 +162,7 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
|
|
|
161
162
|
);
|
|
162
163
|
}
|
|
163
164
|
}
|
|
164
|
-
/** Create the bundle URL (points to the single JS entry file). Exposed for testing. */ _getBundleUrl({ platform , mainModuleName , hostname , engine , baseUrl , isExporting , asyncRoutes , routerRoot }) {
|
|
165
|
+
/** Create the bundle URL (points to the single JS entry file). Exposed for testing. */ _getBundleUrl({ platform , mainModuleName , hostname , engine , baseUrl , isExporting , asyncRoutes , routerRoot , protocol }) {
|
|
165
166
|
var _mode;
|
|
166
167
|
const path = (0, _metroOptions).createBundleUrlPath({
|
|
167
168
|
mode: (_mode = this.options.mode) != null ? _mode : "development",
|
|
@@ -176,7 +177,7 @@ class ManifestMiddleware extends _expoMiddleware.ExpoMiddleware {
|
|
|
176
177
|
routerRoot
|
|
177
178
|
});
|
|
178
179
|
return this.options.constructUrl({
|
|
179
|
-
scheme: "http",
|
|
180
|
+
scheme: protocol != null ? protocol : "http",
|
|
180
181
|
// hostType: this.options.location.hostType,
|
|
181
182
|
hostname
|
|
182
183
|
}) + path;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/ManifestMiddleware.ts"],"sourcesContent":["import {\n ExpoConfig,\n ExpoGoConfig,\n getConfig,\n PackageJSONConfig,\n ProjectConfig,\n} from '@expo/config';\nimport { resolveEntryPoint } from '@expo/config/paths';\nimport findWorkspaceRoot from 'find-yarn-workspace-root';\nimport path from 'path';\nimport { resolve } from 'url';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport {\n shouldEnableAsyncImports,\n createBundleUrlPath,\n getBaseUrlFromExpoConfig,\n getAsyncRoutesFromExpoConfig,\n createBundleUrlPathFromExpoConfig,\n} from './metroOptions';\nimport { resolveGoogleServicesFile, resolveManifestAssets } from './resolveAssets';\nimport { parsePlatformHeader, RuntimePlatform } from './resolvePlatform';\nimport { ServerHeaders, ServerNext, ServerRequest, ServerResponse } from './server.types';\nimport { isEnableHermesManaged } from '../../../export/exportHermes';\nimport * as Log from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { stripExtension } from '../../../utils/url';\nimport * as ProjectDevices from '../../project/devices';\nimport { UrlCreator } from '../UrlCreator';\nimport { getRouterDirectoryModuleIdWithManifest } from '../metro/router';\nimport { getPlatformBundlers, PlatformBundlers } from '../platformBundlers';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../webTemplate';\n\nconst debug = require('debug')('expo:start:server:middleware:manifest') as typeof console.log;\n\n/** Wraps `findWorkspaceRoot` and guards against having an empty `package.json` file in an upper directory. */\nexport function getWorkspaceRoot(projectRoot: string): string | null {\n try {\n return findWorkspaceRoot(projectRoot);\n } catch (error: any) {\n if (error.message.includes('Unexpected end of JSON input')) {\n return null;\n }\n throw error;\n }\n}\n\nconst supportedPlatforms = ['ios', 'android', 'web', 'none'];\n\nexport function getEntryWithServerRoot(\n projectRoot: string,\n props: { platform: string; pkg?: PackageJSONConfig }\n) {\n if (!supportedPlatforms.includes(props.platform)) {\n throw new CommandError(\n `Failed to resolve the project's entry file: The platform \"${props.platform}\" is not supported.`\n );\n }\n return path.relative(getMetroServerRoot(projectRoot), resolveEntryPoint(projectRoot, props));\n}\n\nexport function getMetroServerRoot(projectRoot: string) {\n if (env.EXPO_USE_METRO_WORKSPACE_ROOT) {\n return getWorkspaceRoot(projectRoot) ?? projectRoot;\n }\n\n return projectRoot;\n}\n\n/** Get the main entry module ID (file) relative to the project root. */\nexport function resolveMainModuleName(\n projectRoot: string,\n props: { platform: string; pkg?: PackageJSONConfig }\n): string {\n const entryPoint = getEntryWithServerRoot(projectRoot, props);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${projectRoot})`);\n\n return stripExtension(entryPoint, 'js');\n}\n\n/** Info about the computer hosting the dev server. */\nexport interface HostInfo {\n host: string;\n server: 'expo';\n serverVersion: string;\n serverDriver: string | null;\n serverOS: NodeJS.Platform;\n serverOSVersion: string;\n}\n\n/** Parsed values from the supported request headers. */\nexport interface ManifestRequestInfo {\n /** Platform to serve. */\n platform: RuntimePlatform;\n /** Requested host name. */\n hostname?: string | null;\n}\n\n/** Project related info. */\nexport type ResponseProjectSettings = {\n expoGoConfig: ExpoGoConfig;\n hostUri: string;\n bundleUrl: string;\n exp: ExpoConfig;\n};\n\nexport const DEVELOPER_TOOL = 'expo-cli';\n\nexport type ManifestMiddlewareOptions = {\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n constructUrl: UrlCreator['constructUrl'];\n isNativeWebpack?: boolean;\n privateKeyPath?: string;\n};\n\n/** Base middleware creator for serving the Expo manifest (like the index.html but for native runtimes). */\nexport abstract class ManifestMiddleware<\n TManifestRequestInfo extends ManifestRequestInfo,\n> extends ExpoMiddleware {\n private initialProjectConfig: ProjectConfig;\n private platformBundlers: PlatformBundlers;\n\n constructor(\n protected projectRoot: string,\n protected options: ManifestMiddlewareOptions\n ) {\n super(\n projectRoot,\n /**\n * Only support `/`, `/manifest`, `/index.exp` for the manifest middleware.\n */\n ['/', '/manifest', '/index.exp']\n );\n this.initialProjectConfig = getConfig(projectRoot);\n this.platformBundlers = getPlatformBundlers(projectRoot, this.initialProjectConfig.exp);\n }\n\n /** Exposed for testing. */\n public async _resolveProjectSettingsAsync({\n platform,\n hostname,\n }: Pick<TManifestRequestInfo, 'hostname' | 'platform'>): Promise<ResponseProjectSettings> {\n // Read the config\n const projectConfig = getConfig(this.projectRoot);\n\n // Read from headers\n const mainModuleName = this.resolveMainModuleName({\n pkg: projectConfig.pkg,\n platform,\n });\n\n const isHermesEnabled = isEnableHermesManaged(projectConfig.exp, platform);\n\n // Create the manifest and set fields within it\n const expoGoConfig = this.getExpoGoConfig({\n mainModuleName,\n hostname,\n });\n\n const hostUri = this.options.constructUrl({ scheme: '', hostname });\n\n const bundleUrl = this._getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n engine: isHermesEnabled ? 'hermes' : undefined,\n baseUrl: getBaseUrlFromExpoConfig(projectConfig.exp),\n asyncRoutes: getAsyncRoutesFromExpoConfig(\n projectConfig.exp,\n this.options.mode ?? 'development',\n platform\n ),\n routerRoot: getRouterDirectoryModuleIdWithManifest(this.projectRoot, projectConfig.exp),\n });\n\n // Resolve all assets and set them on the manifest as URLs\n await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);\n\n return {\n expoGoConfig,\n hostUri,\n bundleUrl,\n exp: projectConfig.exp,\n };\n }\n\n /** Get the main entry module ID (file) relative to the project root. */\n private resolveMainModuleName(props: { pkg: PackageJSONConfig; platform: string }): string {\n let entryPoint = getEntryWithServerRoot(this.projectRoot, props);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${this.projectRoot})`);\n\n // NOTE(Bacon): Webpack is currently hardcoded to index.bundle on native\n // in the future (TODO) we should move this logic into a Webpack plugin and use\n // a generated file name like we do on web.\n // const server = getDefaultDevServer();\n // // TODO: Move this into BundlerDevServer and read this info from self.\n // const isNativeWebpack = server instanceof WebpackBundlerDevServer && server.isTargetingNative();\n if (this.options.isNativeWebpack) {\n entryPoint = 'index.js';\n }\n\n return stripExtension(entryPoint, 'js');\n }\n\n /** Parse request headers into options. */\n public abstract getParsedHeaders(req: ServerRequest): TManifestRequestInfo;\n\n /** Store device IDs that were sent in the request headers. */\n private async saveDevicesAsync(req: ServerRequest) {\n const deviceIds = req.headers?.['expo-dev-client-id'];\n if (deviceIds) {\n await ProjectDevices.saveDevicesAsync(this.projectRoot, deviceIds).catch((e) =>\n Log.exception(e)\n );\n }\n }\n\n /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */\n public _getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n engine,\n baseUrl,\n isExporting,\n asyncRoutes,\n routerRoot,\n }: {\n platform: string;\n hostname?: string | null;\n mainModuleName: string;\n engine?: 'hermes';\n baseUrl?: string;\n asyncRoutes: boolean;\n isExporting?: boolean;\n routerRoot: string;\n }): string {\n const path = createBundleUrlPath({\n mode: this.options.mode ?? 'development',\n minify: this.options.minify,\n platform,\n mainModuleName,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n engine,\n baseUrl,\n isExporting: !!isExporting,\n asyncRoutes,\n routerRoot,\n });\n\n return (\n this.options.constructUrl({\n scheme: 'http',\n // hostType: this.options.location.hostType,\n hostname,\n }) + path\n );\n }\n\n /** Log telemetry. */\n protected abstract trackManifest(version?: string): void;\n\n /** Get the manifest response to return to the runtime. This file contains info regarding where the assets can be loaded from. Exposed for testing. */\n public abstract _getManifestResponseAsync(options: TManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }>;\n\n private getExpoGoConfig({\n mainModuleName,\n hostname,\n }: {\n mainModuleName: string;\n hostname?: string | null;\n }): ExpoGoConfig {\n return {\n // localhost:8081\n debuggerHost: this.options.constructUrl({ scheme: '', hostname }),\n // Required for Expo Go to function.\n developer: {\n tool: DEVELOPER_TOOL,\n projectRoot: this.projectRoot,\n },\n packagerOpts: {\n // Required for dev client.\n dev: this.options.mode !== 'production',\n },\n // Indicates the name of the main bundle.\n mainModuleName,\n // Add this string to make Flipper register React Native / Metro as \"running\".\n // Can be tested by running:\n // `METRO_SERVER_PORT=8081 open -a flipper.app`\n // Where 8081 is the port where the Expo project is being hosted.\n __flipperHack: 'React Native packager is running',\n };\n }\n\n /** Resolve all assets and set them on the manifest as URLs */\n private async mutateManifestWithAssetsAsync(manifest: ExpoConfig, bundleUrl: string) {\n await resolveManifestAssets(this.projectRoot, {\n manifest,\n resolver: async (path) => {\n if (this.options.isNativeWebpack) {\n // When using our custom dev server, just do assets normally\n // without the `assets/` subpath redirect.\n return resolve(bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0], path);\n }\n return bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0] + 'assets/' + path;\n },\n });\n // The server normally inserts this but if we're offline we'll do it here\n await resolveGoogleServicesFile(this.projectRoot, manifest);\n }\n\n public getWebBundleUrl() {\n const platform = 'web';\n // Read from headers\n const mainModuleName = this.resolveMainModuleName({\n pkg: this.initialProjectConfig.pkg,\n platform,\n });\n\n return createBundleUrlPathFromExpoConfig(this.projectRoot, this.initialProjectConfig.exp, {\n platform,\n mainModuleName,\n minify: this.options.minify,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n mode: this.options.mode ?? 'development',\n // Hermes doesn't support more modern JS features than most, if not all, modern browser.\n engine: 'hermes',\n isExporting: false,\n });\n }\n\n /**\n * Web platforms should create an index.html response using the same script resolution as native.\n *\n * Instead of adding a `bundleUrl` to a `manifest.json` (native) we'll add a `<script src=\"\">`\n * to an `index.html`, this enables the web platform to load JavaScript from the server.\n */\n private async handleWebRequestAsync(req: ServerRequest, res: ServerResponse) {\n // Read from headers\n const bundleUrl = this.getWebBundleUrl();\n\n res.setHeader('Content-Type', 'text/html');\n\n res.end(\n await createTemplateHtmlFromExpoConfigAsync(this.projectRoot, {\n exp: this.initialProjectConfig.exp,\n scripts: [bundleUrl],\n })\n );\n }\n\n /** Exposed for testing. */\n async checkBrowserRequestAsync(req: ServerRequest, res: ServerResponse, next: ServerNext) {\n if (\n this.platformBundlers.web === 'metro' &&\n this.initialProjectConfig.exp.platforms?.includes('web')\n ) {\n // NOTE(EvanBacon): This effectively disables the safety check we do on custom runtimes to ensure\n // the `expo-platform` header is included. When `web.bundler=web`, if the user has non-standard Expo\n // code loading then they'll get a web bundle without a clear assertion of platform support.\n const platform = parsePlatformHeader(req);\n // On web, serve the public folder\n if (!platform || platform === 'web') {\n if (['static', 'server'].includes(this.initialProjectConfig.exp.web?.output ?? '')) {\n // Skip the spa-styled index.html when static generation is enabled.\n next();\n return true;\n } else {\n await this.handleWebRequestAsync(req, res);\n return true;\n }\n }\n }\n return false;\n }\n\n async handleRequestAsync(\n req: ServerRequest,\n res: ServerResponse,\n next: ServerNext\n ): Promise<void> {\n // First check for standard JavaScript runtimes (aka legacy browsers like Chrome).\n if (await this.checkBrowserRequestAsync(req, res, next)) {\n return;\n }\n\n // Save device IDs for dev client.\n await this.saveDevicesAsync(req);\n\n // Read from headers\n const options = this.getParsedHeaders(req);\n const { body, version, headers } = await this._getManifestResponseAsync(options);\n for (const [headerName, headerValue] of headers) {\n res.setHeader(headerName, headerValue);\n }\n res.end(body);\n\n // Log analytics\n this.trackManifest(version ?? null);\n }\n}\n"],"names":["getWorkspaceRoot","getEntryWithServerRoot","getMetroServerRoot","resolveMainModuleName","Log","ProjectDevices","debug","require","projectRoot","findWorkspaceRoot","error","message","includes","supportedPlatforms","props","platform","CommandError","path","relative","resolveEntryPoint","env","EXPO_USE_METRO_WORKSPACE_ROOT","entryPoint","stripExtension","DEVELOPER_TOOL","ManifestMiddleware","ExpoMiddleware","constructor","options","initialProjectConfig","getConfig","platformBundlers","getPlatformBundlers","exp","_resolveProjectSettingsAsync","hostname","projectConfig","mainModuleName","pkg","isHermesEnabled","isEnableHermesManaged","expoGoConfig","getExpoGoConfig","hostUri","constructUrl","scheme","bundleUrl","_getBundleUrl","engine","undefined","baseUrl","getBaseUrlFromExpoConfig","asyncRoutes","getAsyncRoutesFromExpoConfig","mode","routerRoot","getRouterDirectoryModuleIdWithManifest","mutateManifestWithAssetsAsync","isNativeWebpack","saveDevicesAsync","req","deviceIds","headers","catch","e","exception","isExporting","createBundleUrlPath","minify","lazy","shouldEnableAsyncImports","debuggerHost","developer","tool","packagerOpts","dev","__flipperHack","manifest","resolveManifestAssets","resolver","resolve","match","resolveGoogleServicesFile","getWebBundleUrl","createBundleUrlPathFromExpoConfig","handleWebRequestAsync","res","setHeader","end","createTemplateHtmlFromExpoConfigAsync","scripts","checkBrowserRequestAsync","next","web","platforms","parsePlatformHeader","output","handleRequestAsync","getParsedHeaders","body","version","_getManifestResponseAsync","headerName","headerValue","trackManifest"],"mappings":"AAAA;;;;QAqCgBA,gBAAgB,GAAhBA,gBAAgB;QAahBC,sBAAsB,GAAtBA,sBAAsB;QAYtBC,kBAAkB,GAAlBA,kBAAkB;QASlBC,qBAAqB,GAArBA,qBAAqB;;AAjE9B,IAAA,OAAc,WAAd,cAAc,CAAA;AACa,IAAA,MAAoB,WAApB,oBAAoB,CAAA;AACxB,IAAA,sBAA0B,kCAA1B,0BAA0B,EAAA;AACvC,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,IAAK,WAAL,KAAK,CAAA;AAEE,IAAA,eAAkB,WAAlB,kBAAkB,CAAA;AAO1C,IAAA,aAAgB,WAAhB,gBAAgB,CAAA;AAC0C,IAAA,cAAiB,WAAjB,iBAAiB,CAAA;AAC7B,IAAA,gBAAmB,WAAnB,mBAAmB,CAAA;AAElC,IAAA,aAA8B,WAA9B,8BAA8B,CAAA;AACxDC,IAAAA,GAAG,mCAAM,cAAc,EAApB;AACK,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AACX,IAAA,OAAuB,WAAvB,uBAAuB,CAAA;AACrB,IAAA,KAAoB,WAApB,oBAAoB,CAAA;AACvCC,IAAAA,cAAc,mCAAM,uBAAuB,EAA7B;AAE6B,IAAA,OAAiB,WAAjB,iBAAiB,CAAA;AAClB,IAAA,iBAAqB,WAArB,qBAAqB,CAAA;AACrB,IAAA,YAAgB,WAAhB,gBAAgB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtE,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,uCAAuC,CAAC,AAAsB,AAAC;AAGvF,SAASP,gBAAgB,CAACQ,WAAmB,EAAiB;IACnE,IAAI;QACF,OAAOC,CAAAA,GAAAA,sBAAiB,AAAa,CAAA,QAAb,CAACD,WAAW,CAAC,CAAC;KACvC,CAAC,OAAOE,KAAK,E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AgB,EACD;QACf,kFAAkF;QAClF,IAAI,MAAM,IAAI,CAACD,wBAAwB,CAAC/B,GAAG,EAAE0B,GAAG,EAAEM,IAAI,CAAC,EAAE;YACvD,OAAO;SACR;QAED,kCAAkC;QAClC,MAAM,IAAI,CAACjC,gBAAgB,CAACC,GAAG,CAAC,CAAC;QAEjC,oBAAoB;QACpB,MAAMhC,OAAO,GAAG,IAAI,CAACsE,gBAAgB,CAACtC,GAAG,CAAC,AAAC;QAC3C,MAAM,EAAEuC,IAAI,CAAA,EAAEC,OAAO,CAAA,EAAEtC,OAAO,CAAA,EAAE,GAAG,MAAM,IAAI,CAACuC,yBAAyB,CAACzE,OAAO,CAAC,AAAC;QACjF,KAAK,MAAM,CAAC0E,UAAU,EAAEC,WAAW,CAAC,IAAIzC,OAAO,CAAE;YAC/CwB,GAAG,CAACC,SAAS,CAACe,UAAU,EAAEC,WAAW,CAAC,CAAC;SACxC;QACDjB,GAAG,CAACE,GAAG,CAACW,IAAI,CAAC,CAAC;QAEd,gBAAgB;QAChB,IAAI,CAACK,aAAa,CAACJ,OAAO,WAAPA,OAAO,GAAI,IAAI,CAAC,CAAC;KACrC;CACF;QAjSqB3E,kBAAkB,GAAlBA,kBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/ManifestMiddleware.ts"],"sourcesContent":["import {\n ExpoConfig,\n ExpoGoConfig,\n getConfig,\n PackageJSONConfig,\n ProjectConfig,\n} from '@expo/config';\nimport { resolveEntryPoint } from '@expo/config/paths';\nimport findWorkspaceRoot from 'find-yarn-workspace-root';\nimport path from 'path';\nimport { resolve } from 'url';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport {\n shouldEnableAsyncImports,\n createBundleUrlPath,\n getBaseUrlFromExpoConfig,\n getAsyncRoutesFromExpoConfig,\n createBundleUrlPathFromExpoConfig,\n} from './metroOptions';\nimport { resolveGoogleServicesFile, resolveManifestAssets } from './resolveAssets';\nimport { parsePlatformHeader, RuntimePlatform } from './resolvePlatform';\nimport { ServerHeaders, ServerNext, ServerRequest, ServerResponse } from './server.types';\nimport { isEnableHermesManaged } from '../../../export/exportHermes';\nimport * as Log from '../../../log';\nimport { env } from '../../../utils/env';\nimport { CommandError } from '../../../utils/errors';\nimport { stripExtension } from '../../../utils/url';\nimport * as ProjectDevices from '../../project/devices';\nimport { UrlCreator } from '../UrlCreator';\nimport { getRouterDirectoryModuleIdWithManifest } from '../metro/router';\nimport { getPlatformBundlers, PlatformBundlers } from '../platformBundlers';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../webTemplate';\n\nconst debug = require('debug')('expo:start:server:middleware:manifest') as typeof console.log;\n\n/** Wraps `findWorkspaceRoot` and guards against having an empty `package.json` file in an upper directory. */\nexport function getWorkspaceRoot(projectRoot: string): string | null {\n try {\n return findWorkspaceRoot(projectRoot);\n } catch (error: any) {\n if (error.message.includes('Unexpected end of JSON input')) {\n return null;\n }\n throw error;\n }\n}\n\nconst supportedPlatforms = ['ios', 'android', 'web', 'none'];\n\nexport function getEntryWithServerRoot(\n projectRoot: string,\n props: { platform: string; pkg?: PackageJSONConfig }\n) {\n if (!supportedPlatforms.includes(props.platform)) {\n throw new CommandError(\n `Failed to resolve the project's entry file: The platform \"${props.platform}\" is not supported.`\n );\n }\n return path.relative(getMetroServerRoot(projectRoot), resolveEntryPoint(projectRoot, props));\n}\n\nexport function getMetroServerRoot(projectRoot: string) {\n if (env.EXPO_USE_METRO_WORKSPACE_ROOT) {\n return getWorkspaceRoot(projectRoot) ?? projectRoot;\n }\n\n return projectRoot;\n}\n\n/** Get the main entry module ID (file) relative to the project root. */\nexport function resolveMainModuleName(\n projectRoot: string,\n props: { platform: string; pkg?: PackageJSONConfig }\n): string {\n const entryPoint = getEntryWithServerRoot(projectRoot, props);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${projectRoot})`);\n\n return stripExtension(entryPoint, 'js');\n}\n\n/** Info about the computer hosting the dev server. */\nexport interface HostInfo {\n host: string;\n server: 'expo';\n serverVersion: string;\n serverDriver: string | null;\n serverOS: NodeJS.Platform;\n serverOSVersion: string;\n}\n\n/** Parsed values from the supported request headers. */\nexport interface ManifestRequestInfo {\n /** Platform to serve. */\n platform: RuntimePlatform;\n /** Requested host name. */\n hostname?: string | null;\n /** The protocol used to request the manifest */\n protocol?: 'http' | 'https';\n}\n\n/** Project related info. */\nexport type ResponseProjectSettings = {\n expoGoConfig: ExpoGoConfig;\n hostUri: string;\n bundleUrl: string;\n exp: ExpoConfig;\n};\n\nexport const DEVELOPER_TOOL = 'expo-cli';\n\nexport type ManifestMiddlewareOptions = {\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n constructUrl: UrlCreator['constructUrl'];\n isNativeWebpack?: boolean;\n privateKeyPath?: string;\n};\n\n/** Base middleware creator for serving the Expo manifest (like the index.html but for native runtimes). */\nexport abstract class ManifestMiddleware<\n TManifestRequestInfo extends ManifestRequestInfo,\n> extends ExpoMiddleware {\n private initialProjectConfig: ProjectConfig;\n private platformBundlers: PlatformBundlers;\n\n constructor(\n protected projectRoot: string,\n protected options: ManifestMiddlewareOptions\n ) {\n super(\n projectRoot,\n /**\n * Only support `/`, `/manifest`, `/index.exp` for the manifest middleware.\n */\n ['/', '/manifest', '/index.exp']\n );\n this.initialProjectConfig = getConfig(projectRoot);\n this.platformBundlers = getPlatformBundlers(projectRoot, this.initialProjectConfig.exp);\n }\n\n /** Exposed for testing. */\n public async _resolveProjectSettingsAsync({\n platform,\n hostname,\n protocol,\n }: Pick<\n TManifestRequestInfo,\n 'hostname' | 'platform' | 'protocol'\n >): Promise<ResponseProjectSettings> {\n // Read the config\n const projectConfig = getConfig(this.projectRoot);\n\n // Read from headers\n const mainModuleName = this.resolveMainModuleName({\n pkg: projectConfig.pkg,\n platform,\n });\n\n const isHermesEnabled = isEnableHermesManaged(projectConfig.exp, platform);\n\n // Create the manifest and set fields within it\n const expoGoConfig = this.getExpoGoConfig({\n mainModuleName,\n hostname,\n });\n\n const hostUri = this.options.constructUrl({ scheme: '', hostname });\n\n const bundleUrl = this._getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n engine: isHermesEnabled ? 'hermes' : undefined,\n baseUrl: getBaseUrlFromExpoConfig(projectConfig.exp),\n asyncRoutes: getAsyncRoutesFromExpoConfig(\n projectConfig.exp,\n this.options.mode ?? 'development',\n platform\n ),\n routerRoot: getRouterDirectoryModuleIdWithManifest(this.projectRoot, projectConfig.exp),\n protocol,\n });\n\n // Resolve all assets and set them on the manifest as URLs\n await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);\n\n return {\n expoGoConfig,\n hostUri,\n bundleUrl,\n exp: projectConfig.exp,\n };\n }\n\n /** Get the main entry module ID (file) relative to the project root. */\n private resolveMainModuleName(props: { pkg: PackageJSONConfig; platform: string }): string {\n let entryPoint = getEntryWithServerRoot(this.projectRoot, props);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${this.projectRoot})`);\n\n // NOTE(Bacon): Webpack is currently hardcoded to index.bundle on native\n // in the future (TODO) we should move this logic into a Webpack plugin and use\n // a generated file name like we do on web.\n // const server = getDefaultDevServer();\n // // TODO: Move this into BundlerDevServer and read this info from self.\n // const isNativeWebpack = server instanceof WebpackBundlerDevServer && server.isTargetingNative();\n if (this.options.isNativeWebpack) {\n entryPoint = 'index.js';\n }\n\n return stripExtension(entryPoint, 'js');\n }\n\n /** Parse request headers into options. */\n public abstract getParsedHeaders(req: ServerRequest): TManifestRequestInfo;\n\n /** Store device IDs that were sent in the request headers. */\n private async saveDevicesAsync(req: ServerRequest) {\n const deviceIds = req.headers?.['expo-dev-client-id'];\n if (deviceIds) {\n await ProjectDevices.saveDevicesAsync(this.projectRoot, deviceIds).catch((e) =>\n Log.exception(e)\n );\n }\n }\n\n /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */\n public _getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n engine,\n baseUrl,\n isExporting,\n asyncRoutes,\n routerRoot,\n protocol,\n }: {\n platform: string;\n hostname?: string | null;\n mainModuleName: string;\n engine?: 'hermes';\n baseUrl?: string;\n asyncRoutes: boolean;\n isExporting?: boolean;\n routerRoot: string;\n protocol?: 'http' | 'https';\n }): string {\n const path = createBundleUrlPath({\n mode: this.options.mode ?? 'development',\n minify: this.options.minify,\n platform,\n mainModuleName,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n engine,\n baseUrl,\n isExporting: !!isExporting,\n asyncRoutes,\n routerRoot,\n });\n\n return (\n this.options.constructUrl({\n scheme: protocol ?? 'http',\n // hostType: this.options.location.hostType,\n hostname,\n }) + path\n );\n }\n\n /** Log telemetry. */\n protected abstract trackManifest(version?: string): void;\n\n /** Get the manifest response to return to the runtime. This file contains info regarding where the assets can be loaded from. Exposed for testing. */\n public abstract _getManifestResponseAsync(options: TManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }>;\n\n private getExpoGoConfig({\n mainModuleName,\n hostname,\n }: {\n mainModuleName: string;\n hostname?: string | null;\n }): ExpoGoConfig {\n return {\n // localhost:8081\n debuggerHost: this.options.constructUrl({ scheme: '', hostname }),\n // Required for Expo Go to function.\n developer: {\n tool: DEVELOPER_TOOL,\n projectRoot: this.projectRoot,\n },\n packagerOpts: {\n // Required for dev client.\n dev: this.options.mode !== 'production',\n },\n // Indicates the name of the main bundle.\n mainModuleName,\n // Add this string to make Flipper register React Native / Metro as \"running\".\n // Can be tested by running:\n // `METRO_SERVER_PORT=8081 open -a flipper.app`\n // Where 8081 is the port where the Expo project is being hosted.\n __flipperHack: 'React Native packager is running',\n };\n }\n\n /** Resolve all assets and set them on the manifest as URLs */\n private async mutateManifestWithAssetsAsync(manifest: ExpoConfig, bundleUrl: string) {\n await resolveManifestAssets(this.projectRoot, {\n manifest,\n resolver: async (path) => {\n if (this.options.isNativeWebpack) {\n // When using our custom dev server, just do assets normally\n // without the `assets/` subpath redirect.\n return resolve(bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0], path);\n }\n return bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0] + 'assets/' + path;\n },\n });\n // The server normally inserts this but if we're offline we'll do it here\n await resolveGoogleServicesFile(this.projectRoot, manifest);\n }\n\n public getWebBundleUrl() {\n const platform = 'web';\n // Read from headers\n const mainModuleName = this.resolveMainModuleName({\n pkg: this.initialProjectConfig.pkg,\n platform,\n });\n\n return createBundleUrlPathFromExpoConfig(this.projectRoot, this.initialProjectConfig.exp, {\n platform,\n mainModuleName,\n minify: this.options.minify,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n mode: this.options.mode ?? 'development',\n // Hermes doesn't support more modern JS features than most, if not all, modern browser.\n engine: 'hermes',\n isExporting: false,\n });\n }\n\n /**\n * Web platforms should create an index.html response using the same script resolution as native.\n *\n * Instead of adding a `bundleUrl` to a `manifest.json` (native) we'll add a `<script src=\"\">`\n * to an `index.html`, this enables the web platform to load JavaScript from the server.\n */\n private async handleWebRequestAsync(req: ServerRequest, res: ServerResponse) {\n // Read from headers\n const bundleUrl = this.getWebBundleUrl();\n\n res.setHeader('Content-Type', 'text/html');\n\n res.end(\n await createTemplateHtmlFromExpoConfigAsync(this.projectRoot, {\n exp: this.initialProjectConfig.exp,\n scripts: [bundleUrl],\n })\n );\n }\n\n /** Exposed for testing. */\n async checkBrowserRequestAsync(req: ServerRequest, res: ServerResponse, next: ServerNext) {\n if (\n this.platformBundlers.web === 'metro' &&\n this.initialProjectConfig.exp.platforms?.includes('web')\n ) {\n // NOTE(EvanBacon): This effectively disables the safety check we do on custom runtimes to ensure\n // the `expo-platform` header is included. When `web.bundler=web`, if the user has non-standard Expo\n // code loading then they'll get a web bundle without a clear assertion of platform support.\n const platform = parsePlatformHeader(req);\n // On web, serve the public folder\n if (!platform || platform === 'web') {\n if (['static', 'server'].includes(this.initialProjectConfig.exp.web?.output ?? '')) {\n // Skip the spa-styled index.html when static generation is enabled.\n next();\n return true;\n } else {\n await this.handleWebRequestAsync(req, res);\n return true;\n }\n }\n }\n return false;\n }\n\n async handleRequestAsync(\n req: ServerRequest,\n res: ServerResponse,\n next: ServerNext\n ): Promise<void> {\n // First check for standard JavaScript runtimes (aka legacy browsers like Chrome).\n if (await this.checkBrowserRequestAsync(req, res, next)) {\n return;\n }\n\n // Save device IDs for dev client.\n await this.saveDevicesAsync(req);\n\n // Read from headers\n const options = this.getParsedHeaders(req);\n const { body, version, headers } = await this._getManifestResponseAsync(options);\n for (const [headerName, headerValue] of headers) {\n res.setHeader(headerName, headerValue);\n }\n res.end(body);\n\n // Log analytics\n this.trackManifest(version ?? null);\n }\n}\n"],"names":["getWorkspaceRoot","getEntryWithServerRoot","getMetroServerRoot","resolveMainModuleName","Log","ProjectDevices","debug","require","projectRoot","findWorkspaceRoot","error","message","includes","supportedPlatforms","props","platform","CommandError","path","relative","resolveEntryPoint","env","EXPO_USE_METRO_WORKSPACE_ROOT","entryPoint","stripExtension","DEVELOPER_TOOL","ManifestMiddleware","ExpoMiddleware","constructor","options","initialProjectConfig","getConfig","platformBundlers","getPlatformBundlers","exp","_resolveProjectSettingsAsync","hostname","protocol","projectConfig","mainModuleName","pkg","isHermesEnabled","isEnableHermesManaged","expoGoConfig","getExpoGoConfig","hostUri","constructUrl","scheme","bundleUrl","_getBundleUrl","engine","undefined","baseUrl","getBaseUrlFromExpoConfig","asyncRoutes","getAsyncRoutesFromExpoConfig","mode","routerRoot","getRouterDirectoryModuleIdWithManifest","mutateManifestWithAssetsAsync","isNativeWebpack","saveDevicesAsync","req","deviceIds","headers","catch","e","exception","isExporting","createBundleUrlPath","minify","lazy","shouldEnableAsyncImports","debuggerHost","developer","tool","packagerOpts","dev","__flipperHack","manifest","resolveManifestAssets","resolver","resolve","match","resolveGoogleServicesFile","getWebBundleUrl","createBundleUrlPathFromExpoConfig","handleWebRequestAsync","res","setHeader","end","createTemplateHtmlFromExpoConfigAsync","scripts","checkBrowserRequestAsync","next","web","platforms","parsePlatformHeader","output","handleRequestAsync","getParsedHea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W,kBAAkB,CACtBrC,GAAkB,EAClB0B,GAAmB,EACnBM,IAAgB,EACD;QACf,kFAAkF;QAClF,IAAI,MAAM,IAAI,CAACD,wBAAwB,CAAC/B,GAAG,EAAE0B,GAAG,EAAEM,IAAI,CAAC,EAAE;YACvD,OAAO;SACR;QAED,kCAAkC;QAClC,MAAM,IAAI,CAACjC,gBAAgB,CAACC,GAAG,CAAC,CAAC;QAEjC,oBAAoB;QACpB,MAAMjC,OAAO,GAAG,IAAI,CAACuE,gBAAgB,CAACtC,GAAG,CAAC,AAAC;QAC3C,MAAM,EAAEuC,IAAI,CAAA,EAAEC,OAAO,CAAA,EAAEtC,OAAO,CAAA,EAAE,GAAG,MAAM,IAAI,CAACuC,yBAAyB,CAAC1E,OAAO,CAAC,AAAC;QACjF,KAAK,MAAM,CAAC2E,UAAU,EAAEC,WAAW,CAAC,IAAIzC,OAAO,CAAE;YAC/CwB,GAAG,CAACC,SAAS,CAACe,UAAU,EAAEC,WAAW,CAAC,CAAC;SACxC;QACDjB,GAAG,CAACE,GAAG,CAACW,IAAI,CAAC,CAAC;QAEd,gBAAgB;QAChB,IAAI,CAACK,aAAa,CAACJ,OAAO,WAAPA,OAAO,GAAI,IAAI,CAAC,CAAC;KACrC;CACF;QAxSqB5E,kBAAkB,GAAlBA,kBAAkB"}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", {
|
|
3
|
+
value: true
|
|
4
|
+
});
|
|
5
|
+
exports.logLikeMetro = logLikeMetro;
|
|
6
|
+
exports.formatStackLikeMetro = formatStackLikeMetro;
|
|
7
|
+
exports.augmentLogs = void 0;
|
|
8
|
+
var _metroConfig = require("@expo/metro-config");
|
|
9
|
+
var _chalk = _interopRequireDefault(require("chalk"));
|
|
10
|
+
var _path = _interopRequireDefault(require("path"));
|
|
11
|
+
var stackTraceParser = _interopRequireWildcard(require("stacktrace-parser"));
|
|
12
|
+
var _env = require("../../utils/env");
|
|
13
|
+
var _fn = require("../../utils/fn");
|
|
14
|
+
function _interopRequireDefault(obj) {
|
|
15
|
+
return obj && obj.__esModule ? obj : {
|
|
16
|
+
default: obj
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function _interopRequireWildcard(obj) {
|
|
20
|
+
if (obj && obj.__esModule) {
|
|
21
|
+
return obj;
|
|
22
|
+
} else {
|
|
23
|
+
var newObj = {};
|
|
24
|
+
if (obj != null) {
|
|
25
|
+
for(var key in obj){
|
|
26
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
27
|
+
var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
|
|
28
|
+
if (desc.get || desc.set) {
|
|
29
|
+
Object.defineProperty(newObj, key, desc);
|
|
30
|
+
} else {
|
|
31
|
+
newObj[key] = obj[key];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
newObj.default = obj;
|
|
37
|
+
return newObj;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const groupStack = [];
|
|
41
|
+
let collapsedGuardTimer;
|
|
42
|
+
function logLikeMetro(originalLogFunction, level, platform, ...data) {
|
|
43
|
+
// @ts-expect-error
|
|
44
|
+
const logFunction = console[level] && level !== "trace" ? level : "log";
|
|
45
|
+
const color = level === "error" ? _chalk.default.inverse.red : level === "warn" ? _chalk.default.inverse.yellow : _chalk.default.inverse.white;
|
|
46
|
+
if (level === "group") {
|
|
47
|
+
groupStack.push(level);
|
|
48
|
+
} else if (level === "groupCollapsed") {
|
|
49
|
+
groupStack.push(level);
|
|
50
|
+
clearTimeout(collapsedGuardTimer);
|
|
51
|
+
// Inform users that logs get swallowed if they forget to call `groupEnd`.
|
|
52
|
+
collapsedGuardTimer = setTimeout(()=>{
|
|
53
|
+
if (groupStack.includes("groupCollapsed")) {
|
|
54
|
+
originalLogFunction(_chalk.default.inverse.yellow.bold(" WARN "), "Expected `console.groupEnd` to be called after `console.groupCollapsed`.");
|
|
55
|
+
groupStack.length = 0;
|
|
56
|
+
}
|
|
57
|
+
}, 3000);
|
|
58
|
+
return;
|
|
59
|
+
} else if (level === "groupEnd") {
|
|
60
|
+
groupStack.pop();
|
|
61
|
+
if (!groupStack.length) {
|
|
62
|
+
clearTimeout(collapsedGuardTimer);
|
|
63
|
+
}
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (!groupStack.includes("groupCollapsed")) {
|
|
67
|
+
// Remove excess whitespace at the end of a log message, if possible.
|
|
68
|
+
const lastItem = data[data.length - 1];
|
|
69
|
+
if (typeof lastItem === "string") {
|
|
70
|
+
data[data.length - 1] = lastItem.trimEnd();
|
|
71
|
+
}
|
|
72
|
+
const modePrefix = _chalk.default.bold`${platform}`;
|
|
73
|
+
originalLogFunction(modePrefix + " " + color.bold(` ${logFunction.toUpperCase()} `) + "".padEnd(groupStack.length * 2, " "), ...data);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const escapedPathSep = _path.default.sep === "\\" ? "\\\\" : _path.default.sep;
|
|
77
|
+
const SERVER_STACK_MATCHER = new RegExp(`${escapedPathSep}(react-dom|metro-runtime|expo-router)${escapedPathSep}`);
|
|
78
|
+
function augmentLogsInternal(projectRoot) {
|
|
79
|
+
const augmentLog = (name, fn)=>{
|
|
80
|
+
// @ts-expect-error: TypeScript doesn't know about polyfilled functions.
|
|
81
|
+
if (fn.__polyfilled) {
|
|
82
|
+
return fn;
|
|
83
|
+
}
|
|
84
|
+
const originalFn = fn.bind(console);
|
|
85
|
+
function logWithStack(...args) {
|
|
86
|
+
const stack = new Error().stack;
|
|
87
|
+
// Check if the log originates from the server.
|
|
88
|
+
const isServerLog = !!(stack == null ? void 0 : stack.match(SERVER_STACK_MATCHER));
|
|
89
|
+
if (isServerLog) {
|
|
90
|
+
if (name === "error" || name === "warn") {
|
|
91
|
+
args.push("\n" + formatStackLikeMetro(projectRoot, stack));
|
|
92
|
+
}
|
|
93
|
+
logLikeMetro(originalFn, name, "\u03BB", ...args);
|
|
94
|
+
} else {
|
|
95
|
+
originalFn(...args);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
logWithStack.__polyfilled = true;
|
|
99
|
+
return logWithStack;
|
|
100
|
+
};
|
|
101
|
+
[
|
|
102
|
+
"trace",
|
|
103
|
+
"info",
|
|
104
|
+
"error",
|
|
105
|
+
"warn",
|
|
106
|
+
"log",
|
|
107
|
+
"group",
|
|
108
|
+
"groupCollapsed",
|
|
109
|
+
"groupEnd",
|
|
110
|
+
"debug"
|
|
111
|
+
].forEach((name)=>{
|
|
112
|
+
// @ts-expect-error
|
|
113
|
+
console[name] = augmentLog(name, console[name]);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
function formatStackLikeMetro(projectRoot, stack) {
|
|
117
|
+
// Remove `Error: ` from the beginning of the stack trace.
|
|
118
|
+
// Dim traces that match `INTERNAL_CALLSITES_REGEX`
|
|
119
|
+
const stackTrace = stackTraceParser.parse(stack);
|
|
120
|
+
return stackTrace.filter((line)=>line.file && line.file !== "<anonymous>" && // Ignore unsymbolicated stack frames. It's not clear how this is possible but it sometimes happens when the graph changes.
|
|
121
|
+
!/^https?:\/\//.test(line.file)
|
|
122
|
+
).map((line)=>{
|
|
123
|
+
// Use the same regex we use in Metro config to filter out traces:
|
|
124
|
+
const isCollapsed = _metroConfig.INTERNAL_CALLSITES_REGEX.test(line.file);
|
|
125
|
+
if (isCollapsed && !_env.env.EXPO_DEBUG) {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
// If a file is collapsed, print it with dim styling.
|
|
129
|
+
const style = isCollapsed ? _chalk.default.dim : _chalk.default.gray;
|
|
130
|
+
// Use the `at` prefix to match Node.js
|
|
131
|
+
let fileName = line.file;
|
|
132
|
+
if (fileName.startsWith(_path.default.sep)) {
|
|
133
|
+
fileName = _path.default.relative(projectRoot, fileName);
|
|
134
|
+
}
|
|
135
|
+
if (line.lineNumber != null) {
|
|
136
|
+
fileName += `:${line.lineNumber}`;
|
|
137
|
+
if (line.column != null) {
|
|
138
|
+
fileName += `:${line.column}`;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return style(` ${line.methodName} (${fileName})`);
|
|
142
|
+
}).filter(Boolean).join("\n");
|
|
143
|
+
}
|
|
144
|
+
const augmentLogs = (0, _fn).memoize(augmentLogsInternal);
|
|
145
|
+
exports.augmentLogs = augmentLogs;
|
|
146
|
+
|
|
147
|
+
//# sourceMappingURL=serverLogLikeMetro.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../src/start/server/serverLogLikeMetro.ts"],"sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\nimport { INTERNAL_CALLSITES_REGEX } from '@expo/metro-config';\nimport chalk from 'chalk';\nimport path from 'path';\nimport * as stackTraceParser from 'stacktrace-parser';\n\nimport { env } from '../../utils/env';\nimport { memoize } from '../../utils/fn';\n\nconst groupStack: any = [];\nlet collapsedGuardTimer: ReturnType<typeof setTimeout> | undefined;\n\nexport function logLikeMetro(\n originalLogFunction: (...args: any[]) => void,\n level: string,\n platform: string,\n ...data: any[]\n) {\n // @ts-expect-error\n const logFunction = console[level] && level !== 'trace' ? level : 'log';\n const color =\n level === 'error'\n ? chalk.inverse.red\n : level === 'warn'\n ? chalk.inverse.yellow\n : chalk.inverse.white;\n\n if (level === 'group') {\n groupStack.push(level);\n } else if (level === 'groupCollapsed') {\n groupStack.push(level);\n clearTimeout(collapsedGuardTimer);\n // Inform users that logs get swallowed if they forget to call `groupEnd`.\n collapsedGuardTimer = setTimeout(() => {\n if (groupStack.includes('groupCollapsed')) {\n originalLogFunction(\n chalk.inverse.yellow.bold(' WARN '),\n 'Expected `console.groupEnd` to be called after `console.groupCollapsed`.'\n );\n groupStack.length = 0;\n }\n }, 3000);\n return;\n } else if (level === 'groupEnd') {\n groupStack.pop();\n if (!groupStack.length) {\n clearTimeout(collapsedGuardTimer);\n }\n return;\n }\n\n if (!groupStack.includes('groupCollapsed')) {\n // Remove excess whitespace at the end of a log message, if possible.\n const lastItem = data[data.length - 1];\n if (typeof lastItem === 'string') {\n data[data.length - 1] = lastItem.trimEnd();\n }\n\n const modePrefix = chalk.bold`${platform}`;\n originalLogFunction(\n modePrefix +\n ' ' +\n color.bold(` ${logFunction.toUpperCase()} `) +\n ''.padEnd(groupStack.length * 2, ' '),\n ...data\n );\n }\n}\n\nconst escapedPathSep = path.sep === '\\\\' ? '\\\\\\\\' : path.sep;\nconst SERVER_STACK_MATCHER = new RegExp(\n `${escapedPathSep}(react-dom|metro-runtime|expo-router)${escapedPathSep}`\n);\n\nfunction augmentLogsInternal(projectRoot: string) {\n const augmentLog = (name: string, fn: typeof console.log) => {\n // @ts-expect-error: TypeScript doesn't know about polyfilled functions.\n if (fn.__polyfilled) {\n return fn;\n }\n const originalFn = fn.bind(console);\n function logWithStack(...args: any[]) {\n const stack = new Error().stack;\n // Check if the log originates from the server.\n const isServerLog = !!stack?.match(SERVER_STACK_MATCHER);\n if (isServerLog) {\n if (name === 'error' || name === 'warn') {\n args.push('\\n' + formatStackLikeMetro(projectRoot, stack!));\n }\n logLikeMetro(originalFn, name, 'λ', ...args);\n } else {\n originalFn(...args);\n }\n }\n logWithStack.__polyfilled = true;\n return logWithStack;\n };\n\n ['trace', 'info', 'error', 'warn', 'log', 'group', 'groupCollapsed', 'groupEnd', 'debug'].forEach(\n (name) => {\n // @ts-expect-error\n console[name] = augmentLog(name, console[name]);\n }\n );\n}\n\nexport function formatStackLikeMetro(projectRoot: string, stack: string) {\n // Remove `Error: ` from the beginning of the stack trace.\n // Dim traces that match `INTERNAL_CALLSITES_REGEX`\n\n const stackTrace = stackTraceParser.parse(stack);\n return stackTrace\n .filter(\n (line) =>\n line.file &&\n line.file !== '<anonymous>' &&\n // Ignore unsymbolicated stack frames. It's not clear how this is possible but it sometimes happens when the graph changes.\n !/^https?:\\/\\//.test(line.file)\n )\n .map((line) => {\n // Use the same regex we use in Metro config to filter out traces:\n const isCollapsed = INTERNAL_CALLSITES_REGEX.test(line.file!);\n if (isCollapsed && !env.EXPO_DEBUG) {\n return null;\n }\n // If a file is collapsed, print it with dim styling.\n const style = isCollapsed ? chalk.dim : chalk.gray;\n // Use the `at` prefix to match Node.js\n let fileName = line.file!;\n if (fileName.startsWith(path.sep)) {\n fileName = path.relative(projectRoot, fileName);\n }\n if (line.lineNumber != null) {\n fileName += `:${line.lineNumber}`;\n if (line.column != null) {\n fileName += `:${line.column}`;\n }\n }\n\n return style(` ${line.methodName} (${fileName})`);\n })\n .filter(Boolean)\n .join('\\n');\n}\n\n/** Augment console logs to check the stack trace and format like Metro logs if we think the log came from the SSR renderer or an API route. */\nexport const augmentLogs = memoize(augmentLogsInternal);\n"],"names":["logLikeMetro","formatStackLikeMetro","stackTraceParser","groupStack","collapsedGuardTimer","originalLogFunction","level","platform","data","logFunction","console","color","chalk","inverse","red","yellow","white","push","clearTimeout","setTimeout","includes","bold","length","pop","lastItem","trimEnd","modePrefix","toUpperCase","padEnd","escapedPathSep","path","sep","SERVER_STACK_MATCHER","RegExp","augmentLogsInternal","projectRoot","augmentLog","name","fn","__polyfilled","originalFn","bind","logWithStack","args","stack","Error","isServerLog","match","forEach","stackTrace","parse","filter","line","file","test","map","isCollapsed","INTERNAL_CALLSITES_REGEX","env","EXPO_DEBUG","style","dim","gray","fileName","startsWith","relative","lineNumber","column","methodName","Boolean","join","augmentLogs","memoize"],"mappings":"AAMA;;;;QAWgBA,YAAY,GAAZA,YAAY;QA8FZC,oBAAoB,GAApBA,oBAAoB;;AAzGK,IAAA,YAAoB,WAApB,oBAAoB,CAAA;AAC3C,IAAA,MAAO,kCAAP,OAAO,EAAA;AACR,IAAA,KAAM,kCAAN,MAAM,EAAA;AACXC,IAAAA,gBAAgB,mCAAM,mBAAmB,EAAzB;AAER,IAAA,IAAiB,WAAjB,iBAA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AC,AAAC;QAA3CqC,WAAW,GAAXA,WAAW"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../src/start/server/type-generation/__typetests__/fixtures/basic.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/ban-types */\n\nimport type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link';\nimport type { Router as OriginalRouter } from 'expo-router/build/types';\nexport * from 'expo-router/build';\n\n// prettier-ignore\ntype StaticRoutes = `/apple` | `/banana`;\n// prettier-ignore\ntype DynamicRoutes<T extends string> = `/colors/${SingleRoutePart<T>}` | `/animals/${CatchAllRoutePart<T>}` | `/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}`;\n// prettier-ignore\ntype DynamicRouteTemplate = `/colors/[color]` | `/animals/[...animal]` | `/mix/[fruit]/[color]/[...animals]`;\n\ntype RelativePathString = `./${string}` | `../${string}` | '..';\ntype AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;\ntype ExternalPathString = `${string}:${string}`;\n\ntype ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;\nexport type AllRoutes = ExpoRouterRoutes | ExternalPathString;\n\n/****************\n * Route Utils *\n ****************/\n\ntype SearchOrHash = `?${string}` | `#${string}`;\ntype UnknownInputParams = Record<string, string | number | (string | number)[]>;\ntype UnknownOutputParams = Record<string, string | string[]>;\n\n/**\n * Return only the RoutePart of a string. If the string has multiple parts return never\n *\n * string | type\n * ---------|------\n * 123 | 123\n * /123/abc | never\n * 123?abc | never\n * ./123 | never\n * /123 | never\n * 123/../ | never\n */\ntype SingleRoutePart<S extends string> = S extends `${string}/${string}`\n ? never\n : S extends `${string}${SearchOrHash}`\n
|
|
1
|
+
{"version":3,"sources":["../../../../../../../src/start/server/type-generation/__typetests__/fixtures/basic.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/ban-types */\n\nimport type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link';\nimport type { Router as OriginalRouter } from 'expo-router/build/types';\nexport * from 'expo-router/build';\n\n// prettier-ignore\ntype StaticRoutes = `/apple` | `/banana`;\n// prettier-ignore\ntype DynamicRoutes<T extends string> = `/colors/${SingleRoutePart<T>}` | `/animals/${CatchAllRoutePart<T>}` | `/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}`;\n// prettier-ignore\ntype DynamicRouteTemplate = `/colors/[color]` | `/animals/[...animal]` | `/mix/[fruit]/[color]/[...animals]`;\n\ntype RelativePathString = `./${string}` | `../${string}` | '..';\ntype AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;\ntype ExternalPathString = `${string}:${string}`;\n\ntype ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;\nexport type AllRoutes = ExpoRouterRoutes | ExternalPathString;\n\n/****************\n * Route Utils *\n ****************/\n\ntype SearchOrHash = `?${string}` | `#${string}`;\ntype UnknownInputParams = Record<string, string | number | (string | number)[]>;\ntype UnknownOutputParams = Record<string, string | string[]>;\n\n/**\n * Return only the RoutePart of a string. If the string has multiple parts return never\n *\n * string | type\n * ---------|------\n * 123 | 123\n * /123/abc | never\n * 123?abc | never\n * ./123 | never\n * /123 | never\n * 123/../ | never\n */\ntype SingleRoutePart<S extends string> = S extends `${string}/${string}`\n ? never\n : S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S extends `(${string})`\n ? never\n : S extends `[${string}]`\n ? never\n : S;\n\n/**\n * Return only the CatchAll router part. If the string has search parameters or a hash return never\n */\ntype CatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S extends `${string}(${string})${string}`\n ? never\n : S extends `${string}[${string}]${string}`\n ? never\n : S;\n\n// type OptionalCatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}` ? never : S\n\n/**\n * Return the name of a route parameter\n * '[test]' -> 'test'\n * 'test' -> never\n * '[...test]' -> '...test'\n */\ntype IsParameter<Part> = Part extends `[${infer ParamName}]` ? ParamName : never;\n\n/**\n * Return a union of all parameter names. If there are no names return never\n *\n * /[test] -> 'test'\n * /[abc]/[...def] -> 'abc'|'...def'\n */\ntype ParameterNames<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? IsParameter<PartA> | ParameterNames<PartB>\n : IsParameter<Path>;\n\n/**\n * Returns all segements of a route.\n *\n * /(group)/123/abc/[id]/[...rest] -> ['(group)', '123', 'abc', '[id]', '[...rest]'\n */\ntype RouteSegments<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? PartA extends '' | '.'\n ? [...RouteSegments<PartB>]\n : [PartA, ...RouteSegments<PartB>]\n : Path extends ''\n ? []\n : [Path];\n\n/**\n * Returns a Record of the routes parameters as strings and CatchAll parameters\n *\n * There are two versions, input and output, as you can input 'string | number' but\n * the output will always be 'string'\n *\n * /[id]/[...rest] -> { id: string, rest: string[] }\n * /no-params -> {}\n */\ntype InputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends `...${infer Name}`\n ? Name\n : Key]: Key extends `...${string}` ? (string | number)[] : string | number;\n} & UnknownInputParams;\n\ntype OutputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends `...${infer Name}`\n ? Name\n : Key]: Key extends `...${string}` ? string[] : string;\n} & UnknownOutputParams;\n\n/**\n * Returns the search parameters for a route.\n */\nexport type SearchParams<T extends AllRoutes> = T extends DynamicRouteTemplate\n ? OutputRouteParams<T>\n : T extends StaticRoutes\n ? never\n : UnknownOutputParams;\n\n/**\n * Route is mostly used as part of Href to ensure that a valid route is provided\n *\n * Given a dynamic route, this will return never. This is helpful for conditional logic\n *\n * /test -> /test, /test2, etc\n * /test/[abc] -> never\n * /test/resolve -> /test, /test2, etc\n *\n * Note that if we provide a value for [abc] then the route is allowed\n *\n * This is named Route to prevent confusion, as users they will often see it in tooltips\n */\nexport type Route<T> = T extends string\n ? T extends DynamicRouteTemplate\n ? never\n :\n | StaticRoutes\n | RelativePathString\n | ExternalPathString\n | (T extends `${infer P}${SearchOrHash}`\n ? P extends DynamicRoutes<infer _>\n ? T\n : never\n : T extends DynamicRoutes<infer _>\n ? T\n : never)\n : never;\n\n/*********\n * Href *\n *********/\n\nexport type Href<T> = T extends Record<'pathname', string> ? HrefObject<T> : Route<T>;\n\nexport type HrefObject<\n R extends Record<'pathname', string>,\n P = R['pathname'],\n> = P extends DynamicRouteTemplate\n ? { pathname: P; params: InputRouteParams<P> }\n : P extends Route<P>\n ? { pathname: Route<P> | DynamicRouteTemplate; params?: never | InputRouteParams<never> }\n : never;\n\n/***********************\n * Expo Router Exports *\n ***********************/\n\nexport type Router = Omit<OriginalRouter, 'push' | 'replace' | 'setParams'> & {\n /** Navigate to the provided href. */\n push: <T>(href: Href<T>) => void;\n /** Navigate to route without appending to the history. */\n replace: <T>(href: Href<T>) => void;\n /** Update the current route query params. */\n setParams: <T = ''>(params?: T extends '' ? Record<string, string> : InputRouteParams<T>) => void;\n};\n\n/** The imperative router. */\nexport declare const router: Router;\n\n/************\n * <Link /> *\n ************/\nexport interface LinkProps<T> extends OriginalLinkProps {\n href: Href<T>;\n}\n\nexport interface LinkComponent {\n <T>(props: React.PropsWithChildren<LinkProps<T>>): JSX.Element;\n /** Helper method to resolve an Href object into a string. */\n resolveHref: <T>(href: Href<T>) => string;\n}\n\n/**\n * Component to render link to another route using a path.\n * Uses an anchor tag on the web.\n *\n * @param props.href Absolute path to route (e.g. `/feeds/hot`).\n * @param props.replace Should replace the current route without adding to the history.\n * @param props.asChild Forward props to child component. Useful for custom buttons.\n * @param props.children Child elements to render the content.\n * @param props.className On web, this sets the HTML `class` directly. On native, this can be used with CSS interop tools like Nativewind.\n */\nexport declare const Link: LinkComponent;\n\n/** Redirects to the href as soon as the component is mounted. */\nexport declare const Redirect: <T>(\n props: React.PropsWithChildren<{ href: Href<T> }>\n) => JSX.Element;\n\n/************\n * Hooks *\n ************/\nexport declare function useRouter(): Router;\n\nexport declare function useLocalSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\n/** @deprecated renamed to `useGlobalSearchParams` */\nexport declare function useSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\nexport declare function useGlobalSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\nexport declare function useSegments<\n T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString,\n>(): T extends AbsoluteRoute ? RouteSegments<T> : T extends string ? string[] : T;\n"],"names":[],"mappings":"AAIA;;;;6CAEc,mBAAmB;AAAjC,YAAA,MAAkC;;2CAAlC,MAAkC;;;;mBAAlC,MAAkC;;;EAAA"}
|
|
@@ -94,7 +94,7 @@ async function logEventAsync(event, properties = {}) {
|
|
|
94
94
|
}
|
|
95
95
|
const { userId , deviceId } = identifyData;
|
|
96
96
|
const commonEventProperties = {
|
|
97
|
-
source_version: "0.17.
|
|
97
|
+
source_version: "0.17.5",
|
|
98
98
|
source: "expo"
|
|
99
99
|
};
|
|
100
100
|
const identity = {
|
|
@@ -135,7 +135,7 @@ function getContext() {
|
|
|
135
135
|
},
|
|
136
136
|
app: {
|
|
137
137
|
name: "expo",
|
|
138
|
-
version: "0.17.
|
|
138
|
+
version: "0.17.5"
|
|
139
139
|
},
|
|
140
140
|
ci: ciInfo.isCI ? {
|
|
141
141
|
name: ciInfo.name,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/createFileTransform.ts"],"sourcesContent":["import { IOSConfig } from '@expo/config-plugins';\nimport Minipass from 'minipass';\nimport path from 'path';\nimport picomatch from 'picomatch';\nimport { ReadEntry } from 'tar';\n\nconst debug = require('debug')('expo:file-transform') as typeof console.log;\n\nfunction escapeXMLCharacters(original: string): string {\n const noAmps = original.replace('&', '&');\n const noLt = noAmps.replace('<', '<');\n const noGt = noLt.replace('>', '>');\n const noApos = noGt.replace('\"', '\\\\\"');\n return noApos.replace(\"'\", \"\\\\'\");\n}\n\nclass Transformer extends Minipass {\n data = '';\n\n constructor(private settings: { name: string; extension: string }) {\n super();\n }\n\n write(data: string) {\n this.data += data;\n return true;\n }\n\n getNormalizedName(): string {\n if (['.xml', '.plist'].includes(this.settings.extension)) {\n return escapeXMLCharacters(this.settings.name);\n }\n return this.settings.name;\n }\n\n end() {\n const name = this.getNormalizedName();\n const replaced = this.data\n .replace(/Hello App Display Name/g, name)\n .replace(/HelloWorld/g, IOSConfig.XcodeUtils.sanitizedName(name))\n .replace(/helloworld/g, IOSConfig.XcodeUtils.sanitizedName(name.toLowerCase()));\n super.write(replaced);\n return super.end();\n }\n}\n\nexport function createEntryResolver(name: string) {\n return (entry: ReadEntry) => {\n if (name) {\n // Rewrite paths for bare workflow\n entry.path = entry.path\n .replace(\n /HelloWorld/g,\n entry.path.includes('android')\n ? IOSConfig.XcodeUtils.sanitizedName(name.toLowerCase())\n : IOSConfig.XcodeUtils.sanitizedName(name)\n )\n .replace(/helloworld/g, IOSConfig.XcodeUtils.sanitizedName(name).toLowerCase());\n }\n if (entry.type && /^file$/i.test(entry.type) && path.basename(entry.path) === 'gitignore') {\n // Rename `gitignore` because npm ignores files named `.gitignore` when publishing.\n // See: https://github.com/npm/npm/issues/1862\n entry.path = entry.path.replace(/gitignore$/, '.gitignore');\n }\n };\n}\n\nexport function createFileTransform(name: string) {\n return (entry: ReadEntry) => {\n const extension = path.extname(entry.path);\n\n // Binary files, don't process these (avoid decoding as utf8)\n if (\n ![\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.webp',\n '.psd',\n '.tiff',\n '.svg',\n '.jar',\n '.keystore',\n\n // Font files\n '.otf',\n '.ttf',\n ].includes(extension) &&\n name\n ) {\n return new Transformer({ name, extension });\n }\n return undefined;\n };\n}\n\nexport function createGlobFilter(\n globPattern: picomatch.Glob,\n options?: picomatch.PicomatchOptions\n) {\n const matcher = picomatch(globPattern, options);\n\n debug(\n 'filter: created for pattern(s) \"%s\" (%s)',\n Array.isArray(globPattern) ? globPattern.join('\", \"') : globPattern,\n options\n );\n\n return (path: string) => {\n const included = matcher(path);\n debug('filter: %s - %s', included ? 'include' : 'exclude', path);\n return included;\n };\n}\n"],"names":["createEntryResolver","createFileTransform","createGlobFilter","debug","require","escapeXMLCharacters","original","noAmps","replace","noLt","noGt","noApos","Transformer","Minipass","constructor","settings","data","write","getNormalizedName","includes","extension","name","end","replaced","IOSConfig","XcodeUtils","sanitizedName","toLowerCase","entry","path","type","test","basename","extname","undefined","globPattern","options","matcher","picomatch","Array","isArray","join","included"],"mappings":"AAAA;;;;QA8CgBA,mBAAmB,GAAnBA,mBAAmB;QAqBnBC,mBAAmB,GAAnBA,mBAAmB;
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/createFileTransform.ts"],"sourcesContent":["import { IOSConfig } from '@expo/config-plugins';\nimport Minipass from 'minipass';\nimport path from 'path';\nimport picomatch from 'picomatch';\nimport { ReadEntry } from 'tar';\n\nconst debug = require('debug')('expo:file-transform') as typeof console.log;\n\nfunction escapeXMLCharacters(original: string): string {\n const noAmps = original.replace('&', '&');\n const noLt = noAmps.replace('<', '<');\n const noGt = noLt.replace('>', '>');\n const noApos = noGt.replace('\"', '\\\\\"');\n return noApos.replace(\"'\", \"\\\\'\");\n}\n\nclass Transformer extends Minipass {\n data = '';\n\n constructor(private settings: { name: string; extension: string }) {\n super();\n }\n\n write(data: string) {\n this.data += data;\n return true;\n }\n\n getNormalizedName(): string {\n if (['.xml', '.plist'].includes(this.settings.extension)) {\n return escapeXMLCharacters(this.settings.name);\n }\n return this.settings.name;\n }\n\n end() {\n const name = this.getNormalizedName();\n const replaced = this.data\n .replace(/Hello App Display Name/g, name)\n .replace(/HelloWorld/g, IOSConfig.XcodeUtils.sanitizedName(name))\n .replace(/helloworld/g, IOSConfig.XcodeUtils.sanitizedName(name.toLowerCase()));\n super.write(replaced);\n return super.end();\n }\n}\n\nexport function createEntryResolver(name: string) {\n return (entry: ReadEntry) => {\n if (name) {\n // Rewrite paths for bare workflow\n entry.path = entry.path\n .replace(\n /HelloWorld/g,\n entry.path.includes('android')\n ? IOSConfig.XcodeUtils.sanitizedName(name.toLowerCase())\n : IOSConfig.XcodeUtils.sanitizedName(name)\n )\n .replace(/helloworld/g, IOSConfig.XcodeUtils.sanitizedName(name).toLowerCase());\n }\n if (entry.type && /^file$/i.test(entry.type) && path.basename(entry.path) === 'gitignore') {\n // Rename `gitignore` because npm ignores files named `.gitignore` when publishing.\n // See: https://github.com/npm/npm/issues/1862\n entry.path = entry.path.replace(/gitignore$/, '.gitignore');\n }\n };\n}\n\nexport function createFileTransform(name: string) {\n return (entry: ReadEntry) => {\n const extension = path.extname(entry.path);\n\n // Binary files, don't process these (avoid decoding as utf8)\n if (\n ![\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.webp',\n '.psd',\n '.tiff',\n '.svg',\n '.jar',\n '.keystore',\n '.gz',\n\n // Font files\n '.otf',\n '.ttf',\n ].includes(extension) &&\n name\n ) {\n return new Transformer({ name, extension });\n }\n return undefined;\n };\n}\n\nexport function createGlobFilter(\n globPattern: picomatch.Glob,\n options?: picomatch.PicomatchOptions\n) {\n const matcher = picomatch(globPattern, options);\n\n debug(\n 'filter: created for pattern(s) \"%s\" (%s)',\n Array.isArray(globPattern) ? globPattern.join('\", \"') : globPattern,\n options\n );\n\n return (path: string) => {\n const included = matcher(path);\n debug('filter: %s - %s', included ? 'include' : 'exclude', path);\n return included;\n };\n}\n"],"names":["createEntryResolver","createFileTransform","createGlobFilter","debug","require","escapeXMLCharacters","original","noAmps","replace","noLt","noGt","noApos","Transformer","Minipass","constructor","settings","data","write","getNormalizedName","includes","extension","name","end","replaced","IOSConfig","XcodeUtils","sanitizedName","toLowerCase","entry","path","type","test","basename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CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@expo/cli",
|
|
3
|
-
"version": "0.17.
|
|
3
|
+
"version": "0.17.5",
|
|
4
4
|
"description": "The Expo CLI",
|
|
5
5
|
"main": "build/bin/cli",
|
|
6
6
|
"bin": {
|
|
@@ -103,6 +103,7 @@
|
|
|
103
103
|
"send": "^0.18.0",
|
|
104
104
|
"slugify": "^1.3.4",
|
|
105
105
|
"source-map-support": "~0.5.21",
|
|
106
|
+
"stacktrace-parser": "^0.1.10",
|
|
106
107
|
"structured-headers": "^0.4.1",
|
|
107
108
|
"tar": "^6.0.5",
|
|
108
109
|
"temp-dir": "^2.0.0",
|
|
@@ -167,5 +168,5 @@
|
|
|
167
168
|
"tree-kill": "^1.2.2",
|
|
168
169
|
"tsd": "^0.28.1"
|
|
169
170
|
},
|
|
170
|
-
"gitHead": "
|
|
171
|
+
"gitHead": "4f3dcf3e23eae997f884117fdd34ad734efad9fd"
|
|
171
172
|
}
|