diff --git a/.changeset/angular-sourcemaps.md b/.changeset/angular-sourcemaps.md new file mode 100644 index 00000000..d998f154 --- /dev/null +++ b/.changeset/angular-sourcemaps.md @@ -0,0 +1,8 @@ +--- +'@bugsee/angular': minor +'@bugsee/bundler-plugin-core': minor +--- + +`ng add @bugsee/angular` and Angular source maps. The schematic enables hidden script source maps in the production configuration, launches the SDK in `main.ts`, registers `BugseeErrorHandler` through Angular's own `addRootProvider` (standalone and NgModule apps; it prints what to add by hand rather than guess when it cannot find the bootstrap), and adds a `build:bugsee` script: `ng build`, then the new `bugsee-angular-upload` command (also `@bugsee/angular/sourcemaps`), which stamps debug-IDs into the browser output, uploads the maps and registers the build. Works on Angular's esbuild `application` builder and the webpack `browser` builder. + +`subresourceIntegrity: true` is supported rather than refused: `@bugsee/bundler-plugin-core` gains `resealSri`, which snapshots every script's digests, stamps with `--allow-sri`, swaps each changed script's old digests for its new ones in the pages, an import map, the copy of the page an SSR build embeds in its server modules and the webpack builder's runtime hash table, then verifies the pages. The SRI scan now also reads `` in the same page, pinning EVERY lazy chunk. A stamped lazy chunk is blocked + (`Failed to find a valid digest in the 'integrity' attribute for resource '…/chunk-X.js' … has been blocked`, + and `Failed to fetch dynamically imported module`) while the entry scripts still run — which is what made this a + finding: the first version of the scan read tags only; +- with SSR/prerender, a second copy of the page as a string in `server/assets-chunks/index*.html.mjs` and in + `server/index.server.html`, which the Node server answers requests from. + +Nothing else in the esbuild builder's output (no runtime table). The legacy webpack `browser` builder differs: +its `runtime.*.js` carries the lazy chunks' hashes (`sriHashes`), which NO page pins (measured on +`@angular-devkit/build-angular` 19: a stamped lazy chunk was blocked while the entry scripts ran). So the stale +hashes cannot be found by reading the pages. They are found by what the files WERE: `snapshotScriptDigests` records +the sha256/384/512 of every script under the output before the stamp, and `resealIntegrity` swaps each changed +script's old digests for its new ones in every HTML, `.mjs` and `.js` file (same length, so no byte offset moves and +the maps stay valid), repeating (bounded) because rewriting the runtime's table changes the runtime's own hash. + +The order that works is the one the CLI documents for `--allow-sri`: stamp, then recompute the hashes. +`uploadSourcemaps({ resealSri: true })` does: snapshot, `inject --allow-sri`, verify the stamp, re-seal, then verify +with `findIntegrityMismatches` (the pages' pins, the one thing a browser checks first). A page that still does not +verify is reported, or thrown under `failOnError`, never silent. A hash computed at run time, or kept in a file +outside the directories given, is not covered and is not claimed to be. + +**Verified for real** (`npm run build:bugsee` from `ng add`, the packed `@bugsee/angular` + `@bugsee/bundler-plugin-core`, +the real `bugsee-cli`, a mock collector, Chromium via Playwright; `outputHashing: all`, `subresourceIntegrity: true`): + +| App | Result | +|---|---| +| Angular 22.3, esbuild `application`, lazy route | every pin matches its file; 5 maps uploaded and deleted; the page runs, the lazy chunk loads, 4 debug-IDs registered, no console error | +| same, stamped with `--allow-sri` and NOT re-sealed (control) | blocked outright: nothing runs | +| Angular 22.3, SSR + prerender | 24 pins across `browser/`, `server/index.server.html` and the 3 `assets-chunks` modules all match; the real `server.mjs` serves a page that runs, 5 debug-IDs, no console error | +| Angular 19.2, webpack `browser` builder | the lazy chunk (blocked before the digest snapshot) now loads; 4 debug-IDs, no console error; control blocked | + +CI keeps the bytes half of this: `upload.real-build.test.ts` runs the real CLI over two real Angular 22.3 chunks with +the SRI page shapes above (script tag, import map, SSR copy); the browser half is not in CI. + +**Service worker manifests.** `ngsw.json` (one per locale for a localized build; measured on `@angular/build` 22.3 with +`@angular/service-worker`) carries `hashTable`: SHA-1 hex of each cached file's bytes, keyed by path from the manifest's +directory. A service worker that finds a mismatch treats the app as corrupt and stops serving it, and the SRI re-seal +(sha256/384/512) never touched it: the first version only refused a top-level manifest and so missed the per-locale +ones. `resealIntegrity` now recomputes every entry after the last pass (a targeted text swap, formatting untouched; +the file is found by dropping leading URL segments, which covers a base href), `findStaleServiceWorkerEntries` verifies, +and an entry that cannot be reconciled rolls the build back like a stale SRI hash. No other manifest field depends on +file contents in the version checked. **What it refuses:** nothing for a service worker now. It also stamps `browser/` only: a server bundle's errors are the Node +SDK's, symbolicated by `@bugsee/node`. + +**The legacy webpack `browser` builder** (`@angular-devkit/build-angular:browser`) takes the same route: the post-build +step needs nothing from the builder, and its output is flat (`outputPath` IS the browser directory). Its SRI is the +reason for the digest snapshot above. `@angular-builders/custom-webpack` + `bugseeWebpackPlugin` (the route Sentry +documents) was considered and not built: it would need the plugin's in-build stamp to run before Angular's own SRI +plugin hashes, an ordering nobody verified for Angular's compilation, to cover one legacy builder that the post-build +step already covers with a measured result. --- diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 8a8afa48..30bd358f 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -72,7 +72,7 @@ For **Rspack**, set `devtool: 'source-map'`: its production default is `devtool: there is nothing to upload (the plugin says so through `onNotice`). **What these do not cover.** **Angular's builder does not accept esbuild plugins**, so `bugseeEsbuildPlugin` -cannot be used with `ng build`: use the post-build recipe in §2. Bun's bundler, `tsc` and `swc` have no hook +cannot be used with `ng build`: use `ng add @bugsee/angular` (§2). Bun's bundler, `tsc` and `swc` have no hook either (also §2). Next.js on webpack uses the webpack plugin. **Where the settings come from.** The lookup order is: the **plugin option**, then the **process environment**, @@ -184,20 +184,51 @@ BUGSEE_APP_TOKEN=… bugsee-cli debug-files upload ./dist \ --type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD" ``` -**Angular (17+, `ng build` with the esbuild application builder).** There is no plugin hook, so add the CLI as a -step after the build (for example an npm script or a CI step): +**Angular — `ng add @bugsee/angular`.** Run it once in the workspace (`ng add @bugsee/angular --app-token `): ```bash -ng build --source-map # or "sourceMap": true in angular.json; the output lands in dist//browser -export BUGSEE_APP_TOKEN=… # the CLI does not read .env.bugsee-build-plugin -bugsee-cli sourcemaps inject dist//browser -bugsee-cli debug-files upload dist//browser \ - --type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD" +ng add @bugsee/angular +npm run build:bugsee # ng build --configuration production, then bugsee-angular-upload +``` + +It turns on hidden script source maps in the production configuration +(`"sourceMap": { "scripts": true, "styles": false, "hidden": true }`), launches the SDK in `main.ts`, registers +`BugseeErrorHandler` in your providers, adds the `build:bugsee` script, and keeps the token in +`.env.bugsee-build-plugin` (added to `.gitignore`). Where it cannot find your bootstrap it changes no source and prints +the lines to add. Running it again changes nothing. A plain `ng build` does not upload; run `build:bugsee` where you +build for release, with `BUGSEE_APP_TOKEN` set (or the env file present). + +`bugsee-angular-upload` is the step the script runs, and you can run it yourself after any `ng build` (it finds the +output from `angular.json`): `--project`, `--configuration`, `--dist `, `--dry-run`, `--keep-maps`, +`--fail-on-error`, `--strip-sources-content`, `--help`. The same thing is a function: +`import { uploadAngularSourcemaps } from '@bugsee/angular/sourcemaps'`. It works on both Angular builders — the +esbuild `application` builder (the default since 17, output in `dist//browser`) and the webpack +`browser` builder (`outputPath` is the browser directory) — because it only needs the finished output. + +- **`subresourceIntegrity: true` is supported.** Angular writes a hash of every script into `index.html` (the lazy + chunks in an import map, or in the runtime chunk on the webpack builder) and, with SSR, into the copy of that page + its server serves. The step stamps the bundles, + then re-writes those hashes to match and checks them, so the page keeps loading. (The CLI on its own refuses such a + build; this is what `--allow-sri` assumes you do.) +- **A build with a service worker works.** `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every + file it caches and the service worker rejects a changed one, so after stamping the step re-computes those entries + and checks them; if one cannot be reconciled it restores the build and uploads nothing. +- **If the output moved** (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the output root is re-sealed, because the server embeds the page (for one locale of several, only that locale and its `server/` pages: Angular emits identical shared scripts into every locale, and the others must keep pinning their unstamped copies); if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A + problem locating the output is printed and the command exits 0, so it cannot fail a pipeline whose build + succeeded; `--fail-on-error` makes it exit non-zero. +- **Only `browser/` is uploaded.** An SSR server bundle's errors are reported by the Node SDK. +- `outputHashing: "all"` (the default in production) keeps the file names unique per build; the debug-ID, not the + file name, is what links a frame to its map. + +By hand, without the schematic (any Angular version), the same two steps are: + +```bash +ng build --configuration production # with sourceMap.scripts true in angular.json +BUGSEE_APP_TOKEN=… npx bugsee-angular-upload --configuration production ``` -If you enable `"subresourceIntegrity": true`, bugsee-cli 0.7.13 `inject` refuses to run (it would invalidate the -integrity hashes Angular writes into `index.html`) unless you pass `--allow-sri`, which you should only do if -the hashes are recomputed after it runs; otherwise turn that option off for builds you symbolicate. +Do not run `bugsee-cli sourcemaps inject` yourself on an Angular build that has `subresourceIntegrity`: it refuses +(or, with `--allow-sri`, leaves a page whose hashes no longer match, which the browser blocks). `inject` must run **before deployment** so the shipped bundle carries the debug-ID + the `_bugseeDebugIds` runtime stub the SDK reads. This is exactly what the plugins automate; the CLI is the same engine, just invoked by hand. diff --git a/packages/angular/README.md b/packages/angular/README.md index 08ed7338..ef326f13 100644 --- a/packages/angular/README.md +++ b/packages/angular/README.md @@ -16,11 +16,56 @@ pnpm add @bugsee/angular yarn add @bugsee/angular ``` -Peer dependencies: `@angular/core` >= 16 and `@angular/router` >= 16 (both optional). +Peer dependencies: `@angular/core` >= 16 and `@angular/router` >= 16 (both optional). `@angular-devkit/schematics` and `@schematics/angular` (>= 16.1, optional) are only used by `ng add` and are already in every Angular workspace. -## Usage +## Quick start: `ng add` -Launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a Promise of the client. Await it only if you need the client right away. +```sh +ng add @bugsee/angular +``` + +It asks for your app token and then, in the workspace's application: + +- turns on hidden script source maps in the production configuration of `angular.json` (`"sourceMap": { "scripts": true, "styles": false, "hidden": true }`), unless it already produces maps; +- launches the SDK in `main.ts`, before the bootstrap; +- registers `BugseeErrorHandler` as your `ErrorHandler` (standalone `app.config.ts` or `AppModule`); +- adds a `build:bugsee` script, and keeps the token for it in `.env.bugsee-build-plugin` (added to `.gitignore`). + +Where it cannot find your bootstrap it changes no source and prints the lines to add by hand. Running it again changes nothing. With several applications pass `--project `. + +## Source maps + +Build for release with the script it added: + +```sh +npm run build:bugsee # ng build --configuration production && bugsee-angular-upload --configuration production +``` + +`bugsee-angular-upload` stamps debug-IDs into `dist//browser`, uploads the maps, registers the build and removes the local maps, so a crash from the shipped bundle shows your original source. Set `BUGSEE_APP_TOKEN` (or keep the env file) where you run it. A plain `ng build` does not upload. + +You can also run it by hand after any `ng build` (`bugsee-angular-upload --help` lists the options: `--project`, `--configuration`, `--dist`, `--dry-run`, `--keep-maps`, `--fail-on-error`, …), or call it from code: + +```ts +import { uploadAngularSourcemaps } from "@bugsee/angular/sourcemaps"; + +await uploadAngularSourcemaps({ project: "my-app", configuration: "production" }); +``` + +It works with the esbuild `application` builder and the webpack `browser` builder. Notes: + +- `subresourceIntegrity: true` is supported: after stamping, the integrity hashes in `index.html`, in the import map and in the SSR server modules are re-written to match, so the page keeps loading. +- A build with a service worker works: `ngsw.json` (one per locale for a localized build) lists the SHA-1 of every file it caches, so after stamping those entries are re-computed and checked; if one cannot be reconciled the build is restored and nothing is uploaded. +- If the output is not where `angular.json` says (`ng build --output-path other`), pass `--output-path other` (or `--dist `). When the output is named by its browser directory (also `browser/`) and a sibling `server/` exists inside the project, the output root is re-sealed, because the server embeds the page (for one locale of several, only that locale and its `server/` pages: Angular emits identical shared scripts into every locale, and the others must keep pinning their unstamped copies); if the output root is the project root itself (or outside it) the tool says it cannot, and you should build into its own directory and use `--output-path`. A problem locating the output (no `angular.json`, several applications without `--project`, no build output yet) is printed and the command still exits 0, so it cannot fail a pipeline whose build succeeded; add `--fail-on-error` to make it exit non-zero. +- Install weight: `@bugsee/angular` depends on `@bugsee/bundler-plugin-core` (and through it `@bugsee/cli`, `acorn`, `magic-string`, `unplugin`), because the `bugsee-angular-upload` bin and `@bugsee/angular/sourcemaps` need them. They are build-time only and never reach a browser bundle, but they are installed with the package. Making them an optional peer that `ng add` installs as a devDependency was considered and not done: `ng add` saves the package itself under `dependencies`, the bin would fail for anyone who skips `ng add`, and the extra install step has to be verified against every package manager. +- If your app already provides its own `ErrorHandler`, `ng add` does not add a second one (the last provider wins and would silence yours); it prints how to report from yours with `reportAngularError(error)`, or to wrap it with `createAngularErrorHandler({ delegate })`. +- Known limits: the `ErrorHandler` check scans only the project's `sourceRoot`, so a handler provided from a shared (Nx) library is not seen; the deletion rule assumes Angular cleans its output directory (`deleteOutputPath`, default true), so with `deleteOutputPath: false` or a wider `--dist`, a stale foreign map that carries a debug-ID could be deleted; the integrity check does not follow `` for nested prerendered pages (the digest swap still fixes them). +- Only the browser output is uploaded; errors from an SSR server are reported by the Node SDK. + +Details and the measurements behind them: [source maps](https://github.com/bugsee/bugsee-javascript/blob/main/docs/source-maps-usage.md). + +## Usage by hand + +`ng add` does this for you. To do it yourself, launch Bugsee as early as possible, at the top of your entry module. In the browser `launch()` returns a Promise of the client. Await it only if you need the client right away. ```ts // main.ts diff --git a/packages/angular/package.json b/packages/angular/package.json index b37b4ab3..8818e44a 100644 --- a/packages/angular/package.json +++ b/packages/angular/package.json @@ -7,7 +7,7 @@ "url": "git+https://github.com/bugsee/bugsee-javascript.git", "directory": "packages/angular" }, - "description": "Angular adapter: ErrorHandler + Router naming", + "description": "Angular adapter: ErrorHandler + Router naming, plus `ng add` and a source-map upload step", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", @@ -15,14 +15,19 @@ ".": { "types": "./src/index.ts", "import": "./src/index.ts" - } + }, + "./sourcemaps": { + "types": "./src/sourcemaps/index.ts", + "import": "./src/sourcemaps/index.ts" + }, + "./package.json": "./package.json" }, "files": [ "dist" ], "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" @@ -30,11 +35,14 @@ "dependencies": { "@bugsee/bugsee": "workspace:*", "@bugsee/browser": "workspace:*", - "@bugsee/web-adapter": "workspace:*" + "@bugsee/web-adapter": "workspace:*", + "@bugsee/bundler-plugin-core": "workspace:*" }, "peerDependencies": { "@angular/core": ">=16", - "@angular/router": ">=16" + "@angular/router": ">=16", + "@angular-devkit/schematics": ">=16.1", + "@schematics/angular": ">=16.1" }, "peerDependenciesMeta": { "@angular/core": { @@ -42,6 +50,12 @@ }, "@angular/router": { "optional": true + }, + "@angular-devkit/schematics": { + "optional": true + }, + "@schematics/angular": { + "optional": true } }, "publishConfig": { @@ -58,11 +72,32 @@ "types": "./dist/index.d.cts", "default": "./dist/index.cjs" } - } + }, + "./sourcemaps": { + "import": { + "types": "./dist/sourcemaps/index.d.ts", + "default": "./dist/sourcemaps/index.js" + }, + "require": { + "types": "./dist/sourcemaps/index.d.cts", + "default": "./dist/sourcemaps/index.cjs" + } + }, + "./package.json": "./package.json" }, - "access": "public" + "access": "public", + "bin": { + "bugsee-angular-upload": "./dist/sourcemaps/bin.js" + } }, "devDependencies": { - "@bugsee/core": "workspace:*" + "@bugsee/core": "workspace:*", + "@angular-devkit/schematics": "22.0.0", + "@schematics/angular": "22.0.0", + "@types/node": "^22.20.5" + }, + "schematics": "./dist/schematics/collection.json", + "ng-add": { + "save": "dependencies" } } diff --git a/packages/angular/src/schematics/collection.json b/packages/angular/src/schematics/collection.json new file mode 100644 index 00000000..169c469b --- /dev/null +++ b/packages/angular/src/schematics/collection.json @@ -0,0 +1,10 @@ +{ + "$schema": "../../../../node_modules/@angular-devkit/schematics/collection-schema.json", + "schematics": { + "ng-add": { + "description": "Set up Bugsee in an Angular application: launch the SDK, report errors through Angular's ErrorHandler, and upload source maps after the production build.", + "factory": "./ng-add/index.cjs#ngAdd", + "schema": "./ng-add/schema.json" + } + } +} diff --git a/packages/angular/src/schematics/ng-add/index.test.ts b/packages/angular/src/schematics/ng-add/index.test.ts new file mode 100644 index 00000000..65106f85 --- /dev/null +++ b/packages/angular/src/schematics/ng-add/index.test.ts @@ -0,0 +1,660 @@ +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { callRule, type Rule, type Tree } from '@angular-devkit/schematics'; +import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { ngAdd } from './index'; +import type { Schema } from './schema'; + +// A real Angular workspace and application are generated by Angular's own schematics into a virtual tree, so the +// rule is tested against the files `ng new` writes, not against hand-made imitations of them. +const here = fileURLToPath(new URL('.', import.meta.url)); +const collection = join(here, '..', 'collection.json'); + +let runner: SchematicTestRunner; +let logs: { level: string; message: string }[]; + +beforeEach(() => { + runner = new SchematicTestRunner('@bugsee/angular', collection); + logs = []; + runner.logger.subscribe((entry) => logs.push({ level: entry.level, message: entry.message })); +}); + +const logged = (level?: string) => + logs + .filter((l) => level === undefined || l.level === level) + .map((l) => l.message) + .join('\n'); + +// biome-ignore lint/suspicious/noExplicitAny: angular.json is edited ad hoc throughout these tests +type Loose = Record; + +const NG = '@schematics/angular'; + +async function workspace( + apps: { name: string; standalone?: boolean; ssr?: boolean }[] = [{ name: 'demo' }], +): Promise { + let tree = await runner.runExternalSchematic(NG, 'workspace', { + name: 'ws', + version: '22.0.0', + newProjectRoot: 'projects', + }); + for (const app of apps) { + tree = await runner.runExternalSchematic( + NG, + 'application', + { + name: app.name, + projectRoot: apps.length === 1 ? '' : `projects/${app.name}`, + standalone: app.standalone ?? true, + routing: false, + style: 'css', + skipTests: true, + ssr: app.ssr ?? false, + }, + tree, + ); + } + tree.delete('/.gitignore'); + if (!tree.exists('/package.json')) { + tree.create( + '/package.json', + JSON.stringify({ name: 'ws', version: '1.2.3', scripts: { ng: 'ng' } }, null, 2), + ); + } + return tree; +} + +/** Run a rule against `tree` and resolve to the resulting tree (callRule hands back an Observable). */ +const run = (tree: UnitTestTree, options: Schema = {}, rule: Rule = ngAdd(options)) => + new Promise((resolve, reject) => { + let result: Tree | undefined; + // The runner's own context has a logger nobody can read; this one writes to `runner.logger` (see `logs`). + const context = { + ...runner.engine.createContext({ description: { name: 'ng-add' } } as never), + logger: runner.logger, + }; + callRule(rule, tree, context).subscribe({ + next: (next) => { + result = next; + }, + error: reject, + complete: () => resolve(new UnitTestTree(result as Tree)), + }); + }); + +const json = (tree: UnitTestTree, path: string) => JSON.parse(tree.readContent(path)); +const snapshot = (tree: UnitTestTree) => + Object.fromEntries(tree.files.map((file) => [file, tree.readContent(file)])); + +const prodOf = (tree: UnitTestTree, project = 'demo') => + json(tree, '/angular.json').projects[project].architect.build.configurations.production; + +describe('ng add @bugsee/angular — a standalone application', () => { + it('turns on hidden script source maps in the production configuration', async () => { + const tree = await run(await workspace(), { appToken: 'TOKEN' }); + expect(prodOf(tree).sourceMap).toEqual({ scripts: true, styles: false, hidden: true }); + }); + + it('launches the SDK in main.ts, after the imports and before the bootstrap', async () => { + const tree = await run(await workspace(), { appToken: 'TOKEN' }); + const main = tree.readContent('/src/main.ts'); + expect(main).toContain(`import { launch } from '@bugsee/angular';`); + expect(main).toContain(`launch('TOKEN');`); + expect(main.indexOf(`launch('TOKEN')`)).toBeLessThan(main.indexOf('bootstrapApplication(')); + expect(main.indexOf(`launch('TOKEN')`)).toBeGreaterThan(main.lastIndexOf('import ')); + }); + + it('registers BugseeErrorHandler as the ErrorHandler in the application config', async () => { + const tree = await run(await workspace(), { appToken: 'TOKEN' }); + const config = tree.readContent('/src/app/app.config.ts'); + expect(config).toContain('BugseeErrorHandler'); + expect(config).toMatch(/provide:\s*ErrorHandler,\s*useClass:\s*BugseeErrorHandler\b/); + expect(config).toContain(`from '@bugsee/angular'`); + expect(config).toMatch(/import \{[^}]*ErrorHandler[^}]*\} from '@angular\/core'/); + }); + + it('adds the build:bugsee script', async () => { + const tree = await run(await workspace(), { appToken: 'TOKEN' }); + expect(json(tree, '/package.json').scripts['build:bugsee']).toBe( + 'ng build --configuration production && bugsee-angular-upload --configuration production', + ); + expect(json(tree, '/package.json').scripts.ng).toBe('ng'); + }); + + it('keeps the token for the build in .env.bugsee-build-plugin, out of git', async () => { + const tree = await workspace(); + tree.create('/.gitignore', 'node_modules\n'); + await run(tree, { appToken: 'TOKEN' }); + expect(tree.readContent('/.env.bugsee-build-plugin')).toBe('BUGSEE_APP_TOKEN=TOKEN\n'); + expect(tree.readContent('/.gitignore')).toBe('node_modules\n.env.bugsee-build-plugin\n'); + }); + + it('creates a .gitignore when there is none, and does not duplicate the entry', async () => { + const tree = await run(await workspace(), { appToken: 'TOKEN' }); + expect(tree.readContent('/.gitignore')).toBe('.env.bugsee-build-plugin\n'); + const again = await run(tree, { appToken: 'TOKEN' }); + expect(again.readContent('/.gitignore')).toBe('.env.bugsee-build-plugin\n'); + }); + + it('adds a missing newline before the .gitignore entry', async () => { + const tree = await workspace(); + tree.create('/.gitignore', 'dist'); + await run(tree, { appToken: 'TOKEN' }); + expect(tree.readContent('/.gitignore')).toBe('dist\n.env.bugsee-build-plugin\n'); + }); + + it('is idempotent: a second run changes nothing', async () => { + const first = await run(await workspace(), { appToken: 'TOKEN' }); + const before = snapshot(first); + const second = await run(first, { appToken: 'TOKEN' }); + expect(snapshot(second)).toEqual(before); + }); + + it('does not touch what is already set up, even with another token', async () => { + const first = await run(await workspace(), { appToken: 'TOKEN' }); + const before = snapshot(first); + const second = await run(first, { appToken: 'OTHER' }); + expect(snapshot(second)).toEqual(before); + expect(second.readContent('/src/main.ts')).toContain(`launch('TOKEN')`); + }); +}); + +describe('ng add @bugsee/angular — an NgModule application', () => { + it('registers the ErrorHandler in AppModule and launches in main.ts', async () => { + const tree = await run(await workspace([{ name: 'demo', standalone: false }]), { + appToken: 'T', + }); + const modulePath = tree.files.find((f) => /app[.-]module\.ts$/.test(f)) as string; + const module = tree.readContent(modulePath); + expect(module).toContain('BugseeErrorHandler'); + expect(module).toMatch(/provide:\s*ErrorHandler,\s*useClass:\s*BugseeErrorHandler\b/); + expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`); + expect(tree.readContent('/src/main.ts')).toContain('bootstrapModule'); + }); + + it('is idempotent', async () => { + const first = await run(await workspace([{ name: 'demo', standalone: false }]), { + appToken: 'T', + }); + const second = await run(first, { appToken: 'T' }); + expect(snapshot(second)).toEqual(snapshot(first)); + }); +}); + +describe('ng add @bugsee/angular — without a token', () => { + it('writes a placeholder, creates no env file, and says what to do', async () => { + const tree = await run(await workspace(), {}); + expect(tree.readContent('/src/main.ts')).toContain(`launch('YOUR_APP_TOKEN');`); + expect(tree.exists('/.env.bugsee-build-plugin')).toBe(false); + expect(logged('warn')).toMatch(/YOUR_APP_TOKEN/); + expect(logged('warn')).toMatch(/BUGSEE_APP_TOKEN/); + }); + + it('treats a blank token as none', async () => { + const tree = await run(await workspace(), { appToken: ' ' }); + expect(tree.readContent('/src/main.ts')).toContain(`launch('YOUR_APP_TOKEN');`); + }); + + it.each([ + ['a line break', 'abc\nBUGSEE_ENDPOINT=https://evil'], + ['a carriage return', 'abc\rdef'], + ['a unicode line separator', 'abc\u2028def'], + ['a space', 'abc def'], + ['a # (the env parser reads it as a comment)', 'abc#def'], + ['a single quote', "a'b"], + ['a double quote', 'a"b'], + ['a backtick', 'a`b'], + ['a backslash', 'a\\b'], + ])('rejects a token with %s, which the env file or the launch call cannot carry safely', async (_name, token) => { + const tree = await workspace(); + await expect(run(tree, { appToken: token })).rejects.toThrow(/must not contain/); + expect(tree.exists('/.env.bugsee-build-plugin')).toBe(false); + expect(tree.readContent('/src/main.ts')).not.toContain('launch('); + }); +}); + +describe('ng add @bugsee/angular — the .env file', () => { + it('warns when the env file already holds a DIFFERENT token than the one given, and leaves it', async () => { + const tree = await workspace(); + tree.create('/.env.bugsee-build-plugin', 'BUGSEE_APP_TOKEN=OLD\n'); + await run(tree, { appToken: 'NEW' }); + expect(tree.readContent('/.env.bugsee-build-plugin')).toBe('BUGSEE_APP_TOKEN=OLD\n'); + expect(logged('warn')).toMatch(/different BUGSEE_APP_TOKEN/); + expect(tree.readContent('/src/main.ts')).toContain(`launch('NEW');`); + }); + + it('says nothing when the env file already holds the same token', async () => { + const tree = await workspace(); + tree.create('/.env.bugsee-build-plugin', 'BUGSEE_APP_TOKEN=SAME\n'); + await run(tree, { appToken: 'SAME' }); + expect(logged('warn')).not.toMatch(/different/); + }); + + it('appends the token to an env file that has other settings, and leaves one that has a token alone', async () => { + const tree = await workspace(); + tree.create('/.env.bugsee-build-plugin', 'BUGSEE_ENDPOINT=https://x'); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/.env.bugsee-build-plugin')).toBe( + 'BUGSEE_ENDPOINT=https://x\nBUGSEE_APP_TOKEN=T\n', + ); + const kept = await workspace(); + kept.create('/.env.bugsee-build-plugin', 'BUGSEE_APP_TOKEN=mine\n'); + await run(kept, { appToken: 'T' }); + expect(kept.readContent('/.env.bugsee-build-plugin')).toBe('BUGSEE_APP_TOKEN=mine\n'); + }); +}); + +describe('ng add @bugsee/angular — source maps in angular.json', () => { + const setBuild = (tree: UnitTestTree, edit: (build: Loose) => void) => { + const ws = json(tree, '/angular.json'); + edit(ws.projects.demo.architect.build); + tree.overwrite('/angular.json', JSON.stringify(ws, null, 2)); + }; + + it('replaces a production sourceMap that is off', async () => { + const tree = await workspace(); + setBuild(tree, (b) => { + b.configurations.production.sourceMap = false; + }); + await run(tree, { appToken: 'T' }); + expect(prodOf(tree).sourceMap).toEqual({ scripts: true, styles: false, hidden: true }); + }); + + it('replaces an object with scripts off, but keeps the rest of the object', async () => { + const tree = await workspace(); + setBuild(tree, (b) => { + b.configurations.production.sourceMap = { scripts: false, styles: true, vendor: true }; + }); + await run(tree, { appToken: 'T' }); + expect(prodOf(tree).sourceMap).toEqual({ + scripts: true, + styles: true, + vendor: true, + hidden: true, + }); + }); + + it('leaves a production sourceMap that already includes scripts exactly as the user wrote it', async () => { + for (const value of [true, { scripts: true, hidden: false }, { styles: false }]) { + const tree = await workspace(); + setBuild(tree, (b) => { + b.configurations.production.sourceMap = value; + }); + await run(tree, { appToken: 'T' }); + expect(prodOf(tree).sourceMap).toEqual(value); + } + }); + + it('leaves it alone when the build options already turn maps on for every configuration', async () => { + const tree = await workspace(); + setBuild(tree, (b) => { + b.options.sourceMap = true; + }); + await run(tree, { appToken: 'T' }); + expect(prodOf(tree).sourceMap).toBeUndefined(); + }); + + it('creates the production configuration when the project has none', async () => { + const tree = await workspace(); + setBuild(tree, (b) => { + delete b.configurations; + delete b.defaultConfiguration; + }); + await run(tree, { appToken: 'T' }); + expect(prodOf(tree).sourceMap).toEqual({ scripts: true, styles: false, hidden: true }); + }); + + it('adds the production configuration next to a development-only set', async () => { + const tree = await workspace(); + setBuild(tree, (b) => { + b.configurations = { development: { optimization: false } }; + }); + await run(tree, { appToken: 'T' }); + const configs = json(tree, '/angular.json').projects.demo.architect.build.configurations; + expect(configs.development).toEqual({ optimization: false }); + expect(configs.production.sourceMap).toEqual({ scripts: true, styles: false, hidden: true }); + }); +}); + +describe('ng add @bugsee/angular — choosing the project', () => { + it('uses the only application, ignoring libraries', async () => { + const tree = await workspace(); + const ws = json(tree, '/angular.json'); + ws.projects.lib = { projectType: 'library', root: 'projects/lib', architect: {} }; + tree.overwrite('/angular.json', JSON.stringify(ws)); + const out = await run(tree, { appToken: 'T' }); + expect(prodOf(out).sourceMap.scripts).toBe(true); + }); + + it('asks for --project when there are several applications', async () => { + const tree = await workspace([{ name: 'one' }, { name: 'two' }]); + await expect(run(tree, { appToken: 'T' })).rejects.toThrow(/--project.*one, two/); + }); + + it('sets up the named application and puts its name in the script', async () => { + const tree = await run(await workspace([{ name: 'one' }, { name: 'two' }]), { + project: 'two', + appToken: 'T', + }); + expect(prodOf(tree, 'two').sourceMap.scripts).toBe(true); + expect(prodOf(tree, 'one').sourceMap).toBeUndefined(); + expect(tree.readContent('/projects/two/src/main.ts')).toContain(`launch('T')`); + expect(tree.readContent('/projects/one/src/main.ts')).not.toContain('launch'); + expect(json(tree, '/package.json').scripts['build:bugsee']).toBe( + 'ng build two --configuration production && bugsee-angular-upload --project two --configuration production', + ); + }); + + it('rejects a project that does not exist', async () => { + await expect(run(await workspace(), { project: 'nope' })).rejects.toThrow(/no project "nope"/); + }); + + it('rejects a workspace with no application', async () => { + const tree = await workspace(); + tree.overwrite('/angular.json', JSON.stringify({ version: 1, projects: {} })); + await expect(run(tree, {})).rejects.toThrow(/no application project/); + }); + + it('rejects a project that has no build target', async () => { + const tree = await workspace(); + const ws = json(tree, '/angular.json'); + delete ws.projects.demo.architect.build; + tree.overwrite('/angular.json', JSON.stringify(ws)); + await expect(run(tree, {})).rejects.toThrow(/no "build" target/); + }); +}); + +describe('ng add @bugsee/angular — when it cannot tell how the app starts', () => { + it('changes no source, says what to add by hand, and still sets up the build', async () => { + const tree = await workspace(); + tree.overwrite('/src/main.ts', `import('./boot').then((m) => m.start());\n`); + const before = tree.readContent('/src/app/app.config.ts'); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/main.ts')).toBe(`import('./boot').then((m) => m.start());\n`); + expect(tree.readContent('/src/app/app.config.ts')).toBe(before); + expect(logged('warn')).toMatch(/could not find where the app bootstraps/); + expect(logged('warn')).toMatch(/launch\('T'\)/); + expect(logged('warn')).toMatch(/BugseeErrorHandler/); + expect(prodOf(tree).sourceMap.scripts).toBe(true); + expect(json(tree, '/package.json').scripts['build:bugsee']).toBeDefined(); + }); + + it('says so when the entry file is missing', async () => { + const tree = await workspace(); + tree.delete('/src/main.ts'); + await run(tree, { appToken: 'T' }); + expect(logged('warn')).toMatch(/could not find where the app bootstraps/); + }); + + it('launches but explains the ErrorHandler step when the provider cannot be added', async () => { + const tree = await workspace(); + tree.overwrite( + '/src/main.ts', + `import { bootstrapApplication } from '@angular/platform-browser';\nimport { App } from './app/app';\n\nbootstrapApplication(App, makeConfig());\n`, + ); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`); + expect(logged('warn')).toMatch(/could not register BugseeErrorHandler/); + expect(logged('warn')).toMatch(/provide: ErrorHandler, useClass: BugseeErrorHandler/); + }); + + it('puts the launch first in a main.ts that has no imports', async () => { + const tree = await workspace(); + tree.overwrite('/src/main.ts', `platformBrowser().bootstrapModule(AppModule);\n`); + await run(tree, { appToken: 'T' }); + expect( + tree.readContent('/src/main.ts').startsWith(`import { launch } from '@bugsee/angular';`), + ).toBe(true); + }); + + it('inserts after the last of several imports, including a side-effect import', async () => { + const tree = await workspace(); + tree.overwrite( + '/src/main.ts', + `import { a } from 'a';\nimport {\n b,\n c,\n} from 'b';\nimport 'zone.js';\n\nbootstrapApplication(App, appConfig);\n`, + ); + await run(tree, { appToken: 'T' }); + const main = tree.readContent('/src/main.ts'); + expect(main.indexOf(`from '@bugsee/angular'`)).toBeGreaterThan( + main.indexOf(`import 'zone.js'`), + ); + expect(main.indexOf(`launch('T')`)).toBeLessThan(main.indexOf('bootstrapApplication')); + }); + + it('does not mistake a call that merely starts with "import" for an import', async () => { + const tree = await workspace(); + tree.overwrite( + '/src/main.ts', + `import { a } from 'a';\nimportScripts('worker.js');\nbootstrapApplication(App, appConfig);\n`, + ); + await run(tree, { appToken: 'T' }); + const main = tree.readContent('/src/main.ts'); + expect(main.indexOf(`from '@bugsee/angular'`)).toBeLessThan(main.indexOf('importScripts')); + }); + + it('finds the entry file when angular.json spells it with a leading ./', async () => { + const tree = await workspace(); + const ws = json(tree, '/angular.json'); + ws.projects.demo.architect.build.options.browser = './src/main.ts'; + tree.overwrite('/angular.json', JSON.stringify(ws, null, 2)); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`); + }); +}); + +describe('ng add @bugsee/angular — an app already using Bugsee', () => { + it('does not launch twice, and does not add a second handler', async () => { + const tree = await workspace(); + tree.overwrite( + '/src/main.ts', + `import { launch } from '@bugsee/bugsee';\nimport { bootstrapApplication } from '@angular/platform-browser';\nlaunch('mine');\nbootstrapApplication(App, appConfig);\n`, + ); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/main.ts')).not.toContain(`launch('T')`); + expect(tree.readContent('/src/main.ts').match(/launch\(/g)).toHaveLength(1); + }); + + it('does not add a handler when the app already PROVIDES BugseeErrorHandler somewhere', async () => { + const tree = await workspace(); + tree.create( + '/src/app/errors.ts', + `import { ErrorHandler } from '@angular/core';\nimport { BugseeErrorHandler } from '@bugsee/angular';\nexport const p = { provide: ErrorHandler, useClass: BugseeErrorHandler };\n`, + ); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).not.toContain('BugseeErrorHandler'); + }); + + it('an unused mention of BugseeErrorHandler (an export, a spec, a comment) is not a registration', async () => { + const tree = await workspace(); + tree.create( + '/src/app/errors.ts', + `import { BugseeErrorHandler } from '@bugsee/angular';\nexport const X = BugseeErrorHandler;\n`, + ); + tree.create('/src/app/x.spec.ts', `{ provide: ErrorHandler, useClass: BugseeErrorHandler }\n`); + tree.create('/src/app/c.ts', `// { provide: ErrorHandler, useClass: BugseeErrorHandler }\n`); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).toMatch( + /provide:\s*ErrorHandler,\s*useClass:\s*BugseeErrorHandler\b/, + ); + }); + + it("recognises an aliased ErrorHandler import as the app's own handler", async () => { + const tree = await workspace(); + tree.create( + '/src/app/mine.ts', + `import { ErrorHandler as AngularErrorHandler } from '@angular/core';\nexport const p = { provide: AngularErrorHandler, useClass: MyHandler };\n`, + ); + const before = tree.readContent('/src/app/app.config.ts'); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).toBe(before); + expect(logged('warn')).toMatch(/already provides its own ErrorHandler/); + }); + + it('a comment mentioning @bugsee/angular in main.ts does not stop the launch from being added', async () => { + const tree = await workspace(); + const main = tree.readContent('/src/main.ts'); + tree.overwrite('/src/main.ts', `// TODO: add @bugsee/angular later\n${main}`); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`); + }); + + it('a main.ts that imports a Bugsee helper but never calls launch gets the call (and no second launch import)', async () => { + const tree = await workspace(); + const main = tree.readContent('/src/main.ts'); + tree.overwrite( + '/src/main.ts', + `import { launch } from '@bugsee/bugsee';\nimport { reportAngularError } from '@bugsee/angular';\n${main}`, + ); + await run(tree, { appToken: 'T' }); + const out = tree.readContent('/src/main.ts'); + expect(out).toContain(`launch('T');`); + expect(out.match(/import \{ launch \}/g)).toHaveLength(1); + }); +}); + +describe('ng add @bugsee/angular — an app that already has its own ErrorHandler', () => { + const MINE = `{ provide: ErrorHandler, useClass: MyHandler }`; + + it('standalone: does not add a second handler (the last one wins and would silence theirs), and says what to do', async () => { + const tree = await workspace(); + const config = tree + .readContent('/src/app/app.config.ts') + .replace('providers: [', `providers: [\n ${MINE},`) + .replace(/^/, `import { ErrorHandler } from '@angular/core';\nclass MyHandler {}\n`); + tree.overwrite('/src/app/app.config.ts', config); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).toBe(config); + expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`); + expect(logged('warn')).toMatch(/already provides its own ErrorHandler/); + expect(logged('warn')).toMatch(/reportAngularError\(error\)/); + expect(logged('warn')).toMatch(/createAngularErrorHandler\(\{ delegate/); + }); + + it('NgModule: the same', async () => { + const tree = await workspace([{ name: 'demo', standalone: false }]); + const modulePath = tree.files.find((f) => /app[.-]module\.ts$/.test(f)) as string; + const module = tree + .readContent(modulePath) + .replace('providers: [', `providers: [\n ${MINE},`) + .replace(/^/, `import { ErrorHandler } from '@angular/core';\nclass MyHandler {}\n`); + tree.overwrite(modulePath, module); + await run(tree, { appToken: 'T' }); + expect(tree.readContent(modulePath)).toBe(module); + expect(logged('warn')).toMatch(/already provides its own ErrorHandler/); + }); + + it('is idempotent with it', async () => { + const tree = await workspace(); + tree.create( + '/src/app/handler.ts', + `export const p = { provide: ErrorHandler,\n useClass: MyHandler };\n`, + ); + const first = await run(tree, { appToken: 'T' }); + const before = snapshot(first); + const second = await run(first, { appToken: 'T' }); + expect(snapshot(second)).toEqual(before); + }); + + it('does not mistake another token that starts with ErrorHandler for it', async () => { + const tree = await workspace(); + tree.create('/src/app/x.ts', `export const p = { provide: ErrorHandlerLike, useClass: X };\n`); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).toContain('BugseeErrorHandler'); + }); + + it('ignores a test double in a spec file', async () => { + const tree = await workspace(); + tree.create( + '/src/app/x.spec.ts', + `TestBed.configureTestingModule({ providers: [${MINE}] });\n`, + ); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/app/app.config.ts')).toContain('BugseeErrorHandler'); + }); +}); + +describe('ng add @bugsee/angular — the build script', () => { + const setScripts = (tree: UnitTestTree, scripts: Record, indent = 2) => { + tree.overwrite('/package.json', `${JSON.stringify({ name: 'x', scripts }, null, indent)}\n`); + }; + + it('keeps a build:bugsee script the user already has, and says so', async () => { + const tree = await workspace(); + setScripts(tree, { 'build:bugsee': 'custom' }); + await run(tree, { appToken: 'T' }); + expect(json(tree, '/package.json').scripts['build:bugsee']).toBe('custom'); + expect(logged('info')).toMatch(/build:bugsee.*already/); + }); + + it('preserves the file indentation and trailing newline', async () => { + const tree = await workspace(); + setScripts(tree, { start: 'ng serve' }, 4); + await run(tree, { appToken: 'T' }); + const text = tree.readContent('/package.json'); + expect(text).toContain('\n "scripts": {'); + expect(text.endsWith('}\n')).toBe(true); + }); + + it('creates the scripts object when package.json has none', async () => { + const tree = await workspace(); + tree.overwrite('/package.json', '{"name":"x"}'); + await run(tree, { appToken: 'T' }); + expect(json(tree, '/package.json').scripts['build:bugsee']).toBeDefined(); + expect(tree.readContent('/package.json').endsWith('\n')).toBe(false); + }); + + it('warns instead of failing when there is no package.json', async () => { + const tree = await workspace(); + tree.delete('/package.json'); + await run(tree, { appToken: 'T' }); + expect(logged('warn')).toMatch(/no package\.json/); + }); +}); + +describe('ng add @bugsee/angular — what the build step cannot do, said up front', () => { + const setBuild = (tree: UnitTestTree, edit: (build: Loose) => void) => { + const ws = json(tree, '/angular.json'); + edit(ws.projects.demo.architect.build); + tree.overwrite('/angular.json', JSON.stringify(ws, null, 2)); + }; + + it('explains that subresourceIntegrity is handled', async () => { + const tree = await workspace(); + setBuild(tree, (b) => { + b.configurations.production.subresourceIntegrity = true; + }); + await run(tree, { appToken: 'T' }); + expect(logged('info')).toMatch(/subresourceIntegrity.*re-written/); + }); + + it('explains that service worker manifests are re-computed', async () => { + const tree = await workspace(); + setBuild(tree, (b) => { + b.options.serviceWorker = 'ngsw-config.json'; + }); + await run(tree, { appToken: 'T' }); + expect(logged('info')).toMatch(/serviceWorker.*re-computes/); + }); + + it('says nothing about either when neither is on', async () => { + await run(await workspace(), { appToken: 'T' }); + expect(logged()).not.toMatch(/subresourceIntegrity|serviceWorker/); + }); +}); + +describe('ng add @bugsee/angular — the webpack browser builder', () => { + it('reads the entry from `main`, sets up the same way, and names the builder in the notes', async () => { + const tree = await workspace(); + const ws = json(tree, '/angular.json'); + const build = ws.projects.demo.architect.build; + build.builder = '@angular-devkit/build-angular:browser'; + build.options.main = build.options.browser; + delete build.options.browser; + tree.overwrite('/angular.json', JSON.stringify(ws, null, 2)); + await run(tree, { appToken: 'T' }); + expect(tree.readContent('/src/main.ts')).toContain(`launch('T');`); + expect(prodOf(tree).sourceMap.scripts).toBe(true); + expect(logged('info')).toMatch(/@angular-devkit\/build-angular:browser/); + }); +}); diff --git a/packages/angular/src/schematics/ng-add/index.ts b/packages/angular/src/schematics/ng-add/index.ts new file mode 100644 index 00000000..26d95ed6 --- /dev/null +++ b/packages/angular/src/schematics/ng-add/index.ts @@ -0,0 +1,353 @@ +// `ng add @bugsee/angular` — set an Angular application up for Bugsee. Build-time only: this entry is built +// separately (CommonJS, loaded by the Angular CLI) and nothing in the runtime entry imports it, so it cannot +// reach a browser bundle. +// +// What it does, and what it deliberately does not guess: +// - angular.json: hidden script source maps in the production configuration (never overriding a setting that +// already produces maps). +// - main.ts: `launch(token)` before the bootstrap; the app config / AppModule: `BugseeErrorHandler` as the +// ErrorHandler (through Angular's own `addRootProvider`, which understands standalone and NgModule apps). +// If the bootstrap cannot be found, nothing in the source is changed and the exact lines to add are printed. +// - package.json: a `build:bugsee` script — `ng build`, then `bugsee-angular-upload` (see ../../sourcemaps). +// Angular's esbuild builder has no plugin hook, so the upload is a step after the build. +// - `.env.bugsee-build-plugin` (git-ignored) with the token for that step, when one was given. +// Every step is idempotent: running it again changes nothing. +import { + callRule, + chain, + type Rule, + type SchematicContext, + SchematicsException, + type Tree, +} from '@angular-devkit/schematics'; +import { + addRootProvider, + readWorkspace, + type TargetDefinition, + updateWorkspace, +} from '@schematics/angular/utility'; +import type { Schema } from './schema'; + +const PLACEHOLDER = 'YOUR_APP_TOKEN'; +const ENV_FILE = '.env.bugsee-build-plugin'; +const SCRIPT = 'build:bugsee'; +const SOURCE_MAP = { scripts: true, styles: false, hidden: true }; + +type Obj = Record; + +/** Whether a `sourceMap` value turns script maps on: `true`, or an object that does not turn scripts off. */ +const mapsScripts = (value: unknown): boolean => + value === true || + (typeof value === 'object' && value !== null && (value as Obj).scripts !== false); + +const quote = (text: string): string => `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`; + +/** Run a rule now and wait for it, so its failure can be handled here. */ +function apply(rule: Rule, tree: Tree, context: SchematicContext): Promise { + return new Promise((resolve, reject) => { + callRule(rule, tree, context).subscribe({ error: reject, complete: () => resolve() }); + }); +} + +interface Located { + name: string; + /** Application projects in the workspace — more than one means the script must name this one. */ + applications: number; + builder: string | undefined; + options: Obj; + production: Obj; + mainPath: string | undefined; + sourceRoot: string; +} + +async function locate(tree: Tree, requested: string | undefined): Promise { + const workspace = await readWorkspace(tree); + const apps = [...workspace.projects.entries()] + .filter(([, project]) => project.extensions.projectType === 'application') + .map(([name]) => name); + let name = requested; + if (name === undefined) { + if (apps.length === 0) { + throw new SchematicsException('The workspace has no application project to set up.'); + } + if (apps.length > 1) { + throw new SchematicsException( + `The workspace has several applications; choose one with --project (${apps.join(', ')}).`, + ); + } + name = apps[0] as string; + } + const project = workspace.projects.get(name); + if (project === undefined) { + throw new SchematicsException( + `The workspace has no project "${name}" (it has: ${[...workspace.projects.keys()].join(', ')}).`, + ); + } + const build = project.targets.get('build'); + if (build === undefined) { + throw new SchematicsException(`Project "${name}" has no "build" target.`); + } + const options = (build.options ?? {}) as Obj; + const entry = (options.browser ?? options.main) as string | undefined; + return { + name, + applications: apps.length, + builder: build.builder, + options, + production: (build.configurations?.production ?? {}) as Obj, + mainPath: entry === undefined ? undefined : `/${entry}`, + sourceRoot: `/${(project.sourceRoot ?? `${project.root}/src`).replace(/^\/+/, '')}`, + }; +} + +/** angular.json: hidden script maps in the production configuration, unless it already produces them. */ +function enableSourceMaps(project: string): Rule { + return updateWorkspace((workspace) => { + // `locate` already proved the project and its build target exist. + const build = workspace.projects.get(project)?.targets.get('build') as TargetDefinition; + const production = (build.configurations?.production ?? {}) as Obj; + const effective = 'sourceMap' in production ? production.sourceMap : build.options?.sourceMap; + if (mapsScripts(effective)) { + return; + } + const current = production.sourceMap; + const sourceMap = + typeof current === 'object' && current !== null + ? { ...(current as Obj), scripts: true, hidden: true } + : SOURCE_MAP; + build.configurations = { + ...build.configurations, + production: { ...production, sourceMap }, + } as typeof build.configurations; + }); +} + +/** The end of the last top-level import in `source`, or -1. */ +function endOfImports(source: string): number { + let end = -1; + for (const match of source.matchAll(/^import\s[^;]*?['"][^'"]+['"]\s*;?/gm)) { + end = (match.index as number) + match[0].length; + } + return end; +} + +/** Source without comments, so a mention in one is not read as code. */ +const withoutComments = (text: string): string => + text.replace(/\/\*[\s\S]*?\*\/|(^|[^:'"`])\/\/.*$/gm, '$1'); + +/** The names ErrorHandler is imported under from @angular/core in `text`: `ErrorHandler` and any `as` alias. */ +function errorHandlerNames(text: string): string[] { + const names = ['ErrorHandler']; + for (const [, list] of text.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]@angular\/core['"]/g)) { + for (const [, alias] of (list ?? '').matchAll(/\bErrorHandler\s+as\s+(\w+)/g)) { + names.push(alias as string); + } + } + return names; +} + +const BOOTSTRAP = /\bbootstrap(Application|Module|ModuleFactory)\s*\(/; + +function manualSteps(token: string): string { + return ( + ` // main.ts, before the app starts\n import { launch } from '@bugsee/angular';\n launch(${quote(token)});\n\n` + + ` // your providers (app.config.ts or AppModule)\n import { ErrorHandler } from '@angular/core';\n` + + ` import { BugseeErrorHandler } from '@bugsee/angular';\n { provide: ErrorHandler, useClass: BugseeErrorHandler }` + ); +} + +/** main.ts: launch before the bootstrap; the providers: BugseeErrorHandler. Explains instead of guessing. */ +function instrument(located: Located, token: string): Rule { + return async (tree, context) => { + const main = + located.mainPath !== undefined && tree.exists(located.mainPath) + ? located.mainPath + : undefined; + const source = main === undefined ? undefined : tree.readText(main); + if (main === undefined || source === undefined || !BOOTSTRAP.test(source)) { + context.logger.warn( + `Bugsee: could not find where the app bootstraps (looked for bootstrapApplication / bootstrapModule in ` + + `${located.mainPath ?? "the build target's entry"}), so no source was changed. Add this yourself:\n\n${manualSteps(token)}\n`, + ); + return; + } + const code = withoutComments(source); + // An existing launch CALL (not a mention of the package, not an imported helper) is left exactly as it is. + if (!(/@bugsee\//.test(code) && /\blaunch\s*\(/.test(code))) { + const call = `// Launch Bugsee before the app starts, so startup errors are captured.\nlaunch(${quote(token)});`; + const importsLaunch = /import\s*\{[^}]*\blaunch\b[^}]*\}\s*from\s*['"]@bugsee\//.test(code); + const statement = importsLaunch ? '' : `import { launch } from '@bugsee/angular';\n\n`; + const end = endOfImports(source); + tree.overwrite( + main, + end === -1 + ? `${statement}${call}\n\n${source}` + : `${source.slice(0, end)}\n${statement === '' ? '\n' : statement}${call}${source.slice(end)}`, + ); + } + let provided = false; + let foreign = false; + tree.getDir(located.sourceRoot).visit((path) => { + if (!path.endsWith('.ts')) { + return; + } + if (path.endsWith('.spec.ts')) { + return; + } + const text = withoutComments(tree.readText(path)); + const tokens = errorHandlerNames(text).join('|'); + if (new RegExp(`provide\\s*:\\s*(?:${tokens})\\b[^}]*\\bBugseeErrorHandler\\b`).test(text)) { + provided = true; + } else if (new RegExp(`provide\\s*:\\s*(?:${tokens})\\b`).test(text)) { + foreign = true; + } + }); + if (provided) { + return; + } + if (foreign) { + // Providers are last-wins: adding ours would silently replace theirs. They choose how to combine them. + context.logger.warn( + `Bugsee: your app already provides its own ErrorHandler, so BugseeErrorHandler was not added (it would replace ` + + `yours). Report from inside it instead:\n\n import { reportAngularError } from '@bugsee/angular';\n` + + ` handleError(error: unknown) { reportAngularError(error); /* then your handling */ }\n\n` + + `or wrap yours:\n\n { provide: ErrorHandler, useFactory: () => createAngularErrorHandler({ delegate: new MyHandler() }) }\n`, + ); + return; + } + try { + await apply( + addRootProvider( + located.name, + ({ code, external }) => + code`{ provide: ${external('ErrorHandler', '@angular/core')}, useClass: ${external('BugseeErrorHandler', '@bugsee/angular')} }`, + ), + tree, + context, + ); + } catch (error) { + context.logger.warn( + `Bugsee: could not register BugseeErrorHandler (${(error as Error).message}). Add it to your providers ` + + `yourself:\n\n { provide: ErrorHandler, useClass: BugseeErrorHandler } // both from '@angular/core' / '@bugsee/angular'\n`, + ); + } + }; +} + +/** package.json: the `build:bugsee` script. */ +function addBuildScript(located: Located): Rule { + return (tree, context) => { + if (!tree.exists('/package.json')) { + context.logger.warn( + `Bugsee: no package.json found, so the ${SCRIPT} script was not added. Run:\n ng build --configuration production && bugsee-angular-upload --configuration production`, + ); + return; + } + const text = tree.readText('/package.json'); + const pkg = JSON.parse(text) as { scripts?: Record }; + if (pkg.scripts?.[SCRIPT] !== undefined) { + context.logger.info(`Bugsee: the ${SCRIPT} script is already there; left as it is.`); + return; + } + const several = located.applications > 1; + pkg.scripts = { + ...pkg.scripts, + [SCRIPT]: + `ng build${several ? ` ${located.name}` : ''} --configuration production && ` + + `bugsee-angular-upload${several ? ` --project ${located.name}` : ''} --configuration production`, + }; + const indent = /^([ \t]+)"/m.exec(text)?.[1] ?? ' '; + tree.overwrite( + '/package.json', + `${JSON.stringify(pkg, null, indent)}${text.endsWith('\n') ? '\n' : ''}`, + ); + }; +} + +/** `.env.bugsee-build-plugin` with the token for the build step, git-ignored. */ +function keepToken(token: string | undefined): Rule { + return (tree, context) => { + if (token === undefined) { + return; + } + if (!tree.exists(`/${ENV_FILE}`)) { + tree.create(`/${ENV_FILE}`, `BUGSEE_APP_TOKEN=${token}\n`); + } else { + const text = tree.readText(`/${ENV_FILE}`); + const existing = /^\s*BUGSEE_APP_TOKEN\s*=\s*(.*?)\s*$/m.exec(text)?.[1]; + if (existing !== undefined && existing !== token) { + context.logger.warn( + `Bugsee: ${ENV_FILE} already has a different BUGSEE_APP_TOKEN than the one you gave, and it was left as it is. ` + + `launch() uses the token you gave, the source-map upload uses the file's: if they are not the same app, ` + + `crash reports cannot be symbolicated. Make them match.`, + ); + } + if (!/^\s*BUGSEE_APP_TOKEN\s*=/m.test(text)) { + tree.overwrite( + `/${ENV_FILE}`, + `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}BUGSEE_APP_TOKEN=${token}\n`, + ); + } + } + if (!tree.exists('/.gitignore')) { + tree.create('/.gitignore', `${ENV_FILE}\n`); + } else { + const ignored = tree.readText('/.gitignore'); + if (!ignored.split(/\r?\n/).some((line) => line.trim() === ENV_FILE)) { + tree.overwrite( + '/.gitignore', + `${ignored}${ignored.endsWith('\n') ? '' : '\n'}${ENV_FILE}\n`, + ); + } + } + }; +} + +/** Say what the build step does for this project's configuration. */ +function explain(located: Located, token: string | undefined): Rule { + return (_tree, context) => { + const effective = { ...located.options, ...located.production } as Obj; + context.logger.info( + `Bugsee: source maps are uploaded by \`npm run ${SCRIPT}\` (builder: ${located.builder ?? 'unknown'}); ` + + `plain \`ng build\` does not upload.`, + ); + if (effective.subresourceIntegrity === true) { + context.logger.info( + `Bugsee: subresourceIntegrity is on. The upload step stamps the bundles, then the integrity hashes in ` + + `index.html are re-written to match, so the page keeps loading.`, + ); + } + if (effective.serviceWorker) { + context.logger.info( + `Bugsee: serviceWorker is on. ngsw.json (one per locale) pins a SHA-1 of every file, so the upload step ` + + `re-computes those hashes after stamping and checks them; if one cannot be reconciled it restores the build and uploads nothing.`, + ); + } + if (token === undefined) { + context.logger.warn( + `Bugsee: no app token was given, so launch() has the placeholder ${PLACEHOLDER}. Put your token there, and set ` + + `BUGSEE_APP_TOKEN (or ${ENV_FILE}) wherever you run \`npm run ${SCRIPT}\`.`, + ); + } + }; +} + +export function ngAdd(options: Schema = {}): Rule { + return async (tree) => { + const located = await locate(tree, options.project); + const trimmed = options.appToken?.trim(); + const token = trimmed === undefined || trimmed === '' ? undefined : trimmed; + if (token !== undefined && /[\s"'`#\\]/.test(token)) { + throw new SchematicsException( + 'The app token must not contain whitespace, a line break, quotes, backticks, backslashes or #.', + ); + } + return chain([ + enableSourceMaps(located.name), + instrument(located, token ?? PLACEHOLDER), + addBuildScript(located), + keepToken(token), + explain(located, token), + ]); + }; +} diff --git a/packages/angular/src/schematics/ng-add/schema.json b/packages/angular/src/schematics/ng-add/schema.json new file mode 100644 index 00000000..84e148ce --- /dev/null +++ b/packages/angular/src/schematics/ng-add/schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "http://json-schema.org/schema", + "$id": "BugseeAngularNgAdd", + "title": "Bugsee ng-add options", + "type": "object", + "properties": { + "project": { + "type": "string", + "description": "The application project to set up. Defaults to the workspace's only application.", + "$default": { "$source": "projectName" } + }, + "appToken": { + "type": "string", + "description": "Your Bugsee app token. Written into the launch call and, for the build step, into .env.bugsee-build-plugin (kept out of git).", + "x-prompt": "Your Bugsee app token (press Enter to fill it in later):" + } + }, + "required": [] +} diff --git a/packages/angular/src/schematics/ng-add/schema.ts b/packages/angular/src/schematics/ng-add/schema.ts new file mode 100644 index 00000000..d86ee5b3 --- /dev/null +++ b/packages/angular/src/schematics/ng-add/schema.ts @@ -0,0 +1,7 @@ +/** Options of `ng add @bugsee/angular` (see schema.json). */ +export interface Schema { + /** The application project to set up. Default: the workspace's only application. */ + project?: string; + /** Your Bugsee app token. Empty or absent: a placeholder is written and you are told to fill it in. */ + appToken?: string; +} diff --git a/packages/angular/src/sourcemaps/bin.ts b/packages/angular/src/sourcemaps/bin.ts new file mode 100644 index 00000000..17d6754f --- /dev/null +++ b/packages/angular/src/sourcemaps/bin.ts @@ -0,0 +1,12 @@ +#!/usr/bin/env node +/* v8 ignore start -- the executable shell: the logic is in cli.ts (unit-tested); the built bin is exercised by + the real-build test (angular.real-build.test.ts), which runs in a child process coverage does not see. */ +import { runCli } from './cli'; + +process.exitCode = await runCli(process.argv.slice(2), { + cwd: process.cwd(), + env: process.env, + stdout: (message) => process.stdout.write(message), + stderr: (message) => process.stderr.write(message), +}); +/* v8 ignore stop */ diff --git a/packages/angular/src/sourcemaps/cli.test.ts b/packages/angular/src/sourcemaps/cli.test.ts new file mode 100644 index 00000000..ccaa046b --- /dev/null +++ b/packages/angular/src/sourcemaps/cli.test.ts @@ -0,0 +1,192 @@ +import { describe, expect, it, vi } from 'vitest'; +import { HELP, parseArgs, runCli } from './cli'; +import type { AngularUploadOptions, AngularUploadResult } from './upload'; + +describe('parseArgs', () => { + it('reads every option, in both the spaced and the = form', () => { + expect( + parseArgs([ + '--project', + 'demo', + '--configuration=production', + '--dist', + 'out', + '--output-path=moved', + '--app-version=1.0.0', + '--app-build', + '42', + '--endpoint', + 'https://api.test', + '--dry-run', + '--keep-maps', + '--fail-on-error', + '--strip-sources-content', + '--upload-in-development', + '--no-vcs', + ]), + ).toEqual({ + options: { + project: 'demo', + configuration: 'production', + dist: 'out', + outputPath: 'moved', + appVersion: '1.0.0', + appBuild: '42', + endpoint: 'https://api.test', + dryRun: true, + deleteMaps: false, + failOnError: true, + stripSourcesContent: true, + uploadInDevelopment: true, + vcs: false, + }, + }); + }); + + it('accepts -c for --configuration and -h for help', () => { + expect(parseArgs(['-c', 'staging'])).toEqual({ options: { configuration: 'staging' } }); + expect(parseArgs(['-h'])).toEqual({ options: {}, help: true }); + expect(parseArgs(['--help'])).toEqual({ options: {}, help: true }); + }); + + it('returns nothing for no arguments', () => { + expect(parseArgs([])).toEqual({ options: {} }); + }); + + it('rejects an unknown flag, a missing value and a stray argument', () => { + expect(() => parseArgs(['--nope'])).toThrow(/unknown option "--nope"/); + expect(() => parseArgs(['--project'])).toThrow(/--project needs a value/); + expect(() => parseArgs(['--project', '--dry-run'])).toThrow(/--project needs a value/); + expect(() => parseArgs(['stray'])).toThrow(/unexpected argument "stray"/); + expect(() => parseArgs(['--dry-run=yes'])).toThrow(/--dry-run does not take a value/); + }); + + it('does not take the token on the command line', () => { + expect(() => parseArgs(['--app-token', 'x'])).toThrow(/BUGSEE_APP_TOKEN/); + }); +}); + +describe('runCli', () => { + const io = () => { + const out: string[] = []; + const err: string[] = []; + return { + out, + err, + io: { + cwd: '/ws', + env: { BUGSEE_APP_TOKEN: 'tok' }, + stdout: (m: string) => out.push(m), + stderr: (m: string) => err.push(m), + }, + }; + }; + const uploaded = (over: Partial = {}) => + vi.fn( + async (_o: AngularUploadOptions): Promise => ({ + status: 'uploaded', + outDir: '/ws/dist/demo/browser', + configuration: 'production', + result: { injected: true, uploaded: true, deletedMaps: ['a.map', 'b.map'] }, + ...over, + }), + ); + + it('prints the help and does not upload', async () => { + const { io: i, out } = io(); + const upload = uploaded(); + expect(await runCli(['--help'], i, upload)).toBe(0); + expect(out.join('')).toBe(HELP); + expect(upload).not.toHaveBeenCalled(); + }); + + it('hands the parsed options, the working directory and the environment to the upload', async () => { + const { io: i } = io(); + const upload = uploaded(); + await runCli(['--project', 'demo', '--dry-run'], i, upload); + expect(upload).toHaveBeenCalledWith({ + project: 'demo', + dryRun: true, + cwd: '/ws', + env: { BUGSEE_APP_TOKEN: 'tok' }, + }); + }); + + it('reports what was uploaded and how many maps were removed', async () => { + const { io: i, out } = io(); + expect(await runCli([], i, uploaded())).toBe(0); + expect(out.join('')).toContain('uploaded the source maps of /ws/dist/demo/browser'); + expect(out.join('')).toContain('removed 2 local map(s)'); + }); + + it('reports a dry run as checked, and a kept-maps upload without a removal count', async () => { + const { io: i, out } = io(); + await runCli( + ['--dry-run'], + i, + uploaded({ result: { injected: true, uploaded: false, deletedMaps: [] } }), + ); + expect(out.join('')).toContain('dry run: checked the source maps'); + expect(out.join('')).not.toContain('uploaded the source maps'); + const kept = io(); + await runCli( + ['--keep-maps'], + kept.io, + uploaded({ result: { injected: true, uploaded: true, deletedMaps: [] } }), + ); + expect(kept.out.join('')).toBe('[bugsee] uploaded the source maps of /ws/dist/demo/browser.\n'); + }); + + it('says the upload did not complete when the pipeline contained a failure (already reported)', async () => { + const { io: i, out, err } = io(); + expect( + await runCli( + [], + i, + uploaded({ result: { injected: false, uploaded: false, deletedMaps: [] } }), + ), + ).toBe(0); + expect(out.join('')).toBe(''); + expect(err.join('')).toContain('did not complete'); + }); + + it('is quiet for a skipped, disabled or misconfigured run, whose notice was already printed', async () => { + for (const status of ['skipped', 'disabled', 'misconfigured'] as const) { + const { io: i, out, err } = io(); + const { result: _drop, ...rest } = (await uploaded()({})) as AngularUploadResult; + expect( + await runCli( + [], + i, + vi.fn(async () => ({ ...rest, status })), + ), + ).toBe(0); + expect(out.join('') + err.join('')).toBe(''); + } + }); + + it('exits 1 with the message on an error', async () => { + const { io: i, err } = io(); + const upload = vi.fn(async () => { + throw new Error('boom'); + }); + expect(await runCli([], i, upload)).toBe(1); + expect(err.join('')).toContain('[bugsee] boom'); + }); + + it('exits 2 on a usage error, with the help hint', async () => { + const { io: i, err } = io(); + expect(await runCli(['--nope'], i, uploaded())).toBe(2); + expect(err.join('')).toContain('unknown option'); + expect(err.join('')).toContain('--help'); + }); + + it('reports a non-Error throw', async () => { + const { io: i, err } = io(); + const upload = vi.fn(async () => { + throw 'plain'; + }); + expect(await runCli([], i, upload)).toBe(1); + expect(err.join('')).toContain('plain'); + }); +}); diff --git a/packages/angular/src/sourcemaps/cli.ts b/packages/angular/src/sourcemaps/cli.ts new file mode 100644 index 00000000..c93d8458 --- /dev/null +++ b/packages/angular/src/sourcemaps/cli.ts @@ -0,0 +1,140 @@ +// The `bugsee-angular-upload` command: argument parsing and reporting around uploadAngularSourcemaps. Kept free of +// process globals (the bin passes them in) so it is unit-tested; bin.ts is the three-line shell around it. +import { + type AngularUploadOptions, + type AngularUploadResult, + uploadAngularSourcemaps, +} from './upload'; + +export const HELP = `bugsee-angular-upload — upload the source maps of an Angular build to Bugsee. + +Run it after \`ng build\` (the \`build:bugsee\` script that \`ng add @bugsee/angular\` adds does both): + + ng build && bugsee-angular-upload + +It stamps debug-IDs into the bundles in dist//browser, uploads the maps, registers the build and +removes the local maps. The app token comes from BUGSEE_APP_TOKEN or .env.bugsee-build-plugin. + +Options + --project Application project (default: the only application in angular.json) + -c, --configuration The ng build configuration the output came from (default: the target's default) + --dist The browser output directory, when it is not where angular.json says + --output-path What you gave ng build --output-path (browser/ below it is used when present) + --app-version App version (default: BUGSEE_APP_VERSION, then package.json) + --app-build Build number (default: BUGSEE_APP_BUILD, then the CI commit) + --endpoint API endpoint (default: BUGSEE_ENDPOINT) + --dry-run Run the whole flow without uploading or deleting anything + --keep-maps Keep the local .map files after uploading + --strip-sources-content Upload maps without their embedded source + --fail-on-error Exit non-zero when the upload fails (default: warn and exit 0) + --upload-in-development Also upload from a development configuration + --no-vcs Do not capture the commit / branch + -h, --help Show this help +`; + +type Options = AngularUploadOptions; + +const VALUE_FLAGS: Record = { + '--project': 'project', + '--configuration': 'configuration', + '-c': 'configuration', + '--dist': 'dist', + '--output-path': 'outputPath', + '--app-version': 'appVersion', + '--app-build': 'appBuild', + '--endpoint': 'endpoint', +}; + +const SWITCHES: Record = { + '--dry-run': ['dryRun', true], + '--keep-maps': ['deleteMaps', false], + '--strip-sources-content': ['stripSourcesContent', true], + '--fail-on-error': ['failOnError', true], + '--upload-in-development': ['uploadInDevelopment', true], + '--no-vcs': ['vcs', false], +}; + +/** Parse argv (without the node and script entries). Throws a usage error for anything it does not know. */ +export function parseArgs(argv: readonly string[]): { options: Options; help?: true } { + const options: Record = {}; + let help = false; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] as string; + const eq = arg.startsWith('--') ? arg.indexOf('=') : -1; + const flag = eq === -1 ? arg : arg.slice(0, eq); + if (flag === '-h' || flag === '--help') { + help = true; + } else if (flag === '--app-token') { + throw new Error( + 'the app token is not taken on the command line (it would land in shell history): set BUGSEE_APP_TOKEN', + ); + } else if (flag in VALUE_FLAGS) { + const value = eq === -1 ? argv[++i] : arg.slice(eq + 1); + if (value === undefined || value.startsWith('-')) { + throw new Error(`${flag} needs a value`); + } + options[VALUE_FLAGS[flag] as string] = value; + } else if (flag in SWITCHES) { + if (eq !== -1) { + throw new Error(`${flag} does not take a value`); + } + const [key, value] = SWITCHES[flag] as [string, boolean]; + options[key] = value; + } else if (arg.startsWith('-')) { + throw new Error(`unknown option "${flag}"`); + } else { + throw new Error(`unexpected argument "${arg}"`); + } + } + return help ? { options: options as Options, help: true } : { options: options as Options }; +} + +export interface CliIo { + cwd: string; + env: Record; + stdout(message: string): void; + stderr(message: string): void; +} + +/** Run the command. Resolves to the process exit code: 0 done, 1 failed, 2 misused. */ +export async function runCli( + argv: readonly string[], + io: CliIo, + upload: (options: Options) => Promise = uploadAngularSourcemaps, +): Promise { + let parsed: { options: Options; help?: true }; + try { + parsed = parseArgs(argv); + } catch (error) { + io.stderr(`[bugsee] ${(error as Error).message}\nRun with --help for the options.\n`); + return 2; + } + if (parsed.help) { + io.stdout(HELP); + return 0; + } + try { + const out = await upload({ ...parsed.options, cwd: io.cwd, env: io.env }); + if (out.status === 'uploaded') { + if (parsed.options.dryRun === true) { + io.stdout( + `[bugsee] dry run: checked the source maps of ${out.outDir}; nothing was uploaded or removed.\n`, + ); + } else if (out.result?.uploaded === true) { + const removed = out.result.deletedMaps.length; + io.stdout( + `[bugsee] uploaded the source maps of ${out.outDir}` + + (removed > 0 ? `; removed ${removed} local map(s).\n` : '.\n'), + ); + } else { + io.stderr( + `[bugsee] the source-map upload of ${out.outDir} did not complete (see above).\n`, + ); + } + } + return 0; + } catch (error) { + io.stderr(`[bugsee] ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +} diff --git a/packages/angular/src/sourcemaps/index.ts b/packages/angular/src/sourcemaps/index.ts new file mode 100644 index 00000000..9ee54b58 --- /dev/null +++ b/packages/angular/src/sourcemaps/index.ts @@ -0,0 +1,14 @@ +// @bugsee/angular/sourcemaps — upload the source maps of an Angular build. Node-only: it is a build-time entry +// and is never imported by the runtime entry (`@bugsee/angular`), so it cannot reach a browser bundle. +export { type CliIo, HELP, parseArgs, runCli } from './cli'; +export { + type AngularOutput, + type ResolveAngularOutputOptions, + resolveAngularOutput, +} from './output'; +export { + type AngularUploadDeps, + type AngularUploadOptions, + type AngularUploadResult, + uploadAngularSourcemaps, +} from './upload'; diff --git a/packages/angular/src/sourcemaps/jsonc.test.ts b/packages/angular/src/sourcemaps/jsonc.test.ts new file mode 100644 index 00000000..c3c868f5 --- /dev/null +++ b/packages/angular/src/sourcemaps/jsonc.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest'; +import { parseJsonc } from './jsonc'; + +describe('parseJsonc', () => { + it('parses plain JSON', () => { + expect(parseJsonc('{"a":[1,2,{"b":null}]}')).toEqual({ a: [1, 2, { b: null }] }); + }); + + it('ignores line and block comments, as angular.json allows', () => { + const text = `{ + // the project + "a": 1, /* inline */ "b": 2 + /* trailing + block */ + }`; + expect(parseJsonc(text)).toEqual({ a: 1, b: 2 }); + }); + + it('leaves comment-looking text inside a string alone, including an escaped quote before it', () => { + expect(parseJsonc('{"url":"http://x/*y*/","q":"a\\"//b"}')).toEqual({ + url: 'http://x/*y*/', + q: 'a"//b', + }); + }); + + it('accepts trailing commas', () => { + expect(parseJsonc('{"a":[1,2,],}')).toEqual({ a: [1, 2] }); + }); + + it('keeps a comma that is followed by a value, and one inside a string', () => { + expect(parseJsonc('{"a":"x,]","b":[1,2]}')).toEqual({ a: 'x,]', b: [1, 2] }); + }); + + it('strips a byte-order mark', () => { + expect(parseJsonc('{"a":1}')).toEqual({ a: 1 }); + }); + + it('throws on text that is not JSON once the comments are gone', () => { + expect(() => parseJsonc('{"a":')).toThrow(); + }); + + it('treats an unterminated block comment as running to the end', () => { + expect(parseJsonc('{"a":1} /* never closed')).toEqual({ a: 1 }); + }); +}); diff --git a/packages/angular/src/sourcemaps/jsonc.ts b/packages/angular/src/sourcemaps/jsonc.ts new file mode 100644 index 00000000..f5317a88 --- /dev/null +++ b/packages/angular/src/sourcemaps/jsonc.ts @@ -0,0 +1,40 @@ +// A small JSON-with-comments reader for `angular.json`, which Angular's own tooling accepts with `//` and +// `/* */` comments and trailing commas. Reading only: the schematic edits through Angular's workspace API, +// which preserves the file. Kept here so the upload tool needs no Angular dependency at run time. + +/** Remove comments and trailing commas, leaving string contents untouched. */ +function strip(text: string): string { + let out = ''; + let i = text.charCodeAt(0) === 0xfeff ? 1 : 0; + while (i < text.length) { + const ch = text[i] as string; + if (ch === '"') { + let j = i + 1; + while (j < text.length && text[j] !== '"') { + j += text[j] === '\\' ? 2 : 1; + } + out += text.slice(i, j + 1); + i = j + 1; + } else if (ch === '/' && text[i + 1] === '/') { + while (i < text.length && text[i] !== '\n') { + i++; + } + } else if (ch === '/' && text[i + 1] === '*') { + const end = text.indexOf('*/', i + 2); + i = end === -1 ? text.length : end + 2; + } else { + out += ch; + i++; + } + } + // A comma directly before `]` or `}` (whitespace between is fine). Strings are matched first so a comma + // inside one is never touched. + return out.replace(/"(?:[^"\\]|\\.)*"|,(\s*[\]}])/g, (match, tail?: string) => + tail === undefined ? match : tail, + ); +} + +/** Parse JSON that may carry comments and trailing commas. Throws on anything else that is not JSON. */ +export function parseJsonc(text: string): unknown { + return JSON.parse(strip(text)); +} diff --git a/packages/angular/src/sourcemaps/output.test.ts b/packages/angular/src/sourcemaps/output.test.ts new file mode 100644 index 00000000..3de93cec --- /dev/null +++ b/packages/angular/src/sourcemaps/output.test.ts @@ -0,0 +1,251 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { resolveAngularOutput } from './output'; + +let cwd: string; +beforeEach(async () => { + cwd = await mkdtemp(join(tmpdir(), 'bugsee-ng-out-')); +}); +afterEach(async () => { + await rm(cwd, { recursive: true, force: true }); +}); + +const workspace = async ( + projects: Record, + extra: Record = {}, +) => { + await writeFile(join(cwd, 'angular.json'), JSON.stringify({ version: 1, projects, ...extra })); +}; + +const app = (build: unknown, over: Record = {}) => ({ + projectType: 'application', + root: '', + architect: { build }, + ...over, +}); + +describe('resolveAngularOutput', () => { + it('finds the browser directory of an esbuild application build under dist/', async () => { + await workspace({ demo: app({ builder: '@angular/build:application', options: {} }) }); + expect(resolveAngularOutput({ cwd })).toEqual({ + project: 'demo', + builder: '@angular/build:application', + layout: 'application', + configuration: undefined, + baseDir: join(cwd, 'dist', 'demo'), + browserDir: join(cwd, 'dist', 'demo', 'browser'), + serverDir: join(cwd, 'dist', 'demo', 'server'), + }); + }); + + it('treats the legacy @angular-devkit/build-angular:application builder the same way', async () => { + await workspace({ + demo: app({ + builder: '@angular-devkit/build-angular:application', + options: { outputPath: 'out/x' }, + }), + }); + const out = resolveAngularOutput({ cwd }); + expect(out.layout).toBe('application'); + expect(out.browserDir).toBe(join(cwd, 'out', 'x', 'browser')); + }); + + it('honours the object form of outputPath, including an empty browser folder', async () => { + await workspace({ + demo: app({ + builder: '@angular/build:application', + options: { outputPath: { base: 'out', browser: '', server: 'srv' } }, + }), + }); + const out = resolveAngularOutput({ cwd }); + expect(out.browserDir).toBe(join(cwd, 'out')); + expect(out.serverDir).toBe(join(cwd, 'out', 'srv')); + }); + + it('defaults the browser and server folders when the object form leaves them out', async () => { + await workspace({ + demo: app({ + builder: '@angular/build:application', + options: { outputPath: { base: 'out' } }, + }), + }); + const out = resolveAngularOutput({ cwd }); + expect(out.browserDir).toBe(join(cwd, 'out', 'browser')); + expect(out.serverDir).toBe(join(cwd, 'out', 'server')); + }); + + it('uses the outputPath of the chosen configuration over the options', async () => { + await workspace({ + demo: app({ + builder: '@angular/build:application', + options: { outputPath: 'dist/base' }, + configurations: { production: { outputPath: 'dist/prod' } }, + defaultConfiguration: 'production', + }), + }); + expect(resolveAngularOutput({ cwd }).browserDir).toBe(join(cwd, 'dist', 'prod', 'browser')); + expect(resolveAngularOutput({ cwd }).configuration).toBe('production'); + }); + + it('prefers an explicit configuration to the default, and merges a comma list in order', async () => { + await workspace({ + demo: app({ + builder: '@angular/build:application', + options: {}, + configurations: { + production: { outputPath: 'dist/prod' }, + staging: { outputPath: 'dist/stage' }, + other: {}, + }, + defaultConfiguration: 'production', + }), + }); + expect(resolveAngularOutput({ cwd, configuration: 'staging' }).baseDir).toBe( + join(cwd, 'dist', 'stage'), + ); + expect(resolveAngularOutput({ cwd, configuration: 'production,other' }).baseDir).toBe( + join(cwd, 'dist', 'prod'), + ); + expect(resolveAngularOutput({ cwd, configuration: 'production,staging' }).baseDir).toBe( + join(cwd, 'dist', 'stage'), + ); + }); + + it('ignores a configuration name the target does not define', async () => { + await workspace({ demo: app({ builder: '@angular/build:application', options: {} }) }); + expect(resolveAngularOutput({ cwd, configuration: 'nope' }).baseDir).toBe( + join(cwd, 'dist', 'demo'), + ); + }); + + it('uses the flat output of a webpack browser build, which has no browser subfolder', async () => { + await workspace({ + demo: app({ + builder: '@angular-devkit/build-angular:browser', + options: { outputPath: 'dist/legacy' }, + }), + }); + expect(resolveAngularOutput({ cwd })).toEqual({ + project: 'demo', + builder: '@angular-devkit/build-angular:browser', + layout: 'flat', + configuration: undefined, + baseDir: join(cwd, 'dist', 'legacy'), + browserDir: join(cwd, 'dist', 'legacy'), + }); + }); + + it('reads the base of an object outputPath for a flat builder, and defaults to dist/', async () => { + await workspace({ + a: app({ + builder: '@angular-devkit/build-angular:browser', + options: { outputPath: { base: 'x' } }, + }), + b: app({ builder: '@angular-devkit/build-angular:browser', options: {} }), + }); + expect(resolveAngularOutput({ cwd, project: 'a' }).browserDir).toBe(join(cwd, 'x')); + expect(resolveAngularOutput({ cwd, project: 'b' }).browserDir).toBe(join(cwd, 'dist', 'b')); + }); + + it("reads the `targets` spelling of a project's targets (Angular accepts it beside `architect`)", async () => { + await writeFile( + join(cwd, 'angular.json'), + JSON.stringify({ + projects: { + demo: { + projectType: 'application', + root: '', + targets: { + build: { builder: '@angular/build:application', options: { outputPath: 'out' } }, + }, + }, + }, + }), + ); + expect(resolveAngularOutput({ cwd }).browserDir).toBe(join(cwd, 'out', 'browser')); + }); + + it('treats a target with no builder as flat', async () => { + await workspace({ demo: app({ options: {} }) }); + const out = resolveAngularOutput({ cwd }); + expect(out.layout).toBe('flat'); + expect(out.builder).toBeUndefined(); + }); + + it('keeps an absolute outputPath as it is', async () => { + const abs = join(cwd, 'elsewhere'); + await workspace({ + demo: app({ builder: '@angular-devkit/build-angular:browser', options: { outputPath: abs } }), + }); + expect(resolveAngularOutput({ cwd }).browserDir).toBe(abs); + }); + + it('picks the only application project, ignoring libraries', async () => { + await workspace({ + lib: { projectType: 'library', root: 'projects/lib', architect: { build: {} } }, + demo: app({ builder: '@angular/build:application', options: {} }), + }); + expect(resolveAngularOutput({ cwd }).project).toBe('demo'); + }); + + it('asks for --project when several applications exist, naming them', async () => { + await workspace({ + one: app({ builder: '@angular/build:application', options: {} }), + two: app({ builder: '@angular/build:application', options: {} }), + }); + expect(() => resolveAngularOutput({ cwd })).toThrow(/--project.*one, two/); + }); + + it('uses the legacy defaultProject when several applications exist', async () => { + await workspace( + { + one: app({ builder: '@angular/build:application', options: {} }), + two: app({ builder: '@angular/build:application', options: {} }), + }, + { defaultProject: 'two' }, + ); + expect(resolveAngularOutput({ cwd }).project).toBe('two'); + }); + + it('rejects a project that is not in the workspace, listing what is', async () => { + await workspace({ demo: app({ builder: '@angular/build:application', options: {} }) }); + expect(() => resolveAngularOutput({ cwd, project: 'nope' })).toThrow(/"nope".*demo/); + }); + + it('rejects a workspace with no application and a project with no build target', async () => { + await workspace({ lib: { projectType: 'library', root: 'x', architect: {} } }); + expect(() => resolveAngularOutput({ cwd })).toThrow(/no application project/); + await workspace({ demo: { projectType: 'application', root: '', architect: {} } }); + expect(() => resolveAngularOutput({ cwd })).toThrow(/no "build" target/); + await workspace({ demo: { projectType: 'application', root: '' } }); + expect(() => resolveAngularOutput({ cwd })).toThrow(/no "build" target/); + }); + + it('says how to proceed when there is no angular.json, and when it is not parseable', async () => { + expect(() => resolveAngularOutput({ cwd })).toThrow(/angular\.json.*--dist/); + await writeFile(join(cwd, 'angular.json'), '{ nope'); + expect(() => resolveAngularOutput({ cwd })).toThrow(/could not read.*angular\.json/); + }); + + it('finds angular.json in a parent directory of the working directory', async () => { + await workspace({ demo: app({ builder: '@angular/build:application', options: {} }) }); + const nested = join(cwd, 'projects', 'demo'); + await mkdir(nested, { recursive: true }); + expect(resolveAngularOutput({ cwd: nested }).browserDir).toBe( + join(cwd, 'dist', 'demo', 'browser'), + ); + }); + + it('reads an angular.json with comments', async () => { + await writeFile( + join(cwd, 'angular.json'), + `{ // c + "projects": { "demo": { "projectType": "application", "root": "", + "architect": { "build": { "builder": "@angular/build:application", "options": {}, }, }, }, }, + }`, + ); + expect(resolveAngularOutput({ cwd }).project).toBe('demo'); + }); +}); diff --git a/packages/angular/src/sourcemaps/output.ts b/packages/angular/src/sourcemaps/output.ts new file mode 100644 index 00000000..085d659f --- /dev/null +++ b/packages/angular/src/sourcemaps/output.ts @@ -0,0 +1,140 @@ +// Where `ng build` writes its browser bundles, read from angular.json — so the upload step needs no path +// from the user. The layouts are Angular's own (checked against @angular/build 22's `application` schema): +// - `application` builders (esbuild; `@angular/build:application`, `@angular-devkit/build-angular:application`): +// `outputPath` is a string (the base) or `{ base, browser, server, media }`; the browser bundles are in +// `/` and an SSR server in `/`. +// - everything else (the webpack `browser` builder, `browser-esbuild`): `outputPath` IS the browser directory. +// The default base is `dist/`. +import { existsSync, readFileSync } from 'node:fs'; +import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { parseJsonc } from './jsonc'; + +export interface AngularOutput { + project: string; + builder: string | undefined; + layout: 'application' | 'flat'; + /** The configuration(s) the output was resolved under (`undefined`: none). */ + configuration: string | undefined; + /** The build's output root: the browser directory, plus the server directory of an SSR build. */ + baseDir: string; + /** Where the browser bundles (and `index.html`) are. */ + browserDir: string; + /** Where an SSR build's server bundles would be. Application builders only; it may not exist. */ + serverDir?: string; +} + +export interface ResolveAngularOutputOptions { + /** The directory the command runs in; angular.json is looked for here and in its parents. */ + cwd: string; + /** Application project name. Default: the only application, or the legacy `defaultProject`. */ + project?: string; + /** `ng build --configuration`: one name or a comma list. Default: the target's `defaultConfiguration`. */ + configuration?: string; +} + +type Json = Record; + +const APPLICATION_BUILDERS = new Set([ + '@angular/build:application', + '@angular-devkit/build-angular:application', +]); + +function findWorkspaceFile(cwd: string): string | undefined { + for (let dir = resolve(cwd); ; dir = dirname(dir)) { + const candidate = join(dir, 'angular.json'); + if (existsSync(candidate)) { + return candidate; + } + if (dirname(dir) === dir) { + return undefined; + } + } +} + +function readWorkspace(cwd: string): { file: string; json: Json } { + const file = findWorkspaceFile(cwd); + if (file === undefined) { + throw new Error( + `no angular.json found in ${cwd} or above. Run this from your Angular workspace, or give the build output ` + + `directory yourself with --dist.`, + ); + } + try { + return { file, json: parseJsonc(readFileSync(file, 'utf8')) as Json }; + } catch (error) { + throw new Error(`could not read ${file}: ${String(error)}`); + } +} + +function pickProject(json: Json, requested: string | undefined): string { + const projects = (json.projects ?? {}) as Record; + const names = Object.keys(projects); + if (requested !== undefined) { + if (!(requested in projects)) { + throw new Error(`the workspace has no project "${requested}" (it has: ${names.join(', ')})`); + } + return requested; + } + const apps = names.filter((name) => projects[name]?.projectType === 'application'); + if (apps.length === 0) { + throw new Error('the workspace has no application project to upload source maps for'); + } + const legacyDefault = json.defaultProject; + if (typeof legacyDefault === 'string' && apps.includes(legacyDefault)) { + return legacyDefault; + } + if (apps.length > 1) { + throw new Error( + `the workspace has several applications; pick one with --project (${apps.join(', ')})`, + ); + } + return apps[0] as string; +} + +/** Work out where `ng build` writes the browser bundles of a project, from angular.json. */ +export function resolveAngularOutput(options: ResolveAngularOutputOptions): AngularOutput { + const { file, json } = readWorkspace(options.cwd); + const root = dirname(file); + const project = pickProject(json, options.project); + const entry = (json.projects as Record)[project] as Json; + // Angular accepts `targets` as a spelling of `architect`. + const target = ((entry.architect ?? entry.targets) as Json | undefined)?.build as + | Json + | undefined; + if (target === undefined) { + throw new Error(`project "${project}" has no "build" target`); + } + const builder = target.builder as string | undefined; + const configurations = (target.configurations ?? {}) as Record; + const chosen = + options.configuration ?? + (typeof target.defaultConfiguration === 'string' ? target.defaultConfiguration : undefined); + let merged: Json = { ...(target.options as Json | undefined) }; + for (const name of chosen?.split(',') ?? []) { + merged = { ...merged, ...configurations[name.trim()] }; + } + + const layout = + builder !== undefined && APPLICATION_BUILDERS.has(builder) ? 'application' : 'flat'; + const outputPath = merged.outputPath as + | string + | { base: string; browser?: string; server?: string } + | undefined; + const base = + typeof outputPath === 'string' ? outputPath : (outputPath?.base ?? join('dist', project)); + const baseDir = isAbsolute(base) ? base : join(root, base); + if (layout === 'flat') { + return { project, builder, layout, configuration: chosen, baseDir, browserDir: baseDir }; + } + const parts: { browser?: string; server?: string } = + typeof outputPath === 'object' ? outputPath : {}; + return { + project, + builder, + layout, + configuration: chosen, + baseDir, + browserDir: join(baseDir, parts.browser ?? 'browser'), + serverDir: join(baseDir, parts.server ?? 'server'), + }; +} diff --git a/packages/angular/src/sourcemaps/server-root.test.ts b/packages/angular/src/sourcemaps/server-root.test.ts new file mode 100644 index 00000000..2a924515 --- /dev/null +++ b/packages/angular/src/sourcemaps/server-root.test.ts @@ -0,0 +1,257 @@ +import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, win32 } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { findServerRoot, isStrictlyInside } from './server-root'; +import { uploadAngularSourcemaps } from './upload'; + +let cwd: string; +beforeEach(async () => { + cwd = await mkdtemp(join(tmpdir(), 'bugsee-ng-root-')); +}); +afterEach(async () => { + await rm(cwd, { recursive: true, force: true }); +}); +const dir = (rel: string) => mkdir(join(cwd, rel), { recursive: true }); +const file = async (rel: string) => { + await dir(join(rel, '..')); + await writeFile(join(cwd, rel), 'x();'); +}; + +describe('isStrictlyInside', () => { + it('is true for a descendant, false for the directory itself, a parent, a sibling and another drive', () => { + expect(isStrictlyInside('/p/a/b', '/p')).toBe(true); + expect(isStrictlyInside('/p', '/p')).toBe(false); + expect(isStrictlyInside('/', '/p')).toBe(false); + expect(isStrictlyInside('/q/a', '/p')).toBe(false); + }); + + it('a directory whose name merely starts with two dots is inside', () => { + expect(isStrictlyInside('/p/..out/browser', '/p')).toBe(true); + }); + + it('on Windows a different drive is not inside (relative() answers with an absolute path)', () => { + expect(isStrictlyInside('D:\\out\\app', 'C:\\proj', win32)).toBe(false); + expect(isStrictlyInside('C:\\proj\\out\\app', 'C:\\proj', win32)).toBe(true); + }); +}); + +describe('findServerRoot', () => { + it('finds the output root of an application build from its browser directory', async () => { + await file('o/browser/main.js'); + await dir('o/server'); + expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toEqual({ + root: join(cwd, 'o'), + browser: join(cwd, 'o/browser'), + }); + }); + + it('finds it from a locale directory of a localized build', async () => { + await file('o/browser/fr/main.js'); + await dir('o/server/fr'); + expect(findServerRoot(join(cwd, 'o/browser/fr'), cwd)).toEqual({ + root: join(cwd, 'o'), + browser: join(cwd, 'o/browser'), + }); + }); + + it('does not take an unrelated server/ for the output root, and says it could not tell', async () => { + await file('o/dist/main.js'); + await file('o/server/server.mjs'); + const found = findServerRoot(join(cwd, 'o/dist'), cwd); + expect(found).toMatchObject({ notice: expect.stringContaining('browser') }); + expect((found as { notice: string }).notice).toMatch(/browser\/ name/); + }); + + it('a custom browser directory name (outputPath.browser) is not guessed: it is said', async () => { + await file('o/client/fr/main.js'); + await file('o/server/fr/main.server.mjs'); + expect(findServerRoot(join(cwd, 'o/client/fr'), cwd)).toMatchObject({ + notice: expect.stringContaining('o/server'), + }); + }); + + // A server/ that is not an Angular SSR output is nobody's business: no notice on every CI run. + it('says nothing about a hand-written server/ (Express beside Angular) or a backend next to a client dist', async () => { + await file('server/index.js'); // project root server/ + await file('dist/main.js'); + expect(findServerRoot(join(cwd, 'dist'), cwd)).toBeUndefined(); + await file('apps/dist/client/main.js'); + await file('apps/dist/server/app.js'); // a backend build, no Angular server markers + expect(findServerRoot(join(cwd, 'apps/dist/client'), cwd)).toBeUndefined(); + }); + + it.each([ + 'server.mjs', + 'main.server.mjs', + 'index.server.html', + 'angular-app-manifest.mjs', + 'angular-app-engine-manifest.mjs', + ])('recognises an Angular server output by %s', async (marker) => { + await file('o/client/main.js'); + await file(`o/server/${marker}`); + expect(findServerRoot(join(cwd, 'o/client'), cwd)).toMatchObject({ + notice: expect.any(String), + }); + }); + + it.skipIf(process.getuid?.() === 0)( + 'an unreadable server/ is not taken for an Angular one', + async () => { + await file('o/client/main.js'); + await file('o/server/server.mjs'); + await chmod(join(cwd, 'o/server'), 0o000); + try { + expect(findServerRoot(join(cwd, 'o/client'), cwd)).toBeUndefined(); + } finally { + await chmod(join(cwd, 'o/server'), 0o755); + } + }, + ); + + it('an unmatched server/ outside the project is not reported either', async () => { + const outside = await mkdtemp(join(tmpdir(), 'bugsee-ng-outside2-')); + try { + await mkdir(join(outside, 'server')); + await writeFile(join(outside, 'server', 'server.mjs'), ''); + await mkdir(join(outside, 'client')); + expect(findServerRoot(join(outside, 'client'), cwd)).toBeUndefined(); + } finally { + await rm(outside, { recursive: true, force: true }); + } + }); + + it('names the NEAREST unmatched server/ when two levels both have one', async () => { + await file('o/x/y/main.js'); + await file('o/x/server/server.mjs'); + await file('o/server/server.mjs'); + const found = findServerRoot(join(cwd, 'o/x/y'), cwd) as { notice: string }; + expect(found.notice).toContain(join(cwd, 'o/x/server')); + expect(found.notice).not.toContain(join(cwd, 'o/server')); + }); + + it('looks at most two levels up: a root three levels above is not found', async () => { + await file('o/browser/a/b/main.js'); + await file('o/server/server.mjs'); + expect(findServerRoot(join(cwd, 'o/browser/a/b'), cwd)).toBeUndefined(); + }); + + it('finds nothing without a server/', async () => { + await file('o/browser/fr/main.js'); + expect(findServerRoot(join(cwd, 'o/browser/fr'), cwd)).toBeUndefined(); + expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toBeUndefined(); + }); + + it('does not follow a symlinked server/, and says nothing', async () => { + await file('o/browser/main.js'); + await dir('elsewhere'); + await symlink(join(cwd, 'elsewhere'), join(cwd, 'o/server')); + expect(findServerRoot(join(cwd, 'o/browser'), cwd)).toBeUndefined(); + }); + + it('works under a directory whose name starts with two dots', async () => { + await file('..out/browser/main.js'); + await dir('..out/server'); + expect(findServerRoot(join(cwd, '..out/browser'), cwd)).toEqual({ + root: join(cwd, '..out'), + browser: join(cwd, '..out/browser'), + }); + }); + + it('says it cannot widen when the output root is the project root, instead of re-sealing the project', async () => { + await file('browser/main.js'); + await dir('server'); + const found = findServerRoot(join(cwd, 'browser'), cwd); + expect(found).toMatchObject({ notice: expect.stringContaining('server') }); + expect((found as { notice: string }).notice).toMatch(/--output-path/); + }); + + it('says so when the output root is outside the project', async () => { + const outside = await mkdtemp(join(tmpdir(), 'bugsee-ng-outside-')); + try { + await mkdir(join(outside, 'browser')); + await mkdir(join(outside, 'server')); + const found = findServerRoot(join(outside, 'browser'), cwd); + expect(found).toMatchObject({ notice: expect.stringContaining('outside') }); + } finally { + await rm(outside, { recursive: true, force: true }); + } + }); +}); + +describe('uploadAngularSourcemaps: the server pages are re-sealed whichever way the output is named', () => { + const ran = () => + vi.fn(async (_r: unknown, _d: string, _deps: Record) => ({ + injected: true, + uploaded: true, + deletedMaps: [], + })); + const base = (extra: Record, notices: string[] = []) => ({ + cwd, + appToken: 'tok', + vcs: false, + env: {}, + onNotice: (m: string) => notices.push(m), + ...extra, + }); + const build = async () => { + await file('o/browser/fr/main.js'); + await file('o/browser/fr/main.js.map'); + await dir('o/server/fr'); + }; + + it('--dist /', async () => { + await build(); + const run = ran(); + await uploadAngularSourcemaps(base({ dist: 'o/browser/fr' }), { runPluginUpload: run }); + // Only the stamped locale and ITS server counterpart: Angular emits byte-identical shared scripts into every + // locale, so re-sealing the whole root would pin never-stamped scripts of the other locales to stamped digests. + expect(run.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'o/browser/fr'), join(cwd, 'o/server/fr')], + verifyDirs: [join(cwd, 'o')], + }); + }); + + it('--dist (all locales stamped) re-seals the whole root and verifies it', async () => { + await build(); + const run = ran(); + await uploadAngularSourcemaps(base({ dist: 'o/browser' }), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'o')], + verifyDirs: [join(cwd, 'o')], + }); + }); + + it('--output-path (a flat reading of an application output)', async () => { + await build(); + const run = ran(); + await uploadAngularSourcemaps(base({ outputPath: 'o/browser' }), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o')] }); + }); + + it('--output-path with a browser/ but no server/ is browser-only, and verifies only it', async () => { + await file('b/browser/main.js'); + const run = ran(); + await uploadAngularSourcemaps(base({ outputPath: 'b' }), { runPluginUpload: run }); + const deps = run.mock.calls[0]?.[2] as { resealDirs: string[]; verifyDirs?: string[] }; + expect(deps.resealDirs).toEqual([join(cwd, 'b/browser')]); + expect(deps.verifyDirs).toEqual([join(cwd, 'b/browser')]); + }); + + it('a nested --dist with no server/ keeps the browser directory only', async () => { + await file('o/browser/fr/main.js'); + const run = ran(); + await uploadAngularSourcemaps(base({ dist: 'o/browser/fr' }), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'o/browser/fr')] }); + }); + + it('the project root as output root is said, and not widened', async () => { + await file('browser/main.js'); + await dir('server'); + const run = ran(); + const notices: string[] = []; + await uploadAngularSourcemaps(base({ dist: 'browser' }, notices), { runPluginUpload: run }); + expect(run.mock.calls[0]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'browser')] }); + expect(notices.join('\n')).toMatch(/server.*project root/s); + }); +}); diff --git a/packages/angular/src/sourcemaps/server-root.ts b/packages/angular/src/sourcemaps/server-root.ts new file mode 100644 index 00000000..f8de5384 --- /dev/null +++ b/packages/angular/src/sourcemaps/server-root.ts @@ -0,0 +1,88 @@ +// An SSR build's server modules embed the page, SRI hashes included, so re-sealing the browser directory alone leaves +// the server serving stale hashes (measured: every script blocked). When the output is named by its browser directory +// (`--dist`, or `--output-path` pointing at it) the output ROOT has to be found from it. +import { lstatSync, readdirSync } from 'node:fs'; +import * as path from 'node:path'; + +type PathApi = Pick; + +/** Whether `dir` is strictly below `root` (not equal to it, not above it, not on another drive). */ +export function isStrictlyInside(dir: string, root: string, api: PathApi = path): boolean { + const rel = api.relative(root, dir); + return rel !== '' && rel !== '..' && !rel.startsWith(`..${api.sep}`) && !api.isAbsolute(rel); +} + +const isRealDirectory = (p: string): boolean => { + try { + const info = lstatSync(p); + return info.isDirectory(); // lstat does not follow a symlink, so a symlinked server/ is not a directory here + } catch { + return false; + } +}; + +/** Files an Angular SSR build writes to its server output (`server.mjs`, or the engine manifests and server entry). */ +const ANGULAR_SERVER_FILE = + /^(?:server|main\.server)\.mjs$|^index\.server\.html$|^angular-app(?:-engine)?-manifest\.mjs$/; + +/** Whether `dir` looks like Angular's server output: a marker file in it, or in a locale directory of it. */ +export function looksLikeAngularServer(dir: string): boolean { + try { + return readdirSync(dir, { withFileTypes: true }).some((entry) => + entry.isDirectory() + ? readdirSync(path.join(dir, entry.name)).some((name) => ANGULAR_SERVER_FILE.test(name)) + : ANGULAR_SERVER_FILE.test(entry.name), + ); + } catch { + return false; + } +} + +/** How far above the output directory the root is looked for: `browser/` -> root, `browser//` -> two. */ +const MAX_LEVELS_UP = 2; + +export type ServerRoot = { root: string; browser: string } | { notice: string } | undefined; + +/** + * The output root of the SSR build `outDir` belongs to: the nearest ancestor (at most {@link MAX_LEVELS_UP} up) that + * has both a `browser/` containing `outDir` and a real (not symlinked) `server/`. Requiring the `browser/` sibling + * keeps an unrelated `server/` from becoming the scope. A root that is the project itself, or outside it, is NOT + * returned (re-sealing a project root, or someone else's directory, is not this tool's call): a notice says so. + */ +export function findServerRoot(outDir: string, cwd: string, api: PathApi = path): ServerRoot { + let root = api.dirname(outDir); + let unmatched: string | undefined; + for (let level = 0; level < MAX_LEVELS_UP; level++, root = api.dirname(root)) { + if (!isRealDirectory(api.join(root, 'server'))) { + continue; + } + const browser = api.join(root, 'browser'); + if (outDir !== browser && !isStrictlyInside(outDir, browser, api)) { + if (isStrictlyInside(root, cwd, api) && looksLikeAngularServer(api.join(root, 'server'))) { + unmatched ??= api.join(root, 'server'); + } + continue; + } + if (isStrictlyInside(root, cwd, api)) { + return { root, browser }; + } + return { + notice: + `found ${api.join(root, 'server')} next to the browser output, which embeds the page's integrity hashes, but ` + + (root === cwd + ? 'the output root is the project root' + : 'the output root is outside the project') + + `, so it was not re-sealed and a server-rendered page may keep stale hashes. Build into its own directory and ` + + `pass --output-path .`, + }; + } + if (unmatched === undefined) { + return undefined; + } + return { + notice: + `found ${unmatched} near the output, but the output is not inside a browser/ directory next to it, so it cannot ` + + `tell which is the browser output and did not re-seal the server pages, which embed the page's integrity hashes. ` + + `A custom outputPath.browser name is not supported together with server pages: build with the default browser/ name.`, + }; +} diff --git a/packages/angular/src/sourcemaps/upload.real-build.test.ts b/packages/angular/src/sourcemaps/upload.real-build.test.ts new file mode 100644 index 00000000..9ebb557c --- /dev/null +++ b/packages/angular/src/sourcemaps/upload.real-build.test.ts @@ -0,0 +1,371 @@ +// The upload step against REAL Angular 22.3 output and the REAL bugsee-cli. The two chunks in +// test/fixtures/angular-22 are byte-for-byte what `ng build` (the esbuild `application` builder, production, +// `sourceMap: { scripts: true, styles: false, hidden: true }`) wrote for an app with the Bugsee SDK, maps included — +// Angular had already put its own `//# debugId` in each. The page around them is assembled here in the exact shape +// `subresourceIntegrity: true` gives it (checked on the same build): `` + + `` + + `` + + ``; + writeFileSync(join(browser, 'index.html'), page); + let embedded: string | undefined; + if (options.ssr) { + const server = join(dir, 'dist', 'demo', 'server', 'assets-chunks'); + mkdirSync(server, { recursive: true }); + embedded = join(server, 'index.html.mjs'); + writeFileSync(embedded, `export default ${JSON.stringify(page)};\n`); + } + return { dir, browser, embedded }; +} + +describeReal('uploadAngularSourcemaps on real Angular output with subresourceIntegrity', () => { + it("stamps both bundles, keeps Angular's debug-IDs, re-seals the page, and uploads the maps", async () => { + const { dir, browser } = workspace('sri'); + const before = { + entry: readFileSync(join(browser, ENTRY), 'utf8'), + lazy: readFileSync(join(browser, LAZY), 'utf8'), + }; + const errors: unknown[] = []; + uploads = 0; + + const out = await uploadAngularSourcemaps({ + cwd: dir, + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + + expect(errors).toEqual([]); + expect(out.status).toBe('uploaded'); + expect(out.result).toMatchObject({ injected: true, uploaded: true }); + expect(uploads).toBe(2); + + // Stamped: the runtime registration is appended, and the id Angular wrote is the id that is registered. + for (const [file, original] of [ + [ENTRY, before.entry], + [LAZY, before.lazy], + ] as const) { + const stamped = readFileSync(join(browser, file), 'utf8'); + const id = /\/\/# debugId=([0-9a-f-]{36})/.exec(original)?.[1] as string; + expect(stamped.startsWith(original)).toBe(true); + expect(stamped).toContain('_bugseeDebugIds'); + expect(stamped).toContain(`_bugseeDebugIds[n]="${id}"`); + } + // Uploaded, so the client maps are gone. + expect(existsSync(join(browser, `${ENTRY}.map`))).toBe(false); + expect(existsSync(join(browser, `${LAZY}.map`))).toBe(false); + + // Re-sealed: the page pins what is now on disk, in the script tag and in the import map. + expect(await findIntegrityMismatches(browser)).toEqual([]); + const page = readFileSync(join(browser, 'index.html'), 'utf8'); + expect(page).toContain(sha384(join(browser, ENTRY))); + expect(page).toContain(sha384(join(browser, LAZY))); + }); + + it('also re-seals the copy of the page an SSR build embeds in its server modules', async () => { + const { dir, browser, embedded } = workspace('ssr', { ssr: true }); + const stale = readFileSync(embedded as string, 'utf8'); + const errors: unknown[] = []; + + await uploadAngularSourcemaps({ + cwd: dir, + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + + expect(errors).toEqual([]); + const fresh = readFileSync(embedded as string, 'utf8'); + expect(fresh).not.toBe(stale); + expect(fresh).toContain(sha384(join(browser, ENTRY))); + expect(fresh).toContain(sha384(join(browser, LAZY))); + // The module is the re-sealed page, byte for byte, as the string Angular wrote it as. + expect(fresh).toBe( + `export default ${JSON.stringify(readFileSync(join(browser, 'index.html'), 'utf8'))};\n`, + ); + }); + + // The upload path used here is a directory run without the build's emitted names (Angular reports none), so + // the directory-name fence decides what is "this build's": every map Angular wrote is deleted, and a map a + // foreign tool left under node_modules, src, test or a dot-directory is not touched. + it("deletes all of this build's maps and leaves foreign files under fenced directories alone", async () => { + const { dir, browser } = workspace('foreign'); + const foreign = [ + 'node_modules/pkg/vendor.js.map', + 'src/app.js.map', + 'test/t.js.map', + '.cache/c.js.map', + 'notes.txt', + ]; + const keyed = JSON.stringify({ + version: 3, + sources: [], + names: [], + mappings: '', + debugId: 'f0f0f0f0-0000-4000-8000-000000000000', + }); + for (const rel of foreign) { + mkdirSync(join(browser, rel, '..'), { recursive: true }); + writeFileSync(join(browser, rel), rel.endsWith('.map') ? keyed : 'keep me'); + } + const errors: unknown[] = []; + + const out = await uploadAngularSourcemaps({ + cwd: dir, + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + onNotice: () => undefined, + }); + + expect(errors).toEqual([]); + expect(out.result?.deletedMaps?.map((p) => p.slice(browser.length + 1)).sort()).toEqual( + [`${ENTRY}.map`, `${LAZY}.map`].sort(), + ); + for (const rel of foreign) { + expect(readFileSync(join(browser, rel), 'utf8')).toBe( + rel.endsWith('.map') ? keyed : 'keep me', + ); + } + }); + + // A localized build with a service worker has a manifest per locale. Each lists the SHA-1 of every file it caches + // (measured: sha1 of the bytes, keyed by path from the manifest's directory); stamping and re-sealing change + // those bytes, so they are re-computed, or the worker would treat the app as corrupt. + it('re-computes the service worker manifest of every locale', async () => { + const { dir, browser } = workspace('locales'); + const sha1 = (path: string) => createHash('sha1').update(readFileSync(path)).digest('hex'); + for (const locale of ['', 'fr']) { + const at = join(browser, locale); + mkdirSync(at, { recursive: true }); + if (locale !== '') { + cpSync(join(browser, ENTRY), join(at, ENTRY)); + cpSync(join(browser, 'index.html'), join(at, 'index.html')); + } + writeFileSync( + join(at, 'ngsw.json'), + JSON.stringify( + { + configVersion: 1, + hashTable: { + [`/${ENTRY}`]: sha1(join(at, ENTRY)), + '/index.html': sha1(join(at, 'index.html')), + }, + }, + null, + 2, + ), + ); + } + const errors: unknown[] = []; + + const out = await uploadAngularSourcemaps({ + cwd: dir, + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + + expect(errors).toEqual([]); + expect(out.status).toBe('uploaded'); + for (const locale of ['', 'fr']) { + const at = join(browser, locale); + const table = JSON.parse(readFileSync(join(at, 'ngsw.json'), 'utf8')).hashTable; + expect(table[`/${ENTRY}`]).toBe(sha1(join(at, ENTRY))); + expect(table['/index.html']).toBe(sha1(join(at, 'index.html'))); + } + expect(readFileSync(join(browser, 'fr', ENTRY), 'utf8')).toContain('_bugseeDebugIds'); + }); + + it('--dist on an SSR build re-seals the server copy of the page too (measured without this: every server digest stale)', async () => { + const { dir, browser, embedded } = workspace('dist-ssr', { ssr: true }); + const errors: unknown[] = []; + await uploadAngularSourcemaps({ + cwd: dir, + dist: browser, + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + expect(errors).toEqual([]); + const fresh = readFileSync(embedded as string, 'utf8'); + expect(fresh).toContain(sha384(join(browser, ENTRY))); + expect(fresh).toContain(sha384(join(browser, LAZY))); + }); + + // Angular emits byte-identical shared scripts into every locale. Stamping ONE locale must leave the others' pages and + // server copies pinning their never-stamped scripts: re-sealing the whole root would swap the old digest for the + // stamped one everywhere and block the other locales (measured on 22.3: a blank /fr/, "Failed to find a valid digest"). + it('--dist / stamps and re-seals that locale and its server pages only', async () => { + const dir = join(root, 'locales-one'); + const page = (file: string) => + ``; + const files: Record = {}; + for (const locale of ['en-US', 'fr']) { + for (const f of [ENTRY, `${ENTRY}.map`]) { + mkdirSync(join(dir, 'dist/browser', locale), { recursive: true }); + cpSync(join(fixtures, f), join(dir, 'dist/browser', locale, f)); + } + writeFileSync(join(dir, 'dist/browser', locale, 'index.html'), page(ENTRY)); + mkdirSync(join(dir, 'dist/server', locale), { recursive: true }); + writeFileSync( + join(dir, 'dist/server', locale, 'index.html.mjs'), + `export default ${JSON.stringify(page(ENTRY))};\n`, + ); + } + const read = (rel: string) => readFileSync(join(dir, 'dist', rel), 'utf8'); + for (const rel of [ + 'browser/en-US/index.html', + `browser/en-US/${ENTRY}`, + 'server/en-US/index.html.mjs', + ]) { + files[rel] = read(rel); + } + const errors: unknown[] = []; + + await uploadAngularSourcemaps({ + cwd: dir, + dist: 'dist/browser/fr', + appToken: 'tok', + endpoint, + vcs: false, + registerBuild: false, + env: {}, + onError: (e) => errors.push(e), + }); + + expect(errors).toEqual([]); + expect(readFileSync(join(dir, 'dist/browser/fr', ENTRY), 'utf8')).toContain('_bugseeDebugIds'); + for (const [rel, before] of Object.entries(files)) { + expect(read(rel)).toBe(before); // the unstamped locale is byte-for-byte what Angular wrote + } + const fresh = sha384(join(dir, 'dist/browser/fr', ENTRY)); + expect(read('browser/fr/index.html')).toContain(fresh); + expect(read('server/fr/index.html.mjs')).toContain(fresh); + expect(await findIntegrityMismatches(join(dir, 'dist'))).toEqual([]); + }); + + it('the guard still refuses to stamp this build WITHOUT re-sealing: the import map is seen', async () => { + const { browser } = workspace('refused'); + const errors: unknown[] = []; + const result = await uploadSourcemaps({ + outDir: browser, + appToken: 'tok', + appVersion: '1', + appBuild: '1', + endpoint, + onError: (e) => errors.push(e), + }); + expect(result.injected).toBe(false); + expect(String(errors[0])).toContain('Subresource Integrity'); + expect(readFileSync(join(browser, LAZY), 'utf8')).not.toContain('_bugseeDebugIds'); + }); +}); diff --git a/packages/angular/src/sourcemaps/upload.test.ts b/packages/angular/src/sourcemaps/upload.test.ts new file mode 100644 index 00000000..f3c2893f --- /dev/null +++ b/packages/angular/src/sourcemaps/upload.test.ts @@ -0,0 +1,571 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { uploadAngularSourcemaps } from './upload'; + +let cwd: string; +beforeEach(async () => { + cwd = await mkdtemp(join(tmpdir(), 'bugsee-ng-up-')); +}); +afterEach(async () => { + await rm(cwd, { recursive: true, force: true }); +}); + +const write = async (rel: string, body = '') => { + const full = join(cwd, rel); + await mkdir(join(full, '..'), { recursive: true }); + await writeFile(full, body); +}; + +/** A workspace with an esbuild `application` project that has been built (with a map). */ +const builtApp = async ( + opts: { ssr?: boolean; map?: boolean; ngsw?: boolean; config?: string } = {}, +) => { + await write( + 'angular.json', + JSON.stringify({ + projects: { + demo: { + projectType: 'application', + root: '', + architect: { + build: { + builder: '@angular/build:application', + options: {}, + configurations: { production: {}, development: {} }, + defaultConfiguration: opts.config ?? 'production', + }, + }, + }, + }, + }), + ); + await write('dist/demo/browser/index.html', ''); + await write('dist/demo/browser/main-ABC.js', 'x();'); + if (opts.map !== false) { + await write('dist/demo/browser/main-ABC.js.map', '{}'); + } + if (opts.ssr) { + await write('dist/demo/server/server.mjs', ''); + } + if (opts.ngsw) { + await write('dist/demo/browser/ngsw.json', '{}'); + } +}; + +const ran = (result: Record = {}) => + vi.fn(async (_resolved: unknown, _dir: string, _deps: Record) => ({ + injected: true, + uploaded: true, + deletedMaps: [], + ...result, + })); + +const base = (extra: Record = {}) => ({ + appToken: 'tok', + appVersion: '1.2.3', + appBuild: '9', + vcs: false, + env: {}, + ...extra, +}); + +describe('uploadAngularSourcemaps', () => { + it('uploads the browser directory, stamping through the re-seal path', async () => { + await builtApp(); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, onNotice: (m: string) => notices.push(m) }), + { + runPluginUpload, + }, + ); + expect(out.status).toBe('uploaded'); + expect(out.outDir).toBe(join(cwd, 'dist', 'demo', 'browser')); + const [resolved, dir, deps] = runPluginUpload.mock.calls[0] as [ + Record, + string, + Record, + ]; + expect(dir).toBe(join(cwd, 'dist', 'demo', 'browser')); + expect(resolved).toMatchObject({ + appToken: 'tok', + appVersion: '1.2.3', + appBuild: '9', + projectRoot: cwd, + enabled: true, + }); + expect(deps).toMatchObject({ + resealSri: true, + resealDirs: [join(cwd, 'dist', 'demo', 'browser')], + bundler: { isProduction: true, configuration: 'production' }, + }); + expect(notices).toEqual([]); + }); + + it("names this build's own files, so foreign files under fenced directories are never deleted", async () => { + await builtApp(); + await write('dist/demo/browser/assets/img/logo.png', 'x'); + await write('dist/demo/browser/node_modules/p/v.js.map', '{}'); + await write('dist/demo/browser/src/a.js.map', '{}'); + await write('dist/demo/browser/test/t.js.map', '{}'); + await write('dist/demo/browser/.cache/c.js.map', '{}'); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd }), { runPluginUpload }); + const own = (runPluginUpload.mock.calls[0]?.[2] as { ownFiles?: string[] }).ownFiles?.sort(); + expect(own).toEqual( + ['assets/img/logo.png', 'index.html', 'main-ABC.js', 'main-ABC.js.map'].sort(), + ); + }); + + it('re-seals across the whole output root when the build has a server, which embeds the page', async () => { + await builtApp({ ssr: true }); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd }), { runPluginUpload }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'dist', 'demo')], + }); + }); + + it('takes the directory from --dist and ignores angular.json', async () => { + await write('out/main.js', 'x();'); + await write('out/main.js.map', '{}'); + const runPluginUpload = ran(); + const out = await uploadAngularSourcemaps(base({ cwd, dist: 'out' }), { runPluginUpload }); + expect(out.outDir).toBe(join(cwd, 'out')); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'out')], + bundler: { isProduction: true }, + }); + }); + + it('--dist on an SSR build re-seals the whole output root: the server modules embed the page', async () => { + await write('custom/app/browser/main.js', 'x();'); + await write('custom/app/browser/main.js.map', '{}'); + await write('custom/app/server/server.mjs', ''); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd, dist: 'custom/app/browser' }), { runPluginUpload }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'custom', 'app')], + }); + }); + + it('--dist: a sibling server/ outside the project is not pulled in', async () => { + const outside = await mkdtemp(join(tmpdir(), 'bugsee-ng-out-')); + try { + await mkdir(join(outside, 'browser'), { recursive: true }); + await mkdir(join(outside, 'server')); + await writeFile(join(outside, 'browser', 'main.js'), 'x();'); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd, dist: join(outside, 'browser') }), { + runPluginUpload, + }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(outside, 'browser')], + }); + } finally { + await rm(outside, { recursive: true, force: true }); + } + }); + + it('--dist directly under the project root never re-seals the project root', async () => { + await write('browser/main.js', 'x();'); + await write('server/server.mjs', ''); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd, dist: 'browser' }), { runPluginUpload }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'browser')], + }); + }); + + it('--dist whose sibling is not named server/ stays browser-only', async () => { + await write('x/browser/main.js', 'x();'); + await write('x/other/a.mjs', ''); + const runPluginUpload = ran(); + await uploadAngularSourcemaps(base({ cwd, dist: 'x/browser' }), { runPluginUpload }); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'x', 'browser')], + }); + }); + + it('reads the token and version from the environment and the env file, like the bundler plugins', async () => { + await builtApp(); + await write('.env.bugsee-build-plugin', 'BUGSEE_APP_TOKEN=from-file\n'); + const runPluginUpload = ran(); + await uploadAngularSourcemaps( + { cwd, vcs: false, env: { BUGSEE_APP_VERSION: '4.5.6' } }, + { runPluginUpload }, + ); + expect(runPluginUpload.mock.calls[0]?.[0]).toMatchObject({ + appToken: 'from-file', + appVersion: '4.5.6', + }); + }); + + it('reports a problem with the env file once, through onNotice', async () => { + await builtApp(); + await write('.env.bugsee-build-plugin', '￾'); + const notices: string[] = []; + await uploadAngularSourcemaps(base({ cwd, onNotice: (m: string) => notices.push(m) }), { + runPluginUpload: ran(), + }); + expect(notices).toHaveLength(1); + expect(notices[0]).toMatch(/^\[bugsee\] /); + }); + + it('does nothing, and says so, without a token', async () => { + await builtApp(); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + { cwd, vcs: false, env: {}, onNotice: (m) => notices.push(m) }, + { runPluginUpload }, + ); + expect(out.status).toBe('disabled'); + expect(runPluginUpload).not.toHaveBeenCalled(); + expect(notices.join('\n')).toContain('BUGSEE_APP_TOKEN'); + }); + + it('is a no-op without a token even where the output cannot be located (a contributor build with no secret)', async () => { + const notices: string[] = []; + // No angular.json at all. + const none = await uploadAngularSourcemaps( + { cwd, vcs: false, env: {}, onNotice: (m) => notices.push(m) }, + { runPluginUpload: ran() }, + ); + expect(none.status).toBe('disabled'); + // Several applications and no --project. + await write( + 'angular.json', + JSON.stringify({ + projects: { + one: { projectType: 'application', root: '', architect: { build: {} } }, + two: { projectType: 'application', root: '', architect: { build: {} } }, + }, + }), + ); + const several = await uploadAngularSourcemaps( + { cwd, vcs: false, env: {}, onNotice: (m) => notices.push(m) }, + { runPluginUpload: ran() }, + ); + expect(several.status).toBe('disabled'); + expect(notices.filter((m) => m.includes('BUGSEE_APP_TOKEN'))).toHaveLength(2); + }); + + it('is silent when disabled on purpose', async () => { + await builtApp(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, disabled: true, onNotice: (m: string) => notices.push(m) }), + { + runPluginUpload: ran(), + }, + ); + expect(out.status).toBe('disabled'); + expect(notices).toEqual([]); + }); + + describe('a build whose output cannot be found', () => { + const noDist = async () => + write( + 'angular.json', + JSON.stringify({ + projects: { + demo: { + projectType: 'application', + root: '', + architect: { build: { builder: '@angular/build:application' } }, + }, + }, + }), + ); + const run = (extra: Record, notices: string[] = []) => + uploadAngularSourcemaps(base({ cwd, onNotice: (m: string) => notices.push(m), ...extra }), { + runPluginUpload: ran(), + }); + + it('missing output directory: says which build to run and how to point at another, exits cleanly', async () => { + await noDist(); + const notices: string[] = []; + const out = await run({}, notices); + expect(out.status).toBe('misconfigured'); + expect(notices.join('\n')).toMatch( + /dist.*demo.*browser.*ng build.*--output-path.*Nothing was uploaded/s, + ); + }); + + it('no angular.json, several applications, an unparseable angular.json: each said, none thrown', async () => { + const notices: string[] = []; + expect((await run({}, notices)).status).toBe('misconfigured'); + await write( + 'angular.json', + JSON.stringify({ + projects: { + one: { projectType: 'application', root: '', architect: { build: {} } }, + two: { projectType: 'application', root: '', architect: { build: {} } }, + }, + }), + ); + expect((await run({}, notices)).status).toBe('misconfigured'); + await write('angular.json', '{ nope'); + expect((await run({}, notices)).status).toBe('misconfigured'); + expect(notices).toHaveLength(3); + expect(notices[0]).toMatch(/--output-path/); + }); + + it('under failOnError each of them throws', async () => { + await expect(run({ failOnError: true })).rejects.toThrow(/angular\.json/); + await noDist(); + await expect(run({ failOnError: true })).rejects.toThrow(/ng build/); + }); + + it('outputPath { browser: "" } on an SSR build (server/ inside the browser directory) is refused: it would stamp the server', async () => { + await write( + 'angular.json', + JSON.stringify({ + projects: { + demo: { + projectType: 'application', + root: '', + architect: { + build: { + builder: '@angular/build:application', + options: { outputPath: { base: 'dist/app', browser: '' } }, + }, + }, + }, + }, + }), + ); + await write('dist/app/main.js', 'x();'); + await write('dist/app/server/server.mjs', ''); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, onNotice: (m: string) => notices.push(m) }), + { runPluginUpload }, + ); + expect(out.status).toBe('misconfigured'); + expect(runPluginUpload).not.toHaveBeenCalled(); + expect(notices.join('\n')).toMatch(/server.*inside.*browser/s); + }); + + it('the same layout WITHOUT a server output is fine', async () => { + await write( + 'angular.json', + JSON.stringify({ + projects: { + demo: { + projectType: 'application', + root: '', + architect: { + build: { + builder: '@angular/build:application', + options: { outputPath: { base: 'dist/app', browser: '' } }, + }, + }, + }, + }, + }), + ); + await write('dist/app/main.js', 'x();'); + await write('dist/app/main.js.map', '{}'); + const out = await uploadAngularSourcemaps(base({ cwd }), { runPluginUpload: ran() }); + expect(out.status).toBe('uploaded'); + }); + + it('--dist naming a FILE is a misconfiguration said, not a crash', async () => { + await write('a-file', 'x'); + const notices: string[] = []; + const out = await run({ dist: 'a-file' }, notices); + expect(out.status).toBe('misconfigured'); + expect(notices.join('\n')).toMatch(/not a directory/); + }); + + it('--output-path of a custom-browser build (client/ beside server/) is refused: it would stamp the server', async () => { + await write('o/client/main.js', 'x();'); + await write('o/server/server.mjs', ''); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, outputPath: 'o', onNotice: (m: string) => notices.push(m) }), + { runPluginUpload }, + ); + expect(out.status).toBe('misconfigured'); + expect(runPluginUpload).not.toHaveBeenCalled(); + expect(notices.join('\n')).toMatch(/--dist/); + }); + + it('the project root as output root with SRI pins in the browser pages is refused: the server copies cannot be re-sealed', async () => { + await write('browser/main.js', 'x();'); + await write('browser/index.html', ''); + await write('server/server.mjs', ''); + const runPluginUpload = ran(); + const out = await uploadAngularSourcemaps(base({ cwd, dist: 'browser' }), { + runPluginUpload, + }); + expect(out.status).toBe('misconfigured'); + expect(runPluginUpload).not.toHaveBeenCalled(); + }); + + it('the project root as output root WITHOUT pins is only said, and still uploads', async () => { + await write('browser/main.js', 'x();'); + await write('server/server.mjs', ''); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, dist: 'browser', onNotice: (m: string) => notices.push(m) }), + { runPluginUpload }, + ); + expect(out.status).toBe('uploaded'); + expect(notices.join('\n')).toMatch(/project root/); + }); + + it('--output-path points at the base of an application build, and at a flat one', async () => { + await write('moved/browser/main.js', 'x();'); + await write('moved/browser/main.js.map', '{}'); + await write('moved/server/server.mjs', ''); + await write('flat/main.js', 'x();'); + await write('flat/main.js.map', '{}'); + const runPluginUpload = ran(); + const a = await uploadAngularSourcemaps(base({ cwd, outputPath: 'moved' }), { + runPluginUpload, + }); + expect(a.outDir).toBe(join(cwd, 'moved', 'browser')); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ + resealDirs: [join(cwd, 'moved')], + }); + const b = await uploadAngularSourcemaps(base({ cwd, outputPath: 'flat' }), { + runPluginUpload, + }); + expect(b.outDir).toBe(join(cwd, 'flat')); + expect(runPluginUpload.mock.calls[1]?.[2]).toMatchObject({ resealDirs: [join(cwd, 'flat')] }); + }); + + it('--output-path that does not exist is misconfigured too, and a tokenless run still no-ops', async () => { + const out = await run({ outputPath: 'nowhere' }); + expect(out.status).toBe('misconfigured'); + const none = await uploadAngularSourcemaps( + { cwd, vcs: false, env: {}, outputPath: 'nowhere', onNotice: () => undefined }, + { runPluginUpload: ran() }, + ); + expect(none).toMatchObject({ status: 'disabled', outDir: join(cwd, 'nowhere') }); + }); + }); + + it('stamps a build with service worker manifests, one per locale: it re-computes them, it does not refuse', async () => { + await builtApp({ ngsw: true }); + await write('dist/demo/browser/fr/ngsw.json', '{}'); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, onNotice: (m: string) => notices.push(m) }), + { runPluginUpload }, + ); + expect(out.status).toBe('uploaded'); + expect(runPluginUpload).toHaveBeenCalledTimes(1); + expect(notices).toEqual([]); + }); + + it('says so when the build has no source maps, and still runs (the CLI tolerates an empty directory)', async () => { + await builtApp({ map: false }); + const runPluginUpload = ran(); + const notices: string[] = []; + await uploadAngularSourcemaps(base({ cwd, onNotice: (m: string) => notices.push(m) }), { + runPluginUpload, + }); + expect(notices.join('\n')).toMatch(/no source maps.*sourceMap/s); + expect(runPluginUpload).toHaveBeenCalledTimes(1); + }); + + it('finds a source map in a subdirectory, but not inside node_modules', async () => { + await builtApp({ map: false }); + await write('dist/demo/browser/assets/x.js.map', '{}'); + await write('dist/demo/browser/node_modules/y/z.js.map', '{}'); + const notices: string[] = []; + await uploadAngularSourcemaps(base({ cwd, onNotice: (m: string) => notices.push(m) }), { + runPluginUpload: ran(), + }); + expect(notices).toEqual([]); + await rm(join(cwd, 'dist/demo/browser/assets'), { recursive: true }); + await uploadAngularSourcemaps(base({ cwd, onNotice: (m: string) => notices.push(m) }), { + runPluginUpload: ran(), + }); + expect(notices.join('\n')).toMatch(/no source maps/); + }); + + it('skips a development configuration unless asked, as the other plugins do', async () => { + await builtApp({ config: 'development' }); + const runPluginUpload = ran(); + const notices: string[] = []; + const out = await uploadAngularSourcemaps( + base({ cwd, onNotice: (m: string) => notices.push(m) }), + { + runPluginUpload, + }, + ); + expect(out.status).toBe('skipped'); + expect(runPluginUpload).not.toHaveBeenCalled(); + expect(notices.join('\n')).toMatch(/development/); + const forced = await uploadAngularSourcemaps(base({ cwd, uploadInDevelopment: true }), { + runPluginUpload, + }); + expect(forced.status).toBe('uploaded'); + expect(runPluginUpload.mock.calls[0]?.[2]).toMatchObject({ bundler: { isProduction: false } }); + }); + + it('passes the project and configuration to the output lookup', async () => { + await builtApp(); + const out = await uploadAngularSourcemaps( + base({ cwd, project: 'demo', configuration: 'development', uploadInDevelopment: true }), + { + runPluginUpload: ran(), + }, + ); + expect(out.configuration).toBe('development'); + }); + + it('returns what the upload reported', async () => { + await builtApp(); + const out = await uploadAngularSourcemaps(base({ cwd }), { + runPluginUpload: ran({ uploaded: false, injected: false }), + }); + expect(out.status).toBe('uploaded'); + expect(out.result).toMatchObject({ uploaded: false, injected: false }); + }); + + it('defaults the working directory to the process one, and the environment to process.env', async () => { + await builtApp(); + const spy = vi.spyOn(process, 'cwd').mockReturnValue(cwd); + try { + const runPluginUpload = ran(); + await uploadAngularSourcemaps({ vcs: false, appToken: 'tok' }, { runPluginUpload }); + expect(runPluginUpload.mock.calls[0]?.[1]).toBe(join(cwd, 'dist', 'demo', 'browser')); + } finally { + spy.mockRestore(); + } + }); + + it('does not look for source maps deeper than a build writes them', async () => { + await builtApp({ map: false }); + await write('dist/demo/browser/a/b/c/d/deep.js.map', '{}'); + const notices: string[] = []; + await uploadAngularSourcemaps(base({ cwd, onNotice: (m: string) => notices.push(m) }), { + runPluginUpload: ran(), + }); + expect(notices.join('\n')).toMatch(/no source maps/); + }); + + it('prints notices through console.warn when no sink is given', async () => { + await builtApp({ map: false }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + await uploadAngularSourcemaps(base({ cwd }), { runPluginUpload: ran() }); + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/^\[bugsee\] no source maps/)); + } finally { + warn.mockRestore(); + } + }); +}); diff --git a/packages/angular/src/sourcemaps/upload.ts b/packages/angular/src/sourcemaps/upload.ts new file mode 100644 index 00000000..5b3fad80 --- /dev/null +++ b/packages/angular/src/sourcemaps/upload.ts @@ -0,0 +1,292 @@ +// `@bugsee/angular/sourcemaps` — upload an Angular build's source maps. A post-build step, because Angular's +// esbuild application builder has no plugin hook; it reuses @bugsee/bundler-plugin-core's pipeline (inject +// debug-IDs with `bugsee-cli`, upload the maps, register the build, delete the client maps) and adds only what +// is Angular's: where the output is, and Subresource Integrity. +// +// SRI. With `subresourceIntegrity: true` Angular writes a hash of every script into `index.html` — as tags, and +// (esbuild builder, Angular 21+) as an import map's `integrity` table that pins every lazy chunk — and, for SSR, +// into the copy of that page it embeds in the server modules; the webpack builder also keeps the lazy chunks' +// hashes in its runtime chunk. Stamping the scripts afterwards changes their bytes, so every digest of a changed +// script is re-written wherever it appears (`resealSri`, bundler-plugin-core), and a build that cannot be re-sealed +// is restored. Measured on real @angular/build 22.3 and build-angular 19.2 builds; see docs/design/source-maps.md §7.1. +import { existsSync, readdirSync, statSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; +import { + type BugseePluginOptions, + type EnvRecord, + findSriProtectedScripts, + isFencedPath, + loadBuildPluginEnv, + mergeBuildPluginEnv, + type PluginRunResult, + type ResolvedPluginOptions, + resolvePluginOptions, + runPluginUpload, +} from '@bugsee/bundler-plugin-core'; +import { type AngularOutput, resolveAngularOutput } from './output'; +import { findServerRoot, isStrictlyInside, looksLikeAngularServer } from './server-root'; + +export interface AngularUploadOptions extends BugseePluginOptions { + /** Workspace directory (angular.json is looked for here and above). Default: the working directory. */ + cwd?: string; + /** Application project. Default: the only application in the workspace. */ + project?: string; + /** The `ng build` configuration the output came from. Default: the build target's default. */ + configuration?: string; + /** The browser output directory, when it is not where angular.json says (skips the angular.json lookup). */ + dist?: string; + /** What `ng build --output-path` was given: the output base (its `browser/` is used when present). Skips the lookup. */ + outputPath?: string; + /** Environment to read BUGSEE_* from. Default: `process.env`, plus `.env.bugsee-build-plugin`. */ + env?: EnvRecord; +} + +export interface AngularUploadResult { + /** + * `uploaded`: the pipeline ran (its result says how far it got — a contained failure is reported, not thrown). + * `disabled`: no token or `disabled: true`. `skipped`: a development build. `misconfigured`: the output could + * not be found (said; thrown under `failOnError`). + */ + status: 'uploaded' | 'disabled' | 'skipped' | 'misconfigured'; + outDir: string; + configuration: string | undefined; + result?: PluginRunResult; +} + +export interface AngularUploadDeps { + runPluginUpload?: ( + resolved: ResolvedPluginOptions, + outDir: string, + deps: NonNullable[2]>, + ) => Promise; +} + +/** Whether `dir` holds at least one `.map`, looking a few levels down and never inside `node_modules`. */ +function hasSourceMaps(dir: string, depth = 0): boolean { + if (depth > 3) { + return false; + } + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.isDirectory()) { + if (entry.name !== 'node_modules' && hasSourceMaps(join(dir, entry.name), depth + 1)) { + return true; + } + } else if (entry.name.endsWith('.map')) { + return true; + } + } + return false; +} + +/** + * Every file under `dir` that is not inside a fenced directory (`node_modules`, `src`, `test`, a dot-directory), + * relative to it. Angular reports no list of what it emitted, and cleans its output directory before a build, so + * what is outside the fence IS this build's. Naming them makes the deletion identity-based: a keyed map a foreign + * tool left in a fenced directory is uploaded with the directory but never deleted. + */ +function ownFilesOf(dir: string): string[] { + const found: string[] = []; + const walk = (current: string, level: number): void => { + for (const entry of readdirSync(current, { withFileTypes: true })) { + const full = join(current, entry.name); + if (entry.isDirectory()) { + if (level < 8) { + walk(full, level + 1); + } + } else if (!isFencedPath(relative(dir, full))) { + found.push(relative(dir, full)); + } + } + }; + walk(dir, 0); + return found; +} + +/** Upload the source maps of an Angular build. Never throws for an upload failure unless `failOnError` is set. */ +export async function uploadAngularSourcemaps( + options: AngularUploadOptions, + deps: AngularUploadDeps = {}, +): Promise { + const cwd = resolve(options.cwd ?? process.cwd()); + const say = (message: string): void => { + const text = `[bugsee] ${message}`; + if (options.onNotice !== undefined) { + options.onNotice(text); + } else { + console.warn(text); + } + }; + const file = options.disabled ? { values: {} } : loadBuildPluginEnv(cwd); + if ('problem' in file && file.problem !== undefined) { + say(file.problem); + } + const env = mergeBuildPluginEnv(options.env ?? (process.env as EnvRecord), file.values); + const resolved = resolvePluginOptions( + { ...options, projectRoot: options.projectRoot ?? cwd }, + env, + ); + + if (!resolved.enabled) { + // Before the output is looked up: a build with no token (a contributor's PR, no secrets) is a no-op, and must + // stay one when angular.json cannot be read or names several applications. + if (!options.disabled) { + say('no app token (BUGSEE_APP_TOKEN): nothing was uploaded.'); + } + return { + status: 'disabled', + outDir: + options.dist !== undefined + ? resolve(cwd, options.dist) + : options.outputPath !== undefined + ? resolve(cwd, options.outputPath) + : '', + configuration: options.configuration, + }; + } + // Where the output is. A problem here is a misconfiguration of THIS step (no angular.json, several applications, a + // moved output path, ng build not run), not a failed upload: it must not fail a pipeline whose build succeeded, + // so it is said and the step stops, unless `failOnError` asks for the strict reading. + const misconfigured = (message: string, outDir: string, configuration?: string) => { + if (resolved.failOnError) { + throw new Error(message); + } + say(`${message} Nothing was uploaded.`); + return { status: 'misconfigured' as const, outDir, configuration }; + }; + let located: AngularOutput | undefined; + let outDir: string; + // The output ROOT whose pages must be re-sealed: an SSR build's server modules embed the page. + let resealRoot: string | undefined; + // The browser directory of that root (its name is not always `browser`). + let rootBrowser: string | undefined; + // An SSR output root that could not be located safely: its server copies of the page are not re-sealed. + let unsafeNotice: string | undefined; + const probeServerRoot = (): void => { + const found = findServerRoot(outDir, cwd); + if (found !== undefined && 'root' in found) { + resealRoot = found.root; + rootBrowser = found.browser; + } else if (found !== undefined) { + unsafeNotice = found.notice; // said if the run goes on, part of the refusal if it cannot + } + }; + if (options.dist !== undefined) { + outDir = resolve(cwd, options.dist); + probeServerRoot(); + } else if (options.outputPath !== undefined) { + // `ng build --output-path `: the base of an application build (browser/ and server/ below it), or a + // browser directory itself. + const base = resolve(cwd, options.outputPath); + if (existsSync(join(base, 'browser'))) { + outDir = join(base, 'browser'); + resealRoot = existsSync(join(base, 'server')) ? base : undefined; + rootBrowser = outDir; + } else { + outDir = base; + if (looksLikeAngularServer(join(base, 'server'))) { + // `` holds the server beside a client directory with another name: stamping it would stamp the server. + return misconfigured( + `${base} holds an Angular server output beside its browser output, and the browser directory is not named ` + + `browser/, so the whole of it would be stamped. Give the browser directory itself with --dist.`, + base, + options.configuration, + ); + } + probeServerRoot(); + } + } else { + try { + located = resolveAngularOutput({ + cwd, + ...(options.project !== undefined ? { project: options.project } : {}), + ...(options.configuration !== undefined ? { configuration: options.configuration } : {}), + }); + } catch (error) { + return misconfigured( + `${(error as Error).message}. If you built to a different directory, give it with --output-path (or --dist).`, + '', + options.configuration, + ); + } + outDir = located.browserDir; + if ( + located.serverDir !== undefined && + existsSync(located.serverDir) && + isStrictlyInside(located.serverDir, outDir) + ) { + // `outputPath.browser: ''` puts the browser output in the base, with server/ below it: injecting the directory + // would stamp the server bundles as browser code and upload their maps as browser maps. + return misconfigured( + `the server output ${located.serverDir} is inside the browser output ${outDir} (outputPath.browser is empty), ` + + `so stamping the browser output would stamp the server too. Give the browser output its own directory ` + + `(the default browser/).`, + outDir, + located.configuration, + ); + } + rootBrowser = outDir; + resealRoot = + located.serverDir !== undefined && existsSync(located.serverDir) + ? located.baseDir + : undefined; + } + const configuration = located?.configuration ?? options.configuration; + + if (!existsSync(outDir)) { + return misconfigured( + `the build output ${outDir} does not exist. Run \`ng build\` first (this step uploads what it wrote); if you ` + + `built to a different directory, give it with --output-path (or --dist).`, + outDir, + configuration, + ); + } + if (!statSync(outDir).isDirectory()) { + return misconfigured(`the build output ${outDir} is not a directory.`, outDir, configuration); + } + if (unsafeNotice !== undefined) { + if ((await findSriProtectedScripts(outDir)).length > 0) { + // The browser pages pin script hashes and the server copies of them cannot be re-sealed: stamping would leave + // server-rendered pages pinning the old hashes (every script blocked). + return misconfigured( + `${unsafeNotice} The browser pages pin script hashes, so nothing was stamped.`, + outDir, + configuration, + ); + } + say(unsafeNotice); + } + const isProduction = !(configuration?.split(',').includes('development') ?? false); + if (!isProduction && !resolved.uploadInDevelopment) { + say( + 'development configuration: nothing was uploaded, and any source maps on disk were left in place. Set ' + + '`uploadInDevelopment: true` (--upload-in-development) to upload from it too.', + ); + return { status: 'skipped', outDir, configuration }; + } + if (!hasSourceMaps(outDir)) { + say( + `no source maps found in ${outDir}. Enable them for this build ("sourceMap": { "scripts": true, ` + + `"styles": false, "hidden": true } in angular.json), or nothing can be symbolicated.`, + ); + } + + const run = deps.runPluginUpload ?? runPluginUpload; + const result = await run(resolved, outDir, { + // The re-seal (digest snapshot, spill, swap, verify) runs only when a page pins a script hash or a service worker + // manifest exists; then inject runs with --allow-sri and the hashes are re-written. Otherwise it costs nothing. + resealSri: true, + // The server modules of an SSR build embed the page, hashes included. + resealDirs: + resealRoot === undefined || outDir === rootBrowser + ? [resealRoot ?? outDir] + : // One locale of several: stamp and re-seal only it and ITS server pages. Angular emits byte-identical + // shared scripts into every locale, so re-sealing the whole root would pin the other locales' never-stamped + // scripts to stamped digests. + [outDir, join(resealRoot, 'server', relative(rootBrowser as string, outDir))], + // Verified across the whole output root: a pin anywhere that no longer matches its file is a failure. + verifyDirs: [resealRoot ?? outDir], + bundler: { isProduction, ...(configuration !== undefined ? { configuration } : {}) }, + ownFiles: ownFilesOf(outDir), + }); + return { status: 'uploaded', outDir, configuration, ...(result !== undefined ? { result } : {}) }; +} diff --git a/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js b/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js new file mode 100644 index 00000000..bff5c21d --- /dev/null +++ b/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js @@ -0,0 +1,19 @@ +import { u as el, c as Ip, l as Sp, d as tl } from './main-DNKCXA7T.js'; + +var s = class a { + static ɵfac = (e) => new (e || a)(); + static ɵcmp = Ip({ + type: a, + selectors: [[`app-lazy`]], + decls: 2, + vars: 0, + consts: [[`id`, `lazy`]], + template: (e, m) => { + e & 1 && (el(0, `p`, 0), Sp(1, `lazy-ready`), tl()); + }, + encapsulation: 2, + }); +}; + +export { s as Lazy }; +//# debugId=9f74a859-8fdd-51b3-ba40-449831d3c20a diff --git a/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js.map b/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js.map new file mode 100644 index 00000000..3e80b97c --- /dev/null +++ b/packages/angular/test/fixtures/angular-22/chunk-BE0WtcF2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chunk-BE0WtcF2.js","names":["Lazy","_Lazy","rf","ctx","ɵɵdomElementStart","ɵɵtext","ɵɵdomElementEnd","\\u0275fac","\\u0275cmp","t"],"sources":["../src/app/lazy.ts"],"sourcesContent":["import { Component } from '@angular/core';\n\n@Component({ selector: 'app-lazy', template: '

lazy-ready

' })\nexport class Lazy {}\n"],"mappings":"A,gEAGM,IAAOA,EAAP,MAAOC,CAAI,CAAA,OAAAM,KAAA,SAAA,EAAA,CAAA,OAAA,IAAA,GAAJN,EAAI,EAAA,OAAAO,KAAAC,GAAA,CAAA,KAAJR,EAAI,UAAA,CAAA,CAAA,UAAA,CAAA,EAAA,MAAA,EAAA,KAAA,EAAA,OAAA,CAAA,CAAA,KAAA,MAAA,CAAA,EAAA,SAAA,SAAAC,EAAAC,EAAA,CAAAD,EAAA,IAD6BE,GAAA,EAAA,IAAA,CAAA,EAAaC,GAAA,EAAA,YAAA,EAAUC,GAAA,EAAA,EAAA,cAAA,CAAA,CAAA,CAAA,E","debugId":"9f74a859-8fdd-51b3-ba40-449831d3c20a"} \ No newline at end of file diff --git a/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js b/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js new file mode 100644 index 00000000..b269ae42 --- /dev/null +++ b/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js @@ -0,0 +1,25 @@ +var a = 2; +var r = 0.6; +var n = `image/webp`; +function i(e) { + return e === void 0 || !Number.isFinite(e) ? a : Math.min(60, Math.max(1, Math.round(e))); +} +function t(e) { + return e === void 0 || !Number.isFinite(e) ? r : Math.min(1, Math.max(0, e)); +} +function u(e) { + return e === `image/jpeg` ? `image/jpeg` : n; +} +function m(e) { + return e === `all` ? `all` : i(e); +} +function o(e = {}) { + return { + recordCanvas: !0, + sampling: { canvas: m(e.fps) }, + dataURLOptions: { type: u(e.imageType), quality: t(e.quality) }, + }; +} + +export { o as createCanvasRecordConfig }; +//# debugId=0ce56217-9be4-5485-b3d2-3b96675bd2ff diff --git a/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js.map b/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js.map new file mode 100644 index 00000000..8a51b42a --- /dev/null +++ b/packages/angular/test/fixtures/angular-22/chunk-C4fphy5n.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chunk-C4fphy5n.js","names":["DEFAULT_FPS","DEFAULT_QUALITY","DEFAULT_IMAGE_TYPE","resolveFps","fps","resolveQuality","quality","resolveImageType","imageType","resolveSamplingCanvas","createCanvasRecordConfig","options"],"sources":["../node_modules/@bugsee/replay-canvas/dist/index.js"],"sourcesContent":["// src/canvas-config.ts\nvar DEFAULT_FPS = 2;\nvar DEFAULT_QUALITY = 0.6;\nvar DEFAULT_IMAGE_TYPE = \"image/webp\";\nfunction resolveFps(fps) {\n if (fps === void 0 || !Number.isFinite(fps)) {\n return DEFAULT_FPS;\n }\n return Math.min(60, Math.max(1, Math.round(fps)));\n}\nfunction resolveQuality(quality) {\n if (quality === void 0 || !Number.isFinite(quality)) {\n return DEFAULT_QUALITY;\n }\n return Math.min(1, Math.max(0, quality));\n}\nfunction resolveImageType(imageType) {\n return imageType === \"image/jpeg\" ? \"image/jpeg\" : DEFAULT_IMAGE_TYPE;\n}\nfunction resolveSamplingCanvas(fps) {\n return fps === \"all\" ? \"all\" : resolveFps(fps);\n}\nfunction createCanvasRecordConfig(options = {}) {\n return {\n recordCanvas: true,\n sampling: { canvas: resolveSamplingCanvas(options.fps) },\n dataURLOptions: {\n type: resolveImageType(options.imageType),\n quality: resolveQuality(options.quality)\n }\n };\n}\n\nexport { createCanvasRecordConfig };\n\n"],"ignoreList":[0],"mappings":"AACA,IAAIA,EAAc,EACdC,IAAAA,EAAkB,GAClBC,IAAAA,EAAqB,aACzB,SAASC,EAAWC,EAAK,CACvB,OAAIA,IAAQ,IAAA,IAAU,CAAC,OAAO,SAASA,CAAG,EACjCJ,EAEF,KAAK,IAAI,GAAI,KAAK,IAAI,EAAG,KAAK,MAAMI,CAAG,CAAC,CAAC,CAClD,CACA,SAASC,EAAeC,EAAS,CAC/B,OAAIA,IAAY,IAAA,IAAU,CAAC,OAAO,SAASA,CAAO,EACzCL,EAEF,KAAK,IAAI,EAAG,KAAK,IAAI,EAAGK,CAAO,CAAC,CACzC,CACA,SAASC,EAAiBC,EAAW,CACnC,OAAOA,IAAc,aAAe,aAAeN,CACrD,CACA,SAASO,EAAsBL,EAAK,CAClC,OAAOA,IAAQ,MAAQ,MAAQD,EAAWC,CAAG,CAC/C,CACA,SAASM,EAAyBC,EAAU,CAAC,EAAG,CAC9C,MAAO,CACL,aAAc,CAAA,EACd,SAAU,CAAE,OAAQF,EAAsBE,EAAQ,GAAG,CAAE,EACvD,eAAgB,CACd,KAAMJ,EAAiBI,EAAQ,SAAS,EACxC,QAASN,EAAeM,EAAQ,OAAO,CACzC,CACF,CACF,C","debugId":"0ce56217-9be4-5485-b3d2-3b96675bd2ff"} \ No newline at end of file diff --git a/packages/angular/tsup.config.ts b/packages/angular/tsup.config.ts index 82e2f36b..f98d2094 100644 --- a/packages/angular/tsup.config.ts +++ b/packages/angular/tsup.config.ts @@ -1,4 +1,35 @@ +import { cpSync } from 'node:fs'; import { defineConfig } from 'tsup'; import { baseConfig } from '../../tsup.config.base'; -export default defineConfig(baseConfig); +// Four outputs, because they run in four different places: +// - the runtime entry and the `./sourcemaps` API: ESM + CJS + types (the base preset); +// - the `bugsee-angular-upload` bin: ESM only (it uses top-level await), run by Node; +// - the `ng add` schematic: CommonJS (`.cjs`), loaded by the Angular CLI, with its collection and schema JSON. +// `clean` is off in every one so they cannot delete each other's output; the build script clears dist first. +const shared = { ...baseConfig, clean: false } as const; + +export default defineConfig([ + { + ...shared, + entry: { index: 'src/index.ts', 'sourcemaps/index': 'src/sourcemaps/index.ts' }, + }, + { + ...shared, + dts: false, + format: ['esm'], + platform: 'node', + entry: { 'sourcemaps/bin': 'src/sourcemaps/bin.ts' }, + }, + { + ...shared, + dts: false, + format: ['cjs'], + platform: 'node', + entry: { 'schematics/ng-add/index': 'src/schematics/ng-add/index.ts' }, + onSuccess: async () => { + cpSync('src/schematics/collection.json', 'dist/schematics/collection.json'); + cpSync('src/schematics/ng-add/schema.json', 'dist/schematics/ng-add/schema.json'); + }, + }, +]); diff --git a/packages/bundler-plugin-core/src/index.ts b/packages/bundler-plugin-core/src/index.ts index 3d4be951..6d3b60d6 100644 --- a/packages/bundler-plugin-core/src/index.ts +++ b/packages/bundler-plugin-core/src/index.ts @@ -10,7 +10,12 @@ export { findPackageVersion, } from './app-identity'; export { deriveBuildUuid } from './build-id'; -export { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; +export { + BUILD_PLUGIN_ENV_FILE, + type EnvFileResult, + loadBuildPluginEnv, + mergeBuildPluginEnv, +} from './env-file'; export { defaultDeleteMapFiles, type RunFn, @@ -56,8 +61,21 @@ export { type SpawnResult, spawnProcess, } from './run-cli'; +export { + findIntegrityMismatches, + findSriProtectedScripts, + findStaleDigests, + findStaleServiceWorkerEntries, + hasDigestTokens, + hasServiceWorkerManifest, + listResealFiles, + resealIntegrity, + type ScriptDigests, + type SriProtectedScript, + snapshotScriptDigests, +} from './sri'; export { type AssetStore, type StampAssetsOptions, stampAssets } from './stamp-assets'; -export { cutAtQuery } from './stamp-files'; +export { cutAtQuery, isFencedPath } from './stamp-files'; export { isWorkingTreeDirty, type ResolveVcsMetadataOptions, diff --git a/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts new file mode 100644 index 00000000..53a8e88b --- /dev/null +++ b/packages/bundler-plugin-core/src/orchestrate.reseal-rollback.test.ts @@ -0,0 +1,473 @@ +// A re-seal that fails must leave the build as the bundler emitted it. The stamp is already undone when it does not +// verify (step 1b); the re-seal rewrites more than the stamp touched (pages, server modules, runtime tables), so it +// is undone the same way, from its own snapshot, and nothing is uploaded for bundles that went back unstamped. +// Real `bugsee-cli` for the stamp; only the re-seal (or its verdict) is made to fail. +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { uploadSourcemaps } from './orchestrate'; +import { resolveBugseeCli, runBugseeCli } from './run-cli'; +import { resealIntegrity } from './sri'; + +const cli = resolveBugseeCli(); +const probe = cli.endsWith('.js') + ? spawnSync(process.execPath, [cli, '--version'], { encoding: 'utf8' }) + : spawnSync(cli, ['--version'], { encoding: 'utf8' }); +const required = process.env.CI !== undefined || process.env.BUGSEE_REQUIRE_CLI !== undefined; +const describeReal = probe.status === 0 || required ? describe : describe.skip; + +const made: string[] = []; +afterEach(() => { + for (const dir of made.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +const sha384 = (text: string) => `sha384-${createHash('sha384').update(text).digest('base64')}`; + +/** An output directory with one hashed bundle + map, a page pinning it, and an SSR copy of the page elsewhere. */ +function build() { + const root = mkdtempSync(join(tmpdir(), 'bugsee-rollback-')); + made.push(root); + const out = join(root, 'browser'); + const server = join(root, 'server'); + mkdirSync(out); + mkdirSync(server); + const js = 'console.log(1);\n//# sourceMappingURL=main.js.map\n'; + writeFileSync(join(out, 'main.js'), js); + writeFileSync( + join(out, 'main.js.map'), + JSON.stringify({ version: 3, file: 'main.js', sources: ['a.ts'], names: [], mappings: 'AAAA' }), + ); + const page = ``; + writeFileSync(join(out, 'index.html'), page); + writeFileSync(join(out, 'about.html'), '

no hashes

'); + writeFileSync(join(server, 'index.html.mjs'), `export default ${JSON.stringify(page)};`); + return { root, out, server }; +} + +/** A verifier whose pins are fine until the stamp ran: the first call (before) is clean, later ones report `pins`. */ +const brokenAfterStamp = (pins: { html: string; script: string; integrity: string }[]) => { + let calls = 0; + return async () => (calls++ === 0 ? [] : pins); +}; + +const snapshot = (...dirs: string[]) => + Object.fromEntries( + dirs.flatMap((dir) => + readdirSync(dir).map((name) => [join(dir, name), readFileSync(join(dir, name), 'utf8')]), + ), + ); + +const options = (out: string, server: string, extra: Record = {}) => { + const calls: string[] = []; + const run = vi.fn(async (args: string[], o: Parameters[1]) => { + calls.push(args[0] === 'debug-files' ? 'upload' : args.slice(0, 2).join(' ')); + if (args[0] === 'debug-files') { + return { code: 0, stdout: '', stderr: '' }; + } + return runBugseeCli(args, o); + }); + const errors: unknown[] = []; + return { + calls, + errors, + opts: { + outDir: out, + appToken: 'tok', + appVersion: '1', + appBuild: '1', + resealSri: true, + resealDirs: [out, server], + run, + onError: (e: unknown) => errors.push(e), + ...extra, + }, + }; +}; + +describeReal('uploadSourcemaps re-seal rollback', () => { + it('seals a good build (control): page verifies, upload runs', async () => { + const { out, server } = build(); + const { opts, calls, errors } = options(out, server); + const result = await uploadSourcemaps(opts); + expect(errors).toEqual([]); + expect(result.uploaded).toBe(true); + expect(calls).toContain('upload'); + }); + + it('puts every original byte back when the re-seal throws midway, and uploads nothing', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + reseal: async () => { + // It had already written one file when the disk failed. + writeFileSync(join(out, 'index.html'), 'HALF-SEALED'); + throw new Error('ENOSPC: no space left on device'); + }, + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false, deletedMaps: [] }); + const message = String(errors[0]); + expect(message).toContain('ENOSPC'); + expect(message).toMatch(/restored/); + }); + + it('puts every original byte back when a hash is still stale after the re-seal, and uploads nothing', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + verifySri: brokenAfterStamp([ + { html: join(out, 'index.html'), script: join(out, 'main.js'), integrity: 'sha384-X' }, + ]), + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('still does not match'); + // Only what changed is put back: main.js, its map and the two copies of the page, not about.html. + expect(String(errors[0])).toContain('(4 file(s))'); + // The maps were not deleted either: the unstamped bundles still need them if the user opts out of SRI. + expect(readdirSync(out)).toContain('main.js.map'); + }); + + it('brings back a file the failed re-seal removed', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts } = options(out, server, { + reseal: async () => { + rmSync(join(out, 'index.html')); + throw new Error('boom'); + }, + }); + await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + }); + + it('reports a re-seal that rejects with something that is not an Error', async () => { + const { out, server } = build(); + const { opts, errors } = options(out, server, { + reseal: async () => { + throw 'plain string failure'; + }, + }); + await uploadSourcemaps(opts); + expect(String(errors[0])).toContain('plain string failure'); + }); + + it('removes the temporary copies of the originals it took', async () => { + const { out, server, root } = build(); + const spillRoot = join(root, 'spill'); + mkdirSync(spillRoot); + const { opts } = options(out, server, { spillRoot }); + await uploadSourcemaps(opts); + expect(readdirSync(spillRoot)).toEqual([]); + }); + + it('still reports the inject failure when putting the files back also fails', async () => { + const { out, server } = build(); + const { opts, errors } = options(out, server, { + restoreFile: async () => { + throw new Error('EPERM'); + }, + run: async (args: string[], o: Parameters[1]) => { + if (args[1] === 'inject') { + await runBugseeCli(args, o); + throw new Error('bugsee-cli exited 1 on a later file'); + } + return { code: 0, stdout: '', stderr: '' }; + }, + }); + await uploadSourcemaps(opts); + expect(String(errors[0])).toContain('later file'); + }); + + it('throws the failure under failOnError, after restoring', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts } = options(out, server, { + failOnError: true, + reseal: async () => { + throw new Error('EACCES'); + }, + }); + await expect(uploadSourcemaps(opts)).rejects.toThrow(/EACCES/); + expect(snapshot(out, server)).toEqual(before); + }); + + it('restores everything when a service worker manifest still does not match its files, and uploads nothing', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + verifyServiceWorker: async () => [{ manifest: join(out, 'ngsw.json'), url: '/main.js' }], + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('ngsw.json'); + expect(String(errors[0])).toContain('/main.js'); + expect(String(errors[0])).toMatch(/restored/); + }); + + it('restores everything when an old digest is still present in the server modules after the re-seal', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + verifyDigests: async () => [ + { file: join(server, 'index.html.mjs'), script: join(out, 'main.js') }, + ], + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('index.html.mjs'); + expect(String(errors[0])).toMatch(/restored/); + }); + + it('rolls back when the server copy of the page was not re-sealed (the browser pages alone look fine)', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + // Re-seals the browser directory only, so index.html verifies but the server module keeps the old digest. + reseal: (digests: Parameters[0]) => resealIntegrity(digests, [out]), + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('index.html.mjs'); + }); + + it('verifies the page pins over every verifyDirs, and a mismatch in a later one rolls the build back', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const seen: string[] = []; + const { opts, calls, errors } = options(out, server, { + verifyDirs: [out, server], + verifySri: async (dir: string) => { + seen.push(dir); + return seen.length > 2 && dir === server + ? [ + { + html: join(server, 'fr/index.html'), + script: join(server, 'fr/main.js'), + integrity: 'sha384-X', + }, + ] + : []; + }, + }); + const result = await uploadSourcemaps(opts); + expect(seen).toEqual([out, server, out, server]); // before the stamp, then after the re-seal + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('fr/main.js'); + }); + + it('verifies the output directory alone when no verifyDirs is given', async () => { + const { out, server } = build(); + const seen: string[] = []; + const { opts } = options(out, server, { + verifySri: async (dir: string) => { + seen.push(dir); + return []; + }, + }); + await uploadSourcemaps(opts); + expect(seen).toEqual([out, out]); + }); + + // A pin that was already wrong before we touched anything (a page pinning a file another step changed) is not ours: + // it is said, and it must not roll back a re-seal that did its job. + it('does not roll back for a pin that was already broken before the stamp, and says so', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'vendor.js'), 'vendor();'); + writeFileSync( + join(out, 'other.html'), + ``, + ); + const { opts, calls, errors } = options(out, server, { verifyDirs: [out] }); + const notices: string[] = []; + const result = await uploadSourcemaps({ ...opts, onNotice: (m: string) => notices.push(m) }); + expect(errors).toEqual([]); + expect(result.uploaded).toBe(true); + expect(calls).toContain('upload'); + expect(notices.join('\n')).toMatch(/even before the stamp.*vendor\.js/s); + }); + + it('still rolls back for a pin that WAS valid and is broken after', async () => { + const { out, server } = build(); + let call = 0; + const { opts, calls } = options(out, server, { + // before the stamp nothing is wrong; after the re-seal one page is + verifySri: async () => + call++ === 0 + ? [] + : [ + { + html: join(out, 'index.html'), + script: join(out, 'main.js'), + integrity: 'sha384-X', + }, + ], + }); + const result = await uploadSourcemaps(opts); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(calls).not.toContain('upload'); + }); + + it('a pre-existing bad pin that a re-seal run cannot make worse is not a failure, but a NEW one beside it is', async () => { + const { out, server } = build(); + const old = { html: join(out, 'a.html'), script: join(out, 'v.js'), integrity: 'sha384-A' }; + const fresh = { + html: join(out, 'index.html'), + script: join(out, 'main.js'), + integrity: 'sha384-B', + }; + let call = 0; + const { opts, errors } = options(out, server, { + verifySri: async () => (call++ === 0 ? [old] : [old, fresh]), + }); + await uploadSourcemaps(opts); + expect(String(errors[0])).toContain('main.js'); + expect(String(errors[0])).not.toContain('(and'); + }); + + // The re-seal machinery (digest snapshot, a second spill of every file, the swap walk, the verify) is only worth + // its cost when something can need it: a page that pins a hash, or a service worker manifest. + it('skips the re-seal for an SSR layout too when no page and no server module holds a digest and there is no manifest', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'index.html'), '

no pins

'); + writeFileSync(join(server, 'index.html.mjs'), 'export default "

no pins

";'); + const snapshotDigests = vi.fn(async () => new Map()); + const { opts } = options(out, server, { snapshotDigests, resealDirs: [out, server] }); + await uploadSourcemaps(opts); + expect(snapshotDigests).not.toHaveBeenCalled(); + }); + + it('reports a file it could not put back after a failed inject, naming it', async () => { + const { out, server } = build(); + const { opts, errors } = options(out, server, { + restoreFile: async (_spill: string, target: string) => { + throw new Error(`EBUSY ${target}`); + }, + run: async (args: string[], o: Parameters[1]) => { + if (args[1] === 'inject') { + await runBugseeCli(args, o); + throw new Error('bugsee-cli exited 1 on a later file'); + } + return { code: 0, stdout: '', stderr: '' }; + }, + }); + await uploadSourcemaps(opts); + const message = String(errors[0]); + expect(message).toContain('later file'); + expect(message).toMatch(/COULD NOT restore.*EBUSY.*still stamped/s); + }); + + it('does NOT skip the re-seal when it covers more than the output directory: the server modules may hold the pin', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'index.html'), '

no pins

'); // only the server module embeds a page + const snapshotDigests = vi.fn(async () => new Map()); + const { opts } = options(out, server, { snapshotDigests, resealDirs: [out, server] }); + await uploadSourcemaps(opts); + expect(snapshotDigests).toHaveBeenCalled(); + }); + + it('puts every byte back when inject fails AFTER it stamped (a later batch fails): no stamped bundle against an un-sealed page', async () => { + const { out, server } = build(); + const before = snapshot(out, server); + const { opts, calls, errors } = options(out, server, { + run: async (args: string[], o: Parameters[1]) => { + if (args[1] === 'inject') { + await runBugseeCli(args, o); // stamped on disk... + throw new Error('bugsee-cli exited 1 on a later file'); // ...then the command fails + } + return { code: 0, stdout: '', stderr: '' }; + }, + }); + const result = await uploadSourcemaps(opts); + expect(snapshot(out, server)).toEqual(before); + expect(calls).not.toContain('upload'); + expect(result).toMatchObject({ injected: false, uploaded: false }); + expect(String(errors[0])).toContain('later file'); + }); + + it('skips the whole re-seal when nothing pins a hash and there is no service worker manifest', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'index.html'), '

no pins

'); + const snapshotDigests = vi.fn(async () => new Map()); + const reseal = vi.fn(async () => ({ files: [] })); + const { opts } = options(out, server, { + snapshotDigests, + reseal, + resealDirs: [out], + spillRoot: join(out, '..'), + }); + await uploadSourcemaps(opts); + expect(snapshotDigests).not.toHaveBeenCalled(); + expect(reseal).not.toHaveBeenCalled(); + }); + + it('still re-seals a service worker manifest when no page pins a hash', async () => { + const { out, server } = build(); + writeFileSync(join(out, 'index.html'), '

no pins

'); + const js = readFileSync(join(out, 'main.js'), 'utf8'); + writeFileSync( + join(out, 'ngsw.json'), + JSON.stringify({ hashTable: { '/main.js': createHash('sha1').update(js).digest('hex') } }), + ); + const { opts, errors } = options(out, server, { resealDirs: [out] }); + await uploadSourcemaps(opts); + expect(errors).toEqual([]); + const table = JSON.parse(readFileSync(join(out, 'ngsw.json'), 'utf8')).hashTable; + expect(table['/main.js']).toBe( + createHash('sha1') + .update(readFileSync(join(out, 'main.js'))) + .digest('hex'), + ); + expect(table['/main.js']).not.toBe(createHash('sha1').update(js).digest('hex')); + }); + + it('seals a build with a real service worker manifest (control)', async () => { + const { out, server } = build(); + const js = readFileSync(join(out, 'main.js'), 'utf8'); + const sha1 = (t: string) => createHash('sha1').update(t).digest('hex'); + writeFileSync( + join(out, 'ngsw.json'), + JSON.stringify({ hashTable: { '/main.js': sha1(js) } }, null, 2), + ); + const { opts, calls, errors } = options(out, server); + const result = await uploadSourcemaps(opts); + expect(errors).toEqual([]); + expect(result.uploaded).toBe(true); + expect(calls).toContain('upload'); + const manifest = JSON.parse(readFileSync(join(out, 'ngsw.json'), 'utf8')); + expect(manifest.hashTable['/main.js']).toBe(sha1(readFileSync(join(out, 'main.js'), 'utf8'))); + expect(manifest.hashTable['/main.js']).not.toBe(sha1(js)); + }); + + it('names a file it could not restore', async () => { + const { out, server } = build(); + const { opts, errors } = options(out, server, { + verifySri: brokenAfterStamp([ + { html: join(out, 'index.html'), script: join(out, 'main.js'), integrity: 'sha384-X' }, + ]), + restoreFile: async (_spill: string, target: string) => { + throw new Error(`EPERM on ${target}`); + }, + }); + await uploadSourcemaps(opts); + expect(String(errors[0])).toMatch(/COULD NOT restore/); + expect(String(errors[0])).toContain('EPERM'); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.test.ts b/packages/bundler-plugin-core/src/orchestrate.test.ts index 6008465a..b803d53e 100644 --- a/packages/bundler-plugin-core/src/orchestrate.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.test.ts @@ -872,3 +872,181 @@ describe("a run over the build's own files", () => { expect(onError).toHaveBeenCalledTimes(1); }); }); + +// A build whose only copies of its script hashes are in its HTML (Angular's esbuild builder) can be stamped +// after emit, if the hashes are then re-written to match: inject runs with `--allow-sri`, the pages are +// re-sealed, and the result is verified. The guard that refuses a hashed build stays for every other caller. +/** Clean before the stamp (first call), reports `pins` afterwards. */ +const afterStamp = (pins: { html: string; script: string; integrity: string }[]) => { + let calls = 0; + return async () => (calls++ === 0 ? [] : pins); +}; + +describe('uploadSourcemaps with resealSri', () => { + const pin = { + html: '/build/dist/index.html', + script: '/build/dist/main.js', + integrity: 'sha384-OLD', + }; + const digests = new Map([['/build/dist/main.js', { sha256: 'a', sha384: 'b', sha512: 'c' }]]); + const sealed = (over: Record = {}) => ({ + ...base, + resealSri: true, + findSri: async () => [pin], + snapshotDigests: async () => digests, + reseal: vi.fn(async () => ({ files: ['/build/dist/index.html'] })), + verifySri: async () => [], + deleteMapFiles: async () => [] as string[], + ...over, + }); + + it('does not refuse a hashed build: inject runs with --allow-sri, then upload', async () => { + const { run, calls } = fakeRun(); + const result = await uploadSourcemaps({ ...sealed(), run }); + expect(calls.map((c) => c.args[0])).toEqual(['sourcemaps', 'debug-files']); + expect(calls[0]?.args).toEqual(['sourcemaps', 'inject', '/build/dist', '--allow-sri']); + expect(result.injected).toBe(true); + expect(result.uploaded).toBe(true); + }); + + it('re-seals with the digests taken BEFORE the inject, over the output directory by default', async () => { + const order: string[] = []; + const run = vi.fn(async (args: string[]): Promise => { + order.push(args[0] ?? ''); + return { code: 0, stdout: '', stderr: '' }; + }); + const reseal = vi.fn(async () => { + order.push('reseal'); + return { files: [] }; + }); + const snapshotDigests = vi.fn(async (_dirs: readonly string[]) => { + order.push('snapshot'); + return digests; + }); + await uploadSourcemaps({ ...sealed({ reseal, snapshotDigests }), run }); + expect(order).toEqual(['snapshot', 'sourcemaps', 'reseal', 'debug-files']); + expect(snapshotDigests).toHaveBeenCalledWith(['/build/dist']); + expect(reseal).toHaveBeenCalledWith(digests, ['/build/dist']); + }); + + it('re-seals over resealDirs when given (the SSR server modules that embed the page)', async () => { + const { run } = fakeRun(); + const reseal = vi.fn(async () => ({ files: [] })); + await uploadSourcemaps({ + ...sealed({ reseal, resealDirs: ['/build/dist', '/build/server'] }), + run, + }); + expect(reseal).toHaveBeenCalledWith(digests, ['/build/dist', '/build/server']); + }); + + it('passes --allow-sri to every batch of a file run', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ + files: { scripts: ['/build/dist/main.js'], maps: ['/build/dist/main.js.map'] }, + }), + run, + }); + expect(calls[0]?.args).toEqual([ + 'sourcemaps', + 'inject', + '/build/dist/main.js', + '/build/dist/main.js.map', + '--allow-sri', + ]); + }); + + it('reports a page that still does not verify, restores, and uploads nothing', async () => { + const { run, calls } = fakeRun(); + const onError = vi.fn(); + await uploadSourcemaps({ ...sealed({ verifySri: afterStamp([pin]) }), run, onError }); + expect(String(onError.mock.calls[0]?.[0])).toContain('index.html'); + expect(String(onError.mock.calls[0]?.[0])).toContain('main.js'); + expect(calls.map((c) => c.args[0])).not.toContain('debug-files'); + }); + + it('throws under failOnError when a page still does not verify', async () => { + const { run } = fakeRun(); + await expect( + uploadSourcemaps({ + ...sealed({ verifySri: afterStamp([pin, pin]) }), + run, + failOnError: true, + }), + ).rejects.toThrow(/\(and 1 more\)/); + }); + + it('does not re-seal on a dry run: nothing was written', async () => { + const { run, calls } = fakeRun(); + const reseal = vi.fn(async () => ({ files: [] })); + const snapshotDigests = vi.fn(async () => digests); + await uploadSourcemaps({ ...sealed({ reseal, snapshotDigests }), run, dryRun: true }); + expect(reseal).not.toHaveBeenCalled(); + expect(snapshotDigests).not.toHaveBeenCalled(); + expect(calls[0]?.args).toEqual([ + 'sourcemaps', + 'inject', + '/build/dist', + '--dry-run', + '--allow-sri', + ]); + }); + + // The CLI's own SRI refusal is the safety net for pins OUR scanner cannot resolve (a scheme-less //host, a root-relative + // path under --base-href/--deploy-url): --allow-sri is passed only when a re-seal will actually happen. + it('leaves the CLI refusal ON when resealSri is set but nothing pins a hash and no manifest exists', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ findSri: async () => [], hasServiceWorker: async () => false }), + run, + }); + expect(calls[0]?.args).toEqual(['sourcemaps', 'inject', '/build/dist']); + }); + + it('leaves it on for every batch of a file run too', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ + findSri: async () => [], + hasServiceWorker: async () => false, + files: { scripts: ['/build/dist/main.js'], maps: ['/build/dist/main.js.map'] }, + }), + run, + }); + expect(calls[0]?.args).not.toContain('--allow-sri'); + }); + + it('passes it when only a service worker manifest needs the re-seal', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ findSri: async () => [], hasServiceWorker: async () => true }), + run, + }); + expect(calls[0]?.args).toContain('--allow-sri'); + }); + + it('passes it when a server module holds a digest', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...sealed({ + findSri: async () => [], + hasServiceWorker: async () => false, + resealDirs: ['/build/dist', '/build/server'], + hasDigestTokens: async () => true, + }), + run, + }); + expect(calls[0]?.args).toContain('--allow-sri'); + }); + + it('adds no flag at all when resealSri is off (the refusal path is unchanged)', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...base, + findSri: async () => [], + run, + deleteMapFiles: async () => [], + }); + expect(calls[0]?.args).toEqual(['sourcemaps', 'inject', '/build/dist']); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 12826a5a..19b269f0 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -1,11 +1,23 @@ // SM-A2 — orchestrate a source-map upload by driving `bugsee-cli`: inject debug-IDs, upload the maps, then // delete the client `.map` files (privacy). Each side-effecting step is behind an injectable seam so the // orchestration is unit-tested without a real binary or filesystem. +import { createHash } from 'node:crypto'; import { access, readdir, readFile, unlink } from 'node:fs/promises'; import path, { join, relative, resolve } from 'node:path'; import { readDebugId } from './debug-ids'; import { type RunBugseeCliOptions, runBugseeCli, type SpawnResult } from './run-cli'; -import { findIntegrityMismatches, findSriProtectedScripts, type SriProtectedScript } from './sri'; +import { + findIntegrityMismatches, + findSriProtectedScripts, + findStaleDigests, + findStaleServiceWorkerEntries, + hasDigestTokens, + hasServiceWorkerManifest, + listResealFiles, + resealIntegrity, + type SriProtectedScript, + snapshotScriptDigests, +} from './sri'; import { isFencedPath, isProjectRootOrAbove, @@ -15,6 +27,7 @@ import { NEVER_WALK, ownedBy, partitionByKeyed, + restoreAtomically, restorePaths, type SnapshotTarget, type StampSnapshot, @@ -115,8 +128,36 @@ export interface UploadSourcemapsOptions { listUploadMaps?: (dir: string) => Promise; /** Where the pre-inject originals are spilled (default: the OS temp directory). A test seam. */ spillRoot?: string; - /** Injectable integrity check for the pre-stamped path (default {@link findIntegrityMismatches}). */ + /** Injectable integrity check for the pre-stamped and re-seal paths (default {@link findIntegrityMismatches}). */ verifySri?: (dir: string) => Promise; + /** + * Stamp a build that pins its script hashes, then RE-WRITE the hashes to match, instead of refusing. + * + * For a build whose copies of those hashes are literals in its HTML pages (tags and import maps), the + * server modules that embed them and a runtime table of chunk hashes — Angular's builders. `sourcemaps inject` runs with `--allow-sri`, the stale + * digests are replaced in {@link resealDirs}, and the result is verified; a page that still does not + * verify is reported (or thrown under `failOnError`), never silent. Not for a hash computed at run time. + * Ignored on a dry run (nothing is written). + */ + resealSri?: boolean; + /** Directories whose HTML / `.mjs` carry a copy of the hashes. Default: `[outDir]`. */ + resealDirs?: readonly string[]; + /** Directories whose page pins are verified after the re-seal (default: `[outDir]`): the whole output root of an SSR build. */ + verifyDirs?: readonly string[]; + /** Injectable: does any directory hold a service worker manifest (default {@link hasServiceWorkerManifest}). */ + hasServiceWorker?: (dirs: readonly string[]) => Promise; + /** Injectable: does any file under these directories hold an SRI digest (default {@link hasDigestTokens}). */ + hasDigestTokens?: (dirs: readonly string[]) => Promise; + /** Injectable re-sealer (default {@link resealIntegrity}). */ + reseal?: typeof resealIntegrity; + /** Injectable restore of one file from its spilled original, for the re-seal rollback (default: write temp, then rename). */ + restoreFile?: (spill: string, target: string) => Promise; + /** Injectable script-digest snapshot taken before the stamp (default {@link snapshotScriptDigests}). */ + snapshotDigests?: typeof snapshotScriptDigests; + /** Injectable check that service worker manifests match their files after the re-seal (default {@link findStaleServiceWorkerEntries}). */ + verifyServiceWorker?: typeof findStaleServiceWorkerEntries; + /** Injectable check that no old digest survives anywhere the re-seal covers (default {@link findStaleDigests}). */ + verifyDigests?: typeof findStaleDigests; /** * FAIL the build when `bugsee-cli` fails. Default `false`. * @@ -237,6 +278,8 @@ export async function uploadSourcemaps( const files = options.files; const deleteMaps = options.deleteMaps ?? true; const dryFlag = dryRun ? ['--dry-run'] : []; + // `inject` refuses a hashed build unless told the hashes are re-written afterwards, which resealSri does. + const resealing = options.resealSri === true; const cliOptions: RunBugseeCliOptions = { token: appToken, endpoint }; const onError = options.onError ?? defaultUploadErrorHandler; @@ -425,6 +468,7 @@ export async function uploadSourcemaps( }; let original: StampSnapshot | undefined; + let sealOriginal: StampSnapshot | undefined; let restoredAny = false; try { if (options.preStamped === true) { @@ -511,7 +555,7 @@ export async function uploadSourcemaps( // survivable; shipping a page that does not load is not. Checked BEFORE anything is written, // so a refusal leaves the build exactly as the bundler emitted it. const pinned = await (options.findSri ?? findSriProtectedScripts)(outDir); - if (pinned.length > 0) { + if (pinned.length > 0 && !resealing) { const [first] = pinned as [SriProtectedScript, ...SriProtectedScript[]]; throw new Error( `refusing to stamp debug-IDs: this build uses Subresource Integrity — ${first.html} pins a ` + @@ -526,6 +570,56 @@ export async function uploadSourcemaps( ); } + // 0a. The digest of every script as the build emitted it, for the re-seal: the stale hashes are found by + // what the files WERE, wherever a copy sits (a tag, an import map, a table in the runtime chunk). Not + // on a dry run: nothing is written. + // Only when something can need it: a page that pins a hash (`pinned`), or a service worker manifest. + // Without either, the snapshot, the second spill, the swap walk and the verify would be pure cost. + const sealDirs = options.resealDirs ?? [outDir]; + const needsReseal = + resealing && + !dryRun && + // A re-seal that covers more than the output directory (an SSR build's server modules) cannot be skipped on + // what the output directory's HTML shows alone: a server module may embed a pinned page, so those directories + // are scanned (cheaply, for a digest-shaped token) rather than assumed to need it. + (pinned.length > 0 || + (await (options.hasDigestTokens ?? hasDigestTokens)( + sealDirs.filter((dir) => resolve(dir) !== resolve(outDir)), + )) || + (await (options.hasServiceWorker ?? hasServiceWorkerManifest)(sealDirs))); + // `--allow-sri` switches off the CLI's own refusal of a hashed build, so it is passed only when the pins were + // found here and will be re-written. A pin this scanner cannot resolve (a scheme-less //host, a root-relative path + // under --base-href/--deploy-url) is then still caught by the CLI. + const allowSriFlag = resealing && (pinned.length > 0 || needsReseal) ? ['--allow-sri'] : []; + const digests = needsReseal + ? await (options.snapshotDigests ?? snapshotScriptDigests)([outDir]) + : undefined; + const verifyDirs = options.verifyDirs ?? [outDir]; + const verify = options.verifySri ?? findIntegrityMismatches; + const pinKey = (pin: SriProtectedScript): string => `${pin.html}\0${pin.script}`; + // Pins that were wrong BEFORE we touched anything are not ours to fail on. + const preExisting = new Set(); + if (digests !== undefined) { + for (const dir of verifyDirs) { + for (const pin of await verify(dir)) { + preExisting.add(pinKey(pin)); + } + } + } + + // 0a'. Everything the stamp AND the re-seal may write — scripts, maps, pages, server modules — so a re-seal + // that fails can put the build back exactly as the bundler emitted it (the stamp's own snapshot below + // does not cover pages or server modules). + if (digests !== undefined) { + const sealPaths = new Set([ + ...(await listResealFiles(options.resealDirs ?? [outDir])), + ...(files === undefined + ? await (options.listMapFiles ?? listMapFiles)(outDir) + : [...files.scripts, ...files.maps]), + ]); + sealOriginal = await snapshotStampFiles({ files: [...sealPaths] }, options.spillRoot); + } + // 0b. Take the originals, so a stamp that does not verify can be undone (see below). Not on a dry run: // inject writes nothing, so there is nothing to undo. const target: SnapshotTarget = @@ -547,27 +641,43 @@ export async function uploadSourcemaps( // 1. Inject debug-IDs (rewrites the built .js + .map in place). try { if (files === undefined) { - await run(['sourcemaps', 'inject', outDir, ...dryFlag], cliOptions); + await run(['sourcemaps', 'inject', outDir, ...dryFlag, ...allowSriFlag], cliOptions); } else { // A script and its map may land in different batches: harmless, the debug-id is derived from the // bundle's content, so each side stamps the same id (measured with 250 entries, none mismatched). for (const batch of inBatches([...files.scripts, ...files.maps])) { - await run(['sourcemaps', 'inject', ...batch, ...dryFlag], cliOptions); + await run(['sourcemaps', 'inject', ...batch, ...dryFlag, ...allowSriFlag], cliOptions); } } } catch (error) { // A rejected inject may already have rewritten files (an earlier batch, or a partial write): verify and // restore them BEFORE the failure propagates, so no unverified stamp stays on disk. - if (original !== undefined) { - let note: string | undefined; - try { - const { issues, restored, failed } = await verifyAndRestore(original); - if (failed.length > 0) { - // Files still carry the unverified rewrite: that must not go unmentioned. - note = verifyFailure(issues, restored, failed).message; + // When the pages were meant to be re-sealed, a stamp that stays on disk would sit against pages still pinning + // the old hashes (a blocked page): put EVERYTHING the stamp or the re-seal could write back first. + let sealNote: string | undefined; + if (sealOriginal !== undefined) { + const undone = await restoreChanged(sealOriginal, options.restoreFile); // never throws: failures come back listed + if (undone.failed.length > 0) { + sealNote = `COULD NOT restore ${undone.failed.map((f) => `${f.path} (${f.error})`).join(', ')}, which are still stamped against integrity hashes that were not updated`; + } + } + { + let note: string | undefined = sealNote; + const addNote = (text: string): void => { + note = note === undefined ? text : `${note}; ${text}`; + }; + if (original !== undefined) { + try { + const { issues, restored, failed } = await verifyAndRestore(original); + if (failed.length > 0) { + // Files still carry the unverified rewrite: that must not go unmentioned. + addNote(verifyFailure(issues, restored, failed).message); + } + } catch (restoreError) { + addNote( + `restoring the originals also failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, + ); } - } catch (restoreError) { - note = `restoring the originals also failed: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`; } if (note !== undefined) { // The ORIGINAL error object is kept (a BugseeCliError stays one); the restore problem is appended. @@ -604,6 +714,93 @@ export async function uploadSourcemaps( onError(failure); } } + + // 1c. Re-seal: the bundles changed after the build hashed them, so write the new hashes where the old ones + // are, then check. After 1b, so the bytes sealed are the bytes that stayed on disk (a restored file + // still matches its original hash and is left alone). Not on a dry run: nothing was written. + if (digests !== undefined) { + let sealFailure: Error | undefined; + try { + await (options.reseal ?? resealIntegrity)(digests, options.resealDirs ?? [outDir]); + const broken: SriProtectedScript[] = []; + const already: SriProtectedScript[] = []; + for (const dir of verifyDirs) { + for (const pin of await verify(dir)) { + (preExisting.has(pinKey(pin)) ? already : broken).push(pin); + } + } + if (already.length > 0) { + (options.onNotice ?? ((m: string) => console.warn(`[bugsee] ${m}`)))( + `${already.length} integrity pin(s) did not match their file even before the stamp (for example ` + + `${already[0]?.html} pins ${already[0]?.script}), so they were left as they were and are not a result of this step`, + ); + } + if (broken.length > 0) { + const [first] = broken as [SriProtectedScript, ...SriProtectedScript[]]; + sealFailure = new Error( + `${first.script} still does not match the integrity hash ${first.html} pins` + + (broken.length > 1 ? ` (and ${broken.length - 1} more)` : '') + + ` after the hashes were re-written, so the browser would refuse to run it. A copy of that hash is held in ` + + `a form this step does not rewrite (one computed at run time, or a file outside the directories it covers), ` + + `which it cannot see. Turn Subresource Integrity off for this build, or do not stamp it.`, + ); + } else { + // A service worker manifest (Angular's ngsw.json) pins a SHA-1 of every file it caches; the worker + // treats a file that no longer matches as corrupt and stops serving the app. + const stale = await (options.verifyServiceWorker ?? findStaleServiceWorkerEntries)( + options.resealDirs ?? [outDir], + ); + if (stale.length > 0) { + const [first] = stale as [ + { manifest: string; url: string }, + ...{ manifest: string; url: string }[], + ]; + sealFailure = new Error( + `${first.manifest} still lists a hash for ${first.url} that is not the file's` + + (stale.length > 1 ? ` (and ${stale.length - 1} more)` : '') + + ` after the hashes were re-written, so the service worker would treat the app as corrupt and stop serving it`, + ); + } else { + // Every directory the re-seal covers, not only the one the pages are scanned in: an SSR build's server + // modules hold a copy of the page that findIntegrityMismatches (HTML under outDir) cannot see. + const left = await (options.verifyDigests ?? findStaleDigests)( + digests, + options.resealDirs ?? [outDir], + ); + if (left.length > 0) { + sealFailure = new Error( + `${left[0]?.file} still holds the old integrity hash of ${left[0]?.script}` + + (left.length > 1 ? ` (and ${left.length - 1} more file(s))` : '') + + ` after the hashes were re-written, so a page served from it would be blocked by the browser`, + ); + } + } + } + } catch (error) { + sealFailure = error instanceof Error ? error : new Error(String(error)); + } + if (sealFailure !== undefined) { + // A page that is blocked, or a build half-sealed, is worse than no source maps. Put every file the stamp + // and the re-seal touched back to what the bundler emitted, and upload nothing: the maps belong to bundles + // that no longer carry the debug-ID they were keyed by. + const { restored, failed } = await restoreChanged( + sealOriginal as StampSnapshot, + options.restoreFile, + ); + const failure = new Error( + `${sealFailure.message}. The build was restored to the bundler's original bytes (${restored.length} file(s)) ` + + `and nothing was uploaded` + + (failed.length > 0 + ? `; COULD NOT restore ${failed.map((f) => `${f.path} (${f.error})`).join(', ')}, which are still stamped or half-sealed` + : ''), + ); + if (options.failOnError === true) { + throw failure; + } + onError(failure); + return { injected: false, uploaded: false, deletedMaps: [], ...vcsEcho }; + } + } } // 2. Upload the maps, keyed by the injected debug-ID (+ version/build metadata). @@ -813,6 +1010,7 @@ export async function uploadSourcemaps( // removing the spill directory can fail (EPERM/EBUSY under antivirus on Windows). Said, not thrown. try { await original?.dispose(); + await sealOriginal?.dispose(); } catch (error) { onError( new Error( @@ -822,3 +1020,28 @@ export async function uploadSourcemaps( } } } + +/** Put back, atomically, every snapshotted file whose bytes are not the original's. Never throws: failures are returned. */ +async function restoreChanged( + snapshot: StampSnapshot, + restoreFile: (spill: string, target: string) => Promise = restoreAtomically, +): Promise<{ restored: string[]; failed: { path: string; error: string }[] }> { + const restored: string[] = []; + const failed: { path: string; error: string }[] = []; + for (const [path, entry] of snapshot.entries) { + const now = await readFile(path).then( + (bytes) => createHash('sha1').update(bytes).digest('hex'), + () => undefined, + ); + if (now === entry.hash) { + continue; + } + try { + await restoreFile(entry.spill, path); + restored.push(path); + } catch (error) { + failed.push({ path, error: String(error) }); + } + } + return { restored, failed }; +} diff --git a/packages/bundler-plugin-core/src/resolve.test.ts b/packages/bundler-plugin-core/src/resolve.test.ts index 539dedf9..8f2ff7dd 100644 --- a/packages/bundler-plugin-core/src/resolve.test.ts +++ b/packages/bundler-plugin-core/src/resolve.test.ts @@ -1215,3 +1215,41 @@ describe('runPluginUpload — in-build stamping', () => { expect(uploadSourcemaps).toHaveBeenCalledWith(expect.objectContaining({ preStamped: true })); }); }); + +describe('runPluginUpload — re-sealing', () => { + const stubs = () => ({ + uploadSourcemaps: vi.fn(async (_options: unknown) => ({ + injected: true, + uploaded: true, + deletedMaps: [] as string[], + })), + registerJsBuild: async () => ({ registered: false as const, reason: 'not-release' as const }), + ...noVcs, + }); + + it('forwards resealSri and resealDirs to the orchestrator', async () => { + const deps = stubs(); + await runPluginUpload(resolvePluginOptions({ appToken: 't' }, {}), '/out', { + ...deps, + resealSri: true, + resealDirs: ['/out', '/server'], + verifyDirs: ['/'], + }); + expect(deps.uploadSourcemaps).toHaveBeenCalledWith( + expect.objectContaining({ + resealSri: true, + resealDirs: ['/out', '/server'], + verifyDirs: ['/'], + }), + ); + }); + + it('sends neither when not asked, so every other caller is unchanged', async () => { + const deps = stubs(); + await runPluginUpload(resolvePluginOptions({ appToken: 't' }, {}), '/out', deps); + const sent = deps.uploadSourcemaps.mock.calls[0]?.[0] as unknown as Record; + expect('resealSri' in sent).toBe(false); + expect('resealDirs' in sent).toBe(false); + expect('verifyDirs' in sent).toBe(false); + }); +}); diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index 9ab6a520..ee896e1c 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -371,6 +371,12 @@ async function runPluginUploadInner( bundler?: BundlerBuildContext; /** The bundles were stamped inside the build (stamp-assets.ts); skip the post-emit inject. */ preStamped?: boolean; + /** Stamp a build that pins its script hashes, then re-write the hashes (see `UploadSourcemapsOptions.resealSri`). */ + resealSri?: boolean; + /** Directories whose HTML / `.mjs` carry a copy of the hashes. */ + resealDirs?: readonly string[]; + /** Directories whose page pins are verified after the re-seal. */ + verifyDirs?: readonly string[]; /** The bundles the in-build stamp wrote (relative to the output directory), for the on-disk re-check. */ stampedBundles?: readonly string[]; /** The in-build stamp's bundle -> map names, for the on-disk re-check. */ @@ -456,6 +462,9 @@ async function runPluginUploadInner( } : {}), ...(deps.files !== undefined ? { files: deps.files } : {}), + ...(deps.resealSri === true ? { resealSri: true } : {}), + ...(deps.resealDirs !== undefined ? { resealDirs: deps.resealDirs } : {}), + ...(deps.verifyDirs !== undefined ? { verifyDirs: deps.verifyDirs } : {}), }); // AFTER the upload, because the build id is derived from the debug-ids its inject step stamps // into the bundles — and regardless of whether the maps made it, because a build exists either diff --git a/packages/bundler-plugin-core/src/sri.service-worker.test.ts b/packages/bundler-plugin-core/src/sri.service-worker.test.ts new file mode 100644 index 00000000..43b2ea37 --- /dev/null +++ b/packages/bundler-plugin-core/src/sri.service-worker.test.ts @@ -0,0 +1,210 @@ +// Angular's service worker manifest (`ngsw.json`, one per locale for a localized build) holds `hashTable`: the SHA-1 +// (hex) of every file it caches, keyed by URL. A service worker that finds a file whose hash differs treats the app as +// corrupt and stops serving it. Measured on @angular/build 22.3 + @angular/service-worker: every entry is +// sha1(file bytes), the key is the path from the manifest's directory, and the file is formatted JSON. +import { createHash } from 'node:crypto'; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + findStaleDigests, + findStaleServiceWorkerEntries, + listResealFiles, + resealIntegrity, + snapshotScriptDigests, +} from './sri'; + +const made: string[] = []; +afterEach(async () => { + await Promise.all(made.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +const sha = (alg: string, text: string) => createHash(alg).update(text).digest('base64'); +const sha1 = (text: string) => createHash('sha1').update(text).digest('hex'); +const manifest = (table: Record) => + JSON.stringify({ configVersion: 1, index: '/index.html', hashTable: table }, null, 2); + +let root: string; +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'bugsee-ngsw-')); + made.push(root); +}); +const write = async (rel: string, body: string) => { + const full = join(root, rel); + await mkdir(join(full, '..'), { recursive: true }); + await writeFile(full, body, 'utf8'); + return full; +}; + +describe('findStaleDigests', () => { + it('reports every file under the directories that still holds the old digest of a changed script', async () => { + await write('browser/main.js', 'a();'); + await write('browser/keep.js', 'k();'); + const page = ``; + const html = await write('browser/index.html', page); + const mjs = await write( + 'server/assets/index.html.mjs', + `export default ${JSON.stringify(page)};`, + ); + await write('server/notes.txt', page); + const before = await snapshotScriptDigests([join(root, 'browser')]); + await write('browser/main.js', 'a();\n//# debugId=x'); + const stale = await findStaleDigests(before, [root]); + expect(stale.map((s) => s.file).sort()).toEqual([html, mjs].sort()); + expect(stale[0]?.script).toBe(join(root, 'browser/main.js')); + await resealIntegrity(before, [root]); + expect(await findStaleDigests(before, [root])).toEqual([]); + }); + + it('lists a file once even when it holds the old digests of several changed scripts', async () => { + await write('a.js', 'a();'); + await write('b.js', 'b();'); + const page = await write( + 'index.html', + `sha384-${sha('sha384', 'a();')} sha384-${sha('sha384', 'b();')}`, + ); + const before = await snapshotScriptDigests([root]); + await write('a.js', 'a2();'); + await write('b.js', 'b2();'); + expect(await findStaleDigests(before, [root])).toEqual([ + { file: page, script: expect.stringMatching(/[ab]\.js$/) }, + ]); + }); + + it('says nothing when no script changed, or a changed script is gone', async () => { + await write('browser/main.js', 'a();'); + await write('browser/index.html', `sha384-${sha('sha384', 'a();')}`); + const before = await snapshotScriptDigests([join(root, 'browser')]); + expect(await findStaleDigests(before, [root])).toEqual([]); + await rm(join(root, 'browser/main.js')); + expect(await findStaleDigests(before, [root])).toEqual([]); + }); + + it('checks every algorithm', async () => { + await write('a.js', 'a();'); + const before = await snapshotScriptDigests([root]); + await write('a.js', 'b();'); + for (const alg of ['sha256', 'sha512']) { + const page = await write(`p-${alg}.html`, `${alg}-${sha(alg, 'a();')}`); + expect((await findStaleDigests(before, [root])).map((s) => s.file)).toContain(page); + } + }); +}); + +describe('service worker manifests', () => { + it('re-computes the hash of a file that was stamped or re-sealed, leaving the formatting alone', async () => { + await write('main.js', 'a();'); + await write( + 'index.html', + ``, + ); + const html0 = await readFile(join(root, 'index.html'), 'utf8'); + await write('favicon.ico', 'ico'); + const ngsw = await write( + 'ngsw.json', + manifest({ + '/main.js': sha1('a();'), + '/index.html': sha1(html0), + '/favicon.ico': sha1('ico'), + }), + ); + const before = await snapshotScriptDigests([root]); + await write('main.js', 'a();\n//# debugId=x'); + const { files } = await resealIntegrity(before, [root]); + expect(files).toContain(ngsw); + const html1 = await readFile(join(root, 'index.html'), 'utf8'); + expect(await readFile(ngsw, 'utf8')).toBe( + manifest({ + '/main.js': sha1('a();\n//# debugId=x'), + '/index.html': sha1(html1), + '/favicon.ico': sha1('ico'), + }), + ); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it('does it for the manifest of every locale', async () => { + for (const locale of ['en-US', 'fr']) { + await write(`${locale}/main.js`, `${locale}();`); + await write(`${locale}/ngsw.json`, manifest({ '/main.js': sha1(`${locale}();`) })); + } + const before = await snapshotScriptDigests([root]); + await write('fr/main.js', 'fr();\n//# debugId=y'); + await resealIntegrity(before, [root]); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + expect(await readFile(join(root, 'en-US/ngsw.json'), 'utf8')).toContain(sha1('en-US();')); + expect(await readFile(join(root, 'fr/ngsw.json'), 'utf8')).toContain( + sha1('fr();\n//# debugId=y'), + ); + }); + + it('finds the file under a base href, by dropping leading path segments', async () => { + await write('main.js', 'a();'); + await write('ngsw.json', manifest({ '/app/v2/main.js': sha1('a();') })); + await write('main.js', 'changed'); + expect(await findStaleServiceWorkerEntries([root])).toEqual([ + { manifest: join(root, 'ngsw.json'), url: '/app/v2/main.js' }, + ]); + await resealIntegrity(new Map(), [root]); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it('leaves an entry whose file is not there, and a manifest that is not JSON or has no table', async () => { + await write('d/a.js', 'a'); + const files = [ + await write('a/ngsw.json', manifest({ '/gone.js': sha1('x') })), + await write('b/ngsw.json', '{ nope'), + await write('c/ngsw.json', '{"index":"/"}'), + await write('d/ngsw.json', '{"hashTable":{"/a.js":5}}'), + ]; + const texts = await Promise.all(files.map((f) => readFile(f, 'utf8'))); + await resealIntegrity(new Map(), [root]); + expect(await Promise.all(files.map((f) => readFile(f, 'utf8')))).toEqual(texts); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it('hashes a large listed asset by streaming it (no whole-file buffer), and still reconciles it', async () => { + const big = Buffer.alloc(3 * 1024 * 1024, 7); + await mkdir(join(root, 'media'), { recursive: true }); + await writeFile(join(root, 'media/clip.bin'), big); + await write('ngsw.json', manifest({ '/media/clip.bin': 'stale' })); + expect(await findStaleServiceWorkerEntries([root])).toHaveLength(1); + await resealIntegrity(new Map(), [root]); + expect(await readFile(join(root, 'ngsw.json'), 'utf8')).toContain( + createHash('sha1').update(big).digest('hex'), + ); + }); + + it('an entry that names a directory is skipped, like one whose file is gone', async () => { + await mkdir(join(root, 'assets'), { recursive: true }); + await write('ngsw.json', manifest({ '/assets': 'x' })); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it.skipIf(process.getuid?.() === 0)( + 'a file it cannot read is an error, not a silent skip', + async () => { + const secret = await write('locked.js', 'x'); + await write('ngsw.json', manifest({ '/locked.js': sha1('x') })); + await chmod(secret, 0o000); + try { + await expect(findStaleServiceWorkerEntries([root])).rejects.toThrow(/EACCES/); + } finally { + await chmod(secret, 0o644); + } + }, + ); + + it('does not look in node_modules, and does not follow a key out of the manifest directory', async () => { + await write('node_modules/p/ngsw.json', manifest({ '/m.js': 'x' })); + await write('outside.js', 'o'); + await write('sub/ngsw.json', manifest({ '/../outside.js': 'stale' })); + expect(await findStaleServiceWorkerEntries([root])).toEqual([]); + }); + + it('lists the manifests among the files a re-seal may rewrite', async () => { + const ngsw = await write('x/ngsw.json', '{}'); + expect(await listResealFiles([root])).toContain(ngsw); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.test.ts b/packages/bundler-plugin-core/src/sri.test.ts index 91ad5bef..301f8e8d 100644 --- a/packages/bundler-plugin-core/src/sri.test.ts +++ b/packages/bundler-plugin-core/src/sri.test.ts @@ -1,9 +1,14 @@ import { createHash } from 'node:crypto'; -import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'; +import { chmod, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { basename, join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { findIntegrityMismatches, findSriProtectedScripts } from './sri'; +import { + findIntegrityMismatches, + findSriProtectedScripts, + resealIntegrity, + snapshotScriptDigests, +} from './sri'; // Measured, 2026-09-18: a real webpack 5.111 build with `webpack-subresource-integrity` + // `html-webpack-plugin`, served over HTTP and loaded in Chromium 151. Before `sourcemaps inject` the @@ -341,6 +346,41 @@ describe('findSriProtectedScripts', () => { ]); }); + it('resolves a root-relative src against the directory the page was built into when it is not at the scanned root', async () => { + // Scanning an SSR output root: browser/index.html says `/main.js`, which is browser/main.js, not /main.js. + const dir = await fixture(); + await write(dir, 'browser/main.js', 'a'); + await write(dir, 'browser/fr/chunk.js', 'b'); + await write(dir, 'browser/index.html', ''); + await write( + dir, + 'browser/fr/index.html', + '', + ); + await write(dir, 'top.html', ''); + const scripts = (await findSriProtectedScripts(dir)).map((p) => p.script).sort(); + // top.html's `/main.js` is the scanned root's own (absent) file; the two nested pages find theirs by looking up. + expect(scripts).toEqual( + [join(dir, 'browser/fr/chunk.js'), join(dir, 'browser/main.js'), join(dir, 'main.js')].sort(), + ); + }); + + it('never looks above the scanned root for a root-relative src', async () => { + const dir = await fixture(); + await write(dir, 'main.js', 'outside the scanned directory'); + await write(dir, 'browser/index.html', ''); + const found = await findSriProtectedScripts(join(dir, 'browser')); + expect(found.map((p) => p.script)).toEqual([join(dir, 'browser', 'main.js')]); + }); + + it('a root-relative src that exists nowhere keeps its scanned-root path (a stale pin, as before)', async () => { + const dir = await fixture(); + await write(dir, 'browser/index.html', ''); + expect((await findSriProtectedScripts(dir)).map((p) => p.script)).toEqual([ + join(dir, 'gone.js'), + ]); + }); + it('does not treat a SIBLING directory with a shared prefix as inside the output', async () => { const root = await fixture(); const outDir = join(root, 'dist'); @@ -373,6 +413,80 @@ describe('findSriProtectedScripts', () => { // the CLI's own "path does not exist", not as an unhandled error from a guard. expect(await findSriProtectedScripts(join(await fixture(), 'nope'))).toEqual([]); }); + + // Angular's esbuild builder (v21+) pins its LAZY chunks through an import map's `integrity` table, not through + // a tag: measured on @angular/build 22.3 in Chromium, a stamped lazy chunk was blocked ("Failed to find a valid + // digest in the 'integrity' attribute ... The resource has been blocked") while the page's entry scripts ran. + describe('an import map integrity table', () => { + const importMap = (table: unknown, attrs = 'type="importmap"') => + ``; + + it('finds the scripts it pins, resolving relative and root-relative keys', async () => { + const dir = await fixture(); + await write(dir, 'chunk-a.js', 'a'); + await write(dir, 'assets/chunk-b.mjs', 'b'); + await write( + dir, + 'index.html', + importMap({ './chunk-a.js': 'sha384-A', '/assets/chunk-b.mjs': 'sha384-B' }), + ); + expect(await findSriProtectedScripts(dir)).toEqual([ + { html: join(dir, 'index.html'), script: join(dir, 'chunk-a.js'), integrity: 'sha384-A' }, + { + html: join(dir, 'index.html'), + script: join(dir, 'assets', 'chunk-b.mjs'), + integrity: 'sha384-B', + }, + ]); + }); + + it('lists a script pinned both by a tag and by the map once', async () => { + const dir = await fixture(); + await write(dir, 'main.js', 'a'); + await write( + dir, + 'index.html', + `${importMap({ './main.js': 'sha384-M' })}`, + ); + expect(await findSriProtectedScripts(dir)).toHaveLength(1); + }); + + it('ignores a map that is not JSON, has no integrity table, or pins something that is not ours', async () => { + const dir = await fixture(); + await write(dir, 'a.js', 'a'); + await write(dir, 'data.json', '{}'); + await write(dir, 'index.html', importMap('{ not json')); + await write(dir, 'two.html', importMap({ imports: { x: './a.js' } }.imports)); + await write( + dir, + 'three.html', + '', + ); + await write(dir, 'four.html', ''); + await write( + dir, + 'five.html', + importMap({ + 'https://cdn.test/x.js': 'sha384-X', + './data.json': 'sha384-D', + './a.js': '', + './b.js': 42, + }), + ); + expect(await findSriProtectedScripts(dir)).toEqual([]); + }); + + it('does not read a script that is not an import map, or one inside a comment', async () => { + const dir = await fixture(); + await write(dir, 'a.js', 'a'); + await write( + dir, + 'index.html', + `${importMap({ './a.js': 'sha384-A' }, 'type="application/json"')}${importMap({ './a.js': 'sha384-A' }, 'data-type="importmap"')}`, + ); + expect(await findSriProtectedScripts(dir)).toEqual([]); + }); + }); }); // The question a browser actually asks: does the file's digest match what the page pinned? Used after @@ -455,3 +569,220 @@ describe('findIntegrityMismatches', () => { expect(await findIntegrityMismatches(root)).toEqual([]); }); }); + +describe('resealIntegrity', () => { + const sha = (alg: string, text: string) => + `${alg}-${createHash(alg).update(text).digest('base64')}`; + let root: string; + beforeEach(async () => { + root = await fixture(); + }); + + /** An Angular-shaped page (script + modulepreload) hashed over the ORIGINAL bytes, then the script is stamped. */ + const hashedThenStamped = async () => { + await write(root, 'main.js', 'a();'); + await write(root, 'chunk.js', 'b();'); + const html = await write( + root, + 'index.html', + `` + + ``, + ); + const before = await snapshotScriptDigests([root]); + await write(root, 'main.js', 'a();\n//# debugId=x'); + return { html, before }; + }; + + it('rewrites the pinned hash of a changed script, so the page verifies again', async () => { + const { html, before } = await hashedThenStamped(); + await write(root, 'about.html', '

no hashes here

'); + const { files } = await resealIntegrity(before, [root]); + expect(files).toEqual([html]); + expect(await findIntegrityMismatches(root)).toEqual([]); + const page = await readFile(html, 'utf8'); + expect(page).toContain(sha('sha384', 'a();\n//# debugId=x')); + expect(page).not.toContain(sha('sha384', 'a();')); + }); + + it('leaves a script that did not change, and its page, alone', async () => { + const { html, before } = await hashedThenStamped(); + const page = await readFile(html, 'utf8'); + await write(root, 'main.js', 'a();'); // back to the hashed bytes + expect((await resealIntegrity(before, [root])).files).toEqual([]); + expect(await readFile(html, 'utf8')).toBe(page); + }); + + it('rewrites every algorithm in the value, and keeps the ones it cannot compute', async () => { + await write(root, 'main.js', 'a();'); + const html = await write( + root, + 'index.html', + ``, + ); + const before = await snapshotScriptDigests([root]); + await write(root, 'main.js', 'a2();'); + await resealIntegrity(before, [root]); + const page = await readFile(html, 'utf8'); + expect(page).toContain(sha('sha256', 'a2();')); + expect(page).toContain(sha('sha512', 'a2();')); + expect(page).toContain('md5-zzz'); + expect(await findIntegrityMismatches(root)).toEqual([]); + }); + + it('keeps the ?options suffix of a token', async () => { + await write(root, 'main.js', 'a();'); + const html = await write( + root, + 'index.html', + ``, + ); + const before = await snapshotScriptDigests([root]); + await write(root, 'main.js', 'a2();'); + await resealIntegrity(before, [root]); + expect(await readFile(html, 'utf8')).toContain(`${sha('sha384', 'a2();')}?ct=x`); + }); + + it('also rewrites the copies of the page embedded in server modules, in every directory given', async () => { + const { before } = await hashedThenStamped(); + const server = await fixture(); + const embedded = await write( + server, + 'assets-chunks/index.html.mjs', + `export default "";`, + ); + const untouched = await write(server, 'notes.txt', sha('sha384', 'a();')); + const { files } = await resealIntegrity(before, [root, server]); + expect(files).toContain(embedded); + expect(files).not.toContain(untouched); + expect(await readFile(embedded, 'utf8')).toContain(sha('sha384', 'a();\n//# debugId=x')); + expect(await readFile(untouched, 'utf8')).toBe(sha('sha384', 'a();')); + }); + + it('rewrites a hash held in an import map, which no tag mentions', async () => { + await write(root, 'lazy.js', 'lazy();'); + const html = await write( + root, + 'index.html', + ``, + ); + const before = await snapshotScriptDigests([root]); + await write(root, 'lazy.js', 'lazy();\n//# debugId=x'); + expect((await resealIntegrity(before, [root])).files).toEqual([html]); + expect(await findIntegrityMismatches(root)).toEqual([]); + }); + + // What the webpack builder does with `subresourceIntegrity` (measured on @angular-devkit/build-angular 19, Chromium): + // the page pins runtime/main/polyfills, and the RUNTIME script carries the hashes of the lazy chunks, which no page + // pins. A stamped lazy chunk was blocked while the entry scripts ran. The runtime's own bytes change when its table is + // rewritten, so its pin in the page needs a second round. + it("rewrites a hash table held in a script, and then that script's own pin", async () => { + await write(root, 'lazy.js', 'lazy();'); + const table = (lazy: string) => `var t={"lazy":"${lazy}"};run(t);`; + await write(root, 'runtime.js', table(sha('sha384', 'lazy();'))); + const html = await write( + root, + 'index.html', + ``, + ); + const before = await snapshotScriptDigests([root]); + await write(root, 'lazy.js', 'lazy();\n//# debugId=x'); // stamped after it was hashed + + const { files } = await resealIntegrity(before, [root]); + + const fresh = sha('sha384', 'lazy();\n//# debugId=x'); + expect(await readFile(join(root, 'runtime.js'), 'utf8')).toBe(table(fresh)); + expect(await readFile(html, 'utf8')).toContain(sha('sha384', table(fresh))); + expect(files.sort()).toEqual([html, join(root, 'runtime.js')].sort()); + expect(await findIntegrityMismatches(root)).toEqual([]); + }); + + it('re-seals a script that was stamped AND had its table rewritten, once for each change', async () => { + // The runtime chunk is both: the stamp appends to it, and the lazy chunk's new hash goes in it. + await write(root, 'lazy.js', 'lazy();'); + const table = (lazy: string) => `var t={"lazy":"${lazy}"};run(t);`; + const original = table(sha('sha384', 'lazy();')); + await write(root, 'runtime.js', original); + const html = await write( + root, + 'index.html', + ``, + ); + const before = await snapshotScriptDigests([root]); + await write(root, 'lazy.js', 'lazy();\n//# debugId=x'); + await write(root, 'runtime.js', `${original}\n//# debugId=y`); + + await resealIntegrity(before, [root]); + + expect(await findIntegrityMismatches(root)).toEqual([]); + const runtime = await readFile(join(root, 'runtime.js'), 'utf8'); + expect(runtime).toContain(sha('sha384', 'lazy();\n//# debugId=x')); + expect(await readFile(html, 'utf8')).toContain(sha('sha384', runtime)); + }); + + it("gives up rather than loop when two scripts hold each other's hash", async () => { + // Content-addressed hashes cannot form a cycle in a real build; a hand-made one must still terminate. + const a = await write(root, 'a.js', 'a-original'); + const b = await write(root, 'b.js', 'b-original'); + const before = await snapshotScriptDigests([root]); + await write(root, 'a.js', `x="${sha('sha384', 'b-original')}";`); + await write(root, 'b.js', `y="${sha('sha384', 'a-original')}";`); + const { files } = await resealIntegrity(before, [root]); + expect(files.sort()).toEqual([a, b].sort()); + }); + + it('rewrites EVERY occurrence of a digest, in a page and in a server module', async () => { + await write(root, 'main.js', 'a();'); + const old = sha('sha384', 'a();'); + // Angular emits the same chunk both as a tag and in the import map; the SSR copy repeats the page. + const page = ``; + const html = await write(root, 'index.html', page); + const mjs = await write(root, 'index.html.mjs', `export default ${JSON.stringify(page)};`); + const before = await snapshotScriptDigests([root]); + await write(root, 'main.js', 'a2();'); + await resealIntegrity(before, [root]); + const fresh = sha('sha384', 'a2();'); + for (const file of [html, mjs]) { + const text = await readFile(file, 'utf8'); + expect(text.split(fresh)).toHaveLength(3); + expect(text).not.toContain(old); + } + }); + + it('skips a script that is gone, and a directory that is missing', async () => { + await write(root, 'gone.js', 'x'); + const before = await snapshotScriptDigests([root]); + await rm(join(root, 'gone.js')); + expect(await resealIntegrity(before, [root, join(root, 'missing')])).toEqual({ files: [] }); + }); + + it('does not descend into node_modules, dot directories or past the depth bound', async () => { + const { before } = await hashedThenStamped(); + const hidden = await write(root, 'node_modules/x/index.html', sha('sha384', 'a();')); + const dot = await write(root, '.cache/index.html', sha('sha384', 'a();')); + const deep = await write(root, 'a/b/c/d/e/f/g/h/index.html', sha('sha384', 'a();')); + const { files } = await resealIntegrity(before, [root]); + expect(files).not.toContain(hidden); + expect(files).not.toContain(dot); + expect(files).not.toContain(deep); + }); +}); + +describe('snapshotScriptDigests', () => { + it('records every script under the directories, and nothing else', async () => { + const dir = await fixture(); + const a = await write(dir, 'a.js', 'a'); + const b = await write(dir, 'sub/b.mjs', 'b'); + const c = await write(dir, 'c.cjs', 'c'); + await write(dir, 'd.html', 'd'); + await write(dir, 'e.js.map', 'e'); + await write(dir, 'node_modules/f.js', 'f'); + const snapshot = await snapshotScriptDigests([dir]); + expect([...snapshot.keys()].sort()).toEqual([a, b, c].sort()); + const digest = (alg: string) => createHash(alg).update('a').digest('base64'); + expect(snapshot.get(a)).toEqual({ + sha256: digest('sha256'), + sha384: digest('sha384'), + sha512: digest('sha512'), + }); + }); +}); diff --git a/packages/bundler-plugin-core/src/sri.ts b/packages/bundler-plugin-core/src/sri.ts index 3641731b..653629f5 100644 --- a/packages/bundler-plugin-core/src/sri.ts +++ b/packages/bundler-plugin-core/src/sri.ts @@ -15,9 +15,9 @@ // runtime chunk (`__webpack_require__.sriHashes`), so patching the HTML alone would still break // every dynamic import. import { createHash } from 'node:crypto'; -import type { Dirent } from 'node:fs'; -import { readdir, readFile } from 'node:fs/promises'; -import { isAbsolute, join, normalize, resolve, sep } from 'node:path'; +import { createReadStream, type Dirent } from 'node:fs'; +import { access, readdir, readFile, writeFile } from 'node:fs/promises'; +import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path'; /** One `