@debugkit/cli 0.4.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/README.md +47 -5
- package/dist/cli.js +1966 -1392
- package/dist/lambda/index.mjs +3 -2
- package/package.json +4 -4
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*/.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.
|
|
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,1489 +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/
|
|
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 {
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
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
|
-
//
|
|
369
|
-
var
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
return file.replace(/^address at /, "");
|
|
375
|
-
}
|
|
376
|
-
function parseStack(stack) {
|
|
377
|
-
if (!stack) return [];
|
|
378
|
-
const frames = [];
|
|
379
|
-
for (const raw of stack.split("\n")) {
|
|
380
|
-
const m = V8.exec(raw) ?? GECKO.exec(raw);
|
|
381
|
-
if (!m) continue;
|
|
382
|
-
const [, fn, rawFile, line, col] = m;
|
|
383
|
-
const file = cleanFile(rawFile ?? "");
|
|
384
|
-
frames.push({
|
|
385
|
-
fn: fn || void 0,
|
|
386
|
-
file,
|
|
387
|
-
line: Number(line),
|
|
388
|
-
col: Number(col),
|
|
389
|
-
inApp: RN_BUNDLE.test(file) ? !/^(?:anonymous|eval|global code)$/.test(fn ?? "") : !NOT_IN_APP.some((re) => re.test(file))
|
|
390
|
-
});
|
|
391
|
-
if (frames.length >= 100) break;
|
|
392
|
-
}
|
|
393
|
-
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(",");
|
|
394
398
|
}
|
|
395
399
|
|
|
396
|
-
//
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
}
|
|
403
|
-
return out;
|
|
404
|
-
}
|
|
405
|
-
function safe(fn) {
|
|
406
|
-
try {
|
|
407
|
-
return fn();
|
|
408
|
-
} catch {
|
|
409
|
-
return void 0;
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
function timezone() {
|
|
413
|
-
return safe(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
414
|
-
}
|
|
415
|
-
function browserContext() {
|
|
416
|
-
if (typeof navigator === "undefined" || typeof window === "undefined") {
|
|
417
|
-
const ua2 = typeof navigator !== "undefined" ? navigator.userAgent : void 0;
|
|
418
|
-
const node = typeof process !== "undefined" ? process.versions?.node : void 0;
|
|
419
|
-
return {
|
|
420
|
-
runtime: { name: ua2 === "Cloudflare-Workers" ? "cloudflare-workers" : node ? "node" : "edge", version: node },
|
|
421
|
-
os: { name: "server" },
|
|
422
|
-
timezone: timezone()
|
|
423
|
-
};
|
|
424
|
-
}
|
|
425
|
-
const ua = navigator.userAgent;
|
|
426
|
-
const android = /Android ([\d.]+)/.exec(ua)?.[1];
|
|
427
|
-
const ios = /(?:iPhone|iPad|iPod).*? OS (\d+[_\d]*)/.exec(ua)?.[1];
|
|
428
|
-
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" };
|
|
429
|
-
const conn = navigator.connection;
|
|
430
|
-
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;
|
|
431
|
-
return {
|
|
432
|
-
os,
|
|
433
|
-
runtime: { name: "browser", version: browser ? `${browser.name} ${browser.v}` : void 0 },
|
|
434
|
-
device: {
|
|
435
|
-
type: /iPad|Tablet/.test(ua) ? "tablet" : /Mobi/.test(ua) ? "phone" : "desktop",
|
|
436
|
-
screen: typeof screen !== "undefined" ? { width: screen.width, height: screen.height, scale: window.devicePixelRatio } : void 0
|
|
437
|
-
},
|
|
438
|
-
network: conn ? {
|
|
439
|
-
type: conn.type === "wifi" ? "wifi" : conn.type === "cellular" ? "cellular" : "unknown",
|
|
440
|
-
effectiveType: conn.effectiveType,
|
|
441
|
-
isConnected: navigator.onLine
|
|
442
|
-
} : void 0,
|
|
443
|
-
locale: navigator.language,
|
|
444
|
-
timezone: timezone()
|
|
445
|
-
};
|
|
446
|
-
}
|
|
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
|
+
});
|
|
447
406
|
|
|
448
|
-
//
|
|
449
|
-
var
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
p2 = orig.call(this, input, init2);
|
|
473
|
-
} finally {
|
|
474
|
-
insideFetch--;
|
|
475
|
-
}
|
|
476
|
-
return p2.then(
|
|
477
|
-
(res) => {
|
|
478
|
-
sink.request({ method, url, status: res.status, durationMs: Date.now() - start, stack });
|
|
479
|
-
return res;
|
|
480
|
-
},
|
|
481
|
-
(error) => {
|
|
482
|
-
const aborted = error?.name === "AbortError";
|
|
483
|
-
sink.request({ method, url, error, aborted, durationMs: Date.now() - start, stack });
|
|
484
|
-
throw error;
|
|
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;
|
|
485
431
|
}
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
if (g.fetch === wrapped) g.fetch = orig;
|
|
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
|
+
}
|
|
492
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()];
|
|
493
441
|
}
|
|
494
|
-
function
|
|
495
|
-
const
|
|
496
|
-
const
|
|
497
|
-
if (!
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
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 });
|
|
447
|
+
}
|
|
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.`);
|
|
518
517
|
}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
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
|
+
})
|
|
537
|
+
);
|
|
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);
|
|
544
|
+
}
|
|
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.`);
|
|
546
|
+
}
|
|
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 } }));
|
|
554
|
+
}
|
|
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;
|
|
580
|
+
}
|
|
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.`);
|
|
601
|
+
}
|
|
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
|
+
}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
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
|
+
}
|
|
655
|
+
}
|
|
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;
|
|
674
|
+
}
|
|
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
|
+
]
|
|
527
684
|
};
|
|
528
685
|
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
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;
|
|
694
|
+
}
|
|
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);
|
|
701
|
+
}
|
|
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).`));
|
|
725
|
+
}
|
|
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);
|
|
747
|
+
}
|
|
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 = [];
|
|
532
765
|
try {
|
|
533
|
-
|
|
766
|
+
projects = JSON.parse(list.stdout).result ?? [];
|
|
534
767
|
} catch {
|
|
535
|
-
|
|
768
|
+
p.log.warn(`Couldn't read the project list: ${dim(list.stderr.slice(-300))}`);
|
|
769
|
+
}
|
|
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.`);
|
|
787
|
+
}
|
|
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");
|
|
800
|
+
}
|
|
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.");
|
|
814
|
+
}
|
|
815
|
+
s.stop(`Created the Firestore database (${location2})`);
|
|
816
|
+
}
|
|
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");
|
|
860
|
+
}
|
|
536
861
|
}
|
|
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
|
+
};
|
|
537
873
|
}
|
|
538
|
-
function
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
};
|
|
549
|
-
restores.push(() => c[method] = orig);
|
|
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;
|
|
550
884
|
}
|
|
551
|
-
|
|
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;
|
|
889
|
+
}
|
|
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]);
|
|
552
895
|
}
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
sink.navigated(path());
|
|
562
|
-
return out;
|
|
563
|
-
};
|
|
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;
|
|
564
904
|
}
|
|
565
|
-
const onPop = () => sink.navigated(path());
|
|
566
|
-
g.addEventListener("popstate", onPop);
|
|
567
|
-
sink.navigated(path());
|
|
568
|
-
return () => {
|
|
569
|
-
Object.assign(h, orig);
|
|
570
|
-
g.removeEventListener("popstate", onPop);
|
|
571
|
-
};
|
|
572
905
|
}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
return
|
|
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";
|
|
580
913
|
}
|
|
581
|
-
function
|
|
582
|
-
const
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
};
|
|
589
|
-
|
|
590
|
-
|
|
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;
|
|
591
975
|
}
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
return () => {
|
|
602
|
-
d.removeEventListener("visibilitychange", onVis);
|
|
603
|
-
g.removeEventListener("online", onOnline);
|
|
604
|
-
g.removeEventListener("offline", onOffline);
|
|
605
|
-
};
|
|
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 {
|
|
983
|
+
}
|
|
984
|
+
writeFileSync2(file, JSON.stringify(update(cur), null, 2) + "\n");
|
|
606
985
|
}
|
|
607
986
|
|
|
608
|
-
//
|
|
609
|
-
var
|
|
610
|
-
var
|
|
611
|
-
var
|
|
612
|
-
var
|
|
613
|
-
var
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
if (
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
if (this.opts.flushIntervalMs > 0) {
|
|
653
|
-
this.timer = setInterval(() => void this.flush(), this.opts.flushIntervalMs);
|
|
654
|
-
this.timer.unref?.();
|
|
655
|
-
}
|
|
656
|
-
return this;
|
|
657
|
-
}
|
|
658
|
-
/** Which automatic captures are on, after defaults. */
|
|
659
|
-
get autoCapture() {
|
|
660
|
-
return this.auto;
|
|
661
|
-
}
|
|
662
|
-
/**
|
|
663
|
-
* Begin a new session: a fresh id and a "started" marker. Called by `init()`, and by the
|
|
664
|
-
* React Native entry when the app returns after 30 minutes in the background.
|
|
665
|
-
*/
|
|
666
|
-
startSession() {
|
|
667
|
-
if (!this.ready) return;
|
|
668
|
-
void this.flush();
|
|
669
|
-
this.session = { id: uid(), startedAt: now() };
|
|
670
|
-
this.sessionState = { errored: false, crashed: false };
|
|
671
|
-
if (this.auto.sessions) this.push({ type: "session", id: uid(), ts: now(), status: "started" });
|
|
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 {
|
|
672
1031
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
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));
|
|
678
1042
|
}
|
|
679
|
-
|
|
680
|
-
|
|
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;
|
|
681
1066
|
}
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
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
|
+
}
|
|
685
1075
|
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
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;
|
|
689
1081
|
}
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
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;
|
|
1153
|
+
}
|
|
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));
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
693
1159
|
}
|
|
694
|
-
|
|
695
|
-
|
|
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();
|
|
1217
|
+
}
|
|
696
1218
|
}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
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);
|
|
704
1234
|
}
|
|
705
|
-
|
|
706
|
-
|
|
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 });
|
|
707
1251
|
}
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
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;
|
|
711
1298
|
}
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
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
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
await waitUpdated2(lambda, lambdaMod, functionName);
|
|
716
1334
|
}
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
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
|
+
]) {
|
|
723
1343
|
try {
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
} catch (err) {
|
|
728
|
-
this.event(`${flow}.${step}`, { flow, step, outcome: "failure" });
|
|
729
|
-
if (opts.captureError !== false) this.error(err, { flow, step });
|
|
730
|
-
throw err;
|
|
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}`);
|
|
731
1347
|
}
|
|
732
1348
|
}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
}).finally(() => {
|
|
747
|
-
this.flushing = void 0;
|
|
748
|
-
void this.persist();
|
|
749
|
-
});
|
|
750
|
-
return this.flushing;
|
|
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));
|
|
751
1362
|
}
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
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"
|
|
1376
|
+
};
|
|
1377
|
+
function detectApp(cwd) {
|
|
1378
|
+
let pkg = {};
|
|
1379
|
+
try {
|
|
1380
|
+
pkg = JSON.parse(readFileSync5(join6(cwd, "package.json"), "utf8"));
|
|
1381
|
+
} catch {
|
|
1382
|
+
throw new Error(`No package.json in ${cwd}. Run npx debugkit init from your app's folder.`);
|
|
757
1383
|
}
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
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";
|
|
1389
|
+
return {
|
|
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")
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
function toAppId(name) {
|
|
1406
|
+
return name.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "app";
|
|
1407
|
+
}
|
|
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]];
|
|
1416
|
+
default:
|
|
1417
|
+
return ["npm", ["install", ...pkgs]];
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
|
|
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))
|
|
787
1448
|
});
|
|
1449
|
+
if (frames.length >= 100) break;
|
|
788
1450
|
}
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
};
|
|
798
|
-
if (this.limits.size > 200) this.limits.clear();
|
|
799
|
-
const ok = hit("*", max) && hit(signature, Math.max(1, Math.ceil(max / 6)));
|
|
800
|
-
if (!ok) this.log("rate limited", signature);
|
|
801
|
-
return ok;
|
|
1451
|
+
return frames;
|
|
1452
|
+
}
|
|
1453
|
+
|
|
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;
|
|
802
1460
|
}
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
1461
|
+
return out;
|
|
1462
|
+
}
|
|
1463
|
+
function safe(fn) {
|
|
1464
|
+
try {
|
|
1465
|
+
return fn();
|
|
1466
|
+
} catch {
|
|
1467
|
+
return void 0;
|
|
806
1468
|
}
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
1469
|
+
}
|
|
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
|
+
};
|
|
810
1482
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
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
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
|
|
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}`;
|
|
1516
|
+
}
|
|
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--;
|
|
1533
|
+
}
|
|
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
|
+
};
|
|
1551
|
+
}
|
|
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}`;
|
|
1590
|
+
try {
|
|
1591
|
+
return JSON.stringify(arg) ?? String(arg);
|
|
1592
|
+
} catch {
|
|
1593
|
+
return String(arg);
|
|
820
1594
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
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);
|
|
829
1606
|
};
|
|
1607
|
+
restores.push(() => c[method] = orig);
|
|
830
1608
|
}
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
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;
|
|
842
1621
|
};
|
|
843
|
-
const f = this.opts.fetch ?? this.rawFetch ?? fetch;
|
|
844
|
-
const json = JSON.stringify(body);
|
|
845
|
-
const res = await f(this.opts.endpoint, {
|
|
846
|
-
method: "POST",
|
|
847
|
-
headers: { "content-type": "application/json", "x-debug-key": this.opts.ingestKey },
|
|
848
|
-
body: json,
|
|
849
|
-
// Lets the last batch finish when the page is closing. Browsers cap keepalive bodies at 64 KB.
|
|
850
|
-
...typeof window !== "undefined" && json.length < 6e4 ? { keepalive: true } : {}
|
|
851
|
-
});
|
|
852
|
-
if (res.status >= 400 && res.status < 500 && res.status !== 429) {
|
|
853
|
-
this.log(`ingest rejected batch (${res.status})`, await res.text().catch(() => ""));
|
|
854
|
-
if (res.status === 400 && !this.legacyIngest && hasNewFields(events)) {
|
|
855
|
-
this.legacyIngest = true;
|
|
856
|
-
return this.send(events);
|
|
857
|
-
}
|
|
858
|
-
return;
|
|
859
|
-
}
|
|
860
|
-
if (!res.ok) throw new Error(`ingest responded ${res.status}`);
|
|
861
|
-
}
|
|
862
|
-
async persist() {
|
|
863
|
-
try {
|
|
864
|
-
await this.opts.storage?.setItem(QUEUE_KEY, JSON.stringify(this.queue));
|
|
865
|
-
} catch {
|
|
866
|
-
}
|
|
867
1622
|
}
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
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;
|
|
874
1679
|
}
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
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;
|
|
889
1712
|
}
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
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?.();
|
|
900
1725
|
}
|
|
901
|
-
|
|
902
|
-
if (a.navigation) add(instrumentHistory(sink));
|
|
903
|
-
if (a.clicks) add(instrumentClicks(sink));
|
|
904
|
-
if (a.lifecycle) add(instrumentWebLifecycle(sink));
|
|
905
|
-
}
|
|
906
|
-
uninstrument() {
|
|
907
|
-
while (this.restores.length) this.restores.pop()();
|
|
908
|
-
}
|
|
909
|
-
/** The bridge the instrumentation (./auto, and the platform entry points) reports through. */
|
|
910
|
-
sink() {
|
|
911
|
-
return {
|
|
912
|
-
request: (r) => this.recordRequest(r),
|
|
913
|
-
crumb: (category, message, level = "info", data) => this.breadcrumb(category, message, data, level),
|
|
914
|
-
navigated: (to) => this.navigated(to),
|
|
915
|
-
lifecycle: (state) => {
|
|
916
|
-
this.breadcrumb("ui", state === "background" ? "App went to the background" : "App came to the foreground");
|
|
917
|
-
if (state === "background") void this.flush();
|
|
918
|
-
},
|
|
919
|
-
ignored: (url) => this.isIgnored(url)
|
|
920
|
-
};
|
|
1726
|
+
return this;
|
|
921
1727
|
}
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
if (url.includes(ep) || /\/symbolicate\b|\/logs(?:\?|$)/.test(url)) return true;
|
|
926
|
-
return (this.opts.network?.ignoreUrls ?? []).some((p2) => typeof p2 === "string" ? url.includes(p2) : p2.test(url));
|
|
1728
|
+
/** Which automatic captures are on, after defaults. */
|
|
1729
|
+
get autoCapture() {
|
|
1730
|
+
return this.auto;
|
|
927
1731
|
}
|
|
928
|
-
|
|
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() {
|
|
929
1737
|
if (!this.ready) return;
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
const slow = ms >= (net.slowMs ?? 3e3);
|
|
935
|
-
const outcome = r.aborted ? "aborted" : r.timedOut ? "timed out" : r.status !== void 0 ? String(r.status) : "failed";
|
|
936
|
-
this.breadcrumb("network", `${r.method} ${url} \u2192 ${outcome} (${ms}ms)`, { status: r.status ?? null, durationMs: ms }, failed ? "error" : slow ? "warning" : "info");
|
|
937
|
-
if (!failed) return;
|
|
938
|
-
const flow = net.flows?.find(([p2]) => typeof p2 === "string" ? url.includes(p2) : p2.test(url))?.[1];
|
|
939
|
-
const cause = r.error ? normaliseError(r.error) : void 0;
|
|
940
|
-
const message = r.status !== void 0 ? `${r.method} ${url} responded ${r.status}` : `${r.method} ${url} ${r.timedOut ? "timed out" : "failed"}${cause ? `: ${cause.message}` : ""}`;
|
|
941
|
-
const frames = parseStack(r.stack).slice(1);
|
|
942
|
-
this.captureError(
|
|
943
|
-
{ name: r.status !== void 0 ? "HttpError" : "NetworkError", message, stack: r.stack, frames },
|
|
944
|
-
{ flow, handled: true, tags: { source: "network" } },
|
|
945
|
-
{ method: r.method, url, status: r.status, durationMs: ms }
|
|
946
|
-
);
|
|
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" });
|
|
947
1742
|
}
|
|
948
|
-
|
|
949
|
-
|
|
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;
|
|
950
1748
|
}
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
if (err instanceof Error) return { name: err.name || "Error", message: err.message, stack: err.stack };
|
|
954
|
-
if (typeof err === "string") return { name: "Error", message: err };
|
|
955
|
-
try {
|
|
956
|
-
return { name: "NonError", message: JSON.stringify(err).slice(0, 2e3) };
|
|
957
|
-
} catch {
|
|
958
|
-
return { name: "NonError", message: String(err) };
|
|
1749
|
+
get initialized() {
|
|
1750
|
+
return this.ready;
|
|
959
1751
|
}
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
const sel = typeof o.autoCapture === "object" ? o.autoCapture : {};
|
|
964
|
-
const pick = (k, dflt = all) => sel[k] ?? dflt;
|
|
965
|
-
return {
|
|
966
|
-
errors: o.captureGlobalErrors ?? pick("errors"),
|
|
967
|
-
network: pick("network"),
|
|
968
|
-
console: pick("console"),
|
|
969
|
-
navigation: pick("navigation"),
|
|
970
|
-
clicks: pick("clicks"),
|
|
971
|
-
lifecycle: pick("lifecycle"),
|
|
972
|
-
sessions: pick("sessions")
|
|
973
|
-
};
|
|
974
|
-
}
|
|
975
|
-
var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type === "error" && e.request);
|
|
976
|
-
function toLegacy(events) {
|
|
977
|
-
const out = [];
|
|
978
|
-
for (const e of events) {
|
|
979
|
-
if (e.type === "session") continue;
|
|
980
|
-
if (e.type === "error" && e.request) {
|
|
981
|
-
const { request: _r, ...rest } = e;
|
|
982
|
-
out.push(rest);
|
|
983
|
-
} else out.push(e);
|
|
1752
|
+
/** False when init() was called with `enabled: false` (or not called yet). */
|
|
1753
|
+
get enabled() {
|
|
1754
|
+
return this.ready;
|
|
984
1755
|
}
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
// ../sdk/src/index.ts
|
|
989
|
-
var deBug = new DebugClient();
|
|
990
|
-
|
|
991
|
-
// src/guide.ts
|
|
992
|
-
init_exec();
|
|
993
|
-
function automaticFor(platform, app) {
|
|
994
|
-
const common = [
|
|
995
|
-
`${bold("Crashes")}: uncaught errors and unhandled promise rejections, with the stack trace`,
|
|
996
|
-
`${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`,
|
|
997
|
-
`${bold("Sessions")}: each launch is marked started, then errored or crashed, which gives the crash-free rate per release`,
|
|
998
|
-
`${bold("Context")}: device, OS, app version and network on every event`
|
|
999
|
-
];
|
|
1000
|
-
switch (platform) {
|
|
1001
|
-
case "expo":
|
|
1002
|
-
case "react-native":
|
|
1003
|
-
return [
|
|
1004
|
-
...common,
|
|
1005
|
-
`${bold("Lifecycle")}: the app going to the background and back; a new session after 30 minutes away`,
|
|
1006
|
-
`${bold("Console")}: console.warn and console.error as breadcrumbs`,
|
|
1007
|
-
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`,
|
|
1008
|
-
`${bold("Offline")}: events wait in a queue and send when the connection is back`
|
|
1009
|
-
];
|
|
1010
|
-
case "node":
|
|
1011
|
-
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`];
|
|
1012
|
-
default:
|
|
1013
|
-
return [
|
|
1014
|
-
...common,
|
|
1015
|
-
`${bold("Navigation")}: every page change, with any router`,
|
|
1016
|
-
`${bold("Clicks")}: buttons and links, by their label (never what people type)`,
|
|
1017
|
-
`${bold("Console and lifecycle")}: console warnings, the tab hidden or shown, going offline`
|
|
1018
|
-
];
|
|
1756
|
+
/** Events waiting to be sent. */
|
|
1757
|
+
get pending() {
|
|
1758
|
+
return this.queue.length;
|
|
1019
1759
|
}
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
}
|
|
1024
|
-
var MANUAL = (platform) => `import { deBug } from "${sdkImport(platform)}";
|
|
1025
|
-
|
|
1026
|
-
// 1. In a try/catch you already have: report it, tagged with the part of the app
|
|
1027
|
-
try {
|
|
1028
|
-
await chargeCard(order);
|
|
1029
|
-
} catch (err) {
|
|
1030
|
-
deBug.error(err, { flow: "checkout.payment", step: "charge" });
|
|
1031
|
-
showPaymentError();
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
// 2. A step that can succeed or fail: deBug logs the outcome (and the error),
|
|
1035
|
-
// so the dashboard can say "18% of logins fail", not just "12 errors"
|
|
1036
|
-
await deBug.track("auth.login", "submit_otp", () => api.verifyOtp(code));
|
|
1037
|
-
|
|
1038
|
-
// 3. Something that isn't an error but matters
|
|
1039
|
-
deBug.event("signup_abandoned", { flow: "onboarding.signup", outcome: "abandoned" });
|
|
1040
|
-
|
|
1041
|
-
// 4. Who it happened to (an id, not personal data), once they sign in
|
|
1042
|
-
deBug.setUser(user.id);`;
|
|
1043
|
-
async function sendTestEvents(cfg, app) {
|
|
1044
|
-
const failures = [];
|
|
1045
|
-
let sent = 0;
|
|
1046
|
-
const client = new DebugClient().init({
|
|
1047
|
-
endpoint: cfg.endpoint,
|
|
1048
|
-
ingestKey: cfg.ingestKey,
|
|
1049
|
-
app: { id: cfg.appId, version: app.version ?? "0.0.0", environment: "debugkit-test" },
|
|
1050
|
-
context: { os: { name: process.platform, version: process.version }, runtime: { name: "debugkit-cli" }, device: { type: "desktop", model: "debugkit test" } },
|
|
1051
|
-
autoCapture: { sessions: true, errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false },
|
|
1052
|
-
flushIntervalMs: 0,
|
|
1053
|
-
fetch: async (url, init2) => {
|
|
1054
|
-
let res;
|
|
1055
|
-
try {
|
|
1056
|
-
res = await fetch(url, init2);
|
|
1057
|
-
} catch (err) {
|
|
1058
|
-
failures.push(`couldn't reach it (${err.message})`);
|
|
1059
|
-
throw err;
|
|
1060
|
-
}
|
|
1061
|
-
if (res.ok) sent += (JSON.parse(String(init2?.body ?? "{}")).events ?? []).length;
|
|
1062
|
-
else failures.push(`it answered ${res.status}: ${(await res.clone().text().catch(() => "")).slice(0, 200)}`);
|
|
1063
|
-
return res;
|
|
1064
|
-
}
|
|
1065
|
-
});
|
|
1066
|
-
client.navigated("/cart");
|
|
1067
|
-
client.navigated("/checkout");
|
|
1068
|
-
client.breadcrumb("ui", 'Clicked button "Pay now"');
|
|
1069
|
-
client.breadcrumb("network", "POST /v1/payments/intent \u2192 503 (1840ms)", { status: 503, durationMs: 1840 }, "error");
|
|
1070
|
-
client.captureError(
|
|
1071
|
-
{ name: "HttpError", message: "POST /v1/payments/intent responded 503 (test event from npx debugkit)", stack: new Error().stack },
|
|
1072
|
-
{ flow: "onboarding.test", handled: true, tags: { source: "network", test: "true" } },
|
|
1073
|
-
{ method: "POST", url: "/v1/payments/intent", status: 503, durationMs: 1840 }
|
|
1074
|
-
);
|
|
1075
|
-
try {
|
|
1076
|
-
JSON.parse("<html>502 Bad Gateway</html>");
|
|
1077
|
-
} catch (err) {
|
|
1078
|
-
client.error(err, { flow: "onboarding.test", step: "parse_receipt", tags: { test: "true" } });
|
|
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);
|
|
1079
1763
|
}
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
});
|
|
1083
|
-
for (let i = 0; i < 5 && client.pending && !failures.length; i++) await client.flush();
|
|
1084
|
-
await client.close();
|
|
1085
|
-
if (!failures.length && client.pending) failures.push(`${client.pending} events weren't sent`);
|
|
1086
|
-
return { sent, error: failures.length ? failures.join("; ") : void 0 };
|
|
1087
|
-
}
|
|
1088
|
-
async function waitForArrival(cwd, url, appId, timeoutMs = 9e4) {
|
|
1089
|
-
const until = Date.now() + timeoutMs;
|
|
1090
|
-
let last;
|
|
1091
|
-
while (Date.now() < until) {
|
|
1092
|
-
last = await summary(cwd, url, appId);
|
|
1093
|
-
if (last.ok && last.data?.app === appId && last.data?.issues?.length) return last;
|
|
1094
|
-
await new Promise((r) => setTimeout(r, 2e3));
|
|
1764
|
+
setUser(id) {
|
|
1765
|
+
this.user = { ...this.user, id };
|
|
1095
1766
|
}
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
[
|
|
1104
|
-
`${bold("Your dashboard is running")} at ${code(dashboardUrl)}`,
|
|
1105
|
-
loginHint(cwd),
|
|
1106
|
-
"",
|
|
1107
|
-
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.`
|
|
1108
|
-
].join("\n"),
|
|
1109
|
-
"1 \xB7 The dashboard"
|
|
1110
|
-
);
|
|
1111
|
-
openUrl(dashboardUrl);
|
|
1112
|
-
await next("I'm signed in");
|
|
1113
|
-
p.note(
|
|
1114
|
-
[
|
|
1115
|
-
`${bold("A written summary")}: how many errors today, the worst part of the app, the top issue, the struggling release`,
|
|
1116
|
-
`${bold("Issues by severity")}: errors grouped by cause; open one for the stack trace and the steps that led to it`,
|
|
1117
|
-
`${bold("Release health")}: crash-free and error-free sessions per app version`,
|
|
1118
|
-
`${bold("Failing endpoints")}: requests that time out, fail or return 5xx`,
|
|
1119
|
-
`${bold("Where the app is failing")}: errors and failure rates per flow, like auth.login`,
|
|
1120
|
-
`${bold("Breakdowns")}: by OS, app version and device`
|
|
1121
|
-
].join("\n"),
|
|
1122
|
-
"2 \xB7 What you'll see there"
|
|
1123
|
-
);
|
|
1124
|
-
await next("Send a test event");
|
|
1125
|
-
const s = p.spinner();
|
|
1126
|
-
s.start(`Sending test events to ${cfg.endpoint}`);
|
|
1127
|
-
const sent = await sendTestEvents(cfg, app);
|
|
1128
|
-
if (sent.error) {
|
|
1129
|
-
s.error(`The ingest didn't accept them: ${sent.error}`);
|
|
1130
|
-
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.");
|
|
1131
|
-
} else {
|
|
1132
|
-
s.message("Sent. Waiting for the dashboard to show them");
|
|
1133
|
-
const after = await waitForArrival(cwd, dashboardUrl, cfg.appId);
|
|
1134
|
-
if (after?.ok && after.data?.issues?.length) {
|
|
1135
|
-
s.stop("They arrived");
|
|
1136
|
-
const d = after.data;
|
|
1137
|
-
p.note(
|
|
1138
|
-
[
|
|
1139
|
-
...(d.narrative ?? []).map((l) => `\u201C${l}\u201D`),
|
|
1140
|
-
"",
|
|
1141
|
-
`${bold(String(d.issues.length))} issues \xB7 ${bold(String(d.health?.sessions14d ?? 0))} session \xB7 failing endpoint ${code(d.health?.endpoints?.[0]?.endpoint ?? "\u2014")}`,
|
|
1142
|
-
"",
|
|
1143
|
-
`Refresh the dashboard. You'll see a ${pc.red("HttpError")} from a failed request (captured the way the SDK does it automatically),`,
|
|
1144
|
-
`a ${pc.red("SyntaxError")} reported from a try/catch, and the ${code("onboarding.test")} flow with a 50% failure rate from track().`,
|
|
1145
|
-
dim("They're tagged environment debugkit-test, version " + (app.version ?? "0.0.0") + ". Raw events expire after 30 days.")
|
|
1146
|
-
].join("\n"),
|
|
1147
|
-
"3 \xB7 Your first events"
|
|
1148
|
-
);
|
|
1149
|
-
} else {
|
|
1150
|
-
s.error("Sent, but the dashboard doesn't show them yet");
|
|
1151
|
-
p.log.warn(`The dashboard said: ${after?.status ?? "?"} ${after?.error ?? ""}. Refresh it in a minute, or run npx debugkit test again.`);
|
|
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;
|
|
1152
1774
|
}
|
|
1775
|
+
this.crumbs.push({ ts: now(), category, message: msg, data, level });
|
|
1776
|
+
if (this.crumbs.length > (this.opts?.maxBreadcrumbs ?? 30)) this.crumbs.shift();
|
|
1153
1777
|
}
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
)
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
""
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
`${code(cmdFor("guide"))} replay this walkthrough`
|
|
1178
|
-
].join("\n"),
|
|
1179
|
-
"6 \xB7 Finish wiring your app"
|
|
1180
|
-
);
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
// src/providers/aws.ts
|
|
1184
|
-
init_exec();
|
|
1185
|
-
import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
|
|
1186
|
-
import { homedir } from "os";
|
|
1187
|
-
import { dirname, join as join4 } from "path";
|
|
1188
|
-
import { fileURLToPath } from "url";
|
|
1189
|
-
import { zipSync } from "fflate";
|
|
1190
|
-
|
|
1191
|
-
// src/keys.ts
|
|
1192
|
-
var keyEntry = (key, appId) => `${key}:${appId}`;
|
|
1193
|
-
function mergeKeys(existing, key, appId) {
|
|
1194
|
-
const pairs = (existing ?? "").split(",").map((s) => s.trim()).filter((s) => /^[^:\s]+:[^:\s]+$/.test(s));
|
|
1195
|
-
if (!pairs.some((p2) => p2.split(":")[0] === key)) pairs.push(keyEntry(key, appId));
|
|
1196
|
-
return pairs.join(",");
|
|
1197
|
-
}
|
|
1198
|
-
|
|
1199
|
-
// src/providers/aws.ts
|
|
1200
|
-
var REGIONS = [
|
|
1201
|
-
{ value: "af-south-1", label: "Cape Town (af-south-1)" },
|
|
1202
|
-
{ value: "eu-west-1", label: "Ireland (eu-west-1)" },
|
|
1203
|
-
{ value: "eu-central-1", label: "Frankfurt (eu-central-1)" },
|
|
1204
|
-
{ value: "us-east-1", label: "N. Virginia (us-east-1)" },
|
|
1205
|
-
{ value: "us-west-2", label: "Oregon (us-west-2)" },
|
|
1206
|
-
{ value: "ap-southeast-1", label: "Singapore (ap-southeast-1)" }
|
|
1207
|
-
];
|
|
1208
|
-
function awsProfiles(home = homedir()) {
|
|
1209
|
-
const out = /* @__PURE__ */ new Map();
|
|
1210
|
-
const read = (file, isConfig) => {
|
|
1211
|
-
if (!existsSync4(file)) return;
|
|
1212
|
-
let cur;
|
|
1213
|
-
for (const line of readFileSync3(file, "utf8").split(/\r?\n/)) {
|
|
1214
|
-
const h = /^\s*\[\s*(?:profile\s+)?([^\]\s]+)\s*\]/.exec(line);
|
|
1215
|
-
if (h) {
|
|
1216
|
-
if (isConfig && h[1] && /^sso-session\b/.test(line.replace(/^\s*\[\s*/, ""))) {
|
|
1217
|
-
cur = void 0;
|
|
1218
|
-
continue;
|
|
1219
|
-
}
|
|
1220
|
-
cur = out.get(h[1]) ?? { name: h[1], sso: false };
|
|
1221
|
-
out.set(cur.name, cur);
|
|
1222
|
-
continue;
|
|
1223
|
-
}
|
|
1224
|
-
const kv = /^\s*([a-z_]+)\s*=\s*(.+?)\s*$/.exec(line);
|
|
1225
|
-
if (!cur || !kv) continue;
|
|
1226
|
-
if (kv[1] === "region") cur.region = kv[2];
|
|
1227
|
-
if (kv[1].startsWith("sso_")) cur.sso = true;
|
|
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;
|
|
1228
1801
|
}
|
|
1229
|
-
};
|
|
1230
|
-
read(process.env.AWS_CONFIG_FILE ?? join4(home, ".aws", "config"), true);
|
|
1231
|
-
read(process.env.AWS_SHARED_CREDENTIALS_FILE ?? join4(home, ".aws", "credentials"), false);
|
|
1232
|
-
return [...out.values()];
|
|
1233
|
-
}
|
|
1234
|
-
function lambdaZip() {
|
|
1235
|
-
const here = dirname(fileURLToPath(import.meta.url));
|
|
1236
|
-
const file = [join4(here, "lambda", "index.mjs"), join4(here, "..", "dist", "lambda", "index.mjs")].find(existsSync4);
|
|
1237
|
-
if (!file) throw new Error("The bundled ingest Lambda is missing. Reinstall debugkit.");
|
|
1238
|
-
return zipSync({ "index.mjs": readFileSync3(file) }, { level: 9 });
|
|
1239
|
-
}
|
|
1240
|
-
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1241
|
-
async function setupAws(ctx) {
|
|
1242
|
-
p.note(
|
|
1243
|
-
[
|
|
1244
|
-
"deBug creates a DynamoDB table, a Lambda function with a public URL, and an IAM role in your own AWS account.",
|
|
1245
|
-
"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.",
|
|
1246
|
-
"Your credentials stay on this machine. deBug doesn't receive them."
|
|
1247
|
-
].join("\n"),
|
|
1248
|
-
"Sign in to AWS"
|
|
1249
|
-
);
|
|
1250
|
-
const profiles = awsProfiles();
|
|
1251
|
-
const SSO = "__sso__";
|
|
1252
|
-
const ENV = "__env__";
|
|
1253
|
-
const options = [
|
|
1254
|
-
...profiles.map((x) => ({ value: x.name, label: x.name, hint: [x.sso ? "SSO" : "keys", x.region].filter(Boolean).join(" \xB7 ") })),
|
|
1255
|
-
...process.env.AWS_ACCESS_KEY_ID ? [{ value: ENV, label: "Credentials from the environment (AWS_ACCESS_KEY_ID)" }] : [],
|
|
1256
|
-
{ value: SSO, label: "Sign in with AWS SSO (IAM Identity Center)", hint: which("aws") ? "opens your browser" : "needs the AWS CLI" }
|
|
1257
|
-
];
|
|
1258
|
-
let profile = await choose("Which AWS credentials should deBug use?", options, profiles[0]?.name ?? SSO);
|
|
1259
|
-
if (profile === SSO) {
|
|
1260
|
-
if (!which("aws")) bail("AWS SSO sign-in needs the AWS CLI: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html");
|
|
1261
|
-
const name = await ask("Name for the new AWS profile", { initial: "debugkit" });
|
|
1262
|
-
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.`);
|
|
1263
|
-
if (await interactive("aws", ["configure", "sso", "--profile", name]) !== 0) bail("AWS SSO setup didn't finish.");
|
|
1264
|
-
profile = name;
|
|
1265
|
-
} else if (profile === ENV) profile = void 0;
|
|
1266
|
-
const { fromNodeProviderChain } = await import("@aws-sdk/credential-providers");
|
|
1267
|
-
const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
|
|
1268
|
-
const defaultRegion = profiles.find((x) => x.name === profile)?.region ?? process.env.AWS_REGION ?? "af-south-1";
|
|
1269
|
-
const region = await choose("Which AWS region?", REGIONS.some((r) => r.value === defaultRegion) ? REGIONS : [{ value: defaultRegion, label: defaultRegion }, ...REGIONS], defaultRegion);
|
|
1270
|
-
const credentials = fromNodeProviderChain(profile ? { profile } : {});
|
|
1271
|
-
const base = { region, credentials };
|
|
1272
|
-
let identity;
|
|
1273
|
-
try {
|
|
1274
|
-
identity = await new STSClient(base).send(new GetCallerIdentityCommand({}));
|
|
1275
|
-
} catch (err) {
|
|
1276
|
-
const sso = profiles.find((x) => x.name === profile)?.sso;
|
|
1277
|
-
if (sso && which("aws")) {
|
|
1278
|
-
p.log.info("Your SSO session has expired. Signing in again.");
|
|
1279
|
-
if (await interactive("aws", ["sso", "login", "--profile", profile]) !== 0) bail("AWS SSO sign-in didn't finish.");
|
|
1280
|
-
identity = await new STSClient({ region, credentials: fromNodeProviderChain({ profile }) }).send(new GetCallerIdentityCommand({}));
|
|
1281
|
-
} else bail(`Those AWS credentials didn't work: ${err.message}`);
|
|
1282
1802
|
}
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
const [ddbMod, iamMod, lambdaMod] = await Promise.all([import("@aws-sdk/client-dynamodb"), import("@aws-sdk/client-iam"), import("@aws-sdk/client-lambda")]);
|
|
1295
|
-
const ddb = new ddbMod.DynamoDBClient(base);
|
|
1296
|
-
s.start(`Checking DynamoDB table ${table}`);
|
|
1297
|
-
let tableArn;
|
|
1298
|
-
let ownTable = false;
|
|
1299
|
-
const found = await lookup(() => ddb.send(new ddbMod.DescribeTableCommand({ TableName: table })));
|
|
1300
|
-
if (found) {
|
|
1301
|
-
tableArn = found.Table?.TableArn;
|
|
1302
|
-
const tags = await ddb.send(new ddbMod.ListTagsOfResourceCommand({ ResourceArn: tableArn }));
|
|
1303
|
-
ownTable = !!tags.Tags?.some((t) => t.Key === CREATED_BY && t.Value === "debugkit");
|
|
1304
|
-
const keys = Object.fromEntries((found.Table?.KeySchema ?? []).map((k) => [k.KeyType, k.AttributeName]));
|
|
1305
|
-
const types = Object.fromEntries((found.Table?.AttributeDefinitions ?? []).map((a) => [a.AttributeName, a.AttributeType]));
|
|
1306
|
-
if (keys.HASH !== "pk" || keys.RANGE !== "sk" || types.pk !== "S" || types.sk !== "S") {
|
|
1307
|
-
s.error(`Table ${table} exists with a different key schema`);
|
|
1308
|
-
bail(`${table} isn't a deBug table (it needs string keys pk and sk). Run again and choose another table name.`);
|
|
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) });
|
|
1309
1814
|
}
|
|
1310
|
-
|
|
1311
|
-
if (
|
|
1312
|
-
|
|
1313
|
-
}
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
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
|
+
}
|
|
1336
1870
|
}
|
|
1337
|
-
|
|
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;
|
|
1338
1898
|
}
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
if (ttlOn && ttl?.AttributeName !== "ttl") {
|
|
1343
|
-
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.`);
|
|
1344
|
-
} else if (!ttlOn) {
|
|
1345
|
-
await ddb.send(new ddbMod.UpdateTimeToLiveCommand({ TableName: table, TimeToLiveSpecification: { AttributeName: "ttl", Enabled: true } }));
|
|
1899
|
+
sampled() {
|
|
1900
|
+
const r = this.opts.sampleRate ?? 1;
|
|
1901
|
+
return r >= 1 || Math.random() < r;
|
|
1346
1902
|
}
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
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;
|
|
1357
1961
|
}
|
|
1358
|
-
|
|
1359
|
-
} else {
|
|
1360
|
-
roleArn = (await iam.send(
|
|
1361
|
-
new iamMod.CreateRoleCommand({
|
|
1362
|
-
RoleName: roleName,
|
|
1363
|
-
Description: `deBug ingest Lambda: writes to the DynamoDB table ${table}`.slice(0, 1e3),
|
|
1364
|
-
AssumeRolePolicyDocument: JSON.stringify({
|
|
1365
|
-
Version: "2012-10-17",
|
|
1366
|
-
Statement: [{ Effect: "Allow", Principal: { Service: "lambda.amazonaws.com" }, Action: "sts:AssumeRole", Condition: { StringEquals: { "aws:SourceAccount": account } } }]
|
|
1367
|
-
}),
|
|
1368
|
-
Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
|
|
1369
|
-
})
|
|
1370
|
-
)).Role.Arn;
|
|
1371
|
-
newRole = true;
|
|
1962
|
+
if (!res.ok) throw new Error(`ingest responded ${res.status}`);
|
|
1372
1963
|
}
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
PolicyName: "debugkit-table-write",
|
|
1378
|
-
PolicyDocument: JSON.stringify({
|
|
1379
|
-
Version: "2012-10-17",
|
|
1380
|
-
Statement: [{ Effect: "Allow", Action: ["dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:BatchWriteItem", "dynamodb:GetItem"], Resource: tableArn }]
|
|
1381
|
-
})
|
|
1382
|
-
})
|
|
1383
|
-
);
|
|
1384
|
-
s.stop(`IAM role ${roleName} can write to ${table} and nothing else`);
|
|
1385
|
-
const lambda = new lambdaMod.LambdaClient(base);
|
|
1386
|
-
const zip = lambdaZip();
|
|
1387
|
-
s.start(`Deploying Lambda ${functionName}`);
|
|
1388
|
-
const fn = await lookup(() => lambda.send(new lambdaMod.GetFunctionCommand({ FunctionName: functionName })));
|
|
1389
|
-
if (fn) {
|
|
1390
|
-
if (fn.Tags?.[CREATED_BY] !== "debugkit") {
|
|
1391
|
-
s.error(`Function ${functionName} exists and wasn't created by deBug`);
|
|
1392
|
-
bail(`deBug won't overwrite a function it didn't create. Rename ${functionName}, or choose another table name.`);
|
|
1964
|
+
async persist() {
|
|
1965
|
+
try {
|
|
1966
|
+
await this.opts.storage?.setItem(QUEUE_KEY, JSON.stringify(this.queue));
|
|
1967
|
+
} catch {
|
|
1393
1968
|
}
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
);
|
|
1404
|
-
} else {
|
|
1405
|
-
const env = { Variables: { DEBUG_TABLE: table, DEBUG_INGEST_KEYS: keyEntry(ctx.ingestKey, ctx.app.appId) } };
|
|
1406
|
-
for (let attempt = 0; ; attempt++) {
|
|
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) {
|
|
1407
1978
|
try {
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
Architectures: ["arm64"],
|
|
1413
|
-
Handler: "index.handler",
|
|
1414
|
-
Role: roleArn,
|
|
1415
|
-
Code: { ZipFile: zip },
|
|
1416
|
-
MemorySize: 256,
|
|
1417
|
-
Timeout: 10,
|
|
1418
|
-
Environment: env,
|
|
1419
|
-
Description: "deBug ingest: receives SDK events and writes them to DynamoDB",
|
|
1420
|
-
Tags: { [CREATED_BY]: "debugkit" }
|
|
1421
|
-
})
|
|
1422
|
-
);
|
|
1423
|
-
break;
|
|
1424
|
-
} catch (err) {
|
|
1425
|
-
if (attempt < 10 && /cannot be assumed|role defined for the function/i.test(err.message)) {
|
|
1426
|
-
s.message(newRole ? "Waiting for the new IAM role to be ready" : "Retrying");
|
|
1427
|
-
await sleep(3e3);
|
|
1428
|
-
} else throw err;
|
|
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 {
|
|
1429
1983
|
}
|
|
1984
|
+
return;
|
|
1430
1985
|
}
|
|
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
|
+
})();
|
|
1431
1996
|
}
|
|
1432
|
-
|
|
1433
|
-
const urlCfg = await lookup(() => lambda.send(new lambdaMod.GetFunctionUrlConfigCommand({ FunctionName: functionName })));
|
|
1434
|
-
const url = urlCfg?.FunctionUrl ?? (await lambda.send(new lambdaMod.CreateFunctionUrlConfigCommand({ FunctionName: functionName, AuthType: "NONE" }))).FunctionUrl;
|
|
1435
|
-
if (!url) throw new Error(`AWS didn't return a URL for ${functionName}.`);
|
|
1436
|
-
for (const [sid, input] of [
|
|
1437
|
-
["debugkit-public-url", { Action: "lambda:InvokeFunctionUrl", FunctionUrlAuthType: "NONE" }],
|
|
1438
|
-
["debugkit-public-invoke", { Action: "lambda:InvokeFunction", InvokedViaFunctionUrl: true }]
|
|
1439
|
-
]) {
|
|
1997
|
+
async restore() {
|
|
1440
1998
|
try {
|
|
1441
|
-
await
|
|
1442
|
-
|
|
1443
|
-
|
|
1999
|
+
const raw = await this.opts.storage?.getItem(QUEUE_KEY);
|
|
2000
|
+
if (raw) this.queue.unshift(...JSON.parse(raw));
|
|
2001
|
+
} catch {
|
|
1444
2002
|
}
|
|
1445
2003
|
}
|
|
1446
|
-
|
|
1447
|
-
|
|
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" } }));
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
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));
|
|
2029
|
+
}
|
|
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();
|
|
2049
|
+
}
|
|
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 }
|
|
2079
|
+
);
|
|
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 };
|
|
1448
2088
|
try {
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
PolicyName: `debugkit-dashboard-readonly-${table}`.slice(0, 128),
|
|
1453
|
-
PolicyDocument: JSON.stringify({
|
|
1454
|
-
Version: "2012-10-17",
|
|
1455
|
-
Statement: [{ Effect: "Allow", Action: ["dynamodb:GetItem", "dynamodb:Query", "dynamodb:DescribeTable"], Resource: tableArn }]
|
|
1456
|
-
}),
|
|
1457
|
-
Description: `Read-only access to the deBug table ${table}, for hosting the dashboard`,
|
|
1458
|
-
Tags: [{ Key: CREATED_BY, Value: "debugkit" }]
|
|
1459
|
-
})
|
|
1460
|
-
);
|
|
1461
|
-
} catch (err) {
|
|
1462
|
-
p.log.warn(`Skipped the read-only dashboard policy: ${err.message}`);
|
|
1463
|
-
readOnlyPolicyArn = void 0;
|
|
2089
|
+
return { name: "NonError", message: JSON.stringify(err).slice(0, 2e3) };
|
|
2090
|
+
} catch {
|
|
2091
|
+
return { name: "NonError", message: String(err) };
|
|
1464
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;
|
|
1465
2098
|
return {
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
]
|
|
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")
|
|
1474
2106
|
};
|
|
1475
2107
|
}
|
|
1476
|
-
var
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
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);
|
|
1484
2117
|
}
|
|
2118
|
+
return out;
|
|
1485
2119
|
}
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
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
|
+
];
|
|
1491
2152
|
}
|
|
1492
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)}";
|
|
1493
2158
|
|
|
1494
|
-
//
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
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
|
+
}
|
|
1498
2166
|
|
|
1499
|
-
//
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
{
|
|
1503
|
-
collectionGroup: "rollups",
|
|
1504
|
-
queryScope: "COLLECTION",
|
|
1505
|
-
fields: [
|
|
1506
|
-
{ fieldPath: "dimension", order: "ASCENDING" },
|
|
1507
|
-
{ fieldPath: "day", order: "ASCENDING" }
|
|
1508
|
-
]
|
|
1509
|
-
},
|
|
1510
|
-
{
|
|
1511
|
-
collectionGroup: "events",
|
|
1512
|
-
queryScope: "COLLECTION",
|
|
1513
|
-
fields: [
|
|
1514
|
-
{ fieldPath: "fingerprint", order: "ASCENDING" },
|
|
1515
|
-
{ fieldPath: "ts", order: "DESCENDING" }
|
|
1516
|
-
]
|
|
1517
|
-
}
|
|
1518
|
-
],
|
|
1519
|
-
fieldOverrides: [
|
|
1520
|
-
{
|
|
1521
|
-
collectionGroup: "events",
|
|
1522
|
-
fieldPath: "expireAt",
|
|
1523
|
-
ttl: true,
|
|
1524
|
-
indexes: []
|
|
1525
|
-
}
|
|
1526
|
-
]
|
|
1527
|
-
};
|
|
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));
|
|
1528
2170
|
|
|
1529
|
-
//
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
}
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
if (!accounts.length) {
|
|
1566
|
-
await next("Open the Google sign-in page");
|
|
1567
|
-
if (await fbLive(["login"]) !== 0) bail("Firebase sign-in didn't finish. Run npx debugkit init to try again.");
|
|
1568
|
-
accounts = emailsIn((await fb(["login:list"])).stdout);
|
|
1569
|
-
}
|
|
1570
|
-
const ADD = "__add__";
|
|
1571
|
-
const picked = await choose(
|
|
1572
|
-
"Which Google account should own the deBug resources?",
|
|
1573
|
-
[...accounts.map((a) => ({ value: a, label: a })), { value: ADD, label: "Sign in with another account" }],
|
|
1574
|
-
accounts[0]
|
|
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;
|
|
2188
|
+
try {
|
|
2189
|
+
res = await fetch(url, init2);
|
|
2190
|
+
} catch (err) {
|
|
2191
|
+
failures.push(`couldn't reach it (${err.message})`);
|
|
2192
|
+
throw err;
|
|
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;
|
|
2197
|
+
}
|
|
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 }
|
|
1575
2207
|
);
|
|
1576
|
-
if (picked === ADD) {
|
|
1577
|
-
if (await fbLive(["login:add"]) !== 0) bail("Firebase sign-in didn't finish.");
|
|
1578
|
-
const now2 = emailsIn((await fb(["login:list"])).stdout);
|
|
1579
|
-
account = now2.find((a) => !accounts.includes(a)) ?? now2[0] ?? bail("No Firebase account is signed in.");
|
|
1580
|
-
} else account = picked;
|
|
1581
|
-
const acct = ["--account", account];
|
|
1582
|
-
const s = p.spinner();
|
|
1583
|
-
s.start("Loading your Firebase projects");
|
|
1584
|
-
const list = await fb(["projects:list", "--json", ...acct]);
|
|
1585
|
-
s.stop("Loaded your Firebase projects");
|
|
1586
|
-
let projects = [];
|
|
1587
2208
|
try {
|
|
1588
|
-
|
|
1589
|
-
} catch {
|
|
1590
|
-
|
|
2209
|
+
JSON.parse("<html>502 Bad Gateway</html>");
|
|
2210
|
+
} catch (err) {
|
|
2211
|
+
client.error(err, { flow: "onboarding.test", step: "parse_receipt", tags: { test: "true" } });
|
|
1591
2212
|
}
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
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 };
|
|
2220
|
+
}
|
|
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));
|
|
2228
|
+
}
|
|
2229
|
+
return last;
|
|
2230
|
+
}
|
|
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;
|
|
2235
|
+
p.note(
|
|
1595
2236
|
[
|
|
1596
|
-
{
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
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"
|
|
1600
2243
|
);
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
projectId = await ask("Project id (lowercase, globally unique)", {
|
|
1604
|
-
initial: suggested,
|
|
1605
|
-
validate: (v) => /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/.test(v) ? void 0 : "6\u201330 characters: lowercase letters, digits and dashes"
|
|
1606
|
-
});
|
|
1607
|
-
if (await fbLive(["projects:create", projectId, "--display-name", `${ctx.app.name} deBug`.slice(0, 30), ...acct]) !== 0)
|
|
1608
|
-
bail(`Couldn't create ${projectId}. Pick an existing project or another id.`);
|
|
1609
|
-
}
|
|
1610
|
-
const proj = ["--project", projectId, ...acct];
|
|
2244
|
+
openUrl(dashboardUrl);
|
|
2245
|
+
await next("I'm signed in");
|
|
1611
2246
|
p.note(
|
|
1612
2247
|
[
|
|
1613
|
-
"
|
|
1614
|
-
"
|
|
1615
|
-
|
|
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`
|
|
1616
2254
|
].join("\n"),
|
|
1617
|
-
"
|
|
2255
|
+
"2 \xB7 What you'll see there"
|
|
1618
2256
|
);
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
location2 = existingDb.locationId;
|
|
1627
|
-
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.");
|
|
1628
2264
|
} else {
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
p.
|
|
1635
|
-
|
|
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.`);
|
|
1636
2285
|
}
|
|
1637
|
-
s.stop(`Created the Firestore database (${location2})`);
|
|
1638
|
-
}
|
|
1639
|
-
const region = functionRegion(location2);
|
|
1640
|
-
const dir = writeFunctionSource(ctx, region);
|
|
1641
|
-
s.start("Installing the ingest function's dependencies");
|
|
1642
|
-
const inst = await capture("npm", ["install", "--no-audit", "--no-fund"], { cwd: join5(dir, "functions") });
|
|
1643
|
-
if (inst.code !== 0) {
|
|
1644
|
-
s.error("npm install failed");
|
|
1645
|
-
p.log.error(inst.stderr.slice(-600));
|
|
1646
|
-
bail();
|
|
1647
2286
|
}
|
|
1648
|
-
|
|
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?");
|
|
1649
2293
|
p.note(
|
|
1650
2294
|
[
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
`\u2022 a ${code("debug_apps")} collection in Firestore, with raw events expiring after 30 days`,
|
|
1654
|
-
`\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.`,
|
|
1655
2297
|
"",
|
|
1656
|
-
|
|
2298
|
+
MANUAL(app.platform)
|
|
1657
2299
|
].join("\n"),
|
|
1658
|
-
"
|
|
1659
|
-
);
|
|
1660
|
-
if (!await yes(`Deploy deBug into ${projectId}?`)) bail("Nothing was deployed.");
|
|
1661
|
-
p.log.step("Adding deBug's Firestore indexes (your existing indexes are left alone)");
|
|
1662
|
-
if (await fbLive(["deploy", "--only", "firestore:indexes", "--non-interactive", ...proj], { cwd: dir }) !== 0)
|
|
1663
|
-
p.log.warn("The indexes didn't deploy. The dashboard needs them; deploy them later with the command printed at the end.");
|
|
1664
|
-
p.log.step(`Deploying ${code(FUNCTION_NAME)}. The first deploy turns on the Google APIs it needs and takes a few minutes.`);
|
|
1665
|
-
for (; ; ) {
|
|
1666
|
-
const exit = await fbLive(["deploy", "--only", `functions:${CODEBASE}`, "--force", ...proj], { cwd: dir });
|
|
1667
|
-
if (exit === 0) break;
|
|
1668
|
-
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.");
|
|
1669
|
-
const again = await choose(
|
|
1670
|
-
"What now?",
|
|
1671
|
-
[
|
|
1672
|
-
{ value: "retry", label: "Retry the deploy" },
|
|
1673
|
-
{ value: "billing", label: "Open billing, then retry" },
|
|
1674
|
-
{ value: "stop", label: "Stop here" }
|
|
1675
|
-
],
|
|
1676
|
-
"retry"
|
|
1677
|
-
);
|
|
1678
|
-
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}`);
|
|
1679
|
-
if (again === "billing") {
|
|
1680
|
-
openUrl(`https://console.firebase.google.com/project/${projectId}/usage/details`);
|
|
1681
|
-
await next("Upgraded: retry the deploy");
|
|
1682
|
-
}
|
|
1683
|
-
}
|
|
1684
|
-
const endpoint = `https://${region}-${projectId}.cloudfunctions.net/${FUNCTION_NAME}`;
|
|
1685
|
-
await ensureDashboardAccess(projectId);
|
|
1686
|
-
return {
|
|
1687
|
-
config: { provider: "firebase", endpoint, ingestKey: ctx.ingestKey, firebase: { projectId, region, account, location: location2 } },
|
|
1688
|
-
dashboardEnv: { DEBUG_STORE: "firestore", GOOGLE_CLOUD_PROJECT: projectId, GCLOUD_PROJECT: projectId },
|
|
1689
|
-
created: [
|
|
1690
|
-
`Firestore database in ${code(projectId)} (${location2}), with indexes and 30-day expiry on raw events`,
|
|
1691
|
-
`Cloud Function ${code(FUNCTION_NAME)} in ${region}: ${code(endpoint)}`,
|
|
1692
|
-
`Function source in ${code(".debugkit/firebase")}, so you can redeploy it with the Firebase CLI`
|
|
1693
|
-
]
|
|
1694
|
-
};
|
|
1695
|
-
}
|
|
1696
|
-
async function ensureDashboardAccess(projectId) {
|
|
1697
|
-
if (!which("gcloud")) {
|
|
1698
|
-
p.log.warn(
|
|
1699
|
-
[
|
|
1700
|
-
"The dashboard reads Firestore with Google Cloud credentials, and gcloud isn't installed.",
|
|
1701
|
-
`Install it (${code("https://cloud.google.com/sdk/docs/install")}), then run ${code("gcloud auth application-default login")}.`,
|
|
1702
|
-
"Or create a read-only service account (role: Cloud Datastore Viewer) and set GOOGLE_APPLICATION_CREDENTIALS in .debugkit/dashboard.env."
|
|
1703
|
-
].join("\n")
|
|
1704
|
-
);
|
|
1705
|
-
return;
|
|
1706
|
-
}
|
|
1707
|
-
const t = await capture("gcloud", ["auth", "application-default", "print-access-token"]);
|
|
1708
|
-
if (t.code === 0) {
|
|
1709
|
-
p.log.success("The dashboard will read Firestore with your Google Cloud credentials");
|
|
1710
|
-
return;
|
|
1711
|
-
}
|
|
1712
|
-
p.note("One more Google sign-in: this one lets the dashboard on this machine read deBug's data.", "Dashboard access");
|
|
1713
|
-
await next("Open the Google sign-in page");
|
|
1714
|
-
const exit = await interactive("gcloud", ["auth", "application-default", "login", "--quiet"]);
|
|
1715
|
-
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");
|
|
1716
|
-
else await capture("gcloud", ["auth", "application-default", "set-quota-project", projectId]);
|
|
1717
|
-
}
|
|
1718
|
-
async function defaultDatabase(fb, proj) {
|
|
1719
|
-
const r = await fb(["firestore:databases:get", "(default)", "--json", ...proj]);
|
|
1720
|
-
if (r.code !== 0) return void 0;
|
|
1721
|
-
try {
|
|
1722
|
-
const db = JSON.parse(r.stdout).result;
|
|
1723
|
-
return db?.locationId ? { locationId: db.locationId } : void 0;
|
|
1724
|
-
} catch {
|
|
1725
|
-
return void 0;
|
|
1726
|
-
}
|
|
1727
|
-
}
|
|
1728
|
-
function functionRegion(location2) {
|
|
1729
|
-
const known = LOCATIONS.find((l) => l.value === location2)?.region;
|
|
1730
|
-
if (known) return known;
|
|
1731
|
-
if (location2 === "nam7") return "us-central1";
|
|
1732
|
-
if (location2.startsWith("eur")) return "europe-west1";
|
|
1733
|
-
if (location2.startsWith("nam")) return "us-central1";
|
|
1734
|
-
return /^[a-z]+-[a-z]+\d+$/.test(location2) ? location2 : "us-central1";
|
|
1735
|
-
}
|
|
1736
|
-
function writeFunctionSource(ctx, region) {
|
|
1737
|
-
const dir = paths(ctx.app.cwd).firebase;
|
|
1738
|
-
mkdirSync2(join5(dir, "functions"), { recursive: true });
|
|
1739
|
-
writeFileSync2(
|
|
1740
|
-
join5(dir, "firebase.json"),
|
|
1741
|
-
JSON.stringify(
|
|
1742
|
-
{
|
|
1743
|
-
functions: [{ source: "functions", codebase: CODEBASE, runtime: "nodejs22" }],
|
|
1744
|
-
firestore: { database: "(default)", indexes: "firestore.indexes.json" }
|
|
1745
|
-
},
|
|
1746
|
-
null,
|
|
1747
|
-
2
|
|
1748
|
-
) + "\n"
|
|
1749
|
-
);
|
|
1750
|
-
writeFileSync2(join5(dir, "firestore.indexes.json"), JSON.stringify(firestore_indexes_default, null, 2) + "\n");
|
|
1751
|
-
writeFileSync2(
|
|
1752
|
-
join5(dir, "functions", "package.json"),
|
|
1753
|
-
JSON.stringify(
|
|
1754
|
-
{
|
|
1755
|
-
name: "debugkit-ingest",
|
|
1756
|
-
private: true,
|
|
1757
|
-
type: "module",
|
|
1758
|
-
main: "index.js",
|
|
1759
|
-
engines: { node: "22" },
|
|
1760
|
-
dependencies: {
|
|
1761
|
-
// Same release as this CLI (the packages are versioned together).
|
|
1762
|
-
"@debugkit/adapters": `^${VERSION}`,
|
|
1763
|
-
"@debugkit/ingest": `^${VERSION}`,
|
|
1764
|
-
"firebase-admin": "^13.0.0",
|
|
1765
|
-
"firebase-functions": "^7.0.0"
|
|
1766
|
-
}
|
|
1767
|
-
},
|
|
1768
|
-
null,
|
|
1769
|
-
2
|
|
1770
|
-
) + "\n"
|
|
2300
|
+
"5 \xB7 What you add in your own try/catches"
|
|
1771
2301
|
);
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
export const ${FUNCTION_NAME} = onRequest(
|
|
1785
|
-
{ region: ${JSON.stringify(region)}, invoker: "public", memory: "256MiB", maxInstances: 10 },
|
|
1786
|
-
firebaseHandler({ store: new FirestoreStore(getFirestore()), keys: parseIngestKeys(process.env.DEBUG_INGEST_KEYS) }),
|
|
1787
|
-
);
|
|
1788
|
-
`
|
|
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"
|
|
1789
2313
|
);
|
|
1790
|
-
const envFile = join5(dir, "functions", ".env");
|
|
1791
|
-
const current2 = existsSync5(envFile) ? /^DEBUG_INGEST_KEYS=(.*)$/m.exec(readFileSync4(envFile, "utf8"))?.[1] : void 0;
|
|
1792
|
-
writeFileSync2(envFile, `DEBUG_INGEST_KEYS=${mergeKeys(current2, ctx.ingestKey, ctx.app.appId)}
|
|
1793
|
-
`);
|
|
1794
|
-
return dir;
|
|
1795
2314
|
}
|
|
1796
2315
|
|
|
1797
2316
|
// src/providers/local.ts
|
|
@@ -1822,8 +2341,8 @@ async function setupLocal(ctx) {
|
|
|
1822
2341
|
}
|
|
1823
2342
|
|
|
1824
2343
|
// src/wire.ts
|
|
1825
|
-
import { existsSync as
|
|
1826
|
-
import { dirname as dirname2, join as
|
|
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";
|
|
1827
2346
|
init_exec();
|
|
1828
2347
|
var ENV_ENDPOINT = "DEBUG_ENDPOINT";
|
|
1829
2348
|
var ENV_KEY = "DEBUG_KEY";
|
|
@@ -1850,7 +2369,7 @@ async function installSdk(app) {
|
|
|
1850
2369
|
}
|
|
1851
2370
|
function writeAppEnv(app, conn) {
|
|
1852
2371
|
if (!app.envPrefix) return void 0;
|
|
1853
|
-
const file =
|
|
2372
|
+
const file = join7(app.cwd, ".env");
|
|
1854
2373
|
upsertEnv(file, { [`${app.envPrefix}${ENV_ENDPOINT}`]: conn.endpoint, [`${app.envPrefix}${ENV_KEY}`]: conn.ingestKey });
|
|
1855
2374
|
return file;
|
|
1856
2375
|
}
|
|
@@ -1862,8 +2381,8 @@ function envValues(app, conn, env) {
|
|
|
1862
2381
|
}
|
|
1863
2382
|
function initFile(app, conn, multiEnv = environment.get() !== void 0) {
|
|
1864
2383
|
const ext = app.typescript ? "ts" : "js";
|
|
1865
|
-
const path2 =
|
|
1866
|
-
const rel =
|
|
2384
|
+
const path2 = join7(app.cwd, app.sourceDir, `debug.${ext}`);
|
|
2385
|
+
const rel = relative2(app.cwd, path2);
|
|
1867
2386
|
const env = (k) => app.envPrefix === "VITE_" ? `import.meta.env.${app.envPrefix}${k}` : `process.env.${app.envPrefix ?? ""}${k}`;
|
|
1868
2387
|
const header = `// Set up by npx debugkit init. Import this file once, as early as possible.
|
|
1869
2388
|
`;
|
|
@@ -1974,7 +2493,7 @@ async function wireApp(app, conn) {
|
|
|
1974
2493
|
const extra = [];
|
|
1975
2494
|
if (env) {
|
|
1976
2495
|
const values = app.platform === "react-native" ? {} : envValues(app, conn, env);
|
|
1977
|
-
const usesEas = app.platform === "expo" &&
|
|
2496
|
+
const usesEas = app.platform === "expo" && existsSync7(join7(app.cwd, "eas.json"));
|
|
1978
2497
|
let done = Object.keys(values).length === 0;
|
|
1979
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);
|
|
1980
2499
|
if (!done) {
|
|
@@ -1984,9 +2503,9 @@ async function wireApp(app, conn) {
|
|
|
1984
2503
|
} else {
|
|
1985
2504
|
const envFile = writeAppEnv(app, conn);
|
|
1986
2505
|
if (envFile) {
|
|
1987
|
-
p.log.success(`Wrote ${code(`${app.envPrefix}${ENV_ENDPOINT}`)} and ${code(`${app.envPrefix}${ENV_KEY}`)} to ${code(
|
|
2506
|
+
p.log.success(`Wrote ${code(`${app.envPrefix}${ENV_ENDPOINT}`)} and ${code(`${app.envPrefix}${ENV_KEY}`)} to ${code(relative2(app.cwd, envFile))}`);
|
|
1988
2507
|
} else if (app.platform === "node") {
|
|
1989
|
-
upsertEnv(
|
|
2508
|
+
upsertEnv(join7(app.cwd, ".env"), { [ENV_ENDPOINT]: conn.endpoint, [ENV_KEY]: conn.ingestKey });
|
|
1990
2509
|
p.log.success(`Wrote ${code(ENV_ENDPOINT)} and ${code(ENV_KEY)} to ${code(".env")}`);
|
|
1991
2510
|
}
|
|
1992
2511
|
if (envFile || app.platform === "node") {
|
|
@@ -1994,12 +2513,12 @@ async function wireApp(app, conn) {
|
|
|
1994
2513
|
}
|
|
1995
2514
|
}
|
|
1996
2515
|
const f = initFile(app, conn);
|
|
1997
|
-
const rel =
|
|
1998
|
-
const current2 =
|
|
2516
|
+
const rel = relative2(app.cwd, f.path);
|
|
2517
|
+
const current2 = existsSync7(f.path) ? readFileSync6(f.path, "utf8") : void 0;
|
|
1999
2518
|
if (current2 === f.contents) p.log.info(`${code(rel)} is already up to date`);
|
|
2000
2519
|
else if (current2 === void 0 || await yes(`${rel} already exists. Replace it?`, false)) {
|
|
2001
|
-
|
|
2002
|
-
|
|
2520
|
+
mkdirSync4(dirname2(f.path), { recursive: true });
|
|
2521
|
+
writeFileSync4(f.path, f.contents);
|
|
2003
2522
|
p.log.success(`${current2 === void 0 ? "Created" : "Updated"} ${code(rel)}`);
|
|
2004
2523
|
} else {
|
|
2005
2524
|
p.log.info(`Kept your ${rel}. The generated version is:
|
|
@@ -2013,7 +2532,8 @@ var HELP = `${bold("debugkit")} ${VERSION}: set up deBug in your app
|
|
|
2013
2532
|
${dim("Run as npx debugkit <command> once @debugkit/sdk is installed, or npx @debugkit/cli <command> anywhere.")}
|
|
2014
2533
|
|
|
2015
2534
|
${code("npx debugkit init")} choose a cloud, deploy ingest to your account, wire the SDK, walk through the dashboard
|
|
2016
|
-
${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
|
|
2017
2537
|
${code("npx debugkit test")} send test events and check they arrive
|
|
2018
2538
|
${code("npx debugkit guide")} replay the walkthrough
|
|
2019
2539
|
${code("npx debugkit password")} reset the dashboard login
|
|
@@ -2041,6 +2561,29 @@ function parseArgs(argv) {
|
|
|
2041
2561
|
return out;
|
|
2042
2562
|
}
|
|
2043
2563
|
var envLabel = () => environment.get() ? ` (${environment.get()})` : "";
|
|
2564
|
+
async function askRetention(current2, provider) {
|
|
2565
|
+
const perGb = provider === "aws" ? 0.25 : 0.18;
|
|
2566
|
+
const cost = (d) => {
|
|
2567
|
+
const gb = 1e4 * d * 2 / 1e6;
|
|
2568
|
+
return `${gb < 1 ? gb.toFixed(1) : Math.round(gb)} GB \u2248 $${(gb * perGb).toFixed(2)}/month at 10k events a day`;
|
|
2569
|
+
};
|
|
2570
|
+
p.note(
|
|
2571
|
+
[
|
|
2572
|
+
"Raw events carry the stack trace, breadcrumbs and device details. They expire after the period you pick.",
|
|
2573
|
+
`${bold("Counts, issues and release health are kept forever")}, so charts cover any date range.`,
|
|
2574
|
+
"You can change this later on the dashboard's Settings page."
|
|
2575
|
+
].join("\n"),
|
|
2576
|
+
"Data retention"
|
|
2577
|
+
);
|
|
2578
|
+
const options = [30, 60, 90, 180, 365].map((d) => ({ value: String(d), label: `${d} days`, hint: cost(d) }));
|
|
2579
|
+
const picked = await choose("Keep raw events for how long?", [...options, { value: "custom", label: "Another number of days" }], String(current2 ?? 60));
|
|
2580
|
+
if (picked !== "custom") return Number(picked);
|
|
2581
|
+
const days = await ask("Days (1 to 3650)", {
|
|
2582
|
+
initial: String(current2 ?? 60),
|
|
2583
|
+
validate: (v) => /^\d+$/.test(v) && Number(v) >= 1 && Number(v) <= 3650 ? void 0 : "A whole number from 1 to 3650"
|
|
2584
|
+
});
|
|
2585
|
+
return Number(days);
|
|
2586
|
+
}
|
|
2044
2587
|
function requireConfig(cwd) {
|
|
2045
2588
|
let cfg = readConfig(cwd);
|
|
2046
2589
|
if (!cfg && !environment.get()) {
|
|
@@ -2087,7 +2630,9 @@ async function init(cwd, preset) {
|
|
|
2087
2630
|
);
|
|
2088
2631
|
const dashboardPort = await freePort(4400);
|
|
2089
2632
|
const ingestKey = existing?.provider === provider && existing.ingestKey ? existing.ingestKey : `pk_${provider === "local" ? "local" : "live"}_${randomBytes2(12).toString("hex")}`;
|
|
2090
|
-
const
|
|
2633
|
+
const retentionDays = provider === "local" ? 30 : await askRetention(existing?.retentionDays, provider);
|
|
2634
|
+
const adminToken = readEnv(paths(cwd).dashboardEnv).DEBUG_ADMIN_TOKEN ?? `adm_${randomBytes2(24).toString("hex")}`;
|
|
2635
|
+
const ctx = { app, ingestKey, dashboardPort, retentionDays, adminToken };
|
|
2091
2636
|
let result;
|
|
2092
2637
|
try {
|
|
2093
2638
|
result = provider === "firebase" ? await setupFirebase(ctx) : provider === "aws" ? await setupAws(ctx) : await setupLocal(ctx);
|
|
@@ -2095,7 +2640,7 @@ async function init(cwd, preset) {
|
|
|
2095
2640
|
p.log.error(err.message);
|
|
2096
2641
|
bail("Setup stopped. Nothing else was changed in your app. Fix the error above and run npx debugkit init again.");
|
|
2097
2642
|
}
|
|
2098
|
-
const cfg = { ...result.config, appId: app.appId, dashboardPort, 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() };
|
|
2099
2644
|
writeConfig(cwd, cfg);
|
|
2100
2645
|
p.note(result.created.map((l) => `\u2022 ${l}`).join("\n"), "Created");
|
|
2101
2646
|
const remaining = await wireApp(app, cfg);
|
|
@@ -2116,15 +2661,41 @@ async function init(cwd, preset) {
|
|
|
2116
2661
|
return;
|
|
2117
2662
|
}
|
|
2118
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")}`));
|
|
2119
2680
|
const others = listEnvironments(cwd).filter((e) => e !== environment.get());
|
|
2120
2681
|
p.outro(
|
|
2121
|
-
`deBug is set up${envLabel()}.
|
|
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 ? `
|
|
2122
2683
|
Set up the next environment the same way, e.g. ${code("npx debugkit init --env production")}.` : "")
|
|
2123
2684
|
);
|
|
2124
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
|
+
}
|
|
2125
2695
|
async function dashboard(cwd) {
|
|
2126
2696
|
const cfg = requireConfig(cwd);
|
|
2127
2697
|
p.intro(`${pc.bgRed(pc.white(" deBug "))} dashboard${envLabel()}`);
|
|
2698
|
+
if (cfg.hosted) p.log.info(`Also online at ${code(cfg.hosted.url)}`);
|
|
2128
2699
|
const dash = await startDashboard(cwd);
|
|
2129
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`);
|
|
2130
2701
|
const { openUrl: openUrl2 } = await Promise.resolve().then(() => (init_exec(), exec_exports));
|
|
@@ -2162,9 +2733,10 @@ async function guide(cwd) {
|
|
|
2162
2733
|
}
|
|
2163
2734
|
}
|
|
2164
2735
|
async function password(cwd) {
|
|
2165
|
-
requireConfig(cwd);
|
|
2166
2736
|
p.intro(`${pc.bgRed(pc.white(" deBug "))} reset the dashboard login`);
|
|
2737
|
+
const cfg = requireConfig(cwd);
|
|
2167
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"))}.`);
|
|
2168
2740
|
p.outro(`Saved. Restart the dashboard (${code(cmdFor("dashboard"))}) and sign in with the new password.`);
|
|
2169
2741
|
}
|
|
2170
2742
|
async function main() {
|
|
@@ -2186,6 +2758,8 @@ async function main() {
|
|
|
2186
2758
|
return init(args.cwd, args.provider);
|
|
2187
2759
|
case "dashboard":
|
|
2188
2760
|
return dashboard(args.cwd);
|
|
2761
|
+
case "deploy-dashboard":
|
|
2762
|
+
return deployDashboard(args.cwd);
|
|
2189
2763
|
case "test":
|
|
2190
2764
|
return test(args.cwd);
|
|
2191
2765
|
case "guide":
|