@warlock.js/core 5.5.0 → 5.7.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 (171) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/esm/application/app.d.mts.map +1 -1
  3. package/esm/application/app.mjs +7 -1
  4. package/esm/application/app.mjs.map +1 -1
  5. package/esm/benchmark/profiler.d.mts.map +1 -1
  6. package/esm/benchmark/profiler.mjs +4 -3
  7. package/esm/benchmark/profiler.mjs.map +1 -1
  8. package/esm/cli/cli-commands.manager.mjs +10 -7
  9. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  10. package/esm/cli/cli-commands.utils.mjs.map +1 -1
  11. package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
  12. package/esm/cli/commands/doctor/checks/release-hygiene.check.mjs.map +1 -1
  13. package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
  14. package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
  15. package/esm/cli/commands/routes/format-routes-table.mjs +3 -3
  16. package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
  17. package/esm/cli/commands/routes/route-row.mjs.map +1 -1
  18. package/esm/cli/commands/routes.command.mjs.map +1 -1
  19. package/esm/cli/framework-cli-commands.mjs.map +1 -1
  20. package/esm/cli/parse-cli-args.mjs +1 -0
  21. package/esm/cli/parse-cli-args.mjs.map +1 -1
  22. package/esm/cli/string-similarity.mjs +13 -4
  23. package/esm/cli/string-similarity.mjs.map +1 -1
  24. package/esm/commands/cli-command.d.mts.map +1 -1
  25. package/esm/commands/cli-command.mjs +5 -2
  26. package/esm/commands/cli-command.mjs.map +1 -1
  27. package/esm/config/config-loader.mjs +3 -1
  28. package/esm/config/config-loader.mjs.map +1 -1
  29. package/esm/config/locale-configuration.mjs +11 -1
  30. package/esm/config/locale-configuration.mjs.map +1 -1
  31. package/esm/container/container-instance-registry.mjs +40 -0
  32. package/esm/container/container-instance-registry.mjs.map +1 -0
  33. package/esm/container/index.d.mts +11 -0
  34. package/esm/container/index.d.mts.map +1 -1
  35. package/esm/container/index.mjs +11 -0
  36. package/esm/container/index.mjs.map +1 -1
  37. package/esm/database/drop-tables-action.mjs.map +1 -1
  38. package/esm/database/migrate-action.mjs.map +1 -1
  39. package/esm/database/seed-command-action.mjs.map +1 -1
  40. package/esm/dev-server/dependency-graph.d.mts.map +1 -1
  41. package/esm/dev-server/dependency-graph.mjs +2 -1
  42. package/esm/dev-server/dependency-graph.mjs.map +1 -1
  43. package/esm/dev-server/dev-logger.mjs +7 -5
  44. package/esm/dev-server/dev-logger.mjs.map +1 -1
  45. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  46. package/esm/dev-server/files-orchestrator.mjs +1 -1
  47. package/esm/dev-server/files-orchestrator.mjs.map +1 -1
  48. package/esm/dev-server/layer-executor.mjs.map +1 -1
  49. package/esm/dev-server/loader/build-transpile-init.mjs.map +1 -1
  50. package/esm/dev-server/loader/load-hook.mjs.map +1 -1
  51. package/esm/dev-server/loader/register-loader.mjs.map +1 -1
  52. package/esm/dev-server/loader/resolve-hook.mjs.map +1 -1
  53. package/esm/dev-server/loader/transpile-cache.mjs.map +1 -1
  54. package/esm/dev-server/module-loader.mjs.map +1 -1
  55. package/esm/dev-server/parse-imports.mjs +22 -8
  56. package/esm/dev-server/parse-imports.mjs.map +1 -1
  57. package/esm/dev-server/type-generator.mjs.map +1 -1
  58. package/esm/dev-server/types.d.mts.map +1 -1
  59. package/esm/dev-server/utils.mjs.map +1 -1
  60. package/esm/encryption/encrypt.mjs +1 -0
  61. package/esm/encryption/encrypt.mjs.map +1 -1
  62. package/esm/errors/container-key-missing-error.mjs +28 -0
  63. package/esm/errors/container-key-missing-error.mjs.map +1 -0
  64. package/esm/errors/unknown-locale-error.mjs +28 -0
  65. package/esm/errors/unknown-locale-error.mjs.map +1 -0
  66. package/esm/generations/add-command.action.mjs +8 -2
  67. package/esm/generations/add-command.action.mjs.map +1 -1
  68. package/esm/generations/features/access.feature.mjs.map +1 -1
  69. package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -1
  70. package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -1
  71. package/esm/generations/features/ai-google.feature.mjs.map +1 -1
  72. package/esm/generations/features/ai-ollama.feature.mjs.map +1 -1
  73. package/esm/generations/features/ai-openai.feature.mjs.map +1 -1
  74. package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -1
  75. package/esm/generations/features/ai-tools.feature.mjs.map +1 -1
  76. package/esm/generations/features/ai-workspace.feature.mjs.map +1 -1
  77. package/esm/generations/features/ai.feature.mjs.map +1 -1
  78. package/esm/generations/features/herald.feature.mjs.map +1 -1
  79. package/esm/generations/features/notifications.feature.mjs.map +1 -1
  80. package/esm/generations/features/scheduler.feature.mjs.map +1 -1
  81. package/esm/generations/features/shared/patch-tsconfig-include.mjs.map +1 -1
  82. package/esm/generations/features/shared/relocate-conflicting-home-route.mjs +6 -1
  83. package/esm/generations/features/shared/relocate-conflicting-home-route.mjs.map +1 -1
  84. package/esm/generations/features/tailwind.feature.mjs.map +1 -1
  85. package/esm/generations/features/types.mjs.map +1 -1
  86. package/esm/generations/features/web.feature.mjs.map +1 -1
  87. package/esm/http/context/request-memo.mjs.map +1 -1
  88. package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
  89. package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
  90. package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
  91. package/esm/http/middleware/idempotency.middleware.d.mts.map +1 -1
  92. package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
  93. package/esm/http/middleware/maintenance.middleware.mjs +1 -2
  94. package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
  95. package/esm/http/middleware/max-body-size.middleware.mjs.map +1 -1
  96. package/esm/http/middleware/rate-limit.middleware.mjs.map +1 -1
  97. package/esm/http/middleware/utils/cidr-match.d.mts.map +1 -1
  98. package/esm/http/middleware/utils/cidr-match.mjs +1 -0
  99. package/esm/http/middleware/utils/cidr-match.mjs.map +1 -1
  100. package/esm/http/port-preflight.d.mts.map +1 -1
  101. package/esm/http/port-preflight.mjs.map +1 -1
  102. package/esm/http/request.d.mts.map +1 -1
  103. package/esm/http/request.mjs +16 -9
  104. package/esm/http/request.mjs.map +1 -1
  105. package/esm/http/response.d.mts +38 -0
  106. package/esm/http/response.d.mts.map +1 -1
  107. package/esm/http/response.mjs +47 -0
  108. package/esm/http/response.mjs.map +1 -1
  109. package/esm/http/server.d.mts.map +1 -1
  110. package/esm/http/server.mjs.map +1 -1
  111. package/esm/http/types.d.mts.map +1 -1
  112. package/esm/image/image.d.mts.map +1 -1
  113. package/esm/image/image.mjs.map +1 -1
  114. package/esm/mail/send-mail.mjs.map +1 -1
  115. package/esm/production/build-contributions.mjs.map +1 -1
  116. package/esm/production/bundle-framework-dependencies.mjs +152 -0
  117. package/esm/production/bundle-framework-dependencies.mjs.map +1 -0
  118. package/esm/production/production-builder.mjs +30 -3
  119. package/esm/production/production-builder.mjs.map +1 -1
  120. package/esm/production/production-supervisor.mjs.map +1 -1
  121. package/esm/production/tsconfig-path-aliases.mjs +99 -0
  122. package/esm/production/tsconfig-path-aliases.mjs.map +1 -0
  123. package/esm/react/index.d.mts.map +1 -1
  124. package/esm/react/index.mjs.map +1 -1
  125. package/esm/repositories/adapters/cascade/filter-applicator.mjs +4 -2
  126. package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
  127. package/esm/repositories/contracts/query-builder.contract.d.mts.map +1 -1
  128. package/esm/repositories/contracts/types.d.mts.map +1 -1
  129. package/esm/resource/resource-field-builder.d.mts.map +1 -1
  130. package/esm/resource/resource-field-builder.mjs.map +1 -1
  131. package/esm/resource/types.d.mts.map +1 -1
  132. package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
  133. package/esm/router/positional-handler-diagnostics.mjs +9 -3
  134. package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
  135. package/esm/router/route-registry.mjs +1 -1
  136. package/esm/router/route-registry.mjs.map +1 -1
  137. package/esm/router/router.d.mts.map +1 -1
  138. package/esm/router/router.mjs +1 -2
  139. package/esm/router/router.mjs.map +1 -1
  140. package/esm/router/types.d.mts.map +1 -1
  141. package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
  142. package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
  143. package/esm/storage/scoped-storage.d.mts.map +1 -1
  144. package/esm/storage/scoped-storage.mjs +1 -0
  145. package/esm/storage/scoped-storage.mjs.map +1 -1
  146. package/esm/storage/storage.d.mts.map +1 -1
  147. package/esm/storage/storage.mjs +6 -2
  148. package/esm/storage/storage.mjs.map +1 -1
  149. package/esm/storage/types.d.mts.map +1 -1
  150. package/esm/storage/utils/contain-path.mjs.map +1 -1
  151. package/esm/storage/utils/safe-fetch.d.mts.map +1 -1
  152. package/esm/storage/utils/safe-fetch.mjs +6 -1
  153. package/esm/storage/utils/safe-fetch.mjs.map +1 -1
  154. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  155. package/esm/tests/start-http-development-server.mjs.map +1 -1
  156. package/esm/tests/test-lifecycle-state.mjs.map +1 -1
  157. package/esm/tests/test-setup-timeout.mjs.map +1 -1
  158. package/esm/tests/vitest-setup.d.mts.map +1 -1
  159. package/esm/tests/vitest-setup.mjs.map +1 -1
  160. package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
  161. package/esm/use-cases/use-cases-registry.mjs.map +1 -1
  162. package/esm/utils/app-log.mjs.map +1 -1
  163. package/esm/utils/queue.mjs.map +1 -1
  164. package/esm/utils/sleep.mjs.map +1 -1
  165. package/esm/utils/version-compare.d.mts.map +1 -1
  166. package/esm/utils/version-compare.mjs +12 -4
  167. package/esm/utils/version-compare.mjs.map +1 -1
  168. package/esm/validation/plugins/database-plugin.mjs.map +1 -1
  169. package/esm/vite/lower-stage3-decorators.mjs +1 -0
  170. package/esm/vite/lower-stage3-decorators.mjs.map +1 -1
  171. package/package.json +12 -12
@@ -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 { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\r\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\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 { 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 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. Strip them through a local\r\n // optional view rather than weakening the type every other caller relies on; both\r\n // were already read into locals above.\r\n const strippable = this.options as Partial<ResolvedBuildConfig>;\r\n\r\n delete strippable.outFile;\r\n delete strippable.entryPath;\r\n delete this.options.singleBundle;\r\n delete this.options.esmShim;\r\n delete this.options.banner;\r\n\r\n await ensureDirectoryAsync(writeOutDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\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 = (this.options.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 = this.options.define;\r\n const userExternal: string[] | undefined = this.options.external;\r\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = this.options.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\r\n try {\r\n \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 // `...this.options` 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 packages: singleBundle ? \"bundle\" : \"external\",\r\n minify: this.options!.minify,\r\n sourcemap: this.options!.sourcemap === true ? \"linked\" : this.options!.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: [nativeNodeModulesPlugin],\r\n // Between the defaults and the user spread — the ruled precedence.\r\n ...contributedOptions,\r\n ...(this.options as any),\r\n // AFTER the spread, and NOT overridable: `this.options.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 * 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.\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 alias[from] = path.resolve(baseUrl, to[0]);\r\n }\r\n\r\n return alias;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,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;wBAsM5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA5KA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA8B,CAAC;EAGvD,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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WAAW,CAAC;IACZ,UAAU,eAAe,WAAW;IACpC,QAAQ,KAAK,QAAS;IACtB,WAAW,KAAK,QAAS,cAAc,OAAO,WAAW,KAAK,QAAS;IACvE,QAAQ;IAIR,QAAQ,CAAC,QAAQ;IACjB,YAAY;IACZ;IACA,SAAS,CAAC,uBAAuB;IAEjC,GAAG;IACH,GAAI,KAAK;IAOT,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;EACD,SAAS,GAAG;GACV,QAAQ,IAAI,CAAC;GACb,MAAM;EACR;CACF;;;;;;;;;;;CAYA,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,QAAQ,KAAK,QAAQ,SAAS,GAAG,EAAE;EAC3C;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\";\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 {\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 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. Strip them through a local\r\n // optional view rather than weakening the type every other caller relies on; both\r\n // were already read into locals above.\r\n const strippable = this.options as Partial<ResolvedBuildConfig>;\r\n\r\n delete strippable.outFile;\r\n delete strippable.entryPath;\r\n delete this.options.singleBundle;\r\n delete this.options.esmShim;\r\n delete this.options.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 && (this.options 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 = (this.options.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 = this.options.define;\r\n const userExternal: string[] | undefined = this.options.external;\r\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = this.options.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 // `...this.options` 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: this.options!.minify,\r\n sourcemap: this.options!.sourcemap === true ? \"linked\" : this.options!.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 ...(this.options as any),\r\n // AFTER the spread, and NOT overridable: `this.options.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.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AW,OAAO,KAAK,KAAK;KAAE,CAAC,CAAC,IACpF,CAAC;IACP;IAEA,GAAG;IACH,GAAI,KAAK;IAOT,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,QAAQ,KAAK,QAAQ,SAAS,GAAG,EAAE;EAC3C;EAEA,OAAO;CACT;AACF"}
@@ -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 =\n (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,GACl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tB,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\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,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CACH,CAAC;AACH"}
@@ -0,0 +1,99 @@
1
+ import path from "node:path";
2
+
3
+ //#region ../core/src/production/tsconfig-path-aliases.ts
4
+ /**
5
+ * Turn a tsconfig `paths` map into the WILDCARD entries only, resolved
6
+ * against `baseUrl`. Exact entries are excluded: esbuild's own `alias`
7
+ * option handles those, and it is the better mechanism where it applies.
8
+ */
9
+ function collectWildcardPathAliases(paths, baseUrl) {
10
+ const aliases = [];
11
+ for (const [from, targets] of Object.entries(paths)) {
12
+ if (!Array.isArray(targets) || targets.length === 0) continue;
13
+ const star = from.indexOf("*");
14
+ if (star === -1) continue;
15
+ aliases.push({
16
+ prefix: from.slice(0, star),
17
+ suffix: from.slice(star + 1),
18
+ targets: targets.map((target) => path.resolve(baseUrl, target))
19
+ });
20
+ }
21
+ return aliases.sort((a, b) => b.prefix.length - a.prefix.length);
22
+ }
23
+ /**
24
+ * The substitution TypeScript performs for one `paths` entry: whatever the
25
+ * `*` matched, spliced into each target's own `*`.
26
+ */
27
+ function substituteWildcard(alias, specifier) {
28
+ if (!specifier.startsWith(alias.prefix)) return void 0;
29
+ if (alias.suffix && !specifier.endsWith(alias.suffix)) return void 0;
30
+ const matched = specifier.slice(alias.prefix.length, alias.suffix ? specifier.length - alias.suffix.length : void 0);
31
+ if (!matched) return void 0;
32
+ return alias.targets.map((target) => target.replace("*", matched));
33
+ }
34
+ /**
35
+ * Resolve the tsconfig `paths` entries that esbuild's `alias` option cannot
36
+ * express — the WILDCARD ones.
37
+ *
38
+ * **The defect.** `buildAliasMapFromTsconfig` skips any key ending in `/*`,
39
+ * because esbuild's `alias` takes exact package names and nothing else. That
40
+ * is a correct statement about `alias` and it left the wildcards handled by
41
+ * nobody: `app/*` and `web/*` are how this app's own source refers to itself
42
+ * (`import { User } from "app/users/models/user.model"`), and under
43
+ * `packages: "external"` every one of those survived into the bundle as a
44
+ * bare specifier. Node then looked for a PACKAGE called `app`:
45
+ *
46
+ * ```
47
+ * Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from …/dist/app.js
48
+ * ```
49
+ *
50
+ * The build reported success; the failure waited until `warlock start`.
51
+ *
52
+ * **The resolution is delegated, not reimplemented.** This plugin performs
53
+ * only the substitution TypeScript defines — splice what `*` matched into the
54
+ * target — and hands the resulting ABSOLUTE path straight back to esbuild
55
+ * through `build.resolve`. Extension probing, `index` files, `exports` maps
56
+ * and directory handling stay esbuild's, so a path alias resolves exactly as
57
+ * the same file would have resolved through a relative import. A candidate
58
+ * that does not resolve is reported as esbuild's own error rather than
59
+ * quietly falling through to the next candidate and then to "external",
60
+ * which is how this became a runtime failure in the first place.
61
+ */
62
+ function tsconfigPathAliases(options) {
63
+ const aliases = collectWildcardPathAliases(options.paths, options.baseUrl);
64
+ return {
65
+ name: "warlock:tsconfig-path-aliases",
66
+ setup(build) {
67
+ if (aliases.length === 0) return;
68
+ build.onResolve({ filter: /.*/ }, async (args) => {
69
+ if (args.pluginData?.warlockTsconfigPathAlias) return void 0;
70
+ if (args.namespace !== "file" && args.namespace !== "") return void 0;
71
+ if (args.path.startsWith(".") || path.isAbsolute(args.path)) return void 0;
72
+ for (const alias of aliases) {
73
+ const candidates = substituteWildcard(alias, args.path);
74
+ if (!candidates) continue;
75
+ let lastResult;
76
+ for (const candidate of candidates) {
77
+ const result = await build.resolve(candidate, {
78
+ kind: args.kind,
79
+ importer: args.importer,
80
+ resolveDir: args.resolveDir || path.dirname(args.importer),
81
+ pluginData: { warlockTsconfigPathAlias: true }
82
+ });
83
+ lastResult = result;
84
+ if (result.errors.length === 0) return {
85
+ path: result.path,
86
+ external: result.external,
87
+ namespace: result.namespace
88
+ };
89
+ }
90
+ return lastResult ? { errors: lastResult.errors } : void 0;
91
+ }
92
+ });
93
+ }
94
+ };
95
+ }
96
+
97
+ //#endregion
98
+ export { tsconfigPathAliases };
99
+ //# sourceMappingURL=tsconfig-path-aliases.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tsconfig-path-aliases.mjs","names":[],"sources":["../../../../../../../core/src/production/tsconfig-path-aliases.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { Plugin } from \"esbuild\";\n\nexport type WildcardPathAlias = Readonly<{\n /** The literal text before the `*` — `app/` for `\"app/*\"`. */\n prefix: string;\n /** The literal text after the `*`. Almost always empty. */\n suffix: string;\n /** The `paths` targets, each still carrying its own `*`, resolved against `baseUrl`. */\n targets: readonly string[];\n}>;\n\n/**\n * Turn a tsconfig `paths` map into the WILDCARD entries only, resolved\n * against `baseUrl`. Exact entries are excluded: esbuild's own `alias`\n * option handles those, and it is the better mechanism where it applies.\n */\nexport function collectWildcardPathAliases(\n paths: Record<string, string[] | undefined>,\n baseUrl: string,\n): WildcardPathAlias[] {\n const aliases: WildcardPathAlias[] = [];\n\n for (const [from, targets] of Object.entries(paths)) {\n if (!Array.isArray(targets) || targets.length === 0) continue;\n\n const star = from.indexOf(\"*\");\n if (star === -1) continue;\n\n aliases.push({\n prefix: from.slice(0, star),\n suffix: from.slice(star + 1),\n targets: targets.map((target) => path.resolve(baseUrl, target)),\n });\n }\n\n // Longest prefix first, which is what TypeScript itself does: with both\n // `app/*` and `app/users/*` declared, the more specific one has to be tried\n // first or it can never match.\n return aliases.sort((a, b) => b.prefix.length - a.prefix.length);\n}\n\n/**\n * The substitution TypeScript performs for one `paths` entry: whatever the\n * `*` matched, spliced into each target's own `*`.\n */\nexport function substituteWildcard(\n alias: WildcardPathAlias,\n specifier: string,\n): string[] | undefined {\n if (!specifier.startsWith(alias.prefix)) return undefined;\n if (alias.suffix && !specifier.endsWith(alias.suffix)) return undefined;\n\n const matched = specifier.slice(\n alias.prefix.length,\n alias.suffix ? specifier.length - alias.suffix.length : undefined,\n );\n\n if (!matched) return undefined;\n\n return alias.targets.map((target) => target.replace(\"*\", matched));\n}\n\n/**\n * Resolve the tsconfig `paths` entries that esbuild's `alias` option cannot\n * express — the WILDCARD ones.\n *\n * **The defect.** `buildAliasMapFromTsconfig` skips any key ending in `/*`,\n * because esbuild's `alias` takes exact package names and nothing else. That\n * is a correct statement about `alias` and it left the wildcards handled by\n * nobody: `app/*` and `web/*` are how this app's own source refers to itself\n * (`import { User } from \"app/users/models/user.model\"`), and under\n * `packages: \"external\"` every one of those survived into the bundle as a\n * bare specifier. Node then looked for a PACKAGE called `app`:\n *\n * ```\n * Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from …/dist/app.js\n * ```\n *\n * The build reported success; the failure waited until `warlock start`.\n *\n * **The resolution is delegated, not reimplemented.** This plugin performs\n * only the substitution TypeScript defines — splice what `*` matched into the\n * target — and hands the resulting ABSOLUTE path straight back to esbuild\n * through `build.resolve`. Extension probing, `index` files, `exports` maps\n * and directory handling stay esbuild's, so a path alias resolves exactly as\n * the same file would have resolved through a relative import. A candidate\n * that does not resolve is reported as esbuild's own error rather than\n * quietly falling through to the next candidate and then to \"external\",\n * which is how this became a runtime failure in the first place.\n */\nexport function tsconfigPathAliases(options: {\n baseUrl: string;\n paths: Record<string, string[] | undefined>;\n}): Plugin {\n const aliases = collectWildcardPathAliases(options.paths, options.baseUrl);\n\n return {\n name: \"warlock:tsconfig-path-aliases\",\n setup(build) {\n if (aliases.length === 0) return;\n\n build.onResolve({ filter: /.*/ }, async (args) => {\n if (args.pluginData?.warlockTsconfigPathAlias) return undefined;\n if (args.namespace !== \"file\" && args.namespace !== \"\") return undefined;\n if (args.path.startsWith(\".\") || path.isAbsolute(args.path)) return undefined;\n\n for (const alias of aliases) {\n const candidates = substituteWildcard(alias, args.path);\n if (!candidates) continue;\n\n let lastResult: Awaited<ReturnType<typeof build.resolve>> | undefined;\n\n for (const candidate of candidates) {\n const result = await build.resolve(candidate, {\n kind: args.kind,\n importer: args.importer,\n resolveDir: args.resolveDir || path.dirname(args.importer),\n pluginData: { warlockTsconfigPathAlias: true },\n });\n\n lastResult = result;\n\n if (result.errors.length === 0) {\n return { path: result.path, external: result.external, namespace: result.namespace };\n }\n }\n\n // The prefix matched a declared alias and NO target resolved. That\n // is a broken import, and saying so here is the whole point — the\n // alternative is the silent external that produced the\n // `Cannot find package 'app'` above.\n return lastResult ? { errors: lastResult.errors } : undefined;\n }\n\n return undefined;\n });\n },\n };\n}\n"],"mappings":";;;;;;;;AAiBA,SAAgB,2BACd,OACA,SACqB;CACrB,MAAM,UAA+B,CAAC;CAEtC,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,KAAK,GAAG;EACnD,IAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,GAAG;EAErD,MAAM,OAAO,KAAK,QAAQ,GAAG;EAC7B,IAAI,SAAS,IAAI;EAEjB,QAAQ,KAAK;GACX,QAAQ,KAAK,MAAM,GAAG,IAAI;GAC1B,QAAQ,KAAK,MAAM,OAAO,CAAC;GAC3B,SAAS,QAAQ,KAAK,WAAW,KAAK,QAAQ,SAAS,MAAM,CAAC;EAChE,CAAC;CACH;CAKA,OAAO,QAAQ,MAAM,GAAG,MAAM,EAAE,OAAO,SAAS,EAAE,OAAO,MAAM;AACjE;;;;;AAMA,SAAgB,mBACd,OACA,WACsB;CACtB,IAAI,CAAC,UAAU,WAAW,MAAM,MAAM,GAAG,OAAO;CAChD,IAAI,MAAM,UAAU,CAAC,UAAU,SAAS,MAAM,MAAM,GAAG,OAAO;CAE9D,MAAM,UAAU,UAAU,MACxB,MAAM,OAAO,QACb,MAAM,SAAS,UAAU,SAAS,MAAM,OAAO,SAAS,MAC1D;CAEA,IAAI,CAAC,SAAS,OAAO;CAErB,OAAO,MAAM,QAAQ,KAAK,WAAW,OAAO,QAAQ,KAAK,OAAO,CAAC;AACnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,oBAAoB,SAGzB;CACT,MAAM,UAAU,2BAA2B,QAAQ,OAAO,QAAQ,OAAO;CAEzE,OAAO;EACL,MAAM;EACN,MAAM,OAAO;GACX,IAAI,QAAQ,WAAW,GAAG;GAE1B,MAAM,UAAU,EAAE,QAAQ,KAAK,GAAG,OAAO,SAAS;IAChD,IAAI,KAAK,YAAY,0BAA0B,OAAO;IACtD,IAAI,KAAK,cAAc,UAAU,KAAK,cAAc,IAAI,OAAO;IAC/D,IAAI,KAAK,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,KAAK,IAAI,GAAG,OAAO;IAEpE,KAAK,MAAM,SAAS,SAAS;KAC3B,MAAM,aAAa,mBAAmB,OAAO,KAAK,IAAI;KACtD,IAAI,CAAC,YAAY;KAEjB,IAAI;KAEJ,KAAK,MAAM,aAAa,YAAY;MAClC,MAAM,SAAS,MAAM,MAAM,QAAQ,WAAW;OAC5C,MAAM,KAAK;OACX,UAAU,KAAK;OACf,YAAY,KAAK,cAAc,KAAK,QAAQ,KAAK,QAAQ;OACzD,YAAY,EAAE,0BAA0B,KAAK;MAC/C,CAAC;MAED,aAAa;MAEb,IAAI,OAAO,OAAO,WAAW,GAC3B,OAAO;OAAE,MAAM,OAAO;OAAM,UAAU,OAAO;OAAU,WAAW,OAAO;MAAU;KAEvF;KAMA,OAAO,aAAa,EAAE,QAAQ,WAAW,OAAO,IAAI;IACtD;GAGF,CAAC;EACH;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"mappings":";;;;;AAqKA;;;;;;;;;;;;;iBAAgB,WAAA,CAAY,YAAA,EAAc,YAAA,GAAe,aAAA,GAAgB,SAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"mappings":";;;;;AAwKA;;;;;;;;;;;;;iBAAgB,WAAA,CAAY,YAAA,EAAc,YAAA,GAAe,aAAA,GAAgB,SAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport type { ComponentType, ReactElement, ReactNode } from \"react\";\n\n// ============================================================\n// Lazily Resolved React Modules\n// ============================================================\n\n/**\n * Installation instructions for React\n */\nconst REACT_INSTALL_INSTRUCTIONS = `\nReact SSR functionality requires React packages.\nInstall them with:\n\n warlock add react\n\nOr manually:\n\n npm install react react-dom\n pnpm add react react-dom\n yarn add react react-dom\n`.trim();\n\n/**\n * Cached React modules, populated by the first `resolveReactModules()` call\n */\nlet react: typeof import(\"react\") | null = null;\nlet reactDomServer: typeof import(\"react-dom/server\") | null = null;\n\n/**\n * Whether the resolution attempt already ran (success or failure)\n */\nlet reactResolved = false;\n\n/**\n * Why the resolution failed, when it failed.\n *\n * Cached and re-thrown on every later call: the resolution attempt runs exactly\n * once, so without this the second `renderReact()` would skip the attempt and\n * fall through to the \"not installed\" branch, reporting a different, wrong\n * cause one call after the accurate one.\n */\nlet reactLoadError: Error | null = null;\n\n/**\n * `new Error(message, { cause })` is ES2022, and this package still compiles\n * against the ES2020 lib (see #16), where `Error` is typed as taking a message\n * only. Node has supported the option since v16, so this is the type layer\n * catching up with the runtime, not a change in what the code does.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * Whether `error` says `specifier` itself is absent, as opposed to present but\n * broken.\n *\n * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a\n * dependency missing *inside* react raises the very same code (`Cannot find\n * module 'scheduler'`), and treating that as absence would tell the operator to\n * install a package they already have. So the message has to name the specifier\n * exactly — quoted, which is also what stops `'react-dom'` from matching a\n * check for `'react'`.\n */\nfunction isModuleMissing(error: unknown, specifier: string): boolean {\n if (!(error instanceof Error)) return false;\n\n return (\n (error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\" &&\n error.message.includes(`Cannot find module '${specifier}'`)\n );\n}\n\n/**\n * Require one module, translating its failure into a message that names the\n * specifier that actually failed.\n *\n * The two specifiers are resolved separately and reported separately: a broken\n * `react-dom/server` must never be announced as \"react is not installed\", since\n * that sends the operator to fix a package that is already fine.\n */\nfunction requireModule<T>(require: NodeRequire, specifier: string): T {\n try {\n const module = require(specifier);\n\n return (module.default ?? module) as T;\n } catch (error) {\n if (isModuleMissing(error, specifier)) {\n throw new Error(`${specifier} is not installed.\\n\\n${REACT_INSTALL_INSTRUCTIONS}`);\n }\n\n // The package is there, it just would not load. Its own error names the\n // real cause, so it is inlined *and* chained: a terminal that never prints\n // `cause` must still show the text that actually helps.\n throw new ErrorWithCause(`Failed to load \"${specifier}\": ${(error as Error).message}`, {\n cause: error,\n });\n }\n}\n\n/**\n * Resolve the React modules synchronously, on first use.\n *\n * Resolution is deliberately *lazy* and *synchronous*:\n *\n * - Lazy, because a top-level require would drag react and react-dom into every\n * `import \"@warlock.js/core\"`, including apps that never render a component.\n * - Synchronous, because `renderReact()` is synchronous. An async import kicked\n * off at module load leaves a window in which the modules are neither loaded\n * nor known to be missing, and a render running inside that window has no\n * correct answer to give — it used to read `createElement` off `undefined`.\n *\n * `createRequire` gives an ESM-safe `require`, and the outcome — modules,\n * absence or load failure — is cached, so resolution runs exactly once per\n * process. The failure *reason* is cached too, not just the fact of it: every\n * call after a failed load has to report the same cause as the first one.\n *\n * @throws when react or react-dom is not installed, or cannot be loaded\n */\nfunction resolveReactModules() {\n if (!reactResolved) {\n reactResolved = true;\n\n try {\n const require = createRequire(import.meta.url);\n react = requireModule<typeof import(\"react\")>(require, \"react\");\n reactDomServer = requireModule<typeof import(\"react-dom/server\")>(require, \"react-dom/server\");\n } catch (error) {\n react = null;\n reactDomServer = null;\n reactLoadError = error as Error;\n }\n }\n\n if (reactLoadError) {\n throw reactLoadError;\n }\n\n if (!react || !reactDomServer) {\n throw new Error(`react is not installed.\\n\\n${REACT_INSTALL_INSTRUCTIONS}`);\n }\n\n return { react, reactDomServer };\n}\n\n// ============================================================\n// Render Function\n// ============================================================\n\n/**\n * Render a React element/component to HTML string\n *\n * **Important:** This function requires React packages to be installed.\n * Install them with: `warlock add react` or `yarn add react react-dom`\n *\n * React is resolved synchronously on the first call that needs it, so this\n * function stays synchronous and missing packages throw here rather than\n * surfacing later as a read off an undefined module.\n *\n * @example\n * ```typescript\n * const html = renderReact(<WelcomeEmail name=\"John\" />);\n * ```\n */\nexport function renderReact(reactElement: ReactElement | ComponentType | ReactNode): string {\n const { react, reactDomServer } = resolveReactModules();\n\n if (typeof reactElement === \"function\") {\n reactElement = react.createElement(reactElement);\n }\n\n return reactDomServer.renderToString(reactElement);\n}\n"],"mappings":";;;;;;AAUA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,QAAuC;AAC3C,IAAI,iBAA2D;;;;AAK/D,IAAI,gBAAgB;;;;;;;;;AAUpB,IAAI,iBAA+B;AAUnC,MAAM,iBAAiB;;;;;;;;;;;;AAavB,SAAS,gBAAgB,OAAgB,WAA4B;CACnE,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,OACG,MAAgC,SAAS,sBAC1C,MAAM,QAAQ,SAAS,uBAAuB,UAAU,EAAE;AAE9D;;;;;;;;;AAUA,SAAS,cAAiB,SAAsB,WAAsB;CACpE,IAAI;EACF,MAAM,SAAS,QAAQ,SAAS;EAEhC,OAAQ,OAAO,WAAW;CAC5B,SAAS,OAAO;EACd,IAAI,gBAAgB,OAAO,SAAS,GAClC,MAAM,IAAI,MAAM,GAAG,UAAU,wBAAwB,4BAA4B;EAMnF,MAAM,IAAI,eAAe,mBAAmB,UAAU,KAAM,MAAgB,WAAW,EACrF,OAAO,MACT,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,sBAAsB;CAC7B,IAAI,CAAC,eAAe;EAClB,gBAAgB;EAEhB,IAAI;GACF,MAAM,UAAU,cAAc,OAAO,KAAK,GAAG;GAC7C,QAAQ,cAAsC,SAAS,OAAO;GAC9D,iBAAiB,cAAiD,SAAS,kBAAkB;EAC/F,SAAS,OAAO;GACd,QAAQ;GACR,iBAAiB;GACjB,iBAAiB;EACnB;CACF;CAEA,IAAI,gBACF,MAAM;CAGR,IAAI,CAAC,SAAS,CAAC,gBACb,MAAM,IAAI,MAAM,8BAA8B,4BAA4B;CAG5E,OAAO;EAAE;EAAO;CAAe;AACjC;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,cAAgE;CAC1F,MAAM,EAAE,OAAO,mBAAmB,oBAAoB;CAEtD,IAAI,OAAO,iBAAiB,YAC1B,eAAe,MAAM,cAAc,YAAY;CAGjD,OAAO,eAAe,eAAe,YAAY;AACnD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport type { ComponentType, ReactElement, ReactNode } from \"react\";\n\n// ============================================================\n// Lazily Resolved React Modules\n// ============================================================\n\n/**\n * Installation instructions for React\n */\nconst REACT_INSTALL_INSTRUCTIONS = `\nReact SSR functionality requires React packages.\nInstall them with:\n\n warlock add react\n\nOr manually:\n\n npm install react react-dom\n pnpm add react react-dom\n yarn add react react-dom\n`.trim();\n\n/**\n * Cached React modules, populated by the first `resolveReactModules()` call\n */\nlet react: typeof import(\"react\") | null = null;\nlet reactDomServer: typeof import(\"react-dom/server\") | null = null;\n\n/**\n * Whether the resolution attempt already ran (success or failure)\n */\nlet reactResolved = false;\n\n/**\n * Why the resolution failed, when it failed.\n *\n * Cached and re-thrown on every later call: the resolution attempt runs exactly\n * once, so without this the second `renderReact()` would skip the attempt and\n * fall through to the \"not installed\" branch, reporting a different, wrong\n * cause one call after the accurate one.\n */\nlet reactLoadError: Error | null = null;\n\n/**\n * `new Error(message, { cause })` is ES2022, and this package still compiles\n * against the ES2020 lib (see #16), where `Error` is typed as taking a message\n * only. Node has supported the option since v16, so this is the type layer\n * catching up with the runtime, not a change in what the code does.\n */\ntype ErrorWithCauseConstructor = new (message: string, options: { cause: unknown }) => Error;\n\nconst ErrorWithCause = Error as ErrorWithCauseConstructor;\n\n/**\n * Whether `error` says `specifier` itself is absent, as opposed to present but\n * broken.\n *\n * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a\n * dependency missing *inside* react raises the very same code (`Cannot find\n * module 'scheduler'`), and treating that as absence would tell the operator to\n * install a package they already have. So the message has to name the specifier\n * exactly — quoted, which is also what stops `'react-dom'` from matching a\n * check for `'react'`.\n */\nfunction isModuleMissing(error: unknown, specifier: string): boolean {\n if (!(error instanceof Error)) return false;\n\n return (\n (error as NodeJS.ErrnoException).code === \"MODULE_NOT_FOUND\" &&\n error.message.includes(`Cannot find module '${specifier}'`)\n );\n}\n\n/**\n * Require one module, translating its failure into a message that names the\n * specifier that actually failed.\n *\n * The two specifiers are resolved separately and reported separately: a broken\n * `react-dom/server` must never be announced as \"react is not installed\", since\n * that sends the operator to fix a package that is already fine.\n */\nfunction requireModule<T>(require: NodeRequire, specifier: string): T {\n try {\n const module = require(specifier);\n\n return (module.default ?? module) as T;\n } catch (error) {\n if (isModuleMissing(error, specifier)) {\n throw new Error(`${specifier} is not installed.\\n\\n${REACT_INSTALL_INSTRUCTIONS}`);\n }\n\n // The package is there, it just would not load. Its own error names the\n // real cause, so it is inlined *and* chained: a terminal that never prints\n // `cause` must still show the text that actually helps.\n throw new ErrorWithCause(`Failed to load \"${specifier}\": ${(error as Error).message}`, {\n cause: error,\n });\n }\n}\n\n/**\n * Resolve the React modules synchronously, on first use.\n *\n * Resolution is deliberately *lazy* and *synchronous*:\n *\n * - Lazy, because a top-level require would drag react and react-dom into every\n * `import \"@warlock.js/core\"`, including apps that never render a component.\n * - Synchronous, because `renderReact()` is synchronous. An async import kicked\n * off at module load leaves a window in which the modules are neither loaded\n * nor known to be missing, and a render running inside that window has no\n * correct answer to give — it used to read `createElement` off `undefined`.\n *\n * `createRequire` gives an ESM-safe `require`, and the outcome — modules,\n * absence or load failure — is cached, so resolution runs exactly once per\n * process. The failure *reason* is cached too, not just the fact of it: every\n * call after a failed load has to report the same cause as the first one.\n *\n * @throws when react or react-dom is not installed, or cannot be loaded\n */\nfunction resolveReactModules() {\n if (!reactResolved) {\n reactResolved = true;\n\n try {\n const require = createRequire(import.meta.url);\n react = requireModule<typeof import(\"react\")>(require, \"react\");\n reactDomServer = requireModule<typeof import(\"react-dom/server\")>(\n require,\n \"react-dom/server\",\n );\n } catch (error) {\n react = null;\n reactDomServer = null;\n reactLoadError = error as Error;\n }\n }\n\n if (reactLoadError) {\n throw reactLoadError;\n }\n\n if (!react || !reactDomServer) {\n throw new Error(`react is not installed.\\n\\n${REACT_INSTALL_INSTRUCTIONS}`);\n }\n\n return { react, reactDomServer };\n}\n\n// ============================================================\n// Render Function\n// ============================================================\n\n/**\n * Render a React element/component to HTML string\n *\n * **Important:** This function requires React packages to be installed.\n * Install them with: `warlock add react` or `yarn add react react-dom`\n *\n * React is resolved synchronously on the first call that needs it, so this\n * function stays synchronous and missing packages throw here rather than\n * surfacing later as a read off an undefined module.\n *\n * @example\n * ```typescript\n * const html = renderReact(<WelcomeEmail name=\"John\" />);\n * ```\n */\nexport function renderReact(reactElement: ReactElement | ComponentType | ReactNode): string {\n const { react, reactDomServer } = resolveReactModules();\n\n if (typeof reactElement === \"function\") {\n reactElement = react.createElement(reactElement);\n }\n\n return reactDomServer.renderToString(reactElement);\n}\n"],"mappings":";;;;;;AAUA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,QAAuC;AAC3C,IAAI,iBAA2D;;;;AAK/D,IAAI,gBAAgB;;;;;;;;;AAUpB,IAAI,iBAA+B;AAUnC,MAAM,iBAAiB;;;;;;;;;;;;AAavB,SAAS,gBAAgB,OAAgB,WAA4B;CACnE,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,OACG,MAAgC,SAAS,sBAC1C,MAAM,QAAQ,SAAS,uBAAuB,UAAU,EAAE;AAE9D;;;;;;;;;AAUA,SAAS,cAAiB,SAAsB,WAAsB;CACpE,IAAI;EACF,MAAM,SAAS,QAAQ,SAAS;EAEhC,OAAQ,OAAO,WAAW;CAC5B,SAAS,OAAO;EACd,IAAI,gBAAgB,OAAO,SAAS,GAClC,MAAM,IAAI,MAAM,GAAG,UAAU,wBAAwB,4BAA4B;EAMnF,MAAM,IAAI,eAAe,mBAAmB,UAAU,KAAM,MAAgB,WAAW,EACrF,OAAO,MACT,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,sBAAsB;CAC7B,IAAI,CAAC,eAAe;EAClB,gBAAgB;EAEhB,IAAI;GACF,MAAM,UAAU,cAAc,OAAO,KAAK,GAAG;GAC7C,QAAQ,cAAsC,SAAS,OAAO;GAC9D,iBAAiB,cACf,SACA,kBACF;EACF,SAAS,OAAO;GACd,QAAQ;GACR,iBAAiB;GACjB,iBAAiB;EACnB;CACF;CAEA,IAAI,gBACF,MAAM;CAGR,IAAI,CAAC,SAAS,CAAC,gBACb,MAAM,IAAI,MAAM,8BAA8B,4BAA4B;CAG5E,OAAO;EAAE;EAAO;CAAe;AACjC;;;;;;;;;;;;;;;;AAqBA,SAAgB,YAAY,cAAgE;CAC1F,MAAM,EAAE,OAAO,mBAAmB,oBAAoB;CAEtD,IAAI,OAAO,iBAAiB,YAC1B,eAAe,MAAM,cAAc,YAAY;CAGjD,OAAO,eAAe,eAAe,YAAY;AACnD"}
@@ -13,10 +13,11 @@ var FilterApplicator = class {
13
13
  * @param options - Additional filter options (date formats, etc.)
14
14
  */
15
15
  apply(query, filters, data, options) {
16
- for (const key in filters) {
16
+ for (const [key, filterRule] of Object.entries(filters)) {
17
17
  const value = data[key];
18
18
  if (value === void 0) continue;
19
- const rule = this.parseFilterRule(key, filters[key]);
19
+ if (filterRule === void 0) continue;
20
+ const rule = this.parseFilterRule(key, filterRule);
20
21
  this.applyFilterRule(query, rule, value, data, options);
21
22
  }
22
23
  }
@@ -350,6 +351,7 @@ var FilterApplicator = class {
350
351
  handleDateBetween(query, column, columns, value, options) {
351
352
  if (!Array.isArray(value) || value.length !== 2) return;
352
353
  const [start, end] = value.map((v) => this.parseDate(v, options?.dateFormat));
354
+ if (start === void 0 || end === void 0) return;
353
355
  if (column) query.whereDateBetween(column, [start, end]);
354
356
  else if (columns) for (const col of columns) query.orWhere((q) => q.whereDateBetween(col, [start, end]));
355
357
  }