@expo/cli 57.0.31 → 57.0.33

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 (75) hide show
  1. package/build/bin/cli +1 -1
  2. package/build/src/events/index.js +1 -1
  3. package/build/src/export/compileHermesArtifacts.js +28 -0
  4. package/build/src/export/compileHermesArtifacts.js.map +1 -0
  5. package/build/src/export/embed/exportEmbedAsync.js +4 -0
  6. package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
  7. package/build/src/export/exportApp.js +9 -5
  8. package/build/src/export/exportApp.js.map +1 -1
  9. package/build/src/export/exportDomComponents.js +5 -11
  10. package/build/src/export/exportDomComponents.js.map +1 -1
  11. package/build/src/prebuild/prebuildAsync.js +3 -2
  12. package/build/src/prebuild/prebuildAsync.js.map +1 -1
  13. package/build/src/run/ensureNativeProject.js +3 -2
  14. package/build/src/run/ensureNativeProject.js.map +1 -1
  15. package/build/src/run/ios/appleDevice/ClientManager.js +11 -6
  16. package/build/src/run/ios/appleDevice/ClientManager.js.map +1 -1
  17. package/build/src/run/ios/runIosAsync.js +12 -4
  18. package/build/src/run/ios/runIosAsync.js.map +1 -1
  19. package/build/src/start/interface/cliExtensionMenuItemHandler.js.map +1 -1
  20. package/build/src/start/interface/commandsTable.js.map +1 -1
  21. package/build/src/start/interface/createDevToolsMenuItems.js.map +1 -1
  22. package/build/src/start/interface/interactiveActions.js.map +1 -1
  23. package/build/src/start/platforms/ios/devicectl.js +2 -5
  24. package/build/src/start/platforms/ios/devicectl.js.map +1 -1
  25. package/build/src/start/server/BundlerDevServer.js +6 -9
  26. package/build/src/start/server/BundlerDevServer.js.map +1 -1
  27. package/build/src/start/server/DevServerManager.js +1 -1
  28. package/build/src/start/server/DevServerManager.js.map +1 -1
  29. package/build/src/start/server/UrlCreator.js +10 -4
  30. package/build/src/start/server/UrlCreator.js.map +1 -1
  31. package/build/src/start/server/{DevToolsPlugin.js → devtools/DevToolsPlugin.js} +14 -5
  32. package/build/src/start/server/devtools/DevToolsPlugin.js.map +1 -0
  33. package/build/src/start/server/devtools/DevToolsPlugin.schema.js +195 -0
  34. package/build/src/start/server/devtools/DevToolsPlugin.schema.js.map +1 -0
  35. package/build/src/start/server/{DevToolsPluginCliExtensionExecutor.js → devtools/DevToolsPluginCliExtensionExecutor.js} +1 -1
  36. package/build/src/start/server/devtools/DevToolsPluginCliExtensionExecutor.js.map +1 -0
  37. package/build/src/start/server/{DevToolsPluginCliExtensionResults.js → devtools/DevToolsPluginCliExtensionResults.js} +24 -12
  38. package/build/src/start/server/devtools/DevToolsPluginCliExtensionResults.js.map +1 -0
  39. package/build/src/start/server/{DevToolsPluginManager.js → devtools/DevToolsPluginManager.js} +2 -2
  40. package/build/src/start/server/devtools/DevToolsPluginManager.js.map +1 -0
  41. package/build/src/start/server/devtools/DevToolsPluginServerHelpers.js.map +1 -0
  42. package/build/src/start/server/{MCP.js → mcp/MCP.js} +25 -15
  43. package/build/src/start/server/mcp/MCP.js.map +1 -0
  44. package/build/src/start/server/{MCPDevToolsPluginCLIExtensions.js → mcp/MCPDevToolsPluginCLIExtensions.js} +14 -27
  45. package/build/src/start/server/mcp/MCPDevToolsPluginCLIExtensions.js.map +1 -0
  46. package/build/src/start/server/{createMCPDevToolsExtensionSchema.js → mcp/createMCPDevToolsExtensionSchema.js} +8 -15
  47. package/build/src/start/server/mcp/createMCPDevToolsExtensionSchema.js.map +1 -0
  48. package/build/src/start/server/metro/MetroBundlerDevServer.js +2 -4
  49. package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
  50. package/build/src/start/server/metro/instantiateMetro.js +6 -2
  51. package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
  52. package/build/src/start/server/middleware/DevToolsPluginMiddleware.js +1 -1
  53. package/build/src/start/server/middleware/DevToolsPluginMiddleware.js.map +1 -1
  54. package/build/src/start/server/middleware/metroOptions.js +4 -1
  55. package/build/src/start/server/middleware/metroOptions.js.map +1 -1
  56. package/build/src/start/server/middleware/openHandlers.js +2 -6
  57. package/build/src/start/server/middleware/openHandlers.js.map +1 -1
  58. package/build/src/start/startAsync.js +2 -4
  59. package/build/src/start/startAsync.js.map +1 -1
  60. package/build/src/utils/open.js +47 -31
  61. package/build/src/utils/open.js.map +1 -1
  62. package/build/src/utils/telemetry/clients/FetchClient.js +1 -1
  63. package/build/src/utils/telemetry/utils/context.js +1 -1
  64. package/package.json +25 -21
  65. package/build/src/start/server/DevToolsPlugin.js.map +0 -1
  66. package/build/src/start/server/DevToolsPlugin.schema.js +0 -84
  67. package/build/src/start/server/DevToolsPlugin.schema.js.map +0 -1
  68. package/build/src/start/server/DevToolsPluginCliExtensionExecutor.js.map +0 -1
  69. package/build/src/start/server/DevToolsPluginCliExtensionResults.js.map +0 -1
  70. package/build/src/start/server/DevToolsPluginManager.js.map +0 -1
  71. package/build/src/start/server/DevToolsPluginServerHelpers.js.map +0 -1
  72. package/build/src/start/server/MCP.js.map +0 -1
  73. package/build/src/start/server/MCPDevToolsPluginCLIExtensions.js.map +0 -1
  74. package/build/src/start/server/createMCPDevToolsExtensionSchema.js.map +0 -1
  75. /package/build/src/start/server/{DevToolsPluginServerHelpers.js → devtools/DevToolsPluginServerHelpers.js} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../src/start/platforms/ios/devicectl.ts"],"sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport JsonFile from '@expo/json-file';\nimport type { SpawnOptions, SpawnResult } from '@expo/spawn-async';\nimport spawnAsync from '@expo/spawn-async';\nimport chalk from 'chalk';\nimport { spawn, execSync } from 'child_process';\nimport fs from 'fs';\nimport assert from 'node:assert';\nimport type { Ora } from 'ora';\nimport { EOL } from 'os';\nimport path from 'path';\n\nimport { xcrunAsync } from './xcrun';\nimport { getExpoHomeDirectory } from '../../../api/user/UserSettings';\nimport * as Log from '../../../log';\nimport { createTempFilePath } from '../../../utils/createTempPath';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { ora } from '../../../utils/ora';\nimport { confirmAsync } from '../../../utils/prompts';\n\nconst DEVICE_CTL_EXISTS_PATH = path.join(getExpoHomeDirectory(), 'devicectl-exists');\n\nconst debug = require('debug')('expo:devicectl') as typeof console.log;\n\ntype AnyEnum<T extends string = string> = T | (string & object);\n\ntype DeviceCtlDevice = {\n capabilities: DeviceCtlDeviceCapability[];\n connectionProperties: DeviceCtlConnectionProperties;\n deviceProperties: DeviceCtlDeviceProperties;\n hardwareProperties: DeviceCtlHardwareProperties;\n /** \"A1A1AAA1-0011-1AA1-11A1-10A1111AA11A\" */\n identifier: string;\n visibilityClass: AnyEnum<'default'>;\n};\n\ntype DeviceCtlHardwareProperties = {\n cpuType: DeviceCtlCpuType;\n deviceType: AnyEnum<'iPhone'>;\n /** 1114404411111111 */\n ecid: number;\n /** \"D74AP\" */\n hardwareModel: string;\n /** 512000000000 */\n internalStorageCapacity: number;\n /** true */\n isProductionFused: boolean;\n /** \"iPhone 14 Pro Max\" */\n marketingName: string;\n /** \"iOS\" */\n platform: AnyEnum<'iOS' | 'xrOS'>;\n /** \"iPhone15,3\" */\n productType: AnyEnum<'iPhone13,4' | 'iPhone15,3'>;\n reality: AnyEnum<'physical' | 'simulated'>;\n /** \"X2X1CC1XXX\" */\n serialNumber: string;\n supportedCPUTypes: DeviceCtlCpuType[];\n /** [1] */\n supportedDeviceFamilies: number[];\n thinningProductType: AnyEnum<'iPhone15,3'>;\n /** \"00001110-001111110110101A\" */\n udid: string;\n};\n\ntype DeviceCtlDeviceProperties = {\n /** true */\n bootedFromSnapshot: boolean;\n /** \"com.apple.os.update-AD0CF111ACFF11A11111A76A3D1262AE42A3F56F305AF5AE1135393A7A14A7D1\" */\n bootedSnapshotName: string;\n /** false */\n ddiServicesAvailable: boolean;\n\n developerModeStatus: AnyEnum<'enabled'>;\n /** false */\n hasInternalOSBuild: boolean;\n /** \"Evan's phone\" */\n name: string;\n /** \"21E236\" */\n osBuildUpdate: string;\n /** \"17.4.1\" */\n osVersionNumber: string;\n /** false */\n rootFileSystemIsWritable: boolean;\n};\n\ntype DeviceCtlDeviceCapability =\n | {\n name: AnyEnum;\n featureIdentifier: AnyEnum;\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.connectdevice';\n name: 'Connect to Device';\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.unpairdevice';\n name: 'Unpair Device';\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.acquireusageassertion';\n name: 'Acquire Usage Assertion';\n };\n\ntype DeviceCtlConnectionProperties = {\n authenticationType: AnyEnum<'manualPairing'>;\n isMobileDeviceOnly: boolean;\n /** \"2024-04-20T22:50:04.244Z\" */\n lastConnectionDate: string;\n pairingState: AnyEnum<'paired'>;\n /** [\"00001111-001111110110101A.coredevice.local\", \"A1A1AAA1-0011-1AA1-11A1-10A1111AA11A.coredevice.local\"] */\n potentialHostnames: string[];\n transportType: AnyEnum<'localNetwork' | 'wired'>;\n tunnelState: AnyEnum<'disconnected' | 'unavailable'>;\n tunnelTransportProtocol: AnyEnum<'tcp'>;\n};\n\ntype DeviceCtlCpuType = {\n name: AnyEnum<'arm64e' | 'arm64' | 'arm64_32'>;\n subType: number;\n /** 16777228 */\n type: number;\n};\n\n/** Run a `devicectl` command. */\nexport async function devicectlAsync(\n args: (string | undefined)[],\n options?: SpawnOptions\n): Promise<SpawnResult> {\n try {\n return await xcrunAsync(['devicectl', ...args], options);\n } catch (error: any) {\n if (error instanceof CommandError) {\n throw error;\n }\n if ('stderr' in error) {\n const errorCodes = getDeviceCtlErrorCodes(error.stderr);\n if (errorCodes.includes('Locked')) {\n throw new CommandError('APPLE_DEVICE_LOCKED', 'Device is locked, unlock and try again.');\n }\n }\n throw error;\n }\n}\n\nexport async function getConnectedAppleDevicesAsync() {\n if (!hasDevicectlEverBeenInstalled()) {\n debug('devicectl not found, skipping remote Apple devices.');\n return [];\n }\n\n const tmpPath = createTempFilePath();\n const devices = await devicectlAsync([\n 'list',\n 'devices',\n '--json-output',\n tmpPath,\n // Give two seconds before timing out: between 5 and 9223372036854775807\n '--timeout',\n '5',\n ]);\n debug(devices.stdout);\n const devicesJson = await JsonFile.readAsync(tmpPath);\n\n if (![2, 3, 5].includes((devicesJson as any)?.info?.jsonVersion)) {\n Log.warn(\n 'Unexpected devicectl JSON version output from devicectl. Connecting to physical Apple devices may not work as expected.'\n );\n }\n\n assertDevicesJson(devicesJson);\n\n return (devicesJson.result.devices as DeviceCtlDevice[]).filter(\n (device) => device?.hardwareProperties?.reality !== 'simulated'\n );\n}\n\nfunction assertDevicesJson(\n results: any\n): asserts results is { result: { devices: DeviceCtlDevice[] } } {\n assert(\n results != null && 'result' in results && Array.isArray(results?.result?.devices),\n 'Malformed JSON output from devicectl: ' + JSON.stringify(results, null, 2)\n );\n}\n\nexport async function launchBinaryOnMacAsync(\n bundleId: string,\n appBinaryPath: string\n): Promise<void> {\n const args = ['-b', bundleId, appBinaryPath];\n try {\n await spawnAsync('open', args);\n } catch (error: any) {\n if ('code' in error) {\n if (error.code === 1) {\n throw new CommandError(\n 'MACOS_LAUNCH',\n 'Failed to launch the compatible binary on macOS: open ' +\n args.join(' ') +\n '\\n\\n' +\n error.message\n );\n }\n }\n throw error;\n }\n}\n\nasync function installAppWithDeviceCtlAsync(\n uuid: string,\n bundleIdOrAppPath: string,\n onProgress: (event: { status: string; isComplete: boolean; progress: number }) => void\n): Promise<void> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n await installAppWithDeviceCtlInternalAsync(uuid, bundleIdOrAppPath, onProgress, attempt);\n return;\n } catch (error: any) {\n if (error.code === 'detached') {\n throw error;\n }\n const isTransientDisconnect =\n error.message &&\n (error.message.includes('CoreDeviceError') || error.message.includes('0xFA0'));\n\n if (!isTransientDisconnect || attempt === maxAttempts) {\n throw error;\n }\n const backoffDelay = 500 + Math.pow(2, attempt - 1) * 500;\n await new Promise((resolve) => setTimeout(resolve, backoffDelay));\n }\n }\n}\n\nasync function installAppWithDeviceCtlInternalAsync(\n uuid: string,\n bundleIdOrAppPath: string,\n onProgress: (event: { status: string; isComplete: boolean; progress: number }) => void,\n attempt: number\n): Promise<void> {\n // 𝝠 xcrun devicectl device install app --device 00001110-001111110110101A /Users/evanbacon/Library/Developer/Xcode/DerivedData/Router-hgbqaxzhrhkiftfweydvhgttadvn/Build/Products/Debug-iphoneos/Router.app --verbose\n return new Promise((resolve, reject) => {\n const args: string[] = [\n 'devicectl',\n 'device',\n 'install',\n 'app',\n '--device',\n uuid,\n bundleIdOrAppPath,\n ];\n const childProcess = spawn('xcrun', args);\n debug('xcrun ' + args.join(' '));\n\n let currentProgress = 0;\n let hasStarted = false;\n\n function updateProgress(progress: number) {\n hasStarted = true;\n if (progress <= currentProgress) {\n return;\n }\n currentProgress = progress;\n const statusPrefix = attempt > 1 ? `Installing (attempt ${attempt})` : 'Installing';\n onProgress({\n progress,\n isComplete: progress === 100,\n status: statusPrefix,\n });\n }\n\n childProcess.stdout.on('data', (data: Buffer) => {\n // Sometimes more than one chunk comes at a time, here we split by system newline,\n // then trim and filter.\n const strings = data\n .toString()\n .split(EOL)\n .map((value) => value.trim());\n\n strings.forEach((str) => {\n // Match the progress percentage:\n // - '34%... 35%...' -> 34\n // - '31%...' -> 31\n // - 'Complete!' -> 100\n\n const match = str.match(/(\\d+)%\\.\\.\\./);\n if (match) {\n updateProgress(parseInt(match[1]!, 10));\n } else if (hasStarted) {\n updateProgress(100);\n }\n });\n\n debug('[stdout]:', strings);\n });\n\n let stderrBuffer = '';\n childProcess.stderr.on('data', (data: Buffer) => {\n stderrBuffer += data.toString();\n });\n\n childProcess.on('close', (code) => {\n debug('[close]: ' + code);\n if (code === 0) {\n resolve();\n } else {\n const err = new Error(stderrBuffer || `Command failed with exit code ${code}`);\n (err as any).code = code;\n detach(err);\n }\n });\n\n const detach = async (err?: Error) => {\n off?.();\n if (childProcess) {\n return new Promise<void>((resolve) => {\n childProcess?.on('close', () => resolve());\n childProcess?.kill();\n reject(err ?? new CommandError('detached'));\n });\n }\n };\n\n const off = installExitHooks(() => detach());\n });\n}\n\nexport async function launchAppWithDeviceCtl(deviceId: string, bundleId: string) {\n await devicectlAsync([\n 'device',\n 'process',\n 'launch',\n '--terminate-existing',\n '--device',\n deviceId,\n bundleId,\n ]);\n}\n\n/** Find all error codes from the output log */\nfunction getDeviceCtlErrorCodes(log: string): string[] {\n return [...log.matchAll(/BSErrorCodeDescription\\s+=\\s+(.*)$/gim)].map(([_line, code]) => code!);\n}\n\nlet hasEverBeenInstalled: boolean | undefined;\n\nexport function hasDevicectlEverBeenInstalled() {\n if (hasEverBeenInstalled) return hasEverBeenInstalled;\n // It doesn't appear possible for devicectl to ever be uninstalled. We can just check once and store this result forever\n // to prevent cold boots of devicectl from slowing down all invocations of `expo run ios`\n if (fs.existsSync(DEVICE_CTL_EXISTS_PATH)) {\n hasEverBeenInstalled = true;\n return true;\n }\n\n const isInstalled = isDevicectlInstalled();\n\n if (isInstalled) {\n fs.writeFileSync(DEVICE_CTL_EXISTS_PATH, '1');\n }\n hasEverBeenInstalled = isInstalled;\n return isInstalled;\n}\n\nfunction isDevicectlInstalled() {\n try {\n execSync('xcrun devicectl --version', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Wraps the apple device method for installing and running an app,\n * adds indicator and retry loop for when the device is locked.\n */\nexport async function installAndLaunchAppAsync(props: {\n bundle: string;\n bundleIdentifier: string;\n udid: string;\n deviceName: string;\n}): Promise<void> {\n debug('Running on device:', props);\n const { bundle, bundleIdentifier, udid, deviceName } = props;\n let indicator: Ora | undefined;\n\n try {\n if (!indicator) {\n indicator = ora(`Connecting to: ${props.deviceName}`).start();\n }\n\n await installAppWithDeviceCtlAsync(\n udid,\n bundle,\n ({\n status,\n isComplete,\n progress,\n }: {\n status: string;\n isComplete: boolean;\n progress: number;\n }) => {\n if (!indicator) {\n indicator = ora(status).start();\n }\n indicator.text = `${chalk.bold(status)} ${progress}%`;\n if (isComplete) {\n indicator.succeed();\n }\n }\n );\n } catch (error: any) {\n if (indicator) {\n indicator.fail();\n }\n throw error;\n }\n\n async function launchAppOptionally() {\n try {\n await launchAppWithDeviceCtl(udid, bundleIdentifier);\n } catch (error: any) {\n if (indicator) {\n indicator.fail();\n }\n if (error.code === 'APPLE_DEVICE_LOCKED') {\n // Get the app name from the binary path.\n const appName = path.basename(bundle).split('.')[0] ?? 'app';\n if (\n isInteractive() &&\n (await confirmAsync({\n message: `Cannot launch ${appName} because the device is locked. Unlock ${deviceName} to continue...`,\n initial: true,\n }))\n ) {\n return launchAppOptionally();\n }\n throw new CommandError(\n `Cannot launch ${appName} on ${deviceName} because the device is locked.`\n );\n }\n throw error;\n }\n }\n\n await launchAppOptionally();\n}\n"],"names":["devicectlAsync","getConnectedAppleDevicesAsync","hasDevicectlEverBeenInstalled","installAndLaunchAppAsync","launchAppWithDeviceCtl","launchBinaryOnMacAsync","DEVICE_CTL_EXISTS_PATH","path","join","getExpoHomeDirectory","debug","require","args","options","xcrunAsync","error","CommandError","errorCodes","getDeviceCtlErrorCodes","stderr","includes","tmpPath","createTempFilePath","devices","stdout","devicesJson","JsonFile","readAsync","info","jsonVersion","Log","warn","assertDevicesJson","result","filter","device","hardwareProperties","reality","results","assert","Array","isArray","JSON","stringify","bundleId","appBinaryPath","spawnAsync","code","message","installAppWithDeviceCtlAsync","uuid","bundleIdOrAppPath","onProgress","maxAttempts","attempt","installAppWithDeviceCtlInternalAsync","isTransientDisconnect","backoffDelay","Math","pow","Promise","resolve","setTimeout","reject","childProcess","spawn","currentProgress","hasStarted","updateProgress","progress","statusPrefix","isComplete","status","on","data","strings","toString","split","EOL","map","value","trim","forEach","str","match","parseInt","stderrBuffer","err","Error","detach","off","kill","installExitHooks","deviceId","log","matchAll","_line","hasEverBeenInstalled","fs","existsSync","isInstalled","isDevicectlInstalled","writeFileSync","execSync","stdio","props","bundle","bundleIdentifier","udid","deviceName","indicator","ora","start","text","chalk","bold","succeed","fail","launchAppOptionally","appName","basename","isInteractive","confirmAsync","initial"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QA+HqBA;eAAAA;;QAoBAC;eAAAA;;QA2MNC;eAAAA;;QA+BMC;eAAAA;;QAlDAC;eAAAA;;QA/IAC;eAAAA;;;;gEA1LD;;;;;;;gEAEE;;;;;;;gEACL;;;;;;;yBACc;;;;;;;gEACjB;;;;;;;gEACI;;;;;;;yBAEC;;;;;;;gEACH;;;;;;uBAEU;8BACU;6DAChB;gCACc;wBACN;sBACI;6BACH;qBACV;yBACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE7B,MAAMC,yBAAyBC,eAAI,CAACC,IAAI,CAACC,IAAAA,kCAAoB,KAAI;AAEjE,MAAMC,QAAQC,QAAQ,SAAS;AAsGxB,eAAeX,eACpBY,IAA4B,EAC5BC,OAAsB;IAEtB,IAAI;QACF,OAAO,MAAMC,IAAAA,iBAAU,EAAC;YAAC;eAAgBF;SAAK,EAAEC;IAClD,EAAE,OAAOE,OAAY;QACnB,IAAIA,iBAAiBC,oBAAY,EAAE;YACjC,MAAMD;QACR;QACA,IAAI,YAAYA,OAAO;YACrB,MAAME,aAAaC,uBAAuBH,MAAMI,MAAM;YACtD,IAAIF,WAAWG,QAAQ,CAAC,WAAW;gBACjC,MAAM,IAAIJ,oBAAY,CAAC,uBAAuB;YAChD;QACF;QACA,MAAMD;IACR;AACF;AAEO,eAAed;QAmBI;IAlBxB,IAAI,CAACC,iCAAiC;QACpCQ,MAAM;QACN,OAAO,EAAE;IACX;IAEA,MAAMW,UAAUC,IAAAA,kCAAkB;IAClC,MAAMC,UAAU,MAAMvB,eAAe;QACnC;QACA;QACA;QACAqB;QACA,wEAAwE;QACxE;QACA;KACD;IACDX,MAAMa,QAAQC,MAAM;IACpB,MAAMC,cAAc,MAAMC,mBAAQ,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A,0BAAa,OACZ,MAAMC,IAAAA,qBAAY,EAAC;oBAClB1E,SAAS,CAAC,cAAc,EAAEuE,QAAQ,sCAAsC,EAAEV,WAAW,eAAe,CAAC;oBACrGc,SAAS;gBACX,IACA;oBACA,OAAOL;gBACT;gBACA,MAAM,IAAItG,oBAAY,CACpB,CAAC,cAAc,EAAEuG,QAAQ,IAAI,EAAEV,WAAW,8BAA8B,CAAC;YAE7E;YACA,MAAM9F;QACR;IACF;IAEA,MAAMuG;AACR"}
1
+ {"version":3,"sources":["../../../../../src/start/platforms/ios/devicectl.ts"],"sourcesContent":["/**\n * Copyright © 2024 650 Industries.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nimport JsonFile from '@expo/json-file';\nimport type { SpawnOptions, SpawnResult } from '@expo/spawn-async';\nimport spawnAsync from '@expo/spawn-async';\nimport chalk from 'chalk';\nimport { spawn, execSync } from 'child_process';\nimport fs from 'fs';\nimport assert from 'node:assert';\nimport type { Ora } from 'ora';\nimport { EOL } from 'os';\nimport path from 'path';\n\nimport { xcrunAsync } from './xcrun';\nimport { getExpoHomeDirectory } from '../../../api/user/UserSettings';\nimport * as Log from '../../../log';\nimport { createTempFilePath } from '../../../utils/createTempPath';\nimport { CommandError } from '../../../utils/errors';\nimport { installExitHooks } from '../../../utils/exit';\nimport { isInteractive } from '../../../utils/interactive';\nimport { ora } from '../../../utils/ora';\nimport { confirmAsync } from '../../../utils/prompts';\n\nconst DEVICE_CTL_EXISTS_PATH = path.join(getExpoHomeDirectory(), 'devicectl-exists');\n\nconst debug = require('debug')('expo:devicectl') as typeof console.log;\n\ntype AnyEnum<T extends string = string> = T | (string & object);\n\ntype DeviceCtlDevice = {\n capabilities: DeviceCtlDeviceCapability[];\n connectionProperties: DeviceCtlConnectionProperties;\n deviceProperties: DeviceCtlDeviceProperties;\n hardwareProperties: DeviceCtlHardwareProperties;\n /** \"A1A1AAA1-0011-1AA1-11A1-10A1111AA11A\" */\n identifier: string;\n visibilityClass: AnyEnum<'default'>;\n};\n\ntype DeviceCtlHardwareProperties = {\n cpuType: DeviceCtlCpuType;\n deviceType: AnyEnum<'iPhone'>;\n /** 1114404411111111 */\n ecid: number;\n /** \"D74AP\" */\n hardwareModel: string;\n /** 512000000000 */\n internalStorageCapacity: number;\n /** true */\n isProductionFused: boolean;\n /** \"iPhone 14 Pro Max\" */\n marketingName: string;\n /** \"iOS\" */\n platform: AnyEnum<'iOS' | 'xrOS'>;\n /** \"iPhone15,3\" */\n productType: AnyEnum<'iPhone13,4' | 'iPhone15,3'>;\n reality: AnyEnum<'physical' | 'simulated'>;\n /** \"X2X1CC1XXX\" */\n serialNumber: string;\n supportedCPUTypes: DeviceCtlCpuType[];\n /** [1] */\n supportedDeviceFamilies: number[];\n thinningProductType: AnyEnum<'iPhone15,3'>;\n /** \"00001110-001111110110101A\" */\n udid: string;\n};\n\ntype DeviceCtlDeviceProperties = {\n /** true */\n bootedFromSnapshot: boolean;\n /** \"com.apple.os.update-AD0CF111ACFF11A11111A76A3D1262AE42A3F56F305AF5AE1135393A7A14A7D1\" */\n bootedSnapshotName: string;\n /** false */\n ddiServicesAvailable: boolean;\n\n developerModeStatus: AnyEnum<'enabled'>;\n /** false */\n hasInternalOSBuild: boolean;\n /** \"Evan's phone\" */\n name: string;\n /** \"21E236\" */\n osBuildUpdate: string;\n /** \"17.4.1\" */\n osVersionNumber: string;\n /** false */\n rootFileSystemIsWritable: boolean;\n};\n\ntype DeviceCtlDeviceCapability =\n | {\n name: AnyEnum;\n featureIdentifier: AnyEnum;\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.connectdevice';\n name: 'Connect to Device';\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.unpairdevice';\n name: 'Unpair Device';\n }\n | {\n featureIdentifier: 'com.apple.coredevice.feature.acquireusageassertion';\n name: 'Acquire Usage Assertion';\n };\n\ntype DeviceCtlConnectionProperties = {\n authenticationType: AnyEnum<'manualPairing'>;\n isMobileDeviceOnly: boolean;\n /** \"2024-04-20T22:50:04.244Z\" */\n lastConnectionDate: string;\n pairingState: AnyEnum<'paired'>;\n /** [\"00001111-001111110110101A.coredevice.local\", \"A1A1AAA1-0011-1AA1-11A1-10A1111AA11A.coredevice.local\"] */\n potentialHostnames: string[];\n transportType: AnyEnum<'localNetwork' | 'wired'>;\n tunnelState: AnyEnum<'disconnected' | 'unavailable'>;\n tunnelTransportProtocol: AnyEnum<'tcp'>;\n};\n\ntype DeviceCtlCpuType = {\n name: AnyEnum<'arm64e' | 'arm64' | 'arm64_32'>;\n subType: number;\n /** 16777228 */\n type: number;\n};\n\n/** Run a `devicectl` command. */\nexport async function devicectlAsync(\n args: (string | undefined)[],\n options?: SpawnOptions\n): Promise<SpawnResult> {\n try {\n return await xcrunAsync(['devicectl', ...args], options);\n } catch (error: any) {\n if (error instanceof CommandError) {\n throw error;\n }\n if ('stderr' in error) {\n const errorCodes = getDeviceCtlErrorCodes(error.stderr);\n if (errorCodes.includes('Locked')) {\n throw new CommandError('APPLE_DEVICE_LOCKED', 'Device is locked, unlock and try again.');\n }\n }\n throw error;\n }\n}\n\nexport async function getConnectedAppleDevicesAsync() {\n if (!hasDevicectlEverBeenInstalled()) {\n debug('devicectl not found, skipping remote Apple devices.');\n return [];\n }\n\n const tmpPath = createTempFilePath();\n const devices = await devicectlAsync([\n 'list',\n 'devices',\n '--json-output',\n tmpPath,\n // Give two seconds before timing out: between 5 and 9223372036854775807\n '--timeout',\n '5',\n ]);\n debug(devices.stdout);\n const devicesJson = await JsonFile.readAsync(tmpPath);\n\n if (![2, 3, 5].includes((devicesJson as any)?.info?.jsonVersion)) {\n Log.warn(\n 'Unexpected devicectl JSON version output from devicectl. Connecting to physical Apple devices may not work as expected.'\n );\n }\n\n assertDevicesJson(devicesJson);\n\n return (devicesJson.result.devices as DeviceCtlDevice[]).filter(\n (device) => device?.hardwareProperties?.reality !== 'simulated'\n );\n}\n\nfunction assertDevicesJson(\n results: any\n): asserts results is { result: { devices: DeviceCtlDevice[] } } {\n assert(\n results != null && 'result' in results && Array.isArray(results?.result?.devices),\n 'Malformed JSON output from devicectl: ' + JSON.stringify(results, null, 2)\n );\n}\n\nexport async function launchBinaryOnMacAsync(\n bundleId: string,\n appBinaryPath: string\n): Promise<void> {\n const args = ['-b', bundleId, appBinaryPath];\n try {\n await spawnAsync('open', args);\n } catch (error: any) {\n if ('code' in error) {\n if (error.code === 1) {\n throw new CommandError(\n 'MACOS_LAUNCH',\n 'Failed to launch the compatible binary on macOS: open ' +\n args.join(' ') +\n '\\n\\n' +\n error.message\n );\n }\n }\n throw error;\n }\n}\n\nasync function installAppWithDeviceCtlAsync(\n uuid: string,\n bundleIdOrAppPath: string,\n onProgress: (event: { status: string; progress: number }) => void\n): Promise<void> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n await installAppWithDeviceCtlInternalAsync(uuid, bundleIdOrAppPath, onProgress, attempt);\n return;\n } catch (error: any) {\n if (error.code === 'detached') {\n throw error;\n }\n const isTransientDisconnect =\n error.message &&\n (error.message.includes('CoreDeviceError') || error.message.includes('0xFA0'));\n\n if (!isTransientDisconnect || attempt === maxAttempts) {\n throw error;\n }\n const backoffDelay = 500 + Math.pow(2, attempt - 1) * 500;\n await new Promise((resolve) => setTimeout(resolve, backoffDelay));\n }\n }\n}\n\nasync function installAppWithDeviceCtlInternalAsync(\n uuid: string,\n bundleIdOrAppPath: string,\n onProgress: (event: { status: string; progress: number }) => void,\n attempt: number\n): Promise<void> {\n // 𝝠 xcrun devicectl device install app --device 00001110-001111110110101A /Users/evanbacon/Library/Developer/Xcode/DerivedData/Router-hgbqaxzhrhkiftfweydvhgttadvn/Build/Products/Debug-iphoneos/Router.app --verbose\n return new Promise((resolve, reject) => {\n const args: string[] = [\n 'devicectl',\n 'device',\n 'install',\n 'app',\n '--device',\n uuid,\n bundleIdOrAppPath,\n ];\n const childProcess = spawn('xcrun', args);\n debug('xcrun ' + args.join(' '));\n\n let currentProgress = 0;\n let hasStarted = false;\n\n function updateProgress(progress: number) {\n hasStarted = true;\n if (progress <= currentProgress) {\n return;\n }\n currentProgress = progress;\n const statusPrefix = attempt > 1 ? `Installing (attempt ${attempt})` : 'Installing';\n onProgress({\n progress,\n status: statusPrefix,\n });\n }\n\n childProcess.stdout.on('data', (data: Buffer) => {\n // Sometimes more than one chunk comes at a time, here we split by system newline,\n // then trim and filter.\n const strings = data\n .toString()\n .split(EOL)\n .map((value) => value.trim());\n\n strings.forEach((str) => {\n // Match the progress percentage:\n // - '34%... 35%...' -> 34\n // - '31%...' -> 31\n // - 'Complete!' -> 100\n\n const match = str.match(/(\\d+)%\\.\\.\\./);\n if (match) {\n updateProgress(parseInt(match[1]!, 10));\n } else if (hasStarted) {\n updateProgress(100);\n }\n });\n\n debug('[stdout]:', strings);\n });\n\n let stderrBuffer = '';\n childProcess.stderr.on('data', (data: Buffer) => {\n stderrBuffer += data.toString();\n });\n\n childProcess.on('close', (code) => {\n debug('[close]: ' + code);\n if (code === 0) {\n resolve();\n } else {\n const err = new Error(stderrBuffer || `Command failed with exit code ${code}`);\n (err as any).code = code;\n detach(err);\n }\n });\n\n const detach = async (err?: Error) => {\n off?.();\n if (childProcess) {\n return new Promise<void>((resolve) => {\n childProcess?.on('close', () => resolve());\n childProcess?.kill();\n reject(err ?? new CommandError('detached'));\n });\n }\n };\n\n const off = installExitHooks(() => detach());\n });\n}\n\nexport async function launchAppWithDeviceCtl(deviceId: string, bundleId: string) {\n await devicectlAsync([\n 'device',\n 'process',\n 'launch',\n '--terminate-existing',\n '--device',\n deviceId,\n bundleId,\n ]);\n}\n\n/** Find all error codes from the output log */\nfunction getDeviceCtlErrorCodes(log: string): string[] {\n return [...log.matchAll(/BSErrorCodeDescription\\s+=\\s+(.*)$/gim)].map(([_line, code]) => code!);\n}\n\nlet hasEverBeenInstalled: boolean | undefined;\n\nexport function hasDevicectlEverBeenInstalled() {\n if (hasEverBeenInstalled) return hasEverBeenInstalled;\n // It doesn't appear possible for devicectl to ever be uninstalled. We can just check once and store this result forever\n // to prevent cold boots of devicectl from slowing down all invocations of `expo run ios`\n if (fs.existsSync(DEVICE_CTL_EXISTS_PATH)) {\n hasEverBeenInstalled = true;\n return true;\n }\n\n const isInstalled = isDevicectlInstalled();\n\n if (isInstalled) {\n fs.writeFileSync(DEVICE_CTL_EXISTS_PATH, '1');\n }\n hasEverBeenInstalled = isInstalled;\n return isInstalled;\n}\n\nfunction isDevicectlInstalled() {\n try {\n execSync('xcrun devicectl --version', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Wraps the apple device method for installing and running an app,\n * adds indicator and retry loop for when the device is locked.\n */\nexport async function installAndLaunchAppAsync(props: {\n bundle: string;\n bundleIdentifier: string;\n udid: string;\n deviceName: string;\n}): Promise<void> {\n debug('Running on device:', props);\n const { bundle, bundleIdentifier, udid, deviceName } = props;\n let indicator: Ora | undefined;\n\n try {\n if (!indicator) {\n indicator = ora(`Connecting to: ${props.deviceName}`).start();\n }\n\n await installAppWithDeviceCtlAsync(\n udid,\n bundle,\n ({ status, progress }: { status: string; progress: number }) => {\n if (!indicator) {\n indicator = ora(status).start();\n }\n indicator.text = `${chalk.bold(status)} ${progress}%`;\n }\n );\n indicator.succeed(`Installed on ${deviceName}`);\n } catch (error: any) {\n if (indicator) {\n indicator.fail();\n }\n throw error;\n }\n\n async function launchAppOptionally() {\n try {\n await launchAppWithDeviceCtl(udid, bundleIdentifier);\n } catch (error: any) {\n if (indicator) {\n indicator.fail();\n }\n if (error.code === 'APPLE_DEVICE_LOCKED') {\n // Get the app name from the binary path.\n const appName = path.basename(bundle).split('.')[0] ?? 'app';\n if (\n isInteractive() &&\n (await confirmAsync({\n message: `Cannot launch ${appName} because the device is locked. Unlock ${deviceName} to continue...`,\n initial: true,\n }))\n ) {\n return launchAppOptionally();\n }\n throw new CommandError(\n `Cannot launch ${appName} on ${deviceName} because the device is locked.`\n );\n }\n throw error;\n }\n }\n\n await launchAppOptionally();\n}\n"],"names":["devicectlAsync","getConnectedAppleDevicesAsync","hasDevicectlEverBeenInstalled","installAndLaunchAppAsync","launchAppWithDeviceCtl","launchBinaryOnMacAsync","DEVICE_CTL_EXISTS_PATH","path","join","getExpoHomeDirectory","debug","require","args","options","xcrunAsync","error","CommandError","errorCodes","getDeviceCtlErrorCodes","stderr","includes","tmpPath","createTempFilePath","devices","stdout","devicesJson","JsonFile","readAsync","info","jsonVersion","Log","warn","assertDevicesJson","result","filter","device","hardwareProperties","reality","results","assert","Array","isArray","JSON","stringify","bundleId","appBinaryPath","spawnAsync","code","message","installAppWithDeviceCtlAsync","uuid","bundleIdOrAppPath","onProgress","maxAttempts","attempt","installAppWithDeviceCtlInternalAsync","isTransientDisconnect","backoffDelay","Math","pow","Promise","resolve","setTimeout","reject","childProcess","spawn","currentProgress","hasStarted","updateProgress","progress","statusPrefix","status","on","data","strings","toString","split","EOL","map","value","trim","forEach","str","match","parseInt","stderrBuffer","err","Error","detach","off","kill","installExitHooks","deviceId","log","matchAll","_line","hasEverBeenInstalled","fs","existsSync","isInstalled","isDevicectlInstalled","writeFileSync","execSync","stdio","props","bundle","bundleIdentifier","udid","deviceName","indicator","ora","start","text","chalk","bold","succeed","fail","launchAppOptionally","appName","basename","isInteractive","confirmAsync","initial"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QA+HqBA;eAAAA;;QAoBAC;eAAAA;;QA0MNC;eAAAA;;QA+BMC;eAAAA;;QAlDAC;eAAAA;;QA9IAC;eAAAA;;;;gEA1LD;;;;;;;gEAEE;;;;;;;gEACL;;;;;;;yBACc;;;;;;;gEACjB;;;;;;;gEACI;;;;;;;yBAEC;;;;;;;gEACH;;;;;;uBAEU;8BACU;6DAChB;gCACc;wBACN;sBACI;6BACH;qBACV;yBACS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE7B,MAAMC,yBAAyBC,eAAI,CAACC,IAAI,CAACC,IAAAA,kCAAoB,KAAI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AAElC,MAAM,EAAEF,QAAQ,EAAwC;YACzD,IAAI,CAACwC,WAAW;gBACdA,YAAYC,IAAAA,QAAG,EAACvC,QAAQwC,KAAK;YAC/B;YACAF,UAAUG,IAAI,GAAG,GAAGC,gBAAK,CAACC,IAAI,CAAC3C,QAAQ,CAAC,EAAEF,SAAS,CAAC,CAAC;QACvD;QAEFwC,UAAUM,OAAO,CAAC,CAAC,aAAa,EAAEP,YAAY;IAChD,EAAE,OAAO7F,OAAY;QACnB,IAAI8F,WAAW;YACbA,UAAUO,IAAI;QAChB;QACA,MAAMrG;IACR;IAEA,eAAesG;QACb,IAAI;YACF,MAAMjH,uBAAuBuG,MAAMD;QACrC,EAAE,OAAO3F,OAAY;YACnB,IAAI8F,WAAW;gBACbA,UAAUO,IAAI;YAChB;YACA,IAAIrG,MAAMgC,IAAI,KAAK,uBAAuB;gBACxC,yCAAyC;gBACzC,MAAMuE,UAAU/G,eAAI,CAACgH,QAAQ,CAACd,QAAQ7B,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI;gBACvD,IACE4C,IAAAA,0BAAa,OACZ,MAAMC,IAAAA,qBAAY,EAAC;oBAClBzE,SAAS,CAAC,cAAc,EAAEsE,QAAQ,sCAAsC,EAAEV,WAAW,eAAe,CAAC;oBACrGc,SAAS;gBACX,IACA;oBACA,OAAOL;gBACT;gBACA,MAAM,IAAIrG,oBAAY,CACpB,CAAC,cAAc,EAAEsG,QAAQ,IAAI,EAAEV,WAAW,8BAA8B,CAAC;YAE7E;YACA,MAAM7F;QACR;IACF;IAEA,MAAMsG;AACR"}
@@ -25,7 +25,7 @@ function _resolvefrom() {
25
25
  const _AsyncNgrok = require("./AsyncNgrok");
26
26
  const _AsyncWsTunnel = require("./AsyncWsTunnel");
27
27
  const _Bonjour = require("./Bonjour");
28
- const _DevToolsPluginManager = /*#__PURE__*/ _interop_require_default(require("./DevToolsPluginManager"));
28
+ const _DevToolsPluginManager = /*#__PURE__*/ _interop_require_default(require("./devtools/DevToolsPluginManager"));
29
29
  const _DevelopmentSession = require("./DevelopmentSession");
30
30
  const _UrlCreator = require("./UrlCreator");
31
31
  const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../log"));
@@ -311,10 +311,7 @@ class BundlerDevServer {
311
311
  return this.urlCreator;
312
312
  }
313
313
  getNativeRuntimeUrl(opts = {}) {
314
- return this.isDevClient ? this.getUrlCreator().constructDevClientUrl(opts) ?? this.getDevServerUrl() : this.getUrlCreator().constructUrl({
315
- ...opts,
316
- scheme: 'exp'
317
- });
314
+ return this.isDevClient ? this.getUrlCreator().constructDevClientUrl(opts) ?? this.getDevServerUrl() : this.getUrlCreator().constructExpoGoUrl(opts);
318
315
  }
319
316
  /** Get the URL for the running instance of the dev server. */ getDevServerUrl(options = {}) {
320
317
  const instance = this.getInstance();
@@ -323,7 +320,9 @@ class BundlerDevServer {
323
320
  }
324
321
  // If we have an active WS tunnel instance, we always need to return the tunnel location.
325
322
  if (this.tunnel && this.tunnel instanceof _AsyncWsTunnel.AsyncWsTunnel) {
326
- return this.getUrlCreator().constructUrl();
323
+ return this.getUrlCreator().constructUrl({
324
+ scheme: 'http'
325
+ });
327
326
  }
328
327
  const { location } = instance;
329
328
  if (options.hostType === 'localhost') {
@@ -383,9 +382,7 @@ class BundlerDevServer {
383
382
  }, resolver);
384
383
  }
385
384
  /** Get the URL for opening in Expo Go. */ getExpoGoUrl() {
386
- return this.getUrlCreator().constructUrl({
387
- scheme: 'exp'
388
- });
385
+ return this.getUrlCreator().constructExpoGoUrl();
389
386
  }
390
387
  /** Should use the interstitial page for selecting which runtime to use. */ isRedirectPageEnabled() {
391
388
  return !_env.env.EXPO_NO_REDIRECT_PAGE && // if user passed --dev-client flag, skip interstitial page
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/start/server/BundlerDevServer.ts"],"sourcesContent":["import assert from 'assert';\nimport resolveFrom from 'resolve-from';\n\nimport { AsyncNgrok } from './AsyncNgrok';\nimport { AsyncWsTunnel } from './AsyncWsTunnel';\nimport { Bonjour } from './Bonjour';\nimport DevToolsPluginManager from './DevToolsPluginManager';\nimport { DevelopmentSession } from './DevelopmentSession';\nimport type { CreateURLOptions } from './UrlCreator';\nimport { UrlCreator } from './UrlCreator';\nimport type { PlatformBundlers } from './platformBundlers';\nimport * as Log from '../../log';\nimport { FileNotifier } from '../../utils/FileNotifier';\nimport { resolveWithTimeout } from '../../utils/delay';\nimport { env, envIsWebcontainer } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { isInteractive } from '../../utils/interactive';\nimport { openBrowserAsync } from '../../utils/open';\nimport type { BaseResolveDeviceProps, PlatformManager } from '../platforms/PlatformManager';\n\nconst debug = require('debug')('expo:start:server:devServer') as typeof console.log;\n\nexport type MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\nexport type ServerLike = {\n close(callback?: (err?: Error) => void): void;\n addListener?(event: string, listener: (...args: any[]) => void): unknown;\n};\n\nexport type DevServerInstance = {\n /** Bundler dev server instance. */\n server: ServerLike;\n /** Dev server URL location properties. */\n location: {\n url: string;\n port: number;\n protocol: 'http' | 'https';\n host?: string;\n };\n /** Additional middleware that's attached to the `server`. */\n middleware: any;\n /** Message socket for communicating with the runtime. */\n messageSocket: MessageSocket;\n};\n\nexport interface BundlerStartOptions {\n /** Should the dev server use `https` protocol. */\n https?: boolean;\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Is dev client enabled. */\n devClient?: boolean;\n /** Should run dev servers with clean caches. */\n resetDevServer?: boolean;\n /** Code signing private key path (defaults to same directory as certificate) */\n privateKeyPath?: string;\n\n /** Max amount of workers (threads) to use with Metro bundler, defaults to undefined for max workers. */\n maxWorkers?: number;\n /** Port to start the dev server on. */\n port?: number;\n\n /** Should start a headless dev server e.g. mock representation to approximate info from a server running in a different process. */\n headless?: boolean;\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n\n /** Will the bundler be used for exporting. NOTE: This is an odd option to pass to the dev server. */\n isExporting?: boolean;\n\n // Webpack options\n /** Should modify and create PWA icons. */\n isImageEditingEnabled?: boolean;\n\n location: CreateURLOptions;\n}\n\nconst PLATFORM_MANAGERS = {\n simulator: () =>\n require('../platforms/ios/ApplePlatformManager')\n .ApplePlatformManager as typeof import('../platforms/ios/ApplePlatformManager').ApplePlatformManager,\n emulator: () =>\n require('../platforms/android/AndroidPlatformManager')\n .AndroidPlatformManager as typeof import('../platforms/android/AndroidPlatformManager').AndroidPlatformManager,\n};\n\ntype PlatformManagers = {\n [K in keyof typeof PLATFORM_MANAGERS]: InstanceType<ReturnType<(typeof PLATFORM_MANAGERS)[K]>>;\n};\n\ntype PlatformDevice<Platform extends keyof PlatformManagers> =\n PlatformManagers[Platform] extends PlatformManager<infer Device, any> ? Device : never;\n\ntype PlatformLaunchProps<Platform extends keyof PlatformManagers> =\n PlatformManagers[Platform] extends PlatformManager<any, infer LaunchProps> ? LaunchProps : never;\n\nexport abstract class BundlerDevServer {\n /** Name of the bundler. */\n abstract get name(): string;\n\n /** Tunnel instance for managing tunnel connections. */\n protected tunnel: AsyncNgrok | AsyncWsTunnel | null = null;\n /** Interfaces with the Expo 'Development Session' API. */\n protected devSession: DevelopmentSession | null = null;\n /** Announces dev server via Bonjour */\n protected bonjour: Bonjour | null = null;\n /** Http server and related info. */\n protected instance: DevServerInstance | null = null;\n /** Native platform interfaces for opening projects. */\n private platformManagers: { [K in keyof PlatformManagers]?: PlatformManagers[K] | undefined } =\n {};\n /** Manages the creation of dev server URLs. */\n protected urlCreator?: UrlCreator | null = null;\n\n private notifier: FileNotifier | null = null;\n protected readonly devToolsPluginManager: DevToolsPluginManager;\n public isDevClient: boolean;\n\n constructor(\n /** Project root folder. */\n public projectRoot: string,\n /** A mapping of bundlers to platforms. */\n public platformBundlers: PlatformBundlers,\n /** Advanced options */\n options?: {\n /**\n * The instance of DevToolsPluginManager\n * @default new DevToolsPluginManager(projectRoot)\n */\n devToolsPluginManager?: DevToolsPluginManager;\n // TODO: Replace with custom scheme maybe...\n isDevClient?: boolean;\n }\n ) {\n this.devToolsPluginManager =\n options?.devToolsPluginManager ?? new DevToolsPluginManager(projectRoot);\n this.isDevClient = options?.isDevClient ?? false;\n }\n\n protected setInstance(instance: DevServerInstance) {\n this.instance = instance;\n }\n\n /** Get the manifest middleware function. */\n protected async getManifestMiddlewareAsync(\n options: Pick<BundlerStartOptions, 'minify' | 'mode' | 'privateKeyPath'> = {}\n ) {\n const Middleware = require('./middleware/ExpoGoManifestHandlerMiddleware')\n .ExpoGoManifestHandlerMiddleware as typeof import('./middleware/ExpoGoManifestHandlerMiddleware').ExpoGoManifestHandlerMiddleware;\n\n const urlCreator = this.getUrlCreator();\n const middleware = new Middleware(this.projectRoot, {\n constructUrl: urlCreator.constructUrl.bind(urlCreator),\n mode: options.mode,\n minify: options.minify,\n isNativeWebpack: this.name === 'webpack' && this.isTargetingNative(),\n privateKeyPath: options.privateKeyPath,\n });\n return middleware;\n }\n\n /** Start the dev server using settings defined in the start command. */\n public async startAsync(options: BundlerStartOptions): Promise<DevServerInstance> {\n await this.stopAsync();\n\n let instance: DevServerInstance;\n if (options.headless) {\n instance = await this.startHeadlessAsync(options);\n } else {\n instance = await this.startImplementationAsync(options);\n }\n\n this.setInstance(instance);\n await this.postStartAsync(options);\n return instance;\n }\n\n protected abstract startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance>;\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n return false;\n }\n\n public abstract startTypeScriptServices(): Promise<void>;\n\n public async watchEnvironmentVariables(): Promise<void> {\n // noop -- We've only implemented this functionality in Metro.\n }\n\n /**\n * Creates a mock server representation that can be used to estimate URLs for a server started in another process.\n * This is used for the run commands where you can reuse the server from a previous run.\n */\n private async startHeadlessAsync(options: BundlerStartOptions): Promise<DevServerInstance> {\n if (!options.port)\n throw new CommandError('HEADLESS_SERVER', 'headless dev server requires a port option');\n await this.initUrlCreator(options);\n return {\n // Create a mock server\n server: {\n close: (callback: () => void) => {\n this.instance = null;\n callback?.();\n },\n addListener() {},\n },\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 broadcast: () => {\n throw new CommandError('HEADLESS_SERVER', 'Cannot broadcast messages to headless server');\n },\n },\n };\n }\n\n /**\n * Runs after the `startAsync` function, performing any additional common operations.\n * You can assume the dev server is started by the time this function is called.\n */\n protected async postStartAsync(options: BundlerStartOptions) {\n if (\n options.location.hostType === 'tunnel' &&\n !env.EXPO_OFFLINE &&\n // This is a hack to prevent using tunnel on web since we block it upstream for some reason.\n this.isTargetingNative()\n ) {\n await this._startTunnelAsync();\n } else if (envIsWebcontainer()) {\n await this._startTunnelAsync();\n }\n\n if (!options.isExporting) {\n await Promise.all([this.startDevSessionAsync(), this.startBonjourAsync()]);\n this.watchConfig();\n }\n }\n\n protected abstract getConfigModuleIds(): string[];\n\n protected watchConfig() {\n this.notifier?.stopObserving();\n this.notifier = new FileNotifier(this.projectRoot, this.getConfigModuleIds());\n this.notifier.startObserving();\n }\n\n /** Create the tunnel instance and start the tunnel server. Exposed for testing. */\n public async _startTunnelAsync(): Promise<AsyncNgrok | AsyncWsTunnel | null> {\n const port = this.getInstance()?.location.port;\n if (!port) return null;\n debug('[tunnel] connect to port: ' + port);\n this.tunnel = this._createTunnel(port);\n await this.tunnel.startAsync();\n return this.tunnel;\n }\n\n /** Resolve which tunnel implementation to use, without starting it. */\n private _createTunnel(port: number): AsyncNgrok | AsyncWsTunnel {\n const useV2Tunnel = env.EXPO_UNSTABLE_TUNNEL_V2 || envIsWebcontainer();\n if (useV2Tunnel) {\n const useExpoAccount = !!env.EXPO_UNSTABLE_TUNNEL_V2;\n return new AsyncWsTunnel(this.projectRoot, port, { useExpoAccount });\n }\n\n return new AsyncNgrok(this.projectRoot, port);\n }\n\n protected async startDevSessionAsync() {\n // This is used to make Expo Go open the project in either Expo Go, or the web browser.\n // Must come after ngrok (`startTunnelAsync`) setup.\n this.devSession = new DevelopmentSession(\n this.projectRoot,\n // This URL will be used on external devices so the computer IP won't be relevant.\n this.isTargetingNative()\n ? this.getNativeRuntimeUrl()\n : this.getDevServerUrl({ hostType: 'localhost' })\n );\n\n await this.devSession.startAsync({\n runtime: this.isTargetingNative() ? 'native' : 'web',\n });\n }\n\n protected async startBonjourAsync() {\n // This is used to make Expo Go open the project in either Expo Go, or the web browser.\n // Must come after ngrok (`startTunnelAsync`) setup.\n if (!this.bonjour) {\n this.bonjour = new Bonjour(this.projectRoot, this.getInstance()?.location.port);\n }\n\n await this.bonjour.announceAsync({});\n }\n\n public isTargetingNative() {\n // Temporary hack while we implement multi-bundler dev server proxy.\n return true;\n }\n\n public isTargetingWeb() {\n return this.platformBundlers.web === this.name;\n }\n\n /**\n * Sends a message over web sockets to any connected device,\n * does nothing when the dev server is not running.\n *\n * @param method name of the command. In RN projects `reload`, and `devMenu` are available. In Expo Go, `sendDevCommand` is available.\n * @param params\n */\n public broadcastMessage(\n method: 'reload' | 'devMenu' | 'sendDevCommand',\n params?: Record<string, any>\n ) {\n this.getInstance()?.messageSocket.broadcast(method, params);\n }\n\n /** Get the running dev server instance. */\n public getInstance() {\n return this.instance;\n }\n\n /** Stop the running dev server instance. */\n async stopAsync() {\n // Reset url creator\n this.urlCreator = undefined;\n\n // Stop file watching.\n this.notifier?.stopObserving();\n\n await Promise.all([\n // Stop the bonjour advertiser\n this.bonjour?.closeAsync(),\n // Stop the dev session timer and tell Expo API to remove dev session.\n this.devSession?.closeAsync(),\n ]);\n\n // Stop tunnel if running.\n await this.tunnel?.stopAsync().catch((e) => {\n Log.error(`Error stopping tunnel:`);\n Log.exception(e);\n });\n\n return resolveWithTimeout(\n () =>\n new Promise<void>((resolve, reject) => {\n // Close the server.\n debug(`Stopping dev server (bundler: ${this.name})`);\n\n if (this.instance?.server) {\n // Check if server is even running.\n this.instance.server.close((error) => {\n debug(`Stopped dev server (bundler: ${this.name})`);\n this.instance = null;\n if (error) {\n if ('code' in error && error.code === 'ERR_SERVER_NOT_RUNNING') {\n resolve();\n } else {\n reject(error);\n }\n } else {\n resolve();\n }\n });\n } else {\n debug(`Stopped dev server (bundler: ${this.name})`);\n this.instance = null;\n resolve();\n }\n }),\n {\n // NOTE(Bacon): Metro dev server doesn't seem to be closing in time.\n timeout: 1000,\n errorMessage: `Timeout waiting for '${this.name}' dev server to close`,\n }\n );\n }\n\n // TODO(@kitten): This should be created top-down rather than bottom up from implementors\n protected async initUrlCreator(\n options: Partial<Pick<BundlerStartOptions, 'port' | 'location'>> = {}\n ) {\n assert(options?.port, 'Dev server instance not found');\n assert(!this.urlCreator, 'Dev server is already initialized');\n const urlCreator = await UrlCreator.init(options.location, {\n port: options.port,\n getTunnelUrl: this.getTunnelUrl.bind(this),\n });\n this.urlCreator = urlCreator;\n return urlCreator;\n }\n\n public getUrlCreator() {\n assert(this.urlCreator, 'Dev server is uninitialized');\n return this.urlCreator;\n }\n\n public getNativeRuntimeUrl(opts: Partial<CreateURLOptions> = {}) {\n return this.isDevClient\n ? (this.getUrlCreator().constructDevClientUrl(opts) ?? this.getDevServerUrl())\n : this.getUrlCreator().constructUrl({ ...opts, scheme: 'exp' });\n }\n\n /** Get the URL for the running instance of the dev server. */\n public getDevServerUrl(options: { hostType?: 'localhost' } = {}): string | null {\n const instance = this.getInstance();\n if (!instance?.location) {\n return null;\n }\n\n // If we have an active WS tunnel instance, we always need to return the tunnel location.\n if (this.tunnel && this.tunnel instanceof AsyncWsTunnel) {\n return this.getUrlCreator().constructUrl();\n }\n\n const { location } = instance;\n if (options.hostType === 'localhost') {\n return `${location.protocol}://localhost:${location.port}`;\n }\n\n return location.url ?? null;\n }\n\n public getDevServerUrlOrAssert(options: { hostType?: 'localhost' } = {}): string {\n const instance = this.getDevServerUrl(options);\n if (!instance) {\n throw new CommandError(\n 'DEV_SERVER',\n `Cannot get the dev server URL before the server has started - bundler[${this.name}]`\n );\n }\n\n return instance;\n }\n\n /** Get the base URL for JS inspector */\n public getJsInspectorBaseUrl(): string {\n if (this.name !== 'metro') {\n throw new CommandError(\n 'DEV_SERVER',\n `Cannot get the JS inspector base url - bundler[${this.name}]`\n );\n }\n return this.getUrlCreator().constructUrl({ scheme: 'http' });\n }\n\n /** Get the tunnel URL from the tunnel. */\n public getTunnelUrl(): string | null {\n return this.tunnel?.getActiveUrl() ?? null;\n }\n\n /** Open the dev server in a runtime. */\n public async openPlatformAsync(\n launchTarget: keyof PlatformManagers | 'desktop',\n resolver: BaseResolveDeviceProps<any> = {}\n ) {\n if (launchTarget === 'desktop') {\n const serverUrl = this.getDevServerUrl({ hostType: 'localhost' });\n // Allow opening the tunnel URL when using Metro web.\n const url = this.name === 'metro' ? (this.getTunnelUrl() ?? serverUrl) : serverUrl;\n // Only launch the browser automatically if the process is interactive, otherwise we'll assume it's an agent.\n if (isInteractive()) {\n await openBrowserAsync(url!);\n }\n return { url };\n }\n\n const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';\n const manager = await this.getPlatformManagerAsync(launchTarget);\n return manager.openAsync({ runtime }, resolver);\n }\n\n /** Open the dev server in a runtime. */\n public async openCustomRuntimeAsync<Platform extends keyof PlatformManagers>(\n launchTarget: Platform,\n launchProps: Partial<PlatformLaunchProps<Platform>> = {},\n resolver: BaseResolveDeviceProps<PlatformDevice<Platform>> = {}\n ) {\n const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';\n if (runtime !== 'custom') {\n throw new CommandError(\n `dev server cannot open custom runtimes either because it does not target native platforms or because it is not targeting dev clients. (target: ${runtime})`\n );\n }\n\n const manager = await this.getPlatformManagerAsync(launchTarget);\n return manager.openAsync(\n { runtime: 'custom', props: launchProps },\n resolver as BaseResolveDeviceProps<any>\n );\n }\n\n /** Get the URL for opening in Expo Go. */\n protected getExpoGoUrl(): string {\n return this.getUrlCreator().constructUrl({ scheme: 'exp' });\n }\n\n /** Should use the interstitial page for selecting which runtime to use. */\n protected isRedirectPageEnabled(): boolean {\n return (\n !env.EXPO_NO_REDIRECT_PAGE &&\n // if user passed --dev-client flag, skip interstitial page\n !this.isDevClient &&\n // Checks if dev client is installed.\n !!resolveFrom.silent(this.projectRoot, 'expo-dev-client')\n );\n }\n\n /** Get the redirect URL when redirecting is enabled. */\n public getRedirectUrl(platform: keyof PlatformManagers | null = null): string | null {\n if (!this.isRedirectPageEnabled()) {\n debug('Redirect page is disabled');\n return null;\n }\n\n return (\n this.getUrlCreator().constructLoadingUrl(\n {},\n platform === 'emulator' ? 'android' : platform === 'simulator' ? 'ios' : null\n ) ?? null\n );\n }\n\n protected async getPlatformManagerAsync<Platform extends keyof PlatformManagers>(\n ofPlatform: Platform\n ): Promise<PlatformManagers[Platform]> {\n const platform: keyof PlatformManagers = ofPlatform;\n if (!this.platformManagers[platform]) {\n const port = this.getInstance()?.location.port;\n if (!port || !this.urlCreator) {\n throw new CommandError(\n 'DEV_SERVER',\n 'Cannot interact with native platforms until dev server has started'\n );\n }\n debug(`Creating platform manager (platform: ${platform}, port: ${port})`);\n const managerParams = {\n getCustomRuntimeUrl: this.urlCreator.constructDevClientUrl.bind(this.urlCreator),\n getExpoGoUrl: this.getExpoGoUrl.bind(this),\n getRedirectUrl: this.getRedirectUrl.bind(this, platform),\n getDevServerUrl: this.getDevServerUrl.bind(this, { hostType: 'localhost' }),\n };\n switch (platform) {\n case 'simulator': {\n const Manager = PLATFORM_MANAGERS[platform]();\n this.platformManagers[platform] = new Manager(this.projectRoot, port, managerParams);\n break;\n }\n case 'emulator': {\n const Manager = PLATFORM_MANAGERS[platform]();\n this.platformManagers[platform] = new Manager(this.projectRoot, port, managerParams);\n break;\n }\n }\n }\n return this.platformManagers[platform] as PlatformManagers[Platform];\n }\n}\n"],"names":["BundlerDevServer","debug","require","PLATFORM_MANAGERS","simulator","ApplePlatformManager","emulator","AndroidPlatformManager","projectRoot","platformBundlers","options","tunnel","devSession","bonjour","instance","platformManagers","urlCreator","notifier","devToolsPluginManager","DevToolsPluginManager","isDevClient","setInstance","getManifestMiddlewareAsync","Middleware","ExpoGoManifestHandlerMiddleware","getUrlCreator","middleware","constructUrl","bind","mode","minify","isNativeWebpack","name","isTargetingNative","privateKeyPath","startAsync","stopAsync","headless","startHeadlessAsync","startImplementationAsync","postStartAsync","waitForTypeScriptAsync","watchEnvironmentVariables","port","CommandError","initUrlCreator","server","close","callback","addListener","location","host","url","protocol","messageSocket","broadcast","hostType","env","EXPO_OFFLINE","_startTunnelAsync","envIsWebcontainer","isExporting","Promise","all","startDevSessionAsync","startBonjourAsync","watchConfig","stopObserving","FileNotifier","getConfigModuleIds","startObserving","getInstance","_createTunnel","useV2Tunnel","EXPO_UNSTABLE_TUNNEL_V2","useExpoAccount","AsyncWsTunnel","AsyncNgrok","DevelopmentSession","getNativeRuntimeUrl","getDevServerUrl","runtime","Bonjour","announceAsync","isTargetingWeb","web","broadcastMessage","method","params","undefined","closeAsync","catch","e","Log","error","exception","resolveWithTimeout","resolve","reject","code","timeout","errorMessage","assert","UrlCreator","init","getTunnelUrl","opts","constructDevClientUrl","scheme","getDevServerUrlOrAssert","getJsInspectorBaseUrl","getActiveUrl","openPlatformAsync","launchTarget","resolver","serverUrl","isInteractive","openBrowserAsync","manager","getPlatformManagerAsync","openAsync","openCustomRuntimeAsync","launchProps","props","getExpoGoUrl","isRedirectPageEnabled","EXPO_NO_REDIRECT_PAGE","resolveFrom","silent","getRedirectUrl","platform","constructLoadingUrl","ofPlatform","managerParams","getCustomRuntimeUrl","Manager"],"mappings":";;;;+BAkGsBA;;;eAAAA;;;;gEAlGH;;;;;;;gEACK;;;;;;4BAEG;+BACG;yBACN;8EACU;oCACC;4BAER;6DAEN;8BACQ;uBACM;qBACI;wBACV;6BACC;sBACG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGjC,MAAMC,QAAQC,QAAQ,SAAS;AA2D/B,MAAMC,oBAAoB;IACxBC,W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tH,UAAU,CAAC2F,qBAAqB,CAAC/E,IAAI,CAAC,IAAI,CAACZ,UAAU;gBAC/E4G,cAAc,IAAI,CAACA,YAAY,CAAChG,IAAI,CAAC,IAAI;gBACzCqG,gBAAgB,IAAI,CAACA,cAAc,CAACrG,IAAI,CAAC,IAAI,EAAEsG;gBAC/ClD,iBAAiB,IAAI,CAACA,eAAe,CAACpD,IAAI,CAAC,IAAI,EAAE;oBAAE4B,UAAU;gBAAY;YAC3E;YACA,OAAQ0E;gBACN,KAAK;oBAAa;wBAChB,MAAMK,UAAUpI,iBAAiB,CAAC+H,SAAS;wBAC3C,IAAI,CAACnH,gBAAgB,CAACmH,SAAS,GAAG,IAAIK,QAAQ,IAAI,CAAC/H,WAAW,EAAEmC,MAAM0F;wBACtE;oBACF;gBACA,KAAK;oBAAY;wBACf,MAAME,UAAUpI,iBAAiB,CAAC+H,SAAS;wBAC3C,IAAI,CAACnH,gBAAgB,CAACmH,SAAS,GAAG,IAAIK,QAAQ,IAAI,CAAC/H,WAAW,EAAEmC,MAAM0F;wBACtE;oBACF;YACF;QACF;QACA,OAAO,IAAI,CAACtH,gBAAgB,CAACmH,SAAS;IACxC;AACF"}
1
+ {"version":3,"sources":["../../../../src/start/server/BundlerDevServer.ts"],"sourcesContent":["import assert from 'assert';\nimport resolveFrom from 'resolve-from';\n\nimport { AsyncNgrok } from './AsyncNgrok';\nimport { AsyncWsTunnel } from './AsyncWsTunnel';\nimport { Bonjour } from './Bonjour';\nimport DevToolsPluginManager from './devtools/DevToolsPluginManager';\nimport { DevelopmentSession } from './DevelopmentSession';\nimport type { CreateURLOptions } from './UrlCreator';\nimport { UrlCreator } from './UrlCreator';\nimport type { PlatformBundlers } from './platformBundlers';\nimport * as Log from '../../log';\nimport { FileNotifier } from '../../utils/FileNotifier';\nimport { resolveWithTimeout } from '../../utils/delay';\nimport { env, envIsWebcontainer } from '../../utils/env';\nimport { CommandError } from '../../utils/errors';\nimport { isInteractive } from '../../utils/interactive';\nimport { openBrowserAsync } from '../../utils/open';\nimport type { BaseResolveDeviceProps, PlatformManager } from '../platforms/PlatformManager';\n\nconst debug = require('debug')('expo:start:server:devServer') as typeof console.log;\n\nexport type MessageSocket = {\n broadcast: (method: string, params?: Record<string, any> | undefined) => void;\n};\n\nexport type ServerLike = {\n close(callback?: (err?: Error) => void): void;\n addListener?(event: string, listener: (...args: any[]) => void): unknown;\n};\n\nexport type DevServerInstance = {\n /** Bundler dev server instance. */\n server: ServerLike;\n /** Dev server URL location properties. */\n location: {\n url: string;\n port: number;\n protocol: 'http' | 'https';\n host?: string;\n };\n /** Additional middleware that's attached to the `server`. */\n middleware: any;\n /** Message socket for communicating with the runtime. */\n messageSocket: MessageSocket;\n};\n\nexport interface BundlerStartOptions {\n /** Should the dev server use `https` protocol. */\n https?: boolean;\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Is dev client enabled. */\n devClient?: boolean;\n /** Should run dev servers with clean caches. */\n resetDevServer?: boolean;\n /** Code signing private key path (defaults to same directory as certificate) */\n privateKeyPath?: string;\n\n /** Max amount of workers (threads) to use with Metro bundler, defaults to undefined for max workers. */\n maxWorkers?: number;\n /** Port to start the dev server on. */\n port?: number;\n\n /** Should start a headless dev server e.g. mock representation to approximate info from a server running in a different process. */\n headless?: boolean;\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n\n /** Will the bundler be used for exporting. NOTE: This is an odd option to pass to the dev server. */\n isExporting?: boolean;\n\n // Webpack options\n /** Should modify and create PWA icons. */\n isImageEditingEnabled?: boolean;\n\n location: CreateURLOptions;\n}\n\nconst PLATFORM_MANAGERS = {\n simulator: () =>\n require('../platforms/ios/ApplePlatformManager')\n .ApplePlatformManager as typeof import('../platforms/ios/ApplePlatformManager').ApplePlatformManager,\n emulator: () =>\n require('../platforms/android/AndroidPlatformManager')\n .AndroidPlatformManager as typeof import('../platforms/android/AndroidPlatformManager').AndroidPlatformManager,\n};\n\ntype PlatformManagers = {\n [K in keyof typeof PLATFORM_MANAGERS]: InstanceType<ReturnType<(typeof PLATFORM_MANAGERS)[K]>>;\n};\n\ntype PlatformDevice<Platform extends keyof PlatformManagers> =\n PlatformManagers[Platform] extends PlatformManager<infer Device, any> ? Device : never;\n\ntype PlatformLaunchProps<Platform extends keyof PlatformManagers> =\n PlatformManagers[Platform] extends PlatformManager<any, infer LaunchProps> ? LaunchProps : never;\n\nexport abstract class BundlerDevServer {\n /** Name of the bundler. */\n abstract get name(): string;\n\n /** Tunnel instance for managing tunnel connections. */\n protected tunnel: AsyncNgrok | AsyncWsTunnel | null = null;\n /** Interfaces with the Expo 'Development Session' API. */\n protected devSession: DevelopmentSession | null = null;\n /** Announces dev server via Bonjour */\n protected bonjour: Bonjour | null = null;\n /** Http server and related info. */\n protected instance: DevServerInstance | null = null;\n /** Native platform interfaces for opening projects. */\n private platformManagers: { [K in keyof PlatformManagers]?: PlatformManagers[K] | undefined } =\n {};\n /** Manages the creation of dev server URLs. */\n protected urlCreator?: UrlCreator | null = null;\n\n private notifier: FileNotifier | null = null;\n protected readonly devToolsPluginManager: DevToolsPluginManager;\n public isDevClient: boolean;\n\n constructor(\n /** Project root folder. */\n public projectRoot: string,\n /** A mapping of bundlers to platforms. */\n public platformBundlers: PlatformBundlers,\n /** Advanced options */\n options?: {\n /**\n * The instance of DevToolsPluginManager\n * @default new DevToolsPluginManager(projectRoot)\n */\n devToolsPluginManager?: DevToolsPluginManager;\n // TODO: Replace with custom scheme maybe...\n isDevClient?: boolean;\n }\n ) {\n this.devToolsPluginManager =\n options?.devToolsPluginManager ?? new DevToolsPluginManager(projectRoot);\n this.isDevClient = options?.isDevClient ?? false;\n }\n\n protected setInstance(instance: DevServerInstance) {\n this.instance = instance;\n }\n\n /** Get the manifest middleware function. */\n protected async getManifestMiddlewareAsync(\n options: Pick<BundlerStartOptions, 'minify' | 'mode' | 'privateKeyPath'> = {}\n ) {\n const Middleware = require('./middleware/ExpoGoManifestHandlerMiddleware')\n .ExpoGoManifestHandlerMiddleware as typeof import('./middleware/ExpoGoManifestHandlerMiddleware').ExpoGoManifestHandlerMiddleware;\n\n const urlCreator = this.getUrlCreator();\n const middleware = new Middleware(this.projectRoot, {\n constructUrl: urlCreator.constructUrl.bind(urlCreator),\n mode: options.mode,\n minify: options.minify,\n isNativeWebpack: this.name === 'webpack' && this.isTargetingNative(),\n privateKeyPath: options.privateKeyPath,\n });\n return middleware;\n }\n\n /** Start the dev server using settings defined in the start command. */\n public async startAsync(options: BundlerStartOptions): Promise<DevServerInstance> {\n await this.stopAsync();\n\n let instance: DevServerInstance;\n if (options.headless) {\n instance = await this.startHeadlessAsync(options);\n } else {\n instance = await this.startImplementationAsync(options);\n }\n\n this.setInstance(instance);\n await this.postStartAsync(options);\n return instance;\n }\n\n protected abstract startImplementationAsync(\n options: BundlerStartOptions\n ): Promise<DevServerInstance>;\n\n public async waitForTypeScriptAsync(): Promise<boolean> {\n return false;\n }\n\n public abstract startTypeScriptServices(): Promise<void>;\n\n public async watchEnvironmentVariables(): Promise<void> {\n // noop -- We've only implemented this functionality in Metro.\n }\n\n /**\n * Creates a mock server representation that can be used to estimate URLs for a server started in another process.\n * This is used for the run commands where you can reuse the server from a previous run.\n */\n private async startHeadlessAsync(options: BundlerStartOptions): Promise<DevServerInstance> {\n if (!options.port)\n throw new CommandError('HEADLESS_SERVER', 'headless dev server requires a port option');\n await this.initUrlCreator(options);\n return {\n // Create a mock server\n server: {\n close: (callback: () => void) => {\n this.instance = null;\n callback?.();\n },\n addListener() {},\n },\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 broadcast: () => {\n throw new CommandError('HEADLESS_SERVER', 'Cannot broadcast messages to headless server');\n },\n },\n };\n }\n\n /**\n * Runs after the `startAsync` function, performing any additional common operations.\n * You can assume the dev server is started by the time this function is called.\n */\n protected async postStartAsync(options: BundlerStartOptions) {\n if (\n options.location.hostType === 'tunnel' &&\n !env.EXPO_OFFLINE &&\n // This is a hack to prevent using tunnel on web since we block it upstream for some reason.\n this.isTargetingNative()\n ) {\n await this._startTunnelAsync();\n } else if (envIsWebcontainer()) {\n await this._startTunnelAsync();\n }\n\n if (!options.isExporting) {\n await Promise.all([this.startDevSessionAsync(), this.startBonjourAsync()]);\n this.watchConfig();\n }\n }\n\n protected abstract getConfigModuleIds(): string[];\n\n protected watchConfig() {\n this.notifier?.stopObserving();\n this.notifier = new FileNotifier(this.projectRoot, this.getConfigModuleIds());\n this.notifier.startObserving();\n }\n\n /** Create the tunnel instance and start the tunnel server. Exposed for testing. */\n public async _startTunnelAsync(): Promise<AsyncNgrok | AsyncWsTunnel | null> {\n const port = this.getInstance()?.location.port;\n if (!port) return null;\n debug('[tunnel] connect to port: ' + port);\n this.tunnel = this._createTunnel(port);\n await this.tunnel.startAsync();\n return this.tunnel;\n }\n\n /** Resolve which tunnel implementation to use, without starting it. */\n private _createTunnel(port: number): AsyncNgrok | AsyncWsTunnel {\n const useV2Tunnel = env.EXPO_UNSTABLE_TUNNEL_V2 || envIsWebcontainer();\n if (useV2Tunnel) {\n const useExpoAccount = !!env.EXPO_UNSTABLE_TUNNEL_V2;\n return new AsyncWsTunnel(this.projectRoot, port, { useExpoAccount });\n }\n\n return new AsyncNgrok(this.projectRoot, port);\n }\n\n protected async startDevSessionAsync() {\n // This is used to make Expo Go open the project in either Expo Go, or the web browser.\n // Must come after ngrok (`startTunnelAsync`) setup.\n this.devSession = new DevelopmentSession(\n this.projectRoot,\n // This URL will be used on external devices so the computer IP won't be relevant.\n this.isTargetingNative()\n ? this.getNativeRuntimeUrl()\n : this.getDevServerUrl({ hostType: 'localhost' })\n );\n\n await this.devSession.startAsync({\n runtime: this.isTargetingNative() ? 'native' : 'web',\n });\n }\n\n protected async startBonjourAsync() {\n // This is used to make Expo Go open the project in either Expo Go, or the web browser.\n // Must come after ngrok (`startTunnelAsync`) setup.\n if (!this.bonjour) {\n this.bonjour = new Bonjour(this.projectRoot, this.getInstance()?.location.port);\n }\n\n await this.bonjour.announceAsync({});\n }\n\n public isTargetingNative() {\n // Temporary hack while we implement multi-bundler dev server proxy.\n return true;\n }\n\n public isTargetingWeb() {\n return this.platformBundlers.web === this.name;\n }\n\n /**\n * Sends a message over web sockets to any connected device,\n * does nothing when the dev server is not running.\n *\n * @param method name of the command. In RN projects `reload`, and `devMenu` are available. In Expo Go, `sendDevCommand` is available.\n * @param params\n */\n public broadcastMessage(\n method: 'reload' | 'devMenu' | 'sendDevCommand',\n params?: Record<string, any>\n ) {\n this.getInstance()?.messageSocket.broadcast(method, params);\n }\n\n /** Get the running dev server instance. */\n public getInstance() {\n return this.instance;\n }\n\n /** Stop the running dev server instance. */\n async stopAsync() {\n // Reset url creator\n this.urlCreator = undefined;\n\n // Stop file watching.\n this.notifier?.stopObserving();\n\n await Promise.all([\n // Stop the bonjour advertiser\n this.bonjour?.closeAsync(),\n // Stop the dev session timer and tell Expo API to remove dev session.\n this.devSession?.closeAsync(),\n ]);\n\n // Stop tunnel if running.\n await this.tunnel?.stopAsync().catch((e) => {\n Log.error(`Error stopping tunnel:`);\n Log.exception(e);\n });\n\n return resolveWithTimeout(\n () =>\n new Promise<void>((resolve, reject) => {\n // Close the server.\n debug(`Stopping dev server (bundler: ${this.name})`);\n\n if (this.instance?.server) {\n // Check if server is even running.\n this.instance.server.close((error) => {\n debug(`Stopped dev server (bundler: ${this.name})`);\n this.instance = null;\n if (error) {\n if ('code' in error && error.code === 'ERR_SERVER_NOT_RUNNING') {\n resolve();\n } else {\n reject(error);\n }\n } else {\n resolve();\n }\n });\n } else {\n debug(`Stopped dev server (bundler: ${this.name})`);\n this.instance = null;\n resolve();\n }\n }),\n {\n // NOTE(Bacon): Metro dev server doesn't seem to be closing in time.\n timeout: 1000,\n errorMessage: `Timeout waiting for '${this.name}' dev server to close`,\n }\n );\n }\n\n // TODO(@kitten): This should be created top-down rather than bottom up from implementors\n protected async initUrlCreator(\n options: Partial<Pick<BundlerStartOptions, 'port' | 'location'>> = {}\n ) {\n assert(options?.port, 'Dev server instance not found');\n assert(!this.urlCreator, 'Dev server is already initialized');\n const urlCreator = await UrlCreator.init(options.location, {\n port: options.port,\n getTunnelUrl: this.getTunnelUrl.bind(this),\n });\n this.urlCreator = urlCreator;\n return urlCreator;\n }\n\n public getUrlCreator() {\n assert(this.urlCreator, 'Dev server is uninitialized');\n return this.urlCreator;\n }\n\n public getNativeRuntimeUrl(opts: Partial<CreateURLOptions> = {}) {\n return this.isDevClient\n ? (this.getUrlCreator().constructDevClientUrl(opts) ?? this.getDevServerUrl())\n : this.getUrlCreator().constructExpoGoUrl(opts);\n }\n\n /** Get the URL for the running instance of the dev server. */\n public getDevServerUrl(options: { hostType?: 'localhost' } = {}): string | null {\n const instance = this.getInstance();\n if (!instance?.location) {\n return null;\n }\n\n // If we have an active WS tunnel instance, we always need to return the tunnel location.\n if (this.tunnel && this.tunnel instanceof AsyncWsTunnel) {\n return this.getUrlCreator().constructUrl({ scheme: 'http' });\n }\n\n const { location } = instance;\n if (options.hostType === 'localhost') {\n return `${location.protocol}://localhost:${location.port}`;\n }\n\n return location.url ?? null;\n }\n\n public getDevServerUrlOrAssert(options: { hostType?: 'localhost' } = {}): string {\n const instance = this.getDevServerUrl(options);\n if (!instance) {\n throw new CommandError(\n 'DEV_SERVER',\n `Cannot get the dev server URL before the server has started - bundler[${this.name}]`\n );\n }\n\n return instance;\n }\n\n /** Get the base URL for JS inspector */\n public getJsInspectorBaseUrl(): string {\n if (this.name !== 'metro') {\n throw new CommandError(\n 'DEV_SERVER',\n `Cannot get the JS inspector base url - bundler[${this.name}]`\n );\n }\n return this.getUrlCreator().constructUrl({ scheme: 'http' });\n }\n\n /** Get the tunnel URL from the tunnel. */\n public getTunnelUrl(): string | null {\n return this.tunnel?.getActiveUrl() ?? null;\n }\n\n /** Open the dev server in a runtime. */\n public async openPlatformAsync(\n launchTarget: keyof PlatformManagers | 'desktop',\n resolver: BaseResolveDeviceProps<any> = {}\n ) {\n if (launchTarget === 'desktop') {\n const serverUrl = this.getDevServerUrl({ hostType: 'localhost' });\n // Allow opening the tunnel URL when using Metro web.\n const url = this.name === 'metro' ? (this.getTunnelUrl() ?? serverUrl) : serverUrl;\n // Only launch the browser automatically if the process is interactive, otherwise we'll assume it's an agent.\n if (isInteractive()) {\n await openBrowserAsync(url!);\n }\n return { url };\n }\n\n const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';\n const manager = await this.getPlatformManagerAsync(launchTarget);\n return manager.openAsync({ runtime }, resolver);\n }\n\n /** Open the dev server in a runtime. */\n public async openCustomRuntimeAsync<Platform extends keyof PlatformManagers>(\n launchTarget: Platform,\n launchProps: Partial<PlatformLaunchProps<Platform>> = {},\n resolver: BaseResolveDeviceProps<PlatformDevice<Platform>> = {}\n ) {\n const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';\n if (runtime !== 'custom') {\n throw new CommandError(\n `dev server cannot open custom runtimes either because it does not target native platforms or because it is not targeting dev clients. (target: ${runtime})`\n );\n }\n\n const manager = await this.getPlatformManagerAsync(launchTarget);\n return manager.openAsync(\n { runtime: 'custom', props: launchProps },\n resolver as BaseResolveDeviceProps<any>\n );\n }\n\n /** Get the URL for opening in Expo Go. */\n protected getExpoGoUrl(): string {\n return this.getUrlCreator().constructExpoGoUrl();\n }\n\n /** Should use the interstitial page for selecting which runtime to use. */\n protected isRedirectPageEnabled(): boolean {\n return (\n !env.EXPO_NO_REDIRECT_PAGE &&\n // if user passed --dev-client flag, skip interstitial page\n !this.isDevClient &&\n // Checks if dev client is installed.\n !!resolveFrom.silent(this.projectRoot, 'expo-dev-client')\n );\n }\n\n /** Get the redirect URL when redirecting is enabled. */\n public getRedirectUrl(platform: keyof PlatformManagers | null = null): string | null {\n if (!this.isRedirectPageEnabled()) {\n debug('Redirect page is disabled');\n return null;\n }\n\n return (\n this.getUrlCreator().constructLoadingUrl(\n {},\n platform === 'emulator' ? 'android' : platform === 'simulator' ? 'ios' : null\n ) ?? null\n );\n }\n\n protected async getPlatformManagerAsync<Platform extends keyof PlatformManagers>(\n ofPlatform: Platform\n ): Promise<PlatformManagers[Platform]> {\n const platform: keyof PlatformManagers = ofPlatform;\n if (!this.platformManagers[platform]) {\n const port = this.getInstance()?.location.port;\n if (!port || !this.urlCreator) {\n throw new CommandError(\n 'DEV_SERVER',\n 'Cannot interact with native platforms until dev server has started'\n );\n }\n debug(`Creating platform manager (platform: ${platform}, port: ${port})`);\n const managerParams = {\n getCustomRuntimeUrl: this.urlCreator.constructDevClientUrl.bind(this.urlCreator),\n getExpoGoUrl: this.getExpoGoUrl.bind(this),\n getRedirectUrl: this.getRedirectUrl.bind(this, platform),\n getDevServerUrl: this.getDevServerUrl.bind(this, { hostType: 'localhost' }),\n };\n switch (platform) {\n case 'simulator': {\n const Manager = PLATFORM_MANAGERS[platform]();\n this.platformManagers[platform] = new Manager(this.projectRoot, port, managerParams);\n break;\n }\n case 'emulator': {\n const Manager = PLATFORM_MANAGERS[platform]();\n this.platformManagers[platform] = new Manager(this.projectRoot, port, managerParams);\n break;\n }\n }\n }\n return this.platformManagers[platform] as PlatformManagers[Platform];\n }\n}\n"],"names":["BundlerDevServer","debug","require","PLATFORM_MANAGERS","simulator","ApplePlatformManager","emulator","AndroidPlatformManager","projectRoot","platformBundlers","options","tunnel","devSession","bonjour","instance","platformManagers","urlCreator","notifier","devToolsPluginManager","DevToolsPluginManager","isDevClient","setInstance","getManifestMiddlewareAsync","Middleware","ExpoGoManifestHandlerMiddleware","getUrlCreator","middleware","constructUrl","bind","mode","minify","isNativeWebpack","name","isTargetingNative","privateKeyPath","startAsync","stopAsync","headless","startHeadlessAsync","startImplementationAsync","postStartAsync","waitForTypeScriptAsync","watchEnvironmentVariables","port","CommandError","initUrlCreator","server","close","callback","addListener","location","host","url","protocol","messageSocket","broadcast","hostType","env","EXPO_OFFLINE","_startTunnelAsync","envIsWebcontainer","isExporting","Promise","all","startDevSessionAsync","startBonjourAsync","watchConfig","stopObserving","FileNotifier","getConfigModuleIds","startObserving","getInstance","_createTunnel","useV2Tunnel","EXPO_UNSTABLE_TUNNEL_V2","useExpoAccount","AsyncWsTunnel","AsyncNgrok","DevelopmentSession","getNativeRuntimeUrl","getDevServerUrl","runtime","Bonjour","announceAsync","isTargetingWeb","web","broadcastMessage","method","params","undefined","closeAsync","catch","e","Log","error","exception","resolveWithTimeout","resolve","reject","code","timeout","errorMessage","assert","UrlCreator","init","getTunnelUrl","opts","constructDevClientUrl","constructExpoGoUrl","scheme","getDevServerUrlOrAssert","getJsInspectorBaseUrl","getActiveUrl","openPlatformAsync","launchTarget","resolver","serverUrl","isInteractive","openBrowserAsync","manager","getPlatformManagerAsync","openAsync","openCustomRuntimeAsync","launchProps","props","getExpoGoUrl","isRedirectPageEnabled","EXPO_NO_REDIRECT_PAGE","resolveFrom","silent","getRedirectUrl","platform","constructLoadingUrl","ofPlatform","managerParams","getCustomRuntimeUrl","Manager"],"mappings":";;;;+BAkGsBA;;;eAAAA;;;;gEAlGH;;;;;;;gEACK;;;;;;4BAEG;+BACG;yBACN;8EACU;oCACC;4BAER;6DAEN;8BACQ;uBACM;qBACI;wBACV;6BACC;sBACG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGjC,MAAMC,QAAQC,QAAQ,SAAS;AA2D/B,MAAMC,oBAAoB;IACxBC,WAAW,IACTF,QAAQ,yCACLG,oBAAoB;IACzBC,UAAU,IACRJ,QAAQ,+CACLK,sBAAsB;AAC7B;AAYO,MAAeP;IAsBpB,YACE,yBAAyB,GACzB,AAAOQ,WAAmB,EAC1B,wCAAwC,GACxC,AAAOC,gBAAkC,EACzC,qBAAqB,GACrBC,OAQC,CACD;aAbOF,cAAAA;aAEAC,mBAAAA;QAtBT,qDAAqD,QAC3CE,SAA4C;QACtD,wDAAwD,QAC9CC,aAAwC;QAClD,qCAAqC,QAC3BC,UAA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gI,SAAS;wBAC3C,IAAI,CAACpH,gBAAgB,CAACoH,SAAS,GAAG,IAAIK,QAAQ,IAAI,CAAChI,WAAW,EAAEmC,MAAM2F;wBACtE;oBACF;gBACA,KAAK;oBAAY;wBACf,MAAME,UAAUrI,iBAAiB,CAACgI,SAAS;wBAC3C,IAAI,CAACpH,gBAAgB,CAACoH,SAAS,GAAG,IAAIK,QAAQ,IAAI,CAAChI,WAAW,EAAEmC,MAAM2F;wBACtE;oBACF;YACF;QACF;QACA,OAAO,IAAI,CAACvH,gBAAgB,CAACoH,SAAS;IACxC;AACF"}
@@ -29,7 +29,7 @@ function _chalk() {
29
29
  };
30
30
  return data;
31
31
  }
32
- const _DevToolsPluginManager = /*#__PURE__*/ _interop_require_default(require("./DevToolsPluginManager"));
32
+ const _DevToolsPluginManager = /*#__PURE__*/ _interop_require_default(require("./devtools/DevToolsPluginManager"));
33
33
  const _platformBundlers = require("./platformBundlers");
34
34
  const _log = require("../../log");
35
35
  const _FileNotifier = require("../../utils/FileNotifier");
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/start/server/DevServerManager.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\nimport { getConfig } from '@expo/config';\nimport assert from 'assert';\nimport chalk from 'chalk';\n\nimport type { BundlerDevServer, BundlerStartOptions } from './BundlerDevServer';\nimport DevToolsPluginManager from './DevToolsPluginManager';\nimport { getPlatformBundlers } from './platformBundlers';\nimport { Log } from '../../log';\nimport { FileNotifier } from '../../utils/FileNotifier';\nimport { env } from '../../utils/env';\nimport type { ProjectPrerequisite } from '../doctor/Prerequisite';\nimport { TypeScriptProjectPrerequisite } from '../doctor/typescript/TypeScriptProjectPrerequisite';\nimport { printItem } from '../interface/commandsTable';\nimport * as AndroidDebugBridge from '../platforms/android/adb';\nimport { resolveSchemeAsync } from '../resolveOptions';\n\nconst debug = require('debug')('expo:start:server:devServerManager') as typeof console.log;\n\nexport type MultiBundlerStartOptions = {\n type: keyof typeof BUNDLERS;\n options?: BundlerStartOptions;\n}[];\n\nconst BUNDLERS = {\n webpack: () =>\n require('./webpack/WebpackBundlerDevServer')\n .WebpackBundlerDevServer as typeof import('./webpack/WebpackBundlerDevServer').WebpackBundlerDevServer,\n metro: () =>\n require('./metro/MetroBundlerDevServer')\n .MetroBundlerDevServer as typeof import('./metro/MetroBundlerDevServer').MetroBundlerDevServer,\n};\n\n/** Manages interacting with multiple dev servers. */\nexport class DevServerManager {\n private devServers: BundlerDevServer[] = [];\n\n static async startMetroAsync(projectRoot: string, startOptions: BundlerStartOptions) {\n const devServerManager = new DevServerManager(projectRoot, startOptions);\n\n await devServerManager.startAsync([\n {\n type: 'metro',\n options: startOptions,\n },\n ]);\n return devServerManager;\n }\n\n private projectPrerequisites: ProjectPrerequisite<any, void>[] = [];\n public readonly devtoolsPluginManager: DevToolsPluginManager;\n\n private notifier: FileNotifier | null = null;\n\n constructor(\n public projectRoot: string,\n /** Keep track of the original CLI options for bundlers that are started interactively. */\n public options: BundlerStartOptions\n ) {\n if (!options.isExporting) {\n this.notifier = this.watchBabelConfig();\n }\n this.devtoolsPluginManager = new DevToolsPluginManager(projectRoot);\n }\n\n private watchBabelConfig() {\n const notifier = new FileNotifier(\n this.projectRoot,\n [\n './babel.config.js',\n './babel.config.json',\n './.babelrc.json',\n './.babelrc',\n './.babelrc.js',\n ],\n {\n additionalWarning: chalk` You may need to clear the bundler cache with the {bold --clear} flag for your changes to take effect.`,\n }\n );\n\n notifier.startObserving();\n\n return notifier;\n }\n\n /** Lazily load and assert a project-level prerequisite. */\n async ensureProjectPrerequisiteAsync(PrerequisiteClass: typeof ProjectPrerequisite<any, any>) {\n let prerequisite = this.projectPrerequisites.find(\n (prerequisite) => prerequisite instanceof PrerequisiteClass\n );\n if (!prerequisite) {\n prerequisite = new PrerequisiteClass(this.projectRoot);\n this.projectPrerequisites.push(prerequisite);\n }\n return await prerequisite.assertAsync();\n }\n\n /**\n * Sends a message over web sockets to all connected devices,\n * does nothing when the dev server is not running.\n *\n * @param method name of the command. In RN projects `reload`, and `devMenu` are available. In Expo Go, `sendDevCommand` is available.\n * @param params extra event info to send over the socket.\n */\n broadcastMessage(method: 'reload' | 'devMenu' | 'sendDevCommand', params?: Record<string, any>) {\n this.devServers.forEach((server) => {\n server.broadcastMessage(method, params);\n });\n }\n\n /** Get the port for the dev server (either Webpack or Metro) that is hosting code for React Native runtimes. */\n getNativeDevServerPort() {\n const server = this.devServers.find((server) => server.isTargetingNative());\n return server?.getInstance()?.location.port ?? null;\n }\n\n /** Get the first server that targets web. */\n getWebDevServer() {\n const server = this.devServers.find((server) => server.isTargetingWeb());\n return server ?? null;\n }\n\n getDefaultDevServer(): BundlerDevServer {\n // Return the first native dev server otherwise return the first dev server.\n const server = this.devServers.find((server) => server.isTargetingNative());\n const defaultServer = server ?? this.devServers[0];\n assert(defaultServer, 'No dev servers are running');\n return defaultServer;\n }\n\n async ensureWebDevServerRunningAsync() {\n const [server] = this.devServers.filter((server) => server.isTargetingWeb());\n if (server) {\n return;\n }\n const { exp } = getConfig(this.projectRoot, {\n skipPlugins: true,\n skipSDKVersionRequirement: true,\n });\n const bundler = getPlatformBundlers(this.projectRoot, exp).web;\n debug(`Starting ${bundler} dev server for web`);\n return this.startAsync([\n {\n type: bundler,\n options: this.options,\n },\n ]);\n }\n\n /** Switch between Expo Go and Expo Dev Clients. */\n async toggleRuntimeMode(isUsingDevClient: boolean = !this.options.devClient): Promise<boolean> {\n const nextMode = isUsingDevClient ? '--dev-client' : '--go';\n Log.log(printItem(`Switching to ${chalk`{bold ${nextMode}}`}`, { dim: true }));\n Log.log();\n\n const nextScheme = await resolveSchemeAsync(this.projectRoot, {\n devClient: isUsingDevClient,\n // NOTE: The custom `--scheme` argument is lost from this point on.\n });\n\n this.options.location.scheme = nextScheme;\n this.options.devClient = isUsingDevClient;\n for (const devServer of this.devServers) {\n devServer.isDevClient = isUsingDevClient;\n // TODO(@kitten): Clean up mode switching better\n const urlCreator = devServer.getUrlCreator();\n urlCreator.defaults ??= {};\n urlCreator.defaults.scheme = nextScheme;\n }\n\n debug(`New runtime options (runtime: ${nextMode}):`, this.options);\n return true;\n }\n\n /** Start all dev servers. */\n async startAsync(startOptions: MultiBundlerStartOptions): Promise<ExpoConfig> {\n const { exp } = getConfig(this.projectRoot, { skipSDKVersionRequirement: true });\n const platformBundlers = getPlatformBundlers(this.projectRoot, exp);\n\n // Start all dev servers...\n for (const { type, options } of startOptions) {\n const BundlerDevServerClass = await BUNDLERS[type]();\n const server = new BundlerDevServerClass(this.projectRoot, platformBundlers, {\n devToolsPluginManager: this.devtoolsPluginManager,\n isDevClient: !!options?.devClient,\n });\n await server.startAsync(options ?? this.options);\n this.devServers.push(server);\n }\n\n return exp;\n }\n\n async bootstrapTypeScriptAsync() {\n const typescriptPrerequisite = await this.ensureProjectPrerequisiteAsync(\n TypeScriptProjectPrerequisite\n );\n\n if (env.EXPO_NO_TYPESCRIPT_SETUP) {\n return;\n }\n\n // Optionally, wait for the user to add TypeScript during the\n // development cycle.\n const server = this.devServers.find((server) => server.name === 'metro');\n if (!server) {\n return;\n }\n\n // The dev server shouldn't wait for the typescript services\n if (!typescriptPrerequisite) {\n server.waitForTypeScriptAsync().then(async (success) => {\n if (success) {\n server.startTypeScriptServices();\n }\n });\n } else {\n server.startTypeScriptServices();\n }\n }\n\n async watchEnvironmentVariables() {\n await this.devServers.find((server) => server.name === 'metro')?.watchEnvironmentVariables();\n }\n\n /** Stop all servers including ADB. */\n async stopAsync(): Promise<void> {\n await Promise.allSettled([\n this.notifier?.stopObserving(),\n // Stop ADB\n AndroidDebugBridge.getServer().stopAsync(),\n // Stop all dev servers\n ...this.devServers.map((server) =>\n server.stopAsync().catch((error) => {\n Log.error(`Failed to stop dev server (bundler: ${server.name})`);\n Log.exception(error);\n })\n ),\n ]);\n }\n}\n"],"names":["DevServerManager","debug","require","BUNDLERS","webpack","WebpackBundlerDevServer","metro","MetroBundlerDevServer","startMetroAsync","projectRoot","startOptions","devServerManager","startAsync","type","options","devServers","projectPrerequisites","notifier","isExporting","watchBabelConfig","devtoolsPluginManager","DevToolsPluginManager","FileNotifier","additionalWarning","chalk","startObserving","ensureProjectPrerequisiteAsync","PrerequisiteClass","prerequisite","find","push","assertAsync","broadcastMessage","method","params","forEach","server","getNativeDevServerPort","isTargetingNative","getInstance","location","port","getWebDevServer","isTargetingWeb","getDefaultDevServer","defaultServer","assert","ensureWebDevServerRunningAsync","filter","exp","getConfig","skipPlugins","skipSDKVersionRequirement","bundler","getPlatformBundlers","web","toggleRuntimeMode","isUsingDevClient","devClient","nextMode","Log","log","printItem","dim","nextScheme","resolveSchemeAsync","scheme","devServer","isDevClient","urlCreator","getUrlCreator","defaults","platformBundlers","BundlerDevServerClass","devToolsPluginManager","bootstrapTypeScriptAsync","typescriptPrerequisite","TypeScriptProjectPrerequisite","env","EXPO_NO_TYPESCRIPT_SETUP","name","waitForTypeScriptAsync","then","success","startTypeScriptServices","watchEnvironmentVariables","stopAsync","Promise","allSettled","stopObserving","AndroidDebugBridge","getServer","map","catch","error","exception"],"mappings":";;;;+BAkCaA;;;eAAAA;;;;yBAjCa;;;;;;;gEACP;;;;;;;gEACD;;;;;;8EAGgB;kCACE;qBAChB;8BACS;qBACT;+CAE0B;+BACpB;6DACU;gCACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEnC,MAAMC,QAAQC,QAAQ,SAAS;AAO/B,MAAMC,WAAW;IACfC,SAAS,IACPF,QAAQ,qCACLG,uBAAuB;IAC5BC,OAAO,IACLJ,QAAQ,iCACLK,qBAAqB;AAC5B;AAGO,MAAMP;IAGX,aAAaQ,gBAAgBC,WAAmB,EAAEC,YAAiC,EAAE;QACnF,MAAMC,mBAAmB,IAAIX,iBAAiBS,aAAaC;QAE3D,MAAMC,iBAAiBC,UAAU,CAAC;YAChC;gBACEC,MAAM;gBACNC,SAASJ;YACX;SACD;QACD,OAAOC;IACT;IAOA,YACE,AAAOF,WAAmB,EAC1B,wFAAwF,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;YAChC;QACF;QAEA,6DAA6D;QAC7D,qBAAqB;QACrB,MAAM3C,SAAS,IAAI,CAACrB,UAAU,CAACc,IAAI,CAAC,CAACO,SAAWA,OAAO4C,IAAI,KAAK;QAChE,IAAI,CAAC5C,QAAQ;YACX;QACF;QAEA,4DAA4D;QAC5D,IAAI,CAACwC,wBAAwB;YAC3BxC,OAAO6C,sBAAsB,GAAGC,IAAI,CAAC,OAAOC;gBAC1C,IAAIA,SAAS;oBACX/C,OAAOgD,uBAAuB;gBAChC;YACF;QACF,OAAO;YACLhD,OAAOgD,uBAAuB;QAChC;IACF;IAEA,MAAMC,4BAA4B;YAC1B;QAAN,QAAM,wBAAA,IAAI,CAACtE,UAAU,CAACc,IAAI,CAAC,CAACO,SAAWA,OAAO4C,IAAI,KAAK,6BAAjD,sBAA2DK,yBAAyB;IAC5F;IAEA,oCAAoC,GACpC,MAAMC,YAA2B;YAE7B;QADF,MAAMC,QAAQC,UAAU,CAAC;aACvB,iBAAA,IAAI,CAACvE,QAAQ,qBAAb,eAAewE,aAAa;YAC5B,WAAW;YACXC,KAAmBC,SAAS,GAAGL,SAAS;YACxC,uBAAuB;eACpB,IAAI,CAACvE,UAAU,CAAC6E,GAAG,CAAC,CAACxD,SACtBA,OAAOkD,SAAS,GAAGO,KAAK,CAAC,CAACC;oBACxBlC,QAAG,CAACkC,KAAK,CAAC,CAAC,oCAAoC,EAAE1D,OAAO4C,IAAI,CAAC,CAAC,CAAC;oBAC/DpB,QAAG,CAACmC,SAAS,CAACD;gBAChB;SAEH;IACH;AACF"}
1
+ {"version":3,"sources":["../../../../src/start/server/DevServerManager.ts"],"sourcesContent":["import type { ExpoConfig } from '@expo/config';\nimport { getConfig } from '@expo/config';\nimport assert from 'assert';\nimport chalk from 'chalk';\n\nimport type { BundlerDevServer, BundlerStartOptions } from './BundlerDevServer';\nimport DevToolsPluginManager from './devtools/DevToolsPluginManager';\nimport { getPlatformBundlers } from './platformBundlers';\nimport { Log } from '../../log';\nimport { FileNotifier } from '../../utils/FileNotifier';\nimport { env } from '../../utils/env';\nimport type { ProjectPrerequisite } from '../doctor/Prerequisite';\nimport { TypeScriptProjectPrerequisite } from '../doctor/typescript/TypeScriptProjectPrerequisite';\nimport { printItem } from '../interface/commandsTable';\nimport * as AndroidDebugBridge from '../platforms/android/adb';\nimport { resolveSchemeAsync } from '../resolveOptions';\n\nconst debug = require('debug')('expo:start:server:devServerManager') as typeof console.log;\n\nexport type MultiBundlerStartOptions = {\n type: keyof typeof BUNDLERS;\n options?: BundlerStartOptions;\n}[];\n\nconst BUNDLERS = {\n webpack: () =>\n require('./webpack/WebpackBundlerDevServer')\n .WebpackBundlerDevServer as typeof import('./webpack/WebpackBundlerDevServer').WebpackBundlerDevServer,\n metro: () =>\n require('./metro/MetroBundlerDevServer')\n .MetroBundlerDevServer as typeof import('./metro/MetroBundlerDevServer').MetroBundlerDevServer,\n};\n\n/** Manages interacting with multiple dev servers. */\nexport class DevServerManager {\n private devServers: BundlerDevServer[] = [];\n\n static async startMetroAsync(projectRoot: string, startOptions: BundlerStartOptions) {\n const devServerManager = new DevServerManager(projectRoot, startOptions);\n\n await devServerManager.startAsync([\n {\n type: 'metro',\n options: startOptions,\n },\n ]);\n return devServerManager;\n }\n\n private projectPrerequisites: ProjectPrerequisite<any, void>[] = [];\n public readonly devtoolsPluginManager: DevToolsPluginManager;\n\n private notifier: FileNotifier | null = null;\n\n constructor(\n public projectRoot: string,\n /** Keep track of the original CLI options for bundlers that are started interactively. */\n public options: BundlerStartOptions\n ) {\n if (!options.isExporting) {\n this.notifier = this.watchBabelConfig();\n }\n this.devtoolsPluginManager = new DevToolsPluginManager(projectRoot);\n }\n\n private watchBabelConfig() {\n const notifier = new FileNotifier(\n this.projectRoot,\n [\n './babel.config.js',\n './babel.config.json',\n './.babelrc.json',\n './.babelrc',\n './.babelrc.js',\n ],\n {\n additionalWarning: chalk` You may need to clear the bundler cache with the {bold --clear} flag for your changes to take effect.`,\n }\n );\n\n notifier.startObserving();\n\n return notifier;\n }\n\n /** Lazily load and assert a project-level prerequisite. */\n async ensureProjectPrerequisiteAsync(PrerequisiteClass: typeof ProjectPrerequisite<any, any>) {\n let prerequisite = this.projectPrerequisites.find(\n (prerequisite) => prerequisite instanceof PrerequisiteClass\n );\n if (!prerequisite) {\n prerequisite = new PrerequisiteClass(this.projectRoot);\n this.projectPrerequisites.push(prerequisite);\n }\n return await prerequisite.assertAsync();\n }\n\n /**\n * Sends a message over web sockets to all connected devices,\n * does nothing when the dev server is not running.\n *\n * @param method name of the command. In RN projects `reload`, and `devMenu` are available. In Expo Go, `sendDevCommand` is available.\n * @param params extra event info to send over the socket.\n */\n broadcastMessage(method: 'reload' | 'devMenu' | 'sendDevCommand', params?: Record<string, any>) {\n this.devServers.forEach((server) => {\n server.broadcastMessage(method, params);\n });\n }\n\n /** Get the port for the dev server (either Webpack or Metro) that is hosting code for React Native runtimes. */\n getNativeDevServerPort() {\n const server = this.devServers.find((server) => server.isTargetingNative());\n return server?.getInstance()?.location.port ?? null;\n }\n\n /** Get the first server that targets web. */\n getWebDevServer() {\n const server = this.devServers.find((server) => server.isTargetingWeb());\n return server ?? null;\n }\n\n getDefaultDevServer(): BundlerDevServer {\n // Return the first native dev server otherwise return the first dev server.\n const server = this.devServers.find((server) => server.isTargetingNative());\n const defaultServer = server ?? this.devServers[0];\n assert(defaultServer, 'No dev servers are running');\n return defaultServer;\n }\n\n async ensureWebDevServerRunningAsync() {\n const [server] = this.devServers.filter((server) => server.isTargetingWeb());\n if (server) {\n return;\n }\n const { exp } = getConfig(this.projectRoot, {\n skipPlugins: true,\n skipSDKVersionRequirement: true,\n });\n const bundler = getPlatformBundlers(this.projectRoot, exp).web;\n debug(`Starting ${bundler} dev server for web`);\n return this.startAsync([\n {\n type: bundler,\n options: this.options,\n },\n ]);\n }\n\n /** Switch between Expo Go and Expo Dev Clients. */\n async toggleRuntimeMode(isUsingDevClient: boolean = !this.options.devClient): Promise<boolean> {\n const nextMode = isUsingDevClient ? '--dev-client' : '--go';\n Log.log(printItem(`Switching to ${chalk`{bold ${nextMode}}`}`, { dim: true }));\n Log.log();\n\n const nextScheme = await resolveSchemeAsync(this.projectRoot, {\n devClient: isUsingDevClient,\n // NOTE: The custom `--scheme` argument is lost from this point on.\n });\n\n this.options.location.scheme = nextScheme;\n this.options.devClient = isUsingDevClient;\n for (const devServer of this.devServers) {\n devServer.isDevClient = isUsingDevClient;\n // TODO(@kitten): Clean up mode switching better\n const urlCreator = devServer.getUrlCreator();\n urlCreator.defaults ??= {};\n urlCreator.defaults.scheme = nextScheme;\n }\n\n debug(`New runtime options (runtime: ${nextMode}):`, this.options);\n return true;\n }\n\n /** Start all dev servers. */\n async startAsync(startOptions: MultiBundlerStartOptions): Promise<ExpoConfig> {\n const { exp } = getConfig(this.projectRoot, { skipSDKVersionRequirement: true });\n const platformBundlers = getPlatformBundlers(this.projectRoot, exp);\n\n // Start all dev servers...\n for (const { type, options } of startOptions) {\n const BundlerDevServerClass = await BUNDLERS[type]();\n const server = new BundlerDevServerClass(this.projectRoot, platformBundlers, {\n devToolsPluginManager: this.devtoolsPluginManager,\n isDevClient: !!options?.devClient,\n });\n await server.startAsync(options ?? this.options);\n this.devServers.push(server);\n }\n\n return exp;\n }\n\n async bootstrapTypeScriptAsync() {\n const typescriptPrerequisite = await this.ensureProjectPrerequisiteAsync(\n TypeScriptProjectPrerequisite\n );\n\n if (env.EXPO_NO_TYPESCRIPT_SETUP) {\n return;\n }\n\n // Optionally, wait for the user to add TypeScript during the\n // development cycle.\n const server = this.devServers.find((server) => server.name === 'metro');\n if (!server) {\n return;\n }\n\n // The dev server shouldn't wait for the typescript services\n if (!typescriptPrerequisite) {\n server.waitForTypeScriptAsync().then(async (success) => {\n if (success) {\n server.startTypeScriptServices();\n }\n });\n } else {\n server.startTypeScriptServices();\n }\n }\n\n async watchEnvironmentVariables() {\n await this.devServers.find((server) => server.name === 'metro')?.watchEnvironmentVariables();\n }\n\n /** Stop all servers including ADB. */\n async stopAsync(): Promise<void> {\n await Promise.allSettled([\n this.notifier?.stopObserving(),\n // Stop ADB\n AndroidDebugBridge.getServer().stopAsync(),\n // Stop all dev servers\n ...this.devServers.map((server) =>\n server.stopAsync().catch((error) => {\n Log.error(`Failed to stop dev server (bundler: ${server.name})`);\n Log.exception(error);\n })\n ),\n ]);\n }\n}\n"],"names":["DevServerManager","debug","require","BUNDLERS","webpack","WebpackBundlerDevServer","metro","MetroBundlerDevServer","startMetroAsync","projectRoot","startOptions","devServerManager","startAsync","type","options","devServers","projectPrerequisites","notifier","isExporting","watchBabelConfig","devtoolsPluginManager","DevToolsPluginManager","FileNotifier","additionalWarning","chalk","startObserving","ensureProjectPrerequisiteAsync","PrerequisiteClass","prerequisite","find","push","assertAsync","broadcastMessage","method","params","forEach","server","getNativeDevServerPort","isTargetingNative","getInstance","location","port","getWebDevServer","isTargetingWeb","getDefaultDevServer","defaultServer","assert","ensureWebDevServerRunningAsync","filter","exp","getConfig","skipPlugins","skipSDKVersionRequirement","bundler","getPlatformBundlers","web","toggleRuntimeMode","isUsingDevClient","devClient","nextMode","Log","log","printItem","dim","nextScheme","resolveSchemeAsync","scheme","devServer","isDevClient","urlCreator","getUrlCreator","defaults","platformBundlers","BundlerDevServerClass","devToolsPluginManager","bootstrapTypeScriptAsync","typescriptPrerequisite","TypeScriptProjectPrerequisite","env","EXPO_NO_TYPESCRIPT_SETUP","name","waitForTypeScriptAsync","then","success","startTypeScriptServices","watchEnvironmentVariables","stopAsync","Promise","allSettled","stopObserving","AndroidDebugBridge","getServer","map","catch","error","exception"],"mappings":";;;;+BAkCaA;;;eAAAA;;;;yBAjCa;;;;;;;gEACP;;;;;;;gEACD;;;;;;8EAGgB;kCACE;qBAChB;8BACS;qBACT;+CAE0B;+BACpB;6DACU;gCACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEnC,MAAMC,QAAQC,QAAQ,SAAS;AAO/B,MAAMC,WAAW;IACfC,SAAS,IACPF,Q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pB,QAAG,CAACmC,SAAS,CAACD;gBAChB;SAEH;IACH;AACF"}
@@ -112,7 +112,7 @@ class UrlCreator {
112
112
  return loadingUrl;
113
113
  }
114
114
  /** Create a URI for launching in a native dev client. Returns `null` when no `scheme` can be resolved. */ constructDevClientUrl(options) {
115
- var _this_defaults, _this_defaults1;
115
+ var _this_defaults;
116
116
  const protocol = (options == null ? void 0 : options.scheme) || ((_this_defaults = this.defaults) == null ? void 0 : _this_defaults.scheme);
117
117
  if (!protocol || // Prohibit the use of http(s) in dev client URIs since they'll never be valid.
118
118
  [
@@ -125,12 +125,18 @@ class UrlCreator {
125
125
  }
126
126
  const manifestUrl = this.constructUrl({
127
127
  ...options,
128
- scheme: ((_this_defaults1 = this.defaults) == null ? void 0 : _this_defaults1.hostType) === 'tunnel' ? 'https' : 'http'
128
+ scheme: 'http'
129
129
  });
130
130
  const devClientUrl = `${protocol}://expo-development-client/?url=${encodeURIComponent(manifestUrl)}`;
131
131
  debug(`Dev client URL: ${devClientUrl} -- manifestUrl: ${manifestUrl} -- %O`, options);
132
132
  return devClientUrl;
133
133
  }
134
+ /** Create a URL for launching in Expo Go, e.g. `exp://192.168.1.10:8081`. */ constructExpoGoUrl(options) {
135
+ return this.constructUrl({
136
+ ...options,
137
+ scheme: 'http'
138
+ }).replace(/^http/, 'exp');
139
+ }
134
140
  /** Create a generic URL. */ constructUrl(options) {
135
141
  const urlComponents = this.getUrlComponents({
136
142
  ...this.defaults,
@@ -147,7 +153,7 @@ class UrlCreator {
147
153
  var _this_defaults;
148
154
  return ((_this_defaults = this.defaults) == null ? void 0 : _this_defaults.scheme) ?? null;
149
155
  }
150
- /** Get the URL components from the Ngrok server URL. */ getTunnelUrlComponents(options) {
156
+ /** Get the URL components from the tunnel URL. */ getTunnelUrlComponents(options) {
151
157
  const tunnelUrl = this.bundlerInfo.getTunnelUrl == null ? void 0 : this.bundlerInfo.getTunnelUrl.call(this.bundlerInfo);
152
158
  if (!tunnelUrl) {
153
159
  return null;
@@ -156,7 +162,7 @@ class UrlCreator {
156
162
  return {
157
163
  port: parsed.port,
158
164
  hostname: parsed.hostname,
159
- protocol: options.scheme ?? 'http'
165
+ protocol: parsed.protocol === 'https:' && (options.scheme == null || options.scheme === 'http') ? 'https' : options.scheme ?? 'http'
160
166
  };
161
167
  }
162
168
  getUrlComponents(options) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/start/server/UrlCreator.ts"],"sourcesContent":["import { getOriginalEnvValue } from '@expo/env';\nimport assert from 'assert';\nimport { URL } from 'url';\n\nimport * as Log from '../../log';\nimport type { GatewayInfo } from '../../utils/ip';\nimport { getGateway, getGatewayAsync } from '../../utils/ip';\n\nconst debug = require('debug')('expo:start:server:urlCreator') as typeof console.log;\n\nexport interface CreateURLOptions {\n /** URL scheme to use when opening apps in custom runtimes. */\n scheme?: string | null;\n /** Type of dev server host to use. */\n hostType?: 'localhost' | 'lan' | 'tunnel';\n /** Requested hostname. */\n hostname?: string | null;\n}\n\ninterface UrlComponents {\n port: string;\n hostname: string;\n protocol: string;\n}\n\ninterface BundlerInfo {\n port: number;\n getTunnelUrl?(): string | null;\n}\n\nexport class UrlCreator {\n constructor(\n public defaults: CreateURLOptions,\n private bundlerInfo: BundlerInfo,\n private gatewayInfo: GatewayInfo = getGateway()\n ) {}\n\n static async init(defaults: CreateURLOptions | undefined | null, bundlerInfo: BundlerInfo) {\n const gatewayInfo = await getGatewayAsync();\n return new UrlCreator(defaults || {}, bundlerInfo, gatewayInfo);\n }\n\n /**\n * Return a URL for the \"loading\" interstitial page that is used to disambiguate which\n * native runtime to open the dev server with.\n *\n * @param options options for creating the URL\n * @param platform when opening the URL from the CLI to a connected device we can specify the platform as a query parameter, otherwise it will be inferred from the unsafe user agent sniffing.\n *\n * @returns URL like `http://localhost:8081/_expo/loading?platform=ios`\n * @returns URL like `http://localhost:8081/_expo/loading` when no platform is provided.\n */\n public constructLoadingUrl(options: CreateURLOptions, platform: string | null): string {\n const url = new URL('_expo/loading', this.constructUrl({ scheme: 'http', ...options }));\n if (platform) {\n url.search = new URLSearchParams({ platform }).toString();\n }\n const loadingUrl = url.toString();\n debug(`Loading URL: ${loadingUrl}`);\n return loadingUrl;\n }\n\n /** Create a URI for launching in a native dev client. Returns `null` when no `scheme` can be resolved. */\n public constructDevClientUrl(options?: CreateURLOptions): null | string {\n const protocol = options?.scheme || this.defaults?.scheme;\n\n if (\n !protocol ||\n // Prohibit the use of http(s) in dev client URIs since they'll never be valid.\n ['http', 'https'].includes(protocol.toLowerCase()) ||\n // Prohibit the use of `_` characters in the protocol, Node will throw an error when parsing these URLs\n protocol.includes('_')\n ) {\n debug(`Invalid protocol for dev client URL: ${protocol}`);\n return null;\n }\n\n const manifestUrl = this.constructUrl({\n ...options,\n scheme: this.defaults?.hostType === 'tunnel' ? 'https' : 'http',\n });\n const devClientUrl = `${protocol}://expo-development-client/?url=${encodeURIComponent(\n manifestUrl\n )}`;\n debug(`Dev client URL: ${devClientUrl} -- manifestUrl: ${manifestUrl} -- %O`, options);\n return devClientUrl;\n }\n\n /** Create a generic URL. */\n public constructUrl(options?: Partial<CreateURLOptions> | null): string {\n const urlComponents = this.getUrlComponents({\n ...this.defaults,\n ...options,\n });\n const url = joinUrlComponents(urlComponents);\n debug(`URL: ${url}`);\n return url;\n }\n\n public getDefaultRouteAddress(): string {\n return this.gatewayInfo.address;\n }\n\n /** URL scheme configured for development-build deep links (e.g. `myapp`). `null` when unset. */\n public getScheme(): string | null {\n return this.defaults?.scheme ?? null;\n }\n\n /** Get the URL components from the Ngrok server URL. */\n private getTunnelUrlComponents(options: Pick<CreateURLOptions, 'scheme'>): UrlComponents | null {\n const tunnelUrl = this.bundlerInfo.getTunnelUrl?.();\n if (!tunnelUrl) {\n return null;\n }\n const parsed = new URL(tunnelUrl);\n return {\n port: parsed.port,\n hostname: parsed.hostname,\n protocol: options.scheme ?? 'http',\n };\n }\n\n private getUrlComponents(options: CreateURLOptions): UrlComponents {\n // Proxy comes first.\n const proxyURL = getProxyUrl();\n if (proxyURL) {\n return getUrlComponentsFromProxyUrl(options, proxyURL);\n }\n\n // Ngrok.\n if (options.hostType === 'tunnel') {\n const components = this.getTunnelUrlComponents(options);\n if (components) {\n return components;\n }\n Log.warn('Tunnel URL not found (it might not be ready yet), falling back to LAN URL.');\n } else if (options.hostType === 'localhost' && !options.hostname) {\n options.hostname = 'localhost';\n }\n\n return {\n hostname: getDefaultHostname(options, this.gatewayInfo),\n port: this.bundlerInfo.port.toString(),\n protocol: options.scheme ?? 'http',\n };\n }\n}\n\nfunction getUrlComponentsFromProxyUrl(\n options: Pick<CreateURLOptions, 'scheme'>,\n url: string\n): UrlComponents {\n const parsedProxyUrl = new URL(url);\n let protocol = options.scheme ?? 'http';\n if (parsedProxyUrl.protocol === 'https:') {\n if (protocol === 'http') {\n protocol = 'https';\n }\n if (!parsedProxyUrl.port) {\n parsedProxyUrl.port = '443';\n }\n }\n return {\n port: parsedProxyUrl.port,\n hostname: parsedProxyUrl.hostname,\n protocol,\n };\n}\n\nconst getDefaultHostname = (options: CreateURLOptions, gateway: GatewayInfo) => {\n // TODO: Drop REACT_NATIVE_PACKAGER_HOSTNAME\n if (process.env.REACT_NATIVE_PACKAGER_HOSTNAME) {\n return process.env.REACT_NATIVE_PACKAGER_HOSTNAME.trim();\n } else if (options.hostname === 'localhost') {\n // NOTE: We always convert \"localhost\" as a request to 127.0.0.1,\n // to normalize to an address that's consistent\n return '127.0.0.1';\n } else {\n // Fall back to local address\n return options.hostname || gateway.address;\n }\n};\n\nfunction joinUrlComponents({ protocol, hostname, port }: Partial<UrlComponents>): string {\n assert(hostname, 'hostname cannot be inferred.');\n const validProtocol = protocol ? `${protocol}://` : '';\n\n const url = `${validProtocol}${hostname}`;\n\n if (port) {\n return url + `:${port}`;\n }\n\n return url;\n}\n\n/** @deprecated */\nfunction getProxyUrl(): string | undefined {\n // Read from the pre-dotenv env — overriding this would redirect connected dev\n // clients through an attacker-controlled URL.\n return getOriginalEnvValue('EXPO_PACKAGER_PROXY_URL');\n}\n\n// TODO: Drop the undocumented env variables:\n// REACT_NATIVE_PACKAGER_HOSTNAME\n// EXPO_PACKAGER_PROXY_URL\n"],"names":["UrlCreator","debug","require","defaults","bundlerInfo","gatewayInfo","getGateway","init","getGatewayAsync","constructLoadingUrl","options","platform","url","URL","constructUrl","scheme","search","URLSearchParams","toString","loadingUrl","constructDevClientUrl","protocol","includes","toLowerCase","manifestUrl","hostType","devClientUrl","encodeURIComponent","urlComponents","getUrlComponents","joinUrlComponents","getDefaultRouteAddress","address","getScheme","getTunnelUrlComponents","tunnelUrl","getTunnelUrl","parsed","port","hostname","proxyURL","getProxyUrl","getUrlComponentsFromProxyUrl","components","Log","warn","getDefaultHostname","parsedProxyUrl","gateway","process","env","REACT_NATIVE_PACKAGER_HOSTNAME","trim","assert","validProtocol","getOriginalEnvValue"],"mappings":";;;;+BA8BaA;;;eAAAA;;;;yBA9BuB;;;;;;;gEACjB;;;;;;;yBACC;;;;;;6DAEC;oBAEuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE5C,MAAMC,QAAQC,QAAQ,SAAS;AAsBxB,MAAMF;IACX,YACE,AAAOG,QAA0B,EACjC,AAAQC,WAAwB,EAChC,AAAQC,cAA2BC,IAAAA,cAAU,GAAE,CAC/C;aAHOH,WAAAA;aACCC,cAAAA;aACAC,cAAAA;IACP;IAEH,aAAaE,KAAKJ,QAA6C,EAAEC,WAAwB,EAAE;QACzF,MAAMC,cAAc,MAAMG,IAAAA,mBAAe;QACzC,OAAO,IAAIR,WAAWG,YAAY,CAAC,GAAGC,aAAaC;IACrD;IAEA;;;;;;;;;GASC,GACD,AAAOI,oBAAoBC,OAAyB,EAAEC,QAAuB,EAAU;QACrF,MAAMC,MAAM,IAAIC,CAAAA,MAAE,KAAC,CAAC,iBAAiB,IAAI,CAACC,YAAY,CAAC;YAAEC,QAAQ;YAAQ,GAAGL,OAAO;QAAC;QACpF,IAAIC,UAAU;YACZC,I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WAAW;QACb;QACA,IAAI,CAAC0B,eAAeT,IAAI,EAAE;YACxBS,eAAeT,IAAI,GAAG;QACxB;IACF;IACA,OAAO;QACLA,MAAMS,eAAeT,IAAI;QACzBC,UAAUQ,eAAeR,QAAQ;QACjClB;IACF;AACF;AAEA,MAAMyB,qBAAqB,CAACpC,SAA2BsC;IACrD,4CAA4C;IAC5C,IAAIC,QAAQC,GAAG,CAACC,8BAA8B,EAAE;QAC9C,OAAOF,QAAQC,GAAG,CAACC,8BAA8B,CAACC,IAAI;IACxD,OAAO,IAAI1C,QAAQ6B,QAAQ,KAAK,aAAa;QAC3C,iEAAiE;QACjE,+CAA+C;QAC/C,OAAO;IACT,OAAO;QACL,6BAA6B;QAC7B,OAAO7B,QAAQ6B,QAAQ,IAAIS,QAAQhB,OAAO;IAC5C;AACF;AAEA,SAASF,kBAAkB,EAAET,QAAQ,EAAEkB,QAAQ,EAAED,IAAI,EAA0B;IAC7Ee,IAAAA,iBAAM,EAACd,UAAU;IACjB,MAAMe,gBAAgBjC,WAAW,GAAGA,SAAS,GAAG,CAAC,GAAG;IAEpD,MAAMT,MAAM,GAAG0C,gBAAgBf,UAAU;IAEzC,IAAID,MAAM;QACR,OAAO1B,MAAM,CAAC,CAAC,EAAE0B,MAAM;IACzB;IAEA,OAAO1B;AACT;AAEA,gBAAgB,GAChB,SAAS6B;IACP,8EAA8E;IAC9E,8CAA8C;IAC9C,OAAOc,IAAAA,0BAAmB,EAAC;AAC7B,EAEA,6CAA6C;CAC7C,iCAAiC;CACjC,0BAA0B"}
1
+ {"version":3,"sources":["../../../../src/start/server/UrlCreator.ts"],"sourcesContent":["import { getOriginalEnvValue } from '@expo/env';\nimport assert from 'assert';\nimport { URL } from 'url';\n\nimport * as Log from '../../log';\nimport type { GatewayInfo } from '../../utils/ip';\nimport { getGateway, getGatewayAsync } from '../../utils/ip';\n\nconst debug = require('debug')('expo:start:server:urlCreator') as typeof console.log;\n\nexport interface CreateURLOptions {\n /** URL scheme to use when opening apps in custom runtimes. */\n scheme?: string | null;\n /** Type of dev server host to use. */\n hostType?: 'localhost' | 'lan' | 'tunnel';\n /** Requested hostname. */\n hostname?: string | null;\n}\n\ninterface UrlComponents {\n port: string;\n hostname: string;\n protocol: string;\n}\n\ninterface BundlerInfo {\n port: number;\n getTunnelUrl?(): string | null;\n}\n\nexport class UrlCreator {\n constructor(\n public defaults: CreateURLOptions,\n private bundlerInfo: BundlerInfo,\n private gatewayInfo: GatewayInfo = getGateway()\n ) {}\n\n static async init(defaults: CreateURLOptions | undefined | null, bundlerInfo: BundlerInfo) {\n const gatewayInfo = await getGatewayAsync();\n return new UrlCreator(defaults || {}, bundlerInfo, gatewayInfo);\n }\n\n /**\n * Return a URL for the \"loading\" interstitial page that is used to disambiguate which\n * native runtime to open the dev server with.\n *\n * @param options options for creating the URL\n * @param platform when opening the URL from the CLI to a connected device we can specify the platform as a query parameter, otherwise it will be inferred from the unsafe user agent sniffing.\n *\n * @returns URL like `http://localhost:8081/_expo/loading?platform=ios`\n * @returns URL like `http://localhost:8081/_expo/loading` when no platform is provided.\n */\n public constructLoadingUrl(options: CreateURLOptions, platform: string | null): string {\n const url = new URL('_expo/loading', this.constructUrl({ scheme: 'http', ...options }));\n if (platform) {\n url.search = new URLSearchParams({ platform }).toString();\n }\n const loadingUrl = url.toString();\n debug(`Loading URL: ${loadingUrl}`);\n return loadingUrl;\n }\n\n /** Create a URI for launching in a native dev client. Returns `null` when no `scheme` can be resolved. */\n public constructDevClientUrl(options?: CreateURLOptions): null | string {\n const protocol = options?.scheme || this.defaults?.scheme;\n\n if (\n !protocol ||\n // Prohibit the use of http(s) in dev client URIs since they'll never be valid.\n ['http', 'https'].includes(protocol.toLowerCase()) ||\n // Prohibit the use of `_` characters in the protocol, Node will throw an error when parsing these URLs\n protocol.includes('_')\n ) {\n debug(`Invalid protocol for dev client URL: ${protocol}`);\n return null;\n }\n\n const manifestUrl = this.constructUrl({\n ...options,\n scheme: 'http',\n });\n const devClientUrl = `${protocol}://expo-development-client/?url=${encodeURIComponent(\n manifestUrl\n )}`;\n debug(`Dev client URL: ${devClientUrl} -- manifestUrl: ${manifestUrl} -- %O`, options);\n return devClientUrl;\n }\n\n /** Create a URL for launching in Expo Go, e.g. `exp://192.168.1.10:8081`. */\n public constructExpoGoUrl(options?: Partial<CreateURLOptions> | null): string {\n return this.constructUrl({ ...options, scheme: 'http' }).replace(/^http/, 'exp');\n }\n\n /** Create a generic URL. */\n public constructUrl(options?: Partial<CreateURLOptions> | null): string {\n const urlComponents = this.getUrlComponents({\n ...this.defaults,\n ...options,\n });\n const url = joinUrlComponents(urlComponents);\n debug(`URL: ${url}`);\n return url;\n }\n\n public getDefaultRouteAddress(): string {\n return this.gatewayInfo.address;\n }\n\n /** URL scheme configured for development-build deep links (e.g. `myapp`). `null` when unset. */\n public getScheme(): string | null {\n return this.defaults?.scheme ?? null;\n }\n\n /** Get the URL components from the tunnel URL. */\n private getTunnelUrlComponents(options: Pick<CreateURLOptions, 'scheme'>): UrlComponents | null {\n const tunnelUrl = this.bundlerInfo.getTunnelUrl?.();\n if (!tunnelUrl) {\n return null;\n }\n const parsed = new URL(tunnelUrl);\n return {\n port: parsed.port,\n hostname: parsed.hostname,\n protocol:\n parsed.protocol === 'https:' && (options.scheme == null || options.scheme === 'http')\n ? 'https'\n : (options.scheme ?? 'http'),\n };\n }\n\n private getUrlComponents(options: CreateURLOptions): UrlComponents {\n // Proxy comes first.\n const proxyURL = getProxyUrl();\n if (proxyURL) {\n return getUrlComponentsFromProxyUrl(options, proxyURL);\n }\n\n // Ngrok.\n if (options.hostType === 'tunnel') {\n const components = this.getTunnelUrlComponents(options);\n if (components) {\n return components;\n }\n Log.warn('Tunnel URL not found (it might not be ready yet), falling back to LAN URL.');\n } else if (options.hostType === 'localhost' && !options.hostname) {\n options.hostname = 'localhost';\n }\n\n return {\n hostname: getDefaultHostname(options, this.gatewayInfo),\n port: this.bundlerInfo.port.toString(),\n protocol: options.scheme ?? 'http',\n };\n }\n}\n\nfunction getUrlComponentsFromProxyUrl(\n options: Pick<CreateURLOptions, 'scheme'>,\n url: string\n): UrlComponents {\n const parsedProxyUrl = new URL(url);\n let protocol = options.scheme ?? 'http';\n if (parsedProxyUrl.protocol === 'https:') {\n if (protocol === 'http') {\n protocol = 'https';\n }\n if (!parsedProxyUrl.port) {\n parsedProxyUrl.port = '443';\n }\n }\n return {\n port: parsedProxyUrl.port,\n hostname: parsedProxyUrl.hostname,\n protocol,\n };\n}\n\nconst getDefaultHostname = (options: CreateURLOptions, gateway: GatewayInfo) => {\n // TODO: Drop REACT_NATIVE_PACKAGER_HOSTNAME\n if (process.env.REACT_NATIVE_PACKAGER_HOSTNAME) {\n return process.env.REACT_NATIVE_PACKAGER_HOSTNAME.trim();\n } else if (options.hostname === 'localhost') {\n // NOTE: We always convert \"localhost\" as a request to 127.0.0.1,\n // to normalize to an address that's consistent\n return '127.0.0.1';\n } else {\n // Fall back to local address\n return options.hostname || gateway.address;\n }\n};\n\nfunction joinUrlComponents({ protocol, hostname, port }: Partial<UrlComponents>): string {\n assert(hostname, 'hostname cannot be inferred.');\n const validProtocol = protocol ? `${protocol}://` : '';\n\n const url = `${validProtocol}${hostname}`;\n\n if (port) {\n return url + `:${port}`;\n }\n\n return url;\n}\n\n/** @deprecated */\nfunction getProxyUrl(): string | undefined {\n // Read from the pre-dotenv env — overriding this would redirect connected dev\n // clients through an attacker-controlled URL.\n return getOriginalEnvValue('EXPO_PACKAGER_PROXY_URL');\n}\n\n// TODO: Drop the undocumented env variables:\n// REACT_NATIVE_PACKAGER_HOSTNAME\n// EXPO_PACKAGER_PROXY_URL\n"],"names":["UrlCreator","debug","require","defaults","bundlerInfo","gatewayInfo","getGateway","init","getGatewayAsync","constructLoadingUrl","options","platform","url","URL","constructUrl","scheme","search","URLSearchParams","toString","loadingUrl","constructDevClientUrl","protocol","includes","toLowerCase","manifestUrl","devClientUrl","encodeURIComponent","constructExpoGoUrl","replace","urlComponents","getUrlComponents","joinUrlComponents","getDefaultRouteAddress","address","getScheme","getTunnelUrlComponents","tunnelUrl","getTunnelUrl","parsed","port","hostname","proxyURL","getProxyUrl","getUrlComponentsFromProxyUrl","hostType","components","Log","warn","getDefaultHostname","parsedProxyUrl","gateway","process","env","REACT_NATIVE_PACKAGER_HOSTNAME","trim","assert","validProtocol","getOriginalEnvValue"],"mappings":";;;;+BA8BaA;;;eAAAA;;;;yBA9BuB;;;;;;;gEACjB;;;;;;;yBACC;;;;;;6DAEC;oBAEuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE5C,MAAMC,QAAQC,QAAQ,SAAS;AAsBxB,MAAMF;IACX,YACE,AAAOG,QAA0B,EACjC,AAAQC,WAAwB,EAChC,AAAQC,cAA2BC,IAAAA,cAAU,GAAE,CAC/C;aAHOH,WAAAA;aACCC,cAAAA;aACAC,cAAAA;IACP;IAEH,aAAaE,KAAKJ,QAA6C,EAAEC,WAAwB,EAAE;QACzF,MAAMC,cAAc,MAAMG,IAAAA,mBAAe;QACzC,OAAO,IAAIR,WAAWG,YAAY,CAAC,GAAGC,aAAaC;IACrD;IAEA;;;;;;;;;GASC,GACD,AAAOI,oBAAoBC,OAAyB,EAAEC,QAAuB,EAAU;QACrF,MAAMC,MAAM,IAAIC,CAAAA,MAAE,KAAC,CAAC,iBAAiB,IAAI,CAACC,YAAY,CAAC;YAAEC,QAAQ;YAAQ,GAAGL,OAAO;QAAC;QACpF,IAAIC,UAAU;YACZC,IAAII,MAAM,GAAG,IAAIC,gBAAgB;gBAAEN;YAAS,GAAGO,QAAQ;QACzD;QACA,MAAMC,aAAaP,IAAIM,QAAQ;QAC/BjB,MAAM,CAAC,aAAa,EAAEkB,YAAY;QAClC,OAAOA;IACT;IAEA,wGAAwG,GACxG,AAAOC,sBAAsBV,OAA0B,EAAiB;YAClC;QAApC,MAAMW,WAAWX,CAAAA,2BAAAA,QAASK,MAAM,OAAI,iBAAA,IAAI,CAACZ,QAAQ,qBAAb,eAAe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US,eAAeT,QAAQ;QACjCnB;IACF;AACF;AAEA,MAAM2B,qBAAqB,CAACtC,SAA2BwC;IACrD,4CAA4C;IAC5C,IAAIC,QAAQC,GAAG,CAACC,8BAA8B,EAAE;QAC9C,OAAOF,QAAQC,GAAG,CAACC,8BAA8B,CAACC,IAAI;IACxD,OAAO,IAAI5C,QAAQ8B,QAAQ,KAAK,aAAa;QAC3C,iEAAiE;QACjE,+CAA+C;QAC/C,OAAO;IACT,OAAO;QACL,6BAA6B;QAC7B,OAAO9B,QAAQ8B,QAAQ,IAAIU,QAAQjB,OAAO;IAC5C;AACF;AAEA,SAASF,kBAAkB,EAAEV,QAAQ,EAAEmB,QAAQ,EAAED,IAAI,EAA0B;IAC7EgB,IAAAA,iBAAM,EAACf,UAAU;IACjB,MAAMgB,gBAAgBnC,WAAW,GAAGA,SAAS,GAAG,CAAC,GAAG;IAEpD,MAAMT,MAAM,GAAG4C,gBAAgBhB,UAAU;IAEzC,IAAID,MAAM;QACR,OAAO3B,MAAM,CAAC,CAAC,EAAE2B,MAAM;IACzB;IAEA,OAAO3B;AACT;AAEA,gBAAgB,GAChB,SAAS8B;IACP,8EAA8E;IAC9E,8CAA8C;IAC9C,OAAOe,IAAAA,0BAAmB,EAAC;AAC7B,EAEA,6CAA6C;CAC7C,iCAAiC;CACjC,0BAA0B"}
@@ -8,11 +8,18 @@ Object.defineProperty(exports, "DevToolsPlugin", {
8
8
  return DevToolsPlugin;
9
9
  }
10
10
  });
11
+ function _schemautils() {
12
+ const data = require("@expo/schema-utils");
13
+ _schemautils = function() {
14
+ return data;
15
+ };
16
+ return data;
17
+ }
11
18
  const _DevToolsPluginschema = require("./DevToolsPlugin.schema");
12
19
  const _DevToolsPluginCliExtensionExecutor = require("./DevToolsPluginCliExtensionExecutor");
13
20
  const _DevToolsPluginManager = require("./DevToolsPluginManager");
14
21
  const _DevToolsPluginServerHelpers = require("./DevToolsPluginServerHelpers");
15
- const _dir = require("../../utils/dir");
22
+ const _dir = require("../../../utils/dir");
16
23
  class DevToolsPlugin {
17
24
  constructor(plugin, projectRoot){
18
25
  this.plugin = plugin;
@@ -20,10 +27,12 @@ class DevToolsPlugin {
20
27
  this._executor = undefined;
21
28
  this._requestHandler = undefined;
22
29
  this._webSocketServers = undefined;
23
- const result = _DevToolsPluginschema.PluginSchema.safeParse(plugin);
24
- if (!result.success) {
25
- throw new Error(`Invalid plugin configuration: ${result.error.message}`, {
26
- cause: result.error
30
+ try {
31
+ (0, _schemautils().validate)(_DevToolsPluginschema.PluginSchema, plugin);
32
+ } catch (error) {
33
+ if (!(error instanceof _schemautils().ValidationError)) throw error;
34
+ throw new Error(`Invalid plugin configuration:${error.toErrorsMessage().join('')}`, {
35
+ cause: error
27
36
  });
28
37
  }
29
38
  if (plugin.webpageRoot != null) {
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/start/server/devtools/DevToolsPlugin.ts"],"sourcesContent":["import { validate, ValidationError } from '@expo/schema-utils';\nimport type { WebSocketServer } from 'ws';\n\nimport type { DevToolsPluginInfo } from './DevToolsPlugin.schema';\nimport { PluginSchema } from './DevToolsPlugin.schema';\nimport { DevToolsPluginCliExtensionExecutor } from './DevToolsPluginCliExtensionExecutor';\nimport { DevToolsPluginEndpoint } from './DevToolsPluginManager';\nimport {\n type DevToolsPluginRequestHandler,\n loadRequestHandlerAsync,\n loadWebSocketServerAsync,\n} from './DevToolsPluginServerHelpers';\nimport { isPathInside, maybeRealpathSync } from '../../../utils/dir';\n\nexport type { DevToolsPluginRequestHandler } from './DevToolsPluginServerHelpers';\n\n/**\n * Class that represents a DevTools plugin with CLI and/or web extensions\n *\n * Responsibilities:\n * - Validates plugin configuration against schema\n * - Provides access to plugin metadata (name, description\n * , endpoints)\n * - Manages CLI command execution via DevToolsPluginExecutor\n * - Lazily initializes executor when needed\n * - Constructs web endpoint URLs based on server configuration\n */\nexport class DevToolsPlugin {\n constructor(\n private plugin: DevToolsPluginInfo,\n public readonly projectRoot: string\n ) {\n try {\n validate(PluginSchema, plugin);\n } catch (error) {\n if (!(error instanceof ValidationError)) throw error;\n throw new Error(`Invalid plugin configuration:${error.toErrorsMessage().join('')}`, {\n cause: error,\n });\n }\n\n if (plugin.webpageRoot != null) {\n const webpageRoot = maybeRealpathSync(plugin.webpageRoot) ?? plugin.webpageRoot;\n if (!isPathInside(webpageRoot, plugin.packageRoot)) {\n throw new Error(\n `webpageRoot (${plugin.webpageRoot}) is not inside packageRoot (${plugin.packageRoot}).`\n );\n }\n }\n\n if (plugin.serverEntryPoint != null) {\n const serverEntryPoint =\n maybeRealpathSync(plugin.serverEntryPoint) ?? plugin.serverEntryPoint;\n if (!isPathInside(serverEntryPoint, plugin.packageRoot)) {\n throw new Error(\n `serverEntryPoint (${plugin.serverEntryPoint}) is not inside packageRoot (${plugin.packageRoot}).`\n );\n }\n }\n }\n\n private _executor: DevToolsPluginCliExtensionExecutor | undefined = undefined;\n private _requestHandler: DevToolsPluginRequestHandler | undefined = undefined;\n private _webSocketServers: Record<string, WebSocketServer> | undefined = undefined;\n\n get packageName(): string {\n return this.plugin.packageName;\n }\n\n get packageRoot(): string {\n return this.plugin.packageRoot;\n }\n\n get webpageEndpoint(): string | undefined {\n return this.plugin?.webpageRoot || this.plugin?.serverEntryPoint\n ? `${DevToolsPluginEndpoint}/${this.plugin?.packageName}`\n : undefined;\n }\n\n get webpageRoot(): string | undefined {\n return this.plugin?.webpageRoot;\n }\n\n get serverEntryPoint(): string | undefined {\n return this.plugin?.serverEntryPoint;\n }\n\n /**\n * Lazily loads the request handler from the plugin's `serverEntryPoint`.\n * The entry point must default-export a handler function\n * (`export default function handler(request) {}` or `module.exports = function handler(request) {}`).\n */\n async getRequestHandlerAsync(): Promise<DevToolsPluginRequestHandler | undefined> {\n if (!this.plugin.serverEntryPoint) {\n return undefined;\n }\n\n if (!this._requestHandler) {\n this._requestHandler = await loadRequestHandlerAsync({\n packageName: this.plugin.packageName,\n serverEntryPoint: this.plugin.serverEntryPoint,\n });\n }\n\n return this._requestHandler;\n }\n\n /**\n * Lazily builds the WebSocket servers contributed by the plugin's `serverEntryPoint`. The entry\n * point exports a `webSocketHandlers` map of route (e.g. `/ws`) to a connection handler; each\n * route becomes a `ws` `WebSocketServer` (in `noServer` mode) that the dev server mounts under\n * `/_expo/plugins/<name>/<route>`. The fetch API based `requestHandler` cannot serve WebSocket\n * upgrades, so this is how a plugin opts into them. Returns an empty object when the plugin\n * exports no handlers.\n */\n async getWebSocketServersAsync(): Promise<Record<string, WebSocketServer>> {\n if (!this.plugin.serverEntryPoint) {\n return {};\n }\n\n if (!this._webSocketServers) {\n this._webSocketServers = await loadWebSocketServerAsync({\n packageName: this.plugin.packageName,\n serverEntryPoint: this.plugin.serverEntryPoint,\n });\n }\n\n return this._webSocketServers;\n }\n\n get cliBanner(): boolean {\n return this.plugin.bannerTitle !== undefined && this.plugin.bannerTitle !== false;\n }\n\n get bannerTitle(): string {\n return typeof this.plugin.bannerTitle === 'string' && this.plugin.bannerTitle\n ? this.plugin.bannerTitle\n : this.plugin.packageName;\n }\n\n get description(): string {\n return this.plugin.cliExtensions?.description ?? '';\n }\n\n get cliExtensions(): DevToolsPluginInfo['cliExtensions'] {\n return this.plugin.cliExtensions;\n }\n\n get executor(): DevToolsPluginCliExtensionExecutor | undefined {\n if (!this.plugin.cliExtensions?.entryPoint) {\n return undefined;\n }\n\n if (!this._executor) {\n this._executor = new DevToolsPluginCliExtensionExecutor(this.plugin, this.projectRoot);\n }\n\n return this._executor;\n }\n}\n"],"names":["DevToolsPlugin","plugin","projectRoot","_executor","undefined","_requestHandler","_webSocketServers","validate","PluginSchema","error","ValidationError","Error","toErrorsMessage","join","cause","webpageRoot","maybeRealpathSync","isPathInside","packageRoot","serverEntryPoint","packageName","webpageEndpoint","DevToolsPluginEndpoint","getRequestHandlerAsync","loadRequestHandlerAsync","getWebSocketServersAsync","loadWebSocketServerAsync","cliBanner","bannerTitle","description","cliExtensions","executor","entryPoint","DevToolsPluginCliExtensionExecutor"],"mappings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