@debugkit/cli 0.5.0 → 0.6.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
@@ -60,6 +60,75 @@ var init_exec = __esm({
60
60
  import { randomBytes as randomBytes2 } from "crypto";
61
61
  import { resolve } from "path";
62
62
 
63
+ // src/hosting.ts
64
+ import { createHash } from "crypto";
65
+ import { cpSync, renameSync, existsSync as existsSync5, mkdirSync as mkdirSync3, mkdtempSync, readdirSync, readFileSync as readFileSync4, rmSync, statSync, writeFileSync as writeFileSync3 } from "fs";
66
+ import { tmpdir } from "os";
67
+ import { join as join5, relative } from "path";
68
+ import { zipSync as zipSync2 } from "fflate";
69
+
70
+ // ../adapters/firestore.indexes.json
71
+ var firestore_indexes_default = {
72
+ indexes: [
73
+ {
74
+ collectionGroup: "rollups",
75
+ queryScope: "COLLECTION",
76
+ fields: [
77
+ {
78
+ fieldPath: "dimension",
79
+ order: "ASCENDING"
80
+ },
81
+ {
82
+ fieldPath: "day",
83
+ order: "ASCENDING"
84
+ }
85
+ ]
86
+ },
87
+ {
88
+ collectionGroup: "events",
89
+ queryScope: "COLLECTION",
90
+ fields: [
91
+ {
92
+ fieldPath: "fingerprint",
93
+ order: "ASCENDING"
94
+ },
95
+ {
96
+ fieldPath: "ts",
97
+ order: "DESCENDING"
98
+ }
99
+ ]
100
+ },
101
+ {
102
+ collectionGroup: "users",
103
+ queryScope: "COLLECTION",
104
+ fields: [
105
+ {
106
+ fieldPath: "scope",
107
+ order: "ASCENDING"
108
+ },
109
+ {
110
+ fieldPath: "lastDay",
111
+ order: "ASCENDING"
112
+ }
113
+ ]
114
+ }
115
+ ],
116
+ fieldOverrides: [
117
+ {
118
+ collectionGroup: "events",
119
+ fieldPath: "expireAt",
120
+ ttl: true,
121
+ indexes: []
122
+ },
123
+ {
124
+ collectionGroup: "rollups",
125
+ fieldPath: "expireAt",
126
+ ttl: true,
127
+ indexes: []
128
+ }
129
+ ]
130
+ };
131
+
63
132
  // src/dashboard.ts
64
133
  init_exec();
65
134
  import { spawn as spawn2 } from "child_process";
@@ -113,7 +182,7 @@ function writeConfig(cwd, cfg) {
113
182
  const f = readFile(cwd) ?? {};
114
183
  const out = current ? { ...f, environments: { ...f.environments, [current]: { ...cfg, environment: current } } } : { ...cfg, ...f.environments ? { environments: f.environments } : {} };
115
184
  writeFileSync(config, JSON.stringify(out, null, 2) + "\n");
116
- writeFileSync(join(dir, ".gitignore"), "dashboard*.env\nfirebase*/functions/node_modules/\nfirebase*/functions/.env.*\nfirebase*/.firebase/\n*.log\n");
185
+ writeFileSync(join(dir, ".gitignore"), "dashboard*.env\nfirebase*/functions/node_modules/\nfirebase*/functions/.env.*\nfirebase*/dashboard/node_modules/\nfirebase*/dashboard/.env.*\nfirebase*/dashboard/*.tgz\nfirebase*/hosting-public/\nfirebase*/.firebase/\n*.log\n");
117
186
  }
118
187
  function upsertEnv(file, values) {
119
188
  const lines = existsSync(file) ? readFileSync(file, "utf8").split(/\r?\n/) : [];
@@ -191,7 +260,7 @@ var dim = (s) => pc.dim(s);
191
260
  var bold = (s) => pc.bold(s);
192
261
 
193
262
  // src/dashboard.ts
194
- var VERSION = true ? "0.5.0" : "0.0.0-dev";
263
+ var VERSION = true ? "0.6.0" : "0.0.0-dev";
195
264
  var DASHBOARD_VERSION = VERSION;
196
265
  function hashPassword(password2) {
197
266
  const salt = randomBytes(16);
@@ -309,1618 +378,1939 @@ var loginHint = (cwd) => {
309
378
  return email ? `Sign in as ${code(email)} with the password you chose.` : dim("Sign in with the login in .debugkit/dashboard.env.");
310
379
  };
311
380
 
312
- // src/detect.ts
381
+ // src/hosting.ts
382
+ init_exec();
383
+
384
+ // src/providers/aws.ts
385
+ init_exec();
313
386
  import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
314
- import { join as join3 } from "path";
315
- var PLATFORM_LABEL = {
316
- expo: "Expo",
317
- "react-native": "React Native",
318
- next: "Next.js",
319
- "tanstack-start": "TanStack Start",
320
- "vite-react": "React (Vite)",
321
- react: "React",
322
- node: "Node"
323
- };
324
- function detectApp(cwd) {
325
- let pkg = {};
326
- try {
327
- pkg = JSON.parse(readFileSync2(join3(cwd, "package.json"), "utf8"));
328
- } catch {
329
- throw new Error(`No package.json in ${cwd}. Run npx debugkit init from your app's folder.`);
330
- }
331
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
332
- const has = (d) => d in deps;
333
- const platform = has("expo") ? "expo" : has("react-native") ? "react-native" : has("next") ? "next" : has("@tanstack/react-start") ? "tanstack-start" : has("vite") && has("react") ? "vite-react" : has("react") ? "react" : "node";
334
- const envPrefix = platform === "expo" ? "EXPO_PUBLIC_" : platform === "next" ? "NEXT_PUBLIC_" : platform === "vite-react" || platform === "tanstack-start" ? "VITE_" : void 0;
335
- const name = pkg.name ?? cwd.split(/[\\/]/).pop() ?? "app";
336
- return {
337
- cwd,
338
- name,
339
- appId: toAppId(name),
340
- version: pkg.version,
341
- platform,
342
- expoRouter: has("expo-router"),
343
- reactNavigation: has("@react-navigation/native"),
344
- packageManager: existsSync3(join3(cwd, "pnpm-lock.yaml")) ? "pnpm" : existsSync3(join3(cwd, "yarn.lock")) ? "yarn" : existsSync3(join3(cwd, "bun.lockb")) || existsSync3(join3(cwd, "bun.lock")) ? "bun" : "npm",
345
- hasSdk: has("@debugkit/sdk"),
346
- missingExpoModules: platform === "expo" ? ["expo-device", "expo-application"].filter((m) => !has(m)) : [],
347
- sourceDir: existsSync3(join3(cwd, "src")) ? "src" : ".",
348
- envPrefix,
349
- typescript: existsSync3(join3(cwd, "tsconfig.json")) || has("typescript")
350
- };
351
- }
352
- function toAppId(name) {
353
- return name.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "app";
354
- }
355
- function installCommand(pm, pkgs) {
356
- switch (pm) {
357
- case "pnpm":
358
- return ["pnpm", ["add", ...pkgs]];
359
- case "yarn":
360
- return ["yarn", ["add", ...pkgs]];
361
- case "bun":
362
- return ["bun", ["add", ...pkgs]];
363
- default:
364
- return ["npm", ["install", ...pkgs]];
365
- }
366
- }
387
+ import { homedir } from "os";
388
+ import { dirname, join as join3 } from "path";
389
+ import { fileURLToPath } from "url";
390
+ import { zipSync } from "fflate";
367
391
 
368
- // ../schema/src/core.ts
369
- var LATENCY_BUCKETS_MS = [50, 100, 200, 300, 500, 750, 1e3, 1500, 2e3, 3e3, 5e3, 1e4];
370
- function latencyBucket(ms) {
371
- const i = LATENCY_BUCKETS_MS.findIndex((edge) => ms <= edge);
372
- return i === -1 ? LATENCY_BUCKETS_MS.length : i;
373
- }
374
- var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
375
- var GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
376
- var NOT_IN_APP = [/node_modules/, /\bnative\b/, /\[native code\]/, /InternalBytecode/];
377
- var RN_BUNDLE = /\.(?:js)?bundle\b/;
378
- function cleanFile(file) {
379
- return file.replace(/^address at /, "");
380
- }
381
- function parseStack(stack) {
382
- if (!stack) return [];
383
- const frames = [];
384
- for (const raw of stack.split("\n")) {
385
- const m = V8.exec(raw) ?? GECKO.exec(raw);
386
- if (!m) continue;
387
- const [, fn, rawFile, line, col] = m;
388
- const file = cleanFile(rawFile ?? "");
389
- frames.push({
390
- fn: fn || void 0,
391
- file,
392
- line: Number(line),
393
- col: Number(col),
394
- inApp: RN_BUNDLE.test(file) ? !/^(?:anonymous|eval|global code)$/.test(fn ?? "") : !NOT_IN_APP.some((re) => re.test(file))
395
- });
396
- if (frames.length >= 100) break;
397
- }
398
- return frames;
392
+ // src/keys.ts
393
+ var keyEntry = (key, appId) => `${key}:${appId}`;
394
+ function mergeKeys(existing, key, appId) {
395
+ const pairs = (existing ?? "").split(",").map((s) => s.trim()).filter((s) => /^[^:\s]+:[^:\s]+$/.test(s));
396
+ if (!pairs.some((p2) => p2.split(":")[0] === key)) pairs.push(keyEntry(key, appId));
397
+ return pairs.join(",");
399
398
  }
400
399
 
401
- // ../sdk/src/context.ts
402
- function mergeContext(a, b) {
403
- const out = { ...a };
404
- for (const [k, v] of Object.entries(b)) {
405
- const prev = out[k];
406
- out[k] = v && typeof v === "object" && prev && typeof prev === "object" ? { ...prev, ...v } : v ?? prev;
407
- }
408
- return out;
409
- }
410
- function safe(fn) {
411
- try {
412
- return fn();
413
- } catch {
414
- return void 0;
415
- }
416
- }
417
- function timezone() {
418
- return safe(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
419
- }
420
- function browserContext() {
421
- if (typeof navigator === "undefined" || typeof window === "undefined") {
422
- const ua2 = typeof navigator !== "undefined" ? navigator.userAgent : void 0;
423
- const node = typeof process !== "undefined" ? process.versions?.node : void 0;
424
- return {
425
- runtime: { name: ua2 === "Cloudflare-Workers" ? "cloudflare-workers" : node ? "node" : "edge", version: node },
426
- os: { name: "server" },
427
- timezone: timezone()
428
- };
429
- }
430
- const ua = navigator.userAgent;
431
- const android = /Android ([\d.]+)/.exec(ua)?.[1];
432
- const ios = /(?:iPhone|iPad|iPod).*? OS (\d+[_\d]*)/.exec(ua)?.[1];
433
- const os = android ? { name: "android", version: android } : ios ? { name: "ios", version: ios.replace(/_/g, ".") } : /Mac OS X/.test(ua) ? { name: "macos" } : /Windows/.test(ua) ? { name: "windows" } : /Linux/.test(ua) ? { name: "linux" } : { name: "web" };
434
- const conn = navigator.connection;
435
- const browser = /Edg\/([\d.]+)/.exec(ua) ? { name: "edge", v: /Edg\/([\d.]+)/.exec(ua)[1] } : /Chrome\/([\d.]+)/.exec(ua) ? { name: "chrome", v: /Chrome\/([\d.]+)/.exec(ua)[1] } : /Version\/([\d.]+).*Safari/.exec(ua) ? { name: "safari", v: /Version\/([\d.]+)/.exec(ua)[1] } : /Firefox\/([\d.]+)/.exec(ua) ? { name: "firefox", v: /Firefox\/([\d.]+)/.exec(ua)[1] } : void 0;
436
- return {
437
- os,
438
- runtime: { name: "browser", version: browser ? `${browser.name} ${browser.v}` : void 0 },
439
- device: {
440
- type: /iPad|Tablet/.test(ua) ? "tablet" : /Mobi/.test(ua) ? "phone" : "desktop",
441
- screen: typeof screen !== "undefined" ? { width: screen.width, height: screen.height, scale: window.devicePixelRatio } : void 0
442
- },
443
- network: conn ? {
444
- type: conn.type === "wifi" ? "wifi" : conn.type === "cellular" ? "cellular" : "unknown",
445
- effectiveType: conn.effectiveType,
446
- isConnected: navigator.onLine
447
- } : void 0,
448
- locale: navigator.language,
449
- timezone: timezone()
400
+ // src/providers/types.ts
401
+ var adminEnv = (endpoint, ctx) => ({
402
+ DEBUG_ADMIN_URL: `${endpoint.replace(/\/+$/, "")}/admin`,
403
+ DEBUG_ADMIN_TOKEN: ctx.adminToken,
404
+ DEBUG_RETENTION_DAYS: String(ctx.retentionDays)
405
+ });
406
+
407
+ // src/providers/aws.ts
408
+ var REGIONS = [
409
+ { value: "af-south-1", label: "Cape Town (af-south-1)" },
410
+ { value: "eu-west-1", label: "Ireland (eu-west-1)" },
411
+ { value: "eu-central-1", label: "Frankfurt (eu-central-1)" },
412
+ { value: "us-east-1", label: "N. Virginia (us-east-1)" },
413
+ { value: "us-west-2", label: "Oregon (us-west-2)" },
414
+ { value: "ap-southeast-1", label: "Singapore (ap-southeast-1)" }
415
+ ];
416
+ function awsProfiles(home = homedir()) {
417
+ const out = /* @__PURE__ */ new Map();
418
+ const read = (file, isConfig) => {
419
+ if (!existsSync3(file)) return;
420
+ let cur;
421
+ for (const line of readFileSync2(file, "utf8").split(/\r?\n/)) {
422
+ const h = /^\s*\[\s*(?:profile\s+)?([^\]\s]+)\s*\]/.exec(line);
423
+ if (h) {
424
+ if (isConfig && h[1] && /^sso-session\b/.test(line.replace(/^\s*\[\s*/, ""))) {
425
+ cur = void 0;
426
+ continue;
427
+ }
428
+ cur = out.get(h[1]) ?? { name: h[1], sso: false };
429
+ out.set(cur.name, cur);
430
+ continue;
431
+ }
432
+ const kv = /^\s*([a-z_]+)\s*=\s*(.+?)\s*$/.exec(line);
433
+ if (!cur || !kv) continue;
434
+ if (kv[1] === "region") cur.region = kv[2];
435
+ if (kv[1].startsWith("sso_")) cur.sso = true;
436
+ }
450
437
  };
438
+ read(process.env.AWS_CONFIG_FILE ?? join3(home, ".aws", "config"), true);
439
+ read(process.env.AWS_SHARED_CREDENTIALS_FILE ?? join3(home, ".aws", "credentials"), false);
440
+ return [...out.values()];
451
441
  }
452
-
453
- // ../sdk/src/auto.ts
454
- var g = globalThis;
455
- var ID_SEGMENT = /^(?:\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,}|(?=[^/]*\d)[\w-]{20,})$/i;
456
- function normaliseUrl(raw) {
457
- const m = /^(?:([a-z][a-z0-9+.-]*:)?\/\/([^/?#]*))?([^?#]*)/i.exec(raw.trim());
458
- let host = m?.[2] ?? "";
459
- const path2 = (m?.[3] || "/").split("/").map((s) => ID_SEGMENT.test(s) ? ":id" : s).join("/");
460
- if (host.includes("@")) host = host.slice(host.lastIndexOf("@") + 1);
461
- const here = typeof location !== "undefined" ? location.host : void 0;
462
- return !host || host === here ? path2 : `${host}${path2.startsWith("/") ? "" : "/"}${path2}`;
442
+ function lambdaZip() {
443
+ const here = dirname(fileURLToPath(import.meta.url));
444
+ const file = [join3(here, "lambda", "index.mjs"), join3(here, "..", "dist", "lambda", "index.mjs")].find(existsSync3);
445
+ if (!file) throw new Error("The bundled ingest Lambda is missing. Reinstall debugkit.");
446
+ return zipSync({ "index.mjs": readFileSync2(file) }, { level: 9 });
463
447
  }
464
- var insideFetch = 0;
465
- function instrumentFetch(sink) {
466
- const orig = g.fetch;
467
- if (typeof orig !== "function" || orig.__debug) return;
468
- const wrapped = function(input, init2) {
469
- const url = typeof input === "string" ? input : input?.href ?? input?.url ?? String(input);
470
- if (sink.ignored(url)) return orig.call(this, input, init2);
471
- const method = String(init2?.method ?? input?.method ?? "GET").toUpperCase();
472
- const start = Date.now();
473
- const stack = new Error().stack;
474
- let p2;
475
- insideFetch++;
476
- try {
477
- p2 = orig.call(this, input, init2);
478
- } finally {
479
- insideFetch--;
448
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
449
+ async function setupAws(ctx) {
450
+ p.note(
451
+ [
452
+ "deBug creates a DynamoDB table, a Lambda function with a public URL, and an IAM role in your own AWS account.",
453
+ "It uses an AWS profile on this machine. With AWS SSO (IAM Identity Center) you sign in through your browser; no access keys are needed.",
454
+ "Your credentials stay on this machine. deBug doesn't receive them."
455
+ ].join("\n"),
456
+ "Sign in to AWS"
457
+ );
458
+ const profiles = awsProfiles();
459
+ const SSO = "__sso__";
460
+ const ENV = "__env__";
461
+ const options = [
462
+ ...profiles.map((x) => ({ value: x.name, label: x.name, hint: [x.sso ? "SSO" : "keys", x.region].filter(Boolean).join(" \xB7 ") })),
463
+ ...process.env.AWS_ACCESS_KEY_ID ? [{ value: ENV, label: "Credentials from the environment (AWS_ACCESS_KEY_ID)" }] : [],
464
+ { value: SSO, label: "Sign in with AWS SSO (IAM Identity Center)", hint: which("aws") ? "opens your browser" : "needs the AWS CLI" }
465
+ ];
466
+ let profile = await choose("Which AWS credentials should deBug use?", options, profiles[0]?.name ?? SSO);
467
+ if (profile === SSO) {
468
+ if (!which("aws")) bail("AWS SSO sign-in needs the AWS CLI: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html");
469
+ const name = await ask("Name for the new AWS profile", { initial: "debugkit" });
470
+ p.log.step(`Running ${code(`aws configure sso --profile ${name}`)}. It asks for your SSO start URL and region, then opens your browser to approve access.`);
471
+ if (await interactive("aws", ["configure", "sso", "--profile", name]) !== 0) bail("AWS SSO setup didn't finish.");
472
+ profile = name;
473
+ } else if (profile === ENV) profile = void 0;
474
+ const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
475
+ const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
476
+ const defaultRegion = profiles.find((x) => x.name === profile)?.region ?? process.env.AWS_REGION ?? "af-south-1";
477
+ const region = await choose("Which AWS region?", REGIONS.some((r) => r.value === defaultRegion) ? REGIONS : [{ value: defaultRegion, label: defaultRegion }, ...REGIONS], defaultRegion);
478
+ const credentials = fromNodeProviderChain(profile ? { profile } : {});
479
+ const base = { region, credentials };
480
+ let identity;
481
+ try {
482
+ identity = await new STSClient(base).send(new GetCallerIdentityCommand({}));
483
+ } catch (err) {
484
+ const sso = profiles.find((x) => x.name === profile)?.sso;
485
+ if (sso && which("aws")) {
486
+ p.log.info("Your SSO session has expired. Signing in again.");
487
+ if (await interactive("aws", ["sso", "login", "--profile", profile]) !== 0) bail("AWS SSO sign-in didn't finish.");
488
+ identity = await new STSClient({ region, credentials: fromNodeProviderChain({ profile }) }).send(new GetCallerIdentityCommand({}));
489
+ } else bail(`Those AWS credentials didn't work: ${err.message}`);
490
+ }
491
+ p.log.success(`Signed in to AWS account ${code(identity.Account ?? "?")} ${dim(identity.Arn ?? "")}`);
492
+ if (!identity.Account) bail("AWS didn't say which account these credentials belong to.");
493
+ const account = identity.Account;
494
+ const table = await ask("DynamoDB table name", {
495
+ 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, _ . -"
497
+ });
498
+ const functionName = `debugkit-ingest-${table}`.slice(0, 64);
499
+ const roleName = `debugkit-ingest-${table}-${region}`.slice(0, 64);
500
+ await next(`Create the table, role and function in ${region}`);
501
+ const s = p.spinner();
502
+ const [ddbMod, iamMod, lambdaMod] = await Promise.all([import("@aws-sdk/client-dynamodb"), import("@aws-sdk/client-iam"), import("@aws-sdk/client-lambda")]);
503
+ const ddb = new ddbMod.DynamoDBClient(base);
504
+ s.start(`Checking DynamoDB table ${table}`);
505
+ let tableArn;
506
+ let ownTable = false;
507
+ const found = await lookup(() => ddb.send(new ddbMod.DescribeTableCommand({ TableName: table })));
508
+ if (found) {
509
+ tableArn = found.Table?.TableArn;
510
+ const tags = await ddb.send(new ddbMod.ListTagsOfResourceCommand({ ResourceArn: tableArn }));
511
+ ownTable = !!tags.Tags?.some((t) => t.Key === CREATED_BY && t.Value === "debugkit");
512
+ const keys = Object.fromEntries((found.Table?.KeySchema ?? []).map((k) => [k.KeyType, k.AttributeName]));
513
+ const types = Object.fromEntries((found.Table?.AttributeDefinitions ?? []).map((a) => [a.AttributeName, a.AttributeType]));
514
+ if (keys.HASH !== "pk" || keys.RANGE !== "sk" || types.pk !== "S" || types.sk !== "S") {
515
+ s.error(`Table ${table} exists with a different key schema`);
516
+ bail(`${table} isn't a deBug table (it needs string keys pk and sk). Run again and choose another table name.`);
480
517
  }
481
- return p2.then(
482
- (res) => {
483
- sink.request({ method, url, status: res.status, durationMs: Date.now() - start, stack });
484
- return res;
485
- },
486
- (error) => {
487
- const aborted = error?.name === "AbortError";
488
- sink.request({ method, url, error, aborted, durationMs: Date.now() - start, stack });
489
- throw error;
490
- }
518
+ s.stop(ownTable ? `Reusing deBug's table ${table}` : `Table ${table} exists and wasn't created by deBug`);
519
+ if (!ownTable && !await yes(`Store deBug's data in your existing table ${table}? deBug only adds its own items (pk APPS and APP#\u2026).`, false))
520
+ bail("Run again and choose a new table name.");
521
+ } else {
522
+ s.message(`Creating DynamoDB table ${table}`);
523
+ const out = await ddb.send(
524
+ new ddbMod.CreateTableCommand({
525
+ TableName: table,
526
+ BillingMode: "PAY_PER_REQUEST",
527
+ AttributeDefinitions: [
528
+ { AttributeName: "pk", AttributeType: "S" },
529
+ { AttributeName: "sk", AttributeType: "S" }
530
+ ],
531
+ KeySchema: [
532
+ { AttributeName: "pk", KeyType: "HASH" },
533
+ { AttributeName: "sk", KeyType: "RANGE" }
534
+ ],
535
+ Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
536
+ })
491
537
  );
492
- };
493
- wrapped.__debug = true;
494
- g.fetch = wrapped;
495
- return () => {
496
- if (g.fetch === wrapped) g.fetch = orig;
497
- };
498
- }
499
- function instrumentXhr(sink) {
500
- const X = g.XMLHttpRequest;
501
- const proto = X?.prototype;
502
- if (!proto || proto.open.__debug) return;
503
- const open = proto.open;
504
- const send = proto.send;
505
- const wrappedOpen = function(method, url, ...rest) {
506
- const u = String(url);
507
- this.__debug = insideFetch > 0 || sink.ignored(u) ? null : { method: String(method).toUpperCase(), url: u };
508
- return open.call(this, method, url, ...rest);
509
- };
510
- const wrappedSend = function(...args) {
511
- const d = this.__debug;
512
- if (d) {
513
- const start = Date.now();
514
- const stack = new Error().stack;
515
- let aborted = false;
516
- let timedOut = false;
517
- this.addEventListener("abort", () => aborted = true);
518
- this.addEventListener("timeout", () => timedOut = true);
519
- this.addEventListener(
520
- "loadend",
521
- () => sink.request({ ...d, status: this.status || void 0, aborted, timedOut, durationMs: Date.now() - start, stack })
522
- );
538
+ tableArn = out.TableDescription?.TableArn;
539
+ ownTable = true;
540
+ let active = false;
541
+ for (let i = 0; i < 90 && !active; i++) {
542
+ active = (await ddb.send(new ddbMod.DescribeTableCommand({ TableName: table }))).Table?.TableStatus === "ACTIVE";
543
+ if (!active) await sleep(2e3);
523
544
  }
524
- return send.apply(this, args);
525
- };
526
- wrappedOpen.__debug = true;
527
- proto.open = wrappedOpen;
528
- proto.send = wrappedSend;
529
- return () => {
530
- proto.open = open;
531
- proto.send = send;
532
- };
533
- }
534
- function format(arg) {
535
- if (typeof arg === "string") return arg;
536
- if (arg instanceof Error) return `${arg.name}: ${arg.message}`;
537
- try {
538
- return JSON.stringify(arg) ?? String(arg);
539
- } catch {
540
- return String(arg);
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.`);
541
546
  }
542
- }
543
- function instrumentConsole(sink) {
544
- const c = g.console;
545
- if (!c) return;
546
- const restores = [];
547
- for (const [method, level] of [["warn", "warning"], ["error", "error"]]) {
548
- const orig = c[method];
549
- if (typeof orig !== "function") continue;
550
- c[method] = function(...args) {
551
- if (args[0] !== "[deBug]") sink.crumb("log", args.map(format).join(" ").slice(0, 500), level);
552
- return orig.apply(this, args);
553
- };
554
- restores.push(() => c[method] = orig);
547
+ if (!tableArn) throw new Error(`AWS didn't return the ARN for table ${table}.`);
548
+ const ttl = (await ddb.send(new ddbMod.DescribeTimeToLiveCommand({ TableName: table }))).TimeToLiveDescription;
549
+ const ttlOn = ttl?.TimeToLiveStatus === "ENABLED" || ttl?.TimeToLiveStatus === "ENABLING";
550
+ if (ttlOn && ttl?.AttributeName !== "ttl") {
551
+ p.log.warn(`${table} already expires items on "${ttl?.AttributeName}", so deBug's raw events won't expire on their own. Clean them up yourself, or use a separate table.`);
552
+ } else if (!ttlOn) {
553
+ await ddb.send(new ddbMod.UpdateTimeToLiveCommand({ TableName: table, TimeToLiveSpecification: { AttributeName: "ttl", Enabled: true } }));
555
554
  }
556
- return () => restores.forEach((r) => r());
557
- }
558
- var path = () => typeof location !== "undefined" ? location.pathname : "";
559
- function instrumentHistory(sink) {
560
- const h = g.history;
561
- if (typeof window === "undefined" || !h?.pushState || typeof g.addEventListener !== "function") return;
562
- const orig = { pushState: h.pushState, replaceState: h.replaceState };
563
- for (const k of ["pushState", "replaceState"]) {
564
- h[k] = function(...args) {
565
- const out = orig[k].apply(this, args);
566
- sink.navigated(path());
567
- return out;
568
- };
555
+ p.log.success(`DynamoDB table ${table} is ready (30-day expiry on raw events)`);
556
+ const iam = new iamMod.IAMClient(base);
557
+ s.start(`Setting up IAM role ${roleName}`);
558
+ let roleArn;
559
+ let newRole = false;
560
+ const role = await lookup(() => iam.send(new iamMod.GetRoleCommand({ RoleName: roleName })));
561
+ if (role) {
562
+ if (!role.Role?.Tags?.some((t) => t.Key === CREATED_BY && t.Value === "debugkit")) {
563
+ s.error(`Role ${roleName} exists and wasn't created by deBug`);
564
+ bail(`deBug won't change a role it didn't create. Delete or rename ${roleName}, or choose another table name.`);
565
+ }
566
+ roleArn = role.Role.Arn;
567
+ } else {
568
+ roleArn = (await iam.send(
569
+ new iamMod.CreateRoleCommand({
570
+ RoleName: roleName,
571
+ Description: `deBug ingest Lambda: writes to the DynamoDB table ${table}`.slice(0, 1e3),
572
+ AssumeRolePolicyDocument: JSON.stringify({
573
+ Version: "2012-10-17",
574
+ Statement: [{ Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole", Condition: { StringEquals: { "aws:SourceAccount": account } } }]
575
+ }),
576
+ Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
577
+ })
578
+ )).Role.Arn;
579
+ newRole = true;
569
580
  }
570
- const onPop = () => sink.navigated(path());
571
- g.addEventListener("popstate", onPop);
572
- sink.navigated(path());
573
- return () => {
574
- Object.assign(h, orig);
575
- g.removeEventListener("popstate", onPop);
576
- };
577
- }
578
- var CLICKABLE = 'button,a,[role="button"],[role="link"],[role="tab"],[role="menuitem"],input[type="submit"],input[type="button"],input[type="checkbox"],input[type="radio"],summary,label,[data-testid]';
579
- function describeElement(el) {
580
- const tag = el.tagName.toLowerCase();
581
- const label = el.getAttribute("aria-label") || el.getAttribute("data-testid") || el.getAttribute("title") || (tag === "input" ? el.getAttribute("name") || el.type : el.innerText || el.textContent || "");
582
- const id = el.id ? `#${el.id}` : "";
583
- const text2 = label.replace(/\s+/g, " ").trim().slice(0, 60);
584
- return `${tag}${id}${text2 ? ` "${text2}"` : ""}`;
585
- }
586
- function instrumentClicks(sink) {
587
- const d = g.document;
588
- if (!d?.addEventListener) return;
589
- const onClick = (ev) => {
590
- const t = ev.target;
591
- const el = t?.closest?.(CLICKABLE);
592
- if (el) sink.crumb("ui", `Clicked ${describeElement(el)}`);
593
- };
594
- d.addEventListener("click", onClick, true);
595
- return () => d.removeEventListener("click", onClick, true);
596
- }
597
- function instrumentWebLifecycle(sink) {
598
- const d = g.document;
599
- if (typeof window === "undefined" || !d?.addEventListener) return;
600
- const onVis = () => sink.lifecycle(d.visibilityState === "hidden" ? "background" : "foreground");
601
- const onOnline = () => sink.crumb("network", "Device went online");
602
- const onOffline = () => sink.crumb("network", "Device went offline", "warning");
603
- d.addEventListener("visibilitychange", onVis);
604
- g.addEventListener("online", onOnline);
605
- g.addEventListener("offline", onOffline);
606
- return () => {
607
- d.removeEventListener("visibilitychange", onVis);
608
- g.removeEventListener("online", onOnline);
609
- g.removeEventListener("offline", onOffline);
610
- };
611
- }
612
-
613
- // ../sdk/src/client.ts
614
- var SDK_NAME = "@debugkit/sdk";
615
- var SDK_VERSION = "0.5.0";
616
- var QUEUE_KEY = "@debugkit/queue";
617
- var ANON_KEY = "@debugkit/anonymousId";
618
- function webStorage() {
619
- try {
620
- const ls = globalThis.localStorage;
621
- if (!ls) return void 0;
622
- ls.getItem(ANON_KEY);
623
- return ls;
624
- } catch {
625
- return void 0;
626
- }
627
- }
628
- var MAX_QUEUE = 500;
629
- var uid = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`).replace(/-/g, "");
630
- var now = () => (/* @__PURE__ */ new Date()).toISOString();
631
- var DebugClient = class {
632
- opts;
633
- queue = [];
634
- crumbs = [];
635
- session = { id: uid(), startedAt: now() };
636
- user = { anonymousId: uid() };
637
- timer;
638
- flushing;
639
- backoffUntil = 0;
640
- failures = 0;
641
- ready = false;
642
- handlersInstalled = false;
643
- auto = { errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false, sessions: false };
644
- restores = [];
645
- sessionState = { errored: false, crashed: false };
646
- lastNav;
647
- limits = /* @__PURE__ */ new Map();
648
- /** fetch as it was before instrumentation, so our own uploads are never recorded. */
649
- rawFetch;
650
- init(options) {
651
- if (this.timer) clearInterval(this.timer);
652
- this.uninstrument();
653
- this.opts = { flushIntervalMs: 5e3, maxBatch: 50, maxBreadcrumbs: 30, ...options };
654
- if (options.enabled === false) {
655
- this.ready = false;
656
- this.queue = [];
657
- this.log("disabled for this build (enabled: false)");
658
- return this;
581
+ await iam.send(new iamMod.AttachRolePolicyCommand({ RoleName: roleName, PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" }));
582
+ await iam.send(
583
+ new iamMod.PutRolePolicyCommand({
584
+ RoleName: roleName,
585
+ PolicyName: "debugkit-table-write",
586
+ PolicyDocument: JSON.stringify({
587
+ Version: "2012-10-17",
588
+ Statement: [{ Effect: "Allow", Action: ["dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:BatchWriteItem", "dynamodb:GetItem"], Resource: tableArn }]
589
+ })
590
+ })
591
+ );
592
+ s.stop(`IAM role ${roleName} can write to ${table} and nothing else`);
593
+ const lambda = new lambdaMod.LambdaClient(base);
594
+ const zip = lambdaZip();
595
+ s.start(`Deploying Lambda ${functionName}`);
596
+ const fn = await lookup(() => lambda.send(new lambdaMod.GetFunctionCommand({ FunctionName: functionName })));
597
+ if (fn) {
598
+ if (fn.Tags?.[CREATED_BY] !== "debugkit") {
599
+ s.error(`Function ${functionName} exists and wasn't created by deBug`);
600
+ bail(`deBug won't overwrite a function it didn't create. Rename ${functionName}, or choose another table name.`);
659
601
  }
660
- if (!this.opts.context && typeof window !== "undefined") this.opts.context = browserContext();
661
- this.auto = resolveAuto(options);
662
- this.rawFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.__raw ?? globalThis.fetch : void 0;
663
- this.ready = true;
664
- this.loadAnonymousId();
665
- void this.restore();
666
- if (this.auto.errors && !this.handlersInstalled) this.installGlobalHandlers();
667
- this.instrument();
668
- if (this.auto.sessions) this.startSession();
669
- if (this.opts.flushIntervalMs > 0) {
670
- this.timer = setInterval(() => void this.flush(), this.opts.flushIntervalMs);
671
- this.timer.unref?.();
602
+ const keys = mergeKeys(fn.Configuration?.Environment?.Variables?.DEBUG_INGEST_KEYS, ctx.ingestKey, ctx.app.appId);
603
+ await lambda.send(new lambdaMod.UpdateFunctionCodeCommand({ FunctionName: functionName, ZipFile: zip }));
604
+ await waitUpdated(lambda, lambdaMod, functionName);
605
+ await lambda.send(
606
+ new lambdaMod.UpdateFunctionConfigurationCommand({
607
+ FunctionName: functionName,
608
+ Role: roleArn,
609
+ Environment: {
610
+ Variables: { ...fn.Configuration?.Environment?.Variables, DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keys, DEBUG_RETENTION_DAYS: String(ctx.retentionDays), DEBUG_ADMIN_TOKEN: ctx.adminToken }
611
+ }
612
+ })
613
+ );
614
+ } else {
615
+ const env = { Variables: { DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId), DEBUG_RETENTION_DAYS: String(ctx.retentionDays), DEBUG_ADMIN_TOKEN: ctx.adminToken } };
616
+ for (let attempt = 0; ; attempt++) {
617
+ try {
618
+ await lambda.send(
619
+ new lambdaMod.CreateFunctionCommand({
620
+ FunctionName: functionName,
621
+ Runtime: "nodejs22.x",
622
+ Architectures: ["arm64"],
623
+ Handler: "index.handler",
624
+ Role: roleArn,
625
+ Code: { ZipFile: zip },
626
+ MemorySize: 256,
627
+ Timeout: 10,
628
+ Environment: env,
629
+ Description: "deBug ingest: receives SDK events and writes them to DynamoDB",
630
+ Tags: { [CREATED_BY]: "debugkit" }
631
+ })
632
+ );
633
+ break;
634
+ } catch (err) {
635
+ if (attempt < 10 && /cannot be assumed|role defined for the function/i.test(err.message)) {
636
+ s.message(newRole ? "Waiting for the new IAM role to be ready" : "Retrying");
637
+ await sleep(3e3);
638
+ } else throw err;
639
+ }
672
640
  }
673
- return this;
674
641
  }
675
- /** Which automatic captures are on, after defaults. */
676
- get autoCapture() {
677
- return this.auto;
642
+ await waitUpdated(lambda, lambdaMod, functionName);
643
+ const urlCfg = await lookup(() => lambda.send(new lambdaMod.GetFunctionUrlConfigCommand({ FunctionName: functionName })));
644
+ const url = urlCfg?.FunctionUrl ?? (await lambda.send(new lambdaMod.CreateFunctionUrlConfigCommand({ FunctionName: functionName, AuthType: "NONE" }))).FunctionUrl;
645
+ if (!url) throw new Error(`AWS didn't return a URL for ${functionName}.`);
646
+ for (const [sid, input] of [
647
+ ["debugkit-public-url", { Action: "lambda:InvokeFunctionUrl", FunctionUrlAuthType: "NONE" }],
648
+ ["debugkit-public-invoke", { Action: "lambda:InvokeFunction", InvokedViaFunctionUrl: true }]
649
+ ]) {
650
+ try {
651
+ await lambda.send(new lambdaMod.AddPermissionCommand({ FunctionName: functionName, StatementId: sid, Principal: "*", ...input }));
652
+ } catch (err) {
653
+ if (err.name !== "ResourceConflictException") p.log.warn(`Couldn't add ${sid}: ${err.message}`);
654
+ }
678
655
  }
679
- /**
680
- * Begin a new session: a fresh id and a "started" marker. Called by `init()`, and by the
681
- * React Native entry when the app returns after 30 minutes in the background.
682
- */
683
- startSession() {
684
- if (!this.ready) return;
685
- void this.flush();
686
- this.session = { id: uid(), startedAt: now() };
687
- this.sessionState = { errored: false, crashed: false };
688
- if (this.auto.sessions) this.push({ type: "session", id: uid(), ts: now(), status: "started" });
656
+ s.stop(`Lambda ${functionName} is live at ${url}`);
657
+ let readOnlyPolicyArn = `arn:aws:iam::${account}:policy/debugkit-dashboard-readonly-${table}`.slice(0, 2048);
658
+ try {
659
+ if (!await lookup(() => iam.send(new iamMod.GetPolicyCommand({ PolicyArn: readOnlyPolicyArn }))))
660
+ await iam.send(
661
+ new iamMod.CreatePolicyCommand({
662
+ PolicyName: `debugkit-dashboard-readonly-${table}`.slice(0, 128),
663
+ PolicyDocument: JSON.stringify({
664
+ Version: "2012-10-17",
665
+ Statement: [{ Effect: "Allow", Action: ["dynamodb:GetItem", "dynamodb:Query", "dynamodb:DescribeTable"], Resource: tableArn }]
666
+ }),
667
+ Description: `Read-only access to the deBug table ${table}, for hosting the dashboard`,
668
+ Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
669
+ })
670
+ );
671
+ } catch (err) {
672
+ p.log.warn(`Skipped the read-only dashboard policy: ${err.message}`);
673
+ readOnlyPolicyArn = void 0;
689
674
  }
690
- /** Record a navigation breadcrumb ("from → to"). Repeated paths are ignored. */
691
- navigated(to) {
692
- if (!to || to === this.lastNav) return;
693
- this.breadcrumb("navigation", this.lastNav ? `${this.lastNav} \u2192 ${to}` : to);
694
- this.lastNav = to;
675
+ return {
676
+ config: { provider: "aws", endpoint: url.replace(/\/$/, ""), ingestKey: ctx.ingestKey, aws: { region, profile, table, functionName, roleName, readOnlyPolicyArn } },
677
+ dashboardEnv: { DEBUG_STORE: "dynamodb", AWS_REGION: region, DEBUG_DYNAMO_TABLE: table, ...profile ? { AWS_PROFILE: profile } : {}, ...adminEnv(url, ctx) },
678
+ created: [
679
+ `DynamoDB table ${code(table)} in ${region}${ownTable ? " (on-demand)" : " (your existing table)"}`,
680
+ `Lambda ${code(functionName)} with a public URL: ${code(url)}`,
681
+ `IAM role ${code(roleName)} that can only write to the table`,
682
+ ...readOnlyPolicyArn ? [`Read-only policy for hosting the dashboard: ${code(readOnlyPolicyArn)}`] : []
683
+ ]
684
+ };
685
+ }
686
+ var CREATED_BY = "created-by";
687
+ async function lookup(fn) {
688
+ try {
689
+ return await fn();
690
+ } catch (err) {
691
+ const name = err.name ?? "";
692
+ if (name === "ResourceNotFoundException" || name === "NoSuchEntityException" || name === "NoSuchEntity") return void 0;
693
+ throw err;
695
694
  }
696
- get initialized() {
697
- return this.ready;
695
+ }
696
+ async function waitUpdated(lambda, mod, name) {
697
+ for (let i = 0; i < 60; i++) {
698
+ const c = await lambda.send(new mod.GetFunctionConfigurationCommand({ FunctionName: name }));
699
+ if (c.State !== "Pending" && c.LastUpdateStatus !== "InProgress") return;
700
+ await sleep(1500);
698
701
  }
699
- /** False when init() was called with `enabled: false` (or not called yet). */
700
- get enabled() {
701
- return this.ready;
702
+ }
703
+
704
+ // src/providers/firebase.ts
705
+ init_exec();
706
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
707
+ import { join as join4 } from "path";
708
+ var LOCATIONS = [
709
+ { value: "africa-south1", label: "Johannesburg (africa-south1)", region: "africa-south1" },
710
+ { value: "eur3", label: "Europe, multi-region (eur3)", region: "europe-west1" },
711
+ { value: "europe-west1", label: "Belgium (europe-west1)", region: "europe-west1" },
712
+ { value: "nam5", label: "United States, multi-region (nam5)", region: "us-central1" },
713
+ { value: "us-central1", label: "Iowa (us-central1)", region: "us-central1" },
714
+ { value: "asia-southeast1", label: "Singapore (asia-southeast1)", region: "asia-southeast1" }
715
+ ];
716
+ var FUNCTION_NAME = "debugIngest";
717
+ var CODEBASE = "debugkit";
718
+ var MIN_FIREBASE_TOOLS = 14;
719
+ async function firebaseCli() {
720
+ if (which("firebase")) {
721
+ const v = await capture("firebase", ["--version"]);
722
+ const major = Number(/^(\d+)/.exec(v.stdout.trim())?.[1] ?? 0);
723
+ if (major >= MIN_FIREBASE_TOOLS) return ["firebase", []];
724
+ p.log.info(dim(`Your Firebase CLI is ${v.stdout.trim()}; deBug needs ${MIN_FIREBASE_TOOLS}+ for Node 22, so it'll use npx firebase-tools@latest (same sign-in).`));
702
725
  }
703
- /** Events waiting to be sent. */
704
- get pending() {
705
- return this.queue.length;
726
+ return ["npx", ["-y", "firebase-tools@latest"]];
727
+ }
728
+ var emailsIn = (text2) => [...new Set(text2.match(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g) ?? [])];
729
+ async function setupFirebase(ctx) {
730
+ const [fbCmd, fbPre] = await firebaseCli();
731
+ const fb = (args, opts = {}) => capture(fbCmd, [...fbPre, ...args], opts);
732
+ const fbLive = (args, opts = {}) => interactive(fbCmd, [...fbPre, ...args], opts);
733
+ p.note(
734
+ [
735
+ "deBug deploys a small ingest function and a Firestore database into your own Firebase project.",
736
+ "Firebase will ask you to sign in with Google and allow the Firebase CLI to manage your projects.",
737
+ "That access stays on this machine. deBug doesn't receive it."
738
+ ].join("\n"),
739
+ "Sign in to Firebase"
740
+ );
741
+ let accounts = emailsIn((await fb(["login:list"])).stdout);
742
+ let account;
743
+ if (!accounts.length) {
744
+ 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.");
746
+ accounts = emailsIn((await fb(["login:list"])).stdout);
706
747
  }
707
- /** Merge extra context (e.g. after an async device lookup). Applies to events sent from now on. */
708
- setContext(patch) {
709
- if (this.opts) this.opts.context = mergeContext(this.opts.context ?? {}, patch);
710
- }
711
- setUser(id) {
712
- this.user = { ...this.user, id };
713
- }
714
- breadcrumb(category, message, data, level = "info") {
715
- const msg = message.slice(0, 500);
716
- const last = this.crumbs[this.crumbs.length - 1];
717
- if (last && last.category === category && last.message === msg && last.level === level) {
718
- last.ts = now();
719
- last.data = { ...data, repeated: Number(last.data?.repeated ?? 1) + 1 };
720
- return;
721
- }
722
- this.crumbs.push({ ts: now(), category, message: msg, data, level });
723
- if (this.crumbs.length > (this.opts?.maxBreadcrumbs ?? 30)) this.crumbs.shift();
748
+ const ADD = "__add__";
749
+ const picked = await choose(
750
+ "Which Google account should own the deBug resources?",
751
+ [...accounts.map((a) => ({ value: a, label: a })), { value: ADD, label: "Sign in with another account" }],
752
+ accounts[0]
753
+ );
754
+ if (picked === ADD) {
755
+ if (await fbLive(["login:add"]) !== 0) bail("Firebase sign-in didn't finish.");
756
+ const now2 = emailsIn((await fb(["login:list"])).stdout);
757
+ account = now2.find((a) => !accounts.includes(a)) ?? now2[0] ?? bail("No Firebase account is signed in.");
758
+ } else account = picked;
759
+ const acct = ["--account", account];
760
+ const s = p.spinner();
761
+ s.start("Loading your Firebase projects");
762
+ const list = await fb(["projects:list", "--json", ...acct]);
763
+ s.stop("Loaded your Firebase projects");
764
+ let projects = [];
765
+ try {
766
+ projects = JSON.parse(list.stdout).result ?? [];
767
+ } catch {
768
+ p.log.warn(`Couldn't read the project list: ${dim(list.stderr.slice(-300))}`);
724
769
  }
725
- /** Log an error. `flow` is the part of the app it belongs to, e.g. "auth.login". */
726
- error(err, meta = {}) {
727
- this.captureError(normaliseError(err), meta);
770
+ 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
+ );
779
+ if (projectId === NEW) {
780
+ const suggested = `${ctx.app.appId}-debug`.slice(0, 26).replace(/-+$/, "") + `-${Math.random().toString(36).slice(2, 6)}`;
781
+ projectId = await ask("Project id (lowercase, globally unique)", {
782
+ 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"
784
+ });
785
+ if (await fbLive(["projects:create", projectId, "--display-name", `${ctx.app.name} deBug`.slice(0, 30), ...acct]) !== 0)
786
+ bail(`Couldn't create ${projectId}. Pick an existing project or another id.`);
728
787
  }
729
- /** Log a custom event. Use outcome to let deBug compute failure rates per flow. */
730
- event(name, meta = {}) {
731
- this.breadcrumb("event", name, meta.props);
732
- this.enqueue({ type: "event", id: uid(), ts: now(), name, flow: meta.flow, step: meta.step, tags: meta.tags, outcome: meta.outcome, props: meta.props });
788
+ const proj = ["--project", projectId, ...acct];
789
+ p.note(
790
+ [
791
+ "Cloud Functions only run on Firebase's pay-as-you-go plan (Blaze).",
792
+ "deBug's ingest typically stays inside the free monthly allowance, but Google requires a billing account.",
793
+ `If ${projectId} is already on Blaze, skip this.`
794
+ ].join("\n"),
795
+ "Billing"
796
+ );
797
+ if (await yes(`Open the billing page for ${projectId} to check or upgrade?`, true)) {
798
+ openUrl(`https://console.firebase.google.com/project/${projectId}/usage/details`);
799
+ await next("I've checked: it's on Blaze");
733
800
  }
734
- /**
735
- * Wraps an async step: logs a success or failure outcome for the flow, plus the error.
736
- * Pass `{ captureError: false }` when the error is already reported elsewhere, e.g. a
737
- * server function wrapped in withDebug, so it isn't counted twice.
738
- */
739
- async track(flow, step, fn, opts = {}) {
740
- try {
741
- const out = await fn();
742
- this.event(`${flow}.${step}`, { flow, step, outcome: "success" });
743
- return out;
744
- } catch (err) {
745
- this.event(`${flow}.${step}`, { flow, step, outcome: "failure" });
746
- if (opts.captureError !== false) this.error(err, { flow, step });
747
- throw err;
801
+ let location2;
802
+ const existingDb = await defaultDatabase(fb, proj);
803
+ if (existingDb) {
804
+ location2 = existingDb.locationId;
805
+ p.log.info(`Using the existing Firestore database in ${projectId} (${location2})`);
806
+ } else {
807
+ location2 = await choose("Where should the Firestore database live? This can't be changed later.", LOCATIONS.map(({ value, label }) => ({ value, label })), "africa-south1");
808
+ s.start(`Creating the Firestore database in ${location2}`);
809
+ const r = await fb(["firestore:databases:create", "(default)", "--location", location2, ...proj]);
810
+ if (r.code !== 0 && !/already exists/i.test(r.stderr + r.stdout)) {
811
+ s.error("Couldn't create the database");
812
+ 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.");
748
814
  }
815
+ s.stop(`Created the Firestore database (${location2})`);
749
816
  }
750
- /** Response times per endpoint, sent as one metric event each about once a minute. */
751
- timings = /* @__PURE__ */ new Map();
752
- timingsSince = Date.now();
753
- /** Set when the ingest rejects metric events (older than 0.7): stop sending them, keep the rest. */
754
- noMetrics = false;
755
- timeRequest(key, ms, failed) {
756
- if (this.noMetrics) return;
757
- let t = this.timings.get(key);
758
- if (!t) {
759
- if (this.timings.size >= 50) return;
760
- this.timings.set(key, t = { count: 0, errors: 0, buckets: new Array(LATENCY_BUCKETS_MS.length + 1).fill(0) });
817
+ const region = functionRegion(location2);
818
+ const dir = writeFunctionSource(ctx, region, projectId);
819
+ s.start("Installing the ingest function's dependencies");
820
+ const inst = await capture("npm", ["install", "--no-audit", "--no-fund"], { cwd: join4(dir, "functions") });
821
+ if (inst.code !== 0) {
822
+ s.error("npm install failed");
823
+ p.log.error(inst.stderr.slice(-600));
824
+ bail();
825
+ }
826
+ s.stop("Installed the ingest function's dependencies");
827
+ p.note(
828
+ [
829
+ `In ${bold(projectId)}${environment.get() ? ` (your ${environment.get()} environment)` : ""}, deBug will add:`,
830
+ `\u2022 a Cloud Function ${code(FUNCTION_NAME)} in ${region}, with a public URL (each request needs the ingest key)`,
831
+ `\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)`,
833
+ "",
834
+ "Nothing else in the project is changed. Usage is billed to the project's Blaze plan."
835
+ ].join("\n"),
836
+ "About to deploy"
837
+ );
838
+ if (!await yes(`Deploy deBug into ${projectId}?`)) bail("Nothing was deployed.");
839
+ p.log.step("Adding deBug's Firestore indexes (your existing indexes are left alone)");
840
+ if (await fbLive(["deploy", "--only", "firestore:indexes", "--non-interactive", ...proj], { cwd: dir }) !== 0)
841
+ p.log.warn("The indexes didn't deploy. The dashboard needs them; deploy them later with the command printed at the end.");
842
+ p.log.step(`Deploying ${code(FUNCTION_NAME)}. The first deploy turns on the Google APIs it needs and takes a few minutes.`);
843
+ for (; ; ) {
844
+ const exit = await fbLive(["deploy", "--only", `functions:${CODEBASE}`, "--force", ...proj], { cwd: dir });
845
+ if (exit === 0) break;
846
+ p.log.warn("The deploy didn't finish: see the error above. Common causes: the project isn't on the Blaze plan, or your account lacks permission to deploy functions.");
847
+ const again = await choose(
848
+ "What now?",
849
+ [
850
+ { value: "retry", label: "Retry the deploy" },
851
+ { value: "billing", label: "Open billing, then retry" },
852
+ { value: "stop", label: "Stop here" }
853
+ ],
854
+ "retry"
855
+ );
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}`);
857
+ if (again === "billing") {
858
+ openUrl(`https://console.firebase.google.com/project/${projectId}/usage/details`);
859
+ await next("Upgraded: retry the deploy");
761
860
  }
762
- t.count++;
763
- if (failed) t.errors++;
764
- t.buckets[latencyBucket(ms)]++;
765
861
  }
766
- /** Turn the collected timings into metric events (every minute, or now when `force`). */
767
- queueTimings(force = false) {
768
- if (!this.timings.size || this.noMetrics || !force && Date.now() - this.timingsSince < 6e4) return;
769
- for (const [key, t] of this.timings) this.push({ type: "metric", id: uid(), ts: now(), name: "http", key: key.slice(0, 300), count: t.count, errors: t.errors, buckets: t.buckets });
770
- this.timings.clear();
771
- this.timingsSince = Date.now();
862
+ const endpoint = `https://${region}-${projectId}.cloudfunctions.net/${FUNCTION_NAME}`;
863
+ await ensureDashboardAccess(projectId);
864
+ return {
865
+ config: { provider: "firebase", endpoint, ingestKey: ctx.ingestKey, firebase: { projectId, region, account, location: location2 } },
866
+ dashboardEnv: { DEBUG_STORE: "firestore", GOOGLE_CLOUD_PROJECT: projectId, GCLOUD_PROJECT: projectId, ...adminEnv(endpoint, ctx) },
867
+ created: [
868
+ `Firestore database in ${code(projectId)} (${location2}), with indexes and 30-day expiry on raw events`,
869
+ `Cloud Function ${code(FUNCTION_NAME)} in ${region}: ${code(endpoint)}`,
870
+ `Function source in ${code(".debugkit/firebase")}, so you can redeploy it with the Firebase CLI`
871
+ ]
872
+ };
873
+ }
874
+ async function ensureDashboardAccess(projectId) {
875
+ if (!which("gcloud")) {
876
+ p.log.warn(
877
+ [
878
+ "The dashboard reads Firestore with Google Cloud credentials, and gcloud isn't installed.",
879
+ `Install it (${code("https://cloud.google.com/sdk/docs/install")}), then run ${code("gcloud auth application-default login")}.`,
880
+ "Or create a read-only service account (role: Cloud Datastore Viewer) and set GOOGLE_APPLICATION_CREDENTIALS in .debugkit/dashboard.env."
881
+ ].join("\n")
882
+ );
883
+ return;
772
884
  }
773
- async flush() {
774
- this.queueTimings(this.closing);
775
- if (this.flushing) await this.flushing.catch(() => {
776
- });
777
- if (this.flushing) return this.flushing;
778
- if (!this.ready || this.queue.length === 0 || Date.now() < this.backoffUntil) return;
779
- const batch = this.queue.splice(0, this.opts.maxBatch);
780
- this.flushing = this.send(batch).then(() => {
781
- this.failures = 0;
782
- }).catch((err) => {
783
- this.queue.unshift(...batch);
784
- this.failures++;
785
- this.backoffUntil = Date.now() + Math.min(6e4, 1e3 * 2 ** this.failures);
786
- this.log("flush failed", err);
787
- }).finally(() => {
788
- this.flushing = void 0;
789
- void this.persist();
790
- });
791
- return this.flushing;
885
+ const t = await capture("gcloud", ["auth", "application-default", "print-access-token"]);
886
+ if (t.code === 0) {
887
+ p.log.success("The dashboard will read Firestore with your Google Cloud credentials");
888
+ return;
792
889
  }
793
- /** Stop the flush timer, undo automatic instrumentation and send what is queued. */
794
- closing = false;
795
- close() {
796
- if (this.timer) clearInterval(this.timer);
797
- this.uninstrument();
798
- this.closing = true;
799
- return this.flush().finally(() => this.closing = false);
890
+ p.note("One more Google sign-in: this one lets the dashboard on this machine read deBug's data.", "Dashboard access");
891
+ await next("Open the Google sign-in page");
892
+ const exit = await interactive("gcloud", ["auth", "application-default", "login", "--quiet"]);
893
+ if (exit !== 0) p.log.warn("Google Cloud sign-in didn't finish. The dashboard won't be able to read Firestore until you run: gcloud auth application-default login");
894
+ else await capture("gcloud", ["auth", "application-default", "set-quota-project", projectId]);
895
+ }
896
+ async function defaultDatabase(fb, proj) {
897
+ const r = await fb(["firestore:databases:get", "(default)", "--json", ...proj]);
898
+ if (r.code !== 0) return void 0;
899
+ try {
900
+ const db = JSON.parse(r.stdout).result;
901
+ return db?.locationId ? { locationId: db.locationId } : void 0;
902
+ } catch {
903
+ return void 0;
800
904
  }
801
- /* ---------------- internals ---------------- */
802
- /** @internal Used by the platform entry points for errors that have no thrown value. */
803
- captureError(e, meta, request) {
804
- if (!this.ready) return;
805
- const handled = meta.handled ?? true;
806
- const frames = e.frames ?? parseStack(e.stack);
807
- if (!meta.fatal && !this.allowError(`${e.name}|${e.message.slice(0, 120)}|${frames[0]?.file ?? ""}:${frames[0]?.line ?? ""}`)) return;
808
- if (this.auto.sessions && (!handled || meta.fatal)) {
809
- if (!this.sessionState.errored) {
810
- this.sessionState.errored = true;
811
- this.push({ type: "session", id: uid(), ts: now(), status: "errored" });
812
- }
813
- if (meta.fatal && !this.sessionState.crashed) {
814
- this.sessionState.crashed = true;
815
- this.push({ type: "session", id: uid(), ts: now(), status: "crashed" });
816
- }
817
- }
818
- (meta.fatal ? this.push : this.enqueue).call(this, {
819
- type: "error",
820
- id: uid(),
821
- ts: now(),
822
- flow: meta.flow,
823
- step: meta.step,
824
- tags: meta.tags,
825
- severity: meta.severity ?? (meta.fatal ? "critical" : void 0),
826
- handled,
827
- error: { name: e.name, message: e.message, stack: e.stack, frames },
828
- breadcrumbs: [...this.crumbs],
829
- request
830
- });
905
+ }
906
+ function functionRegion(location2) {
907
+ const known = LOCATIONS.find((l) => l.value === location2)?.region;
908
+ if (known) return known;
909
+ if (location2 === "nam7") return "us-central1";
910
+ if (location2.startsWith("eur")) return "europe-west1";
911
+ if (location2.startsWith("nam")) return "us-central1";
912
+ return /^[a-z]+-[a-z]+\d+$/.test(location2) ? location2 : "us-central1";
913
+ }
914
+ function writeFunctionSource(ctx, region, projectId = "default") {
915
+ const dir = paths(ctx.app.cwd).firebase;
916
+ mkdirSync2(join4(dir, "functions"), { recursive: true });
917
+ writeFirebaseJson(dir, (cur) => ({
918
+ ...cur,
919
+ functions: [{ source: "functions", codebase: CODEBASE, runtime: "nodejs22" }, ...asArray(cur.functions).filter((f) => f.codebase !== CODEBASE)],
920
+ firestore: { database: "(default)", indexes: "firestore.indexes.json" }
921
+ }));
922
+ writeFileSync2(join4(dir, "firestore.indexes.json"), JSON.stringify(firestore_indexes_default, null, 2) + "\n");
923
+ writeFileSync2(
924
+ join4(dir, "functions", "package.json"),
925
+ JSON.stringify(
926
+ {
927
+ name: "debugkit-ingest",
928
+ private: true,
929
+ type: "module",
930
+ main: "index.js",
931
+ engines: { node: "22" },
932
+ dependencies: {
933
+ // Same release as this CLI (the packages are versioned together).
934
+ "@debugkit/adapters": `^${VERSION}`,
935
+ "@debugkit/ingest": `^${VERSION}`,
936
+ "firebase-admin": "^13.0.0",
937
+ "firebase-functions": "^7.0.0"
938
+ }
939
+ },
940
+ null,
941
+ 2
942
+ ) + "\n"
943
+ );
944
+ writeFileSync2(
945
+ join4(dir, "functions", "index.js"),
946
+ `// deBug ingest, deployed by npx debugkit init. Receives events from the SDK and writes them to Firestore.
947
+ import { initializeApp } from "firebase-admin/app";
948
+ import { getFirestore } from "firebase-admin/firestore";
949
+ import { onRequest } from "firebase-functions/v2/https";
950
+ import { FirestoreStore } from "@debugkit/adapters/firestore";
951
+ import { parseIngestKeys } from "@debugkit/ingest";
952
+ import { firebaseHandler } from "@debugkit/ingest/firebase";
953
+
954
+ initializeApp();
955
+
956
+ export const ${FUNCTION_NAME} = onRequest(
957
+ { region: ${JSON.stringify(region)}, invoker: "public", memory: "256MiB", maxInstances: 10 },
958
+ firebaseHandler({
959
+ store: new FirestoreStore(getFirestore()),
960
+ keys: parseIngestKeys(process.env.DEBUG_INGEST_KEYS),
961
+ retentionDays: Number(process.env.DEBUG_RETENTION_DAYS) || undefined,
962
+ adminToken: process.env.DEBUG_ADMIN_TOKEN,
963
+ }),
964
+ );
965
+ `
966
+ );
967
+ const envFile = join4(dir, "functions", ".env");
968
+ const current2 = existsSync4(envFile) ? /^DEBUG_INGEST_KEYS=(.*)$/m.exec(readFileSync3(envFile, "utf8"))?.[1] : void 0;
969
+ writeFileSync2(envFile, `DEBUG_INGEST_KEYS=${mergeKeys(current2, ctx.ingestKey, ctx.app.appId)}
970
+ DEBUG_RETENTION_DAYS=${ctx.retentionDays}
971
+ `);
972
+ writeFileSync2(join4(dir, "functions", `.env.${projectId}`), `DEBUG_ADMIN_TOKEN=${ctx.adminToken}
973
+ `, { mode: 384 });
974
+ return dir;
975
+ }
976
+ var asArray = (v) => Array.isArray(v) ? v : v && typeof v === "object" ? [v] : [];
977
+ function writeFirebaseJson(dir, update) {
978
+ const file = join4(dir, "firebase.json");
979
+ let cur = {};
980
+ try {
981
+ cur = JSON.parse(readFileSync3(file, "utf8"));
982
+ } catch {
831
983
  }
832
- /** Per-minute limits: one runaway error can't flood the queue, the network or your database. */
833
- allowError(signature) {
834
- const max = this.opts.maxErrorsPerMinute ?? 60;
835
- const t = Date.now();
836
- const hit = (key, cap) => {
837
- let l = this.limits.get(key);
838
- if (!l || t - l.since > 6e4) this.limits.set(key, l = { n: 0, since: t });
839
- return ++l.n <= cap;
840
- };
841
- if (this.limits.size > 200) this.limits.clear();
842
- const ok = hit("*", max) && hit(signature, Math.max(1, Math.ceil(max / 6)));
843
- if (!ok) this.log("rate limited", signature);
844
- return ok;
984
+ writeFileSync2(file, JSON.stringify(update(cur), null, 2) + "\n");
985
+ }
986
+
987
+ // src/hosting.ts
988
+ var DASHBOARD_FUNCTION = "debugkitDashboard";
989
+ var DASHBOARD_CODEBASE = "debugkit-dashboard";
990
+ var SA_NAME = "debugkit-dashboard";
991
+ var SHARED = ["DEBUG_STORE", "DEBUG_SESSION_SECRET", "DEBUG_DASHBOARD_USERS", "DEBUG_API_TOKEN", "DEBUG_ADMIN_URL", "DEBUG_ADMIN_TOKEN", "DEBUG_RETENTION_DAYS", "DEBUG_LINEAR_TEAM", "DEBUG_LINEAR", "DEBUG_GITHUB_REPO"];
992
+ var SECRET = /* @__PURE__ */ new Set(["DEBUG_SESSION_SECRET", "DEBUG_DASHBOARD_USERS", "DEBUG_API_TOKEN", "DEBUG_ADMIN_TOKEN"]);
993
+ function hostedEnv(local, url, extra = {}) {
994
+ const plain = { DEBUG_DASHBOARD_URL: url, ...extra };
995
+ const secret = {};
996
+ for (const k of SHARED) if (local[k]) (SECRET.has(k) ? secret : plain)[k] = local[k];
997
+ 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.");
998
+ return { plain, secret };
999
+ }
1000
+ var dotenv = (values) => Object.entries(values).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join("\n") + "\n";
1001
+ async function dashboardDependency(into) {
1002
+ const dir = process.env.DEBUGKIT_DASHBOARD_DIR;
1003
+ if (!dir || !existsSync5(join5(dir, "handler.mjs"))) return `^${DASHBOARD_VERSION}`;
1004
+ for (const f of readdirSync(into)) if (f.endsWith(".tgz")) rmSync(join5(into, f));
1005
+ const r = await capture("npm", ["pack", "--silent", "--pack-destination", into], { cwd: dir });
1006
+ const tgz = r.stdout.trim().split(/\r?\n/).pop();
1007
+ if (r.code !== 0 || !tgz) throw new Error(`Couldn't pack the local dashboard: ${r.stderr.slice(-400)}`);
1008
+ const hash = createHash("sha256").update(readFileSync4(join5(into, tgz))).digest("hex").slice(0, 12);
1009
+ const named = tgz.replace(/\.tgz$/, `-${hash}.tgz`);
1010
+ renameSync(join5(into, tgz), join5(into, named));
1011
+ return `file:./${named}`;
1012
+ }
1013
+ async function npmInstall(cwd, extra = []) {
1014
+ const r = await capture("npm", ["install", "--no-audit", "--no-fund", "--loglevel=error", ...extra], { cwd });
1015
+ if (r.code !== 0) throw new Error(`npm install failed in ${cwd}:
1016
+ ${r.stderr.slice(-600)}`);
1017
+ }
1018
+ async function linkAlerts(local, app, url) {
1019
+ const base = local.DEBUG_ADMIN_URL;
1020
+ const token = local.DEBUG_ADMIN_TOKEN;
1021
+ if (!base || !token) return;
1022
+ const auth = { authorization: `Bearer ${token}` };
1023
+ try {
1024
+ const got = await fetch(`${base}/settings?app=${encodeURIComponent(app)}`, { headers: auth });
1025
+ if (!got.ok) return;
1026
+ const alerts = (await got.json()).settings?.alerts ?? {};
1027
+ const cur = typeof alerts.dashboardUrl === "string" ? alerts.dashboardUrl : "";
1028
+ if (cur && !/\/\/(localhost|127\.0\.0\.1)/.test(cur)) return;
1029
+ await fetch(`${base}/settings`, { method: "PUT", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify({ app, alerts: { ...alerts, dashboardUrl: url } }) });
1030
+ } catch {
845
1031
  }
846
- sampled() {
847
- const r = this.opts.sampleRate ?? 1;
848
- return r >= 1 || Math.random() < r;
1032
+ }
1033
+ async function waitLive(url, ms = 12e4) {
1034
+ const end = Date.now() + ms;
1035
+ while (Date.now() < end) {
1036
+ try {
1037
+ const r = await fetch(`${url}/login`, { redirect: "manual" });
1038
+ if (r.status === 200) return true;
1039
+ } catch {
1040
+ }
1041
+ await new Promise((r) => setTimeout(r, 3e3));
849
1042
  }
850
- enqueue(e) {
851
- if (!this.ready || !this.sampled()) return;
852
- this.push(e);
1043
+ return false;
1044
+ }
1045
+ async function hostDashboard(cwd, cfg) {
1046
+ const local = readEnv(paths(cwd).dashboardEnv);
1047
+ 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.");
1048
+ writeConfig(cwd, { ...cfg, hosted: out.hosted });
1049
+ await linkAlerts(local, cfg.appId, out.hosted.url);
1050
+ const s = p.spinner();
1051
+ s.start(`Checking ${out.hosted.url}`);
1052
+ if (await waitLive(out.hosted.url)) s.stop(`The dashboard is live at ${code(out.hosted.url)}`);
1053
+ else s.error(`${out.hosted.url} didn't answer yet. New deploys can take a minute; open it again shortly.`);
1054
+ return { url: out.hosted.url, created: out.created };
1055
+ }
1056
+ var SITE_ID = /^[a-z0-9](?:[a-z0-9-]{2,61}[a-z0-9])$/;
1057
+ async function listSites(fb, proj) {
1058
+ const r = await fb(["hosting:sites:list", "--json", ...proj]);
1059
+ return [...new Set([...r.stdout.matchAll(/sites\/([a-z0-9-]+)/g)].map((m) => m[1]))];
1060
+ }
1061
+ async function readOnlyServiceAccount(projectId) {
1062
+ const email = `${SA_NAME}@${projectId}.iam.gserviceaccount.com`;
1063
+ if (!which("gcloud")) {
1064
+ 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.`);
1065
+ return void 0;
853
1066
  }
854
- /** Queue without sampling (sessions must be complete for crash-free rates to be right). */
855
- push(e) {
856
- if (!this.ready) return;
857
- const out = this.opts.beforeSend ? this.opts.beforeSend(e) : e;
858
- if (!out) return;
859
- this.queue.push(out);
860
- if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);
861
- if (out.type === "error" || this.queue.length >= this.opts.maxBatch) void this.flush();
862
- else void this.persist();
1067
+ const g2 = (args) => capture("gcloud", [...args, "--project", projectId, "--quiet"]);
1068
+ if ((await g2(["iam", "service-accounts", "describe", email, "--format=value(email)"])).code !== 0) {
1069
+ const c = await g2(["iam", "service-accounts", "create", SA_NAME, "--display-name", "deBug dashboard (read-only)"]);
1070
+ if (c.code !== 0 && !/already exists/i.test(c.stderr)) {
1071
+ p.log.warn(`Couldn't create the read-only service account: ${dim(c.stderr.trim().slice(-300))}
1072
+ The dashboard runs as the project's default service account instead.`);
1073
+ return void 0;
1074
+ }
863
1075
  }
864
- buildContext() {
865
- const c = this.opts.context ?? {};
866
- return {
867
- ...c,
868
- app: { ...c.app ?? {}, ...this.opts.app },
869
- os: { name: "unknown", ...c.os ?? {} },
870
- runtime: { name: "unknown", ...c.runtime ?? {} },
871
- device: c.device ?? {}
872
- };
1076
+ const b = await g2(["projects", "add-iam-policy-binding", projectId, "--member", `serviceAccount:${email}`, "--role", "roles/datastore.viewer", "--condition=None", "--format=none"]);
1077
+ if (b.code !== 0) {
1078
+ p.log.warn(`Couldn't give ${email} read access: ${dim(b.stderr.trim().slice(-300))}
1079
+ The dashboard runs as the project's default service account instead.`);
1080
+ return void 0;
873
1081
  }
874
- /** Set when the ingest rejects 0.2 fields: it predates them, so send what it understands. */
875
- legacyIngest = false;
876
- async send(events) {
877
- if (this.noMetrics) events = events.filter((e) => e.type !== "metric");
878
- if (this.legacyIngest) events = toLegacy(events);
879
- if (!events.length) return;
880
- const body = {
881
- sdk: { name: SDK_NAME, version: SDK_VERSION },
882
- context: this.buildContext(),
883
- user: this.user,
884
- session: this.session,
885
- events
886
- };
887
- const f = this.opts.fetch ?? this.rawFetch ?? fetch;
888
- const json = JSON.stringify(body);
889
- const res = await f(this.opts.endpoint, {
890
- method: "POST",
891
- headers: { "content-type": "application/json", "x-debug-key": this.opts.ingestKey },
892
- body: json,
893
- // Lets the last batch finish when the page is closing. Browsers cap keepalive bodies at 64 KB.
894
- ...typeof window !== "undefined" && json.length < 6e4 ? { keepalive: true } : {}
895
- });
896
- if (res.status >= 400 && res.status < 500 && res.status !== 429) {
897
- this.log(`ingest rejected batch (${res.status})`, await res.text().catch(() => ""));
898
- if (res.status === 400 && !this.noMetrics && events.some((e) => e.type === "metric")) {
899
- this.noMetrics = true;
900
- this.timings.clear();
901
- return this.send(events);
1082
+ return email;
1083
+ }
1084
+ function writeDashboardSource(dir, opts) {
1085
+ const src = join5(dir, "dashboard");
1086
+ mkdirSync3(src, { recursive: true });
1087
+ writeFileSync3(
1088
+ join5(src, "package.json"),
1089
+ JSON.stringify(
1090
+ {
1091
+ name: "debugkit-dashboard-host",
1092
+ private: true,
1093
+ type: "module",
1094
+ main: "index.js",
1095
+ engines: { node: "22" },
1096
+ dependencies: { "@debugkit/dashboard": opts.dependency, "firebase-functions": "^7.0.0" }
1097
+ },
1098
+ null,
1099
+ 2
1100
+ ) + "\n"
1101
+ );
1102
+ const options = { region: opts.region, invoker: "public", memory: "512MiB", timeoutSeconds: 60, maxInstances: 5, ...opts.serviceAccount ? { serviceAccount: opts.serviceAccount } : {} };
1103
+ writeFileSync3(
1104
+ join5(src, "index.js"),
1105
+ `// The deBug dashboard, hosted by npx debugkit deploy-dashboard. Firebase Hosting sends every request here.
1106
+ // It reads Firestore${opts.serviceAccount ? " as a read-only service account" : ""}; settings changes go through the ingest function.
1107
+ import { onRequest } from "firebase-functions/v2/https";
1108
+ import { createHandler } from "@debugkit/dashboard/handler";
1109
+
1110
+ process.env.NODE_ENV ??= "production";
1111
+
1112
+ export const ${DASHBOARD_FUNCTION} = onRequest(${JSON.stringify(options)}, createHandler());
1113
+ `
1114
+ );
1115
+ writeFileSync3(join5(src, ".env"), dotenv(opts.plain));
1116
+ writeFileSync3(join5(src, `.env.${opts.projectId}`), dotenv(opts.secret), { mode: 384 });
1117
+ writeFirebaseJson(dir, (cur) => ({
1118
+ ...cur,
1119
+ functions: [...asArray(cur.functions).filter((f) => f.codebase !== DASHBOARD_CODEBASE), { source: "dashboard", codebase: DASHBOARD_CODEBASE, runtime: "nodejs22" }]
1120
+ }));
1121
+ return src;
1122
+ }
1123
+ function writeHostingConfig(dir, site, region) {
1124
+ writeFirebaseJson(dir, (cur) => ({
1125
+ ...cur,
1126
+ hosting: [
1127
+ ...asArray(cur.hosting).filter((h) => h.site !== site),
1128
+ { site, public: "hosting-public", ignore: ["firebase.json", "**/.*"], rewrites: [{ source: "**", function: { functionId: DASHBOARD_FUNCTION, region } }] }
1129
+ ]
1130
+ }));
1131
+ }
1132
+ async function hostFirebase(cwd, cfg, local) {
1133
+ const fbc = cfg.firebase ?? bail("This setup has no Firebase project saved. Run npx debugkit init again.");
1134
+ const [fbCmd, fbPre] = await firebaseCli();
1135
+ const acct = fbc.account ? ["--account", fbc.account] : [];
1136
+ const proj = ["--project", fbc.projectId, ...acct];
1137
+ const fb = (args, o = {}) => capture(fbCmd, [...fbPre, ...args], o);
1138
+ const fbLive = (args, o = {}) => interactive(fbCmd, [...fbPre, ...args], o);
1139
+ const dir = paths(cwd).firebase;
1140
+ if (!existsSync5(join5(dir, "firebase.json"))) bail(`${dir} is missing. Run ${code("npx debugkit init")} again to recreate it.`);
1141
+ const s = p.spinner();
1142
+ s.start("Finding a Hosting site for the dashboard");
1143
+ const sites = await listSites(fb, proj);
1144
+ const base = `${fbc.projectId}-debug`.replace(/-+/g, "-").slice(0, 63 - 5);
1145
+ let site = cfg.hosted?.site && sites.includes(cfg.hosted.site) ? cfg.hosted.site : sites.find((x) => x === base || x.startsWith(`${base}-`));
1146
+ if (!site) {
1147
+ for (const candidate of [base, `${base}-${Math.random().toString(36).slice(2, 6)}`, `${base}-${Math.random().toString(36).slice(2, 6)}`]) {
1148
+ if (!SITE_ID.test(candidate)) continue;
1149
+ const r = await fb(["hosting:sites:create", candidate, "--non-interactive", ...proj]);
1150
+ if (r.code === 0) {
1151
+ site = candidate;
1152
+ break;
902
1153
  }
903
- if (res.status === 400 && !this.legacyIngest && hasNewFields(events)) {
904
- this.legacyIngest = true;
905
- return this.send(events);
1154
+ if (!/already|taken|exists|reserved/i.test(r.stderr + r.stdout)) {
1155
+ s.error("Couldn't create a Hosting site");
1156
+ throw new Error((r.stderr || r.stdout).slice(-600));
906
1157
  }
907
- return;
908
1158
  }
909
- if (!res.ok) throw new Error(`ingest responded ${res.status}`);
910
1159
  }
911
- async persist() {
912
- try {
913
- await this.opts.storage?.setItem(QUEUE_KEY, JSON.stringify(this.queue));
914
- } catch {
1160
+ if (!site) {
1161
+ s.error("Couldn't find a free Hosting site name");
1162
+ bail(`Create one in the Firebase console (Hosting \u2192 Add another site), then run ${code("npx debugkit deploy-dashboard")}.`);
1163
+ }
1164
+ const url = `https://${site}.web.app`;
1165
+ s.stop(`Hosting site ${code(site)}: ${url}`);
1166
+ const serviceAccount = await readOnlyServiceAccount(fbc.projectId);
1167
+ let region = cfg.hosted?.region ?? fbc.region;
1168
+ const { plain, secret } = hostedEnv(local, url, { DEBUG_COOKIE_NAME: "__session" });
1169
+ s.start("Preparing the dashboard function");
1170
+ mkdirSync3(join5(dir, "dashboard"), { recursive: true });
1171
+ const dependency = await dashboardDependency(join5(dir, "dashboard"));
1172
+ const write = () => {
1173
+ const src2 = writeDashboardSource(dir, { region, projectId: fbc.projectId, serviceAccount, dependency, plain, secret });
1174
+ writeHostingConfig(dir, site, region);
1175
+ return src2;
1176
+ };
1177
+ const src = write();
1178
+ await npmInstall(src);
1179
+ const client = join5(src, "node_modules", "@debugkit", "dashboard", "dist", "client");
1180
+ if (!existsSync5(client)) throw new Error("The dashboard package has no built assets (dist/client).");
1181
+ rmSync(join5(dir, "hosting-public"), { recursive: true, force: true });
1182
+ cpSync(client, join5(dir, "hosting-public"), { recursive: true });
1183
+ s.stop("Prepared the dashboard function");
1184
+ p.note(
1185
+ [
1186
+ `In ${bold(fbc.projectId)}${environment.get() ? ` (your ${environment.get()} environment)` : ""}, deBug will add:`,
1187
+ `\u2022 a Hosting site ${code(site)} at ${code(url)}`,
1188
+ `\u2022 a Cloud Function ${code(DASHBOARD_FUNCTION)} in ${region}${serviceAccount ? `, running as ${code(serviceAccount)} (read-only)` : ""}`,
1189
+ "",
1190
+ "Anyone with the link sees the sign-in page; only people with a login get in.",
1191
+ "Your app's own Hosting site and functions are left alone."
1192
+ ].join("\n"),
1193
+ "About to host the dashboard"
1194
+ );
1195
+ if (!await yes(`Host the dashboard in ${fbc.projectId}?`)) bail("Nothing was deployed. The dashboard still runs locally with npx debugkit dashboard.");
1196
+ writeFileSync3(join5(dir, "firestore.indexes.json"), JSON.stringify(firestore_indexes_default, null, 2) + "\n");
1197
+ p.log.step("Adding any Firestore indexes this version of deBug needs (existing ones are left alone)");
1198
+ if (await fbLive(["deploy", "--only", "firestore:indexes", "--non-interactive", ...proj], { cwd: dir }) !== 0)
1199
+ p.log.warn("The indexes didn't deploy. Some counts on the dashboard may be missing until they do.");
1200
+ for (; ; ) {
1201
+ p.log.step(`Deploying the dashboard to ${url}. The first deploy takes a few minutes.`);
1202
+ const exit = await fbLive(["deploy", "--only", `functions:${DASHBOARD_CODEBASE},hosting:${site}`, "--force", ...proj], { cwd: dir });
1203
+ if (exit === 0) break;
1204
+ const choice = await choose(
1205
+ "The deploy didn't finish (see the error above). What now?",
1206
+ [
1207
+ { value: "retry", label: "Retry" },
1208
+ ...region !== "us-central1" ? [{ value: "us", label: "Retry with the function in us-central1", hint: "if Hosting can't reach the function's region" }] : [],
1209
+ { value: "stop", label: "Stop here" }
1210
+ ],
1211
+ "retry"
1212
+ );
1213
+ if (choice === "stop") bail(`Fix the error above, then run ${code("npx debugkit deploy-dashboard")}.`);
1214
+ if (choice === "us") {
1215
+ region = "us-central1";
1216
+ write();
915
1217
  }
916
1218
  }
917
- /**
918
- * Reuse the install's anonymous id: from localStorage in browsers straight away, or from the
919
- * `storage` option (AsyncStorage in React Native) once it loads. Events queued before then
920
- * carry the new id, which only matters for the very first launch.
921
- */
922
- loadAnonymousId() {
923
- const ws = webStorage();
924
- if (ws) {
925
- try {
926
- const saved = ws.getItem(ANON_KEY);
927
- if (saved) this.user = { ...this.user, anonymousId: saved };
928
- else ws.setItem(ANON_KEY, this.user.anonymousId);
929
- } catch {
930
- }
931
- return;
1219
+ return {
1220
+ hosted: { url, region, functionName: DASHBOARD_FUNCTION, site, deployedAt: (/* @__PURE__ */ new Date()).toISOString() },
1221
+ created: [`Hosted dashboard at ${code(url)} (Hosting site ${code(site)}, function ${code(DASHBOARD_FUNCTION)} in ${region})`]
1222
+ };
1223
+ }
1224
+ var CREATED_BY2 = "created-by";
1225
+ function filesUnder(root, skip) {
1226
+ const out = {};
1227
+ const walk = (d) => {
1228
+ for (const name of readdirSync(d)) {
1229
+ const full = join5(d, name);
1230
+ const rel = relative(root, full).split("\\").join("/");
1231
+ if (skip(rel)) continue;
1232
+ if (statSync(full).isDirectory()) walk(full);
1233
+ else out[rel] = readFileSync4(full);
932
1234
  }
933
- const storage = this.opts.storage;
934
- if (!storage) return;
935
- void (async () => {
936
- try {
937
- const saved = await storage.getItem(ANON_KEY);
938
- if (saved) this.user = { ...this.user, anonymousId: saved };
939
- else await storage.setItem(ANON_KEY, this.user.anonymousId);
940
- } catch {
941
- }
942
- })();
1235
+ };
1236
+ walk(root);
1237
+ return out;
1238
+ }
1239
+ async function dashboardZip() {
1240
+ const dir = mkdtempSync(join5(tmpdir(), "debugkit-dashboard-"));
1241
+ try {
1242
+ const dependency = await dashboardDependency(dir);
1243
+ writeFileSync3(join5(dir, "package.json"), JSON.stringify({ name: "debugkit-dashboard-lambda", private: true, type: "module", dependencies: { "@debugkit/dashboard": dependency } }));
1244
+ await npmInstall(dir, ["--omit=optional", "--omit=dev"]);
1245
+ writeFileSync3(join5(dir, "index.mjs"), `export { handler } from "@debugkit/dashboard/lambda";
1246
+ `);
1247
+ const files = filesUnder(dir, (rel) => rel.endsWith(".tgz") || rel === "package-lock.json" || /(^|\/)(\.bin|\.cache)(\/|$)/.test(rel) || /\.(map|md|d\.ts)$/.test(rel));
1248
+ return zipSync2(files, { level: 6 });
1249
+ } finally {
1250
+ rmSync(dir, { recursive: true, force: true });
943
1251
  }
944
- async restore() {
945
- try {
946
- const raw = await this.opts.storage?.getItem(QUEUE_KEY);
947
- if (raw) this.queue.unshift(...JSON.parse(raw));
948
- } catch {
949
- }
1252
+ }
1253
+ async function hostAws(cfg, local) {
1254
+ const aws = cfg.aws ?? bail("This setup has no AWS details saved. Run npx debugkit init again.");
1255
+ 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.");
1256
+ const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
1257
+ const [iamMod, lambdaMod] = await Promise.all([import("@aws-sdk/client-iam"), import("@aws-sdk/client-lambda")]);
1258
+ const base = { region: aws.region, credentials: fromNodeProviderChain(aws.profile ? { profile: aws.profile } : {}) };
1259
+ const iam = new iamMod.IAMClient(base);
1260
+ const lambda = new lambdaMod.LambdaClient(base);
1261
+ const functionName = `debugkit-dashboard-${aws.table}`.slice(0, 64);
1262
+ const roleName = `debugkit-dashboard-${aws.table}-${aws.region}`.slice(0, 64);
1263
+ const account = /arn:aws:iam::(\d+):/.exec(aws.readOnlyPolicyArn)?.[1];
1264
+ p.note(
1265
+ [
1266
+ `In AWS ${account ?? ""} (${aws.region})${environment.get() ? `, your ${environment.get()} environment` : ""}, deBug will add:`,
1267
+ `\u2022 a Lambda ${code(functionName)} with a public URL, serving the dashboard`,
1268
+ `\u2022 an IAM role ${code(roleName)} that can only read the ${code(aws.table)} table`,
1269
+ "",
1270
+ "Anyone with the link sees the sign-in page; only people with a login get in."
1271
+ ].join("\n"),
1272
+ "About to host the dashboard"
1273
+ );
1274
+ if (!await yes("Host the dashboard in AWS?")) bail("Nothing was deployed. The dashboard still runs locally with npx debugkit dashboard.");
1275
+ const s = p.spinner();
1276
+ s.start("Packaging the dashboard");
1277
+ const zip = await dashboardZip();
1278
+ s.message(`Setting up IAM role ${roleName}`);
1279
+ let roleArn;
1280
+ let newRole = false;
1281
+ const role = await lookup(() => iam.send(new iamMod.GetRoleCommand({ RoleName: roleName })));
1282
+ if (role) {
1283
+ 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.`);
1284
+ roleArn = role.Role.Arn;
1285
+ } else {
1286
+ roleArn = (await iam.send(
1287
+ new iamMod.CreateRoleCommand({
1288
+ RoleName: roleName,
1289
+ Description: `deBug dashboard Lambda: reads the DynamoDB table ${aws.table}`,
1290
+ AssumeRolePolicyDocument: JSON.stringify({
1291
+ Version: "2012-10-17",
1292
+ Statement: [{ Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole", ...account ? { Condition: { StringEquals: { "aws:SourceAccount": account } } } : {} }]
1293
+ }),
1294
+ Tags: [{ Key: CREATED_BY2, Value: "debugkit" }]
1295
+ })
1296
+ )).Role.Arn;
1297
+ newRole = true;
950
1298
  }
951
- installGlobalHandlers() {
952
- this.handlersInstalled = true;
953
- const g2 = globalThis;
954
- if (g2.ErrorUtils?.setGlobalHandler) {
955
- const prev = g2.ErrorUtils.getGlobalHandler?.();
956
- g2.ErrorUtils.setGlobalHandler((err, isFatal) => {
957
- this.error(err, { handled: false, fatal: !!isFatal, tags: { source: "global-handler" } });
958
- void this.flush();
959
- prev?.(err, isFatal);
960
- });
961
- }
962
- if (typeof window !== "undefined" && typeof g2.addEventListener === "function") {
963
- g2.addEventListener("error", (ev) => this.error(ev.error ?? ev.message, { handled: false, tags: { source: "window.onerror" } }));
964
- g2.addEventListener("unhandledrejection", (ev) => this.error(ev.reason, { handled: false, tags: { source: "unhandledrejection" } }));
1299
+ await iam.send(new iamMod.AttachRolePolicyCommand({ RoleName: roleName, PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" }));
1300
+ await iam.send(new iamMod.AttachRolePolicyCommand({ RoleName: roleName, PolicyArn: aws.readOnlyPolicyArn }));
1301
+ s.message(`Deploying Lambda ${functionName}`);
1302
+ const env = (url2) => {
1303
+ const { plain, secret } = hostedEnv(local, url2, { DEBUG_DYNAMO_TABLE: aws.table, NODE_ENV: "production" });
1304
+ return { Variables: { ...plain, ...secret } };
1305
+ };
1306
+ const fn = await lookup(() => lambda.send(new lambdaMod.GetFunctionCommand({ FunctionName: functionName })));
1307
+ const fnConfig = { FunctionName: functionName, Role: roleArn, Handler: "index.handler", Runtime: "nodejs22.x", MemorySize: 1024, Timeout: 30 };
1308
+ if (fn) {
1309
+ if (fn.Tags?.[CREATED_BY2] !== "debugkit") bail(`Function ${functionName} exists and wasn't created by deBug. deBug won't overwrite it.`);
1310
+ await lambda.send(new lambdaMod.UpdateFunctionCodeCommand({ FunctionName: functionName, ZipFile: zip }));
1311
+ await waitUpdated2(lambda, lambdaMod, functionName);
1312
+ } else {
1313
+ for (let attempt = 0; ; attempt++) {
1314
+ try {
1315
+ await lambda.send(
1316
+ new lambdaMod.CreateFunctionCommand({
1317
+ ...fnConfig,
1318
+ Architectures: ["arm64"],
1319
+ Code: { ZipFile: zip },
1320
+ Environment: env(cfg.hosted?.url ?? "https://pending"),
1321
+ Description: "deBug dashboard (read-only on the deBug table)",
1322
+ Tags: { [CREATED_BY2]: "debugkit" }
1323
+ })
1324
+ );
1325
+ break;
1326
+ } catch (err) {
1327
+ if (attempt < 10 && /cannot be assumed|role defined for the function/i.test(err.message)) {
1328
+ s.message(newRole ? "Waiting for the new IAM role to be ready" : "Retrying");
1329
+ await new Promise((r) => setTimeout(r, 3e3));
1330
+ } else throw err;
1331
+ }
965
1332
  }
1333
+ await waitUpdated2(lambda, lambdaMod, functionName);
966
1334
  }
967
- instrument() {
968
- const a = this.auto;
969
- const sink = this.sink();
970
- const add = (r) => r && this.restores.push(r);
971
- if (a.network) {
972
- const restoreFetch = instrumentFetch(sink);
973
- if (restoreFetch) globalThis.fetch.__raw = this.rawFetch;
974
- add(restoreFetch);
975
- add(instrumentXhr(sink));
1335
+ const urlCfg = await lookup(() => lambda.send(new lambdaMod.GetFunctionUrlConfigCommand({ FunctionName: functionName })));
1336
+ const fnUrl = urlCfg?.FunctionUrl ?? (await lambda.send(new lambdaMod.CreateFunctionUrlConfigCommand({ FunctionName: functionName, AuthType: "NONE" }))).FunctionUrl;
1337
+ if (!fnUrl) throw new Error(`AWS didn't return a URL for ${functionName}.`);
1338
+ const url = fnUrl.replace(/\/+$/, "");
1339
+ for (const [sid, input] of [
1340
+ ["debugkit-public-url", { Action: "lambda:InvokeFunctionUrl", FunctionUrlAuthType: "NONE" }],
1341
+ ["debugkit-public-invoke", { Action: "lambda:InvokeFunction", InvokedViaFunctionUrl: true }]
1342
+ ]) {
1343
+ try {
1344
+ await lambda.send(new lambdaMod.AddPermissionCommand({ FunctionName: functionName, StatementId: sid, Principal: "*", ...input }));
1345
+ } catch (err) {
1346
+ if (err.name !== "ResourceConflictException") p.log.warn(`Couldn't add ${sid}: ${err.message}`);
976
1347
  }
977
- if (a.console) add(instrumentConsole(sink));
978
- if (a.navigation) add(instrumentHistory(sink));
979
- if (a.clicks) add(instrumentClicks(sink));
980
- if (a.lifecycle) add(instrumentWebLifecycle(sink));
981
- }
982
- uninstrument() {
983
- while (this.restores.length) this.restores.pop()();
984
- }
985
- /** The bridge the instrumentation (./auto, and the platform entry points) reports through. */
986
- sink() {
987
- return {
988
- request: (r) => this.recordRequest(r),
989
- crumb: (category, message, level = "info", data) => this.breadcrumb(category, message, data, level),
990
- navigated: (to) => this.navigated(to),
991
- lifecycle: (state) => {
992
- this.breadcrumb("ui", state === "background" ? "App went to the background" : "App came to the foreground");
993
- if (state === "background") {
994
- this.queueTimings(true);
995
- void this.flush();
996
- }
997
- },
998
- ignored: (url) => this.isIgnored(url)
999
- };
1000
- }
1001
- isIgnored(url) {
1002
- if (!this.ready) return true;
1003
- const ep = this.opts.endpoint.replace(/^https?:/, "");
1004
- if (url.includes(ep) || /\/symbolicate\b|\/logs(?:\?|$)/.test(url)) return true;
1005
- return (this.opts.network?.ignoreUrls ?? []).some((p2) => typeof p2 === "string" ? url.includes(p2) : p2.test(url));
1006
- }
1007
- recordRequest(r) {
1008
- if (!this.ready) return;
1009
- const net = this.opts.network ?? {};
1010
- const url = normaliseUrl(r.url);
1011
- const ms = Math.round(r.durationMs);
1012
- const failed = r.status === void 0 ? !r.aborted : (net.isFailure ?? ((s) => s >= 500))(r.status, url);
1013
- const slow = ms >= (net.slowMs ?? 3e3);
1014
- const outcome = r.aborted ? "aborted" : r.timedOut ? "timed out" : r.status !== void 0 ? String(r.status) : "failed";
1015
- this.breadcrumb("network", `${r.method} ${url} \u2192 ${outcome} (${ms}ms)`, { status: r.status ?? null, durationMs: ms }, failed ? "error" : slow ? "warning" : "info");
1016
- if (!r.aborted) this.timeRequest(`${r.method} ${url}`, ms, failed);
1017
- if (!failed) return;
1018
- const flow = net.flows?.find(([p2]) => typeof p2 === "string" ? url.includes(p2) : p2.test(url))?.[1];
1019
- const cause = r.error ? normaliseError(r.error) : void 0;
1020
- const message = r.status !== void 0 ? `${r.method} ${url} responded ${r.status}` : `${r.method} ${url} ${r.timedOut ? "timed out" : "failed"}${cause ? `: ${cause.message}` : ""}`;
1021
- const frames = parseStack(r.stack).slice(1);
1022
- this.captureError(
1023
- { name: r.status !== void 0 ? "HttpError" : "NetworkError", message, stack: r.stack, frames },
1024
- { flow, handled: true, tags: { source: "network" } },
1025
- { method: r.method, url, status: r.status, durationMs: ms }
1026
- );
1027
1348
  }
1028
- log(...args) {
1029
- if (this.opts?.debug) console.warn("[deBug]", ...args);
1349
+ await lambda.send(new lambdaMod.UpdateFunctionConfigurationCommand({ ...fnConfig, Environment: env(url) }));
1350
+ await waitUpdated2(lambda, lambdaMod, functionName);
1351
+ s.stop(`Lambda ${functionName} serves the dashboard`);
1352
+ return {
1353
+ hosted: { url, region: aws.region, functionName, deployedAt: (/* @__PURE__ */ new Date()).toISOString() },
1354
+ created: [`Hosted dashboard at ${code(url)} (Lambda ${code(functionName)}, read-only role ${code(roleName)})`]
1355
+ };
1356
+ }
1357
+ async function waitUpdated2(lambda, mod, name) {
1358
+ for (let i = 0; i < 60; i++) {
1359
+ const c = await lambda.send(new mod.GetFunctionConfigurationCommand({ FunctionName: name }));
1360
+ if (c.State !== "Pending" && c.LastUpdateStatus !== "InProgress") return;
1361
+ await new Promise((r) => setTimeout(r, 1500));
1030
1362
  }
1363
+ }
1364
+
1365
+ // src/detect.ts
1366
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
1367
+ import { join as join6 } from "path";
1368
+ var PLATFORM_LABEL = {
1369
+ expo: "Expo",
1370
+ "react-native": "React Native",
1371
+ next: "Next.js",
1372
+ "tanstack-start": "TanStack Start",
1373
+ "vite-react": "React (Vite)",
1374
+ react: "React",
1375
+ node: "Node"
1031
1376
  };
1032
- function normaliseError(err) {
1033
- if (err instanceof Error) return { name: err.name || "Error", message: err.message, stack: err.stack };
1034
- if (typeof err === "string") return { name: "Error", message: err };
1377
+ function detectApp(cwd) {
1378
+ let pkg = {};
1035
1379
  try {
1036
- return { name: "NonError", message: JSON.stringify(err).slice(0, 2e3) };
1380
+ pkg = JSON.parse(readFileSync5(join6(cwd, "package.json"), "utf8"));
1037
1381
  } catch {
1038
- return { name: "NonError", message: String(err) };
1382
+ throw new Error(`No package.json in ${cwd}. Run npx debugkit init from your app's folder.`);
1039
1383
  }
1040
- }
1041
- function resolveAuto(o) {
1042
- const all = o.autoCapture !== false;
1043
- const sel = typeof o.autoCapture === "object" ? o.autoCapture : {};
1044
- const pick = (k, dflt = all) => sel[k] ?? dflt;
1384
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
1385
+ const has = (d) => d in deps;
1386
+ const platform = has("expo") ? "expo" : has("react-native") ? "react-native" : has("next") ? "next" : has("@tanstack/react-start") ? "tanstack-start" : has("vite") && has("react") ? "vite-react" : has("react") ? "react" : "node";
1387
+ const envPrefix = platform === "expo" ? "EXPO_PUBLIC_" : platform === "next" ? "NEXT_PUBLIC_" : platform === "vite-react" || platform === "tanstack-start" ? "VITE_" : void 0;
1388
+ const name = pkg.name ?? cwd.split(/[\\/]/).pop() ?? "app";
1045
1389
  return {
1046
- errors: o.captureGlobalErrors ?? pick("errors"),
1047
- network: pick("network"),
1048
- console: pick("console"),
1049
- navigation: pick("navigation"),
1050
- clicks: pick("clicks"),
1051
- lifecycle: pick("lifecycle"),
1052
- sessions: pick("sessions")
1390
+ cwd,
1391
+ name,
1392
+ appId: toAppId(name),
1393
+ version: pkg.version,
1394
+ platform,
1395
+ expoRouter: has("expo-router"),
1396
+ reactNavigation: has("@react-navigation/native"),
1397
+ 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",
1398
+ hasSdk: has("@debugkit/sdk"),
1399
+ missingExpoModules: platform === "expo" ? ["expo-device", "expo-application"].filter((m) => !has(m)) : [],
1400
+ sourceDir: existsSync6(join6(cwd, "src")) ? "src" : ".",
1401
+ envPrefix,
1402
+ typescript: existsSync6(join6(cwd, "tsconfig.json")) || has("typescript")
1053
1403
  };
1054
1404
  }
1055
- var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type === "error" && e.request);
1056
- function toLegacy(events) {
1057
- const out = [];
1058
- for (const e of events) {
1059
- if (e.type === "session" || e.type === "metric") continue;
1060
- if (e.type === "error" && e.request) {
1061
- const { request: _r, ...rest } = e;
1062
- out.push(rest);
1063
- } else out.push(e);
1064
- }
1065
- return out;
1405
+ function toAppId(name) {
1406
+ return name.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "app";
1066
1407
  }
1067
-
1068
- // ../sdk/src/index.ts
1069
- var deBug = new DebugClient();
1070
-
1071
- // src/guide.ts
1072
- init_exec();
1073
- function automaticFor(platform, app) {
1074
- const common = [
1075
- `${bold("Crashes")}: uncaught errors and unhandled promise rejections, with the stack trace`,
1076
- `${bold("Failed requests")}: every request is a breadcrumb; timeouts, network failures and 5xx responses become errors that point at the line that made the call`,
1077
- `${bold("Sessions")}: each launch is marked started, then errored or crashed, which gives the crash-free rate per release`,
1078
- `${bold("Context")}: device, OS, app version and network on every event`
1079
- ];
1080
- switch (platform) {
1081
- case "expo":
1082
- case "react-native":
1083
- return [
1084
- ...common,
1085
- `${bold("Lifecycle")}: the app going to the background and back; a new session after 30 minutes away`,
1086
- `${bold("Console")}: console.warn and console.error as breadcrumbs`,
1087
- app.expoRouter || app.reactNavigation ? `${bold("Screens")}: every screen change, once you add the ${code(app.expoRouter ? "useDebugExpoRouter()" : "trackReactNavigation()")} line` : `${bold("Screens")}: add the router helper from the SDK for screen-change breadcrumbs`,
1088
- `${bold("Offline")}: events wait in a queue and send when the connection is back`
1089
- ];
1090
- case "node":
1091
- return [...common.slice(0, 2), `${bold("Server errors")}: 5xx responses your server sends, and outgoing node:http requests (axios, SDKs)`, common[3], `${bold("Clean exit")}: on a crash, events are sent before the process exits`];
1408
+ function installCommand(pm, pkgs) {
1409
+ switch (pm) {
1410
+ case "pnpm":
1411
+ return ["pnpm", ["add", ...pkgs]];
1412
+ case "yarn":
1413
+ return ["yarn", ["add", ...pkgs]];
1414
+ case "bun":
1415
+ return ["bun", ["add", ...pkgs]];
1092
1416
  default:
1093
- return [
1094
- ...common,
1095
- `${bold("Navigation")}: every page change, with any router`,
1096
- `${bold("Clicks")}: buttons and links, by their label (never what people type)`,
1097
- `${bold("Console and lifecycle")}: console warnings, the tab hidden or shown, going offline`
1098
- ];
1417
+ return ["npm", ["install", ...pkgs]];
1099
1418
  }
1100
1419
  }
1101
- function sdkImport(platform) {
1102
- return platform === "expo" ? "@debugkit/sdk/expo" : platform === "react-native" ? "@debugkit/sdk/react-native" : platform === "node" ? "@debugkit/sdk/node" : "@debugkit/sdk/react";
1103
- }
1104
- var MANUAL = (platform) => `import { deBug } from "${sdkImport(platform)}";
1105
1420
 
1106
- // 1. In a try/catch you already have: report it, tagged with the part of the app
1107
- try {
1108
- await chargeCard(order);
1109
- } catch (err) {
1110
- deBug.error(err, { flow: "checkout.payment", step: "charge" });
1111
- showPaymentError();
1421
+ // ../schema/src/core.ts
1422
+ var LATENCY_BUCKETS_MS = [50, 100, 200, 300, 500, 750, 1e3, 1500, 2e3, 3e3, 5e3, 1e4];
1423
+ function latencyBucket(ms) {
1424
+ const i = LATENCY_BUCKETS_MS.findIndex((edge) => ms <= edge);
1425
+ return i === -1 ? LATENCY_BUCKETS_MS.length : i;
1426
+ }
1427
+ var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
1428
+ var GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
1429
+ var NOT_IN_APP = [/node_modules/, /\bnative\b/, /\[native code\]/, /InternalBytecode/];
1430
+ var RN_BUNDLE = /\.(?:js)?bundle\b/;
1431
+ function cleanFile(file) {
1432
+ return file.replace(/^address at /, "");
1433
+ }
1434
+ function parseStack(stack) {
1435
+ if (!stack) return [];
1436
+ const frames = [];
1437
+ for (const raw of stack.split("\n")) {
1438
+ const m = V8.exec(raw) ?? GECKO.exec(raw);
1439
+ if (!m) continue;
1440
+ const [, fn, rawFile, line, col] = m;
1441
+ const file = cleanFile(rawFile ?? "");
1442
+ frames.push({
1443
+ fn: fn || void 0,
1444
+ file,
1445
+ line: Number(line),
1446
+ col: Number(col),
1447
+ inApp: RN_BUNDLE.test(file) ? !/^(?:anonymous|eval|global code)$/.test(fn ?? "") : !NOT_IN_APP.some((re) => re.test(file))
1448
+ });
1449
+ if (frames.length >= 100) break;
1450
+ }
1451
+ return frames;
1112
1452
  }
1113
1453
 
1114
- // 2. A step that can succeed or fail: deBug logs the outcome (and the error),
1115
- // so the dashboard can say "18% of logins fail", not just "12 errors"
1116
- await deBug.track("auth.login", "submit_otp", () => api.verifyOtp(code));
1117
-
1118
- // 3. Something that isn't an error but matters
1119
- deBug.event("signup_abandoned", { flow: "onboarding.signup", outcome: "abandoned" });
1120
-
1121
- // 4. Who it happened to (an id, not personal data), once they sign in
1122
- deBug.setUser(user.id);`;
1123
- async function sendTestEvents(cfg, app) {
1124
- const failures = [];
1125
- let sent = 0;
1126
- const client = new DebugClient().init({
1127
- endpoint: cfg.endpoint,
1128
- ingestKey: cfg.ingestKey,
1129
- app: { id: cfg.appId, version: app.version ?? "0.0.0", environment: "debugkit-test" },
1130
- context: { os: { name: process.platform, version: process.version }, runtime: { name: "debugkit-cli" }, device: { type: "desktop", model: "debugkit test" } },
1131
- autoCapture: { sessions: true, errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false },
1132
- flushIntervalMs: 0,
1133
- fetch: async (url, init2) => {
1134
- let res;
1135
- try {
1136
- res = await fetch(url, init2);
1137
- } catch (err) {
1138
- failures.push(`couldn't reach it (${err.message})`);
1139
- throw err;
1140
- }
1141
- if (res.ok) sent += (JSON.parse(String(init2?.body ?? "{}")).events ?? []).length;
1142
- else failures.push(`it answered ${res.status}: ${(await res.clone().text().catch(() => "")).slice(0, 200)}`);
1143
- return res;
1144
- }
1145
- });
1146
- client.navigated("/cart");
1147
- client.navigated("/checkout");
1148
- client.breadcrumb("ui", 'Clicked button "Pay now"');
1149
- client.breadcrumb("network", "POST /v1/payments/intent \u2192 503 (1840ms)", { status: 503, durationMs: 1840 }, "error");
1150
- client.captureError(
1151
- { name: "HttpError", message: "POST /v1/payments/intent responded 503 (test event from npx debugkit)", stack: new Error().stack },
1152
- { flow: "onboarding.test", handled: true, tags: { source: "network", test: "true" } },
1153
- { method: "POST", url: "/v1/payments/intent", status: 503, durationMs: 1840 }
1154
- );
1155
- try {
1156
- JSON.parse("<html>502 Bad Gateway</html>");
1157
- } catch (err) {
1158
- client.error(err, { flow: "onboarding.test", step: "parse_receipt", tags: { test: "true" } });
1454
+ // ../sdk/src/context.ts
1455
+ function mergeContext(a, b) {
1456
+ const out = { ...a };
1457
+ for (const [k, v] of Object.entries(b)) {
1458
+ const prev = out[k];
1459
+ out[k] = v && typeof v === "object" && prev && typeof prev === "object" ? { ...prev, ...v } : v ?? prev;
1159
1460
  }
1160
- await client.track("onboarding.test", "submit", async () => true);
1161
- await client.track("onboarding.test", "submit", async () => Promise.reject(new Error("Test failure from deBug.track()")), { captureError: false }).catch(() => {
1162
- });
1163
- for (let i = 0; i < 5 && client.pending && !failures.length; i++) await client.flush();
1164
- await client.close();
1165
- if (!failures.length && client.pending) failures.push(`${client.pending} events weren't sent`);
1166
- return { sent, error: failures.length ? failures.join("; ") : void 0 };
1461
+ return out;
1167
1462
  }
1168
- async function waitForArrival(cwd, url, appId, timeoutMs = 9e4) {
1169
- const until = Date.now() + timeoutMs;
1170
- let last;
1171
- while (Date.now() < until) {
1172
- last = await summary(cwd, url, appId);
1173
- if (last.ok && last.data?.app === appId && last.data?.issues?.length) return last;
1174
- await new Promise((r) => setTimeout(r, 2e3));
1463
+ function safe(fn) {
1464
+ try {
1465
+ return fn();
1466
+ } catch {
1467
+ return void 0;
1175
1468
  }
1176
- return last;
1177
1469
  }
1178
- async function walkthrough(opts) {
1179
- const { cwd, app, cfg, dashboardUrl } = opts;
1180
- const before = await summary(cwd, dashboardUrl, cfg.appId);
1181
- const empty = before.status === 404 || before.ok && before.data?.app !== cfg.appId;
1182
- p.note(
1183
- [
1184
- `${bold("Your dashboard is running")} at ${code(dashboardUrl)}`,
1185
- loginHint(cwd),
1186
- "",
1187
- empty ? `It's connected to your ${cfg.provider === "local" ? "local" : cfg.provider === "aws" ? "DynamoDB" : "Firestore"} data and ${bold("empty")}: nothing has been sent yet.` : before.ok ? "It's connected, and already has data for this app." : `It couldn't read your data yet (${before.status || "no answer"}: ${before.error ?? "unknown"}). The test below will tell us more.`
1188
- ].join("\n"),
1189
- "1 \xB7 The dashboard"
1190
- );
1191
- openUrl(dashboardUrl);
1192
- await next("I'm signed in");
1193
- p.note(
1194
- [
1195
- `${bold("A written summary")}: how many errors today, the worst part of the app, the top issue, the struggling release`,
1196
- `${bold("Issues by severity")}: errors grouped by cause; open one for the stack trace and the steps that led to it`,
1197
- `${bold("Release health")}: crash-free and error-free sessions per app version`,
1198
- `${bold("Failing endpoints")}: requests that time out, fail or return 5xx`,
1199
- `${bold("Where the app is failing")}: errors and failure rates per flow, like auth.login`,
1200
- `${bold("Breakdowns")}: by OS, app version and device`
1201
- ].join("\n"),
1202
- "2 \xB7 What you'll see there"
1203
- );
1204
- await next("Send a test event");
1205
- const s = p.spinner();
1206
- s.start(`Sending test events to ${cfg.endpoint}`);
1207
- const sent = await sendTestEvents(cfg, app);
1208
- if (sent.error) {
1209
- s.error(`The ingest didn't accept them: ${sent.error}`);
1210
- 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.");
1211
- } else {
1212
- s.message("Sent. Waiting for the dashboard to show them");
1213
- const after = await waitForArrival(cwd, dashboardUrl, cfg.appId);
1214
- if (after?.ok && after.data?.issues?.length) {
1215
- s.stop("They arrived");
1216
- const d = after.data;
1217
- p.note(
1218
- [
1219
- ...(d.narrative ?? []).map((l) => `\u201C${l}\u201D`),
1220
- "",
1221
- `${bold(String(d.issues.length))} issues \xB7 ${bold(String(d.health?.sessionsRange ?? 0))} session \xB7 failing endpoint ${code(d.health?.endpoints?.[0]?.endpoint ?? "\u2014")}`,
1222
- "",
1223
- `Refresh the dashboard. You'll see a ${pc.red("HttpError")} from a failed request (captured the way the SDK does it automatically),`,
1224
- `a ${pc.red("SyntaxError")} reported from a try/catch, and the ${code("onboarding.test")} flow with a 50% failure rate from track().`,
1225
- dim("They're tagged environment debugkit-test, version " + (app.version ?? "0.0.0") + ". Raw events expire after 30 days.")
1226
- ].join("\n"),
1227
- "3 \xB7 Your first events"
1228
- );
1229
- } else {
1230
- s.error("Sent, but the dashboard doesn't show them yet");
1231
- p.log.warn(`The dashboard said: ${after?.status ?? "?"} ${after?.error ?? ""}. Refresh it in a minute, or run npx debugkit test again.`);
1232
- }
1470
+ function timezone() {
1471
+ return safe(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
1472
+ }
1473
+ function browserContext() {
1474
+ if (typeof navigator === "undefined" || typeof window === "undefined") {
1475
+ const ua2 = typeof navigator !== "undefined" ? navigator.userAgent : void 0;
1476
+ const node = typeof process !== "undefined" ? process.versions?.node : void 0;
1477
+ return {
1478
+ runtime: { name: ua2 === "Cloudflare-Workers" ? "cloudflare-workers" : node ? "node" : "edge", version: node },
1479
+ os: { name: "server" },
1480
+ timezone: timezone()
1481
+ };
1233
1482
  }
1234
- await next("What does the SDK do on its own?");
1235
- p.note(
1236
- [`Once ${code("debug." + (app.typescript ? "ts" : "js"))} runs, the SDK records this in the background, with no other code:`, "", ...automaticFor(app.platform, app).map((l) => `\u2022 ${l}`), "", dim("Every error carries the last 30 breadcrumbs: the screen, the tap, the request that failed. Query strings and request bodies never leave the device.")].join("\n"),
1237
- `4 \xB7 Automatic in ${PLATFORM_LABEL[app.platform]}`
1238
- );
1239
- await next("What do I add myself?");
1240
- p.note(
1241
- [
1242
- "Automatic capture says what broke. What it can't know is which part of your app a step belongs to, and whether it worked.",
1243
- `That's what ${code("flow")} is for: a dotted name like ${code("auth.login")} that the dashboard groups everything by.`,
1244
- "",
1245
- MANUAL(app.platform)
1246
- ].join("\n"),
1247
- "5 \xB7 What you add in your own try/catches"
1248
- );
1249
- await next("Show me what's left to do");
1250
- p.note(
1251
- [
1252
- ...opts.remaining.map((l, i) => `${i + 1}. ${l}`),
1253
- `${opts.remaining.length + 1}. Run the app and watch the dashboard fill in`,
1254
- "",
1255
- `${code(cmdFor("dashboard"))} open the dashboard again`,
1256
- `${code(cmdFor("test"))} send another test event`,
1257
- `${code(cmdFor("guide"))} replay this walkthrough`
1258
- ].join("\n"),
1259
- "6 \xB7 Finish wiring your app"
1260
- );
1483
+ const ua = navigator.userAgent;
1484
+ const android = /Android ([\d.]+)/.exec(ua)?.[1];
1485
+ const ios = /(?:iPhone|iPad|iPod).*? OS (\d+[_\d]*)/.exec(ua)?.[1];
1486
+ const os = android ? { name: "android", version: android } : ios ? { name: "ios", version: ios.replace(/_/g, ".") } : /Mac OS X/.test(ua) ? { name: "macos" } : /Windows/.test(ua) ? { name: "windows" } : /Linux/.test(ua) ? { name: "linux" } : { name: "web" };
1487
+ const conn = navigator.connection;
1488
+ const browser = /Edg\/([\d.]+)/.exec(ua) ? { name: "edge", v: /Edg\/([\d.]+)/.exec(ua)[1] } : /Chrome\/([\d.]+)/.exec(ua) ? { name: "chrome", v: /Chrome\/([\d.]+)/.exec(ua)[1] } : /Version\/([\d.]+).*Safari/.exec(ua) ? { name: "safari", v: /Version\/([\d.]+)/.exec(ua)[1] } : /Firefox\/([\d.]+)/.exec(ua) ? { name: "firefox", v: /Firefox\/([\d.]+)/.exec(ua)[1] } : void 0;
1489
+ return {
1490
+ os,
1491
+ runtime: { name: "browser", version: browser ? `${browser.name} ${browser.v}` : void 0 },
1492
+ device: {
1493
+ type: /iPad|Tablet/.test(ua) ? "tablet" : /Mobi/.test(ua) ? "phone" : "desktop",
1494
+ screen: typeof screen !== "undefined" ? { width: screen.width, height: screen.height, scale: window.devicePixelRatio } : void 0
1495
+ },
1496
+ network: conn ? {
1497
+ type: conn.type === "wifi" ? "wifi" : conn.type === "cellular" ? "cellular" : "unknown",
1498
+ effectiveType: conn.effectiveType,
1499
+ isConnected: navigator.onLine
1500
+ } : void 0,
1501
+ locale: navigator.language,
1502
+ timezone: timezone()
1503
+ };
1261
1504
  }
1262
1505
 
1263
- // src/providers/aws.ts
1264
- init_exec();
1265
- import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
1266
- import { homedir } from "os";
1267
- import { dirname, join as join4 } from "path";
1268
- import { fileURLToPath } from "url";
1269
- import { zipSync } from "fflate";
1270
-
1271
- // src/keys.ts
1272
- var keyEntry = (key, appId) => `${key}:${appId}`;
1273
- function mergeKeys(existing, key, appId) {
1274
- const pairs = (existing ?? "").split(",").map((s) => s.trim()).filter((s) => /^[^:\s]+:[^:\s]+$/.test(s));
1275
- if (!pairs.some((p2) => p2.split(":")[0] === key)) pairs.push(keyEntry(key, appId));
1276
- return pairs.join(",");
1506
+ // ../sdk/src/auto.ts
1507
+ var g = globalThis;
1508
+ var ID_SEGMENT = /^(?:\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,}|(?=[^/]*\d)[\w-]{20,})$/i;
1509
+ function normaliseUrl(raw) {
1510
+ const m = /^(?:([a-z][a-z0-9+.-]*:)?\/\/([^/?#]*))?([^?#]*)/i.exec(raw.trim());
1511
+ let host = m?.[2] ?? "";
1512
+ const path2 = (m?.[3] || "/").split("/").map((s) => ID_SEGMENT.test(s) ? ":id" : s).join("/");
1513
+ if (host.includes("@")) host = host.slice(host.lastIndexOf("@") + 1);
1514
+ const here = typeof location !== "undefined" ? location.host : void 0;
1515
+ return !host || host === here ? path2 : `${host}${path2.startsWith("/") ? "" : "/"}${path2}`;
1277
1516
  }
1278
-
1279
- // src/providers/types.ts
1280
- var adminEnv = (endpoint, ctx) => ({
1281
- DEBUG_ADMIN_URL: `${endpoint.replace(/\/+$/, "")}/admin`,
1282
- DEBUG_ADMIN_TOKEN: ctx.adminToken,
1283
- DEBUG_RETENTION_DAYS: String(ctx.retentionDays)
1284
- });
1285
-
1286
- // src/providers/aws.ts
1287
- var REGIONS = [
1288
- { value: "af-south-1", label: "Cape Town (af-south-1)" },
1289
- { value: "eu-west-1", label: "Ireland (eu-west-1)" },
1290
- { value: "eu-central-1", label: "Frankfurt (eu-central-1)" },
1291
- { value: "us-east-1", label: "N. Virginia (us-east-1)" },
1292
- { value: "us-west-2", label: "Oregon (us-west-2)" },
1293
- { value: "ap-southeast-1", label: "Singapore (ap-southeast-1)" }
1294
- ];
1295
- function awsProfiles(home = homedir()) {
1296
- const out = /* @__PURE__ */ new Map();
1297
- const read = (file, isConfig) => {
1298
- if (!existsSync4(file)) return;
1299
- let cur;
1300
- for (const line of readFileSync3(file, "utf8").split(/\r?\n/)) {
1301
- const h = /^\s*\[\s*(?:profile\s+)?([^\]\s]+)\s*\]/.exec(line);
1302
- if (h) {
1303
- if (isConfig && h[1] && /^sso-session\b/.test(line.replace(/^\s*\[\s*/, ""))) {
1304
- cur = void 0;
1305
- continue;
1306
- }
1307
- cur = out.get(h[1]) ?? { name: h[1], sso: false };
1308
- out.set(cur.name, cur);
1309
- continue;
1310
- }
1311
- const kv = /^\s*([a-z_]+)\s*=\s*(.+?)\s*$/.exec(line);
1312
- if (!cur || !kv) continue;
1313
- if (kv[1] === "region") cur.region = kv[2];
1314
- if (kv[1].startsWith("sso_")) cur.sso = true;
1517
+ var insideFetch = 0;
1518
+ function instrumentFetch(sink) {
1519
+ const orig = g.fetch;
1520
+ if (typeof orig !== "function" || orig.__debug) return;
1521
+ const wrapped = function(input, init2) {
1522
+ const url = typeof input === "string" ? input : input?.href ?? input?.url ?? String(input);
1523
+ if (sink.ignored(url)) return orig.call(this, input, init2);
1524
+ const method = String(init2?.method ?? input?.method ?? "GET").toUpperCase();
1525
+ const start = Date.now();
1526
+ const stack = new Error().stack;
1527
+ let p2;
1528
+ insideFetch++;
1529
+ try {
1530
+ p2 = orig.call(this, input, init2);
1531
+ } finally {
1532
+ insideFetch--;
1315
1533
  }
1316
- };
1317
- read(process.env.AWS_CONFIG_FILE ?? join4(home, ".aws", "config"), true);
1318
- read(process.env.AWS_SHARED_CREDENTIALS_FILE ?? join4(home, ".aws", "credentials"), false);
1319
- return [...out.values()];
1320
- }
1321
- function lambdaZip() {
1322
- const here = dirname(fileURLToPath(import.meta.url));
1323
- const file = [join4(here, "lambda", "index.mjs"), join4(here, "..", "dist", "lambda", "index.mjs")].find(existsSync4);
1324
- if (!file) throw new Error("The bundled ingest Lambda is missing. Reinstall debugkit.");
1325
- return zipSync({ "index.mjs": readFileSync3(file) }, { level: 9 });
1534
+ return p2.then(
1535
+ (res) => {
1536
+ sink.request({ method, url, status: res.status, durationMs: Date.now() - start, stack });
1537
+ return res;
1538
+ },
1539
+ (error) => {
1540
+ const aborted = error?.name === "AbortError";
1541
+ sink.request({ method, url, error, aborted, durationMs: Date.now() - start, stack });
1542
+ throw error;
1543
+ }
1544
+ );
1545
+ };
1546
+ wrapped.__debug = true;
1547
+ g.fetch = wrapped;
1548
+ return () => {
1549
+ if (g.fetch === wrapped) g.fetch = orig;
1550
+ };
1326
1551
  }
1327
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1328
- async function setupAws(ctx) {
1329
- p.note(
1330
- [
1331
- "deBug creates a DynamoDB table, a Lambda function with a public URL, and an IAM role in your own AWS account.",
1332
- "It uses an AWS profile on this machine. With AWS SSO (IAM Identity Center) you sign in through your browser; no access keys are needed.",
1333
- "Your credentials stay on this machine. deBug doesn't receive them."
1334
- ].join("\n"),
1335
- "Sign in to AWS"
1336
- );
1337
- const profiles = awsProfiles();
1338
- const SSO = "__sso__";
1339
- const ENV = "__env__";
1340
- const options = [
1341
- ...profiles.map((x) => ({ value: x.name, label: x.name, hint: [x.sso ? "SSO" : "keys", x.region].filter(Boolean).join(" \xB7 ") })),
1342
- ...process.env.AWS_ACCESS_KEY_ID ? [{ value: ENV, label: "Credentials from the environment (AWS_ACCESS_KEY_ID)" }] : [],
1343
- { value: SSO, label: "Sign in with AWS SSO (IAM Identity Center)", hint: which("aws") ? "opens your browser" : "needs the AWS CLI" }
1344
- ];
1345
- let profile = await choose("Which AWS credentials should deBug use?", options, profiles[0]?.name ?? SSO);
1346
- if (profile === SSO) {
1347
- if (!which("aws")) bail("AWS SSO sign-in needs the AWS CLI: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html");
1348
- const name = await ask("Name for the new AWS profile", { initial: "debugkit" });
1349
- p.log.step(`Running ${code(`aws configure sso --profile ${name}`)}. It asks for your SSO start URL and region, then opens your browser to approve access.`);
1350
- if (await interactive("aws", ["configure", "sso", "--profile", name]) !== 0) bail("AWS SSO setup didn't finish.");
1351
- profile = name;
1352
- } else if (profile === ENV) profile = void 0;
1353
- const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
1354
- const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
1355
- const defaultRegion = profiles.find((x) => x.name === profile)?.region ?? process.env.AWS_REGION ?? "af-south-1";
1356
- const region = await choose("Which AWS region?", REGIONS.some((r) => r.value === defaultRegion) ? REGIONS : [{ value: defaultRegion, label: defaultRegion }, ...REGIONS], defaultRegion);
1357
- const credentials = fromNodeProviderChain(profile ? { profile } : {});
1358
- const base = { region, credentials };
1359
- let identity;
1552
+ function instrumentXhr(sink) {
1553
+ const X = g.XMLHttpRequest;
1554
+ const proto = X?.prototype;
1555
+ if (!proto || proto.open.__debug) return;
1556
+ const open = proto.open;
1557
+ const send = proto.send;
1558
+ const wrappedOpen = function(method, url, ...rest) {
1559
+ const u = String(url);
1560
+ this.__debug = insideFetch > 0 || sink.ignored(u) ? null : { method: String(method).toUpperCase(), url: u };
1561
+ return open.call(this, method, url, ...rest);
1562
+ };
1563
+ const wrappedSend = function(...args) {
1564
+ const d = this.__debug;
1565
+ if (d) {
1566
+ const start = Date.now();
1567
+ const stack = new Error().stack;
1568
+ let aborted = false;
1569
+ let timedOut = false;
1570
+ this.addEventListener("abort", () => aborted = true);
1571
+ this.addEventListener("timeout", () => timedOut = true);
1572
+ this.addEventListener(
1573
+ "loadend",
1574
+ () => sink.request({ ...d, status: this.status || void 0, aborted, timedOut, durationMs: Date.now() - start, stack })
1575
+ );
1576
+ }
1577
+ return send.apply(this, args);
1578
+ };
1579
+ wrappedOpen.__debug = true;
1580
+ proto.open = wrappedOpen;
1581
+ proto.send = wrappedSend;
1582
+ return () => {
1583
+ proto.open = open;
1584
+ proto.send = send;
1585
+ };
1586
+ }
1587
+ function format(arg) {
1588
+ if (typeof arg === "string") return arg;
1589
+ if (arg instanceof Error) return `${arg.name}: ${arg.message}`;
1360
1590
  try {
1361
- identity = await new STSClient(base).send(new GetCallerIdentityCommand({}));
1362
- } catch (err) {
1363
- const sso = profiles.find((x) => x.name === profile)?.sso;
1364
- if (sso && which("aws")) {
1365
- p.log.info("Your SSO session has expired. Signing in again.");
1366
- if (await interactive("aws", ["sso", "login", "--profile", profile]) !== 0) bail("AWS SSO sign-in didn't finish.");
1367
- identity = await new STSClient({ region, credentials: fromNodeProviderChain({ profile }) }).send(new GetCallerIdentityCommand({}));
1368
- } else bail(`Those AWS credentials didn't work: ${err.message}`);
1591
+ return JSON.stringify(arg) ?? String(arg);
1592
+ } catch {
1593
+ return String(arg);
1369
1594
  }
1370
- p.log.success(`Signed in to AWS account ${code(identity.Account ?? "?")} ${dim(identity.Arn ?? "")}`);
1371
- if (!identity.Account) bail("AWS didn't say which account these credentials belong to.");
1372
- const account = identity.Account;
1373
- const table = await ask("DynamoDB table name", {
1374
- initial: environment.get() ? `debugkit-${environment.get()}` : "debugkit",
1375
- validate: (v) => /^[A-Za-z0-9_.-]{3,40}$/.test(v) ? void 0 : "3\u201340 characters: letters, digits, _ . -"
1376
- });
1377
- const functionName = `debugkit-ingest-${table}`.slice(0, 64);
1378
- const roleName = `debugkit-ingest-${table}-${region}`.slice(0, 64);
1379
- await next(`Create the table, role and function in ${region}`);
1380
- const s = p.spinner();
1381
- const [ddbMod, iamMod, lambdaMod] = await Promise.all([import("@aws-sdk/client-dynamodb"), import("@aws-sdk/client-iam"), import("@aws-sdk/client-lambda")]);
1382
- const ddb = new ddbMod.DynamoDBClient(base);
1383
- s.start(`Checking DynamoDB table ${table}`);
1384
- let tableArn;
1385
- let ownTable = false;
1386
- const found = await lookup(() => ddb.send(new ddbMod.DescribeTableCommand({ TableName: table })));
1387
- if (found) {
1388
- tableArn = found.Table?.TableArn;
1389
- const tags = await ddb.send(new ddbMod.ListTagsOfResourceCommand({ ResourceArn: tableArn }));
1390
- ownTable = !!tags.Tags?.some((t) => t.Key === CREATED_BY && t.Value === "debugkit");
1391
- const keys = Object.fromEntries((found.Table?.KeySchema ?? []).map((k) => [k.KeyType, k.AttributeName]));
1392
- const types = Object.fromEntries((found.Table?.AttributeDefinitions ?? []).map((a) => [a.AttributeName, a.AttributeType]));
1393
- if (keys.HASH !== "pk" || keys.RANGE !== "sk" || types.pk !== "S" || types.sk !== "S") {
1394
- s.error(`Table ${table} exists with a different key schema`);
1395
- bail(`${table} isn't a deBug table (it needs string keys pk and sk). Run again and choose another table name.`);
1595
+ }
1596
+ function instrumentConsole(sink) {
1597
+ const c = g.console;
1598
+ if (!c) return;
1599
+ const restores = [];
1600
+ for (const [method, level] of [["warn", "warning"], ["error", "error"]]) {
1601
+ const orig = c[method];
1602
+ if (typeof orig !== "function") continue;
1603
+ c[method] = function(...args) {
1604
+ if (args[0] !== "[deBug]") sink.crumb("log", args.map(format).join(" ").slice(0, 500), level);
1605
+ return orig.apply(this, args);
1606
+ };
1607
+ restores.push(() => c[method] = orig);
1608
+ }
1609
+ return () => restores.forEach((r) => r());
1610
+ }
1611
+ var path = () => typeof location !== "undefined" ? location.pathname : "";
1612
+ function instrumentHistory(sink) {
1613
+ const h = g.history;
1614
+ if (typeof window === "undefined" || !h?.pushState || typeof g.addEventListener !== "function") return;
1615
+ const orig = { pushState: h.pushState, replaceState: h.replaceState };
1616
+ for (const k of ["pushState", "replaceState"]) {
1617
+ h[k] = function(...args) {
1618
+ const out = orig[k].apply(this, args);
1619
+ sink.navigated(path());
1620
+ return out;
1621
+ };
1622
+ }
1623
+ const onPop = () => sink.navigated(path());
1624
+ g.addEventListener("popstate", onPop);
1625
+ sink.navigated(path());
1626
+ return () => {
1627
+ Object.assign(h, orig);
1628
+ g.removeEventListener("popstate", onPop);
1629
+ };
1630
+ }
1631
+ var CLICKABLE = 'button,a,[role="button"],[role="link"],[role="tab"],[role="menuitem"],input[type="submit"],input[type="button"],input[type="checkbox"],input[type="radio"],summary,label,[data-testid]';
1632
+ function describeElement(el) {
1633
+ const tag = el.tagName.toLowerCase();
1634
+ const label = el.getAttribute("aria-label") || el.getAttribute("data-testid") || el.getAttribute("title") || (tag === "input" ? el.getAttribute("name") || el.type : el.innerText || el.textContent || "");
1635
+ const id = el.id ? `#${el.id}` : "";
1636
+ const text2 = label.replace(/\s+/g, " ").trim().slice(0, 60);
1637
+ return `${tag}${id}${text2 ? ` "${text2}"` : ""}`;
1638
+ }
1639
+ function instrumentClicks(sink) {
1640
+ const d = g.document;
1641
+ if (!d?.addEventListener) return;
1642
+ const onClick = (ev) => {
1643
+ const t = ev.target;
1644
+ const el = t?.closest?.(CLICKABLE);
1645
+ if (el) sink.crumb("ui", `Clicked ${describeElement(el)}`);
1646
+ };
1647
+ d.addEventListener("click", onClick, true);
1648
+ return () => d.removeEventListener("click", onClick, true);
1649
+ }
1650
+ function instrumentWebLifecycle(sink) {
1651
+ const d = g.document;
1652
+ if (typeof window === "undefined" || !d?.addEventListener) return;
1653
+ const onVis = () => sink.lifecycle(d.visibilityState === "hidden" ? "background" : "foreground");
1654
+ const onOnline = () => sink.crumb("network", "Device went online");
1655
+ const onOffline = () => sink.crumb("network", "Device went offline", "warning");
1656
+ d.addEventListener("visibilitychange", onVis);
1657
+ g.addEventListener("online", onOnline);
1658
+ g.addEventListener("offline", onOffline);
1659
+ return () => {
1660
+ d.removeEventListener("visibilitychange", onVis);
1661
+ g.removeEventListener("online", onOnline);
1662
+ g.removeEventListener("offline", onOffline);
1663
+ };
1664
+ }
1665
+
1666
+ // ../sdk/src/client.ts
1667
+ var SDK_NAME = "@debugkit/sdk";
1668
+ var SDK_VERSION = "0.5.0";
1669
+ var QUEUE_KEY = "@debugkit/queue";
1670
+ var ANON_KEY = "@debugkit/anonymousId";
1671
+ function webStorage() {
1672
+ try {
1673
+ const ls = globalThis.localStorage;
1674
+ if (!ls) return void 0;
1675
+ ls.getItem(ANON_KEY);
1676
+ return ls;
1677
+ } catch {
1678
+ return void 0;
1679
+ }
1680
+ }
1681
+ var MAX_QUEUE = 500;
1682
+ var uid = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`).replace(/-/g, "");
1683
+ var now = () => (/* @__PURE__ */ new Date()).toISOString();
1684
+ var DebugClient = class {
1685
+ opts;
1686
+ queue = [];
1687
+ crumbs = [];
1688
+ session = { id: uid(), startedAt: now() };
1689
+ user = { anonymousId: uid() };
1690
+ timer;
1691
+ flushing;
1692
+ backoffUntil = 0;
1693
+ failures = 0;
1694
+ ready = false;
1695
+ handlersInstalled = false;
1696
+ auto = { errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false, sessions: false };
1697
+ restores = [];
1698
+ sessionState = { errored: false, crashed: false };
1699
+ lastNav;
1700
+ limits = /* @__PURE__ */ new Map();
1701
+ /** fetch as it was before instrumentation, so our own uploads are never recorded. */
1702
+ rawFetch;
1703
+ init(options) {
1704
+ if (this.timer) clearInterval(this.timer);
1705
+ this.uninstrument();
1706
+ this.opts = { flushIntervalMs: 5e3, maxBatch: 50, maxBreadcrumbs: 30, ...options };
1707
+ if (options.enabled === false) {
1708
+ this.ready = false;
1709
+ this.queue = [];
1710
+ this.log("disabled for this build (enabled: false)");
1711
+ return this;
1396
1712
  }
1397
- s.stop(ownTable ? `Reusing deBug's table ${table}` : `Table ${table} exists and wasn't created by deBug`);
1398
- if (!ownTable && !await yes(`Store deBug's data in your existing table ${table}? deBug only adds its own items (pk APPS and APP#\u2026).`, false))
1399
- bail("Run again and choose a new table name.");
1400
- } else {
1401
- s.message(`Creating DynamoDB table ${table}`);
1402
- const out = await ddb.send(
1403
- new ddbMod.CreateTableCommand({
1404
- TableName: table,
1405
- BillingMode: "PAY_PER_REQUEST",
1406
- AttributeDefinitions: [
1407
- { AttributeName: "pk", AttributeType: "S" },
1408
- { AttributeName: "sk", AttributeType: "S" }
1409
- ],
1410
- KeySchema: [
1411
- { AttributeName: "pk", KeyType: "HASH" },
1412
- { AttributeName: "sk", KeyType: "RANGE" }
1413
- ],
1414
- Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
1415
- })
1416
- );
1417
- tableArn = out.TableDescription?.TableArn;
1418
- ownTable = true;
1419
- let active = false;
1420
- for (let i = 0; i < 90 && !active; i++) {
1421
- active = (await ddb.send(new ddbMod.DescribeTableCommand({ TableName: table }))).Table?.TableStatus === "ACTIVE";
1422
- if (!active) await sleep(2e3);
1713
+ if (!this.opts.context && typeof window !== "undefined") this.opts.context = browserContext();
1714
+ this.auto = resolveAuto(options);
1715
+ this.rawFetch = typeof globalThis.fetch === "function" ? globalThis.fetch.__raw ?? globalThis.fetch : void 0;
1716
+ this.ready = true;
1717
+ this.loadAnonymousId();
1718
+ void this.restore();
1719
+ if (this.auto.errors && !this.handlersInstalled) this.installGlobalHandlers();
1720
+ this.instrument();
1721
+ if (this.auto.sessions) this.startSession();
1722
+ if (this.opts.flushIntervalMs > 0) {
1723
+ this.timer = setInterval(() => void this.flush(), this.opts.flushIntervalMs);
1724
+ this.timer.unref?.();
1725
+ }
1726
+ return this;
1727
+ }
1728
+ /** Which automatic captures are on, after defaults. */
1729
+ get autoCapture() {
1730
+ return this.auto;
1731
+ }
1732
+ /**
1733
+ * Begin a new session: a fresh id and a "started" marker. Called by `init()`, and by the
1734
+ * React Native entry when the app returns after 30 minutes in the background.
1735
+ */
1736
+ startSession() {
1737
+ if (!this.ready) return;
1738
+ void this.flush();
1739
+ this.session = { id: uid(), startedAt: now() };
1740
+ this.sessionState = { errored: false, crashed: false };
1741
+ if (this.auto.sessions) this.push({ type: "session", id: uid(), ts: now(), status: "started" });
1742
+ }
1743
+ /** Record a navigation breadcrumb ("from → to"). Repeated paths are ignored. */
1744
+ navigated(to) {
1745
+ if (!to || to === this.lastNav) return;
1746
+ this.breadcrumb("navigation", this.lastNav ? `${this.lastNav} \u2192 ${to}` : to);
1747
+ this.lastNav = to;
1748
+ }
1749
+ get initialized() {
1750
+ return this.ready;
1751
+ }
1752
+ /** False when init() was called with `enabled: false` (or not called yet). */
1753
+ get enabled() {
1754
+ return this.ready;
1755
+ }
1756
+ /** Events waiting to be sent. */
1757
+ get pending() {
1758
+ return this.queue.length;
1759
+ }
1760
+ /** Merge extra context (e.g. after an async device lookup). Applies to events sent from now on. */
1761
+ setContext(patch) {
1762
+ if (this.opts) this.opts.context = mergeContext(this.opts.context ?? {}, patch);
1763
+ }
1764
+ setUser(id) {
1765
+ this.user = { ...this.user, id };
1766
+ }
1767
+ breadcrumb(category, message, data, level = "info") {
1768
+ const msg = message.slice(0, 500);
1769
+ const last = this.crumbs[this.crumbs.length - 1];
1770
+ if (last && last.category === category && last.message === msg && last.level === level) {
1771
+ last.ts = now();
1772
+ last.data = { ...data, repeated: Number(last.data?.repeated ?? 1) + 1 };
1773
+ return;
1774
+ }
1775
+ this.crumbs.push({ ts: now(), category, message: msg, data, level });
1776
+ if (this.crumbs.length > (this.opts?.maxBreadcrumbs ?? 30)) this.crumbs.shift();
1777
+ }
1778
+ /** Log an error. `flow` is the part of the app it belongs to, e.g. "auth.login". */
1779
+ error(err, meta = {}) {
1780
+ this.captureError(normaliseError(err), meta);
1781
+ }
1782
+ /** Log a custom event. Use outcome to let deBug compute failure rates per flow. */
1783
+ event(name, meta = {}) {
1784
+ this.breadcrumb("event", name, meta.props);
1785
+ this.enqueue({ type: "event", id: uid(), ts: now(), name, flow: meta.flow, step: meta.step, tags: meta.tags, outcome: meta.outcome, props: meta.props });
1786
+ }
1787
+ /**
1788
+ * Wraps an async step: logs a success or failure outcome for the flow, plus the error.
1789
+ * Pass `{ captureError: false }` when the error is already reported elsewhere, e.g. a
1790
+ * server function wrapped in withDebug, so it isn't counted twice.
1791
+ */
1792
+ async track(flow, step, fn, opts = {}) {
1793
+ try {
1794
+ const out = await fn();
1795
+ this.event(`${flow}.${step}`, { flow, step, outcome: "success" });
1796
+ return out;
1797
+ } catch (err) {
1798
+ this.event(`${flow}.${step}`, { flow, step, outcome: "failure" });
1799
+ if (opts.captureError !== false) this.error(err, { flow, step });
1800
+ throw err;
1801
+ }
1802
+ }
1803
+ /** Response times per endpoint, sent as one metric event each about once a minute. */
1804
+ timings = /* @__PURE__ */ new Map();
1805
+ timingsSince = Date.now();
1806
+ /** Set when the ingest rejects metric events (older than 0.7): stop sending them, keep the rest. */
1807
+ noMetrics = false;
1808
+ timeRequest(key, ms, failed) {
1809
+ if (this.noMetrics) return;
1810
+ let t = this.timings.get(key);
1811
+ if (!t) {
1812
+ if (this.timings.size >= 50) return;
1813
+ this.timings.set(key, t = { count: 0, errors: 0, buckets: new Array(LATENCY_BUCKETS_MS.length + 1).fill(0) });
1814
+ }
1815
+ t.count++;
1816
+ if (failed) t.errors++;
1817
+ t.buckets[latencyBucket(ms)]++;
1818
+ }
1819
+ /** Turn the collected timings into metric events (every minute, or now when `force`). */
1820
+ queueTimings(force = false) {
1821
+ if (!this.timings.size || this.noMetrics || !force && Date.now() - this.timingsSince < 6e4) return;
1822
+ for (const [key, t] of this.timings) this.push({ type: "metric", id: uid(), ts: now(), name: "http", key: key.slice(0, 300), count: t.count, errors: t.errors, buckets: t.buckets });
1823
+ this.timings.clear();
1824
+ this.timingsSince = Date.now();
1825
+ }
1826
+ async flush() {
1827
+ this.queueTimings(this.closing);
1828
+ if (this.flushing) await this.flushing.catch(() => {
1829
+ });
1830
+ if (this.flushing) return this.flushing;
1831
+ if (!this.ready || this.queue.length === 0 || Date.now() < this.backoffUntil) return;
1832
+ const batch = this.queue.splice(0, this.opts.maxBatch);
1833
+ this.flushing = this.send(batch).then(() => {
1834
+ this.failures = 0;
1835
+ }).catch((err) => {
1836
+ this.queue.unshift(...batch);
1837
+ this.failures++;
1838
+ this.backoffUntil = Date.now() + Math.min(6e4, 1e3 * 2 ** this.failures);
1839
+ this.log("flush failed", err);
1840
+ }).finally(() => {
1841
+ this.flushing = void 0;
1842
+ void this.persist();
1843
+ });
1844
+ return this.flushing;
1845
+ }
1846
+ /** Stop the flush timer, undo automatic instrumentation and send what is queued. */
1847
+ closing = false;
1848
+ close() {
1849
+ if (this.timer) clearInterval(this.timer);
1850
+ this.uninstrument();
1851
+ this.closing = true;
1852
+ return this.flush().finally(() => this.closing = false);
1853
+ }
1854
+ /* ---------------- internals ---------------- */
1855
+ /** @internal Used by the platform entry points for errors that have no thrown value. */
1856
+ captureError(e, meta, request) {
1857
+ if (!this.ready) return;
1858
+ const handled = meta.handled ?? true;
1859
+ const frames = e.frames ?? parseStack(e.stack);
1860
+ if (!meta.fatal && !this.allowError(`${e.name}|${e.message.slice(0, 120)}|${frames[0]?.file ?? ""}:${frames[0]?.line ?? ""}`)) return;
1861
+ if (this.auto.sessions && (!handled || meta.fatal)) {
1862
+ if (!this.sessionState.errored) {
1863
+ this.sessionState.errored = true;
1864
+ this.push({ type: "session", id: uid(), ts: now(), status: "errored" });
1865
+ }
1866
+ if (meta.fatal && !this.sessionState.crashed) {
1867
+ this.sessionState.crashed = true;
1868
+ this.push({ type: "session", id: uid(), ts: now(), status: "crashed" });
1869
+ }
1870
+ }
1871
+ (meta.fatal ? this.push : this.enqueue).call(this, {
1872
+ type: "error",
1873
+ id: uid(),
1874
+ ts: now(),
1875
+ flow: meta.flow,
1876
+ step: meta.step,
1877
+ tags: meta.tags,
1878
+ severity: meta.severity ?? (meta.fatal ? "critical" : void 0),
1879
+ handled,
1880
+ error: { name: e.name, message: e.message, stack: e.stack, frames },
1881
+ breadcrumbs: [...this.crumbs],
1882
+ request
1883
+ });
1884
+ }
1885
+ /** Per-minute limits: one runaway error can't flood the queue, the network or your database. */
1886
+ allowError(signature) {
1887
+ const max = this.opts.maxErrorsPerMinute ?? 60;
1888
+ const t = Date.now();
1889
+ const hit = (key, cap) => {
1890
+ let l = this.limits.get(key);
1891
+ if (!l || t - l.since > 6e4) this.limits.set(key, l = { n: 0, since: t });
1892
+ return ++l.n <= cap;
1893
+ };
1894
+ if (this.limits.size > 200) this.limits.clear();
1895
+ const ok = hit("*", max) && hit(signature, Math.max(1, Math.ceil(max / 6)));
1896
+ if (!ok) this.log("rate limited", signature);
1897
+ return ok;
1898
+ }
1899
+ sampled() {
1900
+ const r = this.opts.sampleRate ?? 1;
1901
+ return r >= 1 || Math.random() < r;
1902
+ }
1903
+ enqueue(e) {
1904
+ if (!this.ready || !this.sampled()) return;
1905
+ this.push(e);
1906
+ }
1907
+ /** Queue without sampling (sessions must be complete for crash-free rates to be right). */
1908
+ push(e) {
1909
+ if (!this.ready) return;
1910
+ const out = this.opts.beforeSend ? this.opts.beforeSend(e) : e;
1911
+ if (!out) return;
1912
+ this.queue.push(out);
1913
+ if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);
1914
+ if (out.type === "error" || this.queue.length >= this.opts.maxBatch) void this.flush();
1915
+ else void this.persist();
1916
+ }
1917
+ buildContext() {
1918
+ const c = this.opts.context ?? {};
1919
+ return {
1920
+ ...c,
1921
+ app: { ...c.app ?? {}, ...this.opts.app },
1922
+ os: { name: "unknown", ...c.os ?? {} },
1923
+ runtime: { name: "unknown", ...c.runtime ?? {} },
1924
+ device: c.device ?? {}
1925
+ };
1926
+ }
1927
+ /** Set when the ingest rejects 0.2 fields: it predates them, so send what it understands. */
1928
+ legacyIngest = false;
1929
+ async send(events) {
1930
+ if (this.noMetrics) events = events.filter((e) => e.type !== "metric");
1931
+ if (this.legacyIngest) events = toLegacy(events);
1932
+ if (!events.length) return;
1933
+ const body = {
1934
+ sdk: { name: SDK_NAME, version: SDK_VERSION },
1935
+ context: this.buildContext(),
1936
+ user: this.user,
1937
+ session: this.session,
1938
+ events
1939
+ };
1940
+ const f = this.opts.fetch ?? this.rawFetch ?? fetch;
1941
+ const json = JSON.stringify(body);
1942
+ const res = await f(this.opts.endpoint, {
1943
+ method: "POST",
1944
+ headers: { "content-type": "application/json", "x-debug-key": this.opts.ingestKey },
1945
+ body: json,
1946
+ // Lets the last batch finish when the page is closing. Browsers cap keepalive bodies at 64 KB.
1947
+ ...typeof window !== "undefined" && json.length < 6e4 ? { keepalive: true } : {}
1948
+ });
1949
+ if (res.status >= 400 && res.status < 500 && res.status !== 429) {
1950
+ this.log(`ingest rejected batch (${res.status})`, await res.text().catch(() => ""));
1951
+ if (res.status === 400 && !this.noMetrics && events.some((e) => e.type === "metric")) {
1952
+ this.noMetrics = true;
1953
+ this.timings.clear();
1954
+ return this.send(events);
1955
+ }
1956
+ if (res.status === 400 && !this.legacyIngest && hasNewFields(events)) {
1957
+ this.legacyIngest = true;
1958
+ return this.send(events);
1959
+ }
1960
+ return;
1961
+ }
1962
+ if (!res.ok) throw new Error(`ingest responded ${res.status}`);
1963
+ }
1964
+ async persist() {
1965
+ try {
1966
+ await this.opts.storage?.setItem(QUEUE_KEY, JSON.stringify(this.queue));
1967
+ } catch {
1968
+ }
1969
+ }
1970
+ /**
1971
+ * Reuse the install's anonymous id: from localStorage in browsers straight away, or from the
1972
+ * `storage` option (AsyncStorage in React Native) once it loads. Events queued before then
1973
+ * carry the new id, which only matters for the very first launch.
1974
+ */
1975
+ loadAnonymousId() {
1976
+ const ws = webStorage();
1977
+ if (ws) {
1978
+ try {
1979
+ const saved = ws.getItem(ANON_KEY);
1980
+ if (saved) this.user = { ...this.user, anonymousId: saved };
1981
+ else ws.setItem(ANON_KEY, this.user.anonymousId);
1982
+ } catch {
1983
+ }
1984
+ return;
1423
1985
  }
1424
- 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.`);
1986
+ const storage = this.opts.storage;
1987
+ if (!storage) return;
1988
+ void (async () => {
1989
+ try {
1990
+ const saved = await storage.getItem(ANON_KEY);
1991
+ if (saved) this.user = { ...this.user, anonymousId: saved };
1992
+ else await storage.setItem(ANON_KEY, this.user.anonymousId);
1993
+ } catch {
1994
+ }
1995
+ })();
1425
1996
  }
1426
- if (!tableArn) throw new Error(`AWS didn't return the ARN for table ${table}.`);
1427
- const ttl = (await ddb.send(new ddbMod.DescribeTimeToLiveCommand({ TableName: table }))).TimeToLiveDescription;
1428
- const ttlOn = ttl?.TimeToLiveStatus === "ENABLED" || ttl?.TimeToLiveStatus === "ENABLING";
1429
- if (ttlOn && ttl?.AttributeName !== "ttl") {
1430
- p.log.warn(`${table} already expires items on "${ttl?.AttributeName}", so deBug's raw events won't expire on their own. Clean them up yourself, or use a separate table.`);
1431
- } else if (!ttlOn) {
1432
- await ddb.send(new ddbMod.UpdateTimeToLiveCommand({ TableName: table, TimeToLiveSpecification: { AttributeName: "ttl", Enabled: true } }));
1997
+ async restore() {
1998
+ try {
1999
+ const raw = await this.opts.storage?.getItem(QUEUE_KEY);
2000
+ if (raw) this.queue.unshift(...JSON.parse(raw));
2001
+ } catch {
2002
+ }
1433
2003
  }
1434
- p.log.success(`DynamoDB table ${table} is ready (30-day expiry on raw events)`);
1435
- const iam = new iamMod.IAMClient(base);
1436
- s.start(`Setting up IAM role ${roleName}`);
1437
- let roleArn;
1438
- let newRole = false;
1439
- const role = await lookup(() => iam.send(new iamMod.GetRoleCommand({ RoleName: roleName })));
1440
- if (role) {
1441
- if (!role.Role?.Tags?.some((t) => t.Key === CREATED_BY && t.Value === "debugkit")) {
1442
- s.error(`Role ${roleName} exists and wasn't created by deBug`);
1443
- bail(`deBug won't change a role it didn't create. Delete or rename ${roleName}, or choose another table name.`);
2004
+ installGlobalHandlers() {
2005
+ this.handlersInstalled = true;
2006
+ const g2 = globalThis;
2007
+ if (g2.ErrorUtils?.setGlobalHandler) {
2008
+ const prev = g2.ErrorUtils.getGlobalHandler?.();
2009
+ g2.ErrorUtils.setGlobalHandler((err, isFatal) => {
2010
+ this.error(err, { handled: false, fatal: !!isFatal, tags: { source: "global-handler" } });
2011
+ void this.flush();
2012
+ prev?.(err, isFatal);
2013
+ });
2014
+ }
2015
+ if (typeof window !== "undefined" && typeof g2.addEventListener === "function") {
2016
+ g2.addEventListener("error", (ev) => this.error(ev.error ?? ev.message, { handled: false, tags: { source: "window.onerror" } }));
2017
+ g2.addEventListener("unhandledrejection", (ev) => this.error(ev.reason, { handled: false, tags: { source: "unhandledrejection" } }));
1444
2018
  }
1445
- roleArn = role.Role.Arn;
1446
- } else {
1447
- roleArn = (await iam.send(
1448
- new iamMod.CreateRoleCommand({
1449
- RoleName: roleName,
1450
- Description: `deBug ingest Lambda: writes to the DynamoDB table ${table}`.slice(0, 1e3),
1451
- AssumeRolePolicyDocument: JSON.stringify({
1452
- Version: "2012-10-17",
1453
- Statement: [{ Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole", Condition: { StringEquals: { "aws:SourceAccount": account } } }]
1454
- }),
1455
- Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
1456
- })
1457
- )).Role.Arn;
1458
- newRole = true;
1459
2019
  }
1460
- await iam.send(new iamMod.AttachRolePolicyCommand({ RoleName: roleName, PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" }));
1461
- await iam.send(
1462
- new iamMod.PutRolePolicyCommand({
1463
- RoleName: roleName,
1464
- PolicyName: "debugkit-table-write",
1465
- PolicyDocument: JSON.stringify({
1466
- Version: "2012-10-17",
1467
- Statement: [{ Effect: "Allow", Action: ["dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:BatchWriteItem", "dynamodb:GetItem"], Resource: tableArn }]
1468
- })
1469
- })
1470
- );
1471
- s.stop(`IAM role ${roleName} can write to ${table} and nothing else`);
1472
- const lambda = new lambdaMod.LambdaClient(base);
1473
- const zip = lambdaZip();
1474
- s.start(`Deploying Lambda ${functionName}`);
1475
- const fn = await lookup(() => lambda.send(new lambdaMod.GetFunctionCommand({ FunctionName: functionName })));
1476
- if (fn) {
1477
- if (fn.Tags?.[CREATED_BY] !== "debugkit") {
1478
- s.error(`Function ${functionName} exists and wasn't created by deBug`);
1479
- bail(`deBug won't overwrite a function it didn't create. Rename ${functionName}, or choose another table name.`);
2020
+ instrument() {
2021
+ const a = this.auto;
2022
+ const sink = this.sink();
2023
+ const add = (r) => r && this.restores.push(r);
2024
+ if (a.network) {
2025
+ const restoreFetch = instrumentFetch(sink);
2026
+ if (restoreFetch) globalThis.fetch.__raw = this.rawFetch;
2027
+ add(restoreFetch);
2028
+ add(instrumentXhr(sink));
1480
2029
  }
1481
- const keys = mergeKeys(fn.Configuration?.Environment?.Variables?.DEBUG_INGEST_KEYS, ctx.ingestKey, ctx.app.appId);
1482
- await lambda.send(new lambdaMod.UpdateFunctionCodeCommand({ FunctionName: functionName, ZipFile: zip }));
1483
- await waitUpdated(lambda, lambdaMod, functionName);
1484
- await lambda.send(
1485
- new lambdaMod.UpdateFunctionConfigurationCommand({
1486
- FunctionName: functionName,
1487
- Role: roleArn,
1488
- Environment: {
1489
- Variables: { ...fn.Configuration?.Environment?.Variables, DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keys, DEBUG_RETENTION_DAYS: String(ctx.retentionDays), DEBUG_ADMIN_TOKEN: ctx.adminToken }
2030
+ if (a.console) add(instrumentConsole(sink));
2031
+ if (a.navigation) add(instrumentHistory(sink));
2032
+ if (a.clicks) add(instrumentClicks(sink));
2033
+ if (a.lifecycle) add(instrumentWebLifecycle(sink));
2034
+ }
2035
+ uninstrument() {
2036
+ while (this.restores.length) this.restores.pop()();
2037
+ }
2038
+ /** The bridge the instrumentation (./auto, and the platform entry points) reports through. */
2039
+ sink() {
2040
+ return {
2041
+ request: (r) => this.recordRequest(r),
2042
+ crumb: (category, message, level = "info", data) => this.breadcrumb(category, message, data, level),
2043
+ navigated: (to) => this.navigated(to),
2044
+ lifecycle: (state) => {
2045
+ this.breadcrumb("ui", state === "background" ? "App went to the background" : "App came to the foreground");
2046
+ if (state === "background") {
2047
+ this.queueTimings(true);
2048
+ void this.flush();
1490
2049
  }
1491
- })
2050
+ },
2051
+ ignored: (url) => this.isIgnored(url)
2052
+ };
2053
+ }
2054
+ isIgnored(url) {
2055
+ if (!this.ready) return true;
2056
+ const ep = this.opts.endpoint.replace(/^https?:/, "");
2057
+ if (url.includes(ep) || /\/symbolicate\b|\/logs(?:\?|$)/.test(url)) return true;
2058
+ return (this.opts.network?.ignoreUrls ?? []).some((p2) => typeof p2 === "string" ? url.includes(p2) : p2.test(url));
2059
+ }
2060
+ recordRequest(r) {
2061
+ if (!this.ready) return;
2062
+ const net = this.opts.network ?? {};
2063
+ const url = normaliseUrl(r.url);
2064
+ const ms = Math.round(r.durationMs);
2065
+ const failed = r.status === void 0 ? !r.aborted : (net.isFailure ?? ((s) => s >= 500))(r.status, url);
2066
+ const slow = ms >= (net.slowMs ?? 3e3);
2067
+ const outcome = r.aborted ? "aborted" : r.timedOut ? "timed out" : r.status !== void 0 ? String(r.status) : "failed";
2068
+ this.breadcrumb("network", `${r.method} ${url} \u2192 ${outcome} (${ms}ms)`, { status: r.status ?? null, durationMs: ms }, failed ? "error" : slow ? "warning" : "info");
2069
+ if (!r.aborted) this.timeRequest(`${r.method} ${url}`, ms, failed);
2070
+ if (!failed) return;
2071
+ const flow = net.flows?.find(([p2]) => typeof p2 === "string" ? url.includes(p2) : p2.test(url))?.[1];
2072
+ const cause = r.error ? normaliseError(r.error) : void 0;
2073
+ const message = r.status !== void 0 ? `${r.method} ${url} responded ${r.status}` : `${r.method} ${url} ${r.timedOut ? "timed out" : "failed"}${cause ? `: ${cause.message}` : ""}`;
2074
+ const frames = parseStack(r.stack).slice(1);
2075
+ this.captureError(
2076
+ { name: r.status !== void 0 ? "HttpError" : "NetworkError", message, stack: r.stack, frames },
2077
+ { flow, handled: true, tags: { source: "network" } },
2078
+ { method: r.method, url, status: r.status, durationMs: ms }
1492
2079
  );
1493
- } else {
1494
- const env = { Variables: { DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId), DEBUG_RETENTION_DAYS: String(ctx.retentionDays), DEBUG_ADMIN_TOKEN: ctx.adminToken } };
1495
- for (let attempt = 0; ; attempt++) {
2080
+ }
2081
+ log(...args) {
2082
+ if (this.opts?.debug) console.warn("[deBug]", ...args);
2083
+ }
2084
+ };
2085
+ function normaliseError(err) {
2086
+ if (err instanceof Error) return { name: err.name || "Error", message: err.message, stack: err.stack };
2087
+ if (typeof err === "string") return { name: "Error", message: err };
2088
+ try {
2089
+ return { name: "NonError", message: JSON.stringify(err).slice(0, 2e3) };
2090
+ } catch {
2091
+ return { name: "NonError", message: String(err) };
2092
+ }
2093
+ }
2094
+ function resolveAuto(o) {
2095
+ const all = o.autoCapture !== false;
2096
+ const sel = typeof o.autoCapture === "object" ? o.autoCapture : {};
2097
+ const pick = (k, dflt = all) => sel[k] ?? dflt;
2098
+ return {
2099
+ errors: o.captureGlobalErrors ?? pick("errors"),
2100
+ network: pick("network"),
2101
+ console: pick("console"),
2102
+ navigation: pick("navigation"),
2103
+ clicks: pick("clicks"),
2104
+ lifecycle: pick("lifecycle"),
2105
+ sessions: pick("sessions")
2106
+ };
2107
+ }
2108
+ var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type === "error" && e.request);
2109
+ function toLegacy(events) {
2110
+ const out = [];
2111
+ for (const e of events) {
2112
+ if (e.type === "session" || e.type === "metric") continue;
2113
+ if (e.type === "error" && e.request) {
2114
+ const { request: _r, ...rest } = e;
2115
+ out.push(rest);
2116
+ } else out.push(e);
2117
+ }
2118
+ return out;
2119
+ }
2120
+
2121
+ // ../sdk/src/index.ts
2122
+ var deBug = new DebugClient();
2123
+
2124
+ // src/guide.ts
2125
+ init_exec();
2126
+ function automaticFor(platform, app) {
2127
+ const common = [
2128
+ `${bold("Crashes")}: uncaught errors and unhandled promise rejections, with the stack trace`,
2129
+ `${bold("Failed requests")}: every request is a breadcrumb; timeouts, network failures and 5xx responses become errors that point at the line that made the call`,
2130
+ `${bold("Sessions")}: each launch is marked started, then errored or crashed, which gives the crash-free rate per release`,
2131
+ `${bold("Context")}: device, OS, app version and network on every event`
2132
+ ];
2133
+ switch (platform) {
2134
+ case "expo":
2135
+ case "react-native":
2136
+ return [
2137
+ ...common,
2138
+ `${bold("Lifecycle")}: the app going to the background and back; a new session after 30 minutes away`,
2139
+ `${bold("Console")}: console.warn and console.error as breadcrumbs`,
2140
+ app.expoRouter || app.reactNavigation ? `${bold("Screens")}: every screen change, once you add the ${code(app.expoRouter ? "useDebugExpoRouter()" : "trackReactNavigation()")} line` : `${bold("Screens")}: add the router helper from the SDK for screen-change breadcrumbs`,
2141
+ `${bold("Offline")}: events wait in a queue and send when the connection is back`
2142
+ ];
2143
+ case "node":
2144
+ return [...common.slice(0, 2), `${bold("Server errors")}: 5xx responses your server sends, and outgoing node:http requests (axios, SDKs)`, common[3], `${bold("Clean exit")}: on a crash, events are sent before the process exits`];
2145
+ default:
2146
+ return [
2147
+ ...common,
2148
+ `${bold("Navigation")}: every page change, with any router`,
2149
+ `${bold("Clicks")}: buttons and links, by their label (never what people type)`,
2150
+ `${bold("Console and lifecycle")}: console warnings, the tab hidden or shown, going offline`
2151
+ ];
2152
+ }
2153
+ }
2154
+ function sdkImport(platform) {
2155
+ return platform === "expo" ? "@debugkit/sdk/expo" : platform === "react-native" ? "@debugkit/sdk/react-native" : platform === "node" ? "@debugkit/sdk/node" : "@debugkit/sdk/react";
2156
+ }
2157
+ var MANUAL = (platform) => `import { deBug } from "${sdkImport(platform)}";
2158
+
2159
+ // 1. In a try/catch you already have: report it, tagged with the part of the app
2160
+ try {
2161
+ await chargeCard(order);
2162
+ } catch (err) {
2163
+ deBug.error(err, { flow: "checkout.payment", step: "charge" });
2164
+ showPaymentError();
2165
+ }
2166
+
2167
+ // 2. A step that can succeed or fail: deBug logs the outcome (and the error),
2168
+ // so the dashboard can say "18% of logins fail", not just "12 errors"
2169
+ await deBug.track("auth.login", "submit_otp", () => api.verifyOtp(code));
2170
+
2171
+ // 3. Something that isn't an error but matters
2172
+ deBug.event("signup_abandoned", { flow: "onboarding.signup", outcome: "abandoned" });
2173
+
2174
+ // 4. Who it happened to (an id, not personal data), once they sign in
2175
+ deBug.setUser(user.id);`;
2176
+ async function sendTestEvents(cfg, app) {
2177
+ const failures = [];
2178
+ let sent = 0;
2179
+ const client = new DebugClient().init({
2180
+ endpoint: cfg.endpoint,
2181
+ ingestKey: cfg.ingestKey,
2182
+ app: { id: cfg.appId, version: app.version ?? "0.0.0", environment: "debugkit-test" },
2183
+ context: { os: { name: process.platform, version: process.version }, runtime: { name: "debugkit-cli" }, device: { type: "desktop", model: "debugkit test" } },
2184
+ autoCapture: { sessions: true, errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false },
2185
+ flushIntervalMs: 0,
2186
+ fetch: async (url, init2) => {
2187
+ let res;
1496
2188
  try {
1497
- await lambda.send(
1498
- new lambdaMod.CreateFunctionCommand({
1499
- FunctionName: functionName,
1500
- Runtime: "nodejs22.x",
1501
- Architectures: ["arm64"],
1502
- Handler: "index.handler",
1503
- Role: roleArn,
1504
- Code: { ZipFile: zip },
1505
- MemorySize: 256,
1506
- Timeout: 10,
1507
- Environment: env,
1508
- Description: "deBug ingest: receives SDK events and writes them to DynamoDB",
1509
- Tags: { [CREATED_BY]: "debugkit" }
1510
- })
1511
- );
1512
- break;
2189
+ res = await fetch(url, init2);
1513
2190
  } catch (err) {
1514
- if (attempt < 10 && /cannot be assumed|role defined for the function/i.test(err.message)) {
1515
- s.message(newRole ? "Waiting for the new IAM role to be ready" : "Retrying");
1516
- await sleep(3e3);
1517
- } else throw err;
2191
+ failures.push(`couldn't reach it (${err.message})`);
2192
+ throw err;
1518
2193
  }
2194
+ if (res.ok) sent += (JSON.parse(String(init2?.body ?? "{}")).events ?? []).length;
2195
+ else failures.push(`it answered ${res.status}: ${(await res.clone().text().catch(() => "")).slice(0, 200)}`);
2196
+ return res;
1519
2197
  }
1520
- }
1521
- await waitUpdated(lambda, lambdaMod, functionName);
1522
- const urlCfg = await lookup(() => lambda.send(new lambdaMod.GetFunctionUrlConfigCommand({ FunctionName: functionName })));
1523
- const url = urlCfg?.FunctionUrl ?? (await lambda.send(new lambdaMod.CreateFunctionUrlConfigCommand({ FunctionName: functionName, AuthType: "NONE" }))).FunctionUrl;
1524
- if (!url) throw new Error(`AWS didn't return a URL for ${functionName}.`);
1525
- for (const [sid, input] of [
1526
- ["debugkit-public-url", { Action: "lambda:InvokeFunctionUrl", FunctionUrlAuthType: "NONE" }],
1527
- ["debugkit-public-invoke", { Action: "lambda:InvokeFunction", InvokedViaFunctionUrl: true }]
1528
- ]) {
1529
- try {
1530
- await lambda.send(new lambdaMod.AddPermissionCommand({ FunctionName: functionName, StatementId: sid, Principal: "*", ...input }));
1531
- } catch (err) {
1532
- if (err.name !== "ResourceConflictException") p.log.warn(`Couldn't add ${sid}: ${err.message}`);
1533
- }
1534
- }
1535
- s.stop(`Lambda ${functionName} is live at ${url}`);
1536
- let readOnlyPolicyArn = `arn:aws:iam::${account}:policy/debugkit-dashboard-readonly-${table}`.slice(0, 2048);
1537
- try {
1538
- if (!await lookup(() => iam.send(new iamMod.GetPolicyCommand({ PolicyArn: readOnlyPolicyArn }))))
1539
- await iam.send(
1540
- new iamMod.CreatePolicyCommand({
1541
- PolicyName: `debugkit-dashboard-readonly-${table}`.slice(0, 128),
1542
- PolicyDocument: JSON.stringify({
1543
- Version: "2012-10-17",
1544
- Statement: [{ Effect: "Allow", Action: ["dynamodb:GetItem", "dynamodb:Query", "dynamodb:DescribeTable"], Resource: tableArn }]
1545
- }),
1546
- Description: `Read-only access to the deBug table ${table}, for hosting the dashboard`,
1547
- Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
1548
- })
1549
- );
1550
- } catch (err) {
1551
- p.log.warn(`Skipped the read-only dashboard policy: ${err.message}`);
1552
- readOnlyPolicyArn = void 0;
1553
- }
1554
- return {
1555
- config: { provider: "aws", endpoint: url.replace(/\/$/, ""), ingestKey: ctx.ingestKey, aws: { region, profile, table, functionName, roleName, readOnlyPolicyArn } },
1556
- dashboardEnv: { DEBUG_STORE: "dynamodb", AWS_REGION: region, DEBUG_DYNAMO_TABLE: table, ...profile ? { AWS_PROFILE: profile } : {}, ...adminEnv(url, ctx) },
1557
- created: [
1558
- `DynamoDB table ${code(table)} in ${region}${ownTable ? " (on-demand)" : " (your existing table)"}`,
1559
- `Lambda ${code(functionName)} with a public URL: ${code(url)}`,
1560
- `IAM role ${code(roleName)} that can only write to the table`,
1561
- ...readOnlyPolicyArn ? [`Read-only policy for hosting the dashboard: ${code(readOnlyPolicyArn)}`] : []
1562
- ]
1563
- };
1564
- }
1565
- var CREATED_BY = "created-by";
1566
- async function lookup(fn) {
2198
+ });
2199
+ client.navigated("/cart");
2200
+ client.navigated("/checkout");
2201
+ client.breadcrumb("ui", 'Clicked button "Pay now"');
2202
+ client.breadcrumb("network", "POST /v1/payments/intent \u2192 503 (1840ms)", { status: 503, durationMs: 1840 }, "error");
2203
+ client.captureError(
2204
+ { name: "HttpError", message: "POST /v1/payments/intent responded 503 (test event from npx debugkit)", stack: new Error().stack },
2205
+ { flow: "onboarding.test", handled: true, tags: { source: "network", test: "true" } },
2206
+ { method: "POST", url: "/v1/payments/intent", status: 503, durationMs: 1840 }
2207
+ );
1567
2208
  try {
1568
- return await fn();
2209
+ JSON.parse("<html>502 Bad Gateway</html>");
1569
2210
  } catch (err) {
1570
- const name = err.name ?? "";
1571
- if (name === "ResourceNotFoundException" || name === "NoSuchEntityException" || name === "NoSuchEntity") return void 0;
1572
- throw err;
1573
- }
1574
- }
1575
- async function waitUpdated(lambda, mod, name) {
1576
- for (let i = 0; i < 60; i++) {
1577
- const c = await lambda.send(new mod.GetFunctionConfigurationCommand({ FunctionName: name }));
1578
- if (c.State !== "Pending" && c.LastUpdateStatus !== "InProgress") return;
1579
- await sleep(1500);
2211
+ client.error(err, { flow: "onboarding.test", step: "parse_receipt", tags: { test: "true" } });
1580
2212
  }
2213
+ await client.track("onboarding.test", "submit", async () => true);
2214
+ await client.track("onboarding.test", "submit", async () => Promise.reject(new Error("Test failure from deBug.track()")), { captureError: false }).catch(() => {
2215
+ });
2216
+ for (let i = 0; i < 5 && client.pending && !failures.length; i++) await client.flush();
2217
+ await client.close();
2218
+ if (!failures.length && client.pending) failures.push(`${client.pending} events weren't sent`);
2219
+ return { sent, error: failures.length ? failures.join("; ") : void 0 };
1581
2220
  }
1582
-
1583
- // src/providers/firebase.ts
1584
- init_exec();
1585
- import { existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "fs";
1586
- import { join as join5 } from "path";
1587
-
1588
- // ../adapters/firestore.indexes.json
1589
- var firestore_indexes_default = {
1590
- indexes: [
1591
- {
1592
- collectionGroup: "rollups",
1593
- queryScope: "COLLECTION",
1594
- fields: [
1595
- {
1596
- fieldPath: "dimension",
1597
- order: "ASCENDING"
1598
- },
1599
- {
1600
- fieldPath: "day",
1601
- order: "ASCENDING"
1602
- }
1603
- ]
1604
- },
1605
- {
1606
- collectionGroup: "events",
1607
- queryScope: "COLLECTION",
1608
- fields: [
1609
- {
1610
- fieldPath: "fingerprint",
1611
- order: "ASCENDING"
1612
- },
1613
- {
1614
- fieldPath: "ts",
1615
- order: "DESCENDING"
1616
- }
1617
- ]
1618
- },
1619
- {
1620
- collectionGroup: "users",
1621
- queryScope: "COLLECTION",
1622
- fields: [
1623
- {
1624
- fieldPath: "scope",
1625
- order: "ASCENDING"
1626
- },
1627
- {
1628
- fieldPath: "lastDay",
1629
- order: "ASCENDING"
1630
- }
1631
- ]
1632
- }
1633
- ],
1634
- fieldOverrides: [
1635
- {
1636
- collectionGroup: "events",
1637
- fieldPath: "expireAt",
1638
- ttl: true,
1639
- indexes: []
1640
- },
1641
- {
1642
- collectionGroup: "rollups",
1643
- fieldPath: "expireAt",
1644
- ttl: true,
1645
- indexes: []
1646
- }
1647
- ]
1648
- };
1649
-
1650
- // src/providers/firebase.ts
1651
- var LOCATIONS = [
1652
- { value: "africa-south1", label: "Johannesburg (africa-south1)", region: "africa-south1" },
1653
- { value: "eur3", label: "Europe, multi-region (eur3)", region: "europe-west1" },
1654
- { value: "europe-west1", label: "Belgium (europe-west1)", region: "europe-west1" },
1655
- { value: "nam5", label: "United States, multi-region (nam5)", region: "us-central1" },
1656
- { value: "us-central1", label: "Iowa (us-central1)", region: "us-central1" },
1657
- { value: "asia-southeast1", label: "Singapore (asia-southeast1)", region: "asia-southeast1" }
1658
- ];
1659
- var FUNCTION_NAME = "debugIngest";
1660
- var CODEBASE = "debugkit";
1661
- var MIN_FIREBASE_TOOLS = 14;
1662
- async function firebaseCli() {
1663
- if (which("firebase")) {
1664
- const v = await capture("firebase", ["--version"]);
1665
- const major = Number(/^(\d+)/.exec(v.stdout.trim())?.[1] ?? 0);
1666
- if (major >= MIN_FIREBASE_TOOLS) return ["firebase", []];
1667
- p.log.info(dim(`Your Firebase CLI is ${v.stdout.trim()}; deBug needs ${MIN_FIREBASE_TOOLS}+ for Node 22, so it'll use npx firebase-tools@latest (same sign-in).`));
2221
+ async function waitForArrival(cwd, url, appId, timeoutMs = 9e4) {
2222
+ const until = Date.now() + timeoutMs;
2223
+ let last;
2224
+ while (Date.now() < until) {
2225
+ last = await summary(cwd, url, appId);
2226
+ if (last.ok && last.data?.app === appId && last.data?.issues?.length) return last;
2227
+ await new Promise((r) => setTimeout(r, 2e3));
1668
2228
  }
1669
- return ["npx", ["-y", "firebase-tools@latest"]];
2229
+ return last;
1670
2230
  }
1671
- var emailsIn = (text2) => [...new Set(text2.match(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g) ?? [])];
1672
- async function setupFirebase(ctx) {
1673
- const [fbCmd, fbPre] = await firebaseCli();
1674
- const fb = (args, opts = {}) => capture(fbCmd, [...fbPre, ...args], opts);
1675
- const fbLive = (args, opts = {}) => interactive(fbCmd, [...fbPre, ...args], opts);
2231
+ async function walkthrough(opts) {
2232
+ const { cwd, app, cfg, dashboardUrl } = opts;
2233
+ const before = await summary(cwd, dashboardUrl, cfg.appId);
2234
+ const empty = before.status === 404 || before.ok && before.data?.app !== cfg.appId;
1676
2235
  p.note(
1677
2236
  [
1678
- "deBug deploys a small ingest function and a Firestore database into your own Firebase project.",
1679
- "Firebase will ask you to sign in with Google and allow the Firebase CLI to manage your projects.",
1680
- "That access stays on this machine. deBug doesn't receive it."
1681
- ].join("\n"),
1682
- "Sign in to Firebase"
1683
- );
1684
- let accounts = emailsIn((await fb(["login:list"])).stdout);
1685
- let account;
1686
- if (!accounts.length) {
1687
- await next("Open the Google sign-in page");
1688
- if (await fbLive(["login"]) !== 0) bail("Firebase sign-in didn't finish. Run npx debugkit init to try again.");
1689
- accounts = emailsIn((await fb(["login:list"])).stdout);
1690
- }
1691
- const ADD = "__add__";
1692
- const picked = await choose(
1693
- "Which Google account should own the deBug resources?",
1694
- [...accounts.map((a) => ({ value: a, label: a })), { value: ADD, label: "Sign in with another account" }],
1695
- accounts[0]
1696
- );
1697
- if (picked === ADD) {
1698
- if (await fbLive(["login:add"]) !== 0) bail("Firebase sign-in didn't finish.");
1699
- const now2 = emailsIn((await fb(["login:list"])).stdout);
1700
- account = now2.find((a) => !accounts.includes(a)) ?? now2[0] ?? bail("No Firebase account is signed in.");
1701
- } else account = picked;
1702
- const acct = ["--account", account];
1703
- const s = p.spinner();
1704
- s.start("Loading your Firebase projects");
1705
- const list = await fb(["projects:list", "--json", ...acct]);
1706
- s.stop("Loaded your Firebase projects");
1707
- let projects = [];
1708
- try {
1709
- projects = JSON.parse(list.stdout).result ?? [];
1710
- } catch {
1711
- p.log.warn(`Couldn't read the project list: ${dim(list.stderr.slice(-300))}`);
1712
- }
1713
- const NEW = "__new__";
1714
- let projectId = await choose(
1715
- "Which Firebase project should deBug use?",
1716
- [
1717
- { value: NEW, label: "Create a new project", hint: "recommended: keeps deBug's data and bill separate" },
1718
- ...projects.map((x) => ({ value: x.projectId, label: x.displayName ? `${x.displayName}` : x.projectId, hint: x.projectId }))
1719
- ],
1720
- NEW
2237
+ `${bold("Your dashboard is running")} at ${code(dashboardUrl)}`,
2238
+ loginHint(cwd),
2239
+ "",
2240
+ empty ? `It's connected to your ${cfg.provider === "local" ? "local" : cfg.provider === "aws" ? "DynamoDB" : "Firestore"} data and ${bold("empty")}: nothing has been sent yet.` : before.ok ? "It's connected, and already has data for this app." : `It couldn't read your data yet (${before.status || "no answer"}: ${before.error ?? "unknown"}). The test below will tell us more.`
2241
+ ].join("\n"),
2242
+ "1 \xB7 The dashboard"
1721
2243
  );
1722
- if (projectId === NEW) {
1723
- const suggested = `${ctx.app.appId}-debug`.slice(0, 26).replace(/-+$/, "") + `-${Math.random().toString(36).slice(2, 6)}`;
1724
- projectId = await ask("Project id (lowercase, globally unique)", {
1725
- initial: suggested,
1726
- validate: (v) => /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(v) ? void 0 : "6\u201330 characters: lowercase letters, digits and dashes"
1727
- });
1728
- if (await fbLive(["projects:create", projectId, "--display-name", `${ctx.app.name} deBug`.slice(0, 30), ...acct]) !== 0)
1729
- bail(`Couldn't create ${projectId}. Pick an existing project or another id.`);
1730
- }
1731
- const proj = ["--project", projectId, ...acct];
2244
+ openUrl(dashboardUrl);
2245
+ await next("I'm signed in");
1732
2246
  p.note(
1733
2247
  [
1734
- "Cloud Functions only run on Firebase's pay-as-you-go plan (Blaze).",
1735
- "deBug's ingest typically stays inside the free monthly allowance, but Google requires a billing account.",
1736
- `If ${projectId} is already on Blaze, skip this.`
2248
+ `${bold("A written summary")}: how many errors today, the worst part of the app, the top issue, the struggling release`,
2249
+ `${bold("Issues by severity")}: errors grouped by cause; open one for the stack trace and the steps that led to it`,
2250
+ `${bold("Release health")}: crash-free and error-free sessions per app version`,
2251
+ `${bold("Failing endpoints")}: requests that time out, fail or return 5xx`,
2252
+ `${bold("Where the app is failing")}: errors and failure rates per flow, like auth.login`,
2253
+ `${bold("Breakdowns")}: by OS, app version and device`
1737
2254
  ].join("\n"),
1738
- "Billing"
2255
+ "2 \xB7 What you'll see there"
1739
2256
  );
1740
- if (await yes(`Open the billing page for ${projectId} to check or upgrade?`, true)) {
1741
- openUrl(`https://console.firebase.google.com/project/${projectId}/usage/details`);
1742
- await next("I've checked: it's on Blaze");
1743
- }
1744
- let location2;
1745
- const existingDb = await defaultDatabase(fb, proj);
1746
- if (existingDb) {
1747
- location2 = existingDb.locationId;
1748
- p.log.info(`Using the existing Firestore database in ${projectId} (${location2})`);
2257
+ await next("Send a test event");
2258
+ const s = p.spinner();
2259
+ s.start(`Sending test events to ${cfg.endpoint}`);
2260
+ const sent = await sendTestEvents(cfg, app);
2261
+ if (sent.error) {
2262
+ s.error(`The ingest didn't accept them: ${sent.error}`);
2263
+ 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.");
1749
2264
  } else {
1750
- location2 = await choose("Where should the Firestore database live? This can't be changed later.", LOCATIONS.map(({ value, label }) => ({ value, label })), "africa-south1");
1751
- s.start(`Creating the Firestore database in ${location2}`);
1752
- const r = await fb(["firestore:databases:create", "(default)", "--location", location2, ...proj]);
1753
- if (r.code !== 0 && !/already exists/i.test(r.stderr + r.stdout)) {
1754
- s.error("Couldn't create the database");
1755
- p.log.error((r.stderr || r.stdout).slice(-600));
1756
- bail("Fix the error above (often: the Firestore API needs enabling, or billing), then run npx debugkit init again.");
2265
+ s.message("Sent. Waiting for the dashboard to show them");
2266
+ const after = await waitForArrival(cwd, dashboardUrl, cfg.appId);
2267
+ if (after?.ok && after.data?.issues?.length) {
2268
+ s.stop("They arrived");
2269
+ const d = after.data;
2270
+ p.note(
2271
+ [
2272
+ ...(d.narrative ?? []).map((l) => `\u201C${l}\u201D`),
2273
+ "",
2274
+ `${bold(String(d.issues.length))} issues \xB7 ${bold(String(d.health?.sessionsRange ?? 0))} session \xB7 failing endpoint ${code(d.health?.endpoints?.[0]?.endpoint ?? "\u2014")}`,
2275
+ "",
2276
+ `Refresh the dashboard. You'll see a ${pc.red("HttpError")} from a failed request (captured the way the SDK does it automatically),`,
2277
+ `a ${pc.red("SyntaxError")} reported from a try/catch, and the ${code("onboarding.test")} flow with a 50% failure rate from track().`,
2278
+ dim("They're tagged environment debugkit-test, version " + (app.version ?? "0.0.0") + ". Raw events expire after 30 days.")
2279
+ ].join("\n"),
2280
+ "3 \xB7 Your first events"
2281
+ );
2282
+ } else {
2283
+ s.error("Sent, but the dashboard doesn't show them yet");
2284
+ p.log.warn(`The dashboard said: ${after?.status ?? "?"} ${after?.error ?? ""}. Refresh it in a minute, or run npx debugkit test again.`);
1757
2285
  }
1758
- s.stop(`Created the Firestore database (${location2})`);
1759
- }
1760
- const region = functionRegion(location2);
1761
- const dir = writeFunctionSource(ctx, region, projectId);
1762
- s.start("Installing the ingest function's dependencies");
1763
- const inst = await capture("npm", ["install", "--no-audit", "--no-fund"], { cwd: join5(dir, "functions") });
1764
- if (inst.code !== 0) {
1765
- s.error("npm install failed");
1766
- p.log.error(inst.stderr.slice(-600));
1767
- bail();
1768
2286
  }
1769
- s.stop("Installed the ingest function's dependencies");
2287
+ await next("What does the SDK do on its own?");
2288
+ p.note(
2289
+ [`Once ${code("debug." + (app.typescript ? "ts" : "js"))} runs, the SDK records this in the background, with no other code:`, "", ...automaticFor(app.platform, app).map((l) => `\u2022 ${l}`), "", dim("Every error carries the last 30 breadcrumbs: the screen, the tap, the request that failed. Query strings and request bodies never leave the device.")].join("\n"),
2290
+ `4 \xB7 Automatic in ${PLATFORM_LABEL[app.platform]}`
2291
+ );
2292
+ await next("What do I add myself?");
1770
2293
  p.note(
1771
2294
  [
1772
- `In ${bold(projectId)}${environment.get() ? ` (your ${environment.get()} environment)` : ""}, deBug will add:`,
1773
- `\u2022 a Cloud Function ${code(FUNCTION_NAME)} in ${region}, with a public URL (each request needs the ingest key)`,
1774
- `\u2022 a ${code("debug_apps")} collection in Firestore, with raw events expiring after 30 days`,
1775
- `\u2022 two Firestore indexes for it (your existing indexes are left alone)`,
2295
+ "Automatic capture says what broke. What it can't know is which part of your app a step belongs to, and whether it worked.",
2296
+ `That's what ${code("flow")} is for: a dotted name like ${code("auth.login")} that the dashboard groups everything by.`,
1776
2297
  "",
1777
- "Nothing else in the project is changed. Usage is billed to the project's Blaze plan."
2298
+ MANUAL(app.platform)
1778
2299
  ].join("\n"),
1779
- "About to deploy"
1780
- );
1781
- if (!await yes(`Deploy deBug into ${projectId}?`)) bail("Nothing was deployed.");
1782
- p.log.step("Adding deBug's Firestore indexes (your existing indexes are left alone)");
1783
- if (await fbLive(["deploy", "--only", "firestore:indexes", "--non-interactive", ...proj], { cwd: dir }) !== 0)
1784
- p.log.warn("The indexes didn't deploy. The dashboard needs them; deploy them later with the command printed at the end.");
1785
- p.log.step(`Deploying ${code(FUNCTION_NAME)}. The first deploy turns on the Google APIs it needs and takes a few minutes.`);
1786
- for (; ; ) {
1787
- const exit = await fbLive(["deploy", "--only", `functions:${CODEBASE}`, "--force", ...proj], { cwd: dir });
1788
- if (exit === 0) break;
1789
- p.log.warn("The deploy didn't finish: see the error above. Common causes: the project isn't on the Blaze plan, or your account lacks permission to deploy functions.");
1790
- const again = await choose(
1791
- "What now?",
1792
- [
1793
- { value: "retry", label: "Retry the deploy" },
1794
- { value: "billing", label: "Open billing, then retry" },
1795
- { value: "stop", label: "Stop here" }
1796
- ],
1797
- "retry"
1798
- );
1799
- 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}`);
1800
- if (again === "billing") {
1801
- openUrl(`https://console.firebase.google.com/project/${projectId}/usage/details`);
1802
- await next("Upgraded: retry the deploy");
1803
- }
1804
- }
1805
- const endpoint = `https://${region}-${projectId}.cloudfunctions.net/${FUNCTION_NAME}`;
1806
- await ensureDashboardAccess(projectId);
1807
- return {
1808
- config: { provider: "firebase", endpoint, ingestKey: ctx.ingestKey, firebase: { projectId, region, account, location: location2 } },
1809
- dashboardEnv: { DEBUG_STORE: "firestore", GOOGLE_CLOUD_PROJECT: projectId, GCLOUD_PROJECT: projectId, ...adminEnv(endpoint, ctx) },
1810
- created: [
1811
- `Firestore database in ${code(projectId)} (${location2}), with indexes and 30-day expiry on raw events`,
1812
- `Cloud Function ${code(FUNCTION_NAME)} in ${region}: ${code(endpoint)}`,
1813
- `Function source in ${code(".debugkit/firebase")}, so you can redeploy it with the Firebase CLI`
1814
- ]
1815
- };
1816
- }
1817
- async function ensureDashboardAccess(projectId) {
1818
- if (!which("gcloud")) {
1819
- p.log.warn(
1820
- [
1821
- "The dashboard reads Firestore with Google Cloud credentials, and gcloud isn't installed.",
1822
- `Install it (${code("https://cloud.google.com/sdk/docs/install")}), then run ${code("gcloud auth application-default login")}.`,
1823
- "Or create a read-only service account (role: Cloud Datastore Viewer) and set GOOGLE_APPLICATION_CREDENTIALS in .debugkit/dashboard.env."
1824
- ].join("\n")
1825
- );
1826
- return;
1827
- }
1828
- const t = await capture("gcloud", ["auth", "application-default", "print-access-token"]);
1829
- if (t.code === 0) {
1830
- p.log.success("The dashboard will read Firestore with your Google Cloud credentials");
1831
- return;
1832
- }
1833
- p.note("One more Google sign-in: this one lets the dashboard on this machine read deBug's data.", "Dashboard access");
1834
- await next("Open the Google sign-in page");
1835
- const exit = await interactive("gcloud", ["auth", "application-default", "login", "--quiet"]);
1836
- if (exit !== 0) p.log.warn("Google Cloud sign-in didn't finish. The dashboard won't be able to read Firestore until you run: gcloud auth application-default login");
1837
- else await capture("gcloud", ["auth", "application-default", "set-quota-project", projectId]);
1838
- }
1839
- async function defaultDatabase(fb, proj) {
1840
- const r = await fb(["firestore:databases:get", "(default)", "--json", ...proj]);
1841
- if (r.code !== 0) return void 0;
1842
- try {
1843
- const db = JSON.parse(r.stdout).result;
1844
- return db?.locationId ? { locationId: db.locationId } : void 0;
1845
- } catch {
1846
- return void 0;
1847
- }
1848
- }
1849
- function functionRegion(location2) {
1850
- const known = LOCATIONS.find((l) => l.value === location2)?.region;
1851
- if (known) return known;
1852
- if (location2 === "nam7") return "us-central1";
1853
- if (location2.startsWith("eur")) return "europe-west1";
1854
- if (location2.startsWith("nam")) return "us-central1";
1855
- return /^[a-z]+-[a-z]+\d+$/.test(location2) ? location2 : "us-central1";
1856
- }
1857
- function writeFunctionSource(ctx, region, projectId = "default") {
1858
- const dir = paths(ctx.app.cwd).firebase;
1859
- mkdirSync2(join5(dir, "functions"), { recursive: true });
1860
- writeFileSync2(
1861
- join5(dir, "firebase.json"),
1862
- JSON.stringify(
1863
- {
1864
- functions: [{ source: "functions", codebase: CODEBASE, runtime: "nodejs22" }],
1865
- firestore: { database: "(default)", indexes: "firestore.indexes.json" }
1866
- },
1867
- null,
1868
- 2
1869
- ) + "\n"
1870
- );
1871
- writeFileSync2(join5(dir, "firestore.indexes.json"), JSON.stringify(firestore_indexes_default, null, 2) + "\n");
1872
- writeFileSync2(
1873
- join5(dir, "functions", "package.json"),
1874
- JSON.stringify(
1875
- {
1876
- name: "debugkit-ingest",
1877
- private: true,
1878
- type: "module",
1879
- main: "index.js",
1880
- engines: { node: "22" },
1881
- dependencies: {
1882
- // Same release as this CLI (the packages are versioned together).
1883
- "@debugkit/adapters": `^${VERSION}`,
1884
- "@debugkit/ingest": `^${VERSION}`,
1885
- "firebase-admin": "^13.0.0",
1886
- "firebase-functions": "^7.0.0"
1887
- }
1888
- },
1889
- null,
1890
- 2
1891
- ) + "\n"
2300
+ "5 \xB7 What you add in your own try/catches"
1892
2301
  );
1893
- writeFileSync2(
1894
- join5(dir, "functions", "index.js"),
1895
- `// deBug ingest, deployed by npx debugkit init. Receives events from the SDK and writes them to Firestore.
1896
- import { initializeApp } from "firebase-admin/app";
1897
- import { getFirestore } from "firebase-admin/firestore";
1898
- import { onRequest } from "firebase-functions/v2/https";
1899
- import { FirestoreStore } from "@debugkit/adapters/firestore";
1900
- import { parseIngestKeys } from "@debugkit/ingest";
1901
- import { firebaseHandler } from "@debugkit/ingest/firebase";
1902
-
1903
- initializeApp();
1904
-
1905
- export const ${FUNCTION_NAME} = onRequest(
1906
- { region: ${JSON.stringify(region)}, invoker: "public", memory: "256MiB", maxInstances: 10 },
1907
- firebaseHandler({
1908
- store: new FirestoreStore(getFirestore()),
1909
- keys: parseIngestKeys(process.env.DEBUG_INGEST_KEYS),
1910
- retentionDays: Number(process.env.DEBUG_RETENTION_DAYS) || undefined,
1911
- adminToken: process.env.DEBUG_ADMIN_TOKEN,
1912
- }),
1913
- );
1914
- `
2302
+ await next("Show me what's left to do");
2303
+ p.note(
2304
+ [
2305
+ ...opts.remaining.map((l, i) => `${i + 1}. ${l}`),
2306
+ `${opts.remaining.length + 1}. Run the app and watch the dashboard fill in`,
2307
+ "",
2308
+ `${code(cmdFor("dashboard"))} open the dashboard again`,
2309
+ `${code(cmdFor("test"))} send another test event`,
2310
+ `${code(cmdFor("guide"))} replay this walkthrough`
2311
+ ].join("\n"),
2312
+ "6 \xB7 Finish wiring your app"
1915
2313
  );
1916
- const envFile = join5(dir, "functions", ".env");
1917
- const current2 = existsSync5(envFile) ? /^DEBUG_INGEST_KEYS=(.*)$/m.exec(readFileSync4(envFile, "utf8"))?.[1] : void 0;
1918
- writeFileSync2(envFile, `DEBUG_INGEST_KEYS=${mergeKeys(current2, ctx.ingestKey, ctx.app.appId)}
1919
- DEBUG_RETENTION_DAYS=${ctx.retentionDays}
1920
- `);
1921
- writeFileSync2(join5(dir, "functions", `.env.${projectId}`), `DEBUG_ADMIN_TOKEN=${ctx.adminToken}
1922
- `, { mode: 384 });
1923
- return dir;
1924
2314
  }
1925
2315
 
1926
2316
  // src/providers/local.ts
@@ -1951,8 +2341,8 @@ async function setupLocal(ctx) {
1951
2341
  }
1952
2342
 
1953
2343
  // src/wire.ts
1954
- import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
1955
- import { dirname as dirname2, join as join6, relative } from "path";
2344
+ import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
2345
+ import { dirname as dirname2, join as join7, relative as relative2 } from "path";
1956
2346
  init_exec();
1957
2347
  var ENV_ENDPOINT = "DEBUG_ENDPOINT";
1958
2348
  var ENV_KEY = "DEBUG_KEY";
@@ -1979,7 +2369,7 @@ async function installSdk(app) {
1979
2369
  }
1980
2370
  function writeAppEnv(app, conn) {
1981
2371
  if (!app.envPrefix) return void 0;
1982
- const file = join6(app.cwd, ".env");
2372
+ const file = join7(app.cwd, ".env");
1983
2373
  upsertEnv(file, { [`${app.envPrefix}${ENV_ENDPOINT}`]: conn.endpoint, [`${app.envPrefix}${ENV_KEY}`]: conn.ingestKey });
1984
2374
  return file;
1985
2375
  }
@@ -1991,8 +2381,8 @@ function envValues(app, conn, env) {
1991
2381
  }
1992
2382
  function initFile(app, conn, multiEnv = environment.get() !== void 0) {
1993
2383
  const ext = app.typescript ? "ts" : "js";
1994
- const path2 = join6(app.cwd, app.sourceDir, `debug.${ext}`);
1995
- const rel = relative(app.cwd, path2);
2384
+ const path2 = join7(app.cwd, app.sourceDir, `debug.${ext}`);
2385
+ const rel = relative2(app.cwd, path2);
1996
2386
  const env = (k) => app.envPrefix === "VITE_" ? `import.meta.env.${app.envPrefix}${k}` : `process.env.${app.envPrefix ?? ""}${k}`;
1997
2387
  const header = `// Set up by npx debugkit init. Import this file once, as early as possible.
1998
2388
  `;
@@ -2103,7 +2493,7 @@ async function wireApp(app, conn) {
2103
2493
  const extra = [];
2104
2494
  if (env) {
2105
2495
  const values = app.platform === "react-native" ? {} : envValues(app, conn, env);
2106
- const usesEas = app.platform === "expo" && existsSync6(join6(app.cwd, "eas.json"));
2496
+ const usesEas = app.platform === "expo" && existsSync7(join7(app.cwd, "eas.json"));
2107
2497
  let done = Object.keys(values).length === 0;
2108
2498
  if (!done && usesEas && EAS_ENVIRONMENTS.includes(env) && await yes(`Set the endpoint and key in EAS's ${env} environment (eas env:set)?`)) done = await writeEasEnv(app, values, env);
2109
2499
  if (!done) {
@@ -2113,9 +2503,9 @@ async function wireApp(app, conn) {
2113
2503
  } else {
2114
2504
  const envFile = writeAppEnv(app, conn);
2115
2505
  if (envFile) {
2116
- p.log.success(`Wrote ${code(`${app.envPrefix}${ENV_ENDPOINT}`)} and ${code(`${app.envPrefix}${ENV_KEY}`)} to ${code(relative(app.cwd, envFile))}`);
2506
+ p.log.success(`Wrote ${code(`${app.envPrefix}${ENV_ENDPOINT}`)} and ${code(`${app.envPrefix}${ENV_KEY}`)} to ${code(relative2(app.cwd, envFile))}`);
2117
2507
  } else if (app.platform === "node") {
2118
- upsertEnv(join6(app.cwd, ".env"), { [ENV_ENDPOINT]: conn.endpoint, [ENV_KEY]: conn.ingestKey });
2508
+ upsertEnv(join7(app.cwd, ".env"), { [ENV_ENDPOINT]: conn.endpoint, [ENV_KEY]: conn.ingestKey });
2119
2509
  p.log.success(`Wrote ${code(ENV_ENDPOINT)} and ${code(ENV_KEY)} to ${code(".env")}`);
2120
2510
  }
2121
2511
  if (envFile || app.platform === "node") {
@@ -2123,12 +2513,12 @@ async function wireApp(app, conn) {
2123
2513
  }
2124
2514
  }
2125
2515
  const f = initFile(app, conn);
2126
- const rel = relative(app.cwd, f.path);
2127
- const current2 = existsSync6(f.path) ? readFileSync5(f.path, "utf8") : void 0;
2516
+ const rel = relative2(app.cwd, f.path);
2517
+ const current2 = existsSync7(f.path) ? readFileSync6(f.path, "utf8") : void 0;
2128
2518
  if (current2 === f.contents) p.log.info(`${code(rel)} is already up to date`);
2129
2519
  else if (current2 === void 0 || await yes(`${rel} already exists. Replace it?`, false)) {
2130
- mkdirSync3(dirname2(f.path), { recursive: true });
2131
- writeFileSync3(f.path, f.contents);
2520
+ mkdirSync4(dirname2(f.path), { recursive: true });
2521
+ writeFileSync4(f.path, f.contents);
2132
2522
  p.log.success(`${current2 === void 0 ? "Created" : "Updated"} ${code(rel)}`);
2133
2523
  } else {
2134
2524
  p.log.info(`Kept your ${rel}. The generated version is:
@@ -2142,7 +2532,8 @@ var HELP = `${bold("debugkit")} ${VERSION}: set up deBug in your app
2142
2532
  ${dim("Run as npx debugkit <command> once @debugkit/sdk is installed, or npx @debugkit/cli <command> anywhere.")}
2143
2533
 
2144
2534
  ${code("npx debugkit init")} choose a cloud, deploy ingest to your account, wire the SDK, walk through the dashboard
2145
- ${code("npx debugkit dashboard")} run the dashboard against your data
2535
+ ${code("npx debugkit dashboard")} run the dashboard against your data, on this machine
2536
+ ${code("npx debugkit deploy-dashboard")} host the dashboard in your Firebase or AWS account, at a link you can share
2146
2537
  ${code("npx debugkit test")} send test events and check they arrive
2147
2538
  ${code("npx debugkit guide")} replay the walkthrough
2148
2539
  ${code("npx debugkit password")} reset the dashboard login
@@ -2249,7 +2640,7 @@ async function init(cwd, preset) {
2249
2640
  p.log.error(err.message);
2250
2641
  bail("Setup stopped. Nothing else was changed in your app. Fix the error above and run npx debugkit init again.");
2251
2642
  }
2252
- const cfg = { ...result.config, appId: app.appId, dashboardPort, retentionDays, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
2643
+ const cfg = { ...result.config, ...existing?.provider === provider && existing.hosted ? { hosted: existing.hosted } : {}, appId: app.appId, dashboardPort, retentionDays, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
2253
2644
  writeConfig(cwd, cfg);
2254
2645
  p.note(result.created.map((l) => `\u2022 ${l}`).join("\n"), "Created");
2255
2646
  const remaining = await wireApp(app, cfg);
@@ -2270,15 +2661,41 @@ async function init(cwd, preset) {
2270
2661
  return;
2271
2662
  }
2272
2663
  dash.stop();
2664
+ let hostedUrl = cfg.hosted?.url;
2665
+ p.note(
2666
+ [
2667
+ `The dashboard ran on this machine. deBug can also host it in your ${provider === "aws" ? "AWS account" : "Firebase project"}, reading the same data,`,
2668
+ "at a link you can share with your team. It signs in with the same login. You can still run it locally."
2669
+ ].join("\n"),
2670
+ "Host the dashboard?"
2671
+ );
2672
+ if (await yes(hostedUrl ? `Update the hosted dashboard at ${hostedUrl}?` : "Host the dashboard online too?", !hostedUrl)) {
2673
+ try {
2674
+ hostedUrl = (await hostDashboard(cwd, readConfig(cwd) ?? cfg)).url;
2675
+ } catch (err) {
2676
+ p.log.error(err.message);
2677
+ p.log.info(`deBug itself is set up. Try hosting again with ${code(cmdFor("deploy-dashboard"))}.`);
2678
+ }
2679
+ } else p.log.info(dim(`Any time later: ${cmdFor("deploy-dashboard")}`));
2273
2680
  const others = listEnvironments(cwd).filter((e) => e !== environment.get());
2274
2681
  p.outro(
2275
- `deBug is set up${envLabel()}. Open the dashboard any time with ${code(cmdFor("dashboard"))}.` + (environment.get() && !others.length ? `
2682
+ `deBug is set up${envLabel()}. ${hostedUrl ? `Share the dashboard: ${code(hostedUrl)}. ` : ""}Open it locally any time with ${code(cmdFor("dashboard"))}.` + (environment.get() && !others.length ? `
2276
2683
  Set up the next environment the same way, e.g. ${code("npx debugkit init --env production")}.` : "")
2277
2684
  );
2278
2685
  }
2686
+ async function deployDashboard(cwd) {
2687
+ const cfg = requireConfig(cwd);
2688
+ p.intro(`${pc.bgRed(pc.white(" deBug "))} host the dashboard${envLabel()}`);
2689
+ 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.`);
2690
+ const { url } = await hostDashboard(cwd, cfg);
2691
+ const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_exec(), exec_exports));
2692
+ openUrl2(url);
2693
+ p.outro(`Share ${code(url)} with your team. ${loginHint(cwd)}`);
2694
+ }
2279
2695
  async function dashboard(cwd) {
2280
2696
  const cfg = requireConfig(cwd);
2281
2697
  p.intro(`${pc.bgRed(pc.white(" deBug "))} dashboard${envLabel()}`);
2698
+ if (cfg.hosted) p.log.info(`Also online at ${code(cfg.hosted.url)}`);
2282
2699
  const dash = await startDashboard(cwd);
2283
2700
  p.log.info(`${code(dash.url)} \xB7 reading ${cfg.provider === "local" ? "in-memory data (and accepting events)" : cfg.provider} \xB7 Ctrl-C to stop`);
2284
2701
  const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_exec(), exec_exports));
@@ -2316,9 +2733,10 @@ async function guide(cwd) {
2316
2733
  }
2317
2734
  }
2318
2735
  async function password(cwd) {
2319
- requireConfig(cwd);
2320
2736
  p.intro(`${pc.bgRed(pc.white(" deBug "))} reset the dashboard login`);
2737
+ const cfg = requireConfig(cwd);
2321
2738
  await resetLogin(cwd);
2739
+ if (cfg.hosted) p.log.info(`The hosted dashboard (${cfg.hosted.url}) still has the old login until you run ${code(cmdFor("deploy-dashboard"))}.`);
2322
2740
  p.outro(`Saved. Restart the dashboard (${code(cmdFor("dashboard"))}) and sign in with the new password.`);
2323
2741
  }
2324
2742
  async function main() {
@@ -2340,6 +2758,8 @@ async function main() {
2340
2758
  return init(args.cwd, args.provider);
2341
2759
  case "dashboard":
2342
2760
  return dashboard(args.cwd);
2761
+ case "deploy-dashboard":
2762
+ return deployDashboard(args.cwd);
2343
2763
  case "test":
2344
2764
  return test(args.cwd);
2345
2765
  case "guide":