@expo/cli 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/bin/cli +2 -2
- package/build/src/api/getExpoGoIntermediateCertificate.js +1 -1
- package/build/src/api/getExpoGoIntermediateCertificate.js.map +1 -1
- package/build/src/api/getExpoSchema.js +1 -1
- package/build/src/api/getExpoSchema.js.map +1 -1
- package/build/src/api/getNativeModuleVersions.js +1 -1
- package/build/src/api/getNativeModuleVersions.js.map +1 -1
- package/build/src/api/getProjectDevelopmentCertificate.js +1 -1
- package/build/src/api/getProjectDevelopmentCertificate.js.map +1 -1
- package/build/src/api/getVersions.js +1 -1
- package/build/src/api/getVersions.js.map +1 -1
- package/build/src/api/rest/cache/wrapFetchWithCache.js.map +1 -1
- package/build/src/api/rest/client.js +5 -5
- package/build/src/api/rest/client.js.map +1 -1
- package/build/src/api/rest/wrapFetchWithOffline.js.map +1 -1
- package/build/src/api/rest/wrapFetchWithProgress.js.map +1 -1
- package/build/src/api/rest/wrapFetchWithProxy.js.map +1 -1
- package/build/src/api/updateDevelopmentSession.js +1 -1
- package/build/src/api/updateDevelopmentSession.js.map +1 -1
- package/build/src/api/user/actions.js +2 -2
- package/build/src/api/user/actions.js.map +1 -1
- package/build/src/api/user/otp.js +1 -1
- package/build/src/api/user/otp.js.map +1 -1
- package/build/src/api/user/user.js +2 -2
- package/build/src/api/user/user.js.map +1 -1
- package/build/src/config/configAsync.js +17 -1
- package/build/src/config/configAsync.js.map +1 -1
- package/build/src/customize/customizeAsync.js +1 -1
- package/build/src/customize/customizeAsync.js.map +1 -1
- package/build/src/customize/generate.js +29 -2
- package/build/src/customize/generate.js.map +1 -1
- package/build/src/customize/templates.js +8 -0
- package/build/src/customize/templates.js.map +1 -1
- package/build/src/customize/typescript.js +54 -0
- package/build/src/customize/typescript.js.map +1 -0
- package/build/src/export/createBundles.js +1 -1
- package/build/src/export/createBundles.js.map +1 -1
- package/build/src/export/createMetadataJson.js.map +1 -1
- package/build/src/export/embed/exportEmbedAsync.js +50 -4
- package/build/src/export/embed/exportEmbedAsync.js.map +1 -1
- package/build/src/export/embed/index.js +1 -3
- package/build/src/export/embed/index.js.map +1 -1
- package/build/src/export/embed/resolveOptions.js +6 -10
- package/build/src/export/embed/resolveOptions.js.map +1 -1
- package/build/src/export/exportApp.js +50 -41
- package/build/src/export/exportApp.js.map +1 -1
- package/build/src/export/exportAssets.js +2 -2
- package/build/src/export/exportAssets.js.map +1 -1
- package/build/src/export/exportAsync.js +1 -1
- package/build/src/export/exportAsync.js.map +1 -1
- package/build/src/export/exportStaticAsync.js +42 -12
- package/build/src/export/exportStaticAsync.js.map +1 -1
- package/build/src/export/fork-bundleAsync.js +27 -2
- package/build/src/export/fork-bundleAsync.js.map +1 -1
- package/build/src/export/getPublicExpoManifest.js +1 -1
- package/build/src/export/getPublicExpoManifest.js.map +1 -1
- package/build/src/export/getResolvedLocales.js.map +1 -1
- package/build/src/export/printBundleSizes.js.map +1 -1
- package/build/src/export/web/exportWebAsync.js.map +1 -1
- package/build/src/export/writeContents.js +5 -1
- package/build/src/export/writeContents.js.map +1 -1
- package/build/src/install/checkPackages.js +1 -1
- package/build/src/install/checkPackages.js.map +1 -1
- package/build/src/install/installAsync.js +1 -1
- package/build/src/install/installAsync.js.map +1 -1
- package/build/src/prebuild/configureProjectAsync.js +5 -9
- package/build/src/prebuild/configureProjectAsync.js.map +1 -1
- package/build/src/prebuild/prebuildAsync.js +5 -5
- package/build/src/prebuild/prebuildAsync.js.map +1 -1
- package/build/src/prebuild/updateFromTemplate.js +8 -5
- package/build/src/prebuild/updateFromTemplate.js.map +1 -1
- package/build/src/register/registerAsync.js +0 -1
- package/build/src/register/registerAsync.js.map +1 -1
- package/build/src/run/android/resolveInstallApkName.js.map +1 -1
- package/build/src/run/android/resolveOptions.js +1 -1
- package/build/src/run/android/resolveOptions.js.map +1 -1
- package/build/src/run/android/runAndroidAsync.js +2 -2
- package/build/src/run/android/runAndroidAsync.js.map +1 -1
- package/build/src/run/ios/XcodeBuild.js +2 -2
- package/build/src/run/ios/XcodeBuild.js.map +1 -1
- package/build/src/run/ios/appleDevice/AppleDevice.js +4 -4
- package/build/src/run/ios/appleDevice/AppleDevice.js.map +1 -1
- package/build/src/run/ios/appleDevice/ClientManager.js +1 -1
- package/build/src/run/ios/appleDevice/ClientManager.js.map +1 -1
- package/build/src/run/ios/appleDevice/client/AFCClient.js +1 -1
- package/build/src/run/ios/appleDevice/client/AFCClient.js.map +1 -1
- package/build/src/run/ios/appleDevice/client/DebugserverClient.js +1 -1
- package/build/src/run/ios/appleDevice/client/DebugserverClient.js.map +1 -1
- package/build/src/run/ios/appleDevice/client/InstallationProxyClient.js +1 -1
- package/build/src/run/ios/appleDevice/client/InstallationProxyClient.js.map +1 -1
- package/build/src/run/ios/appleDevice/client/LockdowndClient.js +1 -1
- package/build/src/run/ios/appleDevice/client/LockdowndClient.js.map +1 -1
- package/build/src/run/ios/appleDevice/client/MobileImageMounterClient.js +1 -1
- package/build/src/run/ios/appleDevice/client/MobileImageMounterClient.js.map +1 -1
- package/build/src/run/ios/appleDevice/client/ServiceClient.js.map +1 -1
- package/build/src/run/ios/appleDevice/client/UsbmuxdClient.js +1 -1
- package/build/src/run/ios/appleDevice/client/UsbmuxdClient.js.map +1 -1
- package/build/src/run/ios/appleDevice/installOnDeviceAsync.js +1 -1
- package/build/src/run/ios/appleDevice/installOnDeviceAsync.js.map +1 -1
- package/build/src/run/ios/appleDevice/protocol/AFCProtocol.js +1 -1
- package/build/src/run/ios/appleDevice/protocol/AFCProtocol.js.map +1 -1
- package/build/src/run/ios/appleDevice/protocol/AbstractProtocol.js.map +1 -1
- package/build/src/run/ios/appleDevice/protocol/GDBProtocol.js +1 -1
- package/build/src/run/ios/appleDevice/protocol/GDBProtocol.js.map +1 -1
- package/build/src/run/ios/appleDevice/protocol/LockdownProtocol.js +1 -1
- package/build/src/run/ios/appleDevice/protocol/LockdownProtocol.js.map +1 -1
- package/build/src/run/ios/codeSigning/configureCodeSigning.js +1 -1
- package/build/src/run/ios/codeSigning/configureCodeSigning.js.map +1 -1
- package/build/src/run/ios/codeSigning/resolveCertificateSigningIdentity.js +2 -2
- package/build/src/run/ios/codeSigning/resolveCertificateSigningIdentity.js.map +1 -1
- package/build/src/run/ios/codeSigning/xcodeCodeSigning.js +3 -0
- package/build/src/run/ios/codeSigning/xcodeCodeSigning.js.map +1 -1
- package/build/src/run/ios/index.js.map +1 -1
- package/build/src/run/ios/launchApp.js +2 -2
- package/build/src/run/ios/launchApp.js.map +1 -1
- package/build/src/run/ios/options/resolveDevice.js +1 -1
- package/build/src/run/ios/options/resolveDevice.js.map +1 -1
- package/build/src/run/ios/options/resolveOptions.js +2 -2
- package/build/src/run/ios/options/resolveOptions.js.map +1 -1
- package/build/src/run/ios/runIosAsync.js +3 -3
- package/build/src/run/ios/runIosAsync.js.map +1 -1
- package/build/src/start/doctor/apple/XcodePrerequisite.js +43 -2
- package/build/src/start/doctor/apple/XcodePrerequisite.js.map +1 -1
- package/build/src/start/doctor/dependencies/ensureDependenciesAsync.js +1 -1
- package/build/src/start/doctor/dependencies/ensureDependenciesAsync.js.map +1 -1
- package/build/src/start/doctor/dependencies/getVersionedPackages.js +5 -3
- package/build/src/start/doctor/dependencies/getVersionedPackages.js.map +1 -1
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js +1 -1
- package/build/src/start/doctor/dependencies/validateDependenciesVersions.js.map +1 -1
- package/build/src/start/doctor/ngrok/ExternalModule.js.map +1 -1
- package/build/src/start/doctor/typescript/TypeScriptProjectPrerequisite.js +7 -7
- package/build/src/start/doctor/typescript/TypeScriptProjectPrerequisite.js.map +1 -1
- package/build/src/start/doctor/typescript/updateTSConfig.js +11 -10
- package/build/src/start/doctor/typescript/updateTSConfig.js.map +1 -1
- package/build/src/start/index.js +0 -2
- package/build/src/start/index.js.map +1 -1
- package/build/src/start/interface/interactiveActions.js +1 -1
- package/build/src/start/interface/interactiveActions.js.map +1 -1
- package/build/src/start/interface/startInterface.js +3 -3
- package/build/src/start/interface/startInterface.js.map +1 -1
- package/build/src/start/platforms/ExpoGoInstaller.js.map +1 -1
- package/build/src/start/platforms/PlatformManager.js.map +1 -1
- package/build/src/start/platforms/android/ADBServer.js +1 -1
- package/build/src/start/platforms/android/ADBServer.js.map +1 -1
- package/build/src/start/platforms/android/AndroidDeviceManager.js +5 -5
- package/build/src/start/platforms/android/AndroidDeviceManager.js.map +1 -1
- package/build/src/start/platforms/android/AndroidPlatformManager.js +1 -1
- package/build/src/start/platforms/android/AndroidPlatformManager.js.map +1 -1
- package/build/src/start/platforms/android/adb.js +1 -1
- package/build/src/start/platforms/android/adb.js.map +1 -1
- package/build/src/start/platforms/android/adbReverse.js +2 -2
- package/build/src/start/platforms/android/adbReverse.js.map +1 -1
- package/build/src/start/platforms/android/emulator.js +1 -1
- package/build/src/start/platforms/android/emulator.js.map +1 -1
- package/build/src/start/platforms/android/getDevices.js +1 -1
- package/build/src/start/platforms/android/getDevices.js.map +1 -1
- package/build/src/start/platforms/android/promptAndroidDevice.js +1 -1
- package/build/src/start/platforms/android/promptAndroidDevice.js.map +1 -1
- package/build/src/start/platforms/ios/AppleDeviceManager.js +5 -5
- package/build/src/start/platforms/ios/AppleDeviceManager.js.map +1 -1
- package/build/src/start/platforms/ios/ApplePlatformManager.js +1 -1
- package/build/src/start/platforms/ios/ApplePlatformManager.js.map +1 -1
- package/build/src/start/platforms/ios/ensureSimulatorAppRunning.js.map +1 -1
- package/build/src/start/platforms/ios/getBestSimulator.js +1 -1
- package/build/src/start/platforms/ios/getBestSimulator.js.map +1 -1
- package/build/src/start/platforms/ios/promptAppleDevice.js +1 -1
- package/build/src/start/platforms/ios/promptAppleDevice.js.map +1 -1
- package/build/src/start/platforms/ios/simctl.js +1 -1
- package/build/src/start/platforms/ios/simctl.js.map +1 -1
- package/build/src/start/platforms/ios/simctlLogging.js +1 -1
- package/build/src/start/platforms/ios/simctlLogging.js.map +1 -1
- package/build/src/start/resolveOptions.js +0 -5
- package/build/src/start/resolveOptions.js.map +1 -1
- package/build/src/start/server/AsyncNgrok.js +4 -3
- package/build/src/start/server/AsyncNgrok.js.map +1 -1
- package/build/src/start/server/BundlerDevServer.js +4 -11
- package/build/src/start/server/BundlerDevServer.js.map +1 -1
- package/build/src/start/server/DevServerManager.js +3 -2
- package/build/src/start/server/DevServerManager.js.map +1 -1
- package/build/src/start/server/UrlCreator.js +2 -1
- package/build/src/start/server/UrlCreator.js.map +1 -1
- package/build/src/start/server/getStaticRenderFunctions.js +2 -2
- package/build/src/start/server/getStaticRenderFunctions.js.map +1 -1
- package/build/src/start/server/metro/MetroBundlerDevServer.js +42 -25
- package/build/src/start/server/metro/MetroBundlerDevServer.js.map +1 -1
- package/build/src/start/server/metro/MetroTerminalReporter.js +14 -3
- package/build/src/start/server/metro/MetroTerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/TerminalReporter.js.map +1 -1
- package/build/src/start/server/metro/TerminalReporter.types.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/device.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/NetworkResponse.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/PageReload.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerGetPossibleBreakpoints.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerScriptParsed.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeDebuggerSetBreakpointByUrl.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/VscodeRuntimeGetProperties.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/handlers/types.js.map +1 -1
- package/build/src/start/server/metro/inspector-proxy/index.js +1 -1
- package/build/src/start/server/metro/inspector-proxy/index.js.map +1 -1
- package/build/src/start/server/metro/instantiateMetro.js +49 -8
- package/build/src/start/server/metro/instantiateMetro.js.map +1 -1
- package/build/src/start/server/metro/resolveFromProject.js +0 -4
- package/build/src/start/server/metro/resolveFromProject.js.map +1 -1
- package/build/src/start/server/metro/runServer-fork.js +1 -1
- package/build/src/start/server/metro/runServer-fork.js.map +1 -1
- package/build/src/start/server/metro/withMetroMultiPlatform.js +59 -9
- package/build/src/start/server/metro/withMetroMultiPlatform.js.map +1 -1
- package/build/src/start/server/metro/withMetroResolvers.js +6 -5
- package/build/src/start/server/metro/withMetroResolvers.js.map +1 -1
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js +2 -2
- package/build/src/start/server/middleware/ExpoGoManifestHandlerMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ExpoMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/FaviconMiddleware.js +1 -1
- package/build/src/start/server/middleware/FaviconMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ManifestMiddleware.js +8 -11
- package/build/src/start/server/middleware/ManifestMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/RuntimeRedirectMiddleware.js +1 -1
- package/build/src/start/server/middleware/RuntimeRedirectMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/ServeStaticMiddleware.js +1 -1
- package/build/src/start/server/middleware/ServeStaticMiddleware.js.map +1 -1
- package/build/src/start/server/middleware/resolvePlatform.js.map +1 -1
- package/build/src/start/server/middleware/server.types.js.map +1 -1
- package/build/src/start/server/openPlatforms.js.map +1 -1
- package/build/src/start/server/type-generation/__typetests__/fixtures/basic.js.map +1 -1
- package/build/src/start/server/type-generation/routes.js +6 -6
- package/build/src/start/server/type-generation/routes.js.map +1 -1
- package/build/src/start/server/type-generation/startTypescriptTypeGeneration.js +3 -3
- package/build/src/start/server/type-generation/startTypescriptTypeGeneration.js.map +1 -1
- package/build/src/start/server/webpack/WebpackBundlerDevServer.js +10 -5
- package/build/src/start/server/webpack/WebpackBundlerDevServer.js.map +1 -1
- package/build/src/start/server/webpack/compile.js +1 -1
- package/build/src/start/server/webpack/compile.js.map +1 -1
- package/build/src/start/startAsync.js +10 -32
- package/build/src/start/startAsync.js.map +1 -1
- package/build/src/utils/FileNotifier.js +1 -1
- package/build/src/utils/FileNotifier.js.map +1 -1
- package/build/src/utils/analytics/metroDebuggerMiddleware.js +1 -1
- package/build/src/utils/analytics/metroDebuggerMiddleware.js.map +1 -1
- package/build/src/utils/analytics/rudderstackClient.js +2 -2
- package/build/src/utils/array.js.map +1 -1
- package/build/src/utils/cocoapods.js +2 -2
- package/build/src/utils/cocoapods.js.map +1 -1
- package/build/src/utils/codesigning.js +2 -2
- package/build/src/utils/codesigning.js.map +1 -1
- package/build/src/utils/downloadAppAsync.js +1 -1
- package/build/src/utils/downloadAppAsync.js.map +1 -1
- package/build/src/utils/downloadExpoGoAsync.js +2 -2
- package/build/src/utils/downloadExpoGoAsync.js.map +1 -1
- package/build/src/utils/editor.js +1 -1
- package/build/src/utils/editor.js.map +1 -1
- package/build/src/utils/env.js +1 -1
- package/build/src/utils/env.js.map +1 -1
- package/build/src/utils/errors.js.map +1 -1
- package/build/src/utils/getOrPromptApplicationId.js +2 -2
- package/build/src/utils/getOrPromptApplicationId.js.map +1 -1
- package/build/src/utils/git.js +1 -1
- package/build/src/utils/git.js.map +1 -1
- package/build/src/utils/modifyConfigAsync.js +1 -1
- package/build/src/utils/modifyConfigAsync.js.map +1 -1
- package/build/src/utils/modifyConfigPlugins.js +1 -1
- package/build/src/utils/modifyConfigPlugins.js.map +1 -1
- package/build/src/utils/npm.js +1 -1
- package/build/src/utils/npm.js.map +1 -1
- package/build/src/utils/obj.js.map +1 -1
- package/build/src/utils/plist.js +1 -1
- package/build/src/utils/plist.js.map +1 -1
- package/build/src/utils/port.js +1 -1
- package/build/src/utils/port.js.map +1 -1
- package/build/src/utils/profile.js +1 -1
- package/build/src/utils/profile.js.map +1 -1
- package/build/src/utils/scheme.js +1 -1
- package/build/src/utils/scheme.js.map +1 -1
- package/build/src/utils/tsconfig/loadTsConfigPaths.js +1 -1
- package/build/src/utils/tsconfig/loadTsConfigPaths.js.map +1 -1
- package/build/src/utils/validateApplicationId.js +85 -5
- package/build/src/utils/validateApplicationId.js.map +1 -1
- package/package.json +11 -8
- package/build/src/api/signManifest.js +0 -26
- package/build/src/api/signManifest.js.map +0 -1
- package/build/src/start/server/middleware/ClassicManifestMiddleware.js +0 -155
- package/build/src/start/server/middleware/ClassicManifestMiddleware.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/ManifestMiddleware.ts"],"sourcesContent":["import { ExpoConfig, ExpoGoConfig, getConfig, ProjectConfig } from '@expo/config';\nimport findWorkspaceRoot from 'find-yarn-workspace-root';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\nimport { resolve } from 'url';\n\nimport * as Log from '../../../log';\nimport { env } from '../../../utils/env';\nimport { stripExtension } from '../../../utils/url';\nimport * as ProjectDevices from '../../project/devices';\nimport { UrlCreator } from '../UrlCreator';\nimport { getPlatformBundlers } from '../platformBundlers';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../webTemplate';\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { resolveGoogleServicesFile, resolveManifestAssets } from './resolveAssets';\nimport { resolveAbsoluteEntryPoint } from './resolveEntryPoint';\nimport { parsePlatformHeader, RuntimePlatform } from './resolvePlatform';\nimport { ServerHeaders, ServerNext, ServerRequest, ServerResponse } from './server.types';\n\nconst debug = require('debug')('expo:start:server:middleware:manifest') as typeof console.log;\n\n/** Wraps `findWorkspaceRoot` and guards against having an empty `package.json` file in an upper directory. */\nexport function getWorkspaceRoot(projectRoot: string): string | null {\n try {\n return findWorkspaceRoot(projectRoot);\n } catch (error: any) {\n if (error.message.includes('Unexpected end of JSON input')) {\n return null;\n }\n throw error;\n }\n}\n\nexport function getEntryWithServerRoot(\n projectRoot: string,\n projectConfig: ProjectConfig,\n platform: string\n) {\n return path.relative(\n getMetroServerRoot(projectRoot),\n resolveAbsoluteEntryPoint(projectRoot, platform, projectConfig)\n );\n}\n\nexport function getMetroServerRoot(projectRoot: string) {\n if (env.EXPO_USE_METRO_WORKSPACE_ROOT) {\n return getWorkspaceRoot(projectRoot) ?? projectRoot;\n }\n\n return projectRoot;\n}\n\n/** Get the main entry module ID (file) relative to the project root. */\nexport function resolveMainModuleName(\n projectRoot: string,\n projectConfig: ProjectConfig,\n platform: string\n): string {\n const entryPoint = getEntryWithServerRoot(projectRoot, projectConfig, platform);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${projectRoot})`);\n\n return stripExtension(entryPoint, 'js');\n}\n\nexport function shouldEnableAsyncImports(projectRoot: string): boolean {\n if (env.EXPO_NO_METRO_LAZY) {\n return false;\n }\n\n // `@expo/metro-runtime` includes support for the fetch + eval runtime code required\n // to support async imports. If it's not installed, we can't support async imports.\n // If it is installed, the user MUST import it somewhere in their project.\n // Expo Router automatically pulls this in, so we can check for it.\n return resolveFrom.silent(projectRoot, '@expo/metro-runtime') != null;\n}\n\nexport function createBundleUrlPath({\n platform,\n mainModuleName,\n mode,\n minify = mode === 'production',\n environment,\n serializerOutput,\n lazy,\n}: {\n platform: string;\n mainModuleName: string;\n mode: string;\n minify?: boolean;\n environment?: string;\n serializerOutput?: 'static';\n lazy?: boolean;\n}): string {\n const queryParams = new URLSearchParams({\n platform: encodeURIComponent(platform),\n dev: String(mode !== 'production'),\n // TODO: Is this still needed?\n hot: String(false),\n });\n\n if (lazy) {\n queryParams.append('lazy', String(lazy));\n }\n\n if (minify) {\n queryParams.append('minify', String(minify));\n }\n if (environment) {\n queryParams.append('resolver.environment', environment);\n queryParams.append('transform.environment', environment);\n }\n if (serializerOutput) {\n queryParams.append('serializer.output', serializerOutput);\n }\n\n return `/${encodeURI(mainModuleName)}.bundle?${queryParams.toString()}`;\n}\n\n/** Info about the computer hosting the dev server. */\nexport interface HostInfo {\n host: string;\n server: 'expo';\n serverVersion: string;\n serverDriver: string | null;\n serverOS: NodeJS.Platform;\n serverOSVersion: string;\n}\n\n/** Parsed values from the supported request headers. */\nexport interface ManifestRequestInfo {\n /** Platform to serve. */\n platform: RuntimePlatform;\n /** Requested host name. */\n hostname?: string | null;\n}\n\n/** Project related info. */\nexport type ResponseProjectSettings = {\n expoGoConfig: ExpoGoConfig;\n hostUri: string;\n bundleUrl: string;\n exp: ExpoConfig;\n};\n\nexport const DEVELOPER_TOOL = 'expo-cli';\n\nexport type ManifestMiddlewareOptions = {\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n constructUrl: UrlCreator['constructUrl'];\n isNativeWebpack?: boolean;\n privateKeyPath?: string;\n};\n\n/** Base middleware creator for serving the Expo manifest (like the index.html but for native runtimes). */\nexport abstract class ManifestMiddleware<\n TManifestRequestInfo extends ManifestRequestInfo\n> extends ExpoMiddleware {\n private initialProjectConfig: ProjectConfig;\n\n constructor(protected projectRoot: string, protected options: ManifestMiddlewareOptions) {\n super(\n projectRoot,\n /**\n * Only support `/`, `/manifest`, `/index.exp` for the manifest middleware.\n */\n ['/', '/manifest', '/index.exp']\n );\n this.initialProjectConfig = getConfig(projectRoot);\n }\n\n /** Exposed for testing. */\n public async _resolveProjectSettingsAsync({\n platform,\n hostname,\n }: Pick<TManifestRequestInfo, 'hostname' | 'platform'>): Promise<ResponseProjectSettings> {\n // Read the config\n const projectConfig = getConfig(this.projectRoot);\n\n // Read from headers\n const mainModuleName = this.resolveMainModuleName(projectConfig, platform);\n\n // Create the manifest and set fields within it\n const expoGoConfig = this.getExpoGoConfig({\n mainModuleName,\n hostname,\n });\n\n const hostUri = this.options.constructUrl({ scheme: '', hostname });\n\n const bundleUrl = this._getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n });\n\n // Resolve all assets and set them on the manifest as URLs\n await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);\n\n return {\n expoGoConfig,\n hostUri,\n bundleUrl,\n exp: projectConfig.exp,\n };\n }\n\n /** Get the main entry module ID (file) relative to the project root. */\n private resolveMainModuleName(projectConfig: ProjectConfig, platform: string): string {\n let entryPoint = getEntryWithServerRoot(this.projectRoot, projectConfig, platform);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${this.projectRoot})`);\n\n // NOTE(Bacon): Webpack is currently hardcoded to index.bundle on native\n // in the future (TODO) we should move this logic into a Webpack plugin and use\n // a generated file name like we do on web.\n // const server = getDefaultDevServer();\n // // TODO: Move this into BundlerDevServer and read this info from self.\n // const isNativeWebpack = server instanceof WebpackBundlerDevServer && server.isTargetingNative();\n if (this.options.isNativeWebpack) {\n entryPoint = 'index.js';\n }\n\n return stripExtension(entryPoint, 'js');\n }\n\n /** Parse request headers into options. */\n public abstract getParsedHeaders(req: ServerRequest): TManifestRequestInfo;\n\n /** Store device IDs that were sent in the request headers. */\n private async saveDevicesAsync(req: ServerRequest) {\n const deviceIds = req.headers?.['expo-dev-client-id'];\n if (deviceIds) {\n await ProjectDevices.saveDevicesAsync(this.projectRoot, deviceIds).catch((e) =>\n Log.exception(e)\n );\n }\n }\n\n /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */\n public _getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n }: {\n platform: string;\n hostname?: string | null;\n mainModuleName: string;\n }): string {\n const path = createBundleUrlPath({\n mode: this.options.mode ?? 'development',\n minify: this.options.minify,\n platform,\n mainModuleName,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n });\n\n return (\n this.options.constructUrl({\n scheme: 'http',\n // hostType: this.options.location.hostType,\n hostname,\n }) + path\n );\n }\n\n public _getBundleUrlPath({\n platform,\n mainModuleName,\n }: {\n platform: string;\n mainModuleName: string;\n }): string {\n const queryParams = new URLSearchParams({\n platform: encodeURIComponent(platform),\n dev: String(this.options.mode !== 'production'),\n // TODO: Is this still needed?\n hot: String(false),\n });\n if (shouldEnableAsyncImports(this.projectRoot)) {\n queryParams.append('lazy', String(true));\n }\n\n if (this.options.minify) {\n queryParams.append('minify', String(this.options.minify));\n }\n\n return `/${encodeURI(mainModuleName)}.bundle?${queryParams.toString()}`;\n }\n\n /** Log telemetry. */\n protected abstract trackManifest(version?: string): void;\n\n /** Get the manifest response to return to the runtime. This file contains info regarding where the assets can be loaded from. Exposed for testing. */\n public abstract _getManifestResponseAsync(options: TManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }>;\n\n private getExpoGoConfig({\n mainModuleName,\n hostname,\n }: {\n mainModuleName: string;\n hostname?: string | null;\n }): ExpoGoConfig {\n return {\n // localhost:8081\n debuggerHost: this.options.constructUrl({ scheme: '', hostname }),\n // http://localhost:8081/logs -- used to send logs to the CLI for displaying in the terminal.\n // This is deprecated in favor of the WebSocket connection setup in Metro.\n logUrl: this.options.constructUrl({ scheme: 'http', hostname }) + '/logs',\n // Required for Expo Go to function.\n developer: {\n tool: DEVELOPER_TOOL,\n projectRoot: this.projectRoot,\n },\n packagerOpts: {\n // Required for dev client.\n dev: this.options.mode !== 'production',\n },\n // Indicates the name of the main bundle.\n mainModuleName,\n // Add this string to make Flipper register React Native / Metro as \"running\".\n // Can be tested by running:\n // `METRO_SERVER_PORT=8081 open -a flipper.app`\n // Where 8081 is the port where the Expo project is being hosted.\n __flipperHack: 'React Native packager is running',\n };\n }\n\n /** Resolve all assets and set them on the manifest as URLs */\n private async mutateManifestWithAssetsAsync(manifest: ExpoConfig, bundleUrl: string) {\n await resolveManifestAssets(this.projectRoot, {\n manifest,\n resolver: async (path) => {\n if (this.options.isNativeWebpack) {\n // When using our custom dev server, just do assets normally\n // without the `assets/` subpath redirect.\n return resolve(bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0], path);\n }\n return bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0] + 'assets/' + path;\n },\n });\n // The server normally inserts this but if we're offline we'll do it here\n await resolveGoogleServicesFile(this.projectRoot, manifest);\n }\n\n public getWebBundleUrl() {\n const platform = 'web';\n // Read from headers\n const mainModuleName = this.resolveMainModuleName(this.initialProjectConfig, platform);\n return this._getBundleUrlPath({\n platform,\n mainModuleName,\n });\n }\n\n /**\n * Web platforms should create an index.html response using the same script resolution as native.\n *\n * Instead of adding a `bundleUrl` to a `manifest.json` (native) we'll add a `<script src=\"\">`\n * to an `index.html`, this enables the web platform to load JavaScript from the server.\n */\n private async handleWebRequestAsync(req: ServerRequest, res: ServerResponse) {\n // Read from headers\n const bundleUrl = this.getWebBundleUrl();\n\n res.setHeader('Content-Type', 'text/html');\n\n res.end(\n await createTemplateHtmlFromExpoConfigAsync(this.projectRoot, {\n exp: this.initialProjectConfig.exp,\n scripts: [bundleUrl],\n })\n );\n }\n\n /** Exposed for testing. */\n async checkBrowserRequestAsync(req: ServerRequest, res: ServerResponse, next: ServerNext) {\n // Read the config\n const bundlers = getPlatformBundlers(this.initialProjectConfig.exp);\n if (bundlers.web === 'metro') {\n // NOTE(EvanBacon): This effectively disables the safety check we do on custom runtimes to ensure\n // the `expo-platform` header is included. When `web.bundler=web`, if the user has non-standard Expo\n // code loading then they'll get a web bundle without a clear assertion of platform support.\n const platform = parsePlatformHeader(req);\n // On web, serve the public folder\n if (!platform || platform === 'web') {\n if (this.initialProjectConfig.exp.web?.output === 'static') {\n // Skip the spa-styled index.html when static generation is enabled.\n next();\n return true;\n } else {\n await this.handleWebRequestAsync(req, res);\n return true;\n }\n }\n }\n return false;\n }\n\n async handleRequestAsync(\n req: ServerRequest,\n res: ServerResponse,\n next: ServerNext\n ): Promise<void> {\n // First check for standard JavaScript runtimes (aka legacy browsers like Chrome).\n if (await this.checkBrowserRequestAsync(req, res, next)) {\n return;\n }\n\n // Save device IDs for dev client.\n await this.saveDevicesAsync(req);\n\n // Read from headers\n const options = this.getParsedHeaders(req);\n const { body, version, headers } = await this._getManifestResponseAsync(options);\n for (const [headerName, headerValue] of headers) {\n res.setHeader(headerName, headerValue);\n }\n res.end(body);\n\n // Log analytics\n this.trackManifest(version ?? null);\n }\n}\n"],"names":["getWorkspaceRoot","getEntryWithServerRoot","getMetroServerRoot","resolveMainModuleName","shouldEnableAsyncImports","createBundleUrlPath","Log","ProjectDevices","debug","require","projectRoot","findWorkspaceRoot","error","message","includes","projectConfig","platform","path","relative","resolveAbsoluteEntryPoint","env","EXPO_USE_METRO_WORKSPACE_ROOT","entryPoint","stripExtension","EXPO_NO_METRO_LAZY","resolveFrom","silent","mainModuleName","mode","minify","environment","serializerOutput","lazy","queryParams","URLSearchParams","encodeURIComponent","dev","String","hot","append","encodeURI","toString","DEVELOPER_TOOL","ManifestMiddleware","ExpoMiddleware","constructor","options","initialProjectConfig","getConfig","_resolveProjectSettingsAsync","hostname","expoGoConfig","getExpoGoConfig","hostUri","constructUrl","scheme","bundleUrl","_getBundleUrl","mutateManifestWithAssetsAsync","exp","isNativeWebpack","saveDevicesAsync","req","deviceIds","headers","catch","e","exception","_getBundleUrlPath","debuggerHost","logUrl","developer","tool","packagerOpts","__flipperHack","manifest","resolveManifestAssets","resolver","resolve","match","resolveGoogleServicesFile","getWebBundleUrl","handleWebRequestAsync","res","setHeader","end","createTemplateHtmlFromExpoConfigAsync","scripts","checkBrowserRequestAsync","next","bundlers","getPlatformBundlers","web","parsePlatformHeader","output","handleRequestAsync","getParsedHeaders","body","version","_getManifestResponseAsync","headerName","headerValue","trackManifest"],"mappings":"AAAA;;;;QAsBgBA,gBAAgB,GAAhBA,gBAAgB;QAWhBC,sBAAsB,GAAtBA,sBAAsB;QAWtBC,kBAAkB,GAAlBA,kBAAkB;QASlBC,qBAAqB,GAArBA,qBAAqB;QAYrBC,wBAAwB,GAAxBA,wBAAwB;QAYxBC,mBAAmB,GAAnBA,mBAAmB;;AA7EgC,IAAA,OAAc,WAAd,cAAc,CAAA;AACnD,IAAA,sBAA0B,kCAA1B,0BAA0B,EAAA;AACvC,IAAA,KAAM,kCAAN,MAAM,EAAA;AACC,IAAA,YAAc,kCAAd,cAAc,EAAA;AACd,IAAA,IAAK,WAAL,KAAK,CAAA;AAEjBC,IAAAA,GAAG,mCAAM,cAAc,EAApB;AACK,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AACT,IAAA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,GAAG,IAAI,CAACkD,gBAAgB,CAAClC,GAAG,CAAC,AAAC;QAC3C,MAAM,EAAEmC,IAAI,CAAA,EAAEC,OAAO,CAAA,EAAElC,OAAO,CAAA,EAAE,GAAG,MAAM,IAAI,CAACmC,yBAAyB,CAACrD,OAAO,CAAC,AAAC;QACjF,KAAK,MAAM,CAACsD,UAAU,EAAEC,WAAW,CAAC,IAAIrC,OAAO,CAAE;YAC/CmB,GAAG,CAACC,SAAS,CAACgB,UAAU,EAAEC,WAAW,CAAC,CAAC;SACxC;QACDlB,GAAG,CAACE,GAAG,CAACY,IAAI,CAAC,CAAC;QAEd,gBAAgB;QAChB,IAAI,CAACK,aAAa,CAACJ,OAAO,WAAPA,OAAO,GAAI,IAAI,CAAC,CAAC;KACrC;CACF;QAhRqBvD,kBAAkB,GAAlBA,kBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/ManifestMiddleware.ts"],"sourcesContent":["import { ExpoConfig, ExpoGoConfig, getConfig, ProjectConfig } from '@expo/config';\nimport findWorkspaceRoot from 'find-yarn-workspace-root';\nimport path from 'path';\nimport resolveFrom from 'resolve-from';\nimport { resolve } from 'url';\n\nimport { ExpoMiddleware } from './ExpoMiddleware';\nimport { resolveGoogleServicesFile, resolveManifestAssets } from './resolveAssets';\nimport { resolveAbsoluteEntryPoint } from './resolveEntryPoint';\nimport { parsePlatformHeader, RuntimePlatform } from './resolvePlatform';\nimport { ServerHeaders, ServerNext, ServerRequest, ServerResponse } from './server.types';\nimport * as Log from '../../../log';\nimport { env } from '../../../utils/env';\nimport { stripExtension } from '../../../utils/url';\nimport * as ProjectDevices from '../../project/devices';\nimport { UrlCreator } from '../UrlCreator';\nimport { getPlatformBundlers } from '../platformBundlers';\nimport { createTemplateHtmlFromExpoConfigAsync } from '../webTemplate';\n\nconst debug = require('debug')('expo:start:server:middleware:manifest') as typeof console.log;\n\n/** Wraps `findWorkspaceRoot` and guards against having an empty `package.json` file in an upper directory. */\nexport function getWorkspaceRoot(projectRoot: string): string | null {\n try {\n return findWorkspaceRoot(projectRoot);\n } catch (error: any) {\n if (error.message.includes('Unexpected end of JSON input')) {\n return null;\n }\n throw error;\n }\n}\n\nexport function getEntryWithServerRoot(\n projectRoot: string,\n projectConfig: ProjectConfig,\n platform: string\n) {\n return path.relative(\n getMetroServerRoot(projectRoot),\n resolveAbsoluteEntryPoint(projectRoot, platform, projectConfig)\n );\n}\n\nexport function getMetroServerRoot(projectRoot: string) {\n if (env.EXPO_USE_METRO_WORKSPACE_ROOT) {\n return getWorkspaceRoot(projectRoot) ?? projectRoot;\n }\n\n return projectRoot;\n}\n\n/** Get the main entry module ID (file) relative to the project root. */\nexport function resolveMainModuleName(\n projectRoot: string,\n projectConfig: ProjectConfig,\n platform: string\n): string {\n const entryPoint = getEntryWithServerRoot(projectRoot, projectConfig, platform);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${projectRoot})`);\n\n return stripExtension(entryPoint, 'js');\n}\n\nexport function shouldEnableAsyncImports(projectRoot: string): boolean {\n if (env.EXPO_NO_METRO_LAZY) {\n return false;\n }\n\n // `@expo/metro-runtime` includes support for the fetch + eval runtime code required\n // to support async imports. If it's not installed, we can't support async imports.\n // If it is installed, the user MUST import it somewhere in their project.\n // Expo Router automatically pulls this in, so we can check for it.\n return resolveFrom.silent(projectRoot, '@expo/metro-runtime') != null;\n}\n\nexport function createBundleUrlPath({\n platform,\n mainModuleName,\n mode,\n minify = mode === 'production',\n environment,\n serializerOutput,\n serializerIncludeMaps,\n lazy,\n}: {\n platform: string;\n mainModuleName: string;\n mode: string;\n minify?: boolean;\n environment?: string;\n serializerOutput?: 'static';\n serializerIncludeMaps?: boolean;\n lazy?: boolean;\n}): string {\n const queryParams = new URLSearchParams({\n platform: encodeURIComponent(platform),\n dev: String(mode !== 'production'),\n // TODO: Is this still needed?\n hot: String(false),\n });\n\n if (lazy) {\n queryParams.append('lazy', String(lazy));\n }\n\n if (minify) {\n queryParams.append('minify', String(minify));\n }\n if (environment) {\n queryParams.append('resolver.environment', environment);\n queryParams.append('transform.environment', environment);\n }\n if (serializerOutput) {\n queryParams.append('serializer.output', serializerOutput);\n }\n if (serializerIncludeMaps) {\n queryParams.append('serializer.map', String(serializerIncludeMaps));\n }\n\n return `/${encodeURI(mainModuleName)}.bundle?${queryParams.toString()}`;\n}\n\n/** Info about the computer hosting the dev server. */\nexport interface HostInfo {\n host: string;\n server: 'expo';\n serverVersion: string;\n serverDriver: string | null;\n serverOS: NodeJS.Platform;\n serverOSVersion: string;\n}\n\n/** Parsed values from the supported request headers. */\nexport interface ManifestRequestInfo {\n /** Platform to serve. */\n platform: RuntimePlatform;\n /** Requested host name. */\n hostname?: string | null;\n}\n\n/** Project related info. */\nexport type ResponseProjectSettings = {\n expoGoConfig: ExpoGoConfig;\n hostUri: string;\n bundleUrl: string;\n exp: ExpoConfig;\n};\n\nexport const DEVELOPER_TOOL = 'expo-cli';\n\nexport type ManifestMiddlewareOptions = {\n /** Should start the dev servers in development mode (minify). */\n mode?: 'development' | 'production';\n /** Should instruct the bundler to create minified bundles. */\n minify?: boolean;\n constructUrl: UrlCreator['constructUrl'];\n isNativeWebpack?: boolean;\n privateKeyPath?: string;\n};\n\n/** Base middleware creator for serving the Expo manifest (like the index.html but for native runtimes). */\nexport abstract class ManifestMiddleware<\n TManifestRequestInfo extends ManifestRequestInfo,\n> extends ExpoMiddleware {\n private initialProjectConfig: ProjectConfig;\n\n constructor(\n protected projectRoot: string,\n protected options: ManifestMiddlewareOptions\n ) {\n super(\n projectRoot,\n /**\n * Only support `/`, `/manifest`, `/index.exp` for the manifest middleware.\n */\n ['/', '/manifest', '/index.exp']\n );\n this.initialProjectConfig = getConfig(projectRoot);\n }\n\n /** Exposed for testing. */\n public async _resolveProjectSettingsAsync({\n platform,\n hostname,\n }: Pick<TManifestRequestInfo, 'hostname' | 'platform'>): Promise<ResponseProjectSettings> {\n // Read the config\n const projectConfig = getConfig(this.projectRoot);\n\n // Read from headers\n const mainModuleName = this.resolveMainModuleName(projectConfig, platform);\n\n // Create the manifest and set fields within it\n const expoGoConfig = this.getExpoGoConfig({\n mainModuleName,\n hostname,\n });\n\n const hostUri = this.options.constructUrl({ scheme: '', hostname });\n\n const bundleUrl = this._getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n });\n\n // Resolve all assets and set them on the manifest as URLs\n await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);\n\n return {\n expoGoConfig,\n hostUri,\n bundleUrl,\n exp: projectConfig.exp,\n };\n }\n\n /** Get the main entry module ID (file) relative to the project root. */\n private resolveMainModuleName(projectConfig: ProjectConfig, platform: string): string {\n let entryPoint = getEntryWithServerRoot(this.projectRoot, projectConfig, platform);\n\n debug(`Resolved entry point: ${entryPoint} (project root: ${this.projectRoot})`);\n\n // NOTE(Bacon): Webpack is currently hardcoded to index.bundle on native\n // in the future (TODO) we should move this logic into a Webpack plugin and use\n // a generated file name like we do on web.\n // const server = getDefaultDevServer();\n // // TODO: Move this into BundlerDevServer and read this info from self.\n // const isNativeWebpack = server instanceof WebpackBundlerDevServer && server.isTargetingNative();\n if (this.options.isNativeWebpack) {\n entryPoint = 'index.js';\n }\n\n return stripExtension(entryPoint, 'js');\n }\n\n /** Parse request headers into options. */\n public abstract getParsedHeaders(req: ServerRequest): TManifestRequestInfo;\n\n /** Store device IDs that were sent in the request headers. */\n private async saveDevicesAsync(req: ServerRequest) {\n const deviceIds = req.headers?.['expo-dev-client-id'];\n if (deviceIds) {\n await ProjectDevices.saveDevicesAsync(this.projectRoot, deviceIds).catch((e) =>\n Log.exception(e)\n );\n }\n }\n\n /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */\n public _getBundleUrl({\n platform,\n mainModuleName,\n hostname,\n }: {\n platform: string;\n hostname?: string | null;\n mainModuleName: string;\n }): string {\n const path = createBundleUrlPath({\n mode: this.options.mode ?? 'development',\n minify: this.options.minify,\n platform,\n mainModuleName,\n lazy: shouldEnableAsyncImports(this.projectRoot),\n });\n\n return (\n this.options.constructUrl({\n scheme: 'http',\n // hostType: this.options.location.hostType,\n hostname,\n }) + path\n );\n }\n\n public _getBundleUrlPath({\n platform,\n mainModuleName,\n }: {\n platform: string;\n mainModuleName: string;\n }): string {\n const queryParams = new URLSearchParams({\n platform: encodeURIComponent(platform),\n dev: String(this.options.mode !== 'production'),\n // TODO: Is this still needed?\n hot: String(false),\n });\n if (shouldEnableAsyncImports(this.projectRoot)) {\n queryParams.append('lazy', String(true));\n }\n\n if (this.options.minify) {\n queryParams.append('minify', String(this.options.minify));\n }\n\n return `/${encodeURI(mainModuleName)}.bundle?${queryParams.toString()}`;\n }\n\n /** Log telemetry. */\n protected abstract trackManifest(version?: string): void;\n\n /** Get the manifest response to return to the runtime. This file contains info regarding where the assets can be loaded from. Exposed for testing. */\n public abstract _getManifestResponseAsync(options: TManifestRequestInfo): Promise<{\n body: string;\n version: string;\n headers: ServerHeaders;\n }>;\n\n private getExpoGoConfig({\n mainModuleName,\n hostname,\n }: {\n mainModuleName: string;\n hostname?: string | null;\n }): ExpoGoConfig {\n return {\n // localhost:8081\n debuggerHost: this.options.constructUrl({ scheme: '', hostname }),\n // Required for Expo Go to function.\n developer: {\n tool: DEVELOPER_TOOL,\n projectRoot: this.projectRoot,\n },\n packagerOpts: {\n // Required for dev client.\n dev: this.options.mode !== 'production',\n },\n // Indicates the name of the main bundle.\n mainModuleName,\n // Add this string to make Flipper register React Native / Metro as \"running\".\n // Can be tested by running:\n // `METRO_SERVER_PORT=8081 open -a flipper.app`\n // Where 8081 is the port where the Expo project is being hosted.\n __flipperHack: 'React Native packager is running',\n };\n }\n\n /** Resolve all assets and set them on the manifest as URLs */\n private async mutateManifestWithAssetsAsync(manifest: ExpoConfig, bundleUrl: string) {\n await resolveManifestAssets(this.projectRoot, {\n manifest,\n resolver: async (path) => {\n if (this.options.isNativeWebpack) {\n // When using our custom dev server, just do assets normally\n // without the `assets/` subpath redirect.\n return resolve(bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0], path);\n }\n return bundleUrl!.match(/^https?:\\/\\/.*?\\//)![0] + 'assets/' + path;\n },\n });\n // The server normally inserts this but if we're offline we'll do it here\n await resolveGoogleServicesFile(this.projectRoot, manifest);\n }\n\n public getWebBundleUrl() {\n const platform = 'web';\n // Read from headers\n const mainModuleName = this.resolveMainModuleName(this.initialProjectConfig, platform);\n return this._getBundleUrlPath({\n platform,\n mainModuleName,\n });\n }\n\n /**\n * Web platforms should create an index.html response using the same script resolution as native.\n *\n * Instead of adding a `bundleUrl` to a `manifest.json` (native) we'll add a `<script src=\"\">`\n * to an `index.html`, this enables the web platform to load JavaScript from the server.\n */\n private async handleWebRequestAsync(req: ServerRequest, res: ServerResponse) {\n // Read from headers\n const bundleUrl = this.getWebBundleUrl();\n\n res.setHeader('Content-Type', 'text/html');\n\n res.end(\n await createTemplateHtmlFromExpoConfigAsync(this.projectRoot, {\n exp: this.initialProjectConfig.exp,\n scripts: [bundleUrl],\n })\n );\n }\n\n /** Exposed for testing. */\n async checkBrowserRequestAsync(req: ServerRequest, res: ServerResponse, next: ServerNext) {\n // Read the config\n const bundlers = getPlatformBundlers(this.initialProjectConfig.exp);\n if (bundlers.web === 'metro') {\n // NOTE(EvanBacon): This effectively disables the safety check we do on custom runtimes to ensure\n // the `expo-platform` header is included. When `web.bundler=web`, if the user has non-standard Expo\n // code loading then they'll get a web bundle without a clear assertion of platform support.\n const platform = parsePlatformHeader(req);\n // On web, serve the public folder\n if (!platform || platform === 'web') {\n if (this.initialProjectConfig.exp.web?.output === 'static') {\n // Skip the spa-styled index.html when static generation is enabled.\n next();\n return true;\n } else {\n await this.handleWebRequestAsync(req, res);\n return true;\n }\n }\n }\n return false;\n }\n\n async handleRequestAsync(\n req: ServerRequest,\n res: ServerResponse,\n next: ServerNext\n ): Promise<void> {\n // First check for standard JavaScript runtimes (aka legacy browsers like Chrome).\n if (await this.checkBrowserRequestAsync(req, res, next)) {\n return;\n }\n\n // Save device IDs for dev client.\n await this.saveDevicesAsync(req);\n\n // Read from headers\n const options = this.getParsedHeaders(req);\n const { body, version, headers } = await this._getManifestResponseAsync(options);\n for (const [headerName, headerValue] of headers) {\n res.setHeader(headerName, headerValue);\n }\n res.end(body);\n\n // Log analytics\n this.trackManifest(version ?? null);\n }\n}\n"],"names":["getWorkspaceRoot","getEntryWithServerRoot","getMetroServerRoot","resolveMainModuleName","shouldEnableAsyncImports","createBundleUrlPath","Log","ProjectDevices","debug","require","projectRoot","findWorkspaceRoot","error","message","includes","projectConfig","platform","path","relative","resolveAbsoluteEntryPoint","env","EXPO_USE_METRO_WORKSPACE_ROOT","entryPoint","stripExtension","EXPO_NO_METRO_LAZY","resolveFrom","silent","mainModuleName","mode","minify","environment","serializerOutput","serializerIncludeMaps","lazy","queryParams","URLSearchParams","encodeURIComponent","dev","String","hot","append","encodeURI","toString","DEVELOPER_TOOL","ManifestMiddleware","ExpoMiddleware","constructor","options","initialProjectConfig","getConfig","_resolveProjectSettingsAsync","hostname","expoGoConfig","getExpoGoConfig","hostUri","constructUrl","scheme","bundleUrl","_getBundleUrl","mutateManifestWithAssetsAsync","exp","isNativeWebpack","saveDevicesAsync","req","deviceIds","headers","catch","e","exception","_getBundleUrlPath","debuggerHost","developer","tool","packagerOpts","__flipperHack","manifest","resolveManifestAssets","resolver","resolve","match","resolveGoogleServicesFile","getWebBundleUrl","handleWebRequestAsync","res","setHeader","end","createTemplateHtmlFromExpoConfigAsync","scripts","checkBrowserRequestAsync","next","bundlers","getPlatformBundlers","web","parsePlatformHeader","output","handleRequestAsync","getParsedHeaders","body","version","_getManifestResponseAsync","headerName","headerValue","trackManifest"],"mappings":"AAAA;;;;QAsBgBA,gBAAgB,GAAhBA,gBAAgB;QAWhBC,sBAAsB,GAAtBA,sBAAsB;QAWtBC,kBAAkB,GAAlBA,kBAAkB;QASlBC,qBAAqB,GAArBA,qBAAqB;QAYrBC,wBAAwB,GAAxBA,wBAAwB;QAYxBC,mBAAmB,GAAnBA,mBAAmB;;AA7EgC,IAAA,OAA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nBM,IAAgB,EACD;QACf,kFAAkF;QAClF,IAAI,MAAM,IAAI,CAACD,wBAAwB,CAACzB,GAAG,EAAEoB,GAAG,EAAEM,IAAI,CAAC,EAAE;YACvD,OAAO;SACR;QAED,kCAAkC;QAClC,MAAM,IAAI,CAAC3B,gBAAgB,CAACC,GAAG,CAAC,CAAC;QAEjC,oBAAoB;QACpB,MAAMhB,OAAO,GAAG,IAAI,CAACiD,gBAAgB,CAACjC,GAAG,CAAC,AAAC;QAC3C,MAAM,EAAEkC,IAAI,CAAA,EAAEC,OAAO,CAAA,EAAEjC,OAAO,CAAA,EAAE,GAAG,MAAM,IAAI,CAACkC,yBAAyB,CAACpD,OAAO,CAAC,AAAC;QACjF,KAAK,MAAM,CAACqD,UAAU,EAAEC,WAAW,CAAC,IAAIpC,OAAO,CAAE;YAC/CkB,GAAG,CAACC,SAAS,CAACgB,UAAU,EAAEC,WAAW,CAAC,CAAC;SACxC;QACDlB,GAAG,CAACE,GAAG,CAACY,IAAI,CAAC,CAAC;QAEd,gBAAgB;QAChB,IAAI,CAACK,aAAa,CAACJ,OAAO,WAAPA,OAAO,GAAI,IAAI,CAAC,CAAC;KACrC;CACF;QAhRqBtD,kBAAkB,GAAlBA,kBAAkB"}
|
|
@@ -3,9 +3,9 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
5
|
var _url = require("url");
|
|
6
|
-
var Log = _interopRequireWildcard(require("../../../log"));
|
|
7
6
|
var _expoMiddleware = require("./ExpoMiddleware");
|
|
8
7
|
var _resolvePlatform = require("./resolvePlatform");
|
|
8
|
+
var Log = _interopRequireWildcard(require("../../../log"));
|
|
9
9
|
function _interopRequireWildcard(obj) {
|
|
10
10
|
if (obj && obj.__esModule) {
|
|
11
11
|
return obj;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/RuntimeRedirectMiddleware.ts"],"sourcesContent":["import { parse } from 'url';\n\nimport
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/RuntimeRedirectMiddleware.ts"],"sourcesContent":["import { parse } from 'url';\n\nimport { disableResponseCache, ExpoMiddleware } from './ExpoMiddleware';\nimport {\n assertMissingRuntimePlatform,\n assertRuntimePlatform,\n parsePlatformHeader,\n resolvePlatformFromUserAgentHeader,\n RuntimePlatform,\n} from './resolvePlatform';\nimport { ServerRequest, ServerResponse } from './server.types';\nimport * as Log from '../../../log';\n\nconst debug = require('debug')(\n 'expo:start:server:middleware:runtimeRedirect'\n) as typeof console.log;\n\n/** Runtime to target: expo = Expo Go, custom = Dev Client. */\ntype RuntimeTarget = 'expo' | 'custom';\n\nexport type DeepLinkHandler = (props: {\n runtime: RuntimeTarget;\n platform: RuntimePlatform;\n}) => void | Promise<void>;\n\nexport class RuntimeRedirectMiddleware extends ExpoMiddleware {\n constructor(\n protected projectRoot: string,\n protected options: {\n onDeepLink: DeepLinkHandler;\n getLocation: (props: { runtime: RuntimeTarget }) => string | null | undefined;\n }\n ) {\n super(projectRoot, ['/_expo/link']);\n }\n\n async handleRequestAsync(req: ServerRequest, res: ServerResponse): Promise<void> {\n const { query } = parse(req.url!, true);\n const isDevClient = query['choice'] === 'expo-dev-client';\n const platform = parsePlatformHeader(req) ?? resolvePlatformFromUserAgentHeader(req);\n assertMissingRuntimePlatform(platform);\n assertRuntimePlatform(platform);\n const runtime = isDevClient ? 'custom' : 'expo';\n\n debug(`props:`, { platform, runtime });\n\n this.options.onDeepLink({ runtime, platform });\n\n const redirect = this.options.getLocation({ runtime });\n if (!redirect) {\n Log.warn(\n `[redirect middleware]: Unable to determine redirect location for runtime '${runtime}' and platform '${platform}'`\n );\n res.statusCode = 404;\n res.end();\n return;\n }\n debug('Redirect ->', redirect);\n res.setHeader('Location', redirect);\n\n // Disable caching\n disableResponseCache(res);\n\n // 'Temporary Redirect'\n res.statusCode = 307;\n res.end();\n }\n}\n"],"names":["Log","debug","require","RuntimeRedirectMiddleware","ExpoMiddleware","constructor","projectRoot","options","handleRequestAsync","req","res","query","parse","url","isDevClient","parsePlatformHeader","platform","resolvePlatformFromUserAgentHeader","assertMissingRuntimePlatform","assertRuntimePlatform","runtime","onDeepLink","redirect","getLocation","warn","statusCode","end","setHeader","disableResponseCache"],"mappings":"AAAA;;;;AAAsB,IAAA,IAAK,WAAL,KAAK,CAAA;AAE0B,IAAA,eAAkB,WAAlB,kBAAkB,CAAA;AAOhE,IAAA,gBAAmB,WAAnB,mBAAmB,CAAA;AAEdA,IAAAA,GAAG,mCAAM,cAAc,EAApB;;;;;;;;;;;;;;;;;;;;;;AAEf,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAC5B,8CAA8C,CAC/C,AAAsB,AAAC;AAUjB,MAAMC,yBAAyB,SAASC,eAAc,eAAA;IAC3DC,YACYC,WAAmB,EACnBC,OAGT,CACD;QACA,KAAK,CAACD,WAAW,EAAE;YAAC,aAAa;SAAC,CAAC,CAAC;aAN1BA,WAAmB,GAAnBA,WAAmB;aACnBC,OAGT,GAHSA,OAGT;KAGF;IAED,MAAMC,kBAAkB,CAACC,GAAkB,EAAEC,GAAmB,EAAiB;QAC/E,MAAM,EAAEC,KAAK,CAAA,EAAE,GAAGC,CAAAA,GAAAA,IAAK,AAAgB,CAAA,MAAhB,CAACH,GAAG,CAACI,GAAG,EAAG,IAAI,CAAC,AAAC;QACxC,MAAMC,WAAW,GAAGH,KAAK,CAAC,QAAQ,CAAC,KAAK,iBAAiB,AAAC;YACzCI,GAAwB;QAAzC,MAAMC,QAAQ,GAAGD,CAAAA,GAAwB,GAAxBA,CAAAA,GAAAA,gBAAmB,AAAK,CAAA,oBAAL,CAACN,GAAG,CAAC,YAAxBM,GAAwB,GAAIE,CAAAA,GAAAA,gBAAkC,AAAK,CAAA,mCAAL,CAACR,GAAG,CAAC,AAAC;QACrFS,CAAAA,GAAAA,gBAA4B,AAAU,CAAA,6BAAV,CAACF,QAAQ,CAAC,CAAC;QACvCG,CAAAA,GAAAA,gBAAqB,AAAU,CAAA,sBAAV,CAACH,QAAQ,CAAC,CAAC;QAChC,MAAMI,OAAO,GAAGN,WAAW,GAAG,QAAQ,GAAG,MAAM,AAAC;QAEhDb,KAAK,CAAC,CAAC,MAAM,CAAC,EAAE;YAAEe,QAAQ;YAAEI,OAAO;SAAE,CAAC,CAAC;QAEvC,IAAI,CAACb,OAAO,CAACc,UAAU,CAAC;YAAED,OAAO;YAAEJ,QAAQ;SAAE,CAAC,CAAC;QAE/C,MAAMM,QAAQ,GAAG,IAAI,CAACf,OAAO,CAACgB,WAAW,CAAC;YAAEH,OAAO;SAAE,CAAC,AAAC;QACvD,IAAI,CAACE,QAAQ,EAAE;YACbtB,GAAG,CAACwB,IAAI,CACN,CAAC,0EAA0E,EAAEJ,OAAO,CAAC,gBAAgB,EAAEJ,QAAQ,CAAC,CAAC,CAAC,CACnH,CAAC;YACFN,GAAG,CAACe,UAAU,GAAG,GAAG,CAAC;YACrBf,GAAG,CAACgB,GAAG,EAAE,CAAC;YACV,OAAO;SACR;QACDzB,KAAK,CAAC,aAAa,EAAEqB,QAAQ,CAAC,CAAC;QAC/BZ,GAAG,CAACiB,SAAS,CAAC,UAAU,EAAEL,QAAQ,CAAC,CAAC;QAEpC,kBAAkB;QAClBM,CAAAA,GAAAA,eAAoB,AAAK,CAAA,qBAAL,CAAClB,GAAG,CAAC,CAAC;QAE1B,uBAAuB;QACvBA,GAAG,CAACe,UAAU,GAAG,GAAG,CAAC;QACrBf,GAAG,CAACgB,GAAG,EAAE,CAAC;KACX;CACF;QA1CYvB,yBAAyB,GAAzBA,yBAAyB"}
|
|
@@ -5,8 +5,8 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
var _path = _interopRequireDefault(require("path"));
|
|
6
6
|
var _send = _interopRequireDefault(require("send"));
|
|
7
7
|
var _url = require("url");
|
|
8
|
-
var _env = require("../../../utils/env");
|
|
9
8
|
var _resolvePlatform = require("./resolvePlatform");
|
|
9
|
+
var _env = require("../../../utils/env");
|
|
10
10
|
function _interopRequireDefault(obj) {
|
|
11
11
|
return obj && obj.__esModule ? obj : {
|
|
12
12
|
default: obj
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/ServeStaticMiddleware.ts"],"sourcesContent":["import path from 'path';\nimport send from 'send';\nimport { parse } from 'url';\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/ServeStaticMiddleware.ts"],"sourcesContent":["import path from 'path';\nimport send from 'send';\nimport { parse } from 'url';\n\nimport { parsePlatformHeader } from './resolvePlatform';\nimport { ServerRequest, ServerResponse } from './server.types';\nimport { env } from '../../../utils/env';\n\nconst debug = require('debug')('expo:start:server:middleware:serveStatic') as typeof console.log;\n\n/**\n * Adds support for serving the files in the static `public/` folder to web apps.\n */\nexport class ServeStaticMiddleware {\n constructor(private projectRoot: string) {}\n getHandler() {\n const publicPath = path.join(this.projectRoot, env.EXPO_PUBLIC_FOLDER);\n\n debug(`Serving static files from:`, publicPath);\n const opts = {\n root: publicPath,\n };\n return (req: ServerRequest, res: ServerResponse, next: any) => {\n if (!req?.url || (req.method !== 'GET' && req.method !== 'HEAD')) {\n return next();\n }\n\n const platform = parsePlatformHeader(req);\n // Currently this is web-only\n if (platform && platform !== 'web') {\n return next();\n }\n\n const pathname = parse(req.url).pathname;\n if (!pathname) {\n return next();\n }\n\n debug(`Maybe serve static:`, pathname);\n const stream = send(req, pathname, opts);\n\n // add file listener for fallthrough\n let forwardError = false;\n stream.on('file', function onFile() {\n // once file is determined, always forward error\n forwardError = true;\n });\n\n // forward errors\n stream.on('error', function error(err: any) {\n if (forwardError || !(err.statusCode < 500)) {\n next(err);\n return;\n }\n\n next();\n });\n\n // pipe\n stream.pipe(res);\n };\n }\n}\n"],"names":["debug","require","ServeStaticMiddleware","constructor","projectRoot","getHandler","publicPath","path","join","env","EXPO_PUBLIC_FOLDER","opts","root","req","res","next","url","method","platform","parsePlatformHeader","pathname","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,CAACR,GAAG,CAACG,GAAG,CAAC,CAACI,QAAQ,AAAC;YACzC,IAAI,CAACA,QAAQ,EAAE;gBACb,OAAOL,IAAI,EAAE,CAAC;aACf;YAEDf,KAAK,CAAC,CAAC,mBAAmB,CAAC,EAAEoB,QAAQ,CAAC,CAAC;YACvC,MAAME,MAAM,GAAGC,CAAAA,GAAAA,KAAI,AAAqB,CAAA,QAArB,CAACV,GAAG,EAAEO,QAAQ,EAAET,IAAI,CAAC,AAAC;YAEzC,oCAAoC;YACpC,IAAIa,YAAY,GAAG,KAAK,AAAC;YACzBF,MAAM,CAACG,EAAE,CAAC,MAAM,EAAE,SAASC,MAAM,GAAG;gBAClC,gDAAgD;gBAChDF,YAAY,GAAG,IAAI,CAAC;aACrB,CAAC,CAAC;YAEH,iBAAiB;YACjBF,MAAM,CAACG,EAAE,CAAC,OAAO,EAAE,SAASE,KAAK,CAACC,GAAQ,EAAE;gBAC1C,IAAIJ,YAAY,IAAI,CAAC,CAACI,GAAG,CAACC,UAAU,GAAG,GAAG,CAAC,EAAE;oBAC3Cd,IAAI,CAACa,GAAG,CAAC,CAAC;oBACV,OAAO;iBACR;gBAEDb,IAAI,EAAE,CAAC;aACR,CAAC,CAAC;YAEH,OAAO;YACPO,MAAM,CAACQ,IAAI,CAAChB,GAAG,CAAC,CAAC;SAClB,CAAC;KACH;CACF;QAjDYZ,qBAAqB,GAArBA,qBAAqB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/resolvePlatform.ts"],"sourcesContent":["import { parse } from 'url';\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/resolvePlatform.ts"],"sourcesContent":["import { parse } from 'url';\n\nimport { ServerRequest } from './server.types';\nimport { CommandError } from '../../../utils/errors';\n\nconst debug = require('debug')(\n 'expo:start:server:middleware:resolvePlatform'\n) as typeof console.log;\n\n/** Supported platforms */\nexport type RuntimePlatform = 'ios' | 'android';\n\n/**\n * Extract the runtime platform from the server request.\n * 1. Query param `platform`: `?platform=ios`\n * 2. Header `expo-platform`: `'expo-platform': ios`\n * 3. Legacy header `exponent-platform`: `'exponent-platform': ios`\n *\n * Returns first item in the case of an array.\n */\nexport function parsePlatformHeader(req: ServerRequest): string | null {\n const url = parse(req.url!, /* parseQueryString */ true);\n const platform =\n url.query?.platform || req.headers['expo-platform'] || req.headers['exponent-platform'];\n return (Array.isArray(platform) ? platform[0] : platform) ?? null;\n}\n\n/** Guess the platform from the user-agent header. */\nexport function resolvePlatformFromUserAgentHeader(req: ServerRequest): string | null {\n let platform = null;\n const userAgent = req.headers['user-agent'];\n if (userAgent?.match(/Android/i)) {\n platform = 'android';\n }\n if (userAgent?.match(/iPhone|iPad/i)) {\n platform = 'ios';\n }\n debug(`Resolved platform ${platform} from user-agent header: ${userAgent}`);\n return platform;\n}\n\n/** Assert if the runtime platform is not included. */\nexport function assertMissingRuntimePlatform(platform?: any): asserts platform {\n if (!platform) {\n throw new CommandError(\n 'PLATFORM_HEADER',\n `Must specify \"expo-platform\" header or \"platform\" query parameter`\n );\n }\n}\n\n/** Assert if the runtime platform is not correct. */\nexport function assertRuntimePlatform(platform: string): asserts platform is RuntimePlatform {\n const stringifiedPlatform = String(platform);\n if (!['android', 'ios', 'web'].includes(stringifiedPlatform)) {\n throw new CommandError(\n 'PLATFORM_HEADER',\n `platform must be \"android\", \"ios\", or \"web\". Received: \"${platform}\"`\n );\n }\n}\n"],"names":["parsePlatformHeader","resolvePlatformFromUserAgentHeader","assertMissingRuntimePlatform","assertRuntimePlatform","debug","require","req","url","parse","platform","query","headers","Array","isArray","userAgent","match","CommandError","stringifiedPlatform","String","includes"],"mappings":"AAAA;;;;QAoBgBA,mBAAmB,GAAnBA,mBAAmB;QAQnBC,kCAAkC,GAAlCA,kCAAkC;QAclCC,4BAA4B,GAA5BA,4BAA4B;QAU5BC,qBAAqB,GAArBA,qBAAqB;AApDf,IAAA,IAAK,WAAL,KAAK,CAAA;AAGE,IA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AC;CACjB;AAGM,SAASP,4BAA4B,CAACO,QAAc,EAAoB;IAC7E,IAAI,CAACA,QAAQ,EAAE;QACb,MAAM,IAAIO,OAAY,aAAA,CACpB,iBAAiB,EACjB,CAAC,iEAAiE,CAAC,CACpE,CAAC;KACH;CACF;AAGM,SAASb,qBAAqB,CAACM,QAAgB,EAAuC;IAC3F,MAAMQ,mBAAmB,GAAGC,MAAM,CAACT,QAAQ,CAAC,AAAC;IAC7C,IAAI,CAAC;QAAC,SAAS;QAAE,KAAK;QAAE,KAAK;KAAC,CAACU,QAAQ,CAACF,mBAAmB,CAAC,EAAE;QAC5D,MAAM,IAAID,OAAY,aAAA,CACpB,iBAAiB,EACjB,CAAC,wDAAwD,EAAEP,QAAQ,CAAC,CAAC,CAAC,CACvE,CAAC;KACH;CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/middleware/server.types.ts"],"sourcesContent":["import express from 'express';\nimport http from 'http';\n\n/** Headers */\nexport type ServerHeaders = Map<string, number | string | readonly string[]>;\n/** Request */\nexport type ServerRequest = express.Request | http.IncomingMessage;\n/** Response */\nexport type ServerResponse = express.Response | http.ServerResponse;\n/** Next function */\nexport type ServerNext = (err?: Error) => void;\n\n/** The `connect()` app that is a http.RequestListener and having the `use()` function for middlewares. */\nexport interface ConnectAppType extends http.RequestListener {\n use: Function;\n}\n"],"names":[],"mappings":"AAAA"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/middleware/server.types.ts"],"sourcesContent":["import express from 'express';\nimport http from 'http';\n\n/** Headers */\nexport type ServerHeaders = Map<string, number | string | readonly string[]>;\n/** Request */\nexport type ServerRequest = express.Request | http.IncomingMessage;\n/** Response */\nexport type ServerResponse = express.Response | http.ServerResponse;\n/** Next function */\nexport type ServerNext = (err?: Error | null) => void;\n\n/** The `connect()` app that is a http.RequestListener and having the `use()` function for middlewares. */\nexport interface ConnectAppType extends http.RequestListener {\n use: Function;\n}\n"],"names":[],"mappings":"AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/start/server/openPlatforms.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../../src/start/server/openPlatforms.ts"],"sourcesContent":["import { DevServerManager } from './DevServerManager';\nimport { AbortCommandError } from '../../utils/errors';\nimport { Options } from '../resolveOptions';\n\n/** Launch the app on various platforms in parallel. */\nexport async function openPlatformsAsync(\n devServerManager: DevServerManager,\n options: Pick<Options, 'ios' | 'android' | 'web'>\n) {\n const results = await Promise.allSettled([\n options.android ? devServerManager.getDefaultDevServer().openPlatformAsync('emulator') : null,\n options.ios ? devServerManager.getDefaultDevServer().openPlatformAsync('simulator') : null,\n options.web\n ? devServerManager\n .ensureWebDevServerRunningAsync()\n .then(() => devServerManager.getWebDevServer()?.openPlatformAsync('desktop'))\n : null,\n ]);\n\n const errors = results\n .map((result) => (result.status === 'rejected' ? result.reason : null))\n .filter(Boolean);\n\n if (errors.length) {\n // ctrl+c\n const isEscapedError = errors.some((error: any) => error.code === 'ABORTED');\n if (isEscapedError) {\n throw new AbortCommandError();\n }\n throw errors[0];\n }\n\n return !!options.android || !!options.ios;\n}\n"],"names":["openPlatformsAsync","devServerManager","options","results","Promise","allSettled","android","getDefaultDevServer","openPlatformAsync","ios","web","ensureWebDevServerRunningAsync","then","getWebDevServer","errors","map","result","status","reason","filter","Boolean","length","isEscapedError","some","error","code","AbortCommandError"],"mappings":"AAAA;;;;QAKsBA,kBAAkB,GAAlBA,kBAAkB;AAJN,IAAA,OAAoB,WAApB,oBAAoB,CAAA;AAI/C,eAAeA,kBAAkB,CACtCC,gBAAkC,EAClCC,OAAiD,EACjD;IACA,MAAMC,OAAO,GAAG,MAAMC,OAAO,CAACC,UAAU,CAAC;QACvCH,OAAO,CAACI,OAAO,GAAGL,gBAAgB,CAACM,mBAAmB,EAAE,CAACC,iBAAiB,CAAC,UAAU,CAAC,GAAG,IAAI;QAC7FN,OAAO,CAACO,GAAG,GAAGR,gBAAgB,CAACM,mBAAmB,EAAE,CAACC,iBAAiB,CAAC,WAAW,CAAC,GAAG,IAAI;QAC1FN,OAAO,CAACQ,GAAG,GACPT,gBAAgB,CACbU,8BAA8B,EAAE,CAChCC,IAAI,CAAC;gBAAMX,GAAkC;YAAlCA,OAAAA,CAAAA,GAAkC,GAAlCA,gBAAgB,CAACY,eAAe,EAAE,SAAmB,GAArDZ,KAAAA,CAAqD,GAArDA,GAAkC,CAAEO,iBAAiB,CAAC,SAAS,CAAC,CAAA;SAAA,CAAC,GAC/E,IAAI;KACT,CAAC,AAAC;IAEH,MAAMM,MAAM,GAAGX,OAAO,CACnBY,GAAG,CAAC,CAACC,MAAM,GAAMA,MAAM,CAACC,MAAM,KAAK,UAAU,GAAGD,MAAM,CAACE,MAAM,GAAG,IAAI;IAAC,CAAC,CACtEC,MAAM,CAACC,OAAO,CAAC,AAAC;IAEnB,IAAIN,MAAM,CAACO,MAAM,EAAE;QACjB,SAAS;QACT,MAAMC,cAAc,GAAGR,MAAM,CAACS,IAAI,CAAC,CAACC,KAAU,GAAKA,KAAK,CAACC,IAAI,KAAK,SAAS;QAAA,CAAC,AAAC;QAC7E,IAAIH,cAAc,EAAE;YAClB,MAAM,IAAII,OAAiB,kBAAA,EAAE,CAAC;SAC/B;QACD,MAAMZ,MAAM,CAAC,CAAC,CAAC,CAAC;KACjB;IAED,OAAO,CAAC,CAACZ,OAAO,CAACI,OAAO,IAAI,CAAC,CAACJ,OAAO,CAACO,GAAG,CAAC;CAC3C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../src/start/server/type-generation/__typetests__/fixtures/basic.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/ban-types */\n\nimport type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link';\nimport type { Router as OriginalRouter } from 'expo-router/src/types';\nexport * from 'expo-router/build';\n\n// prettier-ignore\ntype StaticRoutes = `/apple` | `/banana`;\n// prettier-ignore\ntype DynamicRoutes<T extends string> = `/colors/${SingleRoutePart<T>}` | `/animals/${CatchAllRoutePart<T>}` | `/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}`;\n// prettier-ignore\ntype DynamicRouteTemplate = `/colors/[color]` | `/animals/[...animal]` | `/mix/[fruit]/[color]/[...animals]`;\n\ntype RelativePathString = `./${string}` | `../${string}` | '..';\ntype AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;\ntype ExternalPathString = `http${string}`;\ntype ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;\ntype AllRoutes = ExpoRouterRoutes | ExternalPathString;\n\n/****************\n * Route Utils *\n ****************/\n\ntype SearchOrHash = `?${string}` | `#${string}`;\ntype UnknownInputParams = Record<string, string | number | (string | number)[]>;\ntype UnknownOutputParams = Record<string, string | string[]>;\n\n/**\n * Return only the RoutePart of a string. If the string has multiple parts return never\n *\n * string | type\n * ---------|------\n * 123 | 123\n * /123/abc | never\n * 123?abc | never\n * ./123 | never\n * /123 | never\n * 123/../ | never\n */\ntype SingleRoutePart<S extends string> = S extends `${string}/${string}`\n ? never\n : S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S extends `(${string})`\n ? never\n : S extends `[${string}]`\n ? never\n : S;\n\n/**\n * Return only the CatchAll router part. If the string has search parameters or a hash return never\n */\ntype CatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S extends `${string}(${string})${string}`\n ? never\n : S extends `${string}[${string}]${string}`\n ? never\n : S;\n\n// type OptionalCatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}` ? never : S\n\n/**\n * Return the name of a route parameter\n * '[test]' -> 'test'\n * 'test' -> never\n * '[...test]' -> '...test'\n */\ntype IsParameter<Part> = Part extends `[${infer ParamName}]` ? ParamName : never;\n\n/**\n * Return a union of all parameter names. If there are no names return never\n *\n * /[test] -> 'test'\n * /[abc]/[...def] -> 'abc'|'...def'\n */\ntype ParameterNames<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? IsParameter<PartA> | ParameterNames<PartB>\n : IsParameter<Path>;\n\n/**\n * Returns all segements of a route.\n *\n * /(group)/123/abc/[id]/[...rest] -> ['(group)', '123', 'abc', '[id]', '[...rest]'\n */\ntype RouteSegments<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? PartA extends '' | '.'\n ? [...RouteSegments<PartB>]\n : [PartA, ...RouteSegments<PartB>]\n : Path extends ''\n ? []\n : [Path];\n\n/**\n * Returns a Record of the routes parameters as strings and CatchAll parameters\n *\n * There are two versions, input and output, as you can input 'string | number' but\n * the output will always be 'string'\n *\n * /[id]/[...rest] -> { id: string, rest: string[] }\n * /no-params -> {}\n */\ntype InputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends `...${infer Name}`\n ? Name\n : Key]: Key extends `...${string}` ? (string | number)[] : string | number;\n} & UnknownInputParams;\n\ntype OutputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends `...${infer Name}`\n ? Name\n : Key]: Key extends `...${string}` ? string[] : string;\n} & UnknownOutputParams;\n\n/**\n * Returns the search parameters for a route.\n */\nexport type SearchParams<T extends AllRoutes> = T extends DynamicRouteTemplate\n ? OutputRouteParams<T>\n : T extends StaticRoutes\n ? never\n : UnknownOutputParams;\n\n/**\n * Route is mostly used as part of Href to ensure that a valid route is provided\n *\n * Given a dynamic route, this will return never. This is helpful for conditional logic\n *\n * /test -> /test, /test2, etc\n * /test/[abc] -> never\n * /test/resolve -> /test, /test2, etc\n *\n * Note that if we provide a value for [abc] then the route is allowed\n *\n * This is named Route to prevent confusion, as users they will often see it in tooltips\n */\nexport type Route<T> = T extends string\n ? T extends DynamicRouteTemplate\n ? never\n :\n | StaticRoutes\n | RelativePathString\n | ExternalPathString\n | (T extends `${infer P}${SearchOrHash}`\n ? P extends DynamicRoutes<infer _>\n ? T\n : never\n : T extends DynamicRoutes<infer _>\n ? T\n : never)\n : never;\n\n/*********\n * Href *\n *********/\n\nexport type Href<T> = T extends Record<'pathname', string> ? HrefObject<T> : Route<T>;\n\nexport type HrefObject<\n R extends Record<'pathname', string>,\n P = R['pathname']
|
|
1
|
+
{"version":3,"sources":["../../../../../../../src/start/server/type-generation/__typetests__/fixtures/basic.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/ban-types */\n\nimport type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link';\nimport type { Router as OriginalRouter } from 'expo-router/src/types';\nexport * from 'expo-router/build';\n\n// prettier-ignore\ntype StaticRoutes = `/apple` | `/banana`;\n// prettier-ignore\ntype DynamicRoutes<T extends string> = `/colors/${SingleRoutePart<T>}` | `/animals/${CatchAllRoutePart<T>}` | `/mix/${SingleRoutePart<T>}/${SingleRoutePart<T>}/${CatchAllRoutePart<T>}`;\n// prettier-ignore\ntype DynamicRouteTemplate = `/colors/[color]` | `/animals/[...animal]` | `/mix/[fruit]/[color]/[...animals]`;\n\ntype RelativePathString = `./${string}` | `../${string}` | '..';\ntype AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;\ntype ExternalPathString = `http${string}`;\ntype ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;\ntype AllRoutes = ExpoRouterRoutes | ExternalPathString;\n\n/****************\n * Route Utils *\n ****************/\n\ntype SearchOrHash = `?${string}` | `#${string}`;\ntype UnknownInputParams = Record<string, string | number | (string | number)[]>;\ntype UnknownOutputParams = Record<string, string | string[]>;\n\n/**\n * Return only the RoutePart of a string. If the string has multiple parts return never\n *\n * string | type\n * ---------|------\n * 123 | 123\n * /123/abc | never\n * 123?abc | never\n * ./123 | never\n * /123 | never\n * 123/../ | never\n */\ntype SingleRoutePart<S extends string> = S extends `${string}/${string}`\n ? never\n : S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S extends `(${string})`\n ? never\n : S extends `[${string}]`\n ? never\n : S;\n\n/**\n * Return only the CatchAll router part. If the string has search parameters or a hash return never\n */\ntype CatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}`\n ? never\n : S extends ''\n ? never\n : S extends `${string}(${string})${string}`\n ? never\n : S extends `${string}[${string}]${string}`\n ? never\n : S;\n\n// type OptionalCatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}` ? never : S\n\n/**\n * Return the name of a route parameter\n * '[test]' -> 'test'\n * 'test' -> never\n * '[...test]' -> '...test'\n */\ntype IsParameter<Part> = Part extends `[${infer ParamName}]` ? ParamName : never;\n\n/**\n * Return a union of all parameter names. If there are no names return never\n *\n * /[test] -> 'test'\n * /[abc]/[...def] -> 'abc'|'...def'\n */\ntype ParameterNames<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? IsParameter<PartA> | ParameterNames<PartB>\n : IsParameter<Path>;\n\n/**\n * Returns all segements of a route.\n *\n * /(group)/123/abc/[id]/[...rest] -> ['(group)', '123', 'abc', '[id]', '[...rest]'\n */\ntype RouteSegments<Path> = Path extends `${infer PartA}/${infer PartB}`\n ? PartA extends '' | '.'\n ? [...RouteSegments<PartB>]\n : [PartA, ...RouteSegments<PartB>]\n : Path extends ''\n ? []\n : [Path];\n\n/**\n * Returns a Record of the routes parameters as strings and CatchAll parameters\n *\n * There are two versions, input and output, as you can input 'string | number' but\n * the output will always be 'string'\n *\n * /[id]/[...rest] -> { id: string, rest: string[] }\n * /no-params -> {}\n */\ntype InputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends `...${infer Name}`\n ? Name\n : Key]: Key extends `...${string}` ? (string | number)[] : string | number;\n} & UnknownInputParams;\n\ntype OutputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends `...${infer Name}`\n ? Name\n : Key]: Key extends `...${string}` ? string[] : string;\n} & UnknownOutputParams;\n\n/**\n * Returns the search parameters for a route.\n */\nexport type SearchParams<T extends AllRoutes> = T extends DynamicRouteTemplate\n ? OutputRouteParams<T>\n : T extends StaticRoutes\n ? never\n : UnknownOutputParams;\n\n/**\n * Route is mostly used as part of Href to ensure that a valid route is provided\n *\n * Given a dynamic route, this will return never. This is helpful for conditional logic\n *\n * /test -> /test, /test2, etc\n * /test/[abc] -> never\n * /test/resolve -> /test, /test2, etc\n *\n * Note that if we provide a value for [abc] then the route is allowed\n *\n * This is named Route to prevent confusion, as users they will often see it in tooltips\n */\nexport type Route<T> = T extends string\n ? T extends DynamicRouteTemplate\n ? never\n :\n | StaticRoutes\n | RelativePathString\n | ExternalPathString\n | (T extends `${infer P}${SearchOrHash}`\n ? P extends DynamicRoutes<infer _>\n ? T\n : never\n : T extends DynamicRoutes<infer _>\n ? T\n : never)\n : never;\n\n/*********\n * Href *\n *********/\n\nexport type Href<T> = T extends Record<'pathname', string> ? HrefObject<T> : Route<T>;\n\nexport type HrefObject<\n R extends Record<'pathname', string>,\n P = R['pathname'],\n> = P extends DynamicRouteTemplate\n ? { pathname: P; params: InputRouteParams<P> }\n : P extends Route<P>\n ? { pathname: Route<P> | DynamicRouteTemplate; params?: never | InputRouteParams<never> }\n : never;\n\n/***********************\n * Expo Router Exports *\n ***********************/\n\nexport type Router = Omit<OriginalRouter, 'push' | 'replace' | 'setParams'> & {\n /** Navigate to the provided href. */\n push: <T>(href: Href<T>) => void;\n /** Navigate to route without appending to the history. */\n replace: <T>(href: Href<T>) => void;\n /** Update the current route query params. */\n setParams: <T = ''>(params?: T extends '' ? Record<string, string> : InputRouteParams<T>) => void;\n};\n\n/** The imperative router. */\nexport declare const router: Router;\n\n/************\n * <Link /> *\n ************/\nexport interface LinkProps<T> extends OriginalLinkProps {\n href: Href<T>;\n}\n\nexport interface LinkComponent {\n <T>(props: React.PropsWithChildren<LinkProps<T>>): JSX.Element;\n /** Helper method to resolve an Href object into a string. */\n resolveHref: <T>(href: Href<T>) => string;\n}\n\n/**\n * Component to render link to another route using a path.\n * Uses an anchor tag on the web.\n *\n * @param props.href Absolute path to route (e.g. `/feeds/hot`).\n * @param props.replace Should replace the current route without adding to the history.\n * @param props.asChild Forward props to child component. Useful for custom buttons.\n * @param props.children Child elements to render the content.\n */\nexport declare const Link: LinkComponent;\n\n/** Redirects to the href as soon as the component is mounted. */\nexport declare const Redirect: <T>(\n props: React.PropsWithChildren<{ href: Href<T> }>\n) => JSX.Element;\n\n/************\n * Hooks *\n ************/\nexport declare function useRouter(): Router;\n\nexport declare function useLocalSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\n/** @deprecated renamed to `useGlobalSearchParams` */\nexport declare function useSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\nexport declare function useGlobalSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n>(): T extends AllRoutes ? SearchParams<T> : T;\n\nexport declare function useSegments<\n T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString,\n>(): T extends AbsoluteRoute ? RouteSegments<T> : T extends string ? string[] : T;\n"],"names":[],"mappings":"AAIA;;;;6CAEc,mBAAmB;AAAjC,YAAA,MAAkC;;2CAAlC,MAAkC;;;;mBAAlC,MAAkC;;;EAAA"}
|
|
@@ -31,7 +31,7 @@ exports.CAPTURE_GROUP_REGEX = CAPTURE_GROUP_REGEX;
|
|
|
31
31
|
async function setupTypedRoutes({ server , metro , typesDirectory , projectRoot , routerDirectory }) {
|
|
32
32
|
const absoluteRouterDirectory = _path.default.join(projectRoot, routerDirectory);
|
|
33
33
|
const { filePathToRoute , staticRoutes , dynamicRoutes , addFilePath , isRouteFile } = getTypedRoutesUtils(absoluteRouterDirectory);
|
|
34
|
-
if (metro) {
|
|
34
|
+
if (metro && server) {
|
|
35
35
|
// Setup out watcher first
|
|
36
36
|
(0, _metroWatchTypeScriptFiles).metroWatchTypeScriptFiles({
|
|
37
37
|
projectRoot,
|
|
@@ -395,7 +395,7 @@ declare module "expo-router" {
|
|
|
395
395
|
|
|
396
396
|
export type HrefObject<
|
|
397
397
|
R extends Record<'pathname', string>,
|
|
398
|
-
P = R['pathname']
|
|
398
|
+
P = R['pathname'],
|
|
399
399
|
> = P extends DynamicRouteTemplate
|
|
400
400
|
? { pathname: P; params: InputRouteParams<P> }
|
|
401
401
|
: P extends Route<P>
|
|
@@ -453,20 +453,20 @@ declare module "expo-router" {
|
|
|
453
453
|
export function useRouter(): Router;
|
|
454
454
|
|
|
455
455
|
export function useLocalSearchParams<
|
|
456
|
-
T extends AllRoutes | UnknownOutputParams = UnknownOutputParams
|
|
456
|
+
T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,
|
|
457
457
|
>(): T extends AllRoutes ? SearchParams<T> : T;
|
|
458
458
|
|
|
459
459
|
/** @deprecated renamed to \`useGlobalSearchParams\` */
|
|
460
460
|
export function useSearchParams<
|
|
461
|
-
T extends AllRoutes | UnknownOutputParams = UnknownOutputParams
|
|
461
|
+
T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,
|
|
462
462
|
>(): T extends AllRoutes ? SearchParams<T> : T;
|
|
463
463
|
|
|
464
464
|
export function useGlobalSearchParams<
|
|
465
|
-
T extends AllRoutes | UnknownOutputParams = UnknownOutputParams
|
|
465
|
+
T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,
|
|
466
466
|
>(): T extends AllRoutes ? SearchParams<T> : T;
|
|
467
467
|
|
|
468
468
|
export function useSegments<
|
|
469
|
-
T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString
|
|
469
|
+
T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString,
|
|
470
470
|
>(): T extends AbsoluteRoute ? RouteSegments<T> : T extends string ? string[] : T;
|
|
471
471
|
}
|
|
472
472
|
`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/type-generation/routes.ts"],"sourcesContent":["import fs from 'fs/promises';\nimport { debounce } from 'lodash';\nimport { Server } from 'metro';\nimport path from 'path';\n\nimport { directoryExistsAsync } from '../../../utils/dir';\nimport { unsafeTemplate } from '../../../utils/template';\nimport { ServerLike } from '../BundlerDevServer';\nimport { metroWatchTypeScriptFiles } from '../metro/metroWatchTypeScriptFiles';\n\n// /test/[...param1]/[param2]/[param3] - captures [\"param1\", \"param2\", \"param3\"]\nexport const CAPTURE_DYNAMIC_PARAMS = /\\[(?:\\.{3})?(\\w*?)[\\]$]/g;\n// /[...param1]/ - Match [...param1]\nexport const CATCH_ALL = /\\[\\.\\.\\..+?\\]/g;\n// /[param1] - Match [param1]\nexport const SLUG = /\\[.+?\\]/g;\n// /(group1,group2,group3)/test - match (group1,group2,group3)\nexport const ARRAY_GROUP_REGEX = /\\(\\s*\\w[\\w\\s]*?,.*?\\)/g;\n// /(group1,group2,group3)/test - captures [\"group1\", \"group2\", \"group3\"]\nexport const CAPTURE_GROUP_REGEX = /[\\\\(,]\\s*(\\w[\\w\\s]*?)\\s*(?=[,\\\\)])/g;\n\nexport interface SetupTypedRoutesOptions {\n server: ServerLike;\n metro?: Server | null;\n typesDirectory: string;\n projectRoot: string;\n routerDirectory: string;\n}\n\nexport async function setupTypedRoutes({\n server,\n metro,\n typesDirectory,\n projectRoot,\n routerDirectory,\n}: SetupTypedRoutesOptions) {\n const absoluteRouterDirectory = path.join(projectRoot, routerDirectory);\n\n const { filePathToRoute, staticRoutes, dynamicRoutes, addFilePath, isRouteFile } =\n getTypedRoutesUtils(absoluteRouterDirectory);\n\n if (metro) {\n // Setup out watcher first\n metroWatchTypeScriptFiles({\n projectRoot,\n server,\n metro,\n eventTypes: ['add', 'delete', 'change'],\n async callback({ filePath, type }) {\n if (!isRouteFile(filePath)) {\n return;\n }\n\n let shouldRegenerate = false;\n\n if (type === 'delete') {\n const route = filePathToRoute(filePath);\n staticRoutes.delete(route);\n dynamicRoutes.delete(route);\n shouldRegenerate = true;\n } else {\n shouldRegenerate = addFilePath(filePath);\n }\n\n if (shouldRegenerate) {\n regenerateRouterDotTS(\n typesDirectory,\n new Set([...staticRoutes.values()].flatMap((v) => Array.from(v))),\n new Set([...dynamicRoutes.values()].flatMap((v) => Array.from(v))),\n new Set(dynamicRoutes.keys())\n );\n }\n },\n });\n }\n\n if (await directoryExistsAsync(absoluteRouterDirectory)) {\n // Do we need to walk the entire tree on startup?\n // Idea: Store the list of files in the last write, then simply check Git for what files have changed\n await walk(absoluteRouterDirectory, addFilePath);\n }\n\n regenerateRouterDotTS(\n typesDirectory,\n new Set([...staticRoutes.values()].flatMap((v) => Array.from(v))),\n new Set([...dynamicRoutes.values()].flatMap((v) => Array.from(v))),\n new Set(dynamicRoutes.keys())\n );\n}\n\n/**\n * Generate a router.d.ts file that contains all of the routes in the project.\n * Should be debounced as its very common for developers to make changes to multiple files at once (eg Save All)\n */\nconst regenerateRouterDotTS = debounce(\n async (\n typesDir: string,\n staticRoutes: Set<string>,\n dynamicRoutes: Set<string>,\n dynamicRouteTemplates: Set<string>\n ) => {\n await fs.mkdir(typesDir, { recursive: true });\n await fs.writeFile(\n path.resolve(typesDir, './router.d.ts'),\n getTemplateString(staticRoutes, dynamicRoutes, dynamicRouteTemplates)\n );\n },\n 100\n);\n\n/*\n * This is exported for testing purposes\n */\nexport function getTemplateString(\n staticRoutes: Set<string>,\n dynamicRoutes: Set<string>,\n dynamicRouteTemplates: Set<string>\n) {\n return routerDotTSTemplate({\n staticRoutes: setToUnionType(staticRoutes),\n dynamicRoutes: setToUnionType(dynamicRoutes),\n dynamicRouteParams: setToUnionType(dynamicRouteTemplates),\n });\n}\n\n/**\n * Utility functions for typed routes\n *\n * These are extracted for easier testing\n */\nexport function getTypedRoutesUtils(appRoot: string, filePathSeperator = path.sep) {\n /*\n * staticRoutes are a map where the key if the route without groups and the value\n * is another set of all group versions of the route. e.g,\n * Map([\n * [\"/\", [\"/(app)/(notes)\", \"/(app)/(profile)\"]\n * ])\n */\n const staticRoutes = new Map<string, Set<string>>([['/', new Set('/')]]);\n /*\n * dynamicRoutes are the same as staticRoutes (key if the resolved route,\n * and the value is a set of possible routes). e.g:\n *\n * /[...fruits] -> /${CatchAllRoutePart<T>}\n * /color/[color] -> /color/${SingleRoutePart<T>}\n *\n * The keys of this map are also important, as they can be used as \"static\" types\n * <Link href={{ pathname: \"/[...fruits]\",params: { fruits: [\"apple\"] } }} />\n */\n const dynamicRoutes = new Map<string, Set<string>>();\n\n function normalizedFilePath(filePath: string) {\n return filePath.replaceAll(filePathSeperator, '/');\n }\n\n const normalizedAppRoot = normalizedFilePath(appRoot);\n\n const filePathToRoute = (filePath: string) => {\n return normalizedFilePath(filePath)\n .replace(normalizedAppRoot, '')\n .replace(/index\\.[jt]sx?/, '')\n .replace(/\\.[jt]sx?$/, '');\n };\n\n const isRouteFile = (filePath: string) => {\n // Layout and filenames starting with `+` are not routes\n if (filePath.match(/_layout\\.[tj]sx?$/) || filePath.match(/\\/\\+/)) {\n return false;\n }\n\n // Route files must be nested with in the appRoot\n const relative = path.relative(appRoot, filePath);\n return relative && !relative.startsWith('..') && !path.isAbsolute(relative);\n };\n\n const addFilePath = (filePath: string): boolean => {\n if (!isRouteFile(filePath)) {\n return false;\n }\n\n const route = filePathToRoute(filePath);\n\n // We have already processed this file\n if (staticRoutes.has(route) || dynamicRoutes.has(route)) {\n return false;\n }\n\n const dynamicParams = new Set(\n [...route.matchAll(CAPTURE_DYNAMIC_PARAMS)].map((match) => match[1])\n );\n const isDynamic = dynamicParams.size > 0;\n\n const addRoute = (originalRoute: string, route: string) => {\n if (isDynamic) {\n let set = dynamicRoutes.get(originalRoute);\n\n if (!set) {\n set = new Set();\n dynamicRoutes.set(originalRoute, set);\n }\n\n set.add(\n route\n .replaceAll(CATCH_ALL, '${CatchAllRoutePart<T>}')\n .replaceAll(SLUG, '${SingleRoutePart<T>}')\n );\n } else {\n let set = staticRoutes.get(originalRoute);\n\n if (!set) {\n set = new Set();\n staticRoutes.set(originalRoute, set);\n }\n\n set.add(route);\n }\n };\n\n if (!route.match(ARRAY_GROUP_REGEX)) {\n addRoute(route, route);\n }\n\n // Does this route have a group? eg /(group)\n if (route.includes('/(')) {\n const routeWithoutGroups = route.replace(/\\/\\(.+?\\)/g, '');\n addRoute(route, routeWithoutGroups);\n\n // If there are multiple groups, we need to expand them\n // eg /(test1,test2)/page => /test1/page & /test2/page\n for (const routeWithSingleGroup of extrapolateGroupRoutes(route)) {\n addRoute(route, routeWithSingleGroup);\n }\n }\n\n return true;\n };\n\n return {\n staticRoutes,\n dynamicRoutes,\n filePathToRoute,\n addFilePath,\n isRouteFile,\n };\n}\n\nexport const setToUnionType = <T>(set: Set<T>) => {\n return set.size > 0 ? [...set].map((s) => `\\`${s}\\``).join(' | ') : 'never';\n};\n\n/**\n * Recursively walk a directory and call the callback with the file path.\n */\nasync function walk(directory: string, callback: (filePath: string) => void) {\n const files = await fs.readdir(directory);\n for (const file of files) {\n const p = path.join(directory, file);\n if ((await fs.stat(p)).isDirectory()) {\n await walk(p, callback);\n } else {\n // Normalise the paths so they are easier to convert to URLs\n const normalizedPath = p.replaceAll(path.sep, '/');\n callback(normalizedPath);\n }\n }\n}\n\n/**\n * Given a route, return all possible routes that could be generated from it.\n */\nexport function extrapolateGroupRoutes(\n route: string,\n routes: Set<string> = new Set()\n): Set<string> {\n // Create a version with no groups. We will then need to cleanup double and/or trailing slashes\n routes.add(route.replaceAll(ARRAY_GROUP_REGEX, '').replaceAll(/\\/+/g, '/').replace(/\\/$/, ''));\n\n const match = route.match(ARRAY_GROUP_REGEX);\n\n if (!match) {\n routes.add(route);\n return routes;\n }\n\n const groupsMatch = match[0];\n\n for (const group of groupsMatch.matchAll(CAPTURE_GROUP_REGEX)) {\n extrapolateGroupRoutes(route.replace(groupsMatch, `(${group[1].trim()})`), routes);\n }\n\n return routes;\n}\n\n/**\n * NOTE: This code refers to a specific version of `expo-router` and is therefore unsafe to\n * mix with arbitrary versions.\n * TODO: Version this code with `expo-router` or version expo-router with `@expo/cli`.\n */\nconst routerDotTSTemplate = unsafeTemplate`/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/ban-types */\ndeclare module \"expo-router\" {\n import type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link';\n import type { Router as OriginalRouter } from 'expo-router/src/types';\n export * from 'expo-router/build';\n\n // prettier-ignore\n type StaticRoutes = ${'staticRoutes'};\n // prettier-ignore\n type DynamicRoutes<T extends string> = ${'dynamicRoutes'};\n // prettier-ignore\n type DynamicRouteTemplate = ${'dynamicRouteParams'};\n\n type RelativePathString = \\`./\\${string}\\` | \\`../\\${string}\\` | '..';\n type AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;\n type ExternalPathString = \\`http\\${string}\\`;\n type ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;\n type AllRoutes = ExpoRouterRoutes | ExternalPathString;\n\n /****************\n * Route Utils *\n ****************/\n\n type SearchOrHash = \\`?\\${string}\\` | \\`#\\${string}\\`;\n type UnknownInputParams = Record<string, string | number | (string | number)[]>;\n type UnknownOutputParams = Record<string, string | string[]>;\n\n /**\n * Return only the RoutePart of a string. If the string has multiple parts return never\n *\n * string | type\n * ---------|------\n * 123 | 123\n * /123/abc | never\n * 123?abc | never\n * ./123 | never\n * /123 | never\n * 123/../ | never\n */\n type SingleRoutePart<S extends string> = S extends \\`\\${string}/\\${string}\\`\n ? never\n : S extends \\`\\${string}\\${SearchOrHash}\\`\n ? never\n : S extends ''\n ? never\n : S extends \\`(\\${string})\\`\n ? never\n : S extends \\`[\\${string}]\\`\n ? never\n : S;\n\n /**\n * Return only the CatchAll router part. If the string has search parameters or a hash return never\n */\n type CatchAllRoutePart<S extends string> = S extends \\`\\${string}\\${SearchOrHash}\\`\n ? never\n : S extends ''\n ? never\n : S extends \\`\\${string}(\\${string})\\${string}\\`\n ? never\n : S extends \\`\\${string}[\\${string}]\\${string}\\`\n ? never\n : S;\n\n // type OptionalCatchAllRoutePart<S extends string> = S extends \\`\\${string}\\${SearchOrHash}\\` ? never : S\n\n /**\n * Return the name of a route parameter\n * '[test]' -> 'test'\n * 'test' -> never\n * '[...test]' -> '...test'\n */\n type IsParameter<Part> = Part extends \\`[\\${infer ParamName}]\\` ? ParamName : never;\n\n /**\n * Return a union of all parameter names. If there are no names return never\n *\n * /[test] -> 'test'\n * /[abc]/[...def] -> 'abc'|'...def'\n */\n type ParameterNames<Path> = Path extends \\`\\${infer PartA}/\\${infer PartB}\\`\n ? IsParameter<PartA> | ParameterNames<PartB>\n : IsParameter<Path>;\n\n /**\n * Returns all segements of a route.\n *\n * /(group)/123/abc/[id]/[...rest] -> ['(group)', '123', 'abc', '[id]', '[...rest]'\n */\n type RouteSegments<Path> = Path extends \\`\\${infer PartA}/\\${infer PartB}\\`\n ? PartA extends '' | '.'\n ? [...RouteSegments<PartB>]\n : [PartA, ...RouteSegments<PartB>]\n : Path extends ''\n ? []\n : [Path];\n\n /**\n * Returns a Record of the routes parameters as strings and CatchAll parameters\n *\n * There are two versions, input and output, as you can input 'string | number' but\n * the output will always be 'string'\n *\n * /[id]/[...rest] -> { id: string, rest: string[] }\n * /no-params -> {}\n */\n type InputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends \\`...\\${infer Name}\\`\n ? Name\n : Key]: Key extends \\`...\\${string}\\` ? (string | number)[] : string | number;\n } & UnknownInputParams;\n\n type OutputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends \\`...\\${infer Name}\\`\n ? Name\n : Key]: Key extends \\`...\\${string}\\` ? string[] : string;\n } & UnknownOutputParams;\n\n /**\n * Returns the search parameters for a route.\n */\n export type SearchParams<T extends AllRoutes> = T extends DynamicRouteTemplate\n ? OutputRouteParams<T>\n : T extends StaticRoutes\n ? never\n : UnknownOutputParams;\n\n /**\n * Route is mostly used as part of Href to ensure that a valid route is provided\n *\n * Given a dynamic route, this will return never. This is helpful for conditional logic\n *\n * /test -> /test, /test2, etc\n * /test/[abc] -> never\n * /test/resolve -> /test, /test2, etc\n *\n * Note that if we provide a value for [abc] then the route is allowed\n *\n * This is named Route to prevent confusion, as users they will often see it in tooltips\n */\n export type Route<T> = T extends string\n ? T extends DynamicRouteTemplate\n ? never\n :\n | StaticRoutes\n | RelativePathString\n | ExternalPathString\n | (T extends \\`\\${infer P}\\${SearchOrHash}\\`\n ? P extends DynamicRoutes<infer _>\n ? T\n : never\n : T extends DynamicRoutes<infer _>\n ? T\n : never)\n : never;\n\n /*********\n * Href *\n *********/\n\n export type Href<T> = T extends Record<'pathname', string> ? HrefObject<T> : Route<T>;\n\n export type HrefObject<\n R extends Record<'pathname', string>,\n P = R['pathname']\n > = P extends DynamicRouteTemplate\n ? { pathname: P; params: InputRouteParams<P> }\n : P extends Route<P>\n ? { pathname: Route<P> | DynamicRouteTemplate; params?: never | InputRouteParams<never> }\n : never;\n\n /***********************\n * Expo Router Exports *\n ***********************/\n\n export type Router = Omit<OriginalRouter, 'push' | 'replace' | 'setParams'> & {\n /** Navigate to the provided href. */\n push: <T>(href: Href<T>) => void;\n /** Navigate to route without appending to the history. */\n replace: <T>(href: Href<T>) => void;\n /** Update the current route query params. */\n setParams: <T = ''>(params?: T extends '' ? Record<string, string> : InputRouteParams<T>) => void;\n };\n\n /** The imperative router. */\n export const router: Router;\n\n /************\n * <Link /> *\n ************/\n export interface LinkProps<T> extends OriginalLinkProps {\n href: Href<T>;\n }\n\n export interface LinkComponent {\n <T>(props: React.PropsWithChildren<LinkProps<T>>): JSX.Element;\n /** Helper method to resolve an Href object into a string. */\n resolveHref: <T>(href: Href<T>) => string;\n }\n\n /**\n * Component to render link to another route using a path.\n * Uses an anchor tag on the web.\n *\n * @param props.href Absolute path to route (e.g. \\`/feeds/hot\\`).\n * @param props.replace Should replace the current route without adding to the history.\n * @param props.asChild Forward props to child component. Useful for custom buttons.\n * @param props.children Child elements to render the content.\n */\n export const Link: LinkComponent;\n \n /** Redirects to the href as soon as the component is mounted. */\n export const Redirect: <T>(\n props: React.PropsWithChildren<{ href: Href<T> }>\n ) => JSX.Element;\n\n /************\n * Hooks *\n ************/\n export function useRouter(): Router;\n\n export function useLocalSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams\n >(): T extends AllRoutes ? SearchParams<T> : T;\n\n /** @deprecated renamed to \\`useGlobalSearchParams\\` */\n export function useSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams\n >(): T extends AllRoutes ? SearchParams<T> : T;\n\n export function useGlobalSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams\n >(): T extends AllRoutes ? SearchParams<T> : T;\n\n export function useSegments<\n T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString\n >(): T extends AbsoluteRoute ? RouteSegments<T> : T extends string ? string[] : T;\n}\n`;\n"],"names":["setupTypedRoutes","getTemplateString","getTypedRoutesUtils","extrapolateGroupRoutes","CAPTURE_DYNAMIC_PARAMS","CATCH_ALL","SLUG","ARRAY_GROUP_REGEX","CAPTURE_GROUP_REGEX","server","metro","typesDirectory","projectRoot","routerDirectory","absoluteRouterDirectory","path","join","filePathToRoute","staticRoutes","dynamicRoutes","addFilePath","isRouteFile","metroWatchTypeScriptFiles","eventTypes","callback","filePath","type","shouldRegenerate","route","delete","regenerateRouterDotTS","Set","values","flatMap","v","Array","from","keys","directoryExistsAsync","walk","debounce","typesDir","dynamicRouteTemplates","fs","mkdir","recursive","writeFile","resolve","routerDotTSTemplate","setToUnionType","dynamicRouteParams","appRoot","filePathSeperator","sep","Map","normalizedFilePath","replaceAll","normalizedAppRoot","replace","match","relative","startsWith","isAbsolute","has","dynamicParams","matchAll","map","isDynamic","size","addRoute","originalRoute","set","get","add","includes","routeWithoutGroups","routeWithSingleGroup","s","directory","files","readdir","file","p","stat","isDirectory","normalizedPath","routes","groupsMatch","group","trim","unsafeTemplate"],"mappings":"AAAA;;;;QA6BsBA,gBAAgB,GAAhBA,gBAAgB;QAoFtBC,iBAAiB,GAAjBA,iBAAiB;QAiBjBC,mBAA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmOrD,CAAC,AAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/type-generation/routes.ts"],"sourcesContent":["import fs from 'fs/promises';\nimport { debounce } from 'lodash';\nimport { Server } from 'metro';\nimport path from 'path';\n\nimport { directoryExistsAsync } from '../../../utils/dir';\nimport { unsafeTemplate } from '../../../utils/template';\nimport { ServerLike } from '../BundlerDevServer';\nimport { metroWatchTypeScriptFiles } from '../metro/metroWatchTypeScriptFiles';\n\n// /test/[...param1]/[param2]/[param3] - captures [\"param1\", \"param2\", \"param3\"]\nexport const CAPTURE_DYNAMIC_PARAMS = /\\[(?:\\.{3})?(\\w*?)[\\]$]/g;\n// /[...param1]/ - Match [...param1]\nexport const CATCH_ALL = /\\[\\.\\.\\..+?\\]/g;\n// /[param1] - Match [param1]\nexport const SLUG = /\\[.+?\\]/g;\n// /(group1,group2,group3)/test - match (group1,group2,group3)\nexport const ARRAY_GROUP_REGEX = /\\(\\s*\\w[\\w\\s]*?,.*?\\)/g;\n// /(group1,group2,group3)/test - captures [\"group1\", \"group2\", \"group3\"]\nexport const CAPTURE_GROUP_REGEX = /[\\\\(,]\\s*(\\w[\\w\\s]*?)\\s*(?=[,\\\\)])/g;\n\nexport interface SetupTypedRoutesOptions {\n server?: ServerLike;\n metro?: Server | null;\n typesDirectory: string;\n projectRoot: string;\n routerDirectory: string;\n}\n\nexport async function setupTypedRoutes({\n server,\n metro,\n typesDirectory,\n projectRoot,\n routerDirectory,\n}: SetupTypedRoutesOptions) {\n const absoluteRouterDirectory = path.join(projectRoot, routerDirectory);\n\n const { filePathToRoute, staticRoutes, dynamicRoutes, addFilePath, isRouteFile } =\n getTypedRoutesUtils(absoluteRouterDirectory);\n\n if (metro && server) {\n // Setup out watcher first\n metroWatchTypeScriptFiles({\n projectRoot,\n server,\n metro,\n eventTypes: ['add', 'delete', 'change'],\n async callback({ filePath, type }) {\n if (!isRouteFile(filePath)) {\n return;\n }\n\n let shouldRegenerate = false;\n\n if (type === 'delete') {\n const route = filePathToRoute(filePath);\n staticRoutes.delete(route);\n dynamicRoutes.delete(route);\n shouldRegenerate = true;\n } else {\n shouldRegenerate = addFilePath(filePath);\n }\n\n if (shouldRegenerate) {\n regenerateRouterDotTS(\n typesDirectory,\n new Set([...staticRoutes.values()].flatMap((v) => Array.from(v))),\n new Set([...dynamicRoutes.values()].flatMap((v) => Array.from(v))),\n new Set(dynamicRoutes.keys())\n );\n }\n },\n });\n }\n\n if (await directoryExistsAsync(absoluteRouterDirectory)) {\n // Do we need to walk the entire tree on startup?\n // Idea: Store the list of files in the last write, then simply check Git for what files have changed\n await walk(absoluteRouterDirectory, addFilePath);\n }\n\n regenerateRouterDotTS(\n typesDirectory,\n new Set([...staticRoutes.values()].flatMap((v) => Array.from(v))),\n new Set([...dynamicRoutes.values()].flatMap((v) => Array.from(v))),\n new Set(dynamicRoutes.keys())\n );\n}\n\n/**\n * Generate a router.d.ts file that contains all of the routes in the project.\n * Should be debounced as its very common for developers to make changes to multiple files at once (eg Save All)\n */\nconst regenerateRouterDotTS = debounce(\n async (\n typesDir: string,\n staticRoutes: Set<string>,\n dynamicRoutes: Set<string>,\n dynamicRouteTemplates: Set<string>\n ) => {\n await fs.mkdir(typesDir, { recursive: true });\n await fs.writeFile(\n path.resolve(typesDir, './router.d.ts'),\n getTemplateString(staticRoutes, dynamicRoutes, dynamicRouteTemplates)\n );\n },\n 100\n);\n\n/*\n * This is exported for testing purposes\n */\nexport function getTemplateString(\n staticRoutes: Set<string>,\n dynamicRoutes: Set<string>,\n dynamicRouteTemplates: Set<string>\n) {\n return routerDotTSTemplate({\n staticRoutes: setToUnionType(staticRoutes),\n dynamicRoutes: setToUnionType(dynamicRoutes),\n dynamicRouteParams: setToUnionType(dynamicRouteTemplates),\n });\n}\n\n/**\n * Utility functions for typed routes\n *\n * These are extracted for easier testing\n */\nexport function getTypedRoutesUtils(appRoot: string, filePathSeperator = path.sep) {\n /*\n * staticRoutes are a map where the key if the route without groups and the value\n * is another set of all group versions of the route. e.g,\n * Map([\n * [\"/\", [\"/(app)/(notes)\", \"/(app)/(profile)\"]\n * ])\n */\n const staticRoutes = new Map<string, Set<string>>([['/', new Set('/')]]);\n /*\n * dynamicRoutes are the same as staticRoutes (key if the resolved route,\n * and the value is a set of possible routes). e.g:\n *\n * /[...fruits] -> /${CatchAllRoutePart<T>}\n * /color/[color] -> /color/${SingleRoutePart<T>}\n *\n * The keys of this map are also important, as they can be used as \"static\" types\n * <Link href={{ pathname: \"/[...fruits]\",params: { fruits: [\"apple\"] } }} />\n */\n const dynamicRoutes = new Map<string, Set<string>>();\n\n function normalizedFilePath(filePath: string) {\n return filePath.replaceAll(filePathSeperator, '/');\n }\n\n const normalizedAppRoot = normalizedFilePath(appRoot);\n\n const filePathToRoute = (filePath: string) => {\n return normalizedFilePath(filePath)\n .replace(normalizedAppRoot, '')\n .replace(/index\\.[jt]sx?/, '')\n .replace(/\\.[jt]sx?$/, '');\n };\n\n const isRouteFile = (filePath: string) => {\n // Layout and filenames starting with `+` are not routes\n if (filePath.match(/_layout\\.[tj]sx?$/) || filePath.match(/\\/\\+/)) {\n return false;\n }\n\n // Route files must be nested with in the appRoot\n const relative = path.relative(appRoot, filePath);\n return relative && !relative.startsWith('..') && !path.isAbsolute(relative);\n };\n\n const addFilePath = (filePath: string): boolean => {\n if (!isRouteFile(filePath)) {\n return false;\n }\n\n const route = filePathToRoute(filePath);\n\n // We have already processed this file\n if (staticRoutes.has(route) || dynamicRoutes.has(route)) {\n return false;\n }\n\n const dynamicParams = new Set(\n [...route.matchAll(CAPTURE_DYNAMIC_PARAMS)].map((match) => match[1])\n );\n const isDynamic = dynamicParams.size > 0;\n\n const addRoute = (originalRoute: string, route: string) => {\n if (isDynamic) {\n let set = dynamicRoutes.get(originalRoute);\n\n if (!set) {\n set = new Set();\n dynamicRoutes.set(originalRoute, set);\n }\n\n set.add(\n route\n .replaceAll(CATCH_ALL, '${CatchAllRoutePart<T>}')\n .replaceAll(SLUG, '${SingleRoutePart<T>}')\n );\n } else {\n let set = staticRoutes.get(originalRoute);\n\n if (!set) {\n set = new Set();\n staticRoutes.set(originalRoute, set);\n }\n\n set.add(route);\n }\n };\n\n if (!route.match(ARRAY_GROUP_REGEX)) {\n addRoute(route, route);\n }\n\n // Does this route have a group? eg /(group)\n if (route.includes('/(')) {\n const routeWithoutGroups = route.replace(/\\/\\(.+?\\)/g, '');\n addRoute(route, routeWithoutGroups);\n\n // If there are multiple groups, we need to expand them\n // eg /(test1,test2)/page => /test1/page & /test2/page\n for (const routeWithSingleGroup of extrapolateGroupRoutes(route)) {\n addRoute(route, routeWithSingleGroup);\n }\n }\n\n return true;\n };\n\n return {\n staticRoutes,\n dynamicRoutes,\n filePathToRoute,\n addFilePath,\n isRouteFile,\n };\n}\n\nexport const setToUnionType = <T>(set: Set<T>) => {\n return set.size > 0 ? [...set].map((s) => `\\`${s}\\``).join(' | ') : 'never';\n};\n\n/**\n * Recursively walk a directory and call the callback with the file path.\n */\nasync function walk(directory: string, callback: (filePath: string) => void) {\n const files = await fs.readdir(directory);\n for (const file of files) {\n const p = path.join(directory, file);\n if ((await fs.stat(p)).isDirectory()) {\n await walk(p, callback);\n } else {\n // Normalise the paths so they are easier to convert to URLs\n const normalizedPath = p.replaceAll(path.sep, '/');\n callback(normalizedPath);\n }\n }\n}\n\n/**\n * Given a route, return all possible routes that could be generated from it.\n */\nexport function extrapolateGroupRoutes(\n route: string,\n routes: Set<string> = new Set()\n): Set<string> {\n // Create a version with no groups. We will then need to cleanup double and/or trailing slashes\n routes.add(route.replaceAll(ARRAY_GROUP_REGEX, '').replaceAll(/\\/+/g, '/').replace(/\\/$/, ''));\n\n const match = route.match(ARRAY_GROUP_REGEX);\n\n if (!match) {\n routes.add(route);\n return routes;\n }\n\n const groupsMatch = match[0];\n\n for (const group of groupsMatch.matchAll(CAPTURE_GROUP_REGEX)) {\n extrapolateGroupRoutes(route.replace(groupsMatch, `(${group[1].trim()})`), routes);\n }\n\n return routes;\n}\n\n/**\n * NOTE: This code refers to a specific version of `expo-router` and is therefore unsafe to\n * mix with arbitrary versions.\n * TODO: Version this code with `expo-router` or version expo-router with `@expo/cli`.\n */\nconst routerDotTSTemplate = unsafeTemplate`/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable import/export */\n/* eslint-disable @typescript-eslint/ban-types */\ndeclare module \"expo-router\" {\n import type { LinkProps as OriginalLinkProps } from 'expo-router/build/link/Link';\n import type { Router as OriginalRouter } from 'expo-router/src/types';\n export * from 'expo-router/build';\n\n // prettier-ignore\n type StaticRoutes = ${'staticRoutes'};\n // prettier-ignore\n type DynamicRoutes<T extends string> = ${'dynamicRoutes'};\n // prettier-ignore\n type DynamicRouteTemplate = ${'dynamicRouteParams'};\n\n type RelativePathString = \\`./\\${string}\\` | \\`../\\${string}\\` | '..';\n type AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;\n type ExternalPathString = \\`http\\${string}\\`;\n type ExpoRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;\n type AllRoutes = ExpoRouterRoutes | ExternalPathString;\n\n /****************\n * Route Utils *\n ****************/\n\n type SearchOrHash = \\`?\\${string}\\` | \\`#\\${string}\\`;\n type UnknownInputParams = Record<string, string | number | (string | number)[]>;\n type UnknownOutputParams = Record<string, string | string[]>;\n\n /**\n * Return only the RoutePart of a string. If the string has multiple parts return never\n *\n * string | type\n * ---------|------\n * 123 | 123\n * /123/abc | never\n * 123?abc | never\n * ./123 | never\n * /123 | never\n * 123/../ | never\n */\n type SingleRoutePart<S extends string> = S extends \\`\\${string}/\\${string}\\`\n ? never\n : S extends \\`\\${string}\\${SearchOrHash}\\`\n ? never\n : S extends ''\n ? never\n : S extends \\`(\\${string})\\`\n ? never\n : S extends \\`[\\${string}]\\`\n ? never\n : S;\n\n /**\n * Return only the CatchAll router part. If the string has search parameters or a hash return never\n */\n type CatchAllRoutePart<S extends string> = S extends \\`\\${string}\\${SearchOrHash}\\`\n ? never\n : S extends ''\n ? never\n : S extends \\`\\${string}(\\${string})\\${string}\\`\n ? never\n : S extends \\`\\${string}[\\${string}]\\${string}\\`\n ? never\n : S;\n\n // type OptionalCatchAllRoutePart<S extends string> = S extends \\`\\${string}\\${SearchOrHash}\\` ? never : S\n\n /**\n * Return the name of a route parameter\n * '[test]' -> 'test'\n * 'test' -> never\n * '[...test]' -> '...test'\n */\n type IsParameter<Part> = Part extends \\`[\\${infer ParamName}]\\` ? ParamName : never;\n\n /**\n * Return a union of all parameter names. If there are no names return never\n *\n * /[test] -> 'test'\n * /[abc]/[...def] -> 'abc'|'...def'\n */\n type ParameterNames<Path> = Path extends \\`\\${infer PartA}/\\${infer PartB}\\`\n ? IsParameter<PartA> | ParameterNames<PartB>\n : IsParameter<Path>;\n\n /**\n * Returns all segements of a route.\n *\n * /(group)/123/abc/[id]/[...rest] -> ['(group)', '123', 'abc', '[id]', '[...rest]'\n */\n type RouteSegments<Path> = Path extends \\`\\${infer PartA}/\\${infer PartB}\\`\n ? PartA extends '' | '.'\n ? [...RouteSegments<PartB>]\n : [PartA, ...RouteSegments<PartB>]\n : Path extends ''\n ? []\n : [Path];\n\n /**\n * Returns a Record of the routes parameters as strings and CatchAll parameters\n *\n * There are two versions, input and output, as you can input 'string | number' but\n * the output will always be 'string'\n *\n * /[id]/[...rest] -> { id: string, rest: string[] }\n * /no-params -> {}\n */\n type InputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends \\`...\\${infer Name}\\`\n ? Name\n : Key]: Key extends \\`...\\${string}\\` ? (string | number)[] : string | number;\n } & UnknownInputParams;\n\n type OutputRouteParams<Path> = {\n [Key in ParameterNames<Path> as Key extends \\`...\\${infer Name}\\`\n ? Name\n : Key]: Key extends \\`...\\${string}\\` ? string[] : string;\n } & UnknownOutputParams;\n\n /**\n * Returns the search parameters for a route.\n */\n export type SearchParams<T extends AllRoutes> = T extends DynamicRouteTemplate\n ? OutputRouteParams<T>\n : T extends StaticRoutes\n ? never\n : UnknownOutputParams;\n\n /**\n * Route is mostly used as part of Href to ensure that a valid route is provided\n *\n * Given a dynamic route, this will return never. This is helpful for conditional logic\n *\n * /test -> /test, /test2, etc\n * /test/[abc] -> never\n * /test/resolve -> /test, /test2, etc\n *\n * Note that if we provide a value for [abc] then the route is allowed\n *\n * This is named Route to prevent confusion, as users they will often see it in tooltips\n */\n export type Route<T> = T extends string\n ? T extends DynamicRouteTemplate\n ? never\n :\n | StaticRoutes\n | RelativePathString\n | ExternalPathString\n | (T extends \\`\\${infer P}\\${SearchOrHash}\\`\n ? P extends DynamicRoutes<infer _>\n ? T\n : never\n : T extends DynamicRoutes<infer _>\n ? T\n : never)\n : never;\n\n /*********\n * Href *\n *********/\n\n export type Href<T> = T extends Record<'pathname', string> ? HrefObject<T> : Route<T>;\n\n export type HrefObject<\n R extends Record<'pathname', string>,\n P = R['pathname'],\n > = P extends DynamicRouteTemplate\n ? { pathname: P; params: InputRouteParams<P> }\n : P extends Route<P>\n ? { pathname: Route<P> | DynamicRouteTemplate; params?: never | InputRouteParams<never> }\n : never;\n\n /***********************\n * Expo Router Exports *\n ***********************/\n\n export type Router = Omit<OriginalRouter, 'push' | 'replace' | 'setParams'> & {\n /** Navigate to the provided href. */\n push: <T>(href: Href<T>) => void;\n /** Navigate to route without appending to the history. */\n replace: <T>(href: Href<T>) => void;\n /** Update the current route query params. */\n setParams: <T = ''>(params?: T extends '' ? Record<string, string> : InputRouteParams<T>) => void;\n };\n\n /** The imperative router. */\n export const router: Router;\n\n /************\n * <Link /> *\n ************/\n export interface LinkProps<T> extends OriginalLinkProps {\n href: Href<T>;\n }\n\n export interface LinkComponent {\n <T>(props: React.PropsWithChildren<LinkProps<T>>): JSX.Element;\n /** Helper method to resolve an Href object into a string. */\n resolveHref: <T>(href: Href<T>) => string;\n }\n\n /**\n * Component to render link to another route using a path.\n * Uses an anchor tag on the web.\n *\n * @param props.href Absolute path to route (e.g. \\`/feeds/hot\\`).\n * @param props.replace Should replace the current route without adding to the history.\n * @param props.asChild Forward props to child component. Useful for custom buttons.\n * @param props.children Child elements to render the content.\n */\n export const Link: LinkComponent;\n \n /** Redirects to the href as soon as the component is mounted. */\n export const Redirect: <T>(\n props: React.PropsWithChildren<{ href: Href<T> }>\n ) => JSX.Element;\n\n /************\n * Hooks *\n ************/\n export function useRouter(): Router;\n\n export function useLocalSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n >(): T extends AllRoutes ? SearchParams<T> : T;\n\n /** @deprecated renamed to \\`useGlobalSearchParams\\` */\n export function useSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n >(): T extends AllRoutes ? SearchParams<T> : T;\n\n export function useGlobalSearchParams<\n T extends AllRoutes | UnknownOutputParams = UnknownOutputParams,\n >(): T extends AllRoutes ? SearchParams<T> : T;\n\n export function useSegments<\n T extends AbsoluteRoute | RouteSegments<AbsoluteRoute> | RelativePathString,\n >(): T extends AbsoluteRoute ? RouteSegments<T> : T extends string ? string[] : T;\n}\n`;\n"],"names":["setupTypedRoutes","getTemplateString","getTypedRoutesUtils","extrapolateGroupRoutes","CAPTURE_DYNAMIC_PARAMS","CATCH_ALL","SLUG","ARRAY_GROUP_REGEX","CAPTURE_GROUP_REGEX","server","metro","typesDirectory","projectRoot","routerDirectory","absoluteRouterDirectory","path","join","filePathToRoute","staticRoutes","dynamicRoutes","addFilePath","isRouteFile","metroWatchTypeScriptFiles","eventTypes","callback","filePath","type","shouldRegenerate","route","delete","regenerateRouterDotTS","Set","values","flatMap","v","Array","from","keys","directoryExistsAsync","walk","debounce","typesDir","dynamicRouteTemplates","fs","mkdir","recursive","writeFile","resolve","routerDotTSTemplate","setToUnionType","dynamicRouteParams","appRoot","filePathSeperator","sep","Map","normalizedFilePath","replaceAll","normalizedAppRoot","replace","match","relative","startsWith","isAbsolute","has","dynamicParams","matchAll","map","isDynamic","size","addRoute","originalRoute","set","get","add","includes","routeWithoutGroups","routeWithSingleGroup","s","directory","files","readdir","file","p","stat","isDirectory","normalizedPath","routes","groupsMatch","group","trim","unsafeTemplate"],"mappings":"AAAA;;;;QA6BsBA,gBAAgB,GAAhBA,gBAAgB;QAoFtBC,iBAAiB,GAAjBA,iBAAiB;QAiBjBC,mBAAmB,GAAnBA,mBAAmB;QA4InBC,sBAAsB,GAAtBA,sBAAsB;;AA9QvB,IAAA,SAAa,kCAAb,aAAa,EAAA;AACH,IAAA,OAAQ,WAAR,QAAQ,CAAA;AAEhB,IAAA,KAAM,kCAAN,MAAM,EAAA;AAEc,IAAA,IAAoB,WAApB,oBAAoB,CAAA;AAC1B,IAAA,SAAyB,WAAzB,yBAAyB,CAAA;AAEd,IAAA,0BAAoC,WAApC,oCAAoC,CAAA;;;;;;AAGvE,MAAMC,sBAAsB,6BAA6B,AAAC;QAApDA,sBAAsB,GAAtBA,sBAAsB;AAE5B,MAAMC,SAAS,mBAAmB,AAAC;QAA7BA,SAAS,GAATA,SAAS;AAEf,MAAMC,IAAI,aAAa,AAAC;QAAlBA,IAAI,GAAJA,IAAI;AAEV,MAAMC,iBAAiB,2BAA2B,AAAC;QAA7CA,iBAAiB,GAAjBA,iBAAiB;AAEvB,MAAMC,mBAAmB,wCAAwC,AAAC;QAA5DA,mBAAmB,GAAnBA,mBAAmB;AAUzB,eAAeR,gBAAgB,CAAC,EACrCS,MAAM,CAAA,EACNC,KAAK,CAAA,EACLC,cAAc,CAAA,EACdC,WAAW,CAAA,EACXC,eAAe,CAAA,EACS,EAAE;IAC1B,MAAMC,uBAAuB,GAAGC,KAAI,QAAA,CAACC,IAAI,CAACJ,WAAW,EAAEC,eAAe,CAAC,AAAC;IAExE,MAAM,EAAEI,eAAe,CAAA,EAAEC,YAAY,CA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AC,EAAEC,KAAK,CAAC,CAAC,CAAC,CAACC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,EAAEH,MAAM,CAAC,CAAC;KACpF;IAED,OAAOA,MAAM,CAAC;CACf;AAED;;;;GAIG,CACH,MAAMtC,mBAAmB,GAAG0C,SAAc,eAAA,CAAC;;;;;;;;;sBASrB,EAAE,cAAc,CAAC;;yCAEE,EAAE,eAAe,CAAC;;8BAE7B,EAAE,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmOrD,CAAC,AAAC"}
|
|
@@ -6,12 +6,12 @@ exports.startTypescriptTypeGenerationAsync = startTypescriptTypeGenerationAsync;
|
|
|
6
6
|
var _config = require("@expo/config");
|
|
7
7
|
var _promises = _interopRequireDefault(require("fs/promises"));
|
|
8
8
|
var _path = _interopRequireDefault(require("path"));
|
|
9
|
-
var _mergeGitIgnorePaths = require("../../../utils/mergeGitIgnorePaths");
|
|
10
|
-
var _dotExpo = require("../../project/dotExpo");
|
|
11
|
-
var _router = require("../metro/router");
|
|
12
9
|
var _expoEnv = require("./expo-env");
|
|
13
10
|
var _routes = require("./routes");
|
|
14
11
|
var _tsconfig = require("./tsconfig");
|
|
12
|
+
var _mergeGitIgnorePaths = require("../../../utils/mergeGitIgnorePaths");
|
|
13
|
+
var _dotExpo = require("../../project/dotExpo");
|
|
14
|
+
var _router = require("../metro/router");
|
|
15
15
|
function _interopRequireDefault(obj) {
|
|
16
16
|
return obj && obj.__esModule ? obj : {
|
|
17
17
|
default: obj
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/start/server/type-generation/startTypescriptTypeGeneration.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport fs from 'fs/promises';\nimport { Server } from 'metro';\nimport path from 'path';\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../src/start/server/type-generation/startTypescriptTypeGeneration.ts"],"sourcesContent":["import { getConfig } from '@expo/config';\nimport fs from 'fs/promises';\nimport { Server } from 'metro';\nimport path from 'path';\n\nimport { removeExpoEnvDTS, writeExpoEnvDTS } from './expo-env';\nimport { setupTypedRoutes } from './routes';\nimport { forceRemovalTSConfig, forceUpdateTSConfig } from './tsconfig';\nimport { upsertGitIgnoreContents, removeFromGitIgnore } from '../../../utils/mergeGitIgnorePaths';\nimport { ensureDotExpoProjectDirectoryInitialized } from '../../project/dotExpo';\nimport { ServerLike } from '../BundlerDevServer';\nimport { getRouterDirectory } from '../metro/router';\n\nexport interface TypeScriptTypeGenerationOptions {\n server?: ServerLike;\n metro?: Server | null;\n projectRoot: string;\n}\n\nconst debug = require('debug')('expo:typed-routes') as typeof console.log;\n\n/** Setup all requisite features for statically typed routes in Expo Router v2 / SDK +49. */\nexport async function startTypescriptTypeGenerationAsync({\n metro,\n projectRoot,\n server,\n}: TypeScriptTypeGenerationOptions) {\n const { exp } = getConfig(projectRoot);\n\n // If typed routes are disabled, remove any files that were added.\n if (!exp.experiments?.typedRoutes) {\n debug('Removing typed routes side-effects (experiments.typedRoutes: false)');\n const gitIgnorePath = path.join(projectRoot, '.gitignore');\n await Promise.all([\n forceRemovalTSConfig(projectRoot),\n removeExpoEnvDTS(projectRoot),\n removeFromGitIgnore(gitIgnorePath, 'expo-env.d.ts'),\n ]);\n } else {\n const dotExpoDir = ensureDotExpoProjectDirectoryInitialized(projectRoot);\n const typesDirectory = path.resolve(dotExpoDir, './types');\n debug(\n 'Ensuring typed routes side-effects are setup (experiments.typedRoutes: true, typesDirectory: %s)',\n typesDirectory\n );\n\n // Ensure the types directory exists.\n await fs.mkdir(typesDirectory, { recursive: true });\n\n await Promise.all([\n upsertGitIgnoreContents(path.join(projectRoot, '.gitignore'), 'expo-env.d.ts'),\n writeExpoEnvDTS(projectRoot),\n forceUpdateTSConfig(projectRoot),\n setupTypedRoutes({\n metro,\n server,\n typesDirectory,\n projectRoot,\n routerDirectory: exp.extra?.router?.unstable_src ?? getRouterDirectory(projectRoot),\n }),\n ]);\n }\n}\n"],"names":["startTypescriptTypeGenerationAsync","debug","require","metro","projectRoot","server","exp","getConfig","experiments","typedRoutes","gitIgnorePath","path","join","Promise","all","forceRemovalTSConfig","removeExpoEnvDTS","removeFromGitIgnore","dotExpoDir","ensureDotExpoProjectDirectoryInitialized","typesDirectory","resolve","fs","mkdir","recursive","upsertGitIgnoreContents","writeExpoEnvDTS","forceUpdateTSConfig","setupTypedRoutes","routerDirectory","extra","router","unstable_src","getRouterDirectory"],"mappings":"AAAA;;;;QAsBsBA,kCAAkC,GAAlCA,kCAAkC;AAtB9B,IAAA,OAAc,WAAd,cAAc,CAAA;AACzB,IAAA,SAAa,kCAAb,aAAa,EAAA;AAEX,IAAA,KAAM,kCAAN,MAAM,EAAA;AAE2B,IAAA,QAAY,WAAZ,YAAY,CAAA;AAC7B,IAAA,OAAU,WAAV,UAAU,CAAA;AACe,IAAA,SAAY,WAAZ,YAAY,CAAA;AACT,IAAA,oBAAoC,WAApC,oCAAoC,CAAA;AACxC,IAAA,QAAuB,WAAvB,uBAAuB,CAAA;AAE7C,IAAA,OAAiB,WAAjB,iBAAiB,CAAA;;;;;;AAQpD,MAAMC,KAAK,GAAGC,OAAO,CAAC,OAAO,CAAC,CAAC,mBAAmB,CAAC,AAAsB,AAAC;AAGnE,eAAeF,kCAAkC,CAAC,EACvDG,KAAK,CAAA,EACLC,WAAW,CAAA,EACXC,MAAM,CAAA,EAC0B,EAAE;QAI7BC,GAAe;IAHpB,MAAM,EAAEA,GAAG,CAAA,EAAE,GAAGC,CAAAA,GAAAA,OAAS,AAAa,CAAA,UAAb,CAACH,WAAW,CAAC,AAAC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AACvB,WAAW,CAAC;YAChCwB,CAAAA,GAAAA,OAAgB,AAMd,CAAA,iBANc,CAAC;gBACfzB,KAAK;gBACLE,MAAM;gBACNe,cAAc;gBACdhB,WAAW;gBACXyB,eAAe,EAAEvB,CAAAA,IAA+B,GAA/BA,CAAAA,IAAS,GAATA,GAAG,CAACwB,KAAK,SAAQ,GAAjBxB,KAAAA,CAAiB,GAAjBA,QAAAA,IAAS,CAAEyB,MAAM,SAAA,GAAjBzB,KAAAA,CAAiB,QAAE0B,YAAY,AAAd,YAAjB1B,IAA+B,GAAI2B,CAAAA,GAAAA,OAAkB,AAAa,CAAA,mBAAb,CAAC7B,WAAW,CAAC;aACpF,CAAC;SACH,CAAC,CAAC;KACJ;CACF"}
|
|
@@ -7,6 +7,9 @@ var _chalk = _interopRequireDefault(require("chalk"));
|
|
|
7
7
|
var _fs = _interopRequireDefault(require("fs"));
|
|
8
8
|
var path = _interopRequireWildcard(require("path"));
|
|
9
9
|
var _resolveFrom = _interopRequireDefault(require("resolve-from"));
|
|
10
|
+
var _compile = require("./compile");
|
|
11
|
+
var _resolveFromProject = require("./resolveFromProject");
|
|
12
|
+
var _tls = require("./tls");
|
|
10
13
|
var Log = _interopRequireWildcard(require("../../../log"));
|
|
11
14
|
var _env = require("../../../utils/env");
|
|
12
15
|
var _errors = require("../../../utils/errors");
|
|
@@ -16,9 +19,6 @@ var _port = require("../../../utils/port");
|
|
|
16
19
|
var _progress = require("../../../utils/progress");
|
|
17
20
|
var _dotExpo = require("../../project/dotExpo");
|
|
18
21
|
var _bundlerDevServer = require("../BundlerDevServer");
|
|
19
|
-
var _compile = require("./compile");
|
|
20
|
-
var _resolveFromProject = require("./resolveFromProject");
|
|
21
|
-
var _tls = require("./tls");
|
|
22
22
|
function _interopRequireDefault(obj) {
|
|
23
23
|
return obj && obj.__esModule ? obj : {
|
|
24
24
|
default: obj
|
|
@@ -47,7 +47,7 @@ function _interopRequireWildcard(obj) {
|
|
|
47
47
|
}
|
|
48
48
|
const debug = require("debug")("expo:start:server:webpack:devServer");
|
|
49
49
|
function assertIsWebpackDevServer(value) {
|
|
50
|
-
if (!(value == null ? void 0 : value.sockWrite)) {
|
|
50
|
+
if (!(value == null ? void 0 : value.sockWrite) && !(value == null ? void 0 : value.sendMessage)) {
|
|
51
51
|
var ref;
|
|
52
52
|
var ref1;
|
|
53
53
|
throw new _errors.CommandError("WEBPACK", value ? "Expected Webpack dev server, found: " + ((ref1 = (ref = value.constructor) == null ? void 0 : ref.name) != null ? ref1 : value) : "Webpack dev server not started yet.");
|
|
@@ -75,7 +75,12 @@ class WebpackBundlerDevServer extends _bundlerDevServer.BundlerDevServer {
|
|
|
75
75
|
// Default webpack-dev-server sockets use "content-changed" instead of "reload" (what we use on native).
|
|
76
76
|
// For now, just manually convert the value so our CLI interface can be unified.
|
|
77
77
|
const hackyConvertedMessage = method === "reload" ? "content-changed" : method;
|
|
78
|
-
|
|
78
|
+
if ("sendMessage" in this.instance.server) {
|
|
79
|
+
// @ts-expect-error: https://github.com/expo/expo/issues/21994#issuecomment-1517122501
|
|
80
|
+
this.instance.server.sendMessage(this.instance.server.sockets, hackyConvertedMessage, params);
|
|
81
|
+
} else {
|
|
82
|
+
this.instance.server.sockWrite(this.instance.server.sockets, hackyConvertedMessage, params);
|
|
83
|
+
}
|
|
79
84
|
}
|
|
80
85
|
async attachNativeDevServerMiddlewareToDevServer({ server , middleware , attachToServer , logger }) {
|
|
81
86
|
const { attachInspectorProxy , LogReporter } = await Promise.resolve().then(function() {
|