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