bugwatch-cli 0.3.1 → 0.4.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
@@ -1,11 +1,13 @@
1
1
  # bugwatch-cli
2
2
 
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.
3
+ Set up Bugwatch in your app, and upload your build's source maps to
4
+ Bugwatch, so errors show the original file, line, function, and the
5
+ code around them instead of minified frames.
6
6
 
7
- Two ways to use it, from the same package:
7
+ Three ways to use it, from the same package:
8
8
 
9
+ - **`bugwatch-cli init`** adds Bugwatch to an app for "Add from
10
+ GitHub" (see [Set up a project from GitHub](#set-up-a-project-from-github))
9
11
  - a **CLI** for any build tool: `bugwatch-cli sourcemaps upload`
10
12
  - a **Vite plugin** that uploads at the end of `vite build`
11
13
 
@@ -15,6 +17,47 @@ Node 18 or later. No runtime dependencies.
15
17
  npm install --save-dev bugwatch-cli
16
18
  ```
17
19
 
20
+ ## Set up a project from GitHub
21
+
22
+ In Bugwatch, **Add from GitHub** connects your GitHub account, lets you
23
+ pick a repository, and shows a command with a one-time setup code. Run
24
+ it in your local clone of that repository:
25
+
26
+ ```sh
27
+ npx bugwatch-cli@latest init --setup bws_…
28
+ ```
29
+
30
+ It:
31
+
32
+ 1. fetches the pending project (name, API key) for the setup code
33
+ 2. installs the `bugwatch` SDK with your package manager (npm, pnpm,
34
+ yarn, or bun, from the lockfile)
35
+ 3. writes the `Bugwatch.init({ apiKey })` code:
36
+ - **Next.js**: `instrumentation-client.ts` (or `src/…` when you use a
37
+ `src` folder; Next.js 15.3+). An existing file keeps its code; ours
38
+ goes first
39
+ - **Vite** / **Create React App** / others: `src/bugwatch.ts` (or
40
+ `.js`), imported first in your entry file (Vite's `index.html`
41
+ module script, else `src/main.*` / `src/index.*`)
42
+ 4. writes `.bugwatch.json` at the git root. Bugwatch reads it to verify
43
+ the setup; it holds the setup id, never the setup code or a secret
44
+
45
+ It **never commits or pushes**. Review the changes, commit, and push,
46
+ then press **Verify** in Bugwatch: it checks the branch (the default
47
+ branch unless you enter another) and creates the project. Running it
48
+ again is safe: it updates the API key and does not add a second import.
49
+
50
+ | Option | Description |
51
+ | --- | --- |
52
+ | `--setup <code>` | The `bws_…` code from Add from GitHub. Required |
53
+ | `--api-url <url>` | Bugwatch API (default: `$BUGWATCH_API_URL` or the hosted API); the command Bugwatch shows includes it when needed |
54
+ | `--entry <file>` | Your app's entry file, when it can't be detected |
55
+ | `--skip-install` | Add `bugwatch` to `package.json` without running the package manager |
56
+ | `--dry-run` | Show what would change; installs and writes nothing |
57
+
58
+ The API key ends up in your browser bundle; that is expected (it can
59
+ only send errors to this project). Setup codes expire after 7 days.
60
+
18
61
  ## Before you start
19
62
 
20
63
  0. **Turn on source maps for the project**: project → Settings →
@@ -0,0 +1,350 @@
1
+ import {
2
+ DEFAULT_API_URL,
3
+ UsageError,
4
+ VERSION
5
+ } from "./chunk-YJQR3ZHX.js";
6
+
7
+ // src/init.ts
8
+ import { execFile, spawn } from "child_process";
9
+ import { existsSync, statSync } from "fs";
10
+ import { readFile, writeFile } from "fs/promises";
11
+ import { dirname, join, posix, relative, resolve, sep } from "path";
12
+ var MARKER_FILE = ".bugwatch.json";
13
+ var DEFAULT_INGEST_URL = `${DEFAULT_API_URL}/api/ingest`;
14
+ var SDK_VERSION_RANGE = "^0.3.0";
15
+ var FETCH_TIMEOUT_MS = 15e3;
16
+ var SETUP_CODE = /^bws_[0-9a-f]{32}$/;
17
+ var ENTRY_EXTENSIONS = ["tsx", "ts", "jsx", "js", "mts", "mjs"];
18
+ function setupCodeProblem(code) {
19
+ if (!code) return "A setup code is required (--setup bws_\u2026). Copy the command from Add from GitHub in Bugwatch";
20
+ return SETUP_CODE.test(code) ? null : "The setup code must look like bws_ followed by 32 hex characters";
21
+ }
22
+ function toPosix(path) {
23
+ return path.split(sep).join(posix.sep);
24
+ }
25
+ function findUp(from, name, stopAt) {
26
+ let dir = resolve(from);
27
+ for (; ; ) {
28
+ if (existsSync(join(dir, name))) return dir;
29
+ if (stopAt && dir === stopAt) return null;
30
+ const parent = dirname(dir);
31
+ if (parent === dir) return null;
32
+ dir = parent;
33
+ }
34
+ }
35
+ async function readJson(path) {
36
+ const text = await readFile(path, "utf8");
37
+ const value = JSON.parse(text);
38
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${path} is not a JSON object`);
39
+ return value;
40
+ }
41
+ function deps(pkg) {
42
+ const all = {};
43
+ for (const key of ["dependencies", "devDependencies"]) {
44
+ const value = pkg[key];
45
+ if (typeof value === "object" && value !== null) Object.assign(all, value);
46
+ }
47
+ return all;
48
+ }
49
+ function detectFramework(pkg) {
50
+ const all = deps(pkg);
51
+ if (all.next) return "nextjs";
52
+ if (all.vite) return "vite";
53
+ if (all["react-scripts"]) return "cra";
54
+ return "other";
55
+ }
56
+ function detectPackageManager(packageDir, gitRoot) {
57
+ let dir = packageDir;
58
+ for (; ; ) {
59
+ if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm";
60
+ if (existsSync(join(dir, "yarn.lock"))) return "yarn";
61
+ if (existsSync(join(dir, "bun.lockb")) || existsSync(join(dir, "bun.lock"))) return "bun";
62
+ if (existsSync(join(dir, "package-lock.json"))) return "npm";
63
+ if (dir === gitRoot) return "npm";
64
+ const parent = dirname(dir);
65
+ if (parent === dir) return "npm";
66
+ dir = parent;
67
+ }
68
+ }
69
+ function installCommand(pm) {
70
+ if (pm === "npm") return { command: "npm", args: ["install", "bugwatch"] };
71
+ return { command: pm, args: ["add", "bugwatch"] };
72
+ }
73
+ function defaultRunInstall(command, args, cwd) {
74
+ return new Promise((done) => {
75
+ const child = spawn(command, args, { cwd, stdio: "inherit", shell: process.platform === "win32" });
76
+ child.on("error", () => done(127));
77
+ child.on("close", (code) => done(code ?? 1));
78
+ });
79
+ }
80
+ async function fetchSetup(apiUrl, setupCode) {
81
+ const url = `${apiUrl.replace(/\/+$/, "")}/api/cli/setup`;
82
+ let response;
83
+ try {
84
+ response = await fetch(url, {
85
+ method: "POST",
86
+ headers: { "Content-Type": "application/json", "User-Agent": `bugwatch-cli/${VERSION}` },
87
+ body: JSON.stringify({ setupCode }),
88
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
89
+ });
90
+ } catch (error) {
91
+ throw new Error(`Could not reach Bugwatch at ${apiUrl}: ${error instanceof Error ? error.message : String(error)}`);
92
+ }
93
+ let body = {};
94
+ try {
95
+ body = await response.json();
96
+ } catch {
97
+ }
98
+ if (!response.ok || !body.ok || !body.data) {
99
+ const message = body.error?.message ?? `Bugwatch answered ${response.status}`;
100
+ if (response.status === 404 || response.status === 400) throw new UsageError(message);
101
+ throw new Error(message);
102
+ }
103
+ return body.data;
104
+ }
105
+ function gitRemote(cwd) {
106
+ return new Promise((done) => {
107
+ execFile("git", ["remote", "get-url", "origin"], { cwd, timeout: 5e3 }, (error, stdout) => {
108
+ done(error ? null : stdout.trim() || null);
109
+ });
110
+ });
111
+ }
112
+ function remoteRepo(remote) {
113
+ const match = /github\.com[:/]+([^/]+\/[^/]+?)(?:\.git)?\/?$/i.exec(remote.trim());
114
+ return match ? match[1].toLowerCase() : null;
115
+ }
116
+ function existing(base, stem) {
117
+ for (const ext of ENTRY_EXTENSIONS) {
118
+ const file = `${stem}.${ext}`;
119
+ if (existsSync(join(base, file))) return file;
120
+ }
121
+ return null;
122
+ }
123
+ async function viteEntry(packageDir) {
124
+ const html = join(packageDir, "index.html");
125
+ if (existsSync(html)) {
126
+ const text = await readFile(html, "utf8");
127
+ const match = /<script[^>]*type=["']module["'][^>]*src=["']\/?([^"']+)["']/i.exec(text) ?? /<script[^>]*src=["']\/?([^"']+)["'][^>]*type=["']module["']/i.exec(text);
128
+ if (match && existsSync(join(packageDir, match[1]))) return match[1];
129
+ }
130
+ return existing(packageDir, "src/main") ?? existing(packageDir, "src/index");
131
+ }
132
+ function initSource(setup) {
133
+ const endpoint = setup.ingestUrl !== DEFAULT_INGEST_URL ? `
134
+ endpoint: ${JSON.stringify(setup.ingestUrl)},` : "";
135
+ return [
136
+ `import { Bugwatch } from "bugwatch";`,
137
+ ``,
138
+ `// Bugwatch error tracking for the project ${JSON.stringify(setup.projectName)} (added by bugwatch-cli init).`,
139
+ `// The API key is safe to ship in browser code: it can only send errors to this project.`,
140
+ `Bugwatch.init({`,
141
+ ` apiKey: ${JSON.stringify(setup.apiKey)},${endpoint}`,
142
+ `});`,
143
+ ``
144
+ ].join("\n");
145
+ }
146
+ function replaceApiKey(text, apiKey) {
147
+ const pattern = /(apiKey\s*:\s*)(["'`])bw_[^"'`]*\2/;
148
+ return pattern.test(text) ? text.replace(pattern, `$1$2${apiKey}$2`) : null;
149
+ }
150
+ function importSpecifier(entry, initFile) {
151
+ let spec = posix.relative(posix.dirname(entry), initFile.replace(/\.(m?[jt]sx?)$/, ""));
152
+ if (!spec.startsWith(".")) spec = `./${spec}`;
153
+ return spec;
154
+ }
155
+ function addImport(text, spec) {
156
+ const escaped = spec.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
157
+ if (new RegExp(`import\\s+["']${escaped}(\\.m?[jt]sx?)?["']`).test(text)) return null;
158
+ const lines = text.split("\n");
159
+ let at = 0;
160
+ while (at < lines.length && (/^#!/.test(lines[at]) || /^\s*["']use (client|strict)["'];?\s*$/.test(lines[at]))) at += 1;
161
+ lines.splice(at, 0, `import "${spec}";`);
162
+ return lines.join("\n");
163
+ }
164
+ function detectIndent(text) {
165
+ const match = /^[ \t]+(?=")/m.exec(text);
166
+ return match ? match[0] : 2;
167
+ }
168
+ async function plan(packageDir, pkg, setup, entryOverride, cwd) {
169
+ const framework = detectFramework(pkg);
170
+ const typescript = existsSync(join(packageDir, "tsconfig.json"));
171
+ const ext = typescript ? "ts" : "js";
172
+ const warnings = [];
173
+ const source = initSource(setup);
174
+ let initFile;
175
+ let entryFile = null;
176
+ if (framework === "nextjs" && !entryOverride) {
177
+ const useSrc = existsSync(join(packageDir, "src/app")) || existsSync(join(packageDir, "src/pages"));
178
+ initFile = existing(packageDir, useSrc ? "src/instrumentation-client" : "instrumentation-client") ?? `${useSrc ? "src/" : ""}instrumentation-client.${ext}`;
179
+ const version = /(\d+)\.(\d+)/.exec(deps(pkg).next ?? "");
180
+ if (version && (Number(version[1]) < 15 || Number(version[1]) === 15 && Number(version[2]) < 3)) {
181
+ warnings.push(
182
+ `Next.js ${version[0]} does not load ${initFile} (needs 15.3+). Import it at the top of your root layout or _app, or upgrade Next.js`
183
+ );
184
+ }
185
+ } else {
186
+ if (entryOverride) {
187
+ const abs = resolve(cwd, entryOverride);
188
+ if (!existsSync(abs) || !statSync(abs).isFile()) throw new UsageError(`--entry ${entryOverride} is not a file`);
189
+ entryFile = toPosix(relative(packageDir, abs));
190
+ if (entryFile.startsWith("..")) throw new UsageError(`--entry must be inside ${packageDir}`);
191
+ } else if (framework === "vite") {
192
+ entryFile = await viteEntry(packageDir);
193
+ } else {
194
+ entryFile = existing(packageDir, "src/index") ?? existing(packageDir, "src/main");
195
+ }
196
+ const dir = entryFile ? posix.dirname(entryFile) : existsSync(join(packageDir, "src")) ? "src" : ".";
197
+ const entryExt = entryFile && /\.(m?ts|tsx)$/.test(entryFile) ? "ts" : entryFile ? "js" : ext;
198
+ initFile = existing(packageDir, posix.join(dir, "bugwatch")) ?? posix.join(dir, `bugwatch.${entryExt}`);
199
+ if (!entryFile) {
200
+ warnings.push(`Could not find your app's entry file. Import ./${initFile} first thing in it (or re-run with --entry <file>)`);
201
+ }
202
+ }
203
+ let initContent = source;
204
+ let initAction = "create";
205
+ const initPath = join(packageDir, initFile);
206
+ if (existsSync(initPath)) {
207
+ const current = await readFile(initPath, "utf8");
208
+ if (current.includes("Bugwatch.init")) {
209
+ const replaced = replaceApiKey(current, setup.apiKey);
210
+ if (replaced === null) {
211
+ warnings.push(`${initFile} already calls Bugwatch.init without an apiKey string; check it uses ${setup.apiKey}`);
212
+ initAction = "keep";
213
+ initContent = current;
214
+ } else {
215
+ initAction = replaced === current ? "keep" : "update";
216
+ initContent = replaced;
217
+ }
218
+ } else {
219
+ initAction = "update";
220
+ initContent = `${source}
221
+ ${current}`;
222
+ }
223
+ }
224
+ let entry;
225
+ if (entryFile && entryFile !== initFile) {
226
+ const text = await readFile(join(packageDir, entryFile), "utf8");
227
+ const updated = addImport(text, importSpecifier(entryFile, initFile));
228
+ if (updated !== null) entry = { file: entryFile, content: updated };
229
+ }
230
+ return { framework, initFile, initContent, initAction, ...entry ? { entry } : {}, warnings };
231
+ }
232
+ async function initProject(options) {
233
+ const out = options.out ?? ((line) => process.stdout.write(`${line}
234
+ `));
235
+ const err = options.err ?? ((line) => process.stderr.write(`${line}
236
+ `));
237
+ const cwd = resolve(options.cwd ?? process.cwd());
238
+ const apiUrl = options.apiUrl || DEFAULT_API_URL;
239
+ const dryRun = options.dryRun === true;
240
+ const problem = setupCodeProblem(options.setupCode);
241
+ if (problem) throw new UsageError(problem);
242
+ const gitRoot = findUp(cwd, ".git");
243
+ if (!gitRoot) throw new UsageError("Run this inside your project's git repository (no .git folder found)");
244
+ const packageDir = findUp(cwd, "package.json", gitRoot);
245
+ if (!packageDir) throw new UsageError("No package.json found. Run this in your JavaScript app's folder");
246
+ const setup = await fetchSetup(apiUrl, options.setupCode);
247
+ out(`Bugwatch project "${setup.projectName}" for ${setup.repo.fullName}`);
248
+ const warnings = [];
249
+ const remote = await gitRemote(gitRoot);
250
+ const remoteName = remote ? remoteRepo(remote) : null;
251
+ if (remoteName && remoteName !== setup.repo.fullName.toLowerCase()) {
252
+ warnings.push(`This repository's origin is ${remoteName}, but the setup is for ${setup.repo.fullName}. Bugwatch verifies ${setup.repo.fullName}`);
253
+ }
254
+ const pkgPath = join(packageDir, "package.json");
255
+ const pkgText = await readFile(pkgPath, "utf8");
256
+ const pkg = await readJson(pkgPath);
257
+ const steps = await plan(packageDir, pkg, setup, options.entry, cwd);
258
+ warnings.push(...steps.warnings);
259
+ const packageManager = detectPackageManager(packageDir, gitRoot);
260
+ const hasSdk = Boolean(deps(pkg).bugwatch);
261
+ const fromRoot = (file) => toPosix(relative(gitRoot, join(packageDir, file))) || ".";
262
+ const packageDirRel = toPosix(relative(gitRoot, packageDir)) || ".";
263
+ const changed = [];
264
+ let installed = false;
265
+ if (!hasSdk) {
266
+ const { command, args } = installCommand(packageManager);
267
+ if (dryRun) {
268
+ out(`would run ${options.skipInstall ? `(skipped) add bugwatch@${SDK_VERSION_RANGE} to package.json` : `${command} ${args.join(" ")}`}`);
269
+ } else if (options.skipInstall) {
270
+ const dependencies = typeof pkg.dependencies === "object" && pkg.dependencies !== null ? pkg.dependencies : {};
271
+ pkg.dependencies = { ...dependencies, bugwatch: SDK_VERSION_RANGE };
272
+ await writeFile(pkgPath, `${JSON.stringify(pkg, null, detectIndent(pkgText))}
273
+ `);
274
+ out(`added bugwatch@${SDK_VERSION_RANGE} to ${fromRoot("package.json")} (run ${command} install yourself)`);
275
+ changed.push(fromRoot("package.json"));
276
+ } else {
277
+ out(`running ${command} ${args.join(" ")}`);
278
+ const code = await (options.runInstall ?? defaultRunInstall)(command, args, packageDir);
279
+ if (code !== 0) {
280
+ throw new Error(`${command} ${args.join(" ")} failed (exit ${code}). Fix the install and run this command again`);
281
+ }
282
+ installed = true;
283
+ changed.push(fromRoot("package.json"));
284
+ }
285
+ } else {
286
+ out(`kept bugwatch is already in ${fromRoot("package.json")}`);
287
+ }
288
+ const verb = dryRun ? "would " : "";
289
+ if (steps.initAction === "keep") {
290
+ out(`kept ${fromRoot(steps.initFile)} (already calls Bugwatch.init)`);
291
+ } else {
292
+ if (!dryRun) await writeFile(join(packageDir, steps.initFile), steps.initContent);
293
+ out(`${verb}${steps.initAction === "create" ? "create" : "update"}`.padEnd(12) + fromRoot(steps.initFile));
294
+ changed.push(fromRoot(steps.initFile));
295
+ }
296
+ if (steps.entry) {
297
+ if (!dryRun) await writeFile(join(packageDir, steps.entry.file), steps.entry.content);
298
+ out(`${verb}update`.padEnd(12) + `${fromRoot(steps.entry.file)} (imports the Bugwatch setup first)`);
299
+ changed.push(fromRoot(steps.entry.file));
300
+ }
301
+ const marker = {
302
+ $comment: "Written by bugwatch-cli init. Bugwatch reads this file to verify the setup; it holds no secrets.",
303
+ setupId: setup.setupId,
304
+ project: setup.projectName,
305
+ packageDir: packageDirRel,
306
+ initFile: steps.initFile,
307
+ framework: steps.framework
308
+ };
309
+ if (!dryRun) await writeFile(join(gitRoot, MARKER_FILE), `${JSON.stringify(marker, null, 2)}
310
+ `);
311
+ out(`${verb}write`.padEnd(12) + MARKER_FILE);
312
+ changed.push(MARKER_FILE);
313
+ for (const warning of warnings) err(`Warning: ${warning}`);
314
+ out("");
315
+ if (dryRun) {
316
+ out("Dry run: nothing was installed or written.");
317
+ } else {
318
+ out("Done. Review the changes, then commit and push them:");
319
+ out("");
320
+ out(` git add ${[...new Set(changed)].map((file) => /\s/.test(file) ? JSON.stringify(file) : file).join(" ")}`);
321
+ out(` git commit -m "Add Bugwatch error tracking"`);
322
+ out(` git push origin ${setup.repo.defaultBranch}`);
323
+ out("");
324
+ out("Then press Verify in Bugwatch. If you push to another branch, enter it next to Verify.");
325
+ }
326
+ return {
327
+ setup,
328
+ framework: steps.framework,
329
+ packageManager,
330
+ packageDir: packageDirRel,
331
+ initFile: steps.initFile,
332
+ changed: [...new Set(changed)],
333
+ installed,
334
+ warnings
335
+ };
336
+ }
337
+
338
+ export {
339
+ MARKER_FILE,
340
+ DEFAULT_INGEST_URL,
341
+ setupCodeProblem,
342
+ detectFramework,
343
+ detectPackageManager,
344
+ installCommand,
345
+ remoteRepo,
346
+ replaceApiKey,
347
+ importSpecifier,
348
+ addImport,
349
+ initProject
350
+ };
@@ -1,3 +1,6 @@
1
+ import {
2
+ initProject
3
+ } from "./chunk-IV4JMH5O.js";
1
4
  import {
2
5
  DEFAULT_API_URL,
3
6
  DEFAULT_URL_PREFIX,
@@ -9,10 +12,26 @@ import {
9
12
  isCiToken,
10
13
  isDeprecatedUploadToken,
11
14
  uploadSourceMaps
12
- } from "./chunk-NJEKNSX4.js";
15
+ } from "./chunk-YJQR3ZHX.js";
13
16
 
14
17
  // src/main.ts
15
18
  import { parseArgs } from "util";
19
+ var INIT_USAGE = `Usage: bugwatch-cli init --setup <code> [options]
20
+
21
+ Adds Bugwatch to this app for "Add from GitHub": installs the bugwatch SDK,
22
+ writes the Bugwatch.init code with the project's API key, and writes
23
+ .bugwatch.json at the git root. It never commits or pushes: review, commit,
24
+ and push the changes, then press Verify in Bugwatch.
25
+
26
+ Options:
27
+ --setup <code> The setup code (bws_\u2026) from Add from GitHub. Required
28
+ --api-url <url> Bugwatch API (default: $BUGWATCH_API_URL or ${DEFAULT_API_URL})
29
+ --entry <file> Your app's entry file, when it can't be detected
30
+ --skip-install Add bugwatch to package.json instead of running the package manager
31
+ --dry-run Show what would change; installs and writes nothing
32
+ -h, --help Show this help
33
+
34
+ Exit codes: 0 done, 1 failed (network, install), 2 usage error.`;
16
35
  var USAGE = `Usage: bugwatch-cli sourcemaps upload <dir> --release <version> [options]
17
36
 
18
37
  Uploads every .map file under <dir> to Bugwatch for the release.
@@ -30,7 +49,9 @@ Options:
30
49
  -h, --help Show this help
31
50
  -v, --version Show the version
32
51
 
33
- Exit codes: 0 all uploaded, 1 an upload failed, 2 usage error.`;
52
+ Exit codes: 0 all uploaded, 1 an upload failed, 2 usage error.
53
+
54
+ Set up a new project from GitHub: bugwatch-cli init --setup <code> (see bugwatch-cli init --help).`;
34
55
  async function main(argv, env = process.env, out = (line) => process.stdout.write(`${line}
35
56
  `), err = (line) => process.stderr.write(`${line}
36
57
  `)) {
@@ -47,6 +68,9 @@ async function main(argv, env = process.env, out = (line) => process.stdout.writ
47
68
  project: { type: "string" },
48
69
  "delete-after-upload": { type: "boolean" },
49
70
  "dry-run": { type: "boolean" },
71
+ setup: { type: "string" },
72
+ entry: { type: "string" },
73
+ "skip-install": { type: "boolean" },
50
74
  help: { type: "boolean", short: "h" },
51
75
  version: { type: "boolean", short: "v" }
52
76
  }
@@ -62,6 +86,31 @@ ${USAGE}`);
62
86
  out(VERSION);
63
87
  return 0;
64
88
  }
89
+ if (positionals[0] === "init") {
90
+ if (values.help) {
91
+ out(INIT_USAGE);
92
+ return 0;
93
+ }
94
+ if (positionals.length > 1) {
95
+ err(INIT_USAGE);
96
+ return 2;
97
+ }
98
+ try {
99
+ await initProject({
100
+ setupCode: values.setup ?? "",
101
+ apiUrl: values["api-url"] || env.BUGWATCH_API_URL || DEFAULT_API_URL,
102
+ ...values.entry ? { entry: values.entry } : {},
103
+ skipInstall: values["skip-install"] === true,
104
+ dryRun: values["dry-run"] === true,
105
+ out,
106
+ err
107
+ });
108
+ return 0;
109
+ } catch (error) {
110
+ err(`Error: ${error instanceof Error ? error.message : String(error)}`);
111
+ return error instanceof UsageError ? 2 : 1;
112
+ }
113
+ }
65
114
  if (values.help) {
66
115
  out(USAGE);
67
116
  return 0;
@@ -26,7 +26,7 @@ function formatSummary(summary, { dryRun, release, files }) {
26
26
  }
27
27
 
28
28
  // src/version.ts
29
- var VERSION = "0.3.1";
29
+ var VERSION = "0.4.0";
30
30
 
31
31
  // src/upload.ts
32
32
  import { open, readdir, readFile, stat, unlink } from "fs/promises";
package/dist/cli.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  main
4
- } from "./chunk-YSCPONSJ.js";
5
- import "./chunk-NJEKNSX4.js";
4
+ } from "./chunk-TL4HJZ2T.js";
5
+ import "./chunk-IV4JMH5O.js";
6
+ import "./chunk-YJQR3ZHX.js";
6
7
 
7
8
  // src/cli.ts
8
9
  main(process.argv.slice(2)).then((code) => {
package/dist/index.d.ts CHANGED
@@ -139,7 +139,75 @@ declare function formatSummary(summary: UploadSummary, { dryRun, release, files
139
139
  files: number;
140
140
  }): string;
141
141
 
142
+ /**
143
+ * `bugwatch-cli init --setup bws_…` (Bugwatch "Add from GitHub", backend Step 53):
144
+ * fetches a pending setup, installs the `bugwatch` SDK, writes the
145
+ * `Bugwatch.init` code, and writes `.bugwatch.json` at the git root so Bugwatch
146
+ * can verify the push. It never commits or pushes.
147
+ */
148
+ declare const MARKER_FILE = ".bugwatch.json";
149
+ /** The SDK's default ingest endpoint; `endpoint` is only written for another one. */
150
+ declare const DEFAULT_INGEST_URL = "https://sentry-like.vercel.app/api/ingest";
151
+ type Framework = "nextjs" | "vite" | "cra" | "other";
152
+ type PackageManager = "npm" | "pnpm" | "yarn" | "bun";
153
+ interface CliSetup {
154
+ setupId: string;
155
+ projectName: string;
156
+ apiKey: string;
157
+ ingestUrl: string;
158
+ repo: {
159
+ fullName: string;
160
+ defaultBranch: string;
161
+ };
162
+ expiresAt: string;
163
+ }
164
+ interface InitOptions {
165
+ setupCode: string;
166
+ apiUrl?: string;
167
+ /** Where the command runs; the nearest package.json at or above it is the app. Default: process.cwd(). */
168
+ cwd?: string;
169
+ /** The app's entry file (relative to cwd) to import the init file from, instead of detecting it. */
170
+ entry?: string;
171
+ /** Do not run the package manager; add `bugwatch` to package.json instead. */
172
+ skipInstall?: boolean;
173
+ dryRun?: boolean;
174
+ out?: (line: string) => void;
175
+ err?: (line: string) => void;
176
+ /** Runs the install command; returns its exit code. Tests replace it. */
177
+ runInstall?: (command: string, args: string[], cwd: string) => Promise<number>;
178
+ }
179
+ interface InitReport {
180
+ setup: CliSetup;
181
+ framework: Framework;
182
+ packageManager: PackageManager;
183
+ /** Folder with package.json, relative to the git root (`.` at the root). */
184
+ packageDir: string;
185
+ /** The file that calls Bugwatch.init, relative to packageDir. */
186
+ initFile: string;
187
+ /** Files written or changed, relative to the git root. */
188
+ changed: string[];
189
+ installed: boolean;
190
+ warnings: string[];
191
+ }
192
+ declare function setupCodeProblem(code: string | undefined): string | null;
193
+ declare function detectFramework(pkg: Record<string, unknown>): Framework;
194
+ declare function detectPackageManager(packageDir: string, gitRoot: string): PackageManager;
195
+ declare function installCommand(pm: PackageManager): {
196
+ command: string;
197
+ args: string[];
198
+ };
199
+ /** `git@github.com:acme/shop.git` / `https://github.com/acme/shop` → `acme/shop`. */
200
+ declare function remoteRepo(remote: string): string | null;
201
+ /** Replaces the apiKey string literal in an existing init call; null when there is none to replace. */
202
+ declare function replaceApiKey(text: string, apiKey: string): string | null;
203
+ /** `import "./bugwatch";` from `entry` to `initFile` (both relative to packageDir), without the extension. */
204
+ declare function importSpecifier(entry: string, initFile: string): string;
205
+ /** Puts `import "<spec>";` first in the file, after any "use client" / shebang lines. */
206
+ declare function addImport(text: string, spec: string): string | null;
207
+ /** Runs `init`. Throws UsageError for user mistakes, Error for failures. */
208
+ declare function initProject(options: InitOptions): Promise<InitReport>;
209
+
142
210
  /** Keep in sync with package.json (a test checks it). */
143
- declare const VERSION = "0.3.1";
211
+ declare const VERSION = "0.4.0";
144
212
 
145
- export { CONCURRENCY, DEFAULT_API_URL, DEFAULT_URL_PREFIX, type FileResult, MAX_MAP_BYTES, MAX_RETRIES, type Outcome, type PlannedUpload, STOP_CODES, UPLOAD_TOKEN_DEPRECATED, type UploadOptions, type UploadReport, type UploadSummary, UsageError, VERSION, findMapOwners, findSourceMaps, formatBytes, formatResult, formatSummary, isCiToken, isCssMap, isDeprecatedUploadToken, mapName, planUploads, projectProblem, releaseProblem, sendableMapFile, sourceMappingUrlOf, uploadSourceMaps, urlPrefixProblem };
213
+ 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, sendableMapFile, setupCodeProblem, sourceMappingUrlOf, uploadSourceMaps, urlPrefixProblem };
package/dist/index.js CHANGED
@@ -1,3 +1,16 @@
1
+ import {
2
+ DEFAULT_INGEST_URL,
3
+ MARKER_FILE,
4
+ addImport,
5
+ detectFramework,
6
+ detectPackageManager,
7
+ importSpecifier,
8
+ initProject,
9
+ installCommand,
10
+ remoteRepo,
11
+ replaceApiKey,
12
+ setupCodeProblem
13
+ } from "./chunk-IV4JMH5O.js";
1
14
  import {
2
15
  CONCURRENCY,
3
16
  DEFAULT_API_URL,
@@ -24,22 +37,30 @@ import {
24
37
  sourceMappingUrlOf,
25
38
  uploadSourceMaps,
26
39
  urlPrefixProblem
27
- } from "./chunk-NJEKNSX4.js";
40
+ } from "./chunk-YJQR3ZHX.js";
28
41
  export {
29
42
  CONCURRENCY,
30
43
  DEFAULT_API_URL,
44
+ DEFAULT_INGEST_URL,
31
45
  DEFAULT_URL_PREFIX,
46
+ MARKER_FILE,
32
47
  MAX_MAP_BYTES,
33
48
  MAX_RETRIES,
34
49
  STOP_CODES,
35
50
  UPLOAD_TOKEN_DEPRECATED,
36
51
  UsageError,
37
52
  VERSION,
53
+ addImport,
54
+ detectFramework,
55
+ detectPackageManager,
38
56
  findMapOwners,
39
57
  findSourceMaps,
40
58
  formatBytes,
41
59
  formatResult,
42
60
  formatSummary,
61
+ importSpecifier,
62
+ initProject,
63
+ installCommand,
43
64
  isCiToken,
44
65
  isCssMap,
45
66
  isDeprecatedUploadToken,
@@ -47,7 +68,10 @@ export {
47
68
  planUploads,
48
69
  projectProblem,
49
70
  releaseProblem,
71
+ remoteRepo,
72
+ replaceApiKey,
50
73
  sendableMapFile,
74
+ setupCodeProblem,
51
75
  sourceMappingUrlOf,
52
76
  uploadSourceMaps,
53
77
  urlPrefixProblem
package/dist/main.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  main
3
- } from "./chunk-YSCPONSJ.js";
4
- import "./chunk-NJEKNSX4.js";
3
+ } from "./chunk-TL4HJZ2T.js";
4
+ import "./chunk-IV4JMH5O.js";
5
+ import "./chunk-YJQR3ZHX.js";
5
6
  export {
6
7
  main
7
8
  };
package/dist/vite.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  isCiToken,
8
8
  isDeprecatedUploadToken,
9
9
  uploadSourceMaps
10
- } from "./chunk-NJEKNSX4.js";
10
+ } from "./chunk-YJQR3ZHX.js";
11
11
 
12
12
  // src/vite.ts
13
13
  import { resolve } from "path";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bugwatch-cli",
3
- "version": "0.3.1",
4
- "description": "Upload source maps to Bugwatch from CI (CLI and Vite plugin)",
3
+ "version": "0.4.0",
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": {
7
7
  "bugwatch-cli": "dist/cli.js"