@reqray/core 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -5
- package/dist/panel/index.cjs.map +1 -1
- package/dist/panel/index.d.cts +1 -1
- package/dist/panel/index.d.ts +1 -1
- package/dist/panel/index.js.map +1 -1
- package/package.json +2 -2
package/dist/panel/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/panel/index.ts","../../../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.26_supports-color@7.2.0_typescript@6.0.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js","../../src/panel/activity.ts","../../src/panel/api.ts","../../src/state.ts","../../src/logger.ts","../../src/detectors/duplicates.ts","../../src/weight.ts","../../src/detectors/heavy-response.ts","../../src/sql.ts","../../src/detectors/runs.ts","../../src/detectors/n-plus-one.ts","../../src/timing.ts","../../src/detectors/pool-wait.ts","../../src/http-fingerprint.ts","../../src/detectors/sequential-http.ts","../../src/detectors/slow-budget.ts","../../src/detectors/slow-code.ts","../../src/detectors/transactions.ts","../../src/detectors/transaction-hold.ts","../../src/detectors/registry.ts","../../src/detectors/index.ts","../../src/panel.ts","../../src/panel/findings.ts","../../src/panel/routes.ts","../../src/panel/baseline.ts","../../src/panel/blame.ts","../../src/panel/exceptions.ts","../../src/callsite.ts","../../src/context.ts","../../src/explain-targets.ts","../../src/panel/explain.ts","../../src/panel/export.ts","../../src/panel/filters.ts","../../src/panel/timeline.ts","../../src/panel/history.ts","../../src/panel/paging.ts","../../src/panel/page-from-list.ts","../../src/panel/pressure.ts","../../src/panel/project.ts","../../src/diagnostics.ts","../../src/pools.ts","../../src/replay-waiters.ts","../../src/reqray.ts","../../src/console-capture.ts","../../src/cost.ts","../../src/host.ts","../../src/ids.ts","../../src/profiler.ts","../../src/panel/replay.ts","../../src/panel/series.ts"],"sourcesContent":["/**\n * `@reqray/core/panel` — reading back what was recorded.\n *\n * A separate entry point from `@reqray/core` on purpose. The recording side\n * runs inside somebody's application on the hot path and loads nothing it does\n * not need; this side spawns `git`, serves static files, opens sockets and\n * calls back into the application to replay a request. Joined in one barrel,\n * an instrumentation that only wants to time a query linked the HAR exporter\n * and the blame subprocess runner along with it.\n *\n * Nothing here is imported by the recording path — the split is a fact about\n * the code, not a convention this file asks anyone to keep.\n */\n\nexport {\n type ActivityReport,\n type Outlier,\n type RouteWindow,\n whatRanAt,\n} from './activity.js';\nexport {\n createPanelHandler,\n type DurationSample,\n type PageQuery,\n type PanelHandler,\n type PanelHandlerInit,\n type PanelSource,\n panelSourceFor,\n parseFilter,\n type RequestPage,\n type RequestRow,\n toRow,\n} from './api.js';\nexport { type BaselineQuery, baselineFor } from './baseline.js';\nexport { type BlameLine, blameLine, parsePorcelain } from './blame.js';\nexport {\n type ExceptionFrame,\n type ExceptionGroup,\n groupExceptions,\n} from './exceptions.js';\nexport {\n analyzePlan,\n ExplainError,\n type ExplainNote,\n type ExplainPlanNode,\n type ExplainResult,\n runExplain,\n} from './explain.js';\nexport { toCurlScript, toHar } from './export.js';\nexport {\n filterRequests,\n type RequestFilter,\n type RequestSummary,\n summarize,\n} from './filters.js';\nexport {\n type FindingSample,\n type FindingSamples,\n type FindingsQuery,\n findingSamplesOf,\n flagWithMutes,\n patternKey,\n patternsOf,\n} from './findings.js';\nexport {\n columnsFor,\n type HistoryOptions,\n type HistoryQuery,\n type HistorySample,\n type HistorySamples,\n historyOf,\n historySampleOf,\n SERIES_COLUMNS,\n totalsOf,\n} from './history.js';\nexport { type PageContext, pageFromList } from './page-from-list.js';\nexport {\n type Cursor,\n decodeCursor,\n encodeCursor,\n isAfterCursor,\n} from './paging.js';\nexport { pressureFor } from './pressure.js';\nexport {\n type GitHead,\n type ProjectApp,\n type ProjectReport,\n type ProjectRuntime,\n type ProjectStorage,\n projectReport,\n storageOf,\n} from './project.js';\nexport {\n metricsOf,\n type ReplayComparison,\n type ReplayInput,\n type ReplayMetrics,\n runReplay,\n} from './replay.js';\nexport {\n normalizeRoute,\n percentile,\n type RouteFinding,\n type RouteStats,\n type RoutesReport,\n routeStats,\n TREND_BUCKETS,\n} from './routes.js';\nexport {\n type RouteSeries,\n routeSeries,\n SERIES_BUCKETS,\n type SeriesBucket,\n} from './series.js';\nexport {\n bucketIndex,\n buildTimeline,\n TIMELINE_BUCKETS,\n type TimelineBucket,\n type TimelineReport,\n type TimePoint,\n} from './timeline.js';\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/**\n * What ran here.\n *\n * A chart nobody can click is decoration. Clicking a moment on one should\n * answer the only question worth asking of it — what was different then —\n * and the answer has to be ranked by *how far each route strayed from its own\n * behaviour*, not by how much traffic it had. Ranked by volume, the busiest\n * endpoint tops every list and the moment explains nothing.\n *\n * Every route is compared against itself over the rest of the window, so a\n * spike does not inflate the baseline it is being measured against. When\n * nothing stands out, the answer is that nothing did: whatever moved the\n * chart came from garbage collection, a neighbour on the box, or the host —\n * and a list of ordinary routes presented as an explanation is worse than a\n * sentence admitting there is none.\n */\n\nimport type { ActivityReport, Outlier } from '@reqray/protocol';\n\nexport type { ActivityReport, Outlier };\n\n/** One route's traffic over a stretch of time, as the store groups it. */\nexport interface RouteWindow {\n readonly method: string;\n readonly route: string;\n readonly calls: number;\n /** Mean duration over those calls, ms. */\n readonly avgMs: number;\n}\n\n/**\n * Calls a route needs in the moment before it can be called unusual.\n *\n * Two calls that happened to be slow are two calls that happened to be slow.\n */\nconst MIN_CALLS = 3;\n\n/**\n * How far from its own baseline a route has to be.\n *\n * Half again, on either rate or duration. Below that the difference is inside\n * the noise of a handful of calls, and a list that includes it is a list of\n * everything that ran.\n */\nconst MIN_RATIO = 1.5;\n\n/**\n * How many calls above its usual count a route has to be.\n *\n * A ratio alone is not enough at low rates: a route called twice a minute\n * that happens to be called three times has run at 1.5× its rate and nothing\n * has happened. Three extra calls is the smallest excess that is a count\n * rather than a rounding of one.\n */\nconst MIN_EXCESS_CALLS = 3;\n\n/**\n * How much slower, in milliseconds, before a ratio means anything.\n *\n * A route that goes from 0.2 ms to 0.4 ms has doubled and nobody has noticed.\n * Five milliseconds is the smallest difference somebody could experience, and\n * below it a ratio is reporting the jitter of the clock.\n */\nconst MIN_EXCESS_MS = 5;\n\n/**\n * What stood out in one stretch of time.\n *\n * @param moment routes grouped over the clicked stretch.\n * @param overall the same, over the whole window the chart covers — the\n * moment included, and subtracted here so a spike is not its own baseline.\n */\nexport function whatRanAt(\n moment: readonly RouteWindow[],\n overall: readonly RouteWindow[],\n window: { from: number; to: number; overallMs: number },\n): ActivityReport {\n const before = new Map(overall.map((entry) => [`${entry.method} ${entry.route}`, entry]));\n const momentMs = Math.max(1, window.to - window.from);\n // The rest of the window: what the route usually does, with the moment\n // taken out of it. Never negative, and never zero as a divisor.\n const restMs = Math.max(1, window.overallMs - momentMs);\n\n // How the moment compares as a whole. Bursty traffic — a demo restarting, a\n // cron waking up, a deploy draining a queue — lifts every route at once, and\n // without this every route is an outlier in every burst.\n const momentCalls = moment.reduce((total, entry) => total + entry.calls, 0);\n const overallCalls = overall.reduce((total, entry) => total + entry.calls, 0);\n const restOverall = Math.max(0, overallCalls - momentCalls);\n const overallRatio = restOverall > 0 ? momentCalls / momentMs / (restOverall / restMs) : null;\n\n /**\n * How much busier the moment was for everything *except* this route.\n *\n * Each route is judged against how the rest of the traffic moved, not\n * against the total it is part of — otherwise a route that is the only\n * thing running compares against itself and can never stand out, which is\n * exactly the case where it obviously does.\n */\n const withoutRatio = (entry: RouteWindow, restCalls: number): number | null => {\n const otherMoment = momentCalls - entry.calls;\n const otherRest = restOverall - restCalls;\n if (otherMoment <= 0 || otherRest <= 0) return null;\n return otherMoment / momentMs / (otherRest / restMs);\n };\n\n const outliers: Outlier[] = [];\n for (const entry of moment) {\n if (entry.calls < MIN_CALLS) continue;\n\n const all = before.get(`${entry.method} ${entry.route}`);\n const restCalls = Math.max(0, (all?.calls ?? 0) - entry.calls);\n\n // Never ran outside this moment: not a ratio, a fact.\n if (restCalls === 0) {\n outliers.push({\n method: entry.method,\n route: entry.route,\n calls: entry.calls,\n avgMs: entry.avgMs,\n rateRatio: null,\n slowerRatio: null,\n firstSeen: true,\n });\n continue;\n }\n\n const rate = restCalls / restMs;\n const rateRatio = entry.calls / momentMs / rate;\n // What this moment would have held if the route had simply grown with\n // everything else. The excess over *that* is the part worth reporting,\n // and at low rates it is what tells a burst from a coin toss.\n const others = withoutRatio(entry, restCalls);\n const expected = rate * momentMs * (others ?? 1);\n // The route against how the rest of the traffic moved: one means it rose\n // exactly as much as everything around it, which is not an answer to\n // \"what was different here\".\n const shareRatio = others === null ? rateRatio : rateRatio / others;\n // The mean over the rest, recovered from the totals: the store grouped\n // once, and asking it twice for overlapping ranges would cost a scan to\n // learn something arithmetic already knows.\n const restAvg =\n all && all.calls > 0\n ? Math.max(0, (all.avgMs * all.calls - entry.avgMs * entry.calls) / restCalls)\n : 0;\n const slowerRatio = restAvg > 0 ? entry.avgMs / restAvg : null;\n\n const busier = shareRatio >= MIN_RATIO && entry.calls - expected >= MIN_EXCESS_CALLS;\n const slower =\n slowerRatio !== null && slowerRatio >= MIN_RATIO && entry.avgMs - restAvg >= MIN_EXCESS_MS;\n if (!busier && !slower) continue;\n\n outliers.push({\n method: entry.method,\n route: entry.route,\n calls: entry.calls,\n avgMs: entry.avgMs,\n rateRatio,\n slowerRatio,\n firstSeen: false,\n });\n }\n\n const strength = (outlier: Outlier): number =>\n outlier.firstSeen\n ? Number.POSITIVE_INFINITY\n : Math.max(outlier.rateRatio ?? 0, outlier.slowerRatio ?? 0);\n\n return {\n from: window.from,\n to: window.to,\n calls: momentCalls,\n rateRatio: overallRatio,\n outliers: outliers.sort((a, b) => strength(b) - strength(a)),\n };\n}\n","/**\n * Panel HTTP API.\n *\n * The handler is written against raw `IncomingMessage`/`ServerResponse`, so\n * Express and Fastify mount the very same code — no need to duplicate the API\n * in each adapter.\n */\n\nimport { createReadStream, statSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { extname, resolve, sep } from 'node:path';\nimport type {\n FiledPatternState,\n PanelMeta,\n RequestRow,\n RequestSort,\n RequestSummary,\n SeriesMetric,\n StoredPatternState,\n} from '@reqray/protocol';\nimport type { ResolvedOptions } from '../config.js';\nimport { detectorSettings } from '../detectors/index.js';\nimport { warnOnce } from '../logger.js';\nimport { isPanelRequestAllowed } from '../panel.js';\nimport type { RetentionLimits } from '../retention.js';\nimport { ensureTiming } from '../timing.js';\nimport type { RecordedRequest } from '../types.js';\nimport { type RouteWindow, whatRanAt } from './activity.js';\nimport { type BaselineQuery, baselineFor } from './baseline.js';\nimport { blameLine } from './blame.js';\nimport { groupExceptions } from './exceptions.js';\nimport { ExplainError, runExplain } from './explain.js';\nimport { toCurlScript, toHar } from './export.js';\nimport { filterRequests, type RequestFilter } from './filters.js';\nimport { type FindingSamples, type FindingsQuery, flagWithMutes, patternsOf } from './findings.js';\nimport { type HistoryQuery, type HistorySamples, historyOf, SERIES_COLUMNS } from './history.js';\nimport { pageFromList } from './page-from-list.js';\nimport { pressureFor } from './pressure.js';\nimport { logOf, projectReport, retentionOf } from './project.js';\nimport { type ReplayInput, runReplay } from './replay.js';\nimport { normalizeRoute, routeStats } from './routes.js';\nimport { routeSeries, SERIES_BUCKETS } from './series.js';\nimport { buildTimeline, TIMELINE_BUCKETS, type TimePoint } from './timeline.js';\n\nexport type { RequestRow } from '@reqray/protocol';\n\n/** One page of the request list, newest first. */\nexport interface RequestPage {\n readonly rows: readonly RequestRow[];\n /** Feed back as `cursor` to get the next, older page. `null` — the end. */\n readonly nextCursor: string | null;\n /** Numbers for the status bar, over the whole store rather than the page. */\n readonly summary: RequestSummary;\n}\n\n/** What the panel asks a store for when it wants a page. */\nexport interface PageQuery {\n readonly filter: RequestFilter;\n readonly limit: number;\n /** Where to continue from. Absent or `null` — start at the beginning. */\n readonly cursor?: string | null | undefined;\n /**\n * What \"the beginning\" means: the newest requests, or the slowest.\n *\n * Defaults to `recent`. Sorting is the store's job rather than the\n * caller's — \"the slowest request\" over a history on disk cannot be found\n * by reading a page of it and comparing.\n */\n readonly sort?: RequestSort | undefined;\n}\n\n/** Where the panel gets its data. Implemented by the transport store. */\nexport interface PanelSource {\n /** Requests from newest to oldest. */\n list(): readonly RecordedRequest[];\n get(id: string): RecordedRequest | undefined;\n clear(): void;\n subscribe(listener: (request: RecordedRequest) => void): () => void;\n /**\n * Keeps a request past its turn in the ring buffer, or lets it go again.\n *\n * Optional: a store without pinning is still a valid source, and the panel\n * answers the pin route with an explanation instead of pretending.\n *\n * @returns `false` when the request is gone or the pin limit is reached.\n */\n pin?(id: string, pinned: boolean): boolean;\n /** Ids currently pinned. */\n pinned?(): readonly string[];\n /**\n * When, how long, and whether it failed — for every request the store\n * holds.\n *\n * Optional, and cheap on purpose: three numbers per request, so the strip\n * above the list can span the whole history instead of the page that\n * happens to be loaded. A source without it leaves the panel to draw from\n * the rows it has, which is what it always did.\n */\n timeSeries?(): readonly TimePoint[];\n /**\n * One page of the list, filtered and cut by the store itself.\n *\n * Optional, and the difference between a buffer and a history: reading\n * everything into memory to filter it is what an in-memory ring can afford\n * and a store on disk cannot. A source without this method is served by\n * `list()`, whole.\n */\n page?(query: PageQuery): RequestPage;\n /**\n * Durations of other calls of one route.\n *\n * Optional, and asked for rather than derived from `list()`: judging one\n * call against its route means reading that route's whole history, which a\n * ring buffer can afford to scan and a store on disk should answer with a\n * query. A source without it leaves the detail page with no verdict, which\n * is better than a verdict drawn from the last page that happened to load.\n */\n durations?(query: BaselineQuery): readonly DurationSample[];\n /**\n * Traffic grouped by route over a stretch of time.\n *\n * Optional, and an aggregate rather than a page: answering \"what ran in\n * this moment\" by reading the moment's requests would mean loading a busy\n * minute of them to count four numbers per route.\n */\n counts?(query: { from: number; to: number }): readonly RouteWindow[];\n /**\n * A period's requests, a handful of numbers each.\n *\n * Optional, and the one method that reads a *stretch* rather than a page or\n * a route: the history screen asks what a week did, and answering that from\n * `list()` would mean holding a week of payloads in memory to look at ten\n * fields in each. A store must bound what it reads and say when it stopped\n * — a truncated total presented as a complete one is worse than no screen.\n */\n history?(query: HistoryQuery): HistorySamples;\n /**\n * Finding occurrences over a stretch of time, one row each.\n *\n * Optional, and rare rows on purpose: requests with findings are a small\n * minority, so a store answers this from them alone instead of reading the\n * window. A source without it leaves the findings tab explaining itself\n * rather than empty.\n */\n findings?(query: FindingsQuery): FindingSamples;\n /**\n * The reader's own bookkeeping per pattern: `ack` or `muted`.\n *\n * Patterns in neither state are `new` and are simply absent. A store that\n * persists (SQLite) keeps these across restarts; the in-memory ring keeps\n * them exactly as long as it keeps the requests they are about.\n */\n findingStates?(): ReadonlyMap<string, FiledPatternState>;\n /** Remembers a state; `new` forgets the pattern. */\n setFindingState?(id: string, state: StoredPatternState): void;\n}\n\n/**\n * One call of a route, as the store hands it over.\n *\n * Four numbers rather than a record: judging a call against its route, or\n * drawing the route's last hour, means reading every call of it, and parsing\n * a few thousand JSON documents to look at one field in each is how a page\n * becomes slow.\n */\nexport interface DurationSample {\n readonly durationMs: number;\n /** Epoch ms — what the window the samples cover is measured from. */\n readonly startedAt: number;\n /** Threw, or answered 5xx — what the error-rate chart counts. */\n readonly hasError: boolean;\n /**\n * Mean event-loop delay while it ran, or `null` when nothing measured it.\n *\n * What splits a route's calls into \"the host was fine\" and \"the host was\n * struggling\" — the comparison that says whether the process was to blame.\n */\n readonly loopDelayMs: number | null;\n}\n\n/** Everything the panel handler needs to serve a request. */\nexport interface PanelHandlerInit {\n readonly source: PanelSource;\n readonly options: ResolvedOptions;\n /**\n * Directory with the built dashboard.\n *\n * Left out when `@reqray/dashboard` is not installed: the API keeps working\n * and the UI route answers with an explanation instead of a blank page.\n */\n readonly assetsDir?: string | undefined;\n}\n\n/**\n * Panel request handler.\n *\n * @returns `true` if the request belonged to the panel and has been handled.\n * `false` means it is an ordinary application request and must be passed on.\n */\nexport type PanelHandler = (request: IncomingMessage, response: ServerResponse) => boolean;\n\n/**\n * The transport the panel can read from, if there is one.\n *\n * A transport is a store when it can answer the four questions the panel\n * asks. An HTTP transport to an external collector cannot — the panel then\n * runs in the collector. Neither can a log file, which is write-only by\n * design, so a fan-out is searched through rather than tested as a whole.\n *\n * Warns when the panel is configured and nothing can serve it: a panel that\n * quietly does not mount is a 404 nobody can explain.\n */\nexport function panelSourceFor(transport: unknown, options: ResolvedOptions): PanelSource | null {\n const direct = asPanelSource(transport);\n if (direct) return direct;\n\n const members = (transport as { transports?: readonly unknown[] } | null)?.transports;\n if (Array.isArray(members)) {\n for (const member of members) {\n const found = asPanelSource(member);\n if (found) return found;\n }\n }\n\n if (options.enabled && options.panel) {\n const name = (transport as { name?: unknown } | null)?.name;\n warnOnce(\n 'panel.source',\n `the panel is not mounted: ${typeof name === 'string' ? name : 'this transport'} keeps no requests to show. ` +\n 'A store — @reqray/store-memory or @reqray/store-sqlite — has to be among the transports.',\n );\n }\n return null;\n}\n\n/** Whether a transport can answer what the panel asks of a store. */\nfunction asPanelSource(transport: unknown): PanelSource | null {\n const candidate = transport as Partial<PanelSource> | null;\n if (!candidate) return null;\n const complete =\n typeof candidate.list === 'function' &&\n typeof candidate.get === 'function' &&\n typeof candidate.clear === 'function' &&\n typeof candidate.subscribe === 'function';\n return complete ? (candidate as PanelSource) : null;\n}\n\n/**\n * Projects a record into a list row.\n *\n * The whole list is served on every panel open, and full records with spans\n * and bodies would weigh megabytes. Details come from a separate request by\n * identifier.\n */\nexport function toRow(request: RecordedRequest, pinned = false): RequestRow {\n let sqlCount = 0;\n let httpCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n else if (span.kind === 'http') httpCount++;\n }\n\n return {\n id: request.id,\n method: request.method,\n path: request.path,\n query: request.query,\n route: normalizeRoute(request.path),\n status: request.status,\n durationMs: request.durationMs,\n startedAt: request.startedAt,\n sqlCount,\n httpCount,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n findingCount: request.findings.length,\n flag: [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null,\n hasError: request.error !== null || request.status >= 500,\n // Straight through, including the nulls: a row from a store written\n // before cost was measured has no cost, and inventing a zero would put a\n // cheap-looking request next to genuinely cheap ones.\n cpuMs: request.cost?.cpuMs ?? null,\n cpuShare: request.cost?.cpuShare ?? null,\n pinned,\n test: request.test,\n };\n}\n\n/** A file the browser saves rather than renders. */\nfunction sendDownload(\n response: ServerResponse,\n filename: string,\n contentType: string,\n body: string,\n): void {\n response.writeHead(200, {\n 'content-type': contentType,\n 'content-disposition': `attachment; filename=\"${filename}\"`,\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\nfunction sendJson(response: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload);\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\n/**\n * How many rows one page may hold.\n *\n * Capped rather than trusted: the parameter comes from a browser, and an\n * unbounded page defeats the point of having pages at all.\n */\nconst DEFAULT_PAGE_LIMIT = 100;\nconst MAX_PAGE_LIMIT = 500;\n\nfunction pageLimit(params: URLSearchParams): number {\n const asked = Number(params.get('limit'));\n if (!Number.isFinite(asked) || asked <= 0) return DEFAULT_PAGE_LIMIT;\n return Math.min(Math.floor(asked), MAX_PAGE_LIMIT);\n}\n\n/** A positive finite number from a query parameter, or `undefined`. */\nfunction positive(raw: string | null): number | undefined {\n const value = Number(raw);\n return Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\nconst HOUR_MS = 60 * 60 * 1000;\n\n/** Every metric the history screen may ask for. Nothing outside this list. */\nconst METRICS: readonly SeriesMetric[] = [\n 'p50',\n 'p95',\n 'p99',\n 'throughput',\n 'errorRate',\n 'sqlPerRequest',\n 'httpPerRequest',\n 'bytes',\n 'loopDelay',\n 'findingsPerRequest',\n];\n\n/**\n * Which metrics to draw.\n *\n * Two at most: a third line is a dashboard, and a chart nobody can read is\n * not a better answer than a chart with one line on it.\n */\nfunction parseMetrics(params: URLSearchParams): SeriesMetric[] {\n const asked = params\n .getAll('metric')\n .flatMap((value) => value.split(','))\n .map((value) => value.trim())\n .filter((value): value is SeriesMetric => (METRICS as readonly string[]).includes(value));\n\n const unique = [...new Set(asked)].slice(0, 2);\n return unique.length > 0 ? unique : ['p95'];\n}\n\n/**\n * The query string, as the filter the store applies.\n *\n * Exported so the panel's client-side filter is checked against this and not\n * against a second reading of the same parameters.\n */\nexport function parseFilter(params: URLSearchParams): RequestFilter {\n const methods = params\n .getAll('method')\n .flatMap((value) => value.split(','))\n .filter(Boolean);\n const statusClasses = params\n .getAll('status')\n .flatMap((value) => value.split(','))\n .map((value) => Number.parseInt(value, 10))\n .filter((value) => Number.isFinite(value));\n\n const minDuration = Number(params.get('minDurationMs'));\n const minSql = Number(params.get('minSql'));\n const status = Number(params.get('statusExact'));\n const flagged = params\n .getAll('flagged')\n .flatMap((value) => value.split(','))\n .filter(Boolean);\n const route = params.get('route');\n const routeMethod = params.get('routeMethod');\n const from = Number(params.get('from'));\n const to = Number(params.get('to'));\n\n return {\n from: Number.isFinite(from) && from > 0 ? from : undefined,\n to: Number.isFinite(to) && to > 0 ? to : undefined,\n query: params.get('q') ?? undefined,\n methods,\n statusClasses,\n minDurationMs: Number.isFinite(minDuration) && minDuration > 0 ? minDuration : undefined,\n onlyFindings: params.get('findings') === '1',\n onlyNPlusOne: params.get('nplus') === '1',\n onlyTests: params.get('tests') === '1',\n onlyErrors: params.get('errors') === '1',\n route: route && routeMethod ? { method: routeMethod, route } : undefined,\n path: params.get('path') ?? undefined,\n status: Number.isFinite(status) && status > 0 ? status : undefined,\n minSql: Number.isFinite(minSql) && minSql > 0 ? minSql : undefined,\n flagged: flagged.length > 0 ? flagged : undefined,\n test: params.get('test') ?? undefined,\n };\n}\n\n/**\n * Reads the body of a panel request.\n *\n * An already-parsed body is taken first: the application almost certainly has\n * a json parser (`express.json()`) that consumed the stream before us —\n * reading the socket a second time is pointless, it is already empty.\n */\nasync function readBody(request: IncomingMessage, limitBytes = 1_000_000): Promise<unknown> {\n const parsed = (request as IncomingMessage & { body?: unknown }).body;\n if (parsed !== undefined && parsed !== null) {\n return typeof parsed === 'string' ? JSON.parse(parsed) : parsed;\n }\n\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const buffer = chunk as Buffer;\n size += buffer.length;\n if (size > limitBytes) throw new Error('request body too large');\n chunks.push(buffer);\n }\n const raw = Buffer.concat(chunks).toString('utf8');\n return raw ? JSON.parse(raw) : {};\n}\n\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.woff2': 'font/woff2',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Serves the built dashboard.\n *\n * Anything that is not an existing file falls back to `index.html`: the panel\n * is a single-page app, and its inner screens are state, not server routes.\n */\nfunction serveAsset(assetsDir: string, route: string, response: ServerResponse): boolean {\n const root = resolve(assetsDir);\n const requested = route === '/' ? 'index.html' : route.replace(/^\\/+/, '');\n let target = resolve(root, requested);\n\n // A path escaping the assets directory can only come from a traversal attempt.\n if (target !== root && !target.startsWith(root + sep)) return false;\n\n let file = statSync(target, { throwIfNoEntry: false });\n if (!file?.isFile()) {\n target = resolve(root, 'index.html');\n file = statSync(target, { throwIfNoEntry: false });\n if (!file?.isFile()) return false;\n }\n\n response.writeHead(200, {\n 'content-type': MIME_TYPES[extname(target)] ?? 'application/octet-stream',\n 'content-length': file.size,\n // Asset names are content-hashed by the build; index.html must not be cached.\n 'cache-control': target.endsWith('index.html') ? 'no-store' : 'public, max-age=31536000',\n });\n createReadStream(target).pipe(response);\n return true;\n}\n\n/**\n * The application's own address — replay needs it to call back into itself.\n *\n * From the socket, never from `Host`. Replay follows this address carrying\n * headers the caller chose, so a forged `Host` would aim it — cookies and all\n * — at any host that resolves.\n */\nfunction originOf(request: IncomingMessage): string {\n const port = request.socket.localPort;\n const address = request.socket.localAddress ?? '127.0.0.1';\n // IPv6 literals need brackets in a URL; `::1` is the ordinary local case.\n const host = address.includes(':') ? `[${address}]` : address;\n // TLS never reaches this far: the panel is mounted inside the application,\n // and replay always goes to its own local address.\n return `http://${host}${port ? `:${port}` : ''}`;\n}\n\n/**\n * Whether a state-changing request came from the panel itself.\n *\n * The gate says who may use the panel, not what page is asking. Without this,\n * any site open in a developer's browser can POST to `/api/replay` and make\n * the application run a recorded request again — a second charge, a second\n * email. That the reply is unreadable to that page is no comfort: the effect\n * has happened.\n *\n * `Sec-Fetch-Site` is the browser's own account and cannot be set by script.\n * `same-site` is refused with `cross-site`: two ports of localhost are one\n * site, and the dev server on the other port is the neighbour in question.\n *\n * Neither header means the caller is not a browser, and CSRF is not that.\n */\nfunction isSameOrigin(request: IncomingMessage): boolean {\n const site = request.headers['sec-fetch-site'];\n if (typeof site === 'string') return site === 'same-origin' || site === 'none';\n\n const origin = request.headers.origin;\n if (typeof origin !== 'string' || origin === '') return true;\n\n const host = request.headers.host;\n if (typeof host !== 'string') return false;\n try {\n return new URL(origin).host === host;\n } catch {\n // An origin that is not a URL is not one this panel wrote.\n return false;\n }\n}\n\n/**\n * How many requests one export may carry.\n *\n * It serializes whole records into one string, synchronously, answering a GET.\n * The stores bound `list()`, but a bound living in the store is not this\n * endpoint's: a store written elsewhere would hand over its whole history.\n */\nconst EXPORT_LIMIT = 1_000;\n\n/** The newest requests matching the filter, and how many did not fit. */\nfunction forExport(\n source: PanelSource,\n params: URLSearchParams,\n): { requests: readonly RecordedRequest[]; dropped: number } {\n const matched = filterRequests(source.list(), parseFilter(params));\n if (matched.length <= EXPORT_LIMIT) return { requests: matched, dropped: 0 };\n // The newest, because a truncated export should be the recent part of the\n // story rather than an arbitrary slice of it.\n return {\n requests: matched.slice(-EXPORT_LIMIT),\n dropped: matched.length - EXPORT_LIMIT,\n };\n}\n\n/**\n * What a truncated export says about itself.\n *\n * An export is evidence: a cap nobody is told about reads as \"this is\n * everything\".\n */\nfunction exportNote(dropped: number): string | null {\n return dropped === 0\n ? null\n : `${dropped} older request${dropped === 1 ? '' : 's'} matched and were left out: an export carries at most ${EXPORT_LIMIT}.`;\n}\n\n/**\n * How many live feeds one panel may hold open at once.\n *\n * Each one is a listener on the store and a timer; nothing else bounds them,\n * and a stream is opened by a GET that anything can repeat.\n */\nconst MAX_STREAMS = 32;\n\n/**\n * How much one feed may have written that its reader has not taken.\n *\n * A tab left in the background or a proxy that stalled stops reading, and\n * every row since then sits in this process's memory, per feed, without end.\n * Past this the feed is dropped; the panel reconnects and re-reads the list,\n * which is what it does after any gap.\n */\nconst MAX_STREAM_BACKLOG_BYTES = 1024 * 1024;\n\n/**\n * How many feeds one panel is holding.\n *\n * Per handler rather than per process: two applications in one process are two\n * panels, and a cap they share is a cap that depends on a neighbour.\n */\ninterface StreamCount {\n open: number;\n}\n\nfunction streamEvents(\n source: PanelSource,\n mutes: MuteView,\n request: IncomingMessage,\n response: ServerResponse,\n streams: StreamCount,\n): void {\n if (streams.open >= MAX_STREAMS) {\n sendJson(response, 503, { error: `too many live feeds open (${MAX_STREAMS})` });\n return;\n }\n streams.open++;\n\n response.writeHead(200, {\n 'content-type': 'text/event-stream; charset=utf-8',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n // Disables nginx buffering: without it the feed stalls.\n 'x-accel-buffering': 'no',\n });\n response.write(': reqray stream\\n\\n');\n\n const unsubscribe = source.subscribe((recorded) => {\n // The live feed obeys mutes the same way the list does.\n const [row] = mutes.silence([toRow(recorded)]);\n if (response.writableLength > MAX_STREAM_BACKLOG_BYTES) {\n response.destroy();\n return;\n }\n response.write(`data: ${JSON.stringify(row)}\\n\\n`);\n });\n\n const keepAlive = setInterval(() => response.write(': ping\\n\\n'), 20_000);\n keepAlive.unref?.();\n\n let stopped = false;\n const stop = (): void => {\n // Both `close` events fire for one disconnect; the count must move once.\n if (stopped) return;\n stopped = true;\n streams.open--;\n clearInterval(keepAlive);\n unsubscribe();\n };\n request.on('close', stop);\n response.on('close', stop);\n}\n\n/**\n * Creates the panel handler.\n *\n * Returns `null` if the panel is disabled by options: the adapter then has\n * nothing to mount.\n */\nexport function createPanelHandler(init: PanelHandlerInit): PanelHandler | null {\n const { source, options } = init;\n const panel = options.panel;\n if (!panel || !options.enabled) return null;\n\n const mount = panel.path.endsWith('/') ? panel.path.slice(0, -1) : panel.path;\n const streams: StreamCount = { open: 0 };\n const mutes = new MuteView(source);\n\n const serve: PanelHandler = (request, response) => {\n // Express strips the matched mount prefix from `url` inside `app.use`;\n // `originalUrl` keeps the full path. Anything non-Express has no such\n // property and falls back to the plain url.\n const rawUrl = (request as { originalUrl?: string }).originalUrl ?? request.url ?? '/';\n if (rawUrl !== mount && !rawUrl.startsWith(`${mount}/`) && !rawUrl.startsWith(`${mount}?`)) {\n return false;\n }\n\n const url = new URL(rawUrl, 'http://reqray.local');\n const route = url.pathname.slice(mount.length) || '/';\n\n if (\n !isPanelRequestAllowed(panel.gate, {\n headers: request.headers,\n ip: request.socket.remoteAddress ?? null,\n })\n ) {\n sendJson(response, 403, {\n error: panel.gate\n ? 'panel access denied by the gate'\n : 'without a gate the panel answers only to this machine, at a local address. ' +\n \"To open it further, set one: reqray({ panel: { gate: 'open' } }) or a function.\",\n });\n return true;\n }\n\n const method = request.method ?? 'GET';\n\n // Before anything reads a body: a refusal has to come earlier than the\n // work it refuses, and every state-changing route is behind this line.\n if (method !== 'GET' && method !== 'HEAD' && !isSameOrigin(request)) {\n sendJson(response, 403, { error: 'this request did not come from the panel' });\n return true;\n }\n\n if (route === '/api/meta' && method === 'GET') {\n // Typed rather than inline: this object is the `/api/meta` contract, and\n // the protocol is where that contract is written down.\n const meta: PanelMeta = {\n pid: process.pid,\n startedAt: Date.now() - Math.round(process.uptime() * 1000),\n mode: options.mode,\n bufferSize: options.bufferSize,\n replayEnabled: options.replay,\n blameEnabled: options.blame,\n detectors: detectorSettings(options),\n };\n sendJson(response, 200, meta);\n return true;\n }\n\n if (route === '/api/project' && method === 'GET') {\n // Async, unlike every other route here: it asks git which commit is\n // running, and a panel that lies about the build is worse than one that\n // takes a few milliseconds.\n void projectReport(options, source)\n .then((report) => sendJson(response, 200, report))\n .catch((error: unknown) => {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 500, { error: `project report unavailable: ${reason}` });\n });\n return true;\n }\n\n if (route === '/api/retention' && method === 'GET') {\n sendJson(response, 200, { retention: retentionOf(options), log: logOf(options) });\n return true;\n }\n\n if (route === '/api/retention' && method === 'POST') {\n handleRetention(options, request, response);\n return true;\n }\n\n if (route === '/api/timeline' && method === 'GET') {\n if (!source.timeSeries) {\n sendJson(response, 200, { timeline: null });\n return true;\n }\n const asked = Number(url.searchParams.get('buckets'));\n const buckets =\n Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), 512) : TIMELINE_BUCKETS;\n // A stretch, when the caller names one. A store with days of history\n // and an hour of traffic draws a strip that is empty but for two\n // columns; being able to ask for the part worth looking at is what\n // makes the strip readable without making it lie about the rest.\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const points =\n Number.isFinite(from) && Number.isFinite(to) && to > from\n ? source.timeSeries().filter((point) => point.startedAt >= from && point.startedAt <= to)\n : source.timeSeries();\n sendJson(response, 200, { timeline: buildTimeline(points, buckets) });\n return true;\n }\n\n if (route === '/api/requests' && method === 'GET') {\n const filter = parseFilter(url.searchParams);\n const limit = pageLimit(url.searchParams);\n const sort: RequestSort = url.searchParams.get('sort') === 'slowest' ? 'slowest' : 'recent';\n\n // A store that can page does its own filtering: a history on disk must\n // not be read into memory to answer one screenful.\n if (source.page) {\n const page = source.page({\n filter,\n limit,\n sort,\n cursor: url.searchParams.get('cursor'),\n });\n sendJson(response, 200, {\n requests: mutes.silence(page.rows),\n summary: page.summary,\n nextCursor: page.nextCursor,\n });\n return true;\n }\n\n // No `page()`: the same rule, applied here over everything the store\n // holds, rather than a second implementation of it.\n const page = pageFromList(\n source.list(),\n { filter, limit, sort, cursor: url.searchParams.get('cursor') },\n {\n pinned: new Set(source.pinned?.() ?? []),\n slowMs: options.sampling.slowMs || 500,\n },\n );\n sendJson(response, 200, {\n requests: mutes.silence(page.rows),\n summary: page.summary,\n nextCursor: page.nextCursor,\n });\n return true;\n }\n\n if (route === '/api/export/har' && method === 'GET') {\n const { requests: shown, dropped } = forExport(source, url.searchParams);\n sendDownload(\n response,\n 'reqray.har',\n 'application/json; charset=utf-8',\n JSON.stringify(toHar(shown, new Date(), exportNote(dropped)), null, 2),\n );\n return true;\n }\n\n if (route === '/api/export/curl' && method === 'GET') {\n const { requests: shown, dropped } = forExport(source, url.searchParams);\n sendDownload(\n response,\n 'reqray-requests.sh',\n 'text/x-shellscript; charset=utf-8',\n toCurlScript(shown, originOf(request), exportNote(dropped)),\n );\n return true;\n }\n\n if (route === '/api/blame' && method === 'POST') {\n if (!options.blame) {\n sendJson(response, 403, {\n error:\n 'git blame from the panel is off. Outside local development it is enabled explicitly: reqray({ blame: true }).',\n });\n return true;\n }\n handleBlame(options, request, response);\n return true;\n }\n\n if (route === '/api/routes' && method === 'GET') {\n sendJson(response, 200, routeStats(source.list(), mutes.set()));\n return true;\n }\n\n if (route === '/api/series' && method === 'GET') {\n if (!source.history) {\n // The store cannot read a stretch. Said plainly rather than drawn as\n // an empty chart, which would be a claim about a quiet week.\n sendJson(response, 200, { series: null });\n return true;\n }\n\n const now = Date.now();\n const to = positive(url.searchParams.get('to')) ?? now;\n const from = positive(url.searchParams.get('from')) ?? to - HOUR_MS;\n if (to <= from) {\n sendJson(response, 400, { error: 'the period must end after it starts' });\n return true;\n }\n\n const askedColumns = positive(url.searchParams.get('buckets'));\n const columns = askedColumns ? Math.min(Math.floor(askedColumns), 512) : SERIES_COLUMNS;\n const metrics = parseMetrics(url.searchParams);\n const filter = parseFilter(url.searchParams);\n\n const query = (span: { from: number; to: number }): HistoryQuery => ({\n ...span,\n // The period is the period, whatever the filter's own range says: the\n // screen owns the window, and a stale `from` in the filter would\n // silently narrow it.\n filter: { ...filter, from: span.from, to: span.to },\n });\n\n const current: HistorySamples = source.history(query({ from, to }));\n // The same length again, immediately before. Only ever used for a\n // comparison, so a truncated reading of it changes nothing that is\n // presented as complete.\n const before = source.history(query({ from: from - (to - from), to: from - 1 }));\n\n sendJson(response, 200, {\n series: historyOf(current, before.samples, { from, to, metrics, columns }),\n });\n return true;\n }\n\n if (route === '/api/findings' && method === 'GET') {\n if (!source.findings) {\n // The store cannot read its findings back. Said plainly rather than\n // rendered as an empty work list, which would be a claim about the\n // code being clean.\n sendJson(response, 200, { findings: null });\n return true;\n }\n const read = source.findings({\n from: positive(url.searchParams.get('from')),\n to: positive(url.searchParams.get('to')),\n });\n sendJson(response, 200, {\n findings: patternsOf(read, {\n states: source.findingStates?.(),\n changedAt: fileChangedAt,\n }),\n });\n return true;\n }\n\n if (route === '/api/findings/state' && method === 'POST') {\n handleFindingState(source, mutes, request, response);\n return true;\n }\n\n if (route === '/api/routes/series' && method === 'GET') {\n const wanted = url.searchParams.get('route');\n const verb = url.searchParams.get('method');\n if (!wanted || !verb) {\n sendJson(response, 400, { error: 'a route and a method are needed to draw one' });\n return true;\n }\n // A store that cannot answer draws nothing, rather than a chart of\n // whatever page the browser happened to be holding.\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const samples = source.durations?.({\n method: verb,\n route: wanted,\n // A chart is drawn over the stretch the caller names, so that it\n // covers the same traffic the table beside it describes.\n ...(Number.isFinite(from) && Number.isFinite(to) && to > from ? { from, to } : {}),\n });\n const asked = Number(url.searchParams.get('buckets'));\n const buckets =\n Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), 256) : SERIES_BUCKETS;\n sendJson(response, 200, {\n series: samples ? routeSeries(verb, wanted, samples, buckets) : null,\n });\n return true;\n }\n\n if (route === '/api/timeline/at' && method === 'GET') {\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const overallFrom = Number(url.searchParams.get('overallFrom'));\n const overallTo = Number(url.searchParams.get('overallTo'));\n if (![from, to, overallFrom, overallTo].every(Number.isFinite) || to <= from) {\n sendJson(response, 400, { error: 'a moment needs a start and an end, in epoch ms' });\n return true;\n }\n if (!source.counts) {\n sendJson(response, 200, { activity: null });\n return true;\n }\n sendJson(response, 200, {\n activity: whatRanAt(\n source.counts({ from, to }),\n source.counts({ from: overallFrom, to: overallTo }),\n { from, to, overallMs: overallTo - overallFrom },\n ),\n });\n return true;\n }\n\n if (route === '/api/pin' && method === 'POST') {\n handlePin(source, request, response);\n return true;\n }\n\n if (route === '/api/requests' && method === 'DELETE') {\n source.clear();\n sendJson(response, 200, { cleared: true });\n return true;\n }\n\n // ORDER MATTERS from here to the end of the `/api/requests/` group: these\n // are prefix matches, not exact ones, and `/api/requests/:id` below would\n // swallow `/api/requests/:id/baseline` if it came first. The chain has no\n // way to say so structurally, so it says so here.\n if (route.startsWith('/api/requests/') && route.endsWith('/baseline') && method === 'GET') {\n const id = decodeURIComponent(route.slice('/api/requests/'.length, -'/baseline'.length));\n const found = source.get(id);\n if (!found) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return true;\n }\n // A store that cannot answer produces no baseline, and the panel shows\n // no card: an absent comparison is an ordinary answer here.\n const samples = source.durations?.({\n method: found.method,\n route: normalizeRoute(found.path),\n excludeId: found.id,\n });\n sendJson(response, 200, {\n baseline: baselineFor(found, samples),\n pressure: samples ? pressureFor(samples) : null,\n });\n return true;\n }\n\n if (route.startsWith('/api/requests/') && method === 'GET') {\n const id = decodeURIComponent(route.slice('/api/requests/'.length));\n const found = source.get(id);\n if (!found) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return true;\n }\n // The row fields travel with the record: the panel's detail type\n // extends its row type, and a payload missing half of it is a contract\n // that silently reads `undefined`.\n sendJson(response, 200, {\n ...toRow(found, (source.pinned?.() ?? []).includes(id)),\n ...ensureTiming(found),\n });\n return true;\n }\n\n if (route === '/api/exceptions' && method === 'GET') {\n sendJson(response, 200, { groups: groupExceptions(source.list(), options.stack) });\n return true;\n }\n\n if (route === '/api/stream' && method === 'GET') {\n streamEvents(source, mutes, request, response, streams);\n return true;\n }\n\n if (route === '/api/explain' && method === 'POST') {\n if (!options.explain) {\n sendJson(response, 403, {\n error:\n 'EXPLAIN from the panel is off. Outside local development it is enabled explicitly: reqray({ explain: true }).',\n });\n return true;\n }\n handleExplain(source, request, response);\n return true;\n }\n\n if (route === '/api/replay' && method === 'POST') {\n if (!options.replay) {\n sendJson(response, 403, {\n error:\n 'replay is off. Outside local development it is enabled only explicitly: reqray({ replay: true }) — a replay in production means a second charge and a second email.',\n });\n return true;\n }\n handleReplay(source, request, response);\n return true;\n }\n\n if (route.startsWith('/api/')) {\n sendJson(response, 404, { error: 'no such panel endpoint' });\n return true;\n }\n\n if (method === 'GET' && init.assetsDir && serveAsset(init.assetsDir, route, response)) {\n return true;\n }\n\n sendJson(response, 404, {\n error: init.assetsDir\n ? 'panel asset not found'\n : 'the panel UI is not installed: add @reqray/dashboard. The API keeps working.',\n });\n return true;\n };\n\n return function handlePanelRequest(request, response): boolean {\n try {\n return serve(request, response);\n } catch (error) {\n // Only a panel request gets this far before anything can throw — a\n // malformed `%` in an id, say — and it must end here: on a bare\n // `node:http` server an exception in the listener takes the process,\n // which is the application's.\n const reason = error instanceof Error ? error.message : String(error);\n if (response.headersSent) response.destroy();\n else sendJson(response, 400, { error: `bad panel request: ${reason}` });\n return true;\n }\n };\n}\n\n/**\n * Changes how long requests are kept.\n *\n * The only setting the panel can write, and it deletes data on the way down,\n * so it is refused unless the application handed the panel a policy and said\n * it may be changed. Values are checked here rather than trusted: the panel\n * is a client like any other.\n */\nfunction handleRetention(\n options: ResolvedOptions,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n const policy = options.retention;\n if (!policy) {\n sendJson(response, 501, {\n error:\n 'this application keeps to fixed limits: pass reqray({ retention: retentionPolicy({ … }) }) to make them changeable.',\n });\n return;\n }\n if (!policy.writable) {\n sendJson(response, 403, {\n error: 'retention is read-only here: the policy was created with writable: false.',\n });\n return;\n }\n\n try {\n const payload = (await readBody(request)) as Partial<RetentionLimits>;\n const patch: Record<string, unknown> = {};\n for (const key of ['days', 'maxBytes', 'maxRequests'] as const) {\n if (key in payload) patch[key] = payload[key];\n }\n if (Object.keys(patch).length === 0) {\n sendJson(response, 400, { error: 'nothing to change: days, maxBytes or maxRequests' });\n return;\n }\n\n const limits = policy.update(patch as Partial<RetentionLimits>);\n // The stores sweep on their own schedule; what is reported back is the\n // policy, not a promise that the disk is already smaller.\n sendJson(response, 200, { retention: retentionOf(options), limits });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `retention unchanged: ${reason}` });\n }\n })();\n}\n\nfunction handleBlame(\n options: ResolvedOptions,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as {\n frames?: Array<{ file?: unknown; line?: unknown }>;\n };\n const frames = Array.isArray(payload.frames) ? payload.frames.slice(0, 30) : [];\n\n const blamed = await Promise.all(\n frames.map(async (frame) => {\n if (typeof frame.file !== 'string' || typeof frame.line !== 'number') return null;\n return blameLine(frame.file, frame.line, options.stack.projectRoot);\n }),\n );\n sendJson(response, 200, { frames: blamed });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `blame failed: ${reason}` });\n }\n })();\n}\n\n/**\n * When a file last changed, epoch ms — what `fixed?` is guessed from.\n *\n * The file's mtime rather than git: honest enough for a guess drawn with a\n * question mark, and free. Unreadable files answer \"nobody knows\".\n */\nfunction fileChangedAt(file: string): number | null {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return null;\n }\n}\n\n/**\n * What is muted, remembered between changes.\n *\n * Muting is presentation, not detection: the record keeps its findings, but a\n * muted pattern must stop flagging the list, the live feed and the routes\n * table alike — one that flashes amber on arrival and goes grey on reload is a\n * haunting.\n *\n * Held rather than rebuilt per call: it changes only when somebody mutes\n * something, and the live feed would otherwise walk the whole state map once\n * per request delivered.\n */\nclass MuteView {\n #muted: Set<string> | null = null;\n\n constructor(private readonly source: PanelSource) {}\n\n /** Pattern ids the reader muted, or an empty set when nothing is. */\n set(): ReadonlySet<string> {\n if (this.#muted) return this.#muted;\n\n const muted = new Set<string>();\n const states = this.source.findingStates?.();\n if (states) {\n for (const [id, state] of states) if (state === 'muted') muted.add(id);\n }\n this.#muted = muted;\n return muted;\n }\n\n /** Called when a state changes; the next read rebuilds. */\n forget(): void {\n this.#muted = null;\n }\n\n /**\n * Rows with muted patterns silenced.\n *\n * Only flagged rows are looked up — they are the rare ones — and a record\n * the store has already dropped keeps the flag it had.\n */\n silence(rows: readonly RequestRow[]): readonly RequestRow[] {\n const muted = this.set();\n if (muted.size === 0) return rows;\n return rows.map((row) => {\n if (row.flag === null) return row;\n const record = this.source.get(row.id);\n if (!record) return row;\n const flag = flagWithMutes(record, muted);\n return flag === row.flag ? row : { ...row, flag };\n });\n }\n}\n\n/**\n * The states a client may set.\n *\n * `fixed` is deliberately absent: it is a computed guess, and a stored one\n * would outlive the change it guessed about. The list is what both the check\n * and the refusal message are built from, so they cannot drift apart.\n */\nconst SETTABLE_STATES: readonly StoredPatternState[] = ['new', 'ack', 'muted'];\n\nfunction isSettable(value: unknown): value is StoredPatternState {\n return (SETTABLE_STATES as readonly unknown[]).includes(value);\n}\n\nfunction handleFindingState(\n source: PanelSource,\n mutes: MuteView,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n if (!source.setFindingState) {\n sendJson(response, 501, { error: 'this store cannot remember finding states' });\n return;\n }\n try {\n const payload = (await readBody(request)) as { id?: unknown; state?: unknown };\n if (typeof payload.id !== 'string' || payload.id.length === 0 || !isSettable(payload.state)) {\n sendJson(response, 400, {\n error: `a pattern id and a state (${SETTABLE_STATES.join(', ')}) are needed`,\n });\n return;\n }\n const state = payload.state;\n source.setFindingState(payload.id, state);\n // The only moment what is muted can change.\n mutes.forget();\n sendJson(response, 200, { ok: true });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `state change failed: ${reason}` });\n }\n })();\n}\n\nfunction handlePin(source: PanelSource, request: IncomingMessage, response: ServerResponse): void {\n void (async () => {\n if (!source.pin) {\n sendJson(response, 501, { error: 'this store cannot pin requests' });\n return;\n }\n try {\n const payload = (await readBody(request)) as { id?: unknown; pinned?: unknown };\n if (typeof payload.id !== 'string') {\n sendJson(response, 400, { error: 'id is required' });\n return;\n }\n const wanted = payload.pinned !== false;\n const ok = source.pin(payload.id, wanted);\n if (!ok && wanted) {\n // Either the record is already gone, or the pin board is full — both\n // are worth saying out loud rather than silently doing nothing.\n sendJson(response, 409, {\n error: 'could not pin: the request is gone, or too many are pinned already',\n });\n return;\n }\n sendJson(response, 200, { id: payload.id, pinned: wanted && ok });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `pin failed: ${reason}` });\n }\n })();\n}\n\nfunction handleExplain(\n source: PanelSource,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as { id?: unknown; spanId?: unknown };\n const record = typeof payload.id === 'string' ? source.get(payload.id) : undefined;\n if (!record) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return;\n }\n const spanId = typeof payload.spanId === 'number' ? payload.spanId : Number.NaN;\n\n sendJson(response, 200, await runExplain(record, spanId));\n } catch (error) {\n if (error instanceof ExplainError) {\n sendJson(response, error.status, { error: error.message });\n return;\n }\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.explain', `EXPLAIN failed: ${reason}`);\n sendJson(response, 500, { error: `EXPLAIN failed: ${reason}` });\n }\n })();\n}\n\nfunction handleReplay(\n source: PanelSource,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as {\n id?: unknown;\n method?: unknown;\n path?: unknown;\n headers?: unknown;\n body?: unknown;\n };\n\n const original = typeof payload.id === 'string' ? source.get(payload.id) : undefined;\n if (!original) {\n sendJson(response, 404, { error: 'original request not found' });\n return;\n }\n\n const input: ReplayInput = {\n method: typeof payload.method === 'string' ? payload.method : original.method,\n path: typeof payload.path === 'string' ? payload.path : original.path,\n headers:\n payload.headers && typeof payload.headers === 'object'\n ? (payload.headers as Record<string, string>)\n : {},\n body: typeof payload.body === 'string' ? payload.body : undefined,\n };\n\n sendJson(response, 200, await runReplay(originOf(request), input, original));\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.replay', `replay failed: ${reason}`);\n sendJson(response, 500, { error: `replay failed: ${reason}` });\n }\n })();\n}\n","/**\n * State that has to be single per process.\n *\n * `@reqray/core` is built as both ESM and CJS, and both builds can end up\n * loaded in one application at once: the adapter came in through `import`,\n * while a loader hook or a third-party package came in through `require`. That\n * gives two sets of module-level variables, and it is not cosmetic — two\n * `AsyncLocalStorage` instances mean instrumentation never sees the scope the\n * adapter created, and nothing is recorded at all.\n *\n * So anything that must be single lives on `globalThis`, under a symbol from\n * the global registry that both copies resolve to the same way. This file does\n * not hold that state — it hands out slots, and each module declares, names\n * and types the state it owns.\n */\n\n/** Version in the key: an incompatible change of shape must not break silently. */\nconst REGISTRY_KEY = Symbol.for('reqray.state.v2');\n\ntype Holder = typeof globalThis & { [REGISTRY_KEY]?: Map<string, unknown> };\n\nfunction registry(): Map<string, unknown> {\n const holder = globalThis as Holder;\n const existing = holder[REGISTRY_KEY];\n if (existing) return existing;\n\n const fresh = new Map<string, unknown>();\n holder[REGISTRY_KEY] = fresh;\n return fresh;\n}\n\n/**\n * Declares one piece of process-wide state and returns the way to read it.\n *\n * The name is the identity across module copies, so it must be unique and\n * stable — by convention, `<module>.<what>`. The accessor caches after the\n * first call: `current()` is the first line of every instrumentation wrapper\n * and must not cost a global lookup and a map read each time.\n *\n * @example\n * const fingerprints = globalSlot('sql.fingerprints', () => new Map<string, string>());\n */\nexport function globalSlot<T>(name: string, create: () => T): () => T {\n let cached: T | undefined;\n let resolved = false;\n\n return (): T => {\n if (resolved) return cached as T;\n\n const slots = registry();\n if (!slots.has(name)) slots.set(name, create());\n cached = slots.get(name) as T;\n resolved = true;\n return cached;\n };\n}\n\n/**\n * A single mutable value, for state that is not an object.\n *\n * A slot hands back a reference, so a boolean or a counter needs something to\n * be a reference *to*.\n */\nexport interface Box<T> {\n value: T;\n}\n\n/** @see Box */\nexport function globalBox<T>(name: string, initial: T): () => Box<T> {\n return globalSlot(name, () => ({ value: initial }));\n}\n\n/**\n * A bounded cache with no cliff at the limit.\n *\n * Clearing at the ceiling would make an application sitting just over it throw\n * away its hottest entries with its coldest and miss on everything until the\n * cache refills. Instead the hot generation becomes the cold one and a fresh\n * one starts; a read that hits the cold one promotes the entry. Holds at most\n * twice `limit`.\n */\nexport class TwoGenerationCache<K, V> {\n #hot = new Map<K, V>();\n #cold = new Map<K, V>();\n\n constructor(private readonly limit: number) {}\n\n get(key: K): V | undefined {\n const hot = this.#hot.get(key);\n if (hot !== undefined) return hot;\n\n const cold = this.#cold.get(key);\n if (cold === undefined) return undefined;\n // Used again, so it belongs in the generation that will survive.\n this.#hot.set(key, cold);\n return cold;\n }\n\n set(key: K, value: V): void {\n if (this.#hot.size >= this.limit) {\n this.#cold = this.#hot;\n this.#hot = new Map<K, V>();\n }\n this.#hot.set(key, value);\n }\n\n /** Whether the key is known in either generation. */\n has(key: K): boolean {\n return this.#hot.has(key) || this.#cold.has(key);\n }\n\n clear(): void {\n this.#hot.clear();\n this.#cold.clear();\n }\n\n /** Entries held right now, across both generations. Needed by tests. */\n get size(): number {\n let total = this.#hot.size;\n for (const key of this.#cold.keys()) if (!this.#hot.has(key)) total++;\n return total;\n }\n}\n","/**\n * Reqray's own logging.\n *\n * The project rule: an instrumentation error is caught, logged as a warning\n * **once** and disables that one instrument without touching the rest. Hence\n * {@link warnOnce}.\n */\n\nimport { type Box, globalBox, globalSlot } from './state.js';\n\n/** Where Reqray writes its own messages. */\nexport interface ReqrayLogSink {\n info(message: string): void;\n warn(message: string): void;\n}\n\n/** Keys of warnings already issued, so `warnOnce` means once per process. */\nconst warned = globalSlot('logger.warned', () => new Set<string>());\n\n/** Where Reqray writes its own messages. `null` — the default sink. */\nconst sink: () => Box<ReqrayLogSink | null> = globalBox('logger.sink', null);\n\nconst defaultSink: ReqrayLogSink = {\n info: (message) => console.info(message),\n warn: (message) => console.warn(message),\n};\n\n/** Replaces the message sink. Needed by tests and apps with their own logger. */\nexport function setLogSink(next: ReqrayLogSink | null): void {\n sink().value = next;\n}\n\n/** Writes an informational line, such as the startup report. */\nexport function info(message: string): void {\n try {\n (sink().value ?? defaultSink).info(message);\n } catch {\n // Even a broken logger must not break the application.\n }\n}\n\n/** Writes a warning, prefixed so it is obvious where it came from. */\nexport function warn(message: string): void {\n try {\n (sink().value ?? defaultSink).warn(`reqray: ${message}`);\n } catch {\n // Even a broken logger must not break the application.\n }\n}\n\n/**\n * Writes a warning only the first time a key shows up.\n *\n * Instrumentation on the hot path can fail thousands of times a second —\n * repeat messages add no information and only do harm.\n */\nexport function warnOnce(key: string, message: string): void {\n const seen = warned();\n if (seen.has(key)) return;\n seen.add(key);\n warn(message);\n}\n\n/** Forgets which warnings have already been issued. Needed by tests. */\nexport function resetWarnings(): void {\n warned().clear();\n}\n","/**\n * Duplicate-work detectors: the same call made twice in one request.\n *\n * Unlike the N+1 detectors, order does not matter here — two identical calls\n * are wasted work whether they were sequential or parallel. What does matter\n * is that the call is *safe* to have made once: only reads are flagged, since\n * \"memoize this\" is sound advice for a GET and dangerous for a POST.\n *\n * What is intentionally NOT flagged:\n * - anything but GET/HEAD, and cache writes: repeating those may be the point;\n * - failures and retries — a second attempt after a 5xx is correct behaviour;\n * - calls whose URLs differ at all, query string included: a different URL is\n * a different question, and collapsing them would invent a duplicate;\n * - cache reads of one key that ask for different things: `HGET user:1 email`\n * and `HGET user:1 name` are two reads, not one read made twice.\n */\n\nimport type { CacheSpan, Callsite, Finding, FindingSeverity, HttpSpan } from '../types.js';\nimport type { Detector } from './types.js';\n\nexport interface DuplicateHttpOptions {\n /** How many identical calls before it is worth reporting. */\n readonly threshold: number;\n /** Below this saving the duplicate is not worth a card. */\n readonly minWastedMs: number;\n}\n\nexport interface DuplicateCacheOptions {\n readonly threshold: number;\n}\n\nconst SEVERITY_WARN_MS = 50;\n\n/** Methods where a second identical call returns the same thing. */\nconst READ_METHODS = new Set(['GET', 'HEAD']);\n\nfunction isRetry(span: HttpSpan): boolean {\n if (span.error) return true;\n if (span.statusCode === null) return true;\n return span.statusCode >= 500 || span.statusCode === 429;\n}\n\n/**\n * What is saved by making the call once.\n *\n * The largest of the group is the one assumed to remain, so the number is\n * never larger than the time that actually exists.\n */\nfunction savingOf(spans: readonly { duration: number }[]): number {\n let total = 0;\n let slowest = 0;\n for (const span of spans) {\n total += span.duration;\n if (span.duration > slowest) slowest = span.duration;\n }\n return total - slowest;\n}\n\n/**\n * Where else the same call is made from.\n *\n * The panel already prints the finding's own callsite, so the hint names only\n * the *other* places — the half the reader cannot see yet.\n */\nfunction otherSites(spans: readonly { callsite: Callsite | null }[]): string[] {\n const site = (span: { callsite: Callsite | null }) =>\n span.callsite ? `${span.callsite.relative}:${span.callsite.line}` : '';\n const first = site(spans[0] ?? { callsite: null });\n return [...new Set(spans.slice(1).map(site).filter(Boolean))].filter((place) => place !== first);\n}\n\nfunction group<T>(items: readonly T[], keyOf: (item: T) => string): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n for (const item of items) {\n const key = keyOf(item);\n const existing = groups.get(key);\n if (existing) existing.push(item);\n else groups.set(key, [item]);\n }\n return groups;\n}\n\n/** Two identical outbound reads in one request. */\nexport const duplicateHttp: Detector<DuplicateHttpOptions> = {\n id: 'dup_http',\n\n defaultOptions: {\n threshold: 2,\n // An external call worth deduplicating costs at least this much; below it\n // the card is noise on a screen meant for the expensive things.\n minWastedMs: 10,\n },\n\n run(scope, options) {\n const calls = scope.spans.filter(\n (span): span is HttpSpan =>\n span.kind === 'http' && READ_METHODS.has(span.method.toUpperCase()) && !isRetry(span),\n );\n\n const findings: Finding[] = [];\n for (const [key, spans] of group(calls, (span) => `${span.method} ${span.url}`)) {\n if (spans.length < options.threshold) continue;\n\n const costMs = savingOf(spans);\n if (costMs < options.minWastedMs) continue;\n\n const severity: FindingSeverity = costMs >= SEVERITY_WARN_MS ? 'warn' : 'info';\n const first = spans[0];\n const others = otherSites(spans);\n\n findings.push({\n detector: 'dup_http',\n severity,\n title: `${spans.length} identical calls to the same URL`,\n costMs,\n callsite: first?.callsite ?? null,\n evidence: {\n kind: 'duplicate',\n repeats: spans.length,\n fingerprint: key,\n sample: first ? `${first.method} ${first.url}` : key,\n totalMs: spans.reduce((sum, span) => sum + span.duration, 0),\n spanIds: spans.map((span) => span.id),\n },\n hint:\n (others.length > 0 ? `also called from ${others.join(' and ')} — ` : '') +\n 'the second call returns what the first already fetched. Hold the result for the ' +\n 'duration of the request instead of asking again.',\n });\n }\n return findings;\n },\n};\n\n/**\n * The whole read, as the driver sent it: `GET user:1`, `HGET user:1 email`.\n *\n * The command and the selecting arguments are part of the identity on\n * purpose. `HGET user:1 email` and `HGET user:1 name` touch one key but read\n * different values, and calling that pair a duplicate would be a false\n * positive on a screen whose whole worth is that it does not cry wolf.\n */\nfunction callOf(span: CacheSpan): string {\n return span.command ? `${span.command} ${span.key}`.trimEnd() : span.key;\n}\n\n/** The same cache read made more than once in one request. */\nexport const duplicateCache: Detector<DuplicateCacheOptions> = {\n id: 'dup_cache',\n\n defaultOptions: { threshold: 2 },\n\n run(scope, options) {\n const reads = scope.spans.filter(\n (span): span is CacheSpan => span.kind === 'cache' && span.operation === 'get',\n );\n\n const findings: Finding[] = [];\n for (const [call, spans] of group(reads, callOf)) {\n if (spans.length < options.threshold) continue;\n\n const first = spans[0];\n const others = otherSites(spans);\n findings.push({\n detector: 'dup_cache',\n // Cache reads are cheap; this is a nudge about redundant work, not an\n // alarm about time, so it never outranks a real cost on the screen.\n severity: 'info',\n title: `${spans.length} reads of the same cache key`,\n costMs: savingOf(spans),\n callsite: first?.callsite ?? null,\n evidence: {\n kind: 'duplicate',\n repeats: spans.length,\n fingerprint: call,\n sample: first?.command ? call : `cache.get ${call}`,\n totalMs: spans.reduce((sum, span) => sum + span.duration, 0),\n spanIds: spans.map((span) => span.id),\n },\n hint:\n `\"${first?.key ?? call}\" is read ${spans.length} times while handling one request` +\n `${others.length > 0 ? `, also from ${others.join(' and ')}` : ''}` +\n ' — read it once and pass the value down.',\n });\n }\n return findings;\n },\n};\n","/**\n * What a request moved.\n *\n * The honest answer to \"where is the memory going\". Node has no per-request\n * memory to report: `process.memoryUsage()` around a request, under\n * concurrency and a garbage collector that runs when it likes, is noise and\n * occasionally negative. What *is* knowable is what the request pulled out of\n * the database and pushed back to the client — which is what the spike was\n * made of, and which points at a line of code rather than at a graph.\n */\n\nimport type { RecordedBody, RequestWeight, Span } from './types.js';\n\n/**\n * The size of a body, as the two sources know it.\n *\n * `content-length` is what the client was told and is preferred; the recorded\n * body's own size answers when the header is missing — a chunked response, a\n * framework that streams. Neither is a guess: when both are absent the answer\n * is `null`, and every screen shows nothing rather than a zero.\n */\nfunction bytesOf(\n headers: Readonly<Record<string, string>>,\n body: RecordedBody | null,\n): number | null {\n const declared = Number(headers['content-length']);\n if (Number.isFinite(declared) && declared >= 0) return declared;\n // A body recorded before sizes were kept has no answer to give, and saying\n // zero would put a route that returns megabytes at the bottom of the list.\n return body && Number.isFinite(body.bytes) ? body.bytes : null;\n}\n\n/** Rows across every query that reported a count, and the largest of them. */\nfunction rowsOf(spans: readonly Span[]): { rows: number; biggestRows: number } {\n let rows = 0;\n let biggestRows = 0;\n for (const span of spans) {\n if (span.kind !== 'db' || span.rowCount === null) continue;\n rows += span.rowCount;\n if (span.rowCount > biggestRows) biggestRows = span.rowCount;\n }\n return { rows, biggestRows };\n}\n\n/** What the request moved, in the numbers the panel and the detector read. */\nexport function weightOf(input: {\n readonly spans: readonly Span[];\n readonly requestHeaders: Readonly<Record<string, string>>;\n readonly responseHeaders: Readonly<Record<string, string>>;\n readonly requestBody: RecordedBody | null;\n readonly responseBody: RecordedBody | null;\n}): RequestWeight {\n return {\n bytesIn: bytesOf(input.requestHeaders, input.requestBody),\n bytesOut: bytesOf(input.responseHeaders, input.responseBody),\n ...rowsOf(input.spans),\n };\n}\n\n/**\n * The query a large response most likely came out of.\n *\n * The one that returned the most rows, when the driver says how many. When\n * none of them does — plenty of drivers do not — the answer is the query\n * itself if there was only one, and nothing at all if there were several:\n * picking the slowest and calling it the source would be a guess wearing\n * evidence's clothes.\n */\nexport function biggestQuery(spans: readonly Span[]): Extract<Span, { kind: 'db' }> | null {\n const queries = spans.filter((span): span is Extract<Span, { kind: 'db' }> => span.kind === 'db');\n const counted = queries.filter((span) => span.rowCount !== null);\n if (counted.length === 0) return queries.length === 1 ? (queries[0] ?? null) : null;\n\n let found = counted[0] ?? null;\n for (const span of counted) {\n if (found && (span.rowCount ?? 0) > (found.rowCount ?? 0)) found = span;\n }\n return found;\n}\n","/**\n * Heavy-response detector: this endpoint returned far more than it should.\n *\n * The mistake it names is a missing limit — a list route that grew with the\n * table behind it, an export that was never paginated, a serializer that\n * includes every relation because once it was convenient. It is the ordinary\n * cause of a memory graph that climbs under load, and it is invisible in a\n * waterfall: every query is fast, and the megabytes are in the tail.\n *\n * Two things it deliberately does not do.\n *\n * It does not report a cost in milliseconds. What a large response costs is\n * bytes: memory in this process, bandwidth, and time on somebody's phone that\n * this process never measured. Putting a made-up figure in `costMs` so that\n * the finding sorts higher would be inventing the one number the panel treats\n * as measured.\n *\n * And it does not fire on files. A twelve-megabyte PDF is a document; a\n * twelve-megabyte JSON document is a forgotten `LIMIT`. The content type is\n * the only thing that tells them apart, and guessing wrong here means telling\n * somebody their download is a bug.\n */\n\nimport type { Finding } from '../types.js';\nimport { biggestQuery } from '../weight.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\nexport interface HeavyResponseOptions {\n /** Response size above which the endpoint is doing something wrong. */\n readonly maxBytes: number;\n}\n\n/**\n * Content types that are documents rather than answers.\n *\n * Matched on what a response *is*, not on what it is not: an unknown type is\n * left alone. A detector that fires on everything it does not recognise is a\n * detector that gets switched off.\n */\nconst STRUCTURED = /^(application\\/(json|.*\\+json|xml|.*\\+xml|javascript)|text\\/)/i;\n\n/** What the panel says to do about it, in the order worth trying. */\nconst HINT =\n 'Paginate it, or return only the fields the caller uses. A response this size is memory in this process, bandwidth, and a wait on the device at the other end.';\n\n/** `12 MB`, `840 KB` — the size as the finding's title says it. */\nfunction size(bytes: number): string {\n if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n return `${Math.round(bytes / 1024)} KB`;\n}\n\nexport const heavyResponse: Detector<HeavyResponseOptions> = {\n id: 'heavy_response',\n\n defaultOptions: {\n // A megabyte of structured text is somewhere upwards of a thousand\n // objects. Under it, a response is within what a client absorbs without\n // anybody noticing; over it, somebody forgot a limit — and the threshold\n // has to be high enough that a normal page of results never reaches it,\n // because the first false positive is the one that gets the detector\n // turned off.\n maxBytes: 1024 * 1024,\n },\n\n run(scope, options, request: FinishedRequest): Finding[] {\n const bytes = request.bytesOut;\n if (bytes === null || bytes <= options.maxBytes) return [];\n\n const contentType = request.contentType;\n // Unknown type: no finding. A stream of bytes nobody labelled might be an\n // export somebody meant to write.\n if (!contentType || !STRUCTURED.test(contentType)) return [];\n\n const spans = scope.spans;\n const biggest = biggestQuery(spans);\n let rows = 0;\n for (const span of spans) {\n if (span.kind === 'db' && span.rowCount !== null) rows += span.rowCount;\n }\n\n const from = rows > 0 ? ` from ${rows.toLocaleString('en-US')} rows` : '';\n return [\n {\n detector: 'heavy_response',\n severity: 'warn',\n title: `${size(bytes)} response${from}`,\n // Bytes, not milliseconds — see the note at the top of this file.\n costMs: 0,\n callsite: biggest?.callsite ?? null,\n evidence: {\n kind: 'heavy_response',\n bytes,\n rows,\n sample: biggest ? biggest.sql.replace(/\\s+/g, ' ').trim() : null,\n contentType,\n spanIds: biggest ? [biggest.id] : [],\n },\n hint: HINT,\n },\n ];\n },\n};\n","/**\n * SQL normalization.\n *\n * The fingerprint is what repeats are grouped by: without it `SELECT * FROM\n * users WHERE id = 1` and `... id = 2` count as different queries and the N+1\n * detector finds nothing.\n *\n * Called on the hot path for every database query, hence a single-pass\n * character scanner (rather than a chain of regexes) plus a cache keyed by the\n * source string: the same SQL arrives thousands of times.\n */\n\n/** SQL statement type. Detectors only look at `select`. */\nexport type SqlOperation = 'select' | 'insert' | 'update' | 'delete' | 'other';\n\nimport { globalSlot, TwoGenerationCache } from './state.js';\n\n/**\n * Cache cap.\n *\n * Applications that build SQL dynamically can produce an unbounded set of\n * strings, so both caches have a ceiling. See {@link TwoGenerationCache} for\n * why hitting the ceiling is not a `clear()`: an application sitting just over\n * the limit would otherwise throw away its hottest entries with its coldest\n * and re-scan every statement until the cache refilled.\n */\nconst CACHE_LIMIT = 5_000;\n\nconst fingerprints = globalSlot(\n 'sql.fingerprints',\n () => new TwoGenerationCache<string, string>(CACHE_LIMIT),\n);\n\nconst operations = globalSlot(\n 'sql.operations',\n () => new TwoGenerationCache<string, SqlOperation>(CACHE_LIMIT),\n);\n\nconst CHAR_TAB = 9;\nconst CHAR_LF = 10;\nconst CHAR_CR = 13;\nconst CHAR_SPACE = 32;\nconst CHAR_QUOTE = 39; // '\nconst CHAR_DQUOTE = 34; // \"\nconst CHAR_BACKTICK = 96;\nconst CHAR_BACKSLASH = 92;\nconst CHAR_DASH = 45; // -\nconst CHAR_SLASH = 47; // /\nconst CHAR_STAR = 42; // *\nconst CHAR_DOLLAR = 36;\nconst CHAR_QUESTION = 63;\nconst CHAR_COLON = 58;\nconst CHAR_AT = 64;\nconst CHAR_DOT = 46;\nconst CHAR_PLUS = 43;\nconst CHAR_LOWER_E = 101;\nconst CHAR_UPPER_E = 69;\nconst CHAR_LPAREN = 40;\nconst CHAR_RPAREN = 41;\n\nfunction isSpace(code: number): boolean {\n return code === CHAR_SPACE || code === CHAR_TAB || code === CHAR_LF || code === CHAR_CR;\n}\n\nfunction isDigit(code: number): boolean {\n return code >= 48 && code <= 57;\n}\n\nfunction isIdentStart(code: number): boolean {\n // Anything above ASCII counts as part of an identifier: table names can be anything.\n return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code > 127;\n}\n\nfunction isIdentPart(code: number): boolean {\n return isIdentStart(code) || isDigit(code) || code === CHAR_DOLLAR;\n}\n\n/**\n * End of a dollar-quoted string tag `$tag$` (including the empty `$$`),\n * or -1 if this is not one.\n */\nfunction dollarTagEnd(sql: string, start: number): number {\n for (let i = start + 1; i < sql.length; i++) {\n const code = sql.charCodeAt(i);\n if (code === CHAR_DOLLAR) return i;\n // A tag may only contain letters, digits and `_`; `$` closes it.\n if (!isIdentStart(code) && !isDigit(code)) return -1;\n }\n return -1;\n}\n\nfunction scan(sql: string): string {\n const length = sql.length;\n let out = '';\n let pendingSpace = false;\n let i = 0;\n\n const push = (text: string): void => {\n if (pendingSpace && out.length > 0) out += ' ';\n pendingSpace = false;\n out += text;\n };\n\n while (i < length) {\n const code = sql.charCodeAt(i);\n\n if (isSpace(code)) {\n pendingSpace = true;\n i++;\n continue;\n }\n\n // Comments are dropped entirely: they do not affect what gets executed.\n if (code === CHAR_DASH && sql.charCodeAt(i + 1) === CHAR_DASH) {\n while (i < length && sql.charCodeAt(i) !== CHAR_LF) i++;\n pendingSpace = true;\n continue;\n }\n if (code === CHAR_SLASH && sql.charCodeAt(i + 1) === CHAR_STAR) {\n i += 2;\n while (\n i < length &&\n !(sql.charCodeAt(i) === CHAR_STAR && sql.charCodeAt(i + 1) === CHAR_SLASH)\n )\n i++;\n i += 2;\n pendingSpace = true;\n continue;\n }\n\n // String literal: neither its value nor its length may affect the fingerprint.\n if (code === CHAR_QUOTE) {\n i++;\n while (i < length) {\n const inner = sql.charCodeAt(i);\n if (inner === CHAR_BACKSLASH) {\n i += 2;\n continue;\n }\n if (inner === CHAR_QUOTE) {\n if (sql.charCodeAt(i + 1) === CHAR_QUOTE) {\n i += 2;\n continue;\n }\n i++;\n break;\n }\n i++;\n }\n push('?');\n continue;\n }\n\n // A quoted identifier is a table or column name — it is significant.\n if (code === CHAR_DQUOTE || code === CHAR_BACKTICK) {\n const start = i;\n i++;\n while (i < length && sql.charCodeAt(i) !== code) i++;\n i++;\n push(sql.slice(start, Math.min(i, length)));\n continue;\n }\n\n if (code === CHAR_DOLLAR) {\n if (isDigit(sql.charCodeAt(i + 1))) {\n i++;\n while (i < length && isDigit(sql.charCodeAt(i))) i++;\n push('?');\n continue;\n }\n const tagEnd = dollarTagEnd(sql, i);\n if (tagEnd !== -1) {\n const tag = sql.slice(i, tagEnd + 1);\n const close = sql.indexOf(tag, tagEnd + 1);\n i = close === -1 ? length : close + tag.length;\n push('?');\n continue;\n }\n push('$');\n i++;\n continue;\n }\n\n if (code === CHAR_QUESTION) {\n push('?');\n i++;\n continue;\n }\n\n if (code === CHAR_COLON) {\n // `::` is a Postgres cast, not a named parameter.\n if (sql.charCodeAt(i + 1) === CHAR_COLON) {\n push('::');\n i += 2;\n continue;\n }\n if (isIdentStart(sql.charCodeAt(i + 1))) {\n i++;\n while (i < length && isIdentPart(sql.charCodeAt(i))) i++;\n push('?');\n continue;\n }\n push(':');\n i++;\n continue;\n }\n\n if (code === CHAR_AT && isIdentStart(sql.charCodeAt(i + 1))) {\n i++;\n while (i < length && isIdentPart(sql.charCodeAt(i))) i++;\n push('?');\n continue;\n }\n\n if (isDigit(code) || (code === CHAR_DOT && isDigit(sql.charCodeAt(i + 1)))) {\n i++;\n while (i < length) {\n const next = sql.charCodeAt(i);\n if (isDigit(next) || next === CHAR_DOT) {\n i++;\n continue;\n }\n if (next === CHAR_LOWER_E || next === CHAR_UPPER_E) {\n const after = sql.charCodeAt(i + 1);\n const signed =\n (after === CHAR_PLUS || after === CHAR_DASH) && isDigit(sql.charCodeAt(i + 2));\n if (isDigit(after) || signed) {\n i += 2;\n continue;\n }\n }\n break;\n }\n push('?');\n continue;\n }\n\n if (isIdentStart(code)) {\n const start = i;\n i++;\n while (i < length && isIdentPart(sql.charCodeAt(i))) i++;\n push(sql.slice(start, i));\n continue;\n }\n\n push(sql[i] ?? '');\n i++;\n }\n\n return out;\n}\n\n// After normalization there is never more than one space between tokens, so\n// `\\s?` is enough in these patterns — which also rules out catastrophic\n// backtracking.\nconst IN_LIST = /\\bIN\\s?\\(\\s?\\?(?:,\\s?\\?)*\\s?\\)/gi;\nconst VALUES_TUPLES = /\\bVALUES\\s?(\\((?:\\?,\\s?)*\\?\\))(?:,\\s?\\((?:\\?,\\s?)*\\?\\))+/gi;\n\n/**\n * Collapses variable-length lists.\n *\n * `IN (?, ?, ?)` and `IN (?)` are the same query with a different number of\n * parameters; otherwise every list length yields its own fingerprint. Same for\n * batched `VALUES`.\n */\nfunction collapseLists(sql: string): string {\n return sql.replace(IN_LIST, 'IN (?)').replace(VALUES_TUPLES, 'VALUES $1');\n}\n\n/**\n * Normalized SQL fingerprint.\n *\n * Literals, numbers, placeholders and `IN (...)` lists of any length collapse\n * to `?`, comments are dropped and whitespace is reduced to single spaces.\n */\nexport function fingerprintSql(sql: string): string {\n const cache = fingerprints();\n const cached = cache.get(sql);\n if (cached !== undefined) return cached;\n\n const result = collapseLists(scan(sql));\n cache.set(sql, result);\n return result;\n}\n\nconst STATEMENT_KEYWORDS: Readonly<Record<string, SqlOperation>> = {\n select: 'select',\n insert: 'insert',\n update: 'update',\n delete: 'delete',\n};\n\n/**\n * Statement type: what the query does at the top level.\n *\n * Subqueries are ignored, so `WITH x AS (SELECT …) DELETE FROM …` is a\n * `delete`, not a `select`. Otherwise the N+1 detector would read a delete in\n * a loop as a repeated read and fire a false positive.\n *\n * Accepts a fingerprint or any SQL — comments and literals are handled.\n */\nexport function sqlOperation(sql: string): SqlOperation {\n const cache = operations();\n const cached = cache.get(sql);\n if (cached !== undefined) return cached;\n\n // The scan is idempotent: on an already normalized fingerprint it changes\n // nothing, while on raw SQL it strips comments and literals that could\n // otherwise contain keywords.\n const normalized = scan(sql);\n const length = normalized.length;\n let result: SqlOperation = 'other';\n let depth = 0;\n let insideCte = false;\n let i = 0;\n\n while (i < length) {\n const code = normalized.charCodeAt(i);\n if (code === CHAR_LPAREN) {\n depth++;\n i++;\n continue;\n }\n if (code === CHAR_RPAREN) {\n depth--;\n i++;\n continue;\n }\n if (!isIdentStart(code)) {\n i++;\n continue;\n }\n\n const start = i;\n while (i < length && isIdentPart(normalized.charCodeAt(i))) i++;\n if (depth > 0) continue;\n\n const word = normalized.slice(start, i).toLowerCase();\n if (word === 'with') {\n insideCte = true;\n continue;\n }\n const statement = STATEMENT_KEYWORDS[word];\n if (statement) {\n result = statement;\n break;\n }\n // First word is neither WITH nor a statement: nothing left to parse.\n if (!insideCte) break;\n }\n\n cache.set(sql, result);\n return result;\n}\n\n/** Clears the caches. Needed by tests and benchmarks. */\nexport function clearSqlCaches(): void {\n fingerprints().clear();\n operations().clear();\n}\n","/**\n * Shared machinery for loop-shaped detectors.\n *\n * N+1 and sequential-HTTP are the same finding over different span kinds:\n * repeats of one fingerprint, sequential in time, from a single line of code.\n * The heuristics live here once, so both detectors treat time and attribution\n * identically.\n */\n\nimport type { Callsite } from '../types.js';\n\n/** What the run heuristics need to know about a span. */\nexport interface TimedSpan {\n readonly id: number;\n readonly startedAt: number;\n readonly duration: number;\n readonly callsite: Callsite | null;\n /**\n * Milliseconds the span spent queueing before it could start.\n *\n * Absent for everything that does not queue. Where it is present it is the\n * difference between when the code *asked* for the work and when the work\n * began — and that difference is what tells a loop apart from a pool.\n */\n readonly waitMs?: number | null;\n}\n\nexport function endOf(span: TimedSpan): number {\n return span.startedAt + span.duration;\n}\n\n/**\n * When the code asked for this work, rather than when it got to run.\n *\n * A pool with one connection turns five queries issued through `Promise.all`\n * into five spans that follow one another exactly like a loop: the same SQL,\n * the same line, no overlap. Judged on when they *ran*, they are an N+1 and\n * the advice would be to parallelise code that is already parallel. Judged on\n * when they were *issued*, they all start at once, which is the truth.\n */\nexport function issuedAt(span: TimedSpan): number {\n return span.startedAt - (span.waitMs ?? 0);\n}\n\n/**\n * Splits a fingerprint group into runs on time gaps.\n *\n * The same call at the start and at the end of handling, separated by a long\n * unrelated operation, is not a loop. Splitting lets each run be judged on\n * its own, and short runs simply fall short of the threshold.\n */\nexport function splitRuns<T extends TimedSpan>(sorted: readonly T[], maxGapMs: number): T[][] {\n const runs: T[][] = [];\n let current: T[] = [];\n let previousEnd = Number.NEGATIVE_INFINITY;\n\n for (const span of sorted) {\n if (current.length > 0 && span.startedAt - previousEnd > maxGapMs) {\n runs.push(current);\n current = [];\n previousEnd = Number.NEGATIVE_INFINITY;\n }\n current.push(span);\n previousEnd = Math.max(previousEnd, endOf(span));\n }\n if (current.length > 0) runs.push(current);\n return runs;\n}\n\n/**\n * Share of adjacent pairs that overlap in time.\n *\n * A loop is a waterfall: each call starts after the previous one finished.\n * Calls issued through `Promise.all` overlap — that is already optimised,\n * nothing to fix.\n *\n * Measured from when each call was issued, not from when it started running:\n * see {@link issuedAt}. For everything that never queues the two are the same\n * number.\n */\nexport function overlapRatio(run: readonly TimedSpan[]): number {\n if (run.length < 2) return 0;\n\n let overlapping = 0;\n for (let i = 1; i < run.length; i++) {\n const previous = run[i - 1];\n const current = run[i];\n if (!previous || !current) continue;\n const overlap =\n Math.min(endOf(previous), endOf(current)) - Math.max(issuedAt(previous), issuedAt(current));\n if (overlap > 0) overlapping++;\n }\n return overlapping / (run.length - 1);\n}\n\n/**\n * The single place in the code the whole run came from.\n *\n * Returns `null` if the known callsites disagree (the same call from\n * different places is a coincidence, not a loop) or if there are none at all:\n * a finding without a line of code reports a problem but does not help fix it.\n */\nexport function singleCallsite(run: readonly TimedSpan[]): Callsite | null {\n let found: Callsite | null = null;\n for (const span of run) {\n const callsite = span.callsite;\n if (!callsite) continue;\n if (!found) {\n found = callsite;\n continue;\n }\n if (found.file !== callsite.file || found.line !== callsite.line) return null;\n }\n return found;\n}\n","/**\n * N+1 detector — Reqray's flagship finding.\n *\n * The governing principle here is not up for debate: **a false positive is\n * worse than a miss**. A tool that cries wolf gets switched off within a week.\n * So every heuristic below discards cases where the repeats have a plausible\n * explanation, even at the cost of missing some real N+1s.\n */\n\nimport { sqlOperation } from '../sql.js';\nimport type { DbSpan, Finding, FindingSeverity, Span } from '../types.js';\nimport { overlapRatio, singleCallsite, splitRuns } from './runs.js';\nimport type { Detector } from './types.js';\n\n/** Detector thresholds. All exposed as options — the user tunes them. */\nexport interface NPlusOneOptions {\n /** How many consecutive repeats make a group suspicious. */\n readonly threshold: number;\n /** Below this saving there is nothing worth reporting. */\n readonly minWastedMs: number;\n /**\n * Share of adjacent pairs overlapping in time above which the queries are\n * treated as parallel rather than as a loop.\n */\n readonly maxOverlapRatio: number;\n /**\n * Gap between adjacent repeats above which this is no longer one loop but\n * two different places that happened to run the same query.\n */\n readonly maxGapMs: number;\n}\n\nconst SEVERITY_CRITICAL_MS = 200;\nconst SEVERITY_WARN_MS = 50;\n\nconst TABLE_FROM_SQL = /\\bFROM\\s+\"?([\\w$.]+)\"?/i;\n\nfunction isDbSpan(span: Span): span is DbSpan {\n return span.kind === 'db';\n}\n\n/**\n * Groups SELECT spans by fingerprint.\n *\n * Batched `INSERT`/`UPDATE` is normal practice and must not be flagged, so\n * everything but `select` is dropped up front.\n */\nfunction groupSelects(spans: readonly Span[]): Map<string, DbSpan[]> {\n const groups = new Map<string, DbSpan[]>();\n for (const span of spans) {\n if (!isDbSpan(span)) continue;\n if (sqlOperation(span.fingerprint) !== 'select') continue;\n\n const existing = groups.get(span.fingerprint);\n if (existing) existing.push(span);\n else groups.set(span.fingerprint, [span]);\n }\n return groups;\n}\n\nfunction severityFor(costMs: number): FindingSeverity {\n if (costMs >= SEVERITY_CRITICAL_MS) return 'critical';\n if (costMs >= SEVERITY_WARN_MS) return 'warn';\n return 'info';\n}\n\nfunction hintFor(source: string | null, fingerprint: string): string {\n const table = TABLE_FROM_SQL.exec(fingerprint)?.[1] ?? 'the related table';\n\n switch (source) {\n case 'prisma':\n return `Prisma: pull \"${table}\" in with \\`include\\` on the parent query — one JOIN instead of a series of queries`;\n case 'drizzle':\n return `Drizzle: pull \"${table}\" in with \\`with\\` on the parent query`;\n case 'typeorm':\n return `TypeORM: list \"${table}\" in the parent query's \\`relations\\``;\n default:\n return `Collect the ids and fetch \"${table}\" with a single \\`WHERE … IN (…)\\` instead of a query per iteration`;\n }\n}\n\nconst LIMIT = /\\bLIMIT\\b/i;\n\n/**\n * Whether the run is one table being read a page at a time.\n *\n * `WHERE id > $1 ORDER BY id LIMIT 500` in a loop is the same SQL from the\n * same line, one after another — everything an N+1 is, except that it is the\n * fix rather than the problem: the alternative is one query for the whole\n * table. What gives it away is the shape of the answers: every page full, the\n * same size, until the last one. A lookup per parent row does not come back\n * like that unless every parent has exactly as many children as the limit,\n * and then \"fetch them with one IN\" would be the wrong advice anyway.\n *\n * A limit of one is left alone: that is `findFirst` in a loop, the most\n * common N+1 there is.\n */\nfunction isPaging(run: readonly DbSpan[], fingerprint: string): boolean {\n if (!LIMIT.test(fingerprint)) return false;\n\n const pageSize = run[0]?.rowCount ?? null;\n if (pageSize === null || pageSize < 2) return false;\n\n const last = run.length - 1;\n for (let i = 0; i < last; i++) {\n if (run[i]?.rowCount !== pageSize) return false;\n }\n const tail = run[last]?.rowCount ?? null;\n return tail !== null && tail <= pageSize;\n}\n\nfunction evaluate(\n run: readonly DbSpan[],\n fingerprint: string,\n options: NPlusOneOptions,\n): Finding | null {\n if (run.length < options.threshold) return null;\n if (isPaging(run, fingerprint)) return null;\n if (overlapRatio(run) > options.maxOverlapRatio) return null;\n\n const callsite = singleCallsite(run);\n if (!callsite) return null;\n\n let totalMs = 0;\n let slowestMs = 0;\n for (const span of run) {\n totalMs += span.duration;\n if (span.duration > slowestMs) slowestMs = span.duration;\n }\n\n // The fix does not remove the query altogether — it replaces the run with a\n // single query. Its cost is taken to be the slowest query of the run: a\n // deliberately conservative estimate, since we must never promise more saved\n // time than actually exists.\n const costMs = totalMs - slowestMs;\n if (costMs < options.minWastedMs) return null;\n\n const first = run[0];\n return {\n detector: 'n_plus_one',\n severity: severityFor(costMs),\n title: `${run.length} identical queries ran in a loop`,\n costMs,\n callsite,\n evidence: {\n kind: 'n_plus_one',\n repeats: run.length,\n fingerprint,\n sample: first ? first.sql : fingerprint,\n totalMs,\n spanIds: run.map((span) => span.id),\n },\n hint: hintFor(first?.source ?? null, fingerprint),\n };\n}\n\nexport const nPlusOne: Detector<NPlusOneOptions> = {\n id: 'n_plus_one',\n\n defaultOptions: {\n threshold: 5,\n minWastedMs: 20,\n maxOverlapRatio: 0.2,\n maxGapMs: 100,\n },\n\n run(scope, options) {\n const findings: Finding[] = [];\n\n for (const [fingerprint, spans] of groupSelects(scope.spans)) {\n // The whole group is below the threshold, so no run inside it can pass.\n if (spans.length < options.threshold) continue;\n\n spans.sort((a, b) => a.startedAt - b.startedAt || a.id - b.id);\n for (const run of splitRuns(spans, options.maxGapMs)) {\n const finding = evaluate(run, fingerprint, options);\n if (finding) findings.push(finding);\n }\n }\n\n return findings;\n },\n};\n","/**\n * Where a request's time went.\n *\n * The panel answers \"the database took 41 ms\". It does not answer \"and where\n * did the other 400 ms go\", which for a Node backend is the more common\n * question. This module answers it, once, in the core: the API, the panel and\n * the terminal client read the same number rather than each deriving its own\n * from the span tree.\n *\n * Everything here is an interval union rather than a sum. Adding span\n * durations up is the mistake that makes a `Promise.all` of four 100 ms\n * queries read as 400 ms of database time inside a 120 ms request — a number\n * that is not merely imprecise but larger than the request that contains it.\n */\n\nimport type { HandlerSpan, MiddlewareSpan, RecordedRequest, RequestTiming, Span } from './types.js';\nimport { weightOf } from './weight.js';\n\n/** A stretch of the request's clock, in milliseconds from its start. */\ninterface Interval {\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * A span that holds other work rather than doing any.\n *\n * Exported because the same distinction decides three different questions —\n * what counts as coverage, what a self time is measured against, and what an\n * unaccounted stretch sits inside — and a second definition of \"container\"\n * is how the three drift apart.\n */\nexport function isContainer(span: Span): span is MiddlewareSpan | HandlerSpan {\n return span.kind === 'handler' || span.kind === 'middleware';\n}\n\nfunction intervalOf(span: Span): Interval {\n return { start: span.startedAt, end: span.startedAt + span.duration };\n}\n\n/**\n * The same stretches with overlaps merged away.\n *\n * @param intervals in any order; the result is sorted and disjoint.\n */\nexport function mergeIntervals(intervals: readonly Interval[]): Interval[] {\n if (intervals.length === 0) return [];\n const sorted = [...intervals].sort((a, b) => a.start - b.start);\n const merged: Interval[] = [];\n let current = sorted[0] as Interval;\n for (const interval of sorted.slice(1)) {\n if (interval.start <= current.end) {\n current = { start: current.start, end: Math.max(current.end, interval.end) };\n } else {\n merged.push(current);\n current = interval;\n }\n }\n merged.push(current);\n return merged;\n}\n\n/** How much of the clock these stretches cover, counting overlaps once. */\nexport function coveredMs(intervals: readonly Interval[]): number {\n let total = 0;\n for (const interval of mergeIntervals(intervals)) total += interval.end - interval.start;\n return total;\n}\n\n/** Whether any two of them ran at the same time. */\nexport function anyOverlap(intervals: readonly Interval[]): boolean {\n const sorted = [...intervals].sort((a, b) => a.start - b.start);\n for (let index = 1; index < sorted.length; index++) {\n const previous = sorted[index - 1] as Interval;\n const current = sorted[index] as Interval;\n // Touching is not overlapping: one query ending exactly where the next\n // begins is a sequence, and a rounding tie must not read as concurrency.\n if (current.start < previous.end) return true;\n }\n return false;\n}\n\n/** How much of `outer` the stretches cover. */\nfunction coveredWithin(outer: Interval, intervals: readonly Interval[]): number {\n let total = 0;\n for (const interval of mergeIntervals(intervals)) {\n const start = Math.max(outer.start, interval.start);\n const end = Math.min(outer.end, interval.end);\n if (end > start) total += end - start;\n }\n return total;\n}\n\n/**\n * Time each span spent in its *own* code, by span id.\n *\n * A span's duration minus the stretch its children occupied — where children\n * that ran concurrently count once, and a child reaching outside its parent\n * (a clock that moved, a span closed late) counts only for the part inside.\n *\n * This is the number that answers \"what did the work\", and the reason the\n * panel does not rank by total: the handler is always at the top of that\n * list, because it contains everything and did nothing.\n */\nexport function selfTimes(spans: readonly Span[]): Map<number, number> {\n const children = new Map<number, Interval[]>();\n for (const span of spans) {\n if (span.parentId === null) continue;\n const list = children.get(span.parentId);\n if (list) list.push(intervalOf(span));\n else children.set(span.parentId, [intervalOf(span)]);\n }\n\n const self = new Map<number, number>();\n for (const span of spans) {\n const own = children.get(span.id);\n const covered = own ? coveredWithin(intervalOf(span), own) : 0;\n self.set(span.id, Math.max(0, span.duration - covered));\n }\n return self;\n}\n\n/**\n * Where the request's time went, as the header line reads it.\n *\n * `sqlMs`, `externalMs` and `cacheMs` are unions within their own kind, so\n * each is what that layer actually cost. They can still sum past the wall\n * clock when a query and an outgoing call overlapped, which is why `parallel`\n * travels with them: the panel says so rather than printing an addition that\n * does not add up.\n */\nexport function timingOf(spans: readonly Span[], durationMs: number): RequestTiming {\n const work = spans.filter((span) => !isContainer(span));\n const byKind = (kind: Span['kind']): Interval[] =>\n work.filter((span) => span.kind === kind).map(intervalOf);\n\n const all = work.map(intervalOf);\n const covered = coveredMs(all);\n\n return {\n sqlMs: coveredMs(byKind('db')),\n externalMs: coveredMs(byKind('http')),\n cacheMs: coveredMs(byKind('cache')),\n // Clamped: a span may finish a hair after the response is written, and a\n // negative \"your code\" would be read as a bug in the reader, not in us.\n selfMs: Math.max(0, durationMs - covered),\n parallel: anyOverlap(all),\n };\n}\n\n/**\n * The record with its timing filled in.\n *\n * Records written before this existed are still in stores on disk, and a\n * panel that shows a blank header for yesterday's request would be reporting\n * its own age as the request's fault. Computed on read, and only for those.\n */\nexport function ensureTiming(request: RecordedRequest): RecordedRequest {\n // Typed as required because they are required of anything written from now\n // on; what arrives from a store may predate them, and that is this case.\n const stored = request as Partial<RecordedRequest>;\n if (stored.timing !== undefined && stored.weight !== undefined && stored.cost !== undefined)\n return request;\n const self = selfTimes(request.spans);\n return {\n ...request,\n timing: stored.timing ?? timingOf(request.spans, request.durationMs),\n // Nothing was measuring the loop when this was written, and nothing can\n // work out afterwards what it was doing.\n host: request.host ?? null,\n // Weight, unlike the loop, is entirely derivable from what was stored.\n weight: stored.weight ?? weightOf(request),\n // Nothing was reading the processor clock when this was written, and no\n // arithmetic afterwards can recover what it said.\n cost: stored.cost ?? null,\n spans: request.spans.map((span) => ({ ...span, selfMs: self.get(span.id) ?? span.duration })),\n };\n}\n","/**\n * Pool-wait detector: the query did not take that long, it queued for that\n * long.\n *\n * This is the failure a waterfall is worst at showing. A query that waited\n * 338 ms for a free connection and then ran for 2 draws exactly like a query\n * that worked for 340, and the reader goes off to add an index that will not\n * help. The instrumentation measures the queue separately (`waitMs` on the\n * span); this detector is what says out loud that the queue, not the query,\n * was the request's problem.\n *\n * Two things keep it quiet.\n *\n * The driver only records a wait when the pool was genuinely saturated —\n * every connection in use and none left to create. A brand-new connection\n * being established, or an idle one handed over a tick later, is not a\n * queue, and reporting either would send somebody to change `max` when the\n * fix is elsewhere.\n *\n * And waits are counted as a union of intervals, never a sum. Five queries\n * issued through `Promise.all` queue at the same time, and adding their waits\n * together would claim a saving five times the size of the one that exists.\n *\n * The comparison that decides whether to speak — did it wait longer than it\n * ran — is made per query rather than on the totals, and for the same reason\n * in reverse: a saturated pool runs the queries behind the queue one after\n * another, so their durations add up to the whole request. Weighed against\n * that sum, the clearest case of contention there is comes out a coin flip.\n */\n\nimport { coveredMs } from '../timing.js';\nimport type { DbSpan, Finding, FindingSeverity, Span } from '../types.js';\nimport type { Detector } from './types.js';\n\nexport interface PoolWaitOptions {\n /** Below this, the queue is not the story of the request. */\n readonly minWaitMs: number;\n /**\n * How much of a query's wait must exceed its own run for it to count.\n *\n * At `1` the rule is the one the panel states: it waited longer than it\n * ran. Anything below that is a busy pool doing its job.\n *\n * Applied per query, never to the totals. A pool that serialises five\n * queries makes their run times add up to the whole request, and comparing\n * that sum against the waits would turn the plainest case of contention\n * into a coin flip decided by a couple of milliseconds.\n */\n readonly minRatio: number;\n}\n\n/** A quarter of a second in a queue is not a busy moment, it is a shortage. */\nconst SEVERITY_CRITICAL_MS = 250;\n\nfunction isDb(span: Span): span is DbSpan {\n return span.kind === 'db';\n}\n\nfunction severityFor(waitMs: number): FindingSeverity {\n return waitMs >= SEVERITY_CRITICAL_MS ? 'critical' : 'warn';\n}\n\nconst HINT =\n 'The pool had nothing free to give: every connection was in use and it was already at its limit. ' +\n 'Usually the fix is upstream — a transaction held open across an external call, or a query that runs far longer than it needs to. ' +\n 'Raising `max` helps only if the database can take the extra connections.';\n\nexport const poolWait: Detector<PoolWaitOptions> = {\n id: 'pool_wait',\n\n defaultOptions: {\n // Fifty milliseconds is where a queue stops being scheduling noise and\n // starts being something a reader can act on.\n minWaitMs: 50,\n minRatio: 1,\n },\n\n run(scope, options): Finding[] {\n const waited: DbSpan[] = [];\n for (const span of scope.spans) {\n if (!isDb(span)) continue;\n const wait = span.waitMs;\n if (wait === null || wait <= 0) continue;\n // Only the queries the queue, rather than the database, held up.\n if (wait <= span.duration * options.minRatio) continue;\n waited.push(span);\n }\n if (waited.length === 0) return [];\n\n // Concurrent queries queue concurrently: the request lost the union of\n // the waits, not their sum.\n const waitMs = coveredMs(\n waited.map((span) => ({ start: span.startedAt - (span.waitMs ?? 0), end: span.startedAt })),\n );\n if (waitMs < options.minWaitMs) return [];\n\n const runMs = coveredMs(\n waited.map((span) => ({ start: span.startedAt, end: span.startedAt + span.duration })),\n );\n\n let worst = waited[0] as DbSpan;\n for (const span of waited) {\n if ((span.waitMs ?? 0) > (worst.waitMs ?? 0)) worst = span;\n }\n\n const queries = waited.length;\n return [\n {\n detector: 'pool_wait',\n severity: severityFor(waitMs),\n title: `${queries === 1 ? 'A query' : `${queries} queries`} waited ${Math.round(waitMs)} ms for a free connection`,\n // Real time, and this request's own: had a connection been free, it\n // would have started that much sooner.\n costMs: waitMs,\n callsite: worst.callsite,\n evidence: {\n kind: 'pool_wait',\n waitMs,\n runMs,\n queries,\n sample: worst.sql.replace(/\\s+/g, ' ').trim(),\n spanIds: waited.map((span) => span.id),\n },\n hint: HINT,\n },\n ];\n },\n};\n","/**\n * Fingerprint of an outgoing HTTP call.\n *\n * The counterpart of `fingerprintSql` for the sequential-HTTP detector: calls\n * to `/users/1/orders` and `/users/2/orders` must collapse into one shape,\n * otherwise a loop over ids is invisible. Variable path segments — numbers,\n * uuids, long hex — become `:id`; the query string is dropped entirely\n * (its values are almost always the varying part).\n */\n\nimport { globalSlot, TwoGenerationCache } from './state.js';\n\nconst NUMERIC = /^\\d+$/;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst HEX = /^[0-9a-f]{8,}$/i;\n\nfunction normalizeSegment(segment: string): string {\n if (NUMERIC.test(segment) || UUID.test(segment) || HEX.test(segment)) return ':id';\n return segment;\n}\n\nconst CACHE_LIMIT = 5_000;\n\n/**\n * Process-wide cache: the same URL string is fingerprinted once.\n *\n * In the shared registry rather than in a module variable, for the same reason\n * everything else is: this is read on every outgoing call, and a dual ESM/CJS\n * load would otherwise give two caches with the same ceiling and half the hits\n * each.\n */\nconst cache = globalSlot(\n 'http.fingerprints',\n () => new TwoGenerationCache<string, string>(CACHE_LIMIT),\n);\n\n/**\n * Reduces an outgoing call to its shape: `GET api.example.com/users/:id/orders`.\n *\n * Never throws; an unparseable URL is used as-is.\n */\nexport function fingerprintHttp(method: string, url: string): string {\n const key = `${method} ${url}`;\n const fingerprints = cache();\n const cached = fingerprints.get(key);\n if (cached) return cached;\n\n let fingerprint: string;\n try {\n const parsed = new URL(url);\n const path = parsed.pathname.split('/').map(normalizeSegment).join('/');\n fingerprint = `${method.toUpperCase()} ${parsed.host}${path}`;\n } catch {\n fingerprint = `${method.toUpperCase()} ${url}`;\n }\n\n fingerprints.set(key, fingerprint);\n return fingerprint;\n}\n\n/** Clears the fingerprint cache. Needed by tests. */\nexport function clearHttpFingerprints(): void {\n cache().clear();\n}\n","/**\n * Sequential-HTTP detector: N+1 for outgoing calls.\n *\n * A loop of `await fetch(...)` over a list of ids is the same disease as a\n * query in a loop — each call waits for the previous one for no reason. The\n * heuristics are deliberately identical to the N+1 detector's, and the same\n * principle governs: **a false positive is worse than a miss**.\n *\n * What is intentionally NOT flagged:\n * - calls to *different* URLs in sequence: whether B needs A's response is\n * invisible from timing, and \"parallelize this\" on a dependent chain is a lie;\n * - overlapping calls — that is `Promise.all`, already optimised;\n * - repeats from different lines of code — a coincidence, not a loop;\n * - runs dominated by failures (5xx, 429, network errors) — that is a retry\n * loop, and retries are *supposed* to be sequential.\n */\n\nimport { fingerprintHttp } from '../http-fingerprint.js';\nimport type { Finding, FindingSeverity, HttpSpan, Span } from '../types.js';\nimport { overlapRatio, singleCallsite, splitRuns } from './runs.js';\nimport type { Detector } from './types.js';\n\n/** Detector thresholds. All exposed as options — the user tunes them. */\nexport interface SequentialHttpOptions {\n /** How many consecutive calls of one shape make a run suspicious. */\n readonly threshold: number;\n /** Below this saving there is nothing worth reporting. */\n readonly minWastedMs: number;\n /** Share of overlapping adjacent pairs above which the run is parallel. */\n readonly maxOverlapRatio: number;\n /** Gap between calls above which the run is not one loop. */\n readonly maxGapMs: number;\n}\n\nconst SEVERITY_CRITICAL_MS = 300;\nconst SEVERITY_WARN_MS = 100;\n\nfunction isHttpSpan(span: Span): span is HttpSpan {\n return span.kind === 'http';\n}\n\n/**\n * A retry, not a loop: the call failed at the transport level, hit a 5xx or\n * ran into rate limiting. Sequential retries are correct behaviour.\n */\nfunction looksLikeRetry(span: HttpSpan): boolean {\n if (span.error) return true;\n if (span.statusCode === null) return true;\n return span.statusCode >= 500 || span.statusCode === 429;\n}\n\nfunction groupCalls(spans: readonly Span[]): Map<string, HttpSpan[]> {\n const groups = new Map<string, HttpSpan[]>();\n for (const span of spans) {\n if (!isHttpSpan(span)) continue;\n if (looksLikeRetry(span)) continue;\n\n const fingerprint = fingerprintHttp(span.method, span.url);\n const existing = groups.get(fingerprint);\n if (existing) existing.push(span);\n else groups.set(fingerprint, [span]);\n }\n return groups;\n}\n\nfunction severityFor(costMs: number): FindingSeverity {\n if (costMs >= SEVERITY_CRITICAL_MS) return 'critical';\n if (costMs >= SEVERITY_WARN_MS) return 'warn';\n return 'info';\n}\n\nfunction evaluate(\n run: readonly HttpSpan[],\n fingerprint: string,\n options: SequentialHttpOptions,\n): Finding | null {\n if (run.length < options.threshold) return null;\n if (overlapRatio(run) > options.maxOverlapRatio) return null;\n\n const callsite = singleCallsite(run);\n if (callsite === null) return null;\n\n let totalMs = 0;\n let slowestMs = 0;\n for (const span of run) {\n totalMs += span.duration;\n if (span.duration > slowestMs) slowestMs = span.duration;\n }\n\n // Parallel execution is bounded by the slowest call, so the honest saving\n // is everything above it — never more than actually exists.\n const costMs = totalMs - slowestMs;\n if (costMs < options.minWastedMs) return null;\n\n const first = run[0];\n return {\n detector: 'sequential_http',\n severity: severityFor(costMs),\n title: `${run.length} HTTP calls ran sequentially`,\n costMs,\n callsite,\n evidence: {\n kind: 'sequential_http',\n repeats: run.length,\n fingerprint,\n sample: first ? `${first.method} ${first.url}` : fingerprint,\n totalMs,\n spanIds: run.map((span) => span.id),\n },\n hint:\n 'Calls of one shape from one place can run in parallel: `Promise.all(items.map(…))`. ' +\n 'Better yet — a batch endpoint, if the API offers one: a single call instead of a series.',\n };\n}\n\nexport const sequentialHttp: Detector<SequentialHttpOptions> = {\n id: 'sequential_http',\n\n defaultOptions: {\n // HTTP calls are an order of magnitude dearer than queries, so the bar is\n // lower than the N+1 detector's.\n threshold: 3,\n minWastedMs: 30,\n maxOverlapRatio: 0.2,\n maxGapMs: 100,\n },\n\n run(scope, options) {\n const findings: Finding[] = [];\n\n for (const [fingerprint, spans] of groupCalls(scope.spans)) {\n if (spans.length < options.threshold) continue;\n\n spans.sort((a, b) => a.startedAt - b.startedAt || a.id - b.id);\n for (const run of splitRuns(spans, options.maxGapMs)) {\n const finding = evaluate(run, fingerprint, options);\n if (finding) findings.push(finding);\n }\n }\n\n return findings;\n },\n};\n","/**\n * Budget detector: this request took longer than the page can afford.\n *\n * The other detectors name a specific mistake. This one names a fact — the\n * request went over budget — and then says where the time went, because\n * \"slow\" without a direction is not worth a card. It only fires when the\n * request is genuinely over the line, so the screen stays quiet on a healthy\n * session.\n */\n\nimport type { RequestScope } from '../scope.js';\nimport { coveredMs, timingOf } from '../timing.js';\nimport type { Finding } from '../types.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\nexport interface SlowBudgetOptions {\n /** Wall time above which a request is over budget, milliseconds. */\n readonly budgetMs: number;\n}\n\n/**\n * Where the time went — the same arithmetic the header line uses.\n *\n * Unions rather than sums, so a `Promise.all` of four 200 ms calls inside a\n * 300 ms request is 300 ms of waiting and not 800 ms of it. A hint drawn from\n * a figure larger than the request it describes is worse than no hint.\n */\nfunction breakdown(scope: RequestScope, durationMs: number) {\n return timingOf(scope.spans, durationMs);\n}\n\n/**\n * Of the time spent in the database layer, how much was spent queueing.\n *\n * A union, like everything else here: queries issued together queue together.\n */\nfunction queuedMs(scope: RequestScope): number {\n const waits: Array<{ start: number; end: number }> = [];\n for (const span of scope.spans) {\n if (span.kind !== 'db' || !span.waitMs) continue;\n waits.push({ start: span.startedAt - span.waitMs, end: span.startedAt });\n }\n return waits.length === 0 ? 0 : coveredMs(waits);\n}\n\n/** Above this share, the queue rather than the layer is what to look at. */\nconst MOSTLY_QUEUE = 0.5;\n\nexport const slowBudget: Detector<SlowBudgetOptions> = {\n id: 'slow_budget',\n\n defaultOptions: {\n // The number the panel already treats as \"red\" in the duration column.\n budgetMs: 700,\n },\n\n run(scope: RequestScope, options: SlowBudgetOptions, request: FinishedRequest): Finding[] {\n if (request.durationMs <= options.budgetMs) return [];\n\n const timing = breakdown(scope, request.durationMs);\n const share = (ms: number) => Math.round((ms / request.durationMs) * 100);\n\n // The layer that actually holds the time leads the hint — the largest\n // one, not the first one that is above zero. A request that spent 99% of\n // itself in application code must not be sent to look at the one query\n // that took a millisecond.\n const layers: Array<[string, number]> = [\n ['external HTTP calls', timing.externalMs],\n ['SQL', timing.sqlMs],\n ['the cache', timing.cacheMs],\n ];\n const [label, ms] = layers.reduce((most, layer) => (layer[1] > most[1] ? layer : most));\n\n // A layer can hold the time without being the reason for it. Queries\n // that spent most of their lives waiting for a free connection put the\n // whole wait under \"SQL\", and sending the reader to the queries would be\n // sending them past the finding directly above this one.\n const queued = label === 'SQL' ? queuedMs(scope) : 0;\n\n const hint =\n ms <= timing.selfMs\n ? `Most of the time (${share(timing.selfMs)}%) is not covered by any instrumentation: it is application code, a timer, or something Reqray does not see.`\n : queued > ms * MOSTLY_QUEUE\n ? `${share(ms)}% of the time went to SQL — but ${share(queued)}% of the request was queueing for a free connection, not querying. The pool is the constraint, not the query.`\n : `${share(ms)}% of the time went to ${label} — start there.`;\n\n return [\n {\n detector: 'slow_budget',\n severity: 'warn',\n title: `Over the ${options.budgetMs} ms budget`,\n // The overshoot: what would have to go for the request to fit.\n costMs: request.durationMs - options.budgetMs,\n callsite: null,\n evidence: {\n kind: 'budget',\n durationMs: request.durationMs,\n budgetMs: options.budgetMs,\n externalMs: timing.externalMs,\n sqlMs: timing.sqlMs,\n spanIds: [],\n },\n hint,\n },\n ];\n },\n};\n","/**\n * Slow-code detector: the stretch of a request nothing accounts for.\n *\n * Every other detector names something Reqray watched happen — a query, an\n * outgoing call, a connection held open too long. This one names the\n * opposite: a stretch where nothing it watches was running at all. That is\n * the answer a waterfall gives worst, because the evidence for it is an empty\n * space, and it is the most common answer for a Node backend once the\n * database has been ruled out.\n *\n * The whole difficulty is that an empty space has two explanations — code\n * that ran, or I/O Reqray has no instrumentation for — and only one of them is\n * worth telling somebody about. Coverage is how they are told apart: if the\n * rest of the request was well accounted for, then Reqray does see this\n * application's I/O, and a hole in it is the application's own work. If it\n * was not, Reqray is blind to this process and says nothing, because a tool\n * that blames your code for its own blind spot is a tool nobody keeps\n * installed.\n *\n * What it deliberately does not claim is CPU. The process knows how far\n * behind its event loop was, but never which request put it there — under\n * concurrency the code that blocked the loop is usually somebody else's, so\n * the finding reports a stretch of the request's own wall clock and leaves\n * the loop to the host monitor, which measures the process and says so.\n */\n\nimport type { RequestScope } from '../scope.js';\nimport { coveredMs, isContainer } from '../timing.js';\nimport type { Finding, HandlerSpan, MiddlewareSpan, Span } from '../types.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\nexport interface SlowCodeOptions {\n /** Shortest stretch worth reporting, milliseconds. */\n readonly minMs: number;\n /** What share of the request the stretch has to be, 0..1. */\n readonly minShare: number;\n /**\n * How much of the request's unaccounted time this one stretch has to be,\n * 0..1.\n *\n * The guard against blaming the application for an uninstrumented driver,\n * and the one that actually separates the two cases. A process Reqray cannot\n * see is not slow in one place — it is full of holes, one per call it has\n * no instrumentation for. A process Reqray can see, with one slow function\n * in it, has exactly one. So the question is not how much was covered but\n * whether the silence is concentrated: one long stretch is a thing that\n * happened, and a dozen comparable ones are a blind spot.\n */\n readonly minDominance: number;\n /**\n * Instrumented spans the request must have before any of this is evidence.\n *\n * One is the honest floor: it proves instrumentation was live for this\n * request, which is the difference between a hole in the record and no\n * record at all. A request with nothing in it says nothing about the code.\n */\n readonly minSpans: number;\n}\n\n/** An interval of the request, in milliseconds from its start. */\ninterface Interval {\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * A stretch of the request with no instrumented work in it, and its edges.\n *\n * The neighbours travel with it because they are the whole address: an\n * unaccounted stretch has no callsite of its own, and \"between the query at\n * orders.ts:47 and the call at mailer.ts:12\" is the closest thing to a line\n * number that the absence of evidence can honestly produce.\n */\ninterface Stretch {\n readonly start: number;\n readonly end: number;\n /** The span that finished before it, or `null` when it opens the request. */\n readonly before: Span | null;\n /** The span that ends it, or `null` when the request ends with it. */\n readonly after: Span | null;\n}\n\n/**\n * What a span was doing, for the line that brackets the stretch.\n *\n * The same shapes the other detectors quote, so a reader who has seen one\n * sample has seen them all.\n */\nfunction describe(span: Span): string {\n if (span.kind === 'db') return span.sql.replace(/\\s+/g, ' ').trim();\n if (span.kind === 'http') return `${span.method} ${span.url}`;\n if (span.kind === 'cache') return `${span.command ?? span.operation} ${span.key}`;\n return span.label;\n}\n\n/**\n * The stretch a span occupies, with a query's queueing counted as occupied.\n *\n * Time spent waiting for a free connection is the one idle-looking stretch of\n * a request that is fully accounted for; calling it unaccounted would hide an\n * answer the pool-wait detector already gives behind the word for \"no\n * answer\".\n */\nfunction occupied(span: Span): Interval {\n const wait = span.kind === 'db' ? (span.waitMs ?? 0) : 0;\n return { start: span.startedAt - wait, end: span.startedAt + span.duration };\n}\n\n/**\n * Every unaccounted stretch, in order.\n *\n * A sweep rather than a comparison of every span against every other: at five\n * hundred spans the quadratic version is the detector that costs more than\n * what it measures.\n */\nfunction stretchesOf(work: readonly Span[], durationMs: number): Stretch[] {\n const ordered = work\n .map((span) => ({ span, at: occupied(span) }))\n .sort((a, b) => a.at.start - b.at.start);\n\n const stretches: Stretch[] = [];\n let cursor = 0;\n let previous: Span | null = null;\n\n for (const { span, at } of ordered) {\n if (at.start > cursor) {\n stretches.push({ start: cursor, end: at.start, before: previous, after: span });\n }\n // Only a span that reaches further than everything before it moves the\n // cursor, and only that span is the one a later stretch follows.\n if (at.end > cursor) {\n cursor = at.end;\n previous = span;\n }\n }\n\n if (durationMs > cursor) {\n stretches.push({ start: cursor, end: durationMs, before: previous, after: null });\n }\n return stretches;\n}\n\n/**\n * The innermost handler or middleware the stretch sits inside.\n *\n * Innermost because that is the one that names something: every stretch is\n * inside the handler, and being told the time was spent in the request is not\n * being told anything.\n */\nfunction containerAround(\n spans: readonly Span[],\n stretch: Stretch,\n): MiddlewareSpan | HandlerSpan | null {\n let found: MiddlewareSpan | HandlerSpan | null = null;\n for (const span of spans) {\n if (!isContainer(span)) continue;\n const at = occupied(span);\n if (at.start > stretch.start || at.end < stretch.end) continue;\n if (!found || span.duration < found.duration) found = span;\n }\n return found;\n}\n\n/**\n * Where to send the reader.\n *\n * The span *after* the stretch, in preference to the one before it: the code\n * that ran during the hole is the code that led up to the next call, so its\n * callsite is the bottom of the stretch rather than the top of it. A trailing\n * stretch has no next call, and then the last thing that ran is the best\n * address there is.\n */\nfunction callsiteFor(stretch: Stretch, container: Span | null) {\n return stretch.after?.callsite ?? container?.callsite ?? stretch.before?.callsite ?? null;\n}\n\n/** A response big enough that writing it is a candidate for the time itself. */\nconst HEAVY_TAIL_BYTES = 1024 * 1024;\n\n/**\n * Whether the stretch can be called code without hedging.\n *\n * It can when instrumented work sits on both sides of it: the silence is then\n * demonstrably *between* two things Reqray watched happen, which is where\n * application code runs. At either edge of a request it is not — a leading\n * stretch shares its ground with parsing and middleware Reqray never saw, a\n * trailing one with serializing and writing the response — so an edge keeps\n * the hedge whatever the arithmetic says.\n *\n * Deliberately structural rather than a ratio. Coverage is the obvious\n * measure and it inverts exactly where it matters: the more completely the\n * stretch fills the request, the smaller the window the ratio is computed\n * over, so the clearest cases come out the least certain.\n */\nfunction bracketed(stretch: Stretch): boolean {\n return stretch.before !== null && stretch.after !== null;\n}\n\n/**\n * What to do about it.\n *\n * Three readings, because the same hole means three different things\n * depending on where it sits and how much Reqray can see around it — and a\n * hint that reads the same in all three is a hint nobody acts on.\n */\nfunction hintFor(stretch: Stretch, request: FinishedRequest): string {\n const trailing = stretch.after === null;\n\n if (trailing && request.bytesOut !== null && request.bytesOut >= HEAVY_TAIL_BYTES) {\n return `It is the last thing the request does and the response is ${Math.round(request.bytesOut / 1024)} KB — serializing that and writing it to the socket is the first thing to rule out.`;\n }\n\n if (bracketed(stretch)) {\n return 'Instrumented work sits on both sides of it, so the time is the application’s own: a loop, a parse, a crypto or compression call, or something waiting on a timer.';\n }\n\n return 'This is either the application’s own work or I/O Reqray has no instrumentation for. It covers SQL, outgoing HTTP and the cache — if this request also talks to something else, that is the first place to look.';\n}\n\nexport const slowCode: Detector<SlowCodeOptions> = {\n id: 'slow_code',\n\n defaultOptions: {\n // A tenth of a second: long enough that a person waiting notices it, and\n // far enough above ordinary scheduling jitter that the detector is not\n // reporting the event loop's own heartbeat back as a defect.\n minMs: 100,\n // Under a third of the request, something else is the story — and the\n // budget detector is already the place where \"it was slow\" gets said.\n minShare: 0.3,\n // Seven tenths of the silence in one place. Below that the request has\n // several comparable holes, which is what a process Reqray cannot see\n // looks like, and picking the largest of them would be picking one call\n // out of a driver it does not support and calling it your code.\n minDominance: 0.7,\n // Enough to know instrumentation was live for this request. More would\n // exclude the plainest case there is — one query, then a long wait on\n // something that is not the database.\n minSpans: 1,\n },\n\n run(scope: RequestScope, options: SlowCodeOptions, request: FinishedRequest): Finding[] {\n if (request.durationMs <= 0) return [];\n\n const work = scope.spans.filter((span) => !isContainer(span));\n // Too little watched work for coverage to be evidence of anything. An\n // application whose database Reqray does not instrument looks exactly like\n // an application that does everything in a loop, and the difference\n // cannot be recovered from a request this thin.\n if (work.length < options.minSpans) return [];\n\n const stretches = stretchesOf(work, request.durationMs);\n if (stretches.length === 0) return [];\n\n // The largest single stretch, never the sum of them: forty scattered\n // milliseconds of ordinary async overhead add up to a number that looks\n // like a defect and points at nothing.\n const worst = stretches.reduce((most, stretch) =>\n stretch.end - stretch.start > most.end - most.start ? stretch : most,\n );\n\n const stretchMs = worst.end - worst.start;\n if (stretchMs < options.minMs) return [];\n\n const share = stretchMs / request.durationMs;\n if (share < options.minShare) return [];\n\n // Is the silence concentrated here, or is the whole request full of it?\n const silentMs = stretches.reduce((total, gap) => total + (gap.end - gap.start), 0);\n if (stretchMs / silentMs < options.minDominance) return [];\n\n // Of the time outside the stretch, how much instrumentation accounted\n // for. Not a gate — it decides how much the hint is willing to claim.\n // Unioned, so queries that ran together count once; a sum would report\n // coverage above one.\n const outsideMs = request.durationMs - stretchMs;\n if (outsideMs <= 0) return [];\n const coverage = Math.min(1, coveredMs(work.map(occupied)) / outsideMs);\n\n const container = containerAround(scope.spans, worst);\n const spanIds = [worst.before?.id, worst.after?.id].filter(\n (id): id is number => id !== undefined,\n );\n\n const where = container ? ` in ${container.label}` : '';\n // The heading claims exactly what the hint is prepared to defend. Saying\n // \"your own code\" above a sentence that goes on to allow it might not be\n // is the kind of small contradiction that costs a tool its credibility on\n // the findings that matter.\n const what = bracketed(worst) ? 'of your own code' : 'nothing accounts for';\n\n return [\n {\n detector: 'slow_code',\n severity: 'warn',\n title: `${Math.round(stretchMs)} ms ${what}${where}`,\n // The whole stretch: unlike a duplicate query, there is no irreducible\n // remainder that has to happen anyway. It is an upper bound on the\n // saving, and the hint says what it is made of rather than promising\n // that all of it comes back.\n costMs: stretchMs,\n callsite: callsiteFor(worst, container),\n evidence: {\n kind: 'slow_code',\n stretchMs,\n atMs: worst.start,\n share,\n coverage,\n label: container?.label ?? null,\n before: worst.before ? describe(worst.before) : null,\n after: worst.after ? describe(worst.after) : null,\n spanIds,\n // Filled in afterwards, when the sampling profiler is running: a\n // detector is a pure function of the scope, and reading a profiler\n // is neither pure nor something the scope knows about.\n frames: [],\n busyShare: null,\n },\n hint: hintFor(worst, request),\n },\n ];\n },\n};\n","/**\n * Grouping a request's queries into the transactions they ran in.\n *\n * Nothing new is recorded to make this work. `BEGIN`, `COMMIT` and `ROLLBACK`\n * arrive as ordinary queries, and every db span already carries the\n * connection it ran on — so a transaction is simply the stretch between the\n * two ends *on one connection*. That last part is the whole reason this is a\n * shared helper rather than a line inside a detector: a query issued on some\n * other connection while a transaction is open did not happen inside it, and\n * getting that wrong turns every parallel query in a busy request into\n * evidence of a problem that is not there.\n */\n\nimport type { DbSpan, Span } from '../types.js';\n\n/** One transaction, as the spans of a single request show it. */\nexport interface Transaction {\n readonly connectionId: number;\n /** The `BEGIN` that opened it. */\n readonly begin: DbSpan;\n /**\n * The `COMMIT` or `ROLLBACK` that closed it.\n *\n * `null` when the request ended with the transaction still open — which is\n * either a leak or a request that was cut short, and in both cases the\n * connection was held right up to the end.\n */\n readonly end: DbSpan | null;\n /** Queries between the two ends; the ends themselves are not among them. */\n readonly queries: readonly DbSpan[];\n /** Relative ms from the request start, as spans measure it. */\n readonly startedAt: number;\n /** Where the hold ended: the end of `COMMIT`, or the end of the request. */\n readonly endedAt: number;\n}\n\n/**\n * Transaction control statements, matched on the whole first word.\n *\n * Two traps are deliberate. `ROLLBACK TO SAVEPOINT` does not close a\n * transaction — it rewinds inside one, and reading it as an end would cut a\n * transaction in half and hide everything after the savepoint. And `END` is\n * Postgres's synonym for `COMMIT`, which is why the boundary matters: without\n * it the word would also match a column called `ENDED_AT`.\n */\nconst BEGIN_RE = /^(?:BEGIN|START\\s+TRANSACTION)\\b/;\nconst END_RE = /^(?:COMMIT|ROLLBACK|END)\\b/;\nconst ROLLBACK_TO_RE = /^ROLLBACK\\s+TO\\b/;\n\n/** Leading comments an ORM may prepend, so the first word is the statement. */\nconst LEADING_COMMENTS = /^(?:\\s|\\/\\*[\\s\\S]*?\\*\\/|--[^\\n]*\\n)+/;\n\n/** `begin`, `end`, or `null` for an ordinary query. */\nexport function statementKind(sql: string): 'begin' | 'end' | null {\n // The first characters are enough, and bounding the work keeps a detector\n // from walking a megabyte of generated SQL to read one word.\n const head = sql.slice(0, 200).replace(LEADING_COMMENTS, '').toUpperCase();\n if (BEGIN_RE.test(head)) return 'begin';\n if (ROLLBACK_TO_RE.test(head)) return null;\n if (END_RE.test(head)) return 'end';\n return null;\n}\n\n/** End of a span, in the same relative milliseconds `startedAt` uses. */\nfunction endOf(span: Span): number {\n return span.startedAt + span.duration;\n}\n\n/**\n * The transactions a request opened.\n *\n * @param spans every span of the request, in any order.\n * @param requestEndMs where an unclosed transaction stops being measurable —\n * the request's own duration.\n */\nexport function transactionsOf(spans: readonly Span[], requestEndMs: number): Transaction[] {\n const byConnection = new Map<number, DbSpan[]>();\n for (const span of spans) {\n if (span.kind !== 'db' || span.connectionId === null) continue;\n const existing = byConnection.get(span.connectionId);\n if (existing) existing.push(span);\n else byConnection.set(span.connectionId, [span]);\n }\n\n const transactions: Transaction[] = [];\n for (const [connectionId, queries] of byConnection) {\n queries.sort((a, b) => a.startedAt - b.startedAt || a.id - b.id);\n\n let begin: DbSpan | null = null;\n let inside: DbSpan[] = [];\n\n for (const span of queries) {\n const kind = statementKind(span.sql);\n\n if (kind === 'begin') {\n // A second `BEGIN` with none of it closed is not a nested\n // transaction — Postgres has no such thing — so the first one stands.\n if (!begin) {\n begin = span;\n inside = [];\n }\n continue;\n }\n\n if (kind === 'end') {\n if (begin) {\n transactions.push({\n connectionId,\n begin,\n end: span,\n queries: inside,\n startedAt: begin.startedAt,\n endedAt: endOf(span),\n });\n begin = null;\n inside = [];\n }\n continue;\n }\n\n if (begin) inside.push(span);\n }\n\n if (begin) {\n transactions.push({\n connectionId,\n begin,\n end: null,\n queries: inside,\n startedAt: begin.startedAt,\n // Held until the request ended, which is the last moment anything\n // here can honestly speak for.\n endedAt: Math.max(requestEndMs, endOf(begin)),\n });\n }\n }\n\n return transactions;\n}\n\n/** How long `span` and the window overlap, in ms. Never negative. */\nexport function overlapMs(span: Span, from: number, to: number): number {\n return Math.max(0, Math.min(endOf(span), to) - Math.max(span.startedAt, from));\n}\n","/**\n * Transaction-hold detector: what the connection was doing while it was held.\n *\n * A transaction is not just a correctness construct, it is a connection taken\n * out of the pool for as long as it is open. Two hundred milliseconds of a\n * payment API called between `BEGIN` and `COMMIT` is two hundred milliseconds\n * one connection cannot serve anybody else with, and it is invisible to\n * anything that looks only at SQL or only at outgoing calls: you have to see\n * both, on the same connection, to see it at all.\n *\n * One finding per transaction, never two. The external call and the long hold\n * are the same problem — a connection held for something that is not a query\n * — with the same fix in the same place, and reporting them separately would\n * put two entries on the screen about one `BEGIN`.\n *\n * What it will not fire on:\n * - a call made after the `COMMIT`: the overlap with the open window is zero,\n * which is the whole point of measuring an overlap rather than an order;\n * - a query on another connection while a transaction is open — it was not\n * inside it, and `transactionsOf` groups by connection precisely so this\n * cannot happen;\n * - an implicit single-statement transaction, which every write is: without\n * an explicit `BEGIN` there is no transaction here to talk about;\n * - a transaction that was long because its queries were long. That is a\n * slow query, the panel already says so, and saying it twice in different\n * words is how a tool teaches people to skim its findings.\n */\n\nimport { coveredMs } from '../timing.js';\nimport type { Finding, FindingSeverity, HttpSpan, Span } from '../types.js';\nimport { overlapMs, type Transaction, transactionsOf } from './transactions.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\nexport interface TransactionHoldOptions {\n /**\n * Time inside outgoing calls made while a transaction was open, above which\n * the hold is reported.\n */\n readonly minExternalMs: number;\n /** How long a transaction may hold a connection before the hold is itself the finding. */\n readonly maxHeldMs: number;\n /**\n * How much of a long hold must have gone on something other than querying.\n *\n * A transaction that spent its whole life running queries is a slow query,\n * not a held connection.\n */\n readonly minIdleMs: number;\n}\n\n/** A quarter of a second of somebody else's service, with a connection in hand. */\nconst SEVERITY_CRITICAL_MS = 250;\n\nconst EXTERNAL_HINT =\n 'Move the call out of the transaction: read what you need, call, then open the transaction to write. ' +\n 'While it is open the connection belongs to this request alone, and a pool runs out of connections long before a payment API runs out of patience.';\n\nconst HOLD_HINT =\n 'Do the work before `BEGIN`, not inside it. A transaction is a connection taken out of the pool, and everything that is not a query — serialisation, a template, a call to another service — is time the pool is one connection smaller.';\n\n/** `POST api.stripe.com/v1/charges` — the call, without its query string. */\nfunction callLabel(span: HttpSpan): string {\n const cut = span.url.indexOf('?');\n return `${span.method} ${cut === -1 ? span.url : span.url.slice(0, cut)}`;\n}\n\n/** Milliseconds spent querying inside the window, counted once. */\nfunction sqlInside(transaction: Transaction): number {\n const spans = [transaction.begin, ...transaction.queries];\n if (transaction.end) spans.push(transaction.end);\n return coveredMs(\n spans.map((span) => ({\n start: Math.max(span.startedAt, transaction.startedAt),\n end: Math.min(span.startedAt + span.duration, transaction.endedAt),\n })),\n );\n}\n\n/** Outgoing calls that overlap the open window, longest first. */\nfunction callsInside(spans: readonly Span[], transaction: Transaction): HttpSpan[] {\n const inside: HttpSpan[] = [];\n for (const span of spans) {\n if (span.kind !== 'http') continue;\n if (overlapMs(span, transaction.startedAt, transaction.endedAt) <= 0) continue;\n inside.push(span);\n }\n return inside.sort((a, b) => b.duration - a.duration);\n}\n\nfunction findingFor(\n spans: readonly Span[],\n transaction: Transaction,\n options: TransactionHoldOptions,\n): Finding | null {\n const heldMs = transaction.endedAt - transaction.startedAt;\n const sqlMs = sqlInside(transaction);\n const queries = transaction.queries.length;\n const spanIds = [transaction.begin.id, ...transaction.queries.map((span) => span.id)];\n if (transaction.end) spanIds.push(transaction.end.id);\n\n const calls = callsInside(spans, transaction);\n // A union, not a sum: two calls made through `Promise.all` inside one\n // transaction held the connection once, for as long as the longer of them.\n const externalMs = coveredMs(\n calls.map((span) => ({\n start: Math.max(span.startedAt, transaction.startedAt),\n end: Math.min(span.startedAt + span.duration, transaction.endedAt),\n })),\n );\n\n const worst = calls[0];\n if (worst && externalMs >= options.minExternalMs) {\n const severity: FindingSeverity = externalMs >= SEVERITY_CRITICAL_MS ? 'critical' : 'warn';\n const what =\n calls.length === 1 ? `a ${Math.round(externalMs)} ms call` : `${calls.length} calls`;\n return {\n detector: 'transaction_hold',\n severity,\n title: `A transaction held a connection through ${what}`,\n // Not this request's time: moving the call out does not make the\n // request faster, it gives the connection back sooner. The cost lands\n // on every other request queueing for the pool, and putting a figure\n // here would promise a saving this request will never see.\n costMs: 0,\n // The call is where the fix is written, not the `BEGIN`.\n callsite: worst.callsite ?? transaction.begin.callsite,\n evidence: {\n kind: 'transaction',\n heldMs,\n sqlMs,\n externalMs,\n queries,\n sample: callLabel(worst),\n closedBy: transaction.end ? (statementLabel(transaction.end.sql) ?? null) : null,\n spanIds: [...spanIds, ...calls.map((span) => span.id)],\n },\n hint: EXTERNAL_HINT,\n };\n }\n\n const idleMs = heldMs - sqlMs;\n if (heldMs >= options.maxHeldMs && idleMs >= options.minIdleMs) {\n return {\n detector: 'transaction_hold',\n severity: 'warn',\n title: `A transaction held a connection for ${Math.round(heldMs)} ms, ${Math.round(sqlMs)} ms of it querying`,\n costMs: 0,\n callsite: transaction.begin.callsite,\n evidence: {\n kind: 'transaction',\n heldMs,\n sqlMs,\n externalMs,\n queries,\n sample: null,\n closedBy: transaction.end ? (statementLabel(transaction.end.sql) ?? null) : null,\n spanIds,\n },\n hint: HOLD_HINT,\n };\n }\n\n return null;\n}\n\n/** `COMMIT` or `ROLLBACK`, as the statement itself spells it. */\nfunction statementLabel(sql: string): string | null {\n const word = sql.trim().split(/[\\s;]/, 1)[0];\n return word ? word.toUpperCase() : null;\n}\n\nexport const transactionHold: Detector<TransactionHoldOptions> = {\n id: 'transaction_hold',\n\n defaultOptions: {\n // Fifty milliseconds of somebody else's service is already longer than\n // most of the queries the connection was taken out for.\n minExternalMs: 50,\n maxHeldMs: 500,\n minIdleMs: 100,\n },\n\n run(scope, options, request: FinishedRequest): Finding[] {\n const findings: Finding[] = [];\n for (const transaction of transactionsOf(scope.spans, request.durationMs)) {\n const finding = findingFor(scope.spans, transaction, options);\n if (finding) findings.push(finding);\n }\n return findings;\n },\n};\n","/**\n * Every detector there is, in one object.\n *\n * The single source: `DetectOptions` and `ResolvedDetectOptions` are mapped\n * types over these keys, so a new detector is one line and its options follow.\n *\n * Its own module rather than `detectors/index.ts` because `config.ts` needs\n * it, and the barrel imports `ResolvedDetectOptions` back out of config.\n */\n\nimport { duplicateCache, duplicateHttp } from './duplicates.js';\nimport { heavyResponse } from './heavy-response.js';\nimport { nPlusOne } from './n-plus-one.js';\nimport { poolWait } from './pool-wait.js';\nimport { sequentialHttp } from './sequential-http.js';\nimport { slowBudget } from './slow-budget.js';\nimport { slowCode } from './slow-code.js';\nimport { transactionHold } from './transaction-hold.js';\nimport type { Detector } from './types.js';\n\n/**\n * The detectors, keyed by the name they are configured under.\n *\n * Order matters only for the startup report and for `/api/meta`: findings\n * themselves are sorted by severity and cost when a request finishes.\n */\nexport const detectors = {\n nPlusOne,\n sequentialHttp,\n duplicateHttp,\n duplicateCache,\n slowBudget,\n slowCode,\n heavyResponse,\n poolWait,\n transactionHold,\n} as const;\n\n/** A key of `reqray({ detect: { … } })`. */\nexport type DetectorKey = keyof typeof detectors;\n\n/** The options one detector takes. */\nexport type DetectorOptions<K extends DetectorKey> =\n (typeof detectors)[K] extends Detector<infer Options> ? Options : never;\n\n/** The keys, as an array — `Object.keys` alone loses the type. */\nexport const detectorKeys = Object.keys(detectors) as readonly DetectorKey[];\n","/**\n * Detector registry and its runner.\n *\n * Detectors run after the response has been sent. A failing detector disables\n * only itself: the user must still get the remaining findings.\n */\n\nimport type { ResolvedOptions } from '../config.js';\nimport { warnOnce } from '../logger.js';\nimport type { RequestScope } from '../scope.js';\nimport { globalSlot } from '../state.js';\n\n/**\n * Detectors that disabled themselves after throwing.\n *\n * Process-wide, which is a compromise worth naming: two Reqray instances in one\n * process share this, so a detector that fails on one instance's data stops\n * running for the other too.\n */\nconst disabledDetectors = globalSlot('detectors.disabled', () => new Set<string>());\n\nimport type { Finding } from '../types.js';\nimport { detectorKeys, detectors } from './registry.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\n/**\n * Every detector with the thresholds it actually runs with.\n *\n * For `/api/meta`: an empty findings tab must be able to say what was\n * looking and how it was tuned, or silence reads as a clean bill of health.\n */\nexport function detectorSettings(options: ResolvedOptions): Array<{\n id: string;\n enabled: boolean;\n options: Record<string, number | boolean | string> | null;\n}> {\n return detectorKeys.map((key) => ({\n id: detectors[key].id,\n enabled: options.detect[key] !== null,\n options: options.detect[key] as Record<string, number | boolean | string> | null,\n }));\n}\n\n/** Loudest first, so a sort can put the worse of two findings above. */\nconst SEVERITY: Record<string, number> = { critical: 2, warn: 1, info: 0 };\n\n/**\n * Runs the enabled detectors over a finished request.\n *\n * Findings are sorted by severity and then by cost. Cost alone was enough\n * while every detector measured its damage in milliseconds; a response of\n * twelve megabytes costs bytes, and sorting it below a duplicate cache read\n * that wasted a third of one would order the screen by what is measurable\n * rather than by what matters.\n */\nexport function runDetectors(\n scope: RequestScope,\n options: ResolvedOptions,\n request: FinishedRequest,\n): Finding[] {\n const findings: Finding[] = [];\n const disabled = disabledDetectors();\n\n for (const key of detectorKeys) {\n const detector: Detector<unknown> = detectors[key];\n if (disabled.has(detector.id)) continue;\n\n const detectorOptions = options.detect[key];\n if (!detectorOptions) continue;\n\n try {\n findings.push(...detector.run(scope, detectorOptions, request));\n } catch (error) {\n disabled.add(detector.id);\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce(\n `detector.${detector.id}`,\n `detector ${detector.id} disabled itself after an error: ${reason}`,\n );\n }\n }\n\n return findings.sort(\n (a, b) => (SEVERITY[b.severity] ?? 0) - (SEVERITY[a.severity] ?? 0) || b.costMs - a.costMs,\n );\n}\n\n/** Puts disabled detectors back into service. Needed by tests. */\nexport function resetDetectors(): void {\n disabledDetectors().clear();\n}\n\nexport {\n type DuplicateCacheOptions,\n type DuplicateHttpOptions,\n duplicateCache,\n duplicateHttp,\n} from './duplicates.js';\nexport { type HeavyResponseOptions, heavyResponse } from './heavy-response.js';\nexport { type NPlusOneOptions, nPlusOne } from './n-plus-one.js';\nexport { type PoolWaitOptions, poolWait } from './pool-wait.js';\nexport { type SequentialHttpOptions, sequentialHttp } from './sequential-http.js';\nexport { type SlowBudgetOptions, slowBudget } from './slow-budget.js';\nexport { type SlowCodeOptions, slowCode } from './slow-code.js';\nexport { type TransactionHoldOptions, transactionHold } from './transaction-hold.js';\nexport {\n overlapMs,\n statementKind,\n type Transaction,\n transactionsOf,\n} from './transactions.js';\nexport type { Detector, FinishedRequest } from './types.js';\n","/**\n * Panel access.\n *\n * The panel exposes request bodies, headers and SQL. It is therefore never\n * mounted silently where the process may be reachable from outside: with no\n * explicit gate the application fails at startup with a clear error.\n *\n * Local development means `NODE_ENV` equal to `development`, `test` or unset\n * altogether — the same reading Express itself uses. Everything else\n * (`staging`, `production`, any custom value) requires a gate.\n */\n\nimport type { ResolvedOptions } from './config.js';\nimport type { PanelGate, PanelRequestContext } from './types.js';\n\nexport type { PanelGate, PanelRequestContext };\n\n/** Access error. A separate class so it can be caught in a test. */\nexport class PanelGateError extends Error {\n override readonly name = 'PanelGateError';\n}\n\nfunction gateErrorMessage(mode: string): string {\n return [\n `reqray: panel not mounted — NODE_ENV=${mode} does not count as local development.`,\n 'The panel exposes request bodies, headers and SQL, so it must not open without a check.',\n 'Set a gate:',\n \" reqray({ panel: { gate: (ctx) => ctx.headers['x-reqray-token'] === process.env.REQRAY_TOKEN } })\",\n 'Or disable the panel: reqray({ panel: false })',\n \"Or, if open access is a deliberate decision: reqray({ panel: { gate: 'open' } })\",\n ].join('\\n');\n}\n\n/**\n * Checks that the panel may be mounted. Throws {@link PanelGateError} if a\n * gate is required but not set.\n */\nexport function assertPanelAllowed(options: ResolvedOptions): void {\n const panel = options.panel;\n if (!panel) return;\n if (panel.gate) return;\n if (options.isLocalDevelopment) return;\n\n throw new PanelGateError(gateErrorMessage(process.env['NODE_ENV'] ?? 'unset'));\n}\n\nconst LOOPBACK_IP = /^(?:::ffff:)?127\\.|^::1$/;\nconst LOCAL_HOST = /^(?:localhost|[^.]+\\.localhost|127(?:\\.\\d+){3}|\\[::1\\])(?::\\d+)?$/i;\n\n/**\n * Whether a request came from this machine, addressed to this machine.\n *\n * What stands in for a gate when none is set. \"No gate\" is granted to local\n * development, and `NODE_ENV` is a poor witness of that: a server deployed\n * without it reads as a laptop. The peer address is a better one. The `Host`\n * check is for the page in the developer's own browser: a hostile domain\n * re-pointed at 127.0.0.1 arrives from loopback, but still names itself.\n */\nexport function isLocalRequest(context: PanelRequestContext): boolean {\n if (!context.ip || !LOOPBACK_IP.test(context.ip)) return false;\n const host = context.headers['host'];\n // HTTP/1.0 sends none, and no browser speaks it.\n return host === undefined || (typeof host === 'string' && LOCAL_HOST.test(host));\n}\n\n/** Whether a particular request is let into the panel. */\nexport function isPanelRequestAllowed(\n gate: PanelGate | null,\n context: PanelRequestContext,\n): boolean {\n if (!gate) return isLocalRequest(context);\n if (gate === 'open') return true;\n try {\n return gate(context) === true;\n } catch {\n // A gate that throws is treated as a denial: access must never be opened\n // silently.\n return false;\n }\n}\n","/**\n * Occurrences into patterns — the arithmetic behind the findings tab.\n *\n * The grouping happens here, once, for every store: a store hands over one\n * row per occurrence and says when it stopped reading, the same division of\n * labour the history screen uses. Grouping is by detector plus code\n * location, not by request — `GET /api/orders` and `GET /api/orders/flaky`\n * both firing N+1 at the same line are one problem — and falls back to the\n * route when a finding carries no location, because \"somewhere on this\n * endpoint\" is still one somewhere.\n */\n\nimport type {\n Callsite,\n FindingPattern,\n FindingSeverity,\n FindingsResponse,\n PatternExample,\n StoredPatternState,\n} from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { normalizeRoute } from './routes.js';\n\n/**\n * One finding occurrence, as the tab needs it.\n *\n * A dozen fields rather than a record: the requests that carry findings are\n * a small minority, but a window of them is still not something to hold as\n * payloads to look at one finding in each.\n */\nexport interface FindingSample {\n readonly requestId: string;\n readonly startedAt: number;\n readonly method: string;\n readonly route: string;\n readonly status: number;\n readonly durationMs: number;\n readonly detector: string;\n readonly severity: FindingSeverity;\n readonly title: string;\n readonly costMs: number;\n readonly callsite: Callsite | null;\n readonly hint: string;\n}\n\n/** What a store hands back, and whether it read the whole window. */\nexport interface FindingSamples {\n readonly samples: readonly FindingSample[];\n readonly truncated: boolean;\n}\n\n/** The stretch of time a findings reading covers. Absent bounds mean all. */\nexport interface FindingsQuery {\n readonly from?: number | undefined;\n readonly to?: number | undefined;\n}\n\n/**\n * A request's findings, reduced to occurrence rows.\n *\n * For every store that keeps whole records, so the tab does not depend on\n * which store is behind it.\n */\nexport function findingSamplesOf(request: RecordedRequest): FindingSample[] {\n return request.findings.map((finding) => ({\n requestId: request.id,\n startedAt: request.startedAt,\n method: request.method,\n route: normalizeRoute(request.path),\n status: request.status,\n durationMs: request.durationMs,\n detector: finding.detector,\n severity: finding.severity,\n title: finding.title,\n costMs: finding.costMs,\n callsite: finding.callsite,\n hint: finding.hint,\n }));\n}\n\n/**\n * The pattern a finding belongs to.\n *\n * The code location when there is one — the same problem fires from the same\n * line whatever route reached it — and the route otherwise, so locationless\n * findings (a blown budget, a heavy response) still group by where they live.\n */\nexport function patternKey(sample: {\n readonly detector: string;\n readonly callsite: Callsite | null;\n readonly method: string;\n readonly route: string;\n}): string {\n return sample.callsite\n ? `${sample.detector}@${sample.callsite.relative}:${sample.callsite.line}`\n : `${sample.detector}@${sample.method} ${sample.route}`;\n}\n\n/** How many example requests a pattern carries. */\nconst EXAMPLE_LIMIT = 3;\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = { info: 0, warn: 1, critical: 2 };\n\nexport interface PatternsOptions {\n /** `ack`/`muted` per pattern id, as the store remembered them. */\n readonly states?: ReadonlyMap<string, StoredPatternState> | undefined;\n /**\n * When a file last changed, epoch ms, or `null` when nobody knows.\n *\n * Injected rather than read here: the aggregation stays pure, and what\n * \"changed\" means (mtime, a commit) is the caller's business.\n */\n readonly changedAt?: ((file: string) => number | null) | undefined;\n}\n\n/** Groups occurrences into the tab's patterns, costliest first. */\nexport function patternsOf(read: FindingSamples, options: PatternsOptions = {}): FindingsResponse {\n interface Bucket {\n latest: FindingSample;\n occurrences: number;\n recoverableMs: number;\n firstSeen: number;\n lastSeen: number;\n severity: FindingSeverity;\n routes: Map<string, { method: string; route: string; calls: number }>;\n /** Worst occurrence per request — five findings in one request are one way in. */\n examples: Map<string, PatternExample>;\n }\n\n const buckets = new Map<string, Bucket>();\n for (const sample of read.samples) {\n const key = patternKey(sample);\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n latest: sample,\n occurrences: 0,\n recoverableMs: 0,\n firstSeen: sample.startedAt,\n lastSeen: sample.startedAt,\n severity: sample.severity,\n routes: new Map(),\n examples: new Map(),\n };\n buckets.set(key, bucket);\n }\n\n bucket.occurrences++;\n bucket.recoverableMs += sample.costMs;\n if (sample.startedAt < bucket.firstSeen) bucket.firstSeen = sample.startedAt;\n if (sample.startedAt >= bucket.lastSeen) {\n bucket.lastSeen = sample.startedAt;\n // The sentence and the hint follow the freshest occurrence: \"150\n // identical queries\" must not describe last week's count.\n bucket.latest = sample;\n }\n if (SEVERITY_RANK[sample.severity] > SEVERITY_RANK[bucket.severity]) {\n bucket.severity = sample.severity;\n }\n\n const routeKey = `${sample.method} ${sample.route}`;\n const route = bucket.routes.get(routeKey);\n if (route) route.calls++;\n else bucket.routes.set(routeKey, { method: sample.method, route: sample.route, calls: 1 });\n\n const example = bucket.examples.get(sample.requestId);\n if (!example || sample.costMs > example.costMs) {\n bucket.examples.set(sample.requestId, {\n requestId: sample.requestId,\n startedAt: sample.startedAt,\n method: sample.method,\n route: sample.route,\n status: sample.status,\n durationMs: sample.durationMs,\n costMs: sample.costMs,\n });\n }\n }\n\n const patterns: FindingPattern[] = [...buckets.entries()].map(([id, bucket]) => ({\n id,\n detector: bucket.latest.detector,\n severity: bucket.severity,\n title: bucket.latest.title,\n hint: bucket.latest.hint,\n callsite: bucket.latest.callsite,\n occurrences: bucket.occurrences,\n recoverableMs: bucket.recoverableMs,\n routes: [...bucket.routes.values()].sort((a, b) => b.calls - a.calls),\n firstSeen: bucket.firstSeen,\n lastSeen: bucket.lastSeen,\n state: stateOf(id, bucket, options),\n examples: [...bucket.examples.values()]\n .sort((a, b) => b.costMs - a.costMs)\n .slice(0, EXAMPLE_LIMIT),\n }));\n\n patterns.sort((a, b) => b.recoverableMs - a.recoverableMs || b.occurrences - a.occurrences);\n\n return {\n patterns,\n occurrences: read.samples.length,\n recoverableMs: patterns.reduce(\n (sum, pattern) => (pattern.state === 'muted' ? sum : sum + pattern.recoverableMs),\n 0,\n ),\n truncated: read.truncated,\n };\n}\n\n/**\n * What a pattern's state is, muted winning over everything.\n *\n * `fixed` outranks `ack` because it says more: the pattern has been silent\n * since the file it points at changed. It is only ever a guess — hence the\n * question mark a client draws — and only claimed when somebody did change\n * the file after the last occurrence.\n */\nfunction stateOf(\n id: string,\n bucket: { latest: FindingSample; lastSeen: number },\n options: PatternsOptions,\n): FindingPattern['state'] {\n const stored = options.states?.get(id);\n if (stored === 'muted') return 'muted';\n\n const file = bucket.latest.callsite?.file;\n if (file && options.changedAt) {\n const changed = options.changedAt(file);\n if (changed !== null && changed > bucket.lastSeen) return 'fixed';\n }\n\n return stored === 'ack' ? 'ack' : 'new';\n}\n\n/**\n * The row's flag, with muted patterns silenced.\n *\n * Muting is presentation, not detection: the detector keeps running and the\n * findings stay on the record, but a muted pattern must stop shouting from\n * the list. The flag falls back to the costliest finding that is not muted,\n * and to nothing when they all are.\n */\nexport function flagWithMutes(request: RecordedRequest, muted: ReadonlySet<string>): string | null {\n if (muted.size === 0 || request.findings.length === 0) {\n return [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null;\n }\n const audible = request.findings.filter(\n (finding) =>\n !muted.has(\n patternKey({\n detector: finding.detector,\n callsite: finding.callsite,\n method: request.method,\n route: normalizeRoute(request.path),\n }),\n ),\n );\n return [...audible].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null;\n}\n","/**\n * Per-route aggregates.\n *\n * The request list answers \"what happened just now\"; this answers \"which\n * endpoint is expensive\". It is computed over whatever the store still holds,\n * which is a dev session rather than a statistically sound window — the\n * numbers are for spotting the obvious offender, not for a capacity plan, and\n * the screen says as much by showing the sample count next to them.\n */\n\nimport type { Callsite, RouteFinding, RouteStats, RoutesReport } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { patternKey } from './findings.js';\n\nexport type { RouteFinding, RouteStats, RoutesReport };\n\n/**\n * How many columns a route's sparkline is cut into.\n *\n * Ten: enough to see a shape, few enough that one column of a short window\n * still holds calls rather than drawing a comb of ones and zeroes.\n */\nexport const TREND_BUCKETS = 10;\n\n/**\n * Collapses the variable parts of a path.\n *\n * Per segment rather than by regex over the whole path, so that a route with\n * several ids normalizes cleanly. A hex token must contain a digit to count\n * as an id: otherwise ordinary words like `feed` or `cafe` would normalize\n * away and two unrelated routes would merge into one row.\n */\nexport function normalizeRoute(path: string): string {\n return path\n .split('?')[0]\n ?.split('/')\n .map((segment) => {\n if (/^\\d+$/.test(segment)) return ':id';\n if (/^\\d{4}-\\d{2}/.test(segment)) return ':date';\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment)) {\n return ':id';\n }\n if (/^[0-9a-f]{4,}$/i.test(segment) && /\\d/.test(segment)) return ':id';\n return segment;\n })\n .join('/') as string;\n}\n\n/**\n * A percentile with linear interpolation between neighbouring samples.\n *\n * Index-based selection would collapse p95 and p99 onto the same sample at\n * the sample counts a dev session produces, and two columns showing the same\n * number are worse than one.\n *\n * @param sorted values in ascending order.\n */\nexport function percentile(sorted: readonly number[], p: number): number {\n if (sorted.length === 0) return 0;\n if (sorted.length === 1) return sorted[0] as number;\n\n const position = p * (sorted.length - 1);\n const lower = Math.floor(position);\n const upper = Math.ceil(position);\n const low = sorted[lower] as number;\n if (lower === upper) return low;\n const high = sorted[upper] as number;\n return low + (high - low) * (position - lower);\n}\n\n/** One detector's tally on one route, while it is being accumulated. */\ninterface FoundHere {\n calls: number;\n recoverableMs: number;\n /** When the occurrence that supplied the words happened. */\n at: number;\n title: string;\n hint: string;\n callsite: Callsite | null;\n}\n\ninterface Accumulator {\n method: string;\n route: string;\n durations: number[];\n errors: number;\n sql: number;\n totalMs: number;\n bytes: number;\n /** Calls that reported a size — the divisor for the average. */\n weighed: number;\n /** Per detector, accumulated across the route's calls. */\n findings: Map<string, FoundHere>;\n /** When each call started — bucketed into the trend once the window is known. */\n starts: number[];\n}\n\n/**\n * Aggregates the retained requests by normalized route.\n *\n * @param muted pattern ids the reader silenced, as {@link patternKey} spells\n * them. Their findings stay on the records and out of this table: the column\n * is a shout, and a muted pattern has been told to stop shouting.\n */\nexport function routeStats(\n requests: readonly RecordedRequest[],\n muted: ReadonlySet<string> = new Set(),\n): RoutesReport {\n if (requests.length === 0) {\n return { routes: [], samples: 0, windowMs: 0, from: 0, to: 0 };\n }\n\n const byRoute = new Map<string, Accumulator>();\n let overallMs = 0;\n let oldest = Number.POSITIVE_INFINITY;\n let newest = Number.NEGATIVE_INFINITY;\n\n for (const request of requests) {\n const route = normalizeRoute(request.path);\n const key = `${request.method} ${route}`;\n let bucket = byRoute.get(key);\n if (!bucket) {\n bucket = {\n method: request.method,\n route,\n durations: [],\n errors: 0,\n sql: 0,\n totalMs: 0,\n bytes: 0,\n weighed: 0,\n findings: new Map(),\n starts: [],\n };\n byRoute.set(key, bucket);\n }\n\n bucket.durations.push(request.durationMs);\n bucket.starts.push(request.startedAt);\n\n for (const finding of request.findings) {\n if (\n muted.has(\n patternKey({\n detector: finding.detector,\n callsite: finding.callsite,\n method: request.method,\n route,\n }),\n )\n ) {\n continue;\n }\n const seen = bucket.findings.get(finding.detector);\n if (seen) {\n seen.calls++;\n seen.recoverableMs += finding.costMs;\n // The freshest occurrence speaks: \"150 identical queries\" must not be\n // last week's count.\n if (request.startedAt >= seen.at) {\n seen.at = request.startedAt;\n seen.title = finding.title;\n seen.hint = finding.hint;\n seen.callsite = finding.callsite;\n }\n continue;\n }\n bucket.findings.set(finding.detector, {\n calls: 1,\n recoverableMs: finding.costMs,\n at: request.startedAt,\n title: finding.title,\n hint: finding.hint,\n callsite: finding.callsite,\n });\n }\n bucket.totalMs += request.durationMs;\n const bytesOut = request.weight?.bytesOut ?? null;\n if (bytesOut !== null) {\n bucket.bytes += bytesOut;\n bucket.weighed++;\n }\n if (request.error !== null || request.status >= 500) bucket.errors++;\n for (const span of request.spans) {\n if (span.kind === 'db') bucket.sql++;\n }\n\n overallMs += request.durationMs;\n if (request.startedAt < oldest) oldest = request.startedAt;\n if (request.startedAt > newest) newest = request.startedAt;\n }\n\n // A single request spans no time; one second keeps rps finite and honest.\n const windowMs = Math.max(1_000, newest - oldest);\n\n const routes = [...byRoute.values()].map((bucket): RouteStats => {\n const sorted = [...bucket.durations].sort((a, b) => a - b);\n const calls = sorted.length;\n\n // The shape of the traffic, over the same window every other row uses —\n // so two sparklines on this screen are comparable by eye.\n const trend = new Array<number>(TREND_BUCKETS).fill(0);\n const span = Math.max(1, newest - oldest);\n for (const at of bucket.starts) {\n const index = Math.min(TREND_BUCKETS - 1, Math.floor(((at - oldest) / span) * TREND_BUCKETS));\n trend[index] = (trend[index] ?? 0) + 1;\n }\n\n return {\n method: bucket.method,\n route: bucket.route,\n calls,\n rps: calls / (windowMs / 1_000),\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n errorRate: (bucket.errors / calls) * 100,\n sqlAvg: bucket.sql / calls,\n bytesAvg: bucket.weighed > 0 ? bucket.bytes / bucket.weighed : null,\n timeShare: overallMs > 0 ? (bucket.totalMs / overallMs) * 100 : 0,\n findings: [...bucket.findings.entries()]\n .map(([detector, found]) => ({\n detector,\n calls: found.calls,\n recoverableMs: found.recoverableMs,\n title: found.title,\n hint: found.hint,\n callsite: found.callsite,\n }))\n .sort((a, b) => b.recoverableMs - a.recoverableMs || b.calls - a.calls),\n trend,\n };\n });\n\n // Most expensive first — the order the screen opens in.\n routes.sort((a, b) => b.timeShare - a.timeShare);\n return { routes, samples: requests.length, windowMs, from: oldest, to: newest };\n}\n","/**\n * How one call compares against the route's own history.\n *\n * A duration on its own says nothing. 400 ms is alarming for a cache read and\n * excellent for a report, so the only comparison worth drawing is against\n * other calls of the same route — and only when there are enough of them for\n * the comparison to be worth more than the silence it replaces.\n */\n\nimport type { DurationBaseline, RecordedRequest } from '../types.js';\nimport type { DurationSample } from './api.js';\nimport { normalizeRoute, percentile } from './routes.js';\n\n/**\n * Below this a percentile is one call wearing a statistic's name.\n *\n * Twenty is where the ninety-fifth percentile stops being the single slowest\n * sample and starts interpolating between two — the point at which \"slower\n * than 95% of calls\" is a claim about a distribution rather than about the\n * one unlucky call that happens to top the list.\n */\nconst MIN_FOR_P95 = 20;\n\n/** Below this the request would be measuring itself. */\nconst MIN_SAMPLES = 2;\n\n/** What the store is asked for when a request is judged against its route. */\nexport interface BaselineQuery {\n readonly method: string;\n /** The normalized route, as `normalizeRoute` produces it. */\n readonly route: string;\n /**\n * The request being judged — it is never part of its own baseline.\n *\n * Left out when the caller wants the route's whole history: the charts do,\n * and a chart with one call missing from it would be a different kind of\n * lie from the one this field prevents.\n */\n readonly excludeId?: string;\n /**\n * The stretch to read, epoch ms.\n *\n * Left out for the whole history. The charts pass the same window the\n * routes table was computed over: a table describing thirteen minutes above\n * a chart describing six hours is two answers to one question.\n */\n readonly from?: number;\n readonly to?: number;\n}\n\n/**\n * The verdict, or `null` when there is nothing honest to say.\n *\n * @param samples the route's other calls, as the store hands them over.\n * `undefined` is a store that cannot answer at all, and produces no verdict\n * rather than one drawn from whatever page happened to be loaded.\n */\nexport function baselineFor(\n request: RecordedRequest,\n samples: readonly DurationSample[] | undefined,\n): DurationBaseline | null {\n if (!samples || samples.length < MIN_SAMPLES) return null;\n\n const sorted = samples.map((sample) => sample.durationMs).sort((a, b) => a - b);\n const sum = sorted.reduce((total, value) => total + value, 0);\n const avgMs = sum / sorted.length;\n\n const times = samples.map((sample) => sample.startedAt);\n const windowMs = Math.max(...times) - Math.min(...times);\n\n const p95Ms = sorted.length >= MIN_FOR_P95 ? percentile(sorted, 0.95) : null;\n const p50Ms = percentile(sorted, 0.5);\n const p99Ms = sorted.length >= MIN_FOR_P95 ? percentile(sorted, 0.99) : null;\n const maxMs = sorted[sorted.length - 1] ?? 0;\n\n // Without a trustworthy p95 the strongest claim available is \"at or under\n // the mean\", which roughly half of all calls are. Calling anything slow off\n // five samples is how a tool starts crying wolf.\n const verdict =\n p95Ms !== null && request.durationMs >= p95Ms\n ? 'slower'\n : request.durationMs <= avgMs\n ? 'faster'\n : 'typical';\n\n return {\n method: request.method,\n route: normalizeRoute(request.path),\n samples: sorted.length,\n windowMs,\n avgMs,\n p95Ms,\n p50Ms,\n p99Ms,\n maxMs,\n verdict,\n };\n}\n","/**\n * `git blame` for the frames of an exception.\n *\n * A stack trace says where it broke; blame says who last touched that line\n * and when, which is usually the next question. It runs `git` on the machine\n * the panel runs on, so it is gated exactly like replay and EXPLAIN: local\n * development by default, explicit opt-in anywhere else.\n *\n * Results are cached per file and revision — blame is not cheap, and the same\n * file is asked about once per frame of every occurrence of a group.\n */\n\nimport { execFile } from 'node:child_process';\nimport { isAbsolute, resolve, sep } from 'node:path';\nimport type { BlameLine } from '@reqray/protocol';\nimport { warnOnce } from '../logger.js';\n\nexport type { BlameLine };\n\nconst cache = new Map<string, BlameLine | null>();\n\n/** Bounded so a long session cannot turn the cache into a leak. */\nconst CACHE_LIMIT = 500;\n\nfunction run(command: string, args: readonly string[], cwd: string): Promise<string> {\n return new Promise((resolve, reject) => {\n execFile(\n command,\n args,\n { cwd, timeout: 3_000, maxBuffer: 1024 * 1024, windowsHide: true },\n (error, stdout) => {\n if (error) reject(error);\n else resolve(stdout);\n },\n );\n });\n}\n\n/**\n * Parses `git blame --porcelain` for a single line.\n *\n * The porcelain format leads with the hash, then key/value header lines; only\n * three of them matter here.\n */\nexport function parsePorcelain(output: string): BlameLine | null {\n const lines = output.split('\\n');\n const header = lines[0]?.split(' ')[0];\n if (!header || !/^[0-9a-f]{7,40}$/.test(header)) return null;\n\n let author = 'unknown';\n let at = 0;\n for (const line of lines) {\n if (line.startsWith('author ')) author = line.slice('author '.length).trim();\n else if (line.startsWith('author-time ')) {\n at = Number.parseInt(line.slice('author-time '.length), 10) * 1000;\n }\n }\n\n // A line that is staged but not committed blames to all zeroes; naming a\n // commit that does not exist would be worse than saying nothing.\n if (/^0+$/.test(header)) return null;\n return { sha: header.slice(0, 7), author, at };\n}\n\n/**\n * Blame for one line of one file.\n *\n * @returns `null` when the file is untracked, the repository is absent, or\n * git is not installed — all ordinary situations, none of them an error.\n */\nexport async function blameLine(\n file: string,\n line: number,\n cwd: string,\n): Promise<BlameLine | null> {\n if (!isAbsolute(file) || !Number.isInteger(line) || line < 1) return null;\n\n // Inside the project, or blame becomes a way to ask which absolute paths on\n // this machine are tracked, and by whom.\n const root = resolve(cwd);\n const target = resolve(file);\n if (target !== root && !target.startsWith(root + sep)) return null;\n\n const key = `${file}:${line}`;\n const cached = cache.get(key);\n if (cached !== undefined) return cached;\n\n let result: BlameLine | null = null;\n try {\n const output = await run(\n 'git',\n ['blame', '--porcelain', '-L', `${line},${line}`, '--', file],\n cwd,\n );\n result = parsePorcelain(output);\n } catch (error) {\n // Not a repository, not tracked, no git at all: the panel simply shows\n // nothing for that frame.\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.blame', `git blame unavailable: ${reason}`);\n }\n\n if (cache.size >= CACHE_LIMIT) cache.clear();\n cache.set(key, result);\n return result;\n}\n\n/** Forgets everything blamed so far. Needed by tests and after a checkout. */\nexport function clearBlameCache(): void {\n cache.clear();\n}\n","/**\n * Grouping of exceptions by normalised stack.\n *\n * The same error raised three hundred times is one row in the panel with a\n * repeat count, not three hundred rows. Normalisation drops everything that\n * varies between calls and keeps the shape of the stack.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { ExceptionFrame, ExceptionGroup } from '@reqray/protocol';\nimport { isProjectFrame, parseStackFrame } from '../callsite.js';\nimport type { ResolvedStackOptions } from '../config.js';\nimport type { RecordedRequest, SpanError } from '../types.js';\n\nexport type { ExceptionFrame, ExceptionGroup };\n\n/** Buckets in the sparkline — as many as there are bars in the mockup. */\nconst BUCKET_COUNT = 12;\n\n/** Frames taken into the fingerprint: deeper than this stacks stop differing. */\nconst SIGNIFICANT_FRAMES = 8;\n\nfunction framesOf(error: SpanError, options: ResolvedStackOptions): ExceptionFrame[] {\n if (!error.stack) return [];\n\n const frames: ExceptionFrame[] = [];\n for (const line of error.stack.split('\\n')) {\n if (!line.trim().startsWith('at ')) continue;\n const parsed = parseStackFrame(line);\n frames.push({\n raw: line.trim(),\n file: parsed?.file ?? null,\n line: parsed?.line ?? null,\n project: parsed ? isProjectFrame(parsed.file, options) : false,\n });\n }\n return frames;\n}\n\n/**\n * Stack fingerprint.\n *\n * It takes the exception type and the positions of the first frames — without\n * columns and without the message: the message usually carries varying values\n * (`id 8812`), which would split identical errors into separate groups.\n */\nfunction fingerprintStack(error: SpanError, frames: readonly ExceptionFrame[]): string {\n const parts = [error.name];\n for (const frame of frames.slice(0, SIGNIFICANT_FRAMES)) {\n parts.push(frame.file ? `${frame.file}:${frame.line ?? 0}` : frame.raw);\n }\n // There may be no stack at all — then the message is the only thing that\n // tells errors apart.\n if (frames.length === 0) parts.push(error.message);\n\n return createHash('sha1').update(parts.join('\\n')).digest('hex').slice(0, 12);\n}\n\ninterface Accumulator {\n readonly id: string;\n readonly type: string;\n message: string;\n readonly frames: ExceptionFrame[];\n readonly origin: string | null;\n where: string | null;\n count: number;\n lastSeenAt: number;\n readonly requestIds: string[];\n readonly times: number[];\n test: string | null;\n}\n\nfunction originOf(frames: readonly ExceptionFrame[], options: ResolvedStackOptions): string | null {\n const projectFrame = frames.find((frame) => frame.project && frame.file);\n if (!projectFrame?.file) return null;\n const relative = projectFrame.file.startsWith(options.projectRoot)\n ? projectFrame.file.slice(options.projectRoot.length + 1)\n : projectFrame.file;\n return `${relative}:${projectFrame.line ?? 0}`;\n}\n\nfunction bucketize(times: readonly number[], now: number, windowMs: number): number[] {\n const buckets = new Array<number>(BUCKET_COUNT).fill(0);\n if (windowMs <= 0) return buckets;\n\n const from = now - windowMs;\n for (const time of times) {\n const position = Math.floor(((time - from) / windowMs) * BUCKET_COUNT);\n const index = Math.min(BUCKET_COUNT - 1, Math.max(0, position));\n buckets[index] = (buckets[index] ?? 0) + 1;\n }\n return buckets;\n}\n\n/**\n * Builds exception groups from recorded requests.\n *\n * Requests are expected newest first, the order the store returns them in.\n * Groups come back by descending occurrence count.\n */\nexport function groupExceptions(\n requests: readonly RecordedRequest[],\n options: ResolvedStackOptions,\n now = Date.now(),\n): ExceptionGroup[] {\n const groups = new Map<string, Accumulator>();\n let oldest = now;\n\n for (const request of requests) {\n if (request.startedAt < oldest) oldest = request.startedAt;\n\n const error = request.error;\n if (!error) continue;\n\n const frames = framesOf(error, options);\n const id = fingerprintStack(error, frames);\n\n let group = groups.get(id);\n if (!group) {\n group = {\n id,\n type: error.name,\n message: error.message,\n frames,\n origin: originOf(frames, options),\n where: `${request.method} ${request.path}`,\n count: 0,\n lastSeenAt: request.startedAt,\n requestIds: [],\n times: [],\n test: null,\n };\n groups.set(id, group);\n }\n\n group.count++;\n group.times.push(request.startedAt);\n if (request.startedAt > group.lastSeenAt) {\n group.lastSeenAt = request.startedAt;\n group.message = error.message;\n group.where = `${request.method} ${request.path}`;\n }\n // Records arrive newest first, so the first test name seen is the latest.\n if (group.test === null && request.test !== null) group.test = request.test;\n // The request list is capped: the panel needs the latest ones, not all.\n if (group.requestIds.length < 50) group.requestIds.push(request.id);\n }\n\n const windowMs = Math.max(1, now - oldest);\n\n return [...groups.values()]\n .map(\n (group): ExceptionGroup => ({\n id: group.id,\n type: group.type,\n message: group.message,\n origin: group.origin,\n where: group.where,\n count: group.count,\n lastSeenAt: group.lastSeenAt,\n requestIds: group.requestIds,\n frames: group.frames,\n buckets: bucketize(group.times, now, windowMs),\n test: group.test,\n }),\n )\n .sort((a, b) => b.count - a.count || b.lastSeenAt - a.lastSeenAt);\n}\n","/**\n * Stack capture and locating the user's line of code.\n *\n * The most expensive operation in the whole collection path, so it may only be\n * called through `scope.shouldCaptureStack()`: always in development, only for\n * the first occurrences of each fingerprint in production.\n */\n\nimport { isAbsolute, relative as pathRelative } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ResolvedStackOptions } from './config.js';\nimport { pendingCallsite } from './context.js';\nimport { globalSlot, TwoGenerationCache } from './state.js';\n\n/** What is known about where a fingerprint is issued from. */\ninterface CallsiteRecord {\n callsite: Callsite | null;\n /** How many stacks have been captured for this fingerprint. */\n samples: number;\n /**\n * The same SQL has been seen coming from more than one place.\n *\n * Attributing it to either one would be a lie, so nothing is attributed —\n * and the N+1 detector, which needs a single origin, stays silent.\n */\n ambiguous: boolean;\n}\n\n/**\n * What has been learned about each fingerprint's origin.\n *\n * Process-wide, not per request: capturing a stack is the single most\n * expensive thing Reqray does, and in production it is paid only while the\n * origin of a fingerprint is still unknown.\n *\n * Bounded, which it was not. Every sibling cache has had a ceiling from the\n * start with a comment about applications that build SQL dynamically; this one\n * has the same key space and had no ceiling at all, so such an application\n * leaked a record per distinct statement, for the life of the process, inside\n * somebody else's production.\n */\nconst CACHE_LIMIT = 5_000;\n\nconst learnedCallsites = globalSlot(\n 'callsite.learned',\n () => new TwoGenerationCache<string, CallsiteRecord>(CACHE_LIMIT),\n);\n\nimport type { Callsite } from './types.js';\n\n/** `at fn (/path/file.ts:12:34)` — frame with a function name. */\nconst FRAME_WITH_NAME = /^\\s*at\\s+.*?\\s+\\((.+):(\\d+):(\\d+)\\)\\s*$/;\n/** `at /path/file.ts:12:34` — frame without a function name. */\nconst FRAME_BARE = /^\\s*at\\s+(.+):(\\d+):(\\d+)\\s*$/;\n\nconst NODE_MODULES = /[\\\\/]node_modules[\\\\/]/;\n\n/** A position in a file, parsed out of one stack line. */\nexport interface StackFrame {\n readonly file: string;\n readonly line: number;\n readonly column: number;\n}\n\n/**\n * Parses one line of a V8 stack.\n *\n * Returns `null` for lines that are not frames (the error header) and for\n * frames without a file (`at <anonymous>`, `eval`).\n */\nexport function parseStackFrame(line: string): StackFrame | null {\n const match = FRAME_WITH_NAME.exec(line) ?? FRAME_BARE.exec(line);\n if (!match) return null;\n\n const rawFile = match[1];\n const lineNo = Number(match[2]);\n const columnNo = Number(match[3]);\n if (!rawFile || !Number.isFinite(lineNo) || !Number.isFinite(columnNo)) return null;\n\n // ESM frames arrive as file:// URLs.\n let file = rawFile;\n if (file.startsWith('file://')) {\n try {\n file = fileURLToPath(file);\n } catch {\n return null;\n }\n }\n\n return { file, line: lineNo, column: columnNo };\n}\n\n/**\n * Checks that a frame points at project code: inside `projectRoot`, not in\n * `node_modules`, not in Node internals and not in the exclusion list.\n */\nexport function isProjectFrame(file: string, options: ResolvedStackOptions): boolean {\n // Node internals arrive either as `node:internal/...` or as a relative\n // `internal/process/...` — the absolute-path check rejects both.\n if (!isAbsolute(file)) return false;\n if (NODE_MODULES.test(file)) return false;\n for (const fragment of options.exclude) {\n if (file.includes(fragment)) return false;\n }\n\n const rel = pathRelative(options.projectRoot, file);\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);\n}\n\n/**\n * Finds the first frame in the stack that belongs to project code.\n *\n * Kept as a separate pure function so it can be tested against recorded\n * stacks without depending on a real call tree.\n */\nexport function findProjectFrame(stack: string, options: ResolvedStackOptions): Callsite | null {\n for (const line of stack.split('\\n')) {\n const frame = parseStackFrame(line);\n if (!frame || !isProjectFrame(frame.file, options)) continue;\n\n return {\n file: frame.file,\n relative: pathRelative(options.projectRoot, frame.file).replaceAll('\\\\', '/'),\n line: frame.line,\n column: frame.column,\n };\n }\n return null;\n}\n\n/**\n * Captures a stack and returns the first line inside the project.\n *\n * `Error.stackTraceLimit` is raised for the duration of the capture and\n * restored even on exception. Never throws: a failed capture is `null`, not a\n * broken request.\n *\n * @param boundary the instrumentation's wrapper function. Every frame up to\n * and including it is dropped, so the top frame is user code rather than Reqray\n * itself. The `node_modules` filter cannot be relied on here: when developing\n * against a linked copy of Reqray its sources sit inside the project root, and\n * the first \"project code\" line would be the interceptor itself.\n */\nexport function captureCallsite(\n options: ResolvedStackOptions,\n boundary?: (...args: never[]) => unknown,\n): Callsite | null {\n const previousLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = options.limit;\n try {\n const holder: { stack?: string } = {};\n Error.captureStackTrace(holder, boundary ?? captureCallsite);\n return holder.stack ? findProjectFrame(holder.stack, options) : null;\n } catch {\n return null;\n } finally {\n Error.stackTraceLimit = previousLimit;\n }\n}\n\n/** A callsite handed down from a pool wrapper to the driver wrapper. */\nexport interface HandedCallsite {\n readonly callsite: Callsite | null;\n /** Registry id of the pool the query went through — for EXPLAIN. */\n readonly clientId?: number;\n}\n\n/**\n * Carries a callsite across an asynchronous connection acquire.\n *\n * `pool.query()` resolves a connection asynchronously, so by the time the\n * query reaches the driver the caller's frame has left the stack and there is\n * nothing left to capture. The pool wrapper captures it while the frame is\n * still there and hands it down through this context.\n */\nexport function withHandedCallsite<T>(handed: HandedCallsite, fn: () => T): T {\n return pendingCallsite().run(handed, fn);\n}\n\n/**\n * The callsite handed down by a pool wrapper.\n *\n * `undefined` means the query did not come through a pool, and the driver\n * wrapper should capture a stack of its own.\n */\nexport function handedCallsite(): HandedCallsite | undefined {\n return pendingCallsite().getStore();\n}\n\n/**\n * The callsite for a span, capturing a stack only when it is still needed.\n *\n * This is the single place the capture policy lives, so every instrumentation\n * gets the same behaviour:\n *\n * 1. a callsite handed down by a pool wrapper wins — it is the only one taken\n * while the caller's frame was still on the stack;\n * 2. in development a stack is captured every time, which keeps full fidelity;\n * 3. in production it is captured only until the origin of that fingerprint is\n * known, and later spans reuse what was learned. Capturing a stack costs\n * roughly a third of the application's throughput, so paying it per query\n * is not an option;\n * 4. if the same SQL turns out to come from more than one place, nothing is\n * attributed at all: a wrong line of code is worse than none, and the N+1\n * detector needs a single origin anyway.\n *\n * Never throws — a failed capture is `null`, not a broken request.\n */\nexport function resolveCallsite(\n scope: {\n shouldCaptureStack(fingerprint?: string): boolean;\n options: { stack: ResolvedStackOptions };\n },\n fingerprint: string,\n boundary?: (...args: never[]) => unknown,\n): Callsite | null {\n try {\n const handed = handedCallsite();\n if (handed) return handed.callsite;\n\n // In development every stack is captured, so each span carries its own\n // true origin and the detector compares them per request. Learning would\n // only add a way to be wrong: one unlucky pair of call sites anywhere in\n // the process would permanently mute a whole query shape.\n // Without an explicit boundary this function is the boundary, otherwise\n // the top frame would be Reqray's own code.\n const from = boundary ?? resolveCallsite;\n\n if (scope.options.stack.maxPerFingerprint === Number.POSITIVE_INFINITY) {\n return captureCallsite(scope.options.stack, from);\n }\n\n const learned = learnedCallsites();\n const known = learned.get(fingerprint);\n if (known?.ambiguous) return null;\n\n if (!scope.shouldCaptureStack(fingerprint)) return known?.callsite ?? null;\n\n const captured = captureCallsite(scope.options.stack, from);\n remember(learned, fingerprint, known, captured);\n return learned.get(fingerprint)?.ambiguous ? null : captured;\n } catch {\n return null;\n }\n}\n\nfunction remember(\n learned: TwoGenerationCache<string, CallsiteRecord>,\n fingerprint: string,\n known: CallsiteRecord | undefined,\n captured: Callsite | null,\n): void {\n if (!known) {\n learned.set(fingerprint, { callsite: captured, samples: 1, ambiguous: false });\n return;\n }\n\n known.samples++;\n if (!captured) return;\n if (!known.callsite) {\n known.callsite = captured;\n return;\n }\n if (known.callsite.file !== captured.file || known.callsite.line !== captured.line) {\n known.callsite = null;\n known.ambiguous = true;\n }\n}\n\n/**\n * How many stacks have been captured for a fingerprint so far.\n *\n * Asked by `RequestScope.shouldCaptureStack`, which decides whether to pay for\n * another. The count lives here because the map does.\n */\nexport function samplesFor(fingerprint: string): number {\n return learnedCallsites().get(fingerprint)?.samples ?? 0;\n}\n\n/** Forgets what was learned about fingerprint origins. Needed by tests. */\nexport function resetLearnedCallsites(): void {\n learnedCallsites().clear();\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n/**\n * Current request context.\n *\n * A single `AsyncLocalStorage` per process (see `state.ts` — it lives in the\n * shared state so that the ESM and CJS copies of core do not drift apart).\n * The framework adapter wraps request handling in {@link runInScope};\n * instrumentations reach the scope through {@link current}. No scope means the\n * span is simply ignored, which is not an error: application code also runs\n * outside requests (migrations, workers, startup).\n */\n\nimport type { RequestScope } from './scope.js';\nimport { globalSlot } from './state.js';\nimport type { Callsite } from './types.js';\n\n/** The request context. One per process — see `state.ts` for why. */\nconst storage = globalSlot('context.storage', () => new AsyncLocalStorage<RequestScope>());\n\n/**\n * Callsite handed from a pool wrapper down to the driver wrapper.\n *\n * Absent outside a pooled query — that is what tells the driver wrapper to\n * capture a stack of its own.\n */\nexport const pendingCallsite = globalSlot(\n 'context.pendingCallsite',\n () => new AsyncLocalStorage<{ readonly callsite: Callsite | null; readonly clientId?: number }>(),\n);\n\n/**\n * Scope of the current request, or `undefined`.\n *\n * This is the first check in every instrumentation: no scope, immediate\n * return, not a single allocation made.\n */\nexport function current(): RequestScope | undefined {\n return storage().getStore();\n}\n\n/** Runs `fn` inside the scope. Return values and exceptions pass through as is. */\nexport function runInScope<T>(scope: RequestScope, fn: () => T): T {\n return storage().run(scope, fn);\n}\n\n/**\n * Enters a scope without wrapping a function.\n *\n * Needed by frameworks where the request start and end are different hooks\n * (Fastify's `onRequest`) and handling cannot be wrapped in a single call.\n */\nexport function enterScope(scope: RequestScope): void {\n storage().enterWith(scope);\n}\n\n/**\n * Runs `fn` outside of any scope.\n *\n * Needed for Reqray's own background work: writing to storage must not end up\n * as spans of the request being handled.\n */\nexport function runOutsideScope<T>(fn: () => T): T {\n return storage().exit(fn);\n}\n","/**\n * Registry of live database pools and clients able to run EXPLAIN.\n *\n * The pg instrumentation registers whatever executed a query; the recorded\n * span carries the id, so the panel later sends EXPLAIN to the very same\n * database the query ran against. References are weak: a closed pool must be\n * collectable, and a dead entry simply means EXPLAIN is no longer available\n * for that span.\n */\n\nimport { type Box, globalBox, globalSlot } from './state.js';\n\n/** The one method a target must have — both pg `Pool` and `Client` fit. */\nexport interface ExplainTarget {\n query(sql: string): Promise<unknown>;\n}\n\n/**\n * Ids already assigned, so one pool registers once.\n *\n * Must share a slot with the counter that feeds it: split across two module\n * copies, one pool takes two ids from one sequence and `explainTarget(id)`\n * resolves to the wrong pool.\n */\nconst assigned = globalSlot('explain.assigned', () => new WeakMap<object, number>());\n\n/** Live targets, weakly held: a closed pool must stay collectable. */\nconst targets = globalSlot('explain.targets', () => new Map<number, WeakRef<object>>());\n\n/** Id source for {@link targets}. */\nconst sequence: () => Box<number> = globalBox('explain.sequence', 0);\n\n/** Registers a target (idempotent) and returns its id. */\nexport function registerExplainTarget(target: object): number {\n const ids = assigned();\n const known = ids.get(target);\n if (known !== undefined) return known;\n\n const seq = sequence();\n seq.value += 1;\n ids.set(target, seq.value);\n targets().set(seq.value, new WeakRef(target));\n return seq.value;\n}\n\n/** The live target for an id, or `null` if it has been collected. */\nexport function explainTarget(id: number): ExplainTarget | null {\n const live = targets();\n const ref = live.get(id);\n if (!ref) return null;\n\n const target = ref.deref();\n if (!target) {\n live.delete(id);\n return null;\n }\n if (typeof (target as Partial<ExplainTarget>).query !== 'function') return null;\n return target as ExplainTarget;\n}\n\n/** Forgets every target. Needed by tests. */\nexport function resetExplainTargets(): void {\n targets().clear();\n}\n","/**\n * EXPLAIN of a recorded query, straight from the panel.\n *\n * Safety comes from three rules that are not options:\n * - the SQL is taken from the record — the panel client sends only ids and\n * can never inject a statement;\n * - `ANALYZE` is never used: it executes the query, and an executed\n * INSERT is a write. Plain EXPLAIN plans without running anything;\n * - the query goes to the same pool that ran the original (see\n * `explain-targets.ts`), so \"which database\" is never a guess.\n *\n * Parameterized queries have no recorded values (values are deliberately not\n * collected), so they are planned with `GENERIC_PLAN` — PostgreSQL 16+.\n */\n\nimport type { ExplainNote, ExplainPlanNode, ExplainResult } from '@reqray/protocol';\nimport { explainTarget } from '../explain-targets.js';\nimport type { RecordedRequest } from '../types.js';\n\nexport type { ExplainNote, ExplainPlanNode, ExplainResult };\n\nconst PLACEHOLDER = /\\$\\d+/;\nconst EXPLAIN_TIMEOUT_MS = 5_000;\n\ninterface PlanJson {\n readonly [key: string]: unknown;\n readonly Plans?: readonly PlanJson[];\n}\n\nfunction numberOf(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\nfunction labelOf(node: PlanJson): string {\n const type = typeof node['Node Type'] === 'string' ? (node['Node Type'] as string) : 'node';\n const relation = node['Relation Name'];\n const index = node['Index Name'];\n if (typeof index === 'string' && typeof relation === 'string') {\n return `${type} using ${index} on ${relation}`;\n }\n if (typeof relation === 'string') return `${type} on ${relation}`;\n return type;\n}\n\n/** Flattens the plan tree and derives the warnings. */\nexport function analyzePlan(plan: PlanJson): {\n nodes: ExplainPlanNode[];\n notes: ExplainNote[];\n} {\n const nodes: ExplainPlanNode[] = [];\n const notes: ExplainNote[] = [];\n\n const walk = (node: PlanJson, depth: number): void => {\n nodes.push({\n depth,\n label: labelOf(node),\n rows: numberOf(node['Plan Rows']),\n cost: numberOf(node['Total Cost']),\n });\n\n if (node['Node Type'] === 'Seq Scan' && typeof node['Filter'] === 'string') {\n const relation = typeof node['Relation Name'] === 'string' ? node['Relation Name'] : '?';\n notes.push({\n severity: 'warn',\n message:\n `Seq Scan over \"${relation}\" with filter ${node['Filter']} — ` +\n 'the whole table is read for a fraction of its rows. An index on the filtered column may help.',\n });\n }\n if (node['Node Type'] === 'Sort' && Array.isArray(node['Sort Key'])) {\n notes.push({\n severity: 'info',\n message:\n `Sorting by ${(node['Sort Key'] as unknown[]).join(', ')} happens in memory — ` +\n 'an index in the sort order would remove it entirely.',\n });\n }\n\n for (const child of node.Plans ?? []) walk(child, depth + 1);\n };\n\n walk(node0(plan), 0);\n return { nodes, notes };\n\n function node0(root: PlanJson): PlanJson {\n // `EXPLAIN (FORMAT JSON)` wraps the tree as [{ \"Plan\": {...} }].\n const inner = (root as { Plan?: PlanJson }).Plan;\n return inner ?? root;\n }\n}\n\n/**\n * Whether anything follows the statement's own terminator.\n *\n * A semicolon inside a literal or a comment is not a terminator —\n * `WHERE note = 'a;b'` is one perfectly ordinary statement, and refusing to\n * plan it would be this check crying wolf. So quotes and comments are skipped\n * rather than searched: single quotes with their doubled-quote escape, dollar\n * quoting with its tag, double-quoted identifiers, and both comment forms.\n */\nfunction hasSecondStatement(sql: string): boolean {\n for (let i = 0; i < sql.length; i++) {\n const ch = sql[i];\n\n if (ch === \"'\" || ch === '\"') {\n const quote = ch;\n i++;\n while (i < sql.length) {\n if (sql[i] === quote) {\n // A doubled quote is an escaped one and the literal continues.\n if (sql[i + 1] === quote) i++;\n else break;\n }\n i++;\n }\n continue;\n }\n\n if (ch === '$') {\n const tag = /^\\$[A-Za-z_]\\w*\\$|^\\$\\$/.exec(sql.slice(i));\n if (tag) {\n const close = sql.indexOf(tag[0], i + tag[0].length);\n // An unterminated dollar quote swallows the rest: nothing follows it.\n if (close === -1) return false;\n i = close + tag[0].length - 1;\n continue;\n }\n }\n\n if (ch === '-' && sql[i + 1] === '-') {\n const end = sql.indexOf('\\n', i);\n if (end === -1) return false;\n i = end;\n continue;\n }\n\n if (ch === '/' && sql[i + 1] === '*') {\n const end = sql.indexOf('*/', i + 2);\n if (end === -1) return false;\n i = end + 1;\n continue;\n }\n\n if (ch === ';') return sql.slice(i + 1).trim() !== '';\n }\n return false;\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(`EXPLAIN did not answer within ${ms} ms`)), ms);\n timer.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n },\n );\n });\n}\n\n/** A user-facing failure: the message is shown in the panel as-is. */\nexport class ExplainError extends Error {\n override readonly name = 'ExplainError';\n constructor(\n message: string,\n readonly status = 400,\n ) {\n super(message);\n }\n}\n\n/**\n * Runs EXPLAIN for one recorded span.\n *\n * @throws ExplainError with a message meant for the panel.\n */\nexport async function runExplain(record: RecordedRequest, spanId: number): Promise<ExplainResult> {\n const span = record.spans.find((candidate) => candidate.id === spanId);\n if (span?.kind !== 'db') {\n throw new ExplainError('span not found, or it is not a SQL query', 404);\n }\n if (span.source !== 'pg') {\n throw new ExplainError(\n `EXPLAIN is supported for queries made through pg; this one went through ${span.source ?? 'an unknown driver'}`,\n );\n }\n if (span.clientId === null) {\n throw new ExplainError(\n 'the executor of this query was not recorded — EXPLAIN has nowhere to go',\n );\n }\n\n const target = explainTarget(span.clientId);\n if (!target) {\n throw new ExplainError(\n 'the pool that ran this query lives inside the application process and is not reachable here — ' +\n 'EXPLAIN works in the panel mounted in the application',\n );\n }\n\n // `EXPLAIN <sql>` is concatenation: a second statement after a semicolon\n // would be planned and then *run*. Reaching this needs an injection the\n // application already has, but a read-only endpoint must not be what turns\n // that into a write.\n if (hasSecondStatement(span.sql)) {\n throw new ExplainError(\n 'this record holds more than one statement, and EXPLAIN plans one — nothing was run',\n );\n }\n\n const parameterized = PLACEHOLDER.test(span.sql);\n const statement = parameterized\n ? `EXPLAIN (GENERIC_PLAN, FORMAT JSON) ${span.sql}`\n : `EXPLAIN (FORMAT JSON) ${span.sql}`;\n\n let rows: unknown;\n try {\n const result = (await withTimeout(\n Promise.resolve(target.query(statement)),\n EXPLAIN_TIMEOUT_MS,\n )) as { rows?: unknown };\n rows = result?.rows;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (parameterized && /GENERIC_PLAN|generic_plan|syntax error/i.test(reason)) {\n throw new ExplainError(\n `EXPLAIN of a parameterized query needs PostgreSQL 16+ (GENERIC_PLAN). The database said: ${reason}`,\n );\n }\n throw new ExplainError(`the database rejected EXPLAIN: ${reason}`);\n }\n\n const first = Array.isArray(rows) ? (rows[0] as Record<string, unknown> | undefined) : undefined;\n const planColumn = first?.['QUERY PLAN'];\n const plan = Array.isArray(planColumn) ? planColumn[0] : planColumn;\n if (!plan || typeof plan !== 'object') {\n throw new ExplainError('the database returned the plan in an unexpected shape');\n }\n\n const { nodes, notes } = analyzePlan(plan as PlanJson);\n return { sql: span.sql, nodes, notes, plan };\n}\n","/**\n * Exports: taking a session out of the panel.\n *\n * HAR and cURL are built here rather than in the browser because the panel\n * only ever receives list rows — bodies and headers live in the records, and\n * an export that quietly dropped them would be worse than no export.\n *\n * Both formats are for handing a request to something else: a HAR to a\n * browser's network panel or a colleague's viewer, a curl script to a\n * terminal. Neither is a backup format, and neither promises to round-trip.\n */\n\nimport type { RecordedRequest } from '../types.js';\n\n/** Reqray's own additions to a HAR entry, under the extension prefix HAR reserves. */\ninterface ReqrayHarExtension {\n readonly sqlQueries: number;\n readonly nPlusOne: boolean;\n readonly test: string | null;\n}\n\nfunction headerList(headers: Readonly<Record<string, string>>): Array<{\n name: string;\n value: string;\n}> {\n return Object.entries(headers).map(([name, value]) => ({ name, value }));\n}\n\n/** HAR 1.2. Times are milliseconds, as the format requires. */\nexport function toHar(\n requests: readonly RecordedRequest[],\n now = new Date(0),\n note: string | null = null,\n): Record<string, unknown> {\n return {\n log: {\n version: '1.2',\n creator: { name: 'reqray', version: '0.1' },\n pages: [],\n entries: requests.map((request) => {\n const extension: ReqrayHarExtension = {\n sqlQueries: request.spans.filter((span) => span.kind === 'db').length,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n test: request.test,\n };\n\n return {\n startedDateTime: new Date(request.startedAt).toISOString(),\n time: request.durationMs,\n request: {\n method: request.method,\n url: `${request.path}${request.query ? `?${request.query}` : ''}`,\n httpVersion: 'HTTP/1.1',\n headers: headerList(request.requestHeaders),\n queryString: [],\n cookies: [],\n headersSize: -1,\n bodySize: request.requestBody?.text.length ?? 0,\n ...(request.requestBody\n ? {\n postData: {\n mimeType: request.requestHeaders['content-type'] ?? 'application/json',\n text: request.requestBody.text,\n },\n }\n : {}),\n },\n response: {\n status: request.status,\n statusText: '',\n httpVersion: 'HTTP/1.1',\n headers: headerList(request.responseHeaders),\n cookies: [],\n content: {\n size: request.responseBody?.text.length ?? 0,\n mimeType: request.responseHeaders['content-type'] ?? 'application/json',\n ...(request.responseBody ? { text: request.responseBody.text } : {}),\n },\n redirectURL: '',\n headersSize: -1,\n bodySize: request.responseBody?.text.length ?? 0,\n },\n cache: {},\n // Everything Reqray knows lands in `wait`: the breakdown it has is by\n // span, not by the connection phases HAR describes.\n timings: { send: 0, wait: request.durationMs, receive: 0 },\n _reqray: extension,\n };\n }),\n // Kept out of the entries so a diff of two exports stays readable.\n _exportedAt: now.toISOString(),\n // HAR's own field for this, so a viewer that knows nothing of Reqray\n // still shows it. An export that was cut has to say so: it is evidence,\n // and evidence presented as complete is worse than none.\n ...(note ? { comment: note } : {}),\n },\n };\n}\n\n/** Escapes a value for single-quoted shell. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * A runnable `.sh`: one curl per request.\n *\n * Masked headers and bodies are exported as they were stored — with the\n * masking. A script that leaked the authorization header of every recorded\n * request would undo the one guarantee the buffer makes.\n */\nexport function toCurlScript(\n requests: readonly RecordedRequest[],\n origin: string,\n note: string | null = null,\n): string {\n const lines = [\n '#!/bin/sh',\n '# Exported from reqray. Sensitive headers and fields are masked, so a',\n '# request that needed them will not authenticate as it did.',\n // At the top rather than the bottom: a script is read from the first line,\n // and \"this is not all of them\" belongs where reading starts.\n ...(note ? [`# ${note}`] : []),\n '',\n ];\n\n for (const request of requests) {\n const url = `${origin}${request.path}${request.query ? `?${request.query}` : ''}`;\n const parts = [`curl -i -X ${request.method} ${shellQuote(url)}`];\n for (const [name, value] of Object.entries(request.requestHeaders)) {\n // Hop-by-hop and length headers are curl's business, not the script's.\n if (name === 'host' || name === 'content-length' || name === 'connection') continue;\n parts.push(` -H ${shellQuote(`${name}: ${value}`)}`);\n }\n if (request.requestBody) parts.push(` --data ${shellQuote(request.requestBody.text)}`);\n\n lines.push(\n // One line, whatever the name holds: a record can come off the wire, and\n // a line break here would end the comment and start a command.\n `# ${request.status} · ${Math.round(request.durationMs)} ms${request.test ? ` · ${request.test.replace(/\\p{Cc}/gu, ' ')}` : ''}`,\n parts.join(' \\\\\\n'),\n '',\n );\n }\n\n return lines.join('\\n');\n}\n","/**\n * Filtering and summary over the request list.\n *\n * Pure functions: the panel runs them on every keystroke in the search box,\n * and tests run them without standing up a server.\n */\n\nimport type { RequestSummary } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { normalizeRoute } from './routes.js';\n\nexport type { RequestSummary } from '@reqray/protocol';\n\n/** The panel's filter set. Empty fields exclude nothing. */\nexport interface RequestFilter {\n /** Substring of the path, method or status. Case-insensitive. */\n readonly query?: string | undefined;\n /** Methods: `GET`, `POST`. An empty list means all. */\n readonly methods?: readonly string[] | undefined;\n /** Status classes: 2, 3, 4, 5. An empty list means all. */\n readonly statusClasses?: readonly number[] | undefined;\n /** Only requests no faster than the given duration. */\n readonly minDurationMs?: number | undefined;\n /** Not before this moment, epoch ms. Inclusive. */\n readonly from?: number | undefined;\n /** Not after this moment, epoch ms. Inclusive. */\n readonly to?: number | undefined;\n /** Only requests where the detectors found something. */\n readonly onlyFindings?: boolean | undefined;\n /** Only requests with an N+1 — a narrower question than \"any finding\". */\n readonly onlyNPlusOne?: boolean | undefined;\n /** Only requests a test issued. */\n readonly onlyTests?: boolean | undefined;\n /**\n * Only requests that failed.\n *\n * Wider than the 5xx class: a handler that threw and still answered 200 is\n * a failure, and it is the one worth finding.\n */\n readonly onlyErrors?: boolean | undefined;\n /**\n * One endpoint, as the Routes screen names it: the normalized path and the\n * method that go with it.\n */\n readonly route?: { readonly method: string; readonly route: string } | undefined;\n /** Substring of the path alone — narrower than `query`, which matches four fields. */\n readonly path?: string | undefined;\n /** Exactly this status code — `404`, not the whole 4xx class. */\n readonly status?: number | undefined;\n /** At least this many SQL queries. */\n readonly minSql?: number | undefined;\n /**\n * Rows the list flags with one of these detectors.\n *\n * The *flag* — the costliest finding — not \"any finding of this kind\":\n * both stores can answer that question identically (SQLite keeps the flag\n * as a column), and it is the badge the reader is pointing at anyway.\n */\n readonly flagged?: readonly string[] | undefined;\n /** Requests issued by a test whose name contains this. Case-insensitive. */\n readonly test?: string | undefined;\n}\n\nfunction matchesQuery(request: RecordedRequest, needle: string): boolean {\n if (request.method.toLowerCase().includes(needle)) return true;\n if (request.path.toLowerCase().includes(needle)) return true;\n if (String(request.status).includes(needle)) return true;\n return request.query ? request.query.toLowerCase().includes(needle) : false;\n}\n\n/** Selects requests matching the filter, keeping the original order (newest first). */\nexport function filterRequests(\n requests: readonly RecordedRequest[],\n filter: RequestFilter = {},\n): RecordedRequest[] {\n const needle = filter.query?.trim().toLowerCase();\n const methods = filter.methods?.length\n ? new Set(filter.methods.map((m) => m.toUpperCase()))\n : null;\n const classes = filter.statusClasses?.length ? new Set(filter.statusClasses) : null;\n\n return requests.filter((request) => {\n if (filter.from !== undefined && request.startedAt < filter.from) return false;\n if (filter.to !== undefined && request.startedAt > filter.to) return false;\n if (needle && !matchesQuery(request, needle)) return false;\n if (methods && !methods.has(request.method.toUpperCase())) return false;\n if (classes && !classes.has(Math.floor(request.status / 100))) return false;\n if (filter.minDurationMs !== undefined && request.durationMs < filter.minDurationMs)\n return false;\n if (filter.onlyFindings && request.findings.length === 0) return false;\n if (filter.onlyNPlusOne && !request.findings.some((f) => f.detector === 'n_plus_one'))\n return false;\n if (filter.onlyTests && request.test === null) return false;\n if (filter.path && !request.path.toLowerCase().includes(filter.path.toLowerCase())) {\n return false;\n }\n if (filter.status !== undefined && request.status !== filter.status) return false;\n if (filter.minSql !== undefined) {\n let sql = 0;\n for (const span of request.spans) if (span.kind === 'db') sql++;\n if (sql < filter.minSql) return false;\n }\n if (filter.flagged?.length) {\n // The same rule the list flags a row by: the costliest finding names it.\n const flag = [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector;\n if (!flag || !filter.flagged.includes(flag)) return false;\n }\n if (filter.test !== undefined) {\n if (request.test === null || !request.test.toLowerCase().includes(filter.test.toLowerCase()))\n return false;\n }\n if (filter.onlyErrors && request.error === null && request.status < 500) return false;\n if (filter.route) {\n if (request.method.toUpperCase() !== filter.route.method.toUpperCase()) return false;\n if (normalizeRoute(request.path) !== filter.route.route) return false;\n }\n return true;\n });\n}\n\n/**\n * Summary over the buffer.\n *\n * `slowMs` is the \"slow\" threshold for the status bar, 500 ms by default, as\n * in the panel mockup.\n */\nexport function summarize(\n all: readonly RecordedRequest[],\n shown: readonly RecordedRequest[],\n slowMs = 500,\n): RequestSummary {\n let slow = 0;\n let errors = 0;\n let withFindings = 0;\n\n for (const request of all) {\n if (request.durationMs >= slowMs) slow++;\n if (request.status >= 500 || request.error) errors++;\n if (request.findings.length > 0) withFindings++;\n }\n\n return { shown: shown.length, total: all.length, slow, errors, withFindings };\n}\n","/**\n * The shape of the traffic over time, for the strip above the list.\n *\n * The panel used to draw this from the rows it had loaded, which was fine\n * while a store held five hundred requests and everything was on screen. With\n * a history behind it, \"the rows I have\" is the last page — a few minutes —\n * and a strip that only spans a few minutes cannot be dragged back to\n * yesterday. So the store answers for its whole range instead.\n *\n * Three numbers per request go into it — when, how long, and whether it\n * failed — and the bucketing happens here, once, for every store. Two\n * implementations of \"which bucket does this fall into\" would drift, and the\n * drift would be a strip that disagrees with the list under it.\n */\n\n/** What the timeline needs to know about one request. */\nexport interface TimePoint {\n readonly startedAt: number;\n readonly durationMs: number;\n readonly hasError: boolean;\n}\n\nimport type { TimelineBucket, TimelineReport } from '@reqray/protocol';\n\nexport type { TimelineBucket, TimelineReport };\n\n/** How many columns the strip is drawn with, unless asked otherwise. */\nexport const TIMELINE_BUCKETS = 64;\n/** Above this, a request is drawn as slow — the panel's own threshold. */\nconst SLOW_MS = 500;\n\n/**\n * Which column a moment falls into.\n *\n * Shared with the per-route charts on purpose: two implementations of \"which\n * bucket is this\" drift, and the drift is a strip that disagrees with the\n * chart under it about when something happened. Everything inside a single\n * millisecond lands in the first column rather than dividing by a zero span.\n */\nexport function bucketIndex(at: number, from: number, to: number, count: number): number {\n const span = to - from;\n const fraction = span > 0 ? (at - from) / span : 0;\n return Math.max(0, Math.min(count - 1, Math.floor(fraction * count)));\n}\n\n/**\n * Buckets a set of points into a strip.\n *\n * `null` when there is nothing to draw: an empty store has no range, and a\n * strip with invented ends would be a lie about what is recorded.\n */\nexport function buildTimeline(\n points: readonly TimePoint[],\n bucketCount: number = TIMELINE_BUCKETS,\n): TimelineReport | null {\n if (points.length === 0 || bucketCount <= 0) return null;\n\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n for (const point of points) {\n if (point.startedAt < from) from = point.startedAt;\n if (point.startedAt > to) to = point.startedAt;\n }\n\n const buckets: TimelineBucket[] = Array.from({ length: bucketCount }, () => ({\n err: 0,\n slow: 0,\n rest: 0,\n total: 0,\n }));\n\n for (const point of points) {\n const index = bucketIndex(point.startedAt, from, to, bucketCount);\n const bucket = buckets[index] as {\n err: number;\n slow: number;\n rest: number;\n total: number;\n };\n if (point.hasError) bucket.err++;\n else if (point.durationMs >= SLOW_MS) bucket.slow++;\n else bucket.rest++;\n bucket.total++;\n }\n\n return { from, to, buckets };\n}\n","/**\n * One metric over one period, and what the period adds up to.\n *\n * Everything else the panel draws is scoped to something: the strip above the\n * list counts requests and nothing else, and stage 41's charts cover one route\n * at a time. This is the screen that answers \"what did latency do this week\",\n * and the arithmetic behind it lives here — once, for every store.\n *\n * **Why the store hands over rows rather than answers.** The obvious division\n * of labour is to let SQLite compute percentiles in SQL, and the obvious cost\n * is two implementations of the same statistic that quietly disagree: one\n * interpolating between neighbouring samples, the other picking the nearest\n * rank. So a store hands back a few numbers per request — the shape below,\n * never the payloads — and the bucketing and the percentiles happen here. The\n * rule the plan actually cares about still holds: a week of rows must never\n * reach the browser to have a median taken at the other end.\n *\n * What a store *is* responsible for is not reading its whole history into\n * memory. It reads a bounded number of rows and says when it stopped, and\n * this file passes that admission on rather than presenting a truncated total\n * as a complete one.\n */\n\nimport type { MetricSeries, SeriesMetric, SeriesResponse, SeriesTotals } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport type { RequestFilter } from './filters.js';\nimport { normalizeRoute, percentile } from './routes.js';\nimport { bucketIndex } from './timeline.js';\n\n/**\n * One request, as a history reading needs it.\n *\n * Ten numbers rather than a record: a period is tens of thousands of requests,\n * and parsing that many JSON documents to look at one field in each is how a\n * screen becomes slower than the question it answers.\n */\nexport interface HistorySample {\n readonly startedAt: number;\n readonly durationMs: number;\n readonly hasError: boolean;\n readonly sqlCount: number;\n readonly httpCount: number;\n readonly bytes: number;\n /** Mean event-loop delay while it ran, or `null` when nothing measured it. */\n readonly loopDelayMs: number | null;\n readonly findingCount: number;\n /** Time inside queries, ms. `null` for requests stored before it was kept. */\n readonly sqlMs: number | null;\n /** Time covered by no instrumented work, ms. `null` as above. */\n readonly selfMs: number | null;\n readonly method: string;\n readonly route: string;\n /** The detector the list flags this request with, when one fired. */\n readonly flag: string | null;\n}\n\n/**\n * One request, reduced to what a history reading needs.\n *\n * For every store that keeps whole records — the in-memory ring, and any\n * store answering from `list()` — so that what the screen shows does not\n * depend on which one is behind it.\n */\nexport function historySampleOf(request: RecordedRequest): HistorySample {\n let sqlCount = 0;\n let httpCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n else if (span.kind === 'http') httpCount++;\n }\n\n return {\n startedAt: request.startedAt,\n durationMs: request.durationMs,\n hasError: request.error !== null || request.status >= 500,\n sqlCount,\n httpCount,\n bytes: request.weight?.bytesOut ?? 0,\n loopDelayMs: request.host?.loopDelayMs ?? null,\n findingCount: request.findings.length,\n sqlMs: request.timing?.sqlMs ?? null,\n selfMs: request.timing?.selfMs ?? null,\n method: request.method,\n route: normalizeRoute(request.path),\n // The same rule the list flags a row by: the costliest finding names it.\n flag: [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null,\n };\n}\n\n/** What a store is asked for. */\nexport interface HistoryQuery {\n /** Epoch ms, inclusive. */\n readonly from: number;\n /** Epoch ms, inclusive. */\n readonly to: number;\n /** The same filter the list uses, so a metric can be asked about one route. */\n readonly filter: RequestFilter;\n}\n\n/** What a store answers with. */\nexport interface HistorySamples {\n readonly samples: readonly HistorySample[];\n /** The store stopped reading before the period ended. */\n readonly truncated: boolean;\n}\n\n/** Columns the chart is drawn with, unless the caller asks for fewer. */\nexport const SERIES_COLUMNS = 48;\n\n/**\n * Below this many requests per column a percentile is not a statistic.\n *\n * The same figure stage 41 settled on for a route's charts: a p95 over three\n * samples is the slowest of three, and a chart of those jumps about saying\n * nothing.\n */\nconst MIN_PER_COLUMN = 6;\n\n/** Below this the chart stops being a shape and becomes a row of bars. */\nconst MIN_COLUMNS = 8;\n\n/** A column of the chart, while it is being filled. */\ninterface Column {\n readonly durations: number[];\n errors: number;\n sqlCount: number;\n httpCount: number;\n bytes: number;\n findings: number;\n loopTotal: number;\n loopSamples: number;\n}\n\nfunction emptyColumn(): Column {\n return {\n durations: [],\n errors: 0,\n sqlCount: 0,\n httpCount: 0,\n bytes: 0,\n findings: 0,\n loopTotal: 0,\n loopSamples: 0,\n };\n}\n\n/** The value of one metric in one column, or `null` when it cannot say. */\nfunction metricValue(metric: SeriesMetric, column: Column, bucketMs: number): number | null {\n const calls = column.durations.length;\n // Nothing ran here. Every metric returns a void rather than a zero: a\n // stretch nobody called did not have an error rate of nought.\n if (calls === 0) return null;\n\n switch (metric) {\n case 'p50':\n case 'p95':\n case 'p99': {\n const sorted = [...column.durations].sort((a, b) => a - b);\n const p = metric === 'p50' ? 0.5 : metric === 'p95' ? 0.95 : 0.99;\n return percentile(sorted, p);\n }\n case 'throughput':\n return bucketMs > 0 ? (calls / bucketMs) * 60_000 : null;\n case 'errorRate':\n return column.errors / calls;\n case 'sqlPerRequest':\n return column.sqlCount / calls;\n case 'httpPerRequest':\n return column.httpCount / calls;\n case 'bytes':\n return column.bytes / calls;\n case 'loopDelay':\n // Only the requests that carried a reading. A process that was never\n // measured must not average in as calm.\n return column.loopSamples > 0 ? column.loopTotal / column.loopSamples : null;\n case 'findingsPerRequest':\n return column.findings / calls;\n default:\n return null;\n }\n}\n\n/** Everything a period adds up to. */\nexport function totalsOf(samples: readonly HistorySample[]): SeriesTotals {\n if (samples.length === 0) {\n return {\n calls: 0,\n errorRate: 0,\n p50: 0,\n p95: 0,\n p99: 0,\n sqlMs: null,\n appMs: null,\n busiest: null,\n topFinding: null,\n };\n }\n\n const durations: number[] = [];\n let errors = 0;\n let sqlMs = 0;\n let appMs = 0;\n let timed = 0;\n const routes = new Map<string, { method: string; route: string; calls: number }>();\n const findings = new Map<string, number>();\n\n for (const sample of samples) {\n durations.push(sample.durationMs);\n if (sample.hasError) errors++;\n if (sample.sqlMs !== null && sample.selfMs !== null) {\n sqlMs += sample.sqlMs;\n appMs += sample.selfMs;\n timed++;\n }\n\n const key = `${sample.method} ${sample.route}`;\n const seen = routes.get(key);\n if (seen) seen.calls++;\n else routes.set(key, { method: sample.method, route: sample.route, calls: 1 });\n\n if (sample.flag) findings.set(sample.flag, (findings.get(sample.flag) ?? 0) + 1);\n }\n\n durations.sort((a, b) => a - b);\n\n let busiest: SeriesTotals['busiest'] = null;\n for (const entry of routes.values()) {\n if (!busiest || entry.calls > busiest.calls) busiest = { ...entry };\n }\n\n let topFinding: SeriesTotals['topFinding'] = null;\n for (const [detector, calls] of findings) {\n if (!topFinding || calls > topFinding.calls) topFinding = { detector, calls };\n }\n\n return {\n calls: samples.length,\n errorRate: errors / samples.length,\n p50: percentile(durations, 0.5),\n p95: percentile(durations, 0.95),\n p99: percentile(durations, 0.99),\n // Reported only when something recorded it. A period half of whose\n // requests predate the figure would otherwise show a share of SQL time\n // that is half of the truth and looks like a fall.\n sqlMs: timed > 0 ? sqlMs : null,\n appMs: timed > 0 ? appMs : null,\n busiest,\n topFinding,\n };\n}\n\n/**\n * How many columns a period's traffic can support.\n *\n * Never more than asked for, never so many that each holds a handful of\n * requests — see {@link MIN_PER_COLUMN}.\n */\nexport function columnsFor(sampleCount: number, asked: number): number {\n if (asked <= 0) return 0;\n return Math.max(\n Math.min(MIN_COLUMNS, asked),\n Math.min(asked, Math.ceil(sampleCount / MIN_PER_COLUMN)),\n );\n}\n\nexport interface HistoryOptions {\n /** The period, as the caller chose it — not as the data happens to fall. */\n readonly from: number;\n readonly to: number;\n readonly metrics: readonly SeriesMetric[];\n readonly columns?: number;\n}\n\n/**\n * Builds the answer for one reading of the screen.\n *\n * The period comes from the caller rather than from the samples: a week with\n * traffic in one hour of it must draw a week with one column in it, not an\n * hour stretched across the screen.\n */\n/** Samples into columns of one window — the same cut for a period and its ghost. */\nfunction bucketize(\n samples: readonly HistorySample[],\n from: number,\n to: number,\n count: number,\n): Column[] {\n const columns: Column[] = Array.from({ length: count }, emptyColumn);\n for (const sample of samples) {\n const column = columns[bucketIndex(sample.startedAt, from, to, count)];\n if (!column) continue;\n column.durations.push(sample.durationMs);\n if (sample.hasError) column.errors++;\n column.sqlCount += sample.sqlCount;\n column.httpCount += sample.httpCount;\n column.bytes += sample.bytes;\n column.findings += sample.findingCount;\n if (sample.loopDelayMs !== null) {\n column.loopTotal += sample.loopDelayMs;\n column.loopSamples++;\n }\n }\n return columns;\n}\n\nexport function historyOf(\n current: HistorySamples,\n previous: readonly HistorySample[],\n options: HistoryOptions,\n): SeriesResponse {\n const samples = current.samples;\n const asked = options.columns ?? SERIES_COLUMNS;\n const count = Math.max(1, columnsFor(samples.length, asked));\n\n const columns = bucketize(samples, options.from, options.to, count);\n\n // A period of no width would divide by zero and a chart of it would be a\n // single column claiming to be a stretch of time.\n const span = Math.max(1, options.to - options.from);\n const bucketMs = span / count;\n\n // The period immediately before, cut into the same number of columns, so\n // the ghost lines up with the line it sits behind.\n const ghostColumns =\n previous.length > 0 ? bucketize(previous, options.from - span, options.from - 1, count) : null;\n const primary = options.metrics[0];\n\n const series: MetricSeries[] = options.metrics.map((metric) => ({\n metric,\n values: columns.map((column) => metricValue(metric, column, bucketMs)),\n }));\n\n return {\n from: options.from,\n to: options.to,\n bucketMs,\n calls: columns.map((column) => column.durations.length),\n series,\n totals: totalsOf(samples),\n // No traffic before the period is not a period of zeroes; it is nothing\n // to compare against, and the screen says so instead of inventing a\n // hundred-percent rise.\n previous: previous.length > 0 ? totalsOf(previous) : null,\n ghost:\n ghostColumns && primary\n ? ghostColumns.map((column) => metricValue(primary, column, bucketMs))\n : null,\n truncated: current.truncated,\n };\n}\n","/**\n * Where a page of the request list stopped.\n *\n * The cursor is part of the panel's API, not of any one store: the in-memory\n * ring and the SQLite history hand out cursors the browser cannot tell apart,\n * and both continue from one the other could have written.\n *\n * The key is whatever the page is ordered by — the start time for the list as\n * it is normally read, the duration when the question is \"what was slowest\".\n * It is not a position on its own, because several requests can share a\n * millisecond and plenty share a duration, so the id rides along and breaks\n * the tie exactly the way the ordering does: largest first, among equals the\n * larger id first.\n */\n\n/** A decoded cursor. */\nexport interface Cursor {\n /** Value of the column the page is ordered by. */\n readonly key: number;\n readonly id: string;\n}\n\n/** Writes the position of the last row on a page. */\nexport function encodeCursor(key: number, id: string): string {\n return `${key}.${id}`;\n}\n\n/**\n * Reads a cursor back.\n *\n * Split at the last dot rather than the first: a duration key is fractional,\n * and request ids are base36 with no dot in them.\n *\n * Anything unparseable means \"start from the newest\" rather than an error: a\n * stale link is a thing that happens, and answering it with a 400 helps\n * nobody.\n */\nexport function decodeCursor(raw: string | null | undefined): Cursor | null {\n if (!raw) return null;\n const dot = raw.lastIndexOf('.');\n if (dot <= 0) return null;\n const key = Number(raw.slice(0, dot));\n const id = raw.slice(dot + 1);\n if (!Number.isFinite(key) || id === '') return null;\n return { key, id };\n}\n\n/**\n * Whether a row belongs on a page continuing from `cursor`.\n *\n * Strictly past it, so a row is never served twice and never skipped.\n */\nexport function isAfterCursor(cursor: Cursor, key: number, id: string): boolean {\n if (key !== cursor.key) return key < cursor.key;\n return id < cursor.id;\n}\n","/**\n * One page of a list, from records held in memory.\n *\n * The paging rule, in one place: the router's fallback calls it, and so does\n * any store that holds its records in memory. Two implementations of it would\n * mean one panel giving two answers depending on the store behind it.\n *\n * A store that pages in its own query language cannot use this and should not\n * — pushing the work down is why it has a `page()`. What it owes is the same\n * behaviour, which is what the parity test checks.\n */\n\nimport type { RecordedRequest } from '../types.js';\nimport type { PageQuery, RequestPage } from './api.js';\nimport { toRow } from './api.js';\nimport { filterRequests, summarize } from './filters.js';\nimport { decodeCursor, encodeCursor, isAfterCursor } from './paging.js';\n\n/** What the caller knows that the records do not. */\nexport interface PageContext {\n /** Ids currently pinned. Exempt from the filter, and flagged on the row. */\n readonly pinned?: ReadonlySet<string> | undefined;\n /** Above this a request counts as slow in the summary. */\n readonly slowMs?: number | undefined;\n}\n\n/**\n * Pages `records` — newest first — according to `query`.\n *\n * `records` is the store's whole contents: the summary is over all of them,\n * which is what makes the status bar a statement about the store rather than\n * about the page.\n */\nexport function pageFromList(\n records: readonly RecordedRequest[],\n query: PageQuery,\n context: PageContext = {},\n): RequestPage {\n const pinned = context.pinned ?? new Set<string>();\n\n // A pinned request is one the reader deliberately set aside: it stays\n // through a filter that would otherwise exclude it.\n const matched = new Set(filterRequests(records, query.filter).map((item) => item.id));\n const shown = records.filter((item) => matched.has(item.id) || pinned.has(item.id));\n\n // What the page is ordered by, and therefore what the cursor counts in.\n const slowest = query.sort === 'slowest';\n const keyOf = (item: RecordedRequest): number => (slowest ? item.durationMs : item.startedAt);\n // Sorted in both cases: the cursor counts in this order, and a list handed\n // over in arrival order is not in it — a slow request starts early and\n // lands late, and a page boundary beside it would skip or repeat rows.\n const ordered = [...shown].sort((a, b) => keyOf(b) - keyOf(a) || (a.id < b.id ? 1 : -1));\n\n const cursor = decodeCursor(query.cursor);\n const after = cursor\n ? ordered.filter((item) => isAfterCursor(cursor, keyOf(item), item.id))\n : ordered;\n\n const rows = after.slice(0, query.limit);\n const last = rows[rows.length - 1];\n const nextCursor = after.length > rows.length && last ? encodeCursor(keyOf(last), last.id) : null;\n\n return {\n rows: rows.map((item) => toRow(item, pinned.has(item.id))),\n nextCursor,\n summary: summarize(records, shown, context.slowMs),\n };\n}\n","/**\n * Was the process to blame?\n *\n * Knowing an operation is slow does not say why, and often the code did not\n * change at all — the loop fell behind, and every callback waited before it\n * even started. That is invisible in a waterfall: the spans are each fast and\n * the time is between them.\n *\n * The comparison here is a route against itself. Its calls are split by\n * whether the loop was in its *own* top quartile at the time, and the two\n * halves are compared. Elevated is never a fixed threshold: a delay that is\n * alarming for one service is idle for the next, and the only baseline worth\n * comparing a process against is the same process.\n *\n * It is evidence, not proof, and the panel says so. A batch job hammering the\n * same process explains the shape as well as this route being its victim.\n */\n\nimport type { HostPressure, HostPressureSide } from '../types.js';\nimport type { DurationSample } from './api.js';\nimport { percentile } from './routes.js';\n\n/**\n * Calls needed on each side of the split.\n *\n * Twenty is where a ninety-fifth percentile stops being the single slowest\n * call and starts describing a distribution. Below it the comparison is\n * between two anecdotes.\n */\nconst MIN_PER_SIDE = 20;\n\n/**\n * How much slower the bad half has to be before it is worth a word.\n *\n * Under half again, the difference is inside the noise of a sample this size,\n * and a card that fires there is a card that fires always.\n */\nconst MIN_RATIO = 1.5;\n\n/**\n * How much the loop has to have varied for \"elevated\" to mean anything.\n *\n * A host that was flat has no elevated state to compare against: splitting it\n * at its own quartile would sort calls by a millisecond of jitter and then\n * report whatever the two halves happened to differ by.\n */\nconst MIN_SPREAD_MS = 1;\n\nfunction sideOf(durations: readonly number[]): HostPressureSide {\n const sorted = [...durations].sort((a, b) => a - b);\n const sum = sorted.reduce((total, value) => total + value, 0);\n return {\n calls: sorted.length,\n p95Ms: percentile(sorted, 0.95),\n avgMs: sorted.length === 0 ? 0 : sum / sorted.length,\n };\n}\n\n/**\n * The finding, or `null` — which is the answer far more often, and by design.\n *\n * @param samples every other call of the route, as the store hands them over.\n */\nexport function pressureFor(samples: readonly DurationSample[]): HostPressure | null {\n const measured = samples.filter(\n (sample): sample is DurationSample & { loopDelayMs: number } => sample.loopDelayMs !== null,\n );\n if (measured.length < MIN_PER_SIDE * 2) return null;\n\n const delays = measured.map((sample) => sample.loopDelayMs).sort((a, b) => a - b);\n const cutoffMs = percentile(delays, 0.75);\n // Did the loop actually move? Comparing the top quartile against the bottom\n // one answers it without a threshold of its own.\n if (cutoffMs - percentile(delays, 0.25) < MIN_SPREAD_MS) return null;\n\n const elevated = sideOf(\n measured.filter((sample) => sample.loopDelayMs >= cutoffMs).map((sample) => sample.durationMs),\n );\n const normal = sideOf(\n measured.filter((sample) => sample.loopDelayMs < cutoffMs).map((sample) => sample.durationMs),\n );\n if (elevated.calls < MIN_PER_SIDE || normal.calls < MIN_PER_SIDE) return null;\n // Nothing to be slower than: a route where the good half is instant would\n // report a ratio of infinity and mean nothing by it.\n if (normal.p95Ms <= 0) return null;\n\n const ratio = elevated.p95Ms / normal.p95Ms;\n if (ratio < MIN_RATIO) return null;\n\n return {\n metric: 'loop',\n cutoffMs,\n ratio,\n share: (elevated.calls / measured.length) * 100,\n elevated,\n normal,\n };\n}\n","/**\n * What Reqray knows about the application it is watching.\n *\n * The startup report — what was instrumented and what was not — has so far\n * existed only in the terminal, printed once. That is the wrong place for it:\n * \"why do I not see my SQL\" is a question asked hours later, by which point\n * the line has scrolled away, and in a container it was never on screen at\n * all. So the same facts are served to the panel, together with the settings\n * that decide what gets recorded and the shape of the process doing the\n * recording.\n *\n * Nothing secret goes in here. Environment variables are not read, the panel\n * gate is reported as present or absent rather than by value, and the masking\n * lists are field *names*, which is what makes them safe to show and useful\n * to check.\n */\n\nimport { execFile } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport type {\n GitHead,\n ProjectApp,\n ProjectLog,\n ProjectReport,\n ProjectRetention,\n ProjectRuntime,\n ProjectStorage,\n} from '@reqray/protocol';\nimport type { ResolvedOptions } from '../config.js';\nimport { getDiagnostics } from '../diagnostics.js';\nimport { poolStats } from '../pools.js';\n\nexport type {\n GitHead,\n ProjectApp,\n ProjectLog,\n ProjectReport,\n ProjectRetention,\n ProjectRuntime,\n ProjectStorage,\n};\n\n/** The log's own account of itself, or `null` when there is no log. */\nexport function logOf(options: ResolvedOptions): ProjectLog | null {\n const log = options.requestLog;\n if (!log) return null;\n try {\n return { dir: log.dir, ...log.stats() };\n } catch {\n // A log that cannot describe itself is still not the panel's problem.\n return null;\n }\n}\n\n/** The retention policy as the panel sees it. */\nexport function retentionOf(options: ResolvedOptions): ProjectRetention | null {\n const policy = options.retention;\n if (!policy) return null;\n return {\n ...policy.current(),\n writable: policy.writable,\n remembered: policy.file !== null,\n };\n}\n\nfunction readManifest(directory: string): { name?: unknown; version?: unknown } | null {\n try {\n return JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')) as {\n name?: unknown;\n version?: unknown;\n };\n } catch {\n // No manifest where the project root points: unusual, not an error.\n return null;\n }\n}\n\n/** Version of `@reqray/core` itself — the first thing a bug report needs. */\nfunction reqrayVersion(): string | null {\n try {\n const manifest = createRequire(import.meta.url).resolve('@reqray/core/package.json');\n const parsed = JSON.parse(readFileSync(manifest, 'utf8')) as { version?: unknown };\n return typeof parsed.version === 'string' ? parsed.version : null;\n } catch {\n // Running from source, or packaged without the manifest.\n return null;\n }\n}\n\nfunction git(args: readonly string[], cwd: string): Promise<string | null> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n args,\n { cwd, timeout: 2_000, maxBuffer: 64 * 1024, windowsHide: true },\n (error, stdout) => resolve(error ? null : stdout.trim()),\n );\n });\n}\n\ninterface CachedHead {\n readonly at: number;\n readonly head: GitHead | null;\n}\n\nlet cached: CachedHead | null = null;\n/** Short enough to survive a branch switch, long enough to cost nothing. */\nconst GIT_TTL_MS = 10_000;\n\n/**\n * The commit the running code came from.\n *\n * `null` for anything that is not a git checkout — a container built from a\n * tarball, an installed package, a machine without git. All ordinary, none of\n * them an error.\n */\nexport async function gitHead(cwd: string, now = Date.now()): Promise<GitHead | null> {\n if (cached && now - cached.at < GIT_TTL_MS) return cached.head;\n\n const [branch, sha, status] = await Promise.all([\n git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd),\n git(['rev-parse', '--short', 'HEAD'], cwd),\n git(['status', '--porcelain'], cwd),\n ]);\n\n const head = branch === null && sha === null ? null : { branch, sha, dirty: status !== '' };\n cached = { at: now, head };\n return head;\n}\n\n/** Forgets the cached commit. Needed by tests. */\nexport function clearGitHead(): void {\n cached = null;\n}\n\n/** Anything a store may choose to report about itself. */\ninterface StoreStats {\n size?: unknown;\n capacity?: unknown;\n evicted?: unknown;\n oldestAt?: unknown;\n pinned?: unknown;\n bytes?: unknown;\n}\n\nconst numberOr = (value: unknown, fallback: number | null): number | null =>\n typeof value === 'number' ? value : fallback;\n\n/**\n * What the store will say about itself.\n *\n * `stats()` is not part of the panel's contract — the memory ring and the\n * SQLite history both have one, a third-party store need not — so everything\n * here is optional and nothing is assumed.\n */\nexport function storageOf(source: unknown): ProjectStorage | null {\n const store = source as { name?: unknown; stats?: () => StoreStats };\n if (typeof store?.stats !== 'function') return null;\n try {\n const stats = store.stats();\n return {\n name: typeof store.name === 'string' ? store.name : 'unknown',\n size: numberOr(stats.size, 0) ?? 0,\n capacity: numberOr(stats.capacity, null),\n evicted: numberOr(stats.evicted, null),\n oldestAt: numberOr(stats.oldestAt, null),\n pinned: numberOr(stats.pinned, null),\n bytes: numberOr(stats.bytes, null),\n };\n } catch {\n return null;\n }\n}\n\n/** Collects everything the project screen shows. */\nexport async function projectReport(\n options: ResolvedOptions,\n source: unknown,\n): Promise<ProjectReport> {\n const root = options.stack.projectRoot;\n const manifest = readManifest(root);\n const memory = process.memoryUsage();\n\n return {\n app: {\n name: typeof manifest?.name === 'string' ? manifest.name : null,\n version: typeof manifest?.version === 'string' ? manifest.version : null,\n root,\n git: await gitHead(root),\n },\n runtime: {\n node: process.version,\n platform: process.platform,\n arch: process.arch,\n pid: process.pid,\n startedAt: Date.now() - Math.round(process.uptime() * 1000),\n rssMb: memory.rss / 1024 / 1024,\n heapUsedMb: memory.heapUsed / 1024 / 1024,\n },\n reqray: {\n version: reqrayVersion(),\n mode: options.mode,\n enabled: options.enabled,\n isLocalDevelopment: options.isLocalDevelopment,\n bufferSize: options.bufferSize,\n maxSpansPerRequest: options.maxSpansPerRequest,\n sampling: options.sampling,\n replay: options.replay,\n explain: options.explain,\n blame: options.blame,\n logs: options.logs,\n collectSqlValues: options.collectSqlValues,\n // The gate is a function or a rule; either way it is a credential, and\n // the panel only needs to know that one is in place.\n panel: options.panel\n ? { path: options.panel.path, gated: options.panel.gate !== null }\n : null,\n redact: { headers: options.redact.headers, body: options.redact.body },\n detect: options.detect as unknown as Readonly<Record<string, unknown>>,\n stack: options.stack,\n },\n instrumentation: getDiagnostics(),\n storage: storageOf(source),\n log: logOf(options),\n retention: retentionOf(options),\n pools: poolStats(),\n };\n}\n","/**\n * Startup diagnostics.\n *\n * The library prints what it instrumented and what it could not, with a hint\n * on how to fix it. This heads off most of the future \"I don't see my\n * requests\" issues.\n */\n\nimport type { DiagnosticEntry } from '@reqray/protocol';\nimport { info } from './logger.js';\nimport { globalBox, globalSlot } from './state.js';\n\n/** The instrumentation report, collected at startup. */\nconst report = globalSlot('diagnostics.report', () => [] as DiagnosticEntry[]);\n\nconst printed = globalBox('diagnostics.printed', false);\n\nexport type { DiagnosticEntry };\n\n/** Records the outcome of an attempt to instrument a package. */\nexport function reportInstrumentation(entry: DiagnosticEntry): void {\n report().push(entry);\n}\n\n/** Everything collected so far. */\nexport function getDiagnostics(): readonly DiagnosticEntry[] {\n return report();\n}\n\n/** Clears the report. Needed by tests. */\nexport function clearDiagnostics(): void {\n report().length = 0;\n}\n\nfunction labelOf(entry: DiagnosticEntry): string {\n if (entry.builtin) return `${entry.name} (built-in)`;\n return entry.version ? `${entry.name}@${entry.version}` : entry.name;\n}\n\n/**\n * Renders the report as text.\n *\n * Kept as a separate pure function so the format can be asserted in a test\n * without intercepting the console.\n */\nexport function renderDiagnostics(report: readonly DiagnosticEntry[]): string {\n const active = report.some((entry) => entry.ok);\n const header = active ? 'reqray instrumentation active' : 'reqray instrumentation not attached';\n if (report.length === 0) return header;\n\n const width = Math.max(...report.map((entry) => labelOf(entry).length)) + 4;\n const lines = [header];\n\n for (const entry of report) {\n const mark = entry.ok ? '✔' : '✘';\n const detail = entry.ok ? entry.captures : (entry.reason ?? entry.captures);\n lines.push(` ${mark} ${labelOf(entry).padEnd(width)}${detail}`);\n if (entry.hint) lines.push(` ${' '.repeat(width + 2)}→ ${entry.hint}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * What to say under the report about a panel with no gate.\n *\n * Such a panel answers its own machine and nobody else, and the person who\n * finds that out is looking at a 403 from inside a dev container or behind a\n * local proxy. Said at startup, it is a line read once instead of an issue.\n */\nexport const UNGATED_PANEL_NOTE = [\n ' panel answers this machine only: no gate is set',\n \" → from a container, a proxy or another machine: reqray({ panel: { gate: 'open' } })\",\n].join('\\n');\n\n/** Prints the report. Called once when Reqray initializes. */\nexport function printDiagnostics(note?: string): void {\n const text = renderDiagnostics(report());\n info(note ? `${text}\\n${note}` : text);\n}\n\n/**\n * Prints the report at most once per process lifetime.\n *\n * An application may have several adapters, but only needs one report.\n */\nexport function printDiagnosticsOnce(note?: string): void {\n const once = printed();\n if (once.value) return;\n once.value = true;\n printDiagnostics(note);\n}\n\n/** Allows the report to be printed again. Needed by tests. */\nexport function resetDiagnosticsPrinted(): void {\n printed().value = false;\n}\n","/**\n * Registry of live connection pools.\n *\n * A pool is the one part of the picture that cannot be reconstructed from\n * spans. A span says a query waited; only the pool says whether it was the\n * last free connection or the fortieth request in a queue, and that is the\n * difference between \"raise `max`\" and \"stop holding connections\". So the\n * panel asks the pool itself, at the moment somebody is looking.\n *\n * Two rules hold this together.\n *\n * References are weak. A pool that the application closed and dropped must be\n * collectable; a registry that keeps one alive is a leak with a nice name.\n *\n * And core knows nothing about any driver. Each instrumentation registers its\n * pools with a reader that speaks that driver's dialect — `totalCount` and\n * `idleCount` in `pg`, something else in the next one — so this file never\n * grows a `if (driver === …)`.\n */\n\nimport type { PoolReading, PoolStats } from '@reqray/protocol';\nimport { type Box, globalBox, globalSlot } from './state.js';\n\n/** A registered pool: the reference stays weak, the reader knows the driver. */\ninterface PoolEntry {\n readonly id: number;\n readonly ref: WeakRef<object>;\n readonly read: (pool: object) => PoolReading | null;\n}\n\n/** Live pools, weakly held. */\nconst pools = globalSlot('pools.live', () => new Set<PoolEntry>());\n\n/** Pools already registered, keyed by the pool itself. */\nconst registered = globalSlot('pools.registered', () => new WeakMap<object, PoolEntry>());\n\n/** Id source for {@link pools}. */\nconst sequence: () => Box<number> = globalBox('pools.sequence', 0);\n\nexport type { PoolReading, PoolStats };\n\n/**\n * Registers a pool, idempotently.\n *\n * Called from the instrumentation on every pooled query, so it has to be\n * cheap and it has to tolerate being called a million times: a pool already\n * registered costs one `WeakMap` lookup and nothing else.\n */\nexport function registerPool(pool: object, read: (pool: object) => PoolReading | null): void {\n try {\n const known = registered();\n if (known.has(pool)) return;\n\n const seq = sequence();\n seq.value += 1;\n const entry: PoolEntry = { id: seq.value, ref: new WeakRef(pool), read };\n known.set(pool, entry);\n pools().add(entry);\n } catch {\n // A registry failure must never reach the query that triggered it.\n }\n}\n\n/**\n * What every live pool says about itself, right now.\n *\n * Entries whose pool has been collected are dropped on the way past: this is\n * the only moment the registry is walked, so it is the only place the dead\n * ones can be noticed.\n */\nexport function poolStats(): PoolStats[] {\n const stats: PoolStats[] = [];\n try {\n const live = pools();\n for (const entry of live) {\n const pool = entry.ref.deref();\n if (!pool) {\n live.delete(entry);\n continue;\n }\n try {\n const reading = entry.read(pool);\n if (reading) stats.push({ id: entry.id, ...reading });\n } catch {\n // A driver that changed shape reports nothing rather than throwing\n // into whoever opened the panel.\n }\n }\n } catch {\n return stats;\n }\n return stats;\n}\n\n/** Forgets every pool. Needed by tests. */\nexport function resetPools(): void {\n pools().clear();\n}\n","/**\n * Where a replayed request's record is delivered.\n *\n * A replay runs through the application like any other request, so it is\n * recorded like any other request — and it must not appear in the shared list,\n * because nobody made it. The panel marks it with a header, the adapter puts\n * the marker on the scope, and when the request finishes its record goes to\n * whoever started the replay instead of to the store.\n *\n * The registry sits between the two: `reqray.ts` writes into it on the\n * recording path, `panel/replay.ts` reads from it, and neither imports the\n * other. The one piece of state both entry points share.\n */\n\nimport { globalSlot } from './state.js';\nimport type { RecordedRequest } from './types.js';\n\n/** Replays in flight, by the id the panel put on the request. */\nconst waiters = globalSlot(\n 'replay.waiters',\n () => new Map<string, (request: RecordedRequest) => void>(),\n);\n\n/** Registers interest in a replay's record. Returns the way to stop waiting. */\nexport function awaitReplay(id: string, deliver: (request: RecordedRequest) => void): () => void {\n waiters().set(id, deliver);\n return () => {\n waiters().delete(id);\n };\n}\n\n/**\n * Hands a finished replay to whoever asked for it.\n *\n * @returns whether anybody was waiting — `false` means the record belongs in\n * the store after all, which is what happens when a replay times out and its\n * response arrives anyway.\n */\nexport function deliverReplay(id: string, request: RecordedRequest): boolean {\n const waiter = waiters().get(id);\n if (!waiter) return false;\n waiter(request);\n return true;\n}\n","/**\n * The Reqray runtime: what framework adapters call on every request.\n *\n * This is the hot-path boundary. `begin` and `finish` must cost close to\n * nothing; detectors, masking, serialization and the transport write are\n * deferred to `setImmediate`, where they no longer affect the client's\n * response time.\n */\n\nimport { join } from 'node:path';\nimport { recordBody } from './body.js';\nimport { type ReqrayOptions, type ResolvedOptions, resolveOptions } from './config.js';\nimport { instrumentConsole } from './console-capture.js';\nimport { runOutsideScope } from './context.js';\nimport { measureCost, startCostMeter, stopCostMeter } from './cost.js';\nimport { runDetectors } from './detectors/index.js';\nimport { printDiagnosticsOnce, UNGATED_PANEL_NOTE } from './diagnostics.js';\nimport { type HostMonitor, startHostMonitor } from './host.js';\nimport { nextRequestId } from './ids.js';\nimport { warn, warnOnce } from './logger.js';\nimport { assertPanelAllowed } from './panel.js';\nimport { type HotFrame, type RequestProfiler, startProfiler } from './profiler.js';\nimport { redactHeaders, redactQuery } from './redact.js';\nimport { deliverReplay } from './replay-waiters.js';\nimport { shouldRetain } from './sampling.js';\nimport { RequestScope } from './scope.js';\nimport { selfTimes, timingOf } from './timing.js';\nimport { multiTransport, nullTransport, type Transport } from './transport.js';\nimport type { Finding, LogEntry, RecordedRequest, RequestCost, SpanError } from './types.js';\nimport { weightOf } from './weight.js';\n\n/** Headers in the shape Node and the frameworks hand them over. */\nexport type HeaderMap = Readonly<Record<string, string | string[] | number | undefined>>;\n\n/** What is known about a request when it starts. */\nexport interface RequestStart {\n readonly method: string;\n /** Path without the query string. */\n readonly path: string;\n /**\n * Value of the replay marker header, if present.\n *\n * Such a request stays out of the main list: its record goes to the panel\n * that started the replay.\n */\n readonly replayId?: string | null;\n}\n\n/** Request outcome. Passed by the adapter once the response has been sent. */\nexport interface RequestOutcome {\n readonly status: number;\n /** Query string without the `?`, if there was one. */\n readonly query?: string | null;\n readonly requestHeaders?: HeaderMap;\n readonly responseHeaders?: HeaderMap;\n readonly requestBody?: unknown;\n readonly responseBody?: unknown;\n /** The exception, if handling failed. */\n readonly error?: unknown;\n}\n\n/** What an adapter drives on every request. */\nexport interface Reqray {\n readonly options: ResolvedOptions;\n readonly transport: Transport;\n\n /**\n * Starts a request.\n *\n * @returns the scope, or `undefined` if Reqray is disabled. In that case the\n * adapter must do nothing at all — this is what \"disabled Reqray costs zero\"\n * means.\n */\n begin(start: RequestStart): RequestScope | undefined;\n\n /** Finishes a request. Safely accepts `undefined`. */\n finish(scope: RequestScope | undefined, outcome: RequestOutcome): void;\n\n /**\n * Stops what this runtime started and lets go of what it holds.\n *\n * `createReqray` starts a host monitor and may open a store; `Transport`\n * declares both `flush` and `close`, and there was no way to reach either.\n * A long-lived process never needed this; a test that builds a runtime per\n * case, and a graceful shutdown that wants the last batch to land, both do.\n *\n * Safe to call twice.\n */\n close(): Promise<void>;\n}\n\n/** Runtime creation options. */\nexport interface ReqrayInit extends ReqrayOptions {\n /**\n * Where to put collected requests.\n *\n * Several are allowed and are written to in order: a store the panel reads\n * and a log file on disk are two transports over one stream of requests.\n */\n readonly transport?: Transport | readonly Transport[];\n}\n\n/**\n * Coerces anything thrown into a `SpanError`.\n *\n * Needed by instrumentations: they mark a span with an error but must rethrow\n * the exception itself unchanged.\n */\nexport function toSpanError(error: unknown): SpanError | null {\n if (error === undefined || error === null) return null;\n if (error instanceof Error) {\n return { name: error.name, message: error.message, stack: error.stack ?? null };\n }\n return { name: 'Error', message: String(error), stack: null };\n}\n\nfunction formatDuration(durationMs: number): string {\n return durationMs < 10 ? `${durationMs.toFixed(1)} ms` : `${Math.round(durationMs)} ms`;\n}\n\n/**\n * Brackets the collected log lines with a request start and end line.\n *\n * Assembled at finalization rather than on the hot path: both lines are fully\n * derived from data already known.\n */\nfunction bracketLogs(scope: RequestScope, status: number, durationMs: number): LogEntry[] {\n return [\n { at: 0, level: 'info', message: `→ ${scope.method} ${scope.path}` },\n ...scope.logs,\n {\n at: durationMs,\n level: status >= 500 ? 'error' : 'info',\n message: `← ${status} in ${formatDuration(durationMs)}`,\n },\n ];\n}\n\n/** How a test harness names the test behind a request. */\nexport const TEST_HEADER = 'x-reqray-test';\n\n/**\n * Header that marks a replay.\n *\n * Beside `TEST_HEADER` rather than in the panel: both are read off an incoming\n * request by the adapter, on the recording path. The panel writes this one,\n * which does not make it the panel's.\n */\nexport const REPLAY_HEADER = 'x-reqray-replay';\n\n/** The maximum length of a test name kept in a record. */\nconst MAX_TEST_NAME = 200;\n\n/**\n * The test that issued the request, from the header the harness sets.\n *\n * Read from the raw headers rather than the redacted copy: masking may have\n * replaced the value, and this one is a test name, not a secret.\n *\n * Header values are latin1, and test names are full of characters that are\n * not — Vitest and Jest separate suite from case with `›`. A percent-encoded\n * value is therefore decoded; anything that fails to decode is kept as sent,\n * because a slightly odd name is better than no name.\n */\nfunction testOf(outcome: RequestOutcome): string | null {\n const raw = outcome.requestHeaders?.[TEST_HEADER];\n const value = Array.isArray(raw) ? raw[0] : raw;\n if (typeof value !== 'string') return null;\n let trimmed = value.trim();\n if (trimmed.includes('%')) {\n try {\n trimmed = decodeURIComponent(trimmed);\n } catch {\n // Not percent-encoded after all — a literal `%` in the name.\n }\n }\n // Decoding can produce what a header never could: `%0A` is a line break,\n // and this name is later written into a shell script and onto a terminal.\n trimmed = trimmed.replace(/\\p{Cc}/gu, ' ').trim();\n return trimmed ? trimmed.slice(0, MAX_TEST_NAME) : null;\n}\n\n/**\n * How much went back to the client, cheaply.\n *\n * What the client was told, when it was told anything; the body's own size\n * when the framework streamed it as text. An object body is not serialized\n * here to find out — that is the expensive half of finishing a request, and\n * it happens once, later, for the requests that are kept.\n */\nfunction bytesOutOf(outcome: RequestOutcome): number | null {\n const declared = Number(outcome.responseHeaders?.['content-length']);\n if (Number.isFinite(declared) && declared >= 0) return declared;\n return typeof outcome.responseBody === 'string' ? Buffer.byteLength(outcome.responseBody) : null;\n}\n\n/** What the response said it was, without the charset and the rest. */\nfunction contentTypeOf(outcome: RequestOutcome): string | null {\n const raw = outcome.responseHeaders?.['content-type'];\n const value = Array.isArray(raw) ? raw[0] : raw;\n return typeof value === 'string' ? (value.split(';')[0]?.trim() ?? null) : null;\n}\n\n/**\n * Masking and measurement, done once.\n *\n * The detectors need to know how much came back, and the record needs the\n * same masked headers and bodies. Doing it twice would mean masking twice —\n * the expensive half of finishing a request — so it happens here, after the\n * response is on the wire, and both readers share the result.\n */\nfunction prepare(scope: RequestScope, outcome: RequestOutcome, options: ResolvedOptions) {\n const redact = options.redact;\n const requestHeaders = outcome.requestHeaders\n ? redactHeaders(outcome.requestHeaders, redact)\n : {};\n const responseHeaders = outcome.responseHeaders\n ? redactHeaders(outcome.responseHeaders, redact)\n : {};\n const spans = scope.orderedSpans();\n const requestBody = recordBody(outcome.requestBody, redact);\n const responseBody = recordBody(outcome.responseBody, redact);\n return {\n spans,\n requestHeaders,\n responseHeaders,\n requestBody,\n responseBody,\n weight: weightOf({ spans, requestHeaders, responseHeaders, requestBody, responseBody }),\n };\n}\n\ntype Prepared = ReturnType<typeof prepare>;\n\n/**\n * Completes a slow-code finding with what was actually running in it.\n *\n * The detector can only name the boundary: `shop.js:231` is the query the\n * stretch ends at, not the `pbkdf2Sync` three lines above it that spent the\n * time. Samples know the difference, so where the profiler has them the\n * finding stops pointing at the edge of the hole and points into it.\n *\n * Only the frames are inserted when the window turns out to have been idle.\n * A stretch spent waiting has no line of code to blame, and moving the\n * callsite to whatever ran for two of its samples would be worse than the\n * boundary it already had.\n */\nfunction withHotSpots(\n findings: readonly Finding[],\n scope: RequestScope,\n profiler: RequestProfiler | null,\n): Finding[] {\n if (!profiler) return [...findings];\n\n return findings.map((finding) => {\n const evidence = finding.evidence;\n if (evidence.kind !== 'slow_code') return finding;\n\n const from = scope.startTime + evidence.atMs;\n const hot = profiler.read(from, from + evidence.stretchMs);\n if (!hot) return finding;\n\n const top = hot.frames[0];\n const running = hot.busyShare >= RUNNING_SHARE && top !== undefined;\n\n return {\n ...finding,\n ...(running\n ? {\n callsite: {\n file: join(scope.options.stack.projectRoot, top.relative),\n relative: top.relative,\n line: top.line,\n column: 0,\n },\n title: `${Math.round(evidence.stretchMs)} ms in ${top.functionName}`,\n hint: hintForFrame(top),\n }\n : {\n hint: `Only ${Math.round(hot.busyShare * 100)}% of the samples taken in this stretch were on a processor, so the time went on waiting rather than on running — I/O with no instrumentation behind it, or a timer.`,\n }),\n evidence: { ...evidence, frames: hot.frames, busyShare: hot.busyShare },\n };\n });\n}\n\n/**\n * Where to look, and what to look for once there.\n *\n * V8 reports the line a function is defined on, never the line executing, so\n * the address can only be the function. Naming what it was calling is what\n * closes the remaining distance: `registerUser` at `shop.js:213` is where,\n * and `pbkdf2Sync` is the call inside it that spent the time.\n */\nfunction hintForFrame(frame: HotFrame): string {\n const where = `${Math.round(frame.share * 100)}% of the samples in this stretch were inside ${frame.functionName} at ${frame.relative}:${frame.line}`;\n return frame.inside\n ? `${where}, calling ${frame.inside}. V8 reports where a function starts rather than the line running, so look for the ${frame.inside} call.`\n : `${where}.`;\n}\n\n/**\n * Above this share of running samples, a stretch is called code and the\n * finding is re-aimed at the function holding it.\n *\n * Below it the stretch was mostly waiting, and the busiest frame is whatever\n * the sampler caught on the way past.\n */\nconst RUNNING_SHARE = 0.5;\n\n/**\n * Microseconds between stack samples.\n *\n * A millisecond resolves a hundred-millisecond stretch into roughly eighty\n * readings, which is enough for a share to mean something, and measured at\n * about seven microseconds on a request's p99 — under a fiftieth of the\n * budget the published overhead numbers are held to.\n */\nconst SAMPLE_INTERVAL_US = 1_000;\n\nfunction buildRecord(\n scope: RequestScope,\n outcome: RequestOutcome,\n durationMs: number,\n findings: readonly Finding[],\n host: HostMonitor | null,\n prepared: Prepared,\n cost: RequestCost,\n): RecordedRequest {\n const { spans, requestHeaders, responseHeaders, requestBody, responseBody } = prepared;\n const self = selfTimes(spans);\n return {\n id: scope.id,\n method: scope.method,\n path: scope.path,\n query: outcome.query ? redactQuery(outcome.query, scope.options.redact) : null,\n status: outcome.status,\n durationMs,\n timing: timingOf(spans, durationMs),\n weight: prepared.weight,\n // The window the request ran in, not a measurement of the request: two\n // native reads, and the panel says so in as many words.\n host: host?.read() ?? null,\n cost,\n startedAt: scope.startedAt,\n // Self time is attached here rather than at display time so that the\n // panel, the terminal client and anything else reading the API get one\n // number rather than three implementations of the same subtraction.\n spans: spans.map((span) => ({ ...span, selfMs: self.get(span.id) ?? span.duration })),\n findings,\n // Masking happens before the buffer write, not at display time.\n requestHeaders,\n responseHeaders,\n requestBody,\n responseBody,\n logs: bracketLogs(scope, outcome.status, durationMs),\n error: toSpanError(outcome.error),\n droppedSpans: scope.droppedSpans,\n droppedLogs: scope.droppedLogs,\n test: testOf(outcome),\n };\n}\n\n/**\n * Creates the runtime.\n *\n * If the panel is enabled somewhere it could be reachable from outside and no\n * gate is set, this throws right here, at application startup.\n */\nexport function createReqray(init: ReqrayInit = {}): Reqray {\n const options = resolveOptions(init);\n\n // Before any resource is acquired: this throws on the staging path, and a\n // monitor started first would tick on with nothing left to stop it.\n if (options.enabled) assertPanelAllowed(options);\n\n const transport = Array.isArray(init.transport)\n ? multiTransport(init.transport)\n : ((init.transport as Transport | undefined) ?? nullTransport);\n\n // One histogram for the process, started with it: a request that finishes\n // asks the monitor what the loop was doing, and gets an answer or a null.\n const host = options.enabled && options.hostMetrics ? startHostMonitor() : null;\n\n // The collector is watched from the moment Reqray is: a request's cost is\n // read at its edges, so there is nothing to switch on per request.\n if (options.enabled) startCostMeter();\n\n // Sampling runs for the process, not per request: a stretch worth\n // explaining is only known about once it is over.\n const profiler =\n options.enabled && options.profile\n ? startProfiler({ stack: options.stack, intervalUs: SAMPLE_INTERVAL_US })\n : null;\n\n if (options.enabled) {\n // A global tap; whether a line is recorded is decided per request from\n // its scope's options.\n if (options.logs) instrumentConsole();\n if (options.replay && !options.isLocalDevelopment) {\n warn(\n 'replay is enabled outside local development. Replaying a request in production means charging a card twice and sending an email twice.',\n );\n }\n // The report is printed on the next tick: by then the adapter has reported\n // itself and the loader hooks have reported everything loaded so far.\n const ungated = options.panel !== null && options.panel.gate === null;\n setImmediate(() => printDiagnosticsOnce(ungated ? UNGATED_PANEL_NOTE : undefined));\n }\n\n let closed = false;\n\n return {\n options,\n transport,\n\n begin(start) {\n if (!options.enabled) return undefined;\n return new RequestScope({\n id: nextRequestId(),\n method: start.method,\n path: start.path,\n options,\n replayId: start.replayId ?? null,\n });\n },\n\n finish(scope, outcome) {\n if (!scope) return;\n\n try {\n scope.closeAllSpans();\n } catch {\n // An unclosed span is no reason to lose the whole request.\n }\n // The one thing that cannot wait: measured now, or it measures the\n // scheduling delay as well. The cost is read here for the same reason —\n // the processor time of the tick that follows is not this request's.\n const durationMs = performance.now() - scope.startTime;\n const cost = measureCost(scope.costMark, scope.startTime, durationMs);\n\n setImmediate(() => {\n // Reqray's own work must not end up as spans of the request being handled.\n runOutsideScope(() => {\n try {\n // What the detectors need to know about the request as a whole;\n // the scope only knows about spans. Read straight off the outcome\n // rather than from the prepared record: in production the\n // detectors run before the sampling decision, and masking a body\n // about to be dropped is work nobody asked for.\n //\n // Built here rather than above, because everything in it is\n // derivable from `outcome`, which the closure already holds — and\n // the response path is not the place to allocate an object and\n // split a content-type header.\n const facts = {\n durationMs,\n status: outcome.status,\n bytesOut: bytesOutOf(outcome),\n contentType: contentTypeOf(outcome),\n };\n\n // A replay is not sampled: its record is needed exactly once and\n // right now — the comparison block in the panel is built from it.\n if (\n scope.replayId &&\n deliverReplay(\n scope.replayId,\n buildRecord(\n scope,\n outcome,\n durationMs,\n withHotSpots(runDetectors(scope, options, facts), scope, profiler),\n host,\n prepare(scope, outcome, options),\n cost,\n ),\n )\n ) {\n return;\n }\n\n const hasError = outcome.error !== undefined && outcome.error !== null;\n\n // Detectors run before sampling only when a finding is itself a\n // reason to keep the request. Otherwise they run on the requests\n // that survived, which in production is one in a hundred.\n const findingsFirst = options.sampling.alwaysOnFinding;\n const findings = findingsFirst ? runDetectors(scope, options, facts) : [];\n\n const retained = shouldRetain(options.sampling, {\n durationMs,\n status: outcome.status,\n hasError,\n findings,\n });\n if (!retained) return;\n\n transport.send(\n buildRecord(\n scope,\n outcome,\n durationMs,\n withHotSpots(\n findingsFirst ? findings : runDetectors(scope, options, facts),\n scope,\n profiler,\n ),\n host,\n prepare(scope, outcome, options),\n cost,\n ),\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('reqray.finish', `request not recorded: ${reason}`);\n }\n });\n });\n },\n\n async close() {\n if (closed) return;\n closed = true;\n\n host?.stop();\n profiler?.stop();\n stopCostMeter();\n // Flush before close: the point of closing gracefully is that the last\n // batch lands, and a transport that buffers has nowhere to put it after.\n try {\n await transport.flush?.();\n } catch {\n // A shutdown must not fail because a collector was already gone.\n }\n try {\n await transport.close?.();\n } catch {\n // Same.\n }\n },\n };\n}\n","/**\n * Console capture: log lines written while a request is being handled land in\n * that request's record.\n *\n * Without this, \"you see the whole request\" is a third of a lie — the log of\n * the incident stays in the shared stdout haystack. The tap is deliberately\n * humble:\n *\n * - the original console is always called, with the original arguments, and\n * its output is never altered — capture failing must not cost a single\n * character of terminal output;\n * - no scope — nothing but the passthrough happens;\n * - a line whose normalized text mentions a sensitive pattern is replaced by\n * a marker: free-form text has no field names to mask by, and over-masking\n * is the side this project errs on.\n *\n * Limitation, stated honestly: pino and winston write past `console`, so only\n * `console.*` lines are captured. A pino stream is a separate task.\n */\n\nimport { format } from 'node:util';\nimport { current } from './context.js';\nimport { sensitivePatternIn, truncate } from './redact.js';\nimport type { LogEntry } from './types.js';\n\n/** \"Already patched\" marker: two copies of core must not stack wrappers. */\nconst PATCHED = Symbol.for('reqray.patched.console');\n\nconst METHODS = ['log', 'info', 'warn', 'error', 'debug'] as const;\ntype ConsoleMethod = (typeof METHODS)[number];\n\nconst LEVEL_OF: Record<ConsoleMethod, LogEntry['level']> = {\n log: 'info',\n info: 'info',\n warn: 'warn',\n error: 'error',\n debug: 'debug',\n};\n\ntype ConsoleHolder = Console & { [PATCHED]?: Partial<Record<ConsoleMethod, unknown>> };\n\nfunction capture(method: ConsoleMethod, args: readonly unknown[]): void {\n try {\n const scope = current();\n if (!scope?.options.logs) return;\n\n const redact = scope.options.redact;\n let line = format(...args);\n const hit = sensitivePatternIn(line, redact.body);\n line = hit ? `[line withheld: mentions \"${hit}\"]` : truncate(line, redact.maxStringLength);\n\n scope.addLog(LEVEL_OF[method], line);\n } catch {\n // The passthrough below must survive anything that happens here.\n }\n}\n\n/**\n * Installs the console tap. Idempotent; called by `createReqray`.\n *\n * Whether a line is recorded is decided per request from `scope.options`, so\n * one global tap serves any number of runtimes.\n */\nexport function instrumentConsole(): void {\n const holder = console as ConsoleHolder;\n if (holder[PATCHED]) return;\n\n const originals: Partial<Record<ConsoleMethod, unknown>> = {};\n for (const method of METHODS) {\n const original = holder[method];\n if (typeof original !== 'function') continue;\n originals[method] = original;\n\n holder[method] = function reqrayConsole(this: unknown, ...args: unknown[]) {\n capture(method, args);\n return (original as (...inner: unknown[]) => unknown).apply(this, args);\n };\n }\n holder[PATCHED] = originals;\n}\n\n/** Restores the original console. Needed by tests. */\nexport function uninstrumentConsole(): void {\n const holder = console as ConsoleHolder;\n const originals = holder[PATCHED];\n if (!originals) return;\n\n for (const method of METHODS) {\n const original = originals[method];\n if (original) holder[method] = original as Console[ConsoleMethod];\n }\n delete holder[PATCHED];\n}\n","/**\n * What one request cost the process.\n *\n * The waterfall answers \"how long did it take\". It does not answer \"what did\n * it cost to run\", and the two come apart constantly: a request that waits\n * 800 ms on a database is cheap, and one that spends 80 ms hashing a password\n * is expensive. A list sorted by duration puts the first one on top and the\n * second one nowhere, which is the wrong way round for anyone asking what\n * their process is actually spending itself on.\n *\n * Everything here is measured at the edges of a request and costs about a\n * microsecond, so it is always on. What it cannot do is name the function\n * that burned the time — that needs the sampling profiler, which is a\n * decision rather than a setting.\n *\n * ## What is honest to report, and what is not\n *\n * `process.cpuUsage()` measures the *process*, so the delta across a\n * request's window belongs to the request only when nothing else was running\n * in it. That is why `overlap` travels with every reading: the number of\n * other requests that shared the window. At zero, the CPU figure is this\n * request's. Above it, the figure is the window's and the panel says so\n * rather than dividing by a guess.\n *\n * Retained memory is deliberately absent. There is no way in V8 to ask what a\n * request still holds, and a number invented for the column would be wrong in\n * exactly the cases somebody would act on it. What can be measured is the\n * garbage collector's time inside the window, which is what allocation\n * pressure actually costs the request that triggers it.\n */\n\nimport { type PerformanceEntry, PerformanceObserver } from 'node:perf_hooks';\nimport { warnOnce } from './logger.js';\nimport { globalSlot } from './state.js';\n\n/** A garbage collection, in the same clock spans are placed on. */\ninterface Pause {\n /** `performance.now()` when it started. */\n readonly at: number;\n readonly ms: number;\n}\n\n/**\n * How many recent collections are remembered.\n *\n * Only pauses inside a request's window are ever read, and a request outlives\n * at most a few hundred of them. The ring is what keeps an idle process from\n * accumulating a day of garbage-collection history nobody will ask about.\n */\nconst PAUSE_HISTORY = 512;\n\n/**\n * A collection shorter than this is not worth attributing.\n *\n * Minor collections run constantly and cost tens of microseconds; summing\n * every one of them would produce a figure made mostly of noise.\n */\nconst PAUSE_FLOOR_MS = 0.1;\n\ninterface Meter {\n /** Recent collections, oldest first, capped at {@link PAUSE_HISTORY}. */\n pauses: Pause[];\n /** Requests currently in flight. */\n active: number;\n /** Requests begun since the process started — a monotonic clock of arrivals. */\n begun: number;\n observer: PerformanceObserver | null;\n}\n\n/**\n * Process-wide, and shared across Reqray instances by design.\n *\n * Two Reqray instances in one process observe one garbage collector and one\n * CPU clock. Giving each its own observer would double the cost of watching\n * and still measure the same thing twice.\n */\nconst meter = globalSlot(\n 'cost.meter',\n (): Meter => ({ pauses: [], active: 0, begun: 0, observer: null }),\n);\n\n/**\n * Starts watching the collector.\n *\n * Never throws: on a runtime that does not report collections, every request\n * simply has nothing to say about garbage collection, which is what an\n * unmeasured thing looks like.\n */\nexport function startCostMeter(): void {\n const state = meter();\n if (state.observer) return;\n\n try {\n const observer = new PerformanceObserver((list) => {\n const { pauses } = meter();\n for (const entry of list.getEntries() as PerformanceEntry[]) {\n if (entry.duration < PAUSE_FLOOR_MS) continue;\n pauses.push({ at: entry.startTime, ms: entry.duration });\n }\n if (pauses.length > PAUSE_HISTORY) pauses.splice(0, pauses.length - PAUSE_HISTORY);\n });\n observer.observe({ type: 'gc' });\n state.observer = observer;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('cost.gc', `garbage collection is not being measured: ${reason}`);\n }\n}\n\n/** Stops watching. For tests and shutdown. */\nexport function stopCostMeter(): void {\n const state = meter();\n try {\n state.observer?.disconnect();\n } catch {\n // An observer that will not disconnect is not worth an exception.\n }\n state.observer = null;\n state.pauses = [];\n state.active = 0;\n state.begun = 0;\n}\n\n/** What is read at the start of a request and subtracted at the end. */\nexport interface CostMark {\n readonly cpu: NodeJS.CpuUsage;\n /** Requests already in flight when this one began. */\n readonly overlapping: number;\n /** Arrivals so far, so requests begun during this window can be counted. */\n readonly begun: number;\n}\n\n/**\n * Opens the measurement. Called once per request, on the hot path.\n *\n * About a microsecond, almost all of it `process.cpuUsage()`.\n */\nexport function markCost(): CostMark {\n const state = meter();\n const mark = { cpu: process.cpuUsage(), overlapping: state.active, begun: state.begun };\n state.active++;\n state.begun++;\n return mark;\n}\n\n/** What one request cost, as the panel reports it. */\nexport interface RequestCost {\n /** Processor time in the request's window, user and system, ms. */\n readonly cpuMs: number;\n /**\n * That time as a share of the wall clock. `1` is a request that spent its\n * whole life on a processor.\n *\n * Deliberately not capped. `process.cpuUsage()` counts every thread the\n * process has — the libuv pool doing filesystem, DNS, zlib and crypto work,\n * and any worker threads — so a request that fanned work out across cores\n * genuinely spends more processor time than wall time. Capping it at one\n * would turn the most interesting reading on the screen into the same\n * number as an ordinary busy request.\n */\n readonly cpuShare: number;\n /** Time the garbage collector took inside the window, ms. */\n readonly gcMs: number;\n /** Collections inside the window. */\n readonly collections: number;\n /**\n * Other requests that shared the window.\n *\n * Part of the honesty dial on `cpuMs`, and only part of it: it counts\n * requests, and the processor clock counts threads. A request can be alone\n * in the process and still show more processor time than wall time, because\n * the libuv pool was busy on its behalf — which is why `cpuShare` above one\n * is a reading in its own right rather than a contradiction of this field.\n */\n readonly overlap: number;\n}\n\n/**\n * Closes the measurement.\n *\n * Must be called synchronously when the response ends, for the same reason\n * the duration is: a reading taken a tick later has the tick in it.\n */\nexport function measureCost(mark: CostMark, startTime: number, durationMs: number): RequestCost {\n const state = meter();\n state.active = Math.max(0, state.active - 1);\n\n const spent = process.cpuUsage(mark.cpu);\n const cpuMs = (spent.user + spent.system) / 1000;\n\n const end = startTime + durationMs;\n let gcMs = 0;\n let collections = 0;\n for (const pause of state.pauses) {\n if (pause.at < startTime || pause.at > end) continue;\n gcMs += pause.ms;\n collections++;\n }\n\n return {\n cpuMs,\n // Uncapped on purpose; see the field. Drawing it is the client's problem,\n // and a client that clamps a bar is not the same as a measurement that\n // throws the excess away.\n cpuShare: durationMs > 0 ? cpuMs / durationMs : 0,\n gcMs,\n collections,\n // Those already running when this began, plus those that arrived while it\n // ran. An upper bound on distinct company, computed in constant time.\n overlap: mark.overlapping + (state.begun - mark.begun - 1),\n };\n}\n","/**\n * What the process was doing while a request was in flight.\n *\n * A route that got slower with no change to its span timings is not a slow\n * route; it is a process that could not get scheduled. That is invisible in a\n * waterfall — every span is individually fast, and the time is *between*\n * them — and it is the more common answer for a Node backend than anything\n * the database did.\n *\n * The measurement is deliberately of the process, never of the request. Under\n * concurrency the code that blocked the loop is usually somebody else's, and\n * a number that says \"this request burned 180 ms of CPU\" is wrong often\n * enough to make every other number on the screen suspect.\n */\n\nimport { monitorEventLoopDelay } from 'node:perf_hooks';\nimport { warnOnce } from './logger.js';\nimport type { HostState } from './types.js';\n\nexport interface HostMonitor {\n /**\n * The window in progress, or `null` when nothing has been measured yet.\n *\n * Read when a request finishes, so what it carries is the loop's behaviour\n * over the window the request ran in — at most a second of it.\n */\n read(): HostState | null;\n /** Stops sampling. The timer is unrefed, so this is for tests and shutdown. */\n stop(): void;\n}\n\n/**\n * How often the histogram is emptied.\n *\n * A window shorter than this stops being a distribution; a longer one stops\n * being about the request that reads it. A second is the compromise, and it\n * is why the panel never draws one request against these numbers: a 90 ms\n * request does not resolve against a one-second window.\n */\nconst WINDOW_MS = 1_000;\n\n/**\n * How often the histogram is actually asked, however often it is read.\n *\n * `mean` walks the histogram's buckets on every call and costs about eleven\n * microseconds — trivial once, and eleven milliseconds a second at a thousand\n * requests. The window it summarises is a second long, so a reading fifty\n * milliseconds old is the same reading; what a memo buys is that the cost\n * stops scaling with traffic.\n */\nconst READ_EVERY_MS = 50;\n\n/**\n * How finely libuv samples the loop.\n *\n * Ten milliseconds is the interval the histogram itself schedules at — fine\n * enough to catch a blocking parse, coarse enough that the monitor is not\n * itself the thing keeping the loop busy.\n */\nconst RESOLUTION_MS = 10;\n\n/**\n * A histogram reading, in milliseconds of *delay*.\n *\n * libuv records the whole interval between samples, so an idle loop at a\n * resolution of ten reads about eleven. Reporting that as \"the loop was\n * behind by 11 ms\" would put a number on every request that is wrong on all\n * of them — the baseline comes off, and what is left is the lateness.\n */\nconst delayMs = (nanoseconds: number): number =>\n Number.isFinite(nanoseconds) ? Math.max(0, nanoseconds / 1e6 - RESOLUTION_MS) : 0;\n\n/**\n * Starts watching the event loop.\n *\n * Never throws: on a runtime without the histogram the monitor reads `null`\n * for ever and every screen that shows loop delay simply has nothing to show,\n * which is what an unmeasured thing looks like.\n */\nexport function startHostMonitor(): HostMonitor {\n let histogram: ReturnType<typeof monitorEventLoopDelay> | null = null;\n try {\n histogram = monitorEventLoopDelay({ resolution: RESOLUTION_MS });\n histogram.enable();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('host.monitor', `event-loop delay is not being measured: ${reason}`);\n return { read: () => null, stop: () => {} };\n }\n\n // The window just closed, kept so that a reset cannot swallow what it\n // measured. Without it, a request that blocked the loop and finished a\n // moment after a reset reports nothing at all — which is exactly the\n // request the number exists for.\n let previous: HostState | null = null;\n let cached: HostState | null = null;\n let cachedAt = 0;\n\n // Emptied on a timer rather than on every read: a reset per request would\n // mean each request reports the delay since the previous one finished,\n // which under load is a window of microseconds and a number of zero.\n const timer = setInterval(() => {\n try {\n if (histogram && histogram.count > 0) {\n previous = { loopDelayMs: delayMs(histogram.mean), loopMaxMs: delayMs(histogram.max) };\n }\n histogram?.reset();\n cached = null;\n } catch {\n // A histogram that will not reset still reads; it just widens.\n }\n }, WINDOW_MS);\n // The monitor must never be the reason a process stays alive.\n timer.unref?.();\n\n return {\n read() {\n if (!histogram) return null;\n const now = Date.now();\n if (cached && now - cachedAt < READ_EVERY_MS) return cached;\n try {\n // The window in progress and the one before it, together: the worst\n // the loop was behind over the last second or two, which is the span\n // a request is honestly placed against. An empty window is not a\n // delay of zero — it is no measurement — so the closed window carries\n // the answer alone until the new one has something to say.\n const open =\n histogram.count > 0\n ? { loopDelayMs: delayMs(histogram.mean), loopMaxMs: delayMs(histogram.max) }\n : null;\n const closed = previous;\n if (!open && !closed) return null;\n\n cached = {\n loopDelayMs: open?.loopDelayMs ?? closed?.loopDelayMs ?? 0,\n loopMaxMs: Math.max(open?.loopMaxMs ?? 0, closed?.loopMaxMs ?? 0),\n };\n cachedAt = now;\n return cached;\n } catch {\n return null;\n }\n },\n\n stop() {\n clearInterval(timer);\n cached = null;\n previous = null;\n try {\n histogram?.disable();\n } catch {\n // Already gone.\n }\n histogram = null;\n },\n };\n}\n","/**\n * Request identifiers.\n *\n * Generated on the hot path for every request, hence a counter and string\n * concatenation instead of `crypto.randomUUID()`. The id has to be unique\n * across every process whose requests share a store, and short — the panel\n * displays it.\n */\n\nimport { randomBytes } from 'node:crypto';\n\nlet counter = 0;\n\n/**\n * Random per-process prefix: keeps ids apart across workers and restarts.\n *\n * Forty bits, drawn once. Twenty were not enough: a history on disk collects\n * a prefix per process start, and a few hundred restarts made a repeat likely\n * — after which the store dropped the newer request and opened the older one\n * in its place. Eight characters, so an id stays within the twelve the\n * terminal client gives it for the first million and a half requests.\n */\nconst prefix = randomBytes(5).readUIntBE(0, 5).toString(36).padStart(8, '0');\n\nexport function nextRequestId(): string {\n counter = (counter + 1) % 0xffffffff;\n return `${prefix}${counter.toString(36)}`;\n}\n","/**\n * The sampling profiler: which function burned the time.\n *\n * `slow_code` can find the stretch of a request nothing accounts for and say\n * what brackets it. It cannot say what ran inside, because nothing was\n * recorded there — that is what makes it a stretch. The answer to \"which line\n * is slow\" needs samples of the stack, and V8 has had them all along.\n *\n * Off unless asked for. Sampling costs a few microseconds per request, which\n * is nothing; what it is not is free of consequence, because a profile names\n * the application's functions and files. That is a decision somebody makes,\n * not a default somebody discovers.\n *\n * ## How a sample becomes a line of code\n *\n * V8 reports a leaf frame, which for `pbkdf2Sync` or `JSON.parse` is C++ and\n * has no line at all. The caller chain is walked to the first frame inside\n * the project — the same rule `callsite.ts` applies to stack traces, and for\n * the same reason: a file in `node_modules` is not somewhere anybody can go\n * and change something.\n *\n * ## What a sample cannot tell you\n *\n * Two limits, both V8's rather than ours, and both worth knowing before\n * reading a number off this screen.\n *\n * A node carries the line a function is *defined* on, never the line running:\n * Node's profile omits the per-line tick counts the protocol allows for. So\n * the address is a function, and what recovers the rest is naming the call\n * inside it — `pbkdf2Sync`, `processChunkSync` — which is what `inside` is\n * for.\n *\n * And an optimised function that has been inlined into its caller is not on\n * the stack at all: its samples are attributed to the caller. A small helper\n * called in a loop can therefore be reported as the function that calls it.\n * This is why the answer is a share of samples rather than a measurement of a\n * function, and why the hint says where to look rather than what to delete.\n *\n * ## What the clock does\n *\n * Sample times are microseconds on V8's own clock. They are anchored to\n * `performance.now()` at the moment sampling starts, which measures true to\n * within a few milliseconds: against windows of known busy and idle work,\n * 96.8% of samples inside a busy window read as busy and none of those inside\n * an idle one do. Every drain re-anchors, so the error cannot accumulate.\n */\n\nimport { Session } from 'node:inspector';\nimport { relative as pathRelative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { fileURLToPath } from 'node:url';\nimport { isProjectFrame } from './callsite.js';\nimport type { ResolvedStackOptions } from './config.js';\nimport { warnOnce } from './logger.js';\n\n/** One place in the code, with how much of the window it held. */\nexport interface HotFrame {\n /** The function's name, or `(anonymous)`. */\n readonly functionName: string;\n /** Path relative to the project root. */\n readonly relative: string;\n readonly line: number;\n /**\n * What the frame was calling when the sample was taken, or `null`.\n *\n * V8 gives a function's definition line, never the line executing, so the\n * address stops at the function. The callee is what recovers the rest of\n * the answer: `registerUser` is where to look, and `pbkdf2Sync` is what to\n * look for once there.\n */\n readonly inside: string | null;\n readonly samples: number;\n /** Share of the window's busy samples, 0..1. */\n readonly share: number;\n}\n\n/** What a stretch of a request was doing. */\nexport interface HotSpots {\n /** The project's own frames, heaviest first. */\n readonly frames: readonly HotFrame[];\n /**\n * Share of the window's samples that were on a processor, 0..1.\n *\n * The distinction `slow_code` cannot make on its own: near one, the stretch\n * is code running; near zero, it is the process waiting on something — I/O\n * with no instrumentation behind it, or a timer.\n */\n readonly busyShare: number;\n /** Samples in the window, busy and idle together. */\n readonly samples: number;\n}\n\n/** A frame the profiler has resolved, kept once and referred to by index. */\ninterface KnownFrame {\n readonly functionName: string;\n readonly relative: string;\n readonly line: number;\n}\n\n/** A sample, as the ring keeps it. */\ninterface Sample {\n /** `performance.now()` when V8 took it. */\n readonly at: number;\n /** Index into the frame table, or `-1` for a sample that was not running. */\n readonly frame: number;\n /**\n * Index into the callee table, or `-1`.\n *\n * Kept beside the frame rather than folded into it: a function calling\n * three different things is one hot spot, not three, and keying the frame\n * by its callee would split the share that says how hot it is.\n */\n readonly callee: number;\n}\n\n/**\n * How many samples are kept.\n *\n * Twenty seconds at a millisecond apart. A request is attributed the moment\n * it finishes, so the ring only has to outlive the gap between a request\n * ending and its record being built — the rest is slack for a process that\n * went quiet.\n */\nconst MAX_SAMPLES = 20_000;\n\n/** V8's names for samples that are not running anybody's code. */\nconst NOT_RUNNING = new Set(['(idle)', '(program)', '(root)']);\n\n/** How many frames a hot-spot answer names. */\nconst TOP_FRAMES = 5;\n\n/**\n * Running samples a window needs before its frames are worth showing.\n *\n * Three samples of somebody else's code in an idle stretch is not a hot spot;\n * it is the sampler catching whatever else the process was doing. Below this\n * the window still reports how busy it was — that much is honest at any\n * count — but names nothing.\n */\nconst MIN_BUSY_SAMPLES = 10;\n\nexport interface ProfilerOptions {\n readonly stack: ResolvedStackOptions;\n /** Microseconds between samples. */\n readonly intervalUs: number;\n}\n\nexport interface RequestProfiler {\n /**\n * What ran between two moments of `performance.now()`.\n *\n * `null` when the window holds no samples at all, which is not the same as\n * an idle window and must not be shown as one.\n */\n read(from: number, to: number): HotSpots | null;\n stop(): void;\n}\n\ninterface V8CallFrame {\n functionName: string;\n url: string;\n lineNumber: number;\n}\n\ninterface V8Node {\n id: number;\n callFrame: V8CallFrame;\n children?: number[];\n}\n\ninterface V8Profile {\n nodes: V8Node[];\n startTime: number;\n endTime: number;\n samples?: number[];\n timeDeltas?: number[];\n}\n\n/**\n * Starts sampling.\n *\n * Returns `null` when the inspector is unavailable — a runtime built without\n * it, or a process where the session cannot be opened. A panel then simply\n * has no hot spots to show, which is what an unmeasured thing looks like.\n */\nexport function startProfiler(options: ProfilerOptions): RequestProfiler | null {\n let session: Session;\n try {\n session = new Session();\n session.connect();\n } catch (error) {\n warnOnce('profiler.connect', `the sampling profiler is not available: ${reasonOf(error)}`);\n return null;\n }\n\n /** Every inspector call answers synchronously, which is why a drain can happen inline. */\n const post = <T>(method: string, params?: object): T | null => {\n let result: T | null = null;\n session.post(method, params as never, (error: Error | null, value: unknown) => {\n if (!error) result = value as T;\n });\n return result;\n };\n\n const samples: Sample[] = [];\n const frames: KnownFrame[] = [];\n const frameIds = new Map<string, number>();\n const callees: string[] = [];\n const calleeIds = new Map<string, number>();\n\n /** Callee names are few and repeat constantly; the table keeps them once. */\n function internCallee(name: string): number {\n const known = calleeIds.get(name);\n if (known !== undefined) return known;\n const id = callees.length;\n callees.push(name);\n calleeIds.set(name, id);\n return id;\n }\n let anchor = 0;\n let drainedAt = 0;\n let running = false;\n\n /** The frame table is shared across drains: the same function recurs constantly. */\n function intern(functionName: string, file: string, line: number): number {\n const key = `${functionName} ${file} ${line}`;\n const known = frameIds.get(key);\n if (known !== undefined) return known;\n const id = frames.length;\n frames.push({\n functionName: functionName || '(anonymous)',\n relative: pathRelative(options.stack.projectRoot, file).replaceAll('\\\\', '/'),\n line,\n });\n frameIds.set(key, id);\n return id;\n }\n\n /**\n * The nearest frame in the project, walking outwards from the leaf.\n *\n * A leaf in C++ — `pbkdf2Sync`, `JSON.parse`, a regexp — has no line of its\n * own, and the caller is what somebody can actually go and change.\n */\n function resolve(\n nodeId: number,\n nodes: Map<number, V8Node>,\n parents: Map<number, number>,\n ): { frame: number; callee: number } {\n // What the project frame was calling, kept as the walk passes it. The\n // leaf itself is usually C++ with a name like `run`; the frame directly\n // under the project's own is the one worth naming.\n let callee: string | null = null;\n for (let id: number | undefined = nodeId; id !== undefined; id = parents.get(id)) {\n const frame = nodes.get(id)?.callFrame;\n if (!frame) continue;\n const file = frame.url ? fileOf(frame.url) : null;\n if (!file || !isProjectFrame(file, options.stack)) {\n if (frame.functionName) callee = frame.functionName;\n continue;\n }\n // V8 counts lines from zero; every other number a reader sees is\n // one-based, including the callsites beside this on the same screen.\n return {\n frame: intern(frame.functionName, file, frame.lineNumber + 1),\n callee: callee === null ? -1 : internCallee(callee),\n };\n }\n return { frame: -1, callee: -1 };\n }\n\n function start(): void {\n post('Profiler.start');\n anchor = performance.now();\n running = true;\n }\n\n /** Empties V8's buffer into the ring, and starts a fresh one. */\n function drain(): void {\n if (!running) return;\n const stopped = post<{ profile: V8Profile }>('Profiler.stop');\n const profile = stopped?.profile;\n const anchoredAt = anchor;\n start();\n drainedAt = performance.now();\n if (!profile?.samples || !profile.timeDeltas) return;\n\n const nodes = new Map(profile.nodes.map((node) => [node.id, node]));\n const parents = new Map<number, number>();\n for (const node of profile.nodes) {\n for (const child of node.children ?? []) parents.set(child, node.id);\n }\n\n let at = profile.startTime;\n for (let i = 0; i < profile.samples.length; i++) {\n at += profile.timeDeltas[i] ?? 0;\n const nodeId = profile.samples[i];\n if (nodeId === undefined) continue;\n const name = nodes.get(nodeId)?.callFrame?.functionName ?? '';\n const resolved = NOT_RUNNING.has(name)\n ? { frame: -1, callee: -1 }\n : resolve(nodeId, nodes, parents);\n samples.push({ at: anchoredAt + (at - profile.startTime) / 1000, ...resolved });\n }\n if (samples.length > MAX_SAMPLES) samples.splice(0, samples.length - MAX_SAMPLES);\n }\n\n try {\n post('Profiler.enable');\n post('Profiler.setSamplingInterval', { interval: options.intervalUs });\n start();\n } catch (error) {\n warnOnce('profiler.start', `the sampling profiler did not start: ${reasonOf(error)}`);\n return null;\n }\n\n return {\n read(from: number, to: number): HotSpots | null {\n try {\n // A window reaching past the last drain cannot be in the ring yet:\n // its samples are still in V8's buffer, and answering from what is in\n // hand would name whichever function happened to be sampled early.\n // A wrong line of code is worse than half a millisecond.\n //\n // This is also the whole rate limit. Requests finishing together are\n // attributed one after another, so the first read drains and the rest\n // find their windows already covered.\n if (to > drainedAt) drain();\n\n let total = 0;\n let busy = 0;\n const counts = new Map<number, number>();\n /** Per frame, how often each callee was under it. */\n const inside = new Map<number, Map<number, number>>();\n for (const sample of samples) {\n if (sample.at < from || sample.at > to) continue;\n total++;\n if (sample.frame < 0) continue;\n busy++;\n counts.set(sample.frame, (counts.get(sample.frame) ?? 0) + 1);\n if (sample.callee < 0) continue;\n const seen = inside.get(sample.frame) ?? new Map<number, number>();\n seen.set(sample.callee, (seen.get(sample.callee) ?? 0) + 1);\n inside.set(sample.frame, seen);\n }\n if (total === 0) return null;\n // Busy enough to name something, or the answer is only how busy it was.\n if (busy < MIN_BUSY_SAMPLES) return { frames: [], busyShare: busy / total, samples: total };\n\n const hot = [...counts]\n .sort((a, b) => b[1] - a[1])\n .slice(0, TOP_FRAMES)\n .map(([id, count]) => {\n const frame = frames[id] as KnownFrame;\n // The call it was mostly in — one name, not a list: the point is\n // what to look for in the function, not an inventory of it.\n const top = [...(inside.get(id) ?? [])].sort((a, b) => b[1] - a[1])[0];\n return {\n ...frame,\n inside: top ? (callees[top[0]] ?? null) : null,\n samples: count,\n share: count / busy,\n };\n });\n\n return { frames: hot, busyShare: busy / total, samples: total };\n } catch (error) {\n warnOnce('profiler.read', `the sampling profiler stopped reporting: ${reasonOf(error)}`);\n return null;\n }\n },\n\n stop() {\n try {\n if (running) post('Profiler.stop');\n running = false;\n session.disconnect();\n } catch {\n // A session that will not close is not worth an exception on shutdown.\n }\n samples.length = 0;\n frames.length = 0;\n frameIds.clear();\n callees.length = 0;\n calleeIds.clear();\n },\n };\n}\n\n/** A frame's `url` is a file URL, a bare path, or something that is neither. */\nfunction fileOf(url: string): string | null {\n if (url.startsWith('file://')) {\n try {\n return fileURLToPath(url);\n } catch {\n return null;\n }\n }\n return url.startsWith('node:') || url === '' ? null : url;\n}\n\nfunction reasonOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Request replay from the panel.\n *\n * The request is replayed through the same application — with its full\n * middleware stack — so this is a real run, not a simulation. Hence the\n * restriction: a replay in production means a second card charge and a second\n * email, so outside development it is enabled only by an explicit flag.\n *\n * A replayed request must not show up in the shared list: it is marked by a\n * header, and its record goes not to the transport but to whoever started the\n * replay.\n */\n\nimport type { ReplayComparison, ReplayInput, ReplayMetrics } from '@reqray/protocol';\nimport { runOutsideScope } from '../context.js';\nimport { awaitReplay } from '../replay-waiters.js';\nimport { REPLAY_HEADER } from '../reqray.js';\nimport type { RecordedRequest } from '../types.js';\n\nexport type { ReplayComparison, ReplayInput, ReplayMetrics };\n\nfunction numberOrNull(value: string | undefined): number | null {\n if (value === undefined) return null;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/** Reduces a request record to the comparison metrics. */\nexport function metricsOf(request: RecordedRequest): ReplayMetrics {\n let sqlCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n }\n\n return {\n status: request.status,\n durationMs: request.durationMs,\n sqlCount,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n bytes: numberOrNull(request.responseHeaders['content-length']),\n etag: request.responseHeaders['etag'] ?? null,\n };\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null> {\n return new Promise<T | null>((resolve) => {\n const timer = setTimeout(() => resolve(null), ms);\n timer.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n () => {\n clearTimeout(timer);\n resolve(null);\n },\n );\n });\n}\n\nlet counter = 0;\n\nfunction nextReplayId(): string {\n counter = (counter + 1) % 0xffffff;\n return `r${counter.toString(36)}${Math.random().toString(36).slice(2, 8)}`;\n}\n\n/**\n * Runs the request again and returns a comparison against the original.\n *\n * @param origin the application's own address, e.g. `http://127.0.0.1:3000`.\n * @param recordTimeoutMs how long to wait for the replay's record before\n * returning a partial comparison.\n */\nexport async function runReplay(\n origin: string,\n input: ReplayInput,\n original: RecordedRequest,\n recordTimeoutMs = 2_000,\n): Promise<ReplayComparison> {\n const replayId = nextReplayId();\n\n let stopWaiting = (): void => {};\n const recorded = new Promise<RecordedRequest>((resolve) => {\n stopWaiting = awaitReplay(replayId, resolve);\n });\n\n const startedAt = performance.now();\n try {\n // Outside the scope: Reqray's own HTTP call must not become a span of the\n // request that opened the panel.\n const response = await runOutsideScope(() =>\n fetch(`${origin}${input.path}`, {\n method: input.method,\n headers: { ...input.headers, [REPLAY_HEADER]: replayId },\n ...(input.body === undefined ? {} : { body: input.body }),\n }),\n );\n\n const text = await response.text();\n const durationMs = performance.now() - startedAt;\n const record = await withTimeout(recorded, recordTimeoutMs);\n\n const replay: ReplayMetrics = record\n ? metricsOf(record)\n : {\n status: response.status,\n durationMs,\n sqlCount: 0,\n nPlusOne: false,\n bytes: Buffer.byteLength(text),\n etag: response.headers.get('etag'),\n };\n\n return { original: metricsOf(original), replay, partial: record === null };\n } finally {\n stopWaiting();\n }\n}\n","/**\n * Three charts for one endpoint, and nothing beyond them.\n *\n * Latency over time, the share that failed, and how often it was called —\n * enough to see \"it got slower at 14:20, after the deploy\" and to stop there.\n * Not a dashboard builder, not alerting, not aggregates over arbitrary\n * dimensions: that is the line where this becomes a worse Datadog, and it is\n * written down in the plan so that nobody crosses it by inertia.\n *\n * The bucketing is the strip's own, so a chart and the strip above it cannot\n * disagree about when something happened.\n */\n\nimport type { RouteSeries, SeriesBucket } from '@reqray/protocol';\nimport type { DurationSample } from './api.js';\nimport { percentile } from './routes.js';\nimport { bucketIndex } from './timeline.js';\n\nexport type { RouteSeries, SeriesBucket };\n\n/** Columns a route's charts are drawn with, unless asked otherwise. */\nexport const SERIES_BUCKETS = 48;\n\n/**\n * Calls a column should hold before it is worth drawing as one.\n *\n * A percentile over three samples is the slowest of three, which is why a\n * chart drawn at full resolution over a quiet route shows a p95 and a p99\n * that are the same number and jump about together. Fewer, fuller columns say\n * less about *when* and much more about *what*, and the resolution should\n * follow how much there is to draw rather than the width of the box.\n */\nconst MIN_PER_COLUMN = 6;\n\n/** Below this the chart stops being a shape and becomes a bar. */\nconst MIN_BUCKETS = 12;\n\n/**\n * Buckets one route's calls.\n *\n * `null` when the store holds nothing for it: a chart with invented ends\n * would be a claim about a stretch of time nobody recorded.\n */\nexport function routeSeries(\n method: string,\n route: string,\n samples: readonly DurationSample[],\n bucketCount: number = SERIES_BUCKETS,\n): RouteSeries | null {\n if (samples.length === 0 || bucketCount <= 0) return null;\n\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n for (const sample of samples) {\n if (sample.startedAt < from) from = sample.startedAt;\n if (sample.startedAt > to) to = sample.startedAt;\n }\n\n // As many columns as the traffic supports, and never more than asked for.\n const count = Math.max(\n Math.min(MIN_BUCKETS, bucketCount),\n Math.min(bucketCount, Math.ceil(samples.length / MIN_PER_COLUMN)),\n );\n\n const columns: Array<{ durations: number[]; errors: number }> = Array.from(\n { length: count },\n () => ({ durations: [], errors: 0 }),\n );\n\n for (const sample of samples) {\n const column = columns[bucketIndex(sample.startedAt, from, to, count)];\n if (!column) continue;\n column.durations.push(sample.durationMs);\n if (sample.hasError) column.errors++;\n }\n\n // A single call spans no time; a second keeps throughput finite and honest.\n const span = Math.max(1_000, to - from);\n const bucketMs = span / count;\n\n return {\n method,\n route,\n from,\n to,\n bucketMs,\n calls: samples.length,\n buckets: columns.map((column, index) => {\n const sorted = column.durations.sort((a, b) => a - b);\n return {\n at: from + index * bucketMs,\n calls: sorted.length,\n errors: column.errors,\n p50: sorted.length > 0 ? percentile(sorted, 0.5) : 0,\n p95: sorted.length > 0 ? percentile(sorted, 0.95) : 0,\n p99: sorted.length > 0 ? percentile(sorted, 0.99) : 0,\n };\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ACuB9D,IAAM,YAAY;AASlB,IAAM,YAAY;AAUlB,IAAM,mBAAmB;AASzB,IAAM,gBAAgB;AASf,SAAS,UACd,QACA,SACA,QACgB;AAChB,QAAM,SAAS,IAAI,IAAI,QAAQ,IAAI,CAAC,UAAU,CAAC,GAAG,MAAM,MAAM,IAAI,MAAM,KAAK,IAAI,KAAK,CAAC,CAAC;AACxF,QAAM,WAAW,KAAK,IAAI,GAAG,OAAO,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,SAAS,WAAW,QAAQ,OAAO,SAAS;AAAA,QACjE,SACE,QAAQ,WAAW,OAAO,QAAQ,YAAY,WACzC,QAAQ,UACT,CAAC;AAAA,QACP,MAAM,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO;AAAA,MAC1D;AAEA,eAAS,UAAU,KAAK,MAAM,UAAUH,UAAS,OAAO,GAAG,OAAO,QAAQ,CAAC;AAAA,IAC7E,SAAS,OAAO;AACd,YAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACpE,eAAS,gBAAgB,kBAAkB,MAAM,EAAE;AACnD,eAAS,UAAU,KAAK,EAAE,OAAO,kBAAkB,MAAM,GAAG,CAAC;AAAA,IAC/D;AAAA,EACF,GAAG;AACL;","names":["import_node_fs","import_node_path","cached","cache","cached","current","run","SEVERITY_WARN_MS","run","current","SEVERITY_CRITICAL_MS","severityFor","HINT","CACHE_LIMIT","fingerprints","cached","SEVERITY_CRITICAL_MS","SEVERITY_WARN_MS","severityFor","evaluate","run","ms","hintFor","endOf","SEVERITY_CRITICAL_MS","cache","CACHE_LIMIT","resolve","cached","import_node_path","CACHE_LIMIT","pathRelative","group","resolve","bucketize","current","MIN_RATIO","import_node_child_process","import_node_path","sequence","resolve","import_node_path","import_node_perf_hooks","import_node_crypto","import_node_path","import_node_perf_hooks","import_node_url","withTimeout","resolve","MIN_PER_COLUMN","size","originOf","report","page","current"]}
|
|
1
|
+
{"version":3,"sources":["../../src/panel/index.ts","../../../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.26_supports-color@7.2.0_typescript@6.0.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js","../../src/panel/activity.ts","../../src/panel/api.ts","../../src/state.ts","../../src/logger.ts","../../src/detectors/duplicates.ts","../../src/weight.ts","../../src/detectors/heavy-response.ts","../../src/sql.ts","../../src/detectors/runs.ts","../../src/detectors/n-plus-one.ts","../../src/timing.ts","../../src/detectors/pool-wait.ts","../../src/http-fingerprint.ts","../../src/detectors/sequential-http.ts","../../src/detectors/slow-budget.ts","../../src/detectors/slow-code.ts","../../src/detectors/transactions.ts","../../src/detectors/transaction-hold.ts","../../src/detectors/registry.ts","../../src/detectors/index.ts","../../src/panel.ts","../../src/panel/findings.ts","../../src/panel/routes.ts","../../src/panel/baseline.ts","../../src/panel/blame.ts","../../src/panel/exceptions.ts","../../src/callsite.ts","../../src/context.ts","../../src/explain-targets.ts","../../src/panel/explain.ts","../../src/panel/export.ts","../../src/panel/filters.ts","../../src/panel/timeline.ts","../../src/panel/history.ts","../../src/panel/paging.ts","../../src/panel/page-from-list.ts","../../src/panel/pressure.ts","../../src/panel/project.ts","../../src/diagnostics.ts","../../src/pools.ts","../../src/replay-waiters.ts","../../src/reqray.ts","../../src/console-capture.ts","../../src/cost.ts","../../src/host.ts","../../src/ids.ts","../../src/profiler.ts","../../src/panel/replay.ts","../../src/panel/series.ts"],"sourcesContent":["/**\n * `@reqray/core/panel` — reading back what was recorded.\n *\n * A separate entry point from `@reqray/core` on purpose. The recording side\n * runs inside somebody's application on the hot path and loads nothing it does\n * not need; this side spawns `git`, serves static files, opens sockets and\n * calls back into the application to replay a request. Joined in one barrel,\n * an instrumentation that only wants to time a query linked the HAR exporter\n * and the blame subprocess runner along with it.\n *\n * Nothing here is imported by the recording path — the split is a fact about\n * the code, not a convention this file asks anyone to keep.\n */\n\nexport {\n type ActivityReport,\n type Outlier,\n type RouteWindow,\n whatRanAt,\n} from './activity.js';\nexport {\n createPanelHandler,\n type DurationSample,\n type PageQuery,\n type PanelHandler,\n type PanelHandlerInit,\n type PanelSource,\n panelSourceFor,\n parseFilter,\n type RequestPage,\n type RequestRow,\n toRow,\n} from './api.js';\nexport { type BaselineQuery, baselineFor } from './baseline.js';\nexport { type BlameLine, blameLine, parsePorcelain } from './blame.js';\nexport {\n type ExceptionFrame,\n type ExceptionGroup,\n groupExceptions,\n} from './exceptions.js';\nexport {\n analyzePlan,\n ExplainError,\n type ExplainNote,\n type ExplainPlanNode,\n type ExplainResult,\n runExplain,\n} from './explain.js';\nexport { toCurlScript, toHar } from './export.js';\nexport {\n filterRequests,\n type RequestFilter,\n type RequestSummary,\n summarize,\n} from './filters.js';\nexport {\n type FindingSample,\n type FindingSamples,\n type FindingsQuery,\n findingSamplesOf,\n flagWithMutes,\n patternKey,\n patternsOf,\n} from './findings.js';\nexport {\n columnsFor,\n type HistoryOptions,\n type HistoryQuery,\n type HistorySample,\n type HistorySamples,\n historyOf,\n historySampleOf,\n SERIES_COLUMNS,\n totalsOf,\n} from './history.js';\nexport { type PageContext, pageFromList } from './page-from-list.js';\nexport {\n type Cursor,\n decodeCursor,\n encodeCursor,\n isAfterCursor,\n} from './paging.js';\nexport { pressureFor } from './pressure.js';\nexport {\n type GitHead,\n type ProjectApp,\n type ProjectReport,\n type ProjectRuntime,\n type ProjectStorage,\n projectReport,\n storageOf,\n} from './project.js';\nexport {\n metricsOf,\n type ReplayComparison,\n type ReplayInput,\n type ReplayMetrics,\n runReplay,\n} from './replay.js';\nexport {\n normalizeRoute,\n percentile,\n type RouteFinding,\n type RouteStats,\n type RoutesReport,\n routeStats,\n TREND_BUCKETS,\n} from './routes.js';\nexport {\n type RouteSeries,\n routeSeries,\n SERIES_BUCKETS,\n type SeriesBucket,\n} from './series.js';\nexport {\n bucketIndex,\n buildTimeline,\n TIMELINE_BUCKETS,\n type TimelineBucket,\n type TimelineReport,\n type TimePoint,\n} from './timeline.js';\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/**\n * What ran here.\n *\n * A chart nobody can click is decoration. Clicking a moment on one should\n * answer the only question worth asking of it — what was different then —\n * and the answer has to be ranked by *how far each route strayed from its own\n * behaviour*, not by how much traffic it had. Ranked by volume, the busiest\n * endpoint tops every list and the moment explains nothing.\n *\n * Every route is compared against itself over the rest of the window, so a\n * spike does not inflate the baseline it is being measured against. When\n * nothing stands out, the answer is that nothing did: whatever moved the\n * chart came from garbage collection, a neighbour on the box, or the host —\n * and a list of ordinary routes presented as an explanation is worse than a\n * sentence admitting there is none.\n */\n\nimport type { ActivityReport, Outlier } from '@reqray/protocol';\n\nexport type { ActivityReport, Outlier };\n\n/** One route's traffic over a stretch of time, as the store groups it. */\nexport interface RouteWindow {\n readonly method: string;\n readonly route: string;\n readonly calls: number;\n /** Mean duration over those calls, ms. */\n readonly avgMs: number;\n}\n\n/**\n * Calls a route needs in the moment before it can be called unusual.\n *\n * Two calls that happened to be slow are two calls that happened to be slow.\n */\nconst MIN_CALLS = 3;\n\n/**\n * How far from its own baseline a route has to be.\n *\n * Half again, on either rate or duration. Below that the difference is inside\n * the noise of a handful of calls, and a list that includes it is a list of\n * everything that ran.\n */\nconst MIN_RATIO = 1.5;\n\n/**\n * How many calls above its usual count a route has to be.\n *\n * A ratio alone is not enough at low rates: a route called twice a minute\n * that happens to be called three times has run at 1.5× its rate and nothing\n * has happened. Three extra calls is the smallest excess that is a count\n * rather than a rounding of one.\n */\nconst MIN_EXCESS_CALLS = 3;\n\n/**\n * How much slower, in milliseconds, before a ratio means anything.\n *\n * A route that goes from 0.2 ms to 0.4 ms has doubled and nobody has noticed.\n * Five milliseconds is the smallest difference somebody could experience, and\n * below it a ratio is reporting the jitter of the clock.\n */\nconst MIN_EXCESS_MS = 5;\n\n/**\n * What stood out in one stretch of time.\n *\n * @param moment routes grouped over the clicked stretch.\n * @param overall the same, over the whole window the chart covers — the\n * moment included, and subtracted here so a spike is not its own baseline.\n */\nexport function whatRanAt(\n moment: readonly RouteWindow[],\n overall: readonly RouteWindow[],\n window: { from: number; to: number; overallMs: number },\n): ActivityReport {\n const before = new Map(overall.map((entry) => [`${entry.method} ${entry.route}`, entry]));\n const momentMs = Math.max(1, window.to - window.from);\n // The rest of the window: what the route usually does, with the moment\n // taken out of it. Never negative, and never zero as a divisor.\n const restMs = Math.max(1, window.overallMs - momentMs);\n\n // How the moment compares as a whole. Bursty traffic — a demo restarting, a\n // cron waking up, a deploy draining a queue — lifts every route at once, and\n // without this every route is an outlier in every burst.\n const momentCalls = moment.reduce((total, entry) => total + entry.calls, 0);\n const overallCalls = overall.reduce((total, entry) => total + entry.calls, 0);\n const restOverall = Math.max(0, overallCalls - momentCalls);\n const overallRatio = restOverall > 0 ? momentCalls / momentMs / (restOverall / restMs) : null;\n\n /**\n * How much busier the moment was for everything *except* this route.\n *\n * Each route is judged against how the rest of the traffic moved, not\n * against the total it is part of — otherwise a route that is the only\n * thing running compares against itself and can never stand out, which is\n * exactly the case where it obviously does.\n */\n const withoutRatio = (entry: RouteWindow, restCalls: number): number | null => {\n const otherMoment = momentCalls - entry.calls;\n const otherRest = restOverall - restCalls;\n if (otherMoment <= 0 || otherRest <= 0) return null;\n return otherMoment / momentMs / (otherRest / restMs);\n };\n\n const outliers: Outlier[] = [];\n for (const entry of moment) {\n if (entry.calls < MIN_CALLS) continue;\n\n const all = before.get(`${entry.method} ${entry.route}`);\n const restCalls = Math.max(0, (all?.calls ?? 0) - entry.calls);\n\n // Never ran outside this moment: not a ratio, a fact.\n if (restCalls === 0) {\n outliers.push({\n method: entry.method,\n route: entry.route,\n calls: entry.calls,\n avgMs: entry.avgMs,\n rateRatio: null,\n slowerRatio: null,\n firstSeen: true,\n });\n continue;\n }\n\n const rate = restCalls / restMs;\n const rateRatio = entry.calls / momentMs / rate;\n // What this moment would have held if the route had simply grown with\n // everything else. The excess over *that* is the part worth reporting,\n // and at low rates it is what tells a burst from a coin toss.\n const others = withoutRatio(entry, restCalls);\n const expected = rate * momentMs * (others ?? 1);\n // The route against how the rest of the traffic moved: one means it rose\n // exactly as much as everything around it, which is not an answer to\n // \"what was different here\".\n const shareRatio = others === null ? rateRatio : rateRatio / others;\n // The mean over the rest, recovered from the totals: the store grouped\n // once, and asking it twice for overlapping ranges would cost a scan to\n // learn something arithmetic already knows.\n const restAvg =\n all && all.calls > 0\n ? Math.max(0, (all.avgMs * all.calls - entry.avgMs * entry.calls) / restCalls)\n : 0;\n const slowerRatio = restAvg > 0 ? entry.avgMs / restAvg : null;\n\n const busier = shareRatio >= MIN_RATIO && entry.calls - expected >= MIN_EXCESS_CALLS;\n const slower =\n slowerRatio !== null && slowerRatio >= MIN_RATIO && entry.avgMs - restAvg >= MIN_EXCESS_MS;\n if (!busier && !slower) continue;\n\n outliers.push({\n method: entry.method,\n route: entry.route,\n calls: entry.calls,\n avgMs: entry.avgMs,\n rateRatio,\n slowerRatio,\n firstSeen: false,\n });\n }\n\n const strength = (outlier: Outlier): number =>\n outlier.firstSeen\n ? Number.POSITIVE_INFINITY\n : Math.max(outlier.rateRatio ?? 0, outlier.slowerRatio ?? 0);\n\n return {\n from: window.from,\n to: window.to,\n calls: momentCalls,\n rateRatio: overallRatio,\n outliers: outliers.sort((a, b) => strength(b) - strength(a)),\n };\n}\n","/**\n * Panel HTTP API.\n *\n * The handler is written against raw `IncomingMessage`/`ServerResponse`, so\n * Express and Fastify mount the very same code — no need to duplicate the API\n * in each adapter.\n */\n\nimport { createReadStream, statSync } from 'node:fs';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport { extname, resolve, sep } from 'node:path';\nimport type {\n FiledPatternState,\n PanelMeta,\n RequestRow,\n RequestSort,\n RequestSummary,\n SeriesMetric,\n StoredPatternState,\n} from '@reqray/protocol';\nimport type { ResolvedOptions } from '../config.js';\nimport { detectorSettings } from '../detectors/index.js';\nimport { warnOnce } from '../logger.js';\nimport { isPanelRequestAllowed } from '../panel.js';\nimport type { RetentionLimits } from '../retention.js';\nimport { ensureTiming } from '../timing.js';\nimport type { RecordedRequest } from '../types.js';\nimport { type RouteWindow, whatRanAt } from './activity.js';\nimport { type BaselineQuery, baselineFor } from './baseline.js';\nimport { blameLine } from './blame.js';\nimport { groupExceptions } from './exceptions.js';\nimport { ExplainError, runExplain } from './explain.js';\nimport { toCurlScript, toHar } from './export.js';\nimport { filterRequests, type RequestFilter } from './filters.js';\nimport { type FindingSamples, type FindingsQuery, flagWithMutes, patternsOf } from './findings.js';\nimport { type HistoryQuery, type HistorySamples, historyOf, SERIES_COLUMNS } from './history.js';\nimport { pageFromList } from './page-from-list.js';\nimport { pressureFor } from './pressure.js';\nimport { logOf, projectReport, retentionOf } from './project.js';\nimport { type ReplayInput, runReplay } from './replay.js';\nimport { normalizeRoute, routeStats } from './routes.js';\nimport { routeSeries, SERIES_BUCKETS } from './series.js';\nimport { buildTimeline, TIMELINE_BUCKETS, type TimePoint } from './timeline.js';\n\nexport type { RequestRow } from '@reqray/protocol';\n\n/** One page of the request list, newest first. */\nexport interface RequestPage {\n readonly rows: readonly RequestRow[];\n /** Feed back as `cursor` to get the next, older page. `null` — the end. */\n readonly nextCursor: string | null;\n /** Numbers for the status bar, over the whole store rather than the page. */\n readonly summary: RequestSummary;\n}\n\n/** What the panel asks a store for when it wants a page. */\nexport interface PageQuery {\n readonly filter: RequestFilter;\n readonly limit: number;\n /** Where to continue from. Absent or `null` — start at the beginning. */\n readonly cursor?: string | null | undefined;\n /**\n * What \"the beginning\" means: the newest requests, or the slowest.\n *\n * Defaults to `recent`. Sorting is the store's job rather than the\n * caller's — \"the slowest request\" over a history on disk cannot be found\n * by reading a page of it and comparing.\n */\n readonly sort?: RequestSort | undefined;\n}\n\n/** Where the panel gets its data. Implemented by the transport store. */\nexport interface PanelSource {\n /** Requests from newest to oldest. */\n list(): readonly RecordedRequest[];\n get(id: string): RecordedRequest | undefined;\n clear(): void;\n subscribe(listener: (request: RecordedRequest) => void): () => void;\n /**\n * Keeps a request past its turn in the ring buffer, or lets it go again.\n *\n * Optional: a store without pinning is still a valid source, and the panel\n * answers the pin route with an explanation instead of pretending.\n *\n * @returns `false` when the request is gone or the pin limit is reached.\n */\n pin?(id: string, pinned: boolean): boolean;\n /** Ids currently pinned. */\n pinned?(): readonly string[];\n /**\n * When, how long, and whether it failed — for every request the store\n * holds.\n *\n * Optional, and cheap on purpose: three numbers per request, so the strip\n * above the list can span the whole history instead of the page that\n * happens to be loaded. A source without it leaves the panel to draw from\n * the rows it has, which is what it always did.\n */\n timeSeries?(): readonly TimePoint[];\n /**\n * One page of the list, filtered and cut by the store itself.\n *\n * Optional, and the difference between a buffer and a history: reading\n * everything into memory to filter it is what an in-memory ring can afford\n * and a store on disk cannot. A source without this method is served by\n * `list()`, whole.\n */\n page?(query: PageQuery): RequestPage;\n /**\n * Durations of other calls of one route.\n *\n * Optional, and asked for rather than derived from `list()`: judging one\n * call against its route means reading that route's whole history, which a\n * ring buffer can afford to scan and a store on disk should answer with a\n * query. A source without it leaves the detail page with no verdict, which\n * is better than a verdict drawn from the last page that happened to load.\n */\n durations?(query: BaselineQuery): readonly DurationSample[];\n /**\n * Traffic grouped by route over a stretch of time.\n *\n * Optional, and an aggregate rather than a page: answering \"what ran in\n * this moment\" by reading the moment's requests would mean loading a busy\n * minute of them to count four numbers per route.\n */\n counts?(query: { from: number; to: number }): readonly RouteWindow[];\n /**\n * A period's requests, a handful of numbers each.\n *\n * Optional, and the one method that reads a *stretch* rather than a page or\n * a route: the history screen asks what a week did, and answering that from\n * `list()` would mean holding a week of payloads in memory to look at ten\n * fields in each. A store must bound what it reads and say when it stopped\n * — a truncated total presented as a complete one is worse than no screen.\n */\n history?(query: HistoryQuery): HistorySamples;\n /**\n * Finding occurrences over a stretch of time, one row each.\n *\n * Optional, and rare rows on purpose: requests with findings are a small\n * minority, so a store answers this from them alone instead of reading the\n * window. A source without it leaves the findings tab explaining itself\n * rather than empty.\n */\n findings?(query: FindingsQuery): FindingSamples;\n /**\n * The reader's own bookkeeping per pattern: `ack` or `muted`.\n *\n * Patterns in neither state are `new` and are simply absent. A store that\n * persists (SQLite) keeps these across restarts; the in-memory ring keeps\n * them exactly as long as it keeps the requests they are about.\n */\n findingStates?(): ReadonlyMap<string, FiledPatternState>;\n /** Remembers a state; `new` forgets the pattern. */\n setFindingState?(id: string, state: StoredPatternState): void;\n}\n\n/**\n * One call of a route, as the store hands it over.\n *\n * Four numbers rather than a record: judging a call against its route, or\n * drawing the route's last hour, means reading every call of it, and parsing\n * a few thousand JSON documents to look at one field in each is how a page\n * becomes slow.\n */\nexport interface DurationSample {\n readonly durationMs: number;\n /** Epoch ms — what the window the samples cover is measured from. */\n readonly startedAt: number;\n /** Threw, or answered 5xx — what the error-rate chart counts. */\n readonly hasError: boolean;\n /**\n * Mean event-loop delay while it ran, or `null` when nothing measured it.\n *\n * What splits a route's calls into \"the host was fine\" and \"the host was\n * struggling\" — the comparison that says whether the process was to blame.\n */\n readonly loopDelayMs: number | null;\n}\n\n/** Everything the panel handler needs to serve a request. */\nexport interface PanelHandlerInit {\n readonly source: PanelSource;\n readonly options: ResolvedOptions;\n /**\n * Directory with the built dashboard.\n *\n * Left out when `@reqray/dashboard` is not installed: the API keeps working\n * and the UI route answers with an explanation instead of a blank page.\n */\n readonly assetsDir?: string | undefined;\n}\n\n/**\n * Panel request handler.\n *\n * @returns `true` if the request belonged to the panel and has been handled.\n * `false` means it is an ordinary application request and must be passed on.\n */\nexport type PanelHandler = (request: IncomingMessage, response: ServerResponse) => boolean;\n\n/**\n * The transport the panel can read from, if there is one.\n *\n * A transport is a store when it can answer the four questions the panel\n * asks. An HTTP transport to an external collector cannot — the panel then\n * runs in the collector. Neither can a log file, which is write-only by\n * design, so a fan-out is searched through rather than tested as a whole.\n *\n * Warns when the panel is configured and nothing can serve it: a panel that\n * quietly does not mount is a 404 nobody can explain.\n */\nexport function panelSourceFor(transport: unknown, options: ResolvedOptions): PanelSource | null {\n const direct = asPanelSource(transport);\n if (direct) return direct;\n\n const members = (transport as { transports?: readonly unknown[] } | null)?.transports;\n if (Array.isArray(members)) {\n for (const member of members) {\n const found = asPanelSource(member);\n if (found) return found;\n }\n }\n\n if (options.enabled && options.panel) {\n const name = (transport as { name?: unknown } | null)?.name;\n warnOnce(\n 'panel.source',\n `the panel is not mounted: ${typeof name === 'string' ? name : 'this transport'} keeps no requests to show. ` +\n 'A store — @reqray/store-memory or @reqray/store-sqlite — has to be among the transports.',\n );\n }\n return null;\n}\n\n/** Whether a transport can answer what the panel asks of a store. */\nfunction asPanelSource(transport: unknown): PanelSource | null {\n const candidate = transport as Partial<PanelSource> | null;\n if (!candidate) return null;\n const complete =\n typeof candidate.list === 'function' &&\n typeof candidate.get === 'function' &&\n typeof candidate.clear === 'function' &&\n typeof candidate.subscribe === 'function';\n return complete ? (candidate as PanelSource) : null;\n}\n\n/**\n * Projects a record into a list row.\n *\n * The whole list is served on every panel open, and full records with spans\n * and bodies would weigh megabytes. Details come from a separate request by\n * identifier.\n */\nexport function toRow(request: RecordedRequest, pinned = false): RequestRow {\n let sqlCount = 0;\n let httpCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n else if (span.kind === 'http') httpCount++;\n }\n\n return {\n id: request.id,\n method: request.method,\n path: request.path,\n query: request.query,\n route: normalizeRoute(request.path),\n status: request.status,\n durationMs: request.durationMs,\n startedAt: request.startedAt,\n sqlCount,\n httpCount,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n findingCount: request.findings.length,\n flag: [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null,\n hasError: request.error !== null || request.status >= 500,\n // Straight through, including the nulls: a row from a store written\n // before cost was measured has no cost, and inventing a zero would put a\n // cheap-looking request next to genuinely cheap ones.\n cpuMs: request.cost?.cpuMs ?? null,\n cpuShare: request.cost?.cpuShare ?? null,\n pinned,\n test: request.test,\n };\n}\n\n/** A file the browser saves rather than renders. */\nfunction sendDownload(\n response: ServerResponse,\n filename: string,\n contentType: string,\n body: string,\n): void {\n response.writeHead(200, {\n 'content-type': contentType,\n 'content-disposition': `attachment; filename=\"${filename}\"`,\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\nfunction sendJson(response: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload);\n response.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n });\n response.end(body);\n}\n\n/**\n * How many rows one page may hold.\n *\n * Capped rather than trusted: the parameter comes from a browser, and an\n * unbounded page defeats the point of having pages at all.\n */\nconst DEFAULT_PAGE_LIMIT = 100;\nconst MAX_PAGE_LIMIT = 500;\n\nfunction pageLimit(params: URLSearchParams): number {\n const asked = Number(params.get('limit'));\n if (!Number.isFinite(asked) || asked <= 0) return DEFAULT_PAGE_LIMIT;\n return Math.min(Math.floor(asked), MAX_PAGE_LIMIT);\n}\n\n/** A positive finite number from a query parameter, or `undefined`. */\nfunction positive(raw: string | null): number | undefined {\n const value = Number(raw);\n return Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\nconst HOUR_MS = 60 * 60 * 1000;\n\n/** Every metric the history screen may ask for. Nothing outside this list. */\nconst METRICS: readonly SeriesMetric[] = [\n 'p50',\n 'p95',\n 'p99',\n 'throughput',\n 'errorRate',\n 'sqlPerRequest',\n 'httpPerRequest',\n 'bytes',\n 'loopDelay',\n 'findingsPerRequest',\n];\n\n/**\n * Which metrics to draw.\n *\n * Two at most: a third line is a dashboard, and a chart nobody can read is\n * not a better answer than a chart with one line on it.\n */\nfunction parseMetrics(params: URLSearchParams): SeriesMetric[] {\n const asked = params\n .getAll('metric')\n .flatMap((value) => value.split(','))\n .map((value) => value.trim())\n .filter((value): value is SeriesMetric => (METRICS as readonly string[]).includes(value));\n\n const unique = [...new Set(asked)].slice(0, 2);\n return unique.length > 0 ? unique : ['p95'];\n}\n\n/**\n * The query string, as the filter the store applies.\n *\n * Exported so the panel's client-side filter is checked against this and not\n * against a second reading of the same parameters.\n */\nexport function parseFilter(params: URLSearchParams): RequestFilter {\n const methods = params\n .getAll('method')\n .flatMap((value) => value.split(','))\n .filter(Boolean);\n const statusClasses = params\n .getAll('status')\n .flatMap((value) => value.split(','))\n .map((value) => Number.parseInt(value, 10))\n .filter((value) => Number.isFinite(value));\n\n const minDuration = Number(params.get('minDurationMs'));\n const minSql = Number(params.get('minSql'));\n const status = Number(params.get('statusExact'));\n const flagged = params\n .getAll('flagged')\n .flatMap((value) => value.split(','))\n .filter(Boolean);\n const route = params.get('route');\n const routeMethod = params.get('routeMethod');\n const from = Number(params.get('from'));\n const to = Number(params.get('to'));\n\n return {\n from: Number.isFinite(from) && from > 0 ? from : undefined,\n to: Number.isFinite(to) && to > 0 ? to : undefined,\n query: params.get('q') ?? undefined,\n methods,\n statusClasses,\n minDurationMs: Number.isFinite(minDuration) && minDuration > 0 ? minDuration : undefined,\n onlyFindings: params.get('findings') === '1',\n onlyNPlusOne: params.get('nplus') === '1',\n onlyTests: params.get('tests') === '1',\n onlyErrors: params.get('errors') === '1',\n route: route && routeMethod ? { method: routeMethod, route } : undefined,\n path: params.get('path') ?? undefined,\n status: Number.isFinite(status) && status > 0 ? status : undefined,\n minSql: Number.isFinite(minSql) && minSql > 0 ? minSql : undefined,\n flagged: flagged.length > 0 ? flagged : undefined,\n test: params.get('test') ?? undefined,\n };\n}\n\n/**\n * Reads the body of a panel request.\n *\n * An already-parsed body is taken first: the application almost certainly has\n * a json parser (`express.json()`) that consumed the stream before us —\n * reading the socket a second time is pointless, it is already empty.\n */\nasync function readBody(request: IncomingMessage, limitBytes = 1_000_000): Promise<unknown> {\n const parsed = (request as IncomingMessage & { body?: unknown }).body;\n if (parsed !== undefined && parsed !== null) {\n return typeof parsed === 'string' ? JSON.parse(parsed) : parsed;\n }\n\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n const buffer = chunk as Buffer;\n size += buffer.length;\n if (size > limitBytes) throw new Error('request body too large');\n chunks.push(buffer);\n }\n const raw = Buffer.concat(chunks).toString('utf8');\n return raw ? JSON.parse(raw) : {};\n}\n\nconst MIME_TYPES: Readonly<Record<string, string>> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.woff2': 'font/woff2',\n '.ico': 'image/x-icon',\n};\n\n/**\n * Serves the built dashboard.\n *\n * Anything that is not an existing file falls back to `index.html`: the panel\n * is a single-page app, and its inner screens are state, not server routes.\n */\nfunction serveAsset(assetsDir: string, route: string, response: ServerResponse): boolean {\n const root = resolve(assetsDir);\n const requested = route === '/' ? 'index.html' : route.replace(/^\\/+/, '');\n let target = resolve(root, requested);\n\n // A path escaping the assets directory can only come from a traversal attempt.\n if (target !== root && !target.startsWith(root + sep)) return false;\n\n let file = statSync(target, { throwIfNoEntry: false });\n if (!file?.isFile()) {\n target = resolve(root, 'index.html');\n file = statSync(target, { throwIfNoEntry: false });\n if (!file?.isFile()) return false;\n }\n\n response.writeHead(200, {\n 'content-type': MIME_TYPES[extname(target)] ?? 'application/octet-stream',\n 'content-length': file.size,\n // Asset names are content-hashed by the build; index.html must not be cached.\n 'cache-control': target.endsWith('index.html') ? 'no-store' : 'public, max-age=31536000',\n });\n createReadStream(target).pipe(response);\n return true;\n}\n\n/**\n * The application's own address — replay needs it to call back into itself.\n *\n * From the socket, never from `Host`. Replay follows this address carrying\n * headers the caller chose, so a forged `Host` would aim it — cookies and all\n * — at any host that resolves.\n */\nfunction originOf(request: IncomingMessage): string {\n const port = request.socket.localPort;\n const address = request.socket.localAddress ?? '127.0.0.1';\n // IPv6 literals need brackets in a URL; `::1` is the ordinary local case.\n const host = address.includes(':') ? `[${address}]` : address;\n // TLS never reaches this far: the panel is mounted inside the application,\n // and replay always goes to its own local address.\n return `http://${host}${port ? `:${port}` : ''}`;\n}\n\n/**\n * Whether a state-changing request came from the panel itself.\n *\n * The gate says who may use the panel, not what page is asking. Without this,\n * any site open in a developer's browser can POST to `/api/replay` and make\n * the application run a recorded request again — a second charge, a second\n * email. That the reply is unreadable to that page is no comfort: the effect\n * has happened.\n *\n * `Sec-Fetch-Site` is the browser's own account and cannot be set by script.\n * `same-site` is refused with `cross-site`: two ports of localhost are one\n * site, and the dev server on the other port is the neighbour in question.\n *\n * Neither header means the caller is not a browser, and CSRF is not that.\n */\nfunction isSameOrigin(request: IncomingMessage): boolean {\n const site = request.headers['sec-fetch-site'];\n if (typeof site === 'string') return site === 'same-origin' || site === 'none';\n\n const origin = request.headers.origin;\n if (typeof origin !== 'string' || origin === '') return true;\n\n const host = request.headers.host;\n if (typeof host !== 'string') return false;\n try {\n return new URL(origin).host === host;\n } catch {\n // An origin that is not a URL is not one this panel wrote.\n return false;\n }\n}\n\n/**\n * How many requests one export may carry.\n *\n * It serializes whole records into one string, synchronously, answering a GET.\n * The stores bound `list()`, but a bound living in the store is not this\n * endpoint's: a store written elsewhere would hand over its whole history.\n */\nconst EXPORT_LIMIT = 1_000;\n\n/** The newest requests matching the filter, and how many did not fit. */\nfunction forExport(\n source: PanelSource,\n params: URLSearchParams,\n): { requests: readonly RecordedRequest[]; dropped: number } {\n const matched = filterRequests(source.list(), parseFilter(params));\n if (matched.length <= EXPORT_LIMIT) return { requests: matched, dropped: 0 };\n // The newest, because a truncated export should be the recent part of the\n // story rather than an arbitrary slice of it.\n return {\n requests: matched.slice(-EXPORT_LIMIT),\n dropped: matched.length - EXPORT_LIMIT,\n };\n}\n\n/**\n * What a truncated export says about itself.\n *\n * An export is evidence: a cap nobody is told about reads as \"this is\n * everything\".\n */\nfunction exportNote(dropped: number): string | null {\n return dropped === 0\n ? null\n : `${dropped} older request${dropped === 1 ? '' : 's'} matched and were left out: an export carries at most ${EXPORT_LIMIT}.`;\n}\n\n/**\n * How many live feeds one panel may hold open at once.\n *\n * Each one is a listener on the store and a timer; nothing else bounds them,\n * and a stream is opened by a GET that anything can repeat.\n */\nconst MAX_STREAMS = 32;\n\n/**\n * How much one feed may have written that its reader has not taken.\n *\n * A tab left in the background or a proxy that stalled stops reading, and\n * every row since then sits in this process's memory, per feed, without end.\n * Past this the feed is dropped; the panel reconnects and re-reads the list,\n * which is what it does after any gap.\n */\nconst MAX_STREAM_BACKLOG_BYTES = 1024 * 1024;\n\n/**\n * How many feeds one panel is holding.\n *\n * Per handler rather than per process: two applications in one process are two\n * panels, and a cap they share is a cap that depends on a neighbour.\n */\ninterface StreamCount {\n open: number;\n}\n\nfunction streamEvents(\n source: PanelSource,\n mutes: MuteView,\n request: IncomingMessage,\n response: ServerResponse,\n streams: StreamCount,\n): void {\n if (streams.open >= MAX_STREAMS) {\n sendJson(response, 503, { error: `too many live feeds open (${MAX_STREAMS})` });\n return;\n }\n streams.open++;\n\n response.writeHead(200, {\n 'content-type': 'text/event-stream; charset=utf-8',\n 'cache-control': 'no-cache, no-transform',\n connection: 'keep-alive',\n // Disables nginx buffering: without it the feed stalls.\n 'x-accel-buffering': 'no',\n });\n response.write(': reqray stream\\n\\n');\n\n const unsubscribe = source.subscribe((recorded) => {\n // The live feed obeys mutes the same way the list does.\n const [row] = mutes.silence([toRow(recorded)]);\n if (response.writableLength > MAX_STREAM_BACKLOG_BYTES) {\n response.destroy();\n return;\n }\n response.write(`data: ${JSON.stringify(row)}\\n\\n`);\n });\n\n const keepAlive = setInterval(() => response.write(': ping\\n\\n'), 20_000);\n keepAlive.unref?.();\n\n let stopped = false;\n const stop = (): void => {\n // Both `close` events fire for one disconnect; the count must move once.\n if (stopped) return;\n stopped = true;\n streams.open--;\n clearInterval(keepAlive);\n unsubscribe();\n };\n request.on('close', stop);\n response.on('close', stop);\n}\n\n/**\n * Creates the panel handler.\n *\n * Returns `null` if the panel is disabled by options: the adapter then has\n * nothing to mount.\n */\nexport function createPanelHandler(init: PanelHandlerInit): PanelHandler | null {\n const { source, options } = init;\n const panel = options.panel;\n if (!panel || !options.enabled) return null;\n\n const mount = panel.path.endsWith('/') ? panel.path.slice(0, -1) : panel.path;\n const streams: StreamCount = { open: 0 };\n const mutes = new MuteView(source);\n\n const serve: PanelHandler = (request, response) => {\n // Express strips the matched mount prefix from `url` inside `app.use`;\n // `originalUrl` keeps the full path. Anything non-Express has no such\n // property and falls back to the plain url.\n const rawUrl = (request as { originalUrl?: string }).originalUrl ?? request.url ?? '/';\n if (rawUrl !== mount && !rawUrl.startsWith(`${mount}/`) && !rawUrl.startsWith(`${mount}?`)) {\n return false;\n }\n\n const url = new URL(rawUrl, 'http://reqray.local');\n const route = url.pathname.slice(mount.length) || '/';\n\n if (\n !isPanelRequestAllowed(panel.gate, {\n headers: request.headers,\n ip: request.socket.remoteAddress ?? null,\n })\n ) {\n sendJson(response, 403, {\n error: panel.gate\n ? 'panel access denied by the gate'\n : 'without a gate the panel answers only to this machine, at a local address. ' +\n \"To open it further, set one: reqray({ panel: { gate: 'open' } }) or a function.\",\n });\n return true;\n }\n\n const method = request.method ?? 'GET';\n\n // Before anything reads a body: a refusal has to come earlier than the\n // work it refuses, and every state-changing route is behind this line.\n if (method !== 'GET' && method !== 'HEAD' && !isSameOrigin(request)) {\n sendJson(response, 403, { error: 'this request did not come from the panel' });\n return true;\n }\n\n if (route === '/api/meta' && method === 'GET') {\n // Typed rather than inline: this object is the `/api/meta` contract, and\n // the protocol is where that contract is written down.\n const meta: PanelMeta = {\n pid: process.pid,\n startedAt: Date.now() - Math.round(process.uptime() * 1000),\n mode: options.mode,\n bufferSize: options.bufferSize,\n replayEnabled: options.replay,\n blameEnabled: options.blame,\n detectors: detectorSettings(options),\n };\n sendJson(response, 200, meta);\n return true;\n }\n\n if (route === '/api/project' && method === 'GET') {\n // Async, unlike every other route here: it asks git which commit is\n // running, and a panel that lies about the build is worse than one that\n // takes a few milliseconds.\n void projectReport(options, source)\n .then((report) => sendJson(response, 200, report))\n .catch((error: unknown) => {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 500, { error: `project report unavailable: ${reason}` });\n });\n return true;\n }\n\n if (route === '/api/retention' && method === 'GET') {\n sendJson(response, 200, { retention: retentionOf(options), log: logOf(options) });\n return true;\n }\n\n if (route === '/api/retention' && method === 'POST') {\n handleRetention(options, request, response);\n return true;\n }\n\n if (route === '/api/timeline' && method === 'GET') {\n if (!source.timeSeries) {\n sendJson(response, 200, { timeline: null });\n return true;\n }\n const asked = Number(url.searchParams.get('buckets'));\n const buckets =\n Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), 512) : TIMELINE_BUCKETS;\n // A stretch, when the caller names one. A store with days of history\n // and an hour of traffic draws a strip that is empty but for two\n // columns; being able to ask for the part worth looking at is what\n // makes the strip readable without making it lie about the rest.\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const points =\n Number.isFinite(from) && Number.isFinite(to) && to > from\n ? source.timeSeries().filter((point) => point.startedAt >= from && point.startedAt <= to)\n : source.timeSeries();\n sendJson(response, 200, { timeline: buildTimeline(points, buckets) });\n return true;\n }\n\n if (route === '/api/requests' && method === 'GET') {\n const filter = parseFilter(url.searchParams);\n const limit = pageLimit(url.searchParams);\n const sort: RequestSort = url.searchParams.get('sort') === 'slowest' ? 'slowest' : 'recent';\n\n // A store that can page does its own filtering: a history on disk must\n // not be read into memory to answer one screenful.\n if (source.page) {\n const page = source.page({\n filter,\n limit,\n sort,\n cursor: url.searchParams.get('cursor'),\n });\n sendJson(response, 200, {\n requests: mutes.silence(page.rows),\n summary: page.summary,\n nextCursor: page.nextCursor,\n });\n return true;\n }\n\n // No `page()`: the same rule, applied here over everything the store\n // holds, rather than a second implementation of it.\n const page = pageFromList(\n source.list(),\n { filter, limit, sort, cursor: url.searchParams.get('cursor') },\n {\n pinned: new Set(source.pinned?.() ?? []),\n slowMs: options.sampling.slowMs || 500,\n },\n );\n sendJson(response, 200, {\n requests: mutes.silence(page.rows),\n summary: page.summary,\n nextCursor: page.nextCursor,\n });\n return true;\n }\n\n if (route === '/api/export/har' && method === 'GET') {\n const { requests: shown, dropped } = forExport(source, url.searchParams);\n sendDownload(\n response,\n 'reqray.har',\n 'application/json; charset=utf-8',\n JSON.stringify(toHar(shown, new Date(), exportNote(dropped)), null, 2),\n );\n return true;\n }\n\n if (route === '/api/export/curl' && method === 'GET') {\n const { requests: shown, dropped } = forExport(source, url.searchParams);\n sendDownload(\n response,\n 'reqray-requests.sh',\n 'text/x-shellscript; charset=utf-8',\n toCurlScript(shown, originOf(request), exportNote(dropped)),\n );\n return true;\n }\n\n if (route === '/api/blame' && method === 'POST') {\n if (!options.blame) {\n sendJson(response, 403, {\n error:\n 'git blame from the panel is off. Outside local development it is enabled explicitly: reqray({ blame: true }).',\n });\n return true;\n }\n handleBlame(options, request, response);\n return true;\n }\n\n if (route === '/api/routes' && method === 'GET') {\n sendJson(response, 200, routeStats(source.list(), mutes.set()));\n return true;\n }\n\n if (route === '/api/series' && method === 'GET') {\n if (!source.history) {\n // The store cannot read a stretch. Said plainly rather than drawn as\n // an empty chart, which would be a claim about a quiet week.\n sendJson(response, 200, { series: null });\n return true;\n }\n\n const now = Date.now();\n const to = positive(url.searchParams.get('to')) ?? now;\n const from = positive(url.searchParams.get('from')) ?? to - HOUR_MS;\n if (to <= from) {\n sendJson(response, 400, { error: 'the period must end after it starts' });\n return true;\n }\n\n const askedColumns = positive(url.searchParams.get('buckets'));\n const columns = askedColumns ? Math.min(Math.floor(askedColumns), 512) : SERIES_COLUMNS;\n const metrics = parseMetrics(url.searchParams);\n const filter = parseFilter(url.searchParams);\n\n const query = (span: { from: number; to: number }): HistoryQuery => ({\n ...span,\n // The period is the period, whatever the filter's own range says: the\n // screen owns the window, and a stale `from` in the filter would\n // silently narrow it.\n filter: { ...filter, from: span.from, to: span.to },\n });\n\n const current: HistorySamples = source.history(query({ from, to }));\n // The same length again, immediately before. Only ever used for a\n // comparison, so a truncated reading of it changes nothing that is\n // presented as complete.\n const before = source.history(query({ from: from - (to - from), to: from - 1 }));\n\n sendJson(response, 200, {\n series: historyOf(current, before.samples, { from, to, metrics, columns }),\n });\n return true;\n }\n\n if (route === '/api/findings' && method === 'GET') {\n if (!source.findings) {\n // The store cannot read its findings back. Said plainly rather than\n // rendered as an empty work list, which would be a claim about the\n // code being clean.\n sendJson(response, 200, { findings: null });\n return true;\n }\n const read = source.findings({\n from: positive(url.searchParams.get('from')),\n to: positive(url.searchParams.get('to')),\n });\n sendJson(response, 200, {\n findings: patternsOf(read, {\n states: source.findingStates?.(),\n changedAt: fileChangedAt,\n }),\n });\n return true;\n }\n\n if (route === '/api/findings/state' && method === 'POST') {\n handleFindingState(source, mutes, request, response);\n return true;\n }\n\n if (route === '/api/routes/series' && method === 'GET') {\n const wanted = url.searchParams.get('route');\n const verb = url.searchParams.get('method');\n if (!wanted || !verb) {\n sendJson(response, 400, { error: 'a route and a method are needed to draw one' });\n return true;\n }\n // A store that cannot answer draws nothing, rather than a chart of\n // whatever page the browser happened to be holding.\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const samples = source.durations?.({\n method: verb,\n route: wanted,\n // A chart is drawn over the stretch the caller names, so that it\n // covers the same traffic the table beside it describes.\n ...(Number.isFinite(from) && Number.isFinite(to) && to > from ? { from, to } : {}),\n });\n const asked = Number(url.searchParams.get('buckets'));\n const buckets =\n Number.isFinite(asked) && asked > 0 ? Math.min(Math.floor(asked), 256) : SERIES_BUCKETS;\n sendJson(response, 200, {\n series: samples ? routeSeries(verb, wanted, samples, buckets) : null,\n });\n return true;\n }\n\n if (route === '/api/timeline/at' && method === 'GET') {\n const from = Number(url.searchParams.get('from'));\n const to = Number(url.searchParams.get('to'));\n const overallFrom = Number(url.searchParams.get('overallFrom'));\n const overallTo = Number(url.searchParams.get('overallTo'));\n if (![from, to, overallFrom, overallTo].every(Number.isFinite) || to <= from) {\n sendJson(response, 400, { error: 'a moment needs a start and an end, in epoch ms' });\n return true;\n }\n if (!source.counts) {\n sendJson(response, 200, { activity: null });\n return true;\n }\n sendJson(response, 200, {\n activity: whatRanAt(\n source.counts({ from, to }),\n source.counts({ from: overallFrom, to: overallTo }),\n { from, to, overallMs: overallTo - overallFrom },\n ),\n });\n return true;\n }\n\n if (route === '/api/pin' && method === 'POST') {\n handlePin(source, request, response);\n return true;\n }\n\n if (route === '/api/requests' && method === 'DELETE') {\n source.clear();\n sendJson(response, 200, { cleared: true });\n return true;\n }\n\n // ORDER MATTERS from here to the end of the `/api/requests/` group: these\n // are prefix matches, not exact ones, and `/api/requests/:id` below would\n // swallow `/api/requests/:id/baseline` if it came first. The chain has no\n // way to say so structurally, so it says so here.\n if (route.startsWith('/api/requests/') && route.endsWith('/baseline') && method === 'GET') {\n const id = decodeURIComponent(route.slice('/api/requests/'.length, -'/baseline'.length));\n const found = source.get(id);\n if (!found) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return true;\n }\n // A store that cannot answer produces no baseline, and the panel shows\n // no card: an absent comparison is an ordinary answer here.\n const samples = source.durations?.({\n method: found.method,\n route: normalizeRoute(found.path),\n excludeId: found.id,\n });\n sendJson(response, 200, {\n baseline: baselineFor(found, samples),\n pressure: samples ? pressureFor(samples) : null,\n });\n return true;\n }\n\n if (route.startsWith('/api/requests/') && method === 'GET') {\n const id = decodeURIComponent(route.slice('/api/requests/'.length));\n const found = source.get(id);\n if (!found) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return true;\n }\n // The row fields travel with the record: the panel's detail type\n // extends its row type, and a payload missing half of it is a contract\n // that silently reads `undefined`.\n sendJson(response, 200, {\n ...toRow(found, (source.pinned?.() ?? []).includes(id)),\n ...ensureTiming(found),\n });\n return true;\n }\n\n if (route === '/api/exceptions' && method === 'GET') {\n sendJson(response, 200, { groups: groupExceptions(source.list(), options.stack) });\n return true;\n }\n\n if (route === '/api/stream' && method === 'GET') {\n streamEvents(source, mutes, request, response, streams);\n return true;\n }\n\n if (route === '/api/explain' && method === 'POST') {\n if (!options.explain) {\n sendJson(response, 403, {\n error:\n 'EXPLAIN from the panel is off. Outside local development it is enabled explicitly: reqray({ explain: true }).',\n });\n return true;\n }\n handleExplain(source, request, response);\n return true;\n }\n\n if (route === '/api/replay' && method === 'POST') {\n if (!options.replay) {\n sendJson(response, 403, {\n error:\n 'replay is off. Outside local development it is enabled only explicitly: reqray({ replay: true }) — a replay in production means a second charge and a second email.',\n });\n return true;\n }\n handleReplay(source, request, response);\n return true;\n }\n\n if (route.startsWith('/api/')) {\n sendJson(response, 404, { error: 'no such panel endpoint' });\n return true;\n }\n\n if (method === 'GET' && init.assetsDir && serveAsset(init.assetsDir, route, response)) {\n return true;\n }\n\n sendJson(response, 404, {\n error: init.assetsDir\n ? 'panel asset not found'\n : 'the panel UI is not installed: add @reqray/dashboard. The API keeps working.',\n });\n return true;\n };\n\n return function handlePanelRequest(request, response): boolean {\n try {\n return serve(request, response);\n } catch (error) {\n // Only a panel request gets this far before anything can throw — a\n // malformed `%` in an id, say — and it must end here: on a bare\n // `node:http` server an exception in the listener takes the process,\n // which is the application's.\n const reason = error instanceof Error ? error.message : String(error);\n if (response.headersSent) response.destroy();\n else sendJson(response, 400, { error: `bad panel request: ${reason}` });\n return true;\n }\n };\n}\n\n/**\n * Changes how long requests are kept.\n *\n * The only setting the panel can write, and it deletes data on the way down,\n * so it is refused unless the application handed the panel a policy and said\n * it may be changed. Values are checked here rather than trusted: the panel\n * is a client like any other.\n */\nfunction handleRetention(\n options: ResolvedOptions,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n const policy = options.retention;\n if (!policy) {\n sendJson(response, 501, {\n error:\n 'this application keeps to fixed limits: pass reqray({ retention: retentionPolicy({ … }) }) to make them changeable.',\n });\n return;\n }\n if (!policy.writable) {\n sendJson(response, 403, {\n error: 'retention is read-only here: the policy was created with writable: false.',\n });\n return;\n }\n\n try {\n const payload = (await readBody(request)) as Partial<RetentionLimits>;\n const patch: Record<string, unknown> = {};\n for (const key of ['days', 'maxBytes', 'maxRequests'] as const) {\n if (key in payload) patch[key] = payload[key];\n }\n if (Object.keys(patch).length === 0) {\n sendJson(response, 400, { error: 'nothing to change: days, maxBytes or maxRequests' });\n return;\n }\n\n const limits = policy.update(patch as Partial<RetentionLimits>);\n // The stores sweep on their own schedule; what is reported back is the\n // policy, not a promise that the disk is already smaller.\n sendJson(response, 200, { retention: retentionOf(options), limits });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `retention unchanged: ${reason}` });\n }\n })();\n}\n\nfunction handleBlame(\n options: ResolvedOptions,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as {\n frames?: Array<{ file?: unknown; line?: unknown }>;\n };\n const frames = Array.isArray(payload.frames) ? payload.frames.slice(0, 30) : [];\n\n const blamed = await Promise.all(\n frames.map(async (frame) => {\n if (typeof frame.file !== 'string' || typeof frame.line !== 'number') return null;\n return blameLine(frame.file, frame.line, options.stack.projectRoot);\n }),\n );\n sendJson(response, 200, { frames: blamed });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `blame failed: ${reason}` });\n }\n })();\n}\n\n/**\n * When a file last changed, epoch ms — what `fixed?` is guessed from.\n *\n * The file's mtime rather than git: honest enough for a guess drawn with a\n * question mark, and free. Unreadable files answer \"nobody knows\".\n */\nfunction fileChangedAt(file: string): number | null {\n try {\n return statSync(file).mtimeMs;\n } catch {\n return null;\n }\n}\n\n/**\n * What is muted, remembered between changes.\n *\n * Muting is presentation, not detection: the record keeps its findings, but a\n * muted pattern must stop flagging the list, the live feed and the routes\n * table alike — one that flashes amber on arrival and goes grey on reload is a\n * haunting.\n *\n * Held rather than rebuilt per call: it changes only when somebody mutes\n * something, and the live feed would otherwise walk the whole state map once\n * per request delivered.\n */\nclass MuteView {\n #muted: Set<string> | null = null;\n\n constructor(private readonly source: PanelSource) {}\n\n /** Pattern ids the reader muted, or an empty set when nothing is. */\n set(): ReadonlySet<string> {\n if (this.#muted) return this.#muted;\n\n const muted = new Set<string>();\n const states = this.source.findingStates?.();\n if (states) {\n for (const [id, state] of states) if (state === 'muted') muted.add(id);\n }\n this.#muted = muted;\n return muted;\n }\n\n /** Called when a state changes; the next read rebuilds. */\n forget(): void {\n this.#muted = null;\n }\n\n /**\n * Rows with muted patterns silenced.\n *\n * Only flagged rows are looked up — they are the rare ones — and a record\n * the store has already dropped keeps the flag it had.\n */\n silence(rows: readonly RequestRow[]): readonly RequestRow[] {\n const muted = this.set();\n if (muted.size === 0) return rows;\n return rows.map((row) => {\n if (row.flag === null) return row;\n const record = this.source.get(row.id);\n if (!record) return row;\n const flag = flagWithMutes(record, muted);\n return flag === row.flag ? row : { ...row, flag };\n });\n }\n}\n\n/**\n * The states a client may set.\n *\n * `fixed` is deliberately absent: it is a computed guess, and a stored one\n * would outlive the change it guessed about. The list is what both the check\n * and the refusal message are built from, so they cannot drift apart.\n */\nconst SETTABLE_STATES: readonly StoredPatternState[] = ['new', 'ack', 'muted'];\n\nfunction isSettable(value: unknown): value is StoredPatternState {\n return (SETTABLE_STATES as readonly unknown[]).includes(value);\n}\n\nfunction handleFindingState(\n source: PanelSource,\n mutes: MuteView,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n if (!source.setFindingState) {\n sendJson(response, 501, { error: 'this store cannot remember finding states' });\n return;\n }\n try {\n const payload = (await readBody(request)) as { id?: unknown; state?: unknown };\n if (typeof payload.id !== 'string' || payload.id.length === 0 || !isSettable(payload.state)) {\n sendJson(response, 400, {\n error: `a pattern id and a state (${SETTABLE_STATES.join(', ')}) are needed`,\n });\n return;\n }\n const state = payload.state;\n source.setFindingState(payload.id, state);\n // The only moment what is muted can change.\n mutes.forget();\n sendJson(response, 200, { ok: true });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `state change failed: ${reason}` });\n }\n })();\n}\n\nfunction handlePin(source: PanelSource, request: IncomingMessage, response: ServerResponse): void {\n void (async () => {\n if (!source.pin) {\n sendJson(response, 501, { error: 'this store cannot pin requests' });\n return;\n }\n try {\n const payload = (await readBody(request)) as { id?: unknown; pinned?: unknown };\n if (typeof payload.id !== 'string') {\n sendJson(response, 400, { error: 'id is required' });\n return;\n }\n const wanted = payload.pinned !== false;\n const ok = source.pin(payload.id, wanted);\n if (!ok && wanted) {\n // Either the record is already gone, or the pin board is full — both\n // are worth saying out loud rather than silently doing nothing.\n sendJson(response, 409, {\n error: 'could not pin: the request is gone, or too many are pinned already',\n });\n return;\n }\n sendJson(response, 200, { id: payload.id, pinned: wanted && ok });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n sendJson(response, 400, { error: `pin failed: ${reason}` });\n }\n })();\n}\n\nfunction handleExplain(\n source: PanelSource,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as { id?: unknown; spanId?: unknown };\n const record = typeof payload.id === 'string' ? source.get(payload.id) : undefined;\n if (!record) {\n sendJson(response, 404, {\n error: 'request not found — possibly evicted from the ring buffer',\n });\n return;\n }\n const spanId = typeof payload.spanId === 'number' ? payload.spanId : Number.NaN;\n\n sendJson(response, 200, await runExplain(record, spanId));\n } catch (error) {\n if (error instanceof ExplainError) {\n sendJson(response, error.status, { error: error.message });\n return;\n }\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.explain', `EXPLAIN failed: ${reason}`);\n sendJson(response, 500, { error: `EXPLAIN failed: ${reason}` });\n }\n })();\n}\n\nfunction handleReplay(\n source: PanelSource,\n request: IncomingMessage,\n response: ServerResponse,\n): void {\n void (async () => {\n try {\n const payload = (await readBody(request)) as {\n id?: unknown;\n method?: unknown;\n path?: unknown;\n headers?: unknown;\n body?: unknown;\n };\n\n const original = typeof payload.id === 'string' ? source.get(payload.id) : undefined;\n if (!original) {\n sendJson(response, 404, { error: 'original request not found' });\n return;\n }\n\n const input: ReplayInput = {\n method: typeof payload.method === 'string' ? payload.method : original.method,\n path: typeof payload.path === 'string' ? payload.path : original.path,\n headers:\n payload.headers && typeof payload.headers === 'object'\n ? (payload.headers as Record<string, string>)\n : {},\n body: typeof payload.body === 'string' ? payload.body : undefined,\n };\n\n sendJson(response, 200, await runReplay(originOf(request), input, original));\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.replay', `replay failed: ${reason}`);\n sendJson(response, 500, { error: `replay failed: ${reason}` });\n }\n })();\n}\n","/**\n * State that has to be single per process.\n *\n * `@reqray/core` is built as both ESM and CJS, and both builds can end up\n * loaded in one application at once: the adapter came in through `import`,\n * while a loader hook or a third-party package came in through `require`. That\n * gives two sets of module-level variables, and it is not cosmetic — two\n * `AsyncLocalStorage` instances mean instrumentation never sees the scope the\n * adapter created, and nothing is recorded at all.\n *\n * So anything that must be single lives on `globalThis`, under a symbol from\n * the global registry that both copies resolve to the same way. This file does\n * not hold that state — it hands out slots, and each module declares, names\n * and types the state it owns.\n */\n\n/** Version in the key: an incompatible change of shape must not break silently. */\nconst REGISTRY_KEY = Symbol.for('reqray.state.v2');\n\ntype Holder = typeof globalThis & { [REGISTRY_KEY]?: Map<string, unknown> };\n\nfunction registry(): Map<string, unknown> {\n const holder = globalThis as Holder;\n const existing = holder[REGISTRY_KEY];\n if (existing) return existing;\n\n const fresh = new Map<string, unknown>();\n holder[REGISTRY_KEY] = fresh;\n return fresh;\n}\n\n/**\n * Declares one piece of process-wide state and returns the way to read it.\n *\n * The name is the identity across module copies, so it must be unique and\n * stable — by convention, `<module>.<what>`. The accessor caches after the\n * first call: `current()` is the first line of every instrumentation wrapper\n * and must not cost a global lookup and a map read each time.\n *\n * @example\n * const fingerprints = globalSlot('sql.fingerprints', () => new Map<string, string>());\n */\nexport function globalSlot<T>(name: string, create: () => T): () => T {\n let cached: T | undefined;\n let resolved = false;\n\n return (): T => {\n if (resolved) return cached as T;\n\n const slots = registry();\n if (!slots.has(name)) slots.set(name, create());\n cached = slots.get(name) as T;\n resolved = true;\n return cached;\n };\n}\n\n/**\n * A single mutable value, for state that is not an object.\n *\n * A slot hands back a reference, so a boolean or a counter needs something to\n * be a reference *to*.\n */\nexport interface Box<T> {\n value: T;\n}\n\n/** @see Box */\nexport function globalBox<T>(name: string, initial: T): () => Box<T> {\n return globalSlot(name, () => ({ value: initial }));\n}\n\n/**\n * A bounded cache with no cliff at the limit.\n *\n * Clearing at the ceiling would make an application sitting just over it throw\n * away its hottest entries with its coldest and miss on everything until the\n * cache refills. Instead the hot generation becomes the cold one and a fresh\n * one starts; a read that hits the cold one promotes the entry. Holds at most\n * twice `limit`.\n */\nexport class TwoGenerationCache<K, V> {\n #hot = new Map<K, V>();\n #cold = new Map<K, V>();\n\n constructor(private readonly limit: number) {}\n\n get(key: K): V | undefined {\n const hot = this.#hot.get(key);\n if (hot !== undefined) return hot;\n\n const cold = this.#cold.get(key);\n if (cold === undefined) return undefined;\n // Used again, so it belongs in the generation that will survive.\n this.#hot.set(key, cold);\n return cold;\n }\n\n set(key: K, value: V): void {\n if (this.#hot.size >= this.limit) {\n this.#cold = this.#hot;\n this.#hot = new Map<K, V>();\n }\n this.#hot.set(key, value);\n }\n\n /** Whether the key is known in either generation. */\n has(key: K): boolean {\n return this.#hot.has(key) || this.#cold.has(key);\n }\n\n clear(): void {\n this.#hot.clear();\n this.#cold.clear();\n }\n\n /** Entries held right now, across both generations. Needed by tests. */\n get size(): number {\n let total = this.#hot.size;\n for (const key of this.#cold.keys()) if (!this.#hot.has(key)) total++;\n return total;\n }\n}\n","/**\n * Reqray's own logging.\n *\n * The project rule: an instrumentation error is caught, logged as a warning\n * **once** and disables that one instrument without touching the rest. Hence\n * {@link warnOnce}.\n */\n\nimport { type Box, globalBox, globalSlot } from './state.js';\n\n/** Where Reqray writes its own messages. */\nexport interface ReqrayLogSink {\n info(message: string): void;\n warn(message: string): void;\n}\n\n/** Keys of warnings already issued, so `warnOnce` means once per process. */\nconst warned = globalSlot('logger.warned', () => new Set<string>());\n\n/** Where Reqray writes its own messages. `null` — the default sink. */\nconst sink: () => Box<ReqrayLogSink | null> = globalBox('logger.sink', null);\n\nconst defaultSink: ReqrayLogSink = {\n info: (message) => console.info(message),\n warn: (message) => console.warn(message),\n};\n\n/** Replaces the message sink. Needed by tests and apps with their own logger. */\nexport function setLogSink(next: ReqrayLogSink | null): void {\n sink().value = next;\n}\n\n/** Writes an informational line, such as the startup report. */\nexport function info(message: string): void {\n try {\n (sink().value ?? defaultSink).info(message);\n } catch {\n // Even a broken logger must not break the application.\n }\n}\n\n/** Writes a warning, prefixed so it is obvious where it came from. */\nexport function warn(message: string): void {\n try {\n (sink().value ?? defaultSink).warn(`reqray: ${message}`);\n } catch {\n // Even a broken logger must not break the application.\n }\n}\n\n/**\n * Writes a warning only the first time a key shows up.\n *\n * Instrumentation on the hot path can fail thousands of times a second —\n * repeat messages add no information and only do harm.\n */\nexport function warnOnce(key: string, message: string): void {\n const seen = warned();\n if (seen.has(key)) return;\n seen.add(key);\n warn(message);\n}\n\n/** Forgets which warnings have already been issued. Needed by tests. */\nexport function resetWarnings(): void {\n warned().clear();\n}\n","/**\n * Duplicate-work detectors: the same call made twice in one request.\n *\n * Unlike the N+1 detectors, order does not matter here — two identical calls\n * are wasted work whether they were sequential or parallel. What does matter\n * is that the call is *safe* to have made once: only reads are flagged, since\n * \"memoize this\" is sound advice for a GET and dangerous for a POST.\n *\n * What is intentionally NOT flagged:\n * - anything but GET/HEAD, and cache writes: repeating those may be the point;\n * - failures and retries — a second attempt after a 5xx is correct behaviour;\n * - calls whose URLs differ at all, query string included: a different URL is\n * a different question, and collapsing them would invent a duplicate;\n * - cache reads of one key that ask for different things: `HGET user:1 email`\n * and `HGET user:1 name` are two reads, not one read made twice.\n */\n\nimport type { CacheSpan, Callsite, Finding, FindingSeverity, HttpSpan } from '../types.js';\nimport type { Detector } from './types.js';\n\nexport interface DuplicateHttpOptions {\n /** How many identical calls before it is worth reporting. */\n readonly threshold: number;\n /** Below this saving the duplicate is not worth a card. */\n readonly minWastedMs: number;\n}\n\nexport interface DuplicateCacheOptions {\n readonly threshold: number;\n}\n\nconst SEVERITY_WARN_MS = 50;\n\n/** Methods where a second identical call returns the same thing. */\nconst READ_METHODS = new Set(['GET', 'HEAD']);\n\nfunction isRetry(span: HttpSpan): boolean {\n if (span.error) return true;\n if (span.statusCode === null) return true;\n return span.statusCode >= 500 || span.statusCode === 429;\n}\n\n/**\n * What is saved by making the call once.\n *\n * The largest of the group is the one assumed to remain, so the number is\n * never larger than the time that actually exists.\n */\nfunction savingOf(spans: readonly { duration: number }[]): number {\n let total = 0;\n let slowest = 0;\n for (const span of spans) {\n total += span.duration;\n if (span.duration > slowest) slowest = span.duration;\n }\n return total - slowest;\n}\n\n/**\n * Where else the same call is made from.\n *\n * The panel already prints the finding's own callsite, so the hint names only\n * the *other* places — the half the reader cannot see yet.\n */\nfunction otherSites(spans: readonly { callsite: Callsite | null }[]): string[] {\n const site = (span: { callsite: Callsite | null }) =>\n span.callsite ? `${span.callsite.relative}:${span.callsite.line}` : '';\n const first = site(spans[0] ?? { callsite: null });\n return [...new Set(spans.slice(1).map(site).filter(Boolean))].filter((place) => place !== first);\n}\n\nfunction group<T>(items: readonly T[], keyOf: (item: T) => string): Map<string, T[]> {\n const groups = new Map<string, T[]>();\n for (const item of items) {\n const key = keyOf(item);\n const existing = groups.get(key);\n if (existing) existing.push(item);\n else groups.set(key, [item]);\n }\n return groups;\n}\n\n/** Two identical outbound reads in one request. */\nexport const duplicateHttp: Detector<DuplicateHttpOptions> = {\n id: 'dup_http',\n\n defaultOptions: {\n threshold: 2,\n // An external call worth deduplicating costs at least this much; below it\n // the card is noise on a screen meant for the expensive things.\n minWastedMs: 10,\n },\n\n run(scope, options) {\n const calls = scope.spans.filter(\n (span): span is HttpSpan =>\n span.kind === 'http' && READ_METHODS.has(span.method.toUpperCase()) && !isRetry(span),\n );\n\n const findings: Finding[] = [];\n for (const [key, spans] of group(calls, (span) => `${span.method} ${span.url}`)) {\n if (spans.length < options.threshold) continue;\n\n const costMs = savingOf(spans);\n if (costMs < options.minWastedMs) continue;\n\n const severity: FindingSeverity = costMs >= SEVERITY_WARN_MS ? 'warn' : 'info';\n const first = spans[0];\n const others = otherSites(spans);\n\n findings.push({\n detector: 'dup_http',\n severity,\n title: `${spans.length} identical calls to the same URL`,\n costMs,\n callsite: first?.callsite ?? null,\n evidence: {\n kind: 'duplicate',\n repeats: spans.length,\n fingerprint: key,\n sample: first ? `${first.method} ${first.url}` : key,\n totalMs: spans.reduce((sum, span) => sum + span.duration, 0),\n spanIds: spans.map((span) => span.id),\n },\n hint:\n (others.length > 0 ? `also called from ${others.join(' and ')} — ` : '') +\n 'the second call returns what the first already fetched. Hold the result for the ' +\n 'duration of the request instead of asking again.',\n });\n }\n return findings;\n },\n};\n\n/**\n * The whole read, as the driver sent it: `GET user:1`, `HGET user:1 email`.\n *\n * The command and the selecting arguments are part of the identity on\n * purpose. `HGET user:1 email` and `HGET user:1 name` touch one key but read\n * different values, and calling that pair a duplicate would be a false\n * positive on a screen whose whole worth is that it does not cry wolf.\n */\nfunction callOf(span: CacheSpan): string {\n return span.command ? `${span.command} ${span.key}`.trimEnd() : span.key;\n}\n\n/** The same cache read made more than once in one request. */\nexport const duplicateCache: Detector<DuplicateCacheOptions> = {\n id: 'dup_cache',\n\n defaultOptions: { threshold: 2 },\n\n run(scope, options) {\n const reads = scope.spans.filter(\n (span): span is CacheSpan => span.kind === 'cache' && span.operation === 'get',\n );\n\n const findings: Finding[] = [];\n for (const [call, spans] of group(reads, callOf)) {\n if (spans.length < options.threshold) continue;\n\n const first = spans[0];\n const others = otherSites(spans);\n findings.push({\n detector: 'dup_cache',\n // Cache reads are cheap; this is a nudge about redundant work, not an\n // alarm about time, so it never outranks a real cost on the screen.\n severity: 'info',\n title: `${spans.length} reads of the same cache key`,\n costMs: savingOf(spans),\n callsite: first?.callsite ?? null,\n evidence: {\n kind: 'duplicate',\n repeats: spans.length,\n fingerprint: call,\n sample: first?.command ? call : `cache.get ${call}`,\n totalMs: spans.reduce((sum, span) => sum + span.duration, 0),\n spanIds: spans.map((span) => span.id),\n },\n hint:\n `\"${first?.key ?? call}\" is read ${spans.length} times while handling one request` +\n `${others.length > 0 ? `, also from ${others.join(' and ')}` : ''}` +\n ' — read it once and pass the value down.',\n });\n }\n return findings;\n },\n};\n","/**\n * What a request moved.\n *\n * The honest answer to \"where is the memory going\". Node has no per-request\n * memory to report: `process.memoryUsage()` around a request, under\n * concurrency and a garbage collector that runs when it likes, is noise and\n * occasionally negative. What *is* knowable is what the request pulled out of\n * the database and pushed back to the client — which is what the spike was\n * made of, and which points at a line of code rather than at a graph.\n */\n\nimport type { RecordedBody, RequestWeight, Span } from './types.js';\n\n/**\n * The size of a body, as the two sources know it.\n *\n * `content-length` is what the client was told and is preferred; the recorded\n * body's own size answers when the header is missing — a chunked response, a\n * framework that streams. Neither is a guess: when both are absent the answer\n * is `null`, and every screen shows nothing rather than a zero.\n */\nfunction bytesOf(\n headers: Readonly<Record<string, string>>,\n body: RecordedBody | null,\n): number | null {\n const declared = Number(headers['content-length']);\n if (Number.isFinite(declared) && declared >= 0) return declared;\n // A body recorded before sizes were kept has no answer to give, and saying\n // zero would put a route that returns megabytes at the bottom of the list.\n return body && Number.isFinite(body.bytes) ? body.bytes : null;\n}\n\n/** Rows across every query that reported a count, and the largest of them. */\nfunction rowsOf(spans: readonly Span[]): { rows: number; biggestRows: number } {\n let rows = 0;\n let biggestRows = 0;\n for (const span of spans) {\n if (span.kind !== 'db' || span.rowCount === null) continue;\n rows += span.rowCount;\n if (span.rowCount > biggestRows) biggestRows = span.rowCount;\n }\n return { rows, biggestRows };\n}\n\n/** What the request moved, in the numbers the panel and the detector read. */\nexport function weightOf(input: {\n readonly spans: readonly Span[];\n readonly requestHeaders: Readonly<Record<string, string>>;\n readonly responseHeaders: Readonly<Record<string, string>>;\n readonly requestBody: RecordedBody | null;\n readonly responseBody: RecordedBody | null;\n}): RequestWeight {\n return {\n bytesIn: bytesOf(input.requestHeaders, input.requestBody),\n bytesOut: bytesOf(input.responseHeaders, input.responseBody),\n ...rowsOf(input.spans),\n };\n}\n\n/**\n * The query a large response most likely came out of.\n *\n * The one that returned the most rows, when the driver says how many. When\n * none of them does — plenty of drivers do not — the answer is the query\n * itself if there was only one, and nothing at all if there were several:\n * picking the slowest and calling it the source would be a guess wearing\n * evidence's clothes.\n */\nexport function biggestQuery(spans: readonly Span[]): Extract<Span, { kind: 'db' }> | null {\n const queries = spans.filter((span): span is Extract<Span, { kind: 'db' }> => span.kind === 'db');\n const counted = queries.filter((span) => span.rowCount !== null);\n if (counted.length === 0) return queries.length === 1 ? (queries[0] ?? null) : null;\n\n let found = counted[0] ?? null;\n for (const span of counted) {\n if (found && (span.rowCount ?? 0) > (found.rowCount ?? 0)) found = span;\n }\n return found;\n}\n","/**\n * Heavy-response detector: this endpoint returned far more than it should.\n *\n * The mistake it names is a missing limit — a list route that grew with the\n * table behind it, an export that was never paginated, a serializer that\n * includes every relation because once it was convenient. It is the ordinary\n * cause of a memory graph that climbs under load, and it is invisible in a\n * waterfall: every query is fast, and the megabytes are in the tail.\n *\n * Two things it deliberately does not do.\n *\n * It does not report a cost in milliseconds. What a large response costs is\n * bytes: memory in this process, bandwidth, and time on somebody's phone that\n * this process never measured. Putting a made-up figure in `costMs` so that\n * the finding sorts higher would be inventing the one number the panel treats\n * as measured.\n *\n * And it does not fire on files. A twelve-megabyte PDF is a document; a\n * twelve-megabyte JSON document is a forgotten `LIMIT`. The content type is\n * the only thing that tells them apart, and guessing wrong here means telling\n * somebody their download is a bug.\n */\n\nimport type { Finding } from '../types.js';\nimport { biggestQuery } from '../weight.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\nexport interface HeavyResponseOptions {\n /** Response size above which the endpoint is doing something wrong. */\n readonly maxBytes: number;\n}\n\n/**\n * Content types that are documents rather than answers.\n *\n * Matched on what a response *is*, not on what it is not: an unknown type is\n * left alone. A detector that fires on everything it does not recognise is a\n * detector that gets switched off.\n */\nconst STRUCTURED = /^(application\\/(json|.*\\+json|xml|.*\\+xml|javascript)|text\\/)/i;\n\n/** What the panel says to do about it, in the order worth trying. */\nconst HINT =\n 'Paginate it, or return only the fields the caller uses. A response this size is memory in this process, bandwidth, and a wait on the device at the other end.';\n\n/** `12 MB`, `840 KB` — the size as the finding's title says it. */\nfunction size(bytes: number): string {\n if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n return `${Math.round(bytes / 1024)} KB`;\n}\n\nexport const heavyResponse: Detector<HeavyResponseOptions> = {\n id: 'heavy_response',\n\n defaultOptions: {\n // A megabyte of structured text is somewhere upwards of a thousand\n // objects. Under it, a response is within what a client absorbs without\n // anybody noticing; over it, somebody forgot a limit — and the threshold\n // has to be high enough that a normal page of results never reaches it,\n // because the first false positive is the one that gets the detector\n // turned off.\n maxBytes: 1024 * 1024,\n },\n\n run(scope, options, request: FinishedRequest): Finding[] {\n const bytes = request.bytesOut;\n if (bytes === null || bytes <= options.maxBytes) return [];\n\n const contentType = request.contentType;\n // Unknown type: no finding. A stream of bytes nobody labelled might be an\n // export somebody meant to write.\n if (!contentType || !STRUCTURED.test(contentType)) return [];\n\n const spans = scope.spans;\n const biggest = biggestQuery(spans);\n let rows = 0;\n for (const span of spans) {\n if (span.kind === 'db' && span.rowCount !== null) rows += span.rowCount;\n }\n\n const from = rows > 0 ? ` from ${rows.toLocaleString('en-US')} rows` : '';\n return [\n {\n detector: 'heavy_response',\n severity: 'warn',\n title: `${size(bytes)} response${from}`,\n // Bytes, not milliseconds — see the note at the top of this file.\n costMs: 0,\n callsite: biggest?.callsite ?? null,\n evidence: {\n kind: 'heavy_response',\n bytes,\n rows,\n sample: biggest ? biggest.sql.replace(/\\s+/g, ' ').trim() : null,\n contentType,\n spanIds: biggest ? [biggest.id] : [],\n },\n hint: HINT,\n },\n ];\n },\n};\n","/**\n * SQL normalization.\n *\n * The fingerprint is what repeats are grouped by: without it `SELECT * FROM\n * users WHERE id = 1` and `... id = 2` count as different queries and the N+1\n * detector finds nothing.\n *\n * Called on the hot path for every database query, hence a single-pass\n * character scanner (rather than a chain of regexes) plus a cache keyed by the\n * source string: the same SQL arrives thousands of times.\n */\n\n/** SQL statement type. Detectors only look at `select`. */\nexport type SqlOperation = 'select' | 'insert' | 'update' | 'delete' | 'other';\n\nimport { globalSlot, TwoGenerationCache } from './state.js';\n\n/**\n * Cache cap.\n *\n * Applications that build SQL dynamically can produce an unbounded set of\n * strings, so both caches have a ceiling. See {@link TwoGenerationCache} for\n * why hitting the ceiling is not a `clear()`: an application sitting just over\n * the limit would otherwise throw away its hottest entries with its coldest\n * and re-scan every statement until the cache refilled.\n */\nconst CACHE_LIMIT = 5_000;\n\nconst fingerprints = globalSlot(\n 'sql.fingerprints',\n () => new TwoGenerationCache<string, string>(CACHE_LIMIT),\n);\n\nconst operations = globalSlot(\n 'sql.operations',\n () => new TwoGenerationCache<string, SqlOperation>(CACHE_LIMIT),\n);\n\nconst CHAR_TAB = 9;\nconst CHAR_LF = 10;\nconst CHAR_CR = 13;\nconst CHAR_SPACE = 32;\nconst CHAR_QUOTE = 39; // '\nconst CHAR_DQUOTE = 34; // \"\nconst CHAR_BACKTICK = 96;\nconst CHAR_BACKSLASH = 92;\nconst CHAR_DASH = 45; // -\nconst CHAR_SLASH = 47; // /\nconst CHAR_STAR = 42; // *\nconst CHAR_DOLLAR = 36;\nconst CHAR_QUESTION = 63;\nconst CHAR_COLON = 58;\nconst CHAR_AT = 64;\nconst CHAR_DOT = 46;\nconst CHAR_PLUS = 43;\nconst CHAR_LOWER_E = 101;\nconst CHAR_UPPER_E = 69;\nconst CHAR_LPAREN = 40;\nconst CHAR_RPAREN = 41;\n\nfunction isSpace(code: number): boolean {\n return code === CHAR_SPACE || code === CHAR_TAB || code === CHAR_LF || code === CHAR_CR;\n}\n\nfunction isDigit(code: number): boolean {\n return code >= 48 && code <= 57;\n}\n\nfunction isIdentStart(code: number): boolean {\n // Anything above ASCII counts as part of an identifier: table names can be anything.\n return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95 || code > 127;\n}\n\nfunction isIdentPart(code: number): boolean {\n return isIdentStart(code) || isDigit(code) || code === CHAR_DOLLAR;\n}\n\n/**\n * End of a dollar-quoted string tag `$tag$` (including the empty `$$`),\n * or -1 if this is not one.\n */\nfunction dollarTagEnd(sql: string, start: number): number {\n for (let i = start + 1; i < sql.length; i++) {\n const code = sql.charCodeAt(i);\n if (code === CHAR_DOLLAR) return i;\n // A tag may only contain letters, digits and `_`; `$` closes it.\n if (!isIdentStart(code) && !isDigit(code)) return -1;\n }\n return -1;\n}\n\nfunction scan(sql: string): string {\n const length = sql.length;\n let out = '';\n let pendingSpace = false;\n let i = 0;\n\n const push = (text: string): void => {\n if (pendingSpace && out.length > 0) out += ' ';\n pendingSpace = false;\n out += text;\n };\n\n while (i < length) {\n const code = sql.charCodeAt(i);\n\n if (isSpace(code)) {\n pendingSpace = true;\n i++;\n continue;\n }\n\n // Comments are dropped entirely: they do not affect what gets executed.\n if (code === CHAR_DASH && sql.charCodeAt(i + 1) === CHAR_DASH) {\n while (i < length && sql.charCodeAt(i) !== CHAR_LF) i++;\n pendingSpace = true;\n continue;\n }\n if (code === CHAR_SLASH && sql.charCodeAt(i + 1) === CHAR_STAR) {\n i += 2;\n while (\n i < length &&\n !(sql.charCodeAt(i) === CHAR_STAR && sql.charCodeAt(i + 1) === CHAR_SLASH)\n )\n i++;\n i += 2;\n pendingSpace = true;\n continue;\n }\n\n // String literal: neither its value nor its length may affect the fingerprint.\n if (code === CHAR_QUOTE) {\n i++;\n while (i < length) {\n const inner = sql.charCodeAt(i);\n if (inner === CHAR_BACKSLASH) {\n i += 2;\n continue;\n }\n if (inner === CHAR_QUOTE) {\n if (sql.charCodeAt(i + 1) === CHAR_QUOTE) {\n i += 2;\n continue;\n }\n i++;\n break;\n }\n i++;\n }\n push('?');\n continue;\n }\n\n // A quoted identifier is a table or column name — it is significant.\n if (code === CHAR_DQUOTE || code === CHAR_BACKTICK) {\n const start = i;\n i++;\n while (i < length && sql.charCodeAt(i) !== code) i++;\n i++;\n push(sql.slice(start, Math.min(i, length)));\n continue;\n }\n\n if (code === CHAR_DOLLAR) {\n if (isDigit(sql.charCodeAt(i + 1))) {\n i++;\n while (i < length && isDigit(sql.charCodeAt(i))) i++;\n push('?');\n continue;\n }\n const tagEnd = dollarTagEnd(sql, i);\n if (tagEnd !== -1) {\n const tag = sql.slice(i, tagEnd + 1);\n const close = sql.indexOf(tag, tagEnd + 1);\n i = close === -1 ? length : close + tag.length;\n push('?');\n continue;\n }\n push('$');\n i++;\n continue;\n }\n\n if (code === CHAR_QUESTION) {\n push('?');\n i++;\n continue;\n }\n\n if (code === CHAR_COLON) {\n // `::` is a Postgres cast, not a named parameter.\n if (sql.charCodeAt(i + 1) === CHAR_COLON) {\n push('::');\n i += 2;\n continue;\n }\n if (isIdentStart(sql.charCodeAt(i + 1))) {\n i++;\n while (i < length && isIdentPart(sql.charCodeAt(i))) i++;\n push('?');\n continue;\n }\n push(':');\n i++;\n continue;\n }\n\n if (code === CHAR_AT && isIdentStart(sql.charCodeAt(i + 1))) {\n i++;\n while (i < length && isIdentPart(sql.charCodeAt(i))) i++;\n push('?');\n continue;\n }\n\n if (isDigit(code) || (code === CHAR_DOT && isDigit(sql.charCodeAt(i + 1)))) {\n i++;\n while (i < length) {\n const next = sql.charCodeAt(i);\n if (isDigit(next) || next === CHAR_DOT) {\n i++;\n continue;\n }\n if (next === CHAR_LOWER_E || next === CHAR_UPPER_E) {\n const after = sql.charCodeAt(i + 1);\n const signed =\n (after === CHAR_PLUS || after === CHAR_DASH) && isDigit(sql.charCodeAt(i + 2));\n if (isDigit(after) || signed) {\n i += 2;\n continue;\n }\n }\n break;\n }\n push('?');\n continue;\n }\n\n if (isIdentStart(code)) {\n const start = i;\n i++;\n while (i < length && isIdentPart(sql.charCodeAt(i))) i++;\n push(sql.slice(start, i));\n continue;\n }\n\n push(sql[i] ?? '');\n i++;\n }\n\n return out;\n}\n\n// After normalization there is never more than one space between tokens, so\n// `\\s?` is enough in these patterns — which also rules out catastrophic\n// backtracking.\nconst IN_LIST = /\\bIN\\s?\\(\\s?\\?(?:,\\s?\\?)*\\s?\\)/gi;\nconst VALUES_TUPLES = /\\bVALUES\\s?(\\((?:\\?,\\s?)*\\?\\))(?:,\\s?\\((?:\\?,\\s?)*\\?\\))+/gi;\n\n/**\n * Collapses variable-length lists.\n *\n * `IN (?, ?, ?)` and `IN (?)` are the same query with a different number of\n * parameters; otherwise every list length yields its own fingerprint. Same for\n * batched `VALUES`.\n */\nfunction collapseLists(sql: string): string {\n return sql.replace(IN_LIST, 'IN (?)').replace(VALUES_TUPLES, 'VALUES $1');\n}\n\n/**\n * Normalized SQL fingerprint.\n *\n * Literals, numbers, placeholders and `IN (...)` lists of any length collapse\n * to `?`, comments are dropped and whitespace is reduced to single spaces.\n */\nexport function fingerprintSql(sql: string): string {\n const cache = fingerprints();\n const cached = cache.get(sql);\n if (cached !== undefined) return cached;\n\n const result = collapseLists(scan(sql));\n cache.set(sql, result);\n return result;\n}\n\nconst STATEMENT_KEYWORDS: Readonly<Record<string, SqlOperation>> = {\n select: 'select',\n insert: 'insert',\n update: 'update',\n delete: 'delete',\n};\n\n/**\n * Statement type: what the query does at the top level.\n *\n * Subqueries are ignored, so `WITH x AS (SELECT …) DELETE FROM …` is a\n * `delete`, not a `select`. Otherwise the N+1 detector would read a delete in\n * a loop as a repeated read and fire a false positive.\n *\n * Accepts a fingerprint or any SQL — comments and literals are handled.\n */\nexport function sqlOperation(sql: string): SqlOperation {\n const cache = operations();\n const cached = cache.get(sql);\n if (cached !== undefined) return cached;\n\n // The scan is idempotent: on an already normalized fingerprint it changes\n // nothing, while on raw SQL it strips comments and literals that could\n // otherwise contain keywords.\n const normalized = scan(sql);\n const length = normalized.length;\n let result: SqlOperation = 'other';\n let depth = 0;\n let insideCte = false;\n let i = 0;\n\n while (i < length) {\n const code = normalized.charCodeAt(i);\n if (code === CHAR_LPAREN) {\n depth++;\n i++;\n continue;\n }\n if (code === CHAR_RPAREN) {\n depth--;\n i++;\n continue;\n }\n if (!isIdentStart(code)) {\n i++;\n continue;\n }\n\n const start = i;\n while (i < length && isIdentPart(normalized.charCodeAt(i))) i++;\n if (depth > 0) continue;\n\n const word = normalized.slice(start, i).toLowerCase();\n if (word === 'with') {\n insideCte = true;\n continue;\n }\n const statement = STATEMENT_KEYWORDS[word];\n if (statement) {\n result = statement;\n break;\n }\n // First word is neither WITH nor a statement: nothing left to parse.\n if (!insideCte) break;\n }\n\n cache.set(sql, result);\n return result;\n}\n\n/** Clears the caches. Needed by tests and benchmarks. */\nexport function clearSqlCaches(): void {\n fingerprints().clear();\n operations().clear();\n}\n","/**\n * Shared machinery for loop-shaped detectors.\n *\n * N+1 and sequential-HTTP are the same finding over different span kinds:\n * repeats of one fingerprint, sequential in time, from a single line of code.\n * The heuristics live here once, so both detectors treat time and attribution\n * identically.\n */\n\nimport type { Callsite } from '../types.js';\n\n/** What the run heuristics need to know about a span. */\nexport interface TimedSpan {\n readonly id: number;\n readonly startedAt: number;\n readonly duration: number;\n readonly callsite: Callsite | null;\n /**\n * Milliseconds the span spent queueing before it could start.\n *\n * Absent for everything that does not queue. Where it is present it is the\n * difference between when the code *asked* for the work and when the work\n * began — and that difference is what tells a loop apart from a pool.\n */\n readonly waitMs?: number | null;\n}\n\nexport function endOf(span: TimedSpan): number {\n return span.startedAt + span.duration;\n}\n\n/**\n * When the code asked for this work, rather than when it got to run.\n *\n * A pool with one connection turns five queries issued through `Promise.all`\n * into five spans that follow one another exactly like a loop: the same SQL,\n * the same line, no overlap. Judged on when they *ran*, they are an N+1 and\n * the advice would be to parallelise code that is already parallel. Judged on\n * when they were *issued*, they all start at once, which is the truth.\n */\nexport function issuedAt(span: TimedSpan): number {\n return span.startedAt - (span.waitMs ?? 0);\n}\n\n/**\n * Splits a fingerprint group into runs on time gaps.\n *\n * The same call at the start and at the end of handling, separated by a long\n * unrelated operation, is not a loop. Splitting lets each run be judged on\n * its own, and short runs simply fall short of the threshold.\n */\nexport function splitRuns<T extends TimedSpan>(sorted: readonly T[], maxGapMs: number): T[][] {\n const runs: T[][] = [];\n let current: T[] = [];\n let previousEnd = Number.NEGATIVE_INFINITY;\n\n for (const span of sorted) {\n if (current.length > 0 && span.startedAt - previousEnd > maxGapMs) {\n runs.push(current);\n current = [];\n previousEnd = Number.NEGATIVE_INFINITY;\n }\n current.push(span);\n previousEnd = Math.max(previousEnd, endOf(span));\n }\n if (current.length > 0) runs.push(current);\n return runs;\n}\n\n/**\n * Share of adjacent pairs that overlap in time.\n *\n * A loop is a waterfall: each call starts after the previous one finished.\n * Calls issued through `Promise.all` overlap — that is already optimised,\n * nothing to fix.\n *\n * Measured from when each call was issued, not from when it started running:\n * see {@link issuedAt}. For everything that never queues the two are the same\n * number.\n */\nexport function overlapRatio(run: readonly TimedSpan[]): number {\n if (run.length < 2) return 0;\n\n let overlapping = 0;\n for (let i = 1; i < run.length; i++) {\n const previous = run[i - 1];\n const current = run[i];\n if (!previous || !current) continue;\n const overlap =\n Math.min(endOf(previous), endOf(current)) - Math.max(issuedAt(previous), issuedAt(current));\n if (overlap > 0) overlapping++;\n }\n return overlapping / (run.length - 1);\n}\n\n/**\n * The single place in the code the whole run came from.\n *\n * Returns `null` if the known callsites disagree (the same call from\n * different places is a coincidence, not a loop) or if there are none at all:\n * a finding without a line of code reports a problem but does not help fix it.\n */\nexport function singleCallsite(run: readonly TimedSpan[]): Callsite | null {\n let found: Callsite | null = null;\n for (const span of run) {\n const callsite = span.callsite;\n if (!callsite) continue;\n if (!found) {\n found = callsite;\n continue;\n }\n if (found.file !== callsite.file || found.line !== callsite.line) return null;\n }\n return found;\n}\n","/**\n * N+1 detector — Reqray's flagship finding.\n *\n * The governing principle here is not up for debate: **a false positive is\n * worse than a miss**. A tool that cries wolf gets switched off within a week.\n * So every heuristic below discards cases where the repeats have a plausible\n * explanation, even at the cost of missing some real N+1s.\n */\n\nimport { sqlOperation } from '../sql.js';\nimport type { DbSpan, Finding, FindingSeverity, Span } from '../types.js';\nimport { overlapRatio, singleCallsite, splitRuns } from './runs.js';\nimport type { Detector } from './types.js';\n\n/** Detector thresholds. All exposed as options — the user tunes them. */\nexport interface NPlusOneOptions {\n /** How many consecutive repeats make a group suspicious. */\n readonly threshold: number;\n /** Below this saving there is nothing worth reporting. */\n readonly minWastedMs: number;\n /**\n * Share of adjacent pairs overlapping in time above which the queries are\n * treated as parallel rather than as a loop.\n */\n readonly maxOverlapRatio: number;\n /**\n * Gap between adjacent repeats above which this is no longer one loop but\n * two different places that happened to run the same query.\n */\n readonly maxGapMs: number;\n}\n\nconst SEVERITY_CRITICAL_MS = 200;\nconst SEVERITY_WARN_MS = 50;\n\nconst TABLE_FROM_SQL = /\\bFROM\\s+\"?([\\w$.]+)\"?/i;\n\nfunction isDbSpan(span: Span): span is DbSpan {\n return span.kind === 'db';\n}\n\n/**\n * Groups SELECT spans by fingerprint.\n *\n * Batched `INSERT`/`UPDATE` is normal practice and must not be flagged, so\n * everything but `select` is dropped up front.\n */\nfunction groupSelects(spans: readonly Span[]): Map<string, DbSpan[]> {\n const groups = new Map<string, DbSpan[]>();\n for (const span of spans) {\n if (!isDbSpan(span)) continue;\n if (sqlOperation(span.fingerprint) !== 'select') continue;\n\n const existing = groups.get(span.fingerprint);\n if (existing) existing.push(span);\n else groups.set(span.fingerprint, [span]);\n }\n return groups;\n}\n\nfunction severityFor(costMs: number): FindingSeverity {\n if (costMs >= SEVERITY_CRITICAL_MS) return 'critical';\n if (costMs >= SEVERITY_WARN_MS) return 'warn';\n return 'info';\n}\n\nfunction hintFor(source: string | null, fingerprint: string): string {\n const table = TABLE_FROM_SQL.exec(fingerprint)?.[1] ?? 'the related table';\n\n switch (source) {\n case 'prisma':\n return `Prisma: pull \"${table}\" in with \\`include\\` on the parent query — one JOIN instead of a series of queries`;\n case 'drizzle':\n return `Drizzle: pull \"${table}\" in with \\`with\\` on the parent query`;\n case 'typeorm':\n return `TypeORM: list \"${table}\" in the parent query's \\`relations\\``;\n default:\n return `Collect the ids and fetch \"${table}\" with a single \\`WHERE … IN (…)\\` instead of a query per iteration`;\n }\n}\n\nconst LIMIT = /\\bLIMIT\\b/i;\n\n/**\n * Whether the run is one table being read a page at a time.\n *\n * `WHERE id > $1 ORDER BY id LIMIT 500` in a loop is the same SQL from the\n * same line, one after another — everything an N+1 is, except that it is the\n * fix rather than the problem: the alternative is one query for the whole\n * table. What gives it away is the shape of the answers: every page full, the\n * same size, until the last one. A lookup per parent row does not come back\n * like that unless every parent has exactly as many children as the limit,\n * and then \"fetch them with one IN\" would be the wrong advice anyway.\n *\n * A limit of one is left alone: that is `findFirst` in a loop, the most\n * common N+1 there is.\n */\nfunction isPaging(run: readonly DbSpan[], fingerprint: string): boolean {\n if (!LIMIT.test(fingerprint)) return false;\n\n const pageSize = run[0]?.rowCount ?? null;\n if (pageSize === null || pageSize < 2) return false;\n\n const last = run.length - 1;\n for (let i = 0; i < last; i++) {\n if (run[i]?.rowCount !== pageSize) return false;\n }\n const tail = run[last]?.rowCount ?? null;\n return tail !== null && tail <= pageSize;\n}\n\nfunction evaluate(\n run: readonly DbSpan[],\n fingerprint: string,\n options: NPlusOneOptions,\n): Finding | null {\n if (run.length < options.threshold) return null;\n if (isPaging(run, fingerprint)) return null;\n if (overlapRatio(run) > options.maxOverlapRatio) return null;\n\n const callsite = singleCallsite(run);\n if (!callsite) return null;\n\n let totalMs = 0;\n let slowestMs = 0;\n for (const span of run) {\n totalMs += span.duration;\n if (span.duration > slowestMs) slowestMs = span.duration;\n }\n\n // The fix does not remove the query altogether — it replaces the run with a\n // single query. Its cost is taken to be the slowest query of the run: a\n // deliberately conservative estimate, since we must never promise more saved\n // time than actually exists.\n const costMs = totalMs - slowestMs;\n if (costMs < options.minWastedMs) return null;\n\n const first = run[0];\n return {\n detector: 'n_plus_one',\n severity: severityFor(costMs),\n title: `${run.length} identical queries ran in a loop`,\n costMs,\n callsite,\n evidence: {\n kind: 'n_plus_one',\n repeats: run.length,\n fingerprint,\n sample: first ? first.sql : fingerprint,\n totalMs,\n spanIds: run.map((span) => span.id),\n },\n hint: hintFor(first?.source ?? null, fingerprint),\n };\n}\n\nexport const nPlusOne: Detector<NPlusOneOptions> = {\n id: 'n_plus_one',\n\n defaultOptions: {\n threshold: 5,\n minWastedMs: 20,\n maxOverlapRatio: 0.2,\n maxGapMs: 100,\n },\n\n run(scope, options) {\n const findings: Finding[] = [];\n\n for (const [fingerprint, spans] of groupSelects(scope.spans)) {\n // The whole group is below the threshold, so no run inside it can pass.\n if (spans.length < options.threshold) continue;\n\n spans.sort((a, b) => a.startedAt - b.startedAt || a.id - b.id);\n for (const run of splitRuns(spans, options.maxGapMs)) {\n const finding = evaluate(run, fingerprint, options);\n if (finding) findings.push(finding);\n }\n }\n\n return findings;\n },\n};\n","/**\n * Where a request's time went.\n *\n * The panel answers \"the database took 41 ms\". It does not answer \"and where\n * did the other 400 ms go\", which for a Node backend is the more common\n * question. This module answers it, once, in the core: the API, the panel and\n * the terminal client read the same number rather than each deriving its own\n * from the span tree.\n *\n * Everything here is an interval union rather than a sum. Adding span\n * durations up is the mistake that makes a `Promise.all` of four 100 ms\n * queries read as 400 ms of database time inside a 120 ms request — a number\n * that is not merely imprecise but larger than the request that contains it.\n */\n\nimport type { HandlerSpan, MiddlewareSpan, RecordedRequest, RequestTiming, Span } from './types.js';\nimport { weightOf } from './weight.js';\n\n/** A stretch of the request's clock, in milliseconds from its start. */\ninterface Interval {\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * A span that holds other work rather than doing any.\n *\n * Exported because the same distinction decides three different questions —\n * what counts as coverage, what a self time is measured against, and what an\n * unaccounted stretch sits inside — and a second definition of \"container\"\n * is how the three drift apart.\n */\nexport function isContainer(span: Span): span is MiddlewareSpan | HandlerSpan {\n return span.kind === 'handler' || span.kind === 'middleware';\n}\n\nfunction intervalOf(span: Span): Interval {\n return { start: span.startedAt, end: span.startedAt + span.duration };\n}\n\n/**\n * The same stretches with overlaps merged away.\n *\n * @param intervals in any order; the result is sorted and disjoint.\n */\nexport function mergeIntervals(intervals: readonly Interval[]): Interval[] {\n if (intervals.length === 0) return [];\n const sorted = [...intervals].sort((a, b) => a.start - b.start);\n const merged: Interval[] = [];\n let current = sorted[0] as Interval;\n for (const interval of sorted.slice(1)) {\n if (interval.start <= current.end) {\n current = { start: current.start, end: Math.max(current.end, interval.end) };\n } else {\n merged.push(current);\n current = interval;\n }\n }\n merged.push(current);\n return merged;\n}\n\n/** How much of the clock these stretches cover, counting overlaps once. */\nexport function coveredMs(intervals: readonly Interval[]): number {\n let total = 0;\n for (const interval of mergeIntervals(intervals)) total += interval.end - interval.start;\n return total;\n}\n\n/** Whether any two of them ran at the same time. */\nexport function anyOverlap(intervals: readonly Interval[]): boolean {\n const sorted = [...intervals].sort((a, b) => a.start - b.start);\n for (let index = 1; index < sorted.length; index++) {\n const previous = sorted[index - 1] as Interval;\n const current = sorted[index] as Interval;\n // Touching is not overlapping: one query ending exactly where the next\n // begins is a sequence, and a rounding tie must not read as concurrency.\n if (current.start < previous.end) return true;\n }\n return false;\n}\n\n/** How much of `outer` the stretches cover. */\nfunction coveredWithin(outer: Interval, intervals: readonly Interval[]): number {\n let total = 0;\n for (const interval of mergeIntervals(intervals)) {\n const start = Math.max(outer.start, interval.start);\n const end = Math.min(outer.end, interval.end);\n if (end > start) total += end - start;\n }\n return total;\n}\n\n/**\n * Time each span spent in its *own* code, by span id.\n *\n * A span's duration minus the stretch its children occupied — where children\n * that ran concurrently count once, and a child reaching outside its parent\n * (a clock that moved, a span closed late) counts only for the part inside.\n *\n * This is the number that answers \"what did the work\", and the reason the\n * panel does not rank by total: the handler is always at the top of that\n * list, because it contains everything and did nothing.\n */\nexport function selfTimes(spans: readonly Span[]): Map<number, number> {\n const children = new Map<number, Interval[]>();\n for (const span of spans) {\n if (span.parentId === null) continue;\n const list = children.get(span.parentId);\n if (list) list.push(intervalOf(span));\n else children.set(span.parentId, [intervalOf(span)]);\n }\n\n const self = new Map<number, number>();\n for (const span of spans) {\n const own = children.get(span.id);\n const covered = own ? coveredWithin(intervalOf(span), own) : 0;\n self.set(span.id, Math.max(0, span.duration - covered));\n }\n return self;\n}\n\n/**\n * Where the request's time went, as the header line reads it.\n *\n * `sqlMs`, `externalMs` and `cacheMs` are unions within their own kind, so\n * each is what that layer actually cost. They can still sum past the wall\n * clock when a query and an outgoing call overlapped, which is why `parallel`\n * travels with them: the panel says so rather than printing an addition that\n * does not add up.\n */\nexport function timingOf(spans: readonly Span[], durationMs: number): RequestTiming {\n const work = spans.filter((span) => !isContainer(span));\n const byKind = (kind: Span['kind']): Interval[] =>\n work.filter((span) => span.kind === kind).map(intervalOf);\n\n const all = work.map(intervalOf);\n const covered = coveredMs(all);\n\n return {\n sqlMs: coveredMs(byKind('db')),\n externalMs: coveredMs(byKind('http')),\n cacheMs: coveredMs(byKind('cache')),\n // Clamped: a span may finish a hair after the response is written, and a\n // negative \"your code\" would be read as a bug in the reader, not in us.\n selfMs: Math.max(0, durationMs - covered),\n parallel: anyOverlap(all),\n };\n}\n\n/**\n * The record with its timing filled in.\n *\n * Records written before this existed are still in stores on disk, and a\n * panel that shows a blank header for yesterday's request would be reporting\n * its own age as the request's fault. Computed on read, and only for those.\n */\nexport function ensureTiming(request: RecordedRequest): RecordedRequest {\n // Typed as required because they are required of anything written from now\n // on; what arrives from a store may predate them, and that is this case.\n const stored = request as Partial<RecordedRequest>;\n if (stored.timing !== undefined && stored.weight !== undefined && stored.cost !== undefined)\n return request;\n const self = selfTimes(request.spans);\n return {\n ...request,\n timing: stored.timing ?? timingOf(request.spans, request.durationMs),\n // Nothing was measuring the loop when this was written, and nothing can\n // work out afterwards what it was doing.\n host: request.host ?? null,\n // Weight, unlike the loop, is entirely derivable from what was stored.\n weight: stored.weight ?? weightOf(request),\n // Nothing was reading the processor clock when this was written, and no\n // arithmetic afterwards can recover what it said.\n cost: stored.cost ?? null,\n spans: request.spans.map((span) => ({ ...span, selfMs: self.get(span.id) ?? span.duration })),\n };\n}\n","/**\n * Pool-wait detector: the query did not take that long, it queued for that\n * long.\n *\n * This is the failure a waterfall is worst at showing. A query that waited\n * 338 ms for a free connection and then ran for 2 draws exactly like a query\n * that worked for 340, and the reader goes off to add an index that will not\n * help. The instrumentation measures the queue separately (`waitMs` on the\n * span); this detector is what says out loud that the queue, not the query,\n * was the request's problem.\n *\n * Two things keep it quiet.\n *\n * The driver only records a wait when the pool was genuinely saturated —\n * every connection in use and none left to create. A brand-new connection\n * being established, or an idle one handed over a tick later, is not a\n * queue, and reporting either would send somebody to change `max` when the\n * fix is elsewhere.\n *\n * And waits are counted as a union of intervals, never a sum. Five queries\n * issued through `Promise.all` queue at the same time, and adding their waits\n * together would claim a saving five times the size of the one that exists.\n *\n * The comparison that decides whether to speak — did it wait longer than it\n * ran — is made per query rather than on the totals, and for the same reason\n * in reverse: a saturated pool runs the queries behind the queue one after\n * another, so their durations add up to the whole request. Weighed against\n * that sum, the clearest case of contention there is comes out a coin flip.\n */\n\nimport { coveredMs } from '../timing.js';\nimport type { DbSpan, Finding, FindingSeverity, Span } from '../types.js';\nimport type { Detector } from './types.js';\n\nexport interface PoolWaitOptions {\n /** Below this, the queue is not the story of the request. */\n readonly minWaitMs: number;\n /**\n * How much of a query's wait must exceed its own run for it to count.\n *\n * At `1` the rule is the one the panel states: it waited longer than it\n * ran. Anything below that is a busy pool doing its job.\n *\n * Applied per query, never to the totals. A pool that serialises five\n * queries makes their run times add up to the whole request, and comparing\n * that sum against the waits would turn the plainest case of contention\n * into a coin flip decided by a couple of milliseconds.\n */\n readonly minRatio: number;\n}\n\n/** A quarter of a second in a queue is not a busy moment, it is a shortage. */\nconst SEVERITY_CRITICAL_MS = 250;\n\nfunction isDb(span: Span): span is DbSpan {\n return span.kind === 'db';\n}\n\nfunction severityFor(waitMs: number): FindingSeverity {\n return waitMs >= SEVERITY_CRITICAL_MS ? 'critical' : 'warn';\n}\n\nconst HINT =\n 'The pool had nothing free to give: every connection was in use and it was already at its limit. ' +\n 'Usually the fix is upstream — a transaction held open across an external call, or a query that runs far longer than it needs to. ' +\n 'Raising `max` helps only if the database can take the extra connections.';\n\nexport const poolWait: Detector<PoolWaitOptions> = {\n id: 'pool_wait',\n\n defaultOptions: {\n // Fifty milliseconds is where a queue stops being scheduling noise and\n // starts being something a reader can act on.\n minWaitMs: 50,\n minRatio: 1,\n },\n\n run(scope, options): Finding[] {\n const waited: DbSpan[] = [];\n for (const span of scope.spans) {\n if (!isDb(span)) continue;\n const wait = span.waitMs;\n if (wait === null || wait <= 0) continue;\n // Only the queries the queue, rather than the database, held up.\n if (wait <= span.duration * options.minRatio) continue;\n waited.push(span);\n }\n if (waited.length === 0) return [];\n\n // Concurrent queries queue concurrently: the request lost the union of\n // the waits, not their sum.\n const waitMs = coveredMs(\n waited.map((span) => ({ start: span.startedAt - (span.waitMs ?? 0), end: span.startedAt })),\n );\n if (waitMs < options.minWaitMs) return [];\n\n const runMs = coveredMs(\n waited.map((span) => ({ start: span.startedAt, end: span.startedAt + span.duration })),\n );\n\n let worst = waited[0] as DbSpan;\n for (const span of waited) {\n if ((span.waitMs ?? 0) > (worst.waitMs ?? 0)) worst = span;\n }\n\n const queries = waited.length;\n return [\n {\n detector: 'pool_wait',\n severity: severityFor(waitMs),\n title: `${queries === 1 ? 'A query' : `${queries} queries`} waited ${Math.round(waitMs)} ms for a free connection`,\n // Real time, and this request's own: had a connection been free, it\n // would have started that much sooner.\n costMs: waitMs,\n callsite: worst.callsite,\n evidence: {\n kind: 'pool_wait',\n waitMs,\n runMs,\n queries,\n sample: worst.sql.replace(/\\s+/g, ' ').trim(),\n spanIds: waited.map((span) => span.id),\n },\n hint: HINT,\n },\n ];\n },\n};\n","/**\n * Fingerprint of an outgoing HTTP call.\n *\n * The counterpart of `fingerprintSql` for the sequential-HTTP detector: calls\n * to `/users/1/orders` and `/users/2/orders` must collapse into one shape,\n * otherwise a loop over ids is invisible. Variable path segments — numbers,\n * uuids, long hex — become `:id`; the query string is dropped entirely\n * (its values are almost always the varying part).\n */\n\nimport { globalSlot, TwoGenerationCache } from './state.js';\n\nconst NUMERIC = /^\\d+$/;\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst HEX = /^[0-9a-f]{8,}$/i;\n\nfunction normalizeSegment(segment: string): string {\n if (NUMERIC.test(segment) || UUID.test(segment) || HEX.test(segment)) return ':id';\n return segment;\n}\n\nconst CACHE_LIMIT = 5_000;\n\n/**\n * Process-wide cache: the same URL string is fingerprinted once.\n *\n * In the shared registry rather than in a module variable, for the same reason\n * everything else is: this is read on every outgoing call, and a dual ESM/CJS\n * load would otherwise give two caches with the same ceiling and half the hits\n * each.\n */\nconst cache = globalSlot(\n 'http.fingerprints',\n () => new TwoGenerationCache<string, string>(CACHE_LIMIT),\n);\n\n/**\n * Reduces an outgoing call to its shape: `GET api.example.com/users/:id/orders`.\n *\n * Never throws; an unparseable URL is used as-is.\n */\nexport function fingerprintHttp(method: string, url: string): string {\n const key = `${method} ${url}`;\n const fingerprints = cache();\n const cached = fingerprints.get(key);\n if (cached) return cached;\n\n let fingerprint: string;\n try {\n const parsed = new URL(url);\n const path = parsed.pathname.split('/').map(normalizeSegment).join('/');\n fingerprint = `${method.toUpperCase()} ${parsed.host}${path}`;\n } catch {\n fingerprint = `${method.toUpperCase()} ${url}`;\n }\n\n fingerprints.set(key, fingerprint);\n return fingerprint;\n}\n\n/** Clears the fingerprint cache. Needed by tests. */\nexport function clearHttpFingerprints(): void {\n cache().clear();\n}\n","/**\n * Sequential-HTTP detector: N+1 for outgoing calls.\n *\n * A loop of `await fetch(...)` over a list of ids is the same disease as a\n * query in a loop — each call waits for the previous one for no reason. The\n * heuristics are deliberately identical to the N+1 detector's, and the same\n * principle governs: **a false positive is worse than a miss**.\n *\n * What is intentionally NOT flagged:\n * - calls to *different* URLs in sequence: whether B needs A's response is\n * invisible from timing, and \"parallelize this\" on a dependent chain is a lie;\n * - overlapping calls — that is `Promise.all`, already optimised;\n * - repeats from different lines of code — a coincidence, not a loop;\n * - runs dominated by failures (5xx, 429, network errors) — that is a retry\n * loop, and retries are *supposed* to be sequential.\n */\n\nimport { fingerprintHttp } from '../http-fingerprint.js';\nimport type { Finding, FindingSeverity, HttpSpan, Span } from '../types.js';\nimport { overlapRatio, singleCallsite, splitRuns } from './runs.js';\nimport type { Detector } from './types.js';\n\n/** Detector thresholds. All exposed as options — the user tunes them. */\nexport interface SequentialHttpOptions {\n /** How many consecutive calls of one shape make a run suspicious. */\n readonly threshold: number;\n /** Below this saving there is nothing worth reporting. */\n readonly minWastedMs: number;\n /** Share of overlapping adjacent pairs above which the run is parallel. */\n readonly maxOverlapRatio: number;\n /** Gap between calls above which the run is not one loop. */\n readonly maxGapMs: number;\n}\n\nconst SEVERITY_CRITICAL_MS = 300;\nconst SEVERITY_WARN_MS = 100;\n\nfunction isHttpSpan(span: Span): span is HttpSpan {\n return span.kind === 'http';\n}\n\n/**\n * A retry, not a loop: the call failed at the transport level, hit a 5xx or\n * ran into rate limiting. Sequential retries are correct behaviour.\n */\nfunction looksLikeRetry(span: HttpSpan): boolean {\n if (span.error) return true;\n if (span.statusCode === null) return true;\n return span.statusCode >= 500 || span.statusCode === 429;\n}\n\nfunction groupCalls(spans: readonly Span[]): Map<string, HttpSpan[]> {\n const groups = new Map<string, HttpSpan[]>();\n for (const span of spans) {\n if (!isHttpSpan(span)) continue;\n if (looksLikeRetry(span)) continue;\n\n const fingerprint = fingerprintHttp(span.method, span.url);\n const existing = groups.get(fingerprint);\n if (existing) existing.push(span);\n else groups.set(fingerprint, [span]);\n }\n return groups;\n}\n\nfunction severityFor(costMs: number): FindingSeverity {\n if (costMs >= SEVERITY_CRITICAL_MS) return 'critical';\n if (costMs >= SEVERITY_WARN_MS) return 'warn';\n return 'info';\n}\n\nfunction evaluate(\n run: readonly HttpSpan[],\n fingerprint: string,\n options: SequentialHttpOptions,\n): Finding | null {\n if (run.length < options.threshold) return null;\n if (overlapRatio(run) > options.maxOverlapRatio) return null;\n\n const callsite = singleCallsite(run);\n if (callsite === null) return null;\n\n let totalMs = 0;\n let slowestMs = 0;\n for (const span of run) {\n totalMs += span.duration;\n if (span.duration > slowestMs) slowestMs = span.duration;\n }\n\n // Parallel execution is bounded by the slowest call, so the honest saving\n // is everything above it — never more than actually exists.\n const costMs = totalMs - slowestMs;\n if (costMs < options.minWastedMs) return null;\n\n const first = run[0];\n return {\n detector: 'sequential_http',\n severity: severityFor(costMs),\n title: `${run.length} HTTP calls ran sequentially`,\n costMs,\n callsite,\n evidence: {\n kind: 'sequential_http',\n repeats: run.length,\n fingerprint,\n sample: first ? `${first.method} ${first.url}` : fingerprint,\n totalMs,\n spanIds: run.map((span) => span.id),\n },\n hint:\n 'Calls of one shape from one place can run in parallel: `Promise.all(items.map(…))`. ' +\n 'Better yet — a batch endpoint, if the API offers one: a single call instead of a series.',\n };\n}\n\nexport const sequentialHttp: Detector<SequentialHttpOptions> = {\n id: 'sequential_http',\n\n defaultOptions: {\n // HTTP calls are an order of magnitude dearer than queries, so the bar is\n // lower than the N+1 detector's.\n threshold: 3,\n minWastedMs: 30,\n maxOverlapRatio: 0.2,\n maxGapMs: 100,\n },\n\n run(scope, options) {\n const findings: Finding[] = [];\n\n for (const [fingerprint, spans] of groupCalls(scope.spans)) {\n if (spans.length < options.threshold) continue;\n\n spans.sort((a, b) => a.startedAt - b.startedAt || a.id - b.id);\n for (const run of splitRuns(spans, options.maxGapMs)) {\n const finding = evaluate(run, fingerprint, options);\n if (finding) findings.push(finding);\n }\n }\n\n return findings;\n },\n};\n","/**\n * Budget detector: this request took longer than the page can afford.\n *\n * The other detectors name a specific mistake. This one names a fact — the\n * request went over budget — and then says where the time went, because\n * \"slow\" without a direction is not worth a card. It only fires when the\n * request is genuinely over the line, so the screen stays quiet on a healthy\n * session.\n */\n\nimport type { RequestScope } from '../scope.js';\nimport { coveredMs, timingOf } from '../timing.js';\nimport type { Finding } from '../types.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\nexport interface SlowBudgetOptions {\n /** Wall time above which a request is over budget, milliseconds. */\n readonly budgetMs: number;\n}\n\n/**\n * Where the time went — the same arithmetic the header line uses.\n *\n * Unions rather than sums, so a `Promise.all` of four 200 ms calls inside a\n * 300 ms request is 300 ms of waiting and not 800 ms of it. A hint drawn from\n * a figure larger than the request it describes is worse than no hint.\n */\nfunction breakdown(scope: RequestScope, durationMs: number) {\n return timingOf(scope.spans, durationMs);\n}\n\n/**\n * Of the time spent in the database layer, how much was spent queueing.\n *\n * A union, like everything else here: queries issued together queue together.\n */\nfunction queuedMs(scope: RequestScope): number {\n const waits: Array<{ start: number; end: number }> = [];\n for (const span of scope.spans) {\n if (span.kind !== 'db' || !span.waitMs) continue;\n waits.push({ start: span.startedAt - span.waitMs, end: span.startedAt });\n }\n return waits.length === 0 ? 0 : coveredMs(waits);\n}\n\n/** Above this share, the queue rather than the layer is what to look at. */\nconst MOSTLY_QUEUE = 0.5;\n\nexport const slowBudget: Detector<SlowBudgetOptions> = {\n id: 'slow_budget',\n\n defaultOptions: {\n // The number the panel already treats as \"red\" in the duration column.\n budgetMs: 700,\n },\n\n run(scope: RequestScope, options: SlowBudgetOptions, request: FinishedRequest): Finding[] {\n if (request.durationMs <= options.budgetMs) return [];\n\n const timing = breakdown(scope, request.durationMs);\n const share = (ms: number) => Math.round((ms / request.durationMs) * 100);\n\n // The layer that actually holds the time leads the hint — the largest\n // one, not the first one that is above zero. A request that spent 99% of\n // itself in application code must not be sent to look at the one query\n // that took a millisecond.\n const layers: Array<[string, number]> = [\n ['external HTTP calls', timing.externalMs],\n ['SQL', timing.sqlMs],\n ['the cache', timing.cacheMs],\n ];\n const [label, ms] = layers.reduce((most, layer) => (layer[1] > most[1] ? layer : most));\n\n // A layer can hold the time without being the reason for it. Queries\n // that spent most of their lives waiting for a free connection put the\n // whole wait under \"SQL\", and sending the reader to the queries would be\n // sending them past the finding directly above this one.\n const queued = label === 'SQL' ? queuedMs(scope) : 0;\n\n const hint =\n ms <= timing.selfMs\n ? `Most of the time (${share(timing.selfMs)}%) is not covered by any instrumentation: it is application code, a timer, or something Reqray does not see.`\n : queued > ms * MOSTLY_QUEUE\n ? `${share(ms)}% of the time went to SQL — but ${share(queued)}% of the request was queueing for a free connection, not querying. The pool is the constraint, not the query.`\n : `${share(ms)}% of the time went to ${label} — start there.`;\n\n return [\n {\n detector: 'slow_budget',\n severity: 'warn',\n title: `Over the ${options.budgetMs} ms budget`,\n // The overshoot: what would have to go for the request to fit.\n costMs: request.durationMs - options.budgetMs,\n callsite: null,\n evidence: {\n kind: 'budget',\n durationMs: request.durationMs,\n budgetMs: options.budgetMs,\n externalMs: timing.externalMs,\n sqlMs: timing.sqlMs,\n spanIds: [],\n },\n hint,\n },\n ];\n },\n};\n","/**\n * Slow-code detector: the stretch of a request nothing accounts for.\n *\n * Every other detector names something Reqray watched happen — a query, an\n * outgoing call, a connection held open too long. This one names the\n * opposite: a stretch where nothing it watches was running at all. That is\n * the answer a waterfall gives worst, because the evidence for it is an empty\n * space, and it is the most common answer for a Node backend once the\n * database has been ruled out.\n *\n * The whole difficulty is that an empty space has two explanations — code\n * that ran, or I/O Reqray has no instrumentation for — and only one of them is\n * worth telling somebody about. Coverage is how they are told apart: if the\n * rest of the request was well accounted for, then Reqray does see this\n * application's I/O, and a hole in it is the application's own work. If it\n * was not, Reqray is blind to this process and says nothing, because a tool\n * that blames your code for its own blind spot is a tool nobody keeps\n * installed.\n *\n * What it deliberately does not claim is CPU. The process knows how far\n * behind its event loop was, but never which request put it there — under\n * concurrency the code that blocked the loop is usually somebody else's, so\n * the finding reports a stretch of the request's own wall clock and leaves\n * the loop to the host monitor, which measures the process and says so.\n */\n\nimport type { RequestScope } from '../scope.js';\nimport { coveredMs, isContainer } from '../timing.js';\nimport type { Finding, HandlerSpan, MiddlewareSpan, Span } from '../types.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\nexport interface SlowCodeOptions {\n /** Shortest stretch worth reporting, milliseconds. */\n readonly minMs: number;\n /** What share of the request the stretch has to be, 0..1. */\n readonly minShare: number;\n /**\n * How much of the request's unaccounted time this one stretch has to be,\n * 0..1.\n *\n * The guard against blaming the application for an uninstrumented driver,\n * and the one that actually separates the two cases. A process Reqray cannot\n * see is not slow in one place — it is full of holes, one per call it has\n * no instrumentation for. A process Reqray can see, with one slow function\n * in it, has exactly one. So the question is not how much was covered but\n * whether the silence is concentrated: one long stretch is a thing that\n * happened, and a dozen comparable ones are a blind spot.\n */\n readonly minDominance: number;\n /**\n * Instrumented spans the request must have before any of this is evidence.\n *\n * One is the honest floor: it proves instrumentation was live for this\n * request, which is the difference between a hole in the record and no\n * record at all. A request with nothing in it says nothing about the code.\n */\n readonly minSpans: number;\n}\n\n/** An interval of the request, in milliseconds from its start. */\ninterface Interval {\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * A stretch of the request with no instrumented work in it, and its edges.\n *\n * The neighbours travel with it because they are the whole address: an\n * unaccounted stretch has no callsite of its own, and \"between the query at\n * orders.ts:47 and the call at mailer.ts:12\" is the closest thing to a line\n * number that the absence of evidence can honestly produce.\n */\ninterface Stretch {\n readonly start: number;\n readonly end: number;\n /** The span that finished before it, or `null` when it opens the request. */\n readonly before: Span | null;\n /** The span that ends it, or `null` when the request ends with it. */\n readonly after: Span | null;\n}\n\n/**\n * What a span was doing, for the line that brackets the stretch.\n *\n * The same shapes the other detectors quote, so a reader who has seen one\n * sample has seen them all.\n */\nfunction describe(span: Span): string {\n if (span.kind === 'db') return span.sql.replace(/\\s+/g, ' ').trim();\n if (span.kind === 'http') return `${span.method} ${span.url}`;\n if (span.kind === 'cache') return `${span.command ?? span.operation} ${span.key}`;\n return span.label;\n}\n\n/**\n * The stretch a span occupies, with a query's queueing counted as occupied.\n *\n * Time spent waiting for a free connection is the one idle-looking stretch of\n * a request that is fully accounted for; calling it unaccounted would hide an\n * answer the pool-wait detector already gives behind the word for \"no\n * answer\".\n */\nfunction occupied(span: Span): Interval {\n const wait = span.kind === 'db' ? (span.waitMs ?? 0) : 0;\n return { start: span.startedAt - wait, end: span.startedAt + span.duration };\n}\n\n/**\n * Every unaccounted stretch, in order.\n *\n * A sweep rather than a comparison of every span against every other: at five\n * hundred spans the quadratic version is the detector that costs more than\n * what it measures.\n */\nfunction stretchesOf(work: readonly Span[], durationMs: number): Stretch[] {\n const ordered = work\n .map((span) => ({ span, at: occupied(span) }))\n .sort((a, b) => a.at.start - b.at.start);\n\n const stretches: Stretch[] = [];\n let cursor = 0;\n let previous: Span | null = null;\n\n for (const { span, at } of ordered) {\n if (at.start > cursor) {\n stretches.push({ start: cursor, end: at.start, before: previous, after: span });\n }\n // Only a span that reaches further than everything before it moves the\n // cursor, and only that span is the one a later stretch follows.\n if (at.end > cursor) {\n cursor = at.end;\n previous = span;\n }\n }\n\n if (durationMs > cursor) {\n stretches.push({ start: cursor, end: durationMs, before: previous, after: null });\n }\n return stretches;\n}\n\n/**\n * The innermost handler or middleware the stretch sits inside.\n *\n * Innermost because that is the one that names something: every stretch is\n * inside the handler, and being told the time was spent in the request is not\n * being told anything.\n */\nfunction containerAround(\n spans: readonly Span[],\n stretch: Stretch,\n): MiddlewareSpan | HandlerSpan | null {\n let found: MiddlewareSpan | HandlerSpan | null = null;\n for (const span of spans) {\n if (!isContainer(span)) continue;\n const at = occupied(span);\n if (at.start > stretch.start || at.end < stretch.end) continue;\n if (!found || span.duration < found.duration) found = span;\n }\n return found;\n}\n\n/**\n * Where to send the reader.\n *\n * The span *after* the stretch, in preference to the one before it: the code\n * that ran during the hole is the code that led up to the next call, so its\n * callsite is the bottom of the stretch rather than the top of it. A trailing\n * stretch has no next call, and then the last thing that ran is the best\n * address there is.\n */\nfunction callsiteFor(stretch: Stretch, container: Span | null) {\n return stretch.after?.callsite ?? container?.callsite ?? stretch.before?.callsite ?? null;\n}\n\n/** A response big enough that writing it is a candidate for the time itself. */\nconst HEAVY_TAIL_BYTES = 1024 * 1024;\n\n/**\n * Whether the stretch can be called code without hedging.\n *\n * It can when instrumented work sits on both sides of it: the silence is then\n * demonstrably *between* two things Reqray watched happen, which is where\n * application code runs. At either edge of a request it is not — a leading\n * stretch shares its ground with parsing and middleware Reqray never saw, a\n * trailing one with serializing and writing the response — so an edge keeps\n * the hedge whatever the arithmetic says.\n *\n * Deliberately structural rather than a ratio. Coverage is the obvious\n * measure and it inverts exactly where it matters: the more completely the\n * stretch fills the request, the smaller the window the ratio is computed\n * over, so the clearest cases come out the least certain.\n */\nfunction bracketed(stretch: Stretch): boolean {\n return stretch.before !== null && stretch.after !== null;\n}\n\n/**\n * What to do about it.\n *\n * Three readings, because the same hole means three different things\n * depending on where it sits and how much Reqray can see around it — and a\n * hint that reads the same in all three is a hint nobody acts on.\n */\nfunction hintFor(stretch: Stretch, request: FinishedRequest): string {\n const trailing = stretch.after === null;\n\n if (trailing && request.bytesOut !== null && request.bytesOut >= HEAVY_TAIL_BYTES) {\n return `It is the last thing the request does and the response is ${Math.round(request.bytesOut / 1024)} KB — serializing that and writing it to the socket is the first thing to rule out.`;\n }\n\n if (bracketed(stretch)) {\n return 'Instrumented work sits on both sides of it, so the time is the application’s own: a loop, a parse, a crypto or compression call, or something waiting on a timer.';\n }\n\n return 'This is either the application’s own work or I/O Reqray has no instrumentation for. It covers SQL, outgoing HTTP and the cache — if this request also talks to something else, that is the first place to look.';\n}\n\nexport const slowCode: Detector<SlowCodeOptions> = {\n id: 'slow_code',\n\n defaultOptions: {\n // A tenth of a second: long enough that a person waiting notices it, and\n // far enough above ordinary scheduling jitter that the detector is not\n // reporting the event loop's own heartbeat back as a defect.\n minMs: 100,\n // Under a third of the request, something else is the story — and the\n // budget detector is already the place where \"it was slow\" gets said.\n minShare: 0.3,\n // Seven tenths of the silence in one place. Below that the request has\n // several comparable holes, which is what a process Reqray cannot see\n // looks like, and picking the largest of them would be picking one call\n // out of a driver it does not support and calling it your code.\n minDominance: 0.7,\n // Enough to know instrumentation was live for this request. More would\n // exclude the plainest case there is — one query, then a long wait on\n // something that is not the database.\n minSpans: 1,\n },\n\n run(scope: RequestScope, options: SlowCodeOptions, request: FinishedRequest): Finding[] {\n if (request.durationMs <= 0) return [];\n\n const work = scope.spans.filter((span) => !isContainer(span));\n // Too little watched work for coverage to be evidence of anything. An\n // application whose database Reqray does not instrument looks exactly like\n // an application that does everything in a loop, and the difference\n // cannot be recovered from a request this thin.\n if (work.length < options.minSpans) return [];\n\n const stretches = stretchesOf(work, request.durationMs);\n if (stretches.length === 0) return [];\n\n // The largest single stretch, never the sum of them: forty scattered\n // milliseconds of ordinary async overhead add up to a number that looks\n // like a defect and points at nothing.\n const worst = stretches.reduce((most, stretch) =>\n stretch.end - stretch.start > most.end - most.start ? stretch : most,\n );\n\n const stretchMs = worst.end - worst.start;\n if (stretchMs < options.minMs) return [];\n\n const share = stretchMs / request.durationMs;\n if (share < options.minShare) return [];\n\n // Is the silence concentrated here, or is the whole request full of it?\n const silentMs = stretches.reduce((total, gap) => total + (gap.end - gap.start), 0);\n if (stretchMs / silentMs < options.minDominance) return [];\n\n // Of the time outside the stretch, how much instrumentation accounted\n // for. Not a gate — it decides how much the hint is willing to claim.\n // Unioned, so queries that ran together count once; a sum would report\n // coverage above one.\n const outsideMs = request.durationMs - stretchMs;\n if (outsideMs <= 0) return [];\n const coverage = Math.min(1, coveredMs(work.map(occupied)) / outsideMs);\n\n const container = containerAround(scope.spans, worst);\n const spanIds = [worst.before?.id, worst.after?.id].filter(\n (id): id is number => id !== undefined,\n );\n\n const where = container ? ` in ${container.label}` : '';\n // The heading claims exactly what the hint is prepared to defend. Saying\n // \"your own code\" above a sentence that goes on to allow it might not be\n // is the kind of small contradiction that costs a tool its credibility on\n // the findings that matter.\n const what = bracketed(worst) ? 'of your own code' : 'nothing accounts for';\n\n return [\n {\n detector: 'slow_code',\n severity: 'warn',\n title: `${Math.round(stretchMs)} ms ${what}${where}`,\n // The whole stretch: unlike a duplicate query, there is no irreducible\n // remainder that has to happen anyway. It is an upper bound on the\n // saving, and the hint says what it is made of rather than promising\n // that all of it comes back.\n costMs: stretchMs,\n callsite: callsiteFor(worst, container),\n evidence: {\n kind: 'slow_code',\n stretchMs,\n atMs: worst.start,\n share,\n coverage,\n label: container?.label ?? null,\n before: worst.before ? describe(worst.before) : null,\n after: worst.after ? describe(worst.after) : null,\n spanIds,\n // Filled in afterwards, when the sampling profiler is running: a\n // detector is a pure function of the scope, and reading a profiler\n // is neither pure nor something the scope knows about.\n frames: [],\n busyShare: null,\n },\n hint: hintFor(worst, request),\n },\n ];\n },\n};\n","/**\n * Grouping a request's queries into the transactions they ran in.\n *\n * Nothing new is recorded to make this work. `BEGIN`, `COMMIT` and `ROLLBACK`\n * arrive as ordinary queries, and every db span already carries the\n * connection it ran on — so a transaction is simply the stretch between the\n * two ends *on one connection*. That last part is the whole reason this is a\n * shared helper rather than a line inside a detector: a query issued on some\n * other connection while a transaction is open did not happen inside it, and\n * getting that wrong turns every parallel query in a busy request into\n * evidence of a problem that is not there.\n */\n\nimport type { DbSpan, Span } from '../types.js';\n\n/** One transaction, as the spans of a single request show it. */\nexport interface Transaction {\n readonly connectionId: number;\n /** The `BEGIN` that opened it. */\n readonly begin: DbSpan;\n /**\n * The `COMMIT` or `ROLLBACK` that closed it.\n *\n * `null` when the request ended with the transaction still open — which is\n * either a leak or a request that was cut short, and in both cases the\n * connection was held right up to the end.\n */\n readonly end: DbSpan | null;\n /** Queries between the two ends; the ends themselves are not among them. */\n readonly queries: readonly DbSpan[];\n /** Relative ms from the request start, as spans measure it. */\n readonly startedAt: number;\n /** Where the hold ended: the end of `COMMIT`, or the end of the request. */\n readonly endedAt: number;\n}\n\n/**\n * Transaction control statements, matched on the whole first word.\n *\n * Two traps are deliberate. `ROLLBACK TO SAVEPOINT` does not close a\n * transaction — it rewinds inside one, and reading it as an end would cut a\n * transaction in half and hide everything after the savepoint. And `END` is\n * Postgres's synonym for `COMMIT`, which is why the boundary matters: without\n * it the word would also match a column called `ENDED_AT`.\n */\nconst BEGIN_RE = /^(?:BEGIN|START\\s+TRANSACTION)\\b/;\nconst END_RE = /^(?:COMMIT|ROLLBACK|END)\\b/;\nconst ROLLBACK_TO_RE = /^ROLLBACK\\s+TO\\b/;\n\n/** Leading comments an ORM may prepend, so the first word is the statement. */\nconst LEADING_COMMENTS = /^(?:\\s|\\/\\*[\\s\\S]*?\\*\\/|--[^\\n]*\\n)+/;\n\n/** `begin`, `end`, or `null` for an ordinary query. */\nexport function statementKind(sql: string): 'begin' | 'end' | null {\n // The first characters are enough, and bounding the work keeps a detector\n // from walking a megabyte of generated SQL to read one word.\n const head = sql.slice(0, 200).replace(LEADING_COMMENTS, '').toUpperCase();\n if (BEGIN_RE.test(head)) return 'begin';\n if (ROLLBACK_TO_RE.test(head)) return null;\n if (END_RE.test(head)) return 'end';\n return null;\n}\n\n/** End of a span, in the same relative milliseconds `startedAt` uses. */\nfunction endOf(span: Span): number {\n return span.startedAt + span.duration;\n}\n\n/**\n * The transactions a request opened.\n *\n * @param spans every span of the request, in any order.\n * @param requestEndMs where an unclosed transaction stops being measurable —\n * the request's own duration.\n */\nexport function transactionsOf(spans: readonly Span[], requestEndMs: number): Transaction[] {\n const byConnection = new Map<number, DbSpan[]>();\n for (const span of spans) {\n if (span.kind !== 'db' || span.connectionId === null) continue;\n const existing = byConnection.get(span.connectionId);\n if (existing) existing.push(span);\n else byConnection.set(span.connectionId, [span]);\n }\n\n const transactions: Transaction[] = [];\n for (const [connectionId, queries] of byConnection) {\n queries.sort((a, b) => a.startedAt - b.startedAt || a.id - b.id);\n\n let begin: DbSpan | null = null;\n let inside: DbSpan[] = [];\n\n for (const span of queries) {\n const kind = statementKind(span.sql);\n\n if (kind === 'begin') {\n // A second `BEGIN` with none of it closed is not a nested\n // transaction — Postgres has no such thing — so the first one stands.\n if (!begin) {\n begin = span;\n inside = [];\n }\n continue;\n }\n\n if (kind === 'end') {\n if (begin) {\n transactions.push({\n connectionId,\n begin,\n end: span,\n queries: inside,\n startedAt: begin.startedAt,\n endedAt: endOf(span),\n });\n begin = null;\n inside = [];\n }\n continue;\n }\n\n if (begin) inside.push(span);\n }\n\n if (begin) {\n transactions.push({\n connectionId,\n begin,\n end: null,\n queries: inside,\n startedAt: begin.startedAt,\n // Held until the request ended, which is the last moment anything\n // here can honestly speak for.\n endedAt: Math.max(requestEndMs, endOf(begin)),\n });\n }\n }\n\n return transactions;\n}\n\n/** How long `span` and the window overlap, in ms. Never negative. */\nexport function overlapMs(span: Span, from: number, to: number): number {\n return Math.max(0, Math.min(endOf(span), to) - Math.max(span.startedAt, from));\n}\n","/**\n * Transaction-hold detector: what the connection was doing while it was held.\n *\n * A transaction is not just a correctness construct, it is a connection taken\n * out of the pool for as long as it is open. Two hundred milliseconds of a\n * payment API called between `BEGIN` and `COMMIT` is two hundred milliseconds\n * one connection cannot serve anybody else with, and it is invisible to\n * anything that looks only at SQL or only at outgoing calls: you have to see\n * both, on the same connection, to see it at all.\n *\n * One finding per transaction, never two. The external call and the long hold\n * are the same problem — a connection held for something that is not a query\n * — with the same fix in the same place, and reporting them separately would\n * put two entries on the screen about one `BEGIN`.\n *\n * What it will not fire on:\n * - a call made after the `COMMIT`: the overlap with the open window is zero,\n * which is the whole point of measuring an overlap rather than an order;\n * - a query on another connection while a transaction is open — it was not\n * inside it, and `transactionsOf` groups by connection precisely so this\n * cannot happen;\n * - an implicit single-statement transaction, which every write is: without\n * an explicit `BEGIN` there is no transaction here to talk about;\n * - a transaction that was long because its queries were long. That is a\n * slow query, the panel already says so, and saying it twice in different\n * words is how a tool teaches people to skim its findings.\n */\n\nimport { coveredMs } from '../timing.js';\nimport type { Finding, FindingSeverity, HttpSpan, Span } from '../types.js';\nimport { overlapMs, type Transaction, transactionsOf } from './transactions.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\nexport interface TransactionHoldOptions {\n /**\n * Time inside outgoing calls made while a transaction was open, above which\n * the hold is reported.\n */\n readonly minExternalMs: number;\n /** How long a transaction may hold a connection before the hold is itself the finding. */\n readonly maxHeldMs: number;\n /**\n * How much of a long hold must have gone on something other than querying.\n *\n * A transaction that spent its whole life running queries is a slow query,\n * not a held connection.\n */\n readonly minIdleMs: number;\n}\n\n/** A quarter of a second of somebody else's service, with a connection in hand. */\nconst SEVERITY_CRITICAL_MS = 250;\n\nconst EXTERNAL_HINT =\n 'Move the call out of the transaction: read what you need, call, then open the transaction to write. ' +\n 'While it is open the connection belongs to this request alone, and a pool runs out of connections long before a payment API runs out of patience.';\n\nconst HOLD_HINT =\n 'Do the work before `BEGIN`, not inside it. A transaction is a connection taken out of the pool, and everything that is not a query — serialisation, a template, a call to another service — is time the pool is one connection smaller.';\n\n/** `POST api.stripe.com/v1/charges` — the call, without its query string. */\nfunction callLabel(span: HttpSpan): string {\n const cut = span.url.indexOf('?');\n return `${span.method} ${cut === -1 ? span.url : span.url.slice(0, cut)}`;\n}\n\n/** Milliseconds spent querying inside the window, counted once. */\nfunction sqlInside(transaction: Transaction): number {\n const spans = [transaction.begin, ...transaction.queries];\n if (transaction.end) spans.push(transaction.end);\n return coveredMs(\n spans.map((span) => ({\n start: Math.max(span.startedAt, transaction.startedAt),\n end: Math.min(span.startedAt + span.duration, transaction.endedAt),\n })),\n );\n}\n\n/** Outgoing calls that overlap the open window, longest first. */\nfunction callsInside(spans: readonly Span[], transaction: Transaction): HttpSpan[] {\n const inside: HttpSpan[] = [];\n for (const span of spans) {\n if (span.kind !== 'http') continue;\n if (overlapMs(span, transaction.startedAt, transaction.endedAt) <= 0) continue;\n inside.push(span);\n }\n return inside.sort((a, b) => b.duration - a.duration);\n}\n\nfunction findingFor(\n spans: readonly Span[],\n transaction: Transaction,\n options: TransactionHoldOptions,\n): Finding | null {\n const heldMs = transaction.endedAt - transaction.startedAt;\n const sqlMs = sqlInside(transaction);\n const queries = transaction.queries.length;\n const spanIds = [transaction.begin.id, ...transaction.queries.map((span) => span.id)];\n if (transaction.end) spanIds.push(transaction.end.id);\n\n const calls = callsInside(spans, transaction);\n // A union, not a sum: two calls made through `Promise.all` inside one\n // transaction held the connection once, for as long as the longer of them.\n const externalMs = coveredMs(\n calls.map((span) => ({\n start: Math.max(span.startedAt, transaction.startedAt),\n end: Math.min(span.startedAt + span.duration, transaction.endedAt),\n })),\n );\n\n const worst = calls[0];\n if (worst && externalMs >= options.minExternalMs) {\n const severity: FindingSeverity = externalMs >= SEVERITY_CRITICAL_MS ? 'critical' : 'warn';\n const what =\n calls.length === 1 ? `a ${Math.round(externalMs)} ms call` : `${calls.length} calls`;\n return {\n detector: 'transaction_hold',\n severity,\n title: `A transaction held a connection through ${what}`,\n // Not this request's time: moving the call out does not make the\n // request faster, it gives the connection back sooner. The cost lands\n // on every other request queueing for the pool, and putting a figure\n // here would promise a saving this request will never see.\n costMs: 0,\n // The call is where the fix is written, not the `BEGIN`.\n callsite: worst.callsite ?? transaction.begin.callsite,\n evidence: {\n kind: 'transaction',\n heldMs,\n sqlMs,\n externalMs,\n queries,\n sample: callLabel(worst),\n closedBy: transaction.end ? (statementLabel(transaction.end.sql) ?? null) : null,\n spanIds: [...spanIds, ...calls.map((span) => span.id)],\n },\n hint: EXTERNAL_HINT,\n };\n }\n\n const idleMs = heldMs - sqlMs;\n if (heldMs >= options.maxHeldMs && idleMs >= options.minIdleMs) {\n return {\n detector: 'transaction_hold',\n severity: 'warn',\n title: `A transaction held a connection for ${Math.round(heldMs)} ms, ${Math.round(sqlMs)} ms of it querying`,\n costMs: 0,\n callsite: transaction.begin.callsite,\n evidence: {\n kind: 'transaction',\n heldMs,\n sqlMs,\n externalMs,\n queries,\n sample: null,\n closedBy: transaction.end ? (statementLabel(transaction.end.sql) ?? null) : null,\n spanIds,\n },\n hint: HOLD_HINT,\n };\n }\n\n return null;\n}\n\n/** `COMMIT` or `ROLLBACK`, as the statement itself spells it. */\nfunction statementLabel(sql: string): string | null {\n const word = sql.trim().split(/[\\s;]/, 1)[0];\n return word ? word.toUpperCase() : null;\n}\n\nexport const transactionHold: Detector<TransactionHoldOptions> = {\n id: 'transaction_hold',\n\n defaultOptions: {\n // Fifty milliseconds of somebody else's service is already longer than\n // most of the queries the connection was taken out for.\n minExternalMs: 50,\n maxHeldMs: 500,\n minIdleMs: 100,\n },\n\n run(scope, options, request: FinishedRequest): Finding[] {\n const findings: Finding[] = [];\n for (const transaction of transactionsOf(scope.spans, request.durationMs)) {\n const finding = findingFor(scope.spans, transaction, options);\n if (finding) findings.push(finding);\n }\n return findings;\n },\n};\n","/**\n * Every detector there is, in one object.\n *\n * The single source: `DetectOptions` and `ResolvedDetectOptions` are mapped\n * types over these keys, so a new detector is one line and its options follow.\n *\n * Its own module rather than `detectors/index.ts` because `config.ts` needs\n * it, and the barrel imports `ResolvedDetectOptions` back out of config.\n */\n\nimport { duplicateCache, duplicateHttp } from './duplicates.js';\nimport { heavyResponse } from './heavy-response.js';\nimport { nPlusOne } from './n-plus-one.js';\nimport { poolWait } from './pool-wait.js';\nimport { sequentialHttp } from './sequential-http.js';\nimport { slowBudget } from './slow-budget.js';\nimport { slowCode } from './slow-code.js';\nimport { transactionHold } from './transaction-hold.js';\nimport type { Detector } from './types.js';\n\n/**\n * The detectors, keyed by the name they are configured under.\n *\n * Order matters only for the startup report and for `/api/meta`: findings\n * themselves are sorted by severity and cost when a request finishes.\n */\nexport const detectors = {\n nPlusOne,\n sequentialHttp,\n duplicateHttp,\n duplicateCache,\n slowBudget,\n slowCode,\n heavyResponse,\n poolWait,\n transactionHold,\n} as const;\n\n/** A key of `reqray({ detect: { … } })`. */\nexport type DetectorKey = keyof typeof detectors;\n\n/** The options one detector takes. */\nexport type DetectorOptions<K extends DetectorKey> =\n (typeof detectors)[K] extends Detector<infer Options> ? Options : never;\n\n/** The keys, as an array — `Object.keys` alone loses the type. */\nexport const detectorKeys = Object.keys(detectors) as readonly DetectorKey[];\n","/**\n * Detector registry and its runner.\n *\n * Detectors run after the response has been sent. A failing detector disables\n * only itself: the user must still get the remaining findings.\n */\n\nimport type { ResolvedOptions } from '../config.js';\nimport { warnOnce } from '../logger.js';\nimport type { RequestScope } from '../scope.js';\nimport { globalSlot } from '../state.js';\n\n/**\n * Detectors that disabled themselves after throwing.\n *\n * Process-wide, which is a compromise worth naming: two Reqray instances in one\n * process share this, so a detector that fails on one instance's data stops\n * running for the other too.\n */\nconst disabledDetectors = globalSlot('detectors.disabled', () => new Set<string>());\n\nimport type { Finding } from '../types.js';\nimport { detectorKeys, detectors } from './registry.js';\nimport type { Detector, FinishedRequest } from './types.js';\n\n/**\n * Every detector with the thresholds it actually runs with.\n *\n * For `/api/meta`: an empty findings tab must be able to say what was\n * looking and how it was tuned, or silence reads as a clean bill of health.\n */\nexport function detectorSettings(options: ResolvedOptions): Array<{\n id: string;\n enabled: boolean;\n options: Record<string, number | boolean | string> | null;\n}> {\n return detectorKeys.map((key) => ({\n id: detectors[key].id,\n enabled: options.detect[key] !== null,\n options: options.detect[key] as Record<string, number | boolean | string> | null,\n }));\n}\n\n/** Loudest first, so a sort can put the worse of two findings above. */\nconst SEVERITY: Record<string, number> = { critical: 2, warn: 1, info: 0 };\n\n/**\n * Runs the enabled detectors over a finished request.\n *\n * Findings are sorted by severity and then by cost. Cost alone was enough\n * while every detector measured its damage in milliseconds; a response of\n * twelve megabytes costs bytes, and sorting it below a duplicate cache read\n * that wasted a third of one would order the screen by what is measurable\n * rather than by what matters.\n */\nexport function runDetectors(\n scope: RequestScope,\n options: ResolvedOptions,\n request: FinishedRequest,\n): Finding[] {\n const findings: Finding[] = [];\n const disabled = disabledDetectors();\n\n for (const key of detectorKeys) {\n const detector: Detector<unknown> = detectors[key];\n if (disabled.has(detector.id)) continue;\n\n const detectorOptions = options.detect[key];\n if (!detectorOptions) continue;\n\n try {\n findings.push(...detector.run(scope, detectorOptions, request));\n } catch (error) {\n disabled.add(detector.id);\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce(\n `detector.${detector.id}`,\n `detector ${detector.id} disabled itself after an error: ${reason}`,\n );\n }\n }\n\n return findings.sort(\n (a, b) => (SEVERITY[b.severity] ?? 0) - (SEVERITY[a.severity] ?? 0) || b.costMs - a.costMs,\n );\n}\n\n/** Puts disabled detectors back into service. Needed by tests. */\nexport function resetDetectors(): void {\n disabledDetectors().clear();\n}\n\nexport {\n type DuplicateCacheOptions,\n type DuplicateHttpOptions,\n duplicateCache,\n duplicateHttp,\n} from './duplicates.js';\nexport { type HeavyResponseOptions, heavyResponse } from './heavy-response.js';\nexport { type NPlusOneOptions, nPlusOne } from './n-plus-one.js';\nexport { type PoolWaitOptions, poolWait } from './pool-wait.js';\nexport { type SequentialHttpOptions, sequentialHttp } from './sequential-http.js';\nexport { type SlowBudgetOptions, slowBudget } from './slow-budget.js';\nexport { type SlowCodeOptions, slowCode } from './slow-code.js';\nexport { type TransactionHoldOptions, transactionHold } from './transaction-hold.js';\nexport {\n overlapMs,\n statementKind,\n type Transaction,\n transactionsOf,\n} from './transactions.js';\nexport type { Detector, FinishedRequest } from './types.js';\n","/**\n * Panel access.\n *\n * The panel exposes request bodies, headers and SQL. It is therefore never\n * mounted silently where the process may be reachable from outside: with no\n * explicit gate the application fails at startup with a clear error.\n *\n * Local development means `NODE_ENV` equal to `development`, `test` or unset\n * altogether — the same reading Express itself uses. Everything else\n * (`staging`, `production`, any custom value) requires a gate.\n */\n\nimport type { ResolvedOptions } from './config.js';\nimport type { PanelGate, PanelRequestContext } from './types.js';\n\nexport type { PanelGate, PanelRequestContext };\n\n/** Access error. A separate class so it can be caught in a test. */\nexport class PanelGateError extends Error {\n override readonly name = 'PanelGateError';\n}\n\nfunction gateErrorMessage(mode: string): string {\n return [\n `reqray: panel not mounted — NODE_ENV=${mode} does not count as local development.`,\n 'The panel exposes request bodies, headers and SQL, so it must not open without a check.',\n 'Set a gate:',\n \" reqray({ panel: { gate: (ctx) => ctx.headers['x-reqray-token'] === process.env.REQRAY_TOKEN } })\",\n 'Or disable the panel: reqray({ panel: false })',\n \"Or, if open access is a deliberate decision: reqray({ panel: { gate: 'open' } })\",\n ].join('\\n');\n}\n\n/**\n * Checks that the panel may be mounted. Throws {@link PanelGateError} if a\n * gate is required but not set.\n */\nexport function assertPanelAllowed(options: ResolvedOptions): void {\n const panel = options.panel;\n if (!panel) return;\n if (panel.gate) return;\n if (options.isLocalDevelopment) return;\n\n throw new PanelGateError(gateErrorMessage(process.env['NODE_ENV'] ?? 'unset'));\n}\n\nconst LOOPBACK_IP = /^(?:::ffff:)?127\\.|^::1$/;\nconst LOCAL_HOST = /^(?:localhost|[^.]+\\.localhost|127(?:\\.\\d+){3}|\\[::1\\])(?::\\d+)?$/i;\n\n/**\n * Whether a request came from this machine, addressed to this machine.\n *\n * What stands in for a gate when none is set. \"No gate\" is granted to local\n * development, and `NODE_ENV` is a poor witness of that: a server deployed\n * without it reads as a laptop. The peer address is a better one. The `Host`\n * check is for the page in the developer's own browser: a hostile domain\n * re-pointed at 127.0.0.1 arrives from loopback, but still names itself.\n */\nexport function isLocalRequest(context: PanelRequestContext): boolean {\n if (!context.ip || !LOOPBACK_IP.test(context.ip)) return false;\n const host = context.headers['host'];\n // HTTP/1.0 sends none, and no browser speaks it.\n return host === undefined || (typeof host === 'string' && LOCAL_HOST.test(host));\n}\n\n/** Whether a particular request is let into the panel. */\nexport function isPanelRequestAllowed(\n gate: PanelGate | null,\n context: PanelRequestContext,\n): boolean {\n if (!gate) return isLocalRequest(context);\n if (gate === 'open') return true;\n try {\n return gate(context) === true;\n } catch {\n // A gate that throws is treated as a denial: access must never be opened\n // silently.\n return false;\n }\n}\n","/**\n * Occurrences into patterns — the arithmetic behind the findings tab.\n *\n * The grouping happens here, once, for every store: a store hands over one\n * row per occurrence and says when it stopped reading, the same division of\n * labour the history screen uses. Grouping is by detector plus code\n * location, not by request — `GET /api/orders` and `GET /api/orders/flaky`\n * both firing N+1 at the same line are one problem — and falls back to the\n * route when a finding carries no location, because \"somewhere on this\n * endpoint\" is still one somewhere.\n */\n\nimport type {\n Callsite,\n FindingPattern,\n FindingSeverity,\n FindingsResponse,\n PatternExample,\n StoredPatternState,\n} from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { normalizeRoute } from './routes.js';\n\n/**\n * One finding occurrence, as the tab needs it.\n *\n * A dozen fields rather than a record: the requests that carry findings are\n * a small minority, but a window of them is still not something to hold as\n * payloads to look at one finding in each.\n */\nexport interface FindingSample {\n readonly requestId: string;\n readonly startedAt: number;\n readonly method: string;\n readonly route: string;\n readonly status: number;\n readonly durationMs: number;\n readonly detector: string;\n readonly severity: FindingSeverity;\n readonly title: string;\n readonly costMs: number;\n readonly callsite: Callsite | null;\n readonly hint: string;\n}\n\n/** What a store hands back, and whether it read the whole window. */\nexport interface FindingSamples {\n readonly samples: readonly FindingSample[];\n readonly truncated: boolean;\n}\n\n/** The stretch of time a findings reading covers. Absent bounds mean all. */\nexport interface FindingsQuery {\n readonly from?: number | undefined;\n readonly to?: number | undefined;\n}\n\n/**\n * A request's findings, reduced to occurrence rows.\n *\n * For every store that keeps whole records, so the tab does not depend on\n * which store is behind it.\n */\nexport function findingSamplesOf(request: RecordedRequest): FindingSample[] {\n return request.findings.map((finding) => ({\n requestId: request.id,\n startedAt: request.startedAt,\n method: request.method,\n route: normalizeRoute(request.path),\n status: request.status,\n durationMs: request.durationMs,\n detector: finding.detector,\n severity: finding.severity,\n title: finding.title,\n costMs: finding.costMs,\n callsite: finding.callsite,\n hint: finding.hint,\n }));\n}\n\n/**\n * The pattern a finding belongs to.\n *\n * The code location when there is one — the same problem fires from the same\n * line whatever route reached it — and the route otherwise, so locationless\n * findings (a blown budget, a heavy response) still group by where they live.\n */\nexport function patternKey(sample: {\n readonly detector: string;\n readonly callsite: Callsite | null;\n readonly method: string;\n readonly route: string;\n}): string {\n return sample.callsite\n ? `${sample.detector}@${sample.callsite.relative}:${sample.callsite.line}`\n : `${sample.detector}@${sample.method} ${sample.route}`;\n}\n\n/** How many example requests a pattern carries. */\nconst EXAMPLE_LIMIT = 3;\n\nconst SEVERITY_RANK: Record<FindingSeverity, number> = { info: 0, warn: 1, critical: 2 };\n\nexport interface PatternsOptions {\n /** `ack`/`muted` per pattern id, as the store remembered them. */\n readonly states?: ReadonlyMap<string, StoredPatternState> | undefined;\n /**\n * When a file last changed, epoch ms, or `null` when nobody knows.\n *\n * Injected rather than read here: the aggregation stays pure, and what\n * \"changed\" means (mtime, a commit) is the caller's business.\n */\n readonly changedAt?: ((file: string) => number | null) | undefined;\n}\n\n/** Groups occurrences into the tab's patterns, costliest first. */\nexport function patternsOf(read: FindingSamples, options: PatternsOptions = {}): FindingsResponse {\n interface Bucket {\n latest: FindingSample;\n occurrences: number;\n recoverableMs: number;\n firstSeen: number;\n lastSeen: number;\n severity: FindingSeverity;\n routes: Map<string, { method: string; route: string; calls: number }>;\n /** Worst occurrence per request — five findings in one request are one way in. */\n examples: Map<string, PatternExample>;\n }\n\n const buckets = new Map<string, Bucket>();\n for (const sample of read.samples) {\n const key = patternKey(sample);\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n latest: sample,\n occurrences: 0,\n recoverableMs: 0,\n firstSeen: sample.startedAt,\n lastSeen: sample.startedAt,\n severity: sample.severity,\n routes: new Map(),\n examples: new Map(),\n };\n buckets.set(key, bucket);\n }\n\n bucket.occurrences++;\n bucket.recoverableMs += sample.costMs;\n if (sample.startedAt < bucket.firstSeen) bucket.firstSeen = sample.startedAt;\n if (sample.startedAt >= bucket.lastSeen) {\n bucket.lastSeen = sample.startedAt;\n // The sentence and the hint follow the freshest occurrence: \"150\n // identical queries\" must not describe last week's count.\n bucket.latest = sample;\n }\n if (SEVERITY_RANK[sample.severity] > SEVERITY_RANK[bucket.severity]) {\n bucket.severity = sample.severity;\n }\n\n const routeKey = `${sample.method} ${sample.route}`;\n const route = bucket.routes.get(routeKey);\n if (route) route.calls++;\n else bucket.routes.set(routeKey, { method: sample.method, route: sample.route, calls: 1 });\n\n const example = bucket.examples.get(sample.requestId);\n if (!example || sample.costMs > example.costMs) {\n bucket.examples.set(sample.requestId, {\n requestId: sample.requestId,\n startedAt: sample.startedAt,\n method: sample.method,\n route: sample.route,\n status: sample.status,\n durationMs: sample.durationMs,\n costMs: sample.costMs,\n });\n }\n }\n\n const patterns: FindingPattern[] = [...buckets.entries()].map(([id, bucket]) => ({\n id,\n detector: bucket.latest.detector,\n severity: bucket.severity,\n title: bucket.latest.title,\n hint: bucket.latest.hint,\n callsite: bucket.latest.callsite,\n occurrences: bucket.occurrences,\n recoverableMs: bucket.recoverableMs,\n routes: [...bucket.routes.values()].sort((a, b) => b.calls - a.calls),\n firstSeen: bucket.firstSeen,\n lastSeen: bucket.lastSeen,\n state: stateOf(id, bucket, options),\n examples: [...bucket.examples.values()]\n .sort((a, b) => b.costMs - a.costMs)\n .slice(0, EXAMPLE_LIMIT),\n }));\n\n patterns.sort((a, b) => b.recoverableMs - a.recoverableMs || b.occurrences - a.occurrences);\n\n return {\n patterns,\n occurrences: read.samples.length,\n recoverableMs: patterns.reduce(\n (sum, pattern) => (pattern.state === 'muted' ? sum : sum + pattern.recoverableMs),\n 0,\n ),\n truncated: read.truncated,\n };\n}\n\n/**\n * What a pattern's state is, muted winning over everything.\n *\n * `fixed` outranks `ack` because it says more: the pattern has been silent\n * since the file it points at changed. It is only ever a guess — hence the\n * question mark a client draws — and only claimed when somebody did change\n * the file after the last occurrence.\n */\nfunction stateOf(\n id: string,\n bucket: { latest: FindingSample; lastSeen: number },\n options: PatternsOptions,\n): FindingPattern['state'] {\n const stored = options.states?.get(id);\n if (stored === 'muted') return 'muted';\n\n const file = bucket.latest.callsite?.file;\n if (file && options.changedAt) {\n const changed = options.changedAt(file);\n if (changed !== null && changed > bucket.lastSeen) return 'fixed';\n }\n\n return stored === 'ack' ? 'ack' : 'new';\n}\n\n/**\n * The row's flag, with muted patterns silenced.\n *\n * Muting is presentation, not detection: the detector keeps running and the\n * findings stay on the record, but a muted pattern must stop shouting from\n * the list. The flag falls back to the costliest finding that is not muted,\n * and to nothing when they all are.\n */\nexport function flagWithMutes(request: RecordedRequest, muted: ReadonlySet<string>): string | null {\n if (muted.size === 0 || request.findings.length === 0) {\n return [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null;\n }\n const audible = request.findings.filter(\n (finding) =>\n !muted.has(\n patternKey({\n detector: finding.detector,\n callsite: finding.callsite,\n method: request.method,\n route: normalizeRoute(request.path),\n }),\n ),\n );\n return [...audible].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null;\n}\n","/**\n * Per-route aggregates.\n *\n * The request list answers \"what happened just now\"; this answers \"which\n * endpoint is expensive\". It is computed over whatever the store still holds,\n * which is a dev session rather than a statistically sound window — the\n * numbers are for spotting the obvious offender, not for a capacity plan, and\n * the screen says as much by showing the sample count next to them.\n */\n\nimport type { Callsite, RouteFinding, RouteStats, RoutesReport } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { patternKey } from './findings.js';\n\nexport type { RouteFinding, RouteStats, RoutesReport };\n\n/**\n * How many columns a route's sparkline is cut into.\n *\n * Ten: enough to see a shape, few enough that one column of a short window\n * still holds calls rather than drawing a comb of ones and zeroes.\n */\nexport const TREND_BUCKETS = 10;\n\n/**\n * Collapses the variable parts of a path.\n *\n * Per segment rather than by regex over the whole path, so that a route with\n * several ids normalizes cleanly. A hex token must contain a digit to count\n * as an id: otherwise ordinary words like `feed` or `cafe` would normalize\n * away and two unrelated routes would merge into one row.\n */\nexport function normalizeRoute(path: string): string {\n return path\n .split('?')[0]\n ?.split('/')\n .map((segment) => {\n if (/^\\d+$/.test(segment)) return ':id';\n if (/^\\d{4}-\\d{2}/.test(segment)) return ':date';\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment)) {\n return ':id';\n }\n if (/^[0-9a-f]{4,}$/i.test(segment) && /\\d/.test(segment)) return ':id';\n return segment;\n })\n .join('/') as string;\n}\n\n/**\n * A percentile with linear interpolation between neighbouring samples.\n *\n * Index-based selection would collapse p95 and p99 onto the same sample at\n * the sample counts a dev session produces, and two columns showing the same\n * number are worse than one.\n *\n * @param sorted values in ascending order.\n */\nexport function percentile(sorted: readonly number[], p: number): number {\n if (sorted.length === 0) return 0;\n if (sorted.length === 1) return sorted[0] as number;\n\n const position = p * (sorted.length - 1);\n const lower = Math.floor(position);\n const upper = Math.ceil(position);\n const low = sorted[lower] as number;\n if (lower === upper) return low;\n const high = sorted[upper] as number;\n return low + (high - low) * (position - lower);\n}\n\n/** One detector's tally on one route, while it is being accumulated. */\ninterface FoundHere {\n calls: number;\n recoverableMs: number;\n /** When the occurrence that supplied the words happened. */\n at: number;\n title: string;\n hint: string;\n callsite: Callsite | null;\n}\n\ninterface Accumulator {\n method: string;\n route: string;\n durations: number[];\n errors: number;\n sql: number;\n totalMs: number;\n bytes: number;\n /** Calls that reported a size — the divisor for the average. */\n weighed: number;\n /** Per detector, accumulated across the route's calls. */\n findings: Map<string, FoundHere>;\n /** When each call started — bucketed into the trend once the window is known. */\n starts: number[];\n}\n\n/**\n * Aggregates the retained requests by normalized route.\n *\n * @param muted pattern ids the reader silenced, as {@link patternKey} spells\n * them. Their findings stay on the records and out of this table: the column\n * is a shout, and a muted pattern has been told to stop shouting.\n */\nexport function routeStats(\n requests: readonly RecordedRequest[],\n muted: ReadonlySet<string> = new Set(),\n): RoutesReport {\n if (requests.length === 0) {\n return { routes: [], samples: 0, windowMs: 0, from: 0, to: 0 };\n }\n\n const byRoute = new Map<string, Accumulator>();\n let overallMs = 0;\n let oldest = Number.POSITIVE_INFINITY;\n let newest = Number.NEGATIVE_INFINITY;\n\n for (const request of requests) {\n const route = normalizeRoute(request.path);\n const key = `${request.method} ${route}`;\n let bucket = byRoute.get(key);\n if (!bucket) {\n bucket = {\n method: request.method,\n route,\n durations: [],\n errors: 0,\n sql: 0,\n totalMs: 0,\n bytes: 0,\n weighed: 0,\n findings: new Map(),\n starts: [],\n };\n byRoute.set(key, bucket);\n }\n\n bucket.durations.push(request.durationMs);\n bucket.starts.push(request.startedAt);\n\n for (const finding of request.findings) {\n if (\n muted.has(\n patternKey({\n detector: finding.detector,\n callsite: finding.callsite,\n method: request.method,\n route,\n }),\n )\n ) {\n continue;\n }\n const seen = bucket.findings.get(finding.detector);\n if (seen) {\n seen.calls++;\n seen.recoverableMs += finding.costMs;\n // The freshest occurrence speaks: \"150 identical queries\" must not be\n // last week's count.\n if (request.startedAt >= seen.at) {\n seen.at = request.startedAt;\n seen.title = finding.title;\n seen.hint = finding.hint;\n seen.callsite = finding.callsite;\n }\n continue;\n }\n bucket.findings.set(finding.detector, {\n calls: 1,\n recoverableMs: finding.costMs,\n at: request.startedAt,\n title: finding.title,\n hint: finding.hint,\n callsite: finding.callsite,\n });\n }\n bucket.totalMs += request.durationMs;\n const bytesOut = request.weight?.bytesOut ?? null;\n if (bytesOut !== null) {\n bucket.bytes += bytesOut;\n bucket.weighed++;\n }\n if (request.error !== null || request.status >= 500) bucket.errors++;\n for (const span of request.spans) {\n if (span.kind === 'db') bucket.sql++;\n }\n\n overallMs += request.durationMs;\n if (request.startedAt < oldest) oldest = request.startedAt;\n if (request.startedAt > newest) newest = request.startedAt;\n }\n\n // A single request spans no time; one second keeps rps finite and honest.\n const windowMs = Math.max(1_000, newest - oldest);\n\n const routes = [...byRoute.values()].map((bucket): RouteStats => {\n const sorted = [...bucket.durations].sort((a, b) => a - b);\n const calls = sorted.length;\n\n // The shape of the traffic, over the same window every other row uses —\n // so two sparklines on this screen are comparable by eye.\n const trend = new Array<number>(TREND_BUCKETS).fill(0);\n const span = Math.max(1, newest - oldest);\n for (const at of bucket.starts) {\n const index = Math.min(TREND_BUCKETS - 1, Math.floor(((at - oldest) / span) * TREND_BUCKETS));\n trend[index] = (trend[index] ?? 0) + 1;\n }\n\n return {\n method: bucket.method,\n route: bucket.route,\n calls,\n rps: calls / (windowMs / 1_000),\n p50: percentile(sorted, 0.5),\n p95: percentile(sorted, 0.95),\n p99: percentile(sorted, 0.99),\n errorRate: (bucket.errors / calls) * 100,\n sqlAvg: bucket.sql / calls,\n bytesAvg: bucket.weighed > 0 ? bucket.bytes / bucket.weighed : null,\n timeShare: overallMs > 0 ? (bucket.totalMs / overallMs) * 100 : 0,\n findings: [...bucket.findings.entries()]\n .map(([detector, found]) => ({\n detector,\n calls: found.calls,\n recoverableMs: found.recoverableMs,\n title: found.title,\n hint: found.hint,\n callsite: found.callsite,\n }))\n .sort((a, b) => b.recoverableMs - a.recoverableMs || b.calls - a.calls),\n trend,\n };\n });\n\n // Most expensive first — the order the screen opens in.\n routes.sort((a, b) => b.timeShare - a.timeShare);\n return { routes, samples: requests.length, windowMs, from: oldest, to: newest };\n}\n","/**\n * How one call compares against the route's own history.\n *\n * A duration on its own says nothing. 400 ms is alarming for a cache read and\n * excellent for a report, so the only comparison worth drawing is against\n * other calls of the same route — and only when there are enough of them for\n * the comparison to be worth more than the silence it replaces.\n */\n\nimport type { DurationBaseline, RecordedRequest } from '../types.js';\nimport type { DurationSample } from './api.js';\nimport { normalizeRoute, percentile } from './routes.js';\n\n/**\n * Below this a percentile is one call wearing a statistic's name.\n *\n * Twenty is where the ninety-fifth percentile stops being the single slowest\n * sample and starts interpolating between two — the point at which \"slower\n * than 95% of calls\" is a claim about a distribution rather than about the\n * one unlucky call that happens to top the list.\n */\nconst MIN_FOR_P95 = 20;\n\n/** Below this the request would be measuring itself. */\nconst MIN_SAMPLES = 2;\n\n/** What the store is asked for when a request is judged against its route. */\nexport interface BaselineQuery {\n readonly method: string;\n /** The normalized route, as `normalizeRoute` produces it. */\n readonly route: string;\n /**\n * The request being judged — it is never part of its own baseline.\n *\n * Left out when the caller wants the route's whole history: the charts do,\n * and a chart with one call missing from it would be a different kind of\n * lie from the one this field prevents.\n */\n readonly excludeId?: string;\n /**\n * The stretch to read, epoch ms.\n *\n * Left out for the whole history. The charts pass the same window the\n * routes table was computed over: a table describing thirteen minutes above\n * a chart describing six hours is two answers to one question.\n */\n readonly from?: number;\n readonly to?: number;\n}\n\n/**\n * The verdict, or `null` when there is nothing honest to say.\n *\n * @param samples the route's other calls, as the store hands them over.\n * `undefined` is a store that cannot answer at all, and produces no verdict\n * rather than one drawn from whatever page happened to be loaded.\n */\nexport function baselineFor(\n request: RecordedRequest,\n samples: readonly DurationSample[] | undefined,\n): DurationBaseline | null {\n if (!samples || samples.length < MIN_SAMPLES) return null;\n\n const sorted = samples.map((sample) => sample.durationMs).sort((a, b) => a - b);\n const sum = sorted.reduce((total, value) => total + value, 0);\n const avgMs = sum / sorted.length;\n\n const times = samples.map((sample) => sample.startedAt);\n const windowMs = Math.max(...times) - Math.min(...times);\n\n const p95Ms = sorted.length >= MIN_FOR_P95 ? percentile(sorted, 0.95) : null;\n const p50Ms = percentile(sorted, 0.5);\n const p99Ms = sorted.length >= MIN_FOR_P95 ? percentile(sorted, 0.99) : null;\n const maxMs = sorted[sorted.length - 1] ?? 0;\n\n // Without a trustworthy p95 the strongest claim available is \"at or under\n // the mean\", which roughly half of all calls are. Calling anything slow off\n // five samples is how a tool starts crying wolf.\n const verdict =\n p95Ms !== null && request.durationMs >= p95Ms\n ? 'slower'\n : request.durationMs <= avgMs\n ? 'faster'\n : 'typical';\n\n return {\n method: request.method,\n route: normalizeRoute(request.path),\n samples: sorted.length,\n windowMs,\n avgMs,\n p95Ms,\n p50Ms,\n p99Ms,\n maxMs,\n verdict,\n };\n}\n","/**\n * `git blame` for the frames of an exception.\n *\n * A stack trace says where it broke; blame says who last touched that line\n * and when, which is usually the next question. It runs `git` on the machine\n * the panel runs on, so it is gated exactly like replay and EXPLAIN: local\n * development by default, explicit opt-in anywhere else.\n *\n * Results are cached per file and revision — blame is not cheap, and the same\n * file is asked about once per frame of every occurrence of a group.\n */\n\nimport { execFile } from 'node:child_process';\nimport { isAbsolute, resolve, sep } from 'node:path';\nimport type { BlameLine } from '@reqray/protocol';\nimport { warnOnce } from '../logger.js';\n\nexport type { BlameLine };\n\nconst cache = new Map<string, BlameLine | null>();\n\n/** Bounded so a long session cannot turn the cache into a leak. */\nconst CACHE_LIMIT = 500;\n\nfunction run(command: string, args: readonly string[], cwd: string): Promise<string> {\n return new Promise((resolve, reject) => {\n execFile(\n command,\n args,\n { cwd, timeout: 3_000, maxBuffer: 1024 * 1024, windowsHide: true },\n (error, stdout) => {\n if (error) reject(error);\n else resolve(stdout);\n },\n );\n });\n}\n\n/**\n * Parses `git blame --porcelain` for a single line.\n *\n * The porcelain format leads with the hash, then key/value header lines; only\n * three of them matter here.\n */\nexport function parsePorcelain(output: string): BlameLine | null {\n const lines = output.split('\\n');\n const header = lines[0]?.split(' ')[0];\n if (!header || !/^[0-9a-f]{7,40}$/.test(header)) return null;\n\n let author = 'unknown';\n let at = 0;\n for (const line of lines) {\n if (line.startsWith('author ')) author = line.slice('author '.length).trim();\n else if (line.startsWith('author-time ')) {\n at = Number.parseInt(line.slice('author-time '.length), 10) * 1000;\n }\n }\n\n // A line that is staged but not committed blames to all zeroes; naming a\n // commit that does not exist would be worse than saying nothing.\n if (/^0+$/.test(header)) return null;\n return { sha: header.slice(0, 7), author, at };\n}\n\n/**\n * Blame for one line of one file.\n *\n * @returns `null` when the file is untracked, the repository is absent, or\n * git is not installed — all ordinary situations, none of them an error.\n */\nexport async function blameLine(\n file: string,\n line: number,\n cwd: string,\n): Promise<BlameLine | null> {\n if (!isAbsolute(file) || !Number.isInteger(line) || line < 1) return null;\n\n // Inside the project, or blame becomes a way to ask which absolute paths on\n // this machine are tracked, and by whom.\n const root = resolve(cwd);\n const target = resolve(file);\n if (target !== root && !target.startsWith(root + sep)) return null;\n\n const key = `${file}:${line}`;\n const cached = cache.get(key);\n if (cached !== undefined) return cached;\n\n let result: BlameLine | null = null;\n try {\n const output = await run(\n 'git',\n ['blame', '--porcelain', '-L', `${line},${line}`, '--', file],\n cwd,\n );\n result = parsePorcelain(output);\n } catch (error) {\n // Not a repository, not tracked, no git at all: the panel simply shows\n // nothing for that frame.\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('panel.blame', `git blame unavailable: ${reason}`);\n }\n\n if (cache.size >= CACHE_LIMIT) cache.clear();\n cache.set(key, result);\n return result;\n}\n\n/** Forgets everything blamed so far. Needed by tests and after a checkout. */\nexport function clearBlameCache(): void {\n cache.clear();\n}\n","/**\n * Grouping of exceptions by normalised stack.\n *\n * The same error raised three hundred times is one row in the panel with a\n * repeat count, not three hundred rows. Normalisation drops everything that\n * varies between calls and keeps the shape of the stack.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { ExceptionFrame, ExceptionGroup } from '@reqray/protocol';\nimport { isProjectFrame, parseStackFrame } from '../callsite.js';\nimport type { ResolvedStackOptions } from '../config.js';\nimport type { RecordedRequest, SpanError } from '../types.js';\n\nexport type { ExceptionFrame, ExceptionGroup };\n\n/** Buckets in the sparkline — as many as there are bars in the mockup. */\nconst BUCKET_COUNT = 12;\n\n/** Frames taken into the fingerprint: deeper than this stacks stop differing. */\nconst SIGNIFICANT_FRAMES = 8;\n\nfunction framesOf(error: SpanError, options: ResolvedStackOptions): ExceptionFrame[] {\n if (!error.stack) return [];\n\n const frames: ExceptionFrame[] = [];\n for (const line of error.stack.split('\\n')) {\n if (!line.trim().startsWith('at ')) continue;\n const parsed = parseStackFrame(line);\n frames.push({\n raw: line.trim(),\n file: parsed?.file ?? null,\n line: parsed?.line ?? null,\n project: parsed ? isProjectFrame(parsed.file, options) : false,\n });\n }\n return frames;\n}\n\n/**\n * Stack fingerprint.\n *\n * It takes the exception type and the positions of the first frames — without\n * columns and without the message: the message usually carries varying values\n * (`id 8812`), which would split identical errors into separate groups.\n */\nfunction fingerprintStack(error: SpanError, frames: readonly ExceptionFrame[]): string {\n const parts = [error.name];\n for (const frame of frames.slice(0, SIGNIFICANT_FRAMES)) {\n parts.push(frame.file ? `${frame.file}:${frame.line ?? 0}` : frame.raw);\n }\n // There may be no stack at all — then the message is the only thing that\n // tells errors apart.\n if (frames.length === 0) parts.push(error.message);\n\n return createHash('sha1').update(parts.join('\\n')).digest('hex').slice(0, 12);\n}\n\ninterface Accumulator {\n readonly id: string;\n readonly type: string;\n message: string;\n readonly frames: ExceptionFrame[];\n readonly origin: string | null;\n where: string | null;\n count: number;\n lastSeenAt: number;\n readonly requestIds: string[];\n readonly times: number[];\n test: string | null;\n}\n\nfunction originOf(frames: readonly ExceptionFrame[], options: ResolvedStackOptions): string | null {\n const projectFrame = frames.find((frame) => frame.project && frame.file);\n if (!projectFrame?.file) return null;\n const relative = projectFrame.file.startsWith(options.projectRoot)\n ? projectFrame.file.slice(options.projectRoot.length + 1)\n : projectFrame.file;\n return `${relative}:${projectFrame.line ?? 0}`;\n}\n\nfunction bucketize(times: readonly number[], now: number, windowMs: number): number[] {\n const buckets = new Array<number>(BUCKET_COUNT).fill(0);\n if (windowMs <= 0) return buckets;\n\n const from = now - windowMs;\n for (const time of times) {\n const position = Math.floor(((time - from) / windowMs) * BUCKET_COUNT);\n const index = Math.min(BUCKET_COUNT - 1, Math.max(0, position));\n buckets[index] = (buckets[index] ?? 0) + 1;\n }\n return buckets;\n}\n\n/**\n * Builds exception groups from recorded requests.\n *\n * Requests are expected newest first, the order the store returns them in.\n * Groups come back by descending occurrence count.\n */\nexport function groupExceptions(\n requests: readonly RecordedRequest[],\n options: ResolvedStackOptions,\n now = Date.now(),\n): ExceptionGroup[] {\n const groups = new Map<string, Accumulator>();\n let oldest = now;\n\n for (const request of requests) {\n if (request.startedAt < oldest) oldest = request.startedAt;\n\n const error = request.error;\n if (!error) continue;\n\n const frames = framesOf(error, options);\n const id = fingerprintStack(error, frames);\n\n let group = groups.get(id);\n if (!group) {\n group = {\n id,\n type: error.name,\n message: error.message,\n frames,\n origin: originOf(frames, options),\n where: `${request.method} ${request.path}`,\n count: 0,\n lastSeenAt: request.startedAt,\n requestIds: [],\n times: [],\n test: null,\n };\n groups.set(id, group);\n }\n\n group.count++;\n group.times.push(request.startedAt);\n if (request.startedAt > group.lastSeenAt) {\n group.lastSeenAt = request.startedAt;\n group.message = error.message;\n group.where = `${request.method} ${request.path}`;\n }\n // Records arrive newest first, so the first test name seen is the latest.\n if (group.test === null && request.test !== null) group.test = request.test;\n // The request list is capped: the panel needs the latest ones, not all.\n if (group.requestIds.length < 50) group.requestIds.push(request.id);\n }\n\n const windowMs = Math.max(1, now - oldest);\n\n return [...groups.values()]\n .map(\n (group): ExceptionGroup => ({\n id: group.id,\n type: group.type,\n message: group.message,\n origin: group.origin,\n where: group.where,\n count: group.count,\n lastSeenAt: group.lastSeenAt,\n requestIds: group.requestIds,\n frames: group.frames,\n buckets: bucketize(group.times, now, windowMs),\n test: group.test,\n }),\n )\n .sort((a, b) => b.count - a.count || b.lastSeenAt - a.lastSeenAt);\n}\n","/**\n * Stack capture and locating the user's line of code.\n *\n * The most expensive operation in the whole collection path, so it may only be\n * called through `scope.shouldCaptureStack()`: always in development, only for\n * the first occurrences of each fingerprint in production.\n */\n\nimport { isAbsolute, relative as pathRelative } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ResolvedStackOptions } from './config.js';\nimport { pendingCallsite } from './context.js';\nimport { globalSlot, TwoGenerationCache } from './state.js';\n\n/** What is known about where a fingerprint is issued from. */\ninterface CallsiteRecord {\n callsite: Callsite | null;\n /** How many stacks have been captured for this fingerprint. */\n samples: number;\n /**\n * The same SQL has been seen coming from more than one place.\n *\n * Attributing it to either one would be a lie, so nothing is attributed —\n * and the N+1 detector, which needs a single origin, stays silent.\n */\n ambiguous: boolean;\n}\n\n/**\n * What has been learned about each fingerprint's origin.\n *\n * Process-wide, not per request: capturing a stack is the single most\n * expensive thing Reqray does, and in production it is paid only while the\n * origin of a fingerprint is still unknown.\n *\n * Bounded, which it was not. Every sibling cache has had a ceiling from the\n * start with a comment about applications that build SQL dynamically; this one\n * has the same key space and had no ceiling at all, so such an application\n * leaked a record per distinct statement, for the life of the process, inside\n * somebody else's production.\n */\nconst CACHE_LIMIT = 5_000;\n\nconst learnedCallsites = globalSlot(\n 'callsite.learned',\n () => new TwoGenerationCache<string, CallsiteRecord>(CACHE_LIMIT),\n);\n\nimport type { Callsite } from './types.js';\n\n/** `at fn (/path/file.ts:12:34)` — frame with a function name. */\nconst FRAME_WITH_NAME = /^\\s*at\\s+.*?\\s+\\((.+):(\\d+):(\\d+)\\)\\s*$/;\n/** `at /path/file.ts:12:34` — frame without a function name. */\nconst FRAME_BARE = /^\\s*at\\s+(.+):(\\d+):(\\d+)\\s*$/;\n\nconst NODE_MODULES = /[\\\\/]node_modules[\\\\/]/;\n\n/** A position in a file, parsed out of one stack line. */\nexport interface StackFrame {\n readonly file: string;\n readonly line: number;\n readonly column: number;\n}\n\n/**\n * Parses one line of a V8 stack.\n *\n * Returns `null` for lines that are not frames (the error header) and for\n * frames without a file (`at <anonymous>`, `eval`).\n */\nexport function parseStackFrame(line: string): StackFrame | null {\n const match = FRAME_WITH_NAME.exec(line) ?? FRAME_BARE.exec(line);\n if (!match) return null;\n\n const rawFile = match[1];\n const lineNo = Number(match[2]);\n const columnNo = Number(match[3]);\n if (!rawFile || !Number.isFinite(lineNo) || !Number.isFinite(columnNo)) return null;\n\n // ESM frames arrive as file:// URLs.\n let file = rawFile;\n if (file.startsWith('file://')) {\n try {\n file = fileURLToPath(file);\n } catch {\n return null;\n }\n }\n\n return { file, line: lineNo, column: columnNo };\n}\n\n/**\n * Checks that a frame points at project code: inside `projectRoot`, not in\n * `node_modules`, not in Node internals and not in the exclusion list.\n */\nexport function isProjectFrame(file: string, options: ResolvedStackOptions): boolean {\n // Node internals arrive either as `node:internal/...` or as a relative\n // `internal/process/...` — the absolute-path check rejects both.\n if (!isAbsolute(file)) return false;\n if (NODE_MODULES.test(file)) return false;\n for (const fragment of options.exclude) {\n if (file.includes(fragment)) return false;\n }\n\n const rel = pathRelative(options.projectRoot, file);\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);\n}\n\n/**\n * Finds the first frame in the stack that belongs to project code.\n *\n * Kept as a separate pure function so it can be tested against recorded\n * stacks without depending on a real call tree.\n */\nexport function findProjectFrame(stack: string, options: ResolvedStackOptions): Callsite | null {\n for (const line of stack.split('\\n')) {\n const frame = parseStackFrame(line);\n if (!frame || !isProjectFrame(frame.file, options)) continue;\n\n return {\n file: frame.file,\n relative: pathRelative(options.projectRoot, frame.file).replaceAll('\\\\', '/'),\n line: frame.line,\n column: frame.column,\n };\n }\n return null;\n}\n\n/**\n * Captures a stack and returns the first line inside the project.\n *\n * `Error.stackTraceLimit` is raised for the duration of the capture and\n * restored even on exception. Never throws: a failed capture is `null`, not a\n * broken request.\n *\n * @param boundary the instrumentation's wrapper function. Every frame up to\n * and including it is dropped, so the top frame is user code rather than Reqray\n * itself. The `node_modules` filter cannot be relied on here: when developing\n * against a linked copy of Reqray its sources sit inside the project root, and\n * the first \"project code\" line would be the interceptor itself.\n */\nexport function captureCallsite(\n options: ResolvedStackOptions,\n boundary?: (...args: never[]) => unknown,\n): Callsite | null {\n const previousLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = options.limit;\n try {\n const holder: { stack?: string } = {};\n Error.captureStackTrace(holder, boundary ?? captureCallsite);\n return holder.stack ? findProjectFrame(holder.stack, options) : null;\n } catch {\n return null;\n } finally {\n Error.stackTraceLimit = previousLimit;\n }\n}\n\n/** A callsite handed down from a pool wrapper to the driver wrapper. */\nexport interface HandedCallsite {\n readonly callsite: Callsite | null;\n /** Registry id of the pool the query went through — for EXPLAIN. */\n readonly clientId?: number;\n}\n\n/**\n * Carries a callsite across an asynchronous connection acquire.\n *\n * `pool.query()` resolves a connection asynchronously, so by the time the\n * query reaches the driver the caller's frame has left the stack and there is\n * nothing left to capture. The pool wrapper captures it while the frame is\n * still there and hands it down through this context.\n */\nexport function withHandedCallsite<T>(handed: HandedCallsite, fn: () => T): T {\n return pendingCallsite().run(handed, fn);\n}\n\n/**\n * The callsite handed down by a pool wrapper.\n *\n * `undefined` means the query did not come through a pool, and the driver\n * wrapper should capture a stack of its own.\n */\nexport function handedCallsite(): HandedCallsite | undefined {\n return pendingCallsite().getStore();\n}\n\n/**\n * The callsite for a span, capturing a stack only when it is still needed.\n *\n * This is the single place the capture policy lives, so every instrumentation\n * gets the same behaviour:\n *\n * 1. a callsite handed down by a pool wrapper wins — it is the only one taken\n * while the caller's frame was still on the stack;\n * 2. in development a stack is captured every time, which keeps full fidelity;\n * 3. in production it is captured only until the origin of that fingerprint is\n * known, and later spans reuse what was learned. Capturing a stack costs\n * roughly a third of the application's throughput, so paying it per query\n * is not an option;\n * 4. if the same SQL turns out to come from more than one place, nothing is\n * attributed at all: a wrong line of code is worse than none, and the N+1\n * detector needs a single origin anyway.\n *\n * Never throws — a failed capture is `null`, not a broken request.\n */\nexport function resolveCallsite(\n scope: {\n shouldCaptureStack(fingerprint?: string): boolean;\n options: { stack: ResolvedStackOptions };\n },\n fingerprint: string,\n boundary?: (...args: never[]) => unknown,\n): Callsite | null {\n try {\n const handed = handedCallsite();\n if (handed) return handed.callsite;\n\n // In development every stack is captured, so each span carries its own\n // true origin and the detector compares them per request. Learning would\n // only add a way to be wrong: one unlucky pair of call sites anywhere in\n // the process would permanently mute a whole query shape.\n // Without an explicit boundary this function is the boundary, otherwise\n // the top frame would be Reqray's own code.\n const from = boundary ?? resolveCallsite;\n\n if (scope.options.stack.maxPerFingerprint === Number.POSITIVE_INFINITY) {\n return captureCallsite(scope.options.stack, from);\n }\n\n const learned = learnedCallsites();\n const known = learned.get(fingerprint);\n if (known?.ambiguous) return null;\n\n if (!scope.shouldCaptureStack(fingerprint)) return known?.callsite ?? null;\n\n const captured = captureCallsite(scope.options.stack, from);\n remember(learned, fingerprint, known, captured);\n return learned.get(fingerprint)?.ambiguous ? null : captured;\n } catch {\n return null;\n }\n}\n\nfunction remember(\n learned: TwoGenerationCache<string, CallsiteRecord>,\n fingerprint: string,\n known: CallsiteRecord | undefined,\n captured: Callsite | null,\n): void {\n if (!known) {\n learned.set(fingerprint, { callsite: captured, samples: 1, ambiguous: false });\n return;\n }\n\n known.samples++;\n if (!captured) return;\n if (!known.callsite) {\n known.callsite = captured;\n return;\n }\n if (known.callsite.file !== captured.file || known.callsite.line !== captured.line) {\n known.callsite = null;\n known.ambiguous = true;\n }\n}\n\n/**\n * How many stacks have been captured for a fingerprint so far.\n *\n * Asked by `RequestScope.shouldCaptureStack`, which decides whether to pay for\n * another. The count lives here because the map does.\n */\nexport function samplesFor(fingerprint: string): number {\n return learnedCallsites().get(fingerprint)?.samples ?? 0;\n}\n\n/** Forgets what was learned about fingerprint origins. Needed by tests. */\nexport function resetLearnedCallsites(): void {\n learnedCallsites().clear();\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n/**\n * Current request context.\n *\n * A single `AsyncLocalStorage` per process (see `state.ts` — it lives in the\n * shared state so that the ESM and CJS copies of core do not drift apart).\n * The framework adapter wraps request handling in {@link runInScope};\n * instrumentations reach the scope through {@link current}. No scope means the\n * span is simply ignored, which is not an error: application code also runs\n * outside requests (migrations, workers, startup).\n */\n\nimport type { RequestScope } from './scope.js';\nimport { globalSlot } from './state.js';\nimport type { Callsite } from './types.js';\n\n/** The request context. One per process — see `state.ts` for why. */\nconst storage = globalSlot('context.storage', () => new AsyncLocalStorage<RequestScope>());\n\n/**\n * Callsite handed from a pool wrapper down to the driver wrapper.\n *\n * Absent outside a pooled query — that is what tells the driver wrapper to\n * capture a stack of its own.\n */\nexport const pendingCallsite = globalSlot(\n 'context.pendingCallsite',\n () => new AsyncLocalStorage<{ readonly callsite: Callsite | null; readonly clientId?: number }>(),\n);\n\n/**\n * Scope of the current request, or `undefined`.\n *\n * This is the first check in every instrumentation: no scope, immediate\n * return, not a single allocation made.\n */\nexport function current(): RequestScope | undefined {\n return storage().getStore();\n}\n\n/** Runs `fn` inside the scope. Return values and exceptions pass through as is. */\nexport function runInScope<T>(scope: RequestScope, fn: () => T): T {\n return storage().run(scope, fn);\n}\n\n/**\n * Enters a scope without wrapping a function.\n *\n * Needed by frameworks where the request start and end are different hooks\n * (Fastify's `onRequest`) and handling cannot be wrapped in a single call.\n */\nexport function enterScope(scope: RequestScope): void {\n storage().enterWith(scope);\n}\n\n/**\n * Runs `fn` outside of any scope.\n *\n * Needed for Reqray's own background work: writing to storage must not end up\n * as spans of the request being handled.\n */\nexport function runOutsideScope<T>(fn: () => T): T {\n return storage().exit(fn);\n}\n","/**\n * Registry of live database pools and clients able to run EXPLAIN.\n *\n * The pg instrumentation registers whatever executed a query; the recorded\n * span carries the id, so the panel later sends EXPLAIN to the very same\n * database the query ran against. References are weak: a closed pool must be\n * collectable, and a dead entry simply means EXPLAIN is no longer available\n * for that span.\n */\n\nimport { type Box, globalBox, globalSlot } from './state.js';\n\n/** The one method a target must have — both pg `Pool` and `Client` fit. */\nexport interface ExplainTarget {\n query(sql: string): Promise<unknown>;\n}\n\n/**\n * Ids already assigned, so one pool registers once.\n *\n * Must share a slot with the counter that feeds it: split across two module\n * copies, one pool takes two ids from one sequence and `explainTarget(id)`\n * resolves to the wrong pool.\n */\nconst assigned = globalSlot('explain.assigned', () => new WeakMap<object, number>());\n\n/** Live targets, weakly held: a closed pool must stay collectable. */\nconst targets = globalSlot('explain.targets', () => new Map<number, WeakRef<object>>());\n\n/** Id source for {@link targets}. */\nconst sequence: () => Box<number> = globalBox('explain.sequence', 0);\n\n/** Registers a target (idempotent) and returns its id. */\nexport function registerExplainTarget(target: object): number {\n const ids = assigned();\n const known = ids.get(target);\n if (known !== undefined) return known;\n\n const seq = sequence();\n seq.value += 1;\n ids.set(target, seq.value);\n targets().set(seq.value, new WeakRef(target));\n return seq.value;\n}\n\n/** The live target for an id, or `null` if it has been collected. */\nexport function explainTarget(id: number): ExplainTarget | null {\n const live = targets();\n const ref = live.get(id);\n if (!ref) return null;\n\n const target = ref.deref();\n if (!target) {\n live.delete(id);\n return null;\n }\n if (typeof (target as Partial<ExplainTarget>).query !== 'function') return null;\n return target as ExplainTarget;\n}\n\n/** Forgets every target. Needed by tests. */\nexport function resetExplainTargets(): void {\n targets().clear();\n}\n","/**\n * EXPLAIN of a recorded query, straight from the panel.\n *\n * Safety comes from three rules that are not options:\n * - the SQL is taken from the record — the panel client sends only ids and\n * can never inject a statement;\n * - `ANALYZE` is never used: it executes the query, and an executed\n * INSERT is a write. Plain EXPLAIN plans without running anything;\n * - the query goes to the same pool that ran the original (see\n * `explain-targets.ts`), so \"which database\" is never a guess.\n *\n * Parameterized queries have no recorded values (values are deliberately not\n * collected), so they are planned with `GENERIC_PLAN` — PostgreSQL 16+.\n */\n\nimport type { ExplainNote, ExplainPlanNode, ExplainResult } from '@reqray/protocol';\nimport { explainTarget } from '../explain-targets.js';\nimport type { RecordedRequest } from '../types.js';\n\nexport type { ExplainNote, ExplainPlanNode, ExplainResult };\n\nconst PLACEHOLDER = /\\$\\d+/;\nconst EXPLAIN_TIMEOUT_MS = 5_000;\n\ninterface PlanJson {\n readonly [key: string]: unknown;\n readonly Plans?: readonly PlanJson[];\n}\n\nfunction numberOf(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\nfunction labelOf(node: PlanJson): string {\n const type = typeof node['Node Type'] === 'string' ? (node['Node Type'] as string) : 'node';\n const relation = node['Relation Name'];\n const index = node['Index Name'];\n if (typeof index === 'string' && typeof relation === 'string') {\n return `${type} using ${index} on ${relation}`;\n }\n if (typeof relation === 'string') return `${type} on ${relation}`;\n return type;\n}\n\n/** Flattens the plan tree and derives the warnings. */\nexport function analyzePlan(plan: PlanJson): {\n nodes: ExplainPlanNode[];\n notes: ExplainNote[];\n} {\n const nodes: ExplainPlanNode[] = [];\n const notes: ExplainNote[] = [];\n\n const walk = (node: PlanJson, depth: number): void => {\n nodes.push({\n depth,\n label: labelOf(node),\n rows: numberOf(node['Plan Rows']),\n cost: numberOf(node['Total Cost']),\n });\n\n if (node['Node Type'] === 'Seq Scan' && typeof node['Filter'] === 'string') {\n const relation = typeof node['Relation Name'] === 'string' ? node['Relation Name'] : '?';\n notes.push({\n severity: 'warn',\n message:\n `Seq Scan over \"${relation}\" with filter ${node['Filter']} — ` +\n 'the whole table is read for a fraction of its rows. An index on the filtered column may help.',\n });\n }\n if (node['Node Type'] === 'Sort' && Array.isArray(node['Sort Key'])) {\n notes.push({\n severity: 'info',\n message:\n `Sorting by ${(node['Sort Key'] as unknown[]).join(', ')} happens in memory — ` +\n 'an index in the sort order would remove it entirely.',\n });\n }\n\n for (const child of node.Plans ?? []) walk(child, depth + 1);\n };\n\n walk(node0(plan), 0);\n return { nodes, notes };\n\n function node0(root: PlanJson): PlanJson {\n // `EXPLAIN (FORMAT JSON)` wraps the tree as [{ \"Plan\": {...} }].\n const inner = (root as { Plan?: PlanJson }).Plan;\n return inner ?? root;\n }\n}\n\n/**\n * Whether anything follows the statement's own terminator.\n *\n * A semicolon inside a literal or a comment is not a terminator —\n * `WHERE note = 'a;b'` is one perfectly ordinary statement, and refusing to\n * plan it would be this check crying wolf. So quotes and comments are skipped\n * rather than searched: single quotes with their doubled-quote escape, dollar\n * quoting with its tag, double-quoted identifiers, and both comment forms.\n */\nfunction hasSecondStatement(sql: string): boolean {\n for (let i = 0; i < sql.length; i++) {\n const ch = sql[i];\n\n if (ch === \"'\" || ch === '\"') {\n const quote = ch;\n i++;\n while (i < sql.length) {\n if (sql[i] === quote) {\n // A doubled quote is an escaped one and the literal continues.\n if (sql[i + 1] === quote) i++;\n else break;\n }\n i++;\n }\n continue;\n }\n\n if (ch === '$') {\n const tag = /^\\$[A-Za-z_]\\w*\\$|^\\$\\$/.exec(sql.slice(i));\n if (tag) {\n const close = sql.indexOf(tag[0], i + tag[0].length);\n // An unterminated dollar quote swallows the rest: nothing follows it.\n if (close === -1) return false;\n i = close + tag[0].length - 1;\n continue;\n }\n }\n\n if (ch === '-' && sql[i + 1] === '-') {\n const end = sql.indexOf('\\n', i);\n if (end === -1) return false;\n i = end;\n continue;\n }\n\n if (ch === '/' && sql[i + 1] === '*') {\n const end = sql.indexOf('*/', i + 2);\n if (end === -1) return false;\n i = end + 1;\n continue;\n }\n\n if (ch === ';') return sql.slice(i + 1).trim() !== '';\n }\n return false;\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => reject(new Error(`EXPLAIN did not answer within ${ms} ms`)), ms);\n timer.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error) => {\n clearTimeout(timer);\n reject(error);\n },\n );\n });\n}\n\n/** A user-facing failure: the message is shown in the panel as-is. */\nexport class ExplainError extends Error {\n override readonly name = 'ExplainError';\n constructor(\n message: string,\n readonly status = 400,\n ) {\n super(message);\n }\n}\n\n/**\n * Runs EXPLAIN for one recorded span.\n *\n * @throws ExplainError with a message meant for the panel.\n */\nexport async function runExplain(record: RecordedRequest, spanId: number): Promise<ExplainResult> {\n const span = record.spans.find((candidate) => candidate.id === spanId);\n if (span?.kind !== 'db') {\n throw new ExplainError('span not found, or it is not a SQL query', 404);\n }\n if (span.source !== 'pg') {\n throw new ExplainError(\n `EXPLAIN is supported for queries made through pg; this one went through ${span.source ?? 'an unknown driver'}`,\n );\n }\n if (span.clientId === null) {\n throw new ExplainError(\n 'the executor of this query was not recorded — EXPLAIN has nowhere to go',\n );\n }\n\n const target = explainTarget(span.clientId);\n if (!target) {\n throw new ExplainError(\n 'the pool that ran this query lives inside the application process and is not reachable here — ' +\n 'EXPLAIN works in the panel mounted in the application',\n );\n }\n\n // `EXPLAIN <sql>` is concatenation: a second statement after a semicolon\n // would be planned and then *run*. Reaching this needs an injection the\n // application already has, but a read-only endpoint must not be what turns\n // that into a write.\n if (hasSecondStatement(span.sql)) {\n throw new ExplainError(\n 'this record holds more than one statement, and EXPLAIN plans one — nothing was run',\n );\n }\n\n const parameterized = PLACEHOLDER.test(span.sql);\n const statement = parameterized\n ? `EXPLAIN (GENERIC_PLAN, FORMAT JSON) ${span.sql}`\n : `EXPLAIN (FORMAT JSON) ${span.sql}`;\n\n let rows: unknown;\n try {\n const result = (await withTimeout(\n Promise.resolve(target.query(statement)),\n EXPLAIN_TIMEOUT_MS,\n )) as { rows?: unknown };\n rows = result?.rows;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n if (parameterized && /GENERIC_PLAN|generic_plan|syntax error/i.test(reason)) {\n throw new ExplainError(\n `EXPLAIN of a parameterized query needs PostgreSQL 16+ (GENERIC_PLAN). The database said: ${reason}`,\n );\n }\n throw new ExplainError(`the database rejected EXPLAIN: ${reason}`);\n }\n\n const first = Array.isArray(rows) ? (rows[0] as Record<string, unknown> | undefined) : undefined;\n const planColumn = first?.['QUERY PLAN'];\n const plan = Array.isArray(planColumn) ? planColumn[0] : planColumn;\n if (!plan || typeof plan !== 'object') {\n throw new ExplainError('the database returned the plan in an unexpected shape');\n }\n\n const { nodes, notes } = analyzePlan(plan as PlanJson);\n return { sql: span.sql, nodes, notes, plan };\n}\n","/**\n * Exports: taking a session out of the panel.\n *\n * HAR and cURL are built here rather than in the browser because the panel\n * only ever receives list rows — bodies and headers live in the records, and\n * an export that quietly dropped them would be worse than no export.\n *\n * Both formats are for handing a request to something else: a HAR to a\n * browser's network panel or a colleague's viewer, a curl script to a\n * terminal. Neither is a backup format, and neither promises to round-trip.\n */\n\nimport type { RecordedRequest } from '../types.js';\n\n/** Reqray's own additions to a HAR entry, under the extension prefix HAR reserves. */\ninterface ReqrayHarExtension {\n readonly sqlQueries: number;\n readonly nPlusOne: boolean;\n readonly test: string | null;\n}\n\nfunction headerList(headers: Readonly<Record<string, string>>): Array<{\n name: string;\n value: string;\n}> {\n return Object.entries(headers).map(([name, value]) => ({ name, value }));\n}\n\n/** HAR 1.2. Times are milliseconds, as the format requires. */\nexport function toHar(\n requests: readonly RecordedRequest[],\n now = new Date(0),\n note: string | null = null,\n): Record<string, unknown> {\n return {\n log: {\n version: '1.2',\n creator: { name: 'reqray', version: '0.1' },\n pages: [],\n entries: requests.map((request) => {\n const extension: ReqrayHarExtension = {\n sqlQueries: request.spans.filter((span) => span.kind === 'db').length,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n test: request.test,\n };\n\n return {\n startedDateTime: new Date(request.startedAt).toISOString(),\n time: request.durationMs,\n request: {\n method: request.method,\n url: `${request.path}${request.query ? `?${request.query}` : ''}`,\n httpVersion: 'HTTP/1.1',\n headers: headerList(request.requestHeaders),\n queryString: [],\n cookies: [],\n headersSize: -1,\n bodySize: request.requestBody?.text.length ?? 0,\n ...(request.requestBody\n ? {\n postData: {\n mimeType: request.requestHeaders['content-type'] ?? 'application/json',\n text: request.requestBody.text,\n },\n }\n : {}),\n },\n response: {\n status: request.status,\n statusText: '',\n httpVersion: 'HTTP/1.1',\n headers: headerList(request.responseHeaders),\n cookies: [],\n content: {\n size: request.responseBody?.text.length ?? 0,\n mimeType: request.responseHeaders['content-type'] ?? 'application/json',\n ...(request.responseBody ? { text: request.responseBody.text } : {}),\n },\n redirectURL: '',\n headersSize: -1,\n bodySize: request.responseBody?.text.length ?? 0,\n },\n cache: {},\n // Everything Reqray knows lands in `wait`: the breakdown it has is by\n // span, not by the connection phases HAR describes.\n timings: { send: 0, wait: request.durationMs, receive: 0 },\n _reqray: extension,\n };\n }),\n // Kept out of the entries so a diff of two exports stays readable.\n _exportedAt: now.toISOString(),\n // HAR's own field for this, so a viewer that knows nothing of Reqray\n // still shows it. An export that was cut has to say so: it is evidence,\n // and evidence presented as complete is worse than none.\n ...(note ? { comment: note } : {}),\n },\n };\n}\n\n/** Escapes a value for single-quoted shell. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * A runnable `.sh`: one curl per request.\n *\n * Masked headers and bodies are exported as they were stored — with the\n * masking. A script that leaked the authorization header of every recorded\n * request would undo the one guarantee the buffer makes.\n */\nexport function toCurlScript(\n requests: readonly RecordedRequest[],\n origin: string,\n note: string | null = null,\n): string {\n const lines = [\n '#!/bin/sh',\n '# Exported from reqray. Sensitive headers and fields are masked, so a',\n '# request that needed them will not authenticate as it did.',\n // At the top rather than the bottom: a script is read from the first line,\n // and \"this is not all of them\" belongs where reading starts.\n ...(note ? [`# ${note}`] : []),\n '',\n ];\n\n for (const request of requests) {\n const url = `${origin}${request.path}${request.query ? `?${request.query}` : ''}`;\n const parts = [`curl -i -X ${request.method} ${shellQuote(url)}`];\n for (const [name, value] of Object.entries(request.requestHeaders)) {\n // Hop-by-hop and length headers are curl's business, not the script's.\n if (name === 'host' || name === 'content-length' || name === 'connection') continue;\n parts.push(` -H ${shellQuote(`${name}: ${value}`)}`);\n }\n if (request.requestBody) parts.push(` --data ${shellQuote(request.requestBody.text)}`);\n\n lines.push(\n // One line, whatever the name holds: a record can come off the wire, and\n // a line break here would end the comment and start a command.\n `# ${request.status} · ${Math.round(request.durationMs)} ms${request.test ? ` · ${request.test.replace(/\\p{Cc}/gu, ' ')}` : ''}`,\n parts.join(' \\\\\\n'),\n '',\n );\n }\n\n return lines.join('\\n');\n}\n","/**\n * Filtering and summary over the request list.\n *\n * Pure functions: the panel runs them on every keystroke in the search box,\n * and tests run them without standing up a server.\n */\n\nimport type { RequestSummary } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport { normalizeRoute } from './routes.js';\n\nexport type { RequestSummary } from '@reqray/protocol';\n\n/** The panel's filter set. Empty fields exclude nothing. */\nexport interface RequestFilter {\n /** Substring of the path, method or status. Case-insensitive. */\n readonly query?: string | undefined;\n /** Methods: `GET`, `POST`. An empty list means all. */\n readonly methods?: readonly string[] | undefined;\n /** Status classes: 2, 3, 4, 5. An empty list means all. */\n readonly statusClasses?: readonly number[] | undefined;\n /** Only requests no faster than the given duration. */\n readonly minDurationMs?: number | undefined;\n /** Not before this moment, epoch ms. Inclusive. */\n readonly from?: number | undefined;\n /** Not after this moment, epoch ms. Inclusive. */\n readonly to?: number | undefined;\n /** Only requests where the detectors found something. */\n readonly onlyFindings?: boolean | undefined;\n /** Only requests with an N+1 — a narrower question than \"any finding\". */\n readonly onlyNPlusOne?: boolean | undefined;\n /** Only requests a test issued. */\n readonly onlyTests?: boolean | undefined;\n /**\n * Only requests that failed.\n *\n * Wider than the 5xx class: a handler that threw and still answered 200 is\n * a failure, and it is the one worth finding.\n */\n readonly onlyErrors?: boolean | undefined;\n /**\n * One endpoint, as the Routes screen names it: the normalized path and the\n * method that go with it.\n */\n readonly route?: { readonly method: string; readonly route: string } | undefined;\n /** Substring of the path alone — narrower than `query`, which matches four fields. */\n readonly path?: string | undefined;\n /** Exactly this status code — `404`, not the whole 4xx class. */\n readonly status?: number | undefined;\n /** At least this many SQL queries. */\n readonly minSql?: number | undefined;\n /**\n * Rows the list flags with one of these detectors.\n *\n * The *flag* — the costliest finding — not \"any finding of this kind\":\n * both stores can answer that question identically (SQLite keeps the flag\n * as a column), and it is the badge the reader is pointing at anyway.\n */\n readonly flagged?: readonly string[] | undefined;\n /** Requests issued by a test whose name contains this. Case-insensitive. */\n readonly test?: string | undefined;\n}\n\nfunction matchesQuery(request: RecordedRequest, needle: string): boolean {\n if (request.method.toLowerCase().includes(needle)) return true;\n if (request.path.toLowerCase().includes(needle)) return true;\n if (String(request.status).includes(needle)) return true;\n return request.query ? request.query.toLowerCase().includes(needle) : false;\n}\n\n/** Selects requests matching the filter, keeping the original order (newest first). */\nexport function filterRequests(\n requests: readonly RecordedRequest[],\n filter: RequestFilter = {},\n): RecordedRequest[] {\n const needle = filter.query?.trim().toLowerCase();\n const methods = filter.methods?.length\n ? new Set(filter.methods.map((m) => m.toUpperCase()))\n : null;\n const classes = filter.statusClasses?.length ? new Set(filter.statusClasses) : null;\n\n return requests.filter((request) => {\n if (filter.from !== undefined && request.startedAt < filter.from) return false;\n if (filter.to !== undefined && request.startedAt > filter.to) return false;\n if (needle && !matchesQuery(request, needle)) return false;\n if (methods && !methods.has(request.method.toUpperCase())) return false;\n if (classes && !classes.has(Math.floor(request.status / 100))) return false;\n if (filter.minDurationMs !== undefined && request.durationMs < filter.minDurationMs)\n return false;\n if (filter.onlyFindings && request.findings.length === 0) return false;\n if (filter.onlyNPlusOne && !request.findings.some((f) => f.detector === 'n_plus_one'))\n return false;\n if (filter.onlyTests && request.test === null) return false;\n if (filter.path && !request.path.toLowerCase().includes(filter.path.toLowerCase())) {\n return false;\n }\n if (filter.status !== undefined && request.status !== filter.status) return false;\n if (filter.minSql !== undefined) {\n let sql = 0;\n for (const span of request.spans) if (span.kind === 'db') sql++;\n if (sql < filter.minSql) return false;\n }\n if (filter.flagged?.length) {\n // The same rule the list flags a row by: the costliest finding names it.\n const flag = [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector;\n if (!flag || !filter.flagged.includes(flag)) return false;\n }\n if (filter.test !== undefined) {\n if (request.test === null || !request.test.toLowerCase().includes(filter.test.toLowerCase()))\n return false;\n }\n if (filter.onlyErrors && request.error === null && request.status < 500) return false;\n if (filter.route) {\n if (request.method.toUpperCase() !== filter.route.method.toUpperCase()) return false;\n if (normalizeRoute(request.path) !== filter.route.route) return false;\n }\n return true;\n });\n}\n\n/**\n * Summary over the buffer.\n *\n * `slowMs` is the \"slow\" threshold for the status bar, 500 ms by default, as\n * in the panel mockup.\n */\nexport function summarize(\n all: readonly RecordedRequest[],\n shown: readonly RecordedRequest[],\n slowMs = 500,\n): RequestSummary {\n let slow = 0;\n let errors = 0;\n let withFindings = 0;\n\n for (const request of all) {\n if (request.durationMs >= slowMs) slow++;\n if (request.status >= 500 || request.error) errors++;\n if (request.findings.length > 0) withFindings++;\n }\n\n return { shown: shown.length, total: all.length, slow, errors, withFindings };\n}\n","/**\n * The shape of the traffic over time, for the strip above the list.\n *\n * The panel used to draw this from the rows it had loaded, which was fine\n * while a store held five hundred requests and everything was on screen. With\n * a history behind it, \"the rows I have\" is the last page — a few minutes —\n * and a strip that only spans a few minutes cannot be dragged back to\n * yesterday. So the store answers for its whole range instead.\n *\n * Three numbers per request go into it — when, how long, and whether it\n * failed — and the bucketing happens here, once, for every store. Two\n * implementations of \"which bucket does this fall into\" would drift, and the\n * drift would be a strip that disagrees with the list under it.\n */\n\n/** What the timeline needs to know about one request. */\nexport interface TimePoint {\n readonly startedAt: number;\n readonly durationMs: number;\n readonly hasError: boolean;\n}\n\nimport type { TimelineBucket, TimelineReport } from '@reqray/protocol';\n\nexport type { TimelineBucket, TimelineReport };\n\n/** How many columns the strip is drawn with, unless asked otherwise. */\nexport const TIMELINE_BUCKETS = 64;\n/** Above this, a request is drawn as slow — the panel's own threshold. */\nconst SLOW_MS = 500;\n\n/**\n * Which column a moment falls into.\n *\n * Shared with the per-route charts on purpose: two implementations of \"which\n * bucket is this\" drift, and the drift is a strip that disagrees with the\n * chart under it about when something happened. Everything inside a single\n * millisecond lands in the first column rather than dividing by a zero span.\n */\nexport function bucketIndex(at: number, from: number, to: number, count: number): number {\n const span = to - from;\n const fraction = span > 0 ? (at - from) / span : 0;\n return Math.max(0, Math.min(count - 1, Math.floor(fraction * count)));\n}\n\n/**\n * Buckets a set of points into a strip.\n *\n * `null` when there is nothing to draw: an empty store has no range, and a\n * strip with invented ends would be a lie about what is recorded.\n */\nexport function buildTimeline(\n points: readonly TimePoint[],\n bucketCount: number = TIMELINE_BUCKETS,\n): TimelineReport | null {\n if (points.length === 0 || bucketCount <= 0) return null;\n\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n for (const point of points) {\n if (point.startedAt < from) from = point.startedAt;\n if (point.startedAt > to) to = point.startedAt;\n }\n\n const buckets: TimelineBucket[] = Array.from({ length: bucketCount }, () => ({\n err: 0,\n slow: 0,\n rest: 0,\n total: 0,\n }));\n\n for (const point of points) {\n const index = bucketIndex(point.startedAt, from, to, bucketCount);\n const bucket = buckets[index] as {\n err: number;\n slow: number;\n rest: number;\n total: number;\n };\n if (point.hasError) bucket.err++;\n else if (point.durationMs >= SLOW_MS) bucket.slow++;\n else bucket.rest++;\n bucket.total++;\n }\n\n return { from, to, buckets };\n}\n","/**\n * One metric over one period, and what the period adds up to.\n *\n * Everything else the panel draws is scoped to something: the strip above the\n * list counts requests and nothing else, and the route charts cover one route\n * at a time. This is the screen that answers \"what did latency do this week\",\n * and the arithmetic behind it lives here — once, for every store.\n *\n * **Why the store hands over rows rather than answers.** The obvious division\n * of labour is to let SQLite compute percentiles in SQL, and the obvious cost\n * is two implementations of the same statistic that quietly disagree: one\n * interpolating between neighbouring samples, the other picking the nearest\n * rank. So a store hands back a few numbers per request — the shape below,\n * never the payloads — and the bucketing and the percentiles happen here. The\n * rule the plan actually cares about still holds: a week of rows must never\n * reach the browser to have a median taken at the other end.\n *\n * What a store *is* responsible for is not reading its whole history into\n * memory. It reads a bounded number of rows and says when it stopped, and\n * this file passes that admission on rather than presenting a truncated total\n * as a complete one.\n */\n\nimport type { MetricSeries, SeriesMetric, SeriesResponse, SeriesTotals } from '@reqray/protocol';\nimport type { RecordedRequest } from '../types.js';\nimport type { RequestFilter } from './filters.js';\nimport { normalizeRoute, percentile } from './routes.js';\nimport { bucketIndex } from './timeline.js';\n\n/**\n * One request, as a history reading needs it.\n *\n * Ten numbers rather than a record: a period is tens of thousands of requests,\n * and parsing that many JSON documents to look at one field in each is how a\n * screen becomes slower than the question it answers.\n */\nexport interface HistorySample {\n readonly startedAt: number;\n readonly durationMs: number;\n readonly hasError: boolean;\n readonly sqlCount: number;\n readonly httpCount: number;\n readonly bytes: number;\n /** Mean event-loop delay while it ran, or `null` when nothing measured it. */\n readonly loopDelayMs: number | null;\n readonly findingCount: number;\n /** Time inside queries, ms. `null` for requests stored before it was kept. */\n readonly sqlMs: number | null;\n /** Time covered by no instrumented work, ms. `null` as above. */\n readonly selfMs: number | null;\n readonly method: string;\n readonly route: string;\n /** The detector the list flags this request with, when one fired. */\n readonly flag: string | null;\n}\n\n/**\n * One request, reduced to what a history reading needs.\n *\n * For every store that keeps whole records — the in-memory ring, and any\n * store answering from `list()` — so that what the screen shows does not\n * depend on which one is behind it.\n */\nexport function historySampleOf(request: RecordedRequest): HistorySample {\n let sqlCount = 0;\n let httpCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n else if (span.kind === 'http') httpCount++;\n }\n\n return {\n startedAt: request.startedAt,\n durationMs: request.durationMs,\n hasError: request.error !== null || request.status >= 500,\n sqlCount,\n httpCount,\n bytes: request.weight?.bytesOut ?? 0,\n loopDelayMs: request.host?.loopDelayMs ?? null,\n findingCount: request.findings.length,\n sqlMs: request.timing?.sqlMs ?? null,\n selfMs: request.timing?.selfMs ?? null,\n method: request.method,\n route: normalizeRoute(request.path),\n // The same rule the list flags a row by: the costliest finding names it.\n flag: [...request.findings].sort((a, b) => b.costMs - a.costMs)[0]?.detector ?? null,\n };\n}\n\n/** What a store is asked for. */\nexport interface HistoryQuery {\n /** Epoch ms, inclusive. */\n readonly from: number;\n /** Epoch ms, inclusive. */\n readonly to: number;\n /** The same filter the list uses, so a metric can be asked about one route. */\n readonly filter: RequestFilter;\n}\n\n/** What a store answers with. */\nexport interface HistorySamples {\n readonly samples: readonly HistorySample[];\n /** The store stopped reading before the period ended. */\n readonly truncated: boolean;\n}\n\n/** Columns the chart is drawn with, unless the caller asks for fewer. */\nexport const SERIES_COLUMNS = 48;\n\n/**\n * Below this many requests per column a percentile is not a statistic.\n *\n * The same figure a route's charts use: a p95 over three\n * samples is the slowest of three, and a chart of those jumps about saying\n * nothing.\n */\nconst MIN_PER_COLUMN = 6;\n\n/** Below this the chart stops being a shape and becomes a row of bars. */\nconst MIN_COLUMNS = 8;\n\n/** A column of the chart, while it is being filled. */\ninterface Column {\n readonly durations: number[];\n errors: number;\n sqlCount: number;\n httpCount: number;\n bytes: number;\n findings: number;\n loopTotal: number;\n loopSamples: number;\n}\n\nfunction emptyColumn(): Column {\n return {\n durations: [],\n errors: 0,\n sqlCount: 0,\n httpCount: 0,\n bytes: 0,\n findings: 0,\n loopTotal: 0,\n loopSamples: 0,\n };\n}\n\n/** The value of one metric in one column, or `null` when it cannot say. */\nfunction metricValue(metric: SeriesMetric, column: Column, bucketMs: number): number | null {\n const calls = column.durations.length;\n // Nothing ran here. Every metric returns a void rather than a zero: a\n // stretch nobody called did not have an error rate of nought.\n if (calls === 0) return null;\n\n switch (metric) {\n case 'p50':\n case 'p95':\n case 'p99': {\n const sorted = [...column.durations].sort((a, b) => a - b);\n const p = metric === 'p50' ? 0.5 : metric === 'p95' ? 0.95 : 0.99;\n return percentile(sorted, p);\n }\n case 'throughput':\n return bucketMs > 0 ? (calls / bucketMs) * 60_000 : null;\n case 'errorRate':\n return column.errors / calls;\n case 'sqlPerRequest':\n return column.sqlCount / calls;\n case 'httpPerRequest':\n return column.httpCount / calls;\n case 'bytes':\n return column.bytes / calls;\n case 'loopDelay':\n // Only the requests that carried a reading. A process that was never\n // measured must not average in as calm.\n return column.loopSamples > 0 ? column.loopTotal / column.loopSamples : null;\n case 'findingsPerRequest':\n return column.findings / calls;\n default:\n return null;\n }\n}\n\n/** Everything a period adds up to. */\nexport function totalsOf(samples: readonly HistorySample[]): SeriesTotals {\n if (samples.length === 0) {\n return {\n calls: 0,\n errorRate: 0,\n p50: 0,\n p95: 0,\n p99: 0,\n sqlMs: null,\n appMs: null,\n busiest: null,\n topFinding: null,\n };\n }\n\n const durations: number[] = [];\n let errors = 0;\n let sqlMs = 0;\n let appMs = 0;\n let timed = 0;\n const routes = new Map<string, { method: string; route: string; calls: number }>();\n const findings = new Map<string, number>();\n\n for (const sample of samples) {\n durations.push(sample.durationMs);\n if (sample.hasError) errors++;\n if (sample.sqlMs !== null && sample.selfMs !== null) {\n sqlMs += sample.sqlMs;\n appMs += sample.selfMs;\n timed++;\n }\n\n const key = `${sample.method} ${sample.route}`;\n const seen = routes.get(key);\n if (seen) seen.calls++;\n else routes.set(key, { method: sample.method, route: sample.route, calls: 1 });\n\n if (sample.flag) findings.set(sample.flag, (findings.get(sample.flag) ?? 0) + 1);\n }\n\n durations.sort((a, b) => a - b);\n\n let busiest: SeriesTotals['busiest'] = null;\n for (const entry of routes.values()) {\n if (!busiest || entry.calls > busiest.calls) busiest = { ...entry };\n }\n\n let topFinding: SeriesTotals['topFinding'] = null;\n for (const [detector, calls] of findings) {\n if (!topFinding || calls > topFinding.calls) topFinding = { detector, calls };\n }\n\n return {\n calls: samples.length,\n errorRate: errors / samples.length,\n p50: percentile(durations, 0.5),\n p95: percentile(durations, 0.95),\n p99: percentile(durations, 0.99),\n // Reported only when something recorded it. A period half of whose\n // requests predate the figure would otherwise show a share of SQL time\n // that is half of the truth and looks like a fall.\n sqlMs: timed > 0 ? sqlMs : null,\n appMs: timed > 0 ? appMs : null,\n busiest,\n topFinding,\n };\n}\n\n/**\n * How many columns a period's traffic can support.\n *\n * Never more than asked for, never so many that each holds a handful of\n * requests — see {@link MIN_PER_COLUMN}.\n */\nexport function columnsFor(sampleCount: number, asked: number): number {\n if (asked <= 0) return 0;\n return Math.max(\n Math.min(MIN_COLUMNS, asked),\n Math.min(asked, Math.ceil(sampleCount / MIN_PER_COLUMN)),\n );\n}\n\nexport interface HistoryOptions {\n /** The period, as the caller chose it — not as the data happens to fall. */\n readonly from: number;\n readonly to: number;\n readonly metrics: readonly SeriesMetric[];\n readonly columns?: number;\n}\n\n/**\n * Builds the answer for one reading of the screen.\n *\n * The period comes from the caller rather than from the samples: a week with\n * traffic in one hour of it must draw a week with one column in it, not an\n * hour stretched across the screen.\n */\n/** Samples into columns of one window — the same cut for a period and its ghost. */\nfunction bucketize(\n samples: readonly HistorySample[],\n from: number,\n to: number,\n count: number,\n): Column[] {\n const columns: Column[] = Array.from({ length: count }, emptyColumn);\n for (const sample of samples) {\n const column = columns[bucketIndex(sample.startedAt, from, to, count)];\n if (!column) continue;\n column.durations.push(sample.durationMs);\n if (sample.hasError) column.errors++;\n column.sqlCount += sample.sqlCount;\n column.httpCount += sample.httpCount;\n column.bytes += sample.bytes;\n column.findings += sample.findingCount;\n if (sample.loopDelayMs !== null) {\n column.loopTotal += sample.loopDelayMs;\n column.loopSamples++;\n }\n }\n return columns;\n}\n\nexport function historyOf(\n current: HistorySamples,\n previous: readonly HistorySample[],\n options: HistoryOptions,\n): SeriesResponse {\n const samples = current.samples;\n const asked = options.columns ?? SERIES_COLUMNS;\n const count = Math.max(1, columnsFor(samples.length, asked));\n\n const columns = bucketize(samples, options.from, options.to, count);\n\n // A period of no width would divide by zero and a chart of it would be a\n // single column claiming to be a stretch of time.\n const span = Math.max(1, options.to - options.from);\n const bucketMs = span / count;\n\n // The period immediately before, cut into the same number of columns, so\n // the ghost lines up with the line it sits behind.\n const ghostColumns =\n previous.length > 0 ? bucketize(previous, options.from - span, options.from - 1, count) : null;\n const primary = options.metrics[0];\n\n const series: MetricSeries[] = options.metrics.map((metric) => ({\n metric,\n values: columns.map((column) => metricValue(metric, column, bucketMs)),\n }));\n\n return {\n from: options.from,\n to: options.to,\n bucketMs,\n calls: columns.map((column) => column.durations.length),\n series,\n totals: totalsOf(samples),\n // No traffic before the period is not a period of zeroes; it is nothing\n // to compare against, and the screen says so instead of inventing a\n // hundred-percent rise.\n previous: previous.length > 0 ? totalsOf(previous) : null,\n ghost:\n ghostColumns && primary\n ? ghostColumns.map((column) => metricValue(primary, column, bucketMs))\n : null,\n truncated: current.truncated,\n };\n}\n","/**\n * Where a page of the request list stopped.\n *\n * The cursor is part of the panel's API, not of any one store: the in-memory\n * ring and the SQLite history hand out cursors the browser cannot tell apart,\n * and both continue from one the other could have written.\n *\n * The key is whatever the page is ordered by — the start time for the list as\n * it is normally read, the duration when the question is \"what was slowest\".\n * It is not a position on its own, because several requests can share a\n * millisecond and plenty share a duration, so the id rides along and breaks\n * the tie exactly the way the ordering does: largest first, among equals the\n * larger id first.\n */\n\n/** A decoded cursor. */\nexport interface Cursor {\n /** Value of the column the page is ordered by. */\n readonly key: number;\n readonly id: string;\n}\n\n/** Writes the position of the last row on a page. */\nexport function encodeCursor(key: number, id: string): string {\n return `${key}.${id}`;\n}\n\n/**\n * Reads a cursor back.\n *\n * Split at the last dot rather than the first: a duration key is fractional,\n * and request ids are base36 with no dot in them.\n *\n * Anything unparseable means \"start from the newest\" rather than an error: a\n * stale link is a thing that happens, and answering it with a 400 helps\n * nobody.\n */\nexport function decodeCursor(raw: string | null | undefined): Cursor | null {\n if (!raw) return null;\n const dot = raw.lastIndexOf('.');\n if (dot <= 0) return null;\n const key = Number(raw.slice(0, dot));\n const id = raw.slice(dot + 1);\n if (!Number.isFinite(key) || id === '') return null;\n return { key, id };\n}\n\n/**\n * Whether a row belongs on a page continuing from `cursor`.\n *\n * Strictly past it, so a row is never served twice and never skipped.\n */\nexport function isAfterCursor(cursor: Cursor, key: number, id: string): boolean {\n if (key !== cursor.key) return key < cursor.key;\n return id < cursor.id;\n}\n","/**\n * One page of a list, from records held in memory.\n *\n * The paging rule, in one place: the router's fallback calls it, and so does\n * any store that holds its records in memory. Two implementations of it would\n * mean one panel giving two answers depending on the store behind it.\n *\n * A store that pages in its own query language cannot use this and should not\n * — pushing the work down is why it has a `page()`. What it owes is the same\n * behaviour, which is what the parity test checks.\n */\n\nimport type { RecordedRequest } from '../types.js';\nimport type { PageQuery, RequestPage } from './api.js';\nimport { toRow } from './api.js';\nimport { filterRequests, summarize } from './filters.js';\nimport { decodeCursor, encodeCursor, isAfterCursor } from './paging.js';\n\n/** What the caller knows that the records do not. */\nexport interface PageContext {\n /** Ids currently pinned. Exempt from the filter, and flagged on the row. */\n readonly pinned?: ReadonlySet<string> | undefined;\n /** Above this a request counts as slow in the summary. */\n readonly slowMs?: number | undefined;\n}\n\n/**\n * Pages `records` — newest first — according to `query`.\n *\n * `records` is the store's whole contents: the summary is over all of them,\n * which is what makes the status bar a statement about the store rather than\n * about the page.\n */\nexport function pageFromList(\n records: readonly RecordedRequest[],\n query: PageQuery,\n context: PageContext = {},\n): RequestPage {\n const pinned = context.pinned ?? new Set<string>();\n\n // A pinned request is one the reader deliberately set aside: it stays\n // through a filter that would otherwise exclude it.\n const matched = new Set(filterRequests(records, query.filter).map((item) => item.id));\n const shown = records.filter((item) => matched.has(item.id) || pinned.has(item.id));\n\n // What the page is ordered by, and therefore what the cursor counts in.\n const slowest = query.sort === 'slowest';\n const keyOf = (item: RecordedRequest): number => (slowest ? item.durationMs : item.startedAt);\n // Sorted in both cases: the cursor counts in this order, and a list handed\n // over in arrival order is not in it — a slow request starts early and\n // lands late, and a page boundary beside it would skip or repeat rows.\n const ordered = [...shown].sort((a, b) => keyOf(b) - keyOf(a) || (a.id < b.id ? 1 : -1));\n\n const cursor = decodeCursor(query.cursor);\n const after = cursor\n ? ordered.filter((item) => isAfterCursor(cursor, keyOf(item), item.id))\n : ordered;\n\n const rows = after.slice(0, query.limit);\n const last = rows[rows.length - 1];\n const nextCursor = after.length > rows.length && last ? encodeCursor(keyOf(last), last.id) : null;\n\n return {\n rows: rows.map((item) => toRow(item, pinned.has(item.id))),\n nextCursor,\n summary: summarize(records, shown, context.slowMs),\n };\n}\n","/**\n * Was the process to blame?\n *\n * Knowing an operation is slow does not say why, and often the code did not\n * change at all — the loop fell behind, and every callback waited before it\n * even started. That is invisible in a waterfall: the spans are each fast and\n * the time is between them.\n *\n * The comparison here is a route against itself. Its calls are split by\n * whether the loop was in its *own* top quartile at the time, and the two\n * halves are compared. Elevated is never a fixed threshold: a delay that is\n * alarming for one service is idle for the next, and the only baseline worth\n * comparing a process against is the same process.\n *\n * It is evidence, not proof, and the panel says so. A batch job hammering the\n * same process explains the shape as well as this route being its victim.\n */\n\nimport type { HostPressure, HostPressureSide } from '../types.js';\nimport type { DurationSample } from './api.js';\nimport { percentile } from './routes.js';\n\n/**\n * Calls needed on each side of the split.\n *\n * Twenty is where a ninety-fifth percentile stops being the single slowest\n * call and starts describing a distribution. Below it the comparison is\n * between two anecdotes.\n */\nconst MIN_PER_SIDE = 20;\n\n/**\n * How much slower the bad half has to be before it is worth a word.\n *\n * Under half again, the difference is inside the noise of a sample this size,\n * and a card that fires there is a card that fires always.\n */\nconst MIN_RATIO = 1.5;\n\n/**\n * How much the loop has to have varied for \"elevated\" to mean anything.\n *\n * A host that was flat has no elevated state to compare against: splitting it\n * at its own quartile would sort calls by a millisecond of jitter and then\n * report whatever the two halves happened to differ by.\n */\nconst MIN_SPREAD_MS = 1;\n\nfunction sideOf(durations: readonly number[]): HostPressureSide {\n const sorted = [...durations].sort((a, b) => a - b);\n const sum = sorted.reduce((total, value) => total + value, 0);\n return {\n calls: sorted.length,\n p95Ms: percentile(sorted, 0.95),\n avgMs: sorted.length === 0 ? 0 : sum / sorted.length,\n };\n}\n\n/**\n * The finding, or `null` — which is the answer far more often, and by design.\n *\n * @param samples every other call of the route, as the store hands them over.\n */\nexport function pressureFor(samples: readonly DurationSample[]): HostPressure | null {\n const measured = samples.filter(\n (sample): sample is DurationSample & { loopDelayMs: number } => sample.loopDelayMs !== null,\n );\n if (measured.length < MIN_PER_SIDE * 2) return null;\n\n const delays = measured.map((sample) => sample.loopDelayMs).sort((a, b) => a - b);\n const cutoffMs = percentile(delays, 0.75);\n // Did the loop actually move? Comparing the top quartile against the bottom\n // one answers it without a threshold of its own.\n if (cutoffMs - percentile(delays, 0.25) < MIN_SPREAD_MS) return null;\n\n const elevated = sideOf(\n measured.filter((sample) => sample.loopDelayMs >= cutoffMs).map((sample) => sample.durationMs),\n );\n const normal = sideOf(\n measured.filter((sample) => sample.loopDelayMs < cutoffMs).map((sample) => sample.durationMs),\n );\n if (elevated.calls < MIN_PER_SIDE || normal.calls < MIN_PER_SIDE) return null;\n // Nothing to be slower than: a route where the good half is instant would\n // report a ratio of infinity and mean nothing by it.\n if (normal.p95Ms <= 0) return null;\n\n const ratio = elevated.p95Ms / normal.p95Ms;\n if (ratio < MIN_RATIO) return null;\n\n return {\n metric: 'loop',\n cutoffMs,\n ratio,\n share: (elevated.calls / measured.length) * 100,\n elevated,\n normal,\n };\n}\n","/**\n * What Reqray knows about the application it is watching.\n *\n * The startup report — what was instrumented and what was not — has so far\n * existed only in the terminal, printed once. That is the wrong place for it:\n * \"why do I not see my SQL\" is a question asked hours later, by which point\n * the line has scrolled away, and in a container it was never on screen at\n * all. So the same facts are served to the panel, together with the settings\n * that decide what gets recorded and the shape of the process doing the\n * recording.\n *\n * Nothing secret goes in here. Environment variables are not read, the panel\n * gate is reported as present or absent rather than by value, and the masking\n * lists are field *names*, which is what makes them safe to show and useful\n * to check.\n */\n\nimport { execFile } from 'node:child_process';\nimport { readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join } from 'node:path';\nimport type {\n GitHead,\n ProjectApp,\n ProjectLog,\n ProjectReport,\n ProjectRetention,\n ProjectRuntime,\n ProjectStorage,\n} from '@reqray/protocol';\nimport type { ResolvedOptions } from '../config.js';\nimport { getDiagnostics } from '../diagnostics.js';\nimport { poolStats } from '../pools.js';\n\nexport type {\n GitHead,\n ProjectApp,\n ProjectLog,\n ProjectReport,\n ProjectRetention,\n ProjectRuntime,\n ProjectStorage,\n};\n\n/** The log's own account of itself, or `null` when there is no log. */\nexport function logOf(options: ResolvedOptions): ProjectLog | null {\n const log = options.requestLog;\n if (!log) return null;\n try {\n return { dir: log.dir, ...log.stats() };\n } catch {\n // A log that cannot describe itself is still not the panel's problem.\n return null;\n }\n}\n\n/** The retention policy as the panel sees it. */\nexport function retentionOf(options: ResolvedOptions): ProjectRetention | null {\n const policy = options.retention;\n if (!policy) return null;\n return {\n ...policy.current(),\n writable: policy.writable,\n remembered: policy.file !== null,\n };\n}\n\nfunction readManifest(directory: string): { name?: unknown; version?: unknown } | null {\n try {\n return JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')) as {\n name?: unknown;\n version?: unknown;\n };\n } catch {\n // No manifest where the project root points: unusual, not an error.\n return null;\n }\n}\n\n/** Version of `@reqray/core` itself — the first thing a bug report needs. */\nfunction reqrayVersion(): string | null {\n try {\n const manifest = createRequire(import.meta.url).resolve('@reqray/core/package.json');\n const parsed = JSON.parse(readFileSync(manifest, 'utf8')) as { version?: unknown };\n return typeof parsed.version === 'string' ? parsed.version : null;\n } catch {\n // Running from source, or packaged without the manifest.\n return null;\n }\n}\n\nfunction git(args: readonly string[], cwd: string): Promise<string | null> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n args,\n { cwd, timeout: 2_000, maxBuffer: 64 * 1024, windowsHide: true },\n (error, stdout) => resolve(error ? null : stdout.trim()),\n );\n });\n}\n\ninterface CachedHead {\n readonly at: number;\n readonly head: GitHead | null;\n}\n\nlet cached: CachedHead | null = null;\n/** Short enough to survive a branch switch, long enough to cost nothing. */\nconst GIT_TTL_MS = 10_000;\n\n/**\n * The commit the running code came from.\n *\n * `null` for anything that is not a git checkout — a container built from a\n * tarball, an installed package, a machine without git. All ordinary, none of\n * them an error.\n */\nexport async function gitHead(cwd: string, now = Date.now()): Promise<GitHead | null> {\n if (cached && now - cached.at < GIT_TTL_MS) return cached.head;\n\n const [branch, sha, status] = await Promise.all([\n git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd),\n git(['rev-parse', '--short', 'HEAD'], cwd),\n git(['status', '--porcelain'], cwd),\n ]);\n\n const head = branch === null && sha === null ? null : { branch, sha, dirty: status !== '' };\n cached = { at: now, head };\n return head;\n}\n\n/** Forgets the cached commit. Needed by tests. */\nexport function clearGitHead(): void {\n cached = null;\n}\n\n/** Anything a store may choose to report about itself. */\ninterface StoreStats {\n size?: unknown;\n capacity?: unknown;\n evicted?: unknown;\n oldestAt?: unknown;\n pinned?: unknown;\n bytes?: unknown;\n}\n\nconst numberOr = (value: unknown, fallback: number | null): number | null =>\n typeof value === 'number' ? value : fallback;\n\n/**\n * What the store will say about itself.\n *\n * `stats()` is not part of the panel's contract — the memory ring and the\n * SQLite history both have one, a third-party store need not — so everything\n * here is optional and nothing is assumed.\n */\nexport function storageOf(source: unknown): ProjectStorage | null {\n const store = source as { name?: unknown; stats?: () => StoreStats };\n if (typeof store?.stats !== 'function') return null;\n try {\n const stats = store.stats();\n return {\n name: typeof store.name === 'string' ? store.name : 'unknown',\n size: numberOr(stats.size, 0) ?? 0,\n capacity: numberOr(stats.capacity, null),\n evicted: numberOr(stats.evicted, null),\n oldestAt: numberOr(stats.oldestAt, null),\n pinned: numberOr(stats.pinned, null),\n bytes: numberOr(stats.bytes, null),\n };\n } catch {\n return null;\n }\n}\n\n/** Collects everything the project screen shows. */\nexport async function projectReport(\n options: ResolvedOptions,\n source: unknown,\n): Promise<ProjectReport> {\n const root = options.stack.projectRoot;\n const manifest = readManifest(root);\n const memory = process.memoryUsage();\n\n return {\n app: {\n name: typeof manifest?.name === 'string' ? manifest.name : null,\n version: typeof manifest?.version === 'string' ? manifest.version : null,\n root,\n git: await gitHead(root),\n },\n runtime: {\n node: process.version,\n platform: process.platform,\n arch: process.arch,\n pid: process.pid,\n startedAt: Date.now() - Math.round(process.uptime() * 1000),\n rssMb: memory.rss / 1024 / 1024,\n heapUsedMb: memory.heapUsed / 1024 / 1024,\n },\n reqray: {\n version: reqrayVersion(),\n mode: options.mode,\n enabled: options.enabled,\n isLocalDevelopment: options.isLocalDevelopment,\n bufferSize: options.bufferSize,\n maxSpansPerRequest: options.maxSpansPerRequest,\n sampling: options.sampling,\n replay: options.replay,\n explain: options.explain,\n blame: options.blame,\n logs: options.logs,\n collectSqlValues: options.collectSqlValues,\n // The gate is a function or a rule; either way it is a credential, and\n // the panel only needs to know that one is in place.\n panel: options.panel\n ? { path: options.panel.path, gated: options.panel.gate !== null }\n : null,\n redact: { headers: options.redact.headers, body: options.redact.body },\n detect: options.detect as unknown as Readonly<Record<string, unknown>>,\n stack: options.stack,\n },\n instrumentation: getDiagnostics(),\n storage: storageOf(source),\n log: logOf(options),\n retention: retentionOf(options),\n pools: poolStats(),\n };\n}\n","/**\n * Startup diagnostics.\n *\n * The library prints what it instrumented and what it could not, with a hint\n * on how to fix it. This heads off most of the future \"I don't see my\n * requests\" issues.\n */\n\nimport type { DiagnosticEntry } from '@reqray/protocol';\nimport { info } from './logger.js';\nimport { globalBox, globalSlot } from './state.js';\n\n/** The instrumentation report, collected at startup. */\nconst report = globalSlot('diagnostics.report', () => [] as DiagnosticEntry[]);\n\nconst printed = globalBox('diagnostics.printed', false);\n\nexport type { DiagnosticEntry };\n\n/** Records the outcome of an attempt to instrument a package. */\nexport function reportInstrumentation(entry: DiagnosticEntry): void {\n report().push(entry);\n}\n\n/** Everything collected so far. */\nexport function getDiagnostics(): readonly DiagnosticEntry[] {\n return report();\n}\n\n/** Clears the report. Needed by tests. */\nexport function clearDiagnostics(): void {\n report().length = 0;\n}\n\nfunction labelOf(entry: DiagnosticEntry): string {\n if (entry.builtin) return `${entry.name} (built-in)`;\n return entry.version ? `${entry.name}@${entry.version}` : entry.name;\n}\n\n/**\n * Renders the report as text.\n *\n * Kept as a separate pure function so the format can be asserted in a test\n * without intercepting the console.\n */\nexport function renderDiagnostics(report: readonly DiagnosticEntry[]): string {\n const active = report.some((entry) => entry.ok);\n const header = active ? 'reqray instrumentation active' : 'reqray instrumentation not attached';\n if (report.length === 0) return header;\n\n const width = Math.max(...report.map((entry) => labelOf(entry).length)) + 4;\n const lines = [header];\n\n for (const entry of report) {\n const mark = entry.ok ? '✔' : '✘';\n const detail = entry.ok ? entry.captures : (entry.reason ?? entry.captures);\n lines.push(` ${mark} ${labelOf(entry).padEnd(width)}${detail}`);\n if (entry.hint) lines.push(` ${' '.repeat(width + 2)}→ ${entry.hint}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * What to say under the report about a panel with no gate.\n *\n * Such a panel answers its own machine and nobody else, and the person who\n * finds that out is looking at a 403 from inside a dev container or behind a\n * local proxy. Said at startup, it is a line read once instead of an issue.\n */\nexport const UNGATED_PANEL_NOTE = [\n ' panel answers this machine only: no gate is set',\n \" → from a container, a proxy or another machine: reqray({ panel: { gate: 'open' } })\",\n].join('\\n');\n\n/** Prints the report. Called once when Reqray initializes. */\nexport function printDiagnostics(note?: string): void {\n const text = renderDiagnostics(report());\n info(note ? `${text}\\n${note}` : text);\n}\n\n/**\n * Prints the report at most once per process lifetime.\n *\n * An application may have several adapters, but only needs one report.\n */\nexport function printDiagnosticsOnce(note?: string): void {\n const once = printed();\n if (once.value) return;\n once.value = true;\n printDiagnostics(note);\n}\n\n/** Allows the report to be printed again. Needed by tests. */\nexport function resetDiagnosticsPrinted(): void {\n printed().value = false;\n}\n","/**\n * Registry of live connection pools.\n *\n * A pool is the one part of the picture that cannot be reconstructed from\n * spans. A span says a query waited; only the pool says whether it was the\n * last free connection or the fortieth request in a queue, and that is the\n * difference between \"raise `max`\" and \"stop holding connections\". So the\n * panel asks the pool itself, at the moment somebody is looking.\n *\n * Two rules hold this together.\n *\n * References are weak. A pool that the application closed and dropped must be\n * collectable; a registry that keeps one alive is a leak with a nice name.\n *\n * And core knows nothing about any driver. Each instrumentation registers its\n * pools with a reader that speaks that driver's dialect — `totalCount` and\n * `idleCount` in `pg`, something else in the next one — so this file never\n * grows a `if (driver === …)`.\n */\n\nimport type { PoolReading, PoolStats } from '@reqray/protocol';\nimport { type Box, globalBox, globalSlot } from './state.js';\n\n/** A registered pool: the reference stays weak, the reader knows the driver. */\ninterface PoolEntry {\n readonly id: number;\n readonly ref: WeakRef<object>;\n readonly read: (pool: object) => PoolReading | null;\n}\n\n/** Live pools, weakly held. */\nconst pools = globalSlot('pools.live', () => new Set<PoolEntry>());\n\n/** Pools already registered, keyed by the pool itself. */\nconst registered = globalSlot('pools.registered', () => new WeakMap<object, PoolEntry>());\n\n/** Id source for {@link pools}. */\nconst sequence: () => Box<number> = globalBox('pools.sequence', 0);\n\nexport type { PoolReading, PoolStats };\n\n/**\n * Registers a pool, idempotently.\n *\n * Called from the instrumentation on every pooled query, so it has to be\n * cheap and it has to tolerate being called a million times: a pool already\n * registered costs one `WeakMap` lookup and nothing else.\n */\nexport function registerPool(pool: object, read: (pool: object) => PoolReading | null): void {\n try {\n const known = registered();\n if (known.has(pool)) return;\n\n const seq = sequence();\n seq.value += 1;\n const entry: PoolEntry = { id: seq.value, ref: new WeakRef(pool), read };\n known.set(pool, entry);\n pools().add(entry);\n } catch {\n // A registry failure must never reach the query that triggered it.\n }\n}\n\n/**\n * What every live pool says about itself, right now.\n *\n * Entries whose pool has been collected are dropped on the way past: this is\n * the only moment the registry is walked, so it is the only place the dead\n * ones can be noticed.\n */\nexport function poolStats(): PoolStats[] {\n const stats: PoolStats[] = [];\n try {\n const live = pools();\n for (const entry of live) {\n const pool = entry.ref.deref();\n if (!pool) {\n live.delete(entry);\n continue;\n }\n try {\n const reading = entry.read(pool);\n if (reading) stats.push({ id: entry.id, ...reading });\n } catch {\n // A driver that changed shape reports nothing rather than throwing\n // into whoever opened the panel.\n }\n }\n } catch {\n return stats;\n }\n return stats;\n}\n\n/** Forgets every pool. Needed by tests. */\nexport function resetPools(): void {\n pools().clear();\n}\n","/**\n * Where a replayed request's record is delivered.\n *\n * A replay runs through the application like any other request, so it is\n * recorded like any other request — and it must not appear in the shared list,\n * because nobody made it. The panel marks it with a header, the adapter puts\n * the marker on the scope, and when the request finishes its record goes to\n * whoever started the replay instead of to the store.\n *\n * The registry sits between the two: `reqray.ts` writes into it on the\n * recording path, `panel/replay.ts` reads from it, and neither imports the\n * other. The one piece of state both entry points share.\n */\n\nimport { globalSlot } from './state.js';\nimport type { RecordedRequest } from './types.js';\n\n/** Replays in flight, by the id the panel put on the request. */\nconst waiters = globalSlot(\n 'replay.waiters',\n () => new Map<string, (request: RecordedRequest) => void>(),\n);\n\n/** Registers interest in a replay's record. Returns the way to stop waiting. */\nexport function awaitReplay(id: string, deliver: (request: RecordedRequest) => void): () => void {\n waiters().set(id, deliver);\n return () => {\n waiters().delete(id);\n };\n}\n\n/**\n * Hands a finished replay to whoever asked for it.\n *\n * @returns whether anybody was waiting — `false` means the record belongs in\n * the store after all, which is what happens when a replay times out and its\n * response arrives anyway.\n */\nexport function deliverReplay(id: string, request: RecordedRequest): boolean {\n const waiter = waiters().get(id);\n if (!waiter) return false;\n waiter(request);\n return true;\n}\n","/**\n * The Reqray runtime: what framework adapters call on every request.\n *\n * This is the hot-path boundary. `begin` and `finish` must cost close to\n * nothing; detectors, masking, serialization and the transport write are\n * deferred to `setImmediate`, where they no longer affect the client's\n * response time.\n */\n\nimport { join } from 'node:path';\nimport { recordBody } from './body.js';\nimport { type ReqrayOptions, type ResolvedOptions, resolveOptions } from './config.js';\nimport { instrumentConsole } from './console-capture.js';\nimport { runOutsideScope } from './context.js';\nimport { measureCost, startCostMeter, stopCostMeter } from './cost.js';\nimport { runDetectors } from './detectors/index.js';\nimport { printDiagnosticsOnce, UNGATED_PANEL_NOTE } from './diagnostics.js';\nimport { type HostMonitor, startHostMonitor } from './host.js';\nimport { nextRequestId } from './ids.js';\nimport { warn, warnOnce } from './logger.js';\nimport { assertPanelAllowed } from './panel.js';\nimport { type HotFrame, type RequestProfiler, startProfiler } from './profiler.js';\nimport { redactHeaders, redactQuery } from './redact.js';\nimport { deliverReplay } from './replay-waiters.js';\nimport { shouldRetain } from './sampling.js';\nimport { RequestScope } from './scope.js';\nimport { selfTimes, timingOf } from './timing.js';\nimport { multiTransport, nullTransport, type Transport } from './transport.js';\nimport type { Finding, LogEntry, RecordedRequest, RequestCost, SpanError } from './types.js';\nimport { weightOf } from './weight.js';\n\n/** Headers in the shape Node and the frameworks hand them over. */\nexport type HeaderMap = Readonly<Record<string, string | string[] | number | undefined>>;\n\n/** What is known about a request when it starts. */\nexport interface RequestStart {\n readonly method: string;\n /** Path without the query string. */\n readonly path: string;\n /**\n * Value of the replay marker header, if present.\n *\n * Such a request stays out of the main list: its record goes to the panel\n * that started the replay.\n */\n readonly replayId?: string | null;\n}\n\n/** Request outcome. Passed by the adapter once the response has been sent. */\nexport interface RequestOutcome {\n readonly status: number;\n /** Query string without the `?`, if there was one. */\n readonly query?: string | null;\n readonly requestHeaders?: HeaderMap;\n readonly responseHeaders?: HeaderMap;\n readonly requestBody?: unknown;\n readonly responseBody?: unknown;\n /** The exception, if handling failed. */\n readonly error?: unknown;\n}\n\n/** What an adapter drives on every request. */\nexport interface Reqray {\n readonly options: ResolvedOptions;\n readonly transport: Transport;\n\n /**\n * Starts a request.\n *\n * @returns the scope, or `undefined` if Reqray is disabled. In that case the\n * adapter must do nothing at all — this is what \"disabled Reqray costs zero\"\n * means.\n */\n begin(start: RequestStart): RequestScope | undefined;\n\n /** Finishes a request. Safely accepts `undefined`. */\n finish(scope: RequestScope | undefined, outcome: RequestOutcome): void;\n\n /**\n * Stops what this runtime started and lets go of what it holds.\n *\n * `createReqray` starts a host monitor and may open a store; `Transport`\n * declares both `flush` and `close`, and there was no way to reach either.\n * A long-lived process never needed this; a test that builds a runtime per\n * case, and a graceful shutdown that wants the last batch to land, both do.\n *\n * Safe to call twice.\n */\n close(): Promise<void>;\n}\n\n/** Runtime creation options. */\nexport interface ReqrayInit extends ReqrayOptions {\n /**\n * Where to put collected requests.\n *\n * Several are allowed and are written to in order: a store the panel reads\n * and a log file on disk are two transports over one stream of requests.\n */\n readonly transport?: Transport | readonly Transport[];\n}\n\n/**\n * Coerces anything thrown into a `SpanError`.\n *\n * Needed by instrumentations: they mark a span with an error but must rethrow\n * the exception itself unchanged.\n */\nexport function toSpanError(error: unknown): SpanError | null {\n if (error === undefined || error === null) return null;\n if (error instanceof Error) {\n return { name: error.name, message: error.message, stack: error.stack ?? null };\n }\n return { name: 'Error', message: String(error), stack: null };\n}\n\nfunction formatDuration(durationMs: number): string {\n return durationMs < 10 ? `${durationMs.toFixed(1)} ms` : `${Math.round(durationMs)} ms`;\n}\n\n/**\n * Brackets the collected log lines with a request start and end line.\n *\n * Assembled at finalization rather than on the hot path: both lines are fully\n * derived from data already known.\n */\nfunction bracketLogs(scope: RequestScope, status: number, durationMs: number): LogEntry[] {\n return [\n { at: 0, level: 'info', message: `→ ${scope.method} ${scope.path}` },\n ...scope.logs,\n {\n at: durationMs,\n level: status >= 500 ? 'error' : 'info',\n message: `← ${status} in ${formatDuration(durationMs)}`,\n },\n ];\n}\n\n/** How a test harness names the test behind a request. */\nexport const TEST_HEADER = 'x-reqray-test';\n\n/**\n * Header that marks a replay.\n *\n * Beside `TEST_HEADER` rather than in the panel: both are read off an incoming\n * request by the adapter, on the recording path. The panel writes this one,\n * which does not make it the panel's.\n */\nexport const REPLAY_HEADER = 'x-reqray-replay';\n\n/** The maximum length of a test name kept in a record. */\nconst MAX_TEST_NAME = 200;\n\n/**\n * The test that issued the request, from the header the harness sets.\n *\n * Read from the raw headers rather than the redacted copy: masking may have\n * replaced the value, and this one is a test name, not a secret.\n *\n * Header values are latin1, and test names are full of characters that are\n * not — Vitest and Jest separate suite from case with `›`. A percent-encoded\n * value is therefore decoded; anything that fails to decode is kept as sent,\n * because a slightly odd name is better than no name.\n */\nfunction testOf(outcome: RequestOutcome): string | null {\n const raw = outcome.requestHeaders?.[TEST_HEADER];\n const value = Array.isArray(raw) ? raw[0] : raw;\n if (typeof value !== 'string') return null;\n let trimmed = value.trim();\n if (trimmed.includes('%')) {\n try {\n trimmed = decodeURIComponent(trimmed);\n } catch {\n // Not percent-encoded after all — a literal `%` in the name.\n }\n }\n // Decoding can produce what a header never could: `%0A` is a line break,\n // and this name is later written into a shell script and onto a terminal.\n trimmed = trimmed.replace(/\\p{Cc}/gu, ' ').trim();\n return trimmed ? trimmed.slice(0, MAX_TEST_NAME) : null;\n}\n\n/**\n * How much went back to the client, cheaply.\n *\n * What the client was told, when it was told anything; the body's own size\n * when the framework streamed it as text. An object body is not serialized\n * here to find out — that is the expensive half of finishing a request, and\n * it happens once, later, for the requests that are kept.\n */\nfunction bytesOutOf(outcome: RequestOutcome): number | null {\n const declared = Number(outcome.responseHeaders?.['content-length']);\n if (Number.isFinite(declared) && declared >= 0) return declared;\n return typeof outcome.responseBody === 'string' ? Buffer.byteLength(outcome.responseBody) : null;\n}\n\n/** What the response said it was, without the charset and the rest. */\nfunction contentTypeOf(outcome: RequestOutcome): string | null {\n const raw = outcome.responseHeaders?.['content-type'];\n const value = Array.isArray(raw) ? raw[0] : raw;\n return typeof value === 'string' ? (value.split(';')[0]?.trim() ?? null) : null;\n}\n\n/**\n * Masking and measurement, done once.\n *\n * The detectors need to know how much came back, and the record needs the\n * same masked headers and bodies. Doing it twice would mean masking twice —\n * the expensive half of finishing a request — so it happens here, after the\n * response is on the wire, and both readers share the result.\n */\nfunction prepare(scope: RequestScope, outcome: RequestOutcome, options: ResolvedOptions) {\n const redact = options.redact;\n const requestHeaders = outcome.requestHeaders\n ? redactHeaders(outcome.requestHeaders, redact)\n : {};\n const responseHeaders = outcome.responseHeaders\n ? redactHeaders(outcome.responseHeaders, redact)\n : {};\n const spans = scope.orderedSpans();\n const requestBody = recordBody(outcome.requestBody, redact);\n const responseBody = recordBody(outcome.responseBody, redact);\n return {\n spans,\n requestHeaders,\n responseHeaders,\n requestBody,\n responseBody,\n weight: weightOf({ spans, requestHeaders, responseHeaders, requestBody, responseBody }),\n };\n}\n\ntype Prepared = ReturnType<typeof prepare>;\n\n/**\n * Completes a slow-code finding with what was actually running in it.\n *\n * The detector can only name the boundary: `shop.js:231` is the query the\n * stretch ends at, not the `pbkdf2Sync` three lines above it that spent the\n * time. Samples know the difference, so where the profiler has them the\n * finding stops pointing at the edge of the hole and points into it.\n *\n * Only the frames are inserted when the window turns out to have been idle.\n * A stretch spent waiting has no line of code to blame, and moving the\n * callsite to whatever ran for two of its samples would be worse than the\n * boundary it already had.\n */\nfunction withHotSpots(\n findings: readonly Finding[],\n scope: RequestScope,\n profiler: RequestProfiler | null,\n): Finding[] {\n if (!profiler) return [...findings];\n\n return findings.map((finding) => {\n const evidence = finding.evidence;\n if (evidence.kind !== 'slow_code') return finding;\n\n const from = scope.startTime + evidence.atMs;\n const hot = profiler.read(from, from + evidence.stretchMs);\n if (!hot) return finding;\n\n const top = hot.frames[0];\n const running = hot.busyShare >= RUNNING_SHARE && top !== undefined;\n\n return {\n ...finding,\n ...(running\n ? {\n callsite: {\n file: join(scope.options.stack.projectRoot, top.relative),\n relative: top.relative,\n line: top.line,\n column: 0,\n },\n title: `${Math.round(evidence.stretchMs)} ms in ${top.functionName}`,\n hint: hintForFrame(top),\n }\n : {\n hint: `Only ${Math.round(hot.busyShare * 100)}% of the samples taken in this stretch were on a processor, so the time went on waiting rather than on running — I/O with no instrumentation behind it, or a timer.`,\n }),\n evidence: { ...evidence, frames: hot.frames, busyShare: hot.busyShare },\n };\n });\n}\n\n/**\n * Where to look, and what to look for once there.\n *\n * V8 reports the line a function is defined on, never the line executing, so\n * the address can only be the function. Naming what it was calling is what\n * closes the remaining distance: `registerUser` at `shop.js:213` is where,\n * and `pbkdf2Sync` is the call inside it that spent the time.\n */\nfunction hintForFrame(frame: HotFrame): string {\n const where = `${Math.round(frame.share * 100)}% of the samples in this stretch were inside ${frame.functionName} at ${frame.relative}:${frame.line}`;\n return frame.inside\n ? `${where}, calling ${frame.inside}. V8 reports where a function starts rather than the line running, so look for the ${frame.inside} call.`\n : `${where}.`;\n}\n\n/**\n * Above this share of running samples, a stretch is called code and the\n * finding is re-aimed at the function holding it.\n *\n * Below it the stretch was mostly waiting, and the busiest frame is whatever\n * the sampler caught on the way past.\n */\nconst RUNNING_SHARE = 0.5;\n\n/**\n * Microseconds between stack samples.\n *\n * A millisecond resolves a hundred-millisecond stretch into roughly eighty\n * readings, which is enough for a share to mean something, and measured at\n * about seven microseconds on a request's p99 — under a fiftieth of the\n * budget the published overhead numbers are held to.\n */\nconst SAMPLE_INTERVAL_US = 1_000;\n\nfunction buildRecord(\n scope: RequestScope,\n outcome: RequestOutcome,\n durationMs: number,\n findings: readonly Finding[],\n host: HostMonitor | null,\n prepared: Prepared,\n cost: RequestCost,\n): RecordedRequest {\n const { spans, requestHeaders, responseHeaders, requestBody, responseBody } = prepared;\n const self = selfTimes(spans);\n return {\n id: scope.id,\n method: scope.method,\n path: scope.path,\n query: outcome.query ? redactQuery(outcome.query, scope.options.redact) : null,\n status: outcome.status,\n durationMs,\n timing: timingOf(spans, durationMs),\n weight: prepared.weight,\n // The window the request ran in, not a measurement of the request: two\n // native reads, and the panel says so in as many words.\n host: host?.read() ?? null,\n cost,\n startedAt: scope.startedAt,\n // Self time is attached here rather than at display time so that the\n // panel, the terminal client and anything else reading the API get one\n // number rather than three implementations of the same subtraction.\n spans: spans.map((span) => ({ ...span, selfMs: self.get(span.id) ?? span.duration })),\n findings,\n // Masking happens before the buffer write, not at display time.\n requestHeaders,\n responseHeaders,\n requestBody,\n responseBody,\n logs: bracketLogs(scope, outcome.status, durationMs),\n error: toSpanError(outcome.error),\n droppedSpans: scope.droppedSpans,\n droppedLogs: scope.droppedLogs,\n test: testOf(outcome),\n };\n}\n\n/**\n * Creates the runtime.\n *\n * If the panel is enabled somewhere it could be reachable from outside and no\n * gate is set, this throws right here, at application startup.\n */\nexport function createReqray(init: ReqrayInit = {}): Reqray {\n const options = resolveOptions(init);\n\n // Before any resource is acquired: this throws on the staging path, and a\n // monitor started first would tick on with nothing left to stop it.\n if (options.enabled) assertPanelAllowed(options);\n\n const transport = Array.isArray(init.transport)\n ? multiTransport(init.transport)\n : ((init.transport as Transport | undefined) ?? nullTransport);\n\n // One histogram for the process, started with it: a request that finishes\n // asks the monitor what the loop was doing, and gets an answer or a null.\n const host = options.enabled && options.hostMetrics ? startHostMonitor() : null;\n\n // The collector is watched from the moment Reqray is: a request's cost is\n // read at its edges, so there is nothing to switch on per request.\n if (options.enabled) startCostMeter();\n\n // Sampling runs for the process, not per request: a stretch worth\n // explaining is only known about once it is over.\n const profiler =\n options.enabled && options.profile\n ? startProfiler({ stack: options.stack, intervalUs: SAMPLE_INTERVAL_US })\n : null;\n\n if (options.enabled) {\n // A global tap; whether a line is recorded is decided per request from\n // its scope's options.\n if (options.logs) instrumentConsole();\n if (options.replay && !options.isLocalDevelopment) {\n warn(\n 'replay is enabled outside local development. Replaying a request in production means charging a card twice and sending an email twice.',\n );\n }\n // The report is printed on the next tick: by then the adapter has reported\n // itself and the loader hooks have reported everything loaded so far.\n const ungated = options.panel !== null && options.panel.gate === null;\n setImmediate(() => printDiagnosticsOnce(ungated ? UNGATED_PANEL_NOTE : undefined));\n }\n\n let closed = false;\n\n return {\n options,\n transport,\n\n begin(start) {\n if (!options.enabled) return undefined;\n return new RequestScope({\n id: nextRequestId(),\n method: start.method,\n path: start.path,\n options,\n replayId: start.replayId ?? null,\n });\n },\n\n finish(scope, outcome) {\n if (!scope) return;\n\n try {\n scope.closeAllSpans();\n } catch {\n // An unclosed span is no reason to lose the whole request.\n }\n // The one thing that cannot wait: measured now, or it measures the\n // scheduling delay as well. The cost is read here for the same reason —\n // the processor time of the tick that follows is not this request's.\n const durationMs = performance.now() - scope.startTime;\n const cost = measureCost(scope.costMark, scope.startTime, durationMs);\n\n setImmediate(() => {\n // Reqray's own work must not end up as spans of the request being handled.\n runOutsideScope(() => {\n try {\n // What the detectors need to know about the request as a whole;\n // the scope only knows about spans. Read straight off the outcome\n // rather than from the prepared record: in production the\n // detectors run before the sampling decision, and masking a body\n // about to be dropped is work nobody asked for.\n //\n // Built here rather than above, because everything in it is\n // derivable from `outcome`, which the closure already holds — and\n // the response path is not the place to allocate an object and\n // split a content-type header.\n const facts = {\n durationMs,\n status: outcome.status,\n bytesOut: bytesOutOf(outcome),\n contentType: contentTypeOf(outcome),\n };\n\n // A replay is not sampled: its record is needed exactly once and\n // right now — the comparison block in the panel is built from it.\n if (\n scope.replayId &&\n deliverReplay(\n scope.replayId,\n buildRecord(\n scope,\n outcome,\n durationMs,\n withHotSpots(runDetectors(scope, options, facts), scope, profiler),\n host,\n prepare(scope, outcome, options),\n cost,\n ),\n )\n ) {\n return;\n }\n\n const hasError = outcome.error !== undefined && outcome.error !== null;\n\n // Detectors run before sampling only when a finding is itself a\n // reason to keep the request. Otherwise they run on the requests\n // that survived, which in production is one in a hundred.\n const findingsFirst = options.sampling.alwaysOnFinding;\n const findings = findingsFirst ? runDetectors(scope, options, facts) : [];\n\n const retained = shouldRetain(options.sampling, {\n durationMs,\n status: outcome.status,\n hasError,\n findings,\n });\n if (!retained) return;\n\n transport.send(\n buildRecord(\n scope,\n outcome,\n durationMs,\n withHotSpots(\n findingsFirst ? findings : runDetectors(scope, options, facts),\n scope,\n profiler,\n ),\n host,\n prepare(scope, outcome, options),\n cost,\n ),\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('reqray.finish', `request not recorded: ${reason}`);\n }\n });\n });\n },\n\n async close() {\n if (closed) return;\n closed = true;\n\n host?.stop();\n profiler?.stop();\n stopCostMeter();\n // Flush before close: the point of closing gracefully is that the last\n // batch lands, and a transport that buffers has nowhere to put it after.\n try {\n await transport.flush?.();\n } catch {\n // A shutdown must not fail because a collector was already gone.\n }\n try {\n await transport.close?.();\n } catch {\n // Same.\n }\n },\n };\n}\n","/**\n * Console capture: log lines written while a request is being handled land in\n * that request's record.\n *\n * Without this, \"you see the whole request\" is a third of a lie — the log of\n * the incident stays in the shared stdout haystack. The tap is deliberately\n * humble:\n *\n * - the original console is always called, with the original arguments, and\n * its output is never altered — capture failing must not cost a single\n * character of terminal output;\n * - no scope — nothing but the passthrough happens;\n * - a line whose normalized text mentions a sensitive pattern is replaced by\n * a marker: free-form text has no field names to mask by, and over-masking\n * is the side this project errs on.\n *\n * Limitation, stated honestly: pino and winston write past `console`, so only\n * `console.*` lines are captured. A pino stream is a separate task.\n */\n\nimport { format } from 'node:util';\nimport { current } from './context.js';\nimport { sensitivePatternIn, truncate } from './redact.js';\nimport type { LogEntry } from './types.js';\n\n/** \"Already patched\" marker: two copies of core must not stack wrappers. */\nconst PATCHED = Symbol.for('reqray.patched.console');\n\nconst METHODS = ['log', 'info', 'warn', 'error', 'debug'] as const;\ntype ConsoleMethod = (typeof METHODS)[number];\n\nconst LEVEL_OF: Record<ConsoleMethod, LogEntry['level']> = {\n log: 'info',\n info: 'info',\n warn: 'warn',\n error: 'error',\n debug: 'debug',\n};\n\ntype ConsoleHolder = Console & { [PATCHED]?: Partial<Record<ConsoleMethod, unknown>> };\n\nfunction capture(method: ConsoleMethod, args: readonly unknown[]): void {\n try {\n const scope = current();\n if (!scope?.options.logs) return;\n\n const redact = scope.options.redact;\n let line = format(...args);\n const hit = sensitivePatternIn(line, redact.body);\n line = hit ? `[line withheld: mentions \"${hit}\"]` : truncate(line, redact.maxStringLength);\n\n scope.addLog(LEVEL_OF[method], line);\n } catch {\n // The passthrough below must survive anything that happens here.\n }\n}\n\n/**\n * Installs the console tap. Idempotent; called by `createReqray`.\n *\n * Whether a line is recorded is decided per request from `scope.options`, so\n * one global tap serves any number of runtimes.\n */\nexport function instrumentConsole(): void {\n const holder = console as ConsoleHolder;\n if (holder[PATCHED]) return;\n\n const originals: Partial<Record<ConsoleMethod, unknown>> = {};\n for (const method of METHODS) {\n const original = holder[method];\n if (typeof original !== 'function') continue;\n originals[method] = original;\n\n holder[method] = function reqrayConsole(this: unknown, ...args: unknown[]) {\n capture(method, args);\n return (original as (...inner: unknown[]) => unknown).apply(this, args);\n };\n }\n holder[PATCHED] = originals;\n}\n\n/** Restores the original console. Needed by tests. */\nexport function uninstrumentConsole(): void {\n const holder = console as ConsoleHolder;\n const originals = holder[PATCHED];\n if (!originals) return;\n\n for (const method of METHODS) {\n const original = originals[method];\n if (original) holder[method] = original as Console[ConsoleMethod];\n }\n delete holder[PATCHED];\n}\n","/**\n * What one request cost the process.\n *\n * The waterfall answers \"how long did it take\". It does not answer \"what did\n * it cost to run\", and the two come apart constantly: a request that waits\n * 800 ms on a database is cheap, and one that spends 80 ms hashing a password\n * is expensive. A list sorted by duration puts the first one on top and the\n * second one nowhere, which is the wrong way round for anyone asking what\n * their process is actually spending itself on.\n *\n * Everything here is measured at the edges of a request and costs about a\n * microsecond, so it is always on. What it cannot do is name the function\n * that burned the time — that needs the sampling profiler, which is a\n * decision rather than a setting.\n *\n * ## What is honest to report, and what is not\n *\n * `process.cpuUsage()` measures the *process*, so the delta across a\n * request's window belongs to the request only when nothing else was running\n * in it. That is why `overlap` travels with every reading: the number of\n * other requests that shared the window. At zero, the CPU figure is this\n * request's. Above it, the figure is the window's and the panel says so\n * rather than dividing by a guess.\n *\n * Retained memory is deliberately absent. There is no way in V8 to ask what a\n * request still holds, and a number invented for the column would be wrong in\n * exactly the cases somebody would act on it. What can be measured is the\n * garbage collector's time inside the window, which is what allocation\n * pressure actually costs the request that triggers it.\n */\n\nimport { type PerformanceEntry, PerformanceObserver } from 'node:perf_hooks';\nimport { warnOnce } from './logger.js';\nimport { globalSlot } from './state.js';\n\n/** A garbage collection, in the same clock spans are placed on. */\ninterface Pause {\n /** `performance.now()` when it started. */\n readonly at: number;\n readonly ms: number;\n}\n\n/**\n * How many recent collections are remembered.\n *\n * Only pauses inside a request's window are ever read, and a request outlives\n * at most a few hundred of them. The ring is what keeps an idle process from\n * accumulating a day of garbage-collection history nobody will ask about.\n */\nconst PAUSE_HISTORY = 512;\n\n/**\n * A collection shorter than this is not worth attributing.\n *\n * Minor collections run constantly and cost tens of microseconds; summing\n * every one of them would produce a figure made mostly of noise.\n */\nconst PAUSE_FLOOR_MS = 0.1;\n\ninterface Meter {\n /** Recent collections, oldest first, capped at {@link PAUSE_HISTORY}. */\n pauses: Pause[];\n /** Requests currently in flight. */\n active: number;\n /** Requests begun since the process started — a monotonic clock of arrivals. */\n begun: number;\n observer: PerformanceObserver | null;\n}\n\n/**\n * Process-wide, and shared across Reqray instances by design.\n *\n * Two Reqray instances in one process observe one garbage collector and one\n * CPU clock. Giving each its own observer would double the cost of watching\n * and still measure the same thing twice.\n */\nconst meter = globalSlot(\n 'cost.meter',\n (): Meter => ({ pauses: [], active: 0, begun: 0, observer: null }),\n);\n\n/**\n * Starts watching the collector.\n *\n * Never throws: on a runtime that does not report collections, every request\n * simply has nothing to say about garbage collection, which is what an\n * unmeasured thing looks like.\n */\nexport function startCostMeter(): void {\n const state = meter();\n if (state.observer) return;\n\n try {\n const observer = new PerformanceObserver((list) => {\n const { pauses } = meter();\n for (const entry of list.getEntries() as PerformanceEntry[]) {\n if (entry.duration < PAUSE_FLOOR_MS) continue;\n pauses.push({ at: entry.startTime, ms: entry.duration });\n }\n if (pauses.length > PAUSE_HISTORY) pauses.splice(0, pauses.length - PAUSE_HISTORY);\n });\n observer.observe({ type: 'gc' });\n state.observer = observer;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('cost.gc', `garbage collection is not being measured: ${reason}`);\n }\n}\n\n/** Stops watching. For tests and shutdown. */\nexport function stopCostMeter(): void {\n const state = meter();\n try {\n state.observer?.disconnect();\n } catch {\n // An observer that will not disconnect is not worth an exception.\n }\n state.observer = null;\n state.pauses = [];\n state.active = 0;\n state.begun = 0;\n}\n\n/** What is read at the start of a request and subtracted at the end. */\nexport interface CostMark {\n readonly cpu: NodeJS.CpuUsage;\n /** Requests already in flight when this one began. */\n readonly overlapping: number;\n /** Arrivals so far, so requests begun during this window can be counted. */\n readonly begun: number;\n}\n\n/**\n * Opens the measurement. Called once per request, on the hot path.\n *\n * About a microsecond, almost all of it `process.cpuUsage()`.\n */\nexport function markCost(): CostMark {\n const state = meter();\n const mark = { cpu: process.cpuUsage(), overlapping: state.active, begun: state.begun };\n state.active++;\n state.begun++;\n return mark;\n}\n\n/** What one request cost, as the panel reports it. */\nexport interface RequestCost {\n /** Processor time in the request's window, user and system, ms. */\n readonly cpuMs: number;\n /**\n * That time as a share of the wall clock. `1` is a request that spent its\n * whole life on a processor.\n *\n * Deliberately not capped. `process.cpuUsage()` counts every thread the\n * process has — the libuv pool doing filesystem, DNS, zlib and crypto work,\n * and any worker threads — so a request that fanned work out across cores\n * genuinely spends more processor time than wall time. Capping it at one\n * would turn the most interesting reading on the screen into the same\n * number as an ordinary busy request.\n */\n readonly cpuShare: number;\n /** Time the garbage collector took inside the window, ms. */\n readonly gcMs: number;\n /** Collections inside the window. */\n readonly collections: number;\n /**\n * Other requests that shared the window.\n *\n * Part of the honesty dial on `cpuMs`, and only part of it: it counts\n * requests, and the processor clock counts threads. A request can be alone\n * in the process and still show more processor time than wall time, because\n * the libuv pool was busy on its behalf — which is why `cpuShare` above one\n * is a reading in its own right rather than a contradiction of this field.\n */\n readonly overlap: number;\n}\n\n/**\n * Closes the measurement.\n *\n * Must be called synchronously when the response ends, for the same reason\n * the duration is: a reading taken a tick later has the tick in it.\n */\nexport function measureCost(mark: CostMark, startTime: number, durationMs: number): RequestCost {\n const state = meter();\n state.active = Math.max(0, state.active - 1);\n\n const spent = process.cpuUsage(mark.cpu);\n const cpuMs = (spent.user + spent.system) / 1000;\n\n const end = startTime + durationMs;\n let gcMs = 0;\n let collections = 0;\n for (const pause of state.pauses) {\n if (pause.at < startTime || pause.at > end) continue;\n gcMs += pause.ms;\n collections++;\n }\n\n return {\n cpuMs,\n // Uncapped on purpose; see the field. Drawing it is the client's problem,\n // and a client that clamps a bar is not the same as a measurement that\n // throws the excess away.\n cpuShare: durationMs > 0 ? cpuMs / durationMs : 0,\n gcMs,\n collections,\n // Those already running when this began, plus those that arrived while it\n // ran. An upper bound on distinct company, computed in constant time.\n overlap: mark.overlapping + (state.begun - mark.begun - 1),\n };\n}\n","/**\n * What the process was doing while a request was in flight.\n *\n * A route that got slower with no change to its span timings is not a slow\n * route; it is a process that could not get scheduled. That is invisible in a\n * waterfall — every span is individually fast, and the time is *between*\n * them — and it is the more common answer for a Node backend than anything\n * the database did.\n *\n * The measurement is deliberately of the process, never of the request. Under\n * concurrency the code that blocked the loop is usually somebody else's, and\n * a number that says \"this request burned 180 ms of CPU\" is wrong often\n * enough to make every other number on the screen suspect.\n */\n\nimport { monitorEventLoopDelay } from 'node:perf_hooks';\nimport { warnOnce } from './logger.js';\nimport type { HostState } from './types.js';\n\nexport interface HostMonitor {\n /**\n * The window in progress, or `null` when nothing has been measured yet.\n *\n * Read when a request finishes, so what it carries is the loop's behaviour\n * over the window the request ran in — at most a second of it.\n */\n read(): HostState | null;\n /** Stops sampling. The timer is unrefed, so this is for tests and shutdown. */\n stop(): void;\n}\n\n/**\n * How often the histogram is emptied.\n *\n * A window shorter than this stops being a distribution; a longer one stops\n * being about the request that reads it. A second is the compromise, and it\n * is why the panel never draws one request against these numbers: a 90 ms\n * request does not resolve against a one-second window.\n */\nconst WINDOW_MS = 1_000;\n\n/**\n * How often the histogram is actually asked, however often it is read.\n *\n * `mean` walks the histogram's buckets on every call and costs about eleven\n * microseconds — trivial once, and eleven milliseconds a second at a thousand\n * requests. The window it summarises is a second long, so a reading fifty\n * milliseconds old is the same reading; what a memo buys is that the cost\n * stops scaling with traffic.\n */\nconst READ_EVERY_MS = 50;\n\n/**\n * How finely libuv samples the loop.\n *\n * Ten milliseconds is the interval the histogram itself schedules at — fine\n * enough to catch a blocking parse, coarse enough that the monitor is not\n * itself the thing keeping the loop busy.\n */\nconst RESOLUTION_MS = 10;\n\n/**\n * A histogram reading, in milliseconds of *delay*.\n *\n * libuv records the whole interval between samples, so an idle loop at a\n * resolution of ten reads about eleven. Reporting that as \"the loop was\n * behind by 11 ms\" would put a number on every request that is wrong on all\n * of them — the baseline comes off, and what is left is the lateness.\n */\nconst delayMs = (nanoseconds: number): number =>\n Number.isFinite(nanoseconds) ? Math.max(0, nanoseconds / 1e6 - RESOLUTION_MS) : 0;\n\n/**\n * Starts watching the event loop.\n *\n * Never throws: on a runtime without the histogram the monitor reads `null`\n * for ever and every screen that shows loop delay simply has nothing to show,\n * which is what an unmeasured thing looks like.\n */\nexport function startHostMonitor(): HostMonitor {\n let histogram: ReturnType<typeof monitorEventLoopDelay> | null = null;\n try {\n histogram = monitorEventLoopDelay({ resolution: RESOLUTION_MS });\n histogram.enable();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n warnOnce('host.monitor', `event-loop delay is not being measured: ${reason}`);\n return { read: () => null, stop: () => {} };\n }\n\n // The window just closed, kept so that a reset cannot swallow what it\n // measured. Without it, a request that blocked the loop and finished a\n // moment after a reset reports nothing at all — which is exactly the\n // request the number exists for.\n let previous: HostState | null = null;\n let cached: HostState | null = null;\n let cachedAt = 0;\n\n // Emptied on a timer rather than on every read: a reset per request would\n // mean each request reports the delay since the previous one finished,\n // which under load is a window of microseconds and a number of zero.\n const timer = setInterval(() => {\n try {\n if (histogram && histogram.count > 0) {\n previous = { loopDelayMs: delayMs(histogram.mean), loopMaxMs: delayMs(histogram.max) };\n }\n histogram?.reset();\n cached = null;\n } catch {\n // A histogram that will not reset still reads; it just widens.\n }\n }, WINDOW_MS);\n // The monitor must never be the reason a process stays alive.\n timer.unref?.();\n\n return {\n read() {\n if (!histogram) return null;\n const now = Date.now();\n if (cached && now - cachedAt < READ_EVERY_MS) return cached;\n try {\n // The window in progress and the one before it, together: the worst\n // the loop was behind over the last second or two, which is the span\n // a request is honestly placed against. An empty window is not a\n // delay of zero — it is no measurement — so the closed window carries\n // the answer alone until the new one has something to say.\n const open =\n histogram.count > 0\n ? { loopDelayMs: delayMs(histogram.mean), loopMaxMs: delayMs(histogram.max) }\n : null;\n const closed = previous;\n if (!open && !closed) return null;\n\n cached = {\n loopDelayMs: open?.loopDelayMs ?? closed?.loopDelayMs ?? 0,\n loopMaxMs: Math.max(open?.loopMaxMs ?? 0, closed?.loopMaxMs ?? 0),\n };\n cachedAt = now;\n return cached;\n } catch {\n return null;\n }\n },\n\n stop() {\n clearInterval(timer);\n cached = null;\n previous = null;\n try {\n histogram?.disable();\n } catch {\n // Already gone.\n }\n histogram = null;\n },\n };\n}\n","/**\n * Request identifiers.\n *\n * Generated on the hot path for every request, hence a counter and string\n * concatenation instead of `crypto.randomUUID()`. The id has to be unique\n * across every process whose requests share a store, and short — the panel\n * displays it.\n */\n\nimport { randomBytes } from 'node:crypto';\n\nlet counter = 0;\n\n/**\n * Random per-process prefix: keeps ids apart across workers and restarts.\n *\n * Forty bits, drawn once. Twenty were not enough: a history on disk collects\n * a prefix per process start, and a few hundred restarts made a repeat likely\n * — after which the store dropped the newer request and opened the older one\n * in its place. Eight characters, so an id stays within the twelve the\n * terminal client gives it for the first million and a half requests.\n */\nconst prefix = randomBytes(5).readUIntBE(0, 5).toString(36).padStart(8, '0');\n\nexport function nextRequestId(): string {\n counter = (counter + 1) % 0xffffffff;\n return `${prefix}${counter.toString(36)}`;\n}\n","/**\n * The sampling profiler: which function burned the time.\n *\n * `slow_code` can find the stretch of a request nothing accounts for and say\n * what brackets it. It cannot say what ran inside, because nothing was\n * recorded there — that is what makes it a stretch. The answer to \"which line\n * is slow\" needs samples of the stack, and V8 has had them all along.\n *\n * Off unless asked for. Sampling costs a few microseconds per request, which\n * is nothing; what it is not is free of consequence, because a profile names\n * the application's functions and files. That is a decision somebody makes,\n * not a default somebody discovers.\n *\n * ## How a sample becomes a line of code\n *\n * V8 reports a leaf frame, which for `pbkdf2Sync` or `JSON.parse` is C++ and\n * has no line at all. The caller chain is walked to the first frame inside\n * the project — the same rule `callsite.ts` applies to stack traces, and for\n * the same reason: a file in `node_modules` is not somewhere anybody can go\n * and change something.\n *\n * ## What a sample cannot tell you\n *\n * Two limits, both V8's rather than ours, and both worth knowing before\n * reading a number off this screen.\n *\n * A node carries the line a function is *defined* on, never the line running:\n * Node's profile omits the per-line tick counts the protocol allows for. So\n * the address is a function, and what recovers the rest is naming the call\n * inside it — `pbkdf2Sync`, `processChunkSync` — which is what `inside` is\n * for.\n *\n * And an optimised function that has been inlined into its caller is not on\n * the stack at all: its samples are attributed to the caller. A small helper\n * called in a loop can therefore be reported as the function that calls it.\n * This is why the answer is a share of samples rather than a measurement of a\n * function, and why the hint says where to look rather than what to delete.\n *\n * ## What the clock does\n *\n * Sample times are microseconds on V8's own clock. They are anchored to\n * `performance.now()` at the moment sampling starts, which measures true to\n * within a few milliseconds: against windows of known busy and idle work,\n * 96.8% of samples inside a busy window read as busy and none of those inside\n * an idle one do. Every drain re-anchors, so the error cannot accumulate.\n */\n\nimport { Session } from 'node:inspector';\nimport { relative as pathRelative } from 'node:path';\nimport { performance } from 'node:perf_hooks';\nimport { fileURLToPath } from 'node:url';\nimport { isProjectFrame } from './callsite.js';\nimport type { ResolvedStackOptions } from './config.js';\nimport { warnOnce } from './logger.js';\n\n/** One place in the code, with how much of the window it held. */\nexport interface HotFrame {\n /** The function's name, or `(anonymous)`. */\n readonly functionName: string;\n /** Path relative to the project root. */\n readonly relative: string;\n readonly line: number;\n /**\n * What the frame was calling when the sample was taken, or `null`.\n *\n * V8 gives a function's definition line, never the line executing, so the\n * address stops at the function. The callee is what recovers the rest of\n * the answer: `registerUser` is where to look, and `pbkdf2Sync` is what to\n * look for once there.\n */\n readonly inside: string | null;\n readonly samples: number;\n /** Share of the window's busy samples, 0..1. */\n readonly share: number;\n}\n\n/** What a stretch of a request was doing. */\nexport interface HotSpots {\n /** The project's own frames, heaviest first. */\n readonly frames: readonly HotFrame[];\n /**\n * Share of the window's samples that were on a processor, 0..1.\n *\n * The distinction `slow_code` cannot make on its own: near one, the stretch\n * is code running; near zero, it is the process waiting on something — I/O\n * with no instrumentation behind it, or a timer.\n */\n readonly busyShare: number;\n /** Samples in the window, busy and idle together. */\n readonly samples: number;\n}\n\n/** A frame the profiler has resolved, kept once and referred to by index. */\ninterface KnownFrame {\n readonly functionName: string;\n readonly relative: string;\n readonly line: number;\n}\n\n/** A sample, as the ring keeps it. */\ninterface Sample {\n /** `performance.now()` when V8 took it. */\n readonly at: number;\n /** Index into the frame table, or `-1` for a sample that was not running. */\n readonly frame: number;\n /**\n * Index into the callee table, or `-1`.\n *\n * Kept beside the frame rather than folded into it: a function calling\n * three different things is one hot spot, not three, and keying the frame\n * by its callee would split the share that says how hot it is.\n */\n readonly callee: number;\n}\n\n/**\n * How many samples are kept.\n *\n * Twenty seconds at a millisecond apart. A request is attributed the moment\n * it finishes, so the ring only has to outlive the gap between a request\n * ending and its record being built — the rest is slack for a process that\n * went quiet.\n */\nconst MAX_SAMPLES = 20_000;\n\n/** V8's names for samples that are not running anybody's code. */\nconst NOT_RUNNING = new Set(['(idle)', '(program)', '(root)']);\n\n/** How many frames a hot-spot answer names. */\nconst TOP_FRAMES = 5;\n\n/**\n * Running samples a window needs before its frames are worth showing.\n *\n * Three samples of somebody else's code in an idle stretch is not a hot spot;\n * it is the sampler catching whatever else the process was doing. Below this\n * the window still reports how busy it was — that much is honest at any\n * count — but names nothing.\n */\nconst MIN_BUSY_SAMPLES = 10;\n\nexport interface ProfilerOptions {\n readonly stack: ResolvedStackOptions;\n /** Microseconds between samples. */\n readonly intervalUs: number;\n}\n\nexport interface RequestProfiler {\n /**\n * What ran between two moments of `performance.now()`.\n *\n * `null` when the window holds no samples at all, which is not the same as\n * an idle window and must not be shown as one.\n */\n read(from: number, to: number): HotSpots | null;\n stop(): void;\n}\n\ninterface V8CallFrame {\n functionName: string;\n url: string;\n lineNumber: number;\n}\n\ninterface V8Node {\n id: number;\n callFrame: V8CallFrame;\n children?: number[];\n}\n\ninterface V8Profile {\n nodes: V8Node[];\n startTime: number;\n endTime: number;\n samples?: number[];\n timeDeltas?: number[];\n}\n\n/**\n * Starts sampling.\n *\n * Returns `null` when the inspector is unavailable — a runtime built without\n * it, or a process where the session cannot be opened. A panel then simply\n * has no hot spots to show, which is what an unmeasured thing looks like.\n */\nexport function startProfiler(options: ProfilerOptions): RequestProfiler | null {\n let session: Session;\n try {\n session = new Session();\n session.connect();\n } catch (error) {\n warnOnce('profiler.connect', `the sampling profiler is not available: ${reasonOf(error)}`);\n return null;\n }\n\n /** Every inspector call answers synchronously, which is why a drain can happen inline. */\n const post = <T>(method: string, params?: object): T | null => {\n let result: T | null = null;\n session.post(method, params as never, (error: Error | null, value: unknown) => {\n if (!error) result = value as T;\n });\n return result;\n };\n\n const samples: Sample[] = [];\n const frames: KnownFrame[] = [];\n const frameIds = new Map<string, number>();\n const callees: string[] = [];\n const calleeIds = new Map<string, number>();\n\n /** Callee names are few and repeat constantly; the table keeps them once. */\n function internCallee(name: string): number {\n const known = calleeIds.get(name);\n if (known !== undefined) return known;\n const id = callees.length;\n callees.push(name);\n calleeIds.set(name, id);\n return id;\n }\n let anchor = 0;\n let drainedAt = 0;\n let running = false;\n\n /** The frame table is shared across drains: the same function recurs constantly. */\n function intern(functionName: string, file: string, line: number): number {\n const key = `${functionName} ${file} ${line}`;\n const known = frameIds.get(key);\n if (known !== undefined) return known;\n const id = frames.length;\n frames.push({\n functionName: functionName || '(anonymous)',\n relative: pathRelative(options.stack.projectRoot, file).replaceAll('\\\\', '/'),\n line,\n });\n frameIds.set(key, id);\n return id;\n }\n\n /**\n * The nearest frame in the project, walking outwards from the leaf.\n *\n * A leaf in C++ — `pbkdf2Sync`, `JSON.parse`, a regexp — has no line of its\n * own, and the caller is what somebody can actually go and change.\n */\n function resolve(\n nodeId: number,\n nodes: Map<number, V8Node>,\n parents: Map<number, number>,\n ): { frame: number; callee: number } {\n // What the project frame was calling, kept as the walk passes it. The\n // leaf itself is usually C++ with a name like `run`; the frame directly\n // under the project's own is the one worth naming.\n let callee: string | null = null;\n for (let id: number | undefined = nodeId; id !== undefined; id = parents.get(id)) {\n const frame = nodes.get(id)?.callFrame;\n if (!frame) continue;\n const file = frame.url ? fileOf(frame.url) : null;\n if (!file || !isProjectFrame(file, options.stack)) {\n if (frame.functionName) callee = frame.functionName;\n continue;\n }\n // V8 counts lines from zero; every other number a reader sees is\n // one-based, including the callsites beside this on the same screen.\n return {\n frame: intern(frame.functionName, file, frame.lineNumber + 1),\n callee: callee === null ? -1 : internCallee(callee),\n };\n }\n return { frame: -1, callee: -1 };\n }\n\n function start(): void {\n post('Profiler.start');\n anchor = performance.now();\n running = true;\n }\n\n /** Empties V8's buffer into the ring, and starts a fresh one. */\n function drain(): void {\n if (!running) return;\n const stopped = post<{ profile: V8Profile }>('Profiler.stop');\n const profile = stopped?.profile;\n const anchoredAt = anchor;\n start();\n drainedAt = performance.now();\n if (!profile?.samples || !profile.timeDeltas) return;\n\n const nodes = new Map(profile.nodes.map((node) => [node.id, node]));\n const parents = new Map<number, number>();\n for (const node of profile.nodes) {\n for (const child of node.children ?? []) parents.set(child, node.id);\n }\n\n let at = profile.startTime;\n for (let i = 0; i < profile.samples.length; i++) {\n at += profile.timeDeltas[i] ?? 0;\n const nodeId = profile.samples[i];\n if (nodeId === undefined) continue;\n const name = nodes.get(nodeId)?.callFrame?.functionName ?? '';\n const resolved = NOT_RUNNING.has(name)\n ? { frame: -1, callee: -1 }\n : resolve(nodeId, nodes, parents);\n samples.push({ at: anchoredAt + (at - profile.startTime) / 1000, ...resolved });\n }\n if (samples.length > MAX_SAMPLES) samples.splice(0, samples.length - MAX_SAMPLES);\n }\n\n try {\n post('Profiler.enable');\n post('Profiler.setSamplingInterval', { interval: options.intervalUs });\n start();\n } catch (error) {\n warnOnce('profiler.start', `the sampling profiler did not start: ${reasonOf(error)}`);\n return null;\n }\n\n return {\n read(from: number, to: number): HotSpots | null {\n try {\n // A window reaching past the last drain cannot be in the ring yet:\n // its samples are still in V8's buffer, and answering from what is in\n // hand would name whichever function happened to be sampled early.\n // A wrong line of code is worse than half a millisecond.\n //\n // This is also the whole rate limit. Requests finishing together are\n // attributed one after another, so the first read drains and the rest\n // find their windows already covered.\n if (to > drainedAt) drain();\n\n let total = 0;\n let busy = 0;\n const counts = new Map<number, number>();\n /** Per frame, how often each callee was under it. */\n const inside = new Map<number, Map<number, number>>();\n for (const sample of samples) {\n if (sample.at < from || sample.at > to) continue;\n total++;\n if (sample.frame < 0) continue;\n busy++;\n counts.set(sample.frame, (counts.get(sample.frame) ?? 0) + 1);\n if (sample.callee < 0) continue;\n const seen = inside.get(sample.frame) ?? new Map<number, number>();\n seen.set(sample.callee, (seen.get(sample.callee) ?? 0) + 1);\n inside.set(sample.frame, seen);\n }\n if (total === 0) return null;\n // Busy enough to name something, or the answer is only how busy it was.\n if (busy < MIN_BUSY_SAMPLES) return { frames: [], busyShare: busy / total, samples: total };\n\n const hot = [...counts]\n .sort((a, b) => b[1] - a[1])\n .slice(0, TOP_FRAMES)\n .map(([id, count]) => {\n const frame = frames[id] as KnownFrame;\n // The call it was mostly in — one name, not a list: the point is\n // what to look for in the function, not an inventory of it.\n const top = [...(inside.get(id) ?? [])].sort((a, b) => b[1] - a[1])[0];\n return {\n ...frame,\n inside: top ? (callees[top[0]] ?? null) : null,\n samples: count,\n share: count / busy,\n };\n });\n\n return { frames: hot, busyShare: busy / total, samples: total };\n } catch (error) {\n warnOnce('profiler.read', `the sampling profiler stopped reporting: ${reasonOf(error)}`);\n return null;\n }\n },\n\n stop() {\n try {\n if (running) post('Profiler.stop');\n running = false;\n session.disconnect();\n } catch {\n // A session that will not close is not worth an exception on shutdown.\n }\n samples.length = 0;\n frames.length = 0;\n frameIds.clear();\n callees.length = 0;\n calleeIds.clear();\n },\n };\n}\n\n/** A frame's `url` is a file URL, a bare path, or something that is neither. */\nfunction fileOf(url: string): string | null {\n if (url.startsWith('file://')) {\n try {\n return fileURLToPath(url);\n } catch {\n return null;\n }\n }\n return url.startsWith('node:') || url === '' ? null : url;\n}\n\nfunction reasonOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Request replay from the panel.\n *\n * The request is replayed through the same application — with its full\n * middleware stack — so this is a real run, not a simulation. Hence the\n * restriction: a replay in production means a second card charge and a second\n * email, so outside development it is enabled only by an explicit flag.\n *\n * A replayed request must not show up in the shared list: it is marked by a\n * header, and its record goes not to the transport but to whoever started the\n * replay.\n */\n\nimport type { ReplayComparison, ReplayInput, ReplayMetrics } from '@reqray/protocol';\nimport { runOutsideScope } from '../context.js';\nimport { awaitReplay } from '../replay-waiters.js';\nimport { REPLAY_HEADER } from '../reqray.js';\nimport type { RecordedRequest } from '../types.js';\n\nexport type { ReplayComparison, ReplayInput, ReplayMetrics };\n\nfunction numberOrNull(value: string | undefined): number | null {\n if (value === undefined) return null;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/** Reduces a request record to the comparison metrics. */\nexport function metricsOf(request: RecordedRequest): ReplayMetrics {\n let sqlCount = 0;\n for (const span of request.spans) {\n if (span.kind === 'db') sqlCount++;\n }\n\n return {\n status: request.status,\n durationMs: request.durationMs,\n sqlCount,\n nPlusOne: request.findings.some((finding) => finding.detector === 'n_plus_one'),\n bytes: numberOrNull(request.responseHeaders['content-length']),\n etag: request.responseHeaders['etag'] ?? null,\n };\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null> {\n return new Promise<T | null>((resolve) => {\n const timer = setTimeout(() => resolve(null), ms);\n timer.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n () => {\n clearTimeout(timer);\n resolve(null);\n },\n );\n });\n}\n\nlet counter = 0;\n\nfunction nextReplayId(): string {\n counter = (counter + 1) % 0xffffff;\n return `r${counter.toString(36)}${Math.random().toString(36).slice(2, 8)}`;\n}\n\n/**\n * Runs the request again and returns a comparison against the original.\n *\n * @param origin the application's own address, e.g. `http://127.0.0.1:3000`.\n * @param recordTimeoutMs how long to wait for the replay's record before\n * returning a partial comparison.\n */\nexport async function runReplay(\n origin: string,\n input: ReplayInput,\n original: RecordedRequest,\n recordTimeoutMs = 2_000,\n): Promise<ReplayComparison> {\n const replayId = nextReplayId();\n\n let stopWaiting = (): void => {};\n const recorded = new Promise<RecordedRequest>((resolve) => {\n stopWaiting = awaitReplay(replayId, resolve);\n });\n\n const startedAt = performance.now();\n try {\n // Outside the scope: Reqray's own HTTP call must not become a span of the\n // request that opened the panel.\n const response = await runOutsideScope(() =>\n fetch(`${origin}${input.path}`, {\n method: input.method,\n headers: { ...input.headers, [REPLAY_HEADER]: replayId },\n ...(input.body === undefined ? {} : { body: input.body }),\n }),\n );\n\n const text = await response.text();\n const durationMs = performance.now() - startedAt;\n const record = await withTimeout(recorded, recordTimeoutMs);\n\n const replay: ReplayMetrics = record\n ? metricsOf(record)\n : {\n status: response.status,\n durationMs,\n sqlCount: 0,\n nPlusOne: false,\n bytes: Buffer.byteLength(text),\n etag: response.headers.get('etag'),\n };\n\n return { original: metricsOf(original), replay, partial: record === null };\n } finally {\n stopWaiting();\n }\n}\n","/**\n * Three charts for one endpoint, and nothing beyond them.\n *\n * Latency over time, the share that failed, and how often it was called —\n * enough to see \"it got slower at 14:20, after the deploy\" and to stop there.\n * Not a dashboard builder, not alerting, not aggregates over arbitrary\n * dimensions: that is the line where this becomes a worse Datadog, and it is\n * written down in the plan so that nobody crosses it by inertia.\n *\n * The bucketing is the strip's own, so a chart and the strip above it cannot\n * disagree about when something happened.\n */\n\nimport type { RouteSeries, SeriesBucket } from '@reqray/protocol';\nimport type { DurationSample } from './api.js';\nimport { percentile } from './routes.js';\nimport { bucketIndex } from './timeline.js';\n\nexport type { RouteSeries, SeriesBucket };\n\n/** Columns a route's charts are drawn with, unless asked otherwise. */\nexport const SERIES_BUCKETS = 48;\n\n/**\n * Calls a column should hold before it is worth drawing as one.\n *\n * A percentile over three samples is the slowest of three, which is why a\n * chart drawn at full resolution over a quiet route shows a p95 and a p99\n * that are the same number and jump about together. Fewer, fuller columns say\n * less about *when* and much more about *what*, and the resolution should\n * follow how much there is to draw rather than the width of the box.\n */\nconst MIN_PER_COLUMN = 6;\n\n/** Below this the chart stops being a shape and becomes a bar. */\nconst MIN_BUCKETS = 12;\n\n/**\n * Buckets one route's calls.\n *\n * `null` when the store holds nothing for it: a chart with invented ends\n * would be a claim about a stretch of time nobody recorded.\n */\nexport function routeSeries(\n method: string,\n route: string,\n samples: readonly DurationSample[],\n bucketCount: number = SERIES_BUCKETS,\n): RouteSeries | null {\n if (samples.length === 0 || bucketCount <= 0) return null;\n\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n for (const sample of samples) {\n if (sample.startedAt < from) from = sample.startedAt;\n if (sample.startedAt > to) to = sample.startedAt;\n }\n\n // As many columns as the traffic supports, and never more than asked for.\n const count = Math.max(\n Math.min(MIN_BUCKETS, bucketCount),\n Math.min(bucketCount, Math.ceil(samples.length / MIN_PER_COLUMN)),\n );\n\n const columns: Array<{ durations: number[]; errors: number }> = Array.from(\n { length: count },\n () => ({ durations: [], errors: 0 }),\n );\n\n for (const sample of samples) {\n const column = columns[bucketIndex(sample.startedAt, from, to, count)];\n if (!column) continue;\n column.durations.push(sample.durationMs);\n if (sample.hasError) column.errors++;\n }\n\n // A single call spans no time; a second keeps throughput finite and honest.\n const span = Math.max(1_000, to - from);\n const bucketMs = span / count;\n\n return {\n method,\n route,\n from,\n to,\n bucketMs,\n calls: samples.length,\n buckets: columns.map((column, index) => {\n const sorted = column.durations.sort((a, b) => a - b);\n return {\n at: from + index * bucketMs,\n calls: sorted.length,\n errors: column.errors,\n p50: sorted.length > 0 ? percentile(sorted, 0.5) : 0,\n p95: sorted.length > 0 ? percentile(sorted, 0.95) : 0,\n p99: sorted.length > 0 ? percentile(sorted, 0.99) : 0,\n };\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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;AAAA,MACF;AACA,YAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACpE,eAAS,iBAAiB,mBAAmB,MAAM,EAAE;AACrD,eAAS,UAAU,KAAK,EAAE,OAAO,mBAAmB,MAAM,GAAG,CAAC;AAAA,IAChE;AAAA,EACF,GAAG;AACL;AAEA,SAAS,aACP,QACA,SACA,UACM;AACN,QAAM,YAAY;AAChB,QAAI;AACF,YAAM,UAAW,MAAM,SAAS,OAAO;AAQvC,YAAM,WAAW,OAAO,QAAQ,OAAO,WAAW,OAAO,IAAI,QAAQ,EAAE,IAAI;AAC3E,UAAI,CAAC,UAAU;AACb,iBAAS,UAAU,KAAK,EAAE,OAAO,6BAA6B,CAAC;AAC/D;AAAA,MACF;AAEA,YAAM,QAAqB;AAAA,QACzB,QAAQ,OAAO,QAAQ,WAAW,WAAW,QAAQ,SAAS,SAAS;AAAA,QACvE,MAAM,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO,SAAS;AAAA,QACjE,SACE,QAAQ,WAAW,OAAO,QAAQ,YAAY,WACzC,QAAQ,UACT,CAAC;AAAA,QACP,MAAM,OAAO,QAAQ,SAAS,WAAW,QAAQ,OAAO;AAAA,MAC1D;AAEA,eAAS,UAAU,KAAK,MAAM,UAAUH,UAAS,OAAO,GAAG,OAAO,QAAQ,CAAC;AAAA,IAC7E,SAAS,OAAO;AACd,YAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACpE,eAAS,gBAAgB,kBAAkB,MAAM,EAAE;AACnD,eAAS,UAAU,KAAK,EAAE,OAAO,kBAAkB,MAAM,GAAG,CAAC;AAAA,IAC/D;AAAA,EACF,GAAG;AACL;","names":["import_node_fs","import_node_path","cached","cache","cached","current","run","SEVERITY_WARN_MS","run","current","SEVERITY_CRITICAL_MS","severityFor","HINT","CACHE_LIMIT","fingerprints","cached","SEVERITY_CRITICAL_MS","SEVERITY_WARN_MS","severityFor","evaluate","run","ms","hintFor","endOf","SEVERITY_CRITICAL_MS","cache","CACHE_LIMIT","resolve","cached","import_node_path","CACHE_LIMIT","pathRelative","group","resolve","bucketize","current","MIN_RATIO","import_node_child_process","import_node_path","sequence","resolve","import_node_path","import_node_perf_hooks","import_node_crypto","import_node_path","import_node_perf_hooks","import_node_url","withTimeout","resolve","MIN_PER_COLUMN","size","originOf","report","page","current"]}
|