better-ship 0.18.0 → 0.19.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.
- package/dist/{application-CNdzHIXk.js → application-Dg1jIKPe.js} +2 -2
- package/dist/{application-CNdzHIXk.js.map → application-Dg1jIKPe.js.map} +1 -1
- package/dist/application.js +1 -1
- package/dist/better-auth/apple-client-secret.js +1 -1
- package/dist/better-auth/auth-client.js +1 -1
- package/dist/better-auth/rate-limit.js +1 -1
- package/dist/better-auth.js +1 -1
- package/dist/billing/client.js +1 -1
- package/dist/cloudflare/auth-secondary-storage.js +1 -1
- package/dist/cloudflare/durable-object-client.js +1 -1
- package/dist/cloudflare/durable-object-errors.js +1 -1
- package/dist/cloudflare/kv-client.js +1 -1
- package/dist/cloudflare/kv-errors.js +1 -1
- package/dist/cloudflare/queue.js +2 -2
- package/dist/cloudflare/r2-client.js +1 -1
- package/dist/cloudflare/r2-errors.js +1 -1
- package/dist/cloudflare/scheduled.js +1 -1
- package/dist/cloudflare.js +3 -3
- package/dist/{core-UUW2unJd.js → core-BT1dSEQI.js} +2 -2
- package/dist/{core-UUW2unJd.js.map → core-BT1dSEQI.js.map} +1 -1
- package/dist/core.js +1 -1
- package/dist/http.d.ts +15 -7
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +50 -11
- package/dist/http.js.map +1 -1
- package/dist/{outbox-repository-options-CgdqU20T.js → outbox-repository-options-B8TnAE1h.js} +2 -2
- package/dist/{outbox-repository-options-CgdqU20T.js.map → outbox-repository-options-B8TnAE1h.js.map} +1 -1
- package/dist/postgres.js +3 -3
- package/dist/posthog/server.js +1 -1
- package/dist/resend.d.ts +3 -3
- package/dist/resend.d.ts.map +1 -1
- package/dist/resend.js +30 -57
- package/dist/resend.js.map +1 -1
- package/dist/sentry/client.js +1 -1
- package/dist/stripe/payment-service.error.js +1 -1
- package/dist/stripe/payment-webhook.d.ts +3 -3
- package/dist/stripe/payment-webhook.d.ts.map +1 -1
- package/dist/stripe/payment-webhook.js +6 -18
- package/dist/stripe/payment-webhook.js.map +1 -1
- package/dist/tanstack.js +1 -1
- package/dist/{webhook-verification-BuxPzdr4.d.ts → webhook-verification-D1c7BY4q.d.ts} +8 -16
- package/dist/webhook-verification-D1c7BY4q.d.ts.map +1 -0
- package/dist/{webhook-verification-BBmjkHgI.js → webhook-verification-qSFXv5H3.js} +2 -2
- package/dist/webhook-verification-qSFXv5H3.js.map +1 -0
- package/package.json +1 -1
- package/src/core/console-log-sink.ts +1 -5
- package/src/infrastructure/http/index.ts +2 -6
- package/src/infrastructure/http/webhook-handler.ts +68 -11
- package/src/infrastructure/http/webhook-verification.ts +6 -9
- package/src/infrastructure/resend/email-event.ts +14 -30
- package/src/infrastructure/resend/resend-webhook.ts +12 -22
- package/src/infrastructure/stripe/payment-webhook.ts +7 -20
- package/dist/webhook-verification-BBmjkHgI.js.map +0 -1
- package/dist/webhook-verification-BuxPzdr4.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core-UUW2unJd.js","names":["uuidv7","uuidv7"],"sources":["../src/core/app-error.ts","../src/core/missing-configuration.error.ts","../src/core/analytics-event.ts","../src/core/email-address.ts","../src/core/email-idempotency-key.ts","../src/core/email-service.error.ts","../src/core/email-deliverability.ts","../src/core/record-email-event.ts","../src/core/authentication.error.ts","../src/core/rate-limit.error.ts","../src/core/stale-session.error.ts","../src/core/not-authorized.error.ts","../src/core/internal.errors.ts","../src/core/request.errors.ts","../src/core/problem-details.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/failure-classification.ts","../src/core/transport-classification.ts","../src/core/cloudflare-classification.ts","../src/core/classify-failure.ts","../src/core/backoff.ts","../src/core/console-log-sink.ts","../src/core/logger.ts"],"sourcesContent":["import type { FailureClassification } from './failure-classification.ts'\n\n/**\n * The base of every expected failure. A subclass declares its tag and its classification,\n * so no boundary has to guess what kind of failure it holds. A boundary tells our errors from\n * raw throws with `instanceof AppError`; a value that fails it was never judged.\n *\n * A `readonly` field with a literal initializer keeps the literal type, so\n * `readonly _tag = 'StoreUnavailable'` is enough for `Result` unions and `matchError`.\n */\nexport abstract class AppError extends Error {\n abstract readonly _tag: string\n abstract readonly classification: FailureClassification\n\n override get name(): string {\n return this._tag\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** Required configuration is absent. Ported from Porte's configuration.errors.ts. */\nexport class MissingConfigurationError extends AppError {\n readonly _tag = 'MissingConfigurationError'\n readonly classification = 'terminal'\n\n /** Name the missing setting without including its value. */\n constructor(readonly key: string) {\n super(`${key} is required`)\n }\n}\n","import { z } from 'zod'\n\n/** An event name and its application-owned properties, ported from Typist's analytics/types.ts. */\nexport interface AnalyticsEventInput<\n TName extends string = string,\n TProperties extends object = object,\n> {\n readonly name: TName\n readonly properties: TProperties\n}\n\n/** A value supported by analytics person properties. */\nexport type AnalyticsProperty =\n | string\n | number\n | boolean\n | null\n | undefined\n | readonly AnalyticsProperty[]\n | AnalyticsProperties\n\n/** Person properties supplied by the application. */\nexport interface AnalyticsProperties {\n readonly [name: string]: AnalyticsProperty\n}\n\n/** Parse a persisted analytics event UUID; the SDK generates ordinary event UUIDs itself. */\nexport const AnalyticsEventIdSchema = z.uuid().brand<'AnalyticsEventId'>()\n\n/** The identity of one analytics event across repeated application deliveries. */\nexport type AnalyticsEventId = z.infer<typeof AnalyticsEventIdSchema>\n\n/** Supply both original values when replaying one event; never share them across different occurrences. */\nexport interface AnalyticsEventIdentity {\n readonly uuid: AnalyticsEventId\n readonly timestamp: Date\n}\n","import { z } from 'zod'\n\n/** A parsed email address for message payloads and webhook recipients. Ported from Typist's `EmailSchema`. */\nexport const EmailAddressSchema = z.email().brand<'EmailAddress'>()\n\n/** An address the schema accepted. */\nexport type EmailAddress = z.infer<typeof EmailAddressSchema>\n","import type { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\n\n/** A key only `emailIdempotencyKey` mints, so every send carries one built by its rules. */\nexport type EmailIdempotencyKey = string & z.core.$brand<'EmailIdempotencyKey'>\n\n// Resend accepts 1 to 256 characters. Source: https://resend.com/docs/dashboard/emails/idempotency-keys\nconst MAX_KEY_LENGTH = 256\n\n/** A key outside 1 to 256 characters. Keys come from stable ids, so this is a defect, not a retry. */\nexport class InvalidEmailIdempotencyKeyError extends AppError {\n readonly _tag = 'InvalidEmailIdempotencyKeyError'\n readonly classification = 'terminal'\n\n constructor(readonly length: number) {\n super(`Email idempotency key must have 1 to ${MAX_KEY_LENGTH} characters`)\n }\n}\n\n/**\n * `<scope>/<id>` for one logical send. Resend deduplicates it for 24 hours.\n * Derive `id` from a stable identity: a message id, a job id, a user id with a template name.\n * The same key must map to an identical payload; a changed body is rejected as terminal.\n * A random `id` means every request is a deliberate new send, as a sign-in code resend is.\n * Source: https://resend.com/docs/dashboard/emails/idempotency-keys\n */\nexport function emailIdempotencyKey(scope: string, id: string): EmailIdempotencyKey {\n const key = `${scope}/${id}`\n if (scope.length === 0 || id.length === 0 || key.length > MAX_KEY_LENGTH)\n throw new InvalidEmailIdempotencyKeyError(key.length)\n // SAFETY: the brand is a compile-time mark; the checks above are the whole rule.\n return key as EmailIdempotencyKey\n}\n","import { AppError } from './app-error.ts'\nimport type { FailureClassification } from './failure-classification.ts'\n\n/** Why the provider rejected a send. The reason owns the classification, so the two never disagree. */\nexport type EmailSendFailureReason =\n | 'rate_limited'\n | 'idempotency_conflict'\n | 'provider_error'\n | 'quota_exceeded'\n | 'invalid_request'\n | 'configuration'\n\nconst CLASSIFICATION_BY_REASON = {\n rate_limited: 'transient',\n idempotency_conflict: 'transient',\n provider_error: 'transient',\n quota_exceeded: 'terminal',\n invalid_request: 'terminal',\n configuration: 'terminal',\n} satisfies Record<EmailSendFailureReason, FailureClassification>\n\n/**\n * The provider rejected a send. The boundary that awaited the send logs once; the adapter never does.\n * `retryAfter` is the server's delay in seconds when it sent one, so `retryAfterSecondsOf` reads it.\n */\nexport class EmailServiceError extends AppError {\n readonly _tag = 'EmailServiceError'\n readonly classification: FailureClassification\n readonly reason: EmailSendFailureReason\n readonly provider: string\n readonly providerCode: string\n readonly statusCode: number | null\n readonly retryAfter: number | null\n\n constructor(args: {\n readonly reason: EmailSendFailureReason\n readonly provider: string\n readonly providerCode: string\n readonly statusCode: number | null\n readonly retryAfter: number | null\n readonly cause: unknown\n }) {\n super(`Email 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","import type { LogEntry, LogFields, LogFormat, LogLevel, LogSink } from './logger.ts'\n\nconst METHOD = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n} as const satisfies Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'>\n\nconst ESC = String.fromCharCode(27)\nconst RESET = `${ESC}[0m`\nconst LEVEL_COLOR = {\n DEBUG: `${ESC}[2;36m`,\n INFO: `${ESC}[34m`,\n WARN: `${ESC}[33m`,\n ERROR: `${ESC}[1;31m`,\n} satisfies Record<LogLevel, string>\n\nlet format: LogFormat = 'json'\n\nexport function setConsoleLogFormat(value: LogFormat): void {\n format = value\n}\n\nfunction contextOf(entry: LogEntry): LogFields | undefined {\n const context = { ...entry.attributes }\n if (entry.userId !== undefined) context.userId = entry.userId\n return Object.keys(context).length === 0 ? undefined : context\n}\n\nfunction jsonEntry(entry: LogEntry): LogEntry {\n if (!(entry.error instanceof Error)) return entry\n const error = { name: entry.error.name, message: entry.error.message, stack: entry.error.stack }\n return { ...entry, error }\n}\n\n/** Write one structured record or one readable development entry to `console`. */\nexport const consoleSink: LogSink = (entry) => {\n const write = console[METHOD[entry.level]]\n if (format === 'json') {\n write(jsonEntry(entry))\n return\n }\n\n const context = contextOf(entry)\n const values = context === undefined ? [] : [context]\n const errors = entry.error === undefined ? [] : [entry.error]\n if (format === 'pretty-browser') {\n write(\n `%c${entry.timestamp}%c [${entry.level}] %c[${entry.module}]%c ${entry.event}`,\n 'color: #737373',\n '',\n 'color: #2563eb',\n '',\n ...values,\n ...errors,\n )\n return\n }\n write(\n `${ESC}[90m${entry.timestamp}${RESET} ${LEVEL_COLOR[entry.level]}[${entry.level}]${RESET} ${ESC}[34m[${entry.module}]${RESET} ${entry.event}`,\n ...values,\n ...errors,\n )\n}\n","import { consoleSink, setConsoleLogFormat } from './console-log-sink.ts'\n\n/** One JSON-compatible value in a normal log field. */\nexport type LogValue =\n | string\n | number\n | boolean\n | null\n | readonly LogValue[]\n | { readonly [key: string]: LogValue }\n\n/** Flat fields for one log call. Only `error` can contain an arbitrary value. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- A logger accepts caller-owned fields at its public boundary.\nexport type LogFields = Readonly<Record<string, unknown>>\n\n/** Supported log levels in ascending order. */\nexport const LogLevel = {\n DEBUG: 'DEBUG',\n INFO: 'INFO',\n WARN: 'WARN',\n ERROR: 'ERROR',\n} as const\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]\n\n/** The minimum emitted level, or `OFF` for no console output. */\nexport type LogThreshold = LogLevel | 'OFF'\n\n/** Explicit output formats for production, browser development, and terminal development. */\nexport type LogFormat = 'json' | 'pretty-browser' | 'pretty-terminal'\n\n/** Process-wide logger settings supplied at startup. */\nexport interface LoggerSettings {\n readonly level?: LogThreshold\n readonly format?: LogFormat\n}\n\n/** One structured record sent to a log sink. */\nexport type LogEntry = {\n readonly timestamp: string\n readonly level: LogLevel\n readonly module: string\n readonly event: string\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- The entry keeps caller-owned fields for its sink.\n readonly attributes: LogFields\n readonly userId?: string\n readonly error?: unknown\n}\n\n/** The original error and fields sent to an error service. */\nexport interface ErrorCaptureEntry {\n readonly error: unknown\n readonly userId: string | undefined\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Sentry accepts the caller-owned fields as extra context.\n readonly attributes: LogFields\n}\n\n/** A function that forwards one error to an error service. */\nexport type LoggerErrorHook = (entry: ErrorCaptureEntry) => void\n\n/** A destination for structured log records. */\nexport type LogSink = (entry: LogEntry) => void\n\n/** The common flat logger API for all levels. */\nexport interface Logger {\n debug(event: string, fields?: LogFields): void\n info(event: string, fields?: LogFields): void\n warn(event: string, fields?: LogFields): void\n error(event: string, fields?: LogFields): void\n}\n\nconst LEVELS = Object.values(LogLevel)\nlet threshold: LogThreshold = LogLevel.INFO\nlet logSink: LogSink = consoleSink\nlet errorHook: LoggerErrorHook | null = null\n\n/** Set the process-wide level and output format. Omitted fields restore production defaults. */\nexport function configureLogger(settings: LoggerSettings): void {\n threshold = settings.level ?? LogLevel.INFO\n setConsoleLogFormat(settings.format ?? 'json')\n}\n\n/** Set the process-wide log destination. */\nexport function setLogSink(sink: LogSink): void {\n logSink = sink\n}\n\n/** Set or clear the process-wide error service hook. */\nexport function setLoggerErrorHook(hook: LoggerErrorHook | null): void {\n errorHook = hook\n}\n\n/* oxlint-disable anti-slop/no-runtime-typeof -- The logger validates its reserved userId field. */\nfunction splitFields(fields: LogFields): ErrorCaptureEntry {\n const { error, userId, ...attributes } = fields\n return { error, userId: typeof userId === 'string' ? userId : undefined, attributes }\n}\n/* oxlint-enable anti-slop/no-runtime-typeof */\n\nfunction writeLog(module: string, level: LogLevel, event: string, fields: LogFields): void {\n if (threshold === 'OFF' || LEVELS.indexOf(level) < LEVELS.indexOf(threshold)) return\n\n const { error, userId, attributes } = splitFields(fields)\n let entry: LogEntry = { timestamp: new Date().toISOString(), level, module, event, attributes }\n if (userId !== undefined) entry = { ...entry, userId }\n if (error !== undefined) entry = { ...entry, error }\n try {\n logSink(entry)\n } catch {\n // A diagnostic failure must not change application control flow.\n }\n}\n\n/** Create a logger for one module. */\nexport function createLogger(module: string): Logger {\n return {\n debug: (event, fields = {}) => writeLog(module, LogLevel.DEBUG, event, fields),\n info: (event, fields = {}) => writeLog(module, LogLevel.INFO, event, fields),\n warn: (event, fields = {}) => writeLog(module, LogLevel.WARN, event, fields),\n error: (event, fields = {}) => {\n writeLog(module, LogLevel.ERROR, event, fields)\n const capture = splitFields(fields)\n if (errorHook === null || capture.error === undefined) return\n try {\n errorHook(capture)\n } catch {\n // An error service failure must not change application control flow.\n }\n },\n }\n}\n\nexport { consoleSink }\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAsB,WAAtB,cAAuC,MAAM;CAI3C,IAAa,OAAe;EAC1B,OAAO,KAAK;CACd;AACF;;;;;ACdA,IAAa,4BAAb,cAA+C,SAAS;CAKjC;CAJrB,AAAS,OAAO;CAChB,AAAS,iBAAiB;;CAG1B,YAAY,AAAS,KAAa;EAChC,MAAM,GAAG,IAAI,aAAa;EADP;CAErB;AACF;;;;;ACgBA,MAAa,yBAAyB,EAAE,KAAK,CAAC,CAAC,MAA0B;;;;;ACxBzE,MAAa,qBAAqB,EAAE,MAAM,CAAC,CAAC,MAAsB;;;;ACKlE,MAAM,iBAAiB;;AAGvB,IAAa,kCAAb,cAAqD,SAAS;CAIvC;CAHrB,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,YAAY,AAAS,QAAgB;EACnC,MAAM,wCAAwC,eAAe,YAAY;EADtD;CAErB;AACF;;;;;;;;AASA,SAAgB,oBAAoB,OAAe,IAAiC;CAClF,MAAM,MAAM,GAAG,MAAM,GAAG;CACxB,IAAI,MAAM,WAAW,KAAK,GAAG,WAAW,KAAK,IAAI,SAAS,gBACxD,MAAM,IAAI,gCAAgC,I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AU,YAAY,MAAM;GAClC,IAAI,cAAc,QAAQ,QAAQ,UAAU,QAAW;GACvD,IAAI;IACF,UAAU,OAAO;GACnB,QAAQ,CAER;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"core-BT1dSEQI.js","names":["uuidv7","uuidv7"],"sources":["../src/core/app-error.ts","../src/core/missing-configuration.error.ts","../src/core/analytics-event.ts","../src/core/email-address.ts","../src/core/email-idempotency-key.ts","../src/core/email-service.error.ts","../src/core/email-deliverability.ts","../src/core/record-email-event.ts","../src/core/authentication.error.ts","../src/core/rate-limit.error.ts","../src/core/stale-session.error.ts","../src/core/not-authorized.error.ts","../src/core/internal.errors.ts","../src/core/request.errors.ts","../src/core/problem-details.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/failure-classification.ts","../src/core/transport-classification.ts","../src/core/cloudflare-classification.ts","../src/core/classify-failure.ts","../src/core/backoff.ts","../src/core/console-log-sink.ts","../src/core/logger.ts"],"sourcesContent":["import type { FailureClassification } from './failure-classification.ts'\n\n/**\n * The base of every expected failure. A subclass declares its tag and its classification,\n * so no boundary has to guess what kind of failure it holds. A boundary tells our errors from\n * raw throws with `instanceof AppError`; a value that fails it was never judged.\n *\n * A `readonly` field with a literal initializer keeps the literal type, so\n * `readonly _tag = 'StoreUnavailable'` is enough for `Result` unions and `matchError`.\n */\nexport abstract class AppError extends Error {\n abstract readonly _tag: string\n abstract readonly classification: FailureClassification\n\n override get name(): string {\n return this._tag\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** Required configuration is absent. Ported from Porte's configuration.errors.ts. */\nexport class MissingConfigurationError extends AppError {\n readonly _tag = 'MissingConfigurationError'\n readonly classification = 'terminal'\n\n /** Name the missing setting without including its value. */\n constructor(readonly key: string) {\n super(`${key} is required`)\n }\n}\n","import { z } from 'zod'\n\n/** An event name and its application-owned properties, ported from Typist's analytics/types.ts. */\nexport interface AnalyticsEventInput<\n TName extends string = string,\n TProperties extends object = object,\n> {\n readonly name: TName\n readonly properties: TProperties\n}\n\n/** A value supported by analytics person properties. */\nexport type AnalyticsProperty =\n | string\n | number\n | boolean\n | null\n | undefined\n | readonly AnalyticsProperty[]\n | AnalyticsProperties\n\n/** Person properties supplied by the application. */\nexport interface AnalyticsProperties {\n readonly [name: string]: AnalyticsProperty\n}\n\n/** Parse a persisted analytics event UUID; the SDK generates ordinary event UUIDs itself. */\nexport const AnalyticsEventIdSchema = z.uuid().brand<'AnalyticsEventId'>()\n\n/** The identity of one analytics event across repeated application deliveries. */\nexport type AnalyticsEventId = z.infer<typeof AnalyticsEventIdSchema>\n\n/** Supply both original values when replaying one event; never share them across different occurrences. */\nexport interface AnalyticsEventIdentity {\n readonly uuid: AnalyticsEventId\n readonly timestamp: Date\n}\n","import { z } from 'zod'\n\n/** A parsed email address for message payloads and webhook recipients. Ported from Typist's `EmailSchema`. */\nexport const EmailAddressSchema = z.email().brand<'EmailAddress'>()\n\n/** An address the schema accepted. */\nexport type EmailAddress = z.infer<typeof EmailAddressSchema>\n","import type { z } from 'zod'\n\nimport { AppError } from './app-error.ts'\n\n/** A key only `emailIdempotencyKey` mints, so every send carries one built by its rules. */\nexport type EmailIdempotencyKey = string & z.core.$brand<'EmailIdempotencyKey'>\n\n// Resend accepts 1 to 256 characters. Source: https://resend.com/docs/dashboard/emails/idempotency-keys\nconst MAX_KEY_LENGTH = 256\n\n/** A key outside 1 to 256 characters. Keys come from stable ids, so this is a defect, not a retry. */\nexport class InvalidEmailIdempotencyKeyError extends AppError {\n readonly _tag = 'InvalidEmailIdempotencyKeyError'\n readonly classification = 'terminal'\n\n constructor(readonly length: number) {\n super(`Email idempotency key must have 1 to ${MAX_KEY_LENGTH} characters`)\n }\n}\n\n/**\n * `<scope>/<id>` for one logical send. Resend deduplicates it for 24 hours.\n * Derive `id` from a stable identity: a message id, a job id, a user id with a template name.\n * The same key must map to an identical payload; a changed body is rejected as terminal.\n * A random `id` means every request is a deliberate new send, as a sign-in code resend is.\n * Source: https://resend.com/docs/dashboard/emails/idempotency-keys\n */\nexport function emailIdempotencyKey(scope: string, id: string): EmailIdempotencyKey {\n const key = `${scope}/${id}`\n if (scope.length === 0 || id.length === 0 || key.length > MAX_KEY_LENGTH)\n throw new InvalidEmailIdempotencyKeyError(key.length)\n // SAFETY: the brand is a compile-time mark; the checks above are the whole rule.\n return key as EmailIdempotencyKey\n}\n","import { AppError } from './app-error.ts'\nimport type { FailureClassification } from './failure-classification.ts'\n\n/** Why the provider rejected a send. The reason owns the classification, so the two never disagree. */\nexport type EmailSendFailureReason =\n | 'rate_limited'\n | 'idempotency_conflict'\n | 'provider_error'\n | 'quota_exceeded'\n | 'invalid_request'\n | 'configuration'\n\nconst CLASSIFICATION_BY_REASON = {\n rate_limited: 'transient',\n idempotency_conflict: 'transient',\n provider_error: 'transient',\n quota_exceeded: 'terminal',\n invalid_request: 'terminal',\n configuration: 'terminal',\n} satisfies Record<EmailSendFailureReason, FailureClassification>\n\n/**\n * The provider rejected a send. The boundary that awaited the send logs once; the adapter never does.\n * `retryAfter` is the server's delay in seconds when it sent one, so `retryAfterSecondsOf` reads it.\n */\nexport class EmailServiceError extends AppError {\n readonly _tag = 'EmailServiceError'\n readonly classification: FailureClassification\n readonly reason: EmailSendFailureReason\n readonly provider: string\n readonly providerCode: string\n readonly statusCode: number | null\n readonly retryAfter: number | null\n\n constructor(args: {\n readonly reason: EmailSendFailureReason\n readonly provider: string\n readonly providerCode: string\n readonly statusCode: number | null\n readonly retryAfter: number | null\n readonly cause: unknown\n }) {\n super(`Email 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","import type { LogEntry, LogFields, LogFormat, LogLevel, LogSink } from './logger.ts'\n\nconst METHOD = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n} as const satisfies Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'>\n\nconst ESC = String.fromCharCode(27)\nconst RESET = `${ESC}[0m`\nconst LEVEL_COLOR = {\n DEBUG: `${ESC}[2;36m`,\n INFO: `${ESC}[34m`,\n WARN: `${ESC}[33m`,\n ERROR: `${ESC}[1;31m`,\n} satisfies Record<LogLevel, string>\n\nlet format: LogFormat = 'json'\n\nexport function setConsoleLogFormat(value: LogFormat): void {\n format = value\n}\n\nfunction contextOf(entry: LogEntry): LogFields | undefined {\n const context = { ...entry.attributes }\n if (entry.userId !== undefined) context.userId = entry.userId\n return Object.keys(context).length === 0 ? undefined : context\n}\n\nfunction jsonEntry(entry: LogEntry): LogEntry {\n if (!(entry.error instanceof Error)) return entry\n const error = { name: entry.error.name, message: entry.error.message, stack: entry.error.stack }\n return { ...entry, error }\n}\n\n/** Write one structured record or one readable development entry to `console`. */\nexport const consoleSink: LogSink = (entry) => {\n const write = console[METHOD[entry.level]]\n if (format === 'json') {\n write(jsonEntry(entry))\n return\n }\n\n const context = contextOf(entry)\n const values = context === undefined ? [] : [context]\n const errors = entry.error === undefined ? [] : [entry.error]\n if (format === 'pretty-browser') {\n write(\n `${entry.timestamp} [${entry.level}] [${entry.module}] ${entry.event}`,\n ...values,\n ...errors,\n )\n return\n }\n write(\n `${ESC}[90m${entry.timestamp}${RESET} ${LEVEL_COLOR[entry.level]}[${entry.level}]${RESET} ${ESC}[34m[${entry.module}]${RESET} ${entry.event}`,\n ...values,\n ...errors,\n )\n}\n","import { consoleSink, setConsoleLogFormat } from './console-log-sink.ts'\n\n/** One JSON-compatible value in a normal log field. */\nexport type LogValue =\n | string\n | number\n | boolean\n | null\n | readonly LogValue[]\n | { readonly [key: string]: LogValue }\n\n/** Flat fields for one log call. Only `error` can contain an arbitrary value. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- A logger accepts caller-owned fields at its public boundary.\nexport type LogFields = Readonly<Record<string, unknown>>\n\n/** Supported log levels in ascending order. */\nexport const LogLevel = {\n DEBUG: 'DEBUG',\n INFO: 'INFO',\n WARN: 'WARN',\n ERROR: 'ERROR',\n} as const\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]\n\n/** The minimum emitted level, or `OFF` for no console output. */\nexport type LogThreshold = LogLevel | 'OFF'\n\n/** Explicit output formats for production, browser development, and terminal development. */\nexport type LogFormat = 'json' | 'pretty-browser' | 'pretty-terminal'\n\n/** Process-wide logger settings supplied at startup. */\nexport interface LoggerSettings {\n readonly level?: LogThreshold\n readonly format?: LogFormat\n}\n\n/** One structured record sent to a log sink. */\nexport type LogEntry = {\n readonly timestamp: string\n readonly level: LogLevel\n readonly module: string\n readonly event: string\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- The entry keeps caller-owned fields for its sink.\n readonly attributes: LogFields\n readonly userId?: string\n readonly error?: unknown\n}\n\n/** The original error and fields sent to an error service. */\nexport interface ErrorCaptureEntry {\n readonly error: unknown\n readonly userId: string | undefined\n // oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Sentry accepts the caller-owned fields as extra context.\n readonly attributes: LogFields\n}\n\n/** A function that forwards one error to an error service. */\nexport type LoggerErrorHook = (entry: ErrorCaptureEntry) => void\n\n/** A destination for structured log records. */\nexport type LogSink = (entry: LogEntry) => void\n\n/** The common flat logger API for all levels. */\nexport interface Logger {\n debug(event: string, fields?: LogFields): void\n info(event: string, fields?: LogFields): void\n warn(event: string, fields?: LogFields): void\n error(event: string, fields?: LogFields): void\n}\n\nconst LEVELS = Object.values(LogLevel)\nlet threshold: LogThreshold = LogLevel.INFO\nlet logSink: LogSink = consoleSink\nlet errorHook: LoggerErrorHook | null = null\n\n/** Set the process-wide level and output format. Omitted fields restore production defaults. */\nexport function configureLogger(settings: LoggerSettings): void {\n threshold = settings.level ?? LogLevel.INFO\n setConsoleLogFormat(settings.format ?? 'json')\n}\n\n/** Set the process-wide log destination. */\nexport function setLogSink(sink: LogSink): void {\n logSink = sink\n}\n\n/** Set or clear the process-wide error service hook. */\nexport function setLoggerErrorHook(hook: LoggerErrorHook | null): void {\n errorHook = hook\n}\n\n/* oxlint-disable anti-slop/no-runtime-typeof -- The logger validates its reserved userId field. */\nfunction splitFields(fields: LogFields): ErrorCaptureEntry {\n const { error, userId, ...attributes } = fields\n return { error, userId: typeof userId === 'string' ? userId : undefined, attributes }\n}\n/* oxlint-enable anti-slop/no-runtime-typeof */\n\nfunction writeLog(module: string, level: LogLevel, event: string, fields: LogFields): void {\n if (threshold === 'OFF' || LEVELS.indexOf(level) < LEVELS.indexOf(threshold)) return\n\n const { error, userId, attributes } = splitFields(fields)\n let entry: LogEntry = { timestamp: new Date().toISOString(), level, module, event, attributes }\n if (userId !== undefined) entry = { ...entry, userId }\n if (error !== undefined) entry = { ...entry, error }\n try {\n logSink(entry)\n } catch {\n // A diagnostic failure must not change application control flow.\n }\n}\n\n/** Create a logger for one module. */\nexport function createLogger(module: string): Logger {\n return {\n debug: (event, fields = {}) => writeLog(module, LogLevel.DEBUG, event, fields),\n info: (event, fields = {}) => writeLog(module, LogLevel.INFO, event, fields),\n warn: (event, fields = {}) => writeLog(module, LogLevel.WARN, event, fields),\n error: (event, fields = {}) => {\n writeLog(module, LogLevel.ERROR, event, fields)\n const capture = splitFields(fields)\n if (errorHook === null || capture.error === undefined) return\n try {\n errorHook(capture)\n } catch {\n // An error service failure must not change application control flow.\n }\n },\n }\n}\n\nexport { consoleSink }\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAsB,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AG;CAE9E,MAAM,EAAE,OAAO,QAAQ,eAAe,YAAY,MAAM;CACxD,IAAI,QAAkB;EAAE,4BAAW,IAAI,KAAK,EAAC,CAAC,YAAY;EAAG;EAAO;EAAQ;EAAO;CAAW;CAC9F,IAAI,WAAW,QAAW,QAAQ;EAAE,GAAG;EAAO;CAAO;CACrD,IAAI,UAAU,QAAW,QAAQ;EAAE,GAAG;EAAO;CAAM;CACnD,IAAI;EACF,QAAQ,KAAK;CACf,QAAQ,CAER;AACF;;AAGA,SAAgB,aAAa,QAAwB;CACnD,OAAO;EACL,QAAQ,OAAO,SAAS,CAAC,MAAM,SAAS,QAAQ,SAAS,OAAO,OAAO,MAAM;EAC7E,OAAO,OAAO,SAAS,CAAC,MAAM,SAAS,QAAQ,SAAS,MAAM,OAAO,MAAM;EAC3E,OAAO,OAAO,SAAS,CAAC,MAAM,SAAS,QAAQ,SAAS,MAAM,OAAO,MAAM;EAC3E,QAAQ,OAAO,SAAS,CAAC,MAAM;GAC7B,SAAS,QAAQ,SAAS,OAAO,OAAO,MAAM;GAC9C,MAAM,UAAU,YAAY,MAAM;GAClC,IAAI,cAAc,QAAQ,QAAQ,UAAU,QAAW;GACvD,IAAI;IACF,UAAU,OAAO;GACnB,QAAQ,CAER;EACF;CACF;AACF"}
|
package/dist/core.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $ as EmailAddressSchema, A as sharedErrors, B as ServiceUnavailableError, C as combineMessages, D as unreachable, E as notImplemented, F as RequestTimeoutError, G as RecordEmailEventPayloadSchema, H as StaleSessionError, I as ResourceNotFoundError, J as parseBounceType, K as BounceTypeSchema, L as UpgradeRequiredError, M as ValidationProblemDetailsSchema, N as ValidationProblemErrorSchema, O as DatabaseError, P as MalformedRequestError, Q as emailIdempotencyKey, R as ValidationError, S as DuplicateMessageNameError, T as defineId, U as RateLimitError, V as NotAuthorizedError, W as AuthenticationError, X as EmailServiceError, Y as shouldUpdateBounce, Z as InvalidEmailIdempotencyKeyError, _ as isTransientCloudflareRuntimeError, a as setLoggerErrorHook, b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, et as AnalyticsEventIdSchema, f as retryAfterSecondsOf, g as isCloudflareRetryableError, h as isCloudflareOverloadedError, i as setLogSink, j as ProblemDetailsSchema, k as defineErrors, l as spreadJitterMs, m as isCloudflareObjectResetError, n as configureLogger, nt as AppError, o as consoleSink, p as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, q as isEmailDeliverable, r as createLogger, s as exponentialDelayCapMs, t as LogLevel, tt as MissingConfigurationError, u as classifyBoundaryError, v as isAbortError, w as defineMessages, x as Entity, y as isTransientTransportError, z as InternalServerError } from "./core-
|
|
1
|
+
import { $ as EmailAddressSchema, A as sharedErrors, B as ServiceUnavailableError, C as combineMessages, D as unreachable, E as notImplemented, F as RequestTimeoutError, G as RecordEmailEventPayloadSchema, H as StaleSessionError, I as ResourceNotFoundError, J as parseBounceType, K as BounceTypeSchema, L as UpgradeRequiredError, M as ValidationProblemDetailsSchema, N as ValidationProblemErrorSchema, O as DatabaseError, P as MalformedRequestError, Q as emailIdempotencyKey, R as ValidationError, S as DuplicateMessageNameError, T as defineId, U as RateLimitError, V as NotAuthorizedError, W as AuthenticationError, X as EmailServiceError, Y as shouldUpdateBounce, Z as InvalidEmailIdempotencyKeyError, _ as isTransientCloudflareRuntimeError, a as setLoggerErrorHook, b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, et as AnalyticsEventIdSchema, f as retryAfterSecondsOf, g as isCloudflareRetryableError, h as isCloudflareOverloadedError, i as setLogSink, j as ProblemDetailsSchema, k as defineErrors, l as spreadJitterMs, m as isCloudflareObjectResetError, n as configureLogger, nt as AppError, o as consoleSink, p as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, q as isEmailDeliverable, r as createLogger, s as exponentialDelayCapMs, t as LogLevel, tt as MissingConfigurationError, u as classifyBoundaryError, v as isAbortError, w as defineMessages, x as Entity, y as isTransientTransportError, z as InternalServerError } from "./core-BT1dSEQI.js";
|
|
2
2
|
|
|
3
3
|
export { AnalyticsEventIdSchema, AppError, AuthenticationError, BounceTypeSchema, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, DatabaseError, DuplicateMessageNameError, EmailAddressSchema, EmailServiceError, Entity, InternalServerError, InvalidEmailIdempotencyKeyError, LogLevel, MalformedRequestError, MissingConfigurationError, NotAuthorizedError, ProblemDetailsSchema, RateLimitError, RecordEmailEventPayloadSchema, RequestTimeoutError, ResourceNotFoundError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, ValidationProblemDetailsSchema, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, combineMessages, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, emailIdempotencyKey, exponentialDelayCapMs, exponentialEqualJitterMs, isAbortError, isCloudflareObjectResetError, isCloudflareOverloadedError, isCloudflareRetryableError, isEmailDeliverable, isTransientCloudflareRuntimeError, isTransientTransportError, notImplemented, parseBounceType, retryAfterSecondsOf, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, shouldUpdateBounce, spreadJitterMs, unreachable };
|
package/dist/http.d.ts
CHANGED
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
import { l as Logger } from "./index-DUFS0SJ_.js";
|
|
2
|
-
import { n as
|
|
2
|
+
import { n as WebhookVerifier, t as WebhookVerificationError } from "./webhook-verification-D1c7BY4q.js";
|
|
3
3
|
//#region src/infrastructure/http/webhook-handler.d.ts
|
|
4
|
+
/** Application policy and diagnostics for one webhook body. */
|
|
5
|
+
type WebhookHandlerOptions = {
|
|
6
|
+
readonly maxBodyBytes: number;
|
|
7
|
+
readonly logger?: Pick<Logger, 'warn'>;
|
|
8
|
+
};
|
|
4
9
|
/** Read raw webhook requests and acknowledge effects only after the callback completes. */
|
|
5
|
-
export declare class WebhookHandler<
|
|
10
|
+
export declare class WebhookHandler<Verified> {
|
|
6
11
|
private readonly verifier;
|
|
7
12
|
private readonly logger;
|
|
8
|
-
|
|
9
|
-
|
|
13
|
+
private readonly maxBodyBytes;
|
|
14
|
+
/** Inject provider verification, the application body limit, and optional diagnostics. */
|
|
15
|
+
constructor(verifier: WebhookVerifier<Verified>, options: WebhookHandlerOptions);
|
|
10
16
|
/**
|
|
11
|
-
* Return 401 for authentication failure, 400 for invalid content, and 200 after callback completion or an ignored event.
|
|
17
|
+
* Return 413 for large content, 401 for authentication failure, 400 for invalid content, and 200 after callback completion or an ignored event.
|
|
12
18
|
* Operational and callback failures propagate to the route's error boundary without an acknowledgment.
|
|
13
19
|
*/
|
|
14
|
-
handle(request: Request,
|
|
20
|
+
handle(request: Request, onVerified: (value: Verified) => Promise<void>): Promise<Response>;
|
|
21
|
+
private readBody;
|
|
22
|
+
private rejectBodyTooLarge;
|
|
15
23
|
private reject;
|
|
16
24
|
}
|
|
17
25
|
//#endregion
|
|
18
|
-
export { type
|
|
26
|
+
export { type WebhookHandlerOptions, WebhookVerificationError, type WebhookVerifier };
|
|
19
27
|
//# sourceMappingURL=http.d.ts.map
|
package/dist/http.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.d.ts","names":[],"sources":["../src/infrastructure/http/webhook-handler.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"http.d.ts","names":[],"sources":["../src/infrastructure/http/webhook-handler.ts"],"mappings":";;;;KAOY;WACD;WACA,SAAS,KAAK;;;qBAIZ,eAAe;mBAMP;mBALF;mBACA;;EAGjB,YACmB,UAAU,gBAAgB,WAC3C,SAAS;;;;;EAUL,OACJ,SAAS,SACT,aAAa,OAAO,aAAa,gBAChC,QAAQ;UAcG;UA+BN;UAKA"}
|
package/dist/http.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as createLogger } from "./core-
|
|
2
|
-
import { t as WebhookVerificationError } from "./webhook-verification-
|
|
1
|
+
import { r as createLogger } from "./core-BT1dSEQI.js";
|
|
2
|
+
import { t as WebhookVerificationError } from "./webhook-verification-qSFXv5H3.js";
|
|
3
3
|
import { StatusCodes } from "http-status-codes";
|
|
4
4
|
|
|
5
5
|
//#region src/infrastructure/http/webhook-handler.ts
|
|
@@ -7,22 +7,61 @@ import { StatusCodes } from "http-status-codes";
|
|
|
7
7
|
var WebhookHandler = class {
|
|
8
8
|
verifier;
|
|
9
9
|
logger;
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
maxBodyBytes;
|
|
11
|
+
/** Inject provider verification, the application body limit, and optional diagnostics. */
|
|
12
|
+
constructor(verifier, options) {
|
|
12
13
|
this.verifier = verifier;
|
|
13
|
-
this.logger = logger;
|
|
14
|
+
this.logger = options.logger ?? createLogger("webhook");
|
|
15
|
+
this.maxBodyBytes = options.maxBodyBytes;
|
|
14
16
|
}
|
|
15
17
|
/**
|
|
16
|
-
* Return 401 for authentication failure, 400 for invalid content, and 200 after callback completion or an ignored event.
|
|
18
|
+
* Return 413 for large content, 401 for authentication failure, 400 for invalid content, and 200 after callback completion or an ignored event.
|
|
17
19
|
* Operational and callback failures propagate to the route's error boundary without an acknowledgment.
|
|
18
20
|
*/
|
|
19
|
-
async handle(request,
|
|
20
|
-
const body = await
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
async handle(request, onVerified) {
|
|
22
|
+
const body = await this.readBody(request);
|
|
23
|
+
if (body === null) return this.rejectBodyTooLarge();
|
|
24
|
+
let verified;
|
|
25
|
+
try {
|
|
26
|
+
verified = await this.verifier.verify(body, request.headers);
|
|
27
|
+
} catch (cause) {
|
|
28
|
+
if (cause instanceof WebhookVerificationError) return this.reject(cause);
|
|
29
|
+
throw cause;
|
|
30
|
+
}
|
|
31
|
+
if (verified !== null) await onVerified(verified);
|
|
24
32
|
return new Response(null, { status: StatusCodes.OK });
|
|
25
33
|
}
|
|
34
|
+
async readBody(request) {
|
|
35
|
+
const contentLength = request.headers.get("content-length");
|
|
36
|
+
if (contentLength !== null && /^\d+$/.test(contentLength)) {
|
|
37
|
+
if (Number(contentLength) > this.maxBodyBytes) return null;
|
|
38
|
+
}
|
|
39
|
+
if (request.body === null) return "";
|
|
40
|
+
const reader = request.body.getReader();
|
|
41
|
+
const decoder = new TextDecoder();
|
|
42
|
+
let body = "";
|
|
43
|
+
let byteCount = 0;
|
|
44
|
+
try {
|
|
45
|
+
while (true) {
|
|
46
|
+
const chunk = await reader.read();
|
|
47
|
+
if (chunk.done) return body + decoder.decode();
|
|
48
|
+
byteCount += chunk.value.byteLength;
|
|
49
|
+
if (byteCount > this.maxBodyBytes) {
|
|
50
|
+
try {
|
|
51
|
+
await reader.cancel();
|
|
52
|
+
} catch {}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
body += decoder.decode(chunk.value, { stream: true });
|
|
56
|
+
}
|
|
57
|
+
} finally {
|
|
58
|
+
reader.releaseLock();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
rejectBodyTooLarge() {
|
|
62
|
+
this.logger.warn("webhook_rejected", { reason: "body_too_large" });
|
|
63
|
+
return new Response(null, { status: StatusCodes.REQUEST_TOO_LONG });
|
|
64
|
+
}
|
|
26
65
|
reject(error) {
|
|
27
66
|
this.logger.warn("webhook_rejected", { reason: error.reason });
|
|
28
67
|
const status = error.reason === "missing_headers" || error.reason === "invalid_signature" ? StatusCodes.UNAUTHORIZED : StatusCodes.BAD_REQUEST;
|
package/dist/http.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.js","names":[],"sources":["../src/infrastructure/http/webhook-handler.ts"],"sourcesContent":["import { StatusCodes } from 'http-status-codes'\n\nimport { createLogger, type Logger } from '@/core'\n\nimport { WebhookVerificationError, type WebhookVerifier } from './webhook-verification.ts'\n\n/** Read raw webhook requests and acknowledge effects only after the callback completes. */\nexport class WebhookHandler<
|
|
1
|
+
{"version":3,"file":"http.js","names":[],"sources":["../src/infrastructure/http/webhook-handler.ts"],"sourcesContent":["import { StatusCodes } from 'http-status-codes'\n\nimport { createLogger, type Logger } from '@/core'\n\nimport { WebhookVerificationError, type WebhookVerifier } from './webhook-verification.ts'\n\n/** Application policy and diagnostics for one webhook body. */\nexport type WebhookHandlerOptions = {\n readonly maxBodyBytes: number\n readonly logger?: Pick<Logger, 'warn'>\n}\n\n/** Read raw webhook requests and acknowledge effects only after the callback completes. */\nexport class WebhookHandler<Verified> {\n private readonly logger: Pick<Logger, 'warn'>\n private readonly maxBodyBytes: number\n\n /** Inject provider verification, the application body limit, and optional diagnostics. */\n constructor(\n private readonly verifier: WebhookVerifier<Verified>,\n options: WebhookHandlerOptions,\n ) {\n this.logger = options.logger ?? createLogger('webhook')\n this.maxBodyBytes = options.maxBodyBytes\n }\n\n /**\n * Return 413 for large content, 401 for authentication failure, 400 for invalid content, and 200 after callback completion or an ignored event.\n * Operational and callback failures propagate to the route's error boundary without an acknowledgment.\n */\n async handle(\n request: Request,\n onVerified: (value: Verified) => Promise<void>,\n ): Promise<Response> {\n const body = await this.readBody(request)\n if (body === null) return this.rejectBodyTooLarge()\n let verified: Verified | null\n try {\n verified = await this.verifier.verify(body, request.headers)\n } catch (cause) {\n if (cause instanceof WebhookVerificationError) return this.reject(cause)\n throw cause\n }\n if (verified !== null) await onVerified(verified)\n return new Response(null, { status: StatusCodes.OK })\n }\n\n private async readBody(request: Request): Promise<string | null> {\n const contentLength = request.headers.get('content-length')\n if (contentLength !== null && /^\\d+$/.test(contentLength)) {\n if (Number(contentLength) > this.maxBodyBytes) return null\n }\n if (request.body === null) return ''\n\n const reader = request.body.getReader()\n const decoder = new TextDecoder()\n let body = ''\n let byteCount = 0\n try {\n while (true) {\n const chunk = await reader.read()\n if (chunk.done) return body + decoder.decode()\n byteCount += chunk.value.byteLength\n if (byteCount > this.maxBodyBytes) {\n try {\n await reader.cancel()\n } catch {\n // A cancellation failure must not replace the body-size rejection.\n }\n return null\n }\n body += decoder.decode(chunk.value, { stream: true })\n }\n } finally {\n reader.releaseLock()\n }\n }\n\n private rejectBodyTooLarge(): Response {\n this.logger.warn('webhook_rejected', { reason: 'body_too_large' })\n return new Response(null, { status: StatusCodes.REQUEST_TOO_LONG })\n }\n\n private reject(error: WebhookVerificationError): Response {\n this.logger.warn('webhook_rejected', { reason: error.reason })\n const status =\n error.reason === 'missing_headers' || error.reason === 'invalid_signature'\n ? StatusCodes.UNAUTHORIZED\n : StatusCodes.BAD_REQUEST\n return new Response(null, { status })\n }\n}\n"],"mappings":";;;;;;AAaA,IAAa,iBAAb,MAAsC;CAMjB;CALnB,AAAiB;CACjB,AAAiB;;CAGjB,YACE,AAAiB,UACjB,SACA;EAFiB;EAGjB,KAAK,SAAS,QAAQ,UAAU,aAAa,SAAS;EACtD,KAAK,eAAe,QAAQ;CAC9B;;;;;CAMA,MAAM,OACJ,SACA,YACmB;EACnB,MAAM,OAAO,MAAM,KAAK,SAAS,OAAO;EACxC,IAAI,SAAS,MAAM,OAAO,KAAK,mBAAmB;EAClD,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,KAAK,SAAS,OAAO,MAAM,QAAQ,OAAO;EAC7D,SAAS,OAAO;GACd,IAAI,iBAAiB,0BAA0B,OAAO,KAAK,OAAO,KAAK;GACvE,MAAM;EACR;EACA,IAAI,aAAa,MAAM,MAAM,WAAW,QAAQ;EAChD,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,YAAY,GAAG,CAAC;CACtD;CAEA,MAAc,SAAS,SAA0C;EAC/D,MAAM,gBAAgB,QAAQ,QAAQ,IAAI,gBAAgB;EAC1D,IAAI,kBAAkB,QAAQ,QAAQ,KAAK,aAAa,GACtD;OAAI,OAAO,aAAa,IAAI,KAAK,cAAc,OAAO;EAAG;EAE3D,IAAI,QAAQ,SAAS,MAAM,OAAO;EAElC,MAAM,SAAS,QAAQ,KAAK,UAAU;EACtC,MAAM,UAAU,IAAI,YAAY;EAChC,IAAI,OAAO;EACX,IAAI,YAAY;EAChB,IAAI;GACF,OAAO,MAAM;IACX,MAAM,QAAQ,MAAM,OAAO,KAAK;IAChC,IAAI,MAAM,MAAM,OAAO,OAAO,QAAQ,OAAO;IAC7C,aAAa,MAAM,MAAM;IACzB,IAAI,YAAY,KAAK,cAAc;KACjC,IAAI;MACF,MAAM,OAAO,OAAO;KACtB,QAAQ,CAER;KACA,OAAO;IACT;IACA,QAAQ,QAAQ,OAAO,MAAM,OAAO,EAAE,QAAQ,KAAK,CAAC;GACtD;EACF,UAAU;GACR,OAAO,YAAY;EACrB;CACF;CAEA,AAAQ,qBAA+B;EACrC,KAAK,OAAO,KAAK,oBAAoB,EAAE,QAAQ,iBAAiB,CAAC;EACjE,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,YAAY,iBAAiB,CAAC;CACpE;CAEA,AAAQ,OAAO,OAA2C;EACxD,KAAK,OAAO,KAAK,oBAAoB,EAAE,QAAQ,MAAM,OAAO,CAAC;EAC7D,MAAM,SACJ,MAAM,WAAW,qBAAqB,MAAM,WAAW,sBACnD,YAAY,eACZ,YAAY;EAClB,OAAO,IAAI,SAAS,MAAM,EAAE,OAAO,CAAC;CACtC;AACF"}
|
package/dist/{outbox-repository-options-CgdqU20T.js → outbox-repository-options-B8TnAE1h.js}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as UnitOfWorkAlreadyActiveError } from "./application-
|
|
1
|
+
import { t as UnitOfWorkAlreadyActiveError } from "./application-Dg1jIKPe.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-
|
|
57
|
+
//# sourceMappingURL=outbox-repository-options-B8TnAE1h.js.map
|
package/dist/{outbox-repository-options-CgdqU20T.js.map → outbox-repository-options-B8TnAE1h.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outbox-repository-options-
|
|
1
|
+
{"version":3,"file":"outbox-repository-options-B8TnAE1h.js","names":[],"sources":["../src/infrastructure/unit-of-work-context.ts","../src/infrastructure/outbox-repository-options.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport { panic } from 'better-result'\nimport type { BatchItem } from 'drizzle-orm/batch'\n\nimport { UnitOfWorkAlreadyActiveError, type IEventCollector } from '@/application'\nimport type { DomainEvent } from '@/core'\n\ntype UnitOfWorkContext = { readonly events: DomainEvent[] } & (\n | { readonly database: 'd1'; readonly statements: BatchItem<'sqlite'>[] }\n | { readonly database: 'postgres' }\n)\n\n// One async scope isolates events and D1 statements and rejects nesting across both adapters.\nconst storage = new AsyncLocalStorage<UnitOfWorkContext>()\n\n/** Reject nested transactions before database work starts; preserve independent concurrent execution. */\nexport async function runWithUnitOfWorkContext<T>(\n database: UnitOfWorkContext['database'],\n work: () => Promise<T>,\n): Promise<T> {\n if (storage.getStore() !== undefined) throw new UnitOfWorkAlreadyActiveError()\n const context: UnitOfWorkContext =\n database === 'd1' ? { database, events: [], statements: [] } : { database, events: [] }\n return storage.run(context, work)\n}\n\n/** Inject this shared scope into the unit of work and expose its emitter to application handlers. */\nexport const eventCollector: IEventCollector = {\n emit(event) {\n currentContext().events.push(event)\n },\n collect() {\n return [...currentContext().events]\n },\n}\n\n/** Queue one native D1 statement for the active batch; other contexts cannot accept D1 writes. */\nexport function stageD1Statement(statement: BatchItem<'sqlite'>): void {\n d1Context().statements.push(statement)\n}\n\n/** Read the active D1 batch in staging order for commit. */\nexport function collectD1Statements(): ReadonlyArray<BatchItem<'sqlite'>> {\n return [...d1Context().statements]\n}\n\nfunction d1Context(): Extract<UnitOfWorkContext, { database: 'd1' }> {\n const context = currentContext()\n if (context.database !== 'd1') return panic('D1 statements require a D1 unit of work')\n return context\n}\n\nfunction currentContext(): UnitOfWorkContext {\n return storage.getStore() ?? panic('operation requires an active unit of work')\n}\n","/** Shared lease and delay defaults for both database adapters. */\nexport const OUTBOX_REPOSITORY_DEFAULTS = {\n leaseMs: 60_000,\n retryBaseDelayMs: 1_000,\n retryMaxDelayMs: 60_000,\n}\n\n/** Override lease and delay limits at the composition root. */\nexport type OutboxRepositoryOptions = Readonly<Partial<typeof OUTBOX_REPOSITORY_DEFAULTS>>\n"],"mappings":";;;;;AAcA,MAAM,UAAU,IAAI,kBAAqC;;AAGzD,eAAsB,yBACpB,UACA,MACY;CACZ,IAAI,QAAQ,SAAS,MAAM,QAAW,MAAM,IAAI,6BAA6B;CAC7E,MAAM,UACJ,aAAa,OAAO;EAAE;EAAU,QAAQ,CAAC;EAAG,YAAY,CAAC;CAAE,IAAI;EAAE;EAAU,QAAQ,CAAC;CAAE;CACxF,OAAO,QAAQ,IAAI,SAAS,IAAI;AAClC;;AAGA,MAAa,iBAAkC;CAC7C,KAAK,OAAO;EACV,eAAe,CAAC,CAAC,OAAO,KAAK,KAAK;CACpC;CACA,UAAU;EACR,OAAO,CAAC,GAAG,eAAe,CAAC,CAAC,MAAM;CACpC;AACF;;AAGA,SAAgB,iBAAiB,WAAsC;CACrE,UAAU,CAAC,CAAC,WAAW,KAAK,SAAS;AACvC;;AAGA,SAAgB,sBAA0D;CACxE,OAAO,CAAC,GAAG,UAAU,CAAC,CAAC,UAAU;AACnC;AAEA,SAAS,YAA4D;CACnE,MAAM,UAAU,eAAe;CAC/B,IAAI,QAAQ,aAAa,MAAM,OAAO,MAAM,yCAAyC;CACrF,OAAO;AACT;AAEA,SAAS,iBAAoC;CAC3C,OAAO,QAAQ,SAAS,KAAK,MAAM,2CAA2C;AAChF;;;;;ACtDA,MAAa,6BAA6B;CACxC,SAAS;CACT,kBAAkB;CAClB,iBAAiB;AACnB"}
|
package/dist/postgres.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { O as DatabaseError, nt as AppError, s as exponentialDelayCapMs } from "./core-
|
|
2
|
-
import { o as MessageAlreadyProcessedError } from "./application-
|
|
3
|
-
import { i as runWithUnitOfWorkContext, r as eventCollector, t as OUTBOX_REPOSITORY_DEFAULTS } from "./outbox-repository-options-
|
|
1
|
+
import { O as DatabaseError, nt as AppError, s as exponentialDelayCapMs } from "./core-BT1dSEQI.js";
|
|
2
|
+
import { o as MessageAlreadyProcessedError } from "./application-Dg1jIKPe.js";
|
|
3
|
+
import { i as runWithUnitOfWorkContext, r as eventCollector, t as OUTBOX_REPOSITORY_DEFAULTS } from "./outbox-repository-options-B8TnAE1h.js";
|
|
4
4
|
import { Result } from "better-result";
|
|
5
5
|
import { DrizzleQueryError } from "drizzle-orm/errors";
|
|
6
6
|
import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
|
package/dist/posthog/server.js
CHANGED
package/dist/resend.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { jt as BounceType } from "./index-DUFS0SJ_.js";
|
|
2
2
|
import { B as OutboundEmail, I as EmailAccepted, R as IEmailService } from "./index-CYHXOH08.js";
|
|
3
|
-
import {
|
|
3
|
+
import { n as WebhookVerifier } from "./webhook-verification-D1c7BY4q.js";
|
|
4
4
|
import { Resend } from "resend";
|
|
5
5
|
//#region src/infrastructure/resend/resend-email-service.d.ts
|
|
6
6
|
/** The SDK operations required by the adapter; a test factory can return a plain object. */
|
|
@@ -65,8 +65,8 @@ export declare class ResendWebhook implements WebhookVerifier<EmailEvent> {
|
|
|
65
65
|
private client;
|
|
66
66
|
/** Inject the local SDK verifier when testing. */
|
|
67
67
|
constructor(webhookSecret: string, verifier: () => Promise<ResendWebhookClient>);
|
|
68
|
-
/** Verify the raw body and Svix headers. Invalid requests
|
|
69
|
-
verify(body: string, headers: Headers): Promise<
|
|
68
|
+
/** Verify the raw body and Svix headers. Invalid requests throw typed errors; other failures propagate. */
|
|
69
|
+
verify(body: string, headers: Headers): Promise<EmailEvent | null>;
|
|
70
70
|
}
|
|
71
71
|
//#endregion
|
|
72
72
|
export type { EmailEvent, EmailEventType, ResendEmailClient, ResendWebhookClient };
|
package/dist/resend.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resend.d.ts","names":[],"sources":["../src/infrastructure/resend/resend-email-service.ts","../src/infrastructure/resend/email-event.ts","../src/infrastructure/resend/resend-webhook.ts"],"mappings":";;;;;;KAsEY;WAA+B,QAAQ,KAAK;;;;;;qBAM3C,8BAA8B;mBAatB;mBACA;;SAZZ,OAAO,gBAAgB,sBAAsB;UAO5C;;EAGR,YACmB,oBAAoB,QAAQ,oBAC5B;;EAIb,UAAU,OAAO,gBAAgB,QAAQ;;;;cCzF3C;;KAYM,yBACA;KAgDP;WACM;WACA;WACA;WACA;WACA,MAAM,SAAS;WACf;;;KAIC,cACP;WACU;WACA;aACE,MAAM;aACN;aACA;;MAGZ;WAA4B;WAA+B;MAC3D;WAA4B;WAAgC;MAC5D;WAA4B,cAAc;;;;;
|
|
1
|
+
{"version":3,"file":"resend.d.ts","names":[],"sources":["../src/infrastructure/resend/resend-email-service.ts","../src/infrastructure/resend/email-event.ts","../src/infrastructure/resend/resend-webhook.ts"],"mappings":";;;;;;KAsEY;WAA+B,QAAQ,KAAK;;;;;;qBAM3C,8BAA8B;mBAatB;mBACA;;SAZZ,OAAO,gBAAgB,sBAAsB;UAO5C;;EAGR,YACmB,oBAAoB,QAAQ,oBAC5B;;EAIb,UAAU,OAAO,gBAAgB,QAAQ;;;;cCzF3C;;KAYM,yBACA;KAgDP;WACM;WACA;WACA;WACA;WACA,MAAM,SAAS;WACf;;;KAIC,cACP;WACU;WACA;aACE,MAAM;aACN;aACA;;MAGZ;WAA4B;WAA+B;MAC3D;WAA4B;WAAgC;MAC5D;WAA4B,cAAc;;;;;KC3EnC,sBAAsB,KAAK;;qBAG1B,yBAAyB,gBAAgB;mBAcjC;mBACA;;SAbZ,OAAO,wBAAwB;UAQ9B;;EAGR,YACmB,uBACA,gBAAgB,QAAQ;;EAIrC,OAAO,cAAc,SAAS,UAAU,QAAQ"}
|