@debugkit/dashboard 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/_authed-DTn7rMla.js +1 -0
- package/dist/client/assets/_authed-Dc7covsB.js +7 -0
- package/dist/client/assets/{charts-C76vsG2N.js → charts-C0zeGTzu.js} +18 -18
- package/dist/client/assets/index-D12jr1bm.js +10 -0
- package/dist/client/assets/issues._fingerprint-C6ryZvIu.js +1 -0
- package/dist/client/assets/login-oLP1Yyz3.js +1 -0
- package/dist/client/assets/preload-helper-CDziuvpw.js +3 -0
- package/dist/client/assets/settings-9oQsCwdV.js +1 -0
- package/dist/client/assets/styles-DBg7wMRg.css +2 -0
- package/dist/client/assets/ui-BiRMJGWB.js +1 -0
- package/dist/server/assets/{_authed-ClbGOSDJ.js → _authed-CuDay0Tl.js} +296 -70
- package/dist/server/assets/{_authed-BaehIntL.js → _authed-DODQ_Iys.js} +28 -8
- package/dist/server/assets/{_tanstack-start-manifest_v-eNUCOzFz.js → _tanstack-start-manifest_v-BBxgjm04.js} +16 -7
- package/dist/server/assets/{charts-CNlV7Pga.js → charts-DzTVqJ8z.js} +21 -4
- package/dist/server/assets/{demo-DTdlXNgj.js → demo-hrRBo9_U.js} +87 -10
- package/dist/server/assets/dynamodb-DyPK9SVV.js +354 -0
- package/dist/server/assets/{firestore-BH-gx9no.js → firestore-B2xzpzYA.js} +89 -5
- package/dist/server/assets/fns-DPsnK0zS.js +79 -0
- package/dist/server/assets/fns-hk_OJe6M.js +250 -0
- package/dist/server/assets/{issues._fingerprint-D78dy5os.js → issues._fingerprint-CZCZDm7t.js} +159 -17
- package/dist/server/assets/{login-h3B5Vdhl.js → login-D-UG6SFw.js} +3 -3
- package/dist/server/assets/{queries-DIVV-5j6.js → memory-Do0CDoAX.js} +205 -505
- package/dist/server/assets/queries-CxHrgTdM.js +955 -0
- package/dist/server/assets/range-picker-0zbSGr3Z.js +106 -0
- package/dist/server/assets/rolldown-runtime-D8jQpDG7.js +12 -0
- package/dist/server/assets/{router-DqTf7XfT.js → router-CIIGBCmL.js} +84 -44
- package/dist/server/assets/settings-BHfngShx.js +371 -0
- package/dist/server/assets/src-D9VHcuh4.js +491 -0
- package/dist/server/assets/src-JXktBs5H.js +4 -0
- package/dist/server/assets/{ui-Lv-KcOoP.js → ui-BJokJdYa.js} +25 -3
- package/dist/server/server.js +32 -8
- package/package.json +4 -4
- package/dist/client/assets/_authed-Bi62GTX3.js +0 -7
- package/dist/client/assets/_authed-mWCAMokt.js +0 -1
- package/dist/client/assets/index-D7uhDdvA.js +0 -12
- package/dist/client/assets/issues._fingerprint-fVGLnT37.js +0 -1
- package/dist/client/assets/login-MqvT094Y.js +0 -1
- package/dist/client/assets/styles-CZZRuG1z.css +0 -2
- package/dist/client/assets/ui-Bj6uJIr8.js +0 -1
- package/dist/server/assets/dynamodb-DejcakaF.js +0 -187
- package/dist/server/assets/fns-CgB12FUN.js +0 -31
- package/dist/server/assets/fns-Yg8sT1Cb.js +0 -87
- package/dist/server/assets/memory-4DwW5cTO.js +0 -59
- package/dist/server/assets/rollups-JXbazRNh.js +0 -22
- package/dist/server/assets/src-D5jyi_C4.js +0 -235
|
@@ -0,0 +1,955 @@
|
|
|
1
|
+
import { a as getCookie, i as deleteCookie, o as getRequestHeader, s as setCookie } from "../server.js";
|
|
2
|
+
import { a as SEVERITY_ORDER, d as severityFromCount, i as DEFAULT_SEVERITY_THRESHOLDS, l as percentileMs, o as compareVersions } from "./memory-Do0CDoAX.js";
|
|
3
|
+
import { t as MAX_RETENTION_DAYS } from "./src-JXktBs5H.js";
|
|
4
|
+
import { createHmac, randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
|
|
5
|
+
// src/server/config.ts
|
|
6
|
+
var loaded = false;
|
|
7
|
+
function loadEnv() {
|
|
8
|
+
if (loaded) return;
|
|
9
|
+
loaded = true;
|
|
10
|
+
try {
|
|
11
|
+
process.loadEnvFile?.(process.env.DEBUG_ENV_FILE ?? ".env");
|
|
12
|
+
} catch {}
|
|
13
|
+
}
|
|
14
|
+
var generatedSecret;
|
|
15
|
+
function config() {
|
|
16
|
+
loadEnv();
|
|
17
|
+
const env = process.env;
|
|
18
|
+
const store = env.DEBUG_STORE ?? "demo";
|
|
19
|
+
let secret = env.DEBUG_SESSION_SECRET;
|
|
20
|
+
if (!secret || secret.length < 32) {
|
|
21
|
+
if (store !== "demo" && store !== "memory") throw new Error("DEBUG_SESSION_SECRET must be set (≥32 chars) when not in demo mode. Try: openssl rand -hex 32");
|
|
22
|
+
secret = generatedSecret ??= randomBytes(32).toString("hex");
|
|
23
|
+
}
|
|
24
|
+
const num = (v, d) => v && !Number.isNaN(Number(v)) ? Number(v) : d;
|
|
25
|
+
const severity = {
|
|
26
|
+
critical: num(env.DEBUG_SEVERITY_CRITICAL, DEFAULT_SEVERITY_THRESHOLDS.critical),
|
|
27
|
+
high: num(env.DEBUG_SEVERITY_HIGH, DEFAULT_SEVERITY_THRESHOLDS.high),
|
|
28
|
+
medium: num(env.DEBUG_SEVERITY_MEDIUM, DEFAULT_SEVERITY_THRESHOLDS.medium)
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
store,
|
|
32
|
+
sessionSecret: secret,
|
|
33
|
+
users: env.DEBUG_DASHBOARD_USERS ?? "",
|
|
34
|
+
apiToken: env.DEBUG_API_TOKEN,
|
|
35
|
+
/** Demo mode: keys accepted by POST /api/ingest. "*" = any app. */
|
|
36
|
+
localIngestKeys: env.DEBUG_LOCAL_INGEST_KEYS ?? "pk_local:*",
|
|
37
|
+
firestoreRoot: env.DEBUG_FIRESTORE_ROOT ?? "debug_apps",
|
|
38
|
+
dynamoTable: env.DEBUG_DYNAMO_TABLE ?? "debug",
|
|
39
|
+
severity,
|
|
40
|
+
/** The ingest function's admin routes (…/admin) and their token, for changing settings. */
|
|
41
|
+
adminUrl: env.DEBUG_ADMIN_URL?.replace(/\/+$/, ""),
|
|
42
|
+
adminToken: env.DEBUG_ADMIN_TOKEN,
|
|
43
|
+
/** The deployment's default retention (what ingest uses before an app has a setting). */
|
|
44
|
+
retentionDays: num(env.DEBUG_RETENTION_DAYS, 0) || void 0,
|
|
45
|
+
/** "Create issue" buttons on the issue page. */
|
|
46
|
+
trackers: {
|
|
47
|
+
linear: env.DEBUG_LINEAR === "1" || !!env.DEBUG_LINEAR_TEAM,
|
|
48
|
+
linearTeam: env.DEBUG_LINEAR_TEAM || void 0,
|
|
49
|
+
githubRepo: env.DEBUG_GITHUB_REPO || void 0,
|
|
50
|
+
dashboardUrl: env.DEBUG_DASHBOARD_URL || void 0
|
|
51
|
+
},
|
|
52
|
+
secureCookies: env.NODE_ENV === "production" && env.DEBUG_INSECURE_COOKIES !== "1"
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
// src/server/store.ts
|
|
56
|
+
var store;
|
|
57
|
+
/** The dashboard only ever reads. Point it at read-only credentials. */
|
|
58
|
+
function getStore() {
|
|
59
|
+
return store ??= create();
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Demo mode only: the in-memory store also accepts events, so a local app can send to
|
|
63
|
+
* http://localhost:4400/api/ingest and see them on the dashboard. Real stores stay read-only.
|
|
64
|
+
*/
|
|
65
|
+
async function getLocalWriteStore() {
|
|
66
|
+
const kind = config().store;
|
|
67
|
+
if (kind !== "demo" && kind !== "memory") return null;
|
|
68
|
+
return await getStore();
|
|
69
|
+
}
|
|
70
|
+
async function create() {
|
|
71
|
+
const cfg = config();
|
|
72
|
+
switch (cfg.store) {
|
|
73
|
+
case "firestore": {
|
|
74
|
+
const { initializeApp, getApps } = await import("firebase-admin/app");
|
|
75
|
+
const { getFirestore } = await import("firebase-admin/firestore");
|
|
76
|
+
const { FirestoreStore } = await import("./firestore-B2xzpzYA.js");
|
|
77
|
+
if (!getApps().length) initializeApp();
|
|
78
|
+
return new FirestoreStore(getFirestore(), { root: cfg.firestoreRoot });
|
|
79
|
+
}
|
|
80
|
+
case "dynamodb": {
|
|
81
|
+
const { DynamoDBClient } = await import("@aws-sdk/client-dynamodb");
|
|
82
|
+
const { DynamoDBDocumentClient } = await import("@aws-sdk/lib-dynamodb");
|
|
83
|
+
const { DynamoStore } = await import("./dynamodb-DyPK9SVV.js");
|
|
84
|
+
return new DynamoStore(DynamoDBDocumentClient.from(new DynamoDBClient({})), { table: cfg.dynamoTable });
|
|
85
|
+
}
|
|
86
|
+
case "memory": {
|
|
87
|
+
const { MemoryStore } = await import("./memory-Do0CDoAX.js").then((n) => n.n);
|
|
88
|
+
return new MemoryStore();
|
|
89
|
+
}
|
|
90
|
+
default: {
|
|
91
|
+
const { seedDemo } = await import("./demo-hrRBo9_U.js");
|
|
92
|
+
return seedDemo();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
// src/server/settings.ts
|
|
97
|
+
function settingsWriter() {
|
|
98
|
+
const c = config();
|
|
99
|
+
if (c.store === "demo" || c.store === "memory") return "local";
|
|
100
|
+
return c.adminUrl && c.adminToken ? "admin" : "none";
|
|
101
|
+
}
|
|
102
|
+
async function admin(method, route, body, query) {
|
|
103
|
+
const c = config();
|
|
104
|
+
const url = new URL(`${c.adminUrl}${route}`);
|
|
105
|
+
for (const [k, v] of Object.entries(query ?? {})) url.searchParams.set(k, v);
|
|
106
|
+
const res = await fetch(url, {
|
|
107
|
+
method,
|
|
108
|
+
headers: {
|
|
109
|
+
authorization: `Bearer ${c.adminToken}`,
|
|
110
|
+
...body ? { "content-type": "application/json" } : {}
|
|
111
|
+
},
|
|
112
|
+
body: body ? JSON.stringify(body) : void 0
|
|
113
|
+
});
|
|
114
|
+
const json = await res.json().catch(() => ({}));
|
|
115
|
+
if (!res.ok) throw new Error(json.error ?? `The ingest function answered ${res.status}`);
|
|
116
|
+
return json;
|
|
117
|
+
}
|
|
118
|
+
async function readSettings(app) {
|
|
119
|
+
const writer = settingsWriter();
|
|
120
|
+
const c = config();
|
|
121
|
+
if (writer === "admin") try {
|
|
122
|
+
const out = await admin("GET", "/settings", void 0, { app });
|
|
123
|
+
return {
|
|
124
|
+
app,
|
|
125
|
+
retentionDays: out.retentionDays,
|
|
126
|
+
criticalFlows: out.settings?.criticalFlows ?? [],
|
|
127
|
+
alerts: out.settings?.alerts ?? {},
|
|
128
|
+
source: out.settings?.retentionDays ? "setting" : "default",
|
|
129
|
+
updatedAt: out.settings?.updatedAt,
|
|
130
|
+
writer
|
|
131
|
+
};
|
|
132
|
+
} catch (err) {
|
|
133
|
+
return {
|
|
134
|
+
app,
|
|
135
|
+
retentionDays: c.retentionDays ?? null,
|
|
136
|
+
criticalFlows: [],
|
|
137
|
+
alerts: {},
|
|
138
|
+
source: c.retentionDays ? "default" : "unknown",
|
|
139
|
+
writer,
|
|
140
|
+
note: `Couldn't reach the ingest function: ${err.message}`
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const s = await (await getStore()).getSettings(app).catch(() => null);
|
|
144
|
+
const hook = s?.alerts?.slackWebhookUrl;
|
|
145
|
+
return {
|
|
146
|
+
app,
|
|
147
|
+
retentionDays: s?.retentionDays ?? c.retentionDays ?? (writer === "local" ? 30 : null),
|
|
148
|
+
criticalFlows: s?.criticalFlows ?? [],
|
|
149
|
+
alerts: {
|
|
150
|
+
...s?.alerts,
|
|
151
|
+
slackWebhookUrl: hook ? `https://hooks.slack.com/…${hook.slice(-4)}` : void 0
|
|
152
|
+
},
|
|
153
|
+
source: s?.retentionDays ? "setting" : c.retentionDays || writer === "local" ? "default" : "unknown",
|
|
154
|
+
updatedAt: s?.updatedAt,
|
|
155
|
+
writer,
|
|
156
|
+
note: writer === "none" ? "Changing settings needs DEBUG_ADMIN_URL and DEBUG_ADMIN_TOKEN (npx debugkit init sets them)." : void 0
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function validRetention(days) {
|
|
160
|
+
const n = Number(days);
|
|
161
|
+
if (!Number.isInteger(n) || n < 1 || n > 3650) throw new Error(`Retention must be a whole number of days from 1 to ${MAX_RETENTION_DAYS}.`);
|
|
162
|
+
return n;
|
|
163
|
+
}
|
|
164
|
+
async function writeRetention(app, days) {
|
|
165
|
+
const writer = settingsWriter();
|
|
166
|
+
if (writer === "admin") await admin("PUT", "/settings", {
|
|
167
|
+
app,
|
|
168
|
+
retentionDays: days
|
|
169
|
+
});
|
|
170
|
+
else if (writer === "local") await (await getLocalWriteStore()).putSettings(app, { retentionDays: days });
|
|
171
|
+
else throw new Error("Settings can't be changed from this dashboard: DEBUG_ADMIN_URL and DEBUG_ADMIN_TOKEN aren't set.");
|
|
172
|
+
return readSettings(app);
|
|
173
|
+
}
|
|
174
|
+
/** Change critical flows and/or alert settings. Validation happens in the ingest function (or here, locally). */
|
|
175
|
+
async function writeSettings(app, patch) {
|
|
176
|
+
const writer = settingsWriter();
|
|
177
|
+
if (writer === "admin") await admin("PUT", "/settings", {
|
|
178
|
+
app,
|
|
179
|
+
...patch
|
|
180
|
+
});
|
|
181
|
+
else if (writer === "local") {
|
|
182
|
+
const store = await getLocalWriteStore();
|
|
183
|
+
const cur = await store.getSettings(app);
|
|
184
|
+
const url = patch.alerts?.slackWebhookUrl;
|
|
185
|
+
if (patch.alerts && url && !url.includes("…") && !/^https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9/_-]{10,200}$/.test(url)) throw new Error("Use a Slack incoming-webhook URL (https://hooks.slack.com/services/…).");
|
|
186
|
+
const alerts = patch.alerts ? {
|
|
187
|
+
...patch.alerts,
|
|
188
|
+
slackWebhookUrl: url?.includes("…") ? cur?.alerts?.slackWebhookUrl : url || void 0
|
|
189
|
+
} : void 0;
|
|
190
|
+
await store.putSettings(app, {
|
|
191
|
+
...patch.criticalFlows ? { criticalFlows: patch.criticalFlows } : {},
|
|
192
|
+
...alerts ? { alerts } : {}
|
|
193
|
+
});
|
|
194
|
+
} else throw new Error("Settings can't be changed from this dashboard: DEBUG_ADMIN_URL and DEBUG_ADMIN_TOKEN aren't set.");
|
|
195
|
+
return readSettings(app);
|
|
196
|
+
}
|
|
197
|
+
async function testAlert(app) {
|
|
198
|
+
if (settingsWriter() !== "admin") throw new Error("Test alerts are sent by your ingest function, so they need a cloud setup (not demo or local mode).");
|
|
199
|
+
await admin("POST", "/alert-test", { app });
|
|
200
|
+
}
|
|
201
|
+
/** Open, resolve (optionally "fixed in <version>") or ignore an issue. */
|
|
202
|
+
async function writeIssueStatus(app, fingerprint, status, resolvedIn) {
|
|
203
|
+
const writer = settingsWriter();
|
|
204
|
+
if (writer === "admin") return admin("PUT", "/issue", {
|
|
205
|
+
app,
|
|
206
|
+
fingerprint,
|
|
207
|
+
status,
|
|
208
|
+
resolvedIn
|
|
209
|
+
});
|
|
210
|
+
if (writer === "local") {
|
|
211
|
+
const issue = await (await getLocalWriteStore()).setIssueStatus(app, fingerprint, {
|
|
212
|
+
status,
|
|
213
|
+
resolvedIn
|
|
214
|
+
});
|
|
215
|
+
if (!issue) throw new Error("No such issue.");
|
|
216
|
+
return {
|
|
217
|
+
status: issue.status,
|
|
218
|
+
resolvedIn: issue.resolvedIn ?? null
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
throw new Error("Issue status can't be changed from this dashboard: DEBUG_ADMIN_URL and DEBUG_ADMIN_TOKEN aren't set.");
|
|
222
|
+
}
|
|
223
|
+
/** One page of re-stamping existing events with the current retention. */
|
|
224
|
+
async function restampStep(app, cursor) {
|
|
225
|
+
const writer = settingsWriter();
|
|
226
|
+
if (writer === "admin") return admin("POST", "/restamp", {
|
|
227
|
+
app,
|
|
228
|
+
cursor
|
|
229
|
+
});
|
|
230
|
+
if (writer === "local") {
|
|
231
|
+
const store = await getLocalWriteStore();
|
|
232
|
+
const days = (await store.getSettings(app))?.retentionDays ?? config().retentionDays ?? 30;
|
|
233
|
+
return store.restampExpiry(app, days, { cursor });
|
|
234
|
+
}
|
|
235
|
+
throw new Error("Settings can't be changed from this dashboard.");
|
|
236
|
+
}
|
|
237
|
+
// src/server/auth.ts
|
|
238
|
+
var COOKIE = "debug_session";
|
|
239
|
+
var MAX_AGE_S = 43200;
|
|
240
|
+
var DEMO_USER = {
|
|
241
|
+
email: "demo@debug.local",
|
|
242
|
+
password: "demo-debug"
|
|
243
|
+
};
|
|
244
|
+
function users() {
|
|
245
|
+
const cfg = config();
|
|
246
|
+
const map = /* @__PURE__ */ new Map();
|
|
247
|
+
for (const pair of cfg.users.split(",").map((s) => s.trim()).filter(Boolean)) {
|
|
248
|
+
const i = pair.indexOf("=");
|
|
249
|
+
if (i > 0) map.set(pair.slice(0, i).toLowerCase(), pair.slice(i + 1));
|
|
250
|
+
}
|
|
251
|
+
return map;
|
|
252
|
+
}
|
|
253
|
+
function demoLoginEnabled() {
|
|
254
|
+
return config().store === "demo" && users().size === 0;
|
|
255
|
+
}
|
|
256
|
+
function verifyHash(password, stored) {
|
|
257
|
+
const [algo, saltHex, hashHex] = stored.split(".");
|
|
258
|
+
if (algo !== "scrypt" || !saltHex || !hashHex) return false;
|
|
259
|
+
const expected = Buffer.from(hashHex, "hex");
|
|
260
|
+
const actual = scryptSync(password, Buffer.from(saltHex, "hex"), expected.length);
|
|
261
|
+
return timingSafeEqual(actual, expected);
|
|
262
|
+
}
|
|
263
|
+
function checkCredentials(email, password) {
|
|
264
|
+
const e = email.trim().toLowerCase();
|
|
265
|
+
if (demoLoginEnabled()) return e === DEMO_USER.email && password === DEMO_USER.password ? { email: e } : null;
|
|
266
|
+
const stored = users().get(e);
|
|
267
|
+
const ok = verifyHash(password, stored ?? "scrypt.00000000000000000000000000000000." + "00".repeat(64));
|
|
268
|
+
return stored && ok ? { email: e } : null;
|
|
269
|
+
}
|
|
270
|
+
var sign = (payload) => createHmac("sha256", config().sessionSecret).update(payload).digest("base64url");
|
|
271
|
+
function startSession(user) {
|
|
272
|
+
const payload = Buffer.from(JSON.stringify({
|
|
273
|
+
email: user.email,
|
|
274
|
+
exp: Date.now() + MAX_AGE_S * 1e3
|
|
275
|
+
})).toString("base64url");
|
|
276
|
+
setCookie(COOKIE, `${payload}.${sign(payload)}`, {
|
|
277
|
+
httpOnly: true,
|
|
278
|
+
sameSite: "lax",
|
|
279
|
+
secure: config().secureCookies,
|
|
280
|
+
path: "/",
|
|
281
|
+
maxAge: MAX_AGE_S
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
function endSession() {
|
|
285
|
+
deleteCookie(COOKIE, { path: "/" });
|
|
286
|
+
}
|
|
287
|
+
function readSession() {
|
|
288
|
+
const raw = getCookie(COOKIE);
|
|
289
|
+
if (!raw) return null;
|
|
290
|
+
const [payload, sig] = raw.split(".");
|
|
291
|
+
if (!payload || !sig) return null;
|
|
292
|
+
const expected = Buffer.from(sign(payload));
|
|
293
|
+
const given = Buffer.from(sig);
|
|
294
|
+
if (expected.length !== given.length || !timingSafeEqual(expected, given)) return null;
|
|
295
|
+
try {
|
|
296
|
+
const data = JSON.parse(Buffer.from(payload, "base64url").toString());
|
|
297
|
+
if (Date.now() > data.exp) return null;
|
|
298
|
+
return { email: data.email };
|
|
299
|
+
} catch {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/** For /api/* routes: a browser session or `Authorization: Bearer $DEBUG_API_TOKEN`. */
|
|
304
|
+
function authorizeApi(request) {
|
|
305
|
+
if (readSession()) return true;
|
|
306
|
+
const token = config().apiToken;
|
|
307
|
+
const header = request.headers.get("authorization") ?? getRequestHeader("authorization") ?? "";
|
|
308
|
+
if (!token || !header.startsWith("Bearer ")) return false;
|
|
309
|
+
const a = Buffer.from(header.slice(7));
|
|
310
|
+
const b = Buffer.from(token);
|
|
311
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
312
|
+
}
|
|
313
|
+
// src/server/range.ts
|
|
314
|
+
/** The date range a dashboard view covers, worked out from the URL (range=7d, or from/to). */
|
|
315
|
+
var RANGE_PRESETS = [
|
|
316
|
+
"24h",
|
|
317
|
+
"7d",
|
|
318
|
+
"14d",
|
|
319
|
+
"30d",
|
|
320
|
+
"90d"
|
|
321
|
+
];
|
|
322
|
+
var DAY$1 = 864e5;
|
|
323
|
+
var dayKey$1 = (t) => new Date(t).toISOString().slice(0, 10);
|
|
324
|
+
var ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
325
|
+
function short(day) {
|
|
326
|
+
return (/* @__PURE__ */ new Date(`${day}T00:00:00Z`)).toLocaleDateString("en-GB", {
|
|
327
|
+
day: "numeric",
|
|
328
|
+
month: "short",
|
|
329
|
+
timeZone: "UTC"
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
function resolveRange(input, now = Date.now()) {
|
|
333
|
+
const today = dayKey$1(now);
|
|
334
|
+
let preset = RANGE_PRESETS.includes(input.range ?? "") ? input.range : "14d";
|
|
335
|
+
let from;
|
|
336
|
+
let to = today;
|
|
337
|
+
let days;
|
|
338
|
+
if (input.range === "custom" && ISO_DAY.test(input.from ?? "") && ISO_DAY.test(input.to ?? "") && !Number.isNaN(Date.parse(input.from)) && !Number.isNaN(Date.parse(input.to))) {
|
|
339
|
+
preset = "custom";
|
|
340
|
+
to = input.to > today ? today : input.to;
|
|
341
|
+
from = input.from > to ? to : input.from;
|
|
342
|
+
days = Math.round((Date.parse(to) - Date.parse(from)) / DAY$1) + 1;
|
|
343
|
+
if (days > 730) {
|
|
344
|
+
from = dayKey$1(Date.parse(to) - 729 * DAY$1);
|
|
345
|
+
days = 730;
|
|
346
|
+
}
|
|
347
|
+
} else if (preset === "24h") {
|
|
348
|
+
from = dayKey$1(now - DAY$1);
|
|
349
|
+
days = 1;
|
|
350
|
+
} else {
|
|
351
|
+
days = Number(preset.replace("d", ""));
|
|
352
|
+
from = dayKey$1(now - (days - 1) * DAY$1);
|
|
353
|
+
}
|
|
354
|
+
const prevTo = dayKey$1(Date.parse(from) - DAY$1);
|
|
355
|
+
const prevFrom = dayKey$1(Date.parse(from) - days * DAY$1);
|
|
356
|
+
const span = preset === "24h" ? "24 hours" : `${days} day${days === 1 ? "" : "s"}`;
|
|
357
|
+
const label = preset === "custom" ? from === to ? short(from) : `${short(from)} – ${short(to)}` : `the last ${span}`;
|
|
358
|
+
return {
|
|
359
|
+
preset,
|
|
360
|
+
from,
|
|
361
|
+
to,
|
|
362
|
+
days,
|
|
363
|
+
label,
|
|
364
|
+
span,
|
|
365
|
+
prevFrom,
|
|
366
|
+
prevTo,
|
|
367
|
+
granularity: preset === "24h" ? "hour" : days > 90 ? "week" : "day"
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
/** Every UTC day from `from` to `to`, inclusive. */
|
|
371
|
+
function daysBetween(from, to) {
|
|
372
|
+
const out = [];
|
|
373
|
+
for (let t = Date.parse(`${from}T00:00:00Z`); t <= Date.parse(`${to}T00:00:00Z`); t += DAY$1) out.push(dayKey$1(t));
|
|
374
|
+
return out;
|
|
375
|
+
}
|
|
376
|
+
/** The Monday a day's week starts on, for weekly buckets. */
|
|
377
|
+
function weekOf(day) {
|
|
378
|
+
const t = Date.parse(`${day}T00:00:00Z`);
|
|
379
|
+
return dayKey$1(t - (new Date(t).getUTCDay() + 6) % 7 * DAY$1);
|
|
380
|
+
}
|
|
381
|
+
// src/server/queries.ts
|
|
382
|
+
var DAY = 864e5;
|
|
383
|
+
var HOUR = 36e5;
|
|
384
|
+
var dayKey = (t) => new Date(t).toISOString().slice(0, 10);
|
|
385
|
+
var hourKey = (t) => new Date(t).toISOString().slice(0, 13);
|
|
386
|
+
function hours(now, n) {
|
|
387
|
+
return Array.from({ length: n }, (_, i) => hourKey(now - (n - 1 - i) * HOUR));
|
|
388
|
+
}
|
|
389
|
+
/** Description of every field, shipped with the JSON API so agents can interpret it without docs. */
|
|
390
|
+
var SUMMARY_FIELDS = {
|
|
391
|
+
range: "The period the numbers cover. Query with ?range=24h|7d|14d|30d|90d, or ?range=custom&from=YYYY-MM-DD&to=YYYY-MM-DD. Default 14d.",
|
|
392
|
+
retention: "How long raw events are kept. Counts, issues and release health are kept forever; event details older than detailsFrom have expired.",
|
|
393
|
+
"totals.errors24h": "Error events in the trailing 24 hours (exact, from hourly rollups).",
|
|
394
|
+
"totals.errorsRange": "Error events in the selected range.",
|
|
395
|
+
"totals.changePct": "Percent change of errors vs the previous period of the same length. null when that period had fewer than 10 errors.",
|
|
396
|
+
"totals.activeIssues": "Distinct grouped errors (issues) seen in the range.",
|
|
397
|
+
"totals.criticalIssues": "Issues whose 24h occurrence count meets the critical threshold.",
|
|
398
|
+
"flows[]": "Parts of the app as tagged by the developer (e.g. auth.login). Sorted by severity, then errors24h, then errorsRange.",
|
|
399
|
+
"flows[].failureRate": "failures/(failures+successes) in the range from events logged with an outcome. null when the app logs no outcomes for that flow.",
|
|
400
|
+
"issues[]": "Grouped errors seen in the range. Sorted by severity, then count24h, then countRange.",
|
|
401
|
+
"issues[].severity": "Derived from count24h using thresholds critical/high/medium.",
|
|
402
|
+
"issues[].culprit": "Top in-app stack frame: function (file:line).",
|
|
403
|
+
"trend[]": "Errors and non-error events per hour (24h), UTC day (up to 90 days) or week (longer).",
|
|
404
|
+
breakdowns: "Errors in the range split by OS, app version and device model.",
|
|
405
|
+
narrative: "Plain-language summary of what is going wrong in the range.",
|
|
406
|
+
"health.crashFreeRate": "Share of sessions in the range with no fatal crash. Sessions are recorded automatically by the SDK.",
|
|
407
|
+
"health.errorFreeRate": "Share of sessions in the range with no unhandled error.",
|
|
408
|
+
"health.releases[]": "Crash-free and error-free rates per app version.",
|
|
409
|
+
"health.endpoints[]": "HTTP endpoints whose requests failed most (5xx, timeouts, network errors), from automatic network capture.",
|
|
410
|
+
"health.users": "Distinct users active since the start of the range (user id when set, else the install's anonymous id; stored hashed).",
|
|
411
|
+
"health.crashFreeUsersRate": "Share of those users who didn't crash.",
|
|
412
|
+
"issues[].status": "open, resolved, ignored, or regressed (seen again in the fixed release or later).",
|
|
413
|
+
"issues[].newInLatest": "First seen in latestVersion: likely introduced by the newest release.",
|
|
414
|
+
"issues[].users": "Distinct users affected since the start of the range (top issues only).",
|
|
415
|
+
"releases[]": "Releases first seen inside the range, with the day they appeared: markers on the trend.",
|
|
416
|
+
"steps[]": "track(flow, step) outcomes per step in the range, most failures first.",
|
|
417
|
+
"timings[]": "Busiest endpoints with p50/p95 response time (bucket upper bounds, ms) and error rate, from automatic request timing.",
|
|
418
|
+
"breakdowns.network": "Errors by network type (wifi, cellular...).",
|
|
419
|
+
"breakdowns.country": "Errors by country, from the device's timezone or locale (never IP).",
|
|
420
|
+
criticalFlows: "Flows marked critical in Settings; their issues rank one severity level higher."
|
|
421
|
+
};
|
|
422
|
+
var sumRows = (rows, field = "errors") => rows.reduce((a, r) => a + r[field], 0);
|
|
423
|
+
/** Retention as the dashboard knows it: the app's setting, else the deployment default it was told about. */
|
|
424
|
+
async function retentionFor(store, app, fallbackDays, now = Date.now()) {
|
|
425
|
+
let days = null;
|
|
426
|
+
let source = "unknown";
|
|
427
|
+
try {
|
|
428
|
+
const s = await store.getSettings(app);
|
|
429
|
+
if (s?.retentionDays) [days, source] = [s.retentionDays, "setting"];
|
|
430
|
+
} catch {}
|
|
431
|
+
if (days === null && fallbackDays) [days, source] = [fallbackDays, "default"];
|
|
432
|
+
return {
|
|
433
|
+
days,
|
|
434
|
+
source,
|
|
435
|
+
detailsFrom: days ? dayKey(now - days * DAY) : null
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
async function buildSummary(store, appParam, thresholds, now = Date.now(), opts = {}) {
|
|
439
|
+
const apps = await store.listApps();
|
|
440
|
+
const app = appParam && apps.includes(appParam) ? appParam : apps[0];
|
|
441
|
+
if (!app) return null;
|
|
442
|
+
const range = resolveRange(opts.range ?? {}, now);
|
|
443
|
+
const { from, to } = range;
|
|
444
|
+
const hourly = range.preset === "24h";
|
|
445
|
+
const h24 = hours(now, 24);
|
|
446
|
+
const [sessionRows, endpointRows, total, prevTotal, flowRows, outcomeRows, os, appVersion, deviceModel, issueDays, issues, hourRows, retention] = await Promise.all([
|
|
447
|
+
store.getRollups(app, "session", from, to),
|
|
448
|
+
store.getRollups(app, "endpoint", from, to),
|
|
449
|
+
store.getRollups(app, "total", from, to),
|
|
450
|
+
store.getRollups(app, "total", range.prevFrom, range.prevTo),
|
|
451
|
+
store.getRollups(app, "flow", from, to),
|
|
452
|
+
store.getRollups(app, "flowOutcome", from, to),
|
|
453
|
+
store.getRollups(app, "os", from, to),
|
|
454
|
+
store.getRollups(app, "appVersion", from, to),
|
|
455
|
+
store.getRollups(app, "deviceModel", from, to),
|
|
456
|
+
store.getRollups(app, "issue", from, to),
|
|
457
|
+
store.listIssues(app, { limit: 500 }),
|
|
458
|
+
store.getRollups(app, "issueHour", hours(now, 48)[0], hourKey(now)),
|
|
459
|
+
retentionFor(store, app, opts.retentionDays, now)
|
|
460
|
+
]);
|
|
461
|
+
const [releaseRows, stepRows, requestRows, latencyRows, networkRows, countryRows, appSettings] = await Promise.all([
|
|
462
|
+
store.getRollups(app, "release", dayKey(Date.parse(`${from}T00:00:00Z`) - 365 * DAY), to),
|
|
463
|
+
store.getRollups(app, "flowStep", from, to),
|
|
464
|
+
store.getRollups(app, "requests", from, to),
|
|
465
|
+
store.getRollups(app, "latency", from, to),
|
|
466
|
+
store.getRollups(app, "network", from, to),
|
|
467
|
+
store.getRollups(app, "country", from, to),
|
|
468
|
+
store.getSettings(app).catch(() => null)
|
|
469
|
+
]);
|
|
470
|
+
const criticalFlows = appSettings?.criticalFlows ?? [];
|
|
471
|
+
const critical = new Set(criticalFlows);
|
|
472
|
+
const usersSince = hourly ? dayKey(now - DAY) : from;
|
|
473
|
+
const [users, crashedUsers] = await Promise.all([store.countUsers(app, "app", usersSince), store.countUsers(app, "crash", usersSince)]);
|
|
474
|
+
const last24 = new Set(h24);
|
|
475
|
+
let errors24h = 0;
|
|
476
|
+
let errorsPrev24h = 0;
|
|
477
|
+
const issue24h = /* @__PURE__ */ new Map();
|
|
478
|
+
for (const r of hourRows) if (last24.has(r.day)) {
|
|
479
|
+
errors24h += r.errors;
|
|
480
|
+
issue24h.set(r.key, (issue24h.get(r.key) ?? 0) + r.errors);
|
|
481
|
+
} else errorsPrev24h += r.errors;
|
|
482
|
+
let trend;
|
|
483
|
+
if (hourly) trend = h24.map((h) => ({
|
|
484
|
+
day: h,
|
|
485
|
+
errors: hourRows.filter((r) => r.day === h).reduce((a, r) => a + r.errors, 0),
|
|
486
|
+
events: 0
|
|
487
|
+
}));
|
|
488
|
+
else {
|
|
489
|
+
const byDay = new Map(total.map((r) => [r.day, r]));
|
|
490
|
+
const daily = daysBetween(from, to).map((day) => ({
|
|
491
|
+
day,
|
|
492
|
+
errors: byDay.get(day)?.errors ?? 0,
|
|
493
|
+
events: byDay.get(day)?.events ?? 0
|
|
494
|
+
}));
|
|
495
|
+
if (range.granularity === "week") {
|
|
496
|
+
const weeks = /* @__PURE__ */ new Map();
|
|
497
|
+
for (const d of daily) {
|
|
498
|
+
const w = weekOf(d.day);
|
|
499
|
+
const cur = weeks.get(w) ?? {
|
|
500
|
+
day: w,
|
|
501
|
+
errors: 0,
|
|
502
|
+
events: 0
|
|
503
|
+
};
|
|
504
|
+
cur.errors += d.errors;
|
|
505
|
+
cur.events += d.events;
|
|
506
|
+
weeks.set(w, cur);
|
|
507
|
+
}
|
|
508
|
+
trend = [...weeks.values()];
|
|
509
|
+
} else trend = daily;
|
|
510
|
+
}
|
|
511
|
+
const errorsRange = hourly ? errors24h : sumRows(total);
|
|
512
|
+
const errorsPrev = hourly ? errorsPrev24h : sumRows(prevTotal);
|
|
513
|
+
const issueRange = /* @__PURE__ */ new Map();
|
|
514
|
+
for (const r of issueDays) issueRange.set(r.key, (issueRange.get(r.key) ?? 0) + r.errors);
|
|
515
|
+
const rangeStart = hourly ? (/* @__PURE__ */ new Date(now - DAY)).toISOString() : `${from}T00:00:00.000Z`;
|
|
516
|
+
const versionsInRange = [...new Set(sessionRows.map((r) => r.key.split("|")[0]).filter((v) => v && v !== "unknown"))].sort(compareVersions);
|
|
517
|
+
const latestVersion = versionsInRange[versionsInRange.length - 1] ?? null;
|
|
518
|
+
const issueRows = issues.filter((i) => i.lastSeen >= rangeStart && i.firstSeen <= `${to}T23:59:59.999Z`).map((i) => toIssueRow(i, issue24h.get(i.fingerprint) ?? 0, hourly ? issue24h.get(i.fingerprint) ?? 0 : issueRange.get(i.fingerprint) ?? 0, thresholds, latestVersion, critical)).sort(bySeverityThenCount);
|
|
519
|
+
const active = issueRows.filter((i) => i.status !== "ignored" && i.status !== "resolved");
|
|
520
|
+
await Promise.all(active.slice(0, 10).map(async (i) => i.users = await store.countUsers(app, `issue:${i.fingerprint}`, usersSince)));
|
|
521
|
+
const firstDay = /* @__PURE__ */ new Map();
|
|
522
|
+
for (const r of releaseRows) {
|
|
523
|
+
const cur = firstDay.get(r.key);
|
|
524
|
+
if (!cur) firstDay.set(r.key, {
|
|
525
|
+
day: r.day,
|
|
526
|
+
sessions: r.events
|
|
527
|
+
});
|
|
528
|
+
else {
|
|
529
|
+
if (r.day < cur.day) cur.day = r.day;
|
|
530
|
+
cur.sessions += r.events;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
const releases = [...firstDay.entries()].filter(([, v]) => v.day >= from && v.day <= to).map(([release, v]) => ({
|
|
534
|
+
release,
|
|
535
|
+
firstDay: v.day,
|
|
536
|
+
sessions: v.sessions
|
|
537
|
+
})).sort((a, b) => a.firstDay.localeCompare(b.firstDay));
|
|
538
|
+
const flowMap = /* @__PURE__ */ new Map();
|
|
539
|
+
const flowOf = (flow) => {
|
|
540
|
+
let f = flowMap.get(flow);
|
|
541
|
+
if (!f) flowMap.set(flow, f = {
|
|
542
|
+
flow,
|
|
543
|
+
errors24h: 0,
|
|
544
|
+
errorsRange: 0,
|
|
545
|
+
severity: "low",
|
|
546
|
+
issues: 0,
|
|
547
|
+
successesRange: 0,
|
|
548
|
+
failuresRange: 0,
|
|
549
|
+
failureRate: null,
|
|
550
|
+
critical: critical.has(flow)
|
|
551
|
+
});
|
|
552
|
+
return f;
|
|
553
|
+
};
|
|
554
|
+
for (const r of flowRows) if (r.errors > 0) flowOf(r.key).errorsRange += r.errors;
|
|
555
|
+
for (const i of active) {
|
|
556
|
+
const f = flowOf(i.flow ?? "untagged");
|
|
557
|
+
f.issues++;
|
|
558
|
+
f.errors24h += i.count24h;
|
|
559
|
+
if (SEVERITY_ORDER[i.severity] > SEVERITY_ORDER[f.severity]) f.severity = i.severity;
|
|
560
|
+
}
|
|
561
|
+
for (const r of outcomeRows) {
|
|
562
|
+
const [flow, outcome] = r.key.split("|");
|
|
563
|
+
const f = flowOf(flow);
|
|
564
|
+
if (outcome === "success") f.successesRange += r.events;
|
|
565
|
+
else if (outcome === "failure") f.failuresRange += r.events;
|
|
566
|
+
}
|
|
567
|
+
const flows = [...flowMap.values()].map((f) => ({
|
|
568
|
+
...f,
|
|
569
|
+
failureRate: f.successesRange + f.failuresRange > 0 ? f.failuresRange / (f.successesRange + f.failuresRange) : null
|
|
570
|
+
})).filter((f) => f.errorsRange > 0 || f.failuresRange > 0 || f.errors24h > 0).sort((a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || b.errors24h - a.errors24h || b.errorsRange - a.errorsRange);
|
|
571
|
+
const top = (rows) => {
|
|
572
|
+
const m = /* @__PURE__ */ new Map();
|
|
573
|
+
for (const r of rows) m.set(r.key, (m.get(r.key) ?? 0) + r.errors);
|
|
574
|
+
return [...m.entries()].map(([key, errors]) => ({
|
|
575
|
+
key,
|
|
576
|
+
errors
|
|
577
|
+
})).filter((r) => r.errors > 0).sort((a, b) => b.errors - a.errors).slice(0, 8);
|
|
578
|
+
};
|
|
579
|
+
const summary = {
|
|
580
|
+
app,
|
|
581
|
+
apps,
|
|
582
|
+
generatedAt: new Date(now).toISOString(),
|
|
583
|
+
range,
|
|
584
|
+
retention,
|
|
585
|
+
totals: {
|
|
586
|
+
errors24h,
|
|
587
|
+
errorsRange,
|
|
588
|
+
errorsPrev,
|
|
589
|
+
changePct: errorsPrev >= 10 ? Math.round((errorsRange - errorsPrev) / errorsPrev * 100) : null,
|
|
590
|
+
eventsRange: sumRows(total, "events"),
|
|
591
|
+
activeIssues: active.length,
|
|
592
|
+
criticalIssues: active.filter((i) => i.severity === "critical").length,
|
|
593
|
+
failingFlows: flows.filter((f) => (hourly ? f.errors24h : f.errorsRange) > 0).length
|
|
594
|
+
},
|
|
595
|
+
narrative: [],
|
|
596
|
+
trend,
|
|
597
|
+
flows,
|
|
598
|
+
issues: issueRows,
|
|
599
|
+
breakdowns: {
|
|
600
|
+
os: top(os),
|
|
601
|
+
appVersion: top(appVersion),
|
|
602
|
+
deviceModel: top(deviceModel),
|
|
603
|
+
network: top(networkRows),
|
|
604
|
+
country: top(countryRows)
|
|
605
|
+
},
|
|
606
|
+
steps: buildSteps(stepRows),
|
|
607
|
+
timings: buildTimings(requestRows, latencyRows),
|
|
608
|
+
criticalFlows,
|
|
609
|
+
health: {
|
|
610
|
+
...buildHealth(sessionRows, endpointRows, dayKey(now)),
|
|
611
|
+
users,
|
|
612
|
+
crashedUsers,
|
|
613
|
+
crashFreeUsersRate: users > 0 ? Math.max(0, 1 - crashedUsers / users) : null
|
|
614
|
+
},
|
|
615
|
+
releases,
|
|
616
|
+
latestVersion
|
|
617
|
+
};
|
|
618
|
+
summary.narrative = narrate(summary);
|
|
619
|
+
return summary;
|
|
620
|
+
}
|
|
621
|
+
var rate = (bad, total) => total > 0 ? Math.max(0, 1 - bad / total) : null;
|
|
622
|
+
function buildHealth(sessionRows, endpointRows, today) {
|
|
623
|
+
const byVersion = /* @__PURE__ */ new Map();
|
|
624
|
+
for (const r of sessionRows) {
|
|
625
|
+
const [version = "unknown", status] = r.key.split("|");
|
|
626
|
+
let v = byVersion.get(version);
|
|
627
|
+
if (!v) byVersion.set(version, v = {
|
|
628
|
+
version,
|
|
629
|
+
sessions: 0,
|
|
630
|
+
errored: 0,
|
|
631
|
+
crashed: 0,
|
|
632
|
+
crashFreeRate: null,
|
|
633
|
+
errorFreeRate: null
|
|
634
|
+
});
|
|
635
|
+
if (status === "started") v.sessions += r.events;
|
|
636
|
+
else if (status === "errored") v.errored += r.events;
|
|
637
|
+
else if (status === "crashed") v.crashed += r.events;
|
|
638
|
+
}
|
|
639
|
+
const releases = [...byVersion.values()].map((v) => ({
|
|
640
|
+
...v,
|
|
641
|
+
crashFreeRate: rate(v.crashed, v.sessions),
|
|
642
|
+
errorFreeRate: rate(v.errored, v.sessions)
|
|
643
|
+
})).filter((v) => v.sessions > 0).sort((a, b) => compareVersions(b.version, a.version)).slice(0, 8);
|
|
644
|
+
const sum = (k) => [...byVersion.values()].reduce((a, v) => a + v[k], 0);
|
|
645
|
+
const eps = /* @__PURE__ */ new Map();
|
|
646
|
+
for (const r of endpointRows) {
|
|
647
|
+
let e = eps.get(r.key);
|
|
648
|
+
if (!e) eps.set(r.key, e = {
|
|
649
|
+
endpoint: r.key,
|
|
650
|
+
failuresRange: 0,
|
|
651
|
+
failures24h: 0
|
|
652
|
+
});
|
|
653
|
+
e.failuresRange += r.errors;
|
|
654
|
+
if (r.day === today) e.failures24h += r.errors;
|
|
655
|
+
}
|
|
656
|
+
return {
|
|
657
|
+
sessionsRange: sum("sessions"),
|
|
658
|
+
crashFreeRate: rate(sum("crashed"), sum("sessions")),
|
|
659
|
+
errorFreeRate: rate(sum("errored"), sum("sessions")),
|
|
660
|
+
releases,
|
|
661
|
+
endpoints: [...eps.values()].sort((a, b) => b.failuresRange - a.failuresRange).slice(0, 8)
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
var BUMP = {
|
|
665
|
+
low: "medium",
|
|
666
|
+
medium: "high",
|
|
667
|
+
high: "critical",
|
|
668
|
+
critical: "critical"
|
|
669
|
+
};
|
|
670
|
+
function buildSteps(rows) {
|
|
671
|
+
const m = /* @__PURE__ */ new Map();
|
|
672
|
+
for (const r of rows) {
|
|
673
|
+
const [flow = "", step = "", outcome] = r.key.split("|");
|
|
674
|
+
const k = `${flow}|${step}`;
|
|
675
|
+
let s = m.get(k);
|
|
676
|
+
if (!s) m.set(k, s = {
|
|
677
|
+
flow,
|
|
678
|
+
step,
|
|
679
|
+
successes: 0,
|
|
680
|
+
failures: 0,
|
|
681
|
+
abandoned: 0,
|
|
682
|
+
failureRate: null
|
|
683
|
+
});
|
|
684
|
+
if (outcome === "success") s.successes += r.events;
|
|
685
|
+
else if (outcome === "failure") s.failures += r.events;
|
|
686
|
+
else if (outcome === "abandoned") s.abandoned += r.events;
|
|
687
|
+
}
|
|
688
|
+
return [...m.values()].map((s) => ({
|
|
689
|
+
...s,
|
|
690
|
+
failureRate: s.successes + s.failures > 0 ? s.failures / (s.successes + s.failures) : null
|
|
691
|
+
})).sort((a, b) => b.failures - a.failures || (b.failureRate ?? 0) - (a.failureRate ?? 0)).slice(0, 30);
|
|
692
|
+
}
|
|
693
|
+
function buildTimings(requestRows, latencyRows) {
|
|
694
|
+
const totals = /* @__PURE__ */ new Map();
|
|
695
|
+
for (const r of requestRows) {
|
|
696
|
+
const t = totals.get(r.key) ?? {
|
|
697
|
+
requests: 0,
|
|
698
|
+
failed: 0
|
|
699
|
+
};
|
|
700
|
+
t.requests += r.events;
|
|
701
|
+
t.failed += r.errors;
|
|
702
|
+
totals.set(r.key, t);
|
|
703
|
+
}
|
|
704
|
+
const hist = /* @__PURE__ */ new Map();
|
|
705
|
+
for (const r of latencyRows) {
|
|
706
|
+
const cut = r.key.lastIndexOf("|");
|
|
707
|
+
const key = r.key.slice(0, cut);
|
|
708
|
+
const i = Number(r.key.slice(cut + 1));
|
|
709
|
+
const b = hist.get(key) ?? new Array(13).fill(0);
|
|
710
|
+
if (i >= 0 && i < 13) b[i] += r.events;
|
|
711
|
+
hist.set(key, b);
|
|
712
|
+
}
|
|
713
|
+
return [...totals.entries()].map(([endpoint, t]) => {
|
|
714
|
+
const b = hist.get(endpoint) ?? [];
|
|
715
|
+
return {
|
|
716
|
+
endpoint,
|
|
717
|
+
requests: t.requests,
|
|
718
|
+
failed: t.failed,
|
|
719
|
+
errorRate: t.requests ? t.failed / t.requests : 0,
|
|
720
|
+
p50: percentileMs(b, .5),
|
|
721
|
+
p95: percentileMs(b, .95)
|
|
722
|
+
};
|
|
723
|
+
}).sort((a, b) => b.requests - a.requests).slice(0, 10);
|
|
724
|
+
}
|
|
725
|
+
function toIssueRow(i, count24h, countRange, t, latestVersion = null, critical = /* @__PURE__ */ new Set()) {
|
|
726
|
+
const base = severityFromCount(count24h, t);
|
|
727
|
+
return {
|
|
728
|
+
status: i.status ?? "open",
|
|
729
|
+
resolvedIn: i.resolvedIn,
|
|
730
|
+
firstVersion: i.firstVersion,
|
|
731
|
+
lastVersion: i.lastVersion,
|
|
732
|
+
newInLatest: !!latestVersion && i.firstVersion === latestVersion,
|
|
733
|
+
fingerprint: i.fingerprint,
|
|
734
|
+
title: i.title,
|
|
735
|
+
culprit: i.culprit,
|
|
736
|
+
flow: i.flow,
|
|
737
|
+
severity: i.flow && critical.has(i.flow) && count24h > 0 ? BUMP[base] : base,
|
|
738
|
+
count24h,
|
|
739
|
+
countRange,
|
|
740
|
+
countTotal: i.count,
|
|
741
|
+
firstSeen: i.firstSeen,
|
|
742
|
+
lastSeen: i.lastSeen
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
var bySeverityThenCount = (a, b) => SEVERITY_ORDER[b.severity] - SEVERITY_ORDER[a.severity] || b.count24h - a.count24h || b.countRange - a.countRange || b.lastSeen.localeCompare(a.lastSeen);
|
|
746
|
+
var pct = (n) => `${Math.round(n * 100)}%`;
|
|
747
|
+
var pctOne = (n) => `${(Math.floor(n * 1e3) / 10).toFixed(1)}%`;
|
|
748
|
+
var plural = (n, word) => `${n.toLocaleString()} ${word}${n === 1 ? "" : "s"}`;
|
|
749
|
+
function narrate(s) {
|
|
750
|
+
const out = [];
|
|
751
|
+
const t = s.totals;
|
|
752
|
+
const r = s.range;
|
|
753
|
+
if (t.errorsRange === 0) {
|
|
754
|
+
out.push(`No errors in ${r.label}.`);
|
|
755
|
+
return out;
|
|
756
|
+
}
|
|
757
|
+
const change = t.changePct === null ? "" : t.changePct === 0 ? `, flat versus the previous ${r.span}` : t.changePct > 500 ? `, up from ${t.errorsPrev.toLocaleString()} in the previous ${r.span}` : `, ${t.changePct > 0 ? "up" : "down"} ${Math.abs(t.changePct)}% on the previous ${r.span}`;
|
|
758
|
+
out.push(`${plural(t.errorsRange, "error")} in ${r.label}${change}, across ${t.failingFlows} part${t.failingFlows === 1 ? "" : "s"} of the app.`);
|
|
759
|
+
const f = s.flows[0];
|
|
760
|
+
if (f && (f.errors24h > 0 || f.errorsRange > 0)) {
|
|
761
|
+
const failRate = f.failureRate !== null ? ` ${pct(f.failureRate)} of attempts fail.` : "";
|
|
762
|
+
const n = r.preset === "24h" ? f.errors24h : f.errorsRange;
|
|
763
|
+
out.push(`${f.flow}${f.critical ? " (a critical flow)" : ""} is the most affected flow (${f.severity}): ${plural(n, "error")} in ${r.label} from ${plural(f.issues, "issue")}.${failRate}`);
|
|
764
|
+
}
|
|
765
|
+
const i = s.issues.find((x) => x.status !== "ignored" && x.status !== "resolved");
|
|
766
|
+
if (i && i.countRange > 0) {
|
|
767
|
+
const isNew = Date.parse(s.generatedAt) - Date.parse(i.firstSeen) < 3 * DAY;
|
|
768
|
+
out.push(`Top issue: "${i.title}"${i.culprit ? ` in ${i.culprit}` : ""}, ${plural(i.countRange, "time")} in ${r.label}${isNew ? `, first seen ${relDays(s.generatedAt, i.firstSeen)}` : ""}.`);
|
|
769
|
+
}
|
|
770
|
+
const h = s.health;
|
|
771
|
+
const latest = h.releases[0];
|
|
772
|
+
const prev = h.releases[1];
|
|
773
|
+
if (latest?.crashFreeRate != null && latest.sessions >= 20 && latest.crashFreeRate < .995) {
|
|
774
|
+
const vs = prev?.crashFreeRate != null && prev.sessions >= 20 ? ` (${prev.version}: ${pctOne(prev.crashFreeRate)})` : "";
|
|
775
|
+
out.push(`${latest.version} is ${pctOne(latest.crashFreeRate)} crash-free across ${plural(latest.sessions, "session")}${vs}.`);
|
|
776
|
+
}
|
|
777
|
+
const ep = h.endpoints[0];
|
|
778
|
+
if (ep && ep.failuresRange > 0) out.push(`${ep.endpoint} is the most failing endpoint: ${plural(ep.failuresRange, "failed request")} in ${r.label}.`);
|
|
779
|
+
const net = s.breakdowns.network.filter((r) => r.key !== "unknown");
|
|
780
|
+
const netTotal = net.reduce((a, b) => a + b.errors, 0);
|
|
781
|
+
if (net[0] && netTotal >= 20 && net[0].errors / netTotal > .6 && net[0].key !== "wifi") out.push(`${pct(net[0].errors / netTotal)} of errors happen on ${net[0].key}: check timeouts and retries on slow connections.`);
|
|
782
|
+
const os = s.breakdowns.os;
|
|
783
|
+
const osTotal = os.reduce((a, b) => a + b.errors, 0);
|
|
784
|
+
if (os[0] && osTotal > 20 && os[0].errors / osTotal > .6) out.push(`${pct(os[0].errors / osTotal)} of errors in ${r.label} come from ${os[0].key}.`);
|
|
785
|
+
return out;
|
|
786
|
+
}
|
|
787
|
+
function relDays(now, then) {
|
|
788
|
+
const d = Math.floor((Date.parse(now) - Date.parse(then)) / DAY);
|
|
789
|
+
return d === 0 ? "today" : d === 1 ? "yesterday" : `${d} days ago`;
|
|
790
|
+
}
|
|
791
|
+
async function buildIssueDetail(store, app, fingerprint, thresholds, now = Date.now(), opts = {}) {
|
|
792
|
+
const issue = await store.getIssue(app, fingerprint);
|
|
793
|
+
if (!issue) return null;
|
|
794
|
+
const range = resolveRange(opts.range ?? {}, now);
|
|
795
|
+
const hs = hours(now, 48);
|
|
796
|
+
const [hourRows, dayRows, events, retention] = await Promise.all([
|
|
797
|
+
store.getRollups(app, "issueHour", hs[0], hs[hs.length - 1]),
|
|
798
|
+
store.getRollups(app, "issue", range.from, range.to),
|
|
799
|
+
store.listIssueEvents(app, fingerprint, { limit: 200 }),
|
|
800
|
+
retentionFor(store, app, opts.retentionDays, now)
|
|
801
|
+
]);
|
|
802
|
+
const hourly = hs.map((hour) => ({
|
|
803
|
+
hour,
|
|
804
|
+
count: hourRows.filter((r) => r.key === fingerprint && r.day === hour).reduce((a, r) => a + r.errors, 0)
|
|
805
|
+
}));
|
|
806
|
+
const daily = daysBetween(range.from, range.to).map((day) => ({
|
|
807
|
+
day,
|
|
808
|
+
count: dayRows.filter((r) => r.key === fingerprint && r.day === day).reduce((a, r) => a + r.errors, 0)
|
|
809
|
+
}));
|
|
810
|
+
const count24h = hourly.slice(-24).reduce((a, h) => a + h.count, 0);
|
|
811
|
+
const countRange = range.preset === "24h" ? count24h : daily.reduce((a, d) => a + d.count, 0);
|
|
812
|
+
const split = (pick) => {
|
|
813
|
+
const m = /* @__PURE__ */ new Map();
|
|
814
|
+
for (const e of events) {
|
|
815
|
+
const k = pick(e) || "unknown";
|
|
816
|
+
m.set(k, (m.get(k) ?? 0) + 1);
|
|
817
|
+
}
|
|
818
|
+
return [...m.entries()].map(([key, count]) => ({
|
|
819
|
+
key,
|
|
820
|
+
count,
|
|
821
|
+
share: events.length ? count / events.length : 0
|
|
822
|
+
})).sort((a, b) => b.count - a.count).slice(0, 6);
|
|
823
|
+
};
|
|
824
|
+
const breakdowns = {
|
|
825
|
+
os: split((e) => `${e.context.os.name} ${e.context.os.version ?? ""}`.trim()),
|
|
826
|
+
appVersion: split((e) => e.context.app.version),
|
|
827
|
+
deviceModel: split((e) => e.context.device.model),
|
|
828
|
+
network: split((e) => e.context.network?.type),
|
|
829
|
+
runtime: split((e) => [e.context.runtime.name, e.context.runtime.engine].filter(Boolean).join(" / "))
|
|
830
|
+
};
|
|
831
|
+
const usersSince = range.preset === "24h" ? dayKey(now - DAY) : range.from;
|
|
832
|
+
const affectedUsers = await store.countUsers(app, `issue:${fingerprint}`, usersSince) || new Set(events.map((e) => e.user?.id ?? e.user?.anonymousId ?? e.sessionId)).size;
|
|
833
|
+
const row = toIssueRow(issue, count24h, countRange, thresholds);
|
|
834
|
+
const hints = hintsFor(issue, breakdowns, events);
|
|
835
|
+
const detail = {
|
|
836
|
+
app,
|
|
837
|
+
range,
|
|
838
|
+
retention,
|
|
839
|
+
issue: row,
|
|
840
|
+
hourly,
|
|
841
|
+
daily,
|
|
842
|
+
breakdowns,
|
|
843
|
+
affectedUsers,
|
|
844
|
+
links: {},
|
|
845
|
+
sample: events[0] ?? issue.lastEvent ?? null,
|
|
846
|
+
recent: events.slice(0, 25).map((e) => ({
|
|
847
|
+
ts: e.event.ts,
|
|
848
|
+
os: `${e.context.os.name} ${e.context.os.version ?? ""}`.trim(),
|
|
849
|
+
appVersion: e.context.app.version,
|
|
850
|
+
device: e.context.device.model,
|
|
851
|
+
message: e.event.type === "error" ? e.event.error.message : e.event.type === "event" ? e.event.name : e.event.type === "session" ? `session ${e.event.status}` : `requests to ${e.event.key}`,
|
|
852
|
+
userId: e.user?.id
|
|
853
|
+
})),
|
|
854
|
+
hints
|
|
855
|
+
};
|
|
856
|
+
detail.links = trackerLinks(detail, opts.trackers ?? {});
|
|
857
|
+
return detail;
|
|
858
|
+
}
|
|
859
|
+
/** The issue as a ticket: what, where, how often, what to look at. Kept short enough for a URL. */
|
|
860
|
+
function issueStory(d, dashboardUrl) {
|
|
861
|
+
const i = d.issue;
|
|
862
|
+
const top = (rows) => rows.filter((r) => r.key !== "unknown").slice(0, 3).map((r) => `${r.key} (${Math.round(r.share * 100)}%)`).join(", ") || "n/a";
|
|
863
|
+
const frames = d.sample?.event.type === "error" ? (d.sample.event.error.frames ?? []).filter((f) => f.inApp).slice(0, 3) : [];
|
|
864
|
+
const body = [
|
|
865
|
+
`**${i.title}**`,
|
|
866
|
+
i.culprit ? `At \`${i.culprit}\`${i.flow ? ` in flow \`${i.flow}\`` : ""}.` : i.flow ? `In flow \`${i.flow}\`.` : "",
|
|
867
|
+
"",
|
|
868
|
+
`- ${i.countRange.toLocaleString()} occurrences in ${d.range.label}, ${i.count24h} in the last 24h (severity: ${i.severity})`,
|
|
869
|
+
`- ${d.affectedUsers.toLocaleString()} users affected`,
|
|
870
|
+
`- First seen ${i.firstSeen.slice(0, 10)}${i.firstVersion ? ` in ${i.firstVersion}` : ""}; last seen ${i.lastSeen.slice(0, 10)}${i.lastVersion ? ` in ${i.lastVersion}` : ""}`,
|
|
871
|
+
`- Versions: ${top(d.breakdowns.appVersion)}`,
|
|
872
|
+
`- OS: ${top(d.breakdowns.os)}; devices: ${top(d.breakdowns.deviceModel)}`,
|
|
873
|
+
...frames.length ? [
|
|
874
|
+
"",
|
|
875
|
+
"Stack (in-app frames):",
|
|
876
|
+
...frames.map((f) => `- \`${f.fn ?? "?"}\` ${f.file ?? ""}:${f.line ?? ""}`)
|
|
877
|
+
] : [],
|
|
878
|
+
...d.hints.length ? [
|
|
879
|
+
"",
|
|
880
|
+
"What to look at:",
|
|
881
|
+
...d.hints.slice(0, 3).map((h) => `- ${h.title}: ${h.detail}`)
|
|
882
|
+
] : [],
|
|
883
|
+
...dashboardUrl ? ["", `deBug: ${dashboardUrl.replace(/\/+$/, "")}/issues/${i.fingerprint}?app=${encodeURIComponent(d.app)}`] : []
|
|
884
|
+
].filter((l, n, all) => !(l === "" && all[n - 1] === "")).join("\n");
|
|
885
|
+
return {
|
|
886
|
+
title: `[deBug] ${i.title}`.slice(0, 200),
|
|
887
|
+
body: body.slice(0, 3e3)
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
function trackerLinks(d, t) {
|
|
891
|
+
const { title, body } = issueStory(d, t.dashboardUrl);
|
|
892
|
+
const q = (p) => new URLSearchParams(p).toString();
|
|
893
|
+
return {
|
|
894
|
+
...t.linear || t.linearTeam ? { linear: `${t.linearTeam ? `https://linear.app/team/${encodeURIComponent(t.linearTeam)}/new` : "https://linear.new"}?${q({
|
|
895
|
+
title,
|
|
896
|
+
description: body
|
|
897
|
+
})}` } : {},
|
|
898
|
+
...t.githubRepo && /^[\w.-]+\/[\w.-]+$/.test(t.githubRepo) ? { github: `https://github.com/${t.githubRepo}/issues/new?${q({
|
|
899
|
+
title,
|
|
900
|
+
body
|
|
901
|
+
})}` } : {}
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
/** Rule-based "what to look at" hints. Phase 2 replaces/augments these with an LLM over the same data. */
|
|
905
|
+
function hintsFor(issue, b, events) {
|
|
906
|
+
const hints = [];
|
|
907
|
+
const text = `${issue.title} ${events[0]?.event.type === "error" ? events[0].event.error.stack ?? "" : ""}`.toLowerCase();
|
|
908
|
+
const crumbs = events.flatMap((e) => e.event.type === "error" ? e.event.breadcrumbs ?? [] : []);
|
|
909
|
+
const concentrated = (label, rows) => {
|
|
910
|
+
const r = rows[0];
|
|
911
|
+
if (r && r.key !== "unknown" && r.share >= .8 && events.length >= 5 && rows.length >= 1) hints.push({
|
|
912
|
+
title: `Concentrated on ${label} ${r.key}`,
|
|
913
|
+
detail: `${Math.round(r.share * 100)}% of recent occurrences. Reproduce on ${r.key} first, and check what changed for it.`
|
|
914
|
+
});
|
|
915
|
+
};
|
|
916
|
+
concentrated("app version", b.appVersion);
|
|
917
|
+
concentrated("OS", b.os);
|
|
918
|
+
concentrated("device", b.deviceModel);
|
|
919
|
+
if (/cannot read propert|undefined is not an object|of undefined|of null|is not a function/.test(text)) hints.push({
|
|
920
|
+
title: "A value is missing when the code expects it",
|
|
921
|
+
detail: `Something is null/undefined at ${issue.culprit ?? "the top frame"}. Check the data the previous step returns (API response shape, async state not yet loaded) and add a guard or loading state.`
|
|
922
|
+
});
|
|
923
|
+
if (/network request failed|failed to fetch|networkerror|timeout|timed out|econn|socket/.test(text)) hints.push({
|
|
924
|
+
title: "Network failure",
|
|
925
|
+
detail: "Check if errors line up with poor connectivity (see the network breakdown), add retries with backoff, and show an offline/timeout state instead of failing."
|
|
926
|
+
});
|
|
927
|
+
if (/\b401\b|\b403\b|unauthori[sz]ed|forbidden|token expired|jwt/.test(text)) hints.push({
|
|
928
|
+
title: "Auth/session problem",
|
|
929
|
+
detail: "Look for expired or missing tokens. Confirm the token refresh runs before this call, and that the clock/expiry handling is right."
|
|
930
|
+
});
|
|
931
|
+
if (/json|unexpected token|syntaxerror/.test(text)) hints.push({
|
|
932
|
+
title: "Bad response body",
|
|
933
|
+
detail: "The app tried to parse something that isn't the JSON it expected — often an HTML error page or an empty 204/5xx. Log the status and content-type before parsing."
|
|
934
|
+
});
|
|
935
|
+
if (/\b5\d\d\b|internal server error|bad gateway|service unavailable/.test(text)) hints.push({
|
|
936
|
+
title: "Server-side failure",
|
|
937
|
+
detail: "The backend returned a 5xx. Correlate the timestamps with your API logs."
|
|
938
|
+
});
|
|
939
|
+
const failingRequests = crumbs.filter((c) => c.category === "network" && (c.level === "error" || /\b[45]\d\d\b/.test(c.message)));
|
|
940
|
+
if (failingRequests.length) {
|
|
941
|
+
const m = /* @__PURE__ */ new Map();
|
|
942
|
+
for (const c of failingRequests) m.set(c.message, (m.get(c.message) ?? 0) + 1);
|
|
943
|
+
const [msg] = [...m.entries()].sort((a, b) => b[1] - a[1])[0];
|
|
944
|
+
hints.push({
|
|
945
|
+
title: "A request fails right before the error",
|
|
946
|
+
detail: `Most common: ${msg}`
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
if (hints.length === 0) hints.push({
|
|
950
|
+
title: "Start at the culprit frame",
|
|
951
|
+
detail: `Open ${issue.culprit ?? "the top stack frame"} and use the breadcrumbs below to replay what the user did.`
|
|
952
|
+
});
|
|
953
|
+
return hints;
|
|
954
|
+
}
|
|
955
|
+
export { writeRetention as _, authorizeApi as a, getStore as b, endSession as c, readSettings as d, restampStep as f, writeIssueStatus as g, validRetention as h, DEMO_USER as i, readSession as l, testAlert as m, buildIssueDetail as n, checkCredentials as o, settingsWriter as p, buildSummary as r, demoLoginEnabled as s, SUMMARY_FIELDS as t, startSession as u, writeSettings as v, config as x, getLocalWriteStore as y };
|