@warlock.js/devtools 5.54.0 → 5.56.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/CHANGELOG.md +36 -0
- package/README.md +26 -13
- package/cjs/{ai-source-CSPh1HqJ.cjs → ai-source-DTpxumMA.cjs} +54 -3
- package/cjs/{ai-source-CSPh1HqJ.cjs.map → ai-source-DTpxumMA.cjs.map} +1 -1
- package/cjs/auth-DzU0gHDG.cjs +1655 -0
- package/cjs/auth-DzU0gHDG.cjs.map +1 -0
- package/cjs/boot-BQi0Etor.cjs +138 -0
- package/cjs/boot-BQi0Etor.cjs.map +1 -0
- package/cjs/capture-CqIiaznN.cjs +1342 -0
- package/cjs/capture-CqIiaznN.cjs.map +1 -0
- package/cjs/cascade-store-pHjKeSFm.cjs +863 -0
- package/cjs/cascade-store-pHjKeSFm.cjs.map +1 -0
- package/cjs/collector-CJbQbzzK.cjs +271 -0
- package/cjs/collector-CJbQbzzK.cjs.map +1 -0
- package/cjs/contracts-CVmplkNb.cjs +112 -0
- package/cjs/contracts-CVmplkNb.cjs.map +1 -0
- package/cjs/current-request-id-BoJJb3y7.cjs +37 -0
- package/cjs/current-request-id-BoJJb3y7.cjs.map +1 -0
- package/cjs/errors-CyZp5yS-.cjs +177 -0
- package/cjs/errors-CyZp5yS-.cjs.map +1 -0
- package/cjs/histogram-BaI-PnCv.cjs +102 -0
- package/cjs/histogram-BaI-PnCv.cjs.map +1 -0
- package/cjs/http-CabcUwBx.cjs +870 -0
- package/cjs/http-CabcUwBx.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/insights-BKtqxdnP.cjs +811 -0
- package/cjs/insights-BKtqxdnP.cjs.map +1 -0
- package/cjs/ip-DbNhPOzi.cjs +153 -0
- package/cjs/ip-DbNhPOzi.cjs.map +1 -0
- package/cjs/migrations-w7GMsrQw.cjs +297 -0
- package/cjs/migrations-w7GMsrQw.cjs.map +1 -0
- package/cjs/openapi-CC7OAUc6.cjs +52 -0
- package/cjs/openapi-CC7OAUc6.cjs.map +1 -0
- package/cjs/options-CWqFC5__.cjs +181 -0
- package/cjs/options-CWqFC5__.cjs.map +1 -0
- package/cjs/panels-B0dAfGbJ.cjs +298 -0
- package/cjs/panels-B0dAfGbJ.cjs.map +1 -0
- package/cjs/process-panel-DEOnLxoT.cjs +48 -0
- package/cjs/process-panel-DEOnLxoT.cjs.map +1 -0
- package/cjs/production/index.cjs +238 -0
- package/cjs/production/index.cjs.map +1 -0
- package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +52 -0
- package/cjs/server-B6xdeKS8.cjs +184 -0
- package/cjs/server-B6xdeKS8.cjs.map +1 -0
- package/cjs/{src-BzuntLcd.cjs → src-Ce-3Lniv.cjs} +171 -308
- package/cjs/src-Ce-3Lniv.cjs.map +1 -0
- package/cjs/store-aq207T8v.cjs +9 -0
- package/cjs/stream-route-BGJa-zQu.cjs +875 -0
- package/cjs/stream-route-BGJa-zQu.cjs.map +1 -0
- package/esm/devtools-connector.d.mts +16 -12
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +137 -18
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/options.mjs +3 -1
- package/esm/options.mjs.map +1 -1
- package/esm/panels.mjs +267 -0
- package/esm/panels.mjs.map +1 -0
- package/esm/process-panel.mjs +20 -1
- package/esm/process-panel.mjs.map +1 -1
- package/esm/production/auth/common-passwords.mjs +303 -0
- package/esm/production/auth/common-passwords.mjs.map +1 -0
- package/esm/production/auth/default-crypto.mjs +19 -0
- package/esm/production/auth/default-crypto.mjs.map +1 -0
- package/esm/production/auth/helpers.mjs +77 -0
- package/esm/production/auth/helpers.mjs.map +1 -0
- package/esm/production/auth/index.mjs +6 -0
- package/esm/production/auth/passkeys.mjs +96 -0
- package/esm/production/auth/passkeys.mjs.map +1 -0
- package/esm/production/auth/service.mjs +1166 -0
- package/esm/production/auth/service.mjs.map +1 -0
- package/esm/production/boot.mjs +138 -0
- package/esm/production/boot.mjs.map +1 -0
- package/esm/production/capture/dev-stats.mjs +83 -0
- package/esm/production/capture/dev-stats.mjs.map +1 -0
- package/esm/production/capture/engine.mjs +442 -0
- package/esm/production/capture/engine.mjs.map +1 -0
- package/esm/production/capture/explain.mjs +271 -0
- package/esm/production/capture/explain.mjs.map +1 -0
- package/esm/production/capture/filter.mjs +24 -0
- package/esm/production/capture/filter.mjs.map +1 -0
- package/esm/production/capture/index.mjs +7 -0
- package/esm/production/capture/production-capture.mjs +134 -0
- package/esm/production/capture/production-capture.mjs.map +1 -0
- package/esm/production/capture/redact.mjs +109 -0
- package/esm/production/capture/redact.mjs.map +1 -0
- package/esm/production/capture/stats-stores.mjs +300 -0
- package/esm/production/capture/stats-stores.mjs.map +1 -0
- package/esm/production/cli/actions.mjs +151 -0
- package/esm/production/cli/actions.mjs.map +1 -0
- package/esm/production/cli/index.d.mts +17 -0
- package/esm/production/cli/index.d.mts.map +1 -0
- package/esm/production/cli/index.mjs +86 -0
- package/esm/production/cli/index.mjs.map +1 -0
- package/esm/production/contracts.d.mts +592 -0
- package/esm/production/contracts.d.mts.map +1 -0
- package/esm/production/contracts.mjs +95 -0
- package/esm/production/contracts.mjs.map +1 -0
- package/esm/production/errors.d.mts +31 -0
- package/esm/production/errors.d.mts.map +1 -0
- package/esm/production/errors.mjs +142 -0
- package/esm/production/errors.mjs.map +1 -0
- package/esm/production/http/access.mjs +124 -0
- package/esm/production/http/access.mjs.map +1 -0
- package/esm/production/http/auth-routes.mjs +280 -0
- package/esm/production/http/auth-routes.mjs.map +1 -0
- package/esm/production/http/client.mjs +57 -0
- package/esm/production/http/client.mjs.map +1 -0
- package/esm/production/http/constants.mjs +11 -0
- package/esm/production/http/constants.mjs.map +1 -0
- package/esm/production/http/context.mjs +14 -0
- package/esm/production/http/context.mjs.map +1 -0
- package/esm/production/http/cookie.mjs +39 -0
- package/esm/production/http/cookie.mjs.map +1 -0
- package/esm/production/http/headers.mjs +25 -0
- package/esm/production/http/headers.mjs.map +1 -0
- package/esm/production/http/index.mjs +10 -0
- package/esm/production/http/ip.mjs +130 -0
- package/esm/production/http/ip.mjs.map +1 -0
- package/esm/production/http/mount.mjs +300 -0
- package/esm/production/http/mount.mjs.map +1 -0
- package/esm/production/http/state.mjs +54 -0
- package/esm/production/http/state.mjs.map +1 -0
- package/esm/production/index.d.mts +6 -0
- package/esm/production/index.mjs +5 -0
- package/esm/production/insights/cap-report.mjs +67 -0
- package/esm/production/insights/cap-report.mjs.map +1 -0
- package/esm/production/insights/health.mjs +88 -0
- package/esm/production/insights/health.mjs.map +1 -0
- package/esm/production/insights/index.mjs +10 -0
- package/esm/production/insights/insights.mjs +167 -0
- package/esm/production/insights/insights.mjs.map +1 -0
- package/esm/production/insights/instance.mjs +24 -0
- package/esm/production/insights/instance.mjs.map +1 -0
- package/esm/production/insights/jobs.mjs +100 -0
- package/esm/production/insights/jobs.mjs.map +1 -0
- package/esm/production/insights/reporter.mjs +59 -0
- package/esm/production/insights/reporter.mjs.map +1 -0
- package/esm/production/insights/resources.mjs +139 -0
- package/esm/production/insights/resources.mjs.map +1 -0
- package/esm/production/insights/writer.mjs +72 -0
- package/esm/production/insights/writer.mjs.map +1 -0
- package/esm/production/openapi.mjs +52 -0
- package/esm/production/openapi.mjs.map +1 -0
- package/esm/production/options.d.mts +60 -0
- package/esm/production/options.d.mts.map +1 -0
- package/esm/production/options.mjs +170 -0
- package/esm/production/options.mjs.map +1 -0
- package/esm/production/stats/histogram.mjs +67 -0
- package/esm/production/stats/histogram.mjs.map +1 -0
- package/esm/production/stats/merge.mjs +106 -0
- package/esm/production/stats/merge.mjs.map +1 -0
- package/esm/production/store/cascade-store.mjs +322 -0
- package/esm/production/store/cascade-store.mjs.map +1 -0
- package/esm/production/store/index.mjs +5 -0
- package/esm/production/store/mapping.mjs +258 -0
- package/esm/production/store/mapping.mjs.map +1 -0
- package/esm/production/store/memory-store.mjs +291 -0
- package/esm/production/store/memory-store.mjs.map +1 -0
- package/esm/production/store/migrations.d.mts +11 -0
- package/esm/production/store/migrations.d.mts.map +1 -0
- package/esm/production/store/migrations.mjs +29 -0
- package/esm/production/store/migrations.mjs.map +1 -0
- package/esm/production/store/models/account.migration.mjs +34 -0
- package/esm/production/store/models/account.migration.mjs.map +1 -0
- package/esm/production/store/models/account.model.mjs +13 -0
- package/esm/production/store/models/account.model.mjs.map +1 -0
- package/esm/production/store/models/audit.migration.mjs +30 -0
- package/esm/production/store/models/audit.migration.mjs.map +1 -0
- package/esm/production/store/models/audit.model.mjs +13 -0
- package/esm/production/store/models/audit.model.mjs.map +1 -0
- package/esm/production/store/models/base.mjs +27 -0
- package/esm/production/store/models/base.mjs.map +1 -0
- package/esm/production/store/models/index.mjs +17 -0
- package/esm/production/store/models/invite.migration.mjs +26 -0
- package/esm/production/store/models/invite.migration.mjs.map +1 -0
- package/esm/production/store/models/invite.model.mjs +13 -0
- package/esm/production/store/models/invite.model.mjs.map +1 -0
- package/esm/production/store/models/report.migration.mjs +20 -0
- package/esm/production/store/models/report.migration.mjs.map +1 -0
- package/esm/production/store/models/report.model.mjs +13 -0
- package/esm/production/store/models/report.model.mjs.map +1 -0
- package/esm/production/store/models/sample.migration.mjs +25 -0
- package/esm/production/store/models/sample.migration.mjs.map +1 -0
- package/esm/production/store/models/sample.model.mjs +13 -0
- package/esm/production/store/models/sample.model.mjs.map +1 -0
- package/esm/production/store/models/session.migration.mjs +31 -0
- package/esm/production/store/models/session.migration.mjs.map +1 -0
- package/esm/production/store/models/session.model.mjs +13 -0
- package/esm/production/store/models/session.model.mjs.map +1 -0
- package/esm/production/store/models/state.migration.mjs +26 -0
- package/esm/production/store/models/state.migration.mjs.map +1 -0
- package/esm/production/store/models/state.model.mjs +13 -0
- package/esm/production/store/models/state.model.mjs.map +1 -0
- package/esm/query-shape.mjs +14 -1
- package/esm/query-shape.mjs.map +1 -1
- package/esm/server/explain-route.mjs +26 -1
- package/esm/server/explain-route.mjs.map +1 -1
- package/esm/server/index.mjs +16 -6
- package/esm/server/index.mjs.map +1 -1
- package/esm/server/insights-routes.mjs +62 -0
- package/esm/server/insights-routes.mjs.map +1 -0
- package/esm/server/log-routes.mjs +32 -5
- package/esm/server/log-routes.mjs.map +1 -1
- package/esm/server/openapi-routes.mjs +3 -2
- package/esm/server/openapi-routes.mjs.map +1 -1
- package/esm/server/panel-routes.mjs +44 -0
- package/esm/server/panel-routes.mjs.map +1 -0
- package/esm/server/requests-routes.mjs +125 -0
- package/esm/server/requests-routes.mjs.map +1 -1
- package/esm/server/session-routes.mjs +42 -0
- package/esm/server/session-routes.mjs.map +1 -0
- package/esm/server/stream-route.mjs +81 -11
- package/esm/server/stream-route.mjs.map +1 -1
- package/esm/server/ui-assets.mjs +34 -12
- package/esm/server/ui-assets.mjs.map +1 -1
- package/esm/sources/log-source.mjs +14 -1
- package/esm/sources/log-source.mjs.map +1 -1
- package/esm/types.d.mts +271 -1
- package/esm/types.d.mts.map +1 -1
- package/esm/ui-root.mjs +11 -6
- package/esm/ui-root.mjs.map +1 -1
- package/llms-full.txt +208 -19
- package/llms.txt +2 -2
- package/package.json +32 -8
- package/skills/SKILL.md +208 -19
- package/ui/dashboard/assets/app.css +3 -0
- package/ui/dashboard/assets/app.js +50 -0
- package/ui/dashboard/build-info.json +21 -0
- package/ui/dashboard/index.html +15 -0
- package/ui/panels/processes.js +15 -0
- package/cjs/server-BlQshJLE.cjs +0 -658
- package/cjs/server-BlQshJLE.cjs.map +0 -1
- package/cjs/src-BzuntLcd.cjs.map +0 -1
- package/esm/server/process-routes.mjs +0 -11
- package/esm/server/process-routes.mjs.map +0 -1
- package/ui/app.css +0 -376
- package/ui/app.js +0 -1054
- package/ui/index.html +0 -28
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { PerformanceObserver, constants, monitorEventLoopDelay, performance } from "node:perf_hooks";
|
|
2
|
+
import v8 from "node:v8";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/devtools/src/production/insights/resources.ts
|
|
5
|
+
function gcKindName(kind) {
|
|
6
|
+
if (kind === constants.NODE_PERFORMANCE_GC_MAJOR) return "major";
|
|
7
|
+
if (kind === constants.NODE_PERFORMANCE_GC_INCREMENTAL) return "incremental";
|
|
8
|
+
if (kind === constants.NODE_PERFORMANCE_GC_WEAKCB) return "weakcb";
|
|
9
|
+
return "minor";
|
|
10
|
+
}
|
|
11
|
+
const defaultSources = {
|
|
12
|
+
now: () => Date.now(),
|
|
13
|
+
memoryUsage: () => process.memoryUsage(),
|
|
14
|
+
cpuUsage: () => process.cpuUsage(),
|
|
15
|
+
heapLimit: () => v8.getHeapStatistics().heap_size_limit,
|
|
16
|
+
uptime: () => process.uptime(),
|
|
17
|
+
eventLoopDelay: () => monitorEventLoopDelay({ resolution: 20 }),
|
|
18
|
+
eventLoopUtilization: () => performance.eventLoopUtilization(),
|
|
19
|
+
observeGc(onGc) {
|
|
20
|
+
const observer = new PerformanceObserver((list) => {
|
|
21
|
+
for (const entry of list.getEntries()) onGc(gcKindName(entry.detail?.kind ?? entry.kind), entry.duration);
|
|
22
|
+
});
|
|
23
|
+
observer.observe({ entryTypes: ["gc"] });
|
|
24
|
+
return () => observer.disconnect();
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/** Nanoseconds to milliseconds; a histogram with no samples reports 0. */
|
|
28
|
+
function nsToMs(value) {
|
|
29
|
+
return Number.isFinite(value) && value > 0 && value < 0x38d7ea4c68000 ? value / 1e6 : 0;
|
|
30
|
+
}
|
|
31
|
+
/** Resource sampling every `intervalMs` (default 5000), `historySize` points (default 120). */
|
|
32
|
+
function createResourceMonitor(options = {}) {
|
|
33
|
+
const intervalMs = options.intervalMs ?? 5e3;
|
|
34
|
+
const historySize = Math.max(1, options.historySize ?? 120);
|
|
35
|
+
const sources = {
|
|
36
|
+
...defaultSources,
|
|
37
|
+
...options.sources
|
|
38
|
+
};
|
|
39
|
+
const loopDelay = sources.eventLoopDelay();
|
|
40
|
+
const points = [];
|
|
41
|
+
const gcByKind = {
|
|
42
|
+
minor: {
|
|
43
|
+
count: 0,
|
|
44
|
+
pauseMs: 0
|
|
45
|
+
},
|
|
46
|
+
major: {
|
|
47
|
+
count: 0,
|
|
48
|
+
pauseMs: 0
|
|
49
|
+
},
|
|
50
|
+
incremental: {
|
|
51
|
+
count: 0,
|
|
52
|
+
pauseMs: 0
|
|
53
|
+
},
|
|
54
|
+
weakcb: {
|
|
55
|
+
count: 0,
|
|
56
|
+
pauseMs: 0
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
let gcCountSince = 0;
|
|
60
|
+
let gcPauseSince = 0;
|
|
61
|
+
let lastAt = sources.now();
|
|
62
|
+
let lastCpu = sources.cpuUsage();
|
|
63
|
+
let lastElu = sources.eventLoopUtilization();
|
|
64
|
+
let timer;
|
|
65
|
+
let stopGc;
|
|
66
|
+
function sample() {
|
|
67
|
+
const at = sources.now();
|
|
68
|
+
const memory = sources.memoryUsage();
|
|
69
|
+
const cpu = sources.cpuUsage();
|
|
70
|
+
const elu = sources.eventLoopUtilization();
|
|
71
|
+
const wallMs = at - lastAt;
|
|
72
|
+
const cpuMs = (cpu.user + cpu.system - lastCpu.user - lastCpu.system) / 1e3;
|
|
73
|
+
const active = elu.active - lastElu.active;
|
|
74
|
+
const idle = elu.idle - lastElu.idle;
|
|
75
|
+
const point = {
|
|
76
|
+
at,
|
|
77
|
+
rssBytes: memory.rss,
|
|
78
|
+
heapUsedBytes: memory.heapUsed,
|
|
79
|
+
heapTotalBytes: memory.heapTotal,
|
|
80
|
+
externalBytes: memory.external,
|
|
81
|
+
cpuPercent: wallMs > 0 ? Math.max(0, cpuMs / wallMs * 100) : 0,
|
|
82
|
+
eventLoopDelayP50Ms: nsToMs(loopDelay.percentile(50)),
|
|
83
|
+
eventLoopDelayP99Ms: nsToMs(loopDelay.percentile(99)),
|
|
84
|
+
eventLoopDelayMaxMs: nsToMs(loopDelay.max),
|
|
85
|
+
eventLoopUtilization: active + idle > 0 ? active / (active + idle) : 0,
|
|
86
|
+
gcCount: gcCountSince,
|
|
87
|
+
gcPauseMs: gcPauseSince
|
|
88
|
+
};
|
|
89
|
+
loopDelay.reset();
|
|
90
|
+
lastAt = at;
|
|
91
|
+
lastCpu = cpu;
|
|
92
|
+
lastElu = elu;
|
|
93
|
+
gcCountSince = 0;
|
|
94
|
+
gcPauseSince = 0;
|
|
95
|
+
points.push(point);
|
|
96
|
+
if (points.length > historySize) points.splice(0, points.length - historySize);
|
|
97
|
+
return { ...point };
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
start() {
|
|
101
|
+
if (timer) return;
|
|
102
|
+
lastAt = sources.now();
|
|
103
|
+
lastCpu = sources.cpuUsage();
|
|
104
|
+
lastElu = sources.eventLoopUtilization();
|
|
105
|
+
loopDelay.enable();
|
|
106
|
+
stopGc = sources.observeGc((kind, durationMs) => {
|
|
107
|
+
gcCountSince++;
|
|
108
|
+
gcPauseSince += durationMs;
|
|
109
|
+
gcByKind[kind].count++;
|
|
110
|
+
gcByKind[kind].pauseMs += durationMs;
|
|
111
|
+
});
|
|
112
|
+
timer = setInterval(sample, intervalMs);
|
|
113
|
+
timer.unref();
|
|
114
|
+
},
|
|
115
|
+
stop() {
|
|
116
|
+
if (timer) clearInterval(timer);
|
|
117
|
+
timer = void 0;
|
|
118
|
+
stopGc?.();
|
|
119
|
+
stopGc = void 0;
|
|
120
|
+
loopDelay.disable();
|
|
121
|
+
},
|
|
122
|
+
sample,
|
|
123
|
+
snapshot() {
|
|
124
|
+
return {
|
|
125
|
+
...points[points.length - 1] ?? sample(),
|
|
126
|
+
heapLimitBytes: sources.heapLimit(),
|
|
127
|
+
uptimeSeconds: sources.uptime(),
|
|
128
|
+
gcByKind: structuredClone(gcByKind)
|
|
129
|
+
};
|
|
130
|
+
},
|
|
131
|
+
history() {
|
|
132
|
+
return points.map((point) => ({ ...point }));
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
//#endregion
|
|
138
|
+
export { createResourceMonitor };
|
|
139
|
+
//# sourceMappingURL=resources.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resources.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/insights/resources.ts"],"sourcesContent":["import {\n constants,\n monitorEventLoopDelay,\n performance,\n PerformanceObserver,\n} from \"node:perf_hooks\";\nimport v8 from \"node:v8\";\nimport type { DevtoolsResourcePoint, DevtoolsResourceSnapshot } from \"../contracts\";\nimport type { DevtoolsResourceMonitor } from \"./types\";\n\ntype GcKind = keyof DevtoolsResourceSnapshot[\"gcByKind\"];\n\n/** The readings a monitor takes; replaced by fakes in specs. */\nexport type DevtoolsResourceSources = {\n now(): number;\n memoryUsage(): { rss: number; heapUsed: number; heapTotal: number; external: number };\n /** Microseconds, as `process.cpuUsage()`. */\n cpuUsage(): { user: number; system: number };\n heapLimit(): number;\n uptime(): number;\n /** Nanoseconds, as a `perf_hooks` interval histogram. */\n eventLoopDelay(): {\n enable(): unknown;\n disable(): unknown;\n reset(): void;\n percentile(percentile: number): number;\n readonly max: number;\n };\n eventLoopUtilization(): { idle: number; active: number };\n /** Calls `onGc` for every collection; returns the function that stops observing. */\n observeGc(onGc: (kind: GcKind, durationMs: number) => void): () => void;\n};\n\nfunction gcKindName(kind: number | undefined): GcKind {\n if (kind === constants.NODE_PERFORMANCE_GC_MAJOR) return \"major\";\n if (kind === constants.NODE_PERFORMANCE_GC_INCREMENTAL) return \"incremental\";\n if (kind === constants.NODE_PERFORMANCE_GC_WEAKCB) return \"weakcb\";\n\n return \"minor\";\n}\n\nconst defaultSources: DevtoolsResourceSources = {\n now: () => Date.now(),\n memoryUsage: () => process.memoryUsage(),\n cpuUsage: () => process.cpuUsage(),\n heapLimit: () => v8.getHeapStatistics().heap_size_limit,\n uptime: () => process.uptime(),\n eventLoopDelay: () => monitorEventLoopDelay({ resolution: 20 }),\n eventLoopUtilization: () => performance.eventLoopUtilization(),\n observeGc(onGc) {\n const observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n const detail = (entry as unknown as { detail?: { kind?: number }; kind?: number }).detail;\n const kind = detail?.kind ?? (entry as unknown as { kind?: number }).kind;\n\n onGc(gcKindName(kind), entry.duration);\n }\n });\n\n observer.observe({ entryTypes: [\"gc\"] });\n\n return () => observer.disconnect();\n },\n};\n\n/** Nanoseconds to milliseconds; a histogram with no samples reports 0. */\nfunction nsToMs(value: number): number {\n return Number.isFinite(value) && value > 0 && value < 1e15 ? value / 1e6 : 0;\n}\n\n/** Resource sampling every `intervalMs` (default 5000), `historySize` points (default 120). */\nexport function createResourceMonitor(\n options: {\n intervalMs?: number;\n historySize?: number;\n sources?: Partial<DevtoolsResourceSources>;\n } = {},\n): DevtoolsResourceMonitor {\n const intervalMs = options.intervalMs ?? 5000;\n const historySize = Math.max(1, options.historySize ?? 120);\n const sources: DevtoolsResourceSources = { ...defaultSources, ...options.sources };\n\n const loopDelay = sources.eventLoopDelay();\n const points: DevtoolsResourcePoint[] = [];\n const gcByKind: DevtoolsResourceSnapshot[\"gcByKind\"] = {\n minor: { count: 0, pauseMs: 0 },\n major: { count: 0, pauseMs: 0 },\n incremental: { count: 0, pauseMs: 0 },\n weakcb: { count: 0, pauseMs: 0 },\n };\n let gcCountSince = 0;\n let gcPauseSince = 0;\n let lastAt = sources.now();\n let lastCpu = sources.cpuUsage();\n let lastElu = sources.eventLoopUtilization();\n let timer: ReturnType<typeof setInterval> | undefined;\n let stopGc: (() => void) | undefined;\n\n function sample(): DevtoolsResourcePoint {\n const at = sources.now();\n const memory = sources.memoryUsage();\n const cpu = sources.cpuUsage();\n const elu = sources.eventLoopUtilization();\n const wallMs = at - lastAt;\n const cpuMs = (cpu.user + cpu.system - lastCpu.user - lastCpu.system) / 1000;\n const active = elu.active - lastElu.active;\n const idle = elu.idle - lastElu.idle;\n\n const point: DevtoolsResourcePoint = {\n at,\n rssBytes: memory.rss,\n heapUsedBytes: memory.heapUsed,\n heapTotalBytes: memory.heapTotal,\n externalBytes: memory.external,\n cpuPercent: wallMs > 0 ? Math.max(0, (cpuMs / wallMs) * 100) : 0,\n eventLoopDelayP50Ms: nsToMs(loopDelay.percentile(50)),\n eventLoopDelayP99Ms: nsToMs(loopDelay.percentile(99)),\n eventLoopDelayMaxMs: nsToMs(loopDelay.max),\n eventLoopUtilization: active + idle > 0 ? active / (active + idle) : 0,\n gcCount: gcCountSince,\n gcPauseMs: gcPauseSince,\n };\n\n loopDelay.reset();\n lastAt = at;\n lastCpu = cpu;\n lastElu = elu;\n gcCountSince = 0;\n gcPauseSince = 0;\n\n points.push(point);\n\n if (points.length > historySize) points.splice(0, points.length - historySize);\n\n return { ...point };\n }\n\n return {\n start() {\n if (timer) return;\n\n lastAt = sources.now();\n lastCpu = sources.cpuUsage();\n lastElu = sources.eventLoopUtilization();\n loopDelay.enable();\n stopGc = sources.observeGc((kind, durationMs) => {\n gcCountSince++;\n gcPauseSince += durationMs;\n gcByKind[kind].count++;\n gcByKind[kind].pauseMs += durationMs;\n });\n timer = setInterval(sample, intervalMs);\n timer.unref();\n },\n\n stop() {\n if (timer) clearInterval(timer);\n\n timer = undefined;\n stopGc?.();\n stopGc = undefined;\n loopDelay.disable();\n },\n\n sample,\n\n snapshot() {\n const latest = points[points.length - 1] ?? sample();\n\n return {\n ...latest,\n heapLimitBytes: sources.heapLimit(),\n uptimeSeconds: sources.uptime(),\n gcByKind: structuredClone(gcByKind),\n };\n },\n\n history() {\n return points.map((point) => ({ ...point }));\n },\n };\n}\n"],"mappings":";;;;AAiCA,SAAS,WAAW,MAAkC;CACpD,IAAI,SAAS,UAAU,2BAA2B,OAAO;CACzD,IAAI,SAAS,UAAU,iCAAiC,OAAO;CAC/D,IAAI,SAAS,UAAU,4BAA4B,OAAO;CAE1D,OAAO;AACT;AAEA,MAAM,iBAA0C;CAC9C,WAAW,KAAK,IAAI;CACpB,mBAAmB,QAAQ,YAAY;CACvC,gBAAgB,QAAQ,SAAS;CACjC,iBAAi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AO,SAAS,MAAM,OAAO;IAIjD,gBAAgB,QAAQ,UAAU;IAClC,eAAe,QAAQ,OAAO;IAC9B,UAAU,gBAAgB,QAAQ;GACpC;EACF;EAEA,UAAU;GACR,OAAO,OAAO,KAAK,WAAW,EAAE,GAAG,MAAM,EAAE;EAC7C;CACF;AACF"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { capReportSize } from "./cap-report.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/devtools/src/production/insights/writer.ts
|
|
4
|
+
const HOUSEKEEPING_INTERVAL_MS = 6e5;
|
|
5
|
+
const REPORT_MAX_AGE_MS = 3e5;
|
|
6
|
+
const WARN_EVERY_MS = 6e4;
|
|
7
|
+
/**
|
|
8
|
+
* Writes the report every `production.reportIntervalMs`, and every 10
|
|
9
|
+
* minutes prunes: reports unseen for 5 minutes, samples older than
|
|
10
|
+
* `requestRetentionHours`, expired sessions and invites, audit entries older
|
|
11
|
+
* than `auditRetentionDays`. Timers are `unref`ed; a failed write is logged
|
|
12
|
+
* once per minute, never thrown.
|
|
13
|
+
*/
|
|
14
|
+
function startReportWriter(input) {
|
|
15
|
+
const { reporter, store, production, warn } = input;
|
|
16
|
+
let stopped = false;
|
|
17
|
+
let lastWarnAt = Number.NEGATIVE_INFINITY;
|
|
18
|
+
let pending = Promise.resolve();
|
|
19
|
+
function fail(what, error) {
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
if (!warn || now - lastWarnAt < WARN_EVERY_MS) return;
|
|
22
|
+
lastWarnAt = now;
|
|
23
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
24
|
+
warn(`Devtools could not ${what}: ${reason}. It will try again.`);
|
|
25
|
+
}
|
|
26
|
+
async function write() {
|
|
27
|
+
if (stopped) return;
|
|
28
|
+
try {
|
|
29
|
+
await store.reports.write(capReportSize(await reporter.snapshot()));
|
|
30
|
+
} catch (error) {
|
|
31
|
+
fail("write this instance's report to the database", error);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function housekeeping() {
|
|
35
|
+
if (stopped) return;
|
|
36
|
+
const now = Date.now();
|
|
37
|
+
const steps = [
|
|
38
|
+
["remove old instance reports", () => store.reports.prune(now - REPORT_MAX_AGE_MS)],
|
|
39
|
+
["remove old request samples", () => store.samples.prune(now - production.requestRetentionHours * 36e5)],
|
|
40
|
+
["remove expired sessions", () => store.sessions.removeExpired(now)],
|
|
41
|
+
["remove expired invites", () => store.invites.removeExpired(now)],
|
|
42
|
+
["remove old audit entries", () => store.audit.prune(now - production.auditRetentionDays * 864e5)]
|
|
43
|
+
];
|
|
44
|
+
for (const [what, step] of steps) try {
|
|
45
|
+
await step();
|
|
46
|
+
} catch (error) {
|
|
47
|
+
fail(what, error);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function enqueue(task) {
|
|
51
|
+
pending = pending.then(task);
|
|
52
|
+
return pending;
|
|
53
|
+
}
|
|
54
|
+
const writeTimer = setInterval(() => void enqueue(write), production.reportIntervalMs);
|
|
55
|
+
const housekeepingTimer = setInterval(() => void enqueue(housekeeping), HOUSEKEEPING_INTERVAL_MS);
|
|
56
|
+
writeTimer.unref();
|
|
57
|
+
housekeepingTimer.unref();
|
|
58
|
+
enqueue(write);
|
|
59
|
+
return {
|
|
60
|
+
writeNow: () => enqueue(write),
|
|
61
|
+
async stop() {
|
|
62
|
+
stopped = true;
|
|
63
|
+
clearInterval(writeTimer);
|
|
64
|
+
clearInterval(housekeepingTimer);
|
|
65
|
+
await pending;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
//#endregion
|
|
71
|
+
export { startReportWriter };
|
|
72
|
+
//# sourceMappingURL=writer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"writer.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/insights/writer.ts"],"sourcesContent":["import type { ResolvedDevtoolsProductionOptions } from \"../options\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport { capReportSize } from \"./cap-report\";\nimport type { DevtoolsLocalReporter, DevtoolsReportWriter } from \"./types\";\n\nconst HOUSEKEEPING_INTERVAL_MS = 10 * 60_000;\nconst REPORT_MAX_AGE_MS = 5 * 60_000;\nconst WARN_EVERY_MS = 60_000;\n\n/**\n * Writes the report every `production.reportIntervalMs`, and every 10\n * minutes prunes: reports unseen for 5 minutes, samples older than\n * `requestRetentionHours`, expired sessions and invites, audit entries older\n * than `auditRetentionDays`. Timers are `unref`ed; a failed write is logged\n * once per minute, never thrown.\n */\nexport function startReportWriter(input: {\n reporter: DevtoolsLocalReporter;\n store: DevtoolsStore;\n production: ResolvedDevtoolsProductionOptions;\n warn?: (message: string) => void;\n}): DevtoolsReportWriter {\n const { reporter, store, production, warn } = input;\n let stopped = false;\n let lastWarnAt = Number.NEGATIVE_INFINITY;\n let pending: Promise<void> = Promise.resolve();\n\n function fail(what: string, error: unknown): void {\n const now = Date.now();\n\n if (!warn || now - lastWarnAt < WARN_EVERY_MS) return;\n\n lastWarnAt = now;\n\n const reason = error instanceof Error ? error.message : String(error);\n\n warn(`Devtools could not ${what}: ${reason}. It will try again.`);\n }\n\n async function write(): Promise<void> {\n if (stopped) return;\n\n try {\n await store.reports.write(capReportSize(await reporter.snapshot()));\n } catch (error) {\n fail(\"write this instance's report to the database\", error);\n }\n }\n\n async function housekeeping(): Promise<void> {\n if (stopped) return;\n\n const now = Date.now();\n const steps: [string, () => Promise<unknown>][] = [\n [\"remove old instance reports\", () => store.reports.prune(now - REPORT_MAX_AGE_MS)],\n [\n \"remove old request samples\",\n () => store.samples.prune(now - production.requestRetentionHours * 3_600_000),\n ],\n [\"remove expired sessions\", () => store.sessions.removeExpired(now)],\n [\"remove expired invites\", () => store.invites.removeExpired(now)],\n [\n \"remove old audit entries\",\n () => store.audit.prune(now - production.auditRetentionDays * 86_400_000),\n ],\n ];\n\n for (const [what, step] of steps) {\n try {\n await step();\n } catch (error) {\n fail(what, error);\n }\n }\n }\n\n function enqueue(task: () => Promise<void>): Promise<void> {\n pending = pending.then(task);\n\n return pending;\n }\n\n const writeTimer = setInterval(() => void enqueue(write), production.reportIntervalMs);\n const housekeepingTimer = setInterval(() => void enqueue(housekeeping), HOUSEKEEPING_INTERVAL_MS);\n\n writeTimer.unref();\n housekeepingTimer.unref();\n void enqueue(write);\n\n return {\n writeNow: () => enqueue(write),\n\n async stop() {\n stopped = true;\n clearInterval(writeTimer);\n clearInterval(housekeepingTimer);\n await pending;\n },\n };\n}\n"],"mappings":";;;AAKA,MAAM,2BAA2B;AACjC,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;;;;;;;;AAStB,SAAgB,kBAAkB,OAKT;CACvB,MAAM,EAAE,UAAU,OAAO,YAAY,SAAS;CAC9C,IAAI,UAAU;CACd,IAAI,aAAa,OAAO;CACxB,IAAI,UAAyB,QAAQ,QAAQ;CAE7C,SAAS,KAAK,MAAc,OAAsB;EAChD,MAAM,MAAM,KAAK,IAAI;EAErB,IAAI,CAAC,QAAQ,MAAM,aAAa,eAAe;EAE/C,aAAa;EAEb,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAEpE,KAAK,sBAAsB,KAAK,IAAI,OAAO,qBAAqB;CAClE;CAEA,eAAe,QAAuB;EACpC,IAAI,SAAS;EAEb,IAAI;GACF,MAAM,MAAM,QAAQ,MAAM,cAAc,MAAM,SAAS,SAAS,CAAC,CAAC;EACpE,SAAS,OAAO;GACd,KAAK,gDAAgD,KAAK;EAC5D;CACF;CAEA,eAAe,eAA8B;EAC3C,IAAI,SAAS;EAEb,MAAM,MAAM,KAAK,IAAI;EACrB,MAAM,QAA4C;GAChD,CAAC,qCAAqC,MAAM,QAAQ,MAAM,MAAM,iBAAiB,CAAC;GAClF,CACE,oCACM,MAAM,QAAQ,MAAM,MAAM,WAAW,wBAAwB,IAAS,CAC9E;GACA,CAAC,iCAAiC,MAAM,SAAS,cAAc,GAAG,CAAC;GACnE,CAAC,gCAAgC,MAAM,QAAQ,cAAc,GAAG,CAAC;GACjE,CACE,kCACM,MAAM,MAAM,MAAM,MAAM,WAAW,qBAAqB,KAAU,CAC1E;EACF;EAEA,KAAK,MAAM,CAAC,MAAM,SAAS,OACzB,IAAI;GACF,MAAM,KAAK;EACb,SAAS,OAAO;GACd,KAAK,MAAM,KAAK;EAClB;CAEJ;CAEA,SAAS,QAAQ,MAA0C;EACzD,UAAU,QAAQ,KAAK,IAAI;EAE3B,OAAO;CACT;CAEA,MAAM,aAAa,kBAAkB,KAAK,QAAQ,KAAK,GAAG,WAAW,gBAAgB;CACrF,MAAM,oBAAoB,kBAAkB,KAAK,QAAQ,YAAY,GAAG,wBAAwB;CAEhG,WAAW,MAAM;CACjB,kBAAkB,MAAM;CACxB,AAAK,QAAQ,KAAK;CAElB,OAAO;EACL,gBAAgB,QAAQ,KAAK;EAE7B,MAAM,OAAO;GACX,UAAU;GACV,cAAc,UAAU;GACxB,cAAc,iBAAiB;GAC/B,MAAM;EACR;CACF;AACF"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/devtools/src/production/openapi.ts
|
|
4
|
+
/**
|
|
5
|
+
* The API tab's documents under `warlock start`. Only `warlock dev` registers
|
|
6
|
+
* core's development provider, so production builds the OpenAPI document
|
|
7
|
+
* itself from the routes this process registered, with core's own builder.
|
|
8
|
+
* Resource schemas keep generic names (`Resource1`, …) because production has
|
|
9
|
+
* no source files to read their export names from. Built once per process: the
|
|
10
|
+
* routes do not change after boot; a failed build is tried again next time.
|
|
11
|
+
*/
|
|
12
|
+
function createProductionOpenApi(core) {
|
|
13
|
+
let built;
|
|
14
|
+
const build = async () => {
|
|
15
|
+
const pkg = await readAppPackage(core.rootPath("package.json"));
|
|
16
|
+
const baseUrl = core.config.get("app.baseUrl");
|
|
17
|
+
const { document } = core.buildOpenApiDocument(core.router.list(), {
|
|
18
|
+
info: {
|
|
19
|
+
title: typeof pkg.name === "string" && pkg.name ? pkg.name : "Warlock API",
|
|
20
|
+
version: typeof pkg.version === "string" && pkg.version ? pkg.version : "0.0.0",
|
|
21
|
+
...typeof pkg.description === "string" && pkg.description ? { description: pkg.description } : {}
|
|
22
|
+
},
|
|
23
|
+
...typeof baseUrl === "string" && baseUrl ? { servers: [baseUrl] } : {},
|
|
24
|
+
validationResponse: core.config.get("validation.response", {})
|
|
25
|
+
});
|
|
26
|
+
return document;
|
|
27
|
+
};
|
|
28
|
+
const getOpenApiDocument = () => {
|
|
29
|
+
const current = built ?? build();
|
|
30
|
+
built = current;
|
|
31
|
+
current.catch(() => {
|
|
32
|
+
if (built === current) built = void 0;
|
|
33
|
+
});
|
|
34
|
+
return current;
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
getOpenApiDocument,
|
|
38
|
+
getPostmanCollection: async () => core.openApiToPostmanCollection(await getOpenApiDocument())
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
async function readAppPackage(file) {
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
44
|
+
return parsed !== null && typeof parsed === "object" ? parsed : {};
|
|
45
|
+
} catch {
|
|
46
|
+
return {};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
export { createProductionOpenApi };
|
|
52
|
+
//# sourceMappingURL=openapi.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openapi.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/openapi.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\n\ntype Core = typeof import(\"@warlock.js/core\");\n\n/**\n * The API tab's documents under `warlock start`. Only `warlock dev` registers\n * core's development provider, so production builds the OpenAPI document\n * itself from the routes this process registered, with core's own builder.\n * Resource schemas keep generic names (`Resource1`, …) because production has\n * no source files to read their export names from. Built once per process: the\n * routes do not change after boot; a failed build is tried again next time.\n */\nexport function createProductionOpenApi(\n core: Pick<\n Core,\n \"router\" | \"buildOpenApiDocument\" | \"openApiToPostmanCollection\" | \"config\" | \"rootPath\"\n >,\n): { getOpenApiDocument: () => Promise<object>; getPostmanCollection: () => Promise<object> } {\n let built: Promise<object> | undefined;\n\n const build = async (): Promise<object> => {\n const pkg = await readAppPackage(core.rootPath(\"package.json\"));\n const baseUrl: unknown = core.config.get(\"app.baseUrl\");\n const { document } = core.buildOpenApiDocument(core.router.list(), {\n info: {\n title: typeof pkg.name === \"string\" && pkg.name ? pkg.name : \"Warlock API\",\n version: typeof pkg.version === \"string\" && pkg.version ? pkg.version : \"0.0.0\",\n ...(typeof pkg.description === \"string\" && pkg.description\n ? { description: pkg.description }\n : {}),\n },\n ...(typeof baseUrl === \"string\" && baseUrl ? { servers: [baseUrl] } : {}),\n validationResponse: core.config.get(\"validation.response\", {}),\n });\n\n return document;\n };\n\n const getOpenApiDocument = (): Promise<object> => {\n const current = built ?? build();\n\n built = current;\n current.catch(() => {\n if (built === current) built = undefined;\n });\n\n return current;\n };\n\n return {\n getOpenApiDocument,\n getPostmanCollection: async () =>\n core.openApiToPostmanCollection(\n (await getOpenApiDocument()) as Parameters<Core[\"openApiToPostmanCollection\"]>[0],\n ),\n };\n}\n\nasync function readAppPackage(file: string): Promise<Record<string, unknown>> {\n try {\n const parsed: unknown = JSON.parse(await readFile(file, \"utf8\"));\n\n return parsed !== null && typeof parsed === \"object\" ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAgB,wBACd,MAI4F;CAC5F,IAAI;CAEJ,MAAM,QAAQ,YAA6B;EACzC,MAAM,MAAM,MAAM,eAAe,KAAK,SAAS,cAAc,CAAC;EAC9D,MAAM,UAAmB,KAAK,OAAO,IAAI,aAAa;EACtD,MAAM,EAAE,aAAa,KAAK,qBAAqB,KAAK,OAAO,KAAK,GAAG;GACjE,MAAM;IACJ,OAAO,OAAO,IAAI,SAAS,YAAY,IAAI,OAAO,IAAI,OAAO;IAC7D,SAAS,OAAO,IAAI,YAAY,YAAY,IAAI,UAAU,IAAI,UAAU;IACxE,GAAI,OAAO,IAAI,gBAAgB,YAAY,IAAI,cAC3C,EAAE,aAAa,IAAI,YAAY,IAC/B,CAAC;GACP;GACA,GAAI,OAAO,YAAY,YAAY,UAAU,EAAE,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC;GACvE,oBAAoB,KAAK,OAAO,IAAI,uBAAuB,CAAC,CAAC;EAC/D,CAAC;EAED,OAAO;CACT;CAEA,MAAM,2BAA4C;EAChD,MAAM,UAAU,SAAS,MAAM;EAE/B,QAAQ;EACR,QAAQ,YAAY;GAClB,IAAI,UAAU,SAAS,QAAQ;EACjC,CAAC;EAED,OAAO;CACT;CAEA,OAAO;EACL;EACA,sBAAsB,YACpB,KAAK,2BACF,MAAM,mBAAmB,CAC5B;CACJ;AACF;AAEA,eAAe,eAAe,MAAgD;CAC5E,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,MAAM,SAAS,MAAM,MAAM,CAAC;EAE/D,OAAO,WAAW,QAAQ,OAAO,WAAW,WAAY,SAAqC,CAAC;CAChG,QAAQ;EACN,OAAO,CAAC;CACV;AACF"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { DevtoolsLogEntry } from "../types.mjs";
|
|
2
|
+
//#region ../../packages/devtools/src/production/options.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* `DevtoolsProductionOptions` with every default applied and the environment
|
|
5
|
+
* read. Built once at boot by `resolveProductionOptions`.
|
|
6
|
+
*/
|
|
7
|
+
export type ResolvedDevtoolsProductionOptions = {
|
|
8
|
+
/** The dashboard path, without a trailing slash. */
|
|
9
|
+
path: string;
|
|
10
|
+
/** The first admin from the environment; every field `null` when unset. */
|
|
11
|
+
admin: {
|
|
12
|
+
email: string | null;
|
|
13
|
+
password: string | null;
|
|
14
|
+
setupToken: string | null;
|
|
15
|
+
};
|
|
16
|
+
sampleRate: number;
|
|
17
|
+
slowRequestMs: number;
|
|
18
|
+
slowQueryMs: number;
|
|
19
|
+
maxRequests: number;
|
|
20
|
+
/** Queries kept per sampled request; the rest are counted in `droppedQueries`. */
|
|
21
|
+
maxQueriesPerRequest: number;
|
|
22
|
+
/** Query shapes kept in memory per process (least recently seen evicted). */
|
|
23
|
+
maxShapes: number;
|
|
24
|
+
/** Route keys kept in memory per process. */
|
|
25
|
+
maxRoutes: number;
|
|
26
|
+
/** Error groups kept in memory per process. */
|
|
27
|
+
maxErrorGroups: number;
|
|
28
|
+
requestRetentionHours: number;
|
|
29
|
+
maxStoredSamplesPerMinute: number;
|
|
30
|
+
reportIntervalMs: number;
|
|
31
|
+
trustedProxies: readonly string[];
|
|
32
|
+
requireHttps: boolean;
|
|
33
|
+
allowedIps: readonly string[];
|
|
34
|
+
origin: string | null;
|
|
35
|
+
session: {
|
|
36
|
+
idleMinutes: number;
|
|
37
|
+
maxHours: number;
|
|
38
|
+
pendingMinutes: number;
|
|
39
|
+
};
|
|
40
|
+
twoFactor: "admins" | "everyone";
|
|
41
|
+
rateLimits: {
|
|
42
|
+
windowMinutes: number;
|
|
43
|
+
account: number;
|
|
44
|
+
ip: number;
|
|
45
|
+
global: number;
|
|
46
|
+
lockMinutes: number;
|
|
47
|
+
};
|
|
48
|
+
explain: {
|
|
49
|
+
executing: boolean;
|
|
50
|
+
};
|
|
51
|
+
panels: Readonly<Record<string, boolean>>;
|
|
52
|
+
logLevels: readonly DevtoolsLogEntry["level"][];
|
|
53
|
+
auditRetentionDays: number;
|
|
54
|
+
passkeys: {
|
|
55
|
+
rpName: string;
|
|
56
|
+
rpId: string | null;
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
//#endregion
|
|
60
|
+
//# sourceMappingURL=options.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.d.mts","names":[],"sources":["../../../../../../../../packages/devtools/src/production/options.ts"],"mappings":";;;;;;YAQY;;EAEV;;EAEA;IAAS;IAAsB;IAAyB;;EACxD;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IAAW;IAAqB;IAAkB;;EAClD;EACA;IACE;IACA;IACA;IACA;IACA;;EAEF;IAAW;;EACX,QAAQ,SAAS;EACjB,oBAAoB;EACpB;EACA;IAAY;IAAgB"}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { DevtoolsProductionConfigError } from "./errors.mjs";
|
|
2
|
+
import { isValidNetworkEntry } from "./http/ip.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/devtools/src/production/options.ts
|
|
5
|
+
/** The defaults `resolveProductionOptions` applies (environment values excluded). */
|
|
6
|
+
const DEVTOOLS_PRODUCTION_DEFAULTS = {
|
|
7
|
+
sampleRate: .1,
|
|
8
|
+
slowRequestMs: 1e3,
|
|
9
|
+
slowQueryMs: 200,
|
|
10
|
+
maxRequests: 200,
|
|
11
|
+
maxQueriesPerRequest: 200,
|
|
12
|
+
maxShapes: 500,
|
|
13
|
+
maxRoutes: 300,
|
|
14
|
+
maxErrorGroups: 100,
|
|
15
|
+
requestRetentionHours: 24,
|
|
16
|
+
maxStoredSamplesPerMinute: 120,
|
|
17
|
+
reportIntervalMs: 1e4,
|
|
18
|
+
requireHttps: true,
|
|
19
|
+
session: {
|
|
20
|
+
idleMinutes: 30,
|
|
21
|
+
maxHours: 8,
|
|
22
|
+
pendingMinutes: 10
|
|
23
|
+
},
|
|
24
|
+
twoFactor: "admins",
|
|
25
|
+
rateLimits: {
|
|
26
|
+
windowMinutes: 15,
|
|
27
|
+
account: 5,
|
|
28
|
+
ip: 20,
|
|
29
|
+
global: 100,
|
|
30
|
+
lockMinutes: 15
|
|
31
|
+
},
|
|
32
|
+
explain: { executing: false },
|
|
33
|
+
logLevels: ["warn", "error"],
|
|
34
|
+
auditRetentionDays: 90,
|
|
35
|
+
passkeys: { rpName: "Warlock monitor" }
|
|
36
|
+
};
|
|
37
|
+
/** The environment variables production mode reads. */
|
|
38
|
+
const DEVTOOLS_ENV = {
|
|
39
|
+
path: "DEVTOOLS_PATH",
|
|
40
|
+
adminEmail: "DEVTOOLS_ADMIN_EMAIL",
|
|
41
|
+
adminPassword: "DEVTOOLS_ADMIN_PASSWORD",
|
|
42
|
+
setupToken: "DEVTOOLS_SETUP_TOKEN"
|
|
43
|
+
};
|
|
44
|
+
const LOG_LEVELS = [
|
|
45
|
+
"debug",
|
|
46
|
+
"info",
|
|
47
|
+
"warn",
|
|
48
|
+
"error",
|
|
49
|
+
"success"
|
|
50
|
+
];
|
|
51
|
+
const PATH_CHARACTERS = /^[A-Za-z0-9._~/-]+$/;
|
|
52
|
+
const MIN_PATH_LENGTH = 8;
|
|
53
|
+
const MIN_SETUP_TOKEN_LENGTH = 32;
|
|
54
|
+
function invalid(option, expected) {
|
|
55
|
+
throw new DevtoolsProductionConfigError("DT007", `Option "devtools.production.${option}" is not valid: ${expected}.`);
|
|
56
|
+
}
|
|
57
|
+
function present(value) {
|
|
58
|
+
return value === void 0 || value === "" ? null : value;
|
|
59
|
+
}
|
|
60
|
+
function integerAtLeastOne(option, value, fallback) {
|
|
61
|
+
if (value === void 0) return fallback;
|
|
62
|
+
if (!Number.isInteger(value) || value < 1) invalid(option, "use a whole number of 1 or more");
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
function networkList(option, value) {
|
|
66
|
+
if (value === void 0) return [];
|
|
67
|
+
if (!Array.isArray(value)) invalid(option, "use a list of IPs, CIDR ranges, \"loopback\" or \"private\"");
|
|
68
|
+
for (const entry of value) if (!isValidNetworkEntry(entry)) invalid(option, `"${String(entry)}" is not an IP, a CIDR range, "loopback" or "private"`);
|
|
69
|
+
return [...value];
|
|
70
|
+
}
|
|
71
|
+
/** The dashboard path without a trailing slash, or a DT001/DT002 error. */
|
|
72
|
+
function resolvePath(value) {
|
|
73
|
+
const given = present(value);
|
|
74
|
+
if (given === null) throw new DevtoolsProductionConfigError("DT001");
|
|
75
|
+
const path = given.replace(/\/+$/, "");
|
|
76
|
+
const segments = path.split("/").slice(1);
|
|
77
|
+
const lower = path.toLowerCase();
|
|
78
|
+
if (!path.startsWith("/") || path.length < MIN_PATH_LENGTH || !PATH_CHARACTERS.test(path) || segments.some((segment) => segment === "" || segment === "." || segment === "..") || lower === "/__warlock" || lower.startsWith("/__warlock/")) throw new DevtoolsProductionConfigError("DT002");
|
|
79
|
+
return path;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Applies the defaults to `options`, reads the path and first admin from
|
|
83
|
+
* `env`, and validates everything.
|
|
84
|
+
*
|
|
85
|
+
* Throws `DevtoolsProductionConfigError`: DT001 (no path), DT002 (bad path),
|
|
86
|
+
* DT007 (an option out of range: sampleRate outside 0–1, a non-positive
|
|
87
|
+
* limit, an unknown twoFactor value, a bad CIDR, an origin that is not
|
|
88
|
+
* `https://host[:port]`), DT009 (both a password and a setup token), DT010
|
|
89
|
+
* (setup token shorter than 32 characters). DT003/DT004 (admin) are checked
|
|
90
|
+
* later by `ensureFirstAdmin`, which needs the database.
|
|
91
|
+
*/
|
|
92
|
+
function resolveProductionOptions(options, env) {
|
|
93
|
+
const given = options ?? {};
|
|
94
|
+
const defaults = DEVTOOLS_PRODUCTION_DEFAULTS;
|
|
95
|
+
const path = resolvePath(given.path ?? env[DEVTOOLS_ENV.path]);
|
|
96
|
+
const sampleRate = given.sampleRate ?? defaults.sampleRate;
|
|
97
|
+
if (typeof sampleRate !== "number" || !Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) invalid("sampleRate", "use a number from 0 to 1");
|
|
98
|
+
const requireHttps = given.requireHttps ?? defaults.requireHttps;
|
|
99
|
+
if (typeof requireHttps !== "boolean") invalid("requireHttps", "use true or false");
|
|
100
|
+
const twoFactor = given.twoFactor ?? defaults.twoFactor;
|
|
101
|
+
if (twoFactor !== "admins" && twoFactor !== "everyone") invalid("twoFactor", "use \"admins\" or \"everyone\"");
|
|
102
|
+
const origin = given.origin ?? null;
|
|
103
|
+
if (origin !== null) {
|
|
104
|
+
if (typeof origin !== "string" || !(requireHttps ? /^https:\/\/[^/\s]+$/ : /^https?:\/\/[^/\s]+$/).test(origin)) invalid("origin", requireHttps ? "use an origin such as https://app.example.com, without a path or a trailing slash" : "use an origin such as http://localhost:3000, without a path or a trailing slash");
|
|
105
|
+
}
|
|
106
|
+
const panels = given.panels ?? {};
|
|
107
|
+
if (panels === null || typeof panels !== "object" || Array.isArray(panels)) invalid("panels", "use an object of tab ids and true or false");
|
|
108
|
+
for (const [id, enabled] of Object.entries(panels)) if (typeof enabled !== "boolean") invalid(`panels.${id}`, "use true or false");
|
|
109
|
+
const logLevels = given.logLevels ?? defaults.logLevels;
|
|
110
|
+
if (!Array.isArray(logLevels) || logLevels.some((level) => !LOG_LEVELS.includes(level))) invalid("logLevels", `use a list of ${LOG_LEVELS.join(", ")}`);
|
|
111
|
+
const executing = given.explain?.executing ?? defaults.explain.executing;
|
|
112
|
+
if (typeof executing !== "boolean") invalid("explain.executing", "use true or false");
|
|
113
|
+
const rpName = given.passkeys?.rpName ?? defaults.passkeys.rpName;
|
|
114
|
+
const rpId = given.passkeys?.rpId ?? null;
|
|
115
|
+
if (typeof rpName !== "string" || rpName.trim() === "") invalid("passkeys.rpName", "use a non-empty name");
|
|
116
|
+
if (rpId !== null && (typeof rpId !== "string" || rpId.trim() === "")) invalid("passkeys.rpId", "use a host name such as app.example.com");
|
|
117
|
+
const limits = given.rateLimits ?? {};
|
|
118
|
+
const session = given.session ?? {};
|
|
119
|
+
const resolved = {
|
|
120
|
+
path,
|
|
121
|
+
admin: {
|
|
122
|
+
email: present(env[DEVTOOLS_ENV.adminEmail]),
|
|
123
|
+
password: present(env[DEVTOOLS_ENV.adminPassword]),
|
|
124
|
+
setupToken: present(env[DEVTOOLS_ENV.setupToken])
|
|
125
|
+
},
|
|
126
|
+
sampleRate,
|
|
127
|
+
slowRequestMs: integerAtLeastOne("slowRequestMs", given.slowRequestMs, defaults.slowRequestMs),
|
|
128
|
+
slowQueryMs: integerAtLeastOne("slowQueryMs", given.slowQueryMs, defaults.slowQueryMs),
|
|
129
|
+
maxRequests: integerAtLeastOne("maxRequests", given.maxRequests, defaults.maxRequests),
|
|
130
|
+
maxQueriesPerRequest: defaults.maxQueriesPerRequest,
|
|
131
|
+
maxShapes: defaults.maxShapes,
|
|
132
|
+
maxRoutes: defaults.maxRoutes,
|
|
133
|
+
maxErrorGroups: defaults.maxErrorGroups,
|
|
134
|
+
requestRetentionHours: integerAtLeastOne("requestRetentionHours", given.requestRetentionHours, defaults.requestRetentionHours),
|
|
135
|
+
maxStoredSamplesPerMinute: integerAtLeastOne("maxStoredSamplesPerMinute", given.maxStoredSamplesPerMinute, defaults.maxStoredSamplesPerMinute),
|
|
136
|
+
reportIntervalMs: integerAtLeastOne("reportIntervalMs", given.reportIntervalMs, defaults.reportIntervalMs),
|
|
137
|
+
trustedProxies: networkList("trustedProxies", given.trustedProxies),
|
|
138
|
+
requireHttps,
|
|
139
|
+
allowedIps: networkList("allowedIps", given.allowedIps),
|
|
140
|
+
origin,
|
|
141
|
+
session: {
|
|
142
|
+
idleMinutes: integerAtLeastOne("session.idleMinutes", session.idleMinutes, defaults.session.idleMinutes),
|
|
143
|
+
maxHours: integerAtLeastOne("session.maxHours", session.maxHours, defaults.session.maxHours),
|
|
144
|
+
pendingMinutes: defaults.session.pendingMinutes
|
|
145
|
+
},
|
|
146
|
+
twoFactor,
|
|
147
|
+
rateLimits: {
|
|
148
|
+
windowMinutes: integerAtLeastOne("rateLimits.windowMinutes", limits.windowMinutes, defaults.rateLimits.windowMinutes),
|
|
149
|
+
account: integerAtLeastOne("rateLimits.account", limits.account, defaults.rateLimits.account),
|
|
150
|
+
ip: integerAtLeastOne("rateLimits.ip", limits.ip, defaults.rateLimits.ip),
|
|
151
|
+
global: integerAtLeastOne("rateLimits.global", limits.global, defaults.rateLimits.global),
|
|
152
|
+
lockMinutes: integerAtLeastOne("rateLimits.lockMinutes", limits.lockMinutes, defaults.rateLimits.lockMinutes)
|
|
153
|
+
},
|
|
154
|
+
explain: { executing },
|
|
155
|
+
panels: { ...panels },
|
|
156
|
+
logLevels: [...logLevels],
|
|
157
|
+
auditRetentionDays: integerAtLeastOne("auditRetentionDays", given.auditRetentionDays, defaults.auditRetentionDays),
|
|
158
|
+
passkeys: {
|
|
159
|
+
rpName,
|
|
160
|
+
rpId
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
if (resolved.admin.password !== null && resolved.admin.setupToken !== null) throw new DevtoolsProductionConfigError("DT009");
|
|
164
|
+
if (resolved.admin.setupToken !== null && resolved.admin.setupToken.length < MIN_SETUP_TOKEN_LENGTH) throw new DevtoolsProductionConfigError("DT010");
|
|
165
|
+
return resolved;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
//#endregion
|
|
169
|
+
export { DEVTOOLS_ENV, DEVTOOLS_PRODUCTION_DEFAULTS, resolveProductionOptions };
|
|
170
|
+
//# sourceMappingURL=options.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options.mjs","names":[],"sources":["../../../../../../../../packages/devtools/src/production/options.ts"],"sourcesContent":["import type { DevtoolsLogEntry, DevtoolsProductionOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport { isValidNetworkEntry } from \"./http/ip\";\n\n/**\n * `DevtoolsProductionOptions` with every default applied and the environment\n * read. Built once at boot by `resolveProductionOptions`.\n */\nexport type ResolvedDevtoolsProductionOptions = {\n /** The dashboard path, without a trailing slash. */\n path: string;\n /** The first admin from the environment; every field `null` when unset. */\n admin: { email: string | null; password: string | null; setupToken: string | null };\n sampleRate: number;\n slowRequestMs: number;\n slowQueryMs: number;\n maxRequests: number;\n /** Queries kept per sampled request; the rest are counted in `droppedQueries`. */\n maxQueriesPerRequest: number;\n /** Query shapes kept in memory per process (least recently seen evicted). */\n maxShapes: number;\n /** Route keys kept in memory per process. */\n maxRoutes: number;\n /** Error groups kept in memory per process. */\n maxErrorGroups: number;\n requestRetentionHours: number;\n maxStoredSamplesPerMinute: number;\n reportIntervalMs: number;\n trustedProxies: readonly string[];\n requireHttps: boolean;\n allowedIps: readonly string[];\n origin: string | null;\n session: { idleMinutes: number; maxHours: number; pendingMinutes: number };\n twoFactor: \"admins\" | \"everyone\";\n rateLimits: {\n windowMinutes: number;\n account: number;\n ip: number;\n global: number;\n lockMinutes: number;\n };\n explain: { executing: boolean };\n panels: Readonly<Record<string, boolean>>;\n logLevels: readonly DevtoolsLogEntry[\"level\"][];\n auditRetentionDays: number;\n passkeys: { rpName: string; rpId: string | null };\n};\n\n/** The defaults `resolveProductionOptions` applies (environment values excluded). */\nexport const DEVTOOLS_PRODUCTION_DEFAULTS = {\n sampleRate: 0.1,\n slowRequestMs: 1000,\n slowQueryMs: 200,\n maxRequests: 200,\n maxQueriesPerRequest: 200,\n maxShapes: 500,\n maxRoutes: 300,\n maxErrorGroups: 100,\n requestRetentionHours: 24,\n maxStoredSamplesPerMinute: 120,\n reportIntervalMs: 10_000,\n requireHttps: true,\n session: { idleMinutes: 30, maxHours: 8, pendingMinutes: 10 },\n twoFactor: \"admins\",\n rateLimits: { windowMinutes: 15, account: 5, ip: 20, global: 100, lockMinutes: 15 },\n explain: { executing: false },\n logLevels: [\"warn\", \"error\"],\n auditRetentionDays: 90,\n passkeys: { rpName: \"Warlock monitor\" },\n} as const;\n\n/** The environment variables production mode reads. */\nexport const DEVTOOLS_ENV = {\n path: \"DEVTOOLS_PATH\",\n adminEmail: \"DEVTOOLS_ADMIN_EMAIL\",\n adminPassword: \"DEVTOOLS_ADMIN_PASSWORD\",\n setupToken: \"DEVTOOLS_SETUP_TOKEN\",\n} as const;\n\nconst LOG_LEVELS: readonly DevtoolsLogEntry[\"level\"][] = [\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n \"success\",\n];\n\nconst PATH_CHARACTERS = /^[A-Za-z0-9._~/-]+$/;\nconst MIN_PATH_LENGTH = 8;\nconst MIN_SETUP_TOKEN_LENGTH = 32;\n\nfunction invalid(option: string, expected: string): never {\n throw new DevtoolsProductionConfigError(\n \"DT007\",\n `Option \"devtools.production.${option}\" is not valid: ${expected}.`,\n );\n}\n\nfunction present(value: string | undefined): string | null {\n return value === undefined || value === \"\" ? null : value;\n}\n\nfunction integerAtLeastOne(option: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n\n if (!Number.isInteger(value) || value < 1) invalid(option, \"use a whole number of 1 or more\");\n\n return value;\n}\n\nfunction networkList(option: string, value: readonly string[] | undefined): readonly string[] {\n if (value === undefined) return [];\n\n if (!Array.isArray(value)) {\n invalid(option, 'use a list of IPs, CIDR ranges, \"loopback\" or \"private\"');\n }\n\n for (const entry of value as readonly unknown[]) {\n if (!isValidNetworkEntry(entry)) {\n invalid(option, `\"${String(entry)}\" is not an IP, a CIDR range, \"loopback\" or \"private\"`);\n }\n }\n\n return [...value];\n}\n\n/** The dashboard path without a trailing slash, or a DT001/DT002 error. */\nfunction resolvePath(value: string | undefined): string {\n const given = present(value);\n\n if (given === null) throw new DevtoolsProductionConfigError(\"DT001\");\n\n const path = given.replace(/\\/+$/, \"\");\n const segments = path.split(\"/\").slice(1);\n const lower = path.toLowerCase();\n\n if (\n !path.startsWith(\"/\") ||\n path.length < MIN_PATH_LENGTH ||\n !PATH_CHARACTERS.test(path) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\") ||\n lower === \"/__warlock\" ||\n lower.startsWith(\"/__warlock/\")\n ) {\n throw new DevtoolsProductionConfigError(\"DT002\");\n }\n\n return path;\n}\n\n/**\n * Applies the defaults to `options`, reads the path and first admin from\n * `env`, and validates everything.\n *\n * Throws `DevtoolsProductionConfigError`: DT001 (no path), DT002 (bad path),\n * DT007 (an option out of range: sampleRate outside 0–1, a non-positive\n * limit, an unknown twoFactor value, a bad CIDR, an origin that is not\n * `https://host[:port]`), DT009 (both a password and a setup token), DT010\n * (setup token shorter than 32 characters). DT003/DT004 (admin) are checked\n * later by `ensureFirstAdmin`, which needs the database.\n */\nexport function resolveProductionOptions(\n options: DevtoolsProductionOptions | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): ResolvedDevtoolsProductionOptions {\n const given = options ?? {};\n const defaults = DEVTOOLS_PRODUCTION_DEFAULTS;\n const path = resolvePath(given.path ?? env[DEVTOOLS_ENV.path]);\n\n const sampleRate = given.sampleRate ?? defaults.sampleRate;\n\n if (\n typeof sampleRate !== \"number\" ||\n !Number.isFinite(sampleRate) ||\n sampleRate < 0 ||\n sampleRate > 1\n ) {\n invalid(\"sampleRate\", \"use a number from 0 to 1\");\n }\n\n const requireHttps: boolean = given.requireHttps ?? defaults.requireHttps;\n\n if (typeof requireHttps !== \"boolean\") invalid(\"requireHttps\", \"use true or false\");\n\n const twoFactor = given.twoFactor ?? defaults.twoFactor;\n\n if (twoFactor !== \"admins\" && twoFactor !== \"everyone\") {\n invalid(\"twoFactor\", 'use \"admins\" or \"everyone\"');\n }\n\n const origin = given.origin ?? null;\n\n if (origin !== null) {\n const pattern = requireHttps ? /^https:\\/\\/[^/\\s]+$/ : /^https?:\\/\\/[^/\\s]+$/;\n\n if (typeof origin !== \"string\" || !pattern.test(origin)) {\n invalid(\n \"origin\",\n requireHttps\n ? \"use an origin such as https://app.example.com, without a path or a trailing slash\"\n : \"use an origin such as http://localhost:3000, without a path or a trailing slash\",\n );\n }\n }\n\n const panels: Readonly<Record<string, unknown>> = given.panels ?? {};\n\n if (panels === null || typeof panels !== \"object\" || Array.isArray(panels)) {\n invalid(\"panels\", \"use an object of tab ids and true or false\");\n }\n\n for (const [id, enabled] of Object.entries(panels)) {\n if (typeof enabled !== \"boolean\") invalid(`panels.${id}`, \"use true or false\");\n }\n\n const logLevels = given.logLevels ?? defaults.logLevels;\n\n if (!Array.isArray(logLevels) || logLevels.some((level) => !LOG_LEVELS.includes(level))) {\n invalid(\"logLevels\", `use a list of ${LOG_LEVELS.join(\", \")}`);\n }\n\n const executing: boolean = given.explain?.executing ?? defaults.explain.executing;\n\n if (typeof executing !== \"boolean\") invalid(\"explain.executing\", \"use true or false\");\n\n const rpName: string = given.passkeys?.rpName ?? defaults.passkeys.rpName;\n const rpId = given.passkeys?.rpId ?? null;\n\n if (typeof rpName !== \"string\" || rpName.trim() === \"\") {\n invalid(\"passkeys.rpName\", \"use a non-empty name\");\n }\n\n if (rpId !== null && (typeof rpId !== \"string\" || rpId.trim() === \"\")) {\n invalid(\"passkeys.rpId\", \"use a host name such as app.example.com\");\n }\n\n const limits = given.rateLimits ?? {};\n const session = given.session ?? {};\n\n const resolved: ResolvedDevtoolsProductionOptions = {\n path,\n admin: {\n email: present(env[DEVTOOLS_ENV.adminEmail]),\n password: present(env[DEVTOOLS_ENV.adminPassword]),\n setupToken: present(env[DEVTOOLS_ENV.setupToken]),\n },\n sampleRate,\n slowRequestMs: integerAtLeastOne(\"slowRequestMs\", given.slowRequestMs, defaults.slowRequestMs),\n slowQueryMs: integerAtLeastOne(\"slowQueryMs\", given.slowQueryMs, defaults.slowQueryMs),\n maxRequests: integerAtLeastOne(\"maxRequests\", given.maxRequests, defaults.maxRequests),\n maxQueriesPerRequest: defaults.maxQueriesPerRequest,\n maxShapes: defaults.maxShapes,\n maxRoutes: defaults.maxRoutes,\n maxErrorGroups: defaults.maxErrorGroups,\n requestRetentionHours: integerAtLeastOne(\n \"requestRetentionHours\",\n given.requestRetentionHours,\n defaults.requestRetentionHours,\n ),\n maxStoredSamplesPerMinute: integerAtLeastOne(\n \"maxStoredSamplesPerMinute\",\n given.maxStoredSamplesPerMinute,\n defaults.maxStoredSamplesPerMinute,\n ),\n reportIntervalMs: integerAtLeastOne(\n \"reportIntervalMs\",\n given.reportIntervalMs,\n defaults.reportIntervalMs,\n ),\n trustedProxies: networkList(\"trustedProxies\", given.trustedProxies),\n requireHttps,\n allowedIps: networkList(\"allowedIps\", given.allowedIps),\n origin,\n session: {\n idleMinutes: integerAtLeastOne(\n \"session.idleMinutes\",\n session.idleMinutes,\n defaults.session.idleMinutes,\n ),\n maxHours: integerAtLeastOne(\"session.maxHours\", session.maxHours, defaults.session.maxHours),\n pendingMinutes: defaults.session.pendingMinutes,\n },\n twoFactor,\n rateLimits: {\n windowMinutes: integerAtLeastOne(\n \"rateLimits.windowMinutes\",\n limits.windowMinutes,\n defaults.rateLimits.windowMinutes,\n ),\n account: integerAtLeastOne(\"rateLimits.account\", limits.account, defaults.rateLimits.account),\n ip: integerAtLeastOne(\"rateLimits.ip\", limits.ip, defaults.rateLimits.ip),\n global: integerAtLeastOne(\"rateLimits.global\", limits.global, defaults.rateLimits.global),\n lockMinutes: integerAtLeastOne(\n \"rateLimits.lockMinutes\",\n limits.lockMinutes,\n defaults.rateLimits.lockMinutes,\n ),\n },\n explain: { executing },\n panels: { ...(panels as Readonly<Record<string, boolean>>) },\n logLevels: [...logLevels],\n auditRetentionDays: integerAtLeastOne(\n \"auditRetentionDays\",\n given.auditRetentionDays,\n defaults.auditRetentionDays,\n ),\n passkeys: { rpName, rpId },\n };\n\n if (resolved.admin.password !== null && resolved.admin.setupToken !== null) {\n throw new DevtoolsProductionConfigError(\"DT009\");\n }\n\n if (\n resolved.admin.setupToken !== null &&\n resolved.admin.setupToken.length < MIN_SETUP_TOKEN_LENGTH\n ) {\n throw new DevtoolsProductionConfigError(\"DT010\");\n }\n\n return resolved;\n}\n"],"mappings":";;;;;AAiDA,MAAa,+BAA+B;CAC1C,YAAY;CACZ,eAAe;CACf,aAAa;CACb,aAAa;CACb,sBAAsB;CACtB,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,uBAAuB;CACvB,2BAA2B;CAC3B,kBAAkB;CAClB,cAAc;CACd,SAAS;EAAE,aAAa;EAAI,UAAU;EAAG,gBAAgB;CAAG;CAC5D,WAAW;CACX,YAAY;EAAE,eAAe;EAAI,SAAS;EAAG,IAAI;EAAI,QAAQ;EAAK,aAAa;CAAG;CAClF,SAAS,EAAE,WAAW,MAAM;CAC5B,WAAW,CA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ACV,eAAe,kBACb,4BACA,OAAO,eACP,SAAS,WAAW,aACtB;GACA,SAAS,kBAAkB,sBAAsB,OAAO,SAAS,SAAS,WAAW,OAAO;GAC5F,IAAI,kBAAkB,iBAAiB,OAAO,IAAI,SAAS,WAAW,EAAE;GACxE,QAAQ,kBAAkB,qBAAqB,OAAO,QAAQ,SAAS,WAAW,MAAM;GACxF,aAAa,kBACX,0BACA,OAAO,aACP,SAAS,WAAW,WACtB;EACF;EACA,SAAS,EAAE,UAAU;EACrB,QAAQ,EAAE,GAAI,OAA6C;EAC3D,WAAW,CAAC,GAAG,SAAS;EACxB,oBAAoB,kBAClB,sBACA,MAAM,oBACN,SAAS,kBACX;EACA,UAAU;GAAE;GAAQ;EAAK;CAC3B;CAEA,IAAI,SAAS,MAAM,aAAa,QAAQ,SAAS,MAAM,eAAe,MACpE,MAAM,IAAI,8BAA8B,OAAO;CAGjD,IACE,SAAS,MAAM,eAAe,QAC9B,SAAS,MAAM,WAAW,SAAS,wBAEnC,MAAM,IAAI,8BAA8B,OAAO;CAGjD,OAAO;AACT"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { DEVTOOLS_LATENCY_BUCKETS_MS } from "../contracts.mjs";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/devtools/src/production/stats/histogram.ts
|
|
5
|
+
/** An empty histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */
|
|
6
|
+
function createHistogram() {
|
|
7
|
+
return {
|
|
8
|
+
counts: new Array(DEVTOOLS_LATENCY_BUCKETS_MS.length + 1).fill(0),
|
|
9
|
+
count: 0,
|
|
10
|
+
sumMs: 0,
|
|
11
|
+
maxMs: 0
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** The bucket index a duration falls in. */
|
|
15
|
+
function bucketIndex(durationMs) {
|
|
16
|
+
for (let index = 0; index < DEVTOOLS_LATENCY_BUCKETS_MS.length; index++) if (durationMs <= DEVTOOLS_LATENCY_BUCKETS_MS[index]) return index;
|
|
17
|
+
return DEVTOOLS_LATENCY_BUCKETS_MS.length;
|
|
18
|
+
}
|
|
19
|
+
/** Adds one duration to `histogram` in place. A negative or non-finite value counts as 0. */
|
|
20
|
+
function recordDuration(histogram, durationMs) {
|
|
21
|
+
const value = Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;
|
|
22
|
+
const index = bucketIndex(value);
|
|
23
|
+
histogram.counts[index] = (histogram.counts[index] ?? 0) + 1;
|
|
24
|
+
histogram.count += 1;
|
|
25
|
+
histogram.sumMs += value;
|
|
26
|
+
if (value > histogram.maxMs) histogram.maxMs = value;
|
|
27
|
+
}
|
|
28
|
+
/** The sum of several histograms (exact: they share the bucket bounds). */
|
|
29
|
+
function mergeHistograms(histograms) {
|
|
30
|
+
const merged = createHistogram();
|
|
31
|
+
for (const histogram of histograms) {
|
|
32
|
+
for (let index = 0; index < merged.counts.length; index++) merged.counts[index] = (merged.counts[index] ?? 0) + (histogram.counts[index] ?? 0);
|
|
33
|
+
merged.count += histogram.count;
|
|
34
|
+
merged.sumMs += histogram.sumMs;
|
|
35
|
+
if (histogram.maxMs > merged.maxMs) merged.maxMs = histogram.maxMs;
|
|
36
|
+
}
|
|
37
|
+
return merged;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The `q` quantile (0–1) of a histogram: the upper bound of the bucket that
|
|
41
|
+
* holds it, capped at the largest value seen. 0 for an empty histogram.
|
|
42
|
+
*/
|
|
43
|
+
function histogramQuantile(histogram, q) {
|
|
44
|
+
if (histogram.count === 0) return 0;
|
|
45
|
+
const rank = Math.max(1, Math.ceil(Math.min(Math.max(q, 0), 1) * histogram.count));
|
|
46
|
+
let seen = 0;
|
|
47
|
+
for (let index = 0; index < histogram.counts.length; index++) {
|
|
48
|
+
seen += histogram.counts[index] ?? 0;
|
|
49
|
+
if (seen >= rank) {
|
|
50
|
+
const bound = DEVTOOLS_LATENCY_BUCKETS_MS[index];
|
|
51
|
+
return bound === void 0 ? histogram.maxMs : Math.min(bound, histogram.maxMs);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return histogram.maxMs;
|
|
55
|
+
}
|
|
56
|
+
/** The mean duration, 0 for an empty histogram. */
|
|
57
|
+
function histogramMean(histogram) {
|
|
58
|
+
return histogram.count === 0 ? 0 : histogram.sumMs / histogram.count;
|
|
59
|
+
}
|
|
60
|
+
/** The first 16 hex characters of SHA-256: the id of a query shape or an error fingerprint. */
|
|
61
|
+
function shortId(value) {
|
|
62
|
+
return createHash("sha256").update(value).digest("hex").slice(0, 16);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
//#endregion
|
|
66
|
+
export { bucketIndex, createHistogram, histogramMean, histogramQuantile, mergeHistograms, recordDuration, shortId };
|
|
67
|
+
//# sourceMappingURL=histogram.mjs.map
|