diff --git a/.changeset/sourcemaps-doctor.md b/.changeset/sourcemaps-doctor.md new file mode 100644 index 00000000..6567f716 --- /dev/null +++ b/.changeset/sourcemaps-doctor.md @@ -0,0 +1,5 @@ +--- +'@bugsee/bundler-plugin-core': minor +--- + +Adds `bugsee-sourcemaps-doctor`, an offline check of a build output directory (`npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist`; `--json`, `--strict`, `--deployed`, `--ignore `, `--exclude `), and the matching `diagnoseBuildOutput(dir, options)` API with a versioned report (`schemaVersion: 1`). It tells you why a crash from the build would not symbolicate: unstamped bundles or a missing runtime registration, a map whose debugId differs from its bundle's, dangling, hidden or inline source maps, invalid maps and missing `sourcesContent`, duplicate IDs, Subresource Integrity hazards, leftover public maps, development bundles, and the build environment (token source, version, build, `NODE_ENV`; the token value is never printed). Exit 0 ok, 1 warnings with `--strict`, 2 errors. Also: `stamp-files` no longer spreads large file lists onto the call stack (a directory with more than ~125k scripts or maps overflowed it). The Subresource Integrity page scan in the build plugins is now linear (quadratic regexes on pages with thousands of unterminated tags or comments are replaced by an `indexOf` scanner, with a differential test pinning identical results) and pages larger than 8 MiB are skipped. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index c909a11c..fa805d79 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1532,5 +1532,8 @@ Verified against current majors, all green with no adapter code changes: `@bugse ### Debug-ID stamping inside the build for Vite, Rollup and Rspack; verified stamps; safe map deletion (2026-11-23) `@bugsee/bundler-plugin-core` now stamps INSIDE the build wherever the bundler has a pre-write hook, so Subresource Integrity hashes taken later describe the stamped bytes: webpack 5 and **Rspack** at `PROCESS_ASSETS_STAGE_DEV_TOOLING + 1` (shared `tapProcessAssetsStamp`), **Vite and Rollup** in `generateBundle` (`order: 'pre'`; `rollupAssetStore` over chunks + `.map` assets; the stamped id is also put on `chunk.map` because Vite regenerates the map of a lazy-loading chunk after user hooks). esbuild and the standalone CLI stay post-emit with the SRI refusal (its message now names the workaround). Every stamp is verified (`verify-stamp.ts`: parses, sourceMappingURL intact, map debugId matches, original bytes + appended stamp): in-build all-or-nothing, post-emit snapshot + restore of the failing pair (`stamp-files.ts`); an in-build stamp is re-checked on disk (`verifyStampedPairs`) and against the HTML (`findIntegrityMismatches`). `.map` deletion now requires a confirmed upload AND a debugId on the map (`partitionByKeyed`). Real-build proof: `plugin.in-build.real-build.test.ts` (Vite 7 + 8, Rollup, Rspack with its built-in SRI plugin) and a Chromium run in `instrumentation-tests/test/sri-vite-rollup.e2e.ts`. Measured ordering limits and what the guards do not see: `docs/design/source-maps.md` §7.1. +### `sourcemaps doctor`: offline build-output diagnostics (2026-11-23) +`@bugsee/bundler-plugin-core` ships `diagnoseBuildOutput(dir, options)` (`src/doctor.ts`) and the `bugsee-sourcemaps-doctor` bin (`src/doctor-cli.ts`, ESM-only tsup entry, wired through `publishConfig.bin`). 36 check IDs (`DOCTOR_CHECK_IDS`) over the output directory, bundles, maps, SRI (reusing `sri.ts`), leftover maps and the build environment (token, version, build, `NODE_ENV`; the token is never printed), each with a severity and a fix hint, and one versioned JSON report (`schemaVersion: 1`) that the Rust `bugsee-cli sourcemaps doctor` is specified to share. Exit codes 0 ok, 1 warnings only with `--strict`, 2 errors. Review round (PR #222): `--strict` passes straight after a plugin run (`map.public-leftover` is a note unless `--deployed`; `map.pointer-dangling` is a note when no map is left and every bundle is stamped; `--ignore `), the doctor never throws (`doctor.internal-error`; no spread of large lists, safe `file://` decoding), reads only regular files inside the directory with the size checked first (`map.unreadable`, `map.pointer-outside-dir`), walks the whole output directory (only `node_modules`/`.git` skipped unless it is the project root), resolves bundler-scheme sources against the project root, reports the token's source (`env.token-source`; a missing token is a warning), and pairs maps with the stamp's own `localPointerTarget`. The same spread pattern was fixed in `stamp-files.ts`. Round 8: the SRI page walk follows the doctor's fence (full walk for an output directory, reported fence otherwise); docs always use `npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor`. Round 7: `--exclude` applies to SRI pins and map pointers, unmatched patterns are reported (`output.exclude-unmatched`), an all-unreadable output cannot pass, reads are bounded by bytes in flight, maps need `mappings`/`sections`, every distinct SRI pin is kept for the doctor, `passed` lists only checks that had input. Round 6: `--exclude ` (+ `exclude` option) drops files the build did not emit (`output.excluded`); the walk fence needs a `package.json` as well as cwd and reports what it skipped (`output.walk-fenced`); the stamp's own SRI guard keeps no page cap (only the doctor's scan does). Round 4: the HTML scan in `sri.ts` is linear (an `indexOf` scanner replaced the quadratic comment and script-tag regexes; a differential fuzz test pins identical results) and bounded (pages over 8 MiB are skipped and reported as `sri.html-skipped`); reads go through `safe-read.ts` (open with `O_NOFOLLOW`/`O_NONBLOCK`, type and size judged on the descriptor); in-directory symlinks are followed by real path; FIFOs/sockets/devices named like scripts are reported; a map reached through two names is judged once; long lists and the per-map `map.sources-content` notes are capped/aggregated. Real-build proof in `doctor.real-build.test.ts`: Vite 8 and 7, Rollup and Rspack stamped by the real plugin and CLI (healthy), an unstamped build, an inline-map build, and SRI builds (unstamped hazard, stamped-first clean, stamped-after-hash `sri.mismatch` produced by `bugsee-cli sourcemaps inject --allow-sri`). Webpack itself is not a dependency of this package; Rspack stands in for the shared in-build stamp path. Mutator loop: 10 mutations on the decision logic, all killed. **Not done:** an optional post-build `doctor` call in the plugins (the findings need a policy for failing a build; left as a follow-up), the Rust command, and every check that needs the backend (design hand-off: map-present-for-debug-ID, deployed-URL, synthetic symbolicate round trip). + ### Next.js build integration: `withBugsee` (`@bugsee/nextjs/config`), webpack AND Turbopack (2026-11-23) `withBugsee(nextConfig, options)` makes `next build` stamp debug-IDs and upload source maps (gap #1 of the source-map gap analysis). Design + measured limits: `docs/design/source-maps.md` §7.3; user docs: `packages/nextjs/README.md`. **webpack** (`--webpack`, default <= 15): one per-compilation plugin (client, server, edge) stamping inside the compilation (`PROCESS_ASSETS_STAGE_DEV_TOOLING + 1`, SRI-safe) and uploading exactly the files that compilation emitted (`files` mode, nothing walks `.next`). The generic `@bugsee/webpack-plugin` was NOT reused for Next: measured against a real build it cannot stamp the server compilation (assets named `../app/page.js`, output path `.next/server/chunks`) and its directory-wide upload of `.next` collides across the three compilations. **Turbopack** (default 16; `--turbopack` 15.x): `compiler.runAfterProductionCompile` (15.4.0+) runs the real `inject` + upload over `.next/static` and `.next/server`, bundles paired with maps by the `sourceMappingURL` pointer (Turbopack does not name a map after its bundle; Next 15.5 shares one map between two runtime chunks, which are left unstamped with a notice). Measured limits: Turbopack writes the SRI hashes BEFORE the hook, so an `experimental.sri` Turbopack build is left unmodified with a notice (webpack handles SRI); Next 16 errors on a `webpack` function without a `turbopack` config, so none is added on Turbopack builds; `compiler.define` (not `defineServer`) bakes the app identity. Policy: browser maps deleted after a confirmed upload, server/edge maps kept (`deleteServerMaps`). Composes with a user's `webpack`, `compiler.runAfterProductionCompile`, `compiler.define`, `productionBrowserSourceMaps`, function/async configs; inert for dev/start/export. Core change: `@bugsee/bundler-plugin-core` now also exports `stampAssets`, `AssetStore`, `notify`, `resolveIdentity`, `loadBuildPluginEnv`, `mergeBuildPluginEnv`. Found by the independent reviews and fixed: stamped webpack assets are written as STRING sources (a Buffer is opaque to webpack's RealContentHashPlugin, which renames `[contenthash]` chunks after the stamp, so every lazy chunk 404'd; the e2e now opens each build in headless Chromium and asserts the lazy chunk runs), the baked define is the RAW value (Next JSON-encodes `compiler.define` itself; a JSON string arrived double-quoted), own-files-only deletion on Turbopack, contained post-build hook, version floors (hook 15.4.0, define 15.1.0), idempotent application. Real builds (`@bugsee/nextjs-e2e`, `test/source-maps.e2e.ts`, `next` 15.5.28 and 16.4.6 x webpack/Turbopack + SRI cases, real `bugsee-cli`, mock collector, `next start` smoke): see the PR for the run. diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 8a8afa48..3f0d1fa9 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -220,3 +220,35 @@ stub the SDK reads. This is exactly what the plugins automate; the CLI is the sa - **Not covered: bytecode targets.** React-Native/Hermes compiles JS → bytecode, which drops the injected comment and stub, so the running code reports no debug-ID. That needs a Hermes-specific compose flow and is handled by the separate React-Native SDK, not this (web/node/bun) SDK. + +## 4. Check a build: `bugsee-sourcemaps-doctor` + +When a production crash does not de-minify, run the doctor against the build output you actually deployed (or are about to). It is offline: it reads the files and makes no network call. The token is only looked up (never printed) so the report can say where it comes from; a missing token is a warning, not an error. + +```bash +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist # readable report, fix hint per finding +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --json # for CI (schemaVersion 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --strict # warnings fail the step too (exit 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --deployed # the directory is served: leftover .map files warn +``` + +The binary ships in `@bugsee/bundler-plugin-core`, so always name the package as above (a bare `npx bugsee-sourcemaps-doctor` is only safe when it is already linked into `node_modules/.bin`, which pnpm and Yarn do for direct dependencies only; otherwise npx asks the public registry for an unrelated name). + +`--strict` passes straight after a default plugin run (maps removed after upload, bundles stamped) when the directory holds only what the build emitted. Scripts copied in (Vite `publicDir`, a copy plugin) are never stamped by the plugin and are indistinguishable from a bundle that lost its stamp: exclude them by path, relative to the checked directory (Vite copies `public/` to the ROOT of the output, so `--exclude sw.js --exclude 'pdf.worker.min.mjs*'`; repeatable; listed as `output.excluded`, and a pattern that matches nothing is reported as `output.exclude-unmatched`). `--exclude` only removes files from the audit, not from what you deploy. A directory that is a project (has a `package.json`) and is the working directory is walked fenced (no `src`, `test`, dot-directories, depth > 6), and the skipped directories are listed as `output.walk-fenced`. Other options: `--ignore ` (repeatable; hard failures such as `output.no-js` cannot be ignored), `--project-root`, `--max-map-mb`, `--no-env`, `--`. + +Exit codes: `0` ok, `1` warnings only (with `--strict`), `2` errors. The package is `@bugsee/bundler-plugin-core`; the same report is available in code as `diagnoseBuildOutput(dir, options)`. + +Typical findings and what to do: + +| ID | Meaning | +|---|---| +| `stamp.missing-debug-id` / `stamp.missing-registration` | A bundle is not stamped (or only has the comment, not the runtime registration). Add the plugin, or run `bugsee-cli sourcemaps inject ` after the build. | +| `stamp.map-id-mismatch` / `stamp.map-no-debug-id` | The map's `debugId` is not the bundle's. A step ran after stamping; stamp last. | +| `map.pointer-dangling` | The bundle's `sourceMappingURL` points at a map that is not on disk. A note when no `.map` is left and every bundle is stamped (maps removed after upload); otherwise a warning. Use hidden maps to avoid the 404. | +| `map.inline` | The map is a `data:` URL inside the bundle: nothing to upload, and it ships to every visitor. | +| `map.sources-unresolvable` | No `sourcesContent` and the sources are not on disk: frames will have no source lines. | +| `map.public-leftover` | `.map` files are in the directory. A note by default; a warning with `--deployed` (you serve this directory). Keep `deleteMaps` on, or remove the maps / leave them out of the deploy (`--exclude` does not help: it only hides them from this audit). | +| `sri.unstamped-hazard` / `sri.mismatch` / `sri.manifest-hashes` | Subresource Integrity hashes pin these scripts; stamping after hashing makes the browser block them. | +| `env.token-missing` | No app token is visible to the build (a warning): the plugin is disabled and uploads nothing, which is fine if you upload with `bugsee-cli` by hand. `env.token-source` says where a found token comes from, never its value. | + +The doctor reports which source supplied the token (`env.token-source`: option, environment variable or `.env.bugsee-build-plugin`), never the token. It reads only regular files inside the directory you give it and checks a map's size before reading it. Checks that need the backend (is the map for this ID uploaded? does the deployed URL serve a stamped bundle?) are not part of this command yet. diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index 7292cecf..06dd50c2 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -20,7 +20,23 @@ npm install --save-dev @bugsee/vite-plugin - Settings lookup order: plugin option, then the process environment, then the nearest `.env.bugsee-build-plugin` (only `BUGSEE_APP_TOKEN` / `BUGSEE_APP_VERSION` / `BUGSEE_APP_BUILD` are read from it; searched from the bundler's project directory up to the repo/workspace root, never in or above the home directory; fills gaps only, a blank variable counts as unset; a missing or malformed file never fails the build). Details: `docs/source-maps-usage.md`. - Option resolution (`appToken`, `appVersion`, `appBuild`, `endpoint`, `deleteMaps`, `dryRun`, `disabled`, with environment fallbacks such as `BUGSEE_APP_TOKEN`; the version also falls back to the nearest `package.json` above the bundler's project directory (blank values count as unset; Rollup, which reports no project directory, walks up from the output directory and skips a name-less, version-less marker such as a `dist/cjs/package.json` holding only `{"type":"commonjs"}`), the build to a CI commit id, and a real value is baked into the app bundle as `__BUGSEE_APP_VERSION__` / `__BUGSEE_APP_BUILD__` for the runtime SDK: through `define` on Vite, esbuild, webpack 5 and Rspack, and by rewriting each rendered chunk (with a source map) on Rollup; webpack 4 cannot bake, so there only an explicit value is recorded; a constant you define yourself is what gets recorded when it is a plain string), build-commit detection and the CLI runner. -The programmatic API beyond the plugins is internal and may change between releases. +## `bugsee-sourcemaps-doctor` + +An offline check of a build output directory: why would a crash from this build not symbolicate? No network call; a token is not required (a missing one is only a warning). + +```bash +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist # human report +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --json # machine-readable report (schemaVersion 1) +npx --package=@bugsee/bundler-plugin-core bugsee-sourcemaps-doctor dist --strict # exit 1 on warnings too +``` + +The binary ships in `@bugsee/bundler-plugin-core`, not in a package of its own name, so always name the package (a bare `npx bugsee-sourcemaps-doctor` asks the public registry for an unrelated, unclaimed name unless it happens to be linked into `node_modules/.bin`; pnpm and Yarn link only the bins of direct dependencies). With the package as a direct dependency, `pnpm exec bugsee-sourcemaps-doctor dist` works too. + +Exit codes: 0 ok, 1 warnings only (with `--strict`), 2 errors. Options: `--project-root ` (where `.env.bugsee-build-plugin` and `package.json` are looked up; default the working directory), `--max-map-mb `, `--no-env` (skip the token / version / build / `NODE_ENV` checks), `--deployed` (the directory is, or is about to be, served: leftover `.map` files become a warning instead of a note), `--exclude ` (files the build did not emit, e.g. `sw.js` or `pdf.worker.min.mjs*` for scripts copied from Vite's `publicDir` (it lands at the ROOT of the output) or by a copy plugin, relative to the checked directory, a leading `./` is fine; a pattern that matches nothing is reported as `output.exclude-unmatched`: the plugin never stamps those and a doctor cannot tell them from a bundle that lost its stamp; repeatable; `*` stays in a directory, `**` crosses them; matches are listed as `output.excluded`), `--ignore ` (drop a check ID; repeatable; `output.dir-missing`, `output.no-js` and `doctor.internal-error` cannot be ignored), `--` (end of options); `--key=value` works for options that take a value, and `--strict=false`-style values on flags are refused. Before the upload (hidden maps still on disk, the plugin will delete them) and after it (maps removed), `--strict` passes on a healthy build; add `--deployed` only when checking the directory you serve. Straight after a default plugin run `--strict` passes for a build whose output directory holds only what the build emitted (add `--exclude` for copied-in scripts): leftover maps are a note unless `--deployed`, and a pointer to maps removed on purpose from a fully stamped build is a note. + +It checks, each with a stable ID, a severity and a fix hint: the output directory and its JavaScript; the debug-ID comment and `_bugseeDebugIds` registration on every bundle; a matching map with the same ID; `sourceMappingURL` pointers (dangling, hidden, inline); map validity (v3, `sources`, `sourcesContent` embedded or resolvable on disk, size; a facade or empty chunk's map, with no sources and no mappings, is a note, not an error); mixed stamped/unstamped bundles; duplicate IDs across different contents; Subresource Integrity hazards and mismatches (pages and `*manifest*.json` inside the directory only; a page larger than 8 MiB is reported, not scanned); leftover `.map` files that a deploy would serve; development-mode bundles; and the build environment (token present, version and build resolvable, `NODE_ENV`). The token value is never printed; the report says where it came from (option, environment variable, or `.env.bugsee-build-plugin`), and a missing token is a warning, because uploading by hand is legitimate. When the checked directory is itself a project directory (has a `package.json`) and is, or contains, the working directory, the walk skips `src`/`test`/dot-directories and stops below depth 6 so it stays out of a source tree; the skipped directories are listed as `output.walk-fenced`, never silent. The doctor never throws (an internal failure is a `doctor.internal-error` finding), never reads outside the checked directory, never reads a FIFO, socket or device (they are reported: the file is opened non-blocking where the platform allows it, and its type is checked on the open descriptor before a byte is read), reads a symlink only when its real path stays inside the checked directory (a pnpm-style `assets/app.js -> ../.store/app.js` is fine; a script link that leads out or dangles is reported). Symlinked directories inside the checked directory are followed (once each: loops and aliases are not walked twice); one that leaves it is reported as `output.dir-unreadable`, which `--exclude` can clear; a directory link that dangles is ignored, because its type cannot be known, judges type and size on the open file descriptor, and checks a map's size before reading it. Programmatic use: `diagnoseBuildOutput(dir, options)` returns the same report. The backend-assisted checks (is this ID's map uploaded?) are not part of this command; see `docs/source-maps-usage.md` §4. + +The rest of the programmatic API beyond the plugins and the doctor is internal and may change between releases. ## Links diff --git a/packages/bundler-plugin-core/package.json b/packages/bundler-plugin-core/package.json index cdb887ae..a9905236 100644 --- a/packages/bundler-plugin-core/package.json +++ b/packages/bundler-plugin-core/package.json @@ -22,7 +22,7 @@ ], "sideEffects": false, "scripts": { - "build": "tsup", + "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup", "typecheck": "tsc --noEmit", "test": "vitest run", "test:coverage": "vitest run --coverage" @@ -44,6 +44,9 @@ "vite7": "npm:vite@7.3.6" }, "publishConfig": { + "bin": { + "bugsee-sourcemaps-doctor": "./dist/doctor-cli.js" + }, "main": "./dist/index.cjs", "module": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/packages/bundler-plugin-core/src/doctor-cli.test.ts b/packages/bundler-plugin-core/src/doctor-cli.test.ts new file mode 100644 index 00000000..5fd416d8 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor-cli.test.ts @@ -0,0 +1,285 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { DOCTOR_USAGE, runDoctorCli } from './doctor-cli'; + +const ID = '11111111-1111-4111-8111-111111111111'; +let root: string; +let dist: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-cli-')); + dist = join(root, 'dist'); + mkdirSync(dist); + writeFileSync(join(root, 'package.json'), '{"name":"a","version":"1.0.0"}'); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const stamped = `x\n!function(){globalThis._bugseeDebugIds={}}();\n//# debugId=${ID}\n`; + +async function cli(argv: string[], env = { BUGSEE_APP_TOKEN: 't', BUGSEE_APP_BUILD: 'b' }) { + let out = ''; + let err = ''; + const code = await runDoctorCli(argv, { + stdout: (t) => (out += t), + stderr: (t) => (err += t), + env, + }); + return { code, out, err }; +} + +describe('runDoctorCli --exclude', () => { + it('drops matching files before analysis; repeatable; needs a value', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + mkdirSync(join(dist, 'public')); + writeFileSync(join(dist, 'public', 'sw.js'), 'x'); + writeFileSync(join(dist, 'vendor.js'), 'x'); + expect((await cli([dist, '--no-env', '--json'])).code).toBe(0); + const ids = async (args: string[]) => + JSON.parse((await cli([dist, '--no-env', '--json', ...args])).out).findings.map( + (f: { id: string }) => f.id, + ); + expect(await ids(['--exclude', 'public/**'])).toContain('output.excluded'); + expect(await ids(['--exclude', 'public/**'])).toContain('stamp.missing-debug-id'); // vendor.js remains + const both = await ids(['--exclude=public/**', '--exclude', 'vendor.js']); + expect(both).not.toContain('stamp.missing-debug-id'); + expect(both).not.toContain('stamp.mixed'); + expect((await cli([dist, '--exclude'])).code).toBe(2); + }); +}); + +describe('runDoctorCli', () => { + it('prints the text report and exits 0 for a clean build', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const { code, out, err } = await cli([dist, '--project-root', root]); + expect(code).toBe(0); + expect(out).toContain('The app token comes from the BUGSEE_APP_TOKEN environment variable.'); + expect(out).not.toContain('t,'); // the value is never printed + expect(err).toBe(''); + }); + + it('--json prints a parseable report; exit 2 on errors', async () => { + writeFileSync(join(dist, 'a.js'), 'x\n//# sourceMappingURL=a.js.map'); + writeFileSync(join(dist, 'a.js.map'), '{"version":3,"sources":["a"]}'); + const { code, out } = await cli([dist, '--json', '--no-env']); + expect(code).toBe(2); + const report = JSON.parse(out); + expect(report.schemaVersion).toBe(1); + expect(report.findings.map((f: { id: string }) => f.id)).toContain('stamp.missing-debug-id'); + }); + + it('--strict turns warnings into exit 1; without it they are exit 0', async () => { + writeFileSync(join(dist, 'vendor.js'), 'x'); + expect((await cli([dist, '--no-env'])).code).toBe(0); + expect((await cli([dist, '--no-env', '--strict'])).code).toBe(1); + }); + + it('a missing token is a warning (exit 0; 1 under --strict); --no-env drops the check', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const base = [dist, '--project-root', root, '--json']; + const warned = await cli(base, {} as never); + expect(warned.code).toBe(0); + expect(JSON.parse(warned.out).findings.map((f: { id: string }) => f.id)).toContain( + 'env.token-missing', + ); + expect((await cli([...base, '--strict'], {} as never)).code).toBe(1); + const skipped = await cli([...base, '--no-env', '--strict'], {} as never); + expect(skipped.code).toBe(0); + }); + + it('--strict passes straight after a plugin run: stamped bundle, maps removed, pointer left', async () => { + writeFileSync(join(dist, 'a.js'), `x\n//# sourceMappingURL=a.js.map${stamped}`); + const { code } = await cli([dist, '--project-root', root, '--strict']); + expect(code).toBe(0); + }); + + it('--deployed makes leftover maps a warning; --ignore drops an ID (repeatable)', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + writeFileSync( + join(dist, 'a.js.map'), + JSON.stringify({ + version: 3, + debugId: ID, + sources: ['a'], + sourcesContent: ['x'], + mappings: 'AAAA', + }), + ); + const args = [dist, '--no-env', '--strict']; + expect((await cli(args)).code).toBe(0); + expect((await cli([...args, '--deployed'])).code).toBe(1); + const ignored = await cli([ + ...args, + '--deployed', + '--ignore', + 'map.public-leftover', + '--ignore', + 'x', + '--json', + ]); + expect(ignored.code).toBe(0); + expect(JSON.parse(ignored.out).ignored).toEqual(['map.public-leftover']); + }); + + it('`--` ends options, so a directory can start with a dash', async () => { + const odd = join(root, '-odd'); + mkdirSync(odd); + writeFileSync(join(odd, 'a.js'), stamped); + const { code, out } = await cli(['--no-env', '--', odd]); + expect(code).toBe(0); + expect(out).toContain('1 bundle(s)'); + expect((await cli(['--', odd, 'second'])).code).toBe(2); + }); + + it('a single-dash unknown flag is rejected, not taken for the directory', async () => { + const { code, err } = await cli(['-x', dist]); + expect(code).toBe(2); + expect(err).toContain('Unknown option -x'); + }); + + it('--max-map-mb sets the large-map threshold', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + writeFileSync( + join(dist, 'a.js.map'), + JSON.stringify({ + version: 3, + debugId: ID, + sources: ['a'], + sourcesContent: ['x'.repeat(2000)], + }), + ); + const small = await cli([dist, '--no-env', '--max-map-mb', '0.001', '--json']); + expect(JSON.parse(small.out).findings.map((f: { id: string }) => f.id)).toContain( + 'map.too-large', + ); + // 2000 bytes against 1 MiB: only the right unit (MiB, not KiB) leaves it unflagged + const oneMb = await cli([dist, '--no-env', '--max-map-mb', '1', '--json']); + expect(JSON.parse(oneMb.out).findings.map((f: { id: string }) => f.id)).not.toContain( + 'map.too-large', + ); + const big = await cli([dist, '--no-env', '--json']); + expect(JSON.parse(big.out).findings.map((f: { id: string }) => f.id)).not.toContain( + 'map.too-large', + ); + }); + + it('--key=value forms work for every option that takes a value', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + writeFileSync( + join(dist, 'a.js.map'), + JSON.stringify({ + version: 3, + debugId: ID, + sources: ['a'], + sourcesContent: ['x'.repeat(2000)], + }), + ); + const small = await cli([dist, '--no-env', '--max-map-mb=0.001', '--json']); + expect(JSON.parse(small.out).findings.map((f: { id: string }) => f.id)).toContain( + 'map.too-large', + ); + const ignored = await cli([ + dist, + '--no-env', + '--ignore=map.public-leftover', + `--project-root=${root}`, + '--json', + ]); + expect(JSON.parse(ignored.out).ignored).toEqual(['map.public-leftover']); + expect((await cli([dist, '--max-map-mb='])).code).toBe(2); + }); + + it('`--=x` is an unknown option, not the end-of-options marker', async () => { + const { code, err } = await cli(['--=x', dist]); + expect(code).toBe(2); + expect(err).toContain('Unknown option --'); + }); + + it.each([ + '--json', + '--strict', + '--no-env', + '--deployed', + '--help', + ])('%s takes no value: `=value` is a usage error, not silently dropped', async (flag) => { + const { code, out, err } = await cli([dist, `${flag}=false`]); + expect(code).toBe(2); + expect(out).toBe(''); + expect(err).toContain(`${flag} does not take a value`); + }); + + it('after `--`, an argument containing `=` is a plain directory name', async () => { + const odd = join(root, '--odd=dir'); + mkdirSync(odd); + writeFileSync(join(odd, 'a.js'), stamped); + const here = process.cwd(); + process.chdir(root); + try { + const { code, out } = await cli(['--no-env', '--', '--odd=dir']); + expect(code).toBe(0); + expect(out).toContain('--odd=dir'); + expect(out).toContain('1 bundle(s)'); + } finally { + process.chdir(here); + } + }); + + it('`--project-root=--x` takes the value; `-- --a=b` is one directory (not truncated at `=`)', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const { code } = await cli([dist, '--project-root=--x', '--json']); + expect(code).toBe(0); + const here = process.cwd(); + process.chdir(root); + try { + mkdirSync(join(root, '--a=b')); + const out = await cli(['--no-env', '--', '--a=b']); + expect(out.out).toContain('--a=b'); + expect(out.out).toContain('0 bundle(s)'); + } finally { + process.chdir(here); + } + }); + + it('--ignore of a hard-failure ID warns that it cannot be ignored and still fails', async () => { + const { code, err } = await cli([ + join(root, 'nope'), + '--no-env', + '--ignore', + 'output.dir-missing', + ]); + expect(code).toBe(2); + expect(err).toContain('output.dir-missing cannot be ignored'); + }); + + it('an unknown --ignore ID is warned about on stderr but not fatal', async () => { + writeFileSync(join(dist, 'a.js'), stamped); + const { code, err } = await cli([dist, '--no-env', '--ignore', 'map.public-leftvoer']); + expect(code).toBe(0); + expect(err).toContain('map.public-leftvoer is not a known check ID'); + expect((await cli([dist, '--no-env', '--ignore', 'map.public-leftover'])).err).toBe(''); + }); + + it('--help prints usage and exits 0', async () => { + for (const flag of ['--help', '-h']) { + const { code, out } = await cli([flag]); + expect(code).toBe(0); + expect(out).toBe(`${DOCTOR_USAGE}\n`); + } + }); + + it.each([ + [[], 'Missing the build output directory'], + [['a', 'b'], 'Unexpected argument b'], + [['a', '--bogus'], 'Unknown option --bogus'], + [['a', '--project-root'], '--project-root needs a value'], + [['a', '--max-map-mb', '--json'], '--max-map-mb needs a value'], + [['a', '--max-map-mb', 'abc'], 'positive number, got "abc"'], + [['a', '--max-map-mb', '0'], 'positive number, got "0"'], + ])('usage error for %j', async (argv, message) => { + const { code, out, err } = await cli(argv as string[]); + expect(code).toBe(2); + expect(out).toBe(''); + expect(err).toContain(message); + expect(err).toContain('Usage: bugsee-sourcemaps-doctor'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor-cli.ts b/packages/bundler-plugin-core/src/doctor-cli.ts new file mode 100644 index 00000000..e1bd06e8 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor-cli.ts @@ -0,0 +1,170 @@ +#!/usr/bin/env node +// `bugsee-sourcemaps-doctor` — the command-line face of `diagnoseBuildOutput`. +// +// bugsee-sourcemaps-doctor [--json] [--strict] [--project-root ] [--max-map-mb ] [--no-env] [--exclude ] +// +// Exit codes: 0 ok, 1 warnings only with --strict, 2 errors (or a usage error). +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { + DOCTOR_CHECK_IDS, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, + NON_IGNORABLE_CHECK_IDS, +} from './doctor'; +import type { EnvRecord } from './run-cli'; + +export const DOCTOR_USAGE = `Usage: bugsee-sourcemaps-doctor [options] + +Audits a build output directory for everything that stops Bugsee from symbolicating a crash. + +Options: + --json Print the machine-readable report (schemaVersion 1) instead of text. + --strict Exit 1 when there are warnings (and no errors). + --project-root Where .env.bugsee-build-plugin and package.json are looked up (default: cwd). + --max-map-mb Flag source maps larger than n MiB (default 50). + --no-env Skip the token / version / build / NODE_ENV checks. + --deployed The directory is (about to be) served: leftover .map files become a warning. + --ignore Drop a check ID from the report; repeatable. + --exclude Do not check files the build did not emit (e.g. sw.js; relative to ); repeatable. + -- End of options (a directory may start with a dash after it). + -h, --help Show this help. + +Exit codes: 0 ok, 1 warnings only (with --strict), 2 errors.`; + +/** Flags that take no value: `--strict=false` must be refused, not read as `--strict`. */ +const BOOLEAN_FLAGS: ReadonlySet = new Set([ + '--json', + '--strict', + '--no-env', + '--deployed', + '--help', +]); + +export interface DoctorCliIo { + stdout: (text: string) => void; + stderr: (text: string) => void; + env: EnvRecord; +} + +/** Run the CLI in-process: returns the exit code, writes only through `io`. */ +export async function runDoctorCli(argv: readonly string[], io: DoctorCliIo): Promise { + let dir: string | undefined; + let json = false; + let strict = false; + let skipEnv = false; + let deployed = false; + let onlyPositionals = false; + const ignore: string[] = []; + const exclude: string[] = []; + let projectRoot: string | undefined; + let maxMapBytes: number | undefined; + const usage = (message: string): number => { + io.stderr(`${message}\n\n${DOCTOR_USAGE}\n`); + return 2; + }; + for (let i = 0; i < argv.length; i++) { + let arg = argv[i] as string; + // `--key=value` is the same as `--key value` + let inline: string | undefined; + const eq = !onlyPositionals && arg.startsWith('--') ? arg.indexOf('=') : -1; + if (eq > 2) { + inline = arg.slice(eq + 1); + arg = arg.slice(0, eq); + } + if (inline !== undefined && BOOLEAN_FLAGS.has(arg)) { + return usage(`${arg} does not take a value`); + } + if (onlyPositionals) { + if (dir !== undefined) { + return usage(`Unexpected argument ${arg}`); + } + dir = arg; + } else if (arg === '--') { + onlyPositionals = true; + } else if (arg === '-h' || arg === '--help') { + io.stdout(`${DOCTOR_USAGE}\n`); + return 0; + } else if (arg === '--json') { + json = true; + } else if (arg === '--strict') { + strict = true; + } else if (arg === '--no-env') { + skipEnv = true; + } else if (arg === '--deployed') { + deployed = true; + } else if ( + arg === '--project-root' || + arg === '--max-map-mb' || + arg === '--ignore' || + arg === '--exclude' + ) { + const value = inline ?? argv[++i]; + if (value === undefined || (inline === undefined && value.startsWith('--'))) { + return usage(`${arg} needs a value`); + } + if (arg === '--project-root') { + projectRoot = value; + } else if (arg === '--exclude') { + exclude.push(value); + } else if (arg === '--ignore') { + if (NON_IGNORABLE_CHECK_IDS.has(value)) { + io.stderr( + `Warning: ${value} cannot be ignored (it means nothing was checked); it stays in the report.\n`, + ); + } else if (!(DOCTOR_CHECK_IDS as readonly string[]).includes(value)) { + io.stderr( + `Warning: --ignore ${value} is not a known check ID (see DOCTOR_CHECK_IDS); ignored.\n`, + ); + } + ignore.push(value); + } else { + const mb = Number(value); + if (!Number.isFinite(mb) || mb <= 0) { + return usage(`--max-map-mb needs a positive number, got "${value}"`); + } + maxMapBytes = mb * 1024 * 1024; + } + } else if (arg.startsWith('-')) { + return usage(`Unknown option ${arg}`); + } else if (dir === undefined) { + dir = arg; + } else { + return usage(`Unexpected argument ${arg}`); + } + } + if (dir === undefined) { + return usage('Missing the build output directory'); + } + const report = await diagnoseBuildOutput(dir, { + env: io.env, + skipEnv, + deployed, + ignore, + exclude, + ...(projectRoot !== undefined ? { projectRoot } : {}), + ...(maxMapBytes !== undefined ? { maxMapBytes } : {}), + }); + io.stdout(`${json ? JSON.stringify(report, null, 2) : formatDoctorReport(report)}\n`); + return doctorExitCode(report, strict); +} + +/* v8 ignore start -- process entry point: the logic above is what is tested */ +const self = process.argv[1]; +if (self !== undefined && realpathSync(self) === realpathSync(fileURLToPath(import.meta.url))) { + runDoctorCli(process.argv.slice(2), { + stdout: (text) => process.stdout.write(text), + stderr: (text) => process.stderr.write(text), + env: process.env, + }).then( + (code) => { + process.exitCode = code; + }, + (error: unknown) => { + process.stderr.write(`bugsee-sourcemaps-doctor: ${String(error)}\n`); + process.exitCode = 2; + }, + ); +} +/* v8 ignore stop */ diff --git a/packages/bundler-plugin-core/src/doctor.hardening.test.ts b/packages/bundler-plugin-core/src/doctor.hardening.test.ts new file mode 100644 index 00000000..685c2524 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.hardening.test.ts @@ -0,0 +1,2289 @@ +// Robustness of the doctor: it must never throw, never read what it should not, never be quadratic, and must +// resolve sources the way the build did. Each test pins one reviewed failure mode. +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + truncateSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, posix, relative, sep, win32 } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + batchEnd, + boundedMemo, + type DoctorReport, + diagnoseBuildOutput, + doctorExitCode, + hasOriginalPosition, + sourcePath, + walk, + walkDetailed, +} from './doctor'; +import { isFacadeCode } from './facade'; +import { READ_CEILING, readRegularFile } from './safe-read'; +import { listOutputMaps } from './stamp-files'; + +const ID_A = '11111111-1111-4111-8111-111111111111'; +const ID_B = '22222222-2222-4222-8222-222222222222'; + +let root: string; +let dist: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-hard-')); + dist = join(root, 'dist'); + mkdirSync(dist); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'app', version: '1.0.0' })); +}); +afterEach(() => rmSync(root, { recursive: true, force: true }), 120_000); // removing 130k files is slow + +const put = (rel: string, content: string | Buffer): string => { + const path = join(dist, rel); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); + return path; +}; +const stamp = (id: string): string => + `\n!function(){var g=globalThis;g._bugseeDebugIds=g._bugseeDebugIds||{};g._bugseeDebugIds["x"]="${id}"}();\n//# debugId=${id}\n`; +const mapJson = (extra: Record = {}): string => + JSON.stringify({ + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + names: [], + mappings: 'AAAA', + ...extra, + }); +const run = (options: Parameters[1] = {}): Promise => + diagnoseBuildOutput(dist, { projectRoot: root, skipEnv: true, ...options }); +const ids = (report: DoctorReport): string[] => report.findings.map((f) => f.id); +const find = (report: DoctorReport, id: string) => report.findings.find((f) => f.id === id); + +describe('never throws', () => { + it('a source with a bad percent-escape is unknowable, not an exception', async () => { + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ debugId: ID_A, sourcesContent: undefined, sources: ['file:///x/%zz.ts'] }), + ); + const report = await run(); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('an unexpected internal error becomes a doctor.internal-error finding', async () => { + put('a.js', `a${stamp(ID_A)}`); + const env = new Proxy( + {}, + { + ownKeys() { + throw new Error('boom'); + }, + }, + ); + const report = await diagnoseBuildOutput(dist, { env, projectRoot: root }); + expect(report.findings).toHaveLength(1); + expect(report.findings[0]).toMatchObject({ + id: 'doctor.internal-error', + severity: 'error', + }); + expect(report.findings[0]?.message).toContain('boom'); + expect(report.summary.errors).toBe(1); + expect(report.dir).toBe(dist); + // a hard failure cannot be ignored away + const ignored = await diagnoseBuildOutput(dist, { + env, + projectRoot: root, + ignore: ['doctor.internal-error'], + }); + expect(ignored.findings.map((f) => f.id)).toEqual(['doctor.internal-error']); + expect(ignored.ignored).toBeUndefined(); + }); + + it('a non-Error throw is stringified', async () => { + const env = new Proxy( + {}, + { + ownKeys() { + throw 'plain string'; + }, + }, + ); + put('a.js', 'x'); + const report = await diagnoseBuildOutput(dist, { env, projectRoot: root }); + expect(report.findings[0]?.message).toContain('plain string'); + }); +}); + +describe('a directory with very many files', () => { + it('the walks do not overflow the stack (130k files in one directory)', async () => { + const big = join(dist, 'chunks'); + mkdirSync(big); + for (let i = 0; i < 130_000; i++) { + writeFileSync(join(big, i % 2 === 0 ? `c${i}.js` : `c${i}.map`), ''); + } + expect((await walk(dist)).length).toBe(130_000); + expect((await listOutputMaps(dist)).length).toBe(65_000); + }, 120_000); + + it('20k bundles are checked in bounded time with correct counts', async () => { + for (let i = 0; i < 20_000; i++) { + const id = `${(i + 1).toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`assets/c${i}.js`, `${i}${stamp(id)}`); + } + const started = Date.now(); + const report = await run(); + expect(Date.now() - started).toBeLessThan(60_000); + expect(report.summary).toMatchObject({ bundles: 20_000, errors: 0, warnings: 0 }); + }, 120_000); +}); + +describe('reads', () => { + const mkfifo = (path: string): boolean => spawnSync('mkfifo', [path]).status === 0; + + it('a pointer outside the output directory is reported and never read (a FIFO would hang)', async () => { + const fifo = join(root, 'pipe.map'); + if (!mkfifo(fifo)) { + return; + } + put('a.js', `a\n//# sourceMappingURL=../pipe.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=../../../../../../dev/zero${stamp(ID_B)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')).toMatchObject({ + severity: 'warning', + details: { pointers: ['a.js -> ../pipe.map', 'b.js -> ../../../../../../dev/zero'] }, + }); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('a FIFO named as a map is map.unreadable, not opened; a symlink to a map inside the directory is read', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + if (!mkfifo(join(dist, 'a.js.map'))) { + return; + } + put('real.map', mapJson({ debugId: ID_B })); + put('b.js', `b\n//# sourceMappingURL=link.map${stamp(ID_B)}`); + symlinkSync(join(dist, 'real.map'), join(dist, 'link.map')); + const report = await run(); + const unreadable = report.findings.filter((f) => f.id === 'map.unreadable'); + // the FIFO is refused; the symlink to a map INSIDE the directory is simply read + expect(unreadable.map((f) => f.file)).toEqual(['a.js.map']); + expect(unreadable[0]?.message).toContain('not a regular file'); + expect(unreadable[0]?.severity).toBe('error'); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + }); + + it('a map larger than the limit is judged by its size, before it is read (a sparse 3 GiB file)', async () => { + put('a.js', `a${stamp(ID_A)}`); + const big = put('a.js.map', ''); + truncateSync(big, 3 * 1024 ** 3); + const report = await run(); + expect(find(report, 'map.too-large')).toMatchObject({ + severity: 'warning', + file: 'a.js.map', + details: { bytes: 3 * 1024 ** 3, limit: 50 * 1024 * 1024 }, + }); + expect(find(report, 'map.too-large')?.message).toContain('not read'); + expect(ids(report)).not.toContain('map.invalid'); + }); + + it('map.too-large is exact at the boundary: equal is fine, one byte over is not', async () => { + put('a.js', `a${stamp(ID_A)}`); + const text = mapJson({ debugId: ID_A }); + put('a.js.map', text); + const size = Buffer.byteLength(text); + expect(ids(await run({ maxMapBytes: size }))).not.toContain('map.too-large'); + expect(ids(await run({ maxMapBytes: size - 1 }))).toContain('map.too-large'); + // far over the limit also reports (kills a `>= limit * 2` comparison) + expect(ids(await run({ maxMapBytes: Math.floor(size / 2) }))).toContain('map.too-large'); + expect(find(await run({ maxMapBytes: size - 1 }), 'map.too-large')?.details).toEqual({ + bytes: size, + limit: size - 1, + }); + }); + + it('an oversized or non-regular orphan map is reported too', async () => { + put('style.css.map', mapJson()); + put('big.css.map', 'x'.repeat(100)); + const report = await run({ maxMapBytes: 50 }); + expect(find(report, 'map.too-large')?.file).toBe('big.css.map'); + }); + + it.skipIf(process.getuid?.() === 0)('a read error is a finding, not silence', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + const map = put('a.js.map', mapJson({ debugId: ID_A })); + put('b.js', 'b'); + const locked = put('locked.js', 'x'); + chmodSync(map, 0o000); + chmodSync(locked, 0o000); + try { + const report = await run(); + expect(find(report, 'map.unreadable')?.message).toContain('EACCES'); + expect(find(report, 'output.unreadable')).toMatchObject({ + severity: 'error', + details: { files: ['locked.js could not be read (EACCES)'] }, + }); + } finally { + chmodSync(map, 0o600); + chmodSync(locked, 0o600); + } + }); + + it('a script over the size limit is not read and is reported', async () => { + put('huge.js', 'x'.repeat(1000)); + put('ok.js', `a${stamp(ID_A)}`); + const report = await run({ maxBundleBytes: 999 }); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['huge.js is too large to read'], + }); + expect(report.summary.bundles).toBe(2); + expect(ids(await run({ maxBundleBytes: 1000 }))).not.toContain('output.unreadable'); + }); + + it('a map inside the directory but outside the walked set (node_modules) is still paired by its pointer', async () => { + put('a.js', `a\n//# sourceMappingURL=node_modules/a.map${stamp(ID_A)}`); + put('node_modules/a.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('node_modules/a.map'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('an indented sourceMappingURL comment is honoured', async () => { + put('a.js', `a\n \t//# sourceMappingURL=maps/x.map${stamp(ID_A)}`); + put('maps/x.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/x.map'); + }); + + it('a map that starts with a UTF-8 BOM is map.invalid and the message says BOM', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', `\uFEFF${mapJson({ debugId: ID_A })}`); + const report = await run(); + expect(find(report, 'map.invalid')?.message).toContain('BOM'); + expect(find(report, 'map.invalid')?.severity).toBe('error'); + }); +}); + +describe('source resolution', () => { + it('bundler-scheme sources resolve against the project root, not the map directory', async () => { + mkdirSync(join(root, 'src')); + writeFileSync(join(root, 'src', 'x.ts'), 'x'); + put('a.js', `a${stamp(ID_A)}`); + put( + 'deep/a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sources: ['webpack://app/./src/x.ts', 'webpack://app/./src/missing.ts'], + }), + ); + const report = await run(); + expect(find(report, 'map.sources-unresolvable')?.message).toContain('missing.ts'); + expect(find(report, 'map.sources-unresolvable')?.details).toEqual({ unresolved: 1, total: 2 }); + }); + + it('sourcePath: posix, project root, file URLs, virtual and malformed sources', () => { + expect(sourcePath('/m', '', 'webpack://app/./src/x.ts', '/proj', posix)).toBe('/proj/src/x.ts'); + expect(sourcePath('/m', '', 'webpack://app/./src/x.ts', undefined, posix)).toBe('/m/src/x.ts'); + expect(sourcePath('/m/d', '../s', 'a.ts', '/proj', posix)).toBe('/m/s/a.ts'); + expect(sourcePath('/m', '', '/abs/a.ts', undefined, posix)).toBe('/abs/a.ts'); + expect(sourcePath('/m', '', 'file:///x/a%20b.ts', undefined, posix)).toBe('/x/a b.ts'); + expect(sourcePath('/m', '', 'file:///x/%zz.ts', undefined, posix)).toBeUndefined(); + expect(sourcePath('/m', '', 'webpack/runtime/x', undefined, posix)).toBeUndefined(); + expect(sourcePath('/m', '', '', undefined, posix)).toBeUndefined(); + }); + + it('sourcePath on Windows: drive-letter file URLs and project-relative bundler paths', () => { + expect(sourcePath('C:\\m', '', 'file:///C:/x/a.ts', 'C:\\p', win32)).toBe('C:\\x\\a.ts'); + expect(sourcePath('C:\\m', '', 'webpack://app/./src/x.ts', 'C:\\p', win32)).toBe( + 'C:\\p\\src\\x.ts', + ); + expect(sourcePath('C:\\m', '..\\s', 'a.ts', 'C:\\p', win32)).toBe('C:\\s\\a.ts'); + expect(sourcePath('C:\\m', '', 'D:\\abs\\a.ts', 'C:\\p', win32)).toBe('D:\\abs\\a.ts'); + }); +}); + +describe('pointer reading and pairing (round 2)', () => { + it('a pointer with an unencoded space is read whole (the stamper reads to the end of the line)', async () => { + put('a.js', `a\n//# sourceMappingURL=maps/my map.map${stamp(ID_A)}`); + put('maps/my map.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/my map.map'); + }); + + it('the LAST sourceMappingURL comment wins', async () => { + put('a.js', `a\n//# sourceMappingURL=gone.map\n//# sourceMappingURL=real.map${stamp(ID_A)}`); + put('real.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('real.map'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('uppercase extensions are scripts and maps too, like the stamper', async () => { + put('A.JS', `a${stamp(ID_A)}`); + put('A.JS.map', mapJson({ debugId: ID_B })); + put('C.MAP', mapJson()); + const report = await run(); + expect(report.summary).toMatchObject({ bundles: 1, maps: 2 }); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('A.JS.map'); + }); + + it('a map shared by two bundles is validated once', async () => { + put('a.js', `a\n//# sourceMappingURL=shared.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=shared.map${stamp(ID_A)}`); + put('shared.map', mapJson({ debugId: ID_A, sources: [] })); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.no-sources')).toHaveLength(1); + }); + + it('isInside: the parent itself is outside, a `..`-prefixed NAME inside the directory is not', async () => { + put('a.js', `a\n//# sourceMappingURL=..${stamp(ID_A)}`); + put('..b/x.map', mapJson({ debugId: ID_B })); + put('b.js', `b\n//# sourceMappingURL=..b/x.map${stamp(ID_B)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')?.details).toEqual({ pointers: ['a.js -> ..'] }); + expect(ids(report)).not.toContain('map.unreadable'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('virtual sources never name a file; look-alikes do', () => { + for (const virtual of [ + 'webpack/runtime/x', + '(webpack)/buildin/x.js', + '\0virtual', + 'a\0b.ts', + '', + 'rollup:plugin/x', + 'vite/preload-helper.js', + ]) { + expect(sourcePath('/m', '', virtual, undefined, posix), virtual).toBeUndefined(); + } + for (const real of ['webpackx/a.ts', 'viteish/a.ts', 'rollupx.ts', 'webpack.config.js']) { + expect(sourcePath('/m', '', real, undefined, posix), real).toBe(`/m/${real}`); + } + }); +}); + +describe.skipIf(process.getuid?.() === 0)('an unreadable output directory', () => { + it('reports output.no-js and does not throw', async () => { + put('a.js', 'x'); + chmodSync(dist, 0o000); + try { + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(find(report, 'output.dir-unreadable')?.details).toEqual({ directories: ['.'] }); + } finally { + chmodSync(dist, 0o700); + } + }); + + it('an unreadable SUB-directory is an error naming it, never a silent pass', async () => { + put('registerSW.js', `a${stamp(ID_A)}`); + put('assets/index.js', 'unstamped'); + put('assets/deeper/x.js', 'x'); + chmodSync(join(dist, 'assets'), 0o000); + try { + const report = await run(); + expect(find(report, 'output.dir-unreadable')).toMatchObject({ + severity: 'error', + details: { directories: ['assets'] }, + }); + expect(report.passed).not.toContain('output.dir-unreadable'); + expect(doctorExitCode(report, false)).toBe(2); + } finally { + chmodSync(join(dist, 'assets'), 0o700); + } + expect(ids(await run())).not.toContain('output.dir-unreadable'); + }); + + it('--exclude can name an unreadable directory: it leaves output.dir-unreadable, is listed as excluded, and its pattern is matched', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('vendor/x.js', 'x'); + put('assets/y.js', 'y'); + chmodSync(join(dist, 'vendor'), 0o000); + chmodSync(join(dist, 'assets'), 0o000); + try { + for (const pattern of ['vendor/**', 'vendor/', '**/vendor/**', '**']) { + const report = await run({ exclude: [pattern] }); + const left = find(report, 'output.dir-unreadable')?.details?.directories; + expect(left, pattern).toEqual(pattern === '**' ? undefined : ['assets']); + expect(ids(report), pattern).not.toContain('output.exclude-unmatched'); + } + const report = await run({ exclude: ['vendor/**'] }); + expect( + report.findings.some( + (f) => + f.id === 'output.excluded' && + (f.details?.directories as string[] | undefined)?.includes('vendor'), + ), + ).toBe(true); + // a glob that would NOT hide the directory's files if it could be listed must not hide the directory either + for (const pattern of [ + 'vendor', + 'vendor*', + 'vendor/*', + '*', + 'assets/*', + 'vendor/**/*.js', + '**/*.js', + '**/a/**', + 'vendor/**/*.map', + ]) { + const kept = find(await run({ exclude: [pattern] }), 'output.dir-unreadable')?.details; + expect(kept, pattern).toEqual({ directories: ['assets', 'vendor'] }); + } + expect(find(await run({ exclude: ['nope/**'] }), 'output.dir-unreadable')?.details).toEqual({ + directories: ['assets', 'vendor'], + }); + } finally { + chmodSync(join(dist, 'vendor'), 0o700); + chmodSync(join(dist, 'assets'), 0o700); + } + }); + + it('several unreadable directories are listed, sorted', async () => { + put('a.js', `a${stamp(ID_A)}`); + for (let i = 2; i >= 0; i--) { + put(`d${i}/p.js`, 'x'); + chmodSync(join(dist, `d${i}`), 0o000); + } + try { + const finding = find(await run(), 'output.dir-unreadable'); + expect(finding?.details).toEqual({ directories: ['d0', 'd1', 'd2'] }); + } finally { + for (let i = 0; i < 3; i++) { + chmodSync(join(dist, `d${i}`), 0o700); + } + } + }); + + it('a directory only the HTML page walk enters (src/, which the fenced script walk skips) is reported too', async () => { + put('package.json', '{"name":"p"}'); + put('a.js', `a${stamp(ID_A)}`); + put('src/p.html', '

'); + chmodSync(join(dist, 'src'), 0o000); + const here = process.cwd(); + process.chdir(dist); + try { + const finding = find(await run(), 'output.dir-unreadable'); + expect(finding?.details).toEqual({ directories: ['src'] }); + } finally { + process.chdir(here); + chmodSync(join(dist, 'src'), 0o700); + } + }); +}); + +describe('CRLF bundles (a Windows toolchain)', () => { + it('an inline map after a CRLF line is still map.inline, and a pointer with CR is paired', async () => { + put('a.js', `a\r\n//# sourceMappingURL=data:application/json;base64,e30=\r\n${stamp(ID_A)}`); + put('b.js', `b\r\n//# sourceMappingURL=maps/b.map\r\n${stamp(ID_B)}`); + put('maps/b.map', mapJson({ debugId: ID_A })); + const report = await run(); + expect(find(report, 'map.inline')?.details).toEqual({ files: ['a.js'] }); + expect(find(report, 'stamp.map-id-mismatch')?.file).toBe('maps/b.map'); + expect(ids(report)).not.toContain('map.hidden'); + }); +}); + +describe('symlinks never lead outside the output directory (round 3)', () => { + const secretMap = (): string => + JSON.stringify({ + version: 3, + debugId: ID_B, + sources: ['TOP-SECRET-SOURCE-PATH.ts'], + sourcesContent: ['TOP-SECRET-CONTENT'], + mappings: 'AAAA', + }); + + it('a pointer through a symlinked DIRECTORY is not read: no outside content in any output', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'secret.json'), secretMap()); + symlinkSync(outside, join(dist, 'link')); + put('app.js', `a\n//# sourceMappingURL=link/secret.json${stamp(ID_A)}`); + const report = await run(); + expect(find(report, 'map.pointer-outside-dir')?.details).toEqual({ + pointers: ['app.js -> link/secret.json'], + }); + const everything = JSON.stringify(report); + expect(everything).not.toContain('TOP-SECRET'); + expect(everything).not.toContain(ID_B); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('a pointer through a symlinked directory that stays INSIDE the directory is read normally', async () => { + put('real/x.map', mapJson({ debugId: ID_B })); + symlinkSync(join(dist, 'real'), join(dist, 'alias')); + put('app.js', `a\n//# sourceMappingURL=alias/x.map${stamp(ID_A)}`); + const report = await run(); + expect(find(report, 'stamp.map-id-mismatch')).toBeDefined(); + }); + + it('a symlinked directory that leaves the output directory is never descended into by the walk', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'o.js'), 'x'); + symlinkSync(outside, join(dist, 'linkdir')); + put('a.js', `a${stamp(ID_A)}`); + expect(relFiles(await walk(dist))).toEqual(['a.js']); + }); + + it('a symlinked bundle that leads OUTSIDE is reported, not silently invisible (no misleading output.no-js)', async () => { + const real = join(root, 'real.js'); + writeFileSync(real, `a${stamp(ID_A)}`); + symlinkSync(real, join(dist, 'app.js')); + const report = await run(); + // not the misleading "No .js files found": the script IS there, and nothing could be read + expect(find(report, 'output.no-js')?.message).toContain('could be read'); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['app.js resolves outside the output directory'], + }); + expect(report.summary.bundles).toBe(1); + }); + + it('a manifest that is a symlink to a file outside is not read', async () => { + const outside = join(root, 'outside-manifest.json'); + writeFileSync(outside, '{"integrity":"x"}'); + symlinkSync(outside, join(dist, 'asset-manifest.json')); + put('a.js', `a${stamp(ID_A)}`); + expect(ids(await run())).not.toContain('sri.manifest-hashes'); + }); + + it('an uppercase MANIFEST.JSON is still a manifest', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('ASSET-MANIFEST.JSON', '{"integrity":"x"}'); + expect(ids(await run())).toContain('sri.manifest-hashes'); + }); +}); + +describe('--ignore cannot hide a hard failure (round 3)', () => { + it('output.dir-missing, output.no-js and doctor.internal-error stay in the report', async () => { + const missing = await diagnoseBuildOutput(join(root, 'nope'), { + ignore: ['output.dir-missing'], + skipEnv: true, + }); + expect(ids(missing)).toEqual(['output.dir-missing']); + expect(missing.summary.errors).toBe(1); + expect(missing.ignored).toBeUndefined(); + const empty = await run({ ignore: ['output.no-js', 'map.public-leftover'] }); + expect(ids(empty)).toEqual(['output.no-js']); + expect(empty.ignored).toBeUndefined(); + }); +}); + +describe('SRI reads are as guarded as every other read (review thread)', () => { + const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const page = (src: string, integrity: string): string => + ``; + + it('a pinned script that is a FIFO never hangs the doctor', async () => { + if (spawnSync('mkfifo', [join(dist, 'app.js')]).status !== 0) { + return; + } + put('index.html', page('app.js', sri('x'))); + const report = await run(); + // a FIFO named like a script is listed and refused (never opened), and the pin does not open it either + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['app.js is not a regular file'], + }); + expect(find(report, 'output.no-js')?.message).toContain('could be read'); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + expect(find(report, 'sri.pin-unreadable')?.details).toEqual({ + scripts: ['app.js is not a regular file'], + }); + }, 10_000); + + it('a pinned symlink to /dev/zero is refused, never read', async () => { + symlinkSync('/dev/zero', join(dist, 'zero.js')); + put('index.html', page('zero.js', sri('x'))); + const report = await run(); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['zero.js resolves outside the output directory'], + }); + expect(find(report, 'sri.pin-unreadable')?.details).toEqual({ + scripts: ['zero.js resolves outside the output directory'], + }); + expect(ids(report)).not.toContain('sri.mismatch'); + }, 10_000); + + it('a pinned script reached through a symlinked directory is not read or hashed', async () => { + const outside = join(root, 'outside'); + mkdirSync(outside); + writeFileSync(join(outside, 'app.js'), `x${stamp(ID_A)}`); + symlinkSync(outside, join(dist, 'vendor')); + put('index.html', page('vendor/app.js', sri('something else'))); + const report = await run(); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + }); + + it('a pinned regular script whose bytes no longer match is still sri.mismatch (read once)', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('index.html', page('app.js', sri('c'))); + const report = await run(); + expect(find(report, 'sri.mismatch')?.details).toEqual({ scripts: ['app.js'] }); + }); +}); + +describe('symlinks that stay inside the directory (round 4)', () => { + it('a pnpm-style symlinked bundle and map are read through their real path: no error, no double report', async () => { + put('.store/app.js', `c\n//# sourceMappingURL=app.js.map${stamp(ID_A)}`); + put('.store/app.js.map', mapJson({ debugId: ID_A })); + mkdirSync(join(dist, 'assets')); + symlinkSync(join(dist, '.store', 'app.js'), join(dist, 'assets', 'app.js')); + symlinkSync(join(dist, '.store', 'app.js.map'), join(dist, 'assets', 'app.js.map')); + const report = await run(); + expect(report.summary.errors).toBe(0); + expect(ids(report)).not.toContain('output.unreadable'); + expect(ids(report)).not.toContain('map.unreadable'); + expect(ids(report)).not.toContain('stamp.duplicate-debug-id'); + }); + + it('a symlink to a file inside whose map id differs is judged like the real file', async () => { + put('.store/app.js', `c${stamp(ID_A)}`); + put('.store/app.js.map', mapJson({ debugId: ID_B })); + symlinkSync(join(dist, '.store', 'app.js'), join(dist, 'app.js')); + symlinkSync(join(dist, '.store', 'app.js.map'), join(dist, 'app.js.map')); + const report = await run(); + expect(ids(report)).toContain('stamp.map-id-mismatch'); + }); + + it('a dangling or looping symlink is still reported, never read', async () => { + symlinkSync(join(dist, 'nowhere.js'), join(dist, 'dangling.js')); + symlinkSync(join(dist, 'loop-b.js'), join(dist, 'loop-a.js')); + symlinkSync(join(dist, 'loop-a.js'), join(dist, 'loop-b.js')); + put('ok.js', `a${stamp(ID_A)}`); + const report = await run(); + const files = (find(report, 'output.unreadable')?.details?.files as string[]).sort(); + expect(files).toEqual([ + 'dangling.js could not be resolved (ENOENT)', + 'loop-a.js could not be resolved (ELOOP)', + 'loop-b.js could not be resolved (ELOOP)', + ]); + }); + + it('a pinned script that is a symlink INSIDE the directory is read: a mismatch is not silently skipped', async () => { + put('.store/app.js', `c${stamp(ID_A)}`); + symlinkSync(join(dist, '.store', 'app.js'), join(dist, 'app.js')); + put('index.html', ``); + const report = await run(); + expect(find(report, 'sri.mismatch')?.details).toEqual({ scripts: ['app.js'] }); + expect(ids(report)).not.toContain('sri.pin-unreadable'); + }); + + it('a map reached through two names is validated once', async () => { + put('real/x.map', 'not json'); + symlinkSync(join(dist, 'real'), join(dist, 'alias')); + put('a.js', `a\n//# sourceMappingURL=real/x.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=alias/x.map${stamp(ID_B)}`); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.invalid')).toHaveLength(1); + }); +}); + +describe('big outputs stay readable (round 4)', () => { + it('sources-content notes: a few are listed, many become ONE finding with counts', async () => { + for (let i = 0; i < 3; i++) { + put(`s${i}.js`, `a${stamp(`0000000${i}-1111-4111-8111-111111111111`)}`); + put(`s${i}.js.map`, mapJson({ debugId: `0000000${i}-1111-4111-8111-111111111111` })); + } + const few = await run(); + expect(few.findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(3); + // 10 notes (2 x the listing cap) are still listed one by one; the 11th folds them into one finding. + for (let i = 3; i < 10; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + const ten = await run(); + expect(ten.findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(10); + for (let i = 10; i < 11; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + expect((await run()).findings.filter((f) => f.id === 'map.sources-content')).toHaveLength(1); + for (let i = 11; i < 14; i++) { + const id = `${i.toString(16).padStart(8, '0')}-1111-4111-8111-111111111111`; + put(`s${i}.js`, `a${stamp(id)}`); + put(`s${i}.js.map`, mapJson({ debugId: id })); + } + const many = await run(); + const notes = many.findings.filter((f) => f.id === 'map.sources-content'); + expect(notes).toHaveLength(1); + expect(notes[0]?.details).toEqual({ maps: 14, embedded: 14, resolvableOnDisk: 0 }); + expect(notes[0]?.file).toBeUndefined(); + }); + + it('a list of exactly 100 is not capped and carries no total', async () => { + for (let i = 0; i < 100; i++) { + put(`e${i}.js`, `x${i}`); + } + const finding = find(await run(), 'stamp.missing-debug-id'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details).not.toHaveProperty('total'); + }); + + it('long file lists in details are capped, with the total', async () => { + for (let i = 0; i < 130; i++) { + put(`v${i}.js`, `x${i}`); + } + const report = await run(); + const finding = find(report, 'stamp.missing-debug-id'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details?.total).toBe(130); + put('w.js', 'x'); + const exact = await run(); + expect(find(exact, 'stamp.missing-debug-id')?.details?.total).toBe(131); + }); + + it('an oversized page is reported as sri.html-skipped, and the rest of the audit goes on', async () => { + put('a.js', `a${stamp(ID_A)}`); + const big = put('huge.html', ''); + truncateSync(big, 8 * 1024 * 1024 + 1); + const report = await run(); + expect(find(report, 'sri.html-skipped')).toMatchObject({ + severity: 'warning', + details: { files: ['huge.html'] }, + }); + expect(report.summary.bundles).toBe(1); + }); + + it('--exclude applies to HTML pages too: an oversized or unreadable excluded page is not reported, and its pattern is matched', async () => { + put('a.js', `a${stamp(ID_A)}`); + truncateSync(put('huge.html', ''), 8 * 1024 * 1024 + 1); + truncateSync(put('keep/huge2.html', ''), 8 * 1024 * 1024 + 1); + const report = await run({ exclude: ['huge.html'] }); + expect(find(report, 'sri.html-skipped')?.details).toEqual({ files: ['keep/huge2.html'] }); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + expect(ids(await run({ exclude: ['**/*.html'] }))).not.toContain('sri.html-skipped'); + }); + + it.skipIf(process.getuid?.() === 0)( + 'an unreadable excluded page is not reported either', + async () => { + put('a.js', `a${stamp(ID_A)}`); + const page = put('locked.html', '

'); + chmodSync(page, 0o000); + try { + expect(ids(await run())).toContain('sri.html-skipped'); + const report = await run({ exclude: ['locked.html'] }); + expect(ids(report)).not.toContain('sri.html-skipped'); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + } finally { + chmodSync(page, 0o600); + } + }, + ); + + it('a page of pathological unterminated tags does not stall the doctor', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('index.html', '`); + const before = await run(); + expect(ids(before)).toContain('sri.mismatch'); + const after = await run({ exclude: ['vendor.js'] }); + expect(ids(after)).not.toContain('sri.mismatch'); + expect(ids(after)).not.toContain('sri.unstamped-hazard'); + }); + + it('a pointer to an excluded map is neither read nor reported', async () => { + put('a.js', `a\n//# sourceMappingURL=maps/a.js.map${stamp(ID_A)}`); + put('maps/a.js.map', mapJson({ debugId: ID_B })); + expect(ids(await run())).toContain('stamp.map-id-mismatch'); + const report = await run({ exclude: ['maps/**'] }); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(find(report, 'output.excluded')?.details).toEqual({ files: ['maps/a.js.map'] }); + }); + + it('a pattern that matches only an SRI pin outside the walked files still counts as matched', async () => { + put('package.json', '{"name":"p"}'); + put('app.js', `a${stamp(ID_A)}`); + put('tests/vendor.js', 'v'); // in a fenced (skipped) directory: not in the walk + put('index.html', ``); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run({ exclude: ['tests/vendor.js'] }); + expect(ids(report)).not.toContain('output.exclude-unmatched'); + expect(ids(report)).not.toContain('sri.mismatch'); + } finally { + process.chdir(here); + } + }); + + it('the new info-only IDs are facts, never "passed"', async () => { + healthy(); + put('public/x.js', 'x'); + const report = await run({ exclude: ['public/**'] }); + expect(report.passed).not.toContain('output.excluded'); + expect(report.passed).not.toContain('output.exclude-unmatched'); + expect(report.passed).not.toContain('output.walk-fenced'); + }); + + it('glob semantics: * stays in a directory, ** crosses them, ? is one character, a trailing / is a directory', async () => { + healthy(); + put('a1.js', 'x'); + put('sub/a2.js', 'x'); + put('sub/deep/a3.js', 'x'); + put('vendor/v.js', 'x'); + put('vendor/xv.js', 'x'); + const excluded = async (pattern: string): Promise => + (find(await run({ exclude: [pattern] }), 'output.excluded')?.details?.files as string[]) ?? + []; + expect(await excluded('a?.js')).toEqual(['a1.js']); + expect(await excluded('*.js')).toEqual(['a1.js', 'app.js']); + expect(await excluded('**/*.js')).toEqual([ + 'a1.js', + 'app.js', + 'sub/a2.js', + 'sub/deep/a3.js', + 'vendor/v.js', + 'vendor/xv.js', + ]); + expect(await excluded('sub/*.js')).toEqual(['sub/a2.js']); + expect(await excluded('sub/**')).toEqual(['sub/a2.js', 'sub/deep/a3.js']); + expect(await excluded('vendor/')).toEqual(['vendor/v.js', 'vendor/xv.js']); + expect(await excluded('a.js')).toEqual([]); // `.` is a literal dot, not "any character" + expect(await excluded('a1+js')).toEqual([]); + expect(await excluded('[a]1.js')).toEqual([]); // regex syntax in a glob is literal + expect(await excluded('sub?a2.js')).toEqual([]); // `?` is never a slash + expect(await excluded('**/v.js')).toEqual(['vendor/v.js']); // `**/` is whole path segments: xv.js is not v.js + expect(await excluded('**/a2.js')).toEqual(['sub/a2.js']); + expect(await excluded('**/p.js')).toEqual([]); + }); + + it('excluding every script leaves output.no-js, which cannot be hidden', async () => { + put('public/sw.js', 's'); + const report = await run({ exclude: ['**'] }); + expect(ids(report)).toContain('output.no-js'); + }); + + it('a long exclusion list is capped, with the total', async () => { + healthy(); + for (let i = 0; i < 120; i++) { + put(`public/f${i}.js`, 'x'); + } + const finding = find(await run({ exclude: ['public/**'] }), 'output.excluded'); + expect((finding?.details?.files as string[]).length).toBe(100); + expect(finding?.details?.total).toBe(120); + }); +}); + +describe('the walk fence is reported, and needs a real project directory (round 6)', () => { + const inDist = async (options: Parameters[0] = {}): Promise => { + const here = process.cwd(); + process.chdir(dist); + try { + return await run(options); + } finally { + process.chdir(here); + } + }; + + it('run from inside an output directory WITHOUT a package.json, src/ and dot-directories are audited', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + const report = await inDist(); + expect(report.summary.bundles).toBe(4); + expect(ids(report)).not.toContain('output.walk-fenced'); + }); + + it('a directory that is the project (has a package.json) is fenced, and the report lists what was skipped', async () => { + put('package.json', '{"name":"p"}'); + put('a.js', `a${stamp(ID_A)}`); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + put('tests/t.js', 'x'); + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + const report = await inDist(); + expect(report.summary.bundles).toBe(1); + expect(find(report, 'output.walk-fenced')).toMatchObject({ + severity: 'info', + details: { directories: ['.cache', 'a/b/c/d/e/f/g', 'src', 'tests'] }, + }); + }); + + it('a project directory that is not the working directory is not fenced', async () => { + put('package.json', '{"name":"p"}'); + put('src/s.js', 'x'); + put('a.js', `a${stamp(ID_A)}`); + expect((await run()).summary.bundles).toBe(2); + }); +}); + +describe('round 7 review findings', () => { + const mkfifo = (path: string): boolean => spawnSync('mkfifo', [path]).status === 0; + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + + it('when EVERY script is unreadable the audit cannot pass, even with --ignore output.unreadable', async () => { + if (!mkfifo(join(dist, 'a.js'))) { + return; + } + const report = await run({ ignore: ['output.unreadable'] }); + expect(find(report, 'output.no-js')).toMatchObject({ severity: 'error' }); + expect(find(report, 'output.no-js')?.message).toContain('could be read'); + }); + + it('some unreadable scripts are an ordinary, ignorable finding', async () => { + put('ok.js', `a${stamp(ID_A)}`); + if (!mkfifo(join(dist, 'a.js'))) { + return; + } + const report = await run({ ignore: ['output.unreadable'] }); + expect(ids(report)).not.toContain('output.no-js'); + }); + + it('a version-3 map without mappings (or sections) is map.invalid', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put( + 'a.js.map', + JSON.stringify({ version: 3, sources: ['a.ts'], sourcesContent: ['x'], debugId: ID_A }), + ); + const report = await run(); + expect(find(report, 'map.invalid')?.message).toContain('mappings'); + const sectioned = { + debugId: ID_A, + mappings: undefined, + sources: undefined, + sourcesContent: undefined, + sections: [ + { + offset: { line: 0, column: 0 }, + map: { + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + names: [], + mappings: 'AAAA', + }, + }, + ], + }; + put('a.js.map', mapJson(sectioned)); + expect(ids(await run())).not.toContain('map.invalid'); + put('a.js.map', mapJson({ debugId: ID_A, mappings: 5 })); + expect(ids(await run())).toContain('map.invalid'); + }); + + it('an unreadable HTML page is reported as not scanned, never silently passed', async () => { + put('a.js', `a${stamp(ID_A)}`); + const page = put('index.html', ``); + chmodSync(page, 0o000); + try { + if (spawnSync('sh', ['-c', `cat '${page}' >/dev/null 2>&1`]).status === 0) { + return; // running as root: the permission does not bite + } + const finding = find(await run(), 'sri.html-skipped'); + expect(finding).toMatchObject({ severity: 'warning', details: { files: ['index.html'] } }); + expect(finding?.message).toContain('could not be read'); + } finally { + chmodSync(page, 0o600); + } + }); + + it('the same script pinned by two pages with different hashes: the stale pin is reported', async () => { + const js = `console.log(1);${stamp(ID_A)}`; + put('a.js', js); + put('a.html', ``); + put('b.html', ``); + const report = await run(); + expect(find(report, 'sri.mismatch')).toMatchObject({ details: { scripts: ['a.js'] } }); + }); + + it('passed lists only checks that had input: nothing for the stamp/map checks of an empty directory', async () => { + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + for (const id of [ + 'stamp.missing-registration', + 'stamp.map-id-mismatch', + 'map.invalid', + 'build.dev-bundle', + ]) { + expect(report.passed).not.toContain(id); + } + put('a.js', `a${stamp(ID_A)}`); + const healthy = await run(); + expect(healthy.passed).toContain('stamp.missing-registration'); + expect(healthy.passed).not.toContain('map.invalid'); // a bundle but no map: nothing to validate + put('a.js.map', mapJson({ debugId: ID_A })); + expect((await run()).passed).toContain('map.invalid'); + }); +}); + +describe('batchEnd bounds the bytes read at once', () => { + it('stops at the count limit, at the byte budget, and always takes at least one', () => { + expect(batchEnd([1, 1, 1, 1], 0, 2, 100)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 25)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 20)).toBe(2); + expect(batchEnd([10, 10, 10, 10], 0, 16, 40)).toBe(4); + expect(batchEnd([500, 1, 1], 0, 16, 100)).toBe(1); + expect(batchEnd([1, 500, 1], 1, 16, 100)).toBe(2); + expect(batchEnd([1, 1], 1, 16, 100)).toBe(2); + }); +}); + +describe('the SRI page walk follows the doctor fence (round 8)', () => { + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const pin = (): void => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + }; + + it('an output directory is scanned for pages in test/, dot-directories and deep paths too', async () => { + pin(); + put( + 'tests/index.html', + '', + ); + expect(ids(await run())).toContain('sri.mismatch'); + rmSync(join(dist, 'tests'), { recursive: true }); + put('.well/p.html', ''); + expect(ids(await run())).toContain('sri.mismatch'); + rmSync(join(dist, '.well'), { recursive: true }); + put( + 'a/b/c/d/e/f/g/h/p.html', + '', + ); + expect(ids(await run())).toContain('sri.mismatch'); + }); + + it('a fenced project directory keeps the fence for pages too, and the walk-fenced finding says what was skipped', async () => { + put('package.json', '{"name":"p"}'); + pin(); + put( + 'tests/index.html', + '', + ); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run(); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(find(report, 'output.walk-fenced')?.details).toEqual({ directories: ['tests'] }); + } finally { + process.chdir(here); + } + }); +}); + +describe('a pointer with a ?query (webpack / Rspack [name].js?[contenthash]) (round 9)', () => { + it('pairs the map the query-less path names, and does not call the pointer dangling', async () => { + // NOT a sibling: only following the pointer (query cut) can find it, so the mismatch proves the pairing + put('main.js', `a\n//# sourceMappingURL=maps/main.js.map?3872346a403b27a7${stamp(ID_A)}`); + put('maps/main.js.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('map.hidden'); + }); + + it('a query on a pointer to a map that is not there is still dangling, reported as written', async () => { + put('main.js', `a\n//# sourceMappingURL=gone.js.map?abc${stamp(ID_A)}`); + expect(find(await run(), 'map.pointer-dangling')?.details).toEqual({ + pointers: ['main.js -> gone.js.map?abc'], + }); + }); + + it('an excluded map named with a query is neither read nor dangling', async () => { + put('main.js', `a\n//# sourceMappingURL=maps/main.js.map?x${stamp(ID_A)}`); + put('maps/main.js.map', mapJson({ debugId: ID_B })); + const report = await run({ exclude: ['maps/**'] }); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + }); +}); + +describe('index (sectioned) source maps (round 10)', () => { + // Sections must not overlap: each starts at a later generated line. + const index = (sections: unknown[], extra: Record = {}): string => + JSON.stringify({ + version: 3, + sections: sections.map((s, i) => + typeof s === 'object' && s !== null && 'offset' in s + ? { ...s, offset: { line: i * 10, column: 0 } } + : s, + ), + ...extra, + }); + const section = (sources: string[], content?: string[]) => ({ + offset: { line: 0, column: 0 }, + map: { + version: 3, + sources, + ...(content ? { sourcesContent: content } : {}), + names: [], + mappings: 'AAAA', + }, + }); + const pair = (map: string): void => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put('a.js.map', map); + }; + + it('sources live inside the sections: not map.no-sources, and the embedded content is counted', async () => { + pair(index([section(['a.ts'], ['x']), section(['b.ts'], ['y'])], { debugId: ID_A })); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('map.invalid'); + expect(find(report, 'map.sources-content')?.message).toContain('all 2 sources'); + }); + + it('sections without sourcesContent and with sources not on disk: map.sources-unresolvable', async () => { + pair(index([section(['a.ts']), section(['b.ts'], ['y'])], { debugId: ID_A })); + const report = await run(); + expect(find(report, 'map.sources-unresolvable')?.details).toEqual({ unresolved: 1, total: 2 }); + }); + + it('an index map whose sections carry no sources is still map.no-sources', async () => { + pair(index([section([]), { offset: { line: 1, column: 0 }, url: 'x.map' }], { debugId: ID_A })); + expect(ids(await run())).toContain('map.no-sources'); + pair(index([], { debugId: ID_A })); // no sections at all: nothing generated; the bundle `a` is real code: error + expect(find(await run(), 'map.no-sources')?.severity).toBe('error'); + put('a.js', `export{a}from'./m.js';${stamp(ID_A)}`); // as a facade it is fine + expect(find(await run(), 'map.no-sources')?.severity).toBe('info'); + }); + + it('content stays aligned per section: a second source without content is the one reported', async () => { + pair(index([section(['a.ts', 'b.ts'], ['x'])], { debugId: ID_A })); + expect(find(await run(), 'map.sources-unresolvable')?.details).toEqual({ + unresolved: 1, + total: 2, + }); + }); + + it('an empty top-level sources array falls through to the sections; a section without a map or sources is skipped', async () => { + pair( + index( + [section(['a.ts'], ['x']), { offset: { line: 1, column: 0 }, map: { version: 3 } }, null], + { debugId: ID_A, sources: [] }, + ), + ); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(find(report, 'map.sources-content')?.message).toContain('all 1 sources'); + }); + + it("each section's sources are resolved with the section's own sourceRoot", async () => { + put('src/a.ts', 'x'); + const withRoot = { + offset: { line: 0, column: 0 }, + map: { version: 3, sourceRoot: 'src/', sources: ['a.ts'], names: [], mappings: 'AAAA' }, + }; + pair(index([withRoot], { debugId: ID_A })); + expect(ids(await run())).not.toContain('map.sources-unresolvable'); + put('src/a.ts', 'x'); + const wrongRoot = { ...withRoot, map: { ...withRoot.map, sourceRoot: 'nope/' } }; + pair(index([wrongRoot], { debugId: ID_A })); + expect(ids(await run())).toContain('map.sources-unresolvable'); + }); + + it('nested index maps: leaves are found at any depth, each with its own sourceRoot and content', async () => { + put('lib/b.ts', 'y'); + const leaf = (root: string, sources: string[], content?: string[]) => ({ + offset: { line: 0, column: 0 }, + map: { + version: 3, + sourceRoot: root, + sources, + ...(content ? { sourcesContent: content } : {}), + names: [], + mappings: 'AAAA', + }, + }); + const inner = { + offset: { line: 5, column: 0 }, + map: { version: 3, sections: [leaf('lib/', ['b.ts'])] }, + }; + pair(index([leaf('', ['a.ts'], ['x']), inner], { debugId: ID_A })); + const report = await run(); + expect(ids(report)).not.toContain('map.no-sources'); + expect(ids(report)).not.toContain('map.sources-unresolvable'); // b.ts is under lib/, via the leaf's root + const wrong = { + offset: { line: 5, column: 0 }, + map: { version: 3, sections: [leaf('nope/', ['b.ts'])] }, + }; + pair(index([leaf('', ['a.ts'], ['x']), wrong], { debugId: ID_A })); + expect(find(await run(), 'map.sources-unresolvable')?.details).toEqual({ + unresolved: 1, + total: 2, + }); + }); + + it('index maps are followed to a bounded depth (32): a leaf within it is found, one beyond it is not', async () => { + const chain = (depth: number): string => { + let map: Record = { + version: 3, + sources: ['a.ts'], + sourcesContent: ['x'], + mappings: 'A', + }; + for (let i = 0; i < depth; i++) { + map = { version: 3, sections: [{ offset: { line: 0, column: 0 }, map }] }; + } + return JSON.stringify({ ...map, debugId: ID_A }); + }; + pair(chain(30)); + expect(ids(await run())).not.toContain('map.no-sources'); + pair(chain(40)); + const report = await run(); + expect(ids(report)).toContain('map.no-sources'); + expect(ids(report)).not.toContain('doctor.internal-error'); + }); + + it('top-level sources win over sections', async () => { + pair( + index([section(['z.ts'], ['z'])], { + debugId: ID_A, + sources: ['a.ts'], + sourcesContent: ['x'], + mappings: 'AAAA', + }), + ); + expect(find(await run(), 'map.sources-content')?.message).toContain('all 1 sources'); + }); +}); + +// Windows does not allow a `?` in a path component: the fixture cannot be created there +describe.skipIf(process.platform === 'win32')( + 'a ? in the checked directory path (round 11)', + () => { + it('the pointer is judged on its own query, not on a ? anywhere in the absolute path', async () => { + const weird = join(root, 'we?ird'); + mkdirSync(weird); + const out = join(weird, 'dist'); + mkdirSync(out); + writeFileSync(join(out, 'a.js'), `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + writeFileSync(join(out, 'a.js.map'), mapJson({ debugId: ID_A })); + const report = await diagnoseBuildOutput(out, { projectRoot: root, skipEnv: true }); + expect(ids(report)).not.toContain('map.pointer-outside-dir'); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(ids(report)).not.toContain('map.hidden'); // the pointer paired a.js.map + expect(report.summary.errors + report.summary.warnings).toBe(0); + }); + }, +); + +describe('a scheme in sourceRoot (round 12)', () => { + it('sourceRoot + source is one URL: webpack:/// + src/x.ts names /src/x.ts', async () => { + put('../src/x.ts', 'x'); + const body = { debugId: ID_A, sourcesContent: undefined, sources: ['src/x.ts'] }; + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + for (const sourceRoot of ['webpack:///', 'webpack://app/', 'webpack://app']) { + put('a.js.map', mapJson({ ...body, sourceRoot })); + expect(ids(await run()), sourceRoot).not.toContain('map.sources-unresolvable'); + } + put('a.js.map', mapJson({ ...body, sourceRoot: 'webpack:///', sources: ['src/missing.ts'] })); + expect(ids(await run())).toContain('map.sources-unresolvable'); + }); +}); + +describe('symlinked HTML pages are scanned, or reported, never skipped silently (round 12)', () => { + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const stalePage = ``; + + it('a link to a page inside the directory is read through its real path (stale pin found)', async () => { + put('a.js', `console.log(1);${stamp(ID_A)}`); + // `a.js` from pages/ is pages/a.js (absent): only the link at the ROOT resolves this pin to the script under test + put('pages/real.html', stalePage); + symlinkSync(join(dist, 'pages', 'real.html'), join(dist, 'index.html')); + const report = await run(); + expect(ids(report)).toContain('sri.mismatch'); + }); + + it('a link that leads outside the directory (or dangles) is reported as not scanned', async () => { + put('a.js', `a${stamp(ID_A)}`); + writeFileSync(join(root, 'outside.html'), stalePage); + symlinkSync(join(root, 'outside.html'), join(dist, 'out.html')); + symlinkSync(join(root, 'nowhere.html'), join(dist, 'dangling.html')); + const finding = find(await run(), 'sri.html-skipped'); + expect(finding).toMatchObject({ + severity: 'warning', + details: { files: ['dangling.html', 'out.html'] }, + }); + expect(ids(await run())).not.toContain('sri.mismatch'); + }); +}); + +describe('sourcePath with a scheme sourceRoot (unit)', () => { + it('a source that already carries its own scheme or is absolute ignores the root', () => { + const map = '/p/dist'; + const proj = '/p'; + expect(sourcePath(map, 'webpack:///', 'src/x.ts', proj, posix)).toBe('/p/src/x.ts'); + expect(sourcePath(map, 'webpack:///', 'webpack://app/src/x.ts', proj, posix)).toBe( + '/p/src/x.ts', + ); + expect(sourcePath(map, 'webpack:///', 'file:///tmp/y.ts', proj, posix)).toBe('/tmp/y.ts'); + expect(sourcePath(map, 'webpack:///', '/abs/z.ts', proj, posix)).toBe('/abs/z.ts'); + expect(sourcePath(map, 'https://h/r', '/abs/z.ts', proj, posix)).toBe('/abs/z.ts'); + // a non-URL source with a single-colon scheme is not joined to the root either: it resolves from the map + expect(sourcePath(map, 'webpack:///', 'node:fs', proj, posix)).toBe('/p/dist/webpack:/node:fs'); + // file URL semantics follow the path API it is given, not the host: a drive letter is a plain path segment here + expect(sourcePath('/m', '', 'file:///C:/x/a.ts', '/p', posix)).toBe('/C:/x/a.ts'); + }); +}); + +describe('round 13 review findings', () => { + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + const pair = (map: string, bundle = 'a.js'): void => { + put(bundle, `a\n//# sourceMappingURL=${bundle}.map${stamp(ID_A)}`); + put(`${bundle}.map`, map); + }; + + it("--exclude applies to a READABLE page before its pins are collected (and cannot claim an included page's pin)", async () => { + const js = `console.log(1);${stamp(ID_A)}`; + put('app.js', js); + const stale = ``; + put('a-legacy/x.html', stale.replace('/app.js', '../app.js')); + expect(ids(await run())).toContain('sri.mismatch'); + expect(ids(await run({ exclude: ['a-legacy/**'] }))).not.toContain('sri.mismatch'); + expect(ids(await run({ exclude: ['a-legacy/**'] }))).not.toContain('output.exclude-unmatched'); + // an included page with the SAME pin is still judged although the excluded page sorts first + put('index.html', stale.replace('/app.js', 'app.js')); + const report = await run({ exclude: ['a-legacy/**'] }); + expect(find(report, 'sri.mismatch')?.details).toEqual({ scripts: ['app.js'] }); + }); + + it('a map with no original positions (empty, generated-only, short segments) is map.invalid; a mixed one is fine', async () => { + for (const mappings of ['', ';;;', 'A', 'AAA', 'AAAA;;AAAA', 'A,AAAA', 'AAAAA', 'AAAAIAAAA']) { + pair(mapJson({ debugId: ID_A, mappings })); + const invalid = find(await run(), 'map.invalid'); + const expectInvalid = ['', ';;;', 'A', 'AAA'].includes(mappings); + expect(invalid !== undefined, `mappings ${JSON.stringify(mappings)}`).toBe(expectInvalid); + if (expectInvalid) { + expect(invalid?.message).toContain('original'); + } + } + }); + + it('hasOriginalPosition: a segment needs four or more VLQ values (continuation bits respected)', () => { + expect(hasOriginalPosition('AAAA')).toBe(true); + expect(hasOriginalPosition('AAA')).toBe(false); + expect(hasOriginalPosition('')).toBe(false); + expect(hasOriginalPosition(',,;')).toBe(false); + expect(hasOriginalPosition('A;AAAA')).toBe(true); + expect(hasOriginalPosition('A,AAAA')).toBe(true); + // `gB` is ONE value (g has the continuation bit): gBAAA is 4 values, gBAA is 3 + expect(hasOriginalPosition('gBAAA')).toBe(true); + expect(hasOriginalPosition('gBAA')).toBe(false); + expect(hasOriginalPosition('AAA$A')).toBe(false); // not base64: that segment is unusable + expect(hasOriginalPosition('AA$A,AAAA')).toBe(true); + expect(hasOriginalPosition('AAAA$')).toBe(false); // a bad character spoils the whole segment, wherever it is + }); + + it('hasOriginalPosition answers from the first usable segment without scanning (or splitting) the whole string', () => { + const big = `AAAA${',AAAA'.repeat(5_000_000)}`; // ~25 MB: splitting it into 5M strings takes hundreds of ms + big.charAt(big.length - 1); // V8 builds the string lazily: flatten it first, so only the scan is timed + const started = performance.now(); + expect(hasOriginalPosition(big)).toBe(true); + expect(performance.now() - started).toBeLessThan(100); + // and the answer is the same when the usable segment is the last one + expect(hasOriginalPosition(`${';'.repeat(1000)}AAA,AAAA`)).toBe(true); + expect(hasOriginalPosition(`${'AAA;'.repeat(1000)}AAA`)).toBe(false); + }); + + it('index maps: at least one leaf must carry an original position', async () => { + const leaf = (mappings: string, line: number) => ({ + offset: { line, column: 0 }, + map: { version: 3, sources: ['a.ts'], sourcesContent: ['x'], names: [], mappings }, + }); + pair(JSON.stringify({ version: 3, debugId: ID_A, sections: [leaf('', 0), leaf(';;', 5)] })); + expect(find(await run(), 'map.invalid')?.message).toContain('original'); + pair(JSON.stringify({ version: 3, debugId: ID_A, sections: [leaf('', 0), leaf('AAAA', 5)] })); + expect(ids(await run())).not.toContain('map.invalid'); + pair(JSON.stringify({ version: 3, debugId: ID_A, sections: [leaf('AAAA', 0), leaf('', 5)] })); + expect(ids(await run())).not.toContain('map.invalid'); // any leaf counts, not just the last + }); + + it('one map reached through aliases in DIFFERENT directories has its relative sources checked against each', async () => { + put( + 'real/app.js.map', + mapJson({ debugId: ID_A, sourcesContent: undefined, sources: ['src/x.ts'] }), + ); + put('a/src/x.ts', 'x'); // only a/ has the source + for (const d of ['a', 'b']) { + put(`${d}/app.js`, `a\n//# sourceMappingURL=app.js.map${stamp(ID_A)}`); + symlinkSync(join(dist, 'real', 'app.js.map'), join(dist, d, 'app.js.map')); + } + const report = await run(); + const unresolved = report.findings.filter((f) => f.id === 'map.sources-unresolvable'); + // the real file itself (real/) has no src/x.ts either; a/ is the only base that does + expect(unresolved.map((f) => f.file)).toEqual(['b/app.js.map', 'real/app.js.map']); + expect(ids(report)).not.toContain('map.invalid'); + }); + + it("aliases in different directories report a shared map's CONTENT and STRUCTURE once", async () => { + const alias = (body: Record): void => { + put('real/app.js.map', mapJson({ debugId: ID_A, ...body })); + for (const d of ['a', 'b']) { + put(`${d}/app.js`, `a\n//# sourceMappingURL=app.js.map${stamp(ID_A)}`); + if (!existsSync(join(dist, d, 'app.js.map'))) { + symlinkSync(join(dist, 'real', 'app.js.map'), join(dist, d, 'app.js.map')); + } + } + }; + const count = (report: DoctorReport, id: string): number => + report.findings.filter((f) => f.id === id && !(f.file ?? '').startsWith('real/')).length; + alias({}); // content embedded + expect(count(await run(), 'map.sources-content')).toBe(1); + put('a/src/x.ts', 'x'); + put('b/src/x.ts', 'x'); + alias({ sourcesContent: undefined, sources: ['src/x.ts'] }); // not embedded, resolvable from both + expect(count(await run(), 'map.sources-content')).toBe(1); + alias({ version: 2 }); + expect(count(await run(), 'map.invalid')).toBe(1); + }); + + it('aliases in the SAME directory are still judged once', async () => { + put('real/m.map', mapJson({ debugId: ID_A, sourcesContent: undefined, sources: ['src/x.ts'] })); + for (const n of ['one', 'two']) { + put(`${n}.js`, `a\n//# sourceMappingURL=${n}.map${stamp(ID_A)}`); + symlinkSync(join(dist, 'real', 'm.map'), join(dist, `${n}.map`)); + } + const report = await run(); + const aliases = report.findings.filter( + (f) => f.id === 'map.sources-unresolvable' && !(f.file ?? '').startsWith('real/'), + ); + expect(aliases).toHaveLength(1); + }); +}); + +describe('boundedMemo', () => { + it('computes once per key, caches failures-as-values, and evicts the least recently used', async () => { + const calls: string[] = []; + const memo = boundedMemo(2, async (key: string) => { + calls.push(key); + return key.toUpperCase(); + }); + expect(await memo('a')).toBe('A'); + expect(await memo('a')).toBe('A'); + expect(await memo('b')).toBe('B'); + expect(await memo('a')).toBe('A'); // refreshes a: b is now the oldest + expect(await memo('c')).toBe('C'); // evicts b + expect(await memo('a')).toBe('A'); + expect(calls).toEqual(['a', 'b', 'c']); + expect(await memo('b')).toBe('B'); + expect(calls).toEqual(['a', 'b', 'c', 'b']); + }); + + it('shares an in-flight computation between concurrent callers', async () => { + let runs = 0; + const memo = boundedMemo(4, async (key: string) => { + runs++; + await new Promise((resolve) => setTimeout(resolve, 5)); + return key; + }); + await Promise.all([memo('x'), memo('x'), memo('x')]); + expect(runs).toBe(1); + }); +}); + +describe('walkDetailed on a path that does not exist', () => { + it('does not throw: nothing found, the root itself reported as unreadable', async () => { + const missing = join(root, 'no-such-dir'); + expect(await walk(missing)).toEqual([]); + expect((await walkDetailed(missing)).unreadable).toEqual(['.']); + }); +}); + +describe('symlinked directories are followed inside the output directory, reported when they leave it (round 14)', () => { + const unstampedChunk = (dir: string): void => { + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, 'chunk.js'), 'unstamped'); + }; + + it('a link to a directory INSIDE the output is walked: its scripts are audited (once), under the link name', async () => { + put('app.js', `a${stamp(ID_A)}`); + // the target lives where the plain walk never goes (node_modules), so only FOLLOWING the link can find it + unstampedChunk(join(dist, 'node_modules', 'real-legacy')); + symlinkSync(join(dist, 'node_modules', 'real-legacy'), join(dist, 'legacy')); + const report = await run(); + expect(ids(report)).toContain('stamp.missing-debug-id'); + expect(report.summary.bundles).toBe(2); // app.js and ONE chunk.js + expect(doctorExitCode(report, true)).toBeGreaterThanOrEqual(1); + }); + + it('a link to a directory OUTSIDE is output.dir-unreadable (exit 2), which --exclude can clear', async () => { + put('app.js', `a${stamp(ID_A)}`); + unstampedChunk(join(root, 'legacy-out')); + symlinkSync(join(root, 'legacy-out'), join(dist, 'legacy')); + const report = await run(); + expect(find(report, 'output.dir-unreadable')).toMatchObject({ + severity: 'error', + details: { directories: ['legacy'] }, + }); + expect(doctorExitCode(report, false)).toBe(2); + expect(ids(await run({ exclude: ['legacy/**'] }))).not.toContain('output.dir-unreadable'); + }); + + it('a link that loops back to an ancestor (or to the root) is not walked twice and is not an error', async () => { + put('app.js', `a${stamp(ID_A)}`); + put('sub/x.js', `a${stamp(ID_B)}`); + symlinkSync(dist, join(dist, 'sub', 'up')); + symlinkSync('.', join(dist, 'self')); + const report = await run(); + expect(report.summary.bundles).toBe(2); + expect(ids(report)).not.toContain('output.dir-unreadable'); + }); + + it('a dangling link, and a link to a FILE, are ignored; node_modules and .git links are never followed', async () => { + put('app.js', `a${stamp(ID_A)}`); + symlinkSync(join(root, 'nowhere'), join(dist, 'dangling')); + symlinkSync(join(dist, 'app.js'), join(dist, 'filelink')); + unstampedChunk(join(root, 'ext')); + symlinkSync(join(root, 'ext'), join(dist, 'node_modules')); + symlinkSync(join(root, 'ext'), join(dist, '.git')); + const report = await run(); + expect(ids(report)).not.toContain('output.dir-unreadable'); + expect(report.summary.bundles).toBe(1); + }); + + it('pages under a followed link are scanned for SRI pins; under an outside link they are reported', async () => { + const sri = (bytes: string): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + put('app.js', `console.log(1);${stamp(ID_A)}`); + const page = ``; + put('node_modules/x/p.html', page); // only reachable through the link + symlinkSync(join(dist, 'node_modules', 'x'), join(dist, 'pages')); + expect(ids(await run())).toContain('sri.mismatch'); + mkdirSync(join(root, 'ext-pages')); + writeFileSync(join(root, 'ext-pages', 'p.html'), page); + symlinkSync(join(root, 'ext-pages'), join(dist, 'external')); + expect(find(await run(), 'output.dir-unreadable')?.details).toEqual({ + directories: ['external'], + }); + }); + + it('a followed link inside a fenced project directory still obeys the fence by name', async () => { + put('package.json', '{"name":"p"}'); + put('app.js', `a${stamp(ID_A)}`); + unstampedChunk(join(dist, 'node_modules', 'real')); // not walked by anything else + symlinkSync(join(dist, 'node_modules', 'real'), join(dist, 'tests')); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run(); + expect(find(report, 'output.walk-fenced')?.details).toEqual({ directories: ['tests'] }); + } finally { + process.chdir(here); + } + }); +}); + +// paths relative to the output directory, always with `/` (a Windows host returns backslashes) +const relFiles = (files: string[]): string[] => + files.map((f) => relative(dist, f).split(sep).join('/')); + +describe('a REAL directory always wins over a link to it, whatever the names sort like (round 15)', () => { + for (const linkName of ['latest', 'zlatest']) { + it(`link "${linkName}" -> v2: files are walked, reported and excludable under the REAL path v2/`, async () => { + put('v2/chunk.js', 'unstamped'); + put('app.js', `a${stamp(ID_A)}`); + symlinkSync(join(dist, 'v2'), join(dist, linkName)); + const files = relFiles(await walk(dist)); + expect(files).toEqual(['app.js', 'v2/chunk.js']); + const report = await run(); + expect(report.summary.bundles).toBe(2); + // the exclusion written for the real path works; one written for the alias does not + expect(ids(await run({ exclude: ['v2/**'] }))).not.toContain('stamp.missing-debug-id'); + expect(ids(await run({ exclude: [`${linkName}/**`] }))).toContain('stamp.missing-debug-id'); + }); + } + + it('a link reached BEFORE a deeper real directory it points to still loses to it', async () => { + put('a/b/c/chunk.js', 'unstamped'); // real, deep + symlinkSync(join(dist, 'a', 'b', 'c'), join(dist, '0first')); // sorts before "a", the real parent + symlinkSync(join(dist, 'a', 'b', 'c'), join(dist, 'zlast')); // and one that sorts after + const files = relFiles(await walk(dist)); + expect(files).toEqual(['a/b/c/chunk.js']); + }); + + it('a link to a directory that is NOT reachable as a real directory (skipped by name) is still followed, once', async () => { + put('node_modules/real/chunk.js', 'unstamped'); + symlinkSync(join(dist, 'node_modules', 'real'), join(dist, 'a-link')); + symlinkSync(join(dist, 'node_modules', 'real'), join(dist, 'b-link')); + expect(relFiles(await walk(dist))).toEqual(['a-link/chunk.js']); + }); +}); + +describe('round 16 review findings', () => { + const unstampedChunk = (dir: string): void => { + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, 'chunk.js'), 'unstamped'); + }; + + it('a link NAMED like a script that points to a directory is followed as a directory', async () => { + put('app.js', `a${stamp(ID_A)}`); + unstampedChunk(join(dist, 'node_modules', 'assets')); + symlinkSync(join(dist, 'node_modules', 'assets'), join(dist, 'assets.js')); + symlinkSync(join(dist, 'node_modules', 'assets'), join(dist, 'assets.map')); + const report = await run(); + expect(ids(report)).toContain('stamp.missing-debug-id'); // the chunk inside was audited + expect(ids(report)).not.toContain('output.unreadable'); // and assets.js was not read as a bundle + expect(report.summary.bundles).toBe(2); + expect(relFiles(await walk(dist))).toEqual(['app.js', 'assets.js/chunk.js']); + }); + + it('a script link to a regular file is still a bundle; a dangling one is still reported', async () => { + put('real.js', `a${stamp(ID_A)}`); + symlinkSync(join(dist, 'real.js'), join(dist, 'alias.js')); + symlinkSync(join(root, 'nowhere.js'), join(dist, 'dangling.js')); + const report = await run(); + expect(find(report, 'output.unreadable')?.details).toEqual({ + files: ['dangling.js could not be resolved (ENOENT)'], + }); + }); + + it('fenced: a real directory beyond the depth cap does not stop a SHALLOWER link to it from being audited', async () => { + put('package.json', '{"name":"p"}'); + put('app.js', `a${stamp(ID_A)}`); + unstampedChunk(join(dist, 'a', 'b', 'c', 'd', 'e', 'f', 'g')); // depth 7: over the cap + symlinkSync(join(dist, 'a', 'b', 'c', 'd', 'e', 'f', 'g'), join(dist, 'shortcut')); + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run(); + expect(ids(report)).toContain('stamp.missing-debug-id'); + expect(relFiles(await walk(dist))).toEqual(['app.js', 'shortcut/chunk.js']); + // the link walked it: it is no longer "not searched" + expect(find(report, 'output.walk-fenced')).toBeUndefined(); + } finally { + process.chdir(here); + } + }); + + it.skipIf(process.getuid?.() === 0)( + 'a directory exclude is not satisfied by a pattern that only matches the probe directory names', + async () => { + put('a.js', `a${stamp(ID_A)}`); + put('vendor/app.js', 'x'); + chmodSync(join(dist, 'vendor'), 0o000); + try { + for (const pattern of ['vendor/zz-probe-1/**', 'vendor/zz-1/**', 'vendor/zz-2/zz-3/**']) { + const kept = find(await run({ exclude: [pattern] }), 'output.dir-unreadable')?.details; + expect(kept, pattern).toEqual({ directories: ['vendor'] }); + } + expect(ids(await run({ exclude: ['vendor/**'] }))).not.toContain('output.dir-unreadable'); + } finally { + chmodSync(join(dist, 'vendor'), 0o700); + } + }, + ); + + it('a mapping whose source index is outside the leaf sources has no original position', async () => { + const pairMap = (mappings: string, sources: string[] = ['a.ts']): void => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ debugId: ID_A, mappings, sources, sourcesContent: sources.map(() => 'x') }), + ); + }; + pairMap('ACAA'); // source index 1 of 1: out of range + expect(find(await run(), 'map.invalid')?.message).toContain('original'); + pairMap('AAAA'); + expect(ids(await run())).not.toContain('map.invalid'); + pairMap('ACAA', ['a.ts', 'b.ts']); // index 1 of 2 + expect(ids(await run())).not.toContain('map.invalid'); + pairMap('ADAA'); // index -1 + expect(ids(await run())).toContain('map.invalid'); + pairMap('AAAA,ACAA'); // the SECOND segment is out of range, the first is fine + expect(ids(await run())).not.toContain('map.invalid'); + }); + + it('hasOriginalPosition decodes the cumulative source index (deltas) across segments', () => { + expect(hasOriginalPosition('ACAA', 1)).toBe(false); + expect(hasOriginalPosition('ACAA', 2)).toBe(true); + expect(hasOriginalPosition('ACAA')).toBe(true); // no count given: any index + expect(hasOriginalPosition('ADAA', 5)).toBe(false); // -1 + expect(hasOriginalPosition('AAAA,ADAA,AEAA', 2)).toBe(true); // first segment already fine + expect(hasOriginalPosition('AEAA', 2)).toBe(false); // +2: index 2 of 2 + expect(hasOriginalPosition('AEAA', 3)).toBe(true); + expect(hasOriginalPosition('AEAA;AFAA', 2)).toBe(true); // +2 then -2: the second segment lands on index 0 + // an unusable segment (bad character) does not move the running source index + expect(hasOriginalPosition('AEA$,AAAA', 2)).toBe(true); + // only a segment with an original line and column moves the running source index (ECMA-426) + expect(hasOriginalPosition('AC,EDAA', 1)).toBe(false); // AC (2 values) must not commit +1 + expect(hasOriginalPosition('AEAA$,AAAA', 2)).toBe(true); // a segment with a bad character commits nothing + expect(hasOriginalPosition('ACA,EDAA', 1)).toBe(false); // nor three values + expect(hasOriginalPosition('ACAA,EDAA', 3)).toBe(true); // four values commit: 1 then 1+(-1)=0 + // continuation digits: 'gB' is 16, so the source delta below is 16 + expect(hasOriginalPosition('AgBAA', 17)).toBe(true); + expect(hasOriginalPosition('AgBAA', 16)).toBe(false); + }); + + it('map.too-large reports the limit that was ACTUALLY applied (never above the read ceiling)', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + truncateSync(put('a.js.map', ''), READ_CEILING + 1024 * 1024); + const report = await run({ maxMapBytes: 2 ** 40 }); + const finding = find(report, 'map.too-large'); + expect(finding?.details).toMatchObject({ limit: READ_CEILING }); + expect(finding?.message).toContain('most Node can hold'); + const low = find(await run({ maxMapBytes: 1 }), 'map.too-large'); + expect(low?.details).toMatchObject({ limit: 1 }); + }); + + it('a NaN read limit never disables the ceiling: the reader refuses it, the doctor uses its default', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put('a.js.map', mapJson({ debugId: ID_A })); + const file = join(dist, 'a.js.map'); + expect(await readRegularFile(file, Number.NaN)).toEqual({ + ok: false, + reason: 'has an invalid read limit', + }); + expect(await readRegularFile(file, 100, Number.NaN)).toEqual({ + ok: false, + reason: 'has an invalid read limit', + }); + const report = await run({ maxMapBytes: Number.NaN, maxBundleBytes: Number.NaN }); + expect(ids(report)).not.toContain('map.too-large'); + expect(ids(report)).not.toContain('map.unreadable'); + expect(report.summary).toMatchObject({ bundles: 1, maps: 1, errors: 0 }); + }); +}); + +describe('output.walk-fenced lists only what was really not walked (round 17)', () => { + const inDist = async (fn: () => Promise): Promise => { + const here = process.cwd(); + process.chdir(dist); + try { + return await fn(); + } finally { + process.chdir(here); + } + }; + const fencedWalk = (): Promise<{ files: string[]; skipped: string[] }> => walkDetailed(dist); + + it('an alias (beyond the depth cap) of a directory that WAS walked is not listed', async () => { + put('package.json', '{"name":"p"}'); + put('v2/app.js', `a${stamp(ID_A)}`); + mkdirSync(join(dist, 'a/b/c/d/e/f'), { recursive: true }); + symlinkSync(join(dist, 'v2'), join(dist, 'a/b/c/d/e/f/latest')); + const walked = await inDist(fencedWalk); + expect(relFiles(walked.files)).toEqual(['v2/app.js']); + expect(walked.skipped).toEqual([]); + }); + + it('a deep real directory that a shallower link then walks is not listed either', async () => { + put('package.json', '{"name":"p"}'); + put('a/b/c/d/e/f/g/app.js', `a${stamp(ID_A)}`); + symlinkSync(join(dist, 'a/b/c/d/e/f/g'), join(dist, 'x')); + const walked = await inDist(fencedWalk); + expect(relFiles(walked.files)).toEqual(['x/app.js']); + expect(walked.skipped).toEqual([]); + }); + + it('a directory nothing walked is still listed (depth cap and fenced names)', async () => { + put('package.json', '{"name":"p"}'); + put('a/b/c/d/e/f/g/app.js', 'x'); + put('tests/t.js', 'x'); + const walked = await inDist(fencedWalk); + expect(walked.skipped).toEqual(['a/b/c/d/e/f/g', 'tests']); + }); + + it('a fenced-name directory that a link DOES walk is not listed', async () => { + put('package.json', '{"name":"p"}'); + put('tests/t.js', 'x'); + symlinkSync(join(dist, 'tests'), join(dist, 'viewer')); + const walked = await inDist(fencedWalk); + expect(relFiles(walked.files)).toEqual(['viewer/t.js']); + expect(walked.skipped).toEqual([]); + }); +}); + +describe('a facade or empty chunk has an empty map and that is healthy (round 18)', () => { + const rollupEmpty = (extra: Record = {}): string => + JSON.stringify({ + version: 3, + file: 'index.js', + sources: [], + sourcesContent: [], + names: [], + mappings: '', + ...extra, + }); + const pairOne = (map: string): void => { + put('index.js', `export{a}from'./main.js';\n//# sourceMappingURL=index.js.map${stamp(ID_A)}`); + put('index.js.map', map); + }; + + it('the Rollup facade map (sources [], mappings "") is an info, not an error, and the run passes --strict', async () => { + pairOne(rollupEmpty({ debugId: ID_A })); + const report = await run(); + expect(find(report, 'map.no-sources')).toMatchObject({ + severity: 'info', + file: 'index.js.map', + }); + expect(find(report, 'map.no-sources')?.message).toContain('nothing to map'); + expect(report.summary).toMatchObject({ errors: 0, warnings: 0 }); + expect(doctorExitCode(report, true)).toBe(0); + }); + + it('a chunk with REAL code and an empty map is still an error (a placeholder map, not a facade)', async () => { + put( + 'main.js', + `export function boom(){throw new Error('x')}\nconsole.log(1);\n//# sourceMappingURL=main.js.map${stamp(ID_A)}`, + ); + put('main.js.map', rollupEmpty({ debugId: ID_A, mappings: ';;;;;;' })); + const report = await run(); + expect(find(report, 'map.no-sources')?.severity).toBe('error'); + expect(doctorExitCode(report, false)).toBe(2); + }); + + it('isFacadeCode: only imports, re-exports and comments (and the Bugsee registration) are a facade', () => { + for (const facade of [ + '', + ' \n// nothing here\n/* or here */', + "export{a}from'./main.js';", + 'export { a, b as c } from "./main.js";\n', + "export * from './x.js'; export * as ns from './y.js'", + "import './side-effect.js';", + "import{a}from'./main.js';export{a};", + "import a, { b } from './m.js'\nimport * as c from './c.js'\nexport { a, b, c }", + `export{a}from'./main.js';\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`, + // Rollup's CommonJS output + "'use strict';\n\nvar main = require('./main.js');\n\nexports.a = main.a;\nexports.b = main.b;\n", + "'use strict';\nObject.defineProperty(exports, '__esModule', { value: true });\nvar main = require('./main.js');\nexports.a = main.a;", + '"use strict";require("./side-effect.cjs");', + "'use strict';\nvar m = require('./m.js');\nObject.defineProperty(exports, 'a', {\n enumerable: true,\n get: function () { return m.a; }\n});", + "module.exports = require('./main.cjs');", + "const main = require('./main.js');\nexports.default = main;", + ]) { + expect(isFacadeCode(facade), JSON.stringify(facade)).toBe(true); + } + for (const code of [ + 'export function f(){}', + 'export const a = 1;', + "export { a } from './m.js'; console.log(1)", + "import { a } from './m.js'; a();", + 'var x = 1; export { x }', + 'export default function(){}', + "export { a } from './m.js' + 'x'", + 'console.log(1)', + // CommonJS that is real code + "'use strict';\nvar m = require('./m.js');\nexports.f = function(){ return 1 };", + "'use strict';\nrequire('./m.js')();", + "var m = require('./m.js') + 1;", + 'exports.a = main.a(); ', + "Object.defineProperty(exports, 'a', { get: function () { sideEffect(); return 1; } });", + ]) { + expect(isFacadeCode(code), JSON.stringify(code)).toBe(false); + } + }); + + it("isFacadeCode: Rollup's CommonJS export-star loop and interop helpers are facades", () => { + const exportStar = `'use strict'; + +var lodash = require('lodash'); +var util = require('./util.js'); + +exports.u = util.u; +Object.keys(lodash).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return lodash[k]; } + }); +}); +`; + const interop = `'use strict'; + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +function _interopDefault(e) { return e && e.__esModule ? e : { default: e }; } + +var lodash = require('lodash'); +var lodash__namespace = /*#__PURE__*/_interopNamespaceDefault(lodash); +var x = require('x'); + +exports.lodash = lodash__namespace; +exports.x = _interopDefault(x); +`; + expect(isFacadeCode(exportStar)).toBe(true); + expect(isFacadeCode(interop)).toBe(true); + expect(isFacadeCode(`${exportStar}${stamp(ID_A)}`)).toBe(true); + // the same blocks with something that DOES something are not + expect( + isFacadeCode(exportStar.replace('return lodash[k];', 'track(k); return lodash[k];')), + ).toBe(false); + expect(isFacadeCode(exportStar.replace('Object.keys(lodash)', 'doIt(lodash)'))).toBe(false); + expect(isFacadeCode(interop.replace('Object.freeze(n)', 'sideEffect(n)'))).toBe(false); + expect(isFacadeCode(interop.replace('function _interopDefault', 'function doThing'))).toBe( + false, + ); + expect(isFacadeCode(`${exportStar}\nconsole.log('hi');`)).toBe(false); + expect(isFacadeCode('var x = 1;\nexports.x = x;')).toBe(false); // a value of its own + }); + + it("isFacadeCode: Rollup's es2015 output (arrow getters, for-in, const arrow helper) is a facade", () => { + const es2015 = `'use strict'; + +const _interopNamespaceDefault = (e) => { + const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } }); + if (e) { + for (const k in e) { + if (k !== 'default') { + const d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: () => e[k] + }); + } + } + } + n.default = e; + return Object.freeze(n); +}; +const _interopDefault = e => e && e.__esModule ? e : { default: e }; + +const lodash = require('lodash'); +const dep3 = require('dep3'); +const util = require('./util.js'); +const lodash__namespace = /*#__PURE__*/_interopNamespaceDefault(lodash); + +exports.u = util.u; +Object.keys(lodash).forEach((k) => { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: () => lodash[k] + }); +}); +Object.defineProperty(exports, 'named', { + enumerable: true, + get: () => dep3.named +}); +exports.ns = lodash__namespace; +exports.d = _interopDefault(dep3); +`; + expect(isFacadeCode(es2015)).toBe(true); + expect( + isFacadeCode("Object.defineProperty(exports, 'a', { enumerable: true, get: () => x.a });"), + ).toBe(true); + expect( + isFacadeCode('const _interopDefault = e => e && e.__esModule ? e : { default: e };'), + ).toBe(true); + expect(isFacadeCode('const _interopDefault = function (e) { return e; };')).toBe(true); + // look-alikes that DO something + expect(isFacadeCode(es2015.replace('get: () => dep3.named', 'get: () => dep3.named()'))).toBe( + false, + ); + expect(isFacadeCode(es2015.replace('get: () => lodash[k]', 'get: () => track(k)'))).toBe(false); + expect( + isFacadeCode(es2015.replace('for (const k in e) {', 'for (const k in track(e)) {')), + ).toBe(false); + expect( + isFacadeCode(es2015.replace("if (k !== 'default') {", "if (k !== 'default') { track(k);")), + ).toBe(false); + expect( + isFacadeCode(es2015.replace('const _interopDefault = e =>', 'const doThing = e =>')), + ).toBe(false); + expect(isFacadeCode('const _interopDefault = e => track(e);')).toBe(false); + expect(isFacadeCode('const _interopDefault = 1;')).toBe(false); + expect(isFacadeCode('const doThing = e => e;')).toBe(false); + expect(isFacadeCode('exports.a = () => 1;')).toBe(false); // an arrow that is not a getter + expect( + isFacadeCode("Object.defineProperty(exports, 'a', { enumerable: true, value: () => x });"), + ).toBe(false); + expect(isFacadeCode('for (const k in x) { exports[k] = x[k]; }')).toBe(false); // a loop at top level is code + expect(isFacadeCode('function _interopX(e) { for (var k in e) { k = 1; } return e; }')).toBe( + true, + ); + expect( + isFacadeCode( + 'function _interopX(e) { for (k in e) { Object.defineProperty(e, k, {}); } return e; }', + ), + ).toBe(true); + expect(isFacadeCode('function _interopX(e) { for (const [a, b] in e) { } return e; }')).toBe( + false, + ); + expect( + isFacadeCode( + 'function _interopX(e) { for (const k in e) { } for (const k of e) { } return e; }', + ), + ).toBe(false); // for-of + expect(isFacadeCode('function _interopX(e) { for (const k, j in e) { } return e; }')).toBe( + false, + ); // not valid, parse error + }); + + it('isFacadeCode: shapes that look like a re-export but are not', () => { + const loop = (inner: string, extra = ''): string => + `Object.keys(x).forEach(function (k) { ${inner} }${extra});`; + const define = + 'Object.defineProperty(exports, k, { enumerable: true, get: function () { return x[k]; } });'; + expect(isFacadeCode(loop(`if (k !== 'default') ${define}`))).toBe(true); // the real shape + expect(isFacadeCode("Object['keys'](x);")).toBe(false); // computed callee + expect(isFacadeCode('Object[keys](x);')).toBe(false); + expect(isFacadeCode('var a = x.y;')).toBe(false); // a reference is not a call + expect(isFacadeCode('var a;')).toBe(false); + expect(isFacadeCode(loop(define, ', y'))).toBe(false); // an extra forEach argument + expect(isFacadeCode('require(x);')).toBe(false); // not a literal specifier + expect(isFacadeCode("require('a', 'b');")).toBe(false); + expect(isFacadeCode("var m = require('a', 'b');")).toBe(false); + expect( + isFacadeCode( + "Object.defineProperty(exports, 'a', { enumerable: true, value: function () { return x; } });", + ), + ).toBe(false); + expect(isFacadeCode(loop(`if (k) ${define} else { track(k); }`))).toBe(false); // an impure else + expect(isFacadeCode(loop(`if (k) ${define} else ${define}`))).toBe(true); + expect(isFacadeCode('exports.n += 1;')).toBe(false); // not a plain assignment + expect( + isFacadeCode( + 'Object.keys(x).forEach(function ([k]) { Object.defineProperty(exports, k, {}); });', + ), + ).toBe(false); + expect( + isFacadeCode( + 'Object.keys(x).forEach(function (k, i) { Object.defineProperty(exports, k, {}); });', + ), + ).toBe(true); + expect( + isFacadeCode('Object.keys(x).forEach(k => Object.defineProperty(exports, k, {}));'), + ).toBe(true); // an arrow + expect(isFacadeCode('Object.keys(x).forEach(k => track(k));')).toBe(false); + expect(isFacadeCode('Object.keys(x).forEach(function (k) { return; });')).toBe(true); + expect(isFacadeCode('Object.keys(x).forEach(function (k) { return track(k); });')).toBe(false); + expect(isFacadeCode('Object.keys(x).forEach(function (k) { while (k) {} });')).toBe(false); // a loop is code + expect(isFacadeCode("var a = require('x'), b = _interopDefault(a);")).toBe(true); + expect(isFacadeCode("var a = 1, b = require('x');")).toBe(false); + expect(isFacadeCode("var [a] = require('x');")).toBe(false); // destructuring is not a plain binding + expect(isFacadeCode("var a = k ? require('x') : require('y');")).toBe(false); // not a plain call + expect(isFacadeCode('exports.a = k ? x.a : y.a;')).toBe(true); + expect(isFacadeCode("exports.a = !x && typeof y === 'undefined' ? x.a : void 0;")).toBe(true); + expect(isFacadeCode('exports.a = x[k];')).toBe(true); + expect(isFacadeCode('exports.a = x[track()];')).toBe(false); + expect(isFacadeCode('exports.a = {};')).toBe(true); + expect(isFacadeCode("exports.a = { b: x.b, 'c': 1 };")).toBe(true); + expect(isFacadeCode('exports.a = { ...x };')).toBe(false); // a spread is not a property + expect(isFacadeCode('exports.a = x.a++ ;')).toBe(false); + expect(isFacadeCode('exports.a = `t`;')).toBe(false); + expect(isFacadeCode('exports.a = Object.keys(x);')).toBe(true); + expect(isFacadeCode('export default 1;')).toBe(false); + expect(isFacadeCode('class A {}')).toBe(false); + }); + + it('isFacadeCode: comments are stripped outside quoted module specifiers only', () => { + for (const facade of [ + 'export { a } from "https://cdn.example/a.js";', + "import 'http://x.test/y.js' // a trailing comment", + "/* don't */ export{a}from'./m.js'; // it's fine", + "export{a}from'./m.js'; /* block with // inside */\nexport{b}from'./n.js'", + ]) { + expect(isFacadeCode(facade), facade).toBe(true); + } + expect(isFacadeCode("var u = 'http://x'; export{a}from'./m.js'")).toBe(false); + expect(isFacadeCode("export{a}from'./m.js' /* unterminated")).toBe(false); // unreadable is not a facade + expect(isFacadeCode("export{a}from'./m.js; export function f(){}")).toBe(false); // an open string swallows the rest + }); + + it('isFacadeCode: a registration-looking line is the stub only when the debugId comment follows it', () => { + expect(isFacadeCode('var d=globalThis._bugseeDebugIds;\n// just a note\n')).toBe(false); + expect(isFacadeCode('var d=globalThis._bugseeDebugIds;\n//# sourceMappingURL=a.map\n')).toBe( + false, + ); + }); + + it('isFacadeCode: only the TRAILING registration stub is ignored, not the marker inside real code', () => { + // a bundle that carries the Bugsee SDK has the marker in its own (minified, one-line) code + const sdk = 'var d=globalThis._bugseeDebugIds;export function f(){return d}'; + expect(isFacadeCode(`${sdk}${stamp(ID_A)}`)).toBe(false); + expect(isFacadeCode(`${sdk}\n`)).toBe(false); + // a facade followed by the stub is fine, whatever comments and blank lines come after it + expect( + isFacadeCode(`export{a}from'./m.js';${stamp(ID_A)}\n\n//# sourceMappingURL=x.map\n`), + ).toBe(true); + // a marker in the MIDDLE of a facade-looking file does not make the code after it vanish + expect(isFacadeCode(`var x=globalThis._bugseeDebugIds;\nexport{a}from'./m.js';`)).toBe(false); + }); + + it('only separators in mappings (";;;" or ",;") is still empty', async () => { + for (const mappings of [';;;', ',;,', ';']) { + pairOne(rollupEmpty({ debugId: ID_A, mappings })); + expect(find(await run(), 'map.no-sources')?.severity, mappings).toBe('info'); + } + }); + + it('generated segments but no sources stays an error (a stripped map)', async () => { + pairOne(rollupEmpty({ debugId: ID_A, mappings: 'AAAA' })); + expect(find(await run(), 'map.no-sources')?.severity).toBe('error'); + pairOne(rollupEmpty({ debugId: ID_A, mappings: ';;A' })); + expect(find(await run(), 'map.no-sources')?.severity).toBe('error'); + }); + + it('index maps: empty when no section has segments; an error when any section does or the chain is too deep to tell', async () => { + const leaf = (mappings: string, line: number) => ({ + offset: { line, column: 0 }, + map: { version: 3, sources: [], names: [], mappings }, + }); + pairOne(JSON.stringify({ version: 3, debugId: ID_A, sections: [leaf('', 0), leaf(';', 3)] })); + expect(find(await run(), 'map.no-sources')?.severity).toBe('info'); + pairOne( + JSON.stringify({ version: 3, debugId: ID_A, sections: [leaf('', 0), leaf('AAAA', 3)] }), + ); + expect(find(await run(), 'map.no-sources')?.severity).toBe('error'); + let deep: Record = { version: 3, sources: [], mappings: '' }; + for (let i = 0; i < 40; i++) { + deep = { version: 3, sections: [{ offset: { line: 0, column: 0 }, map: deep }] }; + } + pairOne(JSON.stringify({ ...deep, debugId: ID_A })); + expect(find(await run(), 'map.no-sources')?.severity).toBe('error'); // beyond the cap: cannot tell, so not waved through + }); + + it('an empty map that no bundle claims (there is no code to check) is a note', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', mapJson({ debugId: ID_A })); + put('orphan.css.map', rollupEmpty()); + expect(find(await run(), 'map.no-sources')).toMatchObject({ + severity: 'info', + file: 'orphan.css.map', + }); + }); + + it('an empty map reached through aliases in different directories is noted once', async () => { + put('real/app.js.map', rollupEmpty({ debugId: ID_A })); + for (const d of ['a', 'b']) { + put(`${d}/app.js`, `a\n//# sourceMappingURL=app.js.map${stamp(ID_A)}`); + symlinkSync(join(dist, 'real', 'app.js.map'), join(dist, d, 'app.js.map')); + } + const noted = (await run()).findings.filter( + (f) => f.id === 'map.no-sources' && !(f.file ?? '').startsWith('real/'), + ); + expect(noted).toHaveLength(1); + }); + + it('a shared empty map is an error if ANY claimant has real code, whichever claims it first', async () => { + const facade = `export{a}from'./m.js';${stamp(ID_A)}`; + const real = `export function f(){return 1}\n${stamp(ID_A)}`; + for (const [first, second] of [ + [facade, real], + [real, facade], + ] as const) { + put('a.js', first.replace(stamp(ID_A), `\n//# sourceMappingURL=shared.map${stamp(ID_A)}`)); + put('b.js', second.replace(stamp(ID_A), `\n//# sourceMappingURL=shared.map${stamp(ID_A)}`)); + put('shared.map', rollupEmpty({ debugId: ID_A })); + const noted = (await run()).findings.filter((f) => f.id === 'map.no-sources'); + expect(noted.map((f) => f.severity)).toEqual(['error']); + } + put('b.js', facade.replace(stamp(ID_A), `\n//# sourceMappingURL=shared.map${stamp(ID_A)}`)); + put('a.js', facade.replace(stamp(ID_A), `\n//# sourceMappingURL=shared.map${stamp(ID_A)}`)); + expect( + (await run()).findings.filter((f) => f.id === 'map.no-sources').map((f) => f.severity), + ).toEqual(['info']); + }); + + it('the same in different directories (aliases of one real map)', async () => { + put('real/app.js.map', rollupEmpty({ debugId: ID_A })); + const code = (c: string): string => `${c}\n//# sourceMappingURL=app.js.map${stamp(ID_A)}`; + put('a/app.js', code("export{a}from'./m.js';")); + put('b/app.js', code('export function f(){return 1}')); + for (const d of ['a', 'b']) { + symlinkSync(join(dist, 'real', 'app.js.map'), join(dist, d, 'app.js.map')); + } + const noted = (await run()).findings.filter( + (f) => f.id === 'map.no-sources' && !(f.file ?? '').startsWith('real/'), + ); + expect(noted.map((f) => f.severity)).toEqual(['error']); + }); + + it('a shared empty map is noted once', async () => { + put('a.js', `a\n//# sourceMappingURL=shared.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=shared.map${stamp(ID_A)}`); + put('shared.map', rollupEmpty({ debugId: ID_A })); + const report = await run(); + expect(report.findings.filter((f) => f.id === 'map.no-sources')).toHaveLength(1); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.real-build.test.ts b/packages/bundler-plugin-core/src/doctor.real-build.test.ts new file mode 100644 index 00000000..8dcec483 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.real-build.test.ts @@ -0,0 +1,458 @@ +// The doctor against REAL build output: Vite 8 (Rolldown), Vite 7 (Rollup), Rollup and Rspack (webpack's +// processAssets stamping path) stamped by the real plugin + the real bugsee-cli, an unstamped build, an +// inline-map build, and SRI builds (stamped-first = fine; stamped-after-hash = the browser-blocking mismatch). +// Webpack itself is not a dependency of this package; Rspack exercises the same in-build stamp code. +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { rspack } from '@rspack/core'; +import { rollup } from 'rollup'; +import { type Plugin as VitePlugin, build as viteBuild } from 'vite'; +import { build as vite7Build } from 'vite7'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { type DoctorReport, diagnoseBuildOutput, doctorExitCode } from './doctor'; +import { isFacadeCode } from './facade'; +import { bugseeRollupPlugin, bugseeRspackPlugin, bugseeUnplugin } from './plugin'; +import { resolveBugseeCli, runBugseeCli } from './run-cli'; + +let server: Server; +let endpoint: string; +let root: string; + +const cli = resolveBugseeCli(); +const probe = cli.endsWith('.js') + ? spawnSync(process.execPath, [cli, '--version'], { encoding: 'utf8' }) + : spawnSync(cli, ['--version'], { encoding: 'utf8' }); +const cliAvailable = probe.status === 0; +const cliRequired = process.env.CI !== undefined || process.env.BUGSEE_REQUIRE_CLI !== undefined; +const describeReal = cliAvailable || cliRequired ? describe : describe.skip; + +beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-real-')); + server = createServer((req, res) => { + req.resume(); + req.on('end', () => { + res.setHeader('content-type', 'application/json'); + res.end( + JSON.stringify({ ok: false, error: { type: 'DuplicateSymbolsFoundError', code: 16004 } }), + ); + }); + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}`; +}); +afterAll(async () => { + await new Promise((r) => server.close(() => r())); + rmSync(root, { recursive: true, force: true }); +}); + +const pluginOptions = (extra: object = {}) => ({ + appToken: 'doctor-token', + endpoint, + vcs: false, + registerBuild: false as const, + failOnError: true, + deleteMaps: false, // keep the maps on disk so the doctor has pairs to check + ...extra, +}); + +function makeApp(name: string, options: { lazy?: boolean } = {}): { dir: string; out: string } { + const dir = join(realpathSync(root), name); + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, 'index.html'), + '\n', + ); + writeFileSync(join(dir, 'greet.js'), "export const greet = (n) => 'hello ' + n;\n"); + writeFileSync(join(dir, 'lazy.js'), "export default 'lazy chunk ' + Date.now();\n"); + writeFileSync( + join(dir, 'index.js'), + `import { greet } from './greet.js';\nconsole.log(greet('world'));\n${ + options.lazy === false ? '' : "import('./lazy.js').then((m) => console.log(m.default));\n" + }`, + ); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name, version: '1.2.3' })); + return { dir, out: join(dir, 'dist') }; +} + +const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + +const viteConfig = (app: { dir: string; out: string }, plugins: unknown[], build: object = {}) => + ({ + root: app.dir, + configFile: false, + logLevel: 'silent', + base: './', + plugins, + build: { outDir: app.out, emptyOutDir: true, minify: false, sourcemap: 'hidden', ...build }, + }) as never; + +/** Pins every emitted chunk in the page, hashing in generateBundle (post), like an SRI plugin does. */ +const viteSri = (): VitePlugin => ({ + name: 'doctor-sri', + enforce: 'post', + generateBundle: { + order: 'post', + handler(_options, bundle) { + const page = bundle['index.html']; + if (page?.type === 'asset') { + page.source = String(page.source).replace( + /]*?src="\.?\/?([^"]+\.js)"[^>]*>/g, + (tag, file: string) => { + const entry = bundle[file]; + return entry?.type === 'chunk' + ? tag.replace(/>$/, ` integrity="${sri(entry.code)}">`) + : tag; + }, + ); + } + }, + }, +}); + +const doctor = (out: string, extra: { deployed?: boolean } = {}): Promise => + diagnoseBuildOutput(out, { + ...extra, + env: { BUGSEE_APP_TOKEN: 't', BUGSEE_APP_BUILD: 'b' }, + projectRoot: dirname(out), + }); +const idsOf = (report: DoctorReport, severity?: string): string[] => + report.findings.filter((f) => severity === undefined || f.severity === severity).map((f) => f.id); + +/** The only non-error findings a correctly stamped, maps-kept, hidden-map build is allowed to have. */ +function expectHealthyStamped(report: DoctorReport): void { + expect(idsOf(report, 'error')).toEqual([]); + expect(report.summary.bundles).toBeGreaterThanOrEqual(1); + expect(report.summary.maps).toBe(report.summary.bundles); + expect(idsOf(report).sort()).toEqual( + expect.arrayContaining(['map.hidden', 'map.public-leftover', 'map.sources-content']), + ); + // Straight after a plugin run nothing warns (so `--strict` passes); the leftover maps are a note... + expect(idsOf(report, 'warning')).toEqual([]); + expect(idsOf(report, 'info')).toContain('map.public-leftover'); + expect(report.passed).toEqual( + expect.arrayContaining([ + 'stamp.missing-debug-id', + 'stamp.map-id-mismatch', + 'stamp.missing-registration', + ]), + ); +} + +describeReal('doctor on real, stamped build output', () => { + it('Vite 8 (Rolldown) with hidden maps is healthy', async () => { + const app = makeApp('vite8'); + await viteBuild(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Vite 7 (Rollup) with hidden maps is healthy', async () => { + const app = makeApp('vite7'); + await vite7Build(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Rollup is healthy', async () => { + const app = makeApp('rollup'); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await bundle.write({ dir: app.out, sourcemap: 'hidden' }); + await bundle.close(); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Rollup with maps moved by sourcemapFileNames has no errors (and reports the wrong pointer Rollup writes)', async () => { + const app = makeApp('rollup-moved'); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await bundle.write({ + dir: app.out, + sourcemap: true, + sourcemapFileNames: 'maps/[name].map', + }); + await bundle.close(); + const report = await doctor(app.out, { deployed: true }); + expect(idsOf(report, 'error')).toEqual([]); + expect(report.summary.maps).toBe(report.summary.bundles); + expect(report.findings.some((f) => f.file?.startsWith('maps/'))).toBe(true); + // Rollup writes the pointer as `index.map` (relative to the file NAME, ignoring the `maps/` directory), so the + // browser's request 404s: the doctor says so, truthfully. The moved maps are still read and validated. + expect(idsOf(report, 'warning').sort()).toEqual([ + 'map.pointer-dangling', + 'map.public-leftover', + ]); + }); + + it('Rspack (webpack in-build stamping path) with hidden maps is healthy', async () => { + const app = makeApp('rspack'); + await new Promise((resolve, reject) => { + const compiler = rspack({ + context: app.dir, + mode: 'production', + entry: join(app.dir, 'index.js'), + devtool: 'hidden-source-map', + output: { path: app.out }, + plugins: [bugseeRspackPlugin(pluginOptions())], + }); + compiler.run((err) => compiler.close(() => (err ? reject(err) : resolve()))); + }); + expectHealthyStamped(await doctor(app.out)); + }); + + it('Vite with visible maps and the default deleteMaps leaves a dangling pointer (a note, and --strict passes)', async () => { + const app = makeApp('vite8-dangling'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ deleteMaps: true })) as VitePlugin], { + sourcemap: true, + }), + ); + const report = await doctor(app.out); + expect(report.summary.maps).toBe(0); + expect(idsOf(report, 'error')).toEqual([]); + // maps removed on purpose and every bundle stamped: a note, so --strict passes right after the plugin + expect(idsOf(report, 'warning')).toEqual([]); + expect(idsOf(report, 'info')).toContain('map.pointer-dangling'); + expect(doctorExitCode(report, true)).toBe(0); + }); +}); + +describeReal('doctor on Vite worker builds (stamped by the upload catch-up)', () => { + const workerApp = (name: string, form: 'url' | 'query'): { dir: string; out: string } => { + const app = makeApp(name); + writeFileSync(join(app.dir, 'w.js'), "postMessage('worker-ok');\n"); + writeFileSync( + join(app.dir, 'index.js'), + form === 'url' + ? "const w = new Worker(new URL('./w.js', import.meta.url), { type: 'module' });\nw.onmessage = (e) => console.log(e.data);\n" + : "import W from './w.js?worker';\nconst w = new W();\nw.onmessage = (e) => console.log(e.data);\n", + ); + return app; + }; + for (const [label, build] of [ + ['Vite 8 (Rolldown)', viteBuild], + ['Vite 7 (Rollup)', vite7Build], + ] as const) { + for (const form of ['url', 'query'] as const) { + it(`${label}, ${form} worker: main and worker bundles are stamped and their maps carry the same id`, async () => { + const app = workerApp(`doc-worker-${label.replace(/\W+/g, '')}-${form}`, form); + await build(viteConfig(app, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin])); + const report = await doctor(app.out); + expect(report.summary.bundles).toBeGreaterThanOrEqual(2); // main + worker + expect(report.summary.maps).toBe(report.summary.bundles); + expect(idsOf(report, 'error')).toEqual([]); + expect(idsOf(report, 'warning')).toEqual([]); + expect(report.passed).toEqual( + expect.arrayContaining(['stamp.map-id-mismatch', 'stamp.map-no-debug-id', 'stamp.mixed']), + ); + }); + } + } +}); + +describeReal('doctor on multi-output and nested-directory Rollup builds', () => { + it('six outputs into one directory (maps kept) are all stamped, paired and clean', async () => { + const app = makeApp('doc-many-outputs', { lazy: false }); + const names = ['a', 'b', 'c', 'd', 'e', 'f']; + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await Promise.all( + names.map((n) => + bundle.write({ + file: join(app.out, `${n}.js`), + format: 'iife', + name: `app_${n}`, + sourcemap: 'hidden', + }), + ), + ); + await bundle.close(); + const report = await doctor(app.out); + expect(report.summary).toMatchObject({ bundles: 6, maps: 6, errors: 0, warnings: 0 }); + expect(report.passed).toEqual( + expect.arrayContaining(['stamp.map-id-mismatch', 'stamp.duplicate-debug-id']), + ); + }); + + it('an output nested inside another: checking the parent walks both and finds no problem', async () => { + const app = makeApp('doc-nested-outputs', { lazy: false }); + const bundle = await rollup({ + input: join(app.dir, 'index.js'), + plugins: [bugseeRollupPlugin(pluginOptions())], + }); + await Promise.all([ + bundle.write({ + dir: app.out, + entryFileNames: 'p.js', + format: 'iife', + name: 'p', + sourcemap: 'hidden', + }), + bundle.write({ + dir: join(app.out, 'b'), + entryFileNames: 'c.js', + format: 'iife', + name: 'c', + sourcemap: 'hidden', + }), + ]); + await bundle.close(); + const parent = await doctor(app.out); + expect(parent.summary).toMatchObject({ bundles: 2, maps: 2, errors: 0, warnings: 0 }); + const nested = await doctor(join(app.out, 'b')); + expect(nested.summary).toMatchObject({ bundles: 1, maps: 1, errors: 0, warnings: 0 }); + }); +}); + +describeReal('doctor on real, problematic build output', () => { + it('an unstamped Vite build (plugin disabled) is an error per bundle', async () => { + const app = makeApp('vite8-unstamped'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin], { + sourcemap: true, + }), + ); + const report = await doctor(app.out); + const errors = report.findings.filter((f) => f.severity === 'error'); + expect(errors.length).toBeGreaterThan(0); + expect(errors.every((f) => f.id === 'stamp.missing-debug-id')).toBe(true); + expect(report.summary.errors).toBe(report.summary.bundles); + }); + + it('an inline-map Vite build is reported as map.inline', async () => { + const app = makeApp('vite8-inline'); + await viteBuild( + viteConfig(app, [bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin], { + sourcemap: 'inline', + }), + ); + const report = await doctor(app.out); + expect(idsOf(report, 'error')).toContain('map.inline'); + expect(report.summary.maps).toBe(0); + }); + + it('SRI: an unstamped build pinning hashes is flagged as a hazard; stamped-first is clean; stamped-after-hash is a mismatch', async () => { + const plain = makeApp('vite8-sri-plain'); + await viteBuild( + viteConfig(plain, [ + bugseeUnplugin.vite(pluginOptions({ disabled: true })) as VitePlugin, + viteSri(), + ]), + ); + const hazard = await doctor(plain.out); + expect(idsOf(hazard)).toContain('sri.unstamped-hazard'); + expect(idsOf(hazard)).not.toContain('sri.mismatch'); + + const first = makeApp('vite8-sri-first'); + await viteBuild( + viteConfig(first, [bugseeUnplugin.vite(pluginOptions()) as VitePlugin, viteSri()]), + ); + const clean = await doctor(first.out); + expect(idsOf(clean)).not.toContain('sri.unstamped-hazard'); + expect(idsOf(clean)).not.toContain('sri.mismatch'); + expect(idsOf(clean, 'error')).toEqual([]); + expect(clean.passed).toContain('sri.mismatch'); + + // The post-emit stamp the in-build design exists to avoid: the page was hashed before the stamp. + const result = await runBugseeCli(['sourcemaps', 'inject', plain.out, '--allow-sri'], { + cwd: plain.dir, + }); + expect(result.code).toBe(0); + const broken = await doctor(plain.out); + expect(idsOf(broken, 'error')).toContain('sri.mismatch'); + expect(idsOf(broken)).not.toContain('sri.unstamped-hazard'); + expect(readdirSync(plain.out).length).toBeGreaterThan(0); + expect(readFileSync(join(plain.out, 'index.html'), 'utf8')).toContain('integrity='); + }); +}); + +// A barrel that re-exports dependencies is a FACADE chunk: Rollup writes `sources: []` and an empty `mappings` for it, +// and for CommonJS it writes the `export *` loop and the interop helpers in ES5 or (with generatedCode: 'es2015', which +// Vite 7 library mode uses) arrow form. The doctor must read every one of them as a facade, from the real emitted text. +describe('facade chunks in real Rollup / Vite output', () => { + const sources = (dir: string): void => { + mkdirSync(join(dir, 'src'), { recursive: true }); + writeFileSync( + join(dir, 'src', 'index.js'), + "export * from 'ext-a';\nexport * as ns from 'ext-b';\nexport { named } from 'ext-c';\nexport { default as dflt } from 'ext-d';\nexport { u } from './util.js';\n", + ); + writeFileSync( + join(dir, 'src', 'util.js'), + 'export const u = () => { throw new Error("u"); };\n', + ); + }; + const externals = ['ext-a', 'ext-b', 'ext-c', 'ext-d']; + + const check = async (out: string, indexFiles: string[]): Promise => { + const report = await diagnoseBuildOutput(out, { skipEnv: true, projectRoot: dirname(out) }); + for (const file of indexFiles) { + const code = readFileSync(join(out, file), 'utf8'); + expect(isFacadeCode(code), `${file}:\n${code}`).toBe(true); + const note = report.findings.find( + (f) => f.id === 'map.no-sources' && f.file === `${file}.map`, + ); + expect(note?.severity, `${file}.map`).toBe('info'); + } + // the chunk with real code keeps a real map, and nothing here is an error about maps or sources + expect( + report.findings.filter((f) => f.id === 'map.no-sources' && f.severity === 'error'), + ).toEqual([]); + }; + + for (const generatedCode of ['es5', 'es2015'] as const) { + for (const format of ['es', 'cjs'] as const) { + it(`Rollup ${format} with generatedCode ${generatedCode}`, async () => { + const dir = join(root, `facade-rollup-${format}-${generatedCode}`); + sources(dir); + const bundle = await rollup({ + input: { index: join(dir, 'src', 'index.js'), util: join(dir, 'src', 'util.js') }, + external: externals, + }); + const out = join(dir, 'dist'); + await bundle.write({ dir: out, format, sourcemap: true, generatedCode, interop: 'auto' }); + await bundle.close(); + await check(out, ['index.js']); + }); + } + } + + it('Vite 7 library mode (es + cjs, es2015 output) with a re-export barrel', async () => { + const dir = join(root, 'facade-vite7'); + sources(dir); + await vite7Build({ + root: dir, + configFile: false, + logLevel: 'silent', + build: { + lib: { + entry: { index: join(dir, 'src', 'index.js'), util: join(dir, 'src', 'util.js') }, + formats: ['es', 'cjs'], + }, + sourcemap: true, + minify: false, + outDir: join(dir, 'dist'), + rollupOptions: { external: externals }, + }, + }); + const files = readdirSync(join(dir, 'dist')).filter((f) => /^index\.(m?js|cjs)$/.test(f)); + expect(files.length).toBe(2); + await check(join(dir, 'dist'), files); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.test.ts b/packages/bundler-plugin-core/src/doctor.test.ts new file mode 100644 index 00000000..12b60911 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.test.ts @@ -0,0 +1,653 @@ +import { createHash } from 'node:crypto'; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + DOCTOR_CHECK_IDS, + DOCTOR_SCHEMA_VERSION, + type DoctorReport, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, +} from './doctor'; + +const ID_A = '11111111-1111-4111-8111-111111111111'; +const ID_B = '22222222-2222-4222-8222-222222222222'; +const ID_L = 'abcdef12-3456-4abc-8def-abcdefabcdef'; + +let root: string; +let dist: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-doctor-')); + dist = join(root, 'dist'); + mkdirSync(dist); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'app', version: '1.0.0' })); +}); +afterEach(() => rmSync(root, { recursive: true, force: true })); + +const put = (rel: string, content: string | Buffer): string => { + const path = join(dist, rel); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); + return path; +}; + +const stamp = (id: string): string => + `\n!function(){var g=globalThis;g._bugseeDebugIds=g._bugseeDebugIds||{};g._bugseeDebugIds["x"]="${id}"}();\n//# debugId=${id}\n`; + +const mapJson = (extra: Record = {}): string => + JSON.stringify({ + version: 3, + sources: ['a.ts'], + sourcesContent: ['export const a = 1;'], + names: [], + mappings: 'AAAA', + ...extra, + }); + +/** A fully stamped bundle + matching hidden map. */ +const goodPair = (name = 'app.js', id = ID_A): void => { + put(name, `console.log(1);${stamp(id)}`); + put(`${name}.map`, mapJson({ debugId: id })); +}; + +const ENV = { BUGSEE_APP_TOKEN: 'secret-token-value', BUGSEE_APP_BUILD: 'abc' }; +const run = (options: Parameters[1] = {}): Promise => + diagnoseBuildOutput(dist, { env: ENV, projectRoot: root, ...options }); +const ids = (report: DoctorReport): string[] => report.findings.map((f) => f.id); +const sev = (report: DoctorReport, id: string): string | undefined => + report.findings.find((f) => f.id === id)?.severity; + +describe('diagnoseBuildOutput', () => { + it('a stamped bundle with a matching hidden map has no warnings, only notes (even under --strict)', async () => { + goodPair(); + const report = await run(); + expect(report.schemaVersion).toBe(DOCTOR_SCHEMA_VERSION); + expect(report.tool).toBe('bugsee-sourcemaps-doctor'); + expect(report.summary).toMatchObject({ errors: 0, warnings: 0, bundles: 1, maps: 1 }); + expect(ids(report).sort()).toEqual([ + 'env.token-source', + 'map.hidden', + 'map.public-leftover', + 'map.sources-content', + ]); + expect(sev(report, 'map.public-leftover')).toBe('info'); + expect(doctorExitCode(report, true)).toBe(0); + expect(report.passed).toContain('stamp.missing-debug-id'); + expect(report.passed).not.toContain('map.public-leftover'); + // info-only facts are not "passed" checks + expect(report.passed).not.toContain('map.hidden'); + expect(report.passed).not.toContain('env.token-source'); + }); + + it('map.public-leftover is a warning when the directory is deployed', async () => { + goodPair(); + const report = await run({ deployed: true }); + expect(sev(report, 'map.public-leftover')).toBe('warning'); + expect(report.findings.find((f) => f.id === 'map.public-leftover')?.fix).toContain( + '--deployed', + ); + expect(doctorExitCode(report, true)).toBe(1); + }); + + it('ignore drops the listed IDs from findings and passed, and reports what it dropped', async () => { + goodPair(); + const report = await run({ + deployed: true, + ignore: ['map.public-leftover', 'stamp.mixed', 'env.token-source'], + }); + expect(ids(report)).not.toContain('map.public-leftover'); + expect(report.summary.warnings).toBe(0); + expect(report.ignored).toEqual(['map.public-leftover', 'env.token-source']); + expect(report.passed).not.toContain('stamp.mixed'); + expect((await run()).ignored).toBeUndefined(); + }); + + it('after deleteMaps (bundle stamped, no maps) nothing is wrong', async () => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + const report = await run(); + expect(report.summary).toMatchObject({ errors: 0, warnings: 0 }); + expect(ids(report)).toEqual(['env.token-source']); + expect(doctorExitCode(report)).toBe(0); + expect(doctorExitCode(report, true)).toBe(0); + }); + + it('output.dir-missing: a path that is not a directory', async () => { + const report = await diagnoseBuildOutput(join(root, 'nope'), { env: ENV }); + expect(ids(report)).toEqual(['output.dir-missing']); + expect(report.passed).toEqual([]); + expect(doctorExitCode(report)).toBe(2); + const asFile = await diagnoseBuildOutput(join(root, 'package.json'), { env: ENV }); + expect(ids(asFile)).toEqual(['output.dir-missing']); + }); + + it('output.no-js: a directory with no scripts; node_modules and .git are never searched', async () => { + put('index.html', ''); + put('node_modules/x/y.js', 'x'); + put('.git/z.js', 'x'); + const report = await run(); + expect(ids(report)).toContain('output.no-js'); + expect(sev(report, 'output.no-js')).toBe('error'); + expect(report.summary.bundles).toBe(0); + }); + + it('preserveModules-style layouts (dist/src/a.js, dist/test/b.js, dot-dirs) are walked, not dropped', async () => { + put('src/a.js', `a${stamp(ID_A)}`); + put('test/b.js', `b${stamp(ID_B)}`); + put('.hidden/c.js', 'c'); + const report = await run(); + expect(report.summary.bundles).toBe(3); + expect(ids(report)).not.toContain('output.no-js'); + }); + + it('stamp.missing-debug-id: an unstamped bundle WITH a map is an error', async () => { + put('app.js', 'console.log(1);\n//# sourceMappingURL=app.js.map'); + put('app.js.map', mapJson()); + const report = await run(); + const finding = report.findings.find((f) => f.id === 'stamp.missing-debug-id'); + expect(finding).toMatchObject({ severity: 'error', file: 'app.js' }); + expect(finding?.fix).toContain('sourcemaps inject'); + expect(doctorExitCode(report)).toBe(2); + }); + + it('stamp.missing-debug-id: an unstamped bundle with NO map is only a warning', async () => { + put('vendor.js', 'console.log(1);'); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.missing-debug-id')).toMatchObject({ + severity: 'warning', + details: { files: ['vendor.js'] }, + }); + expect(doctorExitCode(report)).toBe(0); + expect(doctorExitCode(report, true)).toBe(1); + }); + + it('stamp.missing-debug-id: a bundle that lost its stamp while its map kept the id', async () => { + put('app.js', 'console.log(1);'); + put('app.js.map', mapJson({ debugId: ID_A })); + const report = await run(); + const found = report.findings.filter((f) => f.id === 'stamp.missing-debug-id'); + expect(found).toHaveLength(1); + expect(found[0]).toMatchObject({ severity: 'error', details: { mapDebugId: ID_A } }); + }); + + it('stamp.missing-registration: a comment alone is not a stamp', async () => { + put('app.js', `console.log(1);\n//# debugId=${ID_A}\n`); + const report = await run(); + expect(sev(report, 'stamp.missing-registration')).toBe('error'); + expect(report.findings.find((f) => f.id === 'stamp.missing-registration')?.details).toEqual({ + files: ['app.js'], + }); + }); + + it('stamp.map-id-mismatch / stamp.map-no-debug-id', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', mapJson({ debugId: ID_B })); + put('b.js', `b${stamp(ID_B)}`); + put('b.js.map', mapJson()); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.map-id-mismatch')).toMatchObject({ + severity: 'error', + file: 'a.js.map', + details: { bundleDebugId: ID_A, mapDebugId: ID_B }, + }); + expect(report.findings.find((f) => f.id === 'stamp.map-no-debug-id')).toMatchObject({ + severity: 'error', + file: 'b.js.map', + }); + }); + + it('accepts the snake_case debug_id spelling in the map and compares case-insensitively', async () => { + put('a.js', `a${stamp(ID_L)}`); + put('a.js.map', mapJson({ debug_id: ID_L.toUpperCase() })); + const report = await run(); + expect(ID_L.toUpperCase()).not.toBe(ID_L); + expect(ids(report)).not.toContain('stamp.map-id-mismatch'); + expect(ids(report)).not.toContain('stamp.map-no-debug-id'); + }); + + it('stamp.mixed: some bundles stamped, some not', async () => { + goodPair('a.js', ID_A); + put('b.js', 'b\n//# sourceMappingURL=b.js.map'); + put('b.js.map', mapJson()); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.mixed')).toMatchObject({ + severity: 'warning', + details: { stamped: 1, unstamped: 1 }, + }); + }); + + it('stamp.duplicate-debug-id: same id, different contents; identical copies are fine', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('b.js', `different${stamp(ID_A)}`); + put('c.js', `same${stamp(ID_B)}`); + put('d.js', `same${stamp(ID_B)}`); + const report = await run(); + const dup = report.findings.filter((f) => f.id === 'stamp.duplicate-debug-id'); + expect(dup).toHaveLength(1); + expect(dup[0]).toMatchObject({ + severity: 'error', + details: { debugId: ID_A, files: ['a.js', 'b.js'] }, + }); + }); + + it('map.pointer-dangling: a note when the maps were removed on purpose; a warning otherwise', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=https://cdn.example/b.js.map${stamp(ID_B)}`); + const note = await run(); + const found = note.findings.find((f) => f.id === 'map.pointer-dangling'); + expect(found).toMatchObject({ severity: 'info', details: { pointers: ['a.js -> a.js.map'] } }); + expect(doctorExitCode(note, true)).toBe(0); + // a map file elsewhere in the output: the removal was not complete / deliberate + put('other.css.map', mapJson()); + expect(sev(await run(), 'map.pointer-dangling')).toBe('warning'); + rmSync(join(dist, 'other.css.map')); + // an unstamped bundle: nothing says the removal was deliberate + put('c.js', 'c'); + expect(sev(await run(), 'map.pointer-dangling')).toBe('warning'); + }); + + it('a pointer to a map in another directory resolves relative to the bundle', async () => { + put('js/a.js', `a\n//# sourceMappingURL=../maps/a.js.map${stamp(ID_A)}`); + put('maps/a.js.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.map-id-mismatch')?.file).toBe( + 'maps/a.js.map', + ); + expect(ids(report)).not.toContain('map.pointer-dangling'); + }); + + it('a root-absolute or malformed pointer pairs nothing and is not reported dangling (the stamp rule)', async () => { + put('a.js', `a\n//# sourceMappingURL=/a.js.map${stamp(ID_A)}`); + put('b.js', `b\n//# sourceMappingURL=%E0%A4%A.map${stamp(ID_B)}`); + const report = await run(); + expect(ids(report)).not.toContain('map.pointer-dangling'); + expect(report.summary.bundles).toBe(2); + }); + + it('a pointer with an unencoded space or percent-escape resolves like the stamp does', async () => { + put('a b.js', `a\n//# sourceMappingURL=a b.js.map${stamp(ID_A)}`); + put('a b.js.map', mapJson({ debugId: ID_B })); + const report = await run(); + expect(report.findings.find((f) => f.id === 'stamp.map-id-mismatch')?.file).toBe('a b.js.map'); + }); + + it('map.inline: a data: map has nothing to upload', async () => { + put('a.js', `a\n//# sourceMappingURL=data:application/json;base64,e30=${stamp(ID_A)}`); + put('b.js', 'b\n//# sourceMappingURL=data:application/json;base64,e30='); + const report = await run(); + expect(report.findings.find((f) => f.id === 'map.inline')).toMatchObject({ + severity: 'error', + details: { files: ['a.js', 'b.js'] }, + }); + // the unstamped inline bundle is an error even though it has no .map file + expect(report.findings.find((f) => f.id === 'stamp.missing-debug-id')).toMatchObject({ + severity: 'error', + file: 'b.js', + }); + }); + + it('map.invalid: not JSON, not an object, wrong version; also for a map nothing points at', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', '{not json'); + put('b.js', `b${stamp(ID_B)}`); + put('b.js.map', '[]'); + put('c.js', 'c'); + put('c.js.map', mapJson({ version: 2 })); + put('style.css.map', 'nope'); + put('other.css.map', mapJson({ version: 2 })); + const report = await run(); + const invalid = report.findings.filter((f) => f.id === 'map.invalid'); + expect(invalid.map((f) => f.file).sort()).toEqual([ + 'a.js.map', + 'b.js.map', + 'c.js.map', + 'other.css.map', + 'style.css.map', + ]); + expect(invalid.find((f) => f.file === 'a.js.map')?.message).toContain('not valid JSON'); + expect(invalid.find((f) => f.file === 'b.js.map')?.message).toContain('not a JSON object'); + expect(invalid.find((f) => f.file === 'c.js.map')?.message).toContain('version is 2'); + }); + + it('map.no-sources: missing or empty `sources`', async () => { + put('a.js', `a${stamp(ID_A)}`); + put('a.js.map', mapJson({ debugId: ID_A, sources: [] })); + put('b.js', `export{b}from'./m.js';${stamp(ID_B)}`); // a facade: no code of its own + put('b.js.map', JSON.stringify({ version: 3, debugId: ID_B, mappings: '' })); + const report = await run(); + const found = report.findings.filter((f) => f.id === 'map.no-sources'); + expect(found.map((f) => [f.file, f.severity])).toEqual([ + ['a.js.map', 'error'], // generated segments but no sources: a stripped map + ['b.js.map', 'info'], // no sources AND no mappings: an empty chunk, nothing to map + ]); + }); + + it('map.sources-content: embedded is a fact; absent AND unresolvable is a warning; absent but on disk is a fact', async () => { + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sources: ['../src/gone.ts', 'webpack/runtime/x'], + }), + ); + put('b.js', `b${stamp(ID_B)}`); + mkdirSync(join(root, 'src'), { recursive: true }); + writeFileSync(join(root, 'src', 'here.ts'), 'x'); + put( + 'b.js.map', + mapJson({ debugId: ID_B, sourcesContent: [null], sources: ['../src/here.ts'] }), + ); + const report = await run(); + const a = report.findings.find((f) => f.id === 'map.sources-unresolvable'); + expect(a).toMatchObject({ + severity: 'warning', + file: 'a.js.map', + details: { unresolved: 1, total: 2 }, + }); + expect(a?.message).toContain('../src/gone.ts'); + const b = report.findings.find((f) => f.id === 'map.sources-content' && f.file === 'b.js.map'); + expect(b).toMatchObject({ severity: 'info', details: { embedded: 0, total: 1 } }); + }); + + it('sources resolve through sourceRoot, file:// and bundler-scheme prefixes', async () => { + mkdirSync(join(root, 'src'), { recursive: true }); + writeFileSync(join(root, 'src', 'a.ts'), 'x'); + writeFileSync(join(root, 'src', 'b.ts'), 'x'); + writeFileSync(join(root, 'src', 'c.ts'), 'x'); + put('a.js', `a${stamp(ID_A)}`); + put( + 'a.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sourceRoot: '../src/', + sources: ['a.ts'], + }), + ); + put('b.js', `b${stamp(ID_B)}`); + put( + 'b.js.map', + mapJson({ + debugId: ID_B, + sourcesContent: undefined, + sources: [`file://${join(root, 'src', 'b.ts')}`], + }), + ); + put('c.js', 'c'); + put( + 'c.js.map', + mapJson({ + debugId: ID_A, + sourcesContent: undefined, + sourceRoot: '..', + sources: ['webpack://app/src/c.ts', '\0virtual', ''], + }), + ); + const report = await run(); + expect(ids(report)).not.toContain('map.sources-unresolvable'); + }); + + it('map.too-large: warns above the threshold', async () => { + goodPair(); + const report = await run({ maxMapBytes: 10 }); + expect(report.findings.find((f) => f.id === 'map.too-large')).toMatchObject({ + severity: 'warning', + file: 'app.js.map', + }); + expect((await run()).findings.map((f) => f.id)).not.toContain('map.too-large'); + }); + + it('build.dev-bundle: webpack eval-style output', async () => { + put('main.js', `eval("x\\n//# sourceURL=webpack-internal:///./src/a.ts");`); + const report = await run(); + expect(report.findings.find((f) => f.id === 'build.dev-bundle')).toMatchObject({ + severity: 'warning', + details: { files: ['main.js'] }, + }); + }); + + describe('SRI', () => { + const sri = (bytes: string | Buffer): string => + `sha384-${createHash('sha384').update(bytes).digest('base64')}`; + + it('sri.unstamped-hazard: a pinned script that would be broken by stamping', async () => { + const js = 'console.log(1);'; + put('app.js', js); + put('index.html', ``); + const report = await run(); + expect(report.findings.find((f) => f.id === 'sri.unstamped-hazard')).toMatchObject({ + severity: 'warning', + details: { scripts: ['app.js'] }, + }); + expect(ids(report)).not.toContain('sri.mismatch'); + }); + + it('a pin to a script that is not on disk is ignored', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('index.html', ``); + const report = await run(); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + expect(ids(report)).not.toContain('doctor.internal-error'); + expect(report.summary.errors).toBe(0); + }); + + it('a stamped script whose pin matches its bytes is fine', async () => { + const js = `console.log(1);${stamp(ID_A)}`; + put('app.js', js); + put('index.html', ``); + const report = await run(); + expect(ids(report)).not.toContain('sri.unstamped-hazard'); + expect(ids(report)).not.toContain('sri.mismatch'); + expect(report.passed).toContain('sri.mismatch'); + }); + + it('sri.mismatch: stamped AFTER the page was hashed', async () => { + put('app.js', `console.log(1);${stamp(ID_A)}`); + put('index.html', ``); + const report = await run(); + expect(report.findings.find((f) => f.id === 'sri.mismatch')).toMatchObject({ + severity: 'error', + details: { scripts: ['app.js'] }, + }); + expect(report.findings.find((f) => f.id === 'sri.mismatch')?.message).toContain('refuses'); + }); + + it('sri.manifest-hashes: a manifest in the directory pins hashes; the parent directory is never read', async () => { + put('app.js', `c${stamp(ID_A)}`); + put('asset-manifest.json', JSON.stringify({ 'app.js': { integrity: sri('x') } })); + put('plain-manifest.json', '{}'); + put('readme.txt', 'integrity'); + // a page and a manifest in the PARENT (e.g. a CDN script with integrity) are not this build's business + writeFileSync( + join(root, 'index.html'), + ``, + ); + writeFileSync(join(root, 'pins-manifest.json'), `{"h":"${sri('y')}"}`); + const report = await run(); + const found = report.findings.find((f) => f.id === 'sri.manifest-hashes'); + expect(found?.severity).toBe('warning'); + expect(found?.details?.files).toEqual(['asset-manifest.json']); + }); + + it('a FIFO or oversized file named like a manifest is skipped, never opened', async () => { + put('app.js', `c${stamp(ID_A)}`); + const { spawnSync } = await import('node:child_process'); + if (spawnSync('mkfifo', [join(dist, 'x-manifest.json')]).status !== 0) { + return; + } + put('big-manifest.json', `{"integrity":"${'x'.repeat(100)}"}`); + const report = await run({ maxMapBytes: 50 }); + expect(ids(report)).not.toContain('sri.manifest-hashes'); + }); + }); + + describe('environment', () => { + it('env.token-missing is a warning; the token value is never printed, only where it came from', async () => { + goodPair(); + const report = await run({ env: {} }); + expect(report.findings.find((f) => f.id === 'env.token-missing')?.severity).toBe('warning'); + expect(ids(report)).not.toContain('env.token-source'); + const withToken = await run({ appToken: 'super-secret' }); + expect(JSON.stringify(withToken)).not.toContain('super-secret'); + expect(JSON.stringify(withToken)).not.toContain('secret-token-value'); + expect(ids(withToken)).not.toContain('env.token-missing'); + expect(withToken.findings.find((f) => f.id === 'env.token-source')).toMatchObject({ + severity: 'info', + details: { source: 'option' }, + }); + const fromEnv = await run(); + expect(fromEnv.findings.find((f) => f.id === 'env.token-source')?.details).toEqual({ + source: 'env', + }); + expect(JSON.stringify(fromEnv)).not.toContain('secret-token-value'); + // whitespace-only counts as unset + expect(ids(await run({ env: { BUGSEE_APP_TOKEN: ' ' } }))).toContain('env.token-missing'); + expect(ids(await run({ env: {}, appToken: ' ' }))).toContain('env.token-missing'); + }); + + it('env.version-unresolved / env.build-unresolved', async () => { + goodPair(); + const lonely = mkdtempSync(join(tmpdir(), 'bugsee-doctor-lonely-')); + try { + const report = await run({ env: { BUGSEE_APP_TOKEN: 't' }, projectRoot: lonely }); + expect(sev(report, 'env.version-unresolved')).toBe('warning'); + expect(sev(report, 'env.build-unresolved')).toBe('info'); + const explicit = await run({ + env: { BUGSEE_APP_TOKEN: 't' }, + projectRoot: lonely, + appVersion: '9.9.9', + appBuild: '7', + }); + expect(ids(explicit)).not.toContain('env.version-unresolved'); + expect(ids(explicit)).not.toContain('env.build-unresolved'); + } finally { + rmSync(lonely, { recursive: true, force: true }); + } + }); + + it('env.node-env-development', async () => { + goodPair(); + expect( + sev(await run({ env: { ...ENV, NODE_ENV: 'development' } }), 'env.node-env-development'), + ).toBe('warning'); + expect(ids(await run({ env: { ...ENV, NODE_ENV: 'production' } }))).not.toContain( + 'env.node-env-development', + ); + }); + + it('skipEnv drops every env.* check', async () => { + goodPair(); + const report = await run({ env: {}, skipEnv: true }); + expect(ids(report).filter((id) => id.startsWith('env.'))).toEqual([]); + expect(report.passed.filter((id) => id.startsWith('env.'))).toEqual([]); + }); + }); + + it('an output directory is walked at any depth', async () => { + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + put('a/b/c/d/e/f/ok.js', 'x'); + const report = await run(); + expect(report.summary.bundles).toBe(2); + }); + + it('only a project directory that is (or contains) the working directory is fenced and depth-capped', async () => { + put('a/b/c/d/e/f/g/h/deep.js', 'x'); + put('a/ok.js', 'x'); + put('src/s.js', 'x'); + put('.cache/c.js', 'x'); + put('package.json', '{"name":"p"}'); // a directory that IS a project; see doctor.hardening.test.ts + const here = process.cwd(); + process.chdir(dist); + try { + const report = await run({ skipEnv: true }); + expect(report.summary.bundles).toBe(1); + } finally { + process.chdir(here); + } + }); + + it('a map pointer that resolves to a directory is skipped, not a crash', async () => { + put('a.js', `a\n//# sourceMappingURL=a.js.map${stamp(ID_A)}`); + mkdirSync(join(dist, 'a.js.map')); + const report = await run(); + expect(report.summary.bundles).toBe(1); + expect(ids(report)).not.toContain('map.invalid'); + }); + + const describePerm = process.getuid?.() === 0 ? describe.skip : describe; + describePerm('unreadable paths', () => { + it('an unreadable sub-directory contributes nothing (and is reported, see doctor.hardening.test.ts); an unreadable parent is harmless', async () => { + put('a.js', `a${stamp(ID_A)}`); + mkdirSync(join(dist, 'locked')); + writeFileSync(join(dist, 'locked', 'x.js'), 'x'); + chmodSync(join(dist, 'locked'), 0o000); + chmodSync(root, 0o300); + try { + const report = await run({ skipEnv: true }); + expect(report.summary.bundles).toBe(1); + expect(ids(report)).not.toContain('sri.manifest-hashes'); + } finally { + chmodSync(root, 0o700); + chmodSync(join(dist, 'locked'), 0o700); + } + }); + + it('an unreadable manifest is ignored', async () => { + put('a.js', `a${stamp(ID_A)}`); + const manifest = put('asset-manifest.json', '{"integrity":1}'); + chmodSync(manifest, 0o000); + try { + expect(ids(await run({ skipEnv: true }))).not.toContain('sri.manifest-hashes'); + } finally { + chmodSync(manifest, 0o600); + } + }); + }); + + it('every check ID is unique and namespaced', () => { + expect(new Set(DOCTOR_CHECK_IDS).size).toBe(DOCTOR_CHECK_IDS.length); + for (const id of DOCTOR_CHECK_IDS) { + expect(id).toMatch(/^(output|stamp|map|sri|build|env|doctor)\.[a-z-]+$/); + } + }); +}); + +describe('doctorExitCode / formatDoctorReport', () => { + const report = (errors: number, warnings: number): DoctorReport => ({ + schemaVersion: 1, + tool: 'bugsee-sourcemaps-doctor', + dir: '/d', + summary: { errors, warnings, infos: 0, bundles: 0, maps: 0 }, + passed: [], + findings: [], + }); + + it('exit codes: 2 on errors, 1 on warnings only under strict, else 0', () => { + expect(doctorExitCode(report(1, 1), true)).toBe(2); + expect(doctorExitCode(report(0, 1), true)).toBe(1); + expect(doctorExitCode(report(0, 1))).toBe(0); + expect(doctorExitCode(report(0, 0), true)).toBe(0); + }); + + it('renders errors before warnings before notes, with fix hints', async () => { + put('vendor.js', 'x'); + put('app.js', `c${stamp(ID_A)}`); + put('app.js.map', mapJson({ debugId: ID_B })); + const text = formatDoctorReport(await run()); + const error = text.indexOf('ERROR [stamp.map-id-mismatch]'); + const warn = text.indexOf('WARN [stamp.missing-debug-id]'); + const info = text.indexOf('info [map.sources-content]'); + expect(error).toBeGreaterThan(-1); + expect(warn).toBeGreaterThan(error); + expect(info).toBeGreaterThan(warn); + expect(text).toContain(' fix: '); + expect(text).toContain('2 bundle(s), 1 map(s): 1 error(s)'); + }); + + it('says so when there is nothing to report', () => { + expect(formatDoctorReport(report(0, 0))).toContain('No problems found.'); + }); +}); diff --git a/packages/bundler-plugin-core/src/doctor.ts b/packages/bundler-plugin-core/src/doctor.ts new file mode 100644 index 00000000..5232e8a4 --- /dev/null +++ b/packages/bundler-plugin-core/src/doctor.ts @@ -0,0 +1,1550 @@ +// `sourcemaps doctor` — the OFFLINE half. Reads a build output directory exactly as it sits on disk and says +// why a crash from it would (not) symbolicate, without a network call, a token, or a backend. +// +// Every finding has a stable check ID, a severity, a human message and a fix hint, and the report has one +// versioned JSON shape (`DoctorReport`) that the Rust `bugsee-cli sourcemaps doctor` is specified to emit +// too (see the design hand-off), so a CI step can consume either. Pure reads: nothing is written or deleted. +import { createHash } from 'node:crypto'; +import type { Dirent } from 'node:fs'; +import { existsSync } from 'node:fs'; +import { readdir, realpath, stat } from 'node:fs/promises'; +import nodePath, { dirname, join, relative, resolve, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { findAppIdentity } from './app-identity'; +import { readDebugId } from './debug-ids'; +import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; +import { isFacadeCode } from './facade'; +import type { EnvRecord } from './run-cli'; +import { READ_CEILING, type ReadResult, readRegularFile } from './safe-read'; +import { findSriProtectedScriptsDetailed, MAX_HTML_BYTES, passesIntegrity } from './sri'; +import { cutAtQuery, isProjectRootOrAbove, MAX_WALK_DEPTH, NEVER_WALK } from './stamp-files'; +import { lastSourceMappingUrl, localPointerTarget } from './verify-stamp'; + +/** Bumped on any incompatible change to `DoctorReport`; the Rust command emits the same number. */ +export const DOCTOR_SCHEMA_VERSION = 1; + +export type DoctorSeverity = 'error' | 'warning' | 'info'; + +/** One thing the doctor found. `id` is stable across releases and is what tooling should match on. */ +export interface DoctorFinding { + id: string; + severity: DoctorSeverity; + message: string; + /** What to do about it. Omitted for purely informational findings. */ + fix?: string; + /** The file concerned, relative to the checked directory (POSIX separators). */ + file?: string; + /** Machine-readable specifics (counts, ids, paths); never contains a secret. */ + details?: Record; +} + +export interface DoctorReport { + schemaVersion: typeof DOCTOR_SCHEMA_VERSION; + tool: 'bugsee-sourcemaps-doctor'; + /** Absolute path of the checked directory. */ + dir: string; + summary: { errors: number; warnings: number; infos: number; bundles: number; maps: number }; + /** Check IDs that ran and found nothing wrong. */ + passed: string[]; + findings: DoctorFinding[]; + /** Check IDs dropped by `ignore`; omitted when none were. */ + ignored?: string[]; +} + +export interface DoctorOptions { + /** Environment to resolve the token / version / build from. Defaults to `process.env`. */ + env?: EnvRecord; + /** An explicit token (the `appToken` plugin option). Never echoed. */ + appToken?: string; + appVersion?: string; + appBuild?: string; + /** Where `.env.bugsee-build-plugin` and `package.json` are looked up from. Defaults to the working directory. */ + projectRoot?: string; + /** A map larger than this many bytes is flagged. Default 50 MiB. */ + maxMapBytes?: number; + /** Skip the `env.*` checks (an output-only audit, e.g. in a container with no token). */ + skipEnv?: boolean; + /** + * The directory is (about to be) served to the public: leftover `.map` files are then a WARNING (they expose + * source) instead of a note. Off by default so `--strict` works straight after a plugin run. + */ + deployed?: boolean; + /** Check IDs to drop from the report (repeatable `--ignore`). */ + ignore?: readonly string[]; + /** A script larger than this many bytes is not read (default 512 MiB). */ + maxBundleBytes?: number; + /** + * Globs (relative to the checked directory, POSIX separators; `*` stays in a directory, `**` crosses them, `?` is + * one character, a trailing `/` means the directory) of files the build did NOT emit: a doctor cannot tell a + * script copied in (Vite `publicDir`, a copy plugin) from a bundle that lost its stamp, and the plugin never stamps + * the former. Matching files are dropped before analysis and listed as `output.excluded`. + */ + exclude?: readonly string[]; +} + +const DEFAULT_MAX_MAP_BYTES = 50 * 1024 * 1024; +const DEFAULT_MAX_BUNDLE_BYTES = 512 * 1024 * 1024; +/** Files read at once: bounds open handles. */ +const READ_CONCURRENCY = 16; +/** Bytes read at once (a batch of sixteen 512 MiB scripts is 8 GiB): a single larger file is still read, alone. */ +const READ_BYTE_BUDGET = 256 * 1024 * 1024; + +/** + * Where the batch starting at `start` ends (exclusive): at most `maxCount` files and `budget` bytes, but always at + * least one file. `sizes` are what `stat` reported. + */ +export function batchEnd( + sizes: readonly number[], + start: number, + maxCount: number, + budget: number, +): number { + let end = start + 1; + let total = sizes[start] ?? 0; + while (end < sizes.length && end - start < maxCount && total + (sizes[end] ?? 0) <= budget) { + total += sizes[end] ?? 0; + end++; + } + return end; +} +const BUNDLE = /\.[cm]?js$/i; +const MAP = /\.map$/i; +/** The global the runtime stub writes the id into (`@bugsee/browser` reads it at crash time). */ +const REGISTRATION = '_bugseeDebugIds'; +const MAX_LISTED = 5; + +/** Every ID the doctor can emit, in report order. Exported so docs / the Rust port can be checked against it. */ +export const DOCTOR_CHECK_IDS = [ + 'output.dir-missing', + 'output.no-js', + 'output.unreadable', + 'output.dir-unreadable', + 'output.excluded', + 'output.exclude-unmatched', + 'output.walk-fenced', + 'stamp.missing-debug-id', + 'stamp.missing-registration', + 'stamp.map-id-mismatch', + 'stamp.map-no-debug-id', + 'stamp.mixed', + 'stamp.duplicate-debug-id', + 'map.pointer-dangling', + 'map.hidden', + 'map.inline', + 'map.invalid', + 'map.no-sources', + 'map.sources-content', + 'map.sources-unresolvable', + 'map.too-large', + 'map.unreadable', + 'map.pointer-outside-dir', + 'map.public-leftover', + 'sri.unstamped-hazard', + 'sri.mismatch', + 'sri.html-skipped', + 'sri.pin-unreadable', + 'sri.manifest-hashes', + 'build.dev-bundle', + 'env.token-source', + 'env.token-missing', + 'env.version-unresolved', + 'env.build-unresolved', + 'env.node-env-development', + 'doctor.internal-error', +] as const; +export type DoctorCheckId = (typeof DOCTOR_CHECK_IDS)[number]; + +/** Hard failures: `--ignore` never hides these (it would turn "nothing was checked" into a pass). */ +export const NON_IGNORABLE_CHECK_IDS: ReadonlySet = new Set([ + 'output.dir-missing', + 'output.no-js', + 'doctor.internal-error', +]); + +const posix = (path: string): string => path.split('\\').join('/'); + +/** `bundle.js.map` -> the same name as written in the report; always relative to `dir`. */ +const rel = (dir: string, path: string): string => posix(relative(dir, path)); + +/** + * Every script and map under `root`, and the directories the fence skipped. An output directory is walked in full + * (Rollup `preserveModules` writes `dist/src/*.js`; a build may emit `dist/test/`), skipping only `node_modules` + * and `.git`; the fence on `src`/`test`/dot-directories and the depth cap apply ONLY when `root` is a project + * directory (has a `package.json`) that is, or contains, the working directory, where they keep the walk out of the + * source tree. What the fence skipped is returned, never silent. Iterative, and never spreads a result list (a + * directory with 100k files must not overflow the call stack). + */ +export async function walkDetailed( + root: string, +): Promise<{ files: string[]; skipped: string[]; fenced: boolean; unreadable: string[] }> { + const fenced = (await isProjectRootOrAbove(root)) && existsSync(join(root, 'package.json')); + const found: string[] = []; + // Directories the fence kept out, with their REAL path: one that a link then walked is dropped from the report. + const skippedEntries: Array<{ name: string; real: string }> = []; + const unreadable: string[] = []; + // Real directories already WALKED (not merely met: one beyond the depth cap is not walked, and a shallower link to it + // must still get its turn): a loop or an alias is never walked, or counted, twice. + const realRoot = await realpath(root).catch(() => root); + const visited = new Set(); + type Queued = { dir: string; depth: number; real: string }; + const pending: Queued[] = [{ dir: root, depth: 0, real: realRoot }]; + // Links to directories inside the output are followed only AFTER every real directory has been walked, so a real + // directory always wins over an alias whatever the names sort like: every file is reported (and excluded, and + // stamped) under its real path. + const deferred: Queued[] = []; + const drain = async (): Promise => { + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + await visitDir(next); + } + }; + const visitDir = async (next: Queued): Promise => { + if (fenced && next.depth > MAX_WALK_DEPTH) { + skippedEntries.push({ name: rel(root, next.dir), real: next.real }); + return; + } + if (visited.has(next.real)) { + return; + } + visited.add(next.real); + let entries: Dirent[]; + try { + entries = await readdir(next.dir, { withFileTypes: true }); + } catch { + // A directory whose scripts and maps were NOT seen: reported, never a silent pass. + unreadable.push(rel(root, next.dir) || '.'); + return; + } + for (const entry of entries) { + const full = join(next.dir, entry.name); + // What a symlink POINTS AT decides how it is treated (a link named `assets.js` may be a directory): the real + // path of the directory it names, or undefined for a link to a file or a dangling one (those named like a + // script or map are listed below and judged by the guarded read). + let dirLink: string | undefined; + if (entry.isSymbolicLink()) { + const target = await realpath(full).catch(() => undefined); + const isDirectory = + target !== undefined && + (await stat(target).then( + (info) => info.isDirectory(), + /* v8 ignore start -- the link vanished between realpath and stat: a race that cannot be reproduced deterministically */ + () => false, + /* v8 ignore stop */ + )); + dirLink = isDirectory ? target : undefined; + } + if (entry.isDirectory() || dirLink !== undefined) { + if (entry.name === 'node_modules' || entry.name === '.git') { + continue; + } + if (fenced && (NEVER_WALK.has(entry.name) || entry.name.startsWith('.'))) { + skippedEntries.push({ + name: rel(root, full), + real: dirLink ?? join(next.real, entry.name), + }); + continue; + } + if (dirLink === undefined) { + pending.push({ dir: full, depth: next.depth + 1, real: join(next.real, entry.name) }); + } else if (dirLink === realRoot || dirLink.startsWith(realRoot + sep)) { + deferred.push({ dir: full, depth: next.depth + 1, real: dirLink }); + } else { + // A directory whose scripts were NOT seen: it leaves the output directory. + unreadable.push(rel(root, full)); + } + } else if (BUNDLE.test(entry.name) || MAP.test(entry.name)) { + found.push(full); + } + } + }; + await drain(); + // (`deferred` can grow while it is processed: a followed link's tree may hold more links.) + for (let i = 0; i < deferred.length; i++) { + pending.push(deferred[i] as Queued); + await drain(); + } + // What the fence kept out and NOTHING walked (a link may have covered a directory the real walk could not reach). + const skipped = skippedEntries + .filter((entry) => !visited.has(entry.real)) + .map((entry) => entry.name); + return { files: found.sort(), skipped: skipped.sort(), fenced, unreadable: unreadable.sort() }; +} + +export async function walk(root: string): Promise { + return (await walkDetailed(root)).files; +} + +/** A glob (see {@link DoctorOptions.exclude}) as an anchored regular expression over a POSIX relative path. */ +export function globToRegExp(glob: string): RegExp { + const pattern = glob.endsWith('/') ? `${glob}**` : glob; + let source = ''; + for (let i = 0; i < pattern.length; i++) { + const c = pattern.charAt(i); + if (c === '*') { + if (pattern.charAt(i + 1) === '*') { + const slash = pattern.charAt(i + 2) === '/'; + source += slash ? '(?:.*/)?' : '.*'; + i += slash ? 2 : 1; + } else { + source += '[^/]*'; + } + } else if (c === '?') { + source += '[^/]'; + } else { + source += c.replace(/[\\^$.|+()[\]{}]/g, '\\$&'); + } + } + return new RegExp(`^${source}$`); +} + +/** + * The `sources` and their embedded `sourcesContent` (aligned by index) of a map. An ordinary map has them at the top + * level; an INDEX map keeps them inside `sections[].map`, so those are concatenated, each section's content padded to + * its own sources so the alignment survives. + */ +export function mapSources(json: Record): { + sources: unknown[]; + content: unknown[]; + roots: string[]; + hasOriginal: boolean; +} { + let hasOriginal = false; + const sources: unknown[] = []; + const content: unknown[] = []; + const roots: string[] = []; + const collect = (map: Record, depth: number): void => { + if (Array.isArray(map.sources) && map.sources.length > 0) { + // A leaf map: its content and sourceRoot belong to ITS sources only (aligned by index). + const own = map.sources as unknown[]; + const embedded = Array.isArray(map.sourcesContent) ? (map.sourcesContent as unknown[]) : []; + const root = typeof map.sourceRoot === 'string' ? map.sourceRoot : ''; + hasOriginal ||= + typeof map.mappings === 'string' && hasOriginalPosition(map.mappings, own.length); + own.forEach((source, i) => { + sources.push(source); + content.push(embedded[i]); + roots.push(root); + }); + return; + } + if (depth >= MAX_INDEX_DEPTH) { + return; + } + // An INDEX map keeps its maps inside `sections[].map`, which may be index maps themselves. + for (const section of Array.isArray(map.sections) ? (map.sections as unknown[]) : []) { + const inner = (section as { map?: unknown } | null)?.map; + if (typeof inner === 'object' && inner !== null) { + collect(inner as Record, depth + 1); + } + } + }; + collect(json, 0); + return { sources, content, roots, hasOriginal }; +} + +/** Nested index maps are followed this deep (a real one is 1-2 levels); a hostile chain must not overflow the stack. */ +const MAX_INDEX_DEPTH = 32; + +/** + * Whether a map holds any GENERATED segment at all (a `mappings` with something besides separators, in the map or in + * any section). Rollup writes `sources: []`, `mappings: ""` for a facade or empty chunk: there is nothing to map, so + * nothing to symbolicate. Beyond the nesting cap it cannot tell, and says yes (so a deep chain is not waved through). + */ +export function hasGeneratedSegments(map: Record, depth = 0): boolean { + if (typeof map.mappings === 'string' && /[^;,]/.test(map.mappings)) { + return true; + } + if (depth >= MAX_INDEX_DEPTH) { + return true; + } + return (Array.isArray(map.sections) ? (map.sections as unknown[]) : []).some((section) => { + const inner = (section as { map?: unknown } | null)?.map; + return typeof inner === 'object' && inner !== null + ? hasGeneratedSegments(inner as Record, depth + 1) + : false; + }); +} + +const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +/** + * Whether a `mappings` string has at least one segment that names an ORIGINAL position: four or more VLQ values + * (generated column, source index, original line, original column) whose source index points at a real entry of + * `sourceCount` sources. Source indexes are DELTAS against the previous segment's, so they are accumulated across the + * whole string. A map made only of generated-position segments, or empty, or pointing at no source, cannot map a frame + * back to your code. A segment with a character outside the base64 alphabet is unusable and does not count. + * One pass, no split: the first usable segment answers. + */ +export function hasOriginalPosition( + mappings: string, + sourceCount: number = Number.POSITIVE_INFINITY, +): boolean { + let source = 0; // the running source index (deltas accumulate over the whole string) + let values = 0; + let usable = true; + let value = 0; // the VLQ value being decoded + let shift = 0; + let segmentSource = 0; + const finish = (): boolean => + usable && values >= 4 && segmentSource >= 0 && segmentSource < sourceCount; + for (let i = 0; i < mappings.length; i++) { + const ch = mappings.charAt(i); + if (ch === ',' || ch === ';') { + if (finish()) { + return true; + } + if (usable && values >= 4) { + source = segmentSource; // only a segment with an original line and column moves it; the next segment's delta is against this one + } + values = 0; + usable = true; + value = 0; + shift = 0; + continue; + } + const digit = BASE64.indexOf(ch); + if (digit < 0) { + usable = false; + continue; + } + value += (digit & 31) * 2 ** shift; + if ((digit & 32) !== 0) { + shift += 5; + continue; + } + // a value ends here: bit 0 is the sign + const decoded = value % 2 === 1 ? -(value - 1) / 2 : value / 2; + values++; + if (values === 2) { + segmentSource = source + decoded; + } + value = 0; + shift = 0; + } + return finish(); +} + +/** + * Memoise an async computation per key, keeping at most `limit` results (least recently used out first). Used so a + * map that many bundles share is read and parsed once, without keeping every map of a big build in memory. + */ +export function boundedMemo( + limit: number, + compute: (key: string) => Promise, +): (key: string) => Promise { + const cache = new Map>(); + return (key) => { + const hit = cache.get(key); + if (hit !== undefined) { + cache.delete(key); + cache.set(key, hit); // most recently used goes last + return hit; + } + const value = compute(key); + cache.set(key, value); + if (cache.size > limit) { + cache.delete(cache.keys().next().value as string); + } + return value; + }; +} + +interface ParsedMap { + ok: true; + json: Record; + debugId: string | undefined; +} + +function parseMap(text: string): ParsedMap | { ok: false; why: string } { + if (text.startsWith('\uFEFF')) { + return { + ok: false, + why: 'not valid JSON: it starts with a UTF-8 byte order mark (BOM), which the upload rejects', + }; + } + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return { ok: false, why: 'not valid JSON' }; + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return { ok: false, why: 'not a JSON object' }; + } + const json = parsed as Record; + const id = [json.debugId, json.debug_id].find((v) => typeof v === 'string' && v !== ''); + return { ok: true, json, debugId: typeof id === 'string' ? id.toLowerCase() : undefined }; +} + +/** Paths probed to ask "would these patterns hide everything the doctor could find in this directory". */ +const DIR_PROBES = [ + 'c.js', + 'zz-1/c.mjs', + 'zz-2/zz-3/c.cjs', + 'zz-4/c.js.map', + 'zz-5/zz-6/zz-7/c.map', + 'c.html', + 'zz-8/c.htm', + 'zz-9/zz-10/c', +]; + +/** `scheme://...`: a URL, not a directory name. */ +const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//i; + +/** Sources that name no file on disk by construction (bundler runtime, virtual modules). */ +const VIRTUAL_SOURCE = /^(webpack\/|\(webpack\)|\0|<|rollup:|vite\/)|\0/; + +/** + * Resolve a map `sources` entry as a debugger would. `file://` URLs follow `fileURLToPath` (so `file:///C:/x` + * is `C:\x` on Windows and a bad escape is "unknowable", not an exception). A bundler-scheme path + * (`webpack://app/./src/x.ts`) is relative to the PROJECT root, not to the map. Anything else is resolved from + * the map's directory and its `sourceRoot`. Undefined means "names no file on disk" (virtual / unparseable). + */ +export function sourcePath( + mapDir: string, + sourceRoot: string, + source: string, + projectRoot: string = mapDir, + api: typeof nodePath = nodePath, +): string | undefined { + let path = source; + let fromProject = false; + // ECMA-426: the source URL is `sourceRoot + source`. A scheme in the root (`webpack:///` + `src/x.ts`) is the + // same URL as the scheme written into `source`, so it takes the same rule below. + if ( + SCHEME_URL.test(sourceRoot) && + !/^[a-z][a-z0-9+.-]*:/i.test(source) && + !api.isAbsolute(source) + ) { + path = sourceRoot.endsWith('/') ? `${sourceRoot}${source}` : `${sourceRoot}/${source}`; + } + if (/^file:\/\//i.test(path)) { + try { + return fileURLToPath(path, { windows: api === nodePath.win32 }); + } catch { + return undefined; + } + } + if (SCHEME_URL.test(path)) { + // `webpack://app/./src/x.ts` and friends: the scheme/namespace is not a directory; drop it. + path = path.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*\//i, ''); + fromProject = true; + } + if (VIRTUAL_SOURCE.test(path) || path === '') { + return undefined; + } + if (api.isAbsolute(path)) { + return path; + } + return fromProject ? api.resolve(projectRoot, path) : api.resolve(mapDir, sourceRoot, path); +} + +type InsideRead = { ok: true; bytes: Buffer; real: string } | Extract; + +/** + * Read `path` if, and only if, it is a regular file whose REAL path is inside `realRoot`. A symlink that resolves + * inside the directory (pnpm-style `assets/app.js -> ../.store/app.js`) is read through its real path; one that + * leads outside, dangles or loops is a value describing why, never a read. The open itself refuses a symlink, + * blocks on nothing and judges type and size on the descriptor (see safe-read.ts), so there is no + * check-then-use gap on the file. + */ +async function readInside(path: string, limit: number, realRoot: string): Promise { + let real: string; + try { + real = await realpath(path); + } catch (error) { + return { + ok: false, + reason: `could not be resolved (${(error as NodeJS.ErrnoException).code ?? 'error'})`, + }; + } + if (!isInside(realRoot, real)) { + return { ok: false, reason: 'resolves outside the output directory' }; + } + const read = await readRegularFile(real, limit); + return read.ok ? { ...read, real } : read; +} + +/** Most entries a `details` list carries; `total` says how many there were. */ +const MAX_DETAIL = 100; +const listDetails = (key: string, list: readonly unknown[]): Record => ({ + [key]: list.slice(0, MAX_DETAIL), + ...(list.length > MAX_DETAIL ? { total: list.length } : {}), +}); + +/** Whether `target` is `root` itself or inside it. */ +function isInside(root: string, target: string): boolean { + const path = relative(root, target); + return ( + path === '' || + !(path === '..' || path.startsWith(`..${nodePath.sep}`) || nodePath.isAbsolute(path)) + ); +} + +const sha = (bytes: Buffer): string => createHash('sha256').update(bytes).digest('hex'); + +/** + * `*manifest*.json` files directly in `dir` that mention integrity hashes. Only the checked directory is ever read + * (a page in the parent is not this build's to judge, and may be anything), through the bounded regular-file + * reader, so a FIFO or a `/dev/zero` symlink named like a manifest is skipped, not opened. + */ +async function manifestsWithIntegrity( + dir: string, + limit: number, + realRoot: string, +): Promise { + let names: string[]; + try { + names = await readdir(dir); + } catch { + return []; + } + const hits: string[] = []; + for (const name of names.sort()) { + if (!/manifest.*\.json$/i.test(name)) { + continue; + } + const read = await readInside(join(dir, name), limit, realRoot); + if ( + read.ok && + /\bintegrity\b|["'](sha(256|384|512))-[A-Za-z0-9+/=]{20,}/i.test(read.bytes.toString('utf8')) + ) { + hits.push(join(dir, name)); + } + } + return hits; +} + +/** + * Audit the build output in `dirInput`. Never throws for a problem with the directory (that is a finding); + * never writes; reads each script and map once, bounded by size, through the guarded reader (a duplicate-ID candidate is read a second time to compare contents). + */ +export async function diagnoseBuildOutput( + dirInput: string, + options: DoctorOptions = {}, +): Promise { + try { + return await diagnose(dirInput, options); + } catch (error) { + // The contract is "never throws": whatever went wrong is the finding. + return finish( + resolve(String(dirInput)), + [ + { + id: 'doctor.internal-error', + severity: 'error', + message: `The doctor failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`, + fix: 'This is a bug in the doctor; re-run with --json and report it with the directory layout.', + }, + ], + 0, + 0, + [], + options.ignore, + ); + } +} + +async function diagnose(dirInput: string, options: DoctorOptions): Promise { + const dir = resolve(dirInput); + const findings: DoctorFinding[] = []; + const failed = new Set(); + const add = (finding: DoctorFinding): void => { + findings.push(finding); + failed.add(finding.id); + }; + const env = options.env ?? (process.env as EnvRecord); + // A NaN limit would switch the size check off (`size > NaN` is false): it means "not given". The effective limit is + // never above what the reader can hold, and that is the one reported. + const given = (value: number | undefined, fallback: number): number => + value === undefined || Number.isNaN(value) ? fallback : value; + const maxMapBytes = Math.min(given(options.maxMapBytes, DEFAULT_MAX_MAP_BYTES), READ_CEILING); + const maxBundleBytes = given(options.maxBundleBytes, DEFAULT_MAX_BUNDLE_BYTES); + const projectRoot = resolve(options.projectRoot ?? process.cwd()); + + let isDir = false; + try { + isDir = (await stat(dir)).isDirectory(); + } catch { + isDir = false; + } + if (!isDir) { + add({ + id: 'output.dir-missing', + severity: 'error', + message: `${dir} does not exist or is not a directory.`, + fix: 'Run the build first, and pass the bundler output directory (e.g. dist, build, .output/public).', + }); + return finish(dir, findings, 0, 0, [], options.ignore); + } + + const realDir = await realpath(dir); + const walked = await walkDetailed(dir); + // `./public/**` is `public/**`: a leading `./` would otherwise match nothing, silently. + const excludeGlobs = (options.exclude ?? []).map((glob) => glob.replace(/^(\.\/)+/, '')); + const patterns = excludeGlobs.map(globToRegExp); + const matchedPatterns = new Set(); + const isExcludedName = (name: string): boolean => { + let hit = false; + patterns.forEach((pattern, i) => { + if (pattern.test(name)) { + matchedPatterns.add(i); + hit = true; + } + }); + return hit; + }; + const isExcluded = (path: string): boolean => isExcludedName(rel(dir, path)); + const excluded: string[] = []; + const files = walked.files.filter((file) => { + if (isExcluded(file)) { + excluded.push(rel(dir, file)); + return false; + } + return true; + }); + const bundles = files.filter((f) => BUNDLE.test(f)); + const maps = files.filter((f) => MAP.test(f)); + if (bundles.length === 0) { + add({ + id: 'output.no-js', + severity: 'error', + message: `No .js/.cjs/.mjs files found under ${dir} (node_modules and .git are not searched).`, + fix: 'Point the doctor at the bundler output directory, not the project root or a source tree.', + }); + } + + if (excluded.length > 0) { + add({ + id: 'output.excluded', + severity: 'info', + message: `${excluded.length} file(s) matched --exclude and were not checked (${excluded.slice(0, MAX_LISTED).join(', ')}${excluded.length > MAX_LISTED ? ', …' : ''}).`, + details: listDetails('files', excluded), + }); + } + if (walked.skipped.length > 0) { + add({ + id: 'output.walk-fenced', + severity: 'info', + message: `${walked.skipped.length} director${walked.skipped.length === 1 ? 'y was' : 'ies were'} not searched because ${dir} looks like a project directory (${walked.skipped.slice(0, MAX_LISTED).join(', ')}${walked.skipped.length > MAX_LISTED ? ', …' : ''}).`, + fix: 'To audit them, run the doctor on the build output directory from the project root (not from inside a directory that has a package.json).', + details: listDetails('directories', walked.skipped), + }); + } + + const mapSet = new Set(maps); + // A map reached through two names (a symlinked directory, a case-variant pointer) is the same file: judged once. + const seenMaps = new Set(); + // Relative sources resolve from the map URL's directory, so an alias in another directory has its own verdict. + const seenBases = new Set(); + const emptyMapNotes = new Map(); + const markSeen = (real: string): boolean => { + if (seenMaps.has(real)) { + return false; + } + seenMaps.add(real); + return true; + }; + const contentFacts: Array<{ + file: string; + embeddedAll: boolean; + message: string; + details?: Record; + }> = []; + // A map shared by many bundles is read and parsed once (a few at a time are kept: a build of mostly unique maps + // must not retain them all). + const loadMap = boundedMemo(4, async (path: string) => { + const read = await readInside(path, maxMapBytes, realDir); + return read.ok + ? { ok: true as const, real: read.real, parsed: parseMap(read.bytes.toString('utf8')) } + : read; + }); + const claimedMaps = new Set(); + const stampedIds = new Map>(); + let stamped = 0; + const unstamped = new Set(); + const unstampedWithoutMap: string[] = []; + const noRegistration: string[] = []; + const dangling: string[] = []; + const outsideDir: string[] = []; + const devBundles: string[] = []; + const inline = new Set(); + const hidden: string[] = []; + const unreadable: string[] = []; + + // Reads happen in bounded batches; analysis stays sequential so findings keep a deterministic order. + const reads = new Map(); + const readBatch = async (batch: readonly string[]): Promise => { + const results = await Promise.all( + batch.map((path) => readInside(path, maxBundleBytes, realDir)), + ); + batch.forEach((path, i) => { + reads.set(path, results[i] as InsideRead); + }); + }; + + // What `stat` says each script weighs, to bound the bytes held at once (a failed stat weighs nothing: the read reports it). + const sizes = await Promise.all( + bundles.map((path) => + stat(path).then( + (info) => info.size, + () => 0, + ), + ), + ); + let readEnd = 0; + for (let at = 0; at < bundles.length; at++) { + if (at >= readEnd) { + reads.clear(); + readEnd = batchEnd(sizes, at, READ_CONCURRENCY, READ_BYTE_BUDGET); + await readBatch(bundles.slice(at, readEnd)); + } + const bundle = bundles[at] as string; + const name = rel(dir, bundle); + const read = reads.get(bundle) as InsideRead; + if (!read.ok) { + unreadable.push(`${name} ${read.reason}`); + continue; + } + const code = read.bytes.toString('utf8'); + const id = readDebugId(code); + + if (code.includes('webpack-internal:///')) { + devBundles.push(name); + } + + // Which map belongs to this bundle: the one its pointer names, else the sibling `.map`. + const pointer = lastSourceMappingUrl(code); + let mapPath: string | undefined; + if (pointer !== undefined && pointer !== '') { + if (/^data:/i.test(pointer)) { + inline.add(name); + } else { + // The pairing rule the stamp itself uses (verify-stamp.ts): a LOCAL pointer, resolved from the + // bundle's directory; remote / root-absolute / malformed pointers pair nothing. + const raw = localPointerTarget(bundle, code, nodePath); + // webpack / Rspack write `main.js?[hash]` to disk as `main.js` and keep the query in the pointer + // (`main.js.map?[hash]`): a server drops the query when it maps the URL to a file, so does the doctor + // (a file named with a `?` is not a `.map` file, so it could not have been paired anyway). + const bundleDir = nodePath.dirname(bundle); + const target = + raw === undefined + ? undefined + : nodePath.join(bundleDir, cutAtQuery(nodePath.relative(bundleDir, raw))); + if (target !== undefined) { + if (!isInside(dir, target)) { + // Never read it: a pointer can name `/dev/zero`, a FIFO or someone else's file. + outsideDir.push(`${name} -> ${pointer}`); + } else if (mapSet.has(target)) { + mapPath = target; + } else if (isExcluded(target)) { + // an excluded map is not the build's: neither read nor reported as dangling + } else { + // A symlinked DIRECTORY on the way can lead out although the path looks inside: judge the + // real path, never read through it. + const real = await realpath(target).catch(() => undefined); + if (real === undefined) { + dangling.push(`${name} -> ${pointer}`); + } else if (!isInside(realDir, real)) { + outsideDir.push(`${name} -> ${pointer}`); + } else { + mapPath = target; + } + } + } + } + } + if (mapPath === undefined && mapSet.has(`${bundle}.map`)) { + mapPath = `${bundle}.map`; + if (pointer === undefined) { + hidden.push(name); + } + } + + if (id === undefined) { + unstamped.add(name); + if (mapPath === undefined && !inline.has(name)) { + unstampedWithoutMap.push(name); + } + } else { + stamped++; + const list = stampedIds.get(id) ?? []; + list.push({ file: name, path: bundle }); + stampedIds.set(id, list); + if (!code.includes(REGISTRATION)) { + noRegistration.push(name); + } + } + + if (mapPath !== undefined) { + claimedMaps.add(mapPath); + const mapName = rel(dir, mapPath); + const mapRead = await loadMap(mapPath); + if (!mapRead.ok) { + reportUnreadableMap(mapName, mapRead); + continue; + } + const parsed = mapRead.parsed; + if (!parsed.ok) { + if (markSeen(mapRead.real)) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is ${parsed.why}, so it cannot be uploaded or used to symbolicate.`, + fix: 'Check the build is not truncating or post-processing the map; rebuild.', + }); + } + continue; + } + if (id !== undefined && parsed.debugId === undefined) { + add({ + id: 'stamp.map-no-debug-id', + severity: 'error', + file: mapName, + message: `${mapName} has no debugId, but its bundle ${name} carries ${id}; a crash cannot be matched to this map.`, + fix: 'Stamp the bundle and map together (the Bugsee plugin or `bugsee-cli sourcemaps inject`), and make sure no later step regenerates the map.', + details: { bundleDebugId: id }, + }); + } else if (id !== undefined && parsed.debugId !== undefined && parsed.debugId !== id) { + add({ + id: 'stamp.map-id-mismatch', + severity: 'error', + file: mapName, + message: `${mapName} has debugId ${parsed.debugId} but its bundle ${name} carries ${id}.`, + fix: 'Re-run the stamp over the final files; a minifier or copy step ran after stamping.', + details: { bundleDebugId: id, mapDebugId: parsed.debugId }, + }); + } else if (id === undefined && parsed.debugId !== undefined) { + add({ + id: 'stamp.missing-debug-id', + severity: 'error', + file: name, + message: `${name} has no debugId comment, but its map carries ${parsed.debugId}; the bundle lost its stamp.`, + fix: 'Something rewrote the bundle after stamping. Stamp last, or use the in-build stamping plugin.', + details: { mapDebugId: parsed.debugId }, + }); + // Counted once as unstamped above; do not double report below. + unstamped.delete(name); + } + validateMap(mapPath, mapName, parsed.json, mapRead.real, code); + } + } + + // Maps nothing points at (hidden maps of bundles are claimed above; this is the rest, e.g. css maps). + for (const map of maps) { + if (!claimedMaps.has(map)) { + const mapName = rel(dir, map); + const mapRead = await loadMap(map); + if (!mapRead.ok) { + reportUnreadableMap(mapName, mapRead); + continue; + } + const parsed = mapRead.parsed; + if (!parsed.ok) { + if (markSeen(mapRead.real)) { + add({ + id: 'map.invalid', + severity: 'error', + file: mapName, + message: `${mapName} is ${parsed.why}.`, + fix: 'Check the build is not truncating or post-processing the map; rebuild.', + }); + } + } else { + validateMap(map, mapName, parsed.json, mapRead.real); + } + } + } + + function reportUnreadableMap(mapName: string, read: Extract): void { + if (read.tooLarge !== undefined) { + add({ + id: 'map.too-large', + severity: 'warning', + file: mapName, + message: `${mapName} is ${(read.tooLarge.size / 1024 / 1024).toFixed(1)} MiB (limit applied: ${(maxMapBytes / 1024 / 1024).toFixed(0)} MiB${maxMapBytes === READ_CEILING ? ', the most Node can hold in one string' : ''}), so it was not read or validated; the upload may be slow or rejected.`, + fix: 'Split the bundle, strip sourcesContent (`stripSourcesContent`) or exclude vendor chunks; raise --max-map-mb to validate it (the ceiling is about 512 MiB, the largest string Node can hold).', + details: { bytes: read.tooLarge.size, limit: maxMapBytes }, + }); + } else { + add({ + id: 'map.unreadable', + severity: 'error', + file: mapName, + message: `${mapName} ${read.reason}, so it cannot be validated or uploaded.`, + fix: 'Make it a regular file inside the output directory (no symlink, FIFO or device).', + }); + } + } + + function validateMap( + mapPath: string, + mapName: string, + json: Record, + real: string, + /** The bundle that claims this map, when there is one: an empty map is only right for a facade chunk. */ + bundleCode?: string, + ): void { + // An empty map shared with a bundle that has real code is a stripped map for THAT bundle, whichever claimed it first. + const note = emptyMapNotes.get(real); + if (note !== undefined && bundleCode !== undefined && !isFacadeCode(bundleCode)) { + note.severity = 'error'; + note.message = `${note.file} has no \`sources\`; it can map nothing back to your code.`; + note.fix = 'Enable full source maps in the bundler (not a stripped / empty map).'; + } + const first = markSeen(real); // content and structure are the same for every name of one file + const base = `${real}\0${dirname(mapPath)}`; + if (seenBases.has(base)) { + return; // a map shared by several bundles in one directory is validated once + } + seenBases.add(base); + const invalid = (message: string, fix: string, id = 'map.invalid'): void => { + if (first) { + add({ id, severity: 'error', file: mapName, message, fix }); + } + }; + if (json.version !== 3) { + invalid( + `${mapName} is not a source map v3 (version is ${JSON.stringify(json.version)}).`, + 'Only version 3 maps are supported; check the bundler/minifier output.', + ); + return; + } + if (typeof json.mappings !== 'string' && !Array.isArray(json.sections)) { + invalid( + `${mapName} has neither \`mappings\` nor \`sections\`: it carries no position data, so no frame can be mapped.`, + 'Check the build is not stripping the map; rebuild.', + ); + return; + } + const { sources, content, roots, hasOriginal } = mapSources(json); + if (sources.length === 0 && !hasGeneratedSegments(json) && isFacadeCode(bundleCode ?? '')) { + // A facade / empty chunk (Rollup: `sources: []`, `mappings: ""`): nothing generated, nothing to symbolicate. + if (first) { + const finding: DoctorFinding = { + id: 'map.no-sources', + severity: 'info', + file: mapName, + message: `${mapName} has no sources and no mappings (a facade or empty chunk): there is nothing to map, so nothing to symbolicate.`, + }; + add(finding); + emptyMapNotes.set(real, finding); // upgraded to an error if a bundle with real code claims it too + } + return; + } + if (sources.length === 0) { + invalid( + `${mapName} has no \`sources\`; it can map nothing back to your code.`, + 'Enable full source maps in the bundler (not a stripped / empty map).', + 'map.no-sources', + ); + return; + } + if (!hasOriginal) { + invalid( + `${mapName} has no mapping to an original position (its \`mappings\` is empty or holds only generated positions), so no frame can be mapped back to your code.`, + 'Check the build is not stripping the map or minifying without tracking sources; rebuild.', + ); + return; + } + const missingAt = sources.flatMap((_, i) => (typeof content[i] !== 'string' ? [i] : [])); + const missing = missingAt.map((i) => String(sources[i])); + if (missing.length === 0) { + if (first) { + contentFacts.push({ + file: mapName, + embeddedAll: true, + message: `${mapName} embeds sourcesContent for all ${sources.length} sources.`, + }); + } + return; + } + const mapDir = dirname(mapPath); + const unresolved = missingAt.flatMap((i) => { + const path = sourcePath(mapDir, roots[i] as string, String(sources[i]), projectRoot); + return path !== undefined && !existsSync(path) ? [String(sources[i])] : []; + }); + if (unresolved.length > 0) { + add({ + id: 'map.sources-unresolvable', + severity: 'warning', + file: mapName, + message: `${mapName} embeds no sourcesContent for ${unresolved.length} of ${sources.length} sources and they are not on disk (${unresolved.slice(0, MAX_LISTED).join(', ')}${unresolved.length > MAX_LISTED ? ', …' : ''}); frames will show names but no source lines.`, + fix: 'Build with sourcesContent embedded (inlineSources / `sourcesContent: true`), or upload from a machine that still has the sources.', + details: { unresolved: unresolved.length, total: sources.length }, + }); + } else if (first) { + contentFacts.push({ + file: mapName, + embeddedAll: false, + message: `${mapName} does not embed sourcesContent for ${missing.length} sources, but they are resolvable on disk.`, + details: { embedded: sources.length - missing.length, total: sources.length }, + }); + } + } + + // --- aggregate findings ------------------------------------------------------------------------- + // One note per map is useful for a handful of maps and noise for thousands (a 20k-bundle build was 3.6 MB of JSON). + if (contentFacts.length <= MAX_LISTED * 2) { + for (const fact of contentFacts) { + findings.push({ + id: 'map.sources-content', + severity: 'info', + file: fact.file, + message: fact.message, + ...(fact.details !== undefined ? { details: fact.details } : {}), + }); + } + } else { + const embedded = contentFacts.filter((f) => f.embeddedAll).length; + findings.push({ + id: 'map.sources-content', + severity: 'info', + message: `${contentFacts.length} maps carry no sourcesContent problem: ${embedded} embed it for all sources, ${contentFacts.length - embedded} do not but their sources are resolvable on disk.`, + details: { + maps: contentFacts.length, + embedded, + resolvableOnDisk: contentFacts.length - embedded, + }, + }); + } + const withoutMap = new Set(unstampedWithoutMap); + if (bundles.length > 0 && unreadable.length === bundles.length) { + // Nothing was audited: that must not be ignorable into a pass (`--ignore output.unreadable`). + add({ + id: 'output.no-js', + severity: 'error', + message: `None of the ${bundles.length} script(s) under ${dir} could be read, so nothing was checked.`, + fix: 'Make the scripts regular files that the current user can read, and run the doctor again.', + }); + } + if (unreadable.length > 0) { + add({ + id: 'output.unreadable', + severity: 'error', + message: `${unreadable.length} script(s) could not be read (${unreadable.slice(0, MAX_LISTED).join('; ')}${unreadable.length > MAX_LISTED ? '; …' : ''}); they were not checked.`, + fix: 'Make them regular files under the size limit, or exclude them from the output directory.', + details: listDetails('files', unreadable), + }); + } + for (const name of unstamped) { + if (!withoutMap.has(name)) { + add({ + id: 'stamp.missing-debug-id', + severity: 'error', + file: name, + message: `${name} has no debugId comment: crashes from it cannot be matched to a source map.`, + fix: 'Add the Bugsee plugin (it stamps inside the build) or run `bugsee-cli sourcemaps inject

` after the build.', + }); + } + } + if (unstampedWithoutMap.length > 0) { + add({ + id: 'stamp.missing-debug-id', + severity: 'warning', + message: `${unstampedWithoutMap.length} bundle(s) are not stamped and have no map on disk (${unstampedWithoutMap.slice(0, MAX_LISTED).join(', ')}${unstampedWithoutMap.length > MAX_LISTED ? ', …' : ''}); they will not symbolicate.`, + fix: 'Emit source maps and stamp the build; ignore for vendor files you do not want symbolicated.', + details: listDetails('files', unstampedWithoutMap), + }); + } + if (noRegistration.length > 0) { + add({ + id: 'stamp.missing-registration', + severity: 'error', + message: `${noRegistration.length} bundle(s) have a debugId comment but no ${REGISTRATION} registration (${noRegistration.slice(0, MAX_LISTED).join(', ')}); the runtime cannot report the id with a crash.`, + fix: 'Re-stamp with `bugsee-cli sourcemaps inject` (it appends the registration); a hand-added comment is not enough.', + details: listDetails('files', noRegistration), + }); + } + if (stamped > 0 && unstamped.size > 0) { + add({ + id: 'stamp.mixed', + severity: 'warning', + message: `${stamped} bundle(s) are stamped but ${unstamped.size} are not (${[...unstamped].slice(0, MAX_LISTED).join(', ')}${unstamped.size > MAX_LISTED ? ', …' : ''}): a partial stamp usually means a second build output or a late-emitted file was missed.`, + fix: 'Run the stamp over the whole output directory after the last emit step.', + details: { stamped, unstamped: unstamped.size }, + }); + } + for (const [id, entries] of stampedIds) { + if (entries.length < 2) { + continue; // hashing is only worth it for an id that appears more than once + } + const hashes = new Set(); + for (const entry of entries) { + const read = await readInside(entry.path, maxBundleBytes, realDir); + hashes.add(read.ok ? sha(read.bytes) : `unreadable:${entry.path}`); + } + if (hashes.size > 1) { + add({ + id: 'stamp.duplicate-debug-id', + severity: 'error', + message: `debugId ${id} appears on ${entries.length} bundles with different contents (${entries.map((e) => e.file).join(', ')}); one will symbolicate with the other's map.`, + fix: 'Strip the old stamps and re-stamp (a copied or cached stamped file was edited), or clean the output dir before building.', + details: { debugId: id, files: entries.map((e) => e.file) }, + }); + } + } + if (dangling.length > 0) { + // No map file anywhere and every bundle stamped: the maps were removed on purpose (the plugin's + // `deleteMaps` after a confirmed upload), so the leftover comment is a note, not a defect to fail on. + const removedOnPurpose = maps.length === 0 && unstamped.size === 0; + add({ + id: 'map.pointer-dangling', + severity: removedOnPurpose ? 'info' : 'warning', + message: `${dangling.length} bundle(s) point at a source map that is not on disk (${dangling.slice(0, MAX_LISTED).join(', ')}${dangling.length > MAX_LISTED ? ', …' : ''}); browsers request it and get a 404${removedOnPurpose ? ' (harmless for symbolication: the maps were removed and the bundles are stamped)' : ''}.`, + fix: 'Emit hidden source maps (sourcemap: "hidden") so no pointer is written, or keep the maps until deploy.', + details: listDetails('pointers', dangling), + }); + } + if (outsideDir.length > 0) { + add({ + id: 'map.pointer-outside-dir', + severity: 'warning', + message: `${outsideDir.length} bundle(s) point at a source map outside ${dir} (${outsideDir.slice(0, MAX_LISTED).join(', ')}${outsideDir.length > MAX_LISTED ? ', …' : ''}); it was not read and cannot be paired.`, + fix: 'Emit the map inside the output directory, or check the sourceMappingURL.', + details: listDetails('pointers', outsideDir), + }); + } + if (hidden.length > 0) { + findings.push({ + id: 'map.hidden', + severity: 'info', + message: `${hidden.length} bundle(s) have a map but no sourceMappingURL comment (hidden maps): good for privacy.`, + details: listDetails('files', hidden), + }); + } + if (inline.size > 0) { + add({ + id: 'map.inline', + severity: 'error', + message: `${inline.size} bundle(s) carry an inline (data:) source map (${[...inline].slice(0, MAX_LISTED).join(', ')}); there is no .map file to upload and the map ships to every visitor.`, + fix: 'Switch to external hidden maps (Vite `build.sourcemap: "hidden"`, webpack `devtool: "hidden-source-map"`, esbuild `sourcemap: "external"`).', + details: listDetails('files', [...inline]), + }); + } + if (devBundles.length > 0) { + add({ + id: 'build.dev-bundle', + severity: 'warning', + message: `${devBundles.length} bundle(s) look like a development build (webpack eval-style sourceURL markers: ${devBundles.slice(0, MAX_LISTED).join(', ')}); eval maps are not uploadable and bundles are unminified.`, + fix: 'Build in production mode (mode: "production", NODE_ENV=production) before uploading.', + details: listDetails('files', devBundles), + }); + } + if (maps.length > 0) { + add({ + id: 'map.public-leftover', + severity: options.deployed === true ? 'warning' : 'info', + message: `${maps.length} .map file(s) are on disk in ${dir}; if this directory is deployed they are served publicly and expose your source.`, + fix: 'Keep `deleteMaps` on (default) so maps are removed after a confirmed upload, or emit hidden maps and exclude *.map from deploys. Run with --deployed on the directory you actually serve to make this a warning.', + details: { count: maps.length, files: maps.slice(0, MAX_LISTED).map((m) => rel(dir, m)) }, + }); + } + + // --- SRI ------------------------------------------------------------------------------------------ + // A page named by `--exclude` is skipped BEFORE it is read: it contributes no pins (and cannot claim one first). + const sriScan = await findSriProtectedScriptsDetailed( + dir, + MAX_HTML_BYTES, + walked.fenced, + isExcluded, + ); + const allUnreadable = [ + ...new Set([...walked.unreadable, ...sriScan.unreadableDirs.map((d) => rel(dir, d) || '.')]), + ].sort(); + // `--exclude vendor/**` (or `vendor/`) names a directory too. + // Excluded only if the patterns would hide EVERY kind of file the doctor looks at inside it (a probe of each, deep + // down, plus one no extension glob can target): never broader than for a readable directory. + const excludedDirs = allUnreadable.filter((d) => + DIR_PROBES.every((probe) => isExcludedName(`${d}/${probe}`)), + ); + const unreadableDirs = allUnreadable.filter((d) => !excludedDirs.includes(d)); + if (excludedDirs.length > 0) { + add({ + id: 'output.excluded', + severity: 'info', + message: `${excludedDirs.length} unreadable director${excludedDirs.length === 1 ? 'y' : 'ies'} matched --exclude and ${excludedDirs.length === 1 ? 'was' : 'were'} not checked (${excludedDirs.slice(0, MAX_LISTED).join(', ')}${excludedDirs.length > MAX_LISTED ? ', …' : ''}).`, + details: listDetails('directories', excludedDirs), + }); + } + if (unreadableDirs.length > 0) { + // Scripts, maps and pages in them were NOT checked: a pass would be false. + add({ + id: 'output.dir-unreadable', + severity: 'error', + message: `${unreadableDirs.length} director${unreadableDirs.length === 1 ? 'y' : 'ies'} could not be listed (unreadable, or a symlink that leaves the output directory), so nothing in ${unreadableDirs.length === 1 ? 'it was' : 'them was'} checked (${unreadableDirs.slice(0, MAX_LISTED).join(', ')}${unreadableDirs.length > MAX_LISTED ? ', …' : ''}).`, + fix: 'Make the directories readable by the user running the doctor (a build run as root in a container, then checked as another user, is the usual cause) and run it again.', + details: listDetails('directories', unreadableDirs), + }); + } + const pinned = sriScan.scripts.filter((pin) => !isExcluded(pin.script)); + const unmatched = excludeGlobs.filter((_, i) => !matchedPatterns.has(i)); + if (unmatched.length > 0) { + add({ + id: 'output.exclude-unmatched', + severity: 'info', + message: `${unmatched.length} --exclude pattern(s) matched no file (${unmatched.join(', ')}); patterns are relative to ${dir} (Vite copies publicDir to its ROOT: write sw.js, not public/sw.js).`, + details: { patterns: unmatched }, + }); + } + if (sriScan.skippedPages.length > 0) { + const names = sriScan.skippedPages.map((page) => rel(dir, page.html)); + add({ + id: 'sri.html-skipped', + severity: 'warning', + message: `${names.length} page(s) are larger than ${MAX_HTML_BYTES / 1024 / 1024} MiB and were not scanned for integrity pins (${names.slice(0, MAX_LISTED).join(', ')}${names.length > MAX_LISTED ? ', …' : ''}); a script they pin would not be noticed.`, + fix: 'A real page is a few KB; check that this is not a data file named .html. Stamping still sees pins in such a page.', + details: listDetails('files', names), + }); + } + if (sriScan.unreadablePages.length > 0) { + const names = sriScan.unreadablePages.map((page) => rel(dir, page)); + add({ + id: 'sri.html-skipped', + severity: 'warning', + message: `${names.length} page(s) could not be read and were not scanned for integrity pins (${names.slice(0, MAX_LISTED).join(', ')}${names.length > MAX_LISTED ? ', …' : ''}); a script they pin would not be noticed.`, + fix: 'Make the pages readable and run the doctor again.', + details: listDetails('files', names), + }); + } + if (pinned.length > 0) { + const unstampedPinned: typeof pinned = []; + const mismatches: typeof pinned = []; + const pinsUnread: string[] = []; + for (const p of pinned) { + // The same guarded reader as every other read (symlinks resolved only if they stay inside the directory, + // regular files of bounded size only). The bytes read here are also what the integrity check judges. + const read = await readInside(p.script, maxBundleBytes, realDir); + if (!read.ok) { + // A pin to a file that is not there is stale, not something stamping would break; anything else (it + // leads outside, is a FIFO, is too large) is a pin we could not judge, and that is said. + if (!read.reason.includes('(ENOENT)')) { + pinsUnread.push(`${rel(dir, p.script)} ${read.reason}`); + } + continue; + } + if (!passesIntegrity(p.integrity, read.bytes)) { + mismatches.push(p); + } + if (readDebugId(read.bytes.toString('utf8')) === undefined) { + unstampedPinned.push(p); + } + } + if (pinsUnread.length > 0) { + add({ + id: 'sri.pin-unreadable', + severity: 'warning', + message: `${pinsUnread.length} script(s) pinned by an integrity hash could not be checked (${pinsUnread.slice(0, MAX_LISTED).join('; ')}${pinsUnread.length > MAX_LISTED ? '; …' : ''}).`, + fix: 'Make the pinned scripts regular files inside the output directory.', + details: listDetails('scripts', pinsUnread), + }); + } + if (unstampedPinned.length > 0) { + add({ + id: 'sri.unstamped-hazard', + severity: 'warning', + message: `${unstampedPinned.length} script(s) are pinned by an integrity hash in ${rel(dir, unstampedPinned[0]?.html ?? dir)} and are not stamped; stamping them AFTER the page was written would make the browser block them.`, + fix: 'Use the Bugsee plugin (stamps before the SRI plugin hashes; list it first), or re-generate the integrity hashes after `sourcemaps inject`.', + details: { scripts: unstampedPinned.map((p) => rel(dir, p.script)) }, + }); + } + if (mismatches.length > 0) { + add({ + id: 'sri.mismatch', + severity: 'error', + message: `${mismatches.length} script(s) no longer match the integrity hash pinning them (${mismatches + .slice(0, MAX_LISTED) + .map((m) => rel(dir, m.script)) + .join(', ')}); the browser refuses to run them and the page loads nothing.`, + fix: 'Something rewrote the files after the hashes were computed (usually a post-build stamp). Stamp first, hash last.', + details: { scripts: mismatches.map((m) => rel(dir, m.script)) }, + }); + } + } + const manifests = await manifestsWithIntegrity(dir, maxMapBytes, realDir); + if (manifests.length > 0) { + const names = manifests.map((p) => rel(dir, p)); + add({ + id: 'sri.manifest-hashes', + severity: 'warning', + message: `${names.join(', ')} mention integrity hashes the doctor cannot tie to a script; if they pin these bundles, stamping them afterwards breaks the page.`, + fix: 'Check whether the manifest pins hashes of these files; if so make stamping happen before they are computed, or regenerate them. (A page outside this directory is not read: run the doctor on the directory that holds it.)', + details: { files: names }, + }); + } + + // --- environment ---------------------------------------------------------------------------------- + if (options.skipEnv !== true) { + const root = projectRoot; + const fromFile = loadBuildPluginEnv(root); + const merged = mergeBuildPluginEnv(env, fromFile.values); + const optionToken = options.appToken?.trim() ?? ''; + const envToken = merged.BUGSEE_APP_TOKEN?.trim() ?? ''; + if (optionToken === '' && envToken === '') { + add({ + id: 'env.token-missing', + severity: 'warning', + message: + 'No Bugsee app token is resolvable (BUGSEE_APP_TOKEN, .env.bugsee-build-plugin, or the appToken option): the bundler plugin is disabled and uploads nothing (fine if you upload with bugsee-cli by hand).' + + (fromFile.problem !== undefined ? ` ${fromFile.problem}` : ''), + fix: 'Set BUGSEE_APP_TOKEN in the build environment or in .env.bugsee-build-plugin next to your project.', + }); + } else { + // Where it came from, never the value: the same precedence the plugin applies (option, env, file). + const source = + optionToken !== '' + ? ('option' as const) + : (env.BUGSEE_APP_TOKEN?.trim() ?? '') !== '' + ? ('env' as const) + : ('env-file' as const); + const label = { + option: 'the appToken option', + env: 'the BUGSEE_APP_TOKEN environment variable', + 'env-file': '.env.bugsee-build-plugin', + }[source]; + findings.push({ + id: 'env.token-source', + severity: 'info', + message: `The app token comes from ${label}.`, + details: { source }, + }); + } + const identity = findAppIdentity( + { appVersion: options.appVersion, appBuild: options.appBuild }, + merged, + {}, + root, + ); + if (identity.version === undefined) { + add({ + id: 'env.version-unresolved', + severity: 'warning', + message: `No app version is resolvable (BUGSEE_APP_VERSION or a package.json version at or above ${root}); the upload is labelled 0.0.0.`, + fix: 'Set BUGSEE_APP_VERSION, or pass --project-root to the directory holding package.json.', + }); + } + if (identity.build === undefined) { + add({ + id: 'env.build-unresolved', + severity: 'info', + message: + 'No app build id is resolvable (BUGSEE_APP_BUILD or a CI commit variable); the build is labelled 0.', + fix: 'Set BUGSEE_APP_BUILD (e.g. the commit SHA) so builds can be told apart.', + }); + } + if (merged.NODE_ENV === 'development') { + add({ + id: 'env.node-env-development', + severity: 'warning', + message: + 'NODE_ENV is "development": the Bugsee plugins skip the upload for development builds (unless uploadInDevelopment is set).', + fix: 'Build with NODE_ENV=production for the build you deploy.', + }); + } + } + + // A check with no input did not run: no scripts means no stamp / pointer checks, no maps no map-content checks. + const needsBundles = (id: string): boolean => id.startsWith('stamp.') || NEEDS_BUNDLES.has(id); + const passed = DOCTOR_CHECK_IDS.filter( + (id) => + !failed.has(id) && + !INFO_ONLY.has(id) && + !(options.skipEnv === true && id.startsWith('env.')) && + !(bundles.length === 0 && needsBundles(id)) && + !(maps.length === 0 && NEEDS_MAPS.has(id)), + ); + return finish(dir, findings, bundles.length, maps.length, passed, options.ignore); +} + +const NEEDS_BUNDLES: ReadonlySet = new Set([ + 'build.dev-bundle', + 'map.pointer-dangling', + 'map.pointer-outside-dir', + 'map.inline', +]); +const NEEDS_MAPS: ReadonlySet = new Set([ + 'map.invalid', + 'map.no-sources', + 'map.sources-unresolvable', + 'map.too-large', + 'map.unreadable', +]); + +/** Checks that only ever produce an `info` finding: they are not "passed", they are facts. */ +const INFO_ONLY: ReadonlySet = new Set([ + 'output.excluded', + 'output.exclude-unmatched', + 'output.walk-fenced', + 'map.hidden', + 'map.sources-content', + 'env.token-source', + 'doctor.internal-error', +]); + +function finish( + dir: string, + findings: DoctorFinding[], + bundles: number, + maps: number, + passed: readonly string[], + ignore: readonly string[] = [], +): DoctorReport { + ignore = ignore.filter((id) => !NON_IGNORABLE_CHECK_IDS.has(id)); + const dropped = ignore.filter((id) => findings.some((f) => f.id === id)); + if (dropped.length > 0) { + findings = findings.filter((f) => !ignore.includes(f.id)); + } + const count = (severity: DoctorSeverity): number => + findings.filter((f) => f.severity === severity).length; + return { + schemaVersion: DOCTOR_SCHEMA_VERSION, + tool: 'bugsee-sourcemaps-doctor', + dir, + summary: { + errors: count('error'), + warnings: count('warning'), + infos: count('info'), + bundles, + maps, + }, + passed: passed.filter((id) => !ignore.includes(id)), + findings, + ...(dropped.length > 0 ? { ignored: [...new Set(dropped)] } : {}), + }; +} + +/** 0 clean, 2 errors, 1 warnings only under `strict`. */ +export function doctorExitCode(report: DoctorReport, strict = false): 0 | 1 | 2 { + if (report.summary.errors > 0) { + return 2; + } + return strict && report.summary.warnings > 0 ? 1 : 0; +} + +const MARK: Record = { + error: 'ERROR ', + warning: 'WARN ', + info: 'info ', +}; + +/** The human rendering. Stable enough to read; machines should use the JSON report. */ +export function formatDoctorReport(report: DoctorReport): string { + const lines = [ + `Bugsee source-map doctor: ${report.dir}`, + `${report.summary.bundles} bundle(s), ${report.summary.maps} map(s): ${report.summary.errors} error(s), ${report.summary.warnings} warning(s), ${report.summary.infos} note(s)`, + '', + ]; + const order: DoctorSeverity[] = ['error', 'warning', 'info']; + for (const severity of order) { + for (const finding of report.findings.filter((f) => f.severity === severity)) { + lines.push(`${MARK[severity]}[${finding.id}] ${finding.message}`); + if (finding.fix !== undefined) { + lines.push(` fix: ${finding.fix}`); + } + } + } + if (report.findings.length === 0) { + lines.push('No problems found.'); + } + return lines.join('\n'); +} diff --git a/packages/bundler-plugin-core/src/facade.ts b/packages/bundler-plugin-core/src/facade.ts new file mode 100644 index 00000000..a16a393d --- /dev/null +++ b/packages/bundler-plugin-core/src/facade.ts @@ -0,0 +1,260 @@ +// Is a bundle a FACADE: no code of its own, only imports and re-exports? Rollup writes `sources: []` and an empty +// `mappings` for such a chunk (a barrel `export { a } from './main.js'`, an empty chunk), and that empty map is correct. +// A chunk with real code and an empty map is a stripped one, so the doctor has to tell the two apart by reading the +// bundle: parsed (acorn), and every top-level statement checked against the small language a facade is written in. +import { parse } from 'acorn'; + +/** The global the runtime stub writes the id into: the stamp's registration line carries it. */ +const REGISTRATION = '_bugseeDebugIds'; + +type Node = { type: string } & Record; +const isNode = (value: unknown): value is Node => + typeof value === 'object' && value !== null && typeof (value as Node).type === 'string'; +const node = (parent: Node, key: string): Node | undefined => { + const child = parent[key]; + return isNode(child) ? child : undefined; +}; +const nodes = (parent: Node, key: string): Node[] => { + const list = parent[key]; + return Array.isArray(list) ? list.filter(isNode) : []; +}; +const name = (n: Node | undefined): string | undefined => + n?.type === 'Identifier' ? (n.name as string) : undefined; +const literalString = (n: Node | undefined): boolean => + n?.type === 'Literal' && typeof n.value === 'string'; + +/** Rollup's interop helpers: `_interopDefault`, `_interopNamespaceDefault`, `_interopNamespace`, ... */ +const HELPER_NAME = /^_interop[A-Za-z]*$/; +/** `Object.(...)` calls a re-export block makes. */ +// (a regular expression, not a list of strings: the wire-name drift test reads string literals in product code) +const OBJECT_CALL = /^(?:keys|defineProperty|getOwnPropertyDescriptor|create|freeze)$/; + +/** `Object.prototype.hasOwnProperty.call`, as Rollup's `export *` loop writes it. */ +function isHasOwnCall(callee: Node): boolean { + const target = node(callee, 'object'); + const proto = target && node(target, 'object'); + return ( + name(node(callee, 'property')) === 'call' && + target?.type === 'MemberExpression' && + name(node(target, 'property')) === 'hasOwnProperty' && + proto?.type === 'MemberExpression' && + name(node(proto, 'object')) === 'Object' && + name(node(proto, 'property')) === 'prototype' + ); +} + +const isFunction = (n: Node): boolean => + n.type === 'FunctionExpression' || n.type === 'ArrowFunctionExpression'; + +/** A function Rollup writes into a re-export block: plain parameters and a body of re-export statements. */ +function pureFunction(fn: Node): boolean { + if (!nodes(fn, 'params').every((param) => param.type === 'Identifier')) { + return false; + } + const body = node(fn, 'body') as Node; // a function always has a body + return body.type === 'BlockStatement' + ? nodes(body, 'body').every(pureStatement) + : pureExpression(body); +} + +function pureCall(call: Node): boolean { + const callee = node(call, 'callee'); + const args = nodes(call, 'arguments'); + if (callee === undefined) { + return false; + } + const calleeName = name(callee); + if (calleeName === 'require') { + return args.length === 1 && literalString(args[0]); + } + if (calleeName !== undefined) { + return HELPER_NAME.test(calleeName) && args.every(pureExpression); + } + if (callee.type !== 'MemberExpression' || callee.computed === true) { + return false; + } + const property = name(node(callee, 'property')); + if ( + name(node(callee, 'object')) === 'Object' && + property !== undefined && + OBJECT_CALL.test(property) + ) { + return args.every(pureExpression); + } + if (isHasOwnCall(callee)) { + return args.every(pureExpression); + } + if (property === 'forEach') { + const target = node(callee, 'object'); + const callback = args[0]; + return ( + target !== undefined && + pureExpression(target) && + args.length === 1 && + callback !== undefined && + isFunction(callback) && + pureFunction(callback) + ); + } + return false; +} + +/** The expressions a re-export is written with: references, literals, whitelisted calls, getters. */ +function pureExpression(maybe: Node | undefined): boolean { + const expression = maybe as Node; // the grammar guarantees the children asked for; `undefined` falls to `default` + switch (expression?.type) { + case 'Identifier': + case 'Literal': + return true; + case 'MemberExpression': + return ( + pureExpression(node(expression, 'object')) && + (expression.computed !== true || pureExpression(node(expression, 'property'))) + ); + case 'UnaryExpression': + return pureExpression(node(expression, 'argument')); + case 'BinaryExpression': + case 'LogicalExpression': + return pureExpression(node(expression, 'left')) && pureExpression(node(expression, 'right')); + case 'ConditionalExpression': + return ( + pureExpression(node(expression, 'test')) && + pureExpression(node(expression, 'consequent')) && + pureExpression(node(expression, 'alternate')) + ); + case 'AssignmentExpression': + return ( + expression.operator === '=' && + pureExpression(node(expression, 'left')) && + pureExpression(node(expression, 'right')) + ); + case 'ObjectExpression': + return nodes(expression, 'properties').every((property) => { + const value = node(property, 'value'); + const isGetter = + name(node(property, 'key')) === 'get' && + value !== undefined && + isFunction(value) && + pureFunction(value); + return property.type === 'Property' && (isGetter || pureExpression(value)); + }); + case 'CallExpression': + return pureCall(expression); + default: + return false; + } +} + +function pureStatement(statement: Node): boolean { + switch (statement.type) { + case 'ExpressionStatement': + return pureExpression(node(statement, 'expression')); + case 'ReturnStatement': + return statement.argument === null || pureExpression(node(statement, 'argument')); + case 'IfStatement': { + const consequent = node(statement, 'consequent'); + const alternate = node(statement, 'alternate'); + return ( + pureExpression(node(statement, 'test')) && + consequent !== undefined && + pureStatement(consequent) && + (alternate === undefined || pureStatement(alternate)) + ); + } + case 'ForInStatement': { + // Rollup's es2015 interop helper: `for (const k in e) { ... }`; the left side is a plain binding, never a pattern + const left = node(statement, 'left') as Node; + const isBinding = + left.type === 'Identifier' || + (left.type === 'VariableDeclaration' && + nodes(left, 'declarations').every( + (declarator) => node(declarator, 'id')?.type === 'Identifier', + )); + return ( + isBinding && + pureExpression(node(statement, 'right')) && + pureStatement(node(statement, 'body') as Node) + ); + } + case 'BlockStatement': + return nodes(statement, 'body').every(pureStatement); + case 'VariableDeclaration': + return nodes(statement, 'declarations').every( + (declarator) => + node(declarator, 'id')?.type === 'Identifier' && pureExpression(node(declarator, 'init')), + ); + default: + return false; + } +} + +/** One top-level statement of a facade. */ +function facadeStatement(statement: Node): boolean { + switch (statement.type) { + case 'ImportDeclaration': + case 'ExportAllDeclaration': + return true; + case 'ExportNamedDeclaration': + return statement.declaration === null; // `export { a }` / `export { a } from '...'`, not `export function f(){}` + case 'ExpressionStatement': { + // a directive, or an assignment / call of the re-export language: never a bare reference or literal + const expression = node(statement, 'expression'); + return ( + statement.directive !== undefined || + ((expression?.type === 'AssignmentExpression' || expression?.type === 'CallExpression') && + pureExpression(expression)) + ); + } + case 'VariableDeclaration': + // `var main = require('./main.js')` / `var ns = _interopNamespaceDefault(x)`: a call, never a value of its own; + // or `const _interopDefault = e => ...`, a helper function bound to its fixed name + return nodes(statement, 'declarations').every((declarator) => { + const init = node(declarator, 'init'); + const binding = name(node(declarator, 'id')); + return ( + binding !== undefined && + init !== undefined && + (pureCall(init) || (HELPER_NAME.test(binding) && isFunction(init) && pureFunction(init))) + ); + }); + case 'FunctionDeclaration': + return HELPER_NAME.test(name(node(statement, 'id')) ?? '') && pureFunction(statement); + default: + return false; + } +} + +/** + * Whether a bundle holds no code of its own: only imports and re-exports (ESM, or Rollup's CommonJS shape with its + * `export *` loop and interop helpers), plus the Bugsee registration the stamp appended: ONE trailing line carrying the + * marker, accepted only when the stamp's `//# debugId=` comment follows it. A marker earlier in the file is the + * bundle's own code (an SDK reads `_bugseeDebugIds`), so it stays. Anything it cannot read, or that does something + * (a function, a call, a declaration), is real code, and an empty map for it is a stripped one. + */ +export function isFacadeCode(code: string): boolean { + const lines = code.split('\n'); + let sawDebugId = false; + let removedStub = false; + for (let last = lines.at(-1); last !== undefined; last = lines.at(-1)) { + const text = last.trim(); + if (text.startsWith('//')) { + sawDebugId ||= text.startsWith('//# debugId='); + } else if (text !== '') { + if (!(sawDebugId && !removedStub && text.includes(REGISTRATION))) { + break; + } + removedStub = true; // the one registration line the stamp appended + } + lines.pop(); + } + let program: Node; + try { + program = parse(lines.join('\n'), { + ecmaVersion: 'latest', + sourceType: 'module', + }) as unknown as Node; + } catch { + return false; // unreadable: not a facade + } + return nodes(program, 'body').every(facadeStatement); +} diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts index 3d4be951..0f624d75 100644 --- a/packages/bundler-plugin-core/src/index.ts +++ b/packages/bundler-plugin-core/src/index.ts @@ -10,6 +10,18 @@ export { findPackageVersion, } from './app-identity'; export { deriveBuildUuid } from './build-id'; +export { + DOCTOR_CHECK_IDS, + DOCTOR_SCHEMA_VERSION, + type DoctorCheckId, + type DoctorFinding, + type DoctorOptions, + type DoctorReport, + type DoctorSeverity, + diagnoseBuildOutput, + doctorExitCode, + formatDoctorReport, +} from './doctor'; export { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; export { defaultDeleteMapFiles, diff --git a/packages/bundler-plugin-core/src/safe-read.test.ts b/packages/bundler-plugin-core/src/safe-read.test.ts new file mode 100644 index 00000000..bd0ae4d5 --- /dev/null +++ b/packages/bundler-plugin-core/src/safe-read.test.ts @@ -0,0 +1,92 @@ +import { constants as bufferConstants } from 'node:buffer'; +import { spawnSync } from 'node:child_process'; +import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { READ_CEILING, readRegularFile } from './safe-read'; + +let dir: string; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'bugsee-safe-read-')); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('readRegularFile ceiling (the largest string Node can build)', () => { + it('a limit above the ceiling is clamped to it: a bigger file is "too large", not a later decode failure', async () => { + writeFileSync(join(dir, 'a'), 'hello'); + // an injected small ceiling stands in for buffer.constants.MAX_STRING_LENGTH (a 512 MiB file cannot be made here) + expect(await readRegularFile(join(dir, 'a'), Number.POSITIVE_INFINITY, 4)).toEqual({ + ok: false, + reason: 'is too large to read', + tooLarge: { size: 5 }, + }); + expect((await readRegularFile(join(dir, 'a'), 1000, 5)).ok).toBe(true); // equal to the ceiling reads + expect((await readRegularFile(join(dir, 'a'), 4, 1000)).ok).toBe(false); // the caller's lower limit still applies + expect((await readRegularFile(join(dir, 'a'), Number.POSITIVE_INFINITY)).ok).toBe(true); + expect(READ_CEILING).toBe(bufferConstants.MAX_STRING_LENGTH); // the default really is the string limit + }); +}); + +describe('readRegularFile', () => { + it('reads a regular file, including an empty one', async () => { + writeFileSync(join(dir, 'a'), 'hello'); + writeFileSync(join(dir, 'empty'), ''); + const read = await readRegularFile(join(dir, 'a'), 100); + expect(read.ok && read.bytes.toString()).toBe('hello'); + const empty = await readRegularFile(join(dir, 'empty'), 100); + expect(empty.ok && empty.bytes.length).toBe(0); + }); + + it('the limit is exact: equal reads, one over is too large (judged by the size, before reading)', async () => { + writeFileSync(join(dir, 'a'), 'hello'); + expect((await readRegularFile(join(dir, 'a'), 5)).ok).toBe(true); + expect(await readRegularFile(join(dir, 'a'), 4)).toEqual({ + ok: false, + reason: 'is too large to read', + tooLarge: { size: 5 }, + }); + }); + + it('a symlink in the last component is refused, not followed', async () => { + writeFileSync(join(dir, 'real'), 'x'); + symlinkSync(join(dir, 'real'), join(dir, 'link')); + expect(await readRegularFile(join(dir, 'link'), 100)).toEqual({ + ok: false, + reason: 'is a symbolic link', + }); + }); + + it('a FIFO is refused without blocking; a device is refused without reading', async () => { + if (spawnSync('mkfifo', [join(dir, 'pipe')]).status === 0) { + expect(await readRegularFile(join(dir, 'pipe'), 100)).toEqual({ + ok: false, + reason: 'is not a regular file', + }); + } + expect(await readRegularFile('/dev/zero', 100)).toEqual({ + ok: false, + reason: 'is not a regular file', + }); + }, 10_000); + + it('a directory is not a regular file; a missing or unreadable file is a value, not a throw', async () => { + mkdirSync(join(dir, 'd')); + expect(await readRegularFile(join(dir, 'd'), 100)).toEqual({ + ok: false, + reason: 'is not a regular file', + }); + expect(await readRegularFile(join(dir, 'missing'), 100)).toEqual({ + ok: false, + reason: 'could not be read (ENOENT)', + }); + if (process.getuid?.() !== 0) { + writeFileSync(join(dir, 'locked'), 'x'); + chmodSync(join(dir, 'locked'), 0o000); + expect(await readRegularFile(join(dir, 'locked'), 100)).toEqual({ + ok: false, + reason: 'could not be read (EACCES)', + }); + } + }); +}); diff --git a/packages/bundler-plugin-core/src/safe-read.ts b/packages/bundler-plugin-core/src/safe-read.ts new file mode 100644 index 00000000..f3780a6f --- /dev/null +++ b/packages/bundler-plugin-core/src/safe-read.ts @@ -0,0 +1,80 @@ +// Bounded, race-resistant reads of build-output files. +// +// A path in a build output is untrusted input to a diagnostic: it can be a FIFO (opening it blocks for ever), a +// device (`/dev/zero` never ends), a symlink out of the tree, or a file that is swapped between a check and the +// read. So the file is OPENED first (without following a symlink in the last component, and without blocking on a +// FIFO), and every judgement (regular file? how big?) is made on the open descriptor, not on the path. +import { constants as bufferConstants } from 'node:buffer'; +import { constants } from 'node:fs'; +import { open } from 'node:fs/promises'; + +export type ReadResult = + | { ok: true; bytes: Buffer } + | { ok: false; reason: string; tooLarge?: { size: number } }; + +/** + * `O_NOFOLLOW` / `O_NONBLOCK` are absent on some platforms (Windows). There the "never follows a symlink in the last + * component" guarantee is WEAKER: only the descriptor checks (regular file, size) apply, and callers that must stay + * inside a directory (`readInside` in doctor.ts) additionally resolve the real path and check containment first. + */ +const OPEN_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0); + +/** + * Read a regular file of at most `limit` bytes. Never follows a symlink in the last component (ELOOP is "is a + * symbolic link"), never blocks on a FIFO, never reads a device, and never reads more than the size the open + * descriptor reported. A failure is a value, not a throw. + */ +/** The most bytes ever read: callers decode to a string, and V8 cannot build one longer than this (~512 MiB). */ +export const READ_CEILING: number = bufferConstants.MAX_STRING_LENGTH; + +export async function readRegularFile( + path: string, + limit: number, + /** The most bytes ever read: callers decode to a string, and V8 cannot build one longer than this. */ + ceiling: number = READ_CEILING, +): Promise { + if (Number.isNaN(limit) || Number.isNaN(ceiling)) { + // `Math.min(NaN, x)` is NaN and `size > NaN` is false: a NaN limit would switch the size check off entirely. + return { ok: false, reason: 'has an invalid read limit' }; + } + limit = Math.min(limit, ceiling); + let handle: Awaited>; + try { + handle = await open(path, OPEN_FLAGS); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code ?? 'error'; + return { + ok: false, + reason: code === 'ELOOP' ? 'is a symbolic link' : `could not be read (${code})`, + }; + } + try { + const info = await handle.stat(); + if (!info.isFile()) { + return { ok: false, reason: 'is not a regular file' }; + } + if (info.size > limit) { + return { ok: false, reason: 'is too large to read', tooLarge: { size: info.size } }; + } + const bytes = Buffer.alloc(info.size); + let filled = 0; + while (filled < bytes.length) { + const { bytesRead } = await handle.read(bytes, filled, bytes.length - filled, filled); + /* v8 ignore next 3 -- a file truncated between the stat and the read; not reproducible deterministically */ + if (bytesRead === 0) { + break; // the file shrank after the stat: judge what is there + } + filled += bytesRead; + } + return { ok: true, bytes: filled === bytes.length ? bytes : bytes.subarray(0, filled) }; + /* v8 ignore start -- an I/O error on an already open regular file (EIO); not reproducible in a test */ + } catch (error) { + return { + ok: false, + reason: `could not be read (${(error as NodeJS.ErrnoException).code ?? 'error'})`, + }; + /* v8 ignore stop */ + } finally { + await handle.close(); + } +} diff --git a/packages/bundler-plugin-core/src/sri.scan.test.ts b/packages/bundler-plugin-core/src/sri.scan.test.ts new file mode 100644 index 00000000..0fa53889 --- /dev/null +++ b/packages/bundler-plugin-core/src/sri.scan.test.ts @@ -0,0 +1,327 @@ +// The HTML scan must be linear and bounded on hostile input, and must find exactly what the regexes it replaced +// found on ordinary input. +import { mkdir, mkdtemp, rm, symlink, truncate, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + findSriProtectedScripts, + findSriProtectedScriptsDetailed, + findTags, + MAX_HTML_BYTES, + stripComments, +} from './sri'; + +const made: string[] = []; +const fixture = async () => { + const dir = await mkdtemp(join(tmpdir(), 'bugsee-sri-scan-')); + made.push(dir); + return dir; +}; +afterEach(async () => { + await Promise.all(made.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +// The implementations this replaced, kept as the reference the new scanners must agree with. +const SCRIPT_TAG = /]*>/gi; +const PRELOAD_TAG = /]*>/gi; +const HTML_COMMENT = //g; + +it('the detailed scan keeps every distinct pin of a script; the stamp wrapper one per script', async () => { + const dir = await fixture(); + await writeFile(join(dir, 'a.html'), ''); + await writeFile(join(dir, 'b.html'), ''); + await writeFile(join(dir, 'c.html'), ''); + const detailed = await findSriProtectedScriptsDetailed(dir); + expect(detailed.scripts.map((s) => s.integrity)).toEqual(['sha384-AAA', 'sha384-BBB']); + expect(await findSriProtectedScripts(dir)).toHaveLength(1); +}); + +it('MAX_HTML_BYTES is 8 MiB', () => { + expect(MAX_HTML_BYTES).toBe(8 * 1024 * 1024); +}); + +/** + * The reference the linear scanner must agree with: every `` removed by the regex it replaced. Spliced from + * the match positions (not `String.replace`, which is also what a sanitiser would use: this is a test oracle). + */ +const referenceStrip = (text: string): string => { + let out = ''; + let at = 0; + for (const match of text.matchAll(HTML_COMMENT)) { + out += text.slice(at, match.index); + at = (match.index ?? 0) + match[0].length; + } + return out + text.slice(at); +}; + +describe('findTags / stripComments agree with the regexes they replaced', () => { + const pieces = [ + '', + '', + '', + '', + '', + '', + '', + ''.repeat(20_000); + const started = Date.now(); + expect(findTags(stripComments(text), 'script')).toHaveLength(20_000); + expect(Date.now() - started).toBeLessThan(FAST_MS); + }); + + it('end to end: a page of unterminated repeats is scanned fast and finds nothing', async () => { + const dir = await fixture(); + await writeFile(join(dir, 'index.html'), ''); + await writeFile(join(dir, 'sub', 'huge.html'), ''); + await truncate(join(dir, 'sub', 'huge.html'), MAX_HTML_BYTES + 1); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.scripts.map((s) => s.script)).toEqual([join(dir, 'a.js')]); + expect(scan.skippedPages).toEqual([ + { html: join(dir, 'sub', 'huge.html'), size: MAX_HTML_BYTES + 1 }, + ]); + }); + + it('the stamp guard (findSriProtectedScripts) still sees a pin in a page over the doctor cap', async () => { + const dir = await fixture(); + const tag = ''; + await writeFile(join(dir, 'big.html'), tag + ' '.repeat(MAX_HTML_BYTES + 10)); + expect((await findSriProtectedScripts(dir)).map((s) => s.script)).toEqual([join(dir, 'a.js')]); + }); + + it('a page of exactly MAX_HTML_BYTES is scanned', async () => { + const dir = await fixture(); + const tag = ''; + await writeFile(join(dir, 'p.html'), tag + ' '.repeat(MAX_HTML_BYTES - tag.length)); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.skippedPages).toEqual([]); + expect(scan.scripts).toHaveLength(1); + }); +}); + +describe('the page walk fence is optional', () => { + it('fenced (the default) skips test/ and dot-directories; unfenced scans them, still never node_modules', async () => { + const dir = await fixture(); + const page = ''; + for (const sub of ['tests', '.well', 'node_modules', 'ok']) { + await mkdir(join(dir, sub)); + await writeFile(join(dir, sub, 'p.html'), page.replace('/a.js', `../${sub}.js`)); + } + const fenced = await findSriProtectedScriptsDetailed(dir); + expect(fenced.scripts.map((s) => s.html)).toEqual([join(dir, 'ok', 'p.html')]); + const open = await findSriProtectedScriptsDetailed(dir, MAX_HTML_BYTES, false); + expect(open.scripts.map((s) => s.html).sort()).toEqual( + [ + join(dir, '.well', 'p.html'), + join(dir, 'ok', 'p.html'), + join(dir, 'tests', 'p.html'), + ].sort(), + ); + }); +}); + +describe('symlinked pages', () => { + it('a link inside the directory is scanned; one outside or dangling is listed as unreadable', async () => { + const dir = await fixture(); + const outside = await fixture(); + const page = ''; + await mkdir(join(dir, 'tests')); // a directory the (default) fence skips: only the link can reach this page + await writeFile(join(dir, 'tests', 'p.html'), page); + await symlink(join(dir, 'tests', 'p.html'), join(dir, 'in.html')); + await writeFile(join(outside, 'o.html'), page); + await symlink(join(outside, 'o.html'), join(dir, 'out.html')); + await symlink(join(outside, 'none.html'), join(dir, 'dangling.html')); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.scripts.map((s) => s.html)).toEqual([join(dir, 'in.html')]); + expect(scan.unreadablePages.sort()).toEqual( + [join(dir, 'dangling.html'), join(dir, 'out.html')].sort(), + ); + }); +}); + +describe('a page predicate skips pages before they are read', () => { + it("a skipped page contributes no pins and cannot claim a later page's identical pin", async () => { + const dir = await fixture(); + const page = ''; + await mkdir(join(dir, 'a-skip')); + await writeFile(join(dir, 'a-skip', 'p.html'), page.replace('a.js', '../a.js')); + await writeFile(join(dir, 'z.html'), page); + const all = await findSriProtectedScriptsDetailed(dir); + expect(all.scripts.map((s) => s.html)).toEqual([join(dir, 'a-skip', 'p.html')]); + const skipped: string[] = []; + const scan = await findSriProtectedScriptsDetailed(dir, MAX_HTML_BYTES, true, (html) => { + skipped.push(html); + return html.includes('a-skip'); + }); + expect(scan.scripts.map((s) => s.html)).toEqual([join(dir, 'z.html')]); + expect(skipped.sort()).toEqual([join(dir, 'a-skip', 'p.html'), join(dir, 'z.html')].sort()); + const big = join(dir, 'a-skip', 'big.html'); + await writeFile(big, ''); + await truncate(big, MAX_HTML_BYTES + 1); + const again = await findSriProtectedScriptsDetailed(dir, MAX_HTML_BYTES, true, (html) => + html.includes('a-skip'), + ); + expect(again.skippedPages).toEqual([]); + }); +}); + +describe('symlinked directories in the page walk', () => { + it('inside: followed once (loops and aliases too); outside: listed as unreadable; dangling and file links ignored', async () => { + const dir = await fixture(); + const outside = await fixture(); + const page = ''; + await writeFile(join(dir, 'index.html'), page); + await mkdir(join(dir, 'node_modules')); // never walked by name: only a link reaches pages in here + await mkdir(join(dir, 'node_modules', 'x')); + await writeFile(join(dir, 'node_modules', 'x', 'p.html'), page.replace('a.js', 'x.js')); + await symlink(join(dir, 'node_modules', 'x'), join(dir, 'viaLink')); + await symlink(join(dir, 'node_modules', 'x'), join(dir, 'viaLink2')); // an alias: walked once + await symlink(dir, join(dir, 'self')); // a loop back to the root + await writeFile(join(outside, 'o.html'), page); + await symlink(outside, join(dir, 'leaves')); + await symlink(join(outside, 'nowhere'), join(dir, 'dangling')); + await symlink(join(dir, 'index.html'), join(dir, 'filelink')); + const scan = await findSriProtectedScriptsDetailed(dir, MAX_HTML_BYTES, false); + expect(scan.unreadableDirs).toEqual([join(dir, 'leaves')]); + expect(scan.scripts.map((s) => s.html).sort()).toEqual( + [join(dir, 'index.html'), join(dir, 'viaLink', 'p.html')].sort(), + ); + }); +}); + +describe('the stamp guard resolves pins on REAL build paths (a link never claims a real directory)', () => { + for (const linkName of ['latest', 'zlatest']) { + it(`link "${linkName}" -> v2 does not change where v2/index.html's pin points`, async () => { + const dir = await fixture(); + await mkdir(join(dir, 'v2')); + await writeFile(join(dir, 'v2', 'app.js'), 'x'); + await writeFile( + join(dir, 'v2', 'index.html'), + '', + ); + await symlink(join(dir, 'v2'), join(dir, linkName)); + const pins = await findSriProtectedScripts(dir); + expect(pins.map((p) => [p.html, p.script])).toEqual([ + [join(dir, 'v2', 'index.html'), join(dir, 'v2', 'app.js')], + ]); + }); + } +}); + +describe('depth is counted from the link, in the fenced walk', () => { + it('a page deeper than the cap below a followed link is skipped; the same depth below the root is too', async () => { + const dir = await fixture(); + const deep = join(dir, 'node_modules', 'T', 'a', 'b', 'c', 'd', 'e', 'f'); + await mkdir(deep, { recursive: true }); + await writeFile(join(deep, 'p.html'), ''); + const near = join(dir, 'node_modules', 'T', 'a'); + await writeFile(join(near, 'near.html'), ''); + await symlink(join(dir, 'node_modules', 'T'), join(dir, 'l1')); + const scan = await findSriProtectedScriptsDetailed(dir); // fenced (default) + expect(scan.scripts.map((s) => s.html)).toEqual([join(dir, 'l1', 'a', 'near.html')]); + }); +}); + +describe('round 16: links named like pages, and the fenced depth cap', () => { + it('a link named *.html that points to a DIRECTORY is walked as a directory; one to a file is a page', async () => { + const dir = await fixture(); + await mkdir(join(dir, 'node_modules', 'pages'), { recursive: true }); + await writeFile( + join(dir, 'node_modules', 'pages', 'index.html'), + '', + ); + await symlink(join(dir, 'node_modules', 'pages'), join(dir, 'pages.html')); + await writeFile(join(dir, 'real.html'), ''); + await symlink(join(dir, 'real.html'), join(dir, 'alias.html')); + const scan = await findSriProtectedScriptsDetailed(dir); + expect(scan.scripts.map((s) => s.html).sort()).toEqual( + // (alias.html and real.html carry the same pin: one entry, the first page in sorted order) + [join(dir, 'alias.html'), join(dir, 'pages.html', 'index.html')].sort(), + ); + expect(scan.unreadablePages).toEqual([]); + }); + + it('fenced: a real directory over the depth cap does not mark it visited, so a shallower link still covers it', async () => { + const dir = await fixture(); + const deep = join(dir, 'a', 'b', 'c', 'd', 'e', 'f', 'g'); + await mkdir(deep, { recursive: true }); + await writeFile(join(deep, 'p.html'), ''); + await symlink(deep, join(dir, 'shortcut')); + const scan = await findSriProtectedScriptsDetailed(dir); // fenced (default) + expect(scan.scripts.map((s) => s.html)).toEqual([join(dir, 'shortcut', 'p.html')]); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 3641731b..391437d3 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -16,8 +16,12 @@ // every dynamic import. import { createHash } from 'node:crypto'; import type { Dirent } from 'node:fs'; -import { readdir, readFile } from 'node:fs/promises'; +import { readdir, readFile, realpath, stat } from 'node:fs/promises'; import { isAbsolute, join, normalize, resolve, sep } from 'node:path'; +import { readRegularFile } from './safe-read'; + +/** A page larger than this is not scanned (a real page is a few KB): the scan must stay bounded on hostile input. */ +export const MAX_HTML_BYTES = 8 * 1024 * 1024; /** One `