@warlock.js/core 4.10.0 → 4.12.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 (144) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/esm/application/application.d.mts +19 -0
  3. package/esm/application/application.d.mts.map +1 -1
  4. package/esm/application/application.mjs +25 -0
  5. package/esm/application/application.mjs.map +1 -1
  6. package/esm/application/boot-signal.d.mts +77 -0
  7. package/esm/application/boot-signal.d.mts.map +1 -0
  8. package/esm/application/boot-signal.mjs +64 -0
  9. package/esm/application/boot-signal.mjs.map +1 -0
  10. package/esm/application/index.d.mts +1 -0
  11. package/esm/application/index.mjs +1 -0
  12. package/esm/bootstrap.mjs +2 -2
  13. package/esm/bootstrap.mjs.map +1 -1
  14. package/esm/cli/cli-commands.manager.mjs +31 -8
  15. package/esm/cli/cli-commands.manager.mjs.map +1 -1
  16. package/esm/cli/cli-commands.utils.mjs +57 -1
  17. package/esm/cli/cli-commands.utils.mjs.map +1 -1
  18. package/esm/cli/commands/add.command.mjs +4 -2
  19. package/esm/cli/commands/add.command.mjs.map +1 -1
  20. package/esm/cli/commands/generate/generate.command.mjs +42 -21
  21. package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
  22. package/esm/cli/commands/generate/generators/module.generator.mjs +1 -1
  23. package/esm/cli/commands/generate/generators/module.generator.mjs.map +1 -1
  24. package/esm/cli/commands/migrate.command.mjs +6 -2
  25. package/esm/cli/commands/migrate.command.mjs.map +1 -1
  26. package/esm/cli/commands/start-production.command.mjs +4 -25
  27. package/esm/cli/commands/start-production.command.mjs.map +1 -1
  28. package/esm/cli/parse-cli-args.mjs +86 -9
  29. package/esm/cli/parse-cli-args.mjs.map +1 -1
  30. package/esm/cli/types.d.mts +6 -1
  31. package/esm/cli/types.d.mts.map +1 -1
  32. package/esm/config/config-getter.mjs +5 -5
  33. package/esm/config/config-getter.mjs.map +1 -1
  34. package/esm/config/config-loader.mjs +2 -2
  35. package/esm/config/config-loader.mjs.map +1 -1
  36. package/esm/config/config-setter.d.mts +27 -0
  37. package/esm/config/config-setter.d.mts.map +1 -0
  38. package/esm/config/config-setter.mjs +10 -0
  39. package/esm/config/config-setter.mjs.map +1 -0
  40. package/esm/config/index.mjs +1 -0
  41. package/esm/connectors/access-connector.mjs +2 -2
  42. package/esm/connectors/access-connector.mjs.map +1 -1
  43. package/esm/connectors/ai-connector.mjs +2 -2
  44. package/esm/connectors/ai-connector.mjs.map +1 -1
  45. package/esm/connectors/cache-connector.mjs +2 -2
  46. package/esm/connectors/cache-connector.mjs.map +1 -1
  47. package/esm/connectors/database-connector.mjs +2 -2
  48. package/esm/connectors/database-connector.mjs.map +1 -1
  49. package/esm/connectors/herald-connector.mjs +2 -2
  50. package/esm/connectors/herald-connector.mjs.map +1 -1
  51. package/esm/connectors/http-connector.d.mts.map +1 -1
  52. package/esm/connectors/http-connector.mjs +8 -7
  53. package/esm/connectors/http-connector.mjs.map +1 -1
  54. package/esm/connectors/logger-connector.mjs +2 -2
  55. package/esm/connectors/logger-connector.mjs.map +1 -1
  56. package/esm/connectors/mail-connector.mjs +2 -2
  57. package/esm/connectors/mail-connector.mjs.map +1 -1
  58. package/esm/connectors/notifications-connector.mjs +2 -2
  59. package/esm/connectors/notifications-connector.mjs.map +1 -1
  60. package/esm/connectors/socket-connector.mjs +3 -3
  61. package/esm/connectors/socket-connector.mjs.map +1 -1
  62. package/esm/connectors/storage.connector.d.mts +11 -5
  63. package/esm/connectors/storage.connector.d.mts.map +1 -1
  64. package/esm/connectors/storage.connector.mjs +11 -5
  65. package/esm/connectors/storage.connector.mjs.map +1 -1
  66. package/esm/database/migrate-action.mjs +53 -1
  67. package/esm/database/migrate-action.mjs.map +1 -1
  68. package/esm/database/pending-exit-code.mjs +39 -0
  69. package/esm/database/pending-exit-code.mjs.map +1 -0
  70. package/esm/database/resolve-pending-migrations.mjs +49 -0
  71. package/esm/database/resolve-pending-migrations.mjs.map +1 -0
  72. package/esm/dev-server/loader/load-hook.mjs +1 -1
  73. package/esm/generations/stubs.mjs +1 -1
  74. package/esm/generations/stubs.mjs.map +1 -1
  75. package/esm/http/config.mjs +2 -2
  76. package/esm/http/config.mjs.map +1 -1
  77. package/esm/http/createHttpApplication.mjs +2 -2
  78. package/esm/http/createHttpApplication.mjs.map +1 -1
  79. package/esm/http/index.d.mts +1 -0
  80. package/esm/http/index.mjs +1 -0
  81. package/esm/http/middleware/idempotency.middleware.mjs +5 -5
  82. package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
  83. package/esm/http/middleware/inject-request-context.mjs +2 -2
  84. package/esm/http/middleware/inject-request-context.mjs.map +1 -1
  85. package/esm/http/middleware/maintenance.middleware.mjs +4 -4
  86. package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
  87. package/esm/http/plugins.mjs +9 -9
  88. package/esm/http/plugins.mjs.map +1 -1
  89. package/esm/http/port-preflight.d.mts +34 -0
  90. package/esm/http/port-preflight.d.mts.map +1 -0
  91. package/esm/http/port-preflight.mjs +66 -0
  92. package/esm/http/port-preflight.mjs.map +1 -0
  93. package/esm/http/response.mjs +5 -5
  94. package/esm/http/response.mjs.map +1 -1
  95. package/esm/http/server.mjs +4 -4
  96. package/esm/http/server.mjs.map +1 -1
  97. package/esm/image/image.d.mts +3 -2
  98. package/esm/image/image.d.mts.map +1 -1
  99. package/esm/image/image.mjs +63 -17
  100. package/esm/image/image.mjs.map +1 -1
  101. package/esm/index.d.mts +6 -2
  102. package/esm/index.mjs +5 -1
  103. package/esm/mail/mailer-pool.d.mts.map +1 -1
  104. package/esm/mail/mailer-pool.mjs.map +1 -1
  105. package/esm/production/assert-generated-imports.mjs +94 -0
  106. package/esm/production/assert-generated-imports.mjs.map +1 -0
  107. package/esm/production/production-builder.mjs +29 -4
  108. package/esm/production/production-builder.mjs.map +1 -1
  109. package/esm/production/production-supervisor.mjs +108 -0
  110. package/esm/production/production-supervisor.mjs.map +1 -0
  111. package/esm/react/index.d.mts +4 -0
  112. package/esm/react/index.d.mts.map +1 -1
  113. package/esm/react/index.mjs +88 -14
  114. package/esm/react/index.mjs.map +1 -1
  115. package/esm/storage/storage.d.mts +16 -0
  116. package/esm/storage/storage.d.mts.map +1 -1
  117. package/esm/storage/storage.mjs +24 -1
  118. package/esm/storage/storage.mjs.map +1 -1
  119. package/esm/tests/index.d.mts +2 -1
  120. package/esm/tests/index.mjs +1 -0
  121. package/esm/tests/start-http-development-server.d.mts +15 -2
  122. package/esm/tests/start-http-development-server.d.mts.map +1 -1
  123. package/esm/tests/start-http-development-server.mjs +43 -16
  124. package/esm/tests/start-http-development-server.mjs.map +1 -1
  125. package/esm/tests/test-helpers.d.mts.map +1 -1
  126. package/esm/tests/test-helpers.mjs +2 -1
  127. package/esm/tests/test-helpers.mjs.map +1 -1
  128. package/esm/tests/test-server-port-channel.d.mts +27 -0
  129. package/esm/tests/test-server-port-channel.d.mts.map +1 -0
  130. package/esm/tests/test-server-port-channel.mjs +32 -0
  131. package/esm/tests/test-server-port-channel.mjs.map +1 -0
  132. package/esm/utils/load-environment.mjs +59 -0
  133. package/esm/utils/load-environment.mjs.map +1 -0
  134. package/esm/utils/paths.mjs +2 -2
  135. package/esm/utils/paths.mjs.map +1 -1
  136. package/esm/validation/validateAll.mjs +2 -2
  137. package/esm/validation/validateAll.mjs.map +1 -1
  138. package/llms-full.txt +90 -3
  139. package/llms.txt +1 -1
  140. package/package.json +13 -13
  141. package/skills/process-image/SKILL.md +3 -1
  142. package/skills/run-app/SKILL.md +63 -0
  143. package/skills/test-http/SKILL.md +27 -3
  144. package/skills/write-cli-command/SKILL.md +19 -1
@@ -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 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 { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, warlockPath } from \"../utils\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\r\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\r\nimport { toCamelCase, toKebabCase } from \"@mongez/reinforcements\";\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 * Main build entry point\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 // 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: Bundle with esbuild\r\n await this.bundle();\r\n\r\n // // Step 5: 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\r\n // Ensure production directory exists\r\n await ensureDirectoryAsync(this.productionDir);\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 * 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 const imports: string[] = [\r\n 'import config from \"@mongez/config\";',\r\n 'import { 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(`config.set(\"${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 private async generateEntryPoint(): Promise<void> {\r\n console.log(colors.yellow(\" Generating entry point...\"));\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 \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\r\n \"// so data sources, cache, etc. are ready before app code runs\",\r\n 'import { Application, connectorsManager, ConnectorLifecyclePhase } from \"@warlock.js/core\";',\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 // Requires `splitting: true` in esbuild (set below in bundle()).\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 // Start late-phase connectors after app code registers routes/listeners\r\n imports.push(\r\n \"\",\r\n \"// 5. 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 \"// 6. 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 private async bundle(): 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 outDir = this.options.outdir!;\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 delete this.options.outFile;\r\n delete this.options.entryPath;\r\n\r\n await ensureDirectoryAsync(outDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\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 // Required so dynamic `await import(\"./main\")` in the generated\r\n // app.ts produces separate chunks loaded at the runtime call site,\r\n // instead of inlining the modules at instantiation time (which\r\n // would defeat the early/late phase split).\r\n splitting: true,\r\n packages: \"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 outdir: outDir,\r\n entryNames: entryName,\r\n alias,\r\n plugins: [nativeNodeModulesPlugin],\r\n ...(this.options as any),\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":";;;;;;;;;;;;;;;;;;AAqBA,IAAa,oBAAb,MAA+B;;uBAEI,YAAY,YAAY;wBAwChC;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;CAxCA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA8B,CAAC;EAGvD,MAAM,KAAK,kBAAkB;EAG7B,MAAM,KAAK,sBAAsB;EAGjC,MAAM,KAAK,mBAAmB;EAG9B,MAAM,KAAK,OAAO;EAGlB,MAAM,qBAAqB,KAAK,aAAa;EAE7C,QAAQ,IAAI,OAAO,MAAM,iBAAiB,CAAC;EAC3C,QAAQ,IAAI,sCAAsC,OAAO,KAAK,eAAe,GAAG;CAClF;;;;CAKA,MAAc,oBAAmC;EAC/C,KAAK,UAAU,mB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O,WAAW,KAAK,QAAS;IACvE,QAAQ;IAIR,QAAQ,CAAC,QAAQ;IACjB,QAAQ;IACR,YAAY;IACZ;IACA,SAAS,CAAC,uBAAuB;IACjC,GAAI,KAAK;GACX,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 { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, rootPath, warlockPath } from \"../utils\";\r\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\r\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\r\nimport { toCamelCase, toKebabCase } from \"@mongez/reinforcements\";\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 * Main build entry point\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 // 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 5: Bundle with esbuild\r\n await this.bundle();\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\r\n // Ensure production directory exists\r\n await ensureDirectoryAsync(this.productionDir);\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 private async generateEntryPoint(): Promise<void> {\r\n console.log(colors.yellow(\" Generating entry point...\"));\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 \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\r\n \"// so data sources, cache, etc. are ready before app code runs\",\r\n 'import { Application, connectorsManager, ConnectorLifecyclePhase } from \"@warlock.js/core\";',\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 // Requires `splitting: true` in esbuild (set below in bundle()).\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 // Start late-phase connectors after app code registers routes/listeners\r\n imports.push(\r\n \"\",\r\n \"// 5. 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 \"// 6. 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 private async bundle(): 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 outDir = this.options.outdir!;\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 delete this.options.outFile;\r\n delete this.options.entryPath;\r\n\r\n await ensureDirectoryAsync(outDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\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 // Required so dynamic `await import(\"./main\")` in the generated\r\n // app.ts produces separate chunks loaded at the runtime call site,\r\n // instead of inlining the modules at instantiation time (which\r\n // would defeat the early/late phase split).\r\n splitting: true,\r\n packages: \"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 outdir: outDir,\r\n entryNames: entryName,\r\n alias,\r\n plugins: [nativeNodeModulesPlugin],\r\n ...(this.options as any),\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":";;;;;;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,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"}
@@ -0,0 +1,108 @@
1
+ import { BOOT_SIGNAL_ENV_KEY, isBootSignal } from "../application/boot-signal.mjs";
2
+ import { displayMissingReadinessNotice, displayProductionReadyBanner, displayProductionStartFailure } from "../cli/cli-commands.utils.mjs";
3
+ import { spawn } from "child_process";
4
+
5
+ //#region ../core/src/production/production-supervisor.ts
6
+ /**
7
+ * How long a still-running child may stay silent before we say so.
8
+ *
9
+ * Only reached by a bundle built before readiness reporting existed; a current
10
+ * bundle signals as soon as its late-phase connectors are up.
11
+ */
12
+ const DEFAULT_READINESS_NOTICE_DELAY_MS = 1e4;
13
+ /**
14
+ * Run the production bundle in a child process and report honestly on it.
15
+ *
16
+ * The supervisor exists because a parent with `stdio: "inherit"` cannot see
17
+ * whether its child ever booted — it only sees the process exit. It therefore
18
+ * opens an IPC channel and treats the child's `warlock:ready` signal, emitted
19
+ * by `Application.markBooted`, as the single source of truth for "started":
20
+ *
21
+ * 1. The success banner is printed only on that signal.
22
+ * 2. A child that dies before signalling is reported as a failed start and
23
+ * forced to a non-zero exit, even if it exited 0.
24
+ * 3. A child still running without having signalled draws a note on stderr —
25
+ * never stdout, which would be the false-green this whole channel prevents.
26
+ *
27
+ * Resolves rather than exiting so the outcome stays assertable in a test; the
28
+ * `start` command turns the result into the process exit code.
29
+ */
30
+ function superviseProductionProcess({ nodeArgs, cwd = process.cwd(), env = process.env, readinessNoticeDelayMs = DEFAULT_READINESS_NOTICE_DELAY_MS }) {
31
+ return new Promise((resolve) => {
32
+ const child = spawn(process.execPath, nodeArgs, {
33
+ stdio: [
34
+ "inherit",
35
+ "inherit",
36
+ "inherit",
37
+ "ipc"
38
+ ],
39
+ cwd,
40
+ env: {
41
+ ...env,
42
+ [BOOT_SIGNAL_ENV_KEY]: "1"
43
+ },
44
+ detached: false
45
+ });
46
+ const startedAt = Date.now();
47
+ let isReady = false;
48
+ let isShuttingDown = false;
49
+ let isSettled = false;
50
+ const readinessNoticeTimer = setTimeout(() => {
51
+ if (isReady) return;
52
+ displayMissingReadinessNotice(Date.now() - startedAt);
53
+ }, readinessNoticeDelayMs);
54
+ readinessNoticeTimer.unref?.();
55
+ const settle = (result) => {
56
+ if (isSettled) return;
57
+ isSettled = true;
58
+ clearTimeout(readinessNoticeTimer);
59
+ process.off("SIGTERM", onSigterm);
60
+ process.off("SIGINT", onSigint);
61
+ resolve(result);
62
+ };
63
+ child.on("message", (message) => {
64
+ if (isReady || !isBootSignal(message)) return;
65
+ isReady = true;
66
+ clearTimeout(readinessNoticeTimer);
67
+ displayProductionReadyBanner({ bootDurationMs: message.bootDurationMs }).catch((error) => {
68
+ console.error(error);
69
+ });
70
+ });
71
+ child.on("error", (error) => {
72
+ displayProductionStartFailure(1);
73
+ console.error(error);
74
+ settle({
75
+ exitCode: 1,
76
+ ready: false
77
+ });
78
+ });
79
+ const onSigterm = () => {
80
+ if (isShuttingDown) return;
81
+ isShuttingDown = true;
82
+ child.kill("SIGTERM");
83
+ };
84
+ const onSigint = () => {
85
+ isShuttingDown = true;
86
+ };
87
+ process.on("SIGTERM", onSigterm);
88
+ process.on("SIGINT", onSigint);
89
+ child.on("exit", (code) => {
90
+ if (!isReady && !isShuttingDown) {
91
+ const exitCode = code === 0 || code === null ? 1 : code;
92
+ displayProductionStartFailure(exitCode);
93
+ return settle({
94
+ exitCode,
95
+ ready: false
96
+ });
97
+ }
98
+ settle({
99
+ exitCode: code ?? 0,
100
+ ready: isReady
101
+ });
102
+ });
103
+ });
104
+ }
105
+
106
+ //#endregion
107
+ export { superviseProductionProcess };
108
+ //# sourceMappingURL=production-supervisor.mjs.map
@@ -0,0 +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 with `stdio: \"inherit\"` cannot see\n * whether its child ever booted — it only sees the process exit. It therefore\n * opens an IPC channel and treats the child's `warlock:ready` signal, emitted\n * by `Application.markBooted`, as the single source of truth 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 *\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 const child = spawn(process.execPath, nodeArgs, {\n stdio: [\"inherit\", \"inherit\", \"inherit\", \"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 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 child.on(\"error\", (error) => {\n displayProductionStartFailure(1);\n console.error(error);\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 child.on(\"exit\", (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);\n\n return settle({ exitCode, ready: false });\n }\n\n settle({ exitCode: code ?? 0, ready: isReady });\n });\n });\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAa,oCAAoC;;;;;;;;;;;;;;;;;;AAkCjD,SAAgB,2BAA2B,EACzC,UACA,MAAM,QAAQ,IAAI,GAClB,MAAM,QAAQ,KACd,yBAAyB,qCAC0C;CACnE,OAAO,IAAI,SAAqC,YAAY;EAW1D,MAAM,QAAQ,MAAM,QAAQ,UAAU,UAAU;GAC9C,OAAO;IAAC;IAAW;IAAW;IAAW;GAAK;GAC9C;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;EAEhB,MAAM,uBAAuB,iBAAiB;GAC5C,IAAI,SACF;GAGF,8BAA8B,KAAK,IAAI,IAAI,SAAS;EACtD,GAAG,sBAAsB;EAGzB,qBAAqB,QAAQ;EAE7B,MAAM,UAAU,WAAuC;GACrD,IAAI,WACF;GAGF,YAAY;GACZ,aAAa,oBAAoB;GACjC,QAAQ,IAAI,WAAW,SAAS;GAChC,QAAQ,IAAI,UAAU,QAAQ;GAE9B,QAAQ,MAAM;EAChB;EAEA,MAAM,GAAG,YAAY,YAAqB;GACxC,IAAI,WAAW,CAAC,aAAa,OAAO,GAClC;GAGF,UAAU;GACV,aAAa,oBAAoB;GAEjC,6BAA6B,EAAE,gBAAgB,QAAQ,eAAe,CAAC,CAAC,CAAC,OAAO,UAAU;IAGxF,QAAQ,MAAM,KAAK;GACrB,CAAC;EACH,CAAC;EAID,MAAM,GAAG,UAAU,UAAU;GAC3B,8BAA8B,CAAC;GAC/B,QAAQ,MAAM,KAAK;GAEnB,OAAO;IAAE,UAAU;IAAG,OAAO;GAAM,CAAC;EACtC,CAAC;EAGD,MAAM,kBAAkB;GACtB,IAAI,gBACF;GAGF,iBAAiB;GACjB,MAAM,KAAK,SAAS;EACtB;EAIA,MAAM,iBAAiB;GACrB,iBAAiB;EACnB;EAEA,QAAQ,GAAG,WAAW,SAAS;EAC/B,QAAQ,GAAG,UAAU,QAAQ;EAE7B,MAAM,GAAG,SAAS,SAAS;GAQzB,IAAI,CAAC,WAAW,CAAC,gBAAgB;IAC/B,MAAM,WAAW,SAAS,KAAK,SAAS,OAAO,IAAI;IAEnD,8BAA8B,QAAQ;IAEtC,OAAO,OAAO;KAAE;KAAU,OAAO;IAAM,CAAC;GAC1C;GAEA,OAAO;IAAE,UAAU,QAAQ;IAAG,OAAO;GAAQ,CAAC;EAChD,CAAC;CACH,CAAC;AACH"}
@@ -7,6 +7,10 @@ import { ComponentType, ReactElement, ReactNode } from "react";
7
7
  * **Important:** This function requires React packages to be installed.
8
8
  * Install them with: `warlock add react` or `yarn add react react-dom`
9
9
  *
10
+ * React is resolved synchronously on the first call that needs it, so this
11
+ * function stays synchronous and missing packages throw here rather than
12
+ * surfacing later as a read off an undefined module.
13
+ *
10
14
  * @example
11
15
  * ```typescript
12
16
  * const html = renderReact(<WelcomeEmail name="John" />);
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"mappings":";;;;;AAgEA;;;;;;;;;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":";;;;;AAqKA;;;;;;;;;;;;;iBAAgB,WAAA,CAAY,YAAA,EAAc,YAAA,GAAe,aAAA,GAAgB,SAAA"}
@@ -1,3 +1,5 @@
1
+ import { createRequire } from "node:module";
2
+
1
3
  //#region ../core/src/react/index.ts
2
4
  /**
3
5
  * Installation instructions for React
@@ -15,40 +17,112 @@ Or manually:
15
17
  yarn add react react-dom
16
18
  `.trim();
17
19
  /**
18
- * Module availability flag
20
+ * Cached React modules, populated by the first `resolveReactModules()` call
19
21
  */
20
- let moduleExists = null;
22
+ let react = null;
23
+ let reactDomServer = null;
21
24
  /**
22
- * Cached React modules (loaded at import time)
25
+ * Whether the resolution attempt already ran (success or failure)
23
26
  */
24
- let react;
25
- let reactDomServer;
27
+ let reactResolved = false;
26
28
  /**
27
- * Eagerly load React modules at import time
29
+ * Why the resolution failed, when it failed.
30
+ *
31
+ * Cached and re-thrown on every later call: the resolution attempt runs exactly
32
+ * once, so without this the second `renderReact()` would skip the attempt and
33
+ * fall through to the "not installed" branch, reporting a different, wrong
34
+ * cause one call after the accurate one.
35
+ */
36
+ let reactLoadError = null;
37
+ const ErrorWithCause = Error;
38
+ /**
39
+ * Whether `error` says `specifier` itself is absent, as opposed to present but
40
+ * broken.
41
+ *
42
+ * Both halves are load-bearing. `MODULE_NOT_FOUND` alone is not enough: a
43
+ * dependency missing *inside* react raises the very same code (`Cannot find
44
+ * module 'scheduler'`), and treating that as absence would tell the operator to
45
+ * install a package they already have. So the message has to name the specifier
46
+ * exactly — quoted, which is also what stops `'react-dom'` from matching a
47
+ * check for `'react'`.
48
+ */
49
+ function isModuleMissing(error, specifier) {
50
+ if (!(error instanceof Error)) return false;
51
+ return error.code === "MODULE_NOT_FOUND" && error.message.includes(`Cannot find module '${specifier}'`);
52
+ }
53
+ /**
54
+ * Require one module, translating its failure into a message that names the
55
+ * specifier that actually failed.
56
+ *
57
+ * The two specifiers are resolved separately and reported separately: a broken
58
+ * `react-dom/server` must never be announced as "react is not installed", since
59
+ * that sends the operator to fix a package that is already fine.
28
60
  */
29
- async function loadReactModules() {
61
+ function requireModule(require, specifier) {
30
62
  try {
31
- react = await import("react");
32
- reactDomServer = await import("react-dom/server");
33
- moduleExists = true;
34
- } catch {
35
- moduleExists = false;
63
+ const module = require(specifier);
64
+ return module.default ?? module;
65
+ } catch (error) {
66
+ if (isModuleMissing(error, specifier)) throw new Error(`${specifier} is not installed.\n\n${REACT_INSTALL_INSTRUCTIONS}`);
67
+ throw new ErrorWithCause(`Failed to load "${specifier}": ${error.message}`, { cause: error });
36
68
  }
37
69
  }
38
- loadReactModules();
70
+ /**
71
+ * Resolve the React modules synchronously, on first use.
72
+ *
73
+ * Resolution is deliberately *lazy* and *synchronous*:
74
+ *
75
+ * - Lazy, because a top-level require would drag react and react-dom into every
76
+ * `import "@warlock.js/core"`, including apps that never render a component.
77
+ * - Synchronous, because `renderReact()` is synchronous. An async import kicked
78
+ * off at module load leaves a window in which the modules are neither loaded
79
+ * nor known to be missing, and a render running inside that window has no
80
+ * correct answer to give — it used to read `createElement` off `undefined`.
81
+ *
82
+ * `createRequire` gives an ESM-safe `require`, and the outcome — modules,
83
+ * absence or load failure — is cached, so resolution runs exactly once per
84
+ * process. The failure *reason* is cached too, not just the fact of it: every
85
+ * call after a failed load has to report the same cause as the first one.
86
+ *
87
+ * @throws when react or react-dom is not installed, or cannot be loaded
88
+ */
89
+ function resolveReactModules() {
90
+ if (!reactResolved) {
91
+ reactResolved = true;
92
+ try {
93
+ const require = createRequire(import.meta.url);
94
+ react = requireModule(require, "react");
95
+ reactDomServer = requireModule(require, "react-dom/server");
96
+ } catch (error) {
97
+ react = null;
98
+ reactDomServer = null;
99
+ reactLoadError = error;
100
+ }
101
+ }
102
+ if (reactLoadError) throw reactLoadError;
103
+ if (!react || !reactDomServer) throw new Error(`react is not installed.\n\n${REACT_INSTALL_INSTRUCTIONS}`);
104
+ return {
105
+ react,
106
+ reactDomServer
107
+ };
108
+ }
39
109
  /**
40
110
  * Render a React element/component to HTML string
41
111
  *
42
112
  * **Important:** This function requires React packages to be installed.
43
113
  * Install them with: `warlock add react` or `yarn add react react-dom`
44
114
  *
115
+ * React is resolved synchronously on the first call that needs it, so this
116
+ * function stays synchronous and missing packages throw here rather than
117
+ * surfacing later as a read off an undefined module.
118
+ *
45
119
  * @example
46
120
  * ```typescript
47
121
  * const html = renderReact(<WelcomeEmail name="John" />);
48
122
  * ```
49
123
  */
50
124
  function renderReact(reactElement) {
51
- if (moduleExists === false) throw new Error(`react is not installed.\n\n${REACT_INSTALL_INSTRUCTIONS}`);
125
+ const { react, reactDomServer } = resolveReactModules();
52
126
  if (typeof reactElement === "function") reactElement = react.createElement(reactElement);
53
127
  return reactDomServer.renderToString(reactElement);
54
128
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../core/src/react/index.ts"],"sourcesContent":["import type { ComponentType, ReactElement, ReactNode } from \"react\";\n\n// ============================================================\n// Eager-loaded 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 * Module availability flag\n */\nlet moduleExists: boolean | null = null;\n\n/**\n * Cached React modules (loaded at import time)\n */\nlet react: typeof import(\"react\");\nlet reactDomServer: typeof import(\"react-dom/server\");\n\n/**\n * Eagerly load React modules at import time\n */\nasync function loadReactModules() {\n try {\n react = await import(\"react\");\n reactDomServer = await import(\"react-dom/server\");\n moduleExists = true;\n } catch {\n moduleExists = false;\n }\n}\n\n// Kick off eager loading immediately\nloadReactModules();\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 * @example\n * ```typescript\n * const html = renderReact(<WelcomeEmail name=\"John\" />);\n * ```\n */\nexport function renderReact(reactElement: ReactElement | ComponentType | ReactNode): string {\n if (moduleExists === false) {\n throw new Error(`react is not installed.\\n\\n${REACT_INSTALL_INSTRUCTIONS}`);\n }\n\n if (typeof reactElement === \"function\") {\n reactElement = react.createElement(reactElement);\n }\n\n return reactDomServer.renderToString(reactElement);\n}\n"],"mappings":";;;;AASA,MAAM,6BAA6B;;;;;;;;;;;EAWjC,KAAK;;;;AAKP,IAAI,eAA+B;;;;AAKnC,IAAI;AACJ,IAAI;;;;AAKJ,eAAe,mBAAmB;CAChC,IAAI;EACF,QAAQ,MAAM,OAAO;EACrB,iBAAiB,MAAM,OAAO;EAC9B,eAAe;CACjB,QAAQ;EACN,eAAe;CACjB;AACF;AAGA,iBAAiB;;;;;;;;;;;;AAiBjB,SAAgB,YAAY,cAAgE;CAC1F,IAAI,iBAAiB,OACnB,MAAM,IAAI,MAAM,8BAA8B,4BAA4B;CAG5E,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\")>(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\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M,cAAc,YAAY;CAGjD,OAAO,eAAe,eAAe,YAAY;AACnD"}
@@ -97,6 +97,22 @@ declare class Storage extends ScopedStorage implements StorageManagerContract {
97
97
  * @internal
98
98
  */
99
99
  protected loadDriversFromConfig(): void;
100
+ /**
101
+ * Register the built-in `local` driver, rooted at `uploadsPath()`.
102
+ *
103
+ * The storage connector starts unconditionally — unlike database, cache and
104
+ * herald, it does not early-return when `config.get("storage")` is absent —
105
+ * on the stated grounds that `init()` falls back to a built-in local driver so
106
+ * file storage works out of the box. That fallback did not exist: `init()`
107
+ * resolved the default driver *name* and then found no config registered
108
+ * under it, so **any app without `src/config/storage.ts` failed to boot**
109
+ * with `Storage driver "local" is not configured`. Only scaffolded apps, which
110
+ * always ship that file, hid it.
111
+ *
112
+ * Registered before the configured drivers so an app that defines its own
113
+ * `local` entry overrides this one rather than fighting it.
114
+ */
115
+ protected registerBuiltInLocalDriver(): void;
100
116
  /**
101
117
  * Get a scoped storage for a specific driver
102
118
  *
@@ -1 +1 @@
1
- {"version":3,"file":"storage.d.mts","names":[],"sources":["../../../../../../../core/src/storage/storage.ts"],"mappings":";;;;;;;;;;;AAgFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,OAAA,SAAgB,aAAA,YAAyB,sBAAA;EAkUjD;;;;EAAA,UA7TO,OAAA,EAAO,GAAA,SAAA,qBAAA;EA0ZL;;;;EAAA,UApZF,OAAA,EAAO,GAAA,SAAA,mBAAA;EAucd;;;;EAAA,UAjcO,iBAAA,EAAoB,iBAAA;EAsfqB;;;;EAAA,QAhf3C,WAAA;EAiiBwC;;;;;;EAgDoB;;;;;EAhkBvD,IAAA,IAAQ,OAAA;EA4nByB;;;EAxmBvC,KAAA;EA0rBK;;;;;;;;EAAA,IA1qBQ,YAAA,IAAgB,qBAAA;EA2xBsC;;;;EAAA,UA1wBhE,qBAAA;EAm0BqB;;;;;;;;;;;;;;;;;;;;;;EAryBxB,GAAA,CAAI,IAAA,EAAM,iBAA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QAAA,UAAkB,SAAA,YAAqB,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+B7D,sBAAA,CAAuB,KAAA,WAAgB,OAAA,CAAQ,wBAAA;;;;;YAwBlD,YAAA,CACR,MAAA,EAAQ,mBAAA,GACP,yBAAA,GAA4B,yBAAA,GAA4B,sBAAA;;;;;YA8DjD,mBAAA,CAAoB,MAAA,EAAQ,mBAAA,EAAqB,UAAA;;;;;YAkBjD,aAAA,CAAc,IAAA,WAAe,qBAAA;;;;;YAyCvB,oBAAA,IAAwB,OAAA,CAAQ,iBAAA;AAAA;;;;;;;;;;;;;cAwBrC,OAAA,EAAO,OAAgB"}
@@ -1,4 +1,5 @@
1
- import { storageConfig } from "./config.mjs";
1
+ import { uploadsPath } from "../utils/paths.mjs";
2
+ import { storageConfig, storageConfigurations } from "./config.mjs";
2
3
  import { StorageFile } from "./storage-file.mjs";
3
4
  import { safeFetchToBuffer } from "./utils/safe-fetch.mjs";
4
5
  import { ScopedStorage } from "./scoped-storage.mjs";
@@ -105,10 +106,32 @@ var Storage = class extends ScopedStorage {
105
106
  * @internal
106
107
  */
107
108
  loadDriversFromConfig() {
109
+ this.registerBuiltInLocalDriver();
108
110
  const drivers = storageConfig("drivers", {});
109
111
  for (const [name, config] of Object.entries(drivers)) this.configs.set(name, config);
110
112
  }
111
113
  /**
114
+ * Register the built-in `local` driver, rooted at `uploadsPath()`.
115
+ *
116
+ * The storage connector starts unconditionally — unlike database, cache and
117
+ * herald, it does not early-return when `config.get("storage")` is absent —
118
+ * on the stated grounds that `init()` falls back to a built-in local driver so
119
+ * file storage works out of the box. That fallback did not exist: `init()`
120
+ * resolved the default driver *name* and then found no config registered
121
+ * under it, so **any app without `src/config/storage.ts` failed to boot**
122
+ * with `Storage driver "local" is not configured`. Only scaffolded apps, which
123
+ * always ship that file, hid it.
124
+ *
125
+ * Registered before the configured drivers so an app that defines its own
126
+ * `local` entry overrides this one rather than fighting it.
127
+ */
128
+ registerBuiltInLocalDriver() {
129
+ this.configs.set("local", storageConfigurations.local({
130
+ root: uploadsPath(),
131
+ urlPrefix: "/uploads"
132
+ }));
133
+ }
134
+ /**
112
135
  * Get a scoped storage for a specific driver
113
136
  *
114
137
  * Returns a `ScopedStorage` instance that wraps the specified driver.