bugwatch-cli 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ravivicks
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,152 @@
1
- # Temporary Holding Version
1
+ # bugwatch-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Upload your build's source maps to Bugwatch, so errors show the
4
+ original file, line, function, and the code around them instead of
5
+ minified frames.
6
+
7
+ Two ways to use it, from the same package:
8
+
9
+ - a **CLI** for any build tool: `bugwatch-cli sourcemaps upload`
10
+ - a **Vite plugin** that uploads at the end of `vite build`
11
+
12
+ Node 18 or later. No runtime dependencies.
13
+
14
+ ```sh
15
+ npm install --save-dev bugwatch-cli
16
+ ```
17
+
18
+ ## Before you start
19
+
20
+ 1. **Create an upload token** in the dashboard: project → Settings →
21
+ Source maps. It is shown once; store it as a CI secret named
22
+ `BUGWATCH_UPLOAD_TOKEN`. Never commit it.
23
+ 2. **Send a release from the SDK**, the same string you upload maps
24
+ for (SDK 0.2.0 or later):
25
+
26
+ ```js
27
+ Bugwatch.init({ apiKey: "bw_…", release: "1.4.2" });
28
+ ```
29
+
30
+ Maps are matched by release and file URL, so an event without a
31
+ `release` is never mapped.
32
+ 3. **Build with source maps that are not served publicly**. In Vite:
33
+ `build.sourcemap: "hidden"` (writes `.map` files without the
34
+ `//# sourceMappingURL` comment). Delete the `.map` files before
35
+ deploying (the plugin does this by default; the CLI with
36
+ `--delete-after-upload`).
37
+
38
+ ## Vite plugin
39
+
40
+ ```ts
41
+ // vite.config.ts
42
+ import { defineConfig } from "vite";
43
+ import { bugwatchSourcemaps } from "bugwatch-cli/vite";
44
+
45
+ export default defineConfig({
46
+ build: { sourcemap: "hidden" },
47
+ plugins: [
48
+ bugwatchSourcemaps({
49
+ // e.g. the git SHA or package version, set by CI; without it, nothing is uploaded
50
+ release: process.env.RELEASE ?? "",
51
+ }),
52
+ ],
53
+ });
54
+ ```
55
+
56
+ Options:
57
+
58
+ | Option | Default | |
59
+ | ------------------- | ------------------------------- | --- |
60
+ | `release` | — | Required. The same value as `Bugwatch.init({ release })` |
61
+ | `token` | `BUGWATCH_UPLOAD_TOKEN` | Upload token |
62
+ | `urlPrefix` | `"~/"` | See [File names](#file-names) |
63
+ | `apiUrl` | `BUGWATCH_API_URL`, else Bugwatch's hosted API | |
64
+ | `deleteAfterUpload` | `true` | Delete the `.map` files from the build output after a fully successful upload |
65
+ | `failOnError` | `false` | Fail `vite build` when an upload fails (default: log the error and continue) |
66
+
67
+ The plugin runs only for `vite build` (not the dev server), after the
68
+ bundle is written, on `build.outDir`. It warns and does nothing when
69
+ `build.sourcemap` is off or `"inline"`, and skips SSR builds.
70
+
71
+ ## CLI
72
+
73
+ ```sh
74
+ bugwatch-cli sourcemaps upload <dir> --release <version> [options]
75
+ ```
76
+
77
+ ```sh
78
+ npx bugwatch-cli sourcemaps upload dist --release 1.4.2 --delete-after-upload
79
+ ```
80
+
81
+ | Option | |
82
+ | ----------------------- | --- |
83
+ | `--release <version>` | Required |
84
+ | `--url-prefix <prefix>` | Default `~/`. See [File names](#file-names) |
85
+ | `--api-url <url>` | Default `BUGWATCH_API_URL`, else Bugwatch's hosted API |
86
+ | `--token <token>` | Default `BUGWATCH_UPLOAD_TOKEN`. Prefer the variable: flags can end up in CI logs |
87
+ | `--delete-after-upload` | Delete the local `.map` files, only after every upload succeeded |
88
+ | `--dry-run` | Print what would be uploaded; no token needed, nothing sent or deleted |
89
+
90
+ It uploads every `*.map` file under `<dir>` (recursively, skipping
91
+ `node_modules`), 4 at a time, and prints one line per file and a
92
+ summary:
93
+
94
+ ```
95
+ uploaded ~/assets/index-3f9a0c1d.js (assets/index-3f9a0c1d.js.map, 1.8 MB)
96
+ unchanged ~/assets/vendor-77aa01e2.js (assets/vendor-77aa01e2.js.map, 912.4 KB)
97
+
98
+ Release 1.4.2: 1 uploaded, 0 replaced, 1 unchanged, 0 failed.
99
+ ```
100
+
101
+ Exit codes: `0` everything uploaded, `1` an upload failed, `2` usage
102
+ error (no token, no release, no `.map` files, bad prefix).
103
+
104
+ Rate limits (`429`, honouring `Retry-After`), server errors (`5xx`),
105
+ and network errors are retried up to 3 times with backoff. `400`,
106
+ `401`, `409`, and `413` are not retried: the message says what to
107
+ fix. The token is never printed.
108
+
109
+ ## File names
110
+
111
+ Each map is uploaded for the URL of the minified file it belongs to:
112
+ the URL prefix + the map's path inside `<dir>`, without `.map`.
113
+
114
+ | Map in the build | `--url-prefix` | Uploaded for |
115
+ | ------------------------- | ------------------------------ | --- |
116
+ | `dist/assets/index-3f9a.js.map` | `~/` (default) | `~/assets/index-3f9a.js` |
117
+ | `dist/assets/index-3f9a.js.map` | `https://cdn.shop.com/static/` | `https://cdn.shop.com/static/assets/index-3f9a.js` |
118
+
119
+ `~/` matches the path on any host, so it works for every domain and
120
+ preview deployment. Use a full URL prefix when the files are served
121
+ from a different path (e.g. a CDN folder) than their place in the
122
+ build. A map uploaded for a full URL wins over a `~/` one for the
123
+ same script. The prefix must start with `~/`, `http://`, or
124
+ `https://` and end with `/`.
125
+
126
+ ## CI example (GitHub Actions)
127
+
128
+ ```yaml
129
+ - run: npm ci
130
+ - run: npm run build
131
+ env:
132
+ RELEASE: ${{ github.sha }}
133
+ VITE_RELEASE: ${{ github.sha }} # pass it to Bugwatch.init too
134
+ BUGWATCH_UPLOAD_TOKEN: ${{ secrets.BUGWATCH_UPLOAD_TOKEN }}
135
+ # Without the Vite plugin:
136
+ # - run: npx bugwatch-cli sourcemaps upload dist --release ${{ github.sha }} --delete-after-upload
137
+ # env:
138
+ # BUGWATCH_UPLOAD_TOKEN: ${{ secrets.BUGWATCH_UPLOAD_TOKEN }}
139
+ ```
140
+
141
+ ## Limits
142
+
143
+ - One map: at most 20 MB
144
+ - 500 maps per release, 50 MB stored (compressed) per project
145
+ - 600 uploads per 10 minutes per token
146
+ - Maps are kept 90 days after their latest upload; uploading the same
147
+ file again (e.g. a CI re-run) only refreshes that
148
+ - Index maps (with `sections`) are not supported yet
149
+
150
+ ## License
151
+
152
+ MIT
@@ -0,0 +1,204 @@
1
+ // src/version.ts
2
+ var VERSION = "0.1.1";
3
+
4
+ // src/upload.ts
5
+ import { readdir, readFile, stat, unlink } from "fs/promises";
6
+ import { join, relative, resolve, sep } from "path";
7
+ var DEFAULT_API_URL = "https://sentry-like.vercel.app";
8
+ var DEFAULT_URL_PREFIX = "~/";
9
+ var CONCURRENCY = 4;
10
+ var MAX_RETRIES = 3;
11
+ var MAX_MAP_BYTES = 20 * 1024 * 1024;
12
+ var MAX_NAME_LENGTH = 1e3;
13
+ var MAX_RETRY_DELAY_MS = 6e4;
14
+ var UsageError = class extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "UsageError";
18
+ }
19
+ };
20
+ function releaseProblem(release) {
21
+ if (!release) return "A release is required";
22
+ if (release.length > 200) return "The release must be at most 200 characters";
23
+ if (/[\s\u0000-\u001f\u007f]/.test(release)) return "The release must not contain spaces or control characters";
24
+ if (release === "." || release === "..") return 'The release must not be "." or ".."';
25
+ return null;
26
+ }
27
+ function urlPrefixProblem(prefix) {
28
+ if (!/^(~\/|https?:\/\/)/.test(prefix)) return 'The URL prefix must start with "~/", "http://" or "https://"';
29
+ if (!prefix.endsWith("/")) return 'The URL prefix must end with "/"';
30
+ if (/[\s?#]/.test(prefix)) return "The URL prefix must not contain spaces, ? or #";
31
+ return null;
32
+ }
33
+ function mapName(relativePath, urlPrefix = DEFAULT_URL_PREFIX) {
34
+ const path = relativePath.split(sep).join("/").replace(/^\.?\//, "");
35
+ return urlPrefix + path.replace(/\.map$/, "");
36
+ }
37
+ async function findSourceMaps(dir) {
38
+ const root = resolve(dir);
39
+ const found = [];
40
+ async function walk(folder) {
41
+ const entries = await readdir(folder, { withFileTypes: true });
42
+ for (const entry of entries) {
43
+ if (entry.name === "node_modules") continue;
44
+ const path = join(folder, entry.name);
45
+ if (entry.isDirectory()) await walk(path);
46
+ else if (entry.isFile() && entry.name.endsWith(".map")) found.push(relative(root, path).split(sep).join("/"));
47
+ }
48
+ }
49
+ await walk(root);
50
+ return found.sort();
51
+ }
52
+ function retryAfterMs(header, now = Date.now()) {
53
+ if (!header) return null;
54
+ const seconds = Number(header);
55
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
56
+ const date = Date.parse(header);
57
+ return Number.isNaN(date) ? null : Math.max(0, date - now);
58
+ }
59
+ function backoffMs(retry) {
60
+ return 1e3 * 2 ** (retry - 1);
61
+ }
62
+ async function errorMessage(response) {
63
+ try {
64
+ const body = await response.json();
65
+ if (typeof body.error?.message === "string") return body.error.message;
66
+ } catch {
67
+ }
68
+ return `HTTP ${response.status}`;
69
+ }
70
+ async function uploadFile(context, file, name, body) {
71
+ const url = `${context.apiUrl}/api/releases/${encodeURIComponent(context.release)}/sourcemaps?name=${encodeURIComponent(name)}`;
72
+ const base = { file, name, bytes: body.length };
73
+ for (let attempt = 0; ; attempt += 1) {
74
+ let response = null;
75
+ let reason;
76
+ try {
77
+ response = await context.fetch(url, {
78
+ method: "POST",
79
+ headers: {
80
+ authorization: `Bearer ${context.token}`,
81
+ "content-type": "application/json",
82
+ "user-agent": `bugwatch-cli/${VERSION}`
83
+ },
84
+ body
85
+ });
86
+ } catch (error) {
87
+ reason = error instanceof Error ? error.message : "network error";
88
+ }
89
+ if (response) {
90
+ if (response.status === 201) return { ...base, outcome: "uploaded", status: 201 };
91
+ if (response.status === 200) {
92
+ let unchanged = false;
93
+ try {
94
+ unchanged = (await response.json()).data?.unchanged === true;
95
+ } catch {
96
+ }
97
+ return { ...base, outcome: unchanged ? "unchanged" : "replaced", status: 200 };
98
+ }
99
+ const message = await errorMessage(response);
100
+ if (response.status !== 429 && response.status < 500) {
101
+ return { ...base, outcome: "failed", status: response.status, error: message };
102
+ }
103
+ reason = `${response.status} ${message}`;
104
+ if (attempt === MAX_RETRIES) return { ...base, outcome: "failed", status: response.status, error: message };
105
+ } else if (attempt === MAX_RETRIES) {
106
+ return { ...base, outcome: "failed", error: reason };
107
+ }
108
+ const retry = attempt + 1;
109
+ const fromHeader = response?.status === 429 ? retryAfterMs(response.headers.get("retry-after")) : null;
110
+ const delayMs = Math.min(fromHeader ?? backoffMs(retry), MAX_RETRY_DELAY_MS);
111
+ context.onRetry?.({ file, attempt: retry, delayMs, reason });
112
+ await context.sleep(delayMs);
113
+ }
114
+ }
115
+ async function mapLimit(items, limit, worker) {
116
+ const results = new Array(items.length);
117
+ let next = 0;
118
+ const run = async () => {
119
+ while (next < items.length) {
120
+ const index = next;
121
+ next += 1;
122
+ results[index] = await worker(items[index]);
123
+ }
124
+ };
125
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run));
126
+ return results;
127
+ }
128
+ var defaultSleep = (ms) => new Promise((done) => setTimeout(done, ms));
129
+ async function uploadSourceMaps(options) {
130
+ const urlPrefix = options.urlPrefix ?? DEFAULT_URL_PREFIX;
131
+ const apiUrl = (options.apiUrl || DEFAULT_API_URL).replace(/\/+$/, "");
132
+ const releaseError = releaseProblem(options.release);
133
+ if (releaseError) throw new UsageError(releaseError);
134
+ const prefixError = urlPrefixProblem(urlPrefix);
135
+ if (prefixError) throw new UsageError(prefixError);
136
+ if (!/^https?:\/\//.test(apiUrl)) throw new UsageError("The API URL must start with http:// or https://");
137
+ if (!options.dryRun && !options.token) {
138
+ throw new UsageError("An upload token is required: set BUGWATCH_UPLOAD_TOKEN");
139
+ }
140
+ const dir = resolve(options.dir);
141
+ try {
142
+ if (!(await stat(dir)).isDirectory()) throw new UsageError(`Not a folder: ${options.dir}`);
143
+ } catch (error) {
144
+ if (error instanceof UsageError) throw error;
145
+ throw new UsageError(`Folder not found: ${options.dir}`);
146
+ }
147
+ const files = await findSourceMaps(dir);
148
+ if (files.length === 0) throw new UsageError(`No .map files found in ${options.dir}`);
149
+ const context = {
150
+ apiUrl,
151
+ release: options.release,
152
+ token: options.token ?? "",
153
+ fetch: options.fetch ?? globalThis.fetch,
154
+ sleep: options.sleep ?? defaultSleep,
155
+ onRetry: options.onRetry
156
+ };
157
+ const results = await mapLimit(files, CONCURRENCY, async (file) => {
158
+ const name = mapName(file, urlPrefix);
159
+ const path = join(dir, file);
160
+ const { size } = await stat(path);
161
+ let result;
162
+ if (name.length > MAX_NAME_LENGTH) {
163
+ result = { file, name, bytes: size, outcome: "failed", error: `The file URL is longer than ${MAX_NAME_LENGTH} characters` };
164
+ } else if (/[\s?#]/.test(name)) {
165
+ result = { file, name, bytes: size, outcome: "failed", error: "The file URL must not contain spaces, ? or #" };
166
+ } else if (size > MAX_MAP_BYTES) {
167
+ result = { file, name, bytes: size, outcome: "failed", error: "Source map is larger than 20 MB" };
168
+ } else if (options.dryRun) {
169
+ result = { file, name, bytes: size, outcome: "dry-run" };
170
+ } else {
171
+ result = await uploadFile(context, file, name, await readFile(path));
172
+ }
173
+ options.onResult?.(result);
174
+ return result;
175
+ });
176
+ const count = (outcome) => results.filter((r) => r.outcome === outcome).length;
177
+ const summary = {
178
+ uploaded: count("uploaded"),
179
+ replaced: count("replaced"),
180
+ unchanged: count("unchanged"),
181
+ failed: count("failed"),
182
+ deleted: 0
183
+ };
184
+ if (options.deleteAfterUpload && !options.dryRun && summary.failed === 0) {
185
+ await Promise.all(files.map((file) => unlink(join(dir, file))));
186
+ summary.deleted = files.length;
187
+ }
188
+ return { results, summary };
189
+ }
190
+
191
+ export {
192
+ VERSION,
193
+ DEFAULT_API_URL,
194
+ DEFAULT_URL_PREFIX,
195
+ CONCURRENCY,
196
+ MAX_RETRIES,
197
+ MAX_MAP_BYTES,
198
+ UsageError,
199
+ releaseProblem,
200
+ urlPrefixProblem,
201
+ mapName,
202
+ findSourceMaps,
203
+ uploadSourceMaps
204
+ };
@@ -0,0 +1,111 @@
1
+ import {
2
+ formatResult,
3
+ formatSummary
4
+ } from "./chunk-QGLOKEF7.js";
5
+ import {
6
+ DEFAULT_API_URL,
7
+ DEFAULT_URL_PREFIX,
8
+ UsageError,
9
+ VERSION,
10
+ uploadSourceMaps
11
+ } from "./chunk-6YRBKOB7.js";
12
+
13
+ // src/main.ts
14
+ import { parseArgs } from "util";
15
+ var USAGE = `Usage: bugwatch-cli sourcemaps upload <dir> --release <version> [options]
16
+
17
+ Uploads every .map file under <dir> to Bugwatch for the release.
18
+
19
+ Options:
20
+ --release <version> The release the SDK sends (Bugwatch.init({ release })). Required
21
+ --url-prefix <prefix> Prefix of the files' URLs: "~/" (any host, default) or
22
+ e.g. "https://cdn.shop.com/static/". Must end with "/"
23
+ --api-url <url> Bugwatch API (default: $BUGWATCH_API_URL or ${DEFAULT_API_URL})
24
+ --token <token> Upload token (default: $BUGWATCH_UPLOAD_TOKEN; prefer the variable)
25
+ --delete-after-upload Delete the local .map files after every upload succeeded
26
+ --dry-run List what would be uploaded; uploads and deletes nothing
27
+ -h, --help Show this help
28
+ -v, --version Show the version
29
+
30
+ Exit codes: 0 all uploaded, 1 an upload failed, 2 usage error.`;
31
+ async function main(argv, env = process.env, out = (line) => process.stdout.write(`${line}
32
+ `), err = (line) => process.stderr.write(`${line}
33
+ `)) {
34
+ let parsed;
35
+ try {
36
+ parsed = parseArgs({
37
+ args: argv,
38
+ allowPositionals: true,
39
+ options: {
40
+ release: { type: "string" },
41
+ "url-prefix": { type: "string" },
42
+ "api-url": { type: "string" },
43
+ token: { type: "string" },
44
+ "delete-after-upload": { type: "boolean" },
45
+ "dry-run": { type: "boolean" },
46
+ help: { type: "boolean", short: "h" },
47
+ version: { type: "boolean", short: "v" }
48
+ }
49
+ });
50
+ } catch (error) {
51
+ err(`Error: ${error instanceof Error ? error.message : String(error)}
52
+
53
+ ${USAGE}`);
54
+ return 2;
55
+ }
56
+ const { values, positionals } = parsed;
57
+ if (values.version) {
58
+ out(VERSION);
59
+ return 0;
60
+ }
61
+ if (values.help) {
62
+ out(USAGE);
63
+ return 0;
64
+ }
65
+ const [group, command, dir, ...extra] = positionals;
66
+ if (group !== "sourcemaps" || command !== "upload" || !dir || extra.length > 0) {
67
+ err(USAGE);
68
+ return 2;
69
+ }
70
+ const dryRun = values["dry-run"] === true;
71
+ const apiUrl = values["api-url"] || env.BUGWATCH_API_URL || DEFAULT_API_URL;
72
+ const token = values.token || env.BUGWATCH_UPLOAD_TOKEN || void 0;
73
+ if (!values.release) {
74
+ err("Error: A release is required (--release)");
75
+ return 2;
76
+ }
77
+ if (!dryRun && !token) {
78
+ err("Error: An upload token is required: set BUGWATCH_UPLOAD_TOKEN (or pass --token)");
79
+ return 2;
80
+ }
81
+ try {
82
+ const { results, summary } = await uploadSourceMaps({
83
+ dir,
84
+ release: values.release,
85
+ token,
86
+ urlPrefix: values["url-prefix"] ?? DEFAULT_URL_PREFIX,
87
+ apiUrl,
88
+ deleteAfterUpload: values["delete-after-upload"] === true,
89
+ dryRun,
90
+ onResult: (result) => (result.outcome === "failed" ? err : out)(formatResult(result)),
91
+ onRetry: ({ file, attempt, delayMs, reason }) => err(`retry ${file} (attempt ${attempt + 1}, in ${Math.round(delayMs / 100) / 10} s): ${reason}`)
92
+ });
93
+ out("");
94
+ out(formatSummary(summary, { dryRun, release: values.release, files: results.length }));
95
+ if (summary.failed > 0 && values["delete-after-upload"]) {
96
+ out("Kept the local .map files because an upload failed.");
97
+ }
98
+ return summary.failed > 0 ? 1 : 0;
99
+ } catch (error) {
100
+ if (error instanceof UsageError) {
101
+ err(`Error: ${error.message}`);
102
+ return 2;
103
+ }
104
+ err(`Error: ${error instanceof Error ? error.message : String(error)}`);
105
+ return 1;
106
+ }
107
+ }
108
+
109
+ export {
110
+ main
111
+ };
@@ -0,0 +1,28 @@
1
+ // src/format.ts
2
+ function formatBytes(bytes) {
3
+ if (bytes < 1024) return `${bytes} B`;
4
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
5
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
6
+ }
7
+ function formatResult(result) {
8
+ const label = result.outcome.padEnd(9);
9
+ const detail = `${result.file}, ${formatBytes(result.bytes)}`;
10
+ if (result.outcome === "failed") {
11
+ const status = result.status ? `${result.status} ` : "";
12
+ return `${label} ${result.name} (${detail}): ${status}${result.error ?? "unknown error"}`;
13
+ }
14
+ return `${label} ${result.name} (${detail})`;
15
+ }
16
+ function formatSummary(summary, { dryRun, release, files }) {
17
+ if (dryRun) {
18
+ const skipped = summary.failed > 0 ? ` (${summary.failed} would fail)` : "";
19
+ return `Dry run for release ${release}: ${files} source map${files === 1 ? "" : "s"} found${skipped}; nothing was uploaded.`;
20
+ }
21
+ const line = `Release ${release}: ${summary.uploaded} uploaded, ${summary.replaced} replaced, ${summary.unchanged} unchanged, ${summary.failed} failed.`;
22
+ return summary.deleted > 0 ? `${line} Deleted ${summary.deleted} local .map file${summary.deleted === 1 ? "" : "s"}.` : line;
23
+ }
24
+
25
+ export {
26
+ formatResult,
27
+ formatSummary
28
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ main
4
+ } from "./chunk-NWO6RFO7.js";
5
+ import "./chunk-QGLOKEF7.js";
6
+ import "./chunk-6YRBKOB7.js";
7
+
8
+ // src/cli.ts
9
+ main(process.argv.slice(2)).then((code) => {
10
+ process.exitCode = code;
11
+ });
@@ -0,0 +1,83 @@
1
+ /** The SDK's default API host (its ingest endpoint is `<host>/api/ingest`). */
2
+ declare const DEFAULT_API_URL = "https://sentry-like.vercel.app";
3
+ declare const DEFAULT_URL_PREFIX = "~/";
4
+ declare const CONCURRENCY = 4;
5
+ /** Retries after the first attempt (429, 5xx, network errors). */
6
+ declare const MAX_RETRIES = 3;
7
+ /** The backend rejects larger maps with 413. */
8
+ declare const MAX_MAP_BYTES: number;
9
+ type Outcome = "uploaded" | "replaced" | "unchanged" | "failed" | "dry-run";
10
+ interface FileResult {
11
+ /** The map's path relative to `dir`, with `/` separators. */
12
+ file: string;
13
+ /** The minified file's URL the map is uploaded for. */
14
+ name: string;
15
+ outcome: Outcome;
16
+ bytes: number;
17
+ /** HTTP status of the last attempt, when there was a response. */
18
+ status?: number;
19
+ /** Why it failed. */
20
+ error?: string;
21
+ }
22
+ interface UploadSummary {
23
+ uploaded: number;
24
+ replaced: number;
25
+ unchanged: number;
26
+ failed: number;
27
+ /** Local `.map` files deleted after a fully successful upload. */
28
+ deleted: number;
29
+ }
30
+ interface UploadReport {
31
+ results: FileResult[];
32
+ summary: UploadSummary;
33
+ }
34
+ interface UploadOptions {
35
+ /** Folder with the build output (searched recursively, `node_modules` skipped). */
36
+ dir: string;
37
+ release: string;
38
+ /** Upload token (`bwu_…`). Not needed for a dry run. */
39
+ token?: string;
40
+ /** Default `~/`. Must start with `~/`, `http://` or `https://` and end with `/`. */
41
+ urlPrefix?: string;
42
+ /** Default `https://sentry-like.vercel.app`. */
43
+ apiUrl?: string;
44
+ /** Delete the local `.map` files, only when every upload succeeded. */
45
+ deleteAfterUpload?: boolean;
46
+ /** List what would be uploaded; no network, nothing deleted. */
47
+ dryRun?: boolean;
48
+ /** Called once per file as it finishes. */
49
+ onResult?: (result: FileResult) => void;
50
+ /** Called before each retry. */
51
+ onRetry?: (info: {
52
+ file: string;
53
+ attempt: number;
54
+ delayMs: number;
55
+ reason: string;
56
+ }) => void;
57
+ /** For tests. */
58
+ fetch?: typeof fetch;
59
+ /** For tests. */
60
+ sleep?: (ms: number) => Promise<void>;
61
+ }
62
+ /** A problem with the command itself (exit code 2), not with an upload. */
63
+ declare class UsageError extends Error {
64
+ constructor(message: string);
65
+ }
66
+ /** Same rules as the backend's `release`: 1–200 chars, no whitespace or control characters, not `.` / `..`. */
67
+ declare function releaseProblem(release: string | undefined): string | null;
68
+ declare function urlPrefixProblem(prefix: string): string | null;
69
+ /** `assets/index-3f9a.js.map` + `~/` → `~/assets/index-3f9a.js`. */
70
+ declare function mapName(relativePath: string, urlPrefix?: string): string;
71
+ /** Every `*.map` file under `dir`, relative paths with `/`, sorted. Skips `node_modules`. */
72
+ declare function findSourceMaps(dir: string): Promise<string[]>;
73
+ /**
74
+ * Uploads every source map under `dir` for `release` (4 at a time, with
75
+ * retries). Throws `UsageError` for problems with the options; upload
76
+ * failures are reported per file, never thrown. The token is never logged.
77
+ */
78
+ declare function uploadSourceMaps(options: UploadOptions): Promise<UploadReport>;
79
+
80
+ /** Keep in sync with package.json (a test checks it). */
81
+ declare const VERSION = "0.1.1";
82
+
83
+ export { CONCURRENCY, DEFAULT_API_URL, DEFAULT_URL_PREFIX, type FileResult, MAX_MAP_BYTES, MAX_RETRIES, type Outcome, type UploadOptions, type UploadReport, type UploadSummary, UsageError, VERSION, findSourceMaps, mapName, releaseProblem, uploadSourceMaps, urlPrefixProblem };
package/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ import {
2
+ CONCURRENCY,
3
+ DEFAULT_API_URL,
4
+ DEFAULT_URL_PREFIX,
5
+ MAX_MAP_BYTES,
6
+ MAX_RETRIES,
7
+ UsageError,
8
+ VERSION,
9
+ findSourceMaps,
10
+ mapName,
11
+ releaseProblem,
12
+ uploadSourceMaps,
13
+ urlPrefixProblem
14
+ } from "./chunk-6YRBKOB7.js";
15
+ export {
16
+ CONCURRENCY,
17
+ DEFAULT_API_URL,
18
+ DEFAULT_URL_PREFIX,
19
+ MAX_MAP_BYTES,
20
+ MAX_RETRIES,
21
+ UsageError,
22
+ VERSION,
23
+ findSourceMaps,
24
+ mapName,
25
+ releaseProblem,
26
+ uploadSourceMaps,
27
+ urlPrefixProblem
28
+ };
package/dist/main.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Runs the CLI and returns the exit code. Output goes through `out` / `err`. */
2
+ declare function main(argv: string[], env?: NodeJS.ProcessEnv, out?: (line: string) => void, err?: (line: string) => void): Promise<number>;
3
+
4
+ export { main };
package/dist/main.js ADDED
@@ -0,0 +1,8 @@
1
+ import {
2
+ main
3
+ } from "./chunk-NWO6RFO7.js";
4
+ import "./chunk-QGLOKEF7.js";
5
+ import "./chunk-6YRBKOB7.js";
6
+ export {
7
+ main
8
+ };
package/dist/vite.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ interface BugwatchSourcemapsOptions {
2
+ /**
3
+ * The release the SDK sends (`Bugwatch.init({ release })`). Required, but
4
+ * may be `undefined` so `release: process.env.RELEASE` type-checks: then
5
+ * nothing is uploaded and the build logs why (or fails with `failOnError`).
6
+ */
7
+ release: string | undefined;
8
+ /** Upload token. Default: the `BUGWATCH_UPLOAD_TOKEN` environment variable. */
9
+ token?: string;
10
+ /** Default `~/` (any host). */
11
+ urlPrefix?: string;
12
+ /** Default: `BUGWATCH_API_URL`, else Bugwatch's hosted API. */
13
+ apiUrl?: string;
14
+ /** Delete the `.map` files from the build output after uploading. Default `true`. */
15
+ deleteAfterUpload?: boolean;
16
+ /** Fail `vite build` when an upload fails. Default `false` (log and continue). */
17
+ failOnError?: boolean;
18
+ }
19
+ /** The parts of Vite's resolved config the plugin reads (keeps this package free of a `vite` dependency). */
20
+ interface ViteConfigLike {
21
+ root: string;
22
+ build: {
23
+ outDir: string;
24
+ sourcemap: boolean | "inline" | "hidden";
25
+ ssr?: boolean | string;
26
+ };
27
+ logger: {
28
+ info(message: string): void;
29
+ warn(message: string): void;
30
+ error(message: string): void;
31
+ };
32
+ }
33
+ interface BugwatchSourcemapsPlugin {
34
+ name: string;
35
+ apply: "build";
36
+ enforce: "post";
37
+ configResolved(config: ViteConfigLike): void;
38
+ closeBundle(): Promise<void>;
39
+ }
40
+ /**
41
+ * Uploads the build's source maps to Bugwatch after `vite build`
42
+ * (`closeBundle`). Use with `build.sourcemap: "hidden"`.
43
+ */
44
+ declare function bugwatchSourcemaps(options: BugwatchSourcemapsOptions): BugwatchSourcemapsPlugin;
45
+
46
+ export { type BugwatchSourcemapsOptions, type BugwatchSourcemapsPlugin, type ViteConfigLike, bugwatchSourcemaps, bugwatchSourcemaps as default };
package/dist/vite.js ADDED
@@ -0,0 +1,77 @@
1
+ import {
2
+ formatResult,
3
+ formatSummary
4
+ } from "./chunk-QGLOKEF7.js";
5
+ import {
6
+ DEFAULT_URL_PREFIX,
7
+ UsageError,
8
+ uploadSourceMaps
9
+ } from "./chunk-6YRBKOB7.js";
10
+
11
+ // src/vite.ts
12
+ import { resolve } from "path";
13
+ var PREFIX = "[bugwatch]";
14
+ function bugwatchSourcemaps(options) {
15
+ let config;
16
+ return {
17
+ name: "bugwatch-sourcemaps",
18
+ apply: "build",
19
+ enforce: "post",
20
+ configResolved(resolved) {
21
+ config = resolved;
22
+ },
23
+ async closeBundle() {
24
+ if (!config) return;
25
+ const { logger, build } = config;
26
+ const failOnError = options.failOnError === true;
27
+ if (build.ssr) return;
28
+ if (build.sourcemap === false || build.sourcemap === "inline") {
29
+ logger.warn(
30
+ `${PREFIX} build.sourcemap is ${build.sourcemap === "inline" ? '"inline"' : "off"}, so there are no .map files to upload. Set build.sourcemap: "hidden".`
31
+ );
32
+ return;
33
+ }
34
+ const fail = (message) => {
35
+ if (failOnError) throw new Error(`${PREFIX} ${message}`);
36
+ logger.error(`${PREFIX} ${message}`);
37
+ };
38
+ const release = options.release;
39
+ const token = options.token || process.env.BUGWATCH_UPLOAD_TOKEN || void 0;
40
+ if (!release) {
41
+ fail(
42
+ "Source maps not uploaded: no release. Pass release to bugwatchSourcemaps() (e.g. release: process.env.RELEASE) and set it in CI"
43
+ );
44
+ return;
45
+ }
46
+ if (!token) {
47
+ fail("Source maps not uploaded: no upload token. Set BUGWATCH_UPLOAD_TOKEN or the token option");
48
+ return;
49
+ }
50
+ try {
51
+ const { results, summary } = await uploadSourceMaps({
52
+ dir: resolve(config.root, build.outDir),
53
+ release,
54
+ token,
55
+ urlPrefix: options.urlPrefix ?? DEFAULT_URL_PREFIX,
56
+ apiUrl: options.apiUrl || process.env.BUGWATCH_API_URL || void 0,
57
+ deleteAfterUpload: options.deleteAfterUpload ?? true,
58
+ onResult: (result) => (result.outcome === "failed" ? logger.error : logger.info)(`${PREFIX} ${formatResult(result)}`),
59
+ onRetry: ({ file, attempt, reason }) => logger.warn(`${PREFIX} retry ${file} (attempt ${attempt + 1}): ${reason}`)
60
+ });
61
+ logger.info(`${PREFIX} ${formatSummary(summary, { dryRun: false, release, files: results.length })}`);
62
+ if (summary.failed > 0) {
63
+ fail(`${summary.failed} source map upload${summary.failed === 1 ? "" : "s"} failed; the .map files were kept`);
64
+ }
65
+ } catch (error) {
66
+ if (error instanceof Error && error.message.startsWith(PREFIX)) throw error;
67
+ const message = error instanceof Error ? error.message : String(error);
68
+ fail(error instanceof UsageError ? `Source maps not uploaded: ${message}` : `Source map upload failed: ${message}`);
69
+ }
70
+ }
71
+ };
72
+ }
73
+ var vite_default = bugwatchSourcemaps;
74
+ export {
75
+ bugwatchSourcemaps,
76
+ vite_default as default
77
+ };
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "bugwatch-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Upload source maps to Bugwatch from CI (CLI and Vite plugin)",
5
+ "type": "module",
6
+ "bin": {
7
+ "bugwatch-cli": "dist/cli.js"
8
+ },
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./vite": {
15
+ "types": "./dist/vite.d.ts",
16
+ "import": "./dist/vite.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "scripts": {
25
+ "prepublishOnly": "npm test",
26
+ "build": "tsup",
27
+ "typecheck": "tsc --noEmit",
28
+ "test": "npm run build && node --test test/*.test.mjs"
29
+ },
30
+ "keywords": [
31
+ "bugwatch",
32
+ "source-maps",
33
+ "sourcemaps",
34
+ "vite-plugin",
35
+ "cli"
36
+ ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/Ravivicks/sentry-like-sdk.git",
40
+ "directory": "cli"
41
+ },
42
+ "license": "MIT",
43
+ "engines": {
44
+ "node": ">=18"
45
+ },
46
+ "homepage": "https://github.com/Ravivicks/sentry-like-sdk/tree/main/cli#readme",
47
+ "bugs": {
48
+ "url": "https://github.com/Ravivicks/sentry-like-sdk/issues"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^20.19.43",
52
+ "tsup": "^8.5.1",
53
+ "typescript": "^5.9.3"
54
+ }
55
+ }