bugstack-sdk 2.1.0 → 2.2.1
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/CHANGELOG.md +96 -0
- package/README.md +75 -0
- package/bin/bugstack.cjs +6 -0
- package/dist/adapters/express/index.d.mts +2 -2
- package/dist/adapters/express/index.d.ts +2 -2
- package/dist/adapters/express/index.js +1 -1
- package/dist/adapters/express/index.mjs +1 -1
- package/dist/adapters/generic/index.d.mts +2 -2
- package/dist/adapters/generic/index.d.ts +2 -2
- package/dist/adapters/generic/index.js +1 -1
- package/dist/adapters/generic/index.mjs +1 -1
- package/dist/adapters/nextjs/index.d.mts +2 -2
- package/dist/adapters/nextjs/index.d.ts +2 -2
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/adapters/nextjs/index.mjs +1 -1
- package/dist/build/cli.d.mts +2 -0
- package/dist/build/cli.d.ts +2 -0
- package/dist/build/cli.js +256 -0
- package/dist/build/cli.js.map +1 -0
- package/dist/build/cli.mjs +254 -0
- package/dist/build/cli.mjs.map +1 -0
- package/dist/build/upload.d.mts +82 -0
- package/dist/build/upload.d.ts +82 -0
- package/dist/build/upload.js +163 -0
- package/dist/build/upload.js.map +1 -0
- package/dist/build/upload.mjs +161 -0
- package/dist/build/upload.mjs.map +1 -0
- package/dist/{client-BVW9UrBu.d.mts → client-DoqE7sNh.d.mts} +1 -1
- package/dist/{client-BVW9UrBu.d.ts → client-DoqE7sNh.d.ts} +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/next-config/index.d.mts +56 -0
- package/dist/next-config/index.d.ts +56 -0
- package/dist/next-config/index.js +28 -0
- package/dist/next-config/index.js.map +1 -0
- package/dist/next-config/index.mjs +23 -0
- package/dist/next-config/index.mjs.map +1 -0
- package/package.json +17 -2
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `bugstack-sdk` are documented here.
|
|
4
|
+
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
|
+
|
|
6
|
+
## [2.2.1] — 2026-04-30
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
- **`bugstack` CLI is now installed on the user's `PATH`.** In `2.2.0`,
|
|
10
|
+
npm dropped the `bin[bugstack]` entry at publish time because the path
|
|
11
|
+
was prefixed with `./`, so `npx bugstack sourcemaps upload` and global
|
|
12
|
+
installs could not resolve the binary. Path normalized to
|
|
13
|
+
`bin/bugstack.cjs`.
|
|
14
|
+
|
|
15
|
+
## [2.2.0] — 2026-04-29
|
|
16
|
+
|
|
17
|
+
### Added
|
|
18
|
+
- **Source-map upload pipeline for production builds.** Customers can now
|
|
19
|
+
upload server-side source maps to bugstack so the orchestrator resolves
|
|
20
|
+
bundled stack frames (`.next/server/chunks/8393.js:1:8734`) back to
|
|
21
|
+
source-file positions (`app/api/orders/route.ts:42:5`) — turning the
|
|
22
|
+
"Could not identify primary file" failure mode into auto-fixable
|
|
23
|
+
errors. Two-step setup:
|
|
24
|
+
1. Wrap your `next.config.js`:
|
|
25
|
+
```js
|
|
26
|
+
const { withBugstack } = require('bugstack-sdk/next-config')
|
|
27
|
+
module.exports = withBugstack({ /* your config */ })
|
|
28
|
+
```
|
|
29
|
+
This enables `webpack.devtool = 'source-map'` for production
|
|
30
|
+
server builds, preserving any existing webpack hook.
|
|
31
|
+
2. Append to your `build` script:
|
|
32
|
+
```json
|
|
33
|
+
"build": "next build && bugstack sourcemaps upload"
|
|
34
|
+
```
|
|
35
|
+
The CLI walks `.next/server/**/*.map`, uploads each with the
|
|
36
|
+
active release identifier, and never fails the build.
|
|
37
|
+
- New `bugstack` CLI binary (registered via `bin`) — `bugstack sourcemaps
|
|
38
|
+
upload [--api-key X] [--release Y] [--endpoint Z] [--server-dir D]
|
|
39
|
+
[--concurrency N] [--max-bytes N] [--quiet]`. Auto-detects release from
|
|
40
|
+
`BUGSTACK_RELEASE`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`,
|
|
41
|
+
`GITHUB_SHA`, or `git rev-parse HEAD` in that order.
|
|
42
|
+
- New programmatic API: `import { uploadSourceMaps } from 'bugstack-sdk/build'`
|
|
43
|
+
for callers who want to invoke the uploader from a custom Node script
|
|
44
|
+
rather than via the CLI.
|
|
45
|
+
- New entry: `bugstack-sdk/next-config` exports `withBugstack(config,
|
|
46
|
+
options?)` — the Next.js config wrapper. Idempotent and pass-through
|
|
47
|
+
when `emitServerSourceMaps: false`.
|
|
48
|
+
|
|
49
|
+
### Internal
|
|
50
|
+
- New tsup entries for `src/build/upload`, `src/build/cli`, and
|
|
51
|
+
`src/next-config`. Bin stub at `bin/bugstack.cjs` requires the built
|
|
52
|
+
CLI so the shebang concern stays in checked-in JavaScript and out of
|
|
53
|
+
the bundler's hands.
|
|
54
|
+
|
|
55
|
+
## [2.1.0] — 2026-04-29
|
|
56
|
+
|
|
57
|
+
### Added
|
|
58
|
+
- **Chunk-load error telemetry.** `ChunkLoadError` and the related family
|
|
59
|
+
(`Loading chunk N failed`, `Loading CSS chunk N failed`,
|
|
60
|
+
`Failed to fetch dynamically imported module`,
|
|
61
|
+
`Importing a module script failed`) are now detected and routed to a
|
|
62
|
+
lightweight telemetry endpoint instead of the main fix pipeline. They
|
|
63
|
+
aren't real bugs (stale-tab artifacts after a redeploy) and have no
|
|
64
|
+
source frames the orchestrator could fix, so they were wasting LLM
|
|
65
|
+
cycles when they hit `/api/capture`. The new path lets the dashboard
|
|
66
|
+
render a deploy-health spike detector while keeping the noise out of
|
|
67
|
+
the bug feed.
|
|
68
|
+
- New config option `dropChunkErrors` (default `false`) — set to `true`
|
|
69
|
+
to disable telemetry forwarding entirely and silently discard chunk
|
|
70
|
+
errors instead.
|
|
71
|
+
- New config option `chunkErrorsEndpoint` (default auto-derived from the
|
|
72
|
+
main `endpoint` — `/api/capture` becomes `/api/chunk-errors`). Override
|
|
73
|
+
if your error service splits telemetry across hosts.
|
|
74
|
+
- New exported helper `isChunkLoadError(error)` so callers can reuse the
|
|
75
|
+
same detection logic in their own browser-side error boundaries (e.g.
|
|
76
|
+
to soft-reload the page on first occurrence).
|
|
77
|
+
|
|
78
|
+
### Fixed
|
|
79
|
+
- The wire header `X-BugStack-SDK-Version` reported `0.2.0` since pre-2.0,
|
|
80
|
+
regardless of the actual installed version. Now injected at build time
|
|
81
|
+
from `package.json` via `tsup`'s `define`, so it stays in sync on every
|
|
82
|
+
release.
|
|
83
|
+
|
|
84
|
+
### Changed
|
|
85
|
+
- Default behavior of `reportError` for chunk-load errors is now route-to-
|
|
86
|
+
telemetry. Previously these went into the main capture pipeline (where
|
|
87
|
+
they'd create unfixable rows the orchestrator would burn cycles on).
|
|
88
|
+
This is a soft behavior change: customer code is unaffected, but the
|
|
89
|
+
destination endpoint differs. Hosted customers (api.bugstack.ai) get
|
|
90
|
+
the new endpoint automatically; self-hosted error-service deployments
|
|
91
|
+
should pull the matching error-service release for the
|
|
92
|
+
`/api/chunk-errors` ingest route.
|
|
93
|
+
|
|
94
|
+
## [2.0.2] — 2026-02-27
|
|
95
|
+
|
|
96
|
+
Previous published baseline.
|
package/README.md
CHANGED
|
@@ -176,6 +176,81 @@ try {
|
|
|
176
176
|
|
|
177
177
|
---
|
|
178
178
|
|
|
179
|
+
## Source Maps for Production (Next.js)
|
|
180
|
+
|
|
181
|
+
By default, server-side errors in a Next.js production build come back with stack frames that point at compiled chunks like `.next/server/chunks/8393.js:1:8734`. The bugstack orchestrator can't fix what it can't locate — so without source maps, those errors land in your dashboard as "Could not identify primary file from error" and never auto-fix.
|
|
182
|
+
|
|
183
|
+
Uploading source maps closes that loop. The orchestrator resolves bundled frames back to source-file positions (`app/api/orders/route.ts:42:5`) before deciding which file to patch.
|
|
184
|
+
|
|
185
|
+
### Two-step setup
|
|
186
|
+
|
|
187
|
+
**1. Wrap your `next.config.js`:**
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
const { withBugstack } = require('bugstack-sdk/next-config')
|
|
191
|
+
|
|
192
|
+
module.exports = withBugstack({
|
|
193
|
+
// your existing Next.js config
|
|
194
|
+
})
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
This enables `webpack.devtool = 'source-map'` for production server builds (no effect on dev or client). Any existing `webpack` hook you have is preserved and runs first.
|
|
198
|
+
|
|
199
|
+
**2. Append the upload command to your `build` script:**
|
|
200
|
+
|
|
201
|
+
```json
|
|
202
|
+
{
|
|
203
|
+
"scripts": {
|
|
204
|
+
"build": "next build && bugstack sourcemaps upload"
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
The CLI walks `.next/server/**/*.map`, uploads each to bugstack keyed by the active release, and **never fails the build** — source maps are an optimisation, not a release gate.
|
|
210
|
+
|
|
211
|
+
### Required environment
|
|
212
|
+
|
|
213
|
+
The CLI needs two env vars at build time. Set them in your CI / hosting provider:
|
|
214
|
+
|
|
215
|
+
| Variable | Purpose |
|
|
216
|
+
|---|---|
|
|
217
|
+
| `BUGSTACK_PROJECT_API_KEY` | Your project SDK key (find it in your project settings on the bugstack dashboard). |
|
|
218
|
+
| `BUGSTACK_ENDPOINT` | Base URL of the bugstack ingest service. The CLI appends `/api/sourcemaps/upload` automatically. |
|
|
219
|
+
|
|
220
|
+
Release identifiers are auto-detected from `BUGSTACK_RELEASE`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`, `GITHUB_SHA`, or `git rev-parse HEAD` — in that order. Override with `--release <id>` if you have a different versioning scheme.
|
|
221
|
+
|
|
222
|
+
### Verifying
|
|
223
|
+
|
|
224
|
+
After your next deploy with these env vars set, the build log should print something like:
|
|
225
|
+
|
|
226
|
+
```
|
|
227
|
+
[bugstack] Uploading 68 source map(s) to https://… (release=a9ad704)…
|
|
228
|
+
[bugstack] Uploaded 68/68 maps (10.0MB) in 4.2s.
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
When a server-side error captures next, the row's stack trace and proposed fix will reference real source files (`app/api/.../route.ts`) instead of bundled chunks.
|
|
232
|
+
|
|
233
|
+
### Programmatic API
|
|
234
|
+
|
|
235
|
+
If you'd rather drive the upload from a custom script:
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
import { uploadSourceMaps } from 'bugstack-sdk/build'
|
|
239
|
+
|
|
240
|
+
await uploadSourceMaps({
|
|
241
|
+
apiKey: process.env.BUGSTACK_PROJECT_API_KEY,
|
|
242
|
+
endpoint: process.env.BUGSTACK_ENDPOINT,
|
|
243
|
+
release: process.env.GIT_SHA,
|
|
244
|
+
serverDir: '.next/server', // override for non-Next builds
|
|
245
|
+
})
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### Other build systems
|
|
249
|
+
|
|
250
|
+
The CLI defaults to `.next/server` but accepts `--server-dir <path>` so it works for any directory of compiled `.js` + `.js.map` pairs (e.g. `dist/` for tsc, `build/` for CRA, custom esbuild outputs). The `withBugstack` wrapper is Next.js-specific; for other frameworks, enable source-map emission in your bundler config and run the CLI directly.
|
|
251
|
+
|
|
252
|
+
---
|
|
253
|
+
|
|
179
254
|
## Other Languages
|
|
180
255
|
|
|
181
256
|
BugStack also provides SDKs for:
|
package/bin/bugstack.cjs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Tiny shebang stub — keeps the `npx bugstack ...` entry point working
|
|
3
|
+
// without having to wrestle tsup into preserving a shebang on the bundled
|
|
4
|
+
// output. Adding/removing CLI logic happens in src/build/cli.ts; this
|
|
5
|
+
// file only ever needs to require the built artifact.
|
|
6
|
+
require("../dist/build/cli.js");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ErrorRequestHandler, Request, Response, NextFunction } from 'express';
|
|
2
|
-
import {
|
|
3
|
-
export { B as BugStackClient, C as CapturedError,
|
|
2
|
+
import { E as ErrorCaptureConfig } from '../../client-DoqE7sNh.mjs';
|
|
3
|
+
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-DoqE7sNh.mjs';
|
|
4
4
|
import 'next/server';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ErrorRequestHandler, Request, Response, NextFunction } from 'express';
|
|
2
|
-
import {
|
|
3
|
-
export { B as BugStackClient, C as CapturedError,
|
|
2
|
+
import { E as ErrorCaptureConfig } from '../../client-DoqE7sNh.js';
|
|
3
|
+
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-DoqE7sNh.js';
|
|
4
4
|
import 'next/server';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { B as BugStackClient, C as CapturedError } from '../../client-
|
|
1
|
+
import { E as ErrorCaptureConfig, a as ErrorCaptureClient } from '../../client-DoqE7sNh.mjs';
|
|
2
|
+
export { B as BugStackClient, C as CapturedError } from '../../client-DoqE7sNh.mjs';
|
|
3
3
|
import 'next/server';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { B as BugStackClient, C as CapturedError } from '../../client-
|
|
1
|
+
import { E as ErrorCaptureConfig, a as ErrorCaptureClient } from '../../client-DoqE7sNh.js';
|
|
2
|
+
export { B as BugStackClient, C as CapturedError } from '../../client-DoqE7sNh.js';
|
|
3
3
|
import 'next/server';
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextRequest } from 'next/server';
|
|
2
|
-
import {
|
|
3
|
-
export { B as BugStackClient, C as CapturedError,
|
|
2
|
+
import { R as RouteContext, E as ErrorCaptureConfig, b as RouteOptions } from '../../client-DoqE7sNh.mjs';
|
|
3
|
+
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-DoqE7sNh.mjs';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* BugStack SDK - Next.js Adapter
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextRequest } from 'next/server';
|
|
2
|
-
import {
|
|
3
|
-
export { B as BugStackClient, C as CapturedError,
|
|
2
|
+
import { R as RouteContext, E as ErrorCaptureConfig, b as RouteOptions } from '../../client-DoqE7sNh.js';
|
|
3
|
+
export { B as BugStackClient, C as CapturedError, a as ErrorCaptureClient } from '../../client-DoqE7sNh.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* BugStack SDK - Next.js Adapter
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var util = require('util');
|
|
4
|
+
var promises = require('fs/promises');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
var child_process = require('child_process');
|
|
7
|
+
|
|
8
|
+
// src/build/cli.ts
|
|
9
|
+
var DEFAULT_SERVER_DIR = ".next/server";
|
|
10
|
+
var DEFAULT_CONCURRENCY = 6;
|
|
11
|
+
var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
|
|
12
|
+
var ENDPOINT_PATH = "/api/sourcemaps/upload";
|
|
13
|
+
function resolveRelease(explicit) {
|
|
14
|
+
if (explicit !== void 0) return explicit;
|
|
15
|
+
const fromEnv = process.env.BUGSTACK_RELEASE || process.env.RENDER_GIT_COMMIT || process.env.VERCEL_GIT_COMMIT_SHA || process.env.GITHUB_SHA;
|
|
16
|
+
if (fromEnv) return fromEnv;
|
|
17
|
+
try {
|
|
18
|
+
return child_process.execSync("git rev-parse HEAD", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
|
|
19
|
+
} catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function resolveEndpoint(explicit) {
|
|
24
|
+
const base = explicit || process.env.BUGSTACK_ENDPOINT || (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);
|
|
25
|
+
if (!base) return null;
|
|
26
|
+
const normalised = base.replace(/\/+$/, "").replace(/\/api\/capture$/, "").replace(/\/capture$/, "");
|
|
27
|
+
return normalised + ENDPOINT_PATH;
|
|
28
|
+
}
|
|
29
|
+
async function walk(dir) {
|
|
30
|
+
let entries;
|
|
31
|
+
try {
|
|
32
|
+
entries = await promises.readdir(dir, { withFileTypes: true });
|
|
33
|
+
} catch (err) {
|
|
34
|
+
if (err.code === "ENOENT") return [];
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
const out = [];
|
|
38
|
+
for (const entry of entries) {
|
|
39
|
+
const path$1 = path.join(dir, entry.name);
|
|
40
|
+
if (entry.isDirectory()) {
|
|
41
|
+
out.push(...await walk(path$1));
|
|
42
|
+
} else if (entry.name.endsWith(".map")) {
|
|
43
|
+
out.push(path$1);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
async function pool(items, workers, fn) {
|
|
49
|
+
const results = new Array(items.length);
|
|
50
|
+
let i = 0;
|
|
51
|
+
const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {
|
|
52
|
+
while (i < items.length) {
|
|
53
|
+
const idx = i++;
|
|
54
|
+
results[idx] = await fn(items[idx]);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
await Promise.all(runners);
|
|
58
|
+
return results;
|
|
59
|
+
}
|
|
60
|
+
function bundleFileFor(mapPath, serverDir) {
|
|
61
|
+
return path.relative(serverDir, mapPath).replace(/\.map$/, "").split(path.sep).join("/");
|
|
62
|
+
}
|
|
63
|
+
async function uploadSourceMaps(options = {}) {
|
|
64
|
+
const apiKey = options.apiKey || process.env.BUGSTACK_PROJECT_API_KEY || process.env.BUGSTACK_API_KEY;
|
|
65
|
+
const endpoint = resolveEndpoint(options.endpoint);
|
|
66
|
+
const release = resolveRelease(options.release);
|
|
67
|
+
const serverDir = options.serverDir || DEFAULT_SERVER_DIR;
|
|
68
|
+
const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
|
|
69
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
70
|
+
const log = options.log || ((m) => console.log(m));
|
|
71
|
+
const warn = options.warn || ((m) => console.warn(m));
|
|
72
|
+
if (!apiKey) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly."
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
if (!endpoint) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly."
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
const start = Date.now();
|
|
83
|
+
const mapFiles = await walk(serverDir);
|
|
84
|
+
if (mapFiles.length === 0) {
|
|
85
|
+
log(
|
|
86
|
+
`[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`
|
|
87
|
+
);
|
|
88
|
+
return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };
|
|
89
|
+
}
|
|
90
|
+
log(
|
|
91
|
+
`[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || "none"})...`
|
|
92
|
+
);
|
|
93
|
+
const results = await pool(mapFiles, concurrency, async (mapPath) => {
|
|
94
|
+
const bundleFile = bundleFileFor(mapPath, serverDir);
|
|
95
|
+
const stats = await promises.stat(mapPath);
|
|
96
|
+
if (stats.size > maxBytes) {
|
|
97
|
+
return {
|
|
98
|
+
ok: false,
|
|
99
|
+
bundleFile,
|
|
100
|
+
bytes: 0,
|
|
101
|
+
skipped: true,
|
|
102
|
+
error: `Skipped \u2014 ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const mapJson = await promises.readFile(mapPath, "utf8");
|
|
106
|
+
try {
|
|
107
|
+
const res = await fetch(endpoint, {
|
|
108
|
+
method: "POST",
|
|
109
|
+
headers: {
|
|
110
|
+
"Content-Type": "application/json",
|
|
111
|
+
"X-BugStack-API-Key": apiKey
|
|
112
|
+
},
|
|
113
|
+
body: JSON.stringify({ bundleFile, mapJson, release })
|
|
114
|
+
});
|
|
115
|
+
if (!res.ok) {
|
|
116
|
+
const text = await res.text().catch(() => "");
|
|
117
|
+
return {
|
|
118
|
+
ok: false,
|
|
119
|
+
bundleFile,
|
|
120
|
+
bytes: 0,
|
|
121
|
+
skipped: false,
|
|
122
|
+
error: `HTTP ${res.status} ${text.slice(0, 200)}`
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
return { ok: true, bundleFile, bytes: stats.size, skipped: false };
|
|
126
|
+
} catch (err) {
|
|
127
|
+
return {
|
|
128
|
+
ok: false,
|
|
129
|
+
bundleFile,
|
|
130
|
+
bytes: 0,
|
|
131
|
+
skipped: false,
|
|
132
|
+
error: err instanceof Error ? err.message : String(err)
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
const uploaded = results.filter((r) => r.ok).length;
|
|
137
|
+
const skipped = results.filter((r) => !r.ok && r.skipped).length;
|
|
138
|
+
const failed = results.length - uploaded - skipped;
|
|
139
|
+
const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);
|
|
140
|
+
const failures = results.filter((r) => !r.ok && !r.skipped).map((r) => ({ bundleFile: r.bundleFile, error: r.error }));
|
|
141
|
+
const elapsedMs = Date.now() - start;
|
|
142
|
+
log(
|
|
143
|
+
`[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(
|
|
144
|
+
1
|
|
145
|
+
)}MB) in ${(elapsedMs / 1e3).toFixed(1)}s.`
|
|
146
|
+
);
|
|
147
|
+
if (skipped > 0) {
|
|
148
|
+
warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);
|
|
149
|
+
}
|
|
150
|
+
if (failures.length > 0) {
|
|
151
|
+
warn(`[bugstack] ${failures.length} upload(s) failed:`);
|
|
152
|
+
for (const f of failures.slice(0, 10)) {
|
|
153
|
+
warn(` - ${f.bundleFile}: ${f.error}`);
|
|
154
|
+
}
|
|
155
|
+
if (failures.length > 10) {
|
|
156
|
+
warn(` \u2026and ${failures.length - 10} more`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/build/cli.ts
|
|
163
|
+
function printHelp() {
|
|
164
|
+
console.log(`bugstack \u2014 source-map upload + maintenance CLI
|
|
165
|
+
|
|
166
|
+
USAGE
|
|
167
|
+
bugstack sourcemaps upload [options]
|
|
168
|
+
bugstack --help
|
|
169
|
+
|
|
170
|
+
OPTIONS (sourcemaps upload)
|
|
171
|
+
--api-key <key> Project SDK key. Default: BUGSTACK_PROJECT_API_KEY env.
|
|
172
|
+
--endpoint <url> Base URL of the bugstack ingest service. Default:
|
|
173
|
+
BUGSTACK_ENDPOINT env, or ERROR_SERVICE_URL.
|
|
174
|
+
--release <id> Release identifier (commit SHA / version). Default:
|
|
175
|
+
BUGSTACK_RELEASE env, RENDER_GIT_COMMIT,
|
|
176
|
+
VERCEL_GIT_COMMIT_SHA, GITHUB_SHA, or git rev-parse HEAD.
|
|
177
|
+
--server-dir <path> Directory to walk for .map files. Default: .next/server.
|
|
178
|
+
--concurrency <n> Max concurrent uploads. Default: 6.
|
|
179
|
+
--max-bytes <n> Per-file size cap in bytes. Default: 8388608 (8 MiB).
|
|
180
|
+
--quiet Suppress info logs (warnings still printed).
|
|
181
|
+
|
|
182
|
+
EXIT CODES
|
|
183
|
+
0 Always \u2014 upload failures are reported but never fail the build by
|
|
184
|
+
design. Source maps are an optimisation, not a release gate.
|
|
185
|
+
`);
|
|
186
|
+
}
|
|
187
|
+
async function runSourceMapsUpload(argv) {
|
|
188
|
+
let parsed;
|
|
189
|
+
try {
|
|
190
|
+
parsed = util.parseArgs({
|
|
191
|
+
args: argv,
|
|
192
|
+
options: {
|
|
193
|
+
"api-key": { type: "string" },
|
|
194
|
+
endpoint: { type: "string" },
|
|
195
|
+
release: { type: "string" },
|
|
196
|
+
"server-dir": { type: "string" },
|
|
197
|
+
concurrency: { type: "string" },
|
|
198
|
+
"max-bytes": { type: "string" },
|
|
199
|
+
quiet: { type: "boolean", default: false },
|
|
200
|
+
help: { type: "boolean", short: "h", default: false }
|
|
201
|
+
},
|
|
202
|
+
strict: true
|
|
203
|
+
});
|
|
204
|
+
} catch (err) {
|
|
205
|
+
console.error(`bugstack: ${err.message}`);
|
|
206
|
+
return 2;
|
|
207
|
+
}
|
|
208
|
+
if (parsed.values.help) {
|
|
209
|
+
printHelp();
|
|
210
|
+
return 0;
|
|
211
|
+
}
|
|
212
|
+
const opts = {
|
|
213
|
+
apiKey: parsed.values["api-key"],
|
|
214
|
+
endpoint: parsed.values.endpoint,
|
|
215
|
+
release: parsed.values.release,
|
|
216
|
+
serverDir: parsed.values["server-dir"],
|
|
217
|
+
concurrency: parsed.values.concurrency ? Number(parsed.values.concurrency) : void 0,
|
|
218
|
+
maxBytes: parsed.values["max-bytes"] ? Number(parsed.values["max-bytes"]) : void 0
|
|
219
|
+
};
|
|
220
|
+
if (parsed.values.quiet) {
|
|
221
|
+
opts.log = () => {
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
await uploadSourceMaps(opts);
|
|
226
|
+
return 0;
|
|
227
|
+
} catch (err) {
|
|
228
|
+
console.warn(
|
|
229
|
+
`[bugstack] Skipping source-map upload: ${err instanceof Error ? err.message : String(err)}`
|
|
230
|
+
);
|
|
231
|
+
console.warn(`[bugstack] (This is a soft skip \u2014 your build will still succeed.)`);
|
|
232
|
+
return 0;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
async function main() {
|
|
236
|
+
const [, , command, subcommand, ...rest] = process.argv;
|
|
237
|
+
if (!command || command === "--help" || command === "-h" || command === "help") {
|
|
238
|
+
printHelp();
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
if (command === "sourcemaps" && subcommand === "upload") {
|
|
242
|
+
return runSourceMapsUpload(rest);
|
|
243
|
+
}
|
|
244
|
+
console.error(`bugstack: unknown command "${[command, subcommand].filter(Boolean).join(" ")}"`);
|
|
245
|
+
printHelp();
|
|
246
|
+
return 2;
|
|
247
|
+
}
|
|
248
|
+
main().then(
|
|
249
|
+
(code) => process.exit(code),
|
|
250
|
+
(err) => {
|
|
251
|
+
console.error(`bugstack: unexpected error \u2014 ${err instanceof Error ? err.stack : err}`);
|
|
252
|
+
process.exit(1);
|
|
253
|
+
}
|
|
254
|
+
);
|
|
255
|
+
//# sourceMappingURL=cli.js.map
|
|
256
|
+
//# sourceMappingURL=cli.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/build/upload.ts","../../src/build/cli.ts"],"names":["execSync","readdir","path","join","relative","sep","stat","readFile","parseArgs"],"mappings":";;;;;;;;AAiFA,IAAM,kBAAA,GAAqB,cAAA;AAC3B,IAAM,mBAAA,GAAsB,CAAA;AAC5B,IAAM,iBAAA,GAAoB,IAAI,IAAA,GAAO,IAAA;AACrC,IAAM,aAAA,GAAgB,wBAAA;AAEtB,SAAS,eAAe,QAAA,EAAyC;AAC/D,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,EAAA,MAAM,OAAA,GACJ,OAAA,CAAQ,GAAA,CAAI,gBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,iBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,qBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,UAAA;AACd,EAAA,IAAI,SAAS,OAAO,OAAA;AACpB,EAAA,IAAI;AACF,IAAA,OAAOA,sBAAA,CAAS,oBAAA,EAAsB,EAAE,KAAA,EAAO,CAAC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AAI,CAAA;AAAA,EAC3B,CAAC,GAAA,KAAQ;AACP,IAAA,OAAA,CAAQ,MAAM,CAAA,kCAAA,EAAgC,GAAA,YAAe,QAAQ,GAAA,CAAI,KAAA,GAAQ,GAAG,CAAA,CAAE,CAAA;AACtF,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF,CAAA","file":"cli.js","sourcesContent":["/**\r\n * Build-time source map uploader.\r\n *\r\n * Walks a directory of compiled output looking for `.map` files and POSTs\r\n * each one to the bugstack source-map ingest endpoint. The companion\r\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\r\n * Next.js server bundles; once uploaded, the orchestrator can resolve\r\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\r\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\r\n * generate fixes for bundled errors.\r\n *\r\n * This module is import-safe in any Node 18+ environment. It uses no\r\n * runtime dependencies — `node:fs/promises` + global `fetch`.\r\n */\r\n\r\nimport { readdir, readFile, stat } from \"node:fs/promises\";\r\nimport { join, relative, sep } from \"node:path\";\r\nimport { execSync } from \"node:child_process\";\r\n\r\nexport interface UploadSourceMapsOptions {\r\n /**\r\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\r\n * BUGSTACK_API_KEY when not supplied explicitly.\r\n */\r\n apiKey?: string;\r\n\r\n /**\r\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\r\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\r\n * `/api/sourcemaps/upload` to whatever base it gets.\r\n */\r\n endpoint?: string;\r\n\r\n /**\r\n * Release identifier (typically a commit SHA). Lets multiple deploys\r\n * coexist in the source-map table so old errors still resolve against\r\n * old maps. Auto-detected in this order:\r\n * 1. BUGSTACK_RELEASE\r\n * 2. RENDER_GIT_COMMIT\r\n * 3. VERCEL_GIT_COMMIT_SHA\r\n * 4. GITHUB_SHA\r\n * 5. `git rev-parse HEAD` (when a git checkout is present)\r\n */\r\n release?: string | null;\r\n\r\n /**\r\n * Directory to walk for `.map` files. Defaults to `.next/server`.\r\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\r\n */\r\n serverDir?: string;\r\n\r\n /**\r\n * Max concurrent uploads. Higher means faster builds, more pressure on\r\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\r\n */\r\n concurrency?: number;\r\n\r\n /**\r\n * Per-file size cap in bytes. Maps larger than this are skipped with a\r\n * warning rather than failing. Default 8 MiB — covers typical\r\n * `.next/server/chunks/*.js.map` outputs comfortably.\r\n */\r\n maxBytes?: number;\r\n\r\n /**\r\n * Logger. Defaults to console. Pass a no-op logger to silence the\r\n * \"[bugstack] …\" lines in scripted environments.\r\n */\r\n log?: (message: string) => void;\r\n warn?: (message: string) => void;\r\n}\r\n\r\nexport interface UploadResult {\r\n uploaded: number;\r\n skipped: number;\r\n failed: number;\r\n totalBytes: number;\r\n elapsedMs: number;\r\n failures: Array<{ bundleFile: string; error: string }>;\r\n}\r\n\r\nconst DEFAULT_SERVER_DIR = \".next/server\";\r\nconst DEFAULT_CONCURRENCY = 6;\r\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\r\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\r\n\r\nfunction resolveRelease(explicit?: string | null): string | null {\r\n if (explicit !== undefined) return explicit;\r\n const fromEnv =\r\n process.env.BUGSTACK_RELEASE ||\r\n process.env.RENDER_GIT_COMMIT ||\r\n process.env.VERCEL_GIT_COMMIT_SHA ||\r\n process.env.GITHUB_SHA;\r\n if (fromEnv) return fromEnv;\r\n try {\r\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\r\n .toString()\r\n .trim();\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nfunction resolveEndpoint(explicit?: string): string | null {\r\n const base =\r\n explicit ||\r\n process.env.BUGSTACK_ENDPOINT ||\r\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\r\n if (!base) return null;\r\n // Strip trailing slashes + any trailing /api/capture or /capture so the\r\n // same env var that points the SDK at ingestion also works for sourcemaps.\r\n const normalised = base\r\n .replace(/\\/+$/, \"\")\r\n .replace(/\\/api\\/capture$/, \"\")\r\n .replace(/\\/capture$/, \"\");\r\n return normalised + ENDPOINT_PATH;\r\n}\r\n\r\nasync function walk(dir: string): Promise<string[]> {\r\n let entries;\r\n try {\r\n entries = await readdir(dir, { withFileTypes: true });\r\n } catch (err) {\r\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\r\n throw err;\r\n }\r\n const out: string[] = [];\r\n for (const entry of entries) {\r\n const path = join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n out.push(...(await walk(path)));\r\n } else if (entry.name.endsWith(\".map\")) {\r\n out.push(path);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nasync function pool<T, R>(\r\n items: T[],\r\n workers: number,\r\n fn: (item: T) => Promise<R>,\r\n): Promise<R[]> {\r\n const results: R[] = new Array(items.length);\r\n let i = 0;\r\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\r\n while (i < items.length) {\r\n const idx = i++;\r\n results[idx] = await fn(items[idx]);\r\n }\r\n });\r\n await Promise.all(runners);\r\n return results;\r\n}\r\n\r\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\r\n // Strip the serverDir prefix and the .map suffix; normalise Windows\r\n // backslashes so the bundleFile key stored on the server is portable\r\n // regardless of where the build ran.\r\n return relative(serverDir, mapPath)\r\n .replace(/\\.map$/, \"\")\r\n .split(sep)\r\n .join(\"/\");\r\n}\r\n\r\n/**\r\n * Upload every `.map` file under `serverDir` to the bugstack source-map\r\n * endpoint. Tolerant: never throws on individual file failures, returns\r\n * a summary the caller can decide what to do with.\r\n *\r\n * Throws only on hard configuration errors (no API key, no resolvable\r\n * endpoint, serverDir totally missing).\r\n */\r\nexport async function uploadSourceMaps(\r\n options: UploadSourceMapsOptions = {},\r\n): Promise<UploadResult> {\r\n const apiKey =\r\n options.apiKey ||\r\n process.env.BUGSTACK_PROJECT_API_KEY ||\r\n process.env.BUGSTACK_API_KEY;\r\n const endpoint = resolveEndpoint(options.endpoint);\r\n const release = resolveRelease(options.release);\r\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\r\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\r\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\r\n const log = options.log || ((m: string) => console.log(m));\r\n const warn = options.warn || ((m: string) => console.warn(m));\r\n\r\n if (!apiKey) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\r\n );\r\n }\r\n if (!endpoint) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\r\n );\r\n }\r\n\r\n const start = Date.now();\r\n const mapFiles = await walk(serverDir);\r\n\r\n if (mapFiles.length === 0) {\r\n log(\r\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\r\n );\r\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\r\n }\r\n\r\n log(\r\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\r\n );\r\n\r\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\r\n const bundleFile = bundleFileFor(mapPath, serverDir);\r\n const stats = await stat(mapPath);\r\n if (stats.size > maxBytes) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: true,\r\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\r\n };\r\n }\r\n const mapJson = await readFile(mapPath, \"utf8\");\r\n try {\r\n const res = await fetch(endpoint, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"X-BugStack-API-Key\": apiKey,\r\n },\r\n body: JSON.stringify({ bundleFile, mapJson, release }),\r\n });\r\n if (!res.ok) {\r\n const text = await res.text().catch(() => \"\");\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\r\n };\r\n }\r\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\r\n } catch (err) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n });\r\n\r\n const uploaded = results.filter((r) => r.ok).length;\r\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\r\n const failed = results.length - uploaded - skipped;\r\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\r\n const failures = results\r\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\r\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\r\n const elapsedMs = Date.now() - start;\r\n\r\n log(\r\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\r\n 1,\r\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\r\n );\r\n if (skipped > 0) {\r\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\r\n }\r\n if (failures.length > 0) {\r\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\r\n for (const f of failures.slice(0, 10)) {\r\n warn(` - ${f.bundleFile}: ${f.error}`);\r\n }\r\n if (failures.length > 10) {\r\n warn(` …and ${failures.length - 10} more`);\r\n }\r\n }\r\n\r\n return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };\r\n}\r\n","/**\r\n * `bugstack` CLI entry point.\r\n *\r\n * One command for now — `bugstack sourcemaps upload` — but the dispatch\r\n * is structured so additional subcommands can land without a breaking\r\n * change. Reads config from flags first, env vars second; everything has\r\n * a sensible default so the typical CI invocation is just:\r\n *\r\n * bugstack sourcemaps upload\r\n */\r\n\r\nimport { parseArgs } from \"node:util\";\r\nimport { uploadSourceMaps, type UploadSourceMapsOptions } from \"./upload\";\r\n\r\nfunction printHelp(): void {\r\n console.log(`bugstack — source-map upload + maintenance CLI\r\n\r\nUSAGE\r\n bugstack sourcemaps upload [options]\r\n bugstack --help\r\n\r\nOPTIONS (sourcemaps upload)\r\n --api-key <key> Project SDK key. Default: BUGSTACK_PROJECT_API_KEY env.\r\n --endpoint <url> Base URL of the bugstack ingest service. Default:\r\n BUGSTACK_ENDPOINT env, or ERROR_SERVICE_URL.\r\n --release <id> Release identifier (commit SHA / version). Default:\r\n BUGSTACK_RELEASE env, RENDER_GIT_COMMIT,\r\n VERCEL_GIT_COMMIT_SHA, GITHUB_SHA, or git rev-parse HEAD.\r\n --server-dir <path> Directory to walk for .map files. Default: .next/server.\r\n --concurrency <n> Max concurrent uploads. Default: 6.\r\n --max-bytes <n> Per-file size cap in bytes. Default: 8388608 (8 MiB).\r\n --quiet Suppress info logs (warnings still printed).\r\n\r\nEXIT CODES\r\n 0 Always — upload failures are reported but never fail the build by\r\n design. Source maps are an optimisation, not a release gate.\r\n`);\r\n}\r\n\r\nasync function runSourceMapsUpload(argv: string[]): Promise<number> {\r\n let parsed;\r\n try {\r\n parsed = parseArgs({\r\n args: argv,\r\n options: {\r\n \"api-key\": { type: \"string\" },\r\n endpoint: { type: \"string\" },\r\n release: { type: \"string\" },\r\n \"server-dir\": { type: \"string\" },\r\n concurrency: { type: \"string\" },\r\n \"max-bytes\": { type: \"string\" },\r\n quiet: { type: \"boolean\", default: false },\r\n help: { type: \"boolean\", short: \"h\", default: false },\r\n },\r\n strict: true,\r\n });\r\n } catch (err) {\r\n console.error(`bugstack: ${(err as Error).message}`);\r\n return 2;\r\n }\r\n\r\n if (parsed.values.help) {\r\n printHelp();\r\n return 0;\r\n }\r\n\r\n const opts: UploadSourceMapsOptions = {\r\n apiKey: parsed.values[\"api-key\"],\r\n endpoint: parsed.values.endpoint,\r\n release: parsed.values.release,\r\n serverDir: parsed.values[\"server-dir\"],\r\n concurrency: parsed.values.concurrency ? Number(parsed.values.concurrency) : undefined,\r\n maxBytes: parsed.values[\"max-bytes\"] ? Number(parsed.values[\"max-bytes\"]) : undefined,\r\n };\r\n if (parsed.values.quiet) {\r\n opts.log = () => {};\r\n }\r\n\r\n try {\r\n await uploadSourceMaps(opts);\r\n return 0;\r\n } catch (err) {\r\n // Distinguish hard config errors (missing key, bad endpoint) from per-\r\n // file failures: only the former should surface as a non-zero exit.\r\n // Per-file failures stay inside uploadSourceMaps and resolve with a\r\n // logged summary.\r\n console.warn(\r\n `[bugstack] Skipping source-map upload: ${err instanceof Error ? err.message : String(err)}`,\r\n );\r\n console.warn(`[bugstack] (This is a soft skip — your build will still succeed.)`);\r\n return 0;\r\n }\r\n}\r\n\r\nasync function main(): Promise<number> {\r\n const [, , command, subcommand, ...rest] = process.argv;\r\n\r\n if (!command || command === \"--help\" || command === \"-h\" || command === \"help\") {\r\n printHelp();\r\n return 0;\r\n }\r\n\r\n if (command === \"sourcemaps\" && subcommand === \"upload\") {\r\n return runSourceMapsUpload(rest);\r\n }\r\n\r\n console.error(`bugstack: unknown command \"${[command, subcommand].filter(Boolean).join(\" \")}\"`);\r\n printHelp();\r\n return 2;\r\n}\r\n\r\nmain().then(\r\n (code) => process.exit(code),\r\n (err) => {\r\n console.error(`bugstack: unexpected error — ${err instanceof Error ? err.stack : err}`);\r\n process.exit(1);\r\n },\r\n);\r\n"]}
|