better-ship 0.14.0 → 0.16.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 (68) hide show
  1. package/dist/{application-C4JOf71r.js → application-Cf9SER-i.js} +2 -2
  2. package/dist/application-Cf9SER-i.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.d.ts +1 -1
  6. package/dist/better-auth/apple-client-secret.js +1 -1
  7. package/dist/better-auth/auth-client.js +1 -1
  8. package/dist/better-auth/rate-limit.d.ts +1 -1
  9. package/dist/better-auth/rate-limit.js +1 -1
  10. package/dist/better-auth.js +1 -1
  11. package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
  12. package/dist/cloudflare/auth-secondary-storage.js +1 -1
  13. package/dist/cloudflare/durable-object-client.d.ts +18 -0
  14. package/dist/cloudflare/durable-object-client.d.ts.map +1 -0
  15. package/dist/cloudflare/durable-object-client.js +46 -0
  16. package/dist/cloudflare/durable-object-client.js.map +1 -0
  17. package/dist/cloudflare/durable-object-errors.d.ts +40 -0
  18. package/dist/cloudflare/durable-object-errors.d.ts.map +1 -0
  19. package/dist/cloudflare/durable-object-errors.js +48 -0
  20. package/dist/cloudflare/durable-object-errors.js.map +1 -0
  21. package/dist/cloudflare/queue.d.ts +2 -2
  22. package/dist/cloudflare/queue.js +2 -2
  23. package/dist/cloudflare/scheduled.d.ts +1 -1
  24. package/dist/cloudflare/scheduled.js +1 -1
  25. package/dist/cloudflare.d.ts +3 -3
  26. package/dist/cloudflare.js +3 -3
  27. package/dist/{core-hdaNiCOU.js → core-ClSP5-V9.js} +94 -44
  28. package/dist/core-ClSP5-V9.js.map +1 -0
  29. package/dist/core.d.ts +2 -2
  30. package/dist/core.js +2 -2
  31. package/dist/http.d.ts +2 -2
  32. package/dist/http.js +2 -2
  33. package/dist/{index-C28HgVfY.d.ts → index-Cchdg2aQ.d.ts} +4 -4
  34. package/dist/{index-C28HgVfY.d.ts.map → index-Cchdg2aQ.d.ts.map} +1 -1
  35. package/dist/{index-G1QG0P5g.d.ts → index-DvJUcSW1.d.ts} +102 -48
  36. package/dist/{index-G1QG0P5g.d.ts.map → index-DvJUcSW1.d.ts.map} +1 -1
  37. package/dist/{outbox-repository-options-BZjfDqGf.d.ts → outbox-repository-options-AkihEaik.d.ts} +3 -3
  38. package/dist/{outbox-repository-options-BZjfDqGf.d.ts.map → outbox-repository-options-AkihEaik.d.ts.map} +1 -1
  39. package/dist/{outbox-repository-options-DOTpJH-e.js → outbox-repository-options-ICOF8g2h.js} +2 -2
  40. package/dist/{outbox-repository-options-DOTpJH-e.js.map → outbox-repository-options-ICOF8g2h.js.map} +1 -1
  41. package/dist/postgres.d.ts +3 -3
  42. package/dist/postgres.js +3 -3
  43. package/dist/posthog/metrics.d.ts +1 -1
  44. package/dist/posthog/server.d.ts +2 -2
  45. package/dist/posthog/server.js +1 -1
  46. package/dist/resend.d.ts +3 -3
  47. package/dist/resend.js +3 -3
  48. package/dist/resend.js.map +1 -1
  49. package/dist/sentry/client.d.ts +1 -1
  50. package/dist/sentry/client.js +1 -1
  51. package/dist/sentry/server.d.ts +2 -2
  52. package/dist/tanstack.d.ts +1 -1
  53. package/dist/tanstack.js +1 -1
  54. package/dist/testing/outbox-repository.d.ts +2 -2
  55. package/dist/{webhook-verification-D7DIhH6C.d.ts → webhook-verification-BcQQG-vY.d.ts} +2 -2
  56. package/dist/{webhook-verification-D7DIhH6C.d.ts.map → webhook-verification-BcQQG-vY.d.ts.map} +1 -1
  57. package/dist/{webhook-verification-trEgyz7I.js → webhook-verification-D6aGQfNi.js} +2 -2
  58. package/dist/{webhook-verification-trEgyz7I.js.map → webhook-verification-D6aGQfNi.js.map} +1 -1
  59. package/package.json +3 -1
  60. package/src/application/email-service.ts +2 -2
  61. package/src/core/define-messages.ts +209 -103
  62. package/src/core/index.ts +3 -1
  63. package/src/core/messages.ts +1 -1
  64. package/src/infrastructure/cloudflare/durable-object-client.ts +70 -0
  65. package/src/infrastructure/cloudflare/durable-object-errors.ts +70 -0
  66. package/src/infrastructure/resend/resend-email-service.ts +4 -1
  67. package/dist/application-C4JOf71r.js.map +0 -1
  68. package/dist/core-hdaNiCOU.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-ClSP5-V9.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/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 send 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","/**\n * Module-scoped logging for every host.\n *\n * A logger emits one plain-data entry per log. The default sink hands it to `console` as an\n * entry object for a log service or as a colored line for a person, selected at startup.\n */\n\n/** A value a log entry may carry. Errors enter only through `Logger.error`. */\nexport type LogValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ReadonlyArray<LogValue>\n | LogFields\n\n/** Named log values. */\nexport type LogFields = { readonly [key: string]: LogValue }\n\n/**\n * The supported log severity levels, in ascending order.\n *\n * A const object, not an enum, so a parsed environment value typed `'INFO'` is a `LogLevel`.\n */\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/** An error as plain data, including diagnostics, causes, and aggregate members. */\nexport type SerializedError = {\n readonly name: string\n readonly message: string\n readonly stack?: string\n readonly fields?: LogFields\n readonly cause?: SerializedError\n readonly errors?: ReadonlyArray<SerializedError>\n}\n\n/** One log, as the sink receives it. Plain data, safe to stringify. */\nexport type LogEntry = {\n readonly timestamp: string\n readonly level: LogLevel\n readonly module: string\n readonly message: string\n readonly details: LogFields\n readonly userId?: string\n /** Present on `Logger.error` entries that carried an error. */\n readonly error?: SerializedError\n}\n\n/** The context an error log carries. */\nexport type ErrorLogContext = {\n readonly error?: unknown\n readonly userId?: string\n readonly details?: LogFields\n}\n\n/** What a logger lets through: a level and everything above it, or nothing. */\nexport type LogThreshold = LogLevel | 'OFF'\n\n/** Overrides the application settings for one logger. */\nexport interface LoggerConfig {\n readonly level?: LogThreshold\n}\n\n/** `json` writes the entry object. `pretty` writes one readable line for a person. */\nexport type LogFormat = 'json' | 'pretty'\n\n/**\n * The application settings, set once at the composition root.\n *\n * An omitted field keeps its default. An explicit `undefined` is a compile error, so the root\n * parses an environment value before passing it. The logger reads no environment itself.\n */\nexport interface LoggerSettings extends LoggerConfig {\n readonly format?: LogFormat\n}\n\n// The production server setting, so a root that never configures still logs safely.\nconst DEFAULT_SETTINGS: Required<LoggerSettings> = {\n level: LogLevel.INFO,\n format: 'json',\n}\n\n// The application configures once at startup; loggers can exist before startup completes.\nlet settings = DEFAULT_SETTINGS\n\n/**\n * Set application settings, including for existing loggers. Per-logger overrides take priority.\n * Call at startup, never per request. An omitted field resets to INFO and JSON output.\n */\nexport function configureLogger(config: LoggerSettings): void {\n settings = {\n level: config.level ?? DEFAULT_SETTINGS.level,\n format: config.format ?? DEFAULT_SETTINGS.format,\n }\n}\n\n/** The error data sent to the configured error hook. */\nexport interface ErrorCaptureEntry {\n readonly error: unknown\n readonly distinctId: string | undefined\n readonly context: LogFields\n}\n\n/** A function that forwards one logged error to an error service. */\nexport type LoggerErrorHook = (entry: ErrorCaptureEntry) => void\n\n/** Where every log entry goes. */\nexport type LogSink = (entry: LogEntry) => void\n\nlet errorHook: LoggerErrorHook | null = null\n\n/**\n * Register the function that receives each logged error.\n *\n * Set once at the process entry point. A later call replaces the earlier hook.\n */\nexport function setLoggerErrorHook(fn: LoggerErrorHook): void {\n errorHook = fn\n}\n\n// One console method per level, so a host that filters by method can tell them apart.\nconst CONSOLE_METHOD = {\n [LogLevel.DEBUG]: 'debug',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error',\n} as const satisfies Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'>\n\n// Built from the code point so no raw control character sits in the source.\nconst ESC = String.fromCharCode(27)\nconst ANSI_RESET = `${ESC}[0m`\nconst ANSI_GRAY = `${ESC}[90m`\nconst ANSI_BLUE = `${ESC}[34m`\n\n// Severity reads at a glance: quiet levels stay dim, and an error is the only bold line.\nconst LEVEL_ANSI = {\n DEBUG: `${ESC}[2;36m`,\n INFO: ANSI_BLUE,\n WARN: `${ESC}[33m`,\n ERROR: `${ESC}[1;31m`,\n} satisfies Record<LogLevel, string>\n\nfunction prettyLine(entry: LogEntry): string {\n // Node prints debug and info exactly like log, so the level must be in the text too.\n const level = `[${entry.level}]`\n const module = `[${entry.module}]`\n // A browser console colors by method on its own; a terminal needs ANSI to do the same.\n if ('window' in globalThis) return `${entry.timestamp} ${level} ${module} ${entry.message}`\n const timestamp = `${ANSI_GRAY}${entry.timestamp}${ANSI_RESET}`\n const coloredLevel = `${LEVEL_ANSI[entry.level]}${level}${ANSI_RESET}`\n const coloredModule = `${ANSI_BLUE}${module}${ANSI_RESET}`\n return `${timestamp} ${coloredLevel} ${coloredModule} ${entry.message}`\n}\n\n/**\n * JSON format writes the entry object. Pretty format writes one line, then the details,\n * the error, and the stack as separate console arguments.\n */\nexport const consoleSink: LogSink = (entry) => {\n // Resolved per call, so a console replaced after import still receives the output.\n const write = console[CONSOLE_METHOD[entry.level]]\n if (settings.format === 'json') {\n write(entry)\n return\n }\n const line = prettyLine(entry)\n const fields =\n entry.userId === undefined ? entry.details : { ...entry.details, userId: entry.userId }\n const details = Object.keys(fields).length === 0 ? [] : [fields]\n if (entry.error === undefined) {\n write(line, ...details)\n return\n }\n // A stack inside an object prints as one quoted string; as its own argument it prints as lines.\n const { stack, ...error } = entry.error\n if (stack === undefined) write(line, ...details, error)\n else write(line, ...details, error, `\\n${stack}`)\n}\n\nlet logSink: LogSink = consoleSink\n\n/**\n * Send every log entry somewhere other than `console`.\n *\n * Set once at the process entry point, never per module. A logger is created\n * by name and nothing else, so its destination is a fact about the process.\n */\nexport function setLogSink(fn: LogSink): void {\n logSink = fn\n}\n\nconst LOG_LEVELS = Object.values(LogLevel)\nconst MAX_ERROR_DEPTH = 3\n\n/**\n * Diagnostics worth keeping off an error, named one by one.\n *\n * An allowlist rather than every own property: an error raised by a library we\n * do not control may hang a request or a user payload off itself, and a log is\n * the wrong place to discover that. `_tag` and `classification` are what every `AppError`\n * declares. `remote` and the three flags after it are the ones workerd sets itself.\n */\nconst KEPT_ERROR_FIELDS = [\n '_tag',\n 'classification',\n 'code',\n 'operation',\n 'status',\n 'statusCode',\n 'remote',\n 'retryable',\n 'overloaded',\n 'durableObjectReset',\n] as const\n\ntype ErrorDiagnostics = Error & { readonly [K in (typeof KEPT_ERROR_FIELDS)[number]]?: LogValue }\n\ntype MutableSerializedError = { -readonly [K in keyof SerializedError]: SerializedError[K] }\n\nconst serializeError = (error: Error, depth = 0): SerializedError => {\n if (depth > MAX_ERROR_DEPTH) return { name: 'Error', message: '[error nesting truncated]' }\n\n // Every field is optional, so an `Error` is already one of these.\n const carrier: ErrorDiagnostics = error\n const kept = KEPT_ERROR_FIELDS.filter((key) => carrier[key] !== undefined)\n const serialized: MutableSerializedError = { name: error.name, message: error.message }\n if (error.stack !== undefined) serialized.stack = error.stack\n if (kept.length > 0)\n serialized.fields = Object.fromEntries(kept.map((key) => [key, carrier[key]]))\n if (error.cause instanceof Error) serialized.cause = serializeError(error.cause, depth + 1)\n else if (error.cause !== undefined)\n serialized.cause = { name: 'Error', message: '[non-error cause]' }\n if (error instanceof AggregateError) {\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- AggregateError accepts arbitrary values; instanceof Error validates each member.\n serialized.errors = error.errors.map((failure: unknown) =>\n failure instanceof Error\n ? serializeError(failure, depth + 1)\n : { name: 'NonError', message: '[non-error aggregate member]' },\n )\n }\n return serialized\n}\n\n/** Write module-scoped logs with application defaults and optional overrides. */\nexport class Logger {\n private readonly config: LoggerConfig\n\n /** Create a logger for one module. */\n constructor(\n private readonly module: string,\n overrideConfig?: LoggerConfig,\n ) {\n this.config = { ...overrideConfig }\n }\n\n private log(\n level: LogLevel,\n message: string,\n details: LogFields,\n error?: SerializedError,\n userId?: string,\n ): void {\n const threshold = this.config.level ?? settings.level\n if (threshold === 'OFF') return\n if (LOG_LEVELS.indexOf(level) < LOG_LEVELS.indexOf(threshold)) return\n\n let entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n module: this.module,\n message,\n details,\n }\n if (userId !== undefined) entry = { ...entry, userId }\n logSink(error === undefined ? entry : { ...entry, error })\n }\n\n /** Write a debug log. */\n debug(message: string, details: LogFields = {}): void {\n this.log(LogLevel.DEBUG, message, details)\n }\n\n /** Write an information log. */\n info(message: string, details: LogFields = {}): void {\n this.log(LogLevel.INFO, message, details)\n }\n\n /** Write a warning log. */\n warn(message: string, details: LogFields = {}): void {\n this.log(LogLevel.WARN, message, details)\n }\n\n /**\n * Write an error log and send the error to the configured hook.\n *\n * The details say which call this was, and the error says what went wrong\n * inside it. Both the entry and the error hook receive the supplied user ID.\n */\n error(message: string, context: ErrorLogContext = {}): void {\n const details = context.details ?? {}\n const thrown = context.error\n let error: SerializedError | undefined\n if (thrown instanceof Error) {\n error = serializeError(thrown)\n } else if (thrown !== undefined) {\n // Not an `Error`, so there is no name or stack to keep, only its JSON form.\n let json: string\n try {\n json = JSON.stringify(thrown)\n } catch {\n json = '[non-serializable error]'\n }\n error = { name: 'NonError', message: json }\n }\n this.log(LogLevel.ERROR, message, details, error, context.userId)\n\n if (errorHook !== null && thrown !== undefined) {\n errorHook({ error: thrown, distinctId: context.userId, context: details })\n }\n }\n}\n\n/** Create a logger for one module. */\nexport function createLogger(module: string, config?: LoggerConfig): Logger {\n return new Logger(module, config)\n}\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,qBA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/B,IAAI;GACJ,IAAI;IACF,OAAO,KAAK,UAAU,MAAM;GAC9B,QAAQ;IACN,OAAO;GACT;GACA,QAAQ;IAAE,MAAM;IAAY,SAAS;GAAK;EAC5C;EACA,KAAK,IAAI,SAAS,OAAO,SAAS,SAAS,OAAO,QAAQ,MAAM;EAEhE,IAAI,cAAc,QAAQ,WAAW,QACnC,UAAU;GAAE,OAAO;GAAQ,YAAY,QAAQ;GAAQ,SAAS;EAAQ,CAAC;CAE7E;AACF;;AAGA,SAAgB,aAAa,QAAgB,QAA+B;CAC1E,OAAO,IAAI,OAAO,QAAQ,MAAM;AAClC"}
package/dist/core.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as notImplemented, $t as RetryOwner, A as isCloudflareRetryableError, At as RecordEmailEventPayload, B as MessageOf, Bt as InvalidEmailIdempotencyKeyError, C as BoundaryErrorClassifier, Ct as ValidationProblemErrorSchema, D as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, Dt as StaleSessionError, E as retryAfterSecondsOf, Et as NotAuthorizedError, F as EntityData, Ft as parseBounceType, G as DomainEvent, Gt as AnalyticsEventIdSchema, H as QueryOf, Ht as EmailAddress, I as AppMessages, It as shouldUpdateBounce, J as MessageId, Jt as AnalyticsProperties, K as DomainMessage, Kt as AnalyticsEventIdentity, L as CommandOf, Lt as EmailSendFailureReason, M as isAbortError, Mt as BounceType, N as isTransientTransportError, Nt as BounceTypeSchema, O as isCloudflareObjectResetError, Ot as RateLimitError, P as Entity, Pt as isEmailDeliverable, Q as defineId, Qt as FailureClassification, R as EventOf, Rt as EmailServiceError, S as spreadJitterMs, St as ValidationProblemError, T as classifyFailure, Tt as ServiceUnavailableError, U as defineMessages, Ut as EmailAddressSchema, V as PayloadSchemas, Vt as emailIdempotencyKey, W as DomainCommand, Wt as AnalyticsEventId, X as IdDefinition, Xt as MissingConfigurationError, Y as Id, Yt as AnalyticsProperty, Z as IdOf, Zt as AppError, _ as createLogger, _t as ValidationIssue, a as LogFormat, at as ErrorEntry, b as exponentialDelayCapMs, bt as ValidationProblemDetails, c as LogThreshold, ct as ErrorTagOf, d as LoggerConfig, dt as sharedErrors, en as shouldRetryFailure, et as unreachable, f as LoggerErrorHook, ft as MalformedRequestError, g as consoleSink, gt as ValidationError, h as configureLogger, ht as UpgradeRequiredError, i as LogFields, it as ErrorEntries, j as isTransientCloudflareRuntimeError, jt as RecordEmailEventPayloadSchema, k as isCloudflareOverloadedError, kt as AuthenticationError, l as LogValue, lt as ResolvedError, m as SerializedError, mt as ResourceNotFoundError, n as ErrorLogContext, nt as DatabaseError, o as LogLevel, ot as ErrorPayloadOf, p as LoggerSettings, pt as RequestTimeoutError, q as DomainQuery, qt as AnalyticsEventInput, r as LogEntry, rt as DatabaseFailure, s as LogSink, st as ErrorTable, t as ErrorCaptureEntry, tt as D1ConstraintKind, u as Logger, ut as defineErrors, v as setLogSink, vt as ProblemDetails, w as classifyBoundaryError, wt as InternalServerError, x as exponentialEqualJitterMs, xt as ValidationProblemDetailsSchema, y as setLoggerErrorHook, yt as ProblemDetailsSchema, z as MessageDefinition, zt as EmailIdempotencyKey } from "./index-G1QG0P5g.js";
2
- export { type AnalyticsEventId, AnalyticsEventIdSchema, type AnalyticsEventIdentity, type AnalyticsEventInput, type AnalyticsProperties, type AnalyticsProperty, AppError, type AppMessages, AuthenticationError, type BounceType, BounceTypeSchema, type BoundaryErrorClassifier, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, type CommandOf, type D1ConstraintKind, DatabaseError, type DatabaseFailure, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, type EmailAddress, EmailAddressSchema, type EmailIdempotencyKey, type EmailSendFailureReason, EmailServiceError, Entity, type EntityData, type ErrorCaptureEntry, type ErrorEntries, type ErrorEntry, type ErrorLogContext, type ErrorPayloadOf, type ErrorTable, type ErrorTagOf, type EventOf, type FailureClassification, type Id, type IdDefinition, type IdOf, InternalServerError, InvalidEmailIdempotencyKeyError, type LogEntry, type LogFields, type LogFormat, LogLevel, type LogSink, type LogThreshold, type LogValue, Logger, type LoggerConfig, type LoggerErrorHook, type LoggerSettings, MalformedRequestError, type MessageDefinition, type MessageId, type MessageOf, MissingConfigurationError, NotAuthorizedError, type PayloadSchemas, type ProblemDetails, ProblemDetailsSchema, type QueryOf, RateLimitError, type RecordEmailEventPayload, RecordEmailEventPayloadSchema, RequestTimeoutError, type ResolvedError, ResourceNotFoundError, type RetryOwner, type SerializedError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, type ValidationIssue, type ValidationProblemDetails, ValidationProblemDetailsSchema, type ValidationProblemError, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, 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 };
1
+ import { $ as IdOf, $t as AppError, A as isCloudflareRetryableError, At as RateLimitError, B as MessageDefinition, Bt as EmailServiceError, C as BoundaryErrorClassifier, Ct as ValidationProblemDetailsSchema, D as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, Dt as ServiceUnavailableError, E as retryAfterSecondsOf, Et as InternalServerError, F as EntityData, Ft as BounceTypeSchema, G as defineMessages, Gt as EmailAddressSchema, H as PayloadSchemas, Ht as InvalidEmailIdempotencyKeyError, I as CommandOf, It as isEmailDeliverable, J as DomainMessage, Jt as AnalyticsEventIdentity, K as DomainCommand, Kt as AnalyticsEventId, L as DuplicateMessageNameError, Lt as parseBounceType, M as isAbortError, Mt as RecordEmailEventPayload, N as isTransientTransportError, Nt as RecordEmailEventPayloadSchema, O as isCloudflareObjectResetError, Ot as NotAuthorizedError, P as Entity, Pt as BounceType, Q as IdDefinition, Qt as MissingConfigurationError, R as EventOf, Rt as shouldUpdateBounce, S as spreadJitterMs, St as ValidationProblemDetails, T as classifyFailure, Tt as ValidationProblemErrorSchema, U as QueryOf, Ut as emailIdempotencyKey, V as MessageOf, Vt as EmailIdempotencyKey, W as combineMessages, Wt as EmailAddress, X as MessageId, Xt as AnalyticsProperties, Y as DomainQuery, Yt as AnalyticsEventInput, Z as Id, Zt as AnalyticsProperty, _ as createLogger, _t as UpgradeRequiredError, a as LogFormat, at as DatabaseFailure, b as exponentialDelayCapMs, bt as ProblemDetails, c as LogThreshold, ct as ErrorPayloadOf, d as LoggerConfig, dt as ResolvedError, en as FailureClassification, et as defineId, f as LoggerErrorHook, ft as defineErrors, g as consoleSink, gt as ResourceNotFoundError, h as configureLogger, ht as RequestTimeoutError, i as LogFields, it as DatabaseError, j as isTransientCloudflareRuntimeError, jt as AuthenticationError, k as isCloudflareOverloadedError, kt as StaleSessionError, l as LogValue, lt as ErrorTable, m as SerializedError, mt as MalformedRequestError, n as ErrorLogContext, nn as shouldRetryFailure, nt as unreachable, o as LogLevel, ot as ErrorEntries, p as LoggerSettings, pt as sharedErrors, q as DomainEvent, qt as AnalyticsEventIdSchema, r as LogEntry, rt as D1ConstraintKind, s as LogSink, st as ErrorEntry, t as ErrorCaptureEntry, tn as RetryOwner, tt as notImplemented, u as Logger, ut as ErrorTagOf, v as setLogSink, vt as ValidationError, w as classifyBoundaryError, wt as ValidationProblemError, x as exponentialEqualJitterMs, xt as ProblemDetailsSchema, y as setLoggerErrorHook, yt as ValidationIssue, z as MessageCollection, zt as EmailSendFailureReason } from "./index-DvJUcSW1.js";
2
+ export { type AnalyticsEventId, AnalyticsEventIdSchema, type AnalyticsEventIdentity, type AnalyticsEventInput, type AnalyticsProperties, type AnalyticsProperty, AppError, AuthenticationError, type BounceType, BounceTypeSchema, type BoundaryErrorClassifier, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, type CommandOf, type D1ConstraintKind, DatabaseError, type DatabaseFailure, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, DuplicateMessageNameError, type EmailAddress, EmailAddressSchema, type EmailIdempotencyKey, type EmailSendFailureReason, EmailServiceError, Entity, type EntityData, type ErrorCaptureEntry, type ErrorEntries, type ErrorEntry, type ErrorLogContext, type ErrorPayloadOf, type ErrorTable, type ErrorTagOf, type EventOf, type FailureClassification, type Id, type IdDefinition, type IdOf, InternalServerError, InvalidEmailIdempotencyKeyError, type LogEntry, type LogFields, type LogFormat, LogLevel, type LogSink, type LogThreshold, type LogValue, Logger, type LoggerConfig, type LoggerErrorHook, type LoggerSettings, MalformedRequestError, type MessageCollection, type MessageDefinition, type MessageId, type MessageOf, MissingConfigurationError, NotAuthorizedError, type PayloadSchemas, type ProblemDetails, ProblemDetailsSchema, type QueryOf, RateLimitError, type RecordEmailEventPayload, RecordEmailEventPayloadSchema, RequestTimeoutError, type ResolvedError, ResourceNotFoundError, type RetryOwner, type SerializedError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, type ValidationIssue, type ValidationProblemDetails, ValidationProblemDetailsSchema, type ValidationProblemError, 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/core.js CHANGED
@@ -1,3 +1,3 @@
1
- import { $ as AnalyticsEventIdSchema, A as ProblemDetailsSchema, B as NotAuthorizedError, C as defineMessages, D as DatabaseError, E as unreachable, F as ResourceNotFoundError, G as BounceTypeSchema, H as RateLimitError, I as UpgradeRequiredError, J as shouldUpdateBounce, K as isEmailDeliverable, L as ValidationError, M as ValidationProblemErrorSchema, N as MalformedRequestError, O as defineErrors, P as RequestTimeoutError, Q as EmailAddressSchema, R as InternalServerError, S as Entity, T as notImplemented, U as AuthenticationError, V as StaleSessionError, W as RecordEmailEventPayloadSchema, X as InvalidEmailIdempotencyKeyError, Y as EmailServiceError, Z as emailIdempotencyKey, _ as isCloudflareRetryableError, a as createLogger, b as isTransientTransportError, c as exponentialDelayCapMs, d as classifyBoundaryError, et as MissingConfigurationError, f as classifyFailure, g as isCloudflareOverloadedError, h as isCloudflareObjectResetError, i as consoleSink, j as ValidationProblemDetailsSchema, k as sharedErrors, l as exponentialEqualJitterMs, m as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, n as Logger, o as setLogSink, p as retryAfterSecondsOf, q as parseBounceType, r as configureLogger, s as setLoggerErrorHook, t as LogLevel, tt as AppError, u as spreadJitterMs, v as isTransientCloudflareRuntimeError, w as defineId, x as shouldRetryFailure, y as isAbortError, z as ServiceUnavailableError } from "./core-hdaNiCOU.js";
1
+ import { $ as emailIdempotencyKey, A as defineErrors, B as InternalServerError, C as DuplicateMessageNameError, D as notImplemented, E as defineId, F as MalformedRequestError, G as AuthenticationError, H as NotAuthorizedError, I as RequestTimeoutError, J as isEmailDeliverable, K as RecordEmailEventPayloadSchema, L as ResourceNotFoundError, M as ProblemDetailsSchema, N as ValidationProblemDetailsSchema, O as unreachable, P as ValidationProblemErrorSchema, Q as InvalidEmailIdempotencyKeyError, R as UpgradeRequiredError, S as Entity, T as defineMessages, U as StaleSessionError, V as ServiceUnavailableError, W as RateLimitError, X as shouldUpdateBounce, Y as parseBounceType, Z as EmailServiceError, _ as isCloudflareRetryableError, a as createLogger, b as isTransientTransportError, c as exponentialDelayCapMs, d as classifyBoundaryError, et as EmailAddressSchema, f as classifyFailure, g as isCloudflareOverloadedError, h as isCloudflareObjectResetError, i as consoleSink, j as sharedErrors, k as DatabaseError, l as exponentialEqualJitterMs, m as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, n as Logger, nt as MissingConfigurationError, o as setLogSink, p as retryAfterSecondsOf, q as BounceTypeSchema, r as configureLogger, rt as AppError, s as setLoggerErrorHook, t as LogLevel, tt as AnalyticsEventIdSchema, u as spreadJitterMs, v as isTransientCloudflareRuntimeError, w as combineMessages, x as shouldRetryFailure, y as isAbortError, z as ValidationError } from "./core-ClSP5-V9.js";
2
2
 
3
- export { AnalyticsEventIdSchema, AppError, AuthenticationError, BounceTypeSchema, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, DatabaseError, EmailAddressSchema, EmailServiceError, Entity, InternalServerError, InvalidEmailIdempotencyKeyError, LogLevel, Logger, MalformedRequestError, MissingConfigurationError, NotAuthorizedError, ProblemDetailsSchema, RateLimitError, RecordEmailEventPayloadSchema, RequestTimeoutError, ResourceNotFoundError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, ValidationProblemDetailsSchema, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, 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 };
3
+ export { AnalyticsEventIdSchema, AppError, AuthenticationError, BounceTypeSchema, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, DatabaseError, DuplicateMessageNameError, EmailAddressSchema, EmailServiceError, Entity, InternalServerError, InvalidEmailIdempotencyKeyError, LogLevel, Logger, 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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { u as Logger } from "./index-G1QG0P5g.js";
2
- import { n as WebhookVerificationError, r as WebhookVerifier, t as WebhookVerification } from "./webhook-verification-D7DIhH6C.js";
1
+ import { u as Logger } from "./index-DvJUcSW1.js";
2
+ import { n as WebhookVerificationError, r as WebhookVerifier, t as WebhookVerification } from "./webhook-verification-BcQQG-vY.js";
3
3
  //#region src/infrastructure/http/webhook-handler.d.ts
4
4
  /** Read raw webhook requests and acknowledge effects only after the callback completes. */
5
5
  export declare class WebhookHandler<Event> {
package/dist/http.js CHANGED
@@ -1,5 +1,5 @@
1
- import { a as createLogger } from "./core-hdaNiCOU.js";
2
- import { t as WebhookVerificationError } from "./webhook-verification-trEgyz7I.js";
1
+ import { a as createLogger } from "./core-ClSP5-V9.js";
2
+ import { t as WebhookVerificationError } from "./webhook-verification-D6aGQfNi.js";
3
3
  import { StatusCodes } from "http-status-codes";
4
4
 
5
5
  //#region src/infrastructure/http/webhook-handler.ts
@@ -1,4 +1,4 @@
1
- import { At as RecordEmailEventPayload, G as DomainEvent, Ht as EmailAddress, J as MessageId, Jt as AnalyticsProperties, K as DomainMessage, Kt as AnalyticsEventIdentity, Mt as BounceType, W as DomainCommand, Zt as AppError, q as DomainQuery, qt as AnalyticsEventInput, zt as EmailIdempotencyKey } from "./index-G1QG0P5g.js";
1
+ import { $t as AppError, J as DomainMessage, Jt as AnalyticsEventIdentity, K as DomainCommand, Mt as RecordEmailEventPayload, Pt as BounceType, Vt as EmailIdempotencyKey, Wt as EmailAddress, X as MessageId, Xt as AnalyticsProperties, Y as DomainQuery, Yt as AnalyticsEventInput, q as DomainEvent } from "./index-DvJUcSW1.js";
2
2
  //#region src/application/handlers.d.ts
3
3
  /**
4
4
  * Handles one command with the dependency container and returns the caller's value.
@@ -87,8 +87,8 @@ type OutboundEmail = {
87
87
  readonly to: string | readonly string[];
88
88
  readonly subject: string;
89
89
  readonly html: string;
90
- /** The stable identity of this send. Resend deduplicates it for 24 hours. */
91
- readonly idempotencyKey: EmailIdempotencyKey;
90
+ /** Optional stable identity of this send. Resend deduplicates supplied keys for 24 hours. */
91
+ readonly idempotencyKey?: EmailIdempotencyKey;
92
92
  /** Resend generates plain text from html when omitted. An empty string disables that generation. */
93
93
  readonly text?: string;
94
94
  readonly replyTo?: string;
@@ -392,4 +392,4 @@ declare class UnitOfWorkAlreadyActiveError extends AppError {
392
392
  }
393
393
  //#endregion
394
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-C28HgVfY.d.ts.map
395
+ //# sourceMappingURL=index-Cchdg2aQ.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index-C28HgVfY.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,eAAe,MAAM,UAC/D,SAAS,UACT,MAAM,SACH,QAAQ;;;;;KAMD,aAAa,eAAe,aAAa,WAAW,UAC9D,OAAO,QACP,MAAM,cACH,QAAQ;;KAGD,aAAa,eAAe,aAAa,SACnD,OAAO,QACP,MAAM,SACH;;;;UCrBY,iBAAiB,eAAe,sBAAsB;;EAErE,SAAS,oBAAoB,aAAa;;EAE1C,MAAM,oBAAoB;;EAE1B,MAAM,OAAO,QAAQ,oBAAoB,WAAW;;EAEpD,eAAe,OAAO,QAAQ,oBAAoB,WAAW;;;cAIlD,gBAAgB;;;;KCdjB;;KAGA,mBAAmB,SAAS,eAAe;;UAGtC;WACN,aAAa;WACb;;;UAIM,eAAe;;EAE9B,MAAM,MAAM,OAAO,gBAAgB,UAAU;;EAE7C,MAAM,MAAM,OAAO,eAAe,UAAU;;EAE5C,UAAU,MAAM,OAAO,eAAe,UAAU;;;cAIrC,sBAAsB;;;;UCtBlB;WACN;;;UAIM;;EAEf,QAAQ,MAAM;;;UAIC,6BAA6B;;EAE5C,mBAAmB,GAAG,WAAW,OAAO,uBAAuB,IAAI,QAAQ,KAAK,Q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Z,YAAY,wBACZ,oBAAoB;KAEnB,UAAU,QAAQ,wBAAwB,oBAAoB,SAC/D,QAAQ,WAAW,QAAQ,OAAO,QAAQ;;KAIlC,cACV,iBAAiB,eACjB,kBAAkB,mBAChB,iBAAiB,gBACjB,UAAU,uBAAuB,oBACjC,iBAAiB,cACf,UAAU,sBAAsB;;;;UCvDrB,YAAY,kBAAkB;EAC7C,OAAO,iBAAiB,gBAAgB,gBAAgB,YACtD,SAAS,WACR,QAAQ,cAAc,UAAU;;;;;;cAOxB,WAAW,MAAM,kBAAkB,SAAS,kBAAkB,YAAY;mBAElE;mBACA;EAFnB,YACmB,MAAM,MACN,UAAU;;EAIvB,OAAO,iBAAiB,gBAAgB,gBAAgB,YAC5D,SAAS,WACR,QAAQ,cAAc,UAAU;UAM3B;UASA;UASA;;;;;;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
+ {"version":3,"file":"index-Cchdg2aQ.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,eAAe,MAAM,UAC/D,SAAS,UACT,MAAM,SACH,QAA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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"}
@@ -468,7 +468,7 @@ declare function defineId<const Brand extends string>(brand: Brand): IdDefinitio
468
468
  *
469
469
  * Internal messages use UUID v7, so receipts sort by creation. External messages use the
470
470
  * provider's own key, `stripe:event:evt_123`, so a redelivered webhook is a duplicate by
471
- * construction. The app parses and generates ids; this package only carries them.
471
+ * construction. Message factories generate IDs; complete message schemas parse external IDs.
472
472
  */
473
473
  type MessageId = string;
474
474
  /** An action to perform. One handler, returns a value. The product adds its payload. */
@@ -492,59 +492,113 @@ type DomainEvent<Name extends string = string> = {
492
492
  type DomainMessage = DomainCommand | DomainEvent | DomainQuery;
493
493
  //#endregion
494
494
  //#region src/core/define-messages.d.ts
495
- /** Payload schemas keyed by message name. A payload never carries `type`, `name`, or `id`. */
495
+ /** Payload schemas keyed by message name. Payloads cannot declare `type`, `name`, or `id`. */
496
496
  type PayloadSchemas = Readonly<Record<string, z.ZodType<object>>>;
497
- /** An application's messages: one list of payload schemas per kind. */
497
+ /** Optional payload schema maps for one message collection. */
498
498
  type MessageDefinition = {
499
- readonly commands: PayloadSchemas;
500
- readonly events: PayloadSchemas;
501
- readonly queries: PayloadSchemas;
499
+ readonly commands?: PayloadSchemas;
500
+ readonly events?: PayloadSchemas;
501
+ readonly queries?: PayloadSchemas;
502
502
  };
503
- type AnyMessages = {
504
- readonly definition: MessageDefinition;
505
- };
506
- type Def<Messages extends AnyMessages> = Messages['definition'];
507
- type Payload<Schemas extends PayloadSchemas, Name extends keyof Schemas> = z.output<Schemas[Name]>;
508
- /** Every command of an application: `CommandOf<typeof messages>`. */
509
- type CommandOf<Messages extends AnyMessages> = { [Name in keyof Def<Messages>['commands'] & string]: DomainCommand<Name> & Payload<Def<Messages>['commands'], Name>; }[keyof Def<Messages>['commands'] & string];
510
- /** Every event of an application: `EventOf<typeof messages>`. */
511
- type EventOf<Messages extends AnyMessages> = { [Name in keyof Def<Messages>['events'] & string]: DomainEvent<Name> & Payload<Def<Messages>['events'], Name>; }[keyof Def<Messages>['events'] & string];
512
- /** Every query of an application: `QueryOf<typeof messages>`. */
513
- type QueryOf<Messages extends AnyMessages> = { [Name in keyof Def<Messages>['queries'] & string]: DomainQuery<Name> & Payload<Def<Messages>['queries'], Name>; }[keyof Def<Messages>['queries'] & string];
514
- /** Every message of an application: what the registry and the bus are typed with. */
515
- type MessageOf<Messages extends AnyMessages> = CommandOf<Messages> | EventOf<Messages> | QueryOf<Messages>;
516
- /**
517
- * What `defineMessages` returns. The factories build messages for in-process dispatch without
518
- * parsing; the data is already typed. The schemas parse untrusted input at a boundary.
519
- */
520
- type AppMessages<Definition extends MessageDefinition> = {
521
- readonly definition: Definition;
522
- /** Build a command. `id` defaults to a uuid v7; a webhook passes the provider's key, `stripe:event:evt_123`. */
523
- createCommand<Name extends keyof Definition['commands'] & string>(name: Name, payload: Payload<Definition['commands'], Name>, id?: MessageId): DomainCommand<Name> & Payload<Definition['commands'], Name>;
524
- /** Build an event. `id` defaults to a uuid v7, which also orders it in time. */
525
- createEvent<Name extends keyof Definition['events'] & string>(name: Name, payload: Payload<Definition['events'], Name>, id?: MessageId): DomainEvent<Name> & Payload<Definition['events'], Name>;
526
- /** Build a query. No id: nothing claims a read. */
527
- createQuery<Name extends keyof Definition['queries'] & string>(name: Name, payload: Payload<Definition['queries'], Name>): DomainQuery<Name> & Payload<Definition['queries'], Name>;
528
- readonly commandSchema: z.ZodType<CommandOf<AppMessages<Definition>>>;
529
- readonly eventSchema: z.ZodType<EventOf<AppMessages<Definition>>>;
530
- readonly querySchema: z.ZodType<QueryOf<AppMessages<Definition>>>;
531
- /** What a queue body may be: a command or an event. Queries never cross a queue. */
532
- readonly queueSchema: z.ZodType<CommandOf<AppMessages<Definition>> | EventOf<AppMessages<Definition>>>;
503
+ declare const completed: unique symbol;
504
+ declare const envelopes: {
505
+ command: z.ZodObject<{
506
+ type: z.ZodLiteral<"command">;
507
+ id: z.ZodString;
508
+ }, z.core.$strip>;
509
+ event: z.ZodObject<{
510
+ type: z.ZodLiteral<"event">;
511
+ id: z.ZodString;
512
+ }, z.core.$strip>;
513
+ query: z.ZodObject<{
514
+ type: z.ZodLiteral<"query">;
515
+ }, z.core.$strip>;
533
516
  };
517
+ type MessageKind = keyof typeof envelopes;
534
518
  type RoutingField = 'type' | 'name' | 'id';
535
- /** A payload that declares a routing field maps to `never`, so `defineMessages` rejects it. */
536
- type WithoutRoutingFields<Schemas extends PayloadSchemas> = { readonly [Name in keyof Schemas]: keyof z.output<Schemas[Name]> & RoutingField extends never ? Schemas[Name] : never; };
537
- /** The compile-time rule: no payload of any kind declares `type`, `name`, or `id`. */
538
- type ValidDefinition<Definition extends MessageDefinition> = {
539
- readonly commands: WithoutRoutingFields<Definition['commands']>;
540
- readonly events: WithoutRoutingFields<Definition['events']>;
541
- readonly queries: WithoutRoutingFields<Definition['queries']>;
519
+ type SchemaMap = Readonly<Record<string, z.ZodType<object>>>;
520
+ type EmptySchemas = Record<never, never>;
521
+ type SchemaMaps = {
522
+ readonly commandSchemas: SchemaMap;
523
+ readonly eventSchemas: SchemaMap;
524
+ readonly querySchemas: SchemaMap;
525
+ };
526
+ type CompletedMessages = SchemaMaps & {
527
+ readonly [completed]: true;
528
+ };
529
+ type SchemaOf<Schemas extends SchemaMap> = Schemas[keyof Schemas & string];
530
+ type Payload<Message> = Message extends object ? Omit<Message, RoutingField> : never;
531
+ /** Complete schemas, union schemas, and factories for one message collection. */
532
+ type MessageCollection<Maps extends SchemaMaps> = Maps & {
533
+ readonly [completed]: true;
534
+ readonly commandSchema: z.ZodUnion<SchemaOf<Maps['commandSchemas']>[]>;
535
+ readonly eventSchema: z.ZodUnion<SchemaOf<Maps['eventSchemas']>[]>;
536
+ readonly querySchema: z.ZodUnion<SchemaOf<Maps['querySchemas']>[]>;
537
+ /** Commands and events can cross a queue. Queries cannot. */
538
+ readonly queueSchema: z.ZodUnion<(SchemaOf<Maps['commandSchemas']> | SchemaOf<Maps['eventSchemas']>)[]>;
539
+ /** Add the command envelope without parsing. The default ID is UUID v7; supplied IDs stay unchanged. */
540
+ createCommand<Name extends keyof Maps['commandSchemas'] & string>(this: void, name: Name, payload: Payload<z.output<Maps['commandSchemas'][NoInfer<Name>]>>, id?: MessageId): z.output<Maps['commandSchemas'][Name]>;
541
+ /** Add the event envelope without parsing. The default ID is UUID v7; supplied IDs stay unchanged. */
542
+ createEvent<Name extends keyof Maps['eventSchemas'] & string>(this: void, name: Name, payload: Payload<z.output<Maps['eventSchemas'][NoInfer<Name>]>>, id?: MessageId): z.output<Maps['eventSchemas'][Name]>;
543
+ /** Add the query envelope without parsing. Queries have no ID. */
544
+ createQuery<Name extends keyof Maps['querySchemas'] & string>(this: void, name: Name, payload: Payload<z.output<Maps['querySchemas'][NoInfer<Name>]>>): z.output<Maps['querySchemas'][Name]>;
542
545
  };
546
+ /** The command union inferred from a collection's complete schemas. */
547
+ type CommandOf<Messages extends CompletedMessages> = z.output<SchemaOf<Messages['commandSchemas']>>;
548
+ /** The event union inferred from a collection's complete schemas. */
549
+ type EventOf<Messages extends CompletedMessages> = z.output<SchemaOf<Messages['eventSchemas']>>;
550
+ /** The query union inferred from a collection's complete schemas. */
551
+ type QueryOf<Messages extends CompletedMessages> = z.output<SchemaOf<Messages['querySchemas']>>;
552
+ /** Every message inferred from a collection's complete schemas. */
553
+ type MessageOf<Messages extends CompletedMessages> = CommandOf<Messages> | EventOf<Messages> | QueryOf<Messages>;
554
+ type KeysOfUnion<Value> = Value extends Value ? keyof Value : never;
555
+ type WithoutRoutingFields<Schemas extends PayloadSchemas> = { readonly [Name in keyof Schemas]: KeysOfUnion<z.output<Schemas[Name]>> & RoutingField extends never ? Schemas[Name] : never; };
556
+ declare function messageSchema<Kind extends MessageKind, Name extends string, Schema extends z.ZodType<object>>(kind: Kind, name: Name, payload: Schema): z.ZodIntersection<z.ZodIntersection<{
557
+ command: z.ZodObject<{
558
+ type: z.ZodLiteral<"command">;
559
+ id: z.ZodString;
560
+ }, z.core.$strip>;
561
+ event: z.ZodObject<{
562
+ type: z.ZodLiteral<"event">;
563
+ id: z.ZodString;
564
+ }, z.core.$strip>;
565
+ query: z.ZodObject<{
566
+ type: z.ZodLiteral<"query">;
567
+ }, z.core.$strip>;
568
+ }[Kind], z.ZodObject<{
569
+ name: z.ZodLiteral<Name>;
570
+ }, z.core.$strip>>, Schema>;
571
+ type CompleteSchemas<Kind extends MessageKind, Schemas extends PayloadSchemas> = { readonly [Name in keyof Schemas & string]: ReturnType<typeof messageSchema<Kind, Name, Schemas[Name]>>; };
572
+ /** Build each complete schema once. Omitted kinds have empty maps and schemas that reject every input. */
573
+ declare function defineMessages<const Commands extends PayloadSchemas = EmptySchemas, const Events extends PayloadSchemas = EmptySchemas, const Queries extends PayloadSchemas = EmptySchemas>(definition: {
574
+ readonly commands?: Commands & WithoutRoutingFields<Commands>;
575
+ readonly events?: Events & WithoutRoutingFields<Events>;
576
+ readonly queries?: Queries & WithoutRoutingFields<Queries>;
577
+ }): MessageCollection<{
578
+ commandSchemas: CompleteSchemas<"command", Commands>;
579
+ eventSchemas: CompleteSchemas<"event", Events>;
580
+ querySchemas: CompleteSchemas<"query", Queries>;
581
+ }>;
582
+ /** Two collections declare the same name within one message kind. */
583
+ declare class DuplicateMessageNameError extends AppError {
584
+ readonly kind: MessageKind;
585
+ readonly messageName: string;
586
+ readonly _tag = "DuplicateMessageNameError";
587
+ readonly classification = "terminal";
588
+ /** Identify the duplicate kind and name so the application can correct its definitions. */
589
+ constructor(kind: MessageKind, messageName: string);
590
+ }
591
+ type SchemaAtName<Maps, Name extends PropertyKey> = Maps extends Record<Name, infer Schema extends z.ZodType<object>> ? Schema : never;
592
+ type DuplicateNames<Collections extends readonly CompletedMessages[]> = Collections extends readonly [infer First extends CompletedMessages, ...infer Rest extends readonly CompletedMessages[]] ? { [Key in keyof SchemaMaps]: keyof First[Key] & KeysOfUnion<Rest[number][Key]>; }[keyof SchemaMaps] | DuplicateNames<Rest> : never;
543
593
  /**
544
- * Define an application's messages once. The key is the name; the factories add the routing
545
- * fields `type`, `name`, and `id`. A payload that declares one of them is a compile error.
594
+ * Merge completed collections without rebuilding complete schemas.
595
+ * @throws DuplicateMessageNameError when two collections declare the same name within one kind.
546
596
  */
547
- declare function defineMessages<const Definition extends MessageDefinition>(definition: Definition & ValidDefinition<Definition>): AppMessages<Definition>;
597
+ declare function combineMessages<const Collections extends readonly CompletedMessages[]>(...collections: Collections & (DuplicateNames<Collections> extends never ? unknown : never)): MessageCollection<{
598
+ commandSchemas: { readonly [Name in KeysOfUnion<(Collections & (DuplicateNames<Collections> extends never ? unknown : never))[number]["commandSchemas"]> & string]: SchemaAtName<(Collections & (DuplicateNames<Collections> extends never ? unknown : never))[number]["commandSchemas"], Name>; };
599
+ eventSchemas: { readonly [Name in KeysOfUnion<(Collections & (DuplicateNames<Collections> extends never ? unknown : never))[number]["eventSchemas"]> & string]: SchemaAtName<(Collections & (DuplicateNames<Collections> extends never ? unknown : never))[number]["eventSchemas"], Name>; };
600
+ querySchemas: { readonly [Name in KeysOfUnion<(Collections & (DuplicateNames<Collections> extends never ? unknown : never))[number]["querySchemas"]> & string]: SchemaAtName<(Collections & (DuplicateNames<Collections> extends never ? unknown : never))[number]["querySchemas"], Name>; };
601
+ }>;
548
602
  //#endregion
549
603
  //#region src/core/entity.d.ts
550
604
  /** What an aggregate's plain data must have: an identity. A branded id keeps its brand. */
@@ -749,5 +803,5 @@ declare class Logger {
749
803
  /** Create a logger for one module. */
750
804
  declare function createLogger(module: string, config?: LoggerConfig): Logger;
751
805
  //#endregion
752
- export { notImplemented as $, RetryOwner as $t, isCloudflareRetryableError as A, RecordEmailEventPayload as At, MessageOf as B, InvalidEmailIdempotencyKeyError as Bt, BoundaryErrorClassifier as C, ValidationProblemErrorSchema as Ct, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS as D, StaleSessionError as Dt, retryAfterSecondsOf as E, NotAuthorizedError as Et, EntityData as F, parseBounceType as Ft, DomainEvent as G, AnalyticsEventIdSchema as Gt, QueryOf as H, EmailAddress as Ht, AppMessages as I, shouldUpdateBounce as It, MessageId as J, AnalyticsProperties as Jt, DomainMessage as K, AnalyticsEventIdentity as Kt, CommandOf as L, EmailSendFailureReason as Lt, isAbortError as M, BounceType as Mt, isTransientTransportError as N, BounceTypeSchema as Nt, isCloudflareObjectResetError as O, RateLimitError as Ot, Entity as P, isEmailDeliverable as Pt, defineId as Q, FailureClassification as Qt, EventOf as R, EmailServiceError as Rt, spreadJitterMs as S, ValidationProblemError as St, classifyFailure as T, ServiceUnavailableError as Tt, defineMessages as U, EmailAddressSchema as Ut, PayloadSchemas as V, emailIdempotencyKey as Vt, DomainCommand as W, AnalyticsEventId as Wt, IdDefinition as X, MissingConfigurationError as Xt, Id as Y, AnalyticsProperty as Yt, IdOf as Z, AppError as Zt, createLogger as _, ValidationIssue as _t, LogFormat as a, ErrorEntry as at, exponentialDelayCapMs as b, ValidationProblemDetails as bt, LogThreshold as c, ErrorTagOf as ct, LoggerConfig as d, sharedErrors as dt, shouldRetryFailure as en, unreachable as et, LoggerErrorHook as f, MalformedRequestError as ft, consoleSink as g, ValidationError as gt, configureLogger as h, UpgradeRequiredError as ht, LogFields as i, ErrorEntries as it, isTransientCloudflareRuntimeError as j, RecordEmailEventPayloadSchema as jt, isCloudflareOverloadedError as k, AuthenticationError as kt, LogValue as l, ResolvedError as lt, SerializedError as m, ResourceNotFoundError as mt, ErrorLogContext as n, DatabaseError as nt, LogLevel as o, ErrorPayloadOf as ot, LoggerSettings as p, RequestTimeoutError as pt, DomainQuery as q, AnalyticsEventInput as qt, LogEntry as r, DatabaseFailure as rt, LogSink as s, ErrorTable as st, ErrorCaptureEntry as t, D1ConstraintKind as tt, Logger as u, defineErrors as ut, setLogSink as v, ProblemDetails as vt, classifyBoundaryError as w, InternalServerError as wt, exponentialEqualJitterMs as x, ValidationProblemDetailsSchema as xt, setLoggerErrorHook as y, ProblemDetailsSchema as yt, MessageDefinition as z, EmailIdempotencyKey as zt };
753
- //# sourceMappingURL=index-G1QG0P5g.d.ts.map
806
+ export { IdOf as $, AppError as $t, isCloudflareRetryableError as A, RateLimitError as At, MessageDefinition as B, EmailServiceError as Bt, BoundaryErrorClassifier as C, ValidationProblemDetailsSchema as Ct, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS as D, ServiceUnavailableError as Dt, retryAfterSecondsOf as E, InternalServerError as Et, EntityData as F, BounceTypeSchema as Ft, defineMessages as G, EmailAddressSchema as Gt, PayloadSchemas as H, InvalidEmailIdempotencyKeyError as Ht, CommandOf as I, isEmailDeliverable as It, DomainMessage as J, AnalyticsEventIdentity as Jt, DomainCommand as K, AnalyticsEventId as Kt, DuplicateMessageNameError as L, parseBounceType as Lt, isAbortError as M, RecordEmailEventPayload as Mt, isTransientTransportError as N, RecordEmailEventPayloadSchema as Nt, isCloudflareObjectResetError as O, NotAuthorizedError as Ot, Entity as P, BounceType as Pt, IdDefinition as Q, MissingConfigurationError as Qt, EventOf as R, shouldUpdateBounce as Rt, spreadJitterMs as S, ValidationProblemDetails as St, classifyFailure as T, ValidationProblemErrorSchema as Tt, QueryOf as U, emailIdempotencyKey as Ut, MessageOf as V, EmailIdempotencyKey as Vt, combineMessages as W, EmailAddress as Wt, MessageId as X, AnalyticsProperties as Xt, DomainQuery as Y, AnalyticsEventInput as Yt, Id as Z, AnalyticsProperty as Zt, createLogger as _, UpgradeRequiredError as _t, LogFormat as a, DatabaseFailure as at, exponentialDelayCapMs as b, ProblemDetails as bt, LogThreshold as c, ErrorPayloadOf as ct, LoggerConfig as d, ResolvedError as dt, FailureClassification as en, defineId as et, LoggerErrorHook as f, defineErrors as ft, consoleSink as g, ResourceNotFoundError as gt, configureLogger as h, RequestTimeoutError as ht, LogFields as i, DatabaseError as it, isTransientCloudflareRuntimeError as j, AuthenticationError as jt, isCloudflareOverloadedError as k, StaleSessionError as kt, LogValue as l, ErrorTable as lt, SerializedError as m, MalformedRequestError as mt, ErrorLogContext as n, shouldRetryFailure as nn, unreachable as nt, LogLevel as o, ErrorEntries as ot, LoggerSettings as p, sharedErrors as pt, DomainEvent as q, AnalyticsEventIdSchema as qt, LogEntry as r, D1ConstraintKind as rt, LogSink as s, ErrorEntry as st, ErrorCaptureEntry as t, RetryOwner as tn, notImplemented as tt, Logger as u, ErrorTagOf as ut, setLogSink as v, ValidationError as vt, classifyBoundaryError as w, ValidationProblemError as wt, exponentialEqualJitterMs as x, ProblemDetailsSchema as xt, setLoggerErrorHook as y, ValidationIssue as yt, MessageCollection as z, EmailSendFailureReason as zt };
807
+ //# sourceMappingURL=index-DvJUcSW1.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index-G1QG0P5g.d.ts","names":[],"sources":["../src/core/failure-classification.ts","../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/problem-details.ts","../src/core/request.errors.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/messages.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/transport-classification.ts","../src/core/cloudflare-classification.ts","../src/core/classify-failure.ts","../src/core/backoff.ts","../src/core/logger.ts"],"mappings":";;;;;;;;KAMY;;;;;;;KAQA;;iBAGI,mBAAmB;WACxB,gBAAgB;WAChB;WACA,OAAO;;;;;;;;;;;;uBCVI,iBAAiB;oBACnB;oBACA,gBAAgB;MAErB;;;;;cCXF,kCAA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ACA;;iBAOc,sBACd,qBACA,oBACA;;;;;;;;;;KCnBU,0DAMR,cAAc,YACd;;KAGQ;YAAwB,cAAc;;;;;;;cAOrC;WACX;WACA;WACA;WACA;;KAEU,mBAAmB,uBAAuB;;KAG1C;WACD;WACA;WACA;WACA,SAAS;WACT,QAAQ;WACR,SAAS,cAAc;;;KAItB;WACD;WACA,OAAO;WACP;WACA;WACA,SAAS;WACT;;WAEA,QAAQ;;;KAIP;WACD;WACA;WACA,UAAU;;;KAIT,eAAe;;UAGV;WACN,QAAQ;;;KAIP;;;;;;;UAQK,uBAAuB;WAC7B,SAAS;;;;;;iBAgBJ,gBAAgB,QAAQ;;UAQvB;WACN;WACA;WACA,SAAS;;;KAIR,mBAAmB,OAAO;;KAG1B,WAAW,OAAO;;;;;;iBASd,mBAAmB,IAAI;;;;;cA0C1B,aAAa;;;;;;;iBA6BV,WAAW,IAAI;;cAyDlB;mBAKQ;mBAJF;;EAGjB,YACmB,gBACjB,iBAAiB;UAKX;;EAuBR,MAAM,iBAAiB,UAAS;;EAKhC,KAAK,iBAAiB,UAAS;;EAK/B,KAAK,iBAAiB,UAAS;;;;;;;EAU/B,MAAM,iBAAiB,UAAS;;;iBAyBlB,aAAa,gBAAgB,SAAS,eAAe"}
1
+ {"version":3,"file":"index-DvJUcSW1.d.ts","names":[],"sources":["../src/core/failure-classification.ts","../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/problem-details.ts","../src/core/request.errors.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/messages.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/transport-classification.ts","../src/core/cloudflare-classification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WACR,SAAS,cAAc;;;KAItB;WACD;WACA,OAAO;WACP;WACA;WACA,SAAS;WACT;;WAEA,QAAQ;;;KAIP;WACD;WACA;WACA,UAAU;;;KAIT,eAAe;;UAGV;WACN,QAAQ;;;KAIP;;;;;;;UAQK,uBAAuB;WAC7B,SAAS;;;;;;iBAgBJ,gBAAgB,QAAQ;;UAQvB;WACN;WACA;WACA,SAAS;;;KAIR,mBAAmB,OAAO;;KAG1B,WAAW,OAAO;;;;;;iBASd,mBAAmB,IAAI;;;;;cA0C1B,aAAa;;;;;;;iBA6BV,WAAW,IAAI;;cAyDlB;mBAKQ;mBAJF;;EAGjB,YACmB,gBACjB,iBAAiB;UAKX;;EAuBR,MAAM,iBAAiB,UAAS;;EAKhC,KAAK,iBAAiB,UAAS;;EAK/B,KAAK,iBAAiB,UAAS;;;;;;;EAU/B,MAAM,iBAAiB,UAAS;;;iBAyBlB,aAAa,gBAAgB,SAAS,eAAe"}
@@ -1,5 +1,5 @@
1
- import "./index-G1QG0P5g.js";
2
- import { F as IEventCollector } from "./index-C28HgVfY.js";
1
+ import "./index-DvJUcSW1.js";
2
+ import { F as IEventCollector } from "./index-Cchdg2aQ.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-BZjfDqGf.d.ts.map
26
+ //# sourceMappingURL=outbox-repository-options-AkihEaik.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"outbox-repository-options-BZjfDqGf.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-AkihEaik.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,4 +1,4 @@
1
- import { t as UnitOfWorkAlreadyActiveError } from "./application-C4JOf71r.js";
1
+ import { t as UnitOfWorkAlreadyActiveError } from "./application-Cf9SER-i.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-DOTpJH-e.js.map
57
+ //# sourceMappingURL=outbox-repository-options-ICOF8g2h.js.map