diff --git a/docs/scenarios/04-browser-field-remapping.md b/docs/scenarios/04-browser-field-remapping.md index dac5174..7408e4a 100644 --- a/docs/scenarios/04-browser-field-remapping.md +++ b/docs/scenarios/04-browser-field-remapping.md @@ -181,9 +181,9 @@ Expected: `getRuntimeDefaults("edge-light")` returns `{ conditions: ["edge-light **Regression signal:** If Cloudflare Workers builds get browser field remappings applied, the `browserField: false` override is not working. If Vercel Edge builds do NOT get remappings, the `browserField: true` setting is being ignored. -## 4.7 — Browser field remapping for relative imports (HttpPlugin) +## 4.7 — Browser field remapping for relative imports (PackagePlugin) -**What it tests:** The HttpPlugin applies browser field remappings to relative imports *within* a package, not just at entry point resolution. +**What it tests:** The PackagePlugin applies browser field remappings to relative imports *within* a package, not just at entry point resolution. > **This is the scenario that caught the original bug.** The CdnPlugin resolved the entry point correctly, but relative imports inside the package were not being remapped. @@ -206,9 +206,9 @@ Expected: `getRuntimeDefaults("edge-light")` returns `{ conditions: ["edge-light When `utf8.js` internally imports `"./fallback/platform.js"`: 1. CdnPlugin resolves the entry point (`./index.js` from `main`, since `browser` is an object) -2. CdnPlugin passes `packageBaseUrl` in `pluginData` +2. CdnPlugin passes `manifest` and `packageBaseUrl` in `pluginData` 3. HttpPlugin resolves the relative import: `urlJoin(parentUrl, "../", "./fallback/platform.js")` -4. HttpPlugin strips `packageBaseUrl` → gets `"./fallback/platform.js"` +4. PackagePlugin intercepts (onResolve, HTTP namespace) — strips `packageBaseUrl` → gets `"./fallback/platform.js"` 5. `applyManifestRemappings()` checks `browser` field → remaps to `"./fallback/platform.browser.js"` 6. URL is reconstructed with the remapped path @@ -219,7 +219,7 @@ When `utf8.js` internally imports `"./fallback/platform.js"`: ## 4.8 — Browser field exclusion for relative imports -**What it tests:** When a browser field maps an internal relative import to `false`, the HttpPlugin returns an error. +**What it tests:** When a browser field maps an internal relative import to `false`, the PackagePlugin returns an exclusion result. **Synthetic test:** A package whose browser field excludes an internal file: @@ -233,6 +233,6 @@ When `utf8.js` internally imports `"./fallback/platform.js"`: When internal code does `import impl from "./lib/native-impl.js"`: -Expected: `applyManifestRemappings()` returns `{ excluded: true, matchedField: "browser" }` → HttpPlugin returns an esbuild error: `"Module "./lib/native-impl.js" excluded by "browser" field"`. +Expected: `applyManifestRemappings()` returns `{ excluded: true, matchedField: "browser" }` → PackagePlugin checks `remapFalse.importRemapFalse` policy. With the default `"stub"` policy, it returns the import in the `EXCLUDED_MODULE_NAMESPACE`, replacing it with an empty export stub. With `"error"`, it produces a build error. **Regression signal:** If the excluded file is silently fetched (and probably 404s or returns wrong content), the `false` exclusion for relative imports is not being enforced. diff --git a/docs/scenarios/05-platform-remapping.md b/docs/scenarios/05-platform-remapping.md index 01ad1c8..87511a2 100644 --- a/docs/scenarios/05-platform-remapping.md +++ b/docs/scenarios/05-platform-remapping.md @@ -50,7 +50,7 @@ Expected: `react-native` field ignored → `module` → `lib/module/index.js`. ## 5.2 — React Native object-form path remapping -**What it tests:** The `react-native` top-level field as an object (just like browser field object form). The HttpPlugin applies remappings for relative imports when the `react-native` condition is active. +**What it tests:** The `react-native` top-level field as an object (just like browser field object form). PackagePlugin applies remappings for relative imports when the `react-native` condition is active. **Package:** `@exodus/bytes@1.13.0` @@ -191,14 +191,14 @@ Internal imports like `"./fallback/platform.js"` resolve to the original path (t When internal code imports `"./lib/dom-impl.js"`: -Expected: `react-native` field matches → value is `false` → `applyManifestRemappings()` returns `{ excluded: true, matchedField: "react-native" }` → HttpPlugin returns error: `"Module "./lib/dom-impl.js" excluded by "react-native" field"`. +Expected: `react-native` field matches → value is `false` → `applyManifestRemappings()` returns `{ excluded: true, matchedField: "react-native" }` → PackagePlugin calls `buildExclusionResult()`, which checks `remapFalse.importRemapFalse` policy. With the default `"stub"` policy, returns the import in the `EXCLUDED_MODULE_NAMESPACE` (empty export stub). With `"error"`, produces a build error mentioning the `react-native` field. **Regression signal:** If the error message says `"excluded by "browser" field"` when the match came from `react-native`, the `matchedField` is not being propagated correctly. ## 5.7 — Remapping only applies to relative imports, not entry points -**What it tests:** The generalized `applyManifestRemappings()` is only called by the HttpPlugin for relative imports within a package. Entry point resolution follows its own path through `resolveLegacy()`. +**What it tests:** The generalized `applyManifestRemappings()` is only called by PackagePlugin for relative imports within a package. Entry point resolution follows its own path through `resolveLegacy()`. **Package:** `@exodus/bytes@1.13.0` @@ -206,11 +206,11 @@ Expected: `react-native` field matches → value is `false` → `applyManifestRe /?q=@exodus/bytes@1.13.0 ``` -The *entry point* resolution goes through `resolveLegacy()`, which handles `browser` string/object field for the entry point. The *internal relative imports* go through `applyManifestRemappings()` in the HttpPlugin. +The *entry point* resolution goes through `resolveLegacy()`, which handles `browser` string/object field for the entry point. The *internal relative imports* go through `applyManifestRemappings()` in PackagePlugin's onResolve handlers. These are two separate code paths: 1. `CdnPlugin → resolvePackageEntry() → resolveLegacy()` — entry point -2. `HttpPlugin → HttpResolution → applyManifestRemappings()` — relative imports +2. `PackagePlugin → onResolve → applyManifestRemappings()` — relative imports Both must apply remappings, but through different mechanisms. diff --git a/docs/scenarios/12-runtime-conditions.md b/docs/scenarios/12-runtime-conditions.md index a394213..6186d70 100644 --- a/docs/scenarios/12-runtime-conditions.md +++ b/docs/scenarios/12-runtime-conditions.md @@ -190,11 +190,11 @@ Expected: `isRequireContext()` returns `true` (entry-point with CJS format) → **Regression signal:** If the CJS build gets the ESM entry, the import/require dimension is not being derived from format. -## 12.12 — Conditions flow through to HttpPlugin remapping +## 12.12 — Conditions flow through to PackagePlugin remapping -**What it tests:** The conditions computed for CdnPlugin resolution are also available to the HttpPlugin for manifest field remapping. +**What it tests:** The conditions computed for CdnPlugin resolution are also available to PackagePlugin for manifest field remapping. -This is the end-to-end test: conditions are computed in CdnPlugin, stored implicitly via the `effectiveResolveOpts`, and recomputed in HttpPlugin's `HttpResolution` for the `applyManifestRemappings()` call. +This is the end-to-end test: conditions are computed in CdnPlugin, stored implicitly via the `effectiveResolveOpts`, and recomputed in PackagePlugin's onResolve handler via `getResolverConditions(args, effectiveResolveOpts)` for the `applyManifestRemappings()` call. **Package:** `@exodus/bytes@1.13.0` with React Native runtime: @@ -202,6 +202,6 @@ This is the end-to-end test: conditions are computed in CdnPlugin, stored implic /?q=@exodus/bytes@1.13.0&config={"resolve":{"runtime":"react-native"}} ``` -Expected: CdnPlugin resolves the entry point. HttpPlugin resolves relative imports. The HttpPlugin recomputes conditions via `getResolverConditions(args, effectiveResolveOpts)` → includes `"react-native"` → `applyManifestRemappings()` uses the `"react-native"` field. +Expected: CdnPlugin resolves the entry point. PackagePlugin intercepts relative imports (onResolve, HTTP namespace). PackagePlugin recomputes conditions via `getResolverConditions(args, effectiveResolveOpts)` → includes `"react-native"` → `applyManifestRemappings()` uses the `"react-native"` field. -**Regression signal:** If HttpPlugin produces different conditions than CdnPlugin (e.g., missing the runtime overlay), the `effectiveResolveOpts` propagation is broken. This would manifest as entry-point resolution using React Native paths but internal imports using browser paths. +**Regression signal:** If PackagePlugin produces different conditions than CdnPlugin (e.g., missing the runtime overlay), the `effectiveResolveOpts` propagation is broken. This would manifest as entry-point resolution using React Native paths but internal imports using browser paths. diff --git a/docs/scenarios/15-plugin-pipeline.md b/docs/scenarios/15-plugin-pipeline.md index c08470a..e096448 100644 --- a/docs/scenarios/15-plugin-pipeline.md +++ b/docs/scenarios/15-plugin-pipeline.md @@ -2,10 +2,10 @@ ## What this covers -The bundlejs esbuild pipeline registers **six plugins in a fixed order**: +The bundlejs esbuild pipeline registers **seven plugins in a fixed order**: ``` -AliasPlugin → ExternalPlugin → TarballPlugin → VFSPlugin → HttpPlugin → CdnPlugin +AliasPlugin → ExternalPlugin → TarballPlugin → PackagePlugin → VFSPlugin → HttpPlugin → CdnPlugin ``` Registration order is load-bearing: esbuild calls `onResolve` / `onLoad` handlers @@ -17,11 +17,12 @@ document explains the key invariants each plugin must uphold and how they intera | Plugin | Namespace | Core job | |---|---|---| | **AliasPlugin** | `alias-globals` | Rewrites import paths before any other resolution. Strips `node:` prefix, checks `isAlias()`. | -| **ExternalPlugin** | `external-globals` | Marks Node.js builtins as external (empty export) or redirects to polyfills when `polyfill: true`. | +| **ExternalPlugin** | `external-globals`, `excluded-module` | Marks Node.js builtins as external (empty export) or redirects to polyfills when `polyfill: true`. Serves empty stubs for modules excluded by manifest field remappings. | | **TarballPlugin** | `tarball-url` | Detects and extracts tarball archives (HTTP URLs, VFS paths) via `archive-detect` delegation. Handles pkg.pr.new, registry tarballs, GitHub releases, and VFS `.tgz` files. Must run before VFS. | -| **VFSPlugin** | `virtual-filesystem` | Serves in-memory files (entry points, user code). Scoped handlers prevent accidental VFS intercepts of HTTP-relative imports. | -| **HttpPlugin** | `http-url` | Fetches HTTP URLs, probes extensions, applies browser-field / manifest remapping on relative imports. | -| **CdnPlugin** | `cdn-url` | Catch-all for bare npm imports. Resolves versions, fetches package.json, computes entry point, and hands off to HttpPlugin. | +| **PackagePlugin** | `package-features` | Central hub for per-file enrichment and content loading. Owns onResolve for both VFS and HTTP namespaces (sideEffects, manifest remapping). Owns onLoad for both namespaces (fetch/read, Flow stripping, loader inference, asset discovery). | +| **VFSPlugin** | `virtual-filesystem` | Resolve-only: maps VFS-prefixed, absolute, and relative paths to canonical VFS paths. No content loading (PackagePlugin handles onLoad). | +| **HttpPlugin** | `http-url` | Resolve-only: routes HTTP URLs to the `http-url` namespace and resolves relative imports against parent URLs. No content loading or manifest remapping (PackagePlugin handles both). | +| **CdnPlugin** | `cdn-url` | Catch-all for bare npm imports. Resolves versions, fetches package.json, computes entry point, and delegates to PackagePlugin via `build.resolve()`. | ## Key invariants tested @@ -94,40 +95,510 @@ Plugins communicate via the `pluginData` object on resolve/load results: | Field | Set by | Used by | Purpose | |---|---|---|---| -| `url` | HttpPlugin (onLoad) | HttpPlugin (onResolve) | Base for relative import resolution (post-redirect URL) | -| `manifest` | CdnPlugin | HttpPlugin | Package.json for browser-field remapping | -| `packageBaseUrl` | CdnPlugin | HttpPlugin | Strip prefix to get package-relative path for remapping | +| `url` | PackagePlugin (onLoad, HTTP) | HttpPlugin (onResolve), PackagePlugin (onResolve) | Base for relative import resolution (post-redirect URL) | +| `manifest` | CdnPlugin, TarballPlugin | PackagePlugin (onResolve, both namespaces) | Package.json for browser-field remapping + sideEffects computation | +| `packageBaseUrl` | CdnPlugin | PackagePlugin (onResolve, HTTP namespace) | Strip prefix to get package-relative path for remapping (HTTP packages) | +| `packageRoot` | TarballPlugin | PackagePlugin (onResolve, VFS namespace) | VFS directory root for computing package-relative paths (tarball packages) | +| `cdnOrigin` | HttpPlugin (onResolve) | CdnPlugin (onResolve) | Preserves CDN-follows-parent behavior when delegating bare imports via `build.resolve()` | +| `excludedBy` | PackagePlugin (exclusion) | ExternalPlugin (onLoad) | Which manifest field caused the exclusion (for diagnostic messages) | +| `suppressWarning` | PackagePlugin (exclusion) | ExternalPlugin (onLoad) | Whether to suppress the stub warning (from `remapFalse.warnOnStubbedRemapFalse`) | +| `importer` | PackagePlugin (onLoad, VFS) | — | The original import path (for debugging/diagnostics) | + + +### 7a. The `build.resolve()` delegation pattern + +> **Why this exists.** esbuild's plugin API is first-match-wins: the first +> `onResolve` handler that returns a non-`undefined` result determines the +> module's path, namespace, and `sideEffects` hint. Before PackagePlugin, +> enrichment (sideEffects + manifest remapping) was split across multiple +> plugins, with gaps — tarball-extracted VFS files got no sideEffects, and +> no browser-field remapping. The fix: transport plugins (Cdn, Tarball, Http) +> resolve paths and then **re-enter the plugin chain** via `build.resolve()`, +> allowing PackagePlugin to intercept and enrich before the final result +> reaches esbuild. + +The `build.resolve()` function re-invokes the plugin chain from the current +plugin's position onward. By calling it with the resolved URL/path plus package +context in `pluginData`, the transport plugin hands off to PackagePlugin for +enrichment without duplicating that logic. + +**Three delegation sites in the codebase:** + +``` + ┌──────────────────────────────────────────────────────────────────────┐ + │ Site 1: CdnPlugin → PackagePlugin (entry-point delegation) │ + │ │ + │ CdnPlugin resolves a bare import to an HTTP URL + package.json, │ + │ then delegates: │ + │ │ + │ build.resolve(finalUrl, { │ + │ namespace: "http-url", │ + │ pluginData: { │ + │ manifest: resolvedManifest, │ + │ packageBaseUrl: "https://unpkg.com/react@19.0.0/" │ + │ } │ + │ }) │ + │ │ + │ PackagePlugin's HTTP onResolve intercepts: │ + │ • Computes sideEffects from manifest │ + │ • Applies any browser-field remapping │ + │ • Returns enriched result │ + └──────────────────────────────────────────────────────────────────────┘ + + ┌──────────────────────────────────────────────────────────────────────┐ + │ Site 2: HttpPlugin → CdnPlugin (bare import delegation) │ + │ │ + │ When HttpPlugin encounters a bare import within HTTP namespace │ + │ (e.g., "lodash" imported from a CDN-fetched file), it delegates │ + │ back through the chain: │ + │ │ + │ build.resolve("lodash", { │ + │ pluginData: { │ + │ ...parentPluginData, │ + │ cdnOrigin: "https://esm.sh" // CDN-follows-parent │ + │ } │ + │ }) │ + │ │ + │ This re-enters the chain from HttpPlugin's position onward. │ + │ CdnPlugin catches it (catch-all for bare imports) and resolves │ + │ using the parent's CDN origin, then delegates back to │ + │ PackagePlugin via Site 1. │ + └──────────────────────────────────────────────────────────────────────┘ + + ┌──────────────────────────────────────────────────────────────────────┐ + │ Site 3: CdnPlugin → TarballPlugin (registry mode delegation) │ + │ │ + │ When cdn is "npm.registry", CdnPlugin constructs a tarball URL │ + │ and delegates: │ + │ │ + │ build.resolve(tarballUrl, { │ + │ pluginData: args.pluginData │ + │ }) │ + │ │ + │ TarballPlugin intercepts (it runs before PackagePlugin), │ + │ extracts the tarball to VFS, and resolves the entry point. │ + │ The resulting VFS path carries packageRoot + manifest in │ + │ pluginData, which PackagePlugin's VFS onResolve then enriches │ + │ on subsequent relative imports. │ + └──────────────────────────────────────────────────────────────────────┘ +``` + +**End-to-end: a CDN bare import through the full delegation chain:** + +``` + User code: import { debounce } from "lodash-es" + │ + ▼ 1. AliasPlugin (onResolve) + No alias match → pass + │ + ▼ 2. ExternalPlugin (onResolve) + Not a builtin → pass + │ + ▼ 3. TarballPlugin (onResolve) + Not a tarball URL → pass + │ + ▼ 4. PackagePlugin (onResolve, VFS filter: /^[.\/]/) + "lodash-es" doesn't match filter → skip + │ + ▼ 4. PackagePlugin (onResolve, HTTP filter: /^(https?:\/\/|[.\/])/) + "lodash-es" doesn't match filter → skip + │ + ▼ 5. VFSPlugin (onResolve) + Not a VFS path → pass + │ + ▼ 6. HttpPlugin (onResolve, filter: /^https?:\/\//) + Not an HTTP URL → skip + │ + ▼ 6. HttpPlugin (onResolve, filter: /.*/, http-url ns) + Wrong namespace → skip + │ + ▼ 7. CdnPlugin (onResolve) + Bare import! Resolves: + a. parsePackageName("lodash-es") → { name, version } + b. Fetch package.json from CDN + c. resolvePackageEntry() → "./lodash.js" + d. Compute entry URL → "https://unpkg.com/lodash-es@4.17.21/lodash.js" + e. build.resolve(entryUrl, { ◄── DELEGATION SITE 1 + namespace: "http-url", + pluginData: { manifest, packageBaseUrl } + }) + │ + ▼ Re-enters chain from CdnPlugin's position (no earlier plugin sees it) + │ + ▼ PackagePlugin (onResolve, HTTP namespace) + packageBaseUrl exists → enrichment activates: + a. toPackageRelative() → "./lodash.js" + b. applyManifestRemappings() → no remapping + c. computeEsbuildSideEffects() → sideEffects: false (lodash-es declares it) + d. Returns { path: entryUrl, namespace: "http-url", sideEffects: false } + │ + ▼ esbuild has the resolved module. Now loads it: + │ + ▼ PackagePlugin (onLoad, HTTP namespace) + Only onLoad for http-url (registered first): + a. determineExtension() → fetch with extension probing + b. Store in VFS for bundle analyzer + c. fetchAssets() → discover WASM/Workers + d. maybeStripFlow() → no Flow in lodash + e. inferLoader() → "js" + f. Returns { contents, loader: "js", pluginData: { url: finalUrl } } + │ + ▼ esbuild parses the JS, finds: import debounce from "./debounce.js" + │ + ▼ PackagePlugin (onResolve, HTTP namespace) + resolvedUrl = urlJoin(parentUrl, "../", "./debounce.js") + → "https://unpkg.com/lodash-es@4.17.21/debounce.js" + Starts with packageBaseUrl → enrichment: + sideEffects: false (from lodash-es manifest) + │ + ▼ PackagePlugin (onLoad, HTTP namespace) + Fetch, store, infer loader → returns content + │ + ▼ ... continues for each transitive import ... +``` + +**End-to-end: a tarball-extracted VFS import through the delegation chain:** + +``` + User code: import { sql } from "drizzle-orm" (with cdn: "npm.registry") + │ + ▼ 7. CdnPlugin (onResolve, REGISTRY_CDN branch) + Registry mode → construct tarball URL: + "https://registry.npmjs.org/drizzle-orm/-/drizzle-orm-0.45.1.tgz" + build.resolve(tarballUrl, { pluginData }) ◄── DELEGATION SITE 3 + │ + ▼ 3. TarballPlugin (onResolve) + isTarballUrl() → true → extract to VFS: + /__tarballs__// + resolvePackageEntry(manifest, "", conditions) → "./dist/index.js" + Returns { + path: "/__tarballs__//dist/index.js", + namespace: "virtual-filesystem", + sideEffects: , + pluginData: { packageRoot, manifest } + } + │ + ▼ esbuild has the resolved module. Now loads it: + │ + ▼ 4. PackagePlugin (onLoad, VFS namespace) + Only onLoad for virtual-filesystem: + a. getFile() → read from VFS + b. maybeStripFlow() → strip if Flow detected + c. inferLoader() → "ts" or "tsx" + d. resolveDir = dirname(args.path) + e. Returns { contents, loader, resolveDir } + │ + ▼ esbuild parses, finds: import { Column } from "./column.js" + │ + ▼ 4. PackagePlugin (onResolve, VFS namespace) + packageRoot exists → enrichment: + a. resolve(resolveDir, "./column.js") + → "/__tarballs__//dist/column.js" + b. Starts with packageRoot → enrichment activates + c. toPackageRelative() → "./dist/column.js" + d. applyManifestRemappings() → check browser field + e. resolveVfsPath() → probe extensions in VFS + f. computeEsbuildSideEffects() + g. Returns { path, namespace: "virtual-filesystem", sideEffects } + │ + ▼ 4. PackagePlugin (onLoad, VFS namespace) + Read, strip Flow if needed, infer loader → returns content + │ + ▼ ... continues for each transitive import ... +``` ### 8. CDN style routing `getCDNStyle()` classifies URLs into routing categories: -| Input pattern | Style | Plugin | -|---|---|---| -| `https://unpkg.com/...` | `npm` | HttpPlugin | -| `https://pkg.pr.new/...` | `tarball` | TarballPlugin | -| `jsr:@std/...` | `jsr` | CdnPlugin (JSR path) | -| `github:user/repo` | `github` | HttpPlugin | -| `react` (bare import) | `other` | CdnPlugin | +| Input pattern | Style | Resolved by | Content loaded by | +|---|---|---|---| +| `https://unpkg.com/...` | `npm` | HttpPlugin (onResolve) | PackagePlugin (onLoad, HTTP) | +| `https://pkg.pr.new/...` | `tarball` | TarballPlugin | PackagePlugin (onLoad, VFS) | +| `jsr:@std/...` | `jsr` | CdnPlugin (JSR path) | PackagePlugin (onLoad, HTTP) | +| `github:user/repo` | `github` | HttpPlugin | PackagePlugin (onLoad, HTTP) | +| `react` (bare import) | `other` | CdnPlugin → PackagePlugin | PackagePlugin (onLoad, HTTP) | +| `npm.registry` (cdn mode) | `registry` | CdnPlugin → TarballPlugin | PackagePlugin (onLoad, VFS) | + + +### 9. PackagePlugin: the enrichment and content-loading hub + +PackagePlugin (`core/plugins/package.ts`) registers **four handlers** — two `onResolve` +(enrichment) and two `onLoad` (content loading) — covering both the VFS and HTTP namespaces. + +**Why it exists.** Before PackagePlugin, enrichment and content loading were split across +four plugins with gaps: + +| Concern | CDN path (before) | VFS path (before) | After (PackagePlugin) | +|---|---|---|---| +| sideEffects | CdnPlugin (entry only) | ❌ Missing | ✅ Both namespaces | +| Manifest remapping | HttpPlugin (onResolve) | ❌ Missing | ✅ Both namespaces | +| Flow stripping | HttpPlugin (onLoad) | VFSPlugin (onLoad) | ✅ PackagePlugin (onLoad) | +| Content loading | HttpPlugin (onLoad) | VFSPlugin (onLoad) | ✅ PackagePlugin (onLoad) | + +**Handler registration order within PackagePlugin:** + +``` + PackagePlugin.setup(build) registers: + │ + ├── 1. onResolve (VFS namespace, filter: /^[.\/]/) + │ Enriches relative/absolute imports within tarball packages + │ + ├── 2. onResolve (HTTP namespace, filter: /^(https?:\/\/|[.\/])/) + │ Enriches URL imports within CDN packages + │ + ├── 3. onLoad (VFS namespace, filter: /.*/) + │ Reads VFS content, Flow stripping, loader inference + │ + └── 4. onLoad (HTTP namespace, filter: /.*/) + Extension probing, HTTP fetch, VFS storage, asset discovery, + Flow stripping, loader inference +``` + +Because PackagePlugin is registered **before** VFSPlugin and HttpPlugin, its +handlers take priority. When PackagePlugin's `onResolve` returns `undefined` +(no package context), the downstream plugin handles the import. + +#### 9a. VFS onResolve: tarball package enrichment + +**Activation condition:** `pluginData.packageRoot` AND `pluginData.manifest` both exist +(set by TarballPlugin during entry-point resolution). + +``` + Relative import from tarball-extracted file + e.g., import "./lib/stream.js" from /__tarballs__//index.js + │ + ▼ Resolve candidate path + resolve(resolveDir, "./lib/stream.js") + → "/__tarballs__//lib/stream.js" + │ + ▼ Check: candidate starts with packageRoot? + "/__tarballs__//lib/stream.js".startsWith("/__tarballs__//") + → yes → enrichment activates + │ + ▼ Compute package-relative path + toPackageRelative(candidate, packageRoot) + → "./lib/stream.js" + │ + ▼ Apply manifest field remappings + applyManifestRemappings("./lib/stream.js", manifest, conditions) + │ + ├── browser: { "./lib/stream.js": "./lib/stream-browser.js" } + │ → remapped! New path: "./lib/stream-browser.js" + │ + ├── browser: { "./lib/stream.js": false } + │ → excluded! Return buildExclusionResult() + │ │ + │ ▼ Check remapFalse.importRemapFalse policy: + │ "stub" → namespace: "excluded-module" (ExternalPlugin serves empty export) + │ "error" → esbuild build error + │ "external" → mark as external (preserved in output) + │ + └── No match → path unchanged + │ + ▼ Probe VFS for actual file + resolveVfsPath(FileSystem, finalCandidate, resolveExtensions) + → tries: exact, .js, .mjs, .ts, .tsx, /index.js, etc. + → "/__tarballs__//lib/stream-browser.js" + │ + ▼ Compute sideEffects + computeEsbuildSideEffects(manifest, "/lib/stream-browser.js", { cache }) + │ + ├── sideEffects: false → return false (entire package tree-shakeable) + ├── sideEffects: ["./src/nodes/**/*"] → glob match → true or false + └── sideEffects absent → return undefined (conservative default) + │ + ▼ Return enriched result + { + path: "/__tarballs__//lib/stream-browser.js", + namespace: "virtual-filesystem", + sideEffects: false, + pluginData: { packageRoot, manifest, importer } + } +``` + +**When PackagePlugin returns `undefined` (no enrichment):** +- No `pluginData.packageRoot` → user-authored VFS file, not a package +- Import escapes the package root (e.g., `../../outside.js`) +- `resolveVfsPath()` can't find the file → VFSPlugin may resolve differently + +#### 9b. HTTP onResolve: CDN package enrichment + +**Activation condition:** `pluginData.packageBaseUrl` AND `pluginData.manifest` both exist +(set by CdnPlugin during entry-point resolution via `build.resolve()` delegation). + +``` + Relative import from CDN-fetched file + e.g., import "./lib/stream.js" from https://unpkg.com/readable-stream@4.0.0/index.js + │ + ▼ Determine resolved URL + ├── Full HTTP URL (from build.resolve delegation) + │ → use directly: "https://unpkg.com/readable-stream@4.0.0/lib/stream.js" + ├── Absolute path ("/lib/stream.js") + │ → resolve against parent URL origin + └── Relative path ("./lib/stream.js") + → urlJoin(parentUrl, "../", "./lib/stream.js") + → "https://unpkg.com/readable-stream@4.0.0/lib/stream.js" + │ + ▼ Check: resolved URL starts with packageBaseUrl? + "https://unpkg.com/readable-stream@4.0.0/lib/stream.js" + .startsWith("https://unpkg.com/readable-stream@4.0.0/") + → yes → enrichment activates + │ + ▼ Compute package-relative path + toPackageRelative(resolvedUrl, packageBaseUrl) + → "./lib/stream.js" + │ + ▼ Apply manifest field remappings + applyManifestRemappings("./lib/stream.js", manifest, conditions) + → (same logic as VFS — remapping, exclusion, or pass-through) + │ + ▼ Compute sideEffects + computeEsbuildSideEffects(manifest, "/lib/stream.js", { cache }) + │ + ▼ Return enriched result + { + path: "https://unpkg.com/readable-stream@4.0.0/lib/stream-browser.js", + namespace: "http-url", + sideEffects: false, + pluginData: { manifest, packageBaseUrl, url } + } +``` + +**When PackagePlugin returns `undefined` (no enrichment):** +- No `pluginData.packageBaseUrl` → direct URL fetch without package context +- URL escapes the package base URL → cross-package import (handled by HttpPlugin) + +#### 9c. VFS onLoad: content preprocessing for virtual filesystem + +**Always activates** — this is the sole `onLoad` handler for the VFS namespace. + +``` + esbuild needs content for "/__tarballs__//lib/stream.js" + │ + ▼ Read from VFS + getFile(FileSystem, args.path, "buffer") + → Uint8Array of file content + │ + ├── null? → return undefined (esbuild reports missing file) + │ + ▼ Flow type stripping + maybeStripFlow(content, { url: args.path, sourceMap: enableSourceMaps }) + │ + ├── containsFlow() → false? → pass through (zero overhead, ~4KB scan) + └── containsFlow() → true? + │ + ▼ flow-remove-types (lazy-loaded WASM) + Strip type annotations, preserve source positions + If sourceMap enabled → inline source map appended + │ + ▼ Return stripped content as string + │ + ▼ Loader inference + inferLoader(args.path, undefined, content) + │ + ├── Extension-based: .ts → "ts", .tsx → "tsx", .css → "css" + ├── JSX upgrade: .js with JSX patterns → "tsx" + └── Default: "ts" (esbuild strips TS annotations for free) + │ + ▼ Return loaded content + { + contents: processedContent, + loader: "tsx", + resolveDir: dirname(args.path), // ← enables relative imports + pluginData: { ...inherited, importer: args.path } + } +``` + +> **Why `resolveDir`?** Without setting `resolveDir` to the file's parent +> directory, esbuild would resolve relative imports like `"./column.js"` +> against the build's working directory (`/`), not the file's location. +> This is critical for tarball-extracted packages where files live deep +> in `/__tarballs__//dist/`. + +#### 9d. HTTP onLoad: content fetching and preprocessing for CDN files + +**Always activates** — this is the sole `onLoad` handler for the HTTP namespace. + +``` + esbuild needs content for "https://unpkg.com/lodash-es@4.17.21/debounce.js" + │ + ▼ Extension probing + fetch + determineExtension(args.path, { headersOnly: false, StateContext }) + │ + ├── Try exact URL → 200? Use it + ├── Try .js, .mjs, .ts, ... → first 200 wins + ├── Try /index.js, /index.mjs, ... → first 200 wins + └── All 18 variants 404 → throw (build error) + │ + ▼ returns { url: finalUrl, content: Uint8Array, contentType } + │ + ▼ Store in VFS + setFile(FileSystem, toURLPath(url), content) + (for bundle analyzer and install-size reporting) + │ + ▼ Asset discovery + fetchAssets(url, content, StateContext) + │ + ├── Scan for `new URL("./worker.js", import.meta.url)` patterns + ├── Scan for `new URL("./module.wasm", import.meta.url)` patterns + └── Fetch discovered assets → append to Assets array + │ + ▼ Flow type stripping (same as VFS onLoad) + │ + ▼ Loader inference (same as VFS onLoad) + │ + ▼ Return loaded content + { + contents: processedContent, + loader: "js", + pluginData: { + ...inherited, + url: finalUrl // ← CRITICAL: post-redirect URL for relative resolution + } + } +``` + +> **Why `pluginData.url`?** CDN URLs often redirect: `unpkg.com/react@latest` +> → `unpkg.com/react@19.0.0/index.js`. The post-redirect URL is stored in +> `pluginData.url` so that when esbuild encounters `import "./scheduler"` inside +> that file, HttpPlugin resolves it against `https://unpkg.com/react@19.0.0/` +> (the real location), not `https://unpkg.com/react@latest/` (the alias). + + +### 10. Shared helpers exported by PackagePlugin + +| Export | Purpose | +|---|---| +| `createPluginContext()` | Extracts `config`, `effectiveResolveOpts`, and `sideEffectsMatchersCache` from `StateContext`. Eliminates repeated initialization boilerplate across plugins. | +| `toPackageRelative()` | Converts an absolute path/URL to a `"./"` prefixed package-relative path. Used by both VFS and HTTP enrichment. Returns `null` if the path is outside the package. | +| `packageIdFrom()` | Builds a stable `name@version` cache key from a manifest. Used for sideEffects matcher caching. | +| `buildExclusionResult()` | Constructs the esbuild `onResolve` return for per-module exclusions. Respects `remapFalse.importRemapFalse` policy (`"stub"` / `"error"` / `"external"`). | +| `PACKAGE_NAMESPACE` | The plugin name string (`"package-features"`). For identification only — the plugin resolves into VFS and HTTP namespaces, not its own. | + ## Integration test scenarios | Scenario | What it validates | |---|---| -| VFS → CDN handoff | Bare import in VFS entry routes through CdnPlugin | +| VFS → CDN handoff | Bare import in VFS entry routes through CdnPlugin, sideEffects populated by PackagePlugin | | VFS-only build | No network when code has no external imports | -| Builtin exclusion | `import 'fs'` → empty export, no errors | +| Builtin exclusion | `import 'fs'` → empty export stub via ExternalPlugin, no errors | | `node:` prefix handling | `import 'node:path'` → excluded correctly | | Alias rewrite | `alias: { react: "preact" }` → preact fetched from CDN | | Polyfill mode | `polyfill: true` + `import 'path'` → real code from `path-browserify` | -| Browser field remapping | `@exodus/bytes` resolves browser-specific relative imports | +| Browser field remapping | `@exodus/bytes` resolves browser-specific relative imports via PackagePlugin | | Conditional exports | preact ESM, solid-js nested conditions | -| Tree-shaking | rxjs barrel vs single export — significant size reduction | +| Tree-shaking | rxjs barrel vs single export — sideEffects from PackagePlugin enables significant size reduction | | JSR resolution | `jsr:@std/path@1.0.0` bundles correctly | -| Tarball extraction | `pkg.pr.new` URL → TarballPlugin → working bundle | +| Tarball extraction | `pkg.pr.new` URL → TarballPlugin → working bundle, content served by PackagePlugin | | Platform-specific | browser vs node conditions produce valid builds | | CJS / IIFE format | Output contains expected format wrappers | | VFS state isolation | Separate `buildWithEntry` calls don't leak state | +| Flow stripping (HTTP) | React Native from CDN → PackagePlugin strips Flow in onLoad | +| Flow stripping (VFS) | React Native from tarball → PackagePlugin strips Flow in onLoad | +| Per-module exclusion | `browser: { "./server.js": false }` → PackagePlugin stubs via ExternalPlugin | +| `build.resolve()` delegation | CdnPlugin → PackagePlugin enrichment round-trip preserves pluginData | ## Test file diff --git a/docs/scenarios/20-flow-type-stripping.md b/docs/scenarios/20-flow-type-stripping.md index 932201d..3ea9239 100644 --- a/docs/scenarios/20-flow-type-stripping.md +++ b/docs/scenarios/20-flow-type-stripping.md @@ -193,9 +193,11 @@ Detection is ordered by cost (cheapest first): Flow stripping hooks into esbuild's `onLoad` phase — after content is fetched/read but before esbuild parses it: -**HttpPlugin** ([core/plugins/http.ts](../../core/plugins/http.ts)): +**PackagePlugin** ([core/plugins/package.ts](../../core/plugins/package.ts)) — the sole `onLoad` handler for **both** namespaces: + +**HTTP namespace** (CDN-fetched files): ``` - CDN fetch → raw bytes + CDN fetch → raw bytes (via determineExtension) │ ▼ maybeStripFlow(content, { url }) @@ -207,7 +209,7 @@ Flow stripping hooks into esbuild's `onLoad` phase — after content is fetched/ esbuild parse (with inferred loader) ``` -**VirtualFileSystemPlugin** ([core/plugins/fs.ts](../../core/plugins/fs.ts)): +**VFS namespace** (tarball-extracted and user-authored files): ``` VFS getFile() → raw bytes │ @@ -221,7 +223,7 @@ Flow stripping hooks into esbuild's `onLoad` phase — after content is fetched/ esbuild parse (with inferred loader) ``` -**ExternalPlugin** does **not** need Flow stripping — it returns a static `export default {}` stub for builtin modules. +**ExternalPlugin** does **not** need Flow stripping — it returns a static `export default {}` stub for builtin modules and excluded-module stubs. > **Ordering with JSX detection:** Flow stripping runs *before* loader inference. The result (cleaned source) is then passed to `inferLoader()`, which may upgrade the loader from `ts` to `tsx` if JSX is detected in the (now Flow-free) content. This ordering is correct: Flow type annotations could theoretically mask JSX patterns, so stripping first ensures accurate JSX detection. @@ -424,14 +426,14 @@ Expected output: `import Foo from './Foo';` (typeof replaced with spaces, Expected: Non-Flow → `{ contents: Uint8Array, wasStripped: false }`. Flow → `{ contents: string, wasStripped: true }`. -### 20.12 — HttpPlugin strips Flow from CDN content +### 20.12 — PackagePlugin strips Flow from CDN content **What it tests:** End-to-end: a Flow-annotated file fetched from a CDN is stripped before esbuild parses it. ``` GET https://esm.sh/react-native@0.74.0/index.js → Response contains `import typeof ...` -→ HttpPlugin.onLoad calls maybeStripFlow({ url: "https://esm.sh/react-native@0.74.0/index.js" }) +→ PackagePlugin.onLoad (HTTP namespace) calls maybeStripFlow({ url: "https://esm.sh/react-native@0.74.0/index.js" }) → Flow detected (URL heuristic) and stripped → Clean JS returned to esbuild ``` @@ -439,11 +441,11 @@ GET https://esm.sh/react-native@0.74.0/index.js **Regression signal:** `Unexpected "typeof"` error from esbuild when bundling react-native. -### 20.13 — VFS plugin strips Flow from tarball-extracted content +### 20.13 — PackagePlugin strips Flow from tarball-extracted content -**What it tests:** Flow annotations in files extracted from tarballs (via TarballPlugin → VFS) are stripped by VirtualFileSystemPlugin's `onLoad`. +**What it tests:** Flow annotations in files extracted from tarballs (via TarballPlugin → VFS) are stripped by PackagePlugin's `onLoad` handler for the VFS namespace. -Expected: `maybeStripFlow` is called in VFS `onLoad`, Flow content from tarball-extracted `.js` files is cleaned before esbuild receives it. +Expected: `maybeStripFlow` is called in PackagePlugin's VFS `onLoad`, Flow content from tarball-extracted `.js` files is cleaned before esbuild receives it. ### 20.14 — Lazy loading of `flow-remove-types` @@ -561,4 +563,4 @@ Expected: The embedded map's `sourcesContent[0]` is the exact original source te - **[Scenario 18 — JSX in `.js` Files](18-jsx-in-js-files.md):** Sister feature for the same ecosystem problem. Handles JSX syntax detection; Flow stripping handles type annotations. Both target React Native packages. - **[Scenario 12 — Runtime Conditions](12-runtime-conditions.md):** The `react-native` runtime condition (12.6) routes resolution to React Native-specific entry points, which are the files most likely to contain Flow annotations. -- **[Scenario 19 — Registry Tarballs](19-registry-tarballs.md):** Tarballs extracted into VFS may contain Flow files. The VFS plugin's `onLoad` handler strips Flow from tarball-extracted content (Scenario 20.13). +- **[Scenario 19 — Registry Tarballs](19-registry-tarballs.md):** Tarballs extracted into VFS may contain Flow files. PackagePlugin's VFS `onLoad` handler strips Flow from tarball-extracted content (Scenario 20.13).