@warlock.js/core 5.2.2 → 5.2.4
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 +13 -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.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.map +1 -1
- 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.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/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.mjs.map +1 -1
- package/esm/config/config-setter.d.mts.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.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.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/seed-command-action.mjs.map +1 -1
- package/esm/database/seeds/seed-records-table-migration.mjs.map +1 -1
- package/esm/database/seeds/seeders.manager.mjs.map +1 -1
- package/esm/database/seeds/seeds-table-migration.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.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.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/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/generations/add-command.action.mjs +28 -11
- package/esm/generations/add-command.action.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/web.feature.mjs +8 -7
- package/esm/generations/features/web.feature.mjs.map +1 -1
- package/esm/generations/stubs.mjs +49 -33
- package/esm/generations/stubs.mjs.map +1 -1
- package/esm/http/boot-port-preflight.d.mts.map +1 -1
- 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/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/maintenance.middleware.mjs.map +1 -1
- package/esm/http/middleware/utils/idempotency-key.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.map +1 -1
- package/esm/http/request.mjs.map +1 -1
- 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.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/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.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-generated-imports.mjs.map +1 -1
- package/esm/production/build-app-production.mjs.map +1 -1
- package/esm/production/dist-build-manifest.mjs.map +1 -1
- package/esm/production/production-builder.mjs.map +1 -1
- package/esm/production/production-supervisor.mjs.map +1 -1
- package/esm/production/promote-dist.mjs.map +1 -1
- 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/log-request-lifecycle.mjs.map +1 -1
- package/esm/router/normalize-route-path.d.mts.map +1 -1
- 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-registry.d.mts.map +1 -1
- package/esm/router/route-registry.mjs.map +1 -1
- package/esm/router/router.d.mts.map +1 -1
- 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/utils/safe-fetch.mjs.map +1 -1
- package/esm/tests/start-http-development-server.d.mts.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/package-manager.mjs +15 -1
- package/esm/updater/package-manager.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/warlock-config.manager.d.mts.map +1 -1
- package/esm/warlock-config/warlock-config.manager.mjs.map +1 -1
- package/llms-full.txt +4 -1
- package/llms.txt +1 -1
- package/package.json +12 -12
- package/skills/README.md +1 -1
- package/skills/write-cli-command/SKILL.md +4 -1
|
@@ -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,EAAE;EAClC,IAAI,oBA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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,YAAY;EAC9B,SAAS,QAAQ,WAA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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,IAAkB,YAAY;;;;iBAO9B,WAAA,IAAe,YAAY;;;;iBAO3B,WAAA,CAAY,KAAA,WAAgB,YAAY;;;;iBAUxC,kBAAA,CAAmB,OAAA,WAAkB,YAAY;;;;iBAOjD,aAAA,CAAc,KAAa;;;;iBAO3B,sBAAA,CAAuB,OAAe;;;;iBAOtC,cAAA;;;;iBAOA,gBAAA;;;;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,EACrE,CAAC,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,CAAC,CAAC,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"}
|
|
@@ -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,CAAC,CAAC,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,CAAC,CAAC,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,CAAC,CAAC,MAAM;AACtB"}
|
|
@@ -1 +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,
|
|
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,EAAC,CAAC,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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n ensureDirectoryAsync,\r\n fileExistsAsync,\r\n getFileAsync,\r\n getJsonFileAsync,\r\n putFileAsync,\r\n removeDirectoryAsync,\r\n} from \"@warlock.js/fs\";\r\nimport esbuild from \"esbuild\";\r\nimport glob from \"fast-glob\";\r\nimport path from \"path\";\r\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\r\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\r\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\r\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, rootPath, warlockPath } from \"../utils\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\r\nimport { dedupe, runEmitContributions, runGenerateContributions } from \"./build-contributions\";\r\nimport { writeDistBuildManifestAsync } from \"./dist-build-manifest\";\r\nimport { nativeNodeModulesPlugin } from \"./esbuild-plugins\";\r\nimport {\r\n commitDistAsync,\r\n createTempOutputDir,\r\n rollbackDistAsync,\r\n stageDistAsync,\r\n type StagedDist,\r\n} from \"./promote-dist\";\r\nimport { resolveBuildConfig, type ResolvedBuildConfig } from \"./resolve-build-config\";\r\nimport { toCamelCase, toKebabCase } from \"@mongez/reinforcements\";\r\n\r\n/**\r\n * Recreates `require`, `__filename` and `__dirname` at the top of an ESM bundle.\r\n *\r\n * Bundled CommonJS dependencies call `require(\"node:assert\")` and read\r\n * `__dirname` to locate their own assets. Neither exists in an ES module, so\r\n * esbuild substitutes a stub that throws — **after the build has reported\r\n * success**. `Dynamic require of \"node:assert\" is not supported` is that stub\r\n * firing, and it is the defect this shim removes.\r\n *\r\n * `__dirname` matters as much as `require`: without it a dependency resolving\r\n * an asset path silently gets `undefined` and fails later, further from the\r\n * cause.\r\n *\r\n * Written as one line because esbuild inserts a banner verbatim above the\r\n * bundle and a multi-line string here would shift every mapped line.\r\n */\r\nconst ESM_INTEROP_SHIM =\r\n \"import{createRequire as __wlCreateRequire}from'node:module';\" +\r\n \"import{fileURLToPath as __wlFileURLToPath}from'node:url';\" +\r\n \"import{dirname as __wlDirname}from'node:path';\" +\r\n \"const require=__wlCreateRequire(import.meta.url);\" +\r\n \"const __filename=__wlFileURLToPath(import.meta.url);\" +\r\n \"const __dirname=__wlDirname(__filename);\";\r\n\r\n/**\r\n * Combine the framework's banner with the user's, keeping both.\r\n *\r\n * esbuild's `banner` is an object keyed by output type, and every merge in the\r\n * path to it — the config merge and the options spread — REPLACES that object\r\n * rather than merging it. So whichever is applied second silently deletes the\r\n * other. This is the only place the two can coexist.\r\n *\r\n * The shim goes first: it defines `require`, which a user banner may use.\r\n *\r\n * @param userBanner banner from `warlock.config.ts`, if any\r\n * @param shim the interop shim, or undefined when it does not apply\r\n */\r\nfunction mergeBanner(\r\n userBanner: Record<string, string> | undefined,\r\n shim: string | undefined,\r\n): Record<string, string> | undefined {\r\n if (!shim) return userBanner;\r\n\r\n const userJs = userBanner?.js;\r\n\r\n return {\r\n ...userBanner,\r\n js: userJs ? `${shim}${userJs}` : shim,\r\n };\r\n}\r\n\r\n/**\r\n * Prefix every generated file uses to reach the app root.\r\n *\r\n * Generated sources are written into `.warlock/production/`, two levels below\r\n * the app root, so `../../` lands back on it — the same hop already spelled\r\n * out in the `../../src/app/…` and `../../src/config/…` imports the module and\r\n * config-loader generators emit. Named once so a generator that needs a new\r\n * app-root file (`warlock.config`) cannot pick a different depth.\r\n */\r\nconst APP_ROOT_FROM_PRODUCTION_DIR = \"../../\";\r\n\r\n/**\r\n * Production Builder\r\n * Generates production-ready files and bundles them for deployment\r\n * Build options are loaded from warlock.config.ts\r\n */\r\nexport class ProductionBuilder {\r\n private options!: ResolvedBuildConfig;\r\n private readonly productionDir = warlockPath(\"production\");\r\n\r\n /**\r\n * Connectors declared in `warlock.config.ts`. Read statically — `build`\r\n * never calls `boot()`/`start()` on them; it only\r\n * drains their `build` contributions.\r\n */\r\n private connectors: readonly Connector[] = [];\r\n\r\n /**\r\n * The contributors' merged esbuild patch, produced by the `generate` pass\r\n * and consumed by {@link bundle}.\r\n */\r\n private contributedEsbuild: ConnectorEsbuildPatch = {};\r\n\r\n /**\r\n * Main build entry point\r\n *\r\n * The esbuild bundle is written into a TEMP directory next to the real\r\n * output directory, never into it, and that directory is renamed over\r\n * `outdir` as one filesystem operation — so `outdir` is never observed as\r\n * a mix of the old build and the new one, and a build that fails before\r\n * that rename never touches `outdir` at all.\r\n *\r\n * `this.options.outdir` is NOT repointed at the temp directory while that\r\n * happens, and must never be. It is not merely a write target: consumers\r\n * BAKE it into runtime output — `web`'s build contribution derives the\r\n * `clientDir` recorded in its pages manifest from it\r\n * (`web/src/build/contribution.ts`) — so a temp path reaching them\r\n * produces an artifact whose browser paths point at a directory promotion\r\n * has since renamed away. The temp path is passed explicitly, as a\r\n * parameter, to the one operation that writes into it ({@link bundle});\r\n * everything else, `buildContext()` included, keeps reading the final\r\n * destination.\r\n *\r\n * That is also why promotion is STAGED rather than done at the very end.\r\n * Connector `emit` hooks write real artifacts (the web client bundle) and\r\n * see the final `outdir`, so they must run when `outdir` genuinely holds\r\n * this build — after the rename, not before it, or promotion would replace\r\n * the directory they just wrote into. The previous build is kept parked\r\n * aside until they finish: `emit` throwing rolls the whole promotion back,\r\n * and the build-success marker `warlock start` checks is written last of\r\n * all, so a failure at any point leaves no `dist` that start will boot.\r\n */\r\n public async build(): Promise<void> {\r\n console.log(colors.cyan(\"Building for production...\\n\"));\r\n\r\n // Step 1: Initialize options from config\r\n await this.initializeOptions();\r\n\r\n const finalOutDir = this.options.outdir!;\r\n const tempOutDir = createTempOutputDir(finalOutDir);\r\n\r\n // Set once the temp directory has been renamed onto `finalOutDir`. Its\r\n // presence is what tells the catch below whether a failure has a\r\n // promotion to undo or only a temp directory to discard.\r\n let staged: StagedDist | undefined;\r\n\r\n try {\r\n // Step 2: Generate combined files\r\n await this.generateCombinedFiles();\r\n\r\n // Step 3: Generate entry point\r\n await this.generateEntryPoint();\r\n\r\n // Step 4: Refuse to bundle code the app could not resolve at runtime\r\n await this.assertGeneratedImports();\r\n\r\n // Step 4.5: Drain the connectors' `generate` contributions\r\n const contributed = await this.runGenerateContributions();\r\n\r\n // Step 4.6: Re-assert over what the contributors just wrote.\r\n //\r\n // Step 4 only saw core's own generated files; a contributor writes its\r\n // code (a pages barrel, say) AFTER that assertion, so an undeclared bare\r\n // specifier in it reaches the bundle unchecked. Under\r\n // `packages: \"external\"` that specifier survives verbatim into the\r\n // artifact and dies as ERR_MODULE_NOT_FOUND at runtime — the same failure\r\n // step 4 exists to prevent. Skipped when nothing contributed: re-globbing\r\n // and re-reading the production dir is pure cost in the common case.\r\n if (contributed) {\r\n await this.assertGeneratedImports();\r\n }\r\n\r\n // Step 5: Bundle with esbuild into the temp directory. The ONLY\r\n // operation handed that path — it is a write target, not config.\r\n await this.bundle(tempOutDir);\r\n\r\n // Step 5.5: Promote the bundle into `outdir`, keeping the previous\r\n // build parked aside. `outdir` now holds exactly this build, so the\r\n // steps below write into — and record — the real destination.\r\n staged = await stageDistAsync(tempOutDir, finalOutDir);\r\n\r\n // Step 5.6: Drain the connectors' `emit` contributions — after the\r\n // bundle is in place (so what they write survives promotion and the\r\n // paths they bake in resolve), and BEFORE step 6 deletes the\r\n // production directory they may still read.\r\n await runEmitContributions(this.connectors, this.buildContext());\r\n\r\n // Step 5.7: Mark `dist` as a genuine, complete build — the one thing\r\n // `warlock start` trusts. Written LAST on purpose: every earlier step\r\n // can still fail, and until this file exists nothing will boot what\r\n // they left behind.\r\n await writeDistBuildManifestAsync(finalOutDir);\r\n\r\n // Step 5.8: Commit — drop the parked previous build. Cannot throw.\r\n await commitDistAsync(staged);\r\n } catch (error) {\r\n if (staged) {\r\n // The promotion already happened; put the previous build back and\r\n // take this half-finished one out of `outdir`.\r\n await rollbackDistAsync(staged);\r\n } else {\r\n // Nothing this build produced ever reached `outdir` — discard the\r\n // temp directory and leave `outdir` exactly as it was.\r\n await removeDirectoryAsync(tempOutDir).catch(() => undefined);\r\n }\r\n\r\n throw error;\r\n }\r\n\r\n // Step 6: Remove production folder\r\n await removeDirectoryAsync(this.productionDir);\r\n\r\n console.log(colors.green(\"Build complete!\"));\r\n console.log(`Start production server by running ${colors.cyan(\"warlock start\")}`);\r\n }\r\n\r\n /**\r\n * Initialize options from warlock.config.ts\r\n */\r\n private async initializeOptions(): Promise<void> {\r\n this.options = resolveBuildConfig();\r\n // Same config object `resolveBuildConfig` just read — `warlock build`\r\n // preloads warlock.config.ts, so no additional load happens here.\r\n const connectors = warlockConfigManager.get(\"connectors\") ?? [];\r\n\r\n // Checked here, where the array is first read, so nothing downstream has\r\n // drained anything yet: the `generate` and `emit` passes run per ENTRY, so\r\n // a name listed twice would write its files and merge its esbuild options\r\n // twice into an artifact the runtime then boots that name only once from.\r\n // A build that half-applied a connector and reported success is worse than\r\n // one that never started.\r\n assertUniqueConnectorNames([...connectors]);\r\n\r\n // And here rather than only at boot, for the same reason: a name a built-in\r\n // already owns is skipped by the runtime, so an artifact built from it\r\n // carries the custom connector's generated files and esbuild patches while\r\n // the server boots the built-in instead. Refusing it at boot alone would\r\n // mean the build had already emitted that artifact — the failure has to\r\n // land on the developer running `warlock build`, not on whoever starts the\r\n // server. Same assertion the registration half calls, over the same names.\r\n assertNoReservedConnectorNames([...connectors]);\r\n\r\n this.connectors = connectors;\r\n\r\n // Ensure production directory exists\r\n await ensureDirectoryAsync(this.productionDir);\r\n }\r\n\r\n /**\r\n * The context handed to every build contribution.\r\n */\r\n private buildContext(): ConnectorBuildContext {\r\n return {\r\n productionDir: this.productionDir,\r\n appRoot: rootPath(),\r\n options: this.options,\r\n };\r\n }\r\n\r\n /**\r\n * Drain the `generate` hooks and fold what they returned back into the\r\n * build.\r\n *\r\n * The entry point is REGENERATED here rather than generated later. The\r\n * contribution slot is fixed — after `assertGeneratedImports` (so nothing\r\n * bundles that the app could not resolve) and before `bundle` — while\r\n * `generateEntryPoint` must stay at step 3, because `app.ts` is itself\r\n * generated code the assertion has to see; moving it past the assertion\r\n * would silently drop the entry from that check. Rewriting one small file\r\n * is cheaper than losing either guarantee, and the write is pure\r\n * (`generatedFiles` + these imports), so doing it twice is not a\r\n * correctness risk.\r\n *\r\n * @returns whether any connector ran a `generate` hook — the caller uses it\r\n * to decide if the import assertion is worth a second pass. Keyed on the\r\n * hook EXISTING, not on what it returned: a hook that returns nothing may\r\n * still have written files into `productionDir`, and those are exactly the\r\n * files the second pass is there to read.\r\n */\r\n private async runGenerateContributions(): Promise<boolean> {\r\n const contributed = this.connectors.some((connector) => Boolean(connector.build?.generate));\r\n\r\n const { entryImports, esbuild } = await runGenerateContributions(\r\n this.connectors,\r\n this.buildContext(),\r\n );\r\n\r\n this.contributedEsbuild = esbuild;\r\n\r\n if (entryImports.length > 0) {\r\n await this.generateEntryPoint(entryImports);\r\n }\r\n\r\n return contributed;\r\n }\r\n\r\n /**\r\n * Track which special files were generated\r\n */\r\n private generatedFiles = {\r\n locales: false,\r\n events: false,\r\n main: false,\r\n routes: false,\r\n };\r\n\r\n /**\r\n * Generate all combined files\r\n */\r\n private async generateCombinedFiles(): Promise<void> {\r\n console.log(colors.yellow(\" Generating production files...\"));\r\n\r\n // Generate bootstrap.ts file\r\n await this.generateBootstrap();\r\n\r\n // Generate config loader\r\n await this.generateConfigLoader();\r\n\r\n // Generate special files and track which ones have content\r\n const [locales, events, main, routes] = await Promise.all([\r\n this.generateLocales(),\r\n this.generateEvents(),\r\n this.generateMain(),\r\n this.generateRoutes(),\r\n ]);\r\n\r\n this.generatedFiles = { locales, events, main, routes };\r\n }\r\n\r\n /**\r\n * Generate bootstrap.ts - ensures bootstrap() runs first and sets production environment\r\n */\r\n private async generateBootstrap(): Promise<void> {\r\n let content = `import { bootstrap, Application } from \"@warlock.js/core\";\r\n\r\n// Set production environment\r\nApplication.setRuntimeStrategy(\"production\");\r\nApplication.setEnvironment(\"production\");\r\n\r\n// Bootstrap the application\r\nbootstrap();\r\n`;\r\n if (await fileExistsAsync(appPath(\"bootstrap.ts\"))) {\r\n content += \"import './../../src/app/bootstrap';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"bootstrap.ts\"), content);\r\n }\r\n\r\n /**\r\n * Fail the build when generated code imports a package the app does not\r\n * declare.\r\n *\r\n * The bundler is configured `packages: \"external\"`, so every bare specifier\r\n * written above survives verbatim into an artifact that resolves against the\r\n * **consuming app's** node_modules. A framework-internal dependency imported\r\n * there resolves by accident under npm/yarn hoisting and dies under pnpm —\r\n * which is how a production app shipped that could not boot. Rewriting the\r\n * offending import fixes today's bundle; this check is what stops the next\r\n * change to the generator from quietly reintroducing it.\r\n */\r\n private async assertGeneratedImports(): Promise<void> {\r\n const generatedPaths = await glob(\"**/*.{ts,tsx,js,mjs}\", {\r\n cwd: this.productionDir,\r\n absolute: false,\r\n });\r\n\r\n const [files, appPackage] = await Promise.all([\r\n Promise.all(\r\n generatedPaths.map(async (file) => ({\r\n file,\r\n content: await getFileAsync(path.join(this.productionDir, file)),\r\n })),\r\n ),\r\n getJsonFileAsync<{ dependencies?: Record<string, string> }>(rootPath(\"package.json\")),\r\n ]);\r\n\r\n assertGeneratedImportsAreDeclared(files, Object.keys(appPackage.dependencies ?? {}));\r\n }\r\n\r\n /**\r\n * Glob for module files matching a pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModule(fileName: string): Promise<string[]> {\r\n const pattern = `**/${fileName}.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n // Convert to relative paths from .warlock/production/ to src/app/\r\n // e.g., \"users/main\" -> \"../../src/app/users/main\"\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Glob for files in a specific directory pattern\r\n * Returns relative paths from .warlock/production/ to src/app/\r\n */\r\n private async globModuleDirectory(directory: string): Promise<string[]> {\r\n const pattern = `**/${directory}/*.{ts,tsx}`;\r\n const appDirectory = appPath();\r\n\r\n const files = await glob(pattern, {\r\n cwd: appDirectory,\r\n absolute: false,\r\n });\r\n\r\n return files.map((file) => \"../../src/app/\" + file.replace(/\\.(ts|tsx)$/, \"\"));\r\n }\r\n\r\n /**\r\n * Generate config-loader.ts\r\n */\r\n private async generateConfigLoader(): Promise<void> {\r\n const configDirectory = path.join(process.cwd(), \"src/config\");\r\n\r\n const files = await glob(\"*.{ts,tsx}\", {\r\n cwd: configDirectory,\r\n absolute: false,\r\n });\r\n\r\n const configNames = files.map((f) => f.replace(/\\.(ts|tsx)$/, \"\"));\r\n\r\n // Only `@warlock.js/core` — the one package the app itself declares. See\r\n // `assertGeneratedImportsAreDeclared`: `@mongez/config` is core's own\r\n // dependency, so a bare import of it resolved by luck under npm/yarn\r\n // hoisting and died under pnpm's strict layout.\r\n const imports: string[] = [\r\n 'import { setConfig, configSpecialHandlers } from \"@warlock.js/core\";',\r\n ];\r\n const configImports: string[] = [];\r\n const configSetCalls: string[] = [];\r\n const executors: string[] = [];\r\n\r\n for (const configName of configNames) {\r\n const properConfigName = toCamelCase(configName);\r\n const varName = `${properConfigName}Config`;\r\n configImports.push(`import ${varName} from \"../../src/config/${configName}\";`);\r\n configSetCalls.push(`setConfig(\"${properConfigName}\", ${varName});`);\r\n executors.push(`await configSpecialHandlers.execute(\"${properConfigName}\", ${varName});`);\r\n }\r\n\r\n let content = [\r\n ...imports,\r\n \"\",\r\n \"// Config imports\",\r\n ...configImports,\r\n \"\",\r\n \"// Register configs\",\r\n ...configSetCalls,\r\n \"\",\r\n \"// Special handlers\",\r\n ...executors,\r\n \"\",\r\n ].join(\"\\n\");\r\n\r\n if (await fileExistsAsync(appPath(\"prestart.ts\"))) {\r\n content += \"import './../../src/app/prestart';\\n\";\r\n }\r\n\r\n await putFileAsync(path.join(this.productionDir, \"config-loader.ts\"), content);\r\n }\r\n\r\n /**\r\n * Generate locales.ts (only if there are locale files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateLocales(): Promise<boolean> {\r\n const files = await this.globModule(\"utils/locales\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"locales.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate events.ts (only if there are event files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateEvents(): Promise<boolean> {\r\n const files = await this.globModuleDirectory(\"events\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"events.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate main.ts (only if there are main files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateMain(): Promise<boolean> {\r\n const files = await this.globModule(\"main\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"main.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate routes.ts (only if there are route files)\r\n * @returns true if file was generated with content\r\n */\r\n private async generateRoutes(): Promise<boolean> {\r\n const files = await this.globModule(\"routes\");\r\n if (files.length === 0) return false;\r\n await this.generateImportsFile(files, \"routes.ts\");\r\n return true;\r\n }\r\n\r\n /**\r\n * Generate a file with imports from all given files\r\n */\r\n private async generateImportsFile(importPaths: string[], outputFile: string): Promise<void> {\r\n const imports = importPaths.map((importPath) => `import \"${importPath}\";`);\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, outputFile), content);\r\n }\r\n\r\n /**\r\n * Generate the main entry point (app.ts)\r\n *\r\n * @param contributedImports lines from connector `generate` hooks, appended\r\n * to section 4 after `./routes`\r\n */\r\n private async generateEntryPoint(contributedImports: string[] = []): Promise<void> {\r\n console.log(colors.yellow(\" Generating entry point...\"));\r\n\r\n // The names this build resolved, baked in as a literal. The entry imports\r\n // the config source, and that source is re-evaluated at startup — an\r\n // env-conditional `connectors` array can hand the boot a different list\r\n // than the one drained here. A literal is the only part of the array that\r\n // survives into the artifact unchanged, so it is what the boot compares\r\n // against.\r\n const expectedNames = this.connectors\r\n .map((connector) => JSON.stringify(connector.name))\r\n .join(\", \");\r\n\r\n // Build imports based on which files were generated\r\n const imports: string[] = [\r\n \"// 1. Bootstrap (loads .env, initializes framework)\",\r\n 'import \"./bootstrap\";',\r\n \"\",\r\n \"// 2. Load configs\",\r\n 'import \"./config-loader\";',\r\n \"\",\r\n // Registration has to sit between the config being available and the\r\n // first phase starting: the connectors listed in `connectors` are the\r\n // same ones this build drained contributions from, so the bundle boots\r\n // exactly what it was built for. Register any later and an early-phase\r\n // connector would miss its own start.\r\n \"// 2.5 Register connectors declared in warlock.config (the same array this\",\r\n \"// build read its contributions from, so built-for and boots-with match).\",\r\n \"// The config is imported STATICALLY so esbuild bakes it into the bundle\",\r\n \"// and the array is handed over explicitly — an artifact has no\",\r\n \"// warlock.config.ts beside it to read at runtime, and a registration\",\r\n \"// that quietly found nothing to register is the exact drift this\",\r\n \"// section exists to prevent.\",\r\n \"// `expectedNames` is the list this build resolved, in order — boot\",\r\n \"// refuses to start when the config hands over a different set or order.\",\r\n 'import { registerConfiguredConnectors } from \"@warlock.js/core\";',\r\n `import warlockConfig from \"${APP_ROOT_FROM_PRODUCTION_DIR}warlock.config\";`,\r\n `registerConfiguredConnectors(warlockConfig.connectors ?? [], { expectedNames: [${expectedNames}] });`,\r\n \"\",\r\n \"// 2.6 Fail fast on a busy port. `http` is a LATE-phase connector, so its\",\r\n \"// own preflight is not reached until the database and cache have\",\r\n \"// connected and every app module has been imported — seconds of work\",\r\n \"// thrown away before anyone learns the port was taken. This probe is\",\r\n \"// a bind-and-release on a socket that is never served, and it reports\",\r\n \"// on stderr because no log channel is configured this early.\",\r\n 'import { Application, connectorsManager, ConnectorLifecyclePhase, preflightConfiguredHttpPort } from \"@warlock.js/core\";',\r\n \"await preflightConfiguredHttpPort();\",\r\n \"\",\r\n \"// 3. Start early-phase connectors (database, cache, logger, ...)\",\r\n \"// so data sources, cache, etc. are ready before app code runs\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Early);\",\r\n ];\r\n\r\n // App code uses dynamic `await import(...)` so each module's side\r\n // effects fire at THIS point in execution. Static imports would be\r\n // hoisted to module-instantiation time (before the early-phase await\r\n // resolves), which is exactly the bug this split is meant to fix.\r\n //\r\n // The guarantee comes from the imports being DYNAMIC — esbuild wraps a\r\n // dynamically-imported module in its `__esm(() => {…})` helper and runs\r\n // it at the await, not at instantiation. It does NOT come from\r\n // `splitting: true`, which only decides one-file-vs-chunks. This\r\n // previously said splitting was required; it is not, and `singleBundle`\r\n // (splitting: false) preserves the ordering.\r\n imports.push(\"\", \"// 4. Load app code (events, locales, main, routes)\");\r\n\r\n if (this.generatedFiles.events) {\r\n imports.push('await import(\"./events\");');\r\n }\r\n if (this.generatedFiles.locales) {\r\n imports.push('await import(\"./locales\");');\r\n }\r\n if (this.generatedFiles.main) {\r\n imports.push('await import(\"./main\");');\r\n }\r\n if (this.generatedFiles.routes) {\r\n imports.push('await import(\"./routes\");');\r\n }\r\n\r\n // Contributor imports come AFTER `./routes`, never before: a connector\r\n // that registers pages needs the routes app code already collected —\r\n // the same ordering dev uses (routes first, then the connector installs\r\n // on top of them). Emitted verbatim; the contributor writes the whole\r\n // statement (e.g. `await import(\"./pages\");`).\r\n imports.push(...contributedImports);\r\n\r\n // A rejecting validator (Application.onValidateBoot) must abort boot\r\n // before late-phase connectors bind a port.\r\n imports.push(\r\n \"\",\r\n \"// 5. Run startup validators registered via Application.onValidateBoot(...)\",\r\n \"await Application.runStartupValidators();\",\r\n );\r\n\r\n // Start late-phase connectors after app code registers routes/listeners\r\n imports.push(\r\n \"\",\r\n \"// 6. Start late-phase connectors (http, socket) — routes and\",\r\n \"// listeners registered by app code are now ready to bind\",\r\n \"await connectorsManager.startPhase(ConnectorLifecyclePhase.Late);\",\r\n \"\",\r\n \"// 7. Signal a complete boot so `Application.onceBooted(...)` listeners fire\",\r\n \"Application.markBooted({ environment: Application.environment, runtimeStrategy: Application.runtimeStrategy });\",\r\n \"connectorsManager.shutdownOnProcessKill();\",\r\n );\r\n\r\n const content = imports.join(\"\\n\") + \"\\n\";\r\n await putFileAsync(path.join(this.productionDir, \"app.ts\"), content);\r\n }\r\n\r\n /**\r\n * Bundle with esbuild\r\n *\r\n * @param writeOutDir the directory esbuild writes into — the build's\r\n * private temp directory, NOT `options.outdir`. Taken as a parameter\r\n * rather than read off `this.options` because the two are different paths\r\n * with different meanings: `options.outdir` is the final destination every\r\n * consumer bakes into the artifact, and this is only where bytes land\r\n * before promotion moves them there.\r\n */\r\n private async bundle(writeOutDir: string): Promise<void> {\r\n console.log(colors.magenta(\" Bundling with esbuild...\"));\r\n\r\n const entryPoint = path.join(this.productionDir, \"app.ts\");\r\n const outFileName = this.options.outFile!;\r\n // Strip extension so entryNames produces \"<base>.js\" via esbuild\r\n const entryName = path.basename(outFileName, path.extname(outFileName));\r\n\r\n // `singleBundle` and `esmShim` are ours, not esbuild's — it throws on\r\n // unknown keys, and the user options are spread into its call verbatim.\r\n const singleBundle = this.options.singleBundle === true;\r\n const esmShim = this.options.esmShim !== false;\r\n // Read before deleting: the merged banner is applied AFTER the user\r\n // spread, so a user banner must not be lost to it or clobber the shim.\r\n const userBanner = this.options.banner;\r\n\r\n // `outFile` and `entryPath` are REQUIRED on ResolvedBuildConfig on purpose:\r\n // resolve-build-config.ts documents that widening them pushed a lie downstream\r\n // into start-production.command.ts, which then could not trust its own config.\r\n // This is the one place they must be absent - the object is spread into esbuild's\r\n // call verbatim and esbuild throws on unknown keys. Strip them through a local\r\n // optional view rather than weakening the type every other caller relies on; both\r\n // were already read into locals above.\r\n const strippable = this.options as Partial<ResolvedBuildConfig>;\r\n\r\n delete strippable.outFile;\r\n delete strippable.entryPath;\r\n delete this.options.singleBundle;\r\n delete this.options.esmShim;\r\n delete this.options.banner;\r\n\r\n await ensureDirectoryAsync(writeOutDir);\r\n\r\n const alias = this.buildAliasMapFromTsconfig();\r\n\r\n // The user can override `format`, so gate the shim on the EFFECTIVE\r\n // format rather than on the default below. A CJS build already has\r\n // `require` and friends; injecting them there would be a redefinition.\r\n const isEsm = (this.options.format ?? \"esm\") === \"esm\";\r\n const banner = mergeBanner(userBanner, esmShim && isEsm ? ESM_INTEROP_SHIM : undefined);\r\n\r\n // Contributor patch, split into the part that can ride the spread order\r\n // and the three keys that cannot. `jsx` and `jsxImportSource` are placed\r\n // BEFORE the user spread below, which gives the ruled precedence for\r\n // free: builder defaults < contributor < user config.\r\n //\r\n // `define`, `external` and `loader` are pulled out because a spread\r\n // REPLACES them wholesale — the same trap `banner` documents. Two\r\n // contributors' env defines, a contributor's optional peers plus the\r\n // user's, or a contributor's `.svg` loader alongside the user's `.png`,\r\n // must both survive, so they are merged by key/by set and re-applied\r\n // after the spread with the user still winning per key.\r\n const {\r\n define: contributedDefine,\r\n external: contributedExternal,\r\n loader: contributedLoader,\r\n ...contributedOptions\r\n } = this.contributedEsbuild;\r\n\r\n const userDefine: Record<string, string> | undefined = this.options.define;\r\n const userExternal: string[] | undefined = this.options.external;\r\n const userLoader: ConnectorEsbuildPatch[\"loader\"] = this.options.loader;\r\n\r\n const define =\r\n contributedDefine || userDefine ? { ...contributedDefine, ...userDefine } : undefined;\r\n\r\n const loader =\r\n contributedLoader || userLoader ? { ...contributedLoader, ...userLoader } : undefined;\r\n\r\n const external =\r\n contributedExternal || userExternal\r\n ? dedupe([...(contributedExternal ?? []), ...(userExternal ?? [])])\r\n : undefined;\r\n\r\n if (singleBundle) {\r\n console.log(\r\n colors.magenta(\r\n \" Single-bundle mode — one JS file\" +\r\n (esmShim && isEsm ? \" with the ESM interop shim\" : \"\") +\r\n \". Native .node addons are still emitted alongside it.\",\r\n ),\r\n );\r\n }\r\n\r\n\r\n try {\r\n \r\n await esbuild.build({\r\n platform: \"node\",\r\n entryPoints: [entryPoint],\r\n bundle: true,\r\n // Both are DEFAULTS the user can override — they sit before the\r\n // `...this.options` spread deliberately. `singleBundle` moves them,\r\n // an explicit `splitting`/`packages` in warlock.config.ts beats both.\r\n //\r\n // Phase ordering does not depend on `splitting`: it comes from the\r\n // generated app.ts using dynamic `await import(...)` (see\r\n // generateAppEntry above), which esbuild defers to the call site in\r\n // either mode. Splitting only decides one file vs chunks.\r\n splitting: !singleBundle,\r\n packages: singleBundle ? \"bundle\" : \"external\",\r\n minify: this.options!.minify,\r\n sourcemap: this.options!.sourcemap === true ? \"linked\" : this.options!.sourcemap,\r\n format: \"esm\",\r\n // Targeting a concrete Node version (not \"esnext\") so esbuild\r\n // transpiles TC39 stage 3 decorators into helpers — Node does not\r\n // implement them natively yet.\r\n target: [\"node22\"],\r\n entryNames: entryName,\r\n alias,\r\n plugins: [nativeNodeModulesPlugin],\r\n // Between the defaults and the user spread — the ruled precedence.\r\n ...contributedOptions,\r\n ...(this.options as any),\r\n // AFTER the spread, and NOT overridable: `this.options.outdir` rides\r\n // that spread carrying the FINAL destination, which is exactly where\r\n // this build must not write yet. The final path is the user's setting\r\n // and stays authoritative for everyone reading the config — it is only\r\n // this one esbuild call that is redirected, and only until promotion\r\n // moves the result onto that very path.\r\n outdir: writeOutDir,\r\n // AFTER the spread for the same reason `banner` is: a spread replaces\r\n // these objects instead of merging them, so the merged values are\r\n // re-applied here. The user still wins — they were merged in last.\r\n ...(define ? { define } : {}),\r\n ...(external ? { external } : {}),\r\n ...(loader ? { loader } : {}),\r\n // AFTER the spread, and intentionally so: `banner` is an object, and\r\n // both the config merge and this spread REPLACE it wholesale rather\r\n // than merging. Left as a default above, any user banner would delete\r\n // the shim; left to the spread, the shim would delete theirs. The\r\n // merge is the only form that keeps both.\r\n ...(banner ? { banner } : {}),\r\n });\r\n } catch (e) {\r\n console.log(e);\r\n throw e;\r\n }\r\n }\r\n\r\n /**\r\n * Build an alias map from tsconfig `paths` so esbuild resolves local\r\n * source aliases (e.g. `@warlock.js/cascade`) to their on-disk source\r\n * folders during bundling. Without this, `packages: \"external\"` would\r\n * leave those bare specifiers as raw imports and Node would fail to\r\n * resolve them at runtime (they aren't installed in node_modules).\r\n *\r\n * Only exact (non-wildcard) aliases are included — esbuild's `alias`\r\n * option doesn't support glob-style mappings.\r\n */\r\n private buildAliasMapFromTsconfig(): Record<string, string> {\r\n tsconfigManager.init();\r\n\r\n const alias: Record<string, string> = {};\r\n const baseUrl = path.resolve(process.cwd(), tsconfigManager.baseUrl);\r\n\r\n for (const [from, to] of Object.entries(tsconfigManager.aliases)) {\r\n if (from.endsWith(\"/*\") || !Array.isArray(to) || to.length === 0) {\r\n continue;\r\n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;GAC7B,CAAC;EACD,SAAS,GAAG;GACV,QAAQ,IAAI,CAAC;GACb,MAAM;EACR;CACF;;;;;;;;;;;CAYA,AAAQ,4BAAoD;EAC1D,gBAAgB,KAAK;EAErB,MAAM,QAAgC,CAAC;EACvC,MAAM,UAAU,KAAK,QAAQ,QAAQ,IAAI,GAAG,gBAAgB,OAAO;EAEnE,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,gBAAgB,OAAO,GAAG;GAChE,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,QAAQ,EAAE,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,GAAG,EAAE;EAC3C;EAEA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"production-builder.mjs","names":[],"sources":["../../../../../../../core/src/production/production-builder.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\r\nimport {\r\n ensureDirectoryAsync,\r\n fileExistsAsync,\r\n getFileAsync,\r\n getJsonFileAsync,\r\n putFileAsync,\r\n removeDirectoryAsync,\r\n} from \"@warlock.js/fs\";\r\nimport esbuild from \"esbuild\";\r\nimport glob from \"fast-glob\";\r\nimport path from \"path\";\r\nimport { assertNoReservedConnectorNames } from \"../connectors/assert-no-reserved-connector-names\";\r\nimport { assertUniqueConnectorNames } from \"../connectors/assert-unique-connector-names\";\r\nimport type { Connector, ConnectorBuildContext, ConnectorEsbuildPatch } from \"../connectors/types\";\r\nimport { tsconfigManager } from \"../dev-server/tsconfig-manager\";\r\nimport { appPath, rootPath, warlockPath } from \"../utils\";\r\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\r\nimport { assertGeneratedImportsAreDeclared } from \"./assert-generated-imports\";\r\nimport { 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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,KAAK,GAAG,WAAW,GAC7D;GAGF,MAAM,QAAQ,KAAK,QAAQ,SAAS,GAAG,EAAE;EAC3C;EAEA,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"production-supervisor.mjs","names":[],"sources":["../../../../../../../core/src/production/production-supervisor.ts"],"sourcesContent":["import { spawn } from \"child_process\";\nimport { BOOT_SIGNAL_ENV_KEY, isBootSignal } from \"../application/boot-signal\";\nimport {\n displayMissingReadinessNotice,\n displayProductionReadyBanner,\n displayProductionStartFailure,\n} from \"../cli/cli-commands.utils\";\n\n/**\n * How long a still-running child may stay silent before we say so.\n *\n * Only reached by a bundle built before readiness reporting existed; a current\n * bundle signals as soon as its late-phase connectors are up.\n */\nexport const DEFAULT_READINESS_NOTICE_DELAY_MS = 10_000;\n\nexport type ProductionSupervisorOptions = {\n /** Arguments handed to the node binary, entry file included. */\n nodeArgs: string[];\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n readinessNoticeDelayMs?: number;\n};\n\nexport type ProductionSupervisorResult = {\n /** What the CLI should exit with — never 0 for a boot that never completed. */\n exitCode: number;\n /** Whether the child ever reported a finished boot. */\n ready: boolean;\n};\n\n/**\n * Run the production bundle in a child process and report honestly on it.\n *\n * The supervisor exists because a parent that only forwards `stdio` cannot\n * see whether its child ever booted — it only sees the process exit. It\n * therefore opens an IPC channel and treats the child's `warlock:ready`\n * signal, emitted by `Application.markBooted`, as the single source of truth\n * for \"started\":\n *\n * 1. The success banner is printed only on that signal.\n * 2. A child that dies before signalling is reported as a failed start and\n * forced to a non-zero exit, even if it exited 0.\n * 3. A child still running without having signalled draws a note on stderr —\n * never stdout, which would be the false-green this whole channel prevents.\n * 4. Whether the child ever wrote to stdout/stderr before dying is tracked\n * (`sawChildOutput`) so the failure summary only claims \"the cause is\n * printed above\" when that is actually true — see the stdio comment\n * below.\n *\n * Resolves rather than exiting so the outcome stays assertable in a test; the\n * `start` command turns the result into the process exit code.\n */\nexport function superviseProductionProcess({\n nodeArgs,\n cwd = process.cwd(),\n env = process.env,\n readinessNoticeDelayMs = DEFAULT_READINESS_NOTICE_DELAY_MS,\n}: ProductionSupervisorOptions): Promise<ProductionSupervisorResult> {\n return new Promise<ProductionSupervisorResult>((resolve) => {\n // On Windows, we need to be careful with signals - the console sends Ctrl+C\n // to all processes in the group, so we just need to not interfere.\n // `process.execPath`, not \"node\": the bare name needs `node` on PATH, which\n // a systemd unit, a cron job, or a slim container may not provide — and a\n // PATH `node` that *is* present can be a different version than the one\n // running this CLI. execPath is the binary already executing us.\n //\n // The fourth stdio slot opens the IPC channel the child reports readiness\n // on. Without it `process.send` is undefined in the child and we would be\n // back to guessing whether the boot succeeded.\n //\n // stdout/stderr are piped rather than inherited so this supervisor can\n // tell whether the child ever wrote anything, not just forward it blind.\n // `displayProductionStartFailure` used to claim \"the cause is printed\n // above\" on every failed boot, unconditionally — true when the child's\n // logger got far enough to print, false (and misleading) when it died\n // before its log channels were configured. Piping costs nothing here:\n // both streams are re-forwarded to this process's own stdout/stderr as\n // each chunk arrives, so a human watching the terminal sees the exact\n // same live output \"inherit\" gave them.\n const child = spawn(process.execPath, nodeArgs, {\n stdio: [\"inherit\", \"pipe\", \"pipe\", \"ipc\"],\n cwd,\n // The flag identifies us as a parent that speaks the boot protocol. The\n // child stays silent without it, so an app running under pm2 or any other\n // supervisor never writes to a channel that belongs to someone else.\n env: { ...env, [BOOT_SIGNAL_ENV_KEY]: \"1\" },\n // Important: keep child in same process group for proper signal handling\n detached: false,\n });\n\n const startedAt = Date.now();\n let isReady = false;\n let isShuttingDown = false;\n let isSettled = false;\n\n // Whether the child wrote anything to either stream — the only honest\n // basis for telling a developer \"the cause is printed above\". Set from\n // the first chunk on either stream; a child that dies before its first\n // write (a crash mid-import, a logger with no console channel) leaves\n // this `false`, which is exactly the case the summary must admit rather\n // than paper over.\n let sawChildOutput = false;\n\n const forwardChildOutput =\n (target: NodeJS.WritableStream) => (chunk: Buffer) => {\n sawChildOutput = true;\n target.write(chunk);\n };\n\n child.stdout?.on(\"data\", forwardChildOutput(process.stdout));\n child.stderr?.on(\"data\", forwardChildOutput(process.stderr));\n\n const readinessNoticeTimer = setTimeout(() => {\n if (isReady) {\n return;\n }\n\n displayMissingReadinessNotice(Date.now() - startedAt);\n }, readinessNoticeDelayMs);\n\n // A diagnostic timer must never be the reason the CLI stays alive.\n readinessNoticeTimer.unref?.();\n\n const settle = (result: ProductionSupervisorResult) => {\n if (isSettled) {\n return;\n }\n\n isSettled = true;\n clearTimeout(readinessNoticeTimer);\n process.off(\"SIGTERM\", onSigterm);\n process.off(\"SIGINT\", onSigint);\n\n resolve(result);\n };\n\n child.on(\"message\", (message: unknown) => {\n if (isReady || !isBootSignal(message)) {\n return;\n }\n\n isReady = true;\n clearTimeout(readinessNoticeTimer);\n\n displayProductionReadyBanner({ bootDurationMs: message.bootDurationMs }).catch((error) => {\n // The server is up either way — a banner that fails to render must not\n // be reported as, or turn into, a boot failure.\n console.error(error);\n });\n });\n\n // A spawn that never starts (missing binary, EACCES) emits `error` and no\n // `exit`, so without this the command would hang silently on a failure.\n // The error is printed BEFORE the summary that references it — the\n // summary says the cause is \"above\", so it has to already be there.\n child.on(\"error\", (error) => {\n console.error(error);\n displayProductionStartFailure(1, true);\n\n settle({ exitCode: 1, ready: false });\n });\n\n // SIGTERM doesn't auto-propagate like SIGINT does on Windows.\n const onSigterm = () => {\n if (isShuttingDown) {\n return;\n }\n\n isShuttingDown = true;\n child.kill(\"SIGTERM\");\n };\n\n // On Windows Ctrl+C reaches both processes, so the child already has it —\n // we only record that this exit was asked for.\n const onSigint = () => {\n isShuttingDown = true;\n };\n\n process.on(\"SIGTERM\", onSigterm);\n process.on(\"SIGINT\", onSigint);\n\n // `close`, not `exit`: `exit` fires as soon as the OS process ends, which\n // can race ahead of the last chunks still in flight on the piped stdout/\n // stderr streams. `close` waits for those streams to end too, so\n // `sawChildOutput` reflects everything the child actually wrote instead\n // of whatever had been delivered by the time the process happened to die.\n child.on(\"close\", (code) => {\n // A child that dies before reporting readiness never served a request.\n // Exiting 0 there — which a clean `process.exit(0)` in failing app code\n // would do — reports a boot failure as a successful run, so the exit code\n // is forced non-zero to match what actually happened.\n //\n // An operator who interrupts the boot is not a failed boot, so a signalled\n // shutdown keeps the child's own exit code.\n if (!isReady && !isShuttingDown) {\n const exitCode = code === 0 || code === null ? 1 : code;\n\n displayProductionStartFailure(exitCode, sawChildOutput);\n\n return settle({ exitCode, ready: false });\n }\n\n settle({ exitCode: code ?? 0, ready: isReady });\n });\n });\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAa,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;AAuCjD,SAAgB,2BAA2B,EACzC,UACA,MAAM,QAAQ,IAAI,GAClB,MAAM,QAAQ,KACd,yBAAyB,qCAC0C;CACnE,OAAO,IAAI,SAAqC,YAAY;EAqB1D,MAAM,QAAQ,MAAM,QAAQ,UAAU,UAAU;GAC9C,OAAO;IAAC;IAAW;IAAQ;IAAQ;GAAK;GACxC;GAIA,KAAK;IAAE,GAAG;KAAM,sBAAsB;GAAI;GAE1C,UAAU;EACZ,CAAC;EAED,MAAM,YAAY,KAAK,IAAI;EAC3B,IAAI,UAAU;EACd,IAAI,iBAAiB;EACrB,IAAI,YAAY;EAQhB,IAAI,iBAAiB;EAErB,MAAM,sBACH,YAAmC,UAAkB;GACpD,iBAAiB;GACjB,OAAO,MAAM,KAAK;EACpB;EAEF,MAAM,QAAQ,GAAG,QAAQ,mBAAmB,QAAQ,MAAM,CAAC;EAC3D,MAAM,QAAQ,GAAG,QAAQ,mBAAmB,QAAQ,MAAM,CAAC;EAE3D,MAAM,uBAAuB,iBAAiB;GAC5C,IAAI,SACF;GAGF,8BAA8B,KAAK,IAAI,IAAI,SAAS;EACtD,GAAG,sBAAsB;EAGzB,qBAAqB,QAAQ;EAE7B,MAAM,UAAU,WAAuC;GACrD,IAAI,WACF;GAGF,YAAY;GACZ,aAAa,oBAAoB;GACjC,QAAQ,IAAI,WAAW,SAAS;GAChC,QAAQ,IAAI,UAAU,QAAQ;GAE9B,QAAQ,MAAM;EAChB;EAEA,MAAM,GAAG,YAAY,YAAqB;GACxC,IAAI,WAAW,CAAC,aAAa,OAAO,GAClC;GAGF,UAAU;GACV,aAAa,oBAAoB;GAEjC,6BAA6B,EAAE,gBAAgB,QAAQ,eAAe,CAAC,EAAE,OAAO,UAAU;IAGxF,QAAQ,MAAM,KAAK;GACrB,CAAC;EACH,CAAC;EAMD,MAAM,GAAG,UAAU,UAAU;GAC3B,QAAQ,MAAM,KAAK;GACnB,8BAA8B,GAAG,IAAI;GAErC,OAAO;IAAE,UAAU;IAAG,OAAO;GAAM,CAAC;EACtC,CAAC;EAGD,MAAM,kBAAkB;GACtB,IAAI,gBACF;GAGF,iBAAiB;GACjB,MAAM,KAAK,SAAS;EACtB;EAIA,MAAM,iBAAiB;GACrB,iBAAiB;EACnB;EAEA,QAAQ,GAAG,WAAW,SAAS;EAC/B,QAAQ,GAAG,UAAU,QAAQ;EAO7B,MAAM,GAAG,UAAU,SAAS;GAQ1B,IAAI,CAAC,WAAW,CAAC,gBAAgB;IAC/B,MAAM,WAAW,SAAS,KAAK,SAAS,OAAO,IAAI;IAEnD,8BAA8B,UAAU,cAAc;IAEtD,OAAO,OAAO;KAAE;KAAU,OAAO;IAAM,CAAC;GAC1C;GAEA,OAAO;IAAE,UAAU,QAAQ;IAAG,OAAO;GAAQ,CAAC;EAChD,CAAC;CACH,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"production-supervisor.mjs","names":[],"sources":["../../../../../../../core/src/production/production-supervisor.ts"],"sourcesContent":["import { spawn } from \"child_process\";\nimport { BOOT_SIGNAL_ENV_KEY, isBootSignal } from \"../application/boot-signal\";\nimport {\n displayMissingReadinessNotice,\n displayProductionReadyBanner,\n displayProductionStartFailure,\n} from \"../cli/cli-commands.utils\";\n\n/**\n * How long a still-running child may stay silent before we say so.\n *\n * Only reached by a bundle built before readiness reporting existed; a current\n * bundle signals as soon as its late-phase connectors are up.\n */\nexport const DEFAULT_READINESS_NOTICE_DELAY_MS = 10_000;\n\nexport type ProductionSupervisorOptions = {\n /** Arguments handed to the node binary, entry file included. */\n nodeArgs: string[];\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n readinessNoticeDelayMs?: number;\n};\n\nexport type ProductionSupervisorResult = {\n /** What the CLI should exit with — never 0 for a boot that never completed. */\n exitCode: number;\n /** Whether the child ever reported a finished boot. */\n ready: boolean;\n};\n\n/**\n * Run the production bundle in a child process and report honestly on it.\n *\n * The supervisor exists because a parent that only forwards `stdio` cannot\n * see whether its child ever booted — it only sees the process exit. It\n * therefore opens an IPC channel and treats the child's `warlock:ready`\n * signal, emitted by `Application.markBooted`, as the single source of truth\n * for \"started\":\n *\n * 1. The success banner is printed only on that signal.\n * 2. A child that dies before signalling is reported as a failed start and\n * forced to a non-zero exit, even if it exited 0.\n * 3. A child still running without having signalled draws a note on stderr —\n * never stdout, which would be the false-green this whole channel prevents.\n * 4. Whether the child ever wrote to stdout/stderr before dying is tracked\n * (`sawChildOutput`) so the failure summary only claims \"the cause is\n * printed above\" when that is actually true — see the stdio comment\n * below.\n *\n * Resolves rather than exiting so the outcome stays assertable in a test; the\n * `start` command turns the result into the process exit code.\n */\nexport function superviseProductionProcess({\n nodeArgs,\n cwd = process.cwd(),\n env = process.env,\n readinessNoticeDelayMs = DEFAULT_READINESS_NOTICE_DELAY_MS,\n}: ProductionSupervisorOptions): Promise<ProductionSupervisorResult> {\n return new Promise<ProductionSupervisorResult>((resolve) => {\n // On Windows, we need to be careful with signals - the console sends Ctrl+C\n // to all processes in the group, so we just need to not interfere.\n // `process.execPath`, not \"node\": the bare name needs `node` on PATH, which\n // a systemd unit, a cron job, or a slim container may not provide — and a\n // PATH `node` that *is* present can be a different version than the one\n // running this CLI. execPath is the binary already executing us.\n //\n // The fourth stdio slot opens the IPC channel the child reports readiness\n // on. Without it `process.send` is undefined in the child and we would be\n // back to guessing whether the boot succeeded.\n //\n // stdout/stderr are piped rather than inherited so this supervisor can\n // tell whether the child ever wrote anything, not just forward it blind.\n // `displayProductionStartFailure` used to claim \"the cause is printed\n // above\" on every failed boot, unconditionally — true when the child's\n // logger got far enough to print, false (and misleading) when it died\n // before its log channels were configured. Piping costs nothing here:\n // both streams are re-forwarded to this process's own stdout/stderr as\n // each chunk arrives, so a human watching the terminal sees the exact\n // same live output \"inherit\" gave them.\n const child = spawn(process.execPath, nodeArgs, {\n stdio: [\"inherit\", \"pipe\", \"pipe\", \"ipc\"],\n cwd,\n // The flag identifies us as a parent that speaks the boot protocol. The\n // child stays silent without it, so an app running under pm2 or any other\n // supervisor never writes to a channel that belongs to someone else.\n env: { ...env, [BOOT_SIGNAL_ENV_KEY]: \"1\" },\n // Important: keep child in same process group for proper signal handling\n detached: false,\n });\n\n const startedAt = Date.now();\n let isReady = false;\n let isShuttingDown = false;\n let isSettled = false;\n\n // Whether the child wrote anything to either stream — the only honest\n // basis for telling a developer \"the cause is printed above\". Set from\n // the first chunk on either stream; a child that dies before its first\n // write (a crash mid-import, a logger with no console channel) leaves\n // this `false`, which is exactly the case the summary must admit rather\n // than paper over.\n let sawChildOutput = false;\n\n const forwardChildOutput =\n (target: NodeJS.WritableStream) => (chunk: Buffer) => {\n sawChildOutput = true;\n target.write(chunk);\n };\n\n child.stdout?.on(\"data\", forwardChildOutput(process.stdout));\n child.stderr?.on(\"data\", forwardChildOutput(process.stderr));\n\n const readinessNoticeTimer = setTimeout(() => {\n if (isReady) {\n return;\n }\n\n displayMissingReadinessNotice(Date.now() - startedAt);\n }, readinessNoticeDelayMs);\n\n // A diagnostic timer must never be the reason the CLI stays alive.\n readinessNoticeTimer.unref?.();\n\n const settle = (result: ProductionSupervisorResult) => {\n if (isSettled) {\n return;\n }\n\n isSettled = true;\n clearTimeout(readinessNoticeTimer);\n process.off(\"SIGTERM\", onSigterm);\n process.off(\"SIGINT\", onSigint);\n\n resolve(result);\n };\n\n child.on(\"message\", (message: unknown) => {\n if (isReady || !isBootSignal(message)) {\n return;\n }\n\n isReady = true;\n clearTimeout(readinessNoticeTimer);\n\n displayProductionReadyBanner({ bootDurationMs: message.bootDurationMs }).catch((error) => {\n // The server is up either way — a banner that fails to render must not\n // be reported as, or turn into, a boot failure.\n console.error(error);\n });\n });\n\n // A spawn that never starts (missing binary, EACCES) emits `error` and no\n // `exit`, so without this the command would hang silently on a failure.\n // The error is printed BEFORE the summary that references it — the\n // summary says the cause is \"above\", so it has to already be there.\n child.on(\"error\", (error) => {\n console.error(error);\n displayProductionStartFailure(1, true);\n\n settle({ exitCode: 1, ready: false });\n });\n\n // SIGTERM doesn't auto-propagate like SIGINT does on Windows.\n const onSigterm = () => {\n if (isShuttingDown) {\n return;\n }\n\n isShuttingDown = true;\n child.kill(\"SIGTERM\");\n };\n\n // On Windows Ctrl+C reaches both processes, so the child already has it —\n // we only record that this exit was asked for.\n const onSigint = () => {\n isShuttingDown = true;\n };\n\n process.on(\"SIGTERM\", onSigterm);\n process.on(\"SIGINT\", onSigint);\n\n // `close`, not `exit`: `exit` fires as soon as the OS process ends, which\n // can race ahead of the last chunks still in flight on the piped stdout/\n // stderr streams. `close` waits for those streams to end too, so\n // `sawChildOutput` reflects everything the child actually wrote instead\n // of whatever had been delivered by the time the process happened to die.\n child.on(\"close\", (code) => {\n // A child that dies before reporting readiness never served a request.\n // Exiting 0 there — which a clean `process.exit(0)` in failing app code\n // would do — reports a boot failure as a successful run, so the exit code\n // is forced non-zero to match what actually happened.\n //\n // An operator who interrupts the boot is not a failed boot, so a signalled\n // shutdown keeps the child's own exit code.\n if (!isReady && !isShuttingDown) {\n const exitCode = code === 0 || code === null ? 1 : code;\n\n displayProductionStartFailure(exitCode, sawChildOutput);\n\n return settle({ exitCode, ready: false });\n }\n\n settle({ exitCode: code ?? 0, ready: isReady });\n });\n });\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAa,oCAAoC;;;;;;;;;;;;;;;;;;;;;;;AAuCjD,SAAgB,2BAA2B,EACzC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CAAC;EAGD,MAAM,kBAAkB;GACtB,IAAI,gBACF;GAGF,iBAAiB;GACjB,MAAM,KAAK,SAAS;EACtB;EAIA,MAAM,iBAAiB;GACrB,iBAAiB;EACnB;EAEA,QAAQ,GAAG,WAAW,SAAS;EAC/B,QAAQ,GAAG,UAAU,QAAQ;EAO7B,MAAM,GAAG,UAAU,SAAS;GAQ1B,IAAI,CAAC,WAAW,CAAC,gBAAgB;IAC/B,MAAM,WAAW,SAAS,KAAK,SAAS,OAAO,IAAI;IAEnD,8BAA8B,UAAU,cAAc;IAEtD,OAAO,OAAO;KAAE;KAAU,OAAO;IAAM,CAAC;GAC1C;GAEA,OAAO;IAAE,UAAU,QAAQ;IAAG,OAAO;GAAQ,CAAC;EAChD,CAAC;CACH,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"promote-dist.mjs","names":[],"sources":["../../../../../../../core/src/production/promote-dist.ts"],"sourcesContent":["import { directoryExistsAsync, removeDirectoryAsync, renameFileAsync } from \"@warlock.js/fs\";\nimport { randomBytes } from \"crypto\";\nimport path from \"path\";\n\n/**\n * A sibling of `outDir` that esbuild bundles into instead of the real output\n * directory. Same parent folder as `outDir` on purpose — {@link stageDistAsync}\n * moves it into place with a directory rename, and a rename only stays a\n * single atomic filesystem operation when source and destination share a\n * volume.\n *\n * This path is a WRITE TARGET and nothing else. It is never written back into\n * the build config: `options.outdir` names the FINAL destination at all times,\n * because consumers bake it into runtime output (the web contribution derives\n * its `clientDir` from it) and a runtime path pointing at a temp directory\n * that promotion renames away is a broken artifact, not a broken build.\n */\nexport function createTempOutputDir(outDir: string): string {\n const parent = path.dirname(outDir);\n const base = path.basename(outDir);\n const suffix = randomBytes(6).toString(\"hex\");\n\n return path.join(parent, `.${base}.build-${suffix}`);\n}\n\n/**\n * A promotion in flight: the temp build has been renamed onto `outDir`, and\n * the previous `outDir` (when there was one) is parked under `previousDir`\n * until the caller {@link commitDistAsync commits} or\n * {@link rollbackDistAsync rolls back}.\n */\nexport type StagedDist = {\n /** The real output directory (`dist`) the temp build now occupies */\n outDir: string;\n /**\n * The moved-aside previous build, or `undefined` when `outDir` did not\n * exist before staging — the marker for \"a rollback has nothing to restore,\n * it only has to remove what this build put there\".\n */\n previousDir?: string;\n};\n\n/**\n * Move a freshly-built temp directory into place as `outDir`, replacing\n * whatever was there — without ever leaving `outDir` a mix of old and new\n * files, and without discarding the previous build yet.\n *\n * `fs.rename` moves a directory as a single filesystem operation, so each\n * rename below is atomic: `outDir` is observed as either wholly the old\n * build, wholly the new one, or (only for the instant between the two\n * renames below, and only when one previously existed) briefly absent —\n * never a mix of the two.\n *\n * Windows refuses to rename a directory onto a path that already exists, so\n * an existing `outDir` is moved aside first and only deleted by\n * {@link commitDistAsync}, once the build that follows has finished writing\n * into the new one. If the second rename throws — the only realistic way our\n * own code could leave `outDir` missing, as opposed to the process being\n * killed at the exact wrong instant — the old directory is moved straight\n * back before the error propagates, so a failed promotion never costs the\n * previous good build.\n *\n * Staging is deliberately separate from committing. The steps that run\n * between them — connector `emit` hooks, and the build-success marker — need\n * `outDir` to be the REAL path while they run, because what they write bakes\n * that path into the artifact. Renaming first and committing last is what\n * lets them see the final path and still be undone as a unit.\n *\n * @param tempDir the freshly-built directory to promote (removed as a side\n * effect of the rename; the caller does not need to clean it up once this\n * resolves)\n * @param outDir the real output directory (`dist`) to replace\n */\nexport async function stageDistAsync(tempDir: string, outDir: string): Promise<StagedDist> {\n const previousExists = await directoryExistsAsync(outDir);\n\n if (!previousExists) {\n await renameFileAsync(tempDir, outDir);\n\n return { outDir };\n }\n\n const previousDir = `${outDir}.stale-${randomBytes(6).toString(\"hex\")}`;\n\n await renameFileAsync(outDir, previousDir);\n\n try {\n await renameFileAsync(tempDir, outDir);\n } catch (error) {\n await renameFileAsync(previousDir, outDir).catch(() => undefined);\n throw error;\n }\n\n return { outDir, previousDir };\n}\n\n/**\n * Finish a staged promotion: the new `dist` is complete, so the parked\n * previous build is no longer needed.\n *\n * Never throws. It is the last step of a build that has already succeeded,\n * and a leftover `dist.stale-*` directory is untidy, not incorrect — failing\n * the build over it would turn a good artifact into a red run.\n */\nexport async function commitDistAsync(staged: StagedDist): Promise<void> {\n if (!staged.previousDir) return;\n\n await removeDirectoryAsync(staged.previousDir).catch(() => undefined);\n}\n\n/**\n * Undo a staged promotion after a later step failed: put the previous build\n * back where it was, and take the half-finished one out of `dist`.\n *\n * The failed build is renamed aside before the previous one is renamed back,\n * for the same reason {@link stageDistAsync} moves the old directory aside\n * first: a recursive delete of `dist` would leave it observable as a partial\n * tree, while a rename does not.\n *\n * Never throws. It runs inside a `catch`, and the error it is unwinding is\n * the one the developer needs to see — a rollback failure must not replace\n * it. The worst case it can leave behind is a `dist` holding an incomplete\n * build with no build-success marker, which `warlock start` refuses by\n * definition.\n */\nexport async function rollbackDistAsync(staged: StagedDist): Promise<void> {\n const { outDir, previousDir } = staged;\n\n if (!previousDir) {\n await removeDirectoryAsync(outDir).catch(() => undefined);\n\n return;\n }\n\n const discardDir = `${outDir}.failed-${randomBytes(6).toString(\"hex\")}`;\n\n await renameFileAsync(outDir, discardDir).catch(() => undefined);\n await renameFileAsync(previousDir, outDir).catch(() => undefined);\n await removeDirectoryAsync(discardDir).catch(() => undefined);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,oBAAoB,QAAwB;CAC1D,MAAM,SAAS,KAAK,QAAQ,MAAM;CAClC,MAAM,OAAO,KAAK,SAAS,MAAM;CACjC,MAAM,SAAS,YAAY,CAAC,
|
|
1
|
+
{"version":3,"file":"promote-dist.mjs","names":[],"sources":["../../../../../../../core/src/production/promote-dist.ts"],"sourcesContent":["import { directoryExistsAsync, removeDirectoryAsync, renameFileAsync } from \"@warlock.js/fs\";\nimport { randomBytes } from \"crypto\";\nimport path from \"path\";\n\n/**\n * A sibling of `outDir` that esbuild bundles into instead of the real output\n * directory. Same parent folder as `outDir` on purpose — {@link stageDistAsync}\n * moves it into place with a directory rename, and a rename only stays a\n * single atomic filesystem operation when source and destination share a\n * volume.\n *\n * This path is a WRITE TARGET and nothing else. It is never written back into\n * the build config: `options.outdir` names the FINAL destination at all times,\n * because consumers bake it into runtime output (the web contribution derives\n * its `clientDir` from it) and a runtime path pointing at a temp directory\n * that promotion renames away is a broken artifact, not a broken build.\n */\nexport function createTempOutputDir(outDir: string): string {\n const parent = path.dirname(outDir);\n const base = path.basename(outDir);\n const suffix = randomBytes(6).toString(\"hex\");\n\n return path.join(parent, `.${base}.build-${suffix}`);\n}\n\n/**\n * A promotion in flight: the temp build has been renamed onto `outDir`, and\n * the previous `outDir` (when there was one) is parked under `previousDir`\n * until the caller {@link commitDistAsync commits} or\n * {@link rollbackDistAsync rolls back}.\n */\nexport type StagedDist = {\n /** The real output directory (`dist`) the temp build now occupies */\n outDir: string;\n /**\n * The moved-aside previous build, or `undefined` when `outDir` did not\n * exist before staging — the marker for \"a rollback has nothing to restore,\n * it only has to remove what this build put there\".\n */\n previousDir?: string;\n};\n\n/**\n * Move a freshly-built temp directory into place as `outDir`, replacing\n * whatever was there — without ever leaving `outDir` a mix of old and new\n * files, and without discarding the previous build yet.\n *\n * `fs.rename` moves a directory as a single filesystem operation, so each\n * rename below is atomic: `outDir` is observed as either wholly the old\n * build, wholly the new one, or (only for the instant between the two\n * renames below, and only when one previously existed) briefly absent —\n * never a mix of the two.\n *\n * Windows refuses to rename a directory onto a path that already exists, so\n * an existing `outDir` is moved aside first and only deleted by\n * {@link commitDistAsync}, once the build that follows has finished writing\n * into the new one. If the second rename throws — the only realistic way our\n * own code could leave `outDir` missing, as opposed to the process being\n * killed at the exact wrong instant — the old directory is moved straight\n * back before the error propagates, so a failed promotion never costs the\n * previous good build.\n *\n * Staging is deliberately separate from committing. The steps that run\n * between them — connector `emit` hooks, and the build-success marker — need\n * `outDir` to be the REAL path while they run, because what they write bakes\n * that path into the artifact. Renaming first and committing last is what\n * lets them see the final path and still be undone as a unit.\n *\n * @param tempDir the freshly-built directory to promote (removed as a side\n * effect of the rename; the caller does not need to clean it up once this\n * resolves)\n * @param outDir the real output directory (`dist`) to replace\n */\nexport async function stageDistAsync(tempDir: string, outDir: string): Promise<StagedDist> {\n const previousExists = await directoryExistsAsync(outDir);\n\n if (!previousExists) {\n await renameFileAsync(tempDir, outDir);\n\n return { outDir };\n }\n\n const previousDir = `${outDir}.stale-${randomBytes(6).toString(\"hex\")}`;\n\n await renameFileAsync(outDir, previousDir);\n\n try {\n await renameFileAsync(tempDir, outDir);\n } catch (error) {\n await renameFileAsync(previousDir, outDir).catch(() => undefined);\n throw error;\n }\n\n return { outDir, previousDir };\n}\n\n/**\n * Finish a staged promotion: the new `dist` is complete, so the parked\n * previous build is no longer needed.\n *\n * Never throws. It is the last step of a build that has already succeeded,\n * and a leftover `dist.stale-*` directory is untidy, not incorrect — failing\n * the build over it would turn a good artifact into a red run.\n */\nexport async function commitDistAsync(staged: StagedDist): Promise<void> {\n if (!staged.previousDir) return;\n\n await removeDirectoryAsync(staged.previousDir).catch(() => undefined);\n}\n\n/**\n * Undo a staged promotion after a later step failed: put the previous build\n * back where it was, and take the half-finished one out of `dist`.\n *\n * The failed build is renamed aside before the previous one is renamed back,\n * for the same reason {@link stageDistAsync} moves the old directory aside\n * first: a recursive delete of `dist` would leave it observable as a partial\n * tree, while a rename does not.\n *\n * Never throws. It runs inside a `catch`, and the error it is unwinding is\n * the one the developer needs to see — a rollback failure must not replace\n * it. The worst case it can leave behind is a `dist` holding an incomplete\n * build with no build-success marker, which `warlock start` refuses by\n * definition.\n */\nexport async function rollbackDistAsync(staged: StagedDist): Promise<void> {\n const { outDir, previousDir } = staged;\n\n if (!previousDir) {\n await removeDirectoryAsync(outDir).catch(() => undefined);\n\n return;\n }\n\n const discardDir = `${outDir}.failed-${randomBytes(6).toString(\"hex\")}`;\n\n await renameFileAsync(outDir, discardDir).catch(() => undefined);\n await renameFileAsync(previousDir, outDir).catch(() => undefined);\n await removeDirectoryAsync(discardDir).catch(() => undefined);\n}\n"],"mappings":";;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,YAAY,MAAS;AAC9D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-build-config.mjs","names":[],"sources":["../../../../../../../core/src/production/resolve-build-config.ts"],"sourcesContent":["import path from \"path\";\nimport { defaultWarlockConfigurations } from \"../warlock-config/default-configurations\";\nimport { normalizeBuildConfig } from \"../warlock-config/normalize-build-config\";\nimport type { WarlockConfig } from \"../warlock-config/types\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n/**\n * Keys the builder deletes before handing the options to esbuild — ours\n * (`singleBundle`, `esmShim`), which esbuild would reject as unknown, and\n * `banner`, which is re-merged and re-applied after the user spread.\n *\n * They are optional here for a concrete reason: `Required<…>` makes `delete`\n * a type error (TS2790). Naming exactly these three says which keys are\n * removable, rather than casting at each `delete` — a cast there would also\n * hide a genuine mistake.\n *\n * `outFile` and `entryPath` stay REQUIRED even though the builder deletes\n * them too. They are always present after resolution and callers depend on\n * that; widening them to `string | undefined` pushed the lie downstream into\n * `start-production.command.ts`, which then could not trust its own config.\n */\ntype BuilderStrippedKeys = \"singleBundle\" | \"esmShim\" | \"banner\";\n\nexport type ResolvedBuildConfig = Required<\n Omit<NonNullable<WarlockConfig[\"build\"]>, \"outDirectory\" | BuilderStrippedKeys>\n> &\n Partial<Pick<NonNullable<WarlockConfig[\"build\"]>, BuilderStrippedKeys>> & {\n /** Absolute path to the bundled entry file (`{outdir}/{outFile}`) */\n entryPath: string;\n };\n\n/**\n * esbuild options the build config may not carry, and why.\n *\n * Both apply the named compiler options to EVERY file in the bundle, not just\n * the app's own sources — workspace packages compiled under their own tsconfig\n * are silently recompiled under the app's. An app-level\n * `verbatimModuleSyntax: true` reaching package sources that never opted into\n * it strips the imports their decorators rely on, and the build succeeds only\n * to die at import time with `Class extends value undefined`.\n */\nconst FORBIDDEN_BUILD_OPTIONS = {\n tsconfig: \"points esbuild at a tsconfig file\",\n tsconfigRaw: \"inlines compiler options\",\n} as const;\n\n/**\n * Raised when the build config carries an esbuild option the framework owns.\n *\n * The typed config already omits these keys; this catches the forms the type\n * cannot see — an `as any` cast, or a plain `warlock.config.js`. Rejected\n * rather than deleted: dropping the key quietly would leave the author\n * believing a setting applied when it never did.\n */\nexport class ForbiddenBuildOptionError extends Error {\n public constructor(public readonly option: keyof typeof FORBIDDEN_BUILD_OPTIONS) {\n super(\n [\n `build.${option} is not a supported warlock build option.`,\n \"\",\n `Setting it ${FORBIDDEN_BUILD_OPTIONS[option]} for every file in the bundle,`,\n \"including workspace packages that were compiled under their own tsconfig.\",\n \"Options such as `verbatimModuleSyntax` then apply to sources that never\",\n \"opted into them, and the build succeeds but crashes at import time with\",\n \"`Class extends value undefined`.\",\n \"\",\n `Remove \\`${option}\\` from the \\`build\\` block of your warlock config. The builder`,\n \"already reads the app's tsconfig for the parts it needs (path aliases); to\",\n \"change how your own sources compile, edit that tsconfig.json instead.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"ForbiddenBuildOptionError\";\n }\n}\n\n/**\n * Resolve the build config with framework defaults applied.\n *\n * Both the production builder and `warlock start` call this so they\n * agree on where the bundle lives — previously each had its own local\n * fallbacks and they drifted (`.warlock/production` vs `dist`),\n * letting `build` and `start` look at different paths.\n */\nexport function resolveBuildConfig(): ResolvedBuildConfig {\n // Normalised here rather than only in `defineConfig` because a project may\n // export a plain config object that never went through it.\n const userBuild = normalizeBuildConfig(warlockConfigManager.get(\"build\") ?? {});\n\n // Before the merge, so the option cannot reach the esbuild spread in\n // production-builder — which overrides framework defaults with user config.\n for (const option of Object.keys(FORBIDDEN_BUILD_OPTIONS) as Array<\n keyof typeof FORBIDDEN_BUILD_OPTIONS\n >) {\n if (option in userBuild) {\n throw new ForbiddenBuildOptionError(option);\n }\n }\n\n const defaults = defaultWarlockConfigurations.build!;\n const merged = { ...defaults, ...userBuild } as ResolvedBuildConfig;\n\n return {\n ...merged,\n entryPath: path.resolve(merged.outdir, merged.outFile),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,MAAM,0BAA0B;CAC9B,UAAU;CACV,aAAa;AACf;;;;;;;;;AAUA,IAAa,4BAAb,cAA+C,MAAM;CACnD,AAAO,YAAY,AAAgB,QAA8C;EAC/E,MACE;GACE,SAAS,OAAO;GAChB;GACA,cAAc,wBAAwB,QAAQ;GAC9C;GACA;GACA;GACA;GACA;GACA,YAAY,OAAO;GACnB;GACA;EACF,
|
|
1
|
+
{"version":3,"file":"resolve-build-config.mjs","names":[],"sources":["../../../../../../../core/src/production/resolve-build-config.ts"],"sourcesContent":["import path from \"path\";\nimport { defaultWarlockConfigurations } from \"../warlock-config/default-configurations\";\nimport { normalizeBuildConfig } from \"../warlock-config/normalize-build-config\";\nimport type { WarlockConfig } from \"../warlock-config/types\";\nimport { warlockConfigManager } from \"../warlock-config/warlock-config.manager\";\n\n/**\n * Keys the builder deletes before handing the options to esbuild — ours\n * (`singleBundle`, `esmShim`), which esbuild would reject as unknown, and\n * `banner`, which is re-merged and re-applied after the user spread.\n *\n * They are optional here for a concrete reason: `Required<…>` makes `delete`\n * a type error (TS2790). Naming exactly these three says which keys are\n * removable, rather than casting at each `delete` — a cast there would also\n * hide a genuine mistake.\n *\n * `outFile` and `entryPath` stay REQUIRED even though the builder deletes\n * them too. They are always present after resolution and callers depend on\n * that; widening them to `string | undefined` pushed the lie downstream into\n * `start-production.command.ts`, which then could not trust its own config.\n */\ntype BuilderStrippedKeys = \"singleBundle\" | \"esmShim\" | \"banner\";\n\nexport type ResolvedBuildConfig = Required<\n Omit<NonNullable<WarlockConfig[\"build\"]>, \"outDirectory\" | BuilderStrippedKeys>\n> &\n Partial<Pick<NonNullable<WarlockConfig[\"build\"]>, BuilderStrippedKeys>> & {\n /** Absolute path to the bundled entry file (`{outdir}/{outFile}`) */\n entryPath: string;\n };\n\n/**\n * esbuild options the build config may not carry, and why.\n *\n * Both apply the named compiler options to EVERY file in the bundle, not just\n * the app's own sources — workspace packages compiled under their own tsconfig\n * are silently recompiled under the app's. An app-level\n * `verbatimModuleSyntax: true` reaching package sources that never opted into\n * it strips the imports their decorators rely on, and the build succeeds only\n * to die at import time with `Class extends value undefined`.\n */\nconst FORBIDDEN_BUILD_OPTIONS = {\n tsconfig: \"points esbuild at a tsconfig file\",\n tsconfigRaw: \"inlines compiler options\",\n} as const;\n\n/**\n * Raised when the build config carries an esbuild option the framework owns.\n *\n * The typed config already omits these keys; this catches the forms the type\n * cannot see — an `as any` cast, or a plain `warlock.config.js`. Rejected\n * rather than deleted: dropping the key quietly would leave the author\n * believing a setting applied when it never did.\n */\nexport class ForbiddenBuildOptionError extends Error {\n public constructor(public readonly option: keyof typeof FORBIDDEN_BUILD_OPTIONS) {\n super(\n [\n `build.${option} is not a supported warlock build option.`,\n \"\",\n `Setting it ${FORBIDDEN_BUILD_OPTIONS[option]} for every file in the bundle,`,\n \"including workspace packages that were compiled under their own tsconfig.\",\n \"Options such as `verbatimModuleSyntax` then apply to sources that never\",\n \"opted into them, and the build succeeds but crashes at import time with\",\n \"`Class extends value undefined`.\",\n \"\",\n `Remove \\`${option}\\` from the \\`build\\` block of your warlock config. The builder`,\n \"already reads the app's tsconfig for the parts it needs (path aliases); to\",\n \"change how your own sources compile, edit that tsconfig.json instead.\",\n ].join(\"\\n\"),\n );\n\n this.name = \"ForbiddenBuildOptionError\";\n }\n}\n\n/**\n * Resolve the build config with framework defaults applied.\n *\n * Both the production builder and `warlock start` call this so they\n * agree on where the bundle lives — previously each had its own local\n * fallbacks and they drifted (`.warlock/production` vs `dist`),\n * letting `build` and `start` look at different paths.\n */\nexport function resolveBuildConfig(): ResolvedBuildConfig {\n // Normalised here rather than only in `defineConfig` because a project may\n // export a plain config object that never went through it.\n const userBuild = normalizeBuildConfig(warlockConfigManager.get(\"build\") ?? {});\n\n // Before the merge, so the option cannot reach the esbuild spread in\n // production-builder — which overrides framework defaults with user config.\n for (const option of Object.keys(FORBIDDEN_BUILD_OPTIONS) as Array<\n keyof typeof FORBIDDEN_BUILD_OPTIONS\n >) {\n if (option in userBuild) {\n throw new ForbiddenBuildOptionError(option);\n }\n }\n\n const defaults = defaultWarlockConfigurations.build!;\n const merged = { ...defaults, ...userBuild } as ResolvedBuildConfig;\n\n return {\n ...merged,\n entryPath: path.resolve(merged.outdir, merged.outFile),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,MAAM,0BAA0B;CAC9B,UAAU;CACV,aAAa;AACf;;;;;;;;;AAUA,IAAa,4BAAb,cAA+C,MAAM;CACnD,AAAO,YAAY,AAAgB,QAA8C;EAC/E,MACE;GACE,SAAS,OAAO;GAChB;GACA,cAAc,wBAAwB,QAAQ;GAC9C;GACA;GACA;GACA;GACA;GACA,YAAY,OAAO;GACnB;GACA;EACF,CAAC,CAAC,KAAK,IAAI,CACb;EAfiC;EAiBjC,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,SAAgB,qBAA0C;CAGxD,MAAM,YAAY,qBAAqB,qBAAqB,IAAI,OAAO,KAAK,CAAC,CAAC;CAI9E,KAAK,MAAM,UAAU,OAAO,KAAK,uBAAuB,GAGtD,IAAI,UAAU,WACZ,MAAM,IAAI,0BAA0B,MAAM;CAK9C,MAAM,SAAS;EAAE,GADA,6BAA6B;EAChB,GAAG;CAAU;CAE3C,OAAO;EACL,GAAG;EACH,WAAW,KAAK,QAAQ,OAAO,QAAQ,OAAO,OAAO;CACvD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cascade-adapter.d.mts","names":[],"sources":["../../../../../../../../../core/src/repositories/adapters/cascade/cascade-adapter.ts"],"mappings":";;;;;;;;;;;AAiBA;cAAa,cAAA,WAAyB,KAAA,kBAAuB,yBAAA,CAA0B,CAAA;EAAA,QAK1D,KAAA;EALS;;;;cAKT,KAAA,EAAO,UAAA,CAAW,CAAA;EAS7B;;;EAAT,KAAA,
|
|
1
|
+
{"version":3,"file":"cascade-adapter.d.mts","names":[],"sources":["../../../../../../../../../core/src/repositories/adapters/cascade/cascade-adapter.ts"],"mappings":";;;;;;;;;;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