@warlock.js/devtools 5.27.0 → 5.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/cjs/index.cjs +26 -2
- package/cjs/index.cjs.map +1 -1
- package/cjs/{server-CwK7n3-3.cjs → server-6mVWfWkG.cjs} +27 -5
- package/cjs/server-6mVWfWkG.cjs.map +1 -0
- package/esm/devtools-connector.mjs +25 -1
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/server/openapi-routes.mjs +12 -2
- package/esm/server/openapi-routes.mjs.map +1 -1
- package/esm/server/ui-assets.mjs +14 -2
- package/esm/server/ui-assets.mjs.map +1 -1
- package/llms-full.txt +5 -3
- package/llms.txt +1 -1
- package/package.json +5 -5
- package/skills/devtools-overview/SKILL.md +5 -3
- package/ui/app.css +7 -1
- package/ui/app.js +65 -1
- package/ui/docs-swagger.html +15 -0
- package/ui/docs-swagger.js +10 -0
- package/ui/vendor/swagger-ui/LICENSE +202 -0
- package/ui/vendor/swagger-ui/NOTICE +2 -0
- package/ui/vendor/swagger-ui/README.md +28 -0
- package/ui/vendor/swagger-ui/swagger-ui-bundle.js +2 -0
- package/ui/vendor/swagger-ui/swagger-ui-bundle.js.LICENSE.txt +129 -0
- package/ui/vendor/swagger-ui/swagger-ui.css +3 -0
- package/cjs/server-CwK7n3-3.cjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,20 @@ All notable changes to `@warlock.js/devtools` are documented in this file.
|
|
|
4
4
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `@warlock.js/*` packages are released in lockstep — every package shares the same version number, so a version below may list only the changes that affected this package.
|
|
6
6
|
|
|
7
|
+
## 5.29.0 - 2026-10-01
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- Lockstep release; package APIs are unchanged.
|
|
12
|
+
|
|
13
|
+
## 5.28.0 - 2026-10-01
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **Swagger UI.** `/__warlock/docs/swagger` renders the same OpenAPI document with [Swagger UI](https://github.com/swagger-api/swagger-ui) (Apache-2.0), and the dashboard's **API** tab has a **Scalar | Swagger UI** switch (Scalar stays the default; the choice is remembered in the browser). The prebuilt `swagger-ui-dist` 5.33.0 bundle and stylesheet are vendored in `ui/vendor/swagger-ui/` with their license and notice and served as `assets/swagger-ui-bundle.js` and `assets/swagger-ui.css`, so apps install no extra dependencies. The schema validator badge is off, so the page makes no outside request.
|
|
18
|
+
- **Downloads in the API tab.** `OpenAPI JSON` (`/__warlock/api/openapi.json`) and `Postman collection` links.
|
|
19
|
+
- **`GET /__warlock/api/postman.json`** returns the Postman collection for the registered routes, built by core's `getDevelopmentPostmanCollection()`. It answers 503 when the host's core cannot build one, with the same dev-only, loopback-only guard.
|
|
20
|
+
|
|
7
21
|
## 5.27.0 - 2026-10-01
|
|
8
22
|
|
|
9
23
|
### Added
|
package/cjs/index.cjs
CHANGED
|
@@ -633,14 +633,16 @@ function devtoolsConnector(options = {}) {
|
|
|
633
633
|
await attachSource(log, "cache", () => attachCacheSource(collector));
|
|
634
634
|
await attachSource(log, "mail", () => attachMailSource(collector));
|
|
635
635
|
await attachSource(log, "log", () => attachLogSource(collector));
|
|
636
|
-
const { mountDevtoolsRoutes } = await Promise.resolve().then(() => require("./server-
|
|
636
|
+
const { mountDevtoolsRoutes } = await Promise.resolve().then(() => require("./server-6mVWfWkG.cjs"));
|
|
637
|
+
const postmanBuilder = await findPostmanBuilder();
|
|
637
638
|
mountDevtoolsRoutes(getHttpServer(), {
|
|
638
639
|
collector,
|
|
639
640
|
options: resolved,
|
|
640
641
|
isDevelopment: () => Application.runtimeStrategy === "development",
|
|
641
642
|
explain: (query) => explainQuery(query),
|
|
642
643
|
listRoutes: () => listRoutes(),
|
|
643
|
-
getOpenApiDocument: () => getOpenApiDocument()
|
|
644
|
+
getOpenApiDocument: () => getOpenApiDocument(),
|
|
645
|
+
getPostmanCollection: postmanBuilder ? async () => unwrapCollection(await postmanBuilder()) : void 0
|
|
644
646
|
});
|
|
645
647
|
disposers.push(collector.subscribe((event) => {
|
|
646
648
|
if (event.type !== "request" || event.data.warningCount === 0) return;
|
|
@@ -699,6 +701,28 @@ async function getOpenApiDocument() {
|
|
|
699
701
|
const { document } = await getDevelopmentOpenApiDocument();
|
|
700
702
|
return document;
|
|
701
703
|
}
|
|
704
|
+
/**
|
|
705
|
+
* Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.
|
|
706
|
+
* Older cores do not export it; the route then answers 503. The lookup is
|
|
707
|
+
* guarded because a namespace without the export may throw on access. Core is
|
|
708
|
+
* imported lazily, like the OpenAPI document above.
|
|
709
|
+
*/
|
|
710
|
+
async function findPostmanBuilder() {
|
|
711
|
+
try {
|
|
712
|
+
const build = (await import("@warlock.js/core")).getDevelopmentPostmanCollection;
|
|
713
|
+
return typeof build === "function" ? build : void 0;
|
|
714
|
+
} catch {
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Core may return the collection itself or wrap it in `{ collection, warnings }`,
|
|
720
|
+
* like the OpenAPI generator's `{ document, warnings }`.
|
|
721
|
+
*/
|
|
722
|
+
function unwrapCollection(result) {
|
|
723
|
+
if (result && typeof result === "object" && "collection" in result) return result.collection;
|
|
724
|
+
return result;
|
|
725
|
+
}
|
|
702
726
|
|
|
703
727
|
//#endregion
|
|
704
728
|
exports.devtoolsConnector = devtoolsConnector;
|
package/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["requestContext","LogChannel","log"],"sources":["../../../../../../devtools/src/n-plus-one.ts","../../../../../../devtools/src/query-shape.ts","../../../../../../devtools/src/collector.ts","../../../../../../devtools/src/options.ts","../../../../../../devtools/src/current-request-id.ts","../../../../../../devtools/src/sources/cache-source.ts","../../../../../../devtools/src/safe-value.ts","../../../../../../devtools/src/sources/log-source.ts","../../../../../../devtools/src/sources/mail-source.ts","../../../../../../devtools/src/caller-location.ts","../../../../../../devtools/src/sources/query-source.ts","../../../../../../devtools/src/sources/tracing-source.ts","../../../../../../devtools/src/devtools-connector.ts"],"sourcesContent":["import type { DevtoolsCallerLocation, DevtoolsQuery, DevtoolsWarning } from \"./types\";\n\n/** Finds repeated query shapes whose occurrence count reaches the supplied threshold. */\nexport function detectNPlusOne(queries: DevtoolsQuery[], threshold: number): DevtoolsWarning[] {\n const groups = new Map<string, DevtoolsQuery[]>();\n for (const query of queries) groups.set(query.shape, [...(groups.get(query.shape) ?? []), query]);\n\n return [...groups.entries()]\n .filter(([, grouped]) => grouped.length >= threshold)\n .sort(([, left], [, right]) => right.length - left.length)\n .map(([shape, grouped]) => ({\n type: \"n+1\" as const,\n shape,\n count: grouped.length,\n message: `N+1: ${grouped.length}× \"${truncate(shape, 120)}\"`,\n ...(mostFrequentCaller(grouped) ? { caller: mostFrequentCaller(grouped) } : {}),\n }));\n}\n\nfunction truncate(value: string, maximum: number): string {\n return value.length > maximum ? `${value.slice(0, maximum - 1)}…` : value;\n}\n\nfunction mostFrequentCaller(queries: DevtoolsQuery[]): DevtoolsCallerLocation | undefined {\n const callers = new Map<string, { caller: DevtoolsCallerLocation; count: number }>();\n for (const query of queries) {\n if (!query.caller) continue;\n const key = `${query.caller.file}:${query.caller.line}`;\n const found = callers.get(key);\n callers.set(\n key,\n found ? { ...found, count: found.count + 1 } : { caller: query.caller, count: 1 },\n );\n }\n return [...callers.values()].sort((left, right) => right.count - left.count)[0]?.caller;\n}\n","import type { DevtoolsQuery } from \"./types\";\n\ntype QueryShapeInput = Pick<\n DevtoolsQuery,\n \"driver\" | \"sql\" | \"collection\" | \"command\" | \"pipeline\"\n>;\n\nconst numericLiteral = /(?<![\\w$])[-+]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?![\\w$])/g;\nconst quotedLiteral = /'(?:''|[^'])*'/g;\n\n/** Returns a binding-independent shape for a database query. */\nexport function queryShape(query: QueryShapeInput): string {\n if (query.driver === \"postgres\") {\n return (query.sql ?? \"\")\n .replace(quotedLiteral, \"?\")\n .replace(numericLiteral, \"?\")\n .replace(/\\s+/g, \" \")\n .trim();\n }\n\n return `${query.collection ?? \"\"}.${query.command ?? \"\"} ${JSON.stringify(normalizeMongoValue(query.pipeline))}`;\n}\n\nfunction normalizeMongoValue(value: unknown): unknown {\n if (isMongoLeaf(value)) return \"?\";\n\n if (Array.isArray(value)) {\n if (value.every(isMongoLeaf)) return [\"?\"];\n return value.map(normalizeMongoValue);\n }\n\n const record = value as Record<string, unknown>;\n return Object.fromEntries(\n Object.keys(record).map((key) => [key, normalizeMongoValue(record[key])]),\n );\n}\n\nfunction isMongoLeaf(value: unknown): boolean {\n if (value === null || typeof value !== \"object\") return true;\n if (value instanceof Date) return true;\n const record = value as Record<string, unknown>;\n return typeof record.toHexString === \"function\" || typeof record.$oid === \"string\";\n}\n","import type {\n DevtoolsBackground,\n DevtoolsCacheOperation,\n DevtoolsCollector,\n DevtoolsDisposer,\n DevtoolsLogEntry,\n DevtoolsMail,\n DevtoolsMailSummary,\n DevtoolsPhase,\n DevtoolsQuery,\n DevtoolsRequest,\n DevtoolsRequestSummary,\n DevtoolsStreamEvent,\n ResolvedDevtoolsOptions,\n} from \"./types\";\nimport { detectNPlusOne } from \"./n-plus-one\";\nimport { queryShape } from \"./query-shape\";\n\nconst mailLimit = 100;\nconst logLimit = 1000;\nconst backgroundLimit = 500;\n\n/**\n * Creates the in-memory devtools store.\n *\n * Read methods return shallow structural copies, including copied arrays, so consumers\n * cannot mutate collector-owned arrays. The individual nested entries are retained.\n */\nexport function createCollector(options: ResolvedDevtoolsOptions): DevtoolsCollector {\n const requests = new Map<string, DevtoolsRequest>();\n const mails = new Map<string, DevtoolsMail>();\n const logs: DevtoolsLogEntry[] = [];\n const background: DevtoolsBackground = { queries: [], cache: [], logs: [] };\n const listeners = new Set<(event: DevtoolsStreamEvent) => void>();\n let querySequence = 0;\n\n const emit = (event: DevtoolsStreamEvent) => {\n for (const listener of listeners) {\n try {\n listener(event);\n } catch {\n /* Subscribers must not affect collection. */\n }\n }\n };\n\n const addBackground = <T>(list: T[], value: T) => {\n list.push(value);\n if (list.length > backgroundLimit) list.shift();\n };\n\n return {\n startRequest(request) {\n requests.delete(request.id);\n requests.set(request.id, {\n ...request,\n phases: [],\n queries: [],\n cache: [],\n logs: [],\n mails: [],\n warnings: [],\n });\n while (requests.size > options.maxRequests)\n requests.delete(requests.keys().next().value as string);\n },\n endRequest(id, result) {\n const request = requests.get(id);\n if (!request) return;\n request.status = result.status;\n request.durationMs = result.durationMs;\n request.error = result.error;\n if (result.route !== undefined) request.route = result.route;\n request.warnings = detectNPlusOne(request.queries, options.nPlusOneThreshold);\n emit({ type: \"request\", data: summary(request) });\n },\n addPhase(requestId, phase) {\n requests.get(requestId)?.phases.push(phase);\n },\n addQuery(requestId, query) {\n const stored: DevtoolsQuery = {\n ...query,\n id: `q${++querySequence}`,\n shape: queryShape(query),\n };\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.queries.push(stored);\n else addBackground(background.queries, stored);\n return stored;\n },\n addCacheOperation(requestId, operation) {\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.cache.push(operation);\n else addBackground(background.cache, operation);\n },\n addLog(requestId, entry) {\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.logs.push(entry);\n else addBackground(background.logs, entry);\n logs.unshift(entry);\n if (logs.length > logLimit) logs.pop();\n emit({ type: \"log\", data: entry });\n },\n addMail(mail) {\n mails.delete(mail.id);\n mails.set(mail.id, mail);\n while (mails.size > mailLimit) mails.delete(mails.keys().next().value as string);\n if (mail.requestId) requests.get(mail.requestId)?.mails.push(mail.id);\n emit({ type: \"mail\", data: mailSummary(mail) });\n },\n listRequests() {\n return [...requests.values()].reverse().map(summary);\n },\n getRequest(id) {\n const request = requests.get(id);\n return request && copyRequest(request);\n },\n listMails() {\n return [...mails.values()].reverse().map(mailSummary);\n },\n getMail(id) {\n const mail = mails.get(id);\n return (\n mail && {\n ...mail,\n to: [...mail.to],\n cc: [...mail.cc],\n bcc: [...mail.bcc],\n headers: { ...mail.headers },\n attachments: [...mail.attachments],\n }\n );\n },\n listLogs(filter = {}) {\n const module = filter.module?.toLowerCase();\n return logs\n .filter(\n (entry) =>\n (!filter.level || entry.level === filter.level) &&\n (!module || entry.module.toLowerCase().includes(module)),\n )\n .map((entry) => ({ ...entry }));\n },\n getBackground() {\n return {\n queries: [...background.queries],\n cache: [...background.cache],\n logs: [...background.logs],\n };\n },\n subscribe(listener): DevtoolsDisposer {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n clear() {\n requests.clear();\n mails.clear();\n logs.length = 0;\n background.queries.length = 0;\n background.cache.length = 0;\n background.logs.length = 0;\n },\n };\n}\n\nfunction summary(request: DevtoolsRequest): DevtoolsRequestSummary {\n const { id, method, path, route, status, startedAt, durationMs } = request;\n return {\n id,\n method,\n path,\n route,\n status,\n startedAt,\n durationMs,\n queryCount: request.queries.length,\n warningCount: request.warnings.length,\n };\n}\n\nfunction mailSummary(mail: DevtoolsMail): DevtoolsMailSummary {\n const { id, requestId, capturedAt, to, subject } = mail;\n return { id, requestId, capturedAt, to: [...to], subject };\n}\n\nfunction copyRequest(request: DevtoolsRequest): DevtoolsRequest {\n return {\n ...request,\n phases: [...request.phases],\n queries: [...request.queries],\n cache: [...request.cache],\n logs: [...request.logs],\n mails: [...request.mails],\n warnings: [...request.warnings],\n };\n}\n","import type { DevtoolsOptions, ResolvedDevtoolsOptions } from \"./types\";\n\n/** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */\nexport function resolveDevtoolsOptions(options: DevtoolsOptions = {}): ResolvedDevtoolsOptions {\n const path = (options.path ?? \"/__warlock\").replace(/\\/+$/, \"\");\n const maxRequests = options.maxRequests ?? 200;\n const nPlusOneThreshold = options.nPlusOneThreshold ?? 5;\n\n if (!path || !path.startsWith(\"/\")) {\n throw new Error('Devtools option \"path\" must be a non-root path starting with \"/\".');\n }\n\n if (maxRequests < 1) {\n throw new Error('Devtools option \"maxRequests\" must be at least 1.');\n }\n\n if (nPlusOneThreshold < 2) {\n throw new Error('Devtools option \"nPlusOneThreshold\" must be at least 2.');\n }\n\n return { path, maxRequests, nPlusOneThreshold };\n}\n","import { requestContext } from \"@warlock.js/core\";\n\n/**\n * The current request's id (core's `request.id`, threaded through\n * `AsyncLocalStorage`), or `undefined` outside a request — sources feed\n * devtools' background bucket in that case.\n *\n * Only ever reached through `./sources/*`, which the connector imports\n * dynamically inside `boot()` — by then core is already running, so this\n * static import never drags core's runtime graph into config-load time (see\n * `devtools-connector.ts`).\n */\nexport function currentRequestId(): string | undefined {\n try {\n return requestContext.getRequest()?.id;\n } catch {\n return undefined;\n }\n}\n","import { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCacheOperation, DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** Cache events the dashboard's waterfall and background bucket care about. */\nconst EVENT_TYPES = [\"hit\", \"miss\", \"set\", \"removed\", \"invalidated\", \"flushed\"] as const;\n\n/** The shape `cache.on(event, handler)` hands the handler. */\ntype CacheEventData = {\n key?: string;\n driver: string;\n tags?: string[];\n keys?: string[];\n durationMs?: number;\n};\n\n/**\n * Feeds cache hits, misses and mutations, from `@warlock.js/cache`, into the\n * collector. A no-op when `@warlock.js/cache` isn't installed — it is an\n * optional peer.\n */\nexport async function attachCacheSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let cache: {\n on(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n off(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n };\n\n try {\n ({ cache } = await import(\"@warlock.js/cache\"));\n } catch {\n return () => {};\n }\n\n const handlers = EVENT_TYPES.map((type) => {\n const handler = (data: CacheEventData) => {\n const operation: DevtoolsCacheOperation = {\n type,\n driver: data.driver,\n key: data.key,\n tags: data.tags,\n keys: data.keys,\n at: Date.now(),\n durationMs: data.durationMs,\n };\n\n collector.addCacheOperation(currentRequestId(), operation);\n };\n\n cache.on(type, handler);\n\n return { type, handler };\n });\n\n return () => {\n for (const { type, handler } of handlers) cache.off(type, handler);\n };\n}\n","const MAX_DEPTH = 6;\n\n/**\n * A JSON-safe snapshot of a value devtools keeps for later display.\n *\n * Log contexts and phase attributes are app data: they can hold live objects\n * (a request, its socket) whose graphs are circular and which must not be kept\n * alive by the collector anyway. Plain objects and arrays are copied; anything\n * with a `toJSON()` is serialized through it; other class instances collapse\n * to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to\n * `[Object]` / `[Array]`.\n */\nexport function toSafeValue(value: unknown): unknown {\n return snapshot(value, 0, new WeakSet());\n}\n\nfunction snapshot(value: unknown, depth: number, seen: WeakSet<object>): unknown {\n if (value === null || value === undefined) return value;\n\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"symbol\":\n return value.toString();\n case \"function\":\n return undefined;\n }\n\n const object = value as object;\n\n if (seen.has(object)) return \"[Circular]\";\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n if (value instanceof Error) return { name: value.name, message: value.message };\n\n if (depth >= MAX_DEPTH) return Array.isArray(value) ? \"[Array]\" : \"[Object]\";\n\n seen.add(object);\n\n try {\n if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));\n\n const prototype = Object.getPrototypeOf(object);\n\n if (prototype !== Object.prototype && prototype !== null) {\n const toJSON = (object as { toJSON?: unknown }).toJSON;\n\n if (typeof toJSON === \"function\") {\n try {\n return snapshot(toJSON.call(object), depth + 1, seen);\n } catch {\n return `[${constructorName(object)}]`;\n }\n }\n\n return `[${constructorName(object)}]`;\n }\n\n const copy: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(object)) {\n const safe = snapshot(entry, depth + 1, seen);\n if (safe !== undefined) copy[key] = safe;\n }\n\n return copy;\n } finally {\n seen.delete(object);\n }\n}\n\nfunction constructorName(object: object): string {\n return (object as { constructor?: { name?: string } }).constructor?.name || \"Object\";\n}\n","import { LogChannel, log, type LoggingData } from \"@warlock.js/logger\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsLogEntry } from \"../types\";\n\n/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */\nfunction toDevtoolsLevel(type: LoggingData[\"type\"]): DevtoolsLogEntry[\"level\"] {\n return type === \"fatal\" ? \"error\" : type;\n}\n\nclass DevtoolsLogChannel extends LogChannel {\n public override name = \"devtools\";\n public active = true;\n\n public constructor(private readonly collector: DevtoolsCollector) {\n super();\n }\n\n public log(data: LoggingData): void {\n if (!this.active) return;\n\n // Already passed through the logger's redaction floor (`Logger.log`\n // applies it before invoking any channel). It is still app data, and can\n // hold live objects (a request, its socket), so a JSON-safe snapshot is\n // kept instead of the object itself.\n const entry: DevtoolsLogEntry = {\n level: toDevtoolsLevel(data.type),\n module: data.module,\n action: data.action,\n message: data.message,\n at: Date.now(),\n context: toSafeValue(data.context),\n };\n\n this.collector.addLog(currentRequestId(), entry);\n }\n}\n\n/**\n * Feeds every log entry, from `@warlock.js/logger`, into the collector by\n * registering an additional channel. `Logger` has no way to remove a\n * channel, so the disposer flag-ignores further entries instead — the\n * channel stays registered for the process's lifetime.\n */\nexport async function attachLogSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const channel = new DevtoolsLogChannel(collector);\n\n log.addChannel(channel);\n\n return () => {\n channel.active = false;\n };\n}\n","import type { CapturedMail, MailAddress, MailAttachment } from \"@warlock.js/core\";\nimport { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsMailAttachment } from \"../types\";\n\nfunction addressToString(address: MailAddress | undefined): string | undefined {\n if (!address) return undefined;\n\n return typeof address === \"string\" ? address : `${address.name} <${address.address}>`;\n}\n\nfunction attachmentSize(attachment: MailAttachment): number | undefined {\n if (typeof attachment.content === \"string\") return Buffer.byteLength(attachment.content);\n if (Buffer.isBuffer(attachment.content)) return attachment.content.length;\n\n return undefined;\n}\n\nfunction toDevtoolsAttachment(attachment: MailAttachment): DevtoolsMailAttachment {\n return {\n filename: attachment.filename,\n contentType: attachment.contentType,\n size: attachmentSize(attachment),\n };\n}\n\n/**\n * Feeds mails captured in development mode, from core's `mailEvents`, into\n * the collector. The captured attachments carry their content, but only\n * metadata is stored — the bytes are never kept.\n */\nexport async function attachMailSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const { mailEvents } = await import(\"@warlock.js/core\");\n\n const subscription = mailEvents.onCaptured((mail: CapturedMail) => {\n const { normalized } = mail;\n\n collector.addMail({\n id: mail.id,\n requestId: currentRequestId(),\n capturedAt: mail.timestamp.getTime(),\n from: addressToString(normalized.from),\n to: normalized.to,\n cc: normalized.cc,\n bcc: normalized.bcc,\n subject: normalized.subject,\n html: normalized.html,\n text: normalized.text,\n headers: normalized.headers,\n attachments: normalized.attachments.map(toDevtoolsAttachment),\n });\n });\n\n return () => subscription.unsubscribe();\n}\n","import { fileURLToPath } from \"node:url\";\n\nimport type { DevtoolsCallerLocation } from \"./types\";\n\nconst packageDirectory = normalizePath(fileURLToPath(new URL(\"../\", import.meta.url)));\n\n/** Returns the first non-runtime, non-devtools frame in a V8 stack trace. */\nexport function captureCallerLocation(\n stack: string = new Error().stack ?? \"\",\n): DevtoolsCallerLocation | undefined {\n for (const line of stack.split(\"\\n\")) {\n const frame = parseFrame(line);\n if (!frame || shouldSkip(frame.file)) continue;\n return frame;\n }\n return undefined;\n}\n\nfunction parseFrame(frame: string): DevtoolsCallerLocation | undefined {\n const match = frame.match(/\\bat\\s+(?:.*?\\s+\\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/);\n const [, rawFile, line, column] = match ?? [];\n if (!rawFile || !line || !column) return undefined;\n const file = normalizePath(rawFile);\n return { file, line: Number(line), column: Number(column) };\n}\n\n/** A drive-letter file URL names a Windows path on whichever host decodes it. */\nconst WINDOWS_DRIVE_FILE_URL = /^file:\\/\\/\\/[A-Za-z]:/;\n\nfunction normalizePath(path: string): string {\n const decoded = !path.startsWith(\"file:\")\n ? path\n : WINDOWS_DRIVE_FILE_URL.test(path)\n ? fileURLToPath(path, { windows: true })\n : fileURLToPath(path);\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction shouldSkip(file: string): boolean {\n return (\n file.startsWith(\"node:\") ||\n file.includes(\"/node_modules/\") ||\n // Node's own frames (`node:internal/…`, or bare `internal/…` on older\n // runtimes); an app folder named `internal` is still an app frame.\n file.startsWith(\"internal/\") ||\n file.startsWith(packageDirectory)\n );\n}\n","import { applyRedact, log } from \"@warlock.js/logger\";\nimport { captureCallerLocation } from \"../caller-location\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** The shape of the event `dataSourceRegistry` emits for `\"query\"`. */\ntype QueryEvent = {\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n sql?: string;\n bindings?: unknown[];\n collection?: string;\n command?: string;\n pipeline?: unknown;\n durationMs: number;\n startedAt: number;\n rowCount?: number;\n error?: unknown;\n};\n\n/** Redacts query bindings through the logger's redaction rules. */\nfunction redactBindings(bindings: unknown[] | undefined): unknown[] | undefined {\n if (!bindings) return bindings;\n\n const redacted = applyRedact(\n {\n type: \"debug\",\n module: \"devtools\",\n action: \"query\",\n message: undefined,\n context: { bindings },\n },\n log.getRedact(),\n );\n\n return (redacted.context as { bindings: unknown[] }).bindings;\n}\n\n/**\n * Feeds every settled database query, from cascade's data source registry,\n * into the collector. A no-op when `@warlock.js/cascade` isn't installed —\n * it is an optional peer.\n */\nexport async function attachQuerySource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let dataSourceRegistry: {\n on(event: \"query\", listener: (event: QueryEvent) => void): void;\n off(event: \"query\", listener: (event: QueryEvent) => void): void;\n };\n\n try {\n ({ dataSourceRegistry } = await import(\"@warlock.js/cascade\"));\n } catch {\n return () => {};\n }\n\n const listener = (event: QueryEvent) => {\n collector.addQuery(currentRequestId(), {\n connection: event.connection,\n driver: event.driver,\n sql: event.sql,\n bindings: toSafeValue(redactBindings(event.bindings)) as unknown[] | undefined,\n collection: event.collection,\n command: event.command,\n pipeline: event.pipeline,\n startedAt: event.startedAt,\n durationMs: event.durationMs,\n rowCount: event.rowCount,\n error:\n event.error === undefined\n ? undefined\n : event.error instanceof Error\n ? event.error.message\n : String(event.error),\n caller: captureCallerLocation(),\n });\n };\n\n dataSourceRegistry.on(\"query\", listener);\n\n return () => dataSourceRegistry.off(\"query\", listener);\n}\n","import type { TracingContext, TracingPhaseInfo, TracingRequestEndInfo } from \"@warlock.js/core\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, ResolvedDevtoolsOptions } from \"../types\";\n\n/**\n * Feeds request timelines from core's tracing hooks into the collector: one\n * `startRequest`/`endRequest` pair per HTTP request, with every named phase\n * in between. Requests to the dashboard's own path are never recorded, so\n * the dashboard never watches itself.\n */\nexport async function attachTracingSource(\n collector: DevtoolsCollector,\n options: ResolvedDevtoolsOptions,\n): Promise<DevtoolsDisposer> {\n const { registerTracingHooks } = await import(\"@warlock.js/core\");\n\n const isDashboardPath = (path: string): boolean => path.startsWith(options.path);\n\n return registerTracingHooks({\n onRequestStart(ctx: TracingContext) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.startRequest({\n id: ctx.requestId,\n method: ctx.method,\n path: ctx.path,\n route: ctx.route,\n startedAt: performance.timeOrigin + performance.now(),\n });\n },\n onPhase(ctx: TracingContext, phase: TracingPhaseInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.addPhase(ctx.requestId, {\n name: phase.name,\n durationMs: phase.durationMs,\n startedAt: phase.startedAt ?? performance.timeOrigin + performance.now() - phase.durationMs,\n attrs: phase.attrs === undefined ? undefined : (toSafeValue(phase.attrs) as Record<string, unknown>),\n });\n },\n onRequestEnd(ctx: TracingContext, result: TracingRequestEndInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.endRequest(ctx.requestId, {\n status: result.status,\n durationMs: result.durationMs,\n error:\n result.error === undefined\n ? undefined\n : result.error instanceof Error\n ? result.error.message\n : String(result.error),\n route: ctx.route,\n });\n },\n });\n}\n","/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport type { DevtoolsRouteRow } from \"./server\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Refuses to run outside development: `boot()` checks\n * `Application.runtimeStrategy` and, when it isn't `\"development\"`, logs one\n * warning and returns without mounting a route or subscribing to anything.\n * In development it attaches every source (tracing, queries, cache, mail,\n * logs), then mounts the dashboard's routes on the HTTP server — before it\n * starts listening, the only point in the boot sequence where mounting is\n * possible (see `queue/src/dashboard-boot.ts` for the same constraint).\n *\n * Apps don't call this: `warlock dev` registers it automatically when the\n * package is installed (`warlock add devtools`). Keep it OUT of\n * `warlock.config.ts` — devtools is a dev dependency, so a production\n * install doesn't have it and a config import of it would fail there.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const { Application, getHttpServer } = await import(\"@warlock.js/core\");\n const { log } = await import(\"@warlock.js/logger\");\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development; it is not mounted\",\n );\n return;\n }\n\n const resolved = resolveDevtoolsOptions(options);\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n options: resolved,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n for (const dispose of disposers.splice(0)) dispose();\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n"],"mappings":";;;;;;;AAGA,SAAgB,eAAe,SAA0B,WAAsC;CAC7F,MAAM,yBAAS,IAAI,IAA6B;C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AAQ,MAAM,OAAO,YAAY;EACjC,MAAM,MAAM;EACZ,MAAM,MAAM;EACZ,YAAY,MAAM,YAAY,KAAK,eAAe,WAAW,QAAQ,WAAW;CAClF,EAAE;AACJ;;;;;;AAOA,eAAe,qBAAsC;CACnD,MAAM,EAAE,kCAAkC,MAAM,OAAO;CACvD,MAAM,EAAE,aAAa,MAAM,8BAA8B;CAEzD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["requestContext","LogChannel","log"],"sources":["../../../../../../devtools/src/n-plus-one.ts","../../../../../../devtools/src/query-shape.ts","../../../../../../devtools/src/collector.ts","../../../../../../devtools/src/options.ts","../../../../../../devtools/src/current-request-id.ts","../../../../../../devtools/src/sources/cache-source.ts","../../../../../../devtools/src/safe-value.ts","../../../../../../devtools/src/sources/log-source.ts","../../../../../../devtools/src/sources/mail-source.ts","../../../../../../devtools/src/caller-location.ts","../../../../../../devtools/src/sources/query-source.ts","../../../../../../devtools/src/sources/tracing-source.ts","../../../../../../devtools/src/devtools-connector.ts"],"sourcesContent":["import type { DevtoolsCallerLocation, DevtoolsQuery, DevtoolsWarning } from \"./types\";\n\n/** Finds repeated query shapes whose occurrence count reaches the supplied threshold. */\nexport function detectNPlusOne(queries: DevtoolsQuery[], threshold: number): DevtoolsWarning[] {\n const groups = new Map<string, DevtoolsQuery[]>();\n for (const query of queries) groups.set(query.shape, [...(groups.get(query.shape) ?? []), query]);\n\n return [...groups.entries()]\n .filter(([, grouped]) => grouped.length >= threshold)\n .sort(([, left], [, right]) => right.length - left.length)\n .map(([shape, grouped]) => ({\n type: \"n+1\" as const,\n shape,\n count: grouped.length,\n message: `N+1: ${grouped.length}× \"${truncate(shape, 120)}\"`,\n ...(mostFrequentCaller(grouped) ? { caller: mostFrequentCaller(grouped) } : {}),\n }));\n}\n\nfunction truncate(value: string, maximum: number): string {\n return value.length > maximum ? `${value.slice(0, maximum - 1)}…` : value;\n}\n\nfunction mostFrequentCaller(queries: DevtoolsQuery[]): DevtoolsCallerLocation | undefined {\n const callers = new Map<string, { caller: DevtoolsCallerLocation; count: number }>();\n for (const query of queries) {\n if (!query.caller) continue;\n const key = `${query.caller.file}:${query.caller.line}`;\n const found = callers.get(key);\n callers.set(\n key,\n found ? { ...found, count: found.count + 1 } : { caller: query.caller, count: 1 },\n );\n }\n return [...callers.values()].sort((left, right) => right.count - left.count)[0]?.caller;\n}\n","import type { DevtoolsQuery } from \"./types\";\n\ntype QueryShapeInput = Pick<\n DevtoolsQuery,\n \"driver\" | \"sql\" | \"collection\" | \"command\" | \"pipeline\"\n>;\n\nconst numericLiteral = /(?<![\\w$])[-+]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?![\\w$])/g;\nconst quotedLiteral = /'(?:''|[^'])*'/g;\n\n/** Returns a binding-independent shape for a database query. */\nexport function queryShape(query: QueryShapeInput): string {\n if (query.driver === \"postgres\") {\n return (query.sql ?? \"\")\n .replace(quotedLiteral, \"?\")\n .replace(numericLiteral, \"?\")\n .replace(/\\s+/g, \" \")\n .trim();\n }\n\n return `${query.collection ?? \"\"}.${query.command ?? \"\"} ${JSON.stringify(normalizeMongoValue(query.pipeline))}`;\n}\n\nfunction normalizeMongoValue(value: unknown): unknown {\n if (isMongoLeaf(value)) return \"?\";\n\n if (Array.isArray(value)) {\n if (value.every(isMongoLeaf)) return [\"?\"];\n return value.map(normalizeMongoValue);\n }\n\n const record = value as Record<string, unknown>;\n return Object.fromEntries(\n Object.keys(record).map((key) => [key, normalizeMongoValue(record[key])]),\n );\n}\n\nfunction isMongoLeaf(value: unknown): boolean {\n if (value === null || typeof value !== \"object\") return true;\n if (value instanceof Date) return true;\n const record = value as Record<string, unknown>;\n return typeof record.toHexString === \"function\" || typeof record.$oid === \"string\";\n}\n","import type {\n DevtoolsBackground,\n DevtoolsCacheOperation,\n DevtoolsCollector,\n DevtoolsDisposer,\n DevtoolsLogEntry,\n DevtoolsMail,\n DevtoolsMailSummary,\n DevtoolsPhase,\n DevtoolsQuery,\n DevtoolsRequest,\n DevtoolsRequestSummary,\n DevtoolsStreamEvent,\n ResolvedDevtoolsOptions,\n} from \"./types\";\nimport { detectNPlusOne } from \"./n-plus-one\";\nimport { queryShape } from \"./query-shape\";\n\nconst mailLimit = 100;\nconst logLimit = 1000;\nconst backgroundLimit = 500;\n\n/**\n * Creates the in-memory devtools store.\n *\n * Read methods return shallow structural copies, including copied arrays, so consumers\n * cannot mutate collector-owned arrays. The individual nested entries are retained.\n */\nexport function createCollector(options: ResolvedDevtoolsOptions): DevtoolsCollector {\n const requests = new Map<string, DevtoolsRequest>();\n const mails = new Map<string, DevtoolsMail>();\n const logs: DevtoolsLogEntry[] = [];\n const background: DevtoolsBackground = { queries: [], cache: [], logs: [] };\n const listeners = new Set<(event: DevtoolsStreamEvent) => void>();\n let querySequence = 0;\n\n const emit = (event: DevtoolsStreamEvent) => {\n for (const listener of listeners) {\n try {\n listener(event);\n } catch {\n /* Subscribers must not affect collection. */\n }\n }\n };\n\n const addBackground = <T>(list: T[], value: T) => {\n list.push(value);\n if (list.length > backgroundLimit) list.shift();\n };\n\n return {\n startRequest(request) {\n requests.delete(request.id);\n requests.set(request.id, {\n ...request,\n phases: [],\n queries: [],\n cache: [],\n logs: [],\n mails: [],\n warnings: [],\n });\n while (requests.size > options.maxRequests)\n requests.delete(requests.keys().next().value as string);\n },\n endRequest(id, result) {\n const request = requests.get(id);\n if (!request) return;\n request.status = result.status;\n request.durationMs = result.durationMs;\n request.error = result.error;\n if (result.route !== undefined) request.route = result.route;\n request.warnings = detectNPlusOne(request.queries, options.nPlusOneThreshold);\n emit({ type: \"request\", data: summary(request) });\n },\n addPhase(requestId, phase) {\n requests.get(requestId)?.phases.push(phase);\n },\n addQuery(requestId, query) {\n const stored: DevtoolsQuery = {\n ...query,\n id: `q${++querySequence}`,\n shape: queryShape(query),\n };\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.queries.push(stored);\n else addBackground(background.queries, stored);\n return stored;\n },\n addCacheOperation(requestId, operation) {\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.cache.push(operation);\n else addBackground(background.cache, operation);\n },\n addLog(requestId, entry) {\n const request = requestId ? requests.get(requestId) : undefined;\n if (request) request.logs.push(entry);\n else addBackground(background.logs, entry);\n logs.unshift(entry);\n if (logs.length > logLimit) logs.pop();\n emit({ type: \"log\", data: entry });\n },\n addMail(mail) {\n mails.delete(mail.id);\n mails.set(mail.id, mail);\n while (mails.size > mailLimit) mails.delete(mails.keys().next().value as string);\n if (mail.requestId) requests.get(mail.requestId)?.mails.push(mail.id);\n emit({ type: \"mail\", data: mailSummary(mail) });\n },\n listRequests() {\n return [...requests.values()].reverse().map(summary);\n },\n getRequest(id) {\n const request = requests.get(id);\n return request && copyRequest(request);\n },\n listMails() {\n return [...mails.values()].reverse().map(mailSummary);\n },\n getMail(id) {\n const mail = mails.get(id);\n return (\n mail && {\n ...mail,\n to: [...mail.to],\n cc: [...mail.cc],\n bcc: [...mail.bcc],\n headers: { ...mail.headers },\n attachments: [...mail.attachments],\n }\n );\n },\n listLogs(filter = {}) {\n const module = filter.module?.toLowerCase();\n return logs\n .filter(\n (entry) =>\n (!filter.level || entry.level === filter.level) &&\n (!module || entry.module.toLowerCase().includes(module)),\n )\n .map((entry) => ({ ...entry }));\n },\n getBackground() {\n return {\n queries: [...background.queries],\n cache: [...background.cache],\n logs: [...background.logs],\n };\n },\n subscribe(listener): DevtoolsDisposer {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n clear() {\n requests.clear();\n mails.clear();\n logs.length = 0;\n background.queries.length = 0;\n background.cache.length = 0;\n background.logs.length = 0;\n },\n };\n}\n\nfunction summary(request: DevtoolsRequest): DevtoolsRequestSummary {\n const { id, method, path, route, status, startedAt, durationMs } = request;\n return {\n id,\n method,\n path,\n route,\n status,\n startedAt,\n durationMs,\n queryCount: request.queries.length,\n warningCount: request.warnings.length,\n };\n}\n\nfunction mailSummary(mail: DevtoolsMail): DevtoolsMailSummary {\n const { id, requestId, capturedAt, to, subject } = mail;\n return { id, requestId, capturedAt, to: [...to], subject };\n}\n\nfunction copyRequest(request: DevtoolsRequest): DevtoolsRequest {\n return {\n ...request,\n phases: [...request.phases],\n queries: [...request.queries],\n cache: [...request.cache],\n logs: [...request.logs],\n mails: [...request.mails],\n warnings: [...request.warnings],\n };\n}\n","import type { DevtoolsOptions, ResolvedDevtoolsOptions } from \"./types\";\n\n/** Resolves dashboard options and rejects invalid capacity or URL-prefix values. */\nexport function resolveDevtoolsOptions(options: DevtoolsOptions = {}): ResolvedDevtoolsOptions {\n const path = (options.path ?? \"/__warlock\").replace(/\\/+$/, \"\");\n const maxRequests = options.maxRequests ?? 200;\n const nPlusOneThreshold = options.nPlusOneThreshold ?? 5;\n\n if (!path || !path.startsWith(\"/\")) {\n throw new Error('Devtools option \"path\" must be a non-root path starting with \"/\".');\n }\n\n if (maxRequests < 1) {\n throw new Error('Devtools option \"maxRequests\" must be at least 1.');\n }\n\n if (nPlusOneThreshold < 2) {\n throw new Error('Devtools option \"nPlusOneThreshold\" must be at least 2.');\n }\n\n return { path, maxRequests, nPlusOneThreshold };\n}\n","import { requestContext } from \"@warlock.js/core\";\n\n/**\n * The current request's id (core's `request.id`, threaded through\n * `AsyncLocalStorage`), or `undefined` outside a request — sources feed\n * devtools' background bucket in that case.\n *\n * Only ever reached through `./sources/*`, which the connector imports\n * dynamically inside `boot()` — by then core is already running, so this\n * static import never drags core's runtime graph into config-load time (see\n * `devtools-connector.ts`).\n */\nexport function currentRequestId(): string | undefined {\n try {\n return requestContext.getRequest()?.id;\n } catch {\n return undefined;\n }\n}\n","import { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCacheOperation, DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** Cache events the dashboard's waterfall and background bucket care about. */\nconst EVENT_TYPES = [\"hit\", \"miss\", \"set\", \"removed\", \"invalidated\", \"flushed\"] as const;\n\n/** The shape `cache.on(event, handler)` hands the handler. */\ntype CacheEventData = {\n key?: string;\n driver: string;\n tags?: string[];\n keys?: string[];\n durationMs?: number;\n};\n\n/**\n * Feeds cache hits, misses and mutations, from `@warlock.js/cache`, into the\n * collector. A no-op when `@warlock.js/cache` isn't installed — it is an\n * optional peer.\n */\nexport async function attachCacheSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let cache: {\n on(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n off(event: (typeof EVENT_TYPES)[number], handler: (data: CacheEventData) => void): unknown;\n };\n\n try {\n ({ cache } = await import(\"@warlock.js/cache\"));\n } catch {\n return () => {};\n }\n\n const handlers = EVENT_TYPES.map((type) => {\n const handler = (data: CacheEventData) => {\n const operation: DevtoolsCacheOperation = {\n type,\n driver: data.driver,\n key: data.key,\n tags: data.tags,\n keys: data.keys,\n at: Date.now(),\n durationMs: data.durationMs,\n };\n\n collector.addCacheOperation(currentRequestId(), operation);\n };\n\n cache.on(type, handler);\n\n return { type, handler };\n });\n\n return () => {\n for (const { type, handler } of handlers) cache.off(type, handler);\n };\n}\n","const MAX_DEPTH = 6;\n\n/**\n * A JSON-safe snapshot of a value devtools keeps for later display.\n *\n * Log contexts and phase attributes are app data: they can hold live objects\n * (a request, its socket) whose graphs are circular and which must not be kept\n * alive by the collector anyway. Plain objects and arrays are copied; anything\n * with a `toJSON()` is serialized through it; other class instances collapse\n * to `[ClassName]`, cycles to `[Circular]`, and nesting past a fixed depth to\n * `[Object]` / `[Array]`.\n */\nexport function toSafeValue(value: unknown): unknown {\n return snapshot(value, 0, new WeakSet());\n}\n\nfunction snapshot(value: unknown, depth: number, seen: WeakSet<object>): unknown {\n if (value === null || value === undefined) return value;\n\n switch (typeof value) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"symbol\":\n return value.toString();\n case \"function\":\n return undefined;\n }\n\n const object = value as object;\n\n if (seen.has(object)) return \"[Circular]\";\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n if (value instanceof Error) return { name: value.name, message: value.message };\n\n if (depth >= MAX_DEPTH) return Array.isArray(value) ? \"[Array]\" : \"[Object]\";\n\n seen.add(object);\n\n try {\n if (Array.isArray(value)) return value.map((item) => snapshot(item, depth + 1, seen));\n\n const prototype = Object.getPrototypeOf(object);\n\n if (prototype !== Object.prototype && prototype !== null) {\n const toJSON = (object as { toJSON?: unknown }).toJSON;\n\n if (typeof toJSON === \"function\") {\n try {\n return snapshot(toJSON.call(object), depth + 1, seen);\n } catch {\n return `[${constructorName(object)}]`;\n }\n }\n\n return `[${constructorName(object)}]`;\n }\n\n const copy: Record<string, unknown> = {};\n\n for (const [key, entry] of Object.entries(object)) {\n const safe = snapshot(entry, depth + 1, seen);\n if (safe !== undefined) copy[key] = safe;\n }\n\n return copy;\n } finally {\n seen.delete(object);\n }\n}\n\nfunction constructorName(object: object): string {\n return (object as { constructor?: { name?: string } }).constructor?.name || \"Object\";\n}\n","import { LogChannel, log, type LoggingData } from \"@warlock.js/logger\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsLogEntry } from \"../types\";\n\n/** `LoggingData.type` includes `fatal`, which devtools folds into `error`. */\nfunction toDevtoolsLevel(type: LoggingData[\"type\"]): DevtoolsLogEntry[\"level\"] {\n return type === \"fatal\" ? \"error\" : type;\n}\n\nclass DevtoolsLogChannel extends LogChannel {\n public override name = \"devtools\";\n public active = true;\n\n public constructor(private readonly collector: DevtoolsCollector) {\n super();\n }\n\n public log(data: LoggingData): void {\n if (!this.active) return;\n\n // Already passed through the logger's redaction floor (`Logger.log`\n // applies it before invoking any channel). It is still app data, and can\n // hold live objects (a request, its socket), so a JSON-safe snapshot is\n // kept instead of the object itself.\n const entry: DevtoolsLogEntry = {\n level: toDevtoolsLevel(data.type),\n module: data.module,\n action: data.action,\n message: data.message,\n at: Date.now(),\n context: toSafeValue(data.context),\n };\n\n this.collector.addLog(currentRequestId(), entry);\n }\n}\n\n/**\n * Feeds every log entry, from `@warlock.js/logger`, into the collector by\n * registering an additional channel. `Logger` has no way to remove a\n * channel, so the disposer flag-ignores further entries instead — the\n * channel stays registered for the process's lifetime.\n */\nexport async function attachLogSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const channel = new DevtoolsLogChannel(collector);\n\n log.addChannel(channel);\n\n return () => {\n channel.active = false;\n };\n}\n","import type { CapturedMail, MailAddress, MailAttachment } from \"@warlock.js/core\";\nimport { currentRequestId } from \"../current-request-id\";\nimport type { DevtoolsCollector, DevtoolsDisposer, DevtoolsMailAttachment } from \"../types\";\n\nfunction addressToString(address: MailAddress | undefined): string | undefined {\n if (!address) return undefined;\n\n return typeof address === \"string\" ? address : `${address.name} <${address.address}>`;\n}\n\nfunction attachmentSize(attachment: MailAttachment): number | undefined {\n if (typeof attachment.content === \"string\") return Buffer.byteLength(attachment.content);\n if (Buffer.isBuffer(attachment.content)) return attachment.content.length;\n\n return undefined;\n}\n\nfunction toDevtoolsAttachment(attachment: MailAttachment): DevtoolsMailAttachment {\n return {\n filename: attachment.filename,\n contentType: attachment.contentType,\n size: attachmentSize(attachment),\n };\n}\n\n/**\n * Feeds mails captured in development mode, from core's `mailEvents`, into\n * the collector. The captured attachments carry their content, but only\n * metadata is stored — the bytes are never kept.\n */\nexport async function attachMailSource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n const { mailEvents } = await import(\"@warlock.js/core\");\n\n const subscription = mailEvents.onCaptured((mail: CapturedMail) => {\n const { normalized } = mail;\n\n collector.addMail({\n id: mail.id,\n requestId: currentRequestId(),\n capturedAt: mail.timestamp.getTime(),\n from: addressToString(normalized.from),\n to: normalized.to,\n cc: normalized.cc,\n bcc: normalized.bcc,\n subject: normalized.subject,\n html: normalized.html,\n text: normalized.text,\n headers: normalized.headers,\n attachments: normalized.attachments.map(toDevtoolsAttachment),\n });\n });\n\n return () => subscription.unsubscribe();\n}\n","import { fileURLToPath } from \"node:url\";\n\nimport type { DevtoolsCallerLocation } from \"./types\";\n\nconst packageDirectory = normalizePath(fileURLToPath(new URL(\"../\", import.meta.url)));\n\n/** Returns the first non-runtime, non-devtools frame in a V8 stack trace. */\nexport function captureCallerLocation(\n stack: string = new Error().stack ?? \"\",\n): DevtoolsCallerLocation | undefined {\n for (const line of stack.split(\"\\n\")) {\n const frame = parseFrame(line);\n if (!frame || shouldSkip(frame.file)) continue;\n return frame;\n }\n return undefined;\n}\n\nfunction parseFrame(frame: string): DevtoolsCallerLocation | undefined {\n const match = frame.match(/\\bat\\s+(?:.*?\\s+\\()?(.+?):(\\d+):(\\d+)\\)?\\s*$/);\n const [, rawFile, line, column] = match ?? [];\n if (!rawFile || !line || !column) return undefined;\n const file = normalizePath(rawFile);\n return { file, line: Number(line), column: Number(column) };\n}\n\n/** A drive-letter file URL names a Windows path on whichever host decodes it. */\nconst WINDOWS_DRIVE_FILE_URL = /^file:\\/\\/\\/[A-Za-z]:/;\n\nfunction normalizePath(path: string): string {\n const decoded = !path.startsWith(\"file:\")\n ? path\n : WINDOWS_DRIVE_FILE_URL.test(path)\n ? fileURLToPath(path, { windows: true })\n : fileURLToPath(path);\n return decoded.replace(/\\\\/g, \"/\");\n}\n\nfunction shouldSkip(file: string): boolean {\n return (\n file.startsWith(\"node:\") ||\n file.includes(\"/node_modules/\") ||\n // Node's own frames (`node:internal/…`, or bare `internal/…` on older\n // runtimes); an app folder named `internal` is still an app frame.\n file.startsWith(\"internal/\") ||\n file.startsWith(packageDirectory)\n );\n}\n","import { applyRedact, log } from \"@warlock.js/logger\";\nimport { captureCallerLocation } from \"../caller-location\";\nimport { currentRequestId } from \"../current-request-id\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer } from \"../types\";\n\n/** The shape of the event `dataSourceRegistry` emits for `\"query\"`. */\ntype QueryEvent = {\n connection: string;\n driver: \"postgres\" | \"mongodb\";\n sql?: string;\n bindings?: unknown[];\n collection?: string;\n command?: string;\n pipeline?: unknown;\n durationMs: number;\n startedAt: number;\n rowCount?: number;\n error?: unknown;\n};\n\n/** Redacts query bindings through the logger's redaction rules. */\nfunction redactBindings(bindings: unknown[] | undefined): unknown[] | undefined {\n if (!bindings) return bindings;\n\n const redacted = applyRedact(\n {\n type: \"debug\",\n module: \"devtools\",\n action: \"query\",\n message: undefined,\n context: { bindings },\n },\n log.getRedact(),\n );\n\n return (redacted.context as { bindings: unknown[] }).bindings;\n}\n\n/**\n * Feeds every settled database query, from cascade's data source registry,\n * into the collector. A no-op when `@warlock.js/cascade` isn't installed —\n * it is an optional peer.\n */\nexport async function attachQuerySource(collector: DevtoolsCollector): Promise<DevtoolsDisposer> {\n let dataSourceRegistry: {\n on(event: \"query\", listener: (event: QueryEvent) => void): void;\n off(event: \"query\", listener: (event: QueryEvent) => void): void;\n };\n\n try {\n ({ dataSourceRegistry } = await import(\"@warlock.js/cascade\"));\n } catch {\n return () => {};\n }\n\n const listener = (event: QueryEvent) => {\n collector.addQuery(currentRequestId(), {\n connection: event.connection,\n driver: event.driver,\n sql: event.sql,\n bindings: toSafeValue(redactBindings(event.bindings)) as unknown[] | undefined,\n collection: event.collection,\n command: event.command,\n pipeline: event.pipeline,\n startedAt: event.startedAt,\n durationMs: event.durationMs,\n rowCount: event.rowCount,\n error:\n event.error === undefined\n ? undefined\n : event.error instanceof Error\n ? event.error.message\n : String(event.error),\n caller: captureCallerLocation(),\n });\n };\n\n dataSourceRegistry.on(\"query\", listener);\n\n return () => dataSourceRegistry.off(\"query\", listener);\n}\n","import type { TracingContext, TracingPhaseInfo, TracingRequestEndInfo } from \"@warlock.js/core\";\nimport { toSafeValue } from \"../safe-value\";\nimport type { DevtoolsCollector, DevtoolsDisposer, ResolvedDevtoolsOptions } from \"../types\";\n\n/**\n * Feeds request timelines from core's tracing hooks into the collector: one\n * `startRequest`/`endRequest` pair per HTTP request, with every named phase\n * in between. Requests to the dashboard's own path are never recorded, so\n * the dashboard never watches itself.\n */\nexport async function attachTracingSource(\n collector: DevtoolsCollector,\n options: ResolvedDevtoolsOptions,\n): Promise<DevtoolsDisposer> {\n const { registerTracingHooks } = await import(\"@warlock.js/core\");\n\n const isDashboardPath = (path: string): boolean => path.startsWith(options.path);\n\n return registerTracingHooks({\n onRequestStart(ctx: TracingContext) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.startRequest({\n id: ctx.requestId,\n method: ctx.method,\n path: ctx.path,\n route: ctx.route,\n startedAt: performance.timeOrigin + performance.now(),\n });\n },\n onPhase(ctx: TracingContext, phase: TracingPhaseInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.addPhase(ctx.requestId, {\n name: phase.name,\n durationMs: phase.durationMs,\n startedAt: phase.startedAt ?? performance.timeOrigin + performance.now() - phase.durationMs,\n attrs: phase.attrs === undefined ? undefined : (toSafeValue(phase.attrs) as Record<string, unknown>),\n });\n },\n onRequestEnd(ctx: TracingContext, result: TracingRequestEndInfo) {\n if (isDashboardPath(ctx.path)) return;\n\n collector.endRequest(ctx.requestId, {\n status: result.status,\n durationMs: result.durationMs,\n error:\n result.error === undefined\n ? undefined\n : result.error instanceof Error\n ? result.error.message\n : String(result.error),\n route: ctx.route,\n });\n },\n });\n}\n","/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport type { DevtoolsRouteRow } from \"./server\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Refuses to run outside development: `boot()` checks\n * `Application.runtimeStrategy` and, when it isn't `\"development\"`, logs one\n * warning and returns without mounting a route or subscribing to anything.\n * In development it attaches every source (tracing, queries, cache, mail,\n * logs), then mounts the dashboard's routes on the HTTP server — before it\n * starts listening, the only point in the boot sequence where mounting is\n * possible (see `queue/src/dashboard-boot.ts` for the same constraint).\n *\n * Apps don't call this: `warlock dev` registers it automatically when the\n * package is installed (`warlock add devtools`). Keep it OUT of\n * `warlock.config.ts` — devtools is a dev dependency, so a production\n * install doesn't have it and a config import of it would fail there.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const { Application, getHttpServer } = await import(\"@warlock.js/core\");\n const { log } = await import(\"@warlock.js/logger\");\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development; it is not mounted\",\n );\n return;\n }\n\n const resolved = resolveDevtoolsOptions(options);\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n const postmanBuilder = await findPostmanBuilder();\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n options: resolved,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n getPostmanCollection: postmanBuilder\n ? async () => unwrapCollection(await postmanBuilder())\n : undefined,\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n for (const dispose of disposers.splice(0)) dispose();\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n\ntype PostmanBuilder = () => Promise<unknown>;\n\n/**\n * Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.\n * Older cores do not export it; the route then answers 503. The lookup is\n * guarded because a namespace without the export may throw on access. Core is\n * imported lazily, like the OpenAPI document above.\n */\nasync function findPostmanBuilder(): Promise<PostmanBuilder | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const build = core.getDevelopmentPostmanCollection;\n\n return typeof build === \"function\" ? (build as PostmanBuilder) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Core may return the collection itself or wrap it in `{ collection, warnings }`,\n * like the OpenAPI generator's `{ document, warnings }`.\n */\nfunction unwrapCollection(result: unknown): object {\n if (result && typeof result === \"object\" && \"collection\" in result) {\n return (result as { collection: object }).collection;\n }\n\n return result as object;\n}\n"],"mappings":";;;;;;;AAGA,SAAgB,eAAe,SAA0B,WAAsC;CAC7F,MAAM,yBAAS,IAAI,IAA6B;CAChD,KAAK,MAAM,SAAS,SAAS,OAAO,IAAI,MAAM,OAAO,CAAC,GAAI,OAAO,IAAI,MAAM,KAAK,KAAK,CAAC,GAAI,KAAK,CAAC;CAEhG,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,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Y,MAAM,YAAY,KAAK,eAAe,WAAW,QAAQ,WAAW;CAClF,EAAE;AACJ;;;;;;AAOA,eAAe,qBAAsC;CACnD,MAAM,EAAE,kCAAkC,MAAM,OAAO;CACvD,MAAM,EAAE,aAAa,MAAM,8BAA8B;CAEzD,OAAO;AACT;;;;;;;AAUA,eAAe,qBAA0D;CACvE,IAAI;EAEF,MAAM,SAAQ,MAD8B,OAAO,oBACjC,CAAC;EAEnB,OAAO,OAAO,UAAU,aAAc,QAA2B;CACnE,QAAQ;EACN;CACF;AACF;;;;;AAMA,SAAS,iBAAiB,QAAyB;CACjD,IAAI,UAAU,OAAO,WAAW,YAAY,gBAAgB,QAC1D,OAAQ,OAAkC;CAG5C,OAAO;AACT"}
|
|
@@ -187,6 +187,18 @@ const UI_ASSETS = {
|
|
|
187
187
|
"scalar.js": {
|
|
188
188
|
contentType: "text/javascript; charset=utf-8",
|
|
189
189
|
file: uiFile("vendor/scalar/standalone.js")
|
|
190
|
+
},
|
|
191
|
+
"swagger-ui-bundle.js": {
|
|
192
|
+
contentType: "text/javascript; charset=utf-8",
|
|
193
|
+
file: uiFile("vendor/swagger-ui/swagger-ui-bundle.js")
|
|
194
|
+
},
|
|
195
|
+
"swagger-ui.css": {
|
|
196
|
+
contentType: "text/css; charset=utf-8",
|
|
197
|
+
file: uiFile("vendor/swagger-ui/swagger-ui.css")
|
|
198
|
+
},
|
|
199
|
+
"docs-swagger.js": {
|
|
200
|
+
contentType: "text/javascript; charset=utf-8",
|
|
201
|
+
file: uiFile("docs-swagger.js")
|
|
190
202
|
}
|
|
191
203
|
};
|
|
192
204
|
/** Sends `file` with `contentType` and no caching. */
|
|
@@ -195,8 +207,8 @@ function sendFile(reply, file, contentType) {
|
|
|
195
207
|
}
|
|
196
208
|
/**
|
|
197
209
|
* Serves the static dashboard: `index.html` at the dashboard root and the
|
|
198
|
-
* whitelisted assets (`app.js`, `app.css`,
|
|
199
|
-
*
|
|
210
|
+
* whitelisted assets (`app.js`, `app.css`, the vendored Scalar bundle as
|
|
211
|
+
* `scalar.js`, and the vendored Swagger UI files plus their init script). The asset name is matched against a fixed whitelist — never
|
|
200
212
|
* joined into a filesystem path — so no request can traverse outside it.
|
|
201
213
|
*/
|
|
202
214
|
function registerUiAssets(server) {
|
|
@@ -219,8 +231,10 @@ function registerUiAssets(server) {
|
|
|
219
231
|
/**
|
|
220
232
|
* Registers the API docs: `GET /api/openapi.json` returns the document core
|
|
221
233
|
* builds from the registered routes (`deps.getOpenApiDocument`), and
|
|
222
|
-
* `GET /docs` serves the page that renders it with Scalar
|
|
223
|
-
*
|
|
234
|
+
* `GET /docs` serves the page that renders it with Scalar and
|
|
235
|
+
* `GET /docs/swagger` the same document in Swagger UI;
|
|
236
|
+
* `GET /api/postman.json` returns the Postman collection core builds
|
|
237
|
+
* (`deps.getPostmanCollection`). The pages use relative URLs, so it works under whatever base path the dashboard is
|
|
224
238
|
* mounted on.
|
|
225
239
|
*/
|
|
226
240
|
function registerOpenApiRoutes(server, deps) {
|
|
@@ -229,9 +243,17 @@ function registerOpenApiRoutes(server, deps) {
|
|
|
229
243
|
reply.header("Cache-Control", "no-store");
|
|
230
244
|
return deps.getOpenApiDocument();
|
|
231
245
|
});
|
|
246
|
+
server.get("/api/postman.json", async (_request, reply) => {
|
|
247
|
+
if (!deps.getPostmanCollection) return reply.code(503).header("Cache-Control", "no-store").send({ error: "The Postman collection is not available: the host did not provide a generator." });
|
|
248
|
+
reply.header("Cache-Control", "no-store");
|
|
249
|
+
return deps.getPostmanCollection();
|
|
250
|
+
});
|
|
232
251
|
server.get("/docs", (_request, reply) => {
|
|
233
252
|
sendFile(reply, node_path.default.join(resolveUiRoot(), "docs.html"), "text/html; charset=utf-8");
|
|
234
253
|
});
|
|
254
|
+
server.get("/docs/swagger", (_request, reply) => {
|
|
255
|
+
sendFile(reply, node_path.default.join(resolveUiRoot(), "docs-swagger.html"), "text/html; charset=utf-8");
|
|
256
|
+
});
|
|
235
257
|
}
|
|
236
258
|
|
|
237
259
|
//#endregion
|
|
@@ -318,4 +340,4 @@ function mountDevtoolsRoutes(server, deps) {
|
|
|
318
340
|
|
|
319
341
|
//#endregion
|
|
320
342
|
exports.mountDevtoolsRoutes = mountDevtoolsRoutes;
|
|
321
|
-
//# sourceMappingURL=server-
|
|
343
|
+
//# sourceMappingURL=server-6mVWfWkG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-6mVWfWkG.cjs","names":["path","path","path"],"sources":["../../../../../../devtools/src/server/background-routes.ts","../../../../../../devtools/src/server/explain-route.ts","../../../../../../devtools/src/server/guard.ts","../../../../../../devtools/src/server/log-routes.ts","../../../../../../devtools/src/server/mail-routes.ts","../../../../../../devtools/src/ui-root.ts","../../../../../../devtools/src/server/ui-assets.ts","../../../../../../devtools/src/server/openapi-routes.ts","../../../../../../devtools/src/server/requests-routes.ts","../../../../../../devtools/src/server/route-routes.ts","../../../../../../devtools/src/server/stream-route.ts","../../../../../../devtools/src/server/index.ts"],"sourcesContent":["import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/** Registers the route that returns work recorded outside any request. */\nexport function registerBackgroundRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n server.get(\"/api/background\", async () => deps.collector.getBackground());\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/**\n * The value the logger's redaction substitutes for a censored leaf\n * (`logger/src/redact/redact.ts`, `DEFAULT_CENSOR`). Not exported from\n * `@warlock.js/logger`, so matched by literal here.\n */\nconst REDACTED_PLACEHOLDER = \"[REDACTED]\";\n\nfunction isExplainableSql(sql: string | undefined): boolean {\n return /^\\s*(select|with)\\b/i.test(sql ?? \"\");\n}\n\n/** Registers the EXPLAIN route: Postgres `SELECT`/`WITH` queries only. */\nexport function registerExplainRoute(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.post<{ Params: { requestId: string; queryId: string } }>(\n \"/api/requests/:requestId/queries/:queryId/explain\",\n async (request, reply) => {\n const found = deps.collector.getRequest(request.params.requestId);\n const query = found?.queries.find((item) => item.id === request.params.queryId);\n\n if (!query) {\n reply.code(404).send();\n return;\n }\n\n if (query.driver !== \"postgres\" || !isExplainableSql(query.sql) || !deps.explain) {\n reply.code(400).send({ error: \"Only Postgres SELECT or WITH queries can be explained\" });\n return;\n }\n\n if (query.bindings?.some((binding) => binding === REDACTED_PLACEHOLDER)) {\n reply.code(400).send({ error: \"bindings redacted\" });\n return;\n }\n\n try {\n const plan = await deps.explain(query);\n return { plan };\n } catch (error) {\n reply.code(500).send({ error: error instanceof Error ? error.message : String(error) });\n }\n },\n );\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\nconst LOOPBACK_ADDRESSES = new Set([\"127.0.0.1\", \"::1\", \"::ffff:127.0.0.1\"]);\n\n/**\n * Whether `address` is a loopback address. Deliberately reads\n * `request.socket.remoteAddress` rather than `request.ip`, which honours\n * `X-Forwarded-For` when the app trusts a proxy — a header any client can\n * set.\n */\nfunction isLoopbackAddress(address: string | undefined): boolean {\n return address !== undefined && LOOPBACK_ADDRESSES.has(address);\n}\n\n/**\n * Registers the dev-only, loopback-only guard as an `onRequest` hook on\n * `server`. Callers must register this inside an encapsulated Fastify\n * context (a plugin/prefix) so the hook never reaches routes outside the\n * dashboard.\n */\nexport function registerDevtoolsGuard(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n server.addHook(\"onRequest\", async (request: FastifyRequest, reply: FastifyReply) => {\n if (!deps.isDevelopment() || !isLoopbackAddress(request.socket.remoteAddress)) {\n // Returning the reply is what stops the lifecycle in an async hook;\n // without it Fastify still runs the handler after the 404 is sent.\n return reply.code(404).send();\n }\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { DevtoolsLogEntry } from \"../types\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\ntype LogsQuery = { level?: DevtoolsLogEntry[\"level\"]; module?: string };\n\n/** Registers the log listing route, filterable by `level` and `module`. */\nexport function registerLogRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get<{ Querystring: LogsQuery }>(\"/api/logs\", async (request) =>\n deps.collector.listLogs({ level: request.query.level, module: request.query.module }),\n );\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\nconst MAIL_HTML_CSP =\n \"sandbox; default-src 'none'; img-src data: https: http:; style-src 'unsafe-inline'\";\n\n/** Registers the mailbox list, single-mail detail, and mail HTML routes. */\nexport function registerMailRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get(\"/api/mails\", async () => deps.collector.listMails());\n\n server.get<{ Params: { id: string } }>(\"/api/mails/:id\", async (request, reply) => {\n const mail = deps.collector.getMail(request.params.id);\n\n if (!mail) {\n reply.code(404).send();\n return;\n }\n\n const { html, ...rest } = mail;\n return rest;\n });\n\n server.get<{ Params: { id: string } }>(\"/api/mails/:id/html\", async (request, reply) => {\n const mail = deps.collector.getMail(request.params.id);\n\n if (!mail || !mail.html) {\n reply.code(404).send();\n return;\n }\n\n reply\n .header(\"Content-Security-Policy\", MAIL_HTML_CSP)\n .header(\"X-Content-Type-Options\", \"nosniff\")\n .header(\"Content-Type\", \"text/html; charset=utf-8\")\n .send(mail.html);\n });\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nlet cachedUiRoot: string | undefined;\n\n/** Whether `dir` is this package's root: it has `ui/index.html` beside a `package.json` named `@warlock.js/devtools`. */\nfunction isPackageRoot(dir: string): boolean {\n const indexHtml = path.join(dir, \"ui\", \"index.html\");\n const packageJson = path.join(dir, \"package.json\");\n\n if (!existsSync(indexHtml) || !existsSync(packageJson)) {\n return false;\n }\n\n try {\n const parsed = JSON.parse(readFileSync(packageJson, \"utf8\")) as { name?: string };\n return parsed.name === \"@warlock.js/devtools\";\n } catch {\n return false;\n }\n}\n\n/**\n * Locate this package's `ui/` directory by walking up from the current\n * module's directory. Works from `src/` in development and from the built\n * `esm/`/`cjs/` output, since both sit beside `ui/` and `package.json` at\n * the package root.\n */\nexport function resolveUiRoot(): string {\n if (cachedUiRoot) {\n return cachedUiRoot;\n }\n\n let dir = path.dirname(fileURLToPath(import.meta.url));\n\n while (true) {\n if (isPackageRoot(dir)) {\n cachedUiRoot = path.join(dir, \"ui\");\n return cachedUiRoot;\n }\n\n const parent = path.dirname(dir);\n if (parent === dir) {\n throw new Error(\n \"Could not locate the devtools UI directory: no ancestor of \" +\n \"this module has a ui/index.html beside a package.json named \" +\n \"@warlock.js/devtools.\",\n );\n }\n\n dir = parent;\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { FastifyInstance, FastifyReply } from \"fastify\";\nimport { resolveUiRoot } from \"../ui-root\";\n\n/**\n * Where an asset's bytes come from: a file in this package's `ui/` folder.\n */\ntype UiAsset = {\n contentType: string;\n file: () => string;\n};\n\nconst uiFile = (name: string) => () => path.join(resolveUiRoot(), name);\n\n/**\n * The only assets that can be requested. The request's asset name is looked\n * up here and never joined into a filesystem path.\n */\nconst UI_ASSETS: Record<string, UiAsset> = {\n \"app.js\": { contentType: \"text/javascript; charset=utf-8\", file: uiFile(\"app.js\") },\n \"app.css\": { contentType: \"text/css; charset=utf-8\", file: uiFile(\"app.css\") },\n \"scalar.js\": {\n contentType: \"text/javascript; charset=utf-8\",\n file: uiFile(\"vendor/scalar/standalone.js\"),\n },\n \"swagger-ui-bundle.js\": {\n contentType: \"text/javascript; charset=utf-8\",\n file: uiFile(\"vendor/swagger-ui/swagger-ui-bundle.js\"),\n },\n \"swagger-ui.css\": {\n contentType: \"text/css; charset=utf-8\",\n file: uiFile(\"vendor/swagger-ui/swagger-ui.css\"),\n },\n \"docs-swagger.js\": {\n contentType: \"text/javascript; charset=utf-8\",\n file: uiFile(\"docs-swagger.js\"),\n },\n};\n\n/** Sends `file` with `contentType` and no caching. */\nexport function sendFile(reply: FastifyReply, file: string, contentType: string): void {\n reply\n .header(\"Cache-Control\", \"no-store\")\n .header(\"Content-Type\", contentType)\n .send(readFileSync(file));\n}\n\n/**\n * Serves the static dashboard: `index.html` at the dashboard root and the\n * whitelisted assets (`app.js`, `app.css`, the vendored Scalar bundle as\n * `scalar.js`, and the vendored Swagger UI files plus their init script). The asset name is matched against a fixed whitelist — never\n * joined into a filesystem path — so no request can traverse outside it.\n */\nexport function registerUiAssets(server: FastifyInstance): void {\n const serveIndex = (_request: unknown, reply: FastifyReply): void => {\n sendFile(reply, path.join(resolveUiRoot(), \"index.html\"), \"text/html; charset=utf-8\");\n };\n\n server.get(\"/\", serveIndex);\n\n server.get<{ Params: { name: string } }>(\"/assets/:name\", (request, reply) => {\n const asset = Object.hasOwn(UI_ASSETS, request.params.name)\n ? UI_ASSETS[request.params.name]\n : undefined;\n\n if (!asset) {\n reply.code(404).header(\"Cache-Control\", \"no-store\").send();\n return;\n }\n\n sendFile(reply, asset.file(), asset.contentType);\n });\n}\n","import path from \"node:path\";\nimport type { FastifyInstance } from \"fastify\";\nimport { resolveUiRoot } from \"../ui-root\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\nimport { sendFile } from \"./ui-assets\";\n\n/**\n * Registers the API docs: `GET /api/openapi.json` returns the document core\n * builds from the registered routes (`deps.getOpenApiDocument`), and\n * `GET /docs` serves the page that renders it with Scalar and\n * `GET /docs/swagger` the same document in Swagger UI;\n * `GET /api/postman.json` returns the Postman collection core builds\n * (`deps.getPostmanCollection`). The pages use relative URLs, so it works under whatever base path the dashboard is\n * mounted on.\n */\nexport function registerOpenApiRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n server.get(\"/api/openapi.json\", async (_request, reply) => {\n if (!deps.getOpenApiDocument) {\n return reply.code(503).header(\"Cache-Control\", \"no-store\").send({\n error: \"The OpenAPI document is not available: the host did not provide a generator.\",\n });\n }\n\n reply.header(\"Cache-Control\", \"no-store\");\n\n return deps.getOpenApiDocument();\n });\n\n server.get(\"/api/postman.json\", async (_request, reply) => {\n if (!deps.getPostmanCollection) {\n return reply.code(503).header(\"Cache-Control\", \"no-store\").send({\n error: \"The Postman collection is not available: the host did not provide a generator.\",\n });\n }\n\n reply.header(\"Cache-Control\", \"no-store\");\n\n return deps.getPostmanCollection();\n });\n\n server.get(\"/docs\", (_request, reply) => {\n sendFile(reply, path.join(resolveUiRoot(), \"docs.html\"), \"text/html; charset=utf-8\");\n });\n\n server.get(\"/docs/swagger\", (_request, reply) => {\n sendFile(reply, path.join(resolveUiRoot(), \"docs-swagger.html\"), \"text/html; charset=utf-8\");\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/** Registers the request list, single-request detail, and clear routes. */\nexport function registerRequestsRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n server.get(\"/api/requests\", async () => deps.collector.listRequests());\n\n server.get<{ Params: { id: string } }>(\"/api/requests/:id\", async (request, reply) => {\n const found = deps.collector.getRequest(request.params.id);\n\n if (!found) {\n reply.code(404).send();\n return;\n }\n\n return found;\n });\n\n server.delete(\"/api/requests\", async (_request, reply) => {\n deps.collector.clear();\n reply.code(204).send();\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/** Registers the route map, sourced from core's router via `deps.listRoutes`. */\nexport function registerRouteRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get(\"/api/routes\", async () => (deps.listRoutes ? deps.listRoutes() : []));\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\nconst PING_INTERVAL_MS = 15_000;\n\n/**\n * Registers the SSE stream: one `event: <type>\\ndata: <json>\\n\\n` frame per\n * collector event, plus a `: ping` comment every 15s to keep intermediaries\n * from closing an idle connection. The reply is hijacked so Fastify never\n * tries to serialize or close the response itself.\n */\nexport function registerStreamRoute(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.get(\"/api/stream\", async (request, reply) => {\n reply.hijack();\n const res = reply.raw;\n\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-store\",\n Connection: \"keep-alive\",\n });\n\n const dispose = deps.collector.subscribe((event) => {\n res.write(`event: ${event.type}\\ndata: ${JSON.stringify(event.data)}\\n\\n`);\n });\n\n const pingTimer = setInterval(() => res.write(\": ping\\n\\n\"), PING_INTERVAL_MS);\n pingTimer.unref();\n\n request.raw.on(\"close\", () => {\n clearInterval(pingTimer);\n dispose();\n });\n });\n}\n","import type { FastifyError, FastifyInstance } from \"fastify\";\nimport { registerBackgroundRoutes } from \"./background-routes\";\nimport { registerExplainRoute } from \"./explain-route\";\nimport { registerDevtoolsGuard } from \"./guard\";\nimport { registerLogRoutes } from \"./log-routes\";\nimport { registerMailRoutes } from \"./mail-routes\";\nimport { registerOpenApiRoutes } from \"./openapi-routes\";\nimport { registerRequestsRoutes } from \"./requests-routes\";\nimport { registerRouteRoutes } from \"./route-routes\";\nimport { registerStreamRoute } from \"./stream-route\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\nimport { registerUiAssets } from \"./ui-assets\";\n\nexport type { DevtoolsRouteRow, MountDevtoolsRoutesDeps } from \"./types\";\n\n/**\n * Mounts the devtools dashboard and its API under `deps.options.path` on\n * `server`. Every route is registered inside a single encapsulated Fastify\n * context so the dev-only, loopback-only guard never reaches the app's\n * other routes.\n */\nexport function mountDevtoolsRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n server.register(\n async (instance) => {\n registerDevtoolsGuard(instance, deps);\n\n instance.setErrorHandler((error: FastifyError, _request, reply) => {\n reply.code(error.statusCode ?? 500).send({ error: error.message });\n });\n\n registerUiAssets(instance);\n registerRequestsRoutes(instance, deps);\n registerBackgroundRoutes(instance, deps);\n registerMailRoutes(instance, deps);\n registerLogRoutes(instance, deps);\n registerRouteRoutes(instance, deps);\n registerOpenApiRoutes(instance, deps);\n registerExplainRoute(instance, deps);\n registerStreamRoute(instance, deps);\n },\n { prefix: deps.options.path },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAgB,yBACd,QACA,MACM;CACN,OAAO,IAAI,mBAAmB,YAAY,KAAK,UAAU,cAAc,CAAC;AAC1E;;;;;;;;;ACDA,MAAM,uBAAuB;AAE7B,SAAS,iBAAiB,KAAkC;CAC1D,OAAO,uBAAuB,KAAK,OAAO,EAAE;AAC9C;;AAGA,SAAgB,qBAAqB,QAAyB,MAAqC;CACjG,OAAO,KACL,qDACA,OAAO,SAAS,UAAU;EAExB,MAAM,QADQ,KAAK,UAAU,WAAW,QAAQ,OAAO,SACrC,CAAC,EAAE,QAAQ,MAAM,SAAS,KAAK,OAAO,QAAQ,OAAO,OAAO;EAE9E,IAAI,CAAC,OAAO;GACV,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK;GACrB;EACF;EAEA,IAAI,MAAM,WAAW,cAAc,CAAC,iBAAiB,MAAM,GAAG,KAAK,CAAC,KAAK,SAAS;GAChF,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,EAAE,OAAO,wDAAwD,CAAC;GACvF;EACF;EAEA,IAAI,MAAM,UAAU,MAAM,YAAY,YAAY,oBAAoB,GAAG;GACvE,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,EAAE,OAAO,oBAAoB,CAAC;GACnD;EACF;EAEA,IAAI;GAEF,OAAO,EAAE,YADU,KAAK,QAAQ,KAAK,EACvB;EAChB,SAAS,OAAO;GACd,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;EACxF;CACF,CACF;AACF;;;;AC1CA,MAAM,qBAAqB,IAAI,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AAQ,CAAC;EACnE,CAAC;EAED,iBAAiB,QAAQ;EACzB,uBAAuB,UAAU,IAAI;EACrC,yBAAyB,UAAU,IAAI;EACvC,mBAAmB,UAAU,IAAI;EACjC,kBAAkB,UAAU,IAAI;EAChC,oBAAoB,UAAU,IAAI;EAClC,sBAAsB,UAAU,IAAI;EACpC,qBAAqB,UAAU,IAAI;EACnC,oBAAoB,UAAU,IAAI;CACpC,GACA,EAAE,QAAQ,KAAK,QAAQ,KAAK,CAC9B;AACF"}
|
|
@@ -52,13 +52,15 @@ function devtoolsConnector(options = {}) {
|
|
|
52
52
|
await attachSource(log, "mail", () => attachMailSource(collector));
|
|
53
53
|
await attachSource(log, "log", () => attachLogSource(collector));
|
|
54
54
|
const { mountDevtoolsRoutes } = await import("./server/index.mjs");
|
|
55
|
+
const postmanBuilder = await findPostmanBuilder();
|
|
55
56
|
mountDevtoolsRoutes(getHttpServer(), {
|
|
56
57
|
collector,
|
|
57
58
|
options: resolved,
|
|
58
59
|
isDevelopment: () => Application.runtimeStrategy === "development",
|
|
59
60
|
explain: (query) => explainQuery(query),
|
|
60
61
|
listRoutes: () => listRoutes(),
|
|
61
|
-
getOpenApiDocument: () => getOpenApiDocument()
|
|
62
|
+
getOpenApiDocument: () => getOpenApiDocument(),
|
|
63
|
+
getPostmanCollection: postmanBuilder ? async () => unwrapCollection(await postmanBuilder()) : void 0
|
|
62
64
|
});
|
|
63
65
|
disposers.push(collector.subscribe((event) => {
|
|
64
66
|
if (event.type !== "request" || event.data.warningCount === 0) return;
|
|
@@ -117,6 +119,28 @@ async function getOpenApiDocument() {
|
|
|
117
119
|
const { document } = await getDevelopmentOpenApiDocument();
|
|
118
120
|
return document;
|
|
119
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.
|
|
124
|
+
* Older cores do not export it; the route then answers 503. The lookup is
|
|
125
|
+
* guarded because a namespace without the export may throw on access. Core is
|
|
126
|
+
* imported lazily, like the OpenAPI document above.
|
|
127
|
+
*/
|
|
128
|
+
async function findPostmanBuilder() {
|
|
129
|
+
try {
|
|
130
|
+
const build = (await import("@warlock.js/core")).getDevelopmentPostmanCollection;
|
|
131
|
+
return typeof build === "function" ? build : void 0;
|
|
132
|
+
} catch {
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Core may return the collection itself or wrap it in `{ collection, warnings }`,
|
|
138
|
+
* like the OpenAPI generator's `{ document, warnings }`.
|
|
139
|
+
*/
|
|
140
|
+
function unwrapCollection(result) {
|
|
141
|
+
if (result && typeof result === "object" && "collection" in result) return result.collection;
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
120
144
|
|
|
121
145
|
//#endregion
|
|
122
146
|
export { devtoolsConnector };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devtools-connector.mjs","names":[],"sources":["../../../../../../devtools/src/devtools-connector.ts"],"sourcesContent":["/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport type { DevtoolsRouteRow } from \"./server\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Refuses to run outside development: `boot()` checks\n * `Application.runtimeStrategy` and, when it isn't `\"development\"`, logs one\n * warning and returns without mounting a route or subscribing to anything.\n * In development it attaches every source (tracing, queries, cache, mail,\n * logs), then mounts the dashboard's routes on the HTTP server — before it\n * starts listening, the only point in the boot sequence where mounting is\n * possible (see `queue/src/dashboard-boot.ts` for the same constraint).\n *\n * Apps don't call this: `warlock dev` registers it automatically when the\n * package is installed (`warlock add devtools`). Keep it OUT of\n * `warlock.config.ts` — devtools is a dev dependency, so a production\n * install doesn't have it and a config import of it would fail there.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const { Application, getHttpServer } = await import(\"@warlock.js/core\");\n const { log } = await import(\"@warlock.js/logger\");\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development; it is not mounted\",\n );\n return;\n }\n\n const resolved = resolveDevtoolsOptions(options);\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n options: resolved,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n for (const dispose of disposers.splice(0)) dispose();\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,MAAa,8BAA8B;;;;;;;;;;;;;;;;;AAqB3C,SAAgB,kBAAkB,UAAoC,CAAC,GAAc;CACnF,IAAI,SAAS;CACb,MAAM,YAAgC,CAAC;CAEvC,MAAM,YAAuB;EAC3B,MAAM;EACN;EAGA,gBAAgB;EAChB,gBAAgB;EAChB,MAAM,OAAO;GACX,MAAM,EAAE,aAAa,kBAAkB,MAAM,OAAO;GACpD,MAAM,EAAE,QAAQ,MAAM,OAAO;GAE7B,IAAI,YAAY,oBAAoB,eAAe;IACjD,IAAI,KACF,YACA,YACA,kEACF;IACA;GACF;GAEA,MAAM,WAAW,uBAAuB,OAAO;GAC/C,MAAM,YAAY,gBAAgB,QAAQ;GAE1C,MAAM,aAAa,KAAK,iBAAiB,oBAAoB,WAAW,QAAQ,CAAC;GACjF,MAAM,aAAa,KAAK,eAAe,kBAAkB,SAAS,CAAC;GACnE,MAAM,aAAa,KAAK,eAAe,kBAAkB,SAAS,CAAC;GACnE,MAAM,aAAa,KAAK,cAAc,iBAAiB,SAAS,CAAC;GACjE,MAAM,aAAa,KAAK,aAAa,gBAAgB,SAAS,CAAC;GAE/D,MAAM,EAAE,wBAAwB,MAAM,OAAO;GAE7C,oBAAoB,cAAc,GAAG;IACnC;IACA,SAAS;IACT,qBAAqB,YAAY,oBAAoB;IACrD,UAAU,UAAU,aAAa,KAAK;IACtC,kBAAkB,WAAW;IAC7B,0BAA0B,mBAAmB;GAC/C,CAAC;GAKD,UAAU,KACR,UAAU,WAAW,UAAU;IAC7B,IAAI,MAAM,SAAS,aAAa,MA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AAE;AACJ;;;;;;AAOA,eAAe,qBAAsC;CACnD,MAAM,EAAE,kCAAkC,MAAM,OAAO;CACvD,MAAM,EAAE,aAAa,MAAM,8BAA8B;CAEzD,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"devtools-connector.mjs","names":[],"sources":["../../../../../../devtools/src/devtools-connector.ts"],"sourcesContent":["/**\n * The devtools connector for `warlock.config.ts > connectors`.\n *\n * Deliberately a plain object with TYPE-ONLY imports from core: the config\n * file that constructs it must not drag core's runtime graph in at\n * config-load time. Core is imported lazily inside `boot()`, where the app\n * has already loaded it — see `queue/src/queue-connector.ts`, the pattern\n * this mirrors.\n */\nimport type { Connector, ConnectorLifecyclePhase } from \"@warlock.js/core\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport type { DevtoolsRouteRow } from \"./server\";\nimport { attachCacheSource } from \"./sources/cache-source\";\nimport { attachLogSource } from \"./sources/log-source\";\nimport { attachMailSource } from \"./sources/mail-source\";\nimport { attachQuerySource } from \"./sources/query-source\";\nimport { attachTracingSource } from \"./sources/tracing-source\";\nimport type { DevtoolsDisposer, DevtoolsOptions, DevtoolsQuery } from \"./types\";\n\n/**\n * Boots after the queue connector (priority 11), which is the last\n * built-in/framework connector to claim a priority; devtools has nothing\n * that depends on it, so it simply goes last.\n */\nexport const DEVTOOLS_CONNECTOR_PRIORITY = 12;\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Refuses to run outside development: `boot()` checks\n * `Application.runtimeStrategy` and, when it isn't `\"development\"`, logs one\n * warning and returns without mounting a route or subscribing to anything.\n * In development it attaches every source (tracing, queries, cache, mail,\n * logs), then mounts the dashboard's routes on the HTTP server — before it\n * starts listening, the only point in the boot sequence where mounting is\n * possible (see `queue/src/dashboard-boot.ts` for the same constraint).\n *\n * Apps don't call this: `warlock dev` registers it automatically when the\n * package is installed (`warlock add devtools`). Keep it OUT of\n * `warlock.config.ts` — devtools is a dev dependency, so a production\n * install doesn't have it and a config import of it would fail there.\n */\nexport function devtoolsConnector(options: DevtoolsConnectorOptions = {}): Connector {\n let active = false;\n const disposers: DevtoolsDisposer[] = [];\n\n const connector: Connector = {\n name: \"devtools\",\n priority: DEVTOOLS_CONNECTOR_PRIORITY,\n // Core's `ConnectorLifecyclePhase.Late`; spelled out so this module stays\n // free of a runtime import of core.\n lifecyclePhase: \"late\" as ConnectorLifecyclePhase,\n isActive: () => active,\n async boot() {\n const { Application, getHttpServer } = await import(\"@warlock.js/core\");\n const { log } = await import(\"@warlock.js/logger\");\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development; it is not mounted\",\n );\n return;\n }\n\n const resolved = resolveDevtoolsOptions(options);\n const collector = createCollector(resolved);\n\n await attachSource(log, \"tracing\", () => attachTracingSource(collector, resolved));\n await attachSource(log, \"query\", () => attachQuerySource(collector));\n await attachSource(log, \"cache\", () => attachCacheSource(collector));\n await attachSource(log, \"mail\", () => attachMailSource(collector));\n await attachSource(log, \"log\", () => attachLogSource(collector));\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n const postmanBuilder = await findPostmanBuilder();\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n options: resolved,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n explain: (query) => explainQuery(query),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: () => getOpenApiDocument(),\n getPostmanCollection: postmanBuilder\n ? async () => unwrapCollection(await postmanBuilder())\n : undefined,\n });\n\n // An N+1 is worth a terminal line, not just a badge the developer has\n // to go looking for: one warning per offending query shape, with the\n // line that issued it.\n disposers.push(\n collector.subscribe((event) => {\n if (event.type !== \"request\" || event.data.warningCount === 0) return;\n\n for (const warning of collector.getRequest(event.data.id)?.warnings ?? []) {\n const where = warning.caller ? ` — ${warning.caller.file}:${warning.caller.line}` : \"\";\n\n log.warn(\n \"devtools\",\n \"n+1\",\n `${warning.message}${where} (${event.data.method} ${event.data.path})`,\n );\n }\n }),\n );\n\n active = true;\n\n log.info(\"devtools\", \"ready\", `devtools ready at ${resolved.path}`);\n },\n async start() {},\n async restart() {\n await connector.shutdown();\n await connector.start();\n },\n async shutdown() {\n for (const dispose of disposers.splice(0)) dispose();\n active = false;\n },\n shouldRestart: () => false,\n };\n\n /** Attaches one source, logging and continuing when it fails to attach. */\n async function attachSource(\n logger: { warn: (module: string, action: string, message: string) => unknown },\n name: string,\n attach: () => Promise<DevtoolsDisposer>,\n ): Promise<void> {\n try {\n disposers.push(await attach());\n } catch (error) {\n logger.warn(\n \"devtools\",\n \"source-failed\",\n `devtools' ${name} source failed to attach: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n return connector;\n}\n\n/** Runs `EXPLAIN (FORMAT JSON)` for a stored Postgres query on its own connection. */\nasync function explainQuery(query: DevtoolsQuery): Promise<unknown> {\n const { dataSourceRegistry } = await import(\"@warlock.js/cascade\");\n const dataSource = dataSourceRegistry.get(query.connection);\n const { rows } = await dataSource.raw(`EXPLAIN (FORMAT JSON) ${query.sql}`, query.bindings);\n\n return rows;\n}\n\n/** Lists every registered HTTP route — the same source `warlock routes --json` reads. */\nasync function listRoutes(): Promise<DevtoolsRouteRow[]> {\n const { router } = await import(\"@warlock.js/core\");\n\n return router.list().map((route) => ({\n method: route.method.toUpperCase(),\n path: route.path,\n name: route.name,\n middleware: route.middleware?.map((middleware) => middleware.name || \"anonymous\"),\n }));\n}\n\n/**\n * Builds the OpenAPI 3.1 document from the routes registered in this process —\n * the same generator behind `warlock generate.openapi`. Core is imported\n * lazily so this module stays free of a load-time dependency on it.\n */\nasync function getOpenApiDocument(): Promise<object> {\n const { getDevelopmentOpenApiDocument } = await import(\"@warlock.js/core\");\n const { document } = await getDevelopmentOpenApiDocument();\n\n return document;\n}\n\ntype PostmanBuilder = () => Promise<unknown>;\n\n/**\n * Looks up core's Postman collection builder, `getDevelopmentPostmanCollection`.\n * Older cores do not export it; the route then answers 503. The lookup is\n * guarded because a namespace without the export may throw on access. Core is\n * imported lazily, like the OpenAPI document above.\n */\nasync function findPostmanBuilder(): Promise<PostmanBuilder | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const build = core.getDevelopmentPostmanCollection;\n\n return typeof build === \"function\" ? (build as PostmanBuilder) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Core may return the collection itself or wrap it in `{ collection, warnings }`,\n * like the OpenAPI generator's `{ document, warnings }`.\n */\nfunction unwrapCollection(result: unknown): object {\n if (result && typeof result === \"object\" && \"collection\" in result) {\n return (result as { collection: object }).collection;\n }\n\n return result as object;\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,MAAa,8BAA8B;;;;;;;;;;;;;;;;;AAqB3C,SAAgB,kBAAkB,UAAoC,CAAC,GAAc;CACnF,IAAI,SAAS;CACb,MAAM,YAAgC,CAAC;CAEvC,MAAM,YAAuB;EAC3B,MAAM;EACN;EAGA,gBAAgB;EAChB,gBAAgB;EAChB,MAAM,OAAO;GACX,MAAM,EAAE,aAAa,kBAAkB,MAAM,OAAO;GACpD,MAAM,EAAE,QAAQ,MAAM,OAAO;GAE7B,IAAI,YAAY,oBAAoB,eAAe;IACjD,IAAI,KACF,YACA,YACA,kEACF;IACA;GACF;GAEA,MAAM,WAAW,uBAAuB,OAAO;GAC/C,MAAM,YAAY,gBAAgB,QAAQ;GAE1C,MAAM,aAAa,KAAK,iBAAiB,oBAAoB,WAAW,QAAQ,CAAC;GACjF,MAAM,aAAa,KAAK,eAAe,kBAAkB,SAAS,CAAC;GACnE,MAAM,aAAa,KAAK,eAAe,kBAAkB,SAAS,CAAC;GACnE,MAAM,aAAa,KAAK,cAAc,iBAAiB,SAAS,CAAC;GACjE,MAAM,aAAa,KAAK,aAAa,gBAAgB,SAAS,CAAC;GAE/D,MAAM,EAAE,wBAAwB,MAAM,OAAO;GAC7C,MAAM,iBAAiB,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C,CAAC,IAAI,yBAAyB,MAAM,OAAO,MAAM,QAAQ;CAE1F,OAAO;AACT;;AAGA,eAAe,aAA0C;CACvD,MAAM,EAAE,WAAW,MAAM,OAAO;CAEhC,OAAO,OAAO,KAAK,CAAC,CAAC,KAAK,WAAW;EACnC,QAAQ,MAAM,OAAO,YAAY;EACjC,MAAM,MAAM;EACZ,MAAM,MAAM;EACZ,YAAY,MAAM,YAAY,KAAK,eAAe,WAAW,QAAQ,WAAW;CAClF,EAAE;AACJ;;;;;;AAOA,eAAe,qBAAsC;CACnD,MAAM,EAAE,kCAAkC,MAAM,OAAO;CACvD,MAAM,EAAE,aAAa,MAAM,8BAA8B;CAEzD,OAAO;AACT;;;;;;;AAUA,eAAe,qBAA0D;CACvE,IAAI;EAEF,MAAM,SAAQ,MAD8B,OAAO,oBACjC,CAAC;EAEnB,OAAO,OAAO,UAAU,aAAc,QAA2B;CACnE,QAAQ;EACN;CACF;AACF;;;;;AAMA,SAAS,iBAAiB,QAAyB;CACjD,IAAI,UAAU,OAAO,WAAW,YAAY,gBAAgB,QAC1D,OAAQ,OAAkC;CAG5C,OAAO;AACT"}
|
|
@@ -6,8 +6,10 @@ import path from "node:path";
|
|
|
6
6
|
/**
|
|
7
7
|
* Registers the API docs: `GET /api/openapi.json` returns the document core
|
|
8
8
|
* builds from the registered routes (`deps.getOpenApiDocument`), and
|
|
9
|
-
* `GET /docs` serves the page that renders it with Scalar
|
|
10
|
-
*
|
|
9
|
+
* `GET /docs` serves the page that renders it with Scalar and
|
|
10
|
+
* `GET /docs/swagger` the same document in Swagger UI;
|
|
11
|
+
* `GET /api/postman.json` returns the Postman collection core builds
|
|
12
|
+
* (`deps.getPostmanCollection`). The pages use relative URLs, so it works under whatever base path the dashboard is
|
|
11
13
|
* mounted on.
|
|
12
14
|
*/
|
|
13
15
|
function registerOpenApiRoutes(server, deps) {
|
|
@@ -16,9 +18,17 @@ function registerOpenApiRoutes(server, deps) {
|
|
|
16
18
|
reply.header("Cache-Control", "no-store");
|
|
17
19
|
return deps.getOpenApiDocument();
|
|
18
20
|
});
|
|
21
|
+
server.get("/api/postman.json", async (_request, reply) => {
|
|
22
|
+
if (!deps.getPostmanCollection) return reply.code(503).header("Cache-Control", "no-store").send({ error: "The Postman collection is not available: the host did not provide a generator." });
|
|
23
|
+
reply.header("Cache-Control", "no-store");
|
|
24
|
+
return deps.getPostmanCollection();
|
|
25
|
+
});
|
|
19
26
|
server.get("/docs", (_request, reply) => {
|
|
20
27
|
sendFile(reply, path.join(resolveUiRoot(), "docs.html"), "text/html; charset=utf-8");
|
|
21
28
|
});
|
|
29
|
+
server.get("/docs/swagger", (_request, reply) => {
|
|
30
|
+
sendFile(reply, path.join(resolveUiRoot(), "docs-swagger.html"), "text/html; charset=utf-8");
|
|
31
|
+
});
|
|
22
32
|
}
|
|
23
33
|
|
|
24
34
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi-routes.mjs","names":[],"sources":["../../../../../../../devtools/src/server/openapi-routes.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { FastifyInstance } from \"fastify\";\nimport { resolveUiRoot } from \"../ui-root\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\nimport { sendFile } from \"./ui-assets\";\n\n/**\n * Registers the API docs: `GET /api/openapi.json` returns the document core\n * builds from the registered routes (`deps.getOpenApiDocument`), and\n * `GET /docs` serves the page that renders it with Scalar.
|
|
1
|
+
{"version":3,"file":"openapi-routes.mjs","names":[],"sources":["../../../../../../../devtools/src/server/openapi-routes.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { FastifyInstance } from \"fastify\";\nimport { resolveUiRoot } from \"../ui-root\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\nimport { sendFile } from \"./ui-assets\";\n\n/**\n * Registers the API docs: `GET /api/openapi.json` returns the document core\n * builds from the registered routes (`deps.getOpenApiDocument`), and\n * `GET /docs` serves the page that renders it with Scalar and\n * `GET /docs/swagger` the same document in Swagger UI;\n * `GET /api/postman.json` returns the Postman collection core builds\n * (`deps.getPostmanCollection`). The pages use relative URLs, so it works under whatever base path the dashboard is\n * mounted on.\n */\nexport function registerOpenApiRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n): void {\n server.get(\"/api/openapi.json\", async (_request, reply) => {\n if (!deps.getOpenApiDocument) {\n return reply.code(503).header(\"Cache-Control\", \"no-store\").send({\n error: \"The OpenAPI document is not available: the host did not provide a generator.\",\n });\n }\n\n reply.header(\"Cache-Control\", \"no-store\");\n\n return deps.getOpenApiDocument();\n });\n\n server.get(\"/api/postman.json\", async (_request, reply) => {\n if (!deps.getPostmanCollection) {\n return reply.code(503).header(\"Cache-Control\", \"no-store\").send({\n error: \"The Postman collection is not available: the host did not provide a generator.\",\n });\n }\n\n reply.header(\"Cache-Control\", \"no-store\");\n\n return deps.getPostmanCollection();\n });\n\n server.get(\"/docs\", (_request, reply) => {\n sendFile(reply, path.join(resolveUiRoot(), \"docs.html\"), \"text/html; charset=utf-8\");\n });\n\n server.get(\"/docs/swagger\", (_request, reply) => {\n sendFile(reply, path.join(resolveUiRoot(), \"docs-swagger.html\"), \"text/html; charset=utf-8\");\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,SAAgB,sBACd,QACA,MACM;CACN,OAAO,IAAI,qBAAqB,OAAO,UAAU,UAAU;EACzD,IAAI,CAAC,KAAK,oBACR,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,OAAO,iBAAiB,UAAU,CAAC,CAAC,KAAK,EAC9D,OAAO,+EACT,CAAC;EAGH,MAAM,OAAO,iBAAiB,UAAU;EAExC,OAAO,KAAK,mBAAmB;CACjC,CAAC;CAED,OAAO,IAAI,qBAAqB,OAAO,UAAU,UAAU;EACzD,IAAI,CAAC,KAAK,sBACR,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,OAAO,iBAAiB,UAAU,CAAC,CAAC,KAAK,EAC9D,OAAO,iFACT,CAAC;EAGH,MAAM,OAAO,iBAAiB,UAAU;EAExC,OAAO,KAAK,qBAAqB;CACnC,CAAC;CAED,OAAO,IAAI,UAAU,UAAU,UAAU;EACvC,SAAS,OAAO,KAAK,KAAK,cAAc,GAAG,WAAW,GAAG,0BAA0B;CACrF,CAAC;CAED,OAAO,IAAI,kBAAkB,UAAU,UAAU;EAC/C,SAAS,OAAO,KAAK,KAAK,cAAc,GAAG,mBAAmB,GAAG,0BAA0B;CAC7F,CAAC;AACH"}
|
package/esm/server/ui-assets.mjs
CHANGED
|
@@ -20,6 +20,18 @@ const UI_ASSETS = {
|
|
|
20
20
|
"scalar.js": {
|
|
21
21
|
contentType: "text/javascript; charset=utf-8",
|
|
22
22
|
file: uiFile("vendor/scalar/standalone.js")
|
|
23
|
+
},
|
|
24
|
+
"swagger-ui-bundle.js": {
|
|
25
|
+
contentType: "text/javascript; charset=utf-8",
|
|
26
|
+
file: uiFile("vendor/swagger-ui/swagger-ui-bundle.js")
|
|
27
|
+
},
|
|
28
|
+
"swagger-ui.css": {
|
|
29
|
+
contentType: "text/css; charset=utf-8",
|
|
30
|
+
file: uiFile("vendor/swagger-ui/swagger-ui.css")
|
|
31
|
+
},
|
|
32
|
+
"docs-swagger.js": {
|
|
33
|
+
contentType: "text/javascript; charset=utf-8",
|
|
34
|
+
file: uiFile("docs-swagger.js")
|
|
23
35
|
}
|
|
24
36
|
};
|
|
25
37
|
/** Sends `file` with `contentType` and no caching. */
|
|
@@ -28,8 +40,8 @@ function sendFile(reply, file, contentType) {
|
|
|
28
40
|
}
|
|
29
41
|
/**
|
|
30
42
|
* Serves the static dashboard: `index.html` at the dashboard root and the
|
|
31
|
-
* whitelisted assets (`app.js`, `app.css`,
|
|
32
|
-
*
|
|
43
|
+
* whitelisted assets (`app.js`, `app.css`, the vendored Scalar bundle as
|
|
44
|
+
* `scalar.js`, and the vendored Swagger UI files plus their init script). The asset name is matched against a fixed whitelist — never
|
|
33
45
|
* joined into a filesystem path — so no request can traverse outside it.
|
|
34
46
|
*/
|
|
35
47
|
function registerUiAssets(server) {
|