@expo/cli 0.10.9 → 0.10.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/build/bin/cli +2 -2
  2. package/build/src/export/index.js +3 -1
  3. package/build/src/export/index.js.map +1 -1
  4. package/build/src/export/resolveOptions.js +28 -29
  5. package/build/src/export/resolveOptions.js.map +1 -1
  6. package/build/src/start/server/metro/MetroBundlerDevServer.js +31 -1
  7. package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
  8. package/build/src/start/server/metro/inspector-proxy/proxy.js +12 -9
  9. package/build/src/start/server/metro/inspector-proxy/proxy.js.map +1 -1
  10. package/build/src/start/server/metro/metroWatchTypeScriptFiles.js +1 -1
  11. package/build/src/start/server/metro/metroWatchTypeScriptFiles.js.map +1 -1
  12. package/build/src/start/server/metro/withMetroResolvers.js +13 -4
  13. package/build/src/start/server/metro/withMetroResolvers.js.map +1 -1
  14. package/build/src/start/server/middleware/ClassicManifestMiddleware.js +1 -1
  15. package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js.map +1 -1
  16. package/build/src/start/server/type-generation/__typetests__/route.test.js +20 -9
  17. package/build/src/start/server/type-generation/__typetests__/route.test.js.map +1 -1
  18. package/build/src/start/server/type-generation/routes.js +118 -51
  19. package/build/src/start/server/type-generation/routes.js.map +1 -1
  20. package/build/src/utils/analytics/metroDebuggerMiddleware.js +9 -4
  21. package/build/src/utils/analytics/metroDebuggerMiddleware.js.map +1 -1
  22. package/build/src/utils/analytics/rudderstackClient.js +2 -2
  23. package/build/src/utils/port.js +2 -0
  24. package/build/src/utils/port.js.map +1 -1
  25. package/package.json +3 -3
package/build/bin/cli CHANGED
@@ -132,7 +132,7 @@ const args = (0, _arg).default({
132
132
  });
133
133
  if (args["--version"]) {
134
134
  // Version is added in the build script.
135
- console.log("0.10.9");
135
+ console.log("0.10.11");
136
136
  process.exit(0);
137
137
  }
138
138
  if (args["--non-interactive"]) {
@@ -262,7 +262,7 @@ commands[command]().then((exec)=>{
262
262
  logEventAsync("action", {
263
263
  action: `expo ${command}`,
264
264
  source: "expo/cli",
265
- source_version: "0.10.9"
265
+ source_version: "0.10.11"
266
266
  });
267
267
  });
268
268
 
@@ -43,7 +43,9 @@ const expoExport = async (argv)=>{
43
43
  "--dump-sourcemap": Boolean,
44
44
  "--max-workers": Number,
45
45
  "--output-dir": String,
46
- "--platform": String,
46
+ "--platform": [
47
+ String
48
+ ],
47
49
  "--no-minify": Boolean,
48
50
  // Hack: This is added because EAS CLI always includes the flag.
49
51
  // If supplied, we'll do nothing with the value, but at least the process won't crash.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/export/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport chalk from 'chalk';\n\nimport { Command } from '../../bin/cli';\nimport { assertArgs, getProjectRoot, printHelp } from '../utils/args';\nimport { logCmdError } from '../utils/errors';\n\nexport const expoExport: Command = async (argv) => {\n const args = assertArgs(\n {\n // Types\n '--help': Boolean,\n '--clear': Boolean,\n '--dump-assetmap': Boolean,\n '--dev': Boolean,\n '--dump-sourcemap': Boolean,\n '--max-workers': Number,\n '--output-dir': String,\n '--platform': String,\n '--no-minify': Boolean,\n\n // Hack: This is added because EAS CLI always includes the flag.\n // If supplied, we'll do nothing with the value, but at least the process won't crash.\n // Note that we also don't show this value in the `--help` prompt since we don't want people to use it.\n '--experimental-bundle': Boolean,\n\n // Aliases\n '-h': '--help',\n // '-s': '--dump-sourcemap',\n // '-d': '--dump-assetmap',\n '-c': '--clear',\n '-p': '--platform',\n // Interop with Metro docs and RedBox errors.\n '--reset-cache': '--clear',\n },\n argv\n );\n\n if (args['--help']) {\n printHelp(\n `Export the static files of the app for hosting it on a web server`,\n chalk`npx expo export {dim <dir>}`,\n [\n chalk`<dir> Directory of the Expo project. {dim Default: Current working directory}`,\n `--dev Configure static files for developing locally using a non-https server`,\n chalk`--output-dir <dir> The directory to export the static files to. {dim Default: dist}`,\n `--max-workers <number> Maximum number of tasks to allow the bundler to spawn`,\n `--dump-assetmap Dump the asset map for further processing`,\n `--dump-sourcemap Dump the source map for debugging the JS bundle`,\n chalk`-p, --platform <platform> Options: android, ios, web, all. {dim Default: all}`,\n `--no-minify Prevent minifying source`,\n `-c, --clear Clear the bundler cache`,\n `-h, --help Usage info`,\n ].join('\\n')\n );\n }\n\n const projectRoot = getProjectRoot(args);\n const { resolveOptionsAsync } = await import('./resolveOptions');\n const options = await resolveOptionsAsync(projectRoot, args).catch(logCmdError);\n\n const { exportAsync } = await import('./exportAsync');\n return exportAsync(projectRoot, options).catch(logCmdError);\n};\n"],"names":["expoExport","argv","args","assertArgs","Boolean","Number","String","printHelp","chalk","join","projectRoot","getProjectRoot","resolveOptionsAsync","options","catch","logCmdError","exportAsync"],"mappings":"AAAA;;;;;;AACkB,IAAA,MAAO,kCAAP,OAAO,EAAA;AAG6B,IAAA,KAAe,WAAf,eAAe,CAAA;AACzC,IAAA,OAAiB,WAAjB,iBAAiB,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEtC,MAAMA,UAAU,GAAY,OAAOC,IAAI,GAAK;IACjD,MAAMC,IAAI,GAAGC,CAAAA,GAAAA,KAAU,AA4BtB,CAAA,WA5BsB,CACrB;QACE,QAAQ;QACR,QAAQ,EAAEC,OAAO;QACjB,SAAS,EAAEA,OAAO;QAClB,iBAAiB,EAAEA,OAAO;QAC1B,OAAO,EAAEA,OAAO;QAChB,kBAAkB,EAAEA,OAAO;QAC3B,eAAe,EAAEC,MAAM;QACvB,cAAc,EAAEC,MAAM;QACtB,YAAY,EAAEA,MAAM;QACpB,aAAa,EAAEF,OAAO;QAEtB,gEAAgE;QAChE,sFAAsF;QACtF,uGAAuG;QACvG,uBAAuB,EAAEA,OAAO;QAEhC,UAAU;QACV,IAAI,EAAE,QAAQ;QACd,4BAA4B;QAC5B,2BAA2B;QAC3B,IAAI,EAAE,SAAS;QACf,IAAI,EAAE,YAAY;QAClB,6CAA6C;QAC7C,eAAe,EAAE,SAAS;KAC3B,EACDH,IAAI,CACL,AAAC;IAEF,IAAIC,IAAI,CAAC,QAAQ,CAAC,EAAE;QAClBK,CAAAA,GAAAA,KAAS,AAeR,CAAA,UAfQ,CACP,CAAC,iEAAiE,CAAC,EACnEC,MAAK,QAAA,CAAC,2BAA2B,CAAC,EAClC;YACEA,MAAK,QAAA,CAAC,kGAAkG,CAAC;YACzG,CAAC,iGAAiG,CAAC;YACnGA,MAAK,QAAA,CAAC,2FAA2F,CAAC;YAClG,CAAC,gFAAgF,CAAC;YAClF,CAAC,oEAAoE,CAAC;YACtE,CAAC,0EAA0E,CAAC;YAC5EA,MAAK,QAAA,CAAC,8EAA8E,CAAC;YACrF,CAAC,mDAAmD,CAAC;YACrD,CAAC,kDAAkD,CAAC;YACpD,CAAC,qCAAqC,CAAC;SACxC,CAACC,IAAI,CAAC,IAAI,CAAC,CACb,CAAC;KACH;IAED,MAAMC,WAAW,GAAGC,CAAAA,GAAAA,KAAc,AAAM,CAAA,eAAN,CAACT,IAAI,CAAC,AAAC;IACzC,MAAM,EAAEU,mBAAmB,CAAA,EAAE,GAAG,MAAM;+CAAO,kBAAkB;MAAC,AAAC;IACjE,MAAMC,OAAO,GAAG,MAAMD,mBAAmB,CAACF,WAAW,EAAER,IAAI,CAAC,CAACY,KAAK,CAACC,OAAW,YAAA,CAAC,AAAC;IAEhF,MAAM,EAAEC,WAAW,CAAA,EAAE,GAAG,MAAM;+CAAO,eAAe;MAAC,AAAC;IACtD,OAAOA,WAAW,CAACN,WAAW,EAAEG,OAAO,CAAC,CAACC,KAAK,CAACC,OAAW,YAAA,CAAC,CAAC;CAC7D,AAAC;QAxDWf,UAAU,GAAVA,UAAU"}
1
+ {"version":3,"sources":["../../../src/export/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport chalk from 'chalk';\n\nimport { Command } from '../../bin/cli';\nimport { assertArgs, getProjectRoot, printHelp } from '../utils/args';\nimport { logCmdError } from '../utils/errors';\n\nexport const expoExport: Command = async (argv) => {\n const args = assertArgs(\n {\n // Types\n '--help': Boolean,\n '--clear': Boolean,\n '--dump-assetmap': Boolean,\n '--dev': Boolean,\n '--dump-sourcemap': Boolean,\n '--max-workers': Number,\n '--output-dir': String,\n '--platform': [String],\n '--no-minify': Boolean,\n\n // Hack: This is added because EAS CLI always includes the flag.\n // If supplied, we'll do nothing with the value, but at least the process won't crash.\n // Note that we also don't show this value in the `--help` prompt since we don't want people to use it.\n '--experimental-bundle': Boolean,\n\n // Aliases\n '-h': '--help',\n // '-s': '--dump-sourcemap',\n // '-d': '--dump-assetmap',\n '-c': '--clear',\n '-p': '--platform',\n // Interop with Metro docs and RedBox errors.\n '--reset-cache': '--clear',\n },\n argv\n );\n\n if (args['--help']) {\n printHelp(\n `Export the static files of the app for hosting it on a web server`,\n chalk`npx expo export {dim <dir>}`,\n [\n chalk`<dir> Directory of the Expo project. {dim Default: Current working directory}`,\n `--dev Configure static files for developing locally using a non-https server`,\n chalk`--output-dir <dir> The directory to export the static files to. {dim Default: dist}`,\n `--max-workers <number> Maximum number of tasks to allow the bundler to spawn`,\n `--dump-assetmap Dump the asset map for further processing`,\n `--dump-sourcemap Dump the source map for debugging the JS bundle`,\n chalk`-p, --platform <platform> Options: android, ios, web, all. {dim Default: all}`,\n `--no-minify Prevent minifying source`,\n `-c, --clear Clear the bundler cache`,\n `-h, --help Usage info`,\n ].join('\\n')\n );\n }\n\n const projectRoot = getProjectRoot(args);\n const { resolveOptionsAsync } = await import('./resolveOptions');\n const options = await resolveOptionsAsync(projectRoot, args).catch(logCmdError);\n\n const { exportAsync } = await import('./exportAsync');\n return exportAsync(projectRoot, options).catch(logCmdError);\n};\n"],"names":["expoExport","argv","args","assertArgs","Boolean","Number","String","printHelp","chalk","join","projectRoot","getProjectRoot","resolveOptionsAsync","options","catch","logCmdError","exportAsync"],"mappings":"AAAA;;;;;;AACkB,IAAA,MAAO,kCAAP,OAAO,EAAA;AAG6B,IAAA,KAAe,WAAf,eAAe,CAAA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MAAMC,WAAW,GAAGC,CAAAA,GAAAA,KAAc,AAAM,CAAA,eAAN,CAACT,IAAI,CAAC,AAAC;IACzC,MAAM,EAAEU,mBAAmB,CAAA,EAAE,GAAG,MAAM;+CAAO,kBAAkB;MAAC,AAAC;IACjE,MAAMC,OAAO,GAAG,MAAMD,mBAAmB,CAACF,WAAW,EAAER,IAAI,CAAC,CAACY,KAAK,CAACC,OAAW,YAAA,CAAC,AAAC;IAEhF,MAAM,EAAEC,WAAW,CAAA,EAAE,GAAG,MAAM;+CAAO,eAAe;MAAC,AAAC;IACtD,OAAOA,WAAW,CAACN,WAAW,EAAEG,OAAO,CAAC,CAACC,KAAK,CAACC,OAAW,YAAA,CAAC,CAAC;CAC7D,AAAC;QAxDWf,UAAU,GAAVA,UAAU"}
@@ -7,38 +7,39 @@ exports.resolveOptionsAsync = resolveOptionsAsync;
7
7
  var _config = require("@expo/config");
8
8
  var _platformBundlers = require("../start/server/platformBundlers");
9
9
  var _errors = require("../utils/errors");
10
- function resolvePlatformOption(platformBundlers, platform1 = "all") {
11
- const platforms = Object.fromEntries(Object.entries(platformBundlers).filter(([, bundler])=>bundler === "metro"
10
+ function resolvePlatformOption(platformBundlers, platform1 = [
11
+ "all"
12
+ ]) {
13
+ const platformsAvailable = Object.fromEntries(Object.entries(platformBundlers).filter(([, bundler])=>bundler === "metro"
12
14
  ));
13
- if (!Object.keys(platforms).length) {
15
+ if (!Object.keys(platformsAvailable).length) {
14
16
  throw new _errors.CommandError(`No platforms are configured to use the Metro bundler in the project Expo config.`);
15
17
  }
16
18
  const assertPlatformBundler = (platform)=>{
17
- if (!platforms[platform]) {
19
+ if (!platformsAvailable[platform]) {
18
20
  throw new _errors.CommandError("BAD_ARGS", `Platform "${platform}" is not configured to use the Metro bundler in the project Expo config.`);
19
21
  }
22
+ return platform;
20
23
  };
21
- switch(platform1){
22
- case "ios":
23
- assertPlatformBundler("ios");
24
- return [
25
- "ios"
26
- ];
27
- case "web":
28
- assertPlatformBundler("web");
29
- return [
30
- "web"
31
- ];
32
- case "android":
33
- assertPlatformBundler("android");
34
- return [
35
- "android"
36
- ];
37
- case "all":
38
- return Object.keys(platforms);
39
- default:
40
- throw new _errors.CommandError(`Unsupported platform "${platform1}". Options are: ${Object.keys(platforms).join(",")}, all`);
41
- }
24
+ const knownPlatforms = [
25
+ "android",
26
+ "ios",
27
+ "web"
28
+ ];
29
+ const assertPlatformIsKnown = (platform)=>{
30
+ if (!knownPlatforms.includes(platform)) {
31
+ throw new _errors.CommandError(`Unsupported platform "${platform}". Options are: ${knownPlatforms.join(",")},all`);
32
+ }
33
+ return platform;
34
+ };
35
+ return platform1// Expand `all` to all available platforms.
36
+ .map((platform)=>platform === "all" ? Object.keys(platformsAvailable) : platform
37
+ ).flat()// Remove duplicated platforms
38
+ .filter((platform, index, list)=>list.indexOf(platform) === index
39
+ )// Assert platforms are valid
40
+ .map((platform)=>assertPlatformIsKnown(platform)
41
+ ).map((platform)=>assertPlatformBundler(platform)
42
+ );
42
43
  }
43
44
  async function resolveOptionsAsync(projectRoot, args) {
44
45
  const { exp } = (0, _config).getConfig(projectRoot, {
@@ -47,11 +48,9 @@ async function resolveOptionsAsync(projectRoot, args) {
47
48
  });
48
49
  const platformBundlers = (0, _platformBundlers).getPlatformBundlers(exp);
49
50
  var ref;
50
- const platforms = resolvePlatformOption(platformBundlers, (ref = args["--platform"]) != null ? ref : "all");
51
- var ref1;
52
51
  return {
53
- outputDir: (ref1 = args["--output-dir"]) != null ? ref1 : "dist",
54
- platforms,
52
+ platforms: resolvePlatformOption(platformBundlers, args["--platform"]),
53
+ outputDir: (ref = args["--output-dir"]) != null ? ref : "dist",
55
54
  minify: !args["--no-minify"],
56
55
  clear: !!args["--clear"],
57
56
  dev: !!args["--dev"],
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/export/resolveOptions.ts"],"sourcesContent":["import { getConfig, Platform } from '@expo/config';\n\nimport { getPlatformBundlers, PlatformBundlers } from '../start/server/platformBundlers';\nimport { CommandError } from '../utils/errors';\n\nexport type Options = {\n outputDir: string;\n platforms: Platform[];\n maxWorkers?: number;\n dev: boolean;\n clear: boolean;\n minify: boolean;\n dumpAssetmap: boolean;\n dumpSourcemap: boolean;\n};\n\n/** Returns an array of platforms based on the input platform identifier and runtime constraints. */\nexport function resolvePlatformOption(\n platformBundlers: PlatformBundlers,\n platform: string = 'all'\n): Platform[] {\n const platforms: Partial<PlatformBundlers> = Object.fromEntries(\n Object.entries(platformBundlers).filter(([, bundler]) => bundler === 'metro')\n );\n\n if (!Object.keys(platforms).length) {\n throw new CommandError(\n `No platforms are configured to use the Metro bundler in the project Expo config.`\n );\n }\n\n const assertPlatformBundler = (platform: Platform) => {\n if (!platforms[platform]) {\n throw new CommandError(\n 'BAD_ARGS',\n `Platform \"${platform}\" is not configured to use the Metro bundler in the project Expo config.`\n );\n }\n };\n\n switch (platform) {\n case 'ios':\n assertPlatformBundler('ios');\n return ['ios'];\n case 'web':\n assertPlatformBundler('web');\n return ['web'];\n case 'android':\n assertPlatformBundler('android');\n return ['android'];\n case 'all':\n return Object.keys(platforms) as Platform[];\n default:\n throw new CommandError(\n `Unsupported platform \"${platform}\". Options are: ${Object.keys(platforms).join(',')}, all`\n );\n }\n}\n\nexport async function resolveOptionsAsync(projectRoot: string, args: any): Promise<Options> {\n const { exp } = getConfig(projectRoot, { skipPlugins: true, skipSDKVersionRequirement: true });\n const platformBundlers = getPlatformBundlers(exp);\n const platforms: Platform[] = resolvePlatformOption(\n platformBundlers,\n args['--platform'] ?? 'all'\n );\n\n return {\n outputDir: args['--output-dir'] ?? 'dist',\n platforms,\n minify: !args['--no-minify'],\n clear: !!args['--clear'],\n dev: !!args['--dev'],\n maxWorkers: args['--max-workers'],\n dumpAssetmap: !!args['--dump-assetmap'],\n dumpSourcemap: !!args['--dump-sourcemap'],\n };\n}\n"],"names":["resolvePlatformOption","resolveOptionsAsync","platformBundlers","platform","platforms","Object","fromEntries","entries","filter","bundler","keys","length","CommandError","assertPlatformBundler","join","projectRoot","args","exp","getConfig","skipPlugins","skipSDKVersionRequirement","getPlatformBundlers","outputDir","minify","clear","dev","maxWorkers","dumpAssetmap","dumpSourcemap"],"mappings":"AAAA;;;;QAiBgBA,qBAAqB,GAArBA,qBAAqB;QA0CfC,mBAAmB,GAAnBA,mBAAmB;AA3DL,IAAA,OAAc,WAAd,cAAc,CAAA;AAEI,IAAA,iBAAkC,WAAlC,kCAAkC,CAAA;AAC3D,IAAA,OAAiB,WAAjB,iBAAiB,CAAA;AAcvC,SAASD,qBAAqB,CACnCE,gBAAkC,EAClCC,SAAgB,GAAG,KAAK,EACZ;IACZ,MAAMC,SAAS,GAA8BC,MAAM,CAACC,WAAW,CAC7DD,MAAM,CAACE,OAAO,CAACL,gBAAgB,CAAC,CAACM,MAAM,CAAC,CAAC,GAAGC,OAAO,CAAC,GAAKA,OAAO,KAAK,OAAO;IAAA,CAAC,CAC9E,AAAC;IAEF,IAAI,CAACJ,MAAM,CAACK,IAAI,CAACN,SAAS,CAAC,CAACO,MAAM,EAAE;QAClC,MAAM,IAAIC,OAAY,aAAA,CACpB,CAAC,gFAAgF,CAAC,CACnF,CAAC;KACH;IAED,MAAMC,qBAAqB,GAAG,CAACV,QAAkB,GAAK;QACpD,IAAI,CAACC,SAAS,CAACD,QAAQ,CAAC,EAAE;YACxB,MAAM,IAAIS,OAAY,aAAA,CACpB,UAAU,EACV,CAAC,UAAU,EAAET,QAAQ,CAAC,wEAAwE,CAAC,CAChG,CAAC;SACH;KACF,AAAC;IAEF,OAAQA,SAAQ;QACd,KAAK,KAAK;YACRU,qBAAqB,CAAC,KAAK,CAAC,CAAC;YAC7B,OAAO;gBAAC,KAAK;aAAC,CAAC;QACjB,KAAK,KAAK;YACRA,qBAAqB,CAAC,KAAK,CAAC,CAAC;YAC7B,OAAO;gBAAC,KAAK;aAAC,CAAC;QACjB,KAAK,SAAS;YACZA,qBAAqB,CAAC,SAAS,CAAC,CAAC;YACjC,OAAO;gBAAC,SAAS;aAAC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AC1C,CAAC;CACH"}
1
+ {"version":3,"sources":["../../../src/export/resolveOptions.ts"],"sourcesContent":["import { getConfig, Platform } from '@expo/config';\n\nimport { getPlatformBundlers, PlatformBundlers } from '../start/server/platformBundlers';\nimport { CommandError } from '../utils/errors';\n\nexport type Options = {\n outputDir: string;\n platforms: Platform[];\n maxWorkers?: number;\n dev: boolean;\n clear: boolean;\n minify: boolean;\n dumpAssetmap: boolean;\n dumpSourcemap: boolean;\n};\n\n/** Returns an array of platforms based on the input platform identifier and runtime constraints. */\nexport function resolvePlatformOption(\n platformBundlers: PlatformBundlers,\n platform: string[] = ['all']\n): Platform[] {\n const platformsAvailable: Partial<PlatformBundlers> = Object.fromEntries(\n Object.entries(platformBundlers).filter(([, bundler]) => bundler === 'metro')\n );\n\n if (!Object.keys(platformsAvailable).length) {\n throw new CommandError(\n `No platforms are configured to use the Metro bundler in the project Expo config.`\n );\n }\n\n const assertPlatformBundler = (platform: Platform): Platform => {\n if (!platformsAvailable[platform]) {\n throw new CommandError(\n 'BAD_ARGS',\n `Platform \"${platform}\" is not configured to use the Metro bundler in the project Expo config.`\n );\n }\n\n return platform;\n };\n\n const knownPlatforms = ['android', 'ios', 'web'] as Platform[];\n const assertPlatformIsKnown = (platform: string): Platform => {\n if (!knownPlatforms.includes(platform as Platform)) {\n throw new CommandError(\n `Unsupported platform \"${platform}\". Options are: ${knownPlatforms.join(',')},all`\n );\n }\n\n return platform as Platform;\n };\n\n return (\n platform\n // Expand `all` to all available platforms.\n .map((platform) => (platform === 'all' ? Object.keys(platformsAvailable) : platform))\n .flat()\n // Remove duplicated platforms\n .filter((platform, index, list) => list.indexOf(platform) === index)\n // Assert platforms are valid\n .map((platform) => assertPlatformIsKnown(platform))\n .map((platform) => assertPlatformBundler(platform))\n );\n}\n\nexport async function resolveOptionsAsync(projectRoot: string, args: any): Promise<Options> {\n const { exp } = getConfig(projectRoot, { skipPlugins: true, skipSDKVersionRequirement: true });\n const platformBundlers = getPlatformBundlers(exp);\n\n return {\n platforms: resolvePlatformOption(platformBundlers, args['--platform']),\n outputDir: args['--output-dir'] ?? 'dist',\n minify: !args['--no-minify'],\n clear: !!args['--clear'],\n dev: !!args['--dev'],\n maxWorkers: args['--max-workers'],\n dumpAssetmap: !!args['--dump-assetmap'],\n dumpSourcemap: !!args['--dump-sourcemap'],\n };\n}\n"],"names":["resolvePlatformOption","resolveOptionsAsync","platformBundlers","platform","platformsAvailable","Object","fromEntries","entries","filter","bundler","keys","length","CommandError","assertPlatformBundler","knownPlatforms","assertPlatformIsKnown","includes","join","map","flat","index","list","indexOf","projectRoot","args","exp","getConfig","skipPlugins","skipSDKVersionRequirement","getPlatformBundlers","platforms","outputDir","minify","clear","dev","maxWorkers","dumpAssetmap","dumpSourcemap"],"mappings":"AAAA;;;;QAiBgBA,qBAAqB,GAArBA,qBAAqB;QAiDfC,mBAAmB,GAAnBA,mBAAmB;AAlEL,IAAA,OAAc,WAAd,cAAc,CAAA;AAEI,IAAA,iBAAkC,WAAlC,kCAAkC,CAAA;AAC3D,IAAA,OAAiB,WAAjB,iBAAiB,CAAA;AAcvC,SAASD,qBAAqB,CACnCE,gBAAkC,EAClCC,SAAkB,GAAG;IAAC,KAAK;CAAC,EAChB;IACZ,MAAMC,kBAAkB,GAA8BC,MAAM,CAACC,WAAW,CACtED,MAAM,CAACE,OAAO,CAACL,gBAAgB,CAAC,CAACM,MAAM,CAAC,CAAC,GAAGC,OAAO,CAAC,GAAKA,OAAO,KAAK,OAAO;IAAA,CAAC,CAC9E,AAAC;IAEF,IAAI,CAACJ,MAAM,CAACK,IAAI,CAACN,kBAAkB,CAAC,CAACO,MAAM,EAAE;QAC3C,MAAM,IAAIC,OAAY,aAAA,CACpB,CAAC,gFAAgF,CAAC,CACnF,CAAC;KACH;IAED,MAAMC,qBAAqB,GAAG,CAACV,QAAkB,GAAe;QAC9D,IAAI,CAACC,kBAAkB,CAACD,QAAQ,CAAC,EAAE;YACjC,MAAM,IAAIS,OAAY,aAAA,CACpB,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KAAE,CAAC,AAAC;IAC/F,MAAM1B,gBAAgB,GAAG2B,CAAAA,GAAAA,iBAAmB,AAAK,CAAA,oBAAL,CAACJ,GAAG,CAAC,AAAC;QAIrCD,GAAoB;IAFjC,OAAO;QACLM,SAAS,EAAE9B,qBAAqB,CAACE,gBAAgB,EAAEsB,IAAI,CAAC,YAAY,CAAC,CAAC;QACtEO,SAAS,EAAEP,CAAAA,GAAoB,GAApBA,IAAI,CAAC,cAAc,CAAC,YAApBA,GAAoB,GAAI,MAAM;QACzCQ,MAAM,EAAE,CAACR,IAAI,CAAC,aAAa,CAAC;QAC5BS,KAAK,EAAE,CAAC,CAACT,IAAI,CAAC,SAAS,CAAC;QACxBU,GAAG,EAAE,CAAC,CAACV,IAAI,CAAC,OAAO,CAAC;QACpBW,UAAU,EAAEX,IAAI,CAAC,eAAe,CAAC;QACjCY,YAAY,EAAE,CAAC,CAACZ,IAAI,CAAC,iBAAiB,CAAC;QACvCa,aAAa,EAAE,CAAC,CAACb,IAAI,CAAC,kBAAkB,CAAC;KAC1C,CAAC;CACH"}
@@ -83,6 +83,9 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
83
83
  });
84
84
  }
85
85
  async composeResourcesWithHtml({ mode , resources , template , devBundleUrl }) {
86
+ if (!resources) {
87
+ return "";
88
+ }
86
89
  const isDev = mode === "development";
87
90
  return htmlFromSerialAssets(resources, {
88
91
  dev: isDev,
@@ -103,6 +106,7 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
103
106
  };
104
107
  }
105
108
  async getStaticResourcesAsync({ mode , minify =mode !== "development" }) {
109
+ var ref;
106
110
  const devBundleUrlPathname = (0, _manifestMiddleware).createBundleUrlPath({
107
111
  platform: "web",
108
112
  mode,
@@ -115,13 +119,39 @@ class MetroBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
115
119
  // Fetch the generated HTML from our custom Metro serializer
116
120
  const results = await (0, _nodeFetch).default(bundleUrl.toString());
117
121
  const txt = await results.text();
122
+ let data;
118
123
  try {
119
- return JSON.parse(txt);
124
+ data = JSON.parse(txt);
120
125
  } catch (error) {
121
126
  _log.Log.error("Failed to generate resources with Metro, the Metro config may not be using the correct serializer. Ensure the metro.config.js is extending the expo/metro-config and is not overriding the serializer.");
122
127
  debug(txt);
123
128
  throw error;
124
129
  }
130
+ // NOTE: This could potentially need more validation in the future.
131
+ if (Array.isArray(data)) {
132
+ return data;
133
+ }
134
+ if (data != null && (data.errors || ((ref = data.type) == null ? void 0 : ref.match(/.*Error$/)))) {
135
+ // {
136
+ // type: 'InternalError',
137
+ // errors: [],
138
+ // message: 'Metro has encountered an error: While trying to resolve module `stylis` from file `/Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js`, the package `/Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/stylis/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/stylis/dist/stylis.mjs`. Indeed, none of these files exist:\n' +
139
+ // '\n' +
140
+ // ' * /Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/stylis/dist/stylis.mjs(.web.ts|.ts|.web.tsx|.tsx|.web.js|.js|.web.jsx|.jsx|.web.json|.json|.web.cjs|.cjs|.web.scss|.scss|.web.sass|.sass|.web.css|.css)\n' +
141
+ // ' * /Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/stylis/dist/stylis.mjs/index(.web.ts|.ts|.web.tsx|.tsx|.web.js|.js|.web.jsx|.jsx|.web.json|.json|.web.cjs|.cjs|.web.scss|.scss|.web.sass|.sass|.web.css|.css): /Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/metro/src/node-haste/DependencyGraph.js (289:17)\n' +
142
+ // '\n' +
143
+ // '\x1B[0m \x1B[90m 287 |\x1B[39m }\x1B[0m\n' +
144
+ // '\x1B[0m \x1B[90m 288 |\x1B[39m \x1B[36mif\x1B[39m (error \x1B[36minstanceof\x1B[39m \x1B[33mInvalidPackageError\x1B[39m) {\x1B[0m\n' +
145
+ // '\x1B[0m\x1B[31m\x1B[1m>\x1B[22m\x1B[39m\x1B[90m 289 |\x1B[39m \x1B[36mthrow\x1B[39m \x1B[36mnew\x1B[39m \x1B[33mPackageResolutionError\x1B[39m({\x1B[0m\n' +
146
+ // '\x1B[0m \x1B[90m |\x1B[39m \x1B[31m\x1B[1m^\x1B[22m\x1B[39m\x1B[0m\n' +
147
+ // '\x1B[0m \x1B[90m 290 |\x1B[39m packageError\x1B[33m:\x1B[39m error\x1B[33m,\x1B[39m\x1B[0m\n' +
148
+ // '\x1B[0m \x1B[90m 291 |\x1B[39m originModulePath\x1B[33m:\x1B[39m \x1B[36mfrom\x1B[39m\x1B[33m,\x1B[39m\x1B[0m\n' +
149
+ // '\x1B[0m \x1B[90m 292 |\x1B[39m targetModuleName\x1B[33m:\x1B[39m to\x1B[33m,\x1B[39m\x1B[0m'
150
+ // }
151
+ // The Metro logger already showed this error.
152
+ throw new Error(data.message);
153
+ }
154
+ throw new Error("Invalid resources returned from the Metro serializer. Expected array, found: " + data);
125
155
  }
126
156
  async renderStaticErrorAsync(error) {
127
157
  return (0, _metroErrorInterface).getErrorOverlayHtmlAsync({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/MetroBundlerDevServer.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 { getConfig } from '@expo/config';\nimport { prependMiddleware } from '@expo/dev-server';\nimport * as runtimeEnv from '@expo/env';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport fetch from 'node-fetch';\nimport path from 'path';\n\nimport { Log } from '../../../log';\nimport getDevClientProperties from '../../../utils/analytics/getDevClientProperties';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport { getFreePortAsync } from '../../../utils/port';\nimport { BundlerDevServer, BundlerStartOptions, DevServerInstance } from '../BundlerDevServer';\nimport { getStaticRenderFunctions } from '../getStaticRenderFunctions';\nimport { ContextModuleSourceMapsMiddleware } from '../middleware/ContextModuleSourceMapsMiddleware';\nimport { CreateFileMiddleware } from '../middleware/CreateFileMiddleware';\nimport { FaviconMiddleware } from '../middleware/FaviconMiddleware';\nimport { HistoryFallbackMiddleware } from '../middleware/HistoryFallbackMiddleware';\nimport { InterstitialPageMiddleware } from '../middleware/InterstitialPageMiddleware';\nimport { createBundleUrlPath, resolveMainModuleName } from '../middleware/ManifestMiddleware';\nimport { ReactDevToolsPageMiddleware } from '../middleware/ReactDevToolsPageMiddleware';\nimport {\n DeepLinkHandler,\n RuntimeRedirectMiddleware,\n} from '../middleware/RuntimeRedirectMiddleware';\nimport { ServeStaticMiddleware } from '../middleware/ServeStaticMiddleware';\nimport { ServerNext, ServerRequest, ServerResponse } from '../middleware/server.types';\nimport { startTypescriptTypeGenerationAsync } from '../type-generation/startTypescriptTypeGeneration';\nimport { instantiateMetroAsync } from './instantiateMetro';\nimport { getErrorOverlayHtmlAsync } from './metroErrorInterface';\nimport { metroWatchTypeScriptFiles } from './metroWatchTypeScriptFiles';\nimport { observeFileChanges } from './waitForMetroToObserveTypeScriptFile';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\n/** Default port to use for apps running in Expo Go. */\nconst EXPO_GO_METRO_PORT = 8081;\n\n/** Default port to use for apps that run in standard React Native projects or Expo Dev Clients. */\nconst DEV_CLIENT_METRO_PORT = 8081;\n\nexport class MetroBundlerDevServer extends BundlerDevServer {\n private metro: import('metro').Server | null = null;\n\n get name(): string {\n return 'metro';\n }\n\n async resolvePortAsync(options: Partial<BundlerStartOptions> = {}): Promise<number> {\n const port =\n // If the manually defined port is busy then an error should be thrown...\n options.port ??\n // Otherwise use the default port based on the runtime target.\n (options.devClient\n ? // Don't check if the port is busy if we're using the dev client since most clients are hardcoded to 8081.\n Number(process.env.RCT_METRO_PORT) || DEV_CLIENT_METRO_PORT\n : // Otherwise (running in Expo Go) use a free port that falls back on the classic 8081 port.\n await getFreePortAsync(EXPO_GO_METRO_PORT));\n\n return port;\n }\n\n /** Get routes from Expo Router. */\n async getRoutesAsync() {\n const url = this.getDevServerUrl();\n assert(url, 'Dev server must be started');\n const { getManifest } = await getStaticRenderFunctions(this.projectRoot, url, {\n // Ensure the API Routes are included\n environment: 'node',\n });\n\n return getManifest({ fetchData: true });\n }\n\n async composeResourcesWithHtml({\n mode,\n resources,\n template,\n devBundleUrl,\n }: {\n mode: 'development' | 'production';\n resources: SerialAsset[];\n template: string;\n devBundleUrl?: string;\n }) {\n const isDev = mode === 'development';\n return htmlFromSerialAssets(resources, {\n dev: isDev,\n template,\n bundleUrl: isDev ? devBundleUrl : undefined,\n });\n }\n\n async getStaticRenderFunctionAsync({\n mode,\n minify = mode !== 'development',\n }: {\n mode: 'development' | 'production';\n minify?: boolean;\n }) {\n const url = this.getDevServerUrl()!;\n\n const { getStaticContent } = await getStaticRenderFunctions(this.projectRoot, url, {\n minify,\n dev: mode !== 'production',\n // Ensure the API Routes are included\n environment: 'node',\n });\n return async (path: string) => {\n return await getStaticContent(new URL(path, url));\n };\n }\n\n async getStaticResourcesAsync({\n mode,\n minify = mode !== 'development',\n }: {\n mode: string;\n minify?: boolean;\n }): Promise<SerialAsset[]> {\n const devBundleUrlPathname = createBundleUrlPath({\n platform: 'web',\n mode,\n minify,\n environment: 'client',\n serializerOutput: 'static',\n mainModuleName: resolveMainModuleName(this.projectRoot, getConfig(this.projectRoot), 'web'),\n });\n\n const bundleUrl = new URL(devBundleUrlPathname, this.getDevServerUrl()!);\n\n // Fetch the generated HTML from our custom Metro serializer\n const results = await fetch(bundleUrl.toString());\n\n const txt = await results.text();\n\n try {\n return JSON.parse(txt);\n } catch (error: any) {\n Log.error(\n 'Failed to generate resources with Metro, the Metro config may not be using the correct serializer. Ensure the metro.config.js is extending the expo/metro-config and is not overriding the serializer.'\n );\n debug(txt);\n throw error;\n }\n }\n\n private async renderStaticErrorAsync(error: Error) {\n return getErrorOverlayHtmlAsync({\n error,\n projectRoot: this.projectRoot,\n });\n }\n\n async getStaticPageAsync(\n pathname: string,\n {\n mode,\n minify = mode !== 'development',\n }: {\n mode: 'development' | 'production';\n minify?: boolean;\n }\n ) {\n const devBundleUrlPathname = createBundleUrlPath({\n platform: 'web',\n mode,\n environment: 'client',\n mainModuleName: resolveMainModuleName(this.projectRoot, getConfig(this.projectRoot), 'web'),\n });\n\n const bundleStaticHtml = async (): Promise<string> => {\n const { getStaticContent } = await getStaticRenderFunctions(\n this.projectRoot,\n this.getDevServerUrl()!,\n {\n minify: false,\n dev: mode !== 'production',\n // Ensure the API Routes are included\n environment: 'node',\n }\n );\n\n const location = new URL(pathname, this.getDevServerUrl()!);\n return await getStaticContent(location);\n };\n\n const [resources, staticHtml] = await Promise.all([\n this.getStaticResourcesAsync({ mode, minify }),\n bundleStaticHtml(),\n ]);\n const content = await this.composeResourcesWithHtml({\n mode,\n resources,\n template: staticHtml,\n devBundleUrl: devBundleUrlPathname,\n });\n return {\n content,\n resources,\n };\n }\n\n async watchEnvironmentVariables() {\n if (!this.instance) {\n throw new Error(\n 'Cannot observe environment variable changes without a running Metro instance.'\n );\n }\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process.\n debug('Skipping Environment Variable observation because Metro is not running (headless).');\n return;\n }\n\n const envFiles = runtimeEnv\n .getFiles(process.env.NODE_ENV)\n .map((fileName) => path.join(this.projectRoot, fileName));\n\n observeFileChanges(\n {\n metro: this.metro,\n server: this.instance.server,\n },\n envFiles,\n () => {\n debug('Reloading environment variables...');\n // Force reload the environment variables.\n runtimeEnv.load(this.projectRoot, { force: true });\n }\n );\n }\n\n protected async startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance> {\n options.port = await this.resolvePortAsync(options);\n this.urlCreator = this.getUrlCreator(options);\n\n const parsedOptions = {\n port: options.port,\n maxWorkers: options.maxWorkers,\n resetCache: options.resetDevServer,\n\n // Use the unversioned metro config.\n // TODO: Deprecate this property when expo-cli goes away.\n unversioned: false,\n };\n\n // Required for symbolication:\n process.env.EXPO_DEV_SERVER_ORIGIN = `http://localhost:${options.port}`;\n\n const { metro, server, middleware, messageSocket } = await instantiateMetroAsync(\n this,\n parsedOptions\n );\n\n const manifestMiddleware = await this.getManifestMiddlewareAsync(options);\n\n // Important that we noop source maps for context modules as soon as possible.\n prependMiddleware(middleware, new ContextModuleSourceMapsMiddleware().getHandler());\n\n // We need the manifest handler to be the first middleware to run so our\n // routes take precedence over static files. For example, the manifest is\n // served from '/' and if the user has an index.html file in their project\n // then the manifest handler will never run, the static middleware will run\n // and serve index.html instead of the manifest.\n // https://github.com/expo/expo/issues/13114\n prependMiddleware(middleware, manifestMiddleware.getHandler());\n\n middleware.use(\n new InterstitialPageMiddleware(this.projectRoot, {\n // TODO: Prevent this from becoming stale.\n scheme: options.location.scheme ?? null,\n }).getHandler()\n );\n middleware.use(new ReactDevToolsPageMiddleware(this.projectRoot).getHandler());\n\n const deepLinkMiddleware = new RuntimeRedirectMiddleware(this.projectRoot, {\n onDeepLink: getDeepLinkHandler(this.projectRoot),\n getLocation: ({ runtime }) => {\n if (runtime === 'custom') {\n return this.urlCreator?.constructDevClientUrl();\n } else {\n return this.urlCreator?.constructUrl({\n scheme: 'exp',\n });\n }\n },\n });\n middleware.use(deepLinkMiddleware.getHandler());\n\n middleware.use(new CreateFileMiddleware(this.projectRoot).getHandler());\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n const { exp } = getConfig(this.projectRoot, { skipSDKVersionRequirement: true });\n const useWebSSG = exp.web?.output === 'static';\n\n // This MUST be after the manifest middleware so it doesn't have a chance to serve the template `public/index.html`.\n middleware.use(new ServeStaticMiddleware(this.projectRoot).getHandler());\n\n // This should come after the static middleware so it doesn't serve the favicon from `public/favicon.ico`.\n middleware.use(new FaviconMiddleware(this.projectRoot).getHandler());\n\n if (useWebSSG) {\n middleware.use(async (req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n if (!req?.url) {\n return next();\n }\n\n // TODO: Formal manifest for allowed paths\n if (req.url.endsWith('.ico')) {\n return next();\n }\n if (req.url.includes('serializer.output=static')) {\n return next();\n }\n\n try {\n const { content } = await this.getStaticPageAsync(req.url, {\n mode: options.mode ?? 'development',\n });\n\n res.setHeader('Content-Type', 'text/html');\n res.end(content);\n return;\n } catch (error: any) {\n res.setHeader('Content-Type', 'text/html');\n try {\n res.end(await this.renderStaticErrorAsync(error));\n } catch (staticError: any) {\n // Fallback error for when Expo Router is misconfigured in the project.\n res.end(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>'\n );\n }\n }\n });\n }\n\n // This MUST run last since it's the fallback.\n if (!useWebSSG) {\n middleware.use(\n new HistoryFallbackMiddleware(manifestMiddleware.getHandler().internal).getHandler()\n );\n }\n }\n // Extend the close method to ensure that we clean up the local info.\n const originalClose = server.close.bind(server);\n\n server.close = (callback?: (err?: Error) => void) => {\n return originalClose((err?: Error) => {\n this.instance = null;\n this.metro = null;\n callback?.(err);\n });\n };\n\n this.metro = metro;\n return {\n server,\n location: {\n // The port is the main thing we want to send back.\n port: options.port,\n // localhost isn't always correct.\n host: 'localhost',\n // http is the only supported protocol on native.\n url: `http://localhost:${options.port}`,\n protocol: 'http',\n },\n middleware,\n messageSocket,\n };\n }\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n if (!this.instance) {\n throw new Error('Cannot wait for TypeScript without a running server.');\n }\n\n return new Promise<boolean>((resolve) => {\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process. In this case we can't wait for the TypeScript check to complete because we don't\n // have access to the Metro server.\n debug('Skipping TypeScript check because Metro is not running (headless).');\n return resolve(false);\n }\n\n const off = metroWatchTypeScriptFiles({\n projectRoot: this.projectRoot,\n server: this.instance!.server,\n metro: this.metro,\n tsconfig: true,\n throttle: true,\n eventTypes: ['change', 'add'],\n callback: async () => {\n // Run once, this prevents the TypeScript project prerequisite from running on every file change.\n off();\n const { TypeScriptProjectPrerequisite } = await import(\n '../../doctor/typescript/TypeScriptProjectPrerequisite'\n );\n\n try {\n const req = new TypeScriptProjectPrerequisite(this.projectRoot);\n await req.bootstrapAsync();\n resolve(true);\n } catch (error: any) {\n // Ensure the process doesn't fail if the TypeScript check fails.\n // This could happen during the install.\n Log.log();\n Log.error(\n chalk.red`Failed to automatically setup TypeScript for your project. Try restarting the dev server to fix.`\n );\n Log.exception(error);\n resolve(false);\n }\n },\n });\n });\n }\n\n public async startTypeScriptServices() {\n startTypescriptTypeGenerationAsync({\n server: this.instance!.server,\n metro: this.metro,\n projectRoot: this.projectRoot,\n });\n }\n\n protected getConfigModuleIds(): string[] {\n return ['./metro.config.js', './metro.config.json', './rn-cli.config.js'];\n }\n}\n\nexport function getDeepLinkHandler(projectRoot: string): DeepLinkHandler {\n return async ({ runtime }) => {\n if (runtime === 'expo') return;\n const { exp } = getConfig(projectRoot);\n await logEventAsync('dev client start command', {\n status: 'started',\n ...getDevClientProperties(projectRoot, exp),\n });\n };\n}\n\nfunction htmlFromSerialAssets(\n assets: SerialAsset[],\n { dev, template, bundleUrl }: { dev: boolean; template: string; bundleUrl?: string }\n) {\n // Combine the CSS modules into tags that have hot refresh data attributes.\n const styleString = assets\n .filter((asset) => asset.type === 'css')\n .map(({ metadata, filename, source }) => {\n if (dev) {\n return `<style data-expo-css-hmr=\"${metadata.hmrId}\">` + source + '\\n</style>';\n } else {\n return [\n `<link rel=\"preload\" href=\"/${filename}\" as=\"style\">`,\n `<link rel=\"stylesheet\" href=\"/${filename}\">`,\n ].join('');\n }\n })\n .join('');\n\n const jsAssets = assets.filter((asset) => asset.type === 'js');\n\n const scripts = bundleUrl\n ? `<script src=\"${bundleUrl}\" defer></script>`\n : jsAssets\n .map(({ filename }) => {\n return `<script src=\"/${filename}\" defer></script>`;\n })\n .join('');\n\n return template\n .replace('</head>', `${styleString}</head>`)\n .replace('</body>', `${scripts}\\n</body>`);\n}\n"],"names":["getDeepLinkHandler","runtimeEnv","debug","require","EXPO_GO_METRO_PORT","DEV_CLIENT_METRO_PORT","MetroBundlerDevServer","BundlerDevServer","metro","name","resolvePortAsync","options","port","devClient","Number","process","env","RCT_METRO_PORT","getFreePortAsync","getRoutesAsync","url","getDevServerUrl","assert","getManifest","getStaticRenderFunctions","projectRoot","environment","fetchData","composeResourcesWithHtml","mode","resources","template","devBundleUrl","isDev","htmlFromSerialAssets","dev","bundleUrl","undefined","getStaticRenderFunctionAsync","minify","getStaticContent","path","URL","getStaticResourcesAsync","devBundleUrlPathname","createBundleUrlPath","platform","serializerOutput","mainModuleName","resolveMainModuleName","getConfig","results","fetch","toString","txt","text","JSON","parse","error","Log","renderStaticErrorAsync","getErrorOverlayHtmlAsync","getStaticPageAsync","pathname","bundleStaticHtml","location","staticHtml","Promise","all","content","watchEnvironmentVariables","instance","Error","envFiles","getFiles","NODE_ENV","map","fileName","join","observeFileChanges","server","load","force","startImplementationAsync","urlCreator","getUrlCreator","parsedOptions","maxWorkers","resetCache","resetDevServer","unversioned","EXPO_DEV_SERVER_ORIGIN","middleware","messageSocket","instantiateMetroAsync","manifestMiddleware","getManifestMiddlewareAsync","prependMiddleware","ContextModuleSourceMapsMiddleware","getHandler","use","InterstitialPageMiddleware","scheme","ReactDevToolsPageMiddleware","deepLinkMiddleware","RuntimeRedirectMiddleware","onDeepLink","getLocation","runtime","constructDevClientUrl","constructUrl","CreateFileMiddleware","isTargetingWeb","exp","skipSDKVersionRequirement","useWebSSG","web","output","ServeStaticMiddleware","FaviconMiddleware","req","res","next","endsWith","includes","setHeader","end","staticError","message","HistoryFallbackMiddleware","internal","originalClose","close","bind","callback","err","host","protocol","waitForTypeScriptAsync","resolve","off","metroWatchTypeScriptFiles","tsconfig","throttle","eventTypes","TypeScriptProjectPrerequisite","bootstrapAsync","log","chalk","red","exception","startTypeScriptServices","startTypescriptTypeGenerationAsync","getConfigModuleIds","logEventAsync","status","getDevClientProperties","assets","styleString","filter","asset","type","metadata","filename","source","hmrId","jsAssets","scripts","replace"],"mappings":"AAMA;;;;QA0bgBA,kBAAkB,GAAlBA,kBAAkB;AA1bR,IAAA,OAAc,WAAd,cAAc,CAAA;AACN,IAAA,UAAkB,WAAlB,kBAAkB,CAAA;AACxCC,IAAAA,UAAU,mCAAM,WAAW,EAAjB;AAEH,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACT,IAAA,MAAO,kCAAP,OAAO,EAAA;AACP,IAAA,UAAY,kCAAZ,YAAY,EAAA;AACb,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEH,IAAA,IAAc,WAAd,cAAc,CAAA;AACC,IAAA,uBAAiD,kCAAjD,iDAAiD,EAAA;AACtD,IAAA,kBAA4C,WAA5C,4CAA4C,CAAA;AACzC,IAAA,KAAqB,WAArB,qBAAqB,CAAA;AACmB,IAAA,iBAAqB,WAArB,qBAAqB,CAAA;AACrD,IAAA,yBAA6B,WAA7B,6BAA6B,CAAA;AACpB,IAAA,kCAAiD,WAAjD,iDAAiD,CAAA;AAC9D,IAAA,qBAAoC,WAApC,oCAAoC,CAAA;AACvC,IAAA,kBAAiC,WAAjC,iCAAiC,CAAA;AACzB,IAAA,0BAAyC,WAAzC,yCAAyC,CAAA;AACxC,IAAA,2BAA0C,WAA1C,0CAA0C,CAAA;AAC1B,IAAA,mBAAkC,WAAlC,kCAAkC,CAAA;AACjD,IAAA,4BAA2C,WAA3C,2CAA2C,CAAA;AAIhF,IAAA,0BAAyC,WAAzC,yCAAyC,CAAA;AACV,IAAA,sBAAqC,WAArC,qCAAqC,CAAA;AAExB,IAAA,8BAAkD,WAAlD,kDAAkD,CAAA;AAC/D,IAAA,iBAAoB,WAApB,oBAAoB,CAAA;AACjB,IAAA,oBAAuB,WAAvB,uBAAuB,CAAA;AACtB,IAAA,0BAA6B,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OAAO;gBACL,CAAC,2BAA2B,EAAED,QAAQ,CAAC,aAAa,CAAC;gBACrD,CAAC,8BAA8B,EAAEA,QAAQ,CAAC,EAAE,CAAC;aAC9C,CAACrF,IAAI,CAAC,EAAE,CAAC,CAAC;SACZ;KACF,CAAC,CACDA,IAAI,CAAC,EAAE,CAAC,AAAC;IAEZ,MAAMwF,QAAQ,GAAGT,MAAM,CAACE,MAAM,CAAC,CAACC,KAAK,GAAKA,KAAK,CAACC,IAAI,KAAK,IAAI;IAAA,CAAC,AAAC;IAE/D,MAAMM,OAAO,GAAGnI,SAAS,GACrB,CAAC,aAAa,EAAEA,SAAS,CAAC,iBAAiB,CAAC,GAC5CkI,QAAQ,CACL1F,GAAG,CAAC,CAAC,EAAEuF,QAAQ,CAAA,EAAE,GAAK;QACrB,OAAO,CAAC,cAAc,EAAEA,QAAQ,CAAC,iBAAiB,CAAC,CAAC;KACrD,CAAC,CACDrF,IAAI,CAAC,EAAE,CAAC,AAAC;IAEhB,OAAO/C,QAAQ,CACZyI,OAAO,CAAC,SAAS,EAAE,CAAC,EAAEV,WAAW,CAAC,OAAO,CAAC,CAAC,CAC3CU,OAAO,CAAC,SAAS,EAAE,CAAC,EAAED,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC;CAC9C"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/MetroBundlerDevServer.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 { getConfig } from '@expo/config';\nimport { prependMiddleware } from '@expo/dev-server';\nimport * as runtimeEnv from '@expo/env';\nimport { SerialAsset } from '@expo/metro-config/build/serializer/serializerAssets';\nimport assert from 'assert';\nimport chalk from 'chalk';\nimport fetch from 'node-fetch';\nimport path from 'path';\n\nimport { Log } from '../../../log';\nimport getDevClientProperties from '../../../utils/analytics/getDevClientProperties';\nimport { logEventAsync } from '../../../utils/analytics/rudderstackClient';\nimport { getFreePortAsync } from '../../../utils/port';\nimport { BundlerDevServer, BundlerStartOptions, DevServerInstance } from '../BundlerDevServer';\nimport { getStaticRenderFunctions } from '../getStaticRenderFunctions';\nimport { ContextModuleSourceMapsMiddleware } from '../middleware/ContextModuleSourceMapsMiddleware';\nimport { CreateFileMiddleware } from '../middleware/CreateFileMiddleware';\nimport { FaviconMiddleware } from '../middleware/FaviconMiddleware';\nimport { HistoryFallbackMiddleware } from '../middleware/HistoryFallbackMiddleware';\nimport { InterstitialPageMiddleware } from '../middleware/InterstitialPageMiddleware';\nimport { createBundleUrlPath, resolveMainModuleName } from '../middleware/ManifestMiddleware';\nimport { ReactDevToolsPageMiddleware } from '../middleware/ReactDevToolsPageMiddleware';\nimport {\n DeepLinkHandler,\n RuntimeRedirectMiddleware,\n} from '../middleware/RuntimeRedirectMiddleware';\nimport { ServeStaticMiddleware } from '../middleware/ServeStaticMiddleware';\nimport { ServerNext, ServerRequest, ServerResponse } from '../middleware/server.types';\nimport { startTypescriptTypeGenerationAsync } from '../type-generation/startTypescriptTypeGeneration';\nimport { instantiateMetroAsync } from './instantiateMetro';\nimport { getErrorOverlayHtmlAsync } from './metroErrorInterface';\nimport { metroWatchTypeScriptFiles } from './metroWatchTypeScriptFiles';\nimport { observeFileChanges } from './waitForMetroToObserveTypeScriptFile';\n\nconst debug = require('debug')('expo:start:server:metro') as typeof console.log;\n\n/** Default port to use for apps running in Expo Go. */\nconst EXPO_GO_METRO_PORT = 8081;\n\n/** Default port to use for apps that run in standard React Native projects or Expo Dev Clients. */\nconst DEV_CLIENT_METRO_PORT = 8081;\n\nexport class MetroBundlerDevServer extends BundlerDevServer {\n private metro: import('metro').Server | null = null;\n\n get name(): string {\n return 'metro';\n }\n\n async resolvePortAsync(options: Partial<BundlerStartOptions> = {}): Promise<number> {\n const port =\n // If the manually defined port is busy then an error should be thrown...\n options.port ??\n // Otherwise use the default port based on the runtime target.\n (options.devClient\n ? // Don't check if the port is busy if we're using the dev client since most clients are hardcoded to 8081.\n Number(process.env.RCT_METRO_PORT) || DEV_CLIENT_METRO_PORT\n : // Otherwise (running in Expo Go) use a free port that falls back on the classic 8081 port.\n await getFreePortAsync(EXPO_GO_METRO_PORT));\n\n return port;\n }\n\n /** Get routes from Expo Router. */\n async getRoutesAsync() {\n const url = this.getDevServerUrl();\n assert(url, 'Dev server must be started');\n const { getManifest } = await getStaticRenderFunctions(this.projectRoot, url, {\n // Ensure the API Routes are included\n environment: 'node',\n });\n\n return getManifest({ fetchData: true });\n }\n\n async composeResourcesWithHtml({\n mode,\n resources,\n template,\n devBundleUrl,\n }: {\n mode: 'development' | 'production';\n resources: SerialAsset[];\n template: string;\n devBundleUrl?: string;\n }): Promise<string> {\n if (!resources) {\n return '';\n }\n const isDev = mode === 'development';\n return htmlFromSerialAssets(resources, {\n dev: isDev,\n template,\n bundleUrl: isDev ? devBundleUrl : undefined,\n });\n }\n\n async getStaticRenderFunctionAsync({\n mode,\n minify = mode !== 'development',\n }: {\n mode: 'development' | 'production';\n minify?: boolean;\n }) {\n const url = this.getDevServerUrl()!;\n\n const { getStaticContent } = await getStaticRenderFunctions(this.projectRoot, url, {\n minify,\n dev: mode !== 'production',\n // Ensure the API Routes are included\n environment: 'node',\n });\n return async (path: string) => {\n return await getStaticContent(new URL(path, url));\n };\n }\n\n async getStaticResourcesAsync({\n mode,\n minify = mode !== 'development',\n }: {\n mode: string;\n minify?: boolean;\n }): Promise<SerialAsset[]> {\n const devBundleUrlPathname = createBundleUrlPath({\n platform: 'web',\n mode,\n minify,\n environment: 'client',\n serializerOutput: 'static',\n mainModuleName: resolveMainModuleName(this.projectRoot, getConfig(this.projectRoot), 'web'),\n });\n\n const bundleUrl = new URL(devBundleUrlPathname, this.getDevServerUrl()!);\n\n // Fetch the generated HTML from our custom Metro serializer\n const results = await fetch(bundleUrl.toString());\n\n const txt = await results.text();\n\n let data: any;\n try {\n data = JSON.parse(txt);\n } catch (error: any) {\n Log.error(\n 'Failed to generate resources with Metro, the Metro config may not be using the correct serializer. Ensure the metro.config.js is extending the expo/metro-config and is not overriding the serializer.'\n );\n debug(txt);\n throw error;\n }\n\n // NOTE: This could potentially need more validation in the future.\n if (Array.isArray(data)) {\n return data;\n }\n\n if (data != null && (data.errors || data.type?.match(/.*Error$/))) {\n // {\n // type: 'InternalError',\n // errors: [],\n // message: 'Metro has encountered an error: While trying to resolve module `stylis` from file `/Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js`, the package `/Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/stylis/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/stylis/dist/stylis.mjs`. Indeed, none of these files exist:\\n' +\n // '\\n' +\n // ' * /Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/stylis/dist/stylis.mjs(.web.ts|.ts|.web.tsx|.tsx|.web.js|.js|.web.jsx|.jsx|.web.json|.json|.web.cjs|.cjs|.web.scss|.scss|.web.sass|.sass|.web.css|.css)\\n' +\n // ' * /Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/stylis/dist/stylis.mjs/index(.web.ts|.ts|.web.tsx|.tsx|.web.js|.js|.web.jsx|.jsx|.web.json|.json|.web.cjs|.cjs|.web.scss|.scss|.web.sass|.sass|.web.css|.css): /Users/evanbacon/Documents/GitHub/lab/emotion-error-test/node_modules/metro/src/node-haste/DependencyGraph.js (289:17)\\n' +\n // '\\n' +\n // '\\x1B[0m \\x1B[90m 287 |\\x1B[39m }\\x1B[0m\\n' +\n // '\\x1B[0m \\x1B[90m 288 |\\x1B[39m \\x1B[36mif\\x1B[39m (error \\x1B[36minstanceof\\x1B[39m \\x1B[33mInvalidPackageError\\x1B[39m) {\\x1B[0m\\n' +\n // '\\x1B[0m\\x1B[31m\\x1B[1m>\\x1B[22m\\x1B[39m\\x1B[90m 289 |\\x1B[39m \\x1B[36mthrow\\x1B[39m \\x1B[36mnew\\x1B[39m \\x1B[33mPackageResolutionError\\x1B[39m({\\x1B[0m\\n' +\n // '\\x1B[0m \\x1B[90m |\\x1B[39m \\x1B[31m\\x1B[1m^\\x1B[22m\\x1B[39m\\x1B[0m\\n' +\n // '\\x1B[0m \\x1B[90m 290 |\\x1B[39m packageError\\x1B[33m:\\x1B[39m error\\x1B[33m,\\x1B[39m\\x1B[0m\\n' +\n // '\\x1B[0m \\x1B[90m 291 |\\x1B[39m originModulePath\\x1B[33m:\\x1B[39m \\x1B[36mfrom\\x1B[39m\\x1B[33m,\\x1B[39m\\x1B[0m\\n' +\n // '\\x1B[0m \\x1B[90m 292 |\\x1B[39m targetModuleName\\x1B[33m:\\x1B[39m to\\x1B[33m,\\x1B[39m\\x1B[0m'\n // }\n // The Metro logger already showed this error.\n throw new Error(data.message);\n }\n\n throw new Error(\n 'Invalid resources returned from the Metro serializer. Expected array, found: ' + data\n );\n }\n\n private async renderStaticErrorAsync(error: Error) {\n return getErrorOverlayHtmlAsync({\n error,\n projectRoot: this.projectRoot,\n });\n }\n\n async getStaticPageAsync(\n pathname: string,\n {\n mode,\n minify = mode !== 'development',\n }: {\n mode: 'development' | 'production';\n minify?: boolean;\n }\n ) {\n const devBundleUrlPathname = createBundleUrlPath({\n platform: 'web',\n mode,\n environment: 'client',\n mainModuleName: resolveMainModuleName(this.projectRoot, getConfig(this.projectRoot), 'web'),\n });\n\n const bundleStaticHtml = async (): Promise<string> => {\n const { getStaticContent } = await getStaticRenderFunctions(\n this.projectRoot,\n this.getDevServerUrl()!,\n {\n minify: false,\n dev: mode !== 'production',\n // Ensure the API Routes are included\n environment: 'node',\n }\n );\n\n const location = new URL(pathname, this.getDevServerUrl()!);\n return await getStaticContent(location);\n };\n\n const [resources, staticHtml] = await Promise.all([\n this.getStaticResourcesAsync({ mode, minify }),\n bundleStaticHtml(),\n ]);\n const content = await this.composeResourcesWithHtml({\n mode,\n resources,\n template: staticHtml,\n devBundleUrl: devBundleUrlPathname,\n });\n return {\n content,\n resources,\n };\n }\n\n async watchEnvironmentVariables() {\n if (!this.instance) {\n throw new Error(\n 'Cannot observe environment variable changes without a running Metro instance.'\n );\n }\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process.\n debug('Skipping Environment Variable observation because Metro is not running (headless).');\n return;\n }\n\n const envFiles = runtimeEnv\n .getFiles(process.env.NODE_ENV)\n .map((fileName) => path.join(this.projectRoot, fileName));\n\n observeFileChanges(\n {\n metro: this.metro,\n server: this.instance.server,\n },\n envFiles,\n () => {\n debug('Reloading environment variables...');\n // Force reload the environment variables.\n runtimeEnv.load(this.projectRoot, { force: true });\n }\n );\n }\n\n protected async startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance> {\n options.port = await this.resolvePortAsync(options);\n this.urlCreator = this.getUrlCreator(options);\n\n const parsedOptions = {\n port: options.port,\n maxWorkers: options.maxWorkers,\n resetCache: options.resetDevServer,\n\n // Use the unversioned metro config.\n // TODO: Deprecate this property when expo-cli goes away.\n unversioned: false,\n };\n\n // Required for symbolication:\n process.env.EXPO_DEV_SERVER_ORIGIN = `http://localhost:${options.port}`;\n\n const { metro, server, middleware, messageSocket } = await instantiateMetroAsync(\n this,\n parsedOptions\n );\n\n const manifestMiddleware = await this.getManifestMiddlewareAsync(options);\n\n // Important that we noop source maps for context modules as soon as possible.\n prependMiddleware(middleware, new ContextModuleSourceMapsMiddleware().getHandler());\n\n // We need the manifest handler to be the first middleware to run so our\n // routes take precedence over static files. For example, the manifest is\n // served from '/' and if the user has an index.html file in their project\n // then the manifest handler will never run, the static middleware will run\n // and serve index.html instead of the manifest.\n // https://github.com/expo/expo/issues/13114\n prependMiddleware(middleware, manifestMiddleware.getHandler());\n\n middleware.use(\n new InterstitialPageMiddleware(this.projectRoot, {\n // TODO: Prevent this from becoming stale.\n scheme: options.location.scheme ?? null,\n }).getHandler()\n );\n middleware.use(new ReactDevToolsPageMiddleware(this.projectRoot).getHandler());\n\n const deepLinkMiddleware = new RuntimeRedirectMiddleware(this.projectRoot, {\n onDeepLink: getDeepLinkHandler(this.projectRoot),\n getLocation: ({ runtime }) => {\n if (runtime === 'custom') {\n return this.urlCreator?.constructDevClientUrl();\n } else {\n return this.urlCreator?.constructUrl({\n scheme: 'exp',\n });\n }\n },\n });\n middleware.use(deepLinkMiddleware.getHandler());\n\n middleware.use(new CreateFileMiddleware(this.projectRoot).getHandler());\n\n // Append support for redirecting unhandled requests to the index.html page on web.\n if (this.isTargetingWeb()) {\n const { exp } = getConfig(this.projectRoot, { skipSDKVersionRequirement: true });\n const useWebSSG = exp.web?.output === 'static';\n\n // This MUST be after the manifest middleware so it doesn't have a chance to serve the template `public/index.html`.\n middleware.use(new ServeStaticMiddleware(this.projectRoot).getHandler());\n\n // This should come after the static middleware so it doesn't serve the favicon from `public/favicon.ico`.\n middleware.use(new FaviconMiddleware(this.projectRoot).getHandler());\n\n if (useWebSSG) {\n middleware.use(async (req: ServerRequest, res: ServerResponse, next: ServerNext) => {\n if (!req?.url) {\n return next();\n }\n\n // TODO: Formal manifest for allowed paths\n if (req.url.endsWith('.ico')) {\n return next();\n }\n if (req.url.includes('serializer.output=static')) {\n return next();\n }\n\n try {\n const { content } = await this.getStaticPageAsync(req.url, {\n mode: options.mode ?? 'development',\n });\n\n res.setHeader('Content-Type', 'text/html');\n res.end(content);\n return;\n } catch (error: any) {\n res.setHeader('Content-Type', 'text/html');\n try {\n res.end(await this.renderStaticErrorAsync(error));\n } catch (staticError: any) {\n // Fallback error for when Expo Router is misconfigured in the project.\n res.end(\n '<span><h3>Internal Error:</h3><b>Project is not setup correctly for static rendering (check terminal for more info):</b><br/>' +\n error.message +\n '<br/><br/>' +\n staticError.message +\n '</span>'\n );\n }\n }\n });\n }\n\n // This MUST run last since it's the fallback.\n if (!useWebSSG) {\n middleware.use(\n new HistoryFallbackMiddleware(manifestMiddleware.getHandler().internal).getHandler()\n );\n }\n }\n // Extend the close method to ensure that we clean up the local info.\n const originalClose = server.close.bind(server);\n\n server.close = (callback?: (err?: Error) => void) => {\n return originalClose((err?: Error) => {\n this.instance = null;\n this.metro = null;\n callback?.(err);\n });\n };\n\n this.metro = metro;\n return {\n server,\n location: {\n // The port is the main thing we want to send back.\n port: options.port,\n // localhost isn't always correct.\n host: 'localhost',\n // http is the only supported protocol on native.\n url: `http://localhost:${options.port}`,\n protocol: 'http',\n },\n middleware,\n messageSocket,\n };\n }\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n if (!this.instance) {\n throw new Error('Cannot wait for TypeScript without a running server.');\n }\n\n return new Promise<boolean>((resolve) => {\n if (!this.metro) {\n // This can happen when the run command is used and the server is already running in another\n // process. In this case we can't wait for the TypeScript check to complete because we don't\n // have access to the Metro server.\n debug('Skipping TypeScript check because Metro is not running (headless).');\n return resolve(false);\n }\n\n const off = metroWatchTypeScriptFiles({\n projectRoot: this.projectRoot,\n server: this.instance!.server,\n metro: this.metro,\n tsconfig: true,\n throttle: true,\n eventTypes: ['change', 'add'],\n callback: async () => {\n // Run once, this prevents the TypeScript project prerequisite from running on every file change.\n off();\n const { TypeScriptProjectPrerequisite } = await import(\n '../../doctor/typescript/TypeScriptProjectPrerequisite'\n );\n\n try {\n const req = new TypeScriptProjectPrerequisite(this.projectRoot);\n await req.bootstrapAsync();\n resolve(true);\n } catch (error: any) {\n // Ensure the process doesn't fail if the TypeScript check fails.\n // This could happen during the install.\n Log.log();\n Log.error(\n chalk.red`Failed to automatically setup TypeScript for your project. Try restarting the dev server to fix.`\n );\n Log.exception(error);\n resolve(false);\n }\n },\n });\n });\n }\n\n public async startTypeScriptServices() {\n startTypescriptTypeGenerationAsync({\n server: this.instance!.server,\n metro: this.metro,\n projectRoot: this.projectRoot,\n });\n }\n\n protected getConfigModuleIds(): string[] {\n return ['./metro.config.js', './metro.config.json', './rn-cli.config.js'];\n }\n}\n\nexport function getDeepLinkHandler(projectRoot: string): DeepLinkHandler {\n return async ({ runtime }) => {\n if (runtime === 'expo') return;\n const { exp } = getConfig(projectRoot);\n await logEventAsync('dev client start command', {\n status: 'started',\n ...getDevClientProperties(projectRoot, exp),\n });\n };\n}\n\nfunction htmlFromSerialAssets(\n assets: SerialAsset[],\n { dev, template, bundleUrl }: { dev: boolean; template: string; bundleUrl?: string }\n) {\n // Combine the CSS modules into tags that have hot refresh data attributes.\n const styleString = assets\n .filter((asset) => asset.type === 'css')\n .map(({ metadata, filename, source }) => {\n if (dev) {\n return `<style data-expo-css-hmr=\"${metadata.hmrId}\">` + source + '\\n</style>';\n } else {\n return [\n `<link rel=\"preload\" href=\"/${filename}\" as=\"style\">`,\n `<link rel=\"stylesheet\" href=\"/${filename}\">`,\n ].join('');\n }\n })\n .join('');\n\n const jsAssets = assets.filter((asset) => asset.type === 'js');\n\n const scripts = bundleUrl\n ? `<script src=\"${bundleUrl}\" defer></script>`\n : jsAssets\n .map(({ filename }) => {\n return `<script src=\"/${filename}\" defer></script>`;\n })\n .join('');\n\n return template\n .replace('</head>', `${styleString}</head>`)\n .replace('</body>', `${scripts}\\n</body>`);\n}\n"],"names":["getDeepLinkHandler","runtimeEnv","debug","require","EXPO_GO_METRO_PORT","DEV_CLIENT_METRO_PORT","MetroBundlerDevServer","BundlerDevServer","metro","name","resolvePortAsync","options","port","devClient","Number","process","env","RCT_METRO_PORT","getFreePortAsync","getRoutesAsync","url","getDevServerUrl","assert","getManifest","getStaticRenderFunctions","projectRoot","environment","fetchData","composeResourcesWithHtml","mode","resources","template","devBundleUrl","isDev","htmlFromSerialAssets","dev","bundleUrl","undefined","getStaticRenderFunctionAsync","minify","getStaticContent","path","URL","getStaticResourcesAsync","data","devBundleUrlPathname","createBundleUrlPath","platform","serializerOutput","mainModuleName","resolveMainModuleName","getConfig","results","fetch","toString","txt","text","JSON","parse","error","Log","Array","isArray","errors","type","match","Error","message","renderStaticErrorAsync","getErrorOverlayHtmlAsync","getStaticPageAsync","pathname","bundleStaticHtml","location","staticHtml","Promise","all","content","watchEnvironmentVariables","instance","envFiles","getFiles","NODE_ENV","map","fileName","join","observeFileChanges","server","load","force","startImplementationAsync","urlCreator","getUrlCreator","parsedOptions","maxWorkers","resetCache","resetDevServer","unversioned","EXPO_DEV_SERVER_ORIGIN","middleware","messageSocket","instantiateMetroAsync","manifestMiddleware","getManifestMiddlewareAsync","prependMiddleware","ContextModuleSourceMapsMiddleware","getHandler","use","InterstitialPageMiddleware","scheme","ReactDevToolsPageMiddleware","deepLinkMiddleware","RuntimeRedirectMiddleware","onDeepLink","getLocation","runtime","constructDevClientUrl","constructUrl","CreateFileMiddleware","isTargetingWeb","exp","skipSDKVersionRequirement","useWebSSG","web","output","ServeStaticMiddleware","FaviconMiddleware","req","res","next","endsWith","includes","setHeader","end","staticError","HistoryFallbackMiddleware","internal","originalClose","close","bind","callback","err","host","protocol","waitForTypeScriptAsync","resolve","off","metroWatchTypeScriptFiles","tsconfig","throttle","eventTypes","TypeScriptProjectPrerequisite","bootstrapAsync","log","chalk","red","exception","startTypeScriptServices","startTypescriptTypeGenerationAsync","getConfigModuleIds","logEventAsync","status","getDevClientProperties","assets","styleString","filter","asset","metadata","filename","source","hmrId","jsAssets","scripts","replace"],"mappings":"AAMA;;;;QA4dgBA,kBAAkB,GAAlBA,kBAAkB;AA5dR,IAAA,OAAc,WAAd,cAAc,CAAA;AACN,IAAA,UAAkB,WAAlB,kBAAkB,CAAA;AACxCC,IAAAA,UAAU,mCAAM,WAAW,EAAjB;AAEH,IAAA,OAAQ,kCAAR,QAAQ,EAAA;AACT,IAAA,MAAO,kCAAP,OAAO,EAAA;AACP,IAAA,UAAY,kCAAZ,YAAY,EAAA;AACb,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEH,IAAA,IAAc,WAAd,cAAc,CAAA;AACC,IAAA,uBAAiD,kCAAjD,iDAAiD,EAAA;AACtD,IAAA,kBAA4C,WAA5C,4CAA4C,CAAA;AACzC,IAAA,KAAqB,WAArB,qBAAqB,CAAA;AACmB,IAAA,iBAAqB,WAArB,qBAAqB,CAAA;AACrD,IAAA,yBAA6B,WAA7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,CAAC,0BAA0B,EAAEoI,QAAQ,CAACG,KAAK,CAAC,EAAE,CAAC,GAAGD,MAAM,GAAG,YAAY,CAAC;SAChF,MAAM;YACL,OAAO;gBACL,CAAC,2BAA2B,EAAED,QAAQ,CAAC,aAAa,CAAC;gBACrD,CAAC,8BAA8B,EAAEA,QAAQ,CAAC,EAAE,CAAC;aAC9C,CAACnF,IAAI,CAAC,EAAE,CAAC,CAAC;SACZ;KACF,CAAC,CACDA,IAAI,CAAC,EAAE,CAAC,AAAC;IAEZ,MAAMsF,QAAQ,GAAGR,MAAM,CAACE,MAAM,CAAC,CAACC,KAAK,GAAKA,KAAK,CAACtG,IAAI,KAAK,IAAI;IAAA,CAAC,AAAC;IAE/D,MAAM4G,OAAO,GAAGxI,SAAS,GACrB,CAAC,aAAa,EAAEA,SAAS,CAAC,iBAAiB,CAAC,GAC5CuI,QAAQ,CACLxF,GAAG,CAAC,CAAC,EAAEqF,QAAQ,CAAA,EAAE,GAAK;QACrB,OAAO,CAAC,cAAc,EAAEA,QAAQ,CAAC,iBAAiB,CAAC,CAAC;KACrD,CAAC,CACDnF,IAAI,CAAC,EAAE,CAAC,AAAC;IAEhB,OAAOtD,QAAQ,CACZ8I,OAAO,CAAC,SAAS,EAAE,CAAC,EAAET,WAAW,CAAC,OAAO,CAAC,CAAC,CAC3CS,OAAO,CAAC,SAAS,EAAE,CAAC,EAAED,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC;CAC9C"}
@@ -27,27 +27,30 @@ class ExpoInspectorProxy {
27
27
  this.processRequest = this.processRequest.bind(this);
28
28
  }
29
29
  /**
30
- * Initialize the server address from the metro server.
31
- * This is required to properly reference sourcemaps for the debugger.
32
- */ setServerAddress(server) {
33
- const addressInfo = server.address();
30
+ * Normalize the server address for clients to connect to.
31
+ * @param addressInfo the server address returned by `HttpServer.address()` or `HttpsServer.address()`.
32
+ * @returns "address:port"
33
+ */ static normalizeServerAddress(addressInfo) {
34
34
  if (typeof addressInfo === "string") {
35
35
  throw new Error(`Inspector proxy could not resolve the server address, got "${addressInfo}"`);
36
36
  } else if (addressInfo === null) {
37
37
  throw new Error(`Inspector proxy could not resolve the server address, got "null"`);
38
38
  }
39
- const { address , port , family } = addressInfo;
40
- if (family === "IPv6") {
41
- this.metroProxy._serverAddressWithPort = `[${address != null ? address : "::1"}]:${port}`;
39
+ let address = addressInfo.address;
40
+ if (addressInfo.family === "IPv6") {
41
+ address = address === "::" ? `[::1]` : `[${address}]`;
42
42
  } else {
43
- this.metroProxy._serverAddressWithPort = `${address != null ? address : "localhost"}:${port}`;
43
+ address = address === "0.0.0.0" ? "localhost" : address;
44
44
  }
45
+ return `${address}:${addressInfo.port}`;
45
46
  }
46
47
  /** @see https://chromedevtools.github.io/devtools-protocol/#endpoints */ processRequest(req, res, next) {
47
48
  this.metroProxy.processRequest(req, res, next);
48
49
  }
49
50
  createWebSocketListeners(server) {
50
- this.setServerAddress(server);
51
+ // Initialize the server address from the metro server.
52
+ // This is required to properly reference sourcemaps for the debugger.
53
+ this.metroProxy._serverAddressWithPort = ExpoInspectorProxy.normalizeServerAddress(server.address());
51
54
  return {
52
55
  [WS_DEVICE_URL]: this.createDeviceWebSocketServer(),
53
56
  [WS_DEBUGGER_URL]: this.createDebuggerWebSocketServer()
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../src/start/server/metro/inspector-proxy/proxy.ts"],"sourcesContent":["import type { Server as HttpServer, IncomingMessage, ServerResponse } from 'http';\nimport type { Server as HttpsServer } from 'https';\nimport type { InspectorProxy as MetroProxy, Device as MetroDevice } from 'metro-inspector-proxy';\nimport { parse } from 'url';\nimport WS, { Server as WSServer } from 'ws';\n\nimport { Log } from '../../../../log';\n\nconst WS_DEVICE_URL = '/inspector/device';\nconst WS_DEBUGGER_URL = '/inspector/debug';\nconst WS_GENERIC_ERROR_STATUS = 1011;\n\nconst debug = require('debug')('expo:metro:inspector-proxy:proxy') as typeof console.log;\n\n// This is a workaround for `ConstructorType` not working on dynamically generated classes\ntype Instantiatable<Instance> = new (...args: any) => Instance;\n\nexport class ExpoInspectorProxy<D extends MetroDevice = MetroDevice> {\n constructor(\n public readonly metroProxy: MetroProxy,\n private DeviceClass: Instantiatable<D>,\n public readonly devices: Map<string, D> = new Map()\n ) {\n // monkey-patch the device list to expose it within the metro inspector\n // See https://github.com/facebook/metro/pull/991\n // @ts-expect-error - Device ID is changing from `number` to `string`\n this.metroProxy._devices = this.devices;\n\n // force httpEndpointMiddleware to be bound to this proxy instance\n this.processRequest = this.processRequest.bind(this);\n }\n\n /**\n * Initialize the server address from the metro server.\n * This is required to properly reference sourcemaps for the debugger.\n */\n private setServerAddress(server: HttpServer | HttpsServer) {\n const addressInfo = server.address();\n\n if (typeof addressInfo === 'string') {\n throw new Error(`Inspector proxy could not resolve the server address, got \"${addressInfo}\"`);\n } else if (addressInfo === null) {\n throw new Error(`Inspector proxy could not resolve the server address, got \"null\"`);\n }\n\n const { address, port, family } = addressInfo;\n\n if (family === 'IPv6') {\n this.metroProxy._serverAddressWithPort = `[${address ?? '::1'}]:${port}`;\n } else {\n this.metroProxy._serverAddressWithPort = `${address ?? 'localhost'}:${port}`;\n }\n }\n\n /** @see https://chromedevtools.github.io/devtools-protocol/#endpoints */\n public processRequest(req: IncomingMessage, res: ServerResponse, next: (error?: Error) => any) {\n this.metroProxy.processRequest(req, res, next);\n }\n\n public createWebSocketListeners(server: HttpServer | HttpsServer): Record<string, WSServer> {\n this.setServerAddress(server);\n\n return {\n [WS_DEVICE_URL]: this.createDeviceWebSocketServer(),\n [WS_DEBUGGER_URL]: this.createDebuggerWebSocketServer(),\n };\n }\n\n private createDeviceWebSocketServer() {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n\n // See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L157\n wss.on('connection', (socket, request) => {\n try {\n const fallbackDeviceId = String(this.metroProxy._deviceCounter++);\n const { deviceId: newDeviceId, deviceName, appName } = getDeviceInfo(request.url);\n\n const deviceId = newDeviceId ?? fallbackDeviceId;\n\n const oldDevice = this.devices.get(deviceId);\n const newDevice = new this.DeviceClass(\n deviceId,\n deviceName,\n appName,\n socket,\n this.metroProxy._projectRoot\n );\n\n if (oldDevice) {\n debug('Device reconnected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n // See: https://github.com/facebook/metro/pull/991\n // @ts-expect-error - Newly introduced method coming to metro-inspector-proxy soon\n oldDevice.handleDuplicateDeviceConnection(newDevice);\n } else {\n debug('New device connected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n }\n\n this.devices.set(deviceId, newDevice);\n\n socket.on('close', () => {\n if (this.devices.get(deviceId) === newDevice) {\n this.devices.delete(deviceId);\n debug('Device disconnected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n }\n });\n } catch (error: unknown) {\n let message = '';\n\n debug('Could not establish a connection to on-device debugger:', error);\n\n if (error instanceof Error) {\n message = error.toString();\n Log.error('Failed to create a socket connection to on-device debugger (Hermes engine).');\n Log.exception(error);\n } else {\n Log.error(\n 'Failed to create a socket connection to on-device debugger (Hermes engine), unknown error.'\n );\n }\n\n socket.close(WS_GENERIC_ERROR_STATUS, message || 'Unknown error');\n }\n });\n\n return wss;\n }\n\n private createDebuggerWebSocketServer() {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n\n // See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L193\n wss.on('connection', (socket, request) => {\n try {\n const { deviceId, pageId, debuggerType } = getDebuggerInfo(request.url);\n if (!deviceId || !pageId) {\n // TODO(cedric): change these errors to proper error types\n throw new Error(`Missing \"device\" and/or \"page\" IDs in query parameters`);\n }\n\n const device = this.devices.get(deviceId);\n if (!device) {\n // TODO(cedric): change these errors to proper error types\n throw new Error(`Device with ID \"${deviceId}\" not found.`);\n }\n\n debug('New debugger connected: device=%s, app=%s', device._name, device._app);\n\n // @ts-expect-error The `handleDebuggerConnectionWithType` is part of our device implementation, not Metro's device\n if (debuggerType && typeof device.handleDebuggerConnectionWithType === 'function') {\n // @ts-expect-error The `handleDebuggerConnectionWithType` is part of our device implementation, not Metro's device\n device.handleDebuggerConnectionWithType(socket, pageId, debuggerType);\n } else {\n device.handleDebuggerConnection(socket, pageId);\n }\n\n socket.on('close', () => {\n debug('Debugger disconnected: device=%s, app=%s', device._name, device._app);\n });\n } catch (error: unknown) {\n let message = '';\n\n debug('Could not establish a connection to debugger:', error);\n\n if (error instanceof Error) {\n message = error.toString();\n Log.error('Failed to create a socket connection to the debugger.');\n Log.exception(error);\n } else {\n Log.error('Failed to create a socket connection to the debugger, unkown error.');\n }\n\n socket.close(WS_GENERIC_ERROR_STATUS, message || 'Unknown error');\n }\n });\n\n return wss;\n }\n}\n\nfunction asString(value: string | string[] = ''): string {\n return Array.isArray(value) ? value.join() : value;\n}\n\nfunction getDeviceInfo(url: IncomingMessage['url']) {\n const { query } = parse(url ?? '', true);\n return {\n deviceId: asString(query.device) || undefined,\n deviceName: asString(query.name) || 'Unknown device name',\n appName: asString(query.app) || 'Unknown app name',\n };\n}\n\nfunction getDebuggerInfo(url: IncomingMessage['url']) {\n const { query } = parse(url ?? '', true);\n return {\n deviceId: asString(query.device),\n pageId: asString(query.page),\n debuggerType: asString(query.type) ?? undefined,\n };\n}\n"],"names":["WS_DEVICE_URL","WS_DEBUGGER_URL","WS_GENERIC_ERROR_STATUS","debug","require","ExpoInspectorProxy","constructor","metroProxy","DeviceClass","devices","Map","_devices","processRequest","bind","setServerAddress","server","addressInfo","address","Error","port","family","_serverAddressWithPort","req","res","next","createWebSocketListeners","createDeviceWebSocketServer","createDebuggerWebSocketServer","wss","WS","Server","noServer","perMessageDeflate","on","socket","request","fallbackDeviceId","String","_deviceCounter","deviceId","newDeviceId","deviceName","appName","getDeviceInfo","url","oldDevice","get","newDevice","_projectRoot","handleDuplicateDeviceConnection","set","delete","error","message","toString","Log","exception","close","pageId","debuggerType","getDebuggerInfo","device","_name","_app","handleDebuggerConnectionWithType","handleDebuggerConnection","asString","value","Array","isArray","join","query","parse","undefined","name","app","page","type"],"mappings":"AAAA;;;;AAGsB,IAAA,IAAK,WAAL,KAAK,CAAA;AACY,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAEvB,IAAA,IAAiB,WAAjB,iBAAiB,CAAA;;;;;;AAErC,MAAMA,aAAa,GAAG,mBAAmB,AAAC;AAC1C,MAAMC,eAAe,GAAG,kBAAkB,AAAC;AAC3C,MAAMC,uBAAuB,GAAG,IAAI,AAAC;AAErC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,kCAAkC,CAAC,AAAsB,AAAC;AAKlF,MAAMC,kBAAkB;IAC7BC,YACkBC,UAAsB,EAC9BC,WAA8B,EACtBC,OAAuB,GAAG,IAAIC,GAAG,EAAE,CACnD;aAHgBH,UAAsB,GAAtBA,UAAsB;aAC9BC,WAA8B,GAA9BA,WAA8B;aACtBC,OAAuB,GAAvBA,OAAuB;QAEvC,uEAAuE;QACvE,iDAAiD;QACjD,qEAAqE;QACrE,IAAI,CAACF,UAAU,CAACI,QAAQ,GAAG,IAAI,CAACF,OAAO,CAAC;QAExC,kEAAkE;QAClE,IAAI,CAACG,cAAc,GAAG,IAAI,CAACA,cAAc,CAACC,IAAI,CAAC,IAAI,CAAC,CAAC;KACtD;IAED;;;KAGG,CACH,AAAQC,gBAAgB,CAACC,MAAgC,EAAE;QACzD,MAAMC,WAAW,GAAGD,MAAM,CAACE,OAAO,EAAE,AAAC;QAErC,IAAI,OAAOD,WAAW,KAAK,QAAQ,EAAE;YACnC,MAAM,IAAIE,KAAK,CAAC,CAAC,2DAA2D,EAAEF,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;SAC/F,MAAM,IAAIA,WAAW,KAAK,IAAI,EAAE;YAC/B,MAAM,IAAIE,KAAK,CAAC,CAAC,gEAAg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F,KAAK,CAAC,GAAGA,KAAK,CAACG,IAAI,EAAE,GAAGH,KAAK,CAAC;CACpD;AAED,SAASxB,aAAa,CAACC,GAA2B,EAAE;IAClD,MAAM,EAAE2B,KAAK,CAAA,EAAE,GAAGC,CAAAA,GAAAA,IAAK,AAAiB,CAAA,MAAjB,CAAC5B,GAAG,WAAHA,GAAG,GAAI,EAAE,EAAE,IAAI,CAAC,AAAC;IACzC,OAAO;QACLL,QAAQ,EAAE2B,QAAQ,CAACK,KAAK,CAACV,MAAM,CAAC,IAAIY,SAAS;QAC7ChC,UAAU,EAAEyB,QAAQ,CAACK,KAAK,CAACG,IAAI,CAAC,IAAI,qBAAqB;QACzDhC,OAAO,EAAEwB,QAAQ,CAACK,KAAK,CAACI,GAAG,CAAC,IAAI,kBAAkB;KACnD,CAAC;CACH;AAED,SAASf,eAAe,CAAChB,GAA2B,EAAE;IACpD,MAAM,EAAE2B,KAAK,CAAA,EAAE,GAAGC,CAAAA,GAAAA,IAAK,AAAiB,CAAA,MAAjB,CAAC5B,GAAG,WAAHA,GAAG,GAAI,EAAE,EAAE,IAAI,CAAC,AAAC;QAIzBsB,GAAoB;IAHpC,OAAO;QACL3B,QAAQ,EAAE2B,QAAQ,CAACK,KAAK,CAACV,MAAM,CAAC;QAChCH,MAAM,EAAEQ,QAAQ,CAACK,KAAK,CAACK,IAAI,CAAC;QAC5BjB,YAAY,EAAEO,CAAAA,GAAoB,GAApBA,QAAQ,CAACK,KAAK,CAACM,IAAI,CAAC,YAApBX,GAAoB,GAAIO,SAAS;KAChD,CAAC;CACH"}
1
+ {"version":3,"sources":["../../../../../../src/start/server/metro/inspector-proxy/proxy.ts"],"sourcesContent":["import type { Server as HttpServer, IncomingMessage, ServerResponse } from 'http';\nimport type { Server as HttpsServer } from 'https';\nimport type { InspectorProxy as MetroProxy, Device as MetroDevice } from 'metro-inspector-proxy';\nimport { parse } from 'url';\nimport WS, { Server as WSServer } from 'ws';\n\nimport { Log } from '../../../../log';\n\nconst WS_DEVICE_URL = '/inspector/device';\nconst WS_DEBUGGER_URL = '/inspector/debug';\nconst WS_GENERIC_ERROR_STATUS = 1011;\n\nconst debug = require('debug')('expo:metro:inspector-proxy:proxy') as typeof console.log;\n\n// This is a workaround for `ConstructorType` not working on dynamically generated classes\ntype Instantiatable<Instance> = new (...args: any) => Instance;\n\nexport class ExpoInspectorProxy<D extends MetroDevice = MetroDevice> {\n constructor(\n public readonly metroProxy: MetroProxy,\n private DeviceClass: Instantiatable<D>,\n public readonly devices: Map<string, D> = new Map()\n ) {\n // monkey-patch the device list to expose it within the metro inspector\n // See https://github.com/facebook/metro/pull/991\n // @ts-expect-error - Device ID is changing from `number` to `string`\n this.metroProxy._devices = this.devices;\n\n // force httpEndpointMiddleware to be bound to this proxy instance\n this.processRequest = this.processRequest.bind(this);\n }\n\n /**\n * Normalize the server address for clients to connect to.\n * @param addressInfo the server address returned by `HttpServer.address()` or `HttpsServer.address()`.\n * @returns \"address:port\"\n */\n public static normalizeServerAddress(addressInfo: ReturnType<HttpServer['address']>): string {\n if (typeof addressInfo === 'string') {\n throw new Error(`Inspector proxy could not resolve the server address, got \"${addressInfo}\"`);\n } else if (addressInfo === null) {\n throw new Error(`Inspector proxy could not resolve the server address, got \"null\"`);\n }\n\n let address = addressInfo.address;\n if (addressInfo.family === 'IPv6') {\n address = address === '::' ? `[::1]` : `[${address}]`;\n } else {\n address = address === '0.0.0.0' ? 'localhost' : address;\n }\n return `${address}:${addressInfo.port}`;\n }\n\n /** @see https://chromedevtools.github.io/devtools-protocol/#endpoints */\n public processRequest(req: IncomingMessage, res: ServerResponse, next: (error?: Error) => any) {\n this.metroProxy.processRequest(req, res, next);\n }\n\n public createWebSocketListeners(server: HttpServer | HttpsServer): Record<string, WSServer> {\n // Initialize the server address from the metro server.\n // This is required to properly reference sourcemaps for the debugger.\n this.metroProxy._serverAddressWithPort = ExpoInspectorProxy.normalizeServerAddress(\n server.address()\n );\n\n return {\n [WS_DEVICE_URL]: this.createDeviceWebSocketServer(),\n [WS_DEBUGGER_URL]: this.createDebuggerWebSocketServer(),\n };\n }\n\n private createDeviceWebSocketServer() {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n\n // See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L157\n wss.on('connection', (socket, request) => {\n try {\n const fallbackDeviceId = String(this.metroProxy._deviceCounter++);\n const { deviceId: newDeviceId, deviceName, appName } = getDeviceInfo(request.url);\n\n const deviceId = newDeviceId ?? fallbackDeviceId;\n\n const oldDevice = this.devices.get(deviceId);\n const newDevice = new this.DeviceClass(\n deviceId,\n deviceName,\n appName,\n socket,\n this.metroProxy._projectRoot\n );\n\n if (oldDevice) {\n debug('Device reconnected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n // See: https://github.com/facebook/metro/pull/991\n // @ts-expect-error - Newly introduced method coming to metro-inspector-proxy soon\n oldDevice.handleDuplicateDeviceConnection(newDevice);\n } else {\n debug('New device connected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n }\n\n this.devices.set(deviceId, newDevice);\n\n socket.on('close', () => {\n if (this.devices.get(deviceId) === newDevice) {\n this.devices.delete(deviceId);\n debug('Device disconnected: device=%s, app=%s, id=%s', deviceName, appName, deviceId);\n }\n });\n } catch (error: unknown) {\n let message = '';\n\n debug('Could not establish a connection to on-device debugger:', error);\n\n if (error instanceof Error) {\n message = error.toString();\n Log.error('Failed to create a socket connection to on-device debugger (Hermes engine).');\n Log.exception(error);\n } else {\n Log.error(\n 'Failed to create a socket connection to on-device debugger (Hermes engine), unknown error.'\n );\n }\n\n socket.close(WS_GENERIC_ERROR_STATUS, message || 'Unknown error');\n }\n });\n\n return wss;\n }\n\n private createDebuggerWebSocketServer() {\n const wss = new WS.Server({\n noServer: true,\n perMessageDeflate: false,\n });\n\n // See: https://github.com/facebook/metro/blob/eeb211fdcfdcb9e7f8a51721bd0f48bc7d0d211f/packages/metro-inspector-proxy/src/InspectorProxy.js#L193\n wss.on('connection', (socket, request) => {\n try {\n const { deviceId, pageId, debuggerType } = getDebuggerInfo(request.url);\n if (!deviceId || !pageId) {\n // TODO(cedric): change these errors to proper error types\n throw new Error(`Missing \"device\" and/or \"page\" IDs in query parameters`);\n }\n\n const device = this.devices.get(deviceId);\n if (!device) {\n // TODO(cedric): change these errors to proper error types\n throw new Error(`Device with ID \"${deviceId}\" not found.`);\n }\n\n debug('New debugger connected: device=%s, app=%s', device._name, device._app);\n\n // @ts-expect-error The `handleDebuggerConnectionWithType` is part of our device implementation, not Metro's device\n if (debuggerType && typeof device.handleDebuggerConnectionWithType === 'function') {\n // @ts-expect-error The `handleDebuggerConnectionWithType` is part of our device implementation, not Metro's device\n device.handleDebuggerConnectionWithType(socket, pageId, debuggerType);\n } else {\n device.handleDebuggerConnection(socket, pageId);\n }\n\n socket.on('close', () => {\n debug('Debugger disconnected: device=%s, app=%s', device._name, device._app);\n });\n } catch (error: unknown) {\n let message = '';\n\n debug('Could not establish a connection to debugger:', error);\n\n if (error instanceof Error) {\n message = error.toString();\n Log.error('Failed to create a socket connection to the debugger.');\n Log.exception(error);\n } else {\n Log.error('Failed to create a socket connection to the debugger, unkown error.');\n }\n\n socket.close(WS_GENERIC_ERROR_STATUS, message || 'Unknown error');\n }\n });\n\n return wss;\n }\n}\n\nfunction asString(value: string | string[] = ''): string {\n return Array.isArray(value) ? value.join() : value;\n}\n\nfunction getDeviceInfo(url: IncomingMessage['url']) {\n const { query } = parse(url ?? '', true);\n return {\n deviceId: asString(query.device) || undefined,\n deviceName: asString(query.name) || 'Unknown device name',\n appName: asString(query.app) || 'Unknown app name',\n };\n}\n\nfunction getDebuggerInfo(url: IncomingMessage['url']) {\n const { query } = parse(url ?? '', true);\n return {\n deviceId: asString(query.device),\n pageId: asString(query.page),\n debuggerType: asString(query.type) ?? undefined,\n };\n}\n"],"names":["WS_DEVICE_URL","WS_DEBUGGER_URL","WS_GENERIC_ERROR_STATUS","debug","require","ExpoInspectorProxy","constructor","metroProxy","DeviceClass","devices","Map","_devices","processRequest","bind","normalizeServerAddress","addressInfo","Error","address","family","port","req","res","next","createWebSocketListeners","server","_serverAddressWithPort","createDeviceWebSocketServer","createDebuggerWebSocketServer","wss","WS","Server","noServer","perMessageDeflate","on","socket","request","fallbackDeviceId","String","_deviceCounter","deviceId","newDeviceId","deviceName","appName","getDeviceInfo","url","oldDevice","get","newDevice","_projectRoot","handleDuplicateDeviceConnection","set","delete","error","message","toString","Log","exception","close","pageId","debuggerType","getDebuggerInfo","device","_name","_app","handleDebuggerConnectionWithType","handleDebuggerConnection","asString","value","Array","isArray","join","query","parse","undefined","name","app","page","type"],"mappings":"AAAA;;;;AAGsB,IAAA,IAAK,WAAL,KAAK,CAAA;AACY,IAAA,GAAI,kCAAJ,IAAI,EAAA;AAEvB,IAAA,IAAiB,WAAjB,iBAAiB,CAAA;;;;;;AAErC,MAAMA,aAAa,GAAG,mBAAmB,AAAC;AAC1C,MAAMC,eAAe,GAAG,kBAAkB,AAAC;AAC3C,MAAMC,uBAAuB,GAAG,IAAI,AAAC;AAErC,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,kCAAkC,CAAC,AAAsB,AAAC;AAKlF,MAAMC,kBAAkB;IAC7BC,YACkBC,UAAsB,EAC9BC,WAA8B,EACtBC,OAAuB,GAAG,IAAIC,GAAG,EAAE,CACnD;aAHgBH,UAAsB,GAAtBA,UAAsB;aAC9BC,WAA8B,GAA9BA,WAA8B;aACtBC,OAAuB,GAAvBA,OAAuB;QAEvC,uEAAuE;QACvE,iDAAiD;QACjD,qEAAqE;QACrE,IAAI,CAACF,UAAU,CAACI,QAAQ,GAAG,IAAI,CAACF,OAAO,CAAC;QAExC,kEAAkE;QAClE,IAAI,CAACG,cAAc,GAAG,IAAI,CAACA,cAAc,CAACC,IAAI,CAAC,IAAI,CAAC,CAAC;KACtD;IAED;;;;KAIG,CACH,OAAcC,sBAAs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,YAApBX,GAAoB,GAAIO,SAAS;KAChD,CAAC;CACH"}
@@ -9,7 +9,7 @@ function _interopRequireDefault(obj) {
9
9
  default: obj
10
10
  };
11
11
  }
12
- const debug = require("debug")("expo:start:server:metro:waitForTypescript");
12
+ const debug = require("debug")("expo:start:server:metro:metroWatchTypeScriptFiles");
13
13
  function metroWatchTypeScriptFiles({ metro , server , projectRoot , callback , tsconfig =false , throttle =false , eventTypes =[
14
14
  "add",
15
15
  "change",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/server/metro/metroWatchTypeScriptFiles.ts"],"sourcesContent":["import path from 'path';\n\nimport type { ServerLike } from '../BundlerDevServer';\n\nconst debug = require('debug')('expo:start:server:metro:waitForTypescript') as typeof console.log;\n\nexport interface MetroWatchTypeScriptFilesOptions {\n projectRoot: string;\n metro: import('metro').Server;\n server: ServerLike;\n /* Include tsconfig.json in the watcher */\n tsconfig?: boolean;\n callback: (event: WatchEvent) => void;\n /* Array of eventTypes to watch. Defaults to all events */\n eventTypes?: string[];\n /* Throlle the callback. When true and a group of events are recieved, callback it will only be called with the\n * first event */\n throttle?: boolean;\n}\n\ninterface WatchEvent {\n filePath: string;\n metadata?: {\n type: 'f' | 'd' | 'l'; // Regular file / Directory / Symlink\n } | null;\n type: string;\n}\n\n/**\n * Use the native file watcher / Metro ruleset to detect if a\n * TypeScript file is added to the project during development.\n */\nexport function metroWatchTypeScriptFiles({\n metro,\n server,\n projectRoot,\n callback,\n tsconfig = false,\n throttle = false,\n eventTypes = ['add', 'change', 'delete'],\n}: MetroWatchTypeScriptFilesOptions): () => void {\n const watcher = metro.getBundler().getBundler().getWatcher();\n\n const tsconfigPath = path.join(projectRoot, 'tsconfig.json');\n\n const listener = ({ eventsQueue }: { eventsQueue: WatchEvent[] }) => {\n for (const event of eventsQueue) {\n if (\n eventTypes.includes(event.type) &&\n event.metadata?.type !== 'd' &&\n // We need to ignore node_modules because Metro will add all of the files in node_modules to the watcher.\n !/node_modules/.test(event.filePath) &&\n // Ignore declaration files\n !/\\.d\\.ts$/.test(event.filePath)\n ) {\n const { filePath } = event;\n // Is TypeScript?\n if (\n // If the user adds a TypeScript file to the observable files in their project.\n /\\.tsx?$/.test(filePath) ||\n // Or if the user adds a tsconfig.json file to the project root.\n (tsconfig && filePath === tsconfigPath)\n ) {\n debug('Detected TypeScript file changed in the project: ', filePath);\n callback(event);\n\n if (throttle) {\n return;\n }\n }\n }\n }\n };\n\n debug('Waiting for TypeScript files to be added to the project...');\n watcher.addListener('change', listener);\n watcher.addListener('add', listener);\n\n const off = () => {\n watcher.removeListener('change', listener);\n watcher.removeListener('add', listener);\n };\n\n server.addListener?.('close', off);\n return off;\n}\n"],"names":["metroWatchTypeScriptFiles","debug","require","metro","server","projectRoot","callback","tsconfig","throttle","eventTypes","watcher","getBundler","getWatcher","tsconfigPath","path","join","listener","eventsQueue","event","includes","type","metadata","test","filePath","addListener","off","removeListener"],"mappings":"AAAA;;;;QAgCgBA,yBAAyB,GAAzBA,yBAAyB;AAhCxB,IAAA,KAAM,kCAAN,MAAM,EAAA;;;;;;AAIvB,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,2CAA2C,CAAC,AAAsB,AAAC;AA4B3F,SAASF,yBAAyB,CAAC,EACxCG,KAAK,CAAA,EACLC,MAAM,CAAA,EACNC,WAAW,CAAA,EACXC,QAAQ,CAAA,EACRC,QAAQ,EAAG,KAAK,CAAA,EAChBC,QAAQ,EAAG,KAAK,CAAA,EAChBC,UAAU,EAAG;IAAC,KAAK;IAAE,QAAQ;IAAE,QAAQ;CAAC,CAAA,EACP,EAAc;IAC/C,MAAMC,OAAO,GAAGP,KAAK,CAACQ,UAAU,EAAE,CAACA,UAAU,EAAE,CAACC,UAAU,EAAE,AAAC;IAE7D,MAAMC,YAAY,GAAGC,KAAI,QAAA,CAACC,IAAI,CAACV,WAAW,EAAE,eAAe,CAAC,AAAC;IAE7D,MAAMW,QAAQ,GAAG,CAAC,EAAEC,WAA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W,CAAG,OAAO,EAAEC,GAAG,CAAC,AAnFpC,CAmFqC;IACnC,OAAOA,GAAG,CAAC;CACZ"}
1
+ {"version":3,"sources":["../../../../../src/start/server/metro/metroWatchTypeScriptFiles.ts"],"sourcesContent":["import path from 'path';\n\nimport type { ServerLike } from '../BundlerDevServer';\n\nconst debug = require('debug')(\n 'expo:start:server:metro:metroWatchTypeScriptFiles'\n) as typeof console.log;\n\nexport interface MetroWatchTypeScriptFilesOptions {\n projectRoot: string;\n metro: import('metro').Server;\n server: ServerLike;\n /* Include tsconfig.json in the watcher */\n tsconfig?: boolean;\n callback: (event: WatchEvent) => void;\n /* Array of eventTypes to watch. Defaults to all events */\n eventTypes?: string[];\n /* Throlle the callback. When true and a group of events are recieved, callback it will only be called with the\n * first event */\n throttle?: boolean;\n}\n\ninterface WatchEvent {\n filePath: string;\n metadata?: {\n type: 'f' | 'd' | 'l'; // Regular file / Directory / Symlink\n } | null;\n type: string;\n}\n\n/**\n * Use the native file watcher / Metro ruleset to detect if a\n * TypeScript file is added to the project during development.\n */\nexport function metroWatchTypeScriptFiles({\n metro,\n server,\n projectRoot,\n callback,\n tsconfig = false,\n throttle = false,\n eventTypes = ['add', 'change', 'delete'],\n}: MetroWatchTypeScriptFilesOptions): () => void {\n const watcher = metro.getBundler().getBundler().getWatcher();\n\n const tsconfigPath = path.join(projectRoot, 'tsconfig.json');\n\n const listener = ({ eventsQueue }: { eventsQueue: WatchEvent[] }) => {\n for (const event of eventsQueue) {\n if (\n eventTypes.includes(event.type) &&\n event.metadata?.type !== 'd' &&\n // We need to ignore node_modules because Metro will add all of the files in node_modules to the watcher.\n !/node_modules/.test(event.filePath) &&\n // Ignore declaration files\n !/\\.d\\.ts$/.test(event.filePath)\n ) {\n const { filePath } = event;\n // Is TypeScript?\n if (\n // If the user adds a TypeScript file to the observable files in their project.\n /\\.tsx?$/.test(filePath) ||\n // Or if the user adds a tsconfig.json file to the project root.\n (tsconfig && filePath === tsconfigPath)\n ) {\n debug('Detected TypeScript file changed in the project: ', filePath);\n callback(event);\n\n if (throttle) {\n return;\n }\n }\n }\n }\n };\n\n debug('Waiting for TypeScript files to be added to the project...');\n watcher.addListener('change', listener);\n watcher.addListener('add', listener);\n\n const off = () => {\n watcher.removeListener('change', listener);\n watcher.removeListener('add', listener);\n };\n\n server.addListener?.('close', off);\n return off;\n}\n"],"names":["metroWatchTypeScriptFiles","debug","require","metro","server","projectRoot","callback","tsconfig","throttle","eventTypes","watcher","getBundler","getWatcher","tsconfigPath","path","join","listener","eventsQueue","event","includes","type","metadata","test","filePath","addListener","off","removeListener"],"mappings":"AAAA;;;;QAkCgBA,yBAAyB,GAAzBA,yBAAyB;AAlCxB,IAAA,KAAM,kCAAN,MAAM,EAAA;;;;;;AAIvB,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAC5B,mDAAmD,CACpD,AAAsB,AAAC;AA4BjB,SAASF,yBAAyB,CAAC,EACxCG,KAAK,CAAA,EACLC,MAAM,CAAA,EACNC,WAAW,CAAA,EACXC,QAAQ,CAAA,EACRC,QAAQ,EAAG,KAAK,CAAA,EAChBC,QAAQ,EAAG,KAAK,CAAA,EAChBC,UAAU,EAAG;IAAC,KAAK;IAAE,QAAQ;IAAE,QAAQ;CAAC,CAAA,EACP,EAAc;IAC/C,MAAMC,OAAO,GAAGP,KAAK,CAACQ,UAAU,EAAE,CAACA,UAAU,EAAE,CAACC,UAAU,EAAE,AAAC;IAE7D,MAAMC,YAAY,GAAGC,KAAI,QAAA,CAACC,IAAI,CAACV,WAAW,EAAE,eAAe,CAAC,AAAC;IAE7D,MAAMW,QAAQ,GAAG,CAAC,EAAEC,WAAW,CAAA,EAAiC,GAAK;QACnE,KAAK,MAAMC,KAAK,IAAID,WAAW,CAAE;gBAG7BC,GAAc;YAFhB,IACET,UAAU,CAACU,QAAQ,CAACD,KAAK,CAACE,IAAI,CAAC,IAC/BF,CAAAA,CAAAA,GAAc,GAAdA,KAAK,CAACG,QAAQ,SAAM,G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