@warlock.js/core 5.36.0 → 5.37.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 (76) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/esm/cli/commands/migrate.command.mjs +10 -0
  3. package/esm/cli/commands/migrate.command.mjs.map +1 -1
  4. package/esm/cli/commands/release/release-command.action.mjs +245 -0
  5. package/esm/cli/commands/release/release-command.action.mjs.map +1 -0
  6. package/esm/cli/commands/release.command.mjs +66 -0
  7. package/esm/cli/commands/release.command.mjs.map +1 -0
  8. package/esm/cli/framework-cli-commands.mjs +2 -0
  9. package/esm/cli/framework-cli-commands.mjs.map +1 -1
  10. package/esm/database/migrate-action.mjs +24 -2
  11. package/esm/database/migrate-action.mjs.map +1 -1
  12. package/esm/dev-server/loader/load-hook.d.mts.map +1 -1
  13. package/esm/dev-server/loader/load-hook.mjs +6 -0
  14. package/esm/dev-server/loader/load-hook.mjs.map +1 -1
  15. package/esm/index.d.mts +3 -2
  16. package/esm/index.mjs +2 -2
  17. package/esm/production/route-registration-snapshot.mjs +10 -3
  18. package/esm/production/route-registration-snapshot.mjs.map +1 -1
  19. package/esm/release/activate.mjs +261 -0
  20. package/esm/release/activate.mjs.map +1 -0
  21. package/esm/release/candidate.mjs +107 -0
  22. package/esm/release/candidate.mjs.map +1 -0
  23. package/esm/release/cascade-migration-provider.mjs +32 -0
  24. package/esm/release/cascade-migration-provider.mjs.map +1 -0
  25. package/esm/release/config.mjs +60 -0
  26. package/esm/release/config.mjs.map +1 -0
  27. package/esm/release/gate.mjs +67 -0
  28. package/esm/release/gate.mjs.map +1 -0
  29. package/esm/release/migrations-proof.mjs +100 -0
  30. package/esm/release/migrations-proof.mjs.map +1 -0
  31. package/esm/release/prune.mjs +42 -0
  32. package/esm/release/prune.mjs.map +1 -0
  33. package/esm/release/report.mjs +25 -0
  34. package/esm/release/report.mjs.map +1 -0
  35. package/esm/release/runner.mjs +55 -0
  36. package/esm/release/runner.mjs.map +1 -0
  37. package/esm/release/semver.mjs +53 -0
  38. package/esm/release/semver.mjs.map +1 -0
  39. package/esm/release/stage.mjs +122 -0
  40. package/esm/release/stage.mjs.map +1 -0
  41. package/esm/release/store.mjs +131 -0
  42. package/esm/release/store.mjs.map +1 -0
  43. package/esm/release/types.d.mts +102 -0
  44. package/esm/release/types.d.mts.map +1 -0
  45. package/esm/release/verify.mjs +94 -0
  46. package/esm/release/verify.mjs.map +1 -0
  47. package/esm/router/index.d.mts +2 -2
  48. package/esm/router/index.mjs +2 -2
  49. package/esm/router/router.d.mts +4 -2
  50. package/esm/router/router.d.mts.map +1 -1
  51. package/esm/router/router.mjs +13 -5
  52. package/esm/router/router.mjs.map +1 -1
  53. package/esm/router/types.d.mts +26 -0
  54. package/esm/router/types.d.mts.map +1 -1
  55. package/esm/router/unguarded-route-diagnostics.d.mts +6 -0
  56. package/esm/router/unguarded-route-diagnostics.d.mts.map +1 -1
  57. package/esm/router/unguarded-route-diagnostics.mjs +10 -2
  58. package/esm/router/unguarded-route-diagnostics.mjs.map +1 -1
  59. package/esm/tooling/check/security-conventions.mjs +19 -1
  60. package/esm/tooling/check/security-conventions.mjs.map +1 -1
  61. package/esm/tooling/inspect/collect-routes.mjs +3 -2
  62. package/esm/tooling/inspect/collect-routes.mjs.map +1 -1
  63. package/esm/validation/init.mjs +11 -4
  64. package/esm/validation/init.mjs.map +1 -1
  65. package/esm/validation/translate-rule.mjs +63 -0
  66. package/esm/validation/translate-rule.mjs.map +1 -0
  67. package/esm/warlock-config/index.d.mts +2 -1
  68. package/esm/warlock-config/types.d.mts +8 -0
  69. package/esm/warlock-config/types.d.mts.map +1 -1
  70. package/llms-full.txt +94 -2
  71. package/llms.txt +1 -0
  72. package/package.json +13 -13
  73. package/skills/deploy-release/SKILL.md +76 -0
  74. package/skills/index.md +1 -1
  75. package/skills/register-route/SKILL.md +12 -0
  76. package/skills/warlock-conventions/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"router.mjs","names":["configAccessor","config"],"sources":["../../../../../../../../packages/core/src/router/router.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport { WarlockError } from \"../errors/warlock-error\";\nimport type { FastifyStaticOptions } from \"@fastify/static\";\nimport { ltrim, merge, toCamelCase, trim } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { container } from \"../container\";\nimport { registerLazyStatic } from \"../http/lazy-static\";\nimport { buildCorsOptions } from \"../http/build-cors-options\";\nimport { Request } from \"../http/request\";\nimport { buildRequestLogSnapshot } from \"../http/request-log-snapshot\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../http/tracing\";\nimport { describeRouteForLog } from \"./describe-route-for-log\";\nimport { logRequestLifecycle } from \"./log-request-lifecycle\";\nimport {\n forgetPositionalHandlerSuspects,\n inspectHandlerSignature,\n reportPositionalHandlerSuspects,\n} from \"./positional-handler-diagnostics\";\nimport { reportUnguardedMutatingRoutes } from \"./unguarded-route-diagnostics\";\nimport { config as configAccessor } from \"../config/config-getter\";\nimport { normalizeRoutePath } from \"./normalize-route-path\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { resolveRouteRateLimit, resolveStaticRateLimit } from \"./resolve-route-rate-limit\";\nimport { RouteNameTakenError } from \"./route-name-taken-error\";\nimport { DEV_DISPATCH_METHODS, buildNotFoundBody, createDevRateLimiter } from \"./dev-dispatch\";\nimport { RouteRegistry } from \"./route-registry\";\nimport { routeNameMethodSuffix } from \"./route-name-method-suffix\";\nimport type {\n GroupedRoutesOptions,\n HttpContext,\n NamedApiRoute,\n NamedApiRoutesOptions,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n StaticMountOptions,\n} from \"./types\";\n\n/**\n * A Fastify lifecycle hook as it may be declared in a route's `serverOptions`.\n * Fastify accepts a single hook or an array in either position.\n */\ntype RouteLifecycleHook = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => unknown | Promise<unknown>;\n\n/**\n * The pre-handler phases the dev server forwards from a route's `serverOptions`.\n *\n * These are the admission-control phases and they share the `(request, reply)`\n * signature. `preParsing` is deliberately absent — it must return the payload\n * stream, so forwarding it generically would corrupt the body rather than\n * guard it. `bodyLimit` cannot be forwarded at all; Fastify reads it at\n * registration time and no hook can bound a body already being parsed.\n */\nconst FORWARDED_ROUTE_PHASES = [\"onRequest\", \"preValidation\", \"preHandler\"] as const;\n\ntype ForwardedRoutePhase = (typeof FORWARDED_ROUTE_PHASES)[number];\n\n/**\n * The route the dev dispatcher matched, stashed on the request so the hooks and\n * the wildcard handler all act on one match rather than each matching again.\n */\ntype DevMatchedRoute = { route: Route; params: Record<string, string> };\n\ntype DevDispatchRequest = FastifyRequest & {\n matchedDevRoute?: DevMatchedRoute;\n};\n\nfunction toHookList(\n hook: RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n): RouteLifecycleHook[] {\n if (!hook) {\n return [];\n }\n\n return Array.isArray(hook) ? hook : [hook];\n}\n\n/**\n * Run a matched route's hooks for one phase.\n *\n * Returning the reply is how an async Fastify hook signals that it has answered\n * the request; the chain must stop there, so the value is propagated rather\n * than discarded.\n */\nasync function runRouteHooks(\n route: Route,\n phase: ForwardedRoutePhase,\n request: FastifyRequest,\n reply: FastifyReply,\n) {\n const hooks = toHookList(\n route.serverOptions?.[phase] as RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n );\n\n for (const hook of hooks) {\n const outcome = await hook(request, reply);\n\n if (outcome === reply) {\n return reply;\n }\n }\n\n return undefined;\n}\n\n/**\n * Bound functions do not inherit static properties, so the handler metadata that\n * documentation and typings read (`responseSchema`) is copied onto the bound copy.\n */\nfunction copyResponseSchema(source: unknown, target: RequestHandler): void {\n const responseSchema = (source as RequestHandler | undefined)?.responseSchema;\n\n if (responseSchema) {\n target.responseSchema = responseSchema;\n }\n}\n\n/**\n * Bind a restful resource method to its resource, keeping its `responseSchema`.\n */\nfunction bindResourceHandler(\n resource: RouteResource,\n method: ResourceMethod | \"bulkDelete\",\n): RequestHandler {\n const source = resource[method];\n const handler = source?.bind(resource) as RequestHandler;\n\n copyResponseSchema(source, handler);\n\n return handler;\n}\n\n/**\n * Describe one claimant of a route name, for the duplicate-name error.\n *\n * `warlock dev` registers SSR page routes on the same router as API routes, so\n * the two share a single route-name namespace and collide across kinds. The\n * error is only actionable if it says which claimant is which, so `isPage` —\n * the router's only route-kind discriminator — is what separates them here.\n *\n * `sourceFile` is stamped only on routes registered through `withSourceFile`.\n * Routes registered without that scope have no owner, so say the source is\n * unknown rather than printing an empty string.\n */\nfunction describeRouteClaimant(route: Route) {\n const type = route.isPage ? \"page route\" : \"API route\";\n const source = route.sourceFile ? `declared in ${route.sourceFile}` : \"source file unknown\";\n\n return `${type} ${route.method} ${route.path} (${source})`;\n}\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Bumped on every mutation of {@link routes}.\n *\n * The dev dispatcher caches a route registry and needs to know when it is\n * stale. Comparing `routes.length` would miss an HMR reload that replaces a\n * route without changing the count — the registry would then keep matching\n * paths that no longer exist. A version counter cannot miss that.\n */\n private routesVersion = 0;\n\n /**\n * In-progress atomic replacement, when one exists. Reads continue to use\n * {@link routes}; mutations and collision checks use this isolated draft.\n */\n private routeReplacementTransaction?: {\n routes: Route[];\n removedSourceFiles: Set<string>;\n addedRoutes: Route[];\n };\n\n /**\n * Set by the dev server: whether to warn about mutating routes that have no\n * auth middleware and no `public: true` (`http.warnUnguardedRoutes`).\n */\n private warnUnguardedRoutes = false;\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: {\n options: FastifyStaticOptions;\n rateLimit: StaticMountOptions[\"rateLimit\"];\n }[] = [];\n\n /**\n * Event listeners\n */\n protected eventListeners: Record<string, ((router: Router, server: FastifyInstance) => void)[]> =\n {};\n\n /**\n * Stacks\n * Stacks will be used for grouping routes to add prefix, name or middleware\n */\n protected stacks: RouterStacks = {\n prefix: [],\n name: [],\n middleware: [],\n };\n\n /**\n * Get router instance\n */\n public static getInstance() {\n if (!Router.instance) {\n Router.instance = new Router();\n }\n\n return Router.instance;\n }\n\n private constructor() {\n //\n }\n\n /**\n * Listen to router before scan\n */\n public beforeScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.beforeScan = [...(this.eventListeners.beforeScan || []), callback];\n\n return this;\n }\n\n /**\n * Listen to router after scanning\n */\n public afterScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.afterScanning = [...(this.eventListeners.afterScanning || []), callback];\n\n return this;\n }\n\n /**\n * Redirect path to another path\n */\n public redirect(from: string, to: string, redirectMode: \"temporary\" | \"permanent\" = \"temporary\") {\n return this.get(from, ({ response }) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Serve a static folder.\n *\n * Static mounts are exempt from the global rate limiter by default; set\n * `http.rateLimit.staticFiles: true` to count every mount, or pass\n * `{ rateLimit }` to decide for this mount alone: `true` counts it against\n * the global limiter, `false` exempts it, and an object gives it its own\n * limit and bucket.\n *\n * @example\n * router.directory({ root: rootPath(\"docs\"), prefix: \"/docs/\" });\n * router.directory({ root: rootPath(\"exports\"), prefix: \"/exports/\" }, { rateLimit: true });\n */\n public directory(options: FastifyStaticOptions, mountOptions: StaticMountOptions = {}) {\n this.staticDirectories.push({ options, rateLimit: mountOptions.rateLimit });\n\n return this;\n }\n\n /** Declare static routes at boot; load the upstream sender on the first file request. */\n protected registerStaticDirectories(server: FastifyInstance) {\n for (const directory of this.staticDirectories) {\n registerLazyStatic(\n server,\n { ...directory.options, decorateReply: false },\n { rateLimit: resolveStaticRateLimit(directory.rateLimit) },\n );\n }\n }\n\n /**\n * Register a GET route that serves a static file. Like `directory()`, it is\n * exempt from the global rate limiter unless `http.rateLimit.staticFiles`\n * or its own `rateLimit` says otherwise.\n */\n protected addStaticFileRoute(\n path: string,\n handler: RequestHandler,\n mountOptions: StaticMountOptions = {},\n ) {\n this.get(\n path,\n handler,\n mountOptions.rateLimit === undefined ? {} : { rateLimit: mountOptions.rateLimit },\n );\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n const route = routes[routes.length - 1];\n\n if (route) route.$staticFile = true;\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(\n path: string,\n location: string,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n return this.addStaticFileRoute(\n path,\n ({ response }) => {\n response.sendFile(location, cacheTime);\n },\n mountOptions,\n );\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(\n path: string,\n location: string,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n return this.addStaticFileRoute(\n path,\n ({ response }) => {\n response.sendCachedFile(location, cacheTime);\n },\n mountOptions,\n );\n }\n\n /**\n * Serve list of files\n */\n public files(\n files: Record<string, string>,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n for (const [path, location] of Object.entries(files)) {\n this.file(path, location, cacheTime, mountOptions);\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(\n files: Record<string, string>,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n for (const [path, location] of Object.entries(files)) {\n this.cachedFile(path, location, cacheTime, mountOptions);\n }\n }\n\n /**\n * Add proxy route\n */\n public proxy(\n path: string,\n baseUrl: string,\n options?: Omit<FastifyHttpProxyOptions, \"prefix\" | \"upstream\">,\n ): this;\n public proxy(options: FastifyHttpProxyOptions): this;\n public proxy(...args: any[]) {\n this.beforeScanning((_router, server) => {\n if (args.length === 1) {\n server.register(proxy, args[0]);\n } else {\n server.register(proxy, {\n prefix: args[0],\n upstream: args[1],\n ...args[2],\n });\n }\n });\n\n return this;\n }\n\n /**\n * Add route to routes list\n */\n public add(\n method: Route[\"method\"],\n path: string | string[],\n handler: RequestHandlerType,\n options: RouteOptions = {},\n ) {\n if (Array.isArray(path)) {\n path.forEach((p) => this.add(method, p, handler, options));\n return this;\n }\n\n const prefix = this.stacks.prefix.reduce((path, prefix) => {\n return normalizeRoutePath(path, prefix);\n }, \"\");\n\n const name = this.stacks.name.reduceRight(\n (name, prefixName) => {\n return trim(prefixName + \".\" + name, \".\");\n },\n options.name || trim(path.replace(/\\//g, \".\"), \".\"),\n );\n\n // The one place a route path becomes canonical. `normalizeRoutePath` is\n // exported so the build-time page-route manifest can produce the very same\n // string without registering anything.\n path = normalizeRoutePath(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\n\n // Work on a copy: the caller may reuse one options object for several\n // routes, and merging the group stack into it would compound per route.\n options = { ...options };\n\n if (middlewarePrecedence === \"before\") {\n options.middleware = [...(options.middleware || []), ...this.stacks.middleware];\n } else {\n options.middleware = [...this.stacks.middleware, ...(options.middleware || [])];\n }\n\n // An enclosing `router.group({ public: true })` makes the route public\n // unless it says otherwise itself.\n if (options.public === undefined && (this.stacks.public ?? 0) > 0) {\n options.public = true;\n }\n\n if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new WarlockError(\n \"WL3002\",\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\n copyResponseSchema(controller[action], handler);\n\n if (!handler.validation) {\n handler.validation = {};\n if (controller[`${action}ValidationSchema`]) {\n handler.validation.schema = controller[`${action}ValidationSchema`]();\n }\n\n if (controller[`${action}Validate`]) {\n handler.validation.validate = controller[`${action}Validate`];\n }\n }\n }\n\n const routeData: Route = {\n method,\n path,\n handler,\n ...options,\n name,\n rateLimit: options.rateLimit,\n $prefix: prefix || \"/\",\n // it must be a new array to avoid modifying the original array\n $prefixStack: [...this.stacks.prefix],\n // Inject source file from stacks if set\n sourceFile: this.stacks.sourceFile || \"\",\n };\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n\n if (routeData.name) {\n // check if the name exists\n const route = routes.find((route) => route.name === routeData.name);\n\n if (route) {\n // check again if the route name exists with the same method\n if (route.method === routeData.method) {\n throw new RouteNameTakenError(\n routeData.name,\n `Route name \"${routeData.name}\" is already taken.\\n` +\n ` already registered: ${describeRouteClaimant(route)}\\n` +\n ` now being added: ${describeRouteClaimant(routeData)}\\n` +\n `Pages and API routes share one route-name namespace, so a name can only be ` +\n `claimed once. Rename one of them via the \"name\" route option.`,\n );\n } else {\n routeData.name += routeNameMethodSuffix(routeData.method);\n }\n }\n }\n\n // Registration-time only — nothing here runs per request. Suspects are\n // collected now and reported together at boot (see `scan`), so a route file\n // written against v4 produces one legible list instead of a mystery 500 per\n // request. Recorded after the collision check so a route that never lands\n // is never reported.\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.addedRoutes.push(routeData);\n } else {\n inspectHandlerSignature(routeData.handler, routeData);\n }\n\n routes.push(routeData);\n\n if (!this.routeReplacementTransaction) {\n this.routesVersion++;\n }\n\n return this;\n }\n\n /**\n * Add a request that accepts all methods\n */\n public any(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"all\" as Route[\"method\"], path, handler, options);\n }\n\n /**\n * Add get request method\n */\n public get(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"GET\", path, handler, options);\n }\n\n /**\n * Add post request method\n */\n public post(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"POST\", path, handler, options);\n }\n\n /**\n * Add put request method\n */\n public put(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PUT\", path, handler, options);\n }\n\n /**\n * Add delete request method\n */\n public delete(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"DELETE\", path, handler, options);\n }\n\n /**\n * Add patch request method\n */\n public patch(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PATCH\", path, handler, options);\n }\n\n /**\n * Add head request method\n */\n public head(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"HEAD\", path, handler, options);\n }\n\n /**\n * Add options request method\n */\n public options(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"OPTIONS\", path, handler, options);\n }\n\n /**\n * Get a chainable route builder for the same route path\n */\n public route(path: string, options: RouteOptions = {}) {\n return new RouteBuilder(this, path, options);\n }\n\n /**\n * Add full restful resource routes\n * This method will generate the following routes:\n * 1. GET /path: list all resources\n * 2. GET /path/:id: get a single resource\n * 3. POST /path: create a new resource\n * 4. PUT /path/:id: update a resource\n * 5. DELETE /path/:id: delete a resource\n * 6. PATCH /path/:id: update a resource partially\n */\n public restfulResource(\n path: string,\n resource: RouteResource,\n options: RouteOptions & {\n only?: ResourceMethod[];\n except?: ResourceMethod[];\n replace?: Partial<Record<ResourceMethod, RequestHandler>> & {\n bulkDelete?: RequestHandler;\n };\n } = {},\n ) {\n // Derive the base resource name from the path before the group below\n // clears it for use as the routes' relative path. `options.name`, when\n // given, replaces the path-derived name entirely (see the explicit\n // `name` passed to `group()`) rather than composing with it.\n const baseResourceName = options.name || toCamelCase(ltrim(path, \"/\"));\n\n return this.group({ prefix: path, name: baseResourceName }, () => {\n const path = \"\";\n\n // clone the resource so we don't mess up with it\n const routeResource = resource;\n\n const isAcceptableResource = (type: ResourceMethod) => {\n return Boolean(\n // check if the route is not excluded\n (!options.except || !options.except.includes(type)) &&\n // check if the only option is set and the route is included\n (!options.only || options.only.includes(type)),\n );\n };\n\n if (routeResource.list && isAcceptableResource(\"list\")) {\n this.get(path, options.replace?.list || bindResourceHandler(routeResource, \"list\"), {\n ...options,\n name: \"list\",\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n this.get(path + \"/:id\", options.replace?.get || bindResourceHandler(routeResource, \"get\"), {\n ...options,\n name: \"single\",\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: \"create\",\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: \"update\",\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: \"patch\",\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n this.delete(\n path + \"/:id\",\n options.replace?.delete || bindResourceHandler(routeResource, \"delete\"),\n {\n ...options,\n name: \"delete\",\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n this.delete(\n path,\n options.replace?.bulkDelete || bindResourceHandler(routeResource, \"bulkDelete\"),\n {\n ...options,\n name: \"bulkDelete\",\n restful: true,\n },\n );\n }\n\n return this;\n });\n }\n\n /**\n * Group routes with options\n */\n public group(options: GroupedRoutesOptions, callback: RouterGroupCallback) {\n const {\n prefix,\n // name must always be defined because\n // if there are multiple groups without name\n // they might generate the same route name\n // thus causing an error\n // in this case we need always to make sure that\n // the name is always defined.\n name = prefix ? trim(prefix.replace(/\\//g, \".\"), \".\") : undefined,\n middleware,\n public: isPublic,\n } = options;\n\n if (isPublic) {\n this.stacks.public = (this.stacks.public ?? 0) + 1;\n }\n\n if (prefix) {\n this.stacks.prefix.push(prefix);\n }\n\n if (name) {\n this.stacks.name.push(name);\n }\n\n if (middleware) {\n this.stacks.middleware.push(...middleware);\n }\n\n try {\n callback();\n } finally {\n // Always pop/splice this group's stacks, even if the callback throws,\n // so a throwing group never leaks state onto the process-global singleton.\n if (prefix) {\n this.stacks.prefix.pop();\n }\n\n if (name) {\n this.stacks.name.pop();\n }\n\n if (middleware) {\n this.stacks.middleware.splice(\n this.stacks.middleware.length - middleware.length,\n middleware.length,\n );\n }\n if (isPublic) {\n this.stacks.public = (this.stacks.public ?? 1) - 1;\n }\n }\n\n return this;\n }\n\n /**\n * Add prefix to all routes in the given callback\n */\n public prefix(prefix: string, callback: () => void) {\n return this.group({ prefix }, callback);\n }\n\n /**\n * Add API version prefix to all routes in the given callback\n * Automatically formats the version as /v{version}\n * @example\n * router.version(\"1\", () => {\n * router.get(\"/users\", getUsersV1); // /v1/users\n * });\n *\n * router.version(\"2\", () => {\n * router.get(\"/users\", getUsersV2); // /v2/users\n * });\n */\n public version(version: string | number, callback: () => void) {\n return this.prefix(`/v${version}`, callback);\n }\n\n /**\n * Wrap route additions with a source file path\n * Used for tracking which routes come from which file (for HMR)\n * @param sourceFile Relative path to the source file (e.g., \"src/app/users/routes.ts\")\n * @param callback Function that adds routes (will have sourceFile injected)\n */\n public async withSourceFile<T = any>(\n sourceFile: string,\n callback: () => T | Promise<T>,\n ): Promise<T | undefined> {\n // Set source file in stacks\n this.stacks.sourceFile = sourceFile;\n\n try {\n // Execute callback (routes added here will have sourceFile injected)\n return await callback();\n } catch (error) {\n // Log loudly, then RETHROW. Swallowing here silently dropped a whole\n // route file (duplicate name, invalid action, import error) so the\n // surface 404'd with no boot error. The caller decides what a throw\n // means: at boot it aborts the boot, during HMR the dev server's\n // batch-reload handler catches it, prints it, and keeps serving.\n log.error({\n module: \"router\",\n action: \"registerRoutes\",\n message: `Failed to register routes from \"${sourceFile}\"`,\n context: { sourceFile, error },\n });\n\n throw error;\n } finally {\n // Always clear source file from stacks so a throwing file never leaks\n // its sourceFile onto the process-global singleton.\n delete this.stacks.sourceFile;\n }\n }\n\n /**\n * Remove all routes that belong to a specific source file\n * Used when reloading routes files via HMR\n * @param sourceFile Relative path to the source file\n */\n public removeRoutesBySourceFile(sourceFile: string): void {\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.routes = this.routeReplacementTransaction.routes.filter(\n (route) => route.sourceFile !== sourceFile,\n );\n this.routeReplacementTransaction.removedSourceFiles.add(sourceFile);\n return;\n }\n\n this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n\n // Keep the signature diagnostics in step, so a reload that fixes a handler\n // stops reporting the version it replaced.\n forgetPositionalHandlerSuspects(sourceFile);\n\n this.routesVersion++;\n }\n\n /**\n * Atomically replace every route owned by the given exact source-file keys.\n *\n * The installer mutates an isolated draft. Public reads keep seeing the old\n * live table across awaits, and a failed installer discards every draft\n * mutation. A successful installer swaps the whole draft in one synchronous\n * commit and invalidates the dev route registry exactly once.\n */\n public async replaceRoutesBySourceFiles<T>(\n sourceFiles: Iterable<string>,\n install: () => T | Promise<T>,\n ): Promise<T> {\n if (this.routeReplacementTransaction) {\n throw new Error(\"Cannot nest route replacement transactions\");\n }\n\n const removedSourceFiles = new Set(sourceFiles);\n\n this.routeReplacementTransaction = {\n routes: this.routes.filter((route) => !removedSourceFiles.has(route.sourceFile)),\n removedSourceFiles,\n addedRoutes: [],\n };\n\n try {\n const result = await install();\n const transaction = this.routeReplacementTransaction!;\n\n this.routes = transaction.routes;\n this.routeReplacementTransaction = undefined;\n\n // Diagnostic state follows the same commit boundary as the route table.\n // Added routes were deliberately not inspected while still speculative.\n for (const sourceFile of transaction.removedSourceFiles) {\n forgetPositionalHandlerSuspects(sourceFile);\n }\n\n const committedRoutes = new Set(transaction.routes);\n\n for (const route of transaction.addedRoutes) {\n if (committedRoutes.has(route)) {\n inspectHandlerSignature(route.handler, route);\n }\n }\n\n if (this.warnUnguardedRoutes) {\n reportUnguardedMutatingRoutes(\n transaction.addedRoutes.filter((route) => committedRoutes.has(route)),\n );\n }\n\n this.routesVersion++;\n\n return result;\n } catch (error) {\n this.routeReplacementTransaction = undefined;\n throw error;\n }\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = bindResourceHandler(resource, method);\n\n const methodValidation = resource?.validation?.[method];\n\n if (method === \"patch\") {\n handler.validation = methodValidation;\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n\n if (resource.validation?.patch) {\n handler.validation = merge(resource.validation.patch, handler.validation);\n }\n\n return handler;\n }\n\n if (!resource.validation || (!methodValidation && !resource.validation.all)) return handler;\n\n if (resource.validation.all) {\n const validationMethods = {\n all: resource?.validation?.all?.validate,\n [method]: methodValidation?.validate,\n };\n\n const validation: RequestHandlerValidation = {};\n\n if (resource.validation.all.schema || methodValidation?.schema) {\n if (!methodValidation?.schema && resource.validation.all.schema) {\n // Case 2: Only all.schema exists - clone it for this method\n validation.schema = resource.validation.all.schema;\n } else if (methodValidation?.schema && resource.validation.all.schema) {\n // Case 3: Both exist - merge them (all is base, method overrides)\n validation.schema = resource.validation.all.schema.merge(methodValidation.schema);\n } else if (methodValidation?.schema && !resource.validation.all.schema) {\n // Case 1: Only method schema exists - use it directly\n validation.schema = methodValidation.schema;\n }\n // Case 4: Neither exists - handled by outer if being false\n }\n\n if (validationMethods.all || validationMethods[method]) {\n validation.validate = async ({ request, response }: HttpContext) => {\n if (validationMethods.all) {\n const output = await validationMethods.all.call(resource, { request, response });\n\n if (output) return output;\n }\n\n if (validationMethods[method]) {\n return await validationMethods[method]?.call(resource, { request, response });\n }\n\n return;\n };\n }\n\n if (!isEmpty(validation)) {\n handler.validation = validation;\n }\n } else {\n handler.validation = resource.validation[method];\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n }\n\n return handler;\n }\n\n /**\n * Get all routes list\n */\n public list() {\n return this.routes;\n }\n\n /**\n * Return fresh browser-safe snapshots of named, non-page routes.\n *\n * Names are the registered names, including method suffixes. `all` stays\n * intact as route metadata; consumers decide whether their use supports it.\n * A route that opted out with `clientVisible: false` carries that flag, and\n * only that flag, so browser-facing consumers can leave it out.\n */\n public getNamedApiRoutes(options: NamedApiRoutesOptions = {}): readonly NamedApiRoute[] {\n return Object.freeze(\n this.routes\n .filter((route) => !route.isPage && typeof route.name === \"string\" && route.name.length > 0)\n .map((route) => {\n // `clientVisible: false` is the only key this flag ever adds, and it is\n // present only then: the common snapshot keeps its exact shape.\n const snapshot = {\n name: route.name!,\n path: route.path,\n method: route.method,\n ...(route.clientVisible === false ? { clientVisible: false as const } : {}),\n };\n const schema = route.handler?.responseSchema;\n const response = schema ? options.resolveResponse?.(schema, route) : undefined;\n\n // A route without a declared schema keeps exactly the three-key record.\n if (!response || Object.keys(response).length === 0) return Object.freeze(snapshot);\n\n return Object.freeze({ ...snapshot, response: Object.freeze({ ...response }) });\n }),\n );\n }\n\n /**\n * Number of routes currently registered on the singleton.\n *\n * Used as a readiness signal: a successful boot that ends up with zero\n * routes almost always means a route module failed to register silently\n * (see `withSourceFile`), so callers can surface that instead of letting\n * the whole surface 404.\n */\n public routeCount(): number {\n return this.routes.length;\n }\n\n /**\n * Register routes to the server\n */\n public scan(server: FastifyInstance) {\n // Every route is registered by the time we scan, so this is the first\n // moment the whole list can be reported at once — and it is still before a\n // single request is served.\n reportPositionalHandlerSuspects();\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n // Fastify automatically exposes HEAD for every GET route. When an app\n // declares its own HEAD route at the same path, suppress only that GET\n // route's implicit registration so the explicit handler owns HEAD,\n // regardless of declaration order.\n const explicitHeadPaths = new Set(\n this.routes\n .filter((route) => route.method.toLowerCase() === \"head\")\n .map((route) => route.path),\n );\n\n this.routes.forEach((route) => {\n const requestMethod = route.method.toLowerCase();\n const requestMethodFunction = server[requestMethod].bind(server);\n\n const options = {\n ...route.serverOptions,\n ...(requestMethod === \"get\" &&\n explicitHeadPaths.has(route.path) && { exposeHeadRoute: false }),\n config: {\n ...route.serverOptions?.config,\n // `undefined` keeps the global policy; `false` exempts the route.\n rateLimit: resolveRouteRateLimit(route),\n },\n };\n\n requestMethodFunction(\n route.path,\n options,\n async (baseRequest: FastifyRequest, reply: FastifyReply) => {\n const { output, response } = await this.handleRoute(route)(baseRequest, reply);\n\n return output || response.baseResponse;\n },\n );\n });\n\n this.registerStaticDirectories(server);\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Scan routes for the development server\n * Uses wildcard routing with find-my-way for HMR support\n */\n public scanDevServer(server: FastifyInstance) {\n // Same boot-time report as production `scan`. Routes reloaded later by HMR\n // are still recorded, but only surface on the next scan or via\n // `warlock doctor`.\n reportPositionalHandlerSuspects();\n\n // Development only: list mutating routes nobody guarded. Routes added by a\n // later HMR reload are reported when their replacement commits.\n this.warnUnguardedRoutes =\n configAccessor.key<boolean>(\"http.warnUnguardedRoutes\", true) !== false;\n if (this.warnUnguardedRoutes) {\n reportUnguardedMutatingRoutes(this.routes);\n }\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n let routeRegistry: RouteRegistry | undefined;\n let registryVersion = -1;\n\n const applyDevRateLimit = createDevRateLimiter(\n server,\n config.get(\"http.rateLimit.global\") !== false,\n );\n\n // Rebuilt when the route table changes rather than per request. Building it\n // inside the handler re-registered every route on every hit — and `all`\n // routes expand into seven registrations each. Keyed on `routesVersion`\n // rather than on the route count, so an HMR reload that swaps a route\n // without changing the count still invalidates.\n const resolveRouteRegistry = () => {\n if (routeRegistry && registryVersion === this.routesVersion) {\n return routeRegistry;\n }\n\n routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n\n registryVersion = this.routesVersion;\n\n return routeRegistry;\n };\n\n // Matching happens here, in Fastify's own onRequest phase, so a route's\n // `serverOptions.onRequest` still runs BEFORE body parsing. Production\n // `scan()` gets that from per-route registration; the wildcard dispatcher\n // has no per-route slot, so without this the hook silently never runs.\n server.addHook(\n \"onRequest\",\n async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n // Only requests Fastify routed to the dev wildcard belong to the app's\n // router. A plugin's own route (devtools' `/__warlock/api/requests/:id`)\n // must keep its params even when an app catch-all matches the URL too.\n if (fastifyRequest.routeOptions.url !== \"*\") {\n return undefined;\n }\n\n const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);\n\n if (!match) {\n return undefined;\n }\n\n (fastifyRequest as DevDispatchRequest).matchedDevRoute = match;\n\n fastifyRequest.params = match.params;\n\n // Same slot production gives it: the limiter runs first in onRequest,\n // ahead of the route's own hooks.\n await applyDevRateLimit(match.route, fastifyRequest, fastifyReply);\n\n if (fastifyReply.sent) {\n return fastifyReply;\n }\n\n return runRouteHooks(match.route, \"onRequest\", fastifyRequest, fastifyReply);\n },\n );\n\n for (const phase of FORWARDED_ROUTE_PHASES.filter((name) => name !== \"onRequest\")) {\n server.addHook(phase, async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n if (!match) {\n return undefined;\n }\n\n return runRouteHooks(match.route, phase, fastifyRequest, fastifyReply);\n });\n }\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n // No match found - return 404\n if (!match) {\n return fastifyReply\n .code(404)\n .send(buildNotFoundBody(fastifyRequest.method, fastifyRequest.url));\n }\n\n try {\n // Call the matched route handler\n const { output, response } = await this.handleRoute(match.route)(\n fastifyRequest,\n fastifyReply,\n );\n\n return output || response.baseResponse;\n } catch (error) {\n log.error(\"router\", \"dev-dispatch\", error as Error, {\n method: fastifyRequest.method,\n url: buildRequestLogSnapshot({\n id: fastifyRequest.id,\n method: fastifyRequest.method,\n url: fastifyRequest.url,\n route: match.route,\n }).url,\n });\n\n throw error;\n }\n };\n\n // Every verb production can register. Fastify's implicit HEAD for the GET\n // wildcard is switched off so the HEAD wildcard owns it (the registry falls\n // back to the GET route, exactly as production's implicit HEAD does).\n // `@fastify/cors` registers its own OPTIONS \"*\" catch-all whenever\n // preflight is on. Use the plugin's options as well as hasRoute so this\n // dispatcher works both after HTTP plugin boot and before queued plugins.\n const corsOwnsPreflight = buildCorsOptions().preflight !== false;\n\n for (const method of DEV_DISPATCH_METHODS) {\n if (\n method === \"OPTIONS\" &&\n (corsOwnsPreflight || server.hasRoute({ method: \"OPTIONS\", url: \"*\" }))\n ) {\n continue;\n }\n\n server.route({\n method,\n url: \"*\",\n ...(method === \"GET\" && { exposeHeadRoute: false }),\n // The dispatcher limits each matched route itself (see\n // `createDevRateLimiter`), so the plugin must not limit the wildcard:\n // that would count exempt routes and unmatched URLs too.\n config: { rateLimit: false },\n handler: wildcardHandler,\n });\n }\n\n this.registerStaticDirectories(server);\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Get the route path for the given route name\n */\n public getRoute(name: string, params: Record<string, any> = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new WarlockError(\"WL3003\", `Route name \"${name}\" not found`);\n }\n\n const used = new Set<string>();\n\n const path = route.path.replace(/:([A-Za-z0-9_]+)(\\?)?/g, (_match, key: string, optional) => {\n const value = params[key];\n\n if (value === undefined || value === null) {\n if (optional) return \"\";\n\n throw new WarlockError(\"WL3004\", `Route \"${name}\" is missing the \"${key}\" param`);\n }\n\n used.add(key);\n\n return encodeURIComponent(String(value));\n });\n\n const query = Object.keys(params)\n .filter((key) => !used.has(key) && params[key] !== undefined && params[key] !== null)\n .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(params[key]))}`)\n .join(\"&\");\n\n return query ? `${path}?${query}` : path;\n }\n\n /**\n * Handle the given route\n */\n private handleRoute(route: Route) {\n return async (fastifyRequest: FastifyRequest, fastifyResponse: FastifyReply) => {\n const request = new Request();\n const response = new Response();\n response.setResponse(fastifyResponse);\n request.response = response;\n\n response.request = request;\n\n // \"route.match\" tracing phase: the pattern is\n // already known here (`route.path`), so this brackets the cost of\n // stamping the request/route onto the `Request` instance rather than\n // route-registry matching itself, which happens upstream of this\n // function for both the production `scan()` path and the dev wildcard\n // dispatcher (both funnel into `handleRoute`).\n const tracingEnabled = isTracingEnabled();\n const routeMatchStartedAt = tracingEnabled ? performance.now() : 0;\n\n request.setRequest(fastifyRequest).setRoute(route);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"route.match\",\n durationMs: performance.now() - routeMatchStartedAt,\n attrs: { route: route.path },\n });\n }\n\n /*\n Both ends of the entry, not just the start — see\n `log-request-lifecycle.ts`. A start line on its own made a hung request\n and an instant one look identical, and the completion line is what makes\n a MISSING one legible as a hang.\n */\n const result = await logRequestLifecycle(\n {\n info: (entry) => log.info(entry),\n warn: (entry) => log.warn(entry),\n error: (entry) => log.error(entry),\n now: () => performance.now(),\n },\n {\n module: \"route\",\n action: describeRouteForLog(route.method, route.path),\n requestId: request.id,\n // A bounded snapshot, built once with the route's logging policy\n // applied — never the Request/Response instances, whose native\n // request, reply and URL graphs would reach every log channel.\n context: { request: request.toLogSnapshot() },\n request,\n // Read after the run: the status is decided during the request.\n statusCode: () => fastifyResponse.statusCode,\n },\n () => request.execute(),\n );\n\n // A handler may return a plain object (`ReturnedResponse`). Route it\n // through `Response.send` so status, events and hooks apply, exactly as\n // middleware outputs already do.\n let output = result;\n\n if (\n output !== undefined &&\n output !== null &&\n !(output instanceof Response) &&\n (output as unknown) !== fastifyResponse\n ) {\n output = await response.send(output);\n }\n\n return {\n output,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAM,yBAAyB;CAAC;CAAa;CAAiB;AAAY;AAc1E,SAAS,WACP,MACsB;CACtB,IAAI,CAAC,MACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AAC3C;;;;;;;;AASA,eAAe,cACb,OACA,OACA,SACA,OACA;CACA,MAAM,QAAQ,WAC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SAAS,KAAK,MAAM;GAGrC,OAAO;IACL;IACA;IACA;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
1
+ {"version":3,"file":"router.mjs","names":["configAccessor","config"],"sources":["../../../../../../../../packages/core/src/router/router.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport { WarlockError } from \"../errors/warlock-error\";\nimport type { FastifyStaticOptions } from \"@fastify/static\";\nimport { ltrim, merge, toCamelCase, trim } from \"@mongez/reinforcements\";\nimport { isEmpty } from \"@mongez/supportive-is\";\nimport { log } from \"@warlock.js/logger\";\nimport type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { container } from \"../container\";\nimport { registerLazyStatic } from \"../http/lazy-static\";\nimport { buildCorsOptions } from \"../http/build-cors-options\";\nimport { Request } from \"../http/request\";\nimport { buildRequestLogSnapshot } from \"../http/request-log-snapshot\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { buildTracingContext, dispatchPhase, isTracingEnabled } from \"../http/tracing\";\nimport { describeRouteForLog } from \"./describe-route-for-log\";\nimport { logRequestLifecycle } from \"./log-request-lifecycle\";\nimport {\n forgetPositionalHandlerSuspects,\n inspectHandlerSignature,\n reportPositionalHandlerSuspects,\n} from \"./positional-handler-diagnostics\";\nimport { isRequiredGuardRoute, reportUnguardedMutatingRoutes } from \"./unguarded-route-diagnostics\";\nimport { config as configAccessor } from \"../config/config-getter\";\nimport { normalizeRoutePath } from \"./normalize-route-path\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { resolveRouteRateLimit, resolveStaticRateLimit } from \"./resolve-route-rate-limit\";\nimport { RouteNameTakenError } from \"./route-name-taken-error\";\nimport { DEV_DISPATCH_METHODS, buildNotFoundBody, createDevRateLimiter } from \"./dev-dispatch\";\nimport { RouteRegistry } from \"./route-registry\";\nimport { routeNameMethodSuffix } from \"./route-name-method-suffix\";\nimport type {\n GroupedRoutesOptions,\n HttpContext,\n NamedApiRoute,\n NamedApiRoutesOptions,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n StaticMountOptions,\n} from \"./types\";\n\n/**\n * A Fastify lifecycle hook as it may be declared in a route's `serverOptions`.\n * Fastify accepts a single hook or an array in either position.\n */\ntype RouteLifecycleHook = (\n request: FastifyRequest,\n reply: FastifyReply,\n) => unknown | Promise<unknown>;\n\n/**\n * The pre-handler phases the dev server forwards from a route's `serverOptions`.\n *\n * These are the admission-control phases and they share the `(request, reply)`\n * signature. `preParsing` is deliberately absent — it must return the payload\n * stream, so forwarding it generically would corrupt the body rather than\n * guard it. `bodyLimit` cannot be forwarded at all; Fastify reads it at\n * registration time and no hook can bound a body already being parsed.\n */\nconst FORWARDED_ROUTE_PHASES = [\"onRequest\", \"preValidation\", \"preHandler\"] as const;\n\ntype ForwardedRoutePhase = (typeof FORWARDED_ROUTE_PHASES)[number];\n\n/**\n * The route the dev dispatcher matched, stashed on the request so the hooks and\n * the wildcard handler all act on one match rather than each matching again.\n */\ntype DevMatchedRoute = { route: Route; params: Record<string, string> };\n\ntype DevDispatchRequest = FastifyRequest & {\n matchedDevRoute?: DevMatchedRoute;\n};\n\nfunction toHookList(\n hook: RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n): RouteLifecycleHook[] {\n if (!hook) {\n return [];\n }\n\n return Array.isArray(hook) ? hook : [hook];\n}\n\n/**\n * Run a matched route's hooks for one phase.\n *\n * Returning the reply is how an async Fastify hook signals that it has answered\n * the request; the chain must stop there, so the value is propagated rather\n * than discarded.\n */\nasync function runRouteHooks(\n route: Route,\n phase: ForwardedRoutePhase,\n request: FastifyRequest,\n reply: FastifyReply,\n) {\n const hooks = toHookList(\n route.serverOptions?.[phase] as RouteLifecycleHook | RouteLifecycleHook[] | undefined,\n );\n\n for (const hook of hooks) {\n const outcome = await hook(request, reply);\n\n if (outcome === reply) {\n return reply;\n }\n }\n\n return undefined;\n}\n\n/**\n * Bound functions do not inherit static properties, so the handler metadata that\n * documentation and typings read (`responseSchema`) is copied onto the bound copy.\n */\nfunction copyResponseSchema(source: unknown, target: RequestHandler): void {\n const responseSchema = (source as RequestHandler | undefined)?.responseSchema;\n\n if (responseSchema) {\n target.responseSchema = responseSchema;\n }\n}\n\n/**\n * Bind a restful resource method to its resource, keeping its `responseSchema`.\n */\nfunction bindResourceHandler(\n resource: RouteResource,\n method: ResourceMethod | \"bulkDelete\",\n): RequestHandler {\n const source = resource[method];\n const handler = source?.bind(resource) as RequestHandler;\n\n copyResponseSchema(source, handler);\n\n return handler;\n}\n\n/**\n * Describe one claimant of a route name, for the duplicate-name error.\n *\n * `warlock dev` registers SSR page routes on the same router as API routes, so\n * the two share a single route-name namespace and collide across kinds. The\n * error is only actionable if it says which claimant is which, so `isPage` —\n * the router's only route-kind discriminator — is what separates them here.\n *\n * `sourceFile` is stamped only on routes registered through `withSourceFile`.\n * Routes registered without that scope have no owner, so say the source is\n * unknown rather than printing an empty string.\n */\nfunction describeRouteClaimant(route: Route) {\n const type = route.isPage ? \"page route\" : \"API route\";\n const source = route.sourceFile ? `declared in ${route.sourceFile}` : \"source file unknown\";\n\n return `${type} ${route.method} ${route.path} (${source})`;\n}\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Bumped on every mutation of {@link routes}.\n *\n * The dev dispatcher caches a route registry and needs to know when it is\n * stale. Comparing `routes.length` would miss an HMR reload that replaces a\n * route without changing the count — the registry would then keep matching\n * paths that no longer exist. A version counter cannot miss that.\n */\n private routesVersion = 0;\n\n /**\n * In-progress atomic replacement, when one exists. Reads continue to use\n * {@link routes}; mutations and collision checks use this isolated draft.\n */\n private routeReplacementTransaction?: {\n routes: Route[];\n removedSourceFiles: Set<string>;\n addedRoutes: Route[];\n };\n\n /**\n * Set by the dev server: whether to warn about mutating routes that have no\n * auth middleware and no `public: true` (`http.warnUnguardedRoutes`).\n */\n private warnUnguardedRoutes = false;\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: {\n options: FastifyStaticOptions;\n rateLimit: StaticMountOptions[\"rateLimit\"];\n }[] = [];\n\n /**\n * Event listeners\n */\n protected eventListeners: Record<string, ((router: Router, server: FastifyInstance) => void)[]> =\n {};\n\n /**\n * Stacks\n * Stacks will be used for grouping routes to add prefix, name or middleware\n */\n protected stacks: RouterStacks = {\n prefix: [],\n name: [],\n middleware: [],\n };\n\n /**\n * Get router instance\n */\n public static getInstance() {\n if (!Router.instance) {\n Router.instance = new Router();\n }\n\n return Router.instance;\n }\n\n private constructor() {\n //\n }\n\n /**\n * Listen to router before scan\n */\n public beforeScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.beforeScan = [...(this.eventListeners.beforeScan || []), callback];\n\n return this;\n }\n\n /**\n * Listen to router after scanning\n */\n public afterScanning(callback: (router: Router, server: FastifyInstance) => void) {\n this.eventListeners.afterScanning = [...(this.eventListeners.afterScanning || []), callback];\n\n return this;\n }\n\n /**\n * Redirect path to another path\n */\n public redirect(from: string, to: string, redirectMode: \"temporary\" | \"permanent\" = \"temporary\") {\n return this.get(from, ({ response }) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Serve a static folder.\n *\n * Static mounts are exempt from the global rate limiter by default; set\n * `http.rateLimit.staticFiles: true` to count every mount, or pass\n * `{ rateLimit }` to decide for this mount alone: `true` counts it against\n * the global limiter, `false` exempts it, and an object gives it its own\n * limit and bucket.\n *\n * @example\n * router.directory({ root: rootPath(\"docs\"), prefix: \"/docs/\" });\n * router.directory({ root: rootPath(\"exports\"), prefix: \"/exports/\" }, { rateLimit: true });\n */\n public directory(options: FastifyStaticOptions, mountOptions: StaticMountOptions = {}) {\n this.staticDirectories.push({ options, rateLimit: mountOptions.rateLimit });\n\n return this;\n }\n\n /** Declare static routes at boot; load the upstream sender on the first file request. */\n protected registerStaticDirectories(server: FastifyInstance) {\n for (const directory of this.staticDirectories) {\n registerLazyStatic(\n server,\n { ...directory.options, decorateReply: false },\n { rateLimit: resolveStaticRateLimit(directory.rateLimit) },\n );\n }\n }\n\n /**\n * Register a GET route that serves a static file. Like `directory()`, it is\n * exempt from the global rate limiter unless `http.rateLimit.staticFiles`\n * or its own `rateLimit` says otherwise.\n */\n protected addStaticFileRoute(\n path: string,\n handler: RequestHandler,\n mountOptions: StaticMountOptions = {},\n ) {\n this.get(\n path,\n handler,\n mountOptions.rateLimit === undefined ? {} : { rateLimit: mountOptions.rateLimit },\n );\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n const route = routes[routes.length - 1];\n\n if (route) route.$staticFile = true;\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(\n path: string,\n location: string,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n return this.addStaticFileRoute(\n path,\n ({ response }) => {\n response.sendFile(location, cacheTime);\n },\n mountOptions,\n );\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(\n path: string,\n location: string,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n return this.addStaticFileRoute(\n path,\n ({ response }) => {\n response.sendCachedFile(location, cacheTime);\n },\n mountOptions,\n );\n }\n\n /**\n * Serve list of files\n */\n public files(\n files: Record<string, string>,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n for (const [path, location] of Object.entries(files)) {\n this.file(path, location, cacheTime, mountOptions);\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(\n files: Record<string, string>,\n cacheTime?: number,\n mountOptions: StaticMountOptions = {},\n ) {\n for (const [path, location] of Object.entries(files)) {\n this.cachedFile(path, location, cacheTime, mountOptions);\n }\n }\n\n /**\n * Add proxy route\n */\n public proxy(\n path: string,\n baseUrl: string,\n options?: Omit<FastifyHttpProxyOptions, \"prefix\" | \"upstream\">,\n ): this;\n public proxy(options: FastifyHttpProxyOptions): this;\n public proxy(...args: any[]) {\n this.beforeScanning((_router, server) => {\n if (args.length === 1) {\n server.register(proxy, args[0]);\n } else {\n server.register(proxy, {\n prefix: args[0],\n upstream: args[1],\n ...args[2],\n });\n }\n });\n\n return this;\n }\n\n /**\n * Add route to routes list\n */\n public add(\n method: Route[\"method\"],\n path: string | string[],\n handler: RequestHandlerType,\n options: RouteOptions = {},\n ) {\n if (Array.isArray(path)) {\n path.forEach((p) => this.add(method, p, handler, options));\n return this;\n }\n\n const prefix = this.stacks.prefix.reduce((path, prefix) => {\n return normalizeRoutePath(path, prefix);\n }, \"\");\n\n const name = this.stacks.name.reduceRight(\n (name, prefixName) => {\n return trim(prefixName + \".\" + name, \".\");\n },\n options.name || trim(path.replace(/\\//g, \".\"), \".\"),\n );\n\n // The one place a route path becomes canonical. `normalizeRoutePath` is\n // exported so the build-time page-route manifest can produce the very same\n // string without registering anything.\n path = normalizeRoutePath(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\n\n // Work on a copy: the caller may reuse one options object for several\n // routes, and merging the group stack into it would compound per route.\n options = { ...options };\n\n if (middlewarePrecedence === \"before\") {\n options.middleware = [...(options.middleware || []), ...this.stacks.middleware];\n } else {\n options.middleware = [...this.stacks.middleware, ...(options.middleware || [])];\n }\n\n // An enclosing `router.group({ public: true })` makes the route public\n // unless it says otherwise itself.\n if (options.public === undefined && (this.stacks.public ?? 0) > 0) {\n options.public = true;\n }\n\n // An enclosing `router.group({ sites })` scopes the route's browser table\n // entry unless the route names its own sites.\n const groupSites = this.stacks.sites?.at(-1);\n\n if (options.sites === undefined && groupSites !== undefined) {\n options.sites = groupSites;\n }\n\n if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new WarlockError(\n \"WL3002\",\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\n copyResponseSchema(controller[action], handler);\n\n if (!handler.validation) {\n handler.validation = {};\n if (controller[`${action}ValidationSchema`]) {\n handler.validation.schema = controller[`${action}ValidationSchema`]();\n }\n\n if (controller[`${action}Validate`]) {\n handler.validation.validate = controller[`${action}Validate`];\n }\n }\n }\n\n const routeData: Route = {\n method,\n path,\n handler,\n ...options,\n name,\n rateLimit: options.rateLimit,\n $prefix: prefix || \"/\",\n // it must be a new array to avoid modifying the original array\n $prefixStack: [...this.stacks.prefix],\n // Inject source file from stacks if set\n sourceFile: this.stacks.sourceFile || \"\",\n };\n\n const routes = this.routeReplacementTransaction?.routes ?? this.routes;\n\n if (routeData.name) {\n // check if the name exists\n const route = routes.find((route) => route.name === routeData.name);\n\n if (route) {\n // check again if the route name exists with the same method\n if (route.method === routeData.method) {\n throw new RouteNameTakenError(\n routeData.name,\n `Route name \"${routeData.name}\" is already taken.\\n` +\n ` already registered: ${describeRouteClaimant(route)}\\n` +\n ` now being added: ${describeRouteClaimant(routeData)}\\n` +\n `Pages and API routes share one route-name namespace, so a name can only be ` +\n `claimed once. Rename one of them via the \"name\" route option.`,\n );\n } else {\n routeData.name += routeNameMethodSuffix(routeData.method);\n }\n }\n }\n\n // Registration-time only — nothing here runs per request. Suspects are\n // collected now and reported together at boot (see `scan`), so a route file\n // written against v4 produces one legible list instead of a mystery 500 per\n // request. Recorded after the collision check so a route that never lands\n // is never reported.\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.addedRoutes.push(routeData);\n } else {\n inspectHandlerSignature(routeData.handler, routeData);\n }\n\n routes.push(routeData);\n\n if (!this.routeReplacementTransaction) {\n this.routesVersion++;\n }\n\n return this;\n }\n\n /**\n * Add a request that accepts all methods\n */\n public any(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"all\" as Route[\"method\"], path, handler, options);\n }\n\n /**\n * Add get request method\n */\n public get(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"GET\", path, handler, options);\n }\n\n /**\n * Add post request method\n */\n public post(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"POST\", path, handler, options);\n }\n\n /**\n * Add put request method\n */\n public put(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PUT\", path, handler, options);\n }\n\n /**\n * Add delete request method\n */\n public delete(path: string | string[], handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"DELETE\", path, handler, options);\n }\n\n /**\n * Add patch request method\n */\n public patch(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"PATCH\", path, handler, options);\n }\n\n /**\n * Add head request method\n */\n public head(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"HEAD\", path, handler, options);\n }\n\n /**\n * Add options request method\n */\n public options(path: string, handler: RequestHandlerType, options: RouteOptions = {}) {\n return this.add(\"OPTIONS\", path, handler, options);\n }\n\n /**\n * Get a chainable route builder for the same route path\n */\n public route(path: string, options: RouteOptions = {}) {\n return new RouteBuilder(this, path, options);\n }\n\n /**\n * Add full restful resource routes\n * This method will generate the following routes:\n * 1. GET /path: list all resources\n * 2. GET /path/:id: get a single resource\n * 3. POST /path: create a new resource\n * 4. PUT /path/:id: update a resource\n * 5. DELETE /path/:id: delete a resource\n * 6. PATCH /path/:id: update a resource partially\n */\n public restfulResource(\n path: string,\n resource: RouteResource,\n options: RouteOptions & {\n only?: ResourceMethod[];\n except?: ResourceMethod[];\n replace?: Partial<Record<ResourceMethod, RequestHandler>> & {\n bulkDelete?: RequestHandler;\n };\n } = {},\n ) {\n // Derive the base resource name from the path before the group below\n // clears it for use as the routes' relative path. `options.name`, when\n // given, replaces the path-derived name entirely (see the explicit\n // `name` passed to `group()`) rather than composing with it.\n const baseResourceName = options.name || toCamelCase(ltrim(path, \"/\"));\n\n return this.group({ prefix: path, name: baseResourceName }, () => {\n const path = \"\";\n\n // clone the resource so we don't mess up with it\n const routeResource = resource;\n\n const isAcceptableResource = (type: ResourceMethod) => {\n return Boolean(\n // check if the route is not excluded\n (!options.except || !options.except.includes(type)) &&\n // check if the only option is set and the route is included\n (!options.only || options.only.includes(type)),\n );\n };\n\n if (routeResource.list && isAcceptableResource(\"list\")) {\n this.get(path, options.replace?.list || bindResourceHandler(routeResource, \"list\"), {\n ...options,\n name: \"list\",\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n this.get(path + \"/:id\", options.replace?.get || bindResourceHandler(routeResource, \"get\"), {\n ...options,\n name: \"single\",\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: \"create\",\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: \"update\",\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: \"patch\",\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n this.delete(\n path + \"/:id\",\n options.replace?.delete || bindResourceHandler(routeResource, \"delete\"),\n {\n ...options,\n name: \"delete\",\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n this.delete(\n path,\n options.replace?.bulkDelete || bindResourceHandler(routeResource, \"bulkDelete\"),\n {\n ...options,\n name: \"bulkDelete\",\n restful: true,\n },\n );\n }\n\n return this;\n });\n }\n\n /**\n * Group routes with options\n */\n public group(options: GroupedRoutesOptions, callback: RouterGroupCallback) {\n const {\n prefix,\n // name must always be defined because\n // if there are multiple groups without name\n // they might generate the same route name\n // thus causing an error\n // in this case we need always to make sure that\n // the name is always defined.\n name = prefix ? trim(prefix.replace(/\\//g, \".\"), \".\") : undefined,\n middleware,\n public: isPublic,\n sites,\n } = options;\n\n if (sites) {\n (this.stacks.sites ??= []).push(sites);\n }\n\n if (isPublic) {\n this.stacks.public = (this.stacks.public ?? 0) + 1;\n }\n\n if (prefix) {\n this.stacks.prefix.push(prefix);\n }\n\n if (name) {\n this.stacks.name.push(name);\n }\n\n if (middleware) {\n this.stacks.middleware.push(...middleware);\n }\n\n try {\n callback();\n } finally {\n // Always pop/splice this group's stacks, even if the callback throws,\n // so a throwing group never leaks state onto the process-global singleton.\n if (prefix) {\n this.stacks.prefix.pop();\n }\n\n if (name) {\n this.stacks.name.pop();\n }\n\n if (middleware) {\n this.stacks.middleware.splice(\n this.stacks.middleware.length - middleware.length,\n middleware.length,\n );\n }\n if (isPublic) {\n this.stacks.public = (this.stacks.public ?? 1) - 1;\n }\n\n if (sites) {\n this.stacks.sites?.pop();\n }\n }\n\n return this;\n }\n\n /**\n * Add prefix to all routes in the given callback\n */\n public prefix(prefix: string, callback: () => void) {\n return this.group({ prefix }, callback);\n }\n\n /**\n * Add API version prefix to all routes in the given callback\n * Automatically formats the version as /v{version}\n * @example\n * router.version(\"1\", () => {\n * router.get(\"/users\", getUsersV1); // /v1/users\n * });\n *\n * router.version(\"2\", () => {\n * router.get(\"/users\", getUsersV2); // /v2/users\n * });\n */\n public version(version: string | number, callback: () => void) {\n return this.prefix(`/v${version}`, callback);\n }\n\n /**\n * Wrap route additions with a source file path\n * Used for tracking which routes come from which file (for HMR)\n * @param sourceFile Relative path to the source file (e.g., \"src/app/users/routes.ts\")\n * @param callback Function that adds routes (will have sourceFile injected)\n */\n public async withSourceFile<T = any>(\n sourceFile: string,\n callback: () => T | Promise<T>,\n ): Promise<T | undefined> {\n // Set source file in stacks\n this.stacks.sourceFile = sourceFile;\n\n try {\n // Execute callback (routes added here will have sourceFile injected)\n return await callback();\n } catch (error) {\n // Log loudly, then RETHROW. Swallowing here silently dropped a whole\n // route file (duplicate name, invalid action, import error) so the\n // surface 404'd with no boot error. The caller decides what a throw\n // means: at boot it aborts the boot, during HMR the dev server's\n // batch-reload handler catches it, prints it, and keeps serving.\n log.error({\n module: \"router\",\n action: \"registerRoutes\",\n message: `Failed to register routes from \"${sourceFile}\"`,\n context: { sourceFile, error },\n });\n\n throw error;\n } finally {\n // Always clear source file from stacks so a throwing file never leaks\n // its sourceFile onto the process-global singleton.\n delete this.stacks.sourceFile;\n }\n }\n\n /**\n * Remove all routes that belong to a specific source file\n * Used when reloading routes files via HMR\n * @param sourceFile Relative path to the source file\n */\n public removeRoutesBySourceFile(sourceFile: string): void {\n if (this.routeReplacementTransaction) {\n this.routeReplacementTransaction.routes = this.routeReplacementTransaction.routes.filter(\n (route) => route.sourceFile !== sourceFile,\n );\n this.routeReplacementTransaction.removedSourceFiles.add(sourceFile);\n return;\n }\n\n this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n\n // Keep the signature diagnostics in step, so a reload that fixes a handler\n // stops reporting the version it replaced.\n forgetPositionalHandlerSuspects(sourceFile);\n\n this.routesVersion++;\n }\n\n /**\n * Atomically replace every route owned by the given exact source-file keys.\n *\n * The installer mutates an isolated draft. Public reads keep seeing the old\n * live table across awaits, and a failed installer discards every draft\n * mutation. A successful installer swaps the whole draft in one synchronous\n * commit and invalidates the dev route registry exactly once.\n */\n public async replaceRoutesBySourceFiles<T>(\n sourceFiles: Iterable<string>,\n install: () => T | Promise<T>,\n ): Promise<T> {\n if (this.routeReplacementTransaction) {\n throw new Error(\"Cannot nest route replacement transactions\");\n }\n\n const removedSourceFiles = new Set(sourceFiles);\n\n this.routeReplacementTransaction = {\n routes: this.routes.filter((route) => !removedSourceFiles.has(route.sourceFile)),\n removedSourceFiles,\n addedRoutes: [],\n };\n\n try {\n const result = await install();\n const transaction = this.routeReplacementTransaction!;\n\n this.routes = transaction.routes;\n this.routeReplacementTransaction = undefined;\n\n // Diagnostic state follows the same commit boundary as the route table.\n // Added routes were deliberately not inspected while still speculative.\n for (const sourceFile of transaction.removedSourceFiles) {\n forgetPositionalHandlerSuspects(sourceFile);\n }\n\n const committedRoutes = new Set(transaction.routes);\n\n for (const route of transaction.addedRoutes) {\n if (committedRoutes.has(route)) {\n inspectHandlerSignature(route.handler, route);\n }\n }\n\n if (this.warnUnguardedRoutes) {\n reportUnguardedMutatingRoutes(\n transaction.addedRoutes.filter((route) => committedRoutes.has(route)),\n );\n }\n\n this.routesVersion++;\n\n return result;\n } catch (error) {\n this.routeReplacementTransaction = undefined;\n throw error;\n }\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = bindResourceHandler(resource, method);\n\n const methodValidation = resource?.validation?.[method];\n\n if (method === \"patch\") {\n handler.validation = methodValidation;\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n\n if (resource.validation?.patch) {\n handler.validation = merge(resource.validation.patch, handler.validation);\n }\n\n return handler;\n }\n\n if (!resource.validation || (!methodValidation && !resource.validation.all)) return handler;\n\n if (resource.validation.all) {\n const validationMethods = {\n all: resource?.validation?.all?.validate,\n [method]: methodValidation?.validate,\n };\n\n const validation: RequestHandlerValidation = {};\n\n if (resource.validation.all.schema || methodValidation?.schema) {\n if (!methodValidation?.schema && resource.validation.all.schema) {\n // Case 2: Only all.schema exists - clone it for this method\n validation.schema = resource.validation.all.schema;\n } else if (methodValidation?.schema && resource.validation.all.schema) {\n // Case 3: Both exist - merge them (all is base, method overrides)\n validation.schema = resource.validation.all.schema.merge(methodValidation.schema);\n } else if (methodValidation?.schema && !resource.validation.all.schema) {\n // Case 1: Only method schema exists - use it directly\n validation.schema = methodValidation.schema;\n }\n // Case 4: Neither exists - handled by outer if being false\n }\n\n if (validationMethods.all || validationMethods[method]) {\n validation.validate = async ({ request, response }: HttpContext) => {\n if (validationMethods.all) {\n const output = await validationMethods.all.call(resource, { request, response });\n\n if (output) return output;\n }\n\n if (validationMethods[method]) {\n return await validationMethods[method]?.call(resource, { request, response });\n }\n\n return;\n };\n }\n\n if (!isEmpty(validation)) {\n handler.validation = validation;\n }\n } else {\n handler.validation = resource.validation[method];\n\n if (handler.validation?.validate) {\n handler.validation.validate = handler.validation.validate.bind(resource);\n }\n }\n\n return handler;\n }\n\n /**\n * Get all routes list\n */\n public list() {\n return this.routes;\n }\n\n /**\n * Return fresh browser-safe snapshots of named, non-page routes.\n *\n * Names are the registered names, including method suffixes. `all` stays\n * intact as route metadata; consumers decide whether their use supports it.\n * A route that opted out with `clientVisible: false` carries that flag so\n * browser-facing consumers can leave it out. `sites` is present only on a\n * route that declared some, and `guarded: true` only on a route with an auth\n * guard in its middleware chain (group middleware included).\n */\n public getNamedApiRoutes(options: NamedApiRoutesOptions = {}): readonly NamedApiRoute[] {\n return Object.freeze(\n this.routes\n .filter((route) => !route.isPage && typeof route.name === \"string\" && route.name.length > 0)\n .map((route) => {\n // `clientVisible: false` is the only key this flag ever adds, and it is\n // present only then: the common snapshot keeps its exact shape.\n const snapshot = {\n name: route.name!,\n path: route.path,\n method: route.method,\n ...(route.clientVisible === false ? { clientVisible: false as const } : {}),\n ...(route.sites === undefined ? {} : { sites: Object.freeze([...route.sites]) }),\n ...(isRequiredGuardRoute(route) ? { guarded: true as const } : {}),\n };\n const schema = route.handler?.responseSchema;\n const response = schema ? options.resolveResponse?.(schema, route) : undefined;\n\n // A route without a declared schema keeps exactly the three-key record.\n if (!response || Object.keys(response).length === 0) return Object.freeze(snapshot);\n\n return Object.freeze({ ...snapshot, response: Object.freeze({ ...response }) });\n }),\n );\n }\n\n /**\n * Number of routes currently registered on the singleton.\n *\n * Used as a readiness signal: a successful boot that ends up with zero\n * routes almost always means a route module failed to register silently\n * (see `withSourceFile`), so callers can surface that instead of letting\n * the whole surface 404.\n */\n public routeCount(): number {\n return this.routes.length;\n }\n\n /**\n * Register routes to the server\n */\n public scan(server: FastifyInstance) {\n // Every route is registered by the time we scan, so this is the first\n // moment the whole list can be reported at once — and it is still before a\n // single request is served.\n reportPositionalHandlerSuspects();\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n // Fastify automatically exposes HEAD for every GET route. When an app\n // declares its own HEAD route at the same path, suppress only that GET\n // route's implicit registration so the explicit handler owns HEAD,\n // regardless of declaration order.\n const explicitHeadPaths = new Set(\n this.routes\n .filter((route) => route.method.toLowerCase() === \"head\")\n .map((route) => route.path),\n );\n\n this.routes.forEach((route) => {\n const requestMethod = route.method.toLowerCase();\n const requestMethodFunction = server[requestMethod].bind(server);\n\n const options = {\n ...route.serverOptions,\n ...(requestMethod === \"get\" &&\n explicitHeadPaths.has(route.path) && { exposeHeadRoute: false }),\n config: {\n ...route.serverOptions?.config,\n // `undefined` keeps the global policy; `false` exempts the route.\n rateLimit: resolveRouteRateLimit(route),\n },\n };\n\n requestMethodFunction(\n route.path,\n options,\n async (baseRequest: FastifyRequest, reply: FastifyReply) => {\n const { output, response } = await this.handleRoute(route)(baseRequest, reply);\n\n return output || response.baseResponse;\n },\n );\n });\n\n this.registerStaticDirectories(server);\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Scan routes for the development server\n * Uses wildcard routing with find-my-way for HMR support\n */\n public scanDevServer(server: FastifyInstance) {\n // Same boot-time report as production `scan`. Routes reloaded later by HMR\n // are still recorded, but only surface on the next scan or via\n // `warlock doctor`.\n reportPositionalHandlerSuspects();\n\n // Development only: list mutating routes nobody guarded. Routes added by a\n // later HMR reload are reported when their replacement commits.\n this.warnUnguardedRoutes =\n configAccessor.key<boolean>(\"http.warnUnguardedRoutes\", true) !== false;\n if (this.warnUnguardedRoutes) {\n reportUnguardedMutatingRoutes(this.routes);\n }\n\n this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n let routeRegistry: RouteRegistry | undefined;\n let registryVersion = -1;\n\n const applyDevRateLimit = createDevRateLimiter(\n server,\n config.get(\"http.rateLimit.global\") !== false,\n );\n\n // Rebuilt when the route table changes rather than per request. Building it\n // inside the handler re-registered every route on every hit — and `all`\n // routes expand into seven registrations each. Keyed on `routesVersion`\n // rather than on the route count, so an HMR reload that swaps a route\n // without changing the count still invalidates.\n const resolveRouteRegistry = () => {\n if (routeRegistry && registryVersion === this.routesVersion) {\n return routeRegistry;\n }\n\n routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n\n registryVersion = this.routesVersion;\n\n return routeRegistry;\n };\n\n // Matching happens here, in Fastify's own onRequest phase, so a route's\n // `serverOptions.onRequest` still runs BEFORE body parsing. Production\n // `scan()` gets that from per-route registration; the wildcard dispatcher\n // has no per-route slot, so without this the hook silently never runs.\n server.addHook(\n \"onRequest\",\n async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n // Only requests Fastify routed to the dev wildcard belong to the app's\n // router. A plugin's own route (devtools' `/__warlock/api/requests/:id`)\n // must keep its params even when an app catch-all matches the URL too.\n if (fastifyRequest.routeOptions.url !== \"*\") {\n return undefined;\n }\n\n const match = resolveRouteRegistry().find(fastifyRequest.method, fastifyRequest.url);\n\n if (!match) {\n return undefined;\n }\n\n (fastifyRequest as DevDispatchRequest).matchedDevRoute = match;\n\n fastifyRequest.params = match.params;\n\n // Same slot production gives it: the limiter runs first in onRequest,\n // ahead of the route's own hooks.\n await applyDevRateLimit(match.route, fastifyRequest, fastifyReply);\n\n if (fastifyReply.sent) {\n return fastifyReply;\n }\n\n return runRouteHooks(match.route, \"onRequest\", fastifyRequest, fastifyReply);\n },\n );\n\n for (const phase of FORWARDED_ROUTE_PHASES.filter((name) => name !== \"onRequest\")) {\n server.addHook(phase, async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n if (!match) {\n return undefined;\n }\n\n return runRouteHooks(match.route, phase, fastifyRequest, fastifyReply);\n });\n }\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n const match = (fastifyRequest as DevDispatchRequest).matchedDevRoute;\n\n // No match found - return 404\n if (!match) {\n return fastifyReply\n .code(404)\n .send(buildNotFoundBody(fastifyRequest.method, fastifyRequest.url));\n }\n\n try {\n // Call the matched route handler\n const { output, response } = await this.handleRoute(match.route)(\n fastifyRequest,\n fastifyReply,\n );\n\n return output || response.baseResponse;\n } catch (error) {\n log.error(\"router\", \"dev-dispatch\", error as Error, {\n method: fastifyRequest.method,\n url: buildRequestLogSnapshot({\n id: fastifyRequest.id,\n method: fastifyRequest.method,\n url: fastifyRequest.url,\n route: match.route,\n }).url,\n });\n\n throw error;\n }\n };\n\n // Every verb production can register. Fastify's implicit HEAD for the GET\n // wildcard is switched off so the HEAD wildcard owns it (the registry falls\n // back to the GET route, exactly as production's implicit HEAD does).\n // `@fastify/cors` registers its own OPTIONS \"*\" catch-all whenever\n // preflight is on. Use the plugin's options as well as hasRoute so this\n // dispatcher works both after HTTP plugin boot and before queued plugins.\n const corsOwnsPreflight = buildCorsOptions().preflight !== false;\n\n for (const method of DEV_DISPATCH_METHODS) {\n if (\n method === \"OPTIONS\" &&\n (corsOwnsPreflight || server.hasRoute({ method: \"OPTIONS\", url: \"*\" }))\n ) {\n continue;\n }\n\n server.route({\n method,\n url: \"*\",\n ...(method === \"GET\" && { exposeHeadRoute: false }),\n // The dispatcher limits each matched route itself (see\n // `createDevRateLimiter`), so the plugin must not limit the wildcard:\n // that would count exempt routes and unmatched URLs too.\n config: { rateLimit: false },\n handler: wildcardHandler,\n });\n }\n\n this.registerStaticDirectories(server);\n\n this.eventListeners.afterScanning?.forEach((callback) => callback(this, server));\n }\n\n /**\n * Get the route path for the given route name\n */\n public getRoute(name: string, params: Record<string, any> = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new WarlockError(\"WL3003\", `Route name \"${name}\" not found`);\n }\n\n const used = new Set<string>();\n\n const path = route.path.replace(/:([A-Za-z0-9_]+)(\\?)?/g, (_match, key: string, optional) => {\n const value = params[key];\n\n if (value === undefined || value === null) {\n if (optional) return \"\";\n\n throw new WarlockError(\"WL3004\", `Route \"${name}\" is missing the \"${key}\" param`);\n }\n\n used.add(key);\n\n return encodeURIComponent(String(value));\n });\n\n const query = Object.keys(params)\n .filter((key) => !used.has(key) && params[key] !== undefined && params[key] !== null)\n .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(String(params[key]))}`)\n .join(\"&\");\n\n return query ? `${path}?${query}` : path;\n }\n\n /**\n * Handle the given route\n */\n private handleRoute(route: Route) {\n return async (fastifyRequest: FastifyRequest, fastifyResponse: FastifyReply) => {\n const request = new Request();\n const response = new Response();\n response.setResponse(fastifyResponse);\n request.response = response;\n\n response.request = request;\n\n // \"route.match\" tracing phase: the pattern is\n // already known here (`route.path`), so this brackets the cost of\n // stamping the request/route onto the `Request` instance rather than\n // route-registry matching itself, which happens upstream of this\n // function for both the production `scan()` path and the dev wildcard\n // dispatcher (both funnel into `handleRoute`).\n const tracingEnabled = isTracingEnabled();\n const routeMatchStartedAt = tracingEnabled ? performance.now() : 0;\n\n request.setRequest(fastifyRequest).setRoute(route);\n\n if (tracingEnabled) {\n dispatchPhase(buildTracingContext(request), {\n name: \"route.match\",\n durationMs: performance.now() - routeMatchStartedAt,\n attrs: { route: route.path },\n });\n }\n\n /*\n Both ends of the entry, not just the start — see\n `log-request-lifecycle.ts`. A start line on its own made a hung request\n and an instant one look identical, and the completion line is what makes\n a MISSING one legible as a hang.\n */\n const result = await logRequestLifecycle(\n {\n info: (entry) => log.info(entry),\n warn: (entry) => log.warn(entry),\n error: (entry) => log.error(entry),\n now: () => performance.now(),\n },\n {\n module: \"route\",\n action: describeRouteForLog(route.method, route.path),\n requestId: request.id,\n // A bounded snapshot, built once with the route's logging policy\n // applied — never the Request/Response instances, whose native\n // request, reply and URL graphs would reach every log channel.\n context: { request: request.toLogSnapshot() },\n request,\n // Read after the run: the status is decided during the request.\n statusCode: () => fastifyResponse.statusCode,\n },\n () => request.execute(),\n );\n\n // A handler may return a plain object (`ReturnedResponse`). Route it\n // through `Response.send` so status, events and hooks apply, exactly as\n // middleware outputs already do.\n let output = result;\n\n if (\n output !== undefined &&\n output !== null &&\n !(output instanceof Response) &&\n (output as unknown) !== fastifyResponse\n ) {\n output = await response.send(output);\n }\n\n return {\n output,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAM,yBAAyB;CAAC;CAAa;CAAiB;AAAY;AAc1E,SAAS,WACP,MACsB;CACtB,IAAI,CAAC,MACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AAC3C;;;;;;;;AASA,eAAe,cACb,OACA,OACA,SACA,OACA;CACA,MAAM,QAAQ,WACZ,MAAM,gBAAgB,MACxB;CAEA,KAAK,MAAM,QAAQ,OAGjB,IAAI,MAFkB,KAAK,SAAS,KAAK,MAEzB,OACd,OAAO;AAKb;;;;;AAMA,SAAS,mBAAmB,QAAiB,QAA8B;CACzE,MAAM,iBAAkB,QAAuC;CAE/D,IAAI,gBACF,OAAO,iBAAiB;AAE5B;;;;AAKA,SAAS,oBACP,UACA,QACgB;CAChB,MAAM,SAAS,SAAS;CACxB,MAAM,UAAU,QAAQ,KAAK,QAAQ;CAErC,mBAAmB,QAAQ,OAAO;CAElC,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAS,sBAAsB,OAAc;CAC3C,MAAM,OAAO,MAAM,SAAS,eAAe;CAC3C,MAAM,SAAS,MAAM,aAAa,eAAe,MAAM,eAAe;CAEtE,OAAO,GAAG,KAAK,GAAG,MAAM,OAAO,GAAG,MAAM,KAAK,IAAI,OAAO;AAC1D;AAEA,IAAa,SAAb,MAAa,OAAO;;;;CAgElB,OAAc,cAAc;EAC1B,IAAI,CAAC,OAAO,UACV,OAAO,WAAW,IAAI,OAAO;EAG/B,OAAO,OAAO;CAChB;CAEA,AAAQ,cAAc;gBApEI,CA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;;;CAKA,AAAQ,YAAY,OAAc;EAChC,OAAO,OAAO,gBAAgC,oBAAkC;GAC9E,MAAM,UAAU,IAAI,QAAQ;GAC5B,MAAM,WAAW,IAAI,SAAS;GAC9B,SAAS,YAAY,eAAe;GACpC,QAAQ,WAAW;GAEnB,SAAS,UAAU;GAQnB,MAAM,iBAAiB,iBAAiB;GACxC,MAAM,sBAAsB,iBAAiB,YAAY,IAAI,IAAI;GAEjE,QAAQ,WAAW,cAAc,CAAC,CAAC,SAAS,KAAK;GAEjD,IAAI,gBACF,cAAc,oBAAoB,OAAO,GAAG;IAC1C,MAAM;IACN,YAAY,YAAY,IAAI,IAAI;IAChC,OAAO,EAAE,OAAO,MAAM,KAAK;GAC7B,CAAC;GAkCH,IAAI,SAAS,MAzBQ,oBACnB;IACE,OAAO,UAAU,IAAI,KAAK,KAAK;IAC/B,OAAO,UAAU,IAAI,KAAK,KAAK;IAC/B,QAAQ,UAAU,IAAI,MAAM,KAAK;IACjC,WAAW,YAAY,IAAI;GAC7B,GACA;IACE,QAAQ;IACR,QAAQ,oBAAoB,MAAM,QAAQ,MAAM,IAAI;IACpD,WAAW,QAAQ;IAInB,SAAS,EAAE,SAAS,QAAQ,cAAc,EAAE;IAC5C;IAEA,kBAAkB,gBAAgB;GACpC,SACM,QAAQ,QAAQ,CACxB;GAOA,IACE,WAAW,UACX,WAAW,QACX,EAAE,kBAAkB,aACnB,WAAuB,iBAExB,SAAS,MAAM,SAAS,KAAK,MAAM;GAGrC,OAAO;IACL;IACA;IACA;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
@@ -337,6 +337,17 @@ export interface RouteOptions {
337
337
  * router.post("/internal/reindex", reindexController, { name: "internal.reindex", clientVisible: false });
338
338
  */
339
339
  clientVisible?: boolean;
340
+ /**
341
+ * The sites (`web.sites` keys) a multi-site app offers this named API route
342
+ * to in the browser. Absent means the route is shared: every site may embed
343
+ * it. A route registered inside a `router.group({ sites })` inherits the
344
+ * group's list unless it declares its own. This scopes browser route tables
345
+ * only; the endpoint itself still answers on every host.
346
+ *
347
+ * @example
348
+ * router.post("/api/admin/users", createUser, { name: "admin.users.create", sites: ["admin"] });
349
+ */
350
+ sites?: readonly string[];
340
351
  }
341
352
  export type RequestMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "HEAD" | "all";
342
353
  /** Browser-safe snapshot metadata for a named application API route. */
@@ -356,6 +367,14 @@ export type NamedApiRoute = Readonly<{
356
367
  * `clientVisible: false`. Absent means the route may be embedded in pages.
357
368
  */
358
369
  clientVisible?: false;
370
+ /** The route's declared `sites`, present only when it declared some. */
371
+ sites?: readonly string[];
372
+ /**
373
+ * Present only as `true`: a required auth guard (see `markAuthGuard`) is in
374
+ * the route's middleware chain, group middleware included. Browser tables
375
+ * leave such a route out for guest viewers.
376
+ */
377
+ guarded?: true;
359
378
  }>;
360
379
  /** Options for `router.getNamedApiRoutes()`. */
361
380
  export type NamedApiRoutesOptions = Readonly<{
@@ -433,6 +452,11 @@ export type GroupedRoutesOptions = {
433
452
  * opts it back out.
434
453
  */
435
454
  public?: boolean;
455
+ /**
456
+ * Offer every named API route in the group only to these sites (see
457
+ * `RouteOptions.sites`). A route's own `sites` replaces it.
458
+ */
459
+ sites?: readonly string[];
436
460
  };
437
461
  /** Route resource */
438
462
  export type RouteResource = {
@@ -495,6 +519,8 @@ export type RouterStacks = {
495
519
  * is open default to `public: true`.
496
520
  */
497
521
  public?: number;
522
+ /** Open `router.group({ sites })` scopes, innermost last. */
523
+ sites?: (readonly string[])[];
498
524
  /**
499
525
  * Source file path for routes being added (for HMR route tracking)
500
526
  */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/router/types.ts"],"mappings":";;;;;;;;;;;;;YAUY,qBAAqB;;;;;;;YAQrB,WAAW,0BAA0B,UAAU;GACxD,SAAS,YAAY,qBAAqB;;YAGjC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
26
  */
27
27
  export declare function isAuthGuardMiddleware(middleware: unknown): boolean;
28
+ /**
29
+ * Whether an auth guard is in the route's middleware chain. `route.middleware`
30
+ * already holds the middleware of every enclosing `router.group`, so a guard
31
+ * declared once on a group counts for each route inside it.
32
+ */
33
+ export declare function isRequiredGuardRoute(route: Pick<Route, "middleware">): boolean;
28
34
  /** Whether a route mutates state, is not a page route, and is neither guarded nor public. */
29
35
  export declare function isUnguardedMutatingRoute(route: Route): boolean;
30
36
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"unguarded-route-diagnostics.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/router/unguarded-route-diagnostics.ts"],"mappings":";;;;;;;;qBAuBa;;;;;;;;;;;;wBAaG,cAAc,cAAc,2BAC1C,YAAY,GACZ,oBACC;;;;;;wBAea,sBAAsB;;wBAUtB,yBAAyB,OAAO;;;;;wBAoBhC,8BACd,iBAAiB,SACjB,SAAQ,YAAY,eACnB;;wBAsCa"}
1
+ {"version":3,"file":"unguarded-route-diagnostics.d.mts","names":[],"sources":["../../../../../../../../packages/core/src/router/unguarded-route-diagnostics.ts"],"mappings":";;;;;;;;qBAuBa;;;;;;;;;;;;wBAaG,cAAc,cAAc,2BAC1C,YAAY,GACZ,oBACC;;;;;;wBAea,sBAAsB;;;;;;wBActB,qBAAqB,OAAO,KAAK;;wBAKjC,yBAAyB,OAAO;;;;;wBAoBhC,8BACd,iBAAiB,SACjB,SAAQ,YAAY,eACnB;;wBAsCa"}
@@ -51,12 +51,20 @@ function isAuthGuardMiddleware(middleware) {
51
51
  if (typeof marker === "boolean") return marker;
52
52
  return isAuthGuardName(middleware.name);
53
53
  }
54
+ /**
55
+ * Whether an auth guard is in the route's middleware chain. `route.middleware`
56
+ * already holds the middleware of every enclosing `router.group`, so a guard
57
+ * declared once on a group counts for each route inside it.
58
+ */
59
+ function isRequiredGuardRoute(route) {
60
+ return (route.middleware ?? []).some(isAuthGuardMiddleware);
61
+ }
54
62
  /** Whether a route mutates state, is not a page route, and is neither guarded nor public. */
55
63
  function isUnguardedMutatingRoute(route) {
56
64
  if (!isMutatingHttpMethod(String(route.method))) return false;
57
65
  if (route.isPage) return false;
58
66
  if (route.public === true) return false;
59
- return !(route.middleware ?? []).some(isAuthGuardMiddleware);
67
+ return !isRequiredGuardRoute(route);
60
68
  }
61
69
  /** Routes already reported in this process, so an HMR reload does not repeat them. */
62
70
  const reported = /* @__PURE__ */ new Set();
@@ -91,5 +99,5 @@ function resetUnguardedRouteReports() {
91
99
  }
92
100
 
93
101
  //#endregion
94
- export { AUTH_GUARD_MARKER, isAuthGuardMiddleware, isUnguardedMutatingRoute, markAuthGuard, reportUnguardedMutatingRoutes, resetUnguardedRouteReports };
102
+ export { AUTH_GUARD_MARKER, isAuthGuardMiddleware, isRequiredGuardRoute, isUnguardedMutatingRoute, markAuthGuard, reportUnguardedMutatingRoutes, resetUnguardedRouteReports };
95
103
  //# sourceMappingURL=unguarded-route-diagnostics.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"unguarded-route-diagnostics.mjs","names":[],"sources":["../../../../../../../../packages/core/src/router/unguarded-route-diagnostics.ts"],"sourcesContent":["/**\n * Development warning for mutating routes that nobody guarded.\n *\n * A POST/PUT/PATCH/DELETE route without auth middleware is reachable by anyone\n * who can reach the server. Sometimes that is the point (a login, a webhook, a\n * contact form) and sometimes it is a forgotten `guarded()` block. The router\n * cannot tell the two apart, so the app says which with `public: true`, and\n * `warlock dev` lists every mutating route that has neither.\n *\n * Warning only: routes register and behave exactly as before, nothing here\n * throws, and production never runs it. `warlock check` reports the same\n * routes from source as `WL9006`, before the app runs.\n */\n\nimport { log } from \"@warlock.js/logger\";\nimport { isAuthGuardName, isMutatingHttpMethod } from \"./route-guard-names\";\nimport type { Route } from \"./types\";\n\n/**\n * Marks a middleware as an authentication guard. A registry symbol, so a copy\n * of core loaded twice (a linked package next to an installed one) still\n * recognises guards the other copy marked.\n */\nexport const AUTH_GUARD_MARKER: unique symbol = Symbol.for(\"warlock.js.authGuard\");\n\n/**\n * Declare whether a middleware authenticates the request. `authMiddleware()`\n * from `@warlock.js/auth` marks itself (and marks `{ optional: true }` as not\n * a guard); use this for a hand-written guard whose name does not contain\n * `auth` or `guard`.\n *\n * @example\n * export const requireApiKey = markAuthGuard(async ({ request, response }) => {\n * if (request.headers[\"x-api-key\"] !== env(\"API_KEY\")) return response.unauthorized();\n * });\n */\nexport function markAuthGuard<T extends (...args: never[]) => unknown>(\n middleware: T,\n isGuard = true,\n): T {\n Object.defineProperty(middleware, AUTH_GUARD_MARKER, {\n value: isGuard,\n configurable: true,\n enumerable: false,\n });\n\n return middleware;\n}\n\n/**\n * Whether a middleware authenticates the request: its {@link markAuthGuard}\n * marker when it has one, otherwise a function name containing `auth` or\n * `guard`.\n */\nexport function isAuthGuardMiddleware(middleware: unknown): boolean {\n if (typeof middleware !== \"function\") return false;\n\n const marker: unknown = Reflect.get(middleware, AUTH_GUARD_MARKER);\n if (typeof marker === \"boolean\") return marker;\n\n return isAuthGuardName(middleware.name);\n}\n\n/** Whether a route mutates state, is not a page route, and is neither guarded nor public. */\nexport function isUnguardedMutatingRoute(route: Route): boolean {\n if (!isMutatingHttpMethod(String(route.method))) return false;\n // Page actions are authorized by the page itself (`requireUser()`).\n if (route.isPage) return false;\n if (route.public === true) return false;\n\n return !(route.middleware ?? []).some(isAuthGuardMiddleware);\n}\n\n/** Routes already reported in this process, so an HMR reload does not repeat them. */\nconst reported = new Set<string>();\n\nfunction routeKey(route: Route): string {\n return `${String(route.method).toUpperCase()} ${route.path}`;\n}\n\n/**\n * Warn, once per route per process, about every mutating route with no auth\n * middleware and no `public: true`. Returns the routes it reported.\n */\nexport function reportUnguardedMutatingRoutes(\n routes: readonly Route[],\n logger: Pick<typeof log, \"warn\"> = log,\n): Route[] {\n const fresh = routes.filter(\n (route) => isUnguardedMutatingRoute(route) && !reported.has(routeKey(route)),\n );\n\n if (fresh.length === 0) return fresh;\n\n for (const route of fresh) reported.add(routeKey(route));\n\n const headline =\n fresh.length === 1\n ? \"1 mutating route has no auth middleware and is not marked public.\"\n : `${fresh.length} mutating routes have no auth middleware and are not marked public.`;\n\n logger.warn({\n module: \"router\",\n action: \"unguardedRoute\",\n message:\n `${headline} Anyone who can reach the server can call them. Add auth middleware ` +\n `(e.g. register them inside a guarded group), or pass { public: true } if they are ` +\n `meant to be open:\\n` +\n fresh\n .map((route) => ` - ${routeKey(route)}${route.sourceFile ? ` (${route.sourceFile})` : \"\"}`)\n .join(\"\\n\"),\n context: {\n routes: fresh.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n sourceFile: route.sourceFile,\n })),\n },\n });\n\n return fresh;\n}\n\n/** Forget what was reported (tests). */\nexport function resetUnguardedRouteReports(): void {\n reported.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,oBAAmC,OAAO,IAAI,sBAAsB;;;;;;;;;;;;AAajF,SAAgB,cACd,YACA,UAAU,MACP;CACH,OAAO,eAAe,YAAY,mBAAmB;EACnD,OAAO;EACP,cAAc;EACd,YAAY;CACd,CAAC;CAED,OAAO;AACT;;;;;;AAOA,SAAgB,sBAAsB,YAA8B;CAClE,IAAI,OAAO,eAAe,YAAY,OAAO;CAE7C,MAAM,SAAkB,QAAQ,IAAI,YAAY,iBAAiB;CACjE,IAAI,OAAO,WAAW,WAAW,OAAO;CAExC,OAAO,gBAAgB,WAAW,IAAI;AACxC;;AAGA,SAAgB,yBAAyB,OAAuB;CAC9D,IAAI,CAAC,qBAAqB,OAAO,MAAM,MAAM,CAAC,GAAG,OAAO;CAExD,IAAI,MAAM,QAAQ,OAAO;CACzB,IAAI,MAAM,WAAW,MAAM,OAAO;CAElC,OAAO,EAAE,MAAM,cAAc,CAAC,EAAC,CAAE,KAAK,qBAAqB;AAC7D;;AAGA,MAAM,2BAAW,IAAI,IAAY;AAEjC,SAAS,SAAS,OAAsB;CACtC,OAAO,GAAG,OAAO,MAAM,MAAM,CAAC,CAAC,YAAY,EAAE,GAAG,MAAM;AACxD;;;;;AAMA,SAAgB,8BACd,QACA,SAAmC,KAC1B;CACT,MAAM,QAAQ,OAAO,QAClB,UAAU,yBAAyB,KAAK,KAAK,CAAC,SAAS,IAAI,SAAS,KAAK,CAAC,CAC7E;CAEA,IAAI,MAAM,WAAW,GAAG,OAAO;CAE/B,KAAK,MAAM,SAAS,OAAO,SAAS,IAAI,SAAS,KAAK,CAAC;CAEvD,MAAM,WACJ,MAAM,WAAW,IACb,sEACA,GAAG,MAAM,OAAO;CAEtB,OAAO,KAAK;EACV,QAAQ;EACR,QAAQ;EACR,SACE,GAAG,SAAS,6KAGZ,MACG,KAAK,UAAU,OAAO,SAAS,KAAK,IAAI,MAAM,aAAa,KAAK,MAAM,WAAW,KAAK,IAAI,CAAC,CAC3F,KAAK,IAAI;EACd,SAAS,EACP,QAAQ,MAAM,KAAK,WAAW;GAC5B,QAAQ,MAAM;GACd,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,YAAY,MAAM;EACpB,EAAE,EACJ;CACF,CAAC;CAED,OAAO;AACT;;AAGA,SAAgB,6BAAmC;CACjD,SAAS,MAAM;AACjB"}
1
+ {"version":3,"file":"unguarded-route-diagnostics.mjs","names":[],"sources":["../../../../../../../../packages/core/src/router/unguarded-route-diagnostics.ts"],"sourcesContent":["/**\n * Development warning for mutating routes that nobody guarded.\n *\n * A POST/PUT/PATCH/DELETE route without auth middleware is reachable by anyone\n * who can reach the server. Sometimes that is the point (a login, a webhook, a\n * contact form) and sometimes it is a forgotten `guarded()` block. The router\n * cannot tell the two apart, so the app says which with `public: true`, and\n * `warlock dev` lists every mutating route that has neither.\n *\n * Warning only: routes register and behave exactly as before, nothing here\n * throws, and production never runs it. `warlock check` reports the same\n * routes from source as `WL9006`, before the app runs.\n */\n\nimport { log } from \"@warlock.js/logger\";\nimport { isAuthGuardName, isMutatingHttpMethod } from \"./route-guard-names\";\nimport type { Route } from \"./types\";\n\n/**\n * Marks a middleware as an authentication guard. A registry symbol, so a copy\n * of core loaded twice (a linked package next to an installed one) still\n * recognises guards the other copy marked.\n */\nexport const AUTH_GUARD_MARKER: unique symbol = Symbol.for(\"warlock.js.authGuard\");\n\n/**\n * Declare whether a middleware authenticates the request. `authMiddleware()`\n * from `@warlock.js/auth` marks itself (and marks `{ optional: true }` as not\n * a guard); use this for a hand-written guard whose name does not contain\n * `auth` or `guard`.\n *\n * @example\n * export const requireApiKey = markAuthGuard(async ({ request, response }) => {\n * if (request.headers[\"x-api-key\"] !== env(\"API_KEY\")) return response.unauthorized();\n * });\n */\nexport function markAuthGuard<T extends (...args: never[]) => unknown>(\n middleware: T,\n isGuard = true,\n): T {\n Object.defineProperty(middleware, AUTH_GUARD_MARKER, {\n value: isGuard,\n configurable: true,\n enumerable: false,\n });\n\n return middleware;\n}\n\n/**\n * Whether a middleware authenticates the request: its {@link markAuthGuard}\n * marker when it has one, otherwise a function name containing `auth` or\n * `guard`.\n */\nexport function isAuthGuardMiddleware(middleware: unknown): boolean {\n if (typeof middleware !== \"function\") return false;\n\n const marker: unknown = Reflect.get(middleware, AUTH_GUARD_MARKER);\n if (typeof marker === \"boolean\") return marker;\n\n return isAuthGuardName(middleware.name);\n}\n\n/**\n * Whether an auth guard is in the route's middleware chain. `route.middleware`\n * already holds the middleware of every enclosing `router.group`, so a guard\n * declared once on a group counts for each route inside it.\n */\nexport function isRequiredGuardRoute(route: Pick<Route, \"middleware\">): boolean {\n return (route.middleware ?? []).some(isAuthGuardMiddleware);\n}\n\n/** Whether a route mutates state, is not a page route, and is neither guarded nor public. */\nexport function isUnguardedMutatingRoute(route: Route): boolean {\n if (!isMutatingHttpMethod(String(route.method))) return false;\n // Page actions are authorized by the page itself (`requireUser()`).\n if (route.isPage) return false;\n if (route.public === true) return false;\n\n return !isRequiredGuardRoute(route);\n}\n\n/** Routes already reported in this process, so an HMR reload does not repeat them. */\nconst reported = new Set<string>();\n\nfunction routeKey(route: Route): string {\n return `${String(route.method).toUpperCase()} ${route.path}`;\n}\n\n/**\n * Warn, once per route per process, about every mutating route with no auth\n * middleware and no `public: true`. Returns the routes it reported.\n */\nexport function reportUnguardedMutatingRoutes(\n routes: readonly Route[],\n logger: Pick<typeof log, \"warn\"> = log,\n): Route[] {\n const fresh = routes.filter(\n (route) => isUnguardedMutatingRoute(route) && !reported.has(routeKey(route)),\n );\n\n if (fresh.length === 0) return fresh;\n\n for (const route of fresh) reported.add(routeKey(route));\n\n const headline =\n fresh.length === 1\n ? \"1 mutating route has no auth middleware and is not marked public.\"\n : `${fresh.length} mutating routes have no auth middleware and are not marked public.`;\n\n logger.warn({\n module: \"router\",\n action: \"unguardedRoute\",\n message:\n `${headline} Anyone who can reach the server can call them. Add auth middleware ` +\n `(e.g. register them inside a guarded group), or pass { public: true } if they are ` +\n `meant to be open:\\n` +\n fresh\n .map((route) => ` - ${routeKey(route)}${route.sourceFile ? ` (${route.sourceFile})` : \"\"}`)\n .join(\"\\n\"),\n context: {\n routes: fresh.map((route) => ({\n method: route.method,\n path: route.path,\n name: route.name,\n sourceFile: route.sourceFile,\n })),\n },\n });\n\n return fresh;\n}\n\n/** Forget what was reported (tests). */\nexport function resetUnguardedRouteReports(): void {\n reported.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,oBAAmC,OAAO,IAAI,sBAAsB;;;;;;;;;;;;AAajF,SAAgB,cACd,YACA,UAAU,MACP;CACH,OAAO,eAAe,YAAY,mBAAmB;EACnD,OAAO;EACP,cAAc;EACd,YAAY;CACd,CAAC;CAED,OAAO;AACT;;;;;;AAOA,SAAgB,sBAAsB,YAA8B;CAClE,IAAI,OAAO,eAAe,YAAY,OAAO;CAE7C,MAAM,SAAkB,QAAQ,IAAI,YAAY,iBAAiB;CACjE,IAAI,OAAO,WAAW,WAAW,OAAO;CAExC,OAAO,gBAAgB,WAAW,IAAI;AACxC;;;;;;AAOA,SAAgB,qBAAqB,OAA2C;CAC9E,QAAQ,MAAM,cAAc,CAAC,EAAC,CAAE,KAAK,qBAAqB;AAC5D;;AAGA,SAAgB,yBAAyB,OAAuB;CAC9D,IAAI,CAAC,qBAAqB,OAAO,MAAM,MAAM,CAAC,GAAG,OAAO;CAExD,IAAI,MAAM,QAAQ,OAAO;CACzB,IAAI,MAAM,WAAW,MAAM,OAAO;CAElC,OAAO,CAAC,qBAAqB,KAAK;AACpC;;AAGA,MAAM,2BAAW,IAAI,IAAY;AAEjC,SAAS,SAAS,OAAsB;CACtC,OAAO,GAAG,OAAO,MAAM,MAAM,CAAC,CAAC,YAAY,EAAE,GAAG,MAAM;AACxD;;;;;AAMA,SAAgB,8BACd,QACA,SAAmC,KAC1B;CACT,MAAM,QAAQ,OAAO,QAClB,UAAU,yBAAyB,KAAK,KAAK,CAAC,SAAS,IAAI,SAAS,KAAK,CAAC,CAC7E;CAEA,IAAI,MAAM,WAAW,GAAG,OAAO;CAE/B,KAAK,MAAM,SAAS,OAAO,SAAS,IAAI,SAAS,KAAK,CAAC;CAEvD,MAAM,WACJ,MAAM,WAAW,IACb,sEACA,GAAG,MAAM,OAAO;CAEtB,OAAO,KAAK;EACV,QAAQ;EACR,QAAQ;EACR,SACE,GAAG,SAAS,6KAGZ,MACG,KAAK,UAAU,OAAO,SAAS,KAAK,IAAI,MAAM,aAAa,KAAK,MAAM,WAAW,KAAK,IAAI,CAAC,CAC3F,KAAK,IAAI;EACd,SAAS,EACP,QAAQ,MAAM,KAAK,WAAW;GAC5B,QAAQ,MAAM;GACd,MAAM,MAAM;GACZ,MAAM,MAAM;GACZ,YAAY,MAAM;EACpB,EAAE,EACJ;CACF,CAAC;CAED,OAAO;AACT;;AAGA,SAAgB,6BAAmC;CACjD,SAAS,MAAM;AACjB"}
@@ -131,6 +131,24 @@ function isMarkedGuard(identifier) {
131
131
  const value = initializer ? unwrap(initializer) : void 0;
132
132
  return value !== void 0 && isCallExpression(value) && calleeName(value) === "markAuthGuard" && !(value.arguments[1]?.type === "Literal" && value.arguments[1].value === false);
133
133
  }
134
+ /**
135
+ * Whether a call such as `requireAdmin()` invokes a local factory
136
+ * (`const requireAdmin = () => markAuthGuard(fn)`) whose body declares the
137
+ * middleware it returns an auth guard. A name that says nothing about guards
138
+ * (`requireAdmin`) still counts once the factory marks itself.
139
+ */
140
+ function isMarkedGuardFactory(call) {
141
+ const callee = unwrap(expressionOf(call));
142
+ if (!isIdentifier(callee)) return false;
143
+ const initializer = resolveInitializer(callee);
144
+ if (!initializer || !isFunctionLike(unwrap(initializer))) return false;
145
+ let marked = false;
146
+ walk(initializer, (node) => {
147
+ if (isCallExpression(node) && calleeName(node) === "markAuthGuard" && !(node.arguments[1]?.type === "Literal" && node.arguments[1].value === false)) marked = true;
148
+ return marked ? false : void 0;
149
+ }, true);
150
+ return marked;
151
+ }
134
152
  function middlewareHasGuard(node) {
135
153
  const value = unwrap(node);
136
154
  if (!isArrayLiteralExpression(value)) return true;
@@ -139,7 +157,7 @@ function middlewareHasGuard(node) {
139
157
  if (isSpreadElement(element)) return true;
140
158
  const item = unwrap(element);
141
159
  if (isIdentifier(item)) return isGuardName(valueText(item)) || isMarkedGuard(item);
142
- if (isCallExpression(item)) return isGuardName(calleeName(item));
160
+ if (isCallExpression(item)) return !(calleeName(item) === "markAuthGuard" && item.arguments[1]?.type === "Literal" && item.arguments[1].value === false) && (isGuardName(calleeName(item)) || isMarkedGuardFactory(item));
143
161
  if (isMemberAccess(item)) return isGuardName(memberName(item));
144
162
  return false;
145
163
  });