@warlock.js/core 5.11.0 → 5.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 (149) hide show
  1. package/CHANGELOG.md +92 -54
  2. package/esm/application/app.d.mts +3 -3
  3. package/esm/application/app.mjs +6 -6
  4. package/esm/application/app.mjs.map +1 -1
  5. package/esm/cli/cli-commands.utils.mjs +7 -3
  6. package/esm/cli/cli-commands.utils.mjs.map +1 -1
  7. package/esm/cli/commands/doctor/checks/health.check.mjs +1 -1
  8. package/esm/cli/commands/doctor/checks/health.check.mjs.map +1 -1
  9. package/esm/connectors/socket-connector.mjs +13 -16
  10. package/esm/connectors/socket-connector.mjs.map +1 -1
  11. package/esm/container/index.d.mts +20 -7
  12. package/esm/container/index.d.mts.map +1 -1
  13. package/esm/container/index.mjs +8 -5
  14. package/esm/container/index.mjs.map +1 -1
  15. package/esm/database/utils.d.mts +5 -1
  16. package/esm/database/utils.d.mts.map +1 -1
  17. package/esm/database/utils.mjs +7 -3
  18. package/esm/database/utils.mjs.map +1 -1
  19. package/esm/dev-server/dev-logger.mjs +12 -1
  20. package/esm/dev-server/dev-logger.mjs.map +1 -1
  21. package/esm/dev-server/development-server.mjs +1 -1
  22. package/esm/dev-server/development-server.mjs.map +1 -1
  23. package/esm/dev-server/file-event-handler.mjs +72 -13
  24. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  25. package/esm/dev-server/file-manager.d.mts +8 -0
  26. package/esm/dev-server/file-manager.d.mts.map +1 -1
  27. package/esm/dev-server/file-manager.mjs +26 -4
  28. package/esm/dev-server/file-manager.mjs.map +1 -1
  29. package/esm/dev-server/files-orchestrator.mjs +3 -3
  30. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  31. package/esm/dev-server/files-watcher.mjs +16 -2
  32. package/esm/dev-server/files-watcher.mjs.map +1 -1
  33. package/esm/dev-server/flags.mjs +16 -1
  34. package/esm/dev-server/flags.mjs.map +1 -1
  35. package/esm/dev-server/layer-executor.mjs +19 -2
  36. package/esm/dev-server/layer-executor.mjs.map +1 -1
  37. package/esm/dev-server/translation-type-generator.mjs +28 -0
  38. package/esm/dev-server/translation-type-generator.mjs.map +1 -0
  39. package/esm/dev-server/tsconfig-manager.mjs +1 -0
  40. package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
  41. package/esm/dev-server/type-generator.mjs +41 -5
  42. package/esm/dev-server/type-generator.mjs.map +1 -1
  43. package/esm/encryption/index.mjs +1 -1
  44. package/esm/errors/container-key-missing-error.mjs +18 -6
  45. package/esm/errors/container-key-missing-error.mjs.map +1 -1
  46. package/esm/generations/features/auth-google.feature.mjs +18 -0
  47. package/esm/generations/features/auth-google.feature.mjs.map +1 -0
  48. package/esm/generations/features/auth-passkeys.feature.mjs +19 -0
  49. package/esm/generations/features/auth-passkeys.feature.mjs.map +1 -0
  50. package/esm/generations/features/index.mjs +6 -0
  51. package/esm/generations/features/index.mjs.map +1 -1
  52. package/esm/generations/features/queue.feature.mjs +67 -0
  53. package/esm/generations/features/queue.feature.mjs.map +1 -0
  54. package/esm/generations/stubs.mjs +10 -10
  55. package/esm/generations/stubs.mjs.map +1 -1
  56. package/esm/http/context/request-context.d.mts +14 -11
  57. package/esm/http/context/request-context.d.mts.map +1 -1
  58. package/esm/http/context/request-context.mjs +13 -9
  59. package/esm/http/context/request-context.mjs.map +1 -1
  60. package/esm/http/createHttpApplication.d.mts.map +1 -1
  61. package/esm/http/createHttpApplication.mjs +2 -0
  62. package/esm/http/createHttpApplication.mjs.map +1 -1
  63. package/esm/http/csp.d.mts +139 -0
  64. package/esm/http/csp.d.mts.map +1 -0
  65. package/esm/http/csp.mjs +134 -0
  66. package/esm/http/csp.mjs.map +1 -0
  67. package/esm/http/errors/errors.d.mts +17 -1
  68. package/esm/http/errors/errors.d.mts.map +1 -1
  69. package/esm/http/errors/errors.mjs +20 -1
  70. package/esm/http/errors/errors.mjs.map +1 -1
  71. package/esm/http/index.d.mts +8 -3
  72. package/esm/http/index.mjs +6 -1
  73. package/esm/http/middleware/concurrency-limit.middleware.d.mts +2 -2
  74. package/esm/http/middleware/concurrency-limit.middleware.mjs +1 -1
  75. package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
  76. package/esm/http/middleware/inject-request-context.d.mts +1 -1
  77. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  78. package/esm/http/middleware/inject-request-context.mjs +10 -0
  79. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  80. package/esm/http/middleware/rate-limit.middleware.d.mts +1 -1
  81. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  82. package/esm/http/middleware/utils/idempotency-key.d.mts.map +1 -1
  83. package/esm/http/middleware/utils/idempotency-key.mjs +13 -13
  84. package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
  85. package/esm/http/request-controller.d.mts +1 -1
  86. package/esm/http/request.d.mts +32 -44
  87. package/esm/http/request.d.mts.map +1 -1
  88. package/esm/http/request.mjs +52 -44
  89. package/esm/http/request.mjs.map +1 -1
  90. package/esm/http/response.d.mts +18 -0
  91. package/esm/http/response.d.mts.map +1 -1
  92. package/esm/http/response.mjs +31 -0
  93. package/esm/http/response.mjs.map +1 -1
  94. package/esm/http/stream-react-response.d.mts +65 -0
  95. package/esm/http/stream-react-response.d.mts.map +1 -0
  96. package/esm/http/stream-react-response.mjs +46 -0
  97. package/esm/http/stream-react-response.mjs.map +1 -0
  98. package/esm/http/tracing/index.mjs +4 -0
  99. package/esm/http/tracing/trace-id.d.mts +14 -0
  100. package/esm/http/tracing/trace-id.d.mts.map +1 -0
  101. package/esm/http/tracing/trace-id.mjs +37 -0
  102. package/esm/http/tracing/trace-id.mjs.map +1 -0
  103. package/esm/http/tracing/tracing-dispatcher.d.mts +42 -0
  104. package/esm/http/tracing/tracing-dispatcher.d.mts.map +1 -0
  105. package/esm/http/tracing/tracing-dispatcher.mjs +94 -0
  106. package/esm/http/tracing/tracing-dispatcher.mjs.map +1 -0
  107. package/esm/http/tracing/tracing.type.d.mts +66 -0
  108. package/esm/http/tracing/tracing.type.d.mts.map +1 -0
  109. package/esm/http/types.d.mts +27 -21
  110. package/esm/http/types.d.mts.map +1 -1
  111. package/esm/index.d.mts +9 -4
  112. package/esm/index.mjs +7 -3
  113. package/esm/production/esbuild-preflight.mjs +47 -0
  114. package/esm/production/esbuild-preflight.mjs.map +1 -0
  115. package/esm/production/production-builder.mjs +19 -15
  116. package/esm/production/production-builder.mjs.map +1 -1
  117. package/esm/restful/restful.d.mts +1 -1
  118. package/esm/router/log-request-lifecycle.mjs +12 -2
  119. package/esm/router/log-request-lifecycle.mjs.map +1 -1
  120. package/esm/router/router.d.mts.map +1 -1
  121. package/esm/router/router.mjs +10 -0
  122. package/esm/router/router.mjs.map +1 -1
  123. package/esm/router/types.d.mts +1 -1
  124. package/esm/socket/utils.mjs +1 -2
  125. package/esm/socket/utils.mjs.map +1 -1
  126. package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
  127. package/esm/storage/drivers/cloud-driver.mjs +2 -5
  128. package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
  129. package/esm/warlock-config/types.d.mts +12 -0
  130. package/esm/warlock-config/types.d.mts.map +1 -1
  131. package/llms-full.txt +314 -46
  132. package/llms.txt +1 -0
  133. package/package.json +11 -12
  134. package/skills/add-connector/SKILL.md +1 -1
  135. package/skills/build-restful/SKILL.md +2 -2
  136. package/skills/configure-app/SKILL.md +31 -0
  137. package/skills/create-controller/SKILL.md +4 -4
  138. package/skills/request-tracing/SKILL.md +208 -0
  139. package/skills/send-response/SKILL.md +16 -0
  140. package/skills/store-file/SKILL.md +1 -1
  141. package/skills/upload-file/SKILL.md +2 -2
  142. package/skills/use-app-context/SKILL.md +2 -2
  143. package/skills/use-localization/SKILL.md +24 -21
  144. package/skills/use-middleware/SKILL.md +2 -2
  145. package/skills/use-repository/SKILL.md +1 -1
  146. package/skills/use-request-locals/SKILL.md +1 -1
  147. package/skills/wire-socket/SKILL.md +3 -3
  148. package/skills/write-middleware/SKILL.md +11 -5
  149. package/skills/write-use-case/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"health.check.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/doctor/checks/health.check.ts"],"sourcesContent":["import { config } from \"../../../../config/config-getter\";\nimport { container } from \"../../../../container\";\nimport { router } from \"../../../../router/router\";\nimport type { DoctorCheck } from \"../check.types\";\n\n/**\n * Ask the booted Fastify instance whether a GET route exists at this path.\n *\n * `hasRoute` is the instance's own answer, not a re-derivation of the config\n * that was supposed to produce it — which is the entire point of asking it.\n * Guarded because it is the one part of this check that depends on a Fastify\n * API: if the instance cannot answer, the check says so instead of inventing a\n * verdict from the config flag it is meant to be verifying.\n */\nfunction fastifyHasGet(path: string): boolean | undefined {\n const http = container.has(\"http.server\") ? container.get<any>(\"http.server\") : undefined;\n\n if (!http || typeof http.hasRoute !== \"function\") return undefined;\n\n try {\n return Boolean(http.hasRoute({ method: \"GET\", url: path }));\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether an app route already claims this path. The HTTP connector puts the\n * probes on the Fastify instance directly and the router scans app routes onto\n * the same instance at `start()`, so a collision is a duplicate registration:\n * Fastify refuses it and the server does not start.\n */\nfunction appRouteClaims(path: string): boolean {\n return router.list().some((route) => {\n const method = String(route.method).toUpperCase();\n\n return route.path === path && (method === \"GET\" || method === \"ALL\");\n });\n}\n\n/**\n * Confirms the liveness (`/health`) and readiness (`/ready`) endpoints are\n * really there.\n *\n * NEEDS A BOOTED APP: the HTTP connector registers the probes during `boot()`,\n * which the boot pass runs. Previously this check read `http.health.enabled`\n * and reported the endpoints as \"registered\" on that basis alone — in the same\n * report where `routes` said zero, because nothing had been booted at all. It\n * was reporting an intention as a fact, and the two lines contradicted each\n * other in the owner's own run.\n *\n * Verdicts:\n * - no `http` config → not applicable, no line;\n * - `http.health.enabled = false` → `ok`. Turning the probes off is a supported\n * choice, and a warning that fires on a deliberate setting every single run\n * is not read by the time it matters;\n * - an app route already claims a probe's path → `fail`: Fastify will refuse\n * the duplicate and the server will not start;\n * - the instance says the route is absent → `fail`;\n * - otherwise → `ok`, with the paths that are actually registered.\n */\nexport const healthCheck: DoctorCheck = {\n name: \"health\",\n run: (context) => {\n if (!config.get(\"http\")) {\n return undefined;\n }\n\n const healthConfig = config.get(\"http.health\");\n\n if (healthConfig?.enabled === false) {\n return {\n name: \"health\",\n status: \"ok\",\n detail: \"probes disabled by config (http.health.enabled = false)\",\n };\n }\n\n const livenessPath = healthConfig?.path ?? \"/health\";\n const readinessPath = healthConfig?.readinessPath ?? \"/ready\";\n\n const collisions = [livenessPath, readinessPath].filter(appRouteClaims);\n\n if (collisions.length > 0) {\n return {\n name: \"health\",\n status: \"fail\",\n detail:\n `an app route already claims ${collisions.join(\" and \")} — Fastify refuses the ` +\n \"duplicate registration and the server will not start. Move the app route, or \" +\n \"rename the probe via http.health.path / http.health.readinessPath\",\n };\n }\n\n // The HTTP connector is what registers the probes. If it did not boot, the\n // connectors check already says so with the reason — reporting the same\n // defect a second time here as a health failure would inflate one problem\n // into two.\n if (!context.connectors.booted.includes(\"http\")) {\n return undefined;\n }\n\n const registered = [livenessPath, readinessPath].map(fastifyHasGet);\n\n if (registered.some((answer) => answer === undefined)) {\n return {\n name: \"health\",\n status: \"warn\",\n detail:\n \"could not read the http server's route table — \" +\n `${livenessPath} + ${readinessPath} unverified`,\n };\n }\n\n const missing = [livenessPath, readinessPath].filter((_path, index) => !registered[index]);\n\n if (missing.length > 0) {\n return {\n name: \"health\",\n status: \"fail\",\n detail: `enabled in config but not registered on the http server: ${missing.join(\", \")}`,\n };\n }\n\n return {\n name: \"health\",\n status: \"ok\",\n detail: `liveness ${livenessPath} + readiness ${readinessPath} registered`,\n };\n },\n};\n"],"mappings":";;;;;;;;;;;;;;AAcA,SAAS,cAAc,MAAmC;CACxD,MAAM,OAAO,UAAU,IAAI,aAAa,IAAI,UAAU,IAAS,aAAa,IAAI;CAEhF,IAAI,CAAC,QAAQ,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AI;EACvF;EAGF,OAAO;GACL,MAAM;GACN,QAAQ;GACR,QAAQ,YAAY,aAAa,eAAe,cAAc;EAChE;CACF;AACF"}
1
+ {"version":3,"file":"health.check.mjs","names":[],"sources":["../../../../../../../../../../core/src/cli/commands/doctor/checks/health.check.ts"],"sourcesContent":["import { config } from \"../../../../config/config-getter\";\nimport { container } from \"../../../../container\";\nimport { router } from \"../../../../router/router\";\nimport type { DoctorCheck } from \"../check.types\";\n\n/**\n * Ask the booted Fastify instance whether a GET route exists at this path.\n *\n * `hasRoute` is the instance's own answer, not a re-derivation of the config\n * that was supposed to produce it — which is the entire point of asking it.\n * Guarded because it is the one part of this check that depends on a Fastify\n * API: if the instance cannot answer, the check says so instead of inventing a\n * verdict from the config flag it is meant to be verifying.\n */\nfunction fastifyHasGet(path: string): boolean | undefined {\n const http = container.tryGet<any>(\"http.server\");\n\n if (!http || typeof http.hasRoute !== \"function\") return undefined;\n\n try {\n return Boolean(http.hasRoute({ method: \"GET\", url: path }));\n } catch {\n return undefined;\n }\n}\n\n/**\n * Whether an app route already claims this path. The HTTP connector puts the\n * probes on the Fastify instance directly and the router scans app routes onto\n * the same instance at `start()`, so a collision is a duplicate registration:\n * Fastify refuses it and the server does not start.\n */\nfunction appRouteClaims(path: string): boolean {\n return router.list().some((route) => {\n const method = String(route.method).toUpperCase();\n\n return route.path === path && (method === \"GET\" || method === \"ALL\");\n });\n}\n\n/**\n * Confirms the liveness (`/health`) and readiness (`/ready`) endpoints are\n * really there.\n *\n * NEEDS A BOOTED APP: the HTTP connector registers the probes during `boot()`,\n * which the boot pass runs. Previously this check read `http.health.enabled`\n * and reported the endpoints as \"registered\" on that basis alone — in the same\n * report where `routes` said zero, because nothing had been booted at all. It\n * was reporting an intention as a fact, and the two lines contradicted each\n * other in the owner's own run.\n *\n * Verdicts:\n * - no `http` config → not applicable, no line;\n * - `http.health.enabled = false` → `ok`. Turning the probes off is a supported\n * choice, and a warning that fires on a deliberate setting every single run\n * is not read by the time it matters;\n * - an app route already claims a probe's path → `fail`: Fastify will refuse\n * the duplicate and the server will not start;\n * - the instance says the route is absent → `fail`;\n * - otherwise → `ok`, with the paths that are actually registered.\n */\nexport const healthCheck: DoctorCheck = {\n name: \"health\",\n run: (context) => {\n if (!config.get(\"http\")) {\n return undefined;\n }\n\n const healthConfig = config.get(\"http.health\");\n\n if (healthConfig?.enabled === false) {\n return {\n name: \"health\",\n status: \"ok\",\n detail: \"probes disabled by config (http.health.enabled = false)\",\n };\n }\n\n const livenessPath = healthConfig?.path ?? \"/health\";\n const readinessPath = healthConfig?.readinessPath ?? \"/ready\";\n\n const collisions = [livenessPath, readinessPath].filter(appRouteClaims);\n\n if (collisions.length > 0) {\n return {\n name: \"health\",\n status: \"fail\",\n detail:\n `an app route already claims ${collisions.join(\" and \")} — Fastify refuses the ` +\n \"duplicate registration and the server will not start. Move the app route, or \" +\n \"rename the probe via http.health.path / http.health.readinessPath\",\n };\n }\n\n // The HTTP connector is what registers the probes. If it did not boot, the\n // connectors check already says so with the reason — reporting the same\n // defect a second time here as a health failure would inflate one problem\n // into two.\n if (!context.connectors.booted.includes(\"http\")) {\n return undefined;\n }\n\n const registered = [livenessPath, readinessPath].map(fastifyHasGet);\n\n if (registered.some((answer) => answer === undefined)) {\n return {\n name: \"health\",\n status: \"warn\",\n detail:\n \"could not read the http server's route table — \" +\n `${livenessPath} + ${readinessPath} unverified`,\n };\n }\n\n const missing = [livenessPath, readinessPath].filter((_path, index) => !registered[index]);\n\n if (missing.length > 0) {\n return {\n name: \"health\",\n status: \"fail\",\n detail: `enabled in config but not registered on the http server: ${missing.join(\", \")}`,\n };\n }\n\n return {\n name: \"health\",\n status: \"ok\",\n detail: `liveness ${livenessPath} + readiness ${readinessPath} registered`,\n };\n },\n};\n"],"mappings":";;;;;;;;;;;;;;AAcA,SAAS,cAAc,MAAmC;CACxD,MAAM,OAAO,UAAU,OAAY,aAAa;CAEhD,IAAI,CAAC,QAAQ,OAAO,KAAK,aAAa,YAAY,OA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MAAM;GACN,QAAQ;GACR,QAAQ,YAAY,aAAa,eAAe,cAAc;EAChE;CACF;AACF"}
@@ -50,8 +50,9 @@ var SocketConnector = class extends BaseConnector {
50
50
  }
51
51
  log.info("socket", "connection", "Starting Socket.IO server");
52
52
  let server;
53
- if (container.has("http.server")) {
54
- server = container.get("http.server").server;
53
+ const fastify = container.tryGet("http.server");
54
+ if (fastify) {
55
+ server = fastify.server;
55
56
  this.ownsRawServer = false;
56
57
  } else {
57
58
  server = socketConfig.ssl ? createServer$1() : createServer();
@@ -84,21 +85,17 @@ var SocketConnector = class extends BaseConnector {
84
85
  */
85
86
  async shutdown() {
86
87
  if (!this.active) return;
87
- if (container.has("socket")) {
88
- const socket = container.get("socket");
89
- await new Promise((resolve) => {
90
- socket.close(() => resolve());
91
- });
92
- }
93
- if (this.ownsRawServer && container.has("socket.rawServer")) {
94
- const server = container.get("socket.rawServer");
95
- await new Promise((resolve, reject) => {
96
- server.close((error) => {
97
- if (error) reject(error);
98
- else resolve();
99
- });
88
+ const socket = container.tryGet("socket");
89
+ if (socket) await new Promise((resolve) => {
90
+ socket.close(() => resolve());
91
+ });
92
+ const rawServer = this.ownsRawServer ? container.tryGet("socket.rawServer") : void 0;
93
+ if (rawServer) await new Promise((resolve, reject) => {
94
+ rawServer.close((error) => {
95
+ if (error) reject(error);
96
+ else resolve();
100
97
  });
101
- }
98
+ });
102
99
  this.active = false;
103
100
  }
104
101
  };
@@ -1 +1 @@
1
- {"version":3,"file":"socket-connector.mjs","names":["createHttpsServer","createHttpServer"],"sources":["../../../../../../../core/src/connectors/socket-connector.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { log } from \"@warlock.js/logger\";\nimport { createServer as createHttpServer } from \"http\";\nimport { createServer as createHttpsServer } from \"https\";\nimport type { Server } from \"socket.io\";\nimport { container } from \"../container\";\nimport { BaseConnector } from \"./base-connector\";\nimport { ConnectorLifecyclePhase, type ConnectorName, ConnectorPriority } from \"./types\";\n\n/**\n * Shown when a project enables sockets (a `socket` config is present) but the\n * optional `socket.io` peer is not installed.\n */\nconst SOCKET_INSTALL_INSTRUCTIONS = `\nRealtime socket server requires the socket.io package.\nInstall it with:\n\n warlock add socket\n\nOr manually:\n\n npm install socket.io\n pnpm add socket.io\n yarn add socket.io\n`.trim();\n\n/**\n * Socket Connector\n * Manages Socket server (Socket.IO) lifecycle\n */\nexport class SocketConnector extends BaseConnector {\n public readonly name: ConnectorName = \"socket\";\n public readonly priority = ConnectorPriority.SOCKET;\n public readonly lifecyclePhase = ConnectorLifecyclePhase.Late;\n\n /**\n * Files that trigger Socket server restart\n * Note: routes.ts changes will be handled by HMR with wildcard routing\n * Connectors receive config file paths directly (not .env) thanks to layer-executor\n */\n protected readonly watchedFiles = [\"src/config/socket.ts\"];\n\n protected socket?: Server;\n\n /**\n * Whether this connector created the underlying node HTTP(S) server.\n *\n * When `http` is present, socket binds onto the HTTP connector's shared\n * `fastify.server` and must NOT close it on shutdown — the HTTP connector\n * owns the graceful drain. Socket only closes the node server when it\n * created one itself (http absent). See {@link shutdown}.\n */\n protected ownsRawServer = false;\n\n /**\n * Boot the connector\n */\n public async boot() {\n const socketConfig = config.get(\"socket\");\n\n if (!socketConfig) return;\n\n // socket.io is an optional peer — load it lazily so projects that don't use\n // realtime sockets never need it installed (mirrors the mail/storage drivers).\n let SocketServer: typeof import(\"socket.io\").Server;\n try {\n ({ Server: SocketServer } = await import(\"socket.io\"));\n } catch {\n throw new Error(SOCKET_INSTALL_INSTRUCTIONS);\n }\n\n log.info(\"socket\", \"connection\", \"Starting Socket.IO server\");\n\n // now we have two cases\n // 1. http is used, then use it (shared — the HTTP connector owns it)\n // 2. http is not used, then create a new server (we own it)\n let server;\n if (container.has(\"http.server\")) {\n const fastify = container.get(\"http.server\");\n server = fastify.server;\n this.ownsRawServer = false;\n } else {\n server = socketConfig.ssl ? createHttpsServer() : createHttpServer();\n server.listen(socketConfig.port);\n this.ownsRawServer = true;\n }\n\n container.set(\"socket.rawServer\", server);\n\n this.socket = new SocketServer(server, {\n // The shared raw server may carry OTHER `upgrade` consumers — Vite's HMR\n // websocket does exactly that when `WebConnector` is registered\n // (`web/src/server/web-connector.ts`, `server.hmr.server = fastify.server`).\n // engine.io's default `destroyUpgrade: true` schedules a destroy for every\n // upgrade whose path is not `/socket.io`\n // (`engine.io/build/server.js:676-695`: `setTimeout(… socket.end(), 1000)`),\n // and the only thing saving a foreign websocket today is that it wrote its\n // handshake bytes synchronously and so trips the `bytesWritten <= 0` guard\n // before the 1s timer fires. That is an undocumented race, not a contract.\n // Turning the destroy off removes the coupling outright and makes the\n // shared server safe for any app-owned websocket route.\n // A project can still override it via `socket.options`.\n destroyUpgrade: false,\n ...socketConfig.options,\n });\n\n container.set(\"socket\", this.socket);\n }\n\n /**\n * Initialize Socket server\n */\n public async start(): Promise<void> {\n const socketConfig = config.get(\"socket\");\n\n // `this.socket` is only set by boot() once a socket config is present —\n // use it (not a never-assigned field) to detect a successful boot.\n if (!socketConfig || !this.socket) return;\n\n log.success(\"socket\", \"connection\", \"Established Socket.IO server\");\n\n this.active = true;\n }\n\n /**\n * Shutdown Socket server\n *\n * Always closes the Socket.IO layer (and awaits the drain). The underlying\n * node HTTP(S) server is only closed here when this connector created it\n * ({@link ownsRawServer}); when `http` owns the shared server, we leave it\n * for the HTTP connector to drain and close, so the two connectors don't\n * race to `close()` the same socket.\n */\n public async shutdown(): Promise<void> {\n if (!this.active) {\n return;\n }\n\n if (container.has(\"socket\")) {\n const socket = container.get(\"socket\");\n // socket.io's close() takes a callback — await it so shutdown doesn't\n // report done while sockets are still draining.\n await new Promise<void>((resolve) => {\n socket.close(() => resolve());\n });\n }\n\n if (this.ownsRawServer && container.has(\"socket.rawServer\")) {\n const server = container.get(\"socket.rawServer\");\n await new Promise<void>((resolve, reject) => {\n server.close((error?: Error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }\n\n this.active = false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAM,8BA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;IAC3C,OAAO,OAAO,UAAkB;KAC9B,IAAI,OACF,OAAO,KAAK;UAEZ,QAAQ;IAEZ,CAAC;GACH,CAAC;EACH;EAEA,KAAK,SAAS;CAChB;AACF"}
1
+ {"version":3,"file":"socket-connector.mjs","names":["createHttpsServer","createHttpServer"],"sources":["../../../../../../../core/src/connectors/socket-connector.ts"],"sourcesContent":["import config from \"@mongez/config\";\nimport { log } from \"@warlock.js/logger\";\nimport { createServer as createHttpServer } from \"http\";\nimport { createServer as createHttpsServer } from \"https\";\nimport type { Server } from \"socket.io\";\nimport { container } from \"../container\";\nimport { BaseConnector } from \"./base-connector\";\nimport { ConnectorLifecyclePhase, type ConnectorName, ConnectorPriority } from \"./types\";\n\n/**\n * Shown when a project enables sockets (a `socket` config is present) but the\n * optional `socket.io` peer is not installed.\n */\nconst SOCKET_INSTALL_INSTRUCTIONS = `\nRealtime socket server requires the socket.io package.\nInstall it with:\n\n warlock add socket\n\nOr manually:\n\n npm install socket.io\n pnpm add socket.io\n yarn add socket.io\n`.trim();\n\n/**\n * Socket Connector\n * Manages Socket server (Socket.IO) lifecycle\n */\nexport class SocketConnector extends BaseConnector {\n public readonly name: ConnectorName = \"socket\";\n public readonly priority = ConnectorPriority.SOCKET;\n public readonly lifecyclePhase = ConnectorLifecyclePhase.Late;\n\n /**\n * Files that trigger Socket server restart\n * Note: routes.ts changes will be handled by HMR with wildcard routing\n * Connectors receive config file paths directly (not .env) thanks to layer-executor\n */\n protected readonly watchedFiles = [\"src/config/socket.ts\"];\n\n protected socket?: Server;\n\n /**\n * Whether this connector created the underlying node HTTP(S) server.\n *\n * When `http` is present, socket binds onto the HTTP connector's shared\n * `fastify.server` and must NOT close it on shutdown — the HTTP connector\n * owns the graceful drain. Socket only closes the node server when it\n * created one itself (http absent). See {@link shutdown}.\n */\n protected ownsRawServer = false;\n\n /**\n * Boot the connector\n */\n public async boot() {\n const socketConfig = config.get(\"socket\");\n\n if (!socketConfig) return;\n\n // socket.io is an optional peer — load it lazily so projects that don't use\n // realtime sockets never need it installed (mirrors the mail/storage drivers).\n let SocketServer: typeof import(\"socket.io\").Server;\n try {\n ({ Server: SocketServer } = await import(\"socket.io\"));\n } catch {\n throw new Error(SOCKET_INSTALL_INSTRUCTIONS);\n }\n\n log.info(\"socket\", \"connection\", \"Starting Socket.IO server\");\n\n // now we have two cases\n // 1. http is used, then use it (shared — the HTTP connector owns it)\n // 2. http is not used, then create a new server (we own it)\n let server;\n const fastify = container.tryGet(\"http.server\");\n if (fastify) {\n server = fastify.server;\n this.ownsRawServer = false;\n } else {\n server = socketConfig.ssl ? createHttpsServer() : createHttpServer();\n server.listen(socketConfig.port);\n this.ownsRawServer = true;\n }\n\n container.set(\"socket.rawServer\", server);\n\n this.socket = new SocketServer(server, {\n // The shared raw server may carry OTHER `upgrade` consumers — Vite's HMR\n // websocket does exactly that when `WebConnector` is registered\n // (`web/src/server/web-connector.ts`, `server.hmr.server = fastify.server`).\n // engine.io's default `destroyUpgrade: true` schedules a destroy for every\n // upgrade whose path is not `/socket.io`\n // (`engine.io/build/server.js:676-695`: `setTimeout(… socket.end(), 1000)`),\n // and the only thing saving a foreign websocket today is that it wrote its\n // handshake bytes synchronously and so trips the `bytesWritten <= 0` guard\n // before the 1s timer fires. That is an undocumented race, not a contract.\n // Turning the destroy off removes the coupling outright and makes the\n // shared server safe for any app-owned websocket route.\n // A project can still override it via `socket.options`.\n destroyUpgrade: false,\n ...socketConfig.options,\n });\n\n container.set(\"socket\", this.socket);\n }\n\n /**\n * Initialize Socket server\n */\n public async start(): Promise<void> {\n const socketConfig = config.get(\"socket\");\n\n // `this.socket` is only set by boot() once a socket config is present —\n // use it (not a never-assigned field) to detect a successful boot.\n if (!socketConfig || !this.socket) return;\n\n log.success(\"socket\", \"connection\", \"Established Socket.IO server\");\n\n this.active = true;\n }\n\n /**\n * Shutdown Socket server\n *\n * Always closes the Socket.IO layer (and awaits the drain). The underlying\n * node HTTP(S) server is only closed here when this connector created it\n * ({@link ownsRawServer}); when `http` owns the shared server, we leave it\n * for the HTTP connector to drain and close, so the two connectors don't\n * race to `close()` the same socket.\n */\n public async shutdown(): Promise<void> {\n if (!this.active) {\n return;\n }\n\n const socket = container.tryGet(\"socket\");\n if (socket) {\n // socket.io's close() takes a callback — await it so shutdown doesn't\n // report done while sockets are still draining.\n await new Promise<void>((resolve) => {\n socket.close(() => resolve());\n });\n }\n\n const rawServer = this.ownsRawServer ? container.tryGet(\"socket.rawServer\") : undefined;\n if (rawServer) {\n await new Promise<void>((resolve, reject) => {\n rawServer.close((error?: Error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }\n\n this.active = false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAM,8BAA8B;;;;;;;;;;;EAWlC,KAAK;;;;;AAMP,IAAa,kBAAb,cAAqC,cAAc;;;cACX;;;sBASJ,CAAC,sBAAsB;uBAY/B;;;;;CAK1B,MAAa,OAAO;EAClB,MAAM,eAAe,OAAO,IAAI,QAAQ;EAExC,IAAI,CAAC,cAAc;EAInB,IAAI;EACJ,IAAI;GACF,CAAC,CAAE,QAAQ,gBAAiB,MAAM,OAAO;EAC3C,QAAQ;GACN,MAAM,IAAI,MAAM,2BAA2B;EAC7C;EAEA,IAAI,KAAK,UAAU,cAAc,2BAA2B;EAK5D,IAAI;EACJ,MAAM,UAAU,UAAU,OAAO,aAAa;EAC9C,IAAI,SAAS;GACX,SAAS,QAAQ;GACjB,KAAK,gBAAgB;EACvB,OAAO;GACL,SAAS,aAAa,MAAMA,eAAkB,IAAIC,aAAiB;GACnE,OAAO,OAAO,aAAa,IAAI;GAC/B,KAAK,gBAAgB;EACvB;EAEA,UAAU,IAAI,oBAAoB,MAAM;EAExC,KAAK,SAAS,IAAI,aAAa,QAAQ;GAarC,gBAAgB;GAChB,GAAG,aAAa;EAClB,CAAC;EAED,UAAU,IAAI,UAAU,KAAK,MAAM;CACrC;;;;CAKA,MAAa,QAAuB;EAKlC,IAAI,CAJiB,OAAO,IAAI,QAIhB,KAAK,CAAC,KAAK,QAAQ;EAEnC,IAAI,QAAQ,UAAU,cAAc,8BAA8B;EAElE,KAAK,SAAS;CAChB;;;;;;;;;;CAWA,MAAa,WAA0B;EACrC,IAAI,CAAC,KAAK,QACR;EAGF,MAAM,SAAS,UAAU,OAAO,QAAQ;EACxC,IAAI,QAGF,MAAM,IAAI,SAAe,YAAY;GACnC,OAAO,YAAY,QAAQ,CAAC;EAC9B,CAAC;EAGH,MAAM,YAAY,KAAK,gBAAgB,UAAU,OAAO,kBAAkB,IAAI;EAC9E,IAAI,WACF,MAAM,IAAI,SAAe,SAAS,WAAW;GAC3C,UAAU,OAAO,UAAkB;IACjC,IAAI,OACF,OAAO,KAAK;SAEZ,QAAQ;GAEZ,CAAC;EACH,CAAC;EAGH,KAAK,SAAS;CAChB;AACF"}
@@ -22,7 +22,15 @@ declare class Container {
22
22
  set<K extends keyof ContainerTypes>(key: K, value: ContainerTypes[K]): void;
23
23
  set<T = any>(key: string, value: T): void;
24
24
  /**
25
- * Get a value from the container
25
+ * Get a value from the container, or throw if `key` is not registered.
26
+ *
27
+ * Behaves exactly like an ordinary "not registered" error when only one
28
+ * copy of this module is loaded. When {@link getRegisteredContainerInstances}
29
+ * shows more than one, the thrown error additionally names that count, so
30
+ * a duplicate-instance dev-path miss is never indistinguishable from a
31
+ * genuine missing registration.
32
+ *
33
+ * Use {@link tryGet} instead when the value is genuinely optional.
26
34
  */
27
35
  get<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];
28
36
  get<T = any>(key: string): T;
@@ -31,13 +39,18 @@ declare class Container {
31
39
  */
32
40
  has(key: ContainerKeys): boolean;
33
41
  /**
34
- * Get a value from the container, or throw if `key` is not registered.
42
+ * Get a value from the container, or `undefined` if `key` is not
43
+ * registered.
35
44
  *
36
- * Behaves exactly like an ordinary "not registered" error when only one
37
- * copy of this module is loaded. When {@link getRegisteredContainerInstances}
38
- * shows more than one, the thrown error additionally names that count, so
39
- * a duplicate-instance dev-path miss is never indistinguishable from a
40
- * genuine missing registration.
45
+ * Use this only for genuinely optional dependencies where the caller
46
+ * has its own fallback for an absent value. For every other read, prefer
47
+ * {@link get}: a hole in the container should fail loudly, not hand back
48
+ * `undefined` typed as the real value.
49
+ */
50
+ tryGet<K extends keyof ContainerTypes>(key: K): ContainerTypes[K] | undefined;
51
+ tryGet<T = any>(key: string): T | undefined;
52
+ /**
53
+ * @deprecated `get` now throws for a missing key; use {@link get}.
41
54
  */
42
55
  getOrFail<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];
43
56
  getOrFail<T = any>(key: string): T;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"mappings":";;;;;;;;;KAiBY,cAAA;EACV,MAAA,EAAQ,MAAA;EACR,aAAA,EAAe,eAAA;EACf,cAAA;EACA,MAAA,EAAQ,MAAA;EACR,iBAAA,EAAmB,UAAA;AAAA;AAAA,KAGhB,aAAA,SAAsB,cAAc;AAAA,cAEnC,SAAA;EATJ;;;EAaO,GAAA,iBAAoB,cAAA,EAAgB,GAAA,EAAK,CAAA,EAAG,KAAA,EAAO,cAAA,CAAe,CAAA;EAClE,GAAA,UAAa,GAAA,UAAa,KAAA,EAAO,CAAA;EAXxC;;;EAmBO,GAAA,iBAAoB,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAC5D,GAAA,UAAa,GAAA,WAAc,CAAA;EAnBL;AAC7B;;EA0BO,GAAA,CAAI,GAAA,EAAK,aAAA;EAxBuB;AAAA;AAAA;;;;;;;EAqChC,SAAA,iBAA0B,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAClE,SAAA,UAAmB,GAAA,WAAc,CAAA;EAvBQ;;;EAoCzC,MAAA,CAAO,GAAA;AAAA;AAAA,cAKH,SAAA,EAAS,SAAkB"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"mappings":";;;;;;;;;KAiBY,cAAA;EACV,MAAA,EAAQ,MAAA;EACR,aAAA,EAAe,eAAA;EACf,cAAA;EACA,MAAA,EAAQ,MAAA;EACR,iBAAA,EAAmB,UAAA;AAAA;AAAA,KAGhB,aAAA,SAAsB,cAAc;AAAA,cAEnC,SAAA;EATJ;;;EAaO,GAAA,iBAAoB,cAAA,EAAgB,GAAA,EAAK,CAAA,EAAG,KAAA,EAAO,cAAA,CAAe,CAAA;EAClE,GAAA,UAAa,GAAA,UAAa,KAAA,EAAO,CAAA;EAXxC;;;;;AAC6B;AAC7B;;;;AAEuC;EAuBhC,GAAA,iBAAoB,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAC5D,GAAA,UAAa,GAAA,WAAc,CAAA;EAtBrB;;;EAmCN,GAAA,CAAI,GAAA,EAAK,aAAA;EA/ByD;;;;;;;;;EA4ClE,MAAA,iBAAuB,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAC/D,MAAA,UAAgB,GAAA,WAAc,CAAA;EADiC;;;EAS/D,SAAA,iBAA0B,cAAA,EAAgB,GAAA,EAAK,CAAA,GAAI,cAAA,CAAe,CAAA;EAClE,SAAA,UAAmB,GAAA,WAAc,CAAA;EADiC;;;EASlE,MAAA,CAAO,GAAA;AAAA;AAAA,cAKH,SAAA,EAAS,SAAkB"}
@@ -9,6 +9,10 @@ var Container = class {
9
9
  containerMap.set(key, value);
10
10
  }
11
11
  get(key) {
12
+ if (!containerMap.has(key)) {
13
+ const instanceCount = getRegisteredContainerInstances().length;
14
+ throw new ContainerKeyMissingError(key, instanceCount, [...containerMap.keys()]);
15
+ }
12
16
  return containerMap.get(key);
13
17
  }
14
18
  /**
@@ -17,13 +21,12 @@ var Container = class {
17
21
  has(key) {
18
22
  return containerMap.has(key);
19
23
  }
20
- getOrFail(key) {
21
- if (!containerMap.has(key)) {
22
- const instanceCount = getRegisteredContainerInstances().length;
23
- throw new ContainerKeyMissingError(key, instanceCount);
24
- }
24
+ tryGet(key) {
25
25
  return containerMap.get(key);
26
26
  }
27
+ getOrFail(key) {
28
+ return this.get(key);
29
+ }
27
30
  /**
28
31
  * Delete a key from the container
29
32
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"sourcesContent":["import { type DataSource } from \"@warlock.js/cascade\";\nimport { type FastifyInstance } from \"fastify\";\nimport { type Server } from \"socket.io\";\nimport { ContainerKeyMissingError } from \"../errors/container-key-missing-error\";\nimport { type Router } from \"../router\";\nimport {\n getRegisteredContainerInstances,\n registerContainerInstance,\n} from \"./container-instance-registry\";\n\nconst containerMap: Map<string, any> = new Map();\n\nregisterContainerInstance();\n\n/**\n * Known container types for better IDE support\n */\nexport type ContainerTypes = {\n router: Router;\n \"http.server\": FastifyInstance;\n \"http.baseUrl\": string;\n socket: Server;\n \"database.source\": DataSource;\n};\n\ntype ContainerKeys = keyof ContainerTypes | (string & {});\n\nclass Container {\n /**\n * Set a value in the container\n */\n public set<K extends keyof ContainerTypes>(key: K, value: ContainerTypes[K]): void;\n public set<T = any>(key: string, value: T): void;\n public set(key: any, value: any) {\n containerMap.set(key, value);\n }\n\n /**\n * Get a value from the container\n */\n public get<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public get<T = any>(key: string): T;\n public get(key: any): any {\n return containerMap.get(key);\n }\n\n /**\n * Check if a key exists in the container\n */\n public has(key: ContainerKeys) {\n return containerMap.has(key);\n }\n\n /**\n * Get a value from the container, or throw if `key` is not registered.\n *\n * Behaves exactly like an ordinary \"not registered\" error when only one\n * copy of this module is loaded. When {@link getRegisteredContainerInstances}\n * shows more than one, the thrown error additionally names that count, so\n * a duplicate-instance dev-path miss is never indistinguishable from a\n * genuine missing registration.\n */\n public getOrFail<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public getOrFail<T = any>(key: string): T;\n public getOrFail(key: any): any {\n if (!containerMap.has(key)) {\n const instanceCount = getRegisteredContainerInstances().length;\n throw new ContainerKeyMissingError(key, instanceCount);\n }\n\n return containerMap.get(key);\n }\n\n /**\n * Delete a key from the container\n */\n public delete(key: string) {\n containerMap.delete(key);\n }\n}\n\nexport const container = new Container();\n"],"mappings":";;;;AAUA,MAAM,+BAAiC,IAAI,IAAI;AAE/C,0BAA0B;AAe1B,IAAM,YAAN,MAAgB;CAMd,AAAO,IAAI,KAAU,OAAY;EAC/B,aAAa,IAAI,KAAK,KAAK;CAC7B;CAOA,AAAO,IAAI,KAAe;EACxB,OAAO,aAAa,IAAI,GAAG;CAC7B;;;;CAKA,AAAO,IAAI,KAAoB;EAC7B,OAAO,aAAa,IAAI,GAAG;CAC7B;CAaA,AAAO,UAAU,KAAe;EAC9B,IAAI,CAAC,aAAa,IAAI,GAAG,GAAG;GAC1B,MAAM,gBAAgB,gCAAgC,CAAC,CAAC;GACxD,MAAM,IAAI,yBAAyB,KAAK,aAAa;EACvD;EAEA,OAAO,aAAa,IAAI,GAAG;CAC7B;;;;CAKA,AAAO,OAAO,KAAa;EACzB,aAAa,OAAO,GAAG;CACzB;AACF;AAEA,MAAa,YAAY,IAAI,UAAU"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/container/index.ts"],"sourcesContent":["import { type DataSource } from \"@warlock.js/cascade\";\nimport { type FastifyInstance } from \"fastify\";\nimport { type Server } from \"socket.io\";\nimport { ContainerKeyMissingError } from \"../errors/container-key-missing-error\";\nimport { type Router } from \"../router\";\nimport {\n getRegisteredContainerInstances,\n registerContainerInstance,\n} from \"./container-instance-registry\";\n\nconst containerMap: Map<string, any> = new Map();\n\nregisterContainerInstance();\n\n/**\n * Known container types for better IDE support\n */\nexport type ContainerTypes = {\n router: Router;\n \"http.server\": FastifyInstance;\n \"http.baseUrl\": string;\n socket: Server;\n \"database.source\": DataSource;\n};\n\ntype ContainerKeys = keyof ContainerTypes | (string & {});\n\nclass Container {\n /**\n * Set a value in the container\n */\n public set<K extends keyof ContainerTypes>(key: K, value: ContainerTypes[K]): void;\n public set<T = any>(key: string, value: T): void;\n public set(key: any, value: any) {\n containerMap.set(key, value);\n }\n\n /**\n * Get a value from the container, or throw if `key` is not registered.\n *\n * Behaves exactly like an ordinary \"not registered\" error when only one\n * copy of this module is loaded. When {@link getRegisteredContainerInstances}\n * shows more than one, the thrown error additionally names that count, so\n * a duplicate-instance dev-path miss is never indistinguishable from a\n * genuine missing registration.\n *\n * Use {@link tryGet} instead when the value is genuinely optional.\n */\n public get<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public get<T = any>(key: string): T;\n public get(key: any): any {\n if (!containerMap.has(key)) {\n const instanceCount = getRegisteredContainerInstances().length;\n throw new ContainerKeyMissingError(key, instanceCount, [...containerMap.keys()]);\n }\n\n return containerMap.get(key);\n }\n\n /**\n * Check if a key exists in the container\n */\n public has(key: ContainerKeys) {\n return containerMap.has(key);\n }\n\n /**\n * Get a value from the container, or `undefined` if `key` is not\n * registered.\n *\n * Use this only for genuinely optional dependencies where the caller\n * has its own fallback for an absent value. For every other read, prefer\n * {@link get}: a hole in the container should fail loudly, not hand back\n * `undefined` typed as the real value.\n */\n public tryGet<K extends keyof ContainerTypes>(key: K): ContainerTypes[K] | undefined;\n public tryGet<T = any>(key: string): T | undefined;\n public tryGet(key: any): any {\n return containerMap.get(key);\n }\n\n /**\n * @deprecated `get` now throws for a missing key; use {@link get}.\n */\n public getOrFail<K extends keyof ContainerTypes>(key: K): ContainerTypes[K];\n public getOrFail<T = any>(key: string): T;\n public getOrFail(key: any): any {\n return this.get(key);\n }\n\n /**\n * Delete a key from the container\n */\n public delete(key: string) {\n containerMap.delete(key);\n }\n}\n\nexport const container = new Container();\n"],"mappings":";;;;AAUA,MAAM,+BAAiC,IAAI,IAAI;AAE/C,0BAA0B;AAe1B,IAAM,YAAN,MAAgB;CAMd,AAAO,IAAI,KAAU,OAAY;EAC/B,aAAa,IAAI,KAAK,KAAK;CAC7B;CAeA,AAAO,IAAI,KAAe;EACxB,IAAI,CAAC,aAAa,IAAI,GAAG,GAAG;GAC1B,MAAM,gBAAgB,gCAAgC,CAAC,CAAC;GACxD,MAAM,IAAI,yBAAyB,KAAK,eAAe,CAAC,GAAG,aAAa,KAAK,CAAC,CAAC;EACjF;EAEA,OAAO,aAAa,IAAI,GAAG;CAC7B;;;;CAKA,AAAO,IAAI,KAAoB;EAC7B,OAAO,aAAa,IAAI,GAAG;CAC7B;CAaA,AAAO,OAAO,KAAe;EAC3B,OAAO,aAAa,IAAI,GAAG;CAC7B;CAOA,AAAO,UAAU,KAAe;EAC9B,OAAO,KAAK,IAAI,GAAG;CACrB;;;;CAKA,AAAO,OAAO,KAAa;EACzB,aAAa,OAAO,GAAG;CACzB;AACF;AAEA,MAAa,YAAY,IAAI,UAAU"}
@@ -3,7 +3,11 @@ import { Model } from "@warlock.js/cascade";
3
3
 
4
4
  //#region ../core/src/database/utils.d.ts
5
5
  /**
6
- * Hash password on saving if password changes
6
+ * Hash password on saving if password changes.
7
+ *
8
+ * Uses core's own bcrypt `hashPassword` (salt rounds from
9
+ * `encryption.password.salt`). Core must never import `@warlock.js/auth`:
10
+ * auth depends on core, and its `authService.hashPassword` only delegates here.
7
11
  */
8
12
  declare const useHashedPassword: () => import("@warlock.js/seal").TransformerCallback;
9
13
  type ComputedCallbackModel = (data: any, model: Model, context: SchemaContext) => any | Promise<any>;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"mappings":";;;;;;AASA;cAAa,iBAAA,mCAAiB,mBAO1B;AAAA,KAEC,qBAAA,IACH,IAAA,OACA,KAAA,EAAO,KAAA,EACP,OAAA,EAAS,aAAA,WACA,OAAA;;AANP;AAAC;iBAWW,gBAAA,CAAiB,QAAA,EAAU,qBAAA,GAAqB,gBAAA;;;;iBAWhD,eAAA,CAAgB,KAAA,WAAiB,KAAA,0BAAuC,gBAAA"}
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"mappings":";;;;;;AAaA;;;;AAOI;cAPS,iBAAA,mCAAiB,mBAO1B;AAAA,KAEC,qBAAA,IACH,IAAA,OACA,KAAA,EAAO,KAAA,EACP,OAAA,EAAS,aAAA,WACA,OAAA;;;;iBAKK,gBAAA,CAAiB,QAAA,EAAU,qBAAA,GAAqB,gBAAA;;;;iBAWhD,eAAA,CAAgB,KAAA,WAAiB,KAAA,0BAAuC,gBAAA"}
@@ -1,16 +1,20 @@
1
+ import { hashPassword } from "../encryption/password.mjs";
1
2
  import { useModelTransformer } from "@warlock.js/cascade";
2
3
  import { slugify } from "@mongez/slug";
3
4
  import { get } from "@mongez/reinforcements";
4
- import { authService } from "@warlock.js/auth";
5
5
 
6
6
  //#region ../core/src/database/utils.ts
7
7
  /**
8
- * Hash password on saving if password changes
8
+ * Hash password on saving if password changes.
9
+ *
10
+ * Uses core's own bcrypt `hashPassword` (salt rounds from
11
+ * `encryption.password.salt`). Core must never import `@warlock.js/auth`:
12
+ * auth depends on core, and its `authService.hashPassword` only delegates here.
9
13
  */
10
14
  const useHashedPassword = () => useModelTransformer(({ value, isChanged, isNew }) => {
11
15
  if (!value) return value;
12
16
  if (!isNew && !isChanged) return value;
13
- return authService.hashPassword(String(value));
17
+ return hashPassword(String(value));
14
18
  });
15
19
  /**
16
20
  * Generate computed value based on other fields
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"sourcesContent":["import { get } from \"@mongez/reinforcements\";\nimport { slugify } from \"@mongez/slug\";\nimport { authService } from \"@warlock.js/auth\";\nimport { Model, useModelTransformer } from \"@warlock.js/cascade\";\nimport { type ComputedCallback, type SchemaContext } from \"@warlock.js/seal\";\n\n/**\n * Hash password on saving if password changes\n */\nexport const useHashedPassword = () =>\n useModelTransformer(({ value, isChanged, isNew }) => {\n if (!value) return value;\n\n if (!isNew && !isChanged) return value;\n\n return authService.hashPassword(String(value));\n });\n\ntype ComputedCallbackModel = (\n data: any,\n model: Model,\n context: SchemaContext,\n) => any | Promise<any>;\n\n/**\n * Generate computed value based on other fields\n */\nexport function useComputedModel(callback: ComputedCallbackModel) {\n const computedCallback: ComputedCallback = (data, context) => {\n return callback(data, context.rootContext!.model, context);\n };\n\n return computedCallback;\n}\n\n/**\n * Generate slug based on a field on saving\n */\nexport function useComputedSlug(field = \"title\", scope: \"global\" | \"sibling\" = \"sibling\") {\n return useComputedModel((data, model, context) => {\n const value = scope === \"sibling\" ? data[field] : get(context.allValues, field);\n\n if (!value) return model.get(field);\n\n return slugify(value);\n });\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,0BACX,qBAAqB,EAAE,OAAO,WAAW,YAAY;CACnD,IAAI,CAAC,OAAO,OAAO;CAEnB,IAAI,CAAC,SAAS,CAAC,WAAW,OAAO;CAEjC,OAAO,YAAY,aAAa,OAAO,KAAK,CAAC;AAC/C,CAAC;;;;AAWH,SAAgB,iBAAiB,UAAiC;CAChE,MAAM,oBAAsC,MAAM,YAAY;EAC5D,OAAO,SAAS,MAAM,QAAQ,YAAa,OAAO,OAAO;CAC3D;CAEA,OAAO;AACT;;;;AAKA,SAAgB,gBAAgB,QAAQ,SAAS,QAA8B,WAAW;CACxF,OAAO,kBAAkB,MAAM,OAAO,YAAY;EAChD,MAAM,QAAQ,UAAU,YAAY,KAAK,SAAS,IAAI,QAAQ,WAAW,KAAK;EAE9E,IAAI,CAAC,OAAO,OAAO,MAAM,IAAI,KAAK;EAElC,OAAO,QAAQ,KAAK;CACtB,CAAC;AACH"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../../../../../../../core/src/database/utils.ts"],"sourcesContent":["import { get } from \"@mongez/reinforcements\";\nimport { slugify } from \"@mongez/slug\";\nimport { Model, useModelTransformer } from \"@warlock.js/cascade\";\nimport { type ComputedCallback, type SchemaContext } from \"@warlock.js/seal\";\nimport { hashPassword } from \"../encryption/password\";\n\n/**\n * Hash password on saving if password changes.\n *\n * Uses core's own bcrypt `hashPassword` (salt rounds from\n * `encryption.password.salt`). Core must never import `@warlock.js/auth`:\n * auth depends on core, and its `authService.hashPassword` only delegates here.\n */\nexport const useHashedPassword = () =>\n useModelTransformer(({ value, isChanged, isNew }) => {\n if (!value) return value;\n\n if (!isNew && !isChanged) return value;\n\n return hashPassword(String(value));\n });\n\ntype ComputedCallbackModel = (\n data: any,\n model: Model,\n context: SchemaContext,\n) => any | Promise<any>;\n\n/**\n * Generate computed value based on other fields\n */\nexport function useComputedModel(callback: ComputedCallbackModel) {\n const computedCallback: ComputedCallback = (data, context) => {\n return callback(data, context.rootContext!.model, context);\n };\n\n return computedCallback;\n}\n\n/**\n * Generate slug based on a field on saving\n */\nexport function useComputedSlug(field = \"title\", scope: \"global\" | \"sibling\" = \"sibling\") {\n return useComputedModel((data, model, context) => {\n const value = scope === \"sibling\" ? data[field] : get(context.allValues, field);\n\n if (!value) return model.get(field);\n\n return slugify(value);\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,0BACX,qBAAqB,EAAE,OAAO,WAAW,YAAY;CACnD,IAAI,CAAC,OAAO,OAAO;CAEnB,IAAI,CAAC,SAAS,CAAC,WAAW,OAAO;CAEjC,OAAO,aAAa,OAAO,KAAK,CAAC;AACnC,CAAC;;;;AAWH,SAAgB,iBAAiB,UAAiC;CAChE,MAAM,oBAAsC,MAAM,YAAY;EAC5D,OAAO,SAAS,MAAM,QAAQ,YAAa,OAAO,OAAO;CAC3D;CAEA,OAAO;AACT;;;;AAKA,SAAgB,gBAAgB,QAAQ,SAAS,QAA8B,WAAW;CACxF,OAAO,kBAAkB,MAAM,OAAO,YAAY;EAChD,MAAM,QAAQ,UAAU,YAAY,KAAK,SAAS,IAAI,QAAQ,WAAW,KAAK;EAE9E,IAAI,CAAC,OAAO,OAAO,MAAM,IAAI,KAAK;EAElC,OAAO,QAAQ,KAAK;CACtB,CAAC;AACH"}
@@ -71,6 +71,17 @@ function devLogHMR(file, dependents, durationMs) {
71
71
  const durationInfo = durationMs !== void 0 ? colors.dim(` (${durationMs}ms)`) : "";
72
72
  console.log(`${timestamp()} 🔥 ${colors.green("hmr update")} ${colors.dim(relativePath)}${depInfo}${durationInfo}`);
73
73
  }
74
+ function devLogTimings(timings) {
75
+ const phase = (label, ms) => `${colors.dim(label)} ${colors.dim(`${Math.round(ms)}ms`)}`;
76
+ const line = [
77
+ phase("watcher", timings.watcherSettleMs),
78
+ phase("debounce", timings.debounceWaitMs),
79
+ phase("graph", timings.moduleGraphInvalidationMs),
80
+ phase("reimport", timings.reimportMs),
81
+ phase("connectors", timings.connectorRestartMs)
82
+ ].join(colors.dim(" · "));
83
+ console.log(`${timestamp()} ${colors.dim("⏱")} ${line}`);
84
+ }
74
85
  function devLogSection(title) {
75
86
  console.log(`\n${timestamp()} ${colors.bold(colors.cyan(title))}`);
76
87
  }
@@ -106,5 +117,5 @@ function formatModuleNotFoundError(error, suggestions) {
106
117
  const devServeLog = devLog;
107
118
 
108
119
  //#endregion
109
- export { devLogDim, devLogError, devLogHMR, devLogInfo, devLogSection, devLogSuccess, devLogWarn, devServeLog, formatModuleNotFoundError };
120
+ export { devLogDim, devLogError, devLogHMR, devLogInfo, devLogSection, devLogSuccess, devLogTimings, devLogWarn, devServeLog, formatModuleNotFoundError };
110
121
  //# sourceMappingURL=dev-logger.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dev-logger.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/dev-logger.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport dayjs from \"dayjs\";\nimport { Path } from \"../utils/normalized-path\";\n\n/**\n * Dev server logger — Vite-style formatting helpers.\n */\n\nfunction timestamp(): string {\n return colors.dim(`${dayjs().format(\"HH:mm:ss A\")}`);\n}\n\nexport function devLog(message: string) {\n console.log(`${timestamp()} ${message}`);\n}\n\nexport function devLogSuccess(message: string) {\n console.log(`${timestamp()} ${colors.green(\"✓\")} ${colors.green(message)}`);\n}\n\n/**\n * Colourise a stack trace so the eye lands on *your* code.\n *\n * - Error header (`ReferenceError: x is not defined`) → bold red.\n * - Frames in project `src/` → highlighted: a green `›` pointer, yellow\n * function name, cyan relative path, dim `:line:col`. These are almost\n * always where the bug is.\n * - Framework (`@warlock.js`), `node_modules`, and `node:` internal frames\n * → dimmed and relativised. Still there for context, just out of the way.\n *\n * Source maps are enabled in dev, so the paths/lines here are already the\n * original `.ts` locations — this only changes how they're painted.\n */\nexport function formatErrorStack(stack: string): string {\n const frame = /^(\\s*)at (.+?) \\((.+):(\\d+):(\\d+)\\)$/;\n const bareFrame = /^(\\s*)at (.+):(\\d+):(\\d+)$/;\n let headerDone = false;\n\n return stack\n .split(\"\\n\")\n .map((line) => {\n const withFn = line.match(frame);\n const bare = line.match(bareFrame);\n\n if (!withFn && !bare) {\n // Header line(s) before the first frame.\n const painted = headerDone ? colors.dim(line) : colors.bold(colors.red(line));\n return painted;\n }\n\n headerDone = true;\n\n // Every read here is defaulted rather than asserted, and the reason is\n // what this function IS: a stack-trace formatter. If it throws while\n // formatting, it throws INSIDE error reporting — and what the developer\n // then sees is this function's failure instead of the error they were\n // actually chasing. An unreadable frame should degrade to a blank field,\n // never take the report down with it (canon `8d3c13a8`: every fatal\n // needs an unconditional floor).\n const fn = (withFn ? withFn[2] : \"\") ?? \"\";\n const file = (withFn ? withFn[3] : bare?.[2]) ?? \"\";\n const lineNo = (withFn ? withFn[4] : bare?.[3]) ?? \"\";\n const col = (withFn ? withFn[5] : bare?.[4]) ?? \"\";\n\n const isNodeInternal = file.startsWith(\"node:\");\n const isDep = file.includes(\"node_modules\");\n const isFramework = /[\\\\/]@warlock\\.js[\\\\/]/.test(file);\n const isUserCode = !isNodeInternal && !isDep && !isFramework;\n\n const rel = isNodeInternal ? file : Path.toRelative(file);\n const loc = `:${lineNo}:${col}`;\n\n if (isUserCode) {\n return (\n ` ${colors.green(\"›\")} ${colors.dim(\"at\")} ` +\n `${colors.yellow(fn || \"<anonymous>\")} ` +\n `${colors.cyan(rel)}${colors.dim(loc)}`\n );\n }\n\n const label = fn ? `at ${fn} ${rel}${loc}` : `at ${rel}${loc}`;\n return ` ${colors.dim(label)}`;\n })\n .join(\"\\n\");\n}\n\nexport function devLogError(message: string, error?: any) {\n console.log(`${timestamp()} ${colors.red(\"✗\")} ${colors.red(message)}`);\n if (error?.stack) console.log(formatErrorStack(error.stack));\n}\n\nexport function devLogWarn(message: string) {\n console.log(`${timestamp()} ${colors.yellow(\"⚠\")} ${colors.yellow(message)}`);\n}\n\nexport function devLogInfo(message: string) {\n console.log(`${timestamp()} ${colors.cyan(message)}`);\n}\n\nexport function devLogDim(message: string) {\n console.log(`${timestamp()} ${colors.dim(message)}`);\n}\n\nexport function devLogHMR(file: string, dependents?: number, durationMs?: number) {\n const relativePath = Path.toRelative(file);\n const depInfo = dependents\n ? colors.dim(` +${dependents} module${dependents > 1 ? \"s\" : \"\"}`)\n : \"\";\n const durationInfo = durationMs !== undefined ? colors.dim(` (${durationMs}ms)`) : \"\";\n console.log(\n `${timestamp()} 🔥 ${colors.green(\"hmr update\")} ${colors.dim(relativePath)}${depInfo}${durationInfo}`,\n );\n}\n\nexport function devLogConfig(file: string, connectors?: string[]) {\n const relativePath = Path.toRelative(file);\n const connectorInfo =\n connectors && connectors.length > 0 ? colors.dim(` → restarting ${connectors.join(\", \")}`) : \"\";\n console.log(\n `${timestamp()} ${colors.cyan(\"config reload\")} ${colors.dim(relativePath)}${connectorInfo}`,\n );\n}\n\nexport function devLogReady(message: string) {\n console.log(`\\n${timestamp()} ${colors.green(\"➜\")} ${colors.bold(message)}`);\n}\n\nexport function devLogSection(title: string) {\n console.log(`\\n${timestamp()} ${colors.bold(colors.cyan(title))}`);\n}\n\n/**\n * Format ERR_MODULE_NOT_FOUND so the displayed paths are relative to the\n * project root. The loader hook keeps source paths in the URL so we only\n * need to strip the absolute prefix — no cache-path translation any more.\n */\nexport function formatModuleNotFoundError(error: Error, suggestions?: string[]): string {\n const match = error.message.match(/Cannot find module '([^']+)' imported from '([^']+)'/);\n if (!match) return error.message;\n\n // Same rule as the frame formatter above: this renders a MODULE NOT FOUND\n // report, so a missing capture must degrade the message, not replace the\n // user's error with a crash inside the reporter.\n const [, rawModulePath, rawImporterPath] = match;\n const modulePath = rawModulePath ?? \"\";\n const importerPath = rawImporterPath ?? \"\";\n const lines: string[] = [\n \"\",\n `${colors.red(\"❌ MODULE NOT FOUND\")}`,\n \"\",\n `${colors.dim(\"Cannot find:\")} ${colors.cyan(Path.toRelative(modulePath))}`,\n \"\",\n `${colors.dim(\"Imported by:\")}`,\n ` ${colors.yellow(\"→\")} ${colors.white(Path.toRelative(importerPath))}`,\n ];\n\n if (suggestions && suggestions.length > 0) {\n lines.push(\"\");\n lines.push(`${colors.dim(\"Did you mean?\")}`);\n suggestions.forEach((s) => lines.push(` ${colors.cyan(\"→\")} ${colors.green(s)}`));\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/** @deprecated alias retained for older callers. Use `devLog` directly. */\nexport const devServeLog = devLog;\n"],"mappings":";;;;;;;;AAQA,SAAS,YAAoB;CAC3B,OAAO,OAAO,IAAI,GAAG,MAAM,CAAC,CAAC,OAAO,YAAY,GAAG;AACrD;AAEA,SAAgB,OAAO,SAAiB;CACtC,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,SAAS;AACzC;AAEA,SAAgB,cAAc,SAAiB;CAC7C,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,OAAO,MAAM,GAAG,EAAE,GAAG,OAAO,MAAM,OAAO,GAAG;AAC5E;;;;;;;;;;;;;;AAeA,SAAgB,iBAAiB,OAAuB;CACtD,MAAM,QAAQ;CACd,MAAM,YAAY;CAClB,IAAI,aAAa;CAEjB,OAAO,MACJ,MAAM,IAAI,CAAC,CACX,KAAK,SAAS;EACb,MAAM,SAAS,KAAK,MAAM,KAAK;EAC/B,MAAM,OAAO,KAAK,MAAM,SAAS;EAEjC,IAAI,CAAC,UAAU,CAAC,MAGd,OADgB,a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AG,EAAE,GAAG,OAAO,MAAM,CAAC,GAAG,CAAC;CACnF;CAEA,MAAM,KAAK,EAAE;CACb,OAAO,MAAM,KAAK,IAAI;AACxB;;AAGA,MAAa,cAAc"}
1
+ {"version":3,"file":"dev-logger.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/dev-logger.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport dayjs from \"dayjs\";\nimport { Path } from \"../utils/normalized-path\";\n\n/**\n * Dev server logger — Vite-style formatting helpers.\n */\n\nfunction timestamp(): string {\n return colors.dim(`${dayjs().format(\"HH:mm:ss A\")}`);\n}\n\nexport function devLog(message: string) {\n console.log(`${timestamp()} ${message}`);\n}\n\nexport function devLogSuccess(message: string) {\n console.log(`${timestamp()} ${colors.green(\"✓\")} ${colors.green(message)}`);\n}\n\n/**\n * Colourise a stack trace so the eye lands on *your* code.\n *\n * - Error header (`ReferenceError: x is not defined`) → bold red.\n * - Frames in project `src/` → highlighted: a green `›` pointer, yellow\n * function name, cyan relative path, dim `:line:col`. These are almost\n * always where the bug is.\n * - Framework (`@warlock.js`), `node_modules`, and `node:` internal frames\n * → dimmed and relativised. Still there for context, just out of the way.\n *\n * Source maps are enabled in dev, so the paths/lines here are already the\n * original `.ts` locations — this only changes how they're painted.\n */\nexport function formatErrorStack(stack: string): string {\n const frame = /^(\\s*)at (.+?) \\((.+):(\\d+):(\\d+)\\)$/;\n const bareFrame = /^(\\s*)at (.+):(\\d+):(\\d+)$/;\n let headerDone = false;\n\n return stack\n .split(\"\\n\")\n .map((line) => {\n const withFn = line.match(frame);\n const bare = line.match(bareFrame);\n\n if (!withFn && !bare) {\n // Header line(s) before the first frame.\n const painted = headerDone ? colors.dim(line) : colors.bold(colors.red(line));\n return painted;\n }\n\n headerDone = true;\n\n // Every read here is defaulted rather than asserted, and the reason is\n // what this function IS: a stack-trace formatter. If it throws while\n // formatting, it throws INSIDE error reporting — and what the developer\n // then sees is this function's failure instead of the error they were\n // actually chasing. An unreadable frame should degrade to a blank field,\n // never take the report down with it — every fatal needs an\n // unconditional floor.\n const fn = (withFn ? withFn[2] : \"\") ?? \"\";\n const file = (withFn ? withFn[3] : bare?.[2]) ?? \"\";\n const lineNo = (withFn ? withFn[4] : bare?.[3]) ?? \"\";\n const col = (withFn ? withFn[5] : bare?.[4]) ?? \"\";\n\n const isNodeInternal = file.startsWith(\"node:\");\n const isDep = file.includes(\"node_modules\");\n const isFramework = /[\\\\/]@warlock\\.js[\\\\/]/.test(file);\n const isUserCode = !isNodeInternal && !isDep && !isFramework;\n\n const rel = isNodeInternal ? file : Path.toRelative(file);\n const loc = `:${lineNo}:${col}`;\n\n if (isUserCode) {\n return (\n ` ${colors.green(\"›\")} ${colors.dim(\"at\")} ` +\n `${colors.yellow(fn || \"<anonymous>\")} ` +\n `${colors.cyan(rel)}${colors.dim(loc)}`\n );\n }\n\n const label = fn ? `at ${fn} ${rel}${loc}` : `at ${rel}${loc}`;\n return ` ${colors.dim(label)}`;\n })\n .join(\"\\n\");\n}\n\nexport function devLogError(message: string, error?: any) {\n console.log(`${timestamp()} ${colors.red(\"✗\")} ${colors.red(message)}`);\n if (error?.stack) console.log(formatErrorStack(error.stack));\n}\n\nexport function devLogWarn(message: string) {\n console.log(`${timestamp()} ${colors.yellow(\"⚠\")} ${colors.yellow(message)}`);\n}\n\nexport function devLogInfo(message: string) {\n console.log(`${timestamp()} ${colors.cyan(message)}`);\n}\n\nexport function devLogDim(message: string) {\n console.log(`${timestamp()} ${colors.dim(message)}`);\n}\n\nexport function devLogHMR(file: string, dependents?: number, durationMs?: number) {\n const relativePath = Path.toRelative(file);\n const depInfo = dependents\n ? colors.dim(` +${dependents} module${dependents > 1 ? \"s\" : \"\"}`)\n : \"\";\n const durationInfo = durationMs !== undefined ? colors.dim(` (${durationMs}ms)`) : \"\";\n console.log(\n `${timestamp()} 🔥 ${colors.green(\"hmr update\")} ${colors.dim(relativePath)}${depInfo}${durationInfo}`,\n );\n}\n\n/**\n * Per-phase breakdown for one hot reload, printed only when\n * `devServer.timings` is on. Phases run in this order: the watcher's\n * `awaitWriteFinish` settle wait, this handler's own debounce wait,\n * module-graph invalidation (version bumps), re-import of the changed\n * modules, and connector restart/rebind.\n */\nexport type ReloadPhaseTimings = {\n watcherSettleMs: number;\n debounceWaitMs: number;\n moduleGraphInvalidationMs: number;\n reimportMs: number;\n connectorRestartMs: number;\n};\n\nexport function devLogTimings(timings: ReloadPhaseTimings) {\n const phase = (label: string, ms: number) => `${colors.dim(label)} ${colors.dim(`${Math.round(ms)}ms`)}`;\n const line = [\n phase(\"watcher\", timings.watcherSettleMs),\n phase(\"debounce\", timings.debounceWaitMs),\n phase(\"graph\", timings.moduleGraphInvalidationMs),\n phase(\"reimport\", timings.reimportMs),\n phase(\"connectors\", timings.connectorRestartMs),\n ].join(colors.dim(\" · \"));\n console.log(`${timestamp()} ${colors.dim(\"⏱\")} ${line}`);\n}\n\nexport function devLogConfig(file: string, connectors?: string[]) {\n const relativePath = Path.toRelative(file);\n const connectorInfo =\n connectors && connectors.length > 0 ? colors.dim(` → restarting ${connectors.join(\", \")}`) : \"\";\n console.log(\n `${timestamp()} ${colors.cyan(\"config reload\")} ${colors.dim(relativePath)}${connectorInfo}`,\n );\n}\n\nexport function devLogReady(message: string) {\n console.log(`\\n${timestamp()} ${colors.green(\"➜\")} ${colors.bold(message)}`);\n}\n\nexport function devLogSection(title: string) {\n console.log(`\\n${timestamp()} ${colors.bold(colors.cyan(title))}`);\n}\n\n/**\n * Format ERR_MODULE_NOT_FOUND so the displayed paths are relative to the\n * project root. The loader hook keeps source paths in the URL so we only\n * need to strip the absolute prefix — no cache-path translation any more.\n */\nexport function formatModuleNotFoundError(error: Error, suggestions?: string[]): string {\n const match = error.message.match(/Cannot find module '([^']+)' imported from '([^']+)'/);\n if (!match) return error.message;\n\n // Same rule as the frame formatter above: this renders a MODULE NOT FOUND\n // report, so a missing capture must degrade the message, not replace the\n // user's error with a crash inside the reporter.\n const [, rawModulePath, rawImporterPath] = match;\n const modulePath = rawModulePath ?? \"\";\n const importerPath = rawImporterPath ?? \"\";\n const lines: string[] = [\n \"\",\n `${colors.red(\"❌ MODULE NOT FOUND\")}`,\n \"\",\n `${colors.dim(\"Cannot find:\")} ${colors.cyan(Path.toRelative(modulePath))}`,\n \"\",\n `${colors.dim(\"Imported by:\")}`,\n ` ${colors.yellow(\"→\")} ${colors.white(Path.toRelative(importerPath))}`,\n ];\n\n if (suggestions && suggestions.length > 0) {\n lines.push(\"\");\n lines.push(`${colors.dim(\"Did you mean?\")}`);\n suggestions.forEach((s) => lines.push(` ${colors.cyan(\"→\")} ${colors.green(s)}`));\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n/** @deprecated alias retained for older callers. Use `devLog` directly. */\nexport const devServeLog = devLog;\n"],"mappings":";;;;;;;;AAQA,SAAS,YAAoB;CAC3B,OAAO,OAAO,IAAI,GAAG,MAAM,CAAC,CAAC,OAAO,YAAY,GAAG;AACrD;AAEA,SAAgB,OAAO,SAAiB;CACtC,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,SAAS;AACzC;AAEA,SAAgB,cAAc,SAAiB;CAC7C,QAAQ,IAAI,GAAG,UAAU,EAAE,GAAG,OAAO,MAAM,GAAG,EAAE,GAAG,OAAO,MAAM,OAAO,GAAG;AAC5E;;;;;;;;;;;;;;AAeA,SAAgB,iBAAiB,OAAuB;CACtD,MAAM,QAAQ;CACd,MAAM,YAAY;CAClB,IAAI,aAAa;CAEjB,OAAO,MACJ,MAAM,IAAI,CAAC,CACX,KAAK,SAAS;EACb,MAAM,SAAS,KAAK,MAAM,KAAK;EAC/B,MAAM,OAAO,KAAK,MAAM,SAAS;EAEjC,IAAI,CAAC,UAAU,CAAC,MAGd,OADgB,aAAa,OAAO,IAAI,IAAI,IAAI,OAAO,KAAK,OAAO,IAAI,IAAI,CAAC;EAI9E,aAAa;EASb,MAAM,MAAM,SAAS,OAAO,KAAK,OAAO;EACxC,MAAM,QAAQ,SAAS,OAA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AK,WAAW,UAAU,CAAC;EACxE;EACA,GAAG,OAAO,IAAI,cAAc;EAC5B,KAAK,OAAO,OAAO,GAAG,EAAE,GAAG,OAAO,MAAM,KAAK,WAAW,YAAY,CAAC;CACvE;CAEA,IAAI,eAAe,YAAY,SAAS,GAAG;EACzC,MAAM,KAAK,EAAE;EACb,MAAM,KAAK,GAAG,OAAO,IAAI,eAAe,GAAG;EAC3C,YAAY,SAAS,MAAM,MAAM,KAAK,KAAK,OAAO,KAAK,GAAG,EAAE,GAAG,OAAO,MAAM,CAAC,GAAG,CAAC;CACnF;CAEA,MAAM,KAAK,EAAE;CACb,OAAO,MAAM,KAAK,IAAI;AACxB;;AAGA,MAAa,cAAc"}
@@ -87,7 +87,7 @@ var DevelopmentServer = class {
87
87
  if (batch.added.length + batch.changed.length + batch.deleted.length === 0) return;
88
88
  const codeFiles = [...batch.added, ...batch.changed].filter((p) => !isEnvPath(p) && p !== "warlock.config.ts");
89
89
  try {
90
- await this.layerExecutor.executeBatchReload(codeFiles, filesOrchestrator.getFiles(), batch.deleted, batch.changed);
90
+ await this.layerExecutor.executeBatchReload(codeFiles, filesOrchestrator.getFiles(), batch.deleted, batch.changed, batch.timings);
91
91
  typeGenerator.executeTypingsGenerator([...batch.added, ...batch.changed]);
92
92
  filesOrchestrator.checkHealth(batch);
93
93
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"development-server.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/development-server.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport events from \"@mongez/events\";\r\nimport { fileExistsAsync, unlinkAsync } from \"@warlock.js/fs\";\r\nimport { Application } from \"../application\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { warlockConfigManager } from \"../warlock-config\";\r\nimport { BootPreconditionError } from \"./boot-precondition-error\";\r\nimport { devLogInfo, devLogSection, devLogWarn, devServeLog } from \"./dev-logger\";\r\nimport { filesOrchestrator } from \"./files-orchestrator\";\r\nimport { MANIFEST_PATH } from \"./flags\";\r\nimport { LayerExecutor } from \"./layer-executor\";\r\nimport { printReadyBlock } from \"./ready-block\";\r\nimport { restartDevServer } from \"./restart-dev-server\";\r\nimport { devServerShortcuts } from \"./shortcuts\";\r\nimport type { StartDevServerOptions } from \"./start-development-server\";\r\nimport { typeGenerator } from \"./type-generator\";\r\n\r\ntype Batch = { added: string[]; changed: string[]; deleted: string[] };\r\n\r\n/**\r\n * Top-level coordinator for `warlock dev`. Wires the file orchestrator, the\r\n * connectors, and the layer executor together, and listens for the watcher's\r\n * batched events to drive HMR.\r\n */\r\nexport class DevelopmentServer {\r\n private layerExecutor?: LayerExecutor;\r\n private running = false;\r\n private readonly options: StartDevServerOptions;\r\n\r\n public constructor(options: StartDevServerOptions = {}) {\r\n this.options = options;\r\n devLogSection(\"Starting Development Server...\");\r\n }\r\n\r\n public async start(): Promise<void> {\r\n try {\r\n const startedAt = performance.now();\r\n\r\n // --fresh deletes the manifest so reconciliation re-parses every file\r\n // from disk. Transpile caching is owned by the loader hook (in-memory).\r\n if (this.options.fresh && (await fileExistsAsync(MANIFEST_PATH))) {\r\n await unlinkAsync(MANIFEST_PATH);\r\n devServeLog(colors.cyanBright(\"Cleared manifest (--fresh)\"));\r\n }\r\n\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n await filesOrchestrator.watchFiles();\r\n\r\n filesOrchestrator.specialFilesCollector.collect(filesOrchestrator.getFiles());\r\n\r\n this.setupEventListeners();\r\n\r\n // Decorator-driven registries (models, etc.) must be populated before\r\n // routes/services can resolve symbols by name.\r\n await this.autoDiscoverFiles();\r\n\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n\r\n // A rejecting validator (Application.onValidateBoot) must abort boot\r\n // before late-phase connectors bind a port — this is what makes the\r\n // hook actually prevent serving instead of merely being defined.\r\n //\r\n // Wrapped and re-thrown as a BootPreconditionError: a rejected\r\n // validator is, by definition, a precondition whose cause cannot\r\n // change because the worker tried again — the supervisor must not\r\n // restart into the same rejection. See boot-precondition-error.ts.\r\n try {\r\n await Application.runStartupValidators();\r\n } catch (error) {\r\n throw new BootPreconditionError((error as Error).message, { cause: error });\r\n }\r\n\r\n // Late-phase connectors (http, socket) bind after app code has\r\n // registered routes/listeners.\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\r\n\r\n this.layerExecutor = new LayerExecutor(\r\n filesOrchestrator.getDependencyGraph(),\r\n filesOrchestrator.specialFilesCollector,\r\n filesOrchestrator.moduleLoader,\r\n (absolutePath) => filesOrchestrator.bumpVersion(absolutePath),\r\n () => filesOrchestrator.flushVersionBumps(),\r\n );\r\n\r\n this.running = true;\r\n\r\n const duration = performance.now() - startedAt;\r\n\r\n // App modules are loaded and both connector phases are active — signal a\r\n // complete boot so `Application.onceBooted(...)` listeners fire.\r\n Application.markBooted({\r\n environment: Application.environment,\r\n runtimeStrategy: Application.runtimeStrategy,\r\n bootDurationMs: duration,\r\n });\r\n\r\n // ONE block, AFTER the boot it summarises, replacing the scattered\r\n // \"N route(s) registered\" / \"Server ready at …\" / \"ready in …\" lines that\r\n // used to arrive in completion order. Warnings logged during boot sit\r\n // above it and stay there — see `ready-block.ts`.\r\n printReadyBlock(duration);\r\n\r\n // Precedence: explicit CLI option > devServer.* config > default.\r\n const devServerConfig = await warlockConfigManager.get(\"devServer\");\r\n const generateTypings =\r\n this.options.generateTypings ?? devServerConfig?.generateTypings ?? true;\r\n const healthCheckers = this.options.healthCheckers ?? devServerConfig?.healthCheckers ?? true;\r\n\r\n if (generateTypings) typeGenerator.executeGenerateAllCommand();\r\n\r\n if (healthCheckers) {\r\n filesOrchestrator.startCheckingHealth(healthCheckers === true ? undefined : healthCheckers);\r\n }\r\n } catch (error) {\r\n devServeLog(colors.redBright(`Failed to start Development Server: ${error}`));\r\n await this.shutdown();\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Eagerly import files whose decorators populate global registries so any\r\n * symbol-by-name resolution later in boot finds them.\r\n */\r\n private async autoDiscoverFiles(): Promise<void> {\r\n const discoveryTypes = [\"model\"] as const;\r\n for (const file of filesOrchestrator.files.values()) {\r\n if (file.type && (discoveryTypes as readonly string[]).includes(file.type)) {\r\n await filesOrchestrator.moduleLoader.loadModule(file, file.type);\r\n }\r\n }\r\n }\r\n\r\n private setupEventListeners(): void {\r\n events.on(\"dev-server:batch-complete\", (batch: Batch) => this.handleBatchComplete(batch));\r\n }\r\n\r\n private async handleBatchComplete(batch: Batch): Promise<void> {\r\n if (!this.running || !this.layerExecutor) return;\r\n\r\n // warlock.config.ts holds settings read at boot (CLI commands, build\r\n // options, watch patterns, scheduled jobs) and .env feeds every config\r\n // that reads it. Neither can be hot-reloaded without leaving running\r\n // services configured with stale values, so the only honest response is\r\n // a full restart.\r\n const restartTrigger = this.findRestartTrigger(batch);\r\n\r\n if (restartTrigger) {\r\n // On success this never comes back — the process exits and the\r\n // supervisor replaces it. Reaching the next line means the restart was\r\n // declined by config or wasn't possible, so we fall through and still\r\n // hot-reload whatever ordinary code shared the batch.\r\n await this.restartForConfigChange(restartTrigger);\r\n }\r\n\r\n // No-op saves (an editor that fsyncs without a content write) are already\r\n // filtered upstream by the file hash in FileEventHandler, so batch.changed\r\n // only contains genuinely-changed paths by the time it reaches here.\r\n\r\n const total = batch.added.length + batch.changed.length + batch.deleted.length;\r\n if (total === 0) return;\r\n\r\n // Boot-time files still ride along in `changed` when a restart was\r\n // declined (`restartOnConfigChange: false`) or wasn't possible — they are\r\n // never hot-reloaded, so keep them out of the reload set either way.\r\n const codeFiles = [...batch.added, ...batch.changed].filter(\r\n (p) => !isEnvPath(p) && p !== \"warlock.config.ts\",\r\n );\r\n\r\n try {\r\n await this.layerExecutor.executeBatchReload(\r\n codeFiles,\r\n filesOrchestrator.getFiles(),\r\n batch.deleted,\r\n batch.changed,\r\n );\r\n\r\n typeGenerator.executeTypingsGenerator([...batch.added, ...batch.changed]);\r\n\r\n filesOrchestrator.checkHealth(batch);\r\n } catch (error) {\r\n devServeLog(colors.redBright(`Failed to execute batch reload: ${error}`));\r\n }\r\n }\r\n\r\n /**\r\n * The boot-time file in this batch that can only be applied by restarting,\r\n * or `undefined` when the batch is ordinary application code.\r\n */\r\n private findRestartTrigger(batch: Batch): string | undefined {\r\n if (batch.changed.includes(\"warlock.config.ts\")) {\r\n return \"warlock.config.ts\";\r\n }\r\n\r\n return [...batch.added, ...batch.changed].find(isEnvPath);\r\n }\r\n\r\n /**\r\n * Restart so a changed boot-time file actually takes effect.\r\n *\r\n * Opt out with `devServer.restartOnConfigChange: false` and the old\r\n * behaviour returns: a warning telling you to restart yourself. If the\r\n * restart can't be performed at all (no supervisor, a shutdown that threw),\r\n * `restartDevServer` reports it and we fall back to the same warning rather\r\n * than leaving the server running against config it isn't using.\r\n */\r\n private async restartForConfigChange(file: string): Promise<void> {\r\n const devServerConfig = await warlockConfigManager.get(\"devServer\");\r\n\r\n if (devServerConfig?.restartOnConfigChange === false) {\r\n devLogWarn(`${file} changed — restart the dev server to apply.`);\r\n return;\r\n }\r\n\r\n devLogInfo(`${file} changed — restarting to apply.`);\r\n\r\n const restarted = await restartDevServer(this);\r\n\r\n if (!restarted) {\r\n devLogWarn(`${file} changed — restart the dev server to apply.`);\r\n }\r\n }\r\n\r\n public async shutdown(): Promise<void> {\r\n // Always hand the terminal back, even on a repeat/no-op shutdown — a\r\n // process that exits while stdin is still in raw mode leaves the user's\r\n // shell without line editing or Ctrl+C.\r\n devServerShortcuts.release();\r\n\r\n if (!this.running) return;\r\n devServeLog(colors.redBright(\"Shutting down Development Server...\"));\r\n this.running = false;\r\n await connectorsManager.shutdown();\r\n devServeLog(colors.greenBright(\"Development Server stopped\"));\r\n }\r\n\r\n public isRunning(): boolean {\r\n return this.running;\r\n }\r\n}\r\n\r\nfunction isEnvPath(path: string): boolean {\r\n const basename = path.split(\"/\").pop() ?? path;\r\n return basename === \".env\" || basename.startsWith(\".env.\");\r\n}\r\n"],"mappings":";;;;;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KAAK,SAAS;CAC1D;;;;;;;;;;CAWA,MAAc,uBAAuB,MAA6B;EAGhE,KAAI,MAF0B,qBAAqB,IAAI,WAAW,EAE/C,EAAE,0BAA0B,OAAO;GACpD,WAAW,GAAG,KAAK,4CAA4C;GAC/D;EACF;EAEA,WAAW,GAAG,KAAK,gCAAgC;EAInD,IAAI,CAAC,MAFmB,iBAAiB,IAAI,GAG3C,WAAW,GAAG,KAAK,4CAA4C;CAEnE;CAEA,MAAa,WAA0B;EAIrC,mBAAmB,QAAQ;EAE3B,IAAI,CAAC,KAAK,SAAS;EACnB,YAAY,OAAO,UAAU,qCAAqC,CAAC;EACnE,KAAK,UAAU;EACf,MAAM,kBAAkB,SAAS;EACjC,YAAY,OAAO,YAAY,4BAA4B,CAAC;CAC9D;CAEA,AAAO,YAAqB;EAC1B,OAAO,KAAK;CACd;AACF;AAEA,SAAS,UAAU,MAAuB;CACxC,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC1C,OAAO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D"}
1
+ {"version":3,"file":"development-server.mjs","names":[],"sources":["../../../../../../../core/src/dev-server/development-server.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport events from \"@mongez/events\";\r\nimport { fileExistsAsync, unlinkAsync } from \"@warlock.js/fs\";\r\nimport { Application } from \"../application\";\r\nimport { connectorsManager } from \"../connectors/connectors-manager\";\r\nimport { ConnectorLifecyclePhase } from \"../connectors/types\";\r\nimport { warlockConfigManager } from \"../warlock-config\";\r\nimport { BootPreconditionError } from \"./boot-precondition-error\";\r\nimport { devLogInfo, devLogSection, devLogWarn, devServeLog } from \"./dev-logger\";\r\nimport { filesOrchestrator } from \"./files-orchestrator\";\r\nimport { MANIFEST_PATH } from \"./flags\";\r\nimport type { IncomingReloadTimings } from \"./layer-executor\";\r\nimport { LayerExecutor } from \"./layer-executor\";\r\nimport { printReadyBlock } from \"./ready-block\";\r\nimport { restartDevServer } from \"./restart-dev-server\";\r\nimport { devServerShortcuts } from \"./shortcuts\";\r\nimport type { StartDevServerOptions } from \"./start-development-server\";\r\nimport { typeGenerator } from \"./type-generator\";\r\n\r\ntype Batch = {\r\n added: string[];\r\n changed: string[];\r\n deleted: string[];\r\n timings?: IncomingReloadTimings;\r\n};\r\n\r\n/**\r\n * Top-level coordinator for `warlock dev`. Wires the file orchestrator, the\r\n * connectors, and the layer executor together, and listens for the watcher's\r\n * batched events to drive HMR.\r\n */\r\nexport class DevelopmentServer {\r\n private layerExecutor?: LayerExecutor;\r\n private running = false;\r\n private readonly options: StartDevServerOptions;\r\n\r\n public constructor(options: StartDevServerOptions = {}) {\r\n this.options = options;\r\n devLogSection(\"Starting Development Server...\");\r\n }\r\n\r\n public async start(): Promise<void> {\r\n try {\r\n const startedAt = performance.now();\r\n\r\n // --fresh deletes the manifest so reconciliation re-parses every file\r\n // from disk. Transpile caching is owned by the loader hook (in-memory).\r\n if (this.options.fresh && (await fileExistsAsync(MANIFEST_PATH))) {\r\n await unlinkAsync(MANIFEST_PATH);\r\n devServeLog(colors.cyanBright(\"Cleared manifest (--fresh)\"));\r\n }\r\n\r\n await filesOrchestrator.init();\r\n await filesOrchestrator.initializeAll();\r\n await filesOrchestrator.watchFiles();\r\n\r\n filesOrchestrator.specialFilesCollector.collect(filesOrchestrator.getFiles());\r\n\r\n this.setupEventListeners();\r\n\r\n // Decorator-driven registries (models, etc.) must be populated before\r\n // routes/services can resolve symbols by name.\r\n await this.autoDiscoverFiles();\r\n\r\n await filesOrchestrator.moduleLoader.loadAll();\r\n\r\n // A rejecting validator (Application.onValidateBoot) must abort boot\r\n // before late-phase connectors bind a port — this is what makes the\r\n // hook actually prevent serving instead of merely being defined.\r\n //\r\n // Wrapped and re-thrown as a BootPreconditionError: a rejected\r\n // validator is, by definition, a precondition whose cause cannot\r\n // change because the worker tried again — the supervisor must not\r\n // restart into the same rejection. See boot-precondition-error.ts.\r\n try {\r\n await Application.runStartupValidators();\r\n } catch (error) {\r\n throw new BootPreconditionError((error as Error).message, { cause: error });\r\n }\r\n\r\n // Late-phase connectors (http, socket) bind after app code has\r\n // registered routes/listeners.\r\n await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\r\n\r\n this.layerExecutor = new LayerExecutor(\r\n filesOrchestrator.getDependencyGraph(),\r\n filesOrchestrator.specialFilesCollector,\r\n filesOrchestrator.moduleLoader,\r\n (absolutePath) => filesOrchestrator.bumpVersion(absolutePath),\r\n () => filesOrchestrator.flushVersionBumps(),\r\n );\r\n\r\n this.running = true;\r\n\r\n const duration = performance.now() - startedAt;\r\n\r\n // App modules are loaded and both connector phases are active — signal a\r\n // complete boot so `Application.onceBooted(...)` listeners fire.\r\n Application.markBooted({\r\n environment: Application.environment,\r\n runtimeStrategy: Application.runtimeStrategy,\r\n bootDurationMs: duration,\r\n });\r\n\r\n // ONE block, AFTER the boot it summarises, replacing the scattered\r\n // \"N route(s) registered\" / \"Server ready at …\" / \"ready in …\" lines that\r\n // used to arrive in completion order. Warnings logged during boot sit\r\n // above it and stay there — see `ready-block.ts`.\r\n printReadyBlock(duration);\r\n\r\n // Precedence: explicit CLI option > devServer.* config > default.\r\n const devServerConfig = await warlockConfigManager.get(\"devServer\");\r\n const generateTypings =\r\n this.options.generateTypings ?? devServerConfig?.generateTypings ?? true;\r\n const healthCheckers = this.options.healthCheckers ?? devServerConfig?.healthCheckers ?? true;\r\n\r\n if (generateTypings) typeGenerator.executeGenerateAllCommand();\r\n\r\n if (healthCheckers) {\r\n filesOrchestrator.startCheckingHealth(healthCheckers === true ? undefined : healthCheckers);\r\n }\r\n } catch (error) {\r\n devServeLog(colors.redBright(`Failed to start Development Server: ${error}`));\r\n await this.shutdown();\r\n throw error;\r\n }\r\n }\r\n\r\n /**\r\n * Eagerly import files whose decorators populate global registries so any\r\n * symbol-by-name resolution later in boot finds them.\r\n */\r\n private async autoDiscoverFiles(): Promise<void> {\r\n const discoveryTypes = [\"model\"] as const;\r\n for (const file of filesOrchestrator.files.values()) {\r\n if (file.type && (discoveryTypes as readonly string[]).includes(file.type)) {\r\n await filesOrchestrator.moduleLoader.loadModule(file, file.type);\r\n }\r\n }\r\n }\r\n\r\n private setupEventListeners(): void {\r\n events.on(\"dev-server:batch-complete\", (batch: Batch) => this.handleBatchComplete(batch));\r\n }\r\n\r\n private async handleBatchComplete(batch: Batch): Promise<void> {\r\n if (!this.running || !this.layerExecutor) return;\r\n\r\n // warlock.config.ts holds settings read at boot (CLI commands, build\r\n // options, watch patterns, scheduled jobs) and .env feeds every config\r\n // that reads it. Neither can be hot-reloaded without leaving running\r\n // services configured with stale values, so the only honest response is\r\n // a full restart.\r\n const restartTrigger = this.findRestartTrigger(batch);\r\n\r\n if (restartTrigger) {\r\n // On success this never comes back — the process exits and the\r\n // supervisor replaces it. Reaching the next line means the restart was\r\n // declined by config or wasn't possible, so we fall through and still\r\n // hot-reload whatever ordinary code shared the batch.\r\n await this.restartForConfigChange(restartTrigger);\r\n }\r\n\r\n // No-op saves (an editor that fsyncs without a content write) are already\r\n // filtered upstream by the file hash in FileEventHandler, so batch.changed\r\n // only contains genuinely-changed paths by the time it reaches here.\r\n\r\n const total = batch.added.length + batch.changed.length + batch.deleted.length;\r\n if (total === 0) return;\r\n\r\n // Boot-time files still ride along in `changed` when a restart was\r\n // declined (`restartOnConfigChange: false`) or wasn't possible — they are\r\n // never hot-reloaded, so keep them out of the reload set either way.\r\n const codeFiles = [...batch.added, ...batch.changed].filter(\r\n (p) => !isEnvPath(p) && p !== \"warlock.config.ts\",\r\n );\r\n\r\n try {\r\n await this.layerExecutor.executeBatchReload(\r\n codeFiles,\r\n filesOrchestrator.getFiles(),\r\n batch.deleted,\r\n batch.changed,\r\n batch.timings,\r\n );\r\n\r\n typeGenerator.executeTypingsGenerator([...batch.added, ...batch.changed]);\r\n\r\n filesOrchestrator.checkHealth(batch);\r\n } catch (error) {\r\n devServeLog(colors.redBright(`Failed to execute batch reload: ${error}`));\r\n }\r\n }\r\n\r\n /**\r\n * The boot-time file in this batch that can only be applied by restarting,\r\n * or `undefined` when the batch is ordinary application code.\r\n */\r\n private findRestartTrigger(batch: Batch): string | undefined {\r\n if (batch.changed.includes(\"warlock.config.ts\")) {\r\n return \"warlock.config.ts\";\r\n }\r\n\r\n return [...batch.added, ...batch.changed].find(isEnvPath);\r\n }\r\n\r\n /**\r\n * Restart so a changed boot-time file actually takes effect.\r\n *\r\n * Opt out with `devServer.restartOnConfigChange: false` and the old\r\n * behaviour returns: a warning telling you to restart yourself. If the\r\n * restart can't be performed at all (no supervisor, a shutdown that threw),\r\n * `restartDevServer` reports it and we fall back to the same warning rather\r\n * than leaving the server running against config it isn't using.\r\n */\r\n private async restartForConfigChange(file: string): Promise<void> {\r\n const devServerConfig = await warlockConfigManager.get(\"devServer\");\r\n\r\n if (devServerConfig?.restartOnConfigChange === false) {\r\n devLogWarn(`${file} changed — restart the dev server to apply.`);\r\n return;\r\n }\r\n\r\n devLogInfo(`${file} changed — restarting to apply.`);\r\n\r\n const restarted = await restartDevServer(this);\r\n\r\n if (!restarted) {\r\n devLogWarn(`${file} changed — restart the dev server to apply.`);\r\n }\r\n }\r\n\r\n public async shutdown(): Promise<void> {\r\n // Always hand the terminal back, even on a repeat/no-op shutdown — a\r\n // process that exits while stdin is still in raw mode leaves the user's\r\n // shell without line editing or Ctrl+C.\r\n devServerShortcuts.release();\r\n\r\n if (!this.running) return;\r\n devServeLog(colors.redBright(\"Shutting down Development Server...\"));\r\n this.running = false;\r\n await connectorsManager.shutdown();\r\n devServeLog(colors.greenBright(\"Development Server stopped\"));\r\n }\r\n\r\n public isRunning(): boolean {\r\n return this.running;\r\n }\r\n}\r\n\r\nfunction isEnvPath(path: string): boolean {\r\n const basename = path.split(\"/\").pop() ?? path;\r\n return basename === \".env\" || basename.startsWith(\".env.\");\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,oBAAb,MAA+B;CAK7B,AAAO,YAAY,UAAiC,CAAC,GA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B,qBAAqB,IAAI,WAAW,EAE/C,EAAE,0BAA0B,OAAO;GACpD,WAAW,GAAG,KAAK,4CAA4C;GAC/D;EACF;EAEA,WAAW,GAAG,KAAK,gCAAgC;EAInD,IAAI,CAAC,MAFmB,iBAAiB,IAAI,GAG3C,WAAW,GAAG,KAAK,4CAA4C;CAEnE;CAEA,MAAa,WAA0B;EAIrC,mBAAmB,QAAQ;EAE3B,IAAI,CAAC,KAAK,SAAS;EACnB,YAAY,OAAO,UAAU,qCAAqC,CAAC;EACnE,KAAK,UAAU;EACf,MAAM,kBAAkB,SAAS;EACjC,YAAY,OAAO,YAAY,4BAA4B,CAAC;CAC9D;CAEA,AAAO,YAAqB;EAC1B,OAAO,KAAK;CACd;AACF;AAEA,SAAS,UAAU,MAAuB;CACxC,MAAM,WAAW,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;CAC1C,OAAO,aAAa,UAAU,SAAS,WAAW,OAAO;AAC3D"}
@@ -1,11 +1,14 @@
1
1
  import { Path } from "../utils/normalized-path.mjs";
2
2
  import { devLogSuccess } from "./dev-logger.mjs";
3
- import "./flags.mjs";
3
+ import { isTimingsEnabled } from "./flags.mjs";
4
4
  import { clearFileExistsCache } from "./parse-imports.mjs";
5
- import { debounce } from "@mongez/reinforcements";
6
5
  import events from "@mongez/events";
7
6
 
8
7
  //#region ../core/src/dev-server/file-event-handler.ts
8
+ /** Lets an isolated editor save reach HMR without the former fixed 50ms delay. */
9
+ const ISOLATED_SAVE_QUIET_WINDOW_MS = 12;
10
+ /** Bounds a sustained formatter or checkout stream so it cannot postpone HMR forever. */
11
+ const BATCH_MAX_WAIT_MS = 60;
9
12
  /**
10
13
  * Receives raw watcher events and processes them in a single debounced batch.
11
14
  * Order within a batch: adds → changes → deletes, so changes can reference
@@ -20,19 +23,48 @@ var FileEventHandler = class {
20
23
  this.pendingChanges = /* @__PURE__ */ new Set();
21
24
  this.pendingAdds = /* @__PURE__ */ new Set();
22
25
  this.pendingDeletes = /* @__PURE__ */ new Set();
23
- this.processPendingEvents = debounce(() => this.processBatch(), 50);
24
26
  }
25
- handleFileChange(absolutePath) {
27
+ handleFileChange(absolutePath, settleMs) {
28
+ this.recordTimingStart(settleMs);
26
29
  this.pendingChanges.add(Path.toRelative(absolutePath));
27
- this.processPendingEvents();
30
+ this.schedulePendingEvents();
28
31
  }
29
- handleFileAdd(absolutePath) {
32
+ handleFileAdd(absolutePath, settleMs) {
33
+ this.recordTimingStart(settleMs);
30
34
  this.pendingAdds.add(Path.toRelative(absolutePath));
31
- this.processPendingEvents();
35
+ this.schedulePendingEvents();
32
36
  }
33
- handleFileDelete(absolutePath) {
37
+ handleFileDelete(absolutePath, settleMs) {
38
+ this.recordTimingStart(settleMs);
34
39
  this.pendingDeletes.add(Path.toRelative(absolutePath));
35
- this.processPendingEvents();
40
+ this.schedulePendingEvents();
41
+ }
42
+ schedulePendingEvents() {
43
+ if (this.debounceTimer !== void 0) clearTimeout(this.debounceTimer);
44
+ this.debounceTimer = setTimeout(() => this.flushPendingEvents(), ISOLATED_SAVE_QUIET_WINDOW_MS);
45
+ if (this.maxWaitTimer === void 0) this.maxWaitTimer = setTimeout(() => this.flushPendingEvents(), BATCH_MAX_WAIT_MS);
46
+ }
47
+ flushPendingEvents() {
48
+ if (this.debounceTimer !== void 0) {
49
+ clearTimeout(this.debounceTimer);
50
+ this.debounceTimer = void 0;
51
+ }
52
+ if (this.maxWaitTimer !== void 0) {
53
+ clearTimeout(this.maxWaitTimer);
54
+ this.maxWaitTimer = void 0;
55
+ }
56
+ this.processBatch();
57
+ }
58
+ /**
59
+ * Mark the debounce-wait phase start on the first event of a batch, and
60
+ * track the slowest watcher-settle duration seen this batch. `settleMs`
61
+ * only arrives when `devServer.timings` is on (see `FilesWatcher`), so
62
+ * this is a no-op past the cheap `performance.now()` call when it's off.
63
+ */
64
+ recordTimingStart(settleMs) {
65
+ if (this.batchStartedAt === void 0) this.batchStartedAt = performance.now();
66
+ if (settleMs === void 0) return;
67
+ this.watcherSettleMs = this.watcherSettleMs === void 0 ? settleMs : Math.max(this.watcherSettleMs, settleMs);
36
68
  }
37
69
  async processBatch() {
38
70
  const changes = Array.from(this.pendingChanges);
@@ -41,24 +73,33 @@ var FileEventHandler = class {
41
73
  this.pendingChanges.clear();
42
74
  this.pendingAdds.clear();
43
75
  this.pendingDeletes.clear();
76
+ const debounceWaitMs = this.batchStartedAt !== void 0 ? performance.now() - this.batchStartedAt : void 0;
77
+ const watcherSettleMs = this.watcherSettleMs;
78
+ this.batchStartedAt = void 0;
79
+ this.watcherSettleMs = void 0;
44
80
  if (changes.length === 0 && adds.length === 0 && deletes.length === 0) return;
45
81
  const externalChanges = changes.filter(isExternalPath);
82
+ const externalAdds = adds.filter(isExternalPath);
46
83
  const codeChanges = changes.filter((p) => !isExternalPath(p));
47
84
  const codeAdds = adds.filter((p) => !isExternalPath(p));
48
85
  if (codeAdds.length + codeChanges.length > 1) {
49
86
  await new Promise((resolve) => setTimeout(resolve, 500));
50
87
  clearFileExistsCache();
51
88
  }
52
- await this.processBatchAdds(codeAdds);
89
+ const { added: addedCodePaths, vanished } = await this.processBatchAdds(codeAdds);
53
90
  const changedCodePaths = await this.processBatchChanges(codeChanges);
54
91
  await this.processBatchDeletes(deletes);
55
92
  this.fileOperations.updateFileDependents();
56
93
  this.fileOperations.syncFilesToManifest();
57
94
  await this.manifest.save();
58
95
  events.trigger("dev-server:batch-complete", {
59
- added: adds,
96
+ added: [...externalAdds, ...addedCodePaths],
60
97
  changed: [...externalChanges, ...changedCodePaths],
61
- deleted: deletes
98
+ deleted: [...deletes, ...vanished],
99
+ timings: isTimingsEnabled() ? {
100
+ watcherSettleMs: watcherSettleMs ?? 0,
101
+ debounceWaitMs: debounceWaitMs ?? 0
102
+ } : void 0
62
103
  });
63
104
  }
64
105
  /**
@@ -75,15 +116,33 @@ var FileEventHandler = class {
75
116
  });
76
117
  return changed;
77
118
  }
119
+ /**
120
+ * Process pending add events. Returns the paths that genuinely became
121
+ * available (`added`) separately from paths that no longer existed by the
122
+ * time they were read/stat'd (`vanished`) — the latter is a rename or move
123
+ * racing the filesystem, not a failure, so it is unwound as a deletion
124
+ * instead of being logged as an error.
125
+ */
78
126
  async processBatchAdds(relativePaths) {
127
+ const added = [];
128
+ const vanished = [];
79
129
  await runInBatches(relativePaths, 500, async (path) => {
80
130
  try {
81
- await this.fileOperations.addFile(path);
131
+ if ((await this.fileOperations.addFile(path)).state === "deleted") {
132
+ await this.fileOperations.deleteFile(path);
133
+ vanished.push(path);
134
+ return;
135
+ }
136
+ added.push(path);
82
137
  devLogSuccess(`Added file: ${path}`);
83
138
  } catch (error) {
84
139
  console.error(`Failed to add file ${path}:`, error);
85
140
  }
86
141
  });
142
+ return {
143
+ added,
144
+ vanished
145
+ };
87
146
  }
88
147
  async processBatchDeletes(relativePaths) {
89
148
  for (const relativePath of relativePaths) {