@warlock.js/devtools 5.60.0 → 5.61.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 +13 -0
- package/cjs/{boot-Dg5YZGGR.cjs → boot-D0nF-7w3.cjs} +6 -5
- package/cjs/{boot-Dg5YZGGR.cjs.map → boot-D0nF-7w3.cjs.map} +1 -1
- package/cjs/{capture-CBgONYhk.cjs → capture-D2k0GnBN.cjs} +21 -420
- package/cjs/capture-D2k0GnBN.cjs.map +1 -0
- package/cjs/{collector-CJbQbzzK.cjs → collector-BfC4v87v.cjs} +4 -46
- package/cjs/collector-BfC4v87v.cjs.map +1 -0
- package/cjs/errors-DNQ-g49I.cjs.map +1 -1
- package/cjs/{http-DCVCf44M.cjs → http-1nnpAoI7.cjs} +10 -4
- package/cjs/http-1nnpAoI7.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/{insights-CFof59kF.cjs → insights-COA3u37q.cjs} +53 -21
- package/cjs/insights-COA3u37q.cjs.map +1 -0
- package/cjs/query-shape-DShKQa0x.cjs +45 -0
- package/cjs/query-shape-DShKQa0x.cjs.map +1 -0
- package/cjs/redact-DQ28mDzr.cjs +533 -0
- package/cjs/redact-DQ28mDzr.cjs.map +1 -0
- package/cjs/{server-CC5DpObz.cjs → server-DLT3uPef.cjs} +2 -2
- package/cjs/{server-CC5DpObz.cjs.map → server-DLT3uPef.cjs.map} +1 -1
- package/cjs/{src-VyOjEEAo.cjs → src-BZiSv8A1.cjs} +9 -6
- package/cjs/src-BZiSv8A1.cjs.map +1 -0
- package/cjs/{stream-route-DFHuIWgg.cjs → stream-route-B6WAjbPG.cjs} +5 -8
- package/cjs/stream-route-B6WAjbPG.cjs.map +1 -0
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +4 -1
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/production/boot.mjs +1 -0
- package/esm/production/boot.mjs.map +1 -1
- package/esm/production/contracts.d.mts +17 -4
- package/esm/production/contracts.d.mts.map +1 -1
- package/esm/production/contracts.mjs.map +1 -1
- package/esm/production/http/mount.mjs +8 -2
- package/esm/production/http/mount.mjs.map +1 -1
- package/esm/production/http/share.mjs.map +1 -1
- package/esm/production/index.d.mts +2 -2
- package/esm/production/insights/jobs.mjs +45 -11
- package/esm/production/insights/jobs.mjs.map +1 -1
- package/esm/server/panel-routes.mjs.map +1 -1
- package/esm/server/ui-assets.mjs +4 -7
- package/esm/server/ui-assets.mjs.map +1 -1
- package/esm/types.d.mts +2 -2
- package/llms-full.txt +22 -22
- package/package.json +8 -8
- package/skills/SKILL.md +22 -22
- package/ui/dashboard/assets/app.css +1 -1
- package/ui/dashboard/assets/app.js +2 -2
- package/ui/dashboard/build-info.json +7 -7
- package/cjs/capture-CBgONYhk.cjs.map +0 -1
- package/cjs/collector-CJbQbzzK.cjs.map +0 -1
- package/cjs/histogram-CkoVizdf.cjs +0 -102
- package/cjs/histogram-CkoVizdf.cjs.map +0 -1
- package/cjs/http-DCVCf44M.cjs.map +0 -1
- package/cjs/insights-CFof59kF.cjs.map +0 -1
- package/cjs/src-VyOjEEAo.cjs.map +0 -1
- package/cjs/stream-route-DFHuIWgg.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"capture-D2k0GnBN.cjs","names":["detectNPlusOne","DevtoolsApiError","createErrorRef","LOG_MESSAGE_MAX","scrubErrorText","createCollector","createQueryStats","createRouteStats","createErrorGroups","createRecentLogs","toStoredSample","scrubQueryError","queryShape","truncate","log","LogChannel","scrubErrorText"],"sources":["../../../../../../../packages/devtools/src/production/capture/dev-stats.ts","../../../../../../../packages/devtools/src/production/capture/explain.ts","../../../../../../../packages/devtools/src/production/capture/filter.ts","../../../../../../../packages/devtools/src/production/capture/engine.ts","../../../../../../../packages/devtools/src/production/capture/production-capture.ts"],"sourcesContent":["import { detectNPlusOne } from \"../../n-plus-one\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsRequest } from \"../../types\";\nimport type {\n DevtoolsErrorGroups,\n DevtoolsQueryStats,\n DevtoolsRecentLogs,\n DevtoolsRouteStatsStore,\n} from \"./types\";\n\n/**\n * Development: feeds the statistics from the development collector's settled\n * requests (every request, no sampling), so the Queries, Routes and Errors\n * tabs work in `warlock dev` too.\n */\nexport function attachDevelopmentStats(\n collector: DevtoolsCollector,\n parts: {\n queries: DevtoolsQueryStats;\n routes: DevtoolsRouteStatsStore;\n errors: DevtoolsErrorGroups;\n logs: DevtoolsRecentLogs;\n nPlusOneThreshold: number;\n },\n): DevtoolsDisposer {\n const feed = (request: DevtoolsRequest) => {\n const failed =\n (request.status !== undefined && request.status >= 500) || request.error !== undefined;\n const route = request.route ?? null;\n\n for (const query of request.queries) {\n parts.queries.record({\n shape: query.shape,\n driver: query.driver,\n connection: query.connection,\n durationMs: query.durationMs,\n failed: query.error !== undefined,\n at: query.startedAt,\n route,\n requestId: request.id,\n });\n parts.queries.rememberExample(query);\n }\n\n for (const warning of detectNPlusOne(request.queries, parts.nPlusOneThreshold)) {\n parts.queries.recordNPlusOne(warning.shape, warning.count);\n }\n\n parts.routes.record({\n method: request.method,\n route: request.route ?? \"\",\n status: request.status ?? null,\n failed,\n durationMs: request.durationMs ?? 0,\n at: request.startedAt,\n requestId: request.id,\n phases: request.phases.map((phase) => ({ name: phase.name, durationMs: phase.durationMs })),\n });\n\n if (failed) {\n parts.errors.record({\n source: \"request\",\n message: request.error ?? `HTTP ${request.status}`,\n name: null,\n stack: null,\n route,\n status: request.status ?? null,\n requestId: request.id,\n at: request.startedAt,\n });\n }\n };\n\n return collector.subscribe((event) => {\n if (event.type === \"request\") {\n const request = collector.getRequest(event.data.id);\n\n if (request) feed(request);\n return;\n }\n\n if (event.type !== \"log\") return;\n\n const entry = event.data;\n\n if (entry.level !== \"warn\" && entry.level !== \"error\") return;\n\n parts.logs.record({\n level: entry.level,\n module: entry.module,\n action: entry.action,\n message: entry.message,\n at: entry.at,\n requestId: null,\n });\n\n if (entry.level === \"error\") {\n parts.errors.record({\n source: \"log\",\n message: entry.message,\n name: null,\n stack: null,\n route: null,\n status: null,\n requestId: null,\n at: entry.at,\n });\n }\n });\n}\n","import { log } from \"@warlock.js/logger\";\nimport type { DevtoolsExplainResult } from \"../contracts\";\nimport { createErrorRef, DevtoolsApiError } from \"../errors\";\nimport type { DevtoolsQuery } from \"../../types\";\nimport type { DevtoolsExplainRunner, DevtoolsExplainStatement, DevtoolsQueryStats } from \"./types\";\n\ntype ExplainStatement = DevtoolsExplainStatement;\ntype ExplainRunner = DevtoolsExplainRunner;\n\n/** Words that write, lock, call or create something. A read statement holds none of them. */\nconst FORBIDDEN_WORDS =\n /\\b(insert|update|delete|merge|truncate|alter|drop|create|grant|revoke|call|copy|vacuum|reindex|lock|into|refresh|execute|prepare|nextval|setval|pg_sleep\\w*|pg_advisory\\w*|lo_\\w+|dblink\\w*)\\b/i;\n\nconst isIdentifierCharacter = (character: string | undefined): boolean =>\n character !== undefined && /[A-Za-z0-9_$\\u0080-\\uffff]/.test(character);\n\n/** The index after the comment starting at `index` (`--` or a nested block comment), or `-1` when it is not closed. */\nfunction commentEnd(sql: string, index: number): number {\n if (sql.startsWith(\"--\", index)) {\n const newline = sql.indexOf(\"\\n\", index + 2);\n\n return newline === -1 ? sql.length : newline + 1;\n }\n\n let depth = 0;\n let at = index;\n\n while (at < sql.length) {\n if (sql.startsWith(\"/*\", at)) {\n depth++;\n at += 2;\n } else if (sql.startsWith(\"*/\", at)) {\n depth--;\n at += 2;\n\n if (depth === 0) return at;\n } else {\n at++;\n }\n }\n\n return -1;\n}\n\n/**\n * `sql` as the server reads it, with every comment turned into a space and\n * every string, quoted identifier and dollar-quoted body into `?`; `null`\n * when one of them is not closed. `backslashEscapes` reads a backslash as an\n * escape in every string (`standard_conforming_strings = off`); escape\n * strings (`E'…'`) always use it.\n */\nfunction maskSql(sql: string, backslashEscapes: boolean): string | null {\n let out = \"\";\n let at = 0;\n\n while (at < sql.length) {\n const character = sql[at] as string;\n\n if (sql.startsWith(\"--\", at) || sql.startsWith(\"/*\", at)) {\n const end = commentEnd(sql, at);\n\n if (end === -1) return null;\n\n out += \" \";\n at = end;\n continue;\n }\n\n if (character === \"'\" || character === '\"') {\n const escapes =\n character === \"'\" &&\n (backslashEscapes ||\n (/[eE]/.test(sql[at - 1] ?? \"\") && !isIdentifierCharacter(sql[at - 2])));\n let closed = false;\n\n at++;\n\n while (at < sql.length) {\n const current = sql[at];\n\n if (escapes && current === \"\\\\\") {\n at += 2;\n } else if (current === character) {\n at++;\n\n if (sql[at] !== character) {\n closed = true;\n break;\n }\n\n at++;\n } else {\n at++;\n }\n }\n\n if (!closed) return null;\n\n out += \" ? \";\n continue;\n }\n\n if (character === \"$\" && !isIdentifierCharacter(sql[at - 1])) {\n const tag = /^\\$(?:[A-Za-z_\\u0080-\\uffff][A-Za-z0-9_\\u0080-\\uffff]*)?\\$/.exec(sql.slice(at));\n\n const opener = tag?.[0];\n\n if (opener !== undefined) {\n const end = sql.indexOf(opener, at + opener.length);\n\n if (end === -1) return null;\n\n out += \" ? \";\n at = end + opener.length;\n continue;\n }\n }\n\n out += character;\n at++;\n }\n\n return out;\n}\n\n/** `sql` without its leading whitespace and comments, or `null` when a leading comment is not closed. */\nfunction withoutLeadingNoise(sql: string): string | null {\n let at = 0;\n\n while (at < sql.length) {\n if (/\\s/.test(sql[at] as string)) {\n at++;\n } else if (sql.startsWith(\"--\", at) || sql.startsWith(\"/*\", at)) {\n const end = commentEnd(sql, at);\n\n if (end === -1) return null;\n\n at = end;\n } else {\n break;\n }\n }\n\n return sql.slice(at);\n}\n\n/** Whether the masked statement is one read: it starts with SELECT or WITH, ends at most at one `;`, writes nothing. */\nfunction isOneRead(masked: string | null): boolean {\n if (masked === null) return false;\n\n const bare = masked.trim().replace(/;\\s*$/, \"\");\n\n return /^(select|with)\\b/i.test(bare) && !bare.includes(\";\") && !FORBIDDEN_WORDS.test(bare);\n}\n\n/**\n * The statement to explain when `sql` is one plain read (`SELECT` or `WITH`,\n * one statement, nothing that writes, locks or calls a function with side\n * effects), without its leading comments; `null` otherwise. Strings, quoted\n * identifiers, dollar-quoted bodies and nested comments are read the way the\n * server reads them, under both settings of `standard_conforming_strings`, so\n * a `;` or a keyword cannot hide inside what only looks like a string.\n */\nexport function explainableSql(sql: string | undefined): string | null {\n if (sql === undefined) return null;\n\n const statement = withoutLeadingNoise(sql)?.trimEnd();\n\n if (\n statement === undefined ||\n !isOneRead(maskSql(statement, false)) ||\n !isOneRead(maskSql(statement, true))\n ) {\n return null;\n }\n\n return statement.replace(/;\\s*$/, \"\");\n}\n\n/** Keys of a recorded MongoDB command that an inner `explain` command does not accept. */\nconst MONGO_SESSION_KEYS = new Set([\n \"lsid\",\n \"txnNumber\",\n \"autocommit\",\n \"startTransaction\",\n \"readConcern\",\n \"writeConcern\",\n]);\n\nconst MONGO_COMMANDS = new Set([\"find\", \"aggregate\", \"count\"]);\n\n/** Aggregation stages that write their result to a collection. */\nconst MONGO_WRITE_STAGES = new Set([\"$out\", \"$merge\"]);\n\n/** Whether a recorded command or pipeline has a stage that writes. */\nfunction writesInPipeline(recorded: unknown): boolean {\n const pipeline = Array.isArray(recorded)\n ? recorded\n : recorded !== null && typeof recorded === \"object\"\n ? (recorded as Record<string, unknown>).pipeline\n : undefined;\n\n return (\n Array.isArray(pipeline) &&\n pipeline.some(\n (stage) =>\n stage !== null &&\n typeof stage === \"object\" &&\n Object.keys(stage as Record<string, unknown>).some((key) => MONGO_WRITE_STAGES.has(key)),\n )\n );\n}\n\nfunction mongoExplainCommand(\n query: DevtoolsQuery,\n executing: boolean,\n): Record<string, unknown> | null {\n const name = query.command;\n\n if (name === undefined || !MONGO_COMMANDS.has(name) || query.collection === undefined) {\n return null;\n }\n\n if (name === \"aggregate\" && writesInPipeline(query.pipeline)) return null;\n\n let inner: Record<string, unknown>;\n const recorded = query.pipeline;\n\n if (recorded !== null && typeof recorded === \"object\" && !Array.isArray(recorded)) {\n inner = {};\n\n for (const [key, value] of Object.entries(recorded as Record<string, unknown>)) {\n if (key.startsWith(\"$\") || MONGO_SESSION_KEYS.has(key)) continue;\n\n inner[key] = value;\n }\n\n inner[name] = query.collection;\n } else if (name === \"aggregate\") {\n inner = {\n aggregate: query.collection,\n pipeline: Array.isArray(recorded) ? recorded : [],\n cursor: {},\n };\n } else {\n inner = { [name]: query.collection };\n }\n\n return { explain: inner, verbosity: executing ? \"executionStats\" : \"queryPlanner\" };\n}\n\nfunction statementFor(query: DevtoolsQuery, executing: boolean): ExplainStatement | null {\n if (query.driver === \"postgres\") {\n const sql = explainableSql(query.sql);\n\n if (sql === null) return null;\n\n const prefix = executing ? \"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)\" : \"EXPLAIN (FORMAT JSON)\";\n\n return { type: \"sql\", sql: `${prefix} ${sql}` };\n }\n\n const command = mongoExplainCommand(query, executing);\n\n return command === null ? null : { type: \"mongo\", command };\n}\n\ntype ReadOnlyTransaction = {\n context: { query(sql: string, params?: unknown[]): Promise<{ rows: unknown }> };\n commit(): Promise<void>;\n rollback(): Promise<void>;\n};\n\n/**\n * Runs `sql` in a read-only transaction on its own pooled client and rolls it\n * back, so nothing the statement reaches (a function with side effects under\n * `ANALYZE`, a second statement) can write.\n */\nasync function explainReadOnly(\n driver: unknown,\n sql: string,\n bindings: unknown[] | undefined,\n): Promise<unknown> {\n const begin = (driver as { beginTransaction?: unknown }).beginTransaction;\n\n if (typeof begin !== \"function\") {\n throw new Error(\"The connection cannot open a read-only transaction, so EXPLAIN was not run.\");\n }\n\n const transaction = (await begin.call(driver, { readOnly: true })) as ReadOnlyTransaction;\n\n try {\n const { rows } = await transaction.context.query(sql, bindings ?? []);\n\n return rows;\n } finally {\n await transaction.rollback();\n }\n}\n\n/** Runs the statement on the query's own connection through cascade's data source registry. */\nconst runOnDataSource: ExplainRunner = async (query, statement) => {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n\n if (statement.type === \"sql\") {\n return explainReadOnly(dataSource.driver, statement.sql, query.bindings);\n }\n\n const driver = dataSource.driver as unknown as {\n getDatabase(): { command(command: Record<string, unknown>): Promise<unknown> };\n };\n\n return driver.getDatabase().command(statement.command);\n};\n\n/** Keys of a MongoDB plan whose values come from the query (filters, bounds, the echoed command). */\nconst MONGO_VALUE_KEYS = new Set([\n \"parsedQuery\",\n \"filter\",\n \"indexBounds\",\n \"command\",\n \"originalCommand\",\n \"query\",\n \"pipeline\",\n]);\n/** SQL literals inside a PostgreSQL plan's condition text: `'text'` (with `''`), `E'…'` and numbers. */\nconst SQL_LITERAL = /(?:(?<!\\w)[Ee])?'(?:''|\\\\.|[^'])*'|(?<![\\w.$])-?\\d+(?:\\.\\d+)?(?![\\w.])/g;\n\nfunction maskMongoValues(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(maskMongoValues);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).map(([key, inner]) => [key, maskMongoValues(inner)]),\n );\n }\n\n return value === null || value === undefined ? value : \"?\";\n}\n\nfunction redactMongoPlan(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactMongoPlan);\n if (value === null || typeof value !== \"object\") return value;\n\n return Object.fromEntries(\n Object.entries(value).map(([key, inner]) => [\n key,\n MONGO_VALUE_KEYS.has(key) ? maskMongoValues(inner) : redactMongoPlan(inner),\n ]),\n );\n}\n\nfunction redactSqlPlan(value: unknown): unknown {\n if (typeof value === \"string\") return value.replace(SQL_LITERAL, \"?\");\n if (Array.isArray(value)) return value.map(redactSqlPlan);\n if (value === null || typeof value !== \"object\") return value;\n\n return Object.fromEntries(\n Object.entries(value).map(([key, inner]) => [key, redactSqlPlan(inner)]),\n );\n}\n\n/**\n * A plan without the query's values. Plans repeat them: MongoDB echoes the\n * filter (`parsedQuery`, `indexBounds`, the command), PostgreSQL writes them\n * into conditions (`Filter: (email = 'a@b.c'::text)`). Values become `?`;\n * the plan's shape, costs, row counts and index choices stay.\n */\nexport function redactExplainPlan(plan: unknown, driver: string): unknown {\n return driver === \"mongodb\" ? redactMongoPlan(plan) : redactSqlPlan(plan);\n}\n\n/**\n * EXPLAIN by shape id from the examples `queries` kept, used by the production\n * capture and by development (`POST /api/queries/:shapeId/explain`). Plain\n * `EXPLAIN (FORMAT JSON)` / MongoDB `queryPlanner` unless `executing`; never\n * an executing plan for anything but a PostgreSQL `SELECT`/`WITH` or a\n * MongoDB `find`/`aggregate`/`count` (never an aggregate with `$out` or\n * `$merge`). `run` executes the statement on the query's own connection\n * (injected for specs; default: cascade's `dataSourceRegistry`, PostgreSQL\n * inside a read-only transaction that is always rolled back).\n */\nexport function createShapeExplainer(input: {\n queries: DevtoolsQueryStats;\n executing: boolean;\n instance: string;\n run?: ExplainRunner;\n /** Remove the query's values from the plan (`redactExplainPlan`); production sets it. */\n redact?: boolean;\n}): (shapeId: string) => Promise<DevtoolsExplainResult> {\n const run = input.run ?? runOnDataSource;\n\n return async (shapeId) => {\n const example = input.queries.example(shapeId);\n\n if (!example) throw new DevtoolsApiError(\"explain.elsewhere\", { instance: input.instance });\n\n const statement = statementFor(example, input.executing);\n\n if (!statement) throw new DevtoolsApiError(\"explain.unsupported\", { instance: input.instance });\n\n try {\n const plan = await run(example, statement);\n\n return {\n shapeId,\n driver: example.driver,\n executing: input.executing,\n plan: input.redact === true ? redactExplainPlan(plan, example.driver) : plan,\n instance: input.instance,\n };\n } catch (cause) {\n const ref = createErrorRef();\n\n log.error(\n \"devtools\",\n \"explain\",\n `EXPLAIN failed for query shape ${shapeId} (ref ${ref}): ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\n );\n\n throw new DevtoolsApiError(\"explain.failed\", { ref, cause, instance: input.instance });\n }\n };\n}\n","import type { DevtoolsSampleSummary } from \"../contracts\";\nimport type { DevtoolsSampleFilter } from \"../store/types\";\n\n/** Whether a stored sample's row passes a request filter (the same rules as the store). */\nexport function sampleMatchesFilter(\n summary: DevtoolsSampleSummary,\n filter: DevtoolsSampleFilter,\n): boolean {\n if (filter.status !== undefined && !statusMatches(filter.status, summary.status)) return false;\n\n if (filter.method !== undefined && summary.method.toUpperCase() !== filter.method.toUpperCase()) {\n return false;\n }\n\n if (filter.route !== undefined) {\n const haystack = `${summary.route ?? \"\"} ${summary.path}`.toLowerCase();\n\n if (!haystack.includes(filter.route.toLowerCase())) return false;\n }\n\n if (filter.q !== undefined && !summary.path.toLowerCase().includes(filter.q.toLowerCase())) {\n return false;\n }\n\n if (filter.since !== undefined && summary.startedAt < filter.since) return false;\n if (filter.until !== undefined && summary.startedAt > filter.until) return false;\n if (filter.instance !== undefined && summary.instance !== filter.instance) return false;\n\n return true;\n}\n\nfunction statusMatches(filter: string, status: number | undefined): boolean {\n if (status === undefined) return false;\n\n const range = /^([1-5])xx$/i.exec(filter);\n\n if (range) return Math.floor(status / 100) === Number(range[1]);\n\n return status === Number(filter);\n}\n","import { createCollector } from \"../../collector\";\nimport { queryShape } from \"../../query-shape\";\nimport type {\n DevtoolsCacheOperation,\n DevtoolsCollector,\n DevtoolsLogEntry,\n DevtoolsQuery,\n DevtoolsRequest,\n} from \"../../types\";\nimport type {\n DevtoolsCaptureCounters,\n DevtoolsSampleDetail,\n DevtoolsSampleSummary,\n} from \"../contracts\";\nimport type { DevtoolsStoredSample } from \"../store/types\";\nimport { createShapeExplainer } from \"./explain\";\nimport { sampleMatchesFilter } from \"./filter\";\nimport { scrubErrorText, scrubQueryError, toStoredSample } from \"./redact\";\nimport {\n createErrorGroups,\n createQueryStats,\n createRecentLogs,\n createRouteStats,\n truncate,\n} from \"./stats-stores\";\nimport type {\n DevtoolsCaptureDeps,\n DevtoolsErrorGroups,\n DevtoolsQueryStats,\n DevtoolsRecentLogs,\n DevtoolsRequestSource,\n DevtoolsRouteStatsStore,\n} from \"./types\";\n\n/** Per sampled request limits (see \"Bounded memory\"). */\nconst MAX_LOGS_PER_REQUEST = 50;\nconst MAX_PHASES_PER_REQUEST = 100;\nconst MAX_CACHE_PER_REQUEST = 1000;\nconst MAX_ACTIVE = 2000;\nconst MAX_PENDING = 500;\nconst FLUSH_AT = 50;\nconst FLUSH_EVERY_MS = 5000;\nconst WARN_EVERY_MS = 60_000;\nconst LOG_MESSAGE_MAX = 1000;\n\n/** The shape of the event cascade's `dataSourceRegistry` emits for `\"query\"`. */\nexport type DevtoolsQueryEvent = {\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n sql?: string;\n bindings?: unknown[];\n collection?: string;\n command?: string;\n pipeline?: unknown;\n durationMs: number;\n startedAt: number;\n rowCount?: number;\n error?: unknown;\n};\n\n/** What core's tracing hooks hand over for a request. */\nexport type DevtoolsTracedRequest = {\n requestId: string;\n method: string;\n path: string;\n route?: string | undefined;\n};\n\ntype RequestState = {\n queries: number;\n logs: number;\n phases: number;\n cache: number;\n dropped: number;\n route: string | undefined;\n};\n\n/** The functions the tracing, query, log and cache sources call. */\nexport type DevtoolsCaptureHooks = {\n onRequestStart(request: DevtoolsTracedRequest): void;\n onPhase(\n request: DevtoolsTracedRequest,\n phase: { name: string; durationMs: number; startedAt?: number | undefined },\n ): void;\n onRequestEnd(\n request: DevtoolsTracedRequest,\n result: { status?: number | undefined; durationMs: number; error?: unknown },\n ): void;\n onQuery(requestId: string | undefined, event: DevtoolsQueryEvent): void;\n onLog(requestId: string | undefined, entry: Omit<DevtoolsLogEntry, \"context\">): void;\n onCache(requestId: string | undefined, operation: DevtoolsCacheOperation): void;\n};\n\n/** Everything the production capture is made of, apart from the registration with core, cascade, the logger and the cache. */\nexport type DevtoolsCaptureEngine = {\n collector: DevtoolsCollector;\n queries: DevtoolsQueryStats;\n routes: DevtoolsRouteStatsStore;\n errors: DevtoolsErrorGroups;\n logs: DevtoolsRecentLogs;\n requests: DevtoolsRequestSource;\n hooks: DevtoolsCaptureHooks;\n counters(): DevtoolsCaptureCounters;\n explain(shapeId: string): ReturnType<ReturnType<typeof createShapeExplainer>>;\n /** Starts the 5 s write timer (a no-op without a store). */\n startWriter(): void;\n stopWriter(): void;\n flush(): Promise<void>;\n};\n\nfunction stripQuery(path: string): string {\n const index = path.indexOf(\"?\");\n\n return index === -1 ? path : path.slice(0, index);\n}\n\n/** The lengths the error groups keep (see `createErrorGroups`). */\nconst REQUEST_ERROR_MAX = 500;\nconst REQUEST_STACK_MAX = 4000;\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** A request's error message as the monitor keeps it: without the values in it (see `scrubErrorText`). */\nfunction requestErrorMessage(error: unknown): string {\n return scrubErrorText(errorMessage(error), REQUEST_ERROR_MAX);\n}\n\nfunction touchesMonitorTables(event: DevtoolsQueryEvent): boolean {\n return (\n (event.sql !== undefined && event.sql.includes(\"devtools_\")) ||\n (event.collection !== undefined && event.collection.startsWith(\"devtools_\"))\n );\n}\n\n/**\n * The capture of one process without any registration: sampling, the ring,\n * the statistics, the sample writer and the request source. The hooks are\n * plain functions so a spec (or the benchmark) can drive them directly.\n */\nexport function createCaptureEngine(deps: DevtoolsCaptureDeps): DevtoolsCaptureEngine {\n const { production, instance, store } = deps;\n const random = deps.random ?? Math.random;\n const now = deps.now ?? (() => performance.timeOrigin + performance.now());\n const warn = deps.warn ?? (() => {});\n const logLevels = new Set<string>(production.logLevels);\n\n const collector = createCollector({ ...deps.options, maxRequests: production.maxRequests });\n const queries = createQueryStats({ maxShapes: production.maxShapes, instance: instance.id });\n const routes = createRouteStats({ maxRoutes: production.maxRoutes, instance: instance.id });\n const errors = createErrorGroups({ maxGroups: production.maxErrorGroups });\n const logs = createRecentLogs({ maxEntries: 200 });\n\n const active = new Map<string, RequestState>();\n const recent = new Map<string, DevtoolsStoredSample>();\n const pending: DevtoolsStoredSample[] = [];\n const counts = {\n requests: 0,\n sampled: 0,\n keptUnsampled: 0,\n stored: 0,\n droppedStored: 0,\n droppedQueries: 0,\n };\n\n let exampleSequence = 0;\n let budgetMinute = -1;\n let budgetUsed = 0;\n let lastWarnAt = -Infinity;\n let flushing: Promise<void> = Promise.resolve();\n let timer: ReturnType<typeof setInterval> | undefined;\n\n // -- sample writer ---------------------------------------------------------\n\n const remember = (sample: DevtoolsStoredSample) => {\n recent.delete(sample.id);\n recent.set(sample.id, sample);\n\n while (recent.size > production.maxRequests) {\n recent.delete(recent.keys().next().value as string);\n }\n };\n\n const doFlush = async () => {\n if (!store || pending.length === 0) return;\n\n const batch = pending.splice(0, pending.length);\n\n try {\n await store.samples.insert(batch);\n counts.stored += batch.length;\n } catch (error) {\n counts.droppedStored += batch.length;\n\n const at = now();\n\n if (at - lastWarnAt >= WARN_EVERY_MS) {\n lastWarnAt = at;\n warn(\n `devtools could not store ${batch.length} request sample(s), they were dropped: ${errorMessage(error)}. Check the database connection and that the devtools migrations ran.`,\n );\n }\n }\n };\n\n const flush = (): Promise<void> => {\n flushing = flushing.then(doFlush, doFlush);\n\n return flushing;\n };\n\n const enqueue = (sample: DevtoolsStoredSample) => {\n remember(sample);\n\n if (!store) return;\n\n const minute = Math.floor(now() / 60_000);\n\n if (minute !== budgetMinute) {\n budgetMinute = minute;\n budgetUsed = 0;\n }\n\n if (budgetUsed >= production.maxStoredSamplesPerMinute) {\n counts.droppedStored++;\n return;\n }\n\n budgetUsed++;\n pending.push(sample);\n\n if (pending.length > MAX_PENDING) {\n pending.shift();\n counts.droppedStored++;\n }\n\n if (pending.length >= FLUSH_AT) void flush();\n };\n\n // -- hooks -----------------------------------------------------------------\n\n const newState = (route: string | undefined): RequestState => ({\n queries: 0,\n logs: 0,\n phases: 0,\n cache: 0,\n dropped: 0,\n route,\n });\n\n const recordRequestError = (\n request: DevtoolsTracedRequest,\n result: { status?: number | undefined; error?: unknown },\n route: string | undefined,\n ) => {\n const status = result.status;\n const failed = (status !== undefined && status >= 500) || result.error !== undefined;\n\n if (!failed) return;\n\n const error = result.error;\n\n errors.record({\n source: \"request\",\n message: error === undefined ? `HTTP ${status}` : requestErrorMessage(error),\n name: error instanceof Error ? error.name : null,\n // The first line of a stack repeats the message.\n stack:\n error instanceof Error && error.stack !== undefined\n ? scrubErrorText(error.stack, REQUEST_STACK_MAX)\n : null,\n route: route ?? null,\n status: status ?? null,\n requestId: request.requestId,\n at: now(),\n });\n };\n\n const finishSampled = (\n request: DevtoolsTracedRequest,\n state: RequestState,\n result: { status?: number | undefined; durationMs: number; error?: unknown },\n ) => {\n const route = request.route ?? state.route;\n\n collector.endRequest(request.requestId, {\n ...(result.status === undefined ? {} : { status: result.status }),\n durationMs: result.durationMs,\n ...(result.error === undefined ? {} : { error: requestErrorMessage(result.error) }),\n ...(route === undefined ? {} : { route }),\n });\n\n const settled = collector.getRequest(request.requestId);\n\n if (!settled) return;\n\n const failed =\n (result.status !== undefined && result.status >= 500) || result.error !== undefined;\n\n routes.record({\n method: request.method,\n route: route ?? \"\",\n status: result.status ?? null,\n failed,\n durationMs: result.durationMs,\n at: now(),\n requestId: request.requestId,\n phases: settled.phases.map((phase) => ({ name: phase.name, durationMs: phase.durationMs })),\n });\n\n for (const warning of settled.warnings) queries.recordNPlusOne(warning.shape, warning.count);\n\n recordRequestError(request, result, route);\n enqueue(toStoredSample(settled, instance.id, state.dropped));\n };\n\n const finishUnsampled = (\n request: DevtoolsTracedRequest,\n result: { status?: number | undefined; durationMs: number; error?: unknown },\n ) => {\n if (deps.isDashboardPath(request.path)) return;\n\n counts.keptUnsampled++;\n\n const startedAt = now() - result.durationMs;\n const path = stripQuery(request.path);\n const summary: DevtoolsSampleSummary = {\n id: request.requestId,\n method: request.method,\n path,\n startedAt,\n durationMs: result.durationMs,\n queryCount: 0,\n warningCount: 0,\n instance: instance.id,\n partial: true,\n };\n\n if (request.route !== undefined) summary.route = request.route;\n if (result.status !== undefined) summary.status = result.status;\n\n recordRequestError(request, result, request.route);\n enqueue({ id: request.requestId, instance: instance.id, startedAt, summary, detail: null });\n\n // The live stream shows it too.\n collector.startRequest({\n id: request.requestId,\n method: request.method,\n path,\n ...(request.route === undefined ? {} : { route: request.route }),\n startedAt,\n });\n collector.endRequest(request.requestId, {\n ...(result.status === undefined ? {} : { status: result.status }),\n durationMs: result.durationMs,\n ...(result.error === undefined ? {} : { error: requestErrorMessage(result.error) }),\n ...(request.route === undefined ? {} : { route: request.route }),\n });\n };\n\n /** The query without an id or a shape, from what the driver emitted. */\n const queryInput = (event: DevtoolsQueryEvent): Omit<DevtoolsQuery, \"id\" | \"shape\"> => {\n const input: Omit<DevtoolsQuery, \"id\" | \"shape\"> = {\n connection: event.connection,\n driver: event.driver,\n startedAt: event.startedAt,\n durationMs: event.durationMs,\n };\n\n if (event.sql !== undefined) input.sql = event.sql;\n if (event.bindings !== undefined) input.bindings = event.bindings;\n if (event.collection !== undefined) input.collection = event.collection;\n if (event.command !== undefined) input.command = event.command;\n if (event.pipeline !== undefined) input.pipeline = event.pipeline;\n if (event.rowCount !== undefined) input.rowCount = event.rowCount;\n if (event.error !== undefined) input.error = scrubQueryError(errorMessage(event.error));\n\n return input;\n };\n\n const exampleOf = (event: DevtoolsQueryEvent): DevtoolsQuery => ({\n ...queryInput(event),\n id: `x${++exampleSequence}`,\n shape: queryShape(event),\n });\n\n const recordQuery = (query: DevtoolsQuery, route: string | null, requestId: string | null) => {\n queries.record({\n shape: query.shape,\n driver: query.driver,\n connection: query.connection,\n durationMs: query.durationMs,\n failed: query.error !== undefined,\n at: query.startedAt,\n route,\n requestId,\n });\n queries.rememberExample(query);\n };\n\n const hooks: DevtoolsCaptureHooks = {\n onRequestStart(request) {\n if (deps.isDashboardPath(request.path)) return;\n\n counts.requests++;\n\n if (!(random() < production.sampleRate)) return;\n\n counts.sampled++;\n\n if (active.size >= MAX_ACTIVE) active.delete(active.keys().next().value as string);\n\n active.set(request.requestId, newState(request.route));\n collector.startRequest({\n id: request.requestId,\n method: request.method,\n path: stripQuery(request.path),\n ...(request.route === undefined ? {} : { route: request.route }),\n startedAt: now(),\n });\n },\n\n onPhase(request, phase) {\n const state = active.get(request.requestId);\n\n if (!state) return;\n\n if (request.route !== undefined) state.route = request.route;\n if (state.phases >= MAX_PHASES_PER_REQUEST) return;\n\n state.phases++;\n collector.addPhase(request.requestId, {\n name: phase.name,\n durationMs: phase.durationMs,\n startedAt: phase.startedAt ?? now() - phase.durationMs,\n });\n },\n\n onRequestEnd(request, result) {\n const state = active.get(request.requestId);\n\n if (state) {\n active.delete(request.requestId);\n finishSampled(request, state, result);\n return;\n }\n\n if (\n result.durationMs >= production.slowRequestMs ||\n (result.status !== undefined && result.status >= 500) ||\n result.error !== undefined\n ) {\n finishUnsampled(request, result);\n }\n },\n\n onQuery(requestId, event) {\n const state = requestId === undefined ? undefined : active.get(requestId);\n\n if (state && requestId !== undefined) {\n if (touchesMonitorTables(event)) return;\n\n let query: DevtoolsQuery;\n\n if (state.queries < production.maxQueriesPerRequest) {\n state.queries++;\n query = collector.addQuery(requestId, queryInput(event));\n } else {\n state.dropped++;\n counts.droppedQueries++;\n query = exampleOf(event);\n }\n\n recordQuery(query, state.route ?? null, requestId);\n\n // The ring keeps the shape only; the statistics copied what EXPLAIN needs.\n delete query.sql;\n delete query.bindings;\n delete query.pipeline;\n return;\n }\n\n if (requestId === undefined) {\n // Work outside a request is sampled query by query.\n if (touchesMonitorTables(event)) return;\n\n if (random() < production.sampleRate) {\n const query = exampleOf(event);\n\n recordQuery(query, null, null);\n } else if (event.durationMs >= production.slowQueryMs) {\n queries.rememberExample(exampleOf(event));\n }\n\n return;\n }\n\n // An unsampled request: only a slow query leaves a trace, in its shape's `slowest`.\n if (event.durationMs >= production.slowQueryMs && !touchesMonitorTables(event)) {\n queries.rememberExample(exampleOf(event));\n }\n },\n\n onLog(requestId, entry) {\n const wanted = logLevels.has(entry.level);\n const state = requestId === undefined ? undefined : active.get(requestId);\n\n if (!wanted && !state) return;\n\n const message = truncate(entry.message, LOG_MESSAGE_MAX);\n const kept: DevtoolsLogEntry = {\n level: entry.level,\n module: entry.module,\n action: entry.action,\n message,\n at: entry.at,\n };\n\n if (state && requestId !== undefined) {\n if (state.logs < MAX_LOGS_PER_REQUEST) {\n state.logs++;\n collector.addLog(requestId, kept);\n }\n } else {\n collector.addLog(undefined, kept);\n }\n\n if (!wanted) return;\n\n logs.record({\n level: entry.level,\n module: entry.module,\n action: entry.action,\n message,\n at: entry.at,\n requestId: state && requestId !== undefined ? requestId : null,\n });\n\n if (entry.level === \"error\") {\n errors.record({\n source: \"log\",\n message: entry.message,\n name: null,\n stack: null,\n route: state?.route ?? null,\n status: null,\n requestId: state && requestId !== undefined ? requestId : null,\n at: entry.at,\n });\n }\n },\n\n onCache(requestId, operation) {\n if (requestId === undefined) return;\n\n const state = active.get(requestId);\n\n if (!state || state.cache >= MAX_CACHE_PER_REQUEST) return;\n\n state.cache++;\n // Counts only: keys and tags never enter the ring.\n collector.addCacheOperation(requestId, {\n type: operation.type,\n driver: operation.driver,\n at: operation.at,\n });\n },\n };\n\n // -- request source --------------------------------------------------------\n\n const requests: DevtoolsRequestSource = {\n async list(filter) {\n let storedRows: DevtoolsSampleSummary[] = [];\n\n if (store) {\n try {\n storedRows = await store.samples.list(filter);\n } catch (error) {\n warn(\n `devtools could not read request samples: ${errorMessage(error)}. Showing this process's requests only.`,\n );\n }\n }\n\n const merged = new Map<string, DevtoolsSampleSummary>();\n\n for (const row of storedRows) merged.set(row.id, row);\n\n for (const sample of recent.values()) {\n if (!merged.has(sample.id) && sampleMatchesFilter(sample.summary, filter)) {\n merged.set(sample.id, sample.summary);\n }\n }\n\n return [...merged.values()]\n .sort((a, b) => b.startedAt - a.startedAt)\n .slice(0, Math.max(1, filter.limit));\n },\n\n async get(id) {\n let stored: DevtoolsStoredSample | null = null;\n\n if (store) {\n try {\n stored = await store.samples.get(id);\n } catch {\n stored = null;\n }\n }\n\n stored ??= recent.get(id) ?? null;\n\n if (stored) return stored.detail ?? stored.summary;\n\n const live: DevtoolsRequest | undefined = collector.getRequest(id);\n\n if (!live) return null;\n\n const dropped = active.get(id)?.dropped ?? 0;\n const sample = toStoredSample(live, instance.id, dropped);\n\n return (sample.detail ?? sample.summary) as DevtoolsSampleDetail | DevtoolsSampleSummary;\n },\n\n async clear() {\n const memory = recent.size;\n const waiting = pending.length;\n\n recent.clear();\n pending.length = 0;\n collector.clear();\n\n if (!store) return memory;\n\n const removed = await store.samples.clear();\n\n return removed + waiting;\n },\n };\n\n const explain = createShapeExplainer({\n queries,\n executing: production.explain.executing,\n instance: instance.id,\n // Values never leave the process, and plans repeat them.\n redact: true,\n ...(deps.run === undefined ? {} : { run: deps.run }),\n });\n\n return {\n collector,\n queries,\n routes,\n errors,\n logs,\n requests,\n hooks,\n explain,\n flush,\n counters: () => ({\n sampleRate: production.sampleRate,\n requests: counts.requests,\n sampled: counts.sampled,\n keptUnsampled: counts.keptUnsampled,\n stored: counts.stored,\n droppedStored: counts.droppedStored,\n evictedShapes: queries.evicted(),\n evictedRoutes: routes.evicted(),\n evictedErrors: errors.evicted(),\n droppedQueries: counts.droppedQueries,\n }),\n startWriter() {\n if (!store || timer) return;\n\n timer = setInterval(() => void flush(), FLUSH_EVERY_MS);\n timer.unref();\n },\n stopWriter() {\n if (timer) clearInterval(timer);\n\n timer = undefined;\n },\n };\n}\n","import { LogChannel, log, type LoggingData } from \"@warlock.js/logger\";\nimport type { DevtoolsDisposer, DevtoolsLogEntry } from \"../../types\";\nimport { scrubErrorText } from \"./redact\";\nimport { createCaptureEngine, type DevtoolsQueryEvent } from \"./engine\";\nimport type { DevtoolsCaptureDeps, DevtoolsProductionCapture } from \"./types\";\n\n/** Longest log message kept, as in the capture engine. */\nconst LOG_MESSAGE_MAX = 1000;\n\n/** Cache events counted for sampled requests. */\nconst CACHE_EVENT_TYPES = [\"hit\", \"miss\", \"set\", \"removed\", \"invalidated\", \"flushed\"] as const;\n\ntype CacheEventData = {\n key?: string;\n driver: string;\n tags?: string[];\n keys?: string[];\n durationMs?: number;\n};\n\n/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */\nfunction toLevel(type: LoggingData[\"type\"]): DevtoolsLogEntry[\"level\"] {\n return type === \"fatal\" ? \"error\" : type;\n}\n\n/**\n * The production capture of this process: sampling, the bounded in-memory\n * ring of sampled requests (the live view), statistics, error groups, recent\n * logs, the sample writer and EXPLAIN.\n *\n * Unsampled requests cost one random draw at start and one comparison at\n * end; they add nothing to the statistics.\n */\nexport function createProductionCapture(deps: DevtoolsCaptureDeps): DevtoolsProductionCapture {\n const engine = createCaptureEngine({\n ...deps,\n warn: deps.warn ?? ((message) => log.warn(\"devtools\", \"capture\", message)),\n });\n const { hooks } = engine;\n let detach: DevtoolsDisposer | undefined;\n\n const warnFailed = (name: string, error: unknown) => {\n log.warn(\n \"devtools\",\n \"capture\",\n `devtools' ${name} capture failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n };\n\n return {\n collector: engine.collector,\n queries: engine.queries,\n routes: engine.routes,\n errors: engine.errors,\n logs: engine.logs,\n requests: engine.requests,\n counters: engine.counters,\n explain: engine.explain,\n flush: engine.flush,\n\n async attach() {\n if (detach) return detach;\n\n const disposers: DevtoolsDisposer[] = [];\n\n // Reached only here so a process that never enables the monitor never loads core.\n const { currentRequestId } = await import(\"../../current-request-id\");\n\n try {\n const { registerTracingHooks } = await import(\"@warlock.js/core\");\n\n disposers.push(\n registerTracingHooks({\n onRequestStart: hooks.onRequestStart,\n onPhase: hooks.onPhase,\n onRequestEnd: hooks.onRequestEnd,\n }),\n );\n } catch (error) {\n warnFailed(\"request\", error);\n }\n\n try {\n let dataSourceRegistry: {\n on(event: \"query\", listener: (event: DevtoolsQueryEvent) => void): void;\n off(event: \"query\", listener: (event: DevtoolsQueryEvent) => void): void;\n };\n\n ({ dataSourceRegistry } = await import(\"@warlock.js/cascade\"));\n\n const listener = (event: DevtoolsQueryEvent) => hooks.onQuery(currentRequestId(), event);\n\n dataSourceRegistry.on(\"query\", listener);\n disposers.push(() => dataSourceRegistry.off(\"query\", listener));\n } catch {\n // Cascade is an optional peer: without it there are no queries to capture.\n }\n\n try {\n const channel = new (class extends LogChannel {\n public override name = \"devtools-monitor\";\n public active = true;\n\n public log(data: LoggingData): void {\n if (!this.active) return;\n\n const level = toLevel(data.type);\n const text = typeof data.message === \"string\" ? data.message : String(data.message);\n\n hooks.onLog(currentRequestId(), {\n level,\n module: data.module,\n action: data.action,\n // Error lines feed the Errors tab's groups: they lose quoted values, emails and documents.\n message: level === \"error\" ? scrubErrorText(text, LOG_MESSAGE_MAX) : text,\n at: Date.now(),\n });\n }\n })();\n\n log.addChannel(channel);\n // `Logger` cannot remove a channel: a disposed one ignores further entries.\n disposers.push(() => {\n channel.active = false;\n });\n } catch (error) {\n warnFailed(\"log\", error);\n }\n\n try {\n let cache: {\n on(\n event: (typeof CACHE_EVENT_TYPES)[number],\n handler: (data: CacheEventData) => void,\n ): unknown;\n off(\n event: (typeof CACHE_EVENT_TYPES)[number],\n handler: (data: CacheEventData) => void,\n ): unknown;\n };\n\n ({ cache } = await import(\"@warlock.js/cache\"));\n\n const handlers = CACHE_EVENT_TYPES.map((type) => {\n const handler = (data: CacheEventData) =>\n hooks.onCache(currentRequestId(), { type, driver: data.driver, at: Date.now() });\n\n cache.on(type, handler);\n\n return { type, handler };\n });\n\n disposers.push(() => {\n for (const { type, handler } of handlers) cache.off(type, handler);\n });\n } catch {\n // The cache package is an optional peer.\n }\n\n engine.startWriter();\n\n const dispose: DevtoolsDisposer = () => {\n for (const disposer of disposers.splice(0)) disposer();\n\n engine.stopWriter();\n detach = undefined;\n };\n\n detach = dispose;\n\n return dispose;\n },\n\n async dispose() {\n detach?.();\n await engine.flush();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAgB,uBACd,WACA,OAOkB;CAClB,MAAM,QAAQ,YAA6B;EACzC,MAAM,SACH,QAAQ,WAAW,UAAa,QAAQ,UAAU,OAAQ,QAAQ,UAAU;EAC/E,MAAM,QAAQ,QAAQ,SAAS;EAE/B,KAAK,MAAM,SAAS,QAAQ,SAAS;GACnC,MAAM,QAAQ,OAAO;IACnB,OAAO,MAAM;IACb,QAAQ,MAAM;IACd,YAAY,MAAM;IAClB,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WJ,CAAC,CAAE,SAAU,MAAM,OAAO;IAE1B,MAAM,WAAW,kBAAkB,KAAK,SAAS;KAC/C,MAAM,WAAW,SACf,MAAM,QAAQ,iBAAiB,GAAG;MAAE;MAAM,QAAQ,KAAK;MAAQ,IAAI,KAAK,IAAI;KAAE,CAAC;KAEjF,MAAM,GAAG,MAAM,OAAO;KAEtB,OAAO;MAAE;MAAM;KAAQ;IACzB,CAAC;IAED,UAAU,WAAW;KACnB,KAAK,MAAM,EAAE,MAAM,aAAa,UAAU,MAAM,IAAI,MAAM,OAAO;IACnE,CAAC;GACH,QAAQ,CAER;GAEA,OAAO,YAAY;GAEnB,MAAM,gBAAkC;IACtC,KAAK,MAAM,YAAY,UAAU,OAAO,CAAC,GAAG,SAAS;IAErD,OAAO,WAAW;IAClB,SAAS;GACX;GAEA,SAAS;GAET,OAAO;EACT;EAEA,MAAM,UAAU;GACd,SAAS;GACT,MAAM,OAAO,MAAM;EACrB;CACF;AACF"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const require_query_shape = require("./query-shape-DShKQa0x.cjs");
|
|
2
|
+
|
|
1
3
|
//#region ../../packages/devtools/src/n-plus-one.ts
|
|
2
4
|
/** Finds repeated query shapes whose occurrence count reaches the supplied threshold. */
|
|
3
5
|
function detectNPlusOne(queries, threshold) {
|
|
@@ -31,44 +33,6 @@ function mostFrequentCaller(queries) {
|
|
|
31
33
|
return [...callers.values()].sort((left, right) => right.count - left.count)[0]?.caller;
|
|
32
34
|
}
|
|
33
35
|
|
|
34
|
-
//#endregion
|
|
35
|
-
//#region ../../packages/devtools/src/query-shape.ts
|
|
36
|
-
const numericLiteral = /(?<![\w$])[-+]?(?:\d+(?:\.\d+)?|\.\d+)(?![\w$])/g;
|
|
37
|
-
const quotedLiteral = /'(?:''|[^'])*'/g;
|
|
38
|
-
const dollarQuotedLiteral = /(\$[A-Za-z_]*\$)[\s\S]*?\1/g;
|
|
39
|
-
const postgresShapes = /* @__PURE__ */ new Map();
|
|
40
|
-
const POSTGRES_SHAPE_CACHE = 1e3;
|
|
41
|
-
/** Returns a binding-independent shape for a database query. */
|
|
42
|
-
function queryShape(query) {
|
|
43
|
-
if (query.driver === "postgres") {
|
|
44
|
-
const sql = query.sql ?? "";
|
|
45
|
-
const known = postgresShapes.get(sql);
|
|
46
|
-
if (known !== void 0) return known;
|
|
47
|
-
const shape = sql.replace(quotedLiteral, "?").replace(dollarQuotedLiteral, "?").replace(numericLiteral, "?").replace(/\s+/g, " ").trim();
|
|
48
|
-
if (sql.length <= 4e3) {
|
|
49
|
-
if (postgresShapes.size >= POSTGRES_SHAPE_CACHE) postgresShapes.clear();
|
|
50
|
-
postgresShapes.set(sql, shape);
|
|
51
|
-
}
|
|
52
|
-
return shape;
|
|
53
|
-
}
|
|
54
|
-
return `${query.collection ?? ""}.${query.command ?? ""} ${JSON.stringify(normalizeMongoValue(query.pipeline))}`;
|
|
55
|
-
}
|
|
56
|
-
function normalizeMongoValue(value) {
|
|
57
|
-
if (isMongoLeaf(value)) return "?";
|
|
58
|
-
if (Array.isArray(value)) {
|
|
59
|
-
if (value.every(isMongoLeaf)) return ["?"];
|
|
60
|
-
return value.map(normalizeMongoValue);
|
|
61
|
-
}
|
|
62
|
-
const record = value;
|
|
63
|
-
return Object.fromEntries(Object.keys(record).map((key) => [key, normalizeMongoValue(record[key])]));
|
|
64
|
-
}
|
|
65
|
-
function isMongoLeaf(value) {
|
|
66
|
-
if (value === null || typeof value !== "object") return true;
|
|
67
|
-
if (value instanceof Date) return true;
|
|
68
|
-
const record = value;
|
|
69
|
-
return typeof record.toHexString === "function" || typeof record.$oid === "string";
|
|
70
|
-
}
|
|
71
|
-
|
|
72
36
|
//#endregion
|
|
73
37
|
//#region ../../packages/devtools/src/collector.ts
|
|
74
38
|
const mailLimit = 100;
|
|
@@ -134,7 +98,7 @@ function createCollector(options) {
|
|
|
134
98
|
const stored = {
|
|
135
99
|
...query,
|
|
136
100
|
id: `q${++querySequence}`,
|
|
137
|
-
shape: queryShape(query)
|
|
101
|
+
shape: require_query_shape.queryShape(query)
|
|
138
102
|
};
|
|
139
103
|
const request = requestId ? requests.get(requestId) : void 0;
|
|
140
104
|
if (request) request.queries.push(stored);
|
|
@@ -262,10 +226,4 @@ Object.defineProperty(exports, "detectNPlusOne", {
|
|
|
262
226
|
return detectNPlusOne;
|
|
263
227
|
}
|
|
264
228
|
});
|
|
265
|
-
|
|
266
|
-
enumerable: true,
|
|
267
|
-
get: function () {
|
|
268
|
-
return queryShape;
|
|
269
|
-
}
|
|
270
|
-
});
|
|
271
|
-
//# sourceMappingURL=collector-CJbQbzzK.cjs.map
|
|
229
|
+
//# sourceMappingURL=collector-BfC4v87v.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"collector-BfC4v87v.cjs","names":["queryShape"],"sources":["../../../../../../../packages/devtools/src/n-plus-one.ts","../../../../../../../packages/devtools/src/collector.ts"],"sourcesContent":["import type { DevtoolsCallerLocation, DevtoolsQuery, DevtoolsWarning } from \"./types\";\n\n/** Finds repeated query shapes whose occurrence count reaches the supplied threshold. */\nexport function detectNPlusOne(queries: DevtoolsQuery[], threshold: number): DevtoolsWarning[] {\n const groups = new Map<string, DevtoolsQuery[]>();\n for (const query of queries) groups.set(query.shape, [...(groups.get(query.shape) ?? []), query]);\n\n return [...groups.entries()]\n .filter(([, grouped]) => grouped.length >= threshold)\n .sort(([, left], [, right]) => right.length - left.length)\n .map(([shape, grouped]) => ({\n type: \"n+1\" as const,\n shape,\n count: grouped.length,\n message: `N+1: ${grouped.length}× \"${truncate(shape, 120)}\"`,\n ...(mostFrequentCaller(grouped) ? { caller: mostFrequentCaller(grouped) } : {}),\n }));\n}\n\nfunction truncate(value: string, maximum: number): string {\n return value.length > maximum ? `${value.slice(0, maximum - 1)}…` : value;\n}\n\nfunction mostFrequentCaller(queries: DevtoolsQuery[]): DevtoolsCallerLocation | undefined {\n const callers = new Map<string, { caller: DevtoolsCallerLocation; count: number }>();\n for (const query of queries) {\n if (!query.caller) continue;\n const key = `${query.caller.file}:${query.caller.line}`;\n const found = callers.get(key);\n callers.set(\n key,\n found ? { ...found, count: found.count + 1 } : { caller: query.caller, count: 1 },\n );\n }\n return [...callers.values()].sort((left, right) => right.count - left.count)[0]?.caller;\n}\n","import type {\n DevtoolsBackground,\n DevtoolsCollector,\n DevtoolsDisposer,\n DevtoolsLogEntry,\n DevtoolsMail,\n DevtoolsMailSummary,\n DevtoolsQuery,\n DevtoolsRequest,\n DevtoolsRequestSummary,\n DevtoolsStreamEvent,\n ResolvedDevtoolsOptions,\n} from \"./types\";\nimport { detectNPlusOne } from \"./n-plus-one\";\nimport { queryShape } from \"./query-shape\";\n\nconst mailLimit = 100;\nconst logLimit = 1000;\nconst backgroundLimit = 500;\n\n/**\n * Creates the in-memory devtools store.\n *\n * Read methods return shallow structural copies, including copied arrays, so consumers\n * cannot mutate collector-owned arrays. The individual nested entries are retained.\n */\nexport function createCollector(options: ResolvedDevtoolsOptions): DevtoolsCollector {\n const requests = new Map<string, DevtoolsRequest>();\n const mails = new Map<string, DevtoolsMail>();\n const logs: DevtoolsLogEntry[] = [];\n const background: DevtoolsBackground = { queries: [], cache: [], logs: [] };\n const listeners = new Set<(event: DevtoolsStreamEvent) => void>();\n let querySequence = 0;\n\n const emit = (event: DevtoolsStreamEvent) => {\n for (const listener of listeners) {\n try {\n listener(event);\n } catch {\n /* Subscribers must not affect collection. */\n }\n }\n };\n\n const addBackground = <T>(list: T[], value: T) => {\n list.push(value);\n if (list.length > backgroundLimit) list.shift();\n };\n\n return {\n startRequest(request) {\n requests.delete(request.id);\n requests.set(request.id, {\n ...request,\n phases: [],\n queries: [],\n cache: [],\n logs: [],\n mails: [],\n warnings: [],\n });\n while (requests.size > options.maxRequests)\n requests.delete(requests.keys().next().value as string);\n },\n endRequest(id, result) {\n const request = requests.get(id);\n if (!request) return;\n request.status = result.status;\n request.durationMs = result.durationMs;\n request.error = result.error;\n if (result.route !== undefined) request.route = result.route;\n request.warnings = detectNPlusOne(request.queries, options.nPlusOneThreshold);\n emit({ type: \"request\", data: summary(request) });\n },\n addPhase(requestId, phase) {\n requests.get(requestId)?.phases.push(phase);\n },\n addQuery(requestId, query) {\n const stored: DevtoolsQuery = {\n ...query,\n id: `q${++querySequence}`,\n shape: queryShape(query),\n };\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.queries.push(stored);\n else addBackground(background.queries, stored);\n return stored;\n },\n addCacheOperation(requestId, operation) {\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.cache.push(operation);\n else addBackground(background.cache, operation);\n },\n addLog(requestId, entry) {\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.logs.push(entry);\n else addBackground(background.logs, entry);\n logs.unshift(entry);\n if (logs.length > logLimit) logs.pop();\n emit({ type: \"log\", data: entry });\n },\n addMail(mail) {\n mails.delete(mail.id);\n mails.set(mail.id, mail);\n while (mails.size > mailLimit) mails.delete(mails.keys().next().value as string);\n if (mail.requestId) requests.get(mail.requestId)?.mails.push(mail.id);\n emit({ type: \"mail\", data: mailSummary(mail) });\n },\n listRequests() {\n return [...requests.values()].reverse().map(summary);\n },\n getRequest(id) {\n const request = requests.get(id);\n return request && copyRequest(request);\n },\n listMails() {\n return [...mails.values()].reverse().map(mailSummary);\n },\n getMail(id) {\n const mail = mails.get(id);\n return (\n mail && {\n ...mail,\n to: [...mail.to],\n cc: [...mail.cc],\n bcc: [...mail.bcc],\n headers: { ...mail.headers },\n attachments: [...mail.attachments],\n }\n );\n },\n listLogs(filter = {}) {\n const module = filter.module?.toLowerCase();\n return logs\n .filter(\n (entry) =>\n (!filter.level || entry.level === filter.level) &&\n (!module || entry.module.toLowerCase().includes(module)),\n )\n .map((entry) => ({ ...entry }));\n },\n getBackground() {\n return {\n queries: [...background.queries],\n cache: [...background.cache],\n logs: [...background.logs],\n };\n },\n subscribe(listener): DevtoolsDisposer {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n clear() {\n requests.clear();\n mails.clear();\n logs.length = 0;\n background.queries.length = 0;\n background.cache.length = 0;\n background.logs.length = 0;\n },\n };\n}\n\nfunction summary(request: DevtoolsRequest): DevtoolsRequestSummary {\n const { id, method, path, route, status, startedAt, durationMs } = request;\n return {\n id,\n method,\n path,\n route,\n status,\n startedAt,\n durationMs,\n queryCount: request.queries.length,\n warningCount: request.warnings.length,\n };\n}\n\nfunction mailSummary(mail: DevtoolsMail): DevtoolsMailSummary {\n const { id, requestId, capturedAt, to, subject } = mail;\n return { id, requestId, capturedAt, to: [...to], subject };\n}\n\nfunction copyRequest(request: DevtoolsRequest): DevtoolsRequest {\n return {\n ...request,\n phases: [...request.phases],\n queries: [...request.queries],\n cache: [...request.cache],\n logs: [...request.logs],\n mails: [...request.mails],\n warnings: [...request.warnings],\n };\n}\n"],"mappings":";;;;AAGA,SAAgB,eAAe,SAA0B,WAAsC;CAC7F,MAAM,yBAAS,IAAI,IAA6B;CAChD,KAAK,MAAM,SAAS,SAAS,OAAO,IAAI,MAAM,OAAO,CAAC,GAAI,OAAO,IAAI,MAAM,KAAK,KAAK,CAAC,GAAI,KAAK,CAAC;CAEhG,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,QAAQ,GAAG,aAAa,QAAQ,UAAU,SAAS,CAAC,CACpD,MAAM,GAAG,OAAO,GAAG,WAAW,MAAM,SAAS,KAAK,MAAM,CAAC,CACzD,KAAK,CAAC,OAAO,cAAc;EAC1B,MAAM;EACN;EACA,OAAO,QAAQ;EACf,SAAS,QAAQ,QAAQ,OAAO,KAAK,SAAS,OAAO,GAAG,EAAE;EAC1D,GAAI,mBAAmB,OAAO,IAAI,EAAE,QAAQ,mBAAmB,OAAO,EAAE,IAAI,CAAC;CAC/E,EAAE;AACN;AAEA,SAAS,SAAS,OAAe,SAAyB;CACxD,OAAO,MAAM,SAAS,UAAU,GAAG,MAAM,MAAM,GAAG,UAAU,CAAC,EAAE,KAAK;AACtE;AAEA,SAAS,mBAAmB,SAA8D;CACx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,UAA4B;GACpC,UAAU,IAAI,QAAQ;GACtB,aAAa,UAAU,OAAO,QAAQ;EACxC;EACA,QAAQ;GACN,SAAS,MAAM;GACf,MAAM,MAAM;GACZ,KAAK,SAAS;GACd,WAAW,QAAQ,SAAS;GAC5B,WAAW,MAAM,SAAS;GAC1B,WAAW,KAAK,SAAS;EAC3B;CACF;AACF;AAEA,SAAS,QAAQ,SAAkD;CACjE,MAAM,EAAE,IAAI,QAAQ,MAAM,OAAO,QAAQ,WAAW,eAAe;CACnE,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA,YAAY,QAAQ,QAAQ;EAC5B,cAAc,QAAQ,SAAS;CACjC;AACF;AAEA,SAAS,YAAY,MAAyC;CAC5D,MAAM,EAAE,IAAI,WAAW,YAAY,IAAI,YAAY;CACnD,OAAO;EAAE;EAAI;EAAW;EAAY,IAAI,CAAC,GAAG,EAAE;EAAG;CAAQ;AAC3D;AAEA,SAAS,YAAY,SAA2C;CAC9D,OAAO;EACL,GAAG;EACH,QAAQ,CAAC,GAAG,QAAQ,MAAM;EAC1B,SAAS,CAAC,GAAG,QAAQ,OAAO;EAC5B,OAAO,CAAC,GAAG,QAAQ,KAAK;EACxB,MAAM,CAAC,GAAG,QAAQ,IAAI;EACtB,OAAO,CAAC,GAAG,QAAQ,KAAK;EACxB,UAAU,CAAC,GAAG,QAAQ,QAAQ;CAChC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors-DNQ-g49I.cjs","names":["randomBytes"],"sources":["../../../../../../../packages/devtools/src/production/contracts.ts","../../../../../../../packages/devtools/src/production/errors.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: { name: string; counts: Record<string, number> }[];\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n /** Whether the panel declares a shared view (`DevtoolsPanel.share`); always `false` for built-in tabs. */\n shareable: boolean;\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n *\n * The AI section (`ai-reports`, `ai`, `agents`, `ai-models`, `ai-errors`,\n * `ai-evaluate`) sits under \"AI\" in the sidebar. `ai` keeps its id (it is the\n * Runs page) so existing links and `production.panels.ai` keep working. In\n * production the three report tabs show only when the AI feed is available\n * (Panoptic loads), unless `production.panels` turns one on explicitly.\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai-reports\", title: \"Reports\", production: true },\n { id: \"ai\", title: \"Runs\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"ai-models\", title: \"Models\", production: true },\n { id: \"ai-errors\", title: \"Errors\", production: true },\n { id: \"ai-evaluate\", title: \"Evaluate\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n /** Read-only share links: `enabled` mirrors `production.share.enabled`; `null` when signed out and in development. */\n share: { enabled: boolean } | null;\n /** The installed `@warlock.js/core` version; `null` when signed out or not found. */\n warlockVersion: string | null;\n /** The app's own `package.json` name and version (nothing else is read); `null` when signed out or not found. */\n app: { name: string; version: string } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\n/** Where a share link stands. `revoked` wins over `expired`. */\nexport type DevtoolsShareStatus = \"active\" | \"expired\" | \"revoked\";\n\n/** A share link as the admin screen shows it (never the token or its hash). */\nexport type DevtoolsShareView = {\n id: string;\n /** The id of the panel the link opens. */\n panel: string;\n /** What the admin called it, 1-80 characters. */\n label: string;\n /** The email of the admin who made it; `null` when that account is gone. */\n createdBy: string | null;\n createdAt: number;\n expiresAt: number;\n revokedAt: number | null;\n lastUsedAt: number | null;\n /** How many times the link was used, counted at most once a minute. */\n uses: number;\n status: DevtoolsShareStatus;\n};\n\n/** `GET api/admin/shares`. */\nexport type DevtoolsShareList = {\n enabled: boolean;\n /** The longest life a link may have, in days. */\n maxDays: number;\n /** The panels that declare a shared view. */\n panels: { id: string; title: string }[];\n /** Newest first. */\n shares: DevtoolsShareView[];\n};\n\n/** `POST api/admin/shares` body. `label` is 1-80 characters, `days` a whole number from 1 to `maxDays`. */\nexport type DevtoolsShareCreateInput = { panel: string; label: string; days: number };\n\n/** `POST api/admin/shares`: the URL (with the token in its fragment) appears only in this answer. */\nexport type DevtoolsCreatedShare = { share: DevtoolsShareView; url: string };\n\n/**\n * What a share link opens, answered by `POST api/share/open` and\n * `GET api/share/info`: the panel and the names the shared view may load.\n */\nexport type DevtoolsShareOpenAnswer = {\n panel: string;\n /** The panel's title. */\n title: string;\n label: string;\n expiresAt: number;\n /** Served names from the panel's `assets` the shared page may load. */\n assets: string[];\n /** Whether the shared page may load images from the panel's `files`. */\n files: boolean;\n};\n\n/** The longest label of a share link. */\nexport const DEVTOOLS_SHARE_LABEL_MAX = 80;\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\"\n | \"share.created\"\n | \"share.revoked\"\n | \"share.failed\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n \"share.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"share.not-found\"\n | \"stream.too-many\"\n | \"ai.range-invalid\"\n | \"ai.evaluate-unavailable\"\n | \"ai.prompt-not-found\"\n | \"ai.evaluate-failed\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n\n// ---------------------------------------------------------------------------\n// AI section: reports, runs, models, errors, evaluate\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets of the AI rollups.\n * Model calls take seconds, so these differ from `DEVTOOLS_LATENCY_BUCKETS_MS`.\n * A histogram has one more count than this list: the last counts everything\n * above five minutes. Fixed bounds make rollups from several processes add up\n * exactly. Changing them is a breaking change of the stored rollups.\n */\nexport const DEVTOOLS_AI_LATENCY_BUCKETS_MS = [\n 250, 500, 1000, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 30000, 45000, 60000, 120000, 300000,\n] as const;\n\n/** The date-range presets of the Reports, Models and Errors pages. */\nexport type DevtoolsAiRangePreset = \"24h\" | \"7d\" | \"30d\";\n\n/** The range a report covers, after the server aligned it to its buckets. */\nexport type DevtoolsAiResolvedRange = {\n preset: DevtoolsAiRangePreset | \"custom\";\n /** Inclusive start, on an hour boundary. */\n from: number;\n /** Exclusive end, on an hour boundary. */\n to: number;\n /** Bucket width of the charts: 1 hour, 6 hours or 1 day. */\n stepMs: number;\n /** The browser's offset from UTC (minutes east), used to align day buckets. */\n utcOffsetMinutes: number;\n};\n\n/** Why an AI page has nothing to show; `title`, `message` and `command` are written for the page. */\nexport type DevtoolsAiUnavailableReasonView =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\"\n | \"table-missing\"\n | \"reports-off\";\n\n/** The answer of any AI route that cannot serve its data. */\nexport type DevtoolsAiUnavailableView = {\n available: false;\n reason: DevtoolsAiUnavailableReasonView;\n title: string;\n message: string;\n /** A command or config line to copy; `null` when there is none. */\n command: string | null;\n /** The load error and versions for `panoptic-failed`; otherwise `null`. */\n detail: string | null;\n};\n\n/** Token counts. `input` is the whole prompt (cache reads and writes included) on every provider. */\nexport type DevtoolsAiTokenTotals = {\n input: number;\n output: number;\n /** Prompt tokens read from the provider's cache (part of `input`). */\n cached: number;\n /** Prompt tokens written to the provider's cache (part of `input`). */\n cacheWrite: number;\n /** Reasoning tokens (part of `output`). */\n reasoning: number;\n};\n\n/**\n * Estimated cost. `estimatedUsd` sums only runs whose model has pricing; runs\n * that used tokens on a model without pricing are counted in `unpricedRuns`\n * and `unpricedTokens`, never as zero cost.\n */\nexport type DevtoolsAiCostTotals = {\n estimatedUsd: number;\n pricedRuns: number;\n unpricedRuns: number;\n unpricedTokens: number;\n};\n\n/** Latency from the bucketed histogram: each figure is a bucket's upper bound (`null` with no runs). */\nexport type DevtoolsAiLatencyTotals = {\n p50Ms: number | null;\n p95Ms: number | null;\n meanMs: number | null;\n};\n\n/** Totals over a range (or one row of a breakdown). */\nexport type DevtoolsAiTotals = {\n runs: number;\n completed: number;\n failed: number;\n /** Runs that stopped early: `incomplete` and `max-iterations`. */\n incomplete: number;\n cancelled: number;\n /** `(failed + incomplete) / runs`, from 0 to 1; 0 with no runs. Cancelled runs are not errors. */\n errorRate: number;\n tokens: DevtoolsAiTokenTotals;\n cost: DevtoolsAiCostTotals;\n latency: DevtoolsAiLatencyTotals;\n /** Runs where a `fallbackModel()` chain answered from a later model at least once. */\n fallbackRuns: number;\n /** Runs where the provider refused at least once (finish reason `refusal` or a content filter). */\n refusals: number;\n};\n\n/**\n * Time series for a stacked chart: `values[i]` belongs to `buckets[i]`. At\n * most five named series; the rest are summed into one `other` series.\n */\nexport type DevtoolsAiSeriesSet = {\n /** Bucket starts, oldest first. */\n buckets: number[];\n series: {\n /** Stable identity (`provider/model`, an agent name, a category); the UI keys colours on it. */\n key: string;\n label: string;\n values: number[];\n /** `true` for the summed \"Other\" series. */\n other: boolean;\n }[];\n};\n\n/** One bucket of the error-rate line. */\nexport type DevtoolsAiRatePoint = {\n at: number;\n runs: number;\n /** Failed plus incomplete runs. */\n errors: number;\n /** `errors / runs`; `null` for a bucket without runs (the line has a gap there). */\n rate: number | null;\n};\n\n/** A row of the top agents or top models table. */\nexport type DevtoolsAiBreakdownRow = {\n /** The agent name, or `provider/model`. */\n key: string;\n label: string;\n /** The provider for a model row; `null` for an agent row. */\n provider: string | null;\n totals: DevtoolsAiTotals;\n /** Share of the range's estimated cost, 0 to 1 (share of runs when nothing was priced). */\n share: number;\n};\n\n/** The filter values present in a range, for the filter row. */\nexport type DevtoolsAiFilterOptions = {\n agents: string[];\n /** `provider/model` keys. */\n models: string[];\n providers: string[];\n};\n\n/** `GET api/ai/reports`. */\nexport type DevtoolsAiReportView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n /** The period of the same length just before `range`. */\n previousRange: { from: number; to: number };\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** Estimated USD per bucket, by model (top five plus Other). */\n costByModel: DevtoolsAiSeriesSet;\n /** Tokens per bucket: series `uncached`, `cached`, `output`. */\n tokens: DevtoolsAiSeriesSet;\n errorRate: DevtoolsAiRatePoint[];\n /** Up to 10 rows, highest estimated cost first (most runs when nothing was priced). */\n topAgents: DevtoolsAiBreakdownRow[];\n topModels: DevtoolsAiBreakdownRow[];\n /** `provider/model` keys that used tokens without pricing in the range. */\n unpricedModels: string[];\n filters: DevtoolsAiFilterOptions;\n /** `true` when `@warlock.js/ai` observes nothing, so new runs are not counted. */\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Whether a model's runs carried pricing in the range; `no-tokens` when no run used tokens. */\nexport type DevtoolsAiPricingState = \"set\" | \"missing\" | \"partial\" | \"no-tokens\";\n\n/** One row of the Models page. */\nexport type DevtoolsAiModelRow = {\n /** `provider/model`. */\n key: string;\n model: string;\n provider: string;\n totals: DevtoolsAiTotals;\n pricing: DevtoolsAiPricingState;\n /** Estimated USD per priced run; `null` when no run was priced. */\n costPerRunUsd: number | null;\n /** `fallbackRuns / runs`, 0 to 1. */\n fallbackRate: number;\n /** Agents that used the model, most runs first (at most 5). */\n agents: string[];\n /** Start of the last hour with a run. */\n lastSeenAt: number;\n};\n\n/** `GET api/ai/models`. */\nexport type DevtoolsAiModelsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n /** Most runs first. */\n models: DevtoolsAiModelRow[];\n /** Runs per bucket by model (top five plus Other). */\n runsByModel: DevtoolsAiSeriesSet;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** How failed runs are grouped on the Errors page. */\nexport type DevtoolsAiErrorCategory =\n | \"rate-limit\"\n | \"timeout\"\n | \"refusal\"\n | \"provider\"\n | \"budget\"\n | \"tool\"\n | \"schema\"\n | \"incomplete\"\n | \"other\";\n\n/** Every category, in the order the Errors page lists them. */\nexport const DEVTOOLS_AI_ERROR_CATEGORIES = [\n \"rate-limit\",\n \"timeout\",\n \"refusal\",\n \"provider\",\n \"budget\",\n \"tool\",\n \"schema\",\n \"incomplete\",\n \"other\",\n] as const satisfies readonly DevtoolsAiErrorCategory[];\n\n/** One category of failed runs. */\nexport type DevtoolsAiErrorGroup = {\n category: DevtoolsAiErrorCategory;\n /** \"Rate limit\", \"Timeout\", \"Refusal\", \"Provider error\", \"Budget\", \"Tool failed\", \"Invalid output\", \"Incomplete\", \"Other\". */\n label: string;\n count: number;\n /** Share of all failed runs in the range, 0 to 1. */\n share: number;\n previousCount: number;\n /** At most 5 each, most first. */\n byModel: { key: string; count: number }[];\n byAgent: { key: string; count: number }[];\n};\n\n/** A recent failed run (development only: production keeps no run details). */\nexport type DevtoolsAiFailedRun = {\n traceId: string;\n /** The agent span that failed. */\n agent: string;\n /** `provider/model`, or `null` when unreported. */\n model: string | null;\n status: string;\n category: DevtoolsAiErrorCategory;\n /** The error code (`PROVIDER_RATE_LIMIT`) or error name. */\n code: string | null;\n /** The error message, secrets scrubbed, at most 300 characters. */\n message: string | null;\n endedAt: number;\n requestId: string | null;\n};\n\n/** `GET api/ai/errors`. */\nexport type DevtoolsAiErrorsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n /** Categories with at least one failed run, most first. */\n groups: DevtoolsAiErrorGroup[];\n /** Failed runs per bucket by category (top five plus Other). */\n overTime: DevtoolsAiSeriesSet;\n /** Newest first, at most 50; `null` in production. */\n recent: DevtoolsAiFailedRun[] | null;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Usage of one run as the Runs page shows it. */\nexport type DevtoolsAiUsageView = {\n input: number;\n output: number;\n total: number;\n cachedTokens: number | null;\n cacheWriteTokens: number | null;\n /** `false` when `input` excludes cache tokens (the provider reports them on top). */\n inputIncludesCache: boolean | null;\n};\n\n/** One row of the Runs page (a Panoptic trace, content-free). */\nexport type DevtoolsAiRunRow = {\n traceId: string;\n requestId: string | null;\n sessionId: string | null;\n name: string;\n /** The root span type: `agent`, `workflow`, `supervisor`, … */\n type: string;\n status: string;\n startedAt: string;\n duration: number;\n usage: DevtoolsAiUsageView;\n /** Estimated USD; `null` when the run carried no pricing. */\n cost: number | null;\n models: string[];\n /** `promptName@promptVersion` of the root agent, or `null`. */\n promptKey: string | null;\n toolCalls: number;\n retries: number;\n incomplete: boolean;\n};\n\n/** A group of the Runs page (`groupBy=session|prompt|type`). */\nexport type DevtoolsAiRunGroup = {\n key: string;\n label: string;\n runs: number;\n failed: number;\n estimatedCostUsd: number;\n p95Ms: number | null;\n /** Trace ids of the group, newest first (at most 50). */\n traceIds: string[];\n};\n\n/** `GET api/ai/runs`. */\nexport type DevtoolsAiRunsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Newest first, at most `limit` (default 200). */\n runs: DevtoolsAiRunRow[];\n /** `null` unless `groupBy` was given. */\n groups: DevtoolsAiRunGroup[] | null;\n stats: {\n /** Runs matching the filter (before `limit`). */\n count: number;\n failed: number;\n /** Priced runs only. */\n estimatedCostUsd: number;\n /** Runs that used tokens on a model without pricing (not in `estimatedCostUsd`). */\n unpricedRuns: number;\n p50Ms: number | null;\n p95Ms: number | null;\n };\n /** How many traces the dashboard keeps (`maxRequests`). */\n capacity: number;\n };\n\n/** A distinct system prompt seen in recent agent runs (the Evaluate picker). */\nexport type DevtoolsAiEvaluatePrompt = {\n /** The prompt's hash from the agent trace. */\n hash: string;\n /** Agents that used it, most recent first. */\n agents: string[];\n /** The newest run that carried its text. */\n runId: string;\n lastSeenAt: string;\n /** The first 200 characters. */\n preview: string;\n length: number;\n};\n\n/** `GET api/ai/evaluate`. */\nexport type DevtoolsAiEvaluateView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Whether `panoptic.evaluate` (or `panoptic.dashboard.evaluate`) has a judge model. */\n configured: boolean;\n /** The judge model as `provider/name`; `null` when not configured. */\n judge: string | null;\n /** The configured default grading instructions; `\"\"` when none. */\n instructions: string;\n /** Newest first, at most 50. */\n prompts: DevtoolsAiEvaluatePrompt[];\n };\n\n/** `POST api/ai/evaluate` body: exactly one of `runId` and `systemPrompt`. */\nexport type DevtoolsAiEvaluateRequest = {\n /** An agent run whose system prompt text is kept. */\n runId?: string;\n /** A pasted prompt, 1 to 100,000 characters. */\n systemPrompt?: string;\n /** Overrides the configured instructions for this run; at most 4,000 characters. */\n instructions?: string;\n};\n\n/** `POST api/ai/evaluate` answer. */\nexport type DevtoolsAiEvaluateResult = {\n /** 0 to 1; `null` when the judge returned no score. */\n score: number | null;\n issues: string[];\n /** The judge model as `provider/name`. */\n judge: string;\n durationMs: number;\n};\n","import { randomBytes } from \"node:crypto\";\nimport type { DevtoolsApiErrorBody, DevtoolsErrorCode } from \"./contracts\";\n\n/**\n * Why production mode refused to start. Each code names one missing or\n * invalid setting; the message says which and how to fix it.\n */\nexport const DEVTOOLS_CONFIG_CODES = {\n DT001:\n \"Devtools production mode needs a dashboard path. Set DEVTOOLS_PATH (for example /ops-7f3k2q) or devtools.production.path.\",\n DT002:\n 'The devtools dashboard path must start with \"/\", be at least 8 characters, use only letters, digits, \"-\", \"_\", \".\", \"~\" and \"/\", and not be \"/__warlock\".',\n DT003:\n \"Devtools production mode has no admin yet. Set DEVTOOLS_ADMIN_EMAIL with DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin --email <email>`.\",\n DT004:\n \"DEVTOOLS_ADMIN_PASSWORD does not meet the password rules (the minimum length, at most 72 bytes, not a common password unless `passwords.rejectCommon` is false, not the email). Choose another one.\",\n DT005:\n \"Devtools production mode stores its accounts in the database. Install @warlock.js/cascade and configure a database connection.\",\n DT006:\n \"Devtools production mode encrypts two-factor secrets with the app key. Set encryption.key (64 hex characters) in src/config/encryption.ts.\",\n DT007:\n \"A devtools production option has an invalid value. The message names the option and the accepted values.\",\n DT008:\n \"The devtools tables are missing. Add devtoolsMigrations from @warlock.js/devtools/production to database.migrations in warlock.config.ts and run `warlock migrate`.\",\n DT009: \"Set either DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, not both.\",\n DT010:\n \"DEVTOOLS_SETUP_TOKEN must be at least 32 characters. Generate one with: openssl rand -base64 32\",\n} as const;\n\n/** A production configuration error code (`DT001`–`DT010`). */\nexport type DevtoolsConfigCode = keyof typeof DEVTOOLS_CONFIG_CODES;\n\n/**\n * Thrown while the devtools connector boots in production when the monitor is\n * enabled but cannot start safely. It stops the app from booting, so a\n * misconfigured deploy fails at once instead of serving an unprotected\n * dashboard.\n */\nexport class DevtoolsProductionConfigError extends Error {\n public readonly code: DevtoolsConfigCode;\n\n public constructor(code: DevtoolsConfigCode, detail?: string) {\n super(`[${code}] ${detail ? `${detail} ` : \"\"}${DEVTOOLS_CONFIG_CODES[code]}`);\n this.name = \"DevtoolsProductionConfigError\";\n this.code = code;\n }\n}\n\n/** The message every API error code answers with: what failed and what to do next. */\nexport const DEVTOOLS_ERROR_MESSAGES: Record<DevtoolsErrorCode, string> = {\n \"auth.invalid-credentials\":\n \"The email or password is not correct. Check both and try again; after several failed tries, wait 15 minutes.\",\n \"auth.invalid-code\":\n \"The code is not correct or has expired. Enter the current 6-digit code from your authenticator app, or a recovery code.\",\n \"auth.invalid-setup-token\":\n \"This setup link is not valid. Use the link built from DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin`.\",\n \"auth.password-too-short\":\n \"Use a longer password. The minimum length is set by passwords.minLength (8 characters by default).\",\n \"auth.password-too-long\": \"Use a password of at most 72 bytes (about 72 letters).\",\n \"auth.password-common\": \"This password is too common. Choose one that is harder to guess.\",\n \"auth.password-same-as-email\": \"The password must not be your email address. Choose another one.\",\n \"auth.password-unchanged\": \"Choose a new password that differs from the current one.\",\n \"auth.wrong-current-password\": \"The current password is not correct. Enter it again.\",\n \"auth.busy\": \"The server is busy checking other sign-ins. Wait a few seconds and try again.\",\n \"invite.invalid\":\n \"This invite link is not valid, was already used, or has expired. Ask an admin for a new one.\",\n \"invite.email-taken\": \"An account with this email already exists. Sign in instead.\",\n \"account.not-found\": \"This account no longer exists. Reload the list.\",\n \"account.last-admin\": \"This is the last admin. Make another account an admin first.\",\n \"account.self\": \"You cannot do this to your own account. Ask another admin.\",\n \"account.last-factor\":\n \"This is your only second factor. Add another one (an authenticator app or a passkey) before removing it.\",\n \"role.forbidden\": \"Only admins can do this. Ask an admin.\",\n \"csrf.invalid\": \"This page is out of date. Reload the dashboard and try again.\",\n \"passkey.unavailable\":\n \"Passkeys are not available on this server (the @simplewebauthn/server package is not installed). Use an authenticator app instead.\",\n \"passkey.failed\": \"The passkey could not be verified. Try again, or use your authenticator app.\",\n \"explain.not-allowed\": \"Only admins can run EXPLAIN. Ask an admin.\",\n \"explain.unsupported\":\n \"This query cannot be explained: only PostgreSQL SELECT/WITH queries and MongoDB find, aggregate and count commands can.\",\n \"explain.elsewhere\":\n \"Only the instance that ran this query can explain it, and this request reached another one. Try again later or from that instance.\",\n \"explain.failed\":\n \"The database could not explain this query. The reference is in the server log.\",\n \"request.not-found\":\n \"This request is no longer stored. Requests are kept for a limited time (24 hours by default).\",\n \"request.invalid-filter\": \"A filter value is not valid. Check the status, method and dates.\",\n \"share.not-found\": \"This share link no longer exists or is already revoked. Reload the list.\",\n \"stream.too-many\":\n \"Too many live views are open for this session. Close another dashboard tab and reload.\",\n \"ai.range-invalid\":\n \"The date range is not valid. Pick 24 hours, 7 days or 30 days, or a custom range of at least one hour inside the kept history.\",\n \"ai.evaluate-unavailable\":\n \"Evaluate is not set up. Add panoptic.evaluate with a judge model to src/config/ai.ts, then restart.\",\n \"ai.prompt-not-found\":\n \"This run's system prompt is no longer kept. Pick a newer run or paste the prompt.\",\n \"ai.evaluate-failed\":\n \"The judge model could not grade this prompt. Check its API key and quota; the reference is in the server log.\",\n \"input.invalid\": \"Some fields are missing or not valid. Check the form and try again.\",\n \"server.error\":\n \"The dashboard could not complete this action. Try again; if it keeps failing, give your admin the reference shown.\",\n};\n\n/** The HTTP status each code answers with. */\nexport const DEVTOOLS_ERROR_STATUS: Record<DevtoolsErrorCode, number> = {\n \"auth.invalid-credentials\": 401,\n \"auth.invalid-code\": 401,\n \"auth.invalid-setup-token\": 401,\n \"auth.password-too-short\": 422,\n \"auth.password-too-long\": 422,\n \"auth.password-common\": 422,\n \"auth.password-same-as-email\": 422,\n \"auth.password-unchanged\": 422,\n \"auth.wrong-current-password\": 401,\n \"auth.busy\": 503,\n \"invite.invalid\": 410,\n \"invite.email-taken\": 409,\n \"account.not-found\": 404,\n \"account.last-admin\": 409,\n \"account.self\": 409,\n \"account.last-factor\": 409,\n \"role.forbidden\": 403,\n \"csrf.invalid\": 403,\n \"passkey.unavailable\": 501,\n \"passkey.failed\": 401,\n \"explain.not-allowed\": 403,\n \"explain.unsupported\": 400,\n \"explain.elsewhere\": 409,\n \"explain.failed\": 502,\n \"request.not-found\": 404,\n \"request.invalid-filter\": 400,\n \"share.not-found\": 404,\n \"stream.too-many\": 429,\n \"ai.range-invalid\": 400,\n \"ai.evaluate-unavailable\": 409,\n \"ai.prompt-not-found\": 404,\n \"ai.evaluate-failed\": 502,\n \"input.invalid\": 422,\n \"server.error\": 500,\n};\n\n/** A short reference id (8 characters, base32 alphabet) to quote to support. */\nexport function createErrorRef(): string {\n const alphabet = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\n const bytes = randomBytes(8);\n let ref = \"\";\n\n for (const byte of bytes) ref += alphabet[byte % alphabet.length];\n\n return ref;\n}\n\n/**\n * An error a dashboard route answers with. The production error handler turns\n * it into `{ error, code, ref?, instance? }` with `statusCode`.\n */\nexport class DevtoolsApiError extends Error {\n public readonly code: DevtoolsErrorCode;\n public readonly statusCode: number;\n public readonly ref: string | undefined;\n public readonly instance: string | undefined;\n\n public constructor(\n code: DevtoolsErrorCode,\n options: { ref?: string; instance?: string; cause?: unknown; message?: string } = {},\n ) {\n super(\n options.message ?? DEVTOOLS_ERROR_MESSAGES[code],\n options.cause === undefined ? {} : { cause: options.cause },\n );\n this.name = \"DevtoolsApiError\";\n this.code = code;\n this.statusCode = DEVTOOLS_ERROR_STATUS[code];\n this.ref = options.ref;\n this.instance = options.instance;\n }\n\n /** The JSON body this error answers with. */\n public toBody(): DevtoolsApiErrorBody {\n return {\n error: this.message,\n code: this.code,\n ...(this.ref === undefined ? {} : { ref: this.ref }),\n ...(this.instance === undefined ? {} : { instance: this.instance }),\n };\n }\n}\n\n/**\n * Raised by a store when a unique value is taken (an email) so callers can\n * answer with their own error code.\n */\nexport class DevtoolsStoreConflictError extends Error {\n public constructor(public readonly field: string) {\n super(`A devtools record with this ${field} already exists.`);\n this.name = \"DevtoolsStoreConflictError\";\n }\n}\n"],"mappings":";;;;;;;;;AA+DA,MAAa,8BAA8B;CACzC;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;CAAO;AAC/D;;;;;;;;;;;AAsXA,MAAa,2BAA2B;CACtC;EAAE,IAAI;EAAY,OAAO;EAAY,YAAY;CAAK;CACtD;EAAE,IAAI;EAAW,OAAO;EAAW,YAAY;CAAK;CACpD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAa,OAAO;EAAa,YAAY;CAAK;CACxD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAK;CAClD;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAK;CAC9C;EAAE,IAAI;EAAQ,OAAO;EAAQ,YAAY;CAAM;CAC/C;EAAE,IAAI;EAAc,OAAO;EAAW,YAAY;CAAK;CACvD;EAAE,IAAI;EAAM,OAAO;EAAQ,YAAY;CAAM;CAC7C;EAAE,IAAI;EAAU,OAAO;EAAU,YAAY;CAAM;CACnD;EAAE,IAAI;EAAa,OAAO;EAAU,YAAY;CAAK;CACrD;EAAE,IAAI;EAAa,OA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BAAiB;EAD3B;EAEjC,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"errors-DNQ-g49I.cjs","names":["randomBytes"],"sources":["../../../../../../../packages/devtools/src/production/contracts.ts","../../../../../../../packages/devtools/src/production/errors.ts"],"sourcesContent":["/**\n * The contracts of the devtools production monitor: the shapes the server\n * stores, the JSON its API returns, and the few constants both sides share.\n *\n * This file has NO imports, so the dashboard (`ui-src/`) can import its types\n * too. Every timestamp is epoch milliseconds, every duration milliseconds,\n * every size bytes. Absent values are `null`, never missing.\n */\n\n// ---------------------------------------------------------------------------\n// Modes, roles and stages\n// ---------------------------------------------------------------------------\n\n/** Where the dashboard runs: the loopback development dashboard or the signed-in production monitor. */\nexport type DevtoolsMode = \"development\" | \"production\";\n\n/** What an account may do: `admin` manages users and the dashboard, `viewer` reads. */\nexport type DevtoolsRole = \"admin\" | \"viewer\";\n\n/**\n * Where a browser session stands. Only `active` reaches the data routes;\n * every other stage reaches only the sign-in steps it needs next.\n */\nexport type DevtoolsSessionStage =\n | \"signed-out\"\n | \"password-change\"\n | \"mfa-enrol\"\n | \"mfa-verify\"\n | \"active\";\n\n/** How an account's current password was set. `env` and `reset` passwords must be changed at the next sign-in. */\nexport type DevtoolsPasswordSource = \"env\" | \"setup\" | \"invite\" | \"user\" | \"reset\";\n\n// ---------------------------------------------------------------------------\n// Instances\n// ---------------------------------------------------------------------------\n\n/** One process that runs the monitor (a pm2 or cluster worker, a container). */\nexport type DevtoolsInstanceInfo = {\n /** Stable for the life of the process: `<host>:<pid>:<start time base36>`. */\n id: string;\n /** What the dashboard shows: `<host> #<worker>` or `<host> pid <pid>`. */\n label: string;\n host: string;\n pid: number;\n /** pm2's `NODE_APP_INSTANCE` / `pm_id`, or the cluster worker id; `null` when neither is set. */\n worker: string | null;\n startedAt: number;\n /** When the instance last wrote its report (the current time for the instance answering). */\n seenAt: number;\n nodeVersion: string;\n};\n\n// ---------------------------------------------------------------------------\n// Histograms (mergeable across instances)\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets every histogram uses.\n * A histogram's `counts` has one more entry than this list: the last entry\n * counts everything above the highest bound. Fixed bounds make histograms\n * from several instances merge exactly.\n */\nexport const DEVTOOLS_LATENCY_BUCKETS_MS = [\n 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000,\n] as const;\n\n/** A latency histogram over `DEVTOOLS_LATENCY_BUCKETS_MS`. */\nexport type DevtoolsHistogram = {\n /** `DEVTOOLS_LATENCY_BUCKETS_MS.length + 1` entries. */\n counts: number[];\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n// ---------------------------------------------------------------------------\n// Query, route and error statistics\n// ---------------------------------------------------------------------------\n\n/** Statistics for one normalized query shape (literals and bindings replaced by `?`). */\nexport type DevtoolsQueryShapeStats = {\n /** First 16 hex characters of the SHA-256 of `shape`; the id the API and EXPLAIN use. */\n id: string;\n /** The normalized query, at most 2000 characters. Never holds a value. */\n shape: string;\n driver: \"postgres\" | \"mongodb\";\n connection: string;\n count: number;\n errors: number;\n histogram: DevtoolsHistogram;\n /** Sampled requests in which this shape reached the N+1 threshold, and the highest count in one request. */\n nPlusOne: { requests: number; maxPerRequest: number };\n /** The slowest run seen; its values stay in the process that ran it (see EXPLAIN). */\n slowest: {\n durationMs: number;\n at: number;\n route: string | null;\n requestId: string | null;\n instance: string;\n } | null;\n firstSeen: number;\n lastSeen: number;\n /** Whether EXPLAIN can run for this shape (a Postgres `SELECT`/`WITH`, or a MongoDB `find`/`aggregate`/`count`). */\n explainable: boolean;\n};\n\n/** Time spent in one named request phase (middleware, validation, handler, …) on one route. */\nexport type DevtoolsRoutePhaseStats = {\n name: string;\n count: number;\n sumMs: number;\n maxMs: number;\n};\n\n/** Statistics for one route pattern and method. */\nexport type DevtoolsRouteStats = {\n /** `\"<METHOD> <route pattern>\"`, e.g. `\"GET /posts/:slug\"`. */\n key: string;\n method: string;\n route: string;\n count: number;\n /** Responses with a 5xx status or a thrown error. */\n errors: number;\n histogram: DevtoolsHistogram;\n /** At most 30 phases, slowest total first. */\n phases: DevtoolsRoutePhaseStats[];\n slowest: { durationMs: number; at: number; requestId: string | null; instance: string } | null;\n};\n\n/** Errors grouped by fingerprint (normalized message + route + source). */\nexport type DevtoolsErrorGroup = {\n /** First 16 hex characters of the SHA-256 of the fingerprint. */\n id: string;\n /** The latest message as raised, at most 500 characters. */\n message: string;\n /** The error class name when known (`TypeError`). */\n name: string | null;\n source: \"request\" | \"log\";\n route: string | null;\n status: number | null;\n count: number;\n firstSeen: number;\n lastSeen: number;\n lastRequestId: string | null;\n /** The latest stack, at most 4000 characters; `null` when none was available. */\n stack: string | null;\n};\n\n/** A warn/error log entry kept for the Logs panel in production (no context: it may hold values). */\nexport type DevtoolsReportLogEntry = {\n level: \"debug\" | \"info\" | \"warn\" | \"error\" | \"success\";\n module: string;\n action: string;\n /** At most 1000 characters. */\n message: string;\n at: number;\n requestId: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Resources, health, jobs\n// ---------------------------------------------------------------------------\n\n/** One resource reading of a process. */\nexport type DevtoolsResourcePoint = {\n at: number;\n rssBytes: number;\n heapUsedBytes: number;\n heapTotalBytes: number;\n externalBytes: number;\n /** Process CPU time over wall time since the previous point, 0–100 per core (can exceed 100). */\n cpuPercent: number;\n eventLoopDelayP50Ms: number;\n eventLoopDelayP99Ms: number;\n eventLoopDelayMaxMs: number;\n /** `performance.eventLoopUtilization()` since the previous point, 0–1. */\n eventLoopUtilization: number;\n /** Garbage collections since the previous point. */\n gcCount: number;\n /** Total GC pause since the previous point. */\n gcPauseMs: number;\n};\n\n/** The latest resource reading plus values that change rarely. */\nexport type DevtoolsResourceSnapshot = DevtoolsResourcePoint & {\n heapLimitBytes: number;\n uptimeSeconds: number;\n /** Totals since the monitor started, by GC kind. */\n gcByKind: Record<\n \"minor\" | \"major\" | \"incremental\" | \"weakcb\",\n { count: number; pauseMs: number }\n >;\n};\n\n/** Readiness checks (core's `health` registry) of one process, with a short history. */\nexport type DevtoolsHealthReport = {\n status: \"ok\" | \"error\" | \"unknown\";\n checkedAt: number | null;\n checks: Record<string, boolean>;\n /** Newest last, at most 60 entries. */\n history: { at: number; status: \"ok\" | \"error\"; failed: string[] }[];\n};\n\n/** One scheduled job (`@warlock.js/scheduler`). */\nexport type DevtoolsScheduleInfo = {\n name: string;\n /** The cron expression, or `null` for an interval schedule. */\n cron: string | null;\n /** A readable interval such as `\"every 5 minutes\"`, or `null`. */\n interval: string | null;\n isRunning: boolean;\n lastRunAt: number | null;\n nextRunAt: number | null;\n lastDurationMs: number | null;\n lastError: string | null;\n runs: number;\n failures: number;\n /** The latest runs, newest first (at most 10). Absent when the scheduler keeps no history. */\n recentRuns?: DevtoolsScheduleRun[];\n};\n\n/** One recorded run of a scheduled job; the error is a message, never a stack. */\nexport type DevtoolsScheduleRun = {\n startedAt: number;\n durationMs: number;\n outcome: \"success\" | \"failed\" | \"skipped\";\n error?: string;\n skipReason?: string;\n};\n\n/** Background work of one process: schedules and queue counts, each `available: false` when its package is not installed. */\nexport type DevtoolsJobsReport = {\n available: { scheduler: boolean; queue: boolean };\n schedules: DevtoolsScheduleInfo[];\n /** Job counts per queue and state (`waiting`, `active`, `delayed`, `failed`, `completed`). */\n queues: DevtoolsQueueInfo[];\n};\n\n/** One queue's job counts. `countsAvailable: false` when the active driver cannot count. */\nexport type DevtoolsQueueInfo = {\n name: string;\n counts: Record<string, number>;\n countsAvailable?: boolean;\n};\n\n/** What the capture did since the process started. */\nexport type DevtoolsCaptureCounters = {\n sampleRate: number;\n requests: number;\n sampled: number;\n /** Unsampled requests kept as a summary because they were slow or failed. */\n keptUnsampled: number;\n /** Samples written to the database. */\n stored: number;\n /** Samples not written because the per-minute budget was spent. */\n droppedStored: number;\n /** Query shapes, routes and error groups evicted to keep memory bounded. */\n evictedShapes: number;\n evictedRoutes: number;\n evictedErrors: number;\n /** Queries not kept inside a sampled request because it reached its per-request limit. */\n droppedQueries: number;\n};\n\n/**\n * Everything one process reports, written to the database every\n * `reportIntervalMs` (one row per instance) and merged by the dashboard.\n * Serialized it stays under 256 KB: lists are trimmed from the end.\n */\nexport type DevtoolsInstanceReport = {\n instance: DevtoolsInstanceInfo;\n at: number;\n resources: { snapshot: DevtoolsResourceSnapshot; history: DevtoolsResourcePoint[] };\n /** At most 200, highest total time first. */\n queries: DevtoolsQueryShapeStats[];\n /** At most 200, highest total time first. */\n routes: DevtoolsRouteStats[];\n /** At most 50, newest first. */\n errors: DevtoolsErrorGroup[];\n /** At most 50, newest first. */\n logs: DevtoolsReportLogEntry[];\n health: DevtoolsHealthReport;\n jobs: DevtoolsJobsReport;\n capture: DevtoolsCaptureCounters;\n};\n\n// ---------------------------------------------------------------------------\n// Requests (stored samples)\n// ---------------------------------------------------------------------------\n\n/**\n * A request row. Matches the development `DevtoolsRequestSummary` field for\n * field, plus where it was captured.\n */\nexport type DevtoolsSampleSummary = {\n id: string;\n method: string;\n path: string;\n route?: string;\n status?: number;\n startedAt: number;\n durationMs?: number;\n queryCount: number;\n warningCount: number;\n /** Read from the persisted request log only. */\n persisted?: true;\n /** The instance that served the request. */\n instance?: string;\n /** Kept because it was slow or failed, without a timeline (the request was not sampled). */\n partial?: true;\n};\n\n/** A query inside a stored sample: the shape only, never the SQL text with values or the bindings. */\nexport type DevtoolsSampleQuery = {\n id: string;\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n /** Same as `shape`: kept under this name so the request view renders it like a development query. */\n sql?: string;\n collection?: string;\n command?: string;\n shape: string;\n shapeId: string;\n startedAt: number;\n durationMs: number;\n rowCount?: number;\n error?: string;\n};\n\n/** The timeline of a sampled request, with every value removed (see the redaction rules). */\nexport type DevtoolsSampleDetail = DevtoolsSampleSummary & {\n error?: string;\n phases: { name: string; startedAt: number; durationMs: number }[];\n queries: DevtoolsSampleQuery[];\n /** Cache operation counts only; keys are not kept. */\n cache: { hits: number; misses: number; writes: number };\n /** Log entries without context. */\n logs: { level: string; module: string; action: string; message: string; at: number }[];\n warnings: { type: \"n+1\"; message: string; shape: string; count: number }[];\n /** Queries left out because the request reached `maxQueriesPerRequest`. */\n droppedQueries: number;\n};\n\n// ---------------------------------------------------------------------------\n// API views (what the dashboard reads)\n// ---------------------------------------------------------------------------\n\n/** `GET api/instances`. */\nexport type DevtoolsInstancesView = {\n /** The instance that answered this request. */\n current: string;\n /** Instances seen in the last 5 minutes (the answering one included), newest first. */\n instances: DevtoolsInstanceInfo[];\n};\n\n/** `GET api/resources?instance=<id|all>`. */\nexport type DevtoolsResourcesView = {\n instances: {\n instance: DevtoolsInstanceInfo;\n snapshot: DevtoolsResourceSnapshot;\n history: DevtoolsResourcePoint[];\n }[];\n};\n\n/** A shape row with figures computed from its histogram. */\nexport type DevtoolsQueryShapeRow = DevtoolsQueryShapeStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n /** Ids of the instances that reported this shape. */\n instances: string[];\n};\n\n/** `GET api/queries/stats?instance=&sort=total|p95|count|n+1&limit=`. */\nexport type DevtoolsQueryStatsView = {\n shapes: DevtoolsQueryShapeRow[];\n /** The sample rate the counts come from; counts are of sampled requests only. */\n sampleRate: number;\n instanceCount: number;\n evicted: number;\n};\n\n/** A route row with figures computed from its histogram. */\nexport type DevtoolsRouteStatsRow = DevtoolsRouteStats & {\n p50Ms: number;\n p95Ms: number;\n meanMs: number;\n instances: string[];\n};\n\n/** `GET api/routes/stats?instance=&sort=total|p95|count|errors&limit=`. */\nexport type DevtoolsRouteStatsView = {\n routes: DevtoolsRouteStatsRow[];\n sampleRate: number;\n instanceCount: number;\n};\n\n/** `GET api/health?instance=`. */\nexport type DevtoolsHealthView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsHealthReport }[];\n};\n\n/** `GET api/errors?instance=&limit=`. */\nexport type DevtoolsErrorsView = {\n groups: (DevtoolsErrorGroup & { instances: string[] })[];\n};\n\n/**\n * One row of `GET api/logs?level=&module=&instance=` (newest first), in both\n * modes. Development rows carry `context` and no `instance`; production rows\n * carry `instance` and never `context`.\n */\nexport type DevtoolsLogRow = DevtoolsReportLogEntry & {\n instance: string | null;\n context?: unknown;\n};\n\n/** `GET api/logs`: the rows, newest first (a plain array, as in 5.55). */\nexport type DevtoolsLogsView = DevtoolsLogRow[];\n\n/** `GET api/jobs?instance=`. */\nexport type DevtoolsJobsView = {\n instances: { instance: DevtoolsInstanceInfo; report: DevtoolsJobsReport }[];\n};\n\n/** `POST api/queries/:shapeId/explain`. */\nexport type DevtoolsExplainResult = {\n shapeId: string;\n driver: \"postgres\" | \"mongodb\";\n /** `true` only when the project allows executing plans (`explain.executing`). */\n executing: boolean;\n plan: unknown;\n /** The instance whose example ran the EXPLAIN. */\n instance: string;\n};\n\n/** One dashboard tab, as `GET api/panels` lists it (enabled tabs only, in display order). */\nexport type DevtoolsPanelInfo = {\n id: string;\n title: string;\n /** `built-in` tabs are React views in the bundle; `package` tabs load `panels/<id>/view.js`. */\n type: \"built-in\" | \"package\";\n /** Whether the panel declares a shared view (`DevtoolsPanel.share`); always `false` for built-in tabs. */\n shareable: boolean;\n};\n\n/**\n * The built-in tabs, in display order, with whether production shows them\n * when the project says nothing (`production.panels` overrides per id).\n *\n * The AI section (`ai-reports`, `ai`, `agents`, `ai-models`, `ai-errors`,\n * `ai-evaluate`) sits under \"AI\" in the sidebar. `ai` keeps its id (it is the\n * Runs page) so existing links and `production.panels.ai` keep working. In\n * production the three report tabs show only when the AI feed is available\n * (Panoptic loads), unless `production.panels` turns one on explicitly.\n */\nexport const DEVTOOLS_BUILT_IN_PANELS = [\n { id: \"requests\", title: \"Requests\", production: true },\n { id: \"queries\", title: \"Queries\", production: true },\n { id: \"routes\", title: \"Routes\", production: true },\n { id: \"resources\", title: \"Resources\", production: true },\n { id: \"health\", title: \"Health\", production: true },\n { id: \"errors\", title: \"Errors\", production: true },\n { id: \"logs\", title: \"Logs\", production: true },\n { id: \"jobs\", title: \"Jobs\", production: true },\n { id: \"mail\", title: \"Mail\", production: false },\n { id: \"ai-reports\", title: \"Reports\", production: true },\n { id: \"ai\", title: \"Runs\", production: false },\n { id: \"agents\", title: \"Agents\", production: false },\n { id: \"ai-models\", title: \"Models\", production: true },\n { id: \"ai-errors\", title: \"Errors\", production: true },\n { id: \"ai-evaluate\", title: \"Evaluate\", production: false },\n { id: \"api\", title: \"API\", production: false },\n] as const;\n\n/** The id of a built-in tab. */\nexport type DevtoolsBuiltInPanelId = (typeof DEVTOOLS_BUILT_IN_PANELS)[number][\"id\"];\n\n// ---------------------------------------------------------------------------\n// Accounts, sessions, invites\n// ---------------------------------------------------------------------------\n\n/** An account as the API shows it (never a hash or a secret). */\nexport type DevtoolsAccountView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n twoFactor: {\n totp: boolean;\n passkeys: { id: string; name: string; createdAt: number; lastUsedAt: number | null }[];\n recoveryCodesLeft: number;\n };\n mustChangePassword: boolean;\n createdAt: number;\n lastLoginAt: number | null;\n};\n\n/** `GET api/auth/session`: who is signed in and what comes next. */\nexport type DevtoolsSessionView = {\n mode: DevtoolsMode;\n stage: DevtoolsSessionStage;\n /** `null` when signed out, and in development (no accounts there). */\n account: DevtoolsAccountView | null;\n /** `admin` in development; `null` when signed out. */\n role: DevtoolsRole | null;\n /** The token to send as `X-Devtools-Csrf` on every POST/PUT/PATCH/DELETE; `null` when signed out and in development. */\n csrf: string | null;\n /** When the session ends at the latest; `null` when signed out and in development. */\n expiresAt: number | null;\n /** The instance that answered; `null` when signed out. */\n instance: DevtoolsInstanceInfo | null;\n /** Sign-in methods the server offers; `null` when signed out. */\n methods: { totp: true; passkeys: boolean } | null;\n /** Read-only share links: `enabled` mirrors `production.share.enabled`; `null` when signed out and in development. */\n share: { enabled: boolean } | null;\n /** The installed `@warlock.js/core` version; `null` when signed out or not found. */\n warlockVersion: string | null;\n /** The app's own `package.json` name and version (nothing else is read); `null` when signed out or not found. */\n app: { name: string; version: string } | null;\n};\n\n/** `POST api/auth/login` body. */\nexport type DevtoolsLoginInput = { email: string; password: string };\n\n/** Answer of every sign-in step: the next stage, and the new CSRF token when the session changed. */\nexport type DevtoolsAuthStepResult = { stage: DevtoolsSessionStage; csrf: string | null };\n\n/** `POST api/auth/totp/start` (and `api/account/totp/start`). */\nexport type DevtoolsTotpEnrolment = {\n /** Base32, for manual entry. */\n secret: string;\n /** `otpauth://totp/...`, rendered as a QR code by the dashboard. */\n uri: string;\n issuer: string;\n account: string;\n};\n\n/** Recovery codes, shown once. */\nexport type DevtoolsRecoveryCodes = { codes: string[] };\n\n/** A pending or used invite. */\nexport type DevtoolsInviteView = {\n id: string;\n email: string;\n role: DevtoolsRole;\n createdAt: number;\n expiresAt: number;\n createdBy: string | null;\n usedAt: number | null;\n};\n\n/** `POST api/admin/invites`: the token appears only in this answer. */\nexport type DevtoolsCreatedInvite = { invite: DevtoolsInviteView; token: string };\n\n/** `GET api/admin/users`. */\nexport type DevtoolsUserListView = {\n accounts: DevtoolsAccountView[];\n invites: DevtoolsInviteView[];\n};\n\n/** A session as its owner sees it (`GET api/account/sessions`). */\nexport type DevtoolsSessionInfo = {\n id: string;\n current: boolean;\n createdAt: number;\n lastSeenAt: number;\n expiresAt: number;\n ip: string | null;\n userAgent: string | null;\n};\n\n// ---------------------------------------------------------------------------\n// Share links\n// ---------------------------------------------------------------------------\n\n/** Where a share link stands. `revoked` wins over `expired`. */\nexport type DevtoolsShareStatus = \"active\" | \"expired\" | \"revoked\";\n\n/** A share link as the admin screen shows it (never the token or its hash). */\nexport type DevtoolsShareView = {\n id: string;\n /** The id of the panel the link opens. */\n panel: string;\n /** What the admin called it, 1-80 characters. */\n label: string;\n /** The email of the admin who made it; `null` when that account is gone. */\n createdBy: string | null;\n createdAt: number;\n expiresAt: number;\n revokedAt: number | null;\n lastUsedAt: number | null;\n /** How many times the link was used, counted at most once a minute. */\n uses: number;\n status: DevtoolsShareStatus;\n};\n\n/** `GET api/admin/shares`. */\nexport type DevtoolsShareList = {\n enabled: boolean;\n /** The longest life a link may have, in days. */\n maxDays: number;\n /** The panels that declare a shared view. */\n panels: { id: string; title: string }[];\n /** Newest first. */\n shares: DevtoolsShareView[];\n};\n\n/** `POST api/admin/shares` body. `label` is 1-80 characters, `days` a whole number from 1 to `maxDays`. */\nexport type DevtoolsShareCreateInput = { panel: string; label: string; days: number };\n\n/** `POST api/admin/shares`: the URL (with the token in its fragment) appears only in this answer. */\nexport type DevtoolsCreatedShare = { share: DevtoolsShareView; url: string };\n\n/**\n * What a share link opens, answered by `POST api/share/open` and\n * `GET api/share/info`: the panel and the names the shared view may load.\n */\nexport type DevtoolsShareOpenAnswer = {\n panel: string;\n /** The panel's title. */\n title: string;\n label: string;\n expiresAt: number;\n /** Served names from the panel's `assets` the shared page may load. */\n assets: string[];\n /** Whether the shared page may load images from the panel's `files`. */\n files: boolean;\n};\n\n/** The longest label of a share link. */\nexport const DEVTOOLS_SHARE_LABEL_MAX = 80;\n\n// ---------------------------------------------------------------------------\n// Audit log\n// ---------------------------------------------------------------------------\n\n/** Every audited event. `login.failed` and `mfa.failed` are the ones rate limits count. */\nexport type DevtoolsAuditType =\n | \"admin.seeded\"\n | \"admin.reset\"\n | \"setup.completed\"\n | \"login.succeeded\"\n | \"login.failed\"\n | \"login.blocked\"\n | \"mfa.succeeded\"\n | \"mfa.failed\"\n | \"mfa.enrolled\"\n | \"mfa.removed\"\n | \"recovery-code.used\"\n | \"recovery-codes.regenerated\"\n | \"passkey.added\"\n | \"passkey.removed\"\n | \"password.changed\"\n | \"logout\"\n | \"session.revoked\"\n | \"invite.created\"\n | \"invite.revoked\"\n | \"invite.accepted\"\n | \"account.role-changed\"\n | \"account.removed\"\n | \"account.mfa-reset\"\n | \"account.signed-out\"\n | \"dashboard.disabled\"\n | \"dashboard.enabled\"\n | \"dashboard.locked\"\n | \"explain.run\"\n | \"requests.cleared\"\n | \"panel.action\"\n | \"share.created\"\n | \"share.revoked\"\n | \"share.failed\";\n\n/** The audit types that count toward the account, IP and global failure limits. */\nexport const DEVTOOLS_FAILURE_AUDIT_TYPES: readonly DevtoolsAuditType[] = [\n \"login.failed\",\n \"mfa.failed\",\n \"share.failed\",\n];\n\n/** One audit log entry. */\nexport type DevtoolsAuditEntry = {\n id: string;\n at: number;\n type: DevtoolsAuditType;\n /** The account acting or targeted; `null` for an unknown email or the CLI. */\n accountId: string | null;\n /** The email as typed or as stored, lower-cased; `null` when there was none. */\n email: string | null;\n /** `\"cli\"` for a command, else the client IP after trusted-proxy resolution. */\n ip: string | null;\n /** At most 200 characters. */\n userAgent: string | null;\n /** Small flat facts: target account, role, shape id, panel route. Never a secret. */\n detail: Record<string, string | number | boolean | null>;\n /** Short reference shown to users in error messages (8 characters). */\n ref: string;\n};\n\n// ---------------------------------------------------------------------------\n// Errors the API returns\n// ---------------------------------------------------------------------------\n\n/**\n * Error codes in API answers. Each has a fixed message (see\n * `DEVTOOLS_ERROR_MESSAGES` in `errors.ts`) that says what failed and what to\n * do next.\n */\nexport type DevtoolsErrorCode =\n | \"auth.invalid-credentials\"\n | \"auth.invalid-code\"\n | \"auth.invalid-setup-token\"\n | \"auth.password-too-short\"\n | \"auth.password-too-long\"\n | \"auth.password-common\"\n | \"auth.password-same-as-email\"\n | \"auth.password-unchanged\"\n | \"auth.wrong-current-password\"\n | \"auth.busy\"\n | \"invite.invalid\"\n | \"invite.email-taken\"\n | \"account.not-found\"\n | \"account.last-admin\"\n | \"account.self\"\n | \"account.last-factor\"\n | \"role.forbidden\"\n | \"csrf.invalid\"\n | \"passkey.unavailable\"\n | \"passkey.failed\"\n | \"explain.not-allowed\"\n | \"explain.unsupported\"\n | \"explain.elsewhere\"\n | \"explain.failed\"\n | \"request.not-found\"\n | \"request.invalid-filter\"\n | \"share.not-found\"\n | \"stream.too-many\"\n | \"ai.range-invalid\"\n | \"ai.evaluate-unavailable\"\n | \"ai.prompt-not-found\"\n | \"ai.evaluate-failed\"\n | \"input.invalid\"\n | \"server.error\";\n\n/** The JSON body of every failed API call. */\nexport type DevtoolsApiErrorBody = {\n /** What failed and what to do next. */\n error: string;\n code: DevtoolsErrorCode;\n /** Short reference to quote to an admin; also written to the audit log or server log. */\n ref?: string;\n /** The instance that answered, when it matters (`explain.elsewhere`). */\n instance?: string;\n};\n\n// ---------------------------------------------------------------------------\n// AI section: reports, runs, models, errors, evaluate\n// ---------------------------------------------------------------------------\n\n/**\n * Upper bounds (inclusive, ms) of the latency buckets of the AI rollups.\n * Model calls take seconds, so these differ from `DEVTOOLS_LATENCY_BUCKETS_MS`.\n * A histogram has one more count than this list: the last counts everything\n * above five minutes. Fixed bounds make rollups from several processes add up\n * exactly. Changing them is a breaking change of the stored rollups.\n */\nexport const DEVTOOLS_AI_LATENCY_BUCKETS_MS = [\n 250, 500, 1000, 2000, 3000, 5000, 7500, 10000, 15000, 20000, 30000, 45000, 60000, 120000, 300000,\n] as const;\n\n/** The date-range presets of the Reports, Models and Errors pages. */\nexport type DevtoolsAiRangePreset = \"24h\" | \"7d\" | \"30d\";\n\n/** The range a report covers, after the server aligned it to its buckets. */\nexport type DevtoolsAiResolvedRange = {\n preset: DevtoolsAiRangePreset | \"custom\";\n /** Inclusive start, on an hour boundary. */\n from: number;\n /** Exclusive end, on an hour boundary. */\n to: number;\n /** Bucket width of the charts: 1 hour, 6 hours or 1 day. */\n stepMs: number;\n /** The browser's offset from UTC (minutes east), used to align day buckets. */\n utcOffsetMinutes: number;\n};\n\n/** Why an AI page has nothing to show; `title`, `message` and `command` are written for the page. */\nexport type DevtoolsAiUnavailableReasonView =\n | \"ai-missing\"\n | \"panoptic-missing\"\n | \"panoptic-failed\"\n | \"observation-off\"\n | \"not-collected\"\n | \"table-missing\"\n | \"reports-off\";\n\n/** The answer of any AI route that cannot serve its data. */\nexport type DevtoolsAiUnavailableView = {\n available: false;\n reason: DevtoolsAiUnavailableReasonView;\n title: string;\n message: string;\n /** A command or config line to copy; `null` when there is none. */\n command: string | null;\n /** The load error and versions for `panoptic-failed`; otherwise `null`. */\n detail: string | null;\n};\n\n/** Token counts. `input` is the whole prompt (cache reads and writes included) on every provider. */\nexport type DevtoolsAiTokenTotals = {\n input: number;\n output: number;\n /** Prompt tokens read from the provider's cache (part of `input`). */\n cached: number;\n /** Prompt tokens written to the provider's cache (part of `input`). */\n cacheWrite: number;\n /** Reasoning tokens (part of `output`). */\n reasoning: number;\n};\n\n/**\n * Estimated cost. `estimatedUsd` sums only runs whose model has pricing; runs\n * that used tokens on a model without pricing are counted in `unpricedRuns`\n * and `unpricedTokens`, never as zero cost.\n */\nexport type DevtoolsAiCostTotals = {\n estimatedUsd: number;\n pricedRuns: number;\n unpricedRuns: number;\n unpricedTokens: number;\n};\n\n/** Latency from the bucketed histogram: each figure is a bucket's upper bound (`null` with no runs). */\nexport type DevtoolsAiLatencyTotals = {\n p50Ms: number | null;\n p95Ms: number | null;\n meanMs: number | null;\n};\n\n/** Totals over a range (or one row of a breakdown). */\nexport type DevtoolsAiTotals = {\n runs: number;\n completed: number;\n failed: number;\n /** Runs that stopped early: `incomplete` and `max-iterations`. */\n incomplete: number;\n cancelled: number;\n /** `(failed + incomplete) / runs`, from 0 to 1; 0 with no runs. Cancelled runs are not errors. */\n errorRate: number;\n tokens: DevtoolsAiTokenTotals;\n cost: DevtoolsAiCostTotals;\n latency: DevtoolsAiLatencyTotals;\n /** Runs where a `fallbackModel()` chain answered from a later model at least once. */\n fallbackRuns: number;\n /** Runs where the provider refused at least once (finish reason `refusal` or a content filter). */\n refusals: number;\n};\n\n/**\n * Time series for a stacked chart: `values[i]` belongs to `buckets[i]`. At\n * most five named series; the rest are summed into one `other` series.\n */\nexport type DevtoolsAiSeriesSet = {\n /** Bucket starts, oldest first. */\n buckets: number[];\n series: {\n /** Stable identity (`provider/model`, an agent name, a category); the UI keys colours on it. */\n key: string;\n label: string;\n values: number[];\n /** `true` for the summed \"Other\" series. */\n other: boolean;\n }[];\n};\n\n/** One bucket of the error-rate line. */\nexport type DevtoolsAiRatePoint = {\n at: number;\n runs: number;\n /** Failed plus incomplete runs. */\n errors: number;\n /** `errors / runs`; `null` for a bucket without runs (the line has a gap there). */\n rate: number | null;\n};\n\n/** A row of the top agents or top models table. */\nexport type DevtoolsAiBreakdownRow = {\n /** The agent name, or `provider/model`. */\n key: string;\n label: string;\n /** The provider for a model row; `null` for an agent row. */\n provider: string | null;\n totals: DevtoolsAiTotals;\n /** Share of the range's estimated cost, 0 to 1 (share of runs when nothing was priced). */\n share: number;\n};\n\n/** The filter values present in a range, for the filter row. */\nexport type DevtoolsAiFilterOptions = {\n agents: string[];\n /** `provider/model` keys. */\n models: string[];\n providers: string[];\n};\n\n/** `GET api/ai/reports`. */\nexport type DevtoolsAiReportView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n /** The period of the same length just before `range`. */\n previousRange: { from: number; to: number };\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** Estimated USD per bucket, by model (top five plus Other). */\n costByModel: DevtoolsAiSeriesSet;\n /** Tokens per bucket: series `uncached`, `cached`, `output`. */\n tokens: DevtoolsAiSeriesSet;\n errorRate: DevtoolsAiRatePoint[];\n /** Up to 10 rows, highest estimated cost first (most runs when nothing was priced). */\n topAgents: DevtoolsAiBreakdownRow[];\n topModels: DevtoolsAiBreakdownRow[];\n /** `provider/model` keys that used tokens without pricing in the range. */\n unpricedModels: string[];\n filters: DevtoolsAiFilterOptions;\n /** `true` when `@warlock.js/ai` observes nothing, so new runs are not counted. */\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Whether a model's runs carried pricing in the range; `no-tokens` when no run used tokens. */\nexport type DevtoolsAiPricingState = \"set\" | \"missing\" | \"partial\" | \"no-tokens\";\n\n/** One row of the Models page. */\nexport type DevtoolsAiModelRow = {\n /** `provider/model`. */\n key: string;\n model: string;\n provider: string;\n totals: DevtoolsAiTotals;\n pricing: DevtoolsAiPricingState;\n /** Estimated USD per priced run; `null` when no run was priced. */\n costPerRunUsd: number | null;\n /** `fallbackRuns / runs`, 0 to 1. */\n fallbackRate: number;\n /** Agents that used the model, most runs first (at most 5). */\n agents: string[];\n /** Start of the last hour with a run. */\n lastSeenAt: number;\n};\n\n/** `GET api/ai/models`. */\nexport type DevtoolsAiModelsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n /** Most runs first. */\n models: DevtoolsAiModelRow[];\n /** Runs per bucket by model (top five plus Other). */\n runsByModel: DevtoolsAiSeriesSet;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** How failed runs are grouped on the Errors page. */\nexport type DevtoolsAiErrorCategory =\n | \"rate-limit\"\n | \"timeout\"\n | \"refusal\"\n | \"provider\"\n | \"budget\"\n | \"tool\"\n | \"schema\"\n | \"incomplete\"\n | \"other\";\n\n/** Every category, in the order the Errors page lists them. */\nexport const DEVTOOLS_AI_ERROR_CATEGORIES = [\n \"rate-limit\",\n \"timeout\",\n \"refusal\",\n \"provider\",\n \"budget\",\n \"tool\",\n \"schema\",\n \"incomplete\",\n \"other\",\n] as const satisfies readonly DevtoolsAiErrorCategory[];\n\n/** One category of failed runs. */\nexport type DevtoolsAiErrorGroup = {\n category: DevtoolsAiErrorCategory;\n /** \"Rate limit\", \"Timeout\", \"Refusal\", \"Provider error\", \"Budget\", \"Tool failed\", \"Invalid output\", \"Incomplete\", \"Other\". */\n label: string;\n count: number;\n /** Share of all failed runs in the range, 0 to 1. */\n share: number;\n previousCount: number;\n /** At most 5 each, most first. */\n byModel: { key: string; count: number }[];\n byAgent: { key: string; count: number }[];\n};\n\n/** A recent failed run (development only: production keeps no run details). */\nexport type DevtoolsAiFailedRun = {\n traceId: string;\n /** The agent span that failed. */\n agent: string;\n /** `provider/model`, or `null` when unreported. */\n model: string | null;\n status: string;\n category: DevtoolsAiErrorCategory;\n /** The error code (`PROVIDER_RATE_LIMIT`) or error name. */\n code: string | null;\n /** The error message, secrets scrubbed, at most 300 characters. */\n message: string | null;\n endedAt: number;\n requestId: string | null;\n};\n\n/** `GET api/ai/errors`. */\nexport type DevtoolsAiErrorsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n range: DevtoolsAiResolvedRange;\n totals: DevtoolsAiTotals;\n previous: DevtoolsAiTotals;\n /** `false` when part of the previous period is older than the kept history: its totals are partial. */\n previousComplete: boolean;\n /** Categories with at least one failed run, most first. */\n groups: DevtoolsAiErrorGroup[];\n /** Failed runs per bucket by category (top five plus Other). */\n overTime: DevtoolsAiSeriesSet;\n /** Newest first, at most 50; `null` in production. */\n recent: DevtoolsAiFailedRun[] | null;\n filters: DevtoolsAiFilterOptions;\n observationOff: boolean;\n generatedAt: number;\n };\n\n/** Usage of one run as the Runs page shows it. */\nexport type DevtoolsAiUsageView = {\n input: number;\n output: number;\n total: number;\n cachedTokens: number | null;\n cacheWriteTokens: number | null;\n /** `false` when `input` excludes cache tokens (the provider reports them on top). */\n inputIncludesCache: boolean | null;\n};\n\n/** One row of the Runs page (a Panoptic trace, content-free). */\nexport type DevtoolsAiRunRow = {\n traceId: string;\n requestId: string | null;\n sessionId: string | null;\n name: string;\n /** The root span type: `agent`, `workflow`, `supervisor`, … */\n type: string;\n status: string;\n startedAt: string;\n duration: number;\n usage: DevtoolsAiUsageView;\n /** Estimated USD; `null` when the run carried no pricing. */\n cost: number | null;\n models: string[];\n /** `promptName@promptVersion` of the root agent, or `null`. */\n promptKey: string | null;\n toolCalls: number;\n retries: number;\n incomplete: boolean;\n};\n\n/** A group of the Runs page (`groupBy=session|prompt|type`). */\nexport type DevtoolsAiRunGroup = {\n key: string;\n label: string;\n runs: number;\n failed: number;\n estimatedCostUsd: number;\n p95Ms: number | null;\n /** Trace ids of the group, newest first (at most 50). */\n traceIds: string[];\n};\n\n/** `GET api/ai/runs`. */\nexport type DevtoolsAiRunsView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Newest first, at most `limit` (default 200). */\n runs: DevtoolsAiRunRow[];\n /** `null` unless `groupBy` was given. */\n groups: DevtoolsAiRunGroup[] | null;\n stats: {\n /** Runs matching the filter (before `limit`). */\n count: number;\n failed: number;\n /** Priced runs only. */\n estimatedCostUsd: number;\n /** Runs that used tokens on a model without pricing (not in `estimatedCostUsd`). */\n unpricedRuns: number;\n p50Ms: number | null;\n p95Ms: number | null;\n };\n /** How many traces the dashboard keeps (`maxRequests`). */\n capacity: number;\n };\n\n/** A distinct system prompt seen in recent agent runs (the Evaluate picker). */\nexport type DevtoolsAiEvaluatePrompt = {\n /** The prompt's hash from the agent trace. */\n hash: string;\n /** Agents that used it, most recent first. */\n agents: string[];\n /** The newest run that carried its text. */\n runId: string;\n lastSeenAt: string;\n /** The first 200 characters. */\n preview: string;\n length: number;\n};\n\n/** `GET api/ai/evaluate`. */\nexport type DevtoolsAiEvaluateView =\n | DevtoolsAiUnavailableView\n | {\n available: true;\n /** Whether `panoptic.evaluate` (or `panoptic.dashboard.evaluate`) has a judge model. */\n configured: boolean;\n /** The judge model as `provider/name`; `null` when not configured. */\n judge: string | null;\n /** The configured default grading instructions; `\"\"` when none. */\n instructions: string;\n /** Newest first, at most 50. */\n prompts: DevtoolsAiEvaluatePrompt[];\n };\n\n/** `POST api/ai/evaluate` body: exactly one of `runId` and `systemPrompt`. */\nexport type DevtoolsAiEvaluateRequest = {\n /** An agent run whose system prompt text is kept. */\n runId?: string;\n /** A pasted prompt, 1 to 100,000 characters. */\n systemPrompt?: string;\n /** Overrides the configured instructions for this run; at most 4,000 characters. */\n instructions?: string;\n};\n\n/** `POST api/ai/evaluate` answer. */\nexport type DevtoolsAiEvaluateResult = {\n /** 0 to 1; `null` when the judge returned no score. */\n score: number | null;\n issues: string[];\n /** The judge model as `provider/name`. */\n judge: string;\n durationMs: number;\n};\n","import { randomBytes } from \"node:crypto\";\nimport type { DevtoolsApiErrorBody, DevtoolsErrorCode } from \"./contracts\";\n\n/**\n * Why production mode refused to start. Each code names one missing or\n * invalid setting; the message says which and how to fix it.\n */\nexport const DEVTOOLS_CONFIG_CODES = {\n DT001:\n \"Devtools production mode needs a dashboard path. Set DEVTOOLS_PATH (for example /ops-7f3k2q) or devtools.production.path.\",\n DT002:\n 'The devtools dashboard path must start with \"/\", be at least 8 characters, use only letters, digits, \"-\", \"_\", \".\", \"~\" and \"/\", and not be \"/__warlock\".',\n DT003:\n \"Devtools production mode has no admin yet. Set DEVTOOLS_ADMIN_EMAIL with DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin --email <email>`.\",\n DT004:\n \"DEVTOOLS_ADMIN_PASSWORD does not meet the password rules (the minimum length, at most 72 bytes, not a common password unless `passwords.rejectCommon` is false, not the email). Choose another one.\",\n DT005:\n \"Devtools production mode stores its accounts in the database. Install @warlock.js/cascade and configure a database connection.\",\n DT006:\n \"Devtools production mode encrypts two-factor secrets with the app key. Set encryption.key (64 hex characters) in src/config/encryption.ts.\",\n DT007:\n \"A devtools production option has an invalid value. The message names the option and the accepted values.\",\n DT008:\n \"The devtools tables are missing. Add devtoolsMigrations from @warlock.js/devtools/production to database.migrations in warlock.config.ts and run `warlock migrate`.\",\n DT009: \"Set either DEVTOOLS_ADMIN_PASSWORD or DEVTOOLS_SETUP_TOKEN, not both.\",\n DT010:\n \"DEVTOOLS_SETUP_TOKEN must be at least 32 characters. Generate one with: openssl rand -base64 32\",\n} as const;\n\n/** A production configuration error code (`DT001`–`DT010`). */\nexport type DevtoolsConfigCode = keyof typeof DEVTOOLS_CONFIG_CODES;\n\n/**\n * Thrown while the devtools connector boots in production when the monitor is\n * enabled but cannot start safely. It stops the app from booting, so a\n * misconfigured deploy fails at once instead of serving an unprotected\n * dashboard.\n */\nexport class DevtoolsProductionConfigError extends Error {\n public readonly code: DevtoolsConfigCode;\n\n public constructor(code: DevtoolsConfigCode, detail?: string) {\n super(`[${code}] ${detail ? `${detail} ` : \"\"}${DEVTOOLS_CONFIG_CODES[code]}`);\n this.name = \"DevtoolsProductionConfigError\";\n this.code = code;\n }\n}\n\n/** The message every API error code answers with: what failed and what to do next. */\nexport const DEVTOOLS_ERROR_MESSAGES: Record<DevtoolsErrorCode, string> = {\n \"auth.invalid-credentials\":\n \"The email or password is not correct. Check both and try again; after several failed tries, wait 15 minutes.\",\n \"auth.invalid-code\":\n \"The code is not correct or has expired. Enter the current 6-digit code from your authenticator app, or a recovery code.\",\n \"auth.invalid-setup-token\":\n \"This setup link is not valid. Use the link built from DEVTOOLS_SETUP_TOKEN, or run `warlock devtools:reset-admin`.\",\n \"auth.password-too-short\":\n \"Use a longer password. The minimum length is set by passwords.minLength (8 characters by default).\",\n \"auth.password-too-long\": \"Use a password of at most 72 bytes (about 72 letters).\",\n \"auth.password-common\": \"This password is too common. Choose one that is harder to guess.\",\n \"auth.password-same-as-email\": \"The password must not be your email address. Choose another one.\",\n \"auth.password-unchanged\": \"Choose a new password that differs from the current one.\",\n \"auth.wrong-current-password\": \"The current password is not correct. Enter it again.\",\n \"auth.busy\": \"The server is busy checking other sign-ins. Wait a few seconds and try again.\",\n \"invite.invalid\":\n \"This invite link is not valid, was already used, or has expired. Ask an admin for a new one.\",\n \"invite.email-taken\": \"An account with this email already exists. Sign in instead.\",\n \"account.not-found\": \"This account no longer exists. Reload the list.\",\n \"account.last-admin\": \"This is the last admin. Make another account an admin first.\",\n \"account.self\": \"You cannot do this to your own account. Ask another admin.\",\n \"account.last-factor\":\n \"This is your only second factor. Add another one (an authenticator app or a passkey) before removing it.\",\n \"role.forbidden\": \"Only admins can do this. Ask an admin.\",\n \"csrf.invalid\": \"This page is out of date. Reload the dashboard and try again.\",\n \"passkey.unavailable\":\n \"Passkeys are not available on this server (the @simplewebauthn/server package is not installed). Use an authenticator app instead.\",\n \"passkey.failed\": \"The passkey could not be verified. Try again, or use your authenticator app.\",\n \"explain.not-allowed\": \"Only admins can run EXPLAIN. Ask an admin.\",\n \"explain.unsupported\":\n \"This query cannot be explained: only PostgreSQL SELECT/WITH queries and MongoDB find, aggregate and count commands can.\",\n \"explain.elsewhere\":\n \"Only the instance that ran this query can explain it, and this request reached another one. Try again later or from that instance.\",\n \"explain.failed\":\n \"The database could not explain this query. The reference is in the server log.\",\n \"request.not-found\":\n \"This request is no longer stored. Requests are kept for a limited time (24 hours by default).\",\n \"request.invalid-filter\": \"A filter value is not valid. Check the status, method and dates.\",\n \"share.not-found\": \"This share link no longer exists or is already revoked. Reload the list.\",\n \"stream.too-many\":\n \"Too many live views are open for this session. Close another dashboard tab and reload.\",\n \"ai.range-invalid\":\n \"The date range is not valid. Pick 24 hours, 7 days or 30 days, or a custom range of at least one hour inside the kept history.\",\n \"ai.evaluate-unavailable\":\n \"Evaluate is not set up. Add panoptic.evaluate with a judge model to src/config/ai.ts, then restart.\",\n \"ai.prompt-not-found\":\n \"This run's system prompt is no longer kept. Pick a newer run or paste the prompt.\",\n \"ai.evaluate-failed\":\n \"The judge model could not grade this prompt. Check its API key and quota; the reference is in the server log.\",\n \"input.invalid\": \"Some fields are missing or not valid. Check the form and try again.\",\n \"server.error\":\n \"The dashboard could not complete this action. Try again; if it keeps failing, give your admin the reference shown.\",\n};\n\n/** The HTTP status each code answers with. */\nexport const DEVTOOLS_ERROR_STATUS: Record<DevtoolsErrorCode, number> = {\n \"auth.invalid-credentials\": 401,\n \"auth.invalid-code\": 401,\n \"auth.invalid-setup-token\": 401,\n \"auth.password-too-short\": 422,\n \"auth.password-too-long\": 422,\n \"auth.password-common\": 422,\n \"auth.password-same-as-email\": 422,\n \"auth.password-unchanged\": 422,\n \"auth.wrong-current-password\": 401,\n \"auth.busy\": 503,\n \"invite.invalid\": 410,\n \"invite.email-taken\": 409,\n \"account.not-found\": 404,\n \"account.last-admin\": 409,\n \"account.self\": 409,\n \"account.last-factor\": 409,\n \"role.forbidden\": 403,\n \"csrf.invalid\": 403,\n \"passkey.unavailable\": 501,\n \"passkey.failed\": 401,\n \"explain.not-allowed\": 403,\n \"explain.unsupported\": 400,\n \"explain.elsewhere\": 409,\n \"explain.failed\": 502,\n \"request.not-found\": 404,\n \"request.invalid-filter\": 400,\n \"share.not-found\": 404,\n \"stream.too-many\": 429,\n \"ai.range-invalid\": 400,\n \"ai.evaluate-unavailable\": 409,\n \"ai.prompt-not-found\": 404,\n \"ai.evaluate-failed\": 502,\n \"input.invalid\": 422,\n \"server.error\": 500,\n};\n\n/** A short reference id (8 characters, base32 alphabet) to quote to support. */\nexport function createErrorRef(): string {\n const alphabet = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\n const bytes = randomBytes(8);\n let ref = \"\";\n\n for (const byte of bytes) ref += alphabet[byte % alphabet.length];\n\n return ref;\n}\n\n/**\n * An error a dashboard route answers with. The production error handler turns\n * it into `{ error, code, ref?, instance? }` with `statusCode`.\n */\nexport class DevtoolsApiError extends Error {\n public readonly code: DevtoolsErrorCode;\n public readonly statusCode: number;\n public readonly ref: string | undefined;\n public readonly instance: string | undefined;\n\n public constructor(\n code: DevtoolsErrorCode,\n options: { ref?: string; instance?: string; cause?: unknown; message?: string } = {},\n ) {\n super(\n options.message ?? DEVTOOLS_ERROR_MESSAGES[code],\n options.cause === undefined ? {} : { cause: options.cause },\n );\n this.name = \"DevtoolsApiError\";\n this.code = code;\n this.statusCode = DEVTOOLS_ERROR_STATUS[code];\n this.ref = options.ref;\n this.instance = options.instance;\n }\n\n /** The JSON body this error answers with. */\n public toBody(): DevtoolsApiErrorBody {\n return {\n error: this.message,\n code: this.code,\n ...(this.ref === undefined ? {} : { ref: this.ref }),\n ...(this.instance === undefined ? {} : { instance: this.instance }),\n };\n }\n}\n\n/**\n * Raised by a store when a unique value is taken (an email) so callers can\n * answer with their own error code.\n */\nexport class DevtoolsStoreConflictError extends Error {\n public constructor(public readonly field: string) {\n super(`A devtools record with this ${field} already exists.`);\n this.name = \"DevtoolsStoreConflictError\";\n }\n}\n"],"mappings":";;;;;;;;;AA+DA,MAAa,8BAA8B;CACzC;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;CAAO;AAC/D;;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C3B,IAAI,MAAM;CAEV,KAAK,MAAM,QAAQ,OAAO,OAAO,SAAS,OAAO;CAEjD,OAAO;AACT;;;;;AAMA,IAAa,mBAAb,cAAsC,MAAM;CAM1C,AAAO,YACL,MACA,UAAkF,CAAC,GACnF;EACA,MACE,QAAQ,WAAW,wBAAwB,OAC3C,QAAQ,UAAU,SAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM,CAC5D;EACA,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,aAAa,sBAAsB;EACxC,KAAK,MAAM,QAAQ;EACnB,KAAK,WAAW,QAAQ;CAC1B;;CAGA,AAAO,SAA+B;EACpC,OAAO;GACL,OAAO,KAAK;GACZ,MAAM,KAAK;GACX,GAAI,KAAK,QAAQ,SAAY,CAAC,IAAI,EAAE,KAAK,KAAK,IAAI;GAClD,GAAI,KAAK,aAAa,SAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;EACnE;CACF;AACF;;;;;AAMA,IAAa,6BAAb,cAAgD,MAAM;CACpD,AAAO,YAAY,AAAgB,OAAe;EAChD,MAAM,+BAA+B,MAAM,iBAAiB;EAD3B;EAEjC,KAAK,OAAO;CACd;AACF"}
|
|
@@ -2,7 +2,7 @@ const require_errors = require("./errors-DNQ-g49I.cjs");
|
|
|
2
2
|
const require_extract = require("./extract-8kaX_cUV.cjs");
|
|
3
3
|
const require_ip = require("./ip-DbNhPOzi.cjs");
|
|
4
4
|
const require_helpers = require("./helpers-BcMBFy9v.cjs");
|
|
5
|
-
const require_stream_route = require("./stream-route-
|
|
5
|
+
const require_stream_route = require("./stream-route-B6WAjbPG.cjs");
|
|
6
6
|
let node_crypto = require("node:crypto");
|
|
7
7
|
let node_net = require("node:net");
|
|
8
8
|
|
|
@@ -1104,9 +1104,14 @@ function mountProductionDevtools(server, deps) {
|
|
|
1104
1104
|
lastWarningAt = now;
|
|
1105
1105
|
deps.warn?.(message);
|
|
1106
1106
|
};
|
|
1107
|
-
const notFound = (request, reply) => {
|
|
1107
|
+
const notFound = async (request, reply) => {
|
|
1108
1108
|
uniformNotFound.add(request);
|
|
1109
|
-
|
|
1109
|
+
try {
|
|
1110
|
+
if (!(await deps.answerUnknownUrl?.(request, reply) ?? false)) reply.callNotFound();
|
|
1111
|
+
} catch (error) {
|
|
1112
|
+
warn(`The app's answer for an unknown URL failed, the dashboard answers with the plain 404: ${error instanceof Error ? error.message : String(error)}`);
|
|
1113
|
+
if (!reply.sent) reply.callNotFound();
|
|
1114
|
+
}
|
|
1110
1115
|
return reply;
|
|
1111
1116
|
};
|
|
1112
1117
|
const streamSession = async (request) => {
|
|
@@ -1278,6 +1283,7 @@ function mountProductionDevtools(server, deps) {
|
|
|
1278
1283
|
});
|
|
1279
1284
|
});
|
|
1280
1285
|
instance.setErrorHandler((error, request, reply) => {
|
|
1286
|
+
if (uniformNotFound.has(request)) throw error;
|
|
1281
1287
|
if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);
|
|
1282
1288
|
if (error instanceof require_errors.DevtoolsApiError) return reply.code(error.statusCode).send(error.toBody());
|
|
1283
1289
|
const status = error.statusCode;
|
|
@@ -1373,4 +1379,4 @@ exports.mountProductionDevtools = mountProductionDevtools;
|
|
|
1373
1379
|
exports.productionRouteAccess = productionRouteAccess;
|
|
1374
1380
|
exports.resolveClient = resolveClient;
|
|
1375
1381
|
exports.sessionCookie = sessionCookie;
|
|
1376
|
-
//# sourceMappingURL=http-
|
|
1382
|
+
//# sourceMappingURL=http-1nnpAoI7.cjs.map
|