better-ship 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/{application-Dg1jIKPe.js → application-D5tNECiC.js} +2 -2
  2. package/dist/application-D5tNECiC.js.map +1 -0
  3. package/dist/application.d.ts +2 -2
  4. package/dist/application.js +1 -1
  5. package/dist/better-auth/apple-client-secret.js +1 -1
  6. package/dist/better-auth/auth-client.js +1 -1
  7. package/dist/better-auth/rate-limit.js +1 -1
  8. package/dist/better-auth.js +1 -1
  9. package/dist/billing/client.js +1 -1
  10. package/dist/cloudflare/auth-secondary-storage.js +1 -1
  11. package/dist/cloudflare/durable-object-client.js +1 -1
  12. package/dist/cloudflare/durable-object-errors.js +1 -1
  13. package/dist/cloudflare/kv-client.js +1 -1
  14. package/dist/cloudflare/kv-errors.js +1 -1
  15. package/dist/cloudflare/queue.d.ts +1 -1
  16. package/dist/cloudflare/queue.js +2 -2
  17. package/dist/cloudflare/r2-client.js +1 -1
  18. package/dist/cloudflare/r2-errors.js +1 -1
  19. package/dist/cloudflare/scheduled.js +1 -1
  20. package/dist/cloudflare.d.ts +2 -2
  21. package/dist/cloudflare.js +3 -3
  22. package/dist/{core-BT1dSEQI.js → core-BIas38R0.js} +2 -2
  23. package/dist/core-BIas38R0.js.map +1 -0
  24. package/dist/core.js +1 -1
  25. package/dist/http.js +2 -2
  26. package/dist/{index-CYHXOH08.d.ts → index-tNZHSCpJ.d.ts} +6 -2
  27. package/dist/index-tNZHSCpJ.d.ts.map +1 -0
  28. package/dist/{outbox-repository-options-B8TnAE1h.js → outbox-repository-options-D0R8z1yS.js} +2 -2
  29. package/dist/{outbox-repository-options-B8TnAE1h.js.map → outbox-repository-options-D0R8z1yS.js.map} +1 -1
  30. package/dist/{outbox-repository-options-DjBgFhMi.d.ts → outbox-repository-options-_B8l8l6l.d.ts} +2 -2
  31. package/dist/{outbox-repository-options-DjBgFhMi.d.ts.map → outbox-repository-options-_B8l8l6l.d.ts.map} +1 -1
  32. package/dist/postgres.d.ts +2 -2
  33. package/dist/postgres.js +3 -3
  34. package/dist/posthog/metrics.d.ts +1 -1
  35. package/dist/posthog/server.d.ts +1 -1
  36. package/dist/posthog/server.js +1 -1
  37. package/dist/resend.d.ts +14 -16
  38. package/dist/resend.d.ts.map +1 -1
  39. package/dist/resend.js +42 -19
  40. package/dist/resend.js.map +1 -1
  41. package/dist/sentry/client.js +1 -1
  42. package/dist/sentry/server.d.ts +1 -1
  43. package/dist/stripe/client.d.ts +13 -0
  44. package/dist/stripe/client.d.ts.map +1 -0
  45. package/dist/stripe/client.js +20 -0
  46. package/dist/stripe/client.js.map +1 -0
  47. package/dist/stripe/event-map.d.ts +14 -0
  48. package/dist/stripe/event-map.d.ts.map +1 -0
  49. package/dist/stripe/event-map.js +19 -0
  50. package/dist/stripe/event-map.js.map +1 -0
  51. package/dist/stripe/payment-service.d.ts +4 -5
  52. package/dist/stripe/payment-service.d.ts.map +1 -1
  53. package/dist/stripe/payment-service.error.js +2 -2
  54. package/dist/stripe/payment-service.error.js.map +1 -1
  55. package/dist/stripe/payment-service.js +11 -35
  56. package/dist/stripe/payment-service.js.map +1 -1
  57. package/dist/stripe/payment-webhook.js +1 -1
  58. package/dist/stripe/request.d.ts +9 -0
  59. package/dist/stripe/request.d.ts.map +1 -0
  60. package/dist/stripe/request.js +21 -0
  61. package/dist/stripe/request.js.map +1 -0
  62. package/dist/tanstack.js +1 -1
  63. package/dist/testing/outbox-repository.d.ts +1 -1
  64. package/dist/testing/payment-service.d.ts.map +1 -1
  65. package/dist/testing/payment-service.js +12 -12
  66. package/dist/testing/payment-service.js.map +1 -1
  67. package/dist/testing/stripe.d.ts +21 -0
  68. package/dist/testing/stripe.d.ts.map +1 -0
  69. package/dist/testing/stripe.js +33 -0
  70. package/dist/testing/stripe.js.map +1 -0
  71. package/dist/{webhook-verification-qSFXv5H3.js → webhook-verification-CEUARY9X.js} +2 -2
  72. package/dist/{webhook-verification-qSFXv5H3.js.map → webhook-verification-CEUARY9X.js.map} +1 -1
  73. package/package.json +5 -1
  74. package/src/application/email-service.ts +3 -0
  75. package/src/application/index.ts +1 -0
  76. package/src/core/email-service.error.ts +1 -1
  77. package/src/infrastructure/resend/email-event.ts +3 -0
  78. package/src/infrastructure/resend/index.ts +2 -2
  79. package/src/infrastructure/resend/resend-email-service.ts +39 -17
  80. package/src/infrastructure/resend/resend-webhook.ts +15 -16
  81. package/src/infrastructure/stripe/client.ts +16 -0
  82. package/src/infrastructure/stripe/event-map.ts +25 -0
  83. package/src/infrastructure/stripe/payment-service.error.ts +2 -1
  84. package/src/infrastructure/stripe/payment-service.ts +15 -39
  85. package/src/infrastructure/stripe/request.ts +17 -0
  86. package/src/infrastructure/testing/payment-service-contract.ts +11 -14
  87. package/src/infrastructure/testing/stripe-fixture.ts +42 -0
  88. package/dist/application-Dg1jIKPe.js.map +0 -1
  89. package/dist/core-BT1dSEQI.js.map +0 -1
  90. package/dist/index-CYHXOH08.d.ts.map +0 -1
@@ -1,4 +1,4 @@
1
- import { D as unreachable, O as DatabaseError, d as classifyFailure, nt as AppError, r as createLogger } from "./core-BT1dSEQI.js";
1
+ import { D as unreachable, O as DatabaseError, d as classifyFailure, nt as AppError, r as createLogger } from "./core-BIas38R0.js";
2
2
  import { panic } from "better-result";
3
3
 
4
4
  //#region src/application/analytics-service.ts
@@ -286,4 +286,4 @@ var UnitOfWorkAlreadyActiveError = class extends AppError {
286
286
 
287
287
  //#endregion
288
288
  export { MessageBus as a, RecordingEmailService as c, OutboxRelay as i, NULL_METRICS_SERVICE as l, UnitOfWork as n, MessageAlreadyProcessedError as o, OutboxRetention as r, recordEmailEvent as s, UnitOfWorkAlreadyActiveError as t, NULL_ANALYTICS as u };
289
- //# sourceMappingURL=application-Dg1jIKPe.js.map
289
+ //# sourceMappingURL=application-D5tNECiC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"application-D5tNECiC.js","names":["logger"],"sources":["../src/application/analytics-service.ts","../src/application/metrics-service.ts","../src/application/email-service.ts","../src/application/record-email-event.ts","../src/application/message-already-processed.error.ts","../src/application/message-bus.ts","../src/application/outbox-relay.ts","../src/application/outbox-retention.ts","../src/application/unit-of-work.ts","../src/application/unit-of-work.errors.ts"],"sourcesContent":["import type { AnalyticsEventIdentity, AnalyticsEventInput, AnalyticsProperties } from '@/core'\n\n/** Product analytics without an SDK dependency, ported from Typist and Porte. */\nexport interface AnalyticsService<TEvent extends AnalyticsEventInput = AnalyticsEventInput> {\n /** Attach traits to one person. */\n identify(distinctId: string, properties?: AnalyticsProperties): void\n /** Merge a previous ID into this person; the application must establish that both identify the same person. */\n alias(distinctId: string, previousDistinctId: string): void\n /** Schedule an event for a person; returning does not confirm remote acceptance. */\n track(event: TEvent, distinctId: string, identity?: AnalyticsEventIdentity): void\n /** Schedule an event without creating a person profile for its distinct ID. */\n trackAnonymous(event: TEvent, distinctId: string, identity?: AnalyticsEventIdentity): void\n}\n\n/** Reports to nobody. The composition root selects this service when analytics is disabled. */\nexport const NULL_ANALYTICS: AnalyticsService = {\n identify: () => {},\n alias: () => {},\n track: () => {},\n trackAnonymous: () => {},\n}\n","/** A metric dimension; use a small, bounded value set and never user or request IDs. */\nexport type MetricAttributeValue = string | number | boolean\n\n/** Dimensions shared by observations in one time series. */\nexport type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>\n\n/** Unit and dimensions for an operational measurement. */\nexport interface MetricOptions {\n readonly attributes?: MetricAttributes\n readonly unit?: string\n}\n\n/** Operational measurements, ported from Typist's metrics-service.ts; applications own metric names. */\nexport interface MetricsService<TName extends string = string> {\n /** Add a nonnegative value to a total; the default increment is one. */\n count(name: TName, value?: number, options?: MetricOptions): void\n /** Record a current value. */\n gauge(name: TName, value: number, options?: MetricOptions): void\n /** Record one observation in a distribution. */\n histogram(name: TName, value: number, options?: MetricOptions): void\n}\n\n/** Records nothing when the composition root disables metrics. */\nexport const NULL_METRICS_SERVICE: MetricsService = {\n count: () => {},\n gauge: () => {},\n histogram: () => {},\n}\n","import type { EmailIdempotencyKey } from '@/core'\n\n/** A media type such as `application/pdf`. */\nexport type MimeType = `${string}/${string}`\n\n/** A file to attach. Binary content is bytes; the adapter encodes it for the provider. */\nexport type EmailAttachment = {\n readonly filename: string\n readonly content: string | Uint8Array\n /** Optional MIME metadata; Resend accepts filename and content without it. */\n readonly contentType?: MimeType\n}\n\n/**\n * One transactional email. Resend accepts 50 recipients, 75 tags with ASCII names and values,\n * and 40 MB of attachments after base64. Sources: https://resend.com/docs/api-reference/emails/send-email\n * and https://resend.com/docs/dashboard/emails/tags\n */\nexport type OutboundEmail = {\n /** Override the default for this email, for example \"Display Name <address@domain.com>\". */\n readonly from?: string\n readonly to: string | readonly string[]\n readonly subject: string\n readonly html: string\n /** Optional stable identity of this send. Resend deduplicates supplied keys for 24 hours. */\n readonly idempotencyKey?: EmailIdempotencyKey\n /** Resend generates plain text from html when omitted. An empty string disables that generation. */\n readonly text?: string\n readonly replyTo?: string\n /** Labels the provider stores with the email and returns on every delivery event. */\n readonly tags?: Readonly<Record<string, string>>\n readonly attachments?: readonly EmailAttachment[]\n}\n\n/** Received email headers, without the body or attachments. */\nexport type ReceivedEmail = { readonly headers: Readonly<Record<string, string>> }\n\n/** The provider accepted the email and assigned its id. */\nexport type EmailAccepted = { readonly providerId: string }\n\n/**\n * The adapter supplies the default sender and maps provider errors. Each email can override the sender.\n * A provider rejection throws `EmailServiceError`; unexpected SDK rejections propagate unchanged.\n */\nexport interface IEmailService {\n /** Resolve after provider acceptance; this does not confirm delivery to the recipient. */\n sendEmail(email: OutboundEmail): Promise<EmailAccepted>\n}\n\n/** Records every send for a test. Provider ids count up as `recorded-1`, `recorded-2`. */\nexport class RecordingEmailService implements IEmailService {\n /** Sends in call order, including repeated idempotency keys. */\n readonly sent: OutboundEmail[] = []\n\n /** Record the send before returning its provider id. */\n async sendEmail(email: OutboundEmail): Promise<EmailAccepted> {\n this.sent.push(email)\n return { providerId: `recorded-${this.sent.length}` }\n }\n}\n","import type { BounceType, DomainCommand, EmailAddress, RecordEmailEventPayload } from '@/core'\n\nimport type { IUnitOfWork } from './unit-of-work.ts'\n\n/** What a bounce records for one address. */\nexport type EmailBounceRecord = {\n readonly type: BounceType\n readonly subType: string | null\n}\n\n/**\n * The application's deliverability state per address. An implementation keeps the higher bounce\n * severity with `shouldUpdateBounce`, and treats an unknown address as nothing to record.\n */\nexport interface IEmailDeliverabilityStore {\n /** Keep the higher severity atomically. Equal severity permits replacement; the store owns timestamp ordering. */\n recordBounce(address: EmailAddress, bounce: EmailBounceRecord): Promise<void>\n /** Record a complaint without clearing existing suppression state. */\n recordComplaint(address: EmailAddress): Promise<void>\n}\n\n/** The repositories the handler needs from the unit of work. */\nexport type RecordEmailEventRepos = { readonly emailDeliverability: IEmailDeliverabilityStore }\n\n/** The container slice the handler reads. */\nexport type RecordEmailEventDeps = { readonly uow: IUnitOfWork<RecordEmailEventRepos> }\n\n/** The command, under whatever name the application registered the payload. */\nexport type RecordEmailEventCommand = DomainCommand & RecordEmailEventPayload\n\n/**\n * Record a bounce or a complaint for every recipient inside the command's unit of work.\n * The command id is the provider's event id, so a redelivered webhook is `MessageAlreadyProcessedError`.\n */\nexport async function recordEmailEvent(\n command: RecordEmailEventCommand,\n deps: RecordEmailEventDeps,\n): Promise<void> {\n await deps.uow.run(command.id, async ({ emailDeliverability }) => {\n for (const address of command.recipients) {\n if (command.event.type === 'bounced') {\n // oxlint-disable-next-line no-await-in-loop -- Finish each transaction write before starting another; a failure must leave no pending writes.\n await emailDeliverability.recordBounce(address, {\n type: command.event.bounceType,\n subType: command.event.bounceSubType,\n })\n } else {\n // oxlint-disable-next-line no-await-in-loop -- A rejected write must stop the transaction before another write starts.\n await emailDeliverability.recordComplaint(address)\n }\n }\n })\n}\n","import { AppError, DatabaseError, type MessageId } from '@/core'\n\n/** The message's effects already committed. A caller can skip duplicate delivery without repeating those effects. */\nexport class MessageAlreadyProcessedError extends AppError {\n readonly _tag = 'MessageAlreadyProcessedError'\n readonly classification = 'terminal'\n\n constructor(\n readonly messageId: MessageId,\n options?: { readonly cause: unknown },\n ) {\n super(`message ${messageId} already processed`, options)\n }\n\n /** Recognize only the processed-message primary key; preserve other failures unchanged at the call site. */\n static from(cause: unknown, messageId: MessageId): MessageAlreadyProcessedError | undefined {\n if (cause instanceof MessageAlreadyProcessedError) return cause\n if (!(cause instanceof DatabaseError)) return undefined\n const details = cause.details\n const duplicate =\n details.database === 'd1'\n ? details.kind === 'unique' &&\n details.table === 'processed_messages' &&\n details.column === 'message_id'\n : details.code === '23505' &&\n details.table_name === 'processed_messages' &&\n details.constraint_name === 'processed_messages_pkey'\n if (!duplicate) return undefined\n return new MessageAlreadyProcessedError(messageId, { cause })\n }\n}\n","import { panic } from 'better-result'\n\nimport {\n createLogger,\n unreachable,\n type DomainCommand,\n type DomainEvent,\n type DomainMessage,\n type DomainQuery,\n} from '@/core'\n\nimport { MessageAlreadyProcessedError } from './message-already-processed.error.ts'\nimport type { Handlers, MessageResult, RegistryMessage } from './registry.ts'\n\nconst logger = createLogger('message-bus')\n\n/** The port an entrypoint dispatches through. `AppDeps` names this as `IMessageBus<typeof registry>`. */\nexport interface IMessageBus<TRegistry extends Handlers<never>> {\n handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(\n message: TMessage,\n ): Promise<MessageResult<TMessage, TRegistry>>\n}\n\n/**\n * Routes one message to its slot. The bus opens no transaction and keeps no outbox:\n * a handler that writes opens the unit of work itself.\n */\nexport class MessageBus<Deps, TRegistry extends Handlers<Deps>> implements IMessageBus<TRegistry> {\n constructor(\n private readonly deps: Deps,\n private readonly registry: TRegistry,\n ) {}\n\n /** Resolves to the handler's own value for a command or query, and to void for an event. */\n async handle<TMessage extends DomainMessage & RegistryMessage<TRegistry>>(\n message: TMessage,\n ): Promise<MessageResult<TMessage, TRegistry>> {\n // SAFETY: the slot for this name is what `MessageResult` names, and dispatch returns its value.\n return (await this.dispatch(message)) as MessageResult<TMessage, TRegistry>\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- one table holds every slot's value; `handle` names it.\n private dispatch(message: DomainMessage): Promise<unknown> {\n if (message.type === 'command') return this.handleCommand(message)\n if (message.type === 'query') return this.handleQuery(message)\n if (message.type === 'event') return this.handleEvent(message)\n // A message parsed at a boundary cannot reach here; one that does must not resolve silently.\n return unreachable(message)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- see dispatch.\n private handleCommand(command: DomainCommand): Promise<unknown> {\n // `satisfies` proved the registry complete, so a missing slot is a broken registry object.\n const handler = this.registry.commands[command.name]\n if (handler === undefined) return panic(`No handler for command ${command.name}`)\n logger.debug('handling_command', { name: command.name, id: command.id })\n return handler(command, this.deps)\n }\n\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- see dispatch.\n private handleQuery(query: DomainQuery): Promise<unknown> {\n const handler = this.registry.queries[query.name]\n if (handler === undefined) return panic(`No handler for query ${query.name}`)\n return handler(query, this.deps)\n }\n\n /**\n * Every subscriber runs to completion. One failure is rethrown as is. Several are thrown as\n * one `AggregateError`. A `MessageAlreadyProcessedError` means that subscriber already committed on\n * an earlier delivery, so it counts as delivered.\n */\n private async handleEvent(event: DomainEvent): Promise<void> {\n const subscriptions = this.registry.events[event.name] ?? []\n const outcomes = await Promise.allSettled(\n subscriptions.map((subscription) => subscription(event, this.deps)),\n )\n const failures: unknown[] = []\n for (const [subscriber, outcome] of outcomes.entries()) {\n if (outcome.status === 'fulfilled') continue\n if (outcome.reason instanceof MessageAlreadyProcessedError) {\n // The bus swallows this error, so this line is the only record that the skip happened.\n logger.info('duplicate_subscriber_ignored', { event: event.name, id: event.id, subscriber })\n continue\n }\n failures.push(outcome.reason)\n }\n if (failures.length === 1) throw failures[0]\n if (failures.length > 1) {\n throw new AggregateError(failures, `${event.name}: ${failures.length} subscribers failed`)\n }\n }\n}\n","import { classifyFailure, createLogger, type DomainEvent } from '@/core'\n\nimport type {\n DeadLetterReason,\n IOutboxRepository,\n OutboxClaim,\n OutboxMessage,\n} from './outbox-repository.ts'\n\n/**\n * Delivers committed outbox rows. The unit of work only wakes it after a commit that wrote\n * events; the app decides what a wake is: `waitUntil`, a Durable Object alarm, nothing.\n * The sweep is the source of truth, so a lost wake loses no events.\n */\nexport interface IOutboxRelay {\n wake(): void\n}\n\n/** The publisher sends valid events and returns oversized events. QueueClient satisfies this port directly. */\nexport interface IOutboxPublisher {\n /** Resolves after queue acceptance; a rejected batch may already have sent some events. */\n sendBatchPartial(messages: ReadonlyArray<DomainEvent>): Promise<ReadonlyArray<DomainEvent>>\n}\n\n/** Optional limits for one relay; durable attempts exclude the publisher's immediate retries. */\nexport type OutboxRelayOptions = {\n readonly batchSize?: number\n readonly maxBatches?: number\n readonly maxAttempts?: number\n}\n\nconst logger = createLogger('outbox-relay')\n\n/**\n * Publishes committed events with bounded durable retries. Ported from Typist's relay with per-row exhaustion.\n * Send failures are recorded; repository failures propagate to the wake or scheduled boundary.\n */\nexport class OutboxRelay {\n private readonly options: Required<OutboxRelayOptions>\n\n constructor(\n private readonly publisher: IOutboxPublisher,\n private readonly repository: IOutboxRepository,\n options: OutboxRelayOptions = {},\n ) {\n this.options = {\n batchSize: options.batchSize ?? 50,\n maxBatches: options.maxBatches ?? 10,\n maxAttempts: options.maxAttempts ?? 10,\n }\n }\n\n /** Return the claimed count, including released and dead-lettered rows. Zero means no due rows. */\n async flush(): Promise<number> {\n const claim = await this.repository.claimPending(this.options.batchSize)\n const exhausted = claim.messages.filter((row) => row.attempts > this.options.maxAttempts)\n await this.deadLetter(claim, exhausted, 'exhausted', 'Claim attempt limit exceeded')\n const pending = claim.messages.filter((row) => row.attempts <= this.options.maxAttempts)\n if (pending.length === 0) return claim.messages.length\n\n let oversized: ReadonlyArray<DomainEvent>\n try {\n oversized = await this.publisher.sendBatchPartial(pending.map((row) => row.payload))\n } catch (error) {\n await this.handleSendFailure(claim, pending, error)\n return claim.messages.length\n }\n\n const oversizedIds = new Set(oversized.map((event) => event.id))\n await this.deadLetter(\n claim,\n pending.filter((row) => oversizedIds.has(row.payload.id)),\n 'oversized',\n 'Exceeds queue message size limit',\n )\n const sent = pending.filter((row) => !oversizedIds.has(row.payload.id))\n if (sent.length > 0) await this.repository.markPublished(claim, sent)\n return claim.messages.length\n }\n\n /** Drain until an empty claim or the batch limit; return the total claimed count. */\n async drain(): Promise<number> {\n let total = 0\n for (let batch = 0; batch < this.options.maxBatches; batch += 1) {\n // oxlint-disable-next-line no-await-in-loop -- An empty claim must stop the drain before another claim starts.\n const claimed = await this.flush()\n total += claimed\n if (claimed === 0) break\n }\n return total\n }\n\n private async handleSendFailure(\n claim: OutboxClaim,\n pending: ReadonlyArray<OutboxMessage>,\n cause: unknown,\n ): Promise<void> {\n const classification = classifyFailure(cause)\n const message =\n cause instanceof Error ? cause.message : 'Publisher rejected with a non-error value'\n if (classification === 'terminal') {\n await this.deadLetter(claim, pending, 'terminal', message, cause)\n return\n }\n const exhausted = pending.filter((row) => row.attempts >= this.options.maxAttempts)\n await this.deadLetter(claim, exhausted, 'exhausted', message, cause)\n const retry = pending.filter((row) => row.attempts < this.options.maxAttempts)\n if (retry.length > 0) await this.repository.releaseClaim(claim, retry)\n }\n\n private async deadLetter(\n claim: OutboxClaim,\n messages: ReadonlyArray<OutboxMessage>,\n reason: DeadLetterReason,\n errorMessage: string,\n cause?: unknown,\n ): Promise<void> {\n if (messages.length === 0) return\n await this.repository.deadLetter(claim, messages, reason, errorMessage)\n logger.error('outbox_messages_dead_lettered', {\n error: cause,\n claimToken: claim.token,\n count: messages.length,\n reason,\n })\n }\n}\n","import type { IOutboxRetentionRepository } from './outbox-repository.ts'\n\n/** Typist's retention defaults; receipt retention must cover the application's supported replay period. */\nexport type OutboxRetentionOptions = {\n readonly publishedRetentionMs?: number\n readonly failedRetentionMs?: number\n readonly receiptRetentionMs?: number\n readonly batchSize?: number\n readonly maxBatches?: number\n}\n\n/** Deleted records per category during one bounded sweep. */\nexport type OutboxRetentionResult = {\n readonly published: number\n readonly failed: number\n readonly receipts: number\n}\n\n/** Bounded cleanup ported from Typist's message retention handler. The application schedules each sweep. */\nexport class OutboxRetention {\n private readonly options: Required<OutboxRetentionOptions>\n\n constructor(\n private readonly repository: IOutboxRetentionRepository,\n options: OutboxRetentionOptions = {},\n ) {\n this.options = {\n publishedRetentionMs: options.publishedRetentionMs ?? 86_400_000,\n failedRetentionMs: options.failedRetentionMs ?? 30 * 86_400_000,\n receiptRetentionMs: options.receiptRetentionMs ?? 7 * 86_400_000,\n batchSize: options.batchSize ?? 1_000,\n maxBatches: options.maxBatches ?? 10,\n }\n }\n\n /** Calculate all cutoffs from one supplied time; propagate repository failures to the calling boundary. */\n async sweep(at: Date): Promise<OutboxRetentionResult> {\n const { publishedRetentionMs, failedRetentionMs, receiptRetentionMs } = this.options\n const published = await this.deleteBatches((size) =>\n this.repository.deletePublishedBefore(new Date(at.getTime() - publishedRetentionMs), size),\n )\n const failed = await this.deleteBatches((size) =>\n this.repository.deleteFailedBefore(new Date(at.getTime() - failedRetentionMs), size),\n )\n const receipts = await this.deleteBatches((size) =>\n this.repository.deleteReceiptsBefore(new Date(at.getTime() - receiptRetentionMs), size),\n )\n return { published, failed, receipts }\n }\n\n private async deleteBatches(deleteBatch: (size: number) => Promise<number>): Promise<number> {\n let total = 0\n for (let batch = 0; batch < this.options.maxBatches; batch += 1) {\n // oxlint-disable-next-line no-await-in-loop -- The delete count decides whether another batch is needed.\n const deleted = await deleteBatch(this.options.batchSize)\n total += deleted\n if (deleted < this.options.batchSize) break\n }\n return total\n }\n}\n","import type { MessageId } from '@/core'\n\nimport type { IEventCollector } from './event-collector.ts'\nimport { MessageAlreadyProcessedError } from './message-already-processed.error.ts'\nimport type { IMessageStore } from './message-store.ts'\nimport type { IOutboxRelay } from './outbox-relay.ts'\nimport type { ITransaction } from './transaction.ts'\n\n/**\n * Commits the processed-message record, repository writes, and emitted events together before resolving.\n * An existing record rejects with `MessageAlreadyProcessedError`; external effects must run through the outbox after commit.\n * Nested calls reject with `UnitOfWorkAlreadyActiveError`; independent concurrent calls are allowed.\n */\nexport interface IUnitOfWork<Repos> {\n run<T>(messageId: MessageId, work: (repos: Repos) => Promise<T>): Promise<T>\n}\n\nexport type UnitOfWorkDeps<Tx, Repos> = {\n readonly transaction: ITransaction<Tx>\n /** The processed-messages and outbox repository for this transaction. */\n readonly messageStore: (tx: Tx) => IMessageStore\n /** Repositories participate in the current transaction. */\n readonly createRepositories: (tx: Tx) => Repos\n readonly eventCollector: IEventCollector\n readonly relay: IOutboxRelay\n}\n\n/** The unit of work: the boundary, the repositories, the events. Every database call is a port. */\nexport class UnitOfWork<Tx, Repos> implements IUnitOfWork<Repos> {\n constructor(private readonly deps: UnitOfWorkDeps<Tx, Repos>) {}\n\n async run<T>(messageId: MessageId, work: (repos: Repos) => Promise<T>): Promise<T> {\n const { transaction, messageStore, createRepositories, eventCollector, relay } = this.deps\n let written = 0\n\n let value: T\n try {\n value = await transaction.transaction(async (tx) => {\n const store = messageStore(tx)\n await store.claim(messageId)\n const repos = createRepositories(tx)\n const result = await work(repos)\n const pending = eventCollector.collect()\n await store.persistEvents(pending)\n written = pending.length\n return result\n })\n } catch (error) {\n throw MessageAlreadyProcessedError.from(error, messageId) ?? error\n }\n\n if (written > 0) relay.wake()\n return value\n }\n}\n","import { AppError } from '@/core'\n\n/** A boundary was opened inside another. One message, one atomic scope. */\nexport class UnitOfWorkAlreadyActiveError extends AppError {\n readonly _tag = 'UnitOfWorkAlreadyActiveError'\n readonly classification = 'terminal'\n\n constructor() {\n super('a unit of work is already active')\n }\n}\n"],"mappings":";;;;;AAeA,MAAa,iBAAmC;CAC9C,gBAAgB,CAAC;CACjB,aAAa,CAAC;CACd,aAAa,CAAC;CACd,sBAAsB,CAAC;AACzB;;;;;ACGA,MAAa,uBAAuC;CAClD,aAAa,CAAC;CACd,aAAa,CAAC;CACd,iBAAiB,CAAC;AACpB;;;;;ACuBA,IAAa,wBAAb,MAA4D;;CAE1D,AAAS,OAAwB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C;AACF"}
@@ -1,3 +1,3 @@
1
1
  import { G as DomainMessage, K as DomainQuery, U as DomainCommand, W as DomainEvent, q as MessageId } from "./index-DUFS0SJ_.js";
2
- import { $ as EventHandler, A as IOutboxRepository, B as OutboundEmail, C as UnitOfWorkDeps, D as OutboxRelay, E as IOutboxRelay, F as IEventCollector, G as MetricAttributeValue, H as ObservabilityScope, I as EmailAccepted, J as MetricsService, K as MetricAttributes, L as EmailAttachment, M as OutboxClaim, N as OutboxMessage, O as OutboxRelayOptions, P as IMessageStore, Q as CommandHandler, R as IEmailService, S as UnitOfWork, T as IOutboxPublisher, U as ObservabilityService, V as RecordingEmailService, W as ObservabilityUser, X as AnalyticsService, Y as NULL_METRICS_SERVICE, Z as NULL_ANALYTICS, _ as RecordEmailEventCommand, a as OutboxRetentionResult, b as recordEmailEvent, c as CommandRegistry, d as MessageRegistry, et as QueryHandler, f as MessageResult, g as IEmailDeliverabilityStore, h as EmailBounceRecord, i as OutboxRetentionOptions, j as IOutboxRetentionRepository, k as DeadLetterReason, l as EventRegistry, m as RegistryMessage, n as MessageAlreadyProcessedError, o as IMessageBus, p as QueryRegistry, q as MetricOptions, r as OutboxRetention, s as MessageBus, t as UnitOfWorkAlreadyActiveError, u as Handlers, v as RecordEmailEventDeps, w as ITransaction, x as IUnitOfWork, y as RecordEmailEventRepos, z as MimeType } from "./index-CYHXOH08.js";
3
- export { type AnalyticsService, type CommandHandler, type CommandRegistry, type DeadLetterReason, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, type EmailAccepted, type EmailAttachment, type EmailBounceRecord, type EventHandler, type EventRegistry, type Handlers, type IEmailDeliverabilityStore, type IEmailService, type IEventCollector, type IMessageBus, type IMessageStore, type IOutboxPublisher, type IOutboxRelay, type IOutboxRepository, type IOutboxRetentionRepository, type ITransaction, type IUnitOfWork, MessageAlreadyProcessedError, MessageBus, type MessageId, type MessageRegistry, type MessageResult, type MetricAttributeValue, type MetricAttributes, type MetricOptions, type MetricsService, type MimeType, NULL_ANALYTICS, NULL_METRICS_SERVICE, type ObservabilityScope, type ObservabilityService, type ObservabilityUser, type OutboundEmail, type OutboxClaim, type OutboxMessage, OutboxRelay, type OutboxRelayOptions, OutboxRetention, type OutboxRetentionOptions, type OutboxRetentionResult, type QueryHandler, type QueryRegistry, type RecordEmailEventCommand, type RecordEmailEventDeps, type RecordEmailEventRepos, RecordingEmailService, type RegistryMessage, UnitOfWork, UnitOfWorkAlreadyActiveError, type UnitOfWorkDeps, recordEmailEvent };
2
+ import { $ as CommandHandler, A as IOutboxRepository, B as OutboundEmail, C as UnitOfWorkDeps, D as OutboxRelay, E as IOutboxRelay, F as IEventCollector, G as ObservabilityUser, H as RecordingEmailService, I as EmailAccepted, J as MetricOptions, K as MetricAttributeValue, L as EmailAttachment, M as OutboxClaim, N as OutboxMessage, O as OutboxRelayOptions, P as IMessageStore, Q as NULL_ANALYTICS, R as IEmailService, S as UnitOfWork, T as IOutboxPublisher, U as ObservabilityScope, V as ReceivedEmail, W as ObservabilityService, X as NULL_METRICS_SERVICE, Y as MetricsService, Z as AnalyticsService, _ as RecordEmailEventCommand, a as OutboxRetentionResult, b as recordEmailEvent, c as CommandRegistry, d as MessageRegistry, et as EventHandler, f as MessageResult, g as IEmailDeliverabilityStore, h as EmailBounceRecord, i as OutboxRetentionOptions, j as IOutboxRetentionRepository, k as DeadLetterReason, l as EventRegistry, m as RegistryMessage, n as MessageAlreadyProcessedError, o as IMessageBus, p as QueryRegistry, q as MetricAttributes, r as OutboxRetention, s as MessageBus, t as UnitOfWorkAlreadyActiveError, tt as QueryHandler, u as Handlers, v as RecordEmailEventDeps, w as ITransaction, x as IUnitOfWork, y as RecordEmailEventRepos, z as MimeType } from "./index-tNZHSCpJ.js";
3
+ export { type AnalyticsService, type CommandHandler, type CommandRegistry, type DeadLetterReason, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, type EmailAccepted, type EmailAttachment, type EmailBounceRecord, type EventHandler, type EventRegistry, type Handlers, type IEmailDeliverabilityStore, type IEmailService, type IEventCollector, type IMessageBus, type IMessageStore, type IOutboxPublisher, type IOutboxRelay, type IOutboxRepository, type IOutboxRetentionRepository, type ITransaction, type IUnitOfWork, MessageAlreadyProcessedError, MessageBus, type MessageId, type MessageRegistry, type MessageResult, type MetricAttributeValue, type MetricAttributes, type MetricOptions, type MetricsService, type MimeType, NULL_ANALYTICS, NULL_METRICS_SERVICE, type ObservabilityScope, type ObservabilityService, type ObservabilityUser, type OutboundEmail, type OutboxClaim, type OutboxMessage, OutboxRelay, type OutboxRelayOptions, OutboxRetention, type OutboxRetentionOptions, type OutboxRetentionResult, type QueryHandler, type QueryRegistry, type ReceivedEmail, type RecordEmailEventCommand, type RecordEmailEventDeps, type RecordEmailEventRepos, RecordingEmailService, type RegistryMessage, UnitOfWork, UnitOfWorkAlreadyActiveError, type UnitOfWorkDeps, recordEmailEvent };
@@ -1,3 +1,3 @@
1
- import { a as MessageBus, c as RecordingEmailService, i as OutboxRelay, l as NULL_METRICS_SERVICE, n as UnitOfWork, o as MessageAlreadyProcessedError, r as OutboxRetention, s as recordEmailEvent, t as UnitOfWorkAlreadyActiveError, u as NULL_ANALYTICS } from "./application-Dg1jIKPe.js";
1
+ import { a as MessageBus, c as RecordingEmailService, i as OutboxRelay, l as NULL_METRICS_SERVICE, n as UnitOfWork, o as MessageAlreadyProcessedError, r as OutboxRetention, s as recordEmailEvent, t as UnitOfWorkAlreadyActiveError, u as NULL_ANALYTICS } from "./application-D5tNECiC.js";
2
2
 
3
3
  export { MessageAlreadyProcessedError, MessageBus, NULL_ANALYTICS, NULL_METRICS_SERVICE, OutboxRelay, OutboxRetention, RecordingEmailService, UnitOfWork, UnitOfWorkAlreadyActiveError, recordEmailEvent };
@@ -1,4 +1,4 @@
1
- import { nt as AppError, r as createLogger } from "../core-BT1dSEQI.js";
1
+ import { nt as AppError, r as createLogger } from "../core-BIas38R0.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  import { createPrivateKey, sign } from "node:crypto";
4
4
 
@@ -1,4 +1,4 @@
1
- import { U as RateLimitError } from "../core-BT1dSEQI.js";
1
+ import { U as RateLimitError } from "../core-BIas38R0.js";
2
2
  import { createAuthClient } from "better-auth/client";
3
3
 
4
4
  //#region src/infrastructure/better-auth/auth-client.ts
@@ -1,4 +1,4 @@
1
- import { nt as AppError, r as createLogger } from "../core-BT1dSEQI.js";
1
+ import { nt as AppError, r as createLogger } from "../core-BIas38R0.js";
2
2
 
3
3
  //#region src/infrastructure/better-auth/rate-limit.ts
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { r as createLogger } from "./core-BT1dSEQI.js";
1
+ import { r as createLogger } from "./core-BIas38R0.js";
2
2
  import { v7 } from "uuid";
3
3
  import { isAPIError } from "better-auth/api";
4
4
  import { anonymous, bearer, captcha, deviceAuthorization, emailOTP, lastLoginMethod, magicLink, openAPI } from "better-auth/plugins";
@@ -1,4 +1,4 @@
1
- import { nt as AppError } from "../core-BT1dSEQI.js";
1
+ import { nt as AppError } from "../core-BIas38R0.js";
2
2
 
3
3
  //#region src/infrastructure/billing/client.ts
4
4
  /** A Better Auth billing endpoint rejected the request. The browser boundary owns reporting. */
@@ -1,4 +1,4 @@
1
- import { nt as AppError } from "../core-BT1dSEQI.js";
1
+ import { nt as AppError } from "../core-BIas38R0.js";
2
2
  import { DurableObject } from "cloudflare:workers";
3
3
 
4
4
  //#region src/infrastructure/cloudflare/auth-secondary-storage.ts
@@ -1,4 +1,4 @@
1
- import { b as shouldRetryFailure, v as isAbortError } from "../core-BT1dSEQI.js";
1
+ import { b as shouldRetryFailure, v as isAbortError } from "../core-BIas38R0.js";
2
2
  import { DurableObjectCallError, classifyDurableObjectError, isClassifiedDurableObjectError } from "./durable-object-errors.js";
3
3
  import { Result } from "better-result";
4
4
 
@@ -1,4 +1,4 @@
1
- import { _ as isTransientCloudflareRuntimeError, g as isCloudflareRetryableError, h as isCloudflareOverloadedError, nt as AppError, v as isAbortError, y as isTransientTransportError } from "../core-BT1dSEQI.js";
1
+ import { _ as isTransientCloudflareRuntimeError, g as isCloudflareRetryableError, h as isCloudflareOverloadedError, nt as AppError, v as isAbortError, y as isTransientTransportError } from "../core-BIas38R0.js";
2
2
  import { z } from "zod";
3
3
 
4
4
  //#region src/infrastructure/cloudflare/durable-object-errors.ts
@@ -1,4 +1,4 @@
1
- import { l as spreadJitterMs, s as exponentialDelayCapMs } from "../core-BT1dSEQI.js";
1
+ import { l as spreadJitterMs, s as exponentialDelayCapMs } from "../core-BIas38R0.js";
2
2
  import { KVError, decideKVRetry, isKVPutRateLimitError } from "./kv-errors.js";
3
3
  import { Result } from "better-result";
4
4
 
@@ -1,4 +1,4 @@
1
- import { g as isCloudflareRetryableError, h as isCloudflareOverloadedError, nt as AppError, y as isTransientTransportError } from "../core-BT1dSEQI.js";
1
+ import { g as isCloudflareRetryableError, h as isCloudflareOverloadedError, nt as AppError, y as isTransientTransportError } from "../core-BIas38R0.js";
2
2
 
3
3
  //#region src/infrastructure/cloudflare/kv-errors.ts
4
4
  /** Extract Typist's verified KV message formats, including nested causes. */
@@ -1,5 +1,5 @@
1
1
  import { U as DomainCommand, W as DomainEvent, Xt as AppError, Zt as FailureClassification } from "../index-DUFS0SJ_.js";
2
- import { D as OutboxRelay, E as IOutboxRelay } from "../index-CYHXOH08.js";
2
+ import { D as OutboxRelay, E as IOutboxRelay } from "../index-tNZHSCpJ.js";
3
3
  import { z } from "zod";
4
4
  //#region src/infrastructure/cloudflare/queue/queue-message.d.ts
5
5
  /** A message a queue carries: a command from outside the request, or an event from the outbox. */
@@ -1,5 +1,5 @@
1
- import { b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, f as retryAfterSecondsOf, l as spreadJitterMs, nt as AppError, r as createLogger, u as classifyBoundaryError } from "../core-BT1dSEQI.js";
2
- import { o as MessageAlreadyProcessedError } from "../application-Dg1jIKPe.js";
1
+ import { b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, f as retryAfterSecondsOf, l as spreadJitterMs, nt as AppError, r as createLogger, u as classifyBoundaryError } from "../core-BIas38R0.js";
2
+ import { o as MessageAlreadyProcessedError } from "../application-D5tNECiC.js";
3
3
  import { Result } from "better-result";
4
4
 
5
5
  //#region src/infrastructure/cloudflare/queue/queue-limits.ts
@@ -1,4 +1,4 @@
1
- import { nt as AppError, v as isAbortError } from "../core-BT1dSEQI.js";
1
+ import { nt as AppError, v as isAbortError } from "../core-BIas38R0.js";
2
2
  import { R2Error, R2JsonError } from "./r2-errors.js";
3
3
 
4
4
  //#region src/infrastructure/cloudflare/r2-client.ts
@@ -1,4 +1,4 @@
1
- import { nt as AppError, u as classifyBoundaryError, v as isAbortError } from "../core-BT1dSEQI.js";
1
+ import { nt as AppError, u as classifyBoundaryError, v as isAbortError } from "../core-BIas38R0.js";
2
2
  import { z } from "zod";
3
3
 
4
4
  //#region src/infrastructure/cloudflare/r2-errors.ts
@@ -1,4 +1,4 @@
1
- import { r as createLogger } from "../core-BT1dSEQI.js";
1
+ import { r as createLogger } from "../core-BIas38R0.js";
2
2
  import { z } from "zod";
3
3
 
4
4
  //#region src/infrastructure/cloudflare/scheduled/scheduled-handler.ts
@@ -1,6 +1,6 @@
1
1
  import { W as DomainEvent, et as D1ConstraintKind, nt as DatabaseFailure, q as MessageId, tt as DatabaseError } from "./index-DUFS0SJ_.js";
2
- import { A as IOutboxRepository, M as OutboxClaim, N as OutboxMessage, P as IMessageStore, k as DeadLetterReason, w as ITransaction } from "./index-CYHXOH08.js";
3
- import { n as eventCollector, r as DrizzleSchema, t as OutboxRepositoryOptions } from "./outbox-repository-options-DjBgFhMi.js";
2
+ import { A as IOutboxRepository, M as OutboxClaim, N as OutboxMessage, P as IMessageStore, k as DeadLetterReason, w as ITransaction } from "./index-tNZHSCpJ.js";
3
+ import { n as eventCollector, r as DrizzleSchema, t as OutboxRepositoryOptions } from "./outbox-repository-options-_B8l8l6l.js";
4
4
  import { BatchItem } from "drizzle-orm/batch";
5
5
  import { AnyD1Database, DrizzleD1Database } from "drizzle-orm/d1";
6
6
  //#region src/infrastructure/cloudflare/d1-database-types.d.ts
@@ -1,6 +1,6 @@
1
- import { O as DatabaseError, nt as AppError, s as exponentialDelayCapMs } from "./core-BT1dSEQI.js";
2
- import { o as MessageAlreadyProcessedError } from "./application-Dg1jIKPe.js";
3
- import { a as stageD1Statement, i as runWithUnitOfWorkContext, n as collectD1Statements, r as eventCollector, t as OUTBOX_REPOSITORY_DEFAULTS } from "./outbox-repository-options-B8TnAE1h.js";
1
+ import { O as DatabaseError, nt as AppError, s as exponentialDelayCapMs } from "./core-BIas38R0.js";
2
+ import { o as MessageAlreadyProcessedError } from "./application-D5tNECiC.js";
3
+ import { a as stageD1Statement, i as runWithUnitOfWorkContext, n as collectD1Statements, r as eventCollector, t as OUTBOX_REPOSITORY_DEFAULTS } from "./outbox-repository-options-D0R8z1yS.js";
4
4
  import { Result } from "better-result";
5
5
  import { DrizzleQueryError } from "drizzle-orm/errors";
6
6
  import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
@@ -90,7 +90,7 @@ var EmailServiceError = class extends AppError {
90
90
  statusCode;
91
91
  retryAfter;
92
92
  constructor(args) {
93
- super(`Email send failed: ${args.provider} ${args.providerCode}`, { cause: args.cause });
93
+ super(`Email request failed: ${args.provider} ${args.providerCode}`, { cause: args.cause });
94
94
  this.reason = args.reason;
95
95
  this.classification = CLASSIFICATION_BY_REASON[args.reason];
96
96
  this.provider = args.provider;
@@ -885,4 +885,4 @@ function createLogger(module) {
885
885
 
886
886
  //#endregion
887
887
  export { EmailAddressSchema as $, sharedErrors as A, ServiceUnavailableError as B, combineMessages as C, unreachable as D, notImplemented as E, RequestTimeoutError as F, RecordEmailEventPayloadSchema as G, StaleSessionError as H, ResourceNotFoundError as I, parseBounceType as J, BounceTypeSchema as K, UpgradeRequiredError as L, ValidationProblemDetailsSchema as M, ValidationProblemErrorSchema as N, DatabaseError as O, MalformedRequestError as P, emailIdempotencyKey as Q, ValidationError as R, DuplicateMessageNameError as S, defineId as T, RateLimitError as U, NotAuthorizedError as V, AuthenticationError as W, EmailServiceError as X, shouldUpdateBounce as Y, InvalidEmailIdempotencyKeyError as Z, isTransientCloudflareRuntimeError as _, setLoggerErrorHook as a, shouldRetryFailure as b, exponentialEqualJitterMs as c, classifyFailure as d, AnalyticsEventIdSchema as et, retryAfterSecondsOf as f, isCloudflareRetryableError as g, isCloudflareOverloadedError as h, setLogSink as i, ProblemDetailsSchema as j, defineErrors as k, spreadJitterMs as l, isCloudflareObjectResetError as m, configureLogger as n, AppError as nt, consoleSink as o, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS as p, isEmailDeliverable as q, createLogger as r, exponentialDelayCapMs as s, LogLevel as t, MissingConfigurationError as tt, classifyBoundaryError as u, isAbortError as v, defineMessages as w, Entity as x, isTransientTransportError as y, InternalServerError as z };
888
- //# sourceMappingURL=core-BT1dSEQI.js.map
888
+ //# sourceMappingURL=core-BIas38R0.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-BIas38R0.js","names":["uuidv7","uuidv7"],"sources":["../src/core/app-error.ts","../src/core/missing-configuration.error.ts","../src/core/analytics-event.ts","../src/core/email-address.ts","../src/core/email-idempotency-key.ts","../src/core/email-service.error.ts","../src/core/email-deliverability.ts","../src/core/record-email-event.ts","../src/core/authentication.error.ts","../src/core/rate-limit.error.ts","../src/core/stale-session.error.ts","../src/core/not-authorized.error.ts","../src/core/internal.errors.ts","../src/core/request.errors.ts","../src/core/problem-details.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/failure-classification.ts","../src/core/transport-classification.ts","../src/core/cloudflare-classification.ts","../src/core/classify-failure.ts","../src/core/backoff.ts","../src/core/console-log-sink.ts","../src/core/logger.ts"],"sourcesContent":["import type { FailureClassification } from './failure-classification.ts'\n\n/**\n * The base of every expected failure. A subclass declares its tag and its classification,\n * so no boundary has to guess what kind of failure it holds. A boundary tells our errors from\n * raw throws with `instanceof AppError`; a value that fails it was never judged.\n *\n * A `readonly` field with a literal initializer keeps the literal type, so\n * `readonly _tag = 'StoreUnavailable'` is enough for `Result` unions and `matchError`.\n */\nexport abstract class AppError extends Error {\n abstract readonly _tag: string\n abstract readonly classification: FailureClassification\n\n override get name(): string {\n return this._tag\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** Required configuration is absent. Ported from Porte's configuration.errors.ts. */\nexport class MissingConfigurationError extends AppError {\n readonly _tag = 'MissingConfigurationError'\n readonly classification = 'terminal'\n\n /** Name the missing setting without including its value. */\n constructor(readonly key: string) {\n super(`${key} is required`)\n }\n}\n","import { z } from 'zod'\n\n/** An event name and its application-owned properties, ported from Typist's analytics/types.ts. */\nexport interface AnalyticsEventInput<\n TName extends string = string,\n TProperties extends object = object,\n> {\n readonly name: TName\n readonly properties: TProperties\n}\n\n/** A value supported by analytics person properties. */\nexport type AnalyticsProperty =\n | string\n | number\n | boolean\n | null\n | undefined\n | readonly AnalyticsProperty[]\n | AnalyticsProperties\n\n/** Person properties supplied by the application. */\nexport interface AnalyticsProperties {\n readonly [name: string]: AnalyticsProperty\n}\n\n/** Parse a persisted analytics event UUID; the SDK generates ordinary event UUIDs itself. */\nexport const AnalyticsEventIdSchema = z.uuid().brand<'AnalyticsEventId'>()\n\n/** The identity of one analytics event across repeated application deliveries. */\nexport type AnalyticsEventId = z.infer<typeof AnalyticsEventIdSchema>\n\n/** Supply both original values when replaying one event; never share them across different occurrences. */\nexport interface AnalyticsEventIdentity {\n readonly uuid: AnalyticsEventId\n readonly timestamp: Date\n}\n","import { z } from 'zod'\n\n/** A parsed email address for message payloads and webhook recipients. Ported from Typist's `EmailSchema`. */\nexport const EmailAddressSchema = z.email().brand<'EmailAddress'>()\n\n/** An address the schema accepted. */\nexport type EmailAddress = z.infer<typeof EmailAddressSchema>\n","import type { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\n\n/** A key only `emailIdempotencyKey` mints, so every send carries one built by its rules. */\nexport type EmailIdempotencyKey = string & z.core.$brand<'EmailIdempotencyKey'>\n\n// Resend accepts 1 to 256 characters. Source: https://resend.com/docs/dashboard/emails/idempotency-keys\nconst MAX_KEY_LENGTH = 256\n\n/** A key outside 1 to 256 characters. Keys come from stable ids, so this is a defect, not a retry. */\nexport class InvalidEmailIdempotencyKeyError extends AppError {\n readonly _tag = 'InvalidEmailIdempotencyKeyError'\n readonly classification = 'terminal'\n\n constructor(readonly length: number) {\n super(`Email idempotency key must have 1 to ${MAX_KEY_LENGTH} characters`)\n }\n}\n\n/**\n * `<scope>/<id>` for one logical send. Resend deduplicates it for 24 hours.\n * Derive `id` from a stable identity: a message id, a job id, a user id with a template name.\n * The same key must map to an identical payload; a changed body is rejected as terminal.\n * A random `id` means every request is a deliberate new send, as a sign-in code resend is.\n * Source: https://resend.com/docs/dashboard/emails/idempotency-keys\n */\nexport function emailIdempotencyKey(scope: string, id: string): EmailIdempotencyKey {\n const key = `${scope}/${id}`\n if (scope.length === 0 || id.length === 0 || key.length > MAX_KEY_LENGTH)\n throw new InvalidEmailIdempotencyKeyError(key.length)\n // SAFETY: the brand is a compile-time mark; the checks above are the whole rule.\n return key as EmailIdempotencyKey\n}\n","import { AppError } from './app-error.ts'\nimport type { FailureClassification } from './failure-classification.ts'\n\n/** Why the provider rejected a send. The reason owns the classification, so the two never disagree. */\nexport type EmailSendFailureReason =\n | 'rate_limited'\n | 'idempotency_conflict'\n | 'provider_error'\n | 'quota_exceeded'\n | 'invalid_request'\n | 'configuration'\n\nconst CLASSIFICATION_BY_REASON = {\n rate_limited: 'transient',\n idempotency_conflict: 'transient',\n provider_error: 'transient',\n quota_exceeded: 'terminal',\n invalid_request: 'terminal',\n configuration: 'terminal',\n} satisfies Record<EmailSendFailureReason, FailureClassification>\n\n/**\n * The provider rejected a send. The boundary that awaited the send logs once; the adapter never does.\n * `retryAfter` is the server's delay in seconds when it sent one, so `retryAfterSecondsOf` reads it.\n */\nexport class EmailServiceError extends AppError {\n readonly _tag = 'EmailServiceError'\n readonly classification: FailureClassification\n readonly reason: EmailSendFailureReason\n readonly provider: string\n readonly providerCode: string\n readonly statusCode: number | null\n readonly retryAfter: number | null\n\n constructor(args: {\n readonly reason: EmailSendFailureReason\n readonly provider: string\n readonly providerCode: string\n readonly statusCode: number | null\n readonly retryAfter: number | null\n readonly cause: unknown\n }) {\n super(`Email request failed: ${args.provider} ${args.providerCode}`, { cause: args.cause })\n this.reason = args.reason\n this.classification = CLASSIFICATION_BY_REASON[args.reason]\n this.provider = args.provider\n this.providerCode = args.providerCode\n this.statusCode = args.statusCode\n this.retryAfter = args.retryAfter\n }\n}\n","import { z } from 'zod'\n\n/** The bounce classes Resend reports, ported from Typist's comm-eligibility.ts. */\nexport const BounceTypeSchema = z.enum(['Permanent', 'Transient', 'Undetermined'])\n\n/** One bounce class. */\nexport type BounceType = z.infer<typeof BounceTypeSchema>\n\n/** Parse a provider's bounce type. An unknown value is `Undetermined`, which suppresses. */\nexport function parseBounceType(value: string | undefined): BounceType {\n const parsed = BounceTypeSchema.safeParse(value)\n return parsed.success ? parsed.data : 'Undetermined'\n}\n\nconst BOUNCE_SEVERITY = {\n Transient: 1,\n Undetermined: 2,\n Permanent: 3,\n} satisfies Record<BounceType, number>\n\n/** Keep the higher severity. Equal severity permits replacement; callers own timestamp ordering. */\nexport function shouldUpdateBounce(incoming: BounceType, current: BounceType | null): boolean {\n if (current === null) return true\n return BOUNCE_SEVERITY[incoming] >= BOUNCE_SEVERITY[current]\n}\n\n/** Typist's send policy: no complaint, and either no bounce or a transient one. Delivery is not guaranteed. */\nexport function isEmailDeliverable(bounceType: BounceType | null, complained: boolean): boolean {\n if (complained) return false\n return bounceType === null || bounceType === 'Transient'\n}\n","import { z } from 'zod'\n\nimport { EmailAddressSchema } from './email-address.ts'\nimport { BounceTypeSchema } from './email-deliverability.ts'\n\n/**\n * The payload of the command an application registers to record a bounce or a complaint.\n * Register it under a name of the application's choice in `defineMessages`; `recordEmailEvent` handles it.\n */\nexport const RecordEmailEventPayloadSchema = z.object({\n recipients: z.array(EmailAddressSchema).min(1),\n event: z.discriminatedUnion('type', [\n z.object({\n type: z.literal('bounced'),\n bounceType: BounceTypeSchema,\n bounceSubType: z.string().nullable(),\n }),\n z.object({ type: z.literal('complained') }),\n ]),\n})\n\n/** A parsed payload. */\nexport type RecordEmailEventPayload = z.infer<typeof RecordEmailEventPayloadSchema>\n","import { AppError } from './app-error.ts'\n\n/** A protected operation requires a session that the caller did not provide. */\nexport class AuthenticationError extends AppError {\n readonly _tag = 'AuthenticationError'\n readonly classification = 'terminal'\n\n constructor() {\n super('Authentication required')\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** HTTP 429 with a retry delay in seconds. A null delay means the response supplies no valid duration. */\nexport class RateLimitError extends AppError {\n readonly _tag = 'RateLimitError'\n readonly classification = 'transient'\n readonly status = 429\n\n constructor(readonly retryAfter: number | null) {\n super('Too many requests')\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** A presented session cookie no longer resolves; the application owns cleanup and redirect policy. */\nexport class StaleSessionError extends AppError {\n readonly _tag = 'StaleSessionError'\n readonly classification = 'terminal'\n\n constructor() {\n super('Session is no longer valid. Sign in again.')\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** The authenticated caller cannot perform this operation. Ported from Porte's auth.errors.ts. */\nexport class NotAuthorizedError extends AppError {\n readonly _tag = 'NotAuthorizedError'\n readonly classification = 'terminal'\n\n constructor() {\n super('Not allowed')\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** Safe public replacement for an unknown failure, ported from Porte's internal.errors.ts. */\nexport class InternalServerError extends AppError {\n readonly _tag = 'InternalServerError'\n readonly classification = 'unknown'\n\n constructor() {\n super('Something went wrong')\n }\n}\n\n/** Safe public replacement for a classified transient failure. */\nexport class ServiceUnavailableError extends AppError {\n readonly _tag = 'ServiceUnavailableError'\n readonly classification = 'transient'\n\n constructor() {\n super('Try again shortly')\n }\n}\n","import { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\nimport type { ValidationProblemError } from './problem-details.ts'\n\n/** One invalid value as a validator reports it: a message and a path of keys. */\nexport type ValidationIssue = {\n readonly message: string\n readonly path: readonly PropertyKey[]\n}\n\n/** Invalid user input, one entry per invalid value in the RFC 9457 shape. Technical failures use another error. */\nexport class ValidationError extends AppError {\n readonly _tag = 'ValidationError'\n readonly classification = 'terminal'\n\n constructor(\n readonly errors: readonly ValidationProblemError[],\n message = 'The request was not valid',\n ) {\n super(message)\n }\n\n /** Convert a Zod error. Each issue path becomes a JSON Pointer. */\n static fromZod(error: z.ZodError, message?: string): ValidationError {\n return ValidationError.fromIssues(error.issues, message)\n }\n\n /** Convert issues from any validator, such as issues TanStack serialized into an error message. */\n static fromIssues(issues: readonly ValidationIssue[], message?: string): ValidationError {\n return new ValidationError(\n issues.map((issue) => ({ detail: issue.message, pointer: jsonPointer(issue.path) })),\n message,\n )\n }\n}\n\n/** The server cannot parse the request syntax. */\nexport class MalformedRequestError extends AppError {\n readonly _tag = 'MalformedRequestError'\n readonly classification = 'terminal'\n\n constructor(args: { cause: unknown }) {\n super('The request was malformed', args)\n }\n}\n\n/** No resource matches the requested HTTP path. */\nexport class ResourceNotFoundError extends AppError {\n readonly _tag = 'ResourceNotFoundError'\n readonly classification = 'terminal'\n\n constructor() {\n super('Resource not found')\n }\n}\n\n/** A WebSocket route received a request without an upgrade. */\nexport class UpgradeRequiredError extends AppError {\n readonly _tag = 'UpgradeRequiredError'\n readonly classification = 'terminal'\n\n constructor() {\n super('WebSocket upgrade required')\n }\n}\n\n/** The requested operation did not answer before its deadline. */\nexport class RequestTimeoutError extends AppError {\n readonly _tag = 'RequestTimeoutError'\n readonly classification = 'transient'\n\n constructor() {\n super('The request timed out')\n }\n}\n\nconst readablePathSchema = z.array(z.union([z.string(), z.number()]))\n\n// A symbol step cannot be shown, so the pointer keeps only the steps a person can read.\nfunction jsonPointer(path: readonly PropertyKey[]): string {\n const parsed = readablePathSchema.safeParse(path)\n const steps = parsed.success ? parsed.data : []\n if (steps.length === 0) return '#'\n return `#/${steps.map((step) => String(step).replaceAll('~', '~0').replaceAll('/', '~1')).join('/')}`\n}\n","import { z } from 'zod'\n\n/**\n * The standard RFC 9457 body for a failed HTTP response.\n * The HTTP response status remains authoritative; extensions may add problem-specific data.\n * @see https://http.dev/problem-details\n */\nexport const ProblemDetailsSchema = z.looseObject({\n /**\n * Stable URI for the problem type; use `about:blank` when the HTTP status is sufficient.\n * @example \"about:blank\"\n */\n type: z.string(),\n /**\n * Stable human-readable name for the problem type.\n * @example \"Service Unavailable\"\n */\n title: z.string(),\n /**\n * Safe human-readable explanation for this occurrence; clients must not parse it.\n * @example \"The service is unavailable.\"\n */\n detail: z.string().optional(),\n /**\n * URI reference for this occurrence; omit it when no correlation resource exists.\n * @example \"/problems/occurrences/01K5F6Y7\"\n */\n instance: z.string().optional(),\n})\n\n/** An RFC 9457 problem body for a failed HTTP response. */\nexport type ProblemDetails = z.infer<typeof ProblemDetailsSchema>\n\n/** One invalid value in a `422` validation problem. */\nexport const ValidationProblemErrorSchema = z.object({\n /**\n * Safe explanation of why this value is invalid.\n * @example \"Must be a positive integer.\"\n */\n detail: z.string(),\n /**\n * RFC 6901 JSON Pointer fragment for the invalid value.\n * @example \"#/age\"\n */\n pointer: z.string().regex(/^#(?:\\/(?:[^~]|~[01])*)*$/u),\n})\n\n/** One invalid value in a `422` validation problem. */\nexport type ValidationProblemError = z.infer<typeof ValidationProblemErrorSchema>\n\n/** An RFC 9457 validation problem with one or more invalid content values. */\nexport const ValidationProblemDetailsSchema = ProblemDetailsSchema.extend({\n errors: z.array(ValidationProblemErrorSchema).min(1),\n})\n\n/** An RFC 9457 validation problem with one or more invalid content values. */\nexport type ValidationProblemDetails = z.infer<typeof ValidationProblemDetailsSchema>\n","import { panic } from 'better-result'\nimport { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\nimport { AuthenticationError } from './authentication.error.ts'\nimport { InternalServerError, ServiceUnavailableError } from './internal.errors.ts'\nimport { NotAuthorizedError } from './not-authorized.error.ts'\nimport { ValidationProblemErrorSchema } from './problem-details.ts'\nimport { RateLimitError } from './rate-limit.error.ts'\nimport {\n MalformedRequestError,\n RequestTimeoutError,\n ResourceNotFoundError,\n UpgradeRequiredError,\n ValidationError,\n} from './request.errors.ts'\nimport { StaleSessionError } from './stale-session.error.ts'\n\ntype PublicFields = z.ZodObject\n\n/**\n * One public error: its class, its HTTP status, and the extra properties a client may read.\n * `fields` strips the thrown error on the server and parses the payload in the browser.\n */\nexport type ErrorEntry<Tag extends string, Fields extends PublicFields = PublicFields> = {\n readonly error: abstract new (...args: never[]) => AppError & { readonly _tag: Tag }\n readonly status: number\n readonly fields?: Fields\n}\n\ntype AnyErrorEntry = ErrorEntry<string>\n\n/** Entries keyed by tag. The compiler rejects a key that differs from the class's `_tag`. */\nexport type ErrorEntries<Entries> = {\n readonly [Tag in keyof Entries & string]: ErrorEntry<Tag>\n}\n\ntype EntryPayload<Tag extends string, Entry> = Entry extends {\n readonly fields: infer Fields extends z.ZodType\n}\n ? { readonly _tag: Tag; readonly message: string } & z.output<Fields>\n : { readonly _tag: Tag; readonly message: string }\n\ntype PayloadOfEntries<Entries> = {\n [Tag in keyof Entries & string]: EntryPayload<Tag, Entries[Tag]>\n}[keyof Entries & string]\n\n/** The HTTP status and public payload for one resolved failure. */\nexport type ResolvedError<Payload> = {\n readonly status: number\n readonly payload: Payload\n}\n\n/**\n * One application's public errors, shared by every transport boundary and the browser.\n * `resolve` and `fallback` serve boundaries. `parse` and `generic` serve screens.\n */\nexport type ErrorTable<Entries> = {\n readonly entries: Entries\n /** The discriminated union of every entry's `_tag`, `message`, and fields. */\n readonly payloadSchema: z.ZodType<PayloadOfEntries<Entries>>\n /** The `InternalServerError` payload, for screens that must show something. */\n readonly generic: PayloadOfEntries<Entries>\n /** Read a rejection value. Null means no known tag, so the request never reached the Worker. */\n parse(cause: unknown): PayloadOfEntries<Entries> | null\n /** Narrow a rejection value to one tag's payload, for a caller that acts on that one error. */\n is<Tag extends keyof Entries & string>(\n cause: unknown,\n tag: Tag,\n ): cause is Extract<PayloadOfEntries<Entries>, { readonly _tag: Tag }>\n /** Match a local instance or a remote error by tag. Null means the failure is not public. */\n resolve(cause: unknown): ResolvedError<PayloadOfEntries<Entries>> | null\n /** The replacement for an unmapped failure: 503 when it declared itself transient, else 500. */\n fallback(cause: unknown): ResolvedError<PayloadOfEntries<Entries>>\n}\n\n/** The union of payloads a table can produce. */\nexport type ErrorPayloadOf<Table> =\n Table extends ErrorTable<infer Entries> ? PayloadOfEntries<Entries> : never\n\n/** The union of tags a table contains. */\nexport type ErrorTagOf<Table> =\n Table extends ErrorTable<infer Entries> ? keyof Entries & string : never\n\nfunction entriesOf<const Entries extends ErrorEntries<Entries>>(entries: Entries): Entries {\n return entries\n}\n\nconst ValidationFields = z.object({ errors: z.array(ValidationProblemErrorSchema) })\nconst RateLimitFields = z.object({ retryAfter: z.number().nullable() })\n\n/** The errors every application can throw, with their statuses. `defineErrors` includes them. */\nexport const sharedErrors = entriesOf({\n MalformedRequestError: { error: MalformedRequestError, status: 400 },\n AuthenticationError: { error: AuthenticationError, status: 401 },\n StaleSessionError: { error: StaleSessionError, status: 401 },\n NotAuthorizedError: { error: NotAuthorizedError, status: 403 },\n ResourceNotFoundError: { error: ResourceNotFoundError, status: 404 },\n ValidationError: { error: ValidationError, status: 422, fields: ValidationFields },\n UpgradeRequiredError: { error: UpgradeRequiredError, status: 426 },\n RateLimitError: { error: RateLimitError, status: 429, fields: RateLimitFields },\n InternalServerError: { error: InternalServerError, status: 500 },\n ServiceUnavailableError: { error: ServiceUnavailableError, status: 503 },\n RequestTimeoutError: { error: RequestTimeoutError, status: 504 },\n})\n\ntype MergedEntries<Entries> = Omit<typeof sharedErrors, keyof Entries> & Entries\n\n// Workers RPC drops the prototype but keeps own properties and marks the error as remote.\nconst RemoteErrorSchema = z.object({\n _tag: z.string(),\n message: z.string(),\n remote: z.literal(true),\n})\n\ntype Match = { readonly tag: string; readonly entry: AnyErrorEntry; readonly error: Error }\n\nfunction match(byTag: ReadonlyMap<string, AnyErrorEntry>, cause: unknown): Match | null {\n if (cause instanceof AppError) {\n const entry = byTag.get(cause._tag)\n if (entry === undefined || !(cause instanceof entry.error)) return null\n return { tag: cause._tag, entry, error: cause }\n }\n if (!(cause instanceof Error)) return null\n const remote = RemoteErrorSchema.safeParse(cause)\n if (!remote.success) return null\n const entry = byTag.get(remote.data._tag)\n return entry === undefined ? null : { tag: remote.data._tag, entry, error: cause }\n}\n\n/**\n * Build the application's error table. The shared entries are always included;\n * an entry with the same key replaces the shared one.\n */\nexport function defineErrors<const Entries extends ErrorEntries<Entries>>(\n entries: Entries,\n): ErrorTable<MergedEntries<Entries>> {\n type Payload = PayloadOfEntries<MergedEntries<Entries>>\n const merged = { ...sharedErrors, ...entries }\n const byTag: ReadonlyMap<string, AnyErrorEntry> = new Map(Object.entries<AnyErrorEntry>(merged))\n\n const resolve = (cause: unknown): ResolvedError<Payload> | null => {\n const found = match(byTag, cause)\n if (found === null) return null\n const fields = found.entry.fields?.safeParse(found.error)\n if (fields !== undefined && !fields.success) return null\n // SAFETY: The entry's own `fields` schema produced these properties, so the payload has the shape declared for this tag.\n const payload = { _tag: found.tag, message: found.error.message, ...fields?.data } as Payload\n return { status: found.entry.status, payload }\n }\n\n const resolveShared = (error: AppError): ResolvedError<Payload> =>\n resolve(error) ?? panic(`Error table cannot resolve shared error ${error._tag}`)\n const generic = resolveShared(new InternalServerError())\n const unavailable = resolveShared(new ServiceUnavailableError())\n\n const variants = [...byTag].map(([tag, entry]) =>\n // oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- Zod names an object schema's property map `shape`.\n z.strictObject({ _tag: z.literal(tag), message: z.string(), ...entry.fields?.shape }),\n )\n const [first, ...rest] = variants\n if (first === undefined) return panic('Error table has no entries')\n // Each variant is one entry's `_tag`, `message`, and fields, which is the union `PayloadOfEntries` describes.\n const payloadSchema = z.discriminatedUnion('_tag', [first, ...rest]).pipe(z.custom<Payload>())\n\n // No return annotation: TypeScript resolves the deferred payload union differently in that position.\n const parse = (cause: unknown) => {\n const parsed = payloadSchema.safeParse(cause)\n return parsed.success ? parsed.data : null\n }\n\n return {\n entries: merged,\n payloadSchema,\n generic: generic.payload,\n parse,\n is<Tag extends keyof MergedEntries<Entries> & string>(\n cause: unknown,\n tag: Tag,\n ): cause is Extract<Payload, { readonly _tag: Tag }> {\n const parsed = parse(cause)\n return parsed !== null && parsed._tag === tag\n },\n resolve,\n fallback: (cause) =>\n cause instanceof AppError && cause.classification === 'transient' ? unavailable : generic,\n }\n}\n","import { AppError } from './app-error.ts'\nimport type { FailureClassification } from './failure-classification.ts'\n\n/** SQLite reports these constraint categories through D1. */\nexport type D1ConstraintKind = 'unique' | 'not_null' | 'foreign_key' | 'check'\n\n/** Database evidence for callers that interpret a specific code or constraint. */\nexport type DatabaseFailure =\n | {\n readonly database: 'd1'\n readonly code: string | undefined\n readonly kind: D1ConstraintKind | undefined\n readonly table: string | undefined\n readonly column: string | undefined\n readonly constraintName: string | undefined\n }\n | {\n readonly database: 'postgres'\n readonly code: string | undefined\n readonly table_name: string | undefined\n readonly column_name: string | undefined\n readonly constraint_name: string | undefined\n }\n\n/** Classification describes the failure; callers must separately establish whether repetition is safe. */\nexport class DatabaseError extends AppError {\n readonly _tag = 'DatabaseError'\n\n constructor(\n readonly operation: string,\n readonly classification: FailureClassification,\n readonly details: DatabaseFailure,\n options: { readonly cause: unknown },\n ) {\n super(`Database operation failed: ${operation}`, options)\n }\n}\n","import { panic } from 'better-result'\n\n/**\n * Mark a line the types say cannot run. A union member without a branch stops compilation here.\n *\n * @throws Panic when a value outside the union arrives at runtime.\n */\nexport function unreachable(value: never): never {\n return panic(`Unreachable: ${String(value)}`)\n}\n\n/**\n * Mark a body that is not written yet. A defect, not an expected failure.\n *\n * @param what - The behavior the body will provide, such as `invoice export`.\n * @throws Panic always.\n */\nexport function notImplemented(what: string): never {\n return panic(`Not implemented: ${what}`)\n}\n","import { v7 as uuidv7 } from 'uuid'\nimport { z } from 'zod'\n\n/** A string only `create()` or `schema.parse()` of the same kind can produce. */\nexport type Id<Brand extends string> = string & z.core.$brand<Brand>\n\n/** One id kind the application mints. `schema` parses untrusted input; `create` mints a uuid v7. */\nexport type IdDefinition<Brand extends string> = {\n readonly schema: z.core.$ZodBranded<z.ZodUUID, Brand>\n /** Mint a new time-ordered id. No parse: we produced it, so it is valid by construction. */\n create(): Id<Brand>\n}\n\n/** The id type of a definition: `type CallId = IdOf<typeof CallId>`. */\nexport type IdOf<Definition extends IdDefinition<string>> = z.output<Definition['schema']>\n\n/**\n * Define an id kind the application mints: `export const CallId = defineId('CallId')`.\n * An id another system mints, such as a provider's call id, stays a plain branded schema.\n */\nexport function defineId<const Brand extends string>(brand: Brand): IdDefinition<Brand> {\n const schema = z.uuidv7({ error: `Invalid ${brand}` })\n return {\n // SAFETY: `brand()` is type-only and returns a conditional TypeScript cannot reduce for a generic brand; for every literal it is this branded schema.\n schema: schema.brand<Brand>() as z.core.$ZodBranded<z.ZodUUID, Brand>,\n // SAFETY: uuidv7() always yields a valid v7 uuid, and the brand is a compile-time mark only.\n create: () => uuidv7() as Id<Brand>,\n }\n}\n","import { panic } from 'better-result'\nimport { v7 as uuidv7 } from 'uuid'\nimport { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\nimport type { MessageId } from './messages.ts'\n\n/** Payload schemas keyed by message name. Payloads cannot declare `type`, `name`, or `id`. */\nexport type PayloadSchemas = Readonly<Record<string, z.ZodType<object>>>\n\n/** Optional payload schema maps for one message collection. */\nexport type MessageDefinition = {\n readonly commands?: PayloadSchemas\n readonly events?: PayloadSchemas\n readonly queries?: PayloadSchemas\n}\n\nconst completed = Symbol('MessageCollection')\nconst MessageIdSchema = z.string().min(1)\nconst envelopes = {\n command: z.object({ type: z.literal('command'), id: MessageIdSchema }),\n event: z.object({ type: z.literal('event'), id: MessageIdSchema }),\n query: z.object({ type: z.literal('query') }),\n}\n\ntype MessageKind = keyof typeof envelopes\ntype RoutingField = 'type' | 'name' | 'id'\ntype SchemaMap = Readonly<Record<string, z.ZodType<object>>>\ntype EmptySchemas = Record<never, never>\ntype SchemaMaps = {\n readonly commandSchemas: SchemaMap\n readonly eventSchemas: SchemaMap\n readonly querySchemas: SchemaMap\n}\ntype CompletedMessages = SchemaMaps & { readonly [completed]: true }\ntype SchemaOf<Schemas extends SchemaMap> = Schemas[keyof Schemas & string]\ntype Payload<Message> = Message extends object ? Omit<Message, RoutingField> : never\n\n/** Complete schemas, union schemas, and factories for one message collection. */\nexport type MessageCollection<Maps extends SchemaMaps> = Maps & {\n readonly [completed]: true\n readonly commandSchema: z.ZodUnion<SchemaOf<Maps['commandSchemas']>[]>\n readonly eventSchema: z.ZodUnion<SchemaOf<Maps['eventSchemas']>[]>\n readonly querySchema: z.ZodUnion<SchemaOf<Maps['querySchemas']>[]>\n /** Commands and events can cross a queue. Queries cannot. */\n readonly queueSchema: z.ZodUnion<\n (SchemaOf<Maps['commandSchemas']> | SchemaOf<Maps['eventSchemas']>)[]\n >\n /** Add the command envelope without parsing. The default ID is UUID v7; supplied IDs stay unchanged. */\n createCommand<Name extends keyof Maps['commandSchemas'] & string>(\n this: void,\n name: Name,\n payload: Payload<z.output<Maps['commandSchemas'][NoInfer<Name>]>>,\n id?: MessageId,\n ): z.output<Maps['commandSchemas'][Name]>\n /** Add the event envelope without parsing. The default ID is UUID v7; supplied IDs stay unchanged. */\n createEvent<Name extends keyof Maps['eventSchemas'] & string>(\n this: void,\n name: Name,\n payload: Payload<z.output<Maps['eventSchemas'][NoInfer<Name>]>>,\n id?: MessageId,\n ): z.output<Maps['eventSchemas'][Name]>\n /** Add the query envelope without parsing. Queries have no ID. */\n createQuery<Name extends keyof Maps['querySchemas'] & string>(\n this: void,\n name: Name,\n payload: Payload<z.output<Maps['querySchemas'][NoInfer<Name>]>>,\n ): z.output<Maps['querySchemas'][Name]>\n}\n\n/** The command union inferred from a collection's complete schemas. */\nexport type CommandOf<Messages extends CompletedMessages> = z.output<\n SchemaOf<Messages['commandSchemas']>\n>\n\n/** The event union inferred from a collection's complete schemas. */\nexport type EventOf<Messages extends CompletedMessages> = z.output<\n SchemaOf<Messages['eventSchemas']>\n>\n\n/** The query union inferred from a collection's complete schemas. */\nexport type QueryOf<Messages extends CompletedMessages> = z.output<\n SchemaOf<Messages['querySchemas']>\n>\n\n/** Every message inferred from a collection's complete schemas. */\nexport type MessageOf<Messages extends CompletedMessages> =\n | CommandOf<Messages>\n | EventOf<Messages>\n | QueryOf<Messages>\n\ntype KeysOfUnion<Value> = Value extends Value ? keyof Value : never\ntype WithoutRoutingFields<Schemas extends PayloadSchemas> = {\n readonly [Name in keyof Schemas]: KeysOfUnion<z.output<Schemas[Name]>> &\n RoutingField extends never\n ? Schemas[Name]\n : never\n}\n\nfunction messageSchema<\n Kind extends MessageKind,\n Name extends string,\n Schema extends z.ZodType<object>,\n>(kind: Kind, name: Name, payload: Schema) {\n return z.intersection(envelopes[kind], z.object({ name: z.literal(name) })).and(payload)\n}\n\ntype CompleteSchemas<Kind extends MessageKind, Schemas extends PayloadSchemas> = {\n readonly [Name in keyof Schemas & string]: ReturnType<\n typeof messageSchema<Kind, Name, Schemas[Name]>\n >\n}\n\nfunction completeSchemas<Kind extends MessageKind, Schemas extends PayloadSchemas>(\n kind: Kind,\n schemas: Schemas | undefined,\n): CompleteSchemas<Kind, Schemas> {\n const entries = Object.entries<z.ZodType<object>>(schemas ?? {}).map(([name, payload]) => [\n name,\n messageSchema(kind, name, payload),\n ])\n // SAFETY: Each entry preserves its name and wraps its payload schema with the selected envelope.\n return Object.freeze(Object.fromEntries(entries)) as CompleteSchemas<Kind, Schemas>\n}\n\nfunction unionOf<Schemas extends SchemaMap>(schemas: Schemas): z.ZodUnion<SchemaOf<Schemas>[]> {\n // SAFETY: Object.values contains exactly the complete schemas indexed by this map's keys.\n return z.union(Object.values(schemas)) as z.ZodUnion<SchemaOf<Schemas>[]>\n}\n\nfunction collection<Maps extends SchemaMaps>(maps: Maps): MessageCollection<Maps> {\n return Object.freeze<MessageCollection<Maps>>({\n ...maps,\n [completed]: true,\n commandSchema: unionOf<Maps['commandSchemas']>(maps.commandSchemas),\n eventSchema: unionOf<Maps['eventSchemas']>(maps.eventSchemas),\n querySchema: unionOf<Maps['querySchemas']>(maps.querySchemas),\n // SAFETY: The queue union contains the command and event schemas from these maps, without rebuilding them.\n queueSchema: z.union([\n ...Object.values(maps.commandSchemas),\n ...Object.values(maps.eventSchemas),\n ]) as MessageCollection<Maps>['queueSchema'],\n createCommand: (name, payload, id = uuidv7()) => {\n // SAFETY: The typed payload supplies all non-envelope fields for this name; the factory supplies its envelope.\n return { ...payload, type: 'command', name, id } as z.output<\n Maps['commandSchemas'][typeof name]\n >\n },\n createEvent: (name, payload, id = uuidv7()) => {\n // SAFETY: The typed payload supplies all non-envelope fields for this name; the factory supplies its envelope.\n return { ...payload, type: 'event', name, id } as z.output<Maps['eventSchemas'][typeof name]>\n },\n createQuery: (name, payload) => {\n // SAFETY: The typed payload supplies all non-envelope fields for this name; a query has no ID.\n return { ...payload, type: 'query', name } as z.output<Maps['querySchemas'][typeof name]>\n },\n })\n}\n\n/** Build each complete schema once. Omitted kinds have empty maps and schemas that reject every input. */\nexport function defineMessages<\n const Commands extends PayloadSchemas = EmptySchemas,\n const Events extends PayloadSchemas = EmptySchemas,\n const Queries extends PayloadSchemas = EmptySchemas,\n>(definition: {\n readonly commands?: Commands & WithoutRoutingFields<Commands>\n readonly events?: Events & WithoutRoutingFields<Events>\n readonly queries?: Queries & WithoutRoutingFields<Queries>\n}) {\n return collection({\n commandSchemas: completeSchemas<'command', Commands>('command', definition.commands),\n eventSchemas: completeSchemas<'event', Events>('event', definition.events),\n querySchemas: completeSchemas<'query', Queries>('query', definition.queries),\n })\n}\n\n/** Two collections declare the same name within one message kind. */\nexport class DuplicateMessageNameError extends AppError {\n readonly _tag = 'DuplicateMessageNameError'\n readonly classification = 'terminal'\n\n /** Identify the duplicate kind and name so the application can correct its definitions. */\n constructor(\n readonly kind: MessageKind,\n readonly messageName: string,\n ) {\n super(`Duplicate ${kind} name: ${messageName}`)\n }\n}\n\ntype SchemaAtName<Maps, Name extends PropertyKey> =\n Maps extends Record<Name, infer Schema extends z.ZodType<object>> ? Schema : never\ntype MergedMaps<Collections extends readonly CompletedMessages[]> = {\n readonly [Key in keyof SchemaMaps]: {\n readonly [Name in KeysOfUnion<Collections[number][Key]> & string]: SchemaAtName<\n Collections[number][Key],\n Name\n >\n }\n}\ntype DuplicateNames<Collections extends readonly CompletedMessages[]> =\n Collections extends readonly [\n infer First extends CompletedMessages,\n ...infer Rest extends readonly CompletedMessages[],\n ]\n ?\n | {\n [Key in keyof SchemaMaps]: keyof First[Key] & KeysOfUnion<Rest[number][Key]>\n }[keyof SchemaMaps]\n | DuplicateNames<Rest>\n : never\n\nfunction mergeSchemas<\n Collections extends readonly CompletedMessages[],\n Key extends keyof SchemaMaps,\n>(collections: Collections, key: Key, kind: MessageKind): MergedMaps<Collections>[Key] {\n const merged = new Map<string, z.ZodType<object>>()\n for (const messages of collections) {\n if (!messages?.[completed])\n return panic('combineMessages requires completed message collections')\n for (const [name, schema] of Object.entries(messages[key])) {\n if (merged.has(name)) throw new DuplicateMessageNameError(kind, name)\n merged.set(name, schema)\n }\n }\n // SAFETY: Every schema comes from the selected complete map, and duplicate names are rejected before insertion.\n return Object.freeze(Object.fromEntries(merged)) as MergedMaps<Collections>[Key]\n}\n\n/**\n * Merge completed collections without rebuilding complete schemas.\n * @throws DuplicateMessageNameError when two collections declare the same name within one kind.\n */\nexport function combineMessages<const Collections extends readonly CompletedMessages[]>(\n ...collections: Collections & (DuplicateNames<Collections> extends never ? unknown : never)\n) {\n return collection({\n commandSchemas: mergeSchemas(collections, 'commandSchemas', 'command'),\n eventSchemas: mergeSchemas(collections, 'eventSchemas', 'event'),\n querySchemas: mergeSchemas(collections, 'querySchemas', 'query'),\n })\n}\n","import type { DomainEvent } from './messages.ts'\n\n/** What an aggregate's plain data must have: an identity. A branded id keeps its brand. */\nexport type EntityData = { readonly id: string }\n\n/**\n * The base of an aggregate: its identity, the events it raised, and the plain data a repository\n * stores. The subclass keeps its constructor private and declares `static restore(data: Data)`,\n * the one door a repository rebuilds it through. A repository drains the events after `save`.\n */\nexport abstract class Entity<Data extends EntityData, TEvent extends DomainEvent = DomainEvent> {\n private events: TEvent[] = []\n\n abstract readonly id: Data['id']\n\n /** Record one event with the state change that caused it. The unit of work commits both. */\n protected addEvent(event: TEvent): void {\n this.events.push(event)\n }\n\n /** A copy of the events raised since the last `clearEvents`. */\n collectEvents(): ReadonlyArray<TEvent> {\n return [...this.events]\n }\n\n /** Forget the raised events once the boundary has taken them. */\n clearEvents(): void {\n this.events = []\n }\n\n /** Plain data for the repository. The subclass's `restore(data)` accepts exactly this. */\n abstract toPlainObject(): Data\n}\n","/**\n * What one failure is, before any policy decides what to do about it.\n *\n * `transient`: the world may differ on the next attempt. `terminal`: repeating gives the\n * same answer. `unknown`: nobody judged this error, so it came from outside unwrapped.\n */\nexport type FailureClassification = 'transient' | 'terminal' | 'unknown'\n\n/**\n * Who is asking to repeat the work.\n *\n * An immediate owner holds a caller and a socket open. A durable owner already stored the\n * work, so it can afford to try again on a failure nobody classified.\n */\nexport type RetryOwner = 'immediate' | 'durable'\n\n/** Decide whether one retry owner may repeat a failed operation. */\nexport function shouldRetryFailure(args: {\n readonly classification: FailureClassification\n readonly repeatSafe: boolean\n readonly owner: RetryOwner\n}): boolean {\n if (!args.repeatSafe) return false\n if (args.classification === 'transient') return true\n if (args.classification === 'terminal') return false\n return args.owner === 'durable'\n}\n","/**\n * Messages that the platform-neutral transports raise for a failure that may pass.\n *\n * A boundary that knows its own runtime adds its own patterns before these.\n */\nconst TRANSIENT_TRANSPORT_PATTERNS = [\n /network/,\n /fetch failed/,\n /timeout/,\n /timed?\\s*out/,\n /connection.*(lost|reset|refused|closed|aborted)/,\n /econnreset/,\n /econnrefused/,\n /etimedout/,\n /eai_again/,\n]\n\n/** Cancellation is a decision, not a failure to repeat. */\nexport function isAbortError(cause: unknown): boolean {\n return cause instanceof Error && cause.name === 'AbortError'\n}\n\n/** Match known transient transport messages while excluding explicit cancellation. */\nexport function isTransientTransportError(cause: unknown): boolean {\n if (!(cause instanceof Error) || isAbortError(cause)) return false\n const message = cause.message.toLowerCase()\n return TRANSIENT_TRANSPORT_PATTERNS.some((pattern) => pattern.test(message))\n}\n","import { z } from 'zod'\n\n/** Stable Cloudflare messages that mean the runtime failed, not our code, and a repeat may pass. */\nexport const CLOUDFLARE_TRANSIENT_ERROR_PATTERNS = {\n networkConnectionLost: /network connection lost/,\n objectReset: /caused object to be reset/,\n codeUpdateReset: /reset because its code was updated/,\n objectMoved: /object has moved to a different machine/,\n internalWorkflows: /internal workflows error/,\n} as const\n\nconst TRANSIENT_PLATFORM_PATTERNS = [\n CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.objectReset,\n CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.codeUpdateReset,\n CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.objectMoved,\n CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.internalWorkflows,\n]\n\n// workerd stamps these flags as own properties on the error it throws across a binding.\nconst RetryableFlagSchema = z.object({ retryable: z.literal(true) })\nconst OverloadedFlagSchema = z.object({ overloaded: z.literal(true) })\nconst ObjectResetFlagSchema = z.object({ durableObjectReset: z.literal(true) })\n\n/** workerd stamps `retryable` on a failure it judged safe to repeat. */\nexport function isCloudflareRetryableError(cause: unknown): boolean {\n return RetryableFlagSchema.validate(cause)\n}\n\n/** workerd stamps `overloaded` when the target could not take the call. */\nexport function isCloudflareOverloadedError(cause: unknown): boolean {\n return OverloadedFlagSchema.validate(cause)\n}\n\n/** workerd stamps `durableObjectReset` when the object restarted during the call. */\nexport function isCloudflareObjectResetError(cause: unknown): boolean {\n return ObjectResetFlagSchema.validate(cause)\n}\n\n/** Match transient Cloudflare runtime evidence without the general transport patterns. */\nexport function isTransientCloudflareRuntimeError(cause: unknown): boolean {\n if (isCloudflareObjectResetError(cause)) return true\n if (!(cause instanceof Error)) return false\n const message = cause.message.toLowerCase()\n return TRANSIENT_PLATFORM_PATTERNS.some((pattern) => pattern.test(message))\n}\n","import { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\nimport {\n isCloudflareOverloadedError,\n isCloudflareRetryableError,\n isTransientCloudflareRuntimeError,\n} from './cloudflare-classification.ts'\nimport type { FailureClassification } from './failure-classification.ts'\nimport { isAbortError, isTransientTransportError } from './transport-classification.ts'\n\n/** A boundary's own rule for its raw errors. `undefined` means the boundary has no opinion. */\nexport type BoundaryErrorClassifier = (cause: unknown) => FailureClassification | undefined\n\n/**\n * Classify one raw external error: the boundary's own rule first, then Cloudflare's signals,\n * then the transport patterns. Cancellation is terminal even when Cloudflare marks it retryable.\n */\nexport function classifyBoundaryError(args: {\n readonly cause: unknown\n readonly classifyBoundary: BoundaryErrorClassifier\n readonly includeCloudflare: boolean\n}): FailureClassification {\n const boundary = args.classifyBoundary(args.cause)\n if (boundary !== undefined) return boundary\n\n if (isAbortError(args.cause)) return 'terminal'\n\n if (\n args.includeCloudflare &&\n (isCloudflareOverloadedError(args.cause) ||\n isCloudflareRetryableError(args.cause) ||\n isTransientCloudflareRuntimeError(args.cause))\n ) {\n return 'transient'\n }\n\n if (isTransientTransportError(args.cause)) return 'transient'\n\n return 'unknown'\n}\n\n/**\n * Judge a final failure for its durable retry owner. An `AppError` carries its own answer.\n * A raw throw nobody judged is unknown, so an immediate owner stops and a durable one may repeat.\n */\nexport function classifyFailure(cause: unknown): FailureClassification {\n if (cause instanceof AppError) return cause.classification\n if (isAbortError(cause)) return 'terminal'\n if (isTransientCloudflareRuntimeError(cause)) return 'transient'\n return 'unknown'\n}\n\nconst RetryAfterSchema = z.object({ retryAfter: z.number().positive() })\n\n/** Read a positive server-advertised retry delay in seconds, such as `RateLimitError.retryAfter`. */\nexport function retryAfterSecondsOf(cause: unknown): number | null {\n const result = RetryAfterSchema.safeParse(cause)\n return result.success ? result.data.retryAfter : null\n}\n","import { panic } from 'better-result'\n\n/** Uniform jitter within one fixed window. */\nexport function spreadJitterMs(spreadMs: number): number {\n if (!Number.isFinite(spreadMs) || spreadMs < 0) {\n return panic('spreadMs must be a non-negative number')\n }\n return Math.floor(Math.random() * spreadMs)\n}\n\n/**\n * Half the capped exponential delay, plus jitter over the other half. Decorrelates concurrent\n * repeats like full jitter, but keeps a floor: use it when few attempts remain before work is dropped.\n */\nexport function exponentialEqualJitterMs(\n baseDelayMs: number,\n maxDelayMs: number,\n attempt: number,\n): number {\n const halfCapMs = exponentialDelayCapMs(baseDelayMs, maxDelayMs, attempt) / 2\n return Math.floor(halfCapMs) + spreadJitterMs(halfCapMs)\n}\n\n/** Capped exponential delay for a durable retry recorded in storage. */\nexport function exponentialDelayCapMs(\n baseDelayMs: number,\n maxDelayMs: number,\n attempt: number,\n): number {\n if (!Number.isSafeInteger(attempt) || attempt < 1) {\n return panic('attempt must be a positive integer')\n }\n return Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs)\n}\n","import type { LogEntry, LogFields, LogFormat, LogLevel, LogSink } from './logger.ts'\n\nconst METHOD = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n} as const satisfies Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'>\n\nconst ESC = String.fromCharCode(27)\nconst RESET = `${ESC}[0m`\nconst LEVEL_COLOR = {\n DEBUG: `${ESC}[2;36m`,\n INFO: `${ESC}[34m`,\n WARN: `${ESC}[33m`,\n ERROR: `${ESC}[1;31m`,\n} satisfies Record<LogLevel, string>\n\nlet format: LogFormat = 'json'\n\nexport function setConsoleLogFormat(value: LogFormat): void {\n format = value\n}\n\nfunction contextOf(entry: LogEntry): LogFields | undefined {\n const context = { ...entry.attributes }\n if (entry.userId !== undefined) context.userId = entry.userId\n return Object.keys(context).length === 0 ? undefined : context\n}\n\nfunction jsonEntry(entry: LogEntry): LogEntry {\n if (!(entry.error instanceof Error)) return entry\n const error = { name: entry.error.name, message: entry.error.message, stack: entry.error.stack }\n return { ...entry, error }\n}\n\n/** Write one structured record or one readable development entry to `console`. */\nexport const consoleSink: LogSink = (entry) => {\n const write = console[METHOD[entry.level]]\n if (format === 'json') {\n write(jsonEntry(entry))\n return\n }\n\n const context = contextOf(entry)\n const values = context === undefined ? [] : [context]\n const errors = entry.error === undefined ? [] : [entry.error]\n if (format === 'pretty-browser') {\n write(\n `${entry.timestamp} [${entry.level}] [${entry.module}] ${entry.event}`,\n ...values,\n ...errors,\n )\n return\n }\n write(\n `${ESC}[90m${entry.timestamp}${RESET} ${LEVEL_COLOR[entry.level]}[${entry.level}]${RESET} ${ESC}[34m[${entry.module}]${RESET} ${entry.event}`,\n ...values,\n ...errors,\n )\n}\n","import { consoleSink, setConsoleLogFormat } from './console-log-sink.ts'\n\n/** One JSON-compatible value in a normal log field. */\nexport type LogValue =\n | string\n | number\n | boolean\n | null\n | readonly LogValue[]\n | { readonly [key: string]: LogValue }\n\n/** Flat fields for one log call. Only `error` can contain an arbitrary value. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- A logger accepts caller-owned fields at its public boundary.\nexport type LogFields = Readonly<Record<string, unknown>>\n\n/** Supported log levels in ascending order. */\nexport const LogLevel = {\n DEBUG: 'DEBUG',\n INFO: 'INFO',\n WARN: 'WARN',\n ERROR: 'ERROR',\n} as const\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]\n\n/** The minimum emitted level, or `OFF` for no console output. */\nexport type LogThreshold = LogLevel | 'OFF'\n\n/** Explicit output formats for production, browser development, and terminal development. */\nexport type LogFormat = 'json' | 'pretty-browser' | 'pretty-terminal'\n\n/** Process-wide logger settings supplied at startup. */\nexport interface LoggerSettings {\n readonly level?: LogThreshold\n readonly format?: LogFormat\n}\n\n/** One structured record sent to a log sink. */\nexport type LogEntry = {\n readonly timestamp: string\n readonly level: LogLevel\n readonly module: string\n readonly event: string\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- The entry keeps caller-owned fields for its sink.\n readonly attributes: LogFields\n readonly userId?: string\n readonly error?: unknown\n}\n\n/** The original error and fields sent to an error service. */\nexport interface ErrorCaptureEntry {\n readonly error: unknown\n readonly userId: string | undefined\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Sentry accepts the caller-owned fields as extra context.\n readonly attributes: LogFields\n}\n\n/** A function that forwards one error to an error service. */\nexport type LoggerErrorHook = (entry: ErrorCaptureEntry) => void\n\n/** A destination for structured log records. */\nexport type LogSink = (entry: LogEntry) => void\n\n/** The common flat logger API for all levels. */\nexport interface Logger {\n debug(event: string, fields?: LogFields): void\n info(event: string, fields?: LogFields): void\n warn(event: string, fields?: LogFields): void\n error(event: string, fields?: LogFields): void\n}\n\nconst LEVELS = Object.values(LogLevel)\nlet threshold: LogThreshold = LogLevel.INFO\nlet logSink: LogSink = consoleSink\nlet errorHook: LoggerErrorHook | null = null\n\n/** Set the process-wide level and output format. Omitted fields restore production defaults. */\nexport function configureLogger(settings: LoggerSettings): void {\n threshold = settings.level ?? LogLevel.INFO\n setConsoleLogFormat(settings.format ?? 'json')\n}\n\n/** Set the process-wide log destination. */\nexport function setLogSink(sink: LogSink): void {\n logSink = sink\n}\n\n/** Set or clear the process-wide error service hook. */\nexport function setLoggerErrorHook(hook: LoggerErrorHook | null): void {\n errorHook = hook\n}\n\n/* oxlint-disable anti-slop/no-runtime-typeof -- The logger validates its reserved userId field. */\nfunction splitFields(fields: LogFields): ErrorCaptureEntry {\n const { error, userId, ...attributes } = fields\n return { error, userId: typeof userId === 'string' ? userId : undefined, attributes }\n}\n/* oxlint-enable anti-slop/no-runtime-typeof */\n\nfunction writeLog(module: string, level: LogLevel, event: string, fields: LogFields): void {\n if (threshold === 'OFF' || LEVELS.indexOf(level) < LEVELS.indexOf(threshold)) return\n\n const { error, userId, attributes } = splitFields(fields)\n let entry: LogEntry = { timestamp: new Date().toISOString(), level, module, event, attributes }\n if (userId !== undefined) entry = { ...entry, userId }\n if (error !== undefined) entry = { ...entry, error }\n try {\n logSink(entry)\n } catch {\n // A diagnostic failure must not change application control flow.\n }\n}\n\n/** Create a logger for one module. */\nexport function createLogger(module: string): Logger {\n return {\n debug: (event, fields = {}) => writeLog(module, LogLevel.DEBUG, event, fields),\n info: (event, fields = {}) => writeLog(module, LogLevel.INFO, event, fields),\n warn: (event, fields = {}) => writeLog(module, LogLevel.WARN, event, fields),\n error: (event, fields = {}) => {\n writeLog(module, LogLevel.ERROR, event, fields)\n const capture = splitFields(fields)\n if (errorHook === null || capture.error === undefined) return\n try {\n errorHook(capture)\n } catch {\n // An error service failure must not change application control flow.\n }\n },\n }\n}\n\nexport { consoleSink }\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAsB,WAAtB,cAAuC,MAAM;CAI3C,IAAa,OAAe;EAC1B,OAAO,KAAK;CACd;AACF;;;;;ACdA,IAAa,4BAAb,cAA+C,SAAS;CAKjC;CAJrB,AAAS,OAAO;CAChB,AAAS,iBAAiB;;CAG1B,YAAY,AAAS,KAAa;EAChC,MAAM,GAAG,IAAI,aAAa;EADP;CAErB;AACF;;;;;ACgBA,MAAa,yBAAyB,EAAE,KAAK,CAAC,CAAC,MAA0B;;;;;ACxBzE,MAAa,qBAAqB,EAAE,MAAM,CAAC,CAAC,MAAsB;;;;ACKlE,MAAM,iBAAiB;;AAGvB,IAAa,kCAAb,cAAqD,SAAS;CAIvC;CAHrB,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,YAAY,AAAS,QAAgB;EACnC,MAAM,wCAAwC,eAAe,YAAY;EADtD;CAErB;AACF;;;;;;;;AASA,SAAgB,oBAAoB,OAAe,IAAiC;CAClF,MAAM,MAAM,GAAG,MAAM,GAAG;CACxB,IAAI,MAAM,WAAW,KAAK,GAAG,WAAW,KAAK,IAAI,SAAS,gBACxD,MAAM,IAAI,gCAAgC,IAAI,MAAM;CAEtD,OAAO;AACT;;;;ACrBA,MAAM,2BAA2B;CAC/B,cAA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OAAO;GACnB,QAAQ,CAER;EACF;CACF;AACF"}
package/dist/core.js CHANGED
@@ -1,3 +1,3 @@
1
- import { $ as EmailAddressSchema, A as sharedErrors, B as ServiceUnavailableError, C as combineMessages, D as unreachable, E as notImplemented, F as RequestTimeoutError, G as RecordEmailEventPayloadSchema, H as StaleSessionError, I as ResourceNotFoundError, J as parseBounceType, K as BounceTypeSchema, L as UpgradeRequiredError, M as ValidationProblemDetailsSchema, N as ValidationProblemErrorSchema, O as DatabaseError, P as MalformedRequestError, Q as emailIdempotencyKey, R as ValidationError, S as DuplicateMessageNameError, T as defineId, U as RateLimitError, V as NotAuthorizedError, W as AuthenticationError, X as EmailServiceError, Y as shouldUpdateBounce, Z as InvalidEmailIdempotencyKeyError, _ as isTransientCloudflareRuntimeError, a as setLoggerErrorHook, b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, et as AnalyticsEventIdSchema, f as retryAfterSecondsOf, g as isCloudflareRetryableError, h as isCloudflareOverloadedError, i as setLogSink, j as ProblemDetailsSchema, k as defineErrors, l as spreadJitterMs, m as isCloudflareObjectResetError, n as configureLogger, nt as AppError, o as consoleSink, p as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, q as isEmailDeliverable, r as createLogger, s as exponentialDelayCapMs, t as LogLevel, tt as MissingConfigurationError, u as classifyBoundaryError, v as isAbortError, w as defineMessages, x as Entity, y as isTransientTransportError, z as InternalServerError } from "./core-BT1dSEQI.js";
1
+ import { $ as EmailAddressSchema, A as sharedErrors, B as ServiceUnavailableError, C as combineMessages, D as unreachable, E as notImplemented, F as RequestTimeoutError, G as RecordEmailEventPayloadSchema, H as StaleSessionError, I as ResourceNotFoundError, J as parseBounceType, K as BounceTypeSchema, L as UpgradeRequiredError, M as ValidationProblemDetailsSchema, N as ValidationProblemErrorSchema, O as DatabaseError, P as MalformedRequestError, Q as emailIdempotencyKey, R as ValidationError, S as DuplicateMessageNameError, T as defineId, U as RateLimitError, V as NotAuthorizedError, W as AuthenticationError, X as EmailServiceError, Y as shouldUpdateBounce, Z as InvalidEmailIdempotencyKeyError, _ as isTransientCloudflareRuntimeError, a as setLoggerErrorHook, b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, et as AnalyticsEventIdSchema, f as retryAfterSecondsOf, g as isCloudflareRetryableError, h as isCloudflareOverloadedError, i as setLogSink, j as ProblemDetailsSchema, k as defineErrors, l as spreadJitterMs, m as isCloudflareObjectResetError, n as configureLogger, nt as AppError, o as consoleSink, p as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, q as isEmailDeliverable, r as createLogger, s as exponentialDelayCapMs, t as LogLevel, tt as MissingConfigurationError, u as classifyBoundaryError, v as isAbortError, w as defineMessages, x as Entity, y as isTransientTransportError, z as InternalServerError } from "./core-BIas38R0.js";
2
2
 
3
3
  export { AnalyticsEventIdSchema, AppError, AuthenticationError, BounceTypeSchema, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, DatabaseError, DuplicateMessageNameError, EmailAddressSchema, EmailServiceError, Entity, InternalServerError, InvalidEmailIdempotencyKeyError, LogLevel, MalformedRequestError, MissingConfigurationError, NotAuthorizedError, ProblemDetailsSchema, RateLimitError, RecordEmailEventPayloadSchema, RequestTimeoutError, ResourceNotFoundError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, ValidationProblemDetailsSchema, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, combineMessages, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, emailIdempotencyKey, exponentialDelayCapMs, exponentialEqualJitterMs, isAbortError, isCloudflareObjectResetError, isCloudflareOverloadedError, isCloudflareRetryableError, isEmailDeliverable, isTransientCloudflareRuntimeError, isTransientTransportError, notImplemented, parseBounceType, retryAfterSecondsOf, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, shouldUpdateBounce, spreadJitterMs, unreachable };
package/dist/http.js CHANGED
@@ -1,5 +1,5 @@
1
- import { r as createLogger } from "./core-BT1dSEQI.js";
2
- import { t as WebhookVerificationError } from "./webhook-verification-qSFXv5H3.js";
1
+ import { r as createLogger } from "./core-BIas38R0.js";
2
+ import { t as WebhookVerificationError } from "./webhook-verification-CEUARY9X.js";
3
3
  import { StatusCodes } from "http-status-codes";
4
4
 
5
5
  //#region src/infrastructure/http/webhook-handler.ts
@@ -96,6 +96,10 @@ type OutboundEmail = {
96
96
  readonly tags?: Readonly<Record<string, string>>;
97
97
  readonly attachments?: readonly EmailAttachment[];
98
98
  };
99
+ /** Received email headers, without the body or attachments. */
100
+ type ReceivedEmail = {
101
+ readonly headers: Readonly<Record<string, string>>;
102
+ };
99
103
  /** The provider accepted the email and assigned its id. */
100
104
  type EmailAccepted = {
101
105
  readonly providerId: string;
@@ -391,5 +395,5 @@ declare class UnitOfWorkAlreadyActiveError extends AppError {
391
395
  constructor();
392
396
  }
393
397
  //#endregion
394
- export { EventHandler as $, IOutboxRepository as A, OutboundEmail as B, UnitOfWorkDeps as C, OutboxRelay as D, IOutboxRelay as E, IEventCollector as F, MetricAttributeValue as G, ObservabilityScope as H, EmailAccepted as I, MetricsService as J, MetricAttributes as K, EmailAttachment as L, OutboxClaim as M, OutboxMessage as N, OutboxRelayOptions as O, IMessageStore as P, CommandHandler as Q, IEmailService as R, UnitOfWork as S, IOutboxPublisher as T, ObservabilityService as U, RecordingEmailService as V, ObservabilityUser as W, AnalyticsService as X, NULL_METRICS_SERVICE as Y, NULL_ANALYTICS as Z, RecordEmailEventCommand as _, OutboxRetentionResult as a, recordEmailEvent as b, CommandRegistry as c, MessageRegistry as d, QueryHandler as et, MessageResult as f, IEmailDeliverabilityStore as g, EmailBounceRecord as h, OutboxRetentionOptions as i, IOutboxRetentionRepository as j, DeadLetterReason as k, EventRegistry as l, RegistryMessage as m, MessageAlreadyProcessedError as n, IMessageBus as o, QueryRegistry as p, MetricOptions as q, OutboxRetention as r, MessageBus as s, UnitOfWorkAlreadyActiveError as t, Handlers as u, RecordEmailEventDeps as v, ITransaction as w, IUnitOfWork as x, RecordEmailEventRepos as y, MimeType as z };
395
- //# sourceMappingURL=index-CYHXOH08.d.ts.map
398
+ export { CommandHandler as $, IOutboxRepository as A, OutboundEmail as B, UnitOfWorkDeps as C, OutboxRelay as D, IOutboxRelay as E, IEventCollector as F, ObservabilityUser as G, RecordingEmailService as H, EmailAccepted as I, MetricOptions as J, MetricAttributeValue as K, EmailAttachment as L, OutboxClaim as M, OutboxMessage as N, OutboxRelayOptions as O, IMessageStore as P, NULL_ANALYTICS as Q, IEmailService as R, UnitOfWork as S, IOutboxPublisher as T, ObservabilityScope as U, ReceivedEmail as V, ObservabilityService as W, NULL_METRICS_SERVICE as X, MetricsService as Y, AnalyticsService as Z, RecordEmailEventCommand as _, OutboxRetentionResult as a, recordEmailEvent as b, CommandRegistry as c, MessageRegistry as d, EventHandler as et, MessageResult as f, IEmailDeliverabilityStore as g, EmailBounceRecord as h, OutboxRetentionOptions as i, IOutboxRetentionRepository as j, DeadLetterReason as k, EventRegistry as l, RegistryMessage as m, MessageAlreadyProcessedError as n, IMessageBus as o, QueryRegistry as p, MetricAttributes as q, OutboxRetention as r, MessageBus as s, UnitOfWorkAlreadyActiveError as t, QueryHandler as tt, Handlers as u, RecordEmailEventDeps as v, ITransaction as w, IUnitOfWork as x, RecordEmailEventRepos as y, MimeType as z };
399
+ //# sourceMappingURL=index-tNZHSCpJ.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-tNZHSCpJ.d.ts","names":[],"sources":["../src/application/handlers.ts","../src/application/analytics-service.ts","../src/application/metrics-service.ts","../src/application/observability-service.ts","../src/application/email-service.ts","../src/application/event-collector.ts","../src/application/message-store.ts","../src/application/outbox-repository.ts","../src/application/outbox-relay.ts","../src/application/transaction.ts","../src/application/unit-of-work.ts","../src/application/record-email-event.ts","../src/application/registry.ts","../src/application/message-bus.ts","../src/application/outbox-retention.ts","../src/application/message-already-processed.error.ts","../src/application/unit-of-work.errors.ts"],"mappings":";;;;;;KAMY,eAAe,iBAAiB,eAA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;UAWM;;;;;KCpEJ;WACD;WACA;WACA;WACA;WACA;;;KAIC;WACD;WACA;WACA;;;cAIE;mBAIQ;mBAHF;EAEjB,YACmB,YAAY,4BAC7B,UAAS;;EAYL,MAAM,IAAI,OAAO,QAAQ;UAcjB;;;;;cC/CH,qCAAqC;WAKrC,WAAW;WAJb;WACA;EAET,YACW,WAAW,WACpB;aAAqB;;;SAMhB,KAAK,gBAAgB,WAAW,YAAY;;;;;cCZxC,qCAAqC;WACvC;WACA;EAET"}
@@ -1,4 +1,4 @@
1
- import { t as UnitOfWorkAlreadyActiveError } from "./application-Dg1jIKPe.js";
1
+ import { t as UnitOfWorkAlreadyActiveError } from "./application-D5tNECiC.js";
2
2
  import { panic } from "better-result";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
 
@@ -54,4 +54,4 @@ const OUTBOX_REPOSITORY_DEFAULTS = {
54
54
 
55
55
  //#endregion
56
56
  export { stageD1Statement as a, runWithUnitOfWorkContext as i, collectD1Statements as n, eventCollector as r, OUTBOX_REPOSITORY_DEFAULTS as t };
57
- //# sourceMappingURL=outbox-repository-options-B8TnAE1h.js.map
57
+ //# sourceMappingURL=outbox-repository-options-D0R8z1yS.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"outbox-repository-options-B8TnAE1h.js","names":[],"sources":["../src/infrastructure/unit-of-work-context.ts","../src/infrastructure/outbox-repository-options.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { panic } from 'better-result'\nimport type { BatchItem } from 'drizzle-orm/batch'\n\nimport { UnitOfWorkAlreadyActiveError, type IEventCollector } from '@/application'\nimport type { DomainEvent } from '@/core'\n\ntype UnitOfWorkContext = { readonly events: DomainEvent[] } & (\n | { readonly database: 'd1'; readonly statements: BatchItem<'sqlite'>[] }\n | { readonly database: 'postgres' }\n)\n\n// One async scope isolates events and D1 statements and rejects nesting across both adapters.\nconst storage = new AsyncLocalStorage<UnitOfWorkContext>()\n\n/** Reject nested transactions before database work starts; preserve independent concurrent execution. */\nexport async function runWithUnitOfWorkContext<T>(\n database: UnitOfWorkContext['database'],\n work: () => Promise<T>,\n): Promise<T> {\n if (storage.getStore() !== undefined) throw new UnitOfWorkAlreadyActiveError()\n const context: UnitOfWorkContext =\n database === 'd1' ? { database, events: [], statements: [] } : { database, events: [] }\n return storage.run(context, work)\n}\n\n/** Inject this shared scope into the unit of work and expose its emitter to application handlers. */\nexport const eventCollector: IEventCollector = {\n emit(event) {\n currentContext().events.push(event)\n },\n collect() {\n return [...currentContext().events]\n },\n}\n\n/** Queue one native D1 statement for the active batch; other contexts cannot accept D1 writes. */\nexport function stageD1Statement(statement: BatchItem<'sqlite'>): void {\n d1Context().statements.push(statement)\n}\n\n/** Read the active D1 batch in staging order for commit. */\nexport function collectD1Statements(): ReadonlyArray<BatchItem<'sqlite'>> {\n return [...d1Context().statements]\n}\n\nfunction d1Context(): Extract<UnitOfWorkContext, { database: 'd1' }> {\n const context = currentContext()\n if (context.database !== 'd1') return panic('D1 statements require a D1 unit of work')\n return context\n}\n\nfunction currentContext(): UnitOfWorkContext {\n return storage.getStore() ?? panic('operation requires an active unit of work')\n}\n","/** Shared lease and delay defaults for both database adapters. */\nexport const OUTBOX_REPOSITORY_DEFAULTS = {\n leaseMs: 60_000,\n retryBaseDelayMs: 1_000,\n retryMaxDelayMs: 60_000,\n}\n\n/** Override lease and delay limits at the composition root. */\nexport type OutboxRepositoryOptions = Readonly<Partial<typeof OUTBOX_REPOSITORY_DEFAULTS>>\n"],"mappings":";;;;;AAcA,MAAM,UAAU,IAAI,kBAAqC;;AAGzD,eAAsB,yBACpB,UACA,MACY;CACZ,IAAI,QAAQ,SAAS,MAAM,QAAW,MAAM,IAAI,6BAA6B;CAC7E,MAAM,UACJ,aAAa,OAAO;EAAE;EAAU,QAAQ,CAAC;EAAG,YAAY,CAAC;CAAE,IAAI;EAAE;EAAU,QAAQ,CAAC;CAAE;CACxF,OAAO,QAAQ,IAAI,SAAS,IAAI;AAClC;;AAGA,MAAa,iBAAkC;CAC7C,KAAK,OAAO;EACV,eAAe,CAAC,CAAC,OAAO,KAAK,KAAK;CACpC;CACA,UAAU;EACR,OAAO,CAAC,GAAG,eAAe,CAAC,CAAC,MAAM;CACpC;AACF;;AAGA,SAAgB,iBAAiB,WAAsC;CACrE,UAAU,CAAC,CAAC,WAAW,KAAK,SAAS;AACvC;;AAGA,SAAgB,sBAA0D;CACxE,OAAO,CAAC,GAAG,UAAU,CAAC,CAAC,UAAU;AACnC;AAEA,SAAS,YAA4D;CACnE,MAAM,UAAU,eAAe;CAC/B,IAAI,QAAQ,aAAa,MAAM,OAAO,MAAM,yCAAyC;CACrF,OAAO;AACT;AAEA,SAAS,iBAAoC;CAC3C,OAAO,QAAQ,SAAS,KAAK,MAAM,2CAA2C;AAChF;;;;;ACtDA,MAAa,6BAA6B;CACxC,SAAS;CACT,kBAAkB;CAClB,iBAAiB;AACnB"}
1
+ {"version":3,"file":"outbox-repository-options-D0R8z1yS.js","names":[],"sources":["../src/infrastructure/unit-of-work-context.ts","../src/infrastructure/outbox-repository-options.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { panic } from 'better-result'\nimport type { BatchItem } from 'drizzle-orm/batch'\n\nimport { UnitOfWorkAlreadyActiveError, type IEventCollector } from '@/application'\nimport type { DomainEvent } from '@/core'\n\ntype UnitOfWorkContext = { readonly events: DomainEvent[] } & (\n | { readonly database: 'd1'; readonly statements: BatchItem<'sqlite'>[] }\n | { readonly database: 'postgres' }\n)\n\n// One async scope isolates events and D1 statements and rejects nesting across both adapters.\nconst storage = new AsyncLocalStorage<UnitOfWorkContext>()\n\n/** Reject nested transactions before database work starts; preserve independent concurrent execution. */\nexport async function runWithUnitOfWorkContext<T>(\n database: UnitOfWorkContext['database'],\n work: () => Promise<T>,\n): Promise<T> {\n if (storage.getStore() !== undefined) throw new UnitOfWorkAlreadyActiveError()\n const context: UnitOfWorkContext =\n database === 'd1' ? { database, events: [], statements: [] } : { database, events: [] }\n return storage.run(context, work)\n}\n\n/** Inject this shared scope into the unit of work and expose its emitter to application handlers. */\nexport const eventCollector: IEventCollector = {\n emit(event) {\n currentContext().events.push(event)\n },\n collect() {\n return [...currentContext().events]\n },\n}\n\n/** Queue one native D1 statement for the active batch; other contexts cannot accept D1 writes. */\nexport function stageD1Statement(statement: BatchItem<'sqlite'>): void {\n d1Context().statements.push(statement)\n}\n\n/** Read the active D1 batch in staging order for commit. */\nexport function collectD1Statements(): ReadonlyArray<BatchItem<'sqlite'>> {\n return [...d1Context().statements]\n}\n\nfunction d1Context(): Extract<UnitOfWorkContext, { database: 'd1' }> {\n const context = currentContext()\n if (context.database !== 'd1') return panic('D1 statements require a D1 unit of work')\n return context\n}\n\nfunction currentContext(): UnitOfWorkContext {\n return storage.getStore() ?? panic('operation requires an active unit of work')\n}\n","/** Shared lease and delay defaults for both database adapters. */\nexport const OUTBOX_REPOSITORY_DEFAULTS = {\n leaseMs: 60_000,\n retryBaseDelayMs: 1_000,\n retryMaxDelayMs: 60_000,\n}\n\n/** Override lease and delay limits at the composition root. */\nexport type OutboxRepositoryOptions = Readonly<Partial<typeof OUTBOX_REPOSITORY_DEFAULTS>>\n"],"mappings":";;;;;AAcA,MAAM,UAAU,IAAI,kBAAqC;;AAGzD,eAAsB,yBACpB,UACA,MACY;CACZ,IAAI,QAAQ,SAAS,MAAM,QAAW,MAAM,IAAI,6BAA6B;CAC7E,MAAM,UACJ,aAAa,OAAO;EAAE;EAAU,QAAQ,CAAC;EAAG,YAAY,CAAC;CAAE,IAAI;EAAE;EAAU,QAAQ,CAAC;CAAE;CACxF,OAAO,QAAQ,IAAI,SAAS,IAAI;AAClC;;AAGA,MAAa,iBAAkC;CAC7C,KAAK,OAAO;EACV,eAAe,CAAC,CAAC,OAAO,KAAK,KAAK;CACpC;CACA,UAAU;EACR,OAAO,CAAC,GAAG,eAAe,CAAC,CAAC,MAAM;CACpC;AACF;;AAGA,SAAgB,iBAAiB,WAAsC;CACrE,UAAU,CAAC,CAAC,WAAW,KAAK,SAAS;AACvC;;AAGA,SAAgB,sBAA0D;CACxE,OAAO,CAAC,GAAG,UAAU,CAAC,CAAC,UAAU;AACnC;AAEA,SAAS,YAA4D;CACnE,MAAM,UAAU,eAAe;CAC/B,IAAI,QAAQ,aAAa,MAAM,OAAO,MAAM,yCAAyC;CACrF,OAAO;AACT;AAEA,SAAS,iBAAoC;CAC3C,OAAO,QAAQ,SAAS,KAAK,MAAM,2CAA2C;AAChF;;;;;ACtDA,MAAa,6BAA6B;CACxC,SAAS;CACT,kBAAkB;CAClB,iBAAiB;AACnB"}
@@ -1,5 +1,5 @@
1
1
  import "./index-DUFS0SJ_.js";
2
- import { F as IEventCollector } from "./index-CYHXOH08.js";
2
+ import { F as IEventCollector } from "./index-tNZHSCpJ.js";
3
3
  import { BatchItem } from "drizzle-orm/batch";
4
4
  //#region src/infrastructure/drizzle-schema.d.ts
5
5
  /**
@@ -23,4 +23,4 @@ declare const OUTBOX_REPOSITORY_DEFAULTS: {
23
23
  type OutboxRepositoryOptions = Readonly<Partial<typeof OUTBOX_REPOSITORY_DEFAULTS>>;
24
24
  //#endregion
25
25
  export { eventCollector as n, DrizzleSchema as r, OutboxRepositoryOptions as t };
26
- //# sourceMappingURL=outbox-repository-options-DjBgFhMi.d.ts.map
26
+ //# sourceMappingURL=outbox-repository-options-_B8l8l6l.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"outbox-repository-options-DjBgFhMi.d.ts","names":[],"sources":["../src/infrastructure/drizzle-schema.ts","../src/infrastructure/unit-of-work-context.ts","../src/infrastructure/outbox-repository-options.ts"],"mappings":";;;;;;;;KAKY,gBAAgB;;;;cCuBf,gBAAgB;;;;cC3BhB;EACX;EACA;EACA;;;KAIU,0BAA0B,SAAS,eAAe"}
1
+ {"version":3,"file":"outbox-repository-options-_B8l8l6l.d.ts","names":[],"sources":["../src/infrastructure/drizzle-schema.ts","../src/infrastructure/unit-of-work-context.ts","../src/infrastructure/outbox-repository-options.ts"],"mappings":";;;;;;;;KAKY,gBAAgB;;;;cCuBf,gBAAgB;;;;cC3BhB;EACX;EACA;EACA;;;KAIU,0BAA0B,SAAS,eAAe"}
@@ -1,6 +1,6 @@
1
1
  import { W as DomainEvent, nt as DatabaseFailure, q as MessageId, tt as DatabaseError } from "./index-DUFS0SJ_.js";
2
- import { A as IOutboxRepository, M as OutboxClaim, N as OutboxMessage, P as IMessageStore, k as DeadLetterReason, w as ITransaction } from "./index-CYHXOH08.js";
3
- import { n as eventCollector, r as DrizzleSchema, t as OutboxRepositoryOptions } from "./outbox-repository-options-DjBgFhMi.js";
2
+ import { A as IOutboxRepository, M as OutboxClaim, N as OutboxMessage, P as IMessageStore, k as DeadLetterReason, w as ITransaction } from "./index-tNZHSCpJ.js";
3
+ import { n as eventCollector, r as DrizzleSchema, t as OutboxRepositoryOptions } from "./outbox-repository-options-_B8l8l6l.js";
4
4
  import { ExtractTablesWithRelations } from "drizzle-orm";
5
5
  import { PostgresJsDatabase, PostgresJsTransaction, drizzle } from "drizzle-orm/postgres-js";
6
6
  //#region src/infrastructure/postgres/postgres-database-types.d.ts
package/dist/postgres.js CHANGED
@@ -1,6 +1,6 @@
1
- import { O as DatabaseError, nt as AppError, s as exponentialDelayCapMs } from "./core-BT1dSEQI.js";
2
- import { o as MessageAlreadyProcessedError } from "./application-Dg1jIKPe.js";
3
- import { i as runWithUnitOfWorkContext, r as eventCollector, t as OUTBOX_REPOSITORY_DEFAULTS } from "./outbox-repository-options-B8TnAE1h.js";
1
+ import { O as DatabaseError, nt as AppError, s as exponentialDelayCapMs } from "./core-BIas38R0.js";
2
+ import { o as MessageAlreadyProcessedError } from "./application-D5tNECiC.js";
3
+ import { i as runWithUnitOfWorkContext, r as eventCollector, t as OUTBOX_REPOSITORY_DEFAULTS } from "./outbox-repository-options-D0R8z1yS.js";
4
4
  import { Result } from "better-result";
5
5
  import { DrizzleQueryError } from "drizzle-orm/errors";
6
6
  import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
@@ -1,4 +1,4 @@
1
- import { J as MetricsService, q as MetricOptions } from "../index-CYHXOH08.js";
1
+ import { J as MetricOptions, Y as MetricsService } from "../index-tNZHSCpJ.js";
2
2
  import { PostHog } from "posthog-node";
3
3
  //#region src/infrastructure/posthog/metrics.d.ts
4
4
  /** PostHog Metrics with Worker lifetime management, ported from Typist's metrics-service.ts. */