better-ship 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/{application-DjsQtpgw.js → application-DYfcAy-Q.js} +2 -2
  2. package/dist/{application-DjsQtpgw.js.map → application-DYfcAy-Q.js.map} +1 -1
  3. package/dist/application.d.ts +2 -2
  4. package/dist/application.js +1 -1
  5. package/dist/better-auth/apple-client-secret.d.ts +1 -1
  6. package/dist/better-auth/apple-client-secret.js +1 -1
  7. package/dist/better-auth/auth-client.js +1 -1
  8. package/dist/better-auth/rate-limit.d.ts +1 -1
  9. package/dist/better-auth/rate-limit.js +1 -1
  10. package/dist/better-auth.js +1 -1
  11. package/dist/cloudflare/auth-secondary-storage.d.ts +1 -1
  12. package/dist/cloudflare/auth-secondary-storage.js +1 -1
  13. package/dist/cloudflare/queue.d.ts +175 -0
  14. package/dist/cloudflare/queue.d.ts.map +1 -0
  15. package/dist/cloudflare/queue.js +419 -0
  16. package/dist/cloudflare/queue.js.map +1 -0
  17. package/dist/cloudflare.d.ts +3 -3
  18. package/dist/cloudflare.js +3 -3
  19. package/dist/{core-Cx5SeyKV.js → core-DC_4pOrI.js} +92 -2
  20. package/dist/core-DC_4pOrI.js.map +1 -0
  21. package/dist/core.d.ts +2 -2
  22. package/dist/core.js +2 -2
  23. package/dist/{index-BStnggQO.d.ts → index-6XMPJu7u.d.ts} +49 -2
  24. package/dist/index-6XMPJu7u.d.ts.map +1 -0
  25. package/dist/{index-DWIRrJMP.d.ts → index-_Cihfq1J.d.ts} +2 -2
  26. package/dist/{index-DWIRrJMP.d.ts.map → index-_Cihfq1J.d.ts.map} +1 -1
  27. package/dist/postgres.d.ts +3 -3
  28. package/dist/postgres.js +3 -3
  29. package/dist/tanstack.d.ts +1 -1
  30. package/dist/tanstack.js +1 -1
  31. package/dist/{unit-of-work-context-DToDpAkv.js → unit-of-work-context-BFCmU92Z.js} +2 -2
  32. package/dist/{unit-of-work-context-DToDpAkv.js.map → unit-of-work-context-BFCmU92Z.js.map} +1 -1
  33. package/dist/{unit-of-work-context-CPz9rdSS.d.ts → unit-of-work-context-BWTJfYPW.d.ts} +3 -3
  34. package/dist/{unit-of-work-context-CPz9rdSS.d.ts.map → unit-of-work-context-BWTJfYPW.d.ts.map} +1 -1
  35. package/package.json +2 -1
  36. package/src/core/backoff.ts +29 -0
  37. package/src/core/classify-failure.ts +60 -0
  38. package/src/core/cloudflare-classification.ts +45 -0
  39. package/src/core/index.ts +14 -0
  40. package/src/infrastructure/cloudflare/queue/index.ts +25 -0
  41. package/src/infrastructure/cloudflare/queue/queue-client.ts +177 -0
  42. package/src/infrastructure/cloudflare/queue/queue-consumer.ts +146 -0
  43. package/src/infrastructure/cloudflare/queue/queue-limits.ts +54 -0
  44. package/src/infrastructure/cloudflare/queue/queue-message.ts +4 -0
  45. package/src/infrastructure/cloudflare/queue/queue.errors.ts +105 -0
  46. package/src/infrastructure/cloudflare/queue/redelivery-policy.ts +64 -0
  47. package/dist/core-Cx5SeyKV.js.map +0 -1
  48. package/dist/index-BStnggQO.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-DC_4pOrI.js","names":["uuidv7","uuidv7"],"sources":["../src/core/app-error.ts","../src/core/authentication.error.ts","../src/core/rate-limit.error.ts","../src/core/stale-session.error.ts","../src/core/not-authorized.error.ts","../src/core/internal.errors.ts","../src/core/request.errors.ts","../src/core/problem-details.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/failure-classification.ts","../src/core/transport-classification.ts","../src/core/cloudflare-classification.ts","../src/core/classify-failure.ts","../src/core/backoff.ts","../src/core/logger.ts"],"sourcesContent":["import type { FailureClassification } from './failure-classification.ts'\n\n/**\n * The base of every expected failure. A subclass declares its tag and its classification,\n * so no boundary has to guess what kind of failure it holds. A boundary tells our errors from\n * raw throws with `instanceof AppError`; a value that fails it was never judged.\n *\n * A `readonly` field with a literal initializer keeps the literal type, so\n * `readonly _tag = 'StoreUnavailable'` is enough for `Result` unions and `matchError`.\n */\nexport abstract class AppError extends Error {\n abstract readonly _tag: string\n abstract readonly classification: FailureClassification\n\n override get name(): string {\n return this._tag\n }\n}\n","import { AppError } from './app-error.ts'\n\n/** 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 { v7 as uuidv7 } from 'uuid'\nimport { z } from 'zod'\n\nimport type { DomainCommand, DomainEvent, DomainQuery, MessageId } from './messages.ts'\n\n/** Payload schemas keyed by message name. A payload never carries `type`, `name`, or `id`. */\nexport type PayloadSchemas = Readonly<Record<string, z.ZodType<object>>>\n\n/** An application's messages: one list of payload schemas per kind. */\nexport type MessageDefinition = {\n readonly commands: PayloadSchemas\n readonly events: PayloadSchemas\n readonly queries: PayloadSchemas\n}\n\ntype AnyMessages = { readonly definition: MessageDefinition }\ntype Def<Messages extends AnyMessages> = Messages['definition']\ntype Payload<Schemas extends PayloadSchemas, Name extends keyof Schemas> = z.output<Schemas[Name]>\n\n/** Every command of an application: `CommandOf<typeof messages>`. */\nexport type CommandOf<Messages extends AnyMessages> = {\n [Name in keyof Def<Messages>['commands'] & string]: DomainCommand<Name> &\n Payload<Def<Messages>['commands'], Name>\n}[keyof Def<Messages>['commands'] & string]\n\n/** Every event of an application: `EventOf<typeof messages>`. */\nexport type EventOf<Messages extends AnyMessages> = {\n [Name in keyof Def<Messages>['events'] & string]: DomainEvent<Name> &\n Payload<Def<Messages>['events'], Name>\n}[keyof Def<Messages>['events'] & string]\n\n/** Every query of an application: `QueryOf<typeof messages>`. */\nexport type QueryOf<Messages extends AnyMessages> = {\n [Name in keyof Def<Messages>['queries'] & string]: DomainQuery<Name> &\n Payload<Def<Messages>['queries'], Name>\n}[keyof Def<Messages>['queries'] & string]\n\n/** Every message of an application: what the registry and the bus are typed with. */\nexport type MessageOf<Messages extends AnyMessages> =\n | CommandOf<Messages>\n | EventOf<Messages>\n | QueryOf<Messages>\n\n/**\n * What `defineMessages` returns. The factories build messages for in-process dispatch without\n * parsing; the data is already typed. The schemas parse untrusted input at a boundary.\n */\nexport type AppMessages<Definition extends MessageDefinition> = {\n readonly definition: Definition\n /** Build a command. `id` defaults to a uuid v7; a webhook passes the provider's key, `stripe:event:evt_123`. */\n createCommand<Name extends keyof Definition['commands'] & string>(\n name: Name,\n payload: Payload<Definition['commands'], Name>,\n id?: MessageId,\n ): DomainCommand<Name> & Payload<Definition['commands'], Name>\n /** Build an event. `id` defaults to a uuid v7, which also orders it in time. */\n createEvent<Name extends keyof Definition['events'] & string>(\n name: Name,\n payload: Payload<Definition['events'], Name>,\n id?: MessageId,\n ): DomainEvent<Name> & Payload<Definition['events'], Name>\n /** Build a query. No id: nothing claims a read. */\n createQuery<Name extends keyof Definition['queries'] & string>(\n name: Name,\n payload: Payload<Definition['queries'], Name>,\n ): DomainQuery<Name> & Payload<Definition['queries'], Name>\n readonly commandSchema: z.ZodType<CommandOf<AppMessages<Definition>>>\n readonly eventSchema: z.ZodType<EventOf<AppMessages<Definition>>>\n readonly querySchema: z.ZodType<QueryOf<AppMessages<Definition>>>\n /** What a queue body may be: a command or an event. Queries never cross a queue. */\n readonly queueSchema: z.ZodType<\n CommandOf<AppMessages<Definition>> | EventOf<AppMessages<Definition>>\n >\n}\n\ntype RoutingField = 'type' | 'name' | 'id'\n\n/** A payload that declares a routing field maps to `never`, so `defineMessages` rejects it. */\ntype WithoutRoutingFields<Schemas extends PayloadSchemas> = {\n readonly [Name in keyof Schemas]: keyof z.output<Schemas[Name]> & RoutingField extends never\n ? Schemas[Name]\n : never\n}\n\n/** The compile-time rule: no payload of any kind declares `type`, `name`, or `id`. */\ntype ValidDefinition<Definition extends MessageDefinition> = {\n readonly commands: WithoutRoutingFields<Definition['commands']>\n readonly events: WithoutRoutingFields<Definition['events']>\n readonly queries: WithoutRoutingFields<Definition['queries']>\n}\n\nconst MessageIdSchema = z.string().min(1)\n\n/** One full message schema: the routing fields joined to the payload. */\nfunction messageSchema(\n type: 'command' | 'event' | 'query',\n name: string,\n payload: z.ZodType<object>,\n) {\n const routing =\n type === 'query'\n ? z.object({ type: z.literal(type), name: z.literal(name) })\n : z.object({ type: z.literal(type), name: z.literal(name), id: MessageIdSchema })\n return routing.and(payload)\n}\n\n/** A union over every message of one kind. Empty when the application has none of that kind. */\nfunction unionOf(type: 'command' | 'event' | 'query', schemas: PayloadSchemas) {\n return z.union(\n Object.entries(schemas).map(([name, payload]) => messageSchema(type, name, payload)),\n )\n}\n\n/**\n * Define an application's messages once. The key is the name; the factories add the routing\n * fields `type`, `name`, and `id`. A payload that declares one of them is a compile error.\n */\nexport function defineMessages<const Definition extends MessageDefinition>(\n definition: Definition & ValidDefinition<Definition>,\n): AppMessages<Definition> {\n const commandSchema = unionOf('command', definition.commands)\n const eventSchema = unionOf('event', definition.events)\n const querySchema = unionOf('query', definition.queries)\n return {\n definition,\n createCommand: (name, payload, id = uuidv7()) => ({ ...payload, type: 'command', name, id }),\n createEvent: (name, payload, id = uuidv7()) => ({ ...payload, type: 'event', name, id }),\n createQuery: (name, payload) => ({ ...payload, type: 'query', name }),\n commandSchema: commandSchema.pipe(z.custom<CommandOf<AppMessages<Definition>>>()),\n eventSchema: eventSchema.pipe(z.custom<EventOf<AppMessages<Definition>>>()),\n querySchema: querySchema.pipe(z.custom<QueryOf<AppMessages<Definition>>>()),\n queueSchema: z\n .union([commandSchema, eventSchema])\n .pipe(z.custom<CommandOf<AppMessages<Definition>> | EventOf<AppMessages<Definition>>>()),\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\nfunction exponentialDelayCapMs(baseDelayMs: number, maxDelayMs: number, attempt: number): number {\n if (!Number.isSafeInteger(attempt) || attempt < 1) {\n return panic('attempt must be a positive integer')\n }\n return Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs)\n}\n","/**\n * Module-scoped logging for every host.\n *\n * A logger emits one plain-data entry per log. The default sink hands it to `console` as an\n * entry object for a log service or as a colored line for a person, selected at startup.\n */\n\n/** A value a log entry may carry. Errors enter only through `Logger.error`. */\nexport type LogValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ReadonlyArray<LogValue>\n | LogFields\n\n/** Named log values. */\nexport type LogFields = { readonly [key: string]: LogValue }\n\n/**\n * The supported log severity levels, in ascending order.\n *\n * A const object, not an enum, so a parsed environment value typed `'INFO'` is a `LogLevel`.\n */\nexport const LogLevel = {\n DEBUG: 'DEBUG',\n INFO: 'INFO',\n WARN: 'WARN',\n ERROR: 'ERROR',\n} as const\nexport type LogLevel = (typeof LogLevel)[keyof typeof LogLevel]\n\n/** An error as plain data, including diagnostics, causes, and aggregate members. */\nexport type SerializedError = {\n readonly name: string\n readonly message: string\n readonly stack?: string\n readonly fields?: LogFields\n readonly cause?: SerializedError\n readonly errors?: ReadonlyArray<SerializedError>\n}\n\n/** One log, as the sink receives it. Plain data, safe to stringify. */\nexport type LogEntry = {\n readonly timestamp: string\n readonly level: LogLevel\n readonly module: string\n readonly message: string\n readonly details: LogFields\n readonly userId?: string\n /** Present on `Logger.error` entries that carried an error. */\n readonly error?: SerializedError\n}\n\n/** The context an error log carries. */\nexport type ErrorLogContext = {\n readonly error?: unknown\n readonly userId?: string\n readonly details?: LogFields\n}\n\n/** What a logger lets through: a level and everything above it, or nothing. */\nexport type LogThreshold = LogLevel | 'OFF'\n\n/** Overrides the application settings for one logger. */\nexport interface LoggerConfig {\n readonly level?: LogThreshold\n}\n\n/** `json` writes the entry object. `pretty` writes one readable line for a person. */\nexport type LogFormat = 'json' | 'pretty'\n\n/**\n * The application settings, set once at the composition root.\n *\n * An omitted field keeps its default. An explicit `undefined` is a compile error, so the root\n * parses an environment value before passing it. The logger reads no environment itself.\n */\nexport interface LoggerSettings extends LoggerConfig {\n readonly format?: LogFormat\n}\n\n// The production server setting, so a root that never configures still logs safely.\nconst DEFAULT_SETTINGS: Required<LoggerSettings> = {\n level: LogLevel.INFO,\n format: 'json',\n}\n\n// The application configures once at startup; loggers can exist before startup completes.\nlet settings = DEFAULT_SETTINGS\n\n/**\n * Set application settings, including for existing loggers. Per-logger overrides take priority.\n * Call at startup, never per request. An omitted field resets to INFO and JSON output.\n */\nexport function configureLogger(config: LoggerSettings): void {\n settings = {\n level: config.level ?? DEFAULT_SETTINGS.level,\n format: config.format ?? DEFAULT_SETTINGS.format,\n }\n}\n\n/** The error data sent to the configured error hook. */\nexport interface ErrorCaptureEntry {\n readonly error: unknown\n readonly distinctId: string | undefined\n readonly context: LogFields\n}\n\n/** A function that forwards one logged error to an error service. */\nexport type LoggerErrorHook = (entry: ErrorCaptureEntry) => void\n\n/** Where every log entry goes. */\nexport type LogSink = (entry: LogEntry) => void\n\nlet errorHook: LoggerErrorHook | null = null\n\n/**\n * Register the function that receives each logged error.\n *\n * Set once at the process entry point. A later call replaces the earlier hook.\n */\nexport function setLoggerErrorHook(fn: LoggerErrorHook): void {\n errorHook = fn\n}\n\n// One console method per level, so a host that filters by method can tell them apart.\nconst CONSOLE_METHOD = {\n [LogLevel.DEBUG]: 'debug',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error',\n} as const satisfies Record<LogLevel, 'debug' | 'info' | 'warn' | 'error'>\n\n// Built from the code point so no raw control character sits in the source.\nconst ESC = String.fromCharCode(27)\nconst ANSI_RESET = `${ESC}[0m`\nconst ANSI_GRAY = `${ESC}[90m`\nconst ANSI_BLUE = `${ESC}[34m`\n\n// Severity reads at a glance: quiet levels stay dim, and an error is the only bold line.\nconst LEVEL_ANSI = {\n DEBUG: `${ESC}[2;36m`,\n INFO: ANSI_BLUE,\n WARN: `${ESC}[33m`,\n ERROR: `${ESC}[1;31m`,\n} satisfies Record<LogLevel, string>\n\nfunction prettyLine(entry: LogEntry): string {\n // Node prints debug and info exactly like log, so the level must be in the text too.\n const level = `[${entry.level}]`\n const module = `[${entry.module}]`\n // A browser console colors by method on its own; a terminal needs ANSI to do the same.\n if ('window' in globalThis) return `${entry.timestamp} ${level} ${module} ${entry.message}`\n const timestamp = `${ANSI_GRAY}${entry.timestamp}${ANSI_RESET}`\n const coloredLevel = `${LEVEL_ANSI[entry.level]}${level}${ANSI_RESET}`\n const coloredModule = `${ANSI_BLUE}${module}${ANSI_RESET}`\n return `${timestamp} ${coloredLevel} ${coloredModule} ${entry.message}`\n}\n\n/**\n * JSON format writes the entry object. Pretty format writes one line, then the details,\n * the error, and the stack as separate console arguments.\n */\nexport const consoleSink: LogSink = (entry) => {\n // Resolved per call, so a console replaced after import still receives the output.\n const write = console[CONSOLE_METHOD[entry.level]]\n if (settings.format === 'json') {\n write(entry)\n return\n }\n const line = prettyLine(entry)\n const fields =\n entry.userId === undefined ? entry.details : { ...entry.details, userId: entry.userId }\n const details = Object.keys(fields).length === 0 ? [] : [fields]\n if (entry.error === undefined) {\n write(line, ...details)\n return\n }\n // A stack inside an object prints as one quoted string; as its own argument it prints as lines.\n const { stack, ...error } = entry.error\n if (stack === undefined) write(line, ...details, error)\n else write(line, ...details, error, `\\n${stack}`)\n}\n\nlet logSink: LogSink = consoleSink\n\n/**\n * Send every log entry somewhere other than `console`.\n *\n * Set once at the process entry point, never per module. A logger is created\n * by name and nothing else, so its destination is a fact about the process.\n */\nexport function setLogSink(fn: LogSink): void {\n logSink = fn\n}\n\nconst LOG_LEVELS = Object.values(LogLevel)\nconst MAX_ERROR_DEPTH = 3\n\n/**\n * Diagnostics worth keeping off an error, named one by one.\n *\n * An allowlist rather than every own property: an error raised by a library we\n * do not control may hang a request or a user payload off itself, and a log is\n * the wrong place to discover that. `_tag` and `classification` are what every `AppError`\n * declares. `remote` and the three flags after it are the ones workerd sets itself.\n */\nconst KEPT_ERROR_FIELDS = [\n '_tag',\n 'classification',\n 'code',\n 'operation',\n 'status',\n 'statusCode',\n 'remote',\n 'retryable',\n 'overloaded',\n 'durableObjectReset',\n] as const\n\ntype ErrorDiagnostics = Error & { readonly [K in (typeof KEPT_ERROR_FIELDS)[number]]?: LogValue }\n\ntype MutableSerializedError = { -readonly [K in keyof SerializedError]: SerializedError[K] }\n\nconst serializeError = (error: Error, depth = 0): SerializedError => {\n if (depth > MAX_ERROR_DEPTH) return { name: 'Error', message: '[error nesting truncated]' }\n\n // Every field is optional, so an `Error` is already one of these.\n const carrier: ErrorDiagnostics = error\n const kept = KEPT_ERROR_FIELDS.filter((key) => carrier[key] !== undefined)\n const serialized: MutableSerializedError = { name: error.name, message: error.message }\n if (error.stack !== undefined) serialized.stack = error.stack\n if (kept.length > 0)\n serialized.fields = Object.fromEntries(kept.map((key) => [key, carrier[key]]))\n if (error.cause instanceof Error) serialized.cause = serializeError(error.cause, depth + 1)\n else if (error.cause !== undefined)\n serialized.cause = { name: 'Error', message: '[non-error cause]' }\n if (error instanceof AggregateError) {\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- AggregateError accepts arbitrary values; instanceof Error validates each member.\n serialized.errors = error.errors.map((failure: unknown) =>\n failure instanceof Error\n ? serializeError(failure, depth + 1)\n : { name: 'NonError', message: '[non-error aggregate member]' },\n )\n }\n return serialized\n}\n\n/** Write module-scoped logs with application defaults and optional overrides. */\nexport class Logger {\n private readonly config: LoggerConfig\n\n /** Create a logger for one module. */\n constructor(\n private readonly module: string,\n overrideConfig?: LoggerConfig,\n ) {\n this.config = { ...overrideConfig }\n }\n\n private log(\n level: LogLevel,\n message: string,\n details: LogFields,\n error?: SerializedError,\n userId?: string,\n ): void {\n const threshold = this.config.level ?? settings.level\n if (threshold === 'OFF') return\n if (LOG_LEVELS.indexOf(level) < LOG_LEVELS.indexOf(threshold)) return\n\n let entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n module: this.module,\n message,\n details,\n }\n if (userId !== undefined) entry = { ...entry, userId }\n logSink(error === undefined ? entry : { ...entry, error })\n }\n\n /** Write a debug log. */\n debug(message: string, details: LogFields = {}): void {\n this.log(LogLevel.DEBUG, message, details)\n }\n\n /** Write an information log. */\n info(message: string, details: LogFields = {}): void {\n this.log(LogLevel.INFO, message, details)\n }\n\n /** Write a warning log. */\n warn(message: string, details: LogFields = {}): void {\n this.log(LogLevel.WARN, message, details)\n }\n\n /**\n * Write an error log and send the error to the configured hook.\n *\n * The details say which call this was, and the error says what went wrong\n * inside it. Both the entry and the error hook receive the supplied user ID.\n */\n error(message: string, context: ErrorLogContext = {}): void {\n const details = context.details ?? {}\n const thrown = context.error\n let error: SerializedError | undefined\n if (thrown instanceof Error) {\n error = serializeError(thrown)\n } else if (thrown !== undefined) {\n // Not an `Error`, so there is no name or stack to keep, only its JSON form.\n let json: string\n try {\n json = JSON.stringify(thrown)\n } catch {\n json = '[non-serializable error]'\n }\n error = { name: 'NonError', message: json }\n }\n this.log(LogLevel.ERROR, message, details, error, context.userId)\n\n if (errorHook !== null && thrown !== undefined) {\n errorHook({ error: thrown, distinctId: context.userId, context: details })\n }\n }\n}\n\n/** Create a logger for one module. */\nexport function createLogger(module: string, config?: LoggerConfig): Logger {\n return new Logger(module, config)\n}\n"],"mappings":";;;;;;;;;;;;;AAUA,IAAsB,WAAtB,cAAuC,MAAM;CAI3C,IAAa,OAAe;EAC1B,OAAO,KAAK;CACd;AACF;;;;;ACdA,IAAa,sBAAb,cAAyC,SAAS;CAChD,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,cAAc;EACZ,MAAM,yBAAyB;CACjC;AACF;;;;;ACPA,IAAa,iBAAb,cAAoC,SAAS;CAKtB;CAJrB,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAC1B,AAAS,SAAS;CAElB,YAAY,AAAS,YAA2B;EAC9C,MAAM,mBAAmB;EADN;CAErB;AACF;;;;;ACRA,IAAa,oBAAb,cAAuC,SAAS;CAC9C,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,cAAc;EACZ,MAAM,4CAA4C;CACpD;AACF;;;;;ACPA,IAAa,qBAAb,cAAwC,SAAS;CAC/C,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,cAAc;EACZ,MAAM,aAAa;CACrB;AACF;;;;;ACPA,IAAa,sBAAb,cAAyC,SAAS;CAChD,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,cAAc;EACZ,MAAM,sBAAsB;CAC9B;AACF;;AAGA,IAAa,0BAAb,cAA6C,SAAS;CACpD,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,cAAc;EACZ,MAAM,mBAAmB;CAC3B;AACF;;;;;ACRA,IAAa,kBAAb,MAAa,wBAAwB,SAAS;CAKjC;CAJX,AAAS,OAAO;CAChB,AAAS,iBAAiB;CAE1B,YAC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MAAM;GAC9B,QAAQ;IACN,OAAO;GACT;GACA,QAAQ;IAAE,MAAM;IAAY,SAAS;GAAK;EAC5C;EACA,KAAK,IAAI,SAAS,OAAO,SAAS,SAAS,OAAO,QAAQ,MAAM;EAEhE,IAAI,cAAc,QAAQ,WAAW,QACnC,UAAU;GAAE,OAAO;GAAQ,YAAY,QAAQ;GAAQ,SAAS;EAAQ,CAAC;CAE7E;AACF;;AAGA,SAAgB,aAAa,QAAgB,QAA+B;CAC1E,OAAO,IAAI,OAAO,QAAQ,MAAM;AAClC"}
package/dist/core.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as sharedErrors, A as QueryOf, B as defineId, C as EntityData, D as MessageDefinition, E as EventOf, F as DomainQuery, G as DatabaseFailure, H as unreachable, I as MessageId, J as ErrorPayloadOf, K as ErrorEntries, L as Id, M as DomainCommand, N as DomainEvent, O as MessageOf, P as DomainMessage, Q as defineErrors, R as IdDefinition, S as Entity, T as CommandOf, U as D1ConstraintKind, V as notImplemented, W as DatabaseError, X as ErrorTagOf, Y as ErrorTable, Z as ResolvedError, _ as createLogger, _t as AuthenticationError, a as LogFormat, at as ValidationIssue, b as isAbortError, bt as RetryOwner, c as LogThreshold, ct as ValidationProblemDetails, d as LoggerConfig, dt as ValidationProblemErrorSchema, et as MalformedRequestError, f as LoggerErrorHook, ft as InternalServerError, g as consoleSink, gt as RateLimitError, h as configureLogger, ht as StaleSessionError, i as LogFields, it as ValidationError, j as defineMessages, k as PayloadSchemas, l as LogValue, lt as ValidationProblemDetailsSchema, m as SerializedError, mt as NotAuthorizedError, n as ErrorLogContext, nt as ResourceNotFoundError, o as LogLevel, ot as ProblemDetails, p as LoggerSettings, pt as ServiceUnavailableError, q as ErrorEntry, r as LogEntry, rt as UpgradeRequiredError, s as LogSink, st as ProblemDetailsSchema, t as ErrorCaptureEntry, tt as RequestTimeoutError, u as Logger, ut as ValidationProblemError, v as setLogSink, vt as AppError, w as AppMessages, x as isTransientTransportError, xt as shouldRetryFailure, y as setLoggerErrorHook, yt as FailureClassification, z as IdOf } from "./index-BStnggQO.js";
2
- export { AppError, type AppMessages, AuthenticationError, type CommandOf, type D1ConstraintKind, DatabaseError, type DatabaseFailure, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, Entity, type EntityData, type ErrorCaptureEntry, type ErrorEntries, type ErrorEntry, type ErrorLogContext, type ErrorPayloadOf, type ErrorTable, type ErrorTagOf, type EventOf, type FailureClassification, type Id, type IdDefinition, type IdOf, InternalServerError, type LogEntry, type LogFields, type LogFormat, LogLevel, type LogSink, type LogThreshold, type LogValue, Logger, type LoggerConfig, type LoggerErrorHook, type LoggerSettings, MalformedRequestError, type MessageDefinition, type MessageId, type MessageOf, NotAuthorizedError, type PayloadSchemas, type ProblemDetails, ProblemDetailsSchema, type QueryOf, RateLimitError, RequestTimeoutError, type ResolvedError, ResourceNotFoundError, type RetryOwner, type SerializedError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, type ValidationIssue, type ValidationProblemDetails, ValidationProblemDetailsSchema, type ValidationProblemError, ValidationProblemErrorSchema, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, isAbortError, isTransientTransportError, notImplemented, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, unreachable };
1
+ import { $ as unreachable, A as isTransientCloudflareRuntimeError, At as FailureClassification, B as PayloadSchemas, C as classifyBoundaryError, Ct as InternalServerError, D as isCloudflareObjectResetError, Dt as RateLimitError, E as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, Et as StaleSessionError, F as AppMessages, G as DomainMessage, H as defineMessages, I as CommandOf, J as Id, K as DomainQuery, L as EventOf, M as isTransientTransportError, Mt as shouldRetryFailure, N as Entity, O as isCloudflareOverloadedError, Ot as AuthenticationError, P as EntityData, Q as notImplemented, R as MessageDefinition, S as BoundaryErrorClassifier, St as ValidationProblemErrorSchema, T as retryAfterSecondsOf, Tt as NotAuthorizedError, U as DomainCommand, V as QueryOf, W as DomainEvent, X as IdOf, Y as IdDefinition, Z as defineId, _ as createLogger, _t as ProblemDetails, a as LogFormat, at as ErrorPayloadOf, b as exponentialEqualJitterMs, bt as ValidationProblemDetailsSchema, c as LogThreshold, ct as ResolvedError, d as LoggerConfig, dt as MalformedRequestError, et as D1ConstraintKind, f as LoggerErrorHook, ft as RequestTimeoutError, g as consoleSink, gt as ValidationIssue, h as configureLogger, ht as ValidationError, i as LogFields, it as ErrorEntry, j as isAbortError, jt as RetryOwner, k as isCloudflareRetryableError, kt as AppError, l as LogValue, lt as defineErrors, m as SerializedError, mt as UpgradeRequiredError, n as ErrorLogContext, nt as DatabaseFailure, o as LogLevel, ot as ErrorTable, p as LoggerSettings, pt as ResourceNotFoundError, q as MessageId, r as LogEntry, rt as ErrorEntries, s as LogSink, st as ErrorTagOf, t as ErrorCaptureEntry, tt as DatabaseError, u as Logger, ut as sharedErrors, v as setLogSink, vt as ProblemDetailsSchema, w as classifyFailure, wt as ServiceUnavailableError, x as spreadJitterMs, xt as ValidationProblemError, y as setLoggerErrorHook, yt as ValidationProblemDetails, z as MessageOf } from "./index-6XMPJu7u.js";
2
+ export { AppError, type AppMessages, AuthenticationError, type BoundaryErrorClassifier, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, type CommandOf, type D1ConstraintKind, DatabaseError, type DatabaseFailure, type DomainCommand, type DomainEvent, type DomainMessage, type DomainQuery, Entity, type EntityData, type ErrorCaptureEntry, type ErrorEntries, type ErrorEntry, type ErrorLogContext, type ErrorPayloadOf, type ErrorTable, type ErrorTagOf, type EventOf, type FailureClassification, type Id, type IdDefinition, type IdOf, InternalServerError, type LogEntry, type LogFields, type LogFormat, LogLevel, type LogSink, type LogThreshold, type LogValue, Logger, type LoggerConfig, type LoggerErrorHook, type LoggerSettings, MalformedRequestError, type MessageDefinition, type MessageId, type MessageOf, NotAuthorizedError, type PayloadSchemas, type ProblemDetails, ProblemDetailsSchema, type QueryOf, RateLimitError, RequestTimeoutError, type ResolvedError, ResourceNotFoundError, type RetryOwner, type SerializedError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, type ValidationIssue, type ValidationProblemDetails, ValidationProblemDetailsSchema, type ValidationProblemError, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, exponentialEqualJitterMs, isAbortError, isCloudflareObjectResetError, isCloudflareOverloadedError, isCloudflareRetryableError, isTransientCloudflareRuntimeError, isTransientTransportError, notImplemented, retryAfterSecondsOf, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, spreadJitterMs, unreachable };
package/dist/core.js CHANGED
@@ -1,3 +1,3 @@
1
- import { A as StaleSessionError, C as RequestTimeoutError, D as InternalServerError, E as ValidationError, M as AuthenticationError, N as AppError, O as ServiceUnavailableError, S as MalformedRequestError, T as UpgradeRequiredError, _ as defineErrors, a as createLogger, b as ValidationProblemDetailsSchema, c as isAbortError, d as Entity, f as defineMessages, g as DatabaseError, h as unreachable, i as consoleSink, j as RateLimitError, k as NotAuthorizedError, l as isTransientTransportError, m as notImplemented, n as Logger, o as setLogSink, p as defineId, r as configureLogger, s as setLoggerErrorHook, t as LogLevel, u as shouldRetryFailure, v as sharedErrors, w as ResourceNotFoundError, x as ValidationProblemErrorSchema, y as ProblemDetailsSchema } from "./core-Cx5SeyKV.js";
1
+ import { A as ValidationProblemDetailsSchema, B as StaleSessionError, C as defineId, D as defineErrors, E as DatabaseError, F as UpgradeRequiredError, H as AuthenticationError, I as ValidationError, L as InternalServerError, M as MalformedRequestError, N as RequestTimeoutError, O as sharedErrors, P as ResourceNotFoundError, R as ServiceUnavailableError, S as defineMessages, T as unreachable, U as AppError, V as RateLimitError, _ as isTransientCloudflareRuntimeError, a as createLogger, b as shouldRetryFailure, c as exponentialEqualJitterMs, d as classifyFailure, f as retryAfterSecondsOf, g as isCloudflareRetryableError, h as isCloudflareOverloadedError, i as consoleSink, j as ValidationProblemErrorSchema, k as ProblemDetailsSchema, l as spreadJitterMs, m as isCloudflareObjectResetError, n as Logger, o as setLogSink, p as CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, r as configureLogger, s as setLoggerErrorHook, t as LogLevel, u as classifyBoundaryError, v as isAbortError, w as notImplemented, x as Entity, y as isTransientTransportError, z as NotAuthorizedError } from "./core-DC_4pOrI.js";
2
2
 
3
- export { AppError, AuthenticationError, DatabaseError, Entity, InternalServerError, LogLevel, Logger, MalformedRequestError, NotAuthorizedError, ProblemDetailsSchema, RateLimitError, RequestTimeoutError, ResourceNotFoundError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, ValidationProblemDetailsSchema, ValidationProblemErrorSchema, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, isAbortError, isTransientTransportError, notImplemented, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, unreachable };
3
+ export { AppError, AuthenticationError, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS, DatabaseError, Entity, InternalServerError, LogLevel, Logger, MalformedRequestError, NotAuthorizedError, ProblemDetailsSchema, RateLimitError, RequestTimeoutError, ResourceNotFoundError, ServiceUnavailableError, StaleSessionError, UpgradeRequiredError, ValidationError, ValidationProblemDetailsSchema, ValidationProblemErrorSchema, classifyBoundaryError, classifyFailure, configureLogger, consoleSink, createLogger, defineErrors, defineId, defineMessages, exponentialEqualJitterMs, isAbortError, isCloudflareObjectResetError, isCloudflareOverloadedError, isCloudflareRetryableError, isTransientCloudflareRuntimeError, isTransientTransportError, notImplemented, retryAfterSecondsOf, setLogSink, setLoggerErrorHook, sharedErrors, shouldRetryFailure, spreadJitterMs, unreachable };
@@ -455,6 +455,53 @@ declare function isAbortError(cause: unknown): boolean;
455
455
  /** Match known transient transport messages while excluding explicit cancellation. */
456
456
  declare function isTransientTransportError(cause: unknown): boolean;
457
457
  //#endregion
458
+ //#region src/core/cloudflare-classification.d.ts
459
+ /** Stable Cloudflare messages that mean the runtime failed, not our code, and a repeat may pass. */
460
+ declare const CLOUDFLARE_TRANSIENT_ERROR_PATTERNS: {
461
+ readonly networkConnectionLost: RegExp;
462
+ readonly objectReset: RegExp;
463
+ readonly codeUpdateReset: RegExp;
464
+ readonly objectMoved: RegExp;
465
+ readonly internalWorkflows: RegExp;
466
+ };
467
+ /** workerd stamps `retryable` on a failure it judged safe to repeat. */
468
+ declare function isCloudflareRetryableError(cause: unknown): boolean;
469
+ /** workerd stamps `overloaded` when the target could not take the call. */
470
+ declare function isCloudflareOverloadedError(cause: unknown): boolean;
471
+ /** workerd stamps `durableObjectReset` when the object restarted during the call. */
472
+ declare function isCloudflareObjectResetError(cause: unknown): boolean;
473
+ /** Match transient Cloudflare runtime evidence without the general transport patterns. */
474
+ declare function isTransientCloudflareRuntimeError(cause: unknown): boolean;
475
+ //#endregion
476
+ //#region src/core/classify-failure.d.ts
477
+ /** A boundary's own rule for its raw errors. `undefined` means the boundary has no opinion. */
478
+ type BoundaryErrorClassifier = (cause: unknown) => FailureClassification | undefined;
479
+ /**
480
+ * Classify one raw external error: the boundary's own rule first, then Cloudflare's signals,
481
+ * then the transport patterns. Cancellation is terminal even when Cloudflare marks it retryable.
482
+ */
483
+ declare function classifyBoundaryError(args: {
484
+ readonly cause: unknown;
485
+ readonly classifyBoundary: BoundaryErrorClassifier;
486
+ readonly includeCloudflare: boolean;
487
+ }): FailureClassification;
488
+ /**
489
+ * Judge a final failure for its durable retry owner. An `AppError` carries its own answer.
490
+ * A raw throw nobody judged is unknown, so an immediate owner stops and a durable one may repeat.
491
+ */
492
+ declare function classifyFailure(cause: unknown): FailureClassification;
493
+ /** Read a positive server-advertised retry delay in seconds, such as `RateLimitError.retryAfter`. */
494
+ declare function retryAfterSecondsOf(cause: unknown): number | null;
495
+ //#endregion
496
+ //#region src/core/backoff.d.ts
497
+ /** Uniform jitter within one fixed window. */
498
+ declare function spreadJitterMs(spreadMs: number): number;
499
+ /**
500
+ * Half the capped exponential delay, plus jitter over the other half. Decorrelates concurrent
501
+ * repeats like full jitter, but keeps a floor: use it when few attempts remain before work is dropped.
502
+ */
503
+ declare function exponentialEqualJitterMs(baseDelayMs: number, maxDelayMs: number, attempt: number): number;
504
+ //#endregion
458
505
  //#region src/core/logger.d.ts
459
506
  /**
460
507
  * Module-scoped logging for every host.
@@ -580,5 +627,5 @@ declare class Logger {
580
627
  /** Create a logger for one module. */
581
628
  declare function createLogger(module: string, config?: LoggerConfig): Logger;
582
629
  //#endregion
583
- export { sharedErrors as $, QueryOf as A, defineId as B, EntityData as C, MessageDefinition as D, EventOf as E, DomainQuery as F, DatabaseFailure as G, unreachable as H, MessageId as I, ErrorPayloadOf as J, ErrorEntries as K, Id as L, DomainCommand as M, DomainEvent as N, MessageOf as O, DomainMessage as P, defineErrors as Q, IdDefinition as R, Entity as S, CommandOf as T, D1ConstraintKind as U, notImplemented as V, DatabaseError as W, ErrorTagOf as X, ErrorTable as Y, ResolvedError as Z, createLogger as _, AuthenticationError as _t, LogFormat as a, ValidationIssue as at, isAbortError as b, RetryOwner as bt, LogThreshold as c, ValidationProblemDetails as ct, LoggerConfig as d, ValidationProblemErrorSchema as dt, MalformedRequestError as et, LoggerErrorHook as f, InternalServerError as ft, consoleSink as g, RateLimitError as gt, configureLogger as h, StaleSessionError as ht, LogFields as i, ValidationError as it, defineMessages as j, PayloadSchemas as k, LogValue as l, ValidationProblemDetailsSchema as lt, SerializedError as m, NotAuthorizedError as mt, ErrorLogContext as n, ResourceNotFoundError as nt, LogLevel as o, ProblemDetails as ot, LoggerSettings as p, ServiceUnavailableError as pt, ErrorEntry as q, LogEntry as r, UpgradeRequiredError as rt, LogSink as s, ProblemDetailsSchema as st, ErrorCaptureEntry as t, RequestTimeoutError as tt, Logger as u, ValidationProblemError as ut, setLogSink as v, AppError as vt, AppMessages as w, isTransientTransportError as x, shouldRetryFailure as xt, setLoggerErrorHook as y, FailureClassification as yt, IdOf as z };
584
- //# sourceMappingURL=index-BStnggQO.d.ts.map
630
+ export { unreachable as $, isTransientCloudflareRuntimeError as A, FailureClassification as At, PayloadSchemas as B, classifyBoundaryError as C, InternalServerError as Ct, isCloudflareObjectResetError as D, RateLimitError as Dt, CLOUDFLARE_TRANSIENT_ERROR_PATTERNS as E, StaleSessionError as Et, AppMessages as F, DomainMessage as G, defineMessages as H, CommandOf as I, Id as J, DomainQuery as K, EventOf as L, isTransientTransportError as M, shouldRetryFailure as Mt, Entity as N, isCloudflareOverloadedError as O, AuthenticationError as Ot, EntityData as P, notImplemented as Q, MessageDefinition as R, BoundaryErrorClassifier as S, ValidationProblemErrorSchema as St, retryAfterSecondsOf as T, NotAuthorizedError as Tt, DomainCommand as U, QueryOf as V, DomainEvent as W, IdOf as X, IdDefinition as Y, defineId as Z, createLogger as _, ProblemDetails as _t, LogFormat as a, ErrorPayloadOf as at, exponentialEqualJitterMs as b, ValidationProblemDetailsSchema as bt, LogThreshold as c, ResolvedError as ct, LoggerConfig as d, MalformedRequestError as dt, D1ConstraintKind as et, LoggerErrorHook as f, RequestTimeoutError as ft, consoleSink as g, ValidationIssue as gt, configureLogger as h, ValidationError as ht, LogFields as i, ErrorEntry as it, isAbortError as j, RetryOwner as jt, isCloudflareRetryableError as k, AppError as kt, LogValue as l, defineErrors as lt, SerializedError as m, UpgradeRequiredError as mt, ErrorLogContext as n, DatabaseFailure as nt, LogLevel as o, ErrorTable as ot, LoggerSettings as p, ResourceNotFoundError as pt, MessageId as q, LogEntry as r, ErrorEntries as rt, LogSink as s, ErrorTagOf as st, ErrorCaptureEntry as t, DatabaseError as tt, Logger as u, sharedErrors as ut, setLogSink as v, ProblemDetailsSchema as vt, classifyFailure as w, ServiceUnavailableError as wt, spreadJitterMs as x, ValidationProblemError as xt, setLoggerErrorHook as y, ValidationProblemDetails as yt, MessageOf as z };
631
+ //# sourceMappingURL=index-6XMPJu7u.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-6XMPJu7u.d.ts","names":[],"sources":["../src/core/failure-classification.ts","../src/core/app-error.ts","../src/core/authentication.error.ts","../src/core/rate-limit.error.ts","../src/core/stale-session.error.ts","../src/core/not-authorized.error.ts","../src/core/internal.errors.ts","../src/core/problem-details.ts","../src/core/request.errors.ts","../src/core/error-table.ts","../src/core/database.error.ts","../src/core/defects.ts","../src/core/identity.ts","../src/core/messages.ts","../src/core/define-messages.ts","../src/core/entity.ts","../src/core/transport-classification.ts","../src/core/cloudflare-classification.ts","../src/core/classify-failure.ts","../src/core/backoff.ts","../src/core/logger.ts"],"mappings":";;;;;;;;KAMY;;;;;;;KAQA;;iBAGI,mBAAmB;WACxB,gBAAgB;WAChB;WACA,OAAO;;;;;;;;;;;;uBCVI,iBAAiB;oBACnB;oBACA,gBAAgB;MAErB;;;;;cCXF,4BAA4B;WAC9B;WACA;EAET;;;;;cCJW,uBAAuB;WAKb;WAJZ;WACA;WACA;EAET,YAAqB;;;;;cCLV,0BAA0B;WAC5B;WACA;EAET;;;;;cCJW,2BAA2B;WAC7B;WACA;EAET;;;;;cCJW,4BAA4B;WAC9B;WACA;EAET;;;cAMW,gCAAgC;WAClC;WACA;EAET;;;;;;;;;cCVW,sBAAoB,EAAA;;;;;GAqB/B,EAAA,KAAA;;KAGU,iBAAiB,EAAE,aAAa;;cAG/B,8BAA4B,EAAA;;;GAWvC,EAAA,KAAA;;KAGU,yBAAyB,EAAE,aAAa;;cAGvC,gCAA8B,EAAA;;;;;;;;;GAEzC,EAAA,KAAA;;KAGU,2BAA2B,EAAE,aAAa;;;;KClD1C;WACD;WACA,eAAe;;;cAIb,wBAAwB;WAKxB,iBAAiB;WAJnB;WACA;EAET,YACW,iBAAiB,0BAC1B;;SAMK,QAAQ,OAAO,EAAE,UAAU,mBAAmB;;SAK9C,WAAW,iBAAiB,mBAAmB,mBAAmB;;;cAS9D,8BAA8B;WAChC;WACA;EAET,YAAY;IAAQ;;;;cAMT,8BAA8B;WAChC;WACA;EAET;;;cAMW,6BAA6B;WAC/B;WACA;EAET;;;cAMW,4BAA4B;WAC9B;WACA;EAET;;;;KCtDG,eAAe,EAAE;;;;;KAMV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AQ;;UAQvB;WACN;WACA;WACA,SAAS;;;KAIR,mBAAmB,OAAO;;KAG1B,WAAW,OAAO;;;;;;iBASd,mBAAmB,IAAI;;;;;cA0C1B,aAAa;;;;;;;iBA6BV,WAAW,IAAI;;cAyDlB;mBAKQ;mBAJF;;EAGjB,YACmB,gBACjB,iBAAiB;UAKX;;EAuBR,MAAM,iBAAiB,UAAS;;EAKhC,KAAK,iBAAiB,UAAS;;EAK/B,KAAK,iBAAiB,UAAS;;;;;;;EAU/B,MAAM,iBAAiB,UAAS;;;iBAyBlB,aAAa,gBAAgB,SAAS,eAAe"}
@@ -1,4 +1,4 @@
1
- import { F as DomainQuery, I as MessageId, M as DomainCommand, N as DomainEvent, P as DomainMessage, vt as AppError } from "./index-BStnggQO.js";
1
+ import { G as DomainMessage, K as DomainQuery, U as DomainCommand, W as DomainEvent, kt as AppError, q as MessageId } from "./index-6XMPJu7u.js";
2
2
  //#region src/application/handlers.d.ts
3
3
  /**
4
4
  * Handles one command with the dependency container and returns the caller's value.
@@ -168,4 +168,4 @@ declare class UnitOfWorkAlreadyActiveError extends AppError {
168
168
  }
169
169
  //#endregion
170
170
  export { RegistryMessage as _, UnitOfWorkDeps as a, EventHandler as b, IOutboxRelay as c, CommandRegistry as d, EventRegistry as f, QueryRegistry as g, MessageResult as h, UnitOfWork as i, IMessageBus as l, MessageRegistry as m, MessageAlreadyProcessedError as n, IEventCollector as o, Handlers as p, IUnitOfWork as r, ITransaction as s, UnitOfWorkAlreadyActiveError as t, MessageBus as u, IMessageStore as v, QueryHandler as x, CommandHandler as y };
171
- //# sourceMappingURL=index-DWIRrJMP.d.ts.map
171
+ //# sourceMappingURL=index-_Cihfq1J.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index-DWIRrJMP.d.ts","names":[],"sources":["../src/application/handlers.ts","../src/application/message-store.ts","../src/application/registry.ts","../src/application/message-bus.ts","../src/application/outbox-relay.ts","../src/application/transaction.ts","../src/application/event-collector.ts","../src/application/unit-of-work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AkB,mBAChB,iBAAiB,gBACjB,UAAU,uBAAuB,oBACjC,iBAAiB,cACf,UAAU,sBAAsB;;;;UCvDrB,YAAY,kBAAkB;EAC7C,OAAO,iBAAiB,gBAAgB,gBAAgB,YACtD,SAAS,WACR,QAAQ,cAAc,UAAU;;;;;;cAOxB,WAAW,MAAM,kBAAkB,SAAS,kBAAkB,YAAY;mBAElE;mBACA;EAFnB,YACmB,MAAM,MACN,UAAU;;EAIvB,OAAO,iBAAiB,gBAAgB,gBAAgB,YAC5D,SAAS,WACR,QAAQ,cAAc,UAAU;UAM3B;UASA;UASA;;;;;;UAWM;;;;;;;;;UClEC;EACf;;;;;;;;;UCDe,aAAa;EAC5B,YAAY,GAAG,OAAO,IAAI,OAAO,QAAQ,KAAK,QAAQ;;;;;UCHvC;EACf,KAAK,OAAO;EACZ,WAAW,cAAc;;;;;;;;;UCQV,YAAY;EAC3B,IAAI,GAAG,WAAW,WAAW,OAAO,OAAO,UAAU,QAAQ,KAAK,QAAQ;;KAGhE,eAAe,IAAI;WACpB,aAAa,aAAa;;WAE1B,eAAe,IAAI,OAAO;;WAE1B,qBAAqB,IAAI,OAAO;WAChC,gBAAgB;WAChB,OAAO;;;cAIL,WAAW,IAAI,kBAAkB,YAAY;mBAC3B;EAA7B,YAA6B,MAAM,eAAe,IAAI;EAEhD,IAAI,GAAG,WAAW,WAAW,OAAO,OAAO,UAAU,QAAQ,KAAK,QAAQ;;;;;cC5BrE,qCAAqC;WAKrC,WAAW;WAJb;WACA;EAET,YACW,WAAW,WACpB;aAAqB;;;SAMhB,KAAK,gBAAgB,WAAW,YAAY;;;;;cCZxC,qCAAqC;WACvC;WACA;EAET"}
1
+ {"version":3,"file":"index-_Cihfq1J.d.ts","names":[],"sources":["../src/application/handlers.ts","../src/application/message-store.ts","../src/application/registry.ts","../src/application/message-bus.ts","../src/application/outbox-relay.ts","../src/application/transaction.ts","../src/application/event-collector.ts","../src/application/unit-of-work.ts","../src/application/message-already-processed.error.ts","../src/application/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U,uBAAuB,oBACjC,iBAAiB,cACf,UAAU,sBAAsB;;;;UCvDrB,YAAY,kBAAkB;EAC7C,OAAO,iBAAiB,gBAAgB,gBAAgB,YACtD,SAAS,WACR,QAAQ,cAAc,UAAU;;;;;;cAOxB,WAAW,MAAM,kBAAkB,SAAS,kBAAkB,YAAY;mBAElE;mBACA;EAFnB,YACmB,MAAM,MACN,UAAU;;EAIvB,OAAO,iBAAiB,gBAAgB,gBAAgB,YAC5D,SAAS,WACR,QAAQ,cAAc,UAAU;UAM3B;UASA;UASA;;;;;;UAWM;;;;;;;;;UClEC;EACf;;;;;;;;;UCDe,aAAa;EAC5B,YAAY,GAAG,OAAO,IAAI,OAAO,QAAQ,KAAK,QAAQ;;;;;UCHvC;EACf,KAAK,OAAO;EACZ,WAAW,cAAc;;;;;;;;;UCQV,YAAY;EAC3B,IAAI,GAAG,WAAW,WAAW,OAAO,OAAO,UAAU,QAAQ,KAAK,QAAQ;;KAGhE,eAAe,IAAI;WACpB,aAAa,aAAa;;WAE1B,eAAe,IAAI,OAAO;;WAE1B,qBAAqB,IAAI,OAAO;WAChC,gBAAgB;WAChB,OAAO;;;cAIL,WAAW,IAAI,kBAAkB,YAAY;mBAC3B;EAA7B,YAA6B,MAAM,eAAe,IAAI;EAEhD,IAAI,GAAG,WAAW,WAAW,OAAO,OAAO,UAAU,QAAQ,KAAK,QAAQ;;;;;cC5BrE,qCAAqC;WAKrC,WAAW;WAJb;WACA;EAET,YACW,WAAW,WACpB;aAAqB;;;SAMhB,KAAK,gBAAgB,WAAW,YAAY;;;;;cCZxC,qCAAqC;WACvC;WACA;EAET"}
@@ -1,6 +1,6 @@
1
- import { G as DatabaseFailure, I as MessageId, N as DomainEvent, W as DatabaseError } from "./index-BStnggQO.js";
2
- import { s as ITransaction, v as IMessageStore } from "./index-DWIRrJMP.js";
3
- import { n as DrizzleSchema, t as eventCollector } from "./unit-of-work-context-CPz9rdSS.js";
1
+ import { W as DomainEvent, nt as DatabaseFailure, q as MessageId, tt as DatabaseError } from "./index-6XMPJu7u.js";
2
+ import { s as ITransaction, v as IMessageStore } from "./index-_Cihfq1J.js";
3
+ import { n as DrizzleSchema, t as eventCollector } from "./unit-of-work-context-BWTJfYPW.js";
4
4
  import { ExtractTablesWithRelations } from "drizzle-orm";
5
5
  import { PostgresJsDatabase, PostgresJsTransaction, drizzle } from "drizzle-orm/postgres-js";
6
6
  //#region src/infrastructure/postgres/postgres-database-types.d.ts
package/dist/postgres.js CHANGED
@@ -1,6 +1,6 @@
1
- import { N as AppError, g as DatabaseError } from "./core-Cx5SeyKV.js";
2
- import { i as MessageAlreadyProcessedError } from "./application-DjsQtpgw.js";
3
- import { n as eventCollector, r as runWithUnitOfWorkContext } from "./unit-of-work-context-DToDpAkv.js";
1
+ import { E as DatabaseError, U as AppError } from "./core-DC_4pOrI.js";
2
+ import { i as MessageAlreadyProcessedError } from "./application-DYfcAy-Q.js";
3
+ import { n as eventCollector, r as runWithUnitOfWorkContext } from "./unit-of-work-context-BFCmU92Z.js";
4
4
  import { DrizzleQueryError } from "drizzle-orm/errors";
5
5
  import { isNull } from "drizzle-orm";
6
6
  import { index, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
@@ -1,4 +1,4 @@
1
- import { Y as ErrorTable } from "./index-BStnggQO.js";
1
+ import { ot as ErrorTable } from "./index-6XMPJu7u.js";
2
2
  import { Register, RequestServerOptions } from "@tanstack/react-start";
3
3
  import { AnyRedirect } from "@tanstack/react-router";
4
4
  import { BetterAuthCookies } from "better-auth";
package/dist/tanstack.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as StaleSessionError, E as ValidationError, M as AuthenticationError, N as AppError, a as createLogger } from "./core-Cx5SeyKV.js";
1
+ import { B as StaleSessionError, H as AuthenticationError, I as ValidationError, U as AppError, a as createLogger } from "./core-DC_4pOrI.js";
2
2
  import { z } from "zod";
3
3
  import { createMiddleware } from "@tanstack/react-start";
4
4
  import { deleteCookie, getRequestHeaders } from "@tanstack/react-start/server";
@@ -1,4 +1,4 @@
1
- import { t as UnitOfWorkAlreadyActiveError } from "./application-DjsQtpgw.js";
1
+ import { t as UnitOfWorkAlreadyActiveError } from "./application-DYfcAy-Q.js";
2
2
  import { panic } from "better-result";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
 
@@ -45,4 +45,4 @@ function currentContext() {
45
45
 
46
46
  //#endregion
47
47
  export { stageD1Statement as i, eventCollector as n, runWithUnitOfWorkContext as r, collectD1Statements as t };
48
- //# sourceMappingURL=unit-of-work-context-DToDpAkv.js.map
48
+ //# sourceMappingURL=unit-of-work-context-BFCmU92Z.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"unit-of-work-context-DToDpAkv.js","names":[],"sources":["../src/infrastructure/unit-of-work-context.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"],"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"}
1
+ {"version":3,"file":"unit-of-work-context-BFCmU92Z.js","names":[],"sources":["../src/infrastructure/unit-of-work-context.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"],"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"}
@@ -1,5 +1,5 @@
1
- import "./index-BStnggQO.js";
2
- import { o as IEventCollector } from "./index-DWIRrJMP.js";
1
+ import "./index-6XMPJu7u.js";
2
+ import { o as IEventCollector } from "./index-_Cihfq1J.js";
3
3
  import { BatchItem } from "drizzle-orm/batch";
4
4
  //#region src/infrastructure/drizzle-schema.d.ts
5
5
  /**
@@ -13,4 +13,4 @@ type DrizzleSchema = Record<string, unknown>;
13
13
  declare const eventCollector: IEventCollector;
14
14
  //#endregion
15
15
  export { DrizzleSchema as n, eventCollector as t };
16
- //# sourceMappingURL=unit-of-work-context-CPz9rdSS.d.ts.map
16
+ //# sourceMappingURL=unit-of-work-context-BWTJfYPW.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"unit-of-work-context-CPz9rdSS.d.ts","names":[],"sources":["../src/infrastructure/drizzle-schema.ts","../src/infrastructure/unit-of-work-context.ts"],"mappings":";;;;;;;;KAKY,gBAAgB;;;;cCuBf,gBAAgB"}
1
+ {"version":3,"file":"unit-of-work-context-BWTJfYPW.d.ts","names":[],"sources":["../src/infrastructure/drizzle-schema.ts","../src/infrastructure/unit-of-work-context.ts"],"mappings":";;;;;;;;KAKY,gBAAgB;;;;cCuBf,gBAAgB"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://www.schemastore.org/package.json",
3
3
  "name": "better-ship",
4
- "version": "0.7.0",
4
+ "version": "0.8.0",
5
5
  "description": "Foundation for applications on Cloudflare Workers: logger, errors, message bus, infrastructure adapters, and UI primitives",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -24,6 +24,7 @@
24
24
  "./better-auth/stripe": "./dist/better-auth/stripe.js",
25
25
  "./cloudflare": "./dist/cloudflare.js",
26
26
  "./cloudflare/auth-secondary-storage": "./dist/cloudflare/auth-secondary-storage.js",
27
+ "./cloudflare/queue": "./dist/cloudflare/queue.js",
27
28
  "./core": "./dist/core.js",
28
29
  "./postgres": "./dist/postgres.js",
29
30
  "./tanstack": "./dist/tanstack.js",
@@ -0,0 +1,29 @@
1
+ import { panic } from 'better-result'
2
+
3
+ /** Uniform jitter within one fixed window. */
4
+ export function spreadJitterMs(spreadMs: number): number {
5
+ if (!Number.isFinite(spreadMs) || spreadMs < 0) {
6
+ return panic('spreadMs must be a non-negative number')
7
+ }
8
+ return Math.floor(Math.random() * spreadMs)
9
+ }
10
+
11
+ /**
12
+ * Half the capped exponential delay, plus jitter over the other half. Decorrelates concurrent
13
+ * repeats like full jitter, but keeps a floor: use it when few attempts remain before work is dropped.
14
+ */
15
+ export function exponentialEqualJitterMs(
16
+ baseDelayMs: number,
17
+ maxDelayMs: number,
18
+ attempt: number,
19
+ ): number {
20
+ const halfCapMs = exponentialDelayCapMs(baseDelayMs, maxDelayMs, attempt) / 2
21
+ return Math.floor(halfCapMs) + spreadJitterMs(halfCapMs)
22
+ }
23
+
24
+ function exponentialDelayCapMs(baseDelayMs: number, maxDelayMs: number, attempt: number): number {
25
+ if (!Number.isSafeInteger(attempt) || attempt < 1) {
26
+ return panic('attempt must be a positive integer')
27
+ }
28
+ return Math.min(baseDelayMs * 2 ** (attempt - 1), maxDelayMs)
29
+ }
@@ -0,0 +1,60 @@
1
+ import { z } from 'zod'
2
+
3
+ import { AppError } from './app-error.ts'
4
+ import {
5
+ isCloudflareOverloadedError,
6
+ isCloudflareRetryableError,
7
+ isTransientCloudflareRuntimeError,
8
+ } from './cloudflare-classification.ts'
9
+ import type { FailureClassification } from './failure-classification.ts'
10
+ import { isAbortError, isTransientTransportError } from './transport-classification.ts'
11
+
12
+ /** A boundary's own rule for its raw errors. `undefined` means the boundary has no opinion. */
13
+ export type BoundaryErrorClassifier = (cause: unknown) => FailureClassification | undefined
14
+
15
+ /**
16
+ * Classify one raw external error: the boundary's own rule first, then Cloudflare's signals,
17
+ * then the transport patterns. Cancellation is terminal even when Cloudflare marks it retryable.
18
+ */
19
+ export function classifyBoundaryError(args: {
20
+ readonly cause: unknown
21
+ readonly classifyBoundary: BoundaryErrorClassifier
22
+ readonly includeCloudflare: boolean
23
+ }): FailureClassification {
24
+ const boundary = args.classifyBoundary(args.cause)
25
+ if (boundary !== undefined) return boundary
26
+
27
+ if (isAbortError(args.cause)) return 'terminal'
28
+
29
+ if (
30
+ args.includeCloudflare &&
31
+ (isCloudflareOverloadedError(args.cause) ||
32
+ isCloudflareRetryableError(args.cause) ||
33
+ isTransientCloudflareRuntimeError(args.cause))
34
+ ) {
35
+ return 'transient'
36
+ }
37
+
38
+ if (isTransientTransportError(args.cause)) return 'transient'
39
+
40
+ return 'unknown'
41
+ }
42
+
43
+ /**
44
+ * Judge a final failure for its durable retry owner. An `AppError` carries its own answer.
45
+ * A raw throw nobody judged is unknown, so an immediate owner stops and a durable one may repeat.
46
+ */
47
+ export function classifyFailure(cause: unknown): FailureClassification {
48
+ if (cause instanceof AppError) return cause.classification
49
+ if (isAbortError(cause)) return 'terminal'
50
+ if (isTransientCloudflareRuntimeError(cause)) return 'transient'
51
+ return 'unknown'
52
+ }
53
+
54
+ const RetryAfterSchema = z.object({ retryAfter: z.number().positive() })
55
+
56
+ /** Read a positive server-advertised retry delay in seconds, such as `RateLimitError.retryAfter`. */
57
+ export function retryAfterSecondsOf(cause: unknown): number | null {
58
+ const result = RetryAfterSchema.safeParse(cause)
59
+ return result.success ? result.data.retryAfter : null
60
+ }
@@ -0,0 +1,45 @@
1
+ import { z } from 'zod'
2
+
3
+ /** Stable Cloudflare messages that mean the runtime failed, not our code, and a repeat may pass. */
4
+ export const CLOUDFLARE_TRANSIENT_ERROR_PATTERNS = {
5
+ networkConnectionLost: /network connection lost/,
6
+ objectReset: /caused object to be reset/,
7
+ codeUpdateReset: /reset because its code was updated/,
8
+ objectMoved: /object has moved to a different machine/,
9
+ internalWorkflows: /internal workflows error/,
10
+ } as const
11
+
12
+ const TRANSIENT_PLATFORM_PATTERNS = [
13
+ CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.objectReset,
14
+ CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.codeUpdateReset,
15
+ CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.objectMoved,
16
+ CLOUDFLARE_TRANSIENT_ERROR_PATTERNS.internalWorkflows,
17
+ ]
18
+
19
+ // workerd stamps these flags as own properties on the error it throws across a binding.
20
+ const RetryableFlagSchema = z.object({ retryable: z.literal(true) })
21
+ const OverloadedFlagSchema = z.object({ overloaded: z.literal(true) })
22
+ const ObjectResetFlagSchema = z.object({ durableObjectReset: z.literal(true) })
23
+
24
+ /** workerd stamps `retryable` on a failure it judged safe to repeat. */
25
+ export function isCloudflareRetryableError(cause: unknown): boolean {
26
+ return RetryableFlagSchema.validate(cause)
27
+ }
28
+
29
+ /** workerd stamps `overloaded` when the target could not take the call. */
30
+ export function isCloudflareOverloadedError(cause: unknown): boolean {
31
+ return OverloadedFlagSchema.validate(cause)
32
+ }
33
+
34
+ /** workerd stamps `durableObjectReset` when the object restarted during the call. */
35
+ export function isCloudflareObjectResetError(cause: unknown): boolean {
36
+ return ObjectResetFlagSchema.validate(cause)
37
+ }
38
+
39
+ /** Match transient Cloudflare runtime evidence without the general transport patterns. */
40
+ export function isTransientCloudflareRuntimeError(cause: unknown): boolean {
41
+ if (isCloudflareObjectResetError(cause)) return true
42
+ if (!(cause instanceof Error)) return false
43
+ const message = cause.message.toLowerCase()
44
+ return TRANSIENT_PLATFORM_PATTERNS.some((pattern) => pattern.test(message))
45
+ }
package/src/core/index.ts CHANGED
@@ -57,6 +57,20 @@ export {
57
57
  type RetryOwner,
58
58
  } from './failure-classification.ts'
59
59
  export { isAbortError, isTransientTransportError } from './transport-classification.ts'
60
+ export {
61
+ CLOUDFLARE_TRANSIENT_ERROR_PATTERNS,
62
+ isCloudflareObjectResetError,
63
+ isCloudflareOverloadedError,
64
+ isCloudflareRetryableError,
65
+ isTransientCloudflareRuntimeError,
66
+ } from './cloudflare-classification.ts'
67
+ export {
68
+ classifyBoundaryError,
69
+ classifyFailure,
70
+ retryAfterSecondsOf,
71
+ type BoundaryErrorClassifier,
72
+ } from './classify-failure.ts'
73
+ export { exponentialEqualJitterMs, spreadJitterMs } from './backoff.ts'
60
74
  export {
61
75
  configureLogger,
62
76
  consoleSink,
@@ -0,0 +1,25 @@
1
+ export {
2
+ QueueClient,
3
+ type IQueueClient,
4
+ type QueueBinding,
5
+ type QueueClientOptions,
6
+ type QueueSendOptions,
7
+ } from './queue-client.ts'
8
+ export type { QueueMessage } from './queue-message.ts'
9
+ export { QueueConsumer, type DispatchBus, type DispatchWrapper } from './queue-consumer.ts'
10
+ export {
11
+ chunkByLimits,
12
+ isOversized,
13
+ messageByteLength,
14
+ QUEUE_LIMITS,
15
+ sizeMessages,
16
+ type SizedMessage,
17
+ } from './queue-limits.ts'
18
+ export {
19
+ classifyQueueError,
20
+ DeadLetterUnavailableError,
21
+ OversizedMessageError,
22
+ QueueSendError,
23
+ type QueueOperation,
24
+ } from './queue.errors.ts'
25
+ export { decideRedelivery, type RedeliveryDecision } from './redelivery-policy.ts'