From 695a697e88e748ab82ab5182f341c62d834408f2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 25 Apr 2026 17:32:14 -0500 Subject: [PATCH] Support new Worker(new URL(..., import.meta.url)) and asset URLs Shakespeare's esbuild-wasm pipeline now handles the Vite/webpack-compatible patterns for module workers and static asset URLs, so projects using new Worker(new URL('./w.ts', import.meta.url), { type: 'module' }) new SharedWorker(new URL('./w.ts', import.meta.url), { type: 'module' }) new URL('./logo.svg', import.meta.url) build correctly under Shakespeare instead of emitting a 404'ing URL that pointed at the source-file path inside the main bundle. Mechanics: - A new detection pass (src/lib/build/workerPlugin.ts) is invoked from the fs plugin's onLoad for .ts/.tsx/.js/.jsx/.mjs files. It cheaply regex-prefilters on 'new URL(' so 99% of files pay zero overhead, then strips TS/JSX via esbuild.transform and parses with acorn + acorn-jsx for the handful of files that actually match. The string literal spec inside each matched new URL() call is replaced with a unique placeholder token, preserving the enclosing new URL(..., import.meta.url) shape so runtime resolution against the main bundle URL still works. - bundle() now runs a per-worker sub-build (esbuild.build) with the same plugin stack, producing a hashed ESM chunk alongside the main output. The queue drains recursively so nested workers / assets discovered during a sub-build are handled in the same bundle call. - Non-source assets are copied into the output with content-hashed filenames (SHA-256 when SubtleCrypto is available, FNV-1a fallback for test environments). - After all sub-builds finish, placeholder tokens are string-replaced in every JS output with the corresponding './'. - updateCSPForEsmSh gains an emittedWorkers option; when set it additionally ensures worker-src and child-src exist and extends them with the ESM CDN so module workers can import from esm.sh. Errors (with file:line context) are raised for classic (non-module) workers, dynamic specifiers, and unresolvable worker specs. Plain new URL() pointing at a source file emits a console warning and is left untransformed. Tests: 16 new workerPlugin unit tests cover detection, errors, dedup, and quote-style handling; 4 new CSP tests cover the emittedWorkers path. --- AGENTS.md | 35 +++ package-lock.json | 13 +- package.json | 2 + src/lib/build/fsPlugin.ts | 216 +++++++++----- src/lib/build/index.test.ts | 36 ++- src/lib/build/index.ts | 237 +++++++++++++++- src/lib/build/workerPlugin.test.ts | 286 +++++++++++++++++++ src/lib/build/workerPlugin.ts | 438 +++++++++++++++++++++++++++++ 8 files changed, 1173 insertions(+), 90 deletions(-) create mode 100644 src/lib/build/workerPlugin.test.ts create mode 100644 src/lib/build/workerPlugin.ts diff --git a/AGENTS.md b/AGENTS.md index 26475ce2..2ad27f57 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,6 +77,41 @@ AI filesystem access through tools (including shell commands via ShellTool) has - **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories) - **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas +#### Web Workers and Asset URLs + +Shakespeare's esbuild-wasm build pipeline supports the Vite/webpack-compatible patterns for loading Web Workers and static assets: + +```ts +// Module Worker (required: { type: 'module' }) +const worker = new Worker( + new URL('./worker.ts', import.meta.url), + { type: 'module' }, +); + +// SharedWorker, same pattern +const shared = new SharedWorker( + new URL('./shared.ts', import.meta.url), + { type: 'module' }, +); + +// Static asset URL (images, wasm, fonts, audio, etc.) +const logoUrl = new URL('./logo.svg', import.meta.url); +``` + +**Supported:** +- `new Worker(new URL('', import.meta.url), { type: 'module' })` +- `new SharedWorker(new URL('', import.meta.url), { type: 'module' })` +- `new URL('', import.meta.url)` where `` resolves to a non-source file (images, wasm, audio, fonts, etc.) +- Relative (`./`, `../`), absolute (`/`), and alias (`@/`) specifiers +- String literals with any quote style, including backticks without interpolation + +**Not supported (will emit a build error):** +- Classic (non-module) workers — `{ type: 'module' }` is required +- Dynamic specifiers — the first argument to `new URL()` must be a string literal +- `new URL(..., import.meta.url)` pointing at source files (`.ts/.tsx/.js/.jsx/.mjs/.cjs/.css`); use a regular import or the Worker pattern instead (emits a console warning, then leaves the expression untouched) + +Workers are bundled as separate ESM chunks and can import from npm packages normally — the same ESM-CDN rewrites applied to the main bundle apply to workers. When any workers are emitted, the build also extends the output CSP's `worker-src` and `child-src` directives to permit loading the ESM CDN from within workers. + ### Git Integration with isomorphic-git Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB. diff --git a/package-lock.json b/package-lock.json index 661d9f56..e6e6195f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "shakespeare.diy", - "version": "9.11.2", + "version": "9.11.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "shakespeare.diy", - "version": "9.11.2", + "version": "9.11.4", "license": "AGPL-3.0-or-later", "dependencies": { "@capacitor/app": "^8.1.0", @@ -57,6 +57,8 @@ "@tanstack/react-query": "^5.56.2", "@unhead/addons": "^2.0.10", "@unhead/react": "^2.0.10", + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", "buffer": "^6.0.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -6797,9 +6799,9 @@ } }, "node_modules/acorn": { - "version": "8.15.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", - "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", "license": "MIT", "bin": { "acorn": "bin/acorn" @@ -6812,7 +6814,6 @@ "version": "5.3.2", "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, "license": "MIT", "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" diff --git a/package.json b/package.json index 90dbb724..de87e50e 100644 --- a/package.json +++ b/package.json @@ -70,6 +70,8 @@ "@tanstack/react-query": "^5.56.2", "@unhead/addons": "^2.0.10", "@unhead/react": "^2.0.10", + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", "buffer": "^6.0.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index 4a8f24eb..c6964bbd 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -3,6 +3,8 @@ import { join, dirname, extname } from "path-browserify"; import type { Loader, Plugin } from "esbuild-wasm"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; +import { detectWorkersAndAssets, type WorkerMatch, type AssetMatch } from "./workerPlugin"; + interface TsConfig { compilerOptions?: { baseUrl?: string; @@ -21,10 +23,17 @@ interface FsPluginOptions { cwd: string; tsconfig?: TsConfig; packageJson?: PackageJson; + /** + * Optional collectors populated when a source file contains + * `new Worker(new URL(...))` / `new SharedWorker(new URL(...))` / + * `new URL(..., import.meta.url)` patterns. + */ + collectWorkers?: WorkerMatch[]; + collectAssets?: AssetMatch[]; } export function fsPlugin(options: FsPluginOptions): Plugin { - const { fs, cwd, tsconfig, packageJson } = options; + const { fs, cwd, tsconfig, packageJson, collectWorkers, collectAssets } = options; return { name: "fs", @@ -42,74 +51,17 @@ export function fsPlugin(options: FsPluginOptions): Plugin { return; } - let resolved: string | undefined; - - // Handle absolute paths - if (args.path.startsWith("/")) { - resolved = args.path; - } - // Handle @/ alias - else if (args.path.startsWith("@/")) { - resolved = join(cwd, "src", args.path.slice(2)); - } - // Handle relative paths - else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) { - // Remove fs: prefix from importer if present - const importerPath = args.importer.replace(/^fs:/, ''); - resolved = join(dirname(importerPath), args.path); - } - // Handle bare imports (e.g., "react", "@scope/package") - else if (args.path.match(/^[^./]/)) { - // Check if this is a file: dependency - const packageName = args.path.startsWith("@") - ? args.path.split("/").slice(0, 2).join("/") - : args.path.split("/")[0]; - - const allDeps = { - ...packageJson?.dependencies, - ...packageJson?.devDependencies, - ...packageJson?.peerDependencies, - }; - - const depVersion = allDeps[packageName]; - - if (depVersion && depVersion.startsWith("file:")) { - // Extract the file path (e.g., "file:./path" -> "./path") - const filePath = depVersion.slice(5); // Remove "file:" prefix - const packagePath = join(cwd, filePath); - - // Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file") - const subpath = args.path.slice(packageName.length); - - resolved = join(packagePath, subpath); - } else { - return; // Let esmPlugin handle this - } - } - // Handle tsconfig baseUrl - else if (args.importer && tsconfig?.compilerOptions?.baseUrl) { - resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path); - } - // Nothing matched, let other plugins handle it - else { - return; - } - - if (!resolved) { - return; - } + const resolved = await resolveFromImporter(args.path, args.importer, { + fs, + cwd, + tsconfig, + packageJson, + }); - // Vite query parameters https://vite.dev/guide/assets - const [cleaned, query] = resolved.split("?"); - - try { - resolved = await tryFileVariants(fs, cleaned); - } catch { - return; // Let other plugins handle this - } + if (!resolved) return; return { - path: resolved + (typeof query === "string" ? "?" + query : ""), + path: resolved, namespace: "fs", }; }); @@ -138,8 +90,41 @@ export function fsPlugin(options: FsPluginOptions): Plugin { }; } + let contents = await fs.readFile(path, "utf8"); + + // Run worker/asset detection on source-code files. This only + // does any real work if the file contains `new URL(`; the + // prefilter inside `detectWorkersAndAssets` bails early + // otherwise. + if ( + (collectWorkers || collectAssets) && + ["ts", "tsx", "js", "jsx", "mjs", "cjs"].includes(ext) + ) { + const result = await detectWorkersAndAssets({ + source: contents, + filePath: path, + ext, + resolveSpec: async (spec, importerPath) => { + const resolved = await resolveFromImporter(spec, importerPath, { + fs, + cwd, + tsconfig, + packageJson, + }); + if (!resolved) return undefined; + // Strip any ?query that made it onto the resolved path. + return resolved.split("?")[0]; + }, + }); + if (result.workers.length || result.assets.length) { + contents = result.code; + if (collectWorkers) collectWorkers.push(...result.workers); + if (collectAssets) collectAssets.push(...result.assets); + } + } + return { - contents: await fs.readFile(path, "utf8"), + contents, loader: ext as Loader, }; }, @@ -148,6 +133,85 @@ export function fsPlugin(options: FsPluginOptions): Plugin { }; } +interface ResolveContext { + fs: JSRuntimeFS; + cwd: string; + tsconfig?: TsConfig; + packageJson?: PackageJson; +} + +/** + * Resolve a module specifier against an importer. This mirrors the + * resolution rules used by the fs plugin's onResolve handler so it + * can be reused by the worker/asset detection pass. + */ +export async function resolveFromImporter( + path: string, + importer: string | undefined, + ctx: ResolveContext, +): Promise { + const { fs, cwd, tsconfig, packageJson } = ctx; + + let resolved: string | undefined; + + // Handle absolute paths + if (path.startsWith("/")) { + resolved = path; + } + // Handle @/ alias + else if (path.startsWith("@/")) { + resolved = join(cwd, "src", path.slice(2)); + } + // Handle relative paths + else if (importer && (path.startsWith("./") || path.startsWith("../"))) { + const importerPath = importer.replace(/^fs:/, ''); + resolved = join(dirname(importerPath), path); + } + // Handle bare imports (e.g., "react", "@scope/package") + else if (path.match(/^[^./]/)) { + const packageName = path.startsWith("@") + ? path.split("/").slice(0, 2).join("/") + : path.split("/")[0]; + + const allDeps = { + ...packageJson?.dependencies, + ...packageJson?.devDependencies, + ...packageJson?.peerDependencies, + }; + + const depVersion = allDeps[packageName]; + + if (depVersion && depVersion.startsWith("file:")) { + const filePath = depVersion.slice(5); + const packagePath = join(cwd, filePath); + const subpath = path.slice(packageName.length); + resolved = join(packagePath, subpath); + } else { + return undefined; + } + } + // Handle tsconfig baseUrl + else if (importer && tsconfig?.compilerOptions?.baseUrl) { + resolved = join(cwd, tsconfig.compilerOptions.baseUrl, path); + } + else { + return undefined; + } + + if (!resolved) return undefined; + + // Vite query parameters https://vite.dev/guide/assets + const [cleaned, query] = resolved.split("?"); + + try { + resolved = await tryFileVariants(fs, cleaned); + } catch { + return undefined; + } + + return resolved + (typeof query === "string" ? "?" + query : ""); +} + async function tryFileVariants( fs: JSRuntimeFS, basePath: string, @@ -167,23 +231,23 @@ async function tryFileVariants( const packageJsonPath = join(basePath, "package.json"); const packageJsonText = await fs.readFile(packageJsonPath, "utf8"); const packageJson = JSON.parse(packageJsonText); - + // Check for various entry point fields const entryPoint = packageJson.exports?.['.'] - || packageJson.module - || packageJson.main + || packageJson.module + || packageJson.main || 'index.js'; - + // Resolve the entry point - const entryPath = typeof entryPoint === 'string' + const entryPath = typeof entryPoint === 'string' ? join(basePath, entryPoint) : join(basePath, 'index.js'); - + const entryStat = await statSafe(fs, entryPath); if (entryStat.isFile()) { return entryPath; } - + // Try with different extensions if the entry point doesn't exist for (const ext of extensions) { const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext; @@ -195,7 +259,7 @@ async function tryFileVariants( } catch { // package.json doesn't exist or is invalid, fall through to index files } - + // Fall back to trying index files for (const ext of extensions) { const indexFile = join(basePath, "index" + ext); @@ -228,4 +292,4 @@ async function statSafe(fs: JSRuntimeFS, filePath: string): Promise<{ isFile(): isDirectory: () => false, }; } -} \ No newline at end of file +} diff --git a/src/lib/build/index.test.ts b/src/lib/build/index.test.ts index e494d1c2..42889678 100644 --- a/src/lib/build/index.test.ts +++ b/src/lib/build/index.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; -import { buildProject } from './index'; +import { buildProject, updateCSPForEsmSh } from './index'; import { copyFiles } from '../copyFiles'; import type { JSRuntimeFS } from '../JSRuntime'; @@ -594,4 +594,38 @@ react@^18.0.0: // Verify package.json was read expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8'); }); +}); + +describe('updateCSPForEsmSh', () => { + const esmUrl = 'https://esm.shakespeare.diy'; + + it('extends the standard ESM directives with the CDN', () => { + const csp = "default-src 'self'; script-src 'self'; img-src 'self'"; + const result = updateCSPForEsmSh(csp, esmUrl); + expect(result).toContain(`script-src 'self' ${esmUrl}`); + expect(result).toContain(`img-src 'self' ${esmUrl}`); + }); + + it('does NOT extend worker-src by default', () => { + const csp = "script-src 'self'; worker-src 'self'"; + const result = updateCSPForEsmSh(csp, esmUrl); + // worker-src should remain untouched (still 'self' only). + expect(result).toContain("worker-src 'self'"); + expect(result).not.toMatch(new RegExp(`worker-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`)); + }); + + it('extends worker-src and child-src when emittedWorkers is true', () => { + const csp = "script-src 'self'"; + const result = updateCSPForEsmSh(csp, esmUrl, { emittedWorkers: true }); + // The directives may be seeded with 'self' if absent; what matters + // is that the CDN is present in each. + expect(result).toMatch(new RegExp(`worker-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`)); + expect(result).toMatch(new RegExp(`child-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`)); + }); + + it('extends existing worker-src directive without seeding when already present', () => { + const csp = "script-src 'self'; worker-src 'self' blob:"; + const result = updateCSPForEsmSh(csp, esmUrl, { emittedWorkers: true }); + expect(result).toMatch(new RegExp(`worker-src 'self' blob: ${esmUrl.replace(/[.]/g, '\\.')}`)); + }); }); \ No newline at end of file diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index e104e3cd..a18a54aa 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -8,6 +8,7 @@ import { shakespearePlugin } from "./shakespearePlugin"; import { esmPlugin } from "./esmPlugin"; import { fsPlugin } from "./fsPlugin"; import { convertYarnLockToPackageLock } from "./yarnLockConverter"; +import type { WorkerMatch, AssetMatch } from "./workerPlugin"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; import type { Plugin } from 'esbuild-wasm'; @@ -112,6 +113,23 @@ export async function readBuildContext( return { packageJson, packageLock, tsconfig }; } +export interface CreatePluginsOptions { + /** + * When provided, the fs plugin will scan source files for + * `new Worker(new URL(..., import.meta.url))` patterns and push + * matches here so the caller can build them as additional entry + * points. + */ + collectWorkers?: WorkerMatch[]; + /** + * When provided, the fs plugin will scan source files for + * `new URL(..., import.meta.url)` patterns referencing non-source + * assets and push matches here so the caller can copy them into + * the output. + */ + collectAssets?: AssetMatch[]; +} + /** * Create the common esbuild plugins for both project and worker builds * Exported for use by deployment adapters that need to bundle workers @@ -122,10 +140,18 @@ export function createPlugins( context: BuildContext, esmUrl: string, target?: string, + pluginOptions: CreatePluginsOptions = {}, ): Plugin[] { return [ shakespearePlugin({ esmUrl }), - fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }), + fsPlugin({ + fs, + cwd: projectPath, + tsconfig: context.tsconfig, + packageJson: context.packageJson, + collectWorkers: pluginOptions.collectWorkers, + collectAssets: pluginOptions.collectAssets, + }), esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }), ]; } @@ -175,6 +201,9 @@ async function bundle( } } + const collectedWorkers: WorkerMatch[] = []; + const collectedAssets: AssetMatch[] = []; + const results = await esbuild.build({ entryPoints, bundle: true, @@ -188,7 +217,10 @@ async function bundle( entryNames: "[name]-[hash]", chunkNames: "[name]-[hash]", assetNames: "[name]-[hash]", - plugins: createPlugins(fs, projectPath, context, esmUrl, target), + plugins: createPlugins(fs, projectPath, context, esmUrl, target, { + collectWorkers: collectedWorkers, + collectAssets: collectedAssets, + }), define: { "import.meta.env": JSON.stringify({}), }, @@ -222,12 +254,140 @@ async function bundle( } } - // Parse CSP and ensure ESM CDN is allowed for necessary directives + // Build each unique collected worker as its own ESM chunk, looping + // to pick up any nested workers / assets they themselves collect. + // Each iteration passes the same collector arrays so newly + // discovered entries feed the next iteration. + const placeholderToFilename = new Map(); + const workerQueue: WorkerMatch[] = [...collectedWorkers]; + const seenWorkerPaths = new Set(); + + while (workerQueue.length > 0) { + const nextBatch = workerQueue.splice(0, workerQueue.length); + for (const worker of nextBatch) { + if (seenWorkerPaths.has(worker.resolvedPath)) { + // Reuse the output from the prior build of this same worker. + const existing = findPlaceholderForPath(placeholderToFilename, worker.resolvedPath); + if (existing) { + placeholderToFilename.set(worker.placeholder, existing); + } + continue; + } + seenWorkerPaths.add(worker.resolvedPath); + + const before = { + workers: collectedWorkers.length, + assets: collectedAssets.length, + }; + + const workerResult = await esbuild.build({ + entryPoints: [worker.resolvedPath], + bundle: true, + write: false, + format: "esm", + target, + outdir: "/", + jsx: "automatic", + metafile: true, + sourcemap: true, + entryNames: "[name]-[hash]", + chunkNames: "[name]-[hash]", + assetNames: "[name]-[hash]", + plugins: createPlugins(fs, projectPath, context, esmUrl, target, { + collectWorkers: collectedWorkers, + collectAssets: collectedAssets, + }), + define: { + "import.meta.env": JSON.stringify({}), + }, + }); + + let entryFilename: string | undefined; + for (const file of workerResult.outputFiles) { + const filename = file.path.slice(1); + dist[filename] = file.contents; + const outMeta = workerResult.metafile.outputs[filename]; + if (outMeta?.entryPoint && !entryFilename && filename.endsWith(".js")) { + entryFilename = filename; + } + } + if (!entryFilename) { + // Fall back to the first .js output. + const firstJs = workerResult.outputFiles.find((f) => f.path.endsWith(".js")); + if (firstJs) entryFilename = firstJs.path.slice(1); + } + if (!entryFilename) { + throw new Error(`Failed to bundle worker: ${worker.resolvedPath}`); + } + + // Record placeholder -> "./" so main-bundle rewrites + // produce URLs that resolve correctly against import.meta.url + // of the main bundle (which lives at the same origin/dir). + placeholderToFilename.set(worker.placeholder, "./" + entryFilename); + // Record the file path -> filename mapping in a secondary index + // via the placeholder (so the dedup branch above can find it). + placeholderToFilename.set(`@path:${worker.resolvedPath}`, entryFilename); + + // New workers / assets discovered during this sub-build get + // queued. + if (collectedWorkers.length > before.workers) { + workerQueue.push(...collectedWorkers.slice(before.workers)); + } + } + } + + // Copy each unique collected asset into the output directory with + // a content-hashed filename. + const assetPathToFilename = new Map(); + for (const asset of collectedAssets) { + let outName = assetPathToFilename.get(asset.resolvedPath); + if (!outName) { + const bytes = await fs.readFile(asset.resolvedPath); + const data = bytes instanceof Uint8Array ? bytes : new TextEncoder().encode(String(bytes)); + const hash = await shortContentHash(data); + const base = asset.resolvedPath.split("/").pop() ?? "asset"; + const dot = base.lastIndexOf("."); + const stem = dot > 0 ? base.slice(0, dot) : base; + const ext = dot > 0 ? base.slice(dot) : ""; + outName = `${stem}-${hash}${ext}`; + dist[outName] = data; + assetPathToFilename.set(asset.resolvedPath, outName); + } + placeholderToFilename.set(asset.placeholder, "./" + outName); + } + + // Substitute placeholders in every JS output file. + if (placeholderToFilename.size > 0) { + const decoder = new TextDecoder(); + const encoder = new TextEncoder(); + for (const [filename, contents] of Object.entries(dist)) { + if (!filename.endsWith(".js")) continue; + let text = decoder.decode(contents); + let changed = false; + for (const [placeholder, replacement] of placeholderToFilename) { + if (placeholder.startsWith("@path:")) continue; + if (text.includes(placeholder)) { + text = text.split(placeholder).join(replacement.startsWith("./") ? replacement.slice(2) : replacement); + changed = true; + } + } + if (changed) { + dist[filename] = encoder.encode(text); + } + } + } + + // Parse CSP and ensure ESM CDN is allowed for necessary directives. + // If any workers were emitted, also extend worker-src / child-src so + // the browser permits module workers and workers importing from the + // ESM CDN. const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]"); if (cspMeta) { const cspContent = cspMeta.getAttribute("content"); if (cspContent) { - const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl); + const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl, { + emittedWorkers: collectedWorkers.length > 0, + }); cspMeta.setAttribute("content", updatedCSP); } } @@ -238,6 +398,42 @@ async function bundle( return dist; } +function findPlaceholderForPath( + placeholderToFilename: Map, + resolvedPath: string, +): string | undefined { + const key = `@path:${resolvedPath}`; + const filename = placeholderToFilename.get(key); + return filename ? "./" + filename : undefined; +} + +async function shortContentHash(data: Uint8Array): Promise { + // Use SubtleCrypto if available (browsers, modern Node via webcrypto + // global); fall back to a simple non-cryptographic hash for test + // environments that stub out crypto. + try { + const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle; + if (subtle?.digest) { + const buf = await subtle.digest("SHA-256", data); + const bytes = new Uint8Array(buf); + let hex = ""; + for (let i = 0; i < 8; i++) { + hex += bytes[i].toString(16).padStart(2, "0"); + } + return hex; + } + } catch { + // fall through + } + // FNV-1a-ish fallback (good enough for filename uniqueness). + let h = 0x811c9dc5; + for (let i = 0; i < data.length; i++) { + h ^= data[i]; + h = Math.imul(h, 0x01000193); + } + return (h >>> 0).toString(16).padStart(8, "0"); +} + /** * Build project and write output files to the filesystem */ @@ -328,15 +524,42 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise { } /** Updates CSP to allow ESM CDN for scripts, assets, fonts, and CSS */ -export function updateCSPForEsmSh(csp: string, esmUrl: string): string { +export function updateCSPForEsmSh( + csp: string, + esmUrl: string, + options: { emittedWorkers?: boolean } = {}, +): string { const esmDirectives = [ 'script-src', // For JavaScript modules 'img-src', // For images 'media-src', // For video/audio 'font-src', // For fonts 'style-src', // For CSS - 'connect-src' // For fetch/XHR requests to ESM CDN + 'connect-src', // For fetch/XHR requests to ESM CDN ]; - return addDomainToCSP(csp, esmUrl, esmDirectives); + let updated = addDomainToCSP(csp, esmUrl, esmDirectives); + + if (options.emittedWorkers) { + // Module workers load from the same origin; when they import from + // the ESM CDN, worker-src (and child-src for older browsers) must + // list the CDN as well. These directives may not exist in the + // project's CSP, so seed them before extending. + updated = ensureDirective(updated, 'worker-src'); + updated = ensureDirective(updated, 'child-src'); + updated = addDomainToCSP(updated, esmUrl, ['worker-src', 'child-src']); + } + + return updated; +} + +/** + * Ensure a CSP directive exists. If absent, seed it with `'self'` so + * subsequent `addDomainToCSP` calls have something to extend. + */ +function ensureDirective(csp: string, directive: string): string { + const re = new RegExp(`(^|;)\\s*${directive}\\s`); + if (re.test(csp)) return csp; + const trimmed = csp.trim().replace(/;\s*$/, ''); + return trimmed ? `${trimmed}; ${directive} 'self'` : `${directive} 'self'`; } \ No newline at end of file diff --git a/src/lib/build/workerPlugin.test.ts b/src/lib/build/workerPlugin.test.ts new file mode 100644 index 00000000..d2e635f6 --- /dev/null +++ b/src/lib/build/workerPlugin.test.ts @@ -0,0 +1,286 @@ +import { describe, it, expect, vi } from "vitest"; + +// Mock getEsbuild so we can unit-test detection without the real wasm. +// The mock's transform is loader-aware: for "ts"/"tsx"/"jsx" it strips +// obvious TS/JSX constructs enough for acorn to parse. In practice, if +// the input is already valid JS, we just pass it through. +vi.mock("@/lib/esbuild", () => ({ + getEsbuild: vi.fn(async () => ({ + transform: vi.fn(async (source: string) => ({ code: source })), + })), +})); + +import { detectWorkersAndAssets } from "./workerPlugin"; + +const identityResolver = async (spec: string, importer: string): Promise => { + // A trivial resolver that pretends any relative/@ spec resolves to + // an absolute path. Extension determines whether it's a source file. + if (spec.startsWith("./") || spec.startsWith("../")) { + // Pretend to resolve by dropping the leading segment. + return importer.replace(/[^/]+$/, "") + spec.replace(/^\.\/?/, ""); + } + if (spec.startsWith("@/")) { + return "/project/src/" + spec.slice(2); + } + if (spec.startsWith("/")) { + return spec; + } + return undefined; +}; + +describe("detectWorkersAndAssets", () => { + it("returns source unchanged when file contains no `new URL(`", async () => { + const source = ` + import React from 'react'; + export const x = 1; + `; + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.code).toBe(source); + expect(result.workers).toEqual([]); + expect(result.assets).toEqual([]); + }); + + it("detects a module Worker with @/ alias specifier", async () => { + const source = [ + "const w = new Worker(", + " new URL('@/workers/my-worker.ts', import.meta.url),", + " { type: 'module' },", + ");", + ].join("\n"); + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.workers).toHaveLength(1); + expect(result.workers[0].resolvedPath).toBe("/project/src/workers/my-worker.ts"); + expect(result.workers[0].kind).toBe("Worker"); + // Placeholder should appear in the rewritten code. + expect(result.code).toContain(result.workers[0].placeholder); + // Original spec string should be gone. + expect(result.code).not.toContain("@/workers/my-worker.ts"); + // import.meta.url reference should be preserved. + expect(result.code).toContain("import.meta.url"); + }); + + it("detects a SharedWorker", async () => { + const source = ` + const w = new SharedWorker( + new URL('./w.ts', import.meta.url), + { type: 'module' }, + ); + `; + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.workers).toHaveLength(1); + expect(result.workers[0].kind).toBe("SharedWorker"); + }); + + it("errors on classic (non-module) worker", async () => { + const source = ` + const w = new Worker(new URL('./w.ts', import.meta.url)); + `; + await expect( + detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }), + ).rejects.toThrow(/type: 'module'/); + }); + + it("errors on non-literal worker specifier", async () => { + const source = ` + const p = './dyn.ts'; + const w = new Worker(new URL(p, import.meta.url), { type: 'module' }); + `; + await expect( + detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }), + ).rejects.toThrow(/string literal/i); + }); + + it("errors when worker specifier does not resolve", async () => { + const source = ` + const w = new Worker(new URL('./missing.ts', import.meta.url), { type: 'module' }); + `; + await expect( + detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: async () => undefined, + }), + ).rejects.toThrow(/could not resolve worker module/i); + }); + + it("detects plain new URL() asset and rewrites it", async () => { + const source = ` + const u = new URL('./logo.svg', import.meta.url); + console.log(u); + `; + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.assets).toHaveLength(1); + expect(result.assets[0].resolvedPath).toBe("/project/src/logo.svg"); + expect(result.code).toContain(result.assets[0].placeholder); + expect(result.code).not.toContain("./logo.svg"); + }); + + it("does not rewrite plain new URL() when target is a source file", async () => { + const source = ` + const u = new URL('./thing.ts', import.meta.url); + `; + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.assets).toEqual([]); + expect(result.code).toBe(source); + }); + + it("does not rewrite new URL() with a non-literal first argument", async () => { + const source = ` + const p = './thing.svg'; + const u = new URL(p, import.meta.url); + `; + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.assets).toEqual([]); + expect(result.workers).toEqual([]); + expect(result.code).toBe(source); + }); + + it("does not rewrite new URL() with an absolute https:// spec", async () => { + const source = ` + const u = new URL('https://example.com/x.png', import.meta.url); + `; + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.assets).toEqual([]); + expect(result.code).toBe(source); + }); + + it("does not double-rewrite the inner new URL() of a Worker", async () => { + const source = ` + const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' }); + `; + // Resolver returns a non-source extension for './w.ts' would + // otherwise ambiguously pull the inner URL into the asset pass. + // Using ts extension makes it unambiguous: worker match only. + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.workers).toHaveLength(1); + expect(result.assets).toHaveLength(0); + }); + + it("handles both workers and assets in the same file", async () => { + const source = ` + const img = new URL('./logo.png', import.meta.url); + const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' }); + `; + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.workers).toHaveLength(1); + expect(result.assets).toHaveLength(1); + expect(result.assets[0].resolvedPath).toBe("/project/src/logo.png"); + expect(result.workers[0].resolvedPath).toBe("/project/src/w.ts"); + // Both placeholders present. + expect(result.code).toContain(result.workers[0].placeholder); + expect(result.code).toContain(result.assets[0].placeholder); + }); + + it("does not match patterns inside string literals", async () => { + const source = [ + "const s = \"new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })\";", + ].join("\n"); + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.workers).toEqual([]); + expect(result.assets).toEqual([]); + expect(result.code).toBe(source); + }); + + it("does not match patterns inside line comments", async () => { + const source = [ + "// const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });", + "export const x = 1;", + ].join("\n"); + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.workers).toEqual([]); + expect(result.code).toBe(source); + }); + + it("supports double-quoted specifiers", async () => { + const source = ` + const w = new Worker(new URL("./w.ts", import.meta.url), { type: "module" }); + `; + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.workers).toHaveLength(1); + expect(result.code).toContain(result.workers[0].placeholder); + }); + + it("supports backtick-quoted specifiers with no interpolation", async () => { + const source = [ + "const w = new Worker(new URL(`./w.ts`, import.meta.url), { type: 'module' });", + ].join("\n"); + const result = await detectWorkersAndAssets({ + source, + filePath: "/project/src/a.ts", + ext: "ts", + resolveSpec: identityResolver, + }); + expect(result.workers).toHaveLength(1); + }); +}); diff --git a/src/lib/build/workerPlugin.ts b/src/lib/build/workerPlugin.ts new file mode 100644 index 00000000..411a4197 --- /dev/null +++ b/src/lib/build/workerPlugin.ts @@ -0,0 +1,438 @@ +// Detection and rewriting for the Vite/webpack-compatible worker and +// asset URL patterns: +// +// new Worker(new URL("", import.meta.url), { type: "module" }) +// new SharedWorker(new URL("", import.meta.url), { type: "module" }) +// new URL("", import.meta.url) // for non-source assets +// +// esbuild-wasm exposes no onTransform/onParse hook, so we can't reuse +// esbuild's internal AST. To avoid parsing every source file a second +// time, we prefilter with a cheap regex and only invoke acorn on files +// that contain a relevant construct. TS/JSX files are stripped via +// esbuild.transform before being handed to acorn so we don't need a +// TypeScript-aware parser. + +import * as acorn from "acorn"; +import jsx from "acorn-jsx"; +import { getEsbuild } from "@/lib/esbuild"; + +const ParserWithJsx = acorn.Parser.extend(jsx()); + +// Cheap prefilter: bail out for the 99% of files that contain no +// `new URL(` call at all. +const PREFILTER = /\bnew\s+URL\s*\(/; + +export interface WorkerMatch { + /** Unique placeholder token written into the source in place of the spec string. */ + placeholder: string; + /** Resolved absolute path of the worker entry in the VFS. */ + resolvedPath: string; + /** "Worker" or "SharedWorker". */ + kind: "Worker" | "SharedWorker"; +} + +export interface AssetMatch { + /** Unique placeholder token written into the source in place of the spec string. */ + placeholder: string; + /** Resolved absolute path of the asset in the VFS. */ + resolvedPath: string; +} + +export interface DetectResult { + /** The (possibly) rewritten source text. */ + code: string; + workers: WorkerMatch[]; + assets: AssetMatch[]; +} + +export interface DetectOptions { + /** The original source text as stored in the VFS. */ + source: string; + /** The path of the file being processed, for diagnostics. */ + filePath: string; + /** Extension of the source ("ts", "tsx", "js", "jsx", "mjs", "cjs"). */ + ext: string; + /** + * Resolve a module specifier relative to `filePath` against the VFS. + * Returns the resolved absolute path, or undefined if no file exists. + */ + resolveSpec: (spec: string, importerPath: string) => Promise; +} + +/** + * Source-code extensions that must NOT be treated as plain asset URLs. + * These should go through a regular import or the Worker pattern. + */ +const SOURCE_EXTENSIONS = new Set([ + "ts", + "tsx", + "js", + "jsx", + "mjs", + "cjs", + "css", +]); + +let placeholderCounter = 0; +function nextPlaceholder(prefix: "WORKER" | "ASSET"): string { + placeholderCounter += 1; + return `__SHAKESPEARE_${prefix}_URL_${placeholderCounter.toString(36)}__`; +} + +/** + * Scan a source file for Worker / SharedWorker / asset URL patterns. + * Returns the rewritten source along with the collected matches. + * + * Throws with a human-readable message when a problem is found that + * should fail the build (classic worker, non-literal specifier, + * unresolvable specifier). + */ +export async function detectWorkersAndAssets( + options: DetectOptions, +): Promise { + const { source, filePath, ext, resolveSpec } = options; + + // Fast path: no `new URL(` anywhere. + if (!PREFILTER.test(source)) { + return { code: source, workers: [], assets: [] }; + } + + // Strip TS/JSX so acorn can parse it. We only reach this branch for + // files that contain `new URL(`, which is rare, so the transform + // cost is paid for very few files per build. + let jsSource = source; + const needsStrip = ext === "ts" || ext === "tsx" || ext === "jsx"; + if (needsStrip) { + try { + const esbuild = await getEsbuild(); + const result = await esbuild.transform(source, { + loader: ext === "ts" ? "ts" : ext === "tsx" ? "tsx" : "jsx", + sourcemap: false, + sourcefile: filePath, + // Preserve the shape of the source as much as possible; we're + // only using the output to parse, not to emit. + target: "esnext", + }); + jsSource = result.code; + } catch { + // If the transform itself fails, skip worker detection; esbuild's + // main pass will surface the syntax error with a proper location. + return { code: source, workers: [], assets: [] }; + } + } + + // Parse. + let ast: acorn.Node; + try { + ast = ParserWithJsx.parse(jsSource, { + ecmaVersion: "latest", + sourceType: "module", + allowHashBang: true, + allowAwaitOutsideFunction: true, + }); + } catch { + // If acorn can't parse (possibly because of syntax esbuild supports + // that acorn doesn't), skip detection and let the main build + // surface any real error. + return { code: source, workers: [], assets: [] }; + } + + // Walk the AST to find NewExpression nodes we care about. + // We operate on the stripped jsSource for position information, but + // the returned `code` must be the ORIGINAL source with rewrites + // applied. Since replacements are string-literal values (the first + // argument of `new URL`), we search for those literals in the + // original source to do the rewrite. This avoids any dependence on + // post-TS-strip positions. + const workers: WorkerMatch[] = []; + const assets: AssetMatch[] = []; + // Map spec -> list of { kind: "worker" | "asset", placeholder, resolvedPath } + // collected during the AST walk. We rewrite afterwards so that each + // *occurrence* of the spec in the original source that parses back + // to the same construct gets its own placeholder. + interface PendingRewrite { + spec: string; + kind: "worker" | "asset"; + workerKind?: "Worker" | "SharedWorker"; + resolvedPath: string; + } + const pending: PendingRewrite[] = []; + + const seenUrlNodes = new WeakSet(); + + const walk = async (node: acorn.Node | null | undefined): Promise => { + if (!node || typeof node !== "object") return; + // Process this node first (so Worker sees its inner new URL before + // the asset pass does). + await visit(node); + // Recurse into all child nodes. + for (const key of Object.keys(node)) { + if (key === "type" || key === "start" || key === "end" || key === "loc") continue; + const value = (node as unknown as Record)[key]; + if (Array.isArray(value)) { + for (const child of value) { + if (child && typeof child === "object" && "type" in child) { + await walk(child as acorn.Node); + } + } + } else if (value && typeof value === "object" && "type" in value) { + await walk(value as acorn.Node); + } + } + }; + + const visit = async (node: acorn.Node): Promise => { + if (node.type !== "NewExpression") return; + const newExpr = node as unknown as { + type: "NewExpression"; + callee: { type: string; name?: string }; + arguments: acorn.Node[]; + start: number; + end: number; + }; + const calleeName = + newExpr.callee.type === "Identifier" ? newExpr.callee.name : undefined; + + if (calleeName === "Worker" || calleeName === "SharedWorker") { + // new Worker(new URL(, import.meta.url), ?) + const [arg0, arg1] = newExpr.arguments; + if (!isNewUrlWithImportMeta(arg0)) { + // Not the Vite pattern — leave alone. + return; + } + const urlNode = arg0 as unknown as { + type: "NewExpression"; + arguments: acorn.Node[]; + }; + const specNode = urlNode.arguments[0]; + if (!isStringLiteral(specNode)) { + throw new Error( + `${filePath}: new ${calleeName}(new URL(...)) requires a string literal as the first argument to new URL(). Dynamic specifiers are not supported.`, + ); + } + // Require { type: 'module' } as the second argument. + if (!hasTypeModuleOption(arg1)) { + throw new Error( + `${filePath}: new ${calleeName}(new URL(...)) must pass { type: 'module' } as its second argument. Shakespeare does not support classic workers.`, + ); + } + const spec = readStringLiteral(specNode)!; + const resolvedPath = await resolveSpec(spec, filePath); + if (!resolvedPath) { + throw new Error( + `${filePath}: could not resolve worker module '${spec}'.`, + ); + } + // Mark the inner `new URL(...)` as "consumed" so the asset pass + // below doesn't also rewrite it. + seenUrlNodes.add(arg0); + pending.push({ + spec, + kind: "worker", + workerKind: calleeName, + resolvedPath, + }); + return; + } + + if (calleeName === "URL") { + if (seenUrlNodes.has(node)) return; + if (!isNewUrlWithImportMeta(node)) return; + const specNode = newExpr.arguments[0]; + if (!isStringLiteral(specNode)) { + // Non-literal `new URL(...)` is legal and common for runtime + // URL construction. Don't touch it. + return; + } + const spec = readStringLiteral(specNode)!; + // Only rewrite specs that look like module-relative paths. + // Anything else (absolute https://, etc.) is almost certainly a + // runtime URL and not a bundle asset reference. + if (!isRelativeOrAliasSpec(spec)) return; + const resolvedPath = await resolveSpec(spec, filePath); + if (!resolvedPath) { + // Can't resolve — probably a runtime URL; leave alone. + return; + } + // Skip source files — these should go through normal imports or + // the Worker pattern. + const resolvedExt = resolvedPath.split(".").pop()?.toLowerCase() ?? ""; + if (SOURCE_EXTENSIONS.has(resolvedExt)) { + // Emit a console warning but don't fail the build. + console.warn( + `${filePath}: new URL('${spec}', import.meta.url) references a source file. Shakespeare only rewrites non-source assets via this pattern. Use a regular import or new Worker() instead.`, + ); + return; + } + pending.push({ spec, kind: "asset", resolvedPath }); + } + }; + + await walk(ast); + + if (pending.length === 0) { + return { code: source, workers: [], assets: [] }; + } + + // Now apply the rewrites to the ORIGINAL source by replacing the + // string-literal spec. Each `pending` entry consumes the first + // remaining occurrence of its literal form so multiple identical + // specs each get their own placeholder. + // + // Match a quoted literal whose content equals `spec`. We match + // single quotes, double quotes, or backticks (template literal + // without interpolation) to cover all reasonable TS/JS source + // styles. + let code = source; + for (const entry of pending) { + const placeholder = nextPlaceholder(entry.kind === "worker" ? "WORKER" : "ASSET"); + const { literal, index } = findNextSpecLiteral(code, entry.spec); + if (literal === null || index < 0) { + // Shouldn't normally happen (we parsed it); be defensive. + throw new Error( + `${filePath}: internal error rewriting new URL('${entry.spec}', ...); could not locate the literal in source.`, + ); + } + const before = code.slice(0, index); + const after = code.slice(index + literal.length); + // Preserve the quote style of the original literal. + const quote = literal[0]; + code = before + quote + placeholder + quote + after; + + if (entry.kind === "worker") { + workers.push({ + placeholder, + resolvedPath: entry.resolvedPath, + kind: entry.workerKind!, + }); + } else { + assets.push({ placeholder, resolvedPath: entry.resolvedPath }); + } + } + + return { code, workers, assets }; +} + +function isNewUrlWithImportMeta(node: acorn.Node | null | undefined): boolean { + if (!node || node.type !== "NewExpression") return false; + const n = node as unknown as { + callee: { type: string; name?: string }; + arguments: acorn.Node[]; + }; + if (n.callee.type !== "Identifier" || n.callee.name !== "URL") return false; + if (n.arguments.length < 2) return false; + return isImportMetaUrl(n.arguments[1]); +} + +function isImportMetaUrl(node: acorn.Node | undefined): boolean { + if (!node || node.type !== "MemberExpression") return false; + const m = node as unknown as { + object: { type: string; meta?: { name?: string }; property?: { name?: string } }; + property: { type: string; name?: string }; + computed: boolean; + }; + if (m.computed) return false; + if (m.property.type !== "Identifier" || m.property.name !== "url") return false; + if (m.object.type !== "MetaProperty") return false; + if (m.object.meta?.name !== "import") return false; + if (m.object.property?.name !== "meta") return false; + return true; +} + +function isStringLiteral(node: acorn.Node | undefined): boolean { + return readStringLiteral(node) !== undefined; +} + +function readStringLiteral(node: acorn.Node | undefined): string | undefined { + if (!node) return undefined; + if (node.type === "Literal") { + const v = (node as unknown as { value: unknown }).value; + return typeof v === "string" ? v : undefined; + } + if (node.type === "TemplateLiteral") { + const tl = node as unknown as { + expressions: unknown[]; + quasis: Array<{ value: { cooked?: string } }>; + }; + if (tl.expressions.length === 0 && tl.quasis.length === 1 && + typeof tl.quasis[0].value.cooked === "string") { + return tl.quasis[0].value.cooked; + } + } + return undefined; +} + +function hasTypeModuleOption(node: acorn.Node | undefined): boolean { + if (!node || node.type !== "ObjectExpression") return false; + const obj = node as unknown as { + properties: Array<{ + type: string; + key: { type: string; name?: string; value?: unknown }; + value: { type: string; value?: unknown }; + computed: boolean; + }>; + }; + for (const prop of obj.properties) { + if (prop.type !== "Property" || prop.computed) continue; + let keyName: string | undefined; + if (prop.key.type === "Identifier") { + keyName = prop.key.name; + } else if (prop.key.type === "Literal" && typeof prop.key.value === "string") { + keyName = prop.key.value; + } + if (keyName !== "type") continue; + if (prop.value.type === "Literal" && prop.value.value === "module") { + return true; + } + } + return false; +} + +function isRelativeOrAliasSpec(spec: string): boolean { + return ( + spec.startsWith("./") || + spec.startsWith("../") || + spec.startsWith("/") || + spec.startsWith("@/") + ); +} + +/** + * Find the next occurrence of a string literal with the given content + * in `source`. Searches for `'spec'`, `"spec"`, and `` `spec` ``. The + * simplest, correct way: search for each possible quoted form and + * pick the earliest occurrence. + */ +function findNextSpecLiteral( + source: string, + spec: string, +): { literal: string | null; index: number } { + // Build the three possible source-text forms of the literal. + const candidates = [ + encodeAsLiteral(spec, "'"), + encodeAsLiteral(spec, '"'), + encodeAsLiteral(spec, "`"), + ]; + + let bestIdx = -1; + let best: string | null = null; + for (const lit of candidates) { + const idx = source.indexOf(lit); + if (idx >= 0 && (bestIdx < 0 || idx < bestIdx)) { + bestIdx = idx; + best = lit; + } + } + return { literal: best, index: bestIdx }; +} + +function encodeAsLiteral(value: string, quote: "'" | '"' | "`"): string { + // We don't do full JS escape handling — the spec is the parsed + // (decoded) value of a string literal, so the common case is that + // the literal appears in source verbatim as quote + value + quote. + // Escaped characters in the original source (e.g. \n) would + // de-encode to different bytes and won't match here, which means we + // fall through to the "internal error" case. In practice worker + // specs are paths with no escapes, so this is fine. + return quote + value + quote; +}