bugwatch-cli 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -129,7 +129,10 @@ Options:
129
129
  | `urlPrefix` | `"~/"` | See [File names](#file-names) |
130
130
  | `apiUrl` | `BUGWATCH_API_URL`, else Bugwatch's hosted API | |
131
131
  | `deleteAfterUpload` | `true` | Delete the `.map` files from the build output after a fully successful upload |
132
+ | `deleteOld` | `false` | Delete the project's older source maps in Bugwatch after a fully successful upload. See [Keep only the latest deploy](#keep-only-the-latest-deploy) |
132
133
  | `failOnError` | `false` | Fail `vite build` when an upload fails (default: log the error and continue) |
134
+ | `commits` | `true` | 0.7.0: after uploading, send the release's commit (see [Release commits](#release-commits)); nothing is sent when no commit is found, and a failure only warns |
135
+ | `commit` | detected | The commit to send: else `GITHUB_SHA`, `VERCEL_GIT_COMMIT_SHA`, `CI_COMMIT_SHA`, `COMMIT_REF`, `CF_PAGES_COMMIT_SHA`, `BITBUCKET_COMMIT`, or `git rev-parse HEAD` |
133
136
 
134
137
  The plugin runs only for `vite build` (not the dev server), after the
135
138
  bundle is written, on `build.outDir`. It warns and does nothing when
@@ -153,6 +156,7 @@ npx bugwatch-cli sourcemaps upload dist --release 1.4.2 --delete-after-upload
153
156
  | `--token <token>` | Default `BUGWATCH_UPLOAD_TOKEN` (an org CI token, `bwc_…`). Prefer the variable: flags can end up in CI logs |
154
157
  | `--project <id>` | Default `BUGWATCH_PROJECT`. The project id; required with a CI token |
155
158
  | `--delete-after-upload` | Delete the local `.map` files, only after every upload succeeded |
159
+ | `--delete-old` | Delete the project's older source maps in Bugwatch, only after every upload succeeded. See [Keep only the latest deploy](#keep-only-the-latest-deploy) |
156
160
  | `--dry-run` | Print what would be uploaded; no token needed, nothing sent or deleted |
157
161
 
158
162
  It uploads every `*.map` file under `<dir>` (recursively, skipping
@@ -222,6 +226,56 @@ build. A map uploaded for a full URL wins over a `~/` one for the
222
226
  same script. The prefix must start with `~/`, `http://`, or
223
227
  `https://` and end with `/`.
224
228
 
229
+ ## Keep only the latest deploy
230
+
231
+ By default every deploy adds its maps and the older releases' maps stay
232
+ for 90 days, counting toward the plan's storage. With `--delete-old`
233
+ (Vite: `deleteOld: true`) each deploy replaces them:
234
+
235
+ 1. The new maps are uploaded as usual
236
+ 2. Only if every upload succeeded, Bugwatch deletes the project's maps
237
+ of every other release, and of this release the files not in this
238
+ upload (when every deploy reuses one release name, the old hashed
239
+ chunks go)
240
+ 3. If the plan's storage is full, the older releases are deleted
241
+ first and the refused files are sent again
242
+
243
+ ```sh
244
+ npx bugwatch-cli sourcemaps upload dist --release ${GITHUB_SHA} --delete-after-upload --delete-old
245
+ ```
246
+
247
+ - Needs an org CI token (`bwc_…`); upload tokens (`bwu_…`) cannot delete
248
+ - Errors already in Bugwatch keep their readable stack traces. New
249
+ errors from an older release (e.g. a browser tab opened before the
250
+ deploy) are no longer mapped
251
+ - If the upload fails, nothing is deleted. If only the delete fails,
252
+ the command warns and still exits 0: the new maps are stored
253
+ - Run it on deploys of one environment only: a staging deploy with
254
+ `--delete-old` deletes production's maps of the same project
255
+
256
+ ## Release commits
257
+
258
+ Since 0.7.0. Tell Bugwatch which commit a release was built from, and it
259
+ reads the commits since the previous release from GitHub: issues then
260
+ show **suspect commits** (commits of the release that changed a file in
261
+ the error's stack), and stack frames link to the exact line of that
262
+ commit on GitHub. The project needs a GitHub repository in Bugwatch
263
+ (Settings → General → Repository; projects added from GitHub have one).
264
+
265
+ ```sh
266
+ npx bugwatch-cli release commits --release "$RELEASE"
267
+ ```
268
+
269
+ The commit is detected from CI variables (`GITHUB_SHA`,
270
+ `VERCEL_GIT_COMMIT_SHA`, `CI_COMMIT_SHA`, `COMMIT_REF`,
271
+ `CF_PAGES_COMMIT_SHA`, `BITBUCKET_COMMIT`) or `git rev-parse HEAD`; pass
272
+ `--commit <sha>` to choose it, and `--previous-commit <sha>` when the
273
+ release's commits should start somewhere other than the previous
274
+ release's commit. Same token and project options as the upload. The
275
+ Vite plugin does this after uploading (option `commits`). When the
276
+ release version is itself the commit SHA (e.g. `${{ github.sha }}`),
277
+ Bugwatch finds the commit without this step.
278
+
225
279
  ## CI example (GitHub Actions)
226
280
 
227
281
  ```yaml
@@ -233,7 +287,8 @@ same script. The prefix must start with `~/`, `http://`, or
233
287
  BUGWATCH_UPLOAD_TOKEN: ${{ secrets.BUGWATCH_UPLOAD_TOKEN }} # an org CI token
234
288
  BUGWATCH_PROJECT: 6735f0c2a1b2c3d4e5f60718 # the project id (not a secret)
235
289
  # Without the Vite plugin:
236
- # - run: npx bugwatch-cli sourcemaps upload dist --release ${{ github.sha }} --delete-after-upload
290
+ # - run: npx bugwatch-cli sourcemaps upload dist --release ${{ github.sha }} --delete-after-upload --delete-old
291
+ # - run: npx bugwatch-cli release commits --release ${{ github.sha }}
237
292
  # env:
238
293
  # BUGWATCH_UPLOAD_TOKEN: ${{ secrets.BUGWATCH_UPLOAD_TOKEN }}
239
294
  # BUGWATCH_PROJECT: 6735f0c2a1b2c3d4e5f60718
@@ -244,8 +299,9 @@ same script. The prefix must start with `~/`, `http://`, or
244
299
  - One map: at most 20 MB
245
300
  - 500 maps per release
246
301
  - Storage per project by the organization's plan: Free 50 MB, Pro
247
- 2 GB, counted as the `.map` files' sizes (`409` when full; delete
248
- older releases' maps in the dashboard or upgrade)
302
+ 2 GB, counted as the `.map` files' sizes (`409` when full; use
303
+ `--delete-old`, delete older releases' maps in the dashboard, or
304
+ upgrade)
249
305
  - 600 uploads per 10 minutes per token
250
306
  - A CI token uploads only to the projects it covers (`403` for
251
307
  another project of the organization, `404` for any other project)
@@ -2,7 +2,7 @@ import {
2
2
  DEFAULT_API_URL,
3
3
  UsageError,
4
4
  VERSION
5
- } from "./chunk-I5JOKYXA.js";
5
+ } from "./chunk-NKLMUZBK.js";
6
6
 
7
7
  // src/init.ts
8
8
  import { execFile, spawn } from "child_process";
@@ -13,20 +13,30 @@ function formatResult(result) {
13
13
  }
14
14
  return `${label} ${result.name} (${detail})`;
15
15
  }
16
- function formatSummary(summary, { dryRun, release, files }) {
16
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
17
+ function formatPrune(summary, deleteOld) {
18
+ if (!deleteOld) return "";
19
+ const first = summary.prunedFirst ? " (storage was full, so older releases were deleted first and the rest retried)" : "";
20
+ if (summary.pruned != null) return ` Deleted ${plural(summary.pruned, "old source map")} on the server${first}.`;
21
+ if (summary.pruneError) return ` Old source maps were not deleted: ${summary.pruneError}.`;
22
+ return " Old source maps were kept because an upload failed.";
23
+ }
24
+ function formatSummary(summary, { dryRun, release, files, deleteOld = false }) {
17
25
  const css = summary.skipped > 0 ? ` Skipped ${summary.skipped} CSS map${summary.skipped === 1 ? "" : "s"}.` : "";
18
26
  if (dryRun) {
19
27
  const skipped = summary.failed > 0 ? ` (${summary.failed} would fail)` : "";
20
- return `Dry run for release ${release}: ${files} source map${files === 1 ? "" : "s"} found${skipped}; nothing was uploaded.${css}`;
28
+ const old = deleteOld ? " With --delete-old, the project's source maps of other releases (and this release's other files) would then be deleted." : "";
29
+ return `Dry run for release ${release}: ${files} source map${files === 1 ? "" : "s"} found${skipped}; nothing was uploaded.${css}${old}`;
21
30
  }
22
31
  const notSent = summary.notSent > 0 ? ` ${summary.notSent} not sent.` : "";
23
32
  const stopped = summary.stopped ? ` Stopped: ${summary.stopped}` : "";
24
33
  const line = `Release ${release}: ${summary.uploaded} uploaded, ${summary.replaced} replaced, ${summary.unchanged} unchanged, ${summary.failed} failed.${notSent}${css}${stopped}`;
25
- return summary.deleted > 0 ? `${line} Deleted ${summary.deleted} local .map file${summary.deleted === 1 ? "" : "s"}.` : line;
34
+ const local = summary.deleted > 0 ? ` Deleted ${plural(summary.deleted, "local .map file")}.` : "";
35
+ return `${line}${local}${formatPrune(summary, deleteOld)}`;
26
36
  }
27
37
 
28
38
  // src/version.ts
29
- var VERSION = "0.5.3";
39
+ var VERSION = "0.7.0";
30
40
 
31
41
  // src/upload.ts
32
42
  import { open, readdir, readFile, stat, unlink } from "fs/promises";
@@ -223,6 +233,49 @@ async function uploadFile(context, file, name, body, chunkSize) {
223
233
  await context.sleep(delayMs);
224
234
  }
225
235
  }
236
+ async function pruneOld(context, keepNames) {
237
+ const url = `${context.apiUrl}/api/projects/${encodeURIComponent(context.project ?? "")}/releases/${encodeURIComponent(context.release)}/sourcemaps/prune`;
238
+ const body = JSON.stringify(keepNames ? { keepNames } : {});
239
+ for (let attempt = 0; ; attempt += 1) {
240
+ let reason;
241
+ let response = null;
242
+ try {
243
+ response = await context.fetch(url, {
244
+ method: "POST",
245
+ headers: {
246
+ authorization: `Bearer ${context.token}`,
247
+ "content-type": "application/json",
248
+ "user-agent": `bugwatch-cli/${VERSION}`
249
+ },
250
+ body
251
+ });
252
+ } catch (error) {
253
+ reason = error instanceof Error ? error.message : "network error";
254
+ }
255
+ if (response) {
256
+ if (response.ok) {
257
+ try {
258
+ const deleted = (await response.json()).data?.deleted;
259
+ return { deleted: typeof deleted === "number" ? deleted : 0 };
260
+ } catch {
261
+ return { deleted: 0 };
262
+ }
263
+ }
264
+ const { message } = await errorOf(response);
265
+ if (response.status === 404 && message !== "Project not found") {
266
+ return { error: "This Bugwatch server cannot delete old source maps yet (HTTP 404)" };
267
+ }
268
+ if (response.status !== 429 && response.status < 500) return { error: `${response.status} ${message}` };
269
+ reason = `${response.status} ${message}`;
270
+ }
271
+ if (attempt === MAX_RETRIES) return { error: reason };
272
+ const retry = attempt + 1;
273
+ const fromHeader = response?.status === 429 ? retryAfterMs(response.headers.get("retry-after")) : null;
274
+ const delayMs = Math.min(fromHeader ?? backoffMs(retry), MAX_RETRY_DELAY_MS);
275
+ context.onRetry?.({ file: "(delete old source maps)", attempt: retry, delayMs, reason });
276
+ await context.sleep(delayMs);
277
+ }
278
+ }
226
279
  async function mapLimit(items, limit, worker) {
227
280
  const results = new Array(items.length);
228
281
  let next = 0;
@@ -250,6 +303,9 @@ async function uploadSourceMaps(options) {
250
303
  }
251
304
  const projectError = projectProblem(options.project);
252
305
  if (projectError) throw new UsageError(projectError);
306
+ if (options.deleteOld && !options.dryRun && !isCiToken(options.token)) {
307
+ throw new UsageError("Deleting old source maps needs an org CI token (bwc_\u2026); upload tokens (bwu_\u2026) cannot delete");
308
+ }
253
309
  if (!options.dryRun && isCiToken(options.token) && !options.project) {
254
310
  throw new UsageError(
255
311
  "A CI token (bwc_\u2026) needs the project id: set BUGWATCH_PROJECT (from the project's Source maps page)"
@@ -277,7 +333,7 @@ async function uploadSourceMaps(options) {
277
333
  onRetry: options.onRetry
278
334
  };
279
335
  let stopped = null;
280
- const results = await mapLimit(uploads, CONCURRENCY, async ({ map: file, name, script }) => {
336
+ const send = async ({ map: file, name, script }) => {
281
337
  const path = join(dir, file);
282
338
  const { size } = await stat(path);
283
339
  let result;
@@ -298,7 +354,28 @@ async function uploadSourceMaps(options) {
298
354
  }
299
355
  options.onResult?.(result);
300
356
  return result;
301
- });
357
+ };
358
+ const results = await mapLimit(uploads, CONCURRENCY, send);
359
+ const deleteOld = options.deleteOld === true && !options.dryRun;
360
+ let pruneError = null;
361
+ let prunedFirst = false;
362
+ let pruned = 0;
363
+ const refusedForSpace = (result) => result.outcome === "not-sent" || result.code === "SOURCEMAP_PLAN_LIMIT";
364
+ if (deleteOld && results.some((r) => r.code === "SOURCEMAP_PLAN_LIMIT")) {
365
+ const first = await pruneOld(context);
366
+ if ("error" in first) {
367
+ pruneError = first.error;
368
+ } else {
369
+ prunedFirst = true;
370
+ pruned += first.deleted;
371
+ stopped = null;
372
+ const again = uploads.map((upload, index) => ({ upload, index })).filter(({ index }) => refusedForSpace(results[index]));
373
+ const retried = await mapLimit(again, CONCURRENCY, ({ upload }) => send(upload));
374
+ again.forEach(({ index }, i) => {
375
+ results[index] = retried[i];
376
+ });
377
+ }
378
+ }
302
379
  const count = (outcome) => results.filter((r) => r.outcome === outcome).length;
303
380
  const summary = {
304
381
  skipped: files.filter(isCssMap).length,
@@ -308,8 +385,17 @@ async function uploadSourceMaps(options) {
308
385
  failed: count("failed"),
309
386
  notSent: count("not-sent"),
310
387
  stopped,
311
- deleted: 0
388
+ deleted: 0,
389
+ ...options.deleteOld ? { pruned: null, pruneError, prunedFirst } : {}
312
390
  };
391
+ if (deleteOld && pruneError === null && summary.failed === 0 && summary.notSent === 0) {
392
+ const keepNames = [...new Set(uploads.map((upload) => upload.name))];
393
+ const done = await pruneOld(context, keepNames);
394
+ if ("error" in done) summary.pruneError = done.error;
395
+ else summary.pruned = pruned + done.deleted;
396
+ } else if (prunedFirst) {
397
+ summary.pruned = pruned;
398
+ }
313
399
  if (options.deleteAfterUpload && !options.dryRun && summary.failed === 0 && summary.notSent === 0) {
314
400
  await Promise.all(files.map((file) => unlink(join(dir, file))));
315
401
  summary.deleted = files.length;
@@ -317,6 +403,65 @@ async function uploadSourceMaps(options) {
317
403
  return { results, summary };
318
404
  }
319
405
 
406
+ // src/commits.ts
407
+ import { execFileSync } from "child_process";
408
+ var COMMIT_SHA = /^[0-9a-f]{7,40}$/i;
409
+ var COMMIT_ENV_VARS = ["GITHUB_SHA", "VERCEL_GIT_COMMIT_SHA", "CI_COMMIT_SHA", "COMMIT_REF", "CF_PAGES_COMMIT_SHA", "BITBUCKET_COMMIT"];
410
+ function detectCommit(env = process.env, cwd = process.cwd(), git = (dir) => execFileSync("git", ["rev-parse", "HEAD"], { cwd: dir, stdio: ["ignore", "pipe", "ignore"] }).toString()) {
411
+ for (const name of COMMIT_ENV_VARS) {
412
+ const value = env[name]?.trim();
413
+ if (value && COMMIT_SHA.test(value)) return value.toLowerCase();
414
+ }
415
+ try {
416
+ const head = git(cwd).trim();
417
+ return COMMIT_SHA.test(head) ? head.toLowerCase() : null;
418
+ } catch {
419
+ return null;
420
+ }
421
+ }
422
+ async function sendReleaseCommit(options) {
423
+ const releaseError = releaseProblem(options.release);
424
+ if (releaseError) throw new UsageError(releaseError);
425
+ if (!COMMIT_SHA.test(options.commit)) throw new UsageError("The commit must be a SHA (7\u201340 hex characters)");
426
+ if (options.previousCommit !== void 0 && !COMMIT_SHA.test(options.previousCommit)) {
427
+ throw new UsageError("The previous commit must be a SHA (7\u201340 hex characters)");
428
+ }
429
+ if (isCiToken(options.token)) {
430
+ if (!options.project) throw new UsageError("A CI token (bwc_\u2026) needs the project id: set BUGWATCH_PROJECT (or pass --project)");
431
+ const problem = projectProblem(options.project);
432
+ if (problem) throw new UsageError(problem);
433
+ }
434
+ const apiUrl = (options.apiUrl || DEFAULT_API_URL).replace(/\/+$/, "");
435
+ const route = isCiToken(options.token) ? `/api/projects/${encodeURIComponent(options.project)}/releases/${encodeURIComponent(options.release)}/commits` : `/api/releases/${encodeURIComponent(options.release)}/commits`;
436
+ const response = await (options.fetch ?? fetch)(`${apiUrl}${route}`, {
437
+ method: "POST",
438
+ headers: {
439
+ authorization: `Bearer ${options.token}`,
440
+ "content-type": "application/json",
441
+ "user-agent": `bugwatch-cli/${VERSION}`
442
+ },
443
+ body: JSON.stringify({
444
+ commit: options.commit.toLowerCase(),
445
+ ...options.previousCommit ? { previousCommit: options.previousCommit.toLowerCase() } : {}
446
+ })
447
+ });
448
+ let payload = {};
449
+ try {
450
+ payload = await response.json();
451
+ } catch {
452
+ }
453
+ if (!response.ok || !payload.data) {
454
+ if (response.status === 404 && !payload.error) throw new Error("This Bugwatch API does not accept release commits yet (needs backend Step 144)");
455
+ throw new Error(payload.error?.message ?? `HTTP ${response.status}`);
456
+ }
457
+ return payload.data;
458
+ }
459
+ function formatCommitResult(result) {
460
+ const sha = result.commit?.sha.slice(0, 12) ?? "?";
461
+ if (result.commitsStatus === "failed") return `Release ${result.version}: commit ${sha} recorded, but ${result.commitsError ?? "its commits could not be read"}`;
462
+ return `Release ${result.version}: commit ${sha} recorded; Bugwatch is reading its commits from GitHub`;
463
+ }
464
+
320
465
  export {
321
466
  formatBytes,
322
467
  formatResult,
@@ -342,5 +487,10 @@ export {
342
487
  isCssMap,
343
488
  planUploads,
344
489
  sendableMapFile,
345
- uploadSourceMaps
490
+ uploadSourceMaps,
491
+ COMMIT_SHA,
492
+ COMMIT_ENV_VARS,
493
+ detectCommit,
494
+ sendReleaseCommit,
495
+ formatCommitResult
346
496
  };
@@ -1,18 +1,21 @@
1
1
  import {
2
2
  initProject
3
- } from "./chunk-23Q2GI5D.js";
3
+ } from "./chunk-H3LKWUXE.js";
4
4
  import {
5
5
  DEFAULT_API_URL,
6
6
  DEFAULT_URL_PREFIX,
7
7
  UPLOAD_TOKEN_DEPRECATED,
8
8
  UsageError,
9
9
  VERSION,
10
+ detectCommit,
11
+ formatCommitResult,
10
12
  formatResult,
11
13
  formatSummary,
12
14
  isCiToken,
13
15
  isDeprecatedUploadToken,
16
+ sendReleaseCommit,
14
17
  uploadSourceMaps
15
- } from "./chunk-I5JOKYXA.js";
18
+ } from "./chunk-NKLMUZBK.js";
16
19
 
17
20
  // src/main.ts
18
21
  import { parseArgs } from "util";
@@ -34,6 +37,25 @@ Options:
34
37
  -h, --help Show this help
35
38
 
36
39
  Exit codes: 0 done, 1 failed (network, install), 2 usage error.`;
40
+ var COMMITS_USAGE = `Usage: bugwatch-cli release commits --release <version> [options]
41
+
42
+ Tells Bugwatch which commit the release was built from. Bugwatch then reads
43
+ the commits since the previous release from GitHub, for suspect commits on
44
+ issues and links from stack frames to the exact line. The project needs a
45
+ GitHub repository (Bugwatch: Settings \u2192 General \u2192 Repository).
46
+
47
+ Options:
48
+ --release <version> The release the SDK sends (Bugwatch.init({ release })). Required
49
+ --commit <sha> The commit (default: $GITHUB_SHA, $VERCEL_GIT_COMMIT_SHA,
50
+ $CI_COMMIT_SHA, $COMMIT_REF, \u2026 or git rev-parse HEAD)
51
+ --previous-commit <sha> Where the release's commits start (default: the previous
52
+ release's commit in Bugwatch)
53
+ --api-url <url> Bugwatch API (default: $BUGWATCH_API_URL or ${DEFAULT_API_URL})
54
+ --token <token> Org CI token, bwc_\u2026 (default: $BUGWATCH_UPLOAD_TOKEN; prefer the variable)
55
+ --project <id> Project id, required with a CI token (default: $BUGWATCH_PROJECT)
56
+ -h, --help Show this help
57
+
58
+ Exit codes: 0 recorded, 1 failed (network, refused), 2 usage error.`;
37
59
  var USAGE = `Usage: bugwatch-cli sourcemaps upload <dir> --release <version> [options]
38
60
 
39
61
  Uploads every .map file under <dir> to Bugwatch for the release.
@@ -47,13 +69,17 @@ Options:
47
69
  --project <id> Project id, required with a CI token (default: $BUGWATCH_PROJECT;
48
70
  shown on the project's Source maps page)
49
71
  --delete-after-upload Delete the local .map files after every upload succeeded
72
+ --delete-old After every upload succeeded, delete the project's older source
73
+ maps in Bugwatch (other releases, and this release's files not in
74
+ this upload). Needs a CI token
50
75
  --dry-run List what would be uploaded; uploads and deletes nothing
51
76
  -h, --help Show this help
52
77
  -v, --version Show the version
53
78
 
54
79
  Exit codes: 0 all uploaded, 1 an upload failed, 2 usage error.
55
80
 
56
- Set up a new project from GitHub: bugwatch-cli init --setup <code> (see bugwatch-cli init --help).`;
81
+ Set up a new project from GitHub: bugwatch-cli init --setup <code> (see bugwatch-cli init --help).
82
+ Send the release's commit: bugwatch-cli release commits --release <version> (see bugwatch-cli release commits --help).`;
57
83
  async function main(argv, env = process.env, out = (line) => process.stdout.write(`${line}
58
84
  `), err = (line) => process.stderr.write(`${line}
59
85
  `)) {
@@ -69,11 +95,14 @@ async function main(argv, env = process.env, out = (line) => process.stdout.writ
69
95
  token: { type: "string" },
70
96
  project: { type: "string" },
71
97
  "delete-after-upload": { type: "boolean" },
98
+ "delete-old": { type: "boolean" },
72
99
  "dry-run": { type: "boolean" },
73
100
  setup: { type: "string" },
74
101
  entry: { type: "string" },
75
102
  "skip-install": { type: "boolean" },
76
103
  "skip-server": { type: "boolean" },
104
+ commit: { type: "string" },
105
+ "previous-commit": { type: "string" },
77
106
  help: { type: "boolean", short: "h" },
78
107
  version: { type: "boolean", short: "v" }
79
108
  }
@@ -115,6 +144,46 @@ ${USAGE}`);
115
144
  return error instanceof UsageError ? 2 : 1;
116
145
  }
117
146
  }
147
+ if (positionals[0] === "release") {
148
+ if (values.help) {
149
+ out(COMMITS_USAGE);
150
+ return 0;
151
+ }
152
+ if (positionals[1] !== "commits" || positionals.length > 2) {
153
+ err(COMMITS_USAGE);
154
+ return 2;
155
+ }
156
+ if (!values.release) {
157
+ err("Error: A release is required (--release)");
158
+ return 2;
159
+ }
160
+ const token2 = values.token || env.BUGWATCH_UPLOAD_TOKEN || void 0;
161
+ if (!token2) {
162
+ err("Error: A token is required: set BUGWATCH_UPLOAD_TOKEN (or pass --token)");
163
+ return 2;
164
+ }
165
+ const commit = values.commit || detectCommit(env);
166
+ if (!commit) {
167
+ err("Error: No commit found: pass --commit <sha> (or set GITHUB_SHA), or run inside the git checkout");
168
+ return 2;
169
+ }
170
+ const project2 = values.project || env.BUGWATCH_PROJECT || void 0;
171
+ try {
172
+ const result = await sendReleaseCommit({
173
+ release: values.release,
174
+ commit,
175
+ ...values["previous-commit"] ? { previousCommit: values["previous-commit"] } : {},
176
+ token: token2,
177
+ ...project2 ? { project: project2 } : {},
178
+ apiUrl: values["api-url"] || env.BUGWATCH_API_URL || DEFAULT_API_URL
179
+ });
180
+ (result.commitsStatus === "failed" ? err : out)(formatCommitResult(result));
181
+ return 0;
182
+ } catch (error) {
183
+ err(`Error: ${error instanceof Error ? error.message : String(error)}`);
184
+ return error instanceof UsageError ? 2 : 1;
185
+ }
186
+ }
118
187
  if (values.help) {
119
188
  out(USAGE);
120
189
  return 0;
@@ -140,6 +209,11 @@ ${USAGE}`);
140
209
  err("Error: A CI token (bwc_\u2026) needs the project id: set BUGWATCH_PROJECT (or pass --project)");
141
210
  return 2;
142
211
  }
212
+ const deleteOld = values["delete-old"] === true;
213
+ if (!dryRun && deleteOld && !isCiToken(token)) {
214
+ err("Error: --delete-old needs an org CI token (bwc_\u2026); upload tokens (bwu_\u2026) cannot delete source maps");
215
+ return 2;
216
+ }
143
217
  if (!dryRun && isDeprecatedUploadToken(token)) err(`Note: ${UPLOAD_TOKEN_DEPRECATED}`);
144
218
  try {
145
219
  const { results, summary } = await uploadSourceMaps({
@@ -150,12 +224,14 @@ ${USAGE}`);
150
224
  urlPrefix: values["url-prefix"] ?? DEFAULT_URL_PREFIX,
151
225
  apiUrl,
152
226
  deleteAfterUpload: values["delete-after-upload"] === true,
227
+ deleteOld,
153
228
  dryRun,
154
229
  onResult: (result) => (result.outcome === "failed" ? err : out)(formatResult(result)),
155
230
  onRetry: ({ file, attempt, delayMs, reason }) => err(`retry ${file} (attempt ${attempt + 1}, in ${Math.round(delayMs / 100) / 10} s): ${reason}`)
156
231
  });
157
232
  out("");
158
- out(formatSummary(summary, { dryRun, release: values.release, files: results.length }));
233
+ out(formatSummary(summary, { dryRun, release: values.release, files: results.length, deleteOld }));
234
+ if (summary.pruneError) err(`Warning: old source maps were not deleted: ${summary.pruneError}`);
159
235
  if ((summary.failed > 0 || summary.notSent > 0) && values["delete-after-upload"]) {
160
236
  out("Kept the local .map files because an upload failed.");
161
237
  }
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  main
4
- } from "./chunk-CF3QZWJS.js";
5
- import "./chunk-23Q2GI5D.js";
6
- import "./chunk-I5JOKYXA.js";
4
+ } from "./chunk-T4GRUZAC.js";
5
+ import "./chunk-H3LKWUXE.js";
6
+ import "./chunk-NKLMUZBK.js";
7
7
 
8
8
  // src/cli.ts
9
9
  main(process.argv.slice(2)).then((code) => {
package/dist/index.d.ts CHANGED
@@ -50,6 +50,17 @@ interface UploadSummary {
50
50
  stopped: string | null;
51
51
  /** Local `.map` files deleted after a fully successful upload. */
52
52
  deleted: number;
53
+ /**
54
+ * `--delete-old`: the project's older maps deleted on the server (other
55
+ * releases, and this release's names not sent in this run), or null when
56
+ * nothing was pruned (dry run, an upload failed, or the prune failed).
57
+ * Only present with `deleteOld`, like the two fields below.
58
+ */
59
+ pruned?: number | null;
60
+ /** `--delete-old`: why deleting the older maps failed (the uploads still count), or null. */
61
+ pruneError?: string | null;
62
+ /** `--delete-old`: the plan's storage was full, so older releases were deleted first and the rest retried. */
63
+ prunedFirst?: boolean;
53
64
  }
54
65
  interface UploadReport {
55
66
  results: FileResult[];
@@ -69,6 +80,13 @@ interface UploadOptions {
69
80
  apiUrl?: string;
70
81
  /** Delete the local `.map` files, only when every upload succeeded. */
71
82
  deleteAfterUpload?: boolean;
83
+ /**
84
+ * After every upload succeeded, delete the project's other source maps on
85
+ * the server: every other release's, and this release's names not uploaded
86
+ * in this run. If the plan's storage is full, older releases are deleted
87
+ * first and the rest retried. Needs a CI token (`bwc_…`).
88
+ */
89
+ deleteOld?: boolean;
72
90
  /** List what would be uploaded; no network, nothing deleted. */
73
91
  dryRun?: boolean;
74
92
  /** Called once per file as it finishes. */
@@ -133,10 +151,11 @@ declare function uploadSourceMaps(options: UploadOptions): Promise<UploadReport>
133
151
  declare function formatBytes(bytes: number): string;
134
152
  /** `uploaded ~/assets/index.js (assets/index.js.map, 1.8 MB)`, or the reason it failed. */
135
153
  declare function formatResult(result: FileResult): string;
136
- declare function formatSummary(summary: UploadSummary, { dryRun, release, files }: {
154
+ declare function formatSummary(summary: UploadSummary, { dryRun, release, files, deleteOld }: {
137
155
  dryRun: boolean;
138
156
  release: string;
139
157
  files: number;
158
+ deleteOld?: boolean;
140
159
  }): string;
141
160
 
142
161
  /**
@@ -218,7 +237,45 @@ declare function addImport(text: string, spec: string): string | null;
218
237
  /** Runs `init`. Throws UsageError for user mistakes, Error for failures. */
219
238
  declare function initProject(options: InitOptions): Promise<InitReport>;
220
239
 
240
+ /**
241
+ * Release commits (backend Step 144): tell Bugwatch which commit a release
242
+ * was built from. Bugwatch then reads the commits since the previous release
243
+ * from GitHub (through its GitHub App), for suspect commits and code links.
244
+ */
245
+ /** A commit SHA as Bugwatch accepts it (7–40 hex). */
246
+ declare const COMMIT_SHA: RegExp;
247
+ /** CI variables that hold the commit being built, in order. */
248
+ declare const COMMIT_ENV_VARS: readonly ["GITHUB_SHA", "VERCEL_GIT_COMMIT_SHA", "CI_COMMIT_SHA", "COMMIT_REF", "CF_PAGES_COMMIT_SHA", "BITBUCKET_COMMIT"];
249
+ /**
250
+ * The commit to send: the first CI variable that holds a SHA, else `git
251
+ * rev-parse HEAD` in `cwd`; null when neither works (not a git checkout).
252
+ */
253
+ declare function detectCommit(env?: NodeJS.ProcessEnv, cwd?: string, git?: (cwd: string) => string): string | null;
254
+ interface ReleaseCommitOptions {
255
+ release: string;
256
+ commit: string;
257
+ previousCommit?: string;
258
+ token: string;
259
+ /** Required with a CI token (`bwc_…`). */
260
+ project?: string;
261
+ apiUrl?: string;
262
+ fetch?: typeof fetch;
263
+ }
264
+ interface ReleaseCommitResult {
265
+ version: string;
266
+ commit: {
267
+ sha: string;
268
+ url: string | null;
269
+ } | null;
270
+ commitsStatus: "none" | "pending" | "ready" | "failed";
271
+ commitsError: string | null;
272
+ }
273
+ /** Throws a `UsageError` for bad input, an `Error` with the server's message when Bugwatch refuses. */
274
+ declare function sendReleaseCommit(options: ReleaseCommitOptions): Promise<ReleaseCommitResult>;
275
+ /** One line for the result. */
276
+ declare function formatCommitResult(result: ReleaseCommitResult): string;
277
+
221
278
  /** Keep in sync with package.json (a test checks it). */
222
- declare const VERSION = "0.5.3";
279
+ declare const VERSION = "0.7.0";
223
280
 
224
- export { CONCURRENCY, type CliSetup, DEFAULT_API_URL, DEFAULT_INGEST_URL, DEFAULT_URL_PREFIX, type FileResult, type Framework, type InitOptions, type InitReport, MARKER_FILE, MAX_MAP_BYTES, MAX_RETRIES, type Outcome, type PackageManager, type PlannedUpload, STOP_CODES, UPLOAD_TOKEN_DEPRECATED, type UploadOptions, type UploadReport, type UploadSummary, UsageError, VERSION, addImport, detectFramework, detectPackageManager, findMapOwners, findSourceMaps, formatBytes, formatResult, formatSummary, importSpecifier, initProject, installCommand, isCiToken, isCssMap, isDeprecatedUploadToken, mapName, planUploads, projectProblem, releaseProblem, remoteRepo, replaceApiKey, sdkTooOld, sendableMapFile, setupCodeProblem, sourceMappingUrlOf, uploadSourceMaps, urlPrefixProblem };
281
+ export { COMMIT_ENV_VARS, COMMIT_SHA, CONCURRENCY, type CliSetup, DEFAULT_API_URL, DEFAULT_INGEST_URL, DEFAULT_URL_PREFIX, type FileResult, type Framework, type InitOptions, type InitReport, MARKER_FILE, MAX_MAP_BYTES, MAX_RETRIES, type Outcome, type PackageManager, type PlannedUpload, type ReleaseCommitOptions, type ReleaseCommitResult, STOP_CODES, UPLOAD_TOKEN_DEPRECATED, type UploadOptions, type UploadReport, type UploadSummary, UsageError, VERSION, addImport, detectCommit, detectFramework, detectPackageManager, findMapOwners, findSourceMaps, formatBytes, formatCommitResult, formatResult, formatSummary, importSpecifier, initProject, installCommand, isCiToken, isCssMap, isDeprecatedUploadToken, mapName, planUploads, projectProblem, releaseProblem, remoteRepo, replaceApiKey, sdkTooOld, sendReleaseCommit, sendableMapFile, setupCodeProblem, sourceMappingUrlOf, uploadSourceMaps, urlPrefixProblem };
package/dist/index.js CHANGED
@@ -11,8 +11,10 @@ import {
11
11
  replaceApiKey,
12
12
  sdkTooOld,
13
13
  setupCodeProblem
14
- } from "./chunk-23Q2GI5D.js";
14
+ } from "./chunk-H3LKWUXE.js";
15
15
  import {
16
+ COMMIT_ENV_VARS,
17
+ COMMIT_SHA,
16
18
  CONCURRENCY,
17
19
  DEFAULT_API_URL,
18
20
  DEFAULT_URL_PREFIX,
@@ -22,9 +24,11 @@ import {
22
24
  UPLOAD_TOKEN_DEPRECATED,
23
25
  UsageError,
24
26
  VERSION,
27
+ detectCommit,
25
28
  findMapOwners,
26
29
  findSourceMaps,
27
30
  formatBytes,
31
+ formatCommitResult,
28
32
  formatResult,
29
33
  formatSummary,
30
34
  isCiToken,
@@ -34,12 +38,15 @@ import {
34
38
  planUploads,
35
39
  projectProblem,
36
40
  releaseProblem,
41
+ sendReleaseCommit,
37
42
  sendableMapFile,
38
43
  sourceMappingUrlOf,
39
44
  uploadSourceMaps,
40
45
  urlPrefixProblem
41
- } from "./chunk-I5JOKYXA.js";
46
+ } from "./chunk-NKLMUZBK.js";
42
47
  export {
48
+ COMMIT_ENV_VARS,
49
+ COMMIT_SHA,
43
50
  CONCURRENCY,
44
51
  DEFAULT_API_URL,
45
52
  DEFAULT_INGEST_URL,
@@ -52,11 +59,13 @@ export {
52
59
  UsageError,
53
60
  VERSION,
54
61
  addImport,
62
+ detectCommit,
55
63
  detectFramework,
56
64
  detectPackageManager,
57
65
  findMapOwners,
58
66
  findSourceMaps,
59
67
  formatBytes,
68
+ formatCommitResult,
60
69
  formatResult,
61
70
  formatSummary,
62
71
  importSpecifier,
@@ -72,6 +81,7 @@ export {
72
81
  remoteRepo,
73
82
  replaceApiKey,
74
83
  sdkTooOld,
84
+ sendReleaseCommit,
75
85
  sendableMapFile,
76
86
  setupCodeProblem,
77
87
  sourceMappingUrlOf,
package/dist/main.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  main
3
- } from "./chunk-CF3QZWJS.js";
4
- import "./chunk-23Q2GI5D.js";
5
- import "./chunk-I5JOKYXA.js";
3
+ } from "./chunk-T4GRUZAC.js";
4
+ import "./chunk-H3LKWUXE.js";
5
+ import "./chunk-NKLMUZBK.js";
6
6
  export {
7
7
  main
8
8
  };
package/dist/vite.d.ts CHANGED
@@ -15,8 +15,24 @@ interface BugwatchSourcemapsOptions {
15
15
  apiUrl?: string;
16
16
  /** Delete the `.map` files from the build output after uploading. Default `true`. */
17
17
  deleteAfterUpload?: boolean;
18
+ /**
19
+ * After every upload succeeded, delete the project's older source maps in
20
+ * Bugwatch (other releases, and this release's files not in this build).
21
+ * Needs a CI token. Default `false`.
22
+ */
23
+ deleteOld?: boolean;
18
24
  /** Fail `vite build` when an upload fails. Default `false` (log and continue). */
19
25
  failOnError?: boolean;
26
+ /**
27
+ * After uploading, send the release's commit (backend Step 144) so Bugwatch
28
+ * can show suspect commits and link frames to GitHub. The commit comes from
29
+ * `commit`, CI variables (`GITHUB_SHA`, `VERCEL_GIT_COMMIT_SHA`, …), or `git
30
+ * rev-parse HEAD`. Default `true`; nothing is sent when no commit is found.
31
+ * A failure is only a warning.
32
+ */
33
+ commits?: boolean;
34
+ /** The commit to send; default: detected (see `commits`). */
35
+ commit?: string;
20
36
  }
21
37
  /** The parts of Vite's resolved config the plugin reads (keeps this package free of a `vite` dependency). */
22
38
  interface ViteConfigLike {
package/dist/vite.js CHANGED
@@ -1,13 +1,17 @@
1
1
  import {
2
+ DEFAULT_API_URL,
2
3
  DEFAULT_URL_PREFIX,
3
4
  UPLOAD_TOKEN_DEPRECATED,
4
5
  UsageError,
6
+ detectCommit,
7
+ formatCommitResult,
5
8
  formatResult,
6
9
  formatSummary,
7
10
  isCiToken,
8
11
  isDeprecatedUploadToken,
12
+ sendReleaseCommit,
9
13
  uploadSourceMaps
10
- } from "./chunk-I5JOKYXA.js";
14
+ } from "./chunk-NKLMUZBK.js";
11
15
 
12
16
  // src/vite.ts
13
17
  import { resolve } from "path";
@@ -53,6 +57,11 @@ function bugwatchSourcemaps(options) {
53
57
  fail("Source maps not uploaded: a CI token needs the project id. Set BUGWATCH_PROJECT or the project option");
54
58
  return;
55
59
  }
60
+ const deleteOld = options.deleteOld === true;
61
+ if (deleteOld && !isCiToken(token)) {
62
+ fail("Source maps not uploaded: deleteOld needs an org CI token (bwc_\u2026). Set BUGWATCH_UPLOAD_TOKEN to one");
63
+ return;
64
+ }
56
65
  if (isDeprecatedUploadToken(token)) logger.warn(`${PREFIX} ${UPLOAD_TOKEN_DEPRECATED}`);
57
66
  try {
58
67
  const { results, summary } = await uploadSourceMaps({
@@ -63,10 +72,29 @@ function bugwatchSourcemaps(options) {
63
72
  urlPrefix: options.urlPrefix ?? DEFAULT_URL_PREFIX,
64
73
  apiUrl: options.apiUrl || process.env.BUGWATCH_API_URL || void 0,
65
74
  deleteAfterUpload: options.deleteAfterUpload ?? true,
75
+ deleteOld,
66
76
  onResult: (result) => (result.outcome === "failed" ? logger.error : logger.info)(`${PREFIX} ${formatResult(result)}`),
67
77
  onRetry: ({ file, attempt, reason }) => logger.warn(`${PREFIX} retry ${file} (attempt ${attempt + 1}): ${reason}`)
68
78
  });
69
- logger.info(`${PREFIX} ${formatSummary(summary, { dryRun: false, release, files: results.length })}`);
79
+ logger.info(`${PREFIX} ${formatSummary(summary, { dryRun: false, release, files: results.length, deleteOld })}`);
80
+ if (summary.pruneError) logger.warn(`${PREFIX} Old source maps were not deleted: ${summary.pruneError}`);
81
+ if (options.commits !== false) {
82
+ const commit = options.commit || detectCommit(process.env, config.root);
83
+ if (commit) {
84
+ try {
85
+ const result = await sendReleaseCommit({
86
+ release,
87
+ commit,
88
+ token,
89
+ ...project ? { project } : {},
90
+ apiUrl: options.apiUrl || process.env.BUGWATCH_API_URL || DEFAULT_API_URL
91
+ });
92
+ (result.commitsStatus === "failed" ? logger.warn : logger.info)(`${PREFIX} ${formatCommitResult(result)}`);
93
+ } catch (error) {
94
+ logger.warn(`${PREFIX} The release's commit was not sent: ${error instanceof Error ? error.message : String(error)}`);
95
+ }
96
+ }
97
+ }
70
98
  if (summary.failed > 0 || summary.notSent > 0) {
71
99
  const count = summary.failed + summary.notSent;
72
100
  fail(`${count} source map upload${count === 1 ? "" : "s"} failed or not sent; the .map files were kept`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bugwatch-cli",
3
- "version": "0.5.3",
3
+ "version": "0.7.0",
4
4
  "description": "Set up Bugwatch in your app and upload source maps from CI (CLI and Vite plugin)",
5
5
  "type": "module",
6
6
  "bin": {