From 67612b3b8883104ae42d501e70030dad9977be74 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 18:27:01 +0500 Subject: [PATCH 01/12] feat(bundler-plugin-core): read the app token from .env.bugsee-build-plugin Lookup order for BUGSEE_* settings: plugin option, process environment, then the nearest .env.bugsee-build-plugin at or above the bundler's project directory. The file only fills gaps (never overrides the environment); a missing or malformed file never fails the build. Closes #182. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/source-maps-usage.md | 15 ++- packages/bundler-plugin-core/README.md | 1 + .../bundler-plugin-core/src/env-file.test.ts | 121 ++++++++++++++++++ packages/bundler-plugin-core/src/env-file.ts | 76 +++++++++++ .../src/plugin.env-file.test.ts | 121 ++++++++++++++++++ packages/bundler-plugin-core/src/plugin.ts | 16 ++- 6 files changed, 345 insertions(+), 5 deletions(-) create mode 100644 packages/bundler-plugin-core/src/env-file.test.ts create mode 100644 packages/bundler-plugin-core/src/env-file.ts create mode 100644 packages/bundler-plugin-core/src/plugin.env-file.test.ts diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index bbad01873..044189d0b 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -29,11 +29,22 @@ Other bundlers are exported from `@bugsee/bundler-plugin-core` (same core, `unpl `bugseeRollupPlugin`, `bugseeEsbuildPlugin`, `bugseeRspackPlugin`. These transitively cover **Angular 17+** (esbuild builder), **Vite/meta-framework internals** (Rollup), and **Rspack/Next-webpack**. -**Options** (all optional except a token, which may also come from env): +**Where the settings come from.** For every `BUGSEE_*` setting the lookup order is: the **plugin option**, then +the **process environment**, then the **`.env.bugsee-build-plugin`** file. The setup wizard writes the app token +to that file (kept out of version control) in your project root, as Sentry's plugin does with +`.env.sentry-build-plugin`. The plugin uses the nearest copy at or above the bundler's project directory (Vite +`root`, webpack/Rspack `context`, esbuild `absWorkingDir`; the working directory for Rollup, which reports +none). Only `BUGSEE_*` keys are read (`KEY=value`, optional `export`, quotes and `#` comments). The file only +fills gaps: a variable already set in the environment is never overridden (even if set to an empty string), and +`process.env` is never written to. A missing, unreadable or malformed file is ignored and never fails the +build; without a token the plugin simply no-ops. `bugsee-cli` run by hand (§2) does NOT read this file: export +`BUGSEE_APP_TOKEN` there. + +**Options** (all optional except a token, which may also come from env or that file): | option | env fallback | default | meaning | |---|---|---|---| -| `appToken` | `BUGSEE_APP_TOKEN` | — | required to upload; absent ⇒ the plugin no-ops | +| `appToken` | `BUGSEE_APP_TOKEN` (then `.env.bugsee-build-plugin`) | — | required to upload; absent ⇒ the plugin no-ops | | `appVersion` | `BUGSEE_APP_VERSION`, then the `version` of the nearest `package.json` at or above the bundler's project directory (Vite `root`, webpack `context`, esbuild `absWorkingDir`; a nearest manifest with no version means none) | `0.0.0` | recorded on the symbol; a fallback join key. Blank or whitespace-only values count as unset. A real value is also baked into the bundle, so the app's SDK reports it (Vite, esbuild, webpack 5, Rspack and Rollup; on webpack 4 nothing can be baked, so only an explicit value is recorded). A `define` you set for `__BUGSEE_APP_VERSION__` is used as the recorded value when it is a plain string; for an expression (or on webpack 4 with no explicit value) the recorded value is left at the default and the plugin warns through `onNotice` until you set `appVersion` too | | `appBuild` | `BUGSEE_APP_BUILD`, then the CI commit id (`GITHUB_SHA`, `VERCEL_GIT_COMMIT_SHA`, `CI_COMMIT_SHA`, `CIRCLE_SHA1`, `BUILDKITE_COMMIT`, `SOURCE_VERSION`, `RENDER_GIT_COMMIT`, `COMMIT_REF`, `CF_PAGES_COMMIT_SHA`, `GIT_COMMIT`) | `0` | recorded on the symbol; a fallback join key. A real value is also baked into the bundle, so the app's SDK reports it (same bundler coverage and `define` rule as `appVersion`) | | `endpoint` | `BUGSEE_ENDPOINT` | `https://api.bugsee.com` | API endpoint | diff --git a/packages/bundler-plugin-core/README.md b/packages/bundler-plugin-core/README.md index c9c1752d0..0e85924c3 100644 --- a/packages/bundler-plugin-core/README.md +++ b/packages/bundler-plugin-core/README.md @@ -17,6 +17,7 @@ npm install --save-dev @bugsee/vite-plugin - The `unplugin`-based plugin factory behind both of those packages. - Rollup, esbuild and Rspack variants: `bugseeRollupPlugin`, `bugseeEsbuildPlugin`, `bugseeRspackPlugin`. They share the same options, but they are exported only from this package and have no dedicated wrapper package; they are less exercised than the Vite and Webpack plugins. If you use them, install this package as a dev dependency and import them from `@bugsee/bundler-plugin-core`. +- Settings lookup order: plugin option, then the process environment, then the nearest `.env.bugsee-build-plugin` at or above the bundler's project directory (only `BUGSEE_*` keys; never overrides a variable already set; a missing or malformed file never fails the build). - Option resolution (`appToken`, `appVersion`, `appBuild`, `endpoint`, `deleteMaps`, `dryRun`, `disabled`, with environment fallbacks such as `BUGSEE_APP_TOKEN`; the version also falls back to the nearest `package.json` above the bundler's project directory (blank values count as unset; Rollup, which reports no project directory, walks up from the output directory and skips a name-less, version-less marker such as a `dist/cjs/package.json` holding only `{"type":"commonjs"}`), the build to a CI commit id, and a real value is baked into the app bundle as `__BUGSEE_APP_VERSION__` / `__BUGSEE_APP_BUILD__` for the runtime SDK: through `define` on Vite, esbuild, webpack 5 and Rspack, and by rewriting each rendered chunk (with a source map) on Rollup; webpack 4 cannot bake, so there only an explicit value is recorded; a constant you define yourself is what gets recorded when it is a plain string), build-commit detection and the CLI runner. The programmatic API beyond the plugins is internal and may change between releases. diff --git a/packages/bundler-plugin-core/src/env-file.test.ts b/packages/bundler-plugin-core/src/env-file.test.ts new file mode 100644 index 000000000..600723794 --- /dev/null +++ b/packages/bundler-plugin-core/src/env-file.test.ts @@ -0,0 +1,121 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + BUILD_PLUGIN_ENV_FILE, + loadBuildPluginEnv, + mergeBuildPluginEnv, + parseEnvFile, +} from './env-file'; + +describe('parseEnvFile', () => { + it('reads KEY=VALUE lines, comments, blanks, export prefixes and quotes', () => { + const parsed = parseEnvFile( + [ + '# a comment', + '', + 'BUGSEE_APP_TOKEN=abc123', + 'export BUGSEE_ENDPOINT = "https://x.test"', + "BUGSEE_APP_BUILD='42'", + 'BUGSEE_APP_VERSION=1.2.3 # trailing', + 'BUGSEE_EMPTY=', + ].join('\r\n'), + ); + expect(parsed).toEqual({ + BUGSEE_APP_TOKEN: 'abc123', + BUGSEE_ENDPOINT: 'https://x.test', + BUGSEE_APP_BUILD: '42', + BUGSEE_APP_VERSION: '1.2.3', + BUGSEE_EMPTY: '', + }); + }); + + it('keeps a # inside a quoted value and a # without preceding space in an unquoted one', () => { + expect(parseEnvFile('BUGSEE_APP_TOKEN="a #b"\nBUGSEE_APP_BUILD=a#b')).toEqual({ + BUGSEE_APP_TOKEN: 'a #b', + BUGSEE_APP_BUILD: 'a#b', + }); + }); + + it('skips malformed lines and non-BUGSEE keys, never throws', () => { + expect( + parseEnvFile( + 'garbage\n=novalue\n1BAD=x\nNODE_ENV=production\nBUGSEE_APP_TOKEN=ok\n\u0000\u0001', + ), + ).toEqual({ BUGSEE_APP_TOKEN: 'ok' }); + }); + + it('treats an unterminated quote as the raw remainder', () => { + expect(parseEnvFile('BUGSEE_APP_TOKEN="abc')).toEqual({ BUGSEE_APP_TOKEN: '"abc' }); + }); +}); + +describe('loadBuildPluginEnv', () => { + let root: string; + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-envfile-')); + }); + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('reads the file in the project dir', () => { + writeFileSync(join(root, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_TOKEN=tok\n'); + expect(loadBuildPluginEnv(root)).toEqual({ BUGSEE_APP_TOKEN: 'tok' }); + }); + + it('finds the NEAREST file walking up, and stops at the first one found', () => { + writeFileSync(join(root, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_TOKEN=outer\n'); + const app = join(root, 'packages', 'app'); + mkdirSync(app, { recursive: true }); + expect(loadBuildPluginEnv(app)).toEqual({ BUGSEE_APP_TOKEN: 'outer' }); + writeFileSync(join(app, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_BUILD=7\n'); + expect(loadBuildPluginEnv(app)).toEqual({ BUGSEE_APP_BUILD: '7' }); + }); + + it('returns {} when there is no file, or the path is a directory', () => { + // A directory with the file's name is unreadable as a file: skipped, never thrown. The walk then + // reaches the filesystem root, where no such file is expected. + mkdirSync(join(root, BUILD_PLUGIN_ENV_FILE)); + expect(loadBuildPluginEnv(root)).toEqual({}); + }); + + it('survives a malformed (binary) file', () => { + writeFileSync(join(root, BUILD_PLUGIN_ENV_FILE), Buffer.from([0xff, 0xfe, 0x00, 0x3d, 0x3d])); + expect(loadBuildPluginEnv(root)).toEqual({}); + }); + + it('returns {} when the working directory is gone and no root is given', () => { + const gone = () => { + throw new Error('ENOENT uncwd'); + }; + expect(loadBuildPluginEnv(undefined, gone)).toEqual({}); + }); + + it('defaults to the cwd', () => { + writeFileSync(join(root, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_TOKEN=cwd\n'); + expect(loadBuildPluginEnv(undefined, () => root)).toEqual({ BUGSEE_APP_TOKEN: 'cwd' }); + }); +}); + +describe('mergeBuildPluginEnv', () => { + it('never overrides a variable already set, even to an empty string', () => { + const merged = mergeBuildPluginEnv( + { BUGSEE_APP_TOKEN: 'from-env', BUGSEE_APP_BUILD: '', OTHER: 'x' }, + { BUGSEE_APP_TOKEN: 'from-file', BUGSEE_APP_BUILD: '9', BUGSEE_ENDPOINT: 'e' }, + ); + expect(merged).toEqual({ + BUGSEE_APP_TOKEN: 'from-env', + BUGSEE_APP_BUILD: '', + OTHER: 'x', + BUGSEE_ENDPOINT: 'e', + }); + }); + + it('does not mutate its inputs', () => { + const env = { A: '1' }; + mergeBuildPluginEnv(env, { BUGSEE_APP_TOKEN: 't' }); + expect(env).toEqual({ A: '1' }); + }); +}); diff --git a/packages/bundler-plugin-core/src/env-file.ts b/packages/bundler-plugin-core/src/env-file.ts new file mode 100644 index 000000000..f24a261b1 --- /dev/null +++ b/packages/bundler-plugin-core/src/env-file.ts @@ -0,0 +1,76 @@ +// `.env.bugsee-build-plugin` — the file the setup wizard writes the app token to (git-ignored), the way +// Sentry's plugin reads `.env.sentry-build-plugin`. Lookup order for every BUGSEE_* setting: plugin option, +// then the process environment, then this file. The file only FILLS GAPS: a variable already set in the +// environment (even to an empty string) is never overridden, and `process.env` itself is never written to. +// Nothing here may fail a build: a missing, unreadable or malformed file is simply "no values". +import { readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import type { EnvRecord } from './run-cli'; + +export const BUILD_PLUGIN_ENV_FILE = '.env.bugsee-build-plugin'; + +const LINE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/; + +function unquote(raw: string): string { + const value = raw.trim(); + const quote = value[0]; + if (quote === '"' || quote === "'") { + const end = value.indexOf(quote, 1); + // An unterminated quote is kept verbatim rather than guessed at. + return end > 0 ? value.slice(1, end) : value; + } + // Unquoted: an inline comment starts at whitespace + `#`. + const hash = value.search(/\s#/); + return (hash === -1 ? value : value.slice(0, hash)).trim(); +} + +/** Parse dotenv text. Only `BUGSEE_*` keys are kept; malformed lines are skipped. */ +export function parseEnvFile(text: string): Record { + const out: Record = {}; + for (const line of text.split(/\r?\n/)) { + const match = LINE.exec(line.trim()); + if (match?.[1]?.startsWith('BUGSEE_') && match[2] !== undefined) { + out[match[1]] = unquote(match[2]); + } + } + return out; +} + +/** + * Load the NEAREST `.env.bugsee-build-plugin` at or above `root` (the bundler's project directory; the + * working directory when none is known). The first file found wins; an unreadable one is skipped. + */ +export function loadBuildPluginEnv( + root: string | undefined, + cwd: () => string = () => process.cwd(), +): Record { + let dir: string; + try { + dir = resolve(root ?? cwd()); + } catch { + return {}; + } + for (;;) { + try { + return parseEnvFile(readFileSync(join(dir, BUILD_PLUGIN_ENV_FILE), 'utf8')); + } catch { + // missing / a directory / unreadable: keep walking up + } + const parent = dirname(dir); + if (parent === dir) { + return {}; + } + dir = parent; + } +} + +/** `env` with the file's values filling only the keys `env` does not have at all. */ +export function mergeBuildPluginEnv(env: EnvRecord, file: Record): EnvRecord { + const merged: EnvRecord = { ...env }; + for (const [key, value] of Object.entries(file)) { + if (!(key in merged)) { + merged[key] = value; + } + } + return merged; +} diff --git a/packages/bundler-plugin-core/src/plugin.env-file.test.ts b/packages/bundler-plugin-core/src/plugin.env-file.test.ts new file mode 100644 index 000000000..a12424887 --- /dev/null +++ b/packages/bundler-plugin-core/src/plugin.env-file.test.ts @@ -0,0 +1,121 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { UnpluginOptions } from 'unplugin'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { BUILD_PLUGIN_ENV_FILE } from './env-file'; +import type { BugseePluginOptions, ResolvedPluginOptions } from './resolve'; + +// `.env.bugsee-build-plugin` (#182): option > environment > file, looked up from the BUNDLER's project dir. +const { uploadSpy } = vi.hoisted(() => ({ + uploadSpy: vi.fn(async (_resolved: unknown, _outDir: string, _deps?: unknown) => undefined), +})); +vi.mock('./resolve', async (importOriginal) => ({ + ...(await importOriginal()), + runPluginUpload: uploadSpy, +})); + +const { bugseeUnpluginFactory } = await import('./plugin'); +const makePlugin = (options?: BugseePluginOptions): UnpluginOptions => + bugseeUnpluginFactory(options, { framework: 'vite' }) as UnpluginOptions; + +type ViteHooks = { + config: (c: { root?: string }) => unknown; + writeBundle: (o: { dir: string }) => Promise; +}; +const vite = (p: UnpluginOptions) => p.vite as unknown as ViteHooks; +const uploaded = () => uploadSpy.mock.calls[0]?.[0] as ResolvedPluginOptions; + +describe('plugin reads .env.bugsee-build-plugin', () => { + let root: string; + let cwd: string; + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'bugsee-plugin-env-')); + // A cwd with no env file anywhere nearby, so only the project root can supply the token. + cwd = mkdtempSync(join(tmpdir(), 'bugsee-plugin-cwd-')); + vi.spyOn(process, 'cwd').mockReturnValue(cwd); + vi.stubEnv('BUGSEE_APP_TOKEN', undefined as unknown as string); + delete process.env.BUGSEE_APP_TOKEN; + uploadSpy.mockClear(); + }); + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + rmSync(root, { recursive: true, force: true }); + rmSync(cwd, { recursive: true, force: true }); + }); + + it('takes the token from the file in the bundler project dir', async () => { + writeFileSync(join(root, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_TOKEN=file-token\n'); + const plugin = makePlugin(); + vite(plugin).config({ root }); + await vite(plugin).writeBundle({ dir: '/out' }); + expect(uploaded()).toMatchObject({ enabled: true, appToken: 'file-token' }); + }); + + it('finds the nearest file above a nested project dir', async () => { + writeFileSync(join(root, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_TOKEN=outer\n'); + const app = join(root, 'apps', 'web'); + mkdirSync(app, { recursive: true }); + const plugin = makePlugin(); + vite(plugin).config({ root: app }); + await vite(plugin).writeBundle({ dir: '/out' }); + expect(uploaded().appToken).toBe('outer'); + }); + + it('falls back to the working directory when the bundler reports no root', async () => { + writeFileSync(join(cwd, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_TOKEN=cwd-token\n'); + const plugin = makePlugin(); + await vite(plugin).writeBundle({ dir: '/out' }); + expect(uploaded().appToken).toBe('cwd-token'); + }); + + it('the plugin option beats the environment, which beats the file', async () => { + writeFileSync( + join(root, BUILD_PLUGIN_ENV_FILE), + 'BUGSEE_APP_TOKEN=file\nBUGSEE_ENDPOINT=file-ep\n', + ); + vi.stubEnv('BUGSEE_APP_TOKEN', 'env-token'); + + const fromEnv = makePlugin(); + vite(fromEnv).config({ root }); + await vite(fromEnv).writeBundle({ dir: '/out' }); + expect(uploaded()).toMatchObject({ appToken: 'env-token', endpoint: 'file-ep' }); + + uploadSpy.mockClear(); + const fromOption = makePlugin({ appToken: 'option-token' }); + vite(fromOption).config({ root }); + await vite(fromOption).writeBundle({ dir: '/out' }); + expect(uploaded().appToken).toBe('option-token'); + }); + + it('never writes into process.env', () => { + writeFileSync(join(root, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_TOKEN=file-token\n'); + vite(makePlugin()).config({ root }); + expect(process.env.BUGSEE_APP_TOKEN).toBeUndefined(); + }); + + it('a missing file leaves the plugin disabled and the build intact', async () => { + const plugin = makePlugin(); + expect(() => vite(plugin).config({ root })).not.toThrow(); + await vite(plugin).writeBundle({ dir: '/out' }); + expect(uploaded()).toMatchObject({ enabled: false, appToken: '' }); + }); + + it('a malformed file never fails the build and yields no token', async () => { + writeFileSync( + join(root, BUILD_PLUGIN_ENV_FILE), + Buffer.from([0xff, 0x00, 0x3d, 0x0a, 0x3d, 0x3d]), + ); + const plugin = makePlugin(); + expect(() => vite(plugin).config({ root })).not.toThrow(); + await vite(plugin).writeBundle({ dir: '/out' }); + expect(uploaded().enabled).toBe(false); + }); + + it('a file token turns on map emission like any other token', () => { + writeFileSync(join(root, BUILD_PLUGIN_ENV_FILE), 'BUGSEE_APP_TOKEN=file-token\n'); + const result = vite(makePlugin()).config({ root }) as { build?: { sourcemap?: boolean } }; + expect(result.build?.sourcemap).toBe(true); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 806ccf6aa..65c0ba900 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -12,6 +12,7 @@ import { UNBAKEABLE_IDENTITY, } from './app-identity'; import { bakeIdentity, type ParseChunk } from './bake-identity'; +import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; import type { BundlerBuildContext } from './register-build'; import { type BugseePluginOptions, @@ -198,7 +199,12 @@ function webpackBuild(mode: string | undefined): BundlerBuildContext { export const bugseeUnpluginFactory: UnpluginFactory = ( options = {}, ) => { - const resolved = resolvePluginOptions(options, process.env); + // Lookup order for every BUGSEE_* setting: plugin option, process environment, then the nearest + // `.env.bugsee-build-plugin` (env-file.ts; it only fills variables the environment does not set). The + // baseline looks from the working directory; a bundler that reports its project directory (Vite `root`, + // webpack `context`, esbuild `absWorkingDir`) re-resolves from there, below. + let env = mergeBuildPluginEnv(process.env, loadBuildPluginEnv(undefined)); + let resolved = resolvePluginOptions(options, env); const name = 'bugsee'; // The app identity comes from the BUNDLER's project directory (Vite `root`, webpack `context`, esbuild @@ -214,7 +220,11 @@ export const bugseeUnpluginFactory: UnpluginFactory, ): ResolvedIdentity => { - bundlerIdentity = resolveIdentity(options, process.env, root, {}, fixed); + if (root !== undefined) { + env = mergeBuildPluginEnv(process.env, loadBuildPluginEnv(root)); + resolved = resolvePluginOptions(options, env); + } + bundlerIdentity = resolveIdentity(options, env, root, {}, fixed); if (resolved.enabled) { unreadableIdentityNotices(fixed, bundlerIdentity.identityDefines, userDefines).forEach( notify(resolved), @@ -231,7 +241,7 @@ export const bugseeUnpluginFactory: UnpluginFactory Date: Wed, 11 Nov 2026 18:30:08 +0500 Subject: [PATCH 02/12] feat(bundler-plugin-core): upload source maps from the esbuild and Rspack plugins bugseeEsbuildPlugin (onEnd) and bugseeRspackPlugin (afterEmit) now reuse runPluginUpload with the same SRI guard as the Vite/Rollup (writeBundle) and webpack (afterEmit) hooks; esbuild also turns sourcemap on when unset. Proven with real esbuild and @rspack/core builds plus the real bugsee-cli. Docs no longer claim Angular/Rspack coverage that was not true: Angular's builder does not accept esbuild plugins, so a post-build recipe (sourcemaps inject, then debug-files upload) is documented. Closes #184. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/design/source-maps.md | 14 +- docs/source-maps-usage.md | 26 +- packages/bundler-plugin-core/README.md | 2 +- packages/bundler-plugin-core/package.json | 2 + .../src/plugin.esbuild-rspack.test.ts | 200 +++++++++ .../src/plugin.real-build.test.ts | 140 ++++++ packages/bundler-plugin-core/src/plugin.ts | 69 ++- pnpm-lock.yaml | 399 +++++++++++++----- 8 files changed, 731 insertions(+), 121 deletions(-) create mode 100644 packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts create mode 100644 packages/bundler-plugin-core/src/plugin.real-build.test.ts diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 96776315e..df0a4493e 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -124,8 +124,14 @@ debugId ⇒ server falls back to `appVersion`/`appBuild`. are conveniences, not the mechanism: `bugsee-cli` operates on a finished output dir independent of the bundler, so the **universal path is the standalone CLI post-build step** (`sourcemaps inject` → `debug-files upload`; run before deploy). See `docs/source-maps-usage.md §2`. To widen the zero-config plugin experience cheaply, `@bugsee/bundler-plugin-core` -also exports `bugseeRollupPlugin` / `bugseeEsbuildPlugin` / `bugseeRspackPlugin` (same core) — transitively covering -Angular 17+ (esbuild), Vite/meta-framework internals (Rollup) and Rspack/Next-webpack. Deno/Bun stay CLI-post-build. +also exports `bugseeRollupPlugin` / `bugseeEsbuildPlugin` / `bugseeRspackPlugin` (same core). Their end-of-build hooks +are Rollup `writeBundle`, esbuild `onEnd` (registered through unplugin's `esbuild.setup`; skipped on a failed build +or `write: false`; the plugin also turns `sourcemap` on when unset/`false`) and Rspack `afterEmit`, each calling +`runPluginUpload` with the same SRI guard as Vite and webpack (#184; real esbuild and Rspack builds are exercised in +`plugin.real-build.test.ts`). Rspack has no in-compilation stamp stage wired, so it takes the post-emit inject path +(an SRI build is refused, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild +plugins, so Angular uses the documented CLI post-build recipe (`docs/source-maps-usage.md §2`). Next.js on webpack +uses the webpack plugin. Bun/`tsc`/`swc` stay CLI-post-build. **Identifying the correct final map (multi-layer).** The identity is the bundle's own `//# sourceMappingURL` + the debug-ID: `inject` follows each bundle's sourceMappingURL to its declared map and stamps the SAME debug-ID into both, @@ -170,8 +176,8 @@ still runs, `{injected: false, uploaded: false}`. - **Importmap integrity** (`', + ); + const errors: unknown[] = []; + const before = requests.length; + await runRspack( + config(app, { + plugins: [ + bugseeRspackPlugin({ + ...pluginOptions, + endpoint, + failOnError: false, + onError: (e) => errors.push(e), + }), + ], + }), + ); + expect(errors.map(String).join()).toContain('refusing to stamp debug-IDs'); + expect(requests.length).toBe(before); + expect(readFileSync(join(app.out, 'main.js'), 'utf8')).not.toContain('debugId'); + expect(existsSync(join(app.out, 'main.js.map'))).toBe(true); + }); + + it('a build with a compile error uploads nothing', async () => { + const app = makeApp('rspack-broken'); + writeFileSync(app.entry, "import './does-not-exist.js';\n"); + const before = requests.length; + const { errors } = await runRspack( + config(app, { plugins: [bugseeRspackPlugin({ ...pluginOptions, endpoint })] }), + ); + expect(errors).toBeGreaterThan(0); + expect(requests.length).toBe(before); + // Rspack emits nothing for a broken production build, so there is no output to stamp. + expect(existsSync(app.out)).toBe(false); + }); }); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 9603741d7..c84879e5f 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -202,6 +202,30 @@ interface EsbuildBuildLike { onEnd(callback: (result: { errors: readonly unknown[] }) => void | Promise): void; } +/** + * Run uploads for one output directory ONE AFTER ANOTHER. `runPluginUpload` makes a concurrent caller JOIN the + * in-flight run, which is right for one build with several outputs but wrong for esbuild builds that share an + * outdir (tsup's esm + cjs): the in-flight run scanned the directory BEFORE the second build wrote its files, + * and its delete-maps step then removes the second build's maps unuploaded. Each build's own run therefore + * starts only once the previous one has settled, and scans what is on disk by then. A failure in an earlier + * run does not block the next, and is reported to the build that owned it. + */ +const uploadTails = new Map>(); +function serialUpload(outDir: string, run: () => Promise): Promise { + const result = (uploadTails.get(outDir) ?? Promise.resolve()).then(run); + const tail = result.then( + () => undefined, + () => undefined, + ); + uploadTails.set(outDir, tail); + void tail.then(() => { + if (uploadTails.get(outDir) === tail) { + uploadTails.delete(outDir); + } + }); + return result; +} + /** esbuild's output directory: `outdir`, else the directory of `outfile`, resolved against `absWorkingDir`. */ function esbuildOutputDir(options: EsbuildBuildLike['initialOptions']): string | undefined { const out = resolveOutputDir({ dir: options.outdir, file: options.outfile }); @@ -223,8 +247,24 @@ export const bugseeUnpluginFactory: UnpluginFactory(); + const loadFile = (root: string | undefined): Record => { + if (options.disabled) { + return {}; + } + const { values, problem } = loadBuildPluginEnv(root); + if (problem !== undefined && !reported.has(problem)) { + reported.add(problem); + notify(resolved)(problem); + } + return values; + }; + // `resolved` is assigned right below; `loadFile` only reads it after that (it is `let` for the hook refresh). + let resolved = resolvePluginOptions(options, process.env); + let env = mergeBuildPluginEnv(process.env, loadFile(undefined)); + resolved = resolvePluginOptions(options, env); const name = 'bugsee'; // The app identity comes from the BUNDLER's project directory (Vite `root`, webpack `context`, esbuild @@ -241,7 +281,7 @@ export const bugseeUnpluginFactory: UnpluginFactory, ): ResolvedIdentity => { if (root !== undefined) { - env = mergeBuildPluginEnv(process.env, loadBuildPluginEnv(root)); + env = mergeBuildPluginEnv(process.env, loadFile(root)); resolved = resolvePluginOptions(options, env); } bundlerIdentity = resolveIdentity(options, env, root, {}, fixed); @@ -398,13 +438,13 @@ export const bugseeUnpluginFactory: UnpluginFactory 0) { initialOptions.define = define; } - // Like Vite: make the build EMIT the maps this plugin exists to upload. Only the default and an - // explicit `false` are overridden; `external`/`linked`/`inline`/`both` are deliberate choices. - if ( - resolved.enabled && - (initialOptions.sourcemap === undefined || initialOptions.sourcemap === false) - ) { - initialOptions.sourcemap = true; + // Make the build EMIT the maps this plugin exists to upload. Only when the user said nothing: + // `external`, not `true`, because `true` appends a `//# sourceMappingURL` comment and the map is + // deleted after upload, leaving a shipped bundle that points at a missing file. The CLI pairs a + // bundle with its sibling `.map` without the comment. An explicit `false` (or any other + // value) is the user's choice and is left alone; with `false` the empty-maps warning explains. + if (resolved.enabled && initialOptions.sourcemap === undefined) { + initialOptions.sourcemap = 'external'; } }, // End of the build (#184): upload what esbuild wrote, as Vite/Rollup `writeBundle` do. unplugin's own @@ -418,7 +458,21 @@ export const bugseeUnpluginFactory: UnpluginFactory + runPluginUpload(forOutput(outDir), outDir, { bundler: {} }), + ); } }); }, diff --git a/packages/bundler-plugin-core/src/test-setup.ts b/packages/bundler-plugin-core/src/test-setup.ts new file mode 100644 index 000000000..b18e14bdd --- /dev/null +++ b/packages/bundler-plugin-core/src/test-setup.ts @@ -0,0 +1,16 @@ +// Test isolation: the plugin reads `.env.bugsee-build-plugin` from the working directory at startup, so a +// developer's real file in this repo (or any parent) would flip every test that expects "no token => disabled". +// Every test therefore sees NO file, except the files that exercise the lookup itself and opt in with +// `globalThis.__BUGSEE_REAL_ENV_FILE__ = true`. +import { vi } from 'vitest'; + +vi.mock('./env-file', async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + loadBuildPluginEnv: (...args: Parameters) => + (globalThis as { __BUGSEE_REAL_ENV_FILE__?: boolean }).__BUGSEE_REAL_ENV_FILE__ + ? real.loadBuildPluginEnv(...args) + : { values: {} }, + }; +}); diff --git a/packages/bundler-plugin-core/vitest.config.ts b/packages/bundler-plugin-core/vitest.config.ts index 558ca571f..b24eacf4b 100644 --- a/packages/bundler-plugin-core/vitest.config.ts +++ b/packages/bundler-plugin-core/vitest.config.ts @@ -12,10 +12,11 @@ export default defineConfig({ testTimeout: 30_000, environment: 'node', include: ['src/**/*.test.ts'], + setupFiles: ['src/test-setup.ts'], coverage: { provider: 'v8', include: ['src/**/*.ts'], - exclude: ['src/**/*.test.ts', 'src/**/*.test-d.ts', 'src/**/*.d.ts'], + exclude: ['src/test-setup.ts', 'src/**/*.test.ts', 'src/**/*.test-d.ts', 'src/**/*.d.ts'], thresholds: { lines: 100, functions: 100, statements: 100, branches: 90 }, }, }, From 4722ee0c8ec909efeb160d8df3a5b70887994d51 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 18:48:33 +0500 Subject: [PATCH 04/12] feat(bundler-plugin-core): skip esbuild/Rspack dev builds; refuse a project-root outfile Review findings on #196: esbuild/Rspack dev and watch builds no longer upload and delete the local maps unless uploadInDevelopment is set (Rspack by mode, esbuild by NODE_ENV=development); a bare outfile in the project directory is refused with a notice instead of walking the whole project. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/source-maps-usage.md | 7 +- .../src/plugin.esbuild-rspack.test.ts | 104 +++++++++++++++++- packages/bundler-plugin-core/src/plugin.ts | 51 +++++++-- packages/bundler-plugin-core/src/resolve.ts | 12 ++ 4 files changed, 163 insertions(+), 11 deletions(-) diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 8bf27e678..1606d1ec6 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -35,7 +35,11 @@ pairs a bundle with its sibling `.map` anyway). An explicit value, including `fa `false` there are no maps to upload and the CLI reports that. esbuild builds that share one output directory (tsup's ESM + CJS) are uploaded one after another, and each upload deletes only the maps that existed when it started. Use `outdir`: with `outfile` the plugin uploads the whole directory the file is in (every `.js` and -`.map` there, not just yours) and says so in a notice. Rspack stamps after emit rather than inside the compilation, +`.map` there, not just yours) and says so in a notice; an `outfile` in the project directory itself (a bare +`outfile: 'bundle.js'`) is refused, with a notice, because that would make the whole project the output directory. +Development builds do not upload and leave the local maps alone unless you set `uploadInDevelopment: true`: +Rspack states its mode (`development` is skipped), esbuild states none, so only `NODE_ENV=development` marks a +dev build (a bare `esbuild --watch` without it uploads on every rebuild, so set it or disable the plugin there). Rspack stamps after emit rather than inside the compilation, so an Rspack build that adds Subresource Integrity hashes is refused, not stamped (§2 covers that case). **What these do not cover.** **Angular's builder does not accept esbuild plugins**, so `bugseeEsbuildPlugin` @@ -74,6 +78,7 @@ version control) in your project root, as Sentry's plugin does with `.env.sentry | `endpoint` | `BUGSEE_ENDPOINT` | `https://api.bugsee.com` | API endpoint | | `deleteMaps` | — | `true` | delete client `.map`s after upload (privacy) | | `dryRun` | — | `false` | run the CLI with `--dry-run` (no upload, no delete) | +| `uploadInDevelopment` | — | `false` | esbuild / Rspack only: upload from builds the bundler calls development (see §1) | | `disabled` | — | `false` | turn the plugin off (e.g. dev builds) | | `vcs` | — | `true` | capture the build's commit SHA / branch (see §1.1); `false` records nothing at all, even an explicit `commit` | | `commit` | `BUGSEE_BUILD_COMMIT` | detected | explicit commit SHA for this build | diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index e254defad..08977996e 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -281,7 +281,7 @@ describe('rspack: upload after emit', () => { it('passes the bundler mode on, and treats an unset mode as production (same as webpack)', async () => { const dev = rspackCompiler('/out', 'development'); - applyRspack({ appToken: 'tok' }, dev.compiler); + applyRspack({ appToken: 'tok', uploadInDevelopment: true }, dev.compiler); await dev.taps[0]?.fn(); expect(bundlerOf(0)).toEqual({ isProduction: false, configuration: 'development' }); const unset = rspackCompiler('/out'); @@ -306,3 +306,105 @@ describe('rspack: upload after emit', () => { expect(uploadSpy).not.toHaveBeenCalled(); }); }); + +describe('development builds do not upload (and do not delete the local maps) by default', () => { + beforeEach(() => { + uploadSpy.mockReset(); + uploadSpy.mockImplementation(async () => undefined); + }); + + it('rspack: mode development is skipped, with one notice; production and an unset mode are not', async () => { + const notices: string[] = []; + const dev = rspackCompiler('/out', 'development'); + applyRspack({ appToken: 'tok', onNotice: (m) => notices.push(m) }, dev.compiler); + await dev.taps[0]?.fn(); + await dev.taps[0]?.fn(); + expect(uploadSpy).not.toHaveBeenCalled(); + // Said once (other notices, e.g. about an unbakeable identity on this fake compiler, are not ours). + const devNotices = notices.filter((m) => m.includes('uploadInDevelopment')); + expect(devNotices).toHaveLength(1); + for (const mode of ['production', undefined]) { + const c = rspackCompiler('/out', mode); + applyRspack({ appToken: 'tok' }, c.compiler); + await c.taps[0]?.fn(); + } + expect(uploadSpy).toHaveBeenCalledTimes(2); + }); + + it('rspack: uploadInDevelopment opts back in', async () => { + const c = rspackCompiler('/out', 'development'); + applyRspack({ appToken: 'tok', uploadInDevelopment: true }, c.compiler); + await c.taps[0]?.fn(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + }); + + it('esbuild: NODE_ENV=development is skipped; any other value uploads', async () => { + const saved = process.env.NODE_ENV; + try { + process.env.NODE_ENV = 'development'; + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outdir: '/abs/dist' }, + ).end(); + expect(uploadSpy).not.toHaveBeenCalled(); + expect(notices[0]).toContain('esbuild development build'); + await esbuildRun( + { appToken: 'tok', uploadInDevelopment: true }, + { outdir: '/abs/dist' }, + ).end(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + process.env.NODE_ENV = 'production'; + await esbuildRun({ appToken: 'tok' }, { outdir: '/abs/dist' }).end(); + expect(uploadSpy).toHaveBeenCalledTimes(2); + } finally { + if (saved === undefined) { + delete process.env.NODE_ENV; + } else { + process.env.NODE_ENV = saved; + } + } + }); + + it('a disabled plugin says nothing about development builds', async () => { + const notices: string[] = []; + const c = rspackCompiler('/out', 'development'); + applyRspack({ appToken: 'tok', disabled: true, onNotice: (m) => notices.push(m) }, c.compiler); + await c.taps[0]?.fn(); + expect(notices).toEqual([]); + }); +}); + +describe('esbuild: a bare outfile in the project directory is refused', () => { + beforeEach(() => { + uploadSpy.mockReset(); + uploadSpy.mockImplementation(async () => undefined); + }); + + it('uploads nothing and says why (outfile: "bundle.js" would make the whole project the output dir)', async () => { + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outfile: 'bundle.js', absWorkingDir: '/proj/app' }, + ).end(); + expect(uploadSpy).not.toHaveBeenCalled(); + expect(notices.some((m) => m.includes('project directory itself'))).toBe(true); + }); + + it('also against the cwd when there is no absWorkingDir', async () => { + await esbuildRun( + { appToken: 'tok', onNotice: () => undefined }, + { outfile: 'bundle.js' }, + ).end(); + expect(uploadSpy).not.toHaveBeenCalled(); + }); + + it('an outfile in a SUBdirectory, and any outdir (even the project dir), still upload', async () => { + await esbuildRun( + { appToken: 'tok', onNotice: () => undefined }, + { outfile: 'dist/bundle.js', absWorkingDir: '/proj/app' }, + ).end(); + await esbuildRun({ appToken: 'tok' }, { outdir: '.', absWorkingDir: '/proj/app' }).end(); + expect(uploadSpy).toHaveBeenCalledTimes(2); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index c84879e5f..775809072 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -261,6 +261,23 @@ export const bugseeUnpluginFactory: UnpluginFactory { + if (!reported.has(message)) { + reported.add(message); + notify(resolved)(message); + } + }; + // esbuild / Rspack dev builds do not upload (and so do not delete the local maps) unless asked to. + const skipDevelopment = (isProduction: boolean | undefined, bundlerName: string): boolean => { + if (!resolved.enabled || resolved.uploadInDevelopment || isProduction !== false) { + return false; + } + say( + `${bundlerName} development build: source maps were not uploaded and were left in place. Set \`uploadInDevelopment: true\` to upload from dev builds too.`, + ); + return true; + }; // `resolved` is assigned right below; `loadFile` only reads it after that (it is `let` for the hook refresh). let resolved = resolvePluginOptions(options, process.env); let env = mergeBuildPluginEnv(process.env, loadFile(undefined)); @@ -464,11 +481,24 @@ export const bugseeUnpluginFactory: UnpluginFactory runPluginUpload(forOutput(outDir), outDir, { bundler: {} }), @@ -491,10 +521,13 @@ export const bugseeUnpluginFactory: UnpluginFactory { const dir = compiler.options.output?.path; - if (typeof dir === 'string' && dir !== '') { - await runPluginUpload(forOutput(dir), dir, { - bundler: webpackBuild(compiler.options.mode), - }); + const bundler = webpackBuild(compiler.options.mode); + if ( + typeof dir === 'string' && + dir !== '' && + !skipDevelopment(bundler.isProduction, 'Rspack') + ) { + await runPluginUpload(forOutput(dir), dir, { bundler }); } }); }, diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index adaf4197b..9dc750aa5 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -115,6 +115,15 @@ export interface BugseePluginOptions { * output (or {@link BugseePluginOptions.projectRoot}), scope included. */ packageId?: string; + /** + * Upload from a build the bundler calls DEVELOPMENT. Default `false` (#196 review). + * + * Every esbuild watch rebuild and every Rspack `mode: 'development'` build would otherwise spawn + * `bugsee-cli`, upload dev bundles as symbols and delete the local `.map`s devtools rely on. Rspack states + * its mode; esbuild states none, so there only `NODE_ENV=development` marks a dev build. (Vite, Rollup and + * webpack are not gated by this option.) + */ + uploadInDevelopment?: boolean; } /** Map `BUGSEE_REGISTER_BUILD` onto the setting. An unrecognised value is NOT a setting. */ @@ -169,6 +178,8 @@ export interface ResolvedPluginOptions { registerBuild: RegisterBuildSetting; /** Explicit `package_id`; `undefined` means "the nearest package.json". */ packageId: string | undefined; + /** Whether a build the bundler calls development still uploads. Default false. */ + uploadInDevelopment: boolean; /** * `define` entries that bake the app's version/build into its bundle (`__BUGSEE_APP_VERSION__`, * `__BUGSEE_APP_BUILD__`, JSON-encoded). Only values that were actually found are present — never the @@ -243,6 +254,7 @@ export function resolvePluginOptions( registerBuild: options.registerBuild ?? registerBuildFromEnv(env.BUGSEE_REGISTER_BUILD) ?? 'release', packageId: options.packageId, + uploadInDevelopment: options.uploadInDevelopment ?? false, nodeEnv: env.NODE_ENV, }; } From e0977ab69dbaa35ae8e1b80aff30d1f1dc80adc5 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 18:52:58 +0500 Subject: [PATCH 05/12] fix(bundler-plugin-core): narrow the Rspack dev gate, no dev maps, clearer outfile notices Review follow-ups on #196: only Rspack mode development is skipped (none uploads); esbuild does not force maps on for a development build; an outfile in or above the project directory is refused with a single notice; the per-directory notice is emitted only when an upload follows; tests pin NODE_ENV. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/source-maps-usage.md | 4 +- .../src/plugin.esbuild-rspack.test.ts | 64 +++++++++++++++++++ packages/bundler-plugin-core/src/plugin.ts | 40 +++++++----- .../bundler-plugin-core/src/test-setup.ts | 7 +- 4 files changed, 95 insertions(+), 20 deletions(-) diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 1606d1ec6..6809a3b03 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -35,10 +35,10 @@ pairs a bundle with its sibling `.map` anyway). An explicit value, including `fa `false` there are no maps to upload and the CLI reports that. esbuild builds that share one output directory (tsup's ESM + CJS) are uploaded one after another, and each upload deletes only the maps that existed when it started. Use `outdir`: with `outfile` the plugin uploads the whole directory the file is in (every `.js` and -`.map` there, not just yours) and says so in a notice; an `outfile` in the project directory itself (a bare +`.map` there, not just yours) and says so in a notice; an `outfile` in the project directory itself or above it (a bare `outfile: 'bundle.js'`) is refused, with a notice, because that would make the whole project the output directory. Development builds do not upload and leave the local maps alone unless you set `uploadInDevelopment: true`: -Rspack states its mode (`development` is skipped), esbuild states none, so only `NODE_ENV=development` marks a +Rspack states its mode (only `development` is skipped; `none` and `production` upload), esbuild states none, so only `NODE_ENV=development` marks a dev build (a bare `esbuild --watch` without it uploads on every rebuild, so set it or disable the plugin there). Rspack stamps after emit rather than inside the compilation, so an Rspack build that adds Subresource Integrity hashes is refused, not stamped (§2 covers that case). diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index 08977996e..cff81c062 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -408,3 +408,67 @@ describe('esbuild: a bare outfile in the project directory is refused', () => { expect(uploadSpy).toHaveBeenCalledTimes(2); }); }); + +describe('review follow-ups', () => { + beforeEach(() => { + uploadSpy.mockReset(); + uploadSpy.mockImplementation(async () => undefined); + }); + + it("rspack: mode 'none' is a release setting and still uploads", async () => { + const c = rspackCompiler('/out', 'none'); + applyRspack({ appToken: 'tok' }, c.compiler); + await c.taps[0]?.fn(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + }); + + it('esbuild: a development build does not force maps on (unless it uploads in dev)', async () => { + const saved = process.env.NODE_ENV; + process.env.NODE_ENV = 'development'; + try { + const dev: FakeBuild['initialOptions'] = { outdir: '/abs/dist' }; + esbuildRun({ appToken: 'tok' }, dev); + expect(dev.sourcemap).toBeUndefined(); + const optIn: FakeBuild['initialOptions'] = { outdir: '/abs/dist' }; + esbuildRun({ appToken: 'tok', uploadInDevelopment: true }, optIn); + expect(optIn.sourcemap).toBe('external'); + } finally { + process.env.NODE_ENV = saved; + } + }); + + it('esbuild: an outfile ABOVE the project is refused too, and gets one notice, not two', async () => { + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outfile: '/proj/bundle.js', absWorkingDir: '/proj/app' }, + ).end(); + expect(uploadSpy).not.toHaveBeenCalled(); + const ours = notices.filter((m) => m.includes('outfile')); + expect(ours).toHaveLength(1); + expect(ours[0]).toContain('Nothing was uploaded'); + }); + + it('esbuild: a development outfile build gets only the development notice', async () => { + const saved = process.env.NODE_ENV; + process.env.NODE_ENV = 'development'; + try { + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outfile: '/abs/public/app.js' }, + ).end(); + expect(notices.filter((m) => m.includes('outfile'))).toEqual([]); + } finally { + process.env.NODE_ENV = saved; + } + }); + + it('esbuild: a sibling outfile directory (not an ancestor of the project) still uploads', async () => { + await esbuildRun( + { appToken: 'tok', onNotice: () => undefined }, + { outfile: '/proj/app2/out.js', absWorkingDir: '/proj/app' }, + ).end(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 775809072..984c0d6f6 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -2,7 +2,7 @@ // vite/rollup `writeBundle`, webpack/rspack `afterEmit` and esbuild `onEnd`. The per-bundler entry points (@bugsee/vite-plugin, // @bugsee/webpack-plugin) are thin wrappers over `bugseeUnplugin`. The output-dir resolver is a pure, // tested helper; the framework hook registration is thin glue exercised by the real-build e2e (SM-B/SM-C). -import { dirname, resolve } from 'node:path'; +import { dirname, isAbsolute, relative, resolve } from 'node:path'; import { createUnplugin, type UnpluginFactory, type UnpluginInstance } from 'unplugin'; import { APP_BUILD_DEFINE, @@ -460,7 +460,13 @@ export const bugseeUnpluginFactory: UnpluginFactory.map` without the comment. An explicit `false` (or any other // value) is the user's choice and is left alone; with `false` the empty-maps warning explains. - if (resolved.enabled && initialOptions.sourcemap === undefined) { + // Not for a development build (NODE_ENV=development) that will not upload: it would pay for maps + // nothing references. `uploadInDevelopment` keeps them. + if ( + resolved.enabled && + initialOptions.sourcemap === undefined && + (resolved.uploadInDevelopment || resolved.nodeEnv !== 'development') + ) { initialOptions.sourcemap = 'external'; } }, @@ -476,29 +482,28 @@ export const bugseeUnpluginFactory: UnpluginFactory runPluginUpload(forOutput(outDir), outDir, { bundler: {} }), @@ -522,10 +527,11 @@ export const bugseeUnpluginFactory: UnpluginFactory { const dir = compiler.options.output?.path; const bundler = webpackBuild(compiler.options.mode); + // Only `development` is skipped: `mode: 'none'` is a legitimate release setting (own minification). if ( typeof dir === 'string' && dir !== '' && - !skipDevelopment(bundler.isProduction, 'Rspack') + !skipDevelopment(compiler.options.mode !== 'development', 'Rspack') ) { await runPluginUpload(forOutput(dir), dir, { bundler }); } diff --git a/packages/bundler-plugin-core/src/test-setup.ts b/packages/bundler-plugin-core/src/test-setup.ts index b18e14bdd..fac56b1d7 100644 --- a/packages/bundler-plugin-core/src/test-setup.ts +++ b/packages/bundler-plugin-core/src/test-setup.ts @@ -2,7 +2,7 @@ // developer's real file in this repo (or any parent) would flip every test that expects "no token => disabled". // Every test therefore sees NO file, except the files that exercise the lookup itself and opt in with // `globalThis.__BUGSEE_REAL_ENV_FILE__ = true`. -import { vi } from 'vitest'; +import { beforeEach, vi } from 'vitest'; vi.mock('./env-file', async (importOriginal) => { const real = await importOriginal(); @@ -14,3 +14,8 @@ vi.mock('./env-file', async (importOriginal) => { : { values: {} }, }; }); + +// NODE_ENV decides whether esbuild counts as a development build; pin it so a developer's shell cannot flip tests. +beforeEach(() => { + vi.stubEnv('NODE_ENV', 'test'); +}); From be5d9817f0840c8652f7cfe1a64b7765a755438e Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 18:59:47 +0500 Subject: [PATCH 06/12] fix(bundler-plugin-core): tsup notice, retry-safe concurrent esbuild uploads, env-file notices Round-2 review of #196: - esbuild write:false (tsup always sets it) now says why nothing was uploaded; docs state tsup is not covered and give the onSuccess recipe. Real tsup build tested. - Concurrent esbuild builds: a run waits until no build of the directory is in flight and a failure that coincides with another build starting is retried (max 3), fixing the inject/upload window. Real test with a slow-inject CLI wrapper; three-build test for the queue tail guard. - outdir '.' (project dir or above) refused like a bare outfile; sourcemap:false explained by a notice. - env file: empty values and a file in the home directory (project dir == home) now produce notices. - whitespace-only BUGSEE_APP_TOKEN no longer enables the plugin. - BUGSEE_REQUIRE_CLI declared in turbo.json for test and test:coverage; docs: stale sourcemap text, Deno removed. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/design/source-maps.md | 8 +- docs/source-maps-usage.md | 23 +- .../bundler-plugin-core/src/env-file.test.ts | 20 +- packages/bundler-plugin-core/src/env-file.ts | 18 +- .../bundler-plugin-core/src/orchestrate.ts | 11 +- .../src/plugin.esbuild-rspack.test.ts | 205 +++++++++++++++++- .../src/plugin.real-build.test.ts | 103 +++++++++ packages/bundler-plugin-core/src/plugin.ts | 131 ++++++++--- .../bundler-plugin-core/src/resolve.test.ts | 12 + packages/bundler-plugin-core/src/resolve.ts | 4 +- turbo.json | 6 +- 11 files changed, 483 insertions(+), 58 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 36b29d8a8..cd0c3ae5b 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -126,12 +126,16 @@ are conveniences, not the mechanism: `bugsee-cli` operates on a finished output deploy). See `docs/source-maps-usage.md §2`. To widen the zero-config plugin experience cheaply, `@bugsee/bundler-plugin-core` also exports `bugseeRollupPlugin` / `bugseeEsbuildPlugin` / `bugseeRspackPlugin` (same core). Their end-of-build hooks are Rollup `writeBundle`, esbuild `onEnd` (registered through unplugin's `esbuild.setup`; skipped on a failed build -or `write: false`; the plugin also turns `sourcemap` on when unset/`false`) and Rspack `afterEmit`, each calling +or `write: false`, which is what tsup always sets, with a notice; the plugin sets `sourcemap: 'external'` only when it is +unset, and says so when it is `false`) and Rspack `afterEmit`, each calling `runPluginUpload` with the same SRI guard as Vite and webpack (#184; real esbuild and Rspack builds are exercised in `plugin.real-build.test.ts`). Rspack has no in-compilation stamp stage wired, so it takes the post-emit inject path (an SRI build is refused, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild plugins, so Angular uses the documented CLI post-build recipe (`docs/source-maps-usage.md §2`). Next.js on webpack -uses the webpack plugin. Bun/`tsc`/`swc` stay CLI-post-build. +uses the webpack plugin. Bun, tsup and `tsc`/`swc` stay CLI-post-build (tsup via `onSuccess`). +Concurrent esbuild builds into one directory: uploads are serialised per directory, a run waits until no build of +that directory is in flight, deletes only the maps that existed when it started, and a failure that coincides with +another build starting is retried (up to 3 attempts) rather than reported. **Identifying the correct final map (multi-layer).** The identity is the bundle's own `//# sourceMappingURL` + the debug-ID: `inject` follows each bundle's sourceMappingURL to its declared map and stamps the SAME debug-ID into both, diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 6809a3b03..7c96e8d92 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -28,12 +28,12 @@ module.exports = { devtool: 'source-map', plugins: [bugseeWebpackPlugin({ appTok Other bundlers are exported from `@bugsee/bundler-plugin-core` (same core, `unplugin`-based): `bugseeRollupPlugin`, `bugseeEsbuildPlugin`, `bugseeRspackPlugin`. Each injects debug-IDs, uploads the maps and deletes them at the end of the build, exactly as the Vite/webpack plugins do (Rollup: `writeBundle`; esbuild: -`onEnd`, so it works with the esbuild JS API, `tsup` and any tool that accepts esbuild plugins; Rspack: +`onEnd`, so it works with the esbuild JS API and any tool that accepts esbuild plugins AND lets esbuild write the files; Rspack: `afterEmit`), with the same SRI guard. With esbuild the plugin sets `sourcemap: 'external'` when you did not set `sourcemap` at all (external, so the shipped bundle carries no `//# sourceMappingURL` comment pointing at a map that is deleted after upload; the CLI pairs a bundle with its sibling `.map` anyway). An explicit value, including `false`, is left alone: with -`false` there are no maps to upload and the CLI reports that. esbuild builds that share one output directory -(tsup's ESM + CJS) are uploaded one after another, and each upload deletes only the maps that existed when it +`false` there are no maps to upload, and the plugin says so through `onNotice`. esbuild builds that share one output directory +(an ESM + CJS pair) are uploaded one after another, and each upload deletes only the maps that existed when it started. Use `outdir`: with `outfile` the plugin uploads the whole directory the file is in (every `.js` and `.map` there, not just yours) and says so in a notice; an `outfile` in the project directory itself or above it (a bare `outfile: 'bundle.js'`) is refused, with a notice, because that would make the whole project the output directory. @@ -42,6 +42,13 @@ Rspack states its mode (only `development` is skipped; `none` and `production` u dev build (a bare `esbuild --watch` without it uploads on every rebuild, so set it or disable the plugin there). Rspack stamps after emit rather than inside the compilation, so an Rspack build that adds Subresource Integrity hashes is refused, not stamped (§2 covers that case). +**tsup is not covered by the esbuild plugin.** tsup always runs esbuild with `write: false` and writes the files +itself afterwards, so nothing is on disk when the plugin's end-of-build hook runs. The plugin then uploads nothing +and says so through `onNotice`. Use the CLI after the build instead, e.g. in `tsup.config.ts`: +`onSuccess: 'bugsee-cli sourcemaps inject dist && bugsee-cli debug-files upload dist --type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD"'` +(with `sourcemap: true`, and `BUGSEE_APP_TOKEN` exported). The same applies to any tool that calls esbuild with +`write: false`. + **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 either (also §2). Next.js on webpack uses the webpack plugin. @@ -64,7 +71,7 @@ version control) in your project root, as Sentry's plugin does with `.env.sentry `process.env` is never written to. A blank (whitespace-only) environment variable counts as unset, the same rule the version and build already follow. - *Failure.* A missing, unreadable or malformed file never fails the build; without a token the plugin no-ops. A - file that is found but unusable (unreadable, UTF-16/binary, or holding none of the three keys) is reported once + file that is found but unusable (unreadable, UTF-16/binary, holding none of the three keys or only empty values, or sitting in the home directory when that is your project directory) is reported once through `onNotice`, naming the file but never its contents. - `bugsee-cli` run by hand (§2) does NOT read this file: export `BUGSEE_APP_TOKEN` there. @@ -136,16 +143,16 @@ vs the branch head), the tree reads clean and the recorded SHA still is not what `commit` (or set `BUGSEE_BUILD_COMMIT`) with the SHA. An explicit value skips the dirty check. It must be 7-64 hex characters — a branch name or tag is ignored rather than sent. -## 2. Any other target — the universal CLI step (Bun, Deno, tsc/swc, Angular, no-plugin builds) +## 2. Any other target — the universal CLI step (Bun, tsup, tsc/swc, Angular, no-plugin builds) The plugins are **not** the mechanism — `bugsee-cli` operates on a finished output directory, whatever produced -it. For toolchains without a usable plugin hook (Bun's built-in bundler, Deno, `tsc`/`swc`, custom pipelines), run +it. For toolchains without a usable plugin hook (Bun's built-in bundler, tsup, `tsc`/`swc`, custom pipelines), run the CLI as a **post-build step**: ```bash # 1. build with EXTERNAL source maps enabled, e.g.: bun build ./src/index.ts --outdir dist --sourcemap=external -# deno … (emits maps) · tsc --sourceMap · ng build --source-map · esbuild --sourcemap … +# tsc --sourceMap · ng build --source-map · esbuild --sourcemap … # 2. inject debug-IDs into the built bundles + their maps (BEFORE you deploy): bugsee-cli sourcemaps inject ./dist @@ -190,4 +197,4 @@ stub the SDK reads. This is exactly what the plugins automate; the CLI is the sa (and `debug-files upload --dry-run`) to see the pairings/uploads without performing them. - **Not covered: bytecode targets.** React-Native/Hermes compiles JS → bytecode, which drops the injected comment and stub, so the running code reports no debug-ID. That needs a Hermes-specific compose flow and is handled by the - separate React-Native SDK, not this (web/node/bun/deno) SDK. + separate React-Native SDK, not this (web/node/bun) SDK. diff --git a/packages/bundler-plugin-core/src/env-file.test.ts b/packages/bundler-plugin-core/src/env-file.test.ts index 665b53541..46770f37c 100644 --- a/packages/bundler-plugin-core/src/env-file.test.ts +++ b/packages/bundler-plugin-core/src/env-file.test.ts @@ -138,8 +138,15 @@ describe('loadBuildPluginEnv', () => { file(h, 'BUGSEE_APP_TOKEN=home\n'); const proj = mk('home', 'work', 'proj'); expect(loadBuildPluginEnv(proj, { home: () => h })).toEqual({ values: {} }); - // ...and a project that IS the home directory reads nothing either. - expect(loadBuildPluginEnv(h, { home: () => h })).toEqual({ values: {} }); + // ...and a project that IS the home directory (a container WORKDIR of /root) reads nothing, but says why. + const atHome = loadBuildPluginEnv(h, { home: () => h }); + expect(atHome.values).toEqual({}); + expect(atHome.problem).toContain('home directory'); + expect(atHome.problem).not.toContain('home\n'); + // With no file there, nothing is said. + expect(loadBuildPluginEnv(mk('home2'), { home: () => join(base, 'home2') })).toEqual({ + values: {}, + }); // A project directory ABOVE home (home inside it) reads nothing. expect(loadBuildPluginEnv(base, { home: () => h })).toEqual({ values: {} }); }); @@ -165,6 +172,15 @@ describe('loadBuildPluginEnv', () => { expect(result.problem).not.toContain('secret.test'); }); + it('reports a file whose only entry has an EMPTY value (it would silently disable the plugin)', () => { + const proj = mk('proj'); + file(proj, 'BUGSEE_APP_TOKEN=\nBUGSEE_APP_BUILD= \n'); + const result = loadBuildPluginEnv(proj, { home }); + expect(result.problem).toContain('non-empty value'); + file(proj, 'BUGSEE_APP_TOKEN=\nBUGSEE_APP_BUILD=5\n'); + expect(loadBuildPluginEnv(proj, { home }).problem).toBeUndefined(); + }); + it('reports a UTF-16 / binary file as such', () => { const proj = mk('proj'); writeFileSync( diff --git a/packages/bundler-plugin-core/src/env-file.ts b/packages/bundler-plugin-core/src/env-file.ts index e22418162..dc7f12951 100644 --- a/packages/bundler-plugin-core/src/env-file.ts +++ b/packages/bundler-plugin-core/src/env-file.ts @@ -105,10 +105,18 @@ export function loadBuildPluginEnv( } } for (let current = dir; ; current = dirname(current)) { + const path = join(current, BUILD_PLUGIN_ENV_FILE); if (atOrAbove(current, home)) { - return { values: {} }; + // A project that IS the home directory (a container WORKDIR of /root) is never searched: say so + // rather than silently ignoring a file the user put there on purpose. + return current === dir && existsSync(path) + ? { + values: {}, + path, + problem: `${path} is in your home directory, which is never searched for ${BUILD_PLUGIN_ENV_FILE}; it was ignored. Set the variables in the environment, or build from a project subdirectory.`, + } + : { values: {} }; } - const path = join(current, BUILD_PLUGIN_ENV_FILE); if (existsSync(path)) { return readEnvFile(path); } @@ -134,13 +142,15 @@ function readEnvFile(path: string): EnvFileResult { }; } const values = parseEnvFile(text); - if (Object.keys(values).length === 0) { + // An empty value (`BUGSEE_APP_TOKEN=`) is not usable either: it would silently disable the plugin. + const usable = Object.values(values).some((value) => value.trim() !== ''); + if (!usable) { return { values, path, problem: `${path} was found but holds no usable ${[...FILE_KEYS].join(' / ')} entry ` + - '(expected UTF-8 `KEY=value` lines); it was ignored.', + '(expected UTF-8 `KEY=value` lines with a non-empty value); it was ignored.', }; } return { values, path }; diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 83c3b8403..f300d5dac 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -155,6 +155,11 @@ export async function defaultDeleteMapFiles( return deleted; } +/** Where a contained upload failure goes when the user gave no `onError`. */ +export function defaultUploadErrorHandler(error: unknown): void { + console.warn(`[bugsee] source-map upload skipped: ${String(error)}`); +} + /** Drive `bugsee-cli`: inject debug-IDs into the build, upload the source-maps, then delete the client maps. */ export async function uploadSourcemaps( options: UploadSourcemapsOptions, @@ -171,11 +176,7 @@ export async function uploadSourcemaps( const deleteMaps = options.deleteMaps ?? true; const dryFlag = dryRun ? ['--dry-run'] : []; const cliOptions: RunBugseeCliOptions = { token: appToken, endpoint }; - const onError = - options.onError ?? - ((error: unknown): void => { - console.warn(`[bugsee] source-map upload skipped: ${String(error)}`); - }); + const onError = options.onError ?? defaultUploadErrorHandler; try { if (options.preStamped === true) { diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index cff81c062..11cf9764b 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -31,18 +31,28 @@ type FakeBuild = { sourcemap?: boolean | string; define?: Record; }; + onStart: (cb: () => void) => void; onEnd: (cb: (result: EndResult) => Promise) => void; }; function esbuildRun(options: BugseePluginOptions, initialOptions: FakeBuild['initialOptions']) { const ends: Array<(result: EndResult) => Promise> = []; - const build: FakeBuild = { initialOptions, onEnd: (cb) => ends.push(cb) }; + const starts: Array<() => void> = []; + const build: FakeBuild = { + initialOptions, + onStart: (cb) => starts.push(cb), + onEnd: (cb) => ends.push(cb), + }; const hooks = makePlugin(options).esbuild as unknown as { config: (o: FakeBuild['initialOptions']) => void; setup: (b: FakeBuild) => void; }; hooks.config(initialOptions); hooks.setup(build); - return { ends, end: (result: EndResult = { errors: [] }) => ends[0]?.(result) }; + return { + ends, + start: () => starts[0]?.(), + end: (result: EndResult = { errors: [] }) => ends[0]?.(result), + }; } const bundlerOf = (call: number) => @@ -118,12 +128,43 @@ describe('esbuild: upload at the end of the build', () => { expect(quiet).toEqual([]); }); - it('does nothing for a build that writes nothing (no outdir/outfile, or write:false)', async () => { + it('does nothing for a build with no outdir/outfile', async () => { await esbuildRun({ appToken: 'tok' }, {}).end(); - await esbuildRun({ appToken: 'tok' }, { outdir: '/abs/dist', write: false }).end(); expect(uploadSpy).not.toHaveBeenCalled(); }); + it('write:false (tsup always sets it): nothing is uploaded, and a notice says why, once', async () => { + const notices: string[] = []; + const run = esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outdir: '/abs/dist', write: false }, + ); + await run.end(); + await run.end(); + expect(uploadSpy).not.toHaveBeenCalled(); + const ours = notices.filter((m) => m.includes('write: false')); + expect(ours).toHaveLength(1); + expect(ours[0]).toContain('tsup'); + expect(ours[0]).toContain('onSuccess'); + }); + + it('an explicit sourcemap:false is left alone but explained', () => { + const notices: string[] = []; + const own: FakeBuild['initialOptions'] = { outdir: '/abs/dist', sourcemap: false }; + esbuildRun({ appToken: 'tok', onNotice: (m) => notices.push(m) }, own); + expect(own.sourcemap).toBe(false); + expect(notices.some((m) => m.includes('sourcemap: false'))).toBe(true); + const quiet: string[] = []; + esbuildRun( + { appToken: 'tok', disabled: true, onNotice: (m) => quiet.push(m) }, + { + outdir: '/abs/dist', + sourcemap: false, + }, + ); + expect(quiet).toEqual([]); + }); + it('does not upload a FAILED build', async () => { await esbuildRun({ appToken: 'tok' }, { outdir: '/abs/dist' }).end({ errors: [{}] }); expect(uploadSpy).not.toHaveBeenCalled(); @@ -181,6 +222,7 @@ describe('esbuild: upload at the end of the build', () => { plugin.config(initialOptions); plugin.setup({ initialOptions, + onStart: () => undefined, onEnd: (cb) => ends.push(() => cb({ errors: [] })), }); } @@ -210,6 +252,7 @@ describe('esbuild: upload at the end of the build', () => { for (let i = 0; i < 2; i++) { plugin.setup({ initialOptions: { outdir: '/abs/failing' }, + onStart: () => undefined, onEnd: (cb) => ends.push(() => cb({ errors: [] })), }); } @@ -232,6 +275,7 @@ describe('esbuild: upload at the end of the build', () => { for (const outdir of ['/abs/a', '/abs/b']) { plugin.setup({ initialOptions: { outdir }, + onStart: () => undefined, onEnd: (cb) => ends.push(() => cb({ errors: [] })), }); } @@ -399,13 +443,19 @@ describe('esbuild: a bare outfile in the project directory is refused', () => { expect(uploadSpy).not.toHaveBeenCalled(); }); - it('an outfile in a SUBdirectory, and any outdir (even the project dir), still upload', async () => { + it('an outfile in a SUBdirectory still uploads; outdir "." (the whole project) is refused too', async () => { await esbuildRun( { appToken: 'tok', onNotice: () => undefined }, { outfile: 'dist/bundle.js', absWorkingDir: '/proj/app' }, ).end(); - await esbuildRun({ appToken: 'tok' }, { outdir: '.', absWorkingDir: '/proj/app' }).end(); - expect(uploadSpy).toHaveBeenCalledTimes(2); + expect(uploadSpy).toHaveBeenCalledTimes(1); + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outdir: '.', absWorkingDir: '/proj/app' }, + ).end(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + expect(notices.some((m) => m.includes('Nothing was uploaded'))).toBe(true); }); }); @@ -444,7 +494,7 @@ describe('review follow-ups', () => { { outfile: '/proj/bundle.js', absWorkingDir: '/proj/app' }, ).end(); expect(uploadSpy).not.toHaveBeenCalled(); - const ours = notices.filter((m) => m.includes('outfile')); + const ours = notices.filter((m) => m.includes('project directory itself')); expect(ours).toHaveLength(1); expect(ours[0]).toContain('Nothing was uploaded'); }); @@ -472,3 +522,142 @@ describe('review follow-ups', () => { expect(uploadSpy).toHaveBeenCalledTimes(1); }); }); + +describe('esbuild: builds into one directory settle before and while an upload runs', () => { + beforeEach(() => { + uploadSpy.mockReset(); + uploadSpy.mockImplementation(async () => undefined); + }); + + /** A run whose captured onError is fed `error` on its first `failures` calls. */ + const failing = (failures: number, error = new Error('exit 11: map has no debug_id')) => { + let calls = 0; + uploadSpy.mockImplementation(async (resolved: unknown) => { + calls++; + if (calls <= failures) { + (resolved as ResolvedPluginOptions).onError?.(error); + } + return undefined; + }); + }; + + it('a failure while another build started is retried, not reported', async () => { + const a = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/race1' }); + const b = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race1' }); + a.start(); + const pending: Array | undefined> = []; + let calls = 0; + uploadSpy.mockImplementation(async (resolved: unknown) => { + calls++; + if (calls === 1) { + // Build B starts writing while A's inject -> upload is running, and A trips over its map. + b.start(); + (resolved as ResolvedPluginOptions).onError?.(new Error('exit 11')); + pending.push(b.end()); + } + return undefined; + }); + await a.end(); + await Promise.all(pending); + expect(calls).toBeGreaterThanOrEqual(2); + }); + + it('a failure with NO concurrent build is reported as configured: thrown with failOnError', async () => { + failing(1); + const run = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/race2' }); + run.start(); + await expect(run.end()).rejects.toThrow('exit 11'); + expect(uploadSpy).toHaveBeenCalledTimes(1); + }); + + it('... or sent to onError otherwise, and to the default warning when there is none', async () => { + failing(1); + const seen: unknown[] = []; + const run = esbuildRun( + { appToken: 'tok', onError: (e) => seen.push(e) }, + { outdir: '/abs/race3' }, + ); + run.start(); + await run.end(); + expect(String(seen[0])).toContain('exit 11'); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + try { + failing(1); + const quiet = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race4' }); + quiet.start(); + await quiet.end(); + expect(warn.mock.calls.join()).toContain('source-map upload skipped'); + } finally { + warn.mockRestore(); + } + }); + + it('retries are bounded: a failure that keeps coinciding with new builds is finally reported', async () => { + const seen: unknown[] = []; + const run = esbuildRun( + { appToken: 'tok', onError: (e) => seen.push(e) }, + { outdir: '/abs/race5' }, + ); + const other = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race5' }); + run.start(); + const pending: Array | undefined> = []; + let ownCalls = 0; + uploadSpy.mockImplementation(async (resolved: unknown) => { + // Only the owning run's attempts are counted; the other build's own run succeeds. + if ((resolved as ResolvedPluginOptions).onError !== undefined && ownCalls < 3) { + ownCalls++; + other.start(); + (resolved as ResolvedPluginOptions).onError?.(new Error('exit 11')); + pending.push(other.end()); + } + return undefined; + }); + await run.end(); + await Promise.all(pending); + expect(ownCalls).toBe(3); + expect(seen).toHaveLength(1); + }); + + it('a run waits for a build that is still in flight before it scans', async () => { + const a = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race6' }); + const b = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race6' }); + a.start(); + b.start(); + const first = a.end(); + await new Promise((r) => setTimeout(r, 60)); + expect(uploadSpy).not.toHaveBeenCalled(); + await b.end(); + await first; + expect(uploadSpy).toHaveBeenCalled(); + }); + + it('three overlapping builds stay strictly one after another (the queue tail guard)', async () => { + const gates: Array<() => void> = []; + const order: string[] = []; + uploadSpy.mockImplementation(async () => { + const n = gates.length; + order.push(`start${n}`); + await new Promise((r) => gates.push(r)); + order.push(`end${n}`); + return undefined; + }); + const runs = [1, 2, 3].map(() => esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race7' })); + const done = [runs[0]?.end(), runs[1]?.end()]; + await new Promise((r) => setTimeout(r, 20)); + expect(order).toEqual(['start0']); + gates[0]?.(); + await done[0]; + await new Promise((r) => setTimeout(r, 20)); + // Build 1's queue slot has settled but build 2 is still running: build 3 must queue behind build 2. + expect(order).toEqual(['start0', 'end0', 'start1']); + const third = runs[2]?.end(); + await new Promise((r) => setTimeout(r, 20)); + expect(order).toEqual(['start0', 'end0', 'start1']); + gates[1]?.(); + await done[1]; + await new Promise((r) => setTimeout(r, 20)); + expect(order).toEqual(['start0', 'end0', 'start1', 'end1', 'start2']); + gates[2]?.(); + await third; + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index c34e4a4ef..10608a644 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -5,6 +5,7 @@ import { spawnSync } from 'node:child_process'; import { + chmodSync, existsSync, mkdirSync, mkdtempSync, @@ -18,6 +19,7 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { rspack } from '@rspack/core'; import { build as esbuild } from 'esbuild'; +import { build as tsupBuild } from 'tsup'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { bugseeEsbuildPlugin, bugseeRspackPlugin } from './plugin'; import { resolveBugseeCli } from './run-cli'; @@ -274,3 +276,104 @@ describeReal('real Rspack build', () => { expect(existsSync(app.out)).toBe(false); }); }); + +describeReal('real tsup build (tsup always runs esbuild with write:false)', () => { + it('uploads nothing, leaves the maps, and says why instead of silently doing nothing', async () => { + const app = makeApp('tsup-app'); + const notices: string[] = []; + const before = requests.length; + await tsupBuild({ + config: false, + entry: [app.entry], + format: ['esm', 'cjs'], + outDir: app.out, + sourcemap: true, + silent: true, + dts: false, + clean: true, + esbuildPlugins: [ + bugseeEsbuildPlugin({ + ...pluginOptions, + endpoint, + onNotice: (m) => notices.push(m), + }), + ], + }); + expect(requests.length).toBe(before); + expect(notices.filter((m) => m.includes('write: false'))).toHaveLength(1); + const files = readdirSync(app.out); + expect(files.filter((f) => f.endsWith('.map')).length).toBeGreaterThan(0); + expect(files.filter((f) => f.endsWith('.js') || f.endsWith('.cjs'))).not.toEqual([]); + for (const f of files.filter((f) => /\.c?js$/.test(f))) { + expect(readFileSync(join(app.out, f), 'utf8')).not.toContain('debugId'); + } + }); +}); + +describeReal("a build writing while another build's upload is between inject and upload", () => { + it('is retried, not reported as a failed upload (slow-inject CLI wrapper)', async () => { + const app = makeApp('esbuild-inject-race'); + writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); + // A BUGSEE_CLI_PATH wrapper: run the real CLI, then (for `sourcemaps inject` only) dwell, so a second + // build can write AFTER inject scanned but BEFORE the upload scans. Without the retry, the upload trips + // over the second build's map (no debug_id, exit 11) and reports a failure. + const wrapper = join(app.dir, 'slow-inject.js'); + writeFileSync( + wrapper, + `const { spawnSync } = require('node:child_process'); +const r = spawnSync(process.execPath, [${JSON.stringify(cli)}, ...process.argv.slice(2)], { stdio: 'inherit' }); +if (process.argv[2] === 'sourcemaps') { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1500); } +process.exit(r.status ?? 1); +`, + ); + chmodSync(wrapper, 0o755); + const errors: unknown[] = []; + const plugin = bugseeEsbuildPlugin({ + ...pluginOptions, + endpoint, + failOnError: false, + onError: (e) => errors.push(e), + }); + const saved = process.env.BUGSEE_CLI_PATH; + process.env.BUGSEE_CLI_PATH = wrapper; + try { + await Promise.all([ + esbuild({ + entryPoints: [app.entry], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + format: 'esm', + outExtension: { '.js': '.mjs' }, + logLevel: 'silent', + plugins: [plugin], + }), + // Starts only after A's inject has scanned, so its files land between A's inject and A's upload. + new Promise((r) => setTimeout(r, 700)).then(() => + esbuild({ + entryPoints: [join(app.dir, 'second.js')], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + format: 'cjs', + outExtension: { '.js': '.cjs' }, + logLevel: 'silent', + plugins: [plugin], + }), + ), + ]); + } finally { + if (saved === undefined) { + delete process.env.BUGSEE_CLI_PATH; + } else { + process.env.BUGSEE_CLI_PATH = saved; + } + } + expect(errors).toEqual([]); + const files = readdirSync(app.out); + for (const bundle of ['index.mjs', 'second.cjs']) { + expect(readFileSync(join(app.out, bundle), 'utf8')).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); + } + expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 984c0d6f6..225b3962f 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -13,11 +13,13 @@ import { } from './app-identity'; import { bakeIdentity, type ParseChunk } from './bake-identity'; import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; +import { defaultUploadErrorHandler } from './orchestrate'; import type { BundlerBuildContext } from './register-build'; import { type BugseePluginOptions, notify, type ResolvedIdentity, + type ResolvedPluginOptions, resolveIdentity, resolvePluginOptions, runPluginUpload, @@ -199,6 +201,7 @@ function webpackBuild(mode: string | undefined): BundlerBuildContext { /** The slice of esbuild's plugin `build` object the end-of-build upload reads. */ interface EsbuildBuildLike { initialOptions: { outdir?: string; outfile?: string; absWorkingDir?: string; write?: boolean }; + onStart(callback: () => void): void; onEnd(callback: (result: { errors: readonly unknown[] }) => void | Promise): void; } @@ -226,6 +229,64 @@ function serialUpload(outDir: string, run: () => Promise): Promise { return result; } +/** + * What the esbuild builds writing into one directory are doing. Serialising uploads is not enough on its own: + * a run is `inject` then `upload`, each scanning the whole directory, so a build that WRITES between the two + * leaves a map without a debug-id for the upload to trip over (exit 11). So a run first waits until no build + * of the directory is in flight, and a failure while another build started or ended in the meantime is + * retried (the later scan sees finished files) instead of being reported. + */ +interface DirActivity { + inflight: number; + /** Bumped at every build start: lets a run tell that the directory was touched while it ran. */ + starts: number; +} +const dirActivity = new Map(); +const activityOf = (outDir: string): DirActivity => { + let activity = dirActivity.get(outDir); + if (activity === undefined) { + activity = { inflight: 0, starts: 0 }; + dirActivity.set(outDir, activity); + } + return activity; +}; +const MAX_UPLOAD_ATTEMPTS = 3; +const IDLE_WAIT_MS = 60_000; +const IDLE_POLL_MS = 25; + +async function uploadWhenSettled(base: ResolvedPluginOptions, outDir: string): Promise { + const activity = activityOf(outDir); + for (let attempt = 1; ; attempt++) { + for (let waited = 0; activity.inflight > 0 && waited < IDLE_WAIT_MS; waited += IDLE_POLL_MS) { + await new Promise((r) => setTimeout(r, IDLE_POLL_MS)); + } + const startsBefore = activity.starts; + const errors: unknown[] = []; + // The run's own failure handling is replaced by a capture, so a failure caused by a concurrent build + // can be retried; whatever remains is reported exactly as the user configured (failOnError / onError). + await runPluginUpload( + { ...base, failOnError: false, onError: (error) => errors.push(error) }, + outDir, + { bundler: {} }, + ); + const [first] = errors; + if (first === undefined) { + return; + } + if ( + (activity.starts !== startsBefore || activity.inflight > 0) && + attempt < MAX_UPLOAD_ATTEMPTS + ) { + continue; + } + if (base.failOnError) { + throw first; + } + (base.onError ?? defaultUploadErrorHandler)(first); + return; + } +} + /** esbuild's output directory: `outdir`, else the directory of `outfile`, resolved against `absWorkingDir`. */ function esbuildOutputDir(options: EsbuildBuildLike['initialOptions']): string | undefined { const out = resolveOutputDir({ dir: options.outdir, file: options.outfile }); @@ -459,9 +520,14 @@ export const bugseeUnpluginFactory: UnpluginFactory.map` without the comment. An explicit `false` (or any other - // value) is the user's choice and is left alone; with `false` the empty-maps warning explains. + // value) is the user's choice and is left alone; with `false` there is nothing to upload, and a notice says so. // Not for a development build (NODE_ENV=development) that will not upload: it would pay for maps // nothing references. `uploadInDevelopment` keeps them. + if (resolved.enabled && initialOptions.sourcemap === false) { + say( + 'esbuild `sourcemap: false` emits no source maps, so there is nothing to upload (the plugin leaves an explicit false alone). Remove it, or use `sourcemap: "external"`, to symbolicate this build.', + ); + } if ( resolved.enabled && initialOptions.sourcemap === undefined && @@ -474,41 +540,54 @@ export const bugseeUnpluginFactory: UnpluginFactory { + if (activity !== undefined) { + activity.inflight++; + activity.starts++; + } + }); build.onEnd(async (result) => { - // A failed build wrote nothing worth uploading; `write: false` wrote nothing at all. - if (result.errors.length > 0 || build.initialOptions.write === false) { + if (activity !== undefined) { + activity.inflight = Math.max(0, activity.inflight - 1); + } + // A failed build wrote nothing worth uploading. + if (result.errors.length > 0 || outDir === undefined) { return; } - const outDir = esbuildOutputDir(build.initialOptions); - if (outDir !== undefined) { - const { outdir, outfile } = build.initialOptions; - // esbuild states no mode: only NODE_ENV=development marks a dev build. - if (skipDevelopment(resolved.nodeEnv !== 'development', 'esbuild')) { + // `write: false`: esbuild hands the files to the caller, who writes them later (tsup ALWAYS does + // this), so they are not on disk when this hook runs. Say so instead of doing nothing silently. + if (build.initialOptions.write === false) { + say( + 'esbuild runs with `write: false` (tsup always does), so the output is not on disk when the plugin runs and nothing was uploaded. Run the bugsee-cli post-build step instead (`bugsee-cli sourcemaps inject ` then `bugsee-cli debug-files upload --type sourcemaps`, e.g. from tsup `onSuccess`); see docs/source-maps-usage.md section 2.', + ); + return; + } + const { outdir, outfile } = build.initialOptions; + // esbuild states no mode: only NODE_ENV=development marks a dev build. + if (skipDevelopment(resolved.nodeEnv !== 'development', 'esbuild')) { + return; + } + if (resolved.enabled) { + // An output directory that is the project directory (or above it: a bare `outfile: 'bundle.js'`, + // `outdir: '.'`) would make the WHOLE project the output directory, and inject plus the map + // deletion walk all of it: refuse rather than touch unrelated files. + const project = resolve(build.initialOptions.absWorkingDir ?? process.cwd()); + const up = relative(outDir, project); + if (up === '' || (!up.startsWith('..') && !isAbsolute(up))) { + say( + `esbuild output ${outfile ?? outdir} is the project directory itself (or above it), so uploading would stamp and delete maps across the whole project. Nothing was uploaded: use \`outdir\` pointing at a dedicated output directory.`, + ); return; } - if ( - resolved.enabled && - (outdir === undefined || outdir === '') && - outfile !== undefined - ) { - // A bare `outfile` in the project directory (or above it) would make the WHOLE project the - // output directory (inject + map deletion walk it): refuse rather than touch unrelated files. - const project = resolve(build.initialOptions.absWorkingDir ?? process.cwd()); - const up = relative(outDir, project); - if (up === '' || (!up.startsWith('..') && !isAbsolute(up))) { - say( - `esbuild \`outfile\` ${outfile} is in the project directory itself (or above it), so uploading would stamp and delete maps across the whole project. Nothing was uploaded: use \`outdir\` (a dedicated output directory).`, - ); - return; - } + if ((outdir === undefined || outdir === '') && outfile !== undefined) { say( `esbuild \`outfile\` builds are uploaded per DIRECTORY: every .js and .map in ${outDir} is stamped and uploaded, not only ${outfile}. Use \`outdir\` to keep other files out of it.`, ); } - await serialUpload(outDir, () => - runPluginUpload(forOutput(outDir), outDir, { bundler: {} }), - ); } + await serialUpload(outDir, () => uploadWhenSettled(forOutput(outDir), outDir)); }); }, }, diff --git a/packages/bundler-plugin-core/src/resolve.test.ts b/packages/bundler-plugin-core/src/resolve.test.ts index 783fa9c78..a76d353da 100644 --- a/packages/bundler-plugin-core/src/resolve.test.ts +++ b/packages/bundler-plugin-core/src/resolve.test.ts @@ -66,6 +66,18 @@ describe('resolvePluginOptions app identity', () => { }); describe('resolvePluginOptions', () => { + it('a whitespace-only token (option or environment) is no token: the plugin stays off', () => { + for (const r of [ + resolvePluginOptions({}, { BUGSEE_APP_TOKEN: ' ' }), + resolvePluginOptions({ appToken: '\t' }, {}), + ]) { + expect(r.appToken).toBe(''); + expect(r.enabled).toBe(false); + } + // A real token is kept verbatim. + expect(resolvePluginOptions({}, { BUGSEE_APP_TOKEN: ' t ' }).appToken).toBe(' t '); + }); + it('uses explicit options, preferring them over env vars', () => { const r = resolvePluginOptions( { appToken: 'opt-tok', appVersion: '2.0.0', appBuild: '9', endpoint: 'https://opt.test' }, diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index 9dc750aa5..d6e6429d8 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -231,7 +231,9 @@ export function resolvePluginOptions( env: EnvRecord, deps: AppIdentityDeps = {}, ): ResolvedPluginOptions { - const appToken = options.appToken ?? env.BUGSEE_APP_TOKEN ?? ''; + // A whitespace-only token (an `export BUGSEE_APP_TOKEN=" "` left in a CI template) is no token. + const rawToken = options.appToken ?? env.BUGSEE_APP_TOKEN ?? ''; + const appToken = rawToken.trim() === '' ? '' : rawToken; // The BASELINE identity, from the working directory; never throws (see `projectRoot` on // ResolvedPluginOptions). The bundler hooks refine it from the bundler's own project directory. return { diff --git a/turbo.json b/turbo.json index 5f46cff6f..af2731ee6 100644 --- a/turbo.json +++ b/turbo.json @@ -10,11 +10,13 @@ "dependsOn": ["^build"] }, "test": { - "dependsOn": ["^build"] + "dependsOn": ["^build"], + "env": ["BUGSEE_REQUIRE_CLI"] }, "test:coverage": { "dependsOn": ["^build"], - "outputs": ["coverage/**"] + "outputs": ["coverage/**"], + "env": ["BUGSEE_REQUIRE_CLI"] }, "test:unit": { "dependsOn": ["^build"], From 83fde343e6ac398c00c91e32431ea11008fcc645 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 19:03:00 +0500 Subject: [PATCH 07/12] fix(bundler-plugin-core): do not say the write:false notice for a disabled plugin Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- .../src/plugin.esbuild-rspack.test.ts | 9 +++++++++ packages/bundler-plugin-core/src/plugin.ts | 8 +++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index 11cf9764b..09f696411 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -148,6 +148,15 @@ describe('esbuild: upload at the end of the build', () => { expect(ours[0]).toContain('onSuccess'); }); + it('write:false says nothing for a disabled or token-less plugin', async () => { + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', disabled: true, onNotice: (m) => notices.push(m) }, + { outdir: '/abs/dist', write: false }, + ).end(); + expect(notices).toEqual([]); + }); + it('an explicit sourcemap:false is left alone but explained', () => { const notices: string[] = []; const own: FakeBuild['initialOptions'] = { outdir: '/abs/dist', sourcemap: false }; diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 225b3962f..6575c4509 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -559,9 +559,11 @@ export const bugseeUnpluginFactory: UnpluginFactory` then `bugsee-cli debug-files upload --type sourcemaps`, e.g. from tsup `onSuccess`); see docs/source-maps-usage.md section 2.', - ); + if (resolved.enabled) { + say( + 'esbuild runs with `write: false` (tsup always does), so the output is not on disk when the plugin runs and nothing was uploaded. Run the bugsee-cli post-build step instead (`bugsee-cli sourcemaps inject ` then `bugsee-cli debug-files upload --type sourcemaps`, e.g. from tsup `onSuccess`); see docs/source-maps-usage.md section 2.', + ); + } return; } const { outdir, outfile } = build.initialOptions; From ad7685feade8a66457e26a753adff923ffb3b0eb Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 19:21:12 +0500 Subject: [PATCH 08/12] fix(bundler-plugin-core): keep failOnError on the esbuild upload step, no nested-build stall Round-3 review of #196: - failOnError reaches uploadSourcemaps again (it decides --allow-empty): the retry now wraps only that step instead of forcing failOnError false, so an esbuild build with no maps fails under failOnError; registration is not retried. - The first attempt never waits and a disabled plugin queues nothing, so a build nested in another no longer stalls for the idle cap; a retry waits at most 5s (upload-tuning.ts, a test seam). - Dev-skip wording, Rspack devtool notice, package-root outfile guard, segment-aware parent checks (also env-file), tsup recipe fixed, tsup declared as devDependency, deterministic race test, stronger retry tests. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/design/source-maps.md | 8 +- docs/source-maps-usage.md | 20 +- packages/bundler-plugin-core/package.json | 3 +- .../bundler-plugin-core/src/env-file.test.ts | 7 + packages/bundler-plugin-core/src/env-file.ts | 4 +- .../src/plugin.esbuild-rspack.test.ts | 301 +++++++++++++----- .../src/plugin.fixed-identity.test.ts | 6 +- .../src/plugin.real-build.test.ts | 169 ++++++++-- packages/bundler-plugin-core/src/plugin.ts | 141 +++++--- .../bundler-plugin-core/src/upload-tuning.ts | 14 + pnpm-lock.yaml | 7 +- 11 files changed, 512 insertions(+), 168 deletions(-) create mode 100644 packages/bundler-plugin-core/src/upload-tuning.ts diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index cd0c3ae5b..2aa776071 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -133,9 +133,11 @@ unset, and says so when it is `false`) and Rspack `afterEmit`, each calling (an SRI build is refused, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild plugins, so Angular uses the documented CLI post-build recipe (`docs/source-maps-usage.md §2`). Next.js on webpack uses the webpack plugin. Bun, tsup and `tsc`/`swc` stay CLI-post-build (tsup via `onSuccess`). -Concurrent esbuild builds into one directory: uploads are serialised per directory, a run waits until no build of -that directory is in flight, deletes only the maps that existed when it started, and a failure that coincides with -another build starting is retried (up to 3 attempts) rather than reported. +Concurrent esbuild builds into one directory: uploads are serialised per directory; the delete step removes only the +maps that existed when the upload started; and a failure that coincides with another build starting (or one still in +flight) is retried (up to 3 attempts, each retry waiting a bounded time for the other builds) rather than reported. +The first attempt never waits, because a build nested inside another cannot finish until its own upload has. A +disabled plugin queues nothing. Registration failures are reported as themselves and not retried. **Identifying the correct final map (multi-layer).** The identity is the bundle's own `//# sourceMappingURL` + the debug-ID: `inject` follows each bundle's sourceMappingURL to its declared map and stamps the SAME debug-ID into both, diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 7c96e8d92..754b35395 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -44,11 +44,25 @@ so an Rspack build that adds Subresource Integrity hashes is refused, not stampe **tsup is not covered by the esbuild plugin.** tsup always runs esbuild with `write: false` and writes the files itself afterwards, so nothing is on disk when the plugin's end-of-build hook runs. The plugin then uploads nothing -and says so through `onNotice`. Use the CLI after the build instead, e.g. in `tsup.config.ts`: -`onSuccess: 'bugsee-cli sourcemaps inject dist && bugsee-cli debug-files upload dist --type sourcemaps --version "$APP_VERSION" --build "$APP_BUILD"'` -(with `sourcemap: true`, and `BUGSEE_APP_TOKEN` exported). The same applies to any tool that calls esbuild with +and says so through `onNotice`. Use the CLI after the build instead, e.g. in `tsup.config.ts` (with +`sourcemap: true` and `BUGSEE_APP_TOKEN` exported): + +```ts +onSuccess: + 'bugsee-cli sourcemaps inject dist && ' + + 'bugsee-cli debug-files upload dist --type sourcemaps ${APP_VERSION:+--version "$APP_VERSION"} ${APP_BUILD:+--build "$APP_BUILD"} && ' + + 'find dist -name "*.map" -delete', +``` + +The `${VAR:+...}` parts leave the flag out when the variable is unset (an empty `--version ""` would be sent +otherwise). The last step deletes the maps after a successful upload, which is what the plugins do by default; the +shipped bundles keep their `//# sourceMappingURL` comment, which then points at a file that is not there +(harmless; drop the line if you want the maps to ship). The same applies to any tool that calls esbuild with `write: false`. +For **Rspack**, set `devtool: 'source-map'`: its production default is `devtool: false`, which emits no maps, so +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 either (also §2). Next.js on webpack uses the webpack plugin. diff --git a/packages/bundler-plugin-core/package.json b/packages/bundler-plugin-core/package.json index e57deb186..af48ef966 100644 --- a/packages/bundler-plugin-core/package.json +++ b/packages/bundler-plugin-core/package.json @@ -37,7 +37,8 @@ "@rspack/core": "2.2.9", "@types/node": "^22.20.5", "esbuild": "^0.28.2", - "rollup": "^4.65.1" + "rollup": "^4.65.1", + "tsup": "^9.0.0" }, "publishConfig": { "main": "./dist/index.cjs", diff --git a/packages/bundler-plugin-core/src/env-file.test.ts b/packages/bundler-plugin-core/src/env-file.test.ts index 46770f37c..463798914 100644 --- a/packages/bundler-plugin-core/src/env-file.test.ts +++ b/packages/bundler-plugin-core/src/env-file.test.ts @@ -158,6 +158,13 @@ describe('loadBuildPluginEnv', () => { expect(loadBuildPluginEnv(proj, { home: () => h }).values).toEqual({ BUGSEE_APP_TOKEN: 'own' }); }); + it('the home test is segment-aware: a directory ABOVE a home called "..cache" is above it', () => { + const above = mk('above'); + file(above, 'BUGSEE_APP_TOKEN=stray\n'); + const result = loadBuildPluginEnv(above, { home: () => join(above, '..cache') }); + expect(result.values).toEqual({}); + }); + it('stops at the filesystem root', () => { expect(loadBuildPluginEnv('/', { home })).toEqual({ values: {} }); }); diff --git a/packages/bundler-plugin-core/src/env-file.ts b/packages/bundler-plugin-core/src/env-file.ts index dc7f12951..5ccfb4fd5 100644 --- a/packages/bundler-plugin-core/src/env-file.ts +++ b/packages/bundler-plugin-core/src/env-file.ts @@ -15,7 +15,7 @@ // `~/.env.bugsee-build-plugin` cannot give a token to every project below it. import { existsSync, readFileSync } from 'node:fs'; import { homedir } from 'node:os'; -import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import type { EnvRecord } from './run-cli'; export const BUILD_PLUGIN_ENV_FILE = '.env.bugsee-build-plugin'; @@ -74,7 +74,7 @@ const isBoundary = (dir: string): boolean => /** True for the home directory and everything above it: never searched. */ const atOrAbove = (dir: string, home: string): boolean => { const rel = relative(dir, home); - return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); + return rel === '' || !(rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)); }; /** diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index 09f696411..96cc1e0b5 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -1,6 +1,8 @@ -import { resolve } from 'node:path'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; import type { UnpluginOptions } from 'unplugin'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { BugseePluginOptions, ResolvedPluginOptions } from './resolve'; // #184 hook wiring: esbuild `onEnd` and Rspack `afterEmit` reach `runPluginUpload` exactly as Vite/Rollup @@ -15,6 +17,20 @@ vi.mock('./resolve', async (importOriginal) => ({ runPluginUpload: uploadSpy, })); +// The upload STEP (the CLI driver) is stubbed separately so the retry around it can be driven precisely. +const { orchSpy } = vi.hoisted(() => ({ + orchSpy: vi.fn(async (_options: unknown) => ({ + injected: true, + uploaded: true, + deletedMaps: [] as string[], + })), +})); +vi.mock('./orchestrate', async (importOriginal) => ({ + ...(await importOriginal()), + uploadSourcemaps: orchSpy, +})); + +const { uploadTuning } = await import('./upload-tuning'); const { bugseeUnpluginFactory } = await import('./plugin'); const makePlugin = (options?: BugseePluginOptions, framework = 'esbuild'): UnpluginOptions => bugseeUnpluginFactory(options, { framework } as never) as UnpluginOptions; @@ -186,10 +202,18 @@ describe('esbuild: upload at the end of the build', () => { expect(uploadSpy).toHaveBeenCalledTimes(2); }); - it('a disabled or token-less plugin hands the run on, where it is a no-op', async () => { - // The enabled/disabled decision lives in runPluginUpload, as for webpack's afterEmit. + it('a disabled or token-less plugin does not even queue the upload', async () => { await esbuildRun({ appToken: 'tok', disabled: true }, { outdir: '/abs/dist' }).end(); - expect(uploadSpy.mock.calls[0]?.[0]).toMatchObject({ enabled: false }); + const saved = process.env.BUGSEE_APP_TOKEN; + delete process.env.BUGSEE_APP_TOKEN; + try { + await esbuildRun({}, { outdir: '/abs/dist' }).end(); + } finally { + if (saved !== undefined) { + process.env.BUGSEE_APP_TOKEN = saved; + } + } + expect(uploadSpy).not.toHaveBeenCalled(); }); it('makes the build EMIT external maps when the user said nothing', () => { @@ -532,67 +556,117 @@ describe('review follow-ups', () => { }); }); -describe('esbuild: builds into one directory settle before and while an upload runs', () => { +describe('esbuild: builds into one directory settle around an upload', () => { + const failure = () => new Error('exit 11: map has no debug_id'); + const failed = { injected: false, uploaded: false, deletedMaps: [] as string[] }; + const ok = { injected: true, uploaded: true, deletedMaps: [] as string[] }; + beforeEach(() => { uploadSpy.mockReset(); - uploadSpy.mockImplementation(async () => undefined); - }); - - /** A run whose captured onError is fed `error` on its first `failures` calls. */ - const failing = (failures: number, error = new Error('exit 11: map has no debug_id')) => { - let calls = 0; - uploadSpy.mockImplementation(async (resolved: unknown) => { - calls++; - if (calls <= failures) { - (resolved as ResolvedPluginOptions).onError?.(error); - } + orchSpy.mockReset(); + orchSpy.mockImplementation(async () => ok); + // `runPluginUpload` is replaced by one that drives the dependency it is handed, as the real one does. + uploadSpy.mockImplementation(async (resolved: unknown, outDir: string, deps: unknown) => { + const r = resolved as ResolvedPluginOptions; + await (deps as { uploadSourcemaps: (o: unknown) => Promise }).uploadSourcemaps({ + outDir, + appToken: 't', + appVersion: '1', + appBuild: '1', + endpoint: undefined, + deleteMaps: true, + dryRun: false, + stripSourcesContent: false, + failOnError: r.failOnError, + onError: r.onError, + }); return undefined; }); + uploadTuning.idleWaitMs = 200; + uploadTuning.pollMs = 5; + }); + afterEach(() => { + uploadTuning.idleWaitMs = 5000; + uploadTuning.pollMs = 25; + }); + + /** An upload step that fails with `error` (contained, or thrown under failOnError), as the real one does. */ + const failWith = (error: Error, before?: () => void) => async (o: unknown) => { + before?.(); + const options = o as { failOnError?: boolean; onError: (e: unknown) => void }; + if (options.failOnError === true) { + throw error; + } + options.onError(error); + return failed; }; + it('the user failOnError reaches the upload step (it also decides --allow-empty)', async () => { + const run = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/fo' }); + run.start(); + await run.end(); + expect((orchSpy.mock.calls[0]?.[0] as { failOnError?: boolean }).failOnError).toBe(true); + const lax = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/fo2' }); + lax.start(); + await lax.end(); + expect((orchSpy.mock.calls[1]?.[0] as { failOnError?: boolean }).failOnError).toBe(false); + }); + it('a failure while another build started is retried, not reported', async () => { - const a = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/race1' }); - const b = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race1' }); + const seen: unknown[] = []; + const a = esbuildRun({ appToken: 'tok', onError: (e) => seen.push(e) }, { outdir: '/abs/r1' }); + const b = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r1' }); a.start(); - const pending: Array | undefined> = []; - let calls = 0; - uploadSpy.mockImplementation(async (resolved: unknown) => { - calls++; - if (calls === 1) { - // Build B starts writing while A's inject -> upload is running, and A trips over its map. + orchSpy.mockImplementationOnce( + failWith(failure(), () => { b.start(); - (resolved as ResolvedPluginOptions).onError?.(new Error('exit 11')); - pending.push(b.end()); - } - return undefined; - }); + setTimeout(() => void b.end(), 30); + }), + ); await a.end(); - await Promise.all(pending); - expect(calls).toBeGreaterThanOrEqual(2); + expect(orchSpy).toHaveBeenCalledTimes(3); // a: fail + retry ok; b's own run + expect(seen).toEqual([]); }); - it('a failure with NO concurrent build is reported as configured: thrown with failOnError', async () => { - failing(1); - const run = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/race2' }); - run.start(); - await expect(run.end()).rejects.toThrow('exit 11'); - expect(uploadSpy).toHaveBeenCalledTimes(1); + it('a retry WAITS for the other build to finish before scanning again', async () => { + const order: string[] = []; + const a = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r2' }); + const b = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r2' }); + a.start(); + orchSpy.mockImplementationOnce( + failWith(failure(), () => { + b.start(); + setTimeout(() => { + order.push('b-ended'); + void b.end(); + }, 60); + }), + ); + orchSpy.mockImplementationOnce(async () => { + order.push('retry'); + return ok; + }); + await a.end(); + expect(order).toEqual(['b-ended', 'retry']); }); - it('... or sent to onError otherwise, and to the default warning when there is none', async () => { - failing(1); + it('a failure with NO concurrent build is reported as configured', async () => { + orchSpy.mockImplementation(failWith(failure())); + const strict = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/r3' }); + strict.start(); + await expect(strict.end()).rejects.toThrow('exit 11'); const seen: unknown[] = []; - const run = esbuildRun( + const lax = esbuildRun( { appToken: 'tok', onError: (e) => seen.push(e) }, - { outdir: '/abs/race3' }, + { outdir: '/abs/r4' }, ); - run.start(); - await run.end(); + lax.start(); + await lax.end(); expect(String(seen[0])).toContain('exit 11'); + expect(orchSpy).toHaveBeenCalledTimes(2); // no retry in either case const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); try { - failing(1); - const quiet = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race4' }); + const quiet = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r5' }); quiet.start(); await quiet.end(); expect(warn.mock.calls.join()).toContain('source-map upload skipped'); @@ -601,43 +675,58 @@ describe('esbuild: builds into one directory settle before and while an upload r } }); - it('retries are bounded: a failure that keeps coinciding with new builds is finally reported', async () => { + it('exactly three attempts for a lone run whose failures keep coinciding with new builds', async () => { const seen: unknown[] = []; - const run = esbuildRun( - { appToken: 'tok', onError: (e) => seen.push(e) }, - { outdir: '/abs/race5' }, - ); - const other = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race5' }); - run.start(); - const pending: Array | undefined> = []; - let ownCalls = 0; - uploadSpy.mockImplementation(async (resolved: unknown) => { - // Only the owning run's attempts are counted; the other build's own run succeeds. - if ((resolved as ResolvedPluginOptions).onError !== undefined && ownCalls < 3) { - ownCalls++; - other.start(); - (resolved as ResolvedPluginOptions).onError?.(new Error('exit 11')); - pending.push(other.end()); - } - return undefined; + let calls = 0; + const a = esbuildRun({ appToken: 'tok', onError: (e) => seen.push(e) }, { outdir: '/abs/r7' }); + a.start(); + const bump = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r7' }); + orchSpy.mockImplementation(async (o: unknown) => { + calls++; + bump.start(); // another build starts during every attempt... + (o as { onError: (e: unknown) => void }).onError(failure()); + return failed; }); - await run.end(); - await Promise.all(pending); - expect(ownCalls).toBe(3); + await a.end(); + expect(calls).toBe(3); expect(seen).toHaveLength(1); }); - it('a run waits for a build that is still in flight before it scans', async () => { - const a = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race6' }); - const b = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race6' }); + it('a build that started BEFORE the run and never ends (hung) still lets the failure be retried, after the cap', async () => { + const hung = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r8' }); + hung.start(); // never ends + const a = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r8' }); a.start(); - b.start(); - const first = a.end(); - await new Promise((r) => setTimeout(r, 60)); - expect(uploadSpy).not.toHaveBeenCalled(); - await b.end(); - await first; - expect(uploadSpy).toHaveBeenCalled(); + orchSpy.mockImplementationOnce(failWith(failure())); + const t0 = Date.now(); + await a.end(); + expect(orchSpy).toHaveBeenCalledTimes(2); + expect(Date.now() - t0).toBeLessThan(2000); + expect(Date.now() - t0).toBeGreaterThanOrEqual(uploadTuning.idleWaitMs - 50); + }); + + it('a build nested inside another (outer still in flight) is not stalled waiting for it', async () => { + const outer = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r9' }); + const inner = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r9' }); + outer.start(); + inner.start(); + uploadTuning.idleWaitMs = 60_000; + const t0 = Date.now(); + await inner.end(); + expect(Date.now() - t0).toBeLessThan(1000); + expect(orchSpy).toHaveBeenCalledTimes(1); + await outer.end(); + }); + + it('a disabled plugin in a nested build does not stall either', async () => { + const outer = esbuildRun({ disabled: true }, { outdir: '/abs/r10' }); + const inner = esbuildRun({ disabled: true }, { outdir: '/abs/r10' }); + outer.start(); + inner.start(); + const t0 = Date.now(); + await inner.end(); + expect(Date.now() - t0).toBeLessThan(500); + expect(orchSpy).not.toHaveBeenCalled(); }); it('three overlapping builds stay strictly one after another (the queue tail guard)', async () => { @@ -670,3 +759,61 @@ describe('esbuild: builds into one directory settle before and while an upload r await third; }); }); + +describe('guards and notices (review round 3)', () => { + beforeEach(() => { + uploadSpy.mockReset(); + uploadSpy.mockImplementation(async () => undefined); + }); + + it('an outfile directly in a PACKAGE root (monorepo root build) is refused', async () => { + const root = mkdtempSync(join(tmpdir(), 'bugsee-pkgroot-')); + try { + mkdirSync(join(root, 'packages', 'a'), { recursive: true }); + writeFileSync(join(root, 'packages', 'a', 'package.json'), '{}'); + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outfile: 'packages/a/index.js', absWorkingDir: root }, + ).end(); + expect(uploadSpy).not.toHaveBeenCalled(); + expect(notices.some((m) => m.includes('Nothing was uploaded'))).toBe(true); + // The same directory is fine as an `outdir` target (a package may hold a dist with its own package.json). + await esbuildRun({ appToken: 'tok' }, { outdir: 'packages/a', absWorkingDir: root }).end(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + // And an outfile in a package-free subdirectory still uploads. + mkdirSync(join(root, 'out'), { recursive: true }); + await esbuildRun( + { appToken: 'tok', onNotice: () => undefined }, + { outfile: 'out/bundle.js', absWorkingDir: root }, + ).end(); + expect(uploadSpy).toHaveBeenCalledTimes(2); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it('the project-directory test is segment-aware: a project named "..cache" is below its parent', async () => { + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outfile: '/proj/bundle.js', absWorkingDir: '/proj/..cache' }, + ).end(); + expect(uploadSpy).not.toHaveBeenCalled(); + expect(notices.some((m) => m.includes('Nothing was uploaded'))).toBe(true); + }); + + it('rspack: a build with devtool off says nothing is emitted (once, only when enabled)', () => { + const notices: string[] = []; + const off = rspackCompiler('/out', 'production'); + applyRspack({ appToken: 'tok', onNotice: (m) => notices.push(m) }, off.compiler); + applyRspack({ appToken: 'tok', onNotice: (m) => notices.push(m) }, off.compiler); + expect(notices.filter((m) => m.includes('devtool'))).toHaveLength(2); // one per plugin instance + const withMaps = rspackCompiler('/out', 'production'); + (withMaps.compiler.options as { devtool?: string }).devtool = 'source-map'; + const quiet: string[] = []; + applyRspack({ appToken: 'tok', onNotice: (m) => quiet.push(m) }, withMaps.compiler); + applyRspack({ appToken: 'tok', disabled: true, onNotice: (m) => quiet.push(m) }, off.compiler); + expect(quiet.filter((m) => m.includes('devtool'))).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.fixed-identity.test.ts b/packages/bundler-plugin-core/src/plugin.fixed-identity.test.ts index 548650b78..141d88f0e 100644 --- a/packages/bundler-plugin-core/src/plugin.fixed-identity.test.ts +++ b/packages/bundler-plugin-core/src/plugin.fixed-identity.test.ts @@ -198,7 +198,11 @@ describe('an identity constant the plugin cannot read is REPORTED, not silently }; const compiler = { context: web, - options: { plugins: [{ definitions: { [VERSION]: 'process.env.V' } }], output: {} }, + options: { + plugins: [{ definitions: { [VERSION]: 'process.env.V' } }], + output: {}, + devtool: 'source-map', + }, hooks: { afterEmit: { tapPromise: () => undefined } }, [bundler]: { DefinePlugin }, }; diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index 10608a644..95a855f41 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -5,7 +5,6 @@ import { spawnSync } from 'node:child_process'; import { - chmodSync, existsSync, mkdirSync, mkdtempSync, @@ -311,22 +310,37 @@ describeReal('real tsup build (tsup always runs esbuild with write:false)', () = }); describeReal("a build writing while another build's upload is between inject and upload", () => { - it('is retried, not reported as a failed upload (slow-inject CLI wrapper)', async () => { + it('is retried, not reported as a failed upload (CLI wrapper that pauses after inject)', async () => { const app = makeApp('esbuild-inject-race'); writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); - // A BUGSEE_CLI_PATH wrapper: run the real CLI, then (for `sourcemaps inject` only) dwell, so a second - // build can write AFTER inject scanned but BEFORE the upload scans. Without the retry, the upload trips - // over the second build's map (no debug_id, exit 11) and reports a failure. - const wrapper = join(app.dir, 'slow-inject.js'); + // A BUGSEE_CLI_PATH wrapper: run the real CLI, then (for the FIRST `sourcemaps inject` only) signal via + // a file and pause until the test says go. The test starts the second build only after that signal and + // releases the pause only after the second build's map is on disk, so the second build's files land + // exactly between A's inject and A's upload: no timing involved. Without the retry the upload trips over + // that map (no debug_id, exit 11) and reports a failure. + const injected = join(app.dir, 'injected.flag'); + const proceed = join(app.dir, 'proceed.flag'); + const wrapper = join(app.dir, 'pause-after-inject.js'); writeFileSync( wrapper, `const { spawnSync } = require('node:child_process'); +const fs = require('node:fs'); const r = spawnSync(process.execPath, [${JSON.stringify(cli)}, ...process.argv.slice(2)], { stdio: 'inherit' }); -if (process.argv[2] === 'sourcemaps') { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1500); } +if (process.argv[2] === 'sourcemaps' && !fs.existsSync(${JSON.stringify(injected)})) { + fs.writeFileSync(${JSON.stringify(injected)}, '1'); + for (let i = 0; i < 2000 && !fs.existsSync(${JSON.stringify(proceed)}); i++) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10); + } +} process.exit(r.status ?? 1); `, ); - chmodSync(wrapper, 0o755); + const waitFor = async (path: string): Promise => { + for (let i = 0; i < 2000 && !existsSync(path); i++) { + await new Promise((r) => setTimeout(r, 10)); + } + expect(existsSync(path)).toBe(true); + }; const errors: unknown[] = []; const plugin = bugseeEsbuildPlugin({ ...pluginOptions, @@ -337,31 +351,30 @@ process.exit(r.status ?? 1); const saved = process.env.BUGSEE_CLI_PATH; process.env.BUGSEE_CLI_PATH = wrapper; try { - await Promise.all([ - esbuild({ - entryPoints: [app.entry], - bundle: true, - outdir: app.out, - absWorkingDir: app.dir, - format: 'esm', - outExtension: { '.js': '.mjs' }, - logLevel: 'silent', - plugins: [plugin], - }), - // Starts only after A's inject has scanned, so its files land between A's inject and A's upload. - new Promise((r) => setTimeout(r, 700)).then(() => - esbuild({ - entryPoints: [join(app.dir, 'second.js')], - bundle: true, - outdir: app.out, - absWorkingDir: app.dir, - format: 'cjs', - outExtension: { '.js': '.cjs' }, - logLevel: 'silent', - plugins: [plugin], - }), - ), - ]); + const first = esbuild({ + entryPoints: [app.entry], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + format: 'esm', + outExtension: { '.js': '.mjs' }, + logLevel: 'silent', + plugins: [plugin], + }); + await waitFor(injected); + const second = esbuild({ + entryPoints: [join(app.dir, 'second.js')], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + format: 'cjs', + outExtension: { '.js': '.cjs' }, + logLevel: 'silent', + plugins: [plugin], + }); + await waitFor(join(app.out, 'second.cjs.map')); + writeFileSync(proceed, '1'); + await Promise.all([first, second]); } finally { if (saved === undefined) { delete process.env.BUGSEE_CLI_PATH; @@ -377,3 +390,93 @@ process.exit(r.status ?? 1); expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); }); }); + +describeReal('failOnError with an esbuild build that emitted no maps', () => { + const build = (name: string, options: object) => { + const app = makeApp(name); + return esbuild({ + entryPoints: [app.entry], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + sourcemap: 'inline', + logLevel: 'silent', + plugins: [bugseeEsbuildPlugin({ ...pluginOptions, endpoint, ...options })], + }); + }; + + it('fails the build under failOnError (no maps at all is the misconfiguration it exists to stop)', async () => { + const before = requests.length; + await expect(build('esbuild-inline-strict', { failOnError: true })).rejects.toThrow(); + expect(requests.length).toBe(before); + }); + + it('does not fail the build without failOnError', async () => { + const before = requests.length; + await expect(build('esbuild-inline-lax', { failOnError: false })).resolves.toBeDefined(); + expect(requests.length).toBe(before); + }); +}); + +describeReal('a build nested inside another into the same outdir (worker bundling)', () => { + const nested = async (name: string, options: object) => { + const app = makeApp(name); + writeFileSync(join(app.dir, 'worker.js'), "console.log('worker');\n"); + const plugin = bugseeEsbuildPlugin({ ...pluginOptions, endpoint, ...options }); + const inner = { + entryPoints: [join(app.dir, 'worker.js')], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + format: 'cjs' as const, + outExtension: { '.js': '.cjs' }, + logLevel: 'silent' as const, + }; + const t0 = Date.now(); + await esbuild({ + entryPoints: [app.entry], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + format: 'esm', + outExtension: { '.js': '.mjs' }, + logLevel: 'silent', + plugins: [ + plugin, + { + // The pattern: a plugin runs a sub-build from onResolve, reusing the same plugins array. + name: 'worker-subbuild', + setup: (b) => { + let done = false; + b.onStart(async () => { + if (!done) { + done = true; + await esbuild({ ...inner, plugins: [plugin] }); + } + }); + }, + }, + ], + }); + return { app, elapsed: Date.now() - t0 }; + }; + + it('does not stall a build with no token (plugin effectively disabled)', async () => { + const saved = process.env.BUGSEE_APP_TOKEN; + delete process.env.BUGSEE_APP_TOKEN; + try { + const { elapsed } = await nested('esbuild-nested-notoken', { appToken: undefined }); + expect(elapsed).toBeLessThan(10_000); + } finally { + if (saved !== undefined) { + process.env.BUGSEE_APP_TOKEN = saved; + } + } + }); + + it('does not stall an enabled plugin either, and uploads both outputs', async () => { + const { app, elapsed } = await nested('esbuild-nested-enabled', {}); + expect(elapsed).toBeLessThan(10_000); + expect(readdirSync(app.out).filter((f) => f.endsWith('.map'))).toEqual([]); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 6575c4509..daa289bf9 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -2,7 +2,8 @@ // vite/rollup `writeBundle`, webpack/rspack `afterEmit` and esbuild `onEnd`. The per-bundler entry points (@bugsee/vite-plugin, // @bugsee/webpack-plugin) are thin wrappers over `bugseeUnplugin`. The output-dir resolver is a pure, // tested helper; the framework hook registration is thin glue exercised by the real-build e2e (SM-B/SM-C). -import { dirname, isAbsolute, relative, resolve } from 'node:path'; +import { existsSync } from 'node:fs'; +import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { createUnplugin, type UnpluginFactory, type UnpluginInstance } from 'unplugin'; import { APP_BUILD_DEFINE, @@ -13,18 +14,21 @@ import { } from './app-identity'; import { bakeIdentity, type ParseChunk } from './bake-identity'; import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; -import { defaultUploadErrorHandler } from './orchestrate'; +import { + defaultUploadErrorHandler, + uploadSourcemaps as defaultUploadSourcemaps, +} from './orchestrate'; import type { BundlerBuildContext } from './register-build'; import { type BugseePluginOptions, notify, type ResolvedIdentity, - type ResolvedPluginOptions, resolveIdentity, resolvePluginOptions, runPluginUpload, } from './resolve'; import { type AssetStore, stampAssets } from './stamp-assets'; +import { uploadTuning } from './upload-tuning'; /** The subset of a rollup/vite output-options object we read. */ export interface OutputLike { @@ -61,7 +65,7 @@ interface WebpackCompilationLike { /** Minimal shape of the webpack compiler we tap (avoids a webpack type dependency in the core). */ interface WebpackCompilerLike { - options: { output?: { path?: string }; mode?: string; plugins?: unknown[] }; + options: { output?: { path?: string }; mode?: string; plugins?: unknown[]; devtool?: unknown }; /** The base directory of the build (webpack's `context`, default the cwd). */ context?: string; hooks: { @@ -232,9 +236,9 @@ function serialUpload(outDir: string, run: () => Promise): Promise { /** * What the esbuild builds writing into one directory are doing. Serialising uploads is not enough on its own: * a run is `inject` then `upload`, each scanning the whole directory, so a build that WRITES between the two - * leaves a map without a debug-id for the upload to trip over (exit 11). So a run first waits until no build - * of the directory is in flight, and a failure while another build started or ended in the meantime is - * retried (the later scan sees finished files) instead of being reported. + * leaves a map without a debug-id for the upload to trip over (exit 11). So a failure while another build started or ended in the meantime is + * retried (the later scan sees finished files) instead of being reported. The first attempt never waits (a build + * nested in another cannot finish until its own upload has). */ interface DirActivity { inflight: number; @@ -250,41 +254,65 @@ const activityOf = (outDir: string): DirActivity => { } return activity; }; -const MAX_UPLOAD_ATTEMPTS = 3; -const IDLE_WAIT_MS = 60_000; -const IDLE_POLL_MS = 25; +/** Wait (bounded) until no build of the directory is in flight: only a RETRY waits, see `uploadTuning`. */ +async function waitForIdle(activity: DirActivity): Promise { + for ( + let waited = 0; + activity.inflight > 0 && waited < uploadTuning.idleWaitMs; + waited += uploadTuning.pollMs + ) { + await new Promise((r) => setTimeout(r, uploadTuning.pollMs)); + } +} -async function uploadWhenSettled(base: ResolvedPluginOptions, outDir: string): Promise { +/** + * The upload step for one esbuild output directory, with the retry for a build that wrote while it ran. + * + * It wraps ONLY `uploadSourcemaps` (handed to `runPluginUpload` as a dependency), so everything else keeps its + * own handling: the user's `failOnError` still reaches the step (it also decides `--allow-empty`, so a build + * that emitted no maps still fails under `failOnError`), and a build-REGISTRATION failure is reported as + * itself and never retried. A failure is captured; if another build started while the step ran (or one is + * still running) it is retried after a bounded wait, otherwise it is reported as configured. + */ +function settledUpload(outDir: string): typeof defaultUploadSourcemaps { const activity = activityOf(outDir); - for (let attempt = 1; ; attempt++) { - for (let waited = 0; activity.inflight > 0 && waited < IDLE_WAIT_MS; waited += IDLE_POLL_MS) { - await new Promise((r) => setTimeout(r, IDLE_POLL_MS)); - } - const startsBefore = activity.starts; - const errors: unknown[] = []; - // The run's own failure handling is replaced by a capture, so a failure caused by a concurrent build - // can be retried; whatever remains is reported exactly as the user configured (failOnError / onError). - await runPluginUpload( - { ...base, failOnError: false, onError: (error) => errors.push(error) }, - outDir, - { bundler: {} }, - ); - const [first] = errors; - if (first === undefined) { - return; - } - if ( - (activity.starts !== startsBefore || activity.inflight > 0) && - attempt < MAX_UPLOAD_ATTEMPTS - ) { - continue; - } - if (base.failOnError) { - throw first; + return async (options) => { + for (let attempt = 1; ; attempt++) { + const startsBefore = activity.starts; + const captured: unknown[] = []; + let thrown: { error: unknown } | undefined; + let result: Awaited> | undefined; + try { + result = await defaultUploadSourcemaps({ + ...options, + onError: (error) => captured.push(error), + }); + } catch (error) { + thrown = { error }; + } + if (thrown === undefined && captured.length === 0) { + return result as Awaited>; + } + if ( + (activity.starts !== startsBefore || activity.inflight > 0) && + attempt < uploadTuning.attempts + ) { + await waitForIdle(activity); + continue; + } + if (thrown !== undefined) { + throw thrown.error; + } + (options.onError ?? defaultUploadErrorHandler)(captured[0]); + return result as Awaited>; } - (base.onError ?? defaultUploadErrorHandler)(first); - return; - } + }; +} + +/** Whether `dir` is `project` or one of its ancestors (a segment-aware test: `..cache` is not `..`). */ +function isSameOrAbove(dir: string, project: string): boolean { + const rel = relative(dir, project); + return rel === '' || !(rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)); } /** esbuild's output directory: `outdir`, else the directory of `outfile`, resolved against `absWorkingDir`. */ @@ -335,7 +363,7 @@ export const bugseeUnpluginFactory: UnpluginFactory uploadWhenSettled(forOutput(outDir), outDir)); + if (!resolved.enabled) { + return; + } + await serialUpload(outDir, () => + runPluginUpload(forOutput(outDir), outDir, { + bundler: {}, + uploadSourcemaps: settledUpload(outDir), + }), + ); }); }, }, @@ -605,6 +646,13 @@ export const bugseeUnpluginFactory: UnpluginFactory { const dir = compiler.options.output?.path; const bundler = webpackBuild(compiler.options.mode); @@ -691,7 +739,8 @@ export const bugseeUnplugin: UnpluginInstance = // Convenience per-bundler factories over the same core. `@bugsee/vite-plugin` / `@bugsee/webpack-plugin` // ship the two most common ones as their own packages; these cover plain esbuild builds (the esbuild JS API, -// tsup, any tool that accepts esbuild plugins), Rollup, and Rspack. Angular's builder does NOT accept esbuild +// any tool that accepts esbuild plugins and lets esbuild write the files; NOT tsup, which sets +// `write: false`), Rollup, and Rspack. Angular's builder does NOT accept esbuild // plugins, and Bun/tsc/swc have no usable hook: those use the standalone `bugsee-cli` post-build step // (`sourcemaps inject` then `debug-files upload`) instead. export const bugseeRollupPlugin = bugseeUnplugin.rollup; diff --git a/packages/bundler-plugin-core/src/upload-tuning.ts b/packages/bundler-plugin-core/src/upload-tuning.ts new file mode 100644 index 000000000..b243b95a1 --- /dev/null +++ b/packages/bundler-plugin-core/src/upload-tuning.ts @@ -0,0 +1,14 @@ +// Knobs of the esbuild concurrent-build retry (plugin.ts `settledUpload`). A mutable object only so a test can +// shrink the waits; production never changes it and it is not exported from the package entry. +export const uploadTuning = { + /** Attempts for one directory's upload when it keeps coinciding with another build writing. */ + attempts: 3, + /** + * How long a RETRY waits for the other builds of the directory to finish. Bounded and short on purpose: + * the first attempt never waits, because a build nested inside another (a plugin running esbuild.build() + * for a worker into the same outdir) cannot finish until its own upload has, so waiting on it would stall + * the whole build for the full cap. + */ + idleWaitMs: 5_000, + pollMs: 25, +}; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a3f448d65..09becde9b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -444,6 +444,9 @@ importers: rollup: specifier: ^4.65.1 version: 4.65.1 + tsup: + specifier: ^9.0.0 + version: 9.0.0(@microsoft/api-extractor@7.59.4(@types/node@22.20.5))(jiti@2.7.0)(postcss@8.5.32)(tsx@4.23.15)(typescript@6.0.3)(yaml@2.9.1) packages/capture: dependencies: @@ -18386,8 +18389,8 @@ snapshots: tinyglobby@0.2.17: dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 tinyps@0.5.1: {} From cf1764bc5625c25cff7f72b364f6ae5a8adcf83c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 19:29:39 +0500 Subject: [PATCH 09/12] fix(bundler-plugin-core): concurrent esbuild builds under failOnError, retry for in-flight builds Round-4 review of #196: - A run whose build began before an earlier run of the same directory swept (uploaded and deleted) maps is allowed an empty directory (allowEmpty on uploadSourcemaps), so dual-format builds no longer fail under failOnError; a lone map-less build still does. - Retry predicate also covers a build already in flight when the attempt began. - Package-root outfile refusal narrowed (named package.json, or next to src/node_modules); dist/cjs markers allowed. - Rspack devtool notice judged on the resolved default. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/source-maps-usage.md | 5 +- .../src/orchestrate.test.ts | 12 + .../bundler-plugin-core/src/orchestrate.ts | 9 +- .../src/plugin.esbuild-rspack.test.ts | 85 ++++++- .../src/plugin.real-build.test.ts | 216 +++++++++++++----- packages/bundler-plugin-core/src/plugin.ts | 54 ++++- 6 files changed, 312 insertions(+), 69 deletions(-) diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 754b35395..45005e0da 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -36,7 +36,10 @@ pairs a bundle with its sibling `.map` anyway). An explicit value, including `fa (an ESM + CJS pair) are uploaded one after another, and each upload deletes only the maps that existed when it started. Use `outdir`: with `outfile` the plugin uploads the whole directory the file is in (every `.js` and `.map` there, not just yours) and says so in a notice; an `outfile` in the project directory itself or above it (a bare -`outfile: 'bundle.js'`) is refused, with a notice, because that would make the whole project the output directory. +`outfile: 'bundle.js'`), or directly in a package root (a `package.json` with a `name`, or next to `src/` or +`node_modules/`), is refused, with a notice, because that would make the whole project the output directory (a +`dist/cjs/package.json` marker is fine). Under `failOnError`, a build that finds no maps because another build into +the same directory already uploaded (and deleted) them is not a failure; a lone build that emitted no maps still is. Development builds do not upload and leave the local maps alone unless you set `uploadInDevelopment: true`: Rspack states its mode (only `development` is skipped; `none` and `production` upload), esbuild states none, so only `NODE_ENV=development` marks a dev build (a bare `esbuild --watch` without it uploads on every rebuild, so set it or disable the plugin there). Rspack stamps after emit rather than inside the compilation, diff --git a/packages/bundler-plugin-core/src/orchestrate.test.ts b/packages/bundler-plugin-core/src/orchestrate.test.ts index 64c61c716..018ebcec4 100644 --- a/packages/bundler-plugin-core/src/orchestrate.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.test.ts @@ -58,6 +58,18 @@ describe('uploadSourcemaps', () => { // …unless the caller asked for strictness. `failOnError` is for teams who would rather the build // stopped than ship un-symbolicatable crashes, and "this build produced no maps at all" is exactly // the misconfiguration they want it to catch. + it('allowEmpty keeps --allow-empty under failOnError (maps another run already uploaded)', async () => { + const { run, calls } = fakeRun(); + await uploadSourcemaps({ + ...base, + failOnError: true, + allowEmpty: true, + run, + deleteMapFiles: async () => [], + }); + expect(calls[1]?.args).toContain('--allow-empty'); + }); + it('omits --allow-empty under failOnError, so an empty build still fails loudly', async () => { const { run, calls } = fakeRun(); await uploadSourcemaps({ ...base, failOnError: true, run, deleteMapFiles: async () => [] }); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index f300d5dac..49a526cea 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -41,6 +41,12 @@ export interface UploadSourcemapsOptions { * were never sent and must not be deleted. */ deleteMapFiles?: (dir: string, only?: readonly string[]) => Promise; + /** + * Pass `--allow-empty` even under `failOnError`. For a run whose maps were already uploaded (and deleted) by + * another run of the same directory: "no maps" is then success, not the misconfiguration `failOnError` exists + * to catch. Default: `--allow-empty` unless `failOnError`. + */ + allowEmpty?: boolean; /** Injectable `.map` lister for that snapshot (default {@link listMapFiles}). */ listMapFiles?: (dir: string) => Promise; /** Injectable SRI scan (default {@link findSriProtectedScripts}). */ @@ -244,7 +250,8 @@ export async function uploadSourcemaps( // The maps that exist NOW are the ones this upload covers. Another build into the same directory (tsup's // esm + cjs) may write more while the upload is in flight; deleting those would lose them unsent. const uploadedSet = await (options.listMapFiles ?? listMapFiles)(outDir).catch(() => undefined); - const emptyFlag = options.failOnError === true ? [] : ['--allow-empty']; + const emptyFlag = + options.failOnError === true && options.allowEmpty !== true ? [] : ['--allow-empty']; await run( [ 'debug-files', diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index 96cc1e0b5..0e140f55a 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -770,7 +770,7 @@ describe('guards and notices (review round 3)', () => { const root = mkdtempSync(join(tmpdir(), 'bugsee-pkgroot-')); try { mkdirSync(join(root, 'packages', 'a'), { recursive: true }); - writeFileSync(join(root, 'packages', 'a', 'package.json'), '{}'); + writeFileSync(join(root, 'packages', 'a', 'package.json'), '{"name":"a"}'); const notices: string[] = []; await esbuildRun( { appToken: 'tok', onNotice: (m) => notices.push(m) }, @@ -778,6 +778,32 @@ describe('guards and notices (review round 3)', () => { ).end(); expect(uploadSpy).not.toHaveBeenCalled(); expect(notices.some((m) => m.includes('Nothing was uploaded'))).toBe(true); + // A package.json WITHOUT a name and with no src/ or node_modules/ is a marker (dist/cjs), not a package. + mkdirSync(join(root, 'dist', 'cjs'), { recursive: true }); + writeFileSync(join(root, 'dist', 'cjs', 'package.json'), '{"type":"commonjs"}'); + await esbuildRun( + { appToken: 'tok', onNotice: () => undefined }, + { outfile: 'dist/cjs/index.js', absWorkingDir: root }, + ).end(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + uploadSpy.mockClear(); + // ...but one next to a src/ (a nameless package root) is refused. + mkdirSync(join(root, 'lib', 'src'), { recursive: true }); + writeFileSync(join(root, 'lib', 'package.json'), '{"private":true}'); + await esbuildRun( + { appToken: 'tok', onNotice: () => undefined }, + { outfile: 'lib/index.js', absWorkingDir: root }, + ).end(); + expect(uploadSpy).not.toHaveBeenCalled(); + // An unreadable/invalid package.json is no package root either. + mkdirSync(join(root, 'bad'), { recursive: true }); + writeFileSync(join(root, 'bad', 'package.json'), '{not json'); + await esbuildRun( + { appToken: 'tok', onNotice: () => undefined }, + { outfile: 'bad/index.js', absWorkingDir: root }, + ).end(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + uploadSpy.mockClear(); // The same directory is fine as an `outdir` target (a package may hold a dist with its own package.json). await esbuildRun({ appToken: 'tok' }, { outdir: 'packages/a', absWorkingDir: root }).end(); expect(uploadSpy).toHaveBeenCalledTimes(1); @@ -809,6 +835,11 @@ describe('guards and notices (review round 3)', () => { applyRspack({ appToken: 'tok', onNotice: (m) => notices.push(m) }, off.compiler); applyRspack({ appToken: 'tok', onNotice: (m) => notices.push(m) }, off.compiler); expect(notices.filter((m) => m.includes('devtool'))).toHaveLength(2); // one per plugin instance + // A development build with devtool unset gets only the dev-skip notice (its default is eval), not this one. + const devNotices: string[] = []; + const dev = rspackCompiler('/out', 'development'); + applyRspack({ appToken: 'tok', onNotice: (m) => devNotices.push(m) }, dev.compiler); + expect(devNotices.filter((m) => m.includes('devtool'))).toEqual([]); const withMaps = rspackCompiler('/out', 'production'); (withMaps.compiler.options as { devtool?: string }).devtool = 'source-map'; const quiet: string[] = []; @@ -817,3 +848,55 @@ describe('guards and notices (review round 3)', () => { expect(quiet.filter((m) => m.includes('devtool'))).toEqual([]); }); }); + +describe('a sweep by an earlier run lets a later run of the same directory find nothing', () => { + const ok = { injected: true, uploaded: true, deletedMaps: ['/abs/s1/a.map'] as string[] }; + beforeEach(() => { + uploadSpy.mockReset(); + orchSpy.mockReset(); + orchSpy.mockImplementation(async () => ok); + uploadSpy.mockImplementation(async (resolved: unknown, outDir: string, deps: unknown) => { + const r = resolved as ResolvedPluginOptions; + await (deps as { uploadSourcemaps: (o: unknown) => Promise }).uploadSourcemaps({ + outDir, + failOnError: r.failOnError, + onError: r.onError, + }); + return undefined; + }); + }); + const allowEmptyOf = (call: number) => + (orchSpy.mock.calls[call]?.[0] as { allowEmpty?: boolean }).allowEmpty; + + it('the second build, which began before the first run swept, is allowed an empty directory', async () => { + const a = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s1' }); + const b = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s1' }); + a.start(); + b.start(); + await a.end(); + await b.end(); + expect(allowEmptyOf(0)).toBeUndefined(); // nothing swept yet: strict + expect(allowEmptyOf(1)).toBe(true); + }); + + it('a build that began AFTER the sweep is not excused', async () => { + const a = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s2' }); + a.start(); + await a.end(); + const later = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s2' }); + later.start(); + await later.end(); + expect(allowEmptyOf(1)).toBeUndefined(); + }); + + it('a run that deleted nothing is not a sweep', async () => { + orchSpy.mockImplementation(async () => ({ injected: true, uploaded: true, deletedMaps: [] })); + const a = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s3' }); + const b = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s3' }); + a.start(); + b.start(); + await a.end(); + await b.end(); + expect(allowEmptyOf(1)).toBeUndefined(); + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index 95a855f41..de148facb 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -17,7 +17,7 @@ import { createServer, type Server } from 'node:http'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { rspack } from '@rspack/core'; -import { build as esbuild } from 'esbuild'; +import { build as esbuild, type Plugin } from 'esbuild'; import { build as tsupBuild } from 'tsup'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { bugseeEsbuildPlugin, bugseeRspackPlugin } from './plugin'; @@ -309,21 +309,22 @@ describeReal('real tsup build (tsup always runs esbuild with write:false)', () = }); }); -describeReal("a build writing while another build's upload is between inject and upload", () => { - it('is retried, not reported as a failed upload (CLI wrapper that pauses after inject)', async () => { - const app = makeApp('esbuild-inject-race'); - writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); - // A BUGSEE_CLI_PATH wrapper: run the real CLI, then (for the FIRST `sourcemaps inject` only) signal via - // a file and pause until the test says go. The test starts the second build only after that signal and - // releases the pause only after the second build's map is on disk, so the second build's files land - // exactly between A's inject and A's upload: no timing involved. Without the retry the upload trips over - // that map (no debug_id, exit 11) and reports a failure. - const injected = join(app.dir, 'injected.flag'); - const proceed = join(app.dir, 'proceed.flag'); - const wrapper = join(app.dir, 'pause-after-inject.js'); - writeFileSync( - wrapper, - `const { spawnSync } = require('node:child_process'); +/** + * A `BUGSEE_CLI_PATH` wrapper: run the real CLI, then (for the FIRST `sourcemaps inject` only) signal via a file + * and pause until the test releases it. Lets a test place another build's files exactly between a run's inject + * and its upload, with no timing involved. + */ +function pauseAfterInjectWrapper(dir: string): { + wrapper: string; + injected: string; + proceed: string; +} { + const injected = join(dir, 'injected.flag'); + const proceed = join(dir, 'proceed.flag'); + const wrapper = join(dir, 'pause-after-inject.js'); + writeFileSync( + wrapper, + `const { spawnSync } = require('node:child_process'); const fs = require('node:fs'); const r = spawnSync(process.execPath, [${JSON.stringify(cli)}, ...process.argv.slice(2)], { stdio: 'inherit' }); if (process.argv[2] === 'sourcemaps' && !fs.existsSync(${JSON.stringify(injected)})) { @@ -334,13 +335,93 @@ if (process.argv[2] === 'sourcemaps' && !fs.existsSync(${JSON.stringify(injected } process.exit(r.status ?? 1); `, - ); - const waitFor = async (path: string): Promise => { - for (let i = 0; i < 2000 && !existsSync(path); i++) { - await new Promise((r) => setTimeout(r, 10)); - } - expect(existsSync(path)).toBe(true); - }; + ); + return { wrapper, injected, proceed }; +} + +async function waitForFile(path: string): Promise { + for (let i = 0; i < 2000 && !existsSync(path); i++) { + await new Promise((r) => setTimeout(r, 10)); + } + expect(existsSync(path)).toBe(true); +} + +async function withCliPath(wrapper: string, run: () => Promise): Promise { + const saved = process.env.BUGSEE_CLI_PATH; + process.env.BUGSEE_CLI_PATH = wrapper; + try { + return await run(); + } finally { + if (saved === undefined) { + delete process.env.BUGSEE_CLI_PATH; + } else { + process.env.BUGSEE_CLI_PATH = saved; + } + } +} + +const esmBuild = (app: { dir: string; entry: string; out: string }, plugins: Plugin[]) => + esbuild({ + entryPoints: [app.entry], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + format: 'esm', + outExtension: { '.js': '.mjs' }, + logLevel: 'silent', + plugins, + }); +const cjsBuild = (app: { dir: string; out: string }, plugins: Plugin[]) => + esbuild({ + entryPoints: [join(app.dir, 'second.js')], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + format: 'cjs', + outExtension: { '.js': '.cjs' }, + logLevel: 'silent', + plugins, + }); + +function expectBothStamped(out: string): void { + for (const bundle of ['index.mjs', 'second.cjs']) { + expect(readFileSync(join(out, bundle), 'utf8')).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); + } + expect(readdirSync(out).filter((f) => f.endsWith('.map'))).toEqual([]); +} + +describeReal("a build writing while another build's upload is between inject and upload", () => { + it.each([ + false, + true, + ])('is retried, not reported as a failed upload (failOnError: %s; CLI wrapper pauses after inject)', async (failOnError) => { + const app = makeApp(`esbuild-inject-race-${failOnError}`); + writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); + const { wrapper, injected, proceed } = pauseAfterInjectWrapper(app.dir); + const errors: unknown[] = []; + const plugin = bugseeEsbuildPlugin({ + ...pluginOptions, + endpoint, + failOnError, + onError: (e) => errors.push(e), + }); + await withCliPath(wrapper, async () => { + const first = esmBuild(app, [plugin]); + await waitForFile(injected); + // Starts only after A's inject has scanned: its files land between A's inject and A's upload. + const second = cjsBuild(app, [plugin]); + await waitForFile(join(app.out, 'second.cjs.map')); + writeFileSync(proceed, '1'); + await Promise.all([first, second]); + }); + expect(errors).toEqual([]); + expectBothStamped(app.out); + }); + + it('also when the other build was ALREADY in flight when the run began (it finishes between inject and upload)', async () => { + const app = makeApp('esbuild-inject-race-inflight'); + writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); + const { wrapper, injected, proceed } = pauseAfterInjectWrapper(app.dir); const errors: unknown[] = []; const plugin = bugseeEsbuildPlugin({ ...pluginOptions, @@ -348,46 +429,69 @@ process.exit(r.status ?? 1); failOnError: false, onError: (e) => errors.push(e), }); - const saved = process.env.BUGSEE_CLI_PATH; - process.env.BUGSEE_CLI_PATH = wrapper; + let reached: () => void = () => undefined; + const gateReached = new Promise((r) => { + reached = r; + }); + let release: () => void = () => undefined; + const gate = new Promise((r) => { + release = r; + }); + const gatePlugin: Plugin = { + name: 'gate', + setup(b) { + b.onLoad({ filter: /second\.js$/ }, async () => { + reached(); + await gate; + return undefined; + }); + }, + }; + await withCliPath(wrapper, async () => { + const second = cjsBuild(app, [plugin, gatePlugin]); // in flight, held at its first file + await gateReached; + const first = esmBuild(app, [plugin]); // its run starts while the second build is in flight + await waitForFile(injected); + release(); // the second build now writes and ends, between the first run's inject and upload + await waitForFile(join(app.out, 'second.cjs.map')); + writeFileSync(proceed, '1'); + await Promise.all([first, second]); + }); + expect(errors).toEqual([]); + expectBothStamped(app.out); + }); +}); + +describeReal('two concurrent builds into one outdir under failOnError: true', () => { + it.each([ + 0, 400, + ])("both succeed, though the first run sweeps the second build's maps too (collector delay %s ms)", async (delay) => { + const app = makeApp(`esbuild-dual-strict-${delay}`); + writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); + const plugin = bugseeEsbuildPlugin({ ...pluginOptions, endpoint, failOnError: true }); + delayMs = delay; try { - const first = esbuild({ + await Promise.all([esmBuild(app, [plugin]), cjsBuild(app, [plugin])]); + } finally { + delayMs = 0; + } + expectBothStamped(app.out); + }); + + it('a lone build with no maps still fails under failOnError (the sweep rule does not weaken it)', async () => { + const app = makeApp('esbuild-dual-strict-lone'); + const plugin = bugseeEsbuildPlugin({ ...pluginOptions, endpoint, failOnError: true }); + await expect( + esbuild({ entryPoints: [app.entry], bundle: true, outdir: app.out, absWorkingDir: app.dir, - format: 'esm', - outExtension: { '.js': '.mjs' }, + sourcemap: 'inline', logLevel: 'silent', plugins: [plugin], - }); - await waitFor(injected); - const second = esbuild({ - entryPoints: [join(app.dir, 'second.js')], - bundle: true, - outdir: app.out, - absWorkingDir: app.dir, - format: 'cjs', - outExtension: { '.js': '.cjs' }, - logLevel: 'silent', - plugins: [plugin], - }); - await waitFor(join(app.out, 'second.cjs.map')); - writeFileSync(proceed, '1'); - await Promise.all([first, second]); - } finally { - if (saved === undefined) { - delete process.env.BUGSEE_CLI_PATH; - } else { - process.env.BUGSEE_CLI_PATH = saved; - } - } - expect(errors).toEqual([]); - const files = readdirSync(app.out); - for (const bundle of ['index.mjs', 'second.cjs']) { - expect(readFileSync(join(app.out, bundle), 'utf8')).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); - } - expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); + }), + ).rejects.toThrow(); }); }); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index daa289bf9..9b58e588b 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -2,7 +2,7 @@ // vite/rollup `writeBundle`, webpack/rspack `afterEmit` and esbuild `onEnd`. The per-bundler entry points (@bugsee/vite-plugin, // @bugsee/webpack-plugin) are thin wrappers over `bugseeUnplugin`. The output-dir resolver is a pure, // tested helper; the framework hook registration is thin glue exercised by the real-build e2e (SM-B/SM-C). -import { existsSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { createUnplugin, type UnpluginFactory, type UnpluginInstance } from 'unplugin'; import { @@ -244,12 +244,14 @@ interface DirActivity { inflight: number; /** Bumped at every build start: lets a run tell that the directory was touched while it ran. */ starts: number; + /** Runs that uploaded and deleted maps: a later run of a build that began earlier may find nothing left. */ + sweeps: number; } const dirActivity = new Map(); const activityOf = (outDir: string): DirActivity => { let activity = dirActivity.get(outDir); if (activity === undefined) { - activity = { inflight: 0, starts: 0 }; + activity = { inflight: 0, starts: 0, sweeps: 0 }; dirActivity.set(outDir, activity); } return activity; @@ -274,27 +276,36 @@ async function waitForIdle(activity: DirActivity): Promise { * itself and never retried. A failure is captured; if another build started while the step ran (or one is * still running) it is retried after a bounded wait, otherwise it is reported as configured. */ -function settledUpload(outDir: string): typeof defaultUploadSourcemaps { +function settledUpload(outDir: string, sweepsAtStart: number): typeof defaultUploadSourcemaps { const activity = activityOf(outDir); return async (options) => { for (let attempt = 1; ; attempt++) { const startsBefore = activity.starts; + // A build that was already running when this attempt began may write between inject and upload too. + const busyBefore = activity.inflight > 0; const captured: unknown[] = []; let thrown: { error: unknown } | undefined; let result: Awaited> | undefined; try { result = await defaultUploadSourcemaps({ ...options, + // An earlier run of this directory already swept (uploaded and deleted) maps since this build began, + // this build's among them (dual-format builds into one outdir): finding none is then success, even + // under failOnError. A lone map-less build has no such sweep and still fails. + allowEmpty: activity.sweeps > sweepsAtStart ? true : options.allowEmpty, onError: (error) => captured.push(error), }); } catch (error) { thrown = { error }; } if (thrown === undefined && captured.length === 0) { + if ((result?.deletedMaps.length ?? 0) > 0) { + activity.sweeps++; + } return result as Awaited>; } if ( - (activity.starts !== startsBefore || activity.inflight > 0) && + (busyBefore || activity.starts !== startsBefore || activity.inflight > 0) && attempt < uploadTuning.attempts ) { await waitForIdle(activity); @@ -309,6 +320,24 @@ function settledUpload(outDir: string): typeof defaultUploadSourcemaps { }; } +/** + * Whether `dir` looks like a package's root rather than an output folder: a package.json with a `name`, or a + * `src/` or `node_modules/` next to it. (A `dist/cjs/package.json` holding only `{"type":"commonjs"}` is a marker.) + */ +function isPackageRoot(dir: string): boolean { + try { + const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { + name?: unknown; + }; + if (typeof manifest.name === 'string' && manifest.name !== '') { + return true; + } + return existsSync(join(dir, 'src')) || existsSync(join(dir, 'node_modules')); + } catch { + return false; + } +} + /** Whether `dir` is `project` or one of its ancestors (a segment-aware test: `..cache` is not `..`). */ function isSameOrAbove(dir: string, project: string): boolean { const rel = relative(dir, project); @@ -570,10 +599,12 @@ export const bugseeUnpluginFactory: UnpluginFactory { if (activity !== undefined) { activity.inflight++; activity.starts++; + sweepsAtStart = activity.sweeps; } }); build.onEnd(async (result) => { @@ -607,10 +638,7 @@ export const bugseeUnpluginFactory: UnpluginFactory runPluginUpload(forOutput(outDir), outDir, { bundler: {}, - uploadSourcemaps: settledUpload(outDir), + uploadSourcemaps: settledUpload(outDir, sweepsAtStart), }), ); }); @@ -648,7 +676,13 @@ export const bugseeUnpluginFactory: UnpluginFactory Date: Wed, 11 Nov 2026 19:44:16 +0500 Subject: [PATCH 10/12] refactor(bundler-plugin-core): esbuild uploads work on the build's own files Replace the per-directory serialise/retry/sweep machinery with per-build file lists: the plugin asks esbuild for the metafile and injects, uploads and deletes exactly the build's own outputs (200 paths per CLI call). A build only touches files it wrote, so there is no cross-build coordination, no per-directory state and no nested-build wait. - failOnError for esbuild: a build with no .map among its own outputs fails (judged on that build alone). - orchestrate: files option; the directory-run delete snapshot now fails closed. - registration reads only the build's own bundles. - removed serialUpload, activity tracking, retries, upload-tuning, sweep/allowEmpty, package-root and project-dir guards; docs and tests rewritten around real esbuild/tsup/Rspack builds. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/design/source-maps.md | 16 +- docs/source-maps-usage.md | 17 +- .../bundler-plugin-core/src/debug-ids.test.ts | 28 +- packages/bundler-plugin-core/src/debug-ids.ts | 19 + .../src/orchestrate.fuzz.test.ts | 1 + .../src/orchestrate.test.ts | 149 ++- .../bundler-plugin-core/src/orchestrate.ts | 102 ++- .../src/plugin.esbuild-rspack.test.ts | 845 +++++------------- .../src/plugin.real-build.test.ts | 278 +++--- packages/bundler-plugin-core/src/plugin.ts | 216 +---- .../bundler-plugin-core/src/resolve.test.ts | 48 + packages/bundler-plugin-core/src/resolve.ts | 17 +- .../bundler-plugin-core/src/upload-tuning.ts | 14 - 13 files changed, 724 insertions(+), 1026 deletions(-) delete mode 100644 packages/bundler-plugin-core/src/upload-tuning.ts diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 2aa776071..25a1a912b 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -133,11 +133,17 @@ unset, and says so when it is `false`) and Rspack `afterEmit`, each calling (an SRI build is refused, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild plugins, so Angular uses the documented CLI post-build recipe (`docs/source-maps-usage.md §2`). Next.js on webpack uses the webpack plugin. Bun, tsup and `tsc`/`swc` stay CLI-post-build (tsup via `onSuccess`). -Concurrent esbuild builds into one directory: uploads are serialised per directory; the delete step removes only the -maps that existed when the upload started; and a failure that coincides with another build starting (or one still in -flight) is retried (up to 3 attempts, each retry waiting a bounded time for the other builds) rather than reported. -The first attempt never waits, because a build nested inside another cannot finish until its own upload has. A -disabled plugin queues nothing. Registration failures are reported as themselves and not retried. +esbuild builds work on **per-build file lists**: the plugin sets `metafile: true`, takes the build's own `.js`/`.mjs`/ +`.cjs` and `.map` outputs from `result.metafile` in `onEnd`, and runs `sourcemaps inject ` then +`debug-files upload ` (200 paths per CLI call), deleting exactly those maps after a confirmed upload. +Invariants: a build only touches files it wrote, so nothing is deleted without being uploaded, nothing is uploaded +under another build's options, nested/concurrent builds never wait for each other, and there is no per-directory +state (watch mode needs none). Under `failOnError` a build with no `.map` among its own outputs fails. Build +registration reads only the build's own bundles. (An earlier design serialised and retried uploads per directory; +four review rounds each found a new race in it, and per-build file lists remove the whole class.) Rspack/webpack +keep the directory-wide `afterEmit` path, whose delete step is limited to the maps that existed when the upload +started and fails closed if they cannot be listed; a Rspack `MultiCompiler` whose compilers share one `output.path` +keeps the webpack behaviour of joining the in-flight run for that directory. **Identifying the correct final map (multi-layer).** The identity is the bundle's own `//# sourceMappingURL` + the debug-ID: `inject` follows each bundle's sourceMappingURL to its declared map and stamps the SAME debug-ID into both, diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 45005e0da..3062c3681 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -32,14 +32,15 @@ deletes them at the end of the build, exactly as the Vite/webpack plugins do (Ro `afterEmit`), with the same SRI guard. With esbuild the plugin sets `sourcemap: 'external'` when you did not set `sourcemap` at all (external, so the shipped bundle carries no `//# sourceMappingURL` comment pointing at a map that is deleted after upload; the CLI pairs a bundle with its sibling `.map` anyway). An explicit value, including `false`, is left alone: with -`false` there are no maps to upload, and the plugin says so through `onNotice`. esbuild builds that share one output directory -(an ESM + CJS pair) are uploaded one after another, and each upload deletes only the maps that existed when it -started. Use `outdir`: with `outfile` the plugin uploads the whole directory the file is in (every `.js` and -`.map` there, not just yours) and says so in a notice; an `outfile` in the project directory itself or above it (a bare -`outfile: 'bundle.js'`), or directly in a package root (a `package.json` with a `name`, or next to `src/` or -`node_modules/`), is refused, with a notice, because that would make the whole project the output directory (a -`dist/cjs/package.json` marker is fine). Under `failOnError`, a build that finds no maps because another build into -the same directory already uploaded (and deleted) them is not a failure; a lone build that emitted no maps still is. +`false` there are no maps to upload, and the plugin says so through `onNotice`. + +**The esbuild plugin works on the files THIS build wrote.** It asks esbuild for the metafile and hands the CLI +exactly the build's own bundles and maps (in batches of 200 paths), never the directory. So a build only ever +touches files it wrote: nothing is deleted without having been uploaded, nothing is uploaded under another build's +options or another plugin instance's, builds sharing an output directory (an ESM + CJS pair, a worker sub-build, +two plugin instances) never wait for or affect each other, and watch mode keeps no state between rebuilds. Under +`failOnError`, a build whose own outputs contain no `.map` (for example `sourcemap: 'inline'`) fails, judged on that +build alone; without `failOnError` it is a notice. `outfile` and `outdir` behave alike, wherever they point. Development builds do not upload and leave the local maps alone unless you set `uploadInDevelopment: true`: Rspack states its mode (only `development` is skipped; `none` and `production` upload), esbuild states none, so only `NODE_ENV=development` marks a dev build (a bare `esbuild --watch` without it uploads on every rebuild, so set it or disable the plugin there). Rspack stamps after emit rather than inside the compilation, diff --git a/packages/bundler-plugin-core/src/debug-ids.test.ts b/packages/bundler-plugin-core/src/debug-ids.test.ts index d63d3e6b2..9a41b9113 100644 --- a/packages/bundler-plugin-core/src/debug-ids.test.ts +++ b/packages/bundler-plugin-core/src/debug-ids.test.ts @@ -2,7 +2,7 @@ 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 { collectDebugIds, readDebugId } from './debug-ids'; +import { collectDebugIds, collectDebugIdsOf, readDebugId } from './debug-ids'; // The exact tail `bugsee-cli sourcemaps inject` appends (src/inject/mod.rs, `runtime_stub`). const stub = (id: string): string => @@ -124,3 +124,29 @@ describe('collectDebugIds', () => { expect(await collectDebugIds(dir)).toEqual([ID_A]); }); }); + +describe('collectDebugIdsOf', () => { + let dir: string; + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'bugsee-ids-of-')); + }); + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + it('reads the ids of exactly the given bundles, skipping non-bundles, unstamped and missing files', async () => { + await writeFile(join(dir, 'a.js'), `x;${stub(ID_A)}`); + await writeFile(join(dir, 'b.mjs'), `x;${stub(ID_B)}`); + await writeFile(join(dir, 'foreign.cjs'), `x;${stub('11111111-1111-5111-8111-111111111111')}`); + await writeFile(join(dir, 'plain.js'), 'console.log(1)'); + await writeFile(join(dir, 'a.js.map'), `{"debug_id":"${ID_A}"}`); + const ids = await collectDebugIdsOf([ + join(dir, 'a.js'), + join(dir, 'b.mjs'), + join(dir, 'plain.js'), + join(dir, 'a.js.map'), + join(dir, 'missing.js'), + ]); + expect(ids).toEqual([ID_A, ID_B]); // not foreign.cjs: it was not in the list + }); +}); diff --git a/packages/bundler-plugin-core/src/debug-ids.ts b/packages/bundler-plugin-core/src/debug-ids.ts index 379f1cfb9..5089bb201 100644 --- a/packages/bundler-plugin-core/src/debug-ids.ts +++ b/packages/bundler-plugin-core/src/debug-ids.ts @@ -99,3 +99,22 @@ export async function collectDebugIds(dir: string, depth = 0): Promise } return ids; } + +/** The debug-ids stamped into exactly these files (a build's own outputs): same reading rules as the directory walk. */ +export async function collectDebugIdsOf(paths: readonly string[]): Promise { + const ids: string[] = []; + for (const path of paths) { + if (!STAMPED.test(path)) { + continue; + } + try { + const id = readDebugId(await readTail(path)); + if (id !== undefined) { + ids.push(id); + } + } catch { + // Unreadable: this bundle contributes nothing, and the build is not failed for it. + } + } + return ids; +} diff --git a/packages/bundler-plugin-core/src/orchestrate.fuzz.test.ts b/packages/bundler-plugin-core/src/orchestrate.fuzz.test.ts index 58bb23bd0..1f3aab6aa 100644 --- a/packages/bundler-plugin-core/src/orchestrate.fuzz.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.fuzz.test.ts @@ -149,6 +149,7 @@ describe('uploadSourcemaps — deletion happens IFF an upload was confirmed', () deleteMaps, run, deleteMapFiles, + listMapFiles: async () => ['/out/app.js.map'], onError: () => undefined, }); const uploaded = !failing && !dryRun; diff --git a/packages/bundler-plugin-core/src/orchestrate.test.ts b/packages/bundler-plugin-core/src/orchestrate.test.ts index 018ebcec4..339d92c4e 100644 --- a/packages/bundler-plugin-core/src/orchestrate.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.test.ts @@ -2,7 +2,12 @@ import { mkdir, mkdtemp, readdir, 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 { defaultDeleteMapFiles, uploadSourcemaps } from './orchestrate'; +import { + defaultDeleteMapFiles, + listMapFiles, + MAX_PATHS_PER_CALL, + uploadSourcemaps, +} from './orchestrate'; import type { RunBugseeCliOptions, SpawnResult } from './run-cli'; /** A fake `run` that records (args, options) in order and returns success. */ @@ -20,6 +25,8 @@ const base = { appToken: 'tok', appVersion: '1.0.0', appBuild: '7', + // The directory does not exist: the delete snapshot is injected (the real lister is tested below). + listMapFiles: async () => [] as string[], }; describe('uploadSourcemaps', () => { @@ -58,18 +65,6 @@ describe('uploadSourcemaps', () => { // …unless the caller asked for strictness. `failOnError` is for teams who would rather the build // stopped than ship un-symbolicatable crashes, and "this build produced no maps at all" is exactly // the misconfiguration they want it to catch. - it('allowEmpty keeps --allow-empty under failOnError (maps another run already uploaded)', async () => { - const { run, calls } = fakeRun(); - await uploadSourcemaps({ - ...base, - failOnError: true, - allowEmpty: true, - run, - deleteMapFiles: async () => [], - }); - expect(calls[1]?.args).toContain('--allow-empty'); - }); - it('omits --allow-empty under failOnError, so an empty build still fails loudly', async () => { const { run, calls } = fakeRun(); await uploadSourcemaps({ ...base, failOnError: true, run, deleteMapFiles: async () => [] }); @@ -219,9 +214,14 @@ describe('uploadSourcemaps', () => { order.push('delete'); return ['/build/dist/app.js.map']; }); - const result = await uploadSourcemaps({ ...base, run: runOrdered, deleteMapFiles }); - // The snapshot lister failed on the nonexistent dir, so the deleter falls back to "every map". - expect(deleteMapFiles).toHaveBeenCalledWith('/build/dist', undefined); + const result = await uploadSourcemaps({ + ...base, + run: runOrdered, + deleteMapFiles, + listMapFiles: async () => ['/build/dist/app.js.map'], + }); + // Only the maps that existed when the upload started (the snapshot) may be deleted. + expect(deleteMapFiles).toHaveBeenCalledWith('/build/dist', ['/build/dist/app.js.map']); expect(result.deletedMaps).toEqual(['/build/dist/app.js.map']); expect(order).toEqual(['sourcemaps', 'debug-files', 'delete']); // delete is last void run; @@ -331,7 +331,7 @@ describe('deletes only the maps that existed when the upload started', () => { } return { code: 0, stdout: '', stderr: '' }; }); - const result = await uploadSourcemaps({ ...base, outDir: dir, run }); + const result = await uploadSourcemaps({ ...base, outDir: dir, run, listMapFiles }); expect(result.deletedMaps.map((p) => p.split('/').pop())).toEqual(['first.js.map']); expect(await readdir(dir)).toEqual(['second.js.map']); }); @@ -726,3 +726,118 @@ describe('uploadSourcemaps — already stamped in the build', () => { expect(verifySri).not.toHaveBeenCalled(); }); }); + +describe('the delete snapshot fails CLOSED', () => { + const failingList = async (): Promise => { + throw new Error('EACCES: cannot list'); + }; + + it('if the maps cannot be listed, nothing is deleted and the problem is reported', async () => { + const { run } = fakeRun(); + const deleteMapFiles = vi.fn(async () => ['x']); + const onError = vi.fn(); + const result = await uploadSourcemaps({ + ...base, + run, + deleteMapFiles, + onError, + listMapFiles: failingList, + }); + expect(deleteMapFiles).not.toHaveBeenCalled(); + expect(result).toMatchObject({ uploaded: true, deletedMaps: [] }); + expect(String(onError.mock.calls[0]?.[0])).toContain('none were deleted'); + expect(String(onError.mock.calls[0]?.[0])).toContain('EACCES'); + }); + + it('under failOnError it throws instead', async () => { + const { run } = fakeRun(); + const deleteMapFiles = vi.fn(async () => ['x']); + await expect( + uploadSourcemaps({ + ...base, + failOnError: true, + run, + deleteMapFiles, + listMapFiles: failingList, + }), + ).rejects.toThrow('none were deleted'); + expect(deleteMapFiles).not.toHaveBeenCalled(); + }); + + it('is not even attempted when nothing will be deleted (deleteMaps false, or a dry run)', async () => { + const { run } = fakeRun(); + const list = vi.fn(failingList); + await uploadSourcemaps({ ...base, run, deleteMaps: false, listMapFiles: list }); + await uploadSourcemaps({ ...base, run, dryRun: true, listMapFiles: list }); + expect(list).not.toHaveBeenCalled(); + }); +}); + +describe("a run over the build's own files", () => { + const scripts = ['/b/a.js', '/b/b.mjs']; + const maps = ['/b/a.js.map', '/b/b.mjs.map']; + + it('hands the CLI exactly those paths (never the directory), and deletes exactly those maps', async () => { + const { run, calls } = fakeRun(); + const deleteMapFiles = vi.fn(async (_d: string, only?: readonly string[]) => [...(only ?? [])]); + const list = vi.fn(async () => ['/b/foreign.js.map']); + const result = await uploadSourcemaps({ + ...base, + outDir: '/b', + files: { scripts, maps }, + run, + deleteMapFiles, + listMapFiles: list, + }); + expect(calls[0]?.args).toEqual(['sourcemaps', 'inject', ...scripts, ...maps]); + expect(calls[1]?.args.slice(0, 4)).toEqual(['debug-files', 'upload', ...maps]); + expect(calls[1]?.args).not.toContain('/b'); + expect(deleteMapFiles).toHaveBeenCalledWith('/b', maps); + expect(result.deletedMaps).toEqual(maps); + expect(list).not.toHaveBeenCalled(); + }); + + it('batches paths per CLI call, and deletes only after every batch uploaded', async () => { + const many = Array.from({ length: 450 }, (_, i) => `/b/c${i}.js`); + const manyMaps = many.map((f) => `${f}.map`); + const { run, calls } = fakeRun(); + const deleteMapFiles = vi.fn(async (_d: string, only?: readonly string[]) => [...(only ?? [])]); + await uploadSourcemaps({ + ...base, + files: { scripts: many, maps: manyMaps }, + run, + deleteMapFiles, + }); + const injects = calls.filter((c) => c.args[1] === 'inject'); + const uploads = calls.filter((c) => c.args[0] === 'debug-files'); + expect(injects).toHaveLength(5); // 900 paths / 200 + expect(uploads).toHaveLength(3); // 450 maps / 200 + expect(injects.every((c) => c.args.length - 2 <= MAX_PATHS_PER_CALL)).toBe(true); + expect(uploads.flatMap((c) => c.args.filter((a) => a.endsWith('.map')))).toEqual(manyMaps); + expect(deleteMapFiles).toHaveBeenCalledTimes(1); + }); + + it('deletes nothing when a batch fails to upload', async () => { + const { calls } = fakeRun(); + let uploads = 0; + const run = vi.fn(async (args: string[]): Promise => { + calls.push({ args, options: {} }); + if (args[0] === 'debug-files' && ++uploads === 2) { + throw new Error('network down'); + } + return { code: 0, stdout: '', stderr: '' }; + }); + const manyMaps = Array.from({ length: 300 }, (_, i) => `/b/c${i}.js.map`); + const deleteMapFiles = vi.fn(async () => ['x']); + const onError = vi.fn(); + await uploadSourcemaps({ + ...base, + files: { scripts: [], maps: manyMaps }, + run, + deleteMapFiles, + onError, + }); + expect(deleteMapFiles).not.toHaveBeenCalled(); + expect(onError).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 49a526cea..513e83749 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -42,12 +42,13 @@ export interface UploadSourcemapsOptions { */ deleteMapFiles?: (dir: string, only?: readonly string[]) => Promise; /** - * Pass `--allow-empty` even under `failOnError`. For a run whose maps were already uploaded (and deleted) by - * another run of the same directory: "no maps" is then success, not the misconfiguration `failOnError` exists - * to catch. Default: `--allow-empty` unless `failOnError`. + * The build's OWN output files, when the caller knows them (esbuild's metafile). The CLI is then given exactly + * these paths instead of the directory, and exactly these maps are deleted, only after a confirmed upload. + * Nothing walks the directory, so a build can never touch (stamp, upload under its own options, or delete) a + * file another build wrote there. `scripts` are the `.js`/`.mjs`/`.cjs` outputs, `maps` the `.map` outputs. */ - allowEmpty?: boolean; - /** Injectable `.map` lister for that snapshot (default {@link listMapFiles}). */ + files?: { scripts: readonly string[]; maps: readonly string[] }; + /** Injectable `.map` lister for the delete snapshot of a directory run (default {@link listMapFiles}). */ listMapFiles?: (dir: string) => Promise; /** Injectable SRI scan (default {@link findSriProtectedScripts}). */ findSri?: (dir: string) => Promise; @@ -115,6 +116,16 @@ const NEVER_WALK = new Set([ */ const MAX_DELETE_DEPTH = 6; +/** Paths per CLI call: keeps a build with thousands of outputs under the OS command-line length limit. */ +export const MAX_PATHS_PER_CALL = 200; +function inBatches(items: readonly T[]): T[][] { + const batches: T[][] = []; + for (let i = 0; i < items.length; i += MAX_PATHS_PER_CALL) { + batches.push(items.slice(i, i + MAX_PATHS_PER_CALL)); + } + return batches; +} + /** Recursively list every build `*.map` under `dir`. */ export async function listMapFiles(dir: string, depth = 0): Promise { if (depth > MAX_DELETE_DEPTH) { @@ -162,7 +173,7 @@ export async function defaultDeleteMapFiles( } /** Where a contained upload failure goes when the user gave no `onError`. */ -export function defaultUploadErrorHandler(error: unknown): void { +function defaultUploadErrorHandler(error: unknown): void { console.warn(`[bugsee] source-map upload skipped: ${String(error)}`); } @@ -179,6 +190,7 @@ export async function uploadSourcemaps( throw new Error('uploadSourcemaps: appToken is required'); } const run = options.run ?? runBugseeCli; + const files = options.files; const deleteMaps = options.deleteMaps ?? true; const dryFlag = dryRun ? ['--dry-run'] : []; const cliOptions: RunBugseeCliOptions = { token: appToken, endpoint }; @@ -230,7 +242,13 @@ export async function uploadSourcemaps( } // 1. Inject debug-IDs (rewrites the built .js + .map in place). - await run(['sourcemaps', 'inject', outDir, ...dryFlag], cliOptions); + if (files === undefined) { + await run(['sourcemaps', 'inject', outDir, ...dryFlag], cliOptions); + } else { + for (const batch of inBatches([...files.scripts, ...files.maps])) { + await run(['sourcemaps', 'inject', ...batch, ...dryFlag], cliOptions); + } + } } // 2. Upload the maps, keyed by the injected debug-ID (+ version/build metadata). @@ -247,28 +265,41 @@ export async function uploadSourcemaps( // the CLI otherwise exits 10 on it. Under `failOnError` it is NOT passed: a team that asked for // strictness wants "this build produced no maps at all" to stop the build, which is exactly the // misconfiguration that silently costs them symbolication later. - // The maps that exist NOW are the ones this upload covers. Another build into the same directory (tsup's - // esm + cjs) may write more while the upload is in flight; deleting those would lose them unsent. - const uploadedSet = await (options.listMapFiles ?? listMapFiles)(outDir).catch(() => undefined); - const emptyFlag = - options.failOnError === true && options.allowEmpty !== true ? [] : ['--allow-empty']; - await run( - [ - 'debug-files', - 'upload', - outDir, - '--type', - 'sourcemaps', - '--version', - appVersion, - '--build', - appBuild, - ...emptyFlag, - ...(options.stripSourcesContent === true ? ['--strip-sources-content'] : []), - ...dryFlag, - ], - cliOptions, - ); + // + // A DIRECTORY run snapshots the maps that exist now: they are the ones this upload covers, and only they + // may be deleted (a map written meanwhile was never sent). If the snapshot cannot be taken, nothing is + // deleted afterwards and that is reported. A FILE run (`files`) names its maps up front. + let snapshot: string[] | undefined; + let snapshotError: unknown; + if (files === undefined && deleteMaps && !dryRun) { + try { + snapshot = await (options.listMapFiles ?? listMapFiles)(outDir); + } catch (error) { + snapshotError = error; + } + } + const emptyFlag = options.failOnError === true ? [] : ['--allow-empty']; + const uploadArgs = (targets: readonly string[]): string[] => [ + 'debug-files', + 'upload', + ...targets, + '--type', + 'sourcemaps', + '--version', + appVersion, + '--build', + appBuild, + ...emptyFlag, + ...(options.stripSourcesContent === true ? ['--strip-sources-content'] : []), + ...dryFlag, + ]; + if (files === undefined) { + await run(uploadArgs([outDir]), cliOptions); + } else { + for (const batch of inBatches(files.maps)) { + await run(uploadArgs(batch), cliOptions); + } + } // A dry run stops here: nothing was uploaded, so nothing justifies deleting the only copy of the // user's maps. @@ -278,8 +309,19 @@ export async function uploadSourcemaps( // 3. Delete the client .map files (privacy) — only after a CONFIRMED upload. Deleting after a failure // would destroy the only copy of the mapping while the symbols were never delivered. + if (snapshotError !== undefined) { + // Fail CLOSED: with no snapshot, deleting "every map found" could remove maps that were never uploaded. + const failure = new Error( + `the source maps were uploaded but could not be listed for deletion, so none were deleted: ${String(snapshotError)}`, + ); + if (options.failOnError === true) { + throw failure; + } + onError(failure); + return { injected: true, uploaded: true, deletedMaps: [], ...vcsEcho }; + } const deletedMaps = deleteMaps - ? await (options.deleteMapFiles ?? defaultDeleteMapFiles)(outDir, uploadedSet) + ? await (options.deleteMapFiles ?? defaultDeleteMapFiles)(outDir, files?.maps ?? snapshot) : []; return { injected: true, uploaded: true, deletedMaps, ...vcsEcho }; } catch (error) { diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index 0e140f55a..5b51da0ec 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -1,14 +1,12 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; +import { resolve } from 'node:path'; import type { UnpluginOptions } from 'unplugin'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { BugseePluginOptions, ResolvedPluginOptions } from './resolve'; -// #184 hook wiring: esbuild `onEnd` and Rspack `afterEmit` reach `runPluginUpload` exactly as Vite/Rollup -// `writeBundle` and webpack `afterEmit` do. The upload itself (and its SRI guard) is `runPluginUpload`'s, -// covered in orchestrate/resolve tests; `plugin.real-build.test.ts` drives the same hooks through real -// esbuild and Rspack builds. +// Hook wiring for the end-of-build upload: esbuild `onEnd` and Rspack `afterEmit` reach `runPluginUpload` as +// Vite/Rollup `writeBundle` and webpack `afterEmit` do. The upload itself (and its SRI guard) is +// `runPluginUpload`'s, covered in orchestrate/resolve tests; `plugin.real-build.test.ts` drives the same hooks +// through real esbuild, tsup and Rspack builds with the real CLI. const { uploadSpy } = vi.hoisted(() => ({ uploadSpy: vi.fn(async (_resolved: unknown, _outDir: string, _deps?: unknown) => undefined), })); @@ -17,26 +15,13 @@ vi.mock('./resolve', async (importOriginal) => ({ runPluginUpload: uploadSpy, })); -// The upload STEP (the CLI driver) is stubbed separately so the retry around it can be driven precisely. -const { orchSpy } = vi.hoisted(() => ({ - orchSpy: vi.fn(async (_options: unknown) => ({ - injected: true, - uploaded: true, - deletedMaps: [] as string[], - })), -})); -vi.mock('./orchestrate', async (importOriginal) => ({ - ...(await importOriginal()), - uploadSourcemaps: orchSpy, -})); - -const { uploadTuning } = await import('./upload-tuning'); const { bugseeUnpluginFactory } = await import('./plugin'); const makePlugin = (options?: BugseePluginOptions, framework = 'esbuild'): UnpluginOptions => bugseeUnpluginFactory(options, { framework } as never) as UnpluginOptions; interface EndResult { errors: unknown[]; + metafile?: { outputs: Record }; } type FakeBuild = { initialOptions: { @@ -45,67 +30,84 @@ type FakeBuild = { absWorkingDir?: string; write?: boolean; sourcemap?: boolean | string; + metafile?: boolean; define?: Record; }; - onStart: (cb: () => void) => void; onEnd: (cb: (result: EndResult) => Promise) => void; }; +const outputsOf = (...files: string[]): EndResult => ({ + errors: [], + metafile: { outputs: Object.fromEntries(files.map((f) => [f, {}])) }, +}); +/** The default result: one bundle and its map. */ +const okResult = outputsOf('dist/a.js', 'dist/a.js.map'); + function esbuildRun(options: BugseePluginOptions, initialOptions: FakeBuild['initialOptions']) { const ends: Array<(result: EndResult) => Promise> = []; - const starts: Array<() => void> = []; - const build: FakeBuild = { - initialOptions, - onStart: (cb) => starts.push(cb), - onEnd: (cb) => ends.push(cb), - }; + const build: FakeBuild = { initialOptions, onEnd: (cb) => ends.push(cb) }; const hooks = makePlugin(options).esbuild as unknown as { config: (o: FakeBuild['initialOptions']) => void; setup: (b: FakeBuild) => void; }; hooks.config(initialOptions); hooks.setup(build); - return { - ends, - start: () => starts[0]?.(), - end: (result: EndResult = { errors: [] }) => ends[0]?.(result), - }; + return { ends, end: (result: EndResult = okResult) => ends[0]?.(result) }; } const bundlerOf = (call: number) => (uploadSpy.mock.calls[call]?.[2] as { bundler?: unknown } | undefined)?.bundler; +const filesOf = (call: number) => + (uploadSpy.mock.calls[call]?.[2] as { files?: { scripts: string[]; maps: string[] } } | undefined) + ?.files; -describe('esbuild: upload at the end of the build', () => { +describe("esbuild: upload of the build's own files at the end of the build", () => { beforeEach(() => { uploadSpy.mockReset(); uploadSpy.mockImplementation(async () => undefined); }); - it('registers ONE onEnd and uploads the outdir once the build is on disk', async () => { - const run = esbuildRun({ appToken: 'tok', appVersion: '3.0.0' }, { outdir: '/abs/dist' }); + it('uploads exactly the files the metafile lists, resolved against absWorkingDir', async () => { + const run = esbuildRun( + { appToken: 'tok', appVersion: '3.0.0' }, + { outdir: 'dist', absWorkingDir: '/proj/app' }, + ); expect(run.ends).toHaveLength(1); expect(uploadSpy).not.toHaveBeenCalled(); - await run.end(); + await run.end( + outputsOf( + 'dist/a.js', + 'dist/a.js.map', + 'dist/b.mjs', + 'dist/b.mjs.map', + 'dist/c.cjs', + 'dist/style.css', + ), + ); expect(uploadSpy).toHaveBeenCalledTimes(1); const [resolved, outDir] = uploadSpy.mock.calls[0] as [ResolvedPluginOptions, string]; - expect(outDir).toBe('/abs/dist'); + expect(outDir).toBe(resolve('/proj/app', 'dist')); expect(resolved).toMatchObject({ enabled: true, appToken: 'tok', appVersion: '3.0.0' }); + expect(filesOf(0)).toEqual({ + scripts: ['dist/a.js', 'dist/b.mjs', 'dist/c.cjs'].map((f) => resolve('/proj/app', f)), + maps: ['dist/a.js.map', 'dist/b.mjs.map'].map((f) => resolve('/proj/app', f)), + }); // esbuild states nothing about production, so the run falls back to NODE_ENV. expect(bundlerOf(0)).toEqual({}); }); - it('resolves a relative outdir against absWorkingDir', async () => { - await esbuildRun({ appToken: 'tok' }, { outdir: 'out', absWorkingDir: '/proj/app' }).end(); - expect(uploadSpy.mock.calls[0]?.[1]).toBe(resolve('/proj/app', 'out')); + it('resolves paths against the cwd when there is no absWorkingDir', async () => { + await esbuildRun({ appToken: 'tok' }, { outdir: 'dist' }).end(); + expect(filesOf(0)?.maps).toEqual([resolve('dist/a.js.map')]); }); - it('uses the directory of a single outfile', async () => { - await esbuildRun({ appToken: 'tok' }, { outfile: '/abs/dist/app.js' }).end(); - expect(uploadSpy.mock.calls[0]?.[1]).toBe('/abs/dist'); - }); - - it('resolves a relative outdir against the cwd when there is no absWorkingDir', async () => { - await esbuildRun({ appToken: 'tok' }, { outdir: 'rel-out' }).end(); - expect(uploadSpy.mock.calls[0]?.[1]).toBe(resolve('rel-out')); + it('works for an outfile in ANY directory, including the project directory: nothing walks it', async () => { + await esbuildRun({ appToken: 'tok' }, { outfile: 'bundle.js', absWorkingDir: '/proj/app' }).end( + outputsOf('bundle.js', 'bundle.js.map'), + ); + expect(filesOf(0)).toEqual({ + scripts: [resolve('/proj/app', 'bundle.js')], + maps: [resolve('/proj/app', 'bundle.js.map')], + }); }); it('does nothing for a relative outdir when the working directory is gone', async () => { @@ -120,40 +122,84 @@ describe('esbuild: upload at the end of the build', () => { expect(uploadSpy).not.toHaveBeenCalled(); }); - it('an `outfile` build says, once, that the whole directory is uploaded', async () => { - const notices: string[] = []; - const run = esbuildRun( - { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outfile: '/abs/public/app.js' }, - ); - await run.end(); - await run.end(); - expect(notices).toHaveLength(1); - expect(notices[0]).toContain('/abs/public'); - expect(notices[0]).toContain('outdir'); - // outdir builds, and disabled plugins, say nothing. - const quiet: string[] = []; - await esbuildRun( - { appToken: 'tok', onNotice: (m) => quiet.push(m) }, - { outdir: '/abs/dist' }, - ).end(); - await esbuildRun( - { appToken: 'tok', disabled: true, onNotice: (m) => quiet.push(m) }, - { outfile: '/abs/public/app.js' }, - ).end(); - expect(quiet).toEqual([]); - }); - it('does nothing for a build with no outdir/outfile', async () => { await esbuildRun({ appToken: 'tok' }, {}).end(); expect(uploadSpy).not.toHaveBeenCalled(); }); + it('does not upload a FAILED build', async () => { + await esbuildRun({ appToken: 'tok' }, { outdir: 'dist' }).end({ ...okResult, errors: [{}] }); + expect(uploadSpy).not.toHaveBeenCalled(); + }); + + it('uploads again on every rebuild, each with its own outputs (watch mode: no state)', async () => { + const run = esbuildRun({ appToken: 'tok' }, { outdir: 'dist', absWorkingDir: '/p' }); + await run.end(outputsOf('dist/a.js', 'dist/a.js.map')); + await run.end(outputsOf('dist/b.js', 'dist/b.js.map')); + expect(uploadSpy).toHaveBeenCalledTimes(2); + expect(filesOf(0)?.maps).toEqual([resolve('/p', 'dist/a.js.map')]); + expect(filesOf(1)?.maps).toEqual([resolve('/p', 'dist/b.js.map')]); + }); + + it('a disabled or token-less plugin does not upload', async () => { + await esbuildRun({ appToken: 'tok', disabled: true }, { outdir: 'dist' }).end(); + const saved = process.env.BUGSEE_APP_TOKEN; + delete process.env.BUGSEE_APP_TOKEN; + try { + await esbuildRun({}, { outdir: 'dist' }).end(); + } finally { + if (saved !== undefined) { + process.env.BUGSEE_APP_TOKEN = saved; + } + } + expect(uploadSpy).not.toHaveBeenCalled(); + }); + + it('asks esbuild for the metafile (and leaves a user metafile on), only when enabled', () => { + const own: FakeBuild['initialOptions'] = { outdir: 'dist' }; + esbuildRun({ appToken: 'tok' }, own); + expect(own.metafile).toBe(true); + const off: FakeBuild['initialOptions'] = { outdir: 'dist' }; + esbuildRun({ appToken: 'tok', disabled: true }, off); + expect(off.metafile).toBeUndefined(); + }); + + describe('a build with no map among its own outputs', () => { + const inline = outputsOf('dist/a.js'); + + it('fails the build under failOnError, naming the directory (judged on THIS build only)', async () => { + const run = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: 'dist' }); + await expect(run.end(inline)).rejects.toThrow(/emitted no \.map files/); + expect(uploadSpy).not.toHaveBeenCalled(); + }); + + it('is a notice (once) without failOnError, and uploads nothing', async () => { + const notices: string[] = []; + const run = esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outdir: 'dist' }, + ); + await run.end(inline); + await run.end(inline); + expect(uploadSpy).not.toHaveBeenCalled(); + expect(notices.filter((m) => m.includes('emitted no .map files'))).toHaveLength(1); + }); + + it('also when the result carries no metafile at all', async () => { + await esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: 'dist' }) + .end({ errors: [] }) + ?.then( + () => expect.unreachable('should have thrown'), + (e: Error) => expect(e.message).toContain('no .map files'), + ); + }); + }); + it('write:false (tsup always sets it): nothing is uploaded, and a notice says why, once', async () => { const notices: string[] = []; const run = esbuildRun( { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outdir: '/abs/dist', write: false }, + { outdir: 'dist', write: false }, ); await run.end(); await run.end(); @@ -168,157 +214,134 @@ describe('esbuild: upload at the end of the build', () => { const notices: string[] = []; await esbuildRun( { appToken: 'tok', disabled: true, onNotice: (m) => notices.push(m) }, - { outdir: '/abs/dist', write: false }, + { outdir: 'dist', write: false }, ).end(); expect(notices).toEqual([]); }); it('an explicit sourcemap:false is left alone but explained', () => { const notices: string[] = []; - const own: FakeBuild['initialOptions'] = { outdir: '/abs/dist', sourcemap: false }; + const own: FakeBuild['initialOptions'] = { outdir: 'dist', sourcemap: false }; esbuildRun({ appToken: 'tok', onNotice: (m) => notices.push(m) }, own); expect(own.sourcemap).toBe(false); expect(notices.some((m) => m.includes('sourcemap: false'))).toBe(true); const quiet: string[] = []; esbuildRun( { appToken: 'tok', disabled: true, onNotice: (m) => quiet.push(m) }, - { - outdir: '/abs/dist', - sourcemap: false, - }, + { outdir: 'dist', sourcemap: false }, ); expect(quiet).toEqual([]); }); - it('does not upload a FAILED build', async () => { - await esbuildRun({ appToken: 'tok' }, { outdir: '/abs/dist' }).end({ errors: [{}] }); - expect(uploadSpy).not.toHaveBeenCalled(); - }); - - it('uploads again on every rebuild (watch mode)', async () => { - const run = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/dist' }); - await run.end(); - await run.end(); - expect(uploadSpy).toHaveBeenCalledTimes(2); - }); - - it('a disabled or token-less plugin does not even queue the upload', async () => { - await esbuildRun({ appToken: 'tok', disabled: true }, { outdir: '/abs/dist' }).end(); - const saved = process.env.BUGSEE_APP_TOKEN; - delete process.env.BUGSEE_APP_TOKEN; - try { - await esbuildRun({}, { outdir: '/abs/dist' }).end(); - } finally { - if (saved !== undefined) { - process.env.BUGSEE_APP_TOKEN = saved; - } - } - expect(uploadSpy).not.toHaveBeenCalled(); - }); - it('makes the build EMIT external maps when the user said nothing', () => { // `external`, not `true`: the map is deleted after upload, so a sourceMappingURL comment would dangle. - const own: FakeBuild['initialOptions'] = { outdir: '/abs/dist' }; + const own: FakeBuild['initialOptions'] = { outdir: 'dist' }; esbuildRun({ appToken: 'tok' }, own); expect(own.sourcemap).toBe('external'); }); it("leaves any explicit sourcemap choice (false, 'external', 'inline', ...) and a disabled plugin alone", () => { for (const choice of [false, true, 'external', 'linked', 'inline', 'both']) { - const own: FakeBuild['initialOptions'] = { outdir: '/abs/dist', sourcemap: choice }; + const own: FakeBuild['initialOptions'] = { outdir: 'dist', sourcemap: choice }; esbuildRun({ appToken: 'tok' }, own); expect(own.sourcemap).toBe(choice); } - const disabled: FakeBuild['initialOptions'] = { outdir: '/abs/dist' }; + const disabled: FakeBuild['initialOptions'] = { outdir: 'dist' }; esbuildRun({ appToken: 'tok', disabled: true }, disabled); expect(disabled.sourcemap).toBeUndefined(); }); - describe('builds sharing one outdir run their uploads one after another', () => { - it('the second build waits for the first upload and then runs its own', async () => { - const gates: Array<() => void> = []; - const order: string[] = []; - uploadSpy.mockImplementation(async () => { - const n = gates.length; - order.push(`start${n}`); - await new Promise((r) => gates.push(r)); - order.push(`end${n}`); - return undefined; - }); - const plugin = makePlugin({ appToken: 'tok' }).esbuild as unknown as { - config: (o: FakeBuild['initialOptions']) => void; - setup: (b: FakeBuild) => void; - }; - const ends: Array<() => Promise | undefined> = []; - for (let i = 0; i < 2; i++) { - const initialOptions = { outdir: '/abs/shared' }; - plugin.config(initialOptions); - plugin.setup({ - initialOptions, - onStart: () => undefined, - onEnd: (cb) => ends.push(() => cb({ errors: [] })), - }); + describe('development builds (NODE_ENV=development) do not upload', () => { + const withNodeEnv = async (value: string, run: () => Promise) => { + const saved = process.env.NODE_ENV; + process.env.NODE_ENV = value; + try { + await run(); + } finally { + process.env.NODE_ENV = saved; } - const first = ends[0]?.(); - const second = ends[1]?.(); - await new Promise((r) => setTimeout(r, 10)); - // Only the first has started: the second must not join it and must not run yet. - expect(order).toEqual(['start0']); - gates[0]?.(); - await first; - await new Promise((r) => setTimeout(r, 10)); - expect(order).toEqual(['start0', 'end0', 'start1']); - gates[1]?.(); - await second; - expect(uploadSpy).toHaveBeenCalledTimes(2); + }; + + it('is skipped with one notice; uploadInDevelopment opts back in; production uploads', async () => { + await withNodeEnv('development', async () => { + const notices: string[] = []; + const run = esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outdir: 'dist' }, + ); + await run.end(); + await run.end(); + expect(uploadSpy).not.toHaveBeenCalled(); + const ours = notices.filter((m) => m.includes('esbuild development build')); + expect(ours).toHaveLength(1); + expect(ours[0]).toContain('nothing was uploaded'); + await esbuildRun({ appToken: 'tok', uploadInDevelopment: true }, { outdir: 'dist' }).end(); + expect(uploadSpy).toHaveBeenCalledTimes(1); + }); + await withNodeEnv('production', async () => { + await esbuildRun({ appToken: 'tok' }, { outdir: 'dist' }).end(); + expect(uploadSpy).toHaveBeenCalledTimes(2); + }); }); - it('a failed upload does not block the next build, and rejects only its own', async () => { - uploadSpy.mockImplementationOnce(async () => { - throw new Error('boom'); + it('does not force maps on for a development build (unless it uploads in dev)', async () => { + await withNodeEnv('development', async () => { + const dev: FakeBuild['initialOptions'] = { outdir: 'dist' }; + esbuildRun({ appToken: 'tok' }, dev); + expect(dev.sourcemap).toBeUndefined(); + const optIn: FakeBuild['initialOptions'] = { outdir: 'dist' }; + esbuildRun({ appToken: 'tok', uploadInDevelopment: true }, optIn); + expect(optIn.sourcemap).toBe('external'); }); - uploadSpy.mockImplementationOnce(async () => undefined); - const plugin = makePlugin({ appToken: 'tok' }).esbuild as unknown as { - setup: (b: FakeBuild) => void; - }; - const ends: Array<() => Promise | undefined> = []; - for (let i = 0; i < 2; i++) { - plugin.setup({ - initialOptions: { outdir: '/abs/failing' }, - onStart: () => undefined, - onEnd: (cb) => ends.push(() => cb({ errors: [] })), - }); - } - const first = ends[0]?.(); - const second = ends[1]?.(); - await expect(first).rejects.toThrow('boom'); - await expect(second).resolves.toBeUndefined(); - expect(uploadSpy).toHaveBeenCalledTimes(2); }); - it('different output directories do not wait for each other', async () => { - let release: () => void = () => undefined; - uploadSpy.mockImplementationOnce( - () => new Promise((r) => (release = () => r(undefined))), - ); - const plugin = makePlugin({ appToken: 'tok' }).esbuild as unknown as { - setup: (b: FakeBuild) => void; - }; - const ends: Array<() => Promise | undefined> = []; - for (const outdir of ['/abs/a', '/abs/b']) { - plugin.setup({ - initialOptions: { outdir }, - onStart: () => undefined, - onEnd: (cb) => ends.push(() => cb({ errors: [] })), - }); - } - const slow = ends[0]?.(); - await ends[1]?.(); - expect(uploadSpy).toHaveBeenCalledTimes(2); - release(); - await slow; + it('says nothing for a disabled plugin', async () => { + await withNodeEnv('development', async () => { + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', disabled: true, onNotice: (m) => notices.push(m) }, + { outdir: 'dist' }, + ).end(); + expect(notices).toEqual([]); + }); }); }); + + it('builds sharing one outdir never wait for or join each other (no per-directory state)', async () => { + // Two builds end while the first upload is still running: the second starts at once, with its own files. + let release: () => void = () => undefined; + uploadSpy.mockImplementationOnce( + () => new Promise((r) => (release = () => r(undefined))), + ); + const a = esbuildRun({ appToken: 'tok' }, { outdir: 'dist', absWorkingDir: '/p' }); + const b = esbuildRun({ appToken: 'tok' }, { outdir: 'dist', absWorkingDir: '/p' }); + const first = a.end(outputsOf('dist/a.mjs', 'dist/a.mjs.map')); + await b.end(outputsOf('dist/b.cjs', 'dist/b.cjs.map')); + expect(uploadSpy).toHaveBeenCalledTimes(2); + expect(filesOf(0)?.maps).toEqual([resolve('/p', 'dist/a.mjs.map')]); + expect(filesOf(1)?.maps).toEqual([resolve('/p', 'dist/b.cjs.map')]); + release(); + await first; + }); + + it('two plugin instances over one outdir each upload only their own build, with their own options', async () => { + const a = esbuildRun( + { appToken: 'tok-a', deleteMaps: true }, + { outdir: 'dist', absWorkingDir: '/p' }, + ); + const b = esbuildRun( + { appToken: 'tok-b', deleteMaps: false }, + { outdir: 'dist', absWorkingDir: '/p' }, + ); + await a.end(outputsOf('dist/a.js', 'dist/a.js.map')); + await b.end(outputsOf('dist/b.js', 'dist/b.js.map')); + const [ra] = uploadSpy.mock.calls[0] as unknown as [ResolvedPluginOptions]; + const [rb] = uploadSpy.mock.calls[1] as unknown as [ResolvedPluginOptions]; + expect(ra).toMatchObject({ appToken: 'tok-a', deleteMaps: true }); + expect(rb).toMatchObject({ appToken: 'tok-b', deleteMaps: false }); + expect(filesOf(0)?.maps).toEqual([resolve('/p', 'dist/a.js.map')]); + expect(filesOf(1)?.maps).toEqual([resolve('/p', 'dist/b.js.map')]); + }); }); /** The slice of a Rspack compiler the plugin taps. */ @@ -384,7 +407,7 @@ describe('rspack: upload after emit', () => { }); }); -describe('development builds do not upload (and do not delete the local maps) by default', () => { +describe('rspack development builds do not upload (and do not delete the local maps) by default', () => { beforeEach(() => { uploadSpy.mockReset(); uploadSpy.mockImplementation(async () => undefined); @@ -415,34 +438,6 @@ describe('development builds do not upload (and do not delete the local maps) by expect(uploadSpy).toHaveBeenCalledTimes(1); }); - it('esbuild: NODE_ENV=development is skipped; any other value uploads', async () => { - const saved = process.env.NODE_ENV; - try { - process.env.NODE_ENV = 'development'; - const notices: string[] = []; - await esbuildRun( - { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outdir: '/abs/dist' }, - ).end(); - expect(uploadSpy).not.toHaveBeenCalled(); - expect(notices[0]).toContain('esbuild development build'); - await esbuildRun( - { appToken: 'tok', uploadInDevelopment: true }, - { outdir: '/abs/dist' }, - ).end(); - expect(uploadSpy).toHaveBeenCalledTimes(1); - process.env.NODE_ENV = 'production'; - await esbuildRun({ appToken: 'tok' }, { outdir: '/abs/dist' }).end(); - expect(uploadSpy).toHaveBeenCalledTimes(2); - } finally { - if (saved === undefined) { - delete process.env.NODE_ENV; - } else { - process.env.NODE_ENV = saved; - } - } - }); - it('a disabled plugin says nothing about development builds', async () => { const notices: string[] = []; const c = rspackCompiler('/out', 'development'); @@ -452,47 +447,7 @@ describe('development builds do not upload (and do not delete the local maps) by }); }); -describe('esbuild: a bare outfile in the project directory is refused', () => { - beforeEach(() => { - uploadSpy.mockReset(); - uploadSpy.mockImplementation(async () => undefined); - }); - - it('uploads nothing and says why (outfile: "bundle.js" would make the whole project the output dir)', async () => { - const notices: string[] = []; - await esbuildRun( - { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outfile: 'bundle.js', absWorkingDir: '/proj/app' }, - ).end(); - expect(uploadSpy).not.toHaveBeenCalled(); - expect(notices.some((m) => m.includes('project directory itself'))).toBe(true); - }); - - it('also against the cwd when there is no absWorkingDir', async () => { - await esbuildRun( - { appToken: 'tok', onNotice: () => undefined }, - { outfile: 'bundle.js' }, - ).end(); - expect(uploadSpy).not.toHaveBeenCalled(); - }); - - it('an outfile in a SUBdirectory still uploads; outdir "." (the whole project) is refused too', async () => { - await esbuildRun( - { appToken: 'tok', onNotice: () => undefined }, - { outfile: 'dist/bundle.js', absWorkingDir: '/proj/app' }, - ).end(); - expect(uploadSpy).toHaveBeenCalledTimes(1); - const notices: string[] = []; - await esbuildRun( - { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outdir: '.', absWorkingDir: '/proj/app' }, - ).end(); - expect(uploadSpy).toHaveBeenCalledTimes(1); - expect(notices.some((m) => m.includes('Nothing was uploaded'))).toBe(true); - }); -}); - -describe('review follow-ups', () => { +describe('rspack: a build with devtool off', () => { beforeEach(() => { uploadSpy.mockReset(); uploadSpy.mockImplementation(async () => undefined); @@ -505,330 +460,6 @@ describe('review follow-ups', () => { expect(uploadSpy).toHaveBeenCalledTimes(1); }); - it('esbuild: a development build does not force maps on (unless it uploads in dev)', async () => { - const saved = process.env.NODE_ENV; - process.env.NODE_ENV = 'development'; - try { - const dev: FakeBuild['initialOptions'] = { outdir: '/abs/dist' }; - esbuildRun({ appToken: 'tok' }, dev); - expect(dev.sourcemap).toBeUndefined(); - const optIn: FakeBuild['initialOptions'] = { outdir: '/abs/dist' }; - esbuildRun({ appToken: 'tok', uploadInDevelopment: true }, optIn); - expect(optIn.sourcemap).toBe('external'); - } finally { - process.env.NODE_ENV = saved; - } - }); - - it('esbuild: an outfile ABOVE the project is refused too, and gets one notice, not two', async () => { - const notices: string[] = []; - await esbuildRun( - { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outfile: '/proj/bundle.js', absWorkingDir: '/proj/app' }, - ).end(); - expect(uploadSpy).not.toHaveBeenCalled(); - const ours = notices.filter((m) => m.includes('project directory itself')); - expect(ours).toHaveLength(1); - expect(ours[0]).toContain('Nothing was uploaded'); - }); - - it('esbuild: a development outfile build gets only the development notice', async () => { - const saved = process.env.NODE_ENV; - process.env.NODE_ENV = 'development'; - try { - const notices: string[] = []; - await esbuildRun( - { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outfile: '/abs/public/app.js' }, - ).end(); - expect(notices.filter((m) => m.includes('outfile'))).toEqual([]); - } finally { - process.env.NODE_ENV = saved; - } - }); - - it('esbuild: a sibling outfile directory (not an ancestor of the project) still uploads', async () => { - await esbuildRun( - { appToken: 'tok', onNotice: () => undefined }, - { outfile: '/proj/app2/out.js', absWorkingDir: '/proj/app' }, - ).end(); - expect(uploadSpy).toHaveBeenCalledTimes(1); - }); -}); - -describe('esbuild: builds into one directory settle around an upload', () => { - const failure = () => new Error('exit 11: map has no debug_id'); - const failed = { injected: false, uploaded: false, deletedMaps: [] as string[] }; - const ok = { injected: true, uploaded: true, deletedMaps: [] as string[] }; - - beforeEach(() => { - uploadSpy.mockReset(); - orchSpy.mockReset(); - orchSpy.mockImplementation(async () => ok); - // `runPluginUpload` is replaced by one that drives the dependency it is handed, as the real one does. - uploadSpy.mockImplementation(async (resolved: unknown, outDir: string, deps: unknown) => { - const r = resolved as ResolvedPluginOptions; - await (deps as { uploadSourcemaps: (o: unknown) => Promise }).uploadSourcemaps({ - outDir, - appToken: 't', - appVersion: '1', - appBuild: '1', - endpoint: undefined, - deleteMaps: true, - dryRun: false, - stripSourcesContent: false, - failOnError: r.failOnError, - onError: r.onError, - }); - return undefined; - }); - uploadTuning.idleWaitMs = 200; - uploadTuning.pollMs = 5; - }); - afterEach(() => { - uploadTuning.idleWaitMs = 5000; - uploadTuning.pollMs = 25; - }); - - /** An upload step that fails with `error` (contained, or thrown under failOnError), as the real one does. */ - const failWith = (error: Error, before?: () => void) => async (o: unknown) => { - before?.(); - const options = o as { failOnError?: boolean; onError: (e: unknown) => void }; - if (options.failOnError === true) { - throw error; - } - options.onError(error); - return failed; - }; - - it('the user failOnError reaches the upload step (it also decides --allow-empty)', async () => { - const run = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/fo' }); - run.start(); - await run.end(); - expect((orchSpy.mock.calls[0]?.[0] as { failOnError?: boolean }).failOnError).toBe(true); - const lax = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/fo2' }); - lax.start(); - await lax.end(); - expect((orchSpy.mock.calls[1]?.[0] as { failOnError?: boolean }).failOnError).toBe(false); - }); - - it('a failure while another build started is retried, not reported', async () => { - const seen: unknown[] = []; - const a = esbuildRun({ appToken: 'tok', onError: (e) => seen.push(e) }, { outdir: '/abs/r1' }); - const b = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r1' }); - a.start(); - orchSpy.mockImplementationOnce( - failWith(failure(), () => { - b.start(); - setTimeout(() => void b.end(), 30); - }), - ); - await a.end(); - expect(orchSpy).toHaveBeenCalledTimes(3); // a: fail + retry ok; b's own run - expect(seen).toEqual([]); - }); - - it('a retry WAITS for the other build to finish before scanning again', async () => { - const order: string[] = []; - const a = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r2' }); - const b = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r2' }); - a.start(); - orchSpy.mockImplementationOnce( - failWith(failure(), () => { - b.start(); - setTimeout(() => { - order.push('b-ended'); - void b.end(); - }, 60); - }), - ); - orchSpy.mockImplementationOnce(async () => { - order.push('retry'); - return ok; - }); - await a.end(); - expect(order).toEqual(['b-ended', 'retry']); - }); - - it('a failure with NO concurrent build is reported as configured', async () => { - orchSpy.mockImplementation(failWith(failure())); - const strict = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/r3' }); - strict.start(); - await expect(strict.end()).rejects.toThrow('exit 11'); - const seen: unknown[] = []; - const lax = esbuildRun( - { appToken: 'tok', onError: (e) => seen.push(e) }, - { outdir: '/abs/r4' }, - ); - lax.start(); - await lax.end(); - expect(String(seen[0])).toContain('exit 11'); - expect(orchSpy).toHaveBeenCalledTimes(2); // no retry in either case - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); - try { - const quiet = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r5' }); - quiet.start(); - await quiet.end(); - expect(warn.mock.calls.join()).toContain('source-map upload skipped'); - } finally { - warn.mockRestore(); - } - }); - - it('exactly three attempts for a lone run whose failures keep coinciding with new builds', async () => { - const seen: unknown[] = []; - let calls = 0; - const a = esbuildRun({ appToken: 'tok', onError: (e) => seen.push(e) }, { outdir: '/abs/r7' }); - a.start(); - const bump = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r7' }); - orchSpy.mockImplementation(async (o: unknown) => { - calls++; - bump.start(); // another build starts during every attempt... - (o as { onError: (e: unknown) => void }).onError(failure()); - return failed; - }); - await a.end(); - expect(calls).toBe(3); - expect(seen).toHaveLength(1); - }); - - it('a build that started BEFORE the run and never ends (hung) still lets the failure be retried, after the cap', async () => { - const hung = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r8' }); - hung.start(); // never ends - const a = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r8' }); - a.start(); - orchSpy.mockImplementationOnce(failWith(failure())); - const t0 = Date.now(); - await a.end(); - expect(orchSpy).toHaveBeenCalledTimes(2); - expect(Date.now() - t0).toBeLessThan(2000); - expect(Date.now() - t0).toBeGreaterThanOrEqual(uploadTuning.idleWaitMs - 50); - }); - - it('a build nested inside another (outer still in flight) is not stalled waiting for it', async () => { - const outer = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r9' }); - const inner = esbuildRun({ appToken: 'tok' }, { outdir: '/abs/r9' }); - outer.start(); - inner.start(); - uploadTuning.idleWaitMs = 60_000; - const t0 = Date.now(); - await inner.end(); - expect(Date.now() - t0).toBeLessThan(1000); - expect(orchSpy).toHaveBeenCalledTimes(1); - await outer.end(); - }); - - it('a disabled plugin in a nested build does not stall either', async () => { - const outer = esbuildRun({ disabled: true }, { outdir: '/abs/r10' }); - const inner = esbuildRun({ disabled: true }, { outdir: '/abs/r10' }); - outer.start(); - inner.start(); - const t0 = Date.now(); - await inner.end(); - expect(Date.now() - t0).toBeLessThan(500); - expect(orchSpy).not.toHaveBeenCalled(); - }); - - it('three overlapping builds stay strictly one after another (the queue tail guard)', async () => { - const gates: Array<() => void> = []; - const order: string[] = []; - uploadSpy.mockImplementation(async () => { - const n = gates.length; - order.push(`start${n}`); - await new Promise((r) => gates.push(r)); - order.push(`end${n}`); - return undefined; - }); - const runs = [1, 2, 3].map(() => esbuildRun({ appToken: 'tok' }, { outdir: '/abs/race7' })); - const done = [runs[0]?.end(), runs[1]?.end()]; - await new Promise((r) => setTimeout(r, 20)); - expect(order).toEqual(['start0']); - gates[0]?.(); - await done[0]; - await new Promise((r) => setTimeout(r, 20)); - // Build 1's queue slot has settled but build 2 is still running: build 3 must queue behind build 2. - expect(order).toEqual(['start0', 'end0', 'start1']); - const third = runs[2]?.end(); - await new Promise((r) => setTimeout(r, 20)); - expect(order).toEqual(['start0', 'end0', 'start1']); - gates[1]?.(); - await done[1]; - await new Promise((r) => setTimeout(r, 20)); - expect(order).toEqual(['start0', 'end0', 'start1', 'end1', 'start2']); - gates[2]?.(); - await third; - }); -}); - -describe('guards and notices (review round 3)', () => { - beforeEach(() => { - uploadSpy.mockReset(); - uploadSpy.mockImplementation(async () => undefined); - }); - - it('an outfile directly in a PACKAGE root (monorepo root build) is refused', async () => { - const root = mkdtempSync(join(tmpdir(), 'bugsee-pkgroot-')); - try { - mkdirSync(join(root, 'packages', 'a'), { recursive: true }); - writeFileSync(join(root, 'packages', 'a', 'package.json'), '{"name":"a"}'); - const notices: string[] = []; - await esbuildRun( - { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outfile: 'packages/a/index.js', absWorkingDir: root }, - ).end(); - expect(uploadSpy).not.toHaveBeenCalled(); - expect(notices.some((m) => m.includes('Nothing was uploaded'))).toBe(true); - // A package.json WITHOUT a name and with no src/ or node_modules/ is a marker (dist/cjs), not a package. - mkdirSync(join(root, 'dist', 'cjs'), { recursive: true }); - writeFileSync(join(root, 'dist', 'cjs', 'package.json'), '{"type":"commonjs"}'); - await esbuildRun( - { appToken: 'tok', onNotice: () => undefined }, - { outfile: 'dist/cjs/index.js', absWorkingDir: root }, - ).end(); - expect(uploadSpy).toHaveBeenCalledTimes(1); - uploadSpy.mockClear(); - // ...but one next to a src/ (a nameless package root) is refused. - mkdirSync(join(root, 'lib', 'src'), { recursive: true }); - writeFileSync(join(root, 'lib', 'package.json'), '{"private":true}'); - await esbuildRun( - { appToken: 'tok', onNotice: () => undefined }, - { outfile: 'lib/index.js', absWorkingDir: root }, - ).end(); - expect(uploadSpy).not.toHaveBeenCalled(); - // An unreadable/invalid package.json is no package root either. - mkdirSync(join(root, 'bad'), { recursive: true }); - writeFileSync(join(root, 'bad', 'package.json'), '{not json'); - await esbuildRun( - { appToken: 'tok', onNotice: () => undefined }, - { outfile: 'bad/index.js', absWorkingDir: root }, - ).end(); - expect(uploadSpy).toHaveBeenCalledTimes(1); - uploadSpy.mockClear(); - // The same directory is fine as an `outdir` target (a package may hold a dist with its own package.json). - await esbuildRun({ appToken: 'tok' }, { outdir: 'packages/a', absWorkingDir: root }).end(); - expect(uploadSpy).toHaveBeenCalledTimes(1); - // And an outfile in a package-free subdirectory still uploads. - mkdirSync(join(root, 'out'), { recursive: true }); - await esbuildRun( - { appToken: 'tok', onNotice: () => undefined }, - { outfile: 'out/bundle.js', absWorkingDir: root }, - ).end(); - expect(uploadSpy).toHaveBeenCalledTimes(2); - } finally { - rmSync(root, { recursive: true, force: true }); - } - }); - - it('the project-directory test is segment-aware: a project named "..cache" is below its parent', async () => { - const notices: string[] = []; - await esbuildRun( - { appToken: 'tok', onNotice: (m) => notices.push(m) }, - { outfile: '/proj/bundle.js', absWorkingDir: '/proj/..cache' }, - ).end(); - expect(uploadSpy).not.toHaveBeenCalled(); - expect(notices.some((m) => m.includes('Nothing was uploaded'))).toBe(true); - }); - it('rspack: a build with devtool off says nothing is emitted (once, only when enabled)', () => { const notices: string[] = []; const off = rspackCompiler('/out', 'production'); @@ -848,55 +479,3 @@ describe('guards and notices (review round 3)', () => { expect(quiet.filter((m) => m.includes('devtool'))).toEqual([]); }); }); - -describe('a sweep by an earlier run lets a later run of the same directory find nothing', () => { - const ok = { injected: true, uploaded: true, deletedMaps: ['/abs/s1/a.map'] as string[] }; - beforeEach(() => { - uploadSpy.mockReset(); - orchSpy.mockReset(); - orchSpy.mockImplementation(async () => ok); - uploadSpy.mockImplementation(async (resolved: unknown, outDir: string, deps: unknown) => { - const r = resolved as ResolvedPluginOptions; - await (deps as { uploadSourcemaps: (o: unknown) => Promise }).uploadSourcemaps({ - outDir, - failOnError: r.failOnError, - onError: r.onError, - }); - return undefined; - }); - }); - const allowEmptyOf = (call: number) => - (orchSpy.mock.calls[call]?.[0] as { allowEmpty?: boolean }).allowEmpty; - - it('the second build, which began before the first run swept, is allowed an empty directory', async () => { - const a = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s1' }); - const b = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s1' }); - a.start(); - b.start(); - await a.end(); - await b.end(); - expect(allowEmptyOf(0)).toBeUndefined(); // nothing swept yet: strict - expect(allowEmptyOf(1)).toBe(true); - }); - - it('a build that began AFTER the sweep is not excused', async () => { - const a = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s2' }); - a.start(); - await a.end(); - const later = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s2' }); - later.start(); - await later.end(); - expect(allowEmptyOf(1)).toBeUndefined(); - }); - - it('a run that deleted nothing is not a sweep', async () => { - orchSpy.mockImplementation(async () => ({ injected: true, uploaded: true, deletedMaps: [] })); - const a = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s3' }); - const b = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: '/abs/s3' }); - a.start(); - b.start(); - await a.end(); - await b.end(); - expect(allowEmptyOf(1)).toBeUndefined(); - }); -}); diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index de148facb..7912adfa0 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -11,13 +11,14 @@ import { readdirSync, readFileSync, rmSync, + symlinkSync, writeFileSync, } from 'node:fs'; import { createServer, type Server } from 'node:http'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { rspack } from '@rspack/core'; -import { build as esbuild, type Plugin } from 'esbuild'; +import { build as esbuild, context as esbuildContext, type Plugin } from 'esbuild'; import { build as tsupBuild } from 'tsup'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { bugseeEsbuildPlugin, bugseeRspackPlugin } from './plugin'; @@ -117,66 +118,6 @@ describeReal('real esbuild build', () => { ); }); - it('two OVERLAPPING builds into one outdir (tsup esm+cjs) both get stamped, uploaded and cleaned', async () => { - // One plugin object shared by both builds, as tsup does. The collector is slow, so the first build's - // upload is still in flight when the second build writes its files. Joining that in-flight upload - // (it had already scanned the directory) used to delete the second build's maps, never uploaded. - const app = makeApp('esbuild-race'); - writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); - const errors: unknown[] = []; - const plugin = bugseeEsbuildPlugin({ - ...pluginOptions, - endpoint, - failOnError: false, - onError: (e) => errors.push(e), - }); - const before = requests.length; - delayMs = 600; - try { - await Promise.all([ - esbuild({ - entryPoints: [app.entry], - bundle: true, - outdir: app.out, - absWorkingDir: app.dir, - format: 'esm', - outExtension: { '.js': '.mjs' }, - logLevel: 'silent', - plugins: [plugin], - }), - esbuild({ - entryPoints: [join(app.dir, 'second.js')], - bundle: true, - outdir: app.out, - absWorkingDir: app.dir, - format: 'cjs', - outExtension: { '.js': '.cjs' }, - logLevel: 'silent', - // Finishes while the first build's (slow) upload is in flight. - plugins: [ - plugin, - { - name: 'delay', - setup: (b) => { - b.onStart(() => new Promise((r) => setTimeout(r, 250))); - }, - }, - ], - }), - ]); - } finally { - delayMs = 0; - } - expect(errors).toEqual([]); - const files = readdirSync(app.out); - for (const bundle of ['index.mjs', 'second.cjs']) { - expect(readFileSync(join(app.out, bundle), 'utf8')).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); - } - expect(files.filter((f) => f.endsWith('.map'))).toEqual([]); - // Each build's maps were actually uploaded: at least one request per build. - expect(requests.length - before).toBeGreaterThanOrEqual(2); - }); - it('a disabled plugin leaves the build untouched', async () => { const app = makeApp('esbuild-disabled'); const before = requests.length; @@ -360,7 +301,7 @@ async function withCliPath(wrapper: string, run: () => Promise): Promise +const esmBuild = (app: { dir: string; entry: string; out: string }, plugins: Plugin[], more = {}) => esbuild({ entryPoints: [app.entry], bundle: true, @@ -370,8 +311,9 @@ const esmBuild = (app: { dir: string; entry: string; out: string }, plugins: Plu outExtension: { '.js': '.mjs' }, logLevel: 'silent', plugins, + ...more, }); -const cjsBuild = (app: { dir: string; out: string }, plugins: Plugin[]) => +const cjsBuild = (app: { dir: string; out: string }, plugins: Plugin[], more = {}) => esbuild({ entryPoints: [join(app.dir, 'second.js')], bundle: true, @@ -381,23 +323,26 @@ const cjsBuild = (app: { dir: string; out: string }, plugins: Plugin[]) => outExtension: { '.js': '.cjs' }, logLevel: 'silent', plugins, + ...more, }); -function expectBothStamped(out: string): void { - for (const bundle of ['index.mjs', 'second.cjs']) { - expect(readFileSync(join(out, bundle), 'utf8')).toMatch(/\/\/# debugId=[0-9a-f-]{36}/); - } - expect(readdirSync(out).filter((f) => f.endsWith('.map'))).toEqual([]); -} +const STAMP = /\/\/# debugId=[0-9a-f-]{36}/; +const stamped = (path: string): boolean => STAMP.test(readFileSync(path, 'utf8')); +const mapsIn = (dir: string): string[] => readdirSync(dir).filter((f) => f.endsWith('.map')); +const withSecond = (name: string) => { + const app = makeApp(name); + writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); + return app; +}; -describeReal("a build writing while another build's upload is between inject and upload", () => { +describeReal('esm + cjs builds into one outdir (tsup-style, one shared plugin)', () => { it.each([ - false, - true, - ])('is retried, not reported as a failed upload (failOnError: %s; CLI wrapper pauses after inject)', async (failOnError) => { - const app = makeApp(`esbuild-inject-race-${failOnError}`); - writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); - const { wrapper, injected, proceed } = pauseAfterInjectWrapper(app.dir); + [true, 0], + [false, 0], + [true, 400], + [false, 400], + ])('both are stamped, uploaded and cleaned (failOnError %s, collector delay %s ms)', async (failOnError, delay) => { + const app = withSecond(`esbuild-dual-${failOnError}-${delay}`); const errors: unknown[] = []; const plugin = bugseeEsbuildPlugin({ ...pluginOptions, @@ -405,96 +350,147 @@ describeReal("a build writing while another build's upload is between inject and failOnError, onError: (e) => errors.push(e), }); - await withCliPath(wrapper, async () => { - const first = esmBuild(app, [plugin]); - await waitForFile(injected); - // Starts only after A's inject has scanned: its files land between A's inject and A's upload. - const second = cjsBuild(app, [plugin]); - await waitForFile(join(app.out, 'second.cjs.map')); - writeFileSync(proceed, '1'); - await Promise.all([first, second]); - }); + const before = requests.length; + delayMs = delay; + try { + await Promise.all([esmBuild(app, [plugin]), cjsBuild(app, [plugin])]); + } finally { + delayMs = 0; + } expect(errors).toEqual([]); - expectBothStamped(app.out); + expect(stamped(join(app.out, 'index.mjs'))).toBe(true); + expect(stamped(join(app.out, 'second.cjs'))).toBe(true); + expect(mapsIn(app.out)).toEqual([]); + expect(requests.length - before).toBeGreaterThanOrEqual(2); // one upload per build }); +}); - it('also when the other build was ALREADY in flight when the run began (it finishes between inject and upload)', async () => { - const app = makeApp('esbuild-inject-race-inflight'); - writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); +describeReal('a build only touches the files it wrote', () => { + it("foreign files appearing between the run's inject and upload are left exactly as they are", async () => { + const app = withSecond('esbuild-foreign'); const { wrapper, injected, proceed } = pauseAfterInjectWrapper(app.dir); const errors: unknown[] = []; const plugin = bugseeEsbuildPlugin({ ...pluginOptions, endpoint, - failOnError: false, + failOnError: true, onError: (e) => errors.push(e), }); - let reached: () => void = () => undefined; - const gateReached = new Promise((r) => { - reached = r; - }); - let release: () => void = () => undefined; - const gate = new Promise((r) => { - release = r; - }); - const gatePlugin: Plugin = { - name: 'gate', - setup(b) { - b.onLoad({ filter: /second\.js$/ }, async () => { - reached(); - await gate; - return undefined; - }); - }, - }; + mkdirSync(app.out, { recursive: true }); await withCliPath(wrapper, async () => { - const second = cjsBuild(app, [plugin, gatePlugin]); // in flight, held at its first file - await gateReached; - const first = esmBuild(app, [plugin]); // its run starts while the second build is in flight + const first = esmBuild(app, [plugin]); await waitForFile(injected); - release(); // the second build now writes and ends, between the first run's inject and upload - await waitForFile(join(app.out, 'second.cjs.map')); + // A foreign build (no plugin) writes an unstamped bundle and map between inject and upload. + const foreign = cjsBuild(app, [], { sourcemap: 'external' }); + await foreign; writeFileSync(proceed, '1'); - await Promise.all([first, second]); + await first; }); expect(errors).toEqual([]); - expectBothStamped(app.out); + expect(stamped(join(app.out, 'index.mjs'))).toBe(true); + expect(mapsIn(app.out)).toEqual(['second.cjs.map']); // not uploaded, not deleted + expect(stamped(join(app.out, 'second.cjs'))).toBe(false); // not stamped }); -}); -describeReal('two concurrent builds into one outdir under failOnError: true', () => { - it.each([ - 0, 400, - ])("both succeed, though the first run sweeps the second build's maps too (collector delay %s ms)", async (delay) => { - const app = makeApp(`esbuild-dual-strict-${delay}`); - writeFileSync(join(app.dir, 'second.js'), "console.log('second');\n"); + it('two plugin instances over one outdir each upload only their own build, with their own options', async () => { + const app = withSecond('esbuild-two-instances'); + const a = bugseeEsbuildPlugin({ ...pluginOptions, endpoint, deleteMaps: true }); + const b = bugseeEsbuildPlugin({ ...pluginOptions, endpoint, deleteMaps: false }); + const before = requests.length; + await Promise.all([esmBuild(app, [a]), cjsBuild(app, [b])]); + expect(requests.length - before).toBeGreaterThanOrEqual(2); + expect(stamped(join(app.out, 'index.mjs'))).toBe(true); + expect(stamped(join(app.out, 'second.cjs'))).toBe(true); + // A deleted its build's map; B (deleteMaps: false) kept its own, and neither touched the other's. + expect(mapsIn(app.out)).toEqual(['second.cjs.map']); + }); + + it('an external-maps build and an inline-maps build together under failOnError: the inline one FAILS', async () => { + const app = withSecond('esbuild-ext-and-inline'); const plugin = bugseeEsbuildPlugin({ ...pluginOptions, endpoint, failOnError: true }); - delayMs = delay; + const results = await Promise.allSettled([ + esmBuild(app, [plugin], { sourcemap: 'external' }), + cjsBuild(app, [plugin], { sourcemap: 'inline' }), + ]); + expect(results[0]?.status).toBe('fulfilled'); + expect(results[1]?.status).toBe('rejected'); + expect(stamped(join(app.out, 'index.mjs'))).toBe(true); + }); +}); + +describeReal('watch mode (a long-lived esbuild context)', () => { + it("uploads each rebuild's own outputs", async () => { + const app = makeApp('esbuild-watch'); + const plugin = bugseeEsbuildPlugin({ ...pluginOptions, endpoint }); + const ctx = await esbuildContext({ + entryPoints: [app.entry], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + logLevel: 'silent', + plugins: [plugin], + }); try { - await Promise.all([esmBuild(app, [plugin]), cjsBuild(app, [plugin])]); + const before = requests.length; + await ctx.rebuild(); + expect(requests.length).toBeGreaterThan(before); + expect(mapsIn(app.out)).toEqual([]); + const afterFirst = requests.length; + writeFileSync(app.entry, "console.log('changed');\n"); + await ctx.rebuild(); + expect(requests.length).toBeGreaterThan(afterFirst); + expect(mapsIn(app.out)).toEqual([]); + expect(stamped(join(app.out, 'index.js'))).toBe(true); } finally { - delayMs = 0; + await ctx.dispose(); } - expectBothStamped(app.out); }); +}); - it('a lone build with no maps still fails under failOnError (the sweep rule does not weaken it)', async () => { - const app = makeApp('esbuild-dual-strict-lone'); - const plugin = bugseeEsbuildPlugin({ ...pluginOptions, endpoint, failOnError: true }); - await expect( - esbuild({ - entryPoints: [app.entry], - bundle: true, - outdir: app.out, - absWorkingDir: app.dir, - sourcemap: 'inline', - logLevel: 'silent', - plugins: [plugin], - }), - ).rejects.toThrow(); +describeReal('paths and sizes', () => { + it('an outdir reached through a symlink works (nothing compares directories)', async () => { + const app = makeApp('esbuild-symlink'); + const real = join(app.dir, 'real-out'); + mkdirSync(real, { recursive: true }); + const link = join(app.dir, 'linked-out'); + symlinkSync(real, link); + await esbuild({ + entryPoints: [app.entry], + bundle: true, + outdir: link, + absWorkingDir: app.dir, + logLevel: 'silent', + plugins: [bugseeEsbuildPlugin({ ...pluginOptions, endpoint })], + }); + expect(stamped(join(real, 'index.js'))).toBe(true); + expect(mapsIn(real)).toEqual([]); }); -}); + it('a build with more outputs than fit in one CLI call is batched and fully uploaded', async () => { + const app = makeApp('esbuild-many'); + const entries: string[] = []; + for (let i = 0; i < 250; i++) { + const f = join(app.dir, `e${i}.js`); + writeFileSync(f, `console.log(${i});\n`); + entries.push(f); + } + const before = requests.length; + await esbuild({ + entryPoints: entries, + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + logLevel: 'silent', + plugins: [bugseeEsbuildPlugin({ ...pluginOptions, endpoint })], + }); + expect(mapsIn(app.out)).toEqual([]); + expect(readdirSync(app.out).filter((f) => f.endsWith('.js'))).toHaveLength(250); + for (const f of readdirSync(app.out)) { + expect(stamped(join(app.out, f))).toBe(true); + } + expect(requests.length - before).toBeGreaterThanOrEqual(2); + }); +}); describeReal('failOnError with an esbuild build that emitted no maps', () => { const build = (name: string, options: object) => { const app = makeApp(name); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 9b58e588b..4f3f19860 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -2,8 +2,7 @@ // vite/rollup `writeBundle`, webpack/rspack `afterEmit` and esbuild `onEnd`. The per-bundler entry points (@bugsee/vite-plugin, // @bugsee/webpack-plugin) are thin wrappers over `bugseeUnplugin`. The output-dir resolver is a pure, // tested helper; the framework hook registration is thin glue exercised by the real-build e2e (SM-B/SM-C). -import { existsSync, readFileSync } from 'node:fs'; -import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { dirname, resolve } from 'node:path'; import { createUnplugin, type UnpluginFactory, type UnpluginInstance } from 'unplugin'; import { APP_BUILD_DEFINE, @@ -14,10 +13,6 @@ import { } from './app-identity'; import { bakeIdentity, type ParseChunk } from './bake-identity'; import { loadBuildPluginEnv, mergeBuildPluginEnv } from './env-file'; -import { - defaultUploadErrorHandler, - uploadSourcemaps as defaultUploadSourcemaps, -} from './orchestrate'; import type { BundlerBuildContext } from './register-build'; import { type BugseePluginOptions, @@ -28,7 +23,6 @@ import { runPluginUpload, } from './resolve'; import { type AssetStore, stampAssets } from './stamp-assets'; -import { uploadTuning } from './upload-tuning'; /** The subset of a rollup/vite output-options object we read. */ export interface OutputLike { @@ -205,143 +199,37 @@ function webpackBuild(mode: string | undefined): BundlerBuildContext { /** The slice of esbuild's plugin `build` object the end-of-build upload reads. */ interface EsbuildBuildLike { initialOptions: { outdir?: string; outfile?: string; absWorkingDir?: string; write?: boolean }; - onStart(callback: () => void): void; - onEnd(callback: (result: { errors: readonly unknown[] }) => void | Promise): void; + onEnd(callback: (result: EsbuildEndResult) => void | Promise): void; } -/** - * Run uploads for one output directory ONE AFTER ANOTHER. `runPluginUpload` makes a concurrent caller JOIN the - * in-flight run, which is right for one build with several outputs but wrong for esbuild builds that share an - * outdir (tsup's esm + cjs): the in-flight run scanned the directory BEFORE the second build wrote its files, - * and its delete-maps step then removes the second build's maps unuploaded. Each build's own run therefore - * starts only once the previous one has settled, and scans what is on disk by then. A failure in an earlier - * run does not block the next, and is reported to the build that owned it. - */ -const uploadTails = new Map>(); -function serialUpload(outDir: string, run: () => Promise): Promise { - const result = (uploadTails.get(outDir) ?? Promise.resolve()).then(run); - const tail = result.then( - () => undefined, - () => undefined, - ); - uploadTails.set(outDir, tail); - void tail.then(() => { - if (uploadTails.get(outDir) === tail) { - uploadTails.delete(outDir); - } - }); - return result; -} - -/** - * What the esbuild builds writing into one directory are doing. Serialising uploads is not enough on its own: - * a run is `inject` then `upload`, each scanning the whole directory, so a build that WRITES between the two - * leaves a map without a debug-id for the upload to trip over (exit 11). So a failure while another build started or ended in the meantime is - * retried (the later scan sees finished files) instead of being reported. The first attempt never waits (a build - * nested in another cannot finish until its own upload has). - */ -interface DirActivity { - inflight: number; - /** Bumped at every build start: lets a run tell that the directory was touched while it ran. */ - starts: number; - /** Runs that uploaded and deleted maps: a later run of a build that began earlier may find nothing left. */ - sweeps: number; -} -const dirActivity = new Map(); -const activityOf = (outDir: string): DirActivity => { - let activity = dirActivity.get(outDir); - if (activity === undefined) { - activity = { inflight: 0, starts: 0, sweeps: 0 }; - dirActivity.set(outDir, activity); - } - return activity; -}; -/** Wait (bounded) until no build of the directory is in flight: only a RETRY waits, see `uploadTuning`. */ -async function waitForIdle(activity: DirActivity): Promise { - for ( - let waited = 0; - activity.inflight > 0 && waited < uploadTuning.idleWaitMs; - waited += uploadTuning.pollMs - ) { - await new Promise((r) => setTimeout(r, uploadTuning.pollMs)); - } +/** What esbuild hands `onEnd`: the errors, and (we ask for it) the metafile listing the build's own outputs. */ +interface EsbuildEndResult { + errors: readonly unknown[]; + metafile?: { outputs: Record }; } /** - * The upload step for one esbuild output directory, with the retry for a build that wrote while it ran. - * - * It wraps ONLY `uploadSourcemaps` (handed to `runPluginUpload` as a dependency), so everything else keeps its - * own handling: the user's `failOnError` still reaches the step (it also decides `--allow-empty`, so a build - * that emitted no maps still fails under `failOnError`), and a build-REGISTRATION failure is reported as - * itself and never retried. A failure is captured; if another build started while the step ran (or one is - * still running) it is retried after a bounded wait, otherwise it is reported as configured. + * The files THIS build wrote, from its metafile (paths are relative to `absWorkingDir`), split into the bundles + * `sourcemaps inject` stamps and the maps it uploads. The whole esbuild upload runs on these lists and nothing + * else, which is what keeps it correct with no coordination at all: a build only touches files it wrote, so + * nothing is deleted without having been uploaded, nothing is uploaded under another build's options (or + * another plugin instance's), a nested or concurrent build never waits for anything, and watch mode needs no + * state between rebuilds. */ -function settledUpload(outDir: string, sweepsAtStart: number): typeof defaultUploadSourcemaps { - const activity = activityOf(outDir); - return async (options) => { - for (let attempt = 1; ; attempt++) { - const startsBefore = activity.starts; - // A build that was already running when this attempt began may write between inject and upload too. - const busyBefore = activity.inflight > 0; - const captured: unknown[] = []; - let thrown: { error: unknown } | undefined; - let result: Awaited> | undefined; - try { - result = await defaultUploadSourcemaps({ - ...options, - // An earlier run of this directory already swept (uploaded and deleted) maps since this build began, - // this build's among them (dual-format builds into one outdir): finding none is then success, even - // under failOnError. A lone map-less build has no such sweep and still fails. - allowEmpty: activity.sweeps > sweepsAtStart ? true : options.allowEmpty, - onError: (error) => captured.push(error), - }); - } catch (error) { - thrown = { error }; - } - if (thrown === undefined && captured.length === 0) { - if ((result?.deletedMaps.length ?? 0) > 0) { - activity.sweeps++; - } - return result as Awaited>; - } - if ( - (busyBefore || activity.starts !== startsBefore || activity.inflight > 0) && - attempt < uploadTuning.attempts - ) { - await waitForIdle(activity); - continue; - } - if (thrown !== undefined) { - throw thrown.error; - } - (options.onError ?? defaultUploadErrorHandler)(captured[0]); - return result as Awaited>; - } +function esbuildOwnFiles( + result: EsbuildEndResult, + base: string, +): { scripts: string[]; maps: string[] } { + const outputs = Object.keys(result.metafile?.outputs ?? {}).map((file) => resolve(base, file)); + return { + scripts: outputs.filter((file) => /\.[cm]?js$/.test(file)), + maps: outputs.filter((file) => file.endsWith('.map')), }; } -/** - * Whether `dir` looks like a package's root rather than an output folder: a package.json with a `name`, or a - * `src/` or `node_modules/` next to it. (A `dist/cjs/package.json` holding only `{"type":"commonjs"}` is a marker.) - */ -function isPackageRoot(dir: string): boolean { - try { - const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { - name?: unknown; - }; - if (typeof manifest.name === 'string' && manifest.name !== '') { - return true; - } - return existsSync(join(dir, 'src')) || existsSync(join(dir, 'node_modules')); - } catch { - return false; - } -} - -/** Whether `dir` is `project` or one of its ancestors (a segment-aware test: `..cache` is not `..`). */ -function isSameOrAbove(dir: string, project: string): boolean { - const rel = relative(dir, project); - return rel === '' || !(rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)); +/** The directory esbuild's metafile paths are relative to. */ +function esbuildBase(options: EsbuildBuildLike['initialOptions']): string { + return resolve(options.absWorkingDir ?? process.cwd()); } /** esbuild's output directory: `outdir`, else the directory of `outfile`, resolved against `absWorkingDir`. */ @@ -351,7 +239,7 @@ function esbuildOutputDir(options: EsbuildBuildLike['initialOptions']): string | return undefined; } try { - return resolve(options.absWorkingDir ?? process.cwd(), out); + return resolve(esbuildBase(options), out); } catch { // The working directory is gone (`process.cwd()` throws) and the path is relative: nothing to upload. return undefined; @@ -563,6 +451,7 @@ export const bugseeUnpluginFactory: UnpluginFactory; absWorkingDir?: string; sourcemap?: boolean | string; + metafile?: boolean; }) { const { identityDefines } = identityFromRoot( initialOptions.absWorkingDir, @@ -592,25 +481,17 @@ export const bugseeUnpluginFactory: UnpluginFactory { - if (activity !== undefined) { - activity.inflight++; - activity.starts++; - sweepsAtStart = activity.sweeps; - } - }); build.onEnd(async (result) => { - if (activity !== undefined) { - activity.inflight = Math.max(0, activity.inflight - 1); - } // A failed build wrote nothing worth uploading. if (result.errors.length > 0 || outDir === undefined) { return; @@ -625,40 +506,23 @@ export const bugseeUnpluginFactory: UnpluginFactory - runPluginUpload(forOutput(outDir), outDir, { - bundler: {}, - uploadSourcemaps: settledUpload(outDir, sweepsAtStart), - }), - ); + await runPluginUpload(forOutput(outDir), outDir, { bundler: {}, files }); }); }, }, diff --git a/packages/bundler-plugin-core/src/resolve.test.ts b/packages/bundler-plugin-core/src/resolve.test.ts index a76d353da..dc0f7272c 100644 --- a/packages/bundler-plugin-core/src/resolve.test.ts +++ b/packages/bundler-plugin-core/src/resolve.test.ts @@ -245,6 +245,54 @@ describe('one pipeline per output directory', () => { expect(await a).toEqual(await b); // …and the joiner gets the same result, not `undefined` }); + it("a run over the build's own files neither joins nor is joined, and registers from those bundles only", async () => { + const h = held(); + const files = { scripts: ['dist/a.mjs'], maps: ['dist/a.mjs.map'] }; + const seen: Array<{ files?: unknown }> = []; + const upload = async (opts: { outDir: string; files?: unknown }) => { + seen.push(opts); + return h.uploadSourcemaps(opts); + }; + const collected: Array<() => Promise> = []; + const registerJsBuild = vi.fn(async (o: { collectDebugIds?: () => Promise }) => { + if (o.collectDebugIds) { + collected.push(o.collectDebugIds); + } + return { registered: false as const, reason: 'not-release' as const }; + }); + const a = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + registerJsBuild: registerJsBuild as never, + files, + ...noVcs, + }); + const b = runPluginUpload(resolved, 'dist', { + uploadSourcemaps: upload as never, + registerJsBuild: registerJsBuild as never, + files: { scripts: ['dist/b.cjs'], maps: ['dist/b.cjs.map'] }, + ...noVcs, + }); + await tick(); + expect(h.started).toEqual(['dist', 'dist']); // two pipelines at once + expect(seen.map((o) => o.files)).toEqual([ + files, + { scripts: ['dist/b.cjs'], maps: ['dist/b.cjs.map'] }, + ]); + h.release(); + await Promise.all([a, b]); + // The slot map was never used: a later directory-wide run is not blocked or joined. + const later = held(); + later.release(); + await runPluginUpload(resolved, 'dist', { + uploadSourcemaps: later.uploadSourcemaps as never, + ...noVcs, + }); + expect(later.started).toEqual(['dist']); + // Registration was handed a reader scoped to the build's own bundles (absent files: nothing, no throw). + expect(collected).toHaveLength(2); + expect(await collected[0]?.()).toEqual([]); + }); + it('still runs a second pipeline for a DIFFERENT directory — the canary', async () => { const h = held(); const a = runPluginUpload(resolved, 'dist-a', { diff --git a/packages/bundler-plugin-core/src/resolve.ts b/packages/bundler-plugin-core/src/resolve.ts index d6e6429d8..9e45f7c76 100644 --- a/packages/bundler-plugin-core/src/resolve.ts +++ b/packages/bundler-plugin-core/src/resolve.ts @@ -8,6 +8,7 @@ import { type FixedIdentity, findAppIdentity, } from './app-identity'; +import { collectDebugIdsOf } from './debug-ids'; import { uploadSourcemaps as defaultUploadSourcemaps, type UploadSourcemapsResult, @@ -276,6 +277,11 @@ export async function runPluginUpload( bundler?: BundlerBuildContext; /** The bundles were stamped inside the build (stamp-assets.ts); skip the post-emit inject. */ preStamped?: boolean; + /** + * The build's own outputs (esbuild's metafile). The run then touches exactly these files, never joins another + * run of the same directory, and registers from these bundles only. + */ + files?: { scripts: readonly string[]; maps: readonly string[] }; } = {}, ): Promise { if (!resolved.enabled) { @@ -286,7 +292,9 @@ export async function runPluginUpload( // both `dist` — used to start two concurrent pipelines over one tree, with one deleting maps // while the other was still reading them. A concurrent caller JOINS the in-flight run and // gets its result; the entry is released on settle, so `vite build --watch` still uploads every rebuild. - const inFlight = runsByDir.get(outDir); + // A run over a build's OWN files (`deps.files`) neither joins nor is joined: it touches nothing another run + // of the directory touches, so there is nothing to coordinate. + const inFlight = deps.files === undefined ? runsByDir.get(outDir) : undefined; if (inFlight !== undefined) { return inFlight; } @@ -309,6 +317,7 @@ export async function runPluginUpload( // Omitted unless true, so the orchestrator's argument stays exactly what it was for every // build that did not take the in-build path. ...(deps.preStamped === true ? { preStamped: true } : {}), + ...(deps.files !== undefined ? { files: deps.files } : {}), }); // 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 @@ -321,6 +330,9 @@ export async function runPluginUpload( endpoint: resolved.endpoint, setting: resolved.registerBuild, bundler: deps.bundler ?? {}, + ...(deps.files !== undefined + ? { collectDebugIds: () => collectDebugIdsOf(deps.files?.scripts ?? []) } + : {}), env: resolved.nodeEnv !== undefined ? { NODE_ENV: resolved.nodeEnv } : {}, ...(resolved.packageId !== undefined ? { packageId: resolved.packageId } : {}), // The nearest package.json above the OUTPUT names the package that built it. The process cwd @@ -346,6 +358,9 @@ export async function runPluginUpload( // sequential caller (watch mode) find the slot free on its next call. It holds because this function // is `async` and so adds a thenable-adoption tick; the non-async variant reverses the two, leaving // the slot still held when the caller resumes. Not the pure refactor it looks like. + if (deps.files !== undefined) { + return run; + } runsByDir.set(outDir, run); void run .catch(() => undefined) diff --git a/packages/bundler-plugin-core/src/upload-tuning.ts b/packages/bundler-plugin-core/src/upload-tuning.ts deleted file mode 100644 index b243b95a1..000000000 --- a/packages/bundler-plugin-core/src/upload-tuning.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Knobs of the esbuild concurrent-build retry (plugin.ts `settledUpload`). A mutable object only so a test can -// shrink the waits; production never changes it and it is not exported from the package entry. -export const uploadTuning = { - /** Attempts for one directory's upload when it keeps coinciding with another build writing. */ - attempts: 3, - /** - * How long a RETRY waits for the other builds of the directory to finish. Bounded and short on purpose: - * the first attempt never waits, because a build nested inside another (a plugin running esbuild.build() - * for a worker into the same outdir) cannot finish until its own upload has, so waiting on it would stall - * the whole build for the full cap. - */ - idleWaitMs: 5_000, - pollMs: 25, -}; From 57dae62bc2a107ed39254a0d053f27f582d70363 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 19:51:30 +0500 Subject: [PATCH 11/12] fix(bundler-plugin-core): never name stylesheet maps to the CLI; stylesheet-only builds are a no-op Round-6 review of #196: the CLI skips a .css.map when scanning a directory but fails the whole call (exit 11) when one is named as an explicit path. The esbuild file list now keeps only the maps of the build's own scripts and deletes .css.map files with them after a confirmed upload; a build with no scripts is a quiet no-op, a build with scripts but no script maps still fails under failOnError. Real CSS builds (splitting + hashed names, css-only, watch) and unit cases added. Docs: SRI scan wording; comment on batch splitting. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/source-maps-usage.md | 5 +- .../src/orchestrate.test.ts | 15 +++ .../bundler-plugin-core/src/orchestrate.ts | 14 ++- .../src/plugin.esbuild-rspack.test.ts | 32 +++++-- .../src/plugin.real-build.test.ts | 95 +++++++++++++++++++ packages/bundler-plugin-core/src/plugin.ts | 15 ++- packages/bundler-plugin-core/src/resolve.ts | 6 +- 7 files changed, 167 insertions(+), 15 deletions(-) diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 3062c3681..1c29ffdfb 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -40,7 +40,10 @@ touches files it wrote: nothing is deleted without having been uploaded, nothing options or another plugin instance's, builds sharing an output directory (an ESM + CJS pair, a worker sub-build, two plugin instances) never wait for or affect each other, and watch mode keeps no state between rebuilds. Under `failOnError`, a build whose own outputs contain no `.map` (for example `sourcemap: 'inline'`) fails, judged on that -build alone; without `failOnError` it is a notice. `outfile` and `outdir` behave alike, wherever they point. +build alone; without `failOnError` it is a notice. A stylesheet-only build is a quiet no-op, and `.css.map` files are +never sent (they are deleted with the script maps after a successful upload). The upload never walks the output +directory (the one read-only exception is the Subresource-Integrity check, which looks at the `.html` files under it). +`outfile` and `outdir` behave alike, wherever they point. Development builds do not upload and leave the local maps alone unless you set `uploadInDevelopment: true`: Rspack states its mode (only `development` is skipped; `none` and `production` upload), esbuild states none, so only `NODE_ENV=development` marks a dev build (a bare `esbuild --watch` without it uploads on every rebuild, so set it or disable the plugin there). Rspack stamps after emit rather than inside the compilation, diff --git a/packages/bundler-plugin-core/src/orchestrate.test.ts b/packages/bundler-plugin-core/src/orchestrate.test.ts index 339d92c4e..1496b1d3b 100644 --- a/packages/bundler-plugin-core/src/orchestrate.test.ts +++ b/packages/bundler-plugin-core/src/orchestrate.test.ts @@ -797,6 +797,21 @@ describe("a run over the build's own files", () => { expect(list).not.toHaveBeenCalled(); }); + it('stylesheet maps are never given to the CLI but are deleted with the rest after the upload', async () => { + const { run, calls } = fakeRun(); + const deleteMapFiles = vi.fn(async (_d: string, only?: readonly string[]) => [...(only ?? [])]); + const css = ['/b/a.css.map']; + await uploadSourcemaps({ + ...base, + outDir: '/b', + files: { scripts, maps, stylesheetMaps: css }, + run, + deleteMapFiles, + }); + expect(calls.flatMap((c) => c.args)).not.toContain('/b/a.css.map'); + expect(deleteMapFiles).toHaveBeenCalledWith('/b', [...maps, ...css]); + }); + it('batches paths per CLI call, and deletes only after every batch uploaded', async () => { const many = Array.from({ length: 450 }, (_, i) => `/b/c${i}.js`); const manyMaps = many.map((f) => `${f}.map`); diff --git a/packages/bundler-plugin-core/src/orchestrate.ts b/packages/bundler-plugin-core/src/orchestrate.ts index 513e83749..692eb9a8a 100644 --- a/packages/bundler-plugin-core/src/orchestrate.ts +++ b/packages/bundler-plugin-core/src/orchestrate.ts @@ -47,7 +47,12 @@ export interface UploadSourcemapsOptions { * Nothing walks the directory, so a build can never touch (stamp, upload under its own options, or delete) a * file another build wrote there. `scripts` are the `.js`/`.mjs`/`.cjs` outputs, `maps` the `.map` outputs. */ - files?: { scripts: readonly string[]; maps: readonly string[] }; + files?: { + scripts: readonly string[]; + maps: readonly string[]; + /** Maps the CLI is not given (stylesheet maps); deleted with `maps`, only after a confirmed upload. */ + stylesheetMaps?: readonly string[]; + }; /** Injectable `.map` lister for the delete snapshot of a directory run (default {@link listMapFiles}). */ listMapFiles?: (dir: string) => Promise; /** Injectable SRI scan (default {@link findSriProtectedScripts}). */ @@ -245,6 +250,8 @@ export async function uploadSourcemaps( if (files === undefined) { await run(['sourcemaps', 'inject', outDir, ...dryFlag], 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); } @@ -321,7 +328,10 @@ export async function uploadSourcemaps( return { injected: true, uploaded: true, deletedMaps: [], ...vcsEcho }; } const deletedMaps = deleteMaps - ? await (options.deleteMapFiles ?? defaultDeleteMapFiles)(outDir, files?.maps ?? snapshot) + ? await (options.deleteMapFiles ?? defaultDeleteMapFiles)( + outDir, + files === undefined ? snapshot : [...files.maps, ...(files.stylesheetMaps ?? [])], + ) : []; return { injected: true, uploaded: true, deletedMaps, ...vcsEcho }; } catch (error) { diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index 5b51da0ec..e26b6ca13 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -81,6 +81,8 @@ describe("esbuild: upload of the build's own files at the end of the build", () 'dist/b.mjs.map', 'dist/c.cjs', 'dist/style.css', + 'dist/style.css.map', + 'dist/orphan.txt.map', ), ); expect(uploadSpy).toHaveBeenCalledTimes(1); @@ -89,7 +91,10 @@ describe("esbuild: upload of the build's own files at the end of the build", () expect(resolved).toMatchObject({ enabled: true, appToken: 'tok', appVersion: '3.0.0' }); expect(filesOf(0)).toEqual({ scripts: ['dist/a.js', 'dist/b.mjs', 'dist/c.cjs'].map((f) => resolve('/proj/app', f)), + // Only the maps of the build's own scripts are named to the CLI: a stylesheet map has no debug-id and would + // fail the whole call; it is deleted with the rest instead. maps: ['dist/a.js.map', 'dist/b.mjs.map'].map((f) => resolve('/proj/app', f)), + stylesheetMaps: [resolve('/proj/app', 'dist/style.css.map')], }); // esbuild states nothing about production, so the run falls back to NODE_ENV. expect(bundlerOf(0)).toEqual({}); @@ -100,13 +105,14 @@ describe("esbuild: upload of the build's own files at the end of the build", () expect(filesOf(0)?.maps).toEqual([resolve('dist/a.js.map')]); }); - it('works for an outfile in ANY directory, including the project directory: nothing walks it', async () => { + it('works for an outfile in ANY directory, including the project directory: only its own files are named', async () => { await esbuildRun({ appToken: 'tok' }, { outfile: 'bundle.js', absWorkingDir: '/proj/app' }).end( outputsOf('bundle.js', 'bundle.js.map'), ); expect(filesOf(0)).toEqual({ scripts: [resolve('/proj/app', 'bundle.js')], maps: [resolve('/proj/app', 'bundle.js.map')], + stylesheetMaps: [], }); }); @@ -185,13 +191,23 @@ describe("esbuild: upload of the build's own files at the end of the build", () expect(notices.filter((m) => m.includes('emitted no .map files'))).toHaveLength(1); }); - it('also when the result carries no metafile at all', async () => { - await esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: 'dist' }) - .end({ errors: [] }) - ?.then( - () => expect.unreachable('should have thrown'), - (e: Error) => expect(e.message).toContain('no .map files'), - ); + it('a build with no scripts at all (stylesheet-only, or no metafile) is a quiet no-op, even under failOnError', async () => { + const notices: string[] = []; + const run = esbuildRun( + { appToken: 'tok', failOnError: true, onNotice: (m) => notices.push(m) }, + { outdir: 'dist' }, + ); + await run.end(outputsOf('dist/only.css', 'dist/only.css.map')); + await run.end({ errors: [] }); + expect(uploadSpy).not.toHaveBeenCalled(); + expect(notices.filter((m) => m.includes('emitted no .map files'))).toEqual([]); + }); + + it('scripts whose only maps are stylesheet maps still count as no maps', async () => { + const run = esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: 'dist' }); + await expect(run.end(outputsOf('dist/a.js', 'dist/b.css', 'dist/b.css.map'))).rejects.toThrow( + /emitted no \.map files/, + ); }); }); diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index 7912adfa0..6bb9464ba 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -580,3 +580,98 @@ describeReal('a build nested inside another into the same outdir (worker bundlin expect(readdirSync(app.out).filter((f) => f.endsWith('.map'))).toEqual([]); }); }); + +describeReal('builds that emit stylesheet maps (.css.map)', () => { + // The CLI skips a `.css.map` it finds while scanning a directory, but a map named as an explicit path that has no + // debug-id fails the whole call (exit 11). The plugin therefore sends only the maps of the build's own scripts. + const cssApp = (name: string) => { + const app = makeApp(name); + writeFileSync(join(app.dir, 'a.css'), 'body { color: red; }\n'); + writeFileSync(join(app.dir, 'lazy.js'), "export const lazy = () => 'lazy';\n"); + writeFileSync( + app.entry, + "import './a.css';\nimport('./lazy.js').then((m) => console.log(m.lazy()));\n", + ); + return app; + }; + + it.each([ + true, + false, + ])('splitting + hashed names + css uploads the script maps and removes every map (failOnError %s)', async (failOnError) => { + const app = cssApp(`esbuild-css-${failOnError}`); + const errors: unknown[] = []; + const before = requests.length; + await esbuild({ + entryPoints: [app.entry], + bundle: true, + splitting: true, + format: 'esm', + entryNames: '[name]-[hash]', + chunkNames: '[name]-[hash]', + outdir: app.out, + absWorkingDir: app.dir, + logLevel: 'silent', + plugins: [ + bugseeEsbuildPlugin({ + ...pluginOptions, + endpoint, + failOnError, + onError: (e) => errors.push(e), + }), + ], + }); + expect(errors).toEqual([]); + expect(requests.length).toBeGreaterThan(before); + const files = readdirSync(app.out); + expect(files.some((f) => f.endsWith('.css'))).toBe(true); + for (const f of files.filter((f) => f.endsWith('.js'))) { + expect(stamped(join(app.out, f))).toBe(true); + } + expect(mapsIn(app.out)).toEqual([]); // including the .css.map, as the directory path did + }); + + it.each([ + true, + false, + ])('a css-only build (no scripts) is a quiet no-op, even under failOnError (%s)', async (failOnError) => { + const app = makeApp(`esbuild-css-only-${failOnError}`); + writeFileSync(join(app.dir, 'only.css'), 'a { color: blue; }\n'); + const before = requests.length; + await esbuild({ + entryPoints: [join(app.dir, 'only.css')], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + logLevel: 'silent', + plugins: [bugseeEsbuildPlugin({ ...pluginOptions, endpoint, failOnError })], + }); + expect(requests.length).toBe(before); + }); + + it('watch rebuilds of an app that imports css keep uploading', async () => { + const app = cssApp('esbuild-css-watch'); + const errors: unknown[] = []; + const ctx = await esbuildContext({ + entryPoints: [app.entry], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + logLevel: 'silent', + plugins: [ + bugseeEsbuildPlugin({ ...pluginOptions, endpoint, onError: (e) => errors.push(e) }), + ], + }); + try { + await ctx.rebuild(); + const afterFirst = requests.length; + writeFileSync(join(app.dir, 'a.css'), 'body { color: green; }\n'); + await ctx.rebuild(); + expect(requests.length).toBeGreaterThan(afterFirst); + expect(errors).toEqual([]); + expect(mapsIn(app.out)).toEqual([]); + } finally { + await ctx.dispose(); + } + }); +}); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index 4f3f19860..fe3fd2970 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -219,11 +219,17 @@ interface EsbuildEndResult { function esbuildOwnFiles( result: EsbuildEndResult, base: string, -): { scripts: string[]; maps: string[] } { +): { scripts: string[]; maps: string[]; stylesheetMaps: string[] } { const outputs = Object.keys(result.metafile?.outputs ?? {}).map((file) => resolve(base, file)); + const scripts = outputs.filter((file) => /\.[cm]?js$/.test(file)); + const owned = new Set(scripts); return { - scripts: outputs.filter((file) => /\.[cm]?js$/.test(file)), - maps: outputs.filter((file) => file.endsWith('.map')), + scripts, + // Only the maps of the build's own SCRIPTS are named to the CLI: it skips a `.css.map` when scanning a + // directory, but a stylesheet map named as an explicit path has no debug-id and fails the whole call. + maps: outputs.filter((file) => file.endsWith('.map') && owned.has(file.slice(0, -4))), + // Deleted with the rest after a confirmed upload (they embed the source too), never sent. + stylesheetMaps: outputs.filter((file) => file.endsWith('.css.map')), }; } @@ -511,6 +517,9 @@ export const bugseeUnpluginFactory: UnpluginFactory { if (!resolved.enabled) { From 1e86f5bef77dcf566056e902d25978baa9132b72 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 11 Nov 2026 19:57:38 +0500 Subject: [PATCH 12/12] fix(bundler-plugin-core): esbuild JS output that cannot be uploaded must not pass silently A result with no metafile (another plugin turned it off) or maps for outputs inject does not stamp (outExtension .bundle.jsx) now fail under failOnError and are a notice otherwise; a stylesheet-only build stays a quiet no-op. Real-build tests for both shapes; design and usage docs updated. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01WeiJxSMPCqs6TBDKuGw9TG --- docs/design/source-maps.md | 15 ++-- docs/source-maps-usage.md | 4 +- .../src/plugin.esbuild-rspack.test.ts | 32 ++++++- .../src/plugin.real-build.test.ts | 86 +++++++++++++++++++ packages/bundler-plugin-core/src/plugin.ts | 44 +++++++--- 5 files changed, 162 insertions(+), 19 deletions(-) diff --git a/docs/design/source-maps.md b/docs/design/source-maps.md index 25a1a912b..b9cf58a33 100644 --- a/docs/design/source-maps.md +++ b/docs/design/source-maps.md @@ -133,13 +133,18 @@ unset, and says so when it is `false`) and Rspack `afterEmit`, each calling (an SRI build is refused, not stamped). They do **not** cover **Angular**: its builder does not accept esbuild plugins, so Angular uses the documented CLI post-build recipe (`docs/source-maps-usage.md §2`). Next.js on webpack uses the webpack plugin. Bun, tsup and `tsc`/`swc` stay CLI-post-build (tsup via `onSuccess`). -esbuild builds work on **per-build file lists**: the plugin sets `metafile: true`, takes the build's own `.js`/`.mjs`/ -`.cjs` and `.map` outputs from `result.metafile` in `onEnd`, and runs `sourcemaps inject ` then -`debug-files upload ` (200 paths per CLI call), deleting exactly those maps after a confirmed upload. +esbuild builds work on **per-build file lists**: the plugin sets `metafile: true` and, in `onEnd`, takes the build's own +outputs from `result.metafile`: the `.js`/`.mjs`/`.cjs` scripts and the maps OF THOSE SCRIPTS. It runs +`sourcemaps inject ` then `debug-files upload ` (200 paths per CLI call). Stylesheet +maps (`.css.map`) are withheld from the CLI (named as explicit paths they have no debug-id and fail the whole call) and +are deleted together with the script maps, only after a confirmed upload. Deleting is limited to exactly those files. Invariants: a build only touches files it wrote, so nothing is deleted without being uploaded, nothing is uploaded under another build's options, nested/concurrent builds never wait for each other, and there is no per-directory -state (watch mode needs none). Under `failOnError` a build with no `.map` among its own outputs fails. Build -registration reads only the build's own bundles. (An earlier design serialised and retried uploads per directory; +state (watch mode needs none). A build that emits JavaScript the plugin cannot upload must not pass silently: under +`failOnError` it fails, otherwise it is a notice (once per message). That covers a build with scripts but no script map +(`sourcemap: 'inline'`/`false`), a result with no metafile (another plugin turned it off), and maps whose bundle has an +extension `inject` does not stamp (`outExtension: '.bundle.jsx'`). A stylesheet-only build (metafile present, no +scripts, no stray maps) is a quiet no-op. Build registration reads only the build's own bundles. (An earlier design serialised and retried uploads per directory; four review rounds each found a new race in it, and per-build file lists remove the whole class.) Rspack/webpack keep the directory-wide `afterEmit` path, whose delete step is limited to the maps that existed when the upload started and fails closed if they cannot be listed; a Rspack `MultiCompiler` whose compilers share one `output.path` diff --git a/docs/source-maps-usage.md b/docs/source-maps-usage.md index 1c29ffdfb..05f003568 100644 --- a/docs/source-maps-usage.md +++ b/docs/source-maps-usage.md @@ -40,7 +40,9 @@ touches files it wrote: nothing is deleted without having been uploaded, nothing options or another plugin instance's, builds sharing an output directory (an ESM + CJS pair, a worker sub-build, two plugin instances) never wait for or affect each other, and watch mode keeps no state between rebuilds. Under `failOnError`, a build whose own outputs contain no `.map` (for example `sourcemap: 'inline'`) fails, judged on that -build alone; without `failOnError` it is a notice. A stylesheet-only build is a quiet no-op, and `.css.map` files are +build alone; without `failOnError` it is a notice. The same goes for a build whose result carries no metafile (another +plugin set `metafile: false`) and for maps of outputs that are not `.js`/`.mjs`/`.cjs` (an `outExtension` such as +`.bundle.jsx`, which the CLI does not stamp). A stylesheet-only build is a quiet no-op, and `.css.map` files are never sent (they are deleted with the script maps after a successful upload). The upload never walks the output directory (the one read-only exception is the Subresource-Integrity check, which looks at the `.html` files under it). `outfile` and `outdir` behave alike, wherever they point. diff --git a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts index e26b6ca13..931edd822 100644 --- a/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts +++ b/packages/bundler-plugin-core/src/plugin.esbuild-rspack.test.ts @@ -191,16 +191,44 @@ describe("esbuild: upload of the build's own files at the end of the build", () expect(notices.filter((m) => m.includes('emitted no .map files'))).toHaveLength(1); }); - it('a build with no scripts at all (stylesheet-only, or no metafile) is a quiet no-op, even under failOnError', async () => { + it('a stylesheet-only build (metafile present, no scripts) is a quiet no-op, even under failOnError', async () => { const notices: string[] = []; const run = esbuildRun( { appToken: 'tok', failOnError: true, onNotice: (m) => notices.push(m) }, { outdir: 'dist' }, ); await run.end(outputsOf('dist/only.css', 'dist/only.css.map')); + expect(uploadSpy).not.toHaveBeenCalled(); + expect(notices.filter((m) => m.includes('esbuild'))).toEqual([]); + }); + + it('no metafile at all (another plugin turned it off) fails under failOnError, else one notice per build', async () => { + await expect( + esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: 'dist' }).end({ errors: [] }), + ).rejects.toThrow(/no metafile/); + const notices: string[] = []; + const run = esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outdir: 'dist' }, + ); await run.end({ errors: [] }); + await run.end({ errors: [] }); + expect(uploadSpy).not.toHaveBeenCalled(); + expect(notices.filter((m) => m.includes('no metafile'))).toHaveLength(1); + }); + + it('maps without a recognised script (outExtension .bundle.jsx) are the same misconfiguration', async () => { + const jsx = outputsOf('dist/index.bundle.jsx', 'dist/index.bundle.jsx.map'); + await expect( + esbuildRun({ appToken: 'tok', failOnError: true }, { outdir: 'dist' }).end(jsx), + ).rejects.toThrow(/unrecognised|\.js, \.mjs or \.cjs/); + const notices: string[] = []; + await esbuildRun( + { appToken: 'tok', onNotice: (m) => notices.push(m) }, + { outdir: 'dist' }, + ).end(jsx); expect(uploadSpy).not.toHaveBeenCalled(); - expect(notices.filter((m) => m.includes('emitted no .map files'))).toEqual([]); + expect(notices.some((m) => m.includes('.js, .mjs or .cjs'))).toBe(true); }); it('scripts whose only maps are stylesheet maps still count as no maps', async () => { diff --git a/packages/bundler-plugin-core/src/plugin.real-build.test.ts b/packages/bundler-plugin-core/src/plugin.real-build.test.ts index 6bb9464ba..dc70717cc 100644 --- a/packages/bundler-plugin-core/src/plugin.real-build.test.ts +++ b/packages/bundler-plugin-core/src/plugin.real-build.test.ts @@ -675,3 +675,89 @@ describeReal('builds that emit stylesheet maps (.css.map)', () => { } }); }); + +describeReal( + 'a build with JS output the plugin cannot upload must not pass silently under failOnError', + () => { + const run = (name: string, options: object, more: object) => { + const app = makeApp(name); + return { + app, + build: esbuild({ + entryPoints: [app.entry], + bundle: true, + outdir: app.out, + absWorkingDir: app.dir, + sourcemap: 'external', + logLevel: 'silent', + plugins: [bugseeEsbuildPlugin({ ...pluginOptions, endpoint, ...options })], + ...more, + }), + }; + }; + + it('another plugin turning the metafile off', async () => { + const turnOff: Plugin = { + name: 'metafile-off', + setup(b) { + b.initialOptions.metafile = false; + }, + }; + const before = requests.length; + const strict = run('esbuild-nometa-strict', { failOnError: true }, {}); + // the second plugin comes AFTER ours, so it wins + strict.build.catch(() => undefined); + await expect( + esbuild({ + entryPoints: [strict.app.entry], + bundle: true, + outdir: strict.app.out, + absWorkingDir: strict.app.dir, + sourcemap: 'external', + logLevel: 'silent', + plugins: [ + bugseeEsbuildPlugin({ ...pluginOptions, endpoint, failOnError: true }), + turnOff, + ], + }), + ).rejects.toThrow(); + const notices: string[] = []; + const lax = makeApp('esbuild-nometa-lax'); + await esbuild({ + entryPoints: [lax.entry], + bundle: true, + outdir: lax.out, + absWorkingDir: lax.dir, + sourcemap: 'external', + logLevel: 'silent', + plugins: [ + bugseeEsbuildPlugin({ + ...pluginOptions, + endpoint, + failOnError: false, + onNotice: (m) => notices.push(m), + }), + turnOff, + ], + }); + expect(requests.length).toBe(before); + expect(notices.some((m) => m.includes('no metafile'))).toBe(true); + }); + + it('outExtension .bundle.jsx (an extension inject does not stamp)', async () => { + const before = requests.length; + await expect( + run('esbuild-jsx-strict', { failOnError: true }, { outExtension: { '.js': '.bundle.jsx' } }) + .build, + ).rejects.toThrow(); + const notices: string[] = []; + await run( + 'esbuild-jsx-lax', + { failOnError: false, onNotice: (m: string) => notices.push(m) }, + { outExtension: { '.js': '.bundle.jsx' } }, + ).build; + expect(requests.length).toBe(before); + expect(notices.some((m) => m.includes('.js, .mjs or .cjs'))).toBe(true); + }); + }, +); diff --git a/packages/bundler-plugin-core/src/plugin.ts b/packages/bundler-plugin-core/src/plugin.ts index fe3fd2970..90dd9f5b7 100644 --- a/packages/bundler-plugin-core/src/plugin.ts +++ b/packages/bundler-plugin-core/src/plugin.ts @@ -219,7 +219,7 @@ interface EsbuildEndResult { function esbuildOwnFiles( result: EsbuildEndResult, base: string, -): { scripts: string[]; maps: string[]; stylesheetMaps: string[] } { +): { scripts: string[]; maps: string[]; stylesheetMaps: string[]; strayMaps: string[] } { const outputs = Object.keys(result.metafile?.outputs ?? {}).map((file) => resolve(base, file)); const scripts = outputs.filter((file) => /\.[cm]?js$/.test(file)); const owned = new Set(scripts); @@ -230,6 +230,12 @@ function esbuildOwnFiles( maps: outputs.filter((file) => file.endsWith('.map') && owned.has(file.slice(0, -4))), // Deleted with the rest after a confirmed upload (they embed the source too), never sent. stylesheetMaps: outputs.filter((file) => file.endsWith('.css.map')), + // Maps whose bundle is not a recognised script (an `outExtension` like `.bundle.jsx`, which `inject` does not + // stamp): the build emitted maps the plugin cannot upload, which is not the same as having none. + strayMaps: outputs.filter( + (file) => + file.endsWith('.map') && !file.endsWith('.css.map') && !owned.has(file.slice(0, -4)), + ), }; } @@ -516,22 +522,38 @@ export const bugseeUnpluginFactory: UnpluginFactory { if (resolved.failOnError) { throw new Error(message); } say(message); + }; + if (result.metafile === undefined) { + // The plugin asks for it, but another plugin (or esbuild itself) may have turned it off. + problem( + `esbuild build into ${outDir} returned no metafile (did another plugin set metafile: false?), so the build's own files are unknown and nothing was uploaded.`, + ); + return; + } + const files = esbuildOwnFiles(result, esbuildBase(build.initialOptions)); + if (files.scripts.length === 0) { + if (files.strayMaps.length > 0) { + problem( + `esbuild build into ${outDir} emitted maps for outputs that are not .js, .mjs or .cjs (outExtension?), which bugsee-cli cannot stamp, so nothing was uploaded.`, + ); + } + return; // otherwise a stylesheet-only build: nothing to symbolicate + } + if (files.maps.length === 0) { + problem( + `esbuild build into ${outDir} emitted no .map files, so there is nothing to upload (sourcemap: 'inline' or false?). Use sourcemap: 'external' or 'linked'.`, + ); return; } - await runPluginUpload(forOutput(outDir), outDir, { bundler: {}, files }); + const { strayMaps: _stray, ...own } = files; + await runPluginUpload(forOutput(outDir), outDir, { bundler: {}, files: own }); }); }, },