@warlock.js/core 5.1.0 → 5.2.1
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.
- package/CHANGELOG.md +152 -0
- package/esm/application/application.d.mts.map +1 -1
- package/esm/application/application.mjs.map +1 -1
- package/esm/benchmark/benchmark-snapshots.d.mts.map +1 -1
- package/esm/benchmark/benchmark.d.mts.map +1 -1
- package/esm/benchmark/channels/console.channel.mjs.map +1 -1
- package/esm/benchmark/channels/noop.channel.d.mts.map +1 -1
- package/esm/benchmark/profiler.d.mts.map +1 -1
- package/esm/benchmark/profiler.mjs.map +1 -1
- package/esm/bootstrap/setup.d.mts.map +1 -1
- package/esm/bootstrap/setup.mjs.map +1 -1
- package/esm/bootstrap.d.mts.map +1 -1
- package/esm/cache/database-cache-driver.d.mts.map +1 -1
- package/esm/cache/database-cache-driver.mjs.map +1 -1
- package/esm/cli/cli-commands.manager.mjs.map +1 -1
- package/esm/cli/cli-commands.utils.mjs +16 -10
- package/esm/cli/cli-commands.utils.mjs.map +1 -1
- package/esm/cli/commands/doctor/boot-for-diagnostics.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/connectors.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/handler-signature.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/health.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/optional-peers.check.mjs.map +1 -1
- package/esm/cli/commands/doctor/checks/routes.check.mjs.map +1 -1
- package/esm/cli/commands/generate/generate.command.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/column-dsl-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/migration.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/generators/model.generator.mjs.map +1 -1
- package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/name-parser.mjs.map +1 -1
- package/esm/cli/commands/generate/utils/prompt.mjs.map +1 -1
- package/esm/cli/commands/routes/diff-page-routes.mjs +84 -0
- package/esm/cli/commands/routes/diff-page-routes.mjs.map +1 -0
- package/esm/cli/commands/routes/format-routes-table.mjs.map +1 -1
- package/esm/cli/commands/routes/route-row.mjs.map +1 -1
- package/esm/cli/commands/routes/routes-command.action.mjs.map +1 -1
- package/esm/cli/commands/routes/routes-diff.action.mjs +84 -0
- package/esm/cli/commands/routes/routes-diff.action.mjs.map +1 -0
- package/esm/cli/commands/routes.command.mjs +15 -1
- package/esm/cli/commands/routes.command.mjs.map +1 -1
- package/esm/cli/commands/start-production.command.mjs +8 -1
- package/esm/cli/commands/start-production.command.mjs.map +1 -1
- package/esm/cli/commands/storage-put.action.mjs.map +1 -1
- package/esm/cli/commands/typings-generator.command.mjs.map +1 -1
- package/esm/cli/commands-loader.mjs.map +1 -1
- package/esm/cli/framework-cli-commands.mjs +2 -1
- package/esm/cli/framework-cli-commands.mjs.map +1 -1
- package/esm/cli/start.mjs.map +1 -1
- package/esm/cli/string-similarity.mjs.map +1 -1
- package/esm/commands/cli-command.mjs.map +1 -1
- package/esm/config/config-loader.d.mts +1 -1
- package/esm/config/config-loader.d.mts.map +1 -1
- package/esm/config/config-loader.mjs.map +1 -1
- package/esm/config/config-setter.d.mts.map +1 -1
- package/esm/config/config-special-handlers.d.mts +1 -1
- package/esm/config/config-special-handlers.mjs.map +1 -1
- package/esm/config/load-config-files.mjs.map +1 -1
- package/esm/connectors/access-connector.d.mts.map +1 -1
- package/esm/connectors/ai-connector.d.mts.map +1 -1
- package/esm/connectors/assert-no-reserved-connector-names.mjs.map +1 -1
- package/esm/connectors/assert-unique-connector-names.mjs.map +1 -1
- package/esm/connectors/base-connector.d.mts.map +1 -1
- package/esm/connectors/base-connector.mjs.map +1 -1
- package/esm/connectors/cache-connector.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.d.mts.map +1 -1
- package/esm/connectors/connectors-manager.mjs.map +1 -1
- package/esm/connectors/database-connector.d.mts.map +1 -1
- package/esm/connectors/describe-server-address.mjs +20 -3
- package/esm/connectors/describe-server-address.mjs.map +1 -1
- package/esm/connectors/herald-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.d.mts.map +1 -1
- package/esm/connectors/http-connector.mjs +5 -1
- package/esm/connectors/http-connector.mjs.map +1 -1
- package/esm/connectors/logger-connector.d.mts.map +1 -1
- package/esm/connectors/mail-connector.d.mts.map +1 -1
- package/esm/connectors/notifications-connector.d.mts.map +1 -1
- package/esm/connectors/register-configured-connectors.mjs.map +1 -1
- package/esm/connectors/socket-connector.d.mts.map +1 -1
- package/esm/connectors/socket-connector.mjs.map +1 -1
- package/esm/connectors/storage.connector.d.mts.map +1 -1
- package/esm/container/index.d.mts.map +1 -1
- package/esm/database/create-database-action.mjs.map +1 -1
- package/esm/database/drop-tables-action.mjs.map +1 -1
- package/esm/database/migrate-action.mjs.map +1 -1
- package/esm/database/models/database-log/database-log.mjs.map +1 -1
- package/esm/database/seed-command-action.mjs.map +1 -1
- package/esm/database/seeds/seed-records-table-migration.mjs +1 -1
- package/esm/database/seeds/seed-records-table-migration.mjs.map +1 -1
- package/esm/database/seeds/seeder.mjs.map +1 -1
- package/esm/database/seeds/seeders.manager.mjs.map +1 -1
- package/esm/database/seeds/seeds-table-migration.mjs +1 -1
- package/esm/database/seeds/seeds-table-migration.mjs.map +1 -1
- package/esm/database/utils.mjs.map +1 -1
- package/esm/dev-server/check-for-updates.mjs.map +1 -1
- package/esm/dev-server/dependency-graph.d.mts.map +1 -1
- package/esm/dev-server/dependency-graph.mjs.map +1 -1
- package/esm/dev-server/dev-logger.mjs.map +1 -1
- package/esm/dev-server/development-server.mjs.map +1 -1
- package/esm/dev-server/file-event-handler.mjs.map +1 -1
- package/esm/dev-server/file-manager.d.mts.map +1 -1
- package/esm/dev-server/file-manager.mjs.map +1 -1
- package/esm/dev-server/file-operations.d.mts.map +1 -1
- package/esm/dev-server/files-orchestrator.mjs.map +1 -1
- package/esm/dev-server/files-watcher.mjs.map +1 -1
- package/esm/dev-server/health-checker/checkers/eslint-health-checker.mjs.map +1 -1
- package/esm/dev-server/health-checker/checkers/typescript-health-checker.mjs.map +1 -1
- package/esm/dev-server/health-checker/file-health-result.d.mts.map +1 -1
- package/esm/dev-server/health-checker/file-health-result.mjs.map +1 -1
- package/esm/dev-server/health-checker/files-healthcare.manager.mjs.map +1 -1
- package/esm/dev-server/layer-executor.mjs +10 -3
- package/esm/dev-server/layer-executor.mjs.map +1 -1
- package/esm/dev-server/loader/hook-thread.d.mts.map +1 -1
- package/esm/dev-server/loader/own-resolver.mjs.map +1 -1
- package/esm/dev-server/loader/register-loader.mjs.map +1 -1
- package/esm/dev-server/loader/resolve-hook.mjs.map +1 -1
- package/esm/dev-server/loader/source-slug.mjs.map +1 -1
- package/esm/dev-server/loader/transpile-cache.mjs +12 -3
- package/esm/dev-server/loader/transpile-cache.mjs.map +1 -1
- package/esm/dev-server/loader/version-registry.mjs.map +1 -1
- package/esm/dev-server/manifest-manager.d.mts.map +1 -1
- package/esm/dev-server/manifest-manager.mjs.map +1 -1
- package/esm/dev-server/module-loader.mjs.map +1 -1
- package/esm/dev-server/package-json-manager.mjs.map +1 -1
- package/esm/dev-server/parse-imports.mjs.map +1 -1
- package/esm/dev-server/ready-block.mjs.map +1 -1
- package/esm/dev-server/special-files-collector.d.mts.map +1 -1
- package/esm/dev-server/special-files-collector.mjs.map +1 -1
- package/esm/dev-server/supervisor.mjs +9 -6
- package/esm/dev-server/supervisor.mjs.map +1 -1
- package/esm/dev-server/tsconfig-manager.mjs.map +1 -1
- package/esm/dev-server/type-generator.mjs.map +1 -1
- package/esm/dev-server/utils.mjs.map +1 -1
- package/esm/encryption/encrypt.mjs.map +1 -1
- package/esm/encryption/hash.mjs.map +1 -1
- package/esm/encryption/password.mjs.map +1 -1
- package/esm/generations/add-command.action.mjs +11 -4
- package/esm/generations/add-command.action.mjs.map +1 -1
- package/esm/generations/features/access.feature.mjs +2 -1
- package/esm/generations/features/access.feature.mjs.map +1 -1
- package/esm/generations/features/ai-anthropic.feature.mjs +3 -1
- package/esm/generations/features/ai-anthropic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-bedrock.feature.mjs +3 -1
- package/esm/generations/features/ai-bedrock.feature.mjs.map +1 -1
- package/esm/generations/features/ai-google.feature.mjs +3 -1
- package/esm/generations/features/ai-google.feature.mjs.map +1 -1
- package/esm/generations/features/ai-ollama.feature.mjs +3 -1
- package/esm/generations/features/ai-ollama.feature.mjs.map +1 -1
- package/esm/generations/features/ai-openai.feature.mjs +3 -1
- package/esm/generations/features/ai-openai.feature.mjs.map +1 -1
- package/esm/generations/features/ai-panoptic.feature.mjs +2 -1
- package/esm/generations/features/ai-panoptic.feature.mjs.map +1 -1
- package/esm/generations/features/ai-tools.feature.mjs +2 -1
- package/esm/generations/features/ai-tools.feature.mjs.map +1 -1
- package/esm/generations/features/ai-workspace.feature.mjs +2 -1
- package/esm/generations/features/ai-workspace.feature.mjs.map +1 -1
- package/esm/generations/features/ai.feature.mjs +2 -1
- package/esm/generations/features/ai.feature.mjs.map +1 -1
- package/esm/generations/features/herald.feature.mjs +2 -1
- package/esm/generations/features/herald.feature.mjs.map +1 -1
- package/esm/generations/features/notifications.feature.mjs +3 -2
- package/esm/generations/features/notifications.feature.mjs.map +1 -1
- package/esm/generations/features/scheduler.feature.mjs +3 -1
- package/esm/generations/features/scheduler.feature.mjs.map +1 -1
- package/esm/generations/features/shadcn.feature.mjs.map +1 -1
- package/esm/generations/features/shared/migration-timestamp.mjs.map +1 -1
- package/esm/generations/features/tailwind.feature.mjs.map +1 -1
- package/esm/generations/features/types.mjs +14 -0
- package/esm/generations/features/types.mjs.map +1 -0
- package/esm/generations/features/web.feature.mjs +10 -2
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/generations/stubs.mjs +169 -28
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/boot-port-preflight.d.mts +46 -0
- package/esm/http/boot-port-preflight.d.mts.map +1 -0
- package/esm/http/boot-port-preflight.mjs +87 -0
- package/esm/http/boot-port-preflight.mjs.map +1 -0
- package/esm/http/context/request-context.d.mts.map +1 -1
- package/esm/http/context/request-context.mjs.map +1 -1
- package/esm/http/context/request-memo.d.mts.map +1 -1
- package/esm/http/context/request-memo.mjs.map +1 -1
- package/esm/http/createHttpApplication.d.mts.map +1 -1
- package/esm/http/createHttpApplication.mjs.map +1 -1
- package/esm/http/health.d.mts.map +1 -1
- package/esm/http/index.d.mts +1 -0
- package/esm/http/index.mjs +1 -0
- package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
- package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
- package/esm/http/middleware/inject-request-context.mjs.map +1 -1
- package/esm/http/middleware/ip-filter.middleware.d.mts +1 -1
- package/esm/http/middleware/ip-filter.middleware.mjs +1 -1
- package/esm/http/middleware/ip-filter.middleware.mjs.map +1 -1
- package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/idempotency-key.mjs.map +1 -1
- package/esm/http/port-preflight.d.mts +8 -0
- package/esm/http/port-preflight.d.mts.map +1 -1
- package/esm/http/port-preflight.mjs +8 -1
- package/esm/http/port-preflight.mjs.map +1 -1
- package/esm/http/ready-report.d.mts.map +1 -1
- package/esm/http/request-controller.d.mts.map +1 -1
- package/esm/http/request.d.mts +14 -2
- package/esm/http/request.d.mts.map +1 -1
- package/esm/http/request.mjs +16 -2
- package/esm/http/request.mjs.map +1 -1
- package/esm/http/response.d.mts +3 -3
- package/esm/http/response.d.mts.map +1 -1
- package/esm/http/response.mjs.map +1 -1
- package/esm/http/server.d.mts.map +1 -1
- package/esm/http/server.mjs +26 -2
- package/esm/http/server.mjs.map +1 -1
- package/esm/http/types.d.mts +1 -3
- package/esm/http/types.d.mts.map +1 -1
- package/esm/http/uploaded-file.d.mts.map +1 -1
- package/esm/http/uploaded-file.mjs.map +1 -1
- package/esm/http/uploads-config.d.mts.map +1 -1
- package/esm/image/image.d.mts.map +1 -1
- package/esm/image/image.mjs.map +1 -1
- package/esm/index.d.mts +6 -1
- package/esm/index.mjs +6 -1
- package/esm/logger/fatal-visibility.d.mts +25 -0
- package/esm/logger/fatal-visibility.d.mts.map +1 -0
- package/esm/logger/fatal-visibility.mjs +31 -0
- package/esm/logger/fatal-visibility.mjs.map +1 -0
- package/esm/logger/index.d.mts +1 -0
- package/esm/logger/index.mjs +1 -0
- package/esm/logger/logger.mjs.map +1 -1
- package/esm/mail/config.d.mts.map +1 -1
- package/esm/mail/events.d.mts.map +1 -1
- package/esm/mail/mail.d.mts.map +1 -1
- package/esm/mail/mail.mjs.map +1 -1
- package/esm/mail/mailer-pool.d.mts.map +1 -1
- package/esm/mail/mailer-pool.mjs +2 -0
- package/esm/mail/mailer-pool.mjs.map +1 -1
- package/esm/mail/send-mail.mjs.map +1 -1
- package/esm/mail/test-mailbox.d.mts.map +1 -1
- package/esm/mail/test-mailbox.mjs.map +1 -1
- package/esm/production/assert-dist-ready-to-start.mjs +24 -0
- package/esm/production/assert-dist-ready-to-start.mjs.map +1 -0
- package/esm/production/assert-generated-imports.mjs.map +1 -1
- package/esm/production/build-app-production.mjs.map +1 -1
- package/esm/production/dist-build-manifest.mjs +47 -0
- package/esm/production/dist-build-manifest.mjs.map +1 -0
- package/esm/production/production-builder.mjs +68 -13
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs +21 -9
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/promote-dist.mjs +115 -0
- package/esm/production/promote-dist.mjs.map +1 -0
- package/esm/production/resolve-build-config.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-adapter.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-adapter.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts.map +1 -1
- package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
- package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
- package/esm/repositories/repository.manager.d.mts.map +1 -1
- package/esm/repositories/repository.manager.mjs.map +1 -1
- package/esm/resource/register-resource.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.d.mts.map +1 -1
- package/esm/resource/resource-field-builder.mjs.map +1 -1
- package/esm/resource/resource.d.mts.map +1 -1
- package/esm/resource/resource.mjs.map +1 -1
- package/esm/restful/restful.d.mts.map +1 -1
- package/esm/restful/restful.mjs.map +1 -1
- package/esm/router/index.d.mts +3 -0
- package/esm/router/index.mjs +3 -0
- package/esm/router/log-request-lifecycle.mjs.map +1 -1
- package/esm/router/normalize-request-path.d.mts +14 -0
- package/esm/router/normalize-request-path.d.mts.map +1 -0
- package/esm/router/normalize-request-path.mjs +18 -0
- package/esm/router/normalize-request-path.mjs.map +1 -0
- package/esm/router/normalize-route-path.d.mts +28 -0
- package/esm/router/normalize-route-path.d.mts.map +1 -0
- package/esm/router/normalize-route-path.mjs +33 -0
- package/esm/router/normalize-route-path.mjs.map +1 -0
- package/esm/router/positional-handler-diagnostics.d.mts.map +1 -1
- package/esm/router/positional-handler-diagnostics.mjs.map +1 -1
- package/esm/router/route-name-method-suffix.d.mts +33 -0
- package/esm/router/route-name-method-suffix.d.mts.map +1 -0
- package/esm/router/route-name-method-suffix.mjs +39 -0
- package/esm/router/route-name-method-suffix.mjs.map +1 -0
- package/esm/router/route-registry.d.mts.map +1 -1
- package/esm/router/route-registry.mjs +3 -2
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/router/router.d.mts +14 -0
- package/esm/router/router.d.mts.map +1 -1
- package/esm/router/router.mjs +50 -11
- package/esm/router/router.mjs.map +1 -1
- package/esm/socket/utils.d.mts.map +1 -1
- package/esm/storage/config.d.mts.map +1 -1
- package/esm/storage/context/storage-driver-context.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
- package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
- package/esm/storage/drivers/do-spaces-driver.d.mts.map +1 -1
- package/esm/storage/drivers/local-driver.d.mts.map +1 -1
- package/esm/storage/drivers/local-driver.mjs.map +1 -1
- package/esm/storage/drivers/r2-driver.d.mts.map +1 -1
- package/esm/storage/scoped-storage.d.mts.map +1 -1
- package/esm/storage/scoped-storage.mjs.map +1 -1
- package/esm/storage/storage-file.d.mts.map +1 -1
- package/esm/storage/storage-file.mjs.map +1 -1
- package/esm/storage/storage.d.mts.map +1 -1
- package/esm/storage/types.d.mts +14 -0
- package/esm/storage/types.d.mts.map +1 -1
- package/esm/storage/utils/safe-fetch.mjs.map +1 -1
- package/esm/tests/start-http-development-server.d.mts.map +1 -1
- package/esm/tests/start-http-development-server.mjs +2 -1
- package/esm/tests/start-http-development-server.mjs.map +1 -1
- package/esm/tests/test-connectors-selection.mjs.map +1 -1
- package/esm/tests/test-helpers.d.mts.map +1 -1
- package/esm/tests/test-setup-timeout.mjs.map +1 -1
- package/esm/tests/vitest-setup.d.mts.map +1 -1
- package/esm/tests/vitest-setup.mjs.map +1 -1
- package/esm/updater/update-warlock-packages.mjs.map +1 -1
- package/esm/use-cases/use-case-broadcast.d.mts.map +1 -1
- package/esm/use-cases/use-case-events.d.mts.map +1 -1
- package/esm/use-cases/use-case-pipeline.d.mts.map +1 -1
- package/esm/use-cases/use-case.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
- package/esm/use-cases/use-cases-registry.mjs.map +1 -1
- package/esm/utils/database-log.d.mts.map +1 -1
- package/esm/utils/database-log.mjs.map +1 -1
- package/esm/utils/environment.d.mts.map +1 -1
- package/esm/utils/framework-vesion.mjs.map +1 -1
- package/esm/utils/get-localized.mjs.map +1 -1
- package/esm/utils/load-environment.mjs.map +1 -1
- package/esm/utils/normalized-path.d.mts.map +1 -1
- package/esm/utils/paths.d.mts.map +1 -1
- package/esm/utils/promise-all-object.d.mts.map +1 -1
- package/esm/utils/promise-all-object.mjs.map +1 -1
- package/esm/utils/sluggable.mjs.map +1 -1
- package/esm/utils/version-compare.mjs.map +1 -1
- package/esm/validation/database/exists-except-current-id.mjs.map +1 -1
- package/esm/validation/database/exists-except-current-user.mjs.map +1 -1
- package/esm/validation/database/unique-except-current-id.mjs.map +1 -1
- package/esm/validation/plugins/localized-plugin.mjs.map +1 -1
- package/esm/validation/validators/file-validator.mjs.map +1 -1
- package/esm/vite/lower-stage3-decorators.d.mts.map +1 -1
- package/esm/warlock-config/default-configurations.mjs.map +1 -1
- package/esm/warlock-config/warlock-config.manager.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
- package/llms-full.txt +205 -90
- package/llms.txt +5 -5
- package/package.json +12 -12
- package/skills/add-connector/SKILL.md +35 -28
- package/skills/create-controller/SKILL.md +1 -1
- package/skills/create-module/SKILL.md +12 -12
- package/skills/hash-password/SKILL.md +4 -4
- package/skills/run-app/SKILL.md +77 -16
- package/skills/send-mail/SKILL.md +2 -2
- package/skills/use-middleware/SKILL.md +13 -4
- package/skills/use-model-transformers/SKILL.md +2 -2
- package/skills/use-repository/SKILL.md +1 -1
- package/skills/validate-input/SKILL.md +1 -1
- package/skills/warlock-conventions/SKILL.md +1 -1
- package/skills/warlock-doctor/SKILL.md +3 -3
- package/skills/warlock-routes/SKILL.md +47 -9
- package/skills/write-cli-command/SKILL.md +1 -1
- package/skills/write-seeder/SKILL.md +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"send-mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Options as NodemailerOptions } from \"nodemailer/lib/mailer\";\nimport { isDevelopmentMode, isTestMode, resolveMailConfig } from \"./config\";\nimport { MAIL_EVENTS, generateMailId, mailEvents } from \"./events\";\nimport { getMailer } from \"./mailer-pool\";\nimport { renderReactMail } from \"./react-mail\";\nimport { captureMail } from \"./test-mailbox\";\nimport {\n MailError,\n type CapturedMail,\n type MailAddress,\n type MailAttachment,\n type MailOptions,\n type MailPriority,\n type MailResult,\n type NormalizedMail,\n} from \"./types\";\n\n/**\n * Normalize email address to string\n */\nfunction addressToString(address: MailAddress): string {\n if (typeof address === \"string\") {\n return address;\n }\n\n return `\"${address.name}\" <${address.address}>`;\n}\n\n/**\n * Normalize recipients to array\n */\nfunction normalizeRecipients(recipients: string | string[] | undefined): string[] {\n if (!recipients) {\n return [];\n }\n\n return Array.isArray(recipients) ? recipients : [recipients];\n}\n\n/**\n * Map priority to nodemailer format\n */\nfunction mapPriority(priority: MailPriority): \"high\" | \"normal\" | \"low\" {\n return priority;\n}\n\n/**\n * Normalize mail options to internal format\n */\nfunction normalizeMail(options: MailOptions): NormalizedMail {\n const config = resolveMailConfig(options);\n\n return {\n to: normalizeRecipients(options.to),\n cc: normalizeRecipients(options.cc),\n bcc: normalizeRecipients(options.bcc),\n replyTo: options.replyTo,\n from: options.from || config.from || { name: \"No Reply\", address: \"noreply@localhost\" },\n subject: options.subject,\n html: options.html,\n text: options.text,\n attachments: options.attachments || [],\n priority: options.priority || \"normal\",\n headers: options.headers || {},\n tags: options.tags || [],\n correlationId: options.correlationId,\n config,\n };\n}\n\n/**\n * Resolve attachment - read file if path is provided\n */\nasync function resolveAttachment(attachment: MailAttachment): Promise<{\n filename: string;\n content: Buffer | string;\n contentType?: string;\n encoding?: string;\n cid?: string;\n}> {\n // If path is provided, read the file\n if (attachment.path) {\n try {\n const content = await readFile(attachment.path);\n return {\n filename: attachment.filename,\n content,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n } catch (error) {\n throw new MailError(\n `Failed to read attachment file \"${attachment.path}\": ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"CONFIG_ERROR\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n // Already has content\n return {\n filename: attachment.filename,\n content: attachment.content!,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n}\n\n/**\n * Build nodemailer options from normalized mail\n */\nasync function buildNodemailerOptions(normalized: NormalizedMail): Promise<NodemailerOptions> {\n const options: NodemailerOptions = {\n to: normalized.to,\n from: addressToString(normalized.from),\n subject: normalized.subject,\n priority: mapPriority(normalized.priority),\n };\n\n if (normalized.cc.length > 0) {\n options.cc = normalized.cc;\n }\n\n if (normalized.bcc.length > 0) {\n options.bcc = normalized.bcc;\n }\n\n if (normalized.replyTo) {\n options.replyTo = normalized.replyTo;\n }\n\n if (normalized.html) {\n options.html = normalized.html;\n }\n\n if (normalized.text) {\n options.text = normalized.text;\n }\n\n if (normalized.attachments.length > 0) {\n // Resolve all attachments (read files if needed)\n const resolvedAttachments = await Promise.all(\n normalized.attachments.map((att) => resolveAttachment(att as MailAttachment)),\n );\n\n options.attachments = resolvedAttachments.map((att) => ({\n filename: att.filename,\n content: att.content,\n contentType: att.contentType,\n encoding: att.encoding,\n cid: att.cid,\n }));\n }\n\n if (Object.keys(normalized.headers).length > 0) {\n options.headers = normalized.headers;\n }\n\n return options;\n}\n\n/**\n * Run per-mail event handler\n */\nasync function runMailEvent<T extends (...args: any[]) => any>(\n handler: T | undefined,\n ...args: Parameters<T>\n): Promise<ReturnType<T> | undefined> {\n if (!handler) {\n return undefined;\n }\n\n try {\n return await handler(...args);\n } catch (error) {\n log.error(\"mail\", \"event\", `Per-mail event handler error: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Trigger both global and mail-specific events\n */\nasync function triggerEvents(\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n ...args: any[]\n): Promise<any[]> {\n try {\n // Trigger global event (e.g., mail.success)\n const globalEventName =\n event === \"beforeSending\"\n ? \"BEFORE_SENDING\"\n : event === \"sent\"\n ? \"SENT\"\n : event === \"success\"\n ? \"SUCCESS\"\n : \"ERROR\";\n\n const globalResults = await mailEvents.trigger(\n globalEventName as keyof typeof MAIL_EVENTS,\n ...args,\n );\n\n // Trigger mail-specific event (e.g., mail.$id.success)\n const specificResults = await mailEvents.triggerForMail(mailId, event, ...args);\n\n return [...(globalResults || []), ...(specificResults || [])];\n } catch (error) {\n log.error(\"mail\", \"event\", `Event handler error: ${error}`);\n return [];\n }\n}\n\n/**\n * Send an email\n *\n * @param options Mail options including recipients, content, and configuration\n * @returns Result containing success status, message ID, and accepted/rejected recipients\n *\n * @example\n * ```typescript\n * // Basic usage\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n *\n * // With React component\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * component: <WelcomeEmail name=\"John\" />,\n * });\n *\n * // Track specific mail with events\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => {\n * console.log(\"This specific mail was sent!\");\n * });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\nexport async function sendMail(options: MailOptions): Promise<MailResult> {\n // Generate or use provided mail ID\n const mailId = options.id || generateMailId();\n\n // Render React component if provided\n if (options.component) {\n try {\n options.html = await renderReactMail(options.component);\n } catch (error) {\n const mailError = new MailError(\n `Failed to render React component: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"RENDER_ERROR\",\n error instanceof Error ? error : undefined,\n );\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n\n throw mailError;\n }\n }\n\n // Normalize mail\n const normalized = normalizeMail(options);\n const driver = normalized.config.driver || \"smtp\";\n\n // Run beforeSending event (per-mail, global, and mail-specific)\n const beforeResult = await runMailEvent(options.beforeSending, options);\n const globalBeforeResults = await triggerEvents(mailId, \"beforeSending\", options);\n\n // If any returns false, cancel sending\n if (beforeResult === false || globalBeforeResults.some((r) => r === false)) {\n log.info(\n `mail.${driver}`,\n \"cancelled\",\n \"Mail sending cancelled by beforeSending event\",\n );\n\n const result: MailResult = {\n success: false,\n accepted: [],\n rejected: normalized.to,\n response: \"Cancelled by beforeSending event\",\n };\n\n return result;\n }\n\n // Test mode - capture without sending\n if (isTestMode()) {\n log.info(\n `mail.${driver}`,\n \"test\",\n `[TEST MODE] Captured mail to: ${normalized.to.join(\", \")}`,\n );\n\n const result: MailResult = {\n success: true,\n messageId: `test-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Test mode - mail captured\",\n };\n\n const captured: CapturedMail = {\n options,\n normalized,\n timestamp: new Date(),\n result,\n };\n\n captureMail(captured);\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Development mode - log without sending\n if (isDevelopmentMode()) {\n log.info(\n `mail.${driver}`,\n \"dev\",\n `[DEV MODE] Would send mail to: ${normalized.to.join(\", \")}`,\n );\n log.info(`mail.${driver}`, \"dev\", `Subject: ${normalized.subject}`);\n\n if (normalized.html) {\n log.info(\n `mail.${driver}`,\n \"dev\",\n `HTML length: ${normalized.html.length} chars`,\n );\n }\n\n const result: MailResult = {\n success: true,\n messageId: `dev-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Development mode - mail logged\",\n };\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Production mode - actually send\n try {\n const config = resolveMailConfig(options);\n const mailer = await getMailer(config);\n const nodemailerOptions = await buildNodemailerOptions(normalized);\n\n log.info(\n `mail.${driver}`,\n \"send\",\n `Sending mail to: ${normalized.to.join(\", \")}`,\n );\n\n const output = await mailer.sendMail(nodemailerOptions);\n\n const accepted = output.accepted || (output.messageId ? normalized.to : []);\n const rejected = output.rejected || [];\n\n const result: MailResult = {\n success: accepted.length > 0,\n messageId: output.messageId,\n accepted: accepted as string[],\n rejected: rejected as string[],\n response: output.response,\n envelope: output.envelope,\n };\n\n if (result.success) {\n log.success(\n `mail.${driver}`,\n \"sent\",\n `Mail sent successfully (ID: ${result.messageId})`,\n );\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n } else {\n log.warn(\n `mail.${driver}`,\n \"partial\",\n `Mail partially rejected: ${rejected.join(\", \")}`,\n );\n }\n\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n let code: MailError[\"code\"] = \"UNKNOWN\";\n\n // Detect error type\n if (errorMessage.includes(\"ECONNREFUSED\") || errorMessage.includes(\"ENOTFOUND\")) {\n code = \"CONNECTION_ERROR\";\n } else if (errorMessage.includes(\"authentication\") || errorMessage.includes(\"auth\")) {\n code = \"AUTH_ERROR\";\n } else if (errorMessage.includes(\"timeout\") || errorMessage.includes(\"ETIMEDOUT\")) {\n code = \"TIMEOUT\";\n } else if (errorMessage.includes(\"rate\") || errorMessage.includes(\"limit\")) {\n code = \"RATE_LIMIT\";\n }\n\n const mailError = new MailError(\n `Failed to send mail: ${errorMessage}`,\n code,\n error instanceof Error ? error : undefined,\n );\n\n log.error(`mail.${driver}`, \"error\", mailError.message);\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n await runMailEvent(options.onSent, options, null, mailError);\n await triggerEvents(mailId, \"sent\", options, null, mailError);\n\n throw mailError;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAS,gBAAgB,SAA8B;CACrD,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,OAAO,IAAI,QAAQ,KAAK,KAAK,QAAQ,QAAQ;AAC/C;;;;AAKA,SAAS,oBAAoB,YAAqD;CAChF,IAAI,CAAC,YACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAC7D;;;;AAKA,SAAS,YAAY,UAAmD;CACtE,OAAO;AACT;;;;AAKA,SAAS,cAAc,SAAsC;CAC3D,MAAM,SAAS,kBAAkB,OAAO;CAExC,OAAO;EACL,IAAI,oBAAoB,QAAQ,E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B,KAAK,aAAa,SAAS,MAAM,GAChF,OAAO;OACF,IAAI,aAAa,SAAS,SAAS,KAAK,aAAa,SAAS,WAAW,GAC9E,OAAO;OACF,IAAI,aAAa,SAAS,MAAM,KAAK,aAAa,SAAS,OAAO,GACvE,OAAO;EAGT,MAAM,YAAY,IAAI,UACpB,wBAAwB,gBACxB,MACA,iBAAiB,QAAQ,QAAQ,MACnC;EAEA,IAAI,MAAM,QAAQ,UAAU,SAAS,UAAU,OAAO;EAEtD,MAAM,aAAa,QAAQ,SAAS,SAAS,SAAS;EACtD,MAAM,cAAc,QAAQ,SAAS,SAAS,SAAS;EACvD,MAAM,aAAa,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAC3D,MAAM,cAAc,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAE5D,MAAM;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"send-mail.mjs","names":[],"sources":["../../../../../../../core/src/mail/send-mail.ts"],"sourcesContent":["import { log } from \"@warlock.js/logger\";\nimport { readFile } from \"node:fs/promises\";\nimport type { Options as NodemailerOptions } from \"nodemailer/lib/mailer\";\nimport { isDevelopmentMode, isTestMode, resolveMailConfig } from \"./config\";\nimport { MAIL_EVENTS, generateMailId, mailEvents } from \"./events\";\nimport { getMailer } from \"./mailer-pool\";\nimport { renderReactMail } from \"./react-mail\";\nimport { captureMail } from \"./test-mailbox\";\nimport {\n MailError,\n type CapturedMail,\n type MailAddress,\n type MailAttachment,\n type MailOptions,\n type MailPriority,\n type MailResult,\n type NormalizedMail,\n} from \"./types\";\n\n/**\n * Normalize email address to string\n */\nfunction addressToString(address: MailAddress): string {\n if (typeof address === \"string\") {\n return address;\n }\n\n return `\"${address.name}\" <${address.address}>`;\n}\n\n/**\n * Normalize recipients to array\n */\nfunction normalizeRecipients(recipients: string | string[] | undefined): string[] {\n if (!recipients) {\n return [];\n }\n\n return Array.isArray(recipients) ? recipients : [recipients];\n}\n\n/**\n * Map priority to nodemailer format\n */\nfunction mapPriority(priority: MailPriority): \"high\" | \"normal\" | \"low\" {\n return priority;\n}\n\n/**\n * Normalize mail options to internal format\n */\nfunction normalizeMail(options: MailOptions): NormalizedMail {\n const config = resolveMailConfig(options);\n\n return {\n to: normalizeRecipients(options.to),\n cc: normalizeRecipients(options.cc),\n bcc: normalizeRecipients(options.bcc),\n replyTo: options.replyTo,\n from: options.from || config.from || { name: \"No Reply\", address: \"noreply@localhost\" },\n subject: options.subject,\n html: options.html,\n text: options.text,\n attachments: options.attachments || [],\n priority: options.priority || \"normal\",\n headers: options.headers || {},\n tags: options.tags || [],\n correlationId: options.correlationId,\n config,\n };\n}\n\n/**\n * Resolve attachment - read file if path is provided\n */\nasync function resolveAttachment(attachment: MailAttachment): Promise<{\n filename: string;\n content: Buffer | string;\n contentType?: string;\n encoding?: string;\n cid?: string;\n}> {\n // If path is provided, read the file\n if (attachment.path) {\n try {\n const content = await readFile(attachment.path);\n return {\n filename: attachment.filename,\n content,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n } catch (error) {\n throw new MailError(\n `Failed to read attachment file \"${attachment.path}\": ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"CONFIG_ERROR\",\n error instanceof Error ? error : undefined,\n );\n }\n }\n\n // Already has content\n return {\n filename: attachment.filename,\n content: attachment.content!,\n contentType: attachment.contentType,\n encoding: attachment.encoding,\n cid: attachment.cid,\n };\n}\n\n/**\n * Build nodemailer options from normalized mail\n */\nasync function buildNodemailerOptions(normalized: NormalizedMail): Promise<NodemailerOptions> {\n const options: NodemailerOptions = {\n to: normalized.to,\n from: addressToString(normalized.from),\n subject: normalized.subject,\n priority: mapPriority(normalized.priority),\n };\n\n if (normalized.cc.length > 0) {\n options.cc = normalized.cc;\n }\n\n if (normalized.bcc.length > 0) {\n options.bcc = normalized.bcc;\n }\n\n if (normalized.replyTo) {\n options.replyTo = normalized.replyTo;\n }\n\n if (normalized.html) {\n options.html = normalized.html;\n }\n\n if (normalized.text) {\n options.text = normalized.text;\n }\n\n if (normalized.attachments.length > 0) {\n // Resolve all attachments (read files if needed)\n const resolvedAttachments = await Promise.all(\n normalized.attachments.map((att) => resolveAttachment(att as MailAttachment)),\n );\n\n options.attachments = resolvedAttachments.map((att) => ({\n filename: att.filename,\n content: att.content,\n contentType: att.contentType,\n encoding: att.encoding,\n cid: att.cid,\n }));\n }\n\n if (Object.keys(normalized.headers).length > 0) {\n options.headers = normalized.headers;\n }\n\n return options;\n}\n\n/**\n * Run per-mail event handler\n */\nasync function runMailEvent<T extends (...args: any[]) => any>(\n handler: T | undefined,\n ...args: Parameters<T>\n): Promise<ReturnType<T> | undefined> {\n if (!handler) {\n return undefined;\n }\n\n try {\n return await handler(...args);\n } catch (error) {\n log.error(\"mail\", \"event\", `Per-mail event handler error: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Trigger both global and mail-specific events\n */\nasync function triggerEvents(\n mailId: string,\n event: \"beforeSending\" | \"sent\" | \"success\" | \"error\",\n ...args: any[]\n): Promise<any[]> {\n try {\n // Trigger global event (e.g., mail.success)\n const globalEventName =\n event === \"beforeSending\"\n ? \"BEFORE_SENDING\"\n : event === \"sent\"\n ? \"SENT\"\n : event === \"success\"\n ? \"SUCCESS\"\n : \"ERROR\";\n\n const globalResults = await mailEvents.trigger(\n globalEventName as keyof typeof MAIL_EVENTS,\n ...args,\n );\n\n // Trigger mail-specific event (e.g., mail.$id.success)\n const specificResults = await mailEvents.triggerForMail(mailId, event, ...args);\n\n return [...(globalResults || []), ...(specificResults || [])];\n } catch (error) {\n log.error(\"mail\", \"event\", `Event handler error: ${error}`);\n return [];\n }\n}\n\n/**\n * Send an email\n *\n * @param options Mail options including recipients, content, and configuration\n * @returns Result containing success status, message ID, and accepted/rejected recipients\n *\n * @example\n * ```typescript\n * // Basic usage\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Hello\",\n * html: \"<p>World</p>\",\n * });\n *\n * // With React component\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * component: <WelcomeEmail name=\"John\" />,\n * });\n *\n * // Track specific mail with events\n * const mailId = generateMailId();\n * mailEvents.onMailSuccess(mailId, (mail, result) => {\n * console.log(\"This specific mail was sent!\");\n * });\n * await sendMail({ id: mailId, to: \"...\", subject: \"...\", html: \"...\" });\n * ```\n */\nexport async function sendMail(options: MailOptions): Promise<MailResult> {\n // Generate or use provided mail ID\n const mailId = options.id || generateMailId();\n\n // Render React component if provided\n if (options.component) {\n try {\n options.html = await renderReactMail(options.component);\n } catch (error) {\n const mailError = new MailError(\n `Failed to render React component: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n \"RENDER_ERROR\",\n error instanceof Error ? error : undefined,\n );\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n\n throw mailError;\n }\n }\n\n // Normalize mail\n const normalized = normalizeMail(options);\n const driver = normalized.config.driver || \"smtp\";\n\n // Run beforeSending event (per-mail, global, and mail-specific)\n const beforeResult = await runMailEvent(options.beforeSending, options);\n const globalBeforeResults = await triggerEvents(mailId, \"beforeSending\", options);\n\n // If any returns false, cancel sending\n if (beforeResult === false || globalBeforeResults.some((r) => r === false)) {\n log.info(\n `mail.${driver}`,\n \"cancelled\",\n \"Mail sending cancelled by beforeSending event\",\n );\n\n const result: MailResult = {\n success: false,\n accepted: [],\n rejected: normalized.to,\n response: \"Cancelled by beforeSending event\",\n };\n\n return result;\n }\n\n // Test mode - capture without sending\n if (isTestMode()) {\n log.info(\n `mail.${driver}`,\n \"test\",\n `[TEST MODE] Captured mail to: ${normalized.to.join(\", \")}`,\n );\n\n const result: MailResult = {\n success: true,\n messageId: `test-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Test mode - mail captured\",\n };\n\n const captured: CapturedMail = {\n options,\n normalized,\n timestamp: new Date(),\n result,\n };\n\n captureMail(captured);\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Development mode - log without sending\n if (isDevelopmentMode()) {\n log.info(\n `mail.${driver}`,\n \"dev\",\n `[DEV MODE] Would send mail to: ${normalized.to.join(\", \")}`,\n );\n log.info(`mail.${driver}`, \"dev\", `Subject: ${normalized.subject}`);\n\n if (normalized.html) {\n log.info(\n `mail.${driver}`,\n \"dev\",\n `HTML length: ${normalized.html.length} chars`,\n );\n }\n\n const result: MailResult = {\n success: true,\n messageId: `dev-${mailId}@localhost`,\n accepted: normalized.to,\n rejected: [],\n response: \"Development mode - mail logged\",\n };\n\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n }\n\n // Production mode - actually send\n try {\n const config = resolveMailConfig(options);\n const mailer = await getMailer(config);\n const nodemailerOptions = await buildNodemailerOptions(normalized);\n\n log.info(\n `mail.${driver}`,\n \"send\",\n `Sending mail to: ${normalized.to.join(\", \")}`,\n );\n\n const output = await mailer.sendMail(nodemailerOptions);\n\n const accepted = output.accepted || (output.messageId ? normalized.to : []);\n const rejected = output.rejected || [];\n\n const result: MailResult = {\n success: accepted.length > 0,\n messageId: output.messageId,\n accepted: accepted as string[],\n rejected: rejected as string[],\n response: output.response,\n envelope: output.envelope,\n };\n\n if (result.success) {\n log.success(\n `mail.${driver}`,\n \"sent\",\n `Mail sent successfully (ID: ${result.messageId})`,\n );\n await runMailEvent(options.onSuccess, options, result);\n await triggerEvents(mailId, \"success\", options, result);\n } else {\n log.warn(\n `mail.${driver}`,\n \"partial\",\n `Mail partially rejected: ${rejected.join(\", \")}`,\n );\n }\n\n await runMailEvent(options.onSent, options, result, null);\n await triggerEvents(mailId, \"sent\", options, result, null);\n\n return result;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n let code: MailError[\"code\"] = \"UNKNOWN\";\n\n // Detect error type\n if (errorMessage.includes(\"ECONNREFUSED\") || errorMessage.includes(\"ENOTFOUND\")) {\n code = \"CONNECTION_ERROR\";\n } else if (errorMessage.includes(\"authentication\") || errorMessage.includes(\"auth\")) {\n code = \"AUTH_ERROR\";\n } else if (errorMessage.includes(\"timeout\") || errorMessage.includes(\"ETIMEDOUT\")) {\n code = \"TIMEOUT\";\n } else if (errorMessage.includes(\"rate\") || errorMessage.includes(\"limit\")) {\n code = \"RATE_LIMIT\";\n }\n\n const mailError = new MailError(\n `Failed to send mail: ${errorMessage}`,\n code,\n error instanceof Error ? error : undefined,\n );\n\n log.error(`mail.${driver}`, \"error\", mailError.message);\n\n await runMailEvent(options.onError, options, mailError);\n await triggerEvents(mailId, \"error\", options, mailError);\n await runMailEvent(options.onSent, options, null, mailError);\n await triggerEvents(mailId, \"sent\", options, null, mailError);\n\n throw mailError;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAS,gBAAgB,SAA8B;CACrD,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,OAAO,IAAI,QAAQ,KAAK,KAAK,QAAQ,QAAQ;AAC/C;;;;AAKA,SAAS,oBAAoB,YAAqD;CAChF,IAAI,CAAC,YACH,OAAO,CAAC;CAGV,OAAO,MAAM,QAAQ,UAAU,IAAI,aAAa,CAAC,UAAU;AAC7D;;;;AAKA,SAAS,YAAY,UAAmD;CACtE,OAAO;AACT;;;;AAKA,SAAS,cAAc,SAAsC;CAC3D,MAAM,SAAS,kBAAkB,OAAO;CAExC,OAAO;EACL,IAAI,oBAAoB,QAAQ,EAAE;EAClC,IAAI,oBAAoB,QAAQ,EAAE;EAClC,KAAK,oBAAoB,QAAQ,GAAG;EACpC,SAAS,QAAQ;EACjB,MAAM,QAAQ,QAAQ,OAAO,QAAQ;GAAE,MAAM;GAAY,SAAS;EAAoB;EACtF,SAAS,QAAQ;EACjB,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,aAAa,QAAQ,eAAe,CAAC;EACrC,UAAU,QAAQ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U,SAAS,UAAU,OAAO;EAEtD,MAAM,aAAa,QAAQ,SAAS,SAAS,SAAS;EACtD,MAAM,cAAc,QAAQ,SAAS,SAAS,SAAS;EACvD,MAAM,aAAa,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAC3D,MAAM,cAAc,QAAQ,QAAQ,SAAS,MAAM,SAAS;EAE5D,MAAM;CACR;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-mailbox.d.mts","names":[],"sources":["../../../../../../../core/src/mail/test-mailbox.ts"],"mappings":";;;;;;iBA2EgB,WAAA,CAAY,IAAkB,EAAZ,YAAY;;;;iBAO9B,cAAA,
|
|
1
|
+
{"version":3,"file":"test-mailbox.d.mts","names":[],"sources":["../../../../../../../core/src/mail/test-mailbox.ts"],"mappings":";;;;;;iBA2EgB,WAAA,CAAY,IAAkB,EAAZ,YAAY;;;;iBAO9B,cAAA,CAAA,GAAkB,YAAY;;;;iBAO9B,WAAA,CAAA,GAAe,YAAY;;;;iBAO3B,WAAA,CAAY,KAAA,WAAgB,YAAY;;;;iBAUxC,kBAAA,CAAmB,OAAA,WAAkB,YAAY;;;;iBAOjD,aAAA,CAAc,KAAa;;;;iBAO3B,sBAAA,CAAuB,OAAe;;;;iBAOtC,cAAA,CAAA;;;;iBAOA,gBAAA,CAAA;;;;iBAOA,cAAA,CAAe,SAAA,GAAY,IAAA,EAAM,YAAA,eAA2B,YAAY;;;;iBAaxE,eAAA,CAAgB,KAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-mailbox.mjs","names":[],"sources":["../../../../../../../core/src/mail/test-mailbox.ts"],"sourcesContent":["/**\n * Test Mailbox for Mail v2\n *\n * Provides utilities for capturing and asserting sent emails in test mode.\n *\n * ## Setup\n *\n * ```typescript\n * import { setMailMode, clearTestMailbox } from \"@warlock.js/core/mail/v2\";\n *\n * beforeEach(() => {\n * setMailMode(\"test\");\n * clearTestMailbox();\n * });\n * ```\n *\n * ## Usage\n *\n * ```typescript\n * import { sendMail, getTestMailbox, findMailsTo } from \"@warlock.js/core/mail/v2\";\n *\n * // Send email in test mode\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * html: \"<p>Hello</p>\",\n * });\n *\n * // Get all captured mails\n * const mails = getTestMailbox();\n * expect(mails).toHaveLength(1);\n * expect(mails[0].options.subject).toBe(\"Welcome!\");\n *\n * // Find specific mails\n * const userMails = findMailsTo(\"user@example.com\");\n * expect(userMails).toHaveLength(1);\n *\n * // Check if mail was sent\n * expect(wasMailSentTo(\"user@example.com\")).toBe(true);\n * expect(wasMailSentWithSubject(\"Welcome!\")).toBe(true);\n * ```\n *\n * ## Assertion Helpers\n *\n * ```typescript\n * // Assert a mail matching a predicate was sent\n * const mail = assertMailSent(m => m.options.to === \"user@example.com\");\n * expect(mail.options.subject).toBe(\"Welcome!\");\n *\n * // Assert exact count\n * assertMailCount(2); // throws if count doesn't match\n * ```\n *\n * ## Captured Mail Structure\n *\n * Each captured mail contains:\n * - `options` - Original MailOptions passed to sendMail\n * - `normalized` - Normalized mail data (arrays, addresses resolved)\n * - `timestamp` - When the mail was captured\n * - `result` - MailResult (in test mode, always success)\n * - `error` - MailError if sending failed (null in test mode)\n *\n * @module test-mailbox\n */\n\nimport type { CapturedMail } from \"./types\";\n\n/**\n * Test mailbox for capturing sent emails in test mode\n */\nlet testMailbox: CapturedMail[] = [];\n\n/**\n * Add a mail to the test mailbox\n */\nexport function captureMail(mail: CapturedMail): void {\n testMailbox.push(mail);\n}\n\n/**\n * Get all captured mails\n */\nexport function getTestMailbox(): CapturedMail[] {\n return [...testMailbox];\n}\n\n/**\n * Get the last captured mail\n */\nexport function getLastMail(): CapturedMail | undefined {\n return testMailbox[testMailbox.length - 1];\n}\n\n/**\n * Find mails by recipient\n */\nexport function findMailsTo(email: string): CapturedMail[] {\n return testMailbox.filter((mail) => {\n const to = Array.isArray(mail.options.to) ? mail.options.to : [mail.options.to];\n return to.includes(email);\n });\n}\n\n/**\n * Find mails by subject (partial match)\n */\nexport function findMailsBySubject(subject: string): CapturedMail[] {\n return testMailbox.filter((mail) => mail.options.subject.includes(subject));\n}\n\n/**\n * Check if a mail was sent to a specific recipient\n */\nexport function wasMailSentTo(email: string): boolean {\n return findMailsTo(email).length > 0;\n}\n\n/**\n * Check if a mail with specific subject was sent\n */\nexport function wasMailSentWithSubject(subject: string): boolean {\n return testMailbox.some((mail) => mail.options.subject === subject);\n}\n\n/**\n * Get mailbox size\n */\nexport function getMailboxSize(): number {\n return testMailbox.length;\n}\n\n/**\n * Clear the test mailbox\n */\nexport function clearTestMailbox(): void {\n testMailbox = [];\n}\n\n/**\n * Assert helper for testing\n */\nexport function assertMailSent(predicate: (mail: CapturedMail) => boolean): CapturedMail {\n const mail = testMailbox.find(predicate);\n\n if (!mail) {\n throw new Error(\"No mail matching the predicate was found in the test mailbox\");\n }\n\n return mail;\n}\n\n/**\n * Assert that a specific number of mails were sent\n */\nexport function assertMailCount(count: number): void {\n if (testMailbox.length !== count) {\n throw new Error(`Expected ${count} mails to be sent, but found ${testMailbox.length}`);\n }\n}\n"],"mappings":";;;;AAsEA,IAAI,cAA8B,CAAC;;;;AAKnC,SAAgB,YAAY,MAA0B;CACpD,YAAY,KAAK,IAAI;AACvB;;;;AAKA,SAAgB,iBAAiC;CAC/C,OAAO,CAAC,GAAG,WAAW;AACxB;;;;AAKA,SAAgB,cAAwC;CACtD,OAAO,YAAY,YAAY,SAAS;AAC1C;;;;AAKA,SAAgB,YAAY,OAA+B;CACzD,OAAO,YAAY,QAAQ,SAAS;EAElC,QADW,MAAM,QAAQ,KAAK,QAAQ,EAAE,IAAI,KAAK,QAAQ,KAAK,CAAC,KAAK,QAAQ,EAAE,
|
|
1
|
+
{"version":3,"file":"test-mailbox.mjs","names":[],"sources":["../../../../../../../core/src/mail/test-mailbox.ts"],"sourcesContent":["/**\n * Test Mailbox for Mail v2\n *\n * Provides utilities for capturing and asserting sent emails in test mode.\n *\n * ## Setup\n *\n * ```typescript\n * import { setMailMode, clearTestMailbox } from \"@warlock.js/core/mail/v2\";\n *\n * beforeEach(() => {\n * setMailMode(\"test\");\n * clearTestMailbox();\n * });\n * ```\n *\n * ## Usage\n *\n * ```typescript\n * import { sendMail, getTestMailbox, findMailsTo } from \"@warlock.js/core/mail/v2\";\n *\n * // Send email in test mode\n * await sendMail({\n * to: \"user@example.com\",\n * subject: \"Welcome!\",\n * html: \"<p>Hello</p>\",\n * });\n *\n * // Get all captured mails\n * const mails = getTestMailbox();\n * expect(mails).toHaveLength(1);\n * expect(mails[0].options.subject).toBe(\"Welcome!\");\n *\n * // Find specific mails\n * const userMails = findMailsTo(\"user@example.com\");\n * expect(userMails).toHaveLength(1);\n *\n * // Check if mail was sent\n * expect(wasMailSentTo(\"user@example.com\")).toBe(true);\n * expect(wasMailSentWithSubject(\"Welcome!\")).toBe(true);\n * ```\n *\n * ## Assertion Helpers\n *\n * ```typescript\n * // Assert a mail matching a predicate was sent\n * const mail = assertMailSent(m => m.options.to === \"user@example.com\");\n * expect(mail.options.subject).toBe(\"Welcome!\");\n *\n * // Assert exact count\n * assertMailCount(2); // throws if count doesn't match\n * ```\n *\n * ## Captured Mail Structure\n *\n * Each captured mail contains:\n * - `options` - Original MailOptions passed to sendMail\n * - `normalized` - Normalized mail data (arrays, addresses resolved)\n * - `timestamp` - When the mail was captured\n * - `result` - MailResult (in test mode, always success)\n * - `error` - MailError if sending failed (null in test mode)\n *\n * @module test-mailbox\n */\n\nimport type { CapturedMail } from \"./types\";\n\n/**\n * Test mailbox for capturing sent emails in test mode\n */\nlet testMailbox: CapturedMail[] = [];\n\n/**\n * Add a mail to the test mailbox\n */\nexport function captureMail(mail: CapturedMail): void {\n testMailbox.push(mail);\n}\n\n/**\n * Get all captured mails\n */\nexport function getTestMailbox(): CapturedMail[] {\n return [...testMailbox];\n}\n\n/**\n * Get the last captured mail\n */\nexport function getLastMail(): CapturedMail | undefined {\n return testMailbox[testMailbox.length - 1];\n}\n\n/**\n * Find mails by recipient\n */\nexport function findMailsTo(email: string): CapturedMail[] {\n return testMailbox.filter((mail) => {\n const to = Array.isArray(mail.options.to) ? mail.options.to : [mail.options.to];\n return to.includes(email);\n });\n}\n\n/**\n * Find mails by subject (partial match)\n */\nexport function findMailsBySubject(subject: string): CapturedMail[] {\n return testMailbox.filter((mail) => mail.options.subject.includes(subject));\n}\n\n/**\n * Check if a mail was sent to a specific recipient\n */\nexport function wasMailSentTo(email: string): boolean {\n return findMailsTo(email).length > 0;\n}\n\n/**\n * Check if a mail with specific subject was sent\n */\nexport function wasMailSentWithSubject(subject: string): boolean {\n return testMailbox.some((mail) => mail.options.subject === subject);\n}\n\n/**\n * Get mailbox size\n */\nexport function getMailboxSize(): number {\n return testMailbox.length;\n}\n\n/**\n * Clear the test mailbox\n */\nexport function clearTestMailbox(): void {\n testMailbox = [];\n}\n\n/**\n * Assert helper for testing\n */\nexport function assertMailSent(predicate: (mail: CapturedMail) => boolean): CapturedMail {\n const mail = testMailbox.find(predicate);\n\n if (!mail) {\n throw new Error(\"No mail matching the predicate was found in the test mailbox\");\n }\n\n return mail;\n}\n\n/**\n * Assert that a specific number of mails were sent\n */\nexport function assertMailCount(count: number): void {\n if (testMailbox.length !== count) {\n throw new Error(`Expected ${count} mails to be sent, but found ${testMailbox.length}`);\n }\n}\n"],"mappings":";;;;AAsEA,IAAI,cAA8B,CAAC;;;;AAKnC,SAAgB,YAAY,MAA0B;CACpD,YAAY,KAAK,IAAI;AACvB;;;;AAKA,SAAgB,iBAAiC;CAC/C,OAAO,CAAC,GAAG,WAAW;AACxB;;;;AAKA,SAAgB,cAAwC;CACtD,OAAO,YAAY,YAAY,SAAS;AAC1C;;;;AAKA,SAAgB,YAAY,OAA+B;CACzD,OAAO,YAAY,QAAQ,SAAS;EAElC,QADW,MAAM,QAAQ,KAAK,QAAQ,EAAE,IAAI,KAAK,QAAQ,KAAK,CAAC,KAAK,QAAQ,EAAE,GACpE,SAAS,KAAK;CAC1B,CAAC;AACH;;;;AAKA,SAAgB,mBAAmB,SAAiC;CAClE,OAAO,YAAY,QAAQ,SAAS,KAAK,QAAQ,QAAQ,SAAS,OAAO,CAAC;AAC5E;;;;AAKA,SAAgB,cAAc,OAAwB;CACpD,OAAO,YAAY,KAAK,EAAE,SAAS;AACrC;;;;AAKA,SAAgB,uBAAuB,SAA0B;CAC/D,OAAO,YAAY,MAAM,SAAS,KAAK,QAAQ,YAAY,OAAO;AACpE;;;;AAKA,SAAgB,iBAAyB;CACvC,OAAO,YAAY;AACrB;;;;AAKA,SAAgB,mBAAyB;CACvC,cAAc,CAAC;AACjB;;;;AAKA,SAAgB,eAAe,WAA0D;CACvF,MAAM,OAAO,YAAY,KAAK,SAAS;CAEvC,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,8DAA8D;CAGhF,OAAO;AACT;;;;AAKA,SAAgB,gBAAgB,OAAqB;CACnD,IAAI,YAAY,WAAW,OACzB,MAAM,IAAI,MAAM,YAAY,MAAM,+BAA+B,YAAY,QAAQ;AAEzF"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readDistBuildManifestAsync } from "./dist-build-manifest.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../core/src/production/assert-dist-ready-to-start.ts
|
|
4
|
+
/**
|
|
5
|
+
* Decide whether `outDir` is fit for `warlock start` to boot.
|
|
6
|
+
*
|
|
7
|
+
* Checks the build-success marker a promoted build writes — not any
|
|
8
|
+
* particular output file. Before this existed, `start` only failed on a
|
|
9
|
+
* broken `dist` by accident, because it happened to need a file (the client
|
|
10
|
+
* manifest) that an incomplete build never wrote. That guard said nothing
|
|
11
|
+
* when the missing piece was anything else, and named no reason. This
|
|
12
|
+
* refuses explicitly and says why.
|
|
13
|
+
*/
|
|
14
|
+
async function checkDistReadyToStartAsync(outDir) {
|
|
15
|
+
if (await readDistBuildManifestAsync(outDir)) return { ready: true };
|
|
16
|
+
return {
|
|
17
|
+
ready: false,
|
|
18
|
+
reason: `"${outDir}" was not produced by a successful \`warlock build\` run (no build-success marker found). Run \`warlock build\` before \`warlock start\`.`
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
23
|
+
export { checkDistReadyToStartAsync };
|
|
24
|
+
//# sourceMappingURL=assert-dist-ready-to-start.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"assert-dist-ready-to-start.mjs","names":[],"sources":["../../../../../../../core/src/production/assert-dist-ready-to-start.ts"],"sourcesContent":["import { readDistBuildManifestAsync } from \"./dist-build-manifest\";\n\n/**\n * Whether `dist` is safe for `warlock start` to boot, and — when it is\n * not — the reason to show the developer.\n */\nexport type DistReadiness =\n | { ready: true }\n | {\n ready: false;\n reason: string;\n };\n\n/**\n * Decide whether `outDir` is fit for `warlock start` to boot.\n *\n * Checks the build-success marker a promoted build writes — not any\n * particular output file. Before this existed, `start` only failed on a\n * broken `dist` by accident, because it happened to need a file (the client\n * manifest) that an incomplete build never wrote. That guard said nothing\n * when the missing piece was anything else, and named no reason. This\n * refuses explicitly and says why.\n */\nexport async function checkDistReadyToStartAsync(outDir: string): Promise<DistReadiness> {\n const manifest = await readDistBuildManifestAsync(outDir);\n\n if (manifest) {\n return { ready: true };\n }\n\n return {\n ready: false,\n reason:\n `\"${outDir}\" was not produced by a successful \\`warlock build\\` run ` +\n \"(no build-success marker found). Run `warlock build` before `warlock start`.\",\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,eAAsB,2BAA2B,QAAwC;CAGvF,IAAI,MAFmB,2BAA2B,MAAM,GAGtD,OAAO,EAAE,OAAO,KAAK;CAGvB,OAAO;EACL,OAAO;EACP,QACE,IAAI,OAAO;CAEf;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assert-generated-imports.mjs","names":[],"sources":["../../../../../../../core/src/production/assert-generated-imports.ts"],"sourcesContent":["import { builtinModules } from \"node:module\";\n\n/**\n * A specifier the builder wrote into generated code that the consuming app does\n * not declare.\n */\nexport type UndeclaredImport = {\n /** File the import was written into, relative to the generation directory. */\n file: string;\n /** The specifier exactly as emitted. */\n specifier: string;\n /** The package the specifier resolves to — `@scope/name` for a deep import. */\n packageName: string;\n};\n\nexport type GeneratedFile = {\n file: string;\n content: string;\n};\n\n/**\n * Raised when generated code would ship an import the app cannot resolve.\n *\n * Carries every violation rather than the first, so a build reports the whole\n * problem in one pass instead of one specifier per re-run.\n */\nexport class UndeclaredGeneratedImportError extends Error {\n public constructor(public readonly violations: UndeclaredImport[]) {\n super(\n [\n `Generated code imports ${violations.length} package(s) the application does not declare:`,\n \"\",\n ...violations.map(\n ({ file, specifier, packageName }) =>\n ` ${file} → \"${specifier}\" (requires \"${packageName}\" in the app's dependencies)`,\n ),\n \"\",\n \"Generated code may only import packages the app itself declares. A framework-internal\",\n \"dependency must be reached through a re-export from @warlock.js/core — a bare specifier\",\n \"resolves by accident under npm/yarn hoisting and fails under pnpm's strict layout.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"UndeclaredGeneratedImportError\";\n }\n}\n\n// The clause between `import` and `from` excludes `;` and both quote\n// characters so the lazy match cannot run past the end of its own statement.\n// Allowing it to would let a side-effect import (`import \"./bootstrap\";`) bind\n// to the `from` of the NEXT statement and disappear from the results.\nconst IMPORT_PATTERN =\n /(?:import|export)\\s+(?:[^\"';]*?\\sfrom\\s*)?[\"']([^\"']+)[\"']|import\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g;\n\n/**\n * Every module specifier a source file references — static, side-effect,\n * re-export and dynamic `import()` forms alike.\n *\n * Regex is sufficient and deliberate here: the input is code this builder wrote\n * itself, so it has no comments, no strings that look like imports, and no\n * syntax the pattern could misread. Parsing it with a full AST would buy\n * nothing and cost a dependency in the build path.\n */\nexport function extractSpecifiers(content: string): string[] {\n const specifiers: string[] = [];\n\n for (const match of content.matchAll(IMPORT_PATTERN)) {\n const specifier = match[1] ?? match[2];\n\n if (specifier) {\n specifiers.push(specifier);\n }\n }\n\n return specifiers;\n}\n\n/**\n * The package a specifier resolves to — `@scope/name` or `name`, ignoring any\n * deep path after it. Returns undefined for anything that is not a package:\n * relative paths, absolute paths, URLs, and Node builtins.\n */\nexport function resolvePackageName(specifier: string): string | undefined {\n if (\n specifier.startsWith(\".\") ||\n specifier.startsWith(\"/\") ||\n specifier.startsWith(\"node:\") ||\n specifier.includes(\"://\")\n ) {\n return undefined;\n }\n\n const segments = specifier.split(\"/\");\n const packageName = specifier.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : segments[0];\n\n if (builtinModules.includes(packageName)) {\n return undefined;\n }\n\n return packageName;\n}\n\n/**\n * Find every import in generated code that the app does not declare.\n *\n * `dependencies` only, deliberately: the artifact this checks is a production\n * bundle, so a package the app lists as a dev dependency is not guaranteed to\n * be installed where it runs.\n */\nexport function findUndeclaredImports(\n files: GeneratedFile[],\n declaredDependencies: string[],\n): UndeclaredImport[] {\n const declared = new Set(declaredDependencies);\n const violations: UndeclaredImport[] = [];\n\n for (const { file, content } of files) {\n for (const specifier of extractSpecifiers(content)) {\n const packageName = resolvePackageName(specifier);\n\n if (!packageName || declared.has(packageName)) {\n continue;\n }\n\n violations.push({ file, specifier, packageName });\n }\n }\n\n return violations;\n}\n\n/**\n * Fail the build when generated code would import something the app cannot\n * resolve.\n *\n * This is the part that stops the defect class from returning. Rewriting the\n * one bad specifier fixes today's bundle; only the assertion stops the next\n * change to the generator from reintroducing it — under npm or yarn the mistake\n * is invisible, because hoisting resolves it by accident.\n *\n * @throws {UndeclaredGeneratedImportError} listing every violation found.\n */\nexport function assertGeneratedImportsAreDeclared(\n files: GeneratedFile[],\n declaredDependencies: string[],\n): void {\n const violations = findUndeclaredImports(files, declaredDependencies);\n\n if (violations.length > 0) {\n throw new UndeclaredGeneratedImportError(violations);\n }\n}\n"],"mappings":";;;;;;;;;AA0BA,IAAa,iCAAb,cAAoD,MAAM;CACxD,AAAO,YAAY,AAAgB,YAAgC;EACjE,MACE;GACE,0BAA0B,WAAW,OAAO;GAC5C;GACA,GAAG,WAAW,KACX,EAAE,MAAM,WAAW,kBAClB,KAAK,KAAK,MAAM,UAAU,eAAe,YAAY,6BACzD;GACA;GACA;GACA;GACA;EACF,
|
|
1
|
+
{"version":3,"file":"assert-generated-imports.mjs","names":[],"sources":["../../../../../../../core/src/production/assert-generated-imports.ts"],"sourcesContent":["import { builtinModules } from \"node:module\";\n\n/**\n * A specifier the builder wrote into generated code that the consuming app does\n * not declare.\n */\nexport type UndeclaredImport = {\n /** File the import was written into, relative to the generation directory. */\n file: string;\n /** The specifier exactly as emitted. */\n specifier: string;\n /** The package the specifier resolves to — `@scope/name` for a deep import. */\n packageName: string;\n};\n\nexport type GeneratedFile = {\n file: string;\n content: string;\n};\n\n/**\n * Raised when generated code would ship an import the app cannot resolve.\n *\n * Carries every violation rather than the first, so a build reports the whole\n * problem in one pass instead of one specifier per re-run.\n */\nexport class UndeclaredGeneratedImportError extends Error {\n public constructor(public readonly violations: UndeclaredImport[]) {\n super(\n [\n `Generated code imports ${violations.length} package(s) the application does not declare:`,\n \"\",\n ...violations.map(\n ({ file, specifier, packageName }) =>\n ` ${file} → \"${specifier}\" (requires \"${packageName}\" in the app's dependencies)`,\n ),\n \"\",\n \"Generated code may only import packages the app itself declares. A framework-internal\",\n \"dependency must be reached through a re-export from @warlock.js/core — a bare specifier\",\n \"resolves by accident under npm/yarn hoisting and fails under pnpm's strict layout.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"UndeclaredGeneratedImportError\";\n }\n}\n\n// The clause between `import` and `from` excludes `;` and both quote\n// characters so the lazy match cannot run past the end of its own statement.\n// Allowing it to would let a side-effect import (`import \"./bootstrap\";`) bind\n// to the `from` of the NEXT statement and disappear from the results.\nconst IMPORT_PATTERN =\n /(?:import|export)\\s+(?:[^\"';]*?\\sfrom\\s*)?[\"']([^\"']+)[\"']|import\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g;\n\n/**\n * Every module specifier a source file references — static, side-effect,\n * re-export and dynamic `import()` forms alike.\n *\n * Regex is sufficient and deliberate here: the input is code this builder wrote\n * itself, so it has no comments, no strings that look like imports, and no\n * syntax the pattern could misread. Parsing it with a full AST would buy\n * nothing and cost a dependency in the build path.\n */\nexport function extractSpecifiers(content: string): string[] {\n const specifiers: string[] = [];\n\n for (const match of content.matchAll(IMPORT_PATTERN)) {\n const specifier = match[1] ?? match[2];\n\n if (specifier) {\n specifiers.push(specifier);\n }\n }\n\n return specifiers;\n}\n\n/**\n * The package a specifier resolves to — `@scope/name` or `name`, ignoring any\n * deep path after it. Returns undefined for anything that is not a package:\n * relative paths, absolute paths, URLs, and Node builtins.\n */\nexport function resolvePackageName(specifier: string): string | undefined {\n if (\n specifier.startsWith(\".\") ||\n specifier.startsWith(\"/\") ||\n specifier.startsWith(\"node:\") ||\n specifier.includes(\"://\")\n ) {\n return undefined;\n }\n\n const segments = specifier.split(\"/\");\n const packageName = specifier.startsWith(\"@\") ? segments.slice(0, 2).join(\"/\") : segments[0];\n\n if (builtinModules.includes(packageName)) {\n return undefined;\n }\n\n return packageName;\n}\n\n/**\n * Find every import in generated code that the app does not declare.\n *\n * `dependencies` only, deliberately: the artifact this checks is a production\n * bundle, so a package the app lists as a dev dependency is not guaranteed to\n * be installed where it runs.\n */\nexport function findUndeclaredImports(\n files: GeneratedFile[],\n declaredDependencies: string[],\n): UndeclaredImport[] {\n const declared = new Set(declaredDependencies);\n const violations: UndeclaredImport[] = [];\n\n for (const { file, content } of files) {\n for (const specifier of extractSpecifiers(content)) {\n const packageName = resolvePackageName(specifier);\n\n if (!packageName || declared.has(packageName)) {\n continue;\n }\n\n violations.push({ file, specifier, packageName });\n }\n }\n\n return violations;\n}\n\n/**\n * Fail the build when generated code would import something the app cannot\n * resolve.\n *\n * This is the part that stops the defect class from returning. Rewriting the\n * one bad specifier fixes today's bundle; only the assertion stops the next\n * change to the generator from reintroducing it — under npm or yarn the mistake\n * is invisible, because hoisting resolves it by accident.\n *\n * @throws {UndeclaredGeneratedImportError} listing every violation found.\n */\nexport function assertGeneratedImportsAreDeclared(\n files: GeneratedFile[],\n declaredDependencies: string[],\n): void {\n const violations = findUndeclaredImports(files, declaredDependencies);\n\n if (violations.length > 0) {\n throw new UndeclaredGeneratedImportError(violations);\n }\n}\n"],"mappings":";;;;;;;;;AA0BA,IAAa,iCAAb,cAAoD,MAAM;CACxD,AAAO,YAAY,AAAgB,YAAgC;EACjE,MACE;GACE,0BAA0B,WAAW,OAAO;GAC5C;GACA,GAAG,WAAW,KACX,EAAE,MAAM,WAAW,kBAClB,KAAK,KAAK,MAAM,UAAU,eAAe,YAAY,6BACzD;GACA;GACA;GACA;GACA;EACF,EAAE,KAAK,IAAI,CACb;EAdiC;EAgBjC,KAAK,OAAO;CACd;AACF;AAMA,MAAM,iBACJ;;;;;;;;;;AAWF,SAAgB,kBAAkB,SAA2B;CAC3D,MAAM,aAAuB,CAAC;CAE9B,KAAK,MAAM,SAAS,QAAQ,SAAS,cAAc,GAAG;EACpD,MAAM,YAAY,MAAM,MAAM,MAAM;EAEpC,IAAI,WACF,WAAW,KAAK,SAAS;CAE7B;CAEA,OAAO;AACT;;;;;;AAOA,SAAgB,mBAAmB,WAAuC;CACxE,IACE,UAAU,WAAW,GAAG,KACxB,UAAU,WAAW,GAAG,KACxB,UAAU,WAAW,OAAO,KAC5B,UAAU,SAAS,KAAK,GAExB;CAGF,MAAM,WAAW,UAAU,MAAM,GAAG;CACpC,MAAM,cAAc,UAAU,WAAW,GAAG,IAAI,SAAS,MAAM,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,SAAS;CAE1F,IAAI,eAAe,SAAS,WAAW,GACrC;CAGF,OAAO;AACT;;;;;;;;AASA,SAAgB,sBACd,OACA,sBACoB;CACpB,MAAM,WAAW,IAAI,IAAI,oBAAoB;CAC7C,MAAM,aAAiC,CAAC;CAExC,KAAK,MAAM,EAAE,MAAM,aAAa,OAC9B,KAAK,MAAM,aAAa,kBAAkB,OAAO,GAAG;EAClD,MAAM,cAAc,mBAAmB,SAAS;EAEhD,IAAI,CAAC,eAAe,SAAS,IAAI,WAAW,GAC1C;EAGF,WAAW,KAAK;GAAE;GAAM;GAAW;EAAY,CAAC;CAClD;CAGF,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,kCACd,OACA,sBACM;CACN,MAAM,aAAa,sBAAsB,OAAO,oBAAoB;CAEpE,IAAI,WAAW,SAAS,GACtB,MAAM,IAAI,+BAA+B,UAAU;AAEvD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-app-production.mjs","names":[],"sources":["../../../../../../../core/src/production/build-app-production.ts"],"sourcesContent":["import { ProductionBuilder } from \"./production-builder\";\n\n/**\n * Build the application for production\n * Options are loaded from warlock.config.ts\n */\nexport async function buildAppProduction() {\n const builder = new ProductionBuilder();\n await builder.build();\n}\n"],"mappings":";;;;;;;AAMA,eAAsB,qBAAqB;CAEzC,MAAM,IADc,kBACR,
|
|
1
|
+
{"version":3,"file":"build-app-production.mjs","names":[],"sources":["../../../../../../../core/src/production/build-app-production.ts"],"sourcesContent":["import { ProductionBuilder } from \"./production-builder\";\n\n/**\n * Build the application for production\n * Options are loaded from warlock.config.ts\n */\nexport async function buildAppProduction() {\n const builder = new ProductionBuilder();\n await builder.build();\n}\n"],"mappings":";;;;;;;AAMA,eAAsB,qBAAqB;CAEzC,MAAM,IADc,kBACR,EAAE,MAAM;AACtB"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
import { getJsonFileAsync, putJsonFileAsync } from "@warlock.js/fs";
|
|
3
|
+
|
|
4
|
+
//#region ../core/src/production/dist-build-manifest.ts
|
|
5
|
+
/**
|
|
6
|
+
* Name of the marker file `warlock build` writes into the output directory
|
|
7
|
+
* as the last step before promoting it to `dist`, and the only thing
|
|
8
|
+
* `warlock start` trusts to tell a genuine build from stale or
|
|
9
|
+
* hand-assembled output.
|
|
10
|
+
*
|
|
11
|
+
* Hidden (leading dot) so it never collides with a route, a static asset, or
|
|
12
|
+
* anything an app might legitimately name `manifest.json`.
|
|
13
|
+
*/
|
|
14
|
+
const DIST_BUILD_MANIFEST_FILE_NAME = ".warlock-build.json";
|
|
15
|
+
/**
|
|
16
|
+
* Write the build-success marker into an output directory (the temp
|
|
17
|
+
* directory a build assembled, before it is promoted to `dist`).
|
|
18
|
+
*/
|
|
19
|
+
async function writeDistBuildManifestAsync(directory) {
|
|
20
|
+
const manifest = {
|
|
21
|
+
status: "success",
|
|
22
|
+
builtAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
23
|
+
};
|
|
24
|
+
await putJsonFileAsync(path.join(directory, DIST_BUILD_MANIFEST_FILE_NAME), manifest);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Read the build-success marker out of `dist`.
|
|
28
|
+
*
|
|
29
|
+
* Returns `undefined` for every way the marker can fail to back a real
|
|
30
|
+
* build: missing, unreadable, malformed JSON, or present without
|
|
31
|
+
* `status: "success"`. "Never built", "build failed before promoting", and
|
|
32
|
+
* "someone hand-edited dist" all collapse to the same outcome, because
|
|
33
|
+
* `warlock start` treats them identically — refuse, and say why.
|
|
34
|
+
*/
|
|
35
|
+
async function readDistBuildManifestAsync(directory) {
|
|
36
|
+
try {
|
|
37
|
+
const manifest = await getJsonFileAsync(path.join(directory, DIST_BUILD_MANIFEST_FILE_NAME));
|
|
38
|
+
if (manifest?.status !== "success") return;
|
|
39
|
+
return manifest;
|
|
40
|
+
} catch {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
export { readDistBuildManifestAsync, writeDistBuildManifestAsync };
|
|
47
|
+
//# sourceMappingURL=dist-build-manifest.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dist-build-manifest.mjs","names":[],"sources":["../../../../../../../core/src/production/dist-build-manifest.ts"],"sourcesContent":["import { getJsonFileAsync, putJsonFileAsync } from \"@warlock.js/fs\";\nimport path from \"path\";\n\n/**\n * Name of the marker file `warlock build` writes into the output directory\n * as the last step before promoting it to `dist`, and the only thing\n * `warlock start` trusts to tell a genuine build from stale or\n * hand-assembled output.\n *\n * Hidden (leading dot) so it never collides with a route, a static asset, or\n * anything an app might legitimately name `manifest.json`.\n */\nexport const DIST_BUILD_MANIFEST_FILE_NAME = \".warlock-build.json\";\n\n/**\n * Recorded once, at the end of a build that reached the promote step. Its\n * presence — with `status: \"success\"` — is the whole contract `warlock\n * start` checks. Not any particular output file, which a future build shape\n * could rename or drop.\n */\nexport type DistBuildManifest = {\n status: \"success\";\n builtAt: string;\n};\n\n/**\n * Write the build-success marker into an output directory (the temp\n * directory a build assembled, before it is promoted to `dist`).\n */\nexport async function writeDistBuildManifestAsync(directory: string): Promise<void> {\n const manifest: DistBuildManifest = {\n status: \"success\",\n builtAt: new Date().toISOString(),\n };\n\n await putJsonFileAsync(path.join(directory, DIST_BUILD_MANIFEST_FILE_NAME), manifest);\n}\n\n/**\n * Read the build-success marker out of `dist`.\n *\n * Returns `undefined` for every way the marker can fail to back a real\n * build: missing, unreadable, malformed JSON, or present without\n * `status: \"success\"`. \"Never built\", \"build failed before promoting\", and\n * \"someone hand-edited dist\" all collapse to the same outcome, because\n * `warlock start` treats them identically — refuse, and say why.\n */\nexport async function readDistBuildManifestAsync(\n directory: string,\n): Promise<DistBuildManifest | undefined> {\n try {\n const manifest = await getJsonFileAsync<DistBuildManifest>(\n path.join(directory, DIST_BUILD_MANIFEST_FILE_NAME),\n );\n\n if (manifest?.status !== \"success\") {\n return undefined;\n }\n\n return manifest;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,gCAAgC;;;;;AAiB7C,eAAsB,4BAA4B,WAAkC;CAClF,MAAM,WAA8B;EAClC,QAAQ;EACR,0BAAS,IAAI,KAAK,GAAE,YAAY;CAClC;CAEA,MAAM,iBAAiB,KAAK,KAAK,WAAW,6BAA6B,GAAG,QAAQ;AACtF;;;;;;;;;;AAWA,eAAsB,2BACpB,WACwC;CACxC,IAAI;EACF,MAAM,WAAW,MAAM,iBACrB,KAAK,KAAK,WAAW,6BAA6B,CACpD;EAEA,IAAI,UAAU,WAAW,WACvB;EAGF,OAAO;CACT,QAAQ;EACN;CACF;AACF"}
|
|
@@ -6,7 +6,9 @@ import { warlockConfigManager } from "../warlock-config/warlock-config.manager.m
|
|
|
6
6
|
import { tsconfigManager } from "../dev-server/tsconfig-manager.mjs";
|
|
7
7
|
import { assertGeneratedImportsAreDeclared } from "./assert-generated-imports.mjs";
|
|
8
8
|
import { dedupe, runEmitContributions, runGenerateContributions } from "./build-contributions.mjs";
|
|
9
|
+
import { writeDistBuildManifestAsync } from "./dist-build-manifest.mjs";
|
|
9
10
|
import { nativeNodeModulesPlugin } from "./esbuild-plugins.mjs";
|
|
11
|
+
import { commitDistAsync, createTempOutputDir, rollbackDistAsync, stageDistAsync } from "./promote-dist.mjs";
|
|
10
12
|
import { resolveBuildConfig } from "./resolve-build-config.mjs";
|
|
11
13
|
import path from "path";
|
|
12
14
|
import { toCamelCase } from "@mongez/reinforcements";
|
|
@@ -83,16 +85,54 @@ var ProductionBuilder = class {
|
|
|
83
85
|
}
|
|
84
86
|
/**
|
|
85
87
|
* Main build entry point
|
|
88
|
+
*
|
|
89
|
+
* The esbuild bundle is written into a TEMP directory next to the real
|
|
90
|
+
* output directory, never into it, and that directory is renamed over
|
|
91
|
+
* `outdir` as one filesystem operation — so `outdir` is never observed as
|
|
92
|
+
* a mix of the old build and the new one, and a build that fails before
|
|
93
|
+
* that rename never touches `outdir` at all.
|
|
94
|
+
*
|
|
95
|
+
* `this.options.outdir` is NOT repointed at the temp directory while that
|
|
96
|
+
* happens, and must never be. It is not merely a write target: consumers
|
|
97
|
+
* BAKE it into runtime output — `web`'s build contribution derives the
|
|
98
|
+
* `clientDir` recorded in its pages manifest from it
|
|
99
|
+
* (`web/src/build/contribution.ts`) — so a temp path reaching them
|
|
100
|
+
* produces an artifact whose browser paths point at a directory promotion
|
|
101
|
+
* has since renamed away. The temp path is passed explicitly, as a
|
|
102
|
+
* parameter, to the one operation that writes into it ({@link bundle});
|
|
103
|
+
* everything else, `buildContext()` included, keeps reading the final
|
|
104
|
+
* destination.
|
|
105
|
+
*
|
|
106
|
+
* That is also why promotion is STAGED rather than done at the very end.
|
|
107
|
+
* Connector `emit` hooks write real artifacts (the web client bundle) and
|
|
108
|
+
* see the final `outdir`, so they must run when `outdir` genuinely holds
|
|
109
|
+
* this build — after the rename, not before it, or promotion would replace
|
|
110
|
+
* the directory they just wrote into. The previous build is kept parked
|
|
111
|
+
* aside until they finish: `emit` throwing rolls the whole promotion back,
|
|
112
|
+
* and the build-success marker `warlock start` checks is written last of
|
|
113
|
+
* all, so a failure at any point leaves no `dist` that start will boot.
|
|
86
114
|
*/
|
|
87
115
|
async build() {
|
|
88
116
|
console.log(colors.cyan("Building for production...\n"));
|
|
89
117
|
await this.initializeOptions();
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
118
|
+
const finalOutDir = this.options.outdir;
|
|
119
|
+
const tempOutDir = createTempOutputDir(finalOutDir);
|
|
120
|
+
let staged;
|
|
121
|
+
try {
|
|
122
|
+
await this.generateCombinedFiles();
|
|
123
|
+
await this.generateEntryPoint();
|
|
124
|
+
await this.assertGeneratedImports();
|
|
125
|
+
if (await this.runGenerateContributions()) await this.assertGeneratedImports();
|
|
126
|
+
await this.bundle(tempOutDir);
|
|
127
|
+
staged = await stageDistAsync(tempOutDir, finalOutDir);
|
|
128
|
+
await runEmitContributions(this.connectors, this.buildContext());
|
|
129
|
+
await writeDistBuildManifestAsync(finalOutDir);
|
|
130
|
+
await commitDistAsync(staged);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
if (staged) await rollbackDistAsync(staged);
|
|
133
|
+
else await removeDirectoryAsync(tempOutDir).catch(() => void 0);
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
96
136
|
await removeDirectoryAsync(this.productionDir);
|
|
97
137
|
console.log(colors.green("Build complete!"));
|
|
98
138
|
console.log(`Start production server by running ${colors.cyan("warlock start")}`);
|
|
@@ -335,9 +375,17 @@ bootstrap();
|
|
|
335
375
|
`import warlockConfig from "${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config";`,
|
|
336
376
|
`registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,
|
|
337
377
|
"",
|
|
378
|
+
"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its",
|
|
379
|
+
"// own preflight is not reached until the database and cache have",
|
|
380
|
+
"// connected and every app module has been imported — seconds of work",
|
|
381
|
+
"// thrown away before anyone learns the port was taken. This probe is",
|
|
382
|
+
"// a bind-and-release on a socket that is never served, and it reports",
|
|
383
|
+
"// on stderr because no log channel is configured this early.",
|
|
384
|
+
"import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";",
|
|
385
|
+
"await preflightConfiguredHttpPort();",
|
|
386
|
+
"",
|
|
338
387
|
"// 3. Start early-phase connectors (database, cache, logger, ...)",
|
|
339
388
|
"// so data sources, cache, etc. are ready before app code runs",
|
|
340
|
-
"import { Application, connectorsManager, ConnectorLifecyclePhase } from \"@warlock.js/core\";",
|
|
341
389
|
"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);"
|
|
342
390
|
];
|
|
343
391
|
imports.push("", "// 4. Load app code (events, locales, main, routes)");
|
|
@@ -353,22 +401,29 @@ bootstrap();
|
|
|
353
401
|
}
|
|
354
402
|
/**
|
|
355
403
|
* Bundle with esbuild
|
|
404
|
+
*
|
|
405
|
+
* @param writeOutDir the directory esbuild writes into — the build's
|
|
406
|
+
* private temp directory, NOT `options.outdir`. Taken as a parameter
|
|
407
|
+
* rather than read off `this.options` because the two are different paths
|
|
408
|
+
* with different meanings: `options.outdir` is the final destination every
|
|
409
|
+
* consumer bakes into the artifact, and this is only where bytes land
|
|
410
|
+
* before promotion moves them there.
|
|
356
411
|
*/
|
|
357
|
-
async bundle() {
|
|
412
|
+
async bundle(writeOutDir) {
|
|
358
413
|
console.log(colors.magenta(" Bundling with esbuild..."));
|
|
359
414
|
const entryPoint = path.join(this.productionDir, "app.ts");
|
|
360
|
-
const outDir = this.options.outdir;
|
|
361
415
|
const outFileName = this.options.outFile;
|
|
362
416
|
const entryName = path.basename(outFileName, path.extname(outFileName));
|
|
363
417
|
const singleBundle = this.options.singleBundle === true;
|
|
364
418
|
const esmShim = this.options.esmShim !== false;
|
|
365
419
|
const userBanner = this.options.banner;
|
|
366
|
-
|
|
367
|
-
delete
|
|
420
|
+
const strippable = this.options;
|
|
421
|
+
delete strippable.outFile;
|
|
422
|
+
delete strippable.entryPath;
|
|
368
423
|
delete this.options.singleBundle;
|
|
369
424
|
delete this.options.esmShim;
|
|
370
425
|
delete this.options.banner;
|
|
371
|
-
await ensureDirectoryAsync(
|
|
426
|
+
await ensureDirectoryAsync(writeOutDir);
|
|
372
427
|
const alias = this.buildAliasMapFromTsconfig();
|
|
373
428
|
const isEsm = (this.options.format ?? "esm") === "esm";
|
|
374
429
|
const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : void 0);
|
|
@@ -397,12 +452,12 @@ bootstrap();
|
|
|
397
452
|
sourcemap: this.options.sourcemap === true ? "linked" : this.options.sourcemap,
|
|
398
453
|
format: "esm",
|
|
399
454
|
target: ["node22"],
|
|
400
|
-
outdir: outDir,
|
|
401
455
|
entryNames: entryName,
|
|
402
456
|
alias,
|
|
403
457
|
plugins: [nativeNodeModulesPlugin],
|
|
404
458
|
...contributedOptions,
|
|
405
459
|
...this.options,
|
|
460
|
+
outdir: writeOutDir,
|
|
406
461
|
...define ? { define } : {},
|
|
407
462
|
...external ? { external } : {},
|
|
408
463
|
...loader ? { loader } : {},
|
|
@@ -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 { 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 * 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 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 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\r\n await this.bundle();\r\n\r\n // Step 5.5: Drain the connectors' `emit` contributions — after the\r\n // bundle, and BEFORE step 6 deletes the directory they may still read.\r\n await runEmitContributions(this.connectors, this.buildContext());\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 \"// 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 //\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 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 // `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 delete this.options.outFile;\r\n delete this.options.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(outDir);\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 outdir: outDir,\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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,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;wBAqI5B;GACvB,SAAS;GACT,QAAQ;GACR,MAAM;GACN,QAAQ;EACV;;;;;CArIA,MAAa,QAAuB;EAClC,QAAQ,IAAI,OAAO,KAAK,8BAA8B,CAAC;EAGvD,MAAM,KAAK,kBAAkB;EAG7B,MAAM,KAAK,sBAAsB;EAGjC,MAAM,KAAK,mBAAmB;EAG9B,MAAM,KAAK,uBAAuB;EAclC,IAAI,MAXsB,KAAK,yBAAyB,GAYtD,MAAM,KAAK,uBAAuB;EAIpC,MAAM,KAAK,OAAO;EAIlB,MAAM,qBAAqB,KAAK,YAAY,KAAK,aAAa,CAAC;EAG/D,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,mBAAmB;EAGlC,MAAM,aAAa,qBAAqB,IAAI,YAAY,KAAK,CAA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AC;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 { 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;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