@cloudflare/worker-bundler 0.2.4 → 0.2.6
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/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as hasDependencies, r as installDependencies } from "./installer-
|
|
1
|
+
import { n as hasDependencies, r as installDependencies } from "./installer-Dzd--DQ7.js";
|
|
2
2
|
import * as esbuild from "esbuild-wasm/lib/browser.js";
|
|
3
3
|
import { parse } from "es-module-lexer/js";
|
|
4
4
|
import * as resolveExports from "resolve.exports";
|
|
@@ -79,13 +79,17 @@ function resolvePackage(specifier, files, conditions, extensions) {
|
|
|
79
79
|
}
|
|
80
80
|
} catch {}
|
|
81
81
|
const legacyEntry = resolveExports.legacy(pkg, { fields: ["module", "main"] });
|
|
82
|
-
if (legacyEntry && typeof legacyEntry === "string") {
|
|
82
|
+
if (!subpath && legacyEntry && typeof legacyEntry === "string") {
|
|
83
83
|
const fullPath = `node_modules/${packageName}/${normalizeRelativePath(legacyEntry)}`;
|
|
84
84
|
if (files.read(fullPath) !== null) return {
|
|
85
85
|
path: fullPath,
|
|
86
86
|
external: false
|
|
87
87
|
};
|
|
88
88
|
}
|
|
89
|
+
if (subpath && pkg.exports !== void 0) return {
|
|
90
|
+
path: specifier,
|
|
91
|
+
external: true
|
|
92
|
+
};
|
|
89
93
|
const indexPath = resolveWithExtensions(`node_modules/${packageName}${subpath ? `/${subpath}` : ""}`, files, extensions);
|
|
90
94
|
if (indexPath) return {
|
|
91
95
|
path: indexPath,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["getDirectory","parseToml"],"sources":["../src/resolver.ts","../src/bundler.ts","../src/config.ts","../src/transformer.ts","../src/utils.ts","../src/experimental.ts","../src/file-system.ts","../src/mime.ts","../src/asset-handler.ts","../src/app.ts","../src/index.ts"],"sourcesContent":["// Use the asm.js version to avoid WASM (works in workerd)\nimport { parse } from \"es-module-lexer/js\";\nimport * as resolveExports from \"resolve.exports\";\nimport type { FileSystem } from \"./file-system\";\n\nexport interface ResolveOptions {\n /**\n * All files in the virtual file system\n */\n files: FileSystem;\n\n /**\n * Directory of the importing file (relative to root)\n */\n importer?: string;\n\n /**\n * Conditions for exports resolution (e.g., 'import', 'require', 'browser')\n */\n conditions?: string[];\n\n /**\n * Extensions to try when resolving\n */\n extensions?: string[];\n}\n\nexport interface ResolveResult {\n /**\n * Resolved path (relative to root)\n */\n path: string;\n\n /**\n * Whether this is an external module (npm package not in files)\n */\n external: boolean;\n}\n\nconst DEFAULT_EXTENSIONS = [\n \".ts\",\n \".tsx\",\n \".js\",\n \".jsx\",\n \".mts\",\n \".mjs\",\n \".json\"\n];\n\n/**\n * Resolve a module specifier to a file path in the virtual file system.\n *\n * Handles:\n * - Relative imports (./foo, ../bar)\n * - Package imports (lodash, @scope/pkg)\n * - Package.json exports field\n * - Extension resolution (.ts, .tsx, .js, etc.)\n * - Index file resolution (foo/index.ts)\n *\n * @param specifier - The import specifier (e.g., './utils', 'lodash')\n * @param options - Resolution options\n * @returns Resolved path or external marker\n */\nexport function resolveModule(\n specifier: string,\n options: ResolveOptions\n): ResolveResult {\n const {\n files,\n importer = \"\",\n conditions = [\"import\", \"browser\"],\n extensions = DEFAULT_EXTENSIONS\n } = options;\n\n // Handle relative imports\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) {\n const resolved = resolveRelative(specifier, importer, files, extensions);\n if (resolved) {\n return { path: resolved, external: false };\n }\n // Relative import not found\n throw new Error(\n `Cannot resolve relative import '${specifier}' from '${importer}'`\n );\n }\n\n // Handle bare specifiers (npm packages)\n return resolvePackage(specifier, files, conditions, extensions);\n}\n\n/**\n * Resolve a relative import\n */\nfunction resolveRelative(\n specifier: string,\n importer: string,\n files: FileSystem,\n extensions: string[]\n): string | undefined {\n // Get the directory of the importer\n const importerDir = getDirectory(importer);\n\n // Resolve the path\n const resolved = joinPaths(importerDir, specifier);\n\n return resolveWithExtensions(resolved, files, extensions);\n}\n\n/**\n * Resolve a package specifier\n */\nfunction resolvePackage(\n specifier: string,\n files: FileSystem,\n conditions: string[],\n extensions: string[]\n): ResolveResult {\n // Parse the specifier\n const { packageName, subpath } = parsePackageSpecifier(specifier);\n\n // Look for the package in node_modules\n const packageJsonPath = `node_modules/${packageName}/package.json`;\n const packageJson = files.read(packageJsonPath);\n\n if (!packageJson) {\n // Package not found in files, mark as external\n return { path: specifier, external: true };\n }\n\n // Parse package.json\n let pkg: Record<string, unknown>;\n try {\n pkg = JSON.parse(packageJson) as Record<string, unknown>;\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Invalid package.json at ${packageJsonPath} (for \"${packageName}\"): ${detail}`\n );\n }\n\n // Use resolve.exports to handle the exports field\n const entrySubpath = subpath ? `./${subpath}` : \".\";\n\n try {\n const resolved = resolveExports.resolve(pkg, entrySubpath, { conditions });\n if (resolved && resolved.length > 0) {\n // resolve.exports returns relative paths like './dist/index.js'\n const resolvedPath = resolved[0];\n if (resolvedPath) {\n const fullPath = `node_modules/${packageName}/${normalizeRelativePath(resolvedPath)}`;\n if (files.read(fullPath) !== null) {\n return { path: fullPath, external: false };\n }\n }\n }\n } catch {\n // resolve.exports failed, try legacy resolution\n }\n\n // Fall back to legacy resolution (main, module fields)\n const legacyEntry = resolveExports.legacy(pkg, {\n fields: [\"module\", \"main\"]\n });\n if (legacyEntry && typeof legacyEntry === \"string\") {\n const fullPath = `node_modules/${packageName}/${normalizeRelativePath(legacyEntry)}`;\n if (files.read(fullPath) !== null) {\n return { path: fullPath, external: false };\n }\n }\n\n // Try index files directly\n const indexPath = resolveWithExtensions(\n `node_modules/${packageName}${subpath ? `/${subpath}` : \"\"}`,\n files,\n extensions\n );\n if (indexPath) {\n return { path: indexPath, external: false };\n }\n\n // Package found but entry point not resolved, mark as external\n return { path: specifier, external: true };\n}\n\n/**\n * Try to resolve a path with various extensions and index files\n */\nfunction resolveWithExtensions(\n path: string,\n files: FileSystem,\n extensions: string[]\n): string | undefined {\n // Normalize the path\n const normalized = normalizePath(path);\n\n // Try exact match first\n if (files.read(normalized) !== null) {\n return normalized;\n }\n\n // Try adding extensions\n for (const ext of extensions) {\n const withExt = normalized + ext;\n if (files.read(withExt) !== null) {\n return withExt;\n }\n }\n\n // Try index files\n for (const ext of extensions) {\n const indexPath = `${normalized}/index${ext}`;\n if (files.read(indexPath) !== null) {\n return indexPath;\n }\n }\n\n return undefined;\n}\n\n/**\n * Parse a package specifier into package name and subpath\n */\nfunction parsePackageSpecifier(specifier: string): {\n packageName: string;\n subpath: string | undefined;\n} {\n // Handle scoped packages (@scope/pkg)\n if (specifier.startsWith(\"@\")) {\n const parts = specifier.split(\"/\");\n if (parts.length >= 2) {\n const packageName = `${parts[0]}/${parts[1]}`;\n const subpath = parts.slice(2).join(\"/\") || undefined;\n return { packageName, subpath };\n }\n }\n\n // Handle regular packages\n const slashIndex = specifier.indexOf(\"/\");\n if (slashIndex === -1) {\n return { packageName: specifier, subpath: undefined };\n }\n\n return {\n packageName: specifier.slice(0, slashIndex),\n subpath: specifier.slice(slashIndex + 1)\n };\n}\n\n/**\n * Get the directory of a file path\n */\nfunction getDirectory(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n return \"\";\n }\n return filePath.slice(0, lastSlash);\n}\n\n/**\n * Join two paths\n */\nfunction joinPaths(base: string, relative: string): string {\n if (relative.startsWith(\"/\")) {\n return relative.slice(1);\n }\n\n const baseParts = base ? base.split(\"/\") : [];\n const relativeParts = relative.split(\"/\");\n\n for (const part of relativeParts) {\n if (part === \"..\") {\n baseParts.pop();\n } else if (part !== \".\") {\n baseParts.push(part);\n }\n }\n\n return baseParts.join(\"/\");\n}\n\n/**\n * Normalize a path (remove ./ prefix, handle multiple slashes)\n */\nfunction normalizePath(path: string): string {\n return path.replace(/^\\.\\//, \"\").replace(/\\/+/g, \"/\").replace(/\\/$/, \"\");\n}\n\n/**\n * Normalize a relative path from package.json\n */\nfunction normalizeRelativePath(path: string): string {\n if (path.startsWith(\"./\")) {\n return path.slice(2);\n }\n if (path.startsWith(\"/\")) {\n return path.slice(1);\n }\n return path;\n}\n\n/**\n * Parse imports from a JavaScript/TypeScript source file.\n *\n * Uses es-module-lexer for accurate parsing of ES module syntax.\n * Falls back to regex for JSX files since es-module-lexer doesn't\n * handle JSX syntax (e.g., `<div>` is not valid JavaScript).\n */\nexport function parseImports(code: string): string[] {\n try {\n const [imports] = parse(code);\n const specifiers: string[] = [];\n\n for (const imp of imports) {\n // imp.n is the resolved module specifier (handles escape sequences)\n // imp.n is undefined for dynamic imports with non-string arguments\n if (imp.n !== undefined) {\n specifiers.push(imp.n);\n }\n }\n\n return [...new Set(specifiers)]; // Deduplicate\n } catch {\n // es-module-lexer fails on JSX syntax (<Component />) and malformed code\n // Fall back to regex-based parsing\n return parseImportsRegex(code);\n }\n}\n\n/**\n * Regex-based fallback for parsing imports.\n * Used when es-module-lexer fails (e.g., on JSX/TSX files).\n */\nfunction parseImportsRegex(code: string): string[] {\n const imports: string[] = [];\n\n // Match ES module imports\n // import foo from 'bar'\n // import { foo } from 'bar'\n // import * as foo from 'bar'\n // import 'bar'\n // Token-separated, keyword-bounded clause form — see rewriteImports in\n // transformer.ts. Both properties are required for linear matching (#1537).\n const importRegex =\n /\\bimport\\b\\s+(?:(?:(?!\\b(?:import|export)\\b)[\\w*{},])+(?:\\s+(?:(?!\\b(?:import|export)\\b)[\\w*{},])+)*\\s+from\\s+)?['\"]([^'\"]+)['\"]/g;\n for (const match of code.matchAll(importRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n // Match dynamic imports\n // import('bar')\n // await import('bar')\n const dynamicImportRegex = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n for (const match of code.matchAll(dynamicImportRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n // Match export from\n // export { foo } from 'bar'\n // export * from 'bar'\n const exportFromRegex =\n /\\bexport\\b\\s+(?:(?:(?!\\b(?:import|export)\\b)[\\w*{},])+(?:\\s+(?:(?!\\b(?:import|export)\\b)[\\w*{},])+)*\\s+)?from\\s+['\"]([^'\"]+)['\"]/g;\n for (const match of code.matchAll(exportFromRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n return [...new Set(imports)]; // Deduplicate\n}\n","/**\n * esbuild-wasm bundling functionality.\n */\n\n// Use the browser entry directly — the default \"main\" entry rejects\n// wasmModule in Workers with nodejs_compat (it thinks it's Node.js).\nimport * as esbuild from \"esbuild-wasm/lib/browser.js\";\n\nimport { resolveModule } from \"./resolver\";\nimport type { FileSystem } from \"./file-system\";\nimport type {\n BundlerLoader,\n CreateWorkerResult,\n JsxMode,\n Modules\n} from \"./types\";\n\n/**\n * Build a single warning string listing the bundler-only options the caller\n * set together with `bundle: false`. Returns `null` if none were set.\n *\n * `transformAndResolve` is sucrase + naïve module resolution — it cannot apply\n * `define` substitution, custom `loader` overrides, package-export `conditions`,\n * or esbuild plugins. Silently ignoring these would produce subtly wrong output\n * (e.g. `__DEV__` left as a free identifier in the emitted bundle).\n */\nexport function bundlerOnlyOptionsWarning(opts: {\n jsx?: unknown;\n jsxImportSource?: unknown;\n define?: unknown;\n loader?: unknown;\n conditions?: unknown;\n virtualModules?: unknown;\n plugins?: unknown;\n}): string | null {\n const set: string[] = [];\n if (opts.jsx !== undefined) set.push(\"jsx\");\n if (opts.jsxImportSource !== undefined) set.push(\"jsxImportSource\");\n if (opts.define !== undefined) set.push(\"define\");\n if (opts.loader !== undefined) set.push(\"loader\");\n if (opts.conditions !== undefined) set.push(\"conditions\");\n if (opts.virtualModules !== undefined) set.push(\"virtualModules\");\n if (opts.plugins !== undefined) {\n set.push(\"__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\");\n }\n if (set.length === 0) return null;\n return `${set.join(\", \")} ${set.length === 1 ? \"is\" : \"are\"} ignored when \\`bundle: false\\` (transform-only mode does not run esbuild). Set \\`bundle: true\\` (the default) to apply them.`;\n}\n\n/**\n * Internal options for bundleWithEsbuild. Kept as an object (rather than a\n * long positional list) so new bundler knobs can be added without churning\n * every call site.\n */\nexport interface BundleOptions {\n files: FileSystem;\n entryPoint: string;\n externals: string[];\n target: string;\n minify: boolean;\n sourcemap: boolean;\n nodejsCompat: boolean;\n jsx?: JsxMode;\n jsxImportSource?: string;\n define?: Record<string, string>;\n loader?: Record<string, BundlerLoader>;\n conditions?: string[];\n virtualModules?: Record<string, string>;\n /** Extra esbuild plugins to run BEFORE the internal virtual-fs plugin. */\n plugins?: unknown[];\n}\n\n/**\n * Bundle files using esbuild-wasm\n */\nexport async function bundleWithEsbuild(\n options: BundleOptions\n): Promise<CreateWorkerResult> {\n const {\n files,\n entryPoint,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader: loaderOverrides,\n conditions,\n virtualModules,\n plugins: extraPlugins = []\n } = options;\n // Ensure esbuild is initialized (happens lazily on first use)\n await initializeEsbuild();\n\n // Create a virtual file system plugin for esbuild\n const virtualFsPlugin: esbuild.Plugin = {\n name: \"virtual-fs\",\n setup(build) {\n // Resolve all paths to our virtual file system\n build.onResolve({ filter: /.*/ }, (args) => {\n // Handle entry point - it's passed directly without ./ prefix\n if (args.kind === \"entry-point\") {\n return { path: args.path, namespace: \"virtual\" };\n }\n\n // Handle relative imports\n if (args.path.startsWith(\".\")) {\n const resolved = resolveRelativePath(\n args.resolveDir,\n args.path,\n files\n );\n if (resolved) {\n return { path: resolved, namespace: \"virtual\" };\n }\n }\n\n // Handle bare imports (npm packages)\n if (!args.path.startsWith(\"/\") && !args.path.startsWith(\".\")) {\n // Check if it's in externals\n if (\n externals.includes(args.path) ||\n externals.some(\n (e) => args.path.startsWith(`${e}/`) || args.path.startsWith(e)\n )\n ) {\n return { path: args.path, external: true };\n }\n\n // Try to resolve from node_modules in virtual fs\n try {\n const result = resolveModule(args.path, { files });\n if (!result.external) {\n return { path: result.path, namespace: \"virtual\" };\n }\n } catch {\n // Resolution failed\n }\n\n // Mark as external (package not found in node_modules)\n return { path: args.path, external: true };\n }\n\n // Absolute paths in virtual fs\n const normalizedPath = args.path.startsWith(\"/\")\n ? args.path.slice(1)\n : args.path;\n if (files.read(normalizedPath) !== null) {\n return { path: normalizedPath, namespace: \"virtual\" };\n }\n\n return { path: args.path, external: true };\n });\n\n // Load files from virtual file system\n build.onLoad({ filter: /.*/, namespace: \"virtual\" }, (args) => {\n const content = files.read(args.path);\n if (content === null) {\n return { errors: [{ text: `File not found: ${args.path}` }] };\n }\n\n const loader = getLoader(args.path, loaderOverrides);\n // Set resolveDir so relative imports within this file resolve correctly\n const lastSlash = args.path.lastIndexOf(\"/\");\n const resolveDir = lastSlash >= 0 ? args.path.slice(0, lastSlash) : \"\";\n return { contents: content, loader, resolveDir };\n });\n }\n };\n\n const virtualModulePlugin: esbuild.Plugin | null =\n virtualModules && Object.keys(virtualModules).length > 0\n ? {\n name: \"virtual-modules\",\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (Object.hasOwn(virtualModules, args.path)) {\n return { path: args.path, namespace: \"virtual-module\" };\n }\n return undefined;\n });\n\n build.onLoad(\n { filter: /.*/, namespace: \"virtual-module\" },\n (args) => ({\n contents: virtualModules[args.path] ?? \"\",\n loader: \"js\",\n resolveDir: \"\"\n })\n );\n }\n }\n : null;\n\n // Validate user plugins eagerly: the public type is `unknown[]` (so the\n // .d.ts stays free of esbuild types), which means anything can flow in.\n // Without this, a bad value surfaces as an opaque crash from inside esbuild's\n // own plugin machinery — point at the dangerous option name instead.\n for (let i = 0; i < extraPlugins.length; i++) {\n const p = extraPlugins[i] as\n | { name?: unknown; setup?: unknown }\n | null\n | undefined;\n if (\n !p ||\n typeof p !== \"object\" ||\n typeof p.name !== \"string\" ||\n typeof p.setup !== \"function\"\n ) {\n throw new TypeError(\n `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired[${i}] is not a valid esbuild plugin (expected an object with \\`name: string\\` and \\`setup: (build) => void\\`).`\n );\n }\n }\n\n // User plugins run BEFORE the internal virtual-fs plugin so they get first\n // crack at onResolve / onLoad (e.g. an RSC plugin claiming \"server-function:*\"\n // before virtual-fs tries to read it from disk). Don't reorder this without\n // thinking about it.\n const userPlugins = extraPlugins as esbuild.Plugin[];\n\n const result = await esbuild.build({\n entryPoints: [entryPoint],\n bundle: true,\n write: false,\n format: \"esm\",\n platform: nodejsCompat ? \"node\" : \"browser\",\n target,\n minify,\n sourcemap: sourcemap ? \"inline\" : false,\n plugins: [\n ...userPlugins,\n ...(virtualModulePlugin ? [virtualModulePlugin] : []),\n virtualFsPlugin\n ],\n outfile: \"bundle.js\",\n ...(jsx !== undefined ? { jsx } : {}),\n ...(jsxImportSource !== undefined ? { jsxImportSource } : {}),\n ...(define !== undefined ? { define } : {}),\n ...(conditions !== undefined ? { conditions } : {})\n });\n\n const output = result.outputFiles?.[0];\n if (!output) {\n // Almost always means a plugin claimed the entry point and produced\n // nothing, or esbuild emitted only secondary outputs (e.g. via the\n // `file` loader, which this bundler doesn't surface).\n throw new Error(\n `esbuild produced no output for entry point \"${entryPoint}\". This usually means a custom plugin (\\`__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\\`) intercepted the entry without returning contents, or the entry resolved to an externalised module.`\n );\n }\n\n const modules: Modules = {\n \"bundle.js\": output.text\n };\n\n const warnings = result.warnings.map((w) => w.text);\n if (warnings.length > 0) {\n return { mainModule: \"bundle.js\", modules, warnings };\n }\n return { mainModule: \"bundle.js\", modules };\n}\n\n/**\n * Resolve a relative path against a directory within the virtual filesystem.\n */\nfunction resolveRelativePath(\n resolveDir: string,\n relativePath: string,\n files: FileSystem\n): string | undefined {\n // Normalize the resolve directory\n const dir = resolveDir.replace(/^\\//, \"\");\n\n // Resolve the relative path\n const parts = dir ? dir.split(\"/\") : [];\n const relParts = relativePath.split(\"/\");\n\n for (const part of relParts) {\n if (part === \"..\") {\n parts.pop();\n } else if (part !== \".\") {\n parts.push(part);\n }\n }\n\n const resolved = parts.join(\"/\");\n\n // Try exact match\n if (files.read(resolved) !== null) {\n return resolved;\n }\n\n // Try adding extensions\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".mjs\"];\n for (const ext of extensions) {\n if (files.read(resolved + ext) !== null) {\n return resolved + ext;\n }\n }\n\n // Try index files\n for (const ext of extensions) {\n const indexPath = `${resolved}/index${ext}`;\n if (files.read(indexPath) !== null) {\n return indexPath;\n }\n }\n\n return undefined;\n}\n\nfunction getLoader(\n path: string,\n overrides?: Record<string, BundlerLoader>\n): esbuild.Loader {\n if (overrides) {\n // Match on the longest extension first so \".d.ts\" wins over \".ts\" if both\n // are configured.\n const matched = Object.keys(overrides)\n .filter((ext) => path.endsWith(ext))\n .sort((a, b) => b.length - a.length)[0];\n if (matched !== undefined) {\n return overrides[matched] as esbuild.Loader;\n }\n }\n if (path.endsWith(\".ts\") || path.endsWith(\".mts\")) return \"ts\";\n if (path.endsWith(\".tsx\")) return \"tsx\";\n if (path.endsWith(\".jsx\")) return \"jsx\";\n if (path.endsWith(\".json\")) return \"json\";\n if (path.endsWith(\".css\")) return \"css\";\n return \"js\";\n}\n\n// Track esbuild initialization state\nlet esbuildInitialized = false;\nlet esbuildInitializePromise: Promise<void> | null = null;\n\n/**\n * Detect whether we are running inside the Cloudflare Workers runtime\n * (workerd). Both production Workers and the local dev runtime expose\n * `navigator.userAgent === \"Cloudflare-Workers\"`.\n *\n * Exported so tests can sanity-check the guard without standing up a\n * separate Node-only test runner.\n */\nexport function isCloudflareWorkersRuntime(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n typeof navigator.userAgent === \"string\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n );\n}\n\n/**\n * Error message thrown when `createWorker` / `createApp` is called outside of\n * the Workers runtime. Exported so tests can match against it without\n * duplicating the wording.\n */\nexport const NOT_IN_WORKERS_ERROR =\n \"@cloudflare/worker-bundler is only supported inside the Cloudflare Workers runtime (workerd). \" +\n \"It cannot run in plain Node.js — including Vitest, Jest or other Node-based test runners — \" +\n \"because it bundles via a `WebAssembly.Module` import that only the Workers module loader can resolve. \" +\n \"To test code that uses this package, run your tests with @cloudflare/vitest-pool-workers so they execute inside workerd. \" +\n \"See https://developers.cloudflare.com/workers/testing/vitest-integration/ for setup.\";\n\n/**\n * Pre-started promise for the esbuild WASM module load.\n *\n * Pre-warmed at module evaluation time when (and only when) we're inside\n * workerd, so the wasm `Compile` cost runs in parallel with everything else\n * the test/handler is doing — matching the implicit behaviour of the static\n * `import esbuildWasm from \"./esbuild.wasm\"` we used to have. Without this,\n * the first `bundleWithEsbuild` call paid the full wasm-compile cost\n * serially, which was enough to flake the first test of an `app-e2e`-style\n * file under vitest's default 5s timeout on slower CI runners.\n *\n * Outside Workers, we *don't* start the import — Node's ESM-WASM loader\n * would try to resolve esbuild's Go-runtime `gojs` import namespace as an\n * npm package and crash. `initializeEsbuild()` throws `NOT_IN_WORKERS_ERROR`\n * before ever touching the file in that case.\n */\nlet pendingWasmImport: Promise<{ default: WebAssembly.Module }> | null = null;\n\nif (isCloudflareWorkersRuntime()) {\n pendingWasmImport = import(\"./esbuild.wasm\");\n // Suppress unhandled-rejection if `initializeEsbuild()` is never called.\n // Errors are still surfaced when the promise is awaited there.\n pendingWasmImport.catch(() => {});\n}\n\n/**\n * Initialize the esbuild bundler.\n * This is called automatically when needed.\n */\nasync function initializeEsbuild(): Promise<void> {\n // If already initialized, return immediately\n if (esbuildInitialized) return;\n\n // If initialization is in progress, wait for it\n if (esbuildInitializePromise) {\n return esbuildInitializePromise;\n }\n\n // Start initialization\n esbuildInitializePromise = (async () => {\n // Refuse to load esbuild.wasm outside Workers. The .wasm file is built\n // from Go, which declares a `gojs` import namespace in its WASM-host\n // bridge; Node's ESM-WASM loader (Node 22+) tries to resolve that as an\n // npm package and surfaces `Cannot find package 'gojs'` instead of\n // anything actionable. Fail fast with a useful message before we ever\n // touch the .wasm file.\n if (!isCloudflareWorkersRuntime() || pendingWasmImport === null) {\n throw new Error(NOT_IN_WORKERS_ERROR);\n }\n\n try {\n // Await the pre-warmed wasm import kicked off at module evaluation.\n // In the common case (warm worker) this is already resolved.\n const wasmModule = (await pendingWasmImport).default;\n\n await esbuild.initialize({\n wasmModule,\n worker: false\n });\n\n esbuildInitialized = true;\n } catch (error) {\n // If initialization fails, esbuild may already be initialized\n if (\n error instanceof Error &&\n error.message.includes('Cannot call \"initialize\" more than once')\n ) {\n esbuildInitialized = true;\n return;\n }\n throw error;\n }\n })();\n\n try {\n await esbuildInitializePromise;\n } catch (error) {\n // Reset promise so caller can try again\n esbuildInitializePromise = null;\n throw error;\n }\n}\n","/**\n * Wrangler configuration parsing.\n *\n * Parses wrangler.toml, wrangler.json, and wrangler.jsonc files\n * to extract compatibility settings.\n */\n\nimport { parse as parseToml } from \"smol-toml\";\nimport type { WranglerConfig } from \"./types\";\nimport type { FileSystem } from \"./file-system\";\n\n/**\n * Parse wrangler configuration from files.\n *\n * Looks for wrangler.toml, wrangler.json, or wrangler.jsonc in the files\n * and extracts compatibility_date and compatibility_flags.\n *\n * @param files - Virtual file system\n * @returns Parsed wrangler config, or undefined if no config file found\n */\nexport function parseWranglerConfig(\n files: FileSystem\n): WranglerConfig | undefined {\n // Try each config file format in order of preference\n const tomlContent = files.read(\"wrangler.toml\");\n if (tomlContent) {\n return parseWranglerToml(tomlContent);\n }\n\n const jsonContent = files.read(\"wrangler.json\");\n if (jsonContent) {\n return parseWranglerJson(jsonContent);\n }\n\n const jsoncContent = files.read(\"wrangler.jsonc\");\n if (jsoncContent) {\n return parseWranglerJsonc(jsoncContent);\n }\n\n return undefined;\n}\n\n/**\n * Parse wrangler.toml content\n */\nfunction parseWranglerToml(content: string): WranglerConfig {\n try {\n const config = parseToml(content) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse wrangler.json content\n */\nfunction parseWranglerJson(content: string): WranglerConfig {\n try {\n const config = JSON.parse(content) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse wrangler.jsonc content (JSON with comments)\n */\nfunction parseWranglerJsonc(content: string): WranglerConfig {\n try {\n // Strip comments from JSONC\n const jsonContent = stripJsonComments(content);\n const config = JSON.parse(jsonContent) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Extract wrangler config fields from parsed config object.\n * Handles both snake_case (toml) and camelCase (json) formats.\n */\nfunction extractWranglerConfig(\n config: Record<string, unknown>\n): WranglerConfig {\n const result: WranglerConfig = {};\n\n // main entry point\n const main = config[\"main\"];\n if (typeof main === \"string\") {\n result.main = main;\n }\n\n // compatibility_date (toml) or compatibilityDate (json)\n const date = config[\"compatibility_date\"] ?? config[\"compatibilityDate\"];\n if (typeof date === \"string\") {\n result.compatibilityDate = date;\n }\n\n // compatibility_flags (toml) or compatibilityFlags (json)\n const flags = config[\"compatibility_flags\"] ?? config[\"compatibilityFlags\"];\n if (Array.isArray(flags) && flags.every((f) => typeof f === \"string\")) {\n result.compatibilityFlags = flags;\n }\n\n return result;\n}\n\n/**\n * Strip comments from JSONC content.\n * Handles both single-line (//) and multi-line comments.\n */\nfunction stripJsonComments(content: string): string {\n let result = \"\";\n let i = 0;\n let inString = false;\n let stringChar = \"\";\n\n while (i < content.length) {\n const char = content[i];\n const nextChar = content[i + 1];\n\n // Handle string literals (don't strip comments inside strings)\n if (\n (char === '\"' || char === \"'\") &&\n (i === 0 || content[i - 1] !== \"\\\\\")\n ) {\n if (!inString) {\n inString = true;\n stringChar = char;\n } else if (char === stringChar) {\n inString = false;\n }\n result += char;\n i++;\n continue;\n }\n\n if (inString) {\n result += char;\n i++;\n continue;\n }\n\n // Handle single-line comments\n if (char === \"/\" && nextChar === \"/\") {\n // Skip until end of line\n while (i < content.length && content[i] !== \"\\n\") {\n i++;\n }\n continue;\n }\n\n // Handle multi-line comments\n if (char === \"/\" && nextChar === \"*\") {\n i += 2;\n // Skip until */\n while (\n i < content.length - 1 &&\n !(content[i] === \"*\" && content[i + 1] === \"/\")\n ) {\n i++;\n }\n i += 2; // Skip */\n continue;\n }\n\n result += char;\n i++;\n }\n\n return result;\n}\n\n/**\n * Check if nodejs_compat flag is enabled in the config.\n */\nexport function hasNodejsCompat(config: WranglerConfig | undefined): boolean {\n return config?.compatibilityFlags?.includes(\"nodejs_compat\") ?? false;\n}\n","import { transform } from \"sucrase\";\nimport { parseImports, resolveModule } from \"./resolver\";\nimport type { FileSystem } from \"./file-system\";\nimport type { CreateWorkerResult, Modules } from \"./types\";\n\nexport interface TransformResult {\n code: string;\n sourceMap?: string;\n}\n\nexport interface TransformOptions {\n /**\n * Source file path (for source maps and error messages)\n */\n filePath: string;\n\n /**\n * Whether to generate source maps\n */\n sourceMap?: boolean;\n\n /**\n * Whether to preserve JSX (don't transform to createElement calls)\n */\n preserveJsx?: boolean;\n\n /**\n * JSX runtime ('automatic' for new JSX transform, 'classic' for React.createElement)\n */\n jsxRuntime?: \"automatic\" | \"classic\" | \"preserve\";\n\n /**\n * JSX import source for automatic runtime (default: 'react')\n */\n jsxImportSource?: string;\n\n /**\n * Whether this is a production build\n */\n production?: boolean;\n}\n\n/**\n * Transform TypeScript/JSX code to JavaScript using Sucrase.\n *\n * Sucrase is a super-fast TypeScript transformer that:\n * - Strips type annotations\n * - Transforms JSX\n * - Is ~20x faster than Babel\n * - Works in any JS environment (no WASM needed)\n *\n * @param code - Source code to transform\n * @param options - Transform options\n * @returns Transformed code\n */\nexport function transformCode(\n code: string,\n options: TransformOptions\n): TransformResult {\n const {\n filePath,\n sourceMap = false,\n jsxRuntime = \"automatic\",\n jsxImportSource = \"react\",\n production = false\n } = options;\n\n const transforms: Array<\"typescript\" | \"jsx\" | \"flow\"> = [];\n\n // Determine transforms based on file extension\n if (isTypeScriptFile(filePath)) {\n transforms.push(\"typescript\");\n }\n\n if (isJsxFile(filePath)) {\n if (jsxRuntime !== \"preserve\") {\n transforms.push(\"jsx\");\n }\n }\n\n if (transforms.length === 0) {\n // No transforms needed, return as-is\n return { code };\n }\n\n const transformOptions: Parameters<typeof transform>[1] = {\n transforms,\n filePath,\n jsxRuntime,\n jsxImportSource,\n production,\n // Keep ESM imports/exports as-is\n preserveDynamicImport: true,\n // Disable ES transforms since Workers support modern JS\n disableESTransforms: true\n };\n\n if (sourceMap) {\n transformOptions.sourceMapOptions = {\n compiledFilename: filePath.replace(/\\.(tsx?|mts)$/, \".js\")\n };\n }\n\n const result = transform(code, transformOptions);\n\n if (result.sourceMap) {\n return {\n code: result.code,\n sourceMap: JSON.stringify(result.sourceMap)\n };\n }\n return { code: result.code };\n}\n\n/**\n * Check if a file path is a TypeScript file\n */\nexport function isTypeScriptFile(filePath: string): boolean {\n return /\\.(ts|tsx|mts)$/.test(filePath);\n}\n\n/**\n * Check if a file path is a JSX file\n */\nexport function isJsxFile(filePath: string): boolean {\n return /\\.(jsx|tsx)$/.test(filePath);\n}\n\n/**\n * Check if a file path is any JavaScript/TypeScript file\n */\nexport function isJavaScriptFile(filePath: string): boolean {\n return /\\.(js|jsx|ts|tsx|mjs|mts)$/.test(filePath);\n}\n\n/**\n * Get the output path for a transformed file\n */\nexport function getOutputPath(filePath: string): string {\n // .ts -> .js, .tsx -> .js, .mts -> .mjs\n return filePath.replace(/\\.tsx?$/, \".js\").replace(/\\.mts$/, \".mjs\");\n}\n\n/**\n * Transform all files and resolve their dependencies.\n * This produces multiple modules instead of a single bundle.\n */\nexport async function transformAndResolve(\n files: FileSystem,\n entryPoint: string,\n externals: string[]\n): Promise<CreateWorkerResult> {\n const modules: Modules = {};\n const warnings: string[] = [];\n const processed = new Set<string>();\n const toProcess = [entryPoint];\n\n // Map from source path to output path\n const pathMap = new Map<string, string>();\n\n // First pass: collect all files and their output paths\n while (toProcess.length > 0) {\n const filePath = toProcess.pop();\n if (!filePath || processed.has(filePath)) continue;\n processed.add(filePath);\n\n const content = files.read(filePath);\n if (content === null) {\n warnings.push(`File not found: ${filePath}`);\n continue;\n }\n\n // Calculate output path\n const outputPath = isTypeScriptFile(filePath)\n ? getOutputPath(filePath)\n : filePath;\n pathMap.set(filePath, outputPath);\n\n // Handle non-JS files\n if (!isJavaScriptFile(filePath)) {\n if (filePath.endsWith(\".json\")) {\n try {\n modules[filePath] = { json: JSON.parse(content) };\n } catch {\n warnings.push(`Failed to parse JSON file: ${filePath}`);\n }\n } else {\n // Include as text\n modules[filePath] = { text: content };\n }\n continue;\n }\n\n // Parse imports and queue them for processing\n const imports = parseImports(content);\n for (const specifier of imports) {\n // Skip external modules\n if (\n externals.includes(specifier) ||\n externals.some(\n (e) => specifier.startsWith(`${e}/`) || specifier.startsWith(e)\n )\n ) {\n continue;\n }\n\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer: filePath\n });\n\n if (!resolved.external && !processed.has(resolved.path)) {\n toProcess.push(resolved.path);\n }\n } catch (error) {\n warnings.push(\n `Failed to resolve '${specifier}' from ${filePath}: ${error instanceof Error ? error.message : error}`\n );\n }\n }\n }\n\n // Second pass: transform files and rewrite imports\n for (const [sourcePath, outputPath] of pathMap) {\n const content = files.read(sourcePath);\n if (content === null || !isJavaScriptFile(sourcePath)) continue;\n\n let transformedCode: string;\n\n if (isTypeScriptFile(sourcePath)) {\n try {\n const result = transformCode(content, {\n filePath: sourcePath\n });\n transformedCode = result.code;\n } catch (error) {\n warnings.push(\n `Failed to transform ${sourcePath}: ${error instanceof Error ? error.message : error}`\n );\n continue;\n }\n } else {\n transformedCode = content;\n }\n\n // Rewrite imports to use the full output paths\n transformedCode = rewriteImports(\n transformedCode,\n sourcePath,\n files,\n pathMap,\n externals\n );\n\n // Add to output modules\n modules[outputPath] = transformedCode;\n }\n\n // Calculate the main module path (transformed entry point)\n const mainModule = isTypeScriptFile(entryPoint)\n ? getOutputPath(entryPoint)\n : entryPoint;\n\n if (warnings.length > 0) {\n return { mainModule, modules, warnings };\n }\n return { mainModule, modules };\n}\n\n/**\n * Rewrite import specifiers to use full output paths.\n * This is necessary because the Worker Loader expects imports to match registered module names.\n */\nfunction rewriteImports(\n code: string,\n importer: string,\n files: FileSystem,\n pathMap: Map<string, string>,\n externals: string[]\n): string {\n // Match import/export statements with string specifiers\n // Handles: import x from 'y', import { x } from 'y', import 'y', export { x } from 'y', export * from 'y'\n // Clause tokens and whitespace are disjoint, so the regex cannot redistribute\n // whitespace between adjacent quantifiers. Each candidate also stops at the\n // next import/export keyword; otherwise stacked near-matches would make the\n // unanchored global search rescan the remaining suffix (#1537).\n const importExportRegex =\n /(\\bimport\\b\\s+(?:(?:(?!\\b(?:import|export)\\b)[\\w*{},])+(?:\\s+(?:(?!\\b(?:import|export)\\b)[\\w*{},])+)*\\s+from\\s+)?|\\bexport\\b\\s+(?:(?:(?!\\b(?:import|export)\\b)[\\w*{},])+(?:\\s+(?:(?!\\b(?:import|export)\\b)[\\w*{},])+)*\\s+)?from\\s+)(['\"])([^'\"]+)\\2/g;\n\n // Get importer's output path to use as the base for resolving\n const importerOutputPath = pathMap.get(importer) ?? importer;\n\n return code.replace(\n importExportRegex,\n (match, prefix: string, quote: string, specifier: string) => {\n // Skip external modules\n if (\n externals.includes(specifier) ||\n externals.some(\n (e) => specifier.startsWith(`${e}/`) || specifier.startsWith(e)\n )\n ) {\n return match;\n }\n\n // Skip non-relative imports that aren't in our files (bare imports to npm packages)\n if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n // Try to resolve it - if it resolves to node_modules, rewrite the path\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer\n });\n\n if (resolved.external) {\n return match;\n }\n\n // Get the output path for the resolved module\n const resolvedOutputPath =\n pathMap.get(resolved.path) ?? resolved.path;\n\n // For node_modules imports, use the full path\n if (resolved.path.startsWith(\"node_modules/\")) {\n return `${prefix}${quote}/${resolvedOutputPath}${quote}`;\n }\n\n // Calculate relative path for non-node_modules\n const relativePath = calculateRelativePath(\n importerOutputPath,\n resolvedOutputPath\n );\n return `${prefix}${quote}${relativePath}${quote}`;\n } catch {\n // Resolution failed, keep original\n return match;\n }\n }\n\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer\n });\n\n if (resolved.external) {\n return match;\n }\n\n // Get the output path for the resolved module\n const resolvedOutputPath = pathMap.get(resolved.path) ?? resolved.path;\n\n // Calculate the relative path from the importer's output location to the resolved output\n const relativePath = calculateRelativePath(\n importerOutputPath,\n resolvedOutputPath\n );\n\n // Return the rewritten import with the relative output path\n return `${prefix}${quote}${relativePath}${quote}`;\n } catch {\n // If resolution fails, keep the original\n return match;\n }\n }\n );\n}\n\n/**\n * Calculate relative path from one file to another.\n */\nfunction calculateRelativePath(from: string, to: string): string {\n const fromDir = getDirectory(from);\n const toDir = getDirectory(to);\n const toFile = to.split(\"/\").pop() ?? to;\n\n if (fromDir === toDir) {\n // Same directory\n return `./${toFile}`;\n }\n\n const fromParts = fromDir ? fromDir.split(\"/\") : [];\n const toParts = toDir ? toDir.split(\"/\") : [];\n\n // Find common prefix\n let commonLength = 0;\n while (\n commonLength < fromParts.length &&\n commonLength < toParts.length &&\n fromParts[commonLength] === toParts[commonLength]\n ) {\n commonLength++;\n }\n\n // Calculate relative path\n const upCount = fromParts.length - commonLength;\n const downParts = toParts.slice(commonLength);\n\n let relativePath = \"\";\n if (upCount === 0) {\n relativePath = \"./\";\n } else {\n relativePath = \"../\".repeat(upCount);\n }\n\n if (downParts.length > 0) {\n relativePath += `${downParts.join(\"/\")}/`;\n }\n\n return relativePath + toFile;\n}\n\nfunction getDirectory(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n return \"\";\n }\n return filePath.slice(0, lastSlash);\n}\n","/**\n * Utility functions.\n */\n\nimport type { WranglerConfig } from \"./types\";\nimport type { FileSystem } from \"./file-system\";\n\n/**\n * Default entry-point paths searched (in order) when no explicit entry has\n * been provided and `wrangler.*` / `package.json` don't declare one.\n *\n * Exported so the \"Could not determine entry point\" error messages in\n * `index.ts` (createWorker) and `app.ts` (createApp) can reference the same\n * source of truth — otherwise the messages drift out of sync the first time\n * someone adds a default and forgets to update both error strings.\n */\nexport const DEFAULT_ENTRY_POINTS = [\n \"src/index.ts\",\n \"src/index.js\",\n \"src/index.mts\",\n \"src/index.mjs\",\n \"index.ts\",\n \"index.js\",\n \"index.py\",\n \"src/worker.ts\",\n \"src/worker.js\"\n] as const;\n\n/**\n * Detect entry point from wrangler config, package.json, or use defaults.\n * Priority: wrangler main > package.json exports/module/main > default paths\n */\nexport function detectEntryPoint(\n files: FileSystem,\n wranglerConfig: WranglerConfig | undefined\n): string | undefined {\n // First, check wrangler config main field\n if (wranglerConfig?.main) {\n return normalizeEntryPath(wranglerConfig.main);\n }\n\n // Try to read package.json\n const packageJsonContent = files.read(\"package.json\");\n if (packageJsonContent) {\n try {\n const pkg = JSON.parse(packageJsonContent) as {\n main?: string;\n module?: string;\n exports?: Record<string, unknown> | string;\n };\n\n // Check exports field first\n if (pkg.exports) {\n if (typeof pkg.exports === \"string\") {\n return normalizeEntryPath(pkg.exports);\n }\n // Handle exports object - look for \".\" entry\n const dotExport = pkg.exports[\".\"];\n if (dotExport) {\n if (typeof dotExport === \"string\") {\n return normalizeEntryPath(dotExport);\n }\n // Handle conditional exports\n if (typeof dotExport === \"object\" && dotExport !== null) {\n const exp = dotExport as Record<string, unknown>;\n const entry = exp[\"import\"] ?? exp[\"default\"] ?? exp[\"module\"];\n if (typeof entry === \"string\") {\n return normalizeEntryPath(entry);\n }\n }\n }\n }\n\n // Check module field\n if (pkg.module) {\n return normalizeEntryPath(pkg.module);\n }\n\n // Check main field\n if (pkg.main) {\n return normalizeEntryPath(pkg.main);\n }\n } catch {\n // Invalid JSON, continue to defaults\n }\n }\n\n for (const entry of DEFAULT_ENTRY_POINTS) {\n if (files.read(entry) !== null) {\n return entry;\n }\n }\n\n return undefined;\n}\n\nfunction normalizeEntryPath(path: string): string {\n // Remove leading ./\n if (path.startsWith(\"./\")) {\n return path.slice(2);\n }\n return path;\n}\n\n/**\n * Render the user-provided source files as a short, readable list for use in\n * \"entry point not found\" errors. Skips installed `node_modules/` files\n * (which can be tens of thousands of paths and drown out the actually\n * relevant signal — the files the user passed in) and truncates the tail.\n */\nexport function formatFileListForError(files: FileSystem, limit = 10): string {\n const all = files\n .list()\n .filter((p) => !p.startsWith(\"node_modules/\"))\n .sort();\n if (all.length === 0) {\n return \"(none — `files` is empty or only contains node_modules entries)\";\n }\n const shown = all.slice(0, limit).join(\", \");\n if (all.length <= limit) return shown;\n return `${shown}, … (+${all.length - limit} more)`;\n}\n","let warningShown = false;\n\nexport function showExperimentalWarning(fn: string) {\n if (!warningShown) {\n warningShown = true;\n console.warn(\n `[worker-bundler] ${fn}(): This package is experimental and its API may change without notice.`\n );\n }\n}\n","export interface FileSystem {\n /**\n * Reads a file from the file system.\n * @param path The path to the file.\n * @returns The contents of the file, or `null` if the file does not exist.\n */\n read(path: string): string | null;\n\n /**\n * Writes a file to the file system.\n * @param path The path to the file.\n * @param content The contents of the file.\n */\n write(path: string, content: FileEntry): void;\n\n /**\n * Deletes a file from the file system.\n * @param path The path to the file.\n */\n delete(path: string): void;\n\n /**\n * Returns the logical paths of all files in the filesystem, optionally\n * filtered to those whose path starts with `prefix`.\n * @param prefix Optional path prefix to filter results.\n */\n list(prefix?: string): string[];\n\n /**\n * Depending on the implementation of the filesystem writes may be buffered\n * in-memory to avoid (comparatively) expensive I/O operations. This method\n * gives users of the filesystem a way to ensure that all writes are flushed\n * to disk.\n */\n flush(): Promise<void>;\n}\n\n/**\n * A simple in-memory filesystem backed by a `Map`. Intended for use in tests\n * and build pipelines where persistence is not required.\n */\nexport class InMemoryFileSystem implements FileSystem {\n private files: Map<string, string> = new Map();\n\n /**\n * @param files Optional initial file contents. Accepts either a plain object\n * (keys are paths, values are file contents) or a `Map`. Defaults to an\n * empty filesystem.\n */\n constructor(files: Record<string, string> | Map<string, string> = new Map()) {\n this.files = files instanceof Map ? files : new Map(Object.entries(files));\n }\n\n read(path: string): string | null {\n return this.files.get(path) ?? null;\n }\n\n write(path: string, content: string): void {\n this.files.set(path, content);\n }\n\n delete(path: string): void {\n this.files.delete(path);\n }\n\n list(prefix?: string): string[] {\n return Array.from(this.files.keys()).filter(\n (path) => prefix === undefined || path.startsWith(prefix)\n );\n }\n\n flush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/**\n * A generic write-overlay on top of any `FileSystem`. Not re-exported from the\n * package entry point — intended as an implementation detail for higher-level\n * filesystem classes.\n *\n * Writes and deletes are buffered in memory keyed by the raw (untransformed)\n * path. Reads are served from the write buffer first; deleted paths return\n * `null`; remaining reads are delegated to the inner filesystem. `flush()`\n * drains deletes and writes into the inner filesystem, awaits `inner.flush()`,\n * and then clears the buffers.\n */\nexport class OverlayFileSystem implements FileSystem {\n private overlay: Map<string, string> | null = null;\n private deletions: Set<string> | null = null;\n\n constructor(private readonly inner: FileSystem) {}\n\n read(path: string): string | null {\n if (this.overlay?.has(path)) {\n return this.overlay.get(path) ?? null;\n }\n if (this.deletions?.has(path)) {\n return null;\n }\n return this.inner.read(path);\n }\n\n write(path: string, content: string): void {\n if (this.overlay === null) {\n this.overlay = new Map();\n }\n this.overlay.set(path, content);\n this.deletions?.delete(path);\n }\n\n delete(path: string): void {\n this.overlay?.delete(path);\n if (this.deletions === null) {\n this.deletions = new Set();\n }\n this.deletions.add(path);\n }\n\n list(prefix?: string): string[] {\n const innerPaths = this.inner\n .list(prefix)\n .filter((path) => !this.deletions?.has(path));\n // Union of inner paths and overlay paths, with overlay entries taking\n // precedence (Set deduplicates paths that appear in both).\n const result = new Set(innerPaths);\n for (const path of this.overlay?.keys() ?? []) {\n if (prefix === undefined || path.startsWith(prefix)) {\n result.add(path);\n }\n }\n return Array.from(result);\n }\n\n async flush(): Promise<void> {\n if (this.overlay === null && this.deletions === null) {\n return;\n }\n for (const path of this.deletions ?? []) {\n this.inner.delete(path);\n }\n for (const [path, content] of this.overlay ?? []) {\n this.inner.write(path, content);\n }\n await this.inner.flush();\n this.overlay = null;\n this.deletions = null;\n }\n}\n\n/**\n * A filesystem backed directly by Durable Object KV storage. Every write is\n * committed to KV synchronously with no in-memory buffering, and `flush()` is\n * a no-op.\n *\n * Use this when you want immediate, per-write durability and the overhead of\n * individual KV writes is acceptable — for example, when seeding a small number\n * of files. For bulk write workloads, prefer `DurableObjectKVFileSystem`, which\n * batches all writes into a single flush.\n */\nexport class DurableObjectRawFileSystem implements FileSystem {\n /**\n * @param storage The Durable Object storage instance to persist files to.\n * @param prefix An optional path prefix prepended to every key stored in KV.\n * Defaults to `\"bundle/\"`, which namespaces bundle files away\n * from any other keys the Durable Object may store.\n */\n constructor(\n private readonly storage: DurableObjectStorage,\n private readonly prefix: string = \"bundle/\"\n ) {}\n\n read(path: string): string | null {\n return this.storage.kv.get<string>(this.formatPath(path)) ?? null;\n }\n\n write(path: string, content: string): void {\n this.storage.kv.put(this.formatPath(path), content);\n }\n\n delete(path: string): void {\n this.storage.kv.delete(this.formatPath(path));\n }\n\n list(prefix?: string): string[] {\n const formattedPrefix =\n prefix !== undefined ? this.formatPath(prefix) : this.prefix;\n // kv.list() returns Iterable<[key, value]>. Strip the storage prefix from\n // each key so callers always receive logical paths, consistent with\n // InMemoryFileSystem.list().\n const result: string[] = [];\n for (const [key] of this.storage.kv.list({ prefix: formattedPrefix })) {\n result.push(key.slice(this.prefix.length));\n }\n return result;\n }\n\n flush(): Promise<void> {\n return Promise.resolve();\n }\n\n private formatPath(path: string): string {\n return `${this.prefix}${path}`;\n }\n}\n\n/**\n * A filesystem backed by Durable Object KV storage with a write-overlay.\n * Writes are buffered in memory and only persisted to KV when `flush()` is\n * called, avoiding the cost of a KV write on every individual file operation.\n * Reads are served from the overlay when possible, falling back to KV, so\n * callers always observe their own writes immediately.\n *\n * Implemented as an `OverlayFileSystem` wrapping a `DurableObjectRawFileSystem`.\n * Use `DurableObjectRawFileSystem` directly if you want immediate per-write KV\n * durability without buffering.\n */\nexport class DurableObjectKVFileSystem implements FileSystem {\n private readonly fs: OverlayFileSystem;\n\n /**\n * @param storage The Durable Object storage instance to persist files to.\n * @param prefix An optional path prefix prepended to every key stored in KV.\n * Defaults to `\"bundle/\"`, which namespaces bundle files away\n * from any other keys the Durable Object may store.\n */\n constructor(storage: DurableObjectStorage, prefix: string = \"bundle/\") {\n this.fs = new OverlayFileSystem(\n new DurableObjectRawFileSystem(storage, prefix)\n );\n }\n\n read(path: string): string | null {\n return this.fs.read(path);\n }\n\n write(path: string, content: string): void {\n this.fs.write(path, content);\n }\n\n delete(path: string): void {\n this.fs.delete(path);\n }\n\n list(prefix?: string): string[] {\n return this.fs.list(prefix);\n }\n\n flush(): Promise<void> {\n return this.fs.flush();\n }\n}\n\n/**\n * Creates an `InMemoryFileSystem` from an async source of file entries.\n *\n * This is the bridge between async storage backends (e.g. a Durable Object\n * `Workspace` backed by SQLite/R2) and the synchronous `FileSystem` interface\n * required by the bundler and TypeScript language service.\n *\n * @example\n * ```ts\n * // Snapshot a Workspace into a bundler-compatible FileSystem\n * async function* workspaceFiles(workspace) {\n * for (const entry of workspace.glob(\"**\\/*.{ts,tsx,json}\")) {\n * const content = await workspace.readFile(entry.path);\n * if (content !== null) yield [entry.path, content];\n * }\n * }\n *\n * const fs = await createFileSystemSnapshot(workspaceFiles(workspace));\n * const { languageService } = await createTypescriptLanguageService({ fileSystem: fs });\n * ```\n */\nexport async function createFileSystemSnapshot(\n entries:\n | AsyncIterable<readonly [string, string]>\n | Iterable<readonly [string, string]>\n): Promise<InMemoryFileSystem> {\n const fs = new InMemoryFileSystem();\n for await (const [path, content] of entries) {\n fs.write(path, content);\n }\n return fs;\n}\n\nexport function isFileSystem(\n obj: FileSystem | Record<string, string>\n): obj is FileSystem {\n return (\n \"read\" in obj &&\n typeof obj.read === \"function\" &&\n \"delete\" in obj &&\n typeof obj.delete === \"function\"\n );\n}\n\n// Python packages can contain both text and data entries\n// This type allows filesystem entries to properly support both in the way workerd wants to receive them\nexport type FileEntry = string | { data: Uint8Array<ArrayBuffer> };\n","/**\n * MIME type inference from file extensions.\n */\n\nconst MIME_TYPES: Record<string, string> = {\n // HTML\n \".html\": \"text/html; charset=utf-8\",\n \".htm\": \"text/html; charset=utf-8\",\n\n // JavaScript\n \".js\": \"application/javascript; charset=utf-8\",\n \".mjs\": \"application/javascript; charset=utf-8\",\n\n // CSS\n \".css\": \"text/css; charset=utf-8\",\n\n // JSON\n \".json\": \"application/json; charset=utf-8\",\n\n // Images\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n\n // Fonts\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".otf\": \"font/otf\",\n \".eot\": \"application/vnd.ms-fontobject\",\n\n // Media\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".ogg\": \"audio/ogg\",\n \".wav\": \"audio/wav\",\n\n // Documents\n \".pdf\": \"application/pdf\",\n \".xml\": \"application/xml\",\n \".txt\": \"text/plain; charset=utf-8\",\n \".csv\": \"text/csv; charset=utf-8\",\n\n // Archives\n \".zip\": \"application/zip\",\n \".gz\": \"application/gzip\",\n \".tar\": \"application/x-tar\",\n\n // WebAssembly\n \".wasm\": \"application/wasm\",\n\n // Manifest\n \".webmanifest\": \"application/manifest+json\",\n\n // Source maps\n \".map\": \"application/json\"\n};\n\n/**\n * Get the file extension from a path (including the dot).\n */\nfunction getExtension(path: string): string {\n const lastDot = path.lastIndexOf(\".\");\n if (lastDot === -1) return \"\";\n const lastSlash = path.lastIndexOf(\"/\");\n if (lastDot < lastSlash) return \"\";\n return path.slice(lastDot).toLowerCase();\n}\n\n/**\n * Infer MIME type from a file path.\n * Returns undefined if the type is unknown.\n */\nexport function inferContentType(path: string): string | undefined {\n const ext = getExtension(path);\n return MIME_TYPES[ext];\n}\n\n/**\n * Whether a content type represents a text-based format\n * (used to decide text vs binary module storage).\n */\nexport function isTextContentType(contentType: string): boolean {\n return (\n contentType.startsWith(\"text/\") ||\n contentType.includes(\"json\") ||\n contentType.includes(\"xml\") ||\n contentType.includes(\"javascript\") ||\n contentType.includes(\"svg\")\n );\n}\n","/**\n * Asset request handler for serving static assets.\n *\n * Key design: the manifest (routing metadata) is separated from the\n * storage (content retrieval). This lets you plug in any backend —\n * in-memory, KV, R2, Workspace, etc.\n *\n * Inspired by Cloudflare's Workers Static Assets behavior and\n * cloudflare-asset-worker by Timo Wilhelm.\n */\n\nimport { inferContentType } from \"./mime\";\n\n// ── Storage interface ───────────────────────────────────────────────\n\n/**\n * Pluggable storage backend for asset content.\n * Implement this to serve assets from KV, R2, Workspace, or any other source.\n */\nexport interface AssetStorage {\n get(pathname: string): Promise<ReadableStream | ArrayBuffer | string | null>;\n}\n\n/**\n * Metadata for a single asset (no content — that comes from storage).\n */\nexport interface AssetMetadata {\n contentType: string | undefined;\n etag: string;\n}\n\n/**\n * The manifest maps pathnames to metadata. Used for routing decisions,\n * ETag checks, and content-type headers — all without touching storage.\n */\nexport type AssetManifest = Map<string, AssetMetadata>;\n\n/**\n * Create an in-memory storage backend from a pathname->content map.\n * This is the zero-config default for small asset sets.\n */\nexport function createMemoryStorage(\n assets: Record<string, string | ArrayBuffer>\n): AssetStorage {\n const map = new Map(Object.entries(assets));\n return {\n get(pathname) {\n return Promise.resolve(map.get(pathname) ?? null);\n }\n };\n}\n\n// ── Configuration ───────────────────────────────────────────────────\n\n/**\n * Configuration for asset serving behavior.\n */\nexport interface AssetConfig {\n /**\n * How to handle HTML file resolution and trailing slashes.\n * @default 'auto-trailing-slash'\n */\n html_handling?:\n | \"auto-trailing-slash\"\n | \"force-trailing-slash\"\n | \"drop-trailing-slash\"\n | \"none\";\n\n /**\n * How to handle requests that don't match any asset.\n * - 'single-page-application': Serve /index.html for 404s\n * - '404-page': Serve nearest 404.html walking up the directory tree\n * - 'none': Return null (fall through)\n * @default 'none'\n */\n not_found_handling?: \"single-page-application\" | \"404-page\" | \"none\";\n\n /**\n * Static redirect rules. Keys are URL pathnames (or https://host/path for cross-host).\n * Supports * glob and :placeholder tokens.\n */\n redirects?: {\n static?: Record<string, { status: number; to: string }>;\n dynamic?: Record<string, { status: number; to: string }>;\n };\n\n /**\n * Custom response headers per pathname pattern (glob syntax).\n */\n headers?: Record<string, { set?: Record<string, string>; unset?: string[] }>;\n}\n\n/**\n * Normalized configuration with all fields required.\n */\ninterface NormalizedConfig {\n html_handling:\n | \"auto-trailing-slash\"\n | \"force-trailing-slash\"\n | \"drop-trailing-slash\"\n | \"none\";\n not_found_handling: \"single-page-application\" | \"404-page\" | \"none\";\n redirects: {\n static: Record<string, { status: number; to: string; lineNumber: number }>;\n dynamic: Record<string, { status: number; to: string }>;\n };\n headers: Record<string, { set?: Record<string, string>; unset?: string[] }>;\n}\n\n/**\n * Normalize user config with defaults.\n */\nexport function normalizeConfig(config?: AssetConfig): NormalizedConfig {\n const staticRedirects: Record<\n string,\n { status: number; to: string; lineNumber: number }\n > = {};\n if (config?.redirects?.static) {\n let lineNumber = 1;\n for (const [path, rule] of Object.entries(config.redirects.static)) {\n staticRedirects[path] = { ...rule, lineNumber: lineNumber++ };\n }\n }\n\n return {\n html_handling: config?.html_handling ?? \"auto-trailing-slash\",\n not_found_handling: config?.not_found_handling ?? \"none\",\n redirects: {\n static: staticRedirects,\n dynamic: config?.redirects?.dynamic ?? {}\n },\n headers: config?.headers ?? {}\n };\n}\n\n// ── ETag / manifest building ────────────────────────────────────────\n\n/**\n * Compute a simple hash for ETag generation.\n * Uses a fast string hash (FNV-1a) for text, or SHA-256 for binary.\n */\nexport async function computeETag(\n content: string | ArrayBuffer\n): Promise<string> {\n if (typeof content === \"string\") {\n // FNV-1a hash for fast text hashing\n let hash = 2166136261;\n for (let i = 0; i < content.length; i++) {\n hash ^= content.charCodeAt(i);\n hash = (hash * 16777619) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n }\n // SHA-256 for binary\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", content);\n const hashArray = new Uint8Array(hashBuffer);\n return [...hashArray.slice(0, 8)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Build an AssetManifest from a pathname->content mapping.\n * Only computes metadata (content types, ETags) — doesn't store content.\n */\nexport async function buildAssetManifest(\n assets: Record<string, string | ArrayBuffer>\n): Promise<AssetManifest> {\n const manifest: AssetManifest = new Map();\n const entries = Object.entries(assets);\n await Promise.all(\n entries.map(async ([pathname, content]) => {\n const contentType = inferContentType(pathname);\n const etag = await computeETag(content);\n manifest.set(pathname, { contentType, etag });\n })\n );\n return manifest;\n}\n\n/**\n * Convenience: build both a manifest and an in-memory storage from assets.\n */\nexport async function buildAssets(\n assets: Record<string, string | ArrayBuffer>\n): Promise<{ manifest: AssetManifest; storage: AssetStorage }> {\n const manifest = await buildAssetManifest(assets);\n const storage = createMemoryStorage(assets);\n return { manifest, storage };\n}\n\n/**\n * Check if a pathname exists in the manifest.\n */\nfunction exists(\n manifest: AssetManifest,\n pathname: string\n): AssetMetadata | undefined {\n return manifest.get(pathname);\n}\n\n// ── Redirect handling ───────────────────────────────────────────────\n\nconst ESCAPE_REGEX_CHARACTERS = /[-/\\\\^$*+?.()|[\\]{}]/g;\nconst escapeRegex = (s: string) =>\n s.replaceAll(ESCAPE_REGEX_CHARACTERS, String.raw`\\$&`);\n\nconst PLACEHOLDER_REGEX = /:([A-Za-z]\\w*)/g;\n\ntype Replacements = Record<string, string>;\n\nfunction replacer(str: string, replacements: Replacements): string {\n for (const [key, value] of Object.entries(replacements)) {\n str = str.replaceAll(`:${key}`, value);\n }\n return str;\n}\n\nfunction generateRuleRegExp(rule: string): RegExp {\n rule = rule\n .split(\"*\")\n .map((s) => escapeRegex(s))\n .join(\"(?<splat>.*)\");\n\n const matches = rule.matchAll(PLACEHOLDER_REGEX);\n for (const match of matches) {\n rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);\n }\n\n return new RegExp(\"^\" + rule + \"$\");\n}\n\nfunction matchStaticRedirects(\n config: NormalizedConfig,\n host: string,\n pathname: string\n): { status: number; to: string; lineNumber: number } | undefined {\n const withHost = config.redirects.static[`https://${host}${pathname}`];\n const withoutHost = config.redirects.static[pathname];\n if (withHost && withoutHost) {\n return withHost.lineNumber < withoutHost.lineNumber\n ? withHost\n : withoutHost;\n }\n return withHost || withoutHost;\n}\n\nfunction matchDynamicRedirects(\n config: NormalizedConfig,\n request: Request\n): { status: number; to: string } | undefined {\n const { pathname } = new URL(request.url);\n for (const [pattern, rule] of Object.entries(config.redirects.dynamic)) {\n try {\n const re = generateRuleRegExp(pattern);\n const result = re.exec(pathname);\n if (result) {\n const target = replacer(rule.to, result.groups || {}).trim();\n return { status: rule.status, to: target };\n }\n } catch {\n // Skip invalid patterns\n }\n }\n return undefined;\n}\n\nfunction handleRedirects(\n request: Request,\n config: NormalizedConfig\n): Response | { proxied: boolean; pathname: string } {\n const url = new URL(request.url);\n const { search, host } = url;\n let { pathname } = url;\n\n const staticMatch = matchStaticRedirects(config, host, pathname);\n const dynamicMatch = staticMatch\n ? undefined\n : matchDynamicRedirects(config, request);\n const match = staticMatch ?? dynamicMatch;\n\n let proxied = false;\n if (match) {\n if (match.status === 200) {\n pathname = new URL(match.to, request.url).pathname;\n proxied = true;\n } else {\n const destination = new URL(match.to, request.url);\n const location =\n destination.origin === url.origin\n ? `${destination.pathname}${destination.search || search}${destination.hash}`\n : `${destination.href}`;\n return new Response(null, {\n status: match.status,\n headers: { Location: location }\n });\n }\n }\n\n return { proxied, pathname };\n}\n\n// ── Custom headers ──────────────────────────────────────────────────\n\nfunction generateGlobRegExp(pattern: string): RegExp {\n const escaped = pattern\n .split(\"*\")\n .map((s) => escapeRegex(s))\n .join(\".*\");\n return new RegExp(\"^\" + escaped + \"$\");\n}\n\nfunction attachCustomHeaders(\n request: Request,\n response: Response,\n config: NormalizedConfig\n): Response {\n if (Object.keys(config.headers).length === 0) {\n return response;\n }\n\n const { pathname } = new URL(request.url);\n const setMap = new Set<string>();\n\n for (const [pattern, rules] of Object.entries(config.headers)) {\n try {\n const re = generateGlobRegExp(pattern);\n if (!re.test(pathname)) continue;\n } catch {\n continue;\n }\n\n if (rules.unset) {\n for (const key of rules.unset) {\n response.headers.delete(key);\n }\n }\n if (rules.set) {\n for (const [key, value] of Object.entries(rules.set)) {\n if (setMap.has(key.toLowerCase())) {\n response.headers.append(key, value);\n } else {\n response.headers.set(key, value);\n setMap.add(key.toLowerCase());\n }\n }\n }\n }\n\n return response;\n}\n\n// ── Path decoding / encoding ────────────────────────────────────────\n\nfunction decodePath(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n })\n .join(\"/\")\n .replaceAll(/\\/+/g, \"/\");\n}\n\nfunction encodePath(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => {\n try {\n return encodeURIComponent(segment);\n } catch {\n return segment;\n }\n })\n .join(\"/\");\n}\n\n// ── HTML handling modes ─────────────────────────────────────────────\n\ntype Intent =\n | { type: \"asset\"; pathname: string; meta: AssetMetadata; status: number }\n | { type: \"redirect\"; to: string }\n | undefined;\n\nfunction getIntent(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects = false,\n acceptsHtml = true\n): Intent {\n switch (config.html_handling) {\n case \"auto-trailing-slash\":\n return htmlAutoTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"force-trailing-slash\":\n return htmlForceTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"drop-trailing-slash\":\n return htmlDropTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"none\":\n return htmlNone(pathname, manifest, config, acceptsHtml);\n }\n}\n\nfunction assetIntent(\n pathname: string,\n meta: AssetMetadata,\n status = 200\n): Intent {\n return { type: \"asset\", pathname, meta, status };\n}\n\nfunction redirectIntent(to: string): Intent {\n return { type: \"redirect\", to };\n}\n\n/**\n * Safe redirect: only redirect if the file exists and the destination\n * itself resolves to the same asset (avoids redirect loops).\n */\nfunction safeRedirect(\n file: string,\n destination: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skip: boolean\n): Intent {\n if (skip) return undefined;\n if (!exists(manifest, destination)) {\n const intent = getIntent(destination, manifest, config, true);\n if (\n intent?.type === \"asset\" &&\n intent.meta.etag === exists(manifest, file)?.etag\n ) {\n return redirectIntent(destination);\n }\n }\n return undefined;\n}\n\nfunction htmlAutoTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) {\n return assetIntent(pathname, exactMeta);\n }\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/index.html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/\")) {\n const indexPath = `${pathname}index.html`;\n if ((meta = exists(manifest, indexPath))) {\n return assetIntent(indexPath, meta);\n }\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n // Exact match\n if (exactMeta) {\n return assetIntent(pathname, exactMeta);\n }\n // Try .html extension\n const htmlPath = `${pathname}.html`;\n if ((meta = exists(manifest, htmlPath))) {\n return assetIntent(htmlPath, meta);\n }\n // Try /index.html\n if (\n (redirect = safeRedirect(\n `${pathname}/index.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlForceTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/index.html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/\")) {\n let p = `${pathname}index.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n p = `${pathname.slice(0, -\"/\".length)}.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname}/index.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlDropTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (pathname === \"/index\") {\n if (\n (redirect = safeRedirect(\n \"/index.html\",\n \"/\",\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else {\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\"/index.html\")) {\n if (pathname === \"/index.html\") {\n if (\n (redirect = safeRedirect(\n \"/index.html\",\n \"/\",\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\"/\")) {\n if (pathname === \"/\") {\n if ((meta = exists(manifest, \"/index.html\"))) {\n return assetIntent(\"/index.html\", meta);\n }\n } else {\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}/index.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n if (exactMeta) return assetIntent(pathname, exactMeta);\n let p = `${pathname}.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n p = `${pathname}/index.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlNone(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n acceptsHtml: boolean\n): Intent {\n const meta = exists(manifest, pathname);\n return meta\n ? assetIntent(pathname, meta)\n : notFound(pathname, manifest, config, acceptsHtml);\n}\n\n// ── Not-found handling ──────────────────────────────────────────────\n\nfunction notFound(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n acceptsHtml = true\n): Intent {\n switch (config.not_found_handling) {\n case \"single-page-application\": {\n // Only serve the SPA fallback for requests that accept HTML\n // (browser navigation). API calls (Accept: */* or application/json)\n // should fall through to the user's server code.\n if (!acceptsHtml) return undefined;\n const meta = exists(manifest, \"/index.html\");\n if (meta) return assetIntent(\"/index.html\", meta, 200);\n return undefined;\n }\n case \"404-page\": {\n let cwd = pathname;\n while (cwd) {\n cwd = cwd.slice(0, cwd.lastIndexOf(\"/\"));\n const p = `${cwd}/404.html`;\n const meta = exists(manifest, p);\n if (meta) return assetIntent(p, meta, 404);\n }\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\n// ── Cache headers ───────────────────────────────────────────────────\n\nconst CACHE_CONTROL_REVALIDATE = \"public, max-age=0, must-revalidate\";\nconst CACHE_CONTROL_IMMUTABLE = \"public, max-age=31536000, immutable\";\n\nfunction getCacheControl(pathname: string): string {\n // Hashed assets (contain content hash in filename) get long-lived caching\n // Common patterns: app.abc123.js, styles.abc123.css, image.abc123.png\n if (/\\.[a-f0-9]{8,}\\.\\w+$/.test(pathname)) {\n return CACHE_CONTROL_IMMUTABLE;\n }\n return CACHE_CONTROL_REVALIDATE;\n}\n\n// ── Main handler ────────────────────────────────────────────────────\n\n/**\n * Handle an asset request. Returns a Response if an asset matches,\n * or null if the request should fall through to the user's Worker.\n *\n * @param request - The incoming HTTP request\n * @param manifest - Asset manifest (pathname -> metadata)\n * @param storage - Storage backend for fetching content\n * @param config - Asset serving configuration\n */\nexport async function handleAssetRequest(\n request: Request,\n manifest: AssetManifest,\n storage: AssetStorage,\n config?: AssetConfig\n): Promise<Response | null> {\n const normalized = normalizeConfig(config);\n\n // Only handle GET and HEAD\n const method = request.method.toUpperCase();\n if (![\"GET\", \"HEAD\"].includes(method)) {\n return null;\n }\n\n // Check redirects first\n const redirectResult = handleRedirects(request, normalized);\n if (redirectResult instanceof Response) {\n return attachCustomHeaders(request, redirectResult, normalized);\n }\n\n const { pathname } = redirectResult;\n const decodedPathname = decodePath(pathname);\n\n // SPA fallback should only apply to navigation requests that explicitly\n // accept HTML, not to API calls (fetch/XHR) which have Accept: */*\n const accept = request.headers.get(\"Accept\") || \"\";\n const acceptsHtml = accept.includes(\"text/html\");\n\n // Resolve intent through HTML handling\n const intent = getIntent(\n decodedPathname,\n manifest,\n normalized,\n false,\n acceptsHtml\n );\n\n if (!intent) {\n return null;\n }\n\n if (intent.type === \"redirect\") {\n const url = new URL(request.url);\n const encodedDest = encodePath(intent.to);\n const response = new Response(null, {\n status: 307,\n headers: { Location: encodedDest + url.search }\n });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // Check if canonical path differs (needs redirect)\n const encodedPathname = encodePath(decodedPathname);\n if (encodedPathname !== pathname) {\n const url = new URL(request.url);\n const response = new Response(null, {\n status: 307,\n headers: { Location: encodedPathname + url.search }\n });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // ETag conditional request\n const { pathname: assetPath, meta, status } = intent;\n const strongETag = `\"${meta.etag}\"`;\n const weakETag = `W/${strongETag}`;\n const ifNoneMatch = request.headers.get(\"If-None-Match\") || \"\";\n const eTags = new Set(ifNoneMatch.split(\",\").map((t) => t.trim()));\n\n const headers = new Headers();\n headers.set(\"ETag\", strongETag);\n if (meta.contentType) {\n headers.set(\"Content-Type\", meta.contentType);\n }\n headers.set(\"Cache-Control\", getCacheControl(decodedPathname));\n\n if (eTags.has(weakETag) || eTags.has(strongETag)) {\n const response = new Response(null, { status: 304, headers });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // Fetch content from storage (only for non-HEAD)\n let body: ReadableStream | ArrayBuffer | string | null = null;\n if (method !== \"HEAD\") {\n body = await storage.get(assetPath);\n }\n\n const response = new Response(body, { status, headers });\n return attachCustomHeaders(request, response, normalized);\n}\n","/**\n * App bundler: builds a full-stack app (server Worker + client bundle + static assets)\n * for the Worker Loader binding.\n *\n * Assets are returned separately for the host to serve — they are NOT embedded\n * in the dynamic isolate. The caller uses handleAssetRequest() on the host side\n * and only forwards non-asset requests to the isolate.\n */\n\nimport { bundleWithEsbuild, bundlerOnlyOptionsWarning } from \"./bundler\";\nimport { hasNodejsCompat, parseWranglerConfig } from \"./config\";\nimport { hasDependencies, installDependencies } from \"./installer\";\nimport { transformAndResolve } from \"./transformer\";\nimport type { AssetConfig, AssetManifest } from \"./asset-handler\";\nimport { buildAssetManifest } from \"./asset-handler\";\nimport type {\n BundlerLoader,\n CreateWorkerResult,\n Files,\n JsxMode\n} from \"./types\";\nimport {\n InMemoryFileSystem,\n isFileSystem,\n type FileSystem\n} from \"./file-system\";\nimport {\n DEFAULT_ENTRY_POINTS,\n detectEntryPoint,\n formatFileListForError\n} from \"./utils\";\nimport { showExperimentalWarning } from \"./experimental\";\n\n/**\n * Options for createApp\n */\nexport interface CreateAppOptions {\n /**\n * Input files — keys are paths relative to project root, values are file contents.\n * Accepts a plain object (which is wrapped in an InMemoryFileSystem automatically)\n * or any FileSystem implementation for custom storage backends.\n */\n files: Files | FileSystem;\n\n /**\n * Server entry point (the Worker fetch handler).\n * If not specified, detected from wrangler config / package.json / defaults.\n */\n server?: string;\n\n /**\n * Client entry point(s) to bundle for the browser.\n * These are bundled with esbuild targeting the browser.\n */\n client?: string | string[];\n\n /**\n * Static assets to serve as-is (pathname -> content).\n * Keys should be URL pathnames (e.g., \"/favicon.ico\", \"/robots.txt\").\n * These are NOT processed by the bundler.\n */\n assets?: Record<string, string | ArrayBuffer>;\n\n /**\n * Asset serving configuration.\n */\n assetConfig?: AssetConfig;\n\n /**\n * Whether to bundle server dependencies.\n * @default true\n */\n bundle?: boolean;\n\n /**\n * External modules that should not be bundled.\n */\n externals?: string[];\n\n /**\n * Target environment for server bundle.\n * @default 'es2022'\n */\n target?: string;\n\n /**\n * Whether to minify the output.\n * @default false\n */\n minify?: boolean;\n\n /**\n * Generate source maps.\n * @default false\n */\n sourcemap?: boolean;\n\n /**\n * npm registry URL for fetching packages.\n */\n registry?: string;\n\n /**\n * JSX transform mode passed to esbuild. Applied to both server and client\n * bundles.\n */\n jsx?: JsxMode;\n\n /**\n * Module to import the JSX runtime from when `jsx: \"automatic\"`.\n */\n jsxImportSource?: string;\n\n /**\n * Constant replacements applied at bundle time. Applied to both server and\n * client bundles.\n */\n define?: Record<string, string>;\n\n /**\n * Per-extension loader overrides. Applied to both server and client bundles.\n */\n loader?: Record<string, BundlerLoader>;\n\n /**\n * Package export conditions to honour during resolution.\n * Applied to both server and client bundles (the host can pass e.g.\n * `[\"worker\", \"browser\"]` for the client, but most users want a single\n * shared set).\n */\n conditions?: string[];\n\n /**\n * Escape hatch for advanced users: extra esbuild plugins to run **before**\n * the bundler's internal virtual-filesystem plugin. Applied to both server\n * and client bundles.\n *\n * The deliberately unwieldy name is the API contract:\n *\n * - This option is **not** covered by semver. It can change shape, be\n * renamed, or be removed in any release.\n * - The runtime ties you to esbuild. If this package switches bundlers\n * (e.g. to rolldown), plugins authored against this API will break.\n *\n * Typed as `unknown[]` at the public boundary to keep `esbuild-wasm` types\n * out of the published `.d.ts`. Cast your plugin array to `unknown[]` when\n * passing it in. Each element is validated at runtime: it must be an object\n * with `name: string` and `setup: (build) => void`.\n *\n * On the server side, only applies when `bundle: true`; transform-only mode\n * surfaces a warning instead. Always applies to client bundles.\n */\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired?: unknown[];\n}\n\n/**\n * Result from createApp\n */\nexport interface CreateAppResult extends CreateWorkerResult {\n /**\n * Combined assets (user-provided + client bundles) for host-side serving.\n * The host should use createMemoryStorage(assets) and handleAssetRequest()\n * to serve these before forwarding requests to the isolate.\n */\n assets: Record<string, string | ArrayBuffer>;\n\n /**\n * The asset manifest for runtime request handling.\n * Contains metadata (content types, ETags) for each asset.\n */\n assetManifest: AssetManifest;\n\n /**\n * The asset config for runtime request handling.\n */\n assetConfig?: AssetConfig;\n\n /**\n * Client bundle output paths (relative to asset root).\n */\n clientBundles?: string[];\n}\n\n/**\n * Creates a full-stack app bundle from source files.\n *\n * This function:\n * 1. Bundles client entry point(s) for the browser (if provided)\n * 2. Collects static assets and builds the asset manifest\n * 3. Bundles the server Worker\n * 4. Returns server modules (for the isolate) and assets (for host-side serving) separately\n *\n * How the output is mounted (module worker, DO class, facet) is the caller's concern.\n */\nexport async function createApp(\n options: CreateAppOptions\n): Promise<CreateAppResult> {\n showExperimentalWarning(\"createApp\");\n const {\n files,\n bundle = true,\n externals: rawExternals = [],\n target = \"es2022\",\n minify = false,\n sourcemap = false,\n registry,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins\n } = options;\n\n const fileSystem: FileSystem = isFileSystem(files)\n ? files\n : new InMemoryFileSystem(files);\n\n // Always treat cloudflare:* as external\n const externals = [\"cloudflare:\", ...rawExternals];\n\n // Parse wrangler config\n const wranglerConfig = parseWranglerConfig(fileSystem);\n const nodejsCompat = hasNodejsCompat(wranglerConfig);\n\n // Install npm dependencies if needed\n const installWarnings: string[] = [];\n if (hasDependencies(fileSystem)) {\n const installResult = await installDependencies(fileSystem, {\n ...(registry ? { registry } : {})\n });\n installWarnings.push(...installResult.warnings);\n }\n\n // ── Step 1: Build client bundles ──────────────────────────────────\n const clientEntries = options.client\n ? Array.isArray(options.client)\n ? options.client\n : [options.client]\n : [];\n\n const clientOutputs: Record<string, string> = {};\n const clientBundles: string[] = [];\n\n for (const clientEntry of clientEntries) {\n if (fileSystem.read(clientEntry) === null) {\n throw new Error(\n `Client entry point \"${clientEntry}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n const clientResult = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint: clientEntry,\n externals,\n target: \"es2022\",\n minify,\n sourcemap,\n nodejsCompat: false,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n\n const bundleModule = clientResult.modules[\"bundle.js\"];\n if (typeof bundleModule === \"string\") {\n const baseName = clientEntry\n .replace(/^src\\//, \"\")\n .replace(/\\.(tsx?|jsx?)$/, \".js\");\n const outputPath = `/${baseName}`;\n clientOutputs[outputPath] = bundleModule;\n clientBundles.push(outputPath);\n }\n }\n\n // ── Step 2: Collect all assets ────────────────────────────────────\n const allAssets: Record<string, string | ArrayBuffer> = {};\n\n if (options.assets) {\n for (const [pathname, content] of Object.entries(options.assets)) {\n const normalizedPath = pathname.startsWith(\"/\")\n ? pathname\n : `/${pathname}`;\n allAssets[normalizedPath] = content;\n }\n }\n\n for (const [pathname, content] of Object.entries(clientOutputs)) {\n allAssets[pathname] = content;\n }\n\n const assetManifest = await buildAssetManifest(allAssets);\n\n // ── Step 3: Build server Worker ───────────────────────────────────\n const serverEntry =\n options.server ?? detectEntryPoint(fileSystem, wranglerConfig);\n\n if (!serverEntry) {\n throw new Error(\n `Could not determine server entry point for createApp. Tried (in order): the \\`server\\` option, \\`main\\` in wrangler config, \\`exports\\`/\\`module\\`/\\`main\\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(\", \")}. Pass \\`server\\` explicitly or add one of those files.`\n );\n }\n\n if (fileSystem.read(serverEntry) === null) {\n throw new Error(\n `Server entry point \"${serverEntry}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n let serverResult: CreateWorkerResult;\n if (bundle) {\n serverResult = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint: serverEntry,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n } else {\n // Transform-only mode never invokes esbuild, so any bundler-only options\n // are silently inactive — surface that as a warning the caller can see.\n serverResult = await transformAndResolve(\n fileSystem,\n serverEntry,\n externals\n );\n\n const bundlerOnly = bundlerOnlyOptionsWarning({\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n if (bundlerOnly) {\n serverResult.warnings = [...(serverResult.warnings ?? []), bundlerOnly];\n }\n }\n\n const result: CreateAppResult = {\n mainModule: serverResult.mainModule,\n modules: serverResult.modules,\n assets: allAssets,\n assetManifest,\n assetConfig: options.assetConfig,\n clientBundles: clientBundles.length > 0 ? clientBundles : undefined\n };\n\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n if (installWarnings.length > 0) {\n result.warnings = [...(serverResult.warnings ?? []), ...installWarnings];\n } else if (serverResult.warnings) {\n result.warnings = serverResult.warnings;\n }\n\n return result;\n}\n","/**\n * Dynamic Worker Bundler\n *\n * Creates worker bundles from source files for Cloudflare's Worker Loader binding.\n */\n\nimport { bundleWithEsbuild, bundlerOnlyOptionsWarning } from \"./bundler\";\nimport { hasNodejsCompat, parseWranglerConfig } from \"./config\";\nimport { hasDependencies, installDependencies } from \"./installer\";\nimport { transformAndResolve } from \"./transformer\";\nimport type { CreateWorkerOptions, CreateWorkerResult, Modules } from \"./types\";\nimport {\n DEFAULT_ENTRY_POINTS,\n detectEntryPoint,\n formatFileListForError\n} from \"./utils\";\nimport { showExperimentalWarning } from \"./experimental\";\nimport {\n InMemoryFileSystem,\n isFileSystem,\n type FileSystem\n} from \"./file-system\";\n\n// Re-export types\nexport type {\n BundlerLoader,\n CreateWorkerOptions,\n CreateWorkerResult,\n Files,\n JsxMode,\n Modules,\n WranglerConfig\n} from \"./types\";\n\n// Re-export app bundler\nexport { createApp } from \"./app\";\nexport type { CreateAppOptions, CreateAppResult } from \"./app\";\n\n// Re-export asset handler\nexport {\n handleAssetRequest,\n buildAssetManifest,\n buildAssets,\n createMemoryStorage\n} from \"./asset-handler\";\nexport type {\n AssetConfig,\n AssetMetadata,\n AssetManifest,\n AssetStorage\n} from \"./asset-handler\";\n\n// Re-export MIME utilities\nexport { inferContentType, isTextContentType } from \"./mime\";\n\n// Re-export file-system\nexport {\n createFileSystemSnapshot,\n DurableObjectKVFileSystem,\n DurableObjectRawFileSystem,\n InMemoryFileSystem,\n type FileSystem\n} from \"./file-system\";\n\n// Re-export installer utilities\nexport { installDependencies, hasDependencies } from \"./installer\";\nexport type { InstallResult } from \"./common\";\n\n/**\n * Creates a worker bundle from source files.\n *\n * This function performs:\n * 1. Entry point detection (from package.json or defaults)\n * 2. Auto-installation of npm dependencies (if package.json has dependencies)\n * 3. TypeScript/JSX transformation (via Sucrase)\n * 4. Module resolution (handling imports/exports)\n * 5. Optional bundling (combining all modules into one)\n *\n * @param options - Configuration options\n * @returns The main module path and all modules\n */\nexport async function createWorker(\n options: CreateWorkerOptions\n): Promise<CreateWorkerResult> {\n showExperimentalWarning(\"createWorker\");\n let {\n files,\n bundle = true,\n externals = [],\n target = \"es2022\",\n minify = false,\n sourcemap = false,\n registry,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins\n } = options;\n\n let fileSystem: FileSystem;\n if (isFileSystem(files)) {\n fileSystem = files;\n } else {\n fileSystem = new InMemoryFileSystem(files);\n }\n\n // Always treat cloudflare:* modules as external (runtime-provided)\n externals = [\"cloudflare:\", ...externals];\n\n // Parse wrangler config for compatibility settings\n const wranglerConfig = parseWranglerConfig(fileSystem);\n const nodejsCompat = hasNodejsCompat(wranglerConfig);\n\n // Auto-install dependencies if package.json or pyproject.toml has dependencies\n const installWarnings: string[] = [];\n if (hasDependencies(fileSystem)) {\n const installResult = await installDependencies(fileSystem, {\n ...(registry ? { registry } : {})\n });\n installWarnings.push(...installResult.warnings);\n }\n\n // Detect entry point (priority: explicit option > wrangler main > package.json > defaults)\n const entryPoint =\n options.entryPoint ?? detectEntryPoint(fileSystem, wranglerConfig);\n\n if (!entryPoint) {\n throw new Error(\n `Could not determine entry point for createWorker. Tried (in order): the \\`entryPoint\\` option, \\`main\\` in wrangler config, \\`exports\\`/\\`module\\`/\\`main\\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(\", \")}. Pass \\`entryPoint\\` explicitly or add one of those files.`\n );\n }\n\n if (fileSystem.read(entryPoint) === null) {\n throw new Error(\n `Entry point \"${entryPoint}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n if (entryPoint.endsWith(\".py\")) {\n const modules: Modules = {};\n for (const path of fileSystem.list()) {\n if (path === \"pyproject.toml\") {\n continue;\n }\n const content = fileSystem.read(path);\n if (content !== null) {\n modules[path] = content;\n }\n }\n\n return {\n mainModule: entryPoint,\n modules,\n wranglerConfig: {\n compatibilityDate: wranglerConfig?.compatibilityDate ?? \"2026-07-02\",\n compatibilityFlags: wranglerConfig?.compatibilityFlags ?? []\n },\n warnings: installWarnings\n };\n }\n\n if (bundle) {\n // Try bundling with esbuild-wasm\n const result = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n plugins\n });\n\n // Add wrangler config if a config file was found\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n // Add install warnings to result\n if (installWarnings.length > 0) {\n result.warnings = [...(result.warnings ?? []), ...installWarnings];\n }\n return result;\n } else {\n // No bundling - transform files and resolve dependencies.\n // Sourcemaps and the esbuild-only options (jsx, jsxImportSource, define,\n // loader, conditions, plugins) are not supported in transform mode — the\n // output mirrors the input structure and never touches esbuild.\n const result = await transformAndResolve(fileSystem, entryPoint, externals);\n\n const bundlerOnly = bundlerOnlyOptionsWarning({\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n plugins\n });\n\n // Add wrangler config if a config file was found\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n // Add install warnings to result\n const extraWarnings = [\n ...installWarnings,\n ...(bundlerOnly ? [bundlerOnly] : [])\n ];\n if (extraWarnings.length > 0) {\n result.warnings = [...(result.warnings ?? []), ...extraWarnings];\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;;;AAuCA,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,cACd,WACA,SACe;CACf,MAAM,EACJ,OACA,WAAW,IACX,aAAa,CAAC,UAAU,SAAS,GACjC,aAAa,uBACX;CAGJ,IAAI,UAAU,WAAW,GAAG,KAAK,UAAU,WAAW,GAAG,GAAG;EAC1D,MAAM,WAAW,gBAAgB,WAAW,UAAU,OAAO,UAAU;EACvE,IAAI,UACF,OAAO;GAAE,MAAM;GAAU,UAAU;EAAM;EAG3C,MAAM,IAAI,MACR,mCAAmC,UAAU,UAAU,SAAS,EAClE;CACF;CAGA,OAAO,eAAe,WAAW,OAAO,YAAY,UAAU;AAChE;;;;AAKA,SAAS,gBACP,WACA,UACA,OACA,YACoB;CAOpB,OAAO,sBAFU,UAHGA,eAAa,QAGI,GAAG,SAEJ,GAAG,OAAO,UAAU;AAC1D;;;;AAKA,SAAS,eACP,WACA,OACA,YACA,YACe;CAEf,MAAM,EAAE,aAAa,YAAY,sBAAsB,SAAS;CAGhE,MAAM,kBAAkB,gBAAgB,YAAY;CACpD,MAAM,cAAc,MAAM,KAAK,eAAe;CAE9C,IAAI,CAAC,aAEH,OAAO;EAAE,MAAM;EAAW,UAAU;CAAK;CAI3C,IAAI;CACJ,IAAI;EACF,MAAM,KAAK,MAAM,WAAW;CAC9B,SAAS,OAAO;EACd,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACpE,MAAM,IAAI,MACR,2BAA2B,gBAAgB,SAAS,YAAY,MAAM,QACxE;CACF;CAGA,MAAM,eAAe,UAAU,KAAK,YAAY;CAEhD,I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ACrC,OAAO;GACP;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC;EAGD,IAAI,mBAAmB,KAAA,GACrB,OAAO,iBAAiB;EAI1B,IAAI,gBAAgB,SAAS,GAC3B,OAAO,WAAW,CAAC,GAAI,OAAO,YAAY,CAAC,GAAI,GAAG,eAAe;EAEnE,OAAO;CACT,OAAO;EAKL,MAAM,SAAS,MAAM,oBAAoB,YAAY,YAAY,SAAS;EAE1E,MAAM,cAAc,0BAA0B;GAC5C;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC;EAGD,IAAI,mBAAmB,KAAA,GACrB,OAAO,iBAAiB;EAI1B,MAAM,gBAAgB,CACpB,GAAG,iBACH,GAAI,cAAc,CAAC,WAAW,IAAI,CAAC,CACrC;EACA,IAAI,cAAc,SAAS,GACzB,OAAO,WAAW,CAAC,GAAI,OAAO,YAAY,CAAC,GAAI,GAAG,aAAa;EAGjE,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["getDirectory","parseToml"],"sources":["../src/resolver.ts","../src/bundler.ts","../src/config.ts","../src/transformer.ts","../src/utils.ts","../src/experimental.ts","../src/file-system.ts","../src/mime.ts","../src/asset-handler.ts","../src/app.ts","../src/index.ts"],"sourcesContent":["// Use the asm.js version to avoid WASM (works in workerd)\nimport { parse } from \"es-module-lexer/js\";\nimport * as resolveExports from \"resolve.exports\";\nimport type { FileSystem } from \"./file-system\";\n\nexport interface ResolveOptions {\n /**\n * All files in the virtual file system\n */\n files: FileSystem;\n\n /**\n * Directory of the importing file (relative to root)\n */\n importer?: string;\n\n /**\n * Conditions for exports resolution (e.g., 'import', 'require', 'browser')\n */\n conditions?: string[];\n\n /**\n * Extensions to try when resolving\n */\n extensions?: string[];\n}\n\nexport interface ResolveResult {\n /**\n * Resolved path (relative to root)\n */\n path: string;\n\n /**\n * Whether this is an external module (npm package not in files)\n */\n external: boolean;\n}\n\nconst DEFAULT_EXTENSIONS = [\n \".ts\",\n \".tsx\",\n \".js\",\n \".jsx\",\n \".mts\",\n \".mjs\",\n \".json\"\n];\n\n/**\n * Resolve a module specifier to a file path in the virtual file system.\n *\n * Handles:\n * - Relative imports (./foo, ../bar)\n * - Package imports (lodash, @scope/pkg)\n * - Package.json exports field\n * - Extension resolution (.ts, .tsx, .js, etc.)\n * - Index file resolution (foo/index.ts)\n *\n * @param specifier - The import specifier (e.g., './utils', 'lodash')\n * @param options - Resolution options\n * @returns Resolved path or external marker\n */\nexport function resolveModule(\n specifier: string,\n options: ResolveOptions\n): ResolveResult {\n const {\n files,\n importer = \"\",\n conditions = [\"import\", \"browser\"],\n extensions = DEFAULT_EXTENSIONS\n } = options;\n\n // Handle relative imports\n if (specifier.startsWith(\".\") || specifier.startsWith(\"/\")) {\n const resolved = resolveRelative(specifier, importer, files, extensions);\n if (resolved) {\n return { path: resolved, external: false };\n }\n // Relative import not found\n throw new Error(\n `Cannot resolve relative import '${specifier}' from '${importer}'`\n );\n }\n\n // Handle bare specifiers (npm packages)\n return resolvePackage(specifier, files, conditions, extensions);\n}\n\n/**\n * Resolve a relative import\n */\nfunction resolveRelative(\n specifier: string,\n importer: string,\n files: FileSystem,\n extensions: string[]\n): string | undefined {\n // Get the directory of the importer\n const importerDir = getDirectory(importer);\n\n // Resolve the path\n const resolved = joinPaths(importerDir, specifier);\n\n return resolveWithExtensions(resolved, files, extensions);\n}\n\n/**\n * Resolve a package specifier\n */\nfunction resolvePackage(\n specifier: string,\n files: FileSystem,\n conditions: string[],\n extensions: string[]\n): ResolveResult {\n // Parse the specifier\n const { packageName, subpath } = parsePackageSpecifier(specifier);\n\n // Look for the package in node_modules\n const packageJsonPath = `node_modules/${packageName}/package.json`;\n const packageJson = files.read(packageJsonPath);\n\n if (!packageJson) {\n // Package not found in files, mark as external\n return { path: specifier, external: true };\n }\n\n // Parse package.json\n let pkg: Record<string, unknown>;\n try {\n pkg = JSON.parse(packageJson) as Record<string, unknown>;\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Invalid package.json at ${packageJsonPath} (for \"${packageName}\"): ${detail}`\n );\n }\n\n // Use resolve.exports to handle the exports field\n const entrySubpath = subpath ? `./${subpath}` : \".\";\n\n try {\n const resolved = resolveExports.resolve(pkg, entrySubpath, { conditions });\n if (resolved && resolved.length > 0) {\n // resolve.exports returns relative paths like './dist/index.js'\n const resolvedPath = resolved[0];\n if (resolvedPath) {\n const fullPath = `node_modules/${packageName}/${normalizeRelativePath(resolvedPath)}`;\n if (files.read(fullPath) !== null) {\n return { path: fullPath, external: false };\n }\n }\n }\n } catch {\n // resolve.exports failed, try legacy resolution\n }\n\n // Fall back to legacy resolution (main, module fields). These only\n // describe the package root, so a subpath import skips them.\n const legacyEntry = resolveExports.legacy(pkg, {\n fields: [\"module\", \"main\"]\n });\n if (!subpath && legacyEntry && typeof legacyEntry === \"string\") {\n const fullPath = `node_modules/${packageName}/${normalizeRelativePath(legacyEntry)}`;\n if (files.read(fullPath) !== null) {\n return { path: fullPath, external: false };\n }\n }\n\n // An exports map is the package's whole public surface: a subpath it\n // does not export must not be reached by probing files on disk.\n if (subpath && pkg.exports !== undefined) {\n return { path: specifier, external: true };\n }\n\n // Try index files directly\n const indexPath = resolveWithExtensions(\n `node_modules/${packageName}${subpath ? `/${subpath}` : \"\"}`,\n files,\n extensions\n );\n if (indexPath) {\n return { path: indexPath, external: false };\n }\n\n // Package found but entry point not resolved, mark as external\n return { path: specifier, external: true };\n}\n\n/**\n * Try to resolve a path with various extensions and index files\n */\nfunction resolveWithExtensions(\n path: string,\n files: FileSystem,\n extensions: string[]\n): string | undefined {\n // Normalize the path\n const normalized = normalizePath(path);\n\n // Try exact match first\n if (files.read(normalized) !== null) {\n return normalized;\n }\n\n // Try adding extensions\n for (const ext of extensions) {\n const withExt = normalized + ext;\n if (files.read(withExt) !== null) {\n return withExt;\n }\n }\n\n // Try index files\n for (const ext of extensions) {\n const indexPath = `${normalized}/index${ext}`;\n if (files.read(indexPath) !== null) {\n return indexPath;\n }\n }\n\n return undefined;\n}\n\n/**\n * Parse a package specifier into package name and subpath\n */\nfunction parsePackageSpecifier(specifier: string): {\n packageName: string;\n subpath: string | undefined;\n} {\n // Handle scoped packages (@scope/pkg)\n if (specifier.startsWith(\"@\")) {\n const parts = specifier.split(\"/\");\n if (parts.length >= 2) {\n const packageName = `${parts[0]}/${parts[1]}`;\n const subpath = parts.slice(2).join(\"/\") || undefined;\n return { packageName, subpath };\n }\n }\n\n // Handle regular packages\n const slashIndex = specifier.indexOf(\"/\");\n if (slashIndex === -1) {\n return { packageName: specifier, subpath: undefined };\n }\n\n return {\n packageName: specifier.slice(0, slashIndex),\n subpath: specifier.slice(slashIndex + 1)\n };\n}\n\n/**\n * Get the directory of a file path\n */\nfunction getDirectory(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n return \"\";\n }\n return filePath.slice(0, lastSlash);\n}\n\n/**\n * Join two paths\n */\nfunction joinPaths(base: string, relative: string): string {\n if (relative.startsWith(\"/\")) {\n return relative.slice(1);\n }\n\n const baseParts = base ? base.split(\"/\") : [];\n const relativeParts = relative.split(\"/\");\n\n for (const part of relativeParts) {\n if (part === \"..\") {\n baseParts.pop();\n } else if (part !== \".\") {\n baseParts.push(part);\n }\n }\n\n return baseParts.join(\"/\");\n}\n\n/**\n * Normalize a path (remove ./ prefix, handle multiple slashes)\n */\nfunction normalizePath(path: string): string {\n return path.replace(/^\\.\\//, \"\").replace(/\\/+/g, \"/\").replace(/\\/$/, \"\");\n}\n\n/**\n * Normalize a relative path from package.json\n */\nfunction normalizeRelativePath(path: string): string {\n if (path.startsWith(\"./\")) {\n return path.slice(2);\n }\n if (path.startsWith(\"/\")) {\n return path.slice(1);\n }\n return path;\n}\n\n/**\n * Parse imports from a JavaScript/TypeScript source file.\n *\n * Uses es-module-lexer for accurate parsing of ES module syntax.\n * Falls back to regex for JSX files since es-module-lexer doesn't\n * handle JSX syntax (e.g., `<div>` is not valid JavaScript).\n */\nexport function parseImports(code: string): string[] {\n try {\n const [imports] = parse(code);\n const specifiers: string[] = [];\n\n for (const imp of imports) {\n // imp.n is the resolved module specifier (handles escape sequences)\n // imp.n is undefined for dynamic imports with non-string arguments\n if (imp.n !== undefined) {\n specifiers.push(imp.n);\n }\n }\n\n return [...new Set(specifiers)]; // Deduplicate\n } catch {\n // es-module-lexer fails on JSX syntax (<Component />) and malformed code\n // Fall back to regex-based parsing\n return parseImportsRegex(code);\n }\n}\n\n/**\n * Regex-based fallback for parsing imports.\n * Used when es-module-lexer fails (e.g., on JSX/TSX files).\n */\nfunction parseImportsRegex(code: string): string[] {\n const imports: string[] = [];\n\n // Match ES module imports\n // import foo from 'bar'\n // import { foo } from 'bar'\n // import * as foo from 'bar'\n // import 'bar'\n // Token-separated, keyword-bounded clause form — see rewriteImports in\n // transformer.ts. Both properties are required for linear matching (#1537).\n const importRegex =\n /\\bimport\\b\\s+(?:(?:(?!\\b(?:import|export)\\b)[\\w*{},])+(?:\\s+(?:(?!\\b(?:import|export)\\b)[\\w*{},])+)*\\s+from\\s+)?['\"]([^'\"]+)['\"]/g;\n for (const match of code.matchAll(importRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n // Match dynamic imports\n // import('bar')\n // await import('bar')\n const dynamicImportRegex = /import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n for (const match of code.matchAll(dynamicImportRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n // Match export from\n // export { foo } from 'bar'\n // export * from 'bar'\n const exportFromRegex =\n /\\bexport\\b\\s+(?:(?:(?!\\b(?:import|export)\\b)[\\w*{},])+(?:\\s+(?:(?!\\b(?:import|export)\\b)[\\w*{},])+)*\\s+)?from\\s+['\"]([^'\"]+)['\"]/g;\n for (const match of code.matchAll(exportFromRegex)) {\n const specifier = match[1];\n if (specifier) {\n imports.push(specifier);\n }\n }\n\n return [...new Set(imports)]; // Deduplicate\n}\n","/**\n * esbuild-wasm bundling functionality.\n */\n\n// Use the browser entry directly — the default \"main\" entry rejects\n// wasmModule in Workers with nodejs_compat (it thinks it's Node.js).\nimport * as esbuild from \"esbuild-wasm/lib/browser.js\";\n\nimport { resolveModule } from \"./resolver\";\nimport type { FileSystem } from \"./file-system\";\nimport type {\n BundlerLoader,\n CreateWorkerResult,\n JsxMode,\n Modules\n} from \"./types\";\n\n/**\n * Build a single warning string listing the bundler-only options the caller\n * set together with `bundle: false`. Returns `null` if none were set.\n *\n * `transformAndResolve` is sucrase + naïve module resolution — it cannot apply\n * `define` substitution, custom `loader` overrides, package-export `conditions`,\n * or esbuild plugins. Silently ignoring these would produce subtly wrong output\n * (e.g. `__DEV__` left as a free identifier in the emitted bundle).\n */\nexport function bundlerOnlyOptionsWarning(opts: {\n jsx?: unknown;\n jsxImportSource?: unknown;\n define?: unknown;\n loader?: unknown;\n conditions?: unknown;\n virtualModules?: unknown;\n plugins?: unknown;\n}): string | null {\n const set: string[] = [];\n if (opts.jsx !== undefined) set.push(\"jsx\");\n if (opts.jsxImportSource !== undefined) set.push(\"jsxImportSource\");\n if (opts.define !== undefined) set.push(\"define\");\n if (opts.loader !== undefined) set.push(\"loader\");\n if (opts.conditions !== undefined) set.push(\"conditions\");\n if (opts.virtualModules !== undefined) set.push(\"virtualModules\");\n if (opts.plugins !== undefined) {\n set.push(\"__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\");\n }\n if (set.length === 0) return null;\n return `${set.join(\", \")} ${set.length === 1 ? \"is\" : \"are\"} ignored when \\`bundle: false\\` (transform-only mode does not run esbuild). Set \\`bundle: true\\` (the default) to apply them.`;\n}\n\n/**\n * Internal options for bundleWithEsbuild. Kept as an object (rather than a\n * long positional list) so new bundler knobs can be added without churning\n * every call site.\n */\nexport interface BundleOptions {\n files: FileSystem;\n entryPoint: string;\n externals: string[];\n target: string;\n minify: boolean;\n sourcemap: boolean;\n nodejsCompat: boolean;\n jsx?: JsxMode;\n jsxImportSource?: string;\n define?: Record<string, string>;\n loader?: Record<string, BundlerLoader>;\n conditions?: string[];\n virtualModules?: Record<string, string>;\n /** Extra esbuild plugins to run BEFORE the internal virtual-fs plugin. */\n plugins?: unknown[];\n}\n\n/**\n * Bundle files using esbuild-wasm\n */\nexport async function bundleWithEsbuild(\n options: BundleOptions\n): Promise<CreateWorkerResult> {\n const {\n files,\n entryPoint,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader: loaderOverrides,\n conditions,\n virtualModules,\n plugins: extraPlugins = []\n } = options;\n // Ensure esbuild is initialized (happens lazily on first use)\n await initializeEsbuild();\n\n // Create a virtual file system plugin for esbuild\n const virtualFsPlugin: esbuild.Plugin = {\n name: \"virtual-fs\",\n setup(build) {\n // Resolve all paths to our virtual file system\n build.onResolve({ filter: /.*/ }, (args) => {\n // Handle entry point - it's passed directly without ./ prefix\n if (args.kind === \"entry-point\") {\n return { path: args.path, namespace: \"virtual\" };\n }\n\n // Handle relative imports\n if (args.path.startsWith(\".\")) {\n const resolved = resolveRelativePath(\n args.resolveDir,\n args.path,\n files\n );\n if (resolved) {\n return { path: resolved, namespace: \"virtual\" };\n }\n }\n\n // Handle bare imports (npm packages)\n if (!args.path.startsWith(\"/\") && !args.path.startsWith(\".\")) {\n // Check if it's in externals\n if (\n externals.includes(args.path) ||\n externals.some(\n (e) => args.path.startsWith(`${e}/`) || args.path.startsWith(e)\n )\n ) {\n return { path: args.path, external: true };\n }\n\n // Try to resolve from node_modules in virtual fs\n try {\n const result = resolveModule(args.path, { files });\n if (!result.external) {\n return { path: result.path, namespace: \"virtual\" };\n }\n } catch {\n // Resolution failed\n }\n\n // Mark as external (package not found in node_modules)\n return { path: args.path, external: true };\n }\n\n // Absolute paths in virtual fs\n const normalizedPath = args.path.startsWith(\"/\")\n ? args.path.slice(1)\n : args.path;\n if (files.read(normalizedPath) !== null) {\n return { path: normalizedPath, namespace: \"virtual\" };\n }\n\n return { path: args.path, external: true };\n });\n\n // Load files from virtual file system\n build.onLoad({ filter: /.*/, namespace: \"virtual\" }, (args) => {\n const content = files.read(args.path);\n if (content === null) {\n return { errors: [{ text: `File not found: ${args.path}` }] };\n }\n\n const loader = getLoader(args.path, loaderOverrides);\n // Set resolveDir so relative imports within this file resolve correctly\n const lastSlash = args.path.lastIndexOf(\"/\");\n const resolveDir = lastSlash >= 0 ? args.path.slice(0, lastSlash) : \"\";\n return { contents: content, loader, resolveDir };\n });\n }\n };\n\n const virtualModulePlugin: esbuild.Plugin | null =\n virtualModules && Object.keys(virtualModules).length > 0\n ? {\n name: \"virtual-modules\",\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (Object.hasOwn(virtualModules, args.path)) {\n return { path: args.path, namespace: \"virtual-module\" };\n }\n return undefined;\n });\n\n build.onLoad(\n { filter: /.*/, namespace: \"virtual-module\" },\n (args) => ({\n contents: virtualModules[args.path] ?? \"\",\n loader: \"js\",\n resolveDir: \"\"\n })\n );\n }\n }\n : null;\n\n // Validate user plugins eagerly: the public type is `unknown[]` (so the\n // .d.ts stays free of esbuild types), which means anything can flow in.\n // Without this, a bad value surfaces as an opaque crash from inside esbuild's\n // own plugin machinery — point at the dangerous option name instead.\n for (let i = 0; i < extraPlugins.length; i++) {\n const p = extraPlugins[i] as\n | { name?: unknown; setup?: unknown }\n | null\n | undefined;\n if (\n !p ||\n typeof p !== \"object\" ||\n typeof p.name !== \"string\" ||\n typeof p.setup !== \"function\"\n ) {\n throw new TypeError(\n `__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired[${i}] is not a valid esbuild plugin (expected an object with \\`name: string\\` and \\`setup: (build) => void\\`).`\n );\n }\n }\n\n // User plugins run BEFORE the internal virtual-fs plugin so they get first\n // crack at onResolve / onLoad (e.g. an RSC plugin claiming \"server-function:*\"\n // before virtual-fs tries to read it from disk). Don't reorder this without\n // thinking about it.\n const userPlugins = extraPlugins as esbuild.Plugin[];\n\n const result = await esbuild.build({\n entryPoints: [entryPoint],\n bundle: true,\n write: false,\n format: \"esm\",\n platform: nodejsCompat ? \"node\" : \"browser\",\n target,\n minify,\n sourcemap: sourcemap ? \"inline\" : false,\n plugins: [\n ...userPlugins,\n ...(virtualModulePlugin ? [virtualModulePlugin] : []),\n virtualFsPlugin\n ],\n outfile: \"bundle.js\",\n ...(jsx !== undefined ? { jsx } : {}),\n ...(jsxImportSource !== undefined ? { jsxImportSource } : {}),\n ...(define !== undefined ? { define } : {}),\n ...(conditions !== undefined ? { conditions } : {})\n });\n\n const output = result.outputFiles?.[0];\n if (!output) {\n // Almost always means a plugin claimed the entry point and produced\n // nothing, or esbuild emitted only secondary outputs (e.g. via the\n // `file` loader, which this bundler doesn't surface).\n throw new Error(\n `esbuild produced no output for entry point \"${entryPoint}\". This usually means a custom plugin (\\`__dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired\\`) intercepted the entry without returning contents, or the entry resolved to an externalised module.`\n );\n }\n\n const modules: Modules = {\n \"bundle.js\": output.text\n };\n\n const warnings = result.warnings.map((w) => w.text);\n if (warnings.length > 0) {\n return { mainModule: \"bundle.js\", modules, warnings };\n }\n return { mainModule: \"bundle.js\", modules };\n}\n\n/**\n * Resolve a relative path against a directory within the virtual filesystem.\n */\nfunction resolveRelativePath(\n resolveDir: string,\n relativePath: string,\n files: FileSystem\n): string | undefined {\n // Normalize the resolve directory\n const dir = resolveDir.replace(/^\\//, \"\");\n\n // Resolve the relative path\n const parts = dir ? dir.split(\"/\") : [];\n const relParts = relativePath.split(\"/\");\n\n for (const part of relParts) {\n if (part === \"..\") {\n parts.pop();\n } else if (part !== \".\") {\n parts.push(part);\n }\n }\n\n const resolved = parts.join(\"/\");\n\n // Try exact match\n if (files.read(resolved) !== null) {\n return resolved;\n }\n\n // Try adding extensions\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\", \".mts\", \".mjs\"];\n for (const ext of extensions) {\n if (files.read(resolved + ext) !== null) {\n return resolved + ext;\n }\n }\n\n // Try index files\n for (const ext of extensions) {\n const indexPath = `${resolved}/index${ext}`;\n if (files.read(indexPath) !== null) {\n return indexPath;\n }\n }\n\n return undefined;\n}\n\nfunction getLoader(\n path: string,\n overrides?: Record<string, BundlerLoader>\n): esbuild.Loader {\n if (overrides) {\n // Match on the longest extension first so \".d.ts\" wins over \".ts\" if both\n // are configured.\n const matched = Object.keys(overrides)\n .filter((ext) => path.endsWith(ext))\n .sort((a, b) => b.length - a.length)[0];\n if (matched !== undefined) {\n return overrides[matched] as esbuild.Loader;\n }\n }\n if (path.endsWith(\".ts\") || path.endsWith(\".mts\")) return \"ts\";\n if (path.endsWith(\".tsx\")) return \"tsx\";\n if (path.endsWith(\".jsx\")) return \"jsx\";\n if (path.endsWith(\".json\")) return \"json\";\n if (path.endsWith(\".css\")) return \"css\";\n return \"js\";\n}\n\n// Track esbuild initialization state\nlet esbuildInitialized = false;\nlet esbuildInitializePromise: Promise<void> | null = null;\n\n/**\n * Detect whether we are running inside the Cloudflare Workers runtime\n * (workerd). Both production Workers and the local dev runtime expose\n * `navigator.userAgent === \"Cloudflare-Workers\"`.\n *\n * Exported so tests can sanity-check the guard without standing up a\n * separate Node-only test runner.\n */\nexport function isCloudflareWorkersRuntime(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n typeof navigator.userAgent === \"string\" &&\n navigator.userAgent === \"Cloudflare-Workers\"\n );\n}\n\n/**\n * Error message thrown when `createWorker` / `createApp` is called outside of\n * the Workers runtime. Exported so tests can match against it without\n * duplicating the wording.\n */\nexport const NOT_IN_WORKERS_ERROR =\n \"@cloudflare/worker-bundler is only supported inside the Cloudflare Workers runtime (workerd). \" +\n \"It cannot run in plain Node.js — including Vitest, Jest or other Node-based test runners — \" +\n \"because it bundles via a `WebAssembly.Module` import that only the Workers module loader can resolve. \" +\n \"To test code that uses this package, run your tests with @cloudflare/vitest-pool-workers so they execute inside workerd. \" +\n \"See https://developers.cloudflare.com/workers/testing/vitest-integration/ for setup.\";\n\n/**\n * Pre-started promise for the esbuild WASM module load.\n *\n * Pre-warmed at module evaluation time when (and only when) we're inside\n * workerd, so the wasm `Compile` cost runs in parallel with everything else\n * the test/handler is doing — matching the implicit behaviour of the static\n * `import esbuildWasm from \"./esbuild.wasm\"` we used to have. Without this,\n * the first `bundleWithEsbuild` call paid the full wasm-compile cost\n * serially, which was enough to flake the first test of an `app-e2e`-style\n * file under vitest's default 5s timeout on slower CI runners.\n *\n * Outside Workers, we *don't* start the import — Node's ESM-WASM loader\n * would try to resolve esbuild's Go-runtime `gojs` import namespace as an\n * npm package and crash. `initializeEsbuild()` throws `NOT_IN_WORKERS_ERROR`\n * before ever touching the file in that case.\n */\nlet pendingWasmImport: Promise<{ default: WebAssembly.Module }> | null = null;\n\nif (isCloudflareWorkersRuntime()) {\n pendingWasmImport = import(\"./esbuild.wasm\");\n // Suppress unhandled-rejection if `initializeEsbuild()` is never called.\n // Errors are still surfaced when the promise is awaited there.\n pendingWasmImport.catch(() => {});\n}\n\n/**\n * Initialize the esbuild bundler.\n * This is called automatically when needed.\n */\nasync function initializeEsbuild(): Promise<void> {\n // If already initialized, return immediately\n if (esbuildInitialized) return;\n\n // If initialization is in progress, wait for it\n if (esbuildInitializePromise) {\n return esbuildInitializePromise;\n }\n\n // Start initialization\n esbuildInitializePromise = (async () => {\n // Refuse to load esbuild.wasm outside Workers. The .wasm file is built\n // from Go, which declares a `gojs` import namespace in its WASM-host\n // bridge; Node's ESM-WASM loader (Node 22+) tries to resolve that as an\n // npm package and surfaces `Cannot find package 'gojs'` instead of\n // anything actionable. Fail fast with a useful message before we ever\n // touch the .wasm file.\n if (!isCloudflareWorkersRuntime() || pendingWasmImport === null) {\n throw new Error(NOT_IN_WORKERS_ERROR);\n }\n\n try {\n // Await the pre-warmed wasm import kicked off at module evaluation.\n // In the common case (warm worker) this is already resolved.\n const wasmModule = (await pendingWasmImport).default;\n\n await esbuild.initialize({\n wasmModule,\n worker: false\n });\n\n esbuildInitialized = true;\n } catch (error) {\n // If initialization fails, esbuild may already be initialized\n if (\n error instanceof Error &&\n error.message.includes('Cannot call \"initialize\" more than once')\n ) {\n esbuildInitialized = true;\n return;\n }\n throw error;\n }\n })();\n\n try {\n await esbuildInitializePromise;\n } catch (error) {\n // Reset promise so caller can try again\n esbuildInitializePromise = null;\n throw error;\n }\n}\n","/**\n * Wrangler configuration parsing.\n *\n * Parses wrangler.toml, wrangler.json, and wrangler.jsonc files\n * to extract compatibility settings.\n */\n\nimport { parse as parseToml } from \"smol-toml\";\nimport type { WranglerConfig } from \"./types\";\nimport type { FileSystem } from \"./file-system\";\n\n/**\n * Parse wrangler configuration from files.\n *\n * Looks for wrangler.toml, wrangler.json, or wrangler.jsonc in the files\n * and extracts compatibility_date and compatibility_flags.\n *\n * @param files - Virtual file system\n * @returns Parsed wrangler config, or undefined if no config file found\n */\nexport function parseWranglerConfig(\n files: FileSystem\n): WranglerConfig | undefined {\n // Try each config file format in order of preference\n const tomlContent = files.read(\"wrangler.toml\");\n if (tomlContent) {\n return parseWranglerToml(tomlContent);\n }\n\n const jsonContent = files.read(\"wrangler.json\");\n if (jsonContent) {\n return parseWranglerJson(jsonContent);\n }\n\n const jsoncContent = files.read(\"wrangler.jsonc\");\n if (jsoncContent) {\n return parseWranglerJsonc(jsoncContent);\n }\n\n return undefined;\n}\n\n/**\n * Parse wrangler.toml content\n */\nfunction parseWranglerToml(content: string): WranglerConfig {\n try {\n const config = parseToml(content) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse wrangler.json content\n */\nfunction parseWranglerJson(content: string): WranglerConfig {\n try {\n const config = JSON.parse(content) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Parse wrangler.jsonc content (JSON with comments)\n */\nfunction parseWranglerJsonc(content: string): WranglerConfig {\n try {\n // Strip comments from JSONC\n const jsonContent = stripJsonComments(content);\n const config = JSON.parse(jsonContent) as Record<string, unknown>;\n return extractWranglerConfig(config);\n } catch {\n return {};\n }\n}\n\n/**\n * Extract wrangler config fields from parsed config object.\n * Handles both snake_case (toml) and camelCase (json) formats.\n */\nfunction extractWranglerConfig(\n config: Record<string, unknown>\n): WranglerConfig {\n const result: WranglerConfig = {};\n\n // main entry point\n const main = config[\"main\"];\n if (typeof main === \"string\") {\n result.main = main;\n }\n\n // compatibility_date (toml) or compatibilityDate (json)\n const date = config[\"compatibility_date\"] ?? config[\"compatibilityDate\"];\n if (typeof date === \"string\") {\n result.compatibilityDate = date;\n }\n\n // compatibility_flags (toml) or compatibilityFlags (json)\n const flags = config[\"compatibility_flags\"] ?? config[\"compatibilityFlags\"];\n if (Array.isArray(flags) && flags.every((f) => typeof f === \"string\")) {\n result.compatibilityFlags = flags;\n }\n\n return result;\n}\n\n/**\n * Strip comments from JSONC content.\n * Handles both single-line (//) and multi-line comments.\n */\nfunction stripJsonComments(content: string): string {\n let result = \"\";\n let i = 0;\n let inString = false;\n let stringChar = \"\";\n\n while (i < content.length) {\n const char = content[i];\n const nextChar = content[i + 1];\n\n // Handle string literals (don't strip comments inside strings)\n if (\n (char === '\"' || char === \"'\") &&\n (i === 0 || content[i - 1] !== \"\\\\\")\n ) {\n if (!inString) {\n inString = true;\n stringChar = char;\n } else if (char === stringChar) {\n inString = false;\n }\n result += char;\n i++;\n continue;\n }\n\n if (inString) {\n result += char;\n i++;\n continue;\n }\n\n // Handle single-line comments\n if (char === \"/\" && nextChar === \"/\") {\n // Skip until end of line\n while (i < content.length && content[i] !== \"\\n\") {\n i++;\n }\n continue;\n }\n\n // Handle multi-line comments\n if (char === \"/\" && nextChar === \"*\") {\n i += 2;\n // Skip until */\n while (\n i < content.length - 1 &&\n !(content[i] === \"*\" && content[i + 1] === \"/\")\n ) {\n i++;\n }\n i += 2; // Skip */\n continue;\n }\n\n result += char;\n i++;\n }\n\n return result;\n}\n\n/**\n * Check if nodejs_compat flag is enabled in the config.\n */\nexport function hasNodejsCompat(config: WranglerConfig | undefined): boolean {\n return config?.compatibilityFlags?.includes(\"nodejs_compat\") ?? false;\n}\n","import { transform } from \"sucrase\";\nimport { parseImports, resolveModule } from \"./resolver\";\nimport type { FileSystem } from \"./file-system\";\nimport type { CreateWorkerResult, Modules } from \"./types\";\n\nexport interface TransformResult {\n code: string;\n sourceMap?: string;\n}\n\nexport interface TransformOptions {\n /**\n * Source file path (for source maps and error messages)\n */\n filePath: string;\n\n /**\n * Whether to generate source maps\n */\n sourceMap?: boolean;\n\n /**\n * Whether to preserve JSX (don't transform to createElement calls)\n */\n preserveJsx?: boolean;\n\n /**\n * JSX runtime ('automatic' for new JSX transform, 'classic' for React.createElement)\n */\n jsxRuntime?: \"automatic\" | \"classic\" | \"preserve\";\n\n /**\n * JSX import source for automatic runtime (default: 'react')\n */\n jsxImportSource?: string;\n\n /**\n * Whether this is a production build\n */\n production?: boolean;\n}\n\n/**\n * Transform TypeScript/JSX code to JavaScript using Sucrase.\n *\n * Sucrase is a super-fast TypeScript transformer that:\n * - Strips type annotations\n * - Transforms JSX\n * - Is ~20x faster than Babel\n * - Works in any JS environment (no WASM needed)\n *\n * @param code - Source code to transform\n * @param options - Transform options\n * @returns Transformed code\n */\nexport function transformCode(\n code: string,\n options: TransformOptions\n): TransformResult {\n const {\n filePath,\n sourceMap = false,\n jsxRuntime = \"automatic\",\n jsxImportSource = \"react\",\n production = false\n } = options;\n\n const transforms: Array<\"typescript\" | \"jsx\" | \"flow\"> = [];\n\n // Determine transforms based on file extension\n if (isTypeScriptFile(filePath)) {\n transforms.push(\"typescript\");\n }\n\n if (isJsxFile(filePath)) {\n if (jsxRuntime !== \"preserve\") {\n transforms.push(\"jsx\");\n }\n }\n\n if (transforms.length === 0) {\n // No transforms needed, return as-is\n return { code };\n }\n\n const transformOptions: Parameters<typeof transform>[1] = {\n transforms,\n filePath,\n jsxRuntime,\n jsxImportSource,\n production,\n // Keep ESM imports/exports as-is\n preserveDynamicImport: true,\n // Disable ES transforms since Workers support modern JS\n disableESTransforms: true\n };\n\n if (sourceMap) {\n transformOptions.sourceMapOptions = {\n compiledFilename: filePath.replace(/\\.(tsx?|mts)$/, \".js\")\n };\n }\n\n const result = transform(code, transformOptions);\n\n if (result.sourceMap) {\n return {\n code: result.code,\n sourceMap: JSON.stringify(result.sourceMap)\n };\n }\n return { code: result.code };\n}\n\n/**\n * Check if a file path is a TypeScript file\n */\nexport function isTypeScriptFile(filePath: string): boolean {\n return /\\.(ts|tsx|mts)$/.test(filePath);\n}\n\n/**\n * Check if a file path is a JSX file\n */\nexport function isJsxFile(filePath: string): boolean {\n return /\\.(jsx|tsx)$/.test(filePath);\n}\n\n/**\n * Check if a file path is any JavaScript/TypeScript file\n */\nexport function isJavaScriptFile(filePath: string): boolean {\n return /\\.(js|jsx|ts|tsx|mjs|mts)$/.test(filePath);\n}\n\n/**\n * Get the output path for a transformed file\n */\nexport function getOutputPath(filePath: string): string {\n // .ts -> .js, .tsx -> .js, .mts -> .mjs\n return filePath.replace(/\\.tsx?$/, \".js\").replace(/\\.mts$/, \".mjs\");\n}\n\n/**\n * Transform all files and resolve their dependencies.\n * This produces multiple modules instead of a single bundle.\n */\nexport async function transformAndResolve(\n files: FileSystem,\n entryPoint: string,\n externals: string[]\n): Promise<CreateWorkerResult> {\n const modules: Modules = {};\n const warnings: string[] = [];\n const processed = new Set<string>();\n const toProcess = [entryPoint];\n\n // Map from source path to output path\n const pathMap = new Map<string, string>();\n\n // First pass: collect all files and their output paths\n while (toProcess.length > 0) {\n const filePath = toProcess.pop();\n if (!filePath || processed.has(filePath)) continue;\n processed.add(filePath);\n\n const content = files.read(filePath);\n if (content === null) {\n warnings.push(`File not found: ${filePath}`);\n continue;\n }\n\n // Calculate output path\n const outputPath = isTypeScriptFile(filePath)\n ? getOutputPath(filePath)\n : filePath;\n pathMap.set(filePath, outputPath);\n\n // Handle non-JS files\n if (!isJavaScriptFile(filePath)) {\n if (filePath.endsWith(\".json\")) {\n try {\n modules[filePath] = { json: JSON.parse(content) };\n } catch {\n warnings.push(`Failed to parse JSON file: ${filePath}`);\n }\n } else {\n // Include as text\n modules[filePath] = { text: content };\n }\n continue;\n }\n\n // Parse imports and queue them for processing\n const imports = parseImports(content);\n for (const specifier of imports) {\n // Skip external modules\n if (\n externals.includes(specifier) ||\n externals.some(\n (e) => specifier.startsWith(`${e}/`) || specifier.startsWith(e)\n )\n ) {\n continue;\n }\n\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer: filePath\n });\n\n if (!resolved.external && !processed.has(resolved.path)) {\n toProcess.push(resolved.path);\n }\n } catch (error) {\n warnings.push(\n `Failed to resolve '${specifier}' from ${filePath}: ${error instanceof Error ? error.message : error}`\n );\n }\n }\n }\n\n // Second pass: transform files and rewrite imports\n for (const [sourcePath, outputPath] of pathMap) {\n const content = files.read(sourcePath);\n if (content === null || !isJavaScriptFile(sourcePath)) continue;\n\n let transformedCode: string;\n\n if (isTypeScriptFile(sourcePath)) {\n try {\n const result = transformCode(content, {\n filePath: sourcePath\n });\n transformedCode = result.code;\n } catch (error) {\n warnings.push(\n `Failed to transform ${sourcePath}: ${error instanceof Error ? error.message : error}`\n );\n continue;\n }\n } else {\n transformedCode = content;\n }\n\n // Rewrite imports to use the full output paths\n transformedCode = rewriteImports(\n transformedCode,\n sourcePath,\n files,\n pathMap,\n externals\n );\n\n // Add to output modules\n modules[outputPath] = transformedCode;\n }\n\n // Calculate the main module path (transformed entry point)\n const mainModule = isTypeScriptFile(entryPoint)\n ? getOutputPath(entryPoint)\n : entryPoint;\n\n if (warnings.length > 0) {\n return { mainModule, modules, warnings };\n }\n return { mainModule, modules };\n}\n\n/**\n * Rewrite import specifiers to use full output paths.\n * This is necessary because the Worker Loader expects imports to match registered module names.\n */\nfunction rewriteImports(\n code: string,\n importer: string,\n files: FileSystem,\n pathMap: Map<string, string>,\n externals: string[]\n): string {\n // Match import/export statements with string specifiers\n // Handles: import x from 'y', import { x } from 'y', import 'y', export { x } from 'y', export * from 'y'\n // Clause tokens and whitespace are disjoint, so the regex cannot redistribute\n // whitespace between adjacent quantifiers. Each candidate also stops at the\n // next import/export keyword; otherwise stacked near-matches would make the\n // unanchored global search rescan the remaining suffix (#1537).\n const importExportRegex =\n /(\\bimport\\b\\s+(?:(?:(?!\\b(?:import|export)\\b)[\\w*{},])+(?:\\s+(?:(?!\\b(?:import|export)\\b)[\\w*{},])+)*\\s+from\\s+)?|\\bexport\\b\\s+(?:(?:(?!\\b(?:import|export)\\b)[\\w*{},])+(?:\\s+(?:(?!\\b(?:import|export)\\b)[\\w*{},])+)*\\s+)?from\\s+)(['\"])([^'\"]+)\\2/g;\n\n // Get importer's output path to use as the base for resolving\n const importerOutputPath = pathMap.get(importer) ?? importer;\n\n return code.replace(\n importExportRegex,\n (match, prefix: string, quote: string, specifier: string) => {\n // Skip external modules\n if (\n externals.includes(specifier) ||\n externals.some(\n (e) => specifier.startsWith(`${e}/`) || specifier.startsWith(e)\n )\n ) {\n return match;\n }\n\n // Skip non-relative imports that aren't in our files (bare imports to npm packages)\n if (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\")) {\n // Try to resolve it - if it resolves to node_modules, rewrite the path\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer\n });\n\n if (resolved.external) {\n return match;\n }\n\n // Get the output path for the resolved module\n const resolvedOutputPath =\n pathMap.get(resolved.path) ?? resolved.path;\n\n // For node_modules imports, use the full path\n if (resolved.path.startsWith(\"node_modules/\")) {\n return `${prefix}${quote}/${resolvedOutputPath}${quote}`;\n }\n\n // Calculate relative path for non-node_modules\n const relativePath = calculateRelativePath(\n importerOutputPath,\n resolvedOutputPath\n );\n return `${prefix}${quote}${relativePath}${quote}`;\n } catch {\n // Resolution failed, keep original\n return match;\n }\n }\n\n try {\n const resolved = resolveModule(specifier, {\n files,\n importer\n });\n\n if (resolved.external) {\n return match;\n }\n\n // Get the output path for the resolved module\n const resolvedOutputPath = pathMap.get(resolved.path) ?? resolved.path;\n\n // Calculate the relative path from the importer's output location to the resolved output\n const relativePath = calculateRelativePath(\n importerOutputPath,\n resolvedOutputPath\n );\n\n // Return the rewritten import with the relative output path\n return `${prefix}${quote}${relativePath}${quote}`;\n } catch {\n // If resolution fails, keep the original\n return match;\n }\n }\n );\n}\n\n/**\n * Calculate relative path from one file to another.\n */\nfunction calculateRelativePath(from: string, to: string): string {\n const fromDir = getDirectory(from);\n const toDir = getDirectory(to);\n const toFile = to.split(\"/\").pop() ?? to;\n\n if (fromDir === toDir) {\n // Same directory\n return `./${toFile}`;\n }\n\n const fromParts = fromDir ? fromDir.split(\"/\") : [];\n const toParts = toDir ? toDir.split(\"/\") : [];\n\n // Find common prefix\n let commonLength = 0;\n while (\n commonLength < fromParts.length &&\n commonLength < toParts.length &&\n fromParts[commonLength] === toParts[commonLength]\n ) {\n commonLength++;\n }\n\n // Calculate relative path\n const upCount = fromParts.length - commonLength;\n const downParts = toParts.slice(commonLength);\n\n let relativePath = \"\";\n if (upCount === 0) {\n relativePath = \"./\";\n } else {\n relativePath = \"../\".repeat(upCount);\n }\n\n if (downParts.length > 0) {\n relativePath += `${downParts.join(\"/\")}/`;\n }\n\n return relativePath + toFile;\n}\n\nfunction getDirectory(filePath: string): string {\n const lastSlash = filePath.lastIndexOf(\"/\");\n if (lastSlash === -1) {\n return \"\";\n }\n return filePath.slice(0, lastSlash);\n}\n","/**\n * Utility functions.\n */\n\nimport type { WranglerConfig } from \"./types\";\nimport type { FileSystem } from \"./file-system\";\n\n/**\n * Default entry-point paths searched (in order) when no explicit entry has\n * been provided and `wrangler.*` / `package.json` don't declare one.\n *\n * Exported so the \"Could not determine entry point\" error messages in\n * `index.ts` (createWorker) and `app.ts` (createApp) can reference the same\n * source of truth — otherwise the messages drift out of sync the first time\n * someone adds a default and forgets to update both error strings.\n */\nexport const DEFAULT_ENTRY_POINTS = [\n \"src/index.ts\",\n \"src/index.js\",\n \"src/index.mts\",\n \"src/index.mjs\",\n \"index.ts\",\n \"index.js\",\n \"index.py\",\n \"src/worker.ts\",\n \"src/worker.js\"\n] as const;\n\n/**\n * Detect entry point from wrangler config, package.json, or use defaults.\n * Priority: wrangler main > package.json exports/module/main > default paths\n */\nexport function detectEntryPoint(\n files: FileSystem,\n wranglerConfig: WranglerConfig | undefined\n): string | undefined {\n // First, check wrangler config main field\n if (wranglerConfig?.main) {\n return normalizeEntryPath(wranglerConfig.main);\n }\n\n // Try to read package.json\n const packageJsonContent = files.read(\"package.json\");\n if (packageJsonContent) {\n try {\n const pkg = JSON.parse(packageJsonContent) as {\n main?: string;\n module?: string;\n exports?: Record<string, unknown> | string;\n };\n\n // Check exports field first\n if (pkg.exports) {\n if (typeof pkg.exports === \"string\") {\n return normalizeEntryPath(pkg.exports);\n }\n // Handle exports object - look for \".\" entry\n const dotExport = pkg.exports[\".\"];\n if (dotExport) {\n if (typeof dotExport === \"string\") {\n return normalizeEntryPath(dotExport);\n }\n // Handle conditional exports\n if (typeof dotExport === \"object\" && dotExport !== null) {\n const exp = dotExport as Record<string, unknown>;\n const entry = exp[\"import\"] ?? exp[\"default\"] ?? exp[\"module\"];\n if (typeof entry === \"string\") {\n return normalizeEntryPath(entry);\n }\n }\n }\n }\n\n // Check module field\n if (pkg.module) {\n return normalizeEntryPath(pkg.module);\n }\n\n // Check main field\n if (pkg.main) {\n return normalizeEntryPath(pkg.main);\n }\n } catch {\n // Invalid JSON, continue to defaults\n }\n }\n\n for (const entry of DEFAULT_ENTRY_POINTS) {\n if (files.read(entry) !== null) {\n return entry;\n }\n }\n\n return undefined;\n}\n\nfunction normalizeEntryPath(path: string): string {\n // Remove leading ./\n if (path.startsWith(\"./\")) {\n return path.slice(2);\n }\n return path;\n}\n\n/**\n * Render the user-provided source files as a short, readable list for use in\n * \"entry point not found\" errors. Skips installed `node_modules/` files\n * (which can be tens of thousands of paths and drown out the actually\n * relevant signal — the files the user passed in) and truncates the tail.\n */\nexport function formatFileListForError(files: FileSystem, limit = 10): string {\n const all = files\n .list()\n .filter((p) => !p.startsWith(\"node_modules/\"))\n .sort();\n if (all.length === 0) {\n return \"(none — `files` is empty or only contains node_modules entries)\";\n }\n const shown = all.slice(0, limit).join(\", \");\n if (all.length <= limit) return shown;\n return `${shown}, … (+${all.length - limit} more)`;\n}\n","let warningShown = false;\n\nexport function showExperimentalWarning(fn: string) {\n if (!warningShown) {\n warningShown = true;\n console.warn(\n `[worker-bundler] ${fn}(): This package is experimental and its API may change without notice.`\n );\n }\n}\n","export interface FileSystem {\n /**\n * Reads a file from the file system.\n * @param path The path to the file.\n * @returns The contents of the file, or `null` if the file does not exist.\n */\n read(path: string): string | null;\n\n /**\n * Writes a file to the file system.\n * @param path The path to the file.\n * @param content The contents of the file.\n */\n write(path: string, content: FileEntry): void;\n\n /**\n * Deletes a file from the file system.\n * @param path The path to the file.\n */\n delete(path: string): void;\n\n /**\n * Returns the logical paths of all files in the filesystem, optionally\n * filtered to those whose path starts with `prefix`.\n * @param prefix Optional path prefix to filter results.\n */\n list(prefix?: string): string[];\n\n /**\n * Depending on the implementation of the filesystem writes may be buffered\n * in-memory to avoid (comparatively) expensive I/O operations. This method\n * gives users of the filesystem a way to ensure that all writes are flushed\n * to disk.\n */\n flush(): Promise<void>;\n}\n\n/**\n * A simple in-memory filesystem backed by a `Map`. Intended for use in tests\n * and build pipelines where persistence is not required.\n */\nexport class InMemoryFileSystem implements FileSystem {\n private files: Map<string, string> = new Map();\n\n /**\n * @param files Optional initial file contents. Accepts either a plain object\n * (keys are paths, values are file contents) or a `Map`. Defaults to an\n * empty filesystem.\n */\n constructor(files: Record<string, string> | Map<string, string> = new Map()) {\n this.files = files instanceof Map ? files : new Map(Object.entries(files));\n }\n\n read(path: string): string | null {\n return this.files.get(path) ?? null;\n }\n\n write(path: string, content: string): void {\n this.files.set(path, content);\n }\n\n delete(path: string): void {\n this.files.delete(path);\n }\n\n list(prefix?: string): string[] {\n return Array.from(this.files.keys()).filter(\n (path) => prefix === undefined || path.startsWith(prefix)\n );\n }\n\n flush(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/**\n * A generic write-overlay on top of any `FileSystem`. Not re-exported from the\n * package entry point — intended as an implementation detail for higher-level\n * filesystem classes.\n *\n * Writes and deletes are buffered in memory keyed by the raw (untransformed)\n * path. Reads are served from the write buffer first; deleted paths return\n * `null`; remaining reads are delegated to the inner filesystem. `flush()`\n * drains deletes and writes into the inner filesystem, awaits `inner.flush()`,\n * and then clears the buffers.\n */\nexport class OverlayFileSystem implements FileSystem {\n private overlay: Map<string, string> | null = null;\n private deletions: Set<string> | null = null;\n\n constructor(private readonly inner: FileSystem) {}\n\n read(path: string): string | null {\n if (this.overlay?.has(path)) {\n return this.overlay.get(path) ?? null;\n }\n if (this.deletions?.has(path)) {\n return null;\n }\n return this.inner.read(path);\n }\n\n write(path: string, content: string): void {\n if (this.overlay === null) {\n this.overlay = new Map();\n }\n this.overlay.set(path, content);\n this.deletions?.delete(path);\n }\n\n delete(path: string): void {\n this.overlay?.delete(path);\n if (this.deletions === null) {\n this.deletions = new Set();\n }\n this.deletions.add(path);\n }\n\n list(prefix?: string): string[] {\n const innerPaths = this.inner\n .list(prefix)\n .filter((path) => !this.deletions?.has(path));\n // Union of inner paths and overlay paths, with overlay entries taking\n // precedence (Set deduplicates paths that appear in both).\n const result = new Set(innerPaths);\n for (const path of this.overlay?.keys() ?? []) {\n if (prefix === undefined || path.startsWith(prefix)) {\n result.add(path);\n }\n }\n return Array.from(result);\n }\n\n async flush(): Promise<void> {\n if (this.overlay === null && this.deletions === null) {\n return;\n }\n for (const path of this.deletions ?? []) {\n this.inner.delete(path);\n }\n for (const [path, content] of this.overlay ?? []) {\n this.inner.write(path, content);\n }\n await this.inner.flush();\n this.overlay = null;\n this.deletions = null;\n }\n}\n\n/**\n * A filesystem backed directly by Durable Object KV storage. Every write is\n * committed to KV synchronously with no in-memory buffering, and `flush()` is\n * a no-op.\n *\n * Use this when you want immediate, per-write durability and the overhead of\n * individual KV writes is acceptable — for example, when seeding a small number\n * of files. For bulk write workloads, prefer `DurableObjectKVFileSystem`, which\n * batches all writes into a single flush.\n */\nexport class DurableObjectRawFileSystem implements FileSystem {\n /**\n * @param storage The Durable Object storage instance to persist files to.\n * @param prefix An optional path prefix prepended to every key stored in KV.\n * Defaults to `\"bundle/\"`, which namespaces bundle files away\n * from any other keys the Durable Object may store.\n */\n constructor(\n private readonly storage: DurableObjectStorage,\n private readonly prefix: string = \"bundle/\"\n ) {}\n\n read(path: string): string | null {\n return this.storage.kv.get<string>(this.formatPath(path)) ?? null;\n }\n\n write(path: string, content: string): void {\n this.storage.kv.put(this.formatPath(path), content);\n }\n\n delete(path: string): void {\n this.storage.kv.delete(this.formatPath(path));\n }\n\n list(prefix?: string): string[] {\n const formattedPrefix =\n prefix !== undefined ? this.formatPath(prefix) : this.prefix;\n // kv.list() returns Iterable<[key, value]>. Strip the storage prefix from\n // each key so callers always receive logical paths, consistent with\n // InMemoryFileSystem.list().\n const result: string[] = [];\n for (const [key] of this.storage.kv.list({ prefix: formattedPrefix })) {\n result.push(key.slice(this.prefix.length));\n }\n return result;\n }\n\n flush(): Promise<void> {\n return Promise.resolve();\n }\n\n private formatPath(path: string): string {\n return `${this.prefix}${path}`;\n }\n}\n\n/**\n * A filesystem backed by Durable Object KV storage with a write-overlay.\n * Writes are buffered in memory and only persisted to KV when `flush()` is\n * called, avoiding the cost of a KV write on every individual file operation.\n * Reads are served from the overlay when possible, falling back to KV, so\n * callers always observe their own writes immediately.\n *\n * Implemented as an `OverlayFileSystem` wrapping a `DurableObjectRawFileSystem`.\n * Use `DurableObjectRawFileSystem` directly if you want immediate per-write KV\n * durability without buffering.\n */\nexport class DurableObjectKVFileSystem implements FileSystem {\n private readonly fs: OverlayFileSystem;\n\n /**\n * @param storage The Durable Object storage instance to persist files to.\n * @param prefix An optional path prefix prepended to every key stored in KV.\n * Defaults to `\"bundle/\"`, which namespaces bundle files away\n * from any other keys the Durable Object may store.\n */\n constructor(storage: DurableObjectStorage, prefix: string = \"bundle/\") {\n this.fs = new OverlayFileSystem(\n new DurableObjectRawFileSystem(storage, prefix)\n );\n }\n\n read(path: string): string | null {\n return this.fs.read(path);\n }\n\n write(path: string, content: string): void {\n this.fs.write(path, content);\n }\n\n delete(path: string): void {\n this.fs.delete(path);\n }\n\n list(prefix?: string): string[] {\n return this.fs.list(prefix);\n }\n\n flush(): Promise<void> {\n return this.fs.flush();\n }\n}\n\n/**\n * Creates an `InMemoryFileSystem` from an async source of file entries.\n *\n * This is the bridge between async storage backends (e.g. a Durable Object\n * `Workspace` backed by SQLite/R2) and the synchronous `FileSystem` interface\n * required by the bundler and TypeScript language service.\n *\n * @example\n * ```ts\n * // Snapshot a Workspace into a bundler-compatible FileSystem\n * async function* workspaceFiles(workspace) {\n * for (const entry of workspace.glob(\"**\\/*.{ts,tsx,json}\")) {\n * const content = await workspace.readFile(entry.path);\n * if (content !== null) yield [entry.path, content];\n * }\n * }\n *\n * const fs = await createFileSystemSnapshot(workspaceFiles(workspace));\n * const { languageService } = await createTypescriptLanguageService({ fileSystem: fs });\n * ```\n */\nexport async function createFileSystemSnapshot(\n entries:\n | AsyncIterable<readonly [string, string]>\n | Iterable<readonly [string, string]>\n): Promise<InMemoryFileSystem> {\n const fs = new InMemoryFileSystem();\n for await (const [path, content] of entries) {\n fs.write(path, content);\n }\n return fs;\n}\n\nexport function isFileSystem(\n obj: FileSystem | Record<string, string>\n): obj is FileSystem {\n return (\n \"read\" in obj &&\n typeof obj.read === \"function\" &&\n \"delete\" in obj &&\n typeof obj.delete === \"function\"\n );\n}\n\n// Python packages can contain both text and data entries\n// This type allows filesystem entries to properly support both in the way workerd wants to receive them\nexport type FileEntry = string | { data: Uint8Array<ArrayBuffer> };\n","/**\n * MIME type inference from file extensions.\n */\n\nconst MIME_TYPES: Record<string, string> = {\n // HTML\n \".html\": \"text/html; charset=utf-8\",\n \".htm\": \"text/html; charset=utf-8\",\n\n // JavaScript\n \".js\": \"application/javascript; charset=utf-8\",\n \".mjs\": \"application/javascript; charset=utf-8\",\n\n // CSS\n \".css\": \"text/css; charset=utf-8\",\n\n // JSON\n \".json\": \"application/json; charset=utf-8\",\n\n // Images\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".webp\": \"image/webp\",\n \".avif\": \"image/avif\",\n\n // Fonts\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".otf\": \"font/otf\",\n \".eot\": \"application/vnd.ms-fontobject\",\n\n // Media\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n \".webm\": \"video/webm\",\n \".ogg\": \"audio/ogg\",\n \".wav\": \"audio/wav\",\n\n // Documents\n \".pdf\": \"application/pdf\",\n \".xml\": \"application/xml\",\n \".txt\": \"text/plain; charset=utf-8\",\n \".csv\": \"text/csv; charset=utf-8\",\n\n // Archives\n \".zip\": \"application/zip\",\n \".gz\": \"application/gzip\",\n \".tar\": \"application/x-tar\",\n\n // WebAssembly\n \".wasm\": \"application/wasm\",\n\n // Manifest\n \".webmanifest\": \"application/manifest+json\",\n\n // Source maps\n \".map\": \"application/json\"\n};\n\n/**\n * Get the file extension from a path (including the dot).\n */\nfunction getExtension(path: string): string {\n const lastDot = path.lastIndexOf(\".\");\n if (lastDot === -1) return \"\";\n const lastSlash = path.lastIndexOf(\"/\");\n if (lastDot < lastSlash) return \"\";\n return path.slice(lastDot).toLowerCase();\n}\n\n/**\n * Infer MIME type from a file path.\n * Returns undefined if the type is unknown.\n */\nexport function inferContentType(path: string): string | undefined {\n const ext = getExtension(path);\n return MIME_TYPES[ext];\n}\n\n/**\n * Whether a content type represents a text-based format\n * (used to decide text vs binary module storage).\n */\nexport function isTextContentType(contentType: string): boolean {\n return (\n contentType.startsWith(\"text/\") ||\n contentType.includes(\"json\") ||\n contentType.includes(\"xml\") ||\n contentType.includes(\"javascript\") ||\n contentType.includes(\"svg\")\n );\n}\n","/**\n * Asset request handler for serving static assets.\n *\n * Key design: the manifest (routing metadata) is separated from the\n * storage (content retrieval). This lets you plug in any backend —\n * in-memory, KV, R2, Workspace, etc.\n *\n * Inspired by Cloudflare's Workers Static Assets behavior and\n * cloudflare-asset-worker by Timo Wilhelm.\n */\n\nimport { inferContentType } from \"./mime\";\n\n// ── Storage interface ───────────────────────────────────────────────\n\n/**\n * Pluggable storage backend for asset content.\n * Implement this to serve assets from KV, R2, Workspace, or any other source.\n */\nexport interface AssetStorage {\n get(pathname: string): Promise<ReadableStream | ArrayBuffer | string | null>;\n}\n\n/**\n * Metadata for a single asset (no content — that comes from storage).\n */\nexport interface AssetMetadata {\n contentType: string | undefined;\n etag: string;\n}\n\n/**\n * The manifest maps pathnames to metadata. Used for routing decisions,\n * ETag checks, and content-type headers — all without touching storage.\n */\nexport type AssetManifest = Map<string, AssetMetadata>;\n\n/**\n * Create an in-memory storage backend from a pathname->content map.\n * This is the zero-config default for small asset sets.\n */\nexport function createMemoryStorage(\n assets: Record<string, string | ArrayBuffer>\n): AssetStorage {\n const map = new Map(Object.entries(assets));\n return {\n get(pathname) {\n return Promise.resolve(map.get(pathname) ?? null);\n }\n };\n}\n\n// ── Configuration ───────────────────────────────────────────────────\n\n/**\n * Configuration for asset serving behavior.\n */\nexport interface AssetConfig {\n /**\n * How to handle HTML file resolution and trailing slashes.\n * @default 'auto-trailing-slash'\n */\n html_handling?:\n | \"auto-trailing-slash\"\n | \"force-trailing-slash\"\n | \"drop-trailing-slash\"\n | \"none\";\n\n /**\n * How to handle requests that don't match any asset.\n * - 'single-page-application': Serve /index.html for 404s\n * - '404-page': Serve nearest 404.html walking up the directory tree\n * - 'none': Return null (fall through)\n * @default 'none'\n */\n not_found_handling?: \"single-page-application\" | \"404-page\" | \"none\";\n\n /**\n * Static redirect rules. Keys are URL pathnames (or https://host/path for cross-host).\n * Supports * glob and :placeholder tokens.\n */\n redirects?: {\n static?: Record<string, { status: number; to: string }>;\n dynamic?: Record<string, { status: number; to: string }>;\n };\n\n /**\n * Custom response headers per pathname pattern (glob syntax).\n */\n headers?: Record<string, { set?: Record<string, string>; unset?: string[] }>;\n}\n\n/**\n * Normalized configuration with all fields required.\n */\ninterface NormalizedConfig {\n html_handling:\n | \"auto-trailing-slash\"\n | \"force-trailing-slash\"\n | \"drop-trailing-slash\"\n | \"none\";\n not_found_handling: \"single-page-application\" | \"404-page\" | \"none\";\n redirects: {\n static: Record<string, { status: number; to: string; lineNumber: number }>;\n dynamic: Record<string, { status: number; to: string }>;\n };\n headers: Record<string, { set?: Record<string, string>; unset?: string[] }>;\n}\n\n/**\n * Normalize user config with defaults.\n */\nexport function normalizeConfig(config?: AssetConfig): NormalizedConfig {\n const staticRedirects: Record<\n string,\n { status: number; to: string; lineNumber: number }\n > = {};\n if (config?.redirects?.static) {\n let lineNumber = 1;\n for (const [path, rule] of Object.entries(config.redirects.static)) {\n staticRedirects[path] = { ...rule, lineNumber: lineNumber++ };\n }\n }\n\n return {\n html_handling: config?.html_handling ?? \"auto-trailing-slash\",\n not_found_handling: config?.not_found_handling ?? \"none\",\n redirects: {\n static: staticRedirects,\n dynamic: config?.redirects?.dynamic ?? {}\n },\n headers: config?.headers ?? {}\n };\n}\n\n// ── ETag / manifest building ────────────────────────────────────────\n\n/**\n * Compute a simple hash for ETag generation.\n * Uses a fast string hash (FNV-1a) for text, or SHA-256 for binary.\n */\nexport async function computeETag(\n content: string | ArrayBuffer\n): Promise<string> {\n if (typeof content === \"string\") {\n // FNV-1a hash for fast text hashing\n let hash = 2166136261;\n for (let i = 0; i < content.length; i++) {\n hash ^= content.charCodeAt(i);\n hash = (hash * 16777619) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n }\n // SHA-256 for binary\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", content);\n const hashArray = new Uint8Array(hashBuffer);\n return [...hashArray.slice(0, 8)]\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Build an AssetManifest from a pathname->content mapping.\n * Only computes metadata (content types, ETags) — doesn't store content.\n */\nexport async function buildAssetManifest(\n assets: Record<string, string | ArrayBuffer>\n): Promise<AssetManifest> {\n const manifest: AssetManifest = new Map();\n const entries = Object.entries(assets);\n await Promise.all(\n entries.map(async ([pathname, content]) => {\n const contentType = inferContentType(pathname);\n const etag = await computeETag(content);\n manifest.set(pathname, { contentType, etag });\n })\n );\n return manifest;\n}\n\n/**\n * Convenience: build both a manifest and an in-memory storage from assets.\n */\nexport async function buildAssets(\n assets: Record<string, string | ArrayBuffer>\n): Promise<{ manifest: AssetManifest; storage: AssetStorage }> {\n const manifest = await buildAssetManifest(assets);\n const storage = createMemoryStorage(assets);\n return { manifest, storage };\n}\n\n/**\n * Check if a pathname exists in the manifest.\n */\nfunction exists(\n manifest: AssetManifest,\n pathname: string\n): AssetMetadata | undefined {\n return manifest.get(pathname);\n}\n\n// ── Redirect handling ───────────────────────────────────────────────\n\nconst ESCAPE_REGEX_CHARACTERS = /[-/\\\\^$*+?.()|[\\]{}]/g;\nconst escapeRegex = (s: string) =>\n s.replaceAll(ESCAPE_REGEX_CHARACTERS, String.raw`\\$&`);\n\nconst PLACEHOLDER_REGEX = /:([A-Za-z]\\w*)/g;\n\ntype Replacements = Record<string, string>;\n\nfunction replacer(str: string, replacements: Replacements): string {\n for (const [key, value] of Object.entries(replacements)) {\n str = str.replaceAll(`:${key}`, value);\n }\n return str;\n}\n\nfunction generateRuleRegExp(rule: string): RegExp {\n rule = rule\n .split(\"*\")\n .map((s) => escapeRegex(s))\n .join(\"(?<splat>.*)\");\n\n const matches = rule.matchAll(PLACEHOLDER_REGEX);\n for (const match of matches) {\n rule = rule.split(match[0]).join(`(?<${match[1]}>[^/]+)`);\n }\n\n return new RegExp(\"^\" + rule + \"$\");\n}\n\nfunction matchStaticRedirects(\n config: NormalizedConfig,\n host: string,\n pathname: string\n): { status: number; to: string; lineNumber: number } | undefined {\n const withHost = config.redirects.static[`https://${host}${pathname}`];\n const withoutHost = config.redirects.static[pathname];\n if (withHost && withoutHost) {\n return withHost.lineNumber < withoutHost.lineNumber\n ? withHost\n : withoutHost;\n }\n return withHost || withoutHost;\n}\n\nfunction matchDynamicRedirects(\n config: NormalizedConfig,\n request: Request\n): { status: number; to: string } | undefined {\n const { pathname } = new URL(request.url);\n for (const [pattern, rule] of Object.entries(config.redirects.dynamic)) {\n try {\n const re = generateRuleRegExp(pattern);\n const result = re.exec(pathname);\n if (result) {\n const target = replacer(rule.to, result.groups || {}).trim();\n return { status: rule.status, to: target };\n }\n } catch {\n // Skip invalid patterns\n }\n }\n return undefined;\n}\n\nfunction handleRedirects(\n request: Request,\n config: NormalizedConfig\n): Response | { proxied: boolean; pathname: string } {\n const url = new URL(request.url);\n const { search, host } = url;\n let { pathname } = url;\n\n const staticMatch = matchStaticRedirects(config, host, pathname);\n const dynamicMatch = staticMatch\n ? undefined\n : matchDynamicRedirects(config, request);\n const match = staticMatch ?? dynamicMatch;\n\n let proxied = false;\n if (match) {\n if (match.status === 200) {\n pathname = new URL(match.to, request.url).pathname;\n proxied = true;\n } else {\n const destination = new URL(match.to, request.url);\n const location =\n destination.origin === url.origin\n ? `${destination.pathname}${destination.search || search}${destination.hash}`\n : `${destination.href}`;\n return new Response(null, {\n status: match.status,\n headers: { Location: location }\n });\n }\n }\n\n return { proxied, pathname };\n}\n\n// ── Custom headers ──────────────────────────────────────────────────\n\nfunction generateGlobRegExp(pattern: string): RegExp {\n const escaped = pattern\n .split(\"*\")\n .map((s) => escapeRegex(s))\n .join(\".*\");\n return new RegExp(\"^\" + escaped + \"$\");\n}\n\nfunction attachCustomHeaders(\n request: Request,\n response: Response,\n config: NormalizedConfig\n): Response {\n if (Object.keys(config.headers).length === 0) {\n return response;\n }\n\n const { pathname } = new URL(request.url);\n const setMap = new Set<string>();\n\n for (const [pattern, rules] of Object.entries(config.headers)) {\n try {\n const re = generateGlobRegExp(pattern);\n if (!re.test(pathname)) continue;\n } catch {\n continue;\n }\n\n if (rules.unset) {\n for (const key of rules.unset) {\n response.headers.delete(key);\n }\n }\n if (rules.set) {\n for (const [key, value] of Object.entries(rules.set)) {\n if (setMap.has(key.toLowerCase())) {\n response.headers.append(key, value);\n } else {\n response.headers.set(key, value);\n setMap.add(key.toLowerCase());\n }\n }\n }\n }\n\n return response;\n}\n\n// ── Path decoding / encoding ────────────────────────────────────────\n\nfunction decodePath(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n })\n .join(\"/\")\n .replaceAll(/\\/+/g, \"/\");\n}\n\nfunction encodePath(pathname: string): string {\n return pathname\n .split(\"/\")\n .map((segment) => {\n try {\n return encodeURIComponent(segment);\n } catch {\n return segment;\n }\n })\n .join(\"/\");\n}\n\n// ── HTML handling modes ─────────────────────────────────────────────\n\ntype Intent =\n | { type: \"asset\"; pathname: string; meta: AssetMetadata; status: number }\n | { type: \"redirect\"; to: string }\n | undefined;\n\nfunction getIntent(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects = false,\n acceptsHtml = true\n): Intent {\n switch (config.html_handling) {\n case \"auto-trailing-slash\":\n return htmlAutoTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"force-trailing-slash\":\n return htmlForceTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"drop-trailing-slash\":\n return htmlDropTrailingSlash(\n pathname,\n manifest,\n config,\n skipRedirects,\n acceptsHtml\n );\n case \"none\":\n return htmlNone(pathname, manifest, config, acceptsHtml);\n }\n}\n\nfunction assetIntent(\n pathname: string,\n meta: AssetMetadata,\n status = 200\n): Intent {\n return { type: \"asset\", pathname, meta, status };\n}\n\nfunction redirectIntent(to: string): Intent {\n return { type: \"redirect\", to };\n}\n\n/**\n * Safe redirect: only redirect if the file exists and the destination\n * itself resolves to the same asset (avoids redirect loops).\n */\nfunction safeRedirect(\n file: string,\n destination: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skip: boolean\n): Intent {\n if (skip) return undefined;\n if (!exists(manifest, destination)) {\n const intent = getIntent(destination, manifest, config, true);\n if (\n intent?.type === \"asset\" &&\n intent.meta.etag === exists(manifest, file)?.etag\n ) {\n return redirectIntent(destination);\n }\n }\n return undefined;\n}\n\nfunction htmlAutoTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) {\n return assetIntent(pathname, exactMeta);\n }\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/index.html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/\")) {\n const indexPath = `${pathname}index.html`;\n if ((meta = exists(manifest, indexPath))) {\n return assetIntent(indexPath, meta);\n }\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n // Exact match\n if (exactMeta) {\n return assetIntent(pathname, exactMeta);\n }\n // Try .html extension\n const htmlPath = `${pathname}.html`;\n if ((meta = exists(manifest, htmlPath))) {\n return assetIntent(htmlPath, meta);\n }\n // Try /index.html\n if (\n (redirect = safeRedirect(\n `${pathname}/index.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlForceTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/index.html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else if (pathname.endsWith(\"/\")) {\n let p = `${pathname}index.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n p = `${pathname.slice(0, -\"/\".length)}.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n `${pathname.slice(0, -\".html\".length)}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname}/index.html`,\n `${pathname}/`,\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlDropTrailingSlash(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n skipRedirects: boolean,\n acceptsHtml: boolean\n): Intent {\n let meta: AssetMetadata | undefined;\n let redirect: Intent;\n const exactMeta = exists(manifest, pathname);\n\n if (pathname.endsWith(\"/index\")) {\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (pathname === \"/index\") {\n if (\n (redirect = safeRedirect(\n \"/index.html\",\n \"/\",\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else {\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index\".length)}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname}.html`,\n pathname.slice(0, -\"/index\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\"/index.html\")) {\n if (pathname === \"/index.html\") {\n if (\n (redirect = safeRedirect(\n \"/index.html\",\n \"/\",\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n } else {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (exactMeta) return assetIntent(pathname, exactMeta);\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/index.html\".length)}.html`,\n pathname.slice(0, -\"/index.html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\"/\")) {\n if (pathname === \"/\") {\n if ((meta = exists(manifest, \"/index.html\"))) {\n return assetIntent(\"/index.html\", meta);\n }\n } else {\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\"/\".length)}/index.html`,\n pathname.slice(0, -\"/\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n } else if (pathname.endsWith(\".html\")) {\n if (\n (redirect = safeRedirect(\n pathname,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n if (\n (redirect = safeRedirect(\n `${pathname.slice(0, -\".html\".length)}/index.html`,\n pathname.slice(0, -\".html\".length),\n manifest,\n config,\n skipRedirects\n ))\n )\n return redirect;\n }\n\n if (exactMeta) return assetIntent(pathname, exactMeta);\n let p = `${pathname}.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n p = `${pathname}/index.html`;\n if ((meta = exists(manifest, p))) {\n return assetIntent(p, meta);\n }\n\n return notFound(pathname, manifest, config, acceptsHtml);\n}\n\nfunction htmlNone(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n acceptsHtml: boolean\n): Intent {\n const meta = exists(manifest, pathname);\n return meta\n ? assetIntent(pathname, meta)\n : notFound(pathname, manifest, config, acceptsHtml);\n}\n\n// ── Not-found handling ──────────────────────────────────────────────\n\nfunction notFound(\n pathname: string,\n manifest: AssetManifest,\n config: NormalizedConfig,\n acceptsHtml = true\n): Intent {\n switch (config.not_found_handling) {\n case \"single-page-application\": {\n // Only serve the SPA fallback for requests that accept HTML\n // (browser navigation). API calls (Accept: */* or application/json)\n // should fall through to the user's server code.\n if (!acceptsHtml) return undefined;\n const meta = exists(manifest, \"/index.html\");\n if (meta) return assetIntent(\"/index.html\", meta, 200);\n return undefined;\n }\n case \"404-page\": {\n let cwd = pathname;\n while (cwd) {\n cwd = cwd.slice(0, cwd.lastIndexOf(\"/\"));\n const p = `${cwd}/404.html`;\n const meta = exists(manifest, p);\n if (meta) return assetIntent(p, meta, 404);\n }\n return undefined;\n }\n default:\n return undefined;\n }\n}\n\n// ── Cache headers ───────────────────────────────────────────────────\n\nconst CACHE_CONTROL_REVALIDATE = \"public, max-age=0, must-revalidate\";\nconst CACHE_CONTROL_IMMUTABLE = \"public, max-age=31536000, immutable\";\n\nfunction getCacheControl(pathname: string): string {\n // Hashed assets (contain content hash in filename) get long-lived caching\n // Common patterns: app.abc123.js, styles.abc123.css, image.abc123.png\n if (/\\.[a-f0-9]{8,}\\.\\w+$/.test(pathname)) {\n return CACHE_CONTROL_IMMUTABLE;\n }\n return CACHE_CONTROL_REVALIDATE;\n}\n\n// ── Main handler ────────────────────────────────────────────────────\n\n/**\n * Handle an asset request. Returns a Response if an asset matches,\n * or null if the request should fall through to the user's Worker.\n *\n * @param request - The incoming HTTP request\n * @param manifest - Asset manifest (pathname -> metadata)\n * @param storage - Storage backend for fetching content\n * @param config - Asset serving configuration\n */\nexport async function handleAssetRequest(\n request: Request,\n manifest: AssetManifest,\n storage: AssetStorage,\n config?: AssetConfig\n): Promise<Response | null> {\n const normalized = normalizeConfig(config);\n\n // Only handle GET and HEAD\n const method = request.method.toUpperCase();\n if (![\"GET\", \"HEAD\"].includes(method)) {\n return null;\n }\n\n // Check redirects first\n const redirectResult = handleRedirects(request, normalized);\n if (redirectResult instanceof Response) {\n return attachCustomHeaders(request, redirectResult, normalized);\n }\n\n const { pathname } = redirectResult;\n const decodedPathname = decodePath(pathname);\n\n // SPA fallback should only apply to navigation requests that explicitly\n // accept HTML, not to API calls (fetch/XHR) which have Accept: */*\n const accept = request.headers.get(\"Accept\") || \"\";\n const acceptsHtml = accept.includes(\"text/html\");\n\n // Resolve intent through HTML handling\n const intent = getIntent(\n decodedPathname,\n manifest,\n normalized,\n false,\n acceptsHtml\n );\n\n if (!intent) {\n return null;\n }\n\n if (intent.type === \"redirect\") {\n const url = new URL(request.url);\n const encodedDest = encodePath(intent.to);\n const response = new Response(null, {\n status: 307,\n headers: { Location: encodedDest + url.search }\n });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // Check if canonical path differs (needs redirect)\n const encodedPathname = encodePath(decodedPathname);\n if (encodedPathname !== pathname) {\n const url = new URL(request.url);\n const response = new Response(null, {\n status: 307,\n headers: { Location: encodedPathname + url.search }\n });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // ETag conditional request\n const { pathname: assetPath, meta, status } = intent;\n const strongETag = `\"${meta.etag}\"`;\n const weakETag = `W/${strongETag}`;\n const ifNoneMatch = request.headers.get(\"If-None-Match\") || \"\";\n const eTags = new Set(ifNoneMatch.split(\",\").map((t) => t.trim()));\n\n const headers = new Headers();\n headers.set(\"ETag\", strongETag);\n if (meta.contentType) {\n headers.set(\"Content-Type\", meta.contentType);\n }\n headers.set(\"Cache-Control\", getCacheControl(decodedPathname));\n\n if (eTags.has(weakETag) || eTags.has(strongETag)) {\n const response = new Response(null, { status: 304, headers });\n return attachCustomHeaders(request, response, normalized);\n }\n\n // Fetch content from storage (only for non-HEAD)\n let body: ReadableStream | ArrayBuffer | string | null = null;\n if (method !== \"HEAD\") {\n body = await storage.get(assetPath);\n }\n\n const response = new Response(body, { status, headers });\n return attachCustomHeaders(request, response, normalized);\n}\n","/**\n * App bundler: builds a full-stack app (server Worker + client bundle + static assets)\n * for the Worker Loader binding.\n *\n * Assets are returned separately for the host to serve — they are NOT embedded\n * in the dynamic isolate. The caller uses handleAssetRequest() on the host side\n * and only forwards non-asset requests to the isolate.\n */\n\nimport { bundleWithEsbuild, bundlerOnlyOptionsWarning } from \"./bundler\";\nimport { hasNodejsCompat, parseWranglerConfig } from \"./config\";\nimport { hasDependencies, installDependencies } from \"./installer\";\nimport { transformAndResolve } from \"./transformer\";\nimport type { AssetConfig, AssetManifest } from \"./asset-handler\";\nimport { buildAssetManifest } from \"./asset-handler\";\nimport type {\n BundlerLoader,\n CreateWorkerResult,\n Files,\n JsxMode\n} from \"./types\";\nimport {\n InMemoryFileSystem,\n isFileSystem,\n type FileSystem\n} from \"./file-system\";\nimport {\n DEFAULT_ENTRY_POINTS,\n detectEntryPoint,\n formatFileListForError\n} from \"./utils\";\nimport { showExperimentalWarning } from \"./experimental\";\n\n/**\n * Options for createApp\n */\nexport interface CreateAppOptions {\n /**\n * Input files — keys are paths relative to project root, values are file contents.\n * Accepts a plain object (which is wrapped in an InMemoryFileSystem automatically)\n * or any FileSystem implementation for custom storage backends.\n */\n files: Files | FileSystem;\n\n /**\n * Server entry point (the Worker fetch handler).\n * If not specified, detected from wrangler config / package.json / defaults.\n */\n server?: string;\n\n /**\n * Client entry point(s) to bundle for the browser.\n * These are bundled with esbuild targeting the browser.\n */\n client?: string | string[];\n\n /**\n * Static assets to serve as-is (pathname -> content).\n * Keys should be URL pathnames (e.g., \"/favicon.ico\", \"/robots.txt\").\n * These are NOT processed by the bundler.\n */\n assets?: Record<string, string | ArrayBuffer>;\n\n /**\n * Asset serving configuration.\n */\n assetConfig?: AssetConfig;\n\n /**\n * Whether to bundle server dependencies.\n * @default true\n */\n bundle?: boolean;\n\n /**\n * External modules that should not be bundled.\n */\n externals?: string[];\n\n /**\n * Target environment for server bundle.\n * @default 'es2022'\n */\n target?: string;\n\n /**\n * Whether to minify the output.\n * @default false\n */\n minify?: boolean;\n\n /**\n * Generate source maps.\n * @default false\n */\n sourcemap?: boolean;\n\n /**\n * npm registry URL for fetching packages.\n */\n registry?: string;\n\n /**\n * JSX transform mode passed to esbuild. Applied to both server and client\n * bundles.\n */\n jsx?: JsxMode;\n\n /**\n * Module to import the JSX runtime from when `jsx: \"automatic\"`.\n */\n jsxImportSource?: string;\n\n /**\n * Constant replacements applied at bundle time. Applied to both server and\n * client bundles.\n */\n define?: Record<string, string>;\n\n /**\n * Per-extension loader overrides. Applied to both server and client bundles.\n */\n loader?: Record<string, BundlerLoader>;\n\n /**\n * Package export conditions to honour during resolution.\n * Applied to both server and client bundles (the host can pass e.g.\n * `[\"worker\", \"browser\"]` for the client, but most users want a single\n * shared set).\n */\n conditions?: string[];\n\n /**\n * Escape hatch for advanced users: extra esbuild plugins to run **before**\n * the bundler's internal virtual-filesystem plugin. Applied to both server\n * and client bundles.\n *\n * The deliberately unwieldy name is the API contract:\n *\n * - This option is **not** covered by semver. It can change shape, be\n * renamed, or be removed in any release.\n * - The runtime ties you to esbuild. If this package switches bundlers\n * (e.g. to rolldown), plugins authored against this API will break.\n *\n * Typed as `unknown[]` at the public boundary to keep `esbuild-wasm` types\n * out of the published `.d.ts`. Cast your plugin array to `unknown[]` when\n * passing it in. Each element is validated at runtime: it must be an object\n * with `name: string` and `setup: (build) => void`.\n *\n * On the server side, only applies when `bundle: true`; transform-only mode\n * surfaces a warning instead. Always applies to client bundles.\n */\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired?: unknown[];\n}\n\n/**\n * Result from createApp\n */\nexport interface CreateAppResult extends CreateWorkerResult {\n /**\n * Combined assets (user-provided + client bundles) for host-side serving.\n * The host should use createMemoryStorage(assets) and handleAssetRequest()\n * to serve these before forwarding requests to the isolate.\n */\n assets: Record<string, string | ArrayBuffer>;\n\n /**\n * The asset manifest for runtime request handling.\n * Contains metadata (content types, ETags) for each asset.\n */\n assetManifest: AssetManifest;\n\n /**\n * The asset config for runtime request handling.\n */\n assetConfig?: AssetConfig;\n\n /**\n * Client bundle output paths (relative to asset root).\n */\n clientBundles?: string[];\n}\n\n/**\n * Creates a full-stack app bundle from source files.\n *\n * This function:\n * 1. Bundles client entry point(s) for the browser (if provided)\n * 2. Collects static assets and builds the asset manifest\n * 3. Bundles the server Worker\n * 4. Returns server modules (for the isolate) and assets (for host-side serving) separately\n *\n * How the output is mounted (module worker, DO class, facet) is the caller's concern.\n */\nexport async function createApp(\n options: CreateAppOptions\n): Promise<CreateAppResult> {\n showExperimentalWarning(\"createApp\");\n const {\n files,\n bundle = true,\n externals: rawExternals = [],\n target = \"es2022\",\n minify = false,\n sourcemap = false,\n registry,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins\n } = options;\n\n const fileSystem: FileSystem = isFileSystem(files)\n ? files\n : new InMemoryFileSystem(files);\n\n // Always treat cloudflare:* as external\n const externals = [\"cloudflare:\", ...rawExternals];\n\n // Parse wrangler config\n const wranglerConfig = parseWranglerConfig(fileSystem);\n const nodejsCompat = hasNodejsCompat(wranglerConfig);\n\n // Install npm dependencies if needed\n const installWarnings: string[] = [];\n if (hasDependencies(fileSystem)) {\n const installResult = await installDependencies(fileSystem, {\n ...(registry ? { registry } : {})\n });\n installWarnings.push(...installResult.warnings);\n }\n\n // ── Step 1: Build client bundles ──────────────────────────────────\n const clientEntries = options.client\n ? Array.isArray(options.client)\n ? options.client\n : [options.client]\n : [];\n\n const clientOutputs: Record<string, string> = {};\n const clientBundles: string[] = [];\n\n for (const clientEntry of clientEntries) {\n if (fileSystem.read(clientEntry) === null) {\n throw new Error(\n `Client entry point \"${clientEntry}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n const clientResult = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint: clientEntry,\n externals,\n target: \"es2022\",\n minify,\n sourcemap,\n nodejsCompat: false,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n\n const bundleModule = clientResult.modules[\"bundle.js\"];\n if (typeof bundleModule === \"string\") {\n const baseName = clientEntry\n .replace(/^src\\//, \"\")\n .replace(/\\.(tsx?|jsx?)$/, \".js\");\n const outputPath = `/${baseName}`;\n clientOutputs[outputPath] = bundleModule;\n clientBundles.push(outputPath);\n }\n }\n\n // ── Step 2: Collect all assets ────────────────────────────────────\n const allAssets: Record<string, string | ArrayBuffer> = {};\n\n if (options.assets) {\n for (const [pathname, content] of Object.entries(options.assets)) {\n const normalizedPath = pathname.startsWith(\"/\")\n ? pathname\n : `/${pathname}`;\n allAssets[normalizedPath] = content;\n }\n }\n\n for (const [pathname, content] of Object.entries(clientOutputs)) {\n allAssets[pathname] = content;\n }\n\n const assetManifest = await buildAssetManifest(allAssets);\n\n // ── Step 3: Build server Worker ───────────────────────────────────\n const serverEntry =\n options.server ?? detectEntryPoint(fileSystem, wranglerConfig);\n\n if (!serverEntry) {\n throw new Error(\n `Could not determine server entry point for createApp. Tried (in order): the \\`server\\` option, \\`main\\` in wrangler config, \\`exports\\`/\\`module\\`/\\`main\\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(\", \")}. Pass \\`server\\` explicitly or add one of those files.`\n );\n }\n\n if (fileSystem.read(serverEntry) === null) {\n throw new Error(\n `Server entry point \"${serverEntry}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n let serverResult: CreateWorkerResult;\n if (bundle) {\n serverResult = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint: serverEntry,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n } else {\n // Transform-only mode never invokes esbuild, so any bundler-only options\n // are silently inactive — surface that as a warning the caller can see.\n serverResult = await transformAndResolve(\n fileSystem,\n serverEntry,\n externals\n );\n\n const bundlerOnly = bundlerOnlyOptionsWarning({\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n plugins\n });\n if (bundlerOnly) {\n serverResult.warnings = [...(serverResult.warnings ?? []), bundlerOnly];\n }\n }\n\n const result: CreateAppResult = {\n mainModule: serverResult.mainModule,\n modules: serverResult.modules,\n assets: allAssets,\n assetManifest,\n assetConfig: options.assetConfig,\n clientBundles: clientBundles.length > 0 ? clientBundles : undefined\n };\n\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n if (installWarnings.length > 0) {\n result.warnings = [...(serverResult.warnings ?? []), ...installWarnings];\n } else if (serverResult.warnings) {\n result.warnings = serverResult.warnings;\n }\n\n return result;\n}\n","/**\n * Dynamic Worker Bundler\n *\n * Creates worker bundles from source files for Cloudflare's Worker Loader binding.\n */\n\nimport { bundleWithEsbuild, bundlerOnlyOptionsWarning } from \"./bundler\";\nimport { hasNodejsCompat, parseWranglerConfig } from \"./config\";\nimport { hasDependencies, installDependencies } from \"./installer\";\nimport { transformAndResolve } from \"./transformer\";\nimport type { CreateWorkerOptions, CreateWorkerResult, Modules } from \"./types\";\nimport {\n DEFAULT_ENTRY_POINTS,\n detectEntryPoint,\n formatFileListForError\n} from \"./utils\";\nimport { showExperimentalWarning } from \"./experimental\";\nimport {\n InMemoryFileSystem,\n isFileSystem,\n type FileSystem\n} from \"./file-system\";\n\n// Re-export types\nexport type {\n BundlerLoader,\n CreateWorkerOptions,\n CreateWorkerResult,\n Files,\n JsxMode,\n Modules,\n WranglerConfig\n} from \"./types\";\n\n// Re-export app bundler\nexport { createApp } from \"./app\";\nexport type { CreateAppOptions, CreateAppResult } from \"./app\";\n\n// Re-export asset handler\nexport {\n handleAssetRequest,\n buildAssetManifest,\n buildAssets,\n createMemoryStorage\n} from \"./asset-handler\";\nexport type {\n AssetConfig,\n AssetMetadata,\n AssetManifest,\n AssetStorage\n} from \"./asset-handler\";\n\n// Re-export MIME utilities\nexport { inferContentType, isTextContentType } from \"./mime\";\n\n// Re-export file-system\nexport {\n createFileSystemSnapshot,\n DurableObjectKVFileSystem,\n DurableObjectRawFileSystem,\n InMemoryFileSystem,\n type FileSystem\n} from \"./file-system\";\n\n// Re-export installer utilities\nexport { installDependencies, hasDependencies } from \"./installer\";\nexport type { InstallResult } from \"./common\";\n\n/**\n * Creates a worker bundle from source files.\n *\n * This function performs:\n * 1. Entry point detection (from package.json or defaults)\n * 2. Auto-installation of npm dependencies (if package.json has dependencies)\n * 3. TypeScript/JSX transformation (via Sucrase)\n * 4. Module resolution (handling imports/exports)\n * 5. Optional bundling (combining all modules into one)\n *\n * @param options - Configuration options\n * @returns The main module path and all modules\n */\nexport async function createWorker(\n options: CreateWorkerOptions\n): Promise<CreateWorkerResult> {\n showExperimentalWarning(\"createWorker\");\n let {\n files,\n bundle = true,\n externals = [],\n target = \"es2022\",\n minify = false,\n sourcemap = false,\n registry,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n __dangerouslyUseEsBuildPluginsDoNotUseOrYouWillBeFired: plugins\n } = options;\n\n let fileSystem: FileSystem;\n if (isFileSystem(files)) {\n fileSystem = files;\n } else {\n fileSystem = new InMemoryFileSystem(files);\n }\n\n // Always treat cloudflare:* modules as external (runtime-provided)\n externals = [\"cloudflare:\", ...externals];\n\n // Parse wrangler config for compatibility settings\n const wranglerConfig = parseWranglerConfig(fileSystem);\n const nodejsCompat = hasNodejsCompat(wranglerConfig);\n\n // Auto-install dependencies if package.json or pyproject.toml has dependencies\n const installWarnings: string[] = [];\n if (hasDependencies(fileSystem)) {\n const installResult = await installDependencies(fileSystem, {\n ...(registry ? { registry } : {})\n });\n installWarnings.push(...installResult.warnings);\n }\n\n // Detect entry point (priority: explicit option > wrangler main > package.json > defaults)\n const entryPoint =\n options.entryPoint ?? detectEntryPoint(fileSystem, wranglerConfig);\n\n if (!entryPoint) {\n throw new Error(\n `Could not determine entry point for createWorker. Tried (in order): the \\`entryPoint\\` option, \\`main\\` in wrangler config, \\`exports\\`/\\`module\\`/\\`main\\` in package.json, and the defaults ${DEFAULT_ENTRY_POINTS.join(\", \")}. Pass \\`entryPoint\\` explicitly or add one of those files.`\n );\n }\n\n if (fileSystem.read(entryPoint) === null) {\n throw new Error(\n `Entry point \"${entryPoint}\" was not found in \\`files\\`. Available files: ${formatFileListForError(fileSystem)}.`\n );\n }\n\n if (entryPoint.endsWith(\".py\")) {\n const modules: Modules = {};\n for (const path of fileSystem.list()) {\n if (path === \"pyproject.toml\") {\n continue;\n }\n const content = fileSystem.read(path);\n if (content !== null) {\n modules[path] = content;\n }\n }\n\n return {\n mainModule: entryPoint,\n modules,\n wranglerConfig: {\n compatibilityDate: wranglerConfig?.compatibilityDate ?? \"2026-07-02\",\n compatibilityFlags: wranglerConfig?.compatibilityFlags ?? []\n },\n warnings: installWarnings\n };\n }\n\n if (bundle) {\n // Try bundling with esbuild-wasm\n const result = await bundleWithEsbuild({\n files: fileSystem,\n entryPoint,\n externals,\n target,\n minify,\n sourcemap,\n nodejsCompat,\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n plugins\n });\n\n // Add wrangler config if a config file was found\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n // Add install warnings to result\n if (installWarnings.length > 0) {\n result.warnings = [...(result.warnings ?? []), ...installWarnings];\n }\n return result;\n } else {\n // No bundling - transform files and resolve dependencies.\n // Sourcemaps and the esbuild-only options (jsx, jsxImportSource, define,\n // loader, conditions, plugins) are not supported in transform mode — the\n // output mirrors the input structure and never touches esbuild.\n const result = await transformAndResolve(fileSystem, entryPoint, externals);\n\n const bundlerOnly = bundlerOnlyOptionsWarning({\n jsx,\n jsxImportSource,\n define,\n loader,\n conditions,\n virtualModules,\n plugins\n });\n\n // Add wrangler config if a config file was found\n if (wranglerConfig !== undefined) {\n result.wranglerConfig = wranglerConfig;\n }\n\n // Add install warnings to result\n const extraWarnings = [\n ...installWarnings,\n ...(bundlerOnly ? [bundlerOnly] : [])\n ];\n if (extraWarnings.length > 0) {\n result.warnings = [...(result.warnings ?? []), ...extraWarnings];\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;;;AAuCA,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;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CAAC,GAAI,OAAO,YAAY,CAAC,GAAI,GAAG,eAAe;EAEnE,OAAO;CACT,OAAO;EAKL,MAAM,SAAS,MAAM,oBAAoB,YAAY,YAAY,SAAS;EAE1E,MAAM,cAAc,0BAA0B;GAC5C;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC;EAGD,IAAI,mBAAmB,KAAA,GACrB,OAAO,iBAAiB;EAI1B,MAAM,gBAAgB,CACpB,GAAG,iBACH,GAAI,cAAc,CAAC,WAAW,IAAI,CAAC,CACrC;EACA,IAAI,cAAc,SAAS,GACzB,OAAO,WAAW,CAAC,GAAI,OAAO,YAAY,CAAC,GAAI,GAAG,aAAa;EAGjE,OAAO;CACT;AACF"}
|
|
@@ -186,7 +186,8 @@ function shouldInstallDependency(dependencySpecifier) {
|
|
|
186
186
|
function stripWheelToPackage(files) {
|
|
187
187
|
const result = {};
|
|
188
188
|
for (const [path, content] of Object.entries(files)) {
|
|
189
|
-
if (path.includes(".dist-info/")
|
|
189
|
+
if (path.includes(".dist-info/") && !path.endsWith(".dist-info/METADATA")) continue;
|
|
190
|
+
if (path.includes(".data/")) continue;
|
|
190
191
|
result[path] = content;
|
|
191
192
|
}
|
|
192
193
|
return result;
|
|
@@ -627,4 +628,4 @@ function hasDependencies(files) {
|
|
|
627
628
|
//#endregion
|
|
628
629
|
export { hasDependencies as n, installDependencies as r, fetchPackageFiles as t };
|
|
629
630
|
|
|
630
|
-
//# sourceMappingURL=installer-
|
|
631
|
+
//# sourceMappingURL=installer-Dzd--DQ7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"installer-Dzd--DQ7.js","names":["parseToml","parseToml"],"sources":["../src/common.ts","../src/installer-python.ts","../src/installer.ts"],"sourcesContent":["/*\n * File for imports common between multiple files, to avoid cyclic imports.\n */\n\nexport const DEFAULT_TIMEOUT_MS = 30000; // 30 seconds\n\nexport interface InstallResult {\n /**\n * Packages that were freshly installed in this call.\n * Packages already present in the filesystem are skipped and not listed here.\n */\n installed: string[];\n\n /**\n * Warnings encountered during installation\n */\n warnings: string[];\n}\n\n/**\n * Check if a file path is likely a text file.\n */\nexport function isTextFile(path: string): boolean {\n const textExtensions = [\n \".js\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".mts\",\n \".cts\",\n \".tsx\",\n \".jsx\",\n \".json\",\n \".md\",\n \".txt\",\n \".css\",\n \".html\",\n \".yml\",\n \".yaml\",\n \".toml\",\n \".xml\",\n \".svg\",\n \".map\",\n \".d.ts\",\n \".d.mts\",\n \".d.cts\",\n \".py\"\n ];\n\n // Check common config files without extensions\n const configFiles = [\n \"LICENSE\",\n \"README\",\n \"CHANGELOG\",\n \"package.json\",\n \"tsconfig.json\",\n \".npmignore\",\n \".gitignore\"\n ];\n\n const fileName = path.split(\"/\").pop() ?? \"\";\n\n if (\n configFiles.some((f) => fileName.toUpperCase().startsWith(f.toUpperCase()))\n ) {\n return true;\n }\n\n return textExtensions.some((ext) => path.toLowerCase().endsWith(ext));\n}\n\n/**\n * Fetch with a timeout.\n * Throws an error if the request takes longer than the specified timeout.\n */\nexport async function fetchWithTimeout(\n url: string,\n options: RequestInit = {},\n timeoutMs = DEFAULT_TIMEOUT_MS\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n return await fetch(url, { ...options, signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(\n `Request to ${url} timed out after ${timeoutMs}ms (npm registry slow or unreachable from this Worker)`\n );\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n","/*\n * Package resolution logic for Python dynamic workers\n */\n\nimport { isTextFile, fetchWithTimeout, DEFAULT_TIMEOUT_MS } from \"./common.ts\";\nimport type { InstallResult } from \"./common.ts\";\nimport type { FileSystem, FileEntry } from \"./file-system\";\nimport { unzipSync } from \"fflate\";\nimport { parse as parseToml } from \"smol-toml\";\n\n// TODO: Update PYODIDE_VERSION once the patch addressing the Python version mismatch for dynamic workers is merged\nconst PYODIDE_VERSION = \"v0.27.5\"; // Used for retrieving a pyodide lockfile, which is done per Pyodide version. If incompatible wheels are being served, this may be why\nconst PYPI_SIMPLE_API = \"https://pypi.org/simple\";\n\n// Deliberately keeping this minimal\nexport interface PyprojectToml {\n project?: {\n name: string;\n version: string;\n dependencies?: string[];\n };\n}\n\ninterface PyPASimpleFile {\n filename: string;\n url: string;\n hashes?: Record<string, string>;\n \"requires-python\"?: string;\n \"core-metadata\"?: boolean | { hash?: string; url?: string };\n yanked?: boolean | string;\n}\n\ninterface PyPASimpleMetadata {\n name: string;\n files: PyPASimpleFile[];\n}\n\n// Describes the packages that are available on the Pyodide CDN for a given Pyodide version\ninterface PyodideLockfile {\n info: {\n abi_version: string;\n arch: \"wasm32\";\n platform: string;\n python: string;\n version: string;\n };\n packages: Record<string, PyodideLockfilePackage>;\n}\n\ninterface PyodideLockfilePackage {\n name: string;\n version: string;\n file_name: string;\n sha256: string;\n package_type:\n | \"package\"\n | \"cpython_module\"\n | \"shared_library\"\n | \"static_library\";\n install_dir: \"site\" | \"dynlib\";\n imports: string[];\n depends: string[];\n}\n\ninterface PyodideWheelInfo {\n package: PyodideLockfilePackage;\n url: string;\n file: PyPASimpleFile;\n}\n\n// Making this global so it will only need to be fetched once per invocation\n// TODO: Consider caching this somewhere since it's not likely to change between runs\nlet pyodideLockfile: PyodideLockfile | null = null;\n\n/**\n * Install Python dependencies declared in a pyproject.toml file.\n */\nexport async function installDependenciesPython(\n fileSystem: FileSystem,\n pyprojectTomlContent: string\n): Promise<InstallResult> {\n const result: InstallResult = {\n installed: [],\n warnings: []\n };\n\n let pyprojectToml: PyprojectToml;\n try {\n pyprojectToml = parseToml(pyprojectTomlContent) as PyprojectToml;\n } catch {\n result.warnings.push(\"Failed to parse pyproject.toml\");\n return result;\n }\n\n // Collect dependencies to install. We will keep these as full dependency strings.\n const depsToInstall: string[] = pyprojectToml.project?.dependencies ?? [];\n depsToInstall.push(\"workers-runtime-sdk\");\n\n if (!pyodideLockfile) {\n try {\n pyodideLockfile = await fetchPyodideLockfile(PYODIDE_VERSION);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n result.warnings.push(\n `Could not retrieve Pyodide lockfile, attempts to retrieve packages from the Pyodide CDN may fail. Error: ${message}`\n );\n }\n }\n\n // Track installed packages to avoid duplicates\n const installedPackages = new Set<string>();\n // Track in-progress installations to avoid duplicate work\n const inProgress = new Map<string, Promise<void>>();\n\n // Install all dependencies in parallel\n await Promise.all(\n depsToInstall.map((dependencySpecifier) =>\n installPythonPackage(\n dependencySpecifier,\n result,\n fileSystem,\n installedPackages,\n inProgress,\n PYPI_SIMPLE_API\n )\n )\n );\n return result;\n}\n\n/**\n * Parse a Python version specifier string (PEP 508).\n * Currently only extracts the package name.\n */\nfunction parsePythonDependencySpecifier(spec: string): { name: string } {\n // Drop the PEP 508 environment marker (everything after `;`)\n let head = spec.split(\";\", 1)[0] ?? \"\";\n\n // The package name is the leading run of characters allowed in a PEP 508\n // identifier: letters, digits, `.`, `-`, `_`. Stop at the first character\n // that isn't one of those (whitespace, `[`, `(`, `<`, `>`, `=`, `!`, `~`, etc.).\n const match = head.match(/^\\s*([A-Za-z0-9][A-Za-z0-9._-]*)/);\n const name = match ? match[1]! : head.trim();\n\n return { name: name };\n}\n/**\n * Install a single Python package from the Pyodide index.\n * Uses PyPI as a fallback.\n */\nexport async function installPythonPackage(\n dependencySpecifier: string, // the full dependency specifier\n result: InstallResult,\n fileSystem: FileSystem,\n installedPackages: Set<string>,\n inProgress: Map<string, Promise<void>>,\n backupRegistry: string\n): Promise<void> {\n const name = parsePythonDependencySpecifier(dependencySpecifier)[\"name\"];\n // Skip if already installed in this run\n if (installedPackages.has(name)) {\n return;\n }\n\n if (!shouldInstallDependency(dependencySpecifier)) {\n return;\n }\n\n // We explicitly want to deal in names only here, not full dep strings. Only allowing one version of a package per Python environment is defined behavior\n // This was previously in installPromise, but was moved up upon observing that races could still lead to redundant fetches\n installedPackages.add(name);\n\n // TODO: In the JS impl., a check is done here for whether the package already exists in the filesystem\n // Assess in the future whether this is sensible to repeat\n\n // If installation is already in progress, wait for it\n const existing = inProgress.get(name);\n if (existing) {\n return existing;\n }\n\n const installPromise = (async () => {\n try {\n let response: Response = {} as Response;\n let wheel: PyPASimpleFile = {} as PyPASimpleFile;\n let version: string = \"\";\n\n // Try the Pyodide index first, then fall back to PyPI if that fails\n let registryResult = await retrieveFromPyodide(name);\n if (registryResult) {\n [response, wheel, version] = registryResult;\n } else {\n registryResult = await retrieveFromPyPI(name, backupRegistry);\n if (registryResult) {\n [response, wheel, version] = registryResult;\n } else {\n throw new Error(\n `Failed to download ${name}@${version}: ${response.status} ${response.statusText} (${wheel.url})`\n );\n }\n }\n const buffer = await response.arrayBuffer();\n\n const wheelContents = extractWheel(new Uint8Array(buffer));\n const dependencies = getDependenciesFromWheel(wheelContents);\n const packageFilesWheel = stripWheelToPackage(wheelContents);\n\n result.installed.push(`${name}@${version}`);\n\n // Add files to python_modules\n for (const [filePath, content] of Object.entries(packageFilesWheel)) {\n fileSystem.write(`python_modules/${filePath}`, content);\n }\n\n await Promise.all(\n dependencies.map((dep) =>\n installPythonPackage(\n dep,\n result,\n fileSystem,\n installedPackages,\n inProgress,\n PYPI_SIMPLE_API\n )\n )\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n result.warnings.push(`Failed to install ${name}: ${message}`);\n }\n })();\n\n inProgress.set(name, installPromise);\n\n try {\n await installPromise;\n } finally {\n inProgress.delete(name);\n }\n}\n\n// TODO: Genericize this to use the HTML version of this API and use it for both the Pyodide index and PyPI\nasync function retrieveFromPyPI(\n name: string,\n registry: string\n): Promise<[Response, PyPASimpleFile, string] | null> {\n const metadata = await fetchPythonPackageMetadata(name, registry);\n const version = metadata.version;\n const wheel = metadata.wheel;\n\n const response = await fetchWithTimeout(\n wheel.url,\n {},\n DEFAULT_TIMEOUT_MS * 2\n );\n\n if (!response.ok) {\n return null;\n }\n\n return [response, wheel, version];\n}\n\n// TODO: Alter the flow to use the PyPA simple api (index.pyodide.org)\nasync function retrieveFromPyodide(\n name: string\n): Promise<[Response, PyPASimpleFile, string] | null> {\n const pyodideWheel = getPyodideWheel(name);\n if (!pyodideWheel) {\n return null;\n }\n\n const response = await fetchWithTimeout(\n pyodideWheel.url,\n {},\n DEFAULT_TIMEOUT_MS * 2\n );\n if (!response.ok) {\n return null;\n }\n\n const version = pyodideWheel.package.version;\n const wheel = pyodideWheel.file;\n return [response, wheel, version];\n}\n\n// Determine whether a dependency (as listed in a wheel's METADATA) is appropriate to install\nfunction shouldInstallDependency(dependencySpecifier: string): boolean {\n // TODO: This should actually check whether extras are called for, as well as other environment and compatibility attributes\n // For the time being, it excludes any dependency that is behind an 'extra'\n const semicolonPos = dependencySpecifier.indexOf(\";\");\n if (\n semicolonPos > -1 &&\n (dependencySpecifier.substring(semicolonPos).includes(\"extra ==\") ||\n dependencySpecifier.substring(semicolonPos).includes(\"extra==\"))\n ) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Strip a Python wheel down to just the package contents.\n *\n * TODO: Re-review this function once we've cleared issues with file extension limits\n * in workerd; this function excludes certain metadata files in *.dist-info/ for now but it shouldn't remain this way\n */\nfunction stripWheelToPackage(\n files: Record<string, FileEntry>\n): Record<string, FileEntry> {\n const result: Record<string, FileEntry> = {};\n for (const [path, content] of Object.entries(files)) {\n // Keep each distribution's METADATA so importlib.metadata.version()\n // works; skip the rest of the wheel metadata and data directories.\n if (path.includes(\".dist-info/\") && !path.endsWith(\".dist-info/METADATA\")) {\n continue;\n }\n if (path.includes(\".data/\")) {\n continue;\n }\n // We'll expect that any remaining directories in the wheel are importable packages\n result[path] = content;\n }\n return result;\n}\n\n/**\n * Fetch the Pyodide lockfile for a given Pyodide version.\n *\n * The lockfile lists all pre-built packages available in the Pyodide\n * distribution, including their wheel URLs, hashes, and dependencies.\n */\nasync function fetchPyodideLockfile(\n version: string\n): Promise<PyodideLockfile | null> {\n const url = `https://cdn.jsdelivr.net/pyodide/${version}/full/pyodide-lock.json`;\n try {\n const response = await fetchWithTimeout(url);\n if (!response.ok) {\n return null;\n }\n return (await response.json()) as PyodideLockfile;\n } catch {\n return null;\n }\n}\n\n/**\n * Normalize a Python package name per PEP 503.\n *\n * Lowercases the name and collapses runs of `-`, `_`, and `.` into a single `-`.\n */\nfunction normalizePythonName(name: string): string {\n return name.toLowerCase().replace(/[-_.]+/g, \"-\");\n}\n\n/**\n * Look up a package in the loaded Pyodide lockfile and return the URL and a\n * Simple-API-shaped file entry for its wheel.\n *\n * Returns `null` if the lockfile is not loaded or the package is not present.\n */\nfunction getPyodideWheel(name: string): PyodideWheelInfo | null {\n if (!pyodideLockfile) return null;\n\n const normalizedName = normalizePythonName(name);\n const pkg = pyodideLockfile.packages[normalizedName];\n if (!pkg) return null;\n\n const baseUrl = `https://cdn.jsdelivr.net/pyodide/${PYODIDE_VERSION}/full`;\n const url = pkg.file_name.startsWith(\"http\")\n ? pkg.file_name\n : `${baseUrl}/${pkg.file_name}`;\n\n return {\n package: pkg,\n url,\n file: {\n filename: pkg.file_name,\n url,\n hashes: { sha256: pkg.sha256 }\n }\n };\n}\n\n/*\n * Fetch metadata about the 'name' package from 'registry' registry.\n * Expects the registry to support the PyPA Simple API (JSON ver)\n */\nasync function fetchPythonPackageMetadata(\n name: string,\n registry: string\n): Promise<{ version: string; wheel: PyPASimpleFile }> {\n const normalizedName = normalizePythonName(name);\n\n // Fetch package metadata from PyPI Simple API\n const metadataResponse = await fetchWithTimeout(\n `${registry}/${normalizedName}/`,\n {\n headers: {\n Accept: \"application/vnd.pypi.simple.v1+json\"\n }\n }\n );\n\n if (!metadataResponse.ok) {\n const hint =\n metadataResponse.status === 404\n ? \" (package not found — check the name in pyproject.toml)\"\n : \"\";\n throw new Error(\n `Registry ${registry} returned ${metadataResponse.status} ${metadataResponse.statusText} for \"${name}\"${hint}`\n );\n }\n const metadata = (await metadataResponse.json()) as PyPASimpleMetadata;\n\n const wheel = selectLatestCompatibleWheel(metadata.files);\n if (!wheel) {\n throw new Error(\n `No compatible wheel found for ${name} on registry ${registry}`\n );\n }\n\n const version = parseVersionFromWheelName(wheel.filename);\n if (!version) {\n throw new Error(\n `Could not parse version from wheel filename: ${wheel.filename}`\n );\n }\n\n return { version, wheel };\n}\n\n/**\n * Select a compatible wheel from PyPI Simple API files list.\n * Prefers py3-none-any or py2.py3-none-any wheels for maximum compatibility.\n * Selects the latest version from compatible wheels.\n * TODO: implement proper platform/python version matching\n */\nfunction selectLatestCompatibleWheel(\n files: PyPASimpleFile[]\n): PyPASimpleFile | null {\n const wheels = files.filter((f) => f.filename.endsWith(\".whl\"));\n if (wheels.length === 0) return null;\n\n // Filter to universal wheels (py3-none-any or py2.py3-none-any)\n const universal = wheels.filter(\n (w) =>\n w.filename.endsWith(\"-py3-none-any.whl\") ||\n w.filename.endsWith(\"-py2.py3-none-any.whl\")\n );\n\n const candidates = universal.length > 0 ? universal : wheels;\n\n // Select the wheel with the highest version\n let latest: PyPASimpleFile | null = null;\n let latestVersion: string | undefined;\n\n for (const wheel of candidates) {\n const version = parseVersionFromWheelName(wheel.filename);\n if (!version) continue;\n\n if (\n !latest ||\n !latestVersion ||\n comparePythonVersions(version, latestVersion) > 0\n ) {\n latest = wheel;\n latestVersion = version;\n }\n }\n\n return latest;\n}\n\n/**\n * Compare two PEP 440 version strings.\n * Returns >0 if a > b, <0 if a < b, 0 if equal.\n *\n * Python versions (PEP 440) are not semver-compatible (e.g. \"3.6.2.1\" has four\n * release segments), so semver cannot be used here. This is a minimal\n * comparison: it compares the dotted numeric release segments, and treats\n * pre-release/dev versions (a/b/rc/alpha/beta/dev/pre) as lower than the same\n * release so a stable release is preferred.\n * TODO: full PEP 440 ordering (post-releases, local versions, epochs) if needed.\n */\nexport function comparePythonVersions(a: string, b: string): number {\n const parse = (v: string) => {\n const releaseMatch = v.match(/^[0-9]+(?:\\.[0-9]+)*/);\n const release = (releaseMatch?.[0] ?? \"0\").split(\".\").map(Number);\n const rest = v.slice(releaseMatch?.[0].length ?? 0);\n const isPre = /^[.\\-_]?(a|b|c|rc|alpha|beta|dev|pre)/i.test(rest);\n return { release, isPre };\n };\n\n const av = parse(a);\n const bv = parse(b);\n\n const len = Math.max(av.release.length, bv.release.length);\n for (let i = 0; i < len; i++) {\n const diff = (av.release[i] ?? 0) - (bv.release[i] ?? 0);\n if (diff !== 0) return diff;\n }\n\n // Same release: a stable version outranks a pre-release/dev version\n if (av.isPre !== bv.isPre) return av.isPre ? -1 : 1;\n return 0;\n}\n\n/**\n * Parse version from a wheel filename.\n * Wheel format: {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl\n *\n * With no build tag (5 parts): distribution-version-python-abi-platform.whl\n * With build tag (6+ parts): distribution-version-build-python-abi-platform.whl\n */\nfunction parseVersionFromWheelName(filename: string): string | undefined {\n const parts = filename.replace(/\\.whl$/, \"\").split(\"-\");\n if (parts.length < 5) return undefined;\n\n // The last three parts are always: python_tag, abi_tag, platform_tag\n // For 5 parts: distribution, version, py, abi, platform -> version is parts[1]\n // For 6+ parts: distribution, version, build?, py, abi, platform -> version is parts[1]\n return parts[1];\n}\n\n/**\n * Extract Requires-Dist entries from a wheel's *.dist-info/METADATA file.\n * Accepts the file record returned by `extractWheel`.\n * Returns an empty array if METADATA is missing or contains no dependencies.\n */\nfunction getDependenciesFromWheel(files: Record<string, FileEntry>): string[] {\n const metadataPath = Object.keys(files).find((path) =>\n path.endsWith(\".dist-info/METADATA\")\n );\n if (!metadataPath) return [];\n const metadata = files[metadataPath];\n if (!metadata) return [];\n if (typeof metadata !== \"string\") return [];\n return parseRequiresDist(metadata);\n}\n\n/**\n * Parse Requires-Dist headers from Python package METADATA file (RFC 822 format).\n */\nfunction parseRequiresDist(metadata: string): string[] {\n const requires: string[] = [];\n const lines = metadata.split(/\\r?\\n/);\n\n for (const line of lines) {\n // Process previous header if it was Requires-Dist\n if (line !== undefined && line.startsWith(\"Requires-Dist:\")) {\n requires.push(line.slice(\"Requires-Dist:\".length).trim());\n }\n }\n\n return requires;\n}\n\n/**\n * Extract files from a ZIP archive (Python wheel).\n */\nfunction extractWheel(data: Uint8Array): Record<string, FileEntry> {\n const unzipped = unzipSync(data);\n const files: Record<string, FileEntry> = {};\n const textDecoder = new TextDecoder();\n\n for (const [path, content] of Object.entries(unzipped)) {\n // Keep the wheel's core metadata file so callers can read Requires-Dist from it.\n // This file has no extension, so it would otherwise be rejected by isTextFile.\n // TODO: Remove this after we clear the other todo constraining down to just text files\n if (path.endsWith(\".dist-info/METADATA\")) {\n files[path] = textDecoder.decode(content);\n continue;\n }\n\n if (\n // TODO: This can be removed once it's confirmed that workerd doesn't block these (and other) file extensions\n path.endsWith(\".md\") ||\n path.endsWith(\".css\") ||\n path.endsWith(\".js\") ||\n path.endsWith(\".txt\") ||\n path.endsWith(\"LICENSE\") ||\n path.endsWith(\".rst\")\n ) {\n continue;\n }\n\n if (isTextFile(path)) {\n files[path] = textDecoder.decode(content);\n } else {\n files[path] = { data: new Uint8Array(content) };\n }\n }\n\n return files;\n}\n","/**\n * NPM package installer for virtual file systems.\n *\n * This module fetches packages from the npm registry and populates\n * a virtual node_modules directory structure.\n * It also branches into the Python logic in installer-python.ts\n * if dependencies are declared for a Python dynamic worker.\n */\n\nimport { isTextFile, fetchWithTimeout, DEFAULT_TIMEOUT_MS } from \"./common.ts\";\nimport type { InstallResult } from \"./common.ts\";\nimport { installDependenciesPython } from \"./installer-python\";\nimport type { PyprojectToml } from \"./installer-python\";\nimport * as semver from \"semver\";\nimport type { FileSystem } from \"./file-system\";\nimport { parse as parseToml } from \"smol-toml\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org\";\n\ninterface PackageJson {\n name: string;\n version: string;\n main?: string;\n module?: string;\n exports?: unknown;\n dependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n dist?: {\n tarball: string;\n integrity?: string;\n };\n}\n\ninterface NpmPackageMetadata {\n name: string;\n \"dist-tags\": Record<string, string>;\n versions: Record<string, PackageJson>;\n}\n\ninterface InstallOptions {\n /**\n * Include devDependencies (default: false)\n */\n dev?: boolean;\n\n /**\n * Registry URL (default: https://registry.npmjs.org)\n */\n registry?: string;\n}\n\n/**\n * Install npm dependencies into a virtual file system.\n *\n * Reads the package.json from the files, resolves all dependencies,\n * and populates node_modules with the package contents.\n *\n * @param fileSystem - Virtual file system containing package.json\n * @param options - Installation options\n * @returns Metadata about the installation\n */\nexport async function installDependencies(\n fileSystem: FileSystem,\n options: InstallOptions = {}\n): Promise<InstallResult> {\n const { dev = false, registry = NPM_REGISTRY } = options;\n\n const result: InstallResult = {\n installed: [],\n warnings: []\n };\n\n // Read package.json\n const packageJsonContent = fileSystem.read(\"package.json\");\n const pyprojectTomlContent = fileSystem.read(\"pyproject.toml\");\n\n if (packageJsonContent && pyprojectTomlContent) {\n result.warnings.push(\"Cannot have package.json and pyproject.toml\");\n return result;\n }\n\n if (packageJsonContent) {\n let packageJson: PackageJson;\n try {\n packageJson = JSON.parse(packageJsonContent) as PackageJson;\n } catch {\n result.warnings.push(\"Failed to parse package.json\");\n return result;\n }\n\n // Collect dependencies to install\n const depsToInstall: Record<string, string> = {\n ...packageJson.dependencies,\n ...(dev ? packageJson.devDependencies : {})\n };\n\n if (Object.keys(depsToInstall).length === 0) {\n return result; // No dependencies to install\n }\n\n // Track installed packages to avoid duplicates\n const installedPackages = new Set<string>();\n // Track in-progress installations to avoid duplicate work\n const inProgress = new Map<string, Promise<void>>();\n\n // Install all dependencies in parallel\n await Promise.all(\n Object.entries(depsToInstall).map(([name, versionRange]) =>\n installPackage(\n name,\n versionRange,\n result,\n fileSystem,\n installedPackages,\n inProgress,\n registry\n )\n )\n );\n } else if (pyprojectTomlContent) {\n return await installDependenciesPython(fileSystem, pyprojectTomlContent);\n }\n return result;\n}\n\n/**\n * Install a single package and its dependencies recursively.\n */\nasync function installPackage(\n name: string,\n versionRange: string,\n result: InstallResult,\n fileSystem: FileSystem,\n installedPackages: Set<string>,\n inProgress: Map<string, Promise<void>>,\n registry: string\n): Promise<void> {\n // Skip if already installed in this run\n if (installedPackages.has(name)) {\n return;\n }\n\n // Skip if the package already exists in the filesystem. This allows\n // installDependencies to be called on a pre-warmed FileSystem (e.g. after a\n // prior standalone installDependencies call, or a DO filesystem loaded from\n // KV) without triggering redundant network fetches for packages that are\n // already present. Transitive deps are assumed to also be present when the\n // top-level package.json is found.\n if (fileSystem.read(`node_modules/${name}/package.json`) !== null) {\n installedPackages.add(name);\n return;\n }\n\n // If installation is already in progress, wait for it\n const existing = inProgress.get(name);\n if (existing) {\n return existing;\n }\n\n // Create the installation promise\n const installPromise = (async () => {\n try {\n // Fetch package metadata from registry\n const metadata = await fetchPackageMetadata(name, registry);\n\n // Resolve version from range\n const version = resolveVersion(versionRange, metadata);\n if (!version) {\n result.warnings.push(\n `Could not resolve version for ${name}@${versionRange}`\n );\n return;\n }\n\n // Get the specific version metadata\n const versionMetadata = metadata.versions[version];\n if (!versionMetadata) {\n result.warnings.push(`Version ${version} not found for ${name}`);\n return;\n }\n\n // Mark as installed (before fetching to prevent cycles)\n installedPackages.add(name);\n result.installed.push(`${name}@${version}`);\n\n // Fetch and extract the package tarball\n const packageFiles = await fetchPackageFiles(name, versionMetadata);\n\n // Add files to node_modules\n for (const [filePath, content] of Object.entries(packageFiles)) {\n fileSystem.write(`node_modules/${name}/${filePath}`, content);\n }\n\n // Install dependencies in parallel\n const deps = versionMetadata.dependencies ?? {};\n await Promise.all(\n Object.entries(deps).map(([depName, depVersion]) =>\n installPackage(\n depName,\n depVersion,\n result,\n fileSystem,\n installedPackages,\n inProgress,\n registry\n )\n )\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n result.warnings.push(`Failed to install ${name}: ${message}`);\n }\n })();\n\n // Track in progress\n inProgress.set(name, installPromise);\n\n try {\n await installPromise;\n } finally {\n inProgress.delete(name);\n }\n}\n\n/**\n * Fetch package metadata from npm registry.\n */\nasync function fetchPackageMetadata(\n name: string,\n registry: string\n): Promise<NpmPackageMetadata> {\n // Handle scoped packages\n const encodedName = name.startsWith(\"@\")\n ? `@${encodeURIComponent(name.slice(1))}`\n : name;\n const url = `${registry}/${encodedName}`;\n\n const response = await fetchWithTimeout(url, {\n headers: {\n // Use abbreviated metadata to avoid fetching megabytes of version data\n Accept:\n \"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8\"\n }\n });\n\n if (!response.ok) {\n // 404 on the registry usually means the package name is wrong (typo,\n // wrong scope) or the registry doesn't host it — call that out.\n const hint =\n response.status === 404\n ? \" (package not found — check the name in package.json or set the `registry` option if it lives on a private registry)\"\n : \"\";\n throw new Error(\n `Registry returned ${response.status} ${response.statusText} for \"${name}\" at ${url}${hint}`\n );\n }\n\n return (await response.json()) as NpmPackageMetadata;\n}\n\n/**\n * Resolve a semver range to a specific version.\n */\nfunction resolveVersion(\n range: string,\n metadata: NpmPackageMetadata\n): string | undefined {\n // Handle special cases\n if (range === \"latest\" || range === \"*\") {\n return metadata[\"dist-tags\"][\"latest\"];\n }\n\n // Handle exact versions\n if (metadata.versions[range]) {\n return range;\n }\n\n // Handle dist-tags (e.g., \"next\", \"beta\")\n if (metadata[\"dist-tags\"][range]) {\n return metadata[\"dist-tags\"][range];\n }\n\n // Use semver.maxSatisfying to find the best matching version\n const versions = Object.keys(metadata.versions);\n const match = semver.maxSatisfying(versions, range);\n\n return match ?? undefined;\n}\n\n/**\n * Fetch and extract package files from npm tarball.\n */\nexport async function fetchPackageFiles(\n name: string,\n metadata: PackageJson\n): Promise<Record<string, string>> {\n const tarballUrl = metadata.dist?.tarball;\n if (!tarballUrl) {\n throw new Error(\n `Registry metadata for ${name}@${metadata.version} is missing \\`dist.tarball\\` — the registry response is likely malformed or the version was unpublished.`\n );\n }\n\n // Fetch the tarball (use longer timeout for potentially large packages)\n const response = await fetchWithTimeout(\n tarballUrl,\n {},\n DEFAULT_TIMEOUT_MS * 2\n );\n if (!response.ok) {\n throw new Error(\n `Failed to fetch tarball for ${name}@${metadata.version}: ${response.status} ${response.statusText} (${tarballUrl})`\n );\n }\n\n // Get the tarball as array buffer\n const buffer = await response.arrayBuffer();\n\n // Extract the tarball (npm tarballs are gzipped tar files)\n return extractTarball(new Uint8Array(buffer));\n}\n\n/**\n * Extract files from a gzipped tarball.\n *\n * npm packages are distributed as .tgz files (gzipped tar).\n * Package contents are usually enclosed by one archive directory, which is\n * removed by `parseTar` so returned paths are relative to the package root.\n */\nasync function extractTarball(\n data: Uint8Array\n): Promise<Record<string, string>> {\n // Decompress gzip\n const decompressed = await decompress(data);\n\n // Parse tar\n return parseTar(decompressed);\n}\n\n/**\n * Decompress gzip data using DecompressionStream.\n */\nasync function decompress(data: Uint8Array): Promise<Uint8Array> {\n // Use DecompressionStream (available in Workers and modern browsers)\n const ds = new DecompressionStream(\"gzip\");\n const writer = ds.writable.getWriter();\n const reader = ds.readable.getReader();\n\n // Write compressed data\n writer.write(data as Uint8Array<ArrayBuffer>).catch(() => {});\n writer.close().catch(() => {});\n\n // Read decompressed data\n const chunks: Uint8Array[] = [];\n let totalLength = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n totalLength += value.length;\n }\n\n // Concatenate chunks\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n\n return result;\n}\n\n/**\n * Parse a tar archive and extract text files.\n *\n * TAR format:\n * - 512-byte header blocks\n * - File content (padded to 512 bytes)\n * - Two empty blocks at the end\n */\nfunction parseTar(data: Uint8Array): Record<string, string> {\n const textDecoder = new TextDecoder();\n const regularFilePaths: string[] = [];\n const textFiles = new Map<string, string>();\n let offset = 0;\n\n while (offset < data.length - 512) {\n // Read header\n const header = data.slice(offset, offset + 512);\n\n // Check for empty block (end of archive)\n if (header.every((b) => b === 0)) {\n break;\n }\n\n // Parse header fields\n const filePath = normalizeTarEntryPath(readTarEntryPath(header));\n const sizeStr = readString(header, 124, 12);\n const typeFlag = header[156];\n\n // Parse size (octal)\n const size = parseInt(sizeStr.trim(), 8) || 0;\n\n // Move past header\n offset += 512;\n\n // Only regular files describe the paths this text-only extractor returns.\n // Tar metadata entries such as PAX headers and GNU long-name records must\n // not affect package root detection.\n const isRegularFile = typeFlag === 48 || typeFlag === 0;\n if (isRegularFile && filePath !== \"\") {\n regularFilePaths.push(filePath);\n }\n\n if (isRegularFile && size > 0 && isTextFile(filePath)) {\n // Read file content\n const content = data.slice(offset, offset + size);\n\n try {\n textFiles.set(filePath, textDecoder.decode(content));\n } catch {\n // Skip files that can't be decoded as text\n }\n }\n\n // Move to next block (content is padded to 512 bytes)\n offset += Math.ceil(size / 512) * 512;\n }\n\n const archiveRoot = findSharedTarRootDirectory(regularFilePaths);\n const files: Record<string, string> = {};\n for (const [filePath, content] of textFiles) {\n const packagePath = archiveRoot\n ? filePath.slice(archiveRoot.length)\n : filePath;\n files[packagePath] = content;\n }\n\n return files;\n}\n\n/**\n * Read a TAR entry path, including the directory prefix from POSIX USTAR.\n */\nfunction readTarEntryPath(header: Uint8Array): string {\n const name = readString(header, 0, 100);\n const isPosixUstar =\n readString(header, 257, 6) === \"ustar\" &&\n readString(header, 263, 2) === \"00\";\n\n if (!isPosixUstar) {\n return name;\n }\n\n const prefix = readString(header, 345, 155);\n return prefix === \"\" ? name : `${prefix}/${name}`;\n}\n\n/**\n * Normalize the current-directory prefix that tar writers may add to entries.\n */\nfunction normalizeTarEntryPath(filePath: string): string {\n let normalizedPath = filePath;\n while (normalizedPath.startsWith(\"./\")) {\n normalizedPath = normalizedPath.slice(2);\n }\n return normalizedPath;\n}\n\n/**\n * Return the enclosing tar directory shared by every regular file.\n *\n * npm clients remove one enclosing directory during extraction without\n * requiring it to be named `package`. If any file is already at the archive\n * root, or files have different roots, the archive is left unchanged.\n */\nfunction findSharedTarRootDirectory(\n filePaths: readonly string[]\n): string | undefined {\n let sharedRoot: string | undefined;\n\n for (const filePath of filePaths) {\n const separatorIndex = filePath.indexOf(\"/\");\n if (separatorIndex <= 0) {\n return undefined;\n }\n\n const fileRoot = filePath.slice(0, separatorIndex + 1);\n if (sharedRoot === undefined) {\n sharedRoot = fileRoot;\n } else if (sharedRoot !== fileRoot) {\n return undefined;\n }\n }\n\n return sharedRoot;\n}\n\n/**\n * Read a null-terminated string from a buffer.\n */\nfunction readString(\n buffer: Uint8Array,\n offset: number,\n length: number\n): string {\n const bytes = buffer.slice(offset, offset + length);\n const nullIndex = bytes.indexOf(0);\n const relevantBytes = nullIndex >= 0 ? bytes.slice(0, nullIndex) : bytes;\n return new TextDecoder().decode(relevantBytes);\n}\n\n/**\n * Check if files contain a package.json or pyproject.toml with dependencies that need installing.\n */\nexport function hasDependencies(files: FileSystem): boolean {\n const pyprojectToml = files.read(\"pyproject.toml\");\n const packageJson = files.read(\"package.json\");\n if (!packageJson && !pyprojectToml) return false;\n\n if (packageJson) {\n try {\n const pkg = JSON.parse(packageJson);\n const deps = pkg.dependencies ?? {};\n return Object.keys(deps).length > 0;\n } catch {\n return false;\n }\n }\n\n if (pyprojectToml) {\n try {\n const pkg = parseToml(pyprojectToml) as PyprojectToml;\n const deps = pkg.project?.dependencies ?? [];\n return deps.length > 0;\n } catch {\n return false;\n }\n }\n return false;\n}\n"],"mappings":";;;;AAIA,MAAa,qBAAqB;;;;AAkBlC,SAAgB,WAAW,MAAuB;CAChD,MAAM,iBAAiB;EACrB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CAGA,MAAM,cAAc;EAClB;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CAEA,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAE1C,IACE,YAAY,MAAM,MAAM,SAAS,YAAY,CAAC,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC,GAE1E,OAAO;CAGT,OAAO,eAAe,MAAM,QAAQ,KAAK,Y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,KAAK,MAAM,WACR,CAAC,CAAC,gBAAgB,CAAC;EAClC,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS;CACpC,QAAQ;EACN,OAAO;CACT;CAGF,IAAI,eACF,IAAI;EAGF,QAFYC,MAAU,aACP,CAAC,CAAC,SAAS,gBAAgB,CAAC,EAAA,CAC/B,SAAS;CACvB,QAAQ;EACN,OAAO;CACT;CAEF,OAAO;AACT"}
|
package/dist/typescript.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as fetchPackageFiles } from "./installer-
|
|
1
|
+
import { t as fetchPackageFiles } from "./installer-Dzd--DQ7.js";
|
|
2
2
|
import { createVirtualTypeScriptEnvironment } from "@typescript/vfs";
|
|
3
3
|
//#region \0rolldown/runtime.js
|
|
4
4
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"installer-DDvaMqav.js","names":["parseToml","parseToml"],"sources":["../src/common.ts","../src/installer-python.ts","../src/installer.ts"],"sourcesContent":["/*\n * File for imports common between multiple files, to avoid cyclic imports.\n */\n\nexport const DEFAULT_TIMEOUT_MS = 30000; // 30 seconds\n\nexport interface InstallResult {\n /**\n * Packages that were freshly installed in this call.\n * Packages already present in the filesystem are skipped and not listed here.\n */\n installed: string[];\n\n /**\n * Warnings encountered during installation\n */\n warnings: string[];\n}\n\n/**\n * Check if a file path is likely a text file.\n */\nexport function isTextFile(path: string): boolean {\n const textExtensions = [\n \".js\",\n \".mjs\",\n \".cjs\",\n \".ts\",\n \".mts\",\n \".cts\",\n \".tsx\",\n \".jsx\",\n \".json\",\n \".md\",\n \".txt\",\n \".css\",\n \".html\",\n \".yml\",\n \".yaml\",\n \".toml\",\n \".xml\",\n \".svg\",\n \".map\",\n \".d.ts\",\n \".d.mts\",\n \".d.cts\",\n \".py\"\n ];\n\n // Check common config files without extensions\n const configFiles = [\n \"LICENSE\",\n \"README\",\n \"CHANGELOG\",\n \"package.json\",\n \"tsconfig.json\",\n \".npmignore\",\n \".gitignore\"\n ];\n\n const fileName = path.split(\"/\").pop() ?? \"\";\n\n if (\n configFiles.some((f) => fileName.toUpperCase().startsWith(f.toUpperCase()))\n ) {\n return true;\n }\n\n return textExtensions.some((ext) => path.toLowerCase().endsWith(ext));\n}\n\n/**\n * Fetch with a timeout.\n * Throws an error if the request takes longer than the specified timeout.\n */\nexport async function fetchWithTimeout(\n url: string,\n options: RequestInit = {},\n timeoutMs = DEFAULT_TIMEOUT_MS\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n return await fetch(url, { ...options, signal: controller.signal });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(\n `Request to ${url} timed out after ${timeoutMs}ms (npm registry slow or unreachable from this Worker)`\n );\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n","/*\n * Package resolution logic for Python dynamic workers\n */\n\nimport { isTextFile, fetchWithTimeout, DEFAULT_TIMEOUT_MS } from \"./common.ts\";\nimport type { InstallResult } from \"./common.ts\";\nimport type { FileSystem, FileEntry } from \"./file-system\";\nimport { unzipSync } from \"fflate\";\nimport { parse as parseToml } from \"smol-toml\";\n\n// TODO: Update PYODIDE_VERSION once the patch addressing the Python version mismatch for dynamic workers is merged\nconst PYODIDE_VERSION = \"v0.27.5\"; // Used for retrieving a pyodide lockfile, which is done per Pyodide version. If incompatible wheels are being served, this may be why\nconst PYPI_SIMPLE_API = \"https://pypi.org/simple\";\n\n// Deliberately keeping this minimal\nexport interface PyprojectToml {\n project?: {\n name: string;\n version: string;\n dependencies?: string[];\n };\n}\n\ninterface PyPASimpleFile {\n filename: string;\n url: string;\n hashes?: Record<string, string>;\n \"requires-python\"?: string;\n \"core-metadata\"?: boolean | { hash?: string; url?: string };\n yanked?: boolean | string;\n}\n\ninterface PyPASimpleMetadata {\n name: string;\n files: PyPASimpleFile[];\n}\n\n// Describes the packages that are available on the Pyodide CDN for a given Pyodide version\ninterface PyodideLockfile {\n info: {\n abi_version: string;\n arch: \"wasm32\";\n platform: string;\n python: string;\n version: string;\n };\n packages: Record<string, PyodideLockfilePackage>;\n}\n\ninterface PyodideLockfilePackage {\n name: string;\n version: string;\n file_name: string;\n sha256: string;\n package_type:\n | \"package\"\n | \"cpython_module\"\n | \"shared_library\"\n | \"static_library\";\n install_dir: \"site\" | \"dynlib\";\n imports: string[];\n depends: string[];\n}\n\ninterface PyodideWheelInfo {\n package: PyodideLockfilePackage;\n url: string;\n file: PyPASimpleFile;\n}\n\n// Making this global so it will only need to be fetched once per invocation\n// TODO: Consider caching this somewhere since it's not likely to change between runs\nlet pyodideLockfile: PyodideLockfile | null = null;\n\n/**\n * Install Python dependencies declared in a pyproject.toml file.\n */\nexport async function installDependenciesPython(\n fileSystem: FileSystem,\n pyprojectTomlContent: string\n): Promise<InstallResult> {\n const result: InstallResult = {\n installed: [],\n warnings: []\n };\n\n let pyprojectToml: PyprojectToml;\n try {\n pyprojectToml = parseToml(pyprojectTomlContent) as PyprojectToml;\n } catch {\n result.warnings.push(\"Failed to parse pyproject.toml\");\n return result;\n }\n\n // Collect dependencies to install. We will keep these as full dependency strings.\n const depsToInstall: string[] = pyprojectToml.project?.dependencies ?? [];\n depsToInstall.push(\"workers-runtime-sdk\");\n\n if (!pyodideLockfile) {\n try {\n pyodideLockfile = await fetchPyodideLockfile(PYODIDE_VERSION);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n result.warnings.push(\n `Could not retrieve Pyodide lockfile, attempts to retrieve packages from the Pyodide CDN may fail. Error: ${message}`\n );\n }\n }\n\n // Track installed packages to avoid duplicates\n const installedPackages = new Set<string>();\n // Track in-progress installations to avoid duplicate work\n const inProgress = new Map<string, Promise<void>>();\n\n // Install all dependencies in parallel\n await Promise.all(\n depsToInstall.map((dependencySpecifier) =>\n installPythonPackage(\n dependencySpecifier,\n result,\n fileSystem,\n installedPackages,\n inProgress,\n PYPI_SIMPLE_API\n )\n )\n );\n return result;\n}\n\n/**\n * Parse a Python version specifier string (PEP 508).\n * Currently only extracts the package name.\n */\nfunction parsePythonDependencySpecifier(spec: string): { name: string } {\n // Drop the PEP 508 environment marker (everything after `;`)\n let head = spec.split(\";\", 1)[0] ?? \"\";\n\n // The package name is the leading run of characters allowed in a PEP 508\n // identifier: letters, digits, `.`, `-`, `_`. Stop at the first character\n // that isn't one of those (whitespace, `[`, `(`, `<`, `>`, `=`, `!`, `~`, etc.).\n const match = head.match(/^\\s*([A-Za-z0-9][A-Za-z0-9._-]*)/);\n const name = match ? match[1]! : head.trim();\n\n return { name: name };\n}\n/**\n * Install a single Python package from the Pyodide index.\n * Uses PyPI as a fallback.\n */\nexport async function installPythonPackage(\n dependencySpecifier: string, // the full dependency specifier\n result: InstallResult,\n fileSystem: FileSystem,\n installedPackages: Set<string>,\n inProgress: Map<string, Promise<void>>,\n backupRegistry: string\n): Promise<void> {\n const name = parsePythonDependencySpecifier(dependencySpecifier)[\"name\"];\n // Skip if already installed in this run\n if (installedPackages.has(name)) {\n return;\n }\n\n if (!shouldInstallDependency(dependencySpecifier)) {\n return;\n }\n\n // We explicitly want to deal in names only here, not full dep strings. Only allowing one version of a package per Python environment is defined behavior\n // This was previously in installPromise, but was moved up upon observing that races could still lead to redundant fetches\n installedPackages.add(name);\n\n // TODO: In the JS impl., a check is done here for whether the package already exists in the filesystem\n // Assess in the future whether this is sensible to repeat\n\n // If installation is already in progress, wait for it\n const existing = inProgress.get(name);\n if (existing) {\n return existing;\n }\n\n const installPromise = (async () => {\n try {\n let response: Response = {} as Response;\n let wheel: PyPASimpleFile = {} as PyPASimpleFile;\n let version: string = \"\";\n\n // Try the Pyodide index first, then fall back to PyPI if that fails\n let registryResult = await retrieveFromPyodide(name);\n if (registryResult) {\n [response, wheel, version] = registryResult;\n } else {\n registryResult = await retrieveFromPyPI(name, backupRegistry);\n if (registryResult) {\n [response, wheel, version] = registryResult;\n } else {\n throw new Error(\n `Failed to download ${name}@${version}: ${response.status} ${response.statusText} (${wheel.url})`\n );\n }\n }\n const buffer = await response.arrayBuffer();\n\n const wheelContents = extractWheel(new Uint8Array(buffer));\n const dependencies = getDependenciesFromWheel(wheelContents);\n const packageFilesWheel = stripWheelToPackage(wheelContents);\n\n result.installed.push(`${name}@${version}`);\n\n // Add files to python_modules\n for (const [filePath, content] of Object.entries(packageFilesWheel)) {\n fileSystem.write(`python_modules/${filePath}`, content);\n }\n\n await Promise.all(\n dependencies.map((dep) =>\n installPythonPackage(\n dep,\n result,\n fileSystem,\n installedPackages,\n inProgress,\n PYPI_SIMPLE_API\n )\n )\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n result.warnings.push(`Failed to install ${name}: ${message}`);\n }\n })();\n\n inProgress.set(name, installPromise);\n\n try {\n await installPromise;\n } finally {\n inProgress.delete(name);\n }\n}\n\n// TODO: Genericize this to use the HTML version of this API and use it for both the Pyodide index and PyPI\nasync function retrieveFromPyPI(\n name: string,\n registry: string\n): Promise<[Response, PyPASimpleFile, string] | null> {\n const metadata = await fetchPythonPackageMetadata(name, registry);\n const version = metadata.version;\n const wheel = metadata.wheel;\n\n const response = await fetchWithTimeout(\n wheel.url,\n {},\n DEFAULT_TIMEOUT_MS * 2\n );\n\n if (!response.ok) {\n return null;\n }\n\n return [response, wheel, version];\n}\n\n// TODO: Alter the flow to use the PyPA simple api (index.pyodide.org)\nasync function retrieveFromPyodide(\n name: string\n): Promise<[Response, PyPASimpleFile, string] | null> {\n const pyodideWheel = getPyodideWheel(name);\n if (!pyodideWheel) {\n return null;\n }\n\n const response = await fetchWithTimeout(\n pyodideWheel.url,\n {},\n DEFAULT_TIMEOUT_MS * 2\n );\n if (!response.ok) {\n return null;\n }\n\n const version = pyodideWheel.package.version;\n const wheel = pyodideWheel.file;\n return [response, wheel, version];\n}\n\n// Determine whether a dependency (as listed in a wheel's METADATA) is appropriate to install\nfunction shouldInstallDependency(dependencySpecifier: string): boolean {\n // TODO: This should actually check whether extras are called for, as well as other environment and compatibility attributes\n // For the time being, it excludes any dependency that is behind an 'extra'\n const semicolonPos = dependencySpecifier.indexOf(\";\");\n if (\n semicolonPos > -1 &&\n (dependencySpecifier.substring(semicolonPos).includes(\"extra ==\") ||\n dependencySpecifier.substring(semicolonPos).includes(\"extra==\"))\n ) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Strip a Python wheel down to just the package contents.\n *\n * TODO: Re-review this function once we've cleared issues with file extension limits\n * in workerd; this function excludes certain metadata files in *.dist-info/ for now but it shouldn't remain this way\n */\nfunction stripWheelToPackage(\n files: Record<string, FileEntry>\n): Record<string, FileEntry> {\n const result: Record<string, FileEntry> = {};\n for (const [path, content] of Object.entries(files)) {\n // Skip wheel metadata and data directories\n if (path.includes(\".dist-info/\") || path.includes(\".data/\")) {\n continue;\n }\n // We'll expect that any remaining directories in the wheel are importable packages\n result[path] = content;\n }\n return result;\n}\n\n/**\n * Fetch the Pyodide lockfile for a given Pyodide version.\n *\n * The lockfile lists all pre-built packages available in the Pyodide\n * distribution, including their wheel URLs, hashes, and dependencies.\n */\nasync function fetchPyodideLockfile(\n version: string\n): Promise<PyodideLockfile | null> {\n const url = `https://cdn.jsdelivr.net/pyodide/${version}/full/pyodide-lock.json`;\n try {\n const response = await fetchWithTimeout(url);\n if (!response.ok) {\n return null;\n }\n return (await response.json()) as PyodideLockfile;\n } catch {\n return null;\n }\n}\n\n/**\n * Normalize a Python package name per PEP 503.\n *\n * Lowercases the name and collapses runs of `-`, `_`, and `.` into a single `-`.\n */\nfunction normalizePythonName(name: string): string {\n return name.toLowerCase().replace(/[-_.]+/g, \"-\");\n}\n\n/**\n * Look up a package in the loaded Pyodide lockfile and return the URL and a\n * Simple-API-shaped file entry for its wheel.\n *\n * Returns `null` if the lockfile is not loaded or the package is not present.\n */\nfunction getPyodideWheel(name: string): PyodideWheelInfo | null {\n if (!pyodideLockfile) return null;\n\n const normalizedName = normalizePythonName(name);\n const pkg = pyodideLockfile.packages[normalizedName];\n if (!pkg) return null;\n\n const baseUrl = `https://cdn.jsdelivr.net/pyodide/${PYODIDE_VERSION}/full`;\n const url = pkg.file_name.startsWith(\"http\")\n ? pkg.file_name\n : `${baseUrl}/${pkg.file_name}`;\n\n return {\n package: pkg,\n url,\n file: {\n filename: pkg.file_name,\n url,\n hashes: { sha256: pkg.sha256 }\n }\n };\n}\n\n/*\n * Fetch metadata about the 'name' package from 'registry' registry.\n * Expects the registry to support the PyPA Simple API (JSON ver)\n */\nasync function fetchPythonPackageMetadata(\n name: string,\n registry: string\n): Promise<{ version: string; wheel: PyPASimpleFile }> {\n const normalizedName = normalizePythonName(name);\n\n // Fetch package metadata from PyPI Simple API\n const metadataResponse = await fetchWithTimeout(\n `${registry}/${normalizedName}/`,\n {\n headers: {\n Accept: \"application/vnd.pypi.simple.v1+json\"\n }\n }\n );\n\n if (!metadataResponse.ok) {\n const hint =\n metadataResponse.status === 404\n ? \" (package not found — check the name in pyproject.toml)\"\n : \"\";\n throw new Error(\n `Registry ${registry} returned ${metadataResponse.status} ${metadataResponse.statusText} for \"${name}\"${hint}`\n );\n }\n const metadata = (await metadataResponse.json()) as PyPASimpleMetadata;\n\n const wheel = selectLatestCompatibleWheel(metadata.files);\n if (!wheel) {\n throw new Error(\n `No compatible wheel found for ${name} on registry ${registry}`\n );\n }\n\n const version = parseVersionFromWheelName(wheel.filename);\n if (!version) {\n throw new Error(\n `Could not parse version from wheel filename: ${wheel.filename}`\n );\n }\n\n return { version, wheel };\n}\n\n/**\n * Select a compatible wheel from PyPI Simple API files list.\n * Prefers py3-none-any or py2.py3-none-any wheels for maximum compatibility.\n * Selects the latest version from compatible wheels.\n * TODO: implement proper platform/python version matching\n */\nfunction selectLatestCompatibleWheel(\n files: PyPASimpleFile[]\n): PyPASimpleFile | null {\n const wheels = files.filter((f) => f.filename.endsWith(\".whl\"));\n if (wheels.length === 0) return null;\n\n // Filter to universal wheels (py3-none-any or py2.py3-none-any)\n const universal = wheels.filter(\n (w) =>\n w.filename.endsWith(\"-py3-none-any.whl\") ||\n w.filename.endsWith(\"-py2.py3-none-any.whl\")\n );\n\n const candidates = universal.length > 0 ? universal : wheels;\n\n // Select the wheel with the highest version\n let latest: PyPASimpleFile | null = null;\n let latestVersion: string | undefined;\n\n for (const wheel of candidates) {\n const version = parseVersionFromWheelName(wheel.filename);\n if (!version) continue;\n\n if (\n !latest ||\n !latestVersion ||\n comparePythonVersions(version, latestVersion) > 0\n ) {\n latest = wheel;\n latestVersion = version;\n }\n }\n\n return latest;\n}\n\n/**\n * Compare two PEP 440 version strings.\n * Returns >0 if a > b, <0 if a < b, 0 if equal.\n *\n * Python versions (PEP 440) are not semver-compatible (e.g. \"3.6.2.1\" has four\n * release segments), so semver cannot be used here. This is a minimal\n * comparison: it compares the dotted numeric release segments, and treats\n * pre-release/dev versions (a/b/rc/alpha/beta/dev/pre) as lower than the same\n * release so a stable release is preferred.\n * TODO: full PEP 440 ordering (post-releases, local versions, epochs) if needed.\n */\nexport function comparePythonVersions(a: string, b: string): number {\n const parse = (v: string) => {\n const releaseMatch = v.match(/^[0-9]+(?:\\.[0-9]+)*/);\n const release = (releaseMatch?.[0] ?? \"0\").split(\".\").map(Number);\n const rest = v.slice(releaseMatch?.[0].length ?? 0);\n const isPre = /^[.\\-_]?(a|b|c|rc|alpha|beta|dev|pre)/i.test(rest);\n return { release, isPre };\n };\n\n const av = parse(a);\n const bv = parse(b);\n\n const len = Math.max(av.release.length, bv.release.length);\n for (let i = 0; i < len; i++) {\n const diff = (av.release[i] ?? 0) - (bv.release[i] ?? 0);\n if (diff !== 0) return diff;\n }\n\n // Same release: a stable version outranks a pre-release/dev version\n if (av.isPre !== bv.isPre) return av.isPre ? -1 : 1;\n return 0;\n}\n\n/**\n * Parse version from a wheel filename.\n * Wheel format: {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl\n *\n * With no build tag (5 parts): distribution-version-python-abi-platform.whl\n * With build tag (6+ parts): distribution-version-build-python-abi-platform.whl\n */\nfunction parseVersionFromWheelName(filename: string): string | undefined {\n const parts = filename.replace(/\\.whl$/, \"\").split(\"-\");\n if (parts.length < 5) return undefined;\n\n // The last three parts are always: python_tag, abi_tag, platform_tag\n // For 5 parts: distribution, version, py, abi, platform -> version is parts[1]\n // For 6+ parts: distribution, version, build?, py, abi, platform -> version is parts[1]\n return parts[1];\n}\n\n/**\n * Extract Requires-Dist entries from a wheel's *.dist-info/METADATA file.\n * Accepts the file record returned by `extractWheel`.\n * Returns an empty array if METADATA is missing or contains no dependencies.\n */\nfunction getDependenciesFromWheel(files: Record<string, FileEntry>): string[] {\n const metadataPath = Object.keys(files).find((path) =>\n path.endsWith(\".dist-info/METADATA\")\n );\n if (!metadataPath) return [];\n const metadata = files[metadataPath];\n if (!metadata) return [];\n if (typeof metadata !== \"string\") return [];\n return parseRequiresDist(metadata);\n}\n\n/**\n * Parse Requires-Dist headers from Python package METADATA file (RFC 822 format).\n */\nfunction parseRequiresDist(metadata: string): string[] {\n const requires: string[] = [];\n const lines = metadata.split(/\\r?\\n/);\n\n for (const line of lines) {\n // Process previous header if it was Requires-Dist\n if (line !== undefined && line.startsWith(\"Requires-Dist:\")) {\n requires.push(line.slice(\"Requires-Dist:\".length).trim());\n }\n }\n\n return requires;\n}\n\n/**\n * Extract files from a ZIP archive (Python wheel).\n */\nfunction extractWheel(data: Uint8Array): Record<string, FileEntry> {\n const unzipped = unzipSync(data);\n const files: Record<string, FileEntry> = {};\n const textDecoder = new TextDecoder();\n\n for (const [path, content] of Object.entries(unzipped)) {\n // Keep the wheel's core metadata file so callers can read Requires-Dist from it.\n // This file has no extension, so it would otherwise be rejected by isTextFile.\n // TODO: Remove this after we clear the other todo constraining down to just text files\n if (path.endsWith(\".dist-info/METADATA\")) {\n files[path] = textDecoder.decode(content);\n continue;\n }\n\n if (\n // TODO: This can be removed once it's confirmed that workerd doesn't block these (and other) file extensions\n path.endsWith(\".md\") ||\n path.endsWith(\".css\") ||\n path.endsWith(\".js\") ||\n path.endsWith(\".txt\") ||\n path.endsWith(\"LICENSE\") ||\n path.endsWith(\".rst\")\n ) {\n continue;\n }\n\n if (isTextFile(path)) {\n files[path] = textDecoder.decode(content);\n } else {\n files[path] = { data: new Uint8Array(content) };\n }\n }\n\n return files;\n}\n","/**\n * NPM package installer for virtual file systems.\n *\n * This module fetches packages from the npm registry and populates\n * a virtual node_modules directory structure.\n * It also branches into the Python logic in installer-python.ts\n * if dependencies are declared for a Python dynamic worker.\n */\n\nimport { isTextFile, fetchWithTimeout, DEFAULT_TIMEOUT_MS } from \"./common.ts\";\nimport type { InstallResult } from \"./common.ts\";\nimport { installDependenciesPython } from \"./installer-python\";\nimport type { PyprojectToml } from \"./installer-python\";\nimport * as semver from \"semver\";\nimport type { FileSystem } from \"./file-system\";\nimport { parse as parseToml } from \"smol-toml\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org\";\n\ninterface PackageJson {\n name: string;\n version: string;\n main?: string;\n module?: string;\n exports?: unknown;\n dependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n dist?: {\n tarball: string;\n integrity?: string;\n };\n}\n\ninterface NpmPackageMetadata {\n name: string;\n \"dist-tags\": Record<string, string>;\n versions: Record<string, PackageJson>;\n}\n\ninterface InstallOptions {\n /**\n * Include devDependencies (default: false)\n */\n dev?: boolean;\n\n /**\n * Registry URL (default: https://registry.npmjs.org)\n */\n registry?: string;\n}\n\n/**\n * Install npm dependencies into a virtual file system.\n *\n * Reads the package.json from the files, resolves all dependencies,\n * and populates node_modules with the package contents.\n *\n * @param fileSystem - Virtual file system containing package.json\n * @param options - Installation options\n * @returns Metadata about the installation\n */\nexport async function installDependencies(\n fileSystem: FileSystem,\n options: InstallOptions = {}\n): Promise<InstallResult> {\n const { dev = false, registry = NPM_REGISTRY } = options;\n\n const result: InstallResult = {\n installed: [],\n warnings: []\n };\n\n // Read package.json\n const packageJsonContent = fileSystem.read(\"package.json\");\n const pyprojectTomlContent = fileSystem.read(\"pyproject.toml\");\n\n if (packageJsonContent && pyprojectTomlContent) {\n result.warnings.push(\"Cannot have package.json and pyproject.toml\");\n return result;\n }\n\n if (packageJsonContent) {\n let packageJson: PackageJson;\n try {\n packageJson = JSON.parse(packageJsonContent) as PackageJson;\n } catch {\n result.warnings.push(\"Failed to parse package.json\");\n return result;\n }\n\n // Collect dependencies to install\n const depsToInstall: Record<string, string> = {\n ...packageJson.dependencies,\n ...(dev ? packageJson.devDependencies : {})\n };\n\n if (Object.keys(depsToInstall).length === 0) {\n return result; // No dependencies to install\n }\n\n // Track installed packages to avoid duplicates\n const installedPackages = new Set<string>();\n // Track in-progress installations to avoid duplicate work\n const inProgress = new Map<string, Promise<void>>();\n\n // Install all dependencies in parallel\n await Promise.all(\n Object.entries(depsToInstall).map(([name, versionRange]) =>\n installPackage(\n name,\n versionRange,\n result,\n fileSystem,\n installedPackages,\n inProgress,\n registry\n )\n )\n );\n } else if (pyprojectTomlContent) {\n return await installDependenciesPython(fileSystem, pyprojectTomlContent);\n }\n return result;\n}\n\n/**\n * Install a single package and its dependencies recursively.\n */\nasync function installPackage(\n name: string,\n versionRange: string,\n result: InstallResult,\n fileSystem: FileSystem,\n installedPackages: Set<string>,\n inProgress: Map<string, Promise<void>>,\n registry: string\n): Promise<void> {\n // Skip if already installed in this run\n if (installedPackages.has(name)) {\n return;\n }\n\n // Skip if the package already exists in the filesystem. This allows\n // installDependencies to be called on a pre-warmed FileSystem (e.g. after a\n // prior standalone installDependencies call, or a DO filesystem loaded from\n // KV) without triggering redundant network fetches for packages that are\n // already present. Transitive deps are assumed to also be present when the\n // top-level package.json is found.\n if (fileSystem.read(`node_modules/${name}/package.json`) !== null) {\n installedPackages.add(name);\n return;\n }\n\n // If installation is already in progress, wait for it\n const existing = inProgress.get(name);\n if (existing) {\n return existing;\n }\n\n // Create the installation promise\n const installPromise = (async () => {\n try {\n // Fetch package metadata from registry\n const metadata = await fetchPackageMetadata(name, registry);\n\n // Resolve version from range\n const version = resolveVersion(versionRange, metadata);\n if (!version) {\n result.warnings.push(\n `Could not resolve version for ${name}@${versionRange}`\n );\n return;\n }\n\n // Get the specific version metadata\n const versionMetadata = metadata.versions[version];\n if (!versionMetadata) {\n result.warnings.push(`Version ${version} not found for ${name}`);\n return;\n }\n\n // Mark as installed (before fetching to prevent cycles)\n installedPackages.add(name);\n result.installed.push(`${name}@${version}`);\n\n // Fetch and extract the package tarball\n const packageFiles = await fetchPackageFiles(name, versionMetadata);\n\n // Add files to node_modules\n for (const [filePath, content] of Object.entries(packageFiles)) {\n fileSystem.write(`node_modules/${name}/${filePath}`, content);\n }\n\n // Install dependencies in parallel\n const deps = versionMetadata.dependencies ?? {};\n await Promise.all(\n Object.entries(deps).map(([depName, depVersion]) =>\n installPackage(\n depName,\n depVersion,\n result,\n fileSystem,\n installedPackages,\n inProgress,\n registry\n )\n )\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n result.warnings.push(`Failed to install ${name}: ${message}`);\n }\n })();\n\n // Track in progress\n inProgress.set(name, installPromise);\n\n try {\n await installPromise;\n } finally {\n inProgress.delete(name);\n }\n}\n\n/**\n * Fetch package metadata from npm registry.\n */\nasync function fetchPackageMetadata(\n name: string,\n registry: string\n): Promise<NpmPackageMetadata> {\n // Handle scoped packages\n const encodedName = name.startsWith(\"@\")\n ? `@${encodeURIComponent(name.slice(1))}`\n : name;\n const url = `${registry}/${encodedName}`;\n\n const response = await fetchWithTimeout(url, {\n headers: {\n // Use abbreviated metadata to avoid fetching megabytes of version data\n Accept:\n \"application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8\"\n }\n });\n\n if (!response.ok) {\n // 404 on the registry usually means the package name is wrong (typo,\n // wrong scope) or the registry doesn't host it — call that out.\n const hint =\n response.status === 404\n ? \" (package not found — check the name in package.json or set the `registry` option if it lives on a private registry)\"\n : \"\";\n throw new Error(\n `Registry returned ${response.status} ${response.statusText} for \"${name}\" at ${url}${hint}`\n );\n }\n\n return (await response.json()) as NpmPackageMetadata;\n}\n\n/**\n * Resolve a semver range to a specific version.\n */\nfunction resolveVersion(\n range: string,\n metadata: NpmPackageMetadata\n): string | undefined {\n // Handle special cases\n if (range === \"latest\" || range === \"*\") {\n return metadata[\"dist-tags\"][\"latest\"];\n }\n\n // Handle exact versions\n if (metadata.versions[range]) {\n return range;\n }\n\n // Handle dist-tags (e.g., \"next\", \"beta\")\n if (metadata[\"dist-tags\"][range]) {\n return metadata[\"dist-tags\"][range];\n }\n\n // Use semver.maxSatisfying to find the best matching version\n const versions = Object.keys(metadata.versions);\n const match = semver.maxSatisfying(versions, range);\n\n return match ?? undefined;\n}\n\n/**\n * Fetch and extract package files from npm tarball.\n */\nexport async function fetchPackageFiles(\n name: string,\n metadata: PackageJson\n): Promise<Record<string, string>> {\n const tarballUrl = metadata.dist?.tarball;\n if (!tarballUrl) {\n throw new Error(\n `Registry metadata for ${name}@${metadata.version} is missing \\`dist.tarball\\` — the registry response is likely malformed or the version was unpublished.`\n );\n }\n\n // Fetch the tarball (use longer timeout for potentially large packages)\n const response = await fetchWithTimeout(\n tarballUrl,\n {},\n DEFAULT_TIMEOUT_MS * 2\n );\n if (!response.ok) {\n throw new Error(\n `Failed to fetch tarball for ${name}@${metadata.version}: ${response.status} ${response.statusText} (${tarballUrl})`\n );\n }\n\n // Get the tarball as array buffer\n const buffer = await response.arrayBuffer();\n\n // Extract the tarball (npm tarballs are gzipped tar files)\n return extractTarball(new Uint8Array(buffer));\n}\n\n/**\n * Extract files from a gzipped tarball.\n *\n * npm packages are distributed as .tgz files (gzipped tar).\n * Package contents are usually enclosed by one archive directory, which is\n * removed by `parseTar` so returned paths are relative to the package root.\n */\nasync function extractTarball(\n data: Uint8Array\n): Promise<Record<string, string>> {\n // Decompress gzip\n const decompressed = await decompress(data);\n\n // Parse tar\n return parseTar(decompressed);\n}\n\n/**\n * Decompress gzip data using DecompressionStream.\n */\nasync function decompress(data: Uint8Array): Promise<Uint8Array> {\n // Use DecompressionStream (available in Workers and modern browsers)\n const ds = new DecompressionStream(\"gzip\");\n const writer = ds.writable.getWriter();\n const reader = ds.readable.getReader();\n\n // Write compressed data\n writer.write(data as Uint8Array<ArrayBuffer>).catch(() => {});\n writer.close().catch(() => {});\n\n // Read decompressed data\n const chunks: Uint8Array[] = [];\n let totalLength = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n totalLength += value.length;\n }\n\n // Concatenate chunks\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n\n return result;\n}\n\n/**\n * Parse a tar archive and extract text files.\n *\n * TAR format:\n * - 512-byte header blocks\n * - File content (padded to 512 bytes)\n * - Two empty blocks at the end\n */\nfunction parseTar(data: Uint8Array): Record<string, string> {\n const textDecoder = new TextDecoder();\n const regularFilePaths: string[] = [];\n const textFiles = new Map<string, string>();\n let offset = 0;\n\n while (offset < data.length - 512) {\n // Read header\n const header = data.slice(offset, offset + 512);\n\n // Check for empty block (end of archive)\n if (header.every((b) => b === 0)) {\n break;\n }\n\n // Parse header fields\n const filePath = normalizeTarEntryPath(readTarEntryPath(header));\n const sizeStr = readString(header, 124, 12);\n const typeFlag = header[156];\n\n // Parse size (octal)\n const size = parseInt(sizeStr.trim(), 8) || 0;\n\n // Move past header\n offset += 512;\n\n // Only regular files describe the paths this text-only extractor returns.\n // Tar metadata entries such as PAX headers and GNU long-name records must\n // not affect package root detection.\n const isRegularFile = typeFlag === 48 || typeFlag === 0;\n if (isRegularFile && filePath !== \"\") {\n regularFilePaths.push(filePath);\n }\n\n if (isRegularFile && size > 0 && isTextFile(filePath)) {\n // Read file content\n const content = data.slice(offset, offset + size);\n\n try {\n textFiles.set(filePath, textDecoder.decode(content));\n } catch {\n // Skip files that can't be decoded as text\n }\n }\n\n // Move to next block (content is padded to 512 bytes)\n offset += Math.ceil(size / 512) * 512;\n }\n\n const archiveRoot = findSharedTarRootDirectory(regularFilePaths);\n const files: Record<string, string> = {};\n for (const [filePath, content] of textFiles) {\n const packagePath = archiveRoot\n ? filePath.slice(archiveRoot.length)\n : filePath;\n files[packagePath] = content;\n }\n\n return files;\n}\n\n/**\n * Read a TAR entry path, including the directory prefix from POSIX USTAR.\n */\nfunction readTarEntryPath(header: Uint8Array): string {\n const name = readString(header, 0, 100);\n const isPosixUstar =\n readString(header, 257, 6) === \"ustar\" &&\n readString(header, 263, 2) === \"00\";\n\n if (!isPosixUstar) {\n return name;\n }\n\n const prefix = readString(header, 345, 155);\n return prefix === \"\" ? name : `${prefix}/${name}`;\n}\n\n/**\n * Normalize the current-directory prefix that tar writers may add to entries.\n */\nfunction normalizeTarEntryPath(filePath: string): string {\n let normalizedPath = filePath;\n while (normalizedPath.startsWith(\"./\")) {\n normalizedPath = normalizedPath.slice(2);\n }\n return normalizedPath;\n}\n\n/**\n * Return the enclosing tar directory shared by every regular file.\n *\n * npm clients remove one enclosing directory during extraction without\n * requiring it to be named `package`. If any file is already at the archive\n * root, or files have different roots, the archive is left unchanged.\n */\nfunction findSharedTarRootDirectory(\n filePaths: readonly string[]\n): string | undefined {\n let sharedRoot: string | undefined;\n\n for (const filePath of filePaths) {\n const separatorIndex = filePath.indexOf(\"/\");\n if (separatorIndex <= 0) {\n return undefined;\n }\n\n const fileRoot = filePath.slice(0, separatorIndex + 1);\n if (sharedRoot === undefined) {\n sharedRoot = fileRoot;\n } else if (sharedRoot !== fileRoot) {\n return undefined;\n }\n }\n\n return sharedRoot;\n}\n\n/**\n * Read a null-terminated string from a buffer.\n */\nfunction readString(\n buffer: Uint8Array,\n offset: number,\n length: number\n): string {\n const bytes = buffer.slice(offset, offset + length);\n const nullIndex = bytes.indexOf(0);\n const relevantBytes = nullIndex >= 0 ? bytes.slice(0, nullIndex) : bytes;\n return new TextDecoder().decode(relevantBytes);\n}\n\n/**\n * Check if files contain a package.json or pyproject.toml with dependencies that need installing.\n */\nexport function hasDependencies(files: FileSystem): boolean {\n const pyprojectToml = files.read(\"pyproject.toml\");\n const packageJson = files.read(\"package.json\");\n if (!packageJson && !pyprojectToml) return false;\n\n if (packageJson) {\n try {\n const pkg = JSON.parse(packageJson);\n const deps = pkg.dependencies ?? {};\n return Object.keys(deps).length > 0;\n } catch {\n return false;\n }\n }\n\n if (pyprojectToml) {\n try {\n const pkg = parseToml(pyprojectToml) as PyprojectToml;\n const deps = pkg.project?.dependencies ?? [];\n return deps.length > 0;\n } catch {\n return false;\n }\n }\n return false;\n}\n"],"mappings":";;;;AAIA,MAAa,qBAAqB;;;;AAkBlC,SAAgB,WAAW,MAAuB;CAChD,MAAM,iBAAiB;EACrB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CAGA,MAAM,cAAc;EAClB;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CAEA,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAE1C,IACE,YAAY,MAAM,MAAM,SAAS,YAAY,CAAC,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC,GAE1E,OAAO;CAGT,OAAO,eAAe,MAAM,QAAQ,KAAK,YAAY,CAAC,CAAC,SAAS,GAAG,CAAC;AACtE;;;;;AAMA,eAAsB,iBACpB,KACA,UAAuB,CAAC,GACxB,YAAY,oBACO;CACnB,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,YAAY,iBAAiB,WAAW,MAAM,GAAG,SAAS;CAEhE,IAAI;EACF,OAAO,MAAM,MAAM,KAAK;GAAE,GAAG;GAAS,QAAQ,WAAW;EAAO,CAAC;CACnE,SAAS,OAAO;EACd,IAAI,iBAAiB,SAAS,MAAM,SAAS,cAC3C,MAAM,IAAI,MACR,cAAc,IAAI,mBAAmB,UAAU,uDACjD;EAEF,MAAM;CACR,U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