@warlock.js/devtools 5.57.0 → 5.58.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.
Files changed (114) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +3 -0
  3. package/cjs/{auth-DzU0gHDG.cjs → auth-DV2GA1A9.cjs} +33 -403
  4. package/cjs/auth-DV2GA1A9.cjs.map +1 -0
  5. package/cjs/{boot-Dy5OqgTM.cjs → boot-CyeHPFtk.cjs} +14 -12
  6. package/cjs/boot-CyeHPFtk.cjs.map +1 -0
  7. package/cjs/{capture-CqIiaznN.cjs → capture-DcyBhdqw.cjs} +3 -3
  8. package/cjs/{capture-CqIiaznN.cjs.map → capture-DcyBhdqw.cjs.map} +1 -1
  9. package/cjs/{cascade-store-pHjKeSFm.cjs → cascade-store-DEGxAFDI.cjs} +141 -4
  10. package/cjs/cascade-store-DEGxAFDI.cjs.map +1 -0
  11. package/cjs/{contracts-CVmplkNb.cjs → contracts-CDuY-ahl.cjs} +6 -2
  12. package/cjs/{contracts-CVmplkNb.cjs.map → contracts-CDuY-ahl.cjs.map} +1 -1
  13. package/cjs/{errors-CyZp5yS-.cjs → errors-DEqdWaqm.cjs} +3 -1
  14. package/cjs/{errors-CyZp5yS-.cjs.map → errors-DEqdWaqm.cjs.map} +1 -1
  15. package/cjs/helpers-7k_Q-abk.cjs +436 -0
  16. package/cjs/helpers-7k_Q-abk.cjs.map +1 -0
  17. package/cjs/{histogram-BaI-PnCv.cjs → histogram-BRV5eHcp.cjs} +2 -2
  18. package/cjs/{histogram-BaI-PnCv.cjs.map → histogram-BRV5eHcp.cjs.map} +1 -1
  19. package/cjs/{http-DCfXQvw-.cjs → http-XNLYU2vS.cjs} +517 -28
  20. package/cjs/http-XNLYU2vS.cjs.map +1 -0
  21. package/cjs/index.cjs +1 -1
  22. package/cjs/{insights-BKtqxdnP.cjs → insights-BBZnUpWO.cjs} +4 -3
  23. package/cjs/{insights-BKtqxdnP.cjs.map → insights-BBZnUpWO.cjs.map} +1 -1
  24. package/cjs/{migrations-w7GMsrQw.cjs → migrations-DTTzCNpR.cjs} +38 -3
  25. package/cjs/migrations-DTTzCNpR.cjs.map +1 -0
  26. package/cjs/{options-CWqFC5__.cjs → options-CHhmQJic.cjs} +16 -4
  27. package/cjs/options-CHhmQJic.cjs.map +1 -0
  28. package/cjs/{panels-Rcmeitu3.cjs → panels-CHd20RK5.cjs} +74 -7
  29. package/cjs/panels-CHd20RK5.cjs.map +1 -0
  30. package/cjs/production/index.cjs +4 -4
  31. package/cjs/{server-ykxsOwob.cjs → server-C8JfggQU.cjs} +5 -4
  32. package/cjs/server-C8JfggQU.cjs.map +1 -0
  33. package/cjs/{src-UPtTCI2j.cjs → src-DjOUdhKc.cjs} +47 -10
  34. package/cjs/src-DjOUdhKc.cjs.map +1 -0
  35. package/cjs/{store-aq207T8v.cjs → store-C06KO_A1.cjs} +2 -2
  36. package/cjs/{stream-route-CJTABkUy.cjs → stream-route-D4k-sJvW.cjs} +70 -9
  37. package/cjs/stream-route-D4k-sJvW.cjs.map +1 -0
  38. package/esm/devtools-connector.d.mts.map +1 -1
  39. package/esm/devtools-connector.mjs +10 -3
  40. package/esm/devtools-connector.mjs.map +1 -1
  41. package/esm/index.d.mts +3 -3
  42. package/esm/panel-errors.mjs +33 -0
  43. package/esm/panel-errors.mjs.map +1 -0
  44. package/esm/panels.mjs +73 -6
  45. package/esm/panels.mjs.map +1 -1
  46. package/esm/production/auth/service.mjs +4 -2
  47. package/esm/production/auth/service.mjs.map +1 -1
  48. package/esm/production/boot.mjs +4 -2
  49. package/esm/production/boot.mjs.map +1 -1
  50. package/esm/production/contracts.d.mts +68 -2
  51. package/esm/production/contracts.d.mts.map +1 -1
  52. package/esm/production/contracts.mjs +5 -1
  53. package/esm/production/contracts.mjs.map +1 -1
  54. package/esm/production/errors.mjs +2 -0
  55. package/esm/production/errors.mjs.map +1 -1
  56. package/esm/production/http/access.mjs +6 -2
  57. package/esm/production/http/access.mjs.map +1 -1
  58. package/esm/production/http/constants.mjs +7 -1
  59. package/esm/production/http/constants.mjs.map +1 -1
  60. package/esm/production/http/context.mjs.map +1 -1
  61. package/esm/production/http/cookie.mjs +23 -2
  62. package/esm/production/http/cookie.mjs.map +1 -1
  63. package/esm/production/http/mount.mjs +25 -3
  64. package/esm/production/http/mount.mjs.map +1 -1
  65. package/esm/production/http/share-session.mjs +114 -0
  66. package/esm/production/http/share-session.mjs.map +1 -0
  67. package/esm/production/http/share.mjs +339 -0
  68. package/esm/production/http/share.mjs.map +1 -0
  69. package/esm/production/index.d.mts +2 -2
  70. package/esm/production/insights/writer.mjs +2 -1
  71. package/esm/production/insights/writer.mjs.map +1 -1
  72. package/esm/production/options.d.mts +5 -0
  73. package/esm/production/options.d.mts.map +1 -1
  74. package/esm/production/options.mjs +14 -2
  75. package/esm/production/options.mjs.map +1 -1
  76. package/esm/production/store/cascade-store.mjs +49 -2
  77. package/esm/production/store/cascade-store.mjs.map +1 -1
  78. package/esm/production/store/mapping.mjs +29 -1
  79. package/esm/production/store/mapping.mjs.map +1 -1
  80. package/esm/production/store/memory-store.mjs +62 -0
  81. package/esm/production/store/memory-store.mjs.map +1 -1
  82. package/esm/production/store/migrations.d.mts +2 -1
  83. package/esm/production/store/migrations.d.mts.map +1 -1
  84. package/esm/production/store/migrations.mjs +5 -2
  85. package/esm/production/store/migrations.mjs.map +1 -1
  86. package/esm/production/store/models/index.mjs +3 -1
  87. package/esm/production/store/models/share.migration.mjs +27 -0
  88. package/esm/production/store/models/share.migration.mjs.map +1 -0
  89. package/esm/production/store/models/share.model.mjs +13 -0
  90. package/esm/production/store/models/share.model.mjs.map +1 -0
  91. package/esm/server/panel-files.mjs +35 -0
  92. package/esm/server/panel-files.mjs.map +1 -0
  93. package/esm/server/panel-routes.mjs +27 -7
  94. package/esm/server/panel-routes.mjs.map +1 -1
  95. package/esm/server/session-routes.mjs +2 -1
  96. package/esm/server/session-routes.mjs.map +1 -1
  97. package/esm/types.d.mts +81 -2
  98. package/esm/types.d.mts.map +1 -1
  99. package/llms-full.txt +34 -4
  100. package/package.json +8 -8
  101. package/skills/SKILL.md +34 -4
  102. package/ui/dashboard/assets/app.css +1 -1
  103. package/ui/dashboard/assets/app.js +16 -16
  104. package/ui/dashboard/build-info.json +7 -7
  105. package/cjs/auth-DzU0gHDG.cjs.map +0 -1
  106. package/cjs/boot-Dy5OqgTM.cjs.map +0 -1
  107. package/cjs/cascade-store-pHjKeSFm.cjs.map +0 -1
  108. package/cjs/http-DCfXQvw-.cjs.map +0 -1
  109. package/cjs/migrations-w7GMsrQw.cjs.map +0 -1
  110. package/cjs/options-CWqFC5__.cjs.map +0 -1
  111. package/cjs/panels-Rcmeitu3.cjs.map +0 -1
  112. package/cjs/server-ykxsOwob.cjs.map +0 -1
  113. package/cjs/src-UPtTCI2j.cjs.map +0 -1
  114. package/cjs/stream-route-CJTABkUy.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"http-DCfXQvw-.cjs","names":["normalizeIp","isIP","ipMatches","DevtoolsApiError","createHash","DevtoolsApiError","ipMatches","createErrorRef","DEVTOOLS_ERROR_MESSAGES","listPanelInfos","createHash"],"sources":["../../../../../../../packages/devtools/src/production/http/access.ts","../../../../../../../packages/devtools/src/production/http/client.ts","../../../../../../../packages/devtools/src/production/http/constants.ts","../../../../../../../packages/devtools/src/production/http/context.ts","../../../../../../../packages/devtools/src/production/http/cookie.ts","../../../../../../../packages/devtools/src/production/http/auth-routes.ts","../../../../../../../packages/devtools/src/production/http/headers.ts","../../../../../../../packages/devtools/src/production/http/mount.ts","../../../../../../../packages/devtools/src/production/http/state.ts"],"sourcesContent":["import type { DevtoolsRouteAccess, DevtoolsRouteAccessRule } from \"./types\";\n\ntype Method = DevtoolsRouteAccessRule[\"method\"];\n\nconst PUBLIC: DevtoolsRouteAccess = { type: \"public\" };\nconst VIEWER: DevtoolsRouteAccess = { type: \"viewer\" };\nconst ADMIN: DevtoolsRouteAccess = { type: \"admin\" };\n\nconst pending = (...stages: Extract<DevtoolsRouteAccess, { type: \"pending\" }>[\"stages\"]) =>\n ({ type: \"pending\", stages }) satisfies DevtoolsRouteAccess;\n\nconst ALL_STEPS = [\"password-change\", \"mfa-enrol\", \"mfa-verify\"] as const;\n\n/**\n * The access table: every production route, its method and who may call it.\n * A route with no entry is `admin` (fail closed). A package panel `<id>`\n * gets `GET /api/<id>` and `GET /api/<id>/*` for viewers and every other\n * method there for admins, audited as `panel.action`; a url ending in `/*`\n * matches every pattern below it.\n */\nexport function productionRouteAccess(panelIds: readonly string[]): DevtoolsRouteAccessRule[] {\n const rule = (\n method: Method,\n url: string,\n access: DevtoolsRouteAccess,\n audit?: DevtoolsRouteAccessRule[\"audit\"],\n ): DevtoolsRouteAccessRule => ({ method, url, access, ...(audit ? { audit } : {}) });\n\n const rules: DevtoolsRouteAccessRule[] = [\n // The shell and its sign-in steps.\n rule(\"GET\", \"/\", PUBLIC),\n rule(\"GET\", \"/assets/:name\", PUBLIC),\n rule(\"GET\", \"/api/auth/session\", PUBLIC),\n rule(\"POST\", \"/api/auth/login\", PUBLIC),\n rule(\"POST\", \"/api/auth/setup\", PUBLIC),\n rule(\"POST\", \"/api/auth/invite/inspect\", PUBLIC),\n rule(\"POST\", \"/api/auth/invite/accept\", PUBLIC),\n rule(\"POST\", \"/api/auth/password\", pending(\"password-change\")),\n rule(\"POST\", \"/api/auth/totp/start\", pending(\"mfa-enrol\")),\n rule(\"POST\", \"/api/auth/totp/confirm\", pending(\"mfa-enrol\")),\n rule(\"POST\", \"/api/auth/passkey/options\", pending(\"mfa-enrol\", \"mfa-verify\")),\n rule(\"POST\", \"/api/auth/passkey/verify\", pending(\"mfa-enrol\", \"mfa-verify\")),\n rule(\"POST\", \"/api/auth/mfa\", pending(\"mfa-verify\")),\n rule(\"POST\", \"/api/auth/logout\", pending(...ALL_STEPS)),\n\n // The signed-in account.\n rule(\"GET\", \"/api/panels\", VIEWER),\n rule(\"GET\", \"/api/account\", VIEWER),\n rule(\"GET\", \"/api/account/sessions\", VIEWER),\n rule(\"DELETE\", \"/api/account/sessions/:id\", VIEWER),\n rule(\"POST\", \"/api/account/password\", VIEWER),\n rule(\"POST\", \"/api/account/totp/start\", VIEWER),\n rule(\"POST\", \"/api/account/totp/confirm\", VIEWER),\n rule(\"DELETE\", \"/api/account/totp\", VIEWER),\n rule(\"POST\", \"/api/account/recovery-codes\", VIEWER),\n rule(\"POST\", \"/api/account/passkey/options\", VIEWER),\n rule(\"POST\", \"/api/account/passkey/verify\", VIEWER),\n rule(\"DELETE\", \"/api/account/passkeys/:id\", VIEWER),\n\n // Administration.\n rule(\"GET\", \"/api/admin/users\", ADMIN),\n rule(\"POST\", \"/api/admin/invites\", ADMIN),\n rule(\"DELETE\", \"/api/admin/invites/:id\", ADMIN),\n rule(\"PATCH\", \"/api/admin/users/:id\", ADMIN),\n rule(\"DELETE\", \"/api/admin/users/:id\", ADMIN),\n rule(\"POST\", \"/api/admin/users/:id/reset-mfa\", ADMIN),\n rule(\"POST\", \"/api/admin/users/:id/sign-out\", ADMIN),\n rule(\"GET\", \"/api/admin/audit\", ADMIN),\n rule(\"POST\", \"/api/admin/disable\", ADMIN),\n\n // Data.\n rule(\"GET\", \"/api/stream\", VIEWER),\n rule(\"GET\", \"/api/instances\", VIEWER),\n rule(\"GET\", \"/api/resources\", VIEWER),\n rule(\"GET\", \"/api/queries/stats\", VIEWER),\n rule(\"GET\", \"/api/routes/stats\", VIEWER),\n rule(\"GET\", \"/api/health\", VIEWER),\n rule(\"GET\", \"/api/errors\", VIEWER),\n rule(\"GET\", \"/api/jobs\", VIEWER),\n rule(\"GET\", \"/api/logs\", VIEWER),\n rule(\"GET\", \"/api/requests\", VIEWER),\n rule(\"GET\", \"/api/requests/:id\", VIEWER),\n rule(\"GET\", \"/api/requests/:id/curl\", VIEWER),\n rule(\"DELETE\", \"/api/requests\", ADMIN, \"requests.cleared\"),\n rule(\"POST\", \"/api/queries/:shapeId/explain\", ADMIN, \"explain.run\"),\n rule(\"GET\", \"/api/routes\", VIEWER),\n rule(\"GET\", \"/panels/:id/:name\", VIEWER),\n\n // Tabs that are off unless the project turns them on.\n rule(\"GET\", \"/api/mails\", VIEWER),\n rule(\"GET\", \"/api/mails/:id\", VIEWER),\n rule(\"GET\", \"/api/mails/:id/html\", VIEWER),\n rule(\"GET\", \"/api/ai\", VIEWER),\n rule(\"GET\", \"/api/ai/agent-runs\", VIEWER),\n rule(\"GET\", \"/api/ai/agent-runs/:id\", VIEWER),\n rule(\"GET\", \"/api/ai/runs/:id\", VIEWER),\n rule(\"GET\", \"/api/openapi.json\", VIEWER),\n rule(\"GET\", \"/api/postman.json\", VIEWER),\n rule(\"GET\", \"/docs\", VIEWER),\n rule(\"GET\", \"/docs/swagger\", VIEWER),\n ];\n\n for (const id of panelIds) {\n rules.push(rule(\"GET\", `/api/${id}`, VIEWER), rule(\"GET\", `/api/${id}/*`, VIEWER));\n\n for (const method of [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"] as const) {\n rules.push(\n rule(method, `/api/${id}`, ADMIN, \"panel.action\"),\n rule(method, `/api/${id}/*`, ADMIN, \"panel.action\"),\n );\n }\n }\n\n return rules;\n}\n\n/** Looks routes up by method and URL pattern: exact first, then the longest `/*` prefix. */\nexport function createAccessLookup(\n rules: readonly DevtoolsRouteAccessRule[],\n): (method: string, pattern: string) => DevtoolsRouteAccessRule | undefined {\n const exact = new Map<string, DevtoolsRouteAccessRule>();\n const wildcards: { method: Method; prefix: string; rule: DevtoolsRouteAccessRule }[] = [];\n\n for (const rule of rules) {\n if (rule.url.endsWith(\"/*\")) {\n wildcards.push({ method: rule.method, prefix: rule.url.slice(0, -1), rule });\n } else {\n exact.set(`${rule.method} ${rule.url}`, rule);\n }\n }\n\n wildcards.sort((a, b) => b.prefix.length - a.prefix.length);\n\n return (method, pattern) => {\n // A HEAD request is answered by the GET route.\n const verb = method === \"HEAD\" ? \"GET\" : method;\n const found = exact.get(`${verb} ${pattern}`);\n\n if (found) return found;\n\n return wildcards.find((item) => item.method === verb && pattern.startsWith(item.prefix))?.rule;\n };\n}\n","import { isIP } from \"node:net\";\nimport type { DevtoolsClientInfo, DevtoolsProxyRequest } from \"./types\";\nimport { ipMatches, normalizeIp } from \"./ip\";\n\n/** The first value of a header that may repeat or hold a comma list. */\nfunction firstValue(value: string | string[] | undefined): string | undefined {\n const text = Array.isArray(value) ? value[0] : value;\n const first = text?.split(\",\")[0]?.trim();\n\n return first === undefined || first === \"\" ? undefined : first;\n}\n\n/** The host name of a `Host` value: no port, lower case, brackets of an IPv6 literal kept. */\nfunction hostnameOf(host: string): string {\n const value = host.trim().toLowerCase();\n\n if (value.startsWith(\"[\")) {\n const end = value.indexOf(\"]\");\n\n return end === -1 ? value : value.slice(0, end + 1);\n }\n\n const colon = value.indexOf(\":\");\n\n return colon === -1 ? value : value.slice(0, colon);\n}\n\n/** The client address out of an `X-Forwarded-For` value, walking right to left past trusted hops. */\nfunction forwardedClient(\n header: string | string[] | undefined,\n trusted: readonly string[],\n): string | undefined {\n const text = Array.isArray(header) ? header.join(\",\") : header;\n const hops = (text ?? \"\")\n .split(\",\")\n .map((hop) => normalizeIp(hop.trim().replace(/^\\[|\\]$/g, \"\")))\n .filter((hop) => isIP(hop) !== 0);\n\n for (let index = hops.length - 1; index >= 0; index -= 1) {\n const hop = hops[index];\n\n if (hop !== undefined && !ipMatches(hop, trusted)) return hop;\n }\n\n // Every hop is a trusted proxy: the leftmost is the origin of the chain.\n return hops[0];\n}\n\n/**\n * The client IP, protocol and host. Forwarding headers are read only when the\n * socket peer is a trusted proxy; `X-Forwarded-For` is walked right to left,\n * skipping trusted addresses, and the first untrusted one is the client.\n */\nexport function resolveClient(\n request: DevtoolsProxyRequest,\n trustedProxies: readonly string[],\n): DevtoolsClientInfo {\n const peer = normalizeIp(request.socket.remoteAddress ?? \"\");\n const headers = request.headers;\n let ip = peer;\n let proto = request.socket.encrypted === true ? \"https\" : \"http\";\n let host = firstValue(headers.host) ?? \"\";\n\n if (peer !== \"\" && ipMatches(peer, trustedProxies)) {\n ip = forwardedClient(headers[\"x-forwarded-for\"], trustedProxies) ?? peer;\n\n const forwardedProto = firstValue(headers[\"x-forwarded-proto\"])?.toLowerCase();\n\n if (forwardedProto === \"http\" || forwardedProto === \"https\") proto = forwardedProto;\n\n host = firstValue(headers[\"x-forwarded-host\"]) ?? host;\n }\n\n host = host.toLowerCase();\n\n return { ip, proto, hostname: hostnameOf(host), host };\n}\n","/** The header the dashboard sends the CSRF token in. */\nexport const DEVTOOLS_CSRF_HEADER = \"x-devtools-csrf\";\n\n/** The session cookie name over HTTPS (`__Secure-` makes browsers refuse it over plain HTTP). */\nexport const DEVTOOLS_SESSION_COOKIE = \"__Secure-warlock-devtools\";\n\n/** The session cookie name when `requireHttps` is off (local trials only). */\nexport const DEVTOOLS_SESSION_COOKIE_INSECURE = \"warlock-devtools\";\n","import type { FastifyRequest } from \"fastify\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport type { DevtoolsClientInfo, DevtoolsRouteAccessRule } from \"./types\";\n\n/** What the gate learned about a dashboard request, for the handlers that follow. */\nexport type DevtoolsRequestContext = {\n client: DevtoolsClientInfo;\n meta: DevtoolsRequestMeta;\n /** The access rule the route matched; `undefined` for a route with no entry (treated as admin). */\n rule: DevtoolsRouteAccessRule | undefined;\n /** The route pattern relative to the dashboard path (`/api/requests/:id`). */\n pattern: string;\n /** The session, for every route that is not public. */\n authenticated: DevtoolsAuthenticated | null;\n};\n\nconst contexts = new WeakMap<FastifyRequest, DevtoolsRequestContext>();\n\n/** Stores the context of `request` (the gate calls this). */\nexport function setDevtoolsRequestContext(\n request: FastifyRequest,\n context: DevtoolsRequestContext,\n): void {\n contexts.set(request, context);\n}\n\n/** The context the gate stored for `request`, or `undefined` outside the production dashboard. */\nexport function devtoolsRequestContext(\n request: FastifyRequest,\n): DevtoolsRequestContext | undefined {\n return contexts.get(request);\n}\n","import { DEVTOOLS_SESSION_COOKIE, DEVTOOLS_SESSION_COOKIE_INSECURE } from \"./constants\";\n\n/** The cookie name for the HTTPS mode. */\nexport function sessionCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SESSION_COOKIE : DEVTOOLS_SESSION_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a session token (or a clearing cookie when `token`\n * is `null`). The cookie is a browser-session cookie scoped to the dashboard\n * path, `HttpOnly` and `SameSite=Strict`, with no `Domain`.\n */\nexport function sessionCookie(\n token: string | null,\n options: { path: string; secure: boolean },\n): string {\n const parts = [\n `${sessionCookieName(options.secure)}=${token ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (token === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n\n return parts.join(\"; \");\n}\n\n/** The value of cookie `name` in a `Cookie` header, or `undefined`. */\nexport function readCookie(header: string | undefined, name: string): string | undefined {\n if (!header) return undefined;\n\n for (const pair of header.split(\";\")) {\n const equals = pair.indexOf(\"=\");\n\n if (equals === -1) continue;\n\n if (pair.slice(0, equals).trim() === name) {\n const value = pair.slice(equals + 1).trim();\n\n return value === \"\" ? undefined : value;\n }\n }\n\n return undefined;\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { DevtoolsAuthenticated, DevtoolsAuthStep, DevtoolsRequestMeta } from \"../auth/types\";\nimport type { DevtoolsAuditType, DevtoolsAuthStepResult, DevtoolsRole } from \"../contracts\";\nimport { DevtoolsApiError } from \"../errors\";\nimport { readCookie, sessionCookie, sessionCookieName } from \"./cookie\";\nimport { devtoolsRequestContext } from \"./context\";\nimport type { MountProductionDevtoolsDeps } from \"./types\";\n\nconst MAX_TEXT = 1024;\nconst MAX_EMAIL = 320;\nconst MAX_CODE = 128;\nconst MAX_TOKEN = 512;\nconst ROLES: readonly DevtoolsRole[] = [\"admin\", \"viewer\"];\n\n/** A request body that is a plain JSON object, or `input.invalid`. */\nfunction bodyOf(request: FastifyRequest): Record<string, unknown> {\n const body: unknown = request.body;\n\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return body as Record<string, unknown>;\n}\n\n/** A non-empty string field no longer than `max`, or `input.invalid`. */\nfunction text(body: Record<string, unknown>, key: string, max = MAX_TEXT): string {\n const value = body[key];\n\n if (typeof value !== \"string\" || value === \"\" || value.length > max) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return value;\n}\n\n/** An optional string field; `undefined` when absent, `input.invalid` when present but wrong. */\nfunction optionalText(\n body: Record<string, unknown>,\n key: string,\n max = MAX_TEXT,\n): string | undefined {\n return body[key] === undefined ? undefined : text(body, key, max);\n}\n\nfunction email(body: Record<string, unknown>): string {\n const value = text(body, \"email\", MAX_EMAIL).trim().toLowerCase();\n\n if (!/^[^\\s@]+@[^\\s@]+$/.test(value)) throw new DevtoolsApiError(\"input.invalid\");\n\n return value;\n}\n\nfunction role(body: Record<string, unknown>): DevtoolsRole {\n const value = body.role;\n\n if (typeof value !== \"string\" || !ROLES.includes(value as DevtoolsRole)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return value as DevtoolsRole;\n}\n\nfunction purpose(body: Record<string, unknown>): \"register\" | \"login\" {\n const value = body.purpose;\n\n if (value !== \"register\" && value !== \"login\") throw new DevtoolsApiError(\"input.invalid\");\n\n return value;\n}\n\nfunction idParam(request: FastifyRequest): string {\n const { id } = (request.params ?? {}) as { id?: unknown };\n\n if (typeof id !== \"string\" || id === \"\" || id.length > MAX_CODE) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return id;\n}\n\n/** The `current` password of a request that may have no body (a DELETE). */\nfunction currentOf(request: FastifyRequest): string | undefined {\n return request.body === undefined || request.body === null\n ? undefined\n : optionalText(bodyOf(request), \"current\");\n}\n\n/** What the gate stored, for a route that is never reached without it. */\nfunction contextOf(request: FastifyRequest): {\n meta: DevtoolsRequestMeta;\n auth: DevtoolsAuthenticated;\n} {\n const context = devtoolsRequestContext(request);\n\n if (!context?.authenticated) throw new Error(\"A dashboard route ran without its session.\");\n\n return { meta: context.meta, auth: context.authenticated };\n}\n\nfunction metaOf(request: FastifyRequest): DevtoolsRequestMeta {\n const context = devtoolsRequestContext(request);\n\n if (!context) throw new Error(\"A dashboard route ran without its request context.\");\n\n return context.meta;\n}\n\n/**\n * Registers the sign-in, account and admin routes. All decisions live in the\n * auth service; the handlers read the body, call it and answer. The gate\n * (`mountProductionDevtools`) has already checked the session, role, origin\n * and CSRF token by the time a handler runs.\n */\nexport function registerAuthRoutes(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { auth, store, state, production } = deps;\n const cookieOptions = { path: production.path, secure: production.requireHttps };\n\n /** Sets the new session cookie when the step minted one; answers the step. */\n const answerStep = (\n reply: FastifyReply,\n step: DevtoolsAuthStep,\n recoveryCodes?: string[] | null,\n ): DevtoolsAuthStepResult & { recoveryCodes?: string[] } => {\n if (step.token !== null) reply.header(\"set-cookie\", sessionCookie(step.token, cookieOptions));\n\n return {\n stage: step.stage,\n csrf: step.csrf,\n ...(recoveryCodes ? { recoveryCodes } : {}),\n };\n };\n\n /** The stage and CSRF token of the session in force, for answers that do not change it. */\n const currentStep = (authenticated: DevtoolsAuthenticated): DevtoolsAuthStepResult => ({\n stage: authenticated.stage,\n csrf: auth.csrfToken(authenticated.session),\n });\n\n const clearCookie = (reply: FastifyReply): void => {\n reply.header(\"set-cookie\", sessionCookie(null, cookieOptions));\n };\n\n const requireAdmin = (authenticated: DevtoolsAuthenticated): void => {\n if (authenticated.account.role !== \"admin\" || authenticated.stage !== \"active\") {\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n };\n\n // ---- Public ------------------------------------------------------------\n\n server.get(\"/api/auth/session\", async (request, reply) => {\n const token = readCookie(request.headers.cookie, sessionCookieName(production.requireHttps));\n const authenticated = token === undefined ? null : await auth.authenticate(token);\n\n // A cookie that no longer matches a session is dead weight: clear it.\n if (token !== undefined && authenticated === null) clearCookie(reply);\n\n return auth.sessionView(authenticated);\n });\n\n server.post(\"/api/auth/login\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.login(\n { email: email(body), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/setup\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.setup(\n { token: text(body, \"token\", MAX_TOKEN), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/invite/inspect\", async (request) => {\n const body = bodyOf(request);\n\n return auth.inspectInvite(text(body, \"token\", MAX_TOKEN));\n });\n\n server.post(\"/api/auth/invite/accept\", async (request, reply) => {\n const body = bodyOf(request);\n const step = await auth.acceptInvite(\n { token: text(body, \"token\", MAX_TOKEN), password: text(body, \"password\") },\n metaOf(request),\n );\n\n return answerStep(reply, step);\n });\n\n // ---- Sign-in steps and the account (a session is required) --------------\n\n const changePassword = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const current = optionalText(body, \"current\");\n const step = await auth.changePassword(\n authenticated,\n { ...(current === undefined ? {} : { current }), password: text(body, \"password\") },\n meta,\n );\n\n return answerStep(reply, step);\n };\n\n const startTotp = async (request: FastifyRequest) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.startTotp(authenticated, meta);\n };\n\n const confirmTotp = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const result = await auth.confirmTotp(\n authenticated,\n text(body, \"code\", MAX_CODE),\n meta,\n optionalText(body, \"current\"),\n );\n\n return answerStep(reply, result.step, result.recoveryCodes);\n };\n\n const passkeyOptions = async (request: FastifyRequest) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.passkeyOptions(authenticated, purpose(bodyOf(request)), meta);\n };\n\n const passkeyVerify = async (request: FastifyRequest, reply: FastifyReply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n\n if (body.response === null || typeof body.response !== \"object\") {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const result = await auth.verifyPasskey(\n authenticated,\n purpose(body),\n body.response,\n meta,\n optionalText(body, \"current\"),\n );\n\n if (result.step === null) {\n return {\n ...currentStep(authenticated),\n ...(result.recoveryCodes ? { recoveryCodes: result.recoveryCodes } : {}),\n };\n }\n\n return answerStep(reply, result.step, result.recoveryCodes);\n };\n\n server.post(\"/api/auth/password\", changePassword);\n server.post(\"/api/auth/totp/start\", startTotp);\n server.post(\"/api/auth/totp/confirm\", confirmTotp);\n server.post(\"/api/auth/passkey/options\", passkeyOptions);\n server.post(\"/api/auth/passkey/verify\", passkeyVerify);\n\n server.post(\"/api/auth/mfa\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n const code = optionalText(body, \"code\", MAX_CODE);\n const recoveryCode = optionalText(body, \"recoveryCode\", MAX_CODE);\n\n if ((code === undefined) === (recoveryCode === undefined)) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n const step = await auth.verifySecondFactor(\n authenticated,\n code === undefined ? { recoveryCode: recoveryCode as string } : { code },\n meta,\n );\n\n return answerStep(reply, step);\n });\n\n server.post(\"/api/auth/logout\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.logout(authenticated, meta);\n clearCookie(reply);\n\n return reply.code(204).send();\n });\n\n server.get(\"/api/account\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.accountView(authenticated.account);\n });\n\n server.get(\"/api/account/sessions\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.listSessions(authenticated);\n });\n\n server.delete(\"/api/account/sessions/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.revokeSession(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/account/password\", changePassword);\n server.post(\"/api/account/totp/start\", startTotp);\n server.post(\"/api/account/totp/confirm\", confirmTotp);\n\n server.delete(\"/api/account/totp\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removeTotp(authenticated, meta, currentOf(request));\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/account/recovery-codes\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n // No code: a passkey step-up in this session stands in for it.\n const codes = await auth.regenerateRecoveryCodes(\n authenticated,\n optionalText(bodyOf(request), \"code\", MAX_CODE) ?? \"\",\n meta,\n );\n\n return { codes };\n });\n\n server.post(\"/api/account/passkey/options\", passkeyOptions);\n server.post(\"/api/account/passkey/verify\", passkeyVerify);\n\n server.delete(\"/api/account/passkeys/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removePasskey(authenticated, idParam(request), meta, currentOf(request));\n\n return reply.code(204).send();\n });\n\n // ---- Admin ---------------------------------------------------------------\n\n server.get(\"/api/admin/users\", async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n return auth.listUsers(authenticated);\n });\n\n server.post(\"/api/admin/invites\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n const body = bodyOf(request);\n\n return auth.createInvite(authenticated, { email: email(body), role: role(body) }, meta);\n });\n\n server.delete(\"/api/admin/invites/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.revokeInvite(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.patch(\"/api/admin/users/:id\", async (request) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n return auth.setRole(authenticated, idParam(request), role(bodyOf(request)), meta);\n });\n\n server.delete(\"/api/admin/users/:id\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.removeAccount(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/users/:id/reset-mfa\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.resetSecondFactor(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.post(\"/api/admin/users/:id/sign-out\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n await auth.signOutAccount(authenticated, idParam(request), meta);\n\n return reply.code(204).send();\n });\n\n server.get<{ Querystring: Record<string, string | undefined> }>(\n \"/api/admin/audit\",\n async (request) => {\n const { auth: authenticated } = contextOf(request);\n\n requireAdmin(authenticated);\n\n const query = request.query;\n const types = query.type\n ?.split(\",\")\n .map((type) => type.trim())\n .filter((type) => type !== \"\");\n const before = query.before === undefined ? undefined : Number(query.before);\n const limit = query.limit === undefined ? 100 : Number(query.limit);\n\n if (\n (before !== undefined && !Number.isFinite(before)) ||\n !Number.isInteger(limit) ||\n limit < 1\n ) {\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n return store.audit.list({\n ...(types && types.length > 0 ? { types: types as DevtoolsAuditType[] } : {}),\n ...(query.account ? { accountId: query.account } : {}),\n ...(before === undefined ? {} : { before }),\n limit: Math.min(limit, 500),\n });\n },\n );\n\n server.post(\"/api/admin/disable\", async (request, reply) => {\n const { auth: authenticated, meta } = contextOf(request);\n\n if (bodyOf(request).confirm !== \"disable\") throw new DevtoolsApiError(\"input.invalid\");\n\n await auth.disableDashboard(authenticated, meta);\n // This process closes at once; the others within the state cache time.\n state.invalidate();\n\n return reply.code(204).send();\n });\n}\n","/** Headers on every dashboard answer that is not the uniform 404. */\nexport const DASHBOARD_HEADERS: Readonly<Record<string, string>> = {\n \"Cache-Control\": \"no-store\",\n \"X-Robots-Tag\": \"noindex, nofollow, noarchive\",\n \"Referrer-Policy\": \"no-referrer\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"X-Frame-Options\": \"DENY\",\n \"Cross-Origin-Opener-Policy\": \"same-origin\",\n \"Cross-Origin-Resource-Policy\": \"same-origin\",\n \"Permissions-Policy\":\n \"camera=(), microphone=(), geolocation=(), publickey-credentials-get=(self), publickey-credentials-create=(self)\",\n};\n\n/** The policy of the dashboard's own HTML: scripts and styles from the bundle only. */\nexport const DASHBOARD_CSP =\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'\";\n\n/**\n * The policy of the opt-in API documentation pages: scripts from the dashboard\n * only (Scalar and Swagger UI probe `Function` in a try/catch and work without\n * `'unsafe-eval'`), inline styles, and framing by the dashboard itself, whose\n * API tab shows them in a frame.\n */\nexport const DOCS_CSP =\n \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'\";\n","import { createHash } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { listPanelInfos } from \"../../panels\";\nimport { registerAiRoutes } from \"../../server/ai-routes\";\nimport { registerShapeExplainRoute } from \"../../server/explain-route\";\nimport { registerInsightsRoutes } from \"../../server/insights-routes\";\nimport { registerLogRoutes } from \"../../server/log-routes\";\nimport { registerMailRoutes } from \"../../server/mail-routes\";\nimport { registerOpenApiRoutes } from \"../../server/openapi-routes\";\nimport { registerPanelRoutes } from \"../../server/panel-routes\";\nimport { registerRequestsRoutes } from \"../../server/requests-routes\";\nimport { registerRouteRoutes } from \"../../server/route-routes\";\nimport { registerStreamRoute } from \"../../server/stream-route\";\nimport type { DevtoolsStreamSession, MountDevtoolsRoutesDeps } from \"../../server/types\";\nimport { registerUiAssets } from \"../../server/ui-assets\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport { DevtoolsApiError, createErrorRef, DEVTOOLS_ERROR_MESSAGES } from \"../errors\";\nimport { createAccessLookup, productionRouteAccess } from \"./access\";\nimport { registerAuthRoutes } from \"./auth-routes\";\nimport { resolveClient } from \"./client\";\nimport { setDevtoolsRequestContext, devtoolsRequestContext } from \"./context\";\nimport { readCookie, sessionCookieName } from \"./cookie\";\nimport { DASHBOARD_CSP, DASHBOARD_HEADERS, DOCS_CSP } from \"./headers\";\nimport { DEVTOOLS_CSRF_HEADER } from \"./constants\";\nimport { ipMatches } from \"./ip\";\nimport type { DevtoolsRouteAccess, MountProductionDevtoolsDeps } from \"./types\";\n\n/** Open live streams a session may hold, and an instance may serve. */\nconst MAX_STREAMS_PER_SESSION = 3;\nconst MAX_STREAMS_PER_INSTANCE = 50;\n\nconst MAX_USER_AGENT = 200;\n\n/** Methods that never change state. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The routes of the opt-in API documentation pages (they keep a CSP of their own). */\nconst DOCS_PATTERNS = new Set([\"/docs\", \"/docs/swagger\"]);\n\n/** The mail preview's HTML: framed by the dashboard, with a policy of its own. */\nconst MAIL_HTML_PATTERN = \"/api/mails/:id/html\";\n\n/** Which tab a route belongs to: a route of a tab that is off answers the uniform 404. */\nconst TAB_OF_ROUTE: readonly (readonly [prefix: string, tab: string])[] = [\n [\"/api/resources\", \"resources\"],\n [\"/api/queries\", \"queries\"],\n [\"/api/routes/stats\", \"routes\"],\n [\"/api/routes\", \"routes\"],\n [\"/api/health\", \"health\"],\n [\"/api/errors\", \"errors\"],\n [\"/api/jobs\", \"jobs\"],\n [\"/api/logs\", \"logs\"],\n [\"/api/requests\", \"requests\"],\n [\"/api/mails\", \"mail\"],\n [\"/api/ai/agent-runs\", \"agents\"],\n [\"/api/ai\", \"ai\"],\n [\"/api/openapi.json\", \"api\"],\n [\"/api/postman.json\", \"api\"],\n [\"/docs\", \"api\"],\n];\n\nfunction tabOf(pattern: string): string | undefined {\n return TAB_OF_ROUTE.find(\n ([prefix]) => pattern === prefix || pattern.startsWith(`${prefix}/`),\n )?.[1];\n}\n\nfunction tokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n/** Requests that were answered with the uniform 404: they get none of the dashboard's headers. */\nconst uniformNotFound = new WeakSet<FastifyRequest>();\n\n/**\n * The origin the browser must send for an unsafe request: `production.origin`,\n * else the scheme and host the request was addressed to.\n */\nfunction originAllowed(request: FastifyRequest, expected: string): boolean {\n const origin = request.headers.origin;\n const site = request.headers[\"sec-fetch-site\"];\n\n if (site !== undefined && site !== \"same-origin\") return false;\n\n if (origin !== undefined) return origin.toLowerCase() === expected.toLowerCase();\n\n // No Origin header: a same-origin fetch from an older browser. Accept it only with the fetch metadata that proves it.\n return site === \"same-origin\";\n}\n\nfunction hasBody(request: FastifyRequest): boolean {\n const length = request.headers[\"content-length\"];\n\n return (\n (length !== undefined && length !== \"0\") || request.headers[\"transfer-encoding\"] !== undefined\n );\n}\n\nfunction isJson(request: FastifyRequest): boolean {\n return /^application\\/json\\s*(;|$)/i.test(request.headers[\"content-type\"] ?? \"\");\n}\n\nfunction sessionAccessOk(\n access: Exclude<DevtoolsRouteAccess, { type: \"public\" }>,\n stage: string,\n): boolean {\n if (stage === \"active\") return true;\n\n return access.type === \"pending\" && (access.stages as readonly string[]).includes(stage);\n}\n\n/**\n * Mounts the production monitor under `production.path` in one encapsulated\n * Fastify context: the gate (uniform 404, HTTPS, allowed IPs, open state),\n * session and role checks from the access table, CSRF and origin checks,\n * security headers and CORS stripping, the auth/account/admin routes, and\n * the shared data routes of the enabled tabs.\n */\nexport function mountProductionDevtools(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { production, auth, state, store } = deps;\n const prefix = production.path;\n const cookieName = sessionCookieName(production.requireHttps);\n const enabledTabs = new Set(deps.builtInPanels);\n const lookup = createAccessLookup(productionRouteAccess(deps.panels.map((panel) => panel.id)));\n const streamsPerSession = new Map<string, number>();\n let streamsInstance = 0;\n let lastWarningAt = 0;\n\n const warn = (message: string): void => {\n // At most one line a minute: a database outage must not flood the log.\n const now = Date.now();\n\n if (now - lastWarningAt < 60_000) return;\n\n lastWarningAt = now;\n deps.warn?.(message);\n };\n\n const notFound = (request: FastifyRequest, reply: FastifyReply): FastifyReply => {\n uniformNotFound.add(request);\n\n // The app's own not-found handler answers, so the reply is the one any unknown URL gets.\n reply.callNotFound();\n\n // Returning the reply is what stops an async hook's lifecycle.\n return reply;\n };\n\n const streamSession = async (request: FastifyRequest): Promise<DevtoolsStreamSession> => {\n const authenticated = devtoolsRequestContext(request)?.authenticated;\n\n if (!authenticated) throw new Error(\"A dashboard stream was opened without a session.\");\n\n const sessionId = authenticated.session.id;\n const token = readCookie(request.headers.cookie, cookieName);\n const open = streamsPerSession.get(sessionId) ?? 0;\n\n if (open >= MAX_STREAMS_PER_SESSION || streamsInstance >= MAX_STREAMS_PER_INSTANCE) {\n throw new DevtoolsApiError(\"stream.too-many\");\n }\n\n streamsPerSession.set(sessionId, open + 1);\n streamsInstance += 1;\n\n let released = false;\n\n return {\n role: authenticated.account.role,\n logLevels: production.logLevels,\n headers: DASHBOARD_HEADERS,\n // Reads the session without touching `lastSeenAt`: a stream left open must not keep the session alive.\n async revalidate() {\n if (token === undefined || !(await state.isOpen())) return false;\n\n const session = await store.sessions.findByTokenHash(tokenHash(token));\n const now = Date.now();\n\n if (\n session === null ||\n session.stage !== \"active\" ||\n now >= session.expiresAt ||\n now - session.lastSeenAt >= production.session.idleMinutes * 60_000\n ) {\n return false;\n }\n\n return (await store.accounts.findById(session.accountId)) !== null;\n },\n release() {\n if (released) return;\n\n released = true;\n streamsInstance -= 1;\n\n const left = (streamsPerSession.get(sessionId) ?? 1) - 1;\n\n if (left <= 0) streamsPerSession.delete(sessionId);\n else streamsPerSession.set(sessionId, left);\n },\n };\n };\n\n // The route deps the shared route files read: the development deps, completed.\n const routes: MountDevtoolsRoutesDeps = {\n ...deps.routes,\n mode: \"production\",\n isDevelopment: () => false,\n instance: deps.instance,\n insights: deps.insights,\n collector: deps.routes.collector ?? deps.capture.collector,\n requests: deps.routes.requests ?? deps.capture.requests,\n explainShape: deps.routes.explainShape ?? ((shapeId) => deps.capture.explain(shapeId)),\n builtInPanels: deps.builtInPanels,\n streamSession,\n };\n\n server.register(\n async (instance) => {\n // ---- The gate -------------------------------------------------------\n instance.addHook(\"onRequest\", async (request, reply) => {\n let open: boolean;\n\n try {\n open = await state.isOpen();\n } catch (error) {\n // Fail closed: when the state cannot be read the dashboard does not answer.\n warn(\n `The devtools dashboard state could not be read and the dashboard is closed: ${error instanceof Error ? error.message : String(error)}`,\n );\n open = false;\n }\n\n if (!open) return notFound(request, reply);\n\n const client = resolveClient(request, production.trustedProxies);\n\n if (production.requireHttps && client.proto !== \"https\") return notFound(request, reply);\n\n if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) {\n return notFound(request, reply);\n }\n\n const userAgent = request.headers[\"user-agent\"];\n const expectedOrigin = production.origin ?? `${client.proto}://${client.host}`;\n const meta: DevtoolsRequestMeta = {\n ip: client.ip,\n userAgent: typeof userAgent === \"string\" ? userAgent.slice(0, MAX_USER_AGENT) : null,\n origin: expectedOrigin,\n hostname: client.hostname,\n };\n\n const routeUrl = request.routeOptions.url ?? \"\";\n const relative = routeUrl.startsWith(prefix) ? routeUrl.slice(prefix.length) : routeUrl;\n // The shell is registered once for both `<path>` and `<path>/`.\n const pattern = relative === \"\" ? \"/\" : relative;\n const method = request.method;\n\n // The bare path (no trailing slash) redirects to the shell's address. The\n // address as sent: core's server drops a trailing slash before routing,\n // so the rewritten URL of `<path>/` is the bare path too.\n const sent = request.originalUrl ?? request.raw.url ?? \"\";\n\n if (sent.split(\"?\")[0] === prefix) {\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule: undefined,\n pattern,\n authenticated: null,\n });\n\n if (method !== \"GET\" && method !== \"HEAD\") return notFound(request, reply);\n\n const search = sent.includes(\"?\") ? `?${sent.split(\"?\").slice(1).join(\"?\")}` : \"\";\n\n return reply.redirect(`${prefix}/${search}`, 308);\n }\n\n const tab = tabOf(pattern);\n\n if (tab !== undefined && !enabledTabs.has(tab)) return notFound(request, reply);\n\n const rule = lookup(method, pattern);\n const access: DevtoolsRouteAccess = rule?.access ?? { type: \"admin\" };\n let authenticated: DevtoolsAuthenticated | null = null;\n\n if (access.type !== \"public\") {\n try {\n authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));\n } catch (error) {\n warn(\n `The devtools session could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n\n if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) {\n return notFound(request, reply);\n }\n\n if (access.type === \"admin\" && authenticated.account.role !== \"admin\") {\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n }\n\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n\n if (SAFE_METHODS.has(method)) return;\n\n if (!originAllowed(request, expectedOrigin)) {\n if (authenticated === null) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n\n if (hasBody(request) && !isJson(request)) throw new DevtoolsApiError(\"input.invalid\");\n\n if (authenticated !== null) {\n const header = request.headers[DEVTOOLS_CSRF_HEADER];\n\n if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) {\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n }\n });\n\n // ---- Headers --------------------------------------------------------\n instance.addHook(\"onSend\", async (request, reply, payload) => {\n // The uniform 404 must look like any other 404 of the app.\n if (uniformNotFound.has(request)) return payload;\n\n for (const name of Object.keys(reply.getHeaders())) {\n if (name.startsWith(\"access-control-\")) reply.removeHeader(name);\n }\n\n reply.headers(DASHBOARD_HEADERS);\n\n const pattern = devtoolsRequestContext(request)?.pattern ?? \"\";\n\n // The mail preview is the one page the dashboard frames, from its own origin, and it sends its own policy.\n if (pattern === MAIL_HTML_PATTERN) {\n reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n return payload;\n }\n\n // The API docs pages are shown in a frame by the dashboard's API tab.\n if (DOCS_PATTERNS.has(pattern)) reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n // Always the dashboard's policy: the app's own (core's security headers set one on every response) is not\n // written for this page and must not replace it.\n if (String(reply.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n reply.header(\n \"Content-Security-Policy\",\n DOCS_PATTERNS.has(pattern) ? DOCS_CSP : DASHBOARD_CSP,\n );\n }\n\n return payload;\n });\n\n // ---- Audit ----------------------------------------------------------\n instance.addHook(\"onResponse\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n const type = context?.rule?.audit;\n\n if (!context || !type || reply.statusCode < 200 || reply.statusCode > 299) return;\n\n const params = (request.params ?? {}) as Record<string, string | undefined>;\n const detail: Record<string, string | number | boolean | null> =\n type === \"explain.run\"\n ? { shapeId: params.shapeId ?? null }\n : type === \"panel.action\"\n ? {\n panel: context.pattern.split(\"/\")[2] ?? null,\n method: request.method,\n route: context.pattern,\n }\n : {};\n\n await auth.audit(type, { auth: context.authenticated, meta: context.meta, detail });\n });\n\n // ---- Errors ---------------------------------------------------------\n instance.setErrorHandler(\n (error: Error & { statusCode?: number; code?: string }, request, reply) => {\n if (error instanceof DevtoolsApiError) {\n return reply.code(error.statusCode).send(error.toBody());\n }\n\n const status = error.statusCode;\n\n // The request itself was wrong (bad JSON, too large): say so in the dashboard's own shape.\n if (status !== undefined && status >= 400 && status < 500) {\n return reply\n .code(status)\n .send(\n error.code?.startsWith(\"FST_ERR_\")\n ? new DevtoolsApiError(\"input.invalid\").toBody()\n : { error: error.message },\n );\n }\n\n const ref = createErrorRef();\n\n // Never rate limited: the reference the browser shows must always be findable in the log. The route is\n // written relative to the dashboard path, which never reaches the log.\n deps.warn?.(\n `Devtools dashboard error ${ref} on ${request.method} ${devtoolsRequestContext(request)?.pattern ?? \"(dashboard route)\"}: ${error.message}`,\n );\n request.log.error({ ref, err: error }, \"devtools dashboard error\");\n\n return reply.code(500).send({\n error: DEVTOOLS_ERROR_MESSAGES[\"server.error\"],\n code: \"server.error\",\n ref,\n });\n },\n );\n\n // ---- Routes ---------------------------------------------------------\n registerUiAssets(instance, { notFound });\n registerAuthRoutes(instance, deps);\n\n instance.get(\"/api/panels\", async () => listPanelInfos(deps.panels, deps.builtInPanels));\n\n registerRequestsRoutes(instance, routes);\n registerRouteRoutes(instance, routes);\n registerInsightsRoutes(instance, routes);\n registerLogRoutes(instance, routes);\n registerShapeExplainRoute(instance, routes);\n registerPanelRoutes(instance, deps.panels);\n\n if (enabledTabs.has(\"mail\")) registerMailRoutes(instance, routes);\n if (enabledTabs.has(\"ai\") || enabledTabs.has(\"agents\")) registerAiRoutes(instance, routes);\n if (enabledTabs.has(\"api\")) registerOpenApiRoutes(instance, routes);\n\n registerStreamRoute(instance, routes);\n },\n { prefix },\n );\n}\n","import { createHash } from \"node:crypto\";\nimport type { DevtoolsStore } from \"../store/types\";\nimport type { DevtoolsDashboardState } from \"./types\";\n\n/** SHA-256 hex of a dashboard path: what `disabledPathHash` holds. */\nexport function hashDashboardPath(path: string): string {\n return createHash(\"sha256\").update(path).digest(\"hex\");\n}\n\n/**\n * The open/closed state with a `ttlMs` cache (default 5000). Open means the\n * dashboard is not disabled for this path and not locked. A failed read is\n * not cached and rejects, so the caller can fail closed.\n */\nexport function createDashboardState(\n store: DevtoolsStore,\n path: string,\n options: { ttlMs?: number; now?: () => number } = {},\n): DevtoolsDashboardState {\n const ttlMs = options.ttlMs ?? 5000;\n const now = options.now ?? Date.now;\n const pathHash = hashDashboardPath(path);\n let cached: { open: boolean; at: number } | null = null;\n let pending: Promise<boolean> | null = null;\n let generation = 0;\n\n const read = async (): Promise<boolean> => {\n const started = generation;\n const state = await store.state.read();\n const at = now();\n const disabled = state.disabled && state.disabledPathHash === pathHash;\n const locked = state.lockedUntil !== null && state.lockedUntil > at;\n const open = !disabled && !locked;\n\n if (started === generation) cached = { open, at };\n\n return open;\n };\n\n return {\n async isOpen() {\n if (cached !== null && now() - cached.at < ttlMs) return cached.open;\n\n if (pending === null) {\n const current = read().finally(() => {\n if (pending === current) pending = null;\n });\n\n pending = current;\n }\n\n return pending;\n },\n invalidate() {\n generation += 1;\n cached = null;\n pending = null;\n },\n };\n}\n"],"mappings":";;;;;;;;AAIA,MAAM,SAA8B,EAAE,MAAM,SAAS;AACrD,MAAM,SAA8B,EAAE,MAAM,SAAS;AACrD,MAAM,QAA6B,EAAE,MAAM,QAAQ;AAEnD,MAAM,WAAW,GAAG,YACjB;CAAE,MAAM;CAAW;AAAO;AAE7B,MAAM,YAAY;CAAC;CAAmB;CAAa;AAAY;;;;;;;;AAS/D,SAAgB,sBAAsB,UAAwD;CAC5F,MAAM,QACJ,QACA,KACA,QACA,WAC6B;EAAE;EAAQ;EAAK;EAAQ,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;CAAG;CAElF,MAAM,QAAmC;EAEvC,KAAK,OAAO,KAAK,MAAM;EACvB,KAAK,OAAO,iBAAiB,MAAM;EACnC,KAAK,OAAO,qBAAqB,MAAM;EACvC,KAAK,QAAQ,mBAAmB,MAAM;EACtC,KAAK,QAAQ,mBAAmB,MAAM;EACtC,KAAK,QAAQ,4BAA4B,MAAM;EAC/C,KAAK,QAAQ,2BAA2B,MAAM;EAC9C,KAAK,QAAQ,sBAAsB,QAAQ,iBAAiB,CAAC;EAC7D,KAAK,QAAQ,wBAAwB,QAAQ,WAAW,CAAC;EACzD,KAAK,QAAQ,0BAA0B,QAAQ,WAAW,CAAC;EAC3D,KAAK,QAAQ,6BAA6B,QAAQ,aAAa,YAAY,CAAC;EAC5E,KAAK,QAAQ,4BAA4B,QAAQ,aAAa,YAAY,CAAC;EAC3E,KAAK,QAAQ,iBAAiB,QAAQ,YAAY,CAAC;EACnD,KAAK,QAAQ,oBAAoB,QAAQ,GAAG,SAAS,CAAC;EAGtD,KAAK,OAAO,eAAe,MAAM;EACjC,KAAK,OAAO,gBAAgB,MAAM;EAClC,KAAK,OAAO,yBAAyB,MAAM;EAC3C,KAAK,UAAU,6BAA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OAAO,OAAO,OAAO;GAEhE,IAAI,YAAY,MAAM;IACpB,MAAM,UAAU,KAAK,CAAC,CAAC,cAAc;KACnC,IAAI,YAAY,SAAS,UAAU;IACrC,CAAC;IAED,UAAU;GACZ;GAEA,OAAO;EACT;EACA,aAAa;GACX,cAAc;GACd,SAAS;GACT,UAAU;EACZ;CACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"migrations-w7GMsrQw.cjs","names":["Model","migrate","migrate","migrate","migrate","migrate","migrate","migrate"],"sources":["../../../../../../../packages/devtools/src/production/store/models/base.ts","../../../../../../../packages/devtools/src/production/store/models/account.model.ts","../../../../../../../packages/devtools/src/production/store/models/account.migration.ts","../../../../../../../packages/devtools/src/production/store/models/audit.model.ts","../../../../../../../packages/devtools/src/production/store/models/audit.migration.ts","../../../../../../../packages/devtools/src/production/store/models/invite.model.ts","../../../../../../../packages/devtools/src/production/store/models/invite.migration.ts","../../../../../../../packages/devtools/src/production/store/models/report.model.ts","../../../../../../../packages/devtools/src/production/store/models/report.migration.ts","../../../../../../../packages/devtools/src/production/store/models/sample.model.ts","../../../../../../../packages/devtools/src/production/store/models/sample.migration.ts","../../../../../../../packages/devtools/src/production/store/models/session.model.ts","../../../../../../../packages/devtools/src/production/store/models/session.migration.ts","../../../../../../../packages/devtools/src/production/store/models/state.model.ts","../../../../../../../packages/devtools/src/production/store/models/state.migration.ts","../../../../../../../packages/devtools/src/production/store/models/index.ts","../../../../../../../packages/devtools/src/production/store/migrations.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\n\n/**\n * Settings shared by the monitor's tables. Ids are supplied by the store\n * (random uuids, or `\"state\"`), times are plain epoch-millisecond columns the\n * store writes itself, and a removal is always permanent: sessions, invites\n * and samples must not be copied into a trash table.\n */\nexport abstract class DevtoolsRowModel extends Model {\n public static autoGenerateId = false;\n\n public static createdAtColumn = false as const;\n\n public static updatedAtColumn = false as const;\n\n public static deleteStrategy = \"permanent\" as const;\n}\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_accounts`. */\nexport class DevtoolsAccountRow extends DevtoolsRowModel {\n public static table = \"devtools_accounts\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsAccountRow } from \"./account.model\";\n\nexport const DevtoolsAccountsMigration = migrate(DevtoolsAccountRow, {\n name: \"devtoolsAccounts\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"email\", 320).unique();\n this.string(\"role\", 16);\n this.text(\"password_hash\");\n this.string(\"password_source\", 32);\n this.boolean(\"must_change_password\").default(false);\n this.text(\"totp_secret\").nullable();\n this.bigInteger(\"totp_enabled_at\").nullable();\n this.bigInteger(\"totp_last_step\").nullable();\n this.json(\"recovery_codes\");\n this.json(\"passkeys\");\n this.bigInteger(\"failures_reset_at\").nullable();\n this.bigInteger(\"created_at\");\n this.bigInteger(\"updated_at\");\n this.bigInteger(\"last_login_at\").nullable();\n this.string(\"created_by\", 64).nullable();\n this.integer(\"version\").default(1);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_audit`. */\nexport class DevtoolsAuditRow extends DevtoolsRowModel {\n public static table = \"devtools_audit\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsAuditRow } from \"./audit.model\";\n\nexport const DevtoolsAuditMigration = migrate(DevtoolsAuditRow, {\n name: \"devtoolsAudit\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"type\", 64);\n this.bigInteger(\"occurred_at\").index();\n this.string(\"account_id\", 64).nullable();\n this.string(\"email\", 320).nullable();\n this.string(\"ip\", 64).nullable();\n // The per-IP sign-in limit counts by this: the address, or its /64 for IPv6.\n this.string(\"ip_bucket\", 64).nullable();\n this.string(\"user_agent\", 255).nullable();\n this.json(\"detail\");\n this.string(\"ref\", 16);\n\n this.index([\"type\", \"occurred_at\"]);\n this.index([\"ip_bucket\", \"occurred_at\"]);\n this.index([\"account_id\", \"occurred_at\"]);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_invites`. */\nexport class DevtoolsInviteRow extends DevtoolsRowModel {\n public static table = \"devtools_invites\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsInviteRow } from \"./invite.model\";\n\nexport const DevtoolsInvitesMigration = migrate(DevtoolsInviteRow, {\n name: \"devtoolsInvites\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"token_hash\", 64).unique();\n this.string(\"email\", 320);\n this.string(\"role\", 16);\n this.string(\"created_by\", 64).nullable();\n this.bigInteger(\"created_at\");\n this.bigInteger(\"expires_at\").index();\n this.bigInteger(\"used_at\").nullable();\n this.string(\"account_id\", 64).nullable();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_reports`. */\nexport class DevtoolsReportRow extends DevtoolsRowModel {\n public static table = \"devtools_reports\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsReportRow } from \"./report.model\";\n\nexport const DevtoolsReportsMigration = migrate(DevtoolsReportRow, {\n name: \"devtoolsReports\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.bigInteger(\"seen_at\").index();\n // JSON text, up to 256 KB.\n this.longText(\"data\");\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_samples`. */\nexport class DevtoolsSampleRow extends DevtoolsRowModel {\n public static table = \"devtools_samples\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsSampleRow } from \"./sample.model\";\n\nexport const DevtoolsSamplesMigration = migrate(DevtoolsSampleRow, {\n name: \"devtoolsSamples\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"instance\", 128).index();\n this.bigInteger(\"started_at\").index();\n this.integer(\"status\").nullable().index();\n this.string(\"method\", 16);\n this.text(\"path\");\n this.json(\"summary\");\n // JSON text: request data may hold keys MongoDB cannot store as field names.\n this.longText(\"detail\").nullable();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_sessions`. */\nexport class DevtoolsSessionRow extends DevtoolsRowModel {\n public static table = \"devtools_sessions\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsSessionRow } from \"./session.model\";\n\nexport const DevtoolsSessionsMigration = migrate(DevtoolsSessionRow, {\n name: \"devtoolsSessions\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.string(\"token_hash\", 64).unique();\n this.string(\"account_id\", 64).index();\n this.string(\"stage\", 32);\n this.string(\"csrf_secret\", 128);\n this.bigInteger(\"created_at\");\n this.bigInteger(\"last_seen_at\");\n this.bigInteger(\"expires_at\").index();\n this.string(\"ip\", 64).nullable();\n this.string(\"user_agent\", 255).nullable();\n this.text(\"pending_totp_secret\").nullable();\n this.text(\"challenge\").nullable();\n this.bigInteger(\"challenge_expires_at\").nullable();\n this.integer(\"version\").default(1);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","import { DevtoolsRowModel } from \"./base\";\n\n/** A row of `devtools_state`. */\nexport class DevtoolsStateRow extends DevtoolsRowModel {\n public static table = \"devtools_state\";\n}\n","import { migrate } from \"@warlock.js/cascade\";\nimport { DevtoolsStateRow } from \"./state.model\";\n\nexport const DevtoolsStateMigration = migrate(DevtoolsStateRow, {\n name: \"devtoolsState\",\n up() {\n this.createTableIfNotExists();\n\n // The id is a string the store supplies; `unique` also covers MongoDB,\n // which ignores primary keys.\n this.string(\"id\", 64).primary().unique();\n\n this.boolean(\"disabled\").default(false);\n this.string(\"disabled_path_hash\", 64).nullable();\n this.bigInteger(\"disabled_at\").nullable();\n this.string(\"disabled_by\", 64).nullable();\n this.bigInteger(\"locked_until\").nullable();\n this.bigInteger(\"failures_reset_at\").nullable();\n this.bigInteger(\"updated_at\");\n this.integer(\"version\").default(0);\n },\n down() {\n this.dropTableIfExists();\n },\n});\n","export { DevtoolsRowModel } from \"./base\";\nexport { DevtoolsAccountsMigration } from \"./account.migration\";\nexport { DevtoolsAccountRow } from \"./account.model\";\nexport { DevtoolsAuditMigration } from \"./audit.migration\";\nexport { DevtoolsAuditRow } from \"./audit.model\";\nexport { DevtoolsInvitesMigration } from \"./invite.migration\";\nexport { DevtoolsInviteRow } from \"./invite.model\";\nexport { DevtoolsReportsMigration } from \"./report.migration\";\nexport { DevtoolsReportRow } from \"./report.model\";\nexport { DevtoolsSamplesMigration } from \"./sample.migration\";\nexport { DevtoolsSampleRow } from \"./sample.model\";\nexport { DevtoolsSessionsMigration } from \"./session.migration\";\nexport { DevtoolsSessionRow } from \"./session.model\";\nexport { DevtoolsStateMigration } from \"./state.migration\";\nexport { DevtoolsStateRow } from \"./state.model\";\n","import type { MigrationConstructor } from \"@warlock.js/cascade\";\nimport {\n DevtoolsAccountsMigration,\n DevtoolsAuditMigration,\n DevtoolsInvitesMigration,\n DevtoolsReportsMigration,\n DevtoolsSamplesMigration,\n DevtoolsSessionsMigration,\n DevtoolsStateMigration,\n} from \"./models\";\n\n/**\n * The migrations of the production monitor's tables/collections:\n * `devtools_accounts`, `devtools_sessions`, `devtools_invites`,\n * `devtools_audit`, `devtools_state`, `devtools_samples`, `devtools_reports`.\n * An app lists them in `warlock.config.ts > database.migrations`.\n */\nexport const devtoolsMigrations: readonly MigrationConstructor[] = [\n DevtoolsAccountsMigration,\n DevtoolsSessionsMigration,\n DevtoolsInvitesMigration,\n DevtoolsAuditMigration,\n DevtoolsStateMigration,\n DevtoolsSamplesMigration,\n DevtoolsReportsMigration,\n];\n"],"mappings":";;;;;;;;;;AAQA,IAAsB,mBAAtB,cAA+CA,0BAAM;;wBACpB;;;yBAEC;;;yBAEA;;;wBAED;;AACjC;;;;;ACbA,IAAa,qBAAb,cAAwC,iBAAiB;;eACjC;;AACxB;;;;ACFA,MAAa,gCAA4BC,6BAAQ,oBAAoB;CACnE,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAI5B,KAAK,OAAO,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAO;EAEvC,KAAK,OAAO,SAAS,GAAG,CAAC,CAAC,OAAO;EACjC,KAAK,OAAO,QAAQ,EAAE;EACtB,KAAK,KAAK,eAAe;EACzB,KAAK,OAAO,mBAAmB,EAAE;EACjC,KAAK,QAAQ,sBAAsB,CAAC,CAAC,QAAQ,KAAK;EAClD,KAAK,KAAK,aAAa,CAAC,CAAC,SAAS;EAClC,KAAK,WAAW,iBAAiB,CAAC,CAAC,SAAS;EAC5C,KAAK,WAAW,gBAAgB,CAAC,CAAC,SAAS;EAC3C,KAAK,KAAK,gBAAgB;EAC1B,KAAK,KAAK,UAAU;EACpB,KAAK,WAAW,mBAAmB,CAAC,CAAC,SAAS;EAC9C,KAAK,WAAW,YAAY;EAC5B,KAAK,WAAW,YAAY;EAC5B,KAAK,WAAW,eAAe,CAAC,CAAC,SAAS;EAC1C,KAAK,OAAO,cAAc,EAAE,CAAC,CAAC,SAAS;EACvC,KAAK,QAAQ,SAAS,CAAC,CAAC,QAAQ,CAAC;CACnC;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC;;;;;AC7BD,IAAa,mBAAb,cAAsC,iBAAiB;;eAC/B;;AACxB;;;;ACFA,MAAa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","names":["DevtoolsProductionConfigError","isValidNetworkEntry"],"sources":["../../../../../../../packages/devtools/src/production/options.ts"],"sourcesContent":["import type { DevtoolsLogEntry, DevtoolsProductionOptions } from \"../types\";\nimport { DevtoolsProductionConfigError } from \"./errors\";\nimport { isValidNetworkEntry } from \"./http/ip\";\n\n/**\n * `DevtoolsProductionOptions` with every default applied and the environment\n * read. Built once at boot by `resolveProductionOptions`.\n */\nexport type ResolvedDevtoolsProductionOptions = {\n /** The dashboard path, without a trailing slash. */\n path: string;\n /** The first admin from the environment; every field `null` when unset. */\n admin: { email: string | null; password: string | null; setupToken: string | null };\n sampleRate: number;\n slowRequestMs: number;\n slowQueryMs: number;\n maxRequests: number;\n /** Queries kept per sampled request; the rest are counted in `droppedQueries`. */\n maxQueriesPerRequest: number;\n /** Query shapes kept in memory per process (least recently seen evicted). */\n maxShapes: number;\n /** Route keys kept in memory per process. */\n maxRoutes: number;\n /** Error groups kept in memory per process. */\n maxErrorGroups: number;\n requestRetentionHours: number;\n maxStoredSamplesPerMinute: number;\n reportIntervalMs: number;\n trustedProxies: readonly string[];\n requireHttps: boolean;\n allowedIps: readonly string[];\n origin: string | null;\n session: { idleMinutes: number; maxHours: number; pendingMinutes: number };\n twoFactor: \"admins\" | \"everyone\";\n rateLimits: {\n windowMinutes: number;\n account: number;\n ip: number;\n global: number;\n lockMinutes: number;\n };\n explain: { executing: boolean };\n panels: Readonly<Record<string, boolean>>;\n logLevels: readonly DevtoolsLogEntry[\"level\"][];\n auditRetentionDays: number;\n passkeys: { rpName: string; rpId: string | null };\n};\n\n/** The defaults `resolveProductionOptions` applies (environment values excluded). */\nexport const DEVTOOLS_PRODUCTION_DEFAULTS = {\n sampleRate: 0.1,\n slowRequestMs: 1000,\n slowQueryMs: 200,\n maxRequests: 200,\n maxQueriesPerRequest: 200,\n maxShapes: 500,\n maxRoutes: 300,\n maxErrorGroups: 100,\n requestRetentionHours: 24,\n maxStoredSamplesPerMinute: 120,\n reportIntervalMs: 10_000,\n requireHttps: true,\n session: { idleMinutes: 30, maxHours: 8, pendingMinutes: 10 },\n twoFactor: \"admins\",\n rateLimits: { windowMinutes: 15, account: 5, ip: 20, global: 100, lockMinutes: 15 },\n explain: { executing: false },\n logLevels: [\"warn\", \"error\"],\n auditRetentionDays: 90,\n passkeys: { rpName: \"Warlock monitor\" },\n} as const;\n\n/** The environment variables production mode reads. */\nexport const DEVTOOLS_ENV = {\n path: \"DEVTOOLS_PATH\",\n adminEmail: \"DEVTOOLS_ADMIN_EMAIL\",\n adminPassword: \"DEVTOOLS_ADMIN_PASSWORD\",\n setupToken: \"DEVTOOLS_SETUP_TOKEN\",\n} as const;\n\nconst LOG_LEVELS: readonly DevtoolsLogEntry[\"level\"][] = [\n \"debug\",\n \"info\",\n \"warn\",\n \"error\",\n \"success\",\n];\n\nconst PATH_CHARACTERS = /^[A-Za-z0-9._~/-]+$/;\nconst MIN_PATH_LENGTH = 8;\nconst MIN_SETUP_TOKEN_LENGTH = 32;\n\nfunction invalid(option: string, expected: string): never {\n throw new DevtoolsProductionConfigError(\n \"DT007\",\n `Option \"devtools.production.${option}\" is not valid: ${expected}.`,\n );\n}\n\nfunction present(value: string | undefined): string | null {\n return value === undefined || value === \"\" ? null : value;\n}\n\nfunction integerAtLeastOne(option: string, value: number | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n\n if (!Number.isInteger(value) || value < 1) invalid(option, \"use a whole number of 1 or more\");\n\n return value;\n}\n\nfunction networkList(option: string, value: readonly string[] | undefined): readonly string[] {\n if (value === undefined) return [];\n\n if (!Array.isArray(value)) {\n invalid(option, 'use a list of IPs, CIDR ranges, \"loopback\" or \"private\"');\n }\n\n for (const entry of value as readonly unknown[]) {\n if (!isValidNetworkEntry(entry)) {\n invalid(option, `\"${String(entry)}\" is not an IP, a CIDR range, \"loopback\" or \"private\"`);\n }\n }\n\n return [...value];\n}\n\n/** The dashboard path without a trailing slash, or a DT001/DT002 error. */\nfunction resolvePath(value: string | undefined): string {\n const given = present(value);\n\n if (given === null) throw new DevtoolsProductionConfigError(\"DT001\");\n\n const path = given.replace(/\\/+$/, \"\");\n const segments = path.split(\"/\").slice(1);\n const lower = path.toLowerCase();\n\n if (\n !path.startsWith(\"/\") ||\n path.length < MIN_PATH_LENGTH ||\n !PATH_CHARACTERS.test(path) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\") ||\n lower === \"/__warlock\" ||\n lower.startsWith(\"/__warlock/\")\n ) {\n throw new DevtoolsProductionConfigError(\"DT002\");\n }\n\n return path;\n}\n\n/**\n * Applies the defaults to `options`, reads the path and first admin from\n * `env`, and validates everything.\n *\n * Throws `DevtoolsProductionConfigError`: DT001 (no path), DT002 (bad path),\n * DT007 (an option out of range: sampleRate outside 0–1, a non-positive\n * limit, an unknown twoFactor value, a bad CIDR, an origin that is not\n * `https://host[:port]`), DT009 (both a password and a setup token), DT010\n * (setup token shorter than 32 characters). DT003/DT004 (admin) are checked\n * later by `ensureFirstAdmin`, which needs the database.\n */\nexport function resolveProductionOptions(\n options: DevtoolsProductionOptions | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): ResolvedDevtoolsProductionOptions {\n const given = options ?? {};\n const defaults = DEVTOOLS_PRODUCTION_DEFAULTS;\n const path = resolvePath(given.path ?? env[DEVTOOLS_ENV.path]);\n\n const sampleRate = given.sampleRate ?? defaults.sampleRate;\n\n if (\n typeof sampleRate !== \"number\" ||\n !Number.isFinite(sampleRate) ||\n sampleRate < 0 ||\n sampleRate > 1\n ) {\n invalid(\"sampleRate\", \"use a number from 0 to 1\");\n }\n\n const requireHttps: boolean = given.requireHttps ?? defaults.requireHttps;\n\n if (typeof requireHttps !== \"boolean\") invalid(\"requireHttps\", \"use true or false\");\n\n const twoFactor = given.twoFactor ?? defaults.twoFactor;\n\n if (twoFactor !== \"admins\" && twoFactor !== \"everyone\") {\n invalid(\"twoFactor\", 'use \"admins\" or \"everyone\"');\n }\n\n const origin = given.origin ?? null;\n\n if (origin !== null) {\n const pattern = requireHttps ? /^https:\\/\\/[^/\\s]+$/ : /^https?:\\/\\/[^/\\s]+$/;\n\n if (typeof origin !== \"string\" || !pattern.test(origin)) {\n invalid(\n \"origin\",\n requireHttps\n ? \"use an origin such as https://app.example.com, without a path or a trailing slash\"\n : \"use an origin such as http://localhost:3000, without a path or a trailing slash\",\n );\n }\n }\n\n const panels: Readonly<Record<string, unknown>> = given.panels ?? {};\n\n if (panels === null || typeof panels !== \"object\" || Array.isArray(panels)) {\n invalid(\"panels\", \"use an object of tab ids and true or false\");\n }\n\n for (const [id, enabled] of Object.entries(panels)) {\n if (typeof enabled !== \"boolean\") invalid(`panels.${id}`, \"use true or false\");\n }\n\n const logLevels = given.logLevels ?? defaults.logLevels;\n\n if (!Array.isArray(logLevels) || logLevels.some((level) => !LOG_LEVELS.includes(level))) {\n invalid(\"logLevels\", `use a list of ${LOG_LEVELS.join(\", \")}`);\n }\n\n const executing: boolean = given.explain?.executing ?? defaults.explain.executing;\n\n if (typeof executing !== \"boolean\") invalid(\"explain.executing\", \"use true or false\");\n\n const rpName: string = given.passkeys?.rpName ?? defaults.passkeys.rpName;\n const rpId = given.passkeys?.rpId ?? null;\n\n if (typeof rpName !== \"string\" || rpName.trim() === \"\") {\n invalid(\"passkeys.rpName\", \"use a non-empty name\");\n }\n\n if (rpId !== null && (typeof rpId !== \"string\" || rpId.trim() === \"\")) {\n invalid(\"passkeys.rpId\", \"use a host name such as app.example.com\");\n }\n\n const limits = given.rateLimits ?? {};\n const session = given.session ?? {};\n\n const resolved: ResolvedDevtoolsProductionOptions = {\n path,\n admin: {\n email: present(env[DEVTOOLS_ENV.adminEmail]),\n password: present(env[DEVTOOLS_ENV.adminPassword]),\n setupToken: present(env[DEVTOOLS_ENV.setupToken]),\n },\n sampleRate,\n slowRequestMs: integerAtLeastOne(\"slowRequestMs\", given.slowRequestMs, defaults.slowRequestMs),\n slowQueryMs: integerAtLeastOne(\"slowQueryMs\", given.slowQueryMs, defaults.slowQueryMs),\n maxRequests: integerAtLeastOne(\"maxRequests\", given.maxRequests, defaults.maxRequests),\n maxQueriesPerRequest: defaults.maxQueriesPerRequest,\n maxShapes: defaults.maxShapes,\n maxRoutes: defaults.maxRoutes,\n maxErrorGroups: defaults.maxErrorGroups,\n requestRetentionHours: integerAtLeastOne(\n \"requestRetentionHours\",\n given.requestRetentionHours,\n defaults.requestRetentionHours,\n ),\n maxStoredSamplesPerMinute: integerAtLeastOne(\n \"maxStoredSamplesPerMinute\",\n given.maxStoredSamplesPerMinute,\n defaults.maxStoredSamplesPerMinute,\n ),\n reportIntervalMs: integerAtLeastOne(\n \"reportIntervalMs\",\n given.reportIntervalMs,\n defaults.reportIntervalMs,\n ),\n trustedProxies: networkList(\"trustedProxies\", given.trustedProxies),\n requireHttps,\n allowedIps: networkList(\"allowedIps\", given.allowedIps),\n origin,\n session: {\n idleMinutes: integerAtLeastOne(\n \"session.idleMinutes\",\n session.idleMinutes,\n defaults.session.idleMinutes,\n ),\n maxHours: integerAtLeastOne(\"session.maxHours\", session.maxHours, defaults.session.maxHours),\n pendingMinutes: defaults.session.pendingMinutes,\n },\n twoFactor,\n rateLimits: {\n windowMinutes: integerAtLeastOne(\n \"rateLimits.windowMinutes\",\n limits.windowMinutes,\n defaults.rateLimits.windowMinutes,\n ),\n account: integerAtLeastOne(\"rateLimits.account\", limits.account, defaults.rateLimits.account),\n ip: integerAtLeastOne(\"rateLimits.ip\", limits.ip, defaults.rateLimits.ip),\n global: integerAtLeastOne(\"rateLimits.global\", limits.global, defaults.rateLimits.global),\n lockMinutes: integerAtLeastOne(\n \"rateLimits.lockMinutes\",\n limits.lockMinutes,\n defaults.rateLimits.lockMinutes,\n ),\n },\n explain: { executing },\n panels: { ...(panels as Readonly<Record<string, boolean>>) },\n logLevels: [...logLevels],\n auditRetentionDays: integerAtLeastOne(\n \"auditRetentionDays\",\n given.auditRetentionDays,\n defaults.auditRetentionDays,\n ),\n passkeys: { rpName, rpId },\n };\n\n if (resolved.admin.password !== null && resolved.admin.setupToken !== null) {\n throw new DevtoolsProductionConfigError(\"DT009\");\n }\n\n if (\n resolved.admin.setupToken !== null &&\n resolved.admin.setupToken.length < MIN_SETUP_TOKEN_LENGTH\n ) {\n throw new DevtoolsProductionConfigError(\"DT010\");\n }\n\n return resolved;\n}\n"],"mappings":";;;;;AAiDA,MAAa,+BAA+B;CAC1C,YAAY;CACZ,eAAe;CACf,aAAa;CACb,aAAa;CACb,sBAAsB;CACtB,WAAW;CACX,WAAW;CACX,gBAAgB;CAChB,uBAAuB;CACvB,2BAA2B;CAC3B,kBAAkB;CAClB,cAAc;CACd,SAAS;EAAE,aAAa;EAAI,UAAU;EAAG,gBAAgB;CAAG;CAC5D,WAAW;CACX,YAAY;EAAE,eAAe;EAAI,SAAS;EAAG,IAAI;EAAI,QAAQ;EAAK,aAAa;CAAG;CAClF,SAAS,EAAE,WAAW,MAAM;CAC5B,WAAW,CAAC,QAAQ,OAAO;CAC3B,oBAAoB;CACpB,UAAU,EAAE,QAAQ,kBAAkB;AACxC;;AAGA,MAAa,eAAe;CAC1B,MAAM;CACN,YAAY;CACZ,eAAe;CACf,YAAY;AACd;AAEA,MAAM,aAAmD;CACvD;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,yBAAyB;AAE/B,SAAS,QAAQ,QAAgB,UAAyB;CACxD,MAAM,IAAIA,6CACR,SACA,+BAA+B,OAAO,kBAAkB,SAAS,EACnE;AACF;AAEA,SAAS,QAAQ,OAA0C;CACzD,OAAO,UAAU,UAAa,UAAU,KAAK,OAAO;AACtD;AAEA,SAAS,kBAAkB,QAAgB,OAA2B,UAA0B;CAC9F,IAAI,UAAU,QAAW,OAAO;CAEhC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GAAG,QAAQ,QAAQ,iCAAiC;CAE5F,OAAO;AACT;AAEA,SAAS,YAAY,QAAgB,OAAyD;CAC5F,IAAI,UAAU,QAAW,OAAO,CAAC;CAEj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 +0,0 @@
1
- {"version":3,"file":"panels-Rcmeitu3.cjs","names":["path","fileURLToPath","existsSync","statSync","pathToFileURL","readFileSync","createRequire","DEVTOOLS_BUILT_IN_PANELS"],"sources":["../../../../../../../packages/devtools/src/panels.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { DEVTOOLS_BUILT_IN_PANELS } from \"./production/contracts\";\nimport type { DevtoolsMode, DevtoolsPanelInfo } from \"./production/contracts\";\nimport type {\n DevtoolsPanel,\n DevtoolsPanelEntry,\n DevtoolsPanelExport,\n DevtoolsPanelMethod,\n DevtoolsPanelRoute,\n} from \"./types\";\n\n/**\n * A validated panel: file paths are absolute strings and every list is\n * present, so the server never re-checks them per request.\n */\nexport type MountedDevtoolsPanel = {\n id: string;\n title: string;\n view: string;\n routes: readonly (DevtoolsPanelRoute & { method: DevtoolsPanelMethod })[];\n assets: Readonly<Record<string, string>>;\n /** Whether the panel declared itself safe for the production monitor. */\n production: boolean;\n};\n\n/**\n * Ids the dashboard already uses for its own tabs, API segments and URLs. A\n * panel's routes live under `<path>/api/<id>`, so these would collide.\n */\nconst RESERVED_PANEL_IDS = new Set([\n \"account\",\n \"admin\",\n \"agents\",\n \"ai\",\n \"api\",\n \"assets\",\n \"auth\",\n \"background\",\n \"docs\",\n \"errors\",\n \"health\",\n \"instances\",\n \"jobs\",\n \"logs\",\n \"mail\",\n \"mails\",\n \"panels\",\n \"queries\",\n \"requests\",\n \"resources\",\n \"routes\",\n \"stream\",\n]);\n\nconst PANEL_ID = /^[a-z][a-z0-9-]*$/;\nconst ASSET_NAME = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;\nconst METHODS = new Set<DevtoolsPanelMethod>([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/** Content types for the files a panel may serve; anything else is sent as bytes. */\nconst CONTENT_TYPES: Record<string, string> = {\n \".js\": \"text/javascript; charset=utf-8\",\n \".mjs\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".json\": \"application/json; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".woff2\": \"font/woff2\",\n};\n\n/** The content type a panel file is served with, from its served name. */\nexport function panelContentType(name: string): string {\n return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** An absolute file path from a path or `file:` URL, or `undefined` for anything else. */\nfunction toFilePath(value: unknown): string | undefined {\n if (value instanceof URL) return value.protocol === \"file:\" ? fileURLToPath(value) : undefined;\n if (typeof value !== \"string\" || value === \"\") return undefined;\n if (value.startsWith(\"file:\")) return fileURLToPath(value);\n\n return path.isAbsolute(value) ? value : undefined;\n}\n\nfunction isFile(file: string): boolean {\n return existsSync(file) && statSync(file).isFile();\n}\n\n/**\n * Validates `value` as a panel and returns it ready to mount. Throws an\n * error that names the panel and what to change; `taken` maps the ids\n * already registered to their titles and receives this panel's id.\n */\nexport function checkDevtoolsPanel(\n value: unknown,\n taken: Map<string, string>,\n): MountedDevtoolsPanel {\n const panel = (value ?? {}) as Partial<DevtoolsPanel>;\n const id = panel.id;\n\n if (typeof id !== \"string\" || !PANEL_ID.test(id)) {\n throw new Error(\n `A devtools panel needs an \"id\" of lower-case letters, digits and dashes that starts with a letter; got ${JSON.stringify(id)}.`,\n );\n }\n\n if (RESERVED_PANEL_IDS.has(id)) {\n throw new Error(\n `Devtools panel id \"${id}\" is used by the dashboard itself; give the panel another id.`,\n );\n }\n\n const existing = taken.get(id);\n\n if (existing !== undefined) {\n throw new Error(\n `Devtools panel id \"${id}\" is already registered by the \"${existing}\" panel; each panel needs its own id.`,\n );\n }\n\n if (typeof panel.title !== \"string\" || panel.title.trim() === \"\") {\n throw new Error(`Devtools panel \"${id}\" needs a \"title\" for its tab.`);\n }\n\n const view = toFilePath(panel.view);\n\n if (view === undefined) {\n throw new Error(\n `Devtools panel \"${id}\" needs a \"view\": an absolute path or file: URL of its browser module.`,\n );\n }\n\n if (!isFile(view)) {\n throw new Error(`The view module of devtools panel \"${id}\" was not found at ${view}.`);\n }\n\n // Two routes on one method and path would make the server refuse to start.\n const seen = new Set<string>();\n const routes = (panel.routes ?? []).map((route) => {\n const method = route.method ?? \"GET\";\n\n if (!METHODS.has(method)) {\n throw new Error(\n `Devtools panel \"${id}\" has a route with method \"${String(method)}\"; use GET, POST, PUT, PATCH or DELETE.`,\n );\n }\n\n if (typeof route.path !== \"string\" || (route.path !== \"\" && !route.path.startsWith(\"/\"))) {\n throw new Error(\n `Devtools panel \"${id}\" has a route path ${JSON.stringify(route.path)}; use \"\" or a path starting with \"/\".`,\n );\n }\n\n if (typeof route.handler !== \"function\") {\n throw new Error(`Devtools panel \"${id}\" route ${method} \"${route.path}\" has no handler.`);\n }\n\n if (seen.has(`${method} ${route.path}`)) {\n throw new Error(\n `Devtools panel \"${id}\" lists route ${method} \"${route.path}\" twice; keep one.`,\n );\n }\n\n seen.add(`${method} ${route.path}`);\n\n return { ...route, method };\n });\n\n const assets: Record<string, string> = {};\n\n for (const [name, source] of Object.entries(panel.assets ?? {})) {\n if (!ASSET_NAME.test(name) || name === \"view.js\") {\n throw new Error(\n `Devtools panel \"${id}\" has an asset named ${JSON.stringify(name)}; use a plain file name other than \"view.js\".`,\n );\n }\n\n const file = toFilePath(source);\n\n if (file === undefined || !isFile(file)) {\n throw new Error(\n `The asset \"${name}\" of devtools panel \"${id}\" was not found at ${String(source)}; give an absolute path or file: URL.`,\n );\n }\n\n assets[name] = file;\n }\n\n taken.set(id, panel.title);\n\n return { id, title: panel.title, view, routes, assets, production: panel.production === true };\n}\n\n/** Validates a list of panels; the first invalid or duplicate one throws. */\nexport function checkDevtoolsPanels(panels: readonly unknown[]): MountedDevtoolsPanel[] {\n const taken = new Map<string, string>();\n\n return panels.map((panel) => checkDevtoolsPanel(panel, taken));\n}\n\n/** Hooks `loadDevtoolsPanels` uses; replaced in specs. */\nexport type LoadDevtoolsPanelsOptions = {\n /** The app's root directory: bare specifiers resolve from here, `./` paths are relative to it. */\n root: string;\n /** Receives one line per entry that could not be loaded or was rejected. */\n warn: (message: string) => void;\n /** Ids already taken (the built-in panels), mapped to their titles. */\n taken?: ReadonlyMap<string, string>;\n /** Imports a module URL or specifier; defaults to a dynamic `import()`. */\n importModule?: (specifier: string) => Promise<unknown>;\n /** Where the dashboard runs; panel factories receive it as `context.mode`. @default \"development\" */\n mode?: DevtoolsMode;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n\n/** What is wrong with a `[specifier, options]` entry, or `undefined` when it is valid. */\nfunction tupleProblem(entry: readonly unknown[]): string | undefined {\n if (entry.length !== 2) {\n return `it has ${entry.length} item(s); use exactly [specifier, options]`;\n }\n\n if (typeof entry[0] !== \"string\" || entry[0] === \"\") {\n return `its first item is ${JSON.stringify(entry[0])}; use the module specifier as a string`;\n }\n\n if (!isPlainObject(entry[1])) {\n return `its second item is not a plain object; pass the options as { name: value }`;\n }\n\n return undefined;\n}\n\n/** The URL or specifier to import for a `panels` entry. */\nfunction resolvePanelSpecifier(entry: string, root: string): string {\n if (entry.startsWith(\"./\") || entry.startsWith(\"../\") || path.isAbsolute(entry)) {\n return pathToFileURL(path.resolve(root, entry)).href;\n }\n\n return resolveFromNodeModules(entry, root) ?? resolveWithRequire(entry, root) ?? entry;\n}\n\n/** Picks the file an `exports` target names: `import`, then `default`, then `node`. */\nfunction exportTarget(target: unknown): string | undefined {\n if (typeof target === \"string\") return target;\n\n if (Array.isArray(target)) {\n for (const item of target) {\n const found = exportTarget(item);\n\n if (found !== undefined) return found;\n }\n\n return undefined;\n }\n\n if (target !== null && typeof target === \"object\") {\n const conditions = target as Record<string, unknown>;\n\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const found = exportTarget(conditions[condition]);\n\n if (found !== undefined) return found;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a package specifier by looking it up in the `node_modules` folders\n * above the app root and reading its `exports` map. `createRequire().resolve`\n * cannot do this for a package that only has an `import` condition.\n */\nfunction resolveFromNodeModules(entry: string, root: string): string | undefined {\n const parts = entry.split(\"/\");\n const nameLength = entry.startsWith(\"@\") ? 2 : 1;\n const name = parts.slice(0, nameLength).join(\"/\");\n const subpath = parts.length > nameLength ? `./${parts.slice(nameLength).join(\"/\")}` : \".\";\n\n if (!name) return undefined;\n\n let directory = path.resolve(root);\n\n for (;;) {\n const packageDirectory = path.join(directory, \"node_modules\", name);\n const manifestFile = path.join(packageDirectory, \"package.json\");\n\n if (existsSync(manifestFile)) {\n try {\n const manifest = JSON.parse(readFileSync(manifestFile, \"utf8\")) as {\n exports?: unknown;\n main?: string;\n };\n const exported = manifest.exports;\n const map =\n exported !== null && typeof exported === \"object\" && !Array.isArray(exported)\n ? (exported as Record<string, unknown>)\n : undefined;\n const hasSubpaths =\n map !== undefined && Object.keys(map).some((key) => key.startsWith(\".\"));\n const target =\n exported === undefined\n ? subpath === \".\"\n ? (manifest.main ?? \"index.js\")\n : subpath\n : hasSubpaths\n ? exportTarget(map?.[subpath])\n : subpath === \".\"\n ? exportTarget(exported)\n : undefined;\n\n if (target === undefined) return undefined;\n\n const file = path.resolve(packageDirectory, target);\n\n return isFile(file) ? pathToFileURL(file).href : undefined;\n } catch {\n return undefined;\n }\n }\n\n const parent = path.dirname(directory);\n\n if (parent === directory) return undefined;\n\n directory = parent;\n }\n}\n\n/** The `require` resolution, for packages the `node_modules` lookup does not understand. */\nfunction resolveWithRequire(entry: string, root: string): string | undefined {\n try {\n return pathToFileURL(createRequire(path.join(root, \"package.json\")).resolve(entry)).href;\n } catch {\n return undefined;\n }\n}\n\n/** The panels a module's default export describes. */\nasync function panelsOf(\n exported: DevtoolsPanelExport,\n root: string,\n mode: DevtoolsMode,\n panelOptions: Readonly<Record<string, unknown>> = {},\n): Promise<readonly unknown[]> {\n const value =\n typeof exported === \"function\" ? await exported({ ...panelOptions, root, mode }) : exported;\n\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Loads the devtools `panels` option: imports each module entry, reads its\n * default export, and validates every panel. An entry that fails to load and\n * a panel that is invalid or reuses an id are reported through `warn` and\n * skipped, so one broken panel never stops the dashboard.\n */\nexport async function loadDevtoolsPanels(\n entries: readonly DevtoolsPanelEntry[],\n options: LoadDevtoolsPanelsOptions,\n): Promise<MountedDevtoolsPanel[]> {\n // `src/config/devtools.ts` is a plain object with no types: a single string would be read letter by letter.\n if (!Array.isArray(entries as unknown)) {\n options.warn(\n `The devtools \"panels\" option must be a list, such as panels: [\"@warlock.js/grimoire/devtools\"]; got ${JSON.stringify(entries)}. No panel was added.`,\n );\n\n return [];\n }\n\n const importModule = options.importModule ?? ((specifier: string) => import(specifier));\n const mode = options.mode ?? \"development\";\n const taken = new Map<string, string>(options.taken ?? []);\n const panels: MountedDevtoolsPanel[] = [];\n\n for (const entry of entries) {\n let candidates: readonly unknown[];\n\n try {\n if (Array.isArray(entry as unknown)) {\n const problem = tupleProblem(entry as readonly unknown[]);\n\n if (problem !== undefined) {\n options.warn(\n `Devtools panels entry ${JSON.stringify(entry)} is invalid: ${problem}. Example: [\"@warlock.js/grimoire/devtools\", { ttlMs: 60000 }]. The entry was not added.`,\n );\n continue;\n }\n }\n\n if (typeof entry === \"string\" || Array.isArray(entry as unknown)) {\n const [specifier, panelOptions] =\n typeof entry === \"string\"\n ? [entry, undefined]\n : (entry as readonly [string, Record<string, unknown>]);\n const module = (await importModule(resolvePanelSpecifier(specifier, options.root))) as {\n default?: DevtoolsPanelExport;\n };\n\n if (module.default === undefined) {\n throw new Error(\"the module has no default export\");\n }\n\n candidates = await panelsOf(module.default, options.root, mode, panelOptions);\n } else {\n candidates = [entry];\n }\n } catch (error) {\n options.warn(\n `Devtools panel module \"${String(Array.isArray(entry as unknown) ? (entry as readonly unknown[])[0] : entry)}\" could not be loaded: ${describe(error)}. Check that it is installed and listed correctly in the devtools \"panels\" option.`,\n );\n continue;\n }\n\n for (const candidate of candidates) {\n try {\n panels.push(checkDevtoolsPanel(candidate, taken));\n } catch (error) {\n options.warn(`${describe(error)} The panel was not added.`);\n }\n }\n }\n\n return panels;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** What `productionPanels` decides. */\nexport type DevtoolsProductionPanels = {\n /** Built-in tab ids shown, in display order. */\n builtIn: string[];\n /** Package panels shown. */\n panels: MountedDevtoolsPanel[];\n};\n\n/**\n * Which tabs the production monitor shows. A built-in tab follows\n * `DEVTOOLS_BUILT_IN_PANELS` unless `overrides[id]` says otherwise. A package\n * panel (the Processes panel included) shows when it declares\n * `production: true` or `overrides[id]` is `true`; `overrides[id]: false` turns\n * any tab off.\n */\nexport function productionPanels(\n packagePanels: readonly MountedDevtoolsPanel[],\n overrides: Readonly<Record<string, boolean>> = {},\n): DevtoolsProductionPanels {\n const builtIn = DEVTOOLS_BUILT_IN_PANELS.filter((tab) => overrides[tab.id] ?? tab.production).map(\n (tab) => tab.id,\n );\n const panels = packagePanels.filter((panel) => overrides[panel.id] ?? panel.production);\n\n return { builtIn, panels };\n}\n\n/**\n * The tab list `GET api/panels` answers with: the built-in tabs in\n * `builtIn` (default: every one), in display order, then the package panels\n * in registration order.\n */\nexport function listPanelInfos(\n panels: readonly Pick<MountedDevtoolsPanel, \"id\" | \"title\">[],\n builtIn?: readonly string[],\n): DevtoolsPanelInfo[] {\n const tabs: DevtoolsPanelInfo[] = DEVTOOLS_BUILT_IN_PANELS.filter(\n (tab) => builtIn === undefined || builtIn.includes(tab.id),\n ).map((tab) => ({ id: tab.id, title: tab.title, type: \"built-in\" as const }));\n\n for (const panel of panels)\n tabs.push({ id: panel.id, title: panel.title, type: \"package\" as const });\n\n return tabs;\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,qCAAqB,IAAI,IAAI;CAC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M;CAAmB,CAAC;CAE1E,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"server-ykxsOwob.cjs","names":["listPanelInfos","checkDevtoolsPanels","processesDevtoolsPanel"],"sources":["../../../../../../../packages/devtools/src/server/background-routes.ts","../../../../../../../packages/devtools/src/server/guard.ts","../../../../../../../packages/devtools/src/server/session-routes.ts","../../../../../../../packages/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, 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/** Host names that always reach this machine, so DNS cannot be pointed at them. */\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/** Headers a proxy or tunnel adds; their presence means the loopback peer is not the visitor. */\nconst PROXY_HEADERS = [\"x-forwarded-for\", \"x-forwarded-host\", \"x-real-ip\", \"forwarded\"] as const;\n\n/** At most this many distinct refusals are logged per boot. */\nconst MAX_WARNINGS = 20;\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/** The lower-cased host name of a `Host` header value, without its port (`[::1]` keeps its brackets). */\nexport function hostnameOf(host: string): string {\n const value = host.trim().toLowerCase();\n\n if (value.startsWith(\"[\")) {\n const end = value.indexOf(\"]\");\n\n return end === -1 ? \"\" : value.slice(0, end + 1);\n }\n\n const colon = value.indexOf(\":\");\n const name = colon === -1 ? value : value.slice(0, colon);\n\n return name.endsWith(\".\") ? name.slice(0, -1) : name;\n}\n\n/**\n * Whether `hostname` is a loopback name or one of `allowedHosts`. An entry\n * starting with `.` matches that domain and every subdomain of it.\n */\nexport function isAllowedDevtoolsHost(\n hostname: string,\n allowedHosts: readonly string[] = [],\n): boolean {\n if (!hostname) return false;\n if (LOOPBACK_HOSTS.has(hostname) || hostname.endsWith(\".localhost\")) return true;\n\n return allowedHosts.some((entry) => {\n const allowed = entry.trim().toLowerCase();\n\n if (allowed.startsWith(\".\")) {\n return hostname === allowed.slice(1) || hostname.endsWith(allowed);\n }\n\n return hostname === allowed;\n });\n}\n\n/** The `Origin` header's host name, `\"\"` for `null` or an unparsable value. */\nfunction originHostname(origin: string): string {\n try {\n return new URL(origin).hostname.toLowerCase();\n } catch {\n return \"\";\n }\n}\n\n/**\n * Why `request` must be refused, or `undefined` when it may be served.\n * `\"not-local\"` is the silent case (production, or a remote socket). Beyond a\n * loopback socket, the request must be ADDRESSED to a loopback (or allowed)\n * host, come from such an origin, and not have passed through a proxy: a page\n * whose domain was re-pointed at 127.0.0.1, or a tunnel, also arrives on a\n * loopback socket.\n */\nfunction refusalReason(request: FastifyRequest, deps: MountDevtoolsRoutesDeps): string | undefined {\n if (!deps.isDevelopment() || !isLoopbackAddress(request.socket.remoteAddress)) {\n return \"not-local\";\n }\n\n const allowedHosts = deps.options.allowedHosts ?? [];\n const host = hostnameOf(request.headers.host ?? \"\");\n\n if (!isAllowedDevtoolsHost(host, allowedHosts)) {\n return `Devtools refused a request for host \"${host}\". Open the dashboard on localhost, or add the host to the devtools \"allowedHosts\" option.`;\n }\n\n const origin = request.headers.origin;\n\n if (origin !== undefined && !isAllowedDevtoolsHost(originHostname(origin), allowedHosts)) {\n return `Devtools refused a request from origin \"${origin}\". Only pages served from localhost or a host in the devtools \"allowedHosts\" option may call the dashboard.`;\n }\n\n if (\n !deps.options.allowProxied &&\n PROXY_HEADERS.some((name) => request.headers[name] !== undefined)\n ) {\n return 'Devtools refused a proxied request (it carries a forwarding header). Open the dashboard directly on localhost, or set the devtools \"allowProxied\" option for a local proxy nobody else can reach.';\n }\n\n return undefined;\n}\n\n/**\n * Registers the dev-only, local-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 // One terminal line per distinct refusal, so a misconfigured host is\n // explained once without flooding the log on every poll.\n const warned = new Set<string>();\n\n server.addHook(\"onRequest\", async (request: FastifyRequest, reply: FastifyReply) => {\n const reason = refusalReason(request, deps);\n\n if (reason === undefined) return;\n\n if (reason !== \"not-local\" && !warned.has(reason) && warned.size < MAX_WARNINGS) {\n warned.add(reason);\n deps.warn?.(reason);\n }\n\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","import type { FastifyInstance } from \"fastify\";\nimport { listPanelInfos, type MountedDevtoolsPanel } from \"../panels\";\nimport type { DevtoolsPanelInfo, DevtoolsSessionView } from \"../production/contracts\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\n\n/**\n * The session view of the development dashboard: there are no accounts, the\n * loopback guard is the access control, and the visitor is an admin.\n */\nexport function developmentSessionView(deps: MountDevtoolsRoutesDeps): DevtoolsSessionView {\n return {\n mode: \"development\",\n stage: \"active\",\n account: null,\n role: \"admin\",\n csrf: null,\n expiresAt: null,\n instance: deps.instance ?? null,\n methods: null,\n };\n}\n\n/** The tabs `GET api/panels` lists: the built-in tabs in `deps.builtInPanels` (default all), then the package panels. */\nexport function panelInfos(\n deps: MountDevtoolsRoutesDeps,\n panels: readonly Pick<MountedDevtoolsPanel, \"id\" | \"title\">[],\n): DevtoolsPanelInfo[] {\n return listPanelInfos(panels, deps.builtInPanels);\n}\n\n/**\n * Registers `GET /api/auth/session` (the development view: signed in as an\n * admin, no accounts) and `GET /api/panels`, so the same dashboard shell\n * works in both modes. Production answers these from its own mount.\n */\nexport function registerSessionRoutes(\n server: FastifyInstance,\n deps: MountDevtoolsRoutesDeps,\n panels: readonly MountedDevtoolsPanel[],\n): void {\n server.get(\"/api/auth/session\", async (_request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n\n return developmentSessionView(deps);\n });\n\n server.get(\"/api/panels\", async (_request, reply) => {\n reply.header(\"Cache-Control\", \"no-store\");\n\n return panelInfos(deps, panels);\n });\n}\n","import type { FastifyError, FastifyInstance } from \"fastify\";\nimport { checkDevtoolsPanels } from \"../panels\";\nimport { processesDevtoolsPanel } from \"../process-panel\";\nimport { registerAiRoutes } from \"./ai-routes\";\nimport { registerBackgroundRoutes } from \"./background-routes\";\nimport { registerExplainRoute, registerShapeExplainRoute } from \"./explain-route\";\nimport { registerInsightsRoutes } from \"./insights-routes\";\nimport { registerDevtoolsGuard } from \"./guard\";\nimport { registerLogRoutes } from \"./log-routes\";\nimport { registerMailRoutes } from \"./mail-routes\";\nimport { registerOpenApiRoutes } from \"./openapi-routes\";\nimport { registerPanelRoutes } from \"./panel-routes\";\nimport { registerRequestsRoutes } from \"./requests-routes\";\nimport { registerRouteRoutes } from \"./route-routes\";\nimport { registerSessionRoutes } from \"./session-routes\";\nimport { registerStreamRoute } from \"./stream-route\";\nimport type { MountDevtoolsRoutesDeps } from \"./types\";\nimport { registerUiAssets } from \"./ui-assets\";\n\nexport type { DevtoolsRequestLogSource, 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 — the registered panels' data routes and files included.\n *\n * Throws before mounting anything when a panel is invalid or reuses an id.\n */\nexport function mountDevtoolsRoutes(server: FastifyInstance, deps: MountDevtoolsRoutesDeps): void {\n const panels = checkDevtoolsPanels([\n processesDevtoolsPanel(deps.processPanel),\n ...(deps.panels ?? []),\n ]);\n\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 registerSessionRoutes(instance, deps, panels);\n registerRequestsRoutes(instance, deps);\n registerAiRoutes(instance, deps);\n registerBackgroundRoutes(instance, deps);\n registerMailRoutes(instance, deps);\n registerLogRoutes(instance, deps);\n registerRouteRoutes(instance, deps);\n registerPanelRoutes(instance, panels);\n registerOpenApiRoutes(instance, deps);\n registerExplainRoute(instance, deps);\n registerShapeExplainRoute(instance, deps);\n if (deps.insights) registerInsightsRoutes(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;;;;ACNA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAa;CAAO;AAAkB,CAAC;;AAG3E,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;;AAGlE,MAAM,gBAAgB;CAAC;CAAmB;CAAoB;CAAa;AAAW;;AAGtF,MAAM,eAAe;;;;;;;AAQrB,SAAS,kBAAkB,SAAsC;CAC/D,OAAO,YAAY,UAAa,mBAAmB,IAAI,OAAO;AAChE;;AAGA,SAAgB,WAAW,MAAsB;CAC/C,MAAM,QAAQ,KAAK,KAAK,CAAC,CAAC,YAAY;CAEtC,IAAI,MAAM,WAAW,GAAG,GAAG;EACzB,MAAM,MAAM,MAAM,QAAQ,GAAG;EAE7B,OAAO,QAAQ,KAAK,KAAK,MAAM,MAAM,GAAG,MAAM,CAAC;CACjD;CAEA,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,MAAM,OAAO,UAAU,KA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,wCAAmB,UAAU,IAAI;EACjC,uCAAkB,UAAU,IAAI;EAChC,yCAAoB,UAAU,IAAI;EAClC,yCAAoB,UAAU,MAAM;EACpC,2CAAsB,UAAU,IAAI;EACpC,0CAAqB,UAAU,IAAI;EACnC,+CAA0B,UAAU,IAAI;EACxC,IAAI,KAAK,UAAU,4CAAuB,UAAU,IAAI;EACxD,yCAAoB,UAAU,IAAI;CACpC,GACA,EAAE,QAAQ,KAAK,QAAQ,KAAK,CAC9B;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-UPtTCI2j.cjs","names":["currentRequestId","LogChannel","toSafeValue","currentRequestId","currentRequestId","fileURLToPath","applyRedact","log","currentRequestId","toSafeValue","toSafeValue","createCollector","attachAiSource","attachAgentTraceSource","loadProcessPanel","processesDevtoolsPanel","loadDevtoolsPanels","DEVTOOLS_PRODUCTION_DEFAULTS","checkDevtoolsPanels"],"sources":["../../../../../../../packages/devtools/src/options.ts","../../../../../../../packages/devtools/src/sources/cache-source.ts","../../../../../../../packages/devtools/src/sources/log-source.ts","../../../../../../../packages/devtools/src/sources/mail-source.ts","../../../../../../../packages/devtools/src/caller-location.ts","../../../../../../../packages/devtools/src/sources/query-source.ts","../../../../../../../packages/devtools/src/sources/tracing-source.ts","../../../../../../../packages/devtools/src/devtools-connector.ts","../../../../../../../packages/devtools/src/panel-tokens.ts"],"sourcesContent":["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 {\n path,\n maxRequests,\n nPlusOneThreshold,\n allowedHosts: options.allowedHosts ?? [],\n allowProxied: options.allowProxied ?? false,\n panels: options.panels ?? [],\n ...(options.production === undefined ? {} : { production: options.production }),\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","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\n/**\n * The entry's message as text. `request.log(error)` and friends log an Error\n * (or any value) as the message; kept as is, it reached the dashboard as `{}`.\n */\nfunction messageText(message: unknown): string {\n if (typeof message === \"string\") return message;\n if (message instanceof Error) return `${message.name}: ${message.message}`;\n\n try {\n return JSON.stringify(message) ?? String(message);\n } catch {\n return String(message);\n }\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: messageText(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:\n phase.attrs === undefined\n ? undefined\n : (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 { checkDevtoolsPanels, loadDevtoolsPanels } from \"./panels\";\nimport { loadProcessPanel, processesDevtoolsPanel } from \"./process-panel\";\nimport { createCollector } from \"./collector\";\nimport { resolveDevtoolsOptions } from \"./options\";\nimport { DEVTOOLS_PRODUCTION_DEFAULTS } from \"./production/options\";\nimport type { DevtoolsRequestLogSource, DevtoolsRouteRow, MountDevtoolsRoutesDeps } from \"./server\";\nimport { attachAgentTraceSource } from \"./sources/agent-trace-source\";\nimport { attachAiSource } from \"./sources/ai-source\";\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/**\n * The app's `src/config/devtools.ts`, or `{}` when there is none (or the\n * config store cannot be read, which must never stop the dev server).\n */\nfunction readConfiguredOptions(readConfig: () => { get(name: string): unknown }): DevtoolsOptions {\n try {\n const value = readConfig().get(\"devtools\");\n\n return value !== null && typeof value === \"object\" ? (value as DevtoolsOptions) : {};\n } catch {\n return {};\n }\n}\n\n/** Options accepted by `devtoolsConnector()`. */\nexport type DevtoolsConnectorOptions = DevtoolsOptions;\n\n/**\n * Construct the devtools connector.\n *\n * Outside development, `boot()` checks `Application.runtimeStrategy` and\n * `devtools.production.enabled`: unless both say production, it logs one\n * warning and returns without mounting a route or subscribing to anything.\n * With `enabled: true` in production it starts the signed-in production\n * monitor (`bootProductionDevtools`), which refuses to boot when its\n * configuration is incomplete. In development it attaches every source\n * (tracing, queries, cache, mail, logs), loads the panels listed in the\n * `panels` option, then mounts the dashboard's routes on the HTTP server —\n * before it starts listening, the only point in the boot sequence where\n * mounting is possible (see `queue/src/dashboard-boot.ts` for the same\n * constraint).\n *\n * In development apps don't call this: `warlock dev` registers it\n * automatically when the package is installed (`warlock add devtools`). To\n * run the production monitor, list `devtoolsConnector()` in\n * `warlock.config.ts > connectors` (and keep the package in `dependencies`).\n * Options come from the app's `src/config/devtools.ts` (a plain object, no\n * import of this package); options passed here win over it.\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 core = await import(\"@warlock.js/core\");\n const { Application, getHttpServer } = core;\n const { log } = await import(\"@warlock.js/logger\");\n\n const resolved = resolveDevtoolsOptions({\n ...readConfiguredOptions(() => core.config),\n ...options,\n });\n\n if (Application.runtimeStrategy === \"production\" && resolved.production?.enabled === true) {\n disposers.push(await bootProduction(core, log, resolved));\n active = true;\n\n return;\n }\n\n if (Application.runtimeStrategy !== \"development\") {\n log.warn(\n \"devtools\",\n \"disabled\",\n \"@warlock.js/devtools only runs in development unless devtools.production.enabled is true; it is not mounted\",\n );\n return;\n }\n\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 ai = await attachAiSource(resolved.maxRequests);\n disposers.push(ai.dispose);\n\n const agentTraces = await attachAgentTraceSource();\n disposers.push(agentTraces.dispose);\n\n const { mountDevtoolsRoutes } = await import(\"./server\");\n const postmanBuilder = await findPostmanBuilder();\n const requestLog = await findRequestLogSource();\n const processPanel = await loadProcessPanel();\n const builtIn = processesDevtoolsPanel(processPanel);\n // A panel that fails to load or reuses an id is reported and left out;\n // it never stops the dashboard or the app.\n const panels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n });\n\n const insightsWiring = await wireDevelopmentInsights(collector, resolved, log, disposers);\n\n mountDevtoolsRoutes(getHttpServer(), {\n collector,\n ai,\n agentTraces,\n ...(processPanel ? { processPanel } : {}),\n panels,\n options: resolved,\n ...insightsWiring,\n requestLog,\n isDevelopment: () => Application.runtimeStrategy === \"development\",\n warn: (message) => log.warn(\"devtools\", \"refused\", message),\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\ntype ConnectorLogger = {\n info: (module: string, action: string, message: string) => unknown;\n warn: (module: string, action: string, message: string) => unknown;\n error: (module: string, action: string, message: string) => unknown;\n};\n\n/**\n * Development: the statistics, resources, health and jobs behind the\n * Resources, Queries (statistics), Routes (statistics), Errors, Health and\n * Jobs tabs. Wrapped as a whole: when anything fails to start, one line is\n * logged and the dashboard mounts without insights (those tabs then say they\n * are not available). It never stops the dashboard.\n */\nasync function wireDevelopmentInsights(\n collector: ReturnType<typeof createCollector>,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n log: ConnectorLogger,\n disposers: DevtoolsDisposer[],\n): Promise<Pick<MountDevtoolsRoutesDeps, \"instance\" | \"insights\" | \"explainShape\">> {\n const stops: DevtoolsDisposer[] = [];\n\n try {\n const capture = await import(\"./production/capture\");\n const insights = await import(\"./production/insights\");\n const instance = insights.createInstanceInfo();\n const queries = capture.createQueryStats({\n maxShapes: DEVTOOLS_PRODUCTION_DEFAULTS.maxShapes,\n instance: instance.id,\n });\n const routes = capture.createRouteStats({\n maxRoutes: DEVTOOLS_PRODUCTION_DEFAULTS.maxRoutes,\n instance: instance.id,\n });\n const errors = capture.createErrorGroups({\n maxGroups: DEVTOOLS_PRODUCTION_DEFAULTS.maxErrorGroups,\n });\n const logs = capture.createRecentLogs({ maxEntries: 200 });\n\n stops.push(\n capture.attachDevelopmentStats(collector, {\n queries,\n routes,\n errors,\n logs,\n nPlusOneThreshold: resolved.nPlusOneThreshold,\n }),\n );\n\n const resources = insights.createResourceMonitor();\n const health = insights.createHealthHistory();\n\n resources.start();\n health.start();\n stops.push(\n () => resources.stop(),\n () => health.stop(),\n );\n\n const reporter = insights.createLocalReporter({\n instance,\n resources,\n health,\n jobs: insights.createJobsReader(),\n queries,\n routes,\n errors,\n logs,\n counters: null,\n });\n const explainShape = capture.createShapeExplainer({\n queries,\n executing: false,\n instance: instance.id,\n });\n\n disposers.push(...stops);\n\n return { instance, insights: insights.createLocalInsights(reporter), explainShape };\n } catch (error) {\n for (const stop of stops) {\n try {\n stop();\n } catch {\n // Cleanup after a failed start must not hide the reason.\n }\n }\n\n log.warn(\n \"devtools\",\n \"insights-failed\",\n `devtools' statistics could not start, so the Resources, Queries, Routes, Errors, Health and Jobs tabs are not available: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return {};\n }\n}\n\n/**\n * Starts the production monitor: loads the panels in production mode and\n * hands everything to `bootProductionDevtools`, which refuses to boot (throws\n * `DevtoolsProductionConfigError`) when the configuration is incomplete.\n */\nasync function bootProduction(\n core: typeof import(\"@warlock.js/core\"),\n log: ConnectorLogger,\n resolved: ReturnType<typeof resolveDevtoolsOptions>,\n): Promise<DevtoolsDisposer> {\n const { bootProductionDevtools } = await import(\"./production/boot\");\n const requestLog = await findRequestLogSource();\n // The Processes panel reads an app file; load it only when the project turned that tab on.\n const processPanel =\n resolved.production?.panels?.processes === true ? await loadProcessPanel() : undefined;\n const builtIn = processesDevtoolsPanel(processPanel);\n const packagePanels = await loadDevtoolsPanels(resolved.panels ?? [], {\n root: \"rootPath\" in core ? core.rootPath() : process.cwd(),\n warn: (message) => log.warn(\"devtools\", \"panel\", message),\n taken: new Map([[builtIn.id, builtIn.title]]),\n mode: \"production\",\n });\n // `warlock start` registers no development OpenAPI provider: the API tab, when turned on, builds its own.\n const { createProductionOpenApi } = await import(\"./production/openapi\");\n const openApi = createProductionOpenApi(core);\n\n return bootProductionDevtools({\n options: resolved,\n env: process.env,\n server: core.getHttpServer(),\n panels: [...checkDevtoolsPanels([builtIn]), ...packagePanels],\n routes: {\n ...(processPanel ? { processPanel } : {}),\n ...(requestLog ? { requestLog } : {}),\n listRoutes: () => listRoutes(),\n getOpenApiDocument: openApi.getOpenApiDocument,\n getPostmanCollection: openApi.getPostmanCollection,\n },\n log,\n });\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 * Looks up core's persistent request log reader. Older cores do not export\n * it; the dashboard then shows the in-memory requests only. Core is imported\n * lazily, like the builders above.\n */\nasync function findRequestLogSource(): Promise<DevtoolsRequestLogSource | undefined> {\n try {\n const core: Record<string, unknown> = await import(\"@warlock.js/core\");\n const { listRequestLogs, getRequestLog, requestLogToCurl, compileRequestLogFilter } = core;\n\n if (\n typeof listRequestLogs !== \"function\" ||\n typeof getRequestLog !== \"function\" ||\n typeof requestLogToCurl !== \"function\" ||\n typeof compileRequestLogFilter !== \"function\"\n ) {\n return undefined;\n }\n\n return {\n list: (filter) => listRequestLogs(filter),\n get: (id) => getRequestLog(id),\n curl: (record, baseUrl) => requestLogToCurl(record, baseUrl),\n compile: (filter) => compileRequestLogFilter(filter),\n };\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","/**\n * The CSS variables the dashboard defines for package panels, in both themes.\n *\n * A package panel's stylesheet may use only these variables, plus variables it\n * defines itself (in the same file). Anything else is undefined in the\n * dashboard and renders as the browser default, which is how a panel ends up\n * with unreadable text. The dashboard's own colours are checked for contrast\n * (4.5:1 for the text tokens on `--background` and `--card`) in both themes.\n */\nexport const DEVTOOLS_PANEL_TOKENS: readonly string[] = [\n \"--background\",\n \"--foreground\",\n \"--card\",\n \"--card-foreground\",\n \"--popover\",\n \"--popover-foreground\",\n \"--primary\",\n \"--primary-foreground\",\n \"--secondary\",\n \"--secondary-foreground\",\n \"--muted\",\n \"--muted-foreground\",\n \"--accent\",\n \"--accent-foreground\",\n \"--destructive\",\n \"--border\",\n \"--input\",\n \"--ring\",\n \"--radius\",\n \"--brand\",\n \"--brand-foreground\",\n \"--success\",\n \"--warning\",\n \"--info\",\n \"--chart-1\",\n \"--chart-2\",\n \"--chart-3\",\n \"--chart-4\",\n \"--chart-5\",\n];\n"],"mappings":";;;;;;;;;;;;AAGA,SAAgB,uBAAuB,UAA2B,CAAC,GAA4B;CAC7F,MAAM,QAAQ,QAAQ,QAAQ,aAAY,CAAE,QAAQ,QAAQ,EAAE;CAC9D,MAAM,cAAc,QAAQ,eAAe;CAC3C,MAAM,oBAAoB,QAAQ,qBAAqB;CAEvD,IAAI,CAAC,QAAQ,CAAC,KAAK,WAAW,GAAG,GAC/B,MAAM,IAAI,MAAM,uEAAmE;CAGrF,IAAI,cAAc,GAChB,MAAM,IAAI,MAAM,qDAAmD;CAGrE,IAAI,oBAAoB,GACtB,MAAM,IAAI,MAAM,2DAAyD;CAG3E,OAAO;EACL;EACA;EACA;EACA,cAAc,QAAQ,gBAAgB,CAAC;EACvC,cAAc,QAAQ,gBAAgB;EACtC,QAAQ,QAAQ,UAAU,CAAC;EAC3B,GAAI,QAAQ,eAAe,SAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;CAC/E;AACF;;;;;ACzBA,MAAM,cAAc;CAAC;CAAO;CAAQ;CAAO;CAAW;CAAe;AAAS;;;;;;AAgB9E,eAAsB,kBAAkB,WAAyD;CAC/F,IAAI;CAKJ,IAAI;EACF,CAAC,CAAE,SAAU,MAAM,OAAO;CAC5B,QAAQ;EACN,aAAa,CAAC;CAChB;CAEA,MAAM,WAAW,YAAY,KAAK,SAAS;EACzC,MAAM,WAAW,SAAyB;GACxC,MAAM,YAAoC;IACxC;IACA,QAAQ,KAAK;IACb,KAAK,KAAK;IACV,MAAM,KAAK;IACX,MAAM,KAAK;IACX,IA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