@warlock.js/core 5.19.1 → 5.21.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 (378) hide show
  1. package/CHANGELOG.md +1136 -1073
  2. package/esm/benchmark/benchmark.mjs +34 -25
  3. package/esm/benchmark/benchmark.mjs.map +1 -1
  4. package/esm/benchmark/profiler.d.mts.map +1 -1
  5. package/esm/benchmark/profiler.mjs +8 -3
  6. package/esm/benchmark/profiler.mjs.map +1 -1
  7. package/esm/bootstrap.d.mts.map +1 -1
  8. package/esm/bootstrap.mjs +3 -0
  9. package/esm/bootstrap.mjs.map +1 -1
  10. package/esm/cache/database-cache-driver.d.mts +2 -2
  11. package/esm/cache/database-cache-driver.d.mts.map +1 -1
  12. package/esm/cache/database-cache-driver.mjs +3 -2
  13. package/esm/cache/database-cache-driver.mjs.map +1 -1
  14. package/esm/cli/cli-commands.manager.mjs +16 -14
  15. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  16. package/esm/cli/commands/add.command.mjs +1 -1
  17. package/esm/cli/commands/add.command.mjs.map +1 -1
  18. package/esm/cli/commands/doctor/checks/optional-peers.check.mjs +3 -2
  19. package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
  20. package/esm/cli/commands/generate/generate.command.mjs +20 -0
  21. package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
  22. package/esm/cli/commands/generate/generators/column-dsl-parser.mjs +4 -2
  23. package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
  24. package/esm/cli/commands/generate/generators/controller.generator.mjs +1 -1
  25. package/esm/cli/commands/generate/generators/controller.generator.mjs.map +1 -1
  26. package/esm/cli/commands/generate/generators/migration.generator.mjs +22 -6
  27. package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
  28. package/esm/cli/commands/generate/generators/model.generator.mjs +22 -7
  29. package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
  30. package/esm/cli/commands/generate/generators/module.generator.mjs +8 -6
  31. package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
  32. package/esm/cli/commands/generate/generators/repository.generator.mjs +1 -1
  33. package/esm/cli/commands/generate/generators/repository.generator.mjs.map +1 -1
  34. package/esm/cli/commands/generate/generators/resource.generator.mjs +1 -1
  35. package/esm/cli/commands/generate/generators/resource.generator.mjs.map +1 -1
  36. package/esm/cli/commands/generate/generators/service.generator.mjs +1 -1
  37. package/esm/cli/commands/generate/generators/service.generator.mjs.map +1 -1
  38. package/esm/cli/commands/generate/templates/stubs.mjs +7 -7
  39. package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
  40. package/esm/cli/commands/generate/utils/writer.mjs +25 -1
  41. package/esm/cli/commands/generate/utils/writer.mjs.map +1 -1
  42. package/esm/cli/commands/routes/routes-command.action.mjs +5 -1
  43. package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -1
  44. package/esm/cli/commands/routes/with-console-on-stderr.mjs +24 -0
  45. package/esm/cli/commands/routes/with-console-on-stderr.mjs.map +1 -0
  46. package/esm/cli/commands/routes.command.mjs +3 -4
  47. package/esm/cli/commands/routes.command.mjs.map +1 -1
  48. package/esm/cli/commands/start-production.command.mjs +5 -5
  49. package/esm/cli/commands/start-production.command.mjs.map +1 -1
  50. package/esm/cli/commands/storage-put.action.mjs +2 -1
  51. package/esm/cli/commands/storage-put.action.mjs.map +1 -1
  52. package/esm/cli/commands/update.command.mjs +1 -0
  53. package/esm/cli/commands/update.command.mjs.map +1 -1
  54. package/esm/cli/parse-cli-args.mjs +13 -1
  55. package/esm/cli/parse-cli-args.mjs.map +1 -1
  56. package/esm/commands/cli-command.d.mts.map +1 -1
  57. package/esm/commands/cli-command.mjs +4 -2
  58. package/esm/commands/cli-command.mjs.map +1 -1
  59. package/esm/commands/index.mjs +3 -0
  60. package/esm/config/config-key-from-path.mjs +20 -0
  61. package/esm/config/config-key-from-path.mjs.map +1 -0
  62. package/esm/config/config-loader.d.mts.map +1 -1
  63. package/esm/config/config-loader.mjs +2 -3
  64. package/esm/config/config-loader.mjs.map +1 -1
  65. package/esm/connectors/cache-connector.d.mts.map +1 -1
  66. package/esm/connectors/cache-connector.mjs +5 -0
  67. package/esm/connectors/cache-connector.mjs.map +1 -1
  68. package/esm/connectors/connectors-manager.d.mts +4 -0
  69. package/esm/connectors/connectors-manager.d.mts.map +1 -1
  70. package/esm/connectors/connectors-manager.mjs +30 -2
  71. package/esm/connectors/connectors-manager.mjs.map +1 -1
  72. package/esm/connectors/single-server-warnings.mjs +33 -0
  73. package/esm/connectors/single-server-warnings.mjs.map +1 -0
  74. package/esm/connectors/socket-connector.d.mts +29 -0
  75. package/esm/connectors/socket-connector.d.mts.map +1 -1
  76. package/esm/connectors/socket-connector.mjs +77 -9
  77. package/esm/connectors/socket-connector.mjs.map +1 -1
  78. package/esm/connectors/storage.connector.d.mts.map +1 -1
  79. package/esm/connectors/storage.connector.mjs +6 -0
  80. package/esm/connectors/storage.connector.mjs.map +1 -1
  81. package/esm/connectors/types.d.mts +4 -2
  82. package/esm/connectors/types.d.mts.map +1 -1
  83. package/esm/connectors/types.mjs.map +1 -1
  84. package/esm/database/models/database-log/database-log.d.mts +47 -24
  85. package/esm/database/models/database-log/database-log.d.mts.map +1 -1
  86. package/esm/database/models/database-log/database-log.mjs +36 -4
  87. package/esm/database/models/database-log/database-log.mjs.map +1 -1
  88. package/esm/database/seed-command-action.mjs +10 -2
  89. package/esm/database/seed-command-action.mjs.map +1 -1
  90. package/esm/dev-server/development-server.mjs +15 -4
  91. package/esm/dev-server/development-server.mjs.map +1 -1
  92. package/esm/dev-server/file-event-handler.mjs +26 -6
  93. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  94. package/esm/dev-server/file-manager.d.mts.map +1 -1
  95. package/esm/dev-server/file-manager.mjs +2 -2
  96. package/esm/dev-server/file-manager.mjs.map +1 -1
  97. package/esm/dev-server/files-orchestrator.mjs +3 -1
  98. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  99. package/esm/dev-server/files-watcher.mjs +64 -5
  100. package/esm/dev-server/files-watcher.mjs.map +1 -1
  101. package/esm/dev-server/health-checker/files-healthcare.manager.mjs +31 -9
  102. package/esm/dev-server/health-checker/files-healthcare.manager.mjs.map +1 -1
  103. package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs +11 -7
  104. package/esm/dev-server/health-checker/workers/eslint-health.worker.mjs.map +1 -1
  105. package/esm/dev-server/loader/load-hook.mjs +1 -1
  106. package/esm/dev-server/loader/register-loader.mjs +1 -1
  107. package/esm/dev-server/manifest-manager.d.mts.map +1 -1
  108. package/esm/dev-server/manifest-manager.mjs +12 -6
  109. package/esm/dev-server/manifest-manager.mjs.map +1 -1
  110. package/esm/dev-server/parse-imports.mjs +9 -0
  111. package/esm/dev-server/parse-imports.mjs.map +1 -1
  112. package/esm/dev-server/register-dev-shortcuts.mjs +2 -1
  113. package/esm/dev-server/register-dev-shortcuts.mjs.map +1 -1
  114. package/esm/dev-server/route-types-publisher.mjs +60 -0
  115. package/esm/dev-server/route-types-publisher.mjs.map +1 -0
  116. package/esm/dev-server/shortcuts.mjs +2 -2
  117. package/esm/dev-server/shortcuts.mjs.map +1 -1
  118. package/esm/dev-server/special-file-patterns.mjs +18 -0
  119. package/esm/dev-server/special-file-patterns.mjs.map +1 -0
  120. package/esm/dev-server/special-files-collector.d.mts.map +1 -1
  121. package/esm/dev-server/special-files-collector.mjs +2 -5
  122. package/esm/dev-server/special-files-collector.mjs.map +1 -1
  123. package/esm/dev-server/start-development-server.mjs +1 -2
  124. package/esm/dev-server/start-development-server.mjs.map +1 -1
  125. package/esm/dev-server/supervisor.mjs +23 -3
  126. package/esm/dev-server/supervisor.mjs.map +1 -1
  127. package/esm/dev-server/tsconfig-manager.mjs +22 -12
  128. package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
  129. package/esm/dev-server/type-generator.mjs +10 -9
  130. package/esm/dev-server/type-generator.mjs.map +1 -1
  131. package/esm/encryption/encrypt.d.mts.map +1 -1
  132. package/esm/encryption/encrypt.mjs +16 -5
  133. package/esm/encryption/encrypt.mjs.map +1 -1
  134. package/esm/encryption/hash.d.mts.map +1 -1
  135. package/esm/encryption/hash.mjs +2 -0
  136. package/esm/encryption/hash.mjs.map +1 -1
  137. package/esm/encryption/password.d.mts.map +1 -1
  138. package/esm/encryption/password.mjs +3 -1
  139. package/esm/encryption/password.mjs.map +1 -1
  140. package/esm/generations/features/index.mjs +1 -1
  141. package/esm/generations/features/mysql.feature.mjs +9 -2
  142. package/esm/generations/features/mysql.feature.mjs.map +1 -1
  143. package/esm/generations/features/test.feature.mjs +2 -1
  144. package/esm/generations/features/test.feature.mjs.map +1 -1
  145. package/esm/generations/features/web.feature.mjs +4 -2
  146. package/esm/generations/features/web.feature.mjs.map +1 -1
  147. package/esm/http/build-rate-limit-options.d.mts +37 -0
  148. package/esm/http/build-rate-limit-options.d.mts.map +1 -0
  149. package/esm/http/build-rate-limit-options.mjs +37 -0
  150. package/esm/http/build-rate-limit-options.mjs.map +1 -0
  151. package/esm/http/csrf-origin-policy.d.mts.map +1 -1
  152. package/esm/http/csrf-origin-policy.mjs +5 -2
  153. package/esm/http/csrf-origin-policy.mjs.map +1 -1
  154. package/esm/http/flush-pending-cookies.mjs +52 -0
  155. package/esm/http/flush-pending-cookies.mjs.map +1 -0
  156. package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
  157. package/esm/http/middleware/cache-response-middleware.mjs +4 -2
  158. package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
  159. package/esm/http/middleware/idempotency.middleware.d.mts +5 -0
  160. package/esm/http/middleware/idempotency.middleware.d.mts.map +1 -1
  161. package/esm/http/middleware/idempotency.middleware.mjs +35 -3
  162. package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
  163. package/esm/http/middleware/inject-request-context.d.mts.map +1 -1
  164. package/esm/http/middleware/inject-request-context.mjs +14 -3
  165. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  166. package/esm/http/middleware/rate-limit.middleware.d.mts +4 -3
  167. package/esm/http/middleware/rate-limit.middleware.d.mts.map +1 -1
  168. package/esm/http/middleware/rate-limit.middleware.mjs +4 -3
  169. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  170. package/esm/http/middleware/utils/cidr-match.d.mts +1 -1
  171. package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
  172. package/esm/http/middleware/utils/cidr-match.mjs +11 -2
  173. package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
  174. package/esm/http/middleware/utils/idempotency-key.mjs +1 -1
  175. package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
  176. package/esm/http/plugins.d.mts.map +1 -1
  177. package/esm/http/plugins.mjs +13 -5
  178. package/esm/http/plugins.mjs.map +1 -1
  179. package/esm/http/request.d.mts +12 -1
  180. package/esm/http/request.d.mts.map +1 -1
  181. package/esm/http/request.mjs +35 -7
  182. package/esm/http/request.mjs.map +1 -1
  183. package/esm/http/response.d.mts +16 -0
  184. package/esm/http/response.d.mts.map +1 -1
  185. package/esm/http/response.mjs +75 -37
  186. package/esm/http/response.mjs.map +1 -1
  187. package/esm/http/types.d.mts +26 -14
  188. package/esm/http/types.d.mts.map +1 -1
  189. package/esm/http/uploads/uploaded-file.controller.mjs +1 -1
  190. package/esm/http/uploads-config.mjs +2 -1
  191. package/esm/http/uploads-config.mjs.map +1 -1
  192. package/esm/http/uploads-types.d.mts +3 -3
  193. package/esm/image/image.d.mts +1 -1
  194. package/esm/image/image.d.mts.map +1 -1
  195. package/esm/image/image.mjs +25 -15
  196. package/esm/image/image.mjs.map +1 -1
  197. package/esm/index.d.mts +6 -4
  198. package/esm/index.mjs +7 -4
  199. package/esm/logger/logger.mjs +6 -1
  200. package/esm/logger/logger.mjs.map +1 -1
  201. package/esm/mail/config.d.mts.map +1 -1
  202. package/esm/mail/config.mjs +31 -21
  203. package/esm/mail/config.mjs.map +1 -1
  204. package/esm/mail/react-mail.mjs +6 -3
  205. package/esm/mail/react-mail.mjs.map +1 -1
  206. package/esm/mail/send-mail.d.mts.map +1 -1
  207. package/esm/mail/send-mail.mjs +40 -19
  208. package/esm/mail/send-mail.mjs.map +1 -1
  209. package/esm/production/assert-generated-imports.mjs +1 -0
  210. package/esm/production/assert-generated-imports.mjs.map +1 -1
  211. package/esm/production/build-contributions.mjs +3 -0
  212. package/esm/production/build-contributions.mjs.map +1 -1
  213. package/esm/production/esbuild-plugins.mjs +3 -2
  214. package/esm/production/esbuild-plugins.mjs.map +1 -1
  215. package/esm/production/production-builder.mjs +49 -37
  216. package/esm/production/production-builder.mjs.map +1 -1
  217. package/esm/production/production-supervisor.mjs +12 -5
  218. package/esm/production/production-supervisor.mjs.map +1 -1
  219. package/esm/production/route-registration-child.d.mts +1 -0
  220. package/esm/production/route-registration-child.mjs +65 -0
  221. package/esm/production/route-registration-child.mjs.map +1 -0
  222. package/esm/production/route-registration-snapshot.mjs +166 -0
  223. package/esm/production/route-registration-snapshot.mjs.map +1 -0
  224. package/esm/repositories/adapters/cascade/cascade-adapter.d.mts +3 -1
  225. package/esm/repositories/adapters/cascade/cascade-adapter.d.mts.map +1 -1
  226. package/esm/repositories/adapters/cascade/cascade-adapter.mjs +22 -12
  227. package/esm/repositories/adapters/cascade/cascade-adapter.mjs.map +1 -1
  228. package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +3 -3
  229. package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
  230. package/esm/repositories/adapters/cascade/filter-applicator.mjs +88 -61
  231. package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
  232. package/esm/repositories/adapters/cascade/index.d.mts +1 -1
  233. package/esm/repositories/adapters/cascade/index.mjs +1 -1
  234. package/esm/repositories/contracts/query-builder.contract.d.mts +3 -3
  235. package/esm/repositories/contracts/types.d.mts +5 -0
  236. package/esm/repositories/contracts/types.d.mts.map +1 -1
  237. package/esm/repositories/index.d.mts +1 -1
  238. package/esm/repositories/index.mjs +1 -1
  239. package/esm/repositories/repository.manager.d.mts +65 -3
  240. package/esm/repositories/repository.manager.d.mts.map +1 -1
  241. package/esm/repositories/repository.manager.mjs +146 -57
  242. package/esm/repositories/repository.manager.mjs.map +1 -1
  243. package/esm/resource/resource-field-builder.d.mts.map +1 -1
  244. package/esm/resource/resource-field-builder.mjs +1 -0
  245. package/esm/resource/resource-field-builder.mjs.map +1 -1
  246. package/esm/resource/resource.d.mts +10 -3
  247. package/esm/resource/resource.d.mts.map +1 -1
  248. package/esm/resource/resource.mjs +19 -5
  249. package/esm/resource/resource.mjs.map +1 -1
  250. package/esm/restful/restful.d.mts +12 -5
  251. package/esm/restful/restful.d.mts.map +1 -1
  252. package/esm/restful/restful.mjs +47 -16
  253. package/esm/restful/restful.mjs.map +1 -1
  254. package/esm/router/build-route-rate-limit.mjs +22 -0
  255. package/esm/router/build-route-rate-limit.mjs.map +1 -0
  256. package/esm/router/dev-dispatch.mjs +60 -0
  257. package/esm/router/dev-dispatch.mjs.map +1 -0
  258. package/esm/router/route-builder.mjs +4 -1
  259. package/esm/router/route-builder.mjs.map +1 -1
  260. package/esm/router/route-registry.d.mts.map +1 -1
  261. package/esm/router/route-registry.mjs +2 -2
  262. package/esm/router/route-registry.mjs.map +1 -1
  263. package/esm/router/router.d.mts +1 -1
  264. package/esm/router/router.d.mts.map +1 -1
  265. package/esm/router/router.mjs +57 -39
  266. package/esm/router/router.mjs.map +1 -1
  267. package/esm/socket/index.d.mts +1 -1
  268. package/esm/socket/types.d.mts +25 -3
  269. package/esm/socket/types.d.mts.map +1 -1
  270. package/esm/storage/drivers/cloud-driver.d.mts +26 -0
  271. package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
  272. package/esm/storage/drivers/cloud-driver.mjs +100 -16
  273. package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
  274. package/esm/storage/drivers/do-spaces-driver.d.mts +7 -0
  275. package/esm/storage/drivers/do-spaces-driver.d.mts.map +1 -1
  276. package/esm/storage/drivers/do-spaces-driver.mjs +9 -2
  277. package/esm/storage/drivers/do-spaces-driver.mjs.map +1 -1
  278. package/esm/storage/drivers/local-driver.d.mts +16 -5
  279. package/esm/storage/drivers/local-driver.d.mts.map +1 -1
  280. package/esm/storage/drivers/local-driver.mjs +71 -28
  281. package/esm/storage/drivers/local-driver.mjs.map +1 -1
  282. package/esm/storage/index.d.mts +3 -1
  283. package/esm/storage/index.mjs +4 -2
  284. package/esm/storage/scoped-storage.d.mts +27 -1
  285. package/esm/storage/scoped-storage.d.mts.map +1 -1
  286. package/esm/storage/scoped-storage.mjs +40 -8
  287. package/esm/storage/scoped-storage.mjs.map +1 -1
  288. package/esm/storage/storage.d.mts +11 -5
  289. package/esm/storage/storage.d.mts.map +1 -1
  290. package/esm/storage/storage.mjs +39 -16
  291. package/esm/storage/storage.mjs.map +1 -1
  292. package/esm/storage/types.d.mts +43 -4
  293. package/esm/storage/types.d.mts.map +1 -1
  294. package/esm/storage/utils/classify-ip-address.d.mts +13 -0
  295. package/esm/storage/utils/classify-ip-address.d.mts.map +1 -0
  296. package/esm/storage/utils/classify-ip-address.mjs +98 -0
  297. package/esm/storage/utils/classify-ip-address.mjs.map +1 -0
  298. package/esm/storage/utils/safe-fetch.d.mts +3 -12
  299. package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
  300. package/esm/storage/utils/safe-fetch.mjs +3 -48
  301. package/esm/storage/utils/safe-fetch.mjs.map +1 -1
  302. package/esm/storage/utils/storage-capability-error.d.mts +25 -0
  303. package/esm/storage/utils/storage-capability-error.d.mts.map +1 -0
  304. package/esm/storage/utils/storage-capability-error.mjs +26 -0
  305. package/esm/storage/utils/storage-capability-error.mjs.map +1 -0
  306. package/esm/updater/update-warlock-packages.mjs +11 -1
  307. package/esm/updater/update-warlock-packages.mjs.map +1 -1
  308. package/esm/use-cases/use-case-broadcast.mjs +7 -1
  309. package/esm/use-cases/use-case-broadcast.mjs.map +1 -1
  310. package/esm/use-cases/use-cases-registry.mjs +21 -2
  311. package/esm/use-cases/use-cases-registry.mjs.map +1 -1
  312. package/esm/utils/database-log.mjs +0 -3
  313. package/esm/utils/database-log.mjs.map +1 -1
  314. package/esm/utils/queue.d.mts +6 -4
  315. package/esm/utils/queue.d.mts.map +1 -1
  316. package/esm/utils/queue.mjs +20 -9
  317. package/esm/utils/queue.mjs.map +1 -1
  318. package/esm/validation/database/exists-except-current-id.mjs +6 -2
  319. package/esm/validation/database/exists-except-current-id.mjs.map +1 -1
  320. package/esm/validation/database/unique-except-current-id.mjs +6 -2
  321. package/esm/validation/database/unique-except-current-id.mjs.map +1 -1
  322. package/esm/validation/init.mjs +6 -2
  323. package/esm/validation/init.mjs.map +1 -1
  324. package/esm/validation/validateAll.mjs +3 -2
  325. package/esm/validation/validateAll.mjs.map +1 -1
  326. package/esm/warlock-config/types.d.mts +14 -1
  327. package/esm/warlock-config/types.d.mts.map +1 -1
  328. package/esm/warlock-config/warlock-config.manager.d.mts.map +1 -1
  329. package/esm/warlock-config/warlock-config.manager.mjs +3 -1
  330. package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
  331. package/esm/warlock-config/warn-deprecated-config.mjs +25 -0
  332. package/esm/warlock-config/warn-deprecated-config.mjs.map +1 -0
  333. package/llms-full.txt +71 -42
  334. package/llms.txt +41 -41
  335. package/package.json +21 -15
  336. package/skills/add-connector/SKILL.md +5 -1
  337. package/skills/benchmark-code/SKILL.md +1 -1
  338. package/skills/build-restful/SKILL.md +1 -1
  339. package/skills/build-url/SKILL.md +1 -1
  340. package/skills/configure-app/SKILL.md +7 -1
  341. package/skills/create-controller/SKILL.md +1 -1
  342. package/skills/create-module/SKILL.md +1 -1
  343. package/skills/define-resource/SKILL.md +1 -1
  344. package/skills/encrypt-data/SKILL.md +1 -1
  345. package/skills/hash-password/SKILL.md +1 -1
  346. package/skills/health-checks/SKILL.md +1 -1
  347. package/skills/index.md +30 -0
  348. package/skills/lower-stage3-decorators/SKILL.md +1 -1
  349. package/skills/process-image/SKILL.md +1 -1
  350. package/skills/register-route/SKILL.md +1 -1
  351. package/skills/request-memo/SKILL.md +1 -1
  352. package/skills/request-tracing/SKILL.md +1 -1
  353. package/skills/resolve-path/SKILL.md +1 -1
  354. package/skills/retry-operation/SKILL.md +1 -1
  355. package/skills/run-app/SKILL.md +1 -1
  356. package/skills/send-mail/SKILL.md +1 -1
  357. package/skills/send-response/SKILL.md +1 -1
  358. package/skills/store-file/SKILL.md +11 -1
  359. package/skills/test-http/SKILL.md +1 -1
  360. package/skills/test-service/SKILL.md +1 -1
  361. package/skills/update-packages/SKILL.md +1 -1
  362. package/skills/upload-file/SKILL.md +1 -1
  363. package/skills/use-app-context/SKILL.md +1 -1
  364. package/skills/use-localization/SKILL.md +1 -1
  365. package/skills/use-middleware/SKILL.md +7 -2
  366. package/skills/use-model-transformers/SKILL.md +1 -1
  367. package/skills/use-repository/SKILL.md +1 -1
  368. package/skills/use-request-locals/SKILL.md +1 -1
  369. package/skills/validate-input/SKILL.md +1 -1
  370. package/skills/warlock-conventions/SKILL.md +1 -1
  371. package/skills/warlock-doctor/SKILL.md +1 -1
  372. package/skills/warlock-routes/SKILL.md +1 -1
  373. package/skills/wire-socket/SKILL.md +5 -1
  374. package/skills/write-cli-command/SKILL.md +1 -1
  375. package/skills/write-middleware/SKILL.md +1 -1
  376. package/skills/write-seeder/SKILL.md +1 -1
  377. package/skills/write-use-case/SKILL.md +1 -1
  378. package/esm/_virtual/_rolldown/runtime.mjs +0 -7
@@ -4,17 +4,20 @@ import { assertNoReservedConnectorNames } from "../connectors/assert-no-reserved
4
4
  import { assertUniqueConnectorNames } from "../connectors/assert-unique-connector-names.mjs";
5
5
  import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
6
6
  import { tsconfigManager } from "../dev-server/tsconfig-manager.mjs";
7
+ import { isConfigFile, isEventFile, isLocaleFile, isMainFile, isRouteFile } from "../dev-server/special-file-patterns.mjs";
8
+ import { configKeyFromPath } from "../config/config-key-from-path.mjs";
7
9
  import { assertGeneratedImportsAreDeclared } from "./assert-generated-imports.mjs";
8
10
  import { bundleFrameworkDependencies } from "./bundle-framework-dependencies.mjs";
9
11
  import { dedupe, runEmitContributions, runGenerateContributions } from "./build-contributions.mjs";
10
12
  import { writeDistBuildManifestAsync } from "./dist-build-manifest.mjs";
11
13
  import { nativeNodeModulesPlugin } from "./esbuild-plugins.mjs";
12
14
  import { assertEsbuildBinaryIsLinked } from "./esbuild-preflight.mjs";
15
+ import { collectRouteRegistrationSnapshot } from "./route-registration-snapshot.mjs";
16
+ import { clearOwnedRouteTypes } from "../dev-server/route-types-publisher.mjs";
13
17
  import { commitDistAsync, createTempOutputDir, rollbackDistAsync, stageDistAsync } from "./promote-dist.mjs";
14
18
  import { resolveBuildConfig } from "./resolve-build-config.mjs";
15
19
  import { tsconfigPathAliases } from "./tsconfig-path-aliases.mjs";
16
20
  import path from "path";
17
- import { toCamelCase } from "@mongez/reinforcements";
18
21
  import { colors } from "@mongez/copper";
19
22
  import { ensureDirectoryAsync, fileExistsAsync, getFileAsync, getJsonFileAsync, putFileAsync, removeDirectoryAsync } from "@warlock.js/fs";
20
23
  import glob from "fast-glob";
@@ -126,6 +129,7 @@ var ProductionBuilder = class {
126
129
  await this.generateCombinedFiles();
127
130
  await this.generateEntryPoint();
128
131
  await this.assertGeneratedImports();
132
+ await this.captureNamedApiRoutesForWeb();
129
133
  if (await this.runGenerateContributions()) await this.assertGeneratedImports();
130
134
  await this.bundle(tempOutDir);
131
135
  staged = await stageDistAsync(tempOutDir, finalOutDir);
@@ -159,10 +163,23 @@ var ProductionBuilder = class {
159
163
  return {
160
164
  productionDir: this.productionDir,
161
165
  appRoot: rootPath(),
162
- options: this.options
166
+ options: this.options,
167
+ namedApiRoutes: this.namedApiRoutes
163
168
  };
164
169
  }
165
170
  /**
171
+ * Web route declarations need application API registration, which cannot be
172
+ * inferred from generated files. Capture it once in a disposable child before
173
+ * contributors write build artifacts; no connector lifecycle runs there.
174
+ */
175
+ async captureNamedApiRoutesForWeb() {
176
+ if (!this.connectors.some((connector) => connector.name === "web")) {
177
+ await clearOwnedRouteTypes(rootPath());
178
+ return;
179
+ }
180
+ this.namedApiRoutes = (await collectRouteRegistrationSnapshot({ cwd: rootPath() })).routes;
181
+ }
182
+ /**
166
183
  * Drain the `generate` hooks and fold what they returned back into the
167
184
  * build.
168
185
  *
@@ -213,16 +230,17 @@ var ProductionBuilder = class {
213
230
  * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment
214
231
  */
215
232
  async generateBootstrap() {
216
- let content = `import { bootstrap, Application } from "@warlock.js/core";
233
+ const content = `${await fileExistsAsync(appPath("bootstrap.ts")) ? "import './../../src/app/bootstrap';\n" : ""}import { bootstrap, Application } from "@warlock.js/core";
217
234
 
218
- // Set production environment
235
+ // Production runtime; NODE_ENV is only defaulted so an explicit value (e.g. staging) wins
219
236
  Application.setRuntimeStrategy("production");
220
- Application.setEnvironment("production");
237
+ if (!process.env.NODE_ENV) {
238
+ Application.setEnvironment("production");
239
+ }
221
240
 
222
241
  // Bootstrap the application
223
242
  bootstrap();
224
243
  `;
225
- if (await fileExistsAsync(appPath("bootstrap.ts"))) content += "import './../../src/app/bootstrap';\n";
226
244
  await putFileAsync(path.join(this.productionDir, "bootstrap.ts"), content);
227
245
  }
228
246
  /**
@@ -249,45 +267,39 @@ bootstrap();
249
267
  assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));
250
268
  }
251
269
  /**
252
- * Glob for module files matching a pattern
270
+ * Glob `src/app` and keep the files the shared dev-server predicate accepts,
271
+ * so production discovers exactly what the dev collector does.
253
272
  * Returns relative paths from .warlock/production/ to src/app/
254
273
  */
255
- async globModule(fileName) {
256
- return (await glob(`**/${fileName}.{ts,tsx}`, {
274
+ async globModule(matches) {
275
+ return (await glob("**/*.{ts,tsx}", {
257
276
  cwd: appPath(),
258
277
  absolute: false
259
- })).map((file) => "../../src/app/" + file.replace(/\.(ts|tsx)$/, ""));
260
- }
261
- /**
262
- * Glob for files in a specific directory pattern
263
- * Returns relative paths from .warlock/production/ to src/app/
264
- */
265
- async globModuleDirectory(directory) {
266
- return (await glob(`**/${directory}/*.{ts,tsx}`, {
267
- cwd: appPath(),
268
- absolute: false
269
- })).map((file) => "../../src/app/" + file.replace(/\.(ts|tsx)$/, ""));
278
+ })).filter((file) => matches("src/app/" + file)).sort().map((file) => "../../src/app/" + file.replace(/\.(ts|tsx)$/, ""));
270
279
  }
271
280
  /**
272
281
  * Generate config-loader.ts
273
282
  */
274
283
  async generateConfigLoader() {
275
- const configNames = (await glob("*.{ts,tsx}", {
284
+ const configNames = (await glob("**/*.{ts,tsx}", {
276
285
  cwd: path.join(process.cwd(), "src/config"),
277
286
  absolute: false
278
- })).map((f) => f.replace(/\.(ts|tsx)$/, ""));
287
+ })).filter((f) => isConfigFile("src/config/" + f)).map((f) => ({
288
+ path: f.replace(/\.(ts|tsx)$/, ""),
289
+ key: configKeyFromPath("src/config/" + f)
290
+ })).filter((entry) => entry.key !== void 0).sort((a, b) => a.path.localeCompare(b.path));
279
291
  const imports = ["import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";"];
280
292
  const configImports = [];
281
293
  const configSetCalls = [];
282
294
  const executors = [];
283
- for (const configName of configNames) {
284
- const properConfigName = toCamelCase(configName);
285
- const varName = `${properConfigName}Config`;
286
- configImports.push(`import ${varName} from "../../src/config/${configName}";`);
287
- configSetCalls.push(`setConfig("${properConfigName}", ${varName});`);
288
- executors.push(`await configSpecialHandlers.execute("${properConfigName}", ${varName});`);
289
- }
290
- let content = [
295
+ configNames.forEach(({ path: configPath, key }, index) => {
296
+ const varName = `config${index}`;
297
+ configImports.push(`import ${varName} from "../../src/config/${configPath}";`);
298
+ configSetCalls.push(`setConfig(${JSON.stringify(key)}, ${varName});`);
299
+ executors.push(`await configSpecialHandlers.execute(${JSON.stringify(key)}, ${varName});`);
300
+ });
301
+ const content = [
302
+ ...await fileExistsAsync(appPath("prestart.ts")) ? ["import './../../src/app/prestart';"] : [],
291
303
  ...imports,
292
304
  "",
293
305
  "// Config imports",
@@ -300,7 +312,6 @@ bootstrap();
300
312
  ...executors,
301
313
  ""
302
314
  ].join("\n");
303
- if (await fileExistsAsync(appPath("prestart.ts"))) content += "import './../../src/app/prestart';\n";
304
315
  await putFileAsync(path.join(this.productionDir, "config-loader.ts"), content);
305
316
  }
306
317
  /**
@@ -308,7 +319,7 @@ bootstrap();
308
319
  * @returns true if file was generated with content
309
320
  */
310
321
  async generateLocales() {
311
- const files = await this.globModule("utils/locales");
322
+ const files = await this.globModule(isLocaleFile);
312
323
  if (files.length === 0) return false;
313
324
  await this.generateImportsFile(files, "locales.ts");
314
325
  return true;
@@ -318,7 +329,7 @@ bootstrap();
318
329
  * @returns true if file was generated with content
319
330
  */
320
331
  async generateEvents() {
321
- const files = await this.globModuleDirectory("events");
332
+ const files = await this.globModule(isEventFile);
322
333
  if (files.length === 0) return false;
323
334
  await this.generateImportsFile(files, "events.ts");
324
335
  return true;
@@ -328,7 +339,7 @@ bootstrap();
328
339
  * @returns true if file was generated with content
329
340
  */
330
341
  async generateMain() {
331
- const files = await this.globModule("main");
342
+ const files = await this.globModule(isMainFile);
332
343
  if (files.length === 0) return false;
333
344
  await this.generateImportsFile(files, "main.ts");
334
345
  return true;
@@ -338,7 +349,7 @@ bootstrap();
338
349
  * @returns true if file was generated with content
339
350
  */
340
351
  async generateRoutes() {
341
- const files = await this.globModule("routes");
352
+ const files = await this.globModule(isRouteFile);
342
353
  if (files.length === 0) return false;
343
354
  await this.generateImportsFile(files, "routes.ts");
344
355
  return true;
@@ -432,7 +443,7 @@ bootstrap();
432
443
  const perEdgeExternals = !singleBundle && esbuildOptions.packages === void 0;
433
444
  const isEsm = (esbuildOptions.format ?? "esm") === "esm";
434
445
  const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : void 0);
435
- const { define: contributedDefine, external: contributedExternal, loader: contributedLoader, ...contributedOptions } = this.contributedEsbuild;
446
+ const { define: contributedDefine, external: contributedExternal, loader: contributedLoader, plugins: contributedPlugins, ...contributedOptions } = this.contributedEsbuild;
436
447
  const userDefine = esbuildOptions.define;
437
448
  const userExternal = esbuildOptions.external;
438
449
  const userLoader = esbuildOptions.loader;
@@ -465,7 +476,8 @@ bootstrap();
465
476
  ...perEdgeExternals ? [bundleFrameworkDependencies({
466
477
  appRoot: rootPath(),
467
478
  aliasKeys: Object.keys(alias)
468
- })] : []
479
+ })] : [],
480
+ ...contributedPlugins ?? []
469
481
  ],
470
482
  ...contributedOptions,
471
483
  ...esbuildOptions,
@@ -1 +1 @@
1
- {"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n ensureDirectoryAsync,\r\n fileExistsAsync,\r\n getFileAsync,\r\n getJsonFileAsync,\r\n putFileAsync,\r\n removeDirectoryAsync,\r\n} from \"@warlock.js/fs\";\r\nimport esbuild from \"esbuild\";\r\nimport glob from \"fast-glob\";\r\nimport path from \"path\";\r\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\r\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\r\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\r\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, rootPath, warlockPath } from \"../utils\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\r\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\r\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\r\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\r\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\r\nimport {\r\n commitDistAsync,\r\n createTempOutputDir,\r\n rollbackDistAsync,\r\n stageDistAsync,\r\n type StagedDist,\r\n} from \"./promote-dist\";\r\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\r\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\r\nimport { toCamelCase, toKebabCase } from \"@mongez/reinforcements\";\r\n\r\n/**\r\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\r\n *\r\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\r\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\r\n * esbuild substitutes a stub that throws — **after the build has reported\r\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\r\n * firing, and it is the defect this shim removes.\r\n *\r\n * `__dirname` matters as much as `require`: without it a dependency resolving\r\n * an asset path silently gets `undefined` and fails later, further from the\r\n * cause.\r\n *\r\n * Written as one line because esbuild inserts a banner verbatim above the\r\n * bundle and a multi-line string here would shift every mapped line.\r\n */\r\nconst ESM_INTEROP_SHIM =\r\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\r\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\r\n \"import{dirname as __wlDirname}from'node:path';\" +\r\n \"const require=__wlCreateRequire(import.meta.url);\" +\r\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\r\n \"const __dirname=__wlDirname(__filename);\";\r\n\r\n/**\r\n * Combine the framework's banner with the user's, keeping both.\r\n *\r\n * esbuild's `banner` is an object keyed by output type, and every merge in the\r\n * path to it — the config merge and the options spread — REPLACES that object\r\n * rather than merging it. So whichever is applied second silently deletes the\r\n * other. This is the only place the two can coexist.\r\n *\r\n * The shim goes first: it defines `require`, which a user banner may use.\r\n *\r\n * @param userBanner banner from `warlock.config.ts`, if any\r\n * @param shim the interop shim, or undefined when it does not apply\r\n */\r\nfunction mergeBanner(\r\n userBanner: Record<string, string> | undefined,\r\n shim: string | undefined,\r\n): Record<string, string> | undefined {\r\n if (!shim) return userBanner;\r\n\r\n const userJs = userBanner?.js;\r\n\r\n return {\r\n ...userBanner,\r\n js: userJs ? `${shim}${userJs}` : shim,\r\n };\r\n}\r\n\r\n/**\r\n * Prefix every generated file uses to reach the app root.\r\n *\r\n * Generated sources are written into `.warlock/production/`, two levels below\r\n * the app root, so `../../` lands back on it — the same hop already spelled\r\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\r\n * config-loader generators emit. Named once so a generator that needs a new\r\n * app-root file (`warlock.config`) cannot pick a different depth.\r\n */\r\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\r\n\r\n/**\r\n * Production Builder\r\n * Generates production-ready files and bundles them for deployment\r\n * Build options are loaded from warlock.config.ts\r\n */\r\nexport class ProductionBuilder {\r\n private options!: ResolvedBuildConfig;\r\n private readonly productionDir = warlockPath(\"production\");\r\n\r\n /**\r\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\r\n * never calls `boot()`/`start()` on them; it only\r\n * drains their `build` contributions.\r\n */\r\n private connectors: readonly Connector[] = [];\r\n\r\n /**\r\n * The contributors' merged esbuild patch, produced by the `generate` pass\r\n * and consumed by {@link bundle}.\r\n */\r\n private contributedEsbuild: ConnectorEsbuildPatch = {};\r\n\r\n /**\r\n * Main build entry point\r\n *\r\n * The esbuild bundle is written into a TEMP directory next to the real\r\n * output directory, never into it, and that directory is renamed over\r\n * `outdir` as one filesystem operation — so `outdir` is never observed as\r\n * a mix of the old build and the new one, and a build that fails before\r\n * that rename never touches `outdir` at all.\r\n *\r\n * `this.options.outdir` is NOT repointed at the temp directory while that\r\n * happens, and must never be. It is not merely a write target: consumers\r\n * BAKE it into runtime output — `web`'s build contribution derives the\r\n * `clientDir` recorded in its pages manifest from it\r\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\r\n * produces an artifact whose browser paths point at a directory promotion\r\n * has since renamed away. The temp path is passed explicitly, as a\r\n * parameter, to the one operation that writes into it ({@link bundle});\r\n * everything else, `buildContext()` included, keeps reading the final\r\n * destination.\r\n *\r\n * That is also why promotion is STAGED rather than done at the very end.\r\n * Connector `emit` hooks write real artifacts (the web client bundle) and\r\n * see the final `outdir`, so they must run when `outdir` genuinely holds\r\n * this build — after the rename, not before it, or promotion would replace\r\n * the directory they just wrote into. The previous build is kept parked\r\n * aside until they finish: `emit` throwing rolls the whole promotion back,\r\n * and the build-success marker `warlock start` checks is written last of\r\n * all, so a failure at any point leaves no `dist` that start will boot.\r\n */\r\n public async build(): Promise<void> {\r\n console.log(colors.cyan(\"Building for production...\\n\"));\r\n\r\n // Step 0: Fail fast when esbuild's native binary never got linked (the\r\n // state pnpm leaves a project in when its build-script approval gate\r\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\r\n // own cryptic \"package could not be found\" error several steps from now.\r\n assertEsbuildBinaryIsLinked();\r\n\r\n // Step 1: Initialize options from config\r\n await this.initializeOptions();\r\n\r\n const finalOutDir = this.options.outdir!;\r\n const tempOutDir = createTempOutputDir(finalOutDir);\r\n\r\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\r\n // presence is what tells the catch below whether a failure has a\r\n // promotion to undo or only a temp directory to discard.\r\n let staged: StagedDist | undefined;\r\n\r\n try {\r\n // Step 2: Generate combined files\r\n await this.generateCombinedFiles();\r\n\r\n // Step 3: Generate entry point\r\n await this.generateEntryPoint();\r\n\r\n // Step 4: Refuse to bundle code the app could not resolve at runtime\r\n await this.assertGeneratedImports();\r\n\r\n // Step 4.5: Drain the connectors' `generate` contributions\r\n const contributed = await this.runGenerateContributions();\r\n\r\n // Step 4.6: Re-assert over what the contributors just wrote.\r\n //\r\n // Step 4 only saw core's own generated files; a contributor writes its\r\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\r\n // specifier in it reaches the bundle unchecked. Under\r\n // `packages: \"external\"` that specifier survives verbatim into the\r\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\r\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\r\n // and re-reading the production dir is pure cost in the common case.\r\n if (contributed) {\r\n await this.assertGeneratedImports();\r\n }\r\n\r\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\r\n // operation handed that path — it is a write target, not config.\r\n await this.bundle(tempOutDir);\r\n\r\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\r\n // build parked aside. `outdir` now holds exactly this build, so the\r\n // steps below write into — and record — the real destination.\r\n staged = await stageDistAsync(tempOutDir, finalOutDir);\r\n\r\n // Step 5.6: Drain the connectors' `emit` contributions — after the\r\n // bundle is in place (so what they write survives promotion and the\r\n // paths they bake in resolve), and BEFORE step 6 deletes the\r\n // production directory they may still read.\r\n await runEmitContributions(this.connectors, this.buildContext());\r\n\r\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\r\n // `warlock start` trusts. Written LAST on purpose: every earlier step\r\n // can still fail, and until this file exists nothing will boot what\r\n // they left behind.\r\n await writeDistBuildManifestAsync(finalOutDir);\r\n\r\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\r\n await commitDistAsync(staged);\r\n } catch (error) {\r\n if (staged) {\r\n // The promotion already happened; put the previous build back and\r\n // take this half-finished one out of `outdir`.\r\n await rollbackDistAsync(staged);\r\n } else {\r\n // Nothing this build produced ever reached `outdir` — discard the\r\n // temp directory and leave `outdir` exactly as it was.\r\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\r\n }\r\n\r\n throw error;\r\n }\r\n\r\n // Step 6: Remove production folder\r\n await removeDirectoryAsync(this.productionDir);\r\n\r\n console.log(colors.green(\"Build complete!\"));\r\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\r\n }\r\n\r\n /**\r\n * Initialize options from warlock.config.ts\r\n */\r\n private async initializeOptions(): Promise<void> {\r\n this.options = resolveBuildConfig();\r\n // Same config object `resolveBuildConfig` just read — `warlock build`\r\n // preloads warlock.config.ts, so no additional load happens here.\r\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\r\n\r\n // Checked here, where the array is first read, so nothing downstream has\r\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\r\n // a name listed twice would write its files and merge its esbuild options\r\n // twice into an artifact the runtime then boots that name only once from.\r\n // A build that half-applied a connector and reported success is worse than\r\n // one that never started.\r\n assertUniqueConnectorNames([...connectors]);\r\n\r\n // And here rather than only at boot, for the same reason: a name a built-in\r\n // already owns is skipped by the runtime, so an artifact built from it\r\n // carries the custom connector's generated files and esbuild patches while\r\n // the server boots the built-in instead. Refusing it at boot alone would\r\n // mean the build had already emitted that artifact — the failure has to\r\n // land on the developer running `warlock build`, not on whoever starts the\r\n // server. Same assertion the registration half calls, over the same names.\r\n assertNoReservedConnectorNames([...connectors]);\r\n\r\n this.connectors = connectors;\r\n\r\n // Ensure production directory exists\r\n await ensureDirectoryAsync(this.productionDir);\r\n }\r\n\r\n /**\r\n * The context handed to every build contribution.\r\n */\r\n private buildContext(): ConnectorBuildContext {\r\n return {\r\n productionDir: this.productionDir,\r\n appRoot: rootPath(),\r\n options: this.options,\r\n };\r\n }\r\n\r\n /**\r\n * Drain the `generate` hooks and fold what they returned back into the\r\n * build.\r\n *\r\n * The entry point is REGENERATED here rather than generated later. The\r\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\r\n * bundles that the app could not resolve) and before `bundle` — while\r\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\r\n * generated code the assertion has to see; moving it past the assertion\r\n * would silently drop the entry from that check. Rewriting one small file\r\n * is cheaper than losing either guarantee, and the write is pure\r\n * (`generatedFiles` + these imports), so doing it twice is not a\r\n * correctness risk.\r\n *\r\n * @returns whether any connector ran a `generate` hook — the caller uses it\r\n * to decide if the import assertion is worth a second pass. Keyed on the\r\n * hook EXISTING, not on what it returned: a hook that returns nothing may\r\n * still have written files into `productionDir`, and those are exactly the\r\n * files the second pass is there to read.\r\n */\r\n private async runGenerateContributions(): Promise<boolean> {\r\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\r\n\r\n const { entryImports, esbuild } = await runGenerateContributions(\r\n this.connectors,\r\n this.buildContext(),\r\n );\r\n\r\n this.contributedEsbuild = esbuild;\r\n\r\n if (entryImports.length > 0) {\r\n await this.generateEntryPoint(entryImports);\r\n }\r\n\r\n return contributed;\r\n }\r\n\r\n /**\r\n * Track which special files were generated\r\n */\r\n private generatedFiles = {\r\n locales: false,\r\n events: false,\r\n main: false,\r\n routes: false,\r\n };\r\n\r\n /**\r\n * Generate all combined files\r\n */\r\n private async generateCombinedFiles(): Promise<void> {\r\n console.log(colors.yellow(\" Generating production files...\"));\r\n\r\n // Generate bootstrap.ts file\r\n await this.generateBootstrap();\r\n\r\n // Generate config loader\r\n await this.generateConfigLoader();\r\n\r\n // Generate special files and track which ones have content\r\n const [locales, events, main, routes] = await Promise.all([\r\n this.generateLocales(),\r\n this.generateEvents(),\r\n this.generateMain(),\r\n this.generateRoutes(),\r\n ]);\r\n\r\n this.generatedFiles = { locales, events, main, routes };\r\n }\r\n\r\n /**\r\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\r\n */\r\n private async generateBootstrap(): Promise<void> {\r\n let content = `import { bootstrap, Application } from \"@warlock.js/core\";\r\n\r\n// Set production environment\r\nApplication.setRuntimeStrategy(\"production\");\r\nApplication.setEnvironment(\"production\");\r\n\r\n// Bootstrap the application\r\nbootstrap();\r\n`;\r\n if (await fileExistsAsync(appPath(\"bootstrap.ts\"))) {\r\n content += \"import './../../src/app/bootstrap';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\r\n }\r\n\r\n /**\r\n * Fail the build when generated code imports a package the app does not\r\n * declare.\r\n *\r\n * The bundler is configured `packages: \"external\"`, so every bare specifier\r\n * written above survives verbatim into an artifact that resolves against the\r\n * **consuming app's** node_modules. A framework-internal dependency imported\r\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\r\n * which is how a production app shipped that could not boot. Rewriting the\r\n * offending import fixes today's bundle; this check is what stops the next\r\n * change to the generator from quietly reintroducing it.\r\n */\r\n private async assertGeneratedImports(): Promise<void> {\r\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\r\n cwd: this.productionDir,\r\n absolute: false,\r\n });\r\n\r\n const [files, appPackage] = await Promise.all([\r\n Promise.all(\r\n generatedPaths.map(async (file) => ({\r\n file,\r\n content: await getFileAsync(path.join(this.productionDir, file)),\r\n })),\r\n ),\r\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\r\n ]);\r\n\r\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\r\n }\r\n\r\n /**\r\n * Glob for module files matching a pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModule(fileName: string): Promise<string[]> {\r\n const pattern = `**/${fileName}.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n // Convert to relative paths from .warlock/production/ to src/app/\r\n // e.g., \"users/main\" -> \"../../src/app/users/main\"\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Glob for files in a specific directory pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModuleDirectory(directory: string): Promise<string[]> {\r\n const pattern = `**/${directory}/*.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Generate config-loader.ts\r\n */\r\n private async generateConfigLoader(): Promise<void> {\r\n const configDirectory = path.join(process.cwd(), \"src/config\");\r\n\r\n const files = await glob(\"*.{ts,tsx}\", {\r\n cwd: configDirectory,\r\n absolute: false,\r\n });\r\n\r\n const configNames = files.map((f) => f.replace(/\\.(ts|tsx)$/, \"\"));\r\n\r\n // Only `@warlock.js/core` — the one package the app itself declares. See\r\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\r\n // dependency, so a bare import of it resolved by luck under npm/yarn\r\n // hoisting and died under pnpm's strict layout.\r\n const imports: string[] = [\r\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\r\n ];\r\n const configImports: string[] = [];\r\n const configSetCalls: string[] = [];\r\n const executors: string[] = [];\r\n\r\n for (const configName of configNames) {\r\n const properConfigName = toCamelCase(configName);\r\n const varName = `${properConfigName}Config`;\r\n configImports.push(`import ${varName} from \"../../src/config/${configName}\";`);\r\n configSetCalls.push(`setConfig(\"${properConfigName}\", ${varName});`);\r\n executors.push(`await configSpecialHandlers.execute(\"${properConfigName}\", ${varName});`);\r\n }\r\n\r\n let content = [\r\n ...imports,\r\n \"\",\r\n \"// Config imports\",\r\n ...configImports,\r\n \"\",\r\n \"// Register configs\",\r\n ...configSetCalls,\r\n \"\",\r\n \"// Special handlers\",\r\n ...executors,\r\n \"\",\r\n ].join(\"\\n\");\r\n\r\n if (await fileExistsAsync(appPath(\"prestart.ts\"))) {\r\n content += \"import './../../src/app/prestart';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\r\n }\r\n\r\n /**\r\n * Generate locales.ts (only if there are locale files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateLocales(): Promise<boolean> {\r\n const files = await this.globModule(\"utils/locales\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"locales.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate events.ts (only if there are event files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateEvents(): Promise<boolean> {\r\n const files = await this.globModuleDirectory(\"events\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"events.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate main.ts (only if there are main files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateMain(): Promise<boolean> {\r\n const files = await this.globModule(\"main\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"main.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate routes.ts (only if there are route files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateRoutes(): Promise<boolean> {\r\n const files = await this.globModule(\"routes\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"routes.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate a file with imports from all given files\r\n */\r\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\r\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, outputFile), content);\r\n }\r\n\r\n /**\r\n * Generate the main entry point (app.ts)\r\n *\r\n * @param contributedImports lines from connector `generate` hooks, appended\r\n * to section 4 after `./routes`\r\n */\r\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\r\n console.log(colors.yellow(\" Generating entry point...\"));\r\n\r\n // The names this build resolved, baked in as a literal. The entry imports\r\n // the config source, and that source is re-evaluated at startup — an\r\n // env-conditional `connectors` array can hand the boot a different list\r\n // than the one drained here. A literal is the only part of the array that\r\n // survives into the artifact unchanged, so it is what the boot compares\r\n // against.\r\n const expectedNames = this.connectors\r\n .map((connector) => JSON.stringify(connector.name))\r\n .join(\", \");\r\n\r\n // Build imports based on which files were generated\r\n const imports: string[] = [\r\n \"// 1. Bootstrap (loads .env, initializes framework)\",\r\n 'import \"./bootstrap\";',\r\n \"\",\r\n \"// 2. Load configs\",\r\n 'import \"./config-loader\";',\r\n \"\",\r\n // Registration has to sit between the config being available and the\r\n // first phase starting: the connectors listed in `connectors` are the\r\n // same ones this build drained contributions from, so the bundle boots\r\n // exactly what it was built for. Register any later and an early-phase\r\n // connector would miss its own start.\r\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\r\n \"// build read its contributions from, so built-for and boots-with match).\",\r\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\r\n \"// and the array is handed over explicitly — an artifact has no\",\r\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\r\n \"// that quietly found nothing to register is the exact drift this\",\r\n \"// section exists to prevent.\",\r\n \"// `expectedNames` is the list this build resolved, in order — boot\",\r\n \"// refuses to start when the config hands over a different set or order.\",\r\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\r\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\r\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\r\n \"\",\r\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\r\n \"// own preflight is not reached until the database and cache have\",\r\n \"// connected and every app module has been imported — seconds of work\",\r\n \"// thrown away before anyone learns the port was taken. This probe is\",\r\n \"// a bind-and-release on a socket that is never served, and it reports\",\r\n \"// on stderr because no log channel is configured this early.\",\r\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\r\n \"await preflightConfiguredHttpPort();\",\r\n \"\",\r\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\r\n \"// so data sources, cache, etc. are ready before app code runs\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\r\n ];\r\n\r\n // App code uses dynamic `await import(...)` so each module's side\r\n // effects fire at THIS point in execution. Static imports would be\r\n // hoisted to module-instantiation time (before the early-phase await\r\n // resolves), which is exactly the bug this split is meant to fix.\r\n //\r\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\r\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\r\n // it at the await, not at instantiation. It does NOT come from\r\n // `splitting: true`, which only decides one-file-vs-chunks. This\r\n // previously said splitting was required; it is not, and `singleBundle`\r\n // (splitting: false) preserves the ordering.\r\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\r\n\r\n if (this.generatedFiles.events) {\r\n imports.push('await import(\"./events\");');\r\n }\r\n if (this.generatedFiles.locales) {\r\n imports.push('await import(\"./locales\");');\r\n }\r\n if (this.generatedFiles.main) {\r\n imports.push('await import(\"./main\");');\r\n }\r\n if (this.generatedFiles.routes) {\r\n imports.push('await import(\"./routes\");');\r\n }\r\n\r\n // Contributor imports come AFTER `./routes`, never before: a connector\r\n // that registers pages needs the routes app code already collected —\r\n // the same ordering dev uses (routes first, then the connector installs\r\n // on top of them). Emitted verbatim; the contributor writes the whole\r\n // statement (e.g. `await import(\"./pages\");`).\r\n imports.push(...contributedImports);\r\n\r\n // A rejecting validator (Application.onValidateBoot) must abort boot\r\n // before late-phase connectors bind a port.\r\n imports.push(\r\n \"\",\r\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\r\n \"await Application.runStartupValidators();\",\r\n );\r\n\r\n // Start late-phase connectors after app code registers routes/listeners\r\n imports.push(\r\n \"\",\r\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\r\n \"// listeners registered by app code are now ready to bind\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\r\n \"\",\r\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\r\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\r\n \"connectorsManager.shutdownOnProcessKill();\",\r\n );\r\n\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\r\n }\r\n\r\n /**\r\n * Bundle with esbuild\r\n *\r\n * @param writeOutDir the directory esbuild writes into — the build's\r\n * private temp directory, NOT `options.outdir`. Taken as a parameter\r\n * rather than read off `this.options` because the two are different paths\r\n * with different meanings: `options.outdir` is the final destination every\r\n * consumer bakes into the artifact, and this is only where bytes land\r\n * before promotion moves them there.\r\n */\r\n private async bundle(writeOutDir: string): Promise<void> {\r\n console.log(colors.magenta(\" Bundling with esbuild...\"));\r\n\r\n const entryPoint = path.join(this.productionDir, \"app.ts\");\r\n const outFileName = this.options.outFile!;\r\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\r\n const entryName = path.basename(outFileName, path.extname(outFileName));\r\n\r\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\r\n // unknown keys, and the user options are spread into its call verbatim.\r\n const singleBundle = this.options.singleBundle === true;\r\n const esmShim = this.options.esmShim !== false;\r\n // Read before deleting: the merged banner is applied AFTER the user\r\n // spread, so a user banner must not be lost to it or clobber the shim.\r\n const userBanner = this.options.banner;\r\n\r\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\r\n // resolve-build-config.ts documents that widening them pushed a lie downstream\r\n // into start-production.command.ts, which then could not trust its own config.\r\n // This is the one place they must be absent - the object is spread into esbuild's\r\n // call verbatim and esbuild throws on unknown keys.\r\n //\r\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\r\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\r\n // contribution hook, including the `emit` pass that runs AFTER this method\r\n // returns (`build()` step 5.6). Deleting these keys from the shared object\r\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\r\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\r\n // types them as present. A shallow copy is enough — every field this method\r\n // reads off it is either scalar or already re-merged below (`define`,\r\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\r\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\r\n\r\n delete esbuildOptions.outFile;\r\n delete esbuildOptions.entryPath;\r\n delete esbuildOptions.singleBundle;\r\n delete esbuildOptions.esmShim;\r\n delete esbuildOptions.banner;\r\n\r\n await ensureDirectoryAsync(writeOutDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\r\n\r\n // Whether this build decides externality per import EDGE\r\n // (`bundle-framework-dependencies.ts`, which explains the rule at\r\n // length) or keeps the blunt `packages: \"external\"`.\r\n //\r\n // Not in `singleBundle` mode: that bundles everything by definition, and\r\n // a plugin that can only ever ADD an external would silently narrow it.\r\n // Not when the user set `packages` themselves: their value has always\r\n // won over the default below, and it must keep winning — the plugin is\r\n // the default's implementation, not a new policy layered on top.\r\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\r\n\r\n // The user can override `format`, so gate the shim on the EFFECTIVE\r\n // format rather than on the default below. A CJS build already has\r\n // `require` and friends; injecting them there would be a redefinition.\r\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\r\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\r\n\r\n // Contributor patch, split into the part that can ride the spread order\r\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\r\n // BEFORE the user spread below, which gives the ruled precedence for\r\n // free: builder defaults < contributor < user config.\r\n //\r\n // `define`, `external` and `loader` are pulled out because a spread\r\n // REPLACES them wholesale — the same trap `banner` documents. Two\r\n // contributors' env defines, a contributor's optional peers plus the\r\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\r\n // must both survive, so they are merged by key/by set and re-applied\r\n // after the spread with the user still winning per key.\r\n const {\r\n define: contributedDefine,\r\n external: contributedExternal,\r\n loader: contributedLoader,\r\n ...contributedOptions\r\n } = this.contributedEsbuild;\r\n\r\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\r\n const userExternal: string[] | undefined = esbuildOptions.external;\r\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\r\n\r\n const define =\r\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\r\n\r\n const loader =\r\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\r\n\r\n const external =\r\n contributedExternal || userExternal\r\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\r\n : undefined;\r\n\r\n if (singleBundle) {\r\n console.log(\r\n colors.magenta(\r\n \" Single-bundle mode — one JS file\" +\r\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\r\n \". Native .node addons are still emitted alongside it.\",\r\n ),\r\n );\r\n }\r\n\r\n try {\r\n await esbuild.build({\r\n platform: \"node\",\r\n entryPoints: [entryPoint],\r\n bundle: true,\r\n // Both are DEFAULTS the user can override — they sit before the\r\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\r\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\r\n //\r\n // Phase ordering does not depend on `splitting`: it comes from the\r\n // generated app.ts using dynamic `await import(...)` (see\r\n // generateAppEntry above), which esbuild defers to the call site in\r\n // either mode. Splitting only decides one file vs chunks.\r\n splitting: !singleBundle,\r\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\r\n // the plugin below returns `external: true` for every bare specifier\r\n // this build must not bundle, which is all of them bar the framework's\r\n // own declared dependencies. Saying `\"external\"` here instead would\r\n // externalise them before the plugin could rule.\r\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\r\n minify: esbuildOptions.minify,\r\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\r\n format: \"esm\",\r\n // Targeting a concrete Node version (not \"esnext\") so esbuild\r\n // transpiles TC39 stage 3 decorators into helpers — Node does not\r\n // implement them natively yet.\r\n target: [\"node22\"],\r\n entryNames: entryName,\r\n alias,\r\n plugins: [\r\n nativeNodeModulesPlugin,\r\n // BEFORE the framework-dependency plugin, and the order is\r\n // load-bearing: the first `onResolve` callback to answer wins, and\r\n // `app/users/...` is a bare specifier the other one would rule\r\n // external.\r\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\r\n ...(perEdgeExternals\r\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\r\n : []),\r\n ],\r\n // Between the defaults and the user spread — the ruled precedence.\r\n ...contributedOptions,\r\n ...(esbuildOptions as any),\r\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\r\n // that spread carrying the FINAL destination, which is exactly where\r\n // this build must not write yet. The final path is the user's setting\r\n // and stays authoritative for everyone reading the config — it is only\r\n // this one esbuild call that is redirected, and only until promotion\r\n // moves the result onto that very path.\r\n outdir: writeOutDir,\r\n // AFTER the spread for the same reason `banner` is: a spread replaces\r\n // these objects instead of merging them, so the merged values are\r\n // re-applied here. The user still wins — they were merged in last.\r\n ...(define ? { define } : {}),\r\n ...(external ? { external } : {}),\r\n ...(loader ? { loader } : {}),\r\n // AFTER the spread, and intentionally so: `banner` is an object, and\r\n // both the config merge and this spread REPLACE it wholesale rather\r\n // than merging. Left as a default above, any user banner would delete\r\n // the shim; left to the spread, the shim would delete theirs. The\r\n // merge is the only form that keeps both.\r\n ...(banner ? { banner } : {}),\r\n });\r\n } catch (e) {\r\n console.log(e);\r\n throw e;\r\n }\r\n }\r\n\r\n /**\r\n * The WILDCARD half of the same tsconfig `paths` map that\r\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\r\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\r\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\r\n * so the entries it skips have to be resolved by a plugin instead of being\r\n * left to no one.\r\n */\r\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\r\n tsconfigManager.init();\r\n\r\n return {\r\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\r\n paths: tsconfigManager.aliases as Record<string, string[]>,\r\n };\r\n }\r\n\r\n /**\r\n * Build an alias map from tsconfig `paths` so esbuild resolves local\r\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\r\n * folders during bundling. Without this, `packages: \"external\"` would\r\n * leave those bare specifiers as raw imports and Node would fail to\r\n * resolve them at runtime (they aren't installed in node_modules).\r\n *\r\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\r\n * option doesn't support glob-style mappings. The wildcard half is not\r\n * dropped, it is handled elsewhere: see\r\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\r\n */\r\n private buildAliasMapFromTsconfig(): Record<string, string> {\r\n tsconfigManager.init();\r\n\r\n const alias: Record<string, string> = {};\r\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\r\n\r\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\r\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\r\n continue;\r\n }\r\n\r\n const target = to[0];\r\n\r\n if (target === undefined) {\r\n continue;\r\n }\r\n\r\n alias[from] = path.resolve(baseUrl, target);\r\n }\r\n\r\n return alias;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,MACoC;CACpC,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,SAAS,YAAY;CAE3B,OAAO;EACL,GAAG;EACH,IAAI,SAAS,GAAG,OAAO,WAAW;CACpC;AACF;;;;;;;;;;AAWA,MAAM,+BAA+B;;;;;;AAOrC,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;oBAOd,CAAC;4BAMQ,CAAC;wBA4M5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAlLA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA8B,CAAC;EAMvD,4BAA4B;EAG5B,MAAM,KAAK,kBAAkB;EAE7B,MAAM,cAAc,KAAK,QAAQ;EACjC,MAAM,aAAa,oBAAoB,WAAW;EAKlD,IAAI;EAEJ,IAAI;GAEF,MAAM,KAAK,sBAAsB;GAGjC,MAAM,KAAK,mBAAmB;GAG9B,MAAM,KAAK,uBAAuB;GAclC,IAAI,MAXsB,KAAK,yBAAyB,GAYtD,MAAM,KAAK,uBAAuB;GAKpC,MAAM,KAAK,OAAO,UAAU;GAK5B,SAAS,MAAM,eAAe,YAAY,WAAW;GAMrD,MAAM,qBAAqB,KAAK,YAAY,KAAK,aAAa,CAAC;GAM/D,MAAM,4BAA4B,WAAW;GAG7C,MAAM,gBAAgB,MAAM;EAC9B,SAAS,OAAO;GACd,IAAI,QAGF,MAAM,kBAAkB,MAAM;QAI9B,MAAM,qBAA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D,GAAI,mBACA,CAAC,4BAA4B;MAAE,SAAS,SAAS;MAAG,WAAW,OAAO,KAAK,KAAK;KAAE,CAAC,CAAC,IACpF,CAAC;IACP;IAEA,GAAG;IACH,GAAI;IAOJ,QAAQ;IAIR,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAC3B,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAC/B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAM3B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAC7B,CAAC;EACH,SAAS,GAAG;GACV,QAAQ,IAAI,CAAC;GACb,MAAM;EACR;CACF;;;;;;;;;CAUA,AAAQ,0BAAgF;EACtF,gBAAgB,KAAK;EAErB,OAAO;GACL,SAAS,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;GAC5D,OAAO,gBAAgB;EACzB;CACF;;;;;;;;;;;;;CAcA,AAAQ,4BAAoD;EAC1D,gBAAgB,KAAK;EAErB,MAAM,QAAgC,CAAC;EACvC,MAAM,UAAU,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;EAEnE,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,gBAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,SAAS,GAAG;GAElB,IAAI,WAAW,QACb;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,MAAM;EAC5C;EAEA,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport {\n ensureDirectoryAsync,\n fileExistsAsync,\n getFileAsync,\n getJsonFileAsync,\n putFileAsync,\n removeDirectoryAsync,\n} from \"@warlock.js/fs\";\nimport esbuild from \"esbuild\";\nimport glob from \"fast-glob\";\nimport path from \"path\";\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\nimport { configKeyFromPath } from \"../config/config-key-from-path\";\nimport { isConfigFile, isEventFile, isLocaleFile, isMainFile, isRouteFile } from \"../dev-server/special-file-patterns\";\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\nimport { appPath, rootPath, warlockPath } from \"../utils\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\nimport { bundleFrameworkDependencies } from \"./bundle-framework-dependencies\";\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\nimport { assertEsbuildBinaryIsLinked } from \"./esbuild-preflight\";\nimport { collectRouteRegistrationSnapshot } from \"./route-registration-snapshot\";\nimport { clearOwnedRouteTypes } from \"../dev-server/route-types-publisher\";\nimport {\n commitDistAsync,\n createTempOutputDir,\n rollbackDistAsync,\n stageDistAsync,\n type StagedDist,\n} from \"./promote-dist\";\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\nimport { tsconfigPathAliases } from \"./tsconfig-path-aliases\";\nimport { toKebabCase } from \"@mongez/reinforcements\";\n\n/**\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\n *\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\n * esbuild substitutes a stub that throws — **after the build has reported\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\n * firing, and it is the defect this shim removes.\n *\n * `__dirname` matters as much as `require`: without it a dependency resolving\n * an asset path silently gets `undefined` and fails later, further from the\n * cause.\n *\n * Written as one line because esbuild inserts a banner verbatim above the\n * bundle and a multi-line string here would shift every mapped line.\n */\nconst ESM_INTEROP_SHIM =\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\n \"import{dirname as __wlDirname}from'node:path';\" +\n \"const require=__wlCreateRequire(import.meta.url);\" +\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\n \"const __dirname=__wlDirname(__filename);\";\n\n/**\n * Combine the framework's banner with the user's, keeping both.\n *\n * esbuild's `banner` is an object keyed by output type, and every merge in the\n * path to it — the config merge and the options spread — REPLACES that object\n * rather than merging it. So whichever is applied second silently deletes the\n * other. This is the only place the two can coexist.\n *\n * The shim goes first: it defines `require`, which a user banner may use.\n *\n * @param userBanner banner from `warlock.config.ts`, if any\n * @param shim the interop shim, or undefined when it does not apply\n */\nfunction mergeBanner(\n userBanner: Record<string, string> | undefined,\n shim: string | undefined,\n): Record<string, string> | undefined {\n if (!shim) return userBanner;\n\n const userJs = userBanner?.js;\n\n return {\n ...userBanner,\n js: userJs ? `${shim}${userJs}` : shim,\n };\n}\n\n/**\n * Prefix every generated file uses to reach the app root.\n *\n * Generated sources are written into `.warlock/production/`, two levels below\n * the app root, so `../../` lands back on it — the same hop already spelled\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\n * config-loader generators emit. Named once so a generator that needs a new\n * app-root file (`warlock.config`) cannot pick a different depth.\n */\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\n\n/**\n * Production Builder\n * Generates production-ready files and bundles them for deployment\n * Build options are loaded from warlock.config.ts\n */\nexport class ProductionBuilder {\n private options!: ResolvedBuildConfig;\n private readonly productionDir = warlockPath(\"production\");\n\n /**\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\n * never calls `boot()`/`start()` on them; it only\n * drains their `build` contributions.\n */\n private connectors: readonly Connector[] = [];\n\n /**\n * The contributors' merged esbuild patch, produced by the `generate` pass\n * and consumed by {@link bundle}.\n */\n private contributedEsbuild: ConnectorEsbuildPatch = {};\n\n /** Browser-safe API metadata captured in a fresh registration-only child. */\n private namedApiRoutes?: readonly import(\"../router/types\").NamedApiRoute[];\n\n /**\n * Main build entry point\n *\n * The esbuild bundle is written into a TEMP directory next to the real\n * output directory, never into it, and that directory is renamed over\n * `outdir` as one filesystem operation — so `outdir` is never observed as\n * a mix of the old build and the new one, and a build that fails before\n * that rename never touches `outdir` at all.\n *\n * `this.options.outdir` is NOT repointed at the temp directory while that\n * happens, and must never be. It is not merely a write target: consumers\n * BAKE it into runtime output — `web`'s build contribution derives the\n * `clientDir` recorded in its pages manifest from it\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\n * produces an artifact whose browser paths point at a directory promotion\n * has since renamed away. The temp path is passed explicitly, as a\n * parameter, to the one operation that writes into it ({@link bundle});\n * everything else, `buildContext()` included, keeps reading the final\n * destination.\n *\n * That is also why promotion is STAGED rather than done at the very end.\n * Connector `emit` hooks write real artifacts (the web client bundle) and\n * see the final `outdir`, so they must run when `outdir` genuinely holds\n * this build — after the rename, not before it, or promotion would replace\n * the directory they just wrote into. The previous build is kept parked\n * aside until they finish: `emit` throwing rolls the whole promotion back,\n * and the build-success marker `warlock start` checks is written last of\n * all, so a failure at any point leaves no `dist` that start will boot.\n */\n public async build(): Promise<void> {\n console.log(colors.cyan(\"Building for production...\\n\"));\n\n // Step 0: Fail fast when esbuild's native binary never got linked (the\n // state pnpm leaves a project in when its build-script approval gate\n // blocked esbuild's postinstall) rather than let bundling die on esbuild's\n // own cryptic \"package could not be found\" error several steps from now.\n assertEsbuildBinaryIsLinked();\n\n // Step 1: Initialize options from config\n await this.initializeOptions();\n\n const finalOutDir = this.options.outdir!;\n const tempOutDir = createTempOutputDir(finalOutDir);\n\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\n // presence is what tells the catch below whether a failure has a\n // promotion to undo or only a temp directory to discard.\n let staged: StagedDist | undefined;\n\n try {\n // Step 2: Generate combined files\n await this.generateCombinedFiles();\n\n // Step 3: Generate entry point\n await this.generateEntryPoint();\n\n // Step 4: Refuse to bundle code the app could not resolve at runtime\n await this.assertGeneratedImports();\n\n // Step 4.5: Drain the connectors' `generate` contributions\n await this.captureNamedApiRoutesForWeb();\n const contributed = await this.runGenerateContributions();\n\n // Step 4.6: Re-assert over what the contributors just wrote.\n //\n // Step 4 only saw core's own generated files; a contributor writes its\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\n // specifier in it reaches the bundle unchecked. Under\n // `packages: \"external\"` that specifier survives verbatim into the\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\n // and re-reading the production dir is pure cost in the common case.\n if (contributed) {\n await this.assertGeneratedImports();\n }\n\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\n // operation handed that path — it is a write target, not config.\n await this.bundle(tempOutDir);\n\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\n // build parked aside. `outdir` now holds exactly this build, so the\n // steps below write into — and record — the real destination.\n staged = await stageDistAsync(tempOutDir, finalOutDir);\n\n // Step 5.6: Drain the connectors' `emit` contributions — after the\n // bundle is in place (so what they write survives promotion and the\n // paths they bake in resolve), and BEFORE step 6 deletes the\n // production directory they may still read.\n await runEmitContributions(this.connectors, this.buildContext());\n\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\n // `warlock start` trusts. Written LAST on purpose: every earlier step\n // can still fail, and until this file exists nothing will boot what\n // they left behind.\n await writeDistBuildManifestAsync(finalOutDir);\n\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\n await commitDistAsync(staged);\n } catch (error) {\n if (staged) {\n // The promotion already happened; put the previous build back and\n // take this half-finished one out of `outdir`.\n await rollbackDistAsync(staged);\n } else {\n // Nothing this build produced ever reached `outdir` — discard the\n // temp directory and leave `outdir` exactly as it was.\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\n }\n\n throw error;\n }\n\n // Step 6: Remove production folder\n await removeDirectoryAsync(this.productionDir);\n\n console.log(colors.green(\"Build complete!\"));\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\n }\n\n /**\n * Initialize options from warlock.config.ts\n */\n private async initializeOptions(): Promise<void> {\n this.options = resolveBuildConfig();\n // Same config object `resolveBuildConfig` just read — `warlock build`\n // preloads warlock.config.ts, so no additional load happens here.\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\n\n // Checked here, where the array is first read, so nothing downstream has\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\n // a name listed twice would write its files and merge its esbuild options\n // twice into an artifact the runtime then boots that name only once from.\n // A build that half-applied a connector and reported success is worse than\n // one that never started.\n assertUniqueConnectorNames([...connectors]);\n\n // And here rather than only at boot, for the same reason: a name a built-in\n // already owns is skipped by the runtime, so an artifact built from it\n // carries the custom connector's generated files and esbuild patches while\n // the server boots the built-in instead. Refusing it at boot alone would\n // mean the build had already emitted that artifact — the failure has to\n // land on the developer running `warlock build`, not on whoever starts the\n // server. Same assertion the registration half calls, over the same names.\n assertNoReservedConnectorNames([...connectors]);\n\n this.connectors = connectors;\n\n // Ensure production directory exists\n await ensureDirectoryAsync(this.productionDir);\n }\n\n /**\n * The context handed to every build contribution.\n */\n private buildContext(): ConnectorBuildContext {\n return {\n productionDir: this.productionDir,\n appRoot: rootPath(),\n options: this.options,\n namedApiRoutes: this.namedApiRoutes,\n };\n }\n\n /**\n * Web route declarations need application API registration, which cannot be\n * inferred from generated files. Capture it once in a disposable child before\n * contributors write build artifacts; no connector lifecycle runs there.\n */\n private async captureNamedApiRoutesForWeb(): Promise<void> {\n if (!this.connectors.some((connector) => connector.name === \"web\")) {\n await clearOwnedRouteTypes(rootPath());\n return;\n }\n\n this.namedApiRoutes = (await collectRouteRegistrationSnapshot({ cwd: rootPath() })).routes;\n }\n\n /**\n * Drain the `generate` hooks and fold what they returned back into the\n * build.\n *\n * The entry point is REGENERATED here rather than generated later. The\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\n * bundles that the app could not resolve) and before `bundle` — while\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\n * generated code the assertion has to see; moving it past the assertion\n * would silently drop the entry from that check. Rewriting one small file\n * is cheaper than losing either guarantee, and the write is pure\n * (`generatedFiles` + these imports), so doing it twice is not a\n * correctness risk.\n *\n * @returns whether any connector ran a `generate` hook — the caller uses it\n * to decide if the import assertion is worth a second pass. Keyed on the\n * hook EXISTING, not on what it returned: a hook that returns nothing may\n * still have written files into `productionDir`, and those are exactly the\n * files the second pass is there to read.\n */\n private async runGenerateContributions(): Promise<boolean> {\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\n\n const { entryImports, esbuild } = await runGenerateContributions(\n this.connectors,\n this.buildContext(),\n );\n\n this.contributedEsbuild = esbuild;\n\n if (entryImports.length > 0) {\n await this.generateEntryPoint(entryImports);\n }\n\n return contributed;\n }\n\n /**\n * Track which special files were generated\n */\n private generatedFiles = {\n locales: false,\n events: false,\n main: false,\n routes: false,\n };\n\n /**\n * Generate all combined files\n */\n private async generateCombinedFiles(): Promise<void> {\n console.log(colors.yellow(\" Generating production files...\"));\n\n // Generate bootstrap.ts file\n await this.generateBootstrap();\n\n // Generate config loader\n await this.generateConfigLoader();\n\n // Generate special files and track which ones have content\n const [locales, events, main, routes] = await Promise.all([\n this.generateLocales(),\n this.generateEvents(),\n this.generateMain(),\n this.generateRoutes(),\n ]);\n\n this.generatedFiles = { locales, events, main, routes };\n }\n\n /**\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\n */\n private async generateBootstrap(): Promise<void> {\n // ESM hoists imports, so the app bootstrap must be the first import to run first\n const appBootstrapImport = (await fileExistsAsync(appPath(\"bootstrap.ts\")))\n ? \"import './../../src/app/bootstrap';\\n\"\n : \"\";\n\n const content = `${appBootstrapImport}import { bootstrap, Application } from \"@warlock.js/core\";\n\n// Production runtime; NODE_ENV is only defaulted so an explicit value (e.g. staging) wins\nApplication.setRuntimeStrategy(\"production\");\nif (!process.env.NODE_ENV) {\n Application.setEnvironment(\"production\");\n}\n\n// Bootstrap the application\nbootstrap();\n`;\n\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\n }\n\n /**\n * Fail the build when generated code imports a package the app does not\n * declare.\n *\n * The bundler is configured `packages: \"external\"`, so every bare specifier\n * written above survives verbatim into an artifact that resolves against the\n * **consuming app's** node_modules. A framework-internal dependency imported\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\n * which is how a production app shipped that could not boot. Rewriting the\n * offending import fixes today's bundle; this check is what stops the next\n * change to the generator from quietly reintroducing it.\n */\n private async assertGeneratedImports(): Promise<void> {\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\n cwd: this.productionDir,\n absolute: false,\n });\n\n const [files, appPackage] = await Promise.all([\n Promise.all(\n generatedPaths.map(async (file) => ({\n file,\n content: await getFileAsync(path.join(this.productionDir, file)),\n })),\n ),\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\n ]);\n\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\n }\n\n /**\n * Glob `src/app` and keep the files the shared dev-server predicate accepts,\n * so production discovers exactly what the dev collector does.\n * Returns relative paths from .warlock/production/ to src/app/\n */\n private async globModule(matches: (relativePath: string) => boolean): Promise<string[]> {\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: appPath(),\n absolute: false,\n });\n\n // e.g., \"users/main.ts\" -> \"../../src/app/users/main\"\n return files\n .filter((file) => matches(\"src/app/\" + file))\n .sort()\n .map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\n }\n\n /**\n * Generate config-loader.ts\n */\n private async generateConfigLoader(): Promise<void> {\n const configDirectory = path.join(process.cwd(), \"src/config\");\n\n const files = await glob(\"**/*.{ts,tsx}\", {\n cwd: configDirectory,\n absolute: false,\n });\n\n // Same key rule as the dev config loader: the raw path, never camel-cased\n const configNames = files\n .filter((f) => isConfigFile(\"src/config/\" + f))\n .map((f) => ({\n path: f.replace(/\\.(ts|tsx)$/, \"\"),\n key: configKeyFromPath(\"src/config/\" + f),\n }))\n .filter((entry): entry is { path: string; key: string } => entry.key !== undefined)\n .sort((a, b) => a.path.localeCompare(b.path));\n\n // Only `@warlock.js/core` — the one package the app itself declares. See\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\n // dependency, so a bare import of it resolved by luck under npm/yarn\n // hoisting and died under pnpm's strict layout.\n const imports: string[] = [\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\n ];\n const configImports: string[] = [];\n const configSetCalls: string[] = [];\n const executors: string[] = [];\n\n configNames.forEach(({ path: configPath, key }, index) => {\n // Index-based identifier: keys like \"rate-limit\" or \"mail/smtp\" are not valid names\n const varName = `config${index}`;\n configImports.push(`import ${varName} from \"../../src/config/${configPath}\";`);\n configSetCalls.push(`setConfig(${JSON.stringify(key)}, ${varName});`);\n executors.push(`await configSpecialHandlers.execute(${JSON.stringify(key)}, ${varName});`);\n });\n\n // ESM hoists imports, so prestart must be the first import to run first\n const prestartImports = (await fileExistsAsync(appPath(\"prestart.ts\")))\n ? [\"import './../../src/app/prestart';\"]\n : [];\n\n const content = [\n ...prestartImports,\n ...imports,\n \"\",\n \"// Config imports\",\n ...configImports,\n \"\",\n \"// Register configs\",\n ...configSetCalls,\n \"\",\n \"// Special handlers\",\n ...executors,\n \"\",\n ].join(\"\\n\");\n\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\n }\n\n /**\n * Generate locales.ts (only if there are locale files)\n * @returns true if file was generated with content\n */\n private async generateLocales(): Promise<boolean> {\n const files = await this.globModule(isLocaleFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"locales.ts\");\n return true;\n }\n\n /**\n * Generate events.ts (only if there are event files)\n * @returns true if file was generated with content\n */\n private async generateEvents(): Promise<boolean> {\n const files = await this.globModule(isEventFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"events.ts\");\n return true;\n }\n\n /**\n * Generate main.ts (only if there are main files)\n * @returns true if file was generated with content\n */\n private async generateMain(): Promise<boolean> {\n const files = await this.globModule(isMainFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"main.ts\");\n return true;\n }\n\n /**\n * Generate routes.ts (only if there are route files)\n * @returns true if file was generated with content\n */\n private async generateRoutes(): Promise<boolean> {\n const files = await this.globModule(isRouteFile);\n if (files.length === 0) return false;\n await this.generateImportsFile(files, \"routes.ts\");\n return true;\n }\n\n /**\n * Generate a file with imports from all given files\n */\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, outputFile), content);\n }\n\n /**\n * Generate the main entry point (app.ts)\n *\n * @param contributedImports lines from connector `generate` hooks, appended\n * to section 4 after `./routes`\n */\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\n console.log(colors.yellow(\" Generating entry point...\"));\n\n // The names this build resolved, baked in as a literal. The entry imports\n // the config source, and that source is re-evaluated at startup — an\n // env-conditional `connectors` array can hand the boot a different list\n // than the one drained here. A literal is the only part of the array that\n // survives into the artifact unchanged, so it is what the boot compares\n // against.\n const expectedNames = this.connectors\n .map((connector) => JSON.stringify(connector.name))\n .join(\", \");\n\n // Build imports based on which files were generated\n const imports: string[] = [\n \"// 1. Bootstrap (loads .env, initializes framework)\",\n 'import \"./bootstrap\";',\n \"\",\n \"// 2. Load configs\",\n 'import \"./config-loader\";',\n \"\",\n // Registration has to sit between the config being available and the\n // first phase starting: the connectors listed in `connectors` are the\n // same ones this build drained contributions from, so the bundle boots\n // exactly what it was built for. Register any later and an early-phase\n // connector would miss its own start.\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\n \"// build read its contributions from, so built-for and boots-with match).\",\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\n \"// and the array is handed over explicitly — an artifact has no\",\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\n \"// that quietly found nothing to register is the exact drift this\",\n \"// section exists to prevent.\",\n \"// `expectedNames` is the list this build resolved, in order — boot\",\n \"// refuses to start when the config hands over a different set or order.\",\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\n \"\",\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\n \"// own preflight is not reached until the database and cache have\",\n \"// connected and every app module has been imported — seconds of work\",\n \"// thrown away before anyone learns the port was taken. This probe is\",\n \"// a bind-and-release on a socket that is never served, and it reports\",\n \"// on stderr because no log channel is configured this early.\",\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\n \"await preflightConfiguredHttpPort();\",\n \"\",\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\n \"// so data sources, cache, etc. are ready before app code runs\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\n ];\n\n // App code uses dynamic `await import(...)` so each module's side\n // effects fire at THIS point in execution. Static imports would be\n // hoisted to module-instantiation time (before the early-phase await\n // resolves), which is exactly the bug this split is meant to fix.\n //\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\n // it at the await, not at instantiation. It does NOT come from\n // `splitting: true`, which only decides one-file-vs-chunks. This\n // previously said splitting was required; it is not, and `singleBundle`\n // (splitting: false) preserves the ordering.\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\n\n if (this.generatedFiles.events) {\n imports.push('await import(\"./events\");');\n }\n if (this.generatedFiles.locales) {\n imports.push('await import(\"./locales\");');\n }\n if (this.generatedFiles.main) {\n imports.push('await import(\"./main\");');\n }\n if (this.generatedFiles.routes) {\n imports.push('await import(\"./routes\");');\n }\n\n // Contributor imports come AFTER `./routes`, never before: a connector\n // that registers pages needs the routes app code already collected —\n // the same ordering dev uses (routes first, then the connector installs\n // on top of them). Emitted verbatim; the contributor writes the whole\n // statement (e.g. `await import(\"./pages\");`).\n imports.push(...contributedImports);\n\n // A rejecting validator (Application.onValidateBoot) must abort boot\n // before late-phase connectors bind a port.\n imports.push(\n \"\",\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\n \"await Application.runStartupValidators();\",\n );\n\n // Start late-phase connectors after app code registers routes/listeners\n imports.push(\n \"\",\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\n \"// listeners registered by app code are now ready to bind\",\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\n \"\",\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\n \"connectorsManager.shutdownOnProcessKill();\",\n );\n\n const content = imports.join(\"\\n\") + \"\\n\";\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\n }\n\n /**\n * Bundle with esbuild\n *\n * @param writeOutDir the directory esbuild writes into — the build's\n * private temp directory, NOT `options.outdir`. Taken as a parameter\n * rather than read off `this.options` because the two are different paths\n * with different meanings: `options.outdir` is the final destination every\n * consumer bakes into the artifact, and this is only where bytes land\n * before promotion moves them there.\n */\n private async bundle(writeOutDir: string): Promise<void> {\n console.log(colors.magenta(\" Bundling with esbuild...\"));\n\n const entryPoint = path.join(this.productionDir, \"app.ts\");\n const outFileName = this.options.outFile!;\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\n const entryName = path.basename(outFileName, path.extname(outFileName));\n\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\n // unknown keys, and the user options are spread into its call verbatim.\n const singleBundle = this.options.singleBundle === true;\n const esmShim = this.options.esmShim !== false;\n // Read before deleting: the merged banner is applied AFTER the user\n // spread, so a user banner must not be lost to it or clobber the shim.\n const userBanner = this.options.banner;\n\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\n // resolve-build-config.ts documents that widening them pushed a lie downstream\n // into start-production.command.ts, which then could not trust its own config.\n // This is the one place they must be absent - the object is spread into esbuild's\n // call verbatim and esbuild throws on unknown keys.\n //\n // Stripped off a LOCAL COPY of `this.options`, never off `this.options`\n // itself: `buildContext()` hands `this.options` to every `generate`/`emit`\n // contribution hook, including the `emit` pass that runs AFTER this method\n // returns (`build()` step 5.6). Deleting these keys from the shared object\n // used to leave those hooks reading `undefined` for `outFile`, `entryPath`,\n // `singleBundle`, `esmShim` and `banner` even though `ConnectorBuildContext`\n // types them as present. A shallow copy is enough — every field this method\n // reads off it is either scalar or already re-merged below (`define`,\n // `external`, `loader`, `banner`), so nothing here needs a deep clone.\n const esbuildOptions: Partial<ResolvedBuildConfig> = { ...this.options };\n\n delete esbuildOptions.outFile;\n delete esbuildOptions.entryPath;\n delete esbuildOptions.singleBundle;\n delete esbuildOptions.esmShim;\n delete esbuildOptions.banner;\n\n await ensureDirectoryAsync(writeOutDir);\n\n const alias = this.buildAliasMapFromTsconfig();\n\n // Whether this build decides externality per import EDGE\n // (`bundle-framework-dependencies.ts`, which explains the rule at\n // length) or keeps the blunt `packages: \"external\"`.\n //\n // Not in `singleBundle` mode: that bundles everything by definition, and\n // a plugin that can only ever ADD an external would silently narrow it.\n // Not when the user set `packages` themselves: their value has always\n // won over the default below, and it must keep winning — the plugin is\n // the default's implementation, not a new policy layered on top.\n const perEdgeExternals = !singleBundle && (esbuildOptions as any).packages === undefined;\n\n // The user can override `format`, so gate the shim on the EFFECTIVE\n // format rather than on the default below. A CJS build already has\n // `require` and friends; injecting them there would be a redefinition.\n const isEsm = (esbuildOptions.format ?? \"esm\") === \"esm\";\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\n\n // Contributor patch, split into the part that can ride the spread order\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\n // BEFORE the user spread below, which gives the ruled precedence for\n // free: builder defaults < contributor < user config.\n //\n // `define`, `external` and `loader` are pulled out because a spread\n // REPLACES them wholesale — the same trap `banner` documents. Two\n // contributors' env defines, a contributor's optional peers plus the\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\n // must both survive, so they are merged by key/by set and re-applied\n // after the spread with the user still winning per key.\n const {\n define: contributedDefine,\n external: contributedExternal,\n loader: contributedLoader,\n plugins: contributedPlugins,\n ...contributedOptions\n } = this.contributedEsbuild;\n\n const userDefine: Record<string, string> | undefined = esbuildOptions.define;\n const userExternal: string[] | undefined = esbuildOptions.external;\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = esbuildOptions.loader;\n\n const define =\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\n\n const loader =\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\n\n const external =\n contributedExternal || userExternal\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\n : undefined;\n\n if (singleBundle) {\n console.log(\n colors.magenta(\n \" Single-bundle mode — one JS file\" +\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\n \". Native .node addons are still emitted alongside it.\",\n ),\n );\n }\n\n try {\n await esbuild.build({\n platform: \"node\",\n entryPoints: [entryPoint],\n bundle: true,\n // Both are DEFAULTS the user can override — they sit before the\n // `...esbuildOptions` spread deliberately. `singleBundle` moves them,\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\n //\n // Phase ordering does not depend on `splitting`: it comes from the\n // generated app.ts using dynamic `await import(...)` (see\n // generateAppEntry above), which esbuild defers to the call site in\n // either mode. Splitting only decides one file vs chunks.\n splitting: !singleBundle,\n // `\"bundle\"` under `perEdgeExternals` is not \"bundle everything\":\n // the plugin below returns `external: true` for every bare specifier\n // this build must not bundle, which is all of them bar the framework's\n // own declared dependencies. Saying `\"external\"` here instead would\n // externalise them before the plugin could rule.\n packages: singleBundle || perEdgeExternals ? \"bundle\" : \"external\",\n minify: esbuildOptions.minify,\n sourcemap: esbuildOptions.sourcemap === true ? \"linked\" : esbuildOptions.sourcemap,\n format: \"esm\",\n // Targeting a concrete Node version (not \"esnext\") so esbuild\n // transpiles TC39 stage 3 decorators into helpers — Node does not\n // implement them natively yet.\n target: [\"node22\"],\n entryNames: entryName,\n alias,\n plugins: [\n nativeNodeModulesPlugin,\n // BEFORE the framework-dependency plugin, and the order is\n // load-bearing: the first `onResolve` callback to answer wins, and\n // `app/users/...` is a bare specifier the other one would rule\n // external.\n tsconfigPathAliases(this.tsconfigPathAliasConfig()),\n ...(perEdgeExternals\n ? [bundleFrameworkDependencies({ appRoot: rootPath(), aliasKeys: Object.keys(alias) })]\n : []),\n // Contributor plugins run last: they load their own file types and\n // must not shadow the resolvers above.\n ...(contributedPlugins ?? []),\n ],\n // Between the defaults and the user spread — the ruled precedence.\n ...contributedOptions,\n ...(esbuildOptions as any),\n // AFTER the spread, and NOT overridable: `esbuildOptions.outdir` rides\n // that spread carrying the FINAL destination, which is exactly where\n // this build must not write yet. The final path is the user's setting\n // and stays authoritative for everyone reading the config — it is only\n // this one esbuild call that is redirected, and only until promotion\n // moves the result onto that very path.\n outdir: writeOutDir,\n // AFTER the spread for the same reason `banner` is: a spread replaces\n // these objects instead of merging them, so the merged values are\n // re-applied here. The user still wins — they were merged in last.\n ...(define ? { define } : {}),\n ...(external ? { external } : {}),\n ...(loader ? { loader } : {}),\n // AFTER the spread, and intentionally so: `banner` is an object, and\n // both the config merge and this spread REPLACE it wholesale rather\n // than merging. Left as a default above, any user banner would delete\n // the shim; left to the spread, the shim would delete theirs. The\n // merge is the only form that keeps both.\n ...(banner ? { banner } : {}),\n });\n } catch (e) {\n console.log(e);\n throw e;\n }\n }\n\n /**\n * The WILDCARD half of the same tsconfig `paths` map that\n * {@link ProductionBuilder.buildAliasMapFromTsconfig} reads the exact half\n * of. `tsconfig-path-aliases.ts` explains why the two halves need different\n * mechanisms — in short, esbuild's `alias` option cannot express a wildcard,\n * so the entries it skips have to be resolved by a plugin instead of being\n * left to no one.\n */\n private tsconfigPathAliasConfig(): { baseUrl: string; paths: Record<string, string[]> } {\n tsconfigManager.init();\n\n return {\n baseUrl: path.resolve(process.cwd(), tsconfigManager.baseUrl),\n paths: tsconfigManager.aliases as Record<string, string[]>,\n };\n }\n\n /**\n * Build an alias map from tsconfig `paths` so esbuild resolves local\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\n * folders during bundling. Without this, `packages: \"external\"` would\n * leave those bare specifiers as raw imports and Node would fail to\n * resolve them at runtime (they aren't installed in node_modules).\n *\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\n * option doesn't support glob-style mappings. The wildcard half is not\n * dropped, it is handled elsewhere: see\n * {@link ProductionBuilder.tsconfigPathAliasConfig}.\n */\n private buildAliasMapFromTsconfig(): Record<string, string> {\n tsconfigManager.init();\n\n const alias: Record<string, string> = {};\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\n\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\n continue;\n }\n\n const target = to[0];\n\n if (target === undefined) {\n continue;\n }\n\n alias[from] = path.resolve(baseUrl, target);\n }\n\n return alias;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,mBACJ;;;;;;;;;;;;;;AAoBF,SAAS,YACP,YACA,MACoC;CACpC,IAAI,CAAC,MAAM,OAAO;CAElB,MAAM,SAAS,YAAY;CAE3B,OAAO;EACL,GAAG;EACH,IAAI,SAAS,GAAG,OAAO,WAAW;CACpC;AACF;;;;;;;;;;AAWA,MAAM,+BAA+B;;;;;;AAOrC,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;oBAOd,CAAC;4BAMQ,CAAC;wBA+N5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAlMA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KA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OAAO,IAAI,CAAC;IAM3B,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;GAC7B,CAAC;EACH,SAAS,GAAG;GACV,QAAQ,IAAI,CAAC;GACb,MAAM;EACR;CACF;;;;;;;;;CAUA,AAAQ,0BAAgF;EACtF,gBAAgB,KAAK;EAErB,OAAO;GACL,SAAS,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;GAC5D,OAAO,gBAAgB;EACzB;CACF;;;;;;;;;;;;;CAcA,AAAQ,4BAAoD;EAC1D,gBAAgB,KAAK;EAErB,MAAM,QAAgC,CAAC;EACvC,MAAM,UAAU,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;EAEnE,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,gBAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,SAAS,GAAG;GAElB,IAAI,WAAW,QACb;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,MAAM;EAC5C;EAEA,OAAO;CACT;AACF"}
@@ -70,6 +70,7 @@ function superviseProductionProcess({ nodeArgs, cwd = process.cwd(), env = proce
70
70
  clearTimeout(readinessNoticeTimer);
71
71
  process.off("SIGTERM", onSigterm);
72
72
  process.off("SIGINT", onSigint);
73
+ process.off("SIGHUP", onSighup);
73
74
  resolve(result);
74
75
  };
75
76
  child.on("message", (message) => {
@@ -88,16 +89,22 @@ function superviseProductionProcess({ nodeArgs, cwd = process.cwd(), env = proce
88
89
  ready: false
89
90
  });
90
91
  });
91
- const onSigterm = () => {
92
- if (isShuttingDown) return;
92
+ const forward = (signal) => () => {
93
+ if (isShuttingDown) {
94
+ child.kill("SIGKILL");
95
+ return;
96
+ }
93
97
  isShuttingDown = true;
94
- child.kill("SIGTERM");
98
+ child.kill(signal);
95
99
  };
96
- const onSigint = () => {
100
+ const onSigterm = forward("SIGTERM");
101
+ const onSighup = forward("SIGHUP");
102
+ const onSigint = process.platform === "win32" ? () => {
97
103
  isShuttingDown = true;
98
- };
104
+ } : forward("SIGINT");
99
105
  process.on("SIGTERM", onSigterm);
100
106
  process.on("SIGINT", onSigint);
107
+ process.on("SIGHUP", onSighup);
101
108
  child.on("close", (code) => {
102
109
  if (!isReady && !isShuttingDown) {
103
110
  const exitCode = code === 0 || code === null ? 1 : code;
@@ -1 +1 @@
1
- {"version":3,"file":"production-supervisor.mjs","names":[],"sources":["../../../../../../../core/src/production/production-supervisor.ts"],"sourcesContent":["import { spawn } from \"child_process\";\nimport { BOOT_SIGNAL_ENV_KEY, isBootSignal } from \"../application/boot-signal\";\nimport {\n displayMissingReadinessNotice,\n displayProductionReadyBanner,\n displayProductionStartFailure,\n} from \"../cli/cli-commands.utils\";\n\n/**\n * How long a still-running child may stay silent before we say so.\n *\n * Only reached by a bundle built before readiness reporting existed; a current\n * bundle signals as soon as its late-phase connectors are up.\n */\nexport const DEFAULT_READINESS_NOTICE_DELAY_MS = 10_000;\n\nexport type ProductionSupervisorOptions = {\n /** Arguments handed to the node binary, entry file included. */\n nodeArgs: string[];\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n readinessNoticeDelayMs?: number;\n};\n\nexport type ProductionSupervisorResult = {\n /** What the CLI should exit with — never 0 for a boot that never completed. */\n exitCode: number;\n /** Whether the child ever reported a finished boot. */\n ready: boolean;\n};\n\n/**\n * Run the production bundle in a child process and report honestly on it.\n *\n * The supervisor exists because a parent that only forwards `stdio` cannot\n * see whether its child ever booted — it only sees the process exit. It\n * therefore opens an IPC channel and treats the child's `warlock:ready`\n * signal, emitted by `Application.markBooted`, as the single source of truth\n * for \"started\":\n *\n * 1. The success banner is printed only on that signal.\n * 2. A child that dies before signalling is reported as a failed start and\n * forced to a non-zero exit, even if it exited 0.\n * 3. A child still running without having signalled draws a note on stderr —\n * never stdout, which would be the false-green this whole channel prevents.\n * 4. Whether the child ever wrote to stdout/stderr before dying is tracked\n * (`sawChildOutput`) so the failure summary only claims \"the cause is\n * printed above\" when that is actually true — see the stdio comment\n * below.\n *\n * Resolves rather than exiting so the outcome stays assertable in a test; the\n * `start` command turns the result into the process exit code.\n */\nexport function superviseProductionProcess({\n nodeArgs,\n cwd = process.cwd(),\n env = process.env,\n readinessNoticeDelayMs = DEFAULT_READINESS_NOTICE_DELAY_MS,\n}: ProductionSupervisorOptions): Promise<ProductionSupervisorResult> {\n return new Promise<ProductionSupervisorResult>((resolve) => {\n // On Windows, we need to be careful with signals - the console sends Ctrl+C\n // to all processes in the group, so we just need to not interfere.\n // `process.execPath`, not \"node\": the bare name needs `node` on PATH, which\n // a systemd unit, a cron job, or a slim container may not provide — and a\n // PATH `node` that *is* present can be a different version than the one\n // running this CLI. execPath is the binary already executing us.\n //\n // The fourth stdio slot opens the IPC channel the child reports readiness\n // on. Without it `process.send` is undefined in the child and we would be\n // back to guessing whether the boot succeeded.\n //\n // stdout/stderr are piped rather than inherited so this supervisor can\n // tell whether the child ever wrote anything, not just forward it blind.\n // `displayProductionStartFailure` used to claim \"the cause is printed\n // above\" on every failed boot, unconditionally — true when the child's\n // logger got far enough to print, false (and misleading) when it died\n // before its log channels were configured. Piping costs nothing here:\n // both streams are re-forwarded to this process's own stdout/stderr as\n // each chunk arrives, so a human watching the terminal sees the exact\n // same live output \"inherit\" gave them.\n const child = spawn(process.execPath, nodeArgs, {\n stdio: [\"inherit\", \"pipe\", \"pipe\", \"ipc\"],\n cwd,\n // The flag identifies us as a parent that speaks the boot protocol. The\n // child stays silent without it, so an app running under pm2 or any other\n // supervisor never writes to a channel that belongs to someone else.\n env: { ...env, [BOOT_SIGNAL_ENV_KEY]: \"1\" },\n // Important: keep child in same process group for proper signal handling\n detached: false,\n });\n\n const startedAt = Date.now();\n let isReady = false;\n let isShuttingDown = false;\n let isSettled = false;\n\n // Whether the child wrote anything to either stream — the only honest\n // basis for telling a developer \"the cause is printed above\". Set from\n // the first chunk on either stream; a child that dies before its first\n // write (a crash mid-import, a logger with no console channel) leaves\n // this `false`, which is exactly the case the summary must admit rather\n // than paper over.\n let sawChildOutput = false;\n\n const forwardChildOutput = (target: NodeJS.WritableStream) => (chunk: Buffer) => {\n sawChildOutput = true;\n target.write(chunk);\n };\n\n child.stdout?.on(\"data\", forwardChildOutput(process.stdout));\n child.stderr?.on(\"data\", forwardChildOutput(process.stderr));\n\n const readinessNoticeTimer = setTimeout(() => {\n if (isReady) {\n return;\n }\n\n displayMissingReadinessNotice(Date.now() - startedAt);\n }, readinessNoticeDelayMs);\n\n // A diagnostic timer must never be the reason the CLI stays alive.\n readinessNoticeTimer.unref?.();\n\n const settle = (result: ProductionSupervisorResult) => {\n if (isSettled) {\n return;\n }\n\n isSettled = true;\n clearTimeout(readinessNoticeTimer);\n process.off(\"SIGTERM\", onSigterm);\n process.off(\"SIGINT\", onSigint);\n\n resolve(result);\n };\n\n child.on(\"message\", (message: unknown) => {\n if (isReady || !isBootSignal(message)) {\n return;\n }\n\n isReady = true;\n clearTimeout(readinessNoticeTimer);\n\n displayProductionReadyBanner({ bootDurationMs: message.bootDurationMs }).catch((error) => {\n // The server is up either way — a banner that fails to render must not\n // be reported as, or turn into, a boot failure.\n console.error(error);\n });\n });\n\n // A spawn that never starts (missing binary, EACCES) emits `error` and no\n // `exit`, so without this the command would hang silently on a failure.\n // The error is printed BEFORE the summary that references it — the\n // summary says the cause is \"above\", so it has to already be there.\n child.on(\"error\", (error) => {\n console.error(error);\n displayProductionStartFailure(1, true);\n\n settle({ exitCode: 1, ready: false });\n });\n\n // SIGTERM doesn't auto-propagate like SIGINT does on Windows.\n const onSigterm = () => {\n if (isShuttingDown) {\n return;\n }\n\n isShuttingDown = true;\n child.kill(\"SIGTERM\");\n };\n\n // On Windows Ctrl+C reaches both processes, so the child already has it —\n // we only record that this exit was asked for.\n const onSigint = () => {\n isShuttingDown = true;\n };\n\n process.on(\"SIGTERM\", onSigterm);\n process.on(\"SIGINT\", onSigint);\n\n // `close`, not `exit`: `exit` fires as soon as the OS process ends, which\n // can race ahead of the last chunks still in flight on the piped stdout/\n // stderr streams. `close` waits for those streams to end too, so\n // `sawChildOutput` reflects everything the child actually wrote instead\n // of whatever had been delivered by the time the process happened to die.\n child.on(\"close\", (code) => {\n // A child that dies before reporting readiness never served a request.\n // Exiting 0 there — which a clean `process.exit(0)` in failing app code\n // would do — reports a boot failure as a successful run, so the exit code\n // is forced non-zero to match what actually happened.\n //\n // An operator who interrupts the boot is not a failed boot, so a signalled\n // shutdown keeps the child's own exit code.\n if (!isReady && !isShuttingDown) {\n const exitCode = code === 0 || code === null ? 1 : code;\n\n displayProductionStartFailure(exitCode, sawChildOutput);\n\n return settle({ exitCode, ready: false });\n }\n\n settle({ exitCode: code ?? 0, ready: isReady });\n });\n });\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAa,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;AAuCjD,SAAgB,2BAA2B,EACzC,UACA,MAAM,QAAQ,IAAI,GAClB,MAAM,QAAQ,KACd,yBAAyB,qCAC0C;CACnE,OAAO,IAAI,SAAqC,YAAY;EAqB1D,MAAM,QAAQ,MAAM,QAAQ,UAAU,UAAU;GAC9C,OAAO;IAAC;IAAW;IAAQ;IAAQ;GAAK;GACxC;GAIA,KAAK;IAAE,GAAG;KAAM,sBAAsB;GAAI;GAE1C,UAAU;EACZ,CAAC;EAED,MAAM,YAAY,KAAK,IAAI;EAC3B,IAAI,UAAU;EACd,IAAI,iBAAiB;EACrB,IAAI,YAAY;EAQhB,IAAI,iBAAiB;EAErB,MAAM,sBAAsB,YAAmC,UAAkB;GAC/E,iBAAiB;GACjB,OAAO,MAAM,KAAK;EACpB;EAEA,MAAM,QAAQ,GAAG,QAAQ,mBAAmB,QAAQ,MAAM,CAAC;EAC3D,MAAM,QAAQ,GAAG,QAAQ,mBAAmB,QAAQ,MAAM,CAAC;EAE3D,MAAM,uBAAuB,iBAAiB;GAC5C,IAAI,SACF;GAGF,8BAA8B,KAAK,IAAI,IAAI,SAAS;EACtD,GAAG,sBAAsB;EAGzB,qBAAqB,QAAQ;EAE7B,MAAM,UAAU,WAAuC;GACrD,IAAI,WACF;GAGF,YAAY;GACZ,aAAa,oBAAoB;GACjC,QAAQ,IAAI,WAAW,SAAS;GAChC,QAAQ,IAAI,UAAU,QAAQ;GAE9B,QAAQ,MAAM;EAChB;EAEA,MAAM,GAAG,YAAY,YAAqB;GACxC,IAAI,WAAW,CAAC,aAAa,OAAO,GAClC;GAGF,UAAU;GACV,aAAa,oBAAoB;GAEjC,6BAA6B,EAAE,gBAAgB,QAAQ,eAAe,CAAC,CAAC,CAAC,OAAO,UAAU;IAGxF,QAAQ,MAAM,KAAK;GACrB,CAAC;EACH,CAAC;EAMD,MAAM,GAAG,UAAU,UAAU;GAC3B,QAAQ,MAAM,KAAK;GACnB,8BAA8B,GAAG,IAAI;GAErC,OAAO;IAAE,UAAU;IAAG,OAAO;GAAM,CAAC;EACtC,CAAC;EAGD,MAAM,kBAAkB;GACtB,IAAI,gBACF;GAGF,iBAAiB;GACjB,MAAM,KAAK,SAAS;EACtB;EAIA,MAAM,iBAAiB;GACrB,iBAAiB;EACnB;EAEA,QAAQ,GAAG,WAAW,SAAS;EAC/B,QAAQ,GAAG,UAAU,QAAQ;EAO7B,MAAM,GAAG,UAAU,SAAS;GAQ1B,IAAI,CAAC,WAAW,CAAC,gBAAgB;IAC/B,MAAM,WAAW,SAAS,KAAK,SAAS,OAAO,IAAI;IAEnD,8BAA8B,UAAU,cAAc;IAEtD,OAAO,OAAO;KAAE;KAAU,OAAO;IAAM,CAAC;GAC1C;GAEA,OAAO;IAAE,UAAU,QAAQ;IAAG,OAAO;GAAQ,CAAC;EAChD,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"production-supervisor.mjs","names":[],"sources":["../../../../../../../core/src/production/production-supervisor.ts"],"sourcesContent":["import { spawn } from \"child_process\";\nimport { BOOT_SIGNAL_ENV_KEY, isBootSignal } from \"../application/boot-signal\";\nimport {\n displayMissingReadinessNotice,\n displayProductionReadyBanner,\n displayProductionStartFailure,\n} from \"../cli/cli-commands.utils\";\n\n/**\n * How long a still-running child may stay silent before we say so.\n *\n * Only reached by a bundle built before readiness reporting existed; a current\n * bundle signals as soon as its late-phase connectors are up.\n */\nexport const DEFAULT_READINESS_NOTICE_DELAY_MS = 10_000;\n\nexport type ProductionSupervisorOptions = {\n /** Arguments handed to the node binary, entry file included. */\n nodeArgs: string[];\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n readinessNoticeDelayMs?: number;\n};\n\nexport type ProductionSupervisorResult = {\n /** What the CLI should exit with — never 0 for a boot that never completed. */\n exitCode: number;\n /** Whether the child ever reported a finished boot. */\n ready: boolean;\n};\n\n/**\n * Run the production bundle in a child process and report honestly on it.\n *\n * The supervisor exists because a parent that only forwards `stdio` cannot\n * see whether its child ever booted — it only sees the process exit. It\n * therefore opens an IPC channel and treats the child's `warlock:ready`\n * signal, emitted by `Application.markBooted`, as the single source of truth\n * for \"started\":\n *\n * 1. The success banner is printed only on that signal.\n * 2. A child that dies before signalling is reported as a failed start and\n * forced to a non-zero exit, even if it exited 0.\n * 3. A child still running without having signalled draws a note on stderr —\n * never stdout, which would be the false-green this whole channel prevents.\n * 4. Whether the child ever wrote to stdout/stderr before dying is tracked\n * (`sawChildOutput`) so the failure summary only claims \"the cause is\n * printed above\" when that is actually true — see the stdio comment\n * below.\n *\n * Resolves rather than exiting so the outcome stays assertable in a test; the\n * `start` command turns the result into the process exit code.\n */\nexport function superviseProductionProcess({\n nodeArgs,\n cwd = process.cwd(),\n env = process.env,\n readinessNoticeDelayMs = DEFAULT_READINESS_NOTICE_DELAY_MS,\n}: ProductionSupervisorOptions): Promise<ProductionSupervisorResult> {\n return new Promise<ProductionSupervisorResult>((resolve) => {\n // On Windows, we need to be careful with signals - the console sends Ctrl+C\n // to all processes in the group, so we just need to not interfere.\n // `process.execPath`, not \"node\": the bare name needs `node` on PATH, which\n // a systemd unit, a cron job, or a slim container may not provide — and a\n // PATH `node` that *is* present can be a different version than the one\n // running this CLI. execPath is the binary already executing us.\n //\n // The fourth stdio slot opens the IPC channel the child reports readiness\n // on. Without it `process.send` is undefined in the child and we would be\n // back to guessing whether the boot succeeded.\n //\n // stdout/stderr are piped rather than inherited so this supervisor can\n // tell whether the child ever wrote anything, not just forward it blind.\n // `displayProductionStartFailure` used to claim \"the cause is printed\n // above\" on every failed boot, unconditionally — true when the child's\n // logger got far enough to print, false (and misleading) when it died\n // before its log channels were configured. Piping costs nothing here:\n // both streams are re-forwarded to this process's own stdout/stderr as\n // each chunk arrives, so a human watching the terminal sees the exact\n // same live output \"inherit\" gave them.\n const child = spawn(process.execPath, nodeArgs, {\n stdio: [\"inherit\", \"pipe\", \"pipe\", \"ipc\"],\n cwd,\n // The flag identifies us as a parent that speaks the boot protocol. The\n // child stays silent without it, so an app running under pm2 or any other\n // supervisor never writes to a channel that belongs to someone else.\n env: { ...env, [BOOT_SIGNAL_ENV_KEY]: \"1\" },\n // Important: keep child in same process group for proper signal handling\n detached: false,\n });\n\n const startedAt = Date.now();\n let isReady = false;\n let isShuttingDown = false;\n let isSettled = false;\n\n // Whether the child wrote anything to either stream — the only honest\n // basis for telling a developer \"the cause is printed above\". Set from\n // the first chunk on either stream; a child that dies before its first\n // write (a crash mid-import, a logger with no console channel) leaves\n // this `false`, which is exactly the case the summary must admit rather\n // than paper over.\n let sawChildOutput = false;\n\n const forwardChildOutput = (target: NodeJS.WritableStream) => (chunk: Buffer) => {\n sawChildOutput = true;\n target.write(chunk);\n };\n\n child.stdout?.on(\"data\", forwardChildOutput(process.stdout));\n child.stderr?.on(\"data\", forwardChildOutput(process.stderr));\n\n const readinessNoticeTimer = setTimeout(() => {\n if (isReady) {\n return;\n }\n\n displayMissingReadinessNotice(Date.now() - startedAt);\n }, readinessNoticeDelayMs);\n\n // A diagnostic timer must never be the reason the CLI stays alive.\n readinessNoticeTimer.unref?.();\n\n const settle = (result: ProductionSupervisorResult) => {\n if (isSettled) {\n return;\n }\n\n isSettled = true;\n clearTimeout(readinessNoticeTimer);\n process.off(\"SIGTERM\", onSigterm);\n process.off(\"SIGINT\", onSigint);\n process.off(\"SIGHUP\", onSighup);\n\n resolve(result);\n };\n\n child.on(\"message\", (message: unknown) => {\n if (isReady || !isBootSignal(message)) {\n return;\n }\n\n isReady = true;\n clearTimeout(readinessNoticeTimer);\n\n displayProductionReadyBanner({ bootDurationMs: message.bootDurationMs }).catch((error) => {\n // The server is up either way — a banner that fails to render must not\n // be reported as, or turn into, a boot failure.\n console.error(error);\n });\n });\n\n // A spawn that never starts (missing binary, EACCES) emits `error` and no\n // `exit`, so without this the command would hang silently on a failure.\n // The error is printed BEFORE the summary that references it — the\n // summary says the cause is \"above\", so it has to already be there.\n child.on(\"error\", (error) => {\n console.error(error);\n displayProductionStartFailure(1, true);\n\n settle({ exitCode: 1, ready: false });\n });\n\n // Forward every stop signal so a supervisor that only signals this\n // process (docker kill -s INT, systemd KillSignal) still stops the child.\n // A repeated signal means the graceful shutdown is stuck: force-kill.\n const forward = (signal: NodeJS.Signals) => () => {\n if (isShuttingDown) {\n child.kill(\"SIGKILL\");\n return;\n }\n\n isShuttingDown = true;\n child.kill(signal);\n };\n\n const onSigterm = forward(\"SIGTERM\");\n const onSighup = forward(\"SIGHUP\");\n\n // On Windows Ctrl+C reaches both processes, so the child already has it —\n // we only record that this exit was asked for (kill() there is a hard kill).\n const onSigint =\n process.platform === \"win32\"\n ? () => {\n isShuttingDown = true;\n }\n : forward(\"SIGINT\");\n\n process.on(\"SIGTERM\", onSigterm);\n process.on(\"SIGINT\", onSigint);\n process.on(\"SIGHUP\", onSighup);\n\n // `close`, not `exit`: `exit` fires as soon as the OS process ends, which\n // can race ahead of the last chunks still in flight on the piped stdout/\n // stderr streams. `close` waits for those streams to end too, so\n // `sawChildOutput` reflects everything the child actually wrote instead\n // of whatever had been delivered by the time the process happened to die.\n child.on(\"close\", (code) => {\n // A child that dies before reporting readiness never served a request.\n // Exiting 0 there — which a clean `process.exit(0)` in failing app code\n // would do — reports a boot failure as a successful run, so the exit code\n // is forced non-zero to match what actually happened.\n //\n // An operator who interrupts the boot is not a failed boot, so a signalled\n // shutdown keeps the child's own exit code.\n if (!isReady && !isShuttingDown) {\n const exitCode = code === 0 || code === null ? 1 : code;\n\n displayProductionStartFailure(exitCode, sawChildOutput);\n\n return settle({ exitCode, ready: false });\n }\n\n settle({ exitCode: code ?? 0, ready: isReady });\n });\n });\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAa,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;AAuCjD,SAAgB,2BAA2B,EACzC,UACA,MAAM,QAAQ,IAAI,GAClB,MAAM,QAAQ,KACd,yBAAyB,qCAC0C;CACnE,OAAO,IAAI,SAAqC,YAAY;EAqB1D,MAAM,QAAQ,MAAM,QAAQ,UAAU,UAAU;GAC9C,OAAO;IAAC;IAAW;IAAQ;IAAQ;GAAK;GACxC;GAIA,KAAK;IAAE,GAAG;KAAM,sBAAsB;GAAI;GAE1C,UAAU;EACZ,CAAC;EAED,MAAM,YAAY,KAAK,IAAI;EAC3B,IAAI,UAAU;EACd,IAAI,iBAAiB;EACrB,IAAI,YAAY;EAQhB,IAAI,iBAAiB;EAErB,MAAM,sBAAsB,YAAmC,UAAkB;GAC/E,iBAAiB;GACjB,OAAO,MAAM,KAAK;EACpB;EAEA,MAAM,QAAQ,GAAG,QAAQ,mBAAmB,QAAQ,MAAM,CAAC;EAC3D,MAAM,QAAQ,GAAG,QAAQ,mBAAmB,QAAQ,MAAM,CAAC;EAE3D,MAAM,uBAAuB,iBAAiB;GAC5C,IAAI,SACF;GAGF,8BAA8B,KAAK,IAAI,IAAI,SAAS;EACtD,GAAG,sBAAsB;EAGzB,qBAAqB,QAAQ;EAE7B,MAAM,UAAU,WAAuC;GACrD,IAAI,WACF;GAGF,YAAY;GACZ,aAAa,oBAAoB;GACjC,QAAQ,IAAI,WAAW,SAAS;GAChC,QAAQ,IAAI,UAAU,QAAQ;GAC9B,QAAQ,IAAI,UAAU,QAAQ;GAE9B,QAAQ,MAAM;EAChB;EAEA,MAAM,GAAG,YAAY,YAAqB;GACxC,IAAI,WAAW,CAAC,aAAa,OAAO,GAClC;GAGF,UAAU;GACV,aAAa,oBAAoB;GAEjC,6BAA6B,EAAE,gBAAgB,QAAQ,eAAe,CAAC,CAAC,CAAC,OAAO,UAAU;IAGxF,QAAQ,MAAM,KAAK;GACrB,CAAC;EACH,CAAC;EAMD,MAAM,GAAG,UAAU,UAAU;GAC3B,QAAQ,MAAM,KAAK;GACnB,8BAA8B,GAAG,IAAI;GAErC,OAAO;IAAE,UAAU;IAAG,OAAO;GAAM,CAAC;EACtC,CAAC;EAKD,MAAM,WAAW,iBAAiC;GAChD,IAAI,gBAAgB;IAClB,MAAM,KAAK,SAAS;IACpB;GACF;GAEA,iBAAiB;GACjB,MAAM,KAAK,MAAM;EACnB;EAEA,MAAM,YAAY,QAAQ,SAAS;EACnC,MAAM,WAAW,QAAQ,QAAQ;EAIjC,MAAM,WACJ,QAAQ,aAAa,gBACX;GACJ,iBAAiB;EACnB,IACA,QAAQ,QAAQ;EAEtB,QAAQ,GAAG,WAAW,SAAS;EAC/B,QAAQ,GAAG,UAAU,QAAQ;EAC7B,QAAQ,GAAG,UAAU,QAAQ;EAO7B,MAAM,GAAG,UAAU,SAAS;GAQ1B,IAAI,CAAC,WAAW,CAAC,gBAAgB;IAC/B,MAAM,WAAW,SAAS,KAAK,SAAS,OAAO,IAAI;IAEnD,8BAA8B,UAAU,cAAc;IAEtD,OAAO,OAAO;KAAE;KAAU,OAAO;IAAM,CAAC;GAC1C;GAEA,OAAO;IAAE,UAAU,QAAQ;IAAG,OAAO;GAAQ,CAAC;EAChD,CAAC;CACH,CAAC;AACH"}
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,65 @@
1
+ import { appPath } from "../utils/paths.mjs";
2
+ import { Application } from "../application/application.mjs";
3
+ import { router } from "../router/router.mjs";
4
+ import "../application/index.mjs";
5
+ import { loadEnvironmentFiles } from "../utils/load-environment.mjs";
6
+ import { bootstrap } from "../bootstrap.mjs";
7
+ import { warlockConfigManager } from "../warlock-config/warlock-config.manager.mjs";
8
+ import { filesOrchestrator } from "../dev-server/files-orchestrator.mjs";
9
+ import { loadConfigFiles } from "../config/load-config-files.mjs";
10
+ import { fileExistsAsync } from "@warlock.js/fs";
11
+
12
+ //#region ../core/src/production/route-registration-child.ts
13
+ const PROTOCOL_VERSION = 1;
14
+ process.once("message", async (message) => {
15
+ try {
16
+ const request = validateRequest(message);
17
+ process.chdir(request.cwd);
18
+ if (request.environment) Application.setEnvironment(request.environment);
19
+ if (request.runtimeStrategy) Application.setRuntimeStrategy(request.runtimeStrategy);
20
+ await loadEnvironmentFiles();
21
+ await warlockConfigManager.load();
22
+ await filesOrchestrator.init();
23
+ await bootstrap();
24
+ if (await fileExistsAsync(appPath("bootstrap.ts"))) await filesOrchestrator.load("src/app/bootstrap.ts");
25
+ await filesOrchestrator.initializeAll();
26
+ filesOrchestrator.specialFilesCollector.collect(filesOrchestrator.getFiles());
27
+ await loadConfigFiles(true);
28
+ for (const file of filesOrchestrator.files.values()) if (file.type === "model") await filesOrchestrator.moduleLoader.loadModule(file, "model");
29
+ await filesOrchestrator.moduleLoader.loadAll();
30
+ await sendAndExit({
31
+ type: "route-registration:snapshot",
32
+ snapshot: {
33
+ version: PROTOCOL_VERSION,
34
+ routes: router.getNamedApiRoutes()
35
+ }
36
+ });
37
+ } catch (error) {
38
+ await sendAndExit({
39
+ type: "route-registration:error",
40
+ message: error instanceof Error ? error.stack || error.message : String(error)
41
+ }, 1);
42
+ }
43
+ });
44
+ function validateRequest(value) {
45
+ if (typeof value !== "object" || value === null || value.version !== PROTOCOL_VERSION || typeof value.cwd !== "string" || !isOptionalEnvironment(value.environment) || !isOptionalRuntimeStrategy(value.runtimeStrategy)) throw new Error("Route registration child received an invalid protocol request.");
46
+ return value;
47
+ }
48
+ function isOptionalEnvironment(value) {
49
+ return value === void 0 || value === "development" || value === "production" || value === "test";
50
+ }
51
+ function isOptionalRuntimeStrategy(value) {
52
+ return value === void 0 || value === "development" || value === "production";
53
+ }
54
+ async function sendAndExit(message, exitCode = 0) {
55
+ if (typeof process.send !== "function") throw new Error("Route registration child requires an IPC channel.");
56
+ await new Promise((resolve, reject) => {
57
+ process.send(message, (error) => error ? reject(error) : resolve());
58
+ });
59
+ process.disconnect?.();
60
+ process.exit(exitCode);
61
+ }
62
+
63
+ //#endregion
64
+ export { };
65
+ //# sourceMappingURL=route-registration-child.mjs.map