@warlock.js/core 4.11.0 → 4.13.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 (200) hide show
  1. package/CHANGELOG.md +200 -0
  2. package/esm/cli/cli-commands.manager.mjs +28 -5
  3. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  4. package/esm/cli/commands/add.command.mjs +5 -3
  5. package/esm/cli/commands/add.command.mjs.map +1 -1
  6. package/esm/cli/commands/build.command.mjs +1 -1
  7. package/esm/cli/commands/build.command.mjs.map +1 -1
  8. package/esm/cli/commands/create-database.command.mjs +1 -1
  9. package/esm/cli/commands/create-database.command.mjs.map +1 -1
  10. package/esm/cli/commands/dev-server.command.mjs +1 -1
  11. package/esm/cli/commands/dev-server.command.mjs.map +1 -1
  12. package/esm/cli/commands/doctor/doctor-command.action.mjs.map +1 -1
  13. package/esm/cli/commands/doctor.command.mjs +1 -1
  14. package/esm/cli/commands/doctor.command.mjs.map +1 -1
  15. package/esm/cli/commands/drop-tables.command.mjs +1 -1
  16. package/esm/cli/commands/drop-tables.command.mjs.map +1 -1
  17. package/esm/cli/commands/generate/generate.command.mjs +43 -22
  18. package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
  19. package/esm/cli/commands/generate/generators/controller.generator.mjs.map +1 -1
  20. package/esm/cli/commands/generate/generators/migration.generator.mjs +1 -1
  21. package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
  22. package/esm/cli/commands/generate/generators/model.generator.mjs +1 -1
  23. package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
  24. package/esm/cli/commands/generate/generators/module.generator.mjs +1 -1
  25. package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
  26. package/esm/cli/commands/generate/generators/repository.generator.mjs.map +1 -1
  27. package/esm/cli/commands/generate/generators/resource.generator.mjs.map +1 -1
  28. package/esm/cli/commands/generate/generators/service.generator.mjs.map +1 -1
  29. package/esm/cli/commands/generate/utils/path-resolver.mjs +1 -1
  30. package/esm/cli/commands/generate/utils/writer.mjs +1 -1
  31. package/esm/cli/commands/migrate.command.mjs +7 -3
  32. package/esm/cli/commands/migrate.command.mjs.map +1 -1
  33. package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -1
  34. package/esm/cli/commands/routes.command.mjs +1 -1
  35. package/esm/cli/commands/routes.command.mjs.map +1 -1
  36. package/esm/cli/commands/seed.command.mjs +1 -1
  37. package/esm/cli/commands/seed.command.mjs.map +1 -1
  38. package/esm/cli/commands/start-production.command.mjs +1 -1
  39. package/esm/cli/commands/start-production.command.mjs.map +1 -1
  40. package/esm/cli/commands/storage-put.action.mjs.map +1 -1
  41. package/esm/cli/commands/storage-put.command.mjs +1 -1
  42. package/esm/cli/commands/storage-put.command.mjs.map +1 -1
  43. package/esm/cli/commands/typings-generator.command.mjs +2 -2
  44. package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
  45. package/esm/cli/commands/update.command.mjs +1 -1
  46. package/esm/cli/commands/update.command.mjs.map +1 -1
  47. package/esm/cli/commands-loader.mjs +1 -1
  48. package/esm/cli/commands-loader.mjs.map +1 -1
  49. package/esm/cli/parse-cli-args.mjs +86 -9
  50. package/esm/cli/parse-cli-args.mjs.map +1 -1
  51. package/esm/{cli → commands}/cli-command.d.mts +1 -1
  52. package/esm/commands/cli-command.d.mts.map +1 -0
  53. package/esm/{cli → commands}/cli-command.mjs +1 -1
  54. package/esm/commands/cli-command.mjs.map +1 -0
  55. package/esm/{cli → commands}/types.d.mts +1 -1
  56. package/esm/commands/types.d.mts.map +1 -0
  57. package/esm/config/load-config-files.mjs +1 -1
  58. package/esm/config/load-config-files.mjs.map +1 -1
  59. package/esm/connectors/base-connector.mjs +1 -1
  60. package/esm/connectors/base-connector.mjs.map +1 -1
  61. package/esm/connectors/connectors-manager.d.mts.map +1 -1
  62. package/esm/connectors/connectors-manager.mjs +5 -3
  63. package/esm/connectors/connectors-manager.mjs.map +1 -1
  64. package/esm/connectors/http-connector.d.mts.map +1 -1
  65. package/esm/connectors/http-connector.mjs +0 -2
  66. package/esm/connectors/http-connector.mjs.map +1 -1
  67. package/esm/database/create-database-action.mjs.map +1 -1
  68. package/esm/database/drop-tables-action.mjs.map +1 -1
  69. package/esm/database/migrate-action.mjs +54 -2
  70. package/esm/database/migrate-action.mjs.map +1 -1
  71. package/esm/database/pending-exit-code.mjs +39 -0
  72. package/esm/database/pending-exit-code.mjs.map +1 -0
  73. package/esm/database/resolve-pending-migrations.mjs +49 -0
  74. package/esm/database/resolve-pending-migrations.mjs.map +1 -0
  75. package/esm/database/seed-command-action.mjs +1 -1
  76. package/esm/database/seed-command-action.mjs.map +1 -1
  77. package/esm/dev-server/dev-logger.mjs +1 -1
  78. package/esm/dev-server/dev-logger.mjs.map +1 -1
  79. package/esm/dev-server/development-server.mjs +2 -2
  80. package/esm/dev-server/file-event-handler.mjs +1 -1
  81. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  82. package/esm/dev-server/file-manager.mjs +1 -1
  83. package/esm/dev-server/file-manager.mjs.map +1 -1
  84. package/esm/dev-server/file-operations.mjs +1 -1
  85. package/esm/dev-server/file-operations.mjs.map +1 -1
  86. package/esm/dev-server/files-orchestrator.mjs +3 -18
  87. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  88. package/esm/dev-server/files-watcher.mjs +1 -1
  89. package/esm/dev-server/files-watcher.mjs.map +1 -1
  90. package/esm/dev-server/health-checker/file-health-checker.contract.d.mts +1 -1
  91. package/esm/dev-server/layer-executor.mjs +1 -1
  92. package/esm/dev-server/loader/register-loader.mjs +1 -1
  93. package/esm/dev-server/package-json-manager.mjs +1 -1
  94. package/esm/dev-server/package-json-manager.mjs.map +1 -1
  95. package/esm/dev-server/parse-imports.mjs +2 -2
  96. package/esm/dev-server/parse-imports.mjs.map +1 -1
  97. package/esm/dev-server/tsconfig-manager.mjs +1 -1
  98. package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
  99. package/esm/dev-server/type-generator.mjs +1 -1
  100. package/esm/dev-server/type-generator.mjs.map +1 -1
  101. package/esm/dev-server/utils.mjs +1 -1
  102. package/esm/dev-server/utils.mjs.map +1 -1
  103. package/esm/generations/add-command.action.mjs +3 -3
  104. package/esm/generations/add-command.action.mjs.map +1 -1
  105. package/esm/http/build-cors-options.mjs +32 -0
  106. package/esm/http/build-cors-options.mjs.map +1 -0
  107. package/esm/http/middleware/max-body-size.middleware.d.mts +13 -5
  108. package/esm/http/middleware/max-body-size.middleware.d.mts.map +1 -1
  109. package/esm/http/middleware/max-body-size.middleware.mjs +13 -5
  110. package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
  111. package/esm/http/plugins.d.mts.map +1 -1
  112. package/esm/http/plugins.mjs +2 -9
  113. package/esm/http/plugins.mjs.map +1 -1
  114. package/esm/http/server.d.mts.map +1 -1
  115. package/esm/http/server.mjs +3 -8
  116. package/esm/http/server.mjs.map +1 -1
  117. package/esm/image/image.d.mts +3 -2
  118. package/esm/image/image.d.mts.map +1 -1
  119. package/esm/image/image.mjs +63 -17
  120. package/esm/image/image.mjs.map +1 -1
  121. package/esm/index.d.mts +9 -17
  122. package/esm/index.mjs +4 -15
  123. package/esm/mail/mailer-pool.d.mts.map +1 -1
  124. package/esm/mail/mailer-pool.mjs.map +1 -1
  125. package/esm/production/production-builder.mjs +51 -3
  126. package/esm/production/production-builder.mjs.map +1 -1
  127. package/esm/production/resolve-build-config.mjs +1 -1
  128. package/esm/production/resolve-build-config.mjs.map +1 -1
  129. package/esm/react/index.d.mts +4 -0
  130. package/esm/react/index.d.mts.map +1 -1
  131. package/esm/react/index.mjs +88 -14
  132. package/esm/react/index.mjs.map +1 -1
  133. package/esm/router/router.d.mts +9 -0
  134. package/esm/router/router.d.mts.map +1 -1
  135. package/esm/router/router.mjs +58 -5
  136. package/esm/router/router.mjs.map +1 -1
  137. package/esm/router/types.d.mts +24 -1
  138. package/esm/router/types.d.mts.map +1 -1
  139. package/esm/tests/index.d.mts +2 -2
  140. package/esm/tests/index.mjs +1 -2
  141. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  142. package/esm/tests/start-http-development-server.mjs +38 -15
  143. package/esm/tests/start-http-development-server.mjs.map +1 -1
  144. package/esm/tests/test-helpers.d.mts.map +1 -1
  145. package/esm/tests/test-helpers.mjs +34 -13
  146. package/esm/tests/test-helpers.mjs.map +1 -1
  147. package/esm/tests/vitest-setup.d.mts +1 -1
  148. package/esm/tests/vitest-setup.d.mts.map +1 -1
  149. package/esm/tests/vitest-setup.mjs +3 -3
  150. package/esm/tests/vitest-setup.mjs.map +1 -1
  151. package/esm/utils/framework-vesion.mjs +1 -1
  152. package/esm/utils/index.d.mts +1 -0
  153. package/esm/utils/index.mjs +1 -0
  154. package/esm/utils/normalized-path.d.mts +55 -0
  155. package/esm/utils/normalized-path.d.mts.map +1 -0
  156. package/esm/{dev-server/path.mjs → utils/normalized-path.mjs} +15 -2
  157. package/esm/utils/normalized-path.mjs.map +1 -0
  158. package/esm/vite/index.d.mts +2 -0
  159. package/esm/vite/index.mjs +1 -1
  160. package/esm/vite/lower-stage3-decorators.d.mts +1 -1
  161. package/esm/vite/lower-stage3-decorators.mjs +1 -1
  162. package/esm/vite/lower-stage3-decorators.mjs.map +1 -1
  163. package/esm/warlock-config/index.mjs +1 -1
  164. package/esm/warlock-config/types.d.mts +34 -1
  165. package/esm/warlock-config/types.d.mts.map +1 -1
  166. package/esm/warlock-config/warlock-config.manager.d.mts.map +1 -1
  167. package/esm/warlock-config/warlock-config.manager.mjs +1 -2
  168. package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
  169. package/llms-full.txt +78 -23
  170. package/llms.txt +3 -3
  171. package/package.json +24 -12
  172. package/skills/lower-stage3-decorators/SKILL.md +4 -2
  173. package/skills/process-image/SKILL.md +3 -1
  174. package/skills/run-app/SKILL.md +6 -0
  175. package/skills/test-http/SKILL.md +29 -10
  176. package/skills/test-service/SKILL.md +12 -8
  177. package/skills/use-middleware/SKILL.md +5 -1
  178. package/skills/write-cli-command/SKILL.md +19 -1
  179. package/esm/cli/cli-command.d.mts.map +0 -1
  180. package/esm/cli/cli-command.mjs.map +0 -1
  181. package/esm/cli/types.d.mts.map +0 -1
  182. package/esm/dev-server/files-orchestrator.d.mts +0 -89
  183. package/esm/dev-server/files-orchestrator.d.mts.map +0 -1
  184. package/esm/dev-server/files-watcher.d.mts +0 -69
  185. package/esm/dev-server/files-watcher.d.mts.map +0 -1
  186. package/esm/dev-server/health-checker/checkers/base-health-checker.d.mts +0 -55
  187. package/esm/dev-server/health-checker/checkers/base-health-checker.d.mts.map +0 -1
  188. package/esm/dev-server/health-checker/checkers/eslint-health-checker.d.mts +0 -44
  189. package/esm/dev-server/health-checker/checkers/eslint-health-checker.d.mts.map +0 -1
  190. package/esm/dev-server/health-checker/checkers/typescript-health-checker.d.mts +0 -60
  191. package/esm/dev-server/health-checker/checkers/typescript-health-checker.d.mts.map +0 -1
  192. package/esm/dev-server/health-checker/files-healthcare.manager.d.mts +0 -119
  193. package/esm/dev-server/health-checker/files-healthcare.manager.d.mts.map +0 -1
  194. package/esm/dev-server/health-checker/index.mjs +0 -7
  195. package/esm/dev-server/module-loader.d.mts +0 -63
  196. package/esm/dev-server/module-loader.d.mts.map +0 -1
  197. package/esm/dev-server/path.mjs.map +0 -1
  198. package/esm/tests/test-server-port-channel.d.mts +0 -27
  199. package/esm/tests/test-server-port-channel.d.mts.map +0 -1
  200. /package/esm/{cli → commands}/index.d.mts +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"router.mjs","names":[],"sources":["../../../../../../../core/src/router/router.ts"],"sourcesContent":["import proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport fastifyStatic, { type FastifyStaticOptions } from \"@fastify/static\";\nimport concatRoute from \"@mongez/concat-route\";\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 { Request } from \"../http/request\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { RouteRegistry } from \"./route-registry\";\nimport type {\n GroupedRoutesOptions,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\n} from \"./types\";\n\nexport class Router {\n /**\n * Routes list\n */\n private routes: Route[] = [];\n\n /**\n * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: FastifyStaticOptions[] = [];\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, (_request, response) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Server static folder\n */\n public directory(options: FastifyStaticOptions) {\n this.staticDirectories.push(options);\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(path: string, location: string, cacheTime?: number) {\n return this.get(path, (_request, response) => {\n response.sendFile(location, cacheTime);\n });\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(path: string, location: string, cacheTime?: number) {\n return this.get(path, (_request, response) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n\n /**\n * Serve list of files\n */\n public files(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, (_request, response) => {\n response.sendFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, (_request, response) => {\n response.sendCachedFile(location, cacheTime);\n });\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 concatRoute(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 path = concatRoute(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\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 if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new Error(\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\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 if (routeData.name) {\n // check if the name exists\n const route = this.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 Error(`Route name \"${routeData.name}\" already exists`);\n } else {\n routeData.name += `.${routeData.method.toLowerCase()}`;\n }\n }\n }\n\n this.routes.push(routeData);\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 return this.prefix(path, () => {\n path = \"\";\n // get base resource name\n const baseResourceName = options.name || toCamelCase(ltrim(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 const resourceName = baseResourceName + \".list\";\n this.get(path, options.replace?.list || routeResource.list.bind(routeResource), {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n const resourceName = baseResourceName + \".single\";\n\n this.get(path + \"/:id\", options.replace?.get || routeResource.get.bind(routeResource), {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const resourceName = baseResourceName + \".create\";\n\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const resourceName = baseResourceName + \".update\";\n\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const resourceName = baseResourceName + \".patch\";\n\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n const resourceName = baseResourceName + \".delete\";\n\n this.delete(\n path + \"/:id\",\n options.replace?.delete || routeResource.delete.bind(routeResource),\n {\n ...options,\n name: resourceName,\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n const resourceName = baseResourceName + \".bulkDelete\";\n\n this.delete(\n path,\n options.replace?.bulkDelete || routeResource.bulkDelete.bind(routeResource),\n {\n ...options,\n name: resourceName,\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 } = options;\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 }\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 this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = resource[method]?.bind(resource) as RequestHandler;\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: Request, response: Response) => {\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 * 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 this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\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 config: {\n ...route.serverOptions?.config,\n ...(route.rateLimit && { rateLimit: route.rateLimit }),\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 for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\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 this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n // Shared handler for wildcard routing\n const wildcardHandler = async (fastifyRequest: FastifyRequest, fastifyReply: FastifyReply) => {\n // Initialize route registry once (will be rebuilt on HMR via rebuildRouteRegistry)\n const routeRegistry = new RouteRegistry();\n\n routeRegistry.register(this.routes);\n // Find matching route using find-my-way\n const match = routeRegistry.find(fastifyRequest.method, fastifyRequest.url);\n\n // No match found - return 404\n if (!match) {\n return fastifyReply.code(404).send({\n error: \"Route not found\",\n path: fastifyRequest.url,\n method: fastifyRequest.method,\n });\n }\n\n // Inject extracted params into the request\n fastifyRequest.params = match.params;\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 console.log(error);\n throw error;\n }\n };\n\n // Register wildcard route for all methods EXCEPT OPTIONS (to avoid conflict with CORS)\n // OPTIONS is handled by @fastify/cors plugin for preflight requests\n const methods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"] as const;\n for (const method of methods) {\n server.route({\n method,\n url: \"*\",\n handler: wildcardHandler,\n });\n }\n\n // Register static directories\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\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: any = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new Error(`Route name \"${name}\" not found`);\n }\n\n let path = route.path;\n\n if (route.path.includes(\":\")) {\n Object.keys(params).forEach((key) => {\n path = path.replace(\":\" + key, params[key]);\n });\n }\n\n return 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 request.setRequest(fastifyRequest).setRoute(route);\n\n log.info({\n module: \"route\",\n action: route.method + \" \" + route.path.replace(\"/*\", \"\"),\n message: `Starting Request: ${request.id}`,\n context: {\n request,\n response,\n },\n });\n\n const result = await request.execute();\n\n return {\n output: result,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;AA0BA,IAAa,SAAb,MAAa,OAAO;;;;CAmClB,OAAc,cAAc;EAC1B,IAAI,CAAC,OAAO,UACV,OAAO,WAAW,IAAI,OAAO;EAG/B,OAAO,OAAO;CAChB;CAEA,AAAQ,cAAc;gBAvCI,CAAC;2BAU2B,CAAC;wBAMrD,CAAC;gBAM8B;GAC/B,QAAQ,CAAC;GACT,MAAM,CAAC;GACP,YAAY,CAAC;EACf;CAeA;;;;CAKA,AAAO,eAAe,UAA6D;EACjF,KAAK,eAAe,aAAa,CAAC,GAAI,KAAK,eAAe,cAAc,CAAC,GAAI,QAAQ;EAErF,OAAO;CACT;;;;CAKA,AAAO,cAAc,UAA6D;EAChF,KAAK,eAAe,gBAAgB,CAAC,GAAI,KAAK,eAAe,iBAAiB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G,GACzB,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,QAAQ;GACnC,OAAO,KAAK,QAAQ,MAAM,KAAK,OAAO,IAAI;EAC5C,CAAC;EAGH,OAAO;CACT;;;;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;GAEnB,QAAQ,WAAW,cAAc,CAAC,CAAC,SAAS,KAAK;GAEjD,IAAI,KAAK;IACP,QAAQ;IACR,QAAQ,MAAM,SAAS,MAAM,MAAM,KAAK,QAAQ,MAAM,EAAE;IACxD,SAAS,qBAAqB,QAAQ;IACtC,SAAS;KACP;KACA;IACF;GACF,CAAC;GAID,OAAO;IACL,QAAQ,MAHW,QAAQ,QAAQ;IAInC;IACA;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
1
+ {"version":3,"file":"router.mjs","names":[],"sources":["../../../../../../../core/src/router/router.ts"],"sourcesContent":["import proxy, { type FastifyHttpProxyOptions } from \"@fastify/http-proxy\";\nimport fastifyStatic, { type FastifyStaticOptions } from \"@fastify/static\";\nimport concatRoute from \"@mongez/concat-route\";\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 { Request } from \"../http/request\";\nimport { Response } from \"../http/response\";\nimport { type FastifyInstance } from \"../http/server\";\nimport { RouteBuilder } from \"./route-builder\";\nimport { RouteRegistry } from \"./route-registry\";\nimport type {\n GroupedRoutesOptions,\n RequestHandler,\n RequestHandlerType,\n RequestHandlerValidation,\n ResourceMethod,\n Route,\n RouteOptions,\n RouteResource,\n RouterGroupCallback,\n RouterStacks,\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\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 * Router Instance\n */\n private static instance: Router;\n\n /**\n * Static paths\n */\n protected staticDirectories: FastifyStaticOptions[] = [];\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, (_request, response) => {\n response.redirect(to, redirectMode === \"temporary\" ? 302 : 301);\n });\n }\n\n /**\n * Server static folder\n */\n public directory(options: FastifyStaticOptions) {\n this.staticDirectories.push(options);\n\n return this;\n }\n\n /**\n * Serve file\n */\n public file(path: string, location: string, cacheTime?: number) {\n return this.get(path, (_request, response) => {\n response.sendFile(location, cacheTime);\n });\n }\n\n /**\n * Serve cached file, it will cache the file to 1 year by default\n */\n public cachedFile(path: string, location: string, cacheTime?: number) {\n return this.get(path, (_request, response) => {\n response.sendCachedFile(location, cacheTime);\n });\n }\n\n /**\n * Serve list of files\n */\n public files(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, (_request, response) => {\n response.sendFile(location, cacheTime);\n });\n }\n }\n\n /**\n * Serve list of cached files, it will cache the file to 1 year by default\n */\n public cachedFiles(files: Record<string, string>, cacheTime?: number) {\n for (const [path, location] of Object.entries(files)) {\n this.get(path, (_request, response) => {\n response.sendCachedFile(location, cacheTime);\n });\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 concatRoute(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 path = concatRoute(prefix, path);\n\n const middlewarePrecedence = options.middlewarePrecedence || \"after\";\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 if (Array.isArray(handler)) {\n const [controller, action] = handler;\n\n if (typeof controller[action] !== \"function\") {\n throw new Error(\n `Invalid controller action \"${action}\" for controller \"${controller.constructor.name}\"`,\n );\n }\n\n handler = controller[action].bind(controller) as RequestHandler;\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 if (routeData.name) {\n // check if the name exists\n const route = this.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 Error(`Route name \"${routeData.name}\" already exists`);\n } else {\n routeData.name += `.${routeData.method.toLowerCase()}`;\n }\n }\n }\n\n this.routes.push(routeData);\n\n this.routesVersion++;\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 return this.prefix(path, () => {\n path = \"\";\n // get base resource name\n const baseResourceName = options.name || toCamelCase(ltrim(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 const resourceName = baseResourceName + \".list\";\n this.get(path, options.replace?.list || routeResource.list.bind(routeResource), {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.get && isAcceptableResource(\"get\")) {\n const resourceName = baseResourceName + \".single\";\n\n this.get(path + \"/:id\", options.replace?.get || routeResource.get.bind(routeResource), {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.create && isAcceptableResource(\"create\")) {\n const resourceName = baseResourceName + \".create\";\n\n const handler = options.replace?.create || this.manageValidation(routeResource, \"create\");\n\n this.post(path, handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.update && isAcceptableResource(\"update\")) {\n const resourceName = baseResourceName + \".update\";\n\n const handler = options.replace?.update || this.manageValidation(routeResource, \"update\");\n\n this.put(path + \"/:id\", handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.patch && isAcceptableResource(\"patch\")) {\n const resourceName = baseResourceName + \".patch\";\n\n const handler = options.replace?.patch || this.manageValidation(routeResource, \"patch\");\n\n this.patch(path + \"/:id\", handler, {\n ...options,\n name: resourceName,\n restful: true,\n });\n }\n\n if (routeResource.delete && isAcceptableResource(\"delete\")) {\n const resourceName = baseResourceName + \".delete\";\n\n this.delete(\n path + \"/:id\",\n options.replace?.delete || routeResource.delete.bind(routeResource),\n {\n ...options,\n name: resourceName,\n restful: true,\n },\n );\n }\n\n if (routeResource.bulkDelete && isAcceptableResource(\"delete\")) {\n const resourceName = baseResourceName + \".bulkDelete\";\n\n this.delete(\n path,\n options.replace?.bulkDelete || routeResource.bulkDelete.bind(routeResource),\n {\n ...options,\n name: resourceName,\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 } = options;\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 }\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 this.routes = this.routes.filter((route) => route.sourceFile !== sourceFile);\n\n this.routesVersion++;\n }\n\n /**\n * Manage validation system for the given resource\n */\n private manageValidation(resource: RouteResource, method: \"create\" | \"update\" | \"patch\") {\n const handler = resource[method]?.bind(resource) as RequestHandler;\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: Request, response: Response) => {\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 * 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 this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\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 config: {\n ...route.serverOptions?.config,\n ...(route.rateLimit && { rateLimit: route.rateLimit }),\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 for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\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 this.eventListeners.beforeScan?.forEach((callback) => callback(this, server));\n\n let routeRegistry: RouteRegistry | undefined;\n let registryVersion = -1;\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 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 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.code(404).send({\n error: \"Route not found\",\n path: fastifyRequest.url,\n method: fastifyRequest.method,\n });\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: fastifyRequest.url,\n });\n\n throw error;\n }\n };\n\n // Register wildcard route for all methods EXCEPT OPTIONS (to avoid conflict with CORS)\n // OPTIONS is handled by @fastify/cors plugin for preflight requests\n const methods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"] as const;\n for (const method of methods) {\n server.route({\n method,\n url: \"*\",\n handler: wildcardHandler,\n });\n }\n\n // Register static directories\n for (const directoryOptions of this.staticDirectories) {\n server.register(fastifyStatic, {\n ...directoryOptions,\n decorateReply: false,\n });\n }\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: any = {}) {\n const route = this.routes.find((route) => route.name === name);\n\n if (!route) {\n throw new Error(`Route name \"${name}\" not found`);\n }\n\n let path = route.path;\n\n if (route.path.includes(\":\")) {\n Object.keys(params).forEach((key) => {\n path = path.replace(\":\" + key, params[key]);\n });\n }\n\n return 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 request.setRequest(fastifyRequest).setRoute(route);\n\n log.info({\n module: \"route\",\n action: route.method + \" \" + route.path.replace(\"/*\", \"\"),\n message: `Starting Request: ${request.id}`,\n context: {\n request,\n response,\n },\n });\n\n const result = await request.execute();\n\n return {\n output: result,\n response,\n request,\n };\n };\n }\n}\n\nexport const router = Router.getInstance();\n\ncontainer.set(\"router\", router);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4CA,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;AAEA,IAAa,SAAb,MAAa,OAAO;;;;CA6ClB,OAAc,cAAc;EAC1B,IAAI,CAAC,OAAO,UACV,OAAO,WAAW,IAAI,OAAO;EAG/B,OAAO,OAAO;CAChB;CAEA,AAAQ,cAAc;gBAjDI,CAAC;uBAUH;2BAU8B,CAAC;wBAMrD,CAAC;gBAM8B;GAC/B,QAAQ,CAAC;GACT,MAAM,CAAC;GACP,YAAY,CAAC;EACf;CAeA;;;;CAKA,AAAO,eAAe,UAA6D;EACjF,KAAK,eAAe,aAAa,CAAC,GAAI,KAAK,eAAe,cAAc,CAAC,GAAI,QAAQ;EAErF,OAAO;CACT;;;;CAKA,AAAO,cAAc,UAA6D;EAChF,KAAK,eAAe,gBAAgB,CAAC,GAAI,KAAK,eAAe,iBAAiB,CAAC,GAAI,QAAQ;EAE3F,OAAO;CACT;;;;CAKA,AAAO,SAAS,MAAc,IAAY,eAA0C,aAAa;EAC/F,OAAO,KAAK,IAAI,OAAO,UAAU,aAAa;GAC5C,SAAS,SAAS,IAAI,iBAAiB,cAAc,MAAM,GAAG;EAChE,CAAC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tB,GACzB,OAAO,MAAM;GACX;GACA,KAAK;GACL,SAAS;EACX,CAAC;EAIH,KAAK,MAAM,oBAAoB,KAAK,mBAClC,OAAO,SAAS,eAAe;GAC7B,GAAG;GACH,eAAe;EACjB,CAAC;EAGH,KAAK,eAAe,eAAe,SAAS,aAAa,SAAS,MAAM,MAAM,CAAC;CACjF;;;;CAKA,AAAO,SAAS,MAAc,SAAc,CAAC,GAAG;EAC9C,MAAM,QAAQ,KAAK,OAAO,MAAM,UAAU,MAAM,SAAS,IAAI;EAE7D,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,eAAe,KAAK,YAAY;EAGlD,IAAI,OAAO,MAAM;EAEjB,IAAI,MAAM,KAAK,SAAS,GAAG,GACzB,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,QAAQ;GACnC,OAAO,KAAK,QAAQ,MAAM,KAAK,OAAO,IAAI;EAC5C,CAAC;EAGH,OAAO;CACT;;;;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;GAEnB,QAAQ,WAAW,cAAc,CAAC,CAAC,SAAS,KAAK;GAEjD,IAAI,KAAK;IACP,QAAQ;IACR,QAAQ,MAAM,SAAS,MAAM,MAAM,KAAK,QAAQ,MAAM,EAAE;IACxD,SAAS,qBAAqB,QAAQ;IACtC,SAAS;KACP;KACA;IACF;GACF,CAAC;GAID,OAAO;IACL,QAAQ,MAHW,QAAQ,QAAQ;IAInC;IACA;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,OAAO,YAAY;AAEzC,UAAU,IAAI,UAAU,MAAM"}
@@ -101,7 +101,30 @@ interface RouteOptions {
101
101
  */
102
102
  description?: string;
103
103
  /**
104
- * Request server options
104
+ * Fastify route options, forwarded to the route's registration.
105
+ *
106
+ * **Dev server caveat.** The dev server registers wildcard routes and
107
+ * dispatches per request, so it has no per-route registration slot. It
108
+ * forwards the pre-handler hook phases — `onRequest`, `preValidation` and
109
+ * `preHandler` — by matching in Fastify's own `onRequest` phase and running
110
+ * the matched route's hooks there, which keeps `onRequest` running before the
111
+ * body is parsed, as it does in production.
112
+ *
113
+ * **Two things are NOT forwarded in dev, and cannot be:**
114
+ * - `bodyLimit` — Fastify reads it at registration time; no hook can bound a
115
+ * body that is already being parsed.
116
+ * - `preParsing` — it must return the payload stream, so forwarding it
117
+ * generically would corrupt the body rather than guard it.
118
+ *
119
+ * A route that relies on either of those behaves differently in dev than in
120
+ * production. For a pre-parse guarantee that holds in both modes, register a
121
+ * server-level hook through `router.beforeScanning((_router, server) =>
122
+ * server.addHook("onRequest", ...))` — it lands on the Fastify instance
123
+ * rather than in per-route options. That hook fires for **every** request, so
124
+ * it must discriminate on `request.method` and `request.url` itself, and it
125
+ * must be **idempotent per request**: `beforeScanning` runs once per scan and
126
+ * restarting the HTTP connector builds a new server, so the callback can run
127
+ * more than once against different instances.
105
128
  */
106
129
  serverOptions?: RouteShorthandOptions;
107
130
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../core/src/router/types.ts"],"mappings":";;;;;;;;;;;;KASY,kBAAA,GAAqB,gBAAgB;;AAAjD;;;;KAOY,UAAA,2BAAqC,OAAA,GAAU,OAAA;EAAA,CACxD,OAAA,EAAS,iBAAA,EAAmB,QAAA,EAAU,QAAA,GAAW,kBAAA;AAAA;AAAA,KAGxC,mBAAA;AAAA,KAEA,kBAAA,GAAqB,cAAA,SAAuB,aAAa;;;;KAKzD,cAAA;AAAA,KAEA,iBAAA,GAAoB,MAAM,UAAU,UAAA;AAAA,KAEpC,wBAAA,kBAA0C,OAAA,GAAU,OAAA;EAfzC;;;EAmBrB,QAAA,GAAW,UAAA,CAAW,QAAA;EAlBrB;;;;EAuBD,UAAA;EAvBoE;AAGtE;;EAwBE,MAA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,CAAA;;;;KAKjE,oBAAA;EALkE;AAAA;AAK9E;EAIE,UAAA,GAAa,UAAU;;;;EAIvB,MAAA;EAAA;;;AAKI;EAAJ,IAAA;AAAA;;KAIU,aAAA;EAQJ;;;EAJN,IAAA,GAAO,cAAA;EAoBE;;;EAhBT,GAAA,GAAM,cAAA;EAoCK;;;EAhCX,MAAA,GAAS,cAAA;EART;;;EAYA,MAAA,GAAS,cAAA;EAJT;;;EAQA,KAAA,GAAQ,cAAA;EAAR;;;EAIA,MAAA,GAAS,cAAA;EAIT;;;EAAA,UAAA,GAAa,cAAA;EAQL;;;EAJR,UAAA;IAYW;;;IART,GAAA,GAAM,wBAAA;IAY0B;AAIpC;;IAZI,MAAA,GAAS,wBAAA;IAeW;;;IAXpB,MAAA,GAAS,wBAAA;IAWC;;;IAPV,KAAA,GAAQ,wBAAA;EAAA;AAAA;AAAA,KAIA,YAAA;EACV,MAAA;EACA,IAAA;EACA,UAAA,EAAY,UAAU;;;;EAItB,UAAA;AAAA"}
@@ -1,4 +1,4 @@
1
1
  import { StartHttpTestServerOptions, isTestServerRunning, startHttpTestServer, stopHttpTestServer } from "./start-http-development-server.mjs";
2
2
  import { expectJson, getTestServerUrl, parseJsonResponse, testDelete, testGet, testPatch, testPost, testPut, testRequest } from "./test-helpers.mjs";
3
- import { TEST_SERVER_PORT_ENV_KEY, publishTestServerPort, withdrawTestServerPort } from "./test-server-port-channel.mjs";
4
- import { setupTest } from "./vitest-setup.mjs";
3
+ import { setupTest } from "./vitest-setup.mjs";
4
+ export { StartHttpTestServerOptions, expectJson, getTestServerUrl, isTestServerRunning, parseJsonResponse, setupTest, startHttpTestServer, stopHttpTestServer, testDelete, testGet, testPatch, testPost, testPut, testRequest };
@@ -1,6 +1,5 @@
1
- import { TEST_SERVER_PORT_ENV_KEY, publishTestServerPort, withdrawTestServerPort } from "./test-server-port-channel.mjs";
2
1
  import { isTestServerRunning, startHttpTestServer, stopHttpTestServer } from "./start-http-development-server.mjs";
3
2
  import { expectJson, getTestServerUrl, parseJsonResponse, testDelete, testGet, testPatch, testPost, testPut, testRequest } from "./test-helpers.mjs";
4
3
  import { setupTest } from "./vitest-setup.mjs";
5
4
 
6
- export { };
5
+ export { expectJson, getTestServerUrl, isTestServerRunning, parseJsonResponse, setupTest, startHttpTestServer, stopHttpTestServer, testDelete, testGet, testPatch, testPost, testPut, testRequest };
@@ -1 +1 @@
1
- {"version":3,"file":"start-http-development-server.d.mts","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"mappings":";KAwBY,0BAAA;EAAA;;;;AAON;AAuDN;EAvDE,IAAI;AAAA;;;;;;AAyDI;AA8CV;;iBAhDsB,mBAAA,CACpB,OAAA,GAAS,0BAAA,GACR,OAAO;;AA8CyC;AAoBnD;;iBApBsB,kBAAA,IAAsB,OAAO;;AAoBhB;;iBAAnB,mBAAA"}
1
+ {"version":3,"file":"start-http-development-server.d.mts","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"mappings":";KAwBY,0BAAA;EAAA;;;;AAON;AA0EN;EA1EE,IAAI;AAAA;;;;;;AA4EI;AA+EV;;iBAjFsB,mBAAA,CACpB,OAAA,GAAS,0BAAA,GACR,OAAO;;AA+EyC;AA6BnD;;iBA7BsB,kBAAA,IAAsB,OAAO;;AA6BhB;;iBAAnB,mBAAA"}
@@ -41,7 +41,8 @@ async function applyTestServerPort(port) {
41
41
  }
42
42
  if (port !== void 0) config.set("http.port", port);
43
43
  const resolvedPort = config.get("http.port");
44
- if (typeof resolvedPort !== "number" || resolvedPort <= 0) return;
44
+ if (typeof resolvedPort !== "number") return;
45
+ if (resolvedPort <= 0) throw new Error(`startHttpTestServer() cannot run on port ${resolvedPort}. Pass an explicit port — e.g. startHttpTestServer({ port: 3999 }) — or set \`http.port\` in your config. Test workers are separate processes that resolve the server's URL from the port published at startup, and an OS-assigned port is not knowable to them.`);
45
46
  await assertPortIsAvailable(resolvedPort, config.get("http.host") || "localhost");
46
47
  publishTestServerPort(resolvedPort);
47
48
  }
@@ -59,18 +60,39 @@ async function startHttpTestServer(options = {}) {
59
60
  return;
60
61
  }
61
62
  console.log("[test-server] Starting HTTP test server...");
62
- Application.setRuntimeStrategy("development");
63
- Application.setEnvironment("test");
64
- await warlockConfigManager.load();
65
- await bootstrap();
66
- await filesOrchestrator.init();
67
- await filesOrchestrator.initializeAll();
68
- await loadConfigFiles(true);
69
- await connectorsManager.startPhase("early");
70
- await filesOrchestrator.moduleLoader.loadAll();
71
- await applyTestServerPort(options.port);
72
- await connectorsManager.startPhase("late");
73
- isServerRunning = true;
63
+ try {
64
+ Application.setRuntimeStrategy("development");
65
+ Application.setEnvironment("test");
66
+ await warlockConfigManager.load();
67
+ await bootstrap();
68
+ await filesOrchestrator.init();
69
+ await filesOrchestrator.initializeAll();
70
+ await loadConfigFiles(true);
71
+ await connectorsManager.startPhase("early");
72
+ await filesOrchestrator.moduleLoader.loadAll();
73
+ await applyTestServerPort(options.port);
74
+ await connectorsManager.startPhase("late");
75
+ isServerRunning = true;
76
+ } catch (error) {
77
+ await unwindPartialStartup();
78
+ throw error;
79
+ }
80
+ }
81
+ /**
82
+ * Best-effort teardown of whatever a failed {@link startHttpTestServer} managed
83
+ * to start.
84
+ *
85
+ * Every step is independent and none may throw: this runs while an error is
86
+ * already in flight, and the caller is about to rethrow it.
87
+ */
88
+ async function unwindPartialStartup() {
89
+ try {
90
+ await connectorsManager.shutdown();
91
+ } catch (shutdownError) {
92
+ console.error("[test-server] Cleanup after a failed start did not complete:", shutdownError);
93
+ }
94
+ withdrawTestServerPort();
95
+ isServerRunning = false;
74
96
  }
75
97
  /**
76
98
  * Stop the HTTP test server
@@ -83,12 +105,13 @@ async function stopHttpTestServer() {
83
105
  }
84
106
  try {
85
107
  await connectorsManager.shutdown();
86
- withdrawTestServerPort();
87
- isServerRunning = false;
88
108
  console.log("[test-server] HTTP test server stopped");
89
109
  } catch (error) {
90
110
  console.error("[test-server] Error stopping HTTP server:", error);
91
111
  throw error;
112
+ } finally {
113
+ withdrawTestServerPort();
114
+ isServerRunning = false;
92
115
  }
93
116
  }
94
117
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"start-http-development-server.mjs","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"sourcesContent":["/**\r\n * HTTP Test Server\r\n *\r\n * Starts a minimal HTTP server for testing.\r\n * Unlike the full DevelopmentServer, this:\r\n * - Does NOT watch files\r\n * - Does NOT do HMR\r\n * - Only starts connectors needed for HTTP requests\r\n *\r\n * Used in Vitest's globalSetup to start server once for all test workers.\r\n */\r\nimport config from \"@mongez/config\";\r\nimport { Application } from \"../application\";\r\nimport { bootstrap } from \"../bootstrap\";\r\nimport { loadConfigFiles } from \"../config/load-config-files\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { assertPortIsAvailable } from \"../http/port-preflight\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { publishTestServerPort, withdrawTestServerPort } from \"./test-server-port-channel\";\r\n\r\nlet isServerRunning = false;\r\n\r\nexport type StartHttpTestServerOptions = {\r\n /**\r\n * Port the test server binds to, overriding `http.port`.\r\n *\r\n * Needed because the server cannot be moved from outside: this function\r\n * bootstraps the app itself, and that bootstrap re-reads `.env`.\r\n */\r\n port?: number;\r\n};\r\n\r\n/**\r\n * Apply the caller's port and preflight the bind.\r\n *\r\n * Called at the last moment before the HTTP connector binds, and that timing is\r\n * the fix: `bootstrap()` re-reads `.env` through `loadEnv()` (dotenv overrides\r\n * by default), and `src/config/http.ts` then resolves its port from that store,\r\n * so anything the caller set earlier is gone by the time the port is read.\r\n * Writing into `config` here is also the only channel that works — assigning\r\n * `process.env.HTTP_PORT` has no effect, since `env()` reads dotenv's own store\r\n * and never falls back to `process.env`.\r\n */\r\nasync function applyTestServerPort(port?: number): Promise<void> {\r\n const httpConfig = config.get(\"http\");\r\n\r\n if (!httpConfig) {\r\n if (port !== undefined) {\r\n throw new Error(\r\n `startHttpTestServer({ port: ${port} }) was given a port, but this app has no \\`http\\` config, so no HTTP server is started. Add \\`src/config/http.ts\\` first.`,\r\n );\r\n }\r\n\r\n return;\r\n }\r\n\r\n if (port !== undefined) {\r\n config.set(\"http.port\", port);\r\n }\r\n\r\n const resolvedPort = config.get(\"http.port\");\r\n\r\n // No configured port — or an explicit `0`, which is the OS's \"pick a free one\r\n // for me\" idiom — means Fastify chooses the port, so there is nothing to\r\n // preflight and nothing to publish: preflighting 0 would bind some unrelated\r\n // ephemeral port and pass without proving anything, and publishing 0 would\r\n // point every worker request at `http://host:0`.\r\n if (typeof resolvedPort !== \"number\" || resolvedPort <= 0) {\r\n return;\r\n }\r\n\r\n await assertPortIsAvailable(resolvedPort, config.get(\"http.host\") || \"localhost\");\r\n\r\n publishTestServerPort(resolvedPort);\r\n}\r\n\r\n/**\r\n * Start the HTTP test server (minimal - no file watching)\r\n * Call this in Vitest's globalSetup\r\n *\r\n * @example\r\n * // run this suite on its own port, whatever `.env` says\r\n * await startHttpTestServer({ port: 3999 });\r\n */\r\nexport async function startHttpTestServer(\r\n options: StartHttpTestServerOptions = {},\r\n): Promise<void> {\r\n if (isServerRunning) {\r\n console.log(\"[test-server] Server already running, skipping start\");\r\n return;\r\n }\r\n\r\n console.log(\"[test-server] Starting HTTP test server...\");\r\n\r\n // Set environment\r\n Application.setRuntimeStrategy(\"development\");\r\n Application.setEnvironment(\"test\");\r\n\r\n // Bootstrap (env, etc.)\r\n await warlockConfigManager.load();\r\n await bootstrap();\r\n\r\n // Initialize file orchestrator (but don't watch)\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n\r\n // Load config files\r\n await loadConfigFiles(true);\r\n\r\n // Early-phase connectors (database, cache, logger, storage, mailer,\r\n // herald) must start BEFORE app modules load: a module's `main.ts` boot\r\n // side-effect can query the DB at import time, so the data source has to\r\n // be registered first. This mirrors the dev/prod boot order (see\r\n // `cli-commands.manager`, `production-builder`, and `DevelopmentServer`).\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\r\n\r\n // Load application modules (their boot side-effects now see a live DB).\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n\r\n await applyTestServerPort(options.port);\r\n\r\n // Late-phase connectors (http, socket) bind after app code has\r\n // registered its routes and listeners.\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\r\n\r\n isServerRunning = true;\r\n}\r\n\r\n/**\r\n * Stop the HTTP test server\r\n * Call this in Vitest's globalTeardown\r\n */\r\nexport async function stopHttpTestServer(): Promise<void> {\r\n if (!isServerRunning) {\r\n console.log(\"[test-server] No server to stop\");\r\n return;\r\n }\r\n\r\n try {\r\n await connectorsManager.shutdown();\r\n withdrawTestServerPort();\r\n isServerRunning = false;\r\n console.log(\"[test-server] HTTP test server stopped\");\r\n } catch (error) {\r\n console.error(\"[test-server] Error stopping HTTP server:\", error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Check if test server is running\r\n */\r\nexport function isTestServerRunning(): boolean {\r\n return isServerRunning;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAI,kBAAkB;;;;;;;;;;;;AAuBtB,eAAe,oBAAoB,MAA8B;CAG/D,IAAI,CAFe,OAAO,IAAI,MAEhB,GAAG;EACf,IAAI,SAAS,QACX,MAAM,IAAI,MACR,+BAA+B,KAAK,2HACtC;EAGF;CACF;CAEA,IAAI,SAAS,QACX,OAAO,IAAI,aAAa,IAAI;CAG9B,MAAM,eAAe,OAAO,IAAI,WAAW;CAO3C,IAAI,OAAO,iBAAiB,YAAY,gBAAgB,GACtD;CAGF,MAAM,sBAAsB,cAAc,OAAO,IAAI,WAAW,KAAK,WAAW;CAEhF,sBAAsB,YAAY;AACpC;;;;;;;;;AAUA,eAAsB,oBACpB,UAAsC,CAAC,GACxB;CACf,IAAI,iBAAiB;EACnB,QAAQ,IAAI,sDAAsD;EAClE;CACF;CAEA,QAAQ,IAAI,4CAA4C;CAGxD,YAAY,mBAAmB,aAAa;CAC5C,YAAY,eAAe,MAAM;CAGjC,MAAM,qBAAqB,KAAK;CAChC,MAAM,UAAU;CAGhB,MAAM,kBAAkB,KAAK;CAC7B,MAAM,kBAAkB,cAAc;CAGtC,MAAM,gBAAgB,IAAI;CAO1B,MAAM,kBAAkB,kBAAwC;CAGhE,MAAM,kBAAkB,aAAa,QAAQ;CAE7C,MAAM,oBAAoB,QAAQ,IAAI;CAItC,MAAM,kBAAkB,iBAAuC;CAE/D,kBAAkB;AACpB;;;;;AAMA,eAAsB,qBAAoC;CACxD,IAAI,CAAC,iBAAiB;EACpB,QAAQ,IAAI,iCAAiC;EAC7C;CACF;CAEA,IAAI;EACF,MAAM,kBAAkB,SAAS;EACjC,uBAAuB;EACvB,kBAAkB;EAClB,QAAQ,IAAI,wCAAwC;CACtD,SAAS,OAAO;EACd,QAAQ,MAAM,6CAA6C,KAAK;EAChE,MAAM;CACR;AACF;;;;AAKA,SAAgB,sBAA+B;CAC7C,OAAO;AACT"}
1
+ {"version":3,"file":"start-http-development-server.mjs","names":[],"sources":["../../../../../../../core/src/tests/start-http-development-server.ts"],"sourcesContent":["/**\r\n * HTTP Test Server\r\n *\r\n * Starts a minimal HTTP server for testing.\r\n * Unlike the full DevelopmentServer, this:\r\n * - Does NOT watch files\r\n * - Does NOT do HMR\r\n * - Only starts connectors needed for HTTP requests\r\n *\r\n * Used in Vitest's globalSetup to start server once for all test workers.\r\n */\r\nimport config from \"@mongez/config\";\r\nimport { Application } from \"../application\";\r\nimport { bootstrap } from \"../bootstrap\";\r\nimport { loadConfigFiles } from \"../config/load-config-files\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\r\nimport { assertPortIsAvailable } from \"../http/port-preflight\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { publishTestServerPort, withdrawTestServerPort } from \"./test-server-port-channel\";\r\n\r\nlet isServerRunning = false;\r\n\r\nexport type StartHttpTestServerOptions = {\r\n /**\r\n * Port the test server binds to, overriding `http.port`.\r\n *\r\n * Needed because the server cannot be moved from outside: this function\r\n * bootstraps the app itself, and that bootstrap re-reads `.env`.\r\n */\r\n port?: number;\r\n};\r\n\r\n/**\r\n * Apply the caller's port and preflight the bind.\r\n *\r\n * Called at the last moment before the HTTP connector binds, and that timing is\r\n * the fix: `bootstrap()` re-reads `.env` through `loadEnv()` (dotenv overrides\r\n * by default), and `src/config/http.ts` then resolves its port from that store,\r\n * so anything the caller set earlier is gone by the time the port is read.\r\n * Writing into `config` here is also the only channel that works — assigning\r\n * `process.env.HTTP_PORT` has no effect, since `env()` reads dotenv's own store\r\n * and never falls back to `process.env`.\r\n */\r\nasync function applyTestServerPort(port?: number): Promise<void> {\r\n const httpConfig = config.get(\"http\");\r\n\r\n if (!httpConfig) {\r\n if (port !== undefined) {\r\n throw new Error(\r\n `startHttpTestServer({ port: ${port} }) was given a port, but this app has no \\`http\\` config, so no HTTP server is started. Add \\`src/config/http.ts\\` first.`,\r\n );\r\n }\r\n\r\n return;\r\n }\r\n\r\n if (port !== undefined) {\r\n config.set(\"http.port\", port);\r\n }\r\n\r\n const resolvedPort = config.get(\"http.port\");\r\n\r\n // No configured port at all is fine: Fastify falls back to its own default and\r\n // the workers resolve the same one from their own config, so both ends agree\r\n // without the channel.\r\n //\r\n // ⚠ A non-numeric port also lands here, and that is NOT fine — it is just not\r\n // this function's bug to fix. `env()` coerces a value only when it round-trips\r\n // exactly (`String(Number(v)) === v`), so `HTTP_PORT=3999` and `HTTP_PORT=0`\r\n // arrive as numbers, but `03999`, `+3999`, `1e3` and anything with stray\r\n // whitespace stay strings. Those skip the preflight and the publish here, and\r\n // reach `HttpConnector.start()`'s `listen({ port })` unchanged — a production\r\n // path, not a test one. Tracked separately rather than widened into this fix.\r\n if (typeof resolvedPort !== \"number\") {\r\n return;\r\n }\r\n\r\n // `0` is the OS's \"pick a free one for me\" idiom, and the test server cannot\r\n // support it. Preflighting 0 would bind some unrelated ephemeral port and pass\r\n // without proving anything, and there is nothing meaningful to publish: the\r\n // port Fastify ends up binding is never recorded — `HttpConnector.start()`\r\n // stores the port it ASKED for, not the one it got. Accepting 0 silently is\r\n // what left `getTestServerUrl()` resolving to `http://host:0` through its own\r\n // config fallback, so every worker request went to a port nothing listens on.\r\n if (resolvedPort <= 0) {\r\n throw new Error(\r\n `startHttpTestServer() cannot run on port ${resolvedPort}. Pass an explicit port — e.g. startHttpTestServer({ port: 3999 }) — or set \\`http.port\\` in your config. Test workers are separate processes that resolve the server's URL from the port published at startup, and an OS-assigned port is not knowable to them.`,\r\n );\r\n }\r\n\r\n await assertPortIsAvailable(resolvedPort, config.get(\"http.host\") || \"localhost\");\r\n\r\n publishTestServerPort(resolvedPort);\r\n}\r\n\r\n/**\r\n * Start the HTTP test server (minimal - no file watching)\r\n * Call this in Vitest's globalSetup\r\n *\r\n * @example\r\n * // run this suite on its own port, whatever `.env` says\r\n * await startHttpTestServer({ port: 3999 });\r\n */\r\nexport async function startHttpTestServer(\r\n options: StartHttpTestServerOptions = {},\r\n): Promise<void> {\r\n if (isServerRunning) {\r\n console.log(\"[test-server] Server already running, skipping start\");\r\n return;\r\n }\r\n\r\n console.log(\"[test-server] Starting HTTP test server...\");\r\n\r\n try {\r\n // Set environment\r\n Application.setRuntimeStrategy(\"development\");\r\n Application.setEnvironment(\"test\");\r\n\r\n // Bootstrap (env, etc.)\r\n await warlockConfigManager.load();\r\n await bootstrap();\r\n\r\n // Initialize file orchestrator (but don't watch)\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n\r\n // Load config files\r\n await loadConfigFiles(true);\r\n\r\n // Early-phase connectors (database, cache, logger, storage, mailer,\r\n // herald) must start BEFORE app modules load: a module's `main.ts` boot\r\n // side-effect can query the DB at import time, so the data source has to\r\n // be registered first. This mirrors the dev/prod boot order (see\r\n // `cli-commands.manager`, `production-builder`, and `DevelopmentServer`).\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\r\n\r\n // Load application modules (their boot side-effects now see a live DB).\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n\r\n await applyTestServerPort(options.port);\r\n\r\n // Late-phase connectors (http, socket) bind after app code has\r\n // registered its routes and listeners.\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\r\n\r\n isServerRunning = true;\r\n } catch (error) {\r\n // This function owns the connectors it starts, so a failure part-way\r\n // through has to leave nothing behind. Without this, `isServerRunning` was\r\n // still `false` — it is only set on the last line — so `globalTeardown`'s\r\n // `stopHttpTestServer()` reported \"No server to stop\" and walked away from\r\n // live early-phase connectors and a published port that outlived them.\r\n await unwindPartialStartup();\r\n\r\n // Rethrown unchanged: the startup failure is the one the caller needs to\r\n // read. A cleanup failure that replaced it would hide the actual cause.\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Best-effort teardown of whatever a failed {@link startHttpTestServer} managed\r\n * to start.\r\n *\r\n * Every step is independent and none may throw: this runs while an error is\r\n * already in flight, and the caller is about to rethrow it.\r\n */\r\nasync function unwindPartialStartup(): Promise<void> {\r\n try {\r\n await connectorsManager.shutdown();\r\n } catch (shutdownError) {\r\n // Reported, not thrown — it is secondary to the startup error being\r\n // rethrown, and losing that one to this would be the worse outcome.\r\n console.error(\"[test-server] Cleanup after a failed start did not complete:\", shutdownError);\r\n }\r\n\r\n withdrawTestServerPort();\r\n isServerRunning = false;\r\n}\r\n\r\n/**\r\n * Stop the HTTP test server\r\n * Call this in Vitest's globalTeardown\r\n */\r\nexport async function stopHttpTestServer(): Promise<void> {\r\n if (!isServerRunning) {\r\n console.log(\"[test-server] No server to stop\");\r\n return;\r\n }\r\n\r\n try {\r\n await connectorsManager.shutdown();\r\n\r\n console.log(\"[test-server] HTTP test server stopped\");\r\n } catch (error) {\r\n // Surfaced, never swallowed — cleaning up is not the same as the shutdown\r\n // having succeeded, and a suite whose teardown failed should say so.\r\n console.error(\"[test-server] Error stopping HTTP server:\", error);\r\n\r\n throw error;\r\n } finally {\r\n // In a `finally` rather than after the `await`: when `shutdown()` threw,\r\n // the published port survived the server it pointed at, so the next run in\r\n // the same process inherited a stale one and sent every request to it.\r\n withdrawTestServerPort();\r\n\r\n isServerRunning = false;\r\n }\r\n}\r\n\r\n/**\r\n * Check if test server is running\r\n */\r\nexport function isTestServerRunning(): boolean {\r\n return isServerRunning;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAI,kBAAkB;;;;;;;;;;;;AAuBtB,eAAe,oBAAoB,MAA8B;CAG/D,IAAI,CAFe,OAAO,IAAI,MAEhB,GAAG;EACf,IAAI,SAAS,QACX,MAAM,IAAI,MACR,+BAA+B,KAAK,2HACtC;EAGF;CACF;CAEA,IAAI,SAAS,QACX,OAAO,IAAI,aAAa,IAAI;CAG9B,MAAM,eAAe,OAAO,IAAI,WAAW;CAa3C,IAAI,OAAO,iBAAiB,UAC1B;CAUF,IAAI,gBAAgB,GAClB,MAAM,IAAI,MACR,4CAA4C,aAAa,iQAC3D;CAGF,MAAM,sBAAsB,cAAc,OAAO,IAAI,WAAW,KAAK,WAAW;CAEhF,sBAAsB,YAAY;AACpC;;;;;;;;;AAUA,eAAsB,oBACpB,UAAsC,CAAC,GACxB;CACf,IAAI,iBAAiB;EACnB,QAAQ,IAAI,sDAAsD;EAClE;CACF;CAEA,QAAQ,IAAI,4CAA4C;CAExD,IAAI;EAEF,YAAY,mBAAmB,aAAa;EAC5C,YAAY,eAAe,MAAM;EAGjC,MAAM,qBAAqB,KAAK;EAChC,MAAM,UAAU;EAGhB,MAAM,kBAAkB,KAAK;EAC7B,MAAM,kBAAkB,cAAc;EAGtC,MAAM,gBAAgB,IAAI;EAO1B,MAAM,kBAAkB,kBAAwC;EAGhE,MAAM,kBAAkB,aAAa,QAAQ;EAE7C,MAAM,oBAAoB,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OAAA,CAAQ,QAAA;;AAhD6E;AAOxF;iBAoDsB,iBAAA,IAAqB,QAAA,EAAU,QAAA,GAAW,OAAA,CAAQ,CAAA;;;;iBAOlD,UAAA,IAAc,QAAA,EAAU,QAAA,EAAU,cAAA,YAAuB,OAAA,CAAQ,CAAA"}
1
+ {"version":3,"file":"test-helpers.d.mts","names":[],"sources":["../../../../../../../core/src/tests/test-helpers.ts"],"mappings":";;AAYA;;;;AAAgC;AAehC;;AAfgC,iBAAhB,gBAAA;;;;;iBAeM,WAAA,CAAY,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;;iBAgD9D,OAAA,CAAQ,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;AAhDY;iBAuDtE,QAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;;;iBAOW,OAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;;;iBAOW,UAAA,CAAW,IAAA,UAAc,OAAA,GAAS,WAAA,GAAmB,OAAA,CAAQ,QAAA;;;;iBAO7D,SAAA,CACpB,IAAA,UACA,IAAA,YACA,OAAA,GAAS,WAAA,GACR,OAAA,CAAQ,QAAA;;AAxC6E;AAOxF;iBAwCsB,iBAAA,IAAqB,QAAA,EAAU,QAAA,GAAW,OAAA,CAAQ,CAAA;;;;iBAOlD,UAAA,IAAc,QAAA,EAAU,QAAA,EAAU,cAAA,YAAuB,OAAA,CAAQ,CAAA"}
@@ -20,17 +20,38 @@ function getTestServerUrl() {
20
20
  * Uses native fetch - lightweight, no extra dependencies
21
21
  */
22
22
  async function testRequest(path, options = {}) {
23
+ return sendRequest(path, options, false);
24
+ }
25
+ /**
26
+ * The single place a request is actually built.
27
+ *
28
+ * `serializedJson` says whether THIS module turned the caller's value into a
29
+ * JSON string. It is the only thing that justifies setting a JSON content type:
30
+ * a `FormData` body carries a multipart boundary the runtime generates, and
31
+ * labelling it `application/json` produces a request no server can parse.
32
+ */
33
+ async function sendRequest(path, options, serializedJson) {
23
34
  const baseUrl = getTestServerUrl();
24
35
  const url = path.startsWith("/") ? `${baseUrl}${path}` : `${baseUrl}/${path}`;
36
+ const headers = new Headers(options.headers);
37
+ if (serializedJson && !headers.has("content-type")) headers.set("content-type", "application/json");
25
38
  return fetch(url, {
26
39
  ...options,
27
- headers: {
28
- "Content-Type": "application/json",
29
- ...options.headers
30
- }
40
+ headers
31
41
  });
32
42
  }
33
43
  /**
44
+ * Serialize a body for a JSON request.
45
+ *
46
+ * `undefined` means the caller omitted the argument; every other value —
47
+ * including `false`, `0`, `""` and `null` — is a legal JSON document and must
48
+ * be sent. The old check was `body ? JSON.stringify(body) : undefined`, which
49
+ * dropped all four.
50
+ */
51
+ function jsonBody(body) {
52
+ return body === void 0 ? void 0 : JSON.stringify(body);
53
+ }
54
+ /**
34
55
  * GET request helper
35
56
  */
36
57
  async function testGet(path, options = {}) {
@@ -43,21 +64,21 @@ async function testGet(path, options = {}) {
43
64
  * POST request helper
44
65
  */
45
66
  async function testPost(path, body, options = {}) {
46
- return testRequest(path, {
67
+ return sendRequest(path, {
47
68
  ...options,
48
69
  method: "POST",
49
- body: body ? JSON.stringify(body) : void 0
50
- });
70
+ body: jsonBody(body)
71
+ }, body !== void 0);
51
72
  }
52
73
  /**
53
74
  * PUT request helper
54
75
  */
55
76
  async function testPut(path, body, options = {}) {
56
- return testRequest(path, {
77
+ return sendRequest(path, {
57
78
  ...options,
58
79
  method: "PUT",
59
- body: body ? JSON.stringify(body) : void 0
60
- });
80
+ body: jsonBody(body)
81
+ }, body !== void 0);
61
82
  }
62
83
  /**
63
84
  * DELETE request helper
@@ -72,11 +93,11 @@ async function testDelete(path, options = {}) {
72
93
  * PATCH request helper
73
94
  */
74
95
  async function testPatch(path, body, options = {}) {
75
- return testRequest(path, {
96
+ return sendRequest(path, {
76
97
  ...options,
77
98
  method: "PATCH",
78
- body: body ? JSON.stringify(body) : void 0
79
- });
99
+ body: jsonBody(body)
100
+ }, body !== void 0);
80
101
  }
81
102
  /**
82
103
  * Parse JSON response with type safety
@@ -1 +1 @@
1
- {"version":3,"file":"test-helpers.mjs","names":[],"sources":["../../../../../../../core/src/tests/test-helpers.ts"],"sourcesContent":["/**\n * Warlock.js Test Helpers\n *\n * Utilities for testing Warlock.js applications.\n */\n\nimport { config } from \"../config\";\nimport { TEST_SERVER_PORT_ENV_KEY } from \"./test-server-port-channel\";\n\n/**\n * Get the test server base URL\n */\nexport function getTestServerUrl(): string {\n // `startHttpTestServer` publishes the port it actually bound. Test workers are\n // separate processes whose own config resolves `http.port` from `.env`, so\n // without this a suite started on an explicit port would send every request to\n // the `.env` port instead of the one the server is listening on.\n const publishedPort = process.env[TEST_SERVER_PORT_ENV_KEY];\n const port = publishedPort || config.key(\"http.port\", 2031);\n const host = config.key(\"http.host\", \"localhost\");\n return `http://${host}:${port}`;\n}\n\n/**\n * Simple HTTP request helper for test server\n * Uses native fetch - lightweight, no extra dependencies\n */\nexport async function testRequest(path: string, options: RequestInit = {}): Promise<Response> {\n const baseUrl = getTestServerUrl();\n const url = path.startsWith(\"/\") ? `${baseUrl}${path}` : `${baseUrl}/${path}`;\n\n return fetch(url, {\n ...options,\n headers: {\n \"Content-Type\": \"application/json\",\n ...options.headers,\n },\n });\n}\n\n/**\n * GET request helper\n */\nexport async function testGet(path: string, options: RequestInit = {}): Promise<Response> {\n return testRequest(path, { ...options, method: \"GET\" });\n}\n\n/**\n * POST request helper\n */\nexport async function testPost(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n): Promise<Response> {\n return testRequest(path, {\n ...options,\n method: \"POST\",\n body: body ? JSON.stringify(body) : undefined,\n });\n}\n\n/**\n * PUT request helper\n */\nexport async function testPut(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n): Promise<Response> {\n return testRequest(path, {\n ...options,\n method: \"PUT\",\n body: body ? JSON.stringify(body) : undefined,\n });\n}\n\n/**\n * DELETE request helper\n */\nexport async function testDelete(path: string, options: RequestInit = {}): Promise<Response> {\n return testRequest(path, { ...options, method: \"DELETE\" });\n}\n\n/**\n * PATCH request helper\n */\nexport async function testPatch(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n): Promise<Response> {\n return testRequest(path, {\n ...options,\n method: \"PATCH\",\n body: body ? JSON.stringify(body) : undefined,\n });\n}\n\n/**\n * Parse JSON response with type safety\n */\nexport async function parseJsonResponse<T>(response: Response): Promise<T> {\n return response.json() as Promise<T>;\n}\n\n/**\n * Assert response status and return parsed JSON\n */\nexport async function expectJson<T>(response: Response, expectedStatus = 200): Promise<T> {\n if (response.status !== expectedStatus) {\n const text = await response.text();\n throw new Error(`Expected status ${expectedStatus}, got ${response.status}. Body: ${text}`);\n }\n return parseJsonResponse<T>(response);\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,mBAA2B;CAMzC,MAAM,OADgB,QAAQ,mCACA,OAAO,IAAI,aAAa,IAAI;CAE1D,OAAO,UADM,OAAO,IAAI,aAAa,WACjB,EAAE,GAAG;AAC3B;;;;;AAMA,eAAsB,YAAY,MAAc,UAAuB,CAAC,GAAsB;CAC5F,MAAM,UAAU,iBAAiB;CACjC,MAAM,MAAM,KAAK,WAAW,GAAG,IAAI,GAAG,UAAU,SAAS,GAAG,QAAQ,GAAG;CAEvE,OAAO,MAAM,KAAK;EAChB,GAAG;EACH,SAAS;GACP,gBAAgB;GAChB,GAAG,QAAQ;EACb;CACF,CAAC;AACH;;;;AAKA,eAAsB,QAAQ,MAAc,UAAuB,CAAC,GAAsB;CACxF,OAAO,YAAY,MAAM;EAAE,GAAG;EAAS,QAAQ;CAAM,CAAC;AACxD;;;;AAKA,eAAsB,SACpB,MACA,MACA,UAAuB,CAAC,GACL;CACnB,OAAO,YAAY,MAAM;EACvB,GAAG;EACH,QAAQ;EACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;CACtC,CAAC;AACH;;;;AAKA,eAAsB,QACpB,MACA,MACA,UAAuB,CAAC,GACL;CACnB,OAAO,YAAY,MAAM;EACvB,GAAG;EACH,QAAQ;EACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;CACtC,CAAC;AACH;;;;AAKA,eAAsB,WAAW,MAAc,UAAuB,CAAC,GAAsB;CAC3F,OAAO,YAAY,MAAM;EAAE,GAAG;EAAS,QAAQ;CAAS,CAAC;AAC3D;;;;AAKA,eAAsB,UACpB,MACA,MACA,UAAuB,CAAC,GACL;CACnB,OAAO,YAAY,MAAM;EACvB,GAAG;EACH,QAAQ;EACR,MAAM,OAAO,KAAK,UAAU,IAAI,IAAI;CACtC,CAAC;AACH;;;;AAKA,eAAsB,kBAAqB,UAAgC;CACzE,OAAO,SAAS,KAAK;AACvB;;;;AAKA,eAAsB,WAAc,UAAoB,iBAAiB,KAAiB;CACxF,IAAI,SAAS,WAAW,gBAAgB;EACtC,MAAM,OAAO,MAAM,SAAS,KAAK;EACjC,MAAM,IAAI,MAAM,mBAAmB,eAAe,QAAQ,SAAS,OAAO,UAAU,MAAM;CAC5F;CACA,OAAO,kBAAqB,QAAQ;AACtC"}
1
+ {"version":3,"file":"test-helpers.mjs","names":[],"sources":["../../../../../../../core/src/tests/test-helpers.ts"],"sourcesContent":["/**\n * Warlock.js Test Helpers\n *\n * Utilities for testing Warlock.js applications.\n */\n\nimport { config } from \"../config\";\nimport { TEST_SERVER_PORT_ENV_KEY } from \"./test-server-port-channel\";\n\n/**\n * Get the test server base URL\n */\nexport function getTestServerUrl(): string {\n // `startHttpTestServer` publishes the port it actually bound. Test workers are\n // separate processes whose own config resolves `http.port` from `.env`, so\n // without this a suite started on an explicit port would send every request to\n // the `.env` port instead of the one the server is listening on.\n const publishedPort = process.env[TEST_SERVER_PORT_ENV_KEY];\n const port = publishedPort || config.key(\"http.port\", 2031);\n const host = config.key(\"http.host\", \"localhost\");\n return `http://${host}:${port}`;\n}\n\n/**\n * Simple HTTP request helper for test server\n * Uses native fetch - lightweight, no extra dependencies\n */\nexport async function testRequest(path: string, options: RequestInit = {}): Promise<Response> {\n return sendRequest(path, options, false);\n}\n\n/**\n * The single place a request is actually built.\n *\n * `serializedJson` says whether THIS module turned the caller's value into a\n * JSON string. It is the only thing that justifies setting a JSON content type:\n * a `FormData` body carries a multipart boundary the runtime generates, and\n * labelling it `application/json` produces a request no server can parse.\n */\nasync function sendRequest(\n path: string,\n options: RequestInit,\n serializedJson: boolean,\n): Promise<Response> {\n const baseUrl = getTestServerUrl();\n const url = path.startsWith(\"/\") ? `${baseUrl}${path}` : `${baseUrl}/${path}`;\n\n // Normalised through `Headers` rather than object-spread: `RequestInit.headers`\n // may be a record, a `Headers` instance, or a list of `[name, value]` tuples,\n // and spreading the last two silently produces an object with numeric keys —\n // the header is simply lost, with no error anywhere.\n const headers = new Headers(options.headers);\n\n if (serializedJson && !headers.has(\"content-type\")) {\n headers.set(\"content-type\", \"application/json\");\n }\n\n return fetch(url, { ...options, headers });\n}\n\n/**\n * Serialize a body for a JSON request.\n *\n * `undefined` means the caller omitted the argument; every other value —\n * including `false`, `0`, `\"\"` and `null` — is a legal JSON document and must\n * be sent. The old check was `body ? JSON.stringify(body) : undefined`, which\n * dropped all four.\n */\nfunction jsonBody(body: unknown): string | undefined {\n return body === undefined ? undefined : JSON.stringify(body);\n}\n\n/**\n * GET request helper\n */\nexport async function testGet(path: string, options: RequestInit = {}): Promise<Response> {\n return testRequest(path, { ...options, method: \"GET\" });\n}\n\n/**\n * POST request helper\n */\nexport async function testPost(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n): Promise<Response> {\n return sendRequest(path, { ...options, method: \"POST\", body: jsonBody(body) }, body !== undefined);\n}\n\n/**\n * PUT request helper\n */\nexport async function testPut(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n): Promise<Response> {\n return sendRequest(path, { ...options, method: \"PUT\", body: jsonBody(body) }, body !== undefined);\n}\n\n/**\n * DELETE request helper\n */\nexport async function testDelete(path: string, options: RequestInit = {}): Promise<Response> {\n return testRequest(path, { ...options, method: \"DELETE\" });\n}\n\n/**\n * PATCH request helper\n */\nexport async function testPatch(\n path: string,\n body?: unknown,\n options: RequestInit = {},\n): Promise<Response> {\n return sendRequest(path, { ...options, method: \"PATCH\", body: jsonBody(body) }, body !== undefined);\n}\n\n/**\n * Parse JSON response with type safety\n */\nexport async function parseJsonResponse<T>(response: Response): Promise<T> {\n return response.json() as Promise<T>;\n}\n\n/**\n * Assert response status and return parsed JSON\n */\nexport async function expectJson<T>(response: Response, expectedStatus = 200): Promise<T> {\n if (response.status !== expectedStatus) {\n const text = await response.text();\n throw new Error(`Expected status ${expectedStatus}, got ${response.status}. Body: ${text}`);\n }\n return parseJsonResponse<T>(response);\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,mBAA2B;CAMzC,MAAM,OADgB,QAAQ,mCACA,OAAO,IAAI,aAAa,IAAI;CAE1D,OAAO,UADM,OAAO,IAAI,aAAa,WACjB,EAAE,GAAG;AAC3B;;;;;AAMA,eAAsB,YAAY,MAAc,UAAuB,CAAC,GAAsB;CAC5F,OAAO,YAAY,MAAM,SAAS,KAAK;AACzC;;;;;;;;;AAUA,eAAe,YACb,MACA,SACA,gBACmB;CACnB,MAAM,UAAU,iBAAiB;CACjC,MAAM,MAAM,KAAK,WAAW,GAAG,IAAI,GAAG,UAAU,SAAS,GAAG,QAAQ,GAAG;CAMvE,MAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;CAE3C,IAAI,kBAAkB,CAAC,QAAQ,IAAI,cAAc,GAC/C,QAAQ,IAAI,gBAAgB,kBAAkB;CAGhD,OAAO,MAAM,KAAK;EAAE,GAAG;EAAS;CAAQ,CAAC;AAC3C;;;;;;;;;AAUA,SAAS,SAAS,MAAmC;CACnD,OAAO,SAAS,SAAY,SAAY,KAAK,UAAU,IAAI;AAC7D;;;;AAKA,eAAsB,QAAQ,MAAc,UAAuB,CAAC,GAAsB;CACxF,OAAO,YAAY,MAAM;EAAE,GAAG;EAAS,QAAQ;CAAM,CAAC;AACxD;;;;AAKA,eAAsB,SACpB,MACA,MACA,UAAuB,CAAC,GACL;CACnB,OAAO,YAAY,MAAM;EAAE,GAAG;EAAS,QAAQ;EAAQ,MAAM,SAAS,IAAI;CAAE,GAAG,SAAS,MAAS;AACnG;;;;AAKA,eAAsB,QACpB,MACA,MACA,UAAuB,CAAC,GACL;CACnB,OAAO,YAAY,MAAM;EAAE,GAAG;EAAS,QAAQ;EAAO,MAAM,SAAS,IAAI;CAAE,GAAG,SAAS,MAAS;AAClG;;;;AAKA,eAAsB,WAAW,MAAc,UAAuB,CAAC,GAAsB;CAC3F,OAAO,YAAY,MAAM;EAAE,GAAG;EAAS,QAAQ;CAAS,CAAC;AAC3D;;;;AAKA,eAAsB,UACpB,MACA,MACA,UAAuB,CAAC,GACL;CACnB,OAAO,YAAY,MAAM;EAAE,GAAG;EAAS,QAAQ;EAAS,MAAM,SAAS,IAAI;CAAE,GAAG,SAAS,MAAS;AACpG;;;;AAKA,eAAsB,kBAAqB,UAAgC;CACzE,OAAO,SAAS,KAAK;AACvB;;;;AAKA,eAAsB,WAAc,UAAoB,iBAAiB,KAAiB;CACxF,IAAI,SAAS,WAAW,gBAAgB;EACtC,MAAM,OAAO,MAAM,SAAS,KAAK;EACjC,MAAM,IAAI,MAAM,mBAAmB,eAAe,QAAQ,SAAS,OAAO,UAAU,MAAM;CAC5F;CACA,OAAO,kBAAqB,QAAQ;AACtC"}
@@ -8,7 +8,7 @@ type TestSetup = {
8
8
  */
9
9
  declare function setupTest({
10
10
  connectors
11
- }: TestSetup): Promise<void>;
11
+ }?: TestSetup): Promise<void>;
12
12
  //#endregion
13
13
  export { setupTest };
14
14
  //# sourceMappingURL=vitest-setup.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"vitest-setup.d.mts","names":[],"sources":["../../../../../../../core/src/tests/vitest-setup.ts"],"mappings":";;KAmBK,SAAA;EACH,UAAA,aAAuB,aAAa;AAAA;AAR2B;;;AAAA,iBAc3C,SAAA;EAAY;AAAA,GAAqB,SAAA,GAAS,OAAA"}
1
+ {"version":3,"file":"vitest-setup.d.mts","names":[],"sources":["../../../../../../../core/src/tests/vitest-setup.ts"],"mappings":";;KAmBK,SAAA;EACH,UAAA,aAAuB,aAAa;AAAA;AAR2B;;;AAAA,iBAc3C,SAAA;EAAY;AAAA,IAAqB,SAAA,GAAc,OAAA"}
@@ -13,7 +13,7 @@ let isSetupComplete = false;
13
13
  /**
14
14
  * Setup function that runs once per worker thread
15
15
  */
16
- async function setupTest({ connectors = true }) {
16
+ async function setupTest({ connectors = true } = {}) {
17
17
  if (isSetupComplete) return;
18
18
  try {
19
19
  Application.setEnvironment("test");
@@ -21,8 +21,8 @@ async function setupTest({ connectors = true }) {
21
21
  await bootstrap();
22
22
  await filesOrchestrator.init();
23
23
  await loadConfigFiles(true);
24
- const connectorsToStart = config.get("tests").connectors || connectors;
25
- if (Array.isArray(connectorsToStart)) await connectorsManager.start(connectorsToStart);
24
+ const connectorsToStart = config.get("tests", {})?.connectors ?? connectors;
25
+ if (connectorsToStart !== false) if (Array.isArray(connectorsToStart)) await connectorsManager.start(connectorsToStart);
26
26
  else await connectorsManager.startWithout(["http"]);
27
27
  isSetupComplete = true;
28
28
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"vitest-setup.mjs","names":[],"sources":["../../../../../../../core/src/tests/vitest-setup.ts"],"sourcesContent":["/**\n * Vitest Setup File\n *\n * This file runs in each Vitest worker thread before tests execute.\n * It bootstraps the framework and starts necessary connectors so tests\n * have access to database connections and other shared resources.\n */\nimport { GenericObject } from \"@mongez/reinforcements\";\nimport { Application } from \"../application/application\";\nimport { bootstrap } from \"../bootstrap\";\nimport { config } from \"../config\";\nimport { loadConfigFiles } from \"../config/load-config-files\";\nimport { ConnectorName, connectorsManager } from \"../connectors\";\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n// Global flag to prevent duplicate setup within the same worker\nlet isSetupComplete = false;\n\ntype TestSetup = {\n connectors?: boolean | ConnectorName[];\n};\n\n/**\n * Setup function that runs once per worker thread\n */\nexport async function setupTest({ connectors = true }: TestSetup) {\n // Skip if already set up in this worker\n if (isSetupComplete) {\n return;\n }\n\n try {\n // 1. Set environment to test\n Application.setEnvironment(\"test\");\n\n await warlockConfigManager.load();\n await bootstrap();\n\n await filesOrchestrator.init();\n await loadConfigFiles(true);\n\n // 2. Load test configuration\n const testConfig = config.get<GenericObject>(\"tests\");\n\n // 3. Start connectors (database, cache, etc.)\n const connectorsToStart = testConfig.connectors || connectors;\n\n // force not starting http since it will be used globally over all\n // tests files\n if (Array.isArray(connectorsToStart)) {\n await connectorsManager.start(connectorsToStart);\n } else {\n await connectorsManager.startWithout([\"http\"]);\n }\n\n isSetupComplete = true;\n } catch (error) {\n console.error(\"[vitest-setup] Failed to setup test environment:\", error);\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;AAiBA,IAAI,kBAAkB;;;;AAStB,eAAsB,UAAU,EAAE,aAAa,QAAmB;CAEhE,IAAI,iBACF;CAGF,IAAI;EAEF,YAAY,eAAe,MAAM;EAEjC,MAAM,qBAAqB,KAAK;EAChC,MAAM,UAAU;EAEhB,MAAM,kBAAkB,KAAK;EAC7B,MAAM,gBAAgB,IAAI;EAM1B,MAAM,oBAHa,OAAO,IAAmB,OAGV,CAAC,CAAC,cAAc;EAInD,IAAI,MAAM,QAAQ,iBAAiB,GACjC,MAAM,kBAAkB,MAAM,iBAAiB;OAE/C,MAAM,kBAAkB,aAAa,CAAC,MAAM,CAAC;EAG/C,kBAAkB;CACpB,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;EACvE,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"vitest-setup.mjs","names":[],"sources":["../../../../../../../core/src/tests/vitest-setup.ts"],"sourcesContent":["/**\n * Vitest Setup File\n *\n * This file runs in each Vitest worker thread before tests execute.\n * It bootstraps the framework and starts necessary connectors so tests\n * have access to database connections and other shared resources.\n */\nimport { GenericObject } from \"@mongez/reinforcements\";\nimport { Application } from \"../application/application\";\nimport { bootstrap } from \"../bootstrap\";\nimport { config } from \"../config\";\nimport { loadConfigFiles } from \"../config/load-config-files\";\nimport { ConnectorName, connectorsManager } from \"../connectors\";\nimport { filesOrchestrator } from \"../dev-server/files-orchestrator\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n// Global flag to prevent duplicate setup within the same worker\nlet isSetupComplete = false;\n\ntype TestSetup = {\n connectors?: boolean | ConnectorName[];\n};\n\n/**\n * Setup function that runs once per worker thread\n */\nexport async function setupTest({ connectors = true }: TestSetup = {}) {\n // Skip if already set up in this worker\n if (isSetupComplete) {\n return;\n }\n\n try {\n // 1. Set environment to test\n Application.setEnvironment(\"test\");\n\n await warlockConfigManager.load();\n await bootstrap();\n\n await filesOrchestrator.init();\n await loadConfigFiles(true);\n\n // 2. Load test configuration.\n //\n // The default matters: `config.get` resolves an absent key to its default,\n // and ITS default is `null` — not `{}`. `warlock add test` does not generate\n // `src/config/tests.ts`, so reading `.connectors` off the result threw\n // \"Cannot read properties of null\" on the generated default path.\n const testConfig = config.get<GenericObject>(\"tests\", {});\n\n // 3. Choose the connectors.\n //\n // `??`, not `||`: `false` is a meaningful configured value (\"start none\")\n // and `||` discarded it, falling through to the branch that starts\n // everything. The type and the skill both document `false` as \"start none\",\n // so the old behaviour was the exact opposite of the promise.\n const connectorsToStart = testConfig?.connectors ?? connectors;\n\n // `false` means none at all. Everything else starts something: an array\n // starts exactly those, and `true` starts all but http — http is the global\n // setup's job, shared across every worker.\n if (connectorsToStart !== false) {\n if (Array.isArray(connectorsToStart)) {\n await connectorsManager.start(connectorsToStart);\n } else {\n await connectorsManager.startWithout([\"http\"]);\n }\n }\n\n // Set even when no connectors were started: setup DID complete, and a second\n // call in the same worker must stay a no-op either way.\n isSetupComplete = true;\n } catch (error) {\n console.error(\"[vitest-setup] Failed to setup test environment:\", error);\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;AAiBA,IAAI,kBAAkB;;;;AAStB,eAAsB,UAAU,EAAE,aAAa,SAAoB,CAAC,GAAG;CAErE,IAAI,iBACF;CAGF,IAAI;EAEF,YAAY,eAAe,MAAM;EAEjC,MAAM,qBAAqB,KAAK;EAChC,MAAM,UAAU;EAEhB,MAAM,kBAAkB,KAAK;EAC7B,MAAM,gBAAgB,IAAI;EAgB1B,MAAM,oBARa,OAAO,IAAmB,SAAS,CAAC,CAQpB,CAAC,EAAE,cAAc;EAKpD,IAAI,sBAAsB,OACxB,IAAI,MAAM,QAAQ,iBAAiB,GACjC,MAAM,kBAAkB,MAAM,iBAAiB;OAE/C,MAAM,kBAAkB,aAAa,CAAC,MAAM,CAAC;EAMjD,kBAAkB;CACpB,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;EACvE,MAAM;CACR;AACF"}
@@ -1,5 +1,5 @@
1
- import { getJsonFileAsync } from "@warlock.js/fs";
2
1
  import path from "node:path";
2
+ import { getJsonFileAsync } from "@warlock.js/fs";
3
3
 
4
4
  //#region ../core/src/utils/framework-vesion.ts
5
5
  /**
@@ -2,6 +2,7 @@ import { LocalizedObject, getLocalized } from "./get-localized.mjs";
2
2
  import { Environment, RuntimeStrategy, environment, setEnvironment } from "./environment.mjs";
3
3
  import { appLog } from "./app-log.mjs";
4
4
  import { DatabaseLog, DatabaseLogOptions } from "./database-log.mjs";
5
+ import { Path } from "./normalized-path.mjs";
5
6
  import { fetchLatestVersion } from "./npm-registry.mjs";
6
7
  import { appPath, cachePath, configPath, logsPath, paths, publicPath, rootPath, sanitizePath, srcPath, storagePath, tempPath, uploadsPath, warlockPath } from "./paths.mjs";
7
8
  import { promiseAllObject } from "./promise-all-object.mjs";
@@ -2,6 +2,7 @@ import { appLog } from "./app-log.mjs";
2
2
  import { DatabaseLog } from "./database-log.mjs";
3
3
  import { environment, setEnvironment } from "./environment.mjs";
4
4
  import { getLocalized } from "./get-localized.mjs";
5
+ import { Path } from "./normalized-path.mjs";
5
6
  import { fetchLatestVersion } from "./npm-registry.mjs";
6
7
  import { appPath, cachePath, configPath, logsPath, paths, publicPath, rootPath, sanitizePath, srcPath, storagePath, tempPath, uploadsPath, warlockPath } from "./paths.mjs";
7
8
  import { promiseAllObject } from "./promise-all-object.mjs";