@debugkit/cli 0.6.1 → 0.8.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/dist/cli.js CHANGED
@@ -98,6 +98,48 @@ var firestore_indexes_default = {
98
98
  }
99
99
  ]
100
100
  },
101
+ {
102
+ collectionGroup: "events",
103
+ queryScope: "COLLECTION",
104
+ fields: [
105
+ {
106
+ fieldPath: "sessionId",
107
+ order: "ASCENDING"
108
+ },
109
+ {
110
+ fieldPath: "ts",
111
+ order: "DESCENDING"
112
+ }
113
+ ]
114
+ },
115
+ {
116
+ collectionGroup: "events",
117
+ queryScope: "COLLECTION",
118
+ fields: [
119
+ {
120
+ fieldPath: "user.anonymousId",
121
+ order: "ASCENDING"
122
+ },
123
+ {
124
+ fieldPath: "ts",
125
+ order: "DESCENDING"
126
+ }
127
+ ]
128
+ },
129
+ {
130
+ collectionGroup: "events",
131
+ queryScope: "COLLECTION",
132
+ fields: [
133
+ {
134
+ fieldPath: "user.id",
135
+ order: "ASCENDING"
136
+ },
137
+ {
138
+ fieldPath: "ts",
139
+ order: "DESCENDING"
140
+ }
141
+ ]
142
+ },
101
143
  {
102
144
  collectionGroup: "users",
103
145
  queryScope: "COLLECTION",
@@ -173,6 +215,15 @@ function readConfig(cwd) {
173
215
  if (current) return f.environments?.[current];
174
216
  return f.provider ? f : void 0;
175
217
  }
218
+ function usedByAnotherEnvironment(cwd, uses) {
219
+ const f = readFile(cwd);
220
+ if (!f) return void 0;
221
+ if (current !== void 0 && f.provider && uses(f)) return "the default setup";
222
+ for (const [name, cfg] of Object.entries(f.environments ?? {})) if (name !== current && uses(cfg)) return `the ${name} environment`;
223
+ return void 0;
224
+ }
225
+ var firebaseProjectUsedBy = (cwd, projectId) => usedByAnotherEnvironment(cwd, (c) => c.provider === "firebase" && c.firebase?.projectId === projectId);
226
+ var dynamoTableUsedBy = (cwd, table, region, account) => usedByAnotherEnvironment(cwd, (c) => c.provider === "aws" && c.aws?.table === table && c.aws.region === region && (!c.aws.account || c.aws.account === account));
176
227
  function listEnvironments(cwd) {
177
228
  return Object.keys(readFile(cwd)?.environments ?? {});
178
229
  }
@@ -230,7 +281,7 @@ function ensureGitignored(cwd, entry) {
230
281
  import * as p from "@clack/prompts";
231
282
  import pc from "picocolors";
232
283
  var flags = { yes: false, command: "init" };
233
- function bail(message = flags.command === "init" ? "Setup cancelled. Run npx debugkit init again whenever you're ready." : "Stopped.") {
284
+ function bail(message = flags.command === "init" ? `Setup cancelled. Run ${cmdFor("init")} again whenever you're ready.` : "Stopped.") {
234
285
  p.cancel(message);
235
286
  process.exit(0);
236
287
  }
@@ -253,14 +304,18 @@ async function yes(message, initial = true) {
253
304
  }
254
305
  async function next(message = "Continue") {
255
306
  if (flags.yes) return;
256
- must(await p.confirm({ message, active: "Next", inactive: "Stop here", initialValue: true })) || bail("Stopped the walkthrough. Run npx debugkit guide to pick it up again.");
307
+ if (flags.command === "init") {
308
+ must(await p.select({ message, options: [{ value: "next", label: "Next" }] }));
309
+ return;
310
+ }
311
+ must(await p.confirm({ message, active: "Next", inactive: "Stop here", initialValue: true })) || bail(`Stopped the walkthrough. Run ${cmdFor("guide")} to pick it up again.`);
257
312
  }
258
313
  var code = (s) => pc.cyan(s);
259
314
  var dim = (s) => pc.dim(s);
260
315
  var bold = (s) => pc.bold(s);
261
316
 
262
317
  // src/dashboard.ts
263
- var VERSION = true ? "0.6.1" : "0.0.0-dev";
318
+ var VERSION = true ? "0.8.0" : "0.0.0-dev";
264
319
  var DASHBOARD_VERSION = VERSION;
265
320
  function hashPassword(password2) {
266
321
  const salt = randomBytes(16);
@@ -362,13 +417,13 @@ async function summary(cwd, url, app) {
362
417
  const token = readEnv(paths(cwd).dashboardEnv).DEBUG_API_TOKEN;
363
418
  try {
364
419
  const r = await fetch(`${url}/api/summary?app=${encodeURIComponent(app)}`, { headers: token ? { authorization: `Bearer ${token}` } : {} });
365
- const text2 = await r.text();
420
+ const text3 = await r.text();
366
421
  let data;
367
422
  try {
368
- data = JSON.parse(text2);
423
+ data = JSON.parse(text3);
369
424
  } catch {
370
425
  }
371
- return { ok: r.ok, status: r.status, data, error: r.ok ? void 0 : text2.slice(0, 300) };
426
+ return { ok: r.ok, status: r.status, data, error: r.ok ? void 0 : text3.slice(0, 300) };
372
427
  } catch (err) {
373
428
  return { ok: false, status: 0, error: err.message };
374
429
  }
@@ -491,10 +546,17 @@ async function setupAws(ctx) {
491
546
  p.log.success(`Signed in to AWS account ${code(identity.Account ?? "?")} ${dim(identity.Arn ?? "")}`);
492
547
  if (!identity.Account) bail("AWS didn't say which account these credentials belong to.");
493
548
  const account = identity.Account;
549
+ const takenBy = (t) => dynamoTableUsedBy(ctx.app.cwd, t, region, account);
494
550
  const table = await ask("DynamoDB table name", {
495
551
  initial: environment.get() ? `debugkit-${environment.get()}` : "debugkit",
496
- validate: (v) => /^[A-Za-z0-9_.-]{3,40}$/.test(v) ? void 0 : "3\u201340 characters: letters, digits, _ . -"
552
+ validate: (v) => {
553
+ if (!/^[A-Za-z0-9_.-]{3,40}$/.test(v)) return "3\u201340 characters: letters, digits, _ . -";
554
+ const owner = takenBy(v);
555
+ return owner ? `${owner} already uses ${v} in ${region}. Each environment needs its own table.` : void 0;
556
+ }
497
557
  });
558
+ const tableOwner = takenBy(table);
559
+ if (tableOwner) bail(`${table} in ${region} is already ${tableOwner}'s table. Each environment needs its own table: run again without --yes and pick another name.`);
498
560
  const functionName = `debugkit-ingest-${table}`.slice(0, 64);
499
561
  const roleName = `debugkit-ingest-${table}-${region}`.slice(0, 64);
500
562
  await next(`Create the table, role and function in ${region}`);
@@ -542,7 +604,7 @@ async function setupAws(ctx) {
542
604
  active = (await ddb.send(new ddbMod.DescribeTableCommand({ TableName: table }))).Table?.TableStatus === "ACTIVE";
543
605
  if (!active) await sleep(2e3);
544
606
  }
545
- if (!active) throw new Error(`Table ${table} didn't become active within 3 minutes. Check it in the AWS console, then run npx debugkit init again.`);
607
+ if (!active) throw new Error(`Table ${table} didn't become active within 3 minutes. Check it in the AWS console, then run ${cmdFor("init")} again.`);
546
608
  }
547
609
  if (!tableArn) throw new Error(`AWS didn't return the ARN for table ${table}.`);
548
610
  const ttl = (await ddb.send(new ddbMod.DescribeTimeToLiveCommand({ TableName: table }))).TimeToLiveDescription;
@@ -673,7 +735,7 @@ async function setupAws(ctx) {
673
735
  readOnlyPolicyArn = void 0;
674
736
  }
675
737
  return {
676
- config: { provider: "aws", endpoint: url.replace(/\/$/, ""), ingestKey: ctx.ingestKey, aws: { region, profile, table, functionName, roleName, readOnlyPolicyArn } },
738
+ config: { provider: "aws", endpoint: url.replace(/\/$/, ""), ingestKey: ctx.ingestKey, aws: { region, profile, table, functionName, roleName, readOnlyPolicyArn, account } },
677
739
  dashboardEnv: { DEBUG_STORE: "dynamodb", AWS_REGION: region, DEBUG_DYNAMO_TABLE: table, ...profile ? { AWS_PROFILE: profile } : {}, ...adminEnv(url, ctx) },
678
740
  created: [
679
741
  `DynamoDB table ${code(table)} in ${region}${ownTable ? " (on-demand)" : " (your existing table)"}`,
@@ -725,7 +787,7 @@ async function firebaseCli() {
725
787
  }
726
788
  return ["npx", ["-y", "firebase-tools@latest"]];
727
789
  }
728
- var emailsIn = (text2) => [...new Set(text2.match(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g) ?? [])];
790
+ var emailsIn = (text3) => [...new Set(text3.match(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g) ?? [])];
729
791
  async function setupFirebase(ctx) {
730
792
  const [fbCmd, fbPre] = await firebaseCli();
731
793
  const fb = (args, opts = {}) => capture(fbCmd, [...fbPre, ...args], opts);
@@ -742,7 +804,7 @@ async function setupFirebase(ctx) {
742
804
  let account;
743
805
  if (!accounts.length) {
744
806
  await next("Open the Google sign-in page");
745
- if (await fbLive(["login"]) !== 0) bail("Firebase sign-in didn't finish. Run npx debugkit init to try again.");
807
+ if (await fbLive(["login"]) !== 0) bail(`Firebase sign-in didn't finish. Run ${cmdFor("init")} to try again.`);
746
808
  accounts = emailsIn((await fb(["login:list"])).stdout);
747
809
  }
748
810
  const ADD = "__add__";
@@ -768,19 +830,33 @@ async function setupFirebase(ctx) {
768
830
  p.log.warn(`Couldn't read the project list: ${dim(list.stderr.slice(-300))}`);
769
831
  }
770
832
  const NEW = "__new__";
771
- let projectId = await choose(
772
- "Which Firebase project should deBug use?",
773
- [
774
- { value: NEW, label: "Create a new project", hint: "recommended: keeps deBug's data and bill separate" },
775
- ...projects.map((x) => ({ value: x.projectId, label: x.displayName ? `${x.displayName}` : x.projectId, hint: x.projectId }))
776
- ],
777
- NEW
778
- );
833
+ const takenBy = (id) => firebaseProjectUsedBy(ctx.app.cwd, id);
834
+ let projectId;
835
+ for (; ; ) {
836
+ projectId = await choose(
837
+ "Which Firebase project should deBug use?",
838
+ [
839
+ { value: NEW, label: "Create a new project", hint: "recommended: keeps deBug's data and bill separate" },
840
+ ...projects.map((x) => {
841
+ const owner2 = takenBy(x.projectId);
842
+ return { value: x.projectId, label: x.displayName ? `${x.displayName}` : x.projectId, hint: owner2 ? `${x.projectId}, used by ${owner2}` : x.projectId };
843
+ })
844
+ ],
845
+ NEW
846
+ );
847
+ const owner = projectId === NEW ? void 0 : takenBy(projectId);
848
+ if (!owner) break;
849
+ p.log.warn(`${bold(projectId)} is already ${owner}'s project. Each environment needs its own Firebase project, so their data never mixes. Pick another project, or create one.`);
850
+ }
779
851
  if (projectId === NEW) {
780
852
  const suggested = `${ctx.app.appId}-debug`.slice(0, 26).replace(/-+$/, "") + `-${Math.random().toString(36).slice(2, 6)}`;
781
853
  projectId = await ask("Project id (lowercase, globally unique)", {
782
854
  initial: suggested,
783
- validate: (v) => /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(v) ? void 0 : "6\u201330 characters: lowercase letters, digits and dashes"
855
+ validate: (v) => {
856
+ if (!/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(v)) return "6\u201330 characters: lowercase letters, digits and dashes";
857
+ const owner = takenBy(v);
858
+ return owner ? `${owner} already uses ${v}. Each environment needs its own Firebase project.` : void 0;
859
+ }
784
860
  });
785
861
  if (await fbLive(["projects:create", projectId, "--display-name", `${ctx.app.name} deBug`.slice(0, 30), ...acct]) !== 0)
786
862
  bail(`Couldn't create ${projectId}. Pick an existing project or another id.`);
@@ -810,7 +886,7 @@ async function setupFirebase(ctx) {
810
886
  if (r.code !== 0 && !/already exists/i.test(r.stderr + r.stdout)) {
811
887
  s.error("Couldn't create the database");
812
888
  p.log.error((r.stderr || r.stdout).slice(-600));
813
- bail("Fix the error above (often: the Firestore API needs enabling, or billing), then run npx debugkit init again.");
889
+ bail(`Fix the error above (often: the Firestore API needs enabling, or billing), then run ${cmdFor("init")} again.`);
814
890
  }
815
891
  s.stop(`Created the Firestore database (${location2})`);
816
892
  }
@@ -829,7 +905,7 @@ async function setupFirebase(ctx) {
829
905
  `In ${bold(projectId)}${environment.get() ? ` (your ${environment.get()} environment)` : ""}, deBug will add:`,
830
906
  `\u2022 a Cloud Function ${code(FUNCTION_NAME)} in ${region}, with a public URL (each request needs the ingest key)`,
831
907
  `\u2022 a ${code("debug_apps")} collection in Firestore, with raw events expiring after 30 days`,
832
- `\u2022 two Firestore indexes for it (your existing indexes are left alone)`,
908
+ `\u2022 ${firestore_indexes_default.indexes.length} Firestore indexes for it (your existing indexes are left alone)`,
833
909
  "",
834
910
  "Nothing else in the project is changed. Usage is billed to the project's Blaze plan."
835
911
  ].join("\n"),
@@ -853,7 +929,7 @@ async function setupFirebase(ctx) {
853
929
  ],
854
930
  "retry"
855
931
  );
856
- if (again === "stop") bail(`Fix the error above, then run npx debugkit init again (it reuses what's already set up), or deploy by hand: cd ${paths(ctx.app.cwd).firebase} && npx firebase-tools@latest deploy --only functions:${CODEBASE} --project ${projectId}`);
932
+ if (again === "stop") bail(`Fix the error above, then run ${cmdFor("init")} again (it reuses what's already set up), or deploy by hand: cd ${paths(ctx.app.cwd).firebase} && npx firebase-tools@latest deploy --only functions:${CODEBASE} --project ${projectId}`);
857
933
  if (again === "billing") {
858
934
  openUrl(`https://console.firebase.google.com/project/${projectId}/usage/details`);
859
935
  await next("Upgraded: retry the deploy");
@@ -995,7 +1071,7 @@ function hostedEnv(local, url, extra = {}) {
995
1071
  const plain = { DEBUG_DASHBOARD_URL: url, ...extra };
996
1072
  const secret = {};
997
1073
  for (const k of SHARED) if (local[k]) (SECRET.has(k) ? secret : plain)[k] = local[k];
998
- if (!secret.DEBUG_SESSION_SECRET || !secret.DEBUG_DASHBOARD_USERS) throw new Error("The dashboard login isn't set up yet. Run npx debugkit init (or npx debugkit password) first.");
1074
+ if (!secret.DEBUG_SESSION_SECRET || !secret.DEBUG_DASHBOARD_USERS) throw new Error(`The dashboard login isn't set up yet. Run ${cmdFor("init")} (or ${cmdFor("password")}) first.`);
999
1075
  return { plain, secret };
1000
1076
  }
1001
1077
  var dotenv = (values) => Object.entries(values).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join("\n") + "\n";
@@ -1043,9 +1119,21 @@ async function waitLive(url, ms = 12e4) {
1043
1119
  }
1044
1120
  return false;
1045
1121
  }
1046
- async function hostDashboard(cwd, cfg) {
1122
+ function skipOrStop(opts, message) {
1123
+ if (opts.onProblem === "skip") {
1124
+ p.log.info(`${message} Host it any time with ${code(cmdFor("deploy-dashboard"))}.`);
1125
+ return void 0;
1126
+ }
1127
+ bail(message);
1128
+ }
1129
+ function fail(opts, message) {
1130
+ if (opts.onProblem === "skip") throw new Error(message);
1131
+ bail(message);
1132
+ }
1133
+ async function hostDashboard(cwd, cfg, opts = {}) {
1047
1134
  const local = readEnv(paths(cwd).dashboardEnv);
1048
- const out = cfg.provider === "firebase" ? await hostFirebase(cwd, cfg, local) : cfg.provider === "aws" ? await hostAws(cfg, local) : bail("The dashboard can only be hosted on Firebase or AWS. On this setup, run it locally.");
1135
+ const out = cfg.provider === "firebase" ? await hostFirebase(cwd, cfg, local, opts) : cfg.provider === "aws" ? await hostAws(cfg, local, opts) : bail("The dashboard can only be hosted on Firebase or AWS. On this setup, run it locally.");
1136
+ if (!out) return void 0;
1049
1137
  if (cfg.firebase?.account) {
1050
1138
  if (!local.DEBUGKIT_FIREBASE_ACCOUNT) upsertEnv(paths(cwd).dashboardEnv, { DEBUGKIT_FIREBASE_ACCOUNT: cfg.firebase.account });
1051
1139
  const { account: _a, ...firebase } = cfg.firebase;
@@ -1055,9 +1143,10 @@ async function hostDashboard(cwd, cfg) {
1055
1143
  await linkAlerts(local, cfg.appId, out.hosted.url);
1056
1144
  const s = p.spinner();
1057
1145
  s.start(`Checking ${out.hosted.url}`);
1058
- if (await waitLive(out.hosted.url)) s.stop(`The dashboard is live at ${code(out.hosted.url)}`);
1146
+ const live = await waitLive(out.hosted.url);
1147
+ if (live) s.stop(`The dashboard is live at ${code(out.hosted.url)}`);
1059
1148
  else s.error(`${out.hosted.url} didn't answer yet. New deploys can take a minute; open it again shortly.`);
1060
- return { url: out.hosted.url, created: out.created };
1149
+ return { url: out.hosted.url, created: out.created, live };
1061
1150
  }
1062
1151
  var SITE_ID = /^[a-z0-9](?:[a-z0-9-]{2,61}[a-z0-9])$/;
1063
1152
  async function listSites(fb, proj) {
@@ -1067,7 +1156,7 @@ async function listSites(fb, proj) {
1067
1156
  async function readOnlyServiceAccount(projectId) {
1068
1157
  const email = `${SA_NAME}@${projectId}.iam.gserviceaccount.com`;
1069
1158
  if (!which("gcloud")) {
1070
- p.log.warn(`gcloud isn't installed, so the dashboard runs as the project's default service account (which can write). Install gcloud and run ${code("npx debugkit deploy-dashboard")} again to lock it to read-only.`);
1159
+ p.log.warn(`gcloud isn't installed, so the dashboard runs as the project's default service account (which can write). Install gcloud and run ${code(cmdFor("deploy-dashboard"))} again to lock it to read-only.`);
1071
1160
  return void 0;
1072
1161
  }
1073
1162
  const g2 = (args) => capture("gcloud", [...args, "--project", projectId, "--quiet"]);
@@ -1135,8 +1224,8 @@ function writeHostingConfig(dir, site, region) {
1135
1224
  ]
1136
1225
  }));
1137
1226
  }
1138
- async function hostFirebase(cwd, cfg, local) {
1139
- const fbc = cfg.firebase ?? bail("This setup has no Firebase project saved. Run npx debugkit init again.");
1227
+ async function hostFirebase(cwd, cfg, local, opts) {
1228
+ const fbc = cfg.firebase ?? fail(opts, `This setup has no Firebase project saved. Run ${cmdFor("init")} again.`);
1140
1229
  const [fbCmd, fbPre] = await firebaseCli();
1141
1230
  const account = local.DEBUGKIT_FIREBASE_ACCOUNT || fbc.account;
1142
1231
  const acct = account ? ["--account", account] : [];
@@ -1144,7 +1233,7 @@ async function hostFirebase(cwd, cfg, local) {
1144
1233
  const fb = (args, o = {}) => capture(fbCmd, [...fbPre, ...args], o);
1145
1234
  const fbLive = (args, o = {}) => interactive(fbCmd, [...fbPre, ...args], o);
1146
1235
  const dir = paths(cwd).firebase;
1147
- if (!existsSync5(join5(dir, "firebase.json"))) bail(`${dir} is missing. Run ${code("npx debugkit init")} again to recreate it.`);
1236
+ if (!existsSync5(join5(dir, "firebase.json"))) fail(opts, `${dir} is missing. Run ${cmdFor("init")} again to recreate it.`);
1148
1237
  const s = p.spinner();
1149
1238
  s.start("Finding a Hosting site for the dashboard");
1150
1239
  const sites = await listSites(fb, proj);
@@ -1166,7 +1255,7 @@ async function hostFirebase(cwd, cfg, local) {
1166
1255
  }
1167
1256
  if (!site) {
1168
1257
  s.error("Couldn't find a free Hosting site name");
1169
- bail(`Create one in the Firebase console (Hosting \u2192 Add another site), then run ${code("npx debugkit deploy-dashboard")}.`);
1258
+ return skipOrStop(opts, "Create a site in the Firebase console (Hosting \u2192 Add another site).");
1170
1259
  }
1171
1260
  const url = `https://${site}.web.app`;
1172
1261
  s.stop(`Hosting site ${code(site)}: ${url}`);
@@ -1199,7 +1288,7 @@ async function hostFirebase(cwd, cfg, local) {
1199
1288
  ].join("\n"),
1200
1289
  "About to host the dashboard"
1201
1290
  );
1202
- if (!await yes(`Host the dashboard in ${fbc.projectId}?`)) bail("Nothing was deployed. The dashboard still runs locally with npx debugkit dashboard.");
1291
+ if (!opts.confirmed && !await yes(`Host the dashboard in ${fbc.projectId}?`)) return skipOrStop(opts, `Skipped hosting: the dashboard still runs locally with ${cmdFor("dashboard")}.`);
1203
1292
  writeFileSync3(join5(dir, "firestore.indexes.json"), JSON.stringify(firestore_indexes_default, null, 2) + "\n");
1204
1293
  p.log.step("Adding any Firestore indexes this version of deBug needs (existing ones are left alone)");
1205
1294
  if (await fbLive(["deploy", "--only", "firestore:indexes", "--non-interactive", ...proj], { cwd: dir }) !== 0)
@@ -1214,11 +1303,11 @@ async function hostFirebase(cwd, cfg, local) {
1214
1303
  // Hosting can't reach functions in some regions (africa-south1, for one): a plain retry fails the same way.
1215
1304
  ...region !== "us-central1" ? [{ value: "us", label: "Retry with the function in us-central1", hint: "the usual fix when Hosting can't reach the function's region" }] : [],
1216
1305
  { value: "retry", label: "Retry as it is" },
1217
- { value: "stop", label: "Stop here" }
1306
+ { value: "giveUp", label: opts.onProblem === "skip" ? "Skip hosting for now" : "Stop here" }
1218
1307
  ],
1219
1308
  region !== "us-central1" ? "us" : "retry"
1220
1309
  );
1221
- if (choice === "stop") bail(`Fix the error above, then run ${code("npx debugkit deploy-dashboard")}.`);
1310
+ if (choice === "giveUp") return skipOrStop(opts, "The dashboard isn't hosted yet: fix the error above.");
1222
1311
  if (choice === "us") {
1223
1312
  region = "us-central1";
1224
1313
  write();
@@ -1258,9 +1347,9 @@ async function dashboardZip() {
1258
1347
  rmSync(dir, { recursive: true, force: true });
1259
1348
  }
1260
1349
  }
1261
- async function hostAws(cfg, local) {
1262
- const aws = cfg.aws ?? bail("This setup has no AWS details saved. Run npx debugkit init again.");
1263
- if (!aws.readOnlyPolicyArn) bail("The read-only policy for the dashboard is missing. Run npx debugkit init again (it adds it), then npx debugkit deploy-dashboard.");
1350
+ async function hostAws(cfg, local, opts) {
1351
+ const aws = cfg.aws ?? fail(opts, `This setup has no AWS details saved. Run ${cmdFor("init")} again.`);
1352
+ if (!aws.readOnlyPolicyArn) fail(opts, `The read-only policy for the dashboard is missing. Run ${cmdFor("init")} again (it adds it), then ${cmdFor("deploy-dashboard")}.`);
1264
1353
  const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
1265
1354
  const [iamMod, lambdaMod] = await Promise.all([import("@aws-sdk/client-iam"), import("@aws-sdk/client-lambda")]);
1266
1355
  const base = { region: aws.region, credentials: fromNodeProviderChain(aws.profile ? { profile: aws.profile } : {}) };
@@ -1279,7 +1368,7 @@ async function hostAws(cfg, local) {
1279
1368
  ].join("\n"),
1280
1369
  "About to host the dashboard"
1281
1370
  );
1282
- if (!await yes("Host the dashboard in AWS?")) bail("Nothing was deployed. The dashboard still runs locally with npx debugkit dashboard.");
1371
+ if (!opts.confirmed && !await yes("Host the dashboard in AWS?")) return skipOrStop(opts, `Skipped hosting: the dashboard still runs locally with ${cmdFor("dashboard")}.`);
1283
1372
  const s = p.spinner();
1284
1373
  s.start("Packaging the dashboard");
1285
1374
  const zip = await dashboardZip();
@@ -1288,7 +1377,7 @@ async function hostAws(cfg, local) {
1288
1377
  let newRole = false;
1289
1378
  const role = await lookup(() => iam.send(new iamMod.GetRoleCommand({ RoleName: roleName })));
1290
1379
  if (role) {
1291
- if (!role.Role?.Tags?.some((t) => t.Key === CREATED_BY2 && t.Value === "debugkit")) bail(`Role ${roleName} exists and wasn't created by deBug. deBug won't change it.`);
1380
+ if (!role.Role?.Tags?.some((t) => t.Key === CREATED_BY2 && t.Value === "debugkit")) fail(opts, `Role ${roleName} exists and wasn't created by deBug. deBug won't change it.`);
1292
1381
  roleArn = role.Role.Arn;
1293
1382
  } else {
1294
1383
  roleArn = (await iam.send(
@@ -1314,7 +1403,7 @@ async function hostAws(cfg, local) {
1314
1403
  const fn = await lookup(() => lambda.send(new lambdaMod.GetFunctionCommand({ FunctionName: functionName })));
1315
1404
  const fnConfig = { FunctionName: functionName, Role: roleArn, Handler: "index.handler", Runtime: "nodejs22.x", MemorySize: 1024, Timeout: 30 };
1316
1405
  if (fn) {
1317
- if (fn.Tags?.[CREATED_BY2] !== "debugkit") bail(`Function ${functionName} exists and wasn't created by deBug. deBug won't overwrite it.`);
1406
+ if (fn.Tags?.[CREATED_BY2] !== "debugkit") fail(opts, `Function ${functionName} exists and wasn't created by deBug. deBug won't overwrite it.`);
1318
1407
  await lambda.send(new lambdaMod.UpdateFunctionCodeCommand({ FunctionName: functionName, ZipFile: zip }));
1319
1408
  await waitUpdated2(lambda, lambdaMod, functionName);
1320
1409
  } else {
@@ -1387,7 +1476,7 @@ function detectApp(cwd) {
1387
1476
  try {
1388
1477
  pkg = JSON.parse(readFileSync5(join6(cwd, "package.json"), "utf8"));
1389
1478
  } catch {
1390
- throw new Error(`No package.json in ${cwd}. Run npx debugkit init from your app's folder.`);
1479
+ throw new Error(`No package.json in ${cwd}. Run ${cmdFor("init")} from your app's folder.`);
1391
1480
  }
1392
1481
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
1393
1482
  const has = (d) => d in deps;
@@ -1404,7 +1493,7 @@ function detectApp(cwd) {
1404
1493
  reactNavigation: has("@react-navigation/native"),
1405
1494
  packageManager: existsSync6(join6(cwd, "pnpm-lock.yaml")) ? "pnpm" : existsSync6(join6(cwd, "yarn.lock")) ? "yarn" : existsSync6(join6(cwd, "bun.lockb")) || existsSync6(join6(cwd, "bun.lock")) ? "bun" : "npm",
1406
1495
  hasSdk: has("@debugkit/sdk"),
1407
- missingExpoModules: platform === "expo" ? ["expo-device", "expo-application"].filter((m) => !has(m)) : [],
1496
+ missingNativeModules: (platform === "expo" ? ["expo-device", "expo-application", "react-native-device-info"] : platform === "react-native" ? ["react-native-device-info"] : []).filter((m) => !has(m)),
1408
1497
  sourceDir: existsSync6(join6(cwd, "src")) ? "src" : ".",
1409
1498
  envPrefix,
1410
1499
  typescript: existsSync6(join6(cwd, "tsconfig.json")) || has("typescript")
@@ -1426,7 +1515,117 @@ function installCommand(pm, pkgs) {
1426
1515
  }
1427
1516
  }
1428
1517
 
1518
+ // ../schema/src/frames.ts
1519
+ var LIBRARY = /* @__PURE__ */ new Set([
1520
+ // axios
1521
+ "dispatchXhrRequest",
1522
+ "throwIfCancellationRequested",
1523
+ "AxiosError",
1524
+ "onloadend",
1525
+ // React Native networking
1526
+ "__didCompleteResponse",
1527
+ "__didReceiveResponse",
1528
+ "__didReceiveData",
1529
+ "setReadyState",
1530
+ // Hermes / React Native runtime (also in InternalBytecode.js, which is never in-app)
1531
+ "tryCallOne",
1532
+ "tryCallTwo",
1533
+ "doResolve",
1534
+ "handleResolved",
1535
+ "finale",
1536
+ "flushedQueue",
1537
+ "invokeCallbackAndReturnFlushedQueue",
1538
+ "callFunctionReturnFlushedQueue",
1539
+ "__callFunction",
1540
+ "__guard",
1541
+ "callTimers",
1542
+ "_callTimer",
1543
+ "_allocateCallback",
1544
+ "asyncGeneratorStep",
1545
+ "_asyncToGenerator",
1546
+ "_next",
1547
+ "_throw",
1548
+ // React (renderer and events)
1549
+ "executeDispatch",
1550
+ "executeDispatchesInOrder",
1551
+ "processDispatchQueue",
1552
+ "dispatchEvent",
1553
+ "dispatchEventForPluginEventSystem",
1554
+ "batchedUpdatesImpl",
1555
+ "batchedUpdates$1",
1556
+ "batchedUpdates",
1557
+ "invokeGuardedCallbackImpl",
1558
+ "invokeGuardedCallback",
1559
+ "commitRootImpl",
1560
+ "performSyncWorkOnRoot",
1561
+ "renderWithHooks",
1562
+ "mountIndeterminateComponent",
1563
+ "beginWork",
1564
+ "flushPassiveEffects",
1565
+ "commitHookEffectListMount",
1566
+ // TanStack Query
1567
+ "#executeFetch"
1568
+ ]);
1569
+ var LIBRARY_AT_TOP = /* @__PURE__ */ new Set([
1570
+ // axios
1571
+ "xhr",
1572
+ "_request",
1573
+ "request",
1574
+ "wrap",
1575
+ "dispatchRequest",
1576
+ "transformData",
1577
+ "settle",
1578
+ "createError",
1579
+ "handleLoad",
1580
+ "handleError",
1581
+ "handleTimeout",
1582
+ // Babel's async helpers, when they're in the bundle rather than in Hermes' InternalBytecode
1583
+ "step",
1584
+ "spawn",
1585
+ // React Native networking
1586
+ "send",
1587
+ "sendRequest",
1588
+ "fetch",
1589
+ // TanStack Query
1590
+ "fetchFn",
1591
+ "fetchQuery",
1592
+ "executeMutation",
1593
+ "run",
1594
+ "start",
1595
+ "refetch",
1596
+ "onFetch"
1597
+ ]);
1598
+ function cleanFnName(fn) {
1599
+ if (!fn) return fn;
1600
+ return fn.replace(/^\?anon_\d+_/, "");
1601
+ }
1602
+ var RN_BUNDLE = /\.(?:js)?bundle\b/;
1603
+ function markLibraryFrames(frames) {
1604
+ let underLibrary = false;
1605
+ let seenBundleFrame = false;
1606
+ return frames.map((f) => {
1607
+ if (!f.file || !RN_BUNDLE.test(f.file)) return f;
1608
+ const name = cleanFnName(f.fn);
1609
+ const library = !!name && (LIBRARY.has(name) || underLibrary && LIBRARY_AT_TOP.has(name));
1610
+ if (library) {
1611
+ if (!seenBundleFrame) underLibrary = true;
1612
+ } else if (f.inApp !== false) underLibrary = false;
1613
+ seenBundleFrame = true;
1614
+ return library && f.inApp !== false ? { ...f, inApp: false } : f;
1615
+ });
1616
+ }
1617
+
1618
+ // ../schema/src/taxonomy.ts
1619
+ var OWNERS = ["app", "backend", "infrastructure", "third_party", "unknown"];
1620
+ var IMPACTS = ["blocked", "degraded", "silent"];
1621
+ var IMPACT_ORDER = Object.fromEntries(IMPACTS.map((impact, i) => [impact, IMPACTS.length - 1 - i]));
1622
+
1623
+ // ../schema/src/hosts.ts
1624
+ var OWNER_SET = new Set(OWNERS.filter((o) => o !== "unknown"));
1625
+
1429
1626
  // ../schema/src/core.ts
1627
+ var MAX_CAPTURED_BODY = 16384;
1628
+ var MAX_BREADCRUMBS = 50;
1430
1629
  var LATENCY_BUCKETS_MS = [50, 100, 200, 300, 500, 750, 1e3, 1500, 2e3, 3e3, 5e3, 1e4];
1431
1630
  function latencyBucket(ms) {
1432
1631
  const i = LATENCY_BUCKETS_MS.findIndex((edge) => ms <= edge);
@@ -1435,7 +1634,6 @@ function latencyBucket(ms) {
1435
1634
  var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
1436
1635
  var GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
1437
1636
  var NOT_IN_APP = [/node_modules/, /\bnative\b/, /\[native code\]/, /InternalBytecode/];
1438
- var RN_BUNDLE = /\.(?:js)?bundle\b/;
1439
1637
  function cleanFile(file) {
1440
1638
  return file.replace(/^address at /, "");
1441
1639
  }
@@ -1456,7 +1654,7 @@ function parseStack(stack) {
1456
1654
  });
1457
1655
  if (frames.length >= 100) break;
1458
1656
  }
1459
- return frames;
1657
+ return markLibraryFrames(frames);
1460
1658
  }
1461
1659
 
1462
1660
  // ../sdk/src/context.ts
@@ -1464,10 +1662,11 @@ function mergeContext(a, b) {
1464
1662
  const out = { ...a };
1465
1663
  for (const [k, v] of Object.entries(b)) {
1466
1664
  const prev = out[k];
1467
- out[k] = v && typeof v === "object" && prev && typeof prev === "object" ? { ...prev, ...v } : v ?? prev;
1665
+ out[k] = v && typeof v === "object" && prev && typeof prev === "object" ? { ...prev, ...defined(v) } : v ?? prev;
1468
1666
  }
1469
1667
  return out;
1470
1668
  }
1669
+ var defined = (o) => Object.fromEntries(Object.entries(o).filter(([, x]) => x !== void 0));
1471
1670
  function safe(fn) {
1472
1671
  try {
1473
1672
  return fn();
@@ -1530,6 +1729,41 @@ function safeDecode(s) {
1530
1729
  return s;
1531
1730
  }
1532
1731
  }
1732
+ var MAX_BODY_CHARS = 64 * 1024;
1733
+ var BODY_WAIT_MS = 3e3;
1734
+ var TEXT_TYPE = /^(?:text\/|application\/(?:[\w.+-]*json|[\w.+-]*xml|x-www-form-urlencoded|problem\+json|javascript))/i;
1735
+ function describeBody(body, type) {
1736
+ if (body === void 0 || body === null || body === "") return {};
1737
+ if (typeof body === "string") return { text: body.slice(0, MAX_BODY_CHARS) };
1738
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) return { text: body.toString().slice(0, MAX_BODY_CHARS) };
1739
+ if (typeof ArrayBuffer !== "undefined" && (body instanceof ArrayBuffer || ArrayBuffer.isView(body))) return { binary: { bytes: body.byteLength, type } };
1740
+ const blob = body;
1741
+ if (typeof blob.size === "number") return { binary: { bytes: blob.size, type: typeof blob.type === "string" && blob.type ? blob.type : type } };
1742
+ return { binary: { type: type ?? "multipart/form-data" } };
1743
+ }
1744
+ function headerValue(headers, name) {
1745
+ if (!headers) return void 0;
1746
+ const lower = name.toLowerCase();
1747
+ return Object.entries(headers).find(([k]) => k.toLowerCase() === lower)?.[1];
1748
+ }
1749
+ function headerRecord(h) {
1750
+ if (!h) return void 0;
1751
+ const out = {};
1752
+ const pairs = h;
1753
+ if (typeof pairs.forEach === "function" && !Array.isArray(h)) pairs.forEach((v, k) => out[k] = String(v));
1754
+ else if (Array.isArray(h)) for (const [k, v] of h) out[k] = String(v);
1755
+ else for (const [k, v] of Object.entries(h)) out[k] = String(v);
1756
+ return out;
1757
+ }
1758
+ function parseRawHeaders(raw) {
1759
+ if (!raw) return void 0;
1760
+ const out = {};
1761
+ for (const line of raw.split(/\r?\n/)) {
1762
+ const i = line.indexOf(":");
1763
+ if (i > 0) out[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim();
1764
+ }
1765
+ return out;
1766
+ }
1533
1767
  var insideFetch = 0;
1534
1768
  function instrumentFetch(sink) {
1535
1769
  const orig = g.fetch;
@@ -1540,6 +1774,15 @@ function instrumentFetch(sink) {
1540
1774
  const method = String(init2?.method ?? input?.method ?? "GET").toUpperCase();
1541
1775
  const start = Date.now();
1542
1776
  const stack = new Error().stack;
1777
+ let sent = {};
1778
+ if (sink.capturesBodies()) {
1779
+ try {
1780
+ const requestHeaders = headerRecord(init2?.headers ?? input?.headers);
1781
+ const body = describeBody(init2?.body, headerValue(requestHeaders, "content-type"));
1782
+ sent = { requestHeaders, requestBody: body.text, requestBinary: body.binary };
1783
+ } catch {
1784
+ }
1785
+ }
1543
1786
  let p2;
1544
1787
  insideFetch++;
1545
1788
  try {
@@ -1549,12 +1792,41 @@ function instrumentFetch(sink) {
1549
1792
  }
1550
1793
  return p2.then(
1551
1794
  (res) => {
1552
- sink.request({ method, url, status: res.status, durationMs: Date.now() - start, stack });
1795
+ let clone;
1796
+ let failedResponse = {};
1797
+ try {
1798
+ if (sink.wantsBody(res.status, url)) {
1799
+ const type = res.headers?.get?.("content-type") ?? void 0;
1800
+ if (sink.capturesBodies()) failedResponse.responseHeaders = headerRecord(res.headers);
1801
+ if (!type || TEXT_TYPE.test(type)) clone = res.clone();
1802
+ else {
1803
+ const length = Number(res.headers.get("content-length"));
1804
+ failedResponse = { ...failedResponse, responseBinary: { bytes: Number.isFinite(length) && length > 0 ? length : void 0, type } };
1805
+ }
1806
+ }
1807
+ } catch {
1808
+ clone = void 0;
1809
+ }
1810
+ const addBody = sink.request({ method, url, status: res.status, durationMs: Date.now() - start, stack, bodyPending: !!clone, ...sent, ...failedResponse });
1811
+ if (clone && addBody) {
1812
+ let done = false;
1813
+ const finish = (body) => {
1814
+ if (done) return;
1815
+ done = true;
1816
+ clearTimeout(timer);
1817
+ addBody(body);
1818
+ };
1819
+ const timer = setTimeout(() => finish(""), BODY_WAIT_MS);
1820
+ clone.text().then(
1821
+ (body) => finish(body.slice(0, MAX_BODY_CHARS)),
1822
+ () => finish("")
1823
+ );
1824
+ }
1553
1825
  return res;
1554
1826
  },
1555
1827
  (error) => {
1556
1828
  const aborted = error?.name === "AbortError";
1557
- sink.request({ method, url, error, aborted, durationMs: Date.now() - start, stack });
1829
+ sink.request({ method, url, error, aborted, durationMs: Date.now() - start, stack, ...sent });
1558
1830
  throw error;
1559
1831
  }
1560
1832
  );
@@ -1565,39 +1837,102 @@ function instrumentFetch(sink) {
1565
1837
  if (g.fetch === wrapped) g.fetch = orig;
1566
1838
  };
1567
1839
  }
1840
+ function decodeUtf8(buf) {
1841
+ if (buf.byteLength > MAX_BODY_CHARS) return void 0;
1842
+ const bytes = new Uint8Array(buf);
1843
+ if (typeof TextDecoder !== "undefined") return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1844
+ let escaped = "";
1845
+ for (const b of bytes) escaped += `%${b.toString(16).padStart(2, "0")}`;
1846
+ return decodeURIComponent(escaped);
1847
+ }
1848
+ function readXhrBody(x) {
1849
+ let type;
1850
+ try {
1851
+ type = x.getResponseHeader?.("content-type") ?? void 0;
1852
+ const kind = x.responseType ?? "";
1853
+ if (kind === "" || kind === "text") return { text: x.responseText?.slice(0, MAX_BODY_CHARS) };
1854
+ if (kind === "json" && x.response != null) return { text: JSON.stringify(x.response).slice(0, MAX_BODY_CHARS) };
1855
+ if (kind === "arraybuffer" && x.response instanceof ArrayBuffer) {
1856
+ const text3 = decodeUtf8(x.response);
1857
+ return text3 !== void 0 ? { text: text3 } : { binary: { bytes: x.response.byteLength, type } };
1858
+ }
1859
+ const blob = x.response;
1860
+ return { binary: { bytes: typeof blob?.size === "number" ? blob.size : void 0, type } };
1861
+ } catch {
1862
+ return x.response instanceof ArrayBuffer ? { binary: { bytes: x.response.byteLength, type } } : {};
1863
+ }
1864
+ }
1568
1865
  function instrumentXhr(sink) {
1569
1866
  const X = g.XMLHttpRequest;
1570
1867
  const proto = X?.prototype;
1571
1868
  if (!proto || proto.open.__debug) return;
1572
1869
  const open = proto.open;
1573
1870
  const send = proto.send;
1871
+ const setRequestHeader = proto.setRequestHeader;
1574
1872
  const wrappedOpen = function(method, url, ...rest) {
1575
1873
  const u = String(url);
1576
1874
  this.__debug = insideFetch > 0 || sink.ignored(u) ? null : { method: String(method).toUpperCase(), url: u };
1577
1875
  return open.call(this, method, url, ...rest);
1578
1876
  };
1877
+ const wrappedSetRequestHeader = function(name, value) {
1878
+ const d = this.__debug;
1879
+ if (d && sink.capturesBodies()) (d.headers ??= {})[String(name)] = String(value);
1880
+ return setRequestHeader?.call(this, name, value);
1881
+ };
1579
1882
  const wrappedSend = function(...args) {
1580
1883
  const d = this.__debug;
1581
1884
  if (d) {
1885
+ let sent = {};
1886
+ if (sink.capturesBodies()) {
1887
+ try {
1888
+ const body = describeBody(args[0], headerValue(d.headers, "content-type"));
1889
+ sent = { requestHeaders: d.headers, requestBody: body.text, requestBinary: body.binary };
1890
+ } catch {
1891
+ }
1892
+ }
1582
1893
  const start = Date.now();
1583
1894
  const stack = new Error().stack;
1584
1895
  let aborted = false;
1585
1896
  let timedOut = false;
1586
1897
  this.addEventListener("abort", () => aborted = true);
1587
1898
  this.addEventListener("timeout", () => timedOut = true);
1588
- this.addEventListener(
1589
- "loadend",
1590
- () => sink.request({ ...d, status: this.status || void 0, aborted, timedOut, durationMs: Date.now() - start, stack })
1591
- );
1899
+ this.addEventListener("loadend", () => {
1900
+ const status = this.status || void 0;
1901
+ const failed = status !== void 0 && sink.wantsBody(status, d.url);
1902
+ const body = failed ? readXhrBody(this) : {};
1903
+ let responseHeaders;
1904
+ if (failed && sink.capturesBodies()) {
1905
+ try {
1906
+ responseHeaders = parseRawHeaders(this.getAllResponseHeaders?.());
1907
+ } catch {
1908
+ responseHeaders = void 0;
1909
+ }
1910
+ }
1911
+ sink.request({
1912
+ method: d.method,
1913
+ url: d.url,
1914
+ status,
1915
+ aborted,
1916
+ timedOut,
1917
+ durationMs: Date.now() - start,
1918
+ stack,
1919
+ responseBody: body.text,
1920
+ responseBinary: body.binary,
1921
+ responseHeaders,
1922
+ ...sent
1923
+ });
1924
+ });
1592
1925
  }
1593
1926
  return send.apply(this, args);
1594
1927
  };
1595
1928
  wrappedOpen.__debug = true;
1596
1929
  proto.open = wrappedOpen;
1597
1930
  proto.send = wrappedSend;
1931
+ if (setRequestHeader) proto.setRequestHeader = wrappedSetRequestHeader;
1598
1932
  return () => {
1599
1933
  proto.open = open;
1600
1934
  proto.send = send;
1935
+ if (setRequestHeader) proto.setRequestHeader = setRequestHeader;
1601
1936
  };
1602
1937
  }
1603
1938
  function format(arg) {
@@ -1649,8 +1984,8 @@ function describeElement(el) {
1649
1984
  const tag = el.tagName.toLowerCase();
1650
1985
  const label = el.getAttribute("aria-label") || el.getAttribute("data-testid") || el.getAttribute("title") || (tag === "input" ? el.getAttribute("name") || el.type : el.innerText || el.textContent || "");
1651
1986
  const id = el.id ? `#${el.id}` : "";
1652
- const text2 = label.replace(/\s+/g, " ").trim().slice(0, 60);
1653
- return `${tag}${id}${text2 ? ` "${text2}"` : ""}`;
1987
+ const text3 = label.replace(/\s+/g, " ").trim().slice(0, 60);
1988
+ return `${tag}${id}${text3 ? ` "${text3}"` : ""}`;
1654
1989
  }
1655
1990
  function instrumentClicks(sink) {
1656
1991
  const d = g.document;
@@ -1679,10 +2014,195 @@ function instrumentWebLifecycle(sink) {
1679
2014
  };
1680
2015
  }
1681
2016
 
2017
+ // ../sdk/src/redact.ts
2018
+ var REDACTED = "[redacted]";
2019
+ var SECRET_FIELDS = [
2020
+ "password",
2021
+ "pin",
2022
+ "otp",
2023
+ "otpcode",
2024
+ "verificationcode",
2025
+ "cvv",
2026
+ "cvc",
2027
+ "cardnumber",
2028
+ "pan",
2029
+ "idtoken",
2030
+ "accesstoken",
2031
+ "refreshtoken",
2032
+ "token",
2033
+ "secret",
2034
+ "apikey"
2035
+ ];
2036
+ var SECRET_HEADERS = ["authorization", "proxy-authorization", "cookie", "set-cookie"];
2037
+ var SECRET_HEADER_WORDS = /token|key|secret/i;
2038
+ var JWT = /eyJ[\w-]+\.[\w-]+\.[\w-]*(?:\.[\w-]*){0,2}/g;
2039
+ var CARD_CANDIDATE = /\d(?:[ ._-]?\d){12,18}/g;
2040
+ var MAX_HEADERS = 50;
2041
+ var MAX_HEADER_VALUE = 1e3;
2042
+ function luhn(digits) {
2043
+ let sum = 0;
2044
+ for (let i = 0; i < digits.length; i++) {
2045
+ let d = Number(digits[digits.length - 1 - i]);
2046
+ if (i % 2 === 1) {
2047
+ d *= 2;
2048
+ if (d > 9) d -= 9;
2049
+ }
2050
+ sum += d;
2051
+ }
2052
+ return sum % 10 === 0;
2053
+ }
2054
+ function redactValues(text3) {
2055
+ return text3.replace(JWT, REDACTED).replace(CARD_CANDIDATE, (m, offset, whole) => {
2056
+ if (/\d/.test(whole[offset - 1] ?? "") || /\d/.test(whole[offset + m.length] ?? "")) return m;
2057
+ const digits = m.replace(/\D/g, "");
2058
+ return luhn(digits) ? `\u2022\u2022\u2022\u2022 ${digits.slice(-4)}` : m;
2059
+ });
2060
+ }
2061
+ var PERSONAL_TEXT = /[^\s@<>"']+@[^\s@<>"']+\.[^\s@<>"']+|\+?\d(?:[\s().-]?\d){6,}/g;
2062
+ function maskPersonal(text3) {
2063
+ return text3.replace(PERSONAL_TEXT, "\u2022\u2022\u2022");
2064
+ }
2065
+ var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2066
+ function redactKeyValues(text3, fields) {
2067
+ if (fields.size === 0) return text3;
2068
+ const names = [...fields].map(escapeRe).join("|");
2069
+ const quoted = new RegExp(`((["'])(?:${names})\\2\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"?|'[^']*'?|[^,}\\]\\s]+)`, "gi");
2070
+ const bare = new RegExp(`((?:^|[\\s,{;&?])(?:${names})\\s*[:=]\\s*)("(?:[^"\\\\]|\\\\.)*"?|[^,}\\]\\s&;]+)`, "gi");
2071
+ return text3.replace(quoted, (_m, key) => `${key}"${REDACTED}"`).replace(bare, (_m, key) => `${key}${REDACTED}`);
2072
+ }
2073
+ function secretFields(opts) {
2074
+ return /* @__PURE__ */ new Set([...SECRET_FIELDS, ...(opts.fields ?? []).map((f) => f.toLowerCase())]);
2075
+ }
2076
+ function redactJson(value, fields) {
2077
+ if (typeof value === "string") return redactTextWith(value, fields);
2078
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1e12) {
2079
+ const masked2 = redactValues(String(value));
2080
+ return masked2 === String(value) ? value : masked2;
2081
+ }
2082
+ if (Array.isArray(value)) return value.map((v) => redactJson(v, fields));
2083
+ if (value && typeof value === "object") {
2084
+ const out = {};
2085
+ for (const [k, v] of Object.entries(value)) out[k] = fields.has(k.toLowerCase()) ? REDACTED : redactJson(v, fields);
2086
+ return out;
2087
+ }
2088
+ return value;
2089
+ }
2090
+ function formField(key) {
2091
+ let name = key;
2092
+ try {
2093
+ name = decodeURIComponent(key.replace(/\+/g, " "));
2094
+ } catch {
2095
+ }
2096
+ return (/([^[\].]+)\]?$/.exec(name)?.[1] ?? name).toLowerCase();
2097
+ }
2098
+ function redactForm(text3, fields) {
2099
+ return text3.split("&").map((pair) => {
2100
+ const eq = pair.indexOf("=");
2101
+ if (eq < 0) return redactValues(pair);
2102
+ const key = pair.slice(0, eq);
2103
+ return fields.has(formField(key)) ? `${key}=${encodeURIComponent(REDACTED)}` : redactValues(pair);
2104
+ }).join("&");
2105
+ }
2106
+ function redactTextWith(text3, fields) {
2107
+ const trimmed = text3.trim();
2108
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2109
+ try {
2110
+ return JSON.stringify(redactJson(JSON.parse(trimmed), fields));
2111
+ } catch {
2112
+ }
2113
+ }
2114
+ if (trimmed.includes("=") && !/\s/.test(trimmed)) return redactForm(trimmed, fields);
2115
+ return redactValues(redactKeyValues(text3, fields));
2116
+ }
2117
+ function redactText(text3, opts = {}) {
2118
+ return redactTextWith(text3, secretFields(opts));
2119
+ }
2120
+ function redactHeaders(headers, opts = {}) {
2121
+ if (!headers) return void 0;
2122
+ const extra = new Set((opts.headers ?? []).map((h) => h.toLowerCase()));
2123
+ const out = {};
2124
+ for (const [name, value] of Object.entries(headers).slice(0, MAX_HEADERS)) {
2125
+ const lower = name.toLowerCase();
2126
+ out[lower] = SECRET_HEADERS.includes(lower) || extra.has(lower) || SECRET_HEADER_WORDS.test(lower) ? REDACTED : redactValues(String(value)).slice(0, MAX_HEADER_VALUE);
2127
+ }
2128
+ return out;
2129
+ }
2130
+ function captureBody(text3, maxChars, opts = {}) {
2131
+ if (text3 === void 0 || text3 === "") return {};
2132
+ const redacted = redactText(text3, opts);
2133
+ if (redacted.length <= maxChars) return { body: redacted, bodySize: redacted.length };
2134
+ const kb = Math.ceil(redacted.length / 1024);
2135
+ return { body: `${redacted.slice(0, maxChars)}\u2026[truncated, ${kb} KB total]`, bodySize: redacted.length, truncated: true };
2136
+ }
2137
+ function bodyOf(text3, binary, maxChars, opts = {}) {
2138
+ return binary ? binaryBody(binary.bytes, binary.type) : captureBody(text3, maxChars, opts);
2139
+ }
2140
+ function binaryBody(bytes, type) {
2141
+ const size = bytes === void 0 ? "" : ` ${Math.max(1, Math.ceil(bytes / 1024))} KB`;
2142
+ return { body: `[binary${size}${type ? `, ${type}` : ""}]`, bodySize: bytes };
2143
+ }
2144
+
2145
+ // ../sdk/src/network.ts
2146
+ var MAX_TEXT = 200;
2147
+ var MAX_ERRORS = 500;
2148
+ function findBase(url, baseUrls) {
2149
+ const lower = url.toLowerCase();
2150
+ return baseUrls.map((b) => b.replace(/\/+$/, "")).filter((b) => b && lower.startsWith(b.toLowerCase()) && /^(?:[/?#]|$)/.test(url.slice(b.length))).sort((a, b) => b.length - a.length)[0];
2151
+ }
2152
+ function nameRequest(url, baseUrls = []) {
2153
+ const base = findBase(url, baseUrls);
2154
+ const masked2 = normaliseUrl(base ? url.slice(base.length) || "/" : url);
2155
+ const slash = masked2.indexOf("/");
2156
+ const host = !base && slash > 0 ? masked2.slice(0, slash) : "";
2157
+ const path2 = host ? masked2.slice(slash) : masked2.startsWith("/") ? masked2 : `/${masked2}`;
2158
+ const first = path2.split("/").find(Boolean);
2159
+ return { service: host || first || "/", path: path2, matched: !!base };
2160
+ }
2161
+ function text2(v) {
2162
+ return typeof v === "string" && v.trim() ? v.trim().slice(0, MAX_TEXT) : void 0;
2163
+ }
2164
+ function masked(v) {
2165
+ return v === void 0 ? void 0 : maskPersonal(redactValues(v));
2166
+ }
2167
+ function flattenErrors(v) {
2168
+ const parts = [];
2169
+ if (Array.isArray(v)) {
2170
+ for (const e of v) {
2171
+ const s = typeof e === "string" ? e : text2(e?.message) ?? text2(e?.detail);
2172
+ if (s) parts.push(s);
2173
+ }
2174
+ } else if (v && typeof v === "object") {
2175
+ for (const [field, msgs] of Object.entries(v)) {
2176
+ const list = (Array.isArray(msgs) ? msgs : [msgs]).filter((m) => typeof m === "string");
2177
+ if (list.length) parts.push(`${field}: ${list.join(", ")}`);
2178
+ }
2179
+ }
2180
+ const joined = parts.join("; ").slice(0, MAX_ERRORS);
2181
+ return joined || void 0;
2182
+ }
2183
+ function readProblemDetails(body) {
2184
+ if (!body) return void 0;
2185
+ let json;
2186
+ try {
2187
+ json = JSON.parse(body);
2188
+ } catch {
2189
+ return void 0;
2190
+ }
2191
+ if (!json || typeof json !== "object" || Array.isArray(json)) return void 0;
2192
+ const o = json;
2193
+ const title = masked(text2(o.title) ?? text2(o.message) ?? text2(o.error));
2194
+ const code2 = typeof o.code === "number" || text2(o.code) ? o.code : null;
2195
+ const traceId = text2(o.traceId) ?? text2(o.traceID) ?? text2(o.trace_id) ?? text2(o.correlationId) ?? null;
2196
+ const errors = masked(flattenErrors(o.errors)) ?? null;
2197
+ if (!title && code2 === null && !traceId && !errors) return void 0;
2198
+ return { backendTitle: title ?? null, backendCode: code2, traceId, backendErrors: errors };
2199
+ }
2200
+
1682
2201
  // ../sdk/src/client.ts
1683
2202
  var SDK_NAME = "@debugkit/sdk";
1684
2203
  var SDK_VERSION = typeof __DEBUGKIT_SDK_VERSION__ === "string" ? __DEBUGKIT_SDK_VERSION__ : "0.0.0-dev";
1685
2204
  var QUEUE_KEY = "@debugkit/queue";
2205
+ var MAX_BATCH_CHARS = 384 * 1024;
1686
2206
  var ANON_KEY = "@debugkit/anonymousId";
1687
2207
  function webStorage() {
1688
2208
  try {
@@ -1705,6 +2225,9 @@ var DebugClient = class {
1705
2225
  user = { anonymousId: uid() };
1706
2226
  timer;
1707
2227
  flushing;
2228
+ /** Tags on every error and event: deBug's own sources (device facts), then the app's. */
2229
+ tagSources = [];
2230
+ globalTags = {};
1708
2231
  /** The batch being uploaded: still saved, so a crash mid-upload doesn't lose it. */
1709
2232
  inflight = [];
1710
2233
  /** Saved events from the last run, read once; saves wait for it so they don't overwrite them. */
@@ -1712,18 +2235,24 @@ var DebugClient = class {
1712
2235
  backoffUntil = 0;
1713
2236
  failures = 0;
1714
2237
  ready = false;
2238
+ /** Set by close(): nothing more is recorded or queued until the next init(). */
2239
+ closed = false;
1715
2240
  handlersInstalled = false;
1716
2241
  auto = { errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false, sessions: false };
1717
2242
  restores = [];
1718
2243
  sessionState = { errored: false, crashed: false };
1719
2244
  lastNav;
2245
+ /** Failures waiting for their response body (fetch), reported on close if it hasn't come. */
2246
+ pendingReports = /* @__PURE__ */ new Set();
1720
2247
  limits = /* @__PURE__ */ new Map();
1721
2248
  /** fetch as it was before instrumentation, so our own uploads are never recorded. */
1722
2249
  rawFetch;
1723
2250
  init(options) {
1724
2251
  if (this.timer) clearInterval(this.timer);
1725
2252
  this.uninstrument();
1726
- this.opts = { flushIntervalMs: 5e3, maxBatch: 50, maxBreadcrumbs: 30, ...options };
2253
+ this.opts = { flushIntervalMs: 5e3, maxBatch: 50, ...options, maxBreadcrumbs: Math.min(options.maxBreadcrumbs ?? 30, MAX_BREADCRUMBS) };
2254
+ this.closed = false;
2255
+ this.globalTags = { ...options.tags };
1727
2256
  if (options.enabled === false) {
1728
2257
  this.ready = false;
1729
2258
  this.queue = [];
@@ -1762,9 +2291,17 @@ var DebugClient = class {
1762
2291
  }
1763
2292
  /** Record a navigation breadcrumb ("from → to"). Repeated paths are ignored. */
1764
2293
  navigated(to) {
1765
- if (!to || to === this.lastNav) return;
1766
- this.breadcrumb("navigation", this.lastNav ? `${this.lastNav} \u2192 ${to}` : to);
1767
- this.lastNav = to;
2294
+ if (this.closed || !to || to === this.lastNav) return;
2295
+ try {
2296
+ this.breadcrumb("navigation", this.lastNav ? `${this.lastNav} \u2192 ${to}` : to);
2297
+ this.lastNav = String(to);
2298
+ } catch (err) {
2299
+ this.log("navigation breadcrumb failed", err);
2300
+ }
2301
+ }
2302
+ /** The screen the app is on, from the last navigation breadcrumb. */
2303
+ get screen() {
2304
+ return this.lastNav;
1768
2305
  }
1769
2306
  get initialized() {
1770
2307
  return this.ready;
@@ -1781,19 +2318,48 @@ var DebugClient = class {
1781
2318
  setContext(patch) {
1782
2319
  if (this.opts) this.opts.context = mergeContext(this.opts.context ?? {}, patch);
1783
2320
  }
2321
+ /** Add or change tags on every later error and event. A value of undefined removes the tag. */
2322
+ setTags(tags) {
2323
+ for (const [k, v] of Object.entries(tags)) {
2324
+ if (v === void 0) delete this.globalTags[k];
2325
+ else this.globalTags[k] = String(v);
2326
+ }
2327
+ }
2328
+ /**
2329
+ * A function whose tags go on every error and event (the React Native entry adds device
2330
+ * facts this way). Read when each event happens; a source that throws is skipped.
2331
+ */
2332
+ addTagSource(source) {
2333
+ this.tagSources.push(source);
2334
+ return () => {
2335
+ this.tagSources = this.tagSources.filter((s) => s !== source);
2336
+ };
2337
+ }
1784
2338
  setUser(id) {
1785
2339
  this.user = { ...this.user, id };
1786
2340
  }
2341
+ /** Record a breadcrumb. Never throws; does nothing after close(). */
1787
2342
  breadcrumb(category, message, data, level = "info") {
1788
- const msg = message.slice(0, 500);
2343
+ if (this.closed) return;
2344
+ try {
2345
+ this.addCrumb(category, message, data, level);
2346
+ } catch (err) {
2347
+ this.log("breadcrumb failed", err);
2348
+ }
2349
+ }
2350
+ /** Records a breadcrumb and returns the one stored (a repeat collapses into the last). */
2351
+ addCrumb(category, message, data, level) {
2352
+ const msg = String(message).slice(0, 500);
1789
2353
  const last = this.crumbs[this.crumbs.length - 1];
1790
2354
  if (last && last.category === category && last.message === msg && last.level === level) {
1791
2355
  last.ts = now();
1792
2356
  last.data = { ...data, repeated: Number(last.data?.repeated ?? 1) + 1 };
1793
- return;
2357
+ return last;
1794
2358
  }
1795
- this.crumbs.push({ ts: now(), category, message: msg, data, level });
2359
+ const crumb = { ts: now(), category, message: msg, data, level };
2360
+ this.crumbs.push(crumb);
1796
2361
  if (this.crumbs.length > (this.opts?.maxBreadcrumbs ?? 30)) this.crumbs.shift();
2362
+ return crumb;
1797
2363
  }
1798
2364
  /** Log an error. `flow` is the part of the app it belongs to, e.g. "auth.login". */
1799
2365
  error(err, meta = {}) {
@@ -1843,13 +2409,32 @@ var DebugClient = class {
1843
2409
  this.timings.clear();
1844
2410
  this.timingsSince = Date.now();
1845
2411
  }
2412
+ /**
2413
+ * How many queued events the next upload takes: at most `maxBatch`, and no more than about
2414
+ * 384 KB of events (ingest refuses uploads over 512 KB), but always at least one.
2415
+ */
2416
+ batchSize() {
2417
+ let size = 0;
2418
+ let n = 0;
2419
+ for (const e of this.queue) {
2420
+ if (n >= this.opts.maxBatch) break;
2421
+ try {
2422
+ size += JSON.stringify(e).length;
2423
+ } catch {
2424
+ size += 1024;
2425
+ }
2426
+ if (n > 0 && size > MAX_BATCH_CHARS) break;
2427
+ n++;
2428
+ }
2429
+ return Math.max(1, n);
2430
+ }
1846
2431
  async flush() {
1847
2432
  this.queueTimings(this.closing);
1848
2433
  if (this.flushing) await this.flushing.catch(() => {
1849
2434
  });
1850
2435
  if (this.flushing) return this.flushing;
1851
2436
  if (!this.ready || this.queue.length === 0 || Date.now() < this.backoffUntil) return;
1852
- const batch = this.queue.splice(0, this.opts.maxBatch);
2437
+ const batch = this.queue.splice(0, this.batchSize());
1853
2438
  this.inflight = batch;
1854
2439
  this.flushing = this.send(batch).then(() => {
1855
2440
  this.failures = 0;
@@ -1868,16 +2453,23 @@ var DebugClient = class {
1868
2453
  }
1869
2454
  /** Stop the flush timer, undo automatic instrumentation and send what is queued. */
1870
2455
  closing = false;
2456
+ /**
2457
+ * Sends what is queued and stops: automatic capture is removed, and errors, events, sessions
2458
+ * and breadcrumbs are ignored until the next init(). A remote kill switch can rely on it.
2459
+ */
1871
2460
  close() {
1872
2461
  if (this.timer) clearInterval(this.timer);
1873
2462
  this.uninstrument();
2463
+ for (const report of [...this.pendingReports]) report();
2464
+ this.closed = true;
2465
+ this.lastNav = void 0;
1874
2466
  this.closing = true;
1875
2467
  return this.flush().finally(() => this.closing = false);
1876
2468
  }
1877
2469
  /* ---------------- internals ---------------- */
1878
2470
  /** @internal Used by the platform entry points for errors that have no thrown value. */
1879
- captureError(e, meta, request) {
1880
- if (!this.ready) return;
2471
+ captureError(e, meta, request, breadcrumbs = [...this.crumbs], response) {
2472
+ if (!this.ready || this.closed) return;
1881
2473
  const handled = meta.handled ?? true;
1882
2474
  const frames = e.frames ?? parseStack(e.stack);
1883
2475
  if (!meta.fatal && !this.allowError(`${e.name}|${e.message.slice(0, 120)}|${frames[0]?.file ?? ""}:${frames[0]?.line ?? ""}`)) return;
@@ -1901,8 +2493,9 @@ var DebugClient = class {
1901
2493
  severity: meta.severity ?? (meta.fatal ? "critical" : void 0),
1902
2494
  handled,
1903
2495
  error: { name: e.name, message: e.message, stack: e.stack, frames },
1904
- breadcrumbs: [...this.crumbs],
1905
- request
2496
+ breadcrumbs,
2497
+ request,
2498
+ response
1906
2499
  });
1907
2500
  }
1908
2501
  /** Per-minute limits: one runaway error can't flood the queue, the network or your database. */
@@ -1929,11 +2522,11 @@ var DebugClient = class {
1929
2522
  }
1930
2523
  /** Queue without sampling (sessions must be complete for crash-free rates to be right). */
1931
2524
  push(e) {
1932
- if (!this.ready) return;
1933
- let out = e;
2525
+ if (!this.ready || this.closed && !this.closing) return;
2526
+ let out = e.type === "error" || e.type === "event" ? this.withTags(e) : e;
1934
2527
  if (this.opts.beforeSend) {
1935
2528
  try {
1936
- out = this.opts.beforeSend(e);
2529
+ out = this.opts.beforeSend(out);
1937
2530
  } catch (err) {
1938
2531
  this.log("beforeSend threw; sending the event unchanged", err);
1939
2532
  }
@@ -1944,6 +2537,30 @@ var DebugClient = class {
1944
2537
  if (out.type === "error" || this.queue.length >= this.opts.maxBatch) void this.flush();
1945
2538
  else void this.persist();
1946
2539
  }
2540
+ /** deBug's tag sources, then the app's global tags, then enrich(), then the event's own tags. */
2541
+ withTags(e) {
2542
+ const tags = {};
2543
+ const add = (t) => {
2544
+ if (!t) return;
2545
+ for (const [k, v] of Object.entries(t)) if (v !== void 0 && v !== null) tags[k.slice(0, 100)] = String(v).slice(0, 200);
2546
+ };
2547
+ for (const source of this.tagSources) {
2548
+ try {
2549
+ add(source());
2550
+ } catch {
2551
+ }
2552
+ }
2553
+ add(this.globalTags);
2554
+ if (this.opts.enrich) {
2555
+ try {
2556
+ add(this.opts.enrich(e));
2557
+ } catch (err) {
2558
+ this.log("enrich threw; skipped", err);
2559
+ }
2560
+ }
2561
+ add(e.tags);
2562
+ return Object.keys(tags).length ? { ...e, tags } : e;
2563
+ }
1947
2564
  buildContext() {
1948
2565
  const c = this.opts.context ?? {};
1949
2566
  return {
@@ -2105,7 +2722,9 @@ var DebugClient = class {
2105
2722
  void this.flush();
2106
2723
  }
2107
2724
  },
2108
- ignored: (url) => this.isIgnored(url)
2725
+ ignored: (url) => this.isIgnored(url),
2726
+ wantsBody: (status, url) => this.isFailedStatus(status, url),
2727
+ capturesBodies: () => !!this.bodiesOption()
2109
2728
  };
2110
2729
  }
2111
2730
  isIgnored(url) {
@@ -2114,26 +2733,96 @@ var DebugClient = class {
2114
2733
  if (url.includes(ep) || /\/symbolicate\b|\/logs(?:\?|$)/.test(url)) return true;
2115
2734
  return (this.opts.network?.ignoreUrls ?? []).some((p2) => typeof p2 === "string" ? url.includes(p2) : p2.test(url));
2116
2735
  }
2736
+ isFailedStatus(status, rawUrl) {
2737
+ try {
2738
+ return (this.opts.network?.isFailure ?? ((s) => s >= 500))(status, normaliseUrl(rawUrl));
2739
+ } catch {
2740
+ return false;
2741
+ }
2742
+ }
2743
+ /**
2744
+ * Records one request: a breadcrumb now, in call order, and an error for a failure. When the
2745
+ * body is still being read (fetch), returns a function that adds what the backend said to the
2746
+ * breadcrumb and then reports the error, since an error is sent as soon as it is queued.
2747
+ */
2117
2748
  recordRequest(r) {
2118
2749
  if (!this.ready) return;
2119
2750
  const net = this.opts.network ?? {};
2120
2751
  const url = normaliseUrl(r.url);
2121
2752
  const ms = Math.round(r.durationMs);
2122
- const failed = r.status === void 0 ? !r.aborted : (net.isFailure ?? ((s) => s >= 500))(r.status, url);
2753
+ const failed = r.status === void 0 ? !r.aborted : this.isFailedStatus(r.status, r.url);
2123
2754
  const slow = ms >= (net.slowMs ?? 3e3);
2124
- const outcome = r.aborted ? "aborted" : r.timedOut ? "timed out" : r.status !== void 0 ? String(r.status) : "failed";
2125
- this.breadcrumb("network", `${r.method} ${url} \u2192 ${outcome} (${ms}ms)`, { status: r.status ?? null, durationMs: ms }, failed ? "error" : slow ? "warning" : "info");
2755
+ const [ended, outcome] = r.aborted ? ["aborted", "aborted"] : r.timedOut ? ["timed out", "unreachable"] : r.status !== void 0 ? [String(r.status), "answered"] : ["failed", "unreachable"];
2756
+ const name = nameRequest(r.url, net.baseUrls);
2757
+ const data = {
2758
+ service: name.service,
2759
+ path: name.path,
2760
+ method: r.method,
2761
+ status: r.status ?? null,
2762
+ durationMs: ms,
2763
+ outcome,
2764
+ ...failed && readProblemDetails(r.responseBody)
2765
+ };
2766
+ const crumb = this.addCrumb("network", `${r.method} ${name.matched ? name.path : url} \u2192 ${ended} (${ms}ms)`, data, failed ? "error" : slow ? "warning" : "info");
2126
2767
  if (!r.aborted) this.timeRequest(`${r.method} ${url}`, ms, failed);
2127
2768
  if (!failed) return;
2128
2769
  const flow = net.flows?.find(([p2]) => typeof p2 === "string" ? url.includes(p2) : p2.test(url))?.[1];
2129
2770
  const cause = r.error ? normaliseError(r.error) : void 0;
2130
2771
  const message = r.status !== void 0 ? `${r.method} ${url} responded ${r.status}` : `${r.method} ${url} ${r.timedOut ? "timed out" : "failed"}${cause ? `: ${cause.message}` : ""}`;
2131
- const frames = parseStack(r.stack).slice(1);
2132
- this.captureError(
2133
- { name: r.status !== void 0 ? "HttpError" : "NetworkError", message, stack: r.stack, frames },
2134
- { flow, handled: true, tags: { source: "network" } },
2135
- { method: r.method, url, status: r.status, durationMs: ms }
2136
- );
2772
+ const frames = markLibraryFrames(parseStack(r.stack).slice(1));
2773
+ const trail = [...this.crumbs];
2774
+ const bodies = this.bodiesOption();
2775
+ if (bodies) data.hasBodies = true;
2776
+ const report = (responseBody = r.responseBody) => {
2777
+ const http = bodies ? this.describeFailedCall(r, responseBody, bodies) : void 0;
2778
+ this.captureError(
2779
+ { name: r.status !== void 0 ? "HttpError" : "NetworkError", message, stack: r.stack, frames },
2780
+ { flow, handled: true, tags: { source: "network" } },
2781
+ { method: r.method, url, status: r.status, durationMs: ms, ...http?.request },
2782
+ trail,
2783
+ http?.response
2784
+ );
2785
+ };
2786
+ if (!r.bodyPending) return report();
2787
+ let done = false;
2788
+ const finish = (responseBody) => {
2789
+ if (done) return;
2790
+ done = true;
2791
+ this.pendingReports.delete(finishNow);
2792
+ const backend = readProblemDetails(responseBody);
2793
+ if (backend) crumb.data = { ...crumb.data, ...backend };
2794
+ report(responseBody);
2795
+ };
2796
+ const finishNow = () => finish();
2797
+ this.pendingReports.add(finishNow);
2798
+ return (responseBody) => finish(responseBody);
2799
+ }
2800
+ /** `network.bodies` when it is on, else undefined: the one place that decides. */
2801
+ bodiesOption() {
2802
+ const b = this.opts.network?.bodies;
2803
+ return b?.onFailure ? b : void 0;
2804
+ }
2805
+ /** A failed call's request and response, redacted and cut, for `network.bodies`. Never throws. */
2806
+ describeFailedCall(r, responseBody, bodies) {
2807
+ try {
2808
+ const max = bodies.maxChars ?? MAX_CAPTURED_BODY;
2809
+ const redact = bodies.redact ?? {};
2810
+ const rawQuery = /\?([^#]*)/.exec(r.url)?.[1];
2811
+ const request = {
2812
+ query: rawQuery ? redactText(rawQuery, redact).slice(0, max) : void 0,
2813
+ headers: redactHeaders(r.requestHeaders, redact),
2814
+ ...bodyOf(r.requestBody, r.requestBinary, max, redact)
2815
+ };
2816
+ const response = r.status === void 0 ? void 0 : {
2817
+ status: r.status,
2818
+ headers: redactHeaders(r.responseHeaders, redact),
2819
+ ...bodyOf(responseBody, r.responseBinary, max, redact)
2820
+ };
2821
+ return { request, response };
2822
+ } catch (err) {
2823
+ this.log("couldn't describe the failed call", err);
2824
+ return { request: {} };
2825
+ }
2137
2826
  }
2138
2827
  log(...args) {
2139
2828
  if (this.opts?.debug) console.warn("[deBug]", ...args);
@@ -2162,13 +2851,13 @@ function resolveAuto(o) {
2162
2851
  sessions: pick("sessions")
2163
2852
  };
2164
2853
  }
2165
- var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type === "error" && e.request);
2854
+ var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type === "error" && (e.request || e.response));
2166
2855
  function toLegacy(events) {
2167
2856
  const out = [];
2168
2857
  for (const e of events) {
2169
2858
  if (e.type === "session" || e.type === "metric") continue;
2170
- if (e.type === "error" && e.request) {
2171
- const { request: _r, ...rest } = e;
2859
+ if (e.type === "error" && (e.request || e.response)) {
2860
+ const { request: _r, response: _s, ...rest } = e;
2172
2861
  out.push(rest);
2173
2862
  } else out.push(e);
2174
2863
  }
@@ -2317,7 +3006,7 @@ async function walkthrough(opts) {
2317
3006
  const sent = await sendTestEvents(cfg, app);
2318
3007
  if (sent.error) {
2319
3008
  s.error(`The ingest didn't accept them: ${sent.error}`);
2320
- p.log.warn(cfg.provider === "firebase" ? "A brand-new Cloud Function can take a minute to answer. Try again with npx debugkit test." : "Check the endpoint and key in .debugkit/config.json, then run npx debugkit test.");
3009
+ p.log.warn(cfg.provider === "firebase" ? `A brand-new Cloud Function can take a minute to answer. Try again with ${cmdFor("test")}.` : `Check the endpoint and key in .debugkit/config.json, then run ${cmdFor("test")}.`);
2321
3010
  } else {
2322
3011
  s.message("Sent. Waiting for the dashboard to show them");
2323
3012
  const after = await waitForArrival(cwd, dashboardUrl, cfg.appId);
@@ -2338,7 +3027,7 @@ async function walkthrough(opts) {
2338
3027
  );
2339
3028
  } else {
2340
3029
  s.error("Sent, but the dashboard doesn't show them yet");
2341
- p.log.warn(`The dashboard said: ${after?.status ?? "?"} ${after?.error ?? ""}. Refresh it in a minute, or run npx debugkit test again.`);
3030
+ p.log.warn(`The dashboard said: ${after?.status ?? "?"} ${after?.error ?? ""}. Refresh it in a minute, or run ${cmdFor("test")} again.`);
2342
3031
  }
2343
3032
  }
2344
3033
  await next("What does the SDK do on its own?");
@@ -2405,23 +3094,43 @@ var ENV_ENDPOINT = "DEBUG_ENDPOINT";
2405
3094
  var ENV_KEY = "DEBUG_KEY";
2406
3095
  async function installSdk(app) {
2407
3096
  if (!app.hasSdk) {
2408
- const [cmd, args] = installCommand(app.packageManager, ["@debugkit/sdk"]);
3097
+ const [cmd2, args2] = installCommand(app.packageManager, ["@debugkit/sdk"]);
2409
3098
  if (await yes(`Install ${code("@debugkit/sdk")} with ${app.packageManager}?`)) {
2410
3099
  const s = p.spinner();
2411
- s.start(`${cmd} ${args.join(" ")}`);
2412
- const r = await capture(cmd, args, { cwd: app.cwd });
3100
+ s.start(`${cmd2} ${args2.join(" ")}`);
3101
+ const r = await capture(cmd2, args2, { cwd: app.cwd });
2413
3102
  if (r.code !== 0) {
2414
3103
  s.error("Install failed");
2415
3104
  p.log.error(r.stderr.slice(-800));
2416
- throw new Error("Couldn't install @debugkit/sdk. Install it yourself and run npx debugkit init again.");
3105
+ throw new Error(`Couldn't install @debugkit/sdk. Install it yourself and run ${cmdFor("init")} again.`);
2417
3106
  }
2418
3107
  s.stop(`Installed @debugkit/sdk`);
2419
3108
  app.hasSdk = true;
2420
3109
  }
2421
3110
  }
2422
- if (app.platform === "expo" && app.missingExpoModules.length) {
2423
- const exit = await interactive("npx", ["expo", "install", ...app.missingExpoModules], { cwd: app.cwd });
2424
- if (exit !== 0) p.log.warn("Couldn't install expo-device and expo-application. Run: npx expo install expo-device expo-application");
3111
+ const missing = app.missingNativeModules;
3112
+ if (!missing.length) return;
3113
+ p.note(
3114
+ [
3115
+ `deBug reads the device's model, memory, screen, network and storage with ${missing.map(code).join(", ")}.`,
3116
+ "They're native modules, so they go in your app's own dependencies (React Native only links those),",
3117
+ `and the app needs a ${bold("new native build")} before they work: an over-the-air update can't add them.`,
3118
+ "Until then deBug still works, with fewer device details."
3119
+ ].join("\n"),
3120
+ "Device details"
3121
+ );
3122
+ const [cmd, args] = app.platform === "expo" ? ["npx", ["expo", "install", ...missing]] : installCommand(app.packageManager, missing);
3123
+ const command = `${cmd} ${args.join(" ")}`;
3124
+ const names = missing.join(", ");
3125
+ if (!await yes(`Install ${names}?`)) {
3126
+ p.log.info(dim(`Later: ${command}`));
3127
+ return;
3128
+ }
3129
+ const exit = await interactive(cmd, args, { cwd: app.cwd });
3130
+ if (exit !== 0) p.log.warn(`Couldn't install ${names}. Run: ${command}`);
3131
+ else {
3132
+ app.missingNativeModules = [];
3133
+ p.log.success(`Installed ${names}. Rebuild the app${app.platform === "react-native" ? " (cd ios && pod install first)" : " (eas build, or npx expo run:android / run:ios)"} to link them.`);
2425
3134
  }
2426
3135
  }
2427
3136
  function writeAppEnv(app, conn) {
@@ -2471,7 +3180,8 @@ export const deBug = initExpo({
2471
3180
  return {
2472
3181
  path: path2,
2473
3182
  contents: `${header}import { initReactNative } from "@debugkit/sdk/react-native";
2474
- // Optional, for model and app version: npm install react-native-device-info, then pass deviceInfo: DeviceInfo.
3183
+ // Device details (model, memory, screen, network, storage) are read automatically with
3184
+ // react-native-device-info. Add your own with tags: { \u2026 } or deBug.setTags({ \u2026 }).
2475
3185
 
2476
3186
  export const deBug = initReactNative({
2477
3187
  enabled: ${multiEnv ? "!__DEV__ // release builds only" : "true"},
@@ -2701,46 +3411,69 @@ async function init(cwd, preset) {
2701
3411
  result = provider === "firebase" ? await setupFirebase(ctx) : provider === "aws" ? await setupAws(ctx) : await setupLocal(ctx);
2702
3412
  } catch (err) {
2703
3413
  p.log.error(err.message);
2704
- bail("Setup stopped. Nothing else was changed in your app. Fix the error above and run npx debugkit init again.");
3414
+ bail(`Setup stopped. Nothing else was changed in your app. Fix the error above and run ${cmdFor("init")} again.`);
2705
3415
  }
2706
3416
  const cfg = { ...result.config, ...existing?.provider === provider && existing.hosted ? { hosted: existing.hosted } : {}, appId: app.appId, dashboardPort, retentionDays, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
2707
3417
  writeConfig(cwd, cfg);
2708
3418
  p.note(result.created.map((l) => `\u2022 ${l}`).join("\n"), "Created");
2709
3419
  printValues("Your ingest endpoint and key (the key is public: it ships in your app):", { endpoint: cfg.endpoint, key: cfg.ingestKey });
2710
- const remaining = await wireApp(app, cfg);
2711
3420
  await prepareDashboardEnv(cwd, result.dashboardEnv, dashboardPort);
3421
+ let hostedUrl = cfg.hosted?.url;
3422
+ let hostedLive = false;
3423
+ if (provider !== "local") {
3424
+ p.note(
3425
+ [
3426
+ `deBug can host the dashboard in your ${provider === "aws" ? "AWS account" : "Firebase project"} too, reading the same data,`,
3427
+ "at a link you can share with your team. It signs in with the same login, and you can still run it locally.",
3428
+ `Skip it and setup carries on; host it later with ${cmdFor("deploy-dashboard")}.`
3429
+ ].join("\n"),
3430
+ "Host the dashboard"
3431
+ );
3432
+ const choice = await choose(
3433
+ hostedUrl ? `The dashboard is hosted at ${hostedUrl}. Update it?` : "Host the dashboard online?",
3434
+ [
3435
+ { value: "host", label: hostedUrl ? "Update it" : "Host it", hint: "a few minutes" },
3436
+ { value: "skip", label: "Skip for now" }
3437
+ ],
3438
+ "host"
3439
+ );
3440
+ for (let attempt = choice === "host"; attempt; ) {
3441
+ try {
3442
+ const out = await hostDashboard(cwd, readConfig(cwd) ?? cfg, { onProblem: "skip", confirmed: true });
3443
+ if (out) [hostedUrl, hostedLive] = [out.url, out.live];
3444
+ attempt = false;
3445
+ } catch (err) {
3446
+ p.log.error(err.message);
3447
+ attempt = await choose("Hosting didn't finish. What now?", [
3448
+ { value: "retry", label: "Retry" },
3449
+ { value: "skip", label: "Skip hosting for now", hint: "setup carries on" }
3450
+ ], "retry") === "retry";
3451
+ if (!attempt) p.log.info(`Setup carries on. Host it later with ${code(cmdFor("deploy-dashboard"))}.`);
3452
+ }
3453
+ }
3454
+ if (choice === "skip") p.log.info(dim(`Skipped. Any time later: ${cmdFor("deploy-dashboard")}`));
3455
+ }
3456
+ const setup = readConfig(cwd) ?? cfg;
3457
+ const remaining = await wireApp(app, setup);
2712
3458
  let dash;
2713
- try {
2714
- dash = await startDashboard(cwd);
2715
- } catch (err) {
2716
- p.log.error(err.message);
2717
- p.outro(`deBug is set up, but the dashboard didn't start. Try ${code(cmdFor("dashboard"))}.`);
2718
- return;
3459
+ if (!(hostedUrl && hostedLive)) {
3460
+ try {
3461
+ dash = await startDashboard(cwd);
3462
+ } catch (err) {
3463
+ p.log.error(err.message);
3464
+ p.outro(`deBug is set up, but the dashboard didn't start. Try ${code(cmdFor("dashboard"))}.`);
3465
+ return;
3466
+ }
2719
3467
  }
2720
- await walkthrough({ cwd, app, cfg, dashboardUrl: dash.url, remaining });
2721
- if (provider === "local") {
3468
+ await walkthrough({ cwd, app, cfg: setup, dashboardUrl: dash?.url ?? hostedUrl, remaining });
3469
+ if (provider === "local" && dash) {
3470
+ const running = dash;
2722
3471
  p.log.info(`The dashboard is your ingest on this setup, so keep it running while you try the app. Stop it with ${code("Ctrl-C")}.`);
2723
3472
  p.outro("deBug is set up.");
2724
- await new Promise((r) => dash.child.once("exit", () => r()));
3473
+ await new Promise((r) => running.child.once("exit", () => r()));
2725
3474
  return;
2726
3475
  }
2727
- dash.stop();
2728
- let hostedUrl = cfg.hosted?.url;
2729
- p.note(
2730
- [
2731
- `The dashboard ran on this machine. deBug can also host it in your ${provider === "aws" ? "AWS account" : "Firebase project"}, reading the same data,`,
2732
- "at a link you can share with your team. It signs in with the same login. You can still run it locally."
2733
- ].join("\n"),
2734
- "Host the dashboard?"
2735
- );
2736
- if (await yes(hostedUrl ? `Update the hosted dashboard at ${hostedUrl}?` : "Host the dashboard online too?", !hostedUrl)) {
2737
- try {
2738
- hostedUrl = (await hostDashboard(cwd, readConfig(cwd) ?? cfg)).url;
2739
- } catch (err) {
2740
- p.log.error(err.message);
2741
- p.log.info(`deBug itself is set up. Try hosting again with ${code(cmdFor("deploy-dashboard"))}.`);
2742
- }
2743
- } else p.log.info(dim(`Any time later: ${cmdFor("deploy-dashboard")}`));
3476
+ dash?.stop();
2744
3477
  const others = listEnvironments(cwd).filter((e) => e !== environment.get());
2745
3478
  p.outro(
2746
3479
  `deBug is set up${envLabel()}. ${hostedUrl ? `Share the dashboard: ${code(hostedUrl)}. ` : ""}Open it locally any time with ${code(cmdFor("dashboard"))}.` + (environment.get() && !others.length ? `
@@ -2751,7 +3484,9 @@ async function deployDashboard(cwd) {
2751
3484
  const cfg = requireConfig(cwd);
2752
3485
  p.intro(`${pc.bgRed(pc.white(" deBug "))} host the dashboard${envLabel()}`);
2753
3486
  if (cfg.provider === "local") bail(`This setup keeps data on this machine, so there's nothing to host. Run ${code(cmdFor("init"))} with Firebase or AWS first.`);
2754
- const { url } = await hostDashboard(cwd, cfg);
3487
+ const out = await hostDashboard(cwd, cfg);
3488
+ if (!out) return;
3489
+ const { url } = out;
2755
3490
  const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_exec(), exec_exports));
2756
3491
  openUrl2(url);
2757
3492
  p.outro(`Share ${code(url)} with your team. ${loginHint(cwd)}`);