@fabricorg/webhook-delivery 0.1.1 → 0.1.3

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/codes.ts","../src/snapshot.ts","../src/errors.ts","../src/limits.ts","../src/store-input.ts","../src/delivery-store-core.ts","../src/receipt.ts","../src/memory-delivery-store.ts","../src/subscription-store-core.ts","../src/memory-subscription-store.ts","../src/postgres-sql.ts","../src/postgres-delivery-store.ts","../src/postgres-subscription-store.ts","../src/retry.ts","../src/classify.ts","../src/persistence-projection.ts","../src/egress.ts","../src/headers.ts","../src/address.ts","../src/call-bounds.ts","../src/destination.ts","../src/decisions.ts","../src/fan-out-call.ts","../src/fan-out-read.ts","../src/fan-out-publisher.ts","../src/action-events.ts","../src/fan-out-cycle.ts","../src/delivery-read.ts","../src/delivery-cycle.ts","../src/action-parameters.ts","../src/governed-actions.ts"],"names":["field","copy","text","reflectDefineProperty","objectCreate","raw","DateConstructor","record","nowMs","finish","copyOut","entry","compareText","ioBoundary","numberIsSafeInteger","NumberConstructor","created","unreadable","unreadableFail","EMPTY","block","hex","words","reflectGetOwnPropertyDescriptor","abortedGetter","mathMax","mathMin","isAborted","stringSlice","settle","stop","readActor","setTimer","clearTimer","reflectOwnKeys","numberIsFinite","ABORTED","release","INSERT_OUTCOMES","REFUSED","refuse","plain","nonEmpty","whole","MAX_CLAIMED","STATUSES","UNREADABLE","hasMethods","positiveWhole","readConfig","readConfigUnguarded","readClock","keepLease","deadLetter","retryOrDeadLetter","refused","flag","apply","result","subscriptionId","dateGetTime"],"mappings":";AASO,IAAM,8BAAA,GAAiC,OAAO,MAAA,CAAO;AAAA,EAC3D,qBAAA;AAAA,EACA,qBAAA;AAAA,EACA,0BAAA;AAAA,EACA,8BAAA;AAAA,EACA;AACD,CAAU;AAMH,IAAM,wBAAA,GAA2B,OAAO,MAAA,CAAO;AAAA,EACrD,eAA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G,SAAA,CAAU,IAAI,CAAC,CAAA;AAAA,MAChC,UAAA;AAAA,MACA,aAAA,EAAe,IAAA;AAAA,MACf,SAAA,EAAW;AAAA,QACV,YAAA,EAAc,iBAAA;AAAA,QACd,eAAA,EAAiB,WAAA;AAAA,QACjB,WAAA,EAAa,WAAA;AAAA,QACb,UAAA,EAAY,WAAA;AAAA,QACZ,WAAA,EAAa,mBAAA;AAAA,QACb,WAAA,EAAa;AAAA,OACd;AAAA,MACA,OAAA,EAAS,UAAA;AAAA,MACT,aAAA,EAAe,kEAAA;AAAA,MACf,OAAA,EAAS,UAAA,CAAW,IAAA,EAAM,IAAI;AAAA,KAC/B;AACA,IAAA,OAAO,UAAA;AAAA,EACR,CAAC,CAAA;AACD,EAAA,OAAO;AAAA,IACN,WAAW,IAAA,CAAK,SAAA;AAAA,IAChB,OAAA,EAAS,OAAA;AAAA,IACT,WAAA,EAAa,kBAAA;AAAA,IACb,WAAA,EAAa,gHAAA;AAAA,IACb,YAAA,EAAc,CAAC,YAAA,EAAc,MAAA,EAAQ,GAAG,CAAA;AAAA,IACxC,UAAA,EAAY,oCAAoC,GAAA,CAAI,CAAC,eAAe,EAAE,SAAA,EAAW,aAAA,EAAe,CAAA,EAAE,CAAE,CAAA;AAAA,IACpG,OAAA;AAAA,IACA,QAAA,EAAU,CAAC,MAAM;AAAA,GAClB;AACD","file":"index.js","sourcesContent":["/**\n * Fixed code sets. Stored diagnostics, denial reasons and attempt outcomes are\n * typed as one of these codes rather than a free string or a port's error\n * message (ADR 0018 decision 2), so a thrown error has no field through which\n * to carry payload, secret or response-body text into a durable record. The\n * arrays are frozen, so no caller can widen a set at runtime.\n */\n\n/** Reasons an admission port may give for `deny`. */\nexport const WEBHOOK_ADMISSION_DENIAL_CODES = Object.freeze([\n\t\"actor_not_permitted\",\n\t\"scope_not_permitted\",\n\t\"event_type_not_permitted\",\n\t\"classification_not_permitted\",\n\t\"policy_denied\",\n] as const);\n\n/** A reason code carried by an admission `deny` decision and stored on its denial record. */\nexport type WebhookAdmissionDenialCode = (typeof WEBHOOK_ADMISSION_DENIAL_CODES)[number];\n\n/** Reasons a delivery authorization port may give for `revoked`. */\nexport const WEBHOOK_REVOCATION_CODES = Object.freeze([\n\t\"grant_expired\",\n\t\"scope_revoked\",\n\t\"registration_inactive\",\n] as const);\n\n/** A reason code carried by a delivery authorization `revoked` decision. */\nexport type WebhookRevocationCode = (typeof WEBHOOK_REVOCATION_CODES)[number];\n\n/**\n * Diagnostics stored on a fan-out job or delivery intent when a port failed,\n * timed out or a coordination check refused the work. A port exception is\n * stored as the code for that port, not as its message.\n *\n * Three are written only by the fan-out cycle: `eligibility_unsettled` when\n * it defers a job until its event's eligibility is settled (README,\n * \"Fan-out\"), `intent_build_failed` when it could not render a body or\n * create a delivery id for an admitted subscription, and `job_unreadable`\n * when it dead-letters a claimed job whose identity and lease it could read\n * but whose body it could not.\n *\n * Three are written only by the delivery cycle (README, \"Delivery\"):\n * `intent_unreadable` when it dead-letters a claimed intent whose identity\n * and lease it could read but whose body it could not,\n * `subscription_not_in_scope` when the intent's subscription does not exist\n * in the intent's tenant and space, or the store's answer names another\n * one, and `transport_not_sent` when the transport returned `not_sent` for\n * a request it never started.\n */\nexport const WEBHOOK_DIAGNOSTIC_CODES = Object.freeze([\n\t\"admission_unavailable\",\n\t\"authorization_unavailable\",\n\t\"subscription_store_unavailable\",\n\t\"delivery_store_unavailable\",\n\t\"signer_unavailable\",\n\t\"resolver_unavailable\",\n\t\"port_timeout\",\n\t\"scope_predicate_failed\",\n\t\"configuration_conflict\",\n\t\"lease_lost\",\n\t\"intent_not_pending\",\n\t\"processing_deadline_exceeded\",\n\t\"eligibility_unsettled\",\n\t\"intent_build_failed\",\n\t\"job_unreadable\",\n\t\"intent_unreadable\",\n\t\"subscription_not_in_scope\",\n\t\"transport_not_sent\",\n] as const);\n\n/** A stored diagnostic code for a port failure or refused coordination check. */\nexport type WebhookDiagnosticCode = (typeof WEBHOOK_DIAGNOSTIC_CODES)[number];\n\n/**\n * What a delivery attempt's observation means for its intent (ADR 0018\n * decision 10). `not_sent` is never a classification: the delivery cycle\n * records it, with the reason `not_sent`, on an attempt it began under the\n * intent's lease and handed to the transport, when the transport answered\n * that it never started the request (its deadline had passed or its signal\n * had aborted while the request was queued). Such an attempt spends no budget.\n */\nexport const WEBHOOK_ATTEMPT_OUTCOMES = Object.freeze([\n\t\"delivered\",\n\t\"retryable\",\n\t\"dead_letter\",\n\t\"cancelled\",\n\t\"not_sent\",\n] as const);\n\n/**\n * The classified result of one attempt. A 401 or 403 is `retryable` like any\n * other row of that kind; its `http_401` / `http_403` reason and the\n * classification's `receiverActionLikely` flag let the caller surface it to\n * operators before the retry budget is exhausted.\n */\nexport type WebhookAttemptOutcome = (typeof WEBHOOK_ATTEMPT_OUTCOMES)[number];\n\n/** The row of decision 10's table an observation matched. */\nexport const WEBHOOK_ATTEMPT_REASON_CODES = Object.freeze([\n\t\"http_2xx\",\n\t\"network_error\",\n\t\"timeout\",\n\t\"dns_failure\",\n\t\"http_408\",\n\t\"http_425\",\n\t\"http_429\",\n\t\"http_5xx\",\n\t\"signer_unavailable\",\n\t\"http_401\",\n\t\"http_403\",\n\t\"http_1xx\",\n\t\"http_3xx\",\n\t\"http_410\",\n\t\"http_4xx\",\n\t\"invalid_url\",\n\t\"private_address\",\n\t\"authorization_revoked\",\n\t\"subscription_paused\",\n\t\"subscription_deleted\",\n\t\"not_sent\",\n] as const);\n\n/** The reason code recorded with an attempt outcome. */\nexport type WebhookAttemptReasonCode = (typeof WEBHOOK_ATTEMPT_REASON_CODES)[number];\n\n/** Codes on {@link WebhookDeliveryConfigError}. */\nexport const WEBHOOK_CONFIG_ERROR_CODES = Object.freeze([\n\t\"limit_not_positive_finite\",\n\t\"limit_not_integer\",\n\t\"limit_out_of_range\",\n\t\"retry_schedule_empty\",\n\t\"limit_unreadable\",\n] as const);\n\n/** Why a configured limit was rejected. */\nexport type WebhookConfigErrorCode = (typeof WEBHOOK_CONFIG_ERROR_CODES)[number];\n\n/** Codes on {@link WebhookProjectionError}. */\nexport const WEBHOOK_PROJECTION_ERROR_CODES = Object.freeze([\n\t\"invalid_envelope\",\n\t\"payload_field_not_json\",\n\t\"fact_field_not_json\",\n\t\"accessor_property\",\n\t\"inspection_failed\",\n\t\"scope_mismatch\",\n] as const);\n\n/** Why an envelope could not be projected. */\nexport type WebhookProjectionErrorCode = (typeof WEBHOOK_PROJECTION_ERROR_CODES)[number];\n\n/**\n * Codes on the `TypeError` and `RangeError` instances this package throws\n * for malformed call input (headers, classification, retry, admission).\n * Each code has one constant message; neither repeats the input.\n */\nexport const WEBHOOK_INPUT_ERROR_CODES = Object.freeze([\n\t\"input_unreadable\",\n\t\"observation_unknown\",\n\t\"status_out_of_range\",\n\t\"signature_malformed\",\n\t\"timestamp_invalid\",\n\t\"event_id_invalid\",\n\t\"delivery_id_invalid\",\n\t\"attempt_invalid\",\n\t\"raw_body_not_string\",\n\t\"random_source_missing\",\n\t\"random_sample_invalid\",\n\t\"random_source_failed\",\n\t\"denial_code_unknown\",\n] as const);\n\n/** Why call input was refused. */\nexport type WebhookInputErrorCode = (typeof WEBHOOK_INPUT_ERROR_CODES)[number];\n\n/**\n * Codes on {@link WebhookStoreError}: a store call that was malformed, broke\n * a store invariant, or was no longer wanted when the store reached its\n * write. Refusals the caller is expected to handle (a lost lease, an\n * existing key, a replay past the horizon, a requeue of a record that is not\n * dead-lettered) are results, not errors.\n */\nexport const WEBHOOK_STORE_ERROR_CODES = Object.freeze([\n\t\"input_invalid\",\n\t\"record_mismatch\",\n\t\"delivery_id_conflict\",\n\t\"call_aborted\",\n\t\"deadline_passed\",\n\t\"clock_invalid\",\n\t\"store_failed\",\n] as const);\n\n/** Why a store call was refused. */\nexport type WebhookStoreErrorCode = (typeof WEBHOOK_STORE_ERROR_CODES)[number];\n\n/**\n * Codes on {@link WebhookFanOutError}: why the fan-out publisher, the\n * composite publisher or the fan-out cycle refused or failed. A publisher\n * rejection makes the Host relay retry and, once its budget is spent,\n * dead-letter the outbox record, so a failed publish stays visible there.\n *\n * - `event_past_replay_horizon`: `insertFanOutJob` answered `past_horizon`.\n * The event is older than the replay horizon (R5), so no job can be stored\n * and the publish fails rather than counting as delivered.\n * - `fan_out_store_failed` / `fan_out_store_timeout`: the publisher's job\n * insert or the cycle's claim threw, or did not settle within\n * `portTimeoutMs`. Store failures later in a cycle reschedule the job\n * with a diagnostic instead.\n * - `publish_aborted`: the caller's signal aborted before the store answered.\n * - `sink_failed`: a required sink of a composite publisher rejected with an\n * error this package did not create.\n * - `sink_timeout`: a required sink of a composite publisher did not settle\n * within the composite's `sinkTimeoutMs`.\n * - `clock_invalid`: the injected clock threw or returned an invalid time.\n * - `options_invalid`: an option is missing or has the wrong shape.\n */\nexport const WEBHOOK_FAN_OUT_ERROR_CODES = Object.freeze([\n\t\"event_past_replay_horizon\",\n\t\"fan_out_store_failed\",\n\t\"fan_out_store_timeout\",\n\t\"publish_aborted\",\n\t\"sink_failed\",\n\t\"sink_timeout\",\n\t\"clock_invalid\",\n\t\"options_invalid\",\n] as const);\n\n/** Why a fan-out publish or cycle failed. */\nexport type WebhookFanOutErrorCode = (typeof WEBHOOK_FAN_OUT_ERROR_CODES)[number];\n\n/**\n * Codes on {@link WebhookDeliveryError}: why the delivery cycle could not\n * run. Everything that goes wrong while one claimed intent is processed is\n * settled on that intent with a fixed code instead (README, \"Delivery\").\n *\n * - `delivery_store_failed` / `delivery_store_timeout`: the claim threw or\n * answered something unreadable, or did not settle within `portTimeoutMs`.\n * - `clock_invalid`: the injected clock threw or returned an invalid time.\n * - `options_invalid`: an option or port is missing or has the wrong shape.\n */\nexport const WEBHOOK_DELIVERY_ERROR_CODES = Object.freeze([\n\t\"delivery_store_failed\",\n\t\"delivery_store_timeout\",\n\t\"clock_invalid\",\n\t\"options_invalid\",\n] as const);\n\n/** Why a delivery cycle failed. */\nexport type WebhookDeliveryErrorCode = (typeof WEBHOOK_DELIVERY_ERROR_CODES)[number];\n\n/**\n * Why a governed action (PR 9; README, \"Governed actions\") refused. At\n * submission, the action's admission check refuses with\n * `webhook_action_refused:<code>` (or `webhook_parameters_refused:<code>:<field>`\n * with a code from `WEBHOOK_ACTION_PARAMETER_CODES`) and Host records nothing.\n * At execution, the action fails with Host's `error` set to\n * `webhook_action_refused:<code>`, writes nothing more and emits no event.\n *\n * - `admission_not_enforced`: the handler ran without Host's record that the\n * submission was admitted (`ActionContext.admittedAt`), as under a Host\n * older than 7.3.0, which ignores `admitSubmission`. Nothing is written.\n * - `scope_invalid` / `actor_invalid`: Host's trusted context names a tenant,\n * space or actor that breaks the store identifier rule.\n * - `secret_ref_invalid`: the application's secret store says the reference\n * names no secret of this tenant. `secret_ref_unverified`: the check threw,\n * timed out or answered something unreadable.\n * - `secret_ref_unchanged`: a rotation named the reference already in use.\n * - `destination_refused`: the resolver refused the URL (`invalid_url`,\n * `private_address`). `destination_unresolved`: it answered `dns_failure`,\n * threw or timed out. Neither writes anything.\n * - `subscription_not_found`, `subscription_exists`, `subscription_deleted`,\n * `invalid_transition`, `revision_conflict`, `version_conflict`: the\n * subscription store refused the write, or the action's own read found\n * the same. `subscription_not_active`: an intent requeue for a paused or\n * deleted subscription. `paused_since_intent`: an intent requeue for an\n * active subscription that was paused and resumed after the intent's\n * eligibility revision; dispatch would cancel it (decision 3).\n * - `not_found`, `stale`, `not_dead_letter`, `past_replay_horizon`: the\n * delivery store refused a requeue or enrichment (decision 10, R5).\n * - `not_enrichable`, `actor_present`, `actor_suppressed`: enrichment of a\n * completed job, or of a job whose actor is not `legacy` (decision 5).\n * `actor_withheld`, `actor_not_found`, `actor_unavailable`: the\n * application's actor reader withheld the actor, found no such event, or\n * threw, timed out or answered something unreadable.\n * - `store_unavailable`: a read threw, timed out or answered something\n * unreadable; nothing was written. `store_outcome_unknown`: a write threw,\n * timed out or answered something unreadable, so it may have applied\n * (README, \"A store write that timed out is unknown\"); also a re-run of an\n * intent requeue whose evidence predates `subscriptionId` and whose intent\n * can no longer be read, so the applied requeue has no event (README,\n * \"Atomicity and re-runs\").\n * - `action_failed`: anything else, such as a failing clock; nothing it\n * threw is read.\n */\nexport const WEBHOOK_ACTION_REFUSAL_CODES = Object.freeze([\n\t\"admission_not_enforced\",\n\t\"scope_invalid\",\n\t\"actor_invalid\",\n\t\"secret_ref_invalid\",\n\t\"secret_ref_unverified\",\n\t\"secret_ref_unchanged\",\n\t\"destination_refused\",\n\t\"destination_unresolved\",\n\t\"subscription_not_found\",\n\t\"subscription_exists\",\n\t\"subscription_deleted\",\n\t\"subscription_not_active\",\n\t\"paused_since_intent\",\n\t\"invalid_transition\",\n\t\"revision_conflict\",\n\t\"version_conflict\",\n\t\"not_found\",\n\t\"stale\",\n\t\"not_dead_letter\",\n\t\"past_replay_horizon\",\n\t\"not_enrichable\",\n\t\"actor_present\",\n\t\"actor_suppressed\",\n\t\"actor_withheld\",\n\t\"actor_not_found\",\n\t\"actor_unavailable\",\n\t\"store_unavailable\",\n\t\"store_outcome_unknown\",\n\t\"action_failed\",\n] as const);\n\n/** Why a governed action refused. */\nexport type WebhookActionRefusalCode = (typeof WEBHOOK_ACTION_REFUSAL_CODES)[number];\n\n/**\n * Codes on {@link WebhookGovernedActionError}: `options_invalid`, a module\n * option or port is missing or has the wrong shape.\n */\nexport const WEBHOOK_GOVERNED_ACTION_ERROR_CODES = Object.freeze([\"options_invalid\"] as const);\n\n/** Why the governed-action module could not be built. */\nexport type WebhookGovernedActionErrorCode = (typeof WEBHOOK_GOVERNED_ACTION_ERROR_CODES)[number];\n","import type { WebhookJsonValue } from \"./types\";\n\n/*\n * The one place caller-supplied values are read (README, \"Security\n * properties\", P1). Every exported function copies the inputs it needs into\n * a package-owned snapshot here, at entry, and works on the snapshot only;\n * nothing is read after the snapshot is complete.\n *\n * - Properties are read through own property descriptors. An accessor is\n * refused without being called; a value is never read through `[[Get]]`.\n * - Records must be plain: prototype `Object.prototype` or `null`.\n * - Dates are read with the `Date.prototype` intrinsics, never the value's\n * own methods; arrays by index from their own `length`, never through an\n * iterator or their own methods.\n * - Every object the snapshot builds has a `null` prototype or is a fresh\n * array, is frozen, and was populated with `defineProperty` and\n * null-prototype descriptors, so nothing installed on `Object.prototype`\n * or `Array.prototype` is consulted when it is built, read or serialized.\n * - Every built-in the package calls after load is captured below, at module\n * load, and called through the captured `Reflect.apply`; replacing a\n * global or a prototype method later, including from a Proxy trap during\n * a call, does not change what the package runs.\n *\n * For plain data the snapshot is a faithful copy: most properties are read\n * once, and the few read again (a repeated allowlist name whose first read\n * found nothing, a nested object reachable along two paths) give the same\n * answer. A Proxy gets no such promise: its traps execute while the\n * snapshot is taken, possibly more than once for one property in those\n * cases, and the values they return need not agree. The snapshot holds whichever values were read,\n * and only the snapshot is used afterwards. Whatever a trap throws is\n * replaced by the entry point's guard (errors.ts) with a package-created,\n * constant error.\n */\n\nconst reflectApply = Reflect.apply;\nconst reflectOwnKeys = Reflect.ownKeys;\nconst reflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;\nconst reflectGetPrototypeOf = Reflect.getPrototypeOf;\nconst reflectDefineProperty = Reflect.defineProperty;\nconst objectCreate = Object.create;\nconst objectFreeze = Object.freeze;\nconst objectHasOwn = Object.hasOwn;\nconst objectPrototype = Object.prototype;\nconst arrayIsArray = Array.isArray;\nconst dateGetTime = Date.prototype.getTime;\nconst dateToISOString = Date.prototype.toISOString;\nconst DateConstructor = Date;\nconst regExpExec = RegExp.prototype.exec;\nconst stringTrim = String.prototype.trim;\nconst jsonStringify = JSON.stringify;\n\n/** Captured `Reflect.apply`, so a replaced `Function.prototype.call` is never used. */\nexport const apply = reflectApply;\n/** Captured numeric intrinsics. */\nexport const numberIsFinite = Number.isFinite;\nexport const numberIsSafeInteger = Number.isSafeInteger;\nexport const NumberConstructor = Number;\nexport const mathFloor = Math.floor;\nexport const mathMin = Math.min;\nexport const mathMax = Math.max;\nexport const dateParse = Date.parse;\nexport const freeze = objectFreeze;\nexport const hasOwn = objectHasOwn;\nexport const isArray = arrayIsArray;\n\n/** The longest option list (allowlist, retry schedule) a snapshot copies. */\nexport const MAX_LIST_LENGTH = 1_024;\n/** The deepest nesting a JSON snapshot copies; also bounds a cyclic value. */\nexport const MAX_JSON_DEPTH = 64;\n/** The most objects, arrays and dates one JSON snapshot copies. */\nexport const MAX_JSON_NODES = 100_000;\n\n/** Why a snapshot refused a value. The caller's `Fail` maps it to a public error. */\nexport type SnapshotFault = \"accessor\" | \"not_plain\" | \"hole\" | \"not_json\" | \"too_deep\" | \"too_large\";\n\n/** Throws the entry point's public error for a fault at a package-named field. */\nexport type Fail = (fault: SnapshotFault, field: string) => never;\n\n/** Stands in for a non-primitive where an option must be a primitive, so validation rejects it. */\nexport const NOT_PRIMITIVE: unique symbol = Symbol(\"webhook-delivery.not-primitive\");\n\n/** A null-prototype data descriptor, so `defineProperty` reads nothing from `Object.prototype`. */\nfunction dataDescriptor(value: unknown): PropertyDescriptor {\n\tconst descriptor = objectCreate(null) as { value?: unknown; enumerable?: boolean; writable?: boolean; configurable?: boolean };\n\tdescriptor.value = value;\n\tdescriptor.enumerable = true;\n\tdescriptor.writable = false;\n\tdescriptor.configurable = false;\n\treturn descriptor;\n}\n\n/** Define an own, enumerable, read-only data property without consulting any prototype. */\nexport function define(target: object, key: string | number, value: unknown): void {\n\treflectDefineProperty(target, key, dataDescriptor(value));\n}\n\n/** A fresh array holding `values`' elements in order, frozen. `values` must be package-owned. */\nexport function frozenList<T>(values: readonly T[]): readonly T[] {\n\tconst list: T[] = [];\n\tfor (let index = 0; index < values.length; index += 1) define(list, index, values[index]);\n\treturn objectFreeze(list);\n}\n\n/**\n * A frozen null-prototype copy of a package-built object literal. Keys whose\n * value is `undefined` are left out, so optional fields are absent rather\n * than present-and-undefined.\n */\nexport function record<T extends object>(fields: T): T {\n\tconst out = objectCreate(null) as T;\n\tconst keys = reflectOwnKeys(fields);\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index] as string;\n\t\tconst descriptor = reflectGetOwnPropertyDescriptor(fields, key);\n\t\tif (descriptor !== undefined && objectHasOwn(descriptor, \"value\") && descriptor.value !== undefined) define(out, key, descriptor.value);\n\t}\n\treturn objectFreeze(out);\n}\n\n/** A mutable null-prototype map for package-internal bookkeeping. */\nexport function emptyMap<T>(): Record<string, T> {\n\treturn objectCreate(null) as Record<string, T>;\n}\n\n/** `true` when `re` matches `value`, using the captured `RegExp.prototype.exec`. */\nexport function matches(re: RegExp, value: string): boolean {\n\treturn reflectApply(regExpExec, re, [value]) !== null;\n}\n\n/** `value.trim()` with the captured intrinsic. */\nexport function trim(value: string): string {\n\treturn reflectApply(stringTrim, value, []) as string;\n}\n\n/** `true` when `value` is one of the frozen package `codes`. */\nexport function isOneOf(codes: readonly string[], value: unknown): boolean {\n\tif (typeof value !== \"string\") return false;\n\tfor (let index = 0; index < codes.length; index += 1) if (codes[index] === value) return true;\n\treturn false;\n}\n\n/** `true` for a non-array object whose prototype is `Object.prototype` or `null`. A Proxy's trap may run. */\nexport function isPlainRecord(value: unknown): value is object {\n\tif (value === null || typeof value !== \"object\" || arrayIsArray(value)) return false;\n\tconst prototype = reflectGetPrototypeOf(value);\n\treturn prototype === objectPrototype || prototype === null;\n}\n\n/**\n * Read one own data property. Absent is `undefined`; an accessor is refused\n * through `fail` without being called.\n */\nexport function readOwn(target: object, key: string, field: string, fail: Fail): unknown {\n\tconst descriptor = reflectGetOwnPropertyDescriptor(target, key);\n\tif (descriptor === undefined) return undefined;\n\tif (!objectHasOwn(descriptor, \"value\")) return fail(\"accessor\", field);\n\treturn descriptor.value;\n}\n\n/** `undefined` for an absent value, the value for a primitive, {@link NOT_PRIMITIVE} otherwise. */\nexport function primitive(value: unknown): unknown {\n\tif (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return value;\n\treturn NOT_PRIMITIVE;\n}\n\n/**\n * The ISO-8601 form of a real `Date` with a finite time, or `undefined`.\n * Computed with the intrinsics, so an overridden `toISOString`, `getTime`,\n * `toJSON` or `Symbol.toPrimitive` is never called; a Proxy is not a date.\n */\nexport function isoDate(value: unknown): string | undefined {\n\tconst time = timeOf(value);\n\tif (!numberIsFinite(time)) return undefined;\n\treturn reflectApply(dateToISOString, value, []) as string;\n}\n\n/** The time value of a real `Date`, or `NaN` for anything else. */\nexport function timeOf(value: unknown): number {\n\tif (value === null || typeof value !== \"object\") return NaN;\n\ttry {\n\t\t// Throws for anything without a [[DateValue]] slot, a Proxy included,\n\t\t// before any of the value's own code could run.\n\t\treturn reflectApply(dateGetTime, value, []) as number;\n\t} catch {\n\t\treturn NaN;\n\t}\n}\n\n/** A real `Date` or a date string as ISO-8601, or `undefined`. */\nexport function isoFromDateOrString(value: unknown): string | undefined {\n\tif (typeof value === \"string\") return isoDate(new DateConstructor(value));\n\treturn isoDate(value);\n}\n\n/**\n * Copy an option list by index from its own `length`. Holes and\n * non-primitive elements are kept as `undefined` and {@link NOT_PRIMITIVE}\n * so validation can name the index; a non-array is {@link NOT_PRIMITIVE}.\n */\nexport function primitiveList(value: unknown, field: string, fail: Fail): unknown {\n\tif (!arrayIsArray(value)) return value === undefined ? undefined : NOT_PRIMITIVE;\n\tconst length = listLength(value, field, fail);\n\tconst copy: unknown[] = [];\n\tfor (let index = 0; index < length; index += 1) {\n\t\tdefine(copy, index, primitive(readOwn(value, `${index}`, `${field}[${index}]`, fail)));\n\t}\n\treturn objectFreeze(copy);\n}\n\n/** The strings of an option list, in order; other elements and holes are skipped. `undefined` for a non-array. */\nexport function stringList(value: unknown, field: string, fail: Fail): readonly string[] | undefined {\n\tconst copy = primitiveList(value, field, fail);\n\tif (!arrayIsArray(copy)) return undefined;\n\tconst strings: string[] = [];\n\tfor (let index = 0; index < copy.length; index += 1) {\n\t\tconst item = copy[index];\n\t\tif (typeof item === \"string\") define(strings, strings.length, item);\n\t}\n\treturn objectFreeze(strings);\n}\n\nfunction listLength(value: object, field: string, fail: Fail): number {\n\tconst length = readOwn(value, \"length\", field, fail);\n\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 0) return fail(\"not_json\", field);\n\tif (length > MAX_LIST_LENGTH) return fail(\"too_large\", field);\n\treturn length;\n}\n\n/**\n * Snapshot a JSON value: primitives as they are (finite numbers only), a\n * real `Date` as its ISO string, arrays as fresh frozen arrays, plain objects\n * as frozen null-prototype objects holding their own enumerable data\n * properties (`undefined` values skipped, as `JSON.stringify` does).\n * Functions, symbols, bigints, non-finite numbers, holes, accessors,\n * non-plain objects, nesting deeper than {@link MAX_JSON_DEPTH} (a cycle\n * included) and more than {@link MAX_JSON_NODES} containers are refused\n * through `fail`, naming `field` only.\n */\nexport function snapshotJson(value: unknown, field: string, fail: Fail): WebhookJsonValue {\n\treturn copyJson(value, field, fail, 0, { nodes: 0 });\n}\n\n/** The container count several {@link snapshotJsonPart} calls share. */\nexport interface JsonNodeBudget {\n\tnodes: number;\n}\n\n/**\n * Snapshot one part of a larger JSON value as if {@link snapshotJson} had\n * reached it at `depth` with `budget.nodes` containers already counted, so\n * several parts read separately are held to the same depth and node limits\n * as the whole value read at once.\n */\nexport function snapshotJsonPart(value: unknown, field: string, fail: Fail, depth: number, budget: JsonNodeBudget): WebhookJsonValue {\n\treturn copyJson(value, field, fail, depth, budget);\n}\n\nfunction copyJson(value: unknown, field: string, fail: Fail, depth: number, budget: JsonNodeBudget): WebhookJsonValue {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return numberIsFinite(value) ? value : fail(\"not_json\", field);\n\tif (typeof value !== \"object\") return fail(\"not_json\", field);\n\tif (depth >= MAX_JSON_DEPTH) return fail(\"too_deep\", field);\n\tbudget.nodes += 1;\n\tif (budget.nodes > MAX_JSON_NODES) return fail(\"too_large\", field);\n\tconst iso = isoDate(value);\n\tif (iso !== undefined) return iso;\n\tif (arrayIsArray(value)) {\n\t\tconst length = readOwn(value, \"length\", field, fail);\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 0) return fail(\"not_json\", field);\n\t\tif (length > MAX_JSON_NODES) return fail(\"too_large\", field);\n\t\tconst copy: WebhookJsonValue[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst item = readOwn(value, `${index}`, field, fail);\n\t\t\tif (item === undefined) return fail(\"hole\", field);\n\t\t\tdefine(copy, index, copyJson(item, field, fail, depth + 1, budget));\n\t\t}\n\t\treturn objectFreeze(copy);\n\t}\n\tif (!isPlainRecord(value)) return fail(\"not_plain\", field);\n\tconst keys = reflectOwnKeys(value);\n\tconst copy = objectCreate(null) as Record<string, WebhookJsonValue>;\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index];\n\t\tif (typeof key !== \"string\") continue;\n\t\tconst descriptor = reflectGetOwnPropertyDescriptor(value, key);\n\t\tif (descriptor === undefined || descriptor.enumerable !== true) continue;\n\t\tif (!objectHasOwn(descriptor, \"value\")) return fail(\"accessor\", field);\n\t\tif (descriptor.value === undefined) continue;\n\t\tdefine(copy, key, copyJson(descriptor.value, field, fail, depth + 1, budget));\n\t}\n\treturn objectFreeze(copy);\n}\n\n/**\n * Serialize a snapshot to JSON text. It walks only package-built values\n * (frozen null-prototype objects, frozen fresh arrays, primitives), so no\n * `toJSON`, getter or prototype member is ever consulted. Strings are quoted\n * with the captured `JSON.stringify`, which reads no property of a string\n * primitive. The output is what `JSON.stringify` gives for the same data.\n */\nexport function serializeJson(value: unknown): string {\n\tif (value === null) return \"null\";\n\tif (typeof value === \"string\") return jsonStringify(value) as string;\n\tif (typeof value === \"number\") return numberIsFinite(value) ? `${value}` : \"null\";\n\tif (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n\tif (typeof value !== \"object\") return \"null\";\n\tif (arrayIsArray(value)) {\n\t\tlet text = \"[\";\n\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\tif (index > 0) text += \",\";\n\t\t\ttext += serializeJson(value[index]);\n\t\t}\n\t\treturn `${text}]`;\n\t}\n\tconst keys = reflectOwnKeys(value);\n\tlet text = \"{\";\n\tlet first = true;\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index];\n\t\tif (typeof key !== \"string\") continue;\n\t\tconst item = (value as Record<string, unknown>)[key];\n\t\tif (item === undefined) continue;\n\t\ttext += `${first ? \"\" : \",\"}${jsonStringify(key) as string}:${serializeJson(item)}`;\n\t\tfirst = false;\n\t}\n\treturn `${text}}`;\n}\n","import type { WebhookConfigErrorCode, WebhookDeliveryErrorCode, WebhookFanOutErrorCode, WebhookGovernedActionErrorCode, WebhookInputErrorCode, WebhookProjectionErrorCode, WebhookStoreErrorCode } from \"./codes\";\nimport { apply, define, freeze, hasOwn } from \"./snapshot\";\n\n/*\n * Package errors and the one guard every exported function runs inside\n * (README, \"Security properties\", P2).\n *\n * Every error this package throws is created by a factory below, which\n * gives it a fixed code and that code's constant message, replaces its\n * native stack with fixed text, records it in a module-private WeakSet and\n * freezes it. The public constructors never touch\n * the WeakSet, so a caller constructing a `WebhookProjectionError` cannot make\n * it pass for one of ours. The guard tells the two apart with\n * `WeakSet.prototype.has` alone, which runs no Proxy trap and reads no\n * property of the thrown value; anything not in the set is dropped unread and\n * replaced by a fresh error from the entry point's factory.\n *\n * The WeakSet is per copy of the module. It is not a registry of ports or\n * predicates (ADR 0018 decision 6): it holds only errors this copy created,\n * and a second copy of the package (ESM and CommonJS loaded together) treats\n * the first copy's errors as foreign and replaces them with its own.\n */\n\nconst PROJECTION_MESSAGES: Readonly<Record<WebhookProjectionErrorCode, string>> = freeze({\n\tinvalid_envelope: \"Webhook projection failed: a required envelope or job field is missing or invalid.\",\n\tpayload_field_not_json: \"Webhook projection failed: an allowlisted payload field is not plain JSON.\",\n\tfact_field_not_json: \"Webhook projection failed: a declared fact field is not plain JSON.\",\n\taccessor_property: \"Webhook projection failed: accessor properties are not read.\",\n\tinspection_failed: \"Webhook projection failed: an input could not be inspected.\",\n\tscope_mismatch: \"Webhook projection failed: the subscription's scope does not match the event's tenant and space.\",\n});\n\nconst CONFIG_MESSAGES: Readonly<Record<WebhookConfigErrorCode, string>> = freeze({\n\tlimit_not_positive_finite: \"Webhook delivery limit must be a positive, finite number.\",\n\tlimit_not_integer: \"Webhook delivery limit must be a whole number.\",\n\tlimit_out_of_range: \"Webhook delivery limit is outside its allowed range.\",\n\tretry_schedule_empty: \"Webhook delivery retry schedule must list at least one delay.\",\n\tlimit_unreadable: \"Webhook delivery limits could not be read.\",\n});\n\nconst INPUT_MESSAGES: Readonly<Record<WebhookInputErrorCode, string>> = freeze({\n\tinput_unreadable: \"Webhook delivery input could not be read.\",\n\tobservation_unknown: \"Webhook delivery observation is not one decision 10 classifies.\",\n\tstatus_out_of_range: \"Webhook response status must be a whole number from 100 to 599.\",\n\tsignature_malformed: \"Webhook signature must be a v1=<64 lowercase hex> value.\",\n\ttimestamp_invalid: \"Webhook timestamp must be a non-negative whole number of seconds.\",\n\tevent_id_invalid: \"Webhook eventId must be printable ASCII with no control characters or surrounding spaces.\",\n\tdelivery_id_invalid: \"Webhook deliveryId must be printable ASCII with no control characters or surrounding spaces.\",\n\tattempt_invalid: \"Webhook attempt must be a positive whole number.\",\n\traw_body_not_string: \"Webhook raw body must be a string.\",\n\trandom_source_missing: \"createWebhookRetryDelay requires a random source.\",\n\trandom_sample_invalid: \"Webhook retry random source must return a number in [0, 1).\",\n\trandom_source_failed: \"Webhook retry random source failed.\",\n\tdenial_code_unknown: \"Webhook admission denial code is not in WEBHOOK_ADMISSION_DENIAL_CODES.\",\n});\n\nconst STORE_MESSAGES: Readonly<Record<WebhookStoreErrorCode, string>> = freeze({\n\tinput_invalid: \"Webhook store input is missing, malformed or not plain data.\",\n\trecord_mismatch: \"Webhook store record does not match its parent's event, tenant, space or delivery.\",\n\tdelivery_id_conflict: \"Webhook store deliveryId is already used by another subscription and event.\",\n\tcall_aborted: \"Webhook store call was aborted before the store acted.\",\n\tdeadline_passed: \"Webhook store call deadline passed before the store acted.\",\n\tclock_invalid: \"Webhook store clock failed or returned an invalid time.\",\n\tstore_failed: \"Webhook store failed.\",\n});\n\nconst FAN_OUT_MESSAGES: Readonly<Record<WebhookFanOutErrorCode, string>> = freeze({\n\tevent_past_replay_horizon: \"Webhook fan-out refused the event: it is older than the replay horizon, so no fan-out job can be stored.\",\n\tfan_out_store_failed: \"Webhook fan-out store call failed.\",\n\tfan_out_store_timeout: \"Webhook fan-out store call did not settle in time.\",\n\tpublish_aborted: \"Webhook fan-out publish was aborted before the job was stored.\",\n\tsink_failed: \"A required sink of the composite event publisher failed.\",\n\tsink_timeout: \"A required sink of the composite event publisher did not settle in time.\",\n\tclock_invalid: \"Webhook fan-out clock failed or returned an invalid time.\",\n\toptions_invalid: \"Webhook fan-out options are missing or malformed.\",\n});\n\nconst DELIVERY_MESSAGES: Readonly<Record<WebhookDeliveryErrorCode, string>> = freeze({\n\tdelivery_store_failed: \"Webhook delivery store call failed.\",\n\tdelivery_store_timeout: \"Webhook delivery store call did not settle in time.\",\n\tclock_invalid: \"Webhook delivery clock failed or returned an invalid time.\",\n\toptions_invalid: \"Webhook delivery options are missing or malformed.\",\n});\n\nconst GOVERNED_ACTION_MESSAGES: Readonly<Record<WebhookGovernedActionErrorCode, string>> = freeze({\n\toptions_invalid: \"Webhook governed-action module options are missing or malformed.\",\n});\n\nfunction messageFor(table: Readonly<Record<string, string>>, code: unknown, fallback: string): string {\n\treturn typeof code === \"string\" && hasOwn(table, code) ? table[code]! : fallback;\n}\n\nconst reflectDefineProperty = Reflect.defineProperty;\nconst objectCreate = Object.create;\n\n/**\n * An own, enumerable, writable data property, defined with a null-prototype\n * descriptor so neither `Error.prototype` nor `Object.prototype` is consulted.\n * Errors the package throws are frozen afterwards.\n */\nfunction defineField(target: object, key: string, value: unknown): void {\n\tconst descriptor = objectCreate(null) as PropertyDescriptor;\n\tdescriptor.value = value;\n\tdescriptor.enumerable = true;\n\tdescriptor.writable = true;\n\tdescriptor.configurable = true;\n\treflectDefineProperty(target, key, descriptor);\n}\n\n/**\n * A configured limit was not usable: zero, negative, `NaN`, infinite, not an\n * integer where a count is required, outside its documented range, or not\n * readable as plain data. The message is constant for the code; `field`\n * names the limit, for example `deliveryRetryDelaysMs[2]`.\n */\nexport class WebhookDeliveryConfigError extends Error {\n\tdeclare readonly code: WebhookConfigErrorCode;\n\t/** The limit that was rejected, for example `deliveryRetryDelaysMs[2]`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookConfigErrorCode, field: string) {\n\t\tsuper(messageFor(CONFIG_MESSAGES, code, \"Webhook delivery limit was rejected.\"));\n\t\tdefineField(this, \"name\", \"WebhookDeliveryConfigError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * An envelope, job or subscription could not be projected. The message is\n * constant for the code. `field` names an envelope or job field, an option,\n * or a field name from the caller's own allowlist; never a value.\n */\nexport class WebhookProjectionError extends Error {\n\tdeclare readonly code: WebhookProjectionErrorCode;\n\t/** The envelope, job, option or allowlisted payload field at fault. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookProjectionErrorCode, field: string) {\n\t\tsuper(messageFor(PROJECTION_MESSAGES, code, \"Webhook projection failed.\"));\n\t\tdefineField(this, \"name\", \"WebhookProjectionError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * A store call was refused: its input was malformed or not plain data\n * (`input_invalid`), it broke a store invariant (`record_mismatch`,\n * `delivery_id_conflict`), it was aborted or past its deadline when the\n * store reached its write (`call_aborted`, `deadline_passed`), or the\n * store's clock failed (`clock_invalid`). Nothing was written. The message\n * is constant for the code; `field` names an input field, never a value.\n */\nexport class WebhookStoreError extends Error {\n\tdeclare readonly code: WebhookStoreErrorCode;\n\t/** The input field at fault, for example `intent.eventId`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookStoreErrorCode, field: string) {\n\t\tsuper(messageFor(STORE_MESSAGES, code, \"Webhook store call was refused.\"));\n\t\tdefineField(this, \"name\", \"WebhookStoreError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * The fan-out publisher, the composite publisher or the fan-out cycle refused\n * or failed (`WEBHOOK_FAN_OUT_ERROR_CODES`). The message is constant for the\n * code; `field` names an option, a store method or a sink name from the\n * application's own configuration, never an event value.\n */\nexport class WebhookFanOutError extends Error {\n\tdeclare readonly code: WebhookFanOutErrorCode;\n\t/** The option, store method or sink at fault, for example `insertFanOutJob`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookFanOutErrorCode, field: string) {\n\t\tsuper(messageFor(FAN_OUT_MESSAGES, code, \"Webhook fan-out failed.\"));\n\t\tdefineField(this, \"name\", \"WebhookFanOutError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * The delivery cycle could not run (`WEBHOOK_DELIVERY_ERROR_CODES`). The\n * message is constant for the code; `field` names an option or a store\n * method, never a value.\n */\nexport class WebhookDeliveryError extends Error {\n\tdeclare readonly code: WebhookDeliveryErrorCode;\n\t/** The option or store method at fault, for example `claimDeliveryIntents`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookDeliveryErrorCode, field: string) {\n\t\tsuper(messageFor(DELIVERY_MESSAGES, code, \"Webhook delivery failed.\"));\n\t\tdefineField(this, \"name\", \"WebhookDeliveryError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * The governed-action module could not be built\n * (`WEBHOOK_GOVERNED_ACTION_ERROR_CODES`). The message is constant for the\n * code; `field` names an option, never a value.\n */\nexport class WebhookGovernedActionError extends Error {\n\tdeclare readonly code: WebhookGovernedActionErrorCode;\n\t/** The option at fault, for example `secretReferences.verify`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookGovernedActionErrorCode, field: string) {\n\t\tsuper(messageFor(GOVERNED_ACTION_MESSAGES, code, \"Webhook governed-action module could not be built.\"));\n\t\tdefineField(this, \"name\", \"WebhookGovernedActionError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\nconst created = new WeakSet<object>();\nconst weakSetAdd = WeakSet.prototype.add;\nconst weakSetHas = WeakSet.prototype.has;\nconst TypeErrorConstructor = TypeError;\nconst RangeErrorConstructor = RangeError;\n\n/**\n * Register a factory-made error and freeze it. Its native `stack` is\n * replaced first with fixed package text: V8 frames name the functions on\n * the call stack, and a caller can name its own function (a Proxy trap, a\n * getter, a callback that calls a package helper) after a secret. Replacing\n * it before anything reads it also means `Error.prepareStackTrace` is never\n * consulted for a package error.\n */\nfunction mark<E extends Error>(error: E, name: string, code: string): E {\n\tconst stack = objectCreate(null) as PropertyDescriptor;\n\tstack.value = `${name}: ${code}`;\n\tstack.enumerable = false;\n\tstack.writable = false;\n\tstack.configurable = false;\n\tif (!reflectDefineProperty(error, \"stack\", stack)) throw new TypeErrorConstructor(\"Webhook delivery could not seal an error.\");\n\tapply(weakSetAdd, created, [error]);\n\treturn freeze(error);\n}\n\n/** `true` only for an error one of this module's factories created. Runs no code of `value`. */\nfunction isPackageError(value: unknown): boolean {\n\treturn (typeof value === \"object\" || typeof value === \"function\") && value !== null && apply(weakSetHas, created, [value]) === true;\n}\n\n/** @internal A package-created, frozen projection error. */\nexport function projectionError(code: WebhookProjectionErrorCode, field: string): WebhookProjectionError {\n\treturn mark(new WebhookProjectionError(code, field), \"WebhookProjectionError\", code);\n}\n\n/** @internal A package-created, frozen limit error. */\nexport function configError(code: WebhookConfigErrorCode, field: string): WebhookDeliveryConfigError {\n\treturn mark(new WebhookDeliveryConfigError(code, field), \"WebhookDeliveryConfigError\", code);\n}\n\n/** @internal A package-created, frozen store error. */\nexport function storeError(code: WebhookStoreErrorCode, field: string): WebhookStoreError {\n\treturn mark(new WebhookStoreError(code, field), \"WebhookStoreError\", code);\n}\n\n/** @internal A package-created, frozen fan-out error. */\nexport function fanOutError(code: WebhookFanOutErrorCode, field: string): WebhookFanOutError {\n\treturn mark(new WebhookFanOutError(code, field), \"WebhookFanOutError\", code);\n}\n\n/** @internal A package-created, frozen delivery-cycle error. */\nexport function deliveryError(code: WebhookDeliveryErrorCode, field: string): WebhookDeliveryError {\n\treturn mark(new WebhookDeliveryError(code, field), \"WebhookDeliveryError\", code);\n}\n\n/** @internal A package-created, frozen governed-action module error. */\nexport function governedActionError(code: WebhookGovernedActionErrorCode, field: string): WebhookGovernedActionError {\n\treturn mark(new WebhookGovernedActionError(code, field), \"WebhookGovernedActionError\", code);\n}\n\n/** @internal A package-created, frozen `TypeError` or `RangeError` carrying `code`. */\nexport function inputError(kind: \"type\" | \"range\", code: WebhookInputErrorCode): TypeError | RangeError {\n\tconst message = INPUT_MESSAGES[code];\n\tconst error = kind === \"type\" ? new TypeErrorConstructor(message) : new RangeErrorConstructor(message);\n\tdefine(error, \"code\", code);\n\treturn mark(error, kind === \"type\" ? \"TypeError\" : \"RangeError\", code);\n}\n\n/**\n * @internal Run an entry point. A package-created error passes through\n * unchanged; anything else thrown (by a Proxy trap, an injected callback or\n * the engine) is never inspected and is replaced by `replacement()`.\n */\nexport function guard<T>(run: () => T, replacement: () => Error): T {\n\ttry {\n\t\treturn run();\n\t} catch (thrown) {\n\t\tif (isPackageError(thrown)) throw thrown;\n\t\tthrow replacement();\n\t}\n}\n\n/** @internal Run a total function: any throw, package-created or not, yields `fallback()` unread. */\nexport function guardOr<T>(run: () => T, fallback: () => T): T {\n\ttry {\n\t\treturn run();\n\t} catch {\n\t\treturn fallback();\n\t}\n}\n","import { configError, guard } from \"./errors\";\nimport {\n\tdefine,\n\temptyMap,\n\tfreeze,\n\tisArray,\n\tisPlainRecord,\n\tnumberIsFinite,\n\tnumberIsSafeInteger,\n\tprimitive,\n\tprimitiveList,\n\treadOwn,\n\ttype Fail,\n} from \"./snapshot\";\n\n/**\n * Every bound the delivery lifecycle relies on (R4). All values are\n * milliseconds or counts and must be positive and finite;\n * {@link resolveWebhookDeliveryLimits} enforces that.\n */\nexport interface WebhookDeliveryLimits {\n\t/** Attempts per delivery intent before dead letter, including the first. */\n\treadonly maxDeliveryAttempts: number;\n\t/** Delays before attempts 2, 3, ...; the last entry repeats if attempts outnumber it. */\n\treadonly deliveryRetryDelaysMs: readonly number[];\n\t/** Processing deadline persisted on an intent at creation. */\n\treadonly deliveryDeadlineMs: number;\n\t/** Attempts per fan-out job before dead letter. */\n\treadonly maxFanOutAttempts: number;\n\t/** Fan-out retry delays; the last entry repeats. */\n\treadonly fanOutRetryDelaysMs: readonly number[];\n\t/** Processing deadline persisted on a fan-out job at creation. */\n\treadonly fanOutDeadlineMs: number;\n\t/** Bound on one transport call, from handoff to settled response. */\n\treadonly attemptTimeoutMs: number;\n\t/** Bound on every other awaited port call, stores included. */\n\treadonly portTimeoutMs: number;\n\t/** Jitter added to a retry delay, as a fraction of it, in `(0, 1]`. */\n\treadonly retryJitterRatio: number;\n\t/** The longest `Retry-After` honoured; longer requests are clamped to it. */\n\treadonly maxRetryAfterMs: number;\n\t/**\n\t * The replay horizon (R5): how long after an event's `recordedAt` the\n\t * delivery store accepts a fan-out job, intent or denial for it, accepts a\n\t * requeue of one, and keeps its records and tombstones. A replay older\n\t * than this is rejected as `past_horizon`. It must be a whole number of\n\t * milliseconds no shorter than `fanOutDeadlineMs + deliveryDeadlineMs`,\n\t * and should be much longer: it also has to cover the Host relay budget,\n\t * how long a Host outbox dead letter may wait for requeue, and how long an\n\t * operator may take to requeue a webhook dead letter. Pass the same value\n\t * to the delivery store.\n\t */\n\treadonly replayHorizonMs: number;\n}\n\nconst MINUTE = 60_000;\nconst HOUR = 60 * MINUTE;\nconst DAY = 24 * HOUR;\n\n/** The largest millisecond offset a JavaScript `Date` represents, so `now - horizon` stays a valid time. */\nexport const WEBHOOK_MAX_REPLAY_HORIZON_MS = 8_640_000_000_000_000;\n\n/** The largest delay a JavaScript timer accepts without overflowing. */\nexport const WEBHOOK_MAX_TIMER_MS = 2_147_483_647;\n\n/**\n * Defaults. Delivery: eight attempts with AutoRefi's first seven delays\n * (1m, 5m, 15m, 1h, 6h, 12h, 24h), per ADR 0018 decision 10.\n */\nexport const DEFAULT_WEBHOOK_DELIVERY_LIMITS: WebhookDeliveryLimits = Object.freeze({\n\tmaxDeliveryAttempts: 8,\n\tdeliveryRetryDelaysMs: Object.freeze([MINUTE, 5 * MINUTE, 15 * MINUTE, HOUR, 6 * HOUR, 12 * HOUR, 24 * HOUR]),\n\tdeliveryDeadlineMs: 72 * HOUR,\n\tmaxFanOutAttempts: 24,\n\tfanOutRetryDelaysMs: Object.freeze([1_000, 5_000, 30_000, MINUTE, 5 * MINUTE, 15 * MINUTE]),\n\tfanOutDeadlineMs: 24 * HOUR,\n\tattemptTimeoutMs: 15_000,\n\tportTimeoutMs: 5_000,\n\tretryJitterRatio: 0.1,\n\tmaxRetryAfterMs: HOUR,\n\treplayHorizonMs: 30 * DAY,\n});\n\n/** Every limit, in {@link WebhookDeliveryLimits} order. */\nconst LIMIT_KEYS = Object.freeze([\n\t\"maxDeliveryAttempts\",\n\t\"deliveryRetryDelaysMs\",\n\t\"deliveryDeadlineMs\",\n\t\"maxFanOutAttempts\",\n\t\"fanOutRetryDelaysMs\",\n\t\"fanOutDeadlineMs\",\n\t\"attemptTimeoutMs\",\n\t\"portTimeoutMs\",\n\t\"retryJitterRatio\",\n\t\"maxRetryAfterMs\",\n\t\"replayHorizonMs\",\n] as const satisfies readonly (keyof WebhookDeliveryLimits)[]);\n\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;\n\nconst limitFail: Fail = (fault, field) => {\n\tthrow configError(fault === \"too_large\" ? \"limit_out_of_range\" : \"limit_unreadable\", field);\n};\n\n/**\n * Merge overrides onto {@link DEFAULT_WEBHOOK_DELIVERY_LIMITS} and validate\n * every limit. An override left `undefined` keeps the default. The\n * overrides are copied at entry into a snapshot, one descriptor read per\n * limit (an accessor is refused, not called), and schedules are copied by\n * index; the snapshot is validated and is what is returned, frozen. Keys\n * that are not limits are ignored.\n *\n * @throws {WebhookDeliveryConfigError} when any limit is zero, negative,\n * `NaN`, infinite, fractional where a count is required, out of range, or\n * cannot be read as plain data (`limit_unreadable`).\n */\nexport function resolveWebhookDeliveryLimits(\n\toverrides: Partial<WebhookDeliveryLimits> = {},\n): WebhookDeliveryLimits {\n\treturn guard(() => resolveLimits(overrides), () => configError(\"limit_unreadable\", \"overrides\"));\n}\n\nfunction resolveLimits(overrides: unknown): WebhookDeliveryLimits {\n\tif (!isPlainRecord(overrides)) return limitFail(\"not_plain\", \"overrides\");\n\tconst merged = emptyMap<unknown>();\n\tfor (let index = 0; index < LIMIT_KEYS.length; index += 1) {\n\t\tconst key = LIMIT_KEYS[index]!;\n\t\tconst raw = readOwn(overrides, key, key, limitFail);\n\t\tconst value = key === \"deliveryRetryDelaysMs\" || key === \"fanOutRetryDelaysMs\" ? primitiveList(raw, key, limitFail) : primitive(raw);\n\t\tdefine(merged, key, value === undefined ? DEFAULT_WEBHOOK_DELIVERY_LIMITS[key] : value);\n\t}\n\tconst limits = merged as unknown as WebhookDeliveryLimits;\n\tassertPositiveInteger(limits.maxDeliveryAttempts, \"maxDeliveryAttempts\");\n\tassertDelaySchedule(limits.deliveryRetryDelaysMs, \"deliveryRetryDelaysMs\");\n\tassertPositiveFinite(limits.deliveryDeadlineMs, \"deliveryDeadlineMs\");\n\tassertPositiveInteger(limits.maxFanOutAttempts, \"maxFanOutAttempts\");\n\tassertDelaySchedule(limits.fanOutRetryDelaysMs, \"fanOutRetryDelaysMs\");\n\tassertPositiveFinite(limits.fanOutDeadlineMs, \"fanOutDeadlineMs\");\n\tassertTimerBound(limits.attemptTimeoutMs, \"attemptTimeoutMs\");\n\tassertTimerBound(limits.portTimeoutMs, \"portTimeoutMs\");\n\tassertJitterRatio(limits.retryJitterRatio, \"retryJitterRatio\");\n\tassertPositiveFinite(limits.maxRetryAfterMs, \"maxRetryAfterMs\");\n\tassertJitteredScheduleRepresentable(limits.deliveryRetryDelaysMs, limits.retryJitterRatio, \"deliveryRetryDelaysMs\");\n\tassertJitteredScheduleRepresentable(limits.fanOutRetryDelaysMs, limits.retryJitterRatio, \"fanOutRetryDelaysMs\");\n\tassertReplayHorizon(limits.replayHorizonMs, \"replayHorizonMs\");\n\t// A job and its intents legitimately stay pending for up to both\n\t// processing deadlines; a shorter horizon would reject their own writes.\n\tif (limits.replayHorizonMs < limits.fanOutDeadlineMs + limits.deliveryDeadlineMs) {\n\t\tthrow configError(\"limit_out_of_range\", \"replayHorizonMs\");\n\t}\n\t// The snapshot's schedules are already frozen copies; freezing the map\n\t// makes the validated snapshot the returned value.\n\treturn freeze(merged) as unknown as WebhookDeliveryLimits;\n}\n\n/** @internal `value` must come from a snapshot (a primitive). */\nexport function assertPositiveFinite(value: unknown, field: string): asserts value is number {\n\tif (typeof value !== \"number\" || !numberIsFinite(value) || value <= 0) {\n\t\tthrow configError(\"limit_not_positive_finite\", field);\n\t}\n}\n\n/** @internal */\nexport function assertPositiveInteger(value: unknown, field: string): asserts value is number {\n\tassertPositiveFinite(value, field);\n\tif (!numberIsSafeInteger(value)) {\n\t\tthrow configError(\"limit_not_integer\", field);\n\t}\n}\n\n/** @internal `value` must be a snapshot list (see `primitiveList`) or a package constant. */\nexport function assertDelaySchedule(value: unknown, field: string): asserts value is readonly number[] {\n\tif (!isArray(value) || value.length === 0) {\n\t\tthrow configError(\"retry_schedule_empty\", field);\n\t}\n\t// Indexed: a hole in the input is `undefined` in the snapshot.\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tassertPositiveFinite(value[index], `${field}[${index}]`);\n\t}\n}\n\n/**\n * Every delay, with the largest jitter added, must stay a safe integer, so\n * the jittered delay is finite and exactly representable.\n *\n * @internal\n */\nexport function assertJitteredScheduleRepresentable(delays: readonly number[], jitterRatio: number, field: string): void {\n\tfor (let index = 0; index < delays.length; index += 1) {\n\t\tif (!(delays[index]! * (1 + jitterRatio) <= MAX_SAFE_INTEGER)) {\n\t\t\tthrow configError(\"limit_out_of_range\", `${field}[${index}]`);\n\t\t}\n\t}\n}\n\n/** @internal */\nexport function assertJitterRatio(value: unknown, field: string): asserts value is number {\n\tassertPositiveFinite(value, field);\n\tif (value > 1) {\n\t\tthrow configError(\"limit_out_of_range\", field);\n\t}\n}\n\n/**\n * A replay horizon must be a positive whole number of milliseconds no larger\n * than {@link WEBHOOK_MAX_REPLAY_HORIZON_MS}. The delivery stores run this at\n * construction.\n *\n * @internal `value` must be a primitive.\n */\nexport function assertReplayHorizon(value: unknown, field: string): asserts value is number {\n\tassertPositiveInteger(value, field);\n\tif (value > WEBHOOK_MAX_REPLAY_HORIZON_MS) {\n\t\tthrow configError(\"limit_out_of_range\", field);\n\t}\n}\n\nfunction assertTimerBound(value: unknown, field: string): asserts value is number {\n\tassertPositiveFinite(value, field);\n\tif (value > WEBHOOK_MAX_TIMER_MS) {\n\t\tthrow configError(\"limit_out_of_range\", field);\n\t}\n}\n","import { storeError } from \"./errors\";\nimport type { WebhookClock } from \"./ports\";\nimport {\n\tapply,\n\tdateParse,\n\tfreeze,\n\tisArray,\n\tisoDate,\n\tisoFromDateOrString,\n\tisOneOf,\n\tmatches,\n\tnumberIsSafeInteger,\n\treadOwn,\n\tserializeJson,\n\tsnapshotJson,\n\ttimeOf,\n\ttype Fail,\n} from \"./snapshot\";\nimport type { WebhookJsonObject, WebhookJsonValue } from \"./types\";\n\n/*\n * Input reading for the memory stores. A store method copies its arguments\n * into a package-owned snapshot at entry, with the same readers the pure\n * functions use (`src/snapshot.ts`): own data properties only, accessors\n * refused uncalled, `Date`s read with the intrinsics and turned into\n * ISO-8601 strings. The method then reads only the snapshot. Every refusal\n * is a package-created `WebhookStoreError` naming a field, never a value.\n */\n\nconst DateConstructor = Date;\n\nconst inputFail: Fail = (_fault, field) => {\n\tthrow storeError(\"input_invalid\", field);\n};\n\n/** A snapshot of a plain-data input record: frozen, null-prototype, dates as ISO strings. */\nexport type Snapshot = WebhookJsonObject;\n\n/** Snapshot a plain-data record argument. */\nexport function snapshotRecord(value: unknown, field: string): Snapshot {\n\tconst copy = snapshotJson(value, field, inputFail);\n\tif (copy === null || typeof copy !== \"object\" || isArray(copy)) throw storeError(\"input_invalid\", field);\n\treturn copy as Snapshot;\n}\n\n/** A nested record of a snapshot. */\nexport function nestedRecord(record: Snapshot, key: string, field: string): Snapshot {\n\tconst value = own(record, key);\n\tif (value === null || typeof value !== \"object\" || isArray(value)) throw storeError(\"input_invalid\", field);\n\treturn value as Snapshot;\n}\n\nfunction own(record: Snapshot, key: string): WebhookJsonValue | undefined {\n\treturn readOwn(record, key, key, inputFail) as WebhookJsonValue | undefined;\n}\n\n/** A non-empty string field. */\nexport function text(record: Snapshot, key: string, field: string): string {\n\tconst value = own(record, key);\n\tif (typeof value !== \"string\" || value.length === 0) throw storeError(\"input_invalid\", field);\n\treturn value;\n}\n\n/** The longest identifier a store accepts (tenant, space, subscription, event, delivery, worker and actor ids). */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** C0 controls, DEL and C1 controls. */\nconst CONTROL_CHARACTER = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/**\n * A UTF-16 surrogate that is not half of a pair. Without the `u` flag the\n * pattern works on code units, which is what it has to inspect.\n */\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\n\n/**\n * An identifier field: a non-empty string of at most\n * {@link MAX_IDENTIFIER_LENGTH} UTF-16 code units with no control\n * characters and no lone surrogates. Both stores read identifiers through\n * this function, so an identifier one store accepts the other accepts too.\n * No identifier contains the NUL a text key might be tempted to use as a\n * separator. Lone surrogates are refused because they have no UTF-8 form: a\n * PostgreSQL driver encodes each one as U+FFFD, so `\"t\\ud800\"` and\n * `\"t\\udc00\"` would be stored as the same tenant (`tests/postgres-live.test.ts`\n * shows the driver doing that).\n */\nexport function identifier(record: Snapshot, key: string, field: string): string {\n\tconst value = text(record, key, field);\n\tif (!isWebhookIdentifier(value)) throw storeError(\"input_invalid\", field);\n\treturn value;\n}\n\n/**\n * The identifier rule of {@link identifier} as a predicate: a non-empty\n * string of at most {@link MAX_IDENTIFIER_LENGTH} UTF-16 code units with no\n * control character and no lone surrogate. The governed actions' parameter\n * readers (src/action-parameters.ts) use it, so an id an action accepts is\n * one every store accepts.\n */\nexport function isWebhookIdentifier(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH &&\n\t\t!matches(CONTROL_CHARACTER, value) && !matches(LONE_SURROGATE, value);\n}\n\n/** An optional identifier field. */\nexport function optionalIdentifier(record: Snapshot, key: string, field: string): string | undefined {\n\treturn own(record, key) === undefined ? undefined : identifier(record, key, field);\n}\n\n/**\n * A collision-free key for a tuple of strings: the tuple's JSON encoding.\n * Distinct tuples always encode differently, whatever characters the parts\n * hold, because JSON quotes and escapes each part.\n */\nexport function compositeKey(...parts: readonly string[]): string {\n\treturn serializeJson(parts);\n}\n\n/**\n * A fresh frozen deep copy of a value the store built from snapshots:\n * null-prototype objects, arrays and primitives. It has no depth or size\n * limit, so a record the store accepted can always be copied out; the\n * input snapshot already bounded it.\n */\nexport function cloneOut<T>(value: unknown): T {\n\treturn copyTree(value) as T;\n}\n\nfunction copyTree(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (isArray(value)) {\n\t\tconst list: unknown[] = [];\n\t\tfor (let index = 0; index < value.length; index += 1) list[index] = copyTree(value[index]);\n\t\treturn freeze(list);\n\t}\n\tconst out = Object.create(null) as Record<string, unknown>;\n\tconst keys = Object.keys(value);\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index]!;\n\t\tconst item = (value as Record<string, unknown>)[key];\n\t\tif (item !== undefined) out[key] = copyTree(item);\n\t}\n\treturn freeze(out);\n}\n\n/** An optional non-empty string field. */\nexport function optionalText(record: Snapshot, key: string, field: string): string | undefined {\n\treturn own(record, key) === undefined ? undefined : text(record, key, field);\n}\n\n/** A safe integer field at least `min`. */\nexport function wholeNumber(record: Snapshot, key: string, field: string, min: number): number {\n\tconst value = own(record, key);\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < min) throw storeError(\"input_invalid\", field);\n\treturn value;\n}\n\n/** An optional safe integer field at least `min`. */\nexport function optionalWholeNumber(record: Snapshot, key: string, field: string, min: number): number | undefined {\n\treturn own(record, key) === undefined ? undefined : wholeNumber(record, key, field, min);\n}\n\n/** A boolean field. */\nexport function flag(record: Snapshot, key: string, field: string): boolean {\n\tconst value = own(record, key);\n\tif (typeof value !== \"boolean\") throw storeError(\"input_invalid\", field);\n\treturn value;\n}\n\n/** A timestamp field (a `Date` or a date string in the input), as epoch milliseconds. */\nexport function instant(record: Snapshot, key: string, field: string): number {\n\tconst value = own(record, key);\n\tconst iso = typeof value === \"string\" ? isoFromDateOrString(value) : undefined;\n\tif (iso === undefined) throw storeError(\"input_invalid\", field);\n\treturn dateParse(iso);\n}\n\n/** A field that must be one of the frozen package `codes`. */\nexport function codeOf<T extends string>(record: Snapshot, key: string, codes: readonly T[], field: string): T {\n\tconst value = own(record, key);\n\tif (!isOneOf(codes, value)) throw storeError(\"input_invalid\", field);\n\treturn value as T;\n}\n\n/** A non-empty list of non-empty strings, at most 1,024 long (the snapshot's list bound applies to JSON arrays too). */\nexport function textList(record: Snapshot, key: string, field: string): readonly string[] {\n\tconst value = own(record, key);\n\tif (!isArray(value) || value.length === 0 || value.length > 1_024) throw storeError(\"input_invalid\", field);\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst item = value[index];\n\t\tif (typeof item !== \"string\" || item.length === 0) throw storeError(\"input_invalid\", `${field}[${index}]`);\n\t}\n\treturn value as readonly string[];\n}\n\n/** The largest epoch-millisecond value a `Date` holds. */\nexport const MAX_TIME_MS = 8_640_000_000_000_000;\n\n/** The ISO-8601 form of epoch milliseconds. */\nexport function isoOf(ms: number): string {\n\tconst iso = isoDate(new DateConstructor(ms));\n\tif (iso === undefined) throw storeError(\"store_failed\", \"time\");\n\treturn iso;\n}\n\n// ---------------------------------------------------------------------------\n// Call options\n// ---------------------------------------------------------------------------\n\nconst abortedDescriptor = typeof AbortSignal === \"function\" ? Reflect.getOwnPropertyDescriptor(AbortSignal.prototype, \"aborted\") : undefined;\nconst abortedGetter = abortedDescriptor?.get;\n\n/** The parts of {@link WebhookCallOptions} a store checks when it reaches its write. */\nexport interface CallBounds {\n\treadonly deadlineMs: number;\n\treadonly signal: object;\n}\n\nfunction isAborted(signal: object): boolean {\n\tif (abortedGetter === undefined) throw storeError(\"input_invalid\", \"options.signal\");\n\t// The intrinsic getter reads the signal's internal slot; it throws for\n\t// anything that is not a real AbortSignal and runs none of its code.\n\treturn apply(abortedGetter, signal, []) === true;\n}\n\n/** Read `{ deadline, signal }` at entry. The signal must be a real `AbortSignal`. */\nexport function readCallOptions(options: unknown): CallBounds {\n\tif (options === null || typeof options !== \"object\") throw storeError(\"input_invalid\", \"options\");\n\tconst deadline = readOwn(options, \"deadline\", \"options.deadline\", inputFail);\n\tconst deadlineMs = timeOf(deadline);\n\tif (!(deadlineMs === deadlineMs) || deadlineMs === Infinity || deadlineMs === -Infinity) throw storeError(\"input_invalid\", \"options.deadline\");\n\tconst signal = readOwn(options, \"signal\", \"options.signal\", inputFail);\n\tif (signal === null || typeof signal !== \"object\") throw storeError(\"input_invalid\", \"options.signal\");\n\ttry {\n\t\tisAborted(signal);\n\t} catch {\n\t\tthrow storeError(\"input_invalid\", \"options.signal\");\n\t}\n\treturn { deadlineMs, signal };\n}\n\n/**\n * Refuse a call that is no longer wanted at the moment the store would\n * write: its signal aborted, or its deadline is not after the store's\n * `nowMs`. Nothing has been written when this throws.\n */\nexport function assertCallWanted(bounds: CallBounds, nowMs: number): void {\n\tif (isAborted(bounds.signal)) throw storeError(\"call_aborted\", \"options.signal\");\n\tif (!(bounds.deadlineMs > nowMs)) throw storeError(\"deadline_passed\", \"options.deadline\");\n}\n\n// ---------------------------------------------------------------------------\n// Clock\n// ---------------------------------------------------------------------------\n\n/** A clock captured at construction: the object and its `now` function. */\nexport interface CapturedClock {\n\treadonly target: object;\n\treadonly now: (...args: never[]) => unknown;\n}\n\n/** Capture an injected {@link WebhookClock} at construction. */\nexport function captureClock(clock: WebhookClock | undefined): CapturedClock {\n\tif (clock === null || typeof clock !== \"object\") throw storeError(\"clock_invalid\", \"clock\");\n\tconst now = (clock as { now?: unknown }).now;\n\tif (typeof now !== \"function\") throw storeError(\"clock_invalid\", \"clock.now\");\n\treturn { target: clock, now: now as (...args: never[]) => unknown };\n}\n\n/** Read the store's clock as epoch milliseconds; a throw or an invalid `Date` is `clock_invalid`. */\nexport function readClock(clock: CapturedClock): number {\n\tlet value: unknown;\n\ttry {\n\t\tvalue = apply(clock.now, clock.target, []);\n\t} catch {\n\t\tthrow storeError(\"clock_invalid\", \"clock.now\");\n\t}\n\tconst ms = timeOf(value);\n\tif (!(ms === ms) || ms === Infinity || ms === -Infinity) throw storeError(\"clock_invalid\", \"clock.now\");\n\treturn ms;\n}\n","import {\n\tWEBHOOK_ADMISSION_DENIAL_CODES,\n\tWEBHOOK_ATTEMPT_OUTCOMES,\n\tWEBHOOK_ATTEMPT_REASON_CODES,\n\tWEBHOOK_DIAGNOSTIC_CODES,\n\ttype WebhookAdmissionDenialCode,\n\ttype WebhookAttemptOutcome,\n\ttype WebhookAttemptReasonCode,\n\ttype WebhookDiagnosticCode,\n} from \"./codes\";\nimport { configError, guard, storeError } from \"./errors\";\nimport { assertReplayHorizon, WEBHOOK_MAX_REPLAY_HORIZON_MS } from \"./limits\";\nimport type {\n\tWebhookAttemptBeginResult,\n\tWebhookDeliveryLeaseCheck,\n\tWebhookFanOutJobFence,\n\tWebhookActorEnrichmentResult,\n\tWebhookFencedInsertResult,\n\tWebhookRequeueResult,\n} from \"./ports\";\nimport { mathMin, primitive, readOwn } from \"./snapshot\";\nimport {\n\tcloneOut,\n\tcodeOf,\n\tcompositeKey,\n\tflag,\n\tidentifier,\n\tinstant,\n\tisoOf,\n\tMAX_TIME_MS,\n\tnestedRecord,\n\toptionalIdentifier,\n\toptionalWholeNumber,\n\treadCallOptions,\n\tsnapshotRecord,\n\ttext,\n\twholeNumber,\n\ttype CallBounds,\n\ttype Snapshot,\n} from \"./store-input\";\nimport type {\n\tWebhookDeliveryIntentStatus,\n\tWebhookFanOutJobStatus,\n\tWebhookRequeueEvidence,\n} from \"./types\";\n\n/*\n * What the memory and PostgreSQL delivery stores share: the readers that\n * copy and validate each method's arguments at entry, the in-memory shape of\n * a job and an intent, and the functions that render records, requeue\n * evidence and settlements from that shape. Both stores call these, so the\n * input they accept, the identifier fields they validate and the records\n * they return cannot drift apart (README, \"Stores\"). Internal: not exported\n * from the package entry point.\n */\n\nexport interface LeaseState {\n\treadonly owner: string;\n\treadonly fence: number;\n\treadonly expiresAtMs: number;\n}\n\nexport interface Leased {\n\treadonly key: string;\n\tstatus: string;\n\tavailableAtMs: number;\n\treadonly createdAtMs: number;\n\tfence: number;\n\tlease: LeaseState | undefined;\n}\n\nexport interface JobState extends Leased {\n\t/** Replaced, never mutated, by an actor enrichment; otherwise as inserted. */\n\tdraft: Snapshot;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly anchorMs: number;\n\tstatus: WebhookFanOutJobStatus;\n\tattemptCount: number;\n\tprocessingDeadlineMs: number;\n\tcompletedAtMs: number | undefined;\n\tlastDiagnostic: WebhookDiagnosticCode | undefined;\n}\n\nexport interface IntentState extends Leased {\n\treadonly subscriptionId: string;\n\treadonly eventId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly eligibilityRevision: number;\n\treadonly body: string;\n\treadonly anchorMs: number;\n\tstatus: WebhookDeliveryIntentStatus;\n\tattemptCount: number;\n\tprocessingDeadlineMs: number;\n\tlastOutcome: { readonly outcome: WebhookAttemptOutcome; readonly reason: WebhookAttemptReasonCode } | undefined;\n\tlastDiagnostic: WebhookDiagnosticCode | undefined;\n}\n\n/** The uniqueness marker for one (subscriptionId, eventId): the tombstone. */\nexport interface MarkerState {\n\treadonly kind: \"intent\" | \"denial\";\n\treadonly subscriptionId: string;\n\treadonly eventId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly anchorMs: number;\n}\n\nexport const TERMINAL_JOB: readonly string[] = Object.freeze([\"completed\", \"dead_letter\"]);\nexport const TERMINAL_INTENT: readonly string[] = Object.freeze([\"delivered\", \"dead_letter\", \"cancelled\"]);\nconst SETTLEMENT_KINDS = Object.freeze([\"delivered\", \"retry\", \"release\", \"dead_letter\", \"cancelled\"] as const);\nconst CANCEL_REASONS = Object.freeze([\"subscription_paused\", \"subscription_deleted\"] as const);\nconst DEAD_LETTER_REASONS: readonly string[] = Object.freeze([...WEBHOOK_ATTEMPT_REASON_CODES, ...WEBHOOK_DIAGNOSTIC_CODES]);\nconst EXPECTED_STATUS = Object.freeze([\"dead_letter\"] as const);\n\n/**\n * A fresh, frozen, null-prototype deep copy of a value the store built. It\n * has no depth or size limit, so every record the store accepted can be\n * returned (`cloneOut` in src/store-input.ts).\n */\nexport function copyOut<T>(value: object): T {\n\treturn cloneOut<T>(value);\n}\n\n/** The key of one (subscriptionId, eventId) pair; JSON-encoded, so distinct pairs never collide. */\nexport function markerKey(subscriptionId: string, eventId: string): string {\n\treturn compositeKey(subscriptionId, eventId);\n}\n\nexport interface Scope {\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n}\n\nexport function inScope(record: { readonly tenantId: string; readonly spaceId: string }, scope: Scope): boolean {\n\treturn record.tenantId === scope.tenantId && record.spaceId === scope.spaceId;\n}\n\n/**\n * `true` when `owner` holds the record's lease at `fence`, ignoring expiry. A\n * lease's fence is always the record's fence. Only for a decision made\n * before the store's clock is read (the PostgreSQL lock phase's tentative\n * inserts); the decision itself is {@link holds}.\n */\nexport function holdsFence(state: Leased, owner: string, fence: number): boolean {\n\treturn state.status === \"pending\" && state.lease !== undefined && state.lease.owner === owner && state.lease.fence === fence;\n}\n\n/**\n * `true` when `owner` holds the record's lease at `fence` and the lease has\n * not expired at `storeNowMs`, the store's own clock read inside the atomic\n * step (memory) or after every lock is held (PostgreSQL). Every fenced write\n * decides with it, so a write after the lease expired is refused even when\n * no other worker has reclaimed the record yet.\n */\nexport function holds(state: Leased, owner: string, fence: number, storeNowMs: number): boolean {\n\treturn holdsFence(state, owner, fence) && state.lease!.expiresAtMs > storeNowMs;\n}\n\n/** UTF-16 code unit order, as JavaScript's `<` compares strings. */\nexport function compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\n/** Entry: snapshot the arguments. Anything not package-made becomes `input_invalid`. */\nfunction entry<T>(read: () => T): T {\n\treturn guard(read, () => storeError(\"input_invalid\", \"input\"));\n}\n\n/**\n * Read a store's `replayHorizonMs` option, as the constructor of either\n * store does: an own data property, never a getter, validated by\n * `assertReplayHorizon`.\n */\nexport function readHorizonOption(options: unknown): number {\n\treturn guard(\n\t\t() => {\n\t\t\tif (options === null || typeof options !== \"object\") throw configError(\"limit_unreadable\", \"options\");\n\t\t\tconst value = primitive(readOwn(options, \"replayHorizonMs\", \"replayHorizonMs\", () => {\n\t\t\t\tthrow configError(\"limit_unreadable\", \"replayHorizonMs\");\n\t\t\t}));\n\t\t\tassertReplayHorizon(value, \"replayHorizonMs\");\n\t\t\treturn value;\n\t\t},\n\t\t() => configError(\"limit_unreadable\", \"replayHorizonMs\"),\n\t);\n}\n\n/** Read an optional test-seam function option; anything else is `input_invalid`. */\nexport function readHookOption<T extends (...args: never[]) => unknown>(options: unknown, key: string): T | undefined {\n\treturn guard(() => {\n\t\tconst hook = (options as Record<string, unknown>)[key];\n\t\tif (hook !== undefined && typeof hook !== \"function\") throw storeError(\"input_invalid\", key);\n\t\treturn hook as T | undefined;\n\t}, () => storeError(\"input_invalid\", key));\n}\n\nfunction readScope(input: Snapshot, field: string): Scope {\n\treturn { tenantId: identifier(input, \"tenantId\", `${field}.tenantId`), spaceId: identifier(input, \"spaceId\", `${field}.spaceId`) };\n}\n\nexport interface FencedInput {\n\treadonly owner: string;\n\treadonly fence: number;\n\treadonly nowMs: number;\n}\n\nfunction readFenced(input: Snapshot): FencedInput {\n\treturn { owner: identifier(input, \"owner\", \"input.owner\"), fence: wholeNumber(input, \"fence\", \"input.fence\", 0), nowMs: instant(input, \"now\", \"input.now\") };\n}\n\nexport interface ClaimInput {\n\treadonly workerId: string;\n\treadonly leaseDurationMs: number;\n\treadonly limit: number;\n\treadonly nowMs: number;\n}\n\nfunction readClaim(request: unknown): ClaimInput {\n\tconst input = snapshotRecord(request, \"request\");\n\tconst claim: ClaimInput = {\n\t\tworkerId: identifier(input, \"workerId\", \"request.workerId\"),\n\t\tleaseDurationMs: wholeNumber(input, \"leaseDurationMs\", \"request.leaseDurationMs\", 1),\n\t\tlimit: wholeNumber(input, \"limit\", \"request.limit\", 1),\n\t\tnowMs: instant(input, \"now\", \"request.now\"),\n\t};\n\t// The lease expiry must be a representable time, checked before anything is leased.\n\tif (claim.nowMs + claim.leaseDurationMs > MAX_TIME_MS) throw storeError(\"input_invalid\", \"request.leaseDurationMs\");\n\treturn claim;\n}\n\nexport interface RequeueInput {\n\treadonly expectedFence: number;\n\treadonly requestedBy: string;\n\treadonly requestedAtMs: number;\n\treadonly processingDeadlineMs: number;\n\treadonly actionInvocationId: string | undefined;\n}\n\nfunction readRequeueRequest(input: Snapshot): RequeueInput {\n\tconst request = nestedRecord(input, \"request\", \"input.request\");\n\tcodeOf(request, \"expectedStatus\", EXPECTED_STATUS, \"input.request.expectedStatus\");\n\treturn {\n\t\texpectedFence: wholeNumber(request, \"expectedFence\", \"input.request.expectedFence\", 0),\n\t\trequestedBy: identifier(request, \"requestedBy\", \"input.request.requestedBy\"),\n\t\trequestedAtMs: instant(request, \"requestedAt\", \"input.request.requestedAt\"),\n\t\tprocessingDeadlineMs: instant(request, \"processingDeadline\", \"input.request.processingDeadline\"),\n\t\tactionInvocationId: optionalIdentifier(request, \"actionInvocationId\", \"input.request.actionInvocationId\"),\n\t};\n}\n\nfunction readParent(parent: unknown): WebhookFanOutJobFence {\n\tconst input = snapshotRecord(parent, \"parent\");\n\treturn { eventId: identifier(input, \"eventId\", \"parent.eventId\"), owner: identifier(input, \"owner\", \"parent.owner\"), fence: wholeNumber(input, \"fence\", \"parent.fence\", 0) };\n}\n\n// ---------------------------------------------------------------------------\n// Per-method entry readers. Each copies and validates every argument, the\n// call options included, and refuses malformed input as `input_invalid`\n// before the store does anything else.\n// ---------------------------------------------------------------------------\n\nexport function readInsertFanOutJobCall(job: unknown, options: unknown) {\n\treturn entry(() => ({ bounds: readCallOptions(options), job: readJobDraft(job) }));\n}\n\nexport function readClaimCall(request: unknown, options: unknown) {\n\treturn entry(() => ({ bounds: readCallOptions(options), claim: readClaim(request) }));\n}\n\nexport function readJobFencedCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), fenced: readFenced(snap), eventId: identifier(snap, \"eventId\", \"input.eventId\") };\n\t});\n}\n\nexport function readRescheduleCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tfenced: readFenced(snap),\n\t\t\teventId: identifier(snap, \"eventId\", \"input.eventId\"),\n\t\t\tavailableAtMs: instant(snap, \"availableAt\", \"input.availableAt\"),\n\t\t\tdiagnostic: codeOf(snap, \"diagnostic\", WEBHOOK_DIAGNOSTIC_CODES, \"input.diagnostic\"),\n\t\t};\n\t});\n}\n\n/** The lease duration a renewal asks for: a whole number of ms whose expiry from `now` is a representable time. */\nfunction readRenewal(snap: Snapshot, fenced: FencedInput): number {\n\tconst leaseDurationMs = wholeNumber(snap, \"leaseDurationMs\", \"input.leaseDurationMs\", 1);\n\tif (fenced.nowMs + leaseDurationMs > MAX_TIME_MS) throw storeError(\"input_invalid\", \"input.leaseDurationMs\");\n\treturn leaseDurationMs;\n}\n\nexport function readRenewJobCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst fenced = readFenced(snap);\n\t\treturn { bounds: readCallOptions(options), fenced, eventId: identifier(snap, \"eventId\", \"input.eventId\"), leaseDurationMs: readRenewal(snap, fenced) };\n\t});\n}\n\nexport function readRenewIntentCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst fenced = readFenced(snap);\n\t\treturn { bounds: readCallOptions(options), fenced, deliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"), leaseDurationMs: readRenewal(snap, fenced) };\n\t});\n}\n\n/**\n * The expiry a renewal sets on a lease the caller holds: the later of the\n * current expiry and the earlier of `nowMs + leaseDurationMs` (the caller's\n * `now`, as a claim uses it) and the record's processing deadline. So a\n * renewal never shortens a lease and never extends one past the deadline.\n * Whether the caller holds the lease is decided by {@link holds} first.\n */\nexport function renewedExpiryMs(state: Leased & { readonly processingDeadlineMs: number }, nowMs: number, leaseDurationMs: number): number {\n\tconst asked = mathMin(nowMs + leaseDurationMs, state.processingDeadlineMs);\n\tconst current = state.lease!.expiresAtMs;\n\treturn asked > current ? asked : current;\n}\n\nexport function readDeadLetterJobCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tfenced: readFenced(snap),\n\t\t\teventId: identifier(snap, \"eventId\", \"input.eventId\"),\n\t\t\tdiagnostic: codeOf(snap, \"diagnostic\", WEBHOOK_DIAGNOSTIC_CODES, \"input.diagnostic\"),\n\t\t};\n\t});\n}\n\nexport interface EnrichmentInput extends RequeueInput {\n\treadonly actorId: string;\n\treadonly actorType: string;\n}\n\n/** `enrichFanOutJobActor`: a scope, an `eventId` and the request, with the actor read field by field. */\nexport function readJobEnrichmentCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst request = nestedRecord(snap, \"request\", \"input.request\");\n\t\tconst actor = nestedRecord(request, \"actor\", \"input.request.actor\");\n\t\tconst read: EnrichmentInput = {\n\t\t\texpectedFence: wholeNumber(request, \"expectedFence\", \"input.request.expectedFence\", 0),\n\t\t\trequestedBy: identifier(request, \"requestedBy\", \"input.request.requestedBy\"),\n\t\t\trequestedAtMs: instant(request, \"requestedAt\", \"input.request.requestedAt\"),\n\t\t\tprocessingDeadlineMs: instant(request, \"processingDeadline\", \"input.request.processingDeadline\"),\n\t\t\tactionInvocationId: optionalIdentifier(request, \"actionInvocationId\", \"input.request.actionInvocationId\"),\n\t\t\tactorId: identifier(actor, \"actorId\", \"input.request.actor.actorId\"),\n\t\t\tactorType: identifier(actor, \"actorType\", \"input.request.actor.actorType\"),\n\t\t};\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), eventId: identifier(snap, \"eventId\", \"input.eventId\"), request: read };\n\t});\n}\n\nexport function readJobRequeueCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), eventId: identifier(snap, \"eventId\", \"input.eventId\"), request: readRequeueRequest(snap) };\n\t});\n}\n\n/** `readFanOutJob` and `listRequeueEvidence`: a scope and an `eventId`. */\nexport function readEventCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), eventId: identifier(snap, \"eventId\", \"input.eventId\") };\n\t});\n}\n\nexport function readInsertIntentCall(intent: unknown, parent: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(intent, \"intent\");\n\t\tconst fence = readParent(parent);\n\t\tconst read = {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tparent: fence,\n\t\t\tdeliveryId: identifier(snap, \"deliveryId\", \"intent.deliveryId\"),\n\t\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"intent.subscriptionId\"),\n\t\t\teventId: identifier(snap, \"eventId\", \"intent.eventId\"),\n\t\t\ttenantId: identifier(snap, \"tenantId\", \"intent.tenantId\"),\n\t\t\tspaceId: identifier(snap, \"spaceId\", \"intent.spaceId\"),\n\t\t\teligibilityRevision: wholeNumber(snap, \"eligibilityRevision\", \"intent.eligibilityRevision\", 1),\n\t\t\tbody: text(snap, \"body\", \"intent.body\"),\n\t\t\tavailableAtMs: instant(snap, \"availableAt\", \"intent.availableAt\"),\n\t\t\tprocessingDeadlineMs: instant(snap, \"processingDeadline\", \"intent.processingDeadline\"),\n\t\t\tcreatedAtMs: instant(snap, \"createdAt\", \"intent.createdAt\"),\n\t\t};\n\t\tif (read.eventId !== fence.eventId) throw storeError(\"record_mismatch\", \"intent.eventId\");\n\t\treturn read;\n\t});\n}\n\nexport function readDenialCall(record: unknown, parent: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(record, \"record\");\n\t\tconst fence = readParent(parent);\n\t\tconst read = {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tparent: fence,\n\t\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"record.subscriptionId\"),\n\t\t\teventId: identifier(snap, \"eventId\", \"record.eventId\"),\n\t\t\ttenantId: identifier(snap, \"tenantId\", \"record.tenantId\"),\n\t\t\tspaceId: identifier(snap, \"spaceId\", \"record.spaceId\"),\n\t\t\teligibilityRevision: wholeNumber(snap, \"eligibilityRevision\", \"record.eligibilityRevision\", 1),\n\t\t\tcode: codeOf<WebhookAdmissionDenialCode>(snap, \"code\", WEBHOOK_ADMISSION_DENIAL_CODES, \"record.code\"),\n\t\t\trecordedAtMs: instant(snap, \"recordedAt\", \"record.recordedAt\"),\n\t\t};\n\t\tif (read.eventId !== fence.eventId) throw storeError(\"record_mismatch\", \"record.eventId\");\n\t\treturn read;\n\t});\n}\n\n/** The denial record a store keeps, built from a validated call. */\nexport function denialRecord(call: ReturnType<typeof readDenialCall>): Snapshot {\n\treturn copyOut<Snapshot>({\n\t\tsubscriptionId: call.subscriptionId,\n\t\teventId: call.eventId,\n\t\ttenantId: call.tenantId,\n\t\tspaceId: call.spaceId,\n\t\teligibilityRevision: call.eligibilityRevision,\n\t\tcode: call.code,\n\t\trecordedAt: isoOf(call.recordedAtMs),\n\t});\n}\n\nexport function readLeaseCheckCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tscope: readScope(snap, \"input\"),\n\t\t\tdeliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"),\n\t\t\tfenced: readFenced(snap),\n\t\t};\n\t});\n}\n\nexport function readAppendAttemptCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst attempt = nestedRecord(snap, \"attempt\", \"input.attempt\");\n\t\tconst httpStatus = optionalWholeNumber(attempt, \"httpStatus\", \"input.attempt.httpStatus\", 100);\n\t\tif (httpStatus !== undefined && httpStatus > 599) throw storeError(\"input_invalid\", \"input.attempt.httpStatus\");\n\t\tconst record = copyOut<Snapshot>({\n\t\t\tdeliveryId: identifier(attempt, \"deliveryId\", \"input.attempt.deliveryId\"),\n\t\t\tsubscriptionId: identifier(attempt, \"subscriptionId\", \"input.attempt.subscriptionId\"),\n\t\t\teventId: identifier(attempt, \"eventId\", \"input.attempt.eventId\"),\n\t\t\tattempt: wholeNumber(attempt, \"attempt\", \"input.attempt.attempt\", 1),\n\t\t\tconfigurationVersion: wholeNumber(attempt, \"configurationVersion\", \"input.attempt.configurationVersion\", 1),\n\t\t\tstartedAt: isoOf(instant(attempt, \"startedAt\", \"input.attempt.startedAt\")),\n\t\t\tfinishedAt: isoOf(instant(attempt, \"finishedAt\", \"input.attempt.finishedAt\")),\n\t\t\toutcome: codeOf(attempt, \"outcome\", WEBHOOK_ATTEMPT_OUTCOMES, \"input.attempt.outcome\"),\n\t\t\treason: codeOf(attempt, \"reason\", WEBHOOK_ATTEMPT_REASON_CODES, \"input.attempt.reason\"),\n\t\t\thttpStatus,\n\t\t});\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tfenced: readFenced(snap),\n\t\t\trecord,\n\t\t\tdeliveryId: record[\"deliveryId\"] as string,\n\t\t\tsubscriptionId: record[\"subscriptionId\"] as string,\n\t\t\teventId: record[\"eventId\"] as string,\n\t\t};\n\t});\n}\n\n/**\n * `beginAttempt`: the fence, and the start of the attempt. The record kept\n * holds only the `WebhookDeliveryAttemptStart` fields, read one by one.\n */\nexport function readBeginAttemptCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst attempt = nestedRecord(snap, \"attempt\", \"input.attempt\");\n\t\tconst record = copyOut<Snapshot>({\n\t\t\tdeliveryId: identifier(attempt, \"deliveryId\", \"input.attempt.deliveryId\"),\n\t\t\tsubscriptionId: identifier(attempt, \"subscriptionId\", \"input.attempt.subscriptionId\"),\n\t\t\teventId: identifier(attempt, \"eventId\", \"input.attempt.eventId\"),\n\t\t\tattempt: wholeNumber(attempt, \"attempt\", \"input.attempt.attempt\", 1),\n\t\t\tconfigurationVersion: wholeNumber(attempt, \"configurationVersion\", \"input.attempt.configurationVersion\", 1),\n\t\t\tstartedAt: isoOf(instant(attempt, \"startedAt\", \"input.attempt.startedAt\")),\n\t\t});\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tfenced: readFenced(snap),\n\t\t\trecord,\n\t\t\tdeliveryId: record[\"deliveryId\"] as string,\n\t\t\tsubscriptionId: record[\"subscriptionId\"] as string,\n\t\t\teventId: record[\"eventId\"] as string,\n\t\t};\n\t});\n}\n\n/** `finishAttempt`: a scope, the begun attempt's key, and its outcome. */\nexport function readFinishAttemptCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst finish = nestedRecord(snap, \"finish\", \"input.finish\");\n\t\tconst httpStatus = optionalWholeNumber(finish, \"httpStatus\", \"input.finish.httpStatus\", 100);\n\t\tif (httpStatus !== undefined && httpStatus > 599) throw storeError(\"input_invalid\", \"input.finish.httpStatus\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tscope: readScope(snap, \"input\"),\n\t\t\tdeliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"),\n\t\t\tfence: wholeNumber(snap, \"fence\", \"input.fence\", 0),\n\t\t\t// Read like an identifier; an error names the field, never the value.\n\t\t\treceipt: identifier(snap, \"receipt\", \"input.receipt\"),\n\t\t\trecord: copyOut<Snapshot>({\n\t\t\t\tfinishedAt: isoOf(instant(finish, \"finishedAt\", \"input.finish.finishedAt\")),\n\t\t\t\toutcome: codeOf(finish, \"outcome\", WEBHOOK_ATTEMPT_OUTCOMES, \"input.finish.outcome\"),\n\t\t\t\treason: codeOf(finish, \"reason\", WEBHOOK_ATTEMPT_REASON_CODES, \"input.finish.reason\"),\n\t\t\t\thttpStatus,\n\t\t\t}),\n\t\t};\n\t});\n}\n\n/** The key of the attempt begun under one lease of one intent. */\nexport function attemptKey(deliveryId: string, fence: number): string {\n\treturn compositeKey(deliveryId, `${fence}`);\n}\n\n/**\n * Whether `beginAttempt` may record an attempt on `intent`: pending, leased\n * to the caller at its fence, and the lease not expired at the store's\n * clock read in the atomic step.\n */\nexport function mayBegin(intent: IntentState | undefined, fenced: FencedInput, storeNowMs: number): intent is IntentState {\n\treturn intent !== undefined && holds(intent, fenced.owner, fenced.fence, storeNowMs);\n}\n\n/**\n * One attempt log entry as `listDeliveryAttempts` returns it. `fence` is\n * `undefined` for an entry appended whole; otherwise the entry was begun\n * under that fence and `finish` is its outcome, or `undefined` while none is\n * recorded.\n */\nexport function attemptEntryOut(start: Snapshot, fence: number | undefined, finish: Snapshot | undefined): object {\n\tif (fence === undefined) return start;\n\tif (finish === undefined) return { ...start, fence, outcome: \"in_flight\" };\n\treturn { ...start, ...finish, fence };\n}\n\nexport function beginResult(receipt: string | undefined): WebhookAttemptBeginResult {\n\treturn copyOut<WebhookAttemptBeginResult>(receipt === undefined ? { begun: false } : { begun: true, receipt });\n}\n\nexport function readSettleCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), fenced: readFenced(snap), deliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"), settlement: readSettlement(snap) };\n\t});\n}\n\nexport function readCancelCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tinstant(snap, \"now\", \"input.now\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tscope: readScope(snap, \"input\"),\n\t\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"input.subscriptionId\"),\n\t\t\treason: codeOf(snap, \"reason\", CANCEL_REASONS, \"input.reason\"),\n\t\t\tbeforeRevision: wholeNumber(snap, \"beforeRevision\", \"input.beforeRevision\", 1),\n\t\t};\n\t});\n}\n\nexport function readIntentRequeueCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), deliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"), request: readRequeueRequest(snap) };\n\t});\n}\n\n/** `readDeliveryIntent` and `listDeliveryAttempts`: a scope and a `deliveryId`. */\nexport function readDeliveryCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), deliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\") };\n\t});\n}\n\nexport function readTombstoneCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tscope: readScope(snap, \"input\"),\n\t\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"input.subscriptionId\"),\n\t\t\teventId: identifier(snap, \"eventId\", \"input.eventId\"),\n\t\t};\n\t});\n}\n\nexport function readPurgeCall(input: unknown, options: unknown): { readonly bounds: CallBounds; readonly limit: number } {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), limit: wholeNumber(snap, \"limit\", \"input.limit\", 1) };\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Job drafts\n// ---------------------------------------------------------------------------\n\nexport interface JobDraftInput {\n\treadonly draft: Snapshot;\n\treadonly eventId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly anchorMs: number;\n\treadonly createdAtMs: number;\n\treadonly processingDeadlineMs: number;\n}\n\nconst ACTOR_STATES = Object.freeze([\"present\", \"absent\"] as const);\n\nconst PAYLOAD_CLASSIFICATIONS = Object.freeze([\"public\", \"internal\", \"confidential\", \"restricted\"] as const);\nconst CONSISTENCIES = Object.freeze([\"authoritative-now\", \"provisional-until-reconciled\"] as const);\nconst ABSENT_REASONS = Object.freeze([\"suppressed\", \"legacy\"] as const);\nconst ANY_INTEGER = Number.MIN_SAFE_INTEGER;\n\n/**\n * Rebuild the event metadata from an explicit allowlist of\n * `WebhookEventMetadata` fields (R7). Nothing else on the caller's object,\n * such as a payload, trace context, provenance or a secret, is copied.\n */\nfunction readEventMetadata(event: Snapshot): object {\n\tconst consistency = event[\"consistency\"] === undefined ? undefined : codeOf(event, \"consistency\", CONSISTENCIES, \"job.event.consistency\");\n\treturn {\n\t\teventId: identifier(event, \"eventId\", \"job.event.eventId\"),\n\t\teventType: identifier(event, \"eventType\", \"job.event.eventType\"),\n\t\teventSchemaVersion: wholeNumber(event, \"eventSchemaVersion\", \"job.event.eventSchemaVersion\", ANY_INTEGER),\n\t\ttenantId: identifier(event, \"tenantId\", \"job.event.tenantId\"),\n\t\tspaceId: identifier(event, \"spaceId\", \"job.event.spaceId\"),\n\t\tsubjectType: identifier(event, \"subjectType\", \"job.event.subjectType\"),\n\t\tsubjectId: identifier(event, \"subjectId\", \"job.event.subjectId\"),\n\t\tsequence: wholeNumber(event, \"sequence\", \"job.event.sequence\", ANY_INTEGER),\n\t\tactionInvocationId: optionalIdentifier(event, \"actionInvocationId\", \"job.event.actionInvocationId\"),\n\t\tcorrelationId: identifier(event, \"correlationId\", \"job.event.correlationId\"),\n\t\tcausationId: optionalIdentifier(event, \"causationId\", \"job.event.causationId\"),\n\t\toccurredAt: isoOf(instant(event, \"occurredAt\", \"job.event.occurredAt\")),\n\t\trecordedAt: isoOf(instant(event, \"recordedAt\", \"job.event.recordedAt\")),\n\t\tproducerModuleVersion: identifier(event, \"producerModuleVersion\", \"job.event.producerModuleVersion\"),\n\t\tpayloadClassification: codeOf(event, \"payloadClassification\", PAYLOAD_CLASSIFICATIONS, \"job.event.payloadClassification\"),\n\t\tconsistency,\n\t};\n}\n\n/** Rebuild the job actor as one member of the `WebhookJobActor` union, nothing more. */\nfunction readActor(actor: Snapshot): object {\n\tconst state = codeOf(actor, \"state\", ACTOR_STATES, \"job.actor.state\");\n\tif (state === \"present\") {\n\t\treturn { state, actorId: identifier(actor, \"actorId\", \"job.actor.actorId\"), actorType: identifier(actor, \"actorType\", \"job.actor.actorType\") };\n\t}\n\treturn { state, reason: codeOf(actor, \"reason\", ABSENT_REASONS, \"job.actor.reason\") };\n}\n\nfunction readJobDraft(job: unknown): JobDraftInput {\n\tconst snap = snapshotRecord(job, \"job\");\n\tconst eventId = identifier(snap, \"eventId\", \"job.eventId\");\n\tconst tenantId = identifier(snap, \"tenantId\", \"job.tenantId\");\n\tconst spaceId = identifier(snap, \"spaceId\", \"job.spaceId\");\n\tconst event = nestedRecord(snap, \"event\", \"job.event\");\n\tif (identifier(event, \"eventId\", \"job.event.eventId\") !== eventId) throw storeError(\"record_mismatch\", \"job.event.eventId\");\n\tif (identifier(event, \"tenantId\", \"job.event.tenantId\") !== tenantId) throw storeError(\"record_mismatch\", \"job.event.tenantId\");\n\tif (identifier(event, \"spaceId\", \"job.event.spaceId\") !== spaceId) throw storeError(\"record_mismatch\", \"job.event.spaceId\");\n\tconst anchorMs = instant(event, \"recordedAt\", \"job.event.recordedAt\");\n\tconst payloadProjected = flag(snap, \"payloadProjected\", \"job.payloadProjected\");\n\tlet payload: Snapshot | null = null;\n\tif (payloadProjected) payload = nestedRecord(snap, \"payload\", \"job.payload\");\n\telse if (snap[\"payload\"] !== null) throw storeError(\"input_invalid\", \"job.payload\");\n\t// Only the fields WebhookFanOutJobDraft declares are kept. `payload` and\n\t// `facts` are the projection's allowlisted JSON and are kept whole.\n\tconst draft = copyOut<Snapshot>({\n\t\tevent: readEventMetadata(event),\n\t\tpayload,\n\t\tpayloadProjected,\n\t\tfacts: nestedRecord(snap, \"facts\", \"job.facts\"),\n\t\tactor: readActor(nestedRecord(snap, \"actor\", \"job.actor\")),\n\t});\n\treturn {\n\t\tdraft,\n\t\teventId,\n\t\ttenantId,\n\t\tspaceId,\n\t\tanchorMs,\n\t\tcreatedAtMs: instant(snap, \"createdAt\", \"job.createdAt\"),\n\t\tprocessingDeadlineMs: instant(snap, \"processingDeadline\", \"job.processingDeadline\"),\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Settlements\n// ---------------------------------------------------------------------------\n\nexport type Settlement =\n\t| { readonly kind: \"delivered\" }\n\t| { readonly kind: \"retry\"; readonly availableAtMs: number; readonly outcome: WebhookAttemptOutcome; readonly reason: WebhookAttemptReasonCode }\n\t| { readonly kind: \"release\"; readonly availableAtMs: number; readonly diagnostic: WebhookDiagnosticCode }\n\t| { readonly kind: \"dead_letter\"; readonly reason: WebhookAttemptReasonCode | WebhookDiagnosticCode }\n\t| { readonly kind: \"cancelled\"; readonly reason: WebhookAttemptReasonCode };\n\nfunction readSettlement(input: Snapshot): Settlement {\n\tconst settlement = nestedRecord(input, \"settlement\", \"input.settlement\");\n\tconst kind = codeOf(settlement, \"kind\", SETTLEMENT_KINDS, \"input.settlement.kind\");\n\tswitch (kind) {\n\t\tcase \"delivered\":\n\t\t\treturn { kind };\n\t\tcase \"retry\":\n\t\t\treturn {\n\t\t\t\tkind,\n\t\t\t\tavailableAtMs: instant(settlement, \"availableAt\", \"input.settlement.availableAt\"),\n\t\t\t\toutcome: codeOf(settlement, \"outcome\", WEBHOOK_ATTEMPT_OUTCOMES, \"input.settlement.outcome\"),\n\t\t\t\treason: codeOf(settlement, \"reason\", WEBHOOK_ATTEMPT_REASON_CODES, \"input.settlement.reason\"),\n\t\t\t};\n\t\tcase \"release\":\n\t\t\treturn {\n\t\t\t\tkind,\n\t\t\t\tavailableAtMs: instant(settlement, \"availableAt\", \"input.settlement.availableAt\"),\n\t\t\t\tdiagnostic: codeOf(settlement, \"diagnostic\", WEBHOOK_DIAGNOSTIC_CODES, \"input.settlement.diagnostic\"),\n\t\t\t};\n\t\tcase \"dead_letter\":\n\t\t\treturn { kind, reason: codeOf(settlement, \"reason\", DEAD_LETTER_REASONS, \"input.settlement.reason\") as WebhookAttemptReasonCode | WebhookDiagnosticCode };\n\t\tcase \"cancelled\":\n\t\t\treturn { kind, reason: codeOf(settlement, \"reason\", WEBHOOK_ATTEMPT_REASON_CODES, \"input.settlement.reason\") };\n\t}\n}\n\nfunction isAttemptReason(value: string): value is WebhookAttemptReasonCode {\n\treturn (WEBHOOK_ATTEMPT_REASON_CODES as readonly string[]).includes(value);\n}\n\n/**\n * Apply a settlement to an intent the caller holds, clearing its lease.\n * `release` spends no budget, `retry` spends one attempt, and the terminal\n * kinds leave the attempt count as it was.\n */\nexport function applySettlement(intent: IntentState, settlement: Settlement): void {\n\tswitch (settlement.kind) {\n\t\tcase \"delivered\":\n\t\t\tintent.status = \"delivered\";\n\t\t\tintent.lastOutcome = { outcome: \"delivered\", reason: \"http_2xx\" };\n\t\t\tbreak;\n\t\tcase \"retry\":\n\t\t\tintent.attemptCount += 1;\n\t\t\tintent.availableAtMs = settlement.availableAtMs;\n\t\t\tintent.lastOutcome = { outcome: settlement.outcome, reason: settlement.reason };\n\t\t\tbreak;\n\t\tcase \"release\":\n\t\t\tintent.availableAtMs = settlement.availableAtMs;\n\t\t\tintent.lastDiagnostic = settlement.diagnostic;\n\t\t\tbreak;\n\t\tcase \"dead_letter\":\n\t\t\tintent.status = \"dead_letter\";\n\t\t\tif (isAttemptReason(settlement.reason)) intent.lastOutcome = { outcome: \"dead_letter\", reason: settlement.reason };\n\t\t\telse intent.lastDiagnostic = settlement.reason;\n\t\t\tbreak;\n\t\tcase \"cancelled\":\n\t\t\tintent.status = \"cancelled\";\n\t\t\tintent.lastOutcome = { outcome: \"cancelled\", reason: settlement.reason };\n\t\t\tbreak;\n\t}\n\tintent.lease = undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Requeue\n// ---------------------------------------------------------------------------\n\n/** The first refusal a requeue meets, in the port's order, or `undefined` when it applies. */\nexport function requeueRefusal(\n\tstate: { readonly fence: number; readonly status: string; readonly anchorMs: number },\n\trequest: RequeueInput,\n\tfloorMs: number,\n): \"stale\" | \"not_dead_letter\" | \"past_horizon\" | undefined {\n\t// The dead-letter generation the operator saw, in the same step as the\n\t// transition: a second request from that read finds the advanced fence.\n\tif (state.fence !== request.expectedFence) return \"stale\";\n\tif (state.status !== \"dead_letter\") return \"not_dead_letter\";\n\tif (state.anchorMs < floorMs) return \"past_horizon\";\n\treturn undefined;\n}\n\nexport function jobRequeueEvidence(job: JobState, request: RequeueInput, nowMs: number): WebhookRequeueEvidence {\n\treturn copyOut<WebhookRequeueEvidence>({\n\t\ttarget: \"fan_out_job\",\n\t\teventId: job.key,\n\t\ttenantId: job.tenantId,\n\t\tspaceId: job.spaceId,\n\t\trequestedBy: request.requestedBy,\n\t\trequestedAt: isoOf(request.requestedAtMs),\n\t\tactionInvocationId: request.actionInvocationId,\n\t\tappliedAt: isoOf(nowMs),\n\t\tpriorAttemptCount: job.attemptCount,\n\t\tpriorAvailableAt: isoOf(job.availableAtMs),\n\t\tpriorProcessingDeadline: isoOf(job.processingDeadlineMs),\n\t\tpriorFence: job.fence,\n\t\tpriorLastDiagnostic: job.lastDiagnostic,\n\t\tprocessingDeadline: isoOf(request.processingDeadlineMs),\n\t});\n}\n\nexport function intentRequeueEvidence(intent: IntentState, request: RequeueInput, nowMs: number): WebhookRequeueEvidence {\n\treturn copyOut<WebhookRequeueEvidence>({\n\t\ttarget: \"delivery_intent\",\n\t\teventId: intent.eventId,\n\t\tdeliveryId: intent.key,\n\t\tsubscriptionId: intent.subscriptionId,\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\trequestedBy: request.requestedBy,\n\t\trequestedAt: isoOf(request.requestedAtMs),\n\t\tactionInvocationId: request.actionInvocationId,\n\t\tappliedAt: isoOf(nowMs),\n\t\tpriorAttemptCount: intent.attemptCount,\n\t\tpriorAvailableAt: isoOf(intent.availableAtMs),\n\t\tpriorProcessingDeadline: isoOf(intent.processingDeadlineMs),\n\t\tpriorFence: intent.fence,\n\t\tpriorLastDiagnostic: intent.lastDiagnostic,\n\t\tpriorLastOutcome: intent.lastOutcome,\n\t\tprocessingDeadline: isoOf(request.processingDeadlineMs),\n\t});\n}\n\n/**\n * The first refusal an actor enrichment meets, in the port's order, or\n * `undefined` when it applies. Run inside the atomic step, so the actor\n * state checked is the stored one: a `suppressed` or `present` actor is\n * refused here whatever the caller read before.\n */\nexport function enrichmentRefusal(\n\tjob: JobState,\n\trequest: EnrichmentInput,\n\tfloorMs: number,\n): Exclude<Extract<WebhookActorEnrichmentResult, { readonly applied: false }>[\"refusal\"], \"not_found\"> | undefined {\n\tif (job.fence !== request.expectedFence) return \"stale\";\n\tif (job.status === \"completed\") return \"not_enrichable\";\n\tconst actor = job.draft[\"actor\"] as Snapshot;\n\tif (actor[\"state\"] !== \"absent\") return \"actor_present\";\n\tif (actor[\"reason\"] !== \"legacy\") return \"actor_suppressed\";\n\tif (job.anchorMs < floorMs) return \"past_horizon\";\n\treturn undefined;\n}\n\nexport function jobEnrichmentEvidence(job: JobState, request: EnrichmentInput, nowMs: number): WebhookRequeueEvidence {\n\treturn copyOut<WebhookRequeueEvidence>({\n\t\t...(jobRequeueEvidence(job, request, nowMs) as object),\n\t\ttarget: \"fan_out_job_actor\",\n\t\tactor: { actorId: request.actorId, actorType: request.actorType },\n\t});\n}\n\n/**\n * Apply an enrichment to a job the atomic step accepted: the stored draft is\n * replaced by a copy whose actor is the one read from the canonical event,\n * and the job is requeued exactly as {@link applyRequeue} does, so its fence\n * advances and any lease is cleared.\n */\nexport function applyEnrichment(job: JobState, request: EnrichmentInput): void {\n\tjob.draft = copyOut<Snapshot>({ ...(job.draft as object), actor: { state: \"present\", actorId: request.actorId, actorType: request.actorType } });\n\tapplyRequeue(job, request);\n}\n\nexport function enrichmentRefused(reason: Extract<WebhookActorEnrichmentResult, { readonly applied: false }>[\"refusal\"]): WebhookActorEnrichmentResult {\n\treturn copyOut<WebhookActorEnrichmentResult>({ applied: false, refusal: reason });\n}\n\n/** Move a dead letter back to pending with a restored budget, advancing its fence. */\nexport function applyRequeue(state: JobState | IntentState, request: RequeueInput): void {\n\tstate.status = \"pending\";\n\tstate.attemptCount = 0;\n\tstate.availableAtMs = request.requestedAtMs;\n\tstate.processingDeadlineMs = request.processingDeadlineMs;\n\tstate.fence += 1;\n\tstate.lease = undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Rendering\n// ---------------------------------------------------------------------------\n\nfunction leaseOut(lease: LeaseState | undefined): object | undefined {\n\treturn lease === undefined ? undefined : { owner: lease.owner, fence: lease.fence, expiresAt: isoOf(lease.expiresAtMs) };\n}\n\nexport function jobOut(job: JobState, lease: LeaseState | undefined = job.lease): object {\n\tconst draft = job.draft;\n\treturn {\n\t\teventId: job.key,\n\t\ttenantId: job.tenantId,\n\t\tspaceId: job.spaceId,\n\t\tevent: draft[\"event\"],\n\t\tpayload: draft[\"payload\"],\n\t\tpayloadProjected: draft[\"payloadProjected\"],\n\t\tfacts: draft[\"facts\"],\n\t\tactor: draft[\"actor\"],\n\t\tstatus: job.status,\n\t\tattemptCount: job.attemptCount,\n\t\tavailableAt: isoOf(job.availableAtMs),\n\t\tprocessingDeadline: isoOf(job.processingDeadlineMs),\n\t\tcreatedAt: isoOf(job.createdAtMs),\n\t\tcompletedAt: job.completedAtMs === undefined ? undefined : isoOf(job.completedAtMs),\n\t\tlastDiagnostic: job.lastDiagnostic,\n\t\tfence: lease === undefined ? job.fence : lease.fence,\n\t\tlease: leaseOut(lease),\n\t};\n}\n\nexport function intentOut(intent: IntentState, lease: LeaseState | undefined = intent.lease): object {\n\treturn {\n\t\tdeliveryId: intent.key,\n\t\tsubscriptionId: intent.subscriptionId,\n\t\teventId: intent.eventId,\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\teligibilityRevision: intent.eligibilityRevision,\n\t\teventRecordedAt: isoOf(intent.anchorMs),\n\t\tbody: intent.body,\n\t\tstatus: intent.status,\n\t\tattemptCount: intent.attemptCount,\n\t\tavailableAt: isoOf(intent.availableAtMs),\n\t\tprocessingDeadline: isoOf(intent.processingDeadlineMs),\n\t\tcreatedAt: isoOf(intent.createdAtMs),\n\t\tlastOutcome: intent.lastOutcome,\n\t\tlastDiagnostic: intent.lastDiagnostic,\n\t\tfence: lease === undefined ? intent.fence : lease.fence,\n\t\tlease: leaseOut(lease),\n\t};\n}\n\n/** A tombstone as `readTombstone` returns it; `retainUntil` is the anchor plus the horizon, capped at the `Date` range. */\nexport function tombstoneOut(marker: MarkerState, horizonMs: number): object {\n\treturn {\n\t\tkind: marker.kind,\n\t\tsubscriptionId: marker.subscriptionId,\n\t\teventId: marker.eventId,\n\t\ttenantId: marker.tenantId,\n\t\tspaceId: marker.spaceId,\n\t\tretainUntil: isoOf(mathMin(marker.anchorMs + horizonMs, WEBHOOK_MAX_REPLAY_HORIZON_MS)),\n\t};\n}\n\n/**\n * The pre-handoff lease check: `valid` only when the intent is pending,\n * leased to this owner at this fence, in this scope, and the lease has not\n * expired at the caller's `now`.\n */\nexport function leaseCheck(intent: IntentState | undefined, call: ReturnType<typeof readLeaseCheckCall>): WebhookDeliveryLeaseCheck {\n\tif (intent === undefined || !inScope(intent, call.scope)) return copyOut<WebhookDeliveryLeaseCheck>({ valid: false, reason: \"not_found\" });\n\tif (intent.status !== \"pending\") return copyOut<WebhookDeliveryLeaseCheck>({ valid: false, reason: \"intent_not_pending\" });\n\tif (!holdsFence(intent, call.fenced.owner, call.fenced.fence) || intent.lease!.expiresAtMs <= call.fenced.nowMs) {\n\t\treturn copyOut<WebhookDeliveryLeaseCheck>({ valid: false, reason: \"lease_lost\" });\n\t}\n\treturn copyOut<WebhookDeliveryLeaseCheck>({ valid: true });\n}\n\nexport function requeueRefused(reason: \"not_found\" | \"stale\" | \"not_dead_letter\" | \"past_horizon\"): WebhookRequeueResult {\n\treturn copyOut<WebhookRequeueResult>({ applied: false, refusal: reason });\n}\n\n/** The record a governed requeue or enrichment names: a delivery intent's `deliveryId`, or a job's `eventId`. */\nexport type InvocationTarget =\n\t| { readonly target: \"delivery_intent\"; readonly deliveryId: string }\n\t| { readonly target: \"fan_out_job\" | \"fan_out_job_actor\"; readonly eventId: string };\n\n/**\n * Of `records`, the evidence of one scope appended under one\n * `actionInvocationId` (in append order), the first for `target` and its\n * record, or `undefined`. A store calls this inside the atomic step of a\n * requeue or enrichment, before any other check, so a request of the same\n * governed invocation is recognized whether or not the record still exists\n * or still matches the request.\n */\nexport function priorInvocationEvidence(records: readonly Snapshot[], target: InvocationTarget): Snapshot | undefined {\n\tfor (const record of records) {\n\t\tif (record[\"target\"] !== target.target) continue;\n\t\tif (target.target === \"delivery_intent\" ? record[\"deliveryId\"] === target.deliveryId : record[\"eventId\"] === target.eventId) return record;\n\t}\n\treturn undefined;\n}\n\n/** The answer to a request whose invocation already applied: that application's evidence, unchanged. */\nexport function replayedResult<T extends WebhookRequeueResult | WebhookActorEnrichmentResult>(evidence: Snapshot): T {\n\treturn copyOut<T>({ applied: true, replayed: true, evidence });\n}\n\n/** `listInvocationRequeueEvidence`: a scope and an `actionInvocationId`. */\nexport function readInvocationEvidenceCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), actionInvocationId: identifier(snap, \"actionInvocationId\", \"input.actionInvocationId\") };\n\t});\n}\n\nexport function fencedOutcome(outcome: WebhookFencedInsertResult[\"outcome\"]): WebhookFencedInsertResult {\n\treturn copyOut<WebhookFencedInsertResult>({ outcome });\n}\n","import { storeError } from \"./errors\";\n\n/*\n * Attempt receipts (PR 8). `beginAttempt` creates one per begun attempt and\n * returns it to the worker that began it; `finishAttempt` accepts an\n * outcome only with that receipt. The stores keep only its SHA-256 digest,\n * so a receipt cannot be read back out of a store, and no store read,\n * error or log carries it. Portable: Web Crypto only, which Node 20 and\n * current browsers provide on `globalThis.crypto`.\n */\n\nconst textEncoder = new TextEncoder();\nconst RECEIPT_BYTES = 32;\n\n/** The two Web Crypto members used, typed structurally so the package needs no DOM types. */\ninterface WebCrypto {\n\tgetRandomValues(array: Uint8Array): Uint8Array;\n\treadonly subtle: { digest(algorithm: string, data: Uint8Array): Promise<ArrayBuffer> };\n}\n\nfunction webCrypto(field: string): WebCrypto {\n\tconst crypto = (globalThis as { crypto?: WebCrypto }).crypto;\n\tif (crypto === undefined || typeof crypto.getRandomValues !== \"function\" || crypto.subtle === undefined) throw storeError(\"store_failed\", field);\n\treturn crypto;\n}\n\nfunction hex(bytes: Uint8Array): string {\n\tlet text = \"\";\n\tfor (const byte of bytes) text += byte.toString(16).padStart(2, \"0\");\n\treturn text;\n}\n\n/** @internal Lower-case hex SHA-256 of `text` as UTF-8. Throws `store_failed` naming `field` when Web Crypto is missing. */\nexport async function sha256Hex(text: string, field: string): Promise<string> {\n\treturn hex(new Uint8Array(await webCrypto(field).subtle.digest(\"SHA-256\", textEncoder.encode(text))));\n}\n\n/** @internal A new receipt (`rcpt_` and 32 random bytes in hex) and the digest a store keeps of it. */\nexport async function newAttemptReceipt(): Promise<{ readonly receipt: string; readonly digest: string }> {\n\tconst bytes = new Uint8Array(RECEIPT_BYTES);\n\twebCrypto(\"beginAttempt.receipt\").getRandomValues(bytes);\n\tconst receipt = `rcpt_${hex(bytes)}`;\n\treturn { receipt, digest: await sha256Hex(receipt, \"beginAttempt.receipt\") };\n}\n\n/** @internal The digest of a presented receipt, compared with the one stored at begin. */\nexport function attemptReceiptDigest(receipt: string): Promise<string> {\n\treturn sha256Hex(receipt, \"finishAttempt.receipt\");\n}\n","import type { WebhookDiagnosticCode } from \"./codes\";\nimport {\n\tapplyEnrichment,\n\tapplyRequeue,\n\tapplySettlement,\n\tattemptEntryOut,\n\tattemptKey,\n\tbeginResult,\n\tcompareText,\n\tcopyOut,\n\tdenialRecord,\n\tenrichmentRefusal,\n\tenrichmentRefused,\n\tfencedOutcome,\n\tholds,\n\tinScope,\n\tintentOut,\n\tintentRequeueEvidence,\n\tjobEnrichmentEvidence,\n\tjobOut,\n\tjobRequeueEvidence,\n\tleaseCheck,\n\tpriorInvocationEvidence,\n\tmarkerKey,\n\tmayBegin,\n\treadAppendAttemptCall,\n\treadBeginAttemptCall,\n\treadCancelCall,\n\treadClaimCall,\n\treadDeadLetterJobCall,\n\treadDeliveryCall,\n\treadDenialCall,\n\treadEventCall,\n\treadFinishAttemptCall,\n\treadHookOption,\n\treadHorizonOption,\n\treadInsertFanOutJobCall,\n\treadInsertIntentCall,\n\treadIntentRequeueCall,\n\treadInvocationEvidenceCall,\n\treadJobEnrichmentCall,\n\treadJobFencedCall,\n\treadJobRequeueCall,\n\treadLeaseCheckCall,\n\treadPurgeCall,\n\treadRenewIntentCall,\n\treadRenewJobCall,\n\treadRescheduleCall,\n\treadSettleCall,\n\treadTombstoneCall,\n\trenewedExpiryMs,\n\trequeueRefusal,\n\trequeueRefused,\n\treplayedResult,\n\ttype InvocationTarget,\n\tTERMINAL_INTENT,\n\tTERMINAL_JOB,\n\ttombstoneOut,\n\ttype ClaimInput,\n\ttype IntentState,\n\ttype JobState,\n\ttype Leased,\n\ttype LeaseState,\n\ttype MarkerState,\n} from \"./delivery-store-core\";\nimport { guard, storeError } from \"./errors\";\nimport { attemptReceiptDigest, newAttemptReceipt } from \"./receipt\";\nimport type {\n\tWebhookActorEnrichmentResult,\n\tWebhookAttemptBeginResult,\n\tWebhookCallOptions,\n\tWebhookClaimRequest,\n\tWebhookClock,\n\tWebhookDeliveryLeaseCheck,\n\tWebhookDeliveryStore,\n\tWebhookFanOutJobFence,\n\tWebhookFencedInsertResult,\n\tWebhookFencedWrite,\n\tWebhookInsertResult,\n\tWebhookPurgeResult,\n\tWebhookRequeueResult,\n\tWebhookScope,\n} from \"./ports\";\nimport { frozenList, mathMax } from \"./snapshot\";\nimport {\n\tassertCallWanted,\n\tcaptureClock,\n\tisoOf,\n\treadClock,\n\ttype CallBounds,\n\ttype CapturedClock,\n\ttype Snapshot,\n} from \"./store-input\";\nimport type {\n\tWebhookActorEnrichmentRequest,\n\tWebhookAdmissionDenialRecord,\n\tWebhookDeliveryAttemptFinish,\n\tWebhookDeliveryAttemptLogEntry,\n\tWebhookDeliveryAttemptRecord,\n\tWebhookDeliveryAttemptStart,\n\tWebhookDeliveryIntent,\n\tWebhookFanOutJob,\n\tWebhookFanOutJobDraft,\n\tWebhookRequeueEvidence,\n\tWebhookRequeueRequest,\n\tWebhookTombstone,\n} from \"./types\";\n\n/*\n * In-memory WebhookDeliveryStore, for tests and explicit local development.\n * It holds the same contract as the PostgreSQL store (tests/store-contract.ts)\n * so it does not hide ordering, idempotency or recovery bugs. Both stores\n * read their input and render their records through src/delivery-store-core.ts.\n *\n * Every method has the same shape:\n *\n * 1. Entry: copy the arguments into a package-owned snapshot\n * (src/delivery-store-core.ts, src/store-input.ts). Malformed input is\n * refused here, before anything else happens.\n * 2. One `await`, standing where a real store does I/O, so concurrent\n * calls interleave the way they do against a database.\n * 3. One synchronous step, `#atomic`: read the store's clock, refuse a call\n * whose signal aborted or whose deadline passed, then every check\n * (fence, replay horizon, uniqueness, status) and the write. There is\n * no `await` inside it, and JavaScript runs a synchronous block to\n * completion, so no other call on this store can run between its\n * checks and its write: it plays the part of one transaction.\n *\n * State lives in ECMAScript private fields of the instance; nothing is kept\n * in module scope. Reads return fresh frozen copies built from that state,\n * never the state itself.\n */\n\n/** Options for {@link MemoryWebhookDeliveryStore}. */\nexport interface MemoryWebhookDeliveryStoreOptions {\n\t/** The store's clock: it timestamps requeue evidence and decides the replay horizon. */\n\treadonly clock: WebhookClock;\n\t/** The replay horizon in milliseconds; see `WebhookDeliveryLimits.replayHorizonMs`. */\n\treadonly replayHorizonMs: number;\n\t/**\n\t * Test seam. Awaited at each call's I/O boundary, after its input is read\n\t * and before its atomic step, with the method name. A contract test uses\n\t * it to hold one call there while another runs to completion, forcing an\n\t * interleaving. A throw or rejection fails the call as `store_failed`,\n\t * with nothing written. Leave it unset outside tests.\n\t */\n\treadonly beforeAtomicStep?: (operation: string) => Promise<void> | void;\n}\n\ninterface DenialState {\n\treadonly key: string;\n\treadonly record: Snapshot;\n\treadonly anchorMs: number;\n}\n\ninterface AttemptState {\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly deliveryId: string;\n\t/** The whole entry (`appendAttempt`) or the start of a begun attempt (`beginAttempt`). */\n\treadonly record: Snapshot;\n\t/** The lease fence a begun attempt was recorded under; `undefined` for an entry appended whole. */\n\treadonly fence: number | undefined;\n\t/** The SHA-256 digest of a begun attempt's receipt; never the receipt itself. */\n\treadonly receiptDigest: string | undefined;\n}\n\ninterface EvidenceState {\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly eventId: string;\n\treadonly record: Snapshot;\n}\n\n/** Run an async step; a package error passes through, anything else becomes `store_failed`. */\nasync function guardedAsync<T>(run: () => Promise<T>): Promise<T> {\n\ttry {\n\t\treturn await run();\n\t} catch (thrown) {\n\t\treturn guard<T>(() => {\n\t\t\tthrow thrown;\n\t\t}, () => storeError(\"store_failed\", \"store\"));\n\t}\n}\n\n/** Where a database store would do I/O; lets concurrent calls interleave. */\nfunction ioBoundary(): Promise<void> {\n\treturn Promise.resolve();\n}\n\n/**\n * An in-memory {@link WebhookDeliveryStore}. Construct one per test or local\n * process; instances share nothing.\n *\n * @throws {WebhookDeliveryConfigError} when `replayHorizonMs` is not a\n * positive whole number of milliseconds within `WEBHOOK_MAX_REPLAY_HORIZON_MS`.\n * @throws {WebhookStoreError} `clock_invalid` when `clock` has no `now` function.\n */\nexport class MemoryWebhookDeliveryStore implements WebhookDeliveryStore {\n\treadonly #clock: CapturedClock;\n\treadonly #beforeAtomicStep: ((operation: string) => Promise<void> | void) | undefined;\n\treadonly #horizonMs: number;\n\treadonly #jobs = new Map<string, JobState>();\n\treadonly #intents = new Map<string, IntentState>();\n\treadonly #denials = new Map<string, DenialState>();\n\treadonly #markers = new Map<string, MarkerState>();\n\treadonly #attempts: AttemptState[] = [];\n\t/** Begun attempts by (deliveryId, fence); each is also in `#attempts`. */\n\treadonly #begun = new Map<string, AttemptState>();\n\t/** Outcomes of begun attempts by (deliveryId, fence). Written once, never changed. */\n\treadonly #outcomes = new Map<string, Snapshot>();\n\treadonly #evidence: EvidenceState[] = [];\n\t/** The highest cutoff any purge has used; inserts and requeues below it are refused. */\n\t#purgedThroughMs = -Infinity;\n\n\tconstructor(options: MemoryWebhookDeliveryStoreOptions) {\n\t\tthis.#horizonMs = readHorizonOption(options);\n\t\tthis.#clock = guard(() => captureClock((options as { clock?: WebhookClock }).clock), () => storeError(\"clock_invalid\", \"clock\"));\n\t\tthis.#beforeAtomicStep = readHookOption(options, \"beforeAtomicStep\");\n\t}\n\n\t/** The replay horizon this store enforces, in milliseconds. */\n\tget replayHorizonMs(): number {\n\t\treturn this.#horizonMs;\n\t}\n\n\t/** The I/O boundary: the injected seam, or one resolved turn. */\n\tasync #boundary(operation: string): Promise<void> {\n\t\tconst hook = this.#beforeAtomicStep;\n\t\tif (hook === undefined) return ioBoundary();\n\t\ttry {\n\t\t\tawait hook(operation);\n\t\t} catch {\n\t\t\tthrow storeError(\"store_failed\", \"beforeAtomicStep\");\n\t\t}\n\t}\n\n\t/**\n\t * The atomic step. Reads the store clock, refuses an unwanted call, then\n\t * runs `body` synchronously. A package error passes through; anything\n\t * else becomes `store_failed`.\n\t */\n\t#atomic<T>(bounds: CallBounds, body: (nowMs: number) => T): T {\n\t\treturn guard(() => {\n\t\t\tconst nowMs = readClock(this.#clock);\n\t\t\tassertCallWanted(bounds, nowMs);\n\t\t\treturn body(nowMs);\n\t\t}, () => storeError(\"store_failed\", \"store\"));\n\t}\n\n\t/** The horizon floor at `nowMs`: anchors earlier than this are past the horizon. */\n\t#floorMs(nowMs: number): number {\n\t\treturn mathMax(nowMs - this.#horizonMs, this.#purgedThroughMs);\n\t}\n\n\t#pastHorizon(anchorMs: number, nowMs: number): boolean {\n\t\treturn anchorMs < this.#floorMs(nowMs);\n\t}\n\n\t/**\n\t * Evidence `scope` holds under `actionInvocationId` for `target`, or\n\t * `undefined` (always, without an id). Called first in the atomic step of\n\t * a requeue or enrichment: see \"Re-runs of one invocation\" in src/ports.ts.\n\t */\n\t#priorEvidence(scope: WebhookScope, actionInvocationId: string | undefined, target: InvocationTarget): Snapshot | undefined {\n\t\tif (actionInvocationId === undefined) return undefined;\n\t\tconst records = this.#evidence\n\t\t\t.filter((item) => inScope(item, scope) && item.record[\"actionInvocationId\"] === actionInvocationId)\n\t\t\t.map((item) => item.record);\n\t\treturn priorInvocationEvidence(records, target);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Fan-out jobs\n\t// -------------------------------------------------------------------------\n\n\tasync insertFanOutJob(\n\t\tjob: WebhookFanOutJobDraft & { readonly processingDeadline: string; readonly createdAt: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookInsertResult> {\n\t\tconst call = readInsertFanOutJobCall(job, options);\n\t\tawait this.#boundary(\"insertFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst draft = call.job;\n\t\t\t// Horizon first, so the answer for an old event does not depend on\n\t\t\t// whether a purge has removed its job yet.\n\t\t\tif (this.#pastHorizon(draft.anchorMs, nowMs)) return copyOut<WebhookInsertResult>({ outcome: \"past_horizon\" });\n\t\t\tif (this.#jobs.has(draft.eventId)) return copyOut<WebhookInsertResult>({ outcome: \"already_present\" });\n\t\t\tthis.#jobs.set(draft.eventId, {\n\t\t\t\tkey: draft.eventId,\n\t\t\t\tdraft: draft.draft,\n\t\t\t\ttenantId: draft.tenantId,\n\t\t\t\tspaceId: draft.spaceId,\n\t\t\t\tanchorMs: draft.anchorMs,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tattemptCount: 0,\n\t\t\t\tavailableAtMs: draft.createdAtMs,\n\t\t\t\tcreatedAtMs: draft.createdAtMs,\n\t\t\t\tprocessingDeadlineMs: draft.processingDeadlineMs,\n\t\t\t\tcompletedAtMs: undefined,\n\t\t\t\tlastDiagnostic: undefined,\n\t\t\t\tfence: 0,\n\t\t\t\tlease: undefined,\n\t\t\t});\n\t\t\treturn copyOut<WebhookInsertResult>({ outcome: \"inserted\" });\n\t\t});\n\t}\n\n\tasync claimFanOutJobs(request: WebhookClaimRequest, options: WebhookCallOptions): Promise<readonly WebhookFanOutJob[]> {\n\t\tconst call = readClaimCall(request, options);\n\t\tawait this.#boundary(\"claimFanOutJobs\");\n\t\treturn this.#atomic(call.bounds, () =>\n\t\t\tclaimFrom([...this.#jobs.values()], call.claim, jobOut) as readonly WebhookFanOutJob[]);\n\t}\n\n\tasync completeFanOutJob(input: WebhookFencedWrite & { readonly eventId: string }, options: WebhookCallOptions): Promise<boolean> {\n\t\tconst call = readJobFencedCall(input, options);\n\t\tawait this.#boundary(\"completeFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !holds(job, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tjob.status = \"completed\";\n\t\t\tjob.completedAtMs = call.fenced.nowMs;\n\t\t\tjob.lease = undefined;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync rescheduleFanOutJob(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly availableAt: Date; readonly diagnostic: WebhookDiagnosticCode },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRescheduleCall(input, options);\n\t\tawait this.#boundary(\"rescheduleFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !holds(job, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tjob.attemptCount += 1;\n\t\t\tjob.availableAtMs = call.availableAtMs;\n\t\t\tjob.lastDiagnostic = call.diagnostic;\n\t\t\tjob.lease = undefined;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync renewFanOutJobLease(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly leaseDurationMs: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRenewJobCall(input, options);\n\t\tawait this.#boundary(\"renewFanOutJobLease\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !holds(job, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tjob.lease = { ...job.lease!, expiresAtMs: renewedExpiryMs(job, call.fenced.nowMs, call.leaseDurationMs) };\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync deadLetterFanOutJob(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly diagnostic: WebhookDiagnosticCode },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readDeadLetterJobCall(input, options);\n\t\tawait this.#boundary(\"deadLetterFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !holds(job, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tjob.status = \"dead_letter\";\n\t\t\tjob.lastDiagnostic = call.diagnostic;\n\t\t\tjob.lease = undefined;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync requeueFanOutJob(\n\t\tinput: WebhookScope & { readonly eventId: string; readonly request: WebhookRequeueRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookRequeueResult> {\n\t\tconst call = readJobRequeueCall(input, options);\n\t\tawait this.#boundary(\"requeueFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst prior = this.#priorEvidence(call.scope, call.request.actionInvocationId, { target: \"fan_out_job\", eventId: call.eventId });\n\t\t\tif (prior !== undefined) return replayedResult<WebhookRequeueResult>(prior);\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !inScope(job, call.scope)) return requeueRefused(\"not_found\");\n\t\t\tconst refusal = requeueRefusal(job, call.request, this.#floorMs(nowMs));\n\t\t\tif (refusal !== undefined) return requeueRefused(refusal);\n\t\t\tconst evidence = jobRequeueEvidence(job, call.request, nowMs);\n\t\t\tconst result = copyOut<WebhookRequeueResult>({ applied: true, evidence });\n\t\t\tapplyRequeue(job, call.request);\n\t\t\tthis.#evidence.push({ tenantId: job.tenantId, spaceId: job.spaceId, eventId: job.key, record: evidence as unknown as Snapshot });\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync enrichFanOutJobActor(\n\t\tinput: WebhookScope & { readonly eventId: string; readonly request: WebhookActorEnrichmentRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookActorEnrichmentResult> {\n\t\tconst call = readJobEnrichmentCall(input, options);\n\t\tawait this.#boundary(\"enrichFanOutJobActor\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst prior = this.#priorEvidence(call.scope, call.request.actionInvocationId, { target: \"fan_out_job_actor\", eventId: call.eventId });\n\t\t\tif (prior !== undefined) return replayedResult<WebhookActorEnrichmentResult>(prior);\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !inScope(job, call.scope)) return enrichmentRefused(\"not_found\");\n\t\t\tconst refusal = enrichmentRefusal(job, call.request, this.#floorMs(nowMs));\n\t\t\tif (refusal !== undefined) return enrichmentRefused(refusal);\n\t\t\tconst evidence = jobEnrichmentEvidence(job, call.request, nowMs);\n\t\t\tconst result = copyOut<WebhookActorEnrichmentResult>({ applied: true, evidence });\n\t\t\tapplyEnrichment(job, call.request);\n\t\t\tthis.#evidence.push({ tenantId: job.tenantId, spaceId: job.spaceId, eventId: job.key, record: evidence as unknown as Snapshot });\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync readFanOutJob(input: WebhookScope & { readonly eventId: string }, options: WebhookCallOptions): Promise<WebhookFanOutJob | null> {\n\t\tconst call = readEventCall(input, options);\n\t\tawait this.#boundary(\"readFanOutJob\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\treturn job === undefined || !inScope(job, call.scope) ? null : copyOut<WebhookFanOutJob>(jobOut(job));\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Intents and denials\n\t// -------------------------------------------------------------------------\n\n\tasync insertDeliveryIntent(\n\t\tintent: Omit<WebhookDeliveryIntent, \"status\" | \"attemptCount\" | \"lastOutcome\" | \"lastDiagnostic\" | \"lease\" | \"eventRecordedAt\" | \"fence\">,\n\t\tparent: WebhookFanOutJobFence,\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookFencedInsertResult> {\n\t\tconst call = readInsertIntentCall(intent, parent, options);\n\t\tawait this.#boundary(\"insertDeliveryIntent\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#parentJob(call.parent, nowMs);\n\t\t\tif (job === undefined) return fencedOutcome(\"lease_lost\");\n\t\t\tif (!inScope(job, call)) throw storeError(\"record_mismatch\", \"intent.tenantId\");\n\t\t\tif (this.#pastHorizon(job.anchorMs, nowMs)) return fencedOutcome(\"past_horizon\");\n\t\t\tconst key = markerKey(call.subscriptionId, call.eventId);\n\t\t\tif (this.#markers.has(key)) return fencedOutcome(\"already_present\");\n\t\t\tif (this.#intents.has(call.deliveryId)) throw storeError(\"delivery_id_conflict\", \"intent.deliveryId\");\n\t\t\tthis.#intents.set(call.deliveryId, {\n\t\t\t\tkey: call.deliveryId,\n\t\t\t\tsubscriptionId: call.subscriptionId,\n\t\t\t\teventId: call.eventId,\n\t\t\t\ttenantId: call.tenantId,\n\t\t\t\tspaceId: call.spaceId,\n\t\t\t\teligibilityRevision: call.eligibilityRevision,\n\t\t\t\tbody: call.body,\n\t\t\t\tanchorMs: job.anchorMs,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tattemptCount: 0,\n\t\t\t\tavailableAtMs: call.availableAtMs,\n\t\t\t\tcreatedAtMs: call.createdAtMs,\n\t\t\t\tprocessingDeadlineMs: call.processingDeadlineMs,\n\t\t\t\tlastOutcome: undefined,\n\t\t\t\tlastDiagnostic: undefined,\n\t\t\t\tfence: 0,\n\t\t\t\tlease: undefined,\n\t\t\t});\n\t\t\tthis.#markers.set(key, { kind: \"intent\", subscriptionId: call.subscriptionId, eventId: call.eventId, tenantId: call.tenantId, spaceId: call.spaceId, anchorMs: job.anchorMs });\n\t\t\treturn fencedOutcome(\"inserted\");\n\t\t});\n\t}\n\n\tasync recordAdmissionDenial(\n\t\trecord: WebhookAdmissionDenialRecord,\n\t\tparent: WebhookFanOutJobFence,\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookFencedInsertResult> {\n\t\tconst call = readDenialCall(record, parent, options);\n\t\tawait this.#boundary(\"recordAdmissionDenial\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#parentJob(call.parent, nowMs);\n\t\t\tif (job === undefined) return fencedOutcome(\"lease_lost\");\n\t\t\tif (!inScope(job, call)) throw storeError(\"record_mismatch\", \"record.tenantId\");\n\t\t\tif (this.#pastHorizon(job.anchorMs, nowMs)) return fencedOutcome(\"past_horizon\");\n\t\t\tconst key = markerKey(call.subscriptionId, call.eventId);\n\t\t\tif (this.#markers.has(key)) return fencedOutcome(\"already_present\");\n\t\t\tthis.#denials.set(key, { key, record: denialRecord(call), anchorMs: job.anchorMs });\n\t\t\tthis.#markers.set(key, { kind: \"denial\", subscriptionId: call.subscriptionId, eventId: call.eventId, tenantId: call.tenantId, spaceId: call.spaceId, anchorMs: job.anchorMs });\n\t\t\treturn fencedOutcome(\"inserted\");\n\t\t});\n\t}\n\n\t/** The parent job if `fence` still holds its unexpired lease at the store's `nowMs`. */\n\t#parentJob(fence: WebhookFanOutJobFence, nowMs: number): JobState | undefined {\n\t\tconst job = this.#jobs.get(fence.eventId);\n\t\treturn job !== undefined && holds(job, fence.owner, fence.fence, nowMs) ? job : undefined;\n\t}\n\n\tasync claimDeliveryIntents(request: WebhookClaimRequest, options: WebhookCallOptions): Promise<readonly WebhookDeliveryIntent[]> {\n\t\tconst call = readClaimCall(request, options);\n\t\tawait this.#boundary(\"claimDeliveryIntents\");\n\t\treturn this.#atomic(call.bounds, () =>\n\t\t\tclaimFrom([...this.#intents.values()], call.claim, intentOut) as readonly WebhookDeliveryIntent[]);\n\t}\n\n\tasync renewDeliveryIntentLease(\n\t\tinput: WebhookFencedWrite & { readonly deliveryId: string; readonly leaseDurationMs: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRenewIntentCall(input, options);\n\t\tawait this.#boundary(\"renewDeliveryIntentLease\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tintent.lease = { ...intent.lease!, expiresAtMs: renewedExpiryMs(intent, call.fenced.nowMs, call.leaseDurationMs) };\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync checkDeliveryLease(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly owner: string; readonly fence: number; readonly now: Date },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookDeliveryLeaseCheck> {\n\t\tconst call = readLeaseCheckCall(input, options);\n\t\tawait this.#boundary(\"checkDeliveryLease\");\n\t\treturn this.#atomic(call.bounds, () => leaseCheck(this.#intents.get(call.deliveryId), call));\n\t}\n\n\tasync appendAttempt(input: WebhookFencedWrite & { readonly attempt: WebhookDeliveryAttemptRecord }, options: WebhookCallOptions): Promise<boolean> {\n\t\tconst call = readAppendAttemptCall(input, options);\n\t\tawait this.#boundary(\"appendAttempt\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tif (call.subscriptionId !== intent.subscriptionId) throw storeError(\"record_mismatch\", \"input.attempt.subscriptionId\");\n\t\t\tif (call.eventId !== intent.eventId) throw storeError(\"record_mismatch\", \"input.attempt.eventId\");\n\t\t\tthis.#attempts.push({ tenantId: intent.tenantId, spaceId: intent.spaceId, deliveryId: call.deliveryId, record: call.record, fence: undefined, receiptDigest: undefined });\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync beginAttempt(input: WebhookFencedWrite & { readonly attempt: WebhookDeliveryAttemptStart }, options: WebhookCallOptions): Promise<WebhookAttemptBeginResult> {\n\t\tconst call = readBeginAttemptCall(input, options);\n\t\t// Made before the atomic step, which has no await; kept only as a digest.\n\t\tconst receipt = await guardedAsync(newAttemptReceipt);\n\t\tawait this.#boundary(\"beginAttempt\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (!mayBegin(intent, call.fenced, nowMs)) return beginResult(undefined);\n\t\t\tif (call.subscriptionId !== intent.subscriptionId) throw storeError(\"record_mismatch\", \"input.attempt.subscriptionId\");\n\t\t\tif (call.eventId !== intent.eventId) throw storeError(\"record_mismatch\", \"input.attempt.eventId\");\n\t\t\tconst key = attemptKey(call.deliveryId, call.fenced.fence);\n\t\t\tif (this.#begun.has(key)) return beginResult(undefined);\n\t\t\tconst state: AttemptState = {\n\t\t\t\ttenantId: intent.tenantId, spaceId: intent.spaceId, deliveryId: call.deliveryId, record: call.record,\n\t\t\t\tfence: call.fenced.fence, receiptDigest: receipt.digest,\n\t\t\t};\n\t\t\tthis.#attempts.push(state);\n\t\t\tthis.#begun.set(key, state);\n\t\t\treturn beginResult(receipt.receipt);\n\t\t});\n\t}\n\n\tasync finishAttempt(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly fence: number; readonly receipt: string; readonly finish: WebhookDeliveryAttemptFinish },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readFinishAttemptCall(input, options);\n\t\tconst digest = await guardedAsync(() => attemptReceiptDigest(call.receipt));\n\t\tawait this.#boundary(\"finishAttempt\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst key = attemptKey(call.deliveryId, call.fence);\n\t\t\tconst begun = this.#begun.get(key);\n\t\t\t// Unfenced: the begun attempt's key, scope and receipt are checked, and\n\t\t\t// nothing of the intent is read or changed.\n\t\t\tif (begun === undefined || !inScope(begun, call.scope) || begun.receiptDigest !== digest || this.#outcomes.has(key)) return false;\n\t\t\tthis.#outcomes.set(key, call.record);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync settleDeliveryIntent(\n\t\tinput: Parameters<WebhookDeliveryStore[\"settleDeliveryIntent\"]>[0],\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readSettleCall(input, options);\n\t\tawait this.#boundary(\"settleDeliveryIntent\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tapplySettlement(intent, call.settlement);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync cancelPendingIntents(\n\t\tinput: Parameters<WebhookDeliveryStore[\"cancelPendingIntents\"]>[0],\n\t\toptions: WebhookCallOptions,\n\t): Promise<number> {\n\t\tconst call = readCancelCall(input, options);\n\t\tawait this.#boundary(\"cancelPendingIntents\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tlet cancelled = 0;\n\t\t\tfor (const intent of this.#intents.values()) {\n\t\t\t\tif (intent.status !== \"pending\" || intent.subscriptionId !== call.subscriptionId || !inScope(intent, call.scope)) continue;\n\t\t\t\tif (intent.eligibilityRevision >= call.beforeRevision) continue;\n\t\t\t\tintent.status = \"cancelled\";\n\t\t\t\tintent.lastOutcome = { outcome: \"cancelled\", reason: call.reason };\n\t\t\t\tintent.lease = undefined;\n\t\t\t\tcancelled += 1;\n\t\t\t}\n\t\t\treturn cancelled;\n\t\t});\n\t}\n\n\tasync requeueDeliveryIntent(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly request: WebhookRequeueRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookRequeueResult> {\n\t\tconst call = readIntentRequeueCall(input, options);\n\t\tawait this.#boundary(\"requeueDeliveryIntent\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst prior = this.#priorEvidence(call.scope, call.request.actionInvocationId, { target: \"delivery_intent\", deliveryId: call.deliveryId });\n\t\t\tif (prior !== undefined) return replayedResult<WebhookRequeueResult>(prior);\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (intent === undefined || !inScope(intent, call.scope)) return requeueRefused(\"not_found\");\n\t\t\tconst refusal = requeueRefusal(intent, call.request, this.#floorMs(nowMs));\n\t\t\tif (refusal !== undefined) return requeueRefused(refusal);\n\t\t\tconst evidence = intentRequeueEvidence(intent, call.request, nowMs);\n\t\t\tconst result = copyOut<WebhookRequeueResult>({ applied: true, evidence });\n\t\t\tapplyRequeue(intent, call.request);\n\t\t\tthis.#evidence.push({ tenantId: intent.tenantId, spaceId: intent.spaceId, eventId: intent.eventId, record: evidence as unknown as Snapshot });\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync readDeliveryIntent(input: WebhookScope & { readonly deliveryId: string }, options: WebhookCallOptions): Promise<WebhookDeliveryIntent | null> {\n\t\tconst call = readDeliveryCall(input, options);\n\t\tawait this.#boundary(\"readDeliveryIntent\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\treturn intent === undefined || !inScope(intent, call.scope) ? null : copyOut<WebhookDeliveryIntent>(intentOut(intent));\n\t\t});\n\t}\n\n\tasync listDeliveryAttempts(\n\t\tinput: WebhookScope & { readonly deliveryId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookDeliveryAttemptLogEntry[]> {\n\t\tconst call = readDeliveryCall(input, options);\n\t\tawait this.#boundary(\"listDeliveryAttempts\");\n\t\treturn this.#atomic(call.bounds, () => copyOut<readonly WebhookDeliveryAttemptLogEntry[]>(\n\t\t\tthis.#attempts\n\t\t\t\t.filter((item) => item.deliveryId === call.deliveryId && inScope(item, call.scope))\n\t\t\t\t.map((item) => attemptEntryOut(\n\t\t\t\t\titem.record,\n\t\t\t\t\titem.fence,\n\t\t\t\t\titem.fence === undefined ? undefined : this.#outcomes.get(attemptKey(item.deliveryId, item.fence)),\n\t\t\t\t)),\n\t\t));\n\t}\n\n\tasync listRequeueEvidence(input: WebhookScope & { readonly eventId: string }, options: WebhookCallOptions): Promise<readonly WebhookRequeueEvidence[]> {\n\t\tconst call = readEventCall(input, options);\n\t\tawait this.#boundary(\"listRequeueEvidence\");\n\t\treturn this.#atomic(call.bounds, () => copyOut<readonly WebhookRequeueEvidence[]>(\n\t\t\tthis.#evidence.filter((item) => item.eventId === call.eventId && inScope(item, call.scope)).map((item) => item.record),\n\t\t));\n\t}\n\n\tasync listInvocationRequeueEvidence(\n\t\tinput: WebhookScope & { readonly actionInvocationId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookRequeueEvidence[]> {\n\t\tconst call = readInvocationEvidenceCall(input, options);\n\t\tawait this.#boundary(\"listInvocationRequeueEvidence\");\n\t\treturn this.#atomic(call.bounds, () => copyOut<readonly WebhookRequeueEvidence[]>(\n\t\t\tthis.#evidence\n\t\t\t\t.filter((item) => inScope(item, call.scope) && item.record[\"actionInvocationId\"] === call.actionInvocationId)\n\t\t\t\t.map((item) => item.record),\n\t\t));\n\t}\n\n\tasync readTombstone(\n\t\tinput: WebhookScope & { readonly subscriptionId: string; readonly eventId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookTombstone | null> {\n\t\tconst call = readTombstoneCall(input, options);\n\t\tawait this.#boundary(\"readTombstone\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst marker = this.#markers.get(markerKey(call.subscriptionId, call.eventId));\n\t\t\tif (marker === undefined || !inScope(marker, call.scope)) return null;\n\t\t\treturn copyOut<WebhookTombstone>(tombstoneOut(marker, this.#horizonMs));\n\t\t});\n\t}\n\n\tasync purgeExpiredRecords(input: { readonly limit: number }, options: WebhookCallOptions): Promise<WebhookPurgeResult> {\n\t\tconst call = readPurgeCall(input, options);\n\t\tawait this.#boundary(\"purgeExpiredRecords\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst cutoffMs = this.#floorMs(nowMs);\n\t\t\tconst cutoff = isoOf(cutoffMs);\n\t\t\tconst candidates: { readonly anchorMs: number; readonly rank: number; readonly key: string }[] = [];\n\t\t\tfor (const job of this.#jobs.values()) {\n\t\t\t\tif (job.anchorMs < cutoffMs && TERMINAL_JOB.includes(job.status)) candidates.push({ anchorMs: job.anchorMs, rank: 0, key: job.key });\n\t\t\t}\n\t\t\tfor (const denial of this.#denials.values()) {\n\t\t\t\tif (denial.anchorMs < cutoffMs) candidates.push({ anchorMs: denial.anchorMs, rank: 1, key: denial.key });\n\t\t\t}\n\t\t\tfor (const intent of this.#intents.values()) {\n\t\t\t\tif (intent.anchorMs < cutoffMs && TERMINAL_INTENT.includes(intent.status)) candidates.push({ anchorMs: intent.anchorMs, rank: 2, key: intent.key });\n\t\t\t}\n\t\t\tcandidates.sort((left, right) => left.anchorMs - right.anchorMs || left.rank - right.rank || compareText(left.key, right.key));\n\t\t\tconst take = candidates.length < call.limit ? candidates.length : call.limit;\n\t\t\tconst removed = { fanOutJobs: 0, deliveryIntents: 0, admissionDenials: 0 };\n\t\t\tfor (let index = 0; index < take; index += 1) {\n\t\t\t\tconst rank = candidates[index]!.rank;\n\t\t\t\tif (rank === 0) removed.fanOutJobs += 1;\n\t\t\t\telse if (rank === 1) removed.admissionDenials += 1;\n\t\t\t\telse removed.deliveryIntents += 1;\n\t\t\t}\n\t\t\tconst result = copyOut<WebhookPurgeResult>({ cutoff, removed, more: candidates.length > take });\n\t\t\t// Compute, then commit. Raise the floor in the same step as the\n\t\t\t// removals: from here on no insert or requeue can recreate anything\n\t\t\t// below it.\n\t\t\tthis.#purgedThroughMs = cutoffMs;\n\t\t\tfor (let index = 0; index < take; index += 1) {\n\t\t\t\tconst candidate = candidates[index]!;\n\t\t\t\tif (candidate.rank === 0) {\n\t\t\t\t\tthis.#jobs.delete(candidate.key);\n\t\t\t\t} else if (candidate.rank === 1) {\n\t\t\t\t\tthis.#denials.delete(candidate.key);\n\t\t\t\t\tthis.#markers.delete(candidate.key);\n\t\t\t\t} else {\n\t\t\t\t\tconst intent = this.#intents.get(candidate.key)!;\n\t\t\t\t\tthis.#intents.delete(candidate.key);\n\t\t\t\t\tthis.#markers.delete(markerKey(intent.subscriptionId, intent.eventId));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Lease up to `claim.limit` claimable records, oldest `availableAt` first\n * (then `createdAt`, then key), advancing each one's fence. Returns the\n * leased states. Sorting is explicit, so the order never depends on Map\n * insertion order.\n */\nfunction claimFrom<T extends Leased>(records: T[], claim: ClaimInput, render: (record: T, lease: LeaseState) => object): readonly unknown[] {\n\tconst claimable = records.filter((record) =>\n\t\trecord.status === \"pending\" &&\n\t\trecord.availableAtMs <= claim.nowMs &&\n\t\t(record.lease === undefined || record.lease.expiresAtMs <= claim.nowMs));\n\tclaimable.sort((left, right) => left.availableAtMs - right.availableAtMs || left.createdAtMs - right.createdAtMs || compareText(left.key, right.key));\n\tconst leased = claimable.slice(0, claim.limit);\n\t// Compute, then commit: every lease and every returned record is built\n\t// before any record changes, so a failure here leaves the store as it was.\n\tconst plan = leased.map((record) => ({\n\t\trecord,\n\t\tlease: { owner: claim.workerId, fence: record.fence + 1, expiresAtMs: claim.nowMs + claim.leaseDurationMs },\n\t}));\n\tconst out = plan.map(({ record, lease }) => copyOut<object>(render(record, lease)));\n\tfor (const { record, lease } of plan) {\n\t\trecord.fence = lease.fence;\n\t\trecord.lease = lease;\n\t}\n\treturn frozenList(out);\n}\n","import { guard, storeError } from \"./errors\";\nimport type { WebhookScope, WebhookSubscriptionWriteRefusal, WebhookSubscriptionWriteResult } from \"./ports\";\nimport { mathMax } from \"./snapshot\";\nimport {\n\tcloneOut,\n\tcodeOf,\n\tidentifier,\n\tinstant,\n\tisoOf,\n\tnestedRecord,\n\toptionalWholeNumber,\n\treadCallOptions,\n\tsnapshotRecord,\n\ttext,\n\ttextList,\n} from \"./store-input\";\nimport type {\n\tWebhookDeliveryConfiguration,\n\tWebhookDeliveryConfigurationInput,\n\tWebhookSignatureScheme,\n\tWebhookSubscriptionStatus,\n} from \"./types\";\n\n/*\n * What the memory and PostgreSQL subscription stores share: the entry\n * readers, the revision shape, the transition rules and the record\n * renderers. Internal: not exported from the package entry point.\n */\n\nexport interface RevisionState {\n\treadonly revision: number;\n\treadonly status: WebhookSubscriptionStatus;\n\treadonly eventTypePatterns: readonly string[];\n\treadonly effectiveFromMs: number;\n}\n\nexport interface Target extends WebhookScope {\n\treadonly subscriptionId: string;\n}\n\nconst SCHEMES = Object.freeze([\"v1\"] as const);\n\n/** A fresh frozen deep copy with no depth or size limit (`cloneOut`). */\nexport function copyOut<T>(value: object): T {\n\treturn cloneOut<T>(value);\n}\n\nfunction entry<T>(read: () => T): T {\n\treturn guard(read, () => storeError(\"input_invalid\", \"input\"));\n}\n\nfunction readTarget(snap: ReturnType<typeof snapshotRecord>): Target {\n\treturn {\n\t\ttenantId: identifier(snap, \"tenantId\", \"input.tenantId\"),\n\t\tspaceId: identifier(snap, \"spaceId\", \"input.spaceId\"),\n\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"input.subscriptionId\"),\n\t};\n}\n\nfunction readConfiguration(snap: ReturnType<typeof snapshotRecord>): WebhookDeliveryConfigurationInput {\n\tconst configuration = nestedRecord(snap, \"configuration\", \"input.configuration\");\n\treturn {\n\t\tdestinationUrl: text(configuration, \"destinationUrl\", \"input.configuration.destinationUrl\"),\n\t\tsignatureScheme: codeOf<WebhookSignatureScheme>(configuration, \"signatureScheme\", SCHEMES, \"input.configuration.signatureScheme\"),\n\t\tsecretRef: text(configuration, \"secretRef\", \"input.configuration.secretRef\"),\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Per-method entry readers\n// ---------------------------------------------------------------------------\n\nexport function readRevisionsAtCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\ttenantId: identifier(snap, \"tenantId\", \"input.tenantId\"),\n\t\t\tspaceId: identifier(snap, \"spaceId\", \"input.spaceId\"),\n\t\t\trecordedAtMs: instant(snap, \"recordedAt\", \"input.recordedAt\"),\n\t\t};\n\t});\n}\n\n/** `readSubscription` and `listEligibilityHistory`: one subscription in a scope. */\nexport function readTargetCall(input: unknown, options: unknown) {\n\treturn entry(() => ({ bounds: readCallOptions(options), target: readTarget(snapshotRecord(input, \"input\")) }));\n}\n\nexport function readCreateCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\ttarget: readTarget(snap),\n\t\t\tpatterns: textList(snap, \"eventTypePatterns\", \"input.eventTypePatterns\"),\n\t\t\tconfiguration: readConfiguration(snap),\n\t\t};\n\t});\n}\n\nexport function readChangePatternsCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\ttarget: readTarget(snap),\n\t\t\texpectedRevision: optionalWholeNumber(snap, \"expectedRevision\", \"input.expectedRevision\", 1),\n\t\t\tpatterns: textList(snap, \"eventTypePatterns\", \"input.eventTypePatterns\"),\n\t\t};\n\t});\n}\n\nexport function readStatusChangeCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), target: readTarget(snap), expectedRevision: optionalWholeNumber(snap, \"expectedRevision\", \"input.expectedRevision\", 1) };\n\t});\n}\n\nexport function readReplaceConfigurationCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\ttarget: readTarget(snap),\n\t\t\texpectedVersion: optionalWholeNumber(snap, \"expectedVersion\", \"input.expectedVersion\", 1),\n\t\t\tconfiguration: readConfiguration(snap),\n\t\t};\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Transitions\n// ---------------------------------------------------------------------------\n\n/** The status a pause, resume or delete moves to from `status`, or `undefined` when it is not allowed. */\nexport type StatusChange = (status: WebhookSubscriptionStatus) => WebhookSubscriptionStatus | undefined;\n\nexport const PAUSE: StatusChange = (status) => (status === \"active\" ? \"paused\" : undefined);\nexport const RESUME: StatusChange = (status) => (status === \"paused\" ? \"active\" : undefined);\nexport const DELETE: StatusChange = () => \"deleted\";\n\nexport type RevisionChange = (current: RevisionState) => { readonly status: WebhookSubscriptionStatus; readonly patterns: readonly string[] } | undefined;\n\nexport function statusRevisionChange(next: StatusChange): RevisionChange {\n\treturn (current) => {\n\t\tconst status = next(current.status);\n\t\treturn status === undefined ? undefined : { status, patterns: current.eventTypePatterns };\n\t};\n}\n\n/**\n * Decide one transition against the store's current revision: a refusal, or\n * the revision to append. The new revision takes effect at the store's\n * clock, or at the previous revision's start if the clock is behind it, so\n * intervals never invert.\n */\nexport function decideTransition(\n\tcurrent: RevisionState | undefined,\n\texpectedRevision: number | undefined,\n\tnowMs: number,\n\tchange: RevisionChange,\n): { readonly refusal: WebhookSubscriptionWriteResult } | { readonly appended: RevisionState } {\n\tif (current === undefined) return { refusal: refused(\"not_found\") };\n\tif (current.status === \"deleted\") return { refusal: refused(\"deleted\", current.revision) };\n\tif (expectedRevision !== undefined && expectedRevision !== current.revision) return { refusal: refused(\"revision_conflict\", current.revision) };\n\tconst next = change(current);\n\tif (next === undefined) return { refusal: refused(\"invalid_transition\", current.revision) };\n\treturn {\n\t\tappended: {\n\t\t\trevision: current.revision + 1,\n\t\t\tstatus: next.status,\n\t\t\teventTypePatterns: next.patterns,\n\t\t\teffectiveFromMs: mathMax(nowMs, current.effectiveFromMs),\n\t\t},\n\t};\n}\n\nexport function refused(refusal: WebhookSubscriptionWriteRefusal, currentRevision?: number): WebhookSubscriptionWriteResult {\n\treturn copyOut<WebhookSubscriptionWriteResult>({ applied: false, refusal, currentRevision });\n}\n\n// ---------------------------------------------------------------------------\n// Rendering\n// ---------------------------------------------------------------------------\n\n/** A revision as the read port returns it; `nextEffectiveFromMs` is its successor's start, if any. */\nexport function revisionOut(target: Target, revision: RevisionState, nextEffectiveFromMs: number | undefined): object {\n\treturn {\n\t\tsubscriptionId: target.subscriptionId,\n\t\trevision: revision.revision,\n\t\ttenantId: target.tenantId,\n\t\tspaceId: target.spaceId,\n\t\tstatus: revision.status,\n\t\teventTypePatterns: revision.eventTypePatterns,\n\t\teffectiveFrom: isoOf(revision.effectiveFromMs),\n\t\teffectiveUntil: nextEffectiveFromMs === undefined ? null : isoOf(nextEffectiveFromMs),\n\t};\n}\n\n/**\n * The snapshot's `statusSinceRevision`: the revision at which the latest\n * revision's status began, i.e. one past the last revision with another\n * status, or 1. Revisions are numbered 1, 2, 3 … with no gaps\n * (`decideTransition` appends `current.revision + 1`); the PostgreSQL\n * store computes the same in SQL (`readSubscription`), and the contract\n * case \"readSubscription reports the revision the current status began at …\"\n * holds both to it.\n */\nexport function statusSinceRevision(revisions: readonly RevisionState[]): number {\n\tconst current = revisions[revisions.length - 1]!;\n\tfor (let index = revisions.length - 1; index >= 0; index -= 1) {\n\t\tif (revisions[index]!.status !== current.status) return revisions[index]!.revision + 1;\n\t}\n\treturn 1;\n}\n\nexport function configurationOut(target: Target, version: number, configuration: WebhookDeliveryConfigurationInput): WebhookDeliveryConfiguration {\n\treturn copyOut<WebhookDeliveryConfiguration>({\n\t\tsubscriptionId: target.subscriptionId,\n\t\ttenantId: target.tenantId,\n\t\tspaceId: target.spaceId,\n\t\tversion,\n\t\t...configuration,\n\t});\n}\n\n/** UTF-16 code unit order, as JavaScript's `<` compares strings. */\nexport function compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n","import { readHookOption } from \"./delivery-store-core\";\nimport { guard, storeError } from \"./errors\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookConfigurationWriteResult,\n\tWebhookScope,\n\tWebhookSubscriptionStore,\n\tWebhookSubscriptionTransitionInput,\n\tWebhookSubscriptionWriteResult,\n\tWebhookSubscriptionWriter,\n} from \"./ports\";\nimport {\n\tassertCallWanted,\n\tcaptureClock,\n\tcompositeKey,\n\treadClock,\n\ttype CallBounds,\n\ttype CapturedClock,\n} from \"./store-input\";\nimport {\n\tcompareText,\n\tconfigurationOut,\n\tcopyOut,\n\tdecideTransition,\n\tDELETE,\n\tPAUSE,\n\treadChangePatternsCall,\n\treadCreateCall,\n\treadReplaceConfigurationCall,\n\treadRevisionsAtCall,\n\treadStatusChangeCall,\n\treadTargetCall,\n\trefused,\n\tRESUME,\n\trevisionOut,\n\tstatusRevisionChange,\n\tstatusSinceRevision,\n\ttype RevisionChange,\n\ttype RevisionState,\n\ttype StatusChange,\n\ttype Target,\n} from \"./subscription-store-core\";\nimport type {\n\tWebhookDeliveryConfiguration,\n\tWebhookDeliveryConfigurationInput,\n\tWebhookEligibilityRevision,\n\tWebhookSubscriptionSnapshot,\n} from \"./types\";\n\n/*\n * In-memory subscription store: the read port the cycles use and the writer\n * port the governed actions use, in one instance so a test or local process\n * can share state between them. Same method shape as the memory delivery\n * store: snapshot at entry, one I/O boundary, then one synchronous step\n * that reads the store's clock, checks the transition against the store's\n * own current state and appends. Revisions and configuration versions are\n * append-only; a revision's `effectiveUntil` is derived from its\n * successor's `effectiveFrom` on read, so no stored revision is ever changed.\n * Input reading and the transition rules are shared with the PostgreSQL\n * store (src/subscription-store-core.ts).\n */\n\n/** Options for {@link MemoryWebhookSubscriptionStore}. */\nexport interface MemoryWebhookSubscriptionStoreOptions {\n\t/** The store's clock: every revision takes effect at its time (decision 3). */\n\treadonly clock: WebhookClock;\n\t/**\n\t * Test seam. Awaited at each call's I/O boundary, after its input is read\n\t * and before its atomic step, with the method name. A contract test uses\n\t * it to hold one call there while another runs to completion, forcing an\n\t * interleaving. A throw or rejection fails the call as `store_failed`,\n\t * with nothing written. Leave it unset outside tests.\n\t */\n\treadonly beforeAtomicStep?: (operation: string) => Promise<void> | void;\n}\n\ninterface SubscriptionState extends Target {\n\treadonly revisions: RevisionState[];\n\treadonly configurations: WebhookDeliveryConfiguration[];\n}\n\n/** The key of one (tenantId, spaceId, subscriptionId); JSON-encoded, so distinct tuples never collide. */\nfunction subscriptionKey(tenantId: string, spaceId: string, subscriptionId: string): string {\n\treturn compositeKey(tenantId, spaceId, subscriptionId);\n}\n\nfunction ioBoundary(): Promise<void> {\n\treturn Promise.resolve();\n}\n\nfunction revisionAt(subscription: SubscriptionState, index: number): object {\n\treturn revisionOut(subscription, subscription.revisions[index]!, subscription.revisions[index + 1]?.effectiveFromMs);\n}\n\n/**\n * An in-memory {@link WebhookSubscriptionStore} and {@link WebhookSubscriptionWriter}.\n * Subscriptions are keyed by (tenantId, spaceId, subscriptionId); a read or\n * write in another scope does not see them.\n *\n * @throws {WebhookStoreError} `clock_invalid` when `clock` has no `now` function.\n */\nexport class MemoryWebhookSubscriptionStore implements WebhookSubscriptionStore, WebhookSubscriptionWriter {\n\treadonly #clock: CapturedClock;\n\treadonly #beforeAtomicStep: ((operation: string) => Promise<void> | void) | undefined;\n\treadonly #subscriptions = new Map<string, SubscriptionState>();\n\n\tconstructor(options: MemoryWebhookSubscriptionStoreOptions) {\n\t\tthis.#clock = guard(() => {\n\t\t\tif (options === null || typeof options !== \"object\") throw storeError(\"clock_invalid\", \"clock\");\n\t\t\treturn captureClock(options.clock);\n\t\t}, () => storeError(\"clock_invalid\", \"clock\"));\n\t\tthis.#beforeAtomicStep = readHookOption(options, \"beforeAtomicStep\");\n\t}\n\n\t/** The I/O boundary: the injected seam, or one resolved turn. */\n\tasync #boundary(operation: string): Promise<void> {\n\t\tconst hook = this.#beforeAtomicStep;\n\t\tif (hook === undefined) return ioBoundary();\n\t\ttry {\n\t\t\tawait hook(operation);\n\t\t} catch {\n\t\t\tthrow storeError(\"store_failed\", \"beforeAtomicStep\");\n\t\t}\n\t}\n\n\t#atomic<T>(bounds: CallBounds, body: (nowMs: number) => T): T {\n\t\treturn guard(() => {\n\t\t\tconst nowMs = readClock(this.#clock);\n\t\t\tassertCallWanted(bounds, nowMs);\n\t\t\treturn body(nowMs);\n\t\t}, () => storeError(\"store_failed\", \"store\"));\n\t}\n\n\t#find(target: Target): SubscriptionState | undefined {\n\t\treturn this.#subscriptions.get(subscriptionKey(target.tenantId, target.spaceId, target.subscriptionId));\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Reads\n\t// -------------------------------------------------------------------------\n\n\tasync listEligibilityRevisions(\n\t\tinput: WebhookScope & { readonly recordedAt: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookEligibilityRevision[]> {\n\t\tconst call = readRevisionsAtCall(input, options);\n\t\tawait this.#boundary(\"listEligibilityRevisions\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst found: object[] = [];\n\t\t\tconst subscriptions = [...this.#subscriptions.values()]\n\t\t\t\t.filter((subscription) => subscription.tenantId === call.tenantId && subscription.spaceId === call.spaceId)\n\t\t\t\t.sort((left, right) => compareText(left.subscriptionId, right.subscriptionId));\n\t\t\tfor (const subscription of subscriptions) {\n\t\t\t\t// Half-open: effectiveFrom <= recordedAt < next.effectiveFrom.\n\t\t\t\tfor (let index = subscription.revisions.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tif (subscription.revisions[index]!.effectiveFromMs <= call.recordedAtMs) {\n\t\t\t\t\t\tconst next = subscription.revisions[index + 1];\n\t\t\t\t\t\tif (next === undefined || call.recordedAtMs < next.effectiveFromMs) found.push(revisionAt(subscription, index));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn copyOut<readonly WebhookEligibilityRevision[]>(found);\n\t\t});\n\t}\n\n\tasync readSubscription(\n\t\tinput: WebhookScope & { readonly subscriptionId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionSnapshot | null> {\n\t\tconst call = readTargetCall(input, options);\n\t\tawait this.#boundary(\"readSubscription\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst subscription = this.#find(call.target);\n\t\t\tif (subscription === undefined) return null;\n\t\t\treturn copyOut<WebhookSubscriptionSnapshot>({\n\t\t\t\tsubscriptionId: subscription.subscriptionId,\n\t\t\t\ttenantId: subscription.tenantId,\n\t\t\t\tspaceId: subscription.spaceId,\n\t\t\t\tstatus: subscription.revisions[subscription.revisions.length - 1]!.status,\n\t\t\t\tstatusSinceRevision: statusSinceRevision(subscription.revisions),\n\t\t\t\tconfiguration: subscription.configurations[subscription.configurations.length - 1]!,\n\t\t\t});\n\t\t});\n\t}\n\n\tasync listEligibilityHistory(\n\t\tinput: WebhookScope & { readonly subscriptionId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookEligibilityRevision[]> {\n\t\tconst call = readTargetCall(input, options);\n\t\tawait this.#boundary(\"listEligibilityHistory\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst subscription = this.#find(call.target);\n\t\t\tif (subscription === undefined) return copyOut<readonly WebhookEligibilityRevision[]>([]);\n\t\t\treturn copyOut<readonly WebhookEligibilityRevision[]>(subscription.revisions.map((_revision, index) => revisionAt(subscription, index)));\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Writes\n\t// -------------------------------------------------------------------------\n\n\tasync createSubscription(\n\t\tinput: WebhookScope & {\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly eventTypePatterns: readonly string[];\n\t\t\treadonly configuration: WebhookDeliveryConfigurationInput;\n\t\t},\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readCreateCall(input, options);\n\t\tawait this.#boundary(\"createSubscription\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tif (this.#find(call.target) !== undefined) return refused(\"already_exists\");\n\t\t\tconst { tenantId, spaceId, subscriptionId } = call.target;\n\t\t\tconst configuration = configurationOut(call.target, 1, call.configuration);\n\t\t\tconst subscription: SubscriptionState = {\n\t\t\t\tsubscriptionId,\n\t\t\t\ttenantId,\n\t\t\t\tspaceId,\n\t\t\t\trevisions: [{ revision: 1, status: \"active\", eventTypePatterns: call.patterns, effectiveFromMs: nowMs }],\n\t\t\t\tconfigurations: [configuration],\n\t\t\t};\n\t\t\tconst result = copyOut<WebhookSubscriptionWriteResult>({ applied: true, revision: revisionAt(subscription, 0), configuration });\n\t\t\tthis.#subscriptions.set(subscriptionKey(tenantId, spaceId, subscriptionId), subscription);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync changeEventTypePatterns(\n\t\tinput: WebhookSubscriptionTransitionInput & { readonly eventTypePatterns: readonly string[] },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readChangePatternsCall(input, options);\n\t\tawait this.#boundary(\"changeEventTypePatterns\");\n\t\treturn this.#atomic(call.bounds, (nowMs) =>\n\t\t\tthis.#transition(call.target, call.expectedRevision, nowMs, (current) => ({ status: current.status, patterns: call.patterns })));\n\t}\n\n\tasync pauseSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"pauseSubscription\", input, options, PAUSE);\n\t}\n\n\tasync resumeSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"resumeSubscription\", input, options, RESUME);\n\t}\n\n\tasync deleteSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"deleteSubscription\", input, options, DELETE);\n\t}\n\n\tasync replaceDeliveryConfiguration(\n\t\tinput: WebhookScope & { readonly subscriptionId: string; readonly configuration: WebhookDeliveryConfigurationInput; readonly expectedVersion?: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookConfigurationWriteResult> {\n\t\tconst call = readReplaceConfigurationCall(input, options);\n\t\tawait this.#boundary(\"replaceDeliveryConfiguration\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst subscription = this.#find(call.target);\n\t\t\tif (subscription === undefined) return copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"not_found\" });\n\t\t\tif (subscription.revisions[subscription.revisions.length - 1]!.status === \"deleted\") {\n\t\t\t\treturn copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"deleted\" });\n\t\t\t}\n\t\t\tconst current = subscription.configurations[subscription.configurations.length - 1]!;\n\t\t\tif (call.expectedVersion !== undefined && call.expectedVersion !== current.version) {\n\t\t\t\treturn copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"version_conflict\", currentVersion: current.version });\n\t\t\t}\n\t\t\tconst configuration = configurationOut(subscription, current.version + 1, call.configuration);\n\t\t\tconst result = copyOut<WebhookConfigurationWriteResult>({ applied: true, configuration });\n\t\t\tsubscription.configurations.push(configuration);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync #statusChange(\n\t\toperation: string,\n\t\tinput: WebhookSubscriptionTransitionInput,\n\t\toptions: WebhookCallOptions,\n\t\tnext: StatusChange,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readStatusChangeCall(input, options);\n\t\tawait this.#boundary(operation);\n\t\treturn this.#atomic(call.bounds, (nowMs) => this.#transition(call.target, call.expectedRevision, nowMs, statusRevisionChange(next)));\n\t}\n\n\t/**\n\t * Append one revision, checked against the store's current state. Runs\n\t * inside the atomic step.\n\t */\n\t#transition(target: Target, expectedRevision: number | undefined, nowMs: number, change: RevisionChange): WebhookSubscriptionWriteResult {\n\t\tconst subscription = this.#find(target);\n\t\tconst decision = decideTransition(subscription?.revisions[subscription.revisions.length - 1], expectedRevision, nowMs, change);\n\t\tif (\"refusal\" in decision) return decision.refusal;\n\t\tconst current = subscription!;\n\t\t// Compute, then commit: the result is built from the would-be history\n\t\t// before the revision is appended.\n\t\tconst result = copyOut<WebhookSubscriptionWriteResult>({\n\t\t\tapplied: true,\n\t\t\trevision: revisionOut(current, decision.appended, undefined),\n\t\t\tconfiguration: current.configurations[current.configurations.length - 1]!,\n\t\t});\n\t\tcurrent.revisions.push(decision.appended);\n\t\treturn result;\n\t}\n}\n","import { guard, storeError } from \"./errors\";\nimport { sha256Hex } from \"./receipt\";\nimport { matches } from \"./snapshot\";\nimport { assertCallWanted, readClock, type CallBounds, type CapturedClock } from \"./store-input\";\n\n/*\n * What the PostgreSQL stores need from a database client, and the\n * transaction, migration and row-reading helpers both stores share.\n *\n * The client is injected and structural, like Host's `PlatformHostSqlClient`:\n * `pg.Pool` satisfies it, and the package has no runtime dependency on `pg`.\n * Unlike Host's interface it also needs `connect()`, because a store method\n * that checks and then writes runs several statements, with the store's\n * clock read between them, on one connection inside one transaction.\n */\n\n/** The rows a query returned. */\nexport interface WebhookPostgresResult<Row = Record<string, unknown>> {\n\trows: Row[];\n}\n\n/** Anything that runs one parameterized statement. */\nexport interface WebhookPostgresQueryable {\n\tquery<Row = Record<string, unknown>>(sql: string, values?: unknown[]): Promise<WebhookPostgresResult<Row>>;\n}\n\n/** One checked-out connection. `release(true)` discards it instead of returning it to the pool. */\nexport interface WebhookPostgresConnection extends WebhookPostgresQueryable {\n\trelease(destroy?: boolean): void;\n}\n\n/** A connection pool: `pg.Pool`, or a Lakebase-compatible client with the same two methods. */\nexport interface WebhookPostgresPool extends WebhookPostgresQueryable {\n\tconnect(): Promise<WebhookPostgresConnection>;\n}\n\n/** Where the store pauses inside a transaction, for the serialization tests only. */\nexport type WebhookTransactionCheckpointStage = \"locked\" | \"written\";\n\n/**\n * A schema name the stores accept: lower-case ASCII letters, digits and\n * underscores, starting with a letter or underscore, at most 63 bytes (the\n * PostgreSQL identifier limit). It is double-quoted wherever it is used, so\n * the pattern, not quoting, is what keeps it from being read as SQL.\n */\nconst SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;\n\nexport const DEFAULT_WEBHOOK_SCHEMA = \"fabric_webhook_delivery\";\n\n/** Read the optional `schema` option; anything but a valid name is `input_invalid`. */\nexport function readSchemaOption(options: unknown): string {\n\treturn guard(() => {\n\t\tconst schema = (options as { schema?: unknown }).schema;\n\t\tif (schema === undefined) return `\"${DEFAULT_WEBHOOK_SCHEMA}\"`;\n\t\tif (typeof schema !== \"string\" || !matches(SCHEMA_NAME, schema)) throw storeError(\"input_invalid\", \"schema\");\n\t\treturn `\"${schema}\"`;\n\t}, () => storeError(\"input_invalid\", \"schema\"));\n}\n\n/** Read the required `pool` option: an object with `query` and `connect` functions. */\nexport function readPoolOption(options: unknown): WebhookPostgresPool {\n\treturn guard(() => {\n\t\tconst pool = (options as { pool?: unknown }).pool;\n\t\tif (pool === null || typeof pool !== \"object\") throw storeError(\"input_invalid\", \"pool\");\n\t\tconst { query, connect } = pool as { query?: unknown; connect?: unknown };\n\t\tif (typeof query !== \"function\" || typeof connect !== \"function\") throw storeError(\"input_invalid\", \"pool\");\n\t\treturn pool as WebhookPostgresPool;\n\t}, () => storeError(\"input_invalid\", \"pool\"));\n}\n\n/**\n * Run `run` and map whatever it throws: a package error passes through, and\n * anything else (a driver error, a lost connection, a constraint violation)\n * becomes `store_failed` without being read.\n */\nexport async function storeCall<T>(run: () => Promise<T>): Promise<T> {\n\ttry {\n\t\treturn await run();\n\t} catch (thrown) {\n\t\treturn guard<T>(() => {\n\t\t\tthrow thrown;\n\t\t}, () => storeError(\"store_failed\", \"store\"));\n\t}\n}\n\n/** Lets a transaction body end in ROLLBACK while still returning its result. */\nexport interface WebhookTransactionControl {\n\t/** Roll back instead of committing; the body's return value is still returned. */\n\tabandon(): void;\n}\n\n/**\n * Run `run` inside one READ COMMITTED transaction on one connection. The\n * isolation level is named rather than inherited, because the locking\n * argument in the README (\"PostgreSQL stores\") assumes it. The transaction\n * commits unless `run` throws or calls `control.abandon()`. Any throw rolls\n * back; if the rollback itself fails the connection is discarded rather\n * than returned to the pool in an unknown state.\n */\nexport async function inTransaction<T>(\n\tpool: WebhookPostgresPool,\n\trun: (tx: WebhookPostgresQueryable, control: WebhookTransactionControl) => Promise<T>,\n): Promise<T> {\n\tconst connection = await pool.connect();\n\tlet destroy = false;\n\tlet abandoned = false;\n\ttry {\n\t\tawait connection.query(\"BEGIN ISOLATION LEVEL READ COMMITTED\");\n\t\tconst result = await run(connection, { abandon: () => { abandoned = true; } });\n\t\tawait connection.query(abandoned ? \"ROLLBACK\" : \"COMMIT\");\n\t\treturn result;\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait connection.query(\"ROLLBACK\");\n\t\t} catch {\n\t\t\tdestroy = true;\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\tconnection.release(destroy);\n\t}\n}\n\n/**\n * One store write, in one transaction, in three phases:\n *\n * 1. `lock` runs every statement that can wait on another transaction:\n * the horizon table lock, `SELECT … FOR UPDATE` / `FOR SHARE` on the\n * records the write reads, and a tentative insert-if-absent, whose\n * conflict check waits on a concurrent uncommitted insert of the same\n * key. It decides nothing.\n * 2. With every lock held, the store's clock is read and a call whose\n * signal aborted or whose deadline passed is refused, rolling back. A\n * call that waited for a lock is therefore judged, and its horizon\n * floor computed, at the time it decides, not before it waited.\n * 3. `body` decides from what `lock` read and finishes the write. It may\n * call `control.abandon()` to roll back a tentative write and still\n * return its result (an insert that turned out past the horizon).\n *\n * Immediately before COMMIT the clock is read and the bounds are checked\n * once more, so nothing commits if the signal aborted or the deadline\n * passed while `body` ran. The purge is the only write whose `body` can\n * wait on another transaction (its deletes wait for row locks). Every other\n * body writes only rows its `lock` phase already holds, rows it inserted\n * there, rows keyed by a fresh identity value (attempts, requeue evidence),\n * a begun attempt keyed by its intent's current fence (no other transaction\n * can insert that key while this one holds the intent row), or a\n * subscription's next revision or configuration version, which no other\n * transaction can insert while this one holds the head row.\n */\nexport function runWrite<L, T>(\n\tpool: WebhookPostgresPool,\n\tclock: CapturedClock,\n\tbounds: CallBounds,\n\tlock: (tx: WebhookPostgresQueryable) => Promise<L>,\n\tbody: (tx: WebhookPostgresQueryable, nowMs: number, locked: L, control: WebhookTransactionControl) => Promise<T>,\n): Promise<T> {\n\treturn storeCall(() => inTransaction(pool, async (tx, control) => {\n\t\tconst locked = await lock(tx);\n\t\tconst nowMs = readClock(clock);\n\t\tassertCallWanted(bounds, nowMs);\n\t\tconst result = await body(tx, nowMs, locked, control);\n\t\tassertCallWanted(bounds, readClock(clock));\n\t\treturn result;\n\t}));\n}\n\n/** One store read: one statement (its own transaction) after the call-bounds check. */\nexport function runRead<T>(\n\tpool: WebhookPostgresPool,\n\tclock: CapturedClock,\n\tbounds: CallBounds,\n\tbody: (db: WebhookPostgresQueryable, nowMs: number) => Promise<T>,\n): Promise<T> {\n\treturn storeCall(async () => {\n\t\tconst nowMs = readClock(clock);\n\t\tassertCallWanted(bounds, nowMs);\n\t\treturn body(pool, nowMs);\n\t});\n}\n\n/** Await a test seam; a throw or rejection fails the call as `store_failed` naming the seam. */\nexport async function awaitHook(hook: (() => Promise<void> | void) | undefined, field: string): Promise<void> {\n\tif (hook === undefined) return;\n\ttry {\n\t\tawait hook();\n\t} catch {\n\t\tthrow storeError(\"store_failed\", field);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Migrations\n// ---------------------------------------------------------------------------\n\n/** One immutable migration. `sql` names the schema as `{{schema}}`. */\nexport interface WebhookPostgresMigration {\n\treadonly version: number;\n\treadonly name: string;\n\treadonly sql: string;\n}\n\n\n/**\n * Apply `component`'s migrations to `schema`, in version order, in one\n * transaction, mirroring Host's `applyPostgresMigrations`: a\n * transaction-scoped advisory lock serializes concurrent callers, each\n * applied version is recorded with the SHA-256 of its SQL template, and a\n * recorded version whose template has since changed fails as `store_failed`\n * (`ensureSchema.checksum`) instead of being re-run. The checksum is taken\n * before the schema name is substituted, so the same migration has the same\n * checksum in every schema.\n */\nexport async function applyWebhookMigrations(\n\tpool: WebhookPostgresPool,\n\tschema: string,\n\tcomponent: string,\n\tmigrations: readonly WebhookPostgresMigration[],\n): Promise<void> {\n\tconst ordered = [...migrations].sort((left, right) => left.version - right.version);\n\tconst checksums = await Promise.all(ordered.map((migration) => sha256Hex(migration.sql, \"ensureSchema.crypto\")));\n\tawait storeCall(() => inTransaction(pool, async (tx) => {\n\t\tawait tx.query(\"SELECT pg_advisory_xact_lock(hashtext($1))\", [`fabric_webhook_delivery.schema_migrations:${schema}`]);\n\t\tawait tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);\n\t\tawait tx.query(`CREATE TABLE IF NOT EXISTS ${schema}.webhook_schema_migrations (\n\t\t\tcomponent text NOT NULL,\n\t\t\tversion integer NOT NULL,\n\t\t\tname text NOT NULL,\n\t\t\tchecksum text NOT NULL,\n\t\t\tapplied_at timestamptz NOT NULL DEFAULT now(),\n\t\t\tPRIMARY KEY (component, version)\n\t\t)`);\n\t\tfor (let index = 0; index < ordered.length; index += 1) {\n\t\t\tconst migration = ordered[index]!;\n\t\t\tconst checksum = checksums[index]!;\n\t\t\tconst recorded = await tx.query<{ checksum: string }>(\n\t\t\t\t`SELECT checksum FROM ${schema}.webhook_schema_migrations WHERE component = $1 AND version = $2`,\n\t\t\t\t[component, migration.version],\n\t\t\t);\n\t\t\tconst row = recorded.rows[0];\n\t\t\tif (row !== undefined) {\n\t\t\t\tif (row.checksum !== checksum) throw storeError(\"store_failed\", \"ensureSchema.checksum\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait tx.query(migration.sql.replaceAll(\"{{schema}}\", schema));\n\t\t\tawait tx.query(\n\t\t\t\t`INSERT INTO ${schema}.webhook_schema_migrations (component, version, name, checksum) VALUES ($1, $2, $3, $4)`,\n\t\t\t\t[component, migration.version, migration.name, checksum],\n\t\t\t);\n\t\t}\n\t}));\n}\n\n// ---------------------------------------------------------------------------\n// Values in and out\n// ---------------------------------------------------------------------------\n\nconst jsonParse = JSON.parse;\nconst numberIsSafeInteger = Number.isSafeInteger;\nconst NumberConstructor = Number;\n\n/**\n * A sort key whose byte order (under `COLLATE \"C\"`) is the UTF-16 code unit\n * order JavaScript's `<` uses: four hex digits per code unit. PostgreSQL's\n * own text orders compare code points or follow a locale, which would put a\n * few strings in a different order from the memory store's sort.\n */\nexport function utf16SortKey(value: string): string {\n\tlet key = \"\";\n\tfor (let index = 0; index < value.length; index += 1) key += value.charCodeAt(index).toString(16).padStart(4, \"0\");\n\treturn key;\n}\n\n/** A whole number read from a row; `bigint` columns are selected as text so every client returns the same thing. */\nexport function intOf(value: unknown, field: string): number {\n\tconst number = typeof value === \"number\" ? value : typeof value === \"string\" ? NumberConstructor(value) : Number.NaN;\n\tif (!numberIsSafeInteger(number)) throw storeError(\"store_failed\", field);\n\treturn number;\n}\n\nexport function optionalIntOf(value: unknown, field: string): number | undefined {\n\treturn value === null || value === undefined ? undefined : intOf(value, field);\n}\n\nexport function textOf(value: unknown, field: string): string {\n\tif (typeof value !== \"string\") throw storeError(\"store_failed\", field);\n\treturn value;\n}\n\nexport function optionalTextOf(value: unknown, field: string): string | undefined {\n\treturn value === null || value === undefined ? undefined : textOf(value, field);\n}\n\n/**\n * Parse a `json` column selected as text. The stores write JSON text with\n * the package serializer and keep it in `json` columns, not `jsonb`: `json`\n * keeps the text as written, so key order and every string, lone\n * surrogates included, come back exactly as the memory store would return\n * them.\n */\nexport function jsonOf(value: unknown, field: string): unknown {\n\tconst text = textOf(value, field);\n\ttry {\n\t\treturn jsonParse(text) as unknown;\n\t} catch {\n\t\tthrow storeError(\"store_failed\", field);\n\t}\n}\n","import type { WebhookDiagnosticCode } from \"./codes\";\nimport {\n\tapplyEnrichment,\n\tapplyRequeue,\n\tapplySettlement,\n\tattemptEntryOut,\n\tbeginResult,\n\tcompareText,\n\tcopyOut,\n\tdenialRecord,\n\tfencedOutcome,\n\tholds,\n\tholdsFence,\n\tinScope,\n\tintentOut,\n\tenrichmentRefusal,\n\tenrichmentRefused,\n\tintentRequeueEvidence,\n\tjobOut,\n\tjobEnrichmentEvidence,\n\tjobRequeueEvidence,\n\tleaseCheck,\n\tpriorInvocationEvidence,\n\tmarkerKey,\n\tmayBegin,\n\treadAppendAttemptCall,\n\treadBeginAttemptCall,\n\treadCancelCall,\n\treadClaimCall,\n\treadDeadLetterJobCall,\n\treadDeliveryCall,\n\treadDenialCall,\n\treadEventCall,\n\treadFinishAttemptCall,\n\treadHookOption,\n\treadHorizonOption,\n\treadInsertFanOutJobCall,\n\treadInsertIntentCall,\n\treadIntentRequeueCall,\n\treadInvocationEvidenceCall,\n\treadJobFencedCall,\n\treadJobEnrichmentCall,\n\treadJobRequeueCall,\n\treadLeaseCheckCall,\n\treadPurgeCall,\n\treadRenewIntentCall,\n\treadRenewJobCall,\n\treadRescheduleCall,\n\treadSettleCall,\n\treadTombstoneCall,\n\trenewedExpiryMs,\n\trequeueRefusal,\n\trequeueRefused,\n\treplayedResult,\n\ttype InvocationTarget,\n\tTERMINAL_INTENT,\n\tTERMINAL_JOB,\n\ttombstoneOut,\n\ttype IntentState,\n\ttype JobState,\n\ttype MarkerState,\n} from \"./delivery-store-core\";\nimport { guard, storeError } from \"./errors\";\nimport { attemptReceiptDigest, newAttemptReceipt } from \"./receipt\";\nimport type {\n\tWebhookActorEnrichmentResult,\n\tWebhookAttemptBeginResult,\n\tWebhookCallOptions,\n\tWebhookClaimRequest,\n\tWebhookClock,\n\tWebhookDeliveryLeaseCheck,\n\tWebhookDeliveryStore,\n\tWebhookFanOutJobFence,\n\tWebhookFencedInsertResult,\n\tWebhookFencedWrite,\n\tWebhookInsertResult,\n\tWebhookPurgeResult,\n\tWebhookRequeueResult,\n\tWebhookScope,\n} from \"./ports\";\nimport {\n\tapplyWebhookMigrations,\n\tawaitHook,\n\tintOf,\n\tjsonOf,\n\toptionalIntOf,\n\toptionalTextOf,\n\treadPoolOption,\n\treadSchemaOption,\n\trunRead,\n\trunWrite,\n\tstoreCall,\n\ttextOf,\n\tutf16SortKey,\n\ttype WebhookPostgresMigration,\n\ttype WebhookPostgresPool,\n\ttype WebhookPostgresQueryable,\n\ttype WebhookTransactionCheckpointStage,\n\ttype WebhookTransactionControl,\n} from \"./postgres-sql\";\nimport { frozenList, mathMax, serializeJson } from \"./snapshot\";\nimport { captureClock, isoOf, type CallBounds, type CapturedClock, type Snapshot } from \"./store-input\";\nimport type {\n\tWebhookActorEnrichmentRequest,\n\tWebhookAdmissionDenialRecord,\n\tWebhookDeliveryAttemptFinish,\n\tWebhookDeliveryAttemptLogEntry,\n\tWebhookDeliveryAttemptRecord,\n\tWebhookDeliveryAttemptStart,\n\tWebhookDeliveryIntent,\n\tWebhookFanOutJob,\n\tWebhookFanOutJobDraft,\n\tWebhookRequeueEvidence,\n\tWebhookRequeueRequest,\n\tWebhookTombstone,\n} from \"./types\";\n\n/*\n * PostgreSQL WebhookDeliveryStore. It holds the same contract as the memory\n * store (tests/store-contract.ts runs against both) and reads its input and\n * renders its records through the same functions (src/delivery-store-core.ts).\n *\n * Every method has the memory store's shape, with the synchronous atomic\n * step replaced by one transaction:\n *\n * 1. Entry: the shared reader copies and validates the arguments.\n * 2. The `beforeAtomicStep` test seam, awaited before any connection is\n * taken or transaction opened.\n * 3. For a write, one READ COMMITTED transaction on one connection\n * (`runWrite` in src/postgres-sql.ts), in this order:\n * a. every lock, in a fixed order: the horizon table lock first (when\n * the method takes it), then the record rows (`FOR UPDATE`, or\n * `FOR SHARE` on an insert's parent job), then any tentative\n * insert-if-absent, whose conflict check can wait on a concurrent\n * insert of the same key;\n * b. the store's clock, and the refusal of a call whose signal\n * aborted or whose deadline passed, possibly while it waited in (a);\n * c. every check (lease, scope, horizon floor, uniqueness, status) and\n * the write, or a rollback of the tentative insert;\n * d. the clock and the call bounds once more, then COMMIT.\n * A read is one statement after the bounds check.\n *\n * Replay-horizon serialization. A purge and a horizon-checked write (job,\n * intent and denial inserts, job and intent requeues, actor enrichment)\n * must not interleave\n * between the write's read of the purge floor and its write; otherwise a\n * purge could remove a key after an insert read the old floor, and the\n * insert would re-create it. The mechanism is a table-level lock on the\n * store's one-row horizon table, `webhook_delivery_horizon`:\n *\n * - every horizon-checked write takes `LOCK TABLE ... IN SHARE MODE` as its\n * first statement and reads the highest purge cutoff, then takes its\n * record locks, and only then reads the clock;\n * - `purgeExpiredRecords` takes `LOCK TABLE ... IN EXCLUSIVE MODE` as its\n * first statement and reads the cutoff, then reads the clock, removes,\n * and raises the floor before it commits.\n *\n * SHARE conflicts with EXCLUSIVE and not with itself, so writes do not\n * serialize against each other, and a write and a purge cannot both hold the\n * lock: whichever transaction gets it first commits (or rolls back) before\n * the other reads anything. Both orders are then serial, which is all the\n * horizon rules need. A table lock rather than a row lock (`FOR SHARE` /\n * `FOR UPDATE` on the horizon row) because PostgreSQL's lock manager queues\n * a SHARE request behind a waiting EXCLUSIVE one, so a steady stream of\n * inserts cannot keep a purge waiting; a new `FOR SHARE` row lock joins the\n * existing share lockers and can. `tests/postgres-live.test.ts` checks both\n * orders with a pause inside the transaction (\"check-to-write\n * serialization\"), and that a later write queues behind a waiting purge.\n *\n * Other writes take only row locks. A claim takes `FOR UPDATE SKIP LOCKED`\n * on the rows it leases, which never waits, so concurrent claims never\n * lease one record twice. Fenced writes and settlements lock the record with\n * `FOR UPDATE`; an intent or denial insert locks its parent job with\n * `FOR SHARE`, so a reclaim (an UPDATE) cannot advance the parent's fence\n * between the lease check and the insert. \"call bounds while waiting for a\n * lock\" in the live tests holds each of these locks from another connection\n * and checks that an abort or an expired deadline during the wait commits\n * nothing.\n */\n\n/** Options for {@link PostgresWebhookDeliveryStore}. */\nexport interface PostgresWebhookDeliveryStoreOptions {\n\t/** The connection pool, for example a `pg.Pool`. The store never ends it. */\n\treadonly pool: WebhookPostgresPool;\n\t/** The store's clock: it timestamps requeue evidence and decides the replay horizon. */\n\treadonly clock: WebhookClock;\n\t/** The replay horizon in milliseconds; see `WebhookDeliveryLimits.replayHorizonMs`. */\n\treadonly replayHorizonMs: number;\n\t/**\n\t * The schema the tables live in, default `fabric_webhook_delivery`.\n\t * Lower-case letters, digits and underscores only. The horizon floor is\n\t * per schema: two stores on one schema share one floor.\n\t */\n\treadonly schema?: string;\n\t/**\n\t * Test seam, with the memory store's meaning: awaited once per call,\n\t * with the method name, after the input is read and before a connection\n\t * is taken. Leave it unset outside tests.\n\t */\n\treadonly beforeAtomicStep?: (operation: string) => Promise<void> | void;\n\t/**\n\t * Test seam for the serialization tests. Awaited inside the transaction\n\t * of each horizon-checked method and of the purge: at `locked`, after the\n\t * horizon lock, the purge-cutoff read and the record locks, and before\n\t * the clock is read or anything is written; and at `written`, after the\n\t * write and before the commit (a call that returns a refusal does not\n\t * reach it). A throw or rejection rolls the transaction back and fails\n\t * the call as `store_failed`. Leave it unset outside tests.\n\t */\n\treadonly transactionCheckpoint?: (operation: string, stage: WebhookTransactionCheckpointStage) => Promise<void> | void;\n}\n\ntype HorizonLock = \"share\" | \"exclusive\";\n\ninterface Tables {\n\treadonly horizon: string;\n\treadonly jobs: string;\n\treadonly intents: string;\n\treadonly tombstones: string;\n\treadonly denials: string;\n\treadonly attempts: string;\n\treadonly outcomes: string;\n\treadonly evidence: string;\n}\n\nfunction tablesIn(schema: string): Tables {\n\treturn {\n\t\thorizon: `${schema}.webhook_delivery_horizon`,\n\t\tjobs: `${schema}.webhook_fan_out_jobs`,\n\t\tintents: `${schema}.webhook_delivery_intents`,\n\t\ttombstones: `${schema}.webhook_delivery_tombstones`,\n\t\tdenials: `${schema}.webhook_admission_denials`,\n\t\tattempts: `${schema}.webhook_delivery_attempts`,\n\t\toutcomes: `${schema}.webhook_delivery_attempt_outcomes`,\n\t\tevidence: `${schema}.webhook_requeue_evidence`,\n\t};\n}\n\n/**\n * The delivery store's schema. Times are `bigint` epoch milliseconds, so\n * every instant a JavaScript `Date` can hold is stored exactly (a\n * `timestamptz` cannot hold years before 4713 BC, which a `Date` can).\n * Documents and free text are `json` columns holding the package\n * serializer's output (see `jsonOf`). `sort_key` columns hold\n * `utf16SortKey` of the record's key, so ties sort as in the memory store.\n */\nconst DELIVERY_MIGRATIONS: readonly WebhookPostgresMigration[] = Object.freeze([{\n\tversion: 1,\n\tname: \"delivery_baseline\",\n\tsql: `\n\t\tCREATE TABLE {{schema}}.webhook_delivery_horizon (\n\t\t\tsingleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n\t\t\tpurged_through_ms bigint\n\t\t);\n\t\tINSERT INTO {{schema}}.webhook_delivery_horizon (singleton, purged_through_ms) VALUES (true, NULL);\n\t\tCREATE TABLE {{schema}}.webhook_fan_out_jobs (\n\t\t\tevent_id text PRIMARY KEY,\n\t\t\tsort_key text COLLATE \"C\" NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tdraft json NOT NULL,\n\t\t\tanchor_ms bigint NOT NULL,\n\t\t\tstatus text NOT NULL CHECK (status IN ('pending', 'completed', 'dead_letter')),\n\t\t\tattempt_count integer NOT NULL,\n\t\t\tavailable_at_ms bigint NOT NULL,\n\t\t\tcreated_at_ms bigint NOT NULL,\n\t\t\tprocessing_deadline_ms bigint NOT NULL,\n\t\t\tcompleted_at_ms bigint,\n\t\t\tlast_diagnostic text,\n\t\t\tfence bigint NOT NULL,\n\t\t\tlease_owner text,\n\t\t\tlease_expires_at_ms bigint,\n\t\t\tCHECK ((lease_owner IS NULL) = (lease_expires_at_ms IS NULL))\n\t\t);\n\t\tCREATE INDEX webhook_fan_out_jobs_claim_idx ON {{schema}}.webhook_fan_out_jobs (available_at_ms, created_at_ms, sort_key) WHERE status = 'pending';\n\t\tCREATE INDEX webhook_fan_out_jobs_purge_idx ON {{schema}}.webhook_fan_out_jobs (anchor_ms) WHERE status <> 'pending';\n\t\tCREATE TABLE {{schema}}.webhook_delivery_intents (\n\t\t\tdelivery_id text PRIMARY KEY,\n\t\t\tsort_key text COLLATE \"C\" NOT NULL,\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tevent_id text NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\teligibility_revision bigint NOT NULL,\n\t\t\tbody json NOT NULL,\n\t\t\tanchor_ms bigint NOT NULL,\n\t\t\tstatus text NOT NULL CHECK (status IN ('pending', 'delivered', 'dead_letter', 'cancelled')),\n\t\t\tattempt_count integer NOT NULL,\n\t\t\tavailable_at_ms bigint NOT NULL,\n\t\t\tcreated_at_ms bigint NOT NULL,\n\t\t\tprocessing_deadline_ms bigint NOT NULL,\n\t\t\tlast_outcome text,\n\t\t\tlast_reason text,\n\t\t\tlast_diagnostic text,\n\t\t\tfence bigint NOT NULL,\n\t\t\tlease_owner text,\n\t\t\tlease_expires_at_ms bigint,\n\t\t\tCHECK ((lease_owner IS NULL) = (lease_expires_at_ms IS NULL)),\n\t\t\tCHECK ((last_outcome IS NULL) = (last_reason IS NULL))\n\t\t);\n\t\tCREATE INDEX webhook_delivery_intents_claim_idx ON {{schema}}.webhook_delivery_intents (available_at_ms, created_at_ms, sort_key) WHERE status = 'pending';\n\t\tCREATE INDEX webhook_delivery_intents_purge_idx ON {{schema}}.webhook_delivery_intents (anchor_ms) WHERE status <> 'pending';\n\t\tCREATE INDEX webhook_delivery_intents_subscription_idx ON {{schema}}.webhook_delivery_intents (tenant_id, space_id, subscription_id) WHERE status = 'pending';\n\t\tCREATE TABLE {{schema}}.webhook_delivery_tombstones (\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tevent_id text NOT NULL,\n\t\t\tkind text NOT NULL CHECK (kind IN ('intent', 'denial')),\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tanchor_ms bigint NOT NULL,\n\t\t\tPRIMARY KEY (subscription_id, event_id)\n\t\t);\n\t\tCREATE TABLE {{schema}}.webhook_admission_denials (\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tevent_id text NOT NULL,\n\t\t\tsort_key text COLLATE \"C\" NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\trecord json NOT NULL,\n\t\t\tanchor_ms bigint NOT NULL,\n\t\t\tPRIMARY KEY (subscription_id, event_id)\n\t\t);\n\t\tCREATE INDEX webhook_admission_denials_purge_idx ON {{schema}}.webhook_admission_denials (anchor_ms);\n\t\tCREATE TABLE {{schema}}.webhook_delivery_attempts (\n\t\t\tseq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n\t\t\tdelivery_id text NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\trecord json NOT NULL\n\t\t);\n\t\tCREATE INDEX webhook_delivery_attempts_intent_idx ON {{schema}}.webhook_delivery_attempts (delivery_id, seq);\n\t\tCREATE TABLE {{schema}}.webhook_requeue_evidence (\n\t\t\tseq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n\t\t\tevent_id text NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\trecord json NOT NULL\n\t\t);\n\t\tCREATE INDEX webhook_requeue_evidence_event_idx ON {{schema}}.webhook_requeue_evidence (event_id, seq);\n\t`,\n}, {\n\t// PR 8: an attempt begun under the intent's lease before the transport\n\t// handoff (fence and the SHA-256 digest of its receipt set), and its\n\t// outcome, appended once, unfenced, by the holder of the receipt.\n\tversion: 2,\n\tname: \"delivery_attempt_begin_finish\",\n\tsql: `\n\t\tALTER TABLE {{schema}}.webhook_delivery_attempts ADD COLUMN fence bigint;\n\t\tALTER TABLE {{schema}}.webhook_delivery_attempts ADD COLUMN receipt_digest text;\n\t\tALTER TABLE {{schema}}.webhook_delivery_attempts ADD CONSTRAINT webhook_delivery_attempts_receipt_check CHECK ((fence IS NULL) = (receipt_digest IS NULL));\n\t\tCREATE UNIQUE INDEX webhook_delivery_attempts_begun_idx ON {{schema}}.webhook_delivery_attempts (delivery_id, fence) WHERE fence IS NOT NULL;\n\t\tCREATE TABLE {{schema}}.webhook_delivery_attempt_outcomes (\n\t\t\tdelivery_id text NOT NULL,\n\t\t\tfence bigint NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\trecord json NOT NULL,\n\t\t\tPRIMARY KEY (delivery_id, fence)\n\t\t);\n\t`,\n}, {\n\t// PR 9: requeue and enrichment evidence indexed by the governed\n\t// invocation that appended it, so a re-run of that invocation finds it\n\t// inside its own transaction, and after the record it names is purged.\n\t// Rows written before this migration are backfilled from the record.\n\tversion: 3,\n\tname: \"requeue_evidence_invocation\",\n\tsql: `\n\t\tALTER TABLE {{schema}}.webhook_requeue_evidence ADD COLUMN action_invocation_id text;\n\t\tUPDATE {{schema}}.webhook_requeue_evidence SET action_invocation_id = record->>'actionInvocationId';\n\t\tCREATE INDEX webhook_requeue_evidence_invocation_idx ON {{schema}}.webhook_requeue_evidence (tenant_id, space_id, action_invocation_id, seq)\n\t\t\tWHERE action_invocation_id IS NOT NULL;\n\t`,\n}]);\n\nconst JOB_COLUMNS = [\n\t\"event_id\", \"tenant_id\", \"space_id\", \"draft::text AS draft\", \"anchor_ms::text AS anchor_ms\", \"status\",\n\t\"attempt_count::text AS attempt_count\", \"available_at_ms::text AS available_at_ms\", \"created_at_ms::text AS created_at_ms\",\n\t\"processing_deadline_ms::text AS processing_deadline_ms\", \"completed_at_ms::text AS completed_at_ms\", \"last_diagnostic\",\n\t\"fence::text AS fence\", \"lease_owner\", \"lease_expires_at_ms::text AS lease_expires_at_ms\",\n];\n\nconst INTENT_COLUMNS = [\n\t\"delivery_id\", \"subscription_id\", \"event_id\", \"tenant_id\", \"space_id\", \"eligibility_revision::text AS eligibility_revision\",\n\t\"body::text AS body\", \"anchor_ms::text AS anchor_ms\", \"status\", \"attempt_count::text AS attempt_count\",\n\t\"available_at_ms::text AS available_at_ms\", \"created_at_ms::text AS created_at_ms\",\n\t\"processing_deadline_ms::text AS processing_deadline_ms\", \"last_outcome\", \"last_reason\", \"last_diagnostic\",\n\t\"fence::text AS fence\", \"lease_owner\", \"lease_expires_at_ms::text AS lease_expires_at_ms\",\n];\n\nfunction columns(list: readonly string[], alias?: string): string {\n\treturn list.map((column) => (alias === undefined ? column : `${alias}.${column}`)).join(\", \");\n}\n\ntype Row = Record<string, unknown>;\n\n/** Hydrate a job row into the shared state shape, copying each field. */\nfunction jobFrom(row: Row): JobState {\n\tconst fence = intOf(row[\"fence\"], \"row.fence\");\n\tconst owner = optionalTextOf(row[\"lease_owner\"], \"row.lease_owner\");\n\treturn {\n\t\tkey: textOf(row[\"event_id\"], \"row.event_id\"),\n\t\tdraft: jsonOf(row[\"draft\"], \"row.draft\") as Snapshot,\n\t\ttenantId: textOf(row[\"tenant_id\"], \"row.tenant_id\"),\n\t\tspaceId: textOf(row[\"space_id\"], \"row.space_id\"),\n\t\tanchorMs: intOf(row[\"anchor_ms\"], \"row.anchor_ms\"),\n\t\tstatus: textOf(row[\"status\"], \"row.status\") as JobState[\"status\"],\n\t\tattemptCount: intOf(row[\"attempt_count\"], \"row.attempt_count\"),\n\t\tavailableAtMs: intOf(row[\"available_at_ms\"], \"row.available_at_ms\"),\n\t\tcreatedAtMs: intOf(row[\"created_at_ms\"], \"row.created_at_ms\"),\n\t\tprocessingDeadlineMs: intOf(row[\"processing_deadline_ms\"], \"row.processing_deadline_ms\"),\n\t\tcompletedAtMs: optionalIntOf(row[\"completed_at_ms\"], \"row.completed_at_ms\"),\n\t\tlastDiagnostic: optionalTextOf(row[\"last_diagnostic\"], \"row.last_diagnostic\") as WebhookDiagnosticCode | undefined,\n\t\tfence,\n\t\tlease: owner === undefined ? undefined : { owner, fence, expiresAtMs: intOf(row[\"lease_expires_at_ms\"], \"row.lease_expires_at_ms\") },\n\t};\n}\n\n/** Hydrate an intent row into the shared state shape, copying each field. */\nfunction intentFrom(row: Row): IntentState {\n\tconst fence = intOf(row[\"fence\"], \"row.fence\");\n\tconst owner = optionalTextOf(row[\"lease_owner\"], \"row.lease_owner\");\n\tconst outcome = optionalTextOf(row[\"last_outcome\"], \"row.last_outcome\");\n\treturn {\n\t\tkey: textOf(row[\"delivery_id\"], \"row.delivery_id\"),\n\t\tsubscriptionId: textOf(row[\"subscription_id\"], \"row.subscription_id\"),\n\t\teventId: textOf(row[\"event_id\"], \"row.event_id\"),\n\t\ttenantId: textOf(row[\"tenant_id\"], \"row.tenant_id\"),\n\t\tspaceId: textOf(row[\"space_id\"], \"row.space_id\"),\n\t\teligibilityRevision: intOf(row[\"eligibility_revision\"], \"row.eligibility_revision\"),\n\t\tbody: textOf(jsonOf(row[\"body\"], \"row.body\"), \"row.body\"),\n\t\tanchorMs: intOf(row[\"anchor_ms\"], \"row.anchor_ms\"),\n\t\tstatus: textOf(row[\"status\"], \"row.status\") as IntentState[\"status\"],\n\t\tattemptCount: intOf(row[\"attempt_count\"], \"row.attempt_count\"),\n\t\tavailableAtMs: intOf(row[\"available_at_ms\"], \"row.available_at_ms\"),\n\t\tcreatedAtMs: intOf(row[\"created_at_ms\"], \"row.created_at_ms\"),\n\t\tprocessingDeadlineMs: intOf(row[\"processing_deadline_ms\"], \"row.processing_deadline_ms\"),\n\t\tlastOutcome: outcome === undefined\n\t\t\t? undefined\n\t\t\t: { outcome: outcome as NonNullable<IntentState[\"lastOutcome\"]>[\"outcome\"], reason: textOf(row[\"last_reason\"], \"row.last_reason\") as NonNullable<IntentState[\"lastOutcome\"]>[\"reason\"] },\n\t\tlastDiagnostic: optionalTextOf(row[\"last_diagnostic\"], \"row.last_diagnostic\") as WebhookDiagnosticCode | undefined,\n\t\tfence,\n\t\tlease: owner === undefined ? undefined : { owner, fence, expiresAtMs: intOf(row[\"lease_expires_at_ms\"], \"row.lease_expires_at_ms\") },\n\t};\n}\n\n/** Claimed rows in the memory store's claim order: `availableAt`, then `createdAt`, then key. */\nfunction claimOrder<T extends { readonly availableAtMs: number; readonly createdAtMs: number; readonly key: string }>(states: T[]): T[] {\n\treturn states.sort((left, right) => left.availableAtMs - right.availableAtMs || left.createdAtMs - right.createdAtMs || compareText(left.key, right.key));\n}\n\n/**\n * A PostgreSQL {@link WebhookDeliveryStore}. Call {@link ensureSchema} once\n * before use, at startup or from a migration step.\n *\n * @throws {WebhookDeliveryConfigError} when `replayHorizonMs` is not a\n * positive whole number of milliseconds within `WEBHOOK_MAX_REPLAY_HORIZON_MS`.\n * @throws {WebhookStoreError} `clock_invalid` when `clock` has no `now`\n * function; `input_invalid` when `pool`, `schema` or a test seam is not usable.\n */\nexport class PostgresWebhookDeliveryStore implements WebhookDeliveryStore {\n\treadonly #pool: WebhookPostgresPool;\n\treadonly #clock: CapturedClock;\n\treadonly #horizonMs: number;\n\treadonly #schema: string;\n\treadonly #t: Tables;\n\treadonly #beforeAtomicStep: ((operation: string) => Promise<void> | void) | undefined;\n\treadonly #checkpoint: ((operation: string, stage: WebhookTransactionCheckpointStage) => Promise<void> | void) | undefined;\n\n\tconstructor(options: PostgresWebhookDeliveryStoreOptions) {\n\t\tthis.#horizonMs = readHorizonOption(options);\n\t\tthis.#clock = guard(() => captureClock((options as { clock?: WebhookClock }).clock), () => storeError(\"clock_invalid\", \"clock\"));\n\t\tthis.#pool = readPoolOption(options);\n\t\tthis.#schema = readSchemaOption(options);\n\t\tthis.#t = tablesIn(this.#schema);\n\t\tthis.#beforeAtomicStep = readHookOption(options, \"beforeAtomicStep\");\n\t\tthis.#checkpoint = readHookOption(options, \"transactionCheckpoint\");\n\t}\n\n\t/** The replay horizon this store enforces, in milliseconds. */\n\tget replayHorizonMs(): number {\n\t\treturn this.#horizonMs;\n\t}\n\n\t/**\n\t * Create the schema and tables, or check that the applied migrations are\n\t * unchanged. Safe to call concurrently and repeatedly: an advisory lock\n\t * serializes callers and each migration is recorded once\n\t * (`applyWebhookMigrations` in src/postgres-sql.ts).\n\t */\n\tasync ensureSchema(): Promise<void> {\n\t\tawait applyWebhookMigrations(this.#pool, this.#schema, \"delivery\", DELIVERY_MIGRATIONS);\n\t}\n\n\t#boundary(operation: string): Promise<void> {\n\t\tconst hook = this.#beforeAtomicStep;\n\t\treturn awaitHook(hook === undefined ? undefined : () => hook(operation), \"beforeAtomicStep\");\n\t}\n\n\t#pause(operation: string, stage: WebhookTransactionCheckpointStage): Promise<void> {\n\t\tconst hook = this.#checkpoint;\n\t\treturn awaitHook(hook === undefined ? undefined : () => hook(operation, stage), \"transactionCheckpoint\");\n\t}\n\n\t/**\n\t * One write (`runWrite` in src/postgres-sql.ts). `lock` takes every lock\n\t * and runs every statement that can wait; the clock and the call bounds\n\t * are read only after it returns; `body` decides and finishes.\n\t */\n\tasync #write<L, T>(\n\t\toperation: string,\n\t\tbounds: CallBounds,\n\t\tlock: (tx: WebhookPostgresQueryable) => Promise<L>,\n\t\tbody: (tx: WebhookPostgresQueryable, nowMs: number, locked: L, control: WebhookTransactionControl) => Promise<T>,\n\t): Promise<T> {\n\t\tawait this.#boundary(operation);\n\t\treturn runWrite(this.#pool, this.#clock, bounds, lock, body);\n\t}\n\n\t/**\n\t * The horizon table lock, always the first statement of the transaction\n\t * that takes it, then the highest purge cutoff. While the lock is held the\n\t * cutoff cannot change, so it can be read before the record locks.\n\t */\n\tasync #lockHorizon(tx: WebhookPostgresQueryable, mode: HorizonLock): Promise<number> {\n\t\tawait tx.query(`LOCK TABLE ${this.#t.horizon} IN ${mode === \"share\" ? \"SHARE\" : \"EXCLUSIVE\"} MODE`);\n\t\tconst result = await tx.query(`SELECT purged_through_ms::text AS purged_through_ms FROM ${this.#t.horizon}`);\n\t\tconst row = result.rows[0];\n\t\tif (row === undefined) throw storeError(\"store_failed\", \"horizon\");\n\t\treturn optionalIntOf(row[\"purged_through_ms\"], \"horizon.purged_through_ms\") ?? -Infinity;\n\t}\n\n\t/** The horizon floor at `nowMs`, given the highest purge cutoff read under the horizon lock. */\n\t#floorMs(nowMs: number, purgedThroughMs: number): number {\n\t\treturn mathMax(nowMs - this.#horizonMs, purgedThroughMs);\n\t}\n\n\tasync #read<T>(operation: string, bounds: CallBounds, body: (db: WebhookPostgresQueryable) => Promise<T>): Promise<T> {\n\t\tawait this.#boundary(operation);\n\t\treturn runRead(this.#pool, this.#clock, bounds, (db) => body(db));\n\t}\n\n\tasync #lockJob(tx: WebhookPostgresQueryable, eventId: string, lock: \"UPDATE\" | \"SHARE\"): Promise<JobState | undefined> {\n\t\tconst result = await tx.query(`SELECT ${columns(JOB_COLUMNS)} FROM ${this.#t.jobs} WHERE event_id = $1 FOR ${lock}`, [eventId]);\n\t\treturn result.rows[0] === undefined ? undefined : jobFrom(result.rows[0]);\n\t}\n\n\tasync #lockIntent(tx: WebhookPostgresQueryable, deliveryId: string): Promise<IntentState | undefined> {\n\t\tconst result = await tx.query(`SELECT ${columns(INTENT_COLUMNS)} FROM ${this.#t.intents} WHERE delivery_id = $1 FOR UPDATE`, [deliveryId]);\n\t\treturn result.rows[0] === undefined ? undefined : intentFrom(result.rows[0]);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Fan-out jobs\n\t// -------------------------------------------------------------------------\n\n\tasync insertFanOutJob(\n\t\tjob: WebhookFanOutJobDraft & { readonly processingDeadline: string; readonly createdAt: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookInsertResult> {\n\t\tconst call = readInsertFanOutJobCall(job, options);\n\t\tconst draft = call.job;\n\t\treturn this.#write(\n\t\t\t\"insertFanOutJob\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tawait this.#pause(\"insertFanOutJob\", \"locked\");\n\t\t\t\t// Tentative: the conflict check can wait on a concurrent insert of\n\t\t\t\t// the same eventId, so it runs before the clock is read. The body\n\t\t\t\t// rolls it back if the event turns out past the horizon.\n\t\t\t\tconst inserted = await tx.query(\n\t\t\t\t\t`INSERT INTO ${this.#t.jobs}\n\t\t\t\t\t (event_id, sort_key, tenant_id, space_id, draft, anchor_ms, status, attempt_count,\n\t\t\t\t\t available_at_ms, created_at_ms, processing_deadline_ms, fence)\n\t\t\t\t\t VALUES ($1, $2, $3, $4, $5::json, $6, 'pending', 0, $7, $7, $8, 0)\n\t\t\t\t\t ON CONFLICT (event_id) DO NOTHING RETURNING event_id`,\n\t\t\t\t\t[draft.eventId, utf16SortKey(draft.eventId), draft.tenantId, draft.spaceId, serializeJson(draft.draft), draft.anchorMs, draft.createdAtMs, draft.processingDeadlineMs],\n\t\t\t\t);\n\t\t\t\treturn { purgedThroughMs, inserted: inserted.rows.length === 1 };\n\t\t\t},\n\t\t\tasync (_tx, nowMs, locked, control) => {\n\t\t\t\t// Horizon first, so the answer for an old event does not depend on\n\t\t\t\t// whether a purge has removed its job yet.\n\t\t\t\tif (draft.anchorMs < this.#floorMs(nowMs, locked.purgedThroughMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn copyOut<WebhookInsertResult>({ outcome: \"past_horizon\" });\n\t\t\t\t}\n\t\t\t\tawait this.#pause(\"insertFanOutJob\", \"written\");\n\t\t\t\treturn copyOut<WebhookInsertResult>({ outcome: locked.inserted ? \"inserted\" : \"already_present\" });\n\t\t\t},\n\t\t);\n\t}\n\n\tasync claimFanOutJobs(request: WebhookClaimRequest, options: WebhookCallOptions): Promise<readonly WebhookFanOutJob[]> {\n\t\tconst call = readClaimCall(request, options);\n\t\tconst claim = call.claim;\n\t\treturn this.#write(\n\t\t\t\"claimFanOutJobs\",\n\t\t\tcall.bounds,\n\t\t\t// SKIP LOCKED never waits; it leaves rows another transaction holds.\n\t\t\tasync (tx) => (await tx.query(\n\t\t\t\t`SELECT event_id FROM ${this.#t.jobs}\n\t\t\t\t WHERE status = 'pending' AND available_at_ms <= $1\n\t\t\t\t AND (lease_owner IS NULL OR lease_expires_at_ms <= $1)\n\t\t\t\t ORDER BY available_at_ms, created_at_ms, sort_key\n\t\t\t\t LIMIT $2\n\t\t\t\t FOR UPDATE SKIP LOCKED`,\n\t\t\t\t[claim.nowMs, claim.limit],\n\t\t\t)).rows.map((row) => textOf(row[\"event_id\"], \"row.event_id\")),\n\t\t\tasync (tx, _nowMs, picked) => {\n\t\t\t\tif (picked.length === 0) return frozenList<WebhookFanOutJob>([]);\n\t\t\t\tconst result = await tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.jobs} AS job\n\t\t\t\t\t SET fence = job.fence + 1, lease_owner = $2, lease_expires_at_ms = $3\n\t\t\t\t\t WHERE job.event_id = ANY($1::text[])\n\t\t\t\t\t RETURNING ${columns(JOB_COLUMNS, \"job\")}`,\n\t\t\t\t\t[picked, claim.workerId, claim.nowMs + claim.leaseDurationMs],\n\t\t\t\t);\n\t\t\t\tconst states = claimOrder(result.rows.map(jobFrom));\n\t\t\t\treturn frozenList(states.map((state) => copyOut<WebhookFanOutJob>(jobOut(state))));\n\t\t\t},\n\t\t);\n\t}\n\n\t/**\n\t * A fenced job write: the job is locked `FOR UPDATE` before the clock is\n\t * read; `change` runs only when the caller still holds the lease.\n\t */\n\t#fencedJobWrite(\n\t\toperation: string,\n\t\tbounds: CallBounds,\n\t\teventId: string,\n\t\tfenced: { readonly owner: string; readonly fence: number },\n\t\tchange: (tx: WebhookPostgresQueryable, job: JobState) => Promise<void>,\n\t): Promise<boolean> {\n\t\treturn this.#write(operation, bounds, (tx) => this.#lockJob(tx, eventId, \"UPDATE\"), async (tx, nowMs, job) => {\n\t\t\tif (job === undefined || !holds(job, fenced.owner, fenced.fence, nowMs)) return false;\n\t\t\tawait change(tx, job);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync completeFanOutJob(input: WebhookFencedWrite & { readonly eventId: string }, options: WebhookCallOptions): Promise<boolean> {\n\t\tconst call = readJobFencedCall(input, options);\n\t\treturn this.#fencedJobWrite(\"completeFanOutJob\", call.bounds, call.eventId, call.fenced, async (tx) => {\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t SET status = 'completed', completed_at_ms = $2, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t[call.eventId, call.fenced.nowMs],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync rescheduleFanOutJob(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly availableAt: Date; readonly diagnostic: WebhookDiagnosticCode },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRescheduleCall(input, options);\n\t\treturn this.#fencedJobWrite(\"rescheduleFanOutJob\", call.bounds, call.eventId, call.fenced, async (tx) => {\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t SET attempt_count = attempt_count + 1, available_at_ms = $2, last_diagnostic = $3,\n\t\t\t\t lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t[call.eventId, call.availableAtMs, call.diagnostic],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync renewFanOutJobLease(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly leaseDurationMs: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRenewJobCall(input, options);\n\t\treturn this.#fencedJobWrite(\"renewFanOutJobLease\", call.bounds, call.eventId, call.fenced, async (tx, job) => {\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.jobs} SET lease_expires_at_ms = $2 WHERE event_id = $1`,\n\t\t\t\t[call.eventId, renewedExpiryMs(job, call.fenced.nowMs, call.leaseDurationMs)],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync deadLetterFanOutJob(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly diagnostic: WebhookDiagnosticCode },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readDeadLetterJobCall(input, options);\n\t\treturn this.#fencedJobWrite(\"deadLetterFanOutJob\", call.bounds, call.eventId, call.fenced, async (tx) => {\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t SET status = 'dead_letter', last_diagnostic = $2, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t[call.eventId, call.diagnostic],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync requeueFanOutJob(\n\t\tinput: WebhookScope & { readonly eventId: string; readonly request: WebhookRequeueRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookRequeueResult> {\n\t\tconst call = readJobRequeueCall(input, options);\n\t\treturn this.#write(\n\t\t\t\"requeueFanOutJob\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst job = await this.#lockJob(tx, call.eventId, \"UPDATE\");\n\t\t\t\tconst prior = await this.#priorEvidence(tx, call.scope, call.request.actionInvocationId, { target: \"fan_out_job\", eventId: call.eventId });\n\t\t\t\tawait this.#pause(\"requeueFanOutJob\", \"locked\");\n\t\t\t\treturn { purgedThroughMs, job, prior };\n\t\t\t},\n\t\t\tasync (tx, nowMs, { purgedThroughMs, job, prior }) => {\n\t\t\t\tif (prior !== undefined) return replayedResult<WebhookRequeueResult>(prior);\n\t\t\t\tif (job === undefined || !inScope(job, call.scope)) return requeueRefused(\"not_found\");\n\t\t\t\tconst refusal = requeueRefusal(job, call.request, this.#floorMs(nowMs, purgedThroughMs));\n\t\t\t\tif (refusal !== undefined) return requeueRefused(refusal);\n\t\t\t\tconst evidence = jobRequeueEvidence(job, call.request, nowMs);\n\t\t\t\tconst result = copyOut<WebhookRequeueResult>({ applied: true, evidence });\n\t\t\t\tapplyRequeue(job, call.request);\n\t\t\t\tawait tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t\t SET status = 'pending', attempt_count = $2, available_at_ms = $3, processing_deadline_ms = $4,\n\t\t\t\t\t fence = $5, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t\t[job.key, job.attemptCount, job.availableAtMs, job.processingDeadlineMs, job.fence],\n\t\t\t\t);\n\t\t\t\tawait this.#appendEvidence(tx, job.key, job.tenantId, job.spaceId, evidence);\n\t\t\t\tawait this.#pause(\"requeueFanOutJob\", \"written\");\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n\tasync enrichFanOutJobActor(\n\t\tinput: WebhookScope & { readonly eventId: string; readonly request: WebhookActorEnrichmentRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookActorEnrichmentResult> {\n\t\tconst call = readJobEnrichmentCall(input, options);\n\t\treturn this.#write(\n\t\t\t\"enrichFanOutJobActor\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst job = await this.#lockJob(tx, call.eventId, \"UPDATE\");\n\t\t\t\tconst prior = await this.#priorEvidence(tx, call.scope, call.request.actionInvocationId, { target: \"fan_out_job_actor\", eventId: call.eventId });\n\t\t\t\tawait this.#pause(\"enrichFanOutJobActor\", \"locked\");\n\t\t\t\treturn { purgedThroughMs, job, prior };\n\t\t\t},\n\t\t\tasync (tx, nowMs, { purgedThroughMs, job, prior }) => {\n\t\t\t\tif (prior !== undefined) return replayedResult<WebhookActorEnrichmentResult>(prior);\n\t\t\t\tif (job === undefined || !inScope(job, call.scope)) return enrichmentRefused(\"not_found\");\n\t\t\t\tconst refusal = enrichmentRefusal(job, call.request, this.#floorMs(nowMs, purgedThroughMs));\n\t\t\t\tif (refusal !== undefined) return enrichmentRefused(refusal);\n\t\t\t\tconst evidence = jobEnrichmentEvidence(job, call.request, nowMs);\n\t\t\t\tconst result = copyOut<WebhookActorEnrichmentResult>({ applied: true, evidence });\n\t\t\t\tapplyEnrichment(job, call.request);\n\t\t\t\tawait tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t\t SET draft = $2::json, status = 'pending', attempt_count = $3, available_at_ms = $4, processing_deadline_ms = $5,\n\t\t\t\t\t fence = $6, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t\t[job.key, serializeJson(job.draft), job.attemptCount, job.availableAtMs, job.processingDeadlineMs, job.fence],\n\t\t\t\t);\n\t\t\t\tawait this.#appendEvidence(tx, job.key, job.tenantId, job.spaceId, evidence);\n\t\t\t\tawait this.#pause(\"enrichFanOutJobActor\", \"written\");\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n\n\tasync #appendEvidence(tx: WebhookPostgresQueryable, eventId: string, tenantId: string, spaceId: string, evidence: WebhookRequeueEvidence): Promise<void> {\n\t\tawait tx.query(\n\t\t\t`INSERT INTO ${this.#t.evidence} (event_id, tenant_id, space_id, record, action_invocation_id) VALUES ($1, $2, $3, $4::json, $5)`,\n\t\t\t[eventId, tenantId, spaceId, serializeJson(evidence), evidence.actionInvocationId ?? null],\n\t\t);\n\t}\n\n\t/**\n\t * Evidence `scope` holds under `actionInvocationId` for `target`, or\n\t * `undefined` (always, without an id). Called in a requeue's or\n\t * enrichment's transaction after its record lock: a concurrent request of\n\t * the same invocation that applied holds that lock until it commits, and\n\t * under READ COMMITTED this statement then sees its evidence. See\n\t * \"Re-runs of one invocation\" in src/ports.ts.\n\t */\n\tasync #priorEvidence(tx: WebhookPostgresQueryable, scope: WebhookScope, actionInvocationId: string | undefined, target: InvocationTarget): Promise<Snapshot | undefined> {\n\t\tif (actionInvocationId === undefined) return undefined;\n\t\tconst result = await tx.query(\n\t\t\t`SELECT record::text AS record FROM ${this.#t.evidence}\n\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND action_invocation_id = $3 ORDER BY seq`,\n\t\t\t[scope.tenantId, scope.spaceId, actionInvocationId],\n\t\t);\n\t\treturn priorInvocationEvidence(result.rows.map((row) => jsonOf(row[\"record\"], \"row.record\") as Snapshot), target);\n\t}\n\n\tasync readFanOutJob(input: WebhookScope & { readonly eventId: string }, options: WebhookCallOptions): Promise<WebhookFanOutJob | null> {\n\t\tconst call = readEventCall(input, options);\n\t\treturn this.#read(\"readFanOutJob\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT ${columns(JOB_COLUMNS)} FROM ${this.#t.jobs} WHERE event_id = $1 AND tenant_id = $2 AND space_id = $3`,\n\t\t\t\t[call.eventId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\treturn result.rows[0] === undefined ? null : copyOut<WebhookFanOutJob>(jobOut(jobFrom(result.rows[0])));\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Intents and denials\n\t// -------------------------------------------------------------------------\n\n\tasync insertDeliveryIntent(\n\t\tintent: Omit<WebhookDeliveryIntent, \"status\" | \"attemptCount\" | \"lastOutcome\" | \"lastDiagnostic\" | \"lease\" | \"eventRecordedAt\" | \"fence\">,\n\t\tparent: WebhookFanOutJobFence,\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookFencedInsertResult> {\n\t\tconst call = readInsertIntentCall(intent, parent, options);\n\t\treturn this.#write(\n\t\t\t\"insertDeliveryIntent\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst job = await this.#parentJob(tx, call.parent);\n\t\t\t\tawait this.#pause(\"insertDeliveryIntent\", \"locked\");\n\t\t\t\t// Tentative inserts, only when the clock-free checks pass: the\n\t\t\t\t// tombstone's and the intent's conflict checks can wait on a\n\t\t\t\t// concurrent insert, so they run before the clock is read.\n\t\t\t\tif (job === undefined || !inScope(job, call)) return { purgedThroughMs, job, tombstone: false, inserted: false };\n\t\t\t\tconst tombstone = await this.#insertTombstone(tx, \"intent\", call, job.anchorMs);\n\t\t\t\tconst inserted = tombstone && (await tx.query(\n\t\t\t\t\t`INSERT INTO ${this.#t.intents}\n\t\t\t\t\t (delivery_id, sort_key, subscription_id, event_id, tenant_id, space_id, eligibility_revision, body,\n\t\t\t\t\t anchor_ms, status, attempt_count, available_at_ms, created_at_ms, processing_deadline_ms, fence)\n\t\t\t\t\t VALUES ($1, $2, $3, $4, $5, $6, $7, $8::json, $9, 'pending', 0, $10, $11, $12, 0)\n\t\t\t\t\t ON CONFLICT (delivery_id) DO NOTHING RETURNING delivery_id`,\n\t\t\t\t\t[call.deliveryId, utf16SortKey(call.deliveryId), call.subscriptionId, call.eventId, call.tenantId, call.spaceId,\n\t\t\t\t\t\tcall.eligibilityRevision, serializeJson(call.body), job.anchorMs, call.availableAtMs, call.createdAtMs, call.processingDeadlineMs],\n\t\t\t\t)).rows.length === 1;\n\t\t\t\treturn { purgedThroughMs, job, tombstone, inserted };\n\t\t\t},\n\t\t\tasync (_tx, nowMs, locked, control) => {\n\t\t\t\t// The memory store's order: lease, scope, horizon, uniqueness, deliveryId.\n\t\t\t\tconst job = locked.job;\n\t\t\t\tif (job === undefined) return fencedOutcome(\"lease_lost\");\n\t\t\t\t// Expiry is judged here, on the store's clock read after every lock.\n\t\t\t\tif (!holds(job, call.parent.owner, call.parent.fence, nowMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn fencedOutcome(\"lease_lost\");\n\t\t\t\t}\n\t\t\t\tif (!inScope(job, call)) throw storeError(\"record_mismatch\", \"intent.tenantId\");\n\t\t\t\tif (job.anchorMs < this.#floorMs(nowMs, locked.purgedThroughMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn fencedOutcome(\"past_horizon\");\n\t\t\t\t}\n\t\t\t\tif (!locked.tombstone) return fencedOutcome(\"already_present\");\n\t\t\t\t// The tombstone written above is rolled back with this throw.\n\t\t\t\tif (!locked.inserted) throw storeError(\"delivery_id_conflict\", \"intent.deliveryId\");\n\t\t\t\tawait this.#pause(\"insertDeliveryIntent\", \"written\");\n\t\t\t\treturn fencedOutcome(\"inserted\");\n\t\t\t},\n\t\t);\n\t}\n\n\tasync recordAdmissionDenial(\n\t\trecord: WebhookAdmissionDenialRecord,\n\t\tparent: WebhookFanOutJobFence,\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookFencedInsertResult> {\n\t\tconst call = readDenialCall(record, parent, options);\n\t\treturn this.#write(\n\t\t\t\"recordAdmissionDenial\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst job = await this.#parentJob(tx, call.parent);\n\t\t\t\tawait this.#pause(\"recordAdmissionDenial\", \"locked\");\n\t\t\t\tif (job === undefined || !inScope(job, call)) return { purgedThroughMs, job, tombstone: false };\n\t\t\t\t// Tentative, as in insertDeliveryIntent. Once the tombstone is ours,\n\t\t\t\t// no other transaction can be inserting this pair's denial.\n\t\t\t\tconst tombstone = await this.#insertTombstone(tx, \"denial\", call, job.anchorMs);\n\t\t\t\tif (tombstone) {\n\t\t\t\t\tawait tx.query(\n\t\t\t\t\t\t`INSERT INTO ${this.#t.denials} (subscription_id, event_id, sort_key, tenant_id, space_id, record, anchor_ms)\n\t\t\t\t\t\t VALUES ($1, $2, $3, $4, $5, $6::json, $7)`,\n\t\t\t\t\t\t[call.subscriptionId, call.eventId, utf16SortKey(markerKey(call.subscriptionId, call.eventId)), call.tenantId, call.spaceId,\n\t\t\t\t\t\t\tserializeJson(denialRecord(call)), job.anchorMs],\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { purgedThroughMs, job, tombstone };\n\t\t\t},\n\t\t\tasync (_tx, nowMs, locked, control) => {\n\t\t\t\tconst job = locked.job;\n\t\t\t\tif (job === undefined) return fencedOutcome(\"lease_lost\");\n\t\t\t\t// Expiry is judged here, on the store's clock read after every lock.\n\t\t\t\tif (!holds(job, call.parent.owner, call.parent.fence, nowMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn fencedOutcome(\"lease_lost\");\n\t\t\t\t}\n\t\t\t\tif (!inScope(job, call)) throw storeError(\"record_mismatch\", \"record.tenantId\");\n\t\t\t\tif (job.anchorMs < this.#floorMs(nowMs, locked.purgedThroughMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn fencedOutcome(\"past_horizon\");\n\t\t\t\t}\n\t\t\t\tif (!locked.tombstone) return fencedOutcome(\"already_present\");\n\t\t\t\tawait this.#pause(\"recordAdmissionDenial\", \"written\");\n\t\t\t\treturn fencedOutcome(\"inserted\");\n\t\t\t},\n\t\t);\n\t}\n\n\t/**\n\t * The parent job if `fence` still holds its lease, expiry not yet\n\t * judged: that needs the store's clock, which is read only after every\n\t * lock is held, so the insert's body checks it (`holds`) and rolls the\n\t * tentative insert back when the lease has expired. `FOR SHARE` keeps a\n\t * reclaim, a completion or any other update of the job waiting until\n\t * this transaction ends, while other inserts under the same lease proceed.\n\t */\n\tasync #parentJob(tx: WebhookPostgresQueryable, fence: WebhookFanOutJobFence): Promise<JobState | undefined> {\n\t\tconst job = await this.#lockJob(tx, fence.eventId, \"SHARE\");\n\t\treturn job !== undefined && holdsFence(job, fence.owner, fence.fence) ? job : undefined;\n\t}\n\n\t/**\n\t * Insert the (subscriptionId, eventId) tombstone, or report that one\n\t * exists. A concurrent insert of the same pair waits on the primary key\n\t * and then finds it, so of two racing inserts exactly one gets `true`.\n\t */\n\tasync #insertTombstone(\n\t\ttx: WebhookPostgresQueryable,\n\t\tkind: MarkerState[\"kind\"],\n\t\tcall: { readonly subscriptionId: string; readonly eventId: string; readonly tenantId: string; readonly spaceId: string },\n\t\tanchorMs: number,\n\t): Promise<boolean> {\n\t\tconst result = await tx.query(\n\t\t\t`INSERT INTO ${this.#t.tombstones} (subscription_id, event_id, kind, tenant_id, space_id, anchor_ms)\n\t\t\t VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (subscription_id, event_id) DO NOTHING RETURNING event_id`,\n\t\t\t[call.subscriptionId, call.eventId, kind, call.tenantId, call.spaceId, anchorMs],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync claimDeliveryIntents(request: WebhookClaimRequest, options: WebhookCallOptions): Promise<readonly WebhookDeliveryIntent[]> {\n\t\tconst call = readClaimCall(request, options);\n\t\tconst claim = call.claim;\n\t\treturn this.#write(\n\t\t\t\"claimDeliveryIntents\",\n\t\t\tcall.bounds,\n\t\t\t// SKIP LOCKED never waits; it leaves rows another transaction holds.\n\t\t\tasync (tx) => (await tx.query(\n\t\t\t\t`SELECT delivery_id FROM ${this.#t.intents}\n\t\t\t\t WHERE status = 'pending' AND available_at_ms <= $1\n\t\t\t\t AND (lease_owner IS NULL OR lease_expires_at_ms <= $1)\n\t\t\t\t ORDER BY available_at_ms, created_at_ms, sort_key\n\t\t\t\t LIMIT $2\n\t\t\t\t FOR UPDATE SKIP LOCKED`,\n\t\t\t\t[claim.nowMs, claim.limit],\n\t\t\t)).rows.map((row) => textOf(row[\"delivery_id\"], \"row.delivery_id\")),\n\t\t\tasync (tx, _nowMs, picked) => {\n\t\t\t\tif (picked.length === 0) return frozenList<WebhookDeliveryIntent>([]);\n\t\t\t\tconst result = await tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.intents} AS intent\n\t\t\t\t\t SET fence = intent.fence + 1, lease_owner = $2, lease_expires_at_ms = $3\n\t\t\t\t\t WHERE intent.delivery_id = ANY($1::text[])\n\t\t\t\t\t RETURNING ${columns(INTENT_COLUMNS, \"intent\")}`,\n\t\t\t\t\t[picked, claim.workerId, claim.nowMs + claim.leaseDurationMs],\n\t\t\t\t);\n\t\t\t\tconst states = claimOrder(result.rows.map(intentFrom));\n\t\t\t\treturn frozenList(states.map((state) => copyOut<WebhookDeliveryIntent>(intentOut(state))));\n\t\t\t},\n\t\t);\n\t}\n\n\tasync renewDeliveryIntentLease(\n\t\tinput: WebhookFencedWrite & { readonly deliveryId: string; readonly leaseDurationMs: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRenewIntentCall(input, options);\n\t\t// Locked FOR UPDATE first; whether the caller holds the lease is decided on the store's clock read after the lock.\n\t\treturn this.#write(\"renewDeliveryIntentLease\", call.bounds, (tx) => this.#lockIntent(tx, call.deliveryId), async (tx, nowMs, intent) => {\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.intents} SET lease_expires_at_ms = $2 WHERE delivery_id = $1`,\n\t\t\t\t[intent.key, renewedExpiryMs(intent, call.fenced.nowMs, call.leaseDurationMs)],\n\t\t\t);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync checkDeliveryLease(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly owner: string; readonly fence: number; readonly now: Date },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookDeliveryLeaseCheck> {\n\t\tconst call = readLeaseCheckCall(input, options);\n\t\t// One statement on the pool: it reads the committed current row on the\n\t\t// primary the pool is connected to, and changes nothing.\n\t\treturn this.#read(\"checkDeliveryLease\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(`SELECT ${columns(INTENT_COLUMNS)} FROM ${this.#t.intents} WHERE delivery_id = $1`, [call.deliveryId]);\n\t\t\treturn leaseCheck(result.rows[0] === undefined ? undefined : intentFrom(result.rows[0]), call);\n\t\t});\n\t}\n\n\tasync appendAttempt(input: WebhookFencedWrite & { readonly attempt: WebhookDeliveryAttemptRecord }, options: WebhookCallOptions): Promise<boolean> {\n\t\tconst call = readAppendAttemptCall(input, options);\n\t\treturn this.#write(\"appendAttempt\", call.bounds, (tx) => this.#lockIntent(tx, call.deliveryId), async (tx, nowMs, intent) => {\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tif (call.subscriptionId !== intent.subscriptionId) throw storeError(\"record_mismatch\", \"input.attempt.subscriptionId\");\n\t\t\tif (call.eventId !== intent.eventId) throw storeError(\"record_mismatch\", \"input.attempt.eventId\");\n\t\t\tawait tx.query(\n\t\t\t\t`INSERT INTO ${this.#t.attempts} (delivery_id, tenant_id, space_id, record) VALUES ($1, $2, $3, $4::json)`,\n\t\t\t\t[call.deliveryId, intent.tenantId, intent.spaceId, serializeJson(call.record)],\n\t\t\t);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync beginAttempt(input: WebhookFencedWrite & { readonly attempt: WebhookDeliveryAttemptStart }, options: WebhookCallOptions): Promise<WebhookAttemptBeginResult> {\n\t\tconst call = readBeginAttemptCall(input, options);\n\t\t// Made before the transaction; only its digest is stored.\n\t\tconst receipt = await storeCall(newAttemptReceipt);\n\t\t// The intent row is locked FOR UPDATE first, so a concurrent begin, settle,\n\t\t// cancel or reclaim of this intent waits; lease expiry is then judged on\n\t\t// the store's clock read after the lock. The begun row is keyed by\n\t\t// (delivery_id, fence) and only this lease holder can insert it.\n\t\treturn this.#write(\"beginAttempt\", call.bounds, (tx) => this.#lockIntent(tx, call.deliveryId), async (tx, nowMs, intent) => {\n\t\t\tif (!mayBegin(intent, call.fenced, nowMs)) return beginResult(undefined);\n\t\t\tif (call.subscriptionId !== intent.subscriptionId) throw storeError(\"record_mismatch\", \"input.attempt.subscriptionId\");\n\t\t\tif (call.eventId !== intent.eventId) throw storeError(\"record_mismatch\", \"input.attempt.eventId\");\n\t\t\tconst inserted = await tx.query(\n\t\t\t\t`INSERT INTO ${this.#t.attempts} (delivery_id, tenant_id, space_id, record, fence, receipt_digest) VALUES ($1, $2, $3, $4::json, $5, $6)\n\t\t\t\t ON CONFLICT (delivery_id, fence) WHERE fence IS NOT NULL DO NOTHING RETURNING seq`,\n\t\t\t\t[call.deliveryId, intent.tenantId, intent.spaceId, serializeJson(call.record), call.fenced.fence, receipt.digest],\n\t\t\t);\n\t\t\treturn beginResult(inserted.rows.length === 1 ? receipt.receipt : undefined);\n\t\t});\n\t}\n\n\tasync finishAttempt(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly fence: number; readonly receipt: string; readonly finish: WebhookDeliveryAttemptFinish },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readFinishAttemptCall(input, options);\n\t\tconst digest = await storeCall(() => attemptReceiptDigest(call.receipt));\n\t\treturn this.#write(\n\t\t\t\"finishAttempt\",\n\t\t\tcall.bounds,\n\t\t\t// Unfenced: it reads only the begun attempt (rows that never change)\n\t\t\t// and never touches the intent row. The outcome insert can wait on a\n\t\t\t// concurrent insert of the same key, so it runs here, before the clock.\n\t\t\tasync (tx) => {\n\t\t\t\tconst begun = await tx.query(\n\t\t\t\t\t`SELECT 1 FROM ${this.#t.attempts}\n\t\t\t\t\t WHERE delivery_id = $1 AND fence = $2 AND tenant_id = $3 AND space_id = $4 AND receipt_digest = $5`,\n\t\t\t\t\t[call.deliveryId, call.fence, call.scope.tenantId, call.scope.spaceId, digest],\n\t\t\t\t);\n\t\t\t\tif (begun.rows.length === 0) return false;\n\t\t\t\tconst inserted = await tx.query(\n\t\t\t\t\t`INSERT INTO ${this.#t.outcomes} (delivery_id, fence, tenant_id, space_id, record) VALUES ($1, $2, $3, $4, $5::json)\n\t\t\t\t\t ON CONFLICT (delivery_id, fence) DO NOTHING RETURNING fence`,\n\t\t\t\t\t[call.deliveryId, call.fence, call.scope.tenantId, call.scope.spaceId, serializeJson(call.record)],\n\t\t\t\t);\n\t\t\t\treturn inserted.rows.length === 1;\n\t\t\t},\n\t\t\tasync (_tx, _nowMs, inserted) => inserted,\n\t\t);\n\t}\n\n\tasync settleDeliveryIntent(\n\t\tinput: Parameters<WebhookDeliveryStore[\"settleDeliveryIntent\"]>[0],\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readSettleCall(input, options);\n\t\treturn this.#write(\"settleDeliveryIntent\", call.bounds, (tx) => this.#lockIntent(tx, call.deliveryId), async (tx, nowMs, intent) => {\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tapplySettlement(intent, call.settlement);\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.intents}\n\t\t\t\t SET status = $2, attempt_count = $3, available_at_ms = $4, last_outcome = $5, last_reason = $6,\n\t\t\t\t last_diagnostic = $7, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t WHERE delivery_id = $1`,\n\t\t\t\t[intent.key, intent.status, intent.attemptCount, intent.availableAtMs, intent.lastOutcome?.outcome ?? null,\n\t\t\t\t\tintent.lastOutcome?.reason ?? null, intent.lastDiagnostic ?? null],\n\t\t\t);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync cancelPendingIntents(\n\t\tinput: Parameters<WebhookDeliveryStore[\"cancelPendingIntents\"]>[0],\n\t\toptions: WebhookCallOptions,\n\t): Promise<number> {\n\t\tconst call = readCancelCall(input, options);\n\t\treturn this.#write(\n\t\t\t\"cancelPendingIntents\",\n\t\t\tcall.bounds,\n\t\t\t// Lock every matching pending intent first. A row another transaction\n\t\t\t// settles while this waits is re-checked by PostgreSQL and left out.\n\t\t\tasync (tx) => (await tx.query(\n\t\t\t\t`SELECT delivery_id FROM ${this.#t.intents}\n\t\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 AND status = 'pending' AND eligibility_revision < $4\n\t\t\t\t FOR UPDATE`,\n\t\t\t\t[call.scope.tenantId, call.scope.spaceId, call.subscriptionId, call.beforeRevision],\n\t\t\t)).rows.map((row) => textOf(row[\"delivery_id\"], \"row.delivery_id\")),\n\t\t\tasync (tx, _nowMs, locked) => {\n\t\t\t\tif (locked.length === 0) return 0;\n\t\t\t\tconst result = await tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.intents}\n\t\t\t\t\t SET status = 'cancelled', last_outcome = 'cancelled', last_reason = $2, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t\t WHERE delivery_id = ANY($1::text[]) AND status = 'pending'\n\t\t\t\t\t RETURNING delivery_id`,\n\t\t\t\t\t[locked, call.reason],\n\t\t\t\t);\n\t\t\t\treturn result.rows.length;\n\t\t\t},\n\t\t);\n\t}\n\n\tasync requeueDeliveryIntent(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly request: WebhookRequeueRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookRequeueResult> {\n\t\tconst call = readIntentRequeueCall(input, options);\n\t\treturn this.#write(\n\t\t\t\"requeueDeliveryIntent\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst intent = await this.#lockIntent(tx, call.deliveryId);\n\t\t\t\tconst prior = await this.#priorEvidence(tx, call.scope, call.request.actionInvocationId, { target: \"delivery_intent\", deliveryId: call.deliveryId });\n\t\t\t\tawait this.#pause(\"requeueDeliveryIntent\", \"locked\");\n\t\t\t\treturn { purgedThroughMs, intent, prior };\n\t\t\t},\n\t\t\tasync (tx, nowMs, { purgedThroughMs, intent, prior }) => {\n\t\t\t\tif (prior !== undefined) return replayedResult<WebhookRequeueResult>(prior);\n\t\t\t\tif (intent === undefined || !inScope(intent, call.scope)) return requeueRefused(\"not_found\");\n\t\t\t\tconst refusal = requeueRefusal(intent, call.request, this.#floorMs(nowMs, purgedThroughMs));\n\t\t\t\tif (refusal !== undefined) return requeueRefused(refusal);\n\t\t\t\tconst evidence = intentRequeueEvidence(intent, call.request, nowMs);\n\t\t\t\tconst result = copyOut<WebhookRequeueResult>({ applied: true, evidence });\n\t\t\t\tapplyRequeue(intent, call.request);\n\t\t\t\tawait tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.intents}\n\t\t\t\t\t SET status = 'pending', attempt_count = $2, available_at_ms = $3, processing_deadline_ms = $4,\n\t\t\t\t\t fence = $5, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t\t WHERE delivery_id = $1`,\n\t\t\t\t\t[intent.key, intent.attemptCount, intent.availableAtMs, intent.processingDeadlineMs, intent.fence],\n\t\t\t\t);\n\t\t\t\tawait this.#appendEvidence(tx, intent.eventId, intent.tenantId, intent.spaceId, evidence);\n\t\t\t\tawait this.#pause(\"requeueDeliveryIntent\", \"written\");\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n\n\tasync readDeliveryIntent(input: WebhookScope & { readonly deliveryId: string }, options: WebhookCallOptions): Promise<WebhookDeliveryIntent | null> {\n\t\tconst call = readDeliveryCall(input, options);\n\t\treturn this.#read(\"readDeliveryIntent\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT ${columns(INTENT_COLUMNS)} FROM ${this.#t.intents} WHERE delivery_id = $1 AND tenant_id = $2 AND space_id = $3`,\n\t\t\t\t[call.deliveryId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\treturn result.rows[0] === undefined ? null : copyOut<WebhookDeliveryIntent>(intentOut(intentFrom(result.rows[0])));\n\t\t});\n\t}\n\n\tasync listDeliveryAttempts(\n\t\tinput: WebhookScope & { readonly deliveryId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookDeliveryAttemptLogEntry[]> {\n\t\tconst call = readDeliveryCall(input, options);\n\t\treturn this.#read(\"listDeliveryAttempts\", call.bounds, async (db) => {\n\t\t\t// One statement, so the log and the outcomes come from one snapshot.\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT attempt.record::text AS record, attempt.fence::text AS fence, outcome.record::text AS outcome\n\t\t\t\t FROM ${this.#t.attempts} AS attempt\n\t\t\t\t LEFT JOIN ${this.#t.outcomes} AS outcome ON outcome.delivery_id = attempt.delivery_id AND outcome.fence = attempt.fence\n\t\t\t\t WHERE attempt.delivery_id = $1 AND attempt.tenant_id = $2 AND attempt.space_id = $3 ORDER BY attempt.seq`,\n\t\t\t\t[call.deliveryId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\treturn copyOut<readonly WebhookDeliveryAttemptLogEntry[]>(result.rows.map((row) => attemptEntryOut(\n\t\t\t\tjsonOf(row[\"record\"], \"row.record\") as Snapshot,\n\t\t\t\toptionalIntOf(row[\"fence\"], \"row.fence\"),\n\t\t\t\trow[\"outcome\"] === null || row[\"outcome\"] === undefined ? undefined : jsonOf(row[\"outcome\"], \"row.outcome\") as Snapshot,\n\t\t\t)));\n\t\t});\n\t}\n\n\tasync listRequeueEvidence(input: WebhookScope & { readonly eventId: string }, options: WebhookCallOptions): Promise<readonly WebhookRequeueEvidence[]> {\n\t\tconst call = readEventCall(input, options);\n\t\treturn this.#read(\"listRequeueEvidence\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT record::text AS record FROM ${this.#t.evidence}\n\t\t\t\t WHERE event_id = $1 AND tenant_id = $2 AND space_id = $3 ORDER BY seq`,\n\t\t\t\t[call.eventId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\treturn copyOut<readonly WebhookRequeueEvidence[]>(result.rows.map((row) => jsonOf(row[\"record\"], \"row.record\")));\n\t\t});\n\t}\n\n\tasync listInvocationRequeueEvidence(\n\t\tinput: WebhookScope & { readonly actionInvocationId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookRequeueEvidence[]> {\n\t\tconst call = readInvocationEvidenceCall(input, options);\n\t\treturn this.#read(\"listInvocationRequeueEvidence\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT record::text AS record FROM ${this.#t.evidence}\n\t\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND action_invocation_id = $3 ORDER BY seq`,\n\t\t\t\t[call.scope.tenantId, call.scope.spaceId, call.actionInvocationId],\n\t\t\t);\n\t\t\treturn copyOut<readonly WebhookRequeueEvidence[]>(result.rows.map((row) => jsonOf(row[\"record\"], \"row.record\")));\n\t\t});\n\t}\n\n\tasync readTombstone(\n\t\tinput: WebhookScope & { readonly subscriptionId: string; readonly eventId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookTombstone | null> {\n\t\tconst call = readTombstoneCall(input, options);\n\t\treturn this.#read(\"readTombstone\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT kind, subscription_id, event_id, tenant_id, space_id, anchor_ms::text AS anchor_ms FROM ${this.#t.tombstones}\n\t\t\t\t WHERE subscription_id = $1 AND event_id = $2 AND tenant_id = $3 AND space_id = $4`,\n\t\t\t\t[call.subscriptionId, call.eventId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\tconst row = result.rows[0];\n\t\t\tif (row === undefined) return null;\n\t\t\tconst marker: MarkerState = {\n\t\t\t\tkind: textOf(row[\"kind\"], \"row.kind\") as MarkerState[\"kind\"],\n\t\t\t\tsubscriptionId: textOf(row[\"subscription_id\"], \"row.subscription_id\"),\n\t\t\t\teventId: textOf(row[\"event_id\"], \"row.event_id\"),\n\t\t\t\ttenantId: textOf(row[\"tenant_id\"], \"row.tenant_id\"),\n\t\t\t\tspaceId: textOf(row[\"space_id\"], \"row.space_id\"),\n\t\t\t\tanchorMs: intOf(row[\"anchor_ms\"], \"row.anchor_ms\"),\n\t\t\t};\n\t\t\treturn copyOut<WebhookTombstone>(tombstoneOut(marker, this.#horizonMs));\n\t\t});\n\t}\n\n\tasync purgeExpiredRecords(input: { readonly limit: number }, options: WebhookCallOptions): Promise<WebhookPurgeResult> {\n\t\tconst call = readPurgeCall(input, options);\n\t\treturn this.#write(\"purgeExpiredRecords\", call.bounds, async (tx) => {\n\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"exclusive\");\n\t\t\tawait this.#pause(\"purgeExpiredRecords\", \"locked\");\n\t\t\treturn purgedThroughMs;\n\t\t}, async (tx, nowMs, purgedThroughMs) => {\n\t\t\t// Which records to remove depends on the cutoff, and so on the clock,\n\t\t\t// so the purge cannot lock them before reading it. Its DELETEs can\n\t\t\t// wait on a row lock (a settle or append holding a terminal record);\n\t\t\t// runWrite's check before COMMIT refuses the purge if its signal\n\t\t\t// aborted or its deadline passed meanwhile. A wait only makes the\n\t\t\t// cutoff older than the clock at commit, which removes less, never more.\n\t\t\tconst cutoffMs = this.#floorMs(nowMs, purgedThroughMs);\n\t\t\tconst cutoff = isoOf(cutoffMs);\n\t\t\t// The memory store's candidate order: oldest anchor, then jobs,\n\t\t\t// denials and intents, then key in UTF-16 order. One more than the\n\t\t\t// limit is read, to answer `more`.\n\t\t\tconst candidates = await tx.query(\n\t\t\t\t`SELECT rank, key, subscription_id FROM (\n\t\t\t\t\tSELECT 0 AS rank, event_id AS key, NULL::text AS subscription_id, anchor_ms, sort_key\n\t\t\t\t\tFROM ${this.#t.jobs} WHERE anchor_ms < $1 AND status = ANY($3::text[])\n\t\t\t\t\tUNION ALL\n\t\t\t\t\tSELECT 1, event_id, subscription_id, anchor_ms, sort_key\n\t\t\t\t\tFROM ${this.#t.denials} WHERE anchor_ms < $1\n\t\t\t\t\tUNION ALL\n\t\t\t\t\tSELECT 2, delivery_id, NULL::text, anchor_ms, sort_key\n\t\t\t\t\tFROM ${this.#t.intents} WHERE anchor_ms < $1 AND status = ANY($4::text[])\n\t\t\t\t) AS candidate\n\t\t\t\tORDER BY anchor_ms, rank, sort_key\n\t\t\t\tLIMIT $2`,\n\t\t\t\t[cutoffMs, call.limit + 1, [...TERMINAL_JOB], [...TERMINAL_INTENT]],\n\t\t\t);\n\t\t\tconst take = candidates.rows.length < call.limit ? candidates.rows.length : call.limit;\n\t\t\tconst jobs: string[] = [];\n\t\t\tconst denialSubscriptions: string[] = [];\n\t\t\tconst denialEvents: string[] = [];\n\t\t\tconst intents: string[] = [];\n\t\t\tfor (let index = 0; index < take; index += 1) {\n\t\t\t\tconst row = candidates.rows[index]!;\n\t\t\t\tconst rank = intOf(row[\"rank\"], \"row.rank\");\n\t\t\t\tconst key = textOf(row[\"key\"], \"row.key\");\n\t\t\t\tif (rank === 0) jobs.push(key);\n\t\t\t\telse if (rank === 1) {\n\t\t\t\t\tdenialSubscriptions.push(textOf(row[\"subscription_id\"], \"row.subscription_id\"));\n\t\t\t\t\tdenialEvents.push(key);\n\t\t\t\t} else intents.push(key);\n\t\t\t}\n\t\t\t// Each DELETE repeats the terminal-status condition and the counts\n\t\t\t// are what was deleted. Under the horizon lock no requeue can move a\n\t\t\t// candidate back to pending in between, so they equal the candidate\n\t\t\t// counts; the repeat keeps a pending record from ever being removed.\n\t\t\tconst removed = { fanOutJobs: 0, deliveryIntents: 0, admissionDenials: 0 };\n\t\t\tif (jobs.length > 0) {\n\t\t\t\tconst deleted = await tx.query(\n\t\t\t\t\t`DELETE FROM ${this.#t.jobs} WHERE event_id = ANY($1::text[]) AND status = ANY($2::text[]) RETURNING event_id`,\n\t\t\t\t\t[jobs, [...TERMINAL_JOB]],\n\t\t\t\t);\n\t\t\t\tremoved.fanOutJobs = deleted.rows.length;\n\t\t\t}\n\t\t\tif (denialEvents.length > 0) {\n\t\t\t\tconst deleted = await tx.query(\n\t\t\t\t\t`WITH removed AS (\n\t\t\t\t\t\tDELETE FROM ${this.#t.denials} AS target USING unnest($1::text[], $2::text[]) AS pair(subscription_id, event_id)\n\t\t\t\t\t\tWHERE target.subscription_id = pair.subscription_id AND target.event_id = pair.event_id\n\t\t\t\t\t\tRETURNING target.subscription_id, target.event_id\n\t\t\t\t\t), tombstones AS (\n\t\t\t\t\t\tDELETE FROM ${this.#t.tombstones} AS target USING removed\n\t\t\t\t\t\tWHERE target.subscription_id = removed.subscription_id AND target.event_id = removed.event_id\n\t\t\t\t\t)\n\t\t\t\t\tSELECT count(*)::text AS removed FROM removed`,\n\t\t\t\t\t[denialSubscriptions, denialEvents],\n\t\t\t\t);\n\t\t\t\tremoved.admissionDenials = intOf(deleted.rows[0]?.[\"removed\"], \"row.removed\");\n\t\t\t}\n\t\t\tif (intents.length > 0) {\n\t\t\t\tconst deleted = await tx.query(\n\t\t\t\t\t`WITH removed AS (\n\t\t\t\t\t\tDELETE FROM ${this.#t.intents} WHERE delivery_id = ANY($1::text[]) AND status = ANY($2::text[])\n\t\t\t\t\t\tRETURNING subscription_id, event_id\n\t\t\t\t\t), tombstones AS (\n\t\t\t\t\t\tDELETE FROM ${this.#t.tombstones} AS target USING removed\n\t\t\t\t\t\tWHERE target.subscription_id = removed.subscription_id AND target.event_id = removed.event_id\n\t\t\t\t\t)\n\t\t\t\t\tSELECT count(*)::text AS removed FROM removed`,\n\t\t\t\t\t[intents, [...TERMINAL_INTENT]],\n\t\t\t\t);\n\t\t\t\tremoved.deliveryIntents = intOf(deleted.rows[0]?.[\"removed\"], \"row.removed\");\n\t\t\t}\n\t\t\tconst result = copyOut<WebhookPurgeResult>({ cutoff, removed, more: candidates.rows.length > take });\n\t\t\t// Raise the floor in the same transaction as the removals: once this\n\t\t\t// commits, no insert or requeue can recreate anything below it.\n\t\t\tawait tx.query(`UPDATE ${this.#t.horizon} SET purged_through_ms = $1`, [cutoffMs]);\n\t\t\tawait this.#pause(\"purgeExpiredRecords\", \"written\");\n\t\t\treturn result;\n\t\t});\n\t}\n}\n","import { readHookOption } from \"./delivery-store-core\";\nimport { guard, storeError } from \"./errors\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookConfigurationWriteResult,\n\tWebhookScope,\n\tWebhookSubscriptionStore,\n\tWebhookSubscriptionTransitionInput,\n\tWebhookSubscriptionWriteResult,\n\tWebhookSubscriptionWriter,\n} from \"./ports\";\nimport {\n\tapplyWebhookMigrations,\n\tawaitHook,\n\tintOf,\n\tjsonOf,\n\toptionalIntOf,\n\treadPoolOption,\n\treadSchemaOption,\n\trunRead,\n\trunWrite,\n\ttextOf,\n\ttype WebhookPostgresMigration,\n\ttype WebhookPostgresPool,\n\ttype WebhookPostgresQueryable,\n} from \"./postgres-sql\";\nimport { serializeJson } from \"./snapshot\";\nimport { captureClock, type CallBounds, type CapturedClock } from \"./store-input\";\nimport {\n\tcompareText,\n\tconfigurationOut,\n\tcopyOut,\n\tdecideTransition,\n\tDELETE,\n\tPAUSE,\n\treadChangePatternsCall,\n\treadCreateCall,\n\treadReplaceConfigurationCall,\n\treadRevisionsAtCall,\n\treadStatusChangeCall,\n\treadTargetCall,\n\trefused,\n\tRESUME,\n\trevisionOut,\n\tstatusRevisionChange,\n\ttype RevisionChange,\n\ttype RevisionState,\n\ttype StatusChange,\n\ttype Target,\n} from \"./subscription-store-core\";\nimport type {\n\tWebhookDeliveryConfiguration,\n\tWebhookDeliveryConfigurationInput,\n\tWebhookEligibilityRevision,\n\tWebhookSignatureScheme,\n\tWebhookSubscriptionSnapshot,\n\tWebhookSubscriptionStatus,\n} from \"./types\";\n\n/*\n * PostgreSQL subscription store: the read port and the writer port, like\n * the memory subscription store, with the same input readers and transition\n * rules (src/subscription-store-core.ts). Each write is one READ COMMITTED\n * transaction (`runWrite` in src/postgres-sql.ts) that first locks the\n * subscription's head row with `SELECT ... FOR UPDATE`, then reads the\n * store's clock and refuses an aborted or expired call, then checks the\n * transition against the current revision and appends, and checks the call\n * bounds once more before COMMIT. Two writes to one subscription therefore\n * run one after the other, so of several racing transitions with the same\n * `expectedRevision` exactly one applies. Create inserts the head row with\n * `ON CONFLICT DO NOTHING` before reading the clock (that insert can wait on\n * a racing create), so of two racing creates exactly one applies. A call\n * whose signal aborts or deadline passes while it waits for the head row\n * commits nothing (\"call bounds while waiting for a lock\" in\n * tests/postgres-live.test.ts). Revisions and configuration versions are\n * only ever inserted; `effectiveUntil` is derived from the next revision\n * when read. This store keeps no replay horizon.\n */\n\n/** Options for {@link PostgresWebhookSubscriptionStore}. */\nexport interface PostgresWebhookSubscriptionStoreOptions {\n\t/** The connection pool, for example a `pg.Pool`. The store never ends it. */\n\treadonly pool: WebhookPostgresPool;\n\t/** The store's clock: every revision takes effect at its time (decision 3). */\n\treadonly clock: WebhookClock;\n\t/** The schema the tables live in, default `fabric_webhook_delivery`. It may be the delivery store's schema. */\n\treadonly schema?: string;\n\t/** Test seam, with the memory store's meaning. Leave it unset outside tests. */\n\treadonly beforeAtomicStep?: (operation: string) => Promise<void> | void;\n}\n\ninterface Tables {\n\treadonly subscriptions: string;\n\treadonly revisions: string;\n\treadonly configurations: string;\n}\n\nconst SUBSCRIPTION_MIGRATIONS: readonly WebhookPostgresMigration[] = Object.freeze([{\n\tversion: 1,\n\tname: \"subscription_baseline\",\n\tsql: `\n\t\tCREATE TABLE {{schema}}.webhook_subscriptions (\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tPRIMARY KEY (tenant_id, space_id, subscription_id)\n\t\t);\n\t\tCREATE TABLE {{schema}}.webhook_subscription_revisions (\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tsubscription_id text NOT NULL,\n\t\t\trevision bigint NOT NULL,\n\t\t\tstatus text NOT NULL CHECK (status IN ('active', 'paused', 'deleted')),\n\t\t\tevent_type_patterns json NOT NULL,\n\t\t\teffective_from_ms bigint NOT NULL,\n\t\t\tPRIMARY KEY (tenant_id, space_id, subscription_id, revision),\n\t\t\tFOREIGN KEY (tenant_id, space_id, subscription_id) REFERENCES {{schema}}.webhook_subscriptions\n\t\t);\n\t\tCREATE INDEX webhook_subscription_revisions_at_idx\n\t\t\tON {{schema}}.webhook_subscription_revisions (tenant_id, space_id, effective_from_ms);\n\t\tCREATE TABLE {{schema}}.webhook_subscription_configurations (\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tversion bigint NOT NULL,\n\t\t\tdestination_url json NOT NULL,\n\t\t\tsignature_scheme text NOT NULL,\n\t\t\tsecret_ref json NOT NULL,\n\t\t\tPRIMARY KEY (tenant_id, space_id, subscription_id, version),\n\t\t\tFOREIGN KEY (tenant_id, space_id, subscription_id) REFERENCES {{schema}}.webhook_subscriptions\n\t\t);\n\t`,\n}]);\n\nfunction revisionColumns(alias: string): string {\n\treturn `${alias}.revision::text AS revision, ${alias}.status, ${alias}.event_type_patterns::text AS event_type_patterns, ${alias}.effective_from_ms::text AS effective_from_ms`;\n}\n\nfunction configurationColumns(alias: string): string {\n\treturn `${alias}.version::text AS version, ${alias}.destination_url::text AS destination_url, ${alias}.signature_scheme, ${alias}.secret_ref::text AS secret_ref`;\n}\n\ntype Row = Record<string, unknown>;\n\nfunction revisionFrom(row: Row): RevisionState {\n\tconst patterns = jsonOf(row[\"event_type_patterns\"], \"row.event_type_patterns\");\n\tif (!Array.isArray(patterns) || !patterns.every((pattern) => typeof pattern === \"string\")) throw storeError(\"store_failed\", \"row.event_type_patterns\");\n\treturn {\n\t\trevision: intOf(row[\"revision\"], \"row.revision\"),\n\t\tstatus: textOf(row[\"status\"], \"row.status\") as WebhookSubscriptionStatus,\n\t\teventTypePatterns: patterns as string[],\n\t\teffectiveFromMs: intOf(row[\"effective_from_ms\"], \"row.effective_from_ms\"),\n\t};\n}\n\nfunction configurationFrom(target: Target, row: Row): WebhookDeliveryConfiguration {\n\treturn configurationOut(target, intOf(row[\"version\"], \"row.version\"), {\n\t\tdestinationUrl: textOf(jsonOf(row[\"destination_url\"], \"row.destination_url\"), \"row.destination_url\"),\n\t\tsignatureScheme: textOf(row[\"signature_scheme\"], \"row.signature_scheme\") as WebhookSignatureScheme,\n\t\tsecretRef: textOf(jsonOf(row[\"secret_ref\"], \"row.secret_ref\"), \"row.secret_ref\"),\n\t});\n}\n\n/**\n * A PostgreSQL {@link WebhookSubscriptionStore} and {@link WebhookSubscriptionWriter}.\n * Subscriptions are keyed by (tenantId, spaceId, subscriptionId); a read or\n * write in another scope does not see them. Call {@link ensureSchema} once\n * before use.\n *\n * @throws {WebhookStoreError} `clock_invalid` when `clock` has no `now`\n * function; `input_invalid` when `pool`, `schema` or the test seam is not usable.\n */\nexport class PostgresWebhookSubscriptionStore implements WebhookSubscriptionStore, WebhookSubscriptionWriter {\n\treadonly #pool: WebhookPostgresPool;\n\treadonly #clock: CapturedClock;\n\treadonly #schema: string;\n\treadonly #t: Tables;\n\treadonly #beforeAtomicStep: ((operation: string) => Promise<void> | void) | undefined;\n\n\tconstructor(options: PostgresWebhookSubscriptionStoreOptions) {\n\t\tthis.#clock = guard(() => {\n\t\t\tif (options === null || typeof options !== \"object\") throw storeError(\"clock_invalid\", \"clock\");\n\t\t\treturn captureClock(options.clock);\n\t\t}, () => storeError(\"clock_invalid\", \"clock\"));\n\t\tthis.#pool = readPoolOption(options);\n\t\tthis.#schema = readSchemaOption(options);\n\t\tthis.#t = {\n\t\t\tsubscriptions: `${this.#schema}.webhook_subscriptions`,\n\t\t\trevisions: `${this.#schema}.webhook_subscription_revisions`,\n\t\t\tconfigurations: `${this.#schema}.webhook_subscription_configurations`,\n\t\t};\n\t\tthis.#beforeAtomicStep = readHookOption(options, \"beforeAtomicStep\");\n\t}\n\n\t/** Create the schema and tables, or check the applied migrations. Safe to call concurrently and repeatedly. */\n\tasync ensureSchema(): Promise<void> {\n\t\tawait applyWebhookMigrations(this.#pool, this.#schema, \"subscriptions\", SUBSCRIPTION_MIGRATIONS);\n\t}\n\n\t#boundary(operation: string): Promise<void> {\n\t\tconst hook = this.#beforeAtomicStep;\n\t\treturn awaitHook(hook === undefined ? undefined : () => hook(operation), \"beforeAtomicStep\");\n\t}\n\n\tasync #read<T>(operation: string, bounds: CallBounds, body: (db: WebhookPostgresQueryable) => Promise<T>): Promise<T> {\n\t\tawait this.#boundary(operation);\n\t\treturn runRead(this.#pool, this.#clock, bounds, (db) => body(db));\n\t}\n\n\t/** Lock the subscription's head row; `false` when it does not exist in this scope. */\n\tasync #lockHead(tx: WebhookPostgresQueryable, target: Target): Promise<boolean> {\n\t\tconst result = await tx.query(\n\t\t\t`SELECT 1 FROM ${this.#t.subscriptions} WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 FOR UPDATE`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync #currentRevision(db: WebhookPostgresQueryable, target: Target): Promise<RevisionState | undefined> {\n\t\tconst result = await db.query(\n\t\t\t`SELECT ${revisionColumns(\"revision\")} FROM ${this.#t.revisions} AS revision\n\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 ORDER BY revision.revision DESC LIMIT 1`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t);\n\t\treturn result.rows[0] === undefined ? undefined : revisionFrom(result.rows[0]);\n\t}\n\n\tasync #currentConfiguration(db: WebhookPostgresQueryable, target: Target): Promise<WebhookDeliveryConfiguration> {\n\t\tconst result = await db.query(\n\t\t\t`SELECT ${configurationColumns(\"configuration\")} FROM ${this.#t.configurations} AS configuration\n\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 ORDER BY configuration.version DESC LIMIT 1`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t);\n\t\tif (result.rows[0] === undefined) throw storeError(\"store_failed\", \"row.configuration\");\n\t\treturn configurationFrom(target, result.rows[0]);\n\t}\n\n\tasync #insertRevision(tx: WebhookPostgresQueryable, target: Target, revision: RevisionState): Promise<void> {\n\t\tawait tx.query(\n\t\t\t`INSERT INTO ${this.#t.revisions} (tenant_id, space_id, subscription_id, revision, status, event_type_patterns, effective_from_ms)\n\t\t\t VALUES ($1, $2, $3, $4, $5, $6::json, $7)`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId, revision.revision, revision.status, serializeJson(revision.eventTypePatterns), revision.effectiveFromMs],\n\t\t);\n\t}\n\n\tasync #insertConfiguration(tx: WebhookPostgresQueryable, target: Target, version: number, configuration: WebhookDeliveryConfigurationInput): Promise<void> {\n\t\tawait tx.query(\n\t\t\t`INSERT INTO ${this.#t.configurations} (tenant_id, space_id, subscription_id, version, destination_url, signature_scheme, secret_ref)\n\t\t\t VALUES ($1, $2, $3, $4, $5::json, $6, $7::json)`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId, version, serializeJson(configuration.destinationUrl), configuration.signatureScheme, serializeJson(configuration.secretRef)],\n\t\t);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Reads\n\t// -------------------------------------------------------------------------\n\n\tasync listEligibilityRevisions(\n\t\tinput: WebhookScope & { readonly recordedAt: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookEligibilityRevision[]> {\n\t\tconst call = readRevisionsAtCall(input, options);\n\t\treturn this.#read(\"listEligibilityRevisions\", call.bounds, async (db) => {\n\t\t\t// Per subscription, the latest revision in effect at recordedAt\n\t\t\t// (effectiveFrom <= recordedAt), with its successor's start.\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT DISTINCT ON (revision.subscription_id)\n\t\t\t\t\trevision.subscription_id, ${revisionColumns(\"revision\")},\n\t\t\t\t\t(SELECT next.effective_from_ms::text FROM ${this.#t.revisions} AS next\n\t\t\t\t\t WHERE next.tenant_id = revision.tenant_id AND next.space_id = revision.space_id\n\t\t\t\t\t AND next.subscription_id = revision.subscription_id AND next.revision = revision.revision + 1) AS next_from_ms\n\t\t\t\t FROM ${this.#t.revisions} AS revision\n\t\t\t\t WHERE revision.tenant_id = $1 AND revision.space_id = $2 AND revision.effective_from_ms <= $3\n\t\t\t\t ORDER BY revision.subscription_id, revision.revision DESC`,\n\t\t\t\t[call.tenantId, call.spaceId, call.recordedAtMs],\n\t\t\t);\n\t\t\tconst found = result.rows.map((row) => ({\n\t\t\t\ttarget: { tenantId: call.tenantId, spaceId: call.spaceId, subscriptionId: textOf(row[\"subscription_id\"], \"row.subscription_id\") },\n\t\t\t\trevision: revisionFrom(row),\n\t\t\t\tnextFromMs: optionalIntOf(row[\"next_from_ms\"], \"row.next_from_ms\"),\n\t\t\t}))\n\t\t\t\t// Half-open: effectiveFrom <= recordedAt < next.effectiveFrom.\n\t\t\t\t.filter((item) => item.nextFromMs === undefined || call.recordedAtMs < item.nextFromMs)\n\t\t\t\t// The memory store's order (UTF-16 code units), not the database collation.\n\t\t\t\t.sort((left, right) => compareText(left.target.subscriptionId, right.target.subscriptionId));\n\t\t\treturn copyOut<readonly WebhookEligibilityRevision[]>(found.map((item) => revisionOut(item.target, item.revision, item.nextFromMs)));\n\t\t});\n\t}\n\n\tasync readSubscription(\n\t\tinput: WebhookScope & { readonly subscriptionId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionSnapshot | null> {\n\t\tconst call = readTargetCall(input, options);\n\t\treturn this.#read(\"readSubscription\", call.bounds, async (db) => {\n\t\t\tconst target = call.target;\n\t\t\tconst result = await db.query(\n\t\t\t\t// One statement, so the status and the revision it began at are\n\t\t\t\t// read from one snapshot. `status_since` is one past the last\n\t\t\t\t// revision with another status, or 1 (revisions are numbered\n\t\t\t\t// 1, 2, 3 … with no gaps; subscription-store-core.ts,\n\t\t\t\t// `statusSinceRevision`, is the memory store's twin).\n\t\t\t\t`SELECT current_revision.status, current_revision.status_since::text AS status_since,\n\t\t\t\t\t${configurationColumns(\"current_configuration\")}\n\t\t\t\t FROM ${this.#t.subscriptions} AS subscription\n\t\t\t\t CROSS JOIN LATERAL (\n\t\t\t\t\tSELECT latest.status,\n\t\t\t\t\t\tCOALESCE((\n\t\t\t\t\t\t\tSELECT max(prior.revision) FROM ${this.#t.revisions} AS prior\n\t\t\t\t\t\t\tWHERE prior.tenant_id = subscription.tenant_id AND prior.space_id = subscription.space_id\n\t\t\t\t\t\t\t AND prior.subscription_id = subscription.subscription_id AND prior.status <> latest.status\n\t\t\t\t\t\t), 0) + 1 AS status_since\n\t\t\t\t\tFROM (\n\t\t\t\t\t\tSELECT status FROM ${this.#t.revisions} AS revision\n\t\t\t\t\t\tWHERE revision.tenant_id = subscription.tenant_id AND revision.space_id = subscription.space_id\n\t\t\t\t\t\t AND revision.subscription_id = subscription.subscription_id\n\t\t\t\t\t\tORDER BY revision.revision DESC LIMIT 1\n\t\t\t\t\t) AS latest\n\t\t\t\t ) AS current_revision\n\t\t\t\t CROSS JOIN LATERAL (\n\t\t\t\t\tSELECT * FROM ${this.#t.configurations} AS configuration\n\t\t\t\t\tWHERE configuration.tenant_id = subscription.tenant_id AND configuration.space_id = subscription.space_id\n\t\t\t\t\t AND configuration.subscription_id = subscription.subscription_id\n\t\t\t\t\tORDER BY configuration.version DESC LIMIT 1\n\t\t\t\t ) AS current_configuration\n\t\t\t\t WHERE subscription.tenant_id = $1 AND subscription.space_id = $2 AND subscription.subscription_id = $3`,\n\t\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t\t);\n\t\t\tconst row = result.rows[0];\n\t\t\tif (row === undefined) return null;\n\t\t\treturn copyOut<WebhookSubscriptionSnapshot>({\n\t\t\t\tsubscriptionId: target.subscriptionId,\n\t\t\t\ttenantId: target.tenantId,\n\t\t\t\tspaceId: target.spaceId,\n\t\t\t\tstatus: textOf(row[\"status\"], \"row.status\"),\n\t\t\t\tstatusSinceRevision: intOf(row[\"status_since\"], \"row.status_since\"),\n\t\t\t\tconfiguration: configurationFrom(target, row),\n\t\t\t});\n\t\t});\n\t}\n\n\tasync listEligibilityHistory(\n\t\tinput: WebhookScope & { readonly subscriptionId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookEligibilityRevision[]> {\n\t\tconst call = readTargetCall(input, options);\n\t\treturn this.#read(\"listEligibilityHistory\", call.bounds, async (db) => {\n\t\t\tconst target = call.target;\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT ${revisionColumns(\"revision\")} FROM ${this.#t.revisions} AS revision\n\t\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 ORDER BY revision.revision`,\n\t\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t\t);\n\t\t\tconst revisions = result.rows.map(revisionFrom);\n\t\t\treturn copyOut<readonly WebhookEligibilityRevision[]>(revisions.map((revision, index) => revisionOut(target, revision, revisions[index + 1]?.effectiveFromMs)));\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Writes\n\t// -------------------------------------------------------------------------\n\n\tasync createSubscription(\n\t\tinput: WebhookScope & {\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly eventTypePatterns: readonly string[];\n\t\t\treadonly configuration: WebhookDeliveryConfigurationInput;\n\t\t},\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readCreateCall(input, options);\n\t\tawait this.#boundary(\"createSubscription\");\n\t\tconst target = call.target;\n\t\t// The head row is inserted before the clock is read, so the only work\n\t\t// between the clock read and the commit is one statement that writes\n\t\t// revision 1 and configuration version 1 together.\n\t\treturn runWrite(\n\t\t\tthis.#pool,\n\t\t\tthis.#clock,\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => (await tx.query(\n\t\t\t\t`INSERT INTO ${this.#t.subscriptions} (tenant_id, space_id, subscription_id) VALUES ($1, $2, $3)\n\t\t\t\t ON CONFLICT DO NOTHING RETURNING subscription_id`,\n\t\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t\t)).rows.length === 1,\n\t\t\tasync (tx, nowMs, created) => {\n\t\t\t\tif (!created) return refused(\"already_exists\");\n\t\t\t\tconst revision: RevisionState = { revision: 1, status: \"active\", eventTypePatterns: call.patterns, effectiveFromMs: nowMs };\n\t\t\t\tconst configuration = configurationOut(target, 1, call.configuration);\n\t\t\t\tconst result = copyOut<WebhookSubscriptionWriteResult>({ applied: true, revision: revisionOut(target, revision, undefined), configuration });\n\t\t\t\tawait tx.query(\n\t\t\t\t\t`WITH revision AS (\n\t\t\t\t\t\tINSERT INTO ${this.#t.revisions} (tenant_id, space_id, subscription_id, revision, status, event_type_patterns, effective_from_ms)\n\t\t\t\t\t\tVALUES ($1, $2, $3, 1, 'active', $4::json, $5)\n\t\t\t\t\t)\n\t\t\t\t\tINSERT INTO ${this.#t.configurations} (tenant_id, space_id, subscription_id, version, destination_url, signature_scheme, secret_ref)\n\t\t\t\t\tVALUES ($1, $2, $3, 1, $6::json, $7, $8::json)`,\n\t\t\t\t\t[target.tenantId, target.spaceId, target.subscriptionId, serializeJson(call.patterns), nowMs,\n\t\t\t\t\t\tserializeJson(call.configuration.destinationUrl), call.configuration.signatureScheme, serializeJson(call.configuration.secretRef)],\n\t\t\t\t);\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n\n\tasync changeEventTypePatterns(\n\t\tinput: WebhookSubscriptionTransitionInput & { readonly eventTypePatterns: readonly string[] },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readChangePatternsCall(input, options);\n\t\tawait this.#boundary(\"changeEventTypePatterns\");\n\t\treturn this.#transition(call.bounds, call.target, call.expectedRevision, (current) => ({ status: current.status, patterns: call.patterns }));\n\t}\n\n\tasync pauseSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"pauseSubscription\", input, options, PAUSE);\n\t}\n\n\tasync resumeSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"resumeSubscription\", input, options, RESUME);\n\t}\n\n\tasync deleteSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"deleteSubscription\", input, options, DELETE);\n\t}\n\n\tasync replaceDeliveryConfiguration(\n\t\tinput: WebhookScope & { readonly subscriptionId: string; readonly configuration: WebhookDeliveryConfigurationInput; readonly expectedVersion?: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookConfigurationWriteResult> {\n\t\tconst call = readReplaceConfigurationCall(input, options);\n\t\tawait this.#boundary(\"replaceDeliveryConfiguration\");\n\t\tconst target = call.target;\n\t\treturn runWrite(this.#pool, this.#clock, call.bounds, (tx) => this.#lockHead(tx, target), async (tx, _nowMs, exists) => {\n\t\t\tif (!exists) return copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"not_found\" });\n\t\t\tconst revision = await this.#currentRevision(tx, target);\n\t\t\tif (revision === undefined) throw storeError(\"store_failed\", \"row.revision\");\n\t\t\tif (revision.status === \"deleted\") return copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"deleted\" });\n\t\t\tconst current = await this.#currentConfiguration(tx, target);\n\t\t\tif (call.expectedVersion !== undefined && call.expectedVersion !== current.version) {\n\t\t\t\treturn copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"version_conflict\", currentVersion: current.version });\n\t\t\t}\n\t\t\tconst configuration = configurationOut(target, current.version + 1, call.configuration);\n\t\t\tconst result = copyOut<WebhookConfigurationWriteResult>({ applied: true, configuration });\n\t\t\tawait this.#insertConfiguration(tx, target, current.version + 1, call.configuration);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync #statusChange(\n\t\toperation: string,\n\t\tinput: WebhookSubscriptionTransitionInput,\n\t\toptions: WebhookCallOptions,\n\t\tnext: StatusChange,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readStatusChangeCall(input, options);\n\t\tawait this.#boundary(operation);\n\t\treturn this.#transition(call.bounds, call.target, call.expectedRevision, statusRevisionChange(next));\n\t}\n\n\t/**\n\t * Append one revision, checked against the current revision. The head\n\t * row is locked and the current revision and configuration are read\n\t * before the clock, so the clock read that stamps `effectiveFrom` is\n\t * followed only by the INSERT and the COMMIT.\n\t */\n\t#transition(bounds: CallBounds, target: Target, expectedRevision: number | undefined, change: RevisionChange): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn runWrite(\n\t\t\tthis.#pool,\n\t\t\tthis.#clock,\n\t\t\tbounds,\n\t\t\tasync (tx) => {\n\t\t\t\tif (!(await this.#lockHead(tx, target))) return undefined;\n\t\t\t\tconst current = await this.#currentRevision(tx, target);\n\t\t\t\tif (current === undefined) throw storeError(\"store_failed\", \"row.revision\");\n\t\t\t\treturn { current, configuration: await this.#currentConfiguration(tx, target) };\n\t\t\t},\n\t\t\tasync (tx, nowMs, locked) => {\n\t\t\t\tconst decision = decideTransition(locked?.current, expectedRevision, nowMs, change);\n\t\t\t\tif (\"refusal\" in decision) return decision.refusal;\n\t\t\t\tconst result = copyOut<WebhookSubscriptionWriteResult>({ applied: true, revision: revisionOut(target, decision.appended, undefined), configuration: locked!.configuration });\n\t\t\t\tawait this.#insertRevision(tx, target, decision.appended);\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n}\n","import { guard, inputError } from \"./errors\";\nimport {\n\tassertDelaySchedule,\n\tassertJitteredScheduleRepresentable,\n\tassertJitterRatio,\n\tDEFAULT_WEBHOOK_DELIVERY_LIMITS,\n} from \"./limits\";\nimport type { WebhookRandomSource, WebhookRetryDelay } from \"./ports\";\nimport { apply, freeze, isPlainRecord, mathFloor, mathMin, numberIsSafeInteger, primitive, primitiveList, readOwn, type Fail } from \"./snapshot\";\n\n/** Options for {@link createWebhookRetryDelay}. */\nexport interface WebhookRetryDelayOptions {\n\t/** Base delays before attempts 2, 3, ...; defaults to the delivery schedule. The last entry repeats. */\n\treadonly delaysMs?: readonly number[];\n\t/** Jitter as a fraction of the base delay, in `(0, 1]`; defaults to 0.1. */\n\treadonly jitterRatio?: number;\n\t/** Random source in `[0, 1)`. Required so jitter is never hidden process state. */\n\treadonly random: WebhookRandomSource;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/**\n * Build the retry delay port. For the 1-based number of the attempt that just\n * failed, it returns `base + floor(base * jitterRatio * random())`, so a delay\n * lies in `[base, base * (1 + jitterRatio))` and never shortens the schedule.\n * Exhaustion is decided by `maxDeliveryAttempts`, not here. The options are\n * copied at entry into a snapshot, one descriptor read per option, and the\n * schedule copied by index; the port uses only that validated copy.\n *\n * @throws {WebhookDeliveryConfigError} for an empty or non-positive schedule or jitter.\n * @throws {TypeError} `random_source_missing` without a random source, or\n * `input_unreadable` for options that cannot be read.\n *\n * The port throws `RangeError` `attempt_invalid` or `random_sample_invalid`,\n * and `TypeError` `random_source_failed` when the random source throws; the\n * source's exception is dropped unread.\n */\nexport function createWebhookRetryDelay(options: WebhookRetryDelayOptions): WebhookRetryDelay {\n\treturn guard(() => {\n\t\tif (!isPlainRecord(options)) throw unreadable();\n\t\tconst rawDelays = primitiveList(readOwn(options, \"delaysMs\", \"delaysMs\", unreadableFail), \"delaysMs\", unreadableFail);\n\t\tconst rawJitter = primitive(readOwn(options, \"jitterRatio\", \"jitterRatio\", unreadableFail));\n\t\tconst random = readOwn(options, \"random\", \"random\", unreadableFail);\n\t\tconst delaysMs = rawDelays === undefined ? DEFAULT_WEBHOOK_DELIVERY_LIMITS.deliveryRetryDelaysMs : rawDelays;\n\t\tconst jitterRatio = rawJitter === undefined ? DEFAULT_WEBHOOK_DELIVERY_LIMITS.retryJitterRatio : rawJitter;\n\t\tassertDelaySchedule(delaysMs, \"delaysMs\");\n\t\tassertJitterRatio(jitterRatio, \"jitterRatio\");\n\t\tassertJitteredScheduleRepresentable(delaysMs, jitterRatio, \"delaysMs\");\n\t\tif (typeof random !== \"function\") throw inputError(\"type\", \"random_source_missing\");\n\t\tconst delay = (attempt: number): number =>\n\t\t\tguard(() => {\n\t\t\t\tconst value = primitive(attempt);\n\t\t\t\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < 1) throw inputError(\"range\", \"attempt_invalid\");\n\t\t\t\tconst base = delaysMs[mathMin(value, delaysMs.length) - 1]!;\n\t\t\t\tconst sample = apply(random, undefined, []) as unknown;\n\t\t\t\tif (typeof sample !== \"number\" || !(sample >= 0 && sample < 1)) throw inputError(\"range\", \"random_sample_invalid\");\n\t\t\t\treturn base + mathFloor(base * jitterRatio * sample);\n\t\t\t}, () => inputError(\"type\", \"random_source_failed\"));\n\t\treturn freeze(delay);\n\t}, unreadable);\n}\n","import type { WebhookAttemptOutcome, WebhookAttemptReasonCode } from \"./codes\";\nimport { guard, inputError } from \"./errors\";\nimport { assertPositiveFinite } from \"./limits\";\nimport type { WebhookTransportResult } from \"./ports\";\nimport {\n\tdateParse,\n\tisPlainRecord,\n\tmatches,\n\tmathMax,\n\tmathMin,\n\tNumberConstructor,\n\tnumberIsFinite,\n\tnumberIsSafeInteger,\n\tprimitive,\n\treadOwn,\n\trecord,\n\ttimeOf,\n\ttrim,\n\ttype Fail,\n} from \"./snapshot\";\n\n/**\n * Everything decision 10's table classifies: a transport observation that\n * reached the network, or a check that stopped the attempt. A transport\n * `not_sent` result is not here: the dispatcher releases that intent unsent\n * without spending budget.\n */\nexport type WebhookDeliveryObservation =\n\t| Exclude<WebhookTransportResult, { readonly kind: \"not_sent\" }>\n\t| { readonly kind: \"signer_unavailable\" | \"authorization_revoked\" | \"subscription_paused\" | \"subscription_deleted\" };\n\n/** The classified attempt. */\nexport interface WebhookDeliveryClassification {\n\treadonly outcome: WebhookAttemptOutcome;\n\treadonly reason: WebhookAttemptReasonCode;\n\t/** The HTTP status, when a response was received. */\n\treadonly httpStatus?: number;\n\t/**\n\t * For a 429 with a parseable `Retry-After`: the requested delay, clamped\n\t * to `[0, maxRetryAfterMs]`. The dispatcher is expected to schedule the\n\t * later of this and the retry schedule's delay.\n\t */\n\treadonly retryAfterMs?: number;\n\t/**\n\t * `true` for 401 and 403: still `retryable`, but usually needing the\n\t * receiver to act, so the caller surfaces it to operators before the retry\n\t * budget is exhausted.\n\t */\n\treadonly receiverActionLikely?: true;\n}\n\n/** Inputs the classifier needs beyond the observation. */\nexport interface WebhookClassifyOptions {\n\t/** Used to turn an HTTP-date `Retry-After` into a delay. */\n\treadonly now: Date;\n\t/** Upper bound on an honoured `Retry-After`. */\n\treadonly maxRetryAfterMs: number;\n}\n\n/** The classifier options as snapshotted. `nowMs` is `NaN` unless `now` is a real `Date`. */\ninterface OptionsSnapshot {\n\treadonly nowMs: number;\n\treadonly maxRetryAfterMs: number;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/**\n * Classify one attempt by ADR 0018 decision 10:\n *\n * | Observation | Outcome |\n * | --- | --- |\n * | 2xx | `delivered` |\n * | network error, timeout, DNS failure, 408, 425, 429, 5xx, signer unavailable | `retryable` |\n * | 401, 403 | `retryable`, with `receiverActionLikely: true` |\n * | 3xx, 410, other 4xx, invalid URL, private or reserved address | `dead_letter` |\n * | authorization revoked, subscription paused or deleted | `cancelled` |\n *\n * A final 1xx, which the table does not list, is `retryable` (`http_1xx`).\n * The options and the observation are copied into a snapshot at entry,\n * one descriptor read per field; an accessor is refused, not called.\n *\n * @throws {RangeError} `status_out_of_range` for a status that is not a whole number in 100-599.\n * @throws {TypeError} `observation_unknown` for an unknown kind, or\n * `input_unreadable` for an observation or options that cannot be read. The\n * message is constant and never repeats the input.\n * @throws {WebhookDeliveryConfigError} when `maxRetryAfterMs` is not positive and finite.\n */\nexport function classifyWebhookDeliveryObservation(\n\tobservation: WebhookDeliveryObservation,\n\toptions: WebhookClassifyOptions,\n): WebhookDeliveryClassification {\n\treturn guard(() => {\n\t\tconst settings = snapshotOptions(options);\n\t\tif (!isPlainRecord(observation)) throw unreadable();\n\t\tconst kind = primitive(readOwn(observation, \"kind\", \"kind\", unreadableFail));\n\t\tif (kind === \"response\") {\n\t\t\tconst status = primitive(readOwn(observation, \"status\", \"status\", unreadableFail));\n\t\t\tconst retryAfter = primitive(readOwn(observation, \"retryAfter\", \"retryAfter\", unreadableFail));\n\t\t\treturn classifyStatus(status, retryAfter, settings);\n\t\t}\n\t\tswitch (kind) {\n\t\t\tcase \"network_error\":\n\t\t\tcase \"timeout\":\n\t\t\tcase \"dns_failure\":\n\t\t\tcase \"signer_unavailable\":\n\t\t\t\treturn record<WebhookDeliveryClassification>({ outcome: \"retryable\", reason: kind });\n\t\t\tcase \"invalid_url\":\n\t\t\tcase \"private_address\":\n\t\t\t\treturn record<WebhookDeliveryClassification>({ outcome: \"dead_letter\", reason: kind });\n\t\t\tcase \"authorization_revoked\":\n\t\t\tcase \"subscription_paused\":\n\t\t\tcase \"subscription_deleted\":\n\t\t\t\treturn record<WebhookDeliveryClassification>({ outcome: \"cancelled\", reason: kind });\n\t\t\tdefault:\n\t\t\t\tthrow inputError(\"type\", \"observation_unknown\");\n\t\t}\n\t}, unreadable);\n}\n\n/** Snapshot the options and validate the cap. */\nfunction snapshotOptions(options: unknown): OptionsSnapshot {\n\tif (!isPlainRecord(options)) throw unreadable();\n\tconst now = readOwn(options, \"now\", \"now\", unreadableFail);\n\tconst maxRetryAfterMs = primitive(readOwn(options, \"maxRetryAfterMs\", \"maxRetryAfterMs\", unreadableFail));\n\tassertPositiveFinite(maxRetryAfterMs, \"maxRetryAfterMs\");\n\treturn record({ nowMs: timeOf(now), maxRetryAfterMs });\n}\n\nfunction classifyStatus(status: unknown, retryAfter: unknown, settings: OptionsSnapshot): WebhookDeliveryClassification {\n\tif (typeof status !== \"number\" || !numberIsSafeInteger(status) || status < 100 || status > 599) {\n\t\tthrow inputError(\"range\", \"status_out_of_range\");\n\t}\n\tconst httpStatus = status;\n\tconst result = (fields: WebhookDeliveryClassification): WebhookDeliveryClassification => record(fields);\n\tif (status < 200) return result({ outcome: \"retryable\", reason: \"http_1xx\", httpStatus });\n\tif (status < 300) return result({ outcome: \"delivered\", reason: \"http_2xx\", httpStatus });\n\tif (status < 400) return result({ outcome: \"dead_letter\", reason: \"http_3xx\", httpStatus });\n\tif (status >= 500) return result({ outcome: \"retryable\", reason: \"http_5xx\", httpStatus });\n\tswitch (status) {\n\t\tcase 401:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_401\", httpStatus, receiverActionLikely: true });\n\t\tcase 403:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_403\", httpStatus, receiverActionLikely: true });\n\t\tcase 408:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_408\", httpStatus });\n\t\tcase 425:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_425\", httpStatus });\n\t\tcase 429:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_429\", httpStatus, retryAfterMs: retryAfterMsFrom(retryAfter, settings) });\n\t\tcase 410:\n\t\t\treturn result({ outcome: \"dead_letter\", reason: \"http_410\", httpStatus });\n\t\tdefault:\n\t\t\treturn result({ outcome: \"dead_letter\", reason: \"http_4xx\", httpStatus });\n\t}\n}\n\nconst IMF_FIXDATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \\d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4} \\d{2}:\\d{2}:\\d{2} GMT$/;\nconst DELTA_SECONDS = /^\\d+$/;\n\n/**\n * Parse `Retry-After` as delta-seconds or an IMF-fixdate HTTP-date and clamp\n * it to `[0, maxRetryAfterMs]`. An absent or unparseable value returns\n * `undefined`, leaving the retry schedule in charge. The options are\n * snapshotted as {@link classifyWebhookDeliveryObservation} snapshots them.\n *\n * @throws {WebhookDeliveryConfigError} when `maxRetryAfterMs` is not positive and finite.\n * @throws {TypeError} `input_unreadable` for options that cannot be read.\n */\nexport function parseRetryAfterMs(\n\tvalue: string | null | undefined,\n\toptions: WebhookClassifyOptions,\n): number | undefined {\n\treturn guard(() => retryAfterMsFrom(primitive(value), snapshotOptions(options)), unreadable);\n}\n\nfunction retryAfterMsFrom(value: unknown, settings: OptionsSnapshot): number | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = trim(value);\n\tif (trimmed === \"\") return undefined;\n\tlet delayMs: number;\n\tif (matches(DELTA_SECONDS, trimmed)) {\n\t\tdelayMs = NumberConstructor(trimmed) * 1000;\n\t} else {\n\t\t// Only the IMF-fixdate form senders must generate (RFC 9110 5.6.7);\n\t\t// Date.parse alone would accept \"-5\" or \"1.5\" as dates.\n\t\tif (!matches(IMF_FIXDATE, trimmed)) return undefined;\n\t\tconst at = dateParse(trimmed);\n\t\tif (!numberIsFinite(at) || !numberIsFinite(settings.nowMs)) return undefined;\n\t\tdelayMs = at - settings.nowMs;\n\t}\n\tif (delayMs !== delayMs) return undefined;\n\treturn mathMin(mathMax(delayMs, 0), settings.maxRetryAfterMs);\n}\n","import type { WebhookProjectionErrorCode } from \"./codes\";\nimport { guard, projectionError } from \"./errors\";\nimport {\n\tdefine,\n\temptyMap,\n\tfreeze,\n\thasOwn,\n\tisoFromDateOrString,\n\tisPlainRecord,\n\tnumberIsSafeInteger,\n\treadOwn,\n\trecord,\n\tsnapshotJson,\n\tstringList,\n\ttype Fail,\n} from \"./snapshot\";\nimport type {\n\tWebhookEventMetadata,\n\tWebhookFanOutJobDraft,\n\tWebhookJobActor,\n\tWebhookJsonObject,\n\tWebhookJsonValue,\n\tWebhookPayloadPolicy,\n\tWebhookSourceEnvelope,\n} from \"./types\";\n\n/** Inputs to {@link projectWebhookFanOutJob}. */\nexport interface WebhookPersistenceProjectionOptions {\n\t/** The application's per-event-type egress allowlist and declared facts. */\n\treadonly policy: WebhookPayloadPolicy;\n\t/**\n\t * The actor Host passed with the envelope, or why it is absent. Defaults to\n\t * `{ state: \"absent\", reason: \"legacy\" }`.\n\t */\n\treadonly actor?: WebhookJobActor;\n}\n\nconst LEGACY_ACTOR: WebhookJobActor = record({ state: \"absent\", reason: \"legacy\" });\n\n/* Fault mapping. Data records (envelope, job, subscription, actor) report\n * accessors as `accessor_property` and anything else as `invalid_envelope`;\n * call and configuration records (options, input, policy) report\n * `inspection_failed`; JSON values report the code of the list naming them. */\n\n/** @internal */\nexport const dataFail: Fail = (fault, field) => {\n\tthrow projectionError(fault === \"accessor\" ? \"accessor_property\" : \"invalid_envelope\", field);\n};\n\n/** @internal */\nexport const callFail: Fail = (_fault, field) => {\n\tthrow projectionError(\"inspection_failed\", field);\n};\n\nfunction jsonFail(code: WebhookProjectionErrorCode): Fail {\n\treturn (fault, field) => {\n\t\tthrow projectionError(fault === \"accessor\" ? \"accessor_property\" : code, field);\n\t};\n}\n\n/** @internal */\nexport const payloadFail = jsonFail(\"payload_field_not_json\");\n/** @internal */\nexport const factFail = jsonFail(\"fact_field_not_json\");\n\n/** @internal Replacement for anything a projection did not throw itself. */\nexport function uninspectable(field: string): () => Error {\n\treturn () => projectionError(\"inspection_failed\", field);\n}\n\n/**\n * The persistence projection (ADR 0018 decision 2). Host copies\n * `event.payload` into the outbox unchanged, so the fan-out job keeps only:\n *\n * - envelope metadata (no trace context, provenance or payload);\n * - the payload fields allowlisted for the event type, when it has an entry;\n * - the payload fields the entry declares as admission and scope facts.\n *\n * A `restricted` event keeps neither payload fields nor facts unless its\n * entry sets `includeRestricted`. Everything else in the payload is dropped\n * before anything is stored, and the package never asks for it. The\n * envelope and options are copied at entry, through own data property\n * descriptors, into a snapshot (a faithful copy for plain data; a Proxy's\n * traps may run more than once, see README, P1); the job is built\n * from the snapshot and is frozen, with null-prototype records.\n *\n * @throws {WebhookProjectionError} when the envelope lacks a required field,\n * a kept field is not JSON or is an accessor, or an input cannot be\n * inspected. The message is constant for the code; no error keeps an input\n * value or an input-raised error.\n */\nexport function projectWebhookFanOutJob(\n\tenvelope: WebhookSourceEnvelope,\n\toptions: WebhookPersistenceProjectionOptions,\n): WebhookFanOutJobDraft {\n\treturn guard(() => fanOutJob(envelope, options), uninspectable(\"envelope\"));\n}\n\n/**\n * Envelope metadata as a serializable record: identifiers, ordering,\n * classification and consistency. Dates become ISO-8601 strings computed\n * with the `Date.prototype` intrinsics. Only own data properties are read.\n * The renderer runs a stored job's metadata through it again.\n *\n * @throws {WebhookProjectionError} for a missing identifier, an invalid\n * date, an accessor property or a value that cannot be inspected.\n */\nexport function projectWebhookEventMetadata(envelope: unknown): WebhookEventMetadata {\n\treturn guard(() => snapshotEventMetadata(envelope), uninspectable(\"envelope\"));\n}\n\nfunction fanOutJob(envelope: unknown, options: unknown): WebhookFanOutJobDraft {\n\t// Snapshot: options, then envelope metadata, then the policy entry and\n\t// actor, then only the payload fields that entry names.\n\tif (!isPlainRecord(options)) return callFail(\"not_plain\", \"options\");\n\tconst policy = readOwn(options, \"policy\", \"policy\", callFail);\n\tconst rawActor = readOwn(options, \"actor\", \"actor\", callFail);\n\tconst event = snapshotEventMetadata(envelope);\n\tconst entry = snapshotPolicyEntry(policy, event.eventType);\n\tconst actor = snapshotActor(rawActor);\n\tconst restrictedWithoutOptIn = event.payloadClassification === \"restricted\" && entry?.includeRestricted !== true;\n\n\tlet payload: WebhookJsonObject | null = null;\n\tlet facts: WebhookJsonObject = EMPTY;\n\tif (entry && !restrictedWithoutOptIn && (entry.fields || entry.facts)) {\n\t\tconst source = readOwn(envelope as object, \"payload\", \"payload\", dataFail);\n\t\tif (isPlainRecord(source)) {\n\t\t\tconst copies = emptyMap<WebhookJsonValue>();\n\t\t\tif (entry.fields) snapshotNamed(source, entry.fields, payloadFail, copies);\n\t\t\tif (entry.facts) snapshotNamed(source, entry.facts, factFail, copies);\n\t\t\tif (entry.fields) payload = pick(copies, entry.fields);\n\t\t\tif (entry.facts) facts = pick(copies, entry.facts);\n\t\t}\n\t}\n\treturn record({\n\t\teventId: event.eventId,\n\t\ttenantId: event.tenantId,\n\t\tspaceId: event.spaceId,\n\t\tevent,\n\t\tpayload,\n\t\tpayloadProjected: payload !== null,\n\t\tfacts,\n\t\tactor,\n\t});\n}\n\nconst EMPTY: WebhookJsonObject = record({});\n\n/** @internal The policy entry for one event type, as a snapshot. */\nexport interface PolicyEntrySnapshot {\n\t/** `undefined` when the entry has no `fields` list. */\n\treadonly fields?: readonly string[];\n\treadonly facts?: readonly string[];\n\treadonly includeRestricted: boolean;\n\treadonly scoped: boolean;\n}\n\n/**\n * @internal Read the entry for `eventType` from a policy, own data\n * properties only. A missing policy or entry, or a non-object entry, is no\n * entry.\n */\nexport function snapshotPolicyEntry(policy: unknown, eventType: string): PolicyEntrySnapshot | undefined {\n\tif (policy === null || policy === undefined || typeof policy !== \"object\") return undefined;\n\tif (!isPlainRecord(policy)) return callFail(\"not_plain\", \"policy\");\n\tconst entry = readOwn(policy, eventType, \"policy\", callFail);\n\tif (entry === null || entry === undefined || typeof entry !== \"object\") return undefined;\n\tif (!isPlainRecord(entry)) return callFail(\"not_plain\", \"policy\");\n\tconst fields = stringList(readOwn(entry, \"fields\", \"policy\", callFail), \"policy\", callFail);\n\tconst facts = stringList(readOwn(entry, \"facts\", \"policy\", callFail), \"policy\", callFail);\n\treturn record({\n\t\tfields,\n\t\tfacts,\n\t\tincludeRestricted: readOwn(entry, \"includeRestricted\", \"policy\", callFail) === true,\n\t\tscoped: readOwn(entry, \"scoped\", \"policy\", callFail) === true,\n\t});\n}\n\n/**\n * @internal Snapshot each named field of `source` into `copies` (absent\n * and `undefined` fields are left out). A name whose value was already\n * copied is not read again. A repeated name whose first read found nothing\n * is read again, so a Proxy source may answer the second read differently;\n * plain data cannot.\n */\nexport function snapshotNamed(source: object, names: readonly string[], fail: Fail, copies: Record<string, WebhookJsonValue>): void {\n\tfor (let index = 0; index < names.length; index += 1) {\n\t\tconst name = names[index]!;\n\t\tif (hasOwn(copies, name)) continue;\n\t\tconst value = readOwn(source, name, name, fail);\n\t\tif (value === undefined) continue;\n\t\tdefine(copies, name, snapshotJson(value, name, fail));\n\t}\n}\n\n/** @internal A frozen null-prototype object of the named copies, in `names` order. */\nexport function pick(copies: Record<string, WebhookJsonValue>, names: readonly string[]): WebhookJsonObject {\n\tconst picked = emptyMap<WebhookJsonValue>();\n\tfor (let index = 0; index < names.length; index += 1) {\n\t\tconst name = names[index]!;\n\t\tif (hasOwn(copies, name) && !hasOwn(picked, name)) define(picked, name, copies[name]);\n\t}\n\treturn freeze(picked);\n}\n\nconst METADATA_KEYS = freeze([\n\t\"eventId\",\n\t\"eventType\",\n\t\"eventSchemaVersion\",\n\t\"tenantId\",\n\t\"spaceId\",\n\t\"subjectType\",\n\t\"subjectId\",\n\t\"sequence\",\n\t\"actionInvocationId\",\n\t\"correlationId\",\n\t\"causationId\",\n\t\"occurredAt\",\n\t\"recordedAt\",\n\t\"producerModuleVersion\",\n\t\"payloadClassification\",\n\t\"consistency\",\n] as const);\n\n/**\n * @internal Snapshot and validate envelope (or stored job) metadata: every\n * metadata field is read with one descriptor read, then checked.\n */\nexport function snapshotEventMetadata(source: unknown): WebhookEventMetadata {\n\tif (source === null || typeof source !== \"object\") return dataFail(\"not_plain\", \"envelope\");\n\tif (!isPlainRecord(source)) return dataFail(\"not_plain\", \"envelope\");\n\tconst raw = emptyMap<unknown>();\n\tfor (let index = 0; index < METADATA_KEYS.length; index += 1) {\n\t\tconst key = METADATA_KEYS[index]!;\n\t\tdefine(raw, key, readOwn(source, key, key, dataFail));\n\t}\n\tconst classification = raw.payloadClassification;\n\tif (classification !== \"public\" && classification !== \"internal\" && classification !== \"confidential\" && classification !== \"restricted\") {\n\t\treturn dataFail(\"not_json\", \"payloadClassification\");\n\t}\n\tconst consistency = raw.consistency;\n\tif (consistency !== undefined && consistency !== \"authoritative-now\" && consistency !== \"provisional-until-reconciled\") {\n\t\treturn dataFail(\"not_json\", \"consistency\");\n\t}\n\treturn record<WebhookEventMetadata>({\n\t\teventId: requireString(raw.eventId, \"eventId\"),\n\t\teventType: requireString(raw.eventType, \"eventType\"),\n\t\teventSchemaVersion: requireInteger(raw.eventSchemaVersion, \"eventSchemaVersion\"),\n\t\ttenantId: requireString(raw.tenantId, \"tenantId\"),\n\t\tspaceId: requireString(raw.spaceId, \"spaceId\"),\n\t\tsubjectType: requireString(raw.subjectType, \"subjectType\"),\n\t\tsubjectId: requireString(raw.subjectId, \"subjectId\"),\n\t\tsequence: requireInteger(raw.sequence, \"sequence\"),\n\t\tactionInvocationId: optionalString(raw.actionInvocationId, \"actionInvocationId\"),\n\t\tcorrelationId: requireString(raw.correlationId, \"correlationId\"),\n\t\tcausationId: optionalString(raw.causationId, \"causationId\"),\n\t\toccurredAt: requireIsoDate(raw.occurredAt, \"occurredAt\"),\n\t\trecordedAt: requireIsoDate(raw.recordedAt, \"recordedAt\"),\n\t\tproducerModuleVersion: requireString(raw.producerModuleVersion, \"producerModuleVersion\"),\n\t\tpayloadClassification: classification,\n\t\tconsistency,\n\t});\n}\n\nfunction snapshotActor(raw: unknown): WebhookJobActor {\n\tif (raw === undefined) return LEGACY_ACTOR;\n\tif (!isPlainRecord(raw)) return dataFail(\"not_plain\", \"actor\");\n\tconst state = readOwn(raw, \"state\", \"actor\", dataFail);\n\tif (state === \"present\") {\n\t\tconst actorId = readOwn(raw, \"actorId\", \"actorId\", dataFail);\n\t\tconst actorType = readOwn(raw, \"actorType\", \"actorType\", dataFail);\n\t\treturn record<WebhookJobActor>({\n\t\t\tstate: \"present\",\n\t\t\tactorId: requireString(actorId, \"actorId\"),\n\t\t\tactorType: requireString(actorType, \"actorType\"),\n\t\t});\n\t}\n\tconst reason = readOwn(raw, \"reason\", \"actor\", dataFail);\n\tif (state !== \"absent\" || (reason !== \"suppressed\" && reason !== \"legacy\")) return dataFail(\"not_json\", \"actor\");\n\treturn record<WebhookJobActor>({ state: \"absent\", reason });\n}\n\n/** @internal */\nexport function requireString(value: unknown, field: string): string {\n\tif (typeof value !== \"string\" || value.length === 0) return dataFail(\"not_json\", field);\n\treturn value;\n}\n\nfunction optionalString(value: unknown, field: string): string | undefined {\n\treturn value === undefined ? undefined : requireString(value, field);\n}\n\nfunction requireInteger(value: unknown, field: string): number {\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value)) return dataFail(\"not_json\", field);\n\treturn value;\n}\n\n/** A real `Date` or a date string, read with the intrinsics; never calls the value's own methods. */\nfunction requireIsoDate(value: unknown, field: string): string {\n\tconst iso = isoFromDateOrString(value);\n\tif (iso === undefined) return dataFail(\"not_json\", field);\n\treturn iso;\n}\n","import { guard, projectionError } from \"./errors\";\nimport {\n\tcallFail,\n\tdataFail,\n\tfactFail,\n\tpayloadFail,\n\tpick,\n\trequireString,\n\tsnapshotEventMetadata,\n\tsnapshotNamed,\n\tsnapshotPolicyEntry,\n\tuninspectable,\n\ttype PolicyEntrySnapshot,\n} from \"./persistence-projection\";\nimport type { WebhookScopeInput, WebhookScopePredicate } from \"./ports\";\nimport { apply, emptyMap, isPlainRecord, readOwn, record, serializeJson } from \"./snapshot\";\nimport type {\n\tWebhookDeliveryBodyV1,\n\tWebhookEventMetadata,\n\tWebhookFanOutJobDraft,\n\tWebhookJsonObject,\n\tWebhookJsonValue,\n\tWebhookPayloadPolicy,\n} from \"./types\";\n\n/** The v1 body's `format` value. Receivers read it from the raw body. */\nexport const WEBHOOK_DELIVERY_FORMAT_V1 = \"fabric.webhook-delivery.v1\" as const;\n\n/** The subscription a body is rendered for. */\nexport interface WebhookEgressSubscription {\n\treadonly subscriptionId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n}\n\n/** Inputs to {@link projectWebhookEgressPayload}. */\nexport interface WebhookEgressProjectionInput {\n\t/** The fan-out job; only what the persistence projection kept can leave. */\n\treadonly job: WebhookFanOutJobDraft;\n\treadonly subscription: WebhookEgressSubscription;\n\t/** The current allowlist; it is re-applied, so a narrowed entry takes effect. */\n\treadonly policy: WebhookPayloadPolicy;\n\t/** Consulted only for event types whose entry sets `scoped`. */\n\treadonly scopePredicate?: WebhookScopePredicate;\n}\n\n/** The payload that may leave for one subscription, and why it is metadata-only when it is. */\nexport interface WebhookEgressPayload {\n\treadonly payload: WebhookJsonObject | null;\n\treadonly payloadProjected: boolean;\n\t/**\n\t * Why the payload was withheld: no allowlist entry, nothing persisted, a\n\t * restricted event without opt-in, or a scoped type whose predicate was\n\t * missing, threw, or did not return `true`.\n\t */\n\treadonly withheld?:\n\t\t| \"no_allowlist_entry\"\n\t\t| \"not_persisted\"\n\t\t| \"restricted\"\n\t\t| \"scope_predicate_missing\"\n\t\t| \"scope_predicate_failed\"\n\t\t| \"scope_predicate_false\";\n}\n\ninterface Egress extends WebhookEgressPayload {\n\treadonly event: WebhookEventMetadata;\n\treadonly subscriptionId: string;\n}\n\ntype Withheld = NonNullable<WebhookEgressPayload[\"withheld\"]>;\n\n/** Everything the egress decision and the renderer use, snapshotted at entry. */\ninterface EgressSnapshot {\n\treadonly event: WebhookEventMetadata;\n\treadonly subscriptionId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly deliveryId?: string;\n\treadonly entry?: PolicyEntrySnapshot;\n\treadonly payloadProjected: boolean;\n\treadonly payloadPersisted: boolean;\n\t/** The entry's fields copied from the stored payload; only when it may leave. */\n\treadonly payload?: WebhookJsonObject;\n\treadonly facts: WebhookJsonObject;\n\treadonly scopePredicate?: WebhookScopePredicate;\n}\n\n/**\n * The egress projection (ADR 0018 decision 9). The payload leaves only when\n * the event type has an allowlist entry, the job persisted a payload, a\n * `restricted` event's entry opted in, and, for a scoped type, the injected\n * predicate returned exactly `true`. Otherwise the body is metadata-only:\n * `payload: null, payloadProjected: false`. The job is treated as input: it\n * is copied at entry, through own data property descriptors, into a\n * snapshot (a faithful copy for plain data; README, P1); its\n * metadata is re-derived and its payload re-copied from that snapshot. The\n * predicate runs after the snapshot is complete and sees frozen copies.\n *\n * @throws {WebhookProjectionError} `scope_mismatch` when the subscription\n * names another tenant or space than the job; other codes when the job or\n * subscription cannot be read safely.\n */\nexport function projectWebhookEgressPayload(input: WebhookEgressProjectionInput): WebhookEgressPayload {\n\treturn guard(() => {\n\t\tconst egress = decideEgress(snapshotEgress(input, false));\n\t\treturn record({ payload: egress.payload, payloadProjected: egress.payloadProjected, withheld: egress.withheld });\n\t}, uninspectable(\"job\"));\n}\n\nconst EMPTY: WebhookJsonObject = record({});\n\nfunction snapshotEgress(input: unknown, withDeliveryId: boolean): EgressSnapshot {\n\tif (!isPlainRecord(input)) return callFail(\"not_plain\", \"input\");\n\tconst job = readOwn(input, \"job\", \"job\", callFail);\n\tconst subscription = readOwn(input, \"subscription\", \"subscription\", callFail);\n\tconst policy = readOwn(input, \"policy\", \"policy\", callFail);\n\tconst scopePredicate = readOwn(input, \"scopePredicate\", \"scopePredicate\", callFail);\n\tconst rawDeliveryId = withDeliveryId ? readOwn(input, \"deliveryId\", \"deliveryId\", callFail) : undefined;\n\n\tif (!isPlainRecord(job)) return dataFail(\"not_plain\", \"job\");\n\tconst event = snapshotEventMetadata(readOwn(job, \"event\", \"event\", dataFail));\n\tif (!isPlainRecord(subscription)) return dataFail(\"not_plain\", \"subscription\");\n\tconst subscriptionId = requireString(readOwn(subscription, \"subscriptionId\", \"subscriptionId\", dataFail), \"subscriptionId\");\n\tconst tenantId = requireString(readOwn(subscription, \"tenantId\", \"tenantId\", dataFail), \"tenantId\");\n\tconst spaceId = requireString(readOwn(subscription, \"spaceId\", \"spaceId\", dataFail), \"spaceId\");\n\tif (tenantId !== event.tenantId || spaceId !== event.spaceId) throw projectionError(\"scope_mismatch\", \"subscription\");\n\tconst deliveryId = withDeliveryId ? requireString(rawDeliveryId, \"deliveryId\") : undefined;\n\n\tconst entry = snapshotPolicyEntry(policy, event.eventType);\n\tlet payloadProjected = false;\n\tlet payloadPersisted = false;\n\tlet payload: WebhookJsonObject | undefined;\n\tlet facts = EMPTY;\n\tif (entry?.fields) {\n\t\tpayloadProjected = readOwn(job, \"payloadProjected\", \"payloadProjected\", dataFail) === true;\n\t\tconst storedPayload = readOwn(job, \"payload\", \"payload\", dataFail);\n\t\tpayloadPersisted = isPlainRecord(storedPayload);\n\t\tconst restricted = event.payloadClassification === \"restricted\" && !entry.includeRestricted;\n\t\tif (payloadProjected && payloadPersisted && !restricted) {\n\t\t\tconst copies = emptyMap<WebhookJsonValue>();\n\t\t\tsnapshotNamed(storedPayload as object, entry.fields, payloadFail, copies);\n\t\t\tpayload = pick(copies, entry.fields);\n\t\t\tif (entry.scoped && entry.facts) {\n\t\t\t\tconst storedFacts = readOwn(job, \"facts\", \"facts\", dataFail);\n\t\t\t\tif (isPlainRecord(storedFacts)) {\n\t\t\t\t\tconst factCopies = emptyMap<WebhookJsonValue>();\n\t\t\t\t\tsnapshotNamed(storedFacts, entry.facts, factFail, factCopies);\n\t\t\t\t\tfacts = pick(factCopies, entry.facts);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn record<EgressSnapshot>({\n\t\tevent,\n\t\tsubscriptionId,\n\t\ttenantId,\n\t\tspaceId,\n\t\tdeliveryId,\n\t\tentry,\n\t\tpayloadProjected,\n\t\tpayloadPersisted,\n\t\tpayload,\n\t\tfacts,\n\t\tscopePredicate: typeof scopePredicate === \"function\" ? (scopePredicate as WebhookScopePredicate) : undefined,\n\t});\n}\n\n/** The egress decision over a snapshot. The scope predicate is the only code it calls. */\nfunction decideEgress(snapshot: EgressSnapshot): Egress {\n\tconst { event, subscriptionId, entry } = snapshot;\n\tconst metadataOnly = (reason: Withheld): Egress => record({ event, subscriptionId, payload: null, payloadProjected: false, withheld: reason });\n\tif (!entry || !entry.fields) return metadataOnly(\"no_allowlist_entry\");\n\tif (!snapshot.payloadProjected || !snapshot.payloadPersisted) return metadataOnly(\"not_persisted\");\n\tif (event.payloadClassification === \"restricted\" && !entry.includeRestricted) return metadataOnly(\"restricted\");\n\tif (entry.scoped) {\n\t\tconst predicate = snapshot.scopePredicate;\n\t\tif (predicate === undefined) return metadataOnly(\"scope_predicate_missing\");\n\t\tconst scopeInput = record<WebhookScopeInput>({\n\t\t\tsubscriptionId,\n\t\t\ttenantId: snapshot.tenantId,\n\t\t\tspaceId: snapshot.spaceId,\n\t\t\tevent,\n\t\t\tfacts: snapshot.facts,\n\t\t});\n\t\tlet admitted: unknown;\n\t\ttry {\n\t\t\tadmitted = apply(predicate, undefined, [scopeInput]);\n\t\t} catch {\n\t\t\t// The thrown value is dropped unread.\n\t\t\treturn metadataOnly(\"scope_predicate_failed\");\n\t\t}\n\t\tif (admitted !== true) return metadataOnly(\"scope_predicate_false\");\n\t}\n\treturn record({ event, subscriptionId, payload: snapshot.payload ?? EMPTY, payloadProjected: true });\n}\n\n/** Inputs to {@link renderWebhookDeliveryBodyV1}. */\nexport interface WebhookRenderInput extends WebhookEgressProjectionInput {\n\treadonly deliveryId: string;\n}\n\n/** A rendered v1 body: the object and the exact string that is stored, signed and sent. */\nexport interface WebhookRenderedBody {\n\treadonly body: WebhookDeliveryBodyV1;\n\treadonly rawBody: string;\n\treadonly withheld?: WebhookEgressPayload[\"withheld\"];\n}\n\n/**\n * Render the `fabric.webhook-delivery.v1` body (ADR 0018 decision 7) in the\n * ADR's field order. `consistency` appears only for provisional events;\n * `actionInvocationId` only when the event has one. The body names no\n * eligibility revision, configuration version or actor. Every value in it\n * comes from the input's snapshot (see {@link projectWebhookEgressPayload}),\n * and `rawBody` is serialized by the package from that snapshot, so no\n * `toJSON`, getter or prototype member of any object takes part.\n */\nexport function renderWebhookDeliveryBodyV1(input: WebhookRenderInput): WebhookRenderedBody {\n\treturn guard(() => {\n\t\tconst snapshot = snapshotEgress(input, true);\n\t\tconst projected = decideEgress(snapshot);\n\t\tconst { event } = projected;\n\t\tconst body = record<WebhookDeliveryBodyV1>({\n\t\t\tformat: WEBHOOK_DELIVERY_FORMAT_V1,\n\t\t\teventId: event.eventId,\n\t\t\ttype: event.eventType,\n\t\t\ttenantId: event.tenantId,\n\t\t\tspaceId: event.spaceId,\n\t\t\tcorrelationId: event.correlationId,\n\t\t\toccurredAt: event.occurredAt,\n\t\t\tevent: record<WebhookDeliveryBodyV1[\"event\"]>({\n\t\t\t\ttype: event.eventType,\n\t\t\t\tschemaVersion: event.eventSchemaVersion,\n\t\t\t\tsubjectType: event.subjectType,\n\t\t\t\tsubjectId: event.subjectId,\n\t\t\t\tsequence: event.sequence,\n\t\t\t\trecordedAt: event.recordedAt,\n\t\t\t\tactionInvocationId: event.actionInvocationId,\n\t\t\t\tconsistency: event.consistency === \"provisional-until-reconciled\" ? event.consistency : undefined,\n\t\t\t\tpayload: projected.payload,\n\t\t\t\tpayloadProjected: projected.payloadProjected,\n\t\t\t}),\n\t\t\tdelivery: record({\n\t\t\t\tdeliveryId: snapshot.deliveryId!,\n\t\t\t\tsubscriptionId: projected.subscriptionId,\n\t\t\t}),\n\t\t});\n\t\treturn record({ body, rawBody: serializeJson(body), withheld: projected.withheld });\n\t}, uninspectable(\"job\"));\n}\n","import { guard, inputError } from \"./errors\";\nimport { isPlainRecord, matches, numberIsSafeInteger, primitive, readOwn, record, type Fail } from \"./snapshot\";\n\n/** Header names of a v1 delivery (ADR 0018 decision 7). Only the signature and timestamp are signed. */\nexport const WEBHOOK_HEADERS = Object.freeze({\n\tsignature: \"X-Fabric-Signature\",\n\ttimestamp: \"X-Fabric-Timestamp\",\n\teventId: \"X-Fabric-Event-Id\",\n\tdeliveryId: \"X-Fabric-Delivery-Id\",\n\tattempt: \"X-Fabric-Delivery-Attempt\",\n\tcontentType: \"Content-Type\",\n} as const);\n\nconst V1_SIGNATURE = /^v1=[0-9a-f]{64}$/;\n\n/**\n * A header-safe identifier: visible ASCII, inner spaces allowed, no CR, LF,\n * NUL or other control characters, and no leading or trailing space (which a\n * receiver's header parser would trim, making the header disagree with the\n * signed body).\n */\nconst HEADER_SAFE_ID = /^[\\x21-\\x7e](?:[\\x20-\\x7e]*[\\x21-\\x7e])?$/;\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/**\n * The exact string a `v1` signer MACs: `\"<timestampSeconds>.<rawBody>\"`. The\n * signature is `v1=` + hex(HMAC-SHA256(secret, this string as UTF-8)).\n *\n * @throws {RangeError} `timestamp_invalid` when the timestamp is not a\n * non-negative whole number of seconds.\n * @throws {TypeError} `raw_body_not_string` when the body is not a string.\n */\nexport function webhookSignedContentV1(timestampSeconds: number, rawBody: string): string {\n\treturn guard(() => {\n\t\tconst timestamp = primitive(timestampSeconds);\n\t\tconst body = primitive(rawBody);\n\t\tassertTimestampSeconds(timestamp);\n\t\tif (typeof body !== \"string\") throw inputError(\"type\", \"raw_body_not_string\");\n\t\treturn `${timestamp}.${body}`;\n\t}, unreadable);\n}\n\n/** Inputs to {@link buildWebhookRequestHeaders}. */\nexport interface WebhookRequestHeaderInput {\n\t/** The signer's `v1=<64 lowercase hex>` value. */\n\treadonly signature: string;\n\treadonly timestampSeconds: number;\n\treadonly eventId: string;\n\treadonly deliveryId: string;\n\t/** 1-based attempt number. */\n\treadonly attempt: number;\n}\n\n/**\n * Build the headers of one attempt. A signature that is not a well-formed\n * `v1` value is refused rather than sent, so a misbehaving signer cannot put\n * arbitrary text on the wire. The input is copied at entry into a snapshot,\n * one descriptor read per field (an accessor is refused, not called); the\n * headers are built from the snapshot values that were validated, never\n * from a second read.\n *\n * @throws {TypeError | RangeError} with a constant message and a `code` from\n * `WEBHOOK_INPUT_ERROR_CODES` for a malformed signature, timestamp,\n * identifier or attempt, or an input that cannot be read.\n */\nexport function buildWebhookRequestHeaders(input: WebhookRequestHeaderInput): Readonly<Record<string, string>> {\n\treturn guard(() => {\n\t\tif (!isPlainRecord(input)) throw unreadable();\n\t\tconst signature = primitive(readOwn(input, \"signature\", \"signature\", unreadableFail));\n\t\tconst timestampSeconds = primitive(readOwn(input, \"timestampSeconds\", \"timestampSeconds\", unreadableFail));\n\t\tconst eventId = primitive(readOwn(input, \"eventId\", \"eventId\", unreadableFail));\n\t\tconst deliveryId = primitive(readOwn(input, \"deliveryId\", \"deliveryId\", unreadableFail));\n\t\tconst attempt = primitive(readOwn(input, \"attempt\", \"attempt\", unreadableFail));\n\n\t\tif (typeof signature !== \"string\" || !matches(V1_SIGNATURE, signature)) throw inputError(\"type\", \"signature_malformed\");\n\t\tassertTimestampSeconds(timestampSeconds);\n\t\tif (typeof eventId !== \"string\" || !matches(HEADER_SAFE_ID, eventId)) throw inputError(\"type\", \"event_id_invalid\");\n\t\tif (typeof deliveryId !== \"string\" || !matches(HEADER_SAFE_ID, deliveryId)) throw inputError(\"type\", \"delivery_id_invalid\");\n\t\tif (typeof attempt !== \"number\" || !numberIsSafeInteger(attempt) || attempt < 1) throw inputError(\"range\", \"attempt_invalid\");\n\t\treturn record<Record<string, string>>({\n\t\t\t[WEBHOOK_HEADERS.contentType]: \"application/json\",\n\t\t\t[WEBHOOK_HEADERS.signature]: signature,\n\t\t\t[WEBHOOK_HEADERS.timestamp]: `${timestampSeconds}`,\n\t\t\t[WEBHOOK_HEADERS.eventId]: eventId,\n\t\t\t[WEBHOOK_HEADERS.deliveryId]: deliveryId,\n\t\t\t[WEBHOOK_HEADERS.attempt]: `${attempt}`,\n\t\t});\n\t}, unreadable);\n}\n\nfunction assertTimestampSeconds(value: unknown): asserts value is number {\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < 0) throw inputError(\"range\", \"timestamp_invalid\");\n}\n","import { apply, freeze, matches } from \"./snapshot\";\n\n/*\n * Which IP addresses a webhook may be sent to (ADR 0018 decision 6, R8).\n * Portable: no Node built-ins, so the main entry stays runtime-neutral.\n *\n * IPv4 is a deny list of every special-purpose block IANA marks as not\n * globally reachable, plus multicast and the reserved 240/4. IPv6 is an\n * allow list: only global unicast (2000::/3) can pass, so any block outside\n * it (unspecified, loopback, IPv4-mapped, IPv4-compatible, SIIT, the\n * local-use NAT64 prefix, discard-only, SRv6, unique-local, site-local,\n * link-local, multicast) is refused without being listed. Inside 2000::/3 the\n * non-global blocks are refused, and the three that embed an IPv4 address\n * (NAT64 well-known prefix, 6to4, Teredo) pass only when every embedded\n * address is itself public.\n */\n\nconst stringCharCodeAt = String.prototype.charCodeAt;\nconst stringIndexOf = String.prototype.indexOf;\nconst stringSlice = String.prototype.slice;\nconst stringSplit = String.prototype.split;\n\n/** Longest address text parsed: a full IPv6 form with an embedded IPv4 tail is 45 characters. */\nconst MAX_ADDRESS_LENGTH = 45;\n/** Longest text inspected at all, leaving room for a zone index. */\nconst MAX_TEXT_LENGTH = 64;\n\nconst IPV4_OCTET = \"(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\";\n/** Canonical dotted-quad only: no leading zeros, no shorthand, no hex. */\nconst IPV4_DOTTED = new RegExp(`^${IPV4_OCTET}(?:\\\\.${IPV4_OCTET}){3}$`);\nconst HEX_GROUP = /^[0-9A-Fa-f]{1,4}$/;\n\n/** An IPv4 block: network address as an unsigned 32-bit integer and prefix length. */\ninterface Ipv4Block {\n\treadonly base: number;\n\treadonly prefix: number;\n}\n\nfunction ipv4Block(a: number, b: number, c: number, d: number, prefix: number): Ipv4Block {\n\treturn freeze({ base: (((a << 24) | (b << 16) | (c << 8) | d) >>> 0), prefix });\n}\n\n/**\n * IPv4 blocks that are never a webhook destination. The IANA IPv4\n * Special-Purpose Address Registry's not-globally-reachable entries, plus\n * multicast (224.0.0.0/4) and reserved space (240.0.0.0/4, which holds the\n * limited broadcast address). 192.0.0.0/24 is refused whole, including the\n * two anycast /32s in it that IANA marks reachable; neither is a webhook\n * receiver.\n */\nconst REFUSED_IPV4_BLOCKS: readonly Ipv4Block[] = freeze([\n\tipv4Block(0, 0, 0, 0, 8), // \"this network\", including the unspecified 0.0.0.0\n\tipv4Block(10, 0, 0, 0, 8), // private\n\tipv4Block(100, 64, 0, 0, 10), // shared address space (CGNAT)\n\tipv4Block(127, 0, 0, 0, 8), // loopback\n\tipv4Block(169, 254, 0, 0, 16), // link-local, including cloud metadata endpoints\n\tipv4Block(172, 16, 0, 0, 12), // private\n\tipv4Block(192, 0, 0, 0, 24), // IETF protocol assignments\n\tipv4Block(192, 0, 2, 0, 24), // documentation (TEST-NET-1)\n\tipv4Block(192, 88, 99, 0, 24), // deprecated 6to4 relay anycast\n\tipv4Block(192, 168, 0, 0, 16), // private\n\tipv4Block(198, 18, 0, 0, 15), // benchmarking\n\tipv4Block(198, 51, 100, 0, 24), // documentation (TEST-NET-2)\n\tipv4Block(203, 0, 113, 0, 24), // documentation (TEST-NET-3)\n\tipv4Block(224, 0, 0, 0, 4), // multicast\n\tipv4Block(240, 0, 0, 0, 4), // reserved, including 255.255.255.255\n]);\n\nfunction inIpv4Block(value: number, block: Ipv4Block): boolean {\n\tconst mask = block.prefix === 0 ? 0 : (0xffffffff << (32 - block.prefix)) >>> 0;\n\treturn ((value & mask) >>> 0) === block.base;\n}\n\n/** `true` when an IPv4 address, as an unsigned 32-bit integer, is publicly routable. */\nfunction isPublicIpv4Value(value: number): boolean {\n\tfor (let index = 0; index < REFUSED_IPV4_BLOCKS.length; index += 1) {\n\t\tif (inIpv4Block(value, REFUSED_IPV4_BLOCKS[index]!)) return false;\n\t}\n\treturn true;\n}\n\n/** Parse a canonical dotted-quad to an unsigned 32-bit integer, or `undefined`. */\nfunction parseIpv4(text: string): number | undefined {\n\tif (!matches(IPV4_DOTTED, text)) return undefined;\n\tconst parts = apply(stringSplit, text, [\".\"]) as string[];\n\tlet value = 0;\n\tfor (let index = 0; index < 4; index += 1) value = value * 256 + decimal(parts[index]!);\n\treturn value >>> 0;\n}\n\nfunction decimal(text: string): number {\n\tlet value = 0;\n\tfor (let index = 0; index < text.length; index += 1) value = value * 10 + ((apply(stringCharCodeAt, text, [index]) as number) - 48);\n\treturn value;\n}\n\nfunction hex(text: string): number {\n\tlet value = 0;\n\tfor (let index = 0; index < text.length; index += 1) {\n\t\tconst code = apply(stringCharCodeAt, text, [index]) as number;\n\t\tconst digit = code <= 57 ? code - 48 : code <= 70 ? code - 55 : code - 87;\n\t\tvalue = value * 16 + digit;\n\t}\n\treturn value;\n}\n\n/** Parse one side of an IPv6 address (no `::`) into 16-bit words; `tailIpv4` allows a dotted last group. */\nfunction parseIpv6Groups(text: string, tailIpv4: boolean): number[] | undefined {\n\tconst words: number[] = [];\n\tif (text === \"\") return words;\n\tconst groups = apply(stringSplit, text, [\":\"]) as string[];\n\tfor (let index = 0; index < groups.length; index += 1) {\n\t\tconst group = groups[index]!;\n\t\tif (tailIpv4 && index === groups.length - 1 && (apply(stringIndexOf, group, [\".\"]) as number) !== -1) {\n\t\t\tconst v4 = parseIpv4(group);\n\t\t\tif (v4 === undefined) return undefined;\n\t\t\twords[words.length] = v4 >>> 16;\n\t\t\twords[words.length] = v4 & 0xffff;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!matches(HEX_GROUP, group)) return undefined;\n\t\twords[words.length] = hex(group);\n\t}\n\treturn words;\n}\n\n/** Parse an IPv6 address (no brackets, no zone) into eight 16-bit words, or `undefined`. */\nfunction parseIpv6(text: string): number[] | undefined {\n\tconst gap = apply(stringIndexOf, text, [\"::\"]) as number;\n\tif (gap === -1) {\n\t\tconst words = parseIpv6Groups(text, true);\n\t\treturn words !== undefined && words.length === 8 ? words : undefined;\n\t}\n\tif ((apply(stringIndexOf, text, [\"::\", gap + 1]) as number) !== -1) return undefined;\n\tconst head = parseIpv6Groups(apply(stringSlice, text, [0, gap]) as string, false);\n\tconst tail = parseIpv6Groups(apply(stringSlice, text, [gap + 2]) as string, true);\n\tif (head === undefined || tail === undefined || head.length + tail.length > 7) return undefined;\n\tconst words: number[] = [];\n\tfor (let index = 0; index < head.length; index += 1) words[words.length] = head[index]!;\n\tfor (let index = head.length + tail.length; index < 8; index += 1) words[words.length] = 0;\n\tfor (let index = 0; index < tail.length; index += 1) words[words.length] = tail[index]!;\n\treturn words;\n}\n\n/** The IPv4 address held in two consecutive 16-bit words. */\nfunction embeddedIpv4(high: number, low: number): number {\n\treturn ((high << 16) | low) >>> 0;\n}\n\n/** `true` when an IPv6 address, as eight 16-bit words, is publicly routable. */\nfunction isPublicIpv6Words(w: readonly number[]): boolean {\n\t// NAT64 well-known prefix 64:ff9b::/96 (RFC 6052): public only when the\n\t// IPv4 address in its last 32 bits is. The local-use prefix\n\t// 64:ff9b:1::/48 (RFC 8215) is outside 2000::/3 and refused below: the\n\t// operator picks the prefix length inside it, so the embedded address\n\t// cannot be decoded from the address alone.\n\tif (w[0] === 0x0064 && w[1] === 0xff9b && w[2] === 0 && w[3] === 0 && w[4] === 0 && w[5] === 0) {\n\t\treturn isPublicIpv4Value(embeddedIpv4(w[6]!, w[7]!));\n\t}\n\t// Only global unicast can pass.\n\tif ((w[0]! & 0xe000) !== 0x2000) return false;\n\tif (w[0] === 0x2001 && (w[1]! & 0xfe00) === 0) {\n\t\t// 2001::/23, IETF protocol assignments. Teredo (2001::/32, RFC 4380)\n\t\t// carries its server's IPv4 address in words 2-3 and its client's,\n\t\t// bit-inverted, in words 6-7; both must be public. The rest of the /23\n\t\t// (benchmarking, ORCHID, AMT, AS112 and later assignments) is not a\n\t\t// webhook destination.\n\t\tif (w[1] !== 0) return false;\n\t\tconst server = embeddedIpv4(w[2]!, w[3]!);\n\t\tconst client = (~embeddedIpv4(w[6]!, w[7]!)) >>> 0;\n\t\treturn isPublicIpv4Value(server) && isPublicIpv4Value(client);\n\t}\n\tif (w[0] === 0x2001 && w[1] === 0x0db8) return false; // documentation, 2001:db8::/32\n\tif (w[0] === 0x3fff && (w[1]! & 0xf000) === 0) return false; // documentation, 3fff::/20 (RFC 9637)\n\t// 6to4 (2002::/16, RFC 3056): the IPv4 address in words 1-2 must be public.\n\tif (w[0] === 0x2002) return isPublicIpv4Value(embeddedIpv4(w[1]!, w[2]!));\n\treturn true;\n}\n\n/** RFC 5952 text for eight 16-bit words: lowercase, no leading zeros, the longest zero run of two or more compressed. */\nfunction formatIpv6(w: readonly number[]): string {\n\tlet bestStart = -1;\n\tlet bestLength = 0;\n\tfor (let index = 0; index < 8; ) {\n\t\tif (w[index] !== 0) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tlet end = index;\n\t\twhile (end < 8 && w[end] === 0) end += 1;\n\t\tif (end - index > bestLength) {\n\t\t\tbestStart = index;\n\t\t\tbestLength = end - index;\n\t\t}\n\t\tindex = end;\n\t}\n\tif (bestLength < 2) bestStart = -1;\n\tlet text = \"\";\n\tfor (let index = 0; index < 8; index += 1) {\n\t\tif (index === bestStart) {\n\t\t\ttext += \"::\";\n\t\t\tindex += bestLength - 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (text !== \"\" && !endsWithColons(text)) text += \":\";\n\t\ttext += hexText(w[index]!);\n\t}\n\treturn text;\n}\n\nfunction endsWithColons(text: string): boolean {\n\treturn text.length >= 2 && (apply(stringSlice, text, [-2]) as string) === \"::\";\n}\n\nconst HEX_DIGITS = \"0123456789abcdef\";\n\nfunction hexText(value: number): string {\n\tif (value === 0) return \"0\";\n\tlet text = \"\";\n\tfor (let rest = value; rest > 0; rest = (rest - (rest % 16)) / 16) text = HEX_DIGITS[rest % 16]! + text;\n\treturn text;\n}\n\nfunction formatIpv4(value: number): string {\n\treturn `${value >>> 24}.${(value >>> 16) & 0xff}.${(value >>> 8) & 0xff}.${value & 0xff}`;\n}\n\n/**\n * @internal What one textual IP address is, for the destination rules.\n * `malformed` is anything that is not a canonical dotted-quad or a valid\n * IPv6 address; a zone index (`%eth0`) makes an address `non_public`, since\n * only link-scoped addresses carry one.\n */\nexport type WebhookAddressVerdict =\n\t| { readonly kind: \"public\"; readonly address: string; readonly family: 4 | 6 }\n\t| { readonly kind: \"non_public\"; readonly family: 4 | 6 }\n\t| { readonly kind: \"malformed\" };\n\nconst NON_PUBLIC_V4: WebhookAddressVerdict = freeze({ kind: \"non_public\", family: 4 });\nconst NON_PUBLIC_V6: WebhookAddressVerdict = freeze({ kind: \"non_public\", family: 6 });\nconst MALFORMED: WebhookAddressVerdict = freeze({ kind: \"malformed\" });\n\n/** @internal Classify a textual IP address (no brackets). The `address` of a public verdict is canonical. */\nexport function classifyAddress(text: unknown): WebhookAddressVerdict {\n\tif (typeof text !== \"string\" || text.length === 0 || text.length > MAX_TEXT_LENGTH) return MALFORMED;\n\tconst zone = apply(stringIndexOf, text, [\"%\"]) as number;\n\tif (zone !== -1) return parseIpv6(apply(stringSlice, text, [0, zone]) as string) === undefined ? MALFORMED : NON_PUBLIC_V6;\n\tif (text.length > MAX_ADDRESS_LENGTH) return MALFORMED;\n\tconst v4 = parseIpv4(text);\n\tif (v4 !== undefined) {\n\t\treturn isPublicIpv4Value(v4) ? freeze({ kind: \"public\", address: formatIpv4(v4), family: 4 }) : NON_PUBLIC_V4;\n\t}\n\tconst v6 = parseIpv6(text);\n\tif (v6 === undefined) return MALFORMED;\n\treturn isPublicIpv6Words(v6) ? freeze({ kind: \"public\", address: formatIpv6(v6), family: 6 }) : NON_PUBLIC_V6;\n}\n\n/** @internal `true` for a canonical dotted-quad, the form WHATWG URL parsing gives an IPv4 host. */\nexport function isIpv4Literal(text: string): boolean {\n\treturn matches(IPV4_DOTTED, text);\n}\n\n/**\n * `true` when `address` is a well-formed IPv4 (canonical dotted-quad) or\n * IPv6 address that a webhook may be sent to: not loopback, private,\n * link-local, shared (CGNAT), multicast, reserved, unspecified,\n * documentation, benchmarking, unique-local, site-local, IPv4-mapped,\n * IPv4-compatible, or outside IPv6 global unicast; and, for NAT64\n * (`64:ff9b::/96`), 6to4 (`2002::/16`) and Teredo (`2001::/32`), only when\n * every embedded IPv4 address is public. Anything that does not parse is\n * `false`. The README lists every refused block.\n */\nexport function isPublicWebhookAddress(address: string): boolean {\n\treturn classifyAddress(address).kind === \"public\";\n}\n","import { inputError } from \"./errors\";\nimport { WEBHOOK_MAX_TIMER_MS } from \"./limits\";\nimport type { WebhookClock } from \"./ports\";\nimport { apply, readOwn, timeOf, type Fail } from \"./snapshot\";\n\n/*\n * Deadline, signal, clock and timer handling shared by the destination\n * resolver and the Node transport. Portable: it uses only the WHATWG\n * `AbortSignal`/`EventTarget` and the timer globals every supported runtime\n * has, captured at module load.\n */\n\nconst reflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;\nconst abortedGetter = typeof AbortSignal === \"function\" ? reflectGetOwnPropertyDescriptor(AbortSignal.prototype, \"aborted\")?.get : undefined;\nconst eventTargetAdd = typeof EventTarget === \"function\" ? EventTarget.prototype.addEventListener : undefined;\nconst eventTargetRemove = typeof EventTarget === \"function\" ? EventTarget.prototype.removeEventListener : undefined;\nconst setTimer = setTimeout;\nconst clearTimer = clearTimeout;\nconst dateNow = Date.now;\nconst mathMax = Math.max;\nconst mathMin = Math.min;\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/** @internal The `{ deadline, signal }` of one call, read at entry. */\nexport interface CallBounds {\n\treadonly deadlineMs: number;\n\treadonly signal: AbortSignal;\n}\n\n/**\n * @internal Read `{ deadline, signal }` at entry, one descriptor read each.\n * The deadline must be a real `Date` with a finite time and the signal a real\n * `AbortSignal`; anything else throws `input_unreadable`.\n */\nexport function readCallBounds(options: unknown): CallBounds {\n\tif (options === null || typeof options !== \"object\") throw unreadable();\n\tconst deadlineMs = timeOf(readOwn(options, \"deadline\", \"deadline\", unreadableFail));\n\tif (!(deadlineMs === deadlineMs) || deadlineMs === Infinity || deadlineMs === -Infinity) throw unreadable();\n\tconst signal = readOwn(options, \"signal\", \"signal\", unreadableFail);\n\tif (signal === null || typeof signal !== \"object\") throw unreadable();\n\ttry {\n\t\tisAborted(signal as AbortSignal);\n\t} catch {\n\t\tthrow unreadable();\n\t}\n\treturn { deadlineMs, signal: signal as AbortSignal };\n}\n\n/**\n * @internal Whether a real `AbortSignal` has aborted, read through the\n * intrinsic getter (it throws for anything else and runs none of its code).\n */\nexport function isAborted(signal: AbortSignal): boolean {\n\tif (abortedGetter === undefined) throw unreadable();\n\treturn apply(abortedGetter, signal, []) === true;\n}\n\n/** @internal Call `listener` once when `signal` aborts; the returned function removes it. */\nexport function onAbort(signal: AbortSignal, listener: () => void): () => void {\n\tif (eventTargetAdd === undefined || eventTargetRemove === undefined) throw unreadable();\n\tapply(eventTargetAdd, signal, [\"abort\", listener, { once: true }]);\n\treturn () => {\n\t\tapply(eventTargetRemove, signal, [\"abort\", listener]);\n\t};\n}\n\n/** @internal A clock captured at construction, or the system clock when none was injected. */\nexport interface CapturedClock {\n\treadonly target: object | undefined;\n\treadonly now: ((...args: never[]) => unknown) | undefined;\n}\n\n/** @internal Capture an optional {@link WebhookClock}; a non-object or a missing `now` throws `input_unreadable`. */\nexport function captureOptionalClock(clock: unknown): CapturedClock {\n\tif (clock === undefined) return { target: undefined, now: undefined };\n\tif (clock === null || typeof clock !== \"object\") throw unreadable();\n\tconst now = (clock as Partial<WebhookClock>).now;\n\tif (typeof now !== \"function\") throw unreadable();\n\treturn { target: clock, now: now as (...args: never[]) => unknown };\n}\n\n/** @internal Epoch milliseconds from the clock, or `NaN` when it throws or returns no valid `Date`. Never throws. */\nexport function clockNowMs(clock: CapturedClock): number {\n\tif (clock.now === undefined) return dateNow();\n\ttry {\n\t\tconst ms = timeOf(apply(clock.now, clock.target, []));\n\t\treturn ms === Infinity || ms === -Infinity ? NaN : ms;\n\t} catch {\n\t\treturn NaN;\n\t}\n}\n\n/**\n * @internal Run `fire` after `ms`, clamped to `[0, WEBHOOK_MAX_TIMER_MS]` so a\n * far deadline cannot overflow into an immediate timer. Returns a cancel\n * function.\n */\nexport function startTimer(ms: number, fire: () => void): () => void {\n\tconst handle = setTimer(fire, mathMax(0, mathMin(ms, WEBHOOK_MAX_TIMER_MS)));\n\treturn () => {\n\t\tclearTimer(handle);\n\t};\n}\n","import { classifyAddress, isIpv4Literal } from \"./address\";\nimport { readCallBounds, captureOptionalClock, clockNowMs, isAborted, onAbort, startTimer, type CapturedClock } from \"./call-bounds\";\nimport { configError, guard, inputError } from \"./errors\";\nimport { WEBHOOK_MAX_TIMER_MS, assertPositiveFinite } from \"./limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookDestinationResolution,\n\tWebhookDestinationResolver,\n\tWebhookResolvedAddress,\n\tWebhookVettedDestination,\n} from \"./ports\";\nimport { apply, emptyMap, freeze, frozenList, isArray, isPlainRecord, matches, numberIsSafeInteger, primitive, readOwn, record, type Fail } from \"./snapshot\";\n\n/*\n * Destination rules and resolution (ADR 0018 decision 6, R8). Portable: the\n * DNS lookup is injected, so the main entry needs no Node built-in. The Node\n * lookup and transport are at `@fabricorg/webhook-delivery/node`.\n */\n\n/** The longest destination URL accepted, in UTF-16 code units. */\nexport const WEBHOOK_DESTINATION_MAX_URL_LENGTH = 2_048;\n/** The most addresses one lookup may return; a longer answer is refused as `dns_failure`. */\nexport const WEBHOOK_DESTINATION_MAX_ADDRESSES = 32;\n/** The default bound on one DNS lookup. */\nexport const DEFAULT_WEBHOOK_LOOKUP_TIMEOUT_MS = 5_000;\n\nconst URLConstructor = URL;\nconst urlGetter = (name: string): ((this: URL) => string) => {\n\tconst getter = Reflect.getOwnPropertyDescriptor(URL.prototype, name)?.get;\n\tif (getter === undefined) throw new TypeError(`URL.prototype.${name} is not an accessor.`);\n\treturn getter as (this: URL) => string;\n};\nconst urlProtocol = urlGetter(\"protocol\");\nconst urlUsername = urlGetter(\"username\");\nconst urlPassword = urlGetter(\"password\");\nconst urlPort = urlGetter(\"port\");\nconst urlHostname = urlGetter(\"hostname\");\nconst urlPathname = urlGetter(\"pathname\");\nconst urlSearch = urlGetter(\"search\");\nconst stringSlice = String.prototype.slice;\nconst stringEndsWith = String.prototype.endsWith;\nconst PromiseConstructor = Promise;\nconst promiseThen = Promise.prototype.then;\nconst AbortControllerConstructor = AbortController;\nconst abortControllerAbort = AbortController.prototype.abort;\nconst abortControllerSignal = Reflect.getOwnPropertyDescriptor(AbortController.prototype, \"signal\")!.get!;\nconst DateConstructor = Date;\n\n/** No ASCII control character or space anywhere: WHATWG parsing would strip or drop them silently. */\nconst URL_TEXT = /^[^\\x00-\\x20\\x7f]+$/;\n/**\n * `https://` then a host character. WHATWG parsing also accepts\n * `https:host`, `https:///host` and backslashes for a special scheme and\n * finds a host in them; requiring the plain form keeps the host an operator\n * sees in the URL the one that is checked.\n */\nconst URL_PREFIX = /^https:\\/\\/[^/\\\\?#@]/i;\n\n/** The result of checking a destination URL's rules, before any DNS lookup. */\nexport type WebhookDestinationUrlCheck =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** `https://<host><path><query>`: normalized by WHATWG URL parsing, fragment dropped. */\n\t\t\treadonly url: string;\n\t\t\t/** The host without IPv6 brackets: the SNI name and certificate identity. */\n\t\t\treadonly hostname: string;\n\t\t\t/** Set when the host is an IP literal; it is the only address the destination may use. */\n\t\t\treadonly literal?: WebhookResolvedAddress;\n\t }\n\t| { readonly ok: false; readonly code: \"invalid_url\" | \"private_address\" };\n\nconst INVALID_URL: WebhookDestinationUrlCheck = freeze({ ok: false, code: \"invalid_url\" });\nconst PRIVATE_URL: WebhookDestinationUrlCheck = freeze({ ok: false, code: \"private_address\" });\n\n/**\n * Check a destination URL against decision 6's rules without resolving it.\n * `invalid_url` when it is not a string of at most\n * {@link WEBHOOK_DESTINATION_MAX_URL_LENGTH} characters with no ASCII\n * control character or space, does not start with `https://` and a host\n * character (WHATWG would find a host in `https:host` or `https:///host`),\n * does not parse, is not `https:`, names a port\n * other than 443 (an explicit `:443` is the default and accepted), carries\n * userinfo, or has an empty host or one ending in `.`. `private_address` when\n * the host is `localhost` or a `.localhost` name, or an IP literal that is not\n * public ({@link isPublicWebhookAddress}). A public IP literal passes and is\n * returned as `literal`. IPv4 literals in decimal, hex, octal or shorthand\n * form are normalized to dotted-quad by URL parsing before they are checked.\n * Never throws.\n */\nexport function checkWebhookDestinationUrl(url: string): WebhookDestinationUrlCheck {\n\treturn checkDestinationUrl(url, false);\n}\n\n/**\n * @internal {@link checkWebhookDestinationUrl}, optionally accepting a\n * non-public host (an IP literal or a `localhost` name) while every other\n * rule still applies. `true` is passed only when the Node transport was built\n * by the internal test factory with its public-address re-check off.\n */\nexport function checkDestinationUrl(url: unknown, allowNonPublic: boolean): WebhookDestinationUrlCheck {\n\ttry {\n\t\treturn checkUrl(primitive(url), allowNonPublic);\n\t} catch {\n\t\treturn INVALID_URL;\n\t}\n}\n\nfunction checkUrl(text: unknown, allowNonPublic: boolean): WebhookDestinationUrlCheck {\n\tif (typeof text !== \"string\" || text.length === 0 || text.length > WEBHOOK_DESTINATION_MAX_URL_LENGTH) return INVALID_URL;\n\tif (!matches(URL_TEXT, text) || !matches(URL_PREFIX, text)) return INVALID_URL;\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URLConstructor(text);\n\t} catch {\n\t\treturn INVALID_URL;\n\t}\n\tif (apply(urlProtocol, parsed, []) !== \"https:\") return INVALID_URL;\n\tif (apply(urlUsername, parsed, []) !== \"\" || apply(urlPassword, parsed, []) !== \"\") return INVALID_URL;\n\t// WHATWG parsing drops the scheme's default port, so `:443` reads as \"\".\n\tif (apply(urlPort, parsed, []) !== \"\") return INVALID_URL;\n\tconst host = apply(urlHostname, parsed, []) as string;\n\tif (host === \"\" || (apply(stringEndsWith, host, [\".\"]) as boolean)) return INVALID_URL;\n\tconst url = `https://${host}${apply(urlPathname, parsed, []) as string}${apply(urlSearch, parsed, []) as string}`;\n\t// WHATWG parsing serializes an IP-literal host canonically: IPv6 in\n\t// brackets (RFC 5952 form), IPv4 as a dotted-quad.\n\tconst v6 = host[0] === \"[\";\n\tif (v6 || isIpv4Literal(host)) {\n\t\tconst text = v6 ? (apply(stringSlice, host, [1, -1]) as string) : host;\n\t\tconst literal = classifyAddress(text);\n\t\tif (literal.kind === \"malformed\") return INVALID_URL;\n\t\tif (literal.kind === \"non_public\" && !allowNonPublic) return PRIVATE_URL;\n\t\tconst family: 4 | 6 = v6 ? 6 : 4;\n\t\treturn record({ ok: true as const, url, hostname: text, literal: record({ address: text, family }) });\n\t}\n\t// RFC 6761: these names resolve to loopback by definition.\n\tif (!allowNonPublic && (host === \"localhost\" || (apply(stringEndsWith, host, [\".localhost\"]) as boolean))) return PRIVATE_URL;\n\treturn record({ ok: true as const, url, hostname: host });\n}\n\n/**\n * Looks up a hostname's addresses. It is passed `{ deadline, signal }`; the\n * resolver aborts `signal` when it stops waiting, and ignores any answer that\n * arrives after that. Each answer is `{ address, family }` with a textual IPv4\n * or IPv6 address. `createNodeWebhookDnsLookup()` at\n * `@fabricorg/webhook-delivery/node` is one implementation.\n */\nexport type WebhookDnsLookup = (hostname: string, options: WebhookCallOptions) => Promise<readonly WebhookResolvedAddress[]>;\n\n/** Options for {@link createWebhookDestinationResolver}. */\nexport interface WebhookDestinationResolverOptions {\n\treadonly lookup: WebhookDnsLookup;\n\t/** The longest one lookup may take; default {@link DEFAULT_WEBHOOK_LOOKUP_TIMEOUT_MS}. The call's own deadline also applies. */\n\treadonly lookupTimeoutMs?: number;\n\t/** The clock the call's deadline is compared with; the system clock by default. */\n\treadonly clock?: WebhookClock;\n}\n\ninterface ResolverSettings {\n\treadonly lookup: (...args: never[]) => unknown;\n\treadonly lookupTimeoutMs: number;\n\treadonly clock: CapturedClock;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\nconst DNS_FAILURE: WebhookDestinationResolution = freeze({ ok: false, code: \"dns_failure\" });\nconst PRIVATE_ADDRESS: WebhookDestinationResolution = freeze({ ok: false, code: \"private_address\" });\n\n/**\n * A {@link WebhookDestinationResolver} that applies\n * {@link checkWebhookDestinationUrl}, then resolves the host through the\n * injected lookup and requires every answer to be public. The vetted\n * destination it returns carries the addresses the transport must connect\n * to; the transport never resolves the name again, so a later answer (a DNS\n * rebinding) cannot change where the request goes.\n *\n * A URL that passes the rules resolves to `dns_failure`, never a pass, when\n * the call's signal has aborted, its deadline has passed or the clock cannot\n * be read (no lookup is made; this applies to IP literals too), when the\n * lookup throws, rejects, or has not answered within `lookupTimeoutMs` or by\n * the deadline (its signal is then aborted and a late answer ignored), when\n * an answer arrives but, once read, the signal has aborted, the clock cannot\n * be read or that lookup deadline has passed, or when its answer is empty,\n * longer than {@link WEBHOOK_DESTINATION_MAX_ADDRESSES}, or not a list of\n * `{ address, family }` records whose family matches the address. It is\n * `private_address` when any answer is a well-formed address that is not\n * public, whatever the others are. A public IP-literal host is returned\n * without a lookup.\n *\n * @throws {TypeError} `input_unreadable` at construction when `lookup` is not\n * a function or `clock` has no `now` function, and from `resolve` (as a\n * rejected promise) when `{ deadline, signal }` is not a real `Date` and\n * `AbortSignal`.\n * @throws {WebhookDeliveryConfigError} when `lookupTimeoutMs` is not positive,\n * finite and at most `WEBHOOK_MAX_TIMER_MS`.\n */\nexport function createWebhookDestinationResolver(options: WebhookDestinationResolverOptions): WebhookDestinationResolver {\n\tconst settings = guard(() => readResolverOptions(options), unreadable);\n\tconst resolver = {\n\t\tresolve(url: string, callOptions: WebhookCallOptions): Promise<WebhookDestinationResolution> {\n\t\t\ttry {\n\t\t\t\treturn resolveWith(settings, url, callOptions);\n\t\t\t} catch {\n\t\t\t\treturn PromiseConstructor.reject(unreadable());\n\t\t\t}\n\t\t},\n\t};\n\treturn freeze(resolver);\n}\n\nfunction readResolverOptions(options: unknown): ResolverSettings {\n\tif (!isPlainRecord(options)) throw unreadable();\n\tconst lookup = readOwn(options, \"lookup\", \"lookup\", unreadableFail);\n\tif (typeof lookup !== \"function\") throw unreadable();\n\tconst rawTimeout = primitive(readOwn(options, \"lookupTimeoutMs\", \"lookupTimeoutMs\", unreadableFail));\n\tconst lookupTimeoutMs = rawTimeout === undefined ? DEFAULT_WEBHOOK_LOOKUP_TIMEOUT_MS : rawTimeout;\n\tassertPositiveFinite(lookupTimeoutMs, \"lookupTimeoutMs\");\n\tif (lookupTimeoutMs > WEBHOOK_MAX_TIMER_MS) throw configError(\"limit_out_of_range\", \"lookupTimeoutMs\");\n\tconst clock = captureOptionalClock(readOwn(options, \"clock\", \"clock\", unreadableFail));\n\treturn freeze({ lookup: lookup as (...args: never[]) => unknown, lookupTimeoutMs, clock });\n}\n\nfunction resolveWith(settings: ResolverSettings, url: unknown, callOptions: unknown): Promise<WebhookDestinationResolution> {\n\tconst bounds = readCallBounds(callOptions);\n\tconst check = checkWebhookDestinationUrl(url as string);\n\tif (!check.ok) return PromiseConstructor.resolve(record<WebhookDestinationResolution>({ ok: false, code: check.code }));\n\t// No success, a literal's included, for a call that is aborted, past its\n\t// deadline, or whose clock cannot be read.\n\tconst nowMs = clockNowMs(settings.clock);\n\tif (isAborted(bounds.signal) || !(bounds.deadlineMs > nowMs)) return PromiseConstructor.resolve(DNS_FAILURE);\n\tif (check.literal !== undefined) {\n\t\treturn PromiseConstructor.resolve(vetted(check.url, check.hostname, frozenList([check.literal])));\n\t}\n\tconst waitMs = bounds.deadlineMs - nowMs < settings.lookupTimeoutMs ? bounds.deadlineMs - nowMs : settings.lookupTimeoutMs;\n\t/** The earlier of the lookup timeout and the call's deadline. */\n\tconst lookupDeadlineMs = nowMs + waitMs;\n\tconst { url: vettedUrl, hostname } = check;\n\t// Checked again when an answer arrives: a lookup that blocks past the\n\t// deadline and then fulfils would otherwise win, because its fulfilment\n\t// runs as a microtask before the overdue timer.\n\tconst stillWanted = (): boolean => !isAborted(bounds.signal) && clockNowMs(settings.clock) < lookupDeadlineMs;\n\n\treturn new PromiseConstructor<WebhookDestinationResolution>((settle) => {\n\t\tconst controller = new AbortControllerConstructor();\n\t\tconst lookupSignal = apply(abortControllerSignal, controller, []) as AbortSignal;\n\t\tlet done = false;\n\t\tlet cancelTimer: () => void = () => {};\n\t\tlet removeAbort: () => void = () => {};\n\t\tconst finish = (result: WebhookDestinationResolution): void => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tcancelTimer();\n\t\t\tremoveAbort();\n\t\t\t// Tell the lookup to stop; whatever it answers later is ignored.\n\t\t\tapply(abortControllerAbort, controller, []);\n\t\t\tsettle(result);\n\t\t};\n\t\tcancelTimer = startTimer(waitMs, () => finish(DNS_FAILURE));\n\t\tremoveAbort = onAbort(bounds.signal, () => finish(DNS_FAILURE));\n\t\tif (done) return;\n\t\tlet pending: unknown;\n\t\ttry {\n\t\t\tpending = apply(settings.lookup, undefined, [hostname, freeze({ deadline: new DateConstructor(nowMs + waitMs), signal: lookupSignal })] as never[]);\n\t\t} catch {\n\t\t\tfinish(DNS_FAILURE);\n\t\t\treturn;\n\t\t}\n\t\tif (pending === null || (typeof pending !== \"object\" && typeof pending !== \"function\")) {\n\t\t\tfinish(DNS_FAILURE);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\t// Adopt the lookup's result through the intrinsic `then` of a fresh\n\t\t\t// promise, so a thenable's own code runs only as the lookup's code.\n\t\t\tapply(promiseThen, PromiseConstructor.resolve(pending), [\n\t\t\t\t(answer: unknown) => finish(acceptedVerdict(vettedUrl, hostname, answer, stillWanted)),\n\t\t\t\t() => finish(DNS_FAILURE),\n\t\t\t]);\n\t\t} catch {\n\t\t\tfinish(DNS_FAILURE);\n\t\t}\n\t});\n}\n\n/**\n * Judge an answer, then accept a pass only if the call is still wanted at\n * that moment (not aborted, clock valid, before the lookup deadline). The\n * check runs after the answer is read, so time spent reading it counts.\n */\nfunction acceptedVerdict(url: string, hostname: string, answer: unknown, stillWanted: () => boolean): WebhookDestinationResolution {\n\ttry {\n\t\tconst judged = verdict(url, hostname, answer);\n\t\tif (judged.ok && !stillWanted()) return DNS_FAILURE;\n\t\treturn judged;\n\t} catch {\n\t\treturn DNS_FAILURE;\n\t}\n}\n\n/** Judge a lookup answer: any non-public address refuses it; anything unreadable is `dns_failure`. */\nfunction verdict(url: string, hostname: string, answer: unknown): WebhookDestinationResolution {\n\tif (!isArray(answer)) return DNS_FAILURE;\n\tconst length = readOwn(answer, \"length\", \"length\", unreadableFail);\n\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > WEBHOOK_DESTINATION_MAX_ADDRESSES) return DNS_FAILURE;\n\tconst seen = emptyMap<true>();\n\tconst addresses: WebhookResolvedAddress[] = [];\n\tlet malformed = false;\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst entry = readOwn(answer, `${index}`, \"answer\", unreadableFail);\n\t\tif (!isPlainRecord(entry)) {\n\t\t\tmalformed = true;\n\t\t\tcontinue;\n\t\t}\n\t\tconst address = primitive(readOwn(entry, \"address\", \"address\", unreadableFail));\n\t\tconst family = primitive(readOwn(entry, \"family\", \"family\", unreadableFail));\n\t\tconst judged = classifyAddress(address);\n\t\tif (judged.kind === \"non_public\") return PRIVATE_ADDRESS;\n\t\tif (judged.kind === \"malformed\" || judged.family !== family) {\n\t\t\tmalformed = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen[judged.address] === true) continue;\n\t\tseen[judged.address] = true;\n\t\taddresses[addresses.length] = record({ address: judged.address, family: judged.family });\n\t}\n\tif (malformed) return DNS_FAILURE;\n\treturn vetted(url, hostname, frozenList(addresses));\n}\n\nfunction vetted(url: string, hostname: string, addresses: readonly WebhookResolvedAddress[]): WebhookDestinationResolution {\n\tconst destination = record<WebhookVettedDestination>({ url, hostname, port: 443, addresses });\n\treturn record<WebhookDestinationResolution>({ ok: true, destination });\n}\n","import {\n\tWEBHOOK_ADMISSION_DENIAL_CODES,\n\tWEBHOOK_REVOCATION_CODES,\n\ttype WebhookAdmissionDenialCode,\n\ttype WebhookRevocationCode,\n} from \"./codes\";\nimport { guard, guardOr, inputError } from \"./errors\";\nimport type { WebhookAdmissionDecision, WebhookDeliveryAuthorizationDecision } from \"./ports\";\nimport { freeze, isOneOf, isPlainRecord, primitive, readOwn, record, type Fail } from \"./snapshot\";\n\nconst ALLOW: WebhookAdmissionDecision = record({ decision: \"allow\" });\nconst ADMISSION_UNAVAILABLE: WebhookAdmissionDecision = record({ decision: \"unavailable\" });\nconst AUTHORIZED: WebhookDeliveryAuthorizationDecision = record({ decision: \"authorized\" });\nconst AUTHORIZATION_UNAVAILABLE: WebhookDeliveryAuthorizationDecision = record({ decision: \"unavailable\" });\n\n/** Thrown inside a normalizer only, and always caught there. */\nconst UNREADABLE = freeze(Object.create(null) as object);\nconst unreadableFail: Fail = () => {\n\tthrow UNREADABLE;\n};\n\n/** Admission allows the event. */\nexport function webhookAdmissionAllow(): WebhookAdmissionDecision {\n\treturn ALLOW;\n}\n\n/**\n * Admission denies the event with a fixed reason code; the denial is recorded.\n *\n * @throws {TypeError} `denial_code_unknown` for a code outside `WEBHOOK_ADMISSION_DENIAL_CODES`.\n */\nexport function webhookAdmissionDeny(code: WebhookAdmissionDenialCode): WebhookAdmissionDecision {\n\treturn guard(() => {\n\t\tconst value = primitive(code);\n\t\tif (!isOneOf(WEBHOOK_ADMISSION_DENIAL_CODES, value)) throw inputError(\"type\", \"denial_code_unknown\");\n\t\treturn record<WebhookAdmissionDecision>({ decision: \"deny\", code: value as WebhookAdmissionDenialCode });\n\t}, () => inputError(\"type\", \"denial_code_unknown\"));\n}\n\n/** Admission cannot decide now; the job retries without an intent. */\nexport function webhookAdmissionUnavailable(): WebhookAdmissionDecision {\n\treturn ADMISSION_UNAVAILABLE;\n}\n\n/** Snapshot `decision` and `code` from a plain answer; anything unreadable throws, to be caught. */\nfunction snapshotAnswer(value: unknown): { readonly decision: unknown; readonly code: unknown } {\n\tif (!isPlainRecord(value)) throw UNREADABLE;\n\tconst decision = primitive(readOwn(value, \"decision\", \"decision\", unreadableFail));\n\tconst code = primitive(readOwn(value, \"code\", \"code\", unreadableFail));\n\treturn record({ decision, code });\n}\n\n/**\n * Read an admission port's answer fail-closed. Anything other than a\n * well-formed `allow`, `deny` with a known code, or `unavailable`, including\n * a `deny` with an unknown code, an accessor, a non-plain object or an\n * answer whose inspection throws, becomes `unavailable`: it never becomes\n * `allow`, an unknown code is never stored, and this function never throws.\n */\nexport function normalizeWebhookAdmissionDecision(value: unknown): WebhookAdmissionDecision {\n\treturn guardOr(() => {\n\t\tconst { decision, code } = snapshotAnswer(value);\n\t\tif (decision === \"allow\") return ALLOW;\n\t\tif (decision === \"deny\" && isOneOf(WEBHOOK_ADMISSION_DENIAL_CODES, code)) {\n\t\t\treturn record<WebhookAdmissionDecision>({ decision: \"deny\", code: code as WebhookAdmissionDenialCode });\n\t\t}\n\t\treturn ADMISSION_UNAVAILABLE;\n\t}, () => ADMISSION_UNAVAILABLE);\n}\n\n/**\n * Read a delivery authorization port's answer fail-closed. Anything other\n * than a well-formed `authorized`, `revoked` with a known code, or\n * `unavailable`, including an unreadable answer, becomes `unavailable`,\n * which defers the intent unsent. This function never throws.\n */\nexport function normalizeWebhookDeliveryAuthorizationDecision(value: unknown): WebhookDeliveryAuthorizationDecision {\n\treturn guardOr(() => {\n\t\tconst { decision, code } = snapshotAnswer(value);\n\t\tif (decision === \"authorized\") return AUTHORIZED;\n\t\tif (decision === \"revoked\" && isOneOf(WEBHOOK_REVOCATION_CODES, code)) {\n\t\t\treturn record<WebhookDeliveryAuthorizationDecision>({ decision: \"revoked\", code: code as WebhookRevocationCode });\n\t\t}\n\t\treturn AUTHORIZATION_UNAVAILABLE;\n\t}, () => AUTHORIZATION_UNAVAILABLE);\n}\n","import { fanOutError } from \"./errors\";\nimport type { WebhookCallOptions, WebhookClock } from \"./ports\";\nimport { apply, isPlainRecord, numberIsFinite, readOwn, timeOf } from \"./snapshot\";\n\n/*\n * Bounded port calls for the fan-out publisher and cycle and the delivery\n * cycle (R4: each awaited port, stores included, is bounded).\n *\n * Each call gets an absolute `deadline` and its own `AbortSignal`. The\n * caller stops waiting at `timeoutMs` and aborts the signal, so a port that\n * honours it stops work; an answer that settles at or after the bound is a\n * timeout and is dropped (`boundedCall` says how the settle time is taken).\n * A store write that timed out may still have committed, so the cycles\n * treat it as unknown and never follow it with a second, conflicting\n * transition on the strength of the timeout. Every write the cycles make is\n * insert-if-absent or fenced, so a late write either lands once or is\n * refused. The transport\n * call (R3) is not only raced: the transport itself takes the deadline and\n * the signal, refuses an expired or cancelled handoff and stops a started\n * request at the deadline; the delivery cycle waits `settleGraceMs` past\n * the deadline for it to report what it observed (src/delivery-cycle.ts).\n *\n * A thrown value is never read: the outcome records only that it threw.\n * The port's promise has a rejection handler attached as soon as it is\n * returned (`work` in `boundedCall`), so a\n * port that rejects after the caller stopped waiting raises no unhandled\n * rejection.\n */\n\n/** How a bounded call ended. A thrown value is dropped unread. */\nexport type BoundedOutcome<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| { readonly ok: false; readonly reason: \"threw\" | \"timeout\" | \"aborted\" };\n\nconst abortedGetter = typeof AbortSignal === \"function\" ? Reflect.getOwnPropertyDescriptor(AbortSignal.prototype, \"aborted\")?.get : undefined;\n\n/**\n * The caller's `signal` from a publish context, or `undefined`. Read as an\n * own data property; it counts only when the intrinsic `aborted` getter\n * accepts it, which is true of real `AbortSignal`s only and runs none of the\n * value's code. Anything that throws while it is read is dropped unread.\n */\nexport function readContextSignal(context: unknown): AbortSignal | undefined {\n\ttry {\n\t\tif (!isPlainRecord(context) || abortedGetter === undefined) return undefined;\n\t\tconst signal = readOwn(context, \"signal\", \"signal\", () => undefined as never);\n\t\tif (signal === null || typeof signal !== \"object\") return undefined;\n\t\tapply(abortedGetter, signal, []);\n\t\treturn signal as AbortSignal;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Whether a signal {@link readContextSignal} returned has aborted, read with\n * the intrinsic `aborted` getter, so an own `aborted` property on the\n * signal object is never consulted.\n */\nexport function signalAborted(signal: AbortSignal): boolean {\n\tif (abortedGetter === undefined) return false;\n\ttry {\n\t\treturn apply(abortedGetter, signal, []) === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** The context's `actorDisclosure` when it is one of Host's three values, else `undefined`; never throws. */\nexport function readContextDisclosure(context: unknown): \"included\" | \"suppressed\" | \"legacy\" | undefined {\n\ttry {\n\t\tif (!isPlainRecord(context)) return undefined;\n\t\tconst disclosure = readOwn(context, \"actorDisclosure\", \"actorDisclosure\", () => undefined as never);\n\t\treturn disclosure === \"included\" || disclosure === \"suppressed\" || disclosure === \"legacy\" ? disclosure : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** An injected clock captured at construction: the object and its `now` function. */\nexport interface FanOutClock {\n\treadonly target: object;\n\treadonly now: (...args: never[]) => unknown;\n}\n\n/** Capture an injected clock at construction; anything without a `now` function is `options_invalid`. */\nexport function captureFanOutClock(clock: WebhookClock | undefined): FanOutClock {\n\tif (clock === null || typeof clock !== \"object\") throw fanOutError(\"options_invalid\", \"clock\");\n\tconst now = (clock as { now?: unknown }).now;\n\tif (typeof now !== \"function\") throw fanOutError(\"options_invalid\", \"clock.now\");\n\treturn { target: clock, now: now as (...args: never[]) => unknown };\n}\n\n/** Read the captured clock, refusing a throw or an invalid time as `clock_invalid`. */\nexport function readFanOutClock(clock: FanOutClock): number {\n\tlet value: unknown;\n\ttry {\n\t\tvalue = apply(clock.now, clock.target, []);\n\t} catch {\n\t\tthrow fanOutError(\"clock_invalid\", \"clock\");\n\t}\n\tconst ms = timeOf(value);\n\tif (!numberIsFinite(ms)) throw fanOutError(\"clock_invalid\", \"clock\");\n\treturn ms;\n}\n\nconst performanceNow = typeof performance === \"object\" && performance !== null && typeof performance.now === \"function\"\n\t? performance.now.bind(performance)\n\t: Date.now;\n\nconst TIMEOUT: { readonly ok: false; readonly reason: \"timeout\" } = Object.freeze({ ok: false, reason: \"timeout\" });\nconst ABORTED: { readonly ok: false; readonly reason: \"aborted\" } = Object.freeze({ ok: false, reason: \"aborted\" });\nconst THREW: { readonly ok: false; readonly reason: \"threw\" } = Object.freeze({ ok: false, reason: \"threw\" });\n\n/**\n * Run `run` with an absolute deadline `nowMs + timeoutMs` and a signal that\n * aborts at the timeout or when `parent` aborts. Resolves with the outcome;\n * never rejects.\n *\n * An answer (a value or a throw) is classed by when a handler attached\n * directly to the port's promise runs, not by when this function's\n * continuation resumes. That handler records the time: an answer is accepted\n * when, at that handler, `readNow()` (the clock `nowMs` came from) is still\n * before `nowMs + timeoutMs + settleGraceMs` and fewer than\n * `timeoutMs + settleGraceMs` milliseconds have passed on the monotonic\n * clock since the call started. Otherwise it is a `timeout`, and so is an\n * answer whose `readNow()` throws. The classed answer settles the race as\n * soon as that handler returns, so a timer that fires later, or other work\n * that delays this function's own continuation after the handler ran, cannot\n * turn an answer the handler classed as on time into a timeout.\n * `settleGraceMs` (default 0) is the one stated exception, for the\n * transport: its answer is still accepted for that long after its deadline,\n * because the transport itself stops the request at the deadline and\n * reports what it saw.\n *\n * A parent abort settles the race at once, ahead of any answer whose\n * handler has not yet returned, so such an answer is `aborted`.\n *\n * The handler is attached as soon as the port returns, so it runs once the\n * promise settles and the microtasks already queued ahead of it (including\n * any handlers the port itself attached) have run. That delay counts\n * against the answer: it can make an answer late, never early.\n *\n * Whenever this resolves `timeout`, for any reason, the call's signal has\n * already been aborted (`controller.abort()` below runs before it returns),\n * so a port that honours the signal stops, and a store that has not yet\n * reached its atomic step refuses the write. A store write that times out\n * may still have committed: callers treat a timed-out write as unknown.\n */\nexport async function boundedCall<T>(\n\tnowMs: number,\n\ttimeoutMs: number,\n\tparent: AbortSignal | undefined,\n\trun: (options: WebhookCallOptions) => Promise<T>,\n\treadNow: () => number,\n\tsettleGraceMs = 0,\n): Promise<BoundedOutcome<T>> {\n\tif (parent?.aborted) return ABORTED;\n\tconst startedMonotonicMs = performanceNow();\n\tconst acceptWithinMs = timeoutMs + settleGraceMs;\n\tconst acceptUntilMs = nowMs + acceptWithinMs;\n\tconst controller = new AbortController();\n\tconst options: WebhookCallOptions = { deadline: new Date(nowMs + timeoutMs), signal: controller.signal };\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet graceTimer: ReturnType<typeof setTimeout> | undefined;\n\tlet onParentAbort: (() => void) | undefined;\n\tconst stop = new Promise<BoundedOutcome<T>>((resolve) => {\n\t\ttimer = setTimeout(() => {\n\t\t\tcontroller.abort();\n\t\t\tif (settleGraceMs > 0) graceTimer = setTimeout(() => resolve(TIMEOUT), settleGraceMs);\n\t\t\telse resolve(TIMEOUT);\n\t\t}, timeoutMs);\n\t\tif (parent) {\n\t\t\tonParentAbort = () => {\n\t\t\t\tcontroller.abort();\n\t\t\t\tresolve(ABORTED);\n\t\t\t};\n\t\t\tparent.addEventListener(\"abort\", onParentAbort, { once: true });\n\t\t}\n\t});\n\t/** Class an answer when its handler runs (see above). */\n\tconst classify = (outcome: BoundedOutcome<T>): BoundedOutcome<T> => {\n\t\tif (!(performanceNow() - startedMonotonicMs < acceptWithinMs)) return TIMEOUT;\n\t\ttry {\n\t\t\treturn readNow() < acceptUntilMs ? outcome : TIMEOUT;\n\t\t} catch {\n\t\t\treturn TIMEOUT;\n\t\t}\n\t};\n\ttry {\n\t\tlet work: Promise<BoundedOutcome<T>>;\n\t\ttry {\n\t\t\t// The handler is attached directly to what the port returned (a\n\t\t\t// thenable is adopted first, one turn later), so a rejection is\n\t\t\t// always handled. Adoption is inside this guard because it can throw\n\t\t\t// too (a promise whose `constructor` getter throws); that throw is\n\t\t\t// dropped unread, like any other, and cleanup below still runs. Such\n\t\t\t// a promise is outside the port contract (src/ports.ts): no handler\n\t\t\t// can be attached to it, so a rejection it carries stays unhandled.\n\t\t\twork = Promise.resolve(run(options)).then(\n\t\t\t\t(value) => classify({ ok: true, value }),\n\t\t\t\t() => classify(THREW),\n\t\t\t);\n\t\t} catch {\n\t\t\twork = Promise.resolve().then(() => classify(THREW));\n\t\t}\n\t\tconst outcome = await Promise.race([work, stop]);\n\t\tif (!outcome.ok && outcome.reason === \"timeout\") controller.abort();\n\t\treturn outcome;\n\t} finally {\n\t\tif (timer !== undefined) clearTimeout(timer);\n\t\tif (graceTimer !== undefined) clearTimeout(graceTimer);\n\t\tif (parent && onParentAbort) parent.removeEventListener(\"abort\", onParentAbort);\n\t}\n}\n","import { snapshotEventMetadata } from \"./persistence-projection\";\nimport {\n\tdateParse,\n\tisArray,\n\tisOneOf,\n\tisPlainRecord,\n\tnumberIsFinite,\n\tnumberIsSafeInteger,\n\treadOwn,\n\tsnapshotJson,\n\tsnapshotJsonPart,\n\ttype Fail,\n\ttype JsonNodeBudget,\n} from \"./snapshot\";\nimport type {\n\tWebhookEligibilityRevision,\n\tWebhookEventMetadata,\n\tWebhookJobActor,\n\tWebhookJsonObject,\n\tWebhookJsonValue,\n\tWebhookSubscriptionStatus,\n} from \"./types\";\n\n/*\n * Reading what a port returned, for the fan-out publisher and cycle.\n *\n * `boundedCall` (fan-out-call.ts) already turns a port's rejection into a\n * bare reason. A resolved value is still the port's object: inspecting it\n * through ordinary property access could run a getter or a Proxy trap whose\n * error, with whatever text it carries, would escape. So every result is\n * read here, inside one try/catch per reader: own data properties only,\n * through descriptors (an accessor is refused uncalled), copied into\n * package-owned frozen snapshots (`snapshotJson`). Anything that cannot be\n * read this way is `undefined`, and the caller maps that to a fixed code.\n * Nothing thrown inside a reader is kept or read.\n */\n\nconst refuse: Fail = () => {\n\tthrow REFUSED;\n};\nconst REFUSED = Object.freeze(Object.create(null) as object);\n\n/** The `outcome` field of an insert result when it is one of `allowed`, else `undefined`. */\nexport function readOutcome<T extends string>(value: unknown, allowed: readonly T[]): T | undefined {\n\ttry {\n\t\tif (!isPlainRecord(value)) return undefined;\n\t\tconst outcome = readOwn(value, \"outcome\", \"outcome\", refuse);\n\t\treturn isOneOf(allowed, outcome) ? (outcome as T) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Own data property `key` of a snapshot (which is plain, frozen, null-prototype data). */\nfunction field(snapshot: WebhookJsonObject, key: string): WebhookJsonValue | undefined {\n\treturn readOwn(snapshot, key, key, refuse) as WebhookJsonValue | undefined;\n}\n\nfunction object(value: WebhookJsonValue | undefined): WebhookJsonObject {\n\tif (value === null || value === undefined || typeof value !== \"object\" || isArray(value)) throw REFUSED;\n\treturn value as WebhookJsonObject;\n}\n\nfunction nonEmpty(value: WebhookJsonValue | undefined): string {\n\tif (typeof value !== \"string\" || value === \"\") throw REFUSED;\n\treturn value;\n}\n\nfunction whole(value: WebhookJsonValue | undefined, min: number): number {\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < min) throw REFUSED;\n\treturn value;\n}\n\n/** A list result copied into a frozen snapshot, or `undefined`. */\nfunction snapshotList(value: unknown): readonly WebhookJsonValue[] | undefined {\n\tconst copy = snapshotJson(value, \"result\", refuse);\n\treturn isArray(copy) ? copy : undefined;\n}\n\n/**\n * What identifies a claimed record and the lease it was claimed under: the\n * fields a fenced transition needs. Read before, and independently of, the\n * rest of the record ({@link readClaimedJobs}).\n */\nexport interface ClaimedHeader {\n\treadonly eventId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly lease: { readonly owner: string; readonly fence: number };\n}\n\n/** A claimed fan-out job, as the cycle uses it: every field read from the record and validated. */\nexport interface ClaimedJob extends ClaimedHeader {\n\treadonly event: WebhookEventMetadata;\n\treadonly payload: WebhookJsonObject | null;\n\treadonly payloadProjected: boolean;\n\treadonly facts: WebhookJsonObject;\n\treadonly actor: WebhookJobActor;\n\treadonly attemptCount: number;\n\treadonly processingDeadline: string;\n\t/** `processingDeadline` and `event.recordedAt` as epoch milliseconds, both finite. */\n\treadonly processingDeadlineMs: number;\n\treadonly recordedAtMs: number;\n}\n\n/**\n * One entry of a claim result. `undefined`: the record's identity or lease\n * cannot be read, so no fenced write can name it. `job: undefined`: the\n * header was read but the rest of the record cannot be, so the cycle can\n * still end the job through its fenced dead-letter transition.\n */\nexport type ClaimedEntry = { readonly header: ClaimedHeader; readonly job: ClaimedJob | undefined } | undefined;\n\nconst ACTOR_REASONS = Object.freeze([\"suppressed\", \"legacy\"] as const);\n\nfunction readActor(value: WebhookJsonValue | undefined): WebhookJobActor {\n\tconst actor = object(value);\n\tconst state = field(actor, \"state\");\n\tif (state === \"present\") {\n\t\treturn Object.freeze({ state: \"present\", actorId: nonEmpty(field(actor, \"actorId\")), actorType: nonEmpty(field(actor, \"actorType\")) });\n\t}\n\tconst reason = field(actor, \"reason\");\n\tif (state !== \"absent\" || !isOneOf(ACTOR_REASONS, reason)) throw REFUSED;\n\treturn Object.freeze({ state: \"absent\", reason: reason as \"suppressed\" | \"legacy\" });\n}\n\n/** Own data property `key` of a port's record, read once through its descriptor. */\nfunction raw(record: object, key: string): unknown {\n\treturn readOwn(record, key, key, refuse);\n}\n\nfunction plain(value: unknown): object {\n\tif (!isPlainRecord(value)) throw REFUSED;\n\treturn value;\n}\n\n/**\n * The header: identity and lease, each an own data property read once. A\n * store adds the lease when it claims; it is read here as two scalars, with\n * no size budget, so nothing the store adds can make the header unreadable.\n */\nfunction readHeader(record: unknown): ClaimedHeader {\n\tconst job = plain(record);\n\tconst eventId = nonEmpty(raw(job, \"eventId\") as WebhookJsonValue | undefined);\n\tconst tenantId = nonEmpty(raw(job, \"tenantId\") as WebhookJsonValue | undefined);\n\tconst spaceId = nonEmpty(raw(job, \"spaceId\") as WebhookJsonValue | undefined);\n\tconst lease = plain(raw(job, \"lease\"));\n\tconst owner = nonEmpty(raw(lease, \"owner\") as WebhookJsonValue | undefined);\n\tconst fence = whole(raw(lease, \"fence\") as WebhookJsonValue | undefined, 0);\n\treturn Object.freeze({ eventId, tenantId, spaceId, lease: Object.freeze({ owner, fence }) });\n}\n\n/**\n * Containers the insert-side snapshot counted besides `payload` and `facts`:\n * the job record itself, `event` and `actor`. `event` and `actor` hold only\n * scalars once projected, so each is one container.\n */\nconst DRAFT_FIXED_CONTAINERS = 3;\n/** The depth at which the insert-side snapshot reached `payload` and `facts`: one below the job record. */\nconst DRAFT_FIELD_DEPTH = 1;\n\n/**\n * The rest of the record: the projected draft and the scalars the store\n * added (`attemptCount`, `processingDeadline`).\n *\n * Why this cannot refuse a record the store accepted (A1). The insert\n * (`readJobDraft` in the memory store, via `snapshotRecord`) holds the whole\n * submitted job to `snapshotJson`'s limits: at most `MAX_JSON_NODES`\n * containers and `MAX_JSON_DEPTH` levels, counted from the job record. A\n * claimed record is that draft plus whatever the store adds (a lease, a\n * fence, timestamps, an attempt count, a diagnostic), so budgeting the whole\n * claimed record would refuse a draft accepted at the limit. Instead only\n * the draft's open-ended parts, `payload` and `facts`, are snapshotted, with\n * one shared budget seeded with the draft's other containers and starting\n * at the depth the insert reached them. For a store that returns the draft\n * it accepted, the count and depth here are therefore at most the insert's\n * for that draft, whatever the store added; store-added fields are read as\n * scalars and never budgeted. Test:\n * \"a draft accepted at the node limit round-trips through a claim\".\n */\nfunction readBody(record: unknown, header: ClaimedHeader): ClaimedJob {\n\tconst job = plain(record);\n\t// The same validation the projection applies to an envelope.\n\tconst event = snapshotEventMetadata(raw(job, \"event\"));\n\tif (event.eventId !== header.eventId || event.tenantId !== header.tenantId || event.spaceId !== header.spaceId) throw REFUSED;\n\tconst budget: JsonNodeBudget = { nodes: DRAFT_FIXED_CONTAINERS };\n\tconst storedPayload = raw(job, \"payload\");\n\tconst payload = storedPayload === null ? null : object(snapshotJsonPart(storedPayload, \"payload\", refuse, DRAFT_FIELD_DEPTH, budget));\n\tconst facts = object(snapshotJsonPart(raw(job, \"facts\"), \"facts\", refuse, DRAFT_FIELD_DEPTH, budget));\n\tconst actor = readActor(snapshotJsonPart(raw(job, \"actor\"), \"actor\", refuse, DRAFT_FIELD_DEPTH, { nodes: 0 }));\n\tconst processingDeadline = nonEmpty(raw(job, \"processingDeadline\") as WebhookJsonValue | undefined);\n\tconst processingDeadlineMs = dateParse(processingDeadline);\n\tconst recordedAtMs = dateParse(event.recordedAt);\n\tif (!numberIsFinite(processingDeadlineMs) || !numberIsFinite(recordedAtMs)) throw REFUSED;\n\treturn Object.freeze({\n\t\t...header,\n\t\tevent,\n\t\tpayload,\n\t\tpayloadProjected: raw(job, \"payloadProjected\") === true,\n\t\tfacts,\n\t\tactor,\n\t\tattemptCount: whole(raw(job, \"attemptCount\") as WebhookJsonValue | undefined, 0),\n\t\tprocessingDeadline,\n\t\tprocessingDeadlineMs,\n\t\trecordedAtMs,\n\t});\n}\n\n/**\n * The claim result: `undefined` when the list itself cannot be read, and\n * otherwise one {@link ClaimedEntry} per claimed record. Each record's\n * header is read first, in its own try/catch, and its body after, in\n * another, so a body that cannot be read still leaves a header the cycle\n * can dead-letter by (A2). Whatever either read throws is dropped unread.\n */\nexport function readClaimedJobs(value: unknown): readonly ClaimedEntry[] | undefined {\n\tconst items: unknown[] = [];\n\ttry {\n\t\t// The list shallowly, so one unreadable job does not hide the others.\n\t\tif (!isArray(value)) return undefined;\n\t\tconst length = readOwn(value, \"length\", \"length\", refuse);\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 0 || length > MAX_CLAIMED) return undefined;\n\t\tfor (let index = 0; index < length; index += 1) items.push(readOwn(value, `${index}`, \"job\", refuse));\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn Object.freeze(items.map((item): ClaimedEntry => {\n\t\tlet header: ClaimedHeader;\n\t\ttry {\n\t\t\theader = readHeader(item);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\treturn Object.freeze({ header, job: readBody(item, header) });\n\t\t} catch {\n\t\t\treturn Object.freeze({ header, job: undefined });\n\t\t}\n\t}));\n}\n\n/** More jobs than any claim limit a cycle sends; a longer answer is not a claim result. */\nconst MAX_CLAIMED = 100_000;\n\nconst STATUSES = Object.freeze([\"active\", \"paused\", \"deleted\"] as const);\n\n/** The revision listing, or `undefined` when any part of it cannot be read: eligibility is then unknown. */\nexport function readRevisions(value: unknown): readonly WebhookEligibilityRevision[] | undefined {\n\ttry {\n\t\tconst list = snapshotList(value);\n\t\tif (list === undefined) return undefined;\n\t\treturn Object.freeze(list.map((item) => {\n\t\t\tconst revision = object(item);\n\t\t\tconst patterns = field(revision, \"eventTypePatterns\");\n\t\t\tif (!isArray(patterns)) throw REFUSED;\n\t\t\tconst status = field(revision, \"status\");\n\t\t\tif (!isOneOf(STATUSES, status)) throw REFUSED;\n\t\t\tconst effectiveUntil = field(revision, \"effectiveUntil\");\n\t\t\treturn Object.freeze({\n\t\t\t\tsubscriptionId: nonEmpty(field(revision, \"subscriptionId\")),\n\t\t\t\trevision: whole(field(revision, \"revision\"), 1),\n\t\t\t\ttenantId: nonEmpty(field(revision, \"tenantId\")),\n\t\t\t\tspaceId: nonEmpty(field(revision, \"spaceId\")),\n\t\t\t\tstatus: status as WebhookSubscriptionStatus,\n\t\t\t\teventTypePatterns: Object.freeze(patterns.map(nonEmpty)),\n\t\t\t\teffectiveFrom: nonEmpty(field(revision, \"effectiveFrom\")),\n\t\t\t\teffectiveUntil: effectiveUntil === null || effectiveUntil === undefined ? null : nonEmpty(effectiveUntil),\n\t\t\t});\n\t\t}));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * A tombstone read: `\"decided\"` when an intent or denial marker exists for\n * the pair, `\"undecided\"` for `null`, `undefined` when the answer cannot be read.\n */\nexport function readDecided(value: unknown): \"decided\" | \"undecided\" | undefined {\n\ttry {\n\t\tif (value === null) return \"undecided\";\n\t\tif (!isPlainRecord(value)) return undefined;\n\t\tconst kind = readOwn(value, \"kind\", \"kind\", refuse);\n\t\treturn kind === \"intent\" || kind === \"denial\" ? \"decided\" : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n","import type {\n\tEnterpriseEventEnvelope,\n\tEnterpriseEventPublishContext,\n\tEnterpriseEventPublisher,\n} from \"@fabricorg/platform-host\";\n\nimport { configError, fanOutError, guard } from \"./errors\";\nimport { boundedCall, captureFanOutClock, readContextDisclosure, readContextSignal, readFanOutClock, signalAborted, type FanOutClock } from \"./fan-out-call\";\nimport { readOutcome } from \"./fan-out-read\";\nimport { assertPositiveInteger, resolveWebhookDeliveryLimits, WEBHOOK_MAX_TIMER_MS, type WebhookDeliveryLimits } from \"./limits\";\nimport { callFail, dataFail, projectWebhookFanOutJob, uninspectable } from \"./persistence-projection\";\nimport type { WebhookDeliveryStore } from \"./ports\";\nimport { apply, define, emptyMap, freeze, hasOwn, isArray, isPlainRecord, primitive, readOwn, record, snapshotJsonPart, timeOf, type JsonNodeBudget } from \"./snapshot\";\nimport { isoOf } from \"./store-input\";\nimport type { WebhookJobActor, WebhookPayloadPolicy } from \"./types\";\n\n/*\n * Stage one of the two-stage fan-out (ADR 0018 decision 2), and the\n * composite publisher that lets the Host relay feed webhooks and a bus from\n * one outbox (decisions 2 and 5).\n *\n * The fan-out publisher resolves subscriptions not at all. It projects the\n * envelope (persistence projection) and inserts one fan-out job keyed by\n * `eventId`, insert-if-absent, and resolves only after the store answers\n * `inserted` or `already_present`. The Host relay marks the outbox record\n * published only after `publish()` resolves (`runOutboxRelayCycle`,\n * packages/platform-host/src/outbox.ts), so an acknowledged record has a\n * stored job. A crash between the insert and the acknowledgement leaves\n * the record for lease expiry; the relay republishes it under the same\n * `eventId`, the insert answers `already_present`, and nothing is added\n * (test \"crash before acknowledgement ...\", tests/fan-out-host.test.ts).\n *\n * Nothing a port, the caller's context or a sink throws reaches an error\n * this module throws: a rejection is dropped by `boundedCall`, a resolved\n * value is read by `src/fan-out-read.ts`, the context by the readers in\n * `src/fan-out-call.ts`, and the envelope inside the projection's guard.\n * Every failure is a package error with a fixed code.\n */\n\n/** Options for {@link createWebhookFanOutPublisher}. */\nexport interface WebhookFanOutPublisherOptions {\n\t/** Where jobs are inserted. Only `insertFanOutJob` is called. */\n\treadonly store: Pick<WebhookDeliveryStore, \"insertFanOutJob\">;\n\t/** Stamps the job's `createdAt` and processing deadline, and bounds the store call. */\n\treadonly clock: { now(): Date };\n\t/** The persistence projection's allowlist and declared facts (decision 9). */\n\treadonly policy: WebhookPayloadPolicy;\n\t/**\n\t * Overrides of {@link WebhookDeliveryLimits}; every limit is validated as\n\t * positive and finite at construction (R4). The publisher uses\n\t * `fanOutDeadlineMs` (the job's processing deadline) and `portTimeoutMs`\n\t * (the bound on the insert).\n\t */\n\treadonly limits?: Partial<WebhookDeliveryLimits>;\n}\n\n/**\n * The actor a job records, from the relay's disclosure (decision 5). Only an\n * explicit `included` disclosure with both fields present yields an actor.\n * `suppressed` stays `suppressed`. Anything else, including a missing\n * context (a bridge that passed none) and an `included` record whose\n * envelope lacks the fields, is `legacy`: the reason actor enrichment\n * (PR 9) repairs. An `actorId` on an envelope whose disclosure is not\n * `included` is ignored. Runs inside the projection's guard.\n */\nfunction jobActor(event: unknown, disclosure: ReturnType<typeof readContextDisclosure>): WebhookJobActor {\n\tif (disclosure === \"suppressed\") return record<WebhookJobActor>({ state: \"absent\", reason: \"suppressed\" });\n\tif (disclosure === \"included\" && isPlainRecord(event)) {\n\t\tconst actorId = readOwn(event, \"actorId\", \"actorId\", dataFail);\n\t\tconst actorType = readOwn(event, \"actorType\", \"actorType\", dataFail);\n\t\tif (typeof actorId === \"string\" && actorId !== \"\" && typeof actorType === \"string\" && actorType !== \"\") {\n\t\t\treturn record<WebhookJobActor>({ state: \"present\", actorId, actorType });\n\t\t}\n\t}\n\treturn record<WebhookJobActor>({ state: \"absent\", reason: \"legacy\" });\n}\n\ninterface PublisherConfig {\n\treadonly limits: WebhookDeliveryLimits;\n\treadonly store: object;\n\treadonly insertFanOutJob: (...args: never[]) => unknown;\n\treadonly clock: FanOutClock;\n\treadonly policy: WebhookPayloadPolicy;\n}\n\nfunction readPublisherOptions(options: WebhookFanOutPublisherOptions): PublisherConfig {\n\tif (options === null || typeof options !== \"object\") throw fanOutError(\"options_invalid\", \"options\");\n\tconst limits = resolveWebhookDeliveryLimits(options.limits ?? {});\n\tconst store = options.store;\n\tif (store === null || typeof store !== \"object\") throw fanOutError(\"options_invalid\", \"store\");\n\tconst insertFanOutJob = store.insertFanOutJob;\n\tif (typeof insertFanOutJob !== \"function\") throw fanOutError(\"options_invalid\", \"store\");\n\treturn freeze({ limits, store, insertFanOutJob: insertFanOutJob as (...args: never[]) => unknown, clock: captureFanOutClock(options.clock), policy: options.policy });\n}\n\nconst INSERT_OUTCOMES = freeze([\"inserted\", \"already_present\", \"past_horizon\"] as const);\n\n/**\n * Build the stage-one publisher: an `EnterpriseEventPublisher` to hand to\n * `runOutboxRelayCycle()` (alone or inside {@link createWebhookCompositePublisher}),\n * or to call from a bridge for events that do not reach the Host outbox.\n *\n * `publish(event, context)`:\n *\n * 1. projects the envelope with `projectWebhookFanOutJob()`, recording the\n * actor as the relay's `context.actorDisclosure` describes it;\n * 2. inserts the job with `createdAt` now and a processing deadline\n * `fanOutDeadlineMs` later, bounded by `portTimeoutMs` and the caller's\n * signal;\n * 3. resolves on `inserted` or `already_present` (a replay or a bridge\n * overlap: the first insert wins, and the stored job is not changed).\n *\n * It rejects, so the Host relay retries the record and eventually\n * dead-letters it, with a `WebhookProjectionError` when the envelope cannot\n * be projected, or a `WebhookFanOutError`:\n * `event_past_replay_horizon` when the store answered `past_horizon`,\n * `fan_out_store_failed` when the insert threw or its answer cannot be read,\n * `fan_out_store_timeout` when it timed out, `publish_aborted` when the\n * caller's signal aborted first, and `clock_invalid` for a failing clock.\n * An insert that threw, timed out or was aborted may still have committed;\n * the relay's retry of the same `eventId` then answers `already_present`.\n *\n * @throws {WebhookDeliveryConfigError} at construction, for any limit that\n * is not positive and finite.\n * @throws {WebhookFanOutError} `options_invalid` at construction, for a\n * missing or unreadable store, clock or options object.\n */\nexport function createWebhookFanOutPublisher(options: WebhookFanOutPublisherOptions): EnterpriseEventPublisher {\n\tconst config = guard(() => readPublisherOptions(options), () => fanOutError(\"options_invalid\", \"options\"));\n\tconst { limits, store, insertFanOutJob, clock, policy } = config;\n\n\tconst publish = async (event: EnterpriseEventEnvelope, context?: EnterpriseEventPublishContext): Promise<void> => {\n\t\tconst disclosure = readContextDisclosure(context);\n\t\tconst draft = guard(\n\t\t\t() => projectWebhookFanOutJob(event, { policy, actor: jobActor(event, disclosure) }),\n\t\t\tuninspectable(\"envelope\"),\n\t\t);\n\t\tconst nowMs = readFanOutClock(clock);\n\t\tconst job = { ...draft, createdAt: isoOf(nowMs), processingDeadline: isoOf(nowMs + limits.fanOutDeadlineMs) };\n\t\tconst outcome = await boundedCall(nowMs, limits.portTimeoutMs, readContextSignal(context), (callOptions) =>\n\t\t\tapply(insertFanOutJob, store, [job, callOptions] as never[]) as Promise<unknown>, () => readFanOutClock(clock));\n\t\tif (!outcome.ok) {\n\t\t\tthrow fanOutError(\n\t\t\t\toutcome.reason === \"timeout\" ? \"fan_out_store_timeout\" : outcome.reason === \"aborted\" ? \"publish_aborted\" : \"fan_out_store_failed\",\n\t\t\t\t\"insertFanOutJob\",\n\t\t\t);\n\t\t}\n\t\tconst answer = readOutcome(outcome.value, INSERT_OUTCOMES);\n\t\t// Acknowledge only a durable job: a new one, or the one a replay or a\n\t\t// bridge stored first.\n\t\tif (answer === \"inserted\" || answer === \"already_present\") return;\n\t\t// R5, carried from PR 4: an event older than the replay horizon cannot\n\t\t// get a job, so the publish fails and the Host record dead-letters\n\t\t// instead of counting as delivered.\n\t\tif (answer === \"past_horizon\") throw fanOutError(\"event_past_replay_horizon\", \"insertFanOutJob\");\n\t\tthrow fanOutError(\"fan_out_store_failed\", \"insertFanOutJob\");\n\t};\n\treturn freeze({ publish });\n}\n\n// ---------------------------------------------------------------------------\n// Composite\n// ---------------------------------------------------------------------------\n\n/** One sink of a composite publisher. */\nexport interface WebhookCompositeSink {\n\t/** Names the sink in a `sink_failed` or `sink_timeout` error: 1 to 64 printable ASCII characters, unique in the composite. */\n\treadonly name: string;\n\treadonly publisher: EnterpriseEventPublisher;\n\t/**\n\t * Only `true` passes `actorId` and `actorType` to this sink, with the\n\t * relay's `actorDisclosure` unchanged. Any other value gives the sink a\n\t * copy of the envelope without those keys, and reports an `included`\n\t * disclosure to it as `suppressed` (decision 5).\n\t */\n\treadonly includeActor?: boolean;\n\t/**\n\t * Defaults to `true`. The composite resolves only after every required\n\t * sink resolves. A sink with `required: false` is started with the others\n\t * but never waited for: its outcome, timeout included, is ignored, so an\n\t * event it fails is not retried for it.\n\t */\n\treadonly required?: boolean;\n}\n\n/** Options for {@link createWebhookCompositePublisher}. */\nexport interface WebhookCompositePublisherOptions {\n\t/** At least one sink, at most 16, called concurrently. */\n\treadonly sinks: readonly WebhookCompositeSink[];\n\t/**\n\t * How long each sink is given, in ms, before its signal is aborted and\n\t * it counts as timed out. A positive whole number up to\n\t * `WEBHOOK_MAX_TIMER_MS`; default 10 000, Host's default publish timeout.\n\t */\n\treadonly sinkTimeoutMs?: number;\n}\n\ninterface Sink {\n\treadonly name: string;\n\treadonly target: object;\n\treadonly publish: (...args: never[]) => unknown;\n\treadonly includeActor: boolean;\n\treadonly required: boolean;\n}\n\nconst MAX_SINKS = 16;\nconst SINK_NAME = /^[\\x21-\\x7e]{1,64}$/;\nconst DEFAULT_SINK_TIMEOUT_MS = 10_000;\n\nfunction readComposite(options: unknown): { readonly sinks: readonly Sink[]; readonly timeoutMs: number } {\n\tif (options === null || typeof options !== \"object\") throw fanOutError(\"options_invalid\", \"options\");\n\tconst rawTimeout = primitive((options as { sinkTimeoutMs?: unknown }).sinkTimeoutMs);\n\tconst timeoutMs = rawTimeout === undefined ? DEFAULT_SINK_TIMEOUT_MS : rawTimeout;\n\tassertPositiveInteger(timeoutMs, \"sinkTimeoutMs\");\n\tif (timeoutMs > WEBHOOK_MAX_TIMER_MS) throw configError(\"limit_out_of_range\", \"sinkTimeoutMs\");\n\tconst sinks = (options as { sinks?: unknown }).sinks;\n\tif (!isArray(sinks) || sinks.length === 0 || sinks.length > MAX_SINKS) throw fanOutError(\"options_invalid\", \"sinks\");\n\tconst read: Sink[] = [];\n\tconst names: string[] = [];\n\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\tconst sink = sinks[index] as Partial<WebhookCompositeSink> | undefined;\n\t\tif (sink === null || typeof sink !== \"object\") throw fanOutError(\"options_invalid\", `sinks[${index}]`);\n\t\tconst { name, publisher, includeActor, required } = sink;\n\t\tif (typeof name !== \"string\" || !SINK_NAME.test(name) || names.includes(name)) throw fanOutError(\"options_invalid\", `sinks[${index}].name`);\n\t\tif (publisher === null || typeof publisher !== \"object\" || typeof publisher.publish !== \"function\") {\n\t\t\tthrow fanOutError(\"options_invalid\", `sinks[${index}].publisher`);\n\t\t}\n\t\tif (includeActor !== undefined && typeof includeActor !== \"boolean\") throw fanOutError(\"options_invalid\", `sinks[${index}].includeActor`);\n\t\tif (required !== undefined && typeof required !== \"boolean\") throw fanOutError(\"options_invalid\", `sinks[${index}].required`);\n\t\tnames.push(name);\n\t\tread.push(freeze({ name, target: publisher, publish: publisher.publish as (...args: never[]) => unknown, includeActor: includeActor === true, required: required !== false }));\n\t}\n\treturn freeze({ sinks: freeze(read), timeoutMs });\n}\n\n/*\n * Trust model. Sinks are trusted application code wired at the composition\n * root, like Host's adapters. The composite isolates sinks from ordinary\n * sink behaviour: mutating the envelope or context it was handed, throwing\n * synchronously, returning a rejected promise or a thenable that calls its\n * reject callback, rejecting late, ignoring its signal, and hanging. It does\n * not confine code that subverts intrinsics: a returned promise with a\n * poisoned `constructor` getter, a thenable whose `then` throws\n * asynchronously, or a replaced `dispatchEvent` or other\n * `EventTarget` method on the signal it was handed (the intrinsic `abort`\n * below dispatches the abort event on that signal, so such a replacement\n * runs). Those are outside the composite's guarantees.\n *\n * The runtime functions the composite calls are captured when this module\n * loads, in keeping with the rest of the package (src/snapshot.ts). This is\n * consistency, not confinement. The composite installs no listener on a\n * sink's signal and its cleanup calls nothing on the envelope, context or\n * signal it handed a sink. Each capture is `undefined` on a runtime without\n * it, and construction then refuses the composite as `options_invalid`.\n */\nconst AbortControllerIntrinsic = typeof AbortController === \"function\" ? AbortController : undefined;\nconst abortIntrinsic = AbortControllerIntrinsic?.prototype.abort;\nconst controllerSignalGetter = AbortControllerIntrinsic === undefined ? undefined : Reflect.getOwnPropertyDescriptor(AbortControllerIntrinsic.prototype, \"signal\")?.get;\nconst addListenerIntrinsic = typeof EventTarget === \"function\" ? EventTarget.prototype.addEventListener : undefined;\nconst removeListenerIntrinsic = typeof EventTarget === \"function\" ? EventTarget.prototype.removeEventListener : undefined;\nconst setTimer = setTimeout;\nconst clearTimer = clearTimeout;\nconst PromiseIntrinsic = Promise;\nconst deleteProperty = Reflect.deleteProperty;\nconst DateIntrinsic = Date;\nconst reflectOwnKeys = Reflect.ownKeys;\nconst reflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;\nconst reflectDefineProperty = Reflect.defineProperty;\nconst numberIsFinite = Number.isFinite;\n\nfunction compositeRuntimeAvailable(): boolean {\n\treturn abortIntrinsic !== undefined && controllerSignalGetter !== undefined && addListenerIntrinsic !== undefined &&\n\t\tremoveListenerIntrinsic !== undefined;\n}\n\n/**\n * One envelope per sink (B1): no two sinks, and no sink and the caller, share\n * a mutable object through the envelope. What enforces it is an allowlist,\n * not a list of refused types. The caller's envelope is read once by the\n * package's plain-data snapshot (src/snapshot.ts: own data properties only,\n * no getter is called, depth and node budgets), which accepts `null`,\n * booleans, finite numbers, strings, arrays, plain objects and the envelope's\n * two top-level dates, and refuses everything else (typed arrays,\n * `ArrayBuffer`, `SharedArrayBuffer`, `Map`, `Set`, `Error`, class instances,\n * `WebAssembly.Memory`, functions, symbols, accessors, and proxies over any\n * of those; a proxy over plain data cannot be told apart and its traps run\n * while the envelope is read). A refusal\n * fails the publish as `inspection_failed` before any sink starts. A value\n * the snapshot accepts holds no reference to memory outside itself, so each\n * sink's copy, built from the snapshot by `thaw`, shares nothing with another\n * sink's copy or the caller.\n *\n * `occurredAt` and `recordedAt` are copied as new `Date`s. A `Date` anywhere\n * else (in `payload`, say) becomes its ISO-8601 string, as the persistence\n * projection treats it. Host types `payload` as `unknown` and does not\n * guarantee JSON, so an envelope whose payload is not plain data is refused,\n * not passed through. A sink without `includeActor` gets its copy with\n * `actorId` and `actorType` deleted, so the keys are absent, not `undefined`.\n * All copies exist before any sink runs, so a sink mutating its envelope\n * cannot change what another receives (tests \"a sink mutating its envelope\n * ...\", \"an envelope holding ... is refused\").\n */\nfunction sinkEnvelopes(event: unknown, sinks: readonly Sink[]): readonly EnterpriseEventEnvelope[] {\n\tif (!isPlainRecord(event)) throw uninspectable(\"envelope\")();\n\tconst budget: JsonNodeBudget = { nodes: 0 };\n\tconst keys = reflectOwnKeys(event);\n\tconst snapshot: Record<string, unknown> = emptyMap<unknown>();\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index];\n\t\tif (typeof key !== \"string\") continue;\n\t\tconst descriptor = reflectGetOwnPropertyDescriptor(event, key);\n\t\tif (descriptor === undefined || descriptor.enumerable !== true) continue;\n\t\tif (!hasOwn(descriptor, \"value\")) return callFail(\"accessor\", \"envelope\");\n\t\tif (descriptor.value === undefined) continue;\n\t\tif (key === \"occurredAt\" || key === \"recordedAt\") {\n\t\t\tconst time = timeOf(descriptor.value);\n\t\t\tif (!numberIsFinite(time)) return callFail(\"not_json\", \"envelope\");\n\t\t\tdefine(snapshot, key, time);\n\t\t} else {\n\t\t\tdefine(snapshot, key, snapshotJsonPart(descriptor.value, \"envelope\", callFail, 1, budget));\n\t\t}\n\t}\n\tconst copies: EnterpriseEventEnvelope[] = [];\n\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\tconst copy = thaw(snapshot) as Record<string, unknown>;\n\t\tif (typeof snapshot.occurredAt === \"number\") copy.occurredAt = new DateIntrinsic(snapshot.occurredAt);\n\t\tif (typeof snapshot.recordedAt === \"number\") copy.recordedAt = new DateIntrinsic(snapshot.recordedAt);\n\t\tif (!sinks[index]!.includeActor) {\n\t\t\tdeleteProperty(copy, \"actorId\");\n\t\t\tdeleteProperty(copy, \"actorType\");\n\t\t}\n\t\tcopies.push(copy as unknown as EnterpriseEventEnvelope);\n\t}\n\treturn copies;\n}\n\n/**\n * A fresh, mutable, ordinary copy of a package-built snapshot (arrays,\n * null-prototype objects, primitives). It walks only snapshot values, whose\n * depth the snapshot already bounded. A key such as `__proto__` is defined\n * as an own property, never assigned.\n */\nfunction thaw(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (isArray(value)) {\n\t\tconst list: unknown[] = [];\n\t\tfor (let index = 0; index < value.length; index += 1) list.push(thaw(value[index]));\n\t\treturn list;\n\t}\n\tconst keys = reflectOwnKeys(value);\n\tconst out: Record<string, unknown> = {};\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index] as string;\n\t\tdefineMutable(out, key, thaw((value as Record<string, unknown>)[key]));\n\t}\n\treturn out;\n}\n\nfunction defineMutable(target: object, key: string, value: unknown): void {\n\treflectDefineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n/** How one sink's run ended. A rejection reason is kept only to be passed to `guard`, which runs none of its code. */\ntype SinkOutcome =\n\t| { readonly status: \"ok\" }\n\t| { readonly status: \"failed\"; readonly reason: unknown }\n\t| { readonly status: \"timeout\" }\n\t| { readonly status: \"aborted\" };\n\nconst OK: SinkOutcome = freeze({ status: \"ok\" });\nconst TIMED_OUT: SinkOutcome = freeze({ status: \"timeout\" });\nconst ABORTED: SinkOutcome = freeze({ status: \"aborted\" });\n\n/** One sink's run: its outcome, and the two ways the composite drives it. */\ninterface SinkRun {\n\t/** Resolves once, with how the run ended. Never rejects. */\n\treadonly outcome: Promise<SinkOutcome>;\n\t/** Start the sink's timer and call it, unless the run already ended. */\n\treadonly start: () => void;\n\t/** End the run as aborted and abort the sink's signal; nothing once it ended. */\n\treadonly abort: () => void;\n}\n\n/**\n * Prepare one sink's run: its own controller and signal, its own context\n * object, and an outcome promise settled by `end` exactly once, by whichever\n * comes first of the sink settling, the timeout and `abort`.\n *\n * Rejections from ordinary sink behaviour are handled (B3, within the trust\n * model above). `outcome` is resolve-only. The sink is called inside an\n * `async` body whose `try` covers the call, a synchronous throw, and the\n * `await` of what it returned: a rejected promise, early or late, or a\n * thenable that calls its reject callback lands in that `catch`, and the\n * body itself never rejects. `end` catches every error its own cleanup\n * could throw. A returned value that subverts the promise machinery (a\n * poisoned `constructor` getter, a `then` that throws asynchronously) is\n * outside that guarantee.\n *\n * `end` clears the timer and calls `onEnd`, which releases the composite's\n * watch on the caller's signal once every run has ended (B4). A run the\n * composite does not wait for has its timer `unref()`'d where the runtime\n * supports it, so an optional sink still running after `publish()` settled\n * keeps both its timeout and its abort forwarding without keeping the\n * process alive. Tests: the \"fixed outcomes and handled rejections\" and\n * \"optional sinks after publish() settled\" blocks of\n * tests/fan-out-composite.test.ts.\n */\nfunction prepareRun(sink: Sink, envelope: EnterpriseEventEnvelope, disclosure: string | undefined, timeoutMs: number, onEnd: () => void): SinkRun {\n\tconst controller = new AbortControllerIntrinsic!();\n\tconst signal = apply(controllerSignalGetter!, controller, []) as AbortSignal;\n\tconst context = (disclosure === undefined ? { signal } : { signal, actorDisclosure: disclosure }) as EnterpriseEventPublishContext;\n\tlet settle: (outcome: SinkOutcome) => void = () => undefined;\n\tconst outcome = new PromiseIntrinsic<SinkOutcome>((resolve) => {\n\t\tsettle = resolve;\n\t});\n\tlet ended = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst end = (result: SinkOutcome, abortSignal: boolean): void => {\n\t\tif (ended) return;\n\t\tended = true;\n\t\tif (timer !== undefined) {\n\t\t\ttry {\n\t\t\t\tclearTimer(timer);\n\t\t\t} catch {\n\t\t\t\t// Nothing to do: the run has ended either way.\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tonEnd();\n\t\t} catch {\n\t\t\t// As above.\n\t\t}\n\t\tif (abortSignal) {\n\t\t\ttry {\n\t\t\t\tapply(abortIntrinsic!, controller, []);\n\t\t\t} catch {\n\t\t\t\t// As above.\n\t\t\t}\n\t\t}\n\t\tsettle(result);\n\t};\n\tconst start = (): void => {\n\t\tif (ended) return;\n\t\ttimer = setTimer(() => end(TIMED_OUT, true), timeoutMs);\n\t\tif (!sink.required) unrefTimer(timer);\n\t\tvoid (async (): Promise<void> => {\n\t\t\ttry {\n\t\t\t\tawait (apply(sink.publish, sink.target, [envelope, context] as never[]) as unknown);\n\t\t\t\tend(OK, false);\n\t\t\t} catch (reason) {\n\t\t\t\tend({ status: \"failed\", reason }, false);\n\t\t\t}\n\t\t})();\n\t};\n\treturn freeze({ outcome, start, abort: () => end(ABORTED, true) });\n}\n\n/** `timer.unref()` on runtimes whose timers have it (Node); a number timer (browsers) is left alone. */\nfunction unrefTimer(timer: unknown): void {\n\ttry {\n\t\tif (timer === null || typeof timer !== \"object\") return;\n\t\tconst unref = (timer as { unref?: unknown }).unref;\n\t\tif (typeof unref === \"function\") apply(unref, timer, []);\n\t} catch {\n\t\t// A timer that cannot be unref'd still fires and is still cleared.\n\t}\n}\n\n/**\n * Build a publisher that hands each event to several sinks, for example the\n * webhook fan-out publisher and a message bus, from one Host relay. A second\n * relay on the same outbox claims the same records, so it is no substitute\n * (decision 2).\n *\n * Sinks are trusted application code; see the trust model above for what\n * the isolation below covers. Every sink is called concurrently, each with\n * its own envelope copy, its own context and its own signal, which aborts\n * when the caller's signal aborts or the sink's `sinkTimeoutMs` runs out. That holds for an optional\n * sink still running after `publish()` settled, too. The composite resolves\n * once every required sink resolved; optional sinks are not waited for. It\n * rejects:\n *\n * - with `publish_aborted`, and no sink started, when the caller's signal\n * aborts at any point before the sinks start, copying the envelope\n * included;\n * - with `publish_aborted` as soon as the caller's signal aborts while a\n * required sink is still running;\n * - otherwise, once every required sink has settled, for the first required\n * sink in sink order that did not resolve: with that sink's error when\n * this package created it (for example `event_past_replay_horizon`),\n * `sink_failed` for any other error, dropped unread, and `sink_timeout`\n * when it did not settle in time;\n * - with a `WebhookProjectionError` (`inspection_failed`) when the envelope\n * is not plain data (see `sinkEnvelopes`) or cannot be read, before any sink is called.\n *\n * The relay then retries the whole record, so every sink sees the event\n * again under the same `eventId`: each sink must treat a repeated `eventId`\n * as a no-op, as the fan-out publisher does.\n *\n * Actor identity reaches only sinks with `includeActor: true` (decision 5;\n * test \"the composite strips actor identity ...\").\n *\n * @throws {WebhookFanOutError} `options_invalid` at construction for an\n * empty or oversized sink list, a duplicate or malformed name, a sink\n * without a `publish` function, or a runtime without `AbortController`,\n * or `EventTarget`.\n * @throws {WebhookDeliveryConfigError} at construction for a `sinkTimeoutMs`\n * that is not a positive whole number within the timer range.\n */\nexport function createWebhookCompositePublisher(options: WebhookCompositePublisherOptions): EnterpriseEventPublisher {\n\tconst { sinks, timeoutMs } = guard(() => readComposite(options), () => fanOutError(\"options_invalid\", \"options\"));\n\tif (!compositeRuntimeAvailable()) throw fanOutError(\"options_invalid\", \"runtime\");\n\tconst publish = async (event: EnterpriseEventEnvelope, context?: EnterpriseEventPublishContext): Promise<void> => {\n\t\tconst parent = readContextSignal(context);\n\t\tif (parent !== undefined && signalAborted(parent)) throw fanOutError(\"publish_aborted\", \"signal\");\n\t\tconst disclosure = readContextDisclosure(context);\n\t\tconst strippedDisclosure = disclosure === \"included\" ? \"suppressed\" : disclosure;\n\t\tconst envelopes = guard(() => sinkEnvelopes(event, sinks), uninspectable(\"envelope\"));\n\n\t\t// One listener on the caller's signal forwards its abort to every run\n\t\t// still going, and is removed when the last run ends, which may be\n\t\t// after `publish()` settled (B4).\n\t\tlet live = sinks.length;\n\t\tconst runs: SinkRun[] = [];\n\t\tconst onParentAbort = (): void => {\n\t\t\tfor (let index = 0; index < runs.length; index += 1) runs[index]!.abort();\n\t\t};\n\t\tconst release = (): void => {\n\t\t\tlive -= 1;\n\t\t\tif (live === 0 && parent !== undefined) {\n\t\t\t\ttry {\n\t\t\t\t\tapply(removeListenerIntrinsic!, parent, [\"abort\", onParentAbort]);\n\t\t\t\t} catch {\n\t\t\t\t\t// The listener only aborts runs that have all ended.\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\t\tconst sink = sinks[index]!;\n\t\t\truns.push(prepareRun(sink, envelopes[index]!, sink.includeActor ? disclosure : strippedDisclosure, timeoutMs, release));\n\t\t}\n\t\tif (parent !== undefined) {\n\t\t\tlet watching = true;\n\t\t\ttry {\n\t\t\t\tapply(addListenerIntrinsic!, parent, [\"abort\", onParentAbort]);\n\t\t\t} catch {\n\t\t\t\twatching = false;\n\t\t\t}\n\t\t\t// The caller's signal may have aborted after the entry check, for\n\t\t\t// example from a proxy trap that ran while the snapshot copied the\n\t\t\t// envelope (getters are refused, not called), before the listener\n\t\t\t// existed. A caller abort that cannot\n\t\t\t// be watched is treated the same way. Either ends every run before\n\t\t\t// any starts, which also releases the listener.\n\t\t\tif (!watching || signalAborted(parent)) {\n\t\t\t\tonParentAbort();\n\t\t\t\tthrow fanOutError(\"publish_aborted\", \"signal\");\n\t\t\t}\n\t\t}\n\t\t// A sink's synchronous code may abort the caller's signal; a run the\n\t\t// forwarding already ended is then not started.\n\t\tfor (let index = 0; index < runs.length; index += 1) runs[index]!.start();\n\n\t\t// Only required runs are awaited. Each outcome promise is resolved by\n\t\t// its sink, its timer or the caller's abort, so the waits end promptly\n\t\t// on an abort (B5).\n\t\tconst outcomes: SinkOutcome[] = [];\n\t\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\t\tif (sinks[index]!.required) outcomes.push(await runs[index]!.outcome);\n\t\t}\n\t\tlet position = 0;\n\t\tlet failure: { readonly name: string; readonly outcome: SinkOutcome } | undefined;\n\t\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\t\tconst sink = sinks[index]!;\n\t\t\tif (!sink.required) continue;\n\t\t\tconst outcome = outcomes[position]!;\n\t\t\tposition += 1;\n\t\t\t// Only the forwarding of the caller's abort ends a run as aborted.\n\t\t\tif (outcome.status === \"aborted\") throw fanOutError(\"publish_aborted\", \"signal\");\n\t\t\tif (outcome.status !== \"ok\" && failure === undefined) failure = { name: sink.name, outcome };\n\t\t}\n\t\tif (failure === undefined) return;\n\t\tif (failure.outcome.status === \"timeout\") throw fanOutError(\"sink_timeout\", failure.name);\n\t\tconst reason = (failure.outcome as { readonly reason: unknown }).reason;\n\t\t// A package-made error passes through with its code; anything else is\n\t\t// replaced unread.\n\t\tguard(() => {\n\t\t\tthrow reason;\n\t\t}, () => fanOutError(\"sink_failed\", failure.name));\n\t};\n\treturn freeze({ publish });\n}\n","/**\n * The event types the package's governed actions emit (PR 9; README,\n * \"Governed actions\"). They are package constants, the same for every\n * module instance whatever its namespace, so the exclusion below does not\n * depend on how an application composed the module.\n *\n * ADR 0018 decision 9: these types are excluded from fan-out matching.\n * {@link matchesWebhookEventTypePattern} (src/fan-out-cycle.ts), the one\n * function that compares a subscription pattern with an event type, answers\n * `false` for each of them before it looks at the pattern, so no\n * subscription, `*` included, gets an intent or a denial for one. Test:\n * \"own-event exclusion: …\" in tests/governed-actions.test.ts.\n *\n * Kept free of `@fabricorg/platform` imports so the fan-out cycle can use it\n * without loading the module factory.\n */\nimport { apply } from \"./snapshot\";\n\nexport const WEBHOOK_DELIVERY_ACTION_EVENT_TYPES = Object.freeze([\n\t\"WebhookSubscriptionCreated\",\n\t\"WebhookSubscriptionUpdated\",\n\t\"WebhookSubscriptionPaused\",\n\t\"WebhookSubscriptionResumed\",\n\t\"WebhookSubscriptionDeleted\",\n\t\"WebhookSecretRotated\",\n\t\"WebhookDeliveryIntentRequeued\",\n\t\"WebhookFanOutJobRequeued\",\n\t\"WebhookFanOutJobActorEnriched\",\n] as const);\n\n/** An event type one of the package's governed actions emits. */\nexport type WebhookDeliveryActionEventType = (typeof WEBHOOK_DELIVERY_ACTION_EVENT_TYPES)[number];\n\nconst includes = Array.prototype.includes;\n\n/** `true` when `eventType` is emitted by one of the package's governed actions. */\nexport function isWebhookDeliveryActionEventType(eventType: unknown): eventType is WebhookDeliveryActionEventType {\n\treturn typeof eventType === \"string\" && apply(includes, WEBHOOK_DELIVERY_ACTION_EVENT_TYPES, [eventType]) === true;\n}\n","import { isWebhookDeliveryActionEventType } from \"./action-events\";\nimport type { WebhookAdmissionDenialCode, WebhookDiagnosticCode } from \"./codes\";\nimport { normalizeWebhookAdmissionDecision } from \"./decisions\";\nimport { renderWebhookDeliveryBodyV1 } from \"./egress\";\nimport { configError, fanOutError, guard } from \"./errors\";\nimport { boundedCall, captureFanOutClock, readFanOutClock, type BoundedOutcome, type FanOutClock } from \"./fan-out-call\";\nimport { readClaimedJobs, readDecided, readOutcome, readRevisions, type ClaimedHeader, type ClaimedJob } from \"./fan-out-read\";\nimport { assertPositiveInteger, resolveWebhookDeliveryLimits, type WebhookDeliveryLimits } from \"./limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookDeliveryStore,\n\tWebhookEventAdmission,\n\tWebhookFanOutJobFence,\n\tWebhookRandomSource,\n\tWebhookRetryDelay,\n\tWebhookScopePredicate,\n\tWebhookSubscriptionStore,\n} from \"./ports\";\nimport { createWebhookRetryDelay } from \"./retry\";\nimport { apply, freeze, mathMin, numberIsFinite, primitive } from \"./snapshot\";\nimport { isoOf } from \"./store-input\";\nimport type { WebhookEligibilityRevision, WebhookEventMetadata, WebhookPayloadPolicy } from \"./types\";\n\n/*\n * Stage two of the two-stage fan-out (ADR 0018 decisions 2, 3, 4 and 5).\n *\n * Completeness boundary (R1). A job binds each intent or denial to the\n * eligibility revision whose half-open interval contains the event's\n * `recordedAt`. Host stamps `recordedAt` with its clock; the subscription\n * store stamps each revision's `effectiveFrom` with its own. Until the\n * subscription store's clock has passed `recordedAt`, a pattern change,\n * pause, resume or create written now can still take effect at or before\n * `recordedAt` and change which revision contains it: a late-effective\n * revision. So the cycle evaluates a job only once its eligibility is\n * settled: the cycle's clock is at or past `recordedAt + eligibilitySettleMs`\n * (`settleAtMs` in `processJob` below). Before that it defers the job\n * unprocessed, writing no intent or denial.\n *\n * Two assumptions about clocks, which this package cannot enforce:\n *\n * - Skew. `eligibilitySettleMs` exceeds the skew between this worker's\n * clock and the subscription store's clock, plus the longest time a\n * revision write takes from reading that clock to becoming visible to\n * `listEligibilityRevisions` (a database store's transaction).\n * - No regression. The subscription store's clock never moves backward past\n * an event time this worker has already settled: in practice a monotonic,\n * NTP-slewed clock. A step backward larger than `eligibilitySettleMs` voids\n * the boundary for events settled inside the step.\n *\n * Host's clock does not enter either: `recordedAt` is only compared with\n * this worker's clock, so a Host clock running ahead delays evaluation and\n * nothing else.\n *\n * Under both assumptions the selection is final once settled: a revision\n * written later starts at the subscription store's clock\n * (WebhookSubscriptionWriter; `mathMax(nowMs, ...)` in the memory store's\n * `#transition`), which is then past `recordedAt`, so it cannot contain it.\n * If an assumption is broken and a revision is stamped at or before the\n * `recordedAt` of an event whose job already completed, the revision is not\n * applied to that event retroactively: the completed job stays completed\n * (test \"a revision stamped behind an already-settled event ...\"). The\n * job is complete when `completeFanOutJob` succeeds, which the cycle calls only\n * after every eligible revision has an intent or a recorded denial. After\n * that point nothing adds or removes intents for the event: claims take only\n * pending jobs, a job requeue accepts only dead letters, intent and denial\n * inserts are insert-if-absent per (subscriptionId, eventId), and a Host\n * outbox replay or a bridge insert of the same `eventId` answers\n * `already_present`. A pause, delete or resume written after `recordedAt`\n * does not change the event's revision; it acts on delivery instead\n * (`cancelPendingIntents` and the delivery cycle's pre-handoff check,\n * src/delivery-cycle.ts).\n * If the job cannot complete, it is rescheduled and finally dead-lettered: a\n * visible, recoverable failure (R1, decision 2).\n *\n * Processing deadline (R4). No intent, denial or completion is written for a\n * job at or after its persisted `processingDeadline`, on the store's clock.\n * Every port call made while processing a job is bounded by the smaller of\n * `portTimeoutMs` and the job's remaining lifetime, and its absolute\n * `deadline` is at most the processing deadline (`jobCall` below). The store\n * contract refuses a write whose call deadline has passed when it reaches the\n * write (store contract case \"a call whose signal aborted or whose deadline\n * passed writes nothing\"), and the cycle also rechecks the deadline before\n * each intent or denial write and before completion. Once the deadline has\n * passed, the job goes to the fenced dead-letter transition as\n * `processing_deadline_exceeded`, bounded by `portTimeoutMs` alone.\n *\n * Lease renewal (changed in PR 8). Every fenced write is refused once the\n * lease has expired on the store's clock, and a pass over a job can take\n * longer than one lease: it reads one tombstone per eligible revision on\n * every pass, decided pairs included. So before each port call made for a\n * job (`jobCall`, and the dead-letter transition), the worker renews the\n * job's lease when less than `RENEW_MARGIN_CALLS * portTimeoutMs` of it is\n * left (`keepLease`): enough for that call and the renewal before it. A\n * worker that keeps making calls therefore keeps its job, and each pass\n * gets as far as its port answers allow; a worker that stops (a crash, a\n * stalled event loop) stops renewing and loses the job when the lease runs\n * out. The store decides the renewal like any fenced write, on its own\n * clock, and never extends a lease past the job's processing deadline, so\n * that deadline still bounds the whole job. A refused renewal (literal\n * `false`) means the lease is gone: the pass stops on that job at once and\n * writes nothing more for it (`LEASE_LOST`). A renewal that throws, times\n * out or answers unreadably is unknown; the worker carries on with the\n * lease it last knew of, and the store's fence check decides its next\n * write. The worker tracks the lease's expiry on its own clock from the\n * `now` and `leaseDurationMs` it sent with the claim and each renewal; a\n * store clock running ahead of the worker's by more than `portTimeoutMs`\n * can still expire a lease the worker thinks it holds, which the store's\n * fence check then refuses (`lease_lost`).\n */\n\n/** What decides whether a subscription revision needs the event's actor identity. */\nexport interface WebhookActorRequirementInput {\n\treadonly subscriptionId: string;\n\treadonly eligibilityRevision: number;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly event: WebhookEventMetadata;\n}\n\n/** Options for {@link runWebhookFanOutCycle}. */\nexport interface WebhookFanOutCycleOptions {\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly subscriptions: WebhookSubscriptionStore;\n\treadonly admission: WebhookEventAdmission;\n\treadonly clock: { now(): Date };\n\t/** The lease owner this worker claims jobs as. */\n\treadonly workerId: string;\n\t/** The egress allowlist the intent bodies are rendered with (decision 9). */\n\treadonly policy: WebhookPayloadPolicy;\n\t/** Consulted for scoped event types when rendering a body. */\n\treadonly scopePredicate?: WebhookScopePredicate;\n\t/**\n\t * Whether admission for a revision needs actor identity (decision 5).\n\t * Required, so the choice is explicit. `true`, or a function returning\n\t * anything but a literal `false` (a throw included), makes a job whose\n\t * actor is `suppressed` or `legacy` `unavailable` for that revision\n\t * without calling admission: the job retries and finally dead-letters,\n\t * and actor enrichment (PR 9) repairs a legacy one.\n\t */\n\treadonly actorRequired: boolean | ((input: WebhookActorRequirementInput) => boolean);\n\t/**\n\t * Overrides of {@link WebhookDeliveryLimits}, all validated positive and\n\t * finite (R4). Used: `maxFanOutAttempts`, `fanOutRetryDelaysMs`,\n\t * `retryJitterRatio`, `portTimeoutMs`, `deliveryDeadlineMs` (each new\n\t * intent's processing deadline).\n\t */\n\treadonly limits?: Partial<WebhookDeliveryLimits>;\n\t/** Delay before the next attempt; defaults to `fanOutRetryDelaysMs` with jitter from `random`. */\n\treadonly retryDelay?: WebhookRetryDelay;\n\t/** Random source for the default retry delay's jitter; required when `retryDelay` is absent. */\n\treadonly random?: WebhookRandomSource;\n\t/** Jobs claimed per cycle. A positive whole number; default 25. */\n\treadonly batchSize?: number;\n\t/**\n\t * Lease on each claimed job, in ms; renewed while the job is processed\n\t * (see \"Lease renewal\" above). A positive whole number above\n\t * `3 * portTimeoutMs`; default 60 000.\n\t */\n\treadonly leaseDurationMs?: number;\n\t/**\n\t * How long after `recordedAt`, on this worker's clock, an event's\n\t * eligibility is treated as settled (see the completeness boundary\n\t * above). It must exceed the skew between this worker's clock and the\n\t * subscription store's, plus the longest revision write. A positive whole\n\t * number of ms below `fanOutDeadlineMs`; default 5 000.\n\t */\n\treadonly eligibilitySettleMs?: number;\n\t/** Creates each intent's `deliveryId`; defaults to `dlv_` plus a random UUID. */\n\treadonly createDeliveryId?: (input: { readonly subscriptionId: string; readonly eventId: string }) => string;\n\t/** Stops the cycle between jobs; the rest of the claimed jobs are reclaimed after their leases expire. */\n\treadonly signal?: AbortSignal;\n}\n\n/** What one cycle did. */\nexport interface WebhookFanOutCycleResult {\n\treadonly claimed: number;\n\t/** Jobs marked complete. */\n\treadonly completed: number;\n\t/** Jobs deferred unprocessed because their eligibility was not yet settled. */\n\treadonly deferred: number;\n\t/** Jobs returned to pending after an unavailable admission or a failed port. */\n\treadonly rescheduled: number;\n\treadonly deadLettered: number;\n\t/** Jobs this worker stopped on because a fenced write or a lease renewal found its lease gone. */\n\treadonly leaseLost: number;\n\t/**\n\t * Jobs left for lease expiry, with nothing more written: a record whose\n\t * identity or lease could not be read, one leased to another owner, or\n\t * one whose final fenced write threw or timed out. A final write that\n\t * timed out may have committed (README, \"Bounds and late results\"); the\n\t * job is then completed, rescheduled or dead-lettered as that write said.\n\t */\n\treadonly abandoned: number;\n\t/** Intent inserts the store confirmed. One that timed out may have committed and is not counted. */\n\treadonly intentsInserted: number;\n\t/** Denial inserts the store confirmed, counted like `intentsInserted`. */\n\treadonly denialsRecorded: number;\n}\n\n/** Defaults for the cycle's own options. */\nexport const DEFAULT_WEBHOOK_FAN_OUT_CYCLE = freeze({\n\tbatchSize: 25,\n\tleaseDurationMs: 60_000,\n\teligibilitySettleMs: 5_000,\n});\n\n/**\n * Whether an event type matches one subscription pattern. `*` matches every\n * type; a pattern ending in `.*` matches every type that starts with the\n * part before `*` (so `orders.*` matches `orders.OrderAccepted` and\n * `orders.lines.Added`, not `orders`); any other pattern must equal the type.\n * A `*` anywhere else is literal.\n *\n * The event types the package's own governed actions emit\n * (`WEBHOOK_DELIVERY_ACTION_EVENT_TYPES`) match no pattern, `*` included\n * (ADR 0018 decision 9). This is the only place a pattern is compared with\n * an event type (`isEligible` below calls it), so the exclusion holds for\n * every subscription whatever its patterns.\n */\nexport function matchesWebhookEventTypePattern(pattern: string, eventType: string): boolean {\n\tif (typeof pattern !== \"string\" || typeof eventType !== \"string\") return false;\n\tif (isWebhookDeliveryActionEventType(eventType)) return false;\n\tif (pattern === \"*\") return true;\n\tif (pattern.length > 2 && pattern.endsWith(\".*\")) return eventType.startsWith(pattern.slice(0, -1));\n\treturn pattern === eventType;\n}\n\nconst randomUUID: (() => string) | undefined =\n\ttypeof globalThis.crypto?.randomUUID === \"function\" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : undefined;\n\ninterface Config {\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly subscriptions: WebhookSubscriptionStore;\n\treadonly admission: WebhookEventAdmission;\n\treadonly clock: FanOutClock;\n\treadonly workerId: string;\n\treadonly policy: WebhookPayloadPolicy;\n\treadonly scopePredicate: WebhookScopePredicate | undefined;\n\treadonly actorRequired: boolean | ((input: WebhookActorRequirementInput) => boolean);\n\treadonly limits: WebhookDeliveryLimits;\n\treadonly retryDelay: WebhookRetryDelay;\n\treadonly batchSize: number;\n\treadonly leaseDurationMs: number;\n\treadonly settleMs: number;\n\treadonly createDeliveryId: (input: { readonly subscriptionId: string; readonly eventId: string }) => string;\n\treadonly signal: AbortSignal | undefined;\n}\n\nfunction hasMethods(value: unknown, names: readonly string[]): boolean {\n\tif (value === null || typeof value !== \"object\") return false;\n\tfor (const name of names) if (typeof (value as Record<string, unknown>)[name] !== \"function\") return false;\n\treturn true;\n}\n\n/** A cycle option that must be a positive whole number (R4), or its default. */\nfunction positiveWhole(value: unknown, fallback: number, field: string): number {\n\tconst read = primitive(value);\n\tconst resolved = read === undefined ? fallback : read;\n\tassertPositiveInteger(resolved, field);\n\treturn resolved;\n}\n\n/**\n * Read and validate the options. A package error (a limit, a missing port)\n * passes through with its code; anything else thrown while reading them, by\n * a getter or a Proxy trap, is replaced unread with `options_invalid`.\n */\nfunction readConfig(options: WebhookFanOutCycleOptions): Config {\n\treturn guard(() => readConfigUnguarded(options), () => fanOutError(\"options_invalid\", \"options\"));\n}\n\nfunction readConfigUnguarded(options: WebhookFanOutCycleOptions): Config {\n\tif (options === null || typeof options !== \"object\") throw fanOutError(\"options_invalid\", \"options\");\n\tconst limits = resolveWebhookDeliveryLimits(options.limits ?? {});\n\tconst batchSize = positiveWhole(options.batchSize, DEFAULT_WEBHOOK_FAN_OUT_CYCLE.batchSize, \"batchSize\");\n\tconst leaseDurationMs = positiveWhole(options.leaseDurationMs, DEFAULT_WEBHOOK_FAN_OUT_CYCLE.leaseDurationMs, \"leaseDurationMs\");\n\tconst settleMs = positiveWhole(options.eligibilitySettleMs, DEFAULT_WEBHOOK_FAN_OUT_CYCLE.eligibilitySettleMs, \"eligibilitySettleMs\");\n\t// A renewed lease must outlast the renewal call and the margin after it,\n\t// or the worker would renew before every call (see \"Lease renewal\").\n\tif (leaseDurationMs <= (RENEW_MARGIN_CALLS + 1) * limits.portTimeoutMs) throw configError(\"limit_out_of_range\", \"leaseDurationMs\");\n\t// A job whose settle point is past its processing deadline could never be evaluated.\n\tif (settleMs >= limits.fanOutDeadlineMs) throw configError(\"limit_out_of_range\", \"eligibilitySettleMs\");\n\tif (!hasMethods(options.deliveries, [\"claimFanOutJobs\", \"renewFanOutJobLease\", \"completeFanOutJob\", \"rescheduleFanOutJob\", \"deadLetterFanOutJob\", \"insertDeliveryIntent\", \"recordAdmissionDenial\", \"readTombstone\"])) {\n\t\tthrow fanOutError(\"options_invalid\", \"deliveries\");\n\t}\n\tif (!hasMethods(options.subscriptions, [\"listEligibilityRevisions\"])) throw fanOutError(\"options_invalid\", \"subscriptions\");\n\tif (!hasMethods(options.admission, [\"admit\"])) throw fanOutError(\"options_invalid\", \"admission\");\n\tif (typeof options.workerId !== \"string\" || options.workerId === \"\") throw fanOutError(\"options_invalid\", \"workerId\");\n\tconst actorRequired = options.actorRequired;\n\tif (typeof actorRequired !== \"boolean\" && typeof actorRequired !== \"function\") throw fanOutError(\"options_invalid\", \"actorRequired\");\n\tif (options.scopePredicate !== undefined && typeof options.scopePredicate !== \"function\") throw fanOutError(\"options_invalid\", \"scopePredicate\");\n\tif (options.signal !== undefined && !(options.signal instanceof AbortSignal)) throw fanOutError(\"options_invalid\", \"signal\");\n\tlet retryDelay: WebhookRetryDelay;\n\tif (options.retryDelay !== undefined) {\n\t\tif (typeof options.retryDelay !== \"function\") throw fanOutError(\"options_invalid\", \"retryDelay\");\n\t\tretryDelay = options.retryDelay;\n\t} else {\n\t\tretryDelay = createWebhookRetryDelay({ delaysMs: limits.fanOutRetryDelaysMs, jitterRatio: limits.retryJitterRatio, random: options.random! });\n\t}\n\tlet createDeliveryId = options.createDeliveryId;\n\tif (createDeliveryId === undefined) {\n\t\tif (randomUUID === undefined) throw fanOutError(\"options_invalid\", \"createDeliveryId\");\n\t\tconst uuid = randomUUID;\n\t\tcreateDeliveryId = () => `dlv_${uuid()}`;\n\t} else if (typeof createDeliveryId !== \"function\") {\n\t\tthrow fanOutError(\"options_invalid\", \"createDeliveryId\");\n\t}\n\treturn freeze({\n\t\tdeliveries: options.deliveries,\n\t\tsubscriptions: options.subscriptions,\n\t\tadmission: options.admission,\n\t\tclock: captureFanOutClock(options.clock),\n\t\tworkerId: options.workerId,\n\t\tpolicy: options.policy,\n\t\tscopePredicate: options.scopePredicate,\n\t\tactorRequired,\n\t\tlimits,\n\t\tretryDelay,\n\t\tbatchSize,\n\t\tleaseDurationMs,\n\t\tsettleMs,\n\t\tcreateDeliveryId,\n\t\tsignal: options.signal,\n\t});\n}\n\ninterface Counters {\n\tclaimed: number;\n\tcompleted: number;\n\tdeferred: number;\n\trescheduled: number;\n\tdeadLettered: number;\n\tleaseLost: number;\n\tabandoned: number;\n\tintentsInserted: number;\n\tdenialsRecorded: number;\n}\n\n/**\n * Run one fan-out cycle: claim up to `batchSize` pending jobs under a fenced\n * lease and process each in turn. A claimed record whose `eventId`,\n * `tenantId`, `spaceId` or lease cannot be read is left for lease expiry\n * (`abandoned`); one whose identity and lease can be read but whose body\n * cannot is dead-lettered as `job_unreadable` without being processed. For\n * each readable job, in order:\n *\n * 1. Past its processing deadline (persisted at creation; deferrals and\n * reclaims count toward it, R4): dead-letter `processing_deadline_exceeded`.\n * 2. Eligibility not yet settled (`recordedAt + eligibilitySettleMs` still\n * ahead): defer it to that time, unprocessed, as `eligibility_unsettled`.\n * The store's reschedule spends one attempt, so a deferred job has one\n * attempt fewer for failures.\n * 3. List the revisions containing `recordedAt` in the job's tenant and\n * space. Each `active` revision whose patterns match the event type is\n * eligible; a paused or deleted one gets neither intent nor denial.\n * 4. For each eligible revision, in `subscriptionId` order: a pair that\n * already has an intent or a denial (its tombstone) is decided and\n * admission is not asked again. Otherwise, when the revision needs an\n * actor and the job has none (`suppressed` or `legacy`), it is\n * `unavailable`; else admission decides, with a throw, a timeout or an\n * unreadable answer read as `unavailable`. `allow` renders the v1 body and\n * inserts an intent; `deny` records a denial with its code; `unavailable`\n * writes nothing and leaves the job incomplete.\n * 5. Every eligible revision decided: complete the job. Otherwise\n * reschedule it after `retryDelay(attempt)`, or dead-letter it when the\n * attempts are spent or the next attempt would fall past its deadline.\n *\n * Every port call in steps 3 to 5, except the dead-letter transition (bounded\n * by `portTimeoutMs` alone), is bounded by the smaller of\n * `portTimeoutMs` and the job's remaining lifetime; once the processing\n * deadline has passed the job is dead-lettered and nothing else is written\n * for it (see \"Processing deadline\" above). Every port result is read through\n * `src/fan-out-read.ts`, so a getter or Proxy trap in it cannot throw out of\n * the cycle; an unreadable result counts as that port being unavailable.\n *\n * Every write is fenced by the job's lease, which the worker renews while\n * it works (see \"Lease renewal\" above). When the store answers\n * `lease_lost`, a fenced transition answers `false`, or a renewal is\n * refused, the worker stops on that job and writes nothing more for it. A\n * read or an insert that throws or times out stops the job and reschedules\n * it; an insert that timed out may have committed, and the next attempt\n * finds it `already_present`. A final transition (completion, reschedule,\n * dead letter) that throws or times out may have committed too, so nothing\n * follows it: the job is `abandoned`, and a later claim finds it as that\n * transition left it. Inserts already made stay.\n *\n * @throws {WebhookDeliveryConfigError} for a limit or cycle option that is\n * not positive and finite (R4).\n * @throws {WebhookFanOutError} `options_invalid` for a missing port or\n * option; `fan_out_store_failed` or `fan_out_store_timeout` when the claim\n * fails; `clock_invalid` for a failing clock.\n */\nexport async function runWebhookFanOutCycle(options: WebhookFanOutCycleOptions): Promise<WebhookFanOutCycleResult> {\n\tconst config = readConfig(options);\n\tconst counters: Counters = { claimed: 0, completed: 0, deferred: 0, rescheduled: 0, deadLettered: 0, leaseLost: 0, abandoned: 0, intentsInserted: 0, denialsRecorded: 0 };\n\tconst nowMs = readFanOutClock(config.clock);\n\tconst claimed = await bounded(config, nowMs, (callOptions) => config.deliveries.claimFanOutJobs({\n\t\tworkerId: config.workerId,\n\t\tleaseDurationMs: config.leaseDurationMs,\n\t\tlimit: config.batchSize,\n\t\tnow: new Date(nowMs),\n\t}, callOptions));\n\tif (!claimed.ok) throw fanOutError(claimed.reason === \"timeout\" ? \"fan_out_store_timeout\" : \"fan_out_store_failed\", \"claimFanOutJobs\");\n\tconst jobs = readClaimedJobs(claimed.value);\n\tif (jobs === undefined) throw fanOutError(\"fan_out_store_failed\", \"claimFanOutJobs\");\n\tcounters.claimed = jobs.length;\n\t// The expiry this worker asked for; the store sets it from the same `now`.\n\tconst claimedUntilMs = nowMs + config.leaseDurationMs;\n\tfor (const entry of jobs) {\n\t\tif (config.signal?.aborted) break;\n\t\t// A record whose identity or lease cannot be read cannot be named by a\n\t\t// fenced write, and one leased to another owner is not this worker's:\n\t\t// either is left for lease expiry, with nothing written.\n\t\tif (entry === undefined || entry.header.lease.owner !== config.workerId) {\n\t\t\tcounters.abandoned += 1;\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\t// A readable header with a body that cannot be read (A2): the job can\n\t\t\t// never be processed, so it ends now through the fenced dead-letter\n\t\t\t// transition, instead of returning to pending on every lease expiry.\n\t\t\t// Its processing deadline is in the body, so it is unknown here; the\n\t\t\t// store still caps a renewal at it.\n\t\t\tif (entry.job === undefined) {\n\t\t\t\tawait deadLetter(config, jobLease(config, entry.header, claimedUntilMs, Infinity), counters, \"job_unreadable\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait processJob(config, entry.job, jobLease(config, entry.header, claimedUntilMs, entry.job.processingDeadlineMs), counters);\n\t\t} catch (stopped) {\n\t\t\t// A refused renewal: the lease is gone, and nothing more is written for this job.\n\t\t\tif (stopped !== LEASE_LOST) throw stopped;\n\t\t\tcounters.leaseLost += 1;\n\t\t}\n\t}\n\treturn freeze({ ...counters });\n}\n\n/** A port call bounded by `portTimeoutMs` only: the claim, and the dead-letter transition. */\nfunction bounded<T>(config: Config, nowMs: number, run: (options: WebhookCallOptions) => Promise<T>): Promise<BoundedOutcome<T>> {\n\treturn boundedCall(nowMs, config.limits.portTimeoutMs, config.signal, run, () => readFanOutClock(config.clock));\n}\n\n/**\n * The lease this worker holds on one claimed job: the fence every write for\n * it carries (its `eventId`, this worker, the claim's fence), the expiry\n * this worker last asked for, on its own clock, and the job's processing\n * deadline (`Infinity` when the body that holds it could not be read).\n */\ninterface JobLease {\n\treadonly parent: WebhookFanOutJobFence;\n\texpiresAtMs: number;\n\treadonly deadlineMs: number;\n}\n\nfunction jobLease(config: Config, header: ClaimedHeader, expiresAtMs: number, deadlineMs: number): JobLease {\n\treturn { parent: freeze({ eventId: header.eventId, owner: config.workerId, fence: header.lease.fence }), expiresAtMs, deadlineMs };\n}\n\n/**\n * Thrown by {@link keepLease} when the store refuses a renewal, and caught\n * only by `runWebhookFanOutCycle`'s loop: it unwinds the job's processing\n * at once, so nothing more is written for that job. A package-owned object,\n * so no port can throw it.\n */\nconst LEASE_LOST: object = freeze(Object.create(null) as object);\n\n/** Renew when less than this many `portTimeoutMs` of the lease is left: the renewal, then the call it precedes. */\nconst RENEW_MARGIN_CALLS = 2;\n\n/**\n * Keep the job's lease for the next call (see \"Lease renewal\" above). Renews\n * when less than `RENEW_MARGIN_CALLS * portTimeoutMs` is left. Throws\n * {@link LEASE_LOST} on a refusal; carries on when the renewal's outcome is\n * unknown.\n */\nasync function keepLease(config: Config, lease: JobLease): Promise<void> {\n\tconst nowMs = readFanOutClock(config.clock);\n\tif (lease.expiresAtMs - nowMs >= RENEW_MARGIN_CALLS * config.limits.portTimeoutMs) return;\n\tconst { parent } = lease;\n\tconst renewed = await bounded(config, nowMs, (callOptions) => config.deliveries.renewFanOutJobLease({\n\t\teventId: parent.eventId,\n\t\towner: parent.owner,\n\t\tfence: parent.fence,\n\t\tnow: new Date(nowMs),\n\t\tleaseDurationMs: config.leaseDurationMs,\n\t}, callOptions));\n\tif (renewed.ok && renewed.value === true) {\n\t\t// The store's rule: never shorter than before, never past the processing deadline.\n\t\tconst untilMs = mathMin(nowMs + config.leaseDurationMs, lease.deadlineMs);\n\t\tif (untilMs > lease.expiresAtMs) lease.expiresAtMs = untilMs;\n\t\treturn;\n\t}\n\tif (renewed.ok && renewed.value === false) throw LEASE_LOST;\n}\n\n/** One job being processed: its lease and its persisted processing deadline. */\ninterface JobRun {\n\treadonly config: Config;\n\treadonly job: ClaimedJob;\n\treadonly lease: JobLease;\n\treadonly parent: WebhookFanOutJobFence;\n\treadonly deadlineMs: number;\n\treadonly counters: Counters;\n}\n\ntype JobOutcome<T> = BoundedOutcome<T> | { readonly ok: false; readonly reason: \"deadline\" };\n\n/**\n * A port call made while processing a job (R4). It is not made at all once\n * the job's processing deadline has passed, and otherwise it is bounded by\n * the smaller of `portTimeoutMs` and the job's remaining lifetime, so its\n * absolute `deadline`, which the store checks at its write, is never later\n * than the processing deadline. The job's lease is renewed first when it\n * must be (`keepLease`), so the call can finish inside the lease.\n */\nasync function jobCall<T>(run: JobRun, call: (options: WebhookCallOptions, nowMs: number) => Promise<T>): Promise<JobOutcome<T>> {\n\tif (!(run.deadlineMs - readFanOutClock(run.config.clock) > 0)) return { ok: false, reason: \"deadline\" };\n\tawait keepLease(run.config, run.lease);\n\tconst nowMs = readFanOutClock(run.config.clock);\n\tconst remainingMs = run.deadlineMs - nowMs;\n\tif (!(remainingMs > 0)) return { ok: false, reason: \"deadline\" };\n\tconst timeoutMs = remainingMs < run.config.limits.portTimeoutMs ? remainingMs : run.config.limits.portTimeoutMs;\n\treturn boundedCall(nowMs, timeoutMs, run.config.signal, (options) => call(options, nowMs), () => readFanOutClock(run.config.clock));\n}\n\nfunction failureDiagnostic(reason: \"threw\" | \"timeout\" | \"aborted\" | \"deadline\", unavailable: WebhookDiagnosticCode): WebhookDiagnosticCode {\n\tif (reason === \"deadline\") return \"processing_deadline_exceeded\";\n\treturn reason === \"timeout\" ? \"port_timeout\" : unavailable;\n}\n\ntype Decision =\n\t| { readonly kind: \"allow\" }\n\t| { readonly kind: \"deny\"; readonly code: WebhookAdmissionDenialCode }\n\t| { readonly kind: \"decided\" }\n\t| { readonly kind: \"unavailable\"; readonly diagnostic: WebhookDiagnosticCode };\n\n/** Why processing a job stopped early. */\ntype Stop =\n\t| { readonly kind: \"lease_lost\" }\n\t| { readonly kind: \"past_horizon\" }\n\t| { readonly kind: \"failed\"; readonly diagnostic: WebhookDiagnosticCode };\n\nasync function processJob(config: Config, job: ClaimedJob, lease: JobLease, counters: Counters): Promise<void> {\n\t// Both are finite: `readClaimedJobs` refuses a body whose dates do not parse.\n\tconst deadlineMs = job.processingDeadlineMs;\n\tconst run: JobRun = { config, job, lease, parent: lease.parent, deadlineMs, counters };\n\tconst nowMs = readFanOutClock(config.clock);\n\n\t// R4: the processing deadline was persisted when the job was created.\n\tif (nowMs >= deadlineMs) return deadLetterRun(run, \"processing_deadline_exceeded\");\n\n\t// R1: the completeness boundary. Nothing is decided for this event until\n\t// no revision written from now on can take effect at or before recordedAt.\n\tconst settleAtMs = job.recordedAtMs + config.settleMs;\n\tif (nowMs < settleAtMs) {\n\t\tif (settleAtMs >= deadlineMs) return deadLetterRun(run, \"processing_deadline_exceeded\");\n\t\treturn reschedule(run, settleAtMs, \"eligibility_unsettled\", \"deferred\");\n\t}\n\n\tconst listed = await jobCall(run, (callOptions) => config.subscriptions.listEligibilityRevisions(\n\t\t{ tenantId: job.tenantId, spaceId: job.spaceId, recordedAt: job.event.recordedAt },\n\t\tcallOptions,\n\t));\n\tif (!listed.ok) return retryOrDeadLetter(run, failureDiagnostic(listed.reason, \"subscription_store_unavailable\"));\n\tconst revisions = readRevisions(listed.value);\n\tif (revisions === undefined) return retryOrDeadLetter(run, \"subscription_store_unavailable\");\n\n\tlet incomplete: WebhookDiagnosticCode | undefined;\n\tfor (const revision of revisions) {\n\t\tif (!isEligible(revision, job)) continue;\n\t\tconst decision = await decide(run, revision);\n\t\tif (decision.kind === \"decided\") continue;\n\t\tif (decision.kind === \"unavailable\") {\n\t\t\t// A store failure or the deadline stops the job; an admission outage\n\t\t\t// leaves this pair open and moves on to the next one.\n\t\t\tif (decision.diagnostic === \"processing_deadline_exceeded\" || decision.diagnostic === \"delivery_store_unavailable\") {\n\t\t\t\treturn retryOrDeadLetter(run, decision.diagnostic);\n\t\t\t}\n\t\t\tincomplete ??= decision.diagnostic;\n\t\t\tcontinue;\n\t\t}\n\t\tconst stop = decision.kind === \"allow\" ? await insertIntent(run, revision) : await recordDenial(run, revision, decision.code);\n\t\tif (stop === undefined) continue;\n\t\tif (stop.kind === \"lease_lost\") {\n\t\t\t// Another worker holds the job now; this one writes nothing more for it.\n\t\t\tcounters.leaseLost += 1;\n\t\t\treturn;\n\t\t}\n\t\tif (stop.kind === \"past_horizon\") return deadLetterRun(run, \"processing_deadline_exceeded\");\n\t\tif (stop.diagnostic === \"intent_build_failed\") {\n\t\t\tincomplete ??= stop.diagnostic;\n\t\t\tcontinue;\n\t\t}\n\t\treturn retryOrDeadLetter(run, stop.diagnostic);\n\t}\n\tif (incomplete !== undefined) return retryOrDeadLetter(run, incomplete);\n\n\t// `jobCall` rechecks the deadline here, and the store checks the call deadline again at its write.\n\tconst done = await jobCall(run, (callOptions, now) =>\n\t\tconfig.deliveries.completeFanOutJob({ eventId: job.eventId, owner: run.parent.owner, fence: run.parent.fence, now: new Date(now) }, callOptions));\n\t// Only a completion that was never sent is followed by the dead letter. One\n\t// that threw or timed out may have committed, so nothing follows it: the\n\t// job is `abandoned`, and if it is still pending a later claim finds it\n\t// past its deadline and dead-letters it then.\n\tif (!done.ok && done.reason === \"deadline\") return deadLetterRun(run, \"processing_deadline_exceeded\");\n\tsettleCount(done, counters, \"completed\");\n}\n\n/** An `active` revision in the job's own scope whose patterns match the event type. */\nfunction isEligible(revision: WebhookEligibilityRevision, job: ClaimedJob): boolean {\n\tif (revision.status !== \"active\") return false;\n\t// Decision 9: a job reads revisions only for its own tenant and space.\n\tif (revision.tenantId !== job.tenantId || revision.spaceId !== job.spaceId) return false;\n\tfor (const pattern of revision.eventTypePatterns) {\n\t\tif (matchesWebhookEventTypePattern(pattern, job.event.eventType)) return true;\n\t}\n\treturn false;\n}\n\nfunction actorRequiredFor(config: Config, job: ClaimedJob, revision: WebhookEligibilityRevision): boolean {\n\tconst required = config.actorRequired;\n\tif (typeof required === \"boolean\") return required;\n\ttry {\n\t\t// Fail closed: only a literal `false` waives the actor.\n\t\treturn apply(required, undefined, [freeze({\n\t\t\tsubscriptionId: revision.subscriptionId,\n\t\t\teligibilityRevision: revision.revision,\n\t\t\ttenantId: job.tenantId,\n\t\t\tspaceId: job.spaceId,\n\t\t\tevent: job.event,\n\t\t})]) !== false;\n\t} catch {\n\t\treturn true;\n\t}\n}\n\nasync function decide(run: JobRun, revision: WebhookEligibilityRevision): Promise<Decision> {\n\tconst { config, job } = run;\n\t// A pair with an intent or a denial (their tombstone) is decided: a retry\n\t// or a re-claim does not ask admission again, so an admission outage\n\t// after the decision cannot hold the job open.\n\tconst marker = await jobCall(run, (callOptions) => config.deliveries.readTombstone(\n\t\t{ tenantId: job.tenantId, spaceId: job.spaceId, subscriptionId: revision.subscriptionId, eventId: job.eventId },\n\t\tcallOptions,\n\t));\n\tif (!marker.ok) return { kind: \"unavailable\", diagnostic: failureDiagnostic(marker.reason, \"delivery_store_unavailable\") };\n\tconst decided = readDecided(marker.value);\n\tif (decided === undefined) return { kind: \"unavailable\", diagnostic: \"delivery_store_unavailable\" };\n\tif (decided === \"decided\") return { kind: \"decided\" };\n\n\t// Decision 5: suppressed and legacy absence are both `unavailable` for a\n\t// revision that needs the actor; admission is not asked.\n\tif (job.actor.state !== \"present\" && actorRequiredFor(config, job, revision)) {\n\t\treturn { kind: \"unavailable\", diagnostic: \"admission_unavailable\" };\n\t}\n\tconst answer = await jobCall(run, (callOptions) => config.admission.admit({\n\t\tsubscriptionId: revision.subscriptionId,\n\t\teligibilityRevision: revision.revision,\n\t\tevent: job.event,\n\t\tfacts: job.facts,\n\t\tactor: job.actor,\n\t}, callOptions));\n\t// Decision 4: a throw or a timeout is `unavailable`, and no intent is written.\n\tif (!answer.ok) return { kind: \"unavailable\", diagnostic: failureDiagnostic(answer.reason, \"admission_unavailable\") };\n\t// Total: an answer that cannot be read is `unavailable`, never `allow`.\n\tconst decision = normalizeWebhookAdmissionDecision(answer.value);\n\tif (decision.decision === \"allow\") return { kind: \"allow\" };\n\tif (decision.decision === \"deny\") return { kind: \"deny\", code: decision.code };\n\treturn { kind: \"unavailable\", diagnostic: \"admission_unavailable\" };\n}\n\nconst INSERT_OUTCOMES = freeze([\"inserted\", \"already_present\", \"lease_lost\", \"past_horizon\"] as const);\n\n/** Read a fenced insert's answer: `\"inserted\"`, `undefined` to continue, or why to stop. */\nfunction insertStop(outcome: JobOutcome<unknown>): Stop | undefined | \"inserted\" {\n\tif (!outcome.ok) return { kind: \"failed\", diagnostic: failureDiagnostic(outcome.reason, \"delivery_store_unavailable\") };\n\tconst answer = readOutcome(outcome.value, INSERT_OUTCOMES);\n\tif (answer === \"inserted\") return \"inserted\";\n\tif (answer === \"already_present\") return undefined;\n\tif (answer === \"lease_lost\") return { kind: \"lease_lost\" };\n\tif (answer === \"past_horizon\") return { kind: \"past_horizon\" };\n\treturn { kind: \"failed\", diagnostic: \"delivery_store_unavailable\" };\n}\n\nasync function insertIntent(run: JobRun, revision: WebhookEligibilityRevision): Promise<Stop | undefined> {\n\tconst { config, job } = run;\n\tlet deliveryId: string;\n\tlet body: string;\n\ttry {\n\t\tdeliveryId = apply(config.createDeliveryId, undefined, [freeze({ subscriptionId: revision.subscriptionId, eventId: job.eventId })]) as string;\n\t\tif (typeof deliveryId !== \"string\") throw fanOutError(\"options_invalid\", \"createDeliveryId\");\n\t\tbody = renderWebhookDeliveryBodyV1({\n\t\t\tjob,\n\t\t\tsubscription: { subscriptionId: revision.subscriptionId, tenantId: revision.tenantId, spaceId: revision.spaceId },\n\t\t\tpolicy: config.policy,\n\t\t\tscopePredicate: config.scopePredicate,\n\t\t\tdeliveryId,\n\t\t}).rawBody;\n\t} catch {\n\t\treturn { kind: \"failed\", diagnostic: \"intent_build_failed\" };\n\t}\n\t// `jobCall` refuses to start once the deadline has passed and caps the call deadline at it.\n\tconst outcome = await jobCall(run, (callOptions, nowMs) => config.deliveries.insertDeliveryIntent({\n\t\tdeliveryId,\n\t\tsubscriptionId: revision.subscriptionId,\n\t\teventId: job.eventId,\n\t\ttenantId: job.tenantId,\n\t\tspaceId: job.spaceId,\n\t\teligibilityRevision: revision.revision,\n\t\tbody,\n\t\tavailableAt: isoOf(nowMs),\n\t\tprocessingDeadline: isoOf(nowMs + config.limits.deliveryDeadlineMs),\n\t\tcreatedAt: isoOf(nowMs),\n\t}, run.parent, callOptions));\n\tconst stop = insertStop(outcome);\n\tif (stop === \"inserted\") {\n\t\trun.counters.intentsInserted += 1;\n\t\treturn undefined;\n\t}\n\treturn stop;\n}\n\nasync function recordDenial(run: JobRun, revision: WebhookEligibilityRevision, code: WebhookAdmissionDenialCode): Promise<Stop | undefined> {\n\tconst { config, job } = run;\n\tconst outcome = await jobCall(run, (callOptions, nowMs) => config.deliveries.recordAdmissionDenial({\n\t\tsubscriptionId: revision.subscriptionId,\n\t\teventId: job.eventId,\n\t\ttenantId: job.tenantId,\n\t\tspaceId: job.spaceId,\n\t\teligibilityRevision: revision.revision,\n\t\tcode,\n\t\trecordedAt: isoOf(nowMs),\n\t}, run.parent, callOptions));\n\tconst stop = insertStop(outcome);\n\tif (stop === \"inserted\") {\n\t\trun.counters.denialsRecorded += 1;\n\t\treturn undefined;\n\t}\n\treturn stop;\n}\n\n/**\n * Count a fenced transition. Only a literal `true` is done and a literal\n * `false` is a lost lease; anything else, a failed call included, leaves the\n * job for lease expiry. The comparisons run no code of the value.\n */\nfunction settleCount(outcome: JobOutcome<unknown>, counters: Counters, done: \"completed\" | \"deferred\" | \"rescheduled\" | \"deadLettered\"): void {\n\tif (outcome.ok && outcome.value === true) counters[done] += 1;\n\telse if (outcome.ok && outcome.value === false) counters.leaseLost += 1;\n\telse counters.abandoned += 1;\n}\n\nasync function retryOrDeadLetter(run: JobRun, diagnostic: WebhookDiagnosticCode): Promise<void> {\n\tconst { config, job } = run;\n\tconst nowMs = readFanOutClock(config.clock);\n\tif (nowMs >= run.deadlineMs) return deadLetterRun(run, \"processing_deadline_exceeded\");\n\tconst attempt = job.attemptCount + 1;\n\tif (attempt >= config.limits.maxFanOutAttempts) return deadLetterRun(run, diagnostic);\n\tlet delayMs: number;\n\ttry {\n\t\tdelayMs = apply(config.retryDelay, undefined, [attempt]) as number;\n\t} catch {\n\t\tdelayMs = NaN;\n\t}\n\t// A retry delay that is not a non-negative finite number falls back to\n\t// the longest configured delay rather than retrying at once.\n\tif (typeof delayMs !== \"number\" || !numberIsFinite(delayMs) || delayMs < 0) {\n\t\tconst delays = config.limits.fanOutRetryDelaysMs;\n\t\tdelayMs = delays[delays.length - 1]!;\n\t}\n\tconst availableAtMs = nowMs + delayMs;\n\tif (availableAtMs >= run.deadlineMs) return deadLetterRun(run, \"processing_deadline_exceeded\");\n\treturn reschedule(run, availableAtMs, diagnostic, \"rescheduled\");\n}\n\nasync function reschedule(run: JobRun, availableAtMs: number, diagnostic: WebhookDiagnosticCode, done: \"deferred\" | \"rescheduled\"): Promise<void> {\n\tconst { config, job, parent } = run;\n\tconst outcome = await jobCall(run, (callOptions, nowMs) => config.deliveries.rescheduleFanOutJob({\n\t\teventId: job.eventId,\n\t\towner: parent.owner,\n\t\tfence: parent.fence,\n\t\tnow: new Date(nowMs),\n\t\tavailableAt: new Date(availableAtMs),\n\t\tdiagnostic,\n\t}, callOptions));\n\t// As for completion: only a reschedule that was never sent is followed by\n\t// the dead letter; one that threw or timed out may have committed.\n\tif (!outcome.ok && outcome.reason === \"deadline\") return deadLetterRun(run, \"processing_deadline_exceeded\");\n\tsettleCount(outcome, run.counters, done);\n}\n\nfunction deadLetterRun(run: JobRun, diagnostic: WebhookDiagnosticCode): Promise<void> {\n\treturn deadLetter(run.config, run.lease, run.counters, diagnostic);\n}\n\n/**\n * The fenced dead-letter transition, bounded by `portTimeoutMs` alone: it is\n * how a job past its deadline ends, and how a job whose body cannot be read\n * ends (`job_unreadable`). It needs only the job's fence, never its body.\n */\nasync function deadLetter(config: Config, lease: JobLease, counters: Counters, diagnostic: WebhookDiagnosticCode): Promise<void> {\n\tawait keepLease(config, lease);\n\tconst parent = lease.parent;\n\tconst nowMs = readFanOutClock(config.clock);\n\tconst outcome = await bounded(config, nowMs, (callOptions) => config.deliveries.deadLetterFanOutJob({\n\t\teventId: parent.eventId,\n\t\towner: parent.owner,\n\t\tfence: parent.fence,\n\t\tnow: new Date(nowMs),\n\t\tdiagnostic,\n\t}, callOptions));\n\tsettleCount(outcome, counters, \"deadLettered\");\n}\n","import { buildWebhookRequestHeaders } from \"./headers\";\nimport type { WebhookResolvedAddress, WebhookTransportResult, WebhookVettedDestination } from \"./ports\";\nimport {\n\tdateParse,\n\tfreeze,\n\tfrozenList,\n\tisArray,\n\tisOneOf,\n\tisPlainRecord,\n\tnumberIsFinite,\n\tnumberIsSafeInteger,\n\treadOwn,\n\trecord,\n\ttype Fail,\n} from \"./snapshot\";\nimport type { WebhookSubscriptionStatus } from \"./types\";\n\n/*\n * Reading what a port returned, for the delivery cycle. The same rules as\n * src/fan-out-read.ts: own data properties only, read through descriptors\n * (an accessor is refused uncalled), copied into package-owned frozen\n * values, one try/catch per reader, and whatever a reader catches is\n * dropped unread. Anything that cannot be read is `undefined`, and the\n * cycle maps that to a fixed code.\n */\n\nconst REFUSED = freeze(Object.create(null) as object);\nconst refuse: Fail = () => {\n\tthrow REFUSED;\n};\n\nfunction raw(target: object, key: string): unknown {\n\treturn readOwn(target, key, key, refuse);\n}\n\nfunction plain(value: unknown): object {\n\tif (!isPlainRecord(value)) throw REFUSED;\n\treturn value;\n}\n\nfunction nonEmpty(value: unknown): string {\n\tif (typeof value !== \"string\" || value === \"\") throw REFUSED;\n\treturn value;\n}\n\nfunction whole(value: unknown, min: number): number {\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < min) throw REFUSED;\n\treturn value;\n}\n\nfunction instantMs(value: unknown): number {\n\tconst ms = dateParse(nonEmpty(value));\n\tif (!numberIsFinite(ms)) throw REFUSED;\n\treturn ms;\n}\n\n// ---------------------------------------------------------------------------\n// Claimed intents\n// ---------------------------------------------------------------------------\n\n/** What names a claimed intent and its lease: all a fenced settlement needs. */\nexport interface ClaimedIntentHeader {\n\treadonly deliveryId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly lease: { readonly owner: string; readonly fence: number };\n}\n\n/** A claimed intent as the cycle uses it, every field read and validated. */\nexport interface ClaimedIntent extends ClaimedIntentHeader {\n\treadonly subscriptionId: string;\n\treadonly eventId: string;\n\t/** The eligibility revision fan-out bound the intent to (decision 3); dispatch compares it with the snapshot's `statusSinceRevision`. */\n\treadonly eligibilityRevision: number;\n\t/** The rendered v1 body, signed and sent byte for byte. */\n\treadonly body: string;\n\treadonly attemptCount: number;\n\treadonly processingDeadlineMs: number;\n\treadonly leaseExpiresAtMs: number;\n}\n\n/**\n * One entry of a claim result. `undefined`: identity or lease cannot be\n * read, so no fenced write can name it. `intent: undefined`: the header\n * was read but the rest cannot be, so the cycle dead-letters it by its\n * header (`intent_unreadable`).\n */\nexport type ClaimedIntentEntry = { readonly header: ClaimedIntentHeader; readonly intent: ClaimedIntent | undefined } | undefined;\n\n/** More intents than any claim limit a cycle sends; a longer answer is not a claim result. */\nconst MAX_CLAIMED = 100_000;\n\n/** A placeholder `v1` value, used only to check that the intent's ids are header-safe before anything is signed. */\nconst PLACEHOLDER_SIGNATURE = `v1=${\"0\".repeat(64)}`;\n\nfunction readIntentHeader(item: unknown): ClaimedIntentHeader {\n\tconst intent = plain(item);\n\tconst lease = plain(raw(intent, \"lease\"));\n\treturn freeze({\n\t\tdeliveryId: nonEmpty(raw(intent, \"deliveryId\")),\n\t\ttenantId: nonEmpty(raw(intent, \"tenantId\")),\n\t\tspaceId: nonEmpty(raw(intent, \"spaceId\")),\n\t\tlease: freeze({ owner: nonEmpty(raw(lease, \"owner\")), fence: whole(raw(lease, \"fence\"), 0) }),\n\t});\n}\n\nfunction readIntentBody(item: unknown, header: ClaimedIntentHeader): ClaimedIntent {\n\tconst intent = plain(item);\n\tconst body = raw(intent, \"body\");\n\tif (typeof body !== \"string\") throw REFUSED;\n\tconst eventId = nonEmpty(raw(intent, \"eventId\"));\n\tconst attemptCount = whole(raw(intent, \"attemptCount\"), 0);\n\t// An intent whose ids cannot go into the unsigned headers can never be\n\t// sent; refusing it here keeps a header error from being blamed on the signer.\n\tbuildWebhookRequestHeaders({ signature: PLACEHOLDER_SIGNATURE, timestampSeconds: 0, eventId, deliveryId: header.deliveryId, attempt: attemptCount + 1 });\n\treturn freeze({\n\t\t...header,\n\t\tsubscriptionId: nonEmpty(raw(intent, \"subscriptionId\")),\n\t\teventId,\n\t\teligibilityRevision: whole(raw(intent, \"eligibilityRevision\"), 1),\n\t\tbody,\n\t\tattemptCount,\n\t\tprocessingDeadlineMs: instantMs(raw(intent, \"processingDeadline\")),\n\t\tleaseExpiresAtMs: instantMs(raw(plain(raw(intent, \"lease\")), \"expiresAt\")),\n\t});\n}\n\n/**\n * The claim result: `undefined` when the list itself cannot be read, and\n * otherwise one {@link ClaimedIntentEntry} per record. Each record's header\n * is read first, in its own try/catch, and its body after, in another.\n */\nexport function readClaimedIntents(value: unknown): readonly ClaimedIntentEntry[] | undefined {\n\tconst items: unknown[] = [];\n\ttry {\n\t\tif (!isArray(value)) return undefined;\n\t\tconst length = raw(value, \"length\");\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 0 || length > MAX_CLAIMED) return undefined;\n\t\tfor (let index = 0; index < length; index += 1) items.push(raw(value, `${index}`));\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn frozenList(items.map((item): ClaimedIntentEntry => {\n\t\tlet header: ClaimedIntentHeader;\n\t\ttry {\n\t\t\theader = readIntentHeader(item);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\treturn freeze({ header, intent: readIntentBody(item, header) });\n\t\t} catch {\n\t\t\treturn freeze({ header, intent: undefined });\n\t\t}\n\t}));\n}\n\n// ---------------------------------------------------------------------------\n// Subscription state\n// ---------------------------------------------------------------------------\n\n/** The delivery configuration the cycle signs and addresses one attempt with. */\nexport interface DispatchConfiguration {\n\treadonly version: number;\n\treadonly destinationUrl: string;\n\treadonly signatureScheme: \"v1\";\n\treadonly secretRef: string;\n}\n\n/**\n * What a `readSubscription` answer means for one intent.\n * `not_in_scope`: `null` (no such subscription in the intent's tenant and\n * space), or an answer naming another subscription, tenant or space.\n * `unreadable`: anything else that is not a well-formed snapshot, a\n * missing or malformed `statusSinceRevision` included.\n */\nexport type SubscriptionRead =\n\t| {\n\t\treadonly kind: \"ok\";\n\t\treadonly status: WebhookSubscriptionStatus;\n\t\t/** The snapshot's `statusSinceRevision`, read from the same answer as `status`. */\n\t\treadonly statusSinceRevision: number;\n\t\treadonly configuration: DispatchConfiguration;\n\t}\n\t| { readonly kind: \"not_in_scope\" }\n\t| { readonly kind: \"unreadable\" };\n\nconst STATUSES = freeze([\"active\", \"paused\", \"deleted\"] as const);\nconst NOT_IN_SCOPE: SubscriptionRead = freeze({ kind: \"not_in_scope\" });\nconst UNREADABLE: SubscriptionRead = freeze({ kind: \"unreadable\" });\n\n/**\n * Read a `readSubscription` answer for the intent `owner`. The snapshot and\n * its configuration must both name the intent's subscription, tenant and\n * space (decision 9: the worker refuses an intent whose subscription now\n * names another tenant or space).\n */\nexport function readSubscriptionFor(value: unknown, owner: { readonly subscriptionId: string; readonly tenantId: string; readonly spaceId: string }): SubscriptionRead {\n\ttry {\n\t\tif (value === null) return NOT_IN_SCOPE;\n\t\tconst snapshot = plain(value);\n\t\tconst configuration = plain(raw(snapshot, \"configuration\"));\n\t\tconst named = [raw(snapshot, \"subscriptionId\"), raw(snapshot, \"tenantId\"), raw(snapshot, \"spaceId\"),\n\t\t\traw(configuration, \"subscriptionId\"), raw(configuration, \"tenantId\"), raw(configuration, \"spaceId\")];\n\t\tfor (const name of named) nonEmpty(name);\n\t\tif (named[0] !== owner.subscriptionId || named[1] !== owner.tenantId || named[2] !== owner.spaceId\n\t\t\t|| named[3] !== owner.subscriptionId || named[4] !== owner.tenantId || named[5] !== owner.spaceId) {\n\t\t\treturn NOT_IN_SCOPE;\n\t\t}\n\t\tconst status = raw(snapshot, \"status\");\n\t\tif (!isOneOf(STATUSES, status)) return UNREADABLE;\n\t\tif (raw(configuration, \"signatureScheme\") !== \"v1\") return UNREADABLE;\n\t\treturn freeze({\n\t\t\tkind: \"ok\",\n\t\t\tstatus: status as WebhookSubscriptionStatus,\n\t\t\tstatusSinceRevision: whole(raw(snapshot, \"statusSinceRevision\"), 1),\n\t\t\tconfiguration: freeze({\n\t\t\t\tversion: whole(raw(configuration, \"version\"), 1),\n\t\t\t\tdestinationUrl: nonEmpty(raw(configuration, \"destinationUrl\")),\n\t\t\t\tsignatureScheme: \"v1\" as const,\n\t\t\t\tsecretRef: nonEmpty(raw(configuration, \"secretRef\")),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn UNREADABLE;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Destination, signature and transport results\n// ---------------------------------------------------------------------------\n\n/** A resolver answer copied into package-owned frozen values. */\nexport type ResolutionRead =\n\t| { readonly ok: true; readonly destination: WebhookVettedDestination }\n\t| { readonly ok: false; readonly code: \"invalid_url\" | \"private_address\" | \"dns_failure\" };\n\nconst RESOLUTION_CODES = freeze([\"invalid_url\", \"private_address\", \"dns_failure\"] as const);\n/** The most addresses a destination may carry (the resolver's own cap). */\nconst MAX_ADDRESSES = 32;\n\n/** A resolver answer, or `undefined` when it cannot be read. */\nexport function readResolution(value: unknown): ResolutionRead | undefined {\n\ttry {\n\t\tconst answer = plain(value);\n\t\tconst ok = raw(answer, \"ok\");\n\t\tif (ok === false) {\n\t\t\tconst code = raw(answer, \"code\");\n\t\t\treturn isOneOf(RESOLUTION_CODES, code) ? freeze({ ok: false as const, code: code as \"invalid_url\" | \"private_address\" | \"dns_failure\" }) : undefined;\n\t\t}\n\t\tif (ok !== true) return undefined;\n\t\tconst destination = plain(raw(answer, \"destination\"));\n\t\tif (raw(destination, \"port\") !== 443) return undefined;\n\t\tconst list = raw(destination, \"addresses\");\n\t\tif (!isArray(list)) return undefined;\n\t\tconst length = raw(list, \"length\");\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > MAX_ADDRESSES) return undefined;\n\t\tconst addresses: WebhookResolvedAddress[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst item = plain(raw(list, `${index}`));\n\t\t\tconst family = raw(item, \"family\");\n\t\t\tif (family !== 4 && family !== 6) return undefined;\n\t\t\taddresses.push(record({ address: nonEmpty(raw(item, \"address\")), family }));\n\t\t}\n\t\treturn freeze({\n\t\t\tok: true as const,\n\t\t\tdestination: record<WebhookVettedDestination>({\n\t\t\t\turl: nonEmpty(raw(destination, \"url\")),\n\t\t\t\thostname: nonEmpty(raw(destination, \"hostname\")),\n\t\t\t\tport: 443,\n\t\t\t\taddresses: frozenList(addresses),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Longer than any receipt a package store makes (69 characters); a longer one is not a receipt. */\nconst MAX_RECEIPT_LENGTH = 256;\n\n/**\n * A `beginAttempt` answer: `{ begun: true, receipt }` with a non-empty\n * receipt, `{ begun: false }`, or `undefined` when it is neither. Only a\n * well-formed `begun: true` lets the cycle hand off.\n */\nexport function readBeginAnswer(value: unknown): { readonly begun: true; readonly receipt: string } | { readonly begun: false } | undefined {\n\ttry {\n\t\tconst answer = plain(value);\n\t\tconst begun = raw(answer, \"begun\");\n\t\tif (begun === false) return freeze({ begun: false as const });\n\t\tif (begun !== true) return undefined;\n\t\tconst receipt = nonEmpty(raw(answer, \"receipt\"));\n\t\treturn receipt.length > MAX_RECEIPT_LENGTH ? undefined : freeze({ begun: true as const, receipt });\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** A signer answer: the string it returned, or `undefined`. Its format is checked when the headers are built. */\nexport function readSignature(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nconst OBSERVATION_KINDS = freeze([\"network_error\", \"timeout\", \"dns_failure\", \"invalid_url\", \"private_address\"] as const);\nconst NOT_SENT_REASONS = freeze([\"deadline_expired\", \"aborted\"] as const);\n/** Longer than any `Retry-After` the Node transport returns (128); a longer value is dropped, not truncated. */\nconst MAX_RETRY_AFTER_LENGTH = 256;\n\n/**\n * A transport answer copied into a package-owned frozen value, or\n * `undefined` when it cannot be read. Only `kind`, `status`, `retryAfter`\n * and a `not_sent` reason are read; anything else the transport put on its\n * answer, a response body included, is never read.\n */\nexport function readTransportResult(value: unknown): WebhookTransportResult | undefined {\n\ttry {\n\t\tconst answer = plain(value);\n\t\tconst kind = raw(answer, \"kind\");\n\t\tif (kind === \"response\") {\n\t\t\tconst status = raw(answer, \"status\");\n\t\t\tif (typeof status !== \"number\" || !numberIsSafeInteger(status) || status < 100 || status > 599) return undefined;\n\t\t\tconst retryAfter = raw(answer, \"retryAfter\");\n\t\t\tconst kept = typeof retryAfter === \"string\" && retryAfter.length <= MAX_RETRY_AFTER_LENGTH ? retryAfter : null;\n\t\t\treturn record<WebhookTransportResult>({ kind: \"response\", status, retryAfter: kept });\n\t\t}\n\t\tif (kind === \"not_sent\") {\n\t\t\tconst reason = raw(answer, \"reason\");\n\t\t\treturn isOneOf(NOT_SENT_REASONS, reason) ? record<WebhookTransportResult>({ kind: \"not_sent\", reason: reason as \"deadline_expired\" | \"aborted\" }) : undefined;\n\t\t}\n\t\tif (isOneOf(OBSERVATION_KINDS, kind)) return record<WebhookTransportResult>({ kind: kind as \"network_error\" });\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n","import { classifyWebhookDeliveryObservation, type WebhookDeliveryClassification, type WebhookDeliveryObservation } from \"./classify\";\nimport type { WebhookAttemptReasonCode, WebhookDiagnosticCode } from \"./codes\";\nimport { normalizeWebhookDeliveryAuthorizationDecision } from \"./decisions\";\nimport {\n\treadBeginAnswer,\n\treadClaimedIntents,\n\treadResolution,\n\treadSignature,\n\treadSubscriptionFor,\n\treadTransportResult,\n\ttype ClaimedIntent,\n\ttype ClaimedIntentHeader,\n\ttype DispatchConfiguration,\n} from \"./delivery-read\";\nimport { configError, deliveryError, guard } from \"./errors\";\nimport { boundedCall, signalAborted, type BoundedOutcome } from \"./fan-out-call\";\nimport { buildWebhookRequestHeaders } from \"./headers\";\nimport { assertPositiveInteger, resolveWebhookDeliveryLimits, type WebhookDeliveryLimits } from \"./limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookDeliveryAuthorization,\n\tWebhookDeliveryStore,\n\tWebhookDestinationResolver,\n\tWebhookRandomSource,\n\tWebhookRetryDelay,\n\tWebhookSigner,\n\tWebhookSubscriptionStore,\n\tWebhookTransport,\n\tWebhookTransportRequest,\n} from \"./ports\";\nimport { createWebhookRetryDelay } from \"./retry\";\nimport { apply, freeze, mathFloor, mathMax, mathMin, numberIsFinite, primitive, record, timeOf } from \"./snapshot\";\nimport { isoOf } from \"./store-input\";\n\n/*\n * The delivery cycle (ADR 0018 decisions 3, 4, 8 and 10; R2, R4, R6, R7).\n *\n * Check order. For each claimed intent, in this order:\n *\n * 0. The claim: a fenced lease, the intent's fence advanced (store).\n * Then the lease is renewed when less than one whole attempt is left\n * of it (`keepLease`): an intent late in a batch has waited for the\n * ones before it under a lease taken at the claim.\n * 1. Processing deadline, persisted when fan-out created the intent: no\n * call before the handoff (preparation and guard calls, `intentCall`)\n * is started at or after it, and the first call it refuses\n * dead-letters the intent `processing_deadline_exceeded`. Outcome,\n * settlement and attempt-log writes after a handoff are not held to it.\n * 2. `readSubscription` in the intent's tenant and space: not there, or\n * naming another subscription, tenant or space, dead-letters it\n * `subscription_not_in_scope`; paused or deleted cancels it, and so\n * does an active subscription whose `statusSinceRevision` is above the\n * intent's `eligibilityRevision` (paused and resumed since the intent's\n * interval: `subscription_paused`). Otherwise it yields the\n * configuration version `v` this attempt uses.\n * 3. Resolve `v`'s destination and sign the body with `v`'s secret\n * reference (preparation; a refused destination or a failed signer\n * spends an attempt, per decision 10's table, without sending).\n * 4. Guards, immediately before the handoff, with nothing between them but\n * clock reads:\n * a. delivery authorization for this attempt and `v`: revoked cancels,\n * unavailable releases unsent;\n * b. `readSubscription` again: paused, deleted, resumed since the\n * intent's revision or out of scope as in 2;\n * a configuration version other than `v` releases unsent as\n * `configuration_conflict`;\n * c. the transport's deadline: the clock now plus `attemptTimeoutMs`,\n * and at most 4b's start plus `portTimeoutMs + attemptTimeoutMs`,\n * the processing deadline, and the lease's expiry (as claimed or\n * renewed in step 0) less three `portTimeoutMs` (the answer's\n * grace, the outcome write, the settlement);\n * d. `beginAttempt`: in one atomic store step, the lease is still this\n * worker's at this fence and unexpired on the store's clock, and an\n * in-flight attempt entry is written for (deliveryId, fence). The\n * store returns a receipt that only this worker holds.\n * 5. Handoff: `transport.send()` with the signed request. This is the\n * irrevocable point. A change committed after 4b's read (a revocation,\n * a pause, a configuration replacement), or after 4d's begin (a\n * reclaim), may race with the request, which can then reach the old\n * destination with the old secret (R2, decision 3). The transport may\n * still answer `not_sent` when its deadline passed or its signal\n * aborted before it started the request (R3); that attempt is\n * recorded `not_sent` and the intent released.\n * 6. Classify (decision 10), append the attempt's outcome with the\n * receipt (not fenced, so a worker that lost its lease during the\n * request still records it, and nobody else can), then settle under\n * the fence: delivered, retry, dead letter. A settlement the store\n * refuses (lease expired or reclaimed) leaves the intent to be sent\n * again after a reclaim: delivery is at least once.\n *\n * Releases (deferrals) spend no attempt; every deferral, reclaim and\n * configuration conflict counts toward the persisted processing deadline\n * (R4). Each port call before the handoff is bounded by the smaller of\n * `portTimeoutMs` and the intent's remaining lifetime; the transport by its\n * deadline from 4c plus a `portTimeoutMs` grace for its answer; each\n * outcome, settlement and attempt write by `portTimeoutMs`. `boundedCall`\n * accepts no answer that settles at or after its bound, on the injected\n * clock or on the monotonic clock, timed when the port's promise settles,\n * so a late result is dropped and nothing is written from it.\n *\n * A store write that timed out may have committed. The cycle never follows\n * one with a second transition of the intent on the strength of the\n * timeout: a timed-out settlement ends the intent's processing\n * (`abandoned`); a timed-out `beginAttempt` is followed by a release (begin\n * does not change the intent, so the release is the only transition, and a\n * begin that did commit leaves an `in_flight` entry with no request behind\n * it); a timed-out `appendAttempt` is followed by a release, so the log may\n * hold an entry for an attempt that spent nothing, and the next pass logs\n * the same attempt number again.\n */\n\n/** One intent's outcome, as reported to {@link WebhookDeliveryCycleOptions.observe}. */\nexport type WebhookDeliveryCycleResultKind =\n\t| \"delivered\"\n\t| \"retry_scheduled\"\n\t| \"dead_lettered\"\n\t| \"cancelled\"\n\t| \"released\"\n\t| \"lease_lost\"\n\t| \"abandoned\";\n\n/**\n * What the cycle reports for one claimed intent. Every field is an\n * identifier the store already holds, a number, or a fixed code: never a\n * destination, secret reference, signature, header, body or port error.\n */\nexport interface WebhookDeliveryCycleEvent {\n\treadonly deliveryId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly subscriptionId?: string;\n\treadonly eventId?: string;\n\t/** The 1-based attempt number this processing was for. */\n\treadonly attempt?: number;\n\t/** The configuration version the attempt was prepared with, once read. */\n\treadonly configurationVersion?: number;\n\treadonly result: WebhookDeliveryCycleResultKind;\n\t/** `true` once the request was handed to the transport. */\n\treadonly handedOff: boolean;\n\treadonly reason?: WebhookAttemptReasonCode;\n\treadonly diagnostic?: WebhookDiagnosticCode;\n\treadonly httpStatus?: number;\n\t/** 401 or 403: still retried, but usually needing the receiver to act (decision 10). */\n\treadonly receiverActionLikely?: true;\n}\n\n/** Options for {@link runWebhookDeliveryCycle}. */\nexport interface WebhookDeliveryCycleOptions {\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly subscriptions: WebhookSubscriptionStore;\n\treadonly authorization: WebhookDeliveryAuthorization;\n\treadonly signer: WebhookSigner;\n\treadonly resolver: WebhookDestinationResolver;\n\treadonly transport: WebhookTransport;\n\treadonly clock: WebhookClock;\n\t/** The lease owner this worker claims intents as. */\n\treadonly workerId: string;\n\t/**\n\t * Overrides of {@link WebhookDeliveryLimits}, all validated positive and\n\t * finite (R4). Used: `maxDeliveryAttempts`, `deliveryRetryDelaysMs`,\n\t * `retryJitterRatio`, `attemptTimeoutMs`, `portTimeoutMs`, `maxRetryAfterMs`.\n\t */\n\treadonly limits?: Partial<WebhookDeliveryLimits>;\n\t/** Delay before the next attempt; defaults to `deliveryRetryDelaysMs` with jitter from `random`. */\n\treadonly retryDelay?: WebhookRetryDelay;\n\t/** Random source for the default retry delay's jitter; required when `retryDelay` is absent. */\n\treadonly random?: WebhookRandomSource;\n\t/** Intents claimed per cycle. A positive whole number; default 10. */\n\treadonly batchSize?: number;\n\t/**\n\t * Lease on each claimed intent, in ms. A positive whole number above\n\t * `attemptTimeoutMs + 10 * portTimeoutMs` (one whole attempt and the\n\t * renewal before it; see `ATTEMPT_PORT_CALLS`); default 120 000.\n\t */\n\treadonly leaseDurationMs?: number;\n\t/** Called once per claimed intent with fixed-code telemetry. A throw is ignored. */\n\treadonly observe?: (event: WebhookDeliveryCycleEvent) => void;\n\t/** Stops the cycle; intents not yet settled are reclaimed after their leases expire. */\n\treadonly signal?: AbortSignal;\n}\n\n/** What one cycle did. */\nexport interface WebhookDeliveryCycleResult {\n\treadonly claimed: number;\n\treadonly delivered: number;\n\t/** Settled for a later attempt, spending one. */\n\treadonly retried: number;\n\treadonly deadLettered: number;\n\treadonly cancelled: number;\n\t/** Returned to pending unsent, spending no attempt. */\n\treadonly released: number;\n\t/** Intents this worker stopped on because a fenced write found its lease gone. */\n\treadonly leaseLost: number;\n\t/** Intents left for lease expiry: unreadable, another owner's, or whose final write failed. */\n\treadonly abandoned: number;\n\t/** Requests handed to the transport. */\n\treadonly handedOff: number;\n}\n\n/**\n * What may follow the transport's deadline, in units of `portTimeoutMs`: the\n * grace the cycle waits for the transport's answer, then the outcome write\n * and the settlement, each bounded by `portTimeoutMs`. The transport's\n * deadline is kept this far inside the lease, so a request that answers in\n * time can be settled before the lease expires.\n */\nconst SETTLEMENT_WRITES = 3;\n\n/**\n * The port calls one attempt makes besides the transport, each bounded by\n * `portTimeoutMs`: before the handoff, `readSubscription`, the resolver, the\n * signer, authorization, `readSubscription` again and `beginAttempt` (6);\n * after it, the {@link SETTLEMENT_WRITES} (3). Each is cut off at its bound\n * by a timer, so one whole attempt takes about\n * `attemptTimeoutMs + ATTEMPT_PORT_CALLS * portTimeoutMs` at most, more\n * only when timers fire late.\n */\nconst ATTEMPT_PORT_CALLS = 6 + SETTLEMENT_WRITES;\n\n/** Defaults for the cycle's own options. */\nexport const DEFAULT_WEBHOOK_DELIVERY_CYCLE = freeze({\n\tbatchSize: 10,\n\tleaseDurationMs: 120_000,\n});\n\ninterface Clock {\n\treadonly target: object;\n\treadonly now: (...args: never[]) => unknown;\n}\n\ninterface Config {\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly subscriptions: WebhookSubscriptionStore;\n\treadonly authorization: WebhookDeliveryAuthorization;\n\treadonly signer: WebhookSigner;\n\treadonly resolver: WebhookDestinationResolver;\n\treadonly transport: WebhookTransport;\n\treadonly clock: Clock;\n\treadonly workerId: string;\n\treadonly limits: WebhookDeliveryLimits;\n\treadonly retryDelay: WebhookRetryDelay;\n\treadonly batchSize: number;\n\treadonly leaseDurationMs: number;\n\treadonly observe: ((event: WebhookDeliveryCycleEvent) => void) | undefined;\n\treadonly signal: AbortSignal | undefined;\n}\n\nfunction hasMethods(value: unknown, names: readonly string[]): boolean {\n\tif (value === null || typeof value !== \"object\") return false;\n\tfor (const name of names) if (typeof (value as Record<string, unknown>)[name] !== \"function\") return false;\n\treturn true;\n}\n\nfunction positiveWhole(value: unknown, fallback: number, field: string): number {\n\tconst read = primitive(value);\n\tconst resolved = read === undefined ? fallback : read;\n\tassertPositiveInteger(resolved, field);\n\treturn resolved;\n}\n\n/**\n * Read and validate the options. A package error (a limit, a missing random\n * source) passes through with its code; anything else thrown while reading\n * them, by a getter or a Proxy trap, is replaced unread with `options_invalid`.\n */\nfunction readConfig(options: WebhookDeliveryCycleOptions): Config {\n\treturn guard(() => readConfigUnguarded(options), () => deliveryError(\"options_invalid\", \"options\"));\n}\n\nfunction readConfigUnguarded(options: WebhookDeliveryCycleOptions): Config {\n\tif (options === null || typeof options !== \"object\") throw deliveryError(\"options_invalid\", \"options\");\n\tconst limits = resolveWebhookDeliveryLimits(options.limits ?? {});\n\tconst batchSize = positiveWhole(options.batchSize, DEFAULT_WEBHOOK_DELIVERY_CYCLE.batchSize, \"batchSize\");\n\tconst leaseDurationMs = positiveWhole(options.leaseDurationMs, DEFAULT_WEBHOOK_DELIVERY_CYCLE.leaseDurationMs, \"leaseDurationMs\");\n\t// The lease must fit one whole attempt (the calls before the handoff, the\n\t// transport call, its answer's grace, and the outcome and settlement\n\t// writes) after the renewal that precedes it; a shorter one would leave\n\t// an intent too little lease to hand off, on every claim.\n\tif (leaseDurationMs <= limits.attemptTimeoutMs + (ATTEMPT_PORT_CALLS + 1) * limits.portTimeoutMs) throw configError(\"limit_out_of_range\", \"leaseDurationMs\");\n\tif (!hasMethods(options.deliveries, [\"claimDeliveryIntents\", \"renewDeliveryIntentLease\", \"beginAttempt\", \"finishAttempt\", \"appendAttempt\", \"settleDeliveryIntent\"])) {\n\t\tthrow deliveryError(\"options_invalid\", \"deliveries\");\n\t}\n\tif (!hasMethods(options.subscriptions, [\"readSubscription\"])) throw deliveryError(\"options_invalid\", \"subscriptions\");\n\tif (!hasMethods(options.authorization, [\"authorize\"])) throw deliveryError(\"options_invalid\", \"authorization\");\n\tif (!hasMethods(options.signer, [\"sign\"])) throw deliveryError(\"options_invalid\", \"signer\");\n\tif (!hasMethods(options.resolver, [\"resolve\"])) throw deliveryError(\"options_invalid\", \"resolver\");\n\tif (!hasMethods(options.transport, [\"send\"])) throw deliveryError(\"options_invalid\", \"transport\");\n\tif (typeof options.workerId !== \"string\" || options.workerId === \"\") throw deliveryError(\"options_invalid\", \"workerId\");\n\tif (options.observe !== undefined && typeof options.observe !== \"function\") throw deliveryError(\"options_invalid\", \"observe\");\n\tif (options.signal !== undefined && !(options.signal instanceof AbortSignal)) throw deliveryError(\"options_invalid\", \"signal\");\n\tconst clock = options.clock as unknown;\n\tif (clock === null || typeof clock !== \"object\") throw deliveryError(\"options_invalid\", \"clock\");\n\tconst now = (clock as { now?: unknown }).now;\n\tif (typeof now !== \"function\") throw deliveryError(\"options_invalid\", \"clock.now\");\n\tlet retryDelay: WebhookRetryDelay;\n\tif (options.retryDelay !== undefined) {\n\t\tif (typeof options.retryDelay !== \"function\") throw deliveryError(\"options_invalid\", \"retryDelay\");\n\t\tretryDelay = options.retryDelay;\n\t} else {\n\t\tretryDelay = createWebhookRetryDelay({ delaysMs: limits.deliveryRetryDelaysMs, jitterRatio: limits.retryJitterRatio, random: options.random! });\n\t}\n\treturn freeze({\n\t\tdeliveries: options.deliveries,\n\t\tsubscriptions: options.subscriptions,\n\t\tauthorization: options.authorization,\n\t\tsigner: options.signer,\n\t\tresolver: options.resolver,\n\t\ttransport: options.transport,\n\t\tclock: freeze({ target: clock, now: now as (...args: never[]) => unknown }),\n\t\tworkerId: options.workerId,\n\t\tlimits,\n\t\tretryDelay,\n\t\tbatchSize,\n\t\tleaseDurationMs,\n\t\tobserve: options.observe,\n\t\tsignal: options.signal,\n\t});\n}\n\n/** Read the clock; a throw or an invalid time is `clock_invalid`. */\nfunction readClock(clock: Clock): number {\n\tlet value: unknown;\n\ttry {\n\t\tvalue = apply(clock.now, clock.target, []);\n\t} catch {\n\t\tthrow deliveryError(\"clock_invalid\", \"clock\");\n\t}\n\tconst ms = timeOf(value);\n\tif (!numberIsFinite(ms)) throw deliveryError(\"clock_invalid\", \"clock\");\n\treturn ms;\n}\n\ninterface Counters {\n\tclaimed: number;\n\tdelivered: number;\n\tretried: number;\n\tdeadLettered: number;\n\tcancelled: number;\n\treleased: number;\n\tleaseLost: number;\n\tabandoned: number;\n\thandedOff: number;\n}\n\n/**\n * Run one delivery cycle: claim up to `batchSize` pending intents under a\n * fenced lease and process each in turn, in the check order described at\n * the top of this file (and in the README, \"Delivery\"). A claimed record\n * whose `deliveryId`, `tenantId`, `spaceId` or lease cannot be read, or\n * that is leased to another owner, is left for lease expiry (`abandoned`);\n * one whose identity and lease can be read but whose body cannot is\n * dead-lettered as `intent_unreadable`.\n *\n * @throws {WebhookDeliveryConfigError} for a limit or cycle option that is not positive and finite (R4).\n * @throws {WebhookDeliveryError} `options_invalid` for a missing port or\n * option; `delivery_store_failed` or `delivery_store_timeout` when the claim\n * fails; `clock_invalid` for a failing clock.\n */\nexport async function runWebhookDeliveryCycle(options: WebhookDeliveryCycleOptions): Promise<WebhookDeliveryCycleResult> {\n\tconst config = readConfig(options);\n\tconst counters: Counters = { claimed: 0, delivered: 0, retried: 0, deadLettered: 0, cancelled: 0, released: 0, leaseLost: 0, abandoned: 0, handedOff: 0 };\n\tconst nowMs = readClock(config.clock);\n\tconst claimed = await boundedCall(nowMs, config.limits.portTimeoutMs, config.signal, (callOptions) => config.deliveries.claimDeliveryIntents({\n\t\tworkerId: config.workerId,\n\t\tleaseDurationMs: config.leaseDurationMs,\n\t\tlimit: config.batchSize,\n\t\tnow: new Date(nowMs),\n\t}, callOptions), () => readClock(config.clock));\n\tif (!claimed.ok) throw deliveryError(claimed.reason === \"timeout\" ? \"delivery_store_timeout\" : \"delivery_store_failed\", \"claimDeliveryIntents\");\n\tconst entries = readClaimedIntents(claimed.value);\n\tif (entries === undefined) throw deliveryError(\"delivery_store_failed\", \"claimDeliveryIntents\");\n\tcounters.claimed = entries.length;\n\tfor (const entry of entries) {\n\t\tif (config.signal !== undefined && signalAborted(config.signal)) break;\n\t\t// A record whose identity or lease cannot be read cannot be named by a\n\t\t// fenced write, and one leased to another owner is not this worker's.\n\t\tif (entry === undefined) {\n\t\t\tcounters.abandoned += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst run = newRun(config, entry.header, entry.intent, counters);\n\t\tif (entry.header.lease.owner !== config.workerId) {\n\t\t\tfinish(run, \"abandoned\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.intent === undefined) {\n\t\t\tawait settle(run, { kind: \"dead_letter\", reason: \"intent_unreadable\" }, \"dead_lettered\", { diagnostic: \"intent_unreadable\" });\n\t\t\tcontinue;\n\t\t}\n\t\tawait processIntent(run, entry.intent);\n\t}\n\treturn freeze({ ...counters });\n}\n\n/** One claimed intent being processed. */\ninterface Run {\n\treadonly config: Config;\n\treadonly header: ClaimedIntentHeader;\n\treadonly intent: ClaimedIntent | undefined;\n\treadonly counters: Counters;\n\t/** The configuration version read at step 2, once read. */\n\tversion: number | undefined;\n\t/** The lease's expiry as this worker last set it (claim or renewal), on its own clock. */\n\tleaseExpiresAtMs: number;\n\thandedOff: boolean;\n\treported: boolean;\n}\n\nfunction newRun(config: Config, header: ClaimedIntentHeader, intent: ClaimedIntent | undefined, counters: Counters): Run {\n\treturn { config, header, intent, counters, version: undefined, leaseExpiresAtMs: intent === undefined ? NaN : intent.leaseExpiresAtMs, handedOff: false, reported: false };\n}\n\ntype CallFailure = \"threw\" | \"timeout\" | \"aborted\" | \"deadline\";\ntype RunOutcome<T> = BoundedOutcome<T> | { readonly ok: false; readonly reason: \"deadline\" };\n\n/**\n * A port call made before the handoff (R4). It is not made at all once the\n * intent's processing deadline has passed, and otherwise it is bounded by\n * the smaller of `portTimeoutMs` and the intent's remaining lifetime.\n */\nfunction intentCall<T>(run: Run, intent: ClaimedIntent, call: (options: WebhookCallOptions, nowMs: number) => Promise<T>): Promise<RunOutcome<T>> {\n\tconst nowMs = readClock(run.config.clock);\n\tconst remainingMs = intent.processingDeadlineMs - nowMs;\n\tif (!(remainingMs > 0)) return Promise.resolve({ ok: false, reason: \"deadline\" });\n\tconst timeoutMs = mathMin(remainingMs, run.config.limits.portTimeoutMs);\n\treturn boundedCall(nowMs, timeoutMs, run.config.signal, (options) => call(options, nowMs), () => readClock(run.config.clock));\n}\n\n/** A settlement or attempt write: bounded by `portTimeoutMs` alone, so an outcome can be recorded after the deadline. */\nfunction storeWrite<T>(run: Run, call: (options: WebhookCallOptions, nowMs: number) => Promise<T>): Promise<BoundedOutcome<T>> {\n\tconst nowMs = readClock(run.config.clock);\n\treturn boundedCall(nowMs, run.config.limits.portTimeoutMs, run.config.signal, (options) => call(options, nowMs), () => readClock(run.config.clock));\n}\n\n/**\n * Step 0: make sure one whole attempt fits in what is left of the lease,\n * renewing it when it does not. Returns `false` when the intent is done\n * for this cycle: the store refused the renewal (the lease is gone, and\n * nothing more is written) or the cycle's signal aborted. A renewal whose\n * outcome is unknown (it threw, timed out or answered unreadably) is not a\n * refusal: the intent goes ahead under the lease last known, and the\n * transport deadline's lease cap (4c) and the store's fence check bound it.\n * The store never extends a lease past the processing deadline; an intent\n * past it is dead-lettered by its first guard call.\n */\nasync function keepLease(run: Run, intent: ClaimedIntent): Promise<boolean> {\n\tconst { config } = run;\n\tconst { attemptTimeoutMs, portTimeoutMs } = config.limits;\n\tconst nowMs = readClock(config.clock);\n\tif (run.leaseExpiresAtMs - nowMs >= attemptTimeoutMs + ATTEMPT_PORT_CALLS * portTimeoutMs) return true;\n\tlet askedAtMs = nowMs;\n\tconst renewed = await storeWrite(run, (options, callNowMs) => {\n\t\taskedAtMs = callNowMs;\n\t\treturn config.deliveries.renewDeliveryIntentLease({\n\t\t\tdeliveryId: intent.deliveryId,\n\t\t\towner: intent.lease.owner,\n\t\t\tfence: intent.lease.fence,\n\t\t\tnow: new Date(callNowMs),\n\t\t\tleaseDurationMs: config.leaseDurationMs,\n\t\t}, options);\n\t});\n\tif (renewed.ok && renewed.value === true) {\n\t\t// The store's rule: never shorter than before, never past the processing deadline.\n\t\tconst untilMs = mathMin(askedAtMs + config.leaseDurationMs, intent.processingDeadlineMs);\n\t\tif (untilMs > run.leaseExpiresAtMs) run.leaseExpiresAtMs = untilMs;\n\t\treturn true;\n\t}\n\tif (renewed.ok && renewed.value === false) {\n\t\tfinish(run, \"lease_lost\", { diagnostic: \"lease_lost\" });\n\t\treturn false;\n\t}\n\tif (!renewed.ok && renewed.reason === \"aborted\") {\n\t\tfinish(run, \"abandoned\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nasync function processIntent(run: Run, intent: ClaimedIntent): Promise<void> {\n\tconst { config } = run;\n\tconst attempt = intent.attemptCount + 1;\n\n\t// 0. Enough lease for one whole attempt, renewed if need be.\n\tif (!(await keepLease(run, intent))) return;\n\n\t// 1. The processing deadline persisted at creation (R4) is checked on every\n\t// claim by `intentCall`: no port call is made at or after it, and the first\n\t// refusal dead-letters the intent.\n\n\t// 2. Subscription state, scope and the configuration this attempt uses.\n\tconst first = await readState(run, intent);\n\tif (first === undefined) return;\n\tconst configuration = first.configuration;\n\trun.version = configuration.version;\n\n\t// 3a. Destination for that configuration.\n\tconst resolved = await intentCall(run, intent, (options) => config.resolver.resolve(configuration.destinationUrl, options));\n\tif (!resolved.ok) return portFailure(run, resolved.reason, \"resolver_unavailable\");\n\tconst resolution = readResolution(resolved.value);\n\tif (resolution === undefined) return release(run, intent, \"resolver_unavailable\");\n\tif (!resolution.ok) return spendUnsent(run, intent, { kind: resolution.code });\n\n\t// 3b. Sign this attempt with that configuration's secret reference (decision 7: per attempt, at send time).\n\tconst timestampSeconds = mathFloor(readClock(config.clock) / 1_000);\n\tconst signed = await intentCall(run, intent, (options) => config.signer.sign({\n\t\tscheme: configuration.signatureScheme,\n\t\tsecretRef: configuration.secretRef,\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\ttimestampSeconds,\n\t\trawBody: intent.body,\n\t}, options));\n\tif (!signed.ok && (signed.reason === \"deadline\" || signed.reason === \"aborted\")) return portFailure(run, signed.reason, \"signer_unavailable\");\n\tlet headers: Readonly<Record<string, string>> | undefined;\n\ttry {\n\t\t// A malformed signature is refused here rather than sent (headers.ts).\n\t\theaders = signed.ok\n\t\t\t? buildWebhookRequestHeaders({ signature: readSignature(signed.value)!, timestampSeconds, eventId: intent.eventId, deliveryId: intent.deliveryId, attempt })\n\t\t\t: undefined;\n\t} catch {\n\t\theaders = undefined;\n\t}\n\tif (headers === undefined) return spendUnsent(run, intent, { kind: \"signer_unavailable\" });\n\n\t// 4a. Guard: delivery authorization for this attempt (decision 4).\n\tconst authorized = await intentCall(run, intent, (options) => config.authorization.authorize({\n\t\tsubscriptionId: intent.subscriptionId,\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\teventId: intent.eventId,\n\t\tdeliveryId: intent.deliveryId,\n\t\tconfigurationVersion: configuration.version,\n\t\tattempt,\n\t}, options));\n\tif (!authorized.ok) return portFailure(run, authorized.reason, \"authorization_unavailable\");\n\tconst decision = normalizeWebhookDeliveryAuthorizationDecision(authorized.value);\n\tif (decision.decision === \"revoked\") return cancel(run, \"authorization_revoked\");\n\tif (decision.decision === \"unavailable\") return release(run, intent, \"authorization_unavailable\");\n\n\t// 4b. Guard: subscription state and configuration version, re-read (decision 3).\n\tconst second = await readState(run, intent);\n\tif (second === undefined) return;\n\tif (second.configuration.version !== configuration.version) return release(run, intent, \"configuration_conflict\");\n\n\t// 4c. The transport's deadline: the clock now plus `attemptTimeoutMs`, and\n\t// never later than the guard read's start plus `portTimeoutMs +\n\t// attemptTimeoutMs` (the old-secret retention bound, R6, holds even when a\n\t// continuation runs late), the processing deadline, or the lease's expiry\n\t// (as last claimed or renewed, step 0) less the answer's grace and the outcome and settlement writes, so a\n\t// request that answers in time can still be settled under the lease. (The\n\t// processing deadline itself is checked again by `intentCall` below.)\n\tconst { attemptTimeoutMs, portTimeoutMs } = config.limits;\n\tconst sendDeadlineMs = mathMin(\n\t\treadClock(config.clock) + attemptTimeoutMs,\n\t\tsecond.startedMs + portTimeoutMs + attemptTimeoutMs,\n\t\tintent.processingDeadlineMs,\n\t\trun.leaseExpiresAtMs - SETTLEMENT_WRITES * portTimeoutMs,\n\t);\n\n\t// 4d. Guard: the lease, checked and the attempt recorded in one atomic store step.\n\tconst begun = await intentCall(run, intent, (options, nowMs) => config.deliveries.beginAttempt({\n\t\towner: intent.lease.owner,\n\t\tfence: intent.lease.fence,\n\t\tnow: new Date(nowMs),\n\t\tattempt: {\n\t\t\tdeliveryId: intent.deliveryId,\n\t\t\tsubscriptionId: intent.subscriptionId,\n\t\t\teventId: intent.eventId,\n\t\t\tattempt,\n\t\t\tconfigurationVersion: configuration.version,\n\t\t\tstartedAt: isoOf(nowMs),\n\t\t},\n\t}, options));\n\tif (!begun.ok) return portFailure(run, begun.reason, \"delivery_store_unavailable\");\n\tconst answer = readBeginAnswer(begun.value);\n\tif (answer === undefined) return release(run, intent, \"delivery_store_unavailable\");\n\tif (!answer.begun) return finish(run, \"lease_lost\", { diagnostic: \"lease_lost\" });\n\t// The proof that this worker began the attempt: kept here only, never logged or reported.\n\tconst receipt = answer.receipt;\n\n\t// 5. The handoff: the irrevocable point. Nothing is awaited between the\n\t// begin above and this call except the clock read.\n\tconst request: WebhookTransportRequest = record({ destination: resolution.destination, method: \"POST\" as const, headers, body: intent.body });\n\tconst handoffMs = readClock(config.clock);\n\tconst timeoutMs = sendDeadlineMs - handoffMs;\n\tlet observation: WebhookDeliveryObservation;\n\tif (!(timeoutMs > 0)) {\n\t\t// Expired before the handoff: the transport would refuse it (R3), so it is not called.\n\t\treturn notSent(run, intent, receipt);\n\t}\n\trun.handedOff = true;\n\trun.counters.handedOff += 1;\n\tconst sent = await boundedCall(handoffMs, timeoutMs, config.signal, (options) => config.transport.send(request, options), () => readClock(config.clock), portTimeoutMs);\n\tif (!sent.ok && sent.reason === \"aborted\") return finish(run, \"abandoned\");\n\tif (!sent.ok) {\n\t\t// A throw or no answer by the deadline: the request may have been sent.\n\t\tobservation = { kind: sent.reason === \"timeout\" ? \"timeout\" : \"network_error\" };\n\t} else {\n\t\tconst result = readTransportResult(sent.value);\n\t\tif (result !== undefined && result.kind === \"not_sent\") return notSent(run, intent, receipt);\n\t\tobservation = result === undefined ? { kind: \"network_error\" } : result;\n\t}\n\n\t// 6. Classify, record the outcome (unfenced, with the receipt), settle\n\t// (fenced). The outcome is written first: if the settlement is refused\n\t// because the lease expired or was reclaimed, the attempt and what it\n\t// observed are still on record, and the intent is sent again after it is\n\t// reclaimed (at least once; receivers deduplicate by deliveryId).\n\tconst finishedMs = readClock(config.clock);\n\tlet classification: WebhookDeliveryClassification;\n\ttry {\n\t\tclassification = classifyWebhookDeliveryObservation(observation, { now: new Date(finishedMs), maxRetryAfterMs: config.limits.maxRetryAfterMs });\n\t} catch {\n\t\tclassification = record({ outcome: \"retryable\" as const, reason: \"network_error\" as const });\n\t}\n\tawait storeWrite(run, (options) => config.deliveries.finishAttempt({\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\tdeliveryId: intent.deliveryId,\n\t\tfence: intent.lease.fence,\n\t\treceipt,\n\t\tfinish: {\n\t\t\tfinishedAt: isoOf(finishedMs),\n\t\t\toutcome: classification.outcome,\n\t\t\treason: classification.reason,\n\t\t\t...(classification.httpStatus === undefined ? {} : { httpStatus: classification.httpStatus }),\n\t\t},\n\t}, options));\n\treturn applyClassification(run, intent, classification);\n}\n\n/**\n * Steps 2 and 4b: the subscription's state for this intent. Returns the\n * configuration when the subscription is active, in scope, and has been\n * active since the intent's eligibility revision or earlier; otherwise\n * settles the intent and returns `undefined`.\n */\nasync function readState(run: Run, intent: ClaimedIntent): Promise<{ readonly configuration: DispatchConfiguration; readonly startedMs: number } | undefined> {\n\tlet startedMs = Number.NaN;\n\tconst answer = await intentCall(run, intent, (options, nowMs) => {\n\t\tstartedMs = nowMs;\n\t\treturn run.config.subscriptions.readSubscription(\n\t\t\t{ tenantId: intent.tenantId, spaceId: intent.spaceId, subscriptionId: intent.subscriptionId },\n\t\t\toptions,\n\t\t);\n\t});\n\tif (!answer.ok) {\n\t\tawait portFailure(run, answer.reason, \"subscription_store_unavailable\");\n\t\treturn undefined;\n\t}\n\tconst state = readSubscriptionFor(answer.value, intent);\n\tif (state.kind === \"not_in_scope\") {\n\t\tawait deadLetter(run, \"subscription_not_in_scope\");\n\t\treturn undefined;\n\t}\n\tif (state.kind === \"unreadable\") {\n\t\tawait release(run, intent, \"subscription_store_unavailable\");\n\t\treturn undefined;\n\t}\n\tif (state.status === \"paused\") {\n\t\tawait cancel(run, \"subscription_paused\");\n\t\treturn undefined;\n\t}\n\tif (state.status === \"deleted\") {\n\t\tawait cancel(run, \"subscription_deleted\");\n\t\treturn undefined;\n\t}\n\t// Active, but since a revision later than the intent's: a pause ended the\n\t// intent's interval and a resume began a new one, which does not reopen\n\t// it (decision 3). This holds whatever the pause's `cancelPendingIntents`\n\t// did, and for intents fan-out wrote after it ran.\n\tif (intent.eligibilityRevision < state.statusSinceRevision) {\n\t\tawait cancel(run, \"subscription_paused\");\n\t\treturn undefined;\n\t}\n\treturn { configuration: state.configuration, startedMs };\n}\n\n/** A pre-handoff port call that did not answer: past the deadline, aborted, timed out or threw. */\nfunction portFailure(run: Run, reason: CallFailure, unavailable: WebhookDiagnosticCode): Promise<void> {\n\tif (reason === \"deadline\") return deadLetter(run, \"processing_deadline_exceeded\");\n\tif (reason === \"aborted\") {\n\t\tfinish(run, \"abandoned\");\n\t\treturn Promise.resolve();\n\t}\n\treturn release(run, run.intent!, reason === \"timeout\" ? \"port_timeout\" : unavailable);\n}\n\n/**\n * Decision 10 rows that end an attempt before the transport is reached (a\n * refused destination, a failed signer): logged as a complete attempt\n * under the lease, then settled. If the log write fails, nothing is spent:\n * the intent is released instead, so every spent attempt has a log entry.\n * A log write that timed out may still have committed; the release then\n * leaves an entry for an attempt that spent nothing (see the top of this\n * file).\n */\nasync function spendUnsent(run: Run, intent: ClaimedIntent, observation: WebhookDeliveryObservation): Promise<void> {\n\tconst nowMs = readClock(run.config.clock);\n\tconst classification = classifyWebhookDeliveryObservation(observation, { now: new Date(nowMs), maxRetryAfterMs: run.config.limits.maxRetryAfterMs });\n\tconst logged = await storeWrite(run, (options) => run.config.deliveries.appendAttempt({\n\t\towner: intent.lease.owner,\n\t\tfence: intent.lease.fence,\n\t\tnow: new Date(nowMs),\n\t\tattempt: {\n\t\t\tdeliveryId: intent.deliveryId,\n\t\t\tsubscriptionId: intent.subscriptionId,\n\t\t\teventId: intent.eventId,\n\t\t\tattempt: intent.attemptCount + 1,\n\t\t\tconfigurationVersion: run.version!,\n\t\t\tstartedAt: isoOf(nowMs),\n\t\t\tfinishedAt: isoOf(nowMs),\n\t\t\toutcome: classification.outcome,\n\t\t\treason: classification.reason,\n\t\t},\n\t}, options));\n\tif (logged.ok && logged.value === false) return finish(run, \"lease_lost\", { diagnostic: \"lease_lost\" });\n\tif (!logged.ok && logged.reason === \"aborted\") return finish(run, \"abandoned\");\n\tif (!logged.ok || logged.value !== true) return release(run, intent, logged.ok ? \"delivery_store_unavailable\" : logged.reason === \"timeout\" ? \"port_timeout\" : \"delivery_store_unavailable\");\n\treturn applyClassification(run, intent, classification);\n}\n\n/** The transport never started the request: record it `not_sent` and release, spending nothing. */\nasync function notSent(run: Run, intent: ClaimedIntent, receipt: string): Promise<void> {\n\tconst nowMs = readClock(run.config.clock);\n\tawait storeWrite(run, (options) => run.config.deliveries.finishAttempt({\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\tdeliveryId: intent.deliveryId,\n\t\tfence: intent.lease.fence,\n\t\treceipt,\n\t\tfinish: { finishedAt: isoOf(nowMs), outcome: \"not_sent\", reason: \"not_sent\" },\n\t}, options));\n\treturn release(run, intent, \"transport_not_sent\");\n}\n\n/** Settle an attempt's classification (decision 10). */\nfunction applyClassification(run: Run, intent: ClaimedIntent, classification: WebhookDeliveryClassification): Promise<void> {\n\tconst extra = { reason: classification.reason, httpStatus: classification.httpStatus, receiverActionLikely: classification.receiverActionLikely };\n\tswitch (classification.outcome) {\n\t\tcase \"delivered\":\n\t\t\treturn settle(run, { kind: \"delivered\" }, \"delivered\", extra);\n\t\tcase \"dead_letter\":\n\t\t\treturn settle(run, { kind: \"dead_letter\", reason: classification.reason }, \"dead_lettered\", extra);\n\t\tcase \"cancelled\":\n\t\t\treturn settle(run, { kind: \"cancelled\", reason: classification.reason }, \"cancelled\", extra);\n\t\tdefault:\n\t\t\treturn retryOrDeadLetter(run, intent, classification, extra);\n\t}\n}\n\n/** The delay before attempt `attempt + 1`, falling back to the longest configured delay when the port misbehaves. */\nfunction delayAfter(run: Run, attempt: number): number {\n\tlet delayMs: number;\n\ttry {\n\t\tdelayMs = apply(run.config.retryDelay, undefined, [attempt]) as number;\n\t} catch {\n\t\tdelayMs = NaN;\n\t}\n\tif (typeof delayMs !== \"number\" || !numberIsFinite(delayMs) || delayMs < 0) {\n\t\tconst delays = run.config.limits.deliveryRetryDelaysMs;\n\t\tdelayMs = delays[delays.length - 1]!;\n\t}\n\treturn delayMs;\n}\n\nfunction retryOrDeadLetter(\n\trun: Run,\n\tintent: ClaimedIntent,\n\tclassification: WebhookDeliveryClassification,\n\textra: Partial<WebhookDeliveryCycleEvent>,\n): Promise<void> {\n\tconst attempt = intent.attemptCount + 1;\n\tif (attempt >= run.config.limits.maxDeliveryAttempts) {\n\t\treturn settle(run, { kind: \"dead_letter\", reason: classification.reason }, \"dead_lettered\", extra);\n\t}\n\tconst nowMs = readClock(run.config.clock);\n\t// A 429's bounded Retry-After is honoured when it is longer than the schedule.\n\tconst delayMs = mathMax(delayAfter(run, attempt), classification.retryAfterMs ?? 0);\n\tconst availableAtMs = nowMs + delayMs;\n\tif (availableAtMs >= intent.processingDeadlineMs) return deadLetter(run, \"processing_deadline_exceeded\", extra);\n\treturn settle(run, { kind: \"retry\", availableAt: new Date(availableAtMs), outcome: \"retryable\", reason: classification.reason }, \"retry_scheduled\", extra);\n}\n\n/**\n * Return the intent to pending unsent, spending no attempt (decision 3).\n * It is available again after the delay the next attempt would wait; when\n * that falls at or past the processing deadline it is dead-lettered now,\n * because deferrals count toward that deadline (R4).\n */\nfunction release(run: Run, intent: ClaimedIntent, diagnostic: WebhookDiagnosticCode): Promise<void> {\n\tconst nowMs = readClock(run.config.clock);\n\tconst availableAtMs = nowMs + delayAfter(run, intent.attemptCount + 1);\n\tif (availableAtMs >= intent.processingDeadlineMs) return deadLetter(run, \"processing_deadline_exceeded\", { diagnostic });\n\treturn settle(run, { kind: \"release\", availableAt: new Date(availableAtMs), diagnostic }, \"released\", { diagnostic });\n}\n\nfunction cancel(run: Run, reason: \"authorization_revoked\" | \"subscription_paused\" | \"subscription_deleted\"): Promise<void> {\n\treturn settle(run, { kind: \"cancelled\", reason }, \"cancelled\", { reason });\n}\n\nfunction deadLetter(run: Run, diagnostic: WebhookDiagnosticCode, extra: Partial<WebhookDeliveryCycleEvent> = {}): Promise<void> {\n\treturn settle(run, { kind: \"dead_letter\", reason: diagnostic }, \"dead_lettered\", { ...extra, diagnostic });\n}\n\ntype Settlement = Parameters<WebhookDeliveryStore[\"settleDeliveryIntent\"]>[0][\"settlement\"];\n\n/**\n * The fenced settlement that ends this worker's hold on the intent. Only a\n * literal `true` counts as done and a literal `false` as a lost lease.\n * Anything else, a failed or late call included, is `abandoned`: the\n * settlement may or may not have applied, and nothing more is written\n * either way. If it did not apply, the intent is reclaimed after its lease\n * expires. The store clears the lease on every settlement, so at most one\n * settlement per claim applies.\n */\nasync function settle(\n\trun: Run,\n\tsettlement: Settlement,\n\tresult: Exclude<WebhookDeliveryCycleResultKind, \"lease_lost\" | \"abandoned\">,\n\textra: Partial<WebhookDeliveryCycleEvent>,\n): Promise<void> {\n\tconst outcome = await storeWrite(run, (options, nowMs) => run.config.deliveries.settleDeliveryIntent({\n\t\tdeliveryId: run.header.deliveryId,\n\t\towner: run.header.lease.owner,\n\t\tfence: run.header.lease.fence,\n\t\tnow: new Date(nowMs),\n\t\tsettlement,\n\t}, options));\n\tif (outcome.ok && outcome.value === true) return finish(run, result, extra);\n\tif (outcome.ok && outcome.value === false) return finish(run, \"lease_lost\", { ...extra, diagnostic: \"lease_lost\" });\n\treturn finish(run, \"abandoned\", extra);\n}\n\nconst COUNTER: Readonly<Record<WebhookDeliveryCycleResultKind, keyof Counters>> = freeze({\n\tdelivered: \"delivered\",\n\tretry_scheduled: \"retried\",\n\tdead_lettered: \"deadLettered\",\n\tcancelled: \"cancelled\",\n\treleased: \"released\",\n\tlease_lost: \"leaseLost\",\n\tabandoned: \"abandoned\",\n});\n\n/** Count the intent's result and report it once. A throwing observer is ignored. */\nfunction finish(run: Run, result: WebhookDeliveryCycleResultKind, extra: Partial<WebhookDeliveryCycleEvent> = {}): void {\n\tif (run.reported) return;\n\trun.reported = true;\n\trun.counters[COUNTER[result]] += 1;\n\tconst observe = run.config.observe;\n\tif (observe === undefined) return;\n\tconst intent = run.intent;\n\tconst event = record<WebhookDeliveryCycleEvent>({\n\t\tdeliveryId: run.header.deliveryId,\n\t\ttenantId: run.header.tenantId,\n\t\tspaceId: run.header.spaceId,\n\t\tsubscriptionId: intent?.subscriptionId,\n\t\teventId: intent?.eventId,\n\t\tattempt: intent === undefined ? undefined : intent.attemptCount + 1,\n\t\tconfigurationVersion: run.version,\n\t\tresult,\n\t\thandedOff: run.handedOff,\n\t\treason: extra.reason,\n\t\tdiagnostic: extra.diagnostic,\n\t\thttpStatus: extra.httpStatus,\n\t\treceiverActionLikely: extra.receiverActionLikely,\n\t});\n\ttry {\n\t\tapply(observe, undefined, [event]);\n\t} catch {\n\t\t// Telemetry never changes what the cycle did.\n\t}\n}\n","import { checkWebhookDestinationUrl } from \"./destination\";\nimport { guardOr } from \"./errors\";\nimport { freeze, isArray, isOneOf, matches, numberIsSafeInteger, snapshotJson, type Fail } from \"./snapshot\";\nimport { isWebhookIdentifier } from \"./store-input\";\n\n/*\n * Parameters of the governed actions (PR 9; README, \"Governed actions\").\n *\n * Each action's parameters are read here and nowhere else: by the action's\n * admission check (`admitSubmission`, src/governed-actions.ts), which Host\n * runs on every submission before it records anything, by the action's\n * schema (which Host runs before policies and the handler), and by the\n * handler itself (which reads again rather than trusting what it was handed).\n *\n * The reader copies the input with the package's plain-data snapshot (own\n * data properties only, accessors refused uncalled), refuses any key the\n * action does not declare, and checks every field. A refusal carries a fixed\n * code and the name of a declared field or `parameters`\n * (`webhookParameterRefusalMessage` keeps only those), not a caller value or\n * a caller key: Host writes a schema issue into the invocation's durable\n * `error` as `<path>: <message>`, and the path is always the root.\n *\n * Secret references (ADR 0018 decision 8, R7). Fields named `secretRef` take\n * a reference only. {@link isWebhookSecretReference} refuses the shapes key\n * material and ciphertext usually arrive in; it cannot tell an opaque\n * reference from random bytes of the same shape, so the actions also ask the\n * application's `secretReferences.verify` port, which must confirm that the\n * reference names a secret in the tenant's own secret store: at admission,\n * before Host persists the submission, and again before the handler writes.\n */\n\n/** The governed actions, by the name after the module namespace (`<namespace>.<name>`). */\nexport const WEBHOOK_DELIVERY_ACTION_NAMES = freeze([\n\t\"create_subscription\",\n\t\"update_subscription\",\n\t\"pause_subscription\",\n\t\"resume_subscription\",\n\t\"delete_subscription\",\n\t\"rotate_secret_staged\",\n\t\"rotate_secret_emergency\",\n\t\"requeue_delivery_intent\",\n\t\"requeue_fan_out_job\",\n\t\"enrich_fan_out_job_actor\",\n] as const);\n\n/** One governed action name. */\nexport type WebhookDeliveryActionName = (typeof WEBHOOK_DELIVERY_ACTION_NAMES)[number];\n\n/**\n * Why parameters were refused. `parameters_invalid`: not a plain-data\n * object, a field missing or malformed, or an id breaking the store\n * identifier rule. `unknown_parameter`: a key the action does not declare\n * (named in no message). `secret_ref_invalid`: a `secretRef` that is not a\n * secret reference. `destination_invalid`: a destination URL breaking the\n * URL rules (README, \"URL rules\"). `event_type_pattern_invalid`: a pattern\n * outside the pattern grammar. `update_ambiguous`: an update naming both or\n * neither of patterns and destination.\n */\nexport const WEBHOOK_ACTION_PARAMETER_CODES = freeze([\n\t\"parameters_invalid\",\n\t\"unknown_parameter\",\n\t\"secret_ref_invalid\",\n\t\"destination_invalid\",\n\t\"event_type_pattern_invalid\",\n\t\"update_ambiguous\",\n] as const);\n\n/** Why an action's parameters were refused. */\nexport type WebhookActionParameterCode = (typeof WEBHOOK_ACTION_PARAMETER_CODES)[number];\n\n/** `<namespace>.create_subscription` */\nexport interface WebhookCreateSubscriptionParameters {\n\treadonly subscriptionId: string;\n\treadonly eventTypePatterns: readonly string[];\n\treadonly destinationUrl: string;\n\t/** A secret reference, not key material or ciphertext (`isWebhookSecretReference`, then the verifier). */\n\treadonly secretRef: string;\n\t/** Only `v1` exists (decision 7); the default. */\n\treadonly signatureScheme?: \"v1\";\n}\n\n/** `<namespace>.update_subscription`: exactly one of the two changes per invocation. */\nexport type WebhookUpdateSubscriptionParameters =\n\t| { readonly subscriptionId: string; readonly eventTypePatterns: readonly string[]; readonly expectedRevision?: number }\n\t| { readonly subscriptionId: string; readonly destinationUrl: string; readonly expectedVersion?: number };\n\n/** `<namespace>.pause_subscription`, `resume_subscription` and `delete_subscription`. */\nexport interface WebhookSubscriptionTransitionParameters {\n\treadonly subscriptionId: string;\n\treadonly expectedRevision?: number;\n}\n\n/** `<namespace>.rotate_secret_staged` */\nexport interface WebhookStagedRotationParameters {\n\treadonly subscriptionId: string;\n\t/** The next secret's reference, not key material or ciphertext (`isWebhookSecretReference`, then the verifier). */\n\treadonly secretRef: string;\n\t/** The configuration version the operator read; the rotation applies only on it. */\n\treadonly expectedVersion: number;\n\t/** The operator's statement that the receiver already accepts the next secret (decision 8). */\n\treadonly receiverAcceptsNextSecret: true;\n}\n\n/** `<namespace>.rotate_secret_emergency` */\nexport interface WebhookEmergencyRotationParameters {\n\treadonly subscriptionId: string;\n\treadonly secretRef: string;\n\treadonly expectedVersion?: number;\n}\n\n/** `<namespace>.requeue_delivery_intent` */\nexport interface WebhookIntentRequeueParameters {\n\treadonly deliveryId: string;\n\t/** The intent's `fence` as the operator read it. */\n\treadonly expectedFence: number;\n}\n\n/** `<namespace>.requeue_fan_out_job` and `enrich_fan_out_job_actor`. */\nexport interface WebhookJobParameters {\n\treadonly eventId: string;\n\t/** The job's `fence` as the operator read it. */\n\treadonly expectedFence: number;\n}\n\n/** The parameters of each action, by name. */\nexport interface WebhookDeliveryActionParameters {\n\treadonly create_subscription: WebhookCreateSubscriptionParameters;\n\treadonly update_subscription: WebhookUpdateSubscriptionParameters;\n\treadonly pause_subscription: WebhookSubscriptionTransitionParameters;\n\treadonly resume_subscription: WebhookSubscriptionTransitionParameters;\n\treadonly delete_subscription: WebhookSubscriptionTransitionParameters;\n\treadonly rotate_secret_staged: WebhookStagedRotationParameters;\n\treadonly rotate_secret_emergency: WebhookEmergencyRotationParameters;\n\treadonly requeue_delivery_intent: WebhookIntentRequeueParameters;\n\treadonly requeue_fan_out_job: WebhookJobParameters;\n\treadonly enrich_fan_out_job_actor: WebhookJobParameters;\n}\n\n/** What reading one action's parameters found. */\nexport type WebhookActionParameterRead<N extends WebhookDeliveryActionName> =\n\t| { readonly ok: true; readonly value: WebhookDeliveryActionParameters[N] }\n\t| { readonly ok: false; readonly code: WebhookActionParameterCode; readonly field: string };\n\n// ---------------------------------------------------------------------------\n// Secret references and patterns\n// ---------------------------------------------------------------------------\n\n/** The longest secret reference accepted. */\nexport const WEBHOOK_SECRET_REF_MAX_LENGTH = 256;\n/** The longest run of characters between two separators (`:`, `/`, `@`, `#`) in a secret reference. */\nexport const WEBHOOK_SECRET_REF_MAX_SEGMENT = 64;\n\nconst SECRET_REF_SHAPE = /^[a-z][a-z0-9.-]{0,31}:[A-Za-z0-9._~:/@#-]+$/;\nconst SECRET_REF_LONG_SEGMENT = /[A-Za-z0-9._~-]{65,}/;\n\n/**\n * Whether `value` has the shape of a secret reference (ADR 0018 decision 8):\n * a lower-case scheme and `:` (`kms:`, `vault:`, `arn:`, `secret:` …), then\n * only `A–Z a–z 0–9 . _ ~ : / @ # -`, at most\n * {@link WEBHOOK_SECRET_REF_MAX_LENGTH} characters, with no run longer than\n * {@link WEBHOOK_SECRET_REF_MAX_SEGMENT} between separators.\n *\n * That refuses raw key bytes and their usual encodings: hex, base64 and\n * `whsec_…` values (no scheme), padded or standard base64 (`=`, `+`), PEM\n * armour and anything with whitespace or control characters, and long\n * encoded runs such as wrapped ciphertext. It cannot recognise key material\n * deliberately shaped like a reference (`x:` followed by 64 hex digits\n * passes), which is why the actions also require the application's\n * `secretReferences.verify` port to confirm the reference resolves in the\n * tenant's secret store.\n */\nexport function isWebhookSecretReference(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length <= WEBHOOK_SECRET_REF_MAX_LENGTH &&\n\t\tmatches(SECRET_REF_SHAPE, value) && !matches(SECRET_REF_LONG_SEGMENT, value);\n}\n\n/** The most patterns one subscription takes. */\nexport const WEBHOOK_MAX_EVENT_TYPE_PATTERNS = 64;\n\nconst PATTERN_SHAPE = /^(?:\\*|[A-Za-z0-9_:-]+(?:\\.[A-Za-z0-9_:-]+)*(?:\\.\\*)?)$/;\n\n/**\n * Whether `value` is an event type pattern the matcher understands: `*`,\n * `prefix.*`, or an exact type, built from `A–Z a–z 0–9 _ : -` segments\n * joined by `.`, at most 256 characters. A `*` anywhere else is refused,\n * since the matcher would treat it as a literal.\n */\nexport function isWebhookEventTypePattern(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length <= 256 && matches(PATTERN_SHAPE, value);\n}\n\n// ---------------------------------------------------------------------------\n// Reading\n// ---------------------------------------------------------------------------\n\ntype Read<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly code: WebhookActionParameterCode; readonly field: string };\n\n/**\n * Thrown inside a reader to stop it; `readWebhookActionParameters` catches\n * it. Recognized by its private field (`Refusal.is`), which only this class\n * can create and which a brand check reads without running any of the\n * value's code (no getter, no Proxy trap), so a caller's input that throws\n * a look-alike `{ refusal: true, code, … }` from a trap is not taken for\n * one. The class is not exported and keeps no registry (Boundary Guard G5).\n */\nclass Refusal {\n\treadonly #brand = true;\n\treadonly code: WebhookActionParameterCode;\n\treadonly field: string;\n\n\tconstructor(code: WebhookActionParameterCode, field: string) {\n\t\tthis.code = code;\n\t\tthis.field = field;\n\t\tfreeze(this);\n\t}\n\n\t/** Whether `value` was made by this class's constructor. Reads nothing of `value`. */\n\tstatic is(value: unknown): value is Refusal {\n\t\treturn value !== null && typeof value === \"object\" && #brand in value;\n\t}\n}\n\nconst objectKeys = Object.keys;\n\nfunction refuse(code: WebhookActionParameterCode, field: string): never {\n\tthrow new Refusal(code, field);\n}\n\nconst snapshotFail: Fail = () => refuse(\"parameters_invalid\", \"parameters\");\n\ntype Fields = { readonly [key: string]: unknown };\n\nconst ALLOWED_KEYS: { readonly [N in WebhookDeliveryActionName]: readonly string[] } = freeze({\n\tcreate_subscription: freeze([\"subscriptionId\", \"eventTypePatterns\", \"destinationUrl\", \"secretRef\", \"signatureScheme\"]),\n\tupdate_subscription: freeze([\"subscriptionId\", \"eventTypePatterns\", \"expectedRevision\", \"destinationUrl\", \"expectedVersion\"]),\n\tpause_subscription: freeze([\"subscriptionId\", \"expectedRevision\"]),\n\tresume_subscription: freeze([\"subscriptionId\", \"expectedRevision\"]),\n\tdelete_subscription: freeze([\"subscriptionId\", \"expectedRevision\"]),\n\trotate_secret_staged: freeze([\"subscriptionId\", \"secretRef\", \"expectedVersion\", \"receiverAcceptsNextSecret\"]),\n\trotate_secret_emergency: freeze([\"subscriptionId\", \"secretRef\", \"expectedVersion\"]),\n\trequeue_delivery_intent: freeze([\"deliveryId\", \"expectedFence\"]),\n\trequeue_fan_out_job: freeze([\"eventId\", \"expectedFence\"]),\n\tenrich_fan_out_job_actor: freeze([\"eventId\", \"expectedFence\"]),\n});\n\nfunction snapshotParameters(input: unknown): Fields {\n\tconst copy = snapshotJson(input, \"parameters\", snapshotFail);\n\tif (copy === null || typeof copy !== \"object\" || isArray(copy)) refuse(\"parameters_invalid\", \"parameters\");\n\treturn copy as Fields;\n}\n\nfunction idField(fields: Fields, key: string): string {\n\tconst value = fields[key];\n\tif (!isWebhookIdentifier(value)) refuse(\"parameters_invalid\", key);\n\treturn value;\n}\n\nfunction optionalWhole(fields: Fields, key: string, min: number): number | undefined {\n\tconst value = fields[key];\n\tif (value === undefined) return undefined;\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < min) refuse(\"parameters_invalid\", key);\n\treturn value;\n}\n\nfunction whole(fields: Fields, key: string, min: number): number {\n\tconst value = optionalWhole(fields, key, min);\n\tif (value === undefined) refuse(\"parameters_invalid\", key);\n\treturn value;\n}\n\nfunction secretRefField(fields: Fields): string {\n\tconst value = fields[\"secretRef\"];\n\tif (!isWebhookSecretReference(value)) refuse(\"secret_ref_invalid\", \"secretRef\");\n\treturn value;\n}\n\nfunction destinationField(fields: Fields): string {\n\tconst value = fields[\"destinationUrl\"];\n\tif (typeof value !== \"string\") refuse(\"destination_invalid\", \"destinationUrl\");\n\tconst check = guardOr(() => checkWebhookDestinationUrl(value), () => ({ ok: false as const, code: \"invalid_url\" as const }));\n\tif (!check.ok) refuse(\"destination_invalid\", \"destinationUrl\");\n\treturn value;\n}\n\nfunction patternsField(fields: Fields): readonly string[] {\n\tconst value = fields[\"eventTypePatterns\"];\n\tif (!isArray(value) || value.length === 0 || value.length > WEBHOOK_MAX_EVENT_TYPE_PATTERNS) refuse(\"event_type_pattern_invalid\", \"eventTypePatterns\");\n\tconst out: string[] = [];\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst pattern = value[index];\n\t\tif (!isWebhookEventTypePattern(pattern)) refuse(\"event_type_pattern_invalid\", \"eventTypePatterns\");\n\t\tout[index] = pattern;\n\t}\n\treturn freeze(out);\n}\n\n/** Refuse any key the action does not declare, without naming it. */\nfunction onlyKnownKeys(fields: Fields, name: WebhookDeliveryActionName): void {\n\tconst keys = objectKeys(fields);\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tif (!isOneOf(ALLOWED_KEYS[name], keys[index])) refuse(\"unknown_parameter\", \"parameters\");\n\t}\n}\n\nfunction readFields(name: WebhookDeliveryActionName, fields: Fields): object {\n\tswitch (name) {\n\t\tcase \"create_subscription\": {\n\t\t\tconst scheme = fields[\"signatureScheme\"];\n\t\t\tif (scheme !== undefined && scheme !== \"v1\") refuse(\"parameters_invalid\", \"signatureScheme\");\n\t\t\treturn {\n\t\t\t\tsubscriptionId: idField(fields, \"subscriptionId\"),\n\t\t\t\teventTypePatterns: patternsField(fields),\n\t\t\t\tdestinationUrl: destinationField(fields),\n\t\t\t\tsecretRef: secretRefField(fields),\n\t\t\t\t...(scheme === undefined ? {} : { signatureScheme: \"v1\" }),\n\t\t\t};\n\t\t}\n\t\tcase \"update_subscription\": {\n\t\t\tconst patterns = fields[\"eventTypePatterns\"] !== undefined;\n\t\t\tconst destination = fields[\"destinationUrl\"] !== undefined;\n\t\t\tif (patterns === destination) refuse(\"update_ambiguous\", \"parameters\");\n\t\t\tconst subscriptionId = idField(fields, \"subscriptionId\");\n\t\t\tif (patterns) {\n\t\t\t\tif (fields[\"expectedVersion\"] !== undefined) refuse(\"parameters_invalid\", \"expectedVersion\");\n\t\t\t\tconst expectedRevision = optionalWhole(fields, \"expectedRevision\", 1);\n\t\t\t\treturn { subscriptionId, eventTypePatterns: patternsField(fields), ...(expectedRevision === undefined ? {} : { expectedRevision }) };\n\t\t\t}\n\t\t\tif (fields[\"expectedRevision\"] !== undefined) refuse(\"parameters_invalid\", \"expectedRevision\");\n\t\t\tconst expectedVersion = optionalWhole(fields, \"expectedVersion\", 1);\n\t\t\treturn { subscriptionId, destinationUrl: destinationField(fields), ...(expectedVersion === undefined ? {} : { expectedVersion }) };\n\t\t}\n\t\tcase \"pause_subscription\":\n\t\tcase \"resume_subscription\":\n\t\tcase \"delete_subscription\": {\n\t\t\tconst expectedRevision = optionalWhole(fields, \"expectedRevision\", 1);\n\t\t\treturn { subscriptionId: idField(fields, \"subscriptionId\"), ...(expectedRevision === undefined ? {} : { expectedRevision }) };\n\t\t}\n\t\tcase \"rotate_secret_staged\": {\n\t\t\tif (fields[\"receiverAcceptsNextSecret\"] !== true) refuse(\"parameters_invalid\", \"receiverAcceptsNextSecret\");\n\t\t\treturn {\n\t\t\t\tsubscriptionId: idField(fields, \"subscriptionId\"),\n\t\t\t\tsecretRef: secretRefField(fields),\n\t\t\t\texpectedVersion: whole(fields, \"expectedVersion\", 1),\n\t\t\t\treceiverAcceptsNextSecret: true,\n\t\t\t};\n\t\t}\n\t\tcase \"rotate_secret_emergency\": {\n\t\t\tconst expectedVersion = optionalWhole(fields, \"expectedVersion\", 1);\n\t\t\treturn { subscriptionId: idField(fields, \"subscriptionId\"), secretRef: secretRefField(fields), ...(expectedVersion === undefined ? {} : { expectedVersion }) };\n\t\t}\n\t\tcase \"requeue_delivery_intent\":\n\t\t\treturn { deliveryId: idField(fields, \"deliveryId\"), expectedFence: whole(fields, \"expectedFence\", 0) };\n\t\tcase \"requeue_fan_out_job\":\n\t\tcase \"enrich_fan_out_job_actor\":\n\t\t\treturn { eventId: idField(fields, \"eventId\"), expectedFence: whole(fields, \"expectedFence\", 0) };\n\t}\n}\n\n/** The refusal `code` and `field` with each held to its fixed set: a parameter code, and a declared field or `parameters`. */\nfunction fixedRefusal(code: unknown, field: unknown): { readonly ok: false; readonly code: WebhookActionParameterCode; readonly field: string } {\n\treturn freeze({\n\t\tok: false as const,\n\t\tcode: isOneOf(WEBHOOK_ACTION_PARAMETER_CODES, code) ? (code as WebhookActionParameterCode) : \"parameters_invalid\",\n\t\tfield: typeof field === \"string\" && isPackageField(field) ? field : \"parameters\",\n\t});\n}\n\nconst PARAMETERS_INVALID = fixedRefusal(\"parameters_invalid\", \"parameters\");\n\n/**\n * Read one action's parameters. Never throws: the only thrown value whose\n * properties are read is the package's own `Refusal` (recognized by\n * `Refusal.is`, which runs none of a value's code); anything else thrown\n * while the input is read (an accessor, a Proxy trap, a look-alike refusal)\n * is dropped unread and reported as `parameters_invalid`. The code and field\n * returned are each checked against their fixed set (`fixedRefusal`). Tests:\n * \"forged refusals: …\".\n */\nexport function readWebhookActionParameters<N extends WebhookDeliveryActionName>(name: N, input: unknown): WebhookActionParameterRead<N> {\n\ttry {\n\t\tconst fields = snapshotParameters(input);\n\t\tonlyKnownKeys(fields, name);\n\t\treturn freeze({ ok: true as const, value: freeze(readFields(name, fields)) as WebhookDeliveryActionParameters[N] });\n\t} catch (thrown) {\n\t\treturn Refusal.is(thrown) ? fixedRefusal(thrown.code, thrown.field) : PARAMETERS_INVALID;\n\t}\n}\n\n/** A field name the reader itself reports: one of the declared keys, or `parameters`. */\nfunction isPackageField(field: string): boolean {\n\tif (field === \"parameters\") return true;\n\tfor (const name of WEBHOOK_DELIVERY_ACTION_NAMES) if (isOneOf(ALLOWED_KEYS[name], field)) return true;\n\treturn false;\n}\n\n/** The fixed text of a refusal: `<code> (<package field>)`. Never a caller value or key. */\nexport function webhookParameterRefusalMessage(code: WebhookActionParameterCode, field: string): string {\n\treturn `${code} (${isPackageField(field) ? field : \"parameters\"})`;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas\n// ---------------------------------------------------------------------------\n\n/** A Platform `SchemaValidator`, structurally, with the portable JSON Schema discovery reads. */\nexport interface WebhookActionSchema<T> {\n\tparse(input: unknown): T;\n\tsafeParse(input: unknown):\n\t\t| { success: true; data: T }\n\t\t| { success: false; error: { issues: { path: PropertyKey[]; message: string }[] } };\n\ttoJSONSchema(): object;\n}\n\nconst ID_SCHEMA = freeze({ type: \"string\", minLength: 1, maxLength: 256 });\nconst FENCE_SCHEMA = freeze({ type: \"integer\", minimum: 0 });\nconst REVISION_SCHEMA = freeze({ type: \"integer\", minimum: 1 });\nconst SECRET_REF_SCHEMA = freeze({\n\ttype: \"string\",\n\tmaxLength: WEBHOOK_SECRET_REF_MAX_LENGTH,\n\tpattern: \"^[a-z][a-z0-9.-]{0,31}:[A-Za-z0-9._~:/@#-]+$\",\n\tdescription: \"A secret reference resolved in the tenant's secret store, not key material or ciphertext. No run between separators may exceed 64 characters.\",\n});\nconst PATTERNS_SCHEMA = freeze({\n\ttype: \"array\",\n\tminItems: 1,\n\tmaxItems: WEBHOOK_MAX_EVENT_TYPE_PATTERNS,\n\titems: { type: \"string\", maxLength: 256, pattern: \"^(?:\\\\*|[A-Za-z0-9_:-]+(?:\\\\.[A-Za-z0-9_:-]+)*(?:\\\\.\\\\*)?)$\" },\n});\nconst URL_SCHEMA = freeze({ type: \"string\", maxLength: 2048, pattern: \"^https://\" });\n\nfunction objectSchema(properties: Record<string, object>, required: readonly string[]): object {\n\treturn { type: \"object\", properties, required: [...required], additionalProperties: false };\n}\n\nconst JSON_SCHEMAS: { readonly [N in WebhookDeliveryActionName]: () => object } = freeze({\n\tcreate_subscription: () => objectSchema(\n\t\t{ subscriptionId: ID_SCHEMA, eventTypePatterns: PATTERNS_SCHEMA, destinationUrl: URL_SCHEMA, secretRef: SECRET_REF_SCHEMA, signatureScheme: { type: \"string\", enum: [\"v1\"] } },\n\t\t[\"subscriptionId\", \"eventTypePatterns\", \"destinationUrl\", \"secretRef\"],\n\t),\n\tupdate_subscription: () => ({\n\t\t...objectSchema({ subscriptionId: ID_SCHEMA, eventTypePatterns: PATTERNS_SCHEMA, expectedRevision: REVISION_SCHEMA, destinationUrl: URL_SCHEMA, expectedVersion: REVISION_SCHEMA }, [\"subscriptionId\"]),\n\t\toneOf: [{ required: [\"eventTypePatterns\"] }, { required: [\"destinationUrl\"] }],\n\t}),\n\tpause_subscription: () => objectSchema({ subscriptionId: ID_SCHEMA, expectedRevision: REVISION_SCHEMA }, [\"subscriptionId\"]),\n\tresume_subscription: () => objectSchema({ subscriptionId: ID_SCHEMA, expectedRevision: REVISION_SCHEMA }, [\"subscriptionId\"]),\n\tdelete_subscription: () => objectSchema({ subscriptionId: ID_SCHEMA, expectedRevision: REVISION_SCHEMA }, [\"subscriptionId\"]),\n\trotate_secret_staged: () => objectSchema(\n\t\t{ subscriptionId: ID_SCHEMA, secretRef: SECRET_REF_SCHEMA, expectedVersion: REVISION_SCHEMA, receiverAcceptsNextSecret: { type: \"boolean\", const: true } },\n\t\t[\"subscriptionId\", \"secretRef\", \"expectedVersion\", \"receiverAcceptsNextSecret\"],\n\t),\n\trotate_secret_emergency: () => objectSchema({ subscriptionId: ID_SCHEMA, secretRef: SECRET_REF_SCHEMA, expectedVersion: REVISION_SCHEMA }, [\"subscriptionId\", \"secretRef\"]),\n\trequeue_delivery_intent: () => objectSchema({ deliveryId: ID_SCHEMA, expectedFence: FENCE_SCHEMA }, [\"deliveryId\", \"expectedFence\"]),\n\trequeue_fan_out_job: () => objectSchema({ eventId: ID_SCHEMA, expectedFence: FENCE_SCHEMA }, [\"eventId\", \"expectedFence\"]),\n\tenrich_fan_out_job_actor: () => objectSchema({ eventId: ID_SCHEMA, expectedFence: FENCE_SCHEMA }, [\"eventId\", \"expectedFence\"]),\n});\n\n/** A thrown `parse` failure: fixed text only. */\nclass WebhookActionParameterError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookActionParameterError\";\n\t}\n}\n\n/**\n * The schema of one action. `safeParse` reports a refusal as one issue at\n * the root path whose message is {@link webhookParameterRefusalMessage}, so\n * Host's durable `validation_failed` error holds package text only.\n */\nexport function webhookActionSchema<N extends WebhookDeliveryActionName>(name: N): WebhookActionSchema<WebhookDeliveryActionParameters[N]> {\n\tconst safeParse = (input: unknown) => {\n\t\tconst read = readWebhookActionParameters(name, input);\n\t\tif (read.ok) return { success: true as const, data: read.value };\n\t\treturn { success: false as const, error: { issues: [{ path: [] as PropertyKey[], message: webhookParameterRefusalMessage(read.code, read.field) }] } };\n\t};\n\treturn freeze({\n\t\tparse(input: unknown) {\n\t\t\tconst result = safeParse(input);\n\t\t\tif (result.success) return result.data;\n\t\t\tthrow new WebhookActionParameterError(result.error.issues[0]!.message);\n\t\t},\n\t\tsafeParse,\n\t\ttoJSONSchema: JSON_SCHEMAS[name],\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Namespaces and action ids\n// ---------------------------------------------------------------------------\n\nconst NAMESPACE_SHAPE = /^[a-z][a-z0-9-]{0,63}$/;\n\n/** The default module namespace. */\nexport const DEFAULT_WEBHOOK_DELIVERY_NAMESPACE = \"webhook-delivery\";\n\n/** Whether `value` is a module namespace this package accepts (Platform's rule, at most 64 characters). */\nexport function isWebhookDeliveryNamespace(value: unknown): value is string {\n\treturn typeof value === \"string\" && matches(NAMESPACE_SHAPE, value);\n}\n\n/** The action name of `actionId` when it is one of this namespace's governed actions. */\nexport function webhookActionNameOf(namespace: string, actionId: unknown): WebhookDeliveryActionName | undefined {\n\tif (typeof actionId !== \"string\" || actionId.length <= namespace.length + 1 || actionId[namespace.length] !== \".\") return undefined;\n\tif (actionId.slice(0, namespace.length) !== namespace) return undefined;\n\tconst name = actionId.slice(namespace.length + 1);\n\tfor (const candidate of WEBHOOK_DELIVERY_ACTION_NAMES) if (candidate === name) return candidate;\n\treturn undefined;\n}\n","import type {\n\tActionAdmission,\n\tActionAdmissionDecision,\n\tActionContext,\n\tActionDefinition,\n\tActionResult,\n\tFabricModule,\n\tPolicyContext,\n\tPolicyEvaluator,\n\tPolicyOutcome,\n} from \"@fabricorg/platform\";\n\nimport { WEBHOOK_DELIVERY_ACTION_EVENT_TYPES, type WebhookDeliveryActionEventType } from \"./action-events\";\nimport {\n\tDEFAULT_WEBHOOK_DELIVERY_NAMESPACE,\n\tisWebhookDeliveryNamespace,\n\treadWebhookActionParameters,\n\tWEBHOOK_DELIVERY_ACTION_NAMES,\n\twebhookActionNameOf,\n\twebhookActionSchema,\n\ttype WebhookDeliveryActionName,\n\ttype WebhookDeliveryActionParameters,\n} from \"./action-parameters\";\nimport { WEBHOOK_ACTION_REFUSAL_CODES, type WebhookActionRefusalCode } from \"./codes\";\nimport { governedActionError } from \"./errors\";\nimport { boundedCall, captureFanOutClock, readFanOutClock, type FanOutClock } from \"./fan-out-call\";\nimport { assertPositiveInteger, resolveWebhookDeliveryLimits, type WebhookDeliveryLimits } from \"./limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookDeliveryStore,\n\tWebhookDestinationResolver,\n\tWebhookScope,\n\tWebhookSubscriptionStore,\n\tWebhookSubscriptionWriter,\n} from \"./ports\";\nimport { apply, freeze, isOneOf, numberIsSafeInteger } from \"./snapshot\";\nimport { isoOf, isWebhookIdentifier } from \"./store-input\";\n\n/*\n * The governed operator actions (ADR 0018 decisions 5, 8 and 10;\n * Consequences; README, \"Governed actions\"). `createWebhookDeliveryModule()`\n * builds one `FabricModule` from the ports it is given at the composition\n * root; nothing is registered in module scope (decision 6, ADR 0008), so two\n * modules built in one process share nothing but this code.\n *\n * Every action:\n *\n * - declares `admitSubmission` (`admissionFor`), which Host (7.3.0 and\n * later) runs on every submission before it records anything: it reads\n * the parameters with the package reader and, for an action that takes a\n * `secretRef`, asks the application's `secretReferences.verify` with\n * Host's trusted tenant and space. A refused submission leaves no\n * invocation, idempotency key, event or error in Host's store (tests\n * \"secret material in a secretRef is refused at admission …\" and \"key\n * material shaped like a reference …\" in tests/governed-actions.test.ts);\n * - refuses to run (`admission_not_enforced`, `handlerFor`) unless Host\n * hands it `ActionContext.admittedAt`, so under a Host that skipped the\n * check, nothing is written;\n * - runs through Host's governed path: Host validates the parameters with\n * the action's schema, records the module policy's decision, runs the\n * handler and appends the declared event;\n * - acts only in Host's trusted tenant and space: parameters declare no\n * tenant or space (`ALLOWED_KEYS`, src/action-parameters.ts), and\n * `handlerFor` hands each handler `scopeOf(ctx)` as the only scope its\n * store calls use, so a subscription, job or intent of another scope is\n * `not_found` to the store and the action refuses (test \"every action\n * that names a subscription, intent or job refuses one from another tenant\n * or space …\");\n * - makes at most one write to the subscription store and at most one\n * compare-and-set to the delivery store (each handler in `HANDLERS`), so\n * the change is one atomic store step; pause, resume and delete add\n * `cancelPendingIntents` as a best-effort cleanup (`cleanUp`), which\n * dispatch does not depend on;\n * - fails with `webhook_action_refused:<code>` (`WEBHOOK_ACTION_REFUSAL_CODES`)\n * and nothing else in the error (`refused`), emits no event when it\n * refuses, and builds events from ids, numbers, patterns and timestamps\n * only (test \"no secret bytes, reference or URL reaches an event …\").\n *\n * The stores are not Host's store, so a store write and Host's event append\n * are not one transaction. If Host fails after the handler's write (its\n * event append, or a crash before it commits), the write stands without its\n * event; the invocation is left `failed` or `running` for an operator to\n * reconcile. Subscription and rotation actions are declared not idempotent,\n * so Host refuses to re-run an interrupted one (\"manual reconciliation is\n * required\"). The requeue and enrichment actions are idempotent: every\n * attempt of one invocation, one after another or overlapping, reports the\n * change some attempt of it committed, from that change's evidence, even\n * after the record it names was purged (`oncePerInvocation`; the stores\n * recognize the invocation in their compare-and-set's atomic step).\n */\n\n// ---------------------------------------------------------------------------\n// Public options and ports\n// ---------------------------------------------------------------------------\n\n/** What the module's operator policy asks the application about one invocation. */\nexport interface WebhookOperatorAuthorizationInput {\n\t/** `<namespace>.<action name>`. */\n\treadonly actionId: string;\n\treadonly action: WebhookDeliveryActionName;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly actorId: string;\n\treadonly actorType: string;\n\t/** The ids the action names, copied from three id fields by `operatorPolicy`; no URL or secret reference. */\n\treadonly target: {\n\t\treadonly subscriptionId?: string;\n\t\treadonly deliveryId?: string;\n\t\treadonly eventId?: string;\n\t};\n}\n\n/**\n * The module policy's question (`<namespace>.operator_authorized.v1`). Only a\n * literal `true` passes; `false`, any other answer, a throw or a timeout\n * blocks the invocation. Deny by default: the module cannot be built\n * without it.\n */\nexport type WebhookOperatorAuthorization = (\n\tinput: WebhookOperatorAuthorizationInput,\n\toptions: WebhookCallOptions,\n) => boolean | Promise<boolean>;\n\n/**\n * Confirms that a secret reference names a secret of this tenant in the\n * application's secret store (decision 8): at admission, before Host records\n * the submission, and again before the action writes it. Only a literal\n * `\"valid\"` passes. It must not return or log the secret, and it should honour\n * `options.signal`, which Host aborts at its admission deadline.\n */\nexport interface WebhookSecretReferenceVerifier {\n\tverify(input: WebhookScope & { readonly secretRef: string }, options: WebhookCallOptions): Promise<\"valid\" | \"invalid\">;\n}\n\n/**\n * What the application's actor reader found on the canonical event\n * (decision 5). `withheld`: the application's own actor-disclosure rule for\n * this event (the same rule as Host's `includeActor` hook) excludes the\n * actor, so enrichment must not add it. `not_found`: no such event in this\n * tenant and space.\n */\nexport type WebhookEventActorReading =\n\t| { readonly state: \"found\"; readonly actorId: string; readonly actorType: string }\n\t| { readonly state: \"withheld\" }\n\t| { readonly state: \"not_found\" };\n\n/** Reads the actor of the canonical event for a legacy job's tenant, space and `eventId` (decision 5). */\nexport interface WebhookEventActorReader {\n\treadEventActor(\n\t\tinput: WebhookScope & {\n\t\t\treadonly eventId: string;\n\t\t\treadonly eventType: string;\n\t\t\treadonly payloadClassification: string;\n\t\t},\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookEventActorReading>;\n}\n\n/** Options for {@link createWebhookDeliveryModule}. */\nexport interface WebhookDeliveryModuleOptions {\n\t/** The module namespace; actions are `<namespace>.<name>`. Default `webhook-delivery`. */\n\treadonly namespace?: string;\n\treadonly subscriptions: WebhookSubscriptionStore & WebhookSubscriptionWriter;\n\treadonly deliveries: WebhookDeliveryStore;\n\t/** Re-validates a destination at configuration change and at intent requeue (decision 6). */\n\treadonly resolver: WebhookDestinationResolver;\n\treadonly secretReferences: WebhookSecretReferenceVerifier;\n\treadonly actorReader: WebhookEventActorReader;\n\treadonly authorizeOperatorAction: WebhookOperatorAuthorization;\n\treadonly clock: WebhookClock;\n\t/** `portTimeoutMs` bounds every port call; `fanOutDeadlineMs` and `deliveryDeadlineMs` set requeued deadlines; `attemptTimeoutMs` enters the staged rotation's retention. */\n\treadonly limits?: Partial<WebhookDeliveryLimits>;\n\t/** The receivers' signature timestamp tolerance, for a staged rotation's `previousSecretRetainUntil`. Default 300 000 (R6). */\n\treadonly verifierToleranceMs?: number;\n}\n\n/** The module policy's id for a namespace. */\nexport function webhookOperatorPolicyId(namespace: string = DEFAULT_WEBHOOK_DELIVERY_NAMESPACE): `${string}.v${number}` {\n\treturn `${namespace}.operator_authorized.v1`;\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\ninterface Deps {\n\treadonly namespace: string;\n\treadonly subscriptions: WebhookSubscriptionStore & WebhookSubscriptionWriter;\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly resolver: WebhookDestinationResolver;\n\treadonly secretReferences: WebhookSecretReferenceVerifier;\n\treadonly actorReader: WebhookEventActorReader;\n\treadonly authorize: WebhookOperatorAuthorization;\n\treadonly clock: FanOutClock;\n\treadonly limits: WebhookDeliveryLimits;\n\treadonly verifierToleranceMs: number;\n}\n\nconst SUBSCRIPTION = \"WebhookSubscription\";\nconst INTENT = \"WebhookDeliveryIntent\";\nconst JOB = \"WebhookFanOutJob\";\n\n/** A refusal: the handler's result and Host's durable error. */\nfunction refused(code: WebhookActionRefusalCode): ActionResult {\n\treturn { success: false, error: `webhook_action_refused:${code}` };\n}\n\n/** A success with its one event (Host's default `_events` result field). */\nfunction emitted(eventType: WebhookDeliveryActionEventType, subjectType: string, subjectId: string, payload: Record<string, unknown>): ActionResult {\n\treturn {\n\t\tsuccess: true,\n\t\tdata: { ...payload, _events: [{ eventType, eventSchemaVersion: 1, subjectType, subjectId, payload }] },\n\t};\n}\n\n/**\n * A thrown marker that ends a handler with a refusal; `handlerFor`'s catch\n * turns it into the result. Recognized by its private field (`Stop.is`),\n * which only this class can create and which a brand check reads without\n * running any of the value's code, so a port answer that throws a\n * look-alike `{ stop: … }` (from an iterator or a Proxy trap) is not taken\n * for one. Not exported; keeps no registry (Boundary Guard G5).\n */\nclass Stop {\n\treadonly #brand = true;\n\treadonly code: WebhookActionRefusalCode;\n\n\tconstructor(code: WebhookActionRefusalCode) {\n\t\tthis.code = code;\n\t\tfreeze(this);\n\t}\n\n\t/** Whether `value` was made by this class's constructor. Reads nothing of `value`. */\n\tstatic is(value: unknown): value is Stop {\n\t\treturn value !== null && typeof value === \"object\" && #brand in value;\n\t}\n}\n\nfunction stop(code: WebhookActionRefusalCode): never {\n\tthrow new Stop(code);\n}\n\nconst getOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;\n\n/** An own data property of a port's answer, or `undefined`; a getter is not called, and a throwing Proxy trap reads as `undefined`. */\nfunction prop(value: unknown, key: string): unknown {\n\tif (value === null || typeof value !== \"object\") return undefined;\n\ttry {\n\t\tconst descriptor = getOwnPropertyDescriptor(value, key);\n\t\treturn descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction whole(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && numberIsSafeInteger(value) && value >= 0 ? value : undefined;\n}\n\nfunction nowMs(deps: Deps): number {\n\ttry {\n\t\treturn readFanOutClock(deps.clock);\n\t} catch {\n\t\treturn stop(\"action_failed\");\n\t}\n}\n\n/**\n * One port call, bounded by `portTimeoutMs` (R4) and aborted with `parent`.\n * `undefined` when it threw, timed out or was aborted; the thrown value is\n * never read.\n */\nasync function port<T>(deps: Deps, run: (options: WebhookCallOptions) => Promise<T>, parent?: AbortSignal): Promise<{ readonly value: T } | undefined> {\n\tconst outcome = await boundedCall(nowMs(deps), deps.limits.portTimeoutMs, parent, run, () => readFanOutClock(deps.clock));\n\treturn outcome.ok ? { value: outcome.value } : undefined;\n}\n\n/**\n * Host's trusted scope for the invocation. Every store call an action makes\n * is given this scope and no other: no action parameter names a tenant or a\n * space (`ALLOWED_KEYS` in src/action-parameters.ts refuses the keys).\n */\nfunction scopeOf(ctx: ActionContext<unknown>): WebhookScope {\n\tconst tenantId = prop(ctx, \"tenantId\");\n\tconst spaceId = prop(ctx, \"spaceId\");\n\tif (!isWebhookIdentifier(tenantId) || !isWebhookIdentifier(spaceId)) stop(\"scope_invalid\");\n\treturn freeze({ tenantId, spaceId });\n}\n\nfunction actorOf(ctx: ActionContext<unknown>): string {\n\tconst actorId = prop(ctx, \"actorId\");\n\tif (!isWebhookIdentifier(actorId)) stop(\"actor_invalid\");\n\treturn actorId;\n}\n\nfunction invocationOf(ctx: ActionContext<unknown>): string | undefined {\n\tconst id = prop(ctx, \"actionInvocationId\");\n\treturn isWebhookIdentifier(id) ? id : undefined;\n}\n\ninterface SubscriptionRead {\n\treadonly status: string;\n\t/** The revision the current status began at (`WebhookSubscriptionSnapshot.statusSinceRevision`). */\n\treadonly statusSinceRevision: number;\n\treadonly version: number;\n\treadonly destinationUrl: string;\n\treadonly signatureScheme: \"v1\";\n\treadonly secretRef: string;\n}\n\n/** The subscription's current status and configuration in `scope`; refuses when absent or unreadable. */\nasync function currentSubscription(deps: Deps, scope: WebhookScope, subscriptionId: string): Promise<SubscriptionRead> {\n\tconst answer = await port(deps, (options) => deps.subscriptions.readSubscription({ ...scope, subscriptionId }, options));\n\tif (answer === undefined) return stop(\"store_unavailable\");\n\tif (answer.value === null) return stop(\"subscription_not_found\");\n\tconst configuration = prop(answer.value, \"configuration\");\n\tconst read = {\n\t\tstatus: prop(answer.value, \"status\"),\n\t\tstatusSinceRevision: whole(prop(answer.value, \"statusSinceRevision\")),\n\t\tversion: whole(prop(configuration, \"version\")),\n\t\tdestinationUrl: prop(configuration, \"destinationUrl\"),\n\t\tsignatureScheme: prop(configuration, \"signatureScheme\"),\n\t\tsecretRef: prop(configuration, \"secretRef\"),\n\t};\n\t// The answer must be the subscription asked for, in this scope.\n\tif (prop(answer.value, \"subscriptionId\") !== subscriptionId || prop(answer.value, \"tenantId\") !== scope.tenantId || prop(answer.value, \"spaceId\") !== scope.spaceId) {\n\t\treturn stop(\"subscription_not_found\");\n\t}\n\tif (!isOneOf([\"active\", \"paused\", \"deleted\"], read.status) || read.statusSinceRevision === undefined || read.statusSinceRevision < 1 ||\n\t\tread.version === undefined || typeof read.destinationUrl !== \"string\" ||\n\t\tread.signatureScheme !== \"v1\" || typeof read.secretRef !== \"string\") {\n\t\treturn stop(\"store_unavailable\");\n\t}\n\treturn read as SubscriptionRead;\n}\n\n/** Ask the application's secret store whether `secretRef` names one of this tenant's secrets. */\nasync function verifySecretRef(deps: Deps, scope: WebhookScope, secretRef: string, parent?: AbortSignal): Promise<void> {\n\tconst answer = await port(deps, (options) => deps.secretReferences.verify({ ...scope, secretRef }, options), parent);\n\tif (answer === undefined) stop(\"secret_ref_unverified\");\n\tif (answer.value === \"invalid\") stop(\"secret_ref_invalid\");\n\tif (answer.value !== \"valid\") stop(\"secret_ref_unverified\");\n}\n\n/** Re-validate a destination with the resolver (decision 6): only a vetted answer passes. */\nasync function vetDestination(deps: Deps, url: string): Promise<void> {\n\tconst answer = await port(deps, (options) => deps.resolver.resolve(url, options));\n\tif (answer === undefined) stop(\"destination_unresolved\");\n\tif (prop(answer.value, \"ok\") === true) return;\n\tconst code = prop(answer.value, \"code\");\n\tstop(code === \"invalid_url\" || code === \"private_address\" ? \"destination_refused\" : \"destination_unresolved\");\n}\n\nconst SUBSCRIPTION_REFUSALS: { readonly [refusal: string]: WebhookActionRefusalCode } = freeze({\n\tnot_found: \"subscription_not_found\",\n\talready_exists: \"subscription_exists\",\n\tdeleted: \"subscription_deleted\",\n\tinvalid_transition: \"invalid_transition\",\n\trevision_conflict: \"revision_conflict\",\n\tversion_conflict: \"version_conflict\",\n});\n\nconst DELIVERY_REFUSALS: { readonly [refusal: string]: WebhookActionRefusalCode } = freeze({\n\tnot_found: \"not_found\",\n\tstale: \"stale\",\n\tnot_dead_letter: \"not_dead_letter\",\n\tpast_horizon: \"past_replay_horizon\",\n\tnot_enrichable: \"not_enrichable\",\n\tactor_present: \"actor_present\",\n\tactor_suppressed: \"actor_suppressed\",\n});\n\nfunction mapRefusal(table: { readonly [refusal: string]: WebhookActionRefusalCode }, refusal: unknown): WebhookActionRefusalCode {\n\treturn typeof refusal === \"string\" && isOneOf(Object.keys(table), refusal) ? table[refusal]! : \"store_outcome_unknown\";\n}\n\n/**\n * The answer of a store write. `undefined` (the write threw, timed out or\n * answered something unreadable) is `store_outcome_unknown`: it may have\n * applied, so nothing follows it.\n */\nfunction applied(answer: { readonly value: unknown } | undefined, refusals: { readonly [refusal: string]: WebhookActionRefusalCode }): unknown {\n\tif (answer === undefined) return stop(\"store_outcome_unknown\");\n\tconst flag = prop(answer.value, \"applied\");\n\tif (flag === true) return answer.value;\n\tif (flag === false) return stop(mapRefusal(refusals, prop(answer.value, \"refusal\")));\n\treturn stop(\"store_outcome_unknown\");\n}\n\n/** The record an idempotent action names, as its evidence names it. */\ntype EvidenceTarget =\n\t| { readonly target: \"delivery_intent\"; readonly deliveryId: string }\n\t| { readonly target: \"fan_out_job\" | \"fan_out_job_actor\"; readonly eventId: string };\n\n/**\n * Evidence this invocation appended for `target`, by any attempt of it, or\n * `undefined` (always, without an invocation id). Read with the invocation\n * id alone, so it is found whether or not the record it names still exists.\n */\nasync function priorEvidence(deps: Deps, scope: WebhookScope, invocationId: string | undefined, target: EvidenceTarget): Promise<unknown> {\n\tif (invocationId === undefined) return undefined;\n\tconst answer = await port(deps, (options) => deps.deliveries.listInvocationRequeueEvidence({ ...scope, actionInvocationId: invocationId }, options));\n\tif (answer === undefined) return stop(\"store_unavailable\");\n\tconst list = answer.value as unknown;\n\tif (!Array.isArray(list)) return stop(\"store_unavailable\");\n\tfor (const evidence of list) {\n\t\tif (prop(evidence, \"actionInvocationId\") !== invocationId || prop(evidence, \"target\") !== target.target) continue;\n\t\tif (prop(evidence, \"tenantId\") !== scope.tenantId || prop(evidence, \"spaceId\") !== scope.spaceId) continue;\n\t\tif (target.target === \"delivery_intent\" ? prop(evidence, \"deliveryId\") === target.deliveryId : prop(evidence, \"eventId\") === target.eventId) return evidence;\n\t}\n\treturn undefined;\n}\n\n/**\n * One attempt of an idempotent action (requeue, enrichment). Host may run\n * several attempts of one invocation, one after another or overlapping (a\n * worker whose lease expired is still running when recovery starts\n * another). An attempt reports the invocation's change when that change's\n * evidence is visible to one of its evidence reads (steps 1 and 3) or to its\n * store's atomic step (step 2); only the evidence decides it. Not covered:\n * an attempt that ended in a refusal while an older attempt was between its\n * checks and its compare-and-set, and the older attempt commits later. That\n * change stands while Host has recorded the refusal; the evidence names the\n * invocation for an operator to reconcile (README, \"Atomicity and re-runs\").\n * The steps:\n *\n * 1. Before anything about the record is read, the invocation's evidence:\n * the record may since have been claimed, delivered or purged, and the\n * subscription paused or deleted.\n * 2. Otherwise `apply` runs the action's checks and the store's\n * compare-and-set. The store answers a request of an invocation that\n * already applied with that evidence (`replayed`), in the same atomic step\n * as the compare (src/ports.ts, \"Re-runs of one invocation\").\n * 3. An attempt that `apply` ends with a refusal reads the evidence once\n * more: another attempt that committed after step 1 is why a check before\n * the compare-and-set saw the record or subscription changed. If that read\n * fails, the refusal stands.\n *\n * Returns the evidence of the change the invocation made.\n */\nasync function oncePerInvocation(\n\tdeps: Deps,\n\tscope: WebhookScope,\n\tinvocationId: string | undefined,\n\ttarget: EvidenceTarget,\n\tapply: () => Promise<unknown>,\n): Promise<unknown> {\n\tconst prior = await priorEvidence(deps, scope, invocationId, target);\n\tif (prior !== undefined) return prior;\n\ttry {\n\t\treturn await apply();\n\t} catch (thrown) {\n\t\tif (invocationId === undefined) throw thrown;\n\t\tlet committed: unknown;\n\t\ttry {\n\t\t\tcommitted = await priorEvidence(deps, scope, invocationId, target);\n\t\t} catch {\n\t\t\tthrow thrown;\n\t\t}\n\t\tif (committed !== undefined) return committed;\n\t\tthrow thrown;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\ntype Handler<N extends WebhookDeliveryActionName> = (\n\tdeps: Deps,\n\tctx: ActionContext<unknown>,\n\tscope: WebhookScope,\n\tparams: WebhookDeliveryActionParameters[N],\n) => Promise<ActionResult>;\n\ntype Handlers = { readonly [N in WebhookDeliveryActionName]: Handler<N> };\n\nfunction subscriptionEvent(\n\teventType: WebhookDeliveryActionEventType,\n\tsubscriptionId: string,\n\tpayload: Record<string, unknown>,\n): ActionResult {\n\treturn emitted(eventType, SUBSCRIPTION, subscriptionId, { subscriptionId, ...payload });\n}\n\nfunction revisionOf(result: unknown): number {\n\tconst revision = whole(prop(prop(result, \"revision\"), \"revision\"));\n\treturn revision ?? stop(\"store_outcome_unknown\");\n}\n\nfunction versionOf(result: unknown): number {\n\tconst version = whole(prop(prop(result, \"configuration\"), \"version\"));\n\treturn version ?? stop(\"store_outcome_unknown\");\n}\n\n/** Pause and delete: the transition, then `cancelPendingIntents` for the intents of the revisions it ended. */\nasync function stopSubscription(\n\tdeps: Deps,\n\tscope: WebhookScope,\n\tparams: WebhookDeliveryActionParameters[\"pause_subscription\"],\n\tkind: \"pause\" | \"delete\",\n): Promise<ActionResult> {\n\tconst write = kind === \"pause\"\n\t\t? (options: WebhookCallOptions) => deps.subscriptions.pauseSubscription({ ...scope, ...params }, options)\n\t\t: (options: WebhookCallOptions) => deps.subscriptions.deleteSubscription({ ...scope, ...params }, options);\n\tconst revision = revisionOf(applied(await port(deps, write), SUBSCRIPTION_REFUSALS));\n\tconst cancelledPendingIntents = await cleanUp(deps, scope, params.subscriptionId, kind === \"pause\" ? \"subscription_paused\" : \"subscription_deleted\", revision);\n\treturn subscriptionEvent(kind === \"pause\" ? \"WebhookSubscriptionPaused\" : \"WebhookSubscriptionDeleted\", params.subscriptionId, {\n\t\trevision,\n\t\tcancelledPendingIntents,\n\t});\n}\n\n/**\n * Pause, resume and delete: after the revision is written, cancel the\n * subscription's pending intents bound to revisions before it. A cleanup,\n * not the guarantee: the count, or `null` when the call threw, timed out or\n * answered something unreadable, and the action stands either way. What\n * stops those intents is dispatch (src/delivery-cycle.ts, `readState`):\n * it cancels an intent while the subscription is paused or deleted, and\n * while it is active since a revision later than the intent's (README,\n * \"Pause and resume are enforced at dispatch\"). Passing the revision just\n * written leaves intents of any later revision alone.\n */\nasync function cleanUp(\n\tdeps: Deps,\n\tscope: WebhookScope,\n\tsubscriptionId: string,\n\treason: \"subscription_paused\" | \"subscription_deleted\",\n\tbeforeRevision: number,\n): Promise<number | null> {\n\tconst cancelled = await port(deps, (options) => deps.deliveries.cancelPendingIntents({\n\t\t...scope,\n\t\tsubscriptionId,\n\t\treason,\n\t\tbeforeRevision,\n\t\tnow: new Date(nowMs(deps)),\n\t}, options));\n\treturn (cancelled === undefined ? undefined : whole(cancelled.value)) ?? null;\n}\n\n/** Staged and emergency rotation: a new configuration version with the same destination and scheme, and the next secret reference. */\nasync function rotate(\n\tdeps: Deps,\n\tscope: WebhookScope,\n\tparams: { readonly subscriptionId: string; readonly secretRef: string; readonly expectedVersion?: number },\n\tmode: \"staged\" | \"emergency\",\n): Promise<ActionResult> {\n\tconst current = await currentSubscription(deps, scope, params.subscriptionId);\n\tif (current.status === \"deleted\") stop(\"subscription_deleted\");\n\tif (params.expectedVersion !== undefined && params.expectedVersion !== current.version) stop(\"version_conflict\");\n\tif (params.secretRef === current.secretRef) stop(\"secret_ref_unchanged\");\n\tawait verifySecretRef(deps, scope, params.secretRef);\n\tconst result = applied(await port(deps, (options) => deps.subscriptions.replaceDeliveryConfiguration({\n\t\t...scope,\n\t\tsubscriptionId: params.subscriptionId,\n\t\tconfiguration: { destinationUrl: current.destinationUrl, signatureScheme: current.signatureScheme, secretRef: params.secretRef },\n\t\t// The version read above, so a concurrent change between the read and\n\t\t// the write is refused by the store's compare-and-set.\n\t\texpectedVersion: params.expectedVersion ?? current.version,\n\t}, options)), SUBSCRIPTION_REFUSALS);\n\tconst configurationVersion = versionOf(result);\n\tconst activatedAtMs = nowMs(deps);\n\t// R6 and README, \"Old-secret retention\": a request signed with the old\n\t// secret reaches a receiver at most portTimeoutMs + attemptTimeoutMs after\n\t// activation (worker's clock), plus the receiver's timestamp tolerance.\n\tconst retainMs = deps.limits.portTimeoutMs + deps.limits.attemptTimeoutMs + deps.verifierToleranceMs;\n\treturn subscriptionEvent(\"WebhookSecretRotated\", params.subscriptionId, {\n\t\tmode,\n\t\tconfigurationVersion,\n\t\tactivatedAt: isoOf(activatedAtMs),\n\t\tpreviousSecretRetainUntil: mode === \"staged\" ? isoOf(activatedAtMs + retainMs) : null,\n\t});\n}\n\nconst HANDLERS: Handlers = freeze({\n\tasync create_subscription(deps, _ctx, scope, params) {\n\t\tawait verifySecretRef(deps, scope, params.secretRef);\n\t\tawait vetDestination(deps, params.destinationUrl);\n\t\tconst result = applied(await port(deps, (options) => deps.subscriptions.createSubscription({\n\t\t\t...scope,\n\t\t\tsubscriptionId: params.subscriptionId,\n\t\t\teventTypePatterns: params.eventTypePatterns,\n\t\t\tconfiguration: { destinationUrl: params.destinationUrl, signatureScheme: \"v1\", secretRef: params.secretRef },\n\t\t}, options)), SUBSCRIPTION_REFUSALS);\n\t\treturn subscriptionEvent(\"WebhookSubscriptionCreated\", params.subscriptionId, {\n\t\t\trevision: revisionOf(result),\n\t\t\tconfigurationVersion: versionOf(result),\n\t\t\teventTypePatterns: [...params.eventTypePatterns],\n\t\t});\n\t},\n\n\tasync update_subscription(deps, _ctx, scope, params) {\n\t\tif (\"eventTypePatterns\" in params) {\n\t\t\tconst result = applied(await port(deps, (options) => deps.subscriptions.changeEventTypePatterns({ ...scope, ...params }, options)), SUBSCRIPTION_REFUSALS);\n\t\t\treturn subscriptionEvent(\"WebhookSubscriptionUpdated\", params.subscriptionId, {\n\t\t\t\tchange: \"event_type_patterns\",\n\t\t\t\trevision: revisionOf(result),\n\t\t\t\teventTypePatterns: [...params.eventTypePatterns],\n\t\t\t});\n\t\t}\n\t\tconst current = await currentSubscription(deps, scope, params.subscriptionId);\n\t\tif (current.status === \"deleted\") stop(\"subscription_deleted\");\n\t\tif (params.expectedVersion !== undefined && params.expectedVersion !== current.version) stop(\"version_conflict\");\n\t\tawait vetDestination(deps, params.destinationUrl);\n\t\tconst result = applied(await port(deps, (options) => deps.subscriptions.replaceDeliveryConfiguration({\n\t\t\t...scope,\n\t\t\tsubscriptionId: params.subscriptionId,\n\t\t\tconfiguration: { destinationUrl: params.destinationUrl, signatureScheme: current.signatureScheme, secretRef: current.secretRef },\n\t\t\texpectedVersion: params.expectedVersion ?? current.version,\n\t\t}, options)), SUBSCRIPTION_REFUSALS);\n\t\treturn subscriptionEvent(\"WebhookSubscriptionUpdated\", params.subscriptionId, {\n\t\t\tchange: \"destination\",\n\t\t\tconfigurationVersion: versionOf(result),\n\t\t});\n\t},\n\n\tpause_subscription: (deps, _ctx, scope, params) => stopSubscription(deps, scope, params, \"pause\"),\n\n\tasync resume_subscription(deps, _ctx, scope, params) {\n\t\t// Resume does not resurrect (decision 3): a cancelled intent is\n\t\t// terminal, dispatch cancels any intent bound to a revision before\n\t\t// this one (the pause's cleanup may have missed it, or fan-out written\n\t\t// it late), and intent requeue refuses one (`paused_since_intent`).\n\t\t// The cleanup below cancels what is pending now, so it does not sit\n\t\t// until a worker claims it.\n\t\tconst result = applied(await port(deps, (options) => deps.subscriptions.resumeSubscription({ ...scope, ...params }, options)), SUBSCRIPTION_REFUSALS);\n\t\tconst revision = revisionOf(result);\n\t\tconst cancelledPendingIntents = await cleanUp(deps, scope, params.subscriptionId, \"subscription_paused\", revision);\n\t\treturn subscriptionEvent(\"WebhookSubscriptionResumed\", params.subscriptionId, { revision, cancelledPendingIntents });\n\t},\n\n\tdelete_subscription: (deps, _ctx, scope, params) => stopSubscription(deps, scope, params, \"delete\"),\n\n\trotate_secret_staged: (deps, _ctx, scope, params) => rotate(deps, scope, params, \"staged\"),\n\n\trotate_secret_emergency: (deps, _ctx, scope, params) => rotate(deps, scope, params, \"emergency\"),\n\n\tasync requeue_delivery_intent(deps, ctx, scope, params) {\n\t\tconst requestedBy = actorOf(ctx);\n\t\tconst invocationId = invocationOf(ctx);\n\t\tconst evidence = await oncePerInvocation(deps, scope, invocationId, { target: \"delivery_intent\", deliveryId: params.deliveryId }, async () => {\n\t\t\tconst read = await port(deps, (options) => deps.deliveries.readDeliveryIntent({ ...scope, deliveryId: params.deliveryId }, options));\n\t\t\tif (read === undefined) return stop(\"store_unavailable\");\n\t\t\tif (read.value === null) return stop(\"not_found\");\n\t\t\tconst subscriptionId = prop(read.value, \"subscriptionId\");\n\t\t\tconst eligibilityRevision = whole(prop(read.value, \"eligibilityRevision\"));\n\t\t\tif (!isWebhookIdentifier(subscriptionId) || eligibilityRevision === undefined) return stop(\"store_unavailable\");\n\t\t\t// Decision 10: the destination is re-validated at requeue. Dispatch\n\t\t\t// resolves it again before every attempt regardless.\n\t\t\tconst subscription = await currentSubscription(deps, scope, subscriptionId);\n\t\t\tif (subscription.status !== \"active\") stop(\"subscription_not_active\");\n\t\t\t// Paused and resumed since the intent's revision: dispatch would\n\t\t\t// cancel it, so it is not requeued (decision 3). A pause and resume\n\t\t\t// between this read and the compare-and-set is still caught there.\n\t\t\tif (eligibilityRevision < subscription.statusSinceRevision) stop(\"paused_since_intent\");\n\t\t\tawait vetDestination(deps, subscription.destinationUrl);\n\t\t\tconst now = nowMs(deps);\n\t\t\treturn prop(applied(await port(deps, (options) => deps.deliveries.requeueDeliveryIntent({\n\t\t\t\t...scope,\n\t\t\t\tdeliveryId: params.deliveryId,\n\t\t\t\t// The compare-and-set is the store's: fence and status are checked\n\t\t\t\t// in the same atomic step as the transition (src/ports.ts).\n\t\t\t\trequest: {\n\t\t\t\t\texpectedStatus: \"dead_letter\",\n\t\t\t\t\texpectedFence: params.expectedFence,\n\t\t\t\t\trequestedBy,\n\t\t\t\t\trequestedAt: new Date(now),\n\t\t\t\t\tprocessingDeadline: new Date(now + deps.limits.deliveryDeadlineMs),\n\t\t\t\t\t...(invocationId === undefined ? {} : { actionInvocationId: invocationId }),\n\t\t\t\t},\n\t\t\t}, options)), DELIVERY_REFUSALS), \"evidence\");\n\t\t});\n\t\t// From the evidence, not the intent, which a re-run may find purged.\n\t\tconst eventId = prop(evidence, \"eventId\");\n\t\tif (!isWebhookIdentifier(eventId)) return stop(\"store_outcome_unknown\");\n\t\tconst subscriptionId = prop(evidence, \"subscriptionId\") ?? await legacyIntentSubscription(deps, scope, params.deliveryId, eventId);\n\t\tif (!isWebhookIdentifier(subscriptionId)) return stop(\"store_outcome_unknown\");\n\t\treturn emitted(\"WebhookDeliveryIntentRequeued\", INTENT, params.deliveryId, {\n\t\t\tdeliveryId: params.deliveryId,\n\t\t\tsubscriptionId,\n\t\t\teventId,\n\t\t\t...evidenceFields(evidence),\n\t\t});\n\t},\n\n\tasync requeue_fan_out_job(deps, ctx, scope, params) {\n\t\tconst requestedBy = actorOf(ctx);\n\t\tconst invocationId = invocationOf(ctx);\n\t\tconst evidence = await oncePerInvocation(deps, scope, invocationId, { target: \"fan_out_job\", eventId: params.eventId }, async () => {\n\t\t\tconst now = nowMs(deps);\n\t\t\treturn prop(applied(await port(deps, (options) => deps.deliveries.requeueFanOutJob({\n\t\t\t\t...scope,\n\t\t\t\teventId: params.eventId,\n\t\t\t\trequest: {\n\t\t\t\t\texpectedStatus: \"dead_letter\",\n\t\t\t\t\texpectedFence: params.expectedFence,\n\t\t\t\t\trequestedBy,\n\t\t\t\t\trequestedAt: new Date(now),\n\t\t\t\t\tprocessingDeadline: new Date(now + deps.limits.fanOutDeadlineMs),\n\t\t\t\t\t...(invocationId === undefined ? {} : { actionInvocationId: invocationId }),\n\t\t\t\t},\n\t\t\t}, options)), DELIVERY_REFUSALS), \"evidence\");\n\t\t});\n\t\treturn emitted(\"WebhookFanOutJobRequeued\", JOB, params.eventId, { eventId: params.eventId, ...evidenceFields(evidence) });\n\t},\n\n\tasync enrich_fan_out_job_actor(deps, ctx, scope, params) {\n\t\tconst requestedBy = actorOf(ctx);\n\t\tconst invocationId = invocationOf(ctx);\n\t\tconst evidence = await oncePerInvocation(deps, scope, invocationId, { target: \"fan_out_job_actor\", eventId: params.eventId }, async () => {\n\t\t\tconst read = await port(deps, (options) => deps.deliveries.readFanOutJob({ ...scope, eventId: params.eventId }, options));\n\t\t\tif (read === undefined) return stop(\"store_unavailable\");\n\t\t\tif (read.value === null) return stop(\"not_found\");\n\t\t\t// Early refusals, so the application's reader is not asked for an\n\t\t\t// actor that would be refused. The store re-checks each in its\n\t\t\t// atomic step; these are not the guard.\n\t\t\tconst actor = prop(read.value, \"actor\");\n\t\t\tif (prop(read.value, \"status\") === \"completed\") return stop(\"not_enrichable\");\n\t\t\tif (prop(actor, \"state\") === \"present\") return stop(\"actor_present\");\n\t\t\tif (prop(actor, \"reason\") === \"suppressed\") return stop(\"actor_suppressed\");\n\t\t\tconst event = prop(read.value, \"event\");\n\t\t\tconst eventType = prop(event, \"eventType\");\n\t\t\tconst payloadClassification = prop(event, \"payloadClassification\");\n\t\t\tif (typeof eventType !== \"string\" || typeof payloadClassification !== \"string\") return stop(\"store_unavailable\");\n\t\t\tconst found = await port(deps, (options) => deps.actorReader.readEventActor({ ...scope, eventId: params.eventId, eventType, payloadClassification }, options));\n\t\t\tif (found === undefined) return stop(\"actor_unavailable\");\n\t\t\tconst state = prop(found.value, \"state\");\n\t\t\tif (state === \"withheld\") return stop(\"actor_withheld\");\n\t\t\tif (state === \"not_found\") return stop(\"actor_not_found\");\n\t\t\tconst actorId = prop(found.value, \"actorId\");\n\t\t\tconst actorType = prop(found.value, \"actorType\");\n\t\t\tif (state !== \"found\" || !isWebhookIdentifier(actorId) || !isWebhookIdentifier(actorType)) return stop(\"actor_unavailable\");\n\t\t\tconst now = nowMs(deps);\n\t\t\treturn prop(applied(await port(deps, (options) => deps.deliveries.enrichFanOutJobActor({\n\t\t\t\t...scope,\n\t\t\t\teventId: params.eventId,\n\t\t\t\trequest: {\n\t\t\t\t\texpectedFence: params.expectedFence,\n\t\t\t\t\tactor: { actorId, actorType },\n\t\t\t\t\trequestedBy,\n\t\t\t\t\trequestedAt: new Date(now),\n\t\t\t\t\tprocessingDeadline: new Date(now + deps.limits.fanOutDeadlineMs),\n\t\t\t\t\t...(invocationId === undefined ? {} : { actionInvocationId: invocationId }),\n\t\t\t\t},\n\t\t\t}, options)), DELIVERY_REFUSALS), \"evidence\");\n\t\t});\n\t\t// The actor itself stays in the store's evidence, not in the event.\n\t\treturn emitted(\"WebhookFanOutJobActorEnriched\", JOB, params.eventId, { eventId: params.eventId, ...evidenceFields(evidence) });\n\t},\n});\n\n/**\n * The subscription of a requeued intent whose evidence was written before\n * evidence named it (`WebhookRequeueEvidence.subscriptionId`), read from the\n * intent in the invocation's scope. The requeue has applied, so a purged\n * intent, one of another event, or a read that fails is\n * `store_outcome_unknown`: the change stands without its event, for an\n * operator to reconcile from the evidence (README, \"Atomicity and re-runs\").\n */\nasync function legacyIntentSubscription(deps: Deps, scope: WebhookScope, deliveryId: string, eventId: string): Promise<string> {\n\tconst read = await port(deps, (options) => deps.deliveries.readDeliveryIntent({ ...scope, deliveryId }, options));\n\tconst subscriptionId = prop(read?.value, \"subscriptionId\");\n\tif (read === undefined || read.value === null || prop(read.value, \"eventId\") !== eventId || !isWebhookIdentifier(subscriptionId)) {\n\t\treturn stop(\"store_outcome_unknown\");\n\t}\n\treturn subscriptionId;\n}\n\n/** The event fields taken from requeue or enrichment evidence: numbers and timestamps only. */\nfunction evidenceFields(evidence: unknown): Record<string, unknown> {\n\tconst priorFence = whole(prop(evidence, \"priorFence\"));\n\tconst priorAttemptCount = whole(prop(evidence, \"priorAttemptCount\"));\n\tconst processingDeadline = prop(evidence, \"processingDeadline\");\n\tif (priorFence === undefined || priorAttemptCount === undefined || typeof processingDeadline !== \"string\") return stop(\"store_outcome_unknown\");\n\treturn { priorFence, priorAttemptCount, processingDeadline };\n}\n\nconst dateGetTime = Date.prototype.getTime;\n\n/**\n * Host's record that this invocation's submission passed the action's\n * admission check. A Host older than 7.3.0 ignores `admitSubmission` and\n * passes no `admittedAt`; such a Host may already have persisted unchecked\n * parameters, so the action refuses rather than act on them.\n */\nfunction requireAdmission(ctx: ActionContext<unknown>): void {\n\tconst admittedAt = prop(ctx, \"admittedAt\");\n\tif (!(admittedAt instanceof Date) || !Number.isFinite(Reflect.apply(dateGetTime, admittedAt, []))) stop(\"admission_not_enforced\");\n}\n\n/** The handler Host calls: requires Host's admission record, re-reads the parameters, takes the scope from Host's context, never lets a throw out. */\nfunction handlerFor<N extends WebhookDeliveryActionName>(deps: Deps, name: N) {\n\tconst run = HANDLERS[name] as Handler<N>;\n\treturn async (ctx: ActionContext<unknown>, parameters: unknown): Promise<ActionResult> => {\n\t\ttry {\n\t\t\trequireAdmission(ctx);\n\t\t\tconst read = readWebhookActionParameters(name, parameters);\n\t\t\tif (!read.ok) return { success: false, error: `webhook_parameters_refused:${read.code}` };\n\t\t\treturn await run(deps, ctx, scopeOf(ctx), read.value);\n\t\t} catch (thrown) {\n\t\t\t// Only a package `Stop` is read, and its code is checked against the\n\t\t\t// fixed set again; anything else is dropped unread.\n\t\t\treturn refused(Stop.is(thrown) && isOneOf(WEBHOOK_ACTION_REFUSAL_CODES, thrown.code) ? thrown.code : \"action_failed\");\n\t\t}\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Admission\n// ---------------------------------------------------------------------------\n\n/** The actions whose parameters carry a secret reference, verified at admission and again before the write. */\nconst TAKES_SECRET_REF: readonly WebhookDeliveryActionName[] = freeze([\"create_subscription\", \"rotate_secret_staged\", \"rotate_secret_emergency\"] as const);\n\nfunction refusedAdmission(code: string): ActionAdmissionDecision {\n\treturn freeze({ admitted: false as const, code });\n}\n\nconst ADMITTED: ActionAdmissionDecision = freeze({ admitted: true as const });\n\n/**\n * The action's `admitSubmission` (ADR 0018 decision 8). Host runs it on\n * every submission, after authorizing the submitter and before it records\n * anything, with its own copy of the parameters and the submission's trusted\n * tenant, space and actor. It admits only parameters the package reader\n * accepts and, for an action that takes a `secretRef`, only a reference the\n * application's `secretReferences.verify` confirms for that tenant and space.\n * A refusal's code is fixed text: `webhook_parameters_refused:<code>:<field>`\n * (`WEBHOOK_ACTION_PARAMETER_CODES`, a declared field or `parameters`) or\n * `webhook_action_refused:<code>` (`WEBHOOK_ACTION_REFUSAL_CODES`). Never\n * throws; nothing a port throws is read.\n */\nfunction admissionFor(deps: Deps, name: WebhookDeliveryActionName): ActionAdmission {\n\tconst takesSecretRef = TAKES_SECRET_REF.includes(name);\n\treturn async (input) => {\n\t\ttry {\n\t\t\tconst read = readWebhookActionParameters(name, prop(input, \"parameters\"));\n\t\t\tif (!read.ok) return refusedAdmission(`webhook_parameters_refused:${read.code}:${read.field}`);\n\t\t\tif (takesSecretRef) {\n\t\t\t\tconst tenantId = prop(input, \"tenantId\");\n\t\t\t\tconst spaceId = prop(input, \"spaceId\");\n\t\t\t\tif (!isWebhookIdentifier(tenantId) || !isWebhookIdentifier(spaceId)) stop(\"scope_invalid\");\n\t\t\t\tconst signal = prop(input, \"signal\");\n\t\t\t\tawait verifySecretRef(deps, freeze({ tenantId, spaceId }), (read.value as { readonly secretRef: string }).secretRef, signal instanceof AbortSignal ? signal : undefined);\n\t\t\t}\n\t\t\treturn ADMITTED;\n\t\t} catch (thrown) {\n\t\t\treturn refusedAdmission(`webhook_action_refused:${Stop.is(thrown) && isOneOf(WEBHOOK_ACTION_REFUSAL_CODES, thrown.code) ? thrown.code : \"action_failed\"}`);\n\t\t}\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Policy\n// ---------------------------------------------------------------------------\n\nfunction block(policyId: `${string}.v${number}`, reason: string): PolicyOutcome {\n\treturn { policyId, policyVersion: 1, policyKind: \"code\", result: \"block\", reason };\n}\n\nfunction operatorPolicy(deps: Deps): PolicyEvaluator {\n\tconst policyId = webhookOperatorPolicyId(deps.namespace);\n\treturn freeze({\n\t\tpolicyId,\n\t\tversion: 1,\n\t\tkind: \"code\" as const,\n\t\tasync evaluate(ctx: PolicyContext): Promise<PolicyOutcome> {\n\t\t\ttry {\n\t\t\t\tconst action = webhookActionNameOf(deps.namespace, ctx.actionId);\n\t\t\t\tif (action === undefined) return block(policyId, \"action_not_in_module\");\n\t\t\t\tconst read = readWebhookActionParameters(action, ctx.parameters);\n\t\t\t\tif (!read.ok) return block(policyId, \"parameters_invalid\");\n\t\t\t\tconst { tenantId, spaceId, actorId, actorType } = ctx;\n\t\t\t\tif (!isWebhookIdentifier(tenantId) || !isWebhookIdentifier(spaceId) || !isWebhookIdentifier(actorId) || typeof actorType !== \"string\") {\n\t\t\t\t\treturn block(policyId, \"operator_identity_unavailable\");\n\t\t\t\t}\n\t\t\t\tconst value = read.value as Record<string, unknown>;\n\t\t\t\tconst target = freeze({\n\t\t\t\t\t...(typeof value[\"subscriptionId\"] === \"string\" ? { subscriptionId: value[\"subscriptionId\"] } : {}),\n\t\t\t\t\t...(typeof value[\"deliveryId\"] === \"string\" ? { deliveryId: value[\"deliveryId\"] } : {}),\n\t\t\t\t\t...(typeof value[\"eventId\"] === \"string\" ? { eventId: value[\"eventId\"] } : {}),\n\t\t\t\t});\n\t\t\t\tconst input = freeze({ actionId: ctx.actionId, action, tenantId, spaceId, actorId, actorType, target });\n\t\t\t\tconst answer = await port(deps, async (options) => apply(deps.authorize, undefined, [input, options]));\n\t\t\t\tif (answer === undefined) return block(policyId, \"operator_authorization_unavailable\");\n\t\t\t\tif (answer.value !== true) return block(policyId, \"operator_not_authorized\");\n\t\t\t\treturn { policyId, policyVersion: 1, policyKind: \"code\", result: \"pass\" };\n\t\t\t} catch {\n\t\t\t\treturn block(policyId, \"operator_authorization_unavailable\");\n\t\t\t}\n\t\t},\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// The module\n// ---------------------------------------------------------------------------\n\nconst EVENT_FOR: { readonly [N in WebhookDeliveryActionName]: readonly WebhookDeliveryActionEventType[] } = freeze({\n\tcreate_subscription: freeze([\"WebhookSubscriptionCreated\"] as const),\n\tupdate_subscription: freeze([\"WebhookSubscriptionUpdated\"] as const),\n\tpause_subscription: freeze([\"WebhookSubscriptionPaused\"] as const),\n\tresume_subscription: freeze([\"WebhookSubscriptionResumed\"] as const),\n\tdelete_subscription: freeze([\"WebhookSubscriptionDeleted\"] as const),\n\trotate_secret_staged: freeze([\"WebhookSecretRotated\"] as const),\n\trotate_secret_emergency: freeze([\"WebhookSecretRotated\"] as const),\n\trequeue_delivery_intent: freeze([\"WebhookDeliveryIntentRequeued\"] as const),\n\trequeue_fan_out_job: freeze([\"WebhookFanOutJobRequeued\"] as const),\n\tenrich_fan_out_job_actor: freeze([\"WebhookFanOutJobActorEnriched\"] as const),\n});\n\n/** An attempt of one invocation of these reports the change another attempt committed when its evidence reads or the store's atomic step see it (`oncePerInvocation`, with its one exception); the others are not re-run by Host. */\nconst IDEMPOTENT: readonly WebhookDeliveryActionName[] = freeze([\"requeue_delivery_intent\", \"requeue_fan_out_job\", \"enrich_fan_out_job_actor\"] as const);\n\nfunction readDeps(options: WebhookDeliveryModuleOptions): Deps {\n\tconst fail = (field: string): never => {\n\t\tthrow governedActionError(\"options_invalid\", field);\n\t};\n\tif (options === null || typeof options !== \"object\") fail(\"options\");\n\tconst namespace = options.namespace ?? DEFAULT_WEBHOOK_DELIVERY_NAMESPACE;\n\tif (!isWebhookDeliveryNamespace(namespace)) fail(\"namespace\");\n\tconst needs = (value: unknown, field: string, methods: readonly string[]) => {\n\t\tif (value === null || typeof value !== \"object\") fail(field);\n\t\tfor (const method of methods) if (typeof (value as Record<string, unknown>)[method] !== \"function\") fail(`${field}.${method}`);\n\t};\n\tneeds(options.subscriptions, \"subscriptions\", [\n\t\t\"readSubscription\", \"createSubscription\", \"changeEventTypePatterns\", \"pauseSubscription\", \"resumeSubscription\", \"deleteSubscription\", \"replaceDeliveryConfiguration\",\n\t]);\n\tneeds(options.deliveries, \"deliveries\", [\n\t\t\"readDeliveryIntent\", \"readFanOutJob\", \"requeueDeliveryIntent\", \"requeueFanOutJob\", \"enrichFanOutJobActor\", \"cancelPendingIntents\", \"listInvocationRequeueEvidence\",\n\t]);\n\tneeds(options.resolver, \"resolver\", [\"resolve\"]);\n\tneeds(options.secretReferences, \"secretReferences\", [\"verify\"]);\n\tneeds(options.actorReader, \"actorReader\", [\"readEventActor\"]);\n\tif (typeof options.authorizeOperatorAction !== \"function\") fail(\"authorizeOperatorAction\");\n\tlet clock: FanOutClock;\n\ttry {\n\t\tclock = captureFanOutClock(options.clock);\n\t} catch {\n\t\treturn fail(\"clock\");\n\t}\n\tconst limits = resolveWebhookDeliveryLimits(options.limits ?? {});\n\tconst verifierToleranceMs = options.verifierToleranceMs ?? 300_000;\n\tassertPositiveInteger(verifierToleranceMs, \"verifierToleranceMs\");\n\treturn freeze({\n\t\tnamespace,\n\t\tsubscriptions: options.subscriptions,\n\t\tdeliveries: options.deliveries,\n\t\tresolver: options.resolver,\n\t\tsecretReferences: options.secretReferences,\n\t\tactorReader: options.actorReader,\n\t\tauthorize: options.authorizeOperatorAction,\n\t\tclock,\n\t\tlimits,\n\t\tverifierToleranceMs,\n\t});\n}\n\n/**\n * Build the package's governed operator actions as one `FabricModule`\n * (README, \"Governed actions\"). Register it with `createModuleRegistry()`\n * and run it through `createGovernedActionHost()` from\n * `@fabricorg/platform-host` 7.3.0 or later: every action declares\n * `admitSubmission`, which that Host runs before it records a submission,\n * and refuses to run without Host's admission record. Nothing needs wiring\n * into Host for it.\n *\n * @throws {WebhookGovernedActionError} `options_invalid` when a port or\n * option is missing or malformed.\n * @throws {WebhookDeliveryConfigError} when a limit or `verifierToleranceMs`\n * is not a positive whole number.\n */\nexport function createWebhookDeliveryModule<TDb = unknown>(options: WebhookDeliveryModuleOptions): FabricModule<TDb> {\n\tconst deps = readDeps(options);\n\tconst policy = operatorPolicy(deps);\n\tconst actions: ActionDefinition<TDb>[] = WEBHOOK_DELIVERY_ACTION_NAMES.map((name) => {\n\t\tconst idempotent = IDEMPOTENT.includes(name);\n\t\tconst definition: ActionDefinition<TDb> = {\n\t\t\tactionId: `${deps.namespace}.${name}`,\n\t\t\tnamespace: deps.namespace,\n\t\t\tversion: 1,\n\t\t\tkind: \"atomic\",\n\t\t\tschema: webhookActionSchema(name),\n\t\t\tadmitSubmission: admissionFor(deps, name),\n\t\t\tpolicies: [policy.policyId],\n\t\t\temitsEvents: [...EVENT_FOR[name]],\n\t\t\tidempotent,\n\t\t\tmutatesDomain: true,\n\t\t\texecution: {\n\t\t\t\tconnectivity: \"online-required\",\n\t\t\t\tauthorityMoment: \"execution\",\n\t\t\t\tidempotency: \"supported\",\n\t\t\t\tcompletion: \"immediate\",\n\t\t\t\tconsistency: \"authoritative-now\",\n\t\t\t\tsensitivity: \"confidential\",\n\t\t\t},\n\t\t\tsurface: \"internal\",\n\t\t\tsurfaceReason: \"Operator mutation of webhook subscriptions and delivery records.\",\n\t\t\thandler: handlerFor(deps, name) as ActionDefinition<TDb>[\"handler\"],\n\t\t};\n\t\treturn definition;\n\t});\n\treturn {\n\t\tnamespace: deps.namespace,\n\t\tversion: \"1.0.0\",\n\t\tdisplayName: \"Webhook delivery\",\n\t\tdescription: \"Governed operator actions for webhook subscriptions, secret rotation, requeue and actor enrichment (ADR 0018).\",\n\t\tsubjectTypes: [SUBSCRIPTION, INTENT, JOB],\n\t\teventTypes: WEBHOOK_DELIVERY_ACTION_EVENT_TYPES.map((eventType) => ({ eventType, schemaVersion: 1 })),\n\t\tactions,\n\t\tpolicies: [policy],\n\t};\n}\n"]}
1
+ {"version":3,"file":"index.js","names":["reflectOwnKeys","reflectGetOwnPropertyDescriptor","reflectDefineProperty","objectCreate","dateGetTime","DateConstructor","numberIsFinite","numberIsSafeInteger","NumberConstructor","mathMin","mathMax","reflectDefineProperty","numberIsFinite","numberIsSafeInteger","DateConstructor","numberIsSafeInteger","abortedGetter","isAborted","readClock","copyOut","compareText","entry","mathMin","readActor","hex","ioBoundary","readClock","mathMax","copyOut","compareText","refused","mathMax","readClock","refused","readClock","compareText","mathMax","copyOut","refused","unreadable","unreadableFail","numberIsSafeInteger","mathMin","unreadable","unreadableFail","numberIsSafeInteger","NumberConstructor","numberIsFinite","mathMin","mathMax","EMPTY","numberIsSafeInteger","unreadable","unreadableFail","numberIsSafeInteger","stringSlice","reflectGetOwnPropertyDescriptor","abortedGetter","setTimer","clearTimer","unreadable","unreadableFail","unreadableFail","numberIsSafeInteger","UNREADABLE","numberIsFinite","ABORTED","refuse","REFUSED","nonEmpty","whole","numberIsSafeInteger","raw","plain","numberIsFinite","MAX_CLAIMED","STATUSES","INSERT_OUTCOMES","hasMethods","positiveWhole","readConfig","readConfigUnguarded","deadLetter","keepLease","mathMin","retryOrDeadLetter","numberIsFinite","refuse","whole","numberIsSafeInteger","numberIsFinite","numberIsFinite","mathMin","mathMax","numberIsSafeInteger","whole","numberIsSafeInteger"],"sources":["../src/codes.ts","../src/snapshot.ts","../src/errors.ts","../src/limits.ts","../src/store-input.ts","../src/delivery-store-core.ts","../src/receipt.ts","../src/memory-delivery-store.ts","../src/subscription-store-core.ts","../src/memory-subscription-store.ts","../src/postgres-sql.ts","../src/postgres-delivery-store.ts","../src/postgres-subscription-store.ts","../src/retry.ts","../src/classify.ts","../src/persistence-projection.ts","../src/egress.ts","../src/headers.ts","../src/address.ts","../src/call-bounds.ts","../src/destination.ts","../src/decisions.ts","../src/fan-out-call.ts","../src/fan-out-read.ts","../src/fan-out-publisher.ts","../src/action-events.ts","../src/fan-out-cycle.ts","../src/delivery-read.ts","../src/delivery-cycle.ts","../src/action-parameters.ts","../src/governed-actions.ts"],"sourcesContent":["/**\n * Fixed code sets. Stored diagnostics, denial reasons and attempt outcomes are\n * typed as one of these codes rather than a free string or a port's error\n * message (ADR 0018 decision 2), so a thrown error has no field through which\n * to carry payload, secret or response-body text into a durable record. The\n * arrays are frozen, so no caller can widen a set at runtime.\n */\n\n/** Reasons an admission port may give for `deny`. */\nexport const WEBHOOK_ADMISSION_DENIAL_CODES = Object.freeze([\n\t\"actor_not_permitted\",\n\t\"scope_not_permitted\",\n\t\"event_type_not_permitted\",\n\t\"classification_not_permitted\",\n\t\"policy_denied\",\n] as const);\n\n/** A reason code carried by an admission `deny` decision and stored on its denial record. */\nexport type WebhookAdmissionDenialCode = (typeof WEBHOOK_ADMISSION_DENIAL_CODES)[number];\n\n/** Reasons a delivery authorization port may give for `revoked`. */\nexport const WEBHOOK_REVOCATION_CODES = Object.freeze([\n\t\"grant_expired\",\n\t\"scope_revoked\",\n\t\"registration_inactive\",\n] as const);\n\n/** A reason code carried by a delivery authorization `revoked` decision. */\nexport type WebhookRevocationCode = (typeof WEBHOOK_REVOCATION_CODES)[number];\n\n/**\n * Diagnostics stored on a fan-out job or delivery intent when a port failed,\n * timed out or a coordination check refused the work. A port exception is\n * stored as the code for that port, not as its message.\n *\n * Three are written only by the fan-out cycle: `eligibility_unsettled` when\n * it defers a job until its event's eligibility is settled (README,\n * \"Fan-out\"), `intent_build_failed` when it could not render a body or\n * create a delivery id for an admitted subscription, and `job_unreadable`\n * when it dead-letters a claimed job whose identity and lease it could read\n * but whose body it could not.\n *\n * Three are written only by the delivery cycle (README, \"Delivery\"):\n * `intent_unreadable` when it dead-letters a claimed intent whose identity\n * and lease it could read but whose body it could not,\n * `subscription_not_in_scope` when the intent's subscription does not exist\n * in the intent's tenant and space, or the store's answer names another\n * one, and `transport_not_sent` when the transport returned `not_sent` for\n * a request it never started.\n */\nexport const WEBHOOK_DIAGNOSTIC_CODES = Object.freeze([\n\t\"admission_unavailable\",\n\t\"authorization_unavailable\",\n\t\"subscription_store_unavailable\",\n\t\"delivery_store_unavailable\",\n\t\"signer_unavailable\",\n\t\"resolver_unavailable\",\n\t\"port_timeout\",\n\t\"scope_predicate_failed\",\n\t\"configuration_conflict\",\n\t\"lease_lost\",\n\t\"intent_not_pending\",\n\t\"processing_deadline_exceeded\",\n\t\"eligibility_unsettled\",\n\t\"intent_build_failed\",\n\t\"job_unreadable\",\n\t\"intent_unreadable\",\n\t\"subscription_not_in_scope\",\n\t\"transport_not_sent\",\n] as const);\n\n/** A stored diagnostic code for a port failure or refused coordination check. */\nexport type WebhookDiagnosticCode = (typeof WEBHOOK_DIAGNOSTIC_CODES)[number];\n\n/**\n * What a delivery attempt's observation means for its intent (ADR 0018\n * decision 10). `not_sent` is never a classification: the delivery cycle\n * records it, with the reason `not_sent`, on an attempt it began under the\n * intent's lease and handed to the transport, when the transport answered\n * that it never started the request (its deadline had passed or its signal\n * had aborted while the request was queued). Such an attempt spends no budget.\n */\nexport const WEBHOOK_ATTEMPT_OUTCOMES = Object.freeze([\n\t\"delivered\",\n\t\"retryable\",\n\t\"dead_letter\",\n\t\"cancelled\",\n\t\"not_sent\",\n] as const);\n\n/**\n * The classified result of one attempt. A 401 or 403 is `retryable` like any\n * other row of that kind; its `http_401` / `http_403` reason and the\n * classification's `receiverActionLikely` flag let the caller surface it to\n * operators before the retry budget is exhausted.\n */\nexport type WebhookAttemptOutcome = (typeof WEBHOOK_ATTEMPT_OUTCOMES)[number];\n\n/** The row of decision 10's table an observation matched. */\nexport const WEBHOOK_ATTEMPT_REASON_CODES = Object.freeze([\n\t\"http_2xx\",\n\t\"network_error\",\n\t\"timeout\",\n\t\"dns_failure\",\n\t\"http_408\",\n\t\"http_425\",\n\t\"http_429\",\n\t\"http_5xx\",\n\t\"signer_unavailable\",\n\t\"http_401\",\n\t\"http_403\",\n\t\"http_1xx\",\n\t\"http_3xx\",\n\t\"http_410\",\n\t\"http_4xx\",\n\t\"invalid_url\",\n\t\"private_address\",\n\t\"authorization_revoked\",\n\t\"subscription_paused\",\n\t\"subscription_deleted\",\n\t\"not_sent\",\n] as const);\n\n/** The reason code recorded with an attempt outcome. */\nexport type WebhookAttemptReasonCode = (typeof WEBHOOK_ATTEMPT_REASON_CODES)[number];\n\n/** Codes on {@link WebhookDeliveryConfigError}. */\nexport const WEBHOOK_CONFIG_ERROR_CODES = Object.freeze([\n\t\"limit_not_positive_finite\",\n\t\"limit_not_integer\",\n\t\"limit_out_of_range\",\n\t\"retry_schedule_empty\",\n\t\"limit_unreadable\",\n] as const);\n\n/** Why a configured limit was rejected. */\nexport type WebhookConfigErrorCode = (typeof WEBHOOK_CONFIG_ERROR_CODES)[number];\n\n/** Codes on {@link WebhookProjectionError}. */\nexport const WEBHOOK_PROJECTION_ERROR_CODES = Object.freeze([\n\t\"invalid_envelope\",\n\t\"payload_field_not_json\",\n\t\"fact_field_not_json\",\n\t\"accessor_property\",\n\t\"inspection_failed\",\n\t\"scope_mismatch\",\n] as const);\n\n/** Why an envelope could not be projected. */\nexport type WebhookProjectionErrorCode = (typeof WEBHOOK_PROJECTION_ERROR_CODES)[number];\n\n/**\n * Codes on the `TypeError` and `RangeError` instances this package throws\n * for malformed call input (headers, classification, retry, admission).\n * Each code has one constant message; neither repeats the input.\n */\nexport const WEBHOOK_INPUT_ERROR_CODES = Object.freeze([\n\t\"input_unreadable\",\n\t\"observation_unknown\",\n\t\"status_out_of_range\",\n\t\"signature_malformed\",\n\t\"timestamp_invalid\",\n\t\"event_id_invalid\",\n\t\"delivery_id_invalid\",\n\t\"attempt_invalid\",\n\t\"raw_body_not_string\",\n\t\"random_source_missing\",\n\t\"random_sample_invalid\",\n\t\"random_source_failed\",\n\t\"denial_code_unknown\",\n] as const);\n\n/** Why call input was refused. */\nexport type WebhookInputErrorCode = (typeof WEBHOOK_INPUT_ERROR_CODES)[number];\n\n/**\n * Codes on {@link WebhookStoreError}: a store call that was malformed, broke\n * a store invariant, or was no longer wanted when the store reached its\n * write. Refusals the caller is expected to handle (a lost lease, an\n * existing key, a replay past the horizon, a requeue of a record that is not\n * dead-lettered) are results, not errors.\n */\nexport const WEBHOOK_STORE_ERROR_CODES = Object.freeze([\n\t\"input_invalid\",\n\t\"record_mismatch\",\n\t\"delivery_id_conflict\",\n\t\"call_aborted\",\n\t\"deadline_passed\",\n\t\"clock_invalid\",\n\t\"store_failed\",\n] as const);\n\n/** Why a store call was refused. */\nexport type WebhookStoreErrorCode = (typeof WEBHOOK_STORE_ERROR_CODES)[number];\n\n/**\n * Codes on {@link WebhookFanOutError}: why the fan-out publisher, the\n * composite publisher or the fan-out cycle refused or failed. A publisher\n * rejection makes the Host relay retry and, once its budget is spent,\n * dead-letter the outbox record, so a failed publish stays visible there.\n *\n * - `event_past_replay_horizon`: `insertFanOutJob` answered `past_horizon`.\n * The event is older than the replay horizon (R5), so no job can be stored\n * and the publish fails rather than counting as delivered.\n * - `fan_out_store_failed` / `fan_out_store_timeout`: the publisher's job\n * insert or the cycle's claim threw, or did not settle within\n * `portTimeoutMs`. Store failures later in a cycle reschedule the job\n * with a diagnostic instead.\n * - `publish_aborted`: the caller's signal aborted before the store answered.\n * - `sink_failed`: a required sink of a composite publisher rejected with an\n * error this package did not create.\n * - `sink_timeout`: a required sink of a composite publisher did not settle\n * within the composite's `sinkTimeoutMs`.\n * - `clock_invalid`: the injected clock threw or returned an invalid time.\n * - `options_invalid`: an option is missing or has the wrong shape.\n */\nexport const WEBHOOK_FAN_OUT_ERROR_CODES = Object.freeze([\n\t\"event_past_replay_horizon\",\n\t\"fan_out_store_failed\",\n\t\"fan_out_store_timeout\",\n\t\"publish_aborted\",\n\t\"sink_failed\",\n\t\"sink_timeout\",\n\t\"clock_invalid\",\n\t\"options_invalid\",\n] as const);\n\n/** Why a fan-out publish or cycle failed. */\nexport type WebhookFanOutErrorCode = (typeof WEBHOOK_FAN_OUT_ERROR_CODES)[number];\n\n/**\n * Codes on {@link WebhookDeliveryError}: why the delivery cycle could not\n * run. Everything that goes wrong while one claimed intent is processed is\n * settled on that intent with a fixed code instead (README, \"Delivery\").\n *\n * - `delivery_store_failed` / `delivery_store_timeout`: the claim threw or\n * answered something unreadable, or did not settle within `portTimeoutMs`.\n * - `clock_invalid`: the injected clock threw or returned an invalid time.\n * - `options_invalid`: an option or port is missing or has the wrong shape.\n */\nexport const WEBHOOK_DELIVERY_ERROR_CODES = Object.freeze([\n\t\"delivery_store_failed\",\n\t\"delivery_store_timeout\",\n\t\"clock_invalid\",\n\t\"options_invalid\",\n] as const);\n\n/** Why a delivery cycle failed. */\nexport type WebhookDeliveryErrorCode = (typeof WEBHOOK_DELIVERY_ERROR_CODES)[number];\n\n/**\n * Why a governed action (PR 9; README, \"Governed actions\") refused. At\n * submission, the action's admission check refuses with\n * `webhook_action_refused:<code>` (or `webhook_parameters_refused:<code>:<field>`\n * with a code from `WEBHOOK_ACTION_PARAMETER_CODES`) and Host records nothing.\n * At execution, the action fails with Host's `error` set to\n * `webhook_action_refused:<code>`, writes nothing more and emits no event.\n *\n * - `admission_not_enforced`: the handler ran without Host's record that the\n * submission was admitted (`ActionContext.admittedAt`), as under a Host\n * older than 7.3.0, which ignores `admitSubmission`. Nothing is written.\n * - `scope_invalid` / `actor_invalid`: Host's trusted context names a tenant,\n * space or actor that breaks the store identifier rule.\n * - `secret_ref_invalid`: the application's secret store says the reference\n * names no secret of this tenant. `secret_ref_unverified`: the check threw,\n * timed out or answered something unreadable.\n * - `secret_ref_unchanged`: a rotation named the reference already in use.\n * - `destination_refused`: the resolver refused the URL (`invalid_url`,\n * `private_address`). `destination_unresolved`: it answered `dns_failure`,\n * threw or timed out. Neither writes anything.\n * - `subscription_not_found`, `subscription_exists`, `subscription_deleted`,\n * `invalid_transition`, `revision_conflict`, `version_conflict`: the\n * subscription store refused the write, or the action's own read found\n * the same. `subscription_not_active`: an intent requeue for a paused or\n * deleted subscription. `paused_since_intent`: an intent requeue for an\n * active subscription that was paused and resumed after the intent's\n * eligibility revision; dispatch would cancel it (decision 3).\n * - `not_found`, `stale`, `not_dead_letter`, `past_replay_horizon`: the\n * delivery store refused a requeue or enrichment (decision 10, R5).\n * - `not_enrichable`, `actor_present`, `actor_suppressed`: enrichment of a\n * completed job, or of a job whose actor is not `legacy` (decision 5).\n * `actor_withheld`, `actor_not_found`, `actor_unavailable`: the\n * application's actor reader withheld the actor, found no such event, or\n * threw, timed out or answered something unreadable.\n * - `store_unavailable`: a read threw, timed out or answered something\n * unreadable; nothing was written. `store_outcome_unknown`: a write threw,\n * timed out or answered something unreadable, so it may have applied\n * (README, \"A store write that timed out is unknown\"); also a re-run of an\n * intent requeue whose evidence predates `subscriptionId` and whose intent\n * can no longer be read, so the applied requeue has no event (README,\n * \"Atomicity and re-runs\").\n * - `action_failed`: anything else, such as a failing clock; nothing it\n * threw is read.\n */\nexport const WEBHOOK_ACTION_REFUSAL_CODES = Object.freeze([\n\t\"admission_not_enforced\",\n\t\"scope_invalid\",\n\t\"actor_invalid\",\n\t\"secret_ref_invalid\",\n\t\"secret_ref_unverified\",\n\t\"secret_ref_unchanged\",\n\t\"destination_refused\",\n\t\"destination_unresolved\",\n\t\"subscription_not_found\",\n\t\"subscription_exists\",\n\t\"subscription_deleted\",\n\t\"subscription_not_active\",\n\t\"paused_since_intent\",\n\t\"invalid_transition\",\n\t\"revision_conflict\",\n\t\"version_conflict\",\n\t\"not_found\",\n\t\"stale\",\n\t\"not_dead_letter\",\n\t\"past_replay_horizon\",\n\t\"not_enrichable\",\n\t\"actor_present\",\n\t\"actor_suppressed\",\n\t\"actor_withheld\",\n\t\"actor_not_found\",\n\t\"actor_unavailable\",\n\t\"store_unavailable\",\n\t\"store_outcome_unknown\",\n\t\"action_failed\",\n] as const);\n\n/** Why a governed action refused. */\nexport type WebhookActionRefusalCode = (typeof WEBHOOK_ACTION_REFUSAL_CODES)[number];\n\n/**\n * Codes on {@link WebhookGovernedActionError}: `options_invalid`, a module\n * option or port is missing or has the wrong shape.\n */\nexport const WEBHOOK_GOVERNED_ACTION_ERROR_CODES = Object.freeze([\"options_invalid\"] as const);\n\n/** Why the governed-action module could not be built. */\nexport type WebhookGovernedActionErrorCode = (typeof WEBHOOK_GOVERNED_ACTION_ERROR_CODES)[number];\n","import type { WebhookJsonValue } from \"./types\";\n\n/*\n * The one place caller-supplied values are read (README, \"Security\n * properties\", P1). Every exported function copies the inputs it needs into\n * a package-owned snapshot here, at entry, and works on the snapshot only;\n * nothing is read after the snapshot is complete.\n *\n * - Properties are read through own property descriptors. An accessor is\n * refused without being called; a value is never read through `[[Get]]`.\n * - Records must be plain: prototype `Object.prototype` or `null`.\n * - Dates are read with the `Date.prototype` intrinsics, never the value's\n * own methods; arrays by index from their own `length`, never through an\n * iterator or their own methods.\n * - Every object the snapshot builds has a `null` prototype or is a fresh\n * array, is frozen, and was populated with `defineProperty` and\n * null-prototype descriptors, so nothing installed on `Object.prototype`\n * or `Array.prototype` is consulted when it is built, read or serialized.\n * - Every built-in the package calls after load is captured below, at module\n * load, and called through the captured `Reflect.apply`; replacing a\n * global or a prototype method later, including from a Proxy trap during\n * a call, does not change what the package runs.\n *\n * For plain data the snapshot is a faithful copy: most properties are read\n * once, and the few read again (a repeated allowlist name whose first read\n * found nothing, a nested object reachable along two paths) give the same\n * answer. A Proxy gets no such promise: its traps execute while the\n * snapshot is taken, possibly more than once for one property in those\n * cases, and the values they return need not agree. The snapshot holds whichever values were read,\n * and only the snapshot is used afterwards. Whatever a trap throws is\n * replaced by the entry point's guard (errors.ts) with a package-created,\n * constant error.\n */\n\nconst reflectApply = Reflect.apply;\nconst reflectOwnKeys = Reflect.ownKeys;\nconst reflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;\nconst reflectGetPrototypeOf = Reflect.getPrototypeOf;\nconst reflectDefineProperty = Reflect.defineProperty;\nconst objectCreate = Object.create;\nconst objectFreeze = Object.freeze;\nconst objectHasOwn = Object.hasOwn;\nconst objectPrototype = Object.prototype;\nconst arrayIsArray = Array.isArray;\nconst dateGetTime = Date.prototype.getTime;\nconst dateToISOString = Date.prototype.toISOString;\nconst DateConstructor = Date;\nconst regExpExec = RegExp.prototype.exec;\nconst stringTrim = String.prototype.trim;\nconst jsonStringify = JSON.stringify;\n\n/** Captured `Reflect.apply`, so a replaced `Function.prototype.call` is never used. */\nexport const apply = reflectApply;\n/** Captured numeric intrinsics. */\nexport const numberIsFinite = Number.isFinite;\nexport const numberIsSafeInteger = Number.isSafeInteger;\nexport const NumberConstructor = Number;\nexport const mathFloor = Math.floor;\nexport const mathMin = Math.min;\nexport const mathMax = Math.max;\nexport const dateParse = Date.parse;\nexport const freeze = objectFreeze;\nexport const hasOwn = objectHasOwn;\nexport const isArray = arrayIsArray;\n\n/** The longest option list (allowlist, retry schedule) a snapshot copies. */\nexport const MAX_LIST_LENGTH = 1_024;\n/** The deepest nesting a JSON snapshot copies; also bounds a cyclic value. */\nexport const MAX_JSON_DEPTH = 64;\n/** The most objects, arrays and dates one JSON snapshot copies. */\nexport const MAX_JSON_NODES = 100_000;\n\n/** Why a snapshot refused a value. The caller's `Fail` maps it to a public error. */\nexport type SnapshotFault = \"accessor\" | \"not_plain\" | \"hole\" | \"not_json\" | \"too_deep\" | \"too_large\";\n\n/** Throws the entry point's public error for a fault at a package-named field. */\nexport type Fail = (fault: SnapshotFault, field: string) => never;\n\n/** Stands in for a non-primitive where an option must be a primitive, so validation rejects it. */\nexport const NOT_PRIMITIVE: unique symbol = Symbol(\"webhook-delivery.not-primitive\");\n\n/** A null-prototype data descriptor, so `defineProperty` reads nothing from `Object.prototype`. */\nfunction dataDescriptor(value: unknown): PropertyDescriptor {\n\tconst descriptor = objectCreate(null) as { value?: unknown; enumerable?: boolean; writable?: boolean; configurable?: boolean };\n\tdescriptor.value = value;\n\tdescriptor.enumerable = true;\n\tdescriptor.writable = false;\n\tdescriptor.configurable = false;\n\treturn descriptor;\n}\n\n/** Define an own, enumerable, read-only data property without consulting any prototype. */\nexport function define(target: object, key: string | number, value: unknown): void {\n\treflectDefineProperty(target, key, dataDescriptor(value));\n}\n\n/** A fresh array holding `values`' elements in order, frozen. `values` must be package-owned. */\nexport function frozenList<T>(values: readonly T[]): readonly T[] {\n\tconst list: T[] = [];\n\tfor (let index = 0; index < values.length; index += 1) define(list, index, values[index]);\n\treturn objectFreeze(list);\n}\n\n/**\n * A frozen null-prototype copy of a package-built object literal. Keys whose\n * value is `undefined` are left out, so optional fields are absent rather\n * than present-and-undefined.\n */\nexport function record<T extends object>(fields: T): T {\n\tconst out = objectCreate(null) as T;\n\tconst keys = reflectOwnKeys(fields);\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index] as string;\n\t\tconst descriptor = reflectGetOwnPropertyDescriptor(fields, key);\n\t\tif (descriptor !== undefined && objectHasOwn(descriptor, \"value\") && descriptor.value !== undefined) define(out, key, descriptor.value);\n\t}\n\treturn objectFreeze(out);\n}\n\n/** A mutable null-prototype map for package-internal bookkeeping. */\nexport function emptyMap<T>(): Record<string, T> {\n\treturn objectCreate(null) as Record<string, T>;\n}\n\n/** `true` when `re` matches `value`, using the captured `RegExp.prototype.exec`. */\nexport function matches(re: RegExp, value: string): boolean {\n\treturn reflectApply(regExpExec, re, [value]) !== null;\n}\n\n/** `value.trim()` with the captured intrinsic. */\nexport function trim(value: string): string {\n\treturn reflectApply(stringTrim, value, []) as string;\n}\n\n/** `true` when `value` is one of the frozen package `codes`. */\nexport function isOneOf(codes: readonly string[], value: unknown): boolean {\n\tif (typeof value !== \"string\") return false;\n\tfor (let index = 0; index < codes.length; index += 1) if (codes[index] === value) return true;\n\treturn false;\n}\n\n/** `true` for a non-array object whose prototype is `Object.prototype` or `null`. A Proxy's trap may run. */\nexport function isPlainRecord(value: unknown): value is object {\n\tif (value === null || typeof value !== \"object\" || arrayIsArray(value)) return false;\n\tconst prototype = reflectGetPrototypeOf(value);\n\treturn prototype === objectPrototype || prototype === null;\n}\n\n/**\n * Read one own data property. Absent is `undefined`; an accessor is refused\n * through `fail` without being called.\n */\nexport function readOwn(target: object, key: string, field: string, fail: Fail): unknown {\n\tconst descriptor = reflectGetOwnPropertyDescriptor(target, key);\n\tif (descriptor === undefined) return undefined;\n\tif (!objectHasOwn(descriptor, \"value\")) return fail(\"accessor\", field);\n\treturn descriptor.value;\n}\n\n/** `undefined` for an absent value, the value for a primitive, {@link NOT_PRIMITIVE} otherwise. */\nexport function primitive(value: unknown): unknown {\n\tif (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return value;\n\treturn NOT_PRIMITIVE;\n}\n\n/**\n * The ISO-8601 form of a real `Date` with a finite time, or `undefined`.\n * Computed with the intrinsics, so an overridden `toISOString`, `getTime`,\n * `toJSON` or `Symbol.toPrimitive` is never called; a Proxy is not a date.\n */\nexport function isoDate(value: unknown): string | undefined {\n\tconst time = timeOf(value);\n\tif (!numberIsFinite(time)) return undefined;\n\treturn reflectApply(dateToISOString, value, []) as string;\n}\n\n/** The time value of a real `Date`, or `NaN` for anything else. */\nexport function timeOf(value: unknown): number {\n\tif (value === null || typeof value !== \"object\") return NaN;\n\ttry {\n\t\t// Throws for anything without a [[DateValue]] slot, a Proxy included,\n\t\t// before any of the value's own code could run.\n\t\treturn reflectApply(dateGetTime, value, []) as number;\n\t} catch {\n\t\treturn NaN;\n\t}\n}\n\n/** A real `Date` or a date string as ISO-8601, or `undefined`. */\nexport function isoFromDateOrString(value: unknown): string | undefined {\n\tif (typeof value === \"string\") return isoDate(new DateConstructor(value));\n\treturn isoDate(value);\n}\n\n/**\n * Copy an option list by index from its own `length`. Holes and\n * non-primitive elements are kept as `undefined` and {@link NOT_PRIMITIVE}\n * so validation can name the index; a non-array is {@link NOT_PRIMITIVE}.\n */\nexport function primitiveList(value: unknown, field: string, fail: Fail): unknown {\n\tif (!arrayIsArray(value)) return value === undefined ? undefined : NOT_PRIMITIVE;\n\tconst length = listLength(value, field, fail);\n\tconst copy: unknown[] = [];\n\tfor (let index = 0; index < length; index += 1) {\n\t\tdefine(copy, index, primitive(readOwn(value, `${index}`, `${field}[${index}]`, fail)));\n\t}\n\treturn objectFreeze(copy);\n}\n\n/** The strings of an option list, in order; other elements and holes are skipped. `undefined` for a non-array. */\nexport function stringList(value: unknown, field: string, fail: Fail): readonly string[] | undefined {\n\tconst copy = primitiveList(value, field, fail);\n\tif (!arrayIsArray(copy)) return undefined;\n\tconst strings: string[] = [];\n\tfor (let index = 0; index < copy.length; index += 1) {\n\t\tconst item = copy[index];\n\t\tif (typeof item === \"string\") define(strings, strings.length, item);\n\t}\n\treturn objectFreeze(strings);\n}\n\nfunction listLength(value: object, field: string, fail: Fail): number {\n\tconst length = readOwn(value, \"length\", field, fail);\n\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 0) return fail(\"not_json\", field);\n\tif (length > MAX_LIST_LENGTH) return fail(\"too_large\", field);\n\treturn length;\n}\n\n/**\n * Snapshot a JSON value: primitives as they are (finite numbers only), a\n * real `Date` as its ISO string, arrays as fresh frozen arrays, plain objects\n * as frozen null-prototype objects holding their own enumerable data\n * properties (`undefined` values skipped, as `JSON.stringify` does).\n * Functions, symbols, bigints, non-finite numbers, holes, accessors,\n * non-plain objects, nesting deeper than {@link MAX_JSON_DEPTH} (a cycle\n * included) and more than {@link MAX_JSON_NODES} containers are refused\n * through `fail`, naming `field` only.\n */\nexport function snapshotJson(value: unknown, field: string, fail: Fail): WebhookJsonValue {\n\treturn copyJson(value, field, fail, 0, { nodes: 0 });\n}\n\n/** The container count several {@link snapshotJsonPart} calls share. */\nexport interface JsonNodeBudget {\n\tnodes: number;\n}\n\n/**\n * Snapshot one part of a larger JSON value as if {@link snapshotJson} had\n * reached it at `depth` with `budget.nodes` containers already counted, so\n * several parts read separately are held to the same depth and node limits\n * as the whole value read at once.\n */\nexport function snapshotJsonPart(value: unknown, field: string, fail: Fail, depth: number, budget: JsonNodeBudget): WebhookJsonValue {\n\treturn copyJson(value, field, fail, depth, budget);\n}\n\nfunction copyJson(value: unknown, field: string, fail: Fail, depth: number, budget: JsonNodeBudget): WebhookJsonValue {\n\tif (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return numberIsFinite(value) ? value : fail(\"not_json\", field);\n\tif (typeof value !== \"object\") return fail(\"not_json\", field);\n\tif (depth >= MAX_JSON_DEPTH) return fail(\"too_deep\", field);\n\tbudget.nodes += 1;\n\tif (budget.nodes > MAX_JSON_NODES) return fail(\"too_large\", field);\n\tconst iso = isoDate(value);\n\tif (iso !== undefined) return iso;\n\tif (arrayIsArray(value)) {\n\t\tconst length = readOwn(value, \"length\", field, fail);\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 0) return fail(\"not_json\", field);\n\t\tif (length > MAX_JSON_NODES) return fail(\"too_large\", field);\n\t\tconst copy: WebhookJsonValue[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst item = readOwn(value, `${index}`, field, fail);\n\t\t\tif (item === undefined) return fail(\"hole\", field);\n\t\t\tdefine(copy, index, copyJson(item, field, fail, depth + 1, budget));\n\t\t}\n\t\treturn objectFreeze(copy);\n\t}\n\tif (!isPlainRecord(value)) return fail(\"not_plain\", field);\n\tconst keys = reflectOwnKeys(value);\n\tconst copy = objectCreate(null) as Record<string, WebhookJsonValue>;\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index];\n\t\tif (typeof key !== \"string\") continue;\n\t\tconst descriptor = reflectGetOwnPropertyDescriptor(value, key);\n\t\tif (descriptor === undefined || descriptor.enumerable !== true) continue;\n\t\tif (!objectHasOwn(descriptor, \"value\")) return fail(\"accessor\", field);\n\t\tif (descriptor.value === undefined) continue;\n\t\tdefine(copy, key, copyJson(descriptor.value, field, fail, depth + 1, budget));\n\t}\n\treturn objectFreeze(copy);\n}\n\n/**\n * Serialize a snapshot to JSON text. It walks only package-built values\n * (frozen null-prototype objects, frozen fresh arrays, primitives), so no\n * `toJSON`, getter or prototype member is ever consulted. Strings are quoted\n * with the captured `JSON.stringify`, which reads no property of a string\n * primitive. The output is what `JSON.stringify` gives for the same data.\n */\nexport function serializeJson(value: unknown): string {\n\tif (value === null) return \"null\";\n\tif (typeof value === \"string\") return jsonStringify(value) as string;\n\tif (typeof value === \"number\") return numberIsFinite(value) ? `${value}` : \"null\";\n\tif (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n\tif (typeof value !== \"object\") return \"null\";\n\tif (arrayIsArray(value)) {\n\t\tlet text = \"[\";\n\t\tfor (let index = 0; index < value.length; index += 1) {\n\t\t\tif (index > 0) text += \",\";\n\t\t\ttext += serializeJson(value[index]);\n\t\t}\n\t\treturn `${text}]`;\n\t}\n\tconst keys = reflectOwnKeys(value);\n\tlet text = \"{\";\n\tlet first = true;\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index];\n\t\tif (typeof key !== \"string\") continue;\n\t\tconst item = (value as Record<string, unknown>)[key];\n\t\tif (item === undefined) continue;\n\t\ttext += `${first ? \"\" : \",\"}${jsonStringify(key) as string}:${serializeJson(item)}`;\n\t\tfirst = false;\n\t}\n\treturn `${text}}`;\n}\n","import type { WebhookConfigErrorCode, WebhookDeliveryErrorCode, WebhookFanOutErrorCode, WebhookGovernedActionErrorCode, WebhookInputErrorCode, WebhookProjectionErrorCode, WebhookStoreErrorCode } from \"./codes\";\nimport { apply, define, freeze, hasOwn } from \"./snapshot\";\n\n/*\n * Package errors and the one guard every exported function runs inside\n * (README, \"Security properties\", P2).\n *\n * Every error this package throws is created by a factory below, which\n * gives it a fixed code and that code's constant message, replaces its\n * native stack with fixed text, records it in a module-private WeakSet and\n * freezes it. The public constructors never touch\n * the WeakSet, so a caller constructing a `WebhookProjectionError` cannot make\n * it pass for one of ours. The guard tells the two apart with\n * `WeakSet.prototype.has` alone, which runs no Proxy trap and reads no\n * property of the thrown value; anything not in the set is dropped unread and\n * replaced by a fresh error from the entry point's factory.\n *\n * The WeakSet is per copy of the module. It is not a registry of ports or\n * predicates (ADR 0018 decision 6): it holds only errors this copy created,\n * and a second copy of the package (ESM and CommonJS loaded together) treats\n * the first copy's errors as foreign and replaces them with its own.\n */\n\nconst PROJECTION_MESSAGES: Readonly<Record<WebhookProjectionErrorCode, string>> = freeze({\n\tinvalid_envelope: \"Webhook projection failed: a required envelope or job field is missing or invalid.\",\n\tpayload_field_not_json: \"Webhook projection failed: an allowlisted payload field is not plain JSON.\",\n\tfact_field_not_json: \"Webhook projection failed: a declared fact field is not plain JSON.\",\n\taccessor_property: \"Webhook projection failed: accessor properties are not read.\",\n\tinspection_failed: \"Webhook projection failed: an input could not be inspected.\",\n\tscope_mismatch: \"Webhook projection failed: the subscription's scope does not match the event's tenant and space.\",\n});\n\nconst CONFIG_MESSAGES: Readonly<Record<WebhookConfigErrorCode, string>> = freeze({\n\tlimit_not_positive_finite: \"Webhook delivery limit must be a positive, finite number.\",\n\tlimit_not_integer: \"Webhook delivery limit must be a whole number.\",\n\tlimit_out_of_range: \"Webhook delivery limit is outside its allowed range.\",\n\tretry_schedule_empty: \"Webhook delivery retry schedule must list at least one delay.\",\n\tlimit_unreadable: \"Webhook delivery limits could not be read.\",\n});\n\nconst INPUT_MESSAGES: Readonly<Record<WebhookInputErrorCode, string>> = freeze({\n\tinput_unreadable: \"Webhook delivery input could not be read.\",\n\tobservation_unknown: \"Webhook delivery observation is not one decision 10 classifies.\",\n\tstatus_out_of_range: \"Webhook response status must be a whole number from 100 to 599.\",\n\tsignature_malformed: \"Webhook signature must be a v1=<64 lowercase hex> value.\",\n\ttimestamp_invalid: \"Webhook timestamp must be a non-negative whole number of seconds.\",\n\tevent_id_invalid: \"Webhook eventId must be printable ASCII with no control characters or surrounding spaces.\",\n\tdelivery_id_invalid: \"Webhook deliveryId must be printable ASCII with no control characters or surrounding spaces.\",\n\tattempt_invalid: \"Webhook attempt must be a positive whole number.\",\n\traw_body_not_string: \"Webhook raw body must be a string.\",\n\trandom_source_missing: \"createWebhookRetryDelay requires a random source.\",\n\trandom_sample_invalid: \"Webhook retry random source must return a number in [0, 1).\",\n\trandom_source_failed: \"Webhook retry random source failed.\",\n\tdenial_code_unknown: \"Webhook admission denial code is not in WEBHOOK_ADMISSION_DENIAL_CODES.\",\n});\n\nconst STORE_MESSAGES: Readonly<Record<WebhookStoreErrorCode, string>> = freeze({\n\tinput_invalid: \"Webhook store input is missing, malformed or not plain data.\",\n\trecord_mismatch: \"Webhook store record does not match its parent's event, tenant, space or delivery.\",\n\tdelivery_id_conflict: \"Webhook store deliveryId is already used by another subscription and event.\",\n\tcall_aborted: \"Webhook store call was aborted before the store acted.\",\n\tdeadline_passed: \"Webhook store call deadline passed before the store acted.\",\n\tclock_invalid: \"Webhook store clock failed or returned an invalid time.\",\n\tstore_failed: \"Webhook store failed.\",\n});\n\nconst FAN_OUT_MESSAGES: Readonly<Record<WebhookFanOutErrorCode, string>> = freeze({\n\tevent_past_replay_horizon: \"Webhook fan-out refused the event: it is older than the replay horizon, so no fan-out job can be stored.\",\n\tfan_out_store_failed: \"Webhook fan-out store call failed.\",\n\tfan_out_store_timeout: \"Webhook fan-out store call did not settle in time.\",\n\tpublish_aborted: \"Webhook fan-out publish was aborted before the job was stored.\",\n\tsink_failed: \"A required sink of the composite event publisher failed.\",\n\tsink_timeout: \"A required sink of the composite event publisher did not settle in time.\",\n\tclock_invalid: \"Webhook fan-out clock failed or returned an invalid time.\",\n\toptions_invalid: \"Webhook fan-out options are missing or malformed.\",\n});\n\nconst DELIVERY_MESSAGES: Readonly<Record<WebhookDeliveryErrorCode, string>> = freeze({\n\tdelivery_store_failed: \"Webhook delivery store call failed.\",\n\tdelivery_store_timeout: \"Webhook delivery store call did not settle in time.\",\n\tclock_invalid: \"Webhook delivery clock failed or returned an invalid time.\",\n\toptions_invalid: \"Webhook delivery options are missing or malformed.\",\n});\n\nconst GOVERNED_ACTION_MESSAGES: Readonly<Record<WebhookGovernedActionErrorCode, string>> = freeze({\n\toptions_invalid: \"Webhook governed-action module options are missing or malformed.\",\n});\n\nfunction messageFor(table: Readonly<Record<string, string>>, code: unknown, fallback: string): string {\n\treturn typeof code === \"string\" && hasOwn(table, code) ? table[code]! : fallback;\n}\n\nconst reflectDefineProperty = Reflect.defineProperty;\nconst objectCreate = Object.create;\n\n/**\n * An own, enumerable, writable data property, defined with a null-prototype\n * descriptor so neither `Error.prototype` nor `Object.prototype` is consulted.\n * Errors the package throws are frozen afterwards.\n */\nfunction defineField(target: object, key: string, value: unknown): void {\n\tconst descriptor = objectCreate(null) as PropertyDescriptor;\n\tdescriptor.value = value;\n\tdescriptor.enumerable = true;\n\tdescriptor.writable = true;\n\tdescriptor.configurable = true;\n\treflectDefineProperty(target, key, descriptor);\n}\n\n/**\n * A configured limit was not usable: zero, negative, `NaN`, infinite, not an\n * integer where a count is required, outside its documented range, or not\n * readable as plain data. The message is constant for the code; `field`\n * names the limit, for example `deliveryRetryDelaysMs[2]`.\n */\nexport class WebhookDeliveryConfigError extends Error {\n\tdeclare readonly code: WebhookConfigErrorCode;\n\t/** The limit that was rejected, for example `deliveryRetryDelaysMs[2]`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookConfigErrorCode, field: string) {\n\t\tsuper(messageFor(CONFIG_MESSAGES, code, \"Webhook delivery limit was rejected.\"));\n\t\tdefineField(this, \"name\", \"WebhookDeliveryConfigError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * An envelope, job or subscription could not be projected. The message is\n * constant for the code. `field` names an envelope or job field, an option,\n * or a field name from the caller's own allowlist; never a value.\n */\nexport class WebhookProjectionError extends Error {\n\tdeclare readonly code: WebhookProjectionErrorCode;\n\t/** The envelope, job, option or allowlisted payload field at fault. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookProjectionErrorCode, field: string) {\n\t\tsuper(messageFor(PROJECTION_MESSAGES, code, \"Webhook projection failed.\"));\n\t\tdefineField(this, \"name\", \"WebhookProjectionError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * A store call was refused: its input was malformed or not plain data\n * (`input_invalid`), it broke a store invariant (`record_mismatch`,\n * `delivery_id_conflict`), it was aborted or past its deadline when the\n * store reached its write (`call_aborted`, `deadline_passed`), or the\n * store's clock failed (`clock_invalid`). Nothing was written. The message\n * is constant for the code; `field` names an input field, never a value.\n */\nexport class WebhookStoreError extends Error {\n\tdeclare readonly code: WebhookStoreErrorCode;\n\t/** The input field at fault, for example `intent.eventId`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookStoreErrorCode, field: string) {\n\t\tsuper(messageFor(STORE_MESSAGES, code, \"Webhook store call was refused.\"));\n\t\tdefineField(this, \"name\", \"WebhookStoreError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * The fan-out publisher, the composite publisher or the fan-out cycle refused\n * or failed (`WEBHOOK_FAN_OUT_ERROR_CODES`). The message is constant for the\n * code; `field` names an option, a store method or a sink name from the\n * application's own configuration, never an event value.\n */\nexport class WebhookFanOutError extends Error {\n\tdeclare readonly code: WebhookFanOutErrorCode;\n\t/** The option, store method or sink at fault, for example `insertFanOutJob`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookFanOutErrorCode, field: string) {\n\t\tsuper(messageFor(FAN_OUT_MESSAGES, code, \"Webhook fan-out failed.\"));\n\t\tdefineField(this, \"name\", \"WebhookFanOutError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * The delivery cycle could not run (`WEBHOOK_DELIVERY_ERROR_CODES`). The\n * message is constant for the code; `field` names an option or a store\n * method, never a value.\n */\nexport class WebhookDeliveryError extends Error {\n\tdeclare readonly code: WebhookDeliveryErrorCode;\n\t/** The option or store method at fault, for example `claimDeliveryIntents`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookDeliveryErrorCode, field: string) {\n\t\tsuper(messageFor(DELIVERY_MESSAGES, code, \"Webhook delivery failed.\"));\n\t\tdefineField(this, \"name\", \"WebhookDeliveryError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\n/**\n * The governed-action module could not be built\n * (`WEBHOOK_GOVERNED_ACTION_ERROR_CODES`). The message is constant for the\n * code; `field` names an option, never a value.\n */\nexport class WebhookGovernedActionError extends Error {\n\tdeclare readonly code: WebhookGovernedActionErrorCode;\n\t/** The option at fault, for example `secretReferences.verify`. */\n\tdeclare readonly field: string;\n\n\tconstructor(code: WebhookGovernedActionErrorCode, field: string) {\n\t\tsuper(messageFor(GOVERNED_ACTION_MESSAGES, code, \"Webhook governed-action module could not be built.\"));\n\t\tdefineField(this, \"name\", \"WebhookGovernedActionError\");\n\t\tdefineField(this, \"code\", code);\n\t\tdefineField(this, \"field\", field);\n\t}\n}\n\nconst created = new WeakSet<object>();\nconst weakSetAdd = WeakSet.prototype.add;\nconst weakSetHas = WeakSet.prototype.has;\nconst TypeErrorConstructor = TypeError;\nconst RangeErrorConstructor = RangeError;\n\n/**\n * Register a factory-made error and freeze it. Its native `stack` is\n * replaced first with fixed package text: V8 frames name the functions on\n * the call stack, and a caller can name its own function (a Proxy trap, a\n * getter, a callback that calls a package helper) after a secret. Replacing\n * it before anything reads it also means `Error.prepareStackTrace` is never\n * consulted for a package error.\n */\nfunction mark<E extends Error>(error: E, name: string, code: string): E {\n\tconst stack = objectCreate(null) as PropertyDescriptor;\n\tstack.value = `${name}: ${code}`;\n\tstack.enumerable = false;\n\tstack.writable = false;\n\tstack.configurable = false;\n\tif (!reflectDefineProperty(error, \"stack\", stack)) throw new TypeErrorConstructor(\"Webhook delivery could not seal an error.\");\n\tapply(weakSetAdd, created, [error]);\n\treturn freeze(error);\n}\n\n/** `true` only for an error one of this module's factories created. Runs no code of `value`. */\nfunction isPackageError(value: unknown): boolean {\n\treturn (typeof value === \"object\" || typeof value === \"function\") && value !== null && apply(weakSetHas, created, [value]) === true;\n}\n\n/** @internal A package-created, frozen projection error. */\nexport function projectionError(code: WebhookProjectionErrorCode, field: string): WebhookProjectionError {\n\treturn mark(new WebhookProjectionError(code, field), \"WebhookProjectionError\", code);\n}\n\n/** @internal A package-created, frozen limit error. */\nexport function configError(code: WebhookConfigErrorCode, field: string): WebhookDeliveryConfigError {\n\treturn mark(new WebhookDeliveryConfigError(code, field), \"WebhookDeliveryConfigError\", code);\n}\n\n/** @internal A package-created, frozen store error. */\nexport function storeError(code: WebhookStoreErrorCode, field: string): WebhookStoreError {\n\treturn mark(new WebhookStoreError(code, field), \"WebhookStoreError\", code);\n}\n\n/** @internal A package-created, frozen fan-out error. */\nexport function fanOutError(code: WebhookFanOutErrorCode, field: string): WebhookFanOutError {\n\treturn mark(new WebhookFanOutError(code, field), \"WebhookFanOutError\", code);\n}\n\n/** @internal A package-created, frozen delivery-cycle error. */\nexport function deliveryError(code: WebhookDeliveryErrorCode, field: string): WebhookDeliveryError {\n\treturn mark(new WebhookDeliveryError(code, field), \"WebhookDeliveryError\", code);\n}\n\n/** @internal A package-created, frozen governed-action module error. */\nexport function governedActionError(code: WebhookGovernedActionErrorCode, field: string): WebhookGovernedActionError {\n\treturn mark(new WebhookGovernedActionError(code, field), \"WebhookGovernedActionError\", code);\n}\n\n/** @internal A package-created, frozen `TypeError` or `RangeError` carrying `code`. */\nexport function inputError(kind: \"type\" | \"range\", code: WebhookInputErrorCode): TypeError | RangeError {\n\tconst message = INPUT_MESSAGES[code];\n\tconst error = kind === \"type\" ? new TypeErrorConstructor(message) : new RangeErrorConstructor(message);\n\tdefine(error, \"code\", code);\n\treturn mark(error, kind === \"type\" ? \"TypeError\" : \"RangeError\", code);\n}\n\n/**\n * @internal Run an entry point. A package-created error passes through\n * unchanged; anything else thrown (by a Proxy trap, an injected callback or\n * the engine) is never inspected and is replaced by `replacement()`.\n */\nexport function guard<T>(run: () => T, replacement: () => Error): T {\n\ttry {\n\t\treturn run();\n\t} catch (thrown) {\n\t\tif (isPackageError(thrown)) throw thrown;\n\t\tthrow replacement();\n\t}\n}\n\n/** @internal Run a total function: any throw, package-created or not, yields `fallback()` unread. */\nexport function guardOr<T>(run: () => T, fallback: () => T): T {\n\ttry {\n\t\treturn run();\n\t} catch {\n\t\treturn fallback();\n\t}\n}\n","import { configError, guard } from \"./errors\";\nimport {\n\tdefine,\n\temptyMap,\n\tfreeze,\n\tisArray,\n\tisPlainRecord,\n\tnumberIsFinite,\n\tnumberIsSafeInteger,\n\tprimitive,\n\tprimitiveList,\n\treadOwn,\n\ttype Fail,\n} from \"./snapshot\";\n\n/**\n * Every bound the delivery lifecycle relies on (R4). All values are\n * milliseconds or counts and must be positive and finite;\n * {@link resolveWebhookDeliveryLimits} enforces that.\n */\nexport interface WebhookDeliveryLimits {\n\t/** Attempts per delivery intent before dead letter, including the first. */\n\treadonly maxDeliveryAttempts: number;\n\t/** Delays before attempts 2, 3, ...; the last entry repeats if attempts outnumber it. */\n\treadonly deliveryRetryDelaysMs: readonly number[];\n\t/** Processing deadline persisted on an intent at creation. */\n\treadonly deliveryDeadlineMs: number;\n\t/** Attempts per fan-out job before dead letter. */\n\treadonly maxFanOutAttempts: number;\n\t/** Fan-out retry delays; the last entry repeats. */\n\treadonly fanOutRetryDelaysMs: readonly number[];\n\t/** Processing deadline persisted on a fan-out job at creation. */\n\treadonly fanOutDeadlineMs: number;\n\t/** Bound on one transport call, from handoff to settled response. */\n\treadonly attemptTimeoutMs: number;\n\t/** Bound on every other awaited port call, stores included. */\n\treadonly portTimeoutMs: number;\n\t/** Jitter added to a retry delay, as a fraction of it, in `(0, 1]`. */\n\treadonly retryJitterRatio: number;\n\t/** The longest `Retry-After` honoured; longer requests are clamped to it. */\n\treadonly maxRetryAfterMs: number;\n\t/**\n\t * The replay horizon (R5): how long after an event's `recordedAt` the\n\t * delivery store accepts a fan-out job, intent or denial for it, accepts a\n\t * requeue of one, and keeps its records and tombstones. A replay older\n\t * than this is rejected as `past_horizon`. It must be a whole number of\n\t * milliseconds no shorter than `fanOutDeadlineMs + deliveryDeadlineMs`,\n\t * and should be much longer: it also has to cover the Host relay budget,\n\t * how long a Host outbox dead letter may wait for requeue, and how long an\n\t * operator may take to requeue a webhook dead letter. Pass the same value\n\t * to the delivery store.\n\t */\n\treadonly replayHorizonMs: number;\n}\n\nconst MINUTE = 60_000;\nconst HOUR = 60 * MINUTE;\nconst DAY = 24 * HOUR;\n\n/** The largest millisecond offset a JavaScript `Date` represents, so `now - horizon` stays a valid time. */\nexport const WEBHOOK_MAX_REPLAY_HORIZON_MS = 8_640_000_000_000_000;\n\n/** The largest delay a JavaScript timer accepts without overflowing. */\nexport const WEBHOOK_MAX_TIMER_MS = 2_147_483_647;\n\n/**\n * Defaults. Delivery: eight attempts with AutoRefi's first seven delays\n * (1m, 5m, 15m, 1h, 6h, 12h, 24h), per ADR 0018 decision 10.\n */\nexport const DEFAULT_WEBHOOK_DELIVERY_LIMITS: WebhookDeliveryLimits = Object.freeze({\n\tmaxDeliveryAttempts: 8,\n\tdeliveryRetryDelaysMs: Object.freeze([MINUTE, 5 * MINUTE, 15 * MINUTE, HOUR, 6 * HOUR, 12 * HOUR, 24 * HOUR]),\n\tdeliveryDeadlineMs: 72 * HOUR,\n\tmaxFanOutAttempts: 24,\n\tfanOutRetryDelaysMs: Object.freeze([1_000, 5_000, 30_000, MINUTE, 5 * MINUTE, 15 * MINUTE]),\n\tfanOutDeadlineMs: 24 * HOUR,\n\tattemptTimeoutMs: 15_000,\n\tportTimeoutMs: 5_000,\n\tretryJitterRatio: 0.1,\n\tmaxRetryAfterMs: HOUR,\n\treplayHorizonMs: 30 * DAY,\n});\n\n/** Every limit, in {@link WebhookDeliveryLimits} order. */\nconst LIMIT_KEYS = Object.freeze([\n\t\"maxDeliveryAttempts\",\n\t\"deliveryRetryDelaysMs\",\n\t\"deliveryDeadlineMs\",\n\t\"maxFanOutAttempts\",\n\t\"fanOutRetryDelaysMs\",\n\t\"fanOutDeadlineMs\",\n\t\"attemptTimeoutMs\",\n\t\"portTimeoutMs\",\n\t\"retryJitterRatio\",\n\t\"maxRetryAfterMs\",\n\t\"replayHorizonMs\",\n] as const satisfies readonly (keyof WebhookDeliveryLimits)[]);\n\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;\n\nconst limitFail: Fail = (fault, field) => {\n\tthrow configError(fault === \"too_large\" ? \"limit_out_of_range\" : \"limit_unreadable\", field);\n};\n\n/**\n * Merge overrides onto {@link DEFAULT_WEBHOOK_DELIVERY_LIMITS} and validate\n * every limit. An override left `undefined` keeps the default. The\n * overrides are copied at entry into a snapshot, one descriptor read per\n * limit (an accessor is refused, not called), and schedules are copied by\n * index; the snapshot is validated and is what is returned, frozen. Keys\n * that are not limits are ignored.\n *\n * @throws {WebhookDeliveryConfigError} when any limit is zero, negative,\n * `NaN`, infinite, fractional where a count is required, out of range, or\n * cannot be read as plain data (`limit_unreadable`).\n */\nexport function resolveWebhookDeliveryLimits(\n\toverrides: Partial<WebhookDeliveryLimits> = {},\n): WebhookDeliveryLimits {\n\treturn guard(() => resolveLimits(overrides), () => configError(\"limit_unreadable\", \"overrides\"));\n}\n\nfunction resolveLimits(overrides: unknown): WebhookDeliveryLimits {\n\tif (!isPlainRecord(overrides)) return limitFail(\"not_plain\", \"overrides\");\n\tconst merged = emptyMap<unknown>();\n\tfor (let index = 0; index < LIMIT_KEYS.length; index += 1) {\n\t\tconst key = LIMIT_KEYS[index]!;\n\t\tconst raw = readOwn(overrides, key, key, limitFail);\n\t\tconst value = key === \"deliveryRetryDelaysMs\" || key === \"fanOutRetryDelaysMs\" ? primitiveList(raw, key, limitFail) : primitive(raw);\n\t\tdefine(merged, key, value === undefined ? DEFAULT_WEBHOOK_DELIVERY_LIMITS[key] : value);\n\t}\n\tconst limits = merged as unknown as WebhookDeliveryLimits;\n\tassertPositiveInteger(limits.maxDeliveryAttempts, \"maxDeliveryAttempts\");\n\tassertDelaySchedule(limits.deliveryRetryDelaysMs, \"deliveryRetryDelaysMs\");\n\tassertPositiveFinite(limits.deliveryDeadlineMs, \"deliveryDeadlineMs\");\n\tassertPositiveInteger(limits.maxFanOutAttempts, \"maxFanOutAttempts\");\n\tassertDelaySchedule(limits.fanOutRetryDelaysMs, \"fanOutRetryDelaysMs\");\n\tassertPositiveFinite(limits.fanOutDeadlineMs, \"fanOutDeadlineMs\");\n\tassertTimerBound(limits.attemptTimeoutMs, \"attemptTimeoutMs\");\n\tassertTimerBound(limits.portTimeoutMs, \"portTimeoutMs\");\n\tassertJitterRatio(limits.retryJitterRatio, \"retryJitterRatio\");\n\tassertPositiveFinite(limits.maxRetryAfterMs, \"maxRetryAfterMs\");\n\tassertJitteredScheduleRepresentable(limits.deliveryRetryDelaysMs, limits.retryJitterRatio, \"deliveryRetryDelaysMs\");\n\tassertJitteredScheduleRepresentable(limits.fanOutRetryDelaysMs, limits.retryJitterRatio, \"fanOutRetryDelaysMs\");\n\tassertReplayHorizon(limits.replayHorizonMs, \"replayHorizonMs\");\n\t// A job and its intents legitimately stay pending for up to both\n\t// processing deadlines; a shorter horizon would reject their own writes.\n\tif (limits.replayHorizonMs < limits.fanOutDeadlineMs + limits.deliveryDeadlineMs) {\n\t\tthrow configError(\"limit_out_of_range\", \"replayHorizonMs\");\n\t}\n\t// The snapshot's schedules are already frozen copies; freezing the map\n\t// makes the validated snapshot the returned value.\n\treturn freeze(merged) as unknown as WebhookDeliveryLimits;\n}\n\n/** @internal `value` must come from a snapshot (a primitive). */\nexport function assertPositiveFinite(value: unknown, field: string): asserts value is number {\n\tif (typeof value !== \"number\" || !numberIsFinite(value) || value <= 0) {\n\t\tthrow configError(\"limit_not_positive_finite\", field);\n\t}\n}\n\n/** @internal */\nexport function assertPositiveInteger(value: unknown, field: string): asserts value is number {\n\tassertPositiveFinite(value, field);\n\tif (!numberIsSafeInteger(value)) {\n\t\tthrow configError(\"limit_not_integer\", field);\n\t}\n}\n\n/** @internal `value` must be a snapshot list (see `primitiveList`) or a package constant. */\nexport function assertDelaySchedule(value: unknown, field: string): asserts value is readonly number[] {\n\tif (!isArray(value) || value.length === 0) {\n\t\tthrow configError(\"retry_schedule_empty\", field);\n\t}\n\t// Indexed: a hole in the input is `undefined` in the snapshot.\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tassertPositiveFinite(value[index], `${field}[${index}]`);\n\t}\n}\n\n/**\n * Every delay, with the largest jitter added, must stay a safe integer, so\n * the jittered delay is finite and exactly representable.\n *\n * @internal\n */\nexport function assertJitteredScheduleRepresentable(delays: readonly number[], jitterRatio: number, field: string): void {\n\tfor (let index = 0; index < delays.length; index += 1) {\n\t\tif (!(delays[index]! * (1 + jitterRatio) <= MAX_SAFE_INTEGER)) {\n\t\t\tthrow configError(\"limit_out_of_range\", `${field}[${index}]`);\n\t\t}\n\t}\n}\n\n/** @internal */\nexport function assertJitterRatio(value: unknown, field: string): asserts value is number {\n\tassertPositiveFinite(value, field);\n\tif (value > 1) {\n\t\tthrow configError(\"limit_out_of_range\", field);\n\t}\n}\n\n/**\n * A replay horizon must be a positive whole number of milliseconds no larger\n * than {@link WEBHOOK_MAX_REPLAY_HORIZON_MS}. The delivery stores run this at\n * construction.\n *\n * @internal `value` must be a primitive.\n */\nexport function assertReplayHorizon(value: unknown, field: string): asserts value is number {\n\tassertPositiveInteger(value, field);\n\tif (value > WEBHOOK_MAX_REPLAY_HORIZON_MS) {\n\t\tthrow configError(\"limit_out_of_range\", field);\n\t}\n}\n\nfunction assertTimerBound(value: unknown, field: string): asserts value is number {\n\tassertPositiveFinite(value, field);\n\tif (value > WEBHOOK_MAX_TIMER_MS) {\n\t\tthrow configError(\"limit_out_of_range\", field);\n\t}\n}\n","import { storeError } from \"./errors\";\nimport type { WebhookClock } from \"./ports\";\nimport {\n\tapply,\n\tdateParse,\n\tfreeze,\n\tisArray,\n\tisoDate,\n\tisoFromDateOrString,\n\tisOneOf,\n\tmatches,\n\tnumberIsSafeInteger,\n\treadOwn,\n\tserializeJson,\n\tsnapshotJson,\n\ttimeOf,\n\ttype Fail,\n} from \"./snapshot\";\nimport type { WebhookJsonObject, WebhookJsonValue } from \"./types\";\n\n/*\n * Input reading for the memory stores. A store method copies its arguments\n * into a package-owned snapshot at entry, with the same readers the pure\n * functions use (`src/snapshot.ts`): own data properties only, accessors\n * refused uncalled, `Date`s read with the intrinsics and turned into\n * ISO-8601 strings. The method then reads only the snapshot. Every refusal\n * is a package-created `WebhookStoreError` naming a field, never a value.\n */\n\nconst DateConstructor = Date;\n\nconst inputFail: Fail = (_fault, field) => {\n\tthrow storeError(\"input_invalid\", field);\n};\n\n/** A snapshot of a plain-data input record: frozen, null-prototype, dates as ISO strings. */\nexport type Snapshot = WebhookJsonObject;\n\n/** Snapshot a plain-data record argument. */\nexport function snapshotRecord(value: unknown, field: string): Snapshot {\n\tconst copy = snapshotJson(value, field, inputFail);\n\tif (copy === null || typeof copy !== \"object\" || isArray(copy)) throw storeError(\"input_invalid\", field);\n\treturn copy as Snapshot;\n}\n\n/** A nested record of a snapshot. */\nexport function nestedRecord(record: Snapshot, key: string, field: string): Snapshot {\n\tconst value = own(record, key);\n\tif (value === null || typeof value !== \"object\" || isArray(value)) throw storeError(\"input_invalid\", field);\n\treturn value as Snapshot;\n}\n\nfunction own(record: Snapshot, key: string): WebhookJsonValue | undefined {\n\treturn readOwn(record, key, key, inputFail) as WebhookJsonValue | undefined;\n}\n\n/** A non-empty string field. */\nexport function text(record: Snapshot, key: string, field: string): string {\n\tconst value = own(record, key);\n\tif (typeof value !== \"string\" || value.length === 0) throw storeError(\"input_invalid\", field);\n\treturn value;\n}\n\n/** The longest identifier a store accepts (tenant, space, subscription, event, delivery, worker and actor ids). */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** C0 controls, DEL and C1 controls. */\nconst CONTROL_CHARACTER = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/**\n * A UTF-16 surrogate that is not half of a pair. Without the `u` flag the\n * pattern works on code units, which is what it has to inspect.\n */\nconst LONE_SURROGATE = /[\\ud800-\\udbff](?![\\udc00-\\udfff])|(?<![\\ud800-\\udbff])[\\udc00-\\udfff]/;\n\n/**\n * An identifier field: a non-empty string of at most\n * {@link MAX_IDENTIFIER_LENGTH} UTF-16 code units with no control\n * characters and no lone surrogates. Both stores read identifiers through\n * this function, so an identifier one store accepts the other accepts too.\n * No identifier contains the NUL a text key might be tempted to use as a\n * separator. Lone surrogates are refused because they have no UTF-8 form: a\n * PostgreSQL driver encodes each one as U+FFFD, so `\"t\\ud800\"` and\n * `\"t\\udc00\"` would be stored as the same tenant (`tests/postgres-live.test.ts`\n * shows the driver doing that).\n */\nexport function identifier(record: Snapshot, key: string, field: string): string {\n\tconst value = text(record, key, field);\n\tif (!isWebhookIdentifier(value)) throw storeError(\"input_invalid\", field);\n\treturn value;\n}\n\n/**\n * The identifier rule of {@link identifier} as a predicate: a non-empty\n * string of at most {@link MAX_IDENTIFIER_LENGTH} UTF-16 code units with no\n * control character and no lone surrogate. The governed actions' parameter\n * readers (src/action-parameters.ts) use it, so an id an action accepts is\n * one every store accepts.\n */\nexport function isWebhookIdentifier(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH &&\n\t\t!matches(CONTROL_CHARACTER, value) && !matches(LONE_SURROGATE, value);\n}\n\n/** An optional identifier field. */\nexport function optionalIdentifier(record: Snapshot, key: string, field: string): string | undefined {\n\treturn own(record, key) === undefined ? undefined : identifier(record, key, field);\n}\n\n/**\n * A collision-free key for a tuple of strings: the tuple's JSON encoding.\n * Distinct tuples always encode differently, whatever characters the parts\n * hold, because JSON quotes and escapes each part.\n */\nexport function compositeKey(...parts: readonly string[]): string {\n\treturn serializeJson(parts);\n}\n\n/**\n * A fresh frozen deep copy of a value the store built from snapshots:\n * null-prototype objects, arrays and primitives. It has no depth or size\n * limit, so a record the store accepted can always be copied out; the\n * input snapshot already bounded it.\n */\nexport function cloneOut<T>(value: unknown): T {\n\treturn copyTree(value) as T;\n}\n\nfunction copyTree(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (isArray(value)) {\n\t\tconst list: unknown[] = [];\n\t\tfor (let index = 0; index < value.length; index += 1) list[index] = copyTree(value[index]);\n\t\treturn freeze(list);\n\t}\n\tconst out = Object.create(null) as Record<string, unknown>;\n\tconst keys = Object.keys(value);\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index]!;\n\t\tconst item = (value as Record<string, unknown>)[key];\n\t\tif (item !== undefined) out[key] = copyTree(item);\n\t}\n\treturn freeze(out);\n}\n\n/** An optional non-empty string field. */\nexport function optionalText(record: Snapshot, key: string, field: string): string | undefined {\n\treturn own(record, key) === undefined ? undefined : text(record, key, field);\n}\n\n/** A safe integer field at least `min`. */\nexport function wholeNumber(record: Snapshot, key: string, field: string, min: number): number {\n\tconst value = own(record, key);\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < min) throw storeError(\"input_invalid\", field);\n\treturn value;\n}\n\n/** An optional safe integer field at least `min`. */\nexport function optionalWholeNumber(record: Snapshot, key: string, field: string, min: number): number | undefined {\n\treturn own(record, key) === undefined ? undefined : wholeNumber(record, key, field, min);\n}\n\n/** A boolean field. */\nexport function flag(record: Snapshot, key: string, field: string): boolean {\n\tconst value = own(record, key);\n\tif (typeof value !== \"boolean\") throw storeError(\"input_invalid\", field);\n\treturn value;\n}\n\n/** A timestamp field (a `Date` or a date string in the input), as epoch milliseconds. */\nexport function instant(record: Snapshot, key: string, field: string): number {\n\tconst value = own(record, key);\n\tconst iso = typeof value === \"string\" ? isoFromDateOrString(value) : undefined;\n\tif (iso === undefined) throw storeError(\"input_invalid\", field);\n\treturn dateParse(iso);\n}\n\n/** A field that must be one of the frozen package `codes`. */\nexport function codeOf<T extends string>(record: Snapshot, key: string, codes: readonly T[], field: string): T {\n\tconst value = own(record, key);\n\tif (!isOneOf(codes, value)) throw storeError(\"input_invalid\", field);\n\treturn value as T;\n}\n\n/** A non-empty list of non-empty strings, at most 1,024 long (the snapshot's list bound applies to JSON arrays too). */\nexport function textList(record: Snapshot, key: string, field: string): readonly string[] {\n\tconst value = own(record, key);\n\tif (!isArray(value) || value.length === 0 || value.length > 1_024) throw storeError(\"input_invalid\", field);\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst item = value[index];\n\t\tif (typeof item !== \"string\" || item.length === 0) throw storeError(\"input_invalid\", `${field}[${index}]`);\n\t}\n\treturn value as readonly string[];\n}\n\n/** The largest epoch-millisecond value a `Date` holds. */\nexport const MAX_TIME_MS = 8_640_000_000_000_000;\n\n/** The ISO-8601 form of epoch milliseconds. */\nexport function isoOf(ms: number): string {\n\tconst iso = isoDate(new DateConstructor(ms));\n\tif (iso === undefined) throw storeError(\"store_failed\", \"time\");\n\treturn iso;\n}\n\n// ---------------------------------------------------------------------------\n// Call options\n// ---------------------------------------------------------------------------\n\nconst abortedDescriptor = typeof AbortSignal === \"function\" ? Reflect.getOwnPropertyDescriptor(AbortSignal.prototype, \"aborted\") : undefined;\nconst abortedGetter = abortedDescriptor?.get;\n\n/** The parts of {@link WebhookCallOptions} a store checks when it reaches its write. */\nexport interface CallBounds {\n\treadonly deadlineMs: number;\n\treadonly signal: object;\n}\n\nfunction isAborted(signal: object): boolean {\n\tif (abortedGetter === undefined) throw storeError(\"input_invalid\", \"options.signal\");\n\t// The intrinsic getter reads the signal's internal slot; it throws for\n\t// anything that is not a real AbortSignal and runs none of its code.\n\treturn apply(abortedGetter, signal, []) === true;\n}\n\n/** Read `{ deadline, signal }` at entry. The signal must be a real `AbortSignal`. */\nexport function readCallOptions(options: unknown): CallBounds {\n\tif (options === null || typeof options !== \"object\") throw storeError(\"input_invalid\", \"options\");\n\tconst deadline = readOwn(options, \"deadline\", \"options.deadline\", inputFail);\n\tconst deadlineMs = timeOf(deadline);\n\tif (!(deadlineMs === deadlineMs) || deadlineMs === Infinity || deadlineMs === -Infinity) throw storeError(\"input_invalid\", \"options.deadline\");\n\tconst signal = readOwn(options, \"signal\", \"options.signal\", inputFail);\n\tif (signal === null || typeof signal !== \"object\") throw storeError(\"input_invalid\", \"options.signal\");\n\ttry {\n\t\tisAborted(signal);\n\t} catch {\n\t\tthrow storeError(\"input_invalid\", \"options.signal\");\n\t}\n\treturn { deadlineMs, signal };\n}\n\n/**\n * Refuse a call that is no longer wanted at the moment the store would\n * write: its signal aborted, or its deadline is not after the store's\n * `nowMs`. Nothing has been written when this throws.\n */\nexport function assertCallWanted(bounds: CallBounds, nowMs: number): void {\n\tif (isAborted(bounds.signal)) throw storeError(\"call_aborted\", \"options.signal\");\n\tif (!(bounds.deadlineMs > nowMs)) throw storeError(\"deadline_passed\", \"options.deadline\");\n}\n\n// ---------------------------------------------------------------------------\n// Clock\n// ---------------------------------------------------------------------------\n\n/** A clock captured at construction: the object and its `now` function. */\nexport interface CapturedClock {\n\treadonly target: object;\n\treadonly now: (...args: never[]) => unknown;\n}\n\n/** Capture an injected {@link WebhookClock} at construction. */\nexport function captureClock(clock: WebhookClock | undefined): CapturedClock {\n\tif (clock === null || typeof clock !== \"object\") throw storeError(\"clock_invalid\", \"clock\");\n\tconst now = (clock as { now?: unknown }).now;\n\tif (typeof now !== \"function\") throw storeError(\"clock_invalid\", \"clock.now\");\n\treturn { target: clock, now: now as (...args: never[]) => unknown };\n}\n\n/** Read the store's clock as epoch milliseconds; a throw or an invalid `Date` is `clock_invalid`. */\nexport function readClock(clock: CapturedClock): number {\n\tlet value: unknown;\n\ttry {\n\t\tvalue = apply(clock.now, clock.target, []);\n\t} catch {\n\t\tthrow storeError(\"clock_invalid\", \"clock.now\");\n\t}\n\tconst ms = timeOf(value);\n\tif (!(ms === ms) || ms === Infinity || ms === -Infinity) throw storeError(\"clock_invalid\", \"clock.now\");\n\treturn ms;\n}\n","import {\n\tWEBHOOK_ADMISSION_DENIAL_CODES,\n\tWEBHOOK_ATTEMPT_OUTCOMES,\n\tWEBHOOK_ATTEMPT_REASON_CODES,\n\tWEBHOOK_DIAGNOSTIC_CODES,\n\ttype WebhookAdmissionDenialCode,\n\ttype WebhookAttemptOutcome,\n\ttype WebhookAttemptReasonCode,\n\ttype WebhookDiagnosticCode,\n} from \"./codes\";\nimport { configError, guard, storeError } from \"./errors\";\nimport { assertReplayHorizon, WEBHOOK_MAX_REPLAY_HORIZON_MS } from \"./limits\";\nimport type {\n\tWebhookAttemptBeginResult,\n\tWebhookDeliveryLeaseCheck,\n\tWebhookFanOutJobFence,\n\tWebhookActorEnrichmentResult,\n\tWebhookFencedInsertResult,\n\tWebhookRequeueResult,\n} from \"./ports\";\nimport { mathMin, primitive, readOwn } from \"./snapshot\";\nimport {\n\tcloneOut,\n\tcodeOf,\n\tcompositeKey,\n\tflag,\n\tidentifier,\n\tinstant,\n\tisoOf,\n\tMAX_TIME_MS,\n\tnestedRecord,\n\toptionalIdentifier,\n\toptionalWholeNumber,\n\treadCallOptions,\n\tsnapshotRecord,\n\ttext,\n\twholeNumber,\n\ttype CallBounds,\n\ttype Snapshot,\n} from \"./store-input\";\nimport type {\n\tWebhookDeliveryIntentStatus,\n\tWebhookFanOutJobStatus,\n\tWebhookRequeueEvidence,\n} from \"./types\";\n\n/*\n * What the memory and PostgreSQL delivery stores share: the readers that\n * copy and validate each method's arguments at entry, the in-memory shape of\n * a job and an intent, and the functions that render records, requeue\n * evidence and settlements from that shape. Both stores call these, so the\n * input they accept, the identifier fields they validate and the records\n * they return cannot drift apart (README, \"Stores\"). Internal: not exported\n * from the package entry point.\n */\n\nexport interface LeaseState {\n\treadonly owner: string;\n\treadonly fence: number;\n\treadonly expiresAtMs: number;\n}\n\nexport interface Leased {\n\treadonly key: string;\n\tstatus: string;\n\tavailableAtMs: number;\n\treadonly createdAtMs: number;\n\tfence: number;\n\tlease: LeaseState | undefined;\n}\n\nexport interface JobState extends Leased {\n\t/** Replaced, never mutated, by an actor enrichment; otherwise as inserted. */\n\tdraft: Snapshot;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly anchorMs: number;\n\tstatus: WebhookFanOutJobStatus;\n\tattemptCount: number;\n\tprocessingDeadlineMs: number;\n\tcompletedAtMs: number | undefined;\n\tlastDiagnostic: WebhookDiagnosticCode | undefined;\n}\n\nexport interface IntentState extends Leased {\n\treadonly subscriptionId: string;\n\treadonly eventId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly eligibilityRevision: number;\n\treadonly body: string;\n\treadonly anchorMs: number;\n\tstatus: WebhookDeliveryIntentStatus;\n\tattemptCount: number;\n\tprocessingDeadlineMs: number;\n\tlastOutcome: { readonly outcome: WebhookAttemptOutcome; readonly reason: WebhookAttemptReasonCode } | undefined;\n\tlastDiagnostic: WebhookDiagnosticCode | undefined;\n}\n\n/** The uniqueness marker for one (subscriptionId, eventId): the tombstone. */\nexport interface MarkerState {\n\treadonly kind: \"intent\" | \"denial\";\n\treadonly subscriptionId: string;\n\treadonly eventId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly anchorMs: number;\n}\n\nexport const TERMINAL_JOB: readonly string[] = Object.freeze([\"completed\", \"dead_letter\"]);\nexport const TERMINAL_INTENT: readonly string[] = Object.freeze([\"delivered\", \"dead_letter\", \"cancelled\"]);\nconst SETTLEMENT_KINDS = Object.freeze([\"delivered\", \"retry\", \"release\", \"dead_letter\", \"cancelled\"] as const);\nconst CANCEL_REASONS = Object.freeze([\"subscription_paused\", \"subscription_deleted\"] as const);\nconst DEAD_LETTER_REASONS: readonly string[] = Object.freeze([...WEBHOOK_ATTEMPT_REASON_CODES, ...WEBHOOK_DIAGNOSTIC_CODES]);\nconst EXPECTED_STATUS = Object.freeze([\"dead_letter\"] as const);\n\n/**\n * A fresh, frozen, null-prototype deep copy of a value the store built. It\n * has no depth or size limit, so every record the store accepted can be\n * returned (`cloneOut` in src/store-input.ts).\n */\nexport function copyOut<T>(value: object): T {\n\treturn cloneOut<T>(value);\n}\n\n/** The key of one (subscriptionId, eventId) pair; JSON-encoded, so distinct pairs never collide. */\nexport function markerKey(subscriptionId: string, eventId: string): string {\n\treturn compositeKey(subscriptionId, eventId);\n}\n\nexport interface Scope {\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n}\n\nexport function inScope(record: { readonly tenantId: string; readonly spaceId: string }, scope: Scope): boolean {\n\treturn record.tenantId === scope.tenantId && record.spaceId === scope.spaceId;\n}\n\n/**\n * `true` when `owner` holds the record's lease at `fence`, ignoring expiry. A\n * lease's fence is always the record's fence. Only for a decision made\n * before the store's clock is read (the PostgreSQL lock phase's tentative\n * inserts); the decision itself is {@link holds}.\n */\nexport function holdsFence(state: Leased, owner: string, fence: number): boolean {\n\treturn state.status === \"pending\" && state.lease !== undefined && state.lease.owner === owner && state.lease.fence === fence;\n}\n\n/**\n * `true` when `owner` holds the record's lease at `fence` and the lease has\n * not expired at `storeNowMs`, the store's own clock read inside the atomic\n * step (memory) or after every lock is held (PostgreSQL). Every fenced write\n * decides with it, so a write after the lease expired is refused even when\n * no other worker has reclaimed the record yet.\n */\nexport function holds(state: Leased, owner: string, fence: number, storeNowMs: number): boolean {\n\treturn holdsFence(state, owner, fence) && state.lease!.expiresAtMs > storeNowMs;\n}\n\n/** UTF-16 code unit order, as JavaScript's `<` compares strings. */\nexport function compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n\n/** Entry: snapshot the arguments. Anything not package-made becomes `input_invalid`. */\nfunction entry<T>(read: () => T): T {\n\treturn guard(read, () => storeError(\"input_invalid\", \"input\"));\n}\n\n/**\n * Read a store's `replayHorizonMs` option, as the constructor of either\n * store does: an own data property, never a getter, validated by\n * `assertReplayHorizon`.\n */\nexport function readHorizonOption(options: unknown): number {\n\treturn guard(\n\t\t() => {\n\t\t\tif (options === null || typeof options !== \"object\") throw configError(\"limit_unreadable\", \"options\");\n\t\t\tconst value = primitive(readOwn(options, \"replayHorizonMs\", \"replayHorizonMs\", () => {\n\t\t\t\tthrow configError(\"limit_unreadable\", \"replayHorizonMs\");\n\t\t\t}));\n\t\t\tassertReplayHorizon(value, \"replayHorizonMs\");\n\t\t\treturn value;\n\t\t},\n\t\t() => configError(\"limit_unreadable\", \"replayHorizonMs\"),\n\t);\n}\n\n/** Read an optional test-seam function option; anything else is `input_invalid`. */\nexport function readHookOption<T extends (...args: never[]) => unknown>(options: unknown, key: string): T | undefined {\n\treturn guard(() => {\n\t\tconst hook = (options as Record<string, unknown>)[key];\n\t\tif (hook !== undefined && typeof hook !== \"function\") throw storeError(\"input_invalid\", key);\n\t\treturn hook as T | undefined;\n\t}, () => storeError(\"input_invalid\", key));\n}\n\nfunction readScope(input: Snapshot, field: string): Scope {\n\treturn { tenantId: identifier(input, \"tenantId\", `${field}.tenantId`), spaceId: identifier(input, \"spaceId\", `${field}.spaceId`) };\n}\n\nexport interface FencedInput {\n\treadonly owner: string;\n\treadonly fence: number;\n\treadonly nowMs: number;\n}\n\nfunction readFenced(input: Snapshot): FencedInput {\n\treturn { owner: identifier(input, \"owner\", \"input.owner\"), fence: wholeNumber(input, \"fence\", \"input.fence\", 0), nowMs: instant(input, \"now\", \"input.now\") };\n}\n\nexport interface ClaimInput {\n\treadonly workerId: string;\n\treadonly leaseDurationMs: number;\n\treadonly limit: number;\n\treadonly nowMs: number;\n}\n\nfunction readClaim(request: unknown): ClaimInput {\n\tconst input = snapshotRecord(request, \"request\");\n\tconst claim: ClaimInput = {\n\t\tworkerId: identifier(input, \"workerId\", \"request.workerId\"),\n\t\tleaseDurationMs: wholeNumber(input, \"leaseDurationMs\", \"request.leaseDurationMs\", 1),\n\t\tlimit: wholeNumber(input, \"limit\", \"request.limit\", 1),\n\t\tnowMs: instant(input, \"now\", \"request.now\"),\n\t};\n\t// The lease expiry must be a representable time, checked before anything is leased.\n\tif (claim.nowMs + claim.leaseDurationMs > MAX_TIME_MS) throw storeError(\"input_invalid\", \"request.leaseDurationMs\");\n\treturn claim;\n}\n\nexport interface RequeueInput {\n\treadonly expectedFence: number;\n\treadonly requestedBy: string;\n\treadonly requestedAtMs: number;\n\treadonly processingDeadlineMs: number;\n\treadonly actionInvocationId: string | undefined;\n}\n\nfunction readRequeueRequest(input: Snapshot): RequeueInput {\n\tconst request = nestedRecord(input, \"request\", \"input.request\");\n\tcodeOf(request, \"expectedStatus\", EXPECTED_STATUS, \"input.request.expectedStatus\");\n\treturn {\n\t\texpectedFence: wholeNumber(request, \"expectedFence\", \"input.request.expectedFence\", 0),\n\t\trequestedBy: identifier(request, \"requestedBy\", \"input.request.requestedBy\"),\n\t\trequestedAtMs: instant(request, \"requestedAt\", \"input.request.requestedAt\"),\n\t\tprocessingDeadlineMs: instant(request, \"processingDeadline\", \"input.request.processingDeadline\"),\n\t\tactionInvocationId: optionalIdentifier(request, \"actionInvocationId\", \"input.request.actionInvocationId\"),\n\t};\n}\n\nfunction readParent(parent: unknown): WebhookFanOutJobFence {\n\tconst input = snapshotRecord(parent, \"parent\");\n\treturn { eventId: identifier(input, \"eventId\", \"parent.eventId\"), owner: identifier(input, \"owner\", \"parent.owner\"), fence: wholeNumber(input, \"fence\", \"parent.fence\", 0) };\n}\n\n// ---------------------------------------------------------------------------\n// Per-method entry readers. Each copies and validates every argument, the\n// call options included, and refuses malformed input as `input_invalid`\n// before the store does anything else.\n// ---------------------------------------------------------------------------\n\nexport function readInsertFanOutJobCall(job: unknown, options: unknown) {\n\treturn entry(() => ({ bounds: readCallOptions(options), job: readJobDraft(job) }));\n}\n\nexport function readClaimCall(request: unknown, options: unknown) {\n\treturn entry(() => ({ bounds: readCallOptions(options), claim: readClaim(request) }));\n}\n\nexport function readJobFencedCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), fenced: readFenced(snap), eventId: identifier(snap, \"eventId\", \"input.eventId\") };\n\t});\n}\n\nexport function readRescheduleCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tfenced: readFenced(snap),\n\t\t\teventId: identifier(snap, \"eventId\", \"input.eventId\"),\n\t\t\tavailableAtMs: instant(snap, \"availableAt\", \"input.availableAt\"),\n\t\t\tdiagnostic: codeOf(snap, \"diagnostic\", WEBHOOK_DIAGNOSTIC_CODES, \"input.diagnostic\"),\n\t\t};\n\t});\n}\n\n/** The lease duration a renewal asks for: a whole number of ms whose expiry from `now` is a representable time. */\nfunction readRenewal(snap: Snapshot, fenced: FencedInput): number {\n\tconst leaseDurationMs = wholeNumber(snap, \"leaseDurationMs\", \"input.leaseDurationMs\", 1);\n\tif (fenced.nowMs + leaseDurationMs > MAX_TIME_MS) throw storeError(\"input_invalid\", \"input.leaseDurationMs\");\n\treturn leaseDurationMs;\n}\n\nexport function readRenewJobCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst fenced = readFenced(snap);\n\t\treturn { bounds: readCallOptions(options), fenced, eventId: identifier(snap, \"eventId\", \"input.eventId\"), leaseDurationMs: readRenewal(snap, fenced) };\n\t});\n}\n\nexport function readRenewIntentCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst fenced = readFenced(snap);\n\t\treturn { bounds: readCallOptions(options), fenced, deliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"), leaseDurationMs: readRenewal(snap, fenced) };\n\t});\n}\n\n/**\n * The expiry a renewal sets on a lease the caller holds: the later of the\n * current expiry and the earlier of `nowMs + leaseDurationMs` (the caller's\n * `now`, as a claim uses it) and the record's processing deadline. So a\n * renewal never shortens a lease and never extends one past the deadline.\n * Whether the caller holds the lease is decided by {@link holds} first.\n */\nexport function renewedExpiryMs(state: Leased & { readonly processingDeadlineMs: number }, nowMs: number, leaseDurationMs: number): number {\n\tconst asked = mathMin(nowMs + leaseDurationMs, state.processingDeadlineMs);\n\tconst current = state.lease!.expiresAtMs;\n\treturn asked > current ? asked : current;\n}\n\nexport function readDeadLetterJobCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tfenced: readFenced(snap),\n\t\t\teventId: identifier(snap, \"eventId\", \"input.eventId\"),\n\t\t\tdiagnostic: codeOf(snap, \"diagnostic\", WEBHOOK_DIAGNOSTIC_CODES, \"input.diagnostic\"),\n\t\t};\n\t});\n}\n\nexport interface EnrichmentInput extends RequeueInput {\n\treadonly actorId: string;\n\treadonly actorType: string;\n}\n\n/** `enrichFanOutJobActor`: a scope, an `eventId` and the request, with the actor read field by field. */\nexport function readJobEnrichmentCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst request = nestedRecord(snap, \"request\", \"input.request\");\n\t\tconst actor = nestedRecord(request, \"actor\", \"input.request.actor\");\n\t\tconst read: EnrichmentInput = {\n\t\t\texpectedFence: wholeNumber(request, \"expectedFence\", \"input.request.expectedFence\", 0),\n\t\t\trequestedBy: identifier(request, \"requestedBy\", \"input.request.requestedBy\"),\n\t\t\trequestedAtMs: instant(request, \"requestedAt\", \"input.request.requestedAt\"),\n\t\t\tprocessingDeadlineMs: instant(request, \"processingDeadline\", \"input.request.processingDeadline\"),\n\t\t\tactionInvocationId: optionalIdentifier(request, \"actionInvocationId\", \"input.request.actionInvocationId\"),\n\t\t\tactorId: identifier(actor, \"actorId\", \"input.request.actor.actorId\"),\n\t\t\tactorType: identifier(actor, \"actorType\", \"input.request.actor.actorType\"),\n\t\t};\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), eventId: identifier(snap, \"eventId\", \"input.eventId\"), request: read };\n\t});\n}\n\nexport function readJobRequeueCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), eventId: identifier(snap, \"eventId\", \"input.eventId\"), request: readRequeueRequest(snap) };\n\t});\n}\n\n/** `readFanOutJob` and `listRequeueEvidence`: a scope and an `eventId`. */\nexport function readEventCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), eventId: identifier(snap, \"eventId\", \"input.eventId\") };\n\t});\n}\n\nexport function readInsertIntentCall(intent: unknown, parent: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(intent, \"intent\");\n\t\tconst fence = readParent(parent);\n\t\tconst read = {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tparent: fence,\n\t\t\tdeliveryId: identifier(snap, \"deliveryId\", \"intent.deliveryId\"),\n\t\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"intent.subscriptionId\"),\n\t\t\teventId: identifier(snap, \"eventId\", \"intent.eventId\"),\n\t\t\ttenantId: identifier(snap, \"tenantId\", \"intent.tenantId\"),\n\t\t\tspaceId: identifier(snap, \"spaceId\", \"intent.spaceId\"),\n\t\t\teligibilityRevision: wholeNumber(snap, \"eligibilityRevision\", \"intent.eligibilityRevision\", 1),\n\t\t\tbody: text(snap, \"body\", \"intent.body\"),\n\t\t\tavailableAtMs: instant(snap, \"availableAt\", \"intent.availableAt\"),\n\t\t\tprocessingDeadlineMs: instant(snap, \"processingDeadline\", \"intent.processingDeadline\"),\n\t\t\tcreatedAtMs: instant(snap, \"createdAt\", \"intent.createdAt\"),\n\t\t};\n\t\tif (read.eventId !== fence.eventId) throw storeError(\"record_mismatch\", \"intent.eventId\");\n\t\treturn read;\n\t});\n}\n\nexport function readDenialCall(record: unknown, parent: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(record, \"record\");\n\t\tconst fence = readParent(parent);\n\t\tconst read = {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tparent: fence,\n\t\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"record.subscriptionId\"),\n\t\t\teventId: identifier(snap, \"eventId\", \"record.eventId\"),\n\t\t\ttenantId: identifier(snap, \"tenantId\", \"record.tenantId\"),\n\t\t\tspaceId: identifier(snap, \"spaceId\", \"record.spaceId\"),\n\t\t\teligibilityRevision: wholeNumber(snap, \"eligibilityRevision\", \"record.eligibilityRevision\", 1),\n\t\t\tcode: codeOf<WebhookAdmissionDenialCode>(snap, \"code\", WEBHOOK_ADMISSION_DENIAL_CODES, \"record.code\"),\n\t\t\trecordedAtMs: instant(snap, \"recordedAt\", \"record.recordedAt\"),\n\t\t};\n\t\tif (read.eventId !== fence.eventId) throw storeError(\"record_mismatch\", \"record.eventId\");\n\t\treturn read;\n\t});\n}\n\n/** The denial record a store keeps, built from a validated call. */\nexport function denialRecord(call: ReturnType<typeof readDenialCall>): Snapshot {\n\treturn copyOut<Snapshot>({\n\t\tsubscriptionId: call.subscriptionId,\n\t\teventId: call.eventId,\n\t\ttenantId: call.tenantId,\n\t\tspaceId: call.spaceId,\n\t\teligibilityRevision: call.eligibilityRevision,\n\t\tcode: call.code,\n\t\trecordedAt: isoOf(call.recordedAtMs),\n\t});\n}\n\nexport function readLeaseCheckCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tscope: readScope(snap, \"input\"),\n\t\t\tdeliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"),\n\t\t\tfenced: readFenced(snap),\n\t\t};\n\t});\n}\n\nexport function readAppendAttemptCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst attempt = nestedRecord(snap, \"attempt\", \"input.attempt\");\n\t\tconst httpStatus = optionalWholeNumber(attempt, \"httpStatus\", \"input.attempt.httpStatus\", 100);\n\t\tif (httpStatus !== undefined && httpStatus > 599) throw storeError(\"input_invalid\", \"input.attempt.httpStatus\");\n\t\tconst record = copyOut<Snapshot>({\n\t\t\tdeliveryId: identifier(attempt, \"deliveryId\", \"input.attempt.deliveryId\"),\n\t\t\tsubscriptionId: identifier(attempt, \"subscriptionId\", \"input.attempt.subscriptionId\"),\n\t\t\teventId: identifier(attempt, \"eventId\", \"input.attempt.eventId\"),\n\t\t\tattempt: wholeNumber(attempt, \"attempt\", \"input.attempt.attempt\", 1),\n\t\t\tconfigurationVersion: wholeNumber(attempt, \"configurationVersion\", \"input.attempt.configurationVersion\", 1),\n\t\t\tstartedAt: isoOf(instant(attempt, \"startedAt\", \"input.attempt.startedAt\")),\n\t\t\tfinishedAt: isoOf(instant(attempt, \"finishedAt\", \"input.attempt.finishedAt\")),\n\t\t\toutcome: codeOf(attempt, \"outcome\", WEBHOOK_ATTEMPT_OUTCOMES, \"input.attempt.outcome\"),\n\t\t\treason: codeOf(attempt, \"reason\", WEBHOOK_ATTEMPT_REASON_CODES, \"input.attempt.reason\"),\n\t\t\thttpStatus,\n\t\t});\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tfenced: readFenced(snap),\n\t\t\trecord,\n\t\t\tdeliveryId: record[\"deliveryId\"] as string,\n\t\t\tsubscriptionId: record[\"subscriptionId\"] as string,\n\t\t\teventId: record[\"eventId\"] as string,\n\t\t};\n\t});\n}\n\n/**\n * `beginAttempt`: the fence, and the start of the attempt. The record kept\n * holds only the `WebhookDeliveryAttemptStart` fields, read one by one.\n */\nexport function readBeginAttemptCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst attempt = nestedRecord(snap, \"attempt\", \"input.attempt\");\n\t\tconst record = copyOut<Snapshot>({\n\t\t\tdeliveryId: identifier(attempt, \"deliveryId\", \"input.attempt.deliveryId\"),\n\t\t\tsubscriptionId: identifier(attempt, \"subscriptionId\", \"input.attempt.subscriptionId\"),\n\t\t\teventId: identifier(attempt, \"eventId\", \"input.attempt.eventId\"),\n\t\t\tattempt: wholeNumber(attempt, \"attempt\", \"input.attempt.attempt\", 1),\n\t\t\tconfigurationVersion: wholeNumber(attempt, \"configurationVersion\", \"input.attempt.configurationVersion\", 1),\n\t\t\tstartedAt: isoOf(instant(attempt, \"startedAt\", \"input.attempt.startedAt\")),\n\t\t});\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tfenced: readFenced(snap),\n\t\t\trecord,\n\t\t\tdeliveryId: record[\"deliveryId\"] as string,\n\t\t\tsubscriptionId: record[\"subscriptionId\"] as string,\n\t\t\teventId: record[\"eventId\"] as string,\n\t\t};\n\t});\n}\n\n/** `finishAttempt`: a scope, the begun attempt's key, and its outcome. */\nexport function readFinishAttemptCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tconst finish = nestedRecord(snap, \"finish\", \"input.finish\");\n\t\tconst httpStatus = optionalWholeNumber(finish, \"httpStatus\", \"input.finish.httpStatus\", 100);\n\t\tif (httpStatus !== undefined && httpStatus > 599) throw storeError(\"input_invalid\", \"input.finish.httpStatus\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tscope: readScope(snap, \"input\"),\n\t\t\tdeliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"),\n\t\t\tfence: wholeNumber(snap, \"fence\", \"input.fence\", 0),\n\t\t\t// Read like an identifier; an error names the field, never the value.\n\t\t\treceipt: identifier(snap, \"receipt\", \"input.receipt\"),\n\t\t\trecord: copyOut<Snapshot>({\n\t\t\t\tfinishedAt: isoOf(instant(finish, \"finishedAt\", \"input.finish.finishedAt\")),\n\t\t\t\toutcome: codeOf(finish, \"outcome\", WEBHOOK_ATTEMPT_OUTCOMES, \"input.finish.outcome\"),\n\t\t\t\treason: codeOf(finish, \"reason\", WEBHOOK_ATTEMPT_REASON_CODES, \"input.finish.reason\"),\n\t\t\t\thttpStatus,\n\t\t\t}),\n\t\t};\n\t});\n}\n\n/** The key of the attempt begun under one lease of one intent. */\nexport function attemptKey(deliveryId: string, fence: number): string {\n\treturn compositeKey(deliveryId, `${fence}`);\n}\n\n/**\n * Whether `beginAttempt` may record an attempt on `intent`: pending, leased\n * to the caller at its fence, and the lease not expired at the store's\n * clock read in the atomic step.\n */\nexport function mayBegin(intent: IntentState | undefined, fenced: FencedInput, storeNowMs: number): intent is IntentState {\n\treturn intent !== undefined && holds(intent, fenced.owner, fenced.fence, storeNowMs);\n}\n\n/**\n * One attempt log entry as `listDeliveryAttempts` returns it. `fence` is\n * `undefined` for an entry appended whole; otherwise the entry was begun\n * under that fence and `finish` is its outcome, or `undefined` while none is\n * recorded.\n */\nexport function attemptEntryOut(start: Snapshot, fence: number | undefined, finish: Snapshot | undefined): object {\n\tif (fence === undefined) return start;\n\tif (finish === undefined) return { ...start, fence, outcome: \"in_flight\" };\n\treturn { ...start, ...finish, fence };\n}\n\nexport function beginResult(receipt: string | undefined): WebhookAttemptBeginResult {\n\treturn copyOut<WebhookAttemptBeginResult>(receipt === undefined ? { begun: false } : { begun: true, receipt });\n}\n\nexport function readSettleCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), fenced: readFenced(snap), deliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"), settlement: readSettlement(snap) };\n\t});\n}\n\nexport function readCancelCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\tinstant(snap, \"now\", \"input.now\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tscope: readScope(snap, \"input\"),\n\t\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"input.subscriptionId\"),\n\t\t\treason: codeOf(snap, \"reason\", CANCEL_REASONS, \"input.reason\"),\n\t\t\tbeforeRevision: wholeNumber(snap, \"beforeRevision\", \"input.beforeRevision\", 1),\n\t\t};\n\t});\n}\n\nexport function readIntentRequeueCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), deliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\"), request: readRequeueRequest(snap) };\n\t});\n}\n\n/** `readDeliveryIntent` and `listDeliveryAttempts`: a scope and a `deliveryId`. */\nexport function readDeliveryCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), deliveryId: identifier(snap, \"deliveryId\", \"input.deliveryId\") };\n\t});\n}\n\nexport function readTombstoneCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\tscope: readScope(snap, \"input\"),\n\t\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"input.subscriptionId\"),\n\t\t\teventId: identifier(snap, \"eventId\", \"input.eventId\"),\n\t\t};\n\t});\n}\n\nexport function readPurgeCall(input: unknown, options: unknown): { readonly bounds: CallBounds; readonly limit: number } {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), limit: wholeNumber(snap, \"limit\", \"input.limit\", 1) };\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Job drafts\n// ---------------------------------------------------------------------------\n\nexport interface JobDraftInput {\n\treadonly draft: Snapshot;\n\treadonly eventId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly anchorMs: number;\n\treadonly createdAtMs: number;\n\treadonly processingDeadlineMs: number;\n}\n\nconst ACTOR_STATES = Object.freeze([\"present\", \"absent\"] as const);\n\nconst PAYLOAD_CLASSIFICATIONS = Object.freeze([\"public\", \"internal\", \"confidential\", \"restricted\"] as const);\nconst CONSISTENCIES = Object.freeze([\"authoritative-now\", \"provisional-until-reconciled\"] as const);\nconst ABSENT_REASONS = Object.freeze([\"suppressed\", \"legacy\"] as const);\nconst ANY_INTEGER = Number.MIN_SAFE_INTEGER;\n\n/**\n * Rebuild the event metadata from an explicit allowlist of\n * `WebhookEventMetadata` fields (R7). Nothing else on the caller's object,\n * such as a payload, trace context, provenance or a secret, is copied.\n */\nfunction readEventMetadata(event: Snapshot): object {\n\tconst consistency = event[\"consistency\"] === undefined ? undefined : codeOf(event, \"consistency\", CONSISTENCIES, \"job.event.consistency\");\n\treturn {\n\t\teventId: identifier(event, \"eventId\", \"job.event.eventId\"),\n\t\teventType: identifier(event, \"eventType\", \"job.event.eventType\"),\n\t\teventSchemaVersion: wholeNumber(event, \"eventSchemaVersion\", \"job.event.eventSchemaVersion\", ANY_INTEGER),\n\t\ttenantId: identifier(event, \"tenantId\", \"job.event.tenantId\"),\n\t\tspaceId: identifier(event, \"spaceId\", \"job.event.spaceId\"),\n\t\tsubjectType: identifier(event, \"subjectType\", \"job.event.subjectType\"),\n\t\tsubjectId: identifier(event, \"subjectId\", \"job.event.subjectId\"),\n\t\tsequence: wholeNumber(event, \"sequence\", \"job.event.sequence\", ANY_INTEGER),\n\t\tactionInvocationId: optionalIdentifier(event, \"actionInvocationId\", \"job.event.actionInvocationId\"),\n\t\tcorrelationId: identifier(event, \"correlationId\", \"job.event.correlationId\"),\n\t\tcausationId: optionalIdentifier(event, \"causationId\", \"job.event.causationId\"),\n\t\toccurredAt: isoOf(instant(event, \"occurredAt\", \"job.event.occurredAt\")),\n\t\trecordedAt: isoOf(instant(event, \"recordedAt\", \"job.event.recordedAt\")),\n\t\tproducerModuleVersion: identifier(event, \"producerModuleVersion\", \"job.event.producerModuleVersion\"),\n\t\tpayloadClassification: codeOf(event, \"payloadClassification\", PAYLOAD_CLASSIFICATIONS, \"job.event.payloadClassification\"),\n\t\tconsistency,\n\t};\n}\n\n/** Rebuild the job actor as one member of the `WebhookJobActor` union, nothing more. */\nfunction readActor(actor: Snapshot): object {\n\tconst state = codeOf(actor, \"state\", ACTOR_STATES, \"job.actor.state\");\n\tif (state === \"present\") {\n\t\treturn { state, actorId: identifier(actor, \"actorId\", \"job.actor.actorId\"), actorType: identifier(actor, \"actorType\", \"job.actor.actorType\") };\n\t}\n\treturn { state, reason: codeOf(actor, \"reason\", ABSENT_REASONS, \"job.actor.reason\") };\n}\n\nfunction readJobDraft(job: unknown): JobDraftInput {\n\tconst snap = snapshotRecord(job, \"job\");\n\tconst eventId = identifier(snap, \"eventId\", \"job.eventId\");\n\tconst tenantId = identifier(snap, \"tenantId\", \"job.tenantId\");\n\tconst spaceId = identifier(snap, \"spaceId\", \"job.spaceId\");\n\tconst event = nestedRecord(snap, \"event\", \"job.event\");\n\tif (identifier(event, \"eventId\", \"job.event.eventId\") !== eventId) throw storeError(\"record_mismatch\", \"job.event.eventId\");\n\tif (identifier(event, \"tenantId\", \"job.event.tenantId\") !== tenantId) throw storeError(\"record_mismatch\", \"job.event.tenantId\");\n\tif (identifier(event, \"spaceId\", \"job.event.spaceId\") !== spaceId) throw storeError(\"record_mismatch\", \"job.event.spaceId\");\n\tconst anchorMs = instant(event, \"recordedAt\", \"job.event.recordedAt\");\n\tconst payloadProjected = flag(snap, \"payloadProjected\", \"job.payloadProjected\");\n\tlet payload: Snapshot | null = null;\n\tif (payloadProjected) payload = nestedRecord(snap, \"payload\", \"job.payload\");\n\telse if (snap[\"payload\"] !== null) throw storeError(\"input_invalid\", \"job.payload\");\n\t// Only the fields WebhookFanOutJobDraft declares are kept. `payload` and\n\t// `facts` are the projection's allowlisted JSON and are kept whole.\n\tconst draft = copyOut<Snapshot>({\n\t\tevent: readEventMetadata(event),\n\t\tpayload,\n\t\tpayloadProjected,\n\t\tfacts: nestedRecord(snap, \"facts\", \"job.facts\"),\n\t\tactor: readActor(nestedRecord(snap, \"actor\", \"job.actor\")),\n\t});\n\treturn {\n\t\tdraft,\n\t\teventId,\n\t\ttenantId,\n\t\tspaceId,\n\t\tanchorMs,\n\t\tcreatedAtMs: instant(snap, \"createdAt\", \"job.createdAt\"),\n\t\tprocessingDeadlineMs: instant(snap, \"processingDeadline\", \"job.processingDeadline\"),\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Settlements\n// ---------------------------------------------------------------------------\n\nexport type Settlement =\n\t| { readonly kind: \"delivered\" }\n\t| { readonly kind: \"retry\"; readonly availableAtMs: number; readonly outcome: WebhookAttemptOutcome; readonly reason: WebhookAttemptReasonCode }\n\t| { readonly kind: \"release\"; readonly availableAtMs: number; readonly diagnostic: WebhookDiagnosticCode }\n\t| { readonly kind: \"dead_letter\"; readonly reason: WebhookAttemptReasonCode | WebhookDiagnosticCode }\n\t| { readonly kind: \"cancelled\"; readonly reason: WebhookAttemptReasonCode };\n\nfunction readSettlement(input: Snapshot): Settlement {\n\tconst settlement = nestedRecord(input, \"settlement\", \"input.settlement\");\n\tconst kind = codeOf(settlement, \"kind\", SETTLEMENT_KINDS, \"input.settlement.kind\");\n\tswitch (kind) {\n\t\tcase \"delivered\":\n\t\t\treturn { kind };\n\t\tcase \"retry\":\n\t\t\treturn {\n\t\t\t\tkind,\n\t\t\t\tavailableAtMs: instant(settlement, \"availableAt\", \"input.settlement.availableAt\"),\n\t\t\t\toutcome: codeOf(settlement, \"outcome\", WEBHOOK_ATTEMPT_OUTCOMES, \"input.settlement.outcome\"),\n\t\t\t\treason: codeOf(settlement, \"reason\", WEBHOOK_ATTEMPT_REASON_CODES, \"input.settlement.reason\"),\n\t\t\t};\n\t\tcase \"release\":\n\t\t\treturn {\n\t\t\t\tkind,\n\t\t\t\tavailableAtMs: instant(settlement, \"availableAt\", \"input.settlement.availableAt\"),\n\t\t\t\tdiagnostic: codeOf(settlement, \"diagnostic\", WEBHOOK_DIAGNOSTIC_CODES, \"input.settlement.diagnostic\"),\n\t\t\t};\n\t\tcase \"dead_letter\":\n\t\t\treturn { kind, reason: codeOf(settlement, \"reason\", DEAD_LETTER_REASONS, \"input.settlement.reason\") as WebhookAttemptReasonCode | WebhookDiagnosticCode };\n\t\tcase \"cancelled\":\n\t\t\treturn { kind, reason: codeOf(settlement, \"reason\", WEBHOOK_ATTEMPT_REASON_CODES, \"input.settlement.reason\") };\n\t}\n}\n\nfunction isAttemptReason(value: string): value is WebhookAttemptReasonCode {\n\treturn (WEBHOOK_ATTEMPT_REASON_CODES as readonly string[]).includes(value);\n}\n\n/**\n * Apply a settlement to an intent the caller holds, clearing its lease.\n * `release` spends no budget, `retry` spends one attempt, and the terminal\n * kinds leave the attempt count as it was.\n */\nexport function applySettlement(intent: IntentState, settlement: Settlement): void {\n\tswitch (settlement.kind) {\n\t\tcase \"delivered\":\n\t\t\tintent.status = \"delivered\";\n\t\t\tintent.lastOutcome = { outcome: \"delivered\", reason: \"http_2xx\" };\n\t\t\tbreak;\n\t\tcase \"retry\":\n\t\t\tintent.attemptCount += 1;\n\t\t\tintent.availableAtMs = settlement.availableAtMs;\n\t\t\tintent.lastOutcome = { outcome: settlement.outcome, reason: settlement.reason };\n\t\t\tbreak;\n\t\tcase \"release\":\n\t\t\tintent.availableAtMs = settlement.availableAtMs;\n\t\t\tintent.lastDiagnostic = settlement.diagnostic;\n\t\t\tbreak;\n\t\tcase \"dead_letter\":\n\t\t\tintent.status = \"dead_letter\";\n\t\t\tif (isAttemptReason(settlement.reason)) intent.lastOutcome = { outcome: \"dead_letter\", reason: settlement.reason };\n\t\t\telse intent.lastDiagnostic = settlement.reason;\n\t\t\tbreak;\n\t\tcase \"cancelled\":\n\t\t\tintent.status = \"cancelled\";\n\t\t\tintent.lastOutcome = { outcome: \"cancelled\", reason: settlement.reason };\n\t\t\tbreak;\n\t}\n\tintent.lease = undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Requeue\n// ---------------------------------------------------------------------------\n\n/** The first refusal a requeue meets, in the port's order, or `undefined` when it applies. */\nexport function requeueRefusal(\n\tstate: { readonly fence: number; readonly status: string; readonly anchorMs: number },\n\trequest: RequeueInput,\n\tfloorMs: number,\n): \"stale\" | \"not_dead_letter\" | \"past_horizon\" | undefined {\n\t// The dead-letter generation the operator saw, in the same step as the\n\t// transition: a second request from that read finds the advanced fence.\n\tif (state.fence !== request.expectedFence) return \"stale\";\n\tif (state.status !== \"dead_letter\") return \"not_dead_letter\";\n\tif (state.anchorMs < floorMs) return \"past_horizon\";\n\treturn undefined;\n}\n\nexport function jobRequeueEvidence(job: JobState, request: RequeueInput, nowMs: number): WebhookRequeueEvidence {\n\treturn copyOut<WebhookRequeueEvidence>({\n\t\ttarget: \"fan_out_job\",\n\t\teventId: job.key,\n\t\ttenantId: job.tenantId,\n\t\tspaceId: job.spaceId,\n\t\trequestedBy: request.requestedBy,\n\t\trequestedAt: isoOf(request.requestedAtMs),\n\t\tactionInvocationId: request.actionInvocationId,\n\t\tappliedAt: isoOf(nowMs),\n\t\tpriorAttemptCount: job.attemptCount,\n\t\tpriorAvailableAt: isoOf(job.availableAtMs),\n\t\tpriorProcessingDeadline: isoOf(job.processingDeadlineMs),\n\t\tpriorFence: job.fence,\n\t\tpriorLastDiagnostic: job.lastDiagnostic,\n\t\tprocessingDeadline: isoOf(request.processingDeadlineMs),\n\t});\n}\n\nexport function intentRequeueEvidence(intent: IntentState, request: RequeueInput, nowMs: number): WebhookRequeueEvidence {\n\treturn copyOut<WebhookRequeueEvidence>({\n\t\ttarget: \"delivery_intent\",\n\t\teventId: intent.eventId,\n\t\tdeliveryId: intent.key,\n\t\tsubscriptionId: intent.subscriptionId,\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\trequestedBy: request.requestedBy,\n\t\trequestedAt: isoOf(request.requestedAtMs),\n\t\tactionInvocationId: request.actionInvocationId,\n\t\tappliedAt: isoOf(nowMs),\n\t\tpriorAttemptCount: intent.attemptCount,\n\t\tpriorAvailableAt: isoOf(intent.availableAtMs),\n\t\tpriorProcessingDeadline: isoOf(intent.processingDeadlineMs),\n\t\tpriorFence: intent.fence,\n\t\tpriorLastDiagnostic: intent.lastDiagnostic,\n\t\tpriorLastOutcome: intent.lastOutcome,\n\t\tprocessingDeadline: isoOf(request.processingDeadlineMs),\n\t});\n}\n\n/**\n * The first refusal an actor enrichment meets, in the port's order, or\n * `undefined` when it applies. Run inside the atomic step, so the actor\n * state checked is the stored one: a `suppressed` or `present` actor is\n * refused here whatever the caller read before.\n */\nexport function enrichmentRefusal(\n\tjob: JobState,\n\trequest: EnrichmentInput,\n\tfloorMs: number,\n): Exclude<Extract<WebhookActorEnrichmentResult, { readonly applied: false }>[\"refusal\"], \"not_found\"> | undefined {\n\tif (job.fence !== request.expectedFence) return \"stale\";\n\tif (job.status === \"completed\") return \"not_enrichable\";\n\tconst actor = job.draft[\"actor\"] as Snapshot;\n\tif (actor[\"state\"] !== \"absent\") return \"actor_present\";\n\tif (actor[\"reason\"] !== \"legacy\") return \"actor_suppressed\";\n\tif (job.anchorMs < floorMs) return \"past_horizon\";\n\treturn undefined;\n}\n\nexport function jobEnrichmentEvidence(job: JobState, request: EnrichmentInput, nowMs: number): WebhookRequeueEvidence {\n\treturn copyOut<WebhookRequeueEvidence>({\n\t\t...(jobRequeueEvidence(job, request, nowMs) as object),\n\t\ttarget: \"fan_out_job_actor\",\n\t\tactor: { actorId: request.actorId, actorType: request.actorType },\n\t});\n}\n\n/**\n * Apply an enrichment to a job the atomic step accepted: the stored draft is\n * replaced by a copy whose actor is the one read from the canonical event,\n * and the job is requeued exactly as {@link applyRequeue} does, so its fence\n * advances and any lease is cleared.\n */\nexport function applyEnrichment(job: JobState, request: EnrichmentInput): void {\n\tjob.draft = copyOut<Snapshot>({ ...(job.draft as object), actor: { state: \"present\", actorId: request.actorId, actorType: request.actorType } });\n\tapplyRequeue(job, request);\n}\n\nexport function enrichmentRefused(reason: Extract<WebhookActorEnrichmentResult, { readonly applied: false }>[\"refusal\"]): WebhookActorEnrichmentResult {\n\treturn copyOut<WebhookActorEnrichmentResult>({ applied: false, refusal: reason });\n}\n\n/** Move a dead letter back to pending with a restored budget, advancing its fence. */\nexport function applyRequeue(state: JobState | IntentState, request: RequeueInput): void {\n\tstate.status = \"pending\";\n\tstate.attemptCount = 0;\n\tstate.availableAtMs = request.requestedAtMs;\n\tstate.processingDeadlineMs = request.processingDeadlineMs;\n\tstate.fence += 1;\n\tstate.lease = undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Rendering\n// ---------------------------------------------------------------------------\n\nfunction leaseOut(lease: LeaseState | undefined): object | undefined {\n\treturn lease === undefined ? undefined : { owner: lease.owner, fence: lease.fence, expiresAt: isoOf(lease.expiresAtMs) };\n}\n\nexport function jobOut(job: JobState, lease: LeaseState | undefined = job.lease): object {\n\tconst draft = job.draft;\n\treturn {\n\t\teventId: job.key,\n\t\ttenantId: job.tenantId,\n\t\tspaceId: job.spaceId,\n\t\tevent: draft[\"event\"],\n\t\tpayload: draft[\"payload\"],\n\t\tpayloadProjected: draft[\"payloadProjected\"],\n\t\tfacts: draft[\"facts\"],\n\t\tactor: draft[\"actor\"],\n\t\tstatus: job.status,\n\t\tattemptCount: job.attemptCount,\n\t\tavailableAt: isoOf(job.availableAtMs),\n\t\tprocessingDeadline: isoOf(job.processingDeadlineMs),\n\t\tcreatedAt: isoOf(job.createdAtMs),\n\t\tcompletedAt: job.completedAtMs === undefined ? undefined : isoOf(job.completedAtMs),\n\t\tlastDiagnostic: job.lastDiagnostic,\n\t\tfence: lease === undefined ? job.fence : lease.fence,\n\t\tlease: leaseOut(lease),\n\t};\n}\n\nexport function intentOut(intent: IntentState, lease: LeaseState | undefined = intent.lease): object {\n\treturn {\n\t\tdeliveryId: intent.key,\n\t\tsubscriptionId: intent.subscriptionId,\n\t\teventId: intent.eventId,\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\teligibilityRevision: intent.eligibilityRevision,\n\t\teventRecordedAt: isoOf(intent.anchorMs),\n\t\tbody: intent.body,\n\t\tstatus: intent.status,\n\t\tattemptCount: intent.attemptCount,\n\t\tavailableAt: isoOf(intent.availableAtMs),\n\t\tprocessingDeadline: isoOf(intent.processingDeadlineMs),\n\t\tcreatedAt: isoOf(intent.createdAtMs),\n\t\tlastOutcome: intent.lastOutcome,\n\t\tlastDiagnostic: intent.lastDiagnostic,\n\t\tfence: lease === undefined ? intent.fence : lease.fence,\n\t\tlease: leaseOut(lease),\n\t};\n}\n\n/** A tombstone as `readTombstone` returns it; `retainUntil` is the anchor plus the horizon, capped at the `Date` range. */\nexport function tombstoneOut(marker: MarkerState, horizonMs: number): object {\n\treturn {\n\t\tkind: marker.kind,\n\t\tsubscriptionId: marker.subscriptionId,\n\t\teventId: marker.eventId,\n\t\ttenantId: marker.tenantId,\n\t\tspaceId: marker.spaceId,\n\t\tretainUntil: isoOf(mathMin(marker.anchorMs + horizonMs, WEBHOOK_MAX_REPLAY_HORIZON_MS)),\n\t};\n}\n\n/**\n * The pre-handoff lease check: `valid` only when the intent is pending,\n * leased to this owner at this fence, in this scope, and the lease has not\n * expired at the caller's `now`.\n */\nexport function leaseCheck(intent: IntentState | undefined, call: ReturnType<typeof readLeaseCheckCall>): WebhookDeliveryLeaseCheck {\n\tif (intent === undefined || !inScope(intent, call.scope)) return copyOut<WebhookDeliveryLeaseCheck>({ valid: false, reason: \"not_found\" });\n\tif (intent.status !== \"pending\") return copyOut<WebhookDeliveryLeaseCheck>({ valid: false, reason: \"intent_not_pending\" });\n\tif (!holdsFence(intent, call.fenced.owner, call.fenced.fence) || intent.lease!.expiresAtMs <= call.fenced.nowMs) {\n\t\treturn copyOut<WebhookDeliveryLeaseCheck>({ valid: false, reason: \"lease_lost\" });\n\t}\n\treturn copyOut<WebhookDeliveryLeaseCheck>({ valid: true });\n}\n\nexport function requeueRefused(reason: \"not_found\" | \"stale\" | \"not_dead_letter\" | \"past_horizon\"): WebhookRequeueResult {\n\treturn copyOut<WebhookRequeueResult>({ applied: false, refusal: reason });\n}\n\n/** The record a governed requeue or enrichment names: a delivery intent's `deliveryId`, or a job's `eventId`. */\nexport type InvocationTarget =\n\t| { readonly target: \"delivery_intent\"; readonly deliveryId: string }\n\t| { readonly target: \"fan_out_job\" | \"fan_out_job_actor\"; readonly eventId: string };\n\n/**\n * Of `records`, the evidence of one scope appended under one\n * `actionInvocationId` (in append order), the first for `target` and its\n * record, or `undefined`. A store calls this inside the atomic step of a\n * requeue or enrichment, before any other check, so a request of the same\n * governed invocation is recognized whether or not the record still exists\n * or still matches the request.\n */\nexport function priorInvocationEvidence(records: readonly Snapshot[], target: InvocationTarget): Snapshot | undefined {\n\tfor (const record of records) {\n\t\tif (record[\"target\"] !== target.target) continue;\n\t\tif (target.target === \"delivery_intent\" ? record[\"deliveryId\"] === target.deliveryId : record[\"eventId\"] === target.eventId) return record;\n\t}\n\treturn undefined;\n}\n\n/** The answer to a request whose invocation already applied: that application's evidence, unchanged. */\nexport function replayedResult<T extends WebhookRequeueResult | WebhookActorEnrichmentResult>(evidence: Snapshot): T {\n\treturn copyOut<T>({ applied: true, replayed: true, evidence });\n}\n\n/** `listInvocationRequeueEvidence`: a scope and an `actionInvocationId`. */\nexport function readInvocationEvidenceCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), scope: readScope(snap, \"input\"), actionInvocationId: identifier(snap, \"actionInvocationId\", \"input.actionInvocationId\") };\n\t});\n}\n\nexport function fencedOutcome(outcome: WebhookFencedInsertResult[\"outcome\"]): WebhookFencedInsertResult {\n\treturn copyOut<WebhookFencedInsertResult>({ outcome });\n}\n","import { storeError } from \"./errors\";\n\n/*\n * Attempt receipts (PR 8). `beginAttempt` creates one per begun attempt and\n * returns it to the worker that began it; `finishAttempt` accepts an\n * outcome only with that receipt. The stores keep only its SHA-256 digest,\n * so a receipt cannot be read back out of a store, and no store read,\n * error or log carries it. Portable: Web Crypto only, which Node 20 and\n * current browsers provide on `globalThis.crypto`.\n */\n\nconst textEncoder = new TextEncoder();\nconst RECEIPT_BYTES = 32;\n\n/** The two Web Crypto members used, typed structurally so the package needs no DOM types. */\ninterface WebCrypto {\n\tgetRandomValues(array: Uint8Array): Uint8Array;\n\treadonly subtle: { digest(algorithm: string, data: Uint8Array): Promise<ArrayBuffer> };\n}\n\nfunction webCrypto(field: string): WebCrypto {\n\tconst crypto = (globalThis as { crypto?: WebCrypto }).crypto;\n\tif (crypto === undefined || typeof crypto.getRandomValues !== \"function\" || crypto.subtle === undefined) throw storeError(\"store_failed\", field);\n\treturn crypto;\n}\n\nfunction hex(bytes: Uint8Array): string {\n\tlet text = \"\";\n\tfor (const byte of bytes) text += byte.toString(16).padStart(2, \"0\");\n\treturn text;\n}\n\n/** @internal Lower-case hex SHA-256 of `text` as UTF-8. Throws `store_failed` naming `field` when Web Crypto is missing. */\nexport async function sha256Hex(text: string, field: string): Promise<string> {\n\treturn hex(new Uint8Array(await webCrypto(field).subtle.digest(\"SHA-256\", textEncoder.encode(text))));\n}\n\n/** @internal A new receipt (`rcpt_` and 32 random bytes in hex) and the digest a store keeps of it. */\nexport async function newAttemptReceipt(): Promise<{ readonly receipt: string; readonly digest: string }> {\n\tconst bytes = new Uint8Array(RECEIPT_BYTES);\n\twebCrypto(\"beginAttempt.receipt\").getRandomValues(bytes);\n\tconst receipt = `rcpt_${hex(bytes)}`;\n\treturn { receipt, digest: await sha256Hex(receipt, \"beginAttempt.receipt\") };\n}\n\n/** @internal The digest of a presented receipt, compared with the one stored at begin. */\nexport function attemptReceiptDigest(receipt: string): Promise<string> {\n\treturn sha256Hex(receipt, \"finishAttempt.receipt\");\n}\n","import type { WebhookDiagnosticCode } from \"./codes\";\nimport {\n\tapplyEnrichment,\n\tapplyRequeue,\n\tapplySettlement,\n\tattemptEntryOut,\n\tattemptKey,\n\tbeginResult,\n\tcompareText,\n\tcopyOut,\n\tdenialRecord,\n\tenrichmentRefusal,\n\tenrichmentRefused,\n\tfencedOutcome,\n\tholds,\n\tinScope,\n\tintentOut,\n\tintentRequeueEvidence,\n\tjobEnrichmentEvidence,\n\tjobOut,\n\tjobRequeueEvidence,\n\tleaseCheck,\n\tpriorInvocationEvidence,\n\tmarkerKey,\n\tmayBegin,\n\treadAppendAttemptCall,\n\treadBeginAttemptCall,\n\treadCancelCall,\n\treadClaimCall,\n\treadDeadLetterJobCall,\n\treadDeliveryCall,\n\treadDenialCall,\n\treadEventCall,\n\treadFinishAttemptCall,\n\treadHookOption,\n\treadHorizonOption,\n\treadInsertFanOutJobCall,\n\treadInsertIntentCall,\n\treadIntentRequeueCall,\n\treadInvocationEvidenceCall,\n\treadJobEnrichmentCall,\n\treadJobFencedCall,\n\treadJobRequeueCall,\n\treadLeaseCheckCall,\n\treadPurgeCall,\n\treadRenewIntentCall,\n\treadRenewJobCall,\n\treadRescheduleCall,\n\treadSettleCall,\n\treadTombstoneCall,\n\trenewedExpiryMs,\n\trequeueRefusal,\n\trequeueRefused,\n\treplayedResult,\n\ttype InvocationTarget,\n\tTERMINAL_INTENT,\n\tTERMINAL_JOB,\n\ttombstoneOut,\n\ttype ClaimInput,\n\ttype IntentState,\n\ttype JobState,\n\ttype Leased,\n\ttype LeaseState,\n\ttype MarkerState,\n} from \"./delivery-store-core\";\nimport { guard, storeError } from \"./errors\";\nimport { attemptReceiptDigest, newAttemptReceipt } from \"./receipt\";\nimport type {\n\tWebhookActorEnrichmentResult,\n\tWebhookAttemptBeginResult,\n\tWebhookCallOptions,\n\tWebhookClaimRequest,\n\tWebhookClock,\n\tWebhookDeliveryLeaseCheck,\n\tWebhookDeliveryStore,\n\tWebhookFanOutJobFence,\n\tWebhookFencedInsertResult,\n\tWebhookFencedWrite,\n\tWebhookInsertResult,\n\tWebhookPurgeResult,\n\tWebhookRequeueResult,\n\tWebhookScope,\n} from \"./ports\";\nimport { frozenList, mathMax } from \"./snapshot\";\nimport {\n\tassertCallWanted,\n\tcaptureClock,\n\tisoOf,\n\treadClock,\n\ttype CallBounds,\n\ttype CapturedClock,\n\ttype Snapshot,\n} from \"./store-input\";\nimport type {\n\tWebhookActorEnrichmentRequest,\n\tWebhookAdmissionDenialRecord,\n\tWebhookDeliveryAttemptFinish,\n\tWebhookDeliveryAttemptLogEntry,\n\tWebhookDeliveryAttemptRecord,\n\tWebhookDeliveryAttemptStart,\n\tWebhookDeliveryIntent,\n\tWebhookFanOutJob,\n\tWebhookFanOutJobDraft,\n\tWebhookRequeueEvidence,\n\tWebhookRequeueRequest,\n\tWebhookTombstone,\n} from \"./types\";\n\n/*\n * In-memory WebhookDeliveryStore, for tests and explicit local development.\n * It holds the same contract as the PostgreSQL store (tests/store-contract.ts)\n * so it does not hide ordering, idempotency or recovery bugs. Both stores\n * read their input and render their records through src/delivery-store-core.ts.\n *\n * Every method has the same shape:\n *\n * 1. Entry: copy the arguments into a package-owned snapshot\n * (src/delivery-store-core.ts, src/store-input.ts). Malformed input is\n * refused here, before anything else happens.\n * 2. One `await`, standing where a real store does I/O, so concurrent\n * calls interleave the way they do against a database.\n * 3. One synchronous step, `#atomic`: read the store's clock, refuse a call\n * whose signal aborted or whose deadline passed, then every check\n * (fence, replay horizon, uniqueness, status) and the write. There is\n * no `await` inside it, and JavaScript runs a synchronous block to\n * completion, so no other call on this store can run between its\n * checks and its write: it plays the part of one transaction.\n *\n * State lives in ECMAScript private fields of the instance; nothing is kept\n * in module scope. Reads return fresh frozen copies built from that state,\n * never the state itself.\n */\n\n/** Options for {@link MemoryWebhookDeliveryStore}. */\nexport interface MemoryWebhookDeliveryStoreOptions {\n\t/** The store's clock: it timestamps requeue evidence and decides the replay horizon. */\n\treadonly clock: WebhookClock;\n\t/** The replay horizon in milliseconds; see `WebhookDeliveryLimits.replayHorizonMs`. */\n\treadonly replayHorizonMs: number;\n\t/**\n\t * Test seam. Awaited at each call's I/O boundary, after its input is read\n\t * and before its atomic step, with the method name. A contract test uses\n\t * it to hold one call there while another runs to completion, forcing an\n\t * interleaving. A throw or rejection fails the call as `store_failed`,\n\t * with nothing written. Leave it unset outside tests.\n\t */\n\treadonly beforeAtomicStep?: (operation: string) => Promise<void> | void;\n}\n\ninterface DenialState {\n\treadonly key: string;\n\treadonly record: Snapshot;\n\treadonly anchorMs: number;\n}\n\ninterface AttemptState {\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly deliveryId: string;\n\t/** The whole entry (`appendAttempt`) or the start of a begun attempt (`beginAttempt`). */\n\treadonly record: Snapshot;\n\t/** The lease fence a begun attempt was recorded under; `undefined` for an entry appended whole. */\n\treadonly fence: number | undefined;\n\t/** The SHA-256 digest of a begun attempt's receipt; never the receipt itself. */\n\treadonly receiptDigest: string | undefined;\n}\n\ninterface EvidenceState {\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly eventId: string;\n\treadonly record: Snapshot;\n}\n\n/** Run an async step; a package error passes through, anything else becomes `store_failed`. */\nasync function guardedAsync<T>(run: () => Promise<T>): Promise<T> {\n\ttry {\n\t\treturn await run();\n\t} catch (thrown) {\n\t\treturn guard<T>(() => {\n\t\t\tthrow thrown;\n\t\t}, () => storeError(\"store_failed\", \"store\"));\n\t}\n}\n\n/** Where a database store would do I/O; lets concurrent calls interleave. */\nfunction ioBoundary(): Promise<void> {\n\treturn Promise.resolve();\n}\n\n/**\n * An in-memory {@link WebhookDeliveryStore}. Construct one per test or local\n * process; instances share nothing.\n *\n * @throws {WebhookDeliveryConfigError} when `replayHorizonMs` is not a\n * positive whole number of milliseconds within `WEBHOOK_MAX_REPLAY_HORIZON_MS`.\n * @throws {WebhookStoreError} `clock_invalid` when `clock` has no `now` function.\n */\nexport class MemoryWebhookDeliveryStore implements WebhookDeliveryStore {\n\treadonly #clock: CapturedClock;\n\treadonly #beforeAtomicStep: ((operation: string) => Promise<void> | void) | undefined;\n\treadonly #horizonMs: number;\n\treadonly #jobs = new Map<string, JobState>();\n\treadonly #intents = new Map<string, IntentState>();\n\treadonly #denials = new Map<string, DenialState>();\n\treadonly #markers = new Map<string, MarkerState>();\n\treadonly #attempts: AttemptState[] = [];\n\t/** Begun attempts by (deliveryId, fence); each is also in `#attempts`. */\n\treadonly #begun = new Map<string, AttemptState>();\n\t/** Outcomes of begun attempts by (deliveryId, fence). Written once, never changed. */\n\treadonly #outcomes = new Map<string, Snapshot>();\n\treadonly #evidence: EvidenceState[] = [];\n\t/** The highest cutoff any purge has used; inserts and requeues below it are refused. */\n\t#purgedThroughMs = -Infinity;\n\n\tconstructor(options: MemoryWebhookDeliveryStoreOptions) {\n\t\tthis.#horizonMs = readHorizonOption(options);\n\t\tthis.#clock = guard(() => captureClock((options as { clock?: WebhookClock }).clock), () => storeError(\"clock_invalid\", \"clock\"));\n\t\tthis.#beforeAtomicStep = readHookOption(options, \"beforeAtomicStep\");\n\t}\n\n\t/** The replay horizon this store enforces, in milliseconds. */\n\tget replayHorizonMs(): number {\n\t\treturn this.#horizonMs;\n\t}\n\n\t/** The I/O boundary: the injected seam, or one resolved turn. */\n\tasync #boundary(operation: string): Promise<void> {\n\t\tconst hook = this.#beforeAtomicStep;\n\t\tif (hook === undefined) return ioBoundary();\n\t\ttry {\n\t\t\tawait hook(operation);\n\t\t} catch {\n\t\t\tthrow storeError(\"store_failed\", \"beforeAtomicStep\");\n\t\t}\n\t}\n\n\t/**\n\t * The atomic step. Reads the store clock, refuses an unwanted call, then\n\t * runs `body` synchronously. A package error passes through; anything\n\t * else becomes `store_failed`.\n\t */\n\t#atomic<T>(bounds: CallBounds, body: (nowMs: number) => T): T {\n\t\treturn guard(() => {\n\t\t\tconst nowMs = readClock(this.#clock);\n\t\t\tassertCallWanted(bounds, nowMs);\n\t\t\treturn body(nowMs);\n\t\t}, () => storeError(\"store_failed\", \"store\"));\n\t}\n\n\t/** The horizon floor at `nowMs`: anchors earlier than this are past the horizon. */\n\t#floorMs(nowMs: number): number {\n\t\treturn mathMax(nowMs - this.#horizonMs, this.#purgedThroughMs);\n\t}\n\n\t#pastHorizon(anchorMs: number, nowMs: number): boolean {\n\t\treturn anchorMs < this.#floorMs(nowMs);\n\t}\n\n\t/**\n\t * Evidence `scope` holds under `actionInvocationId` for `target`, or\n\t * `undefined` (always, without an id). Called first in the atomic step of\n\t * a requeue or enrichment: see \"Re-runs of one invocation\" in src/ports.ts.\n\t */\n\t#priorEvidence(scope: WebhookScope, actionInvocationId: string | undefined, target: InvocationTarget): Snapshot | undefined {\n\t\tif (actionInvocationId === undefined) return undefined;\n\t\tconst records = this.#evidence\n\t\t\t.filter((item) => inScope(item, scope) && item.record[\"actionInvocationId\"] === actionInvocationId)\n\t\t\t.map((item) => item.record);\n\t\treturn priorInvocationEvidence(records, target);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Fan-out jobs\n\t// -------------------------------------------------------------------------\n\n\tasync insertFanOutJob(\n\t\tjob: WebhookFanOutJobDraft & { readonly processingDeadline: string; readonly createdAt: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookInsertResult> {\n\t\tconst call = readInsertFanOutJobCall(job, options);\n\t\tawait this.#boundary(\"insertFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst draft = call.job;\n\t\t\t// Horizon first, so the answer for an old event does not depend on\n\t\t\t// whether a purge has removed its job yet.\n\t\t\tif (this.#pastHorizon(draft.anchorMs, nowMs)) return copyOut<WebhookInsertResult>({ outcome: \"past_horizon\" });\n\t\t\tif (this.#jobs.has(draft.eventId)) return copyOut<WebhookInsertResult>({ outcome: \"already_present\" });\n\t\t\tthis.#jobs.set(draft.eventId, {\n\t\t\t\tkey: draft.eventId,\n\t\t\t\tdraft: draft.draft,\n\t\t\t\ttenantId: draft.tenantId,\n\t\t\t\tspaceId: draft.spaceId,\n\t\t\t\tanchorMs: draft.anchorMs,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tattemptCount: 0,\n\t\t\t\tavailableAtMs: draft.createdAtMs,\n\t\t\t\tcreatedAtMs: draft.createdAtMs,\n\t\t\t\tprocessingDeadlineMs: draft.processingDeadlineMs,\n\t\t\t\tcompletedAtMs: undefined,\n\t\t\t\tlastDiagnostic: undefined,\n\t\t\t\tfence: 0,\n\t\t\t\tlease: undefined,\n\t\t\t});\n\t\t\treturn copyOut<WebhookInsertResult>({ outcome: \"inserted\" });\n\t\t});\n\t}\n\n\tasync claimFanOutJobs(request: WebhookClaimRequest, options: WebhookCallOptions): Promise<readonly WebhookFanOutJob[]> {\n\t\tconst call = readClaimCall(request, options);\n\t\tawait this.#boundary(\"claimFanOutJobs\");\n\t\treturn this.#atomic(call.bounds, () =>\n\t\t\tclaimFrom([...this.#jobs.values()], call.claim, jobOut) as readonly WebhookFanOutJob[]);\n\t}\n\n\tasync completeFanOutJob(input: WebhookFencedWrite & { readonly eventId: string }, options: WebhookCallOptions): Promise<boolean> {\n\t\tconst call = readJobFencedCall(input, options);\n\t\tawait this.#boundary(\"completeFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !holds(job, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tjob.status = \"completed\";\n\t\t\tjob.completedAtMs = call.fenced.nowMs;\n\t\t\tjob.lease = undefined;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync rescheduleFanOutJob(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly availableAt: Date; readonly diagnostic: WebhookDiagnosticCode },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRescheduleCall(input, options);\n\t\tawait this.#boundary(\"rescheduleFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !holds(job, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tjob.attemptCount += 1;\n\t\t\tjob.availableAtMs = call.availableAtMs;\n\t\t\tjob.lastDiagnostic = call.diagnostic;\n\t\t\tjob.lease = undefined;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync renewFanOutJobLease(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly leaseDurationMs: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRenewJobCall(input, options);\n\t\tawait this.#boundary(\"renewFanOutJobLease\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !holds(job, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tjob.lease = { ...job.lease!, expiresAtMs: renewedExpiryMs(job, call.fenced.nowMs, call.leaseDurationMs) };\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync deadLetterFanOutJob(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly diagnostic: WebhookDiagnosticCode },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readDeadLetterJobCall(input, options);\n\t\tawait this.#boundary(\"deadLetterFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !holds(job, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tjob.status = \"dead_letter\";\n\t\t\tjob.lastDiagnostic = call.diagnostic;\n\t\t\tjob.lease = undefined;\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync requeueFanOutJob(\n\t\tinput: WebhookScope & { readonly eventId: string; readonly request: WebhookRequeueRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookRequeueResult> {\n\t\tconst call = readJobRequeueCall(input, options);\n\t\tawait this.#boundary(\"requeueFanOutJob\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst prior = this.#priorEvidence(call.scope, call.request.actionInvocationId, { target: \"fan_out_job\", eventId: call.eventId });\n\t\t\tif (prior !== undefined) return replayedResult<WebhookRequeueResult>(prior);\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !inScope(job, call.scope)) return requeueRefused(\"not_found\");\n\t\t\tconst refusal = requeueRefusal(job, call.request, this.#floorMs(nowMs));\n\t\t\tif (refusal !== undefined) return requeueRefused(refusal);\n\t\t\tconst evidence = jobRequeueEvidence(job, call.request, nowMs);\n\t\t\tconst result = copyOut<WebhookRequeueResult>({ applied: true, evidence });\n\t\t\tapplyRequeue(job, call.request);\n\t\t\tthis.#evidence.push({ tenantId: job.tenantId, spaceId: job.spaceId, eventId: job.key, record: evidence as unknown as Snapshot });\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync enrichFanOutJobActor(\n\t\tinput: WebhookScope & { readonly eventId: string; readonly request: WebhookActorEnrichmentRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookActorEnrichmentResult> {\n\t\tconst call = readJobEnrichmentCall(input, options);\n\t\tawait this.#boundary(\"enrichFanOutJobActor\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst prior = this.#priorEvidence(call.scope, call.request.actionInvocationId, { target: \"fan_out_job_actor\", eventId: call.eventId });\n\t\t\tif (prior !== undefined) return replayedResult<WebhookActorEnrichmentResult>(prior);\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\tif (job === undefined || !inScope(job, call.scope)) return enrichmentRefused(\"not_found\");\n\t\t\tconst refusal = enrichmentRefusal(job, call.request, this.#floorMs(nowMs));\n\t\t\tif (refusal !== undefined) return enrichmentRefused(refusal);\n\t\t\tconst evidence = jobEnrichmentEvidence(job, call.request, nowMs);\n\t\t\tconst result = copyOut<WebhookActorEnrichmentResult>({ applied: true, evidence });\n\t\t\tapplyEnrichment(job, call.request);\n\t\t\tthis.#evidence.push({ tenantId: job.tenantId, spaceId: job.spaceId, eventId: job.key, record: evidence as unknown as Snapshot });\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync readFanOutJob(input: WebhookScope & { readonly eventId: string }, options: WebhookCallOptions): Promise<WebhookFanOutJob | null> {\n\t\tconst call = readEventCall(input, options);\n\t\tawait this.#boundary(\"readFanOutJob\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst job = this.#jobs.get(call.eventId);\n\t\t\treturn job === undefined || !inScope(job, call.scope) ? null : copyOut<WebhookFanOutJob>(jobOut(job));\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Intents and denials\n\t// -------------------------------------------------------------------------\n\n\tasync insertDeliveryIntent(\n\t\tintent: Omit<WebhookDeliveryIntent, \"status\" | \"attemptCount\" | \"lastOutcome\" | \"lastDiagnostic\" | \"lease\" | \"eventRecordedAt\" | \"fence\">,\n\t\tparent: WebhookFanOutJobFence,\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookFencedInsertResult> {\n\t\tconst call = readInsertIntentCall(intent, parent, options);\n\t\tawait this.#boundary(\"insertDeliveryIntent\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#parentJob(call.parent, nowMs);\n\t\t\tif (job === undefined) return fencedOutcome(\"lease_lost\");\n\t\t\tif (!inScope(job, call)) throw storeError(\"record_mismatch\", \"intent.tenantId\");\n\t\t\tif (this.#pastHorizon(job.anchorMs, nowMs)) return fencedOutcome(\"past_horizon\");\n\t\t\tconst key = markerKey(call.subscriptionId, call.eventId);\n\t\t\tif (this.#markers.has(key)) return fencedOutcome(\"already_present\");\n\t\t\tif (this.#intents.has(call.deliveryId)) throw storeError(\"delivery_id_conflict\", \"intent.deliveryId\");\n\t\t\tthis.#intents.set(call.deliveryId, {\n\t\t\t\tkey: call.deliveryId,\n\t\t\t\tsubscriptionId: call.subscriptionId,\n\t\t\t\teventId: call.eventId,\n\t\t\t\ttenantId: call.tenantId,\n\t\t\t\tspaceId: call.spaceId,\n\t\t\t\teligibilityRevision: call.eligibilityRevision,\n\t\t\t\tbody: call.body,\n\t\t\t\tanchorMs: job.anchorMs,\n\t\t\t\tstatus: \"pending\",\n\t\t\t\tattemptCount: 0,\n\t\t\t\tavailableAtMs: call.availableAtMs,\n\t\t\t\tcreatedAtMs: call.createdAtMs,\n\t\t\t\tprocessingDeadlineMs: call.processingDeadlineMs,\n\t\t\t\tlastOutcome: undefined,\n\t\t\t\tlastDiagnostic: undefined,\n\t\t\t\tfence: 0,\n\t\t\t\tlease: undefined,\n\t\t\t});\n\t\t\tthis.#markers.set(key, { kind: \"intent\", subscriptionId: call.subscriptionId, eventId: call.eventId, tenantId: call.tenantId, spaceId: call.spaceId, anchorMs: job.anchorMs });\n\t\t\treturn fencedOutcome(\"inserted\");\n\t\t});\n\t}\n\n\tasync recordAdmissionDenial(\n\t\trecord: WebhookAdmissionDenialRecord,\n\t\tparent: WebhookFanOutJobFence,\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookFencedInsertResult> {\n\t\tconst call = readDenialCall(record, parent, options);\n\t\tawait this.#boundary(\"recordAdmissionDenial\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst job = this.#parentJob(call.parent, nowMs);\n\t\t\tif (job === undefined) return fencedOutcome(\"lease_lost\");\n\t\t\tif (!inScope(job, call)) throw storeError(\"record_mismatch\", \"record.tenantId\");\n\t\t\tif (this.#pastHorizon(job.anchorMs, nowMs)) return fencedOutcome(\"past_horizon\");\n\t\t\tconst key = markerKey(call.subscriptionId, call.eventId);\n\t\t\tif (this.#markers.has(key)) return fencedOutcome(\"already_present\");\n\t\t\tthis.#denials.set(key, { key, record: denialRecord(call), anchorMs: job.anchorMs });\n\t\t\tthis.#markers.set(key, { kind: \"denial\", subscriptionId: call.subscriptionId, eventId: call.eventId, tenantId: call.tenantId, spaceId: call.spaceId, anchorMs: job.anchorMs });\n\t\t\treturn fencedOutcome(\"inserted\");\n\t\t});\n\t}\n\n\t/** The parent job if `fence` still holds its unexpired lease at the store's `nowMs`. */\n\t#parentJob(fence: WebhookFanOutJobFence, nowMs: number): JobState | undefined {\n\t\tconst job = this.#jobs.get(fence.eventId);\n\t\treturn job !== undefined && holds(job, fence.owner, fence.fence, nowMs) ? job : undefined;\n\t}\n\n\tasync claimDeliveryIntents(request: WebhookClaimRequest, options: WebhookCallOptions): Promise<readonly WebhookDeliveryIntent[]> {\n\t\tconst call = readClaimCall(request, options);\n\t\tawait this.#boundary(\"claimDeliveryIntents\");\n\t\treturn this.#atomic(call.bounds, () =>\n\t\t\tclaimFrom([...this.#intents.values()], call.claim, intentOut) as readonly WebhookDeliveryIntent[]);\n\t}\n\n\tasync renewDeliveryIntentLease(\n\t\tinput: WebhookFencedWrite & { readonly deliveryId: string; readonly leaseDurationMs: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRenewIntentCall(input, options);\n\t\tawait this.#boundary(\"renewDeliveryIntentLease\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tintent.lease = { ...intent.lease!, expiresAtMs: renewedExpiryMs(intent, call.fenced.nowMs, call.leaseDurationMs) };\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync checkDeliveryLease(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly owner: string; readonly fence: number; readonly now: Date },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookDeliveryLeaseCheck> {\n\t\tconst call = readLeaseCheckCall(input, options);\n\t\tawait this.#boundary(\"checkDeliveryLease\");\n\t\treturn this.#atomic(call.bounds, () => leaseCheck(this.#intents.get(call.deliveryId), call));\n\t}\n\n\tasync appendAttempt(input: WebhookFencedWrite & { readonly attempt: WebhookDeliveryAttemptRecord }, options: WebhookCallOptions): Promise<boolean> {\n\t\tconst call = readAppendAttemptCall(input, options);\n\t\tawait this.#boundary(\"appendAttempt\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tif (call.subscriptionId !== intent.subscriptionId) throw storeError(\"record_mismatch\", \"input.attempt.subscriptionId\");\n\t\t\tif (call.eventId !== intent.eventId) throw storeError(\"record_mismatch\", \"input.attempt.eventId\");\n\t\t\tthis.#attempts.push({ tenantId: intent.tenantId, spaceId: intent.spaceId, deliveryId: call.deliveryId, record: call.record, fence: undefined, receiptDigest: undefined });\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync beginAttempt(input: WebhookFencedWrite & { readonly attempt: WebhookDeliveryAttemptStart }, options: WebhookCallOptions): Promise<WebhookAttemptBeginResult> {\n\t\tconst call = readBeginAttemptCall(input, options);\n\t\t// Made before the atomic step, which has no await; kept only as a digest.\n\t\tconst receipt = await guardedAsync(newAttemptReceipt);\n\t\tawait this.#boundary(\"beginAttempt\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (!mayBegin(intent, call.fenced, nowMs)) return beginResult(undefined);\n\t\t\tif (call.subscriptionId !== intent.subscriptionId) throw storeError(\"record_mismatch\", \"input.attempt.subscriptionId\");\n\t\t\tif (call.eventId !== intent.eventId) throw storeError(\"record_mismatch\", \"input.attempt.eventId\");\n\t\t\tconst key = attemptKey(call.deliveryId, call.fenced.fence);\n\t\t\tif (this.#begun.has(key)) return beginResult(undefined);\n\t\t\tconst state: AttemptState = {\n\t\t\t\ttenantId: intent.tenantId, spaceId: intent.spaceId, deliveryId: call.deliveryId, record: call.record,\n\t\t\t\tfence: call.fenced.fence, receiptDigest: receipt.digest,\n\t\t\t};\n\t\t\tthis.#attempts.push(state);\n\t\t\tthis.#begun.set(key, state);\n\t\t\treturn beginResult(receipt.receipt);\n\t\t});\n\t}\n\n\tasync finishAttempt(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly fence: number; readonly receipt: string; readonly finish: WebhookDeliveryAttemptFinish },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readFinishAttemptCall(input, options);\n\t\tconst digest = await guardedAsync(() => attemptReceiptDigest(call.receipt));\n\t\tawait this.#boundary(\"finishAttempt\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst key = attemptKey(call.deliveryId, call.fence);\n\t\t\tconst begun = this.#begun.get(key);\n\t\t\t// Unfenced: the begun attempt's key, scope and receipt are checked, and\n\t\t\t// nothing of the intent is read or changed.\n\t\t\tif (begun === undefined || !inScope(begun, call.scope) || begun.receiptDigest !== digest || this.#outcomes.has(key)) return false;\n\t\t\tthis.#outcomes.set(key, call.record);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync settleDeliveryIntent(\n\t\tinput: Parameters<WebhookDeliveryStore[\"settleDeliveryIntent\"]>[0],\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readSettleCall(input, options);\n\t\tawait this.#boundary(\"settleDeliveryIntent\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tapplySettlement(intent, call.settlement);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync cancelPendingIntents(\n\t\tinput: Parameters<WebhookDeliveryStore[\"cancelPendingIntents\"]>[0],\n\t\toptions: WebhookCallOptions,\n\t): Promise<number> {\n\t\tconst call = readCancelCall(input, options);\n\t\tawait this.#boundary(\"cancelPendingIntents\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tlet cancelled = 0;\n\t\t\tfor (const intent of this.#intents.values()) {\n\t\t\t\tif (intent.status !== \"pending\" || intent.subscriptionId !== call.subscriptionId || !inScope(intent, call.scope)) continue;\n\t\t\t\tif (intent.eligibilityRevision >= call.beforeRevision) continue;\n\t\t\t\tintent.status = \"cancelled\";\n\t\t\t\tintent.lastOutcome = { outcome: \"cancelled\", reason: call.reason };\n\t\t\t\tintent.lease = undefined;\n\t\t\t\tcancelled += 1;\n\t\t\t}\n\t\t\treturn cancelled;\n\t\t});\n\t}\n\n\tasync requeueDeliveryIntent(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly request: WebhookRequeueRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookRequeueResult> {\n\t\tconst call = readIntentRequeueCall(input, options);\n\t\tawait this.#boundary(\"requeueDeliveryIntent\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst prior = this.#priorEvidence(call.scope, call.request.actionInvocationId, { target: \"delivery_intent\", deliveryId: call.deliveryId });\n\t\t\tif (prior !== undefined) return replayedResult<WebhookRequeueResult>(prior);\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\tif (intent === undefined || !inScope(intent, call.scope)) return requeueRefused(\"not_found\");\n\t\t\tconst refusal = requeueRefusal(intent, call.request, this.#floorMs(nowMs));\n\t\t\tif (refusal !== undefined) return requeueRefused(refusal);\n\t\t\tconst evidence = intentRequeueEvidence(intent, call.request, nowMs);\n\t\t\tconst result = copyOut<WebhookRequeueResult>({ applied: true, evidence });\n\t\t\tapplyRequeue(intent, call.request);\n\t\t\tthis.#evidence.push({ tenantId: intent.tenantId, spaceId: intent.spaceId, eventId: intent.eventId, record: evidence as unknown as Snapshot });\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync readDeliveryIntent(input: WebhookScope & { readonly deliveryId: string }, options: WebhookCallOptions): Promise<WebhookDeliveryIntent | null> {\n\t\tconst call = readDeliveryCall(input, options);\n\t\tawait this.#boundary(\"readDeliveryIntent\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst intent = this.#intents.get(call.deliveryId);\n\t\t\treturn intent === undefined || !inScope(intent, call.scope) ? null : copyOut<WebhookDeliveryIntent>(intentOut(intent));\n\t\t});\n\t}\n\n\tasync listDeliveryAttempts(\n\t\tinput: WebhookScope & { readonly deliveryId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookDeliveryAttemptLogEntry[]> {\n\t\tconst call = readDeliveryCall(input, options);\n\t\tawait this.#boundary(\"listDeliveryAttempts\");\n\t\treturn this.#atomic(call.bounds, () => copyOut<readonly WebhookDeliveryAttemptLogEntry[]>(\n\t\t\tthis.#attempts\n\t\t\t\t.filter((item) => item.deliveryId === call.deliveryId && inScope(item, call.scope))\n\t\t\t\t.map((item) => attemptEntryOut(\n\t\t\t\t\titem.record,\n\t\t\t\t\titem.fence,\n\t\t\t\t\titem.fence === undefined ? undefined : this.#outcomes.get(attemptKey(item.deliveryId, item.fence)),\n\t\t\t\t)),\n\t\t));\n\t}\n\n\tasync listRequeueEvidence(input: WebhookScope & { readonly eventId: string }, options: WebhookCallOptions): Promise<readonly WebhookRequeueEvidence[]> {\n\t\tconst call = readEventCall(input, options);\n\t\tawait this.#boundary(\"listRequeueEvidence\");\n\t\treturn this.#atomic(call.bounds, () => copyOut<readonly WebhookRequeueEvidence[]>(\n\t\t\tthis.#evidence.filter((item) => item.eventId === call.eventId && inScope(item, call.scope)).map((item) => item.record),\n\t\t));\n\t}\n\n\tasync listInvocationRequeueEvidence(\n\t\tinput: WebhookScope & { readonly actionInvocationId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookRequeueEvidence[]> {\n\t\tconst call = readInvocationEvidenceCall(input, options);\n\t\tawait this.#boundary(\"listInvocationRequeueEvidence\");\n\t\treturn this.#atomic(call.bounds, () => copyOut<readonly WebhookRequeueEvidence[]>(\n\t\t\tthis.#evidence\n\t\t\t\t.filter((item) => inScope(item, call.scope) && item.record[\"actionInvocationId\"] === call.actionInvocationId)\n\t\t\t\t.map((item) => item.record),\n\t\t));\n\t}\n\n\tasync readTombstone(\n\t\tinput: WebhookScope & { readonly subscriptionId: string; readonly eventId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookTombstone | null> {\n\t\tconst call = readTombstoneCall(input, options);\n\t\tawait this.#boundary(\"readTombstone\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst marker = this.#markers.get(markerKey(call.subscriptionId, call.eventId));\n\t\t\tif (marker === undefined || !inScope(marker, call.scope)) return null;\n\t\t\treturn copyOut<WebhookTombstone>(tombstoneOut(marker, this.#horizonMs));\n\t\t});\n\t}\n\n\tasync purgeExpiredRecords(input: { readonly limit: number }, options: WebhookCallOptions): Promise<WebhookPurgeResult> {\n\t\tconst call = readPurgeCall(input, options);\n\t\tawait this.#boundary(\"purgeExpiredRecords\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tconst cutoffMs = this.#floorMs(nowMs);\n\t\t\tconst cutoff = isoOf(cutoffMs);\n\t\t\tconst candidates: { readonly anchorMs: number; readonly rank: number; readonly key: string }[] = [];\n\t\t\tfor (const job of this.#jobs.values()) {\n\t\t\t\tif (job.anchorMs < cutoffMs && TERMINAL_JOB.includes(job.status)) candidates.push({ anchorMs: job.anchorMs, rank: 0, key: job.key });\n\t\t\t}\n\t\t\tfor (const denial of this.#denials.values()) {\n\t\t\t\tif (denial.anchorMs < cutoffMs) candidates.push({ anchorMs: denial.anchorMs, rank: 1, key: denial.key });\n\t\t\t}\n\t\t\tfor (const intent of this.#intents.values()) {\n\t\t\t\tif (intent.anchorMs < cutoffMs && TERMINAL_INTENT.includes(intent.status)) candidates.push({ anchorMs: intent.anchorMs, rank: 2, key: intent.key });\n\t\t\t}\n\t\t\tcandidates.sort((left, right) => left.anchorMs - right.anchorMs || left.rank - right.rank || compareText(left.key, right.key));\n\t\t\tconst take = candidates.length < call.limit ? candidates.length : call.limit;\n\t\t\tconst removed = { fanOutJobs: 0, deliveryIntents: 0, admissionDenials: 0 };\n\t\t\tfor (let index = 0; index < take; index += 1) {\n\t\t\t\tconst rank = candidates[index]!.rank;\n\t\t\t\tif (rank === 0) removed.fanOutJobs += 1;\n\t\t\t\telse if (rank === 1) removed.admissionDenials += 1;\n\t\t\t\telse removed.deliveryIntents += 1;\n\t\t\t}\n\t\t\tconst result = copyOut<WebhookPurgeResult>({ cutoff, removed, more: candidates.length > take });\n\t\t\t// Compute, then commit. Raise the floor in the same step as the\n\t\t\t// removals: from here on no insert or requeue can recreate anything\n\t\t\t// below it.\n\t\t\tthis.#purgedThroughMs = cutoffMs;\n\t\t\tfor (let index = 0; index < take; index += 1) {\n\t\t\t\tconst candidate = candidates[index]!;\n\t\t\t\tif (candidate.rank === 0) {\n\t\t\t\t\tthis.#jobs.delete(candidate.key);\n\t\t\t\t} else if (candidate.rank === 1) {\n\t\t\t\t\tthis.#denials.delete(candidate.key);\n\t\t\t\t\tthis.#markers.delete(candidate.key);\n\t\t\t\t} else {\n\t\t\t\t\tconst intent = this.#intents.get(candidate.key)!;\n\t\t\t\t\tthis.#intents.delete(candidate.key);\n\t\t\t\t\tthis.#markers.delete(markerKey(intent.subscriptionId, intent.eventId));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Lease up to `claim.limit` claimable records, oldest `availableAt` first\n * (then `createdAt`, then key), advancing each one's fence. Returns the\n * leased states. Sorting is explicit, so the order never depends on Map\n * insertion order.\n */\nfunction claimFrom<T extends Leased>(records: T[], claim: ClaimInput, render: (record: T, lease: LeaseState) => object): readonly unknown[] {\n\tconst claimable = records.filter((record) =>\n\t\trecord.status === \"pending\" &&\n\t\trecord.availableAtMs <= claim.nowMs &&\n\t\t(record.lease === undefined || record.lease.expiresAtMs <= claim.nowMs));\n\tclaimable.sort((left, right) => left.availableAtMs - right.availableAtMs || left.createdAtMs - right.createdAtMs || compareText(left.key, right.key));\n\tconst leased = claimable.slice(0, claim.limit);\n\t// Compute, then commit: every lease and every returned record is built\n\t// before any record changes, so a failure here leaves the store as it was.\n\tconst plan = leased.map((record) => ({\n\t\trecord,\n\t\tlease: { owner: claim.workerId, fence: record.fence + 1, expiresAtMs: claim.nowMs + claim.leaseDurationMs },\n\t}));\n\tconst out = plan.map(({ record, lease }) => copyOut<object>(render(record, lease)));\n\tfor (const { record, lease } of plan) {\n\t\trecord.fence = lease.fence;\n\t\trecord.lease = lease;\n\t}\n\treturn frozenList(out);\n}\n","import { guard, storeError } from \"./errors\";\nimport type { WebhookScope, WebhookSubscriptionWriteRefusal, WebhookSubscriptionWriteResult } from \"./ports\";\nimport { mathMax } from \"./snapshot\";\nimport {\n\tcloneOut,\n\tcodeOf,\n\tidentifier,\n\tinstant,\n\tisoOf,\n\tnestedRecord,\n\toptionalWholeNumber,\n\treadCallOptions,\n\tsnapshotRecord,\n\ttext,\n\ttextList,\n} from \"./store-input\";\nimport type {\n\tWebhookDeliveryConfiguration,\n\tWebhookDeliveryConfigurationInput,\n\tWebhookSignatureScheme,\n\tWebhookSubscriptionStatus,\n} from \"./types\";\n\n/*\n * What the memory and PostgreSQL subscription stores share: the entry\n * readers, the revision shape, the transition rules and the record\n * renderers. Internal: not exported from the package entry point.\n */\n\nexport interface RevisionState {\n\treadonly revision: number;\n\treadonly status: WebhookSubscriptionStatus;\n\treadonly eventTypePatterns: readonly string[];\n\treadonly effectiveFromMs: number;\n}\n\nexport interface Target extends WebhookScope {\n\treadonly subscriptionId: string;\n}\n\nconst SCHEMES = Object.freeze([\"v1\"] as const);\n\n/** A fresh frozen deep copy with no depth or size limit (`cloneOut`). */\nexport function copyOut<T>(value: object): T {\n\treturn cloneOut<T>(value);\n}\n\nfunction entry<T>(read: () => T): T {\n\treturn guard(read, () => storeError(\"input_invalid\", \"input\"));\n}\n\nfunction readTarget(snap: ReturnType<typeof snapshotRecord>): Target {\n\treturn {\n\t\ttenantId: identifier(snap, \"tenantId\", \"input.tenantId\"),\n\t\tspaceId: identifier(snap, \"spaceId\", \"input.spaceId\"),\n\t\tsubscriptionId: identifier(snap, \"subscriptionId\", \"input.subscriptionId\"),\n\t};\n}\n\nfunction readConfiguration(snap: ReturnType<typeof snapshotRecord>): WebhookDeliveryConfigurationInput {\n\tconst configuration = nestedRecord(snap, \"configuration\", \"input.configuration\");\n\treturn {\n\t\tdestinationUrl: text(configuration, \"destinationUrl\", \"input.configuration.destinationUrl\"),\n\t\tsignatureScheme: codeOf<WebhookSignatureScheme>(configuration, \"signatureScheme\", SCHEMES, \"input.configuration.signatureScheme\"),\n\t\tsecretRef: text(configuration, \"secretRef\", \"input.configuration.secretRef\"),\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Per-method entry readers\n// ---------------------------------------------------------------------------\n\nexport function readRevisionsAtCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\ttenantId: identifier(snap, \"tenantId\", \"input.tenantId\"),\n\t\t\tspaceId: identifier(snap, \"spaceId\", \"input.spaceId\"),\n\t\t\trecordedAtMs: instant(snap, \"recordedAt\", \"input.recordedAt\"),\n\t\t};\n\t});\n}\n\n/** `readSubscription` and `listEligibilityHistory`: one subscription in a scope. */\nexport function readTargetCall(input: unknown, options: unknown) {\n\treturn entry(() => ({ bounds: readCallOptions(options), target: readTarget(snapshotRecord(input, \"input\")) }));\n}\n\nexport function readCreateCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\ttarget: readTarget(snap),\n\t\t\tpatterns: textList(snap, \"eventTypePatterns\", \"input.eventTypePatterns\"),\n\t\t\tconfiguration: readConfiguration(snap),\n\t\t};\n\t});\n}\n\nexport function readChangePatternsCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\ttarget: readTarget(snap),\n\t\t\texpectedRevision: optionalWholeNumber(snap, \"expectedRevision\", \"input.expectedRevision\", 1),\n\t\t\tpatterns: textList(snap, \"eventTypePatterns\", \"input.eventTypePatterns\"),\n\t\t};\n\t});\n}\n\nexport function readStatusChangeCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn { bounds: readCallOptions(options), target: readTarget(snap), expectedRevision: optionalWholeNumber(snap, \"expectedRevision\", \"input.expectedRevision\", 1) };\n\t});\n}\n\nexport function readReplaceConfigurationCall(input: unknown, options: unknown) {\n\treturn entry(() => {\n\t\tconst snap = snapshotRecord(input, \"input\");\n\t\treturn {\n\t\t\tbounds: readCallOptions(options),\n\t\t\ttarget: readTarget(snap),\n\t\t\texpectedVersion: optionalWholeNumber(snap, \"expectedVersion\", \"input.expectedVersion\", 1),\n\t\t\tconfiguration: readConfiguration(snap),\n\t\t};\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Transitions\n// ---------------------------------------------------------------------------\n\n/** The status a pause, resume or delete moves to from `status`, or `undefined` when it is not allowed. */\nexport type StatusChange = (status: WebhookSubscriptionStatus) => WebhookSubscriptionStatus | undefined;\n\nexport const PAUSE: StatusChange = (status) => (status === \"active\" ? \"paused\" : undefined);\nexport const RESUME: StatusChange = (status) => (status === \"paused\" ? \"active\" : undefined);\nexport const DELETE: StatusChange = () => \"deleted\";\n\nexport type RevisionChange = (current: RevisionState) => { readonly status: WebhookSubscriptionStatus; readonly patterns: readonly string[] } | undefined;\n\nexport function statusRevisionChange(next: StatusChange): RevisionChange {\n\treturn (current) => {\n\t\tconst status = next(current.status);\n\t\treturn status === undefined ? undefined : { status, patterns: current.eventTypePatterns };\n\t};\n}\n\n/**\n * Decide one transition against the store's current revision: a refusal, or\n * the revision to append. The new revision takes effect at the store's\n * clock, or at the previous revision's start if the clock is behind it, so\n * intervals never invert.\n */\nexport function decideTransition(\n\tcurrent: RevisionState | undefined,\n\texpectedRevision: number | undefined,\n\tnowMs: number,\n\tchange: RevisionChange,\n): { readonly refusal: WebhookSubscriptionWriteResult } | { readonly appended: RevisionState } {\n\tif (current === undefined) return { refusal: refused(\"not_found\") };\n\tif (current.status === \"deleted\") return { refusal: refused(\"deleted\", current.revision) };\n\tif (expectedRevision !== undefined && expectedRevision !== current.revision) return { refusal: refused(\"revision_conflict\", current.revision) };\n\tconst next = change(current);\n\tif (next === undefined) return { refusal: refused(\"invalid_transition\", current.revision) };\n\treturn {\n\t\tappended: {\n\t\t\trevision: current.revision + 1,\n\t\t\tstatus: next.status,\n\t\t\teventTypePatterns: next.patterns,\n\t\t\teffectiveFromMs: mathMax(nowMs, current.effectiveFromMs),\n\t\t},\n\t};\n}\n\nexport function refused(refusal: WebhookSubscriptionWriteRefusal, currentRevision?: number): WebhookSubscriptionWriteResult {\n\treturn copyOut<WebhookSubscriptionWriteResult>({ applied: false, refusal, currentRevision });\n}\n\n// ---------------------------------------------------------------------------\n// Rendering\n// ---------------------------------------------------------------------------\n\n/** A revision as the read port returns it; `nextEffectiveFromMs` is its successor's start, if any. */\nexport function revisionOut(target: Target, revision: RevisionState, nextEffectiveFromMs: number | undefined): object {\n\treturn {\n\t\tsubscriptionId: target.subscriptionId,\n\t\trevision: revision.revision,\n\t\ttenantId: target.tenantId,\n\t\tspaceId: target.spaceId,\n\t\tstatus: revision.status,\n\t\teventTypePatterns: revision.eventTypePatterns,\n\t\teffectiveFrom: isoOf(revision.effectiveFromMs),\n\t\teffectiveUntil: nextEffectiveFromMs === undefined ? null : isoOf(nextEffectiveFromMs),\n\t};\n}\n\n/**\n * The snapshot's `statusSinceRevision`: the revision at which the latest\n * revision's status began, i.e. one past the last revision with another\n * status, or 1. Revisions are numbered 1, 2, 3 … with no gaps\n * (`decideTransition` appends `current.revision + 1`); the PostgreSQL\n * store computes the same in SQL (`readSubscription`), and the contract\n * case \"readSubscription reports the revision the current status began at …\"\n * holds both to it.\n */\nexport function statusSinceRevision(revisions: readonly RevisionState[]): number {\n\tconst current = revisions[revisions.length - 1]!;\n\tfor (let index = revisions.length - 1; index >= 0; index -= 1) {\n\t\tif (revisions[index]!.status !== current.status) return revisions[index]!.revision + 1;\n\t}\n\treturn 1;\n}\n\nexport function configurationOut(target: Target, version: number, configuration: WebhookDeliveryConfigurationInput): WebhookDeliveryConfiguration {\n\treturn copyOut<WebhookDeliveryConfiguration>({\n\t\tsubscriptionId: target.subscriptionId,\n\t\ttenantId: target.tenantId,\n\t\tspaceId: target.spaceId,\n\t\tversion,\n\t\t...configuration,\n\t});\n}\n\n/** UTF-16 code unit order, as JavaScript's `<` compares strings. */\nexport function compareText(left: string, right: string): number {\n\treturn left < right ? -1 : left > right ? 1 : 0;\n}\n","import { readHookOption } from \"./delivery-store-core\";\nimport { guard, storeError } from \"./errors\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookConfigurationWriteResult,\n\tWebhookScope,\n\tWebhookSubscriptionStore,\n\tWebhookSubscriptionTransitionInput,\n\tWebhookSubscriptionWriteResult,\n\tWebhookSubscriptionWriter,\n} from \"./ports\";\nimport {\n\tassertCallWanted,\n\tcaptureClock,\n\tcompositeKey,\n\treadClock,\n\ttype CallBounds,\n\ttype CapturedClock,\n} from \"./store-input\";\nimport {\n\tcompareText,\n\tconfigurationOut,\n\tcopyOut,\n\tdecideTransition,\n\tDELETE,\n\tPAUSE,\n\treadChangePatternsCall,\n\treadCreateCall,\n\treadReplaceConfigurationCall,\n\treadRevisionsAtCall,\n\treadStatusChangeCall,\n\treadTargetCall,\n\trefused,\n\tRESUME,\n\trevisionOut,\n\tstatusRevisionChange,\n\tstatusSinceRevision,\n\ttype RevisionChange,\n\ttype RevisionState,\n\ttype StatusChange,\n\ttype Target,\n} from \"./subscription-store-core\";\nimport type {\n\tWebhookDeliveryConfiguration,\n\tWebhookDeliveryConfigurationInput,\n\tWebhookEligibilityRevision,\n\tWebhookSubscriptionSnapshot,\n} from \"./types\";\n\n/*\n * In-memory subscription store: the read port the cycles use and the writer\n * port the governed actions use, in one instance so a test or local process\n * can share state between them. Same method shape as the memory delivery\n * store: snapshot at entry, one I/O boundary, then one synchronous step\n * that reads the store's clock, checks the transition against the store's\n * own current state and appends. Revisions and configuration versions are\n * append-only; a revision's `effectiveUntil` is derived from its\n * successor's `effectiveFrom` on read, so no stored revision is ever changed.\n * Input reading and the transition rules are shared with the PostgreSQL\n * store (src/subscription-store-core.ts).\n */\n\n/** Options for {@link MemoryWebhookSubscriptionStore}. */\nexport interface MemoryWebhookSubscriptionStoreOptions {\n\t/** The store's clock: every revision takes effect at its time (decision 3). */\n\treadonly clock: WebhookClock;\n\t/**\n\t * Test seam. Awaited at each call's I/O boundary, after its input is read\n\t * and before its atomic step, with the method name. A contract test uses\n\t * it to hold one call there while another runs to completion, forcing an\n\t * interleaving. A throw or rejection fails the call as `store_failed`,\n\t * with nothing written. Leave it unset outside tests.\n\t */\n\treadonly beforeAtomicStep?: (operation: string) => Promise<void> | void;\n}\n\ninterface SubscriptionState extends Target {\n\treadonly revisions: RevisionState[];\n\treadonly configurations: WebhookDeliveryConfiguration[];\n}\n\n/** The key of one (tenantId, spaceId, subscriptionId); JSON-encoded, so distinct tuples never collide. */\nfunction subscriptionKey(tenantId: string, spaceId: string, subscriptionId: string): string {\n\treturn compositeKey(tenantId, spaceId, subscriptionId);\n}\n\nfunction ioBoundary(): Promise<void> {\n\treturn Promise.resolve();\n}\n\nfunction revisionAt(subscription: SubscriptionState, index: number): object {\n\treturn revisionOut(subscription, subscription.revisions[index]!, subscription.revisions[index + 1]?.effectiveFromMs);\n}\n\n/**\n * An in-memory {@link WebhookSubscriptionStore} and {@link WebhookSubscriptionWriter}.\n * Subscriptions are keyed by (tenantId, spaceId, subscriptionId); a read or\n * write in another scope does not see them.\n *\n * @throws {WebhookStoreError} `clock_invalid` when `clock` has no `now` function.\n */\nexport class MemoryWebhookSubscriptionStore implements WebhookSubscriptionStore, WebhookSubscriptionWriter {\n\treadonly #clock: CapturedClock;\n\treadonly #beforeAtomicStep: ((operation: string) => Promise<void> | void) | undefined;\n\treadonly #subscriptions = new Map<string, SubscriptionState>();\n\n\tconstructor(options: MemoryWebhookSubscriptionStoreOptions) {\n\t\tthis.#clock = guard(() => {\n\t\t\tif (options === null || typeof options !== \"object\") throw storeError(\"clock_invalid\", \"clock\");\n\t\t\treturn captureClock(options.clock);\n\t\t}, () => storeError(\"clock_invalid\", \"clock\"));\n\t\tthis.#beforeAtomicStep = readHookOption(options, \"beforeAtomicStep\");\n\t}\n\n\t/** The I/O boundary: the injected seam, or one resolved turn. */\n\tasync #boundary(operation: string): Promise<void> {\n\t\tconst hook = this.#beforeAtomicStep;\n\t\tif (hook === undefined) return ioBoundary();\n\t\ttry {\n\t\t\tawait hook(operation);\n\t\t} catch {\n\t\t\tthrow storeError(\"store_failed\", \"beforeAtomicStep\");\n\t\t}\n\t}\n\n\t#atomic<T>(bounds: CallBounds, body: (nowMs: number) => T): T {\n\t\treturn guard(() => {\n\t\t\tconst nowMs = readClock(this.#clock);\n\t\t\tassertCallWanted(bounds, nowMs);\n\t\t\treturn body(nowMs);\n\t\t}, () => storeError(\"store_failed\", \"store\"));\n\t}\n\n\t#find(target: Target): SubscriptionState | undefined {\n\t\treturn this.#subscriptions.get(subscriptionKey(target.tenantId, target.spaceId, target.subscriptionId));\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Reads\n\t// -------------------------------------------------------------------------\n\n\tasync listEligibilityRevisions(\n\t\tinput: WebhookScope & { readonly recordedAt: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookEligibilityRevision[]> {\n\t\tconst call = readRevisionsAtCall(input, options);\n\t\tawait this.#boundary(\"listEligibilityRevisions\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst found: object[] = [];\n\t\t\tconst subscriptions = [...this.#subscriptions.values()]\n\t\t\t\t.filter((subscription) => subscription.tenantId === call.tenantId && subscription.spaceId === call.spaceId)\n\t\t\t\t.sort((left, right) => compareText(left.subscriptionId, right.subscriptionId));\n\t\t\tfor (const subscription of subscriptions) {\n\t\t\t\t// Half-open: effectiveFrom <= recordedAt < next.effectiveFrom.\n\t\t\t\tfor (let index = subscription.revisions.length - 1; index >= 0; index -= 1) {\n\t\t\t\t\tif (subscription.revisions[index]!.effectiveFromMs <= call.recordedAtMs) {\n\t\t\t\t\t\tconst next = subscription.revisions[index + 1];\n\t\t\t\t\t\tif (next === undefined || call.recordedAtMs < next.effectiveFromMs) found.push(revisionAt(subscription, index));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn copyOut<readonly WebhookEligibilityRevision[]>(found);\n\t\t});\n\t}\n\n\tasync readSubscription(\n\t\tinput: WebhookScope & { readonly subscriptionId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionSnapshot | null> {\n\t\tconst call = readTargetCall(input, options);\n\t\tawait this.#boundary(\"readSubscription\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst subscription = this.#find(call.target);\n\t\t\tif (subscription === undefined) return null;\n\t\t\treturn copyOut<WebhookSubscriptionSnapshot>({\n\t\t\t\tsubscriptionId: subscription.subscriptionId,\n\t\t\t\ttenantId: subscription.tenantId,\n\t\t\t\tspaceId: subscription.spaceId,\n\t\t\t\tstatus: subscription.revisions[subscription.revisions.length - 1]!.status,\n\t\t\t\tstatusSinceRevision: statusSinceRevision(subscription.revisions),\n\t\t\t\tconfiguration: subscription.configurations[subscription.configurations.length - 1]!,\n\t\t\t});\n\t\t});\n\t}\n\n\tasync listEligibilityHistory(\n\t\tinput: WebhookScope & { readonly subscriptionId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookEligibilityRevision[]> {\n\t\tconst call = readTargetCall(input, options);\n\t\tawait this.#boundary(\"listEligibilityHistory\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst subscription = this.#find(call.target);\n\t\t\tif (subscription === undefined) return copyOut<readonly WebhookEligibilityRevision[]>([]);\n\t\t\treturn copyOut<readonly WebhookEligibilityRevision[]>(subscription.revisions.map((_revision, index) => revisionAt(subscription, index)));\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Writes\n\t// -------------------------------------------------------------------------\n\n\tasync createSubscription(\n\t\tinput: WebhookScope & {\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly eventTypePatterns: readonly string[];\n\t\t\treadonly configuration: WebhookDeliveryConfigurationInput;\n\t\t},\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readCreateCall(input, options);\n\t\tawait this.#boundary(\"createSubscription\");\n\t\treturn this.#atomic(call.bounds, (nowMs) => {\n\t\t\tif (this.#find(call.target) !== undefined) return refused(\"already_exists\");\n\t\t\tconst { tenantId, spaceId, subscriptionId } = call.target;\n\t\t\tconst configuration = configurationOut(call.target, 1, call.configuration);\n\t\t\tconst subscription: SubscriptionState = {\n\t\t\t\tsubscriptionId,\n\t\t\t\ttenantId,\n\t\t\t\tspaceId,\n\t\t\t\trevisions: [{ revision: 1, status: \"active\", eventTypePatterns: call.patterns, effectiveFromMs: nowMs }],\n\t\t\t\tconfigurations: [configuration],\n\t\t\t};\n\t\t\tconst result = copyOut<WebhookSubscriptionWriteResult>({ applied: true, revision: revisionAt(subscription, 0), configuration });\n\t\t\tthis.#subscriptions.set(subscriptionKey(tenantId, spaceId, subscriptionId), subscription);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync changeEventTypePatterns(\n\t\tinput: WebhookSubscriptionTransitionInput & { readonly eventTypePatterns: readonly string[] },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readChangePatternsCall(input, options);\n\t\tawait this.#boundary(\"changeEventTypePatterns\");\n\t\treturn this.#atomic(call.bounds, (nowMs) =>\n\t\t\tthis.#transition(call.target, call.expectedRevision, nowMs, (current) => ({ status: current.status, patterns: call.patterns })));\n\t}\n\n\tasync pauseSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"pauseSubscription\", input, options, PAUSE);\n\t}\n\n\tasync resumeSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"resumeSubscription\", input, options, RESUME);\n\t}\n\n\tasync deleteSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"deleteSubscription\", input, options, DELETE);\n\t}\n\n\tasync replaceDeliveryConfiguration(\n\t\tinput: WebhookScope & { readonly subscriptionId: string; readonly configuration: WebhookDeliveryConfigurationInput; readonly expectedVersion?: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookConfigurationWriteResult> {\n\t\tconst call = readReplaceConfigurationCall(input, options);\n\t\tawait this.#boundary(\"replaceDeliveryConfiguration\");\n\t\treturn this.#atomic(call.bounds, () => {\n\t\t\tconst subscription = this.#find(call.target);\n\t\t\tif (subscription === undefined) return copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"not_found\" });\n\t\t\tif (subscription.revisions[subscription.revisions.length - 1]!.status === \"deleted\") {\n\t\t\t\treturn copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"deleted\" });\n\t\t\t}\n\t\t\tconst current = subscription.configurations[subscription.configurations.length - 1]!;\n\t\t\tif (call.expectedVersion !== undefined && call.expectedVersion !== current.version) {\n\t\t\t\treturn copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"version_conflict\", currentVersion: current.version });\n\t\t\t}\n\t\t\tconst configuration = configurationOut(subscription, current.version + 1, call.configuration);\n\t\t\tconst result = copyOut<WebhookConfigurationWriteResult>({ applied: true, configuration });\n\t\t\tsubscription.configurations.push(configuration);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync #statusChange(\n\t\toperation: string,\n\t\tinput: WebhookSubscriptionTransitionInput,\n\t\toptions: WebhookCallOptions,\n\t\tnext: StatusChange,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readStatusChangeCall(input, options);\n\t\tawait this.#boundary(operation);\n\t\treturn this.#atomic(call.bounds, (nowMs) => this.#transition(call.target, call.expectedRevision, nowMs, statusRevisionChange(next)));\n\t}\n\n\t/**\n\t * Append one revision, checked against the store's current state. Runs\n\t * inside the atomic step.\n\t */\n\t#transition(target: Target, expectedRevision: number | undefined, nowMs: number, change: RevisionChange): WebhookSubscriptionWriteResult {\n\t\tconst subscription = this.#find(target);\n\t\tconst decision = decideTransition(subscription?.revisions[subscription.revisions.length - 1], expectedRevision, nowMs, change);\n\t\tif (\"refusal\" in decision) return decision.refusal;\n\t\tconst current = subscription!;\n\t\t// Compute, then commit: the result is built from the would-be history\n\t\t// before the revision is appended.\n\t\tconst result = copyOut<WebhookSubscriptionWriteResult>({\n\t\t\tapplied: true,\n\t\t\trevision: revisionOut(current, decision.appended, undefined),\n\t\t\tconfiguration: current.configurations[current.configurations.length - 1]!,\n\t\t});\n\t\tcurrent.revisions.push(decision.appended);\n\t\treturn result;\n\t}\n}\n","import { guard, storeError } from \"./errors\";\nimport { sha256Hex } from \"./receipt\";\nimport { matches } from \"./snapshot\";\nimport { assertCallWanted, readClock, type CallBounds, type CapturedClock } from \"./store-input\";\n\n/*\n * What the PostgreSQL stores need from a database client, and the\n * transaction, migration and row-reading helpers both stores share.\n *\n * The client is injected and structural, like Host's `PlatformHostSqlClient`:\n * `pg.Pool` satisfies it, and the package has no runtime dependency on `pg`.\n * Unlike Host's interface it also needs `connect()`, because a store method\n * that checks and then writes runs several statements, with the store's\n * clock read between them, on one connection inside one transaction.\n */\n\n/** The rows a query returned. */\nexport interface WebhookPostgresResult<Row = Record<string, unknown>> {\n\trows: Row[];\n}\n\n/** Anything that runs one parameterized statement. */\nexport interface WebhookPostgresQueryable {\n\tquery<Row = Record<string, unknown>>(sql: string, values?: unknown[]): Promise<WebhookPostgresResult<Row>>;\n}\n\n/** One checked-out connection. `release(true)` discards it instead of returning it to the pool. */\nexport interface WebhookPostgresConnection extends WebhookPostgresQueryable {\n\trelease(destroy?: boolean): void;\n}\n\n/** A connection pool: `pg.Pool`, or a Lakebase-compatible client with the same two methods. */\nexport interface WebhookPostgresPool extends WebhookPostgresQueryable {\n\tconnect(): Promise<WebhookPostgresConnection>;\n}\n\n/** Where the store pauses inside a transaction, for the serialization tests only. */\nexport type WebhookTransactionCheckpointStage = \"locked\" | \"written\";\n\n/**\n * A schema name the stores accept: lower-case ASCII letters, digits and\n * underscores, starting with a letter or underscore, at most 63 bytes (the\n * PostgreSQL identifier limit). It is double-quoted wherever it is used, so\n * the pattern, not quoting, is what keeps it from being read as SQL.\n */\nconst SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;\n\nexport const DEFAULT_WEBHOOK_SCHEMA = \"fabric_webhook_delivery\";\n\n/** Read the optional `schema` option; anything but a valid name is `input_invalid`. */\nexport function readSchemaOption(options: unknown): string {\n\treturn guard(() => {\n\t\tconst schema = (options as { schema?: unknown }).schema;\n\t\tif (schema === undefined) return `\"${DEFAULT_WEBHOOK_SCHEMA}\"`;\n\t\tif (typeof schema !== \"string\" || !matches(SCHEMA_NAME, schema)) throw storeError(\"input_invalid\", \"schema\");\n\t\treturn `\"${schema}\"`;\n\t}, () => storeError(\"input_invalid\", \"schema\"));\n}\n\n/** Read the required `pool` option: an object with `query` and `connect` functions. */\nexport function readPoolOption(options: unknown): WebhookPostgresPool {\n\treturn guard(() => {\n\t\tconst pool = (options as { pool?: unknown }).pool;\n\t\tif (pool === null || typeof pool !== \"object\") throw storeError(\"input_invalid\", \"pool\");\n\t\tconst { query, connect } = pool as { query?: unknown; connect?: unknown };\n\t\tif (typeof query !== \"function\" || typeof connect !== \"function\") throw storeError(\"input_invalid\", \"pool\");\n\t\treturn pool as WebhookPostgresPool;\n\t}, () => storeError(\"input_invalid\", \"pool\"));\n}\n\n/**\n * Run `run` and map whatever it throws: a package error passes through, and\n * anything else (a driver error, a lost connection, a constraint violation)\n * becomes `store_failed` without being read.\n */\nexport async function storeCall<T>(run: () => Promise<T>): Promise<T> {\n\ttry {\n\t\treturn await run();\n\t} catch (thrown) {\n\t\treturn guard<T>(() => {\n\t\t\tthrow thrown;\n\t\t}, () => storeError(\"store_failed\", \"store\"));\n\t}\n}\n\n/** Lets a transaction body end in ROLLBACK while still returning its result. */\nexport interface WebhookTransactionControl {\n\t/** Roll back instead of committing; the body's return value is still returned. */\n\tabandon(): void;\n}\n\n/**\n * Run `run` inside one READ COMMITTED transaction on one connection. The\n * isolation level is named rather than inherited, because the locking\n * argument in the README (\"PostgreSQL stores\") assumes it. The transaction\n * commits unless `run` throws or calls `control.abandon()`. Any throw rolls\n * back; if the rollback itself fails the connection is discarded rather\n * than returned to the pool in an unknown state.\n */\nexport async function inTransaction<T>(\n\tpool: WebhookPostgresPool,\n\trun: (tx: WebhookPostgresQueryable, control: WebhookTransactionControl) => Promise<T>,\n): Promise<T> {\n\tconst connection = await pool.connect();\n\tlet destroy = false;\n\tlet abandoned = false;\n\ttry {\n\t\tawait connection.query(\"BEGIN ISOLATION LEVEL READ COMMITTED\");\n\t\tconst result = await run(connection, { abandon: () => { abandoned = true; } });\n\t\tawait connection.query(abandoned ? \"ROLLBACK\" : \"COMMIT\");\n\t\treturn result;\n\t} catch (error) {\n\t\ttry {\n\t\t\tawait connection.query(\"ROLLBACK\");\n\t\t} catch {\n\t\t\tdestroy = true;\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\tconnection.release(destroy);\n\t}\n}\n\n/**\n * One store write, in one transaction, in three phases:\n *\n * 1. `lock` runs every statement that can wait on another transaction:\n * the horizon table lock, `SELECT … FOR UPDATE` / `FOR SHARE` on the\n * records the write reads, and a tentative insert-if-absent, whose\n * conflict check waits on a concurrent uncommitted insert of the same\n * key. It decides nothing.\n * 2. With every lock held, the store's clock is read and a call whose\n * signal aborted or whose deadline passed is refused, rolling back. A\n * call that waited for a lock is therefore judged, and its horizon\n * floor computed, at the time it decides, not before it waited.\n * 3. `body` decides from what `lock` read and finishes the write. It may\n * call `control.abandon()` to roll back a tentative write and still\n * return its result (an insert that turned out past the horizon).\n *\n * Immediately before COMMIT the clock is read and the bounds are checked\n * once more, so nothing commits if the signal aborted or the deadline\n * passed while `body` ran. The purge is the only write whose `body` can\n * wait on another transaction (its deletes wait for row locks). Every other\n * body writes only rows its `lock` phase already holds, rows it inserted\n * there, rows keyed by a fresh identity value (attempts, requeue evidence),\n * a begun attempt keyed by its intent's current fence (no other transaction\n * can insert that key while this one holds the intent row), or a\n * subscription's next revision or configuration version, which no other\n * transaction can insert while this one holds the head row.\n */\nexport function runWrite<L, T>(\n\tpool: WebhookPostgresPool,\n\tclock: CapturedClock,\n\tbounds: CallBounds,\n\tlock: (tx: WebhookPostgresQueryable) => Promise<L>,\n\tbody: (tx: WebhookPostgresQueryable, nowMs: number, locked: L, control: WebhookTransactionControl) => Promise<T>,\n): Promise<T> {\n\treturn storeCall(() => inTransaction(pool, async (tx, control) => {\n\t\tconst locked = await lock(tx);\n\t\tconst nowMs = readClock(clock);\n\t\tassertCallWanted(bounds, nowMs);\n\t\tconst result = await body(tx, nowMs, locked, control);\n\t\tassertCallWanted(bounds, readClock(clock));\n\t\treturn result;\n\t}));\n}\n\n/** One store read: one statement (its own transaction) after the call-bounds check. */\nexport function runRead<T>(\n\tpool: WebhookPostgresPool,\n\tclock: CapturedClock,\n\tbounds: CallBounds,\n\tbody: (db: WebhookPostgresQueryable, nowMs: number) => Promise<T>,\n): Promise<T> {\n\treturn storeCall(async () => {\n\t\tconst nowMs = readClock(clock);\n\t\tassertCallWanted(bounds, nowMs);\n\t\treturn body(pool, nowMs);\n\t});\n}\n\n/** Await a test seam; a throw or rejection fails the call as `store_failed` naming the seam. */\nexport async function awaitHook(hook: (() => Promise<void> | void) | undefined, field: string): Promise<void> {\n\tif (hook === undefined) return;\n\ttry {\n\t\tawait hook();\n\t} catch {\n\t\tthrow storeError(\"store_failed\", field);\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Migrations\n// ---------------------------------------------------------------------------\n\n/** One immutable migration. `sql` names the schema as `{{schema}}`. */\nexport interface WebhookPostgresMigration {\n\treadonly version: number;\n\treadonly name: string;\n\treadonly sql: string;\n}\n\n\n/**\n * Apply `component`'s migrations to `schema`, in version order, in one\n * transaction, mirroring Host's `applyPostgresMigrations`: a\n * transaction-scoped advisory lock serializes concurrent callers, each\n * applied version is recorded with the SHA-256 of its SQL template, and a\n * recorded version whose template has since changed fails as `store_failed`\n * (`ensureSchema.checksum`) instead of being re-run. The checksum is taken\n * before the schema name is substituted, so the same migration has the same\n * checksum in every schema.\n */\nexport async function applyWebhookMigrations(\n\tpool: WebhookPostgresPool,\n\tschema: string,\n\tcomponent: string,\n\tmigrations: readonly WebhookPostgresMigration[],\n): Promise<void> {\n\tconst ordered = [...migrations].sort((left, right) => left.version - right.version);\n\tconst checksums = await Promise.all(ordered.map((migration) => sha256Hex(migration.sql, \"ensureSchema.crypto\")));\n\tawait storeCall(() => inTransaction(pool, async (tx) => {\n\t\tawait tx.query(\"SELECT pg_advisory_xact_lock(hashtext($1))\", [`fabric_webhook_delivery.schema_migrations:${schema}`]);\n\t\tawait tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);\n\t\tawait tx.query(`CREATE TABLE IF NOT EXISTS ${schema}.webhook_schema_migrations (\n\t\t\tcomponent text NOT NULL,\n\t\t\tversion integer NOT NULL,\n\t\t\tname text NOT NULL,\n\t\t\tchecksum text NOT NULL,\n\t\t\tapplied_at timestamptz NOT NULL DEFAULT now(),\n\t\t\tPRIMARY KEY (component, version)\n\t\t)`);\n\t\tfor (let index = 0; index < ordered.length; index += 1) {\n\t\t\tconst migration = ordered[index]!;\n\t\t\tconst checksum = checksums[index]!;\n\t\t\tconst recorded = await tx.query<{ checksum: string }>(\n\t\t\t\t`SELECT checksum FROM ${schema}.webhook_schema_migrations WHERE component = $1 AND version = $2`,\n\t\t\t\t[component, migration.version],\n\t\t\t);\n\t\t\tconst row = recorded.rows[0];\n\t\t\tif (row !== undefined) {\n\t\t\t\tif (row.checksum !== checksum) throw storeError(\"store_failed\", \"ensureSchema.checksum\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait tx.query(migration.sql.replaceAll(\"{{schema}}\", schema));\n\t\t\tawait tx.query(\n\t\t\t\t`INSERT INTO ${schema}.webhook_schema_migrations (component, version, name, checksum) VALUES ($1, $2, $3, $4)`,\n\t\t\t\t[component, migration.version, migration.name, checksum],\n\t\t\t);\n\t\t}\n\t}));\n}\n\n// ---------------------------------------------------------------------------\n// Values in and out\n// ---------------------------------------------------------------------------\n\nconst jsonParse = JSON.parse;\nconst numberIsSafeInteger = Number.isSafeInteger;\nconst NumberConstructor = Number;\n\n/**\n * A sort key whose byte order (under `COLLATE \"C\"`) is the UTF-16 code unit\n * order JavaScript's `<` uses: four hex digits per code unit. PostgreSQL's\n * own text orders compare code points or follow a locale, which would put a\n * few strings in a different order from the memory store's sort.\n */\nexport function utf16SortKey(value: string): string {\n\tlet key = \"\";\n\tfor (let index = 0; index < value.length; index += 1) key += value.charCodeAt(index).toString(16).padStart(4, \"0\");\n\treturn key;\n}\n\n/** A whole number read from a row; `bigint` columns are selected as text so every client returns the same thing. */\nexport function intOf(value: unknown, field: string): number {\n\tconst number = typeof value === \"number\" ? value : typeof value === \"string\" ? NumberConstructor(value) : Number.NaN;\n\tif (!numberIsSafeInteger(number)) throw storeError(\"store_failed\", field);\n\treturn number;\n}\n\nexport function optionalIntOf(value: unknown, field: string): number | undefined {\n\treturn value === null || value === undefined ? undefined : intOf(value, field);\n}\n\nexport function textOf(value: unknown, field: string): string {\n\tif (typeof value !== \"string\") throw storeError(\"store_failed\", field);\n\treturn value;\n}\n\nexport function optionalTextOf(value: unknown, field: string): string | undefined {\n\treturn value === null || value === undefined ? undefined : textOf(value, field);\n}\n\n/**\n * Parse a `json` column selected as text. The stores write JSON text with\n * the package serializer and keep it in `json` columns, not `jsonb`: `json`\n * keeps the text as written, so key order and every string, lone\n * surrogates included, come back exactly as the memory store would return\n * them.\n */\nexport function jsonOf(value: unknown, field: string): unknown {\n\tconst text = textOf(value, field);\n\ttry {\n\t\treturn jsonParse(text) as unknown;\n\t} catch {\n\t\tthrow storeError(\"store_failed\", field);\n\t}\n}\n","import type { WebhookDiagnosticCode } from \"./codes\";\nimport {\n\tapplyEnrichment,\n\tapplyRequeue,\n\tapplySettlement,\n\tattemptEntryOut,\n\tbeginResult,\n\tcompareText,\n\tcopyOut,\n\tdenialRecord,\n\tfencedOutcome,\n\tholds,\n\tholdsFence,\n\tinScope,\n\tintentOut,\n\tenrichmentRefusal,\n\tenrichmentRefused,\n\tintentRequeueEvidence,\n\tjobOut,\n\tjobEnrichmentEvidence,\n\tjobRequeueEvidence,\n\tleaseCheck,\n\tpriorInvocationEvidence,\n\tmarkerKey,\n\tmayBegin,\n\treadAppendAttemptCall,\n\treadBeginAttemptCall,\n\treadCancelCall,\n\treadClaimCall,\n\treadDeadLetterJobCall,\n\treadDeliveryCall,\n\treadDenialCall,\n\treadEventCall,\n\treadFinishAttemptCall,\n\treadHookOption,\n\treadHorizonOption,\n\treadInsertFanOutJobCall,\n\treadInsertIntentCall,\n\treadIntentRequeueCall,\n\treadInvocationEvidenceCall,\n\treadJobFencedCall,\n\treadJobEnrichmentCall,\n\treadJobRequeueCall,\n\treadLeaseCheckCall,\n\treadPurgeCall,\n\treadRenewIntentCall,\n\treadRenewJobCall,\n\treadRescheduleCall,\n\treadSettleCall,\n\treadTombstoneCall,\n\trenewedExpiryMs,\n\trequeueRefusal,\n\trequeueRefused,\n\treplayedResult,\n\ttype InvocationTarget,\n\tTERMINAL_INTENT,\n\tTERMINAL_JOB,\n\ttombstoneOut,\n\ttype IntentState,\n\ttype JobState,\n\ttype MarkerState,\n} from \"./delivery-store-core\";\nimport { guard, storeError } from \"./errors\";\nimport { attemptReceiptDigest, newAttemptReceipt } from \"./receipt\";\nimport type {\n\tWebhookActorEnrichmentResult,\n\tWebhookAttemptBeginResult,\n\tWebhookCallOptions,\n\tWebhookClaimRequest,\n\tWebhookClock,\n\tWebhookDeliveryLeaseCheck,\n\tWebhookDeliveryStore,\n\tWebhookFanOutJobFence,\n\tWebhookFencedInsertResult,\n\tWebhookFencedWrite,\n\tWebhookInsertResult,\n\tWebhookPurgeResult,\n\tWebhookRequeueResult,\n\tWebhookScope,\n} from \"./ports\";\nimport {\n\tapplyWebhookMigrations,\n\tawaitHook,\n\tintOf,\n\tjsonOf,\n\toptionalIntOf,\n\toptionalTextOf,\n\treadPoolOption,\n\treadSchemaOption,\n\trunRead,\n\trunWrite,\n\tstoreCall,\n\ttextOf,\n\tutf16SortKey,\n\ttype WebhookPostgresMigration,\n\ttype WebhookPostgresPool,\n\ttype WebhookPostgresQueryable,\n\ttype WebhookTransactionCheckpointStage,\n\ttype WebhookTransactionControl,\n} from \"./postgres-sql\";\nimport { frozenList, mathMax, serializeJson } from \"./snapshot\";\nimport { captureClock, isoOf, type CallBounds, type CapturedClock, type Snapshot } from \"./store-input\";\nimport type {\n\tWebhookActorEnrichmentRequest,\n\tWebhookAdmissionDenialRecord,\n\tWebhookDeliveryAttemptFinish,\n\tWebhookDeliveryAttemptLogEntry,\n\tWebhookDeliveryAttemptRecord,\n\tWebhookDeliveryAttemptStart,\n\tWebhookDeliveryIntent,\n\tWebhookFanOutJob,\n\tWebhookFanOutJobDraft,\n\tWebhookRequeueEvidence,\n\tWebhookRequeueRequest,\n\tWebhookTombstone,\n} from \"./types\";\n\n/*\n * PostgreSQL WebhookDeliveryStore. It holds the same contract as the memory\n * store (tests/store-contract.ts runs against both) and reads its input and\n * renders its records through the same functions (src/delivery-store-core.ts).\n *\n * Every method has the memory store's shape, with the synchronous atomic\n * step replaced by one transaction:\n *\n * 1. Entry: the shared reader copies and validates the arguments.\n * 2. The `beforeAtomicStep` test seam, awaited before any connection is\n * taken or transaction opened.\n * 3. For a write, one READ COMMITTED transaction on one connection\n * (`runWrite` in src/postgres-sql.ts), in this order:\n * a. every lock, in a fixed order: the horizon table lock first (when\n * the method takes it), then the record rows (`FOR UPDATE`, or\n * `FOR SHARE` on an insert's parent job), then any tentative\n * insert-if-absent, whose conflict check can wait on a concurrent\n * insert of the same key;\n * b. the store's clock, and the refusal of a call whose signal\n * aborted or whose deadline passed, possibly while it waited in (a);\n * c. every check (lease, scope, horizon floor, uniqueness, status) and\n * the write, or a rollback of the tentative insert;\n * d. the clock and the call bounds once more, then COMMIT.\n * A read is one statement after the bounds check.\n *\n * Replay-horizon serialization. A purge and a horizon-checked write (job,\n * intent and denial inserts, job and intent requeues, actor enrichment)\n * must not interleave\n * between the write's read of the purge floor and its write; otherwise a\n * purge could remove a key after an insert read the old floor, and the\n * insert would re-create it. The mechanism is a table-level lock on the\n * store's one-row horizon table, `webhook_delivery_horizon`:\n *\n * - every horizon-checked write takes `LOCK TABLE ... IN SHARE MODE` as its\n * first statement and reads the highest purge cutoff, then takes its\n * record locks, and only then reads the clock;\n * - `purgeExpiredRecords` takes `LOCK TABLE ... IN EXCLUSIVE MODE` as its\n * first statement and reads the cutoff, then reads the clock, removes,\n * and raises the floor before it commits.\n *\n * SHARE conflicts with EXCLUSIVE and not with itself, so writes do not\n * serialize against each other, and a write and a purge cannot both hold the\n * lock: whichever transaction gets it first commits (or rolls back) before\n * the other reads anything. Both orders are then serial, which is all the\n * horizon rules need. A table lock rather than a row lock (`FOR SHARE` /\n * `FOR UPDATE` on the horizon row) because PostgreSQL's lock manager queues\n * a SHARE request behind a waiting EXCLUSIVE one, so a steady stream of\n * inserts cannot keep a purge waiting; a new `FOR SHARE` row lock joins the\n * existing share lockers and can. `tests/postgres-live.test.ts` checks both\n * orders with a pause inside the transaction (\"check-to-write\n * serialization\"), and that a later write queues behind a waiting purge.\n *\n * Other writes take only row locks. A claim takes `FOR UPDATE SKIP LOCKED`\n * on the rows it leases, which never waits, so concurrent claims never\n * lease one record twice. Fenced writes and settlements lock the record with\n * `FOR UPDATE`; an intent or denial insert locks its parent job with\n * `FOR SHARE`, so a reclaim (an UPDATE) cannot advance the parent's fence\n * between the lease check and the insert. \"call bounds while waiting for a\n * lock\" in the live tests holds each of these locks from another connection\n * and checks that an abort or an expired deadline during the wait commits\n * nothing.\n */\n\n/** Options for {@link PostgresWebhookDeliveryStore}. */\nexport interface PostgresWebhookDeliveryStoreOptions {\n\t/** The connection pool, for example a `pg.Pool`. The store never ends it. */\n\treadonly pool: WebhookPostgresPool;\n\t/** The store's clock: it timestamps requeue evidence and decides the replay horizon. */\n\treadonly clock: WebhookClock;\n\t/** The replay horizon in milliseconds; see `WebhookDeliveryLimits.replayHorizonMs`. */\n\treadonly replayHorizonMs: number;\n\t/**\n\t * The schema the tables live in, default `fabric_webhook_delivery`.\n\t * Lower-case letters, digits and underscores only. The horizon floor is\n\t * per schema: two stores on one schema share one floor.\n\t */\n\treadonly schema?: string;\n\t/**\n\t * Test seam, with the memory store's meaning: awaited once per call,\n\t * with the method name, after the input is read and before a connection\n\t * is taken. Leave it unset outside tests.\n\t */\n\treadonly beforeAtomicStep?: (operation: string) => Promise<void> | void;\n\t/**\n\t * Test seam for the serialization tests. Awaited inside the transaction\n\t * of each horizon-checked method and of the purge: at `locked`, after the\n\t * horizon lock, the purge-cutoff read and the record locks, and before\n\t * the clock is read or anything is written; and at `written`, after the\n\t * write and before the commit (a call that returns a refusal does not\n\t * reach it). A throw or rejection rolls the transaction back and fails\n\t * the call as `store_failed`. Leave it unset outside tests.\n\t */\n\treadonly transactionCheckpoint?: (operation: string, stage: WebhookTransactionCheckpointStage) => Promise<void> | void;\n}\n\ntype HorizonLock = \"share\" | \"exclusive\";\n\ninterface Tables {\n\treadonly horizon: string;\n\treadonly jobs: string;\n\treadonly intents: string;\n\treadonly tombstones: string;\n\treadonly denials: string;\n\treadonly attempts: string;\n\treadonly outcomes: string;\n\treadonly evidence: string;\n}\n\nfunction tablesIn(schema: string): Tables {\n\treturn {\n\t\thorizon: `${schema}.webhook_delivery_horizon`,\n\t\tjobs: `${schema}.webhook_fan_out_jobs`,\n\t\tintents: `${schema}.webhook_delivery_intents`,\n\t\ttombstones: `${schema}.webhook_delivery_tombstones`,\n\t\tdenials: `${schema}.webhook_admission_denials`,\n\t\tattempts: `${schema}.webhook_delivery_attempts`,\n\t\toutcomes: `${schema}.webhook_delivery_attempt_outcomes`,\n\t\tevidence: `${schema}.webhook_requeue_evidence`,\n\t};\n}\n\n/**\n * The delivery store's schema. Times are `bigint` epoch milliseconds, so\n * every instant a JavaScript `Date` can hold is stored exactly (a\n * `timestamptz` cannot hold years before 4713 BC, which a `Date` can).\n * Documents and free text are `json` columns holding the package\n * serializer's output (see `jsonOf`). `sort_key` columns hold\n * `utf16SortKey` of the record's key, so ties sort as in the memory store.\n */\nconst DELIVERY_MIGRATIONS: readonly WebhookPostgresMigration[] = Object.freeze([{\n\tversion: 1,\n\tname: \"delivery_baseline\",\n\tsql: `\n\t\tCREATE TABLE {{schema}}.webhook_delivery_horizon (\n\t\t\tsingleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n\t\t\tpurged_through_ms bigint\n\t\t);\n\t\tINSERT INTO {{schema}}.webhook_delivery_horizon (singleton, purged_through_ms) VALUES (true, NULL);\n\t\tCREATE TABLE {{schema}}.webhook_fan_out_jobs (\n\t\t\tevent_id text PRIMARY KEY,\n\t\t\tsort_key text COLLATE \"C\" NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tdraft json NOT NULL,\n\t\t\tanchor_ms bigint NOT NULL,\n\t\t\tstatus text NOT NULL CHECK (status IN ('pending', 'completed', 'dead_letter')),\n\t\t\tattempt_count integer NOT NULL,\n\t\t\tavailable_at_ms bigint NOT NULL,\n\t\t\tcreated_at_ms bigint NOT NULL,\n\t\t\tprocessing_deadline_ms bigint NOT NULL,\n\t\t\tcompleted_at_ms bigint,\n\t\t\tlast_diagnostic text,\n\t\t\tfence bigint NOT NULL,\n\t\t\tlease_owner text,\n\t\t\tlease_expires_at_ms bigint,\n\t\t\tCHECK ((lease_owner IS NULL) = (lease_expires_at_ms IS NULL))\n\t\t);\n\t\tCREATE INDEX webhook_fan_out_jobs_claim_idx ON {{schema}}.webhook_fan_out_jobs (available_at_ms, created_at_ms, sort_key) WHERE status = 'pending';\n\t\tCREATE INDEX webhook_fan_out_jobs_purge_idx ON {{schema}}.webhook_fan_out_jobs (anchor_ms) WHERE status <> 'pending';\n\t\tCREATE TABLE {{schema}}.webhook_delivery_intents (\n\t\t\tdelivery_id text PRIMARY KEY,\n\t\t\tsort_key text COLLATE \"C\" NOT NULL,\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tevent_id text NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\teligibility_revision bigint NOT NULL,\n\t\t\tbody json NOT NULL,\n\t\t\tanchor_ms bigint NOT NULL,\n\t\t\tstatus text NOT NULL CHECK (status IN ('pending', 'delivered', 'dead_letter', 'cancelled')),\n\t\t\tattempt_count integer NOT NULL,\n\t\t\tavailable_at_ms bigint NOT NULL,\n\t\t\tcreated_at_ms bigint NOT NULL,\n\t\t\tprocessing_deadline_ms bigint NOT NULL,\n\t\t\tlast_outcome text,\n\t\t\tlast_reason text,\n\t\t\tlast_diagnostic text,\n\t\t\tfence bigint NOT NULL,\n\t\t\tlease_owner text,\n\t\t\tlease_expires_at_ms bigint,\n\t\t\tCHECK ((lease_owner IS NULL) = (lease_expires_at_ms IS NULL)),\n\t\t\tCHECK ((last_outcome IS NULL) = (last_reason IS NULL))\n\t\t);\n\t\tCREATE INDEX webhook_delivery_intents_claim_idx ON {{schema}}.webhook_delivery_intents (available_at_ms, created_at_ms, sort_key) WHERE status = 'pending';\n\t\tCREATE INDEX webhook_delivery_intents_purge_idx ON {{schema}}.webhook_delivery_intents (anchor_ms) WHERE status <> 'pending';\n\t\tCREATE INDEX webhook_delivery_intents_subscription_idx ON {{schema}}.webhook_delivery_intents (tenant_id, space_id, subscription_id) WHERE status = 'pending';\n\t\tCREATE TABLE {{schema}}.webhook_delivery_tombstones (\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tevent_id text NOT NULL,\n\t\t\tkind text NOT NULL CHECK (kind IN ('intent', 'denial')),\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tanchor_ms bigint NOT NULL,\n\t\t\tPRIMARY KEY (subscription_id, event_id)\n\t\t);\n\t\tCREATE TABLE {{schema}}.webhook_admission_denials (\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tevent_id text NOT NULL,\n\t\t\tsort_key text COLLATE \"C\" NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\trecord json NOT NULL,\n\t\t\tanchor_ms bigint NOT NULL,\n\t\t\tPRIMARY KEY (subscription_id, event_id)\n\t\t);\n\t\tCREATE INDEX webhook_admission_denials_purge_idx ON {{schema}}.webhook_admission_denials (anchor_ms);\n\t\tCREATE TABLE {{schema}}.webhook_delivery_attempts (\n\t\t\tseq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n\t\t\tdelivery_id text NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\trecord json NOT NULL\n\t\t);\n\t\tCREATE INDEX webhook_delivery_attempts_intent_idx ON {{schema}}.webhook_delivery_attempts (delivery_id, seq);\n\t\tCREATE TABLE {{schema}}.webhook_requeue_evidence (\n\t\t\tseq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n\t\t\tevent_id text NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\trecord json NOT NULL\n\t\t);\n\t\tCREATE INDEX webhook_requeue_evidence_event_idx ON {{schema}}.webhook_requeue_evidence (event_id, seq);\n\t`,\n}, {\n\t// PR 8: an attempt begun under the intent's lease before the transport\n\t// handoff (fence and the SHA-256 digest of its receipt set), and its\n\t// outcome, appended once, unfenced, by the holder of the receipt.\n\tversion: 2,\n\tname: \"delivery_attempt_begin_finish\",\n\tsql: `\n\t\tALTER TABLE {{schema}}.webhook_delivery_attempts ADD COLUMN fence bigint;\n\t\tALTER TABLE {{schema}}.webhook_delivery_attempts ADD COLUMN receipt_digest text;\n\t\tALTER TABLE {{schema}}.webhook_delivery_attempts ADD CONSTRAINT webhook_delivery_attempts_receipt_check CHECK ((fence IS NULL) = (receipt_digest IS NULL));\n\t\tCREATE UNIQUE INDEX webhook_delivery_attempts_begun_idx ON {{schema}}.webhook_delivery_attempts (delivery_id, fence) WHERE fence IS NOT NULL;\n\t\tCREATE TABLE {{schema}}.webhook_delivery_attempt_outcomes (\n\t\t\tdelivery_id text NOT NULL,\n\t\t\tfence bigint NOT NULL,\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\trecord json NOT NULL,\n\t\t\tPRIMARY KEY (delivery_id, fence)\n\t\t);\n\t`,\n}, {\n\t// PR 9: requeue and enrichment evidence indexed by the governed\n\t// invocation that appended it, so a re-run of that invocation finds it\n\t// inside its own transaction, and after the record it names is purged.\n\t// Rows written before this migration are backfilled from the record.\n\tversion: 3,\n\tname: \"requeue_evidence_invocation\",\n\tsql: `\n\t\tALTER TABLE {{schema}}.webhook_requeue_evidence ADD COLUMN action_invocation_id text;\n\t\tUPDATE {{schema}}.webhook_requeue_evidence SET action_invocation_id = record->>'actionInvocationId';\n\t\tCREATE INDEX webhook_requeue_evidence_invocation_idx ON {{schema}}.webhook_requeue_evidence (tenant_id, space_id, action_invocation_id, seq)\n\t\t\tWHERE action_invocation_id IS NOT NULL;\n\t`,\n}]);\n\nconst JOB_COLUMNS = [\n\t\"event_id\", \"tenant_id\", \"space_id\", \"draft::text AS draft\", \"anchor_ms::text AS anchor_ms\", \"status\",\n\t\"attempt_count::text AS attempt_count\", \"available_at_ms::text AS available_at_ms\", \"created_at_ms::text AS created_at_ms\",\n\t\"processing_deadline_ms::text AS processing_deadline_ms\", \"completed_at_ms::text AS completed_at_ms\", \"last_diagnostic\",\n\t\"fence::text AS fence\", \"lease_owner\", \"lease_expires_at_ms::text AS lease_expires_at_ms\",\n];\n\nconst INTENT_COLUMNS = [\n\t\"delivery_id\", \"subscription_id\", \"event_id\", \"tenant_id\", \"space_id\", \"eligibility_revision::text AS eligibility_revision\",\n\t\"body::text AS body\", \"anchor_ms::text AS anchor_ms\", \"status\", \"attempt_count::text AS attempt_count\",\n\t\"available_at_ms::text AS available_at_ms\", \"created_at_ms::text AS created_at_ms\",\n\t\"processing_deadline_ms::text AS processing_deadline_ms\", \"last_outcome\", \"last_reason\", \"last_diagnostic\",\n\t\"fence::text AS fence\", \"lease_owner\", \"lease_expires_at_ms::text AS lease_expires_at_ms\",\n];\n\nfunction columns(list: readonly string[], alias?: string): string {\n\treturn list.map((column) => (alias === undefined ? column : `${alias}.${column}`)).join(\", \");\n}\n\ntype Row = Record<string, unknown>;\n\n/** Hydrate a job row into the shared state shape, copying each field. */\nfunction jobFrom(row: Row): JobState {\n\tconst fence = intOf(row[\"fence\"], \"row.fence\");\n\tconst owner = optionalTextOf(row[\"lease_owner\"], \"row.lease_owner\");\n\treturn {\n\t\tkey: textOf(row[\"event_id\"], \"row.event_id\"),\n\t\tdraft: jsonOf(row[\"draft\"], \"row.draft\") as Snapshot,\n\t\ttenantId: textOf(row[\"tenant_id\"], \"row.tenant_id\"),\n\t\tspaceId: textOf(row[\"space_id\"], \"row.space_id\"),\n\t\tanchorMs: intOf(row[\"anchor_ms\"], \"row.anchor_ms\"),\n\t\tstatus: textOf(row[\"status\"], \"row.status\") as JobState[\"status\"],\n\t\tattemptCount: intOf(row[\"attempt_count\"], \"row.attempt_count\"),\n\t\tavailableAtMs: intOf(row[\"available_at_ms\"], \"row.available_at_ms\"),\n\t\tcreatedAtMs: intOf(row[\"created_at_ms\"], \"row.created_at_ms\"),\n\t\tprocessingDeadlineMs: intOf(row[\"processing_deadline_ms\"], \"row.processing_deadline_ms\"),\n\t\tcompletedAtMs: optionalIntOf(row[\"completed_at_ms\"], \"row.completed_at_ms\"),\n\t\tlastDiagnostic: optionalTextOf(row[\"last_diagnostic\"], \"row.last_diagnostic\") as WebhookDiagnosticCode | undefined,\n\t\tfence,\n\t\tlease: owner === undefined ? undefined : { owner, fence, expiresAtMs: intOf(row[\"lease_expires_at_ms\"], \"row.lease_expires_at_ms\") },\n\t};\n}\n\n/** Hydrate an intent row into the shared state shape, copying each field. */\nfunction intentFrom(row: Row): IntentState {\n\tconst fence = intOf(row[\"fence\"], \"row.fence\");\n\tconst owner = optionalTextOf(row[\"lease_owner\"], \"row.lease_owner\");\n\tconst outcome = optionalTextOf(row[\"last_outcome\"], \"row.last_outcome\");\n\treturn {\n\t\tkey: textOf(row[\"delivery_id\"], \"row.delivery_id\"),\n\t\tsubscriptionId: textOf(row[\"subscription_id\"], \"row.subscription_id\"),\n\t\teventId: textOf(row[\"event_id\"], \"row.event_id\"),\n\t\ttenantId: textOf(row[\"tenant_id\"], \"row.tenant_id\"),\n\t\tspaceId: textOf(row[\"space_id\"], \"row.space_id\"),\n\t\teligibilityRevision: intOf(row[\"eligibility_revision\"], \"row.eligibility_revision\"),\n\t\tbody: textOf(jsonOf(row[\"body\"], \"row.body\"), \"row.body\"),\n\t\tanchorMs: intOf(row[\"anchor_ms\"], \"row.anchor_ms\"),\n\t\tstatus: textOf(row[\"status\"], \"row.status\") as IntentState[\"status\"],\n\t\tattemptCount: intOf(row[\"attempt_count\"], \"row.attempt_count\"),\n\t\tavailableAtMs: intOf(row[\"available_at_ms\"], \"row.available_at_ms\"),\n\t\tcreatedAtMs: intOf(row[\"created_at_ms\"], \"row.created_at_ms\"),\n\t\tprocessingDeadlineMs: intOf(row[\"processing_deadline_ms\"], \"row.processing_deadline_ms\"),\n\t\tlastOutcome: outcome === undefined\n\t\t\t? undefined\n\t\t\t: { outcome: outcome as NonNullable<IntentState[\"lastOutcome\"]>[\"outcome\"], reason: textOf(row[\"last_reason\"], \"row.last_reason\") as NonNullable<IntentState[\"lastOutcome\"]>[\"reason\"] },\n\t\tlastDiagnostic: optionalTextOf(row[\"last_diagnostic\"], \"row.last_diagnostic\") as WebhookDiagnosticCode | undefined,\n\t\tfence,\n\t\tlease: owner === undefined ? undefined : { owner, fence, expiresAtMs: intOf(row[\"lease_expires_at_ms\"], \"row.lease_expires_at_ms\") },\n\t};\n}\n\n/** Claimed rows in the memory store's claim order: `availableAt`, then `createdAt`, then key. */\nfunction claimOrder<T extends { readonly availableAtMs: number; readonly createdAtMs: number; readonly key: string }>(states: T[]): T[] {\n\treturn states.sort((left, right) => left.availableAtMs - right.availableAtMs || left.createdAtMs - right.createdAtMs || compareText(left.key, right.key));\n}\n\n/**\n * A PostgreSQL {@link WebhookDeliveryStore}. Call {@link ensureSchema} once\n * before use, at startup or from a migration step.\n *\n * @throws {WebhookDeliveryConfigError} when `replayHorizonMs` is not a\n * positive whole number of milliseconds within `WEBHOOK_MAX_REPLAY_HORIZON_MS`.\n * @throws {WebhookStoreError} `clock_invalid` when `clock` has no `now`\n * function; `input_invalid` when `pool`, `schema` or a test seam is not usable.\n */\nexport class PostgresWebhookDeliveryStore implements WebhookDeliveryStore {\n\treadonly #pool: WebhookPostgresPool;\n\treadonly #clock: CapturedClock;\n\treadonly #horizonMs: number;\n\treadonly #schema: string;\n\treadonly #t: Tables;\n\treadonly #beforeAtomicStep: ((operation: string) => Promise<void> | void) | undefined;\n\treadonly #checkpoint: ((operation: string, stage: WebhookTransactionCheckpointStage) => Promise<void> | void) | undefined;\n\n\tconstructor(options: PostgresWebhookDeliveryStoreOptions) {\n\t\tthis.#horizonMs = readHorizonOption(options);\n\t\tthis.#clock = guard(() => captureClock((options as { clock?: WebhookClock }).clock), () => storeError(\"clock_invalid\", \"clock\"));\n\t\tthis.#pool = readPoolOption(options);\n\t\tthis.#schema = readSchemaOption(options);\n\t\tthis.#t = tablesIn(this.#schema);\n\t\tthis.#beforeAtomicStep = readHookOption(options, \"beforeAtomicStep\");\n\t\tthis.#checkpoint = readHookOption(options, \"transactionCheckpoint\");\n\t}\n\n\t/** The replay horizon this store enforces, in milliseconds. */\n\tget replayHorizonMs(): number {\n\t\treturn this.#horizonMs;\n\t}\n\n\t/**\n\t * Create the schema and tables, or check that the applied migrations are\n\t * unchanged. Safe to call concurrently and repeatedly: an advisory lock\n\t * serializes callers and each migration is recorded once\n\t * (`applyWebhookMigrations` in src/postgres-sql.ts).\n\t */\n\tasync ensureSchema(): Promise<void> {\n\t\tawait applyWebhookMigrations(this.#pool, this.#schema, \"delivery\", DELIVERY_MIGRATIONS);\n\t}\n\n\t#boundary(operation: string): Promise<void> {\n\t\tconst hook = this.#beforeAtomicStep;\n\t\treturn awaitHook(hook === undefined ? undefined : () => hook(operation), \"beforeAtomicStep\");\n\t}\n\n\t#pause(operation: string, stage: WebhookTransactionCheckpointStage): Promise<void> {\n\t\tconst hook = this.#checkpoint;\n\t\treturn awaitHook(hook === undefined ? undefined : () => hook(operation, stage), \"transactionCheckpoint\");\n\t}\n\n\t/**\n\t * One write (`runWrite` in src/postgres-sql.ts). `lock` takes every lock\n\t * and runs every statement that can wait; the clock and the call bounds\n\t * are read only after it returns; `body` decides and finishes.\n\t */\n\tasync #write<L, T>(\n\t\toperation: string,\n\t\tbounds: CallBounds,\n\t\tlock: (tx: WebhookPostgresQueryable) => Promise<L>,\n\t\tbody: (tx: WebhookPostgresQueryable, nowMs: number, locked: L, control: WebhookTransactionControl) => Promise<T>,\n\t): Promise<T> {\n\t\tawait this.#boundary(operation);\n\t\treturn runWrite(this.#pool, this.#clock, bounds, lock, body);\n\t}\n\n\t/**\n\t * The horizon table lock, always the first statement of the transaction\n\t * that takes it, then the highest purge cutoff. While the lock is held the\n\t * cutoff cannot change, so it can be read before the record locks.\n\t */\n\tasync #lockHorizon(tx: WebhookPostgresQueryable, mode: HorizonLock): Promise<number> {\n\t\tawait tx.query(`LOCK TABLE ${this.#t.horizon} IN ${mode === \"share\" ? \"SHARE\" : \"EXCLUSIVE\"} MODE`);\n\t\tconst result = await tx.query(`SELECT purged_through_ms::text AS purged_through_ms FROM ${this.#t.horizon}`);\n\t\tconst row = result.rows[0];\n\t\tif (row === undefined) throw storeError(\"store_failed\", \"horizon\");\n\t\treturn optionalIntOf(row[\"purged_through_ms\"], \"horizon.purged_through_ms\") ?? -Infinity;\n\t}\n\n\t/** The horizon floor at `nowMs`, given the highest purge cutoff read under the horizon lock. */\n\t#floorMs(nowMs: number, purgedThroughMs: number): number {\n\t\treturn mathMax(nowMs - this.#horizonMs, purgedThroughMs);\n\t}\n\n\tasync #read<T>(operation: string, bounds: CallBounds, body: (db: WebhookPostgresQueryable) => Promise<T>): Promise<T> {\n\t\tawait this.#boundary(operation);\n\t\treturn runRead(this.#pool, this.#clock, bounds, (db) => body(db));\n\t}\n\n\tasync #lockJob(tx: WebhookPostgresQueryable, eventId: string, lock: \"UPDATE\" | \"SHARE\"): Promise<JobState | undefined> {\n\t\tconst result = await tx.query(`SELECT ${columns(JOB_COLUMNS)} FROM ${this.#t.jobs} WHERE event_id = $1 FOR ${lock}`, [eventId]);\n\t\treturn result.rows[0] === undefined ? undefined : jobFrom(result.rows[0]);\n\t}\n\n\tasync #lockIntent(tx: WebhookPostgresQueryable, deliveryId: string): Promise<IntentState | undefined> {\n\t\tconst result = await tx.query(`SELECT ${columns(INTENT_COLUMNS)} FROM ${this.#t.intents} WHERE delivery_id = $1 FOR UPDATE`, [deliveryId]);\n\t\treturn result.rows[0] === undefined ? undefined : intentFrom(result.rows[0]);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Fan-out jobs\n\t// -------------------------------------------------------------------------\n\n\tasync insertFanOutJob(\n\t\tjob: WebhookFanOutJobDraft & { readonly processingDeadline: string; readonly createdAt: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookInsertResult> {\n\t\tconst call = readInsertFanOutJobCall(job, options);\n\t\tconst draft = call.job;\n\t\treturn this.#write(\n\t\t\t\"insertFanOutJob\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tawait this.#pause(\"insertFanOutJob\", \"locked\");\n\t\t\t\t// Tentative: the conflict check can wait on a concurrent insert of\n\t\t\t\t// the same eventId, so it runs before the clock is read. The body\n\t\t\t\t// rolls it back if the event turns out past the horizon.\n\t\t\t\tconst inserted = await tx.query(\n\t\t\t\t\t`INSERT INTO ${this.#t.jobs}\n\t\t\t\t\t (event_id, sort_key, tenant_id, space_id, draft, anchor_ms, status, attempt_count,\n\t\t\t\t\t available_at_ms, created_at_ms, processing_deadline_ms, fence)\n\t\t\t\t\t VALUES ($1, $2, $3, $4, $5::json, $6, 'pending', 0, $7, $7, $8, 0)\n\t\t\t\t\t ON CONFLICT (event_id) DO NOTHING RETURNING event_id`,\n\t\t\t\t\t[draft.eventId, utf16SortKey(draft.eventId), draft.tenantId, draft.spaceId, serializeJson(draft.draft), draft.anchorMs, draft.createdAtMs, draft.processingDeadlineMs],\n\t\t\t\t);\n\t\t\t\treturn { purgedThroughMs, inserted: inserted.rows.length === 1 };\n\t\t\t},\n\t\t\tasync (_tx, nowMs, locked, control) => {\n\t\t\t\t// Horizon first, so the answer for an old event does not depend on\n\t\t\t\t// whether a purge has removed its job yet.\n\t\t\t\tif (draft.anchorMs < this.#floorMs(nowMs, locked.purgedThroughMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn copyOut<WebhookInsertResult>({ outcome: \"past_horizon\" });\n\t\t\t\t}\n\t\t\t\tawait this.#pause(\"insertFanOutJob\", \"written\");\n\t\t\t\treturn copyOut<WebhookInsertResult>({ outcome: locked.inserted ? \"inserted\" : \"already_present\" });\n\t\t\t},\n\t\t);\n\t}\n\n\tasync claimFanOutJobs(request: WebhookClaimRequest, options: WebhookCallOptions): Promise<readonly WebhookFanOutJob[]> {\n\t\tconst call = readClaimCall(request, options);\n\t\tconst claim = call.claim;\n\t\treturn this.#write(\n\t\t\t\"claimFanOutJobs\",\n\t\t\tcall.bounds,\n\t\t\t// SKIP LOCKED never waits; it leaves rows another transaction holds.\n\t\t\tasync (tx) => (await tx.query(\n\t\t\t\t`SELECT event_id FROM ${this.#t.jobs}\n\t\t\t\t WHERE status = 'pending' AND available_at_ms <= $1\n\t\t\t\t AND (lease_owner IS NULL OR lease_expires_at_ms <= $1)\n\t\t\t\t ORDER BY available_at_ms, created_at_ms, sort_key\n\t\t\t\t LIMIT $2\n\t\t\t\t FOR UPDATE SKIP LOCKED`,\n\t\t\t\t[claim.nowMs, claim.limit],\n\t\t\t)).rows.map((row) => textOf(row[\"event_id\"], \"row.event_id\")),\n\t\t\tasync (tx, _nowMs, picked) => {\n\t\t\t\tif (picked.length === 0) return frozenList<WebhookFanOutJob>([]);\n\t\t\t\tconst result = await tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.jobs} AS job\n\t\t\t\t\t SET fence = job.fence + 1, lease_owner = $2, lease_expires_at_ms = $3\n\t\t\t\t\t WHERE job.event_id = ANY($1::text[])\n\t\t\t\t\t RETURNING ${columns(JOB_COLUMNS, \"job\")}`,\n\t\t\t\t\t[picked, claim.workerId, claim.nowMs + claim.leaseDurationMs],\n\t\t\t\t);\n\t\t\t\tconst states = claimOrder(result.rows.map(jobFrom));\n\t\t\t\treturn frozenList(states.map((state) => copyOut<WebhookFanOutJob>(jobOut(state))));\n\t\t\t},\n\t\t);\n\t}\n\n\t/**\n\t * A fenced job write: the job is locked `FOR UPDATE` before the clock is\n\t * read; `change` runs only when the caller still holds the lease.\n\t */\n\t#fencedJobWrite(\n\t\toperation: string,\n\t\tbounds: CallBounds,\n\t\teventId: string,\n\t\tfenced: { readonly owner: string; readonly fence: number },\n\t\tchange: (tx: WebhookPostgresQueryable, job: JobState) => Promise<void>,\n\t): Promise<boolean> {\n\t\treturn this.#write(operation, bounds, (tx) => this.#lockJob(tx, eventId, \"UPDATE\"), async (tx, nowMs, job) => {\n\t\t\tif (job === undefined || !holds(job, fenced.owner, fenced.fence, nowMs)) return false;\n\t\t\tawait change(tx, job);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync completeFanOutJob(input: WebhookFencedWrite & { readonly eventId: string }, options: WebhookCallOptions): Promise<boolean> {\n\t\tconst call = readJobFencedCall(input, options);\n\t\treturn this.#fencedJobWrite(\"completeFanOutJob\", call.bounds, call.eventId, call.fenced, async (tx) => {\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t SET status = 'completed', completed_at_ms = $2, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t[call.eventId, call.fenced.nowMs],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync rescheduleFanOutJob(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly availableAt: Date; readonly diagnostic: WebhookDiagnosticCode },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRescheduleCall(input, options);\n\t\treturn this.#fencedJobWrite(\"rescheduleFanOutJob\", call.bounds, call.eventId, call.fenced, async (tx) => {\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t SET attempt_count = attempt_count + 1, available_at_ms = $2, last_diagnostic = $3,\n\t\t\t\t lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t[call.eventId, call.availableAtMs, call.diagnostic],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync renewFanOutJobLease(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly leaseDurationMs: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRenewJobCall(input, options);\n\t\treturn this.#fencedJobWrite(\"renewFanOutJobLease\", call.bounds, call.eventId, call.fenced, async (tx, job) => {\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.jobs} SET lease_expires_at_ms = $2 WHERE event_id = $1`,\n\t\t\t\t[call.eventId, renewedExpiryMs(job, call.fenced.nowMs, call.leaseDurationMs)],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync deadLetterFanOutJob(\n\t\tinput: WebhookFencedWrite & { readonly eventId: string; readonly diagnostic: WebhookDiagnosticCode },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readDeadLetterJobCall(input, options);\n\t\treturn this.#fencedJobWrite(\"deadLetterFanOutJob\", call.bounds, call.eventId, call.fenced, async (tx) => {\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t SET status = 'dead_letter', last_diagnostic = $2, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t[call.eventId, call.diagnostic],\n\t\t\t);\n\t\t});\n\t}\n\n\tasync requeueFanOutJob(\n\t\tinput: WebhookScope & { readonly eventId: string; readonly request: WebhookRequeueRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookRequeueResult> {\n\t\tconst call = readJobRequeueCall(input, options);\n\t\treturn this.#write(\n\t\t\t\"requeueFanOutJob\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst job = await this.#lockJob(tx, call.eventId, \"UPDATE\");\n\t\t\t\tconst prior = await this.#priorEvidence(tx, call.scope, call.request.actionInvocationId, { target: \"fan_out_job\", eventId: call.eventId });\n\t\t\t\tawait this.#pause(\"requeueFanOutJob\", \"locked\");\n\t\t\t\treturn { purgedThroughMs, job, prior };\n\t\t\t},\n\t\t\tasync (tx, nowMs, { purgedThroughMs, job, prior }) => {\n\t\t\t\tif (prior !== undefined) return replayedResult<WebhookRequeueResult>(prior);\n\t\t\t\tif (job === undefined || !inScope(job, call.scope)) return requeueRefused(\"not_found\");\n\t\t\t\tconst refusal = requeueRefusal(job, call.request, this.#floorMs(nowMs, purgedThroughMs));\n\t\t\t\tif (refusal !== undefined) return requeueRefused(refusal);\n\t\t\t\tconst evidence = jobRequeueEvidence(job, call.request, nowMs);\n\t\t\t\tconst result = copyOut<WebhookRequeueResult>({ applied: true, evidence });\n\t\t\t\tapplyRequeue(job, call.request);\n\t\t\t\tawait tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t\t SET status = 'pending', attempt_count = $2, available_at_ms = $3, processing_deadline_ms = $4,\n\t\t\t\t\t fence = $5, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t\t[job.key, job.attemptCount, job.availableAtMs, job.processingDeadlineMs, job.fence],\n\t\t\t\t);\n\t\t\t\tawait this.#appendEvidence(tx, job.key, job.tenantId, job.spaceId, evidence);\n\t\t\t\tawait this.#pause(\"requeueFanOutJob\", \"written\");\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n\tasync enrichFanOutJobActor(\n\t\tinput: WebhookScope & { readonly eventId: string; readonly request: WebhookActorEnrichmentRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookActorEnrichmentResult> {\n\t\tconst call = readJobEnrichmentCall(input, options);\n\t\treturn this.#write(\n\t\t\t\"enrichFanOutJobActor\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst job = await this.#lockJob(tx, call.eventId, \"UPDATE\");\n\t\t\t\tconst prior = await this.#priorEvidence(tx, call.scope, call.request.actionInvocationId, { target: \"fan_out_job_actor\", eventId: call.eventId });\n\t\t\t\tawait this.#pause(\"enrichFanOutJobActor\", \"locked\");\n\t\t\t\treturn { purgedThroughMs, job, prior };\n\t\t\t},\n\t\t\tasync (tx, nowMs, { purgedThroughMs, job, prior }) => {\n\t\t\t\tif (prior !== undefined) return replayedResult<WebhookActorEnrichmentResult>(prior);\n\t\t\t\tif (job === undefined || !inScope(job, call.scope)) return enrichmentRefused(\"not_found\");\n\t\t\t\tconst refusal = enrichmentRefusal(job, call.request, this.#floorMs(nowMs, purgedThroughMs));\n\t\t\t\tif (refusal !== undefined) return enrichmentRefused(refusal);\n\t\t\t\tconst evidence = jobEnrichmentEvidence(job, call.request, nowMs);\n\t\t\t\tconst result = copyOut<WebhookActorEnrichmentResult>({ applied: true, evidence });\n\t\t\t\tapplyEnrichment(job, call.request);\n\t\t\t\tawait tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.jobs}\n\t\t\t\t\t SET draft = $2::json, status = 'pending', attempt_count = $3, available_at_ms = $4, processing_deadline_ms = $5,\n\t\t\t\t\t fence = $6, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t\t WHERE event_id = $1`,\n\t\t\t\t\t[job.key, serializeJson(job.draft), job.attemptCount, job.availableAtMs, job.processingDeadlineMs, job.fence],\n\t\t\t\t);\n\t\t\t\tawait this.#appendEvidence(tx, job.key, job.tenantId, job.spaceId, evidence);\n\t\t\t\tawait this.#pause(\"enrichFanOutJobActor\", \"written\");\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n\n\tasync #appendEvidence(tx: WebhookPostgresQueryable, eventId: string, tenantId: string, spaceId: string, evidence: WebhookRequeueEvidence): Promise<void> {\n\t\tawait tx.query(\n\t\t\t`INSERT INTO ${this.#t.evidence} (event_id, tenant_id, space_id, record, action_invocation_id) VALUES ($1, $2, $3, $4::json, $5)`,\n\t\t\t[eventId, tenantId, spaceId, serializeJson(evidence), evidence.actionInvocationId ?? null],\n\t\t);\n\t}\n\n\t/**\n\t * Evidence `scope` holds under `actionInvocationId` for `target`, or\n\t * `undefined` (always, without an id). Called in a requeue's or\n\t * enrichment's transaction after its record lock: a concurrent request of\n\t * the same invocation that applied holds that lock until it commits, and\n\t * under READ COMMITTED this statement then sees its evidence. See\n\t * \"Re-runs of one invocation\" in src/ports.ts.\n\t */\n\tasync #priorEvidence(tx: WebhookPostgresQueryable, scope: WebhookScope, actionInvocationId: string | undefined, target: InvocationTarget): Promise<Snapshot | undefined> {\n\t\tif (actionInvocationId === undefined) return undefined;\n\t\tconst result = await tx.query(\n\t\t\t`SELECT record::text AS record FROM ${this.#t.evidence}\n\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND action_invocation_id = $3 ORDER BY seq`,\n\t\t\t[scope.tenantId, scope.spaceId, actionInvocationId],\n\t\t);\n\t\treturn priorInvocationEvidence(result.rows.map((row) => jsonOf(row[\"record\"], \"row.record\") as Snapshot), target);\n\t}\n\n\tasync readFanOutJob(input: WebhookScope & { readonly eventId: string }, options: WebhookCallOptions): Promise<WebhookFanOutJob | null> {\n\t\tconst call = readEventCall(input, options);\n\t\treturn this.#read(\"readFanOutJob\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT ${columns(JOB_COLUMNS)} FROM ${this.#t.jobs} WHERE event_id = $1 AND tenant_id = $2 AND space_id = $3`,\n\t\t\t\t[call.eventId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\treturn result.rows[0] === undefined ? null : copyOut<WebhookFanOutJob>(jobOut(jobFrom(result.rows[0])));\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Intents and denials\n\t// -------------------------------------------------------------------------\n\n\tasync insertDeliveryIntent(\n\t\tintent: Omit<WebhookDeliveryIntent, \"status\" | \"attemptCount\" | \"lastOutcome\" | \"lastDiagnostic\" | \"lease\" | \"eventRecordedAt\" | \"fence\">,\n\t\tparent: WebhookFanOutJobFence,\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookFencedInsertResult> {\n\t\tconst call = readInsertIntentCall(intent, parent, options);\n\t\treturn this.#write(\n\t\t\t\"insertDeliveryIntent\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst job = await this.#parentJob(tx, call.parent);\n\t\t\t\tawait this.#pause(\"insertDeliveryIntent\", \"locked\");\n\t\t\t\t// Tentative inserts, only when the clock-free checks pass: the\n\t\t\t\t// tombstone's and the intent's conflict checks can wait on a\n\t\t\t\t// concurrent insert, so they run before the clock is read.\n\t\t\t\tif (job === undefined || !inScope(job, call)) return { purgedThroughMs, job, tombstone: false, inserted: false };\n\t\t\t\tconst tombstone = await this.#insertTombstone(tx, \"intent\", call, job.anchorMs);\n\t\t\t\tconst inserted = tombstone && (await tx.query(\n\t\t\t\t\t`INSERT INTO ${this.#t.intents}\n\t\t\t\t\t (delivery_id, sort_key, subscription_id, event_id, tenant_id, space_id, eligibility_revision, body,\n\t\t\t\t\t anchor_ms, status, attempt_count, available_at_ms, created_at_ms, processing_deadline_ms, fence)\n\t\t\t\t\t VALUES ($1, $2, $3, $4, $5, $6, $7, $8::json, $9, 'pending', 0, $10, $11, $12, 0)\n\t\t\t\t\t ON CONFLICT (delivery_id) DO NOTHING RETURNING delivery_id`,\n\t\t\t\t\t[call.deliveryId, utf16SortKey(call.deliveryId), call.subscriptionId, call.eventId, call.tenantId, call.spaceId,\n\t\t\t\t\t\tcall.eligibilityRevision, serializeJson(call.body), job.anchorMs, call.availableAtMs, call.createdAtMs, call.processingDeadlineMs],\n\t\t\t\t)).rows.length === 1;\n\t\t\t\treturn { purgedThroughMs, job, tombstone, inserted };\n\t\t\t},\n\t\t\tasync (_tx, nowMs, locked, control) => {\n\t\t\t\t// The memory store's order: lease, scope, horizon, uniqueness, deliveryId.\n\t\t\t\tconst job = locked.job;\n\t\t\t\tif (job === undefined) return fencedOutcome(\"lease_lost\");\n\t\t\t\t// Expiry is judged here, on the store's clock read after every lock.\n\t\t\t\tif (!holds(job, call.parent.owner, call.parent.fence, nowMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn fencedOutcome(\"lease_lost\");\n\t\t\t\t}\n\t\t\t\tif (!inScope(job, call)) throw storeError(\"record_mismatch\", \"intent.tenantId\");\n\t\t\t\tif (job.anchorMs < this.#floorMs(nowMs, locked.purgedThroughMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn fencedOutcome(\"past_horizon\");\n\t\t\t\t}\n\t\t\t\tif (!locked.tombstone) return fencedOutcome(\"already_present\");\n\t\t\t\t// The tombstone written above is rolled back with this throw.\n\t\t\t\tif (!locked.inserted) throw storeError(\"delivery_id_conflict\", \"intent.deliveryId\");\n\t\t\t\tawait this.#pause(\"insertDeliveryIntent\", \"written\");\n\t\t\t\treturn fencedOutcome(\"inserted\");\n\t\t\t},\n\t\t);\n\t}\n\n\tasync recordAdmissionDenial(\n\t\trecord: WebhookAdmissionDenialRecord,\n\t\tparent: WebhookFanOutJobFence,\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookFencedInsertResult> {\n\t\tconst call = readDenialCall(record, parent, options);\n\t\treturn this.#write(\n\t\t\t\"recordAdmissionDenial\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst job = await this.#parentJob(tx, call.parent);\n\t\t\t\tawait this.#pause(\"recordAdmissionDenial\", \"locked\");\n\t\t\t\tif (job === undefined || !inScope(job, call)) return { purgedThroughMs, job, tombstone: false };\n\t\t\t\t// Tentative, as in insertDeliveryIntent. Once the tombstone is ours,\n\t\t\t\t// no other transaction can be inserting this pair's denial.\n\t\t\t\tconst tombstone = await this.#insertTombstone(tx, \"denial\", call, job.anchorMs);\n\t\t\t\tif (tombstone) {\n\t\t\t\t\tawait tx.query(\n\t\t\t\t\t\t`INSERT INTO ${this.#t.denials} (subscription_id, event_id, sort_key, tenant_id, space_id, record, anchor_ms)\n\t\t\t\t\t\t VALUES ($1, $2, $3, $4, $5, $6::json, $7)`,\n\t\t\t\t\t\t[call.subscriptionId, call.eventId, utf16SortKey(markerKey(call.subscriptionId, call.eventId)), call.tenantId, call.spaceId,\n\t\t\t\t\t\t\tserializeJson(denialRecord(call)), job.anchorMs],\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\treturn { purgedThroughMs, job, tombstone };\n\t\t\t},\n\t\t\tasync (_tx, nowMs, locked, control) => {\n\t\t\t\tconst job = locked.job;\n\t\t\t\tif (job === undefined) return fencedOutcome(\"lease_lost\");\n\t\t\t\t// Expiry is judged here, on the store's clock read after every lock.\n\t\t\t\tif (!holds(job, call.parent.owner, call.parent.fence, nowMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn fencedOutcome(\"lease_lost\");\n\t\t\t\t}\n\t\t\t\tif (!inScope(job, call)) throw storeError(\"record_mismatch\", \"record.tenantId\");\n\t\t\t\tif (job.anchorMs < this.#floorMs(nowMs, locked.purgedThroughMs)) {\n\t\t\t\t\tcontrol.abandon();\n\t\t\t\t\treturn fencedOutcome(\"past_horizon\");\n\t\t\t\t}\n\t\t\t\tif (!locked.tombstone) return fencedOutcome(\"already_present\");\n\t\t\t\tawait this.#pause(\"recordAdmissionDenial\", \"written\");\n\t\t\t\treturn fencedOutcome(\"inserted\");\n\t\t\t},\n\t\t);\n\t}\n\n\t/**\n\t * The parent job if `fence` still holds its lease, expiry not yet\n\t * judged: that needs the store's clock, which is read only after every\n\t * lock is held, so the insert's body checks it (`holds`) and rolls the\n\t * tentative insert back when the lease has expired. `FOR SHARE` keeps a\n\t * reclaim, a completion or any other update of the job waiting until\n\t * this transaction ends, while other inserts under the same lease proceed.\n\t */\n\tasync #parentJob(tx: WebhookPostgresQueryable, fence: WebhookFanOutJobFence): Promise<JobState | undefined> {\n\t\tconst job = await this.#lockJob(tx, fence.eventId, \"SHARE\");\n\t\treturn job !== undefined && holdsFence(job, fence.owner, fence.fence) ? job : undefined;\n\t}\n\n\t/**\n\t * Insert the (subscriptionId, eventId) tombstone, or report that one\n\t * exists. A concurrent insert of the same pair waits on the primary key\n\t * and then finds it, so of two racing inserts exactly one gets `true`.\n\t */\n\tasync #insertTombstone(\n\t\ttx: WebhookPostgresQueryable,\n\t\tkind: MarkerState[\"kind\"],\n\t\tcall: { readonly subscriptionId: string; readonly eventId: string; readonly tenantId: string; readonly spaceId: string },\n\t\tanchorMs: number,\n\t): Promise<boolean> {\n\t\tconst result = await tx.query(\n\t\t\t`INSERT INTO ${this.#t.tombstones} (subscription_id, event_id, kind, tenant_id, space_id, anchor_ms)\n\t\t\t VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (subscription_id, event_id) DO NOTHING RETURNING event_id`,\n\t\t\t[call.subscriptionId, call.eventId, kind, call.tenantId, call.spaceId, anchorMs],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync claimDeliveryIntents(request: WebhookClaimRequest, options: WebhookCallOptions): Promise<readonly WebhookDeliveryIntent[]> {\n\t\tconst call = readClaimCall(request, options);\n\t\tconst claim = call.claim;\n\t\treturn this.#write(\n\t\t\t\"claimDeliveryIntents\",\n\t\t\tcall.bounds,\n\t\t\t// SKIP LOCKED never waits; it leaves rows another transaction holds.\n\t\t\tasync (tx) => (await tx.query(\n\t\t\t\t`SELECT delivery_id FROM ${this.#t.intents}\n\t\t\t\t WHERE status = 'pending' AND available_at_ms <= $1\n\t\t\t\t AND (lease_owner IS NULL OR lease_expires_at_ms <= $1)\n\t\t\t\t ORDER BY available_at_ms, created_at_ms, sort_key\n\t\t\t\t LIMIT $2\n\t\t\t\t FOR UPDATE SKIP LOCKED`,\n\t\t\t\t[claim.nowMs, claim.limit],\n\t\t\t)).rows.map((row) => textOf(row[\"delivery_id\"], \"row.delivery_id\")),\n\t\t\tasync (tx, _nowMs, picked) => {\n\t\t\t\tif (picked.length === 0) return frozenList<WebhookDeliveryIntent>([]);\n\t\t\t\tconst result = await tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.intents} AS intent\n\t\t\t\t\t SET fence = intent.fence + 1, lease_owner = $2, lease_expires_at_ms = $3\n\t\t\t\t\t WHERE intent.delivery_id = ANY($1::text[])\n\t\t\t\t\t RETURNING ${columns(INTENT_COLUMNS, \"intent\")}`,\n\t\t\t\t\t[picked, claim.workerId, claim.nowMs + claim.leaseDurationMs],\n\t\t\t\t);\n\t\t\t\tconst states = claimOrder(result.rows.map(intentFrom));\n\t\t\t\treturn frozenList(states.map((state) => copyOut<WebhookDeliveryIntent>(intentOut(state))));\n\t\t\t},\n\t\t);\n\t}\n\n\tasync renewDeliveryIntentLease(\n\t\tinput: WebhookFencedWrite & { readonly deliveryId: string; readonly leaseDurationMs: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readRenewIntentCall(input, options);\n\t\t// Locked FOR UPDATE first; whether the caller holds the lease is decided on the store's clock read after the lock.\n\t\treturn this.#write(\"renewDeliveryIntentLease\", call.bounds, (tx) => this.#lockIntent(tx, call.deliveryId), async (tx, nowMs, intent) => {\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.intents} SET lease_expires_at_ms = $2 WHERE delivery_id = $1`,\n\t\t\t\t[intent.key, renewedExpiryMs(intent, call.fenced.nowMs, call.leaseDurationMs)],\n\t\t\t);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync checkDeliveryLease(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly owner: string; readonly fence: number; readonly now: Date },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookDeliveryLeaseCheck> {\n\t\tconst call = readLeaseCheckCall(input, options);\n\t\t// One statement on the pool: it reads the committed current row on the\n\t\t// primary the pool is connected to, and changes nothing.\n\t\treturn this.#read(\"checkDeliveryLease\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(`SELECT ${columns(INTENT_COLUMNS)} FROM ${this.#t.intents} WHERE delivery_id = $1`, [call.deliveryId]);\n\t\t\treturn leaseCheck(result.rows[0] === undefined ? undefined : intentFrom(result.rows[0]), call);\n\t\t});\n\t}\n\n\tasync appendAttempt(input: WebhookFencedWrite & { readonly attempt: WebhookDeliveryAttemptRecord }, options: WebhookCallOptions): Promise<boolean> {\n\t\tconst call = readAppendAttemptCall(input, options);\n\t\treturn this.#write(\"appendAttempt\", call.bounds, (tx) => this.#lockIntent(tx, call.deliveryId), async (tx, nowMs, intent) => {\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tif (call.subscriptionId !== intent.subscriptionId) throw storeError(\"record_mismatch\", \"input.attempt.subscriptionId\");\n\t\t\tif (call.eventId !== intent.eventId) throw storeError(\"record_mismatch\", \"input.attempt.eventId\");\n\t\t\tawait tx.query(\n\t\t\t\t`INSERT INTO ${this.#t.attempts} (delivery_id, tenant_id, space_id, record) VALUES ($1, $2, $3, $4::json)`,\n\t\t\t\t[call.deliveryId, intent.tenantId, intent.spaceId, serializeJson(call.record)],\n\t\t\t);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync beginAttempt(input: WebhookFencedWrite & { readonly attempt: WebhookDeliveryAttemptStart }, options: WebhookCallOptions): Promise<WebhookAttemptBeginResult> {\n\t\tconst call = readBeginAttemptCall(input, options);\n\t\t// Made before the transaction; only its digest is stored.\n\t\tconst receipt = await storeCall(newAttemptReceipt);\n\t\t// The intent row is locked FOR UPDATE first, so a concurrent begin, settle,\n\t\t// cancel or reclaim of this intent waits; lease expiry is then judged on\n\t\t// the store's clock read after the lock. The begun row is keyed by\n\t\t// (delivery_id, fence) and only this lease holder can insert it.\n\t\treturn this.#write(\"beginAttempt\", call.bounds, (tx) => this.#lockIntent(tx, call.deliveryId), async (tx, nowMs, intent) => {\n\t\t\tif (!mayBegin(intent, call.fenced, nowMs)) return beginResult(undefined);\n\t\t\tif (call.subscriptionId !== intent.subscriptionId) throw storeError(\"record_mismatch\", \"input.attempt.subscriptionId\");\n\t\t\tif (call.eventId !== intent.eventId) throw storeError(\"record_mismatch\", \"input.attempt.eventId\");\n\t\t\tconst inserted = await tx.query(\n\t\t\t\t`INSERT INTO ${this.#t.attempts} (delivery_id, tenant_id, space_id, record, fence, receipt_digest) VALUES ($1, $2, $3, $4::json, $5, $6)\n\t\t\t\t ON CONFLICT (delivery_id, fence) WHERE fence IS NOT NULL DO NOTHING RETURNING seq`,\n\t\t\t\t[call.deliveryId, intent.tenantId, intent.spaceId, serializeJson(call.record), call.fenced.fence, receipt.digest],\n\t\t\t);\n\t\t\treturn beginResult(inserted.rows.length === 1 ? receipt.receipt : undefined);\n\t\t});\n\t}\n\n\tasync finishAttempt(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly fence: number; readonly receipt: string; readonly finish: WebhookDeliveryAttemptFinish },\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readFinishAttemptCall(input, options);\n\t\tconst digest = await storeCall(() => attemptReceiptDigest(call.receipt));\n\t\treturn this.#write(\n\t\t\t\"finishAttempt\",\n\t\t\tcall.bounds,\n\t\t\t// Unfenced: it reads only the begun attempt (rows that never change)\n\t\t\t// and never touches the intent row. The outcome insert can wait on a\n\t\t\t// concurrent insert of the same key, so it runs here, before the clock.\n\t\t\tasync (tx) => {\n\t\t\t\tconst begun = await tx.query(\n\t\t\t\t\t`SELECT 1 FROM ${this.#t.attempts}\n\t\t\t\t\t WHERE delivery_id = $1 AND fence = $2 AND tenant_id = $3 AND space_id = $4 AND receipt_digest = $5`,\n\t\t\t\t\t[call.deliveryId, call.fence, call.scope.tenantId, call.scope.spaceId, digest],\n\t\t\t\t);\n\t\t\t\tif (begun.rows.length === 0) return false;\n\t\t\t\tconst inserted = await tx.query(\n\t\t\t\t\t`INSERT INTO ${this.#t.outcomes} (delivery_id, fence, tenant_id, space_id, record) VALUES ($1, $2, $3, $4, $5::json)\n\t\t\t\t\t ON CONFLICT (delivery_id, fence) DO NOTHING RETURNING fence`,\n\t\t\t\t\t[call.deliveryId, call.fence, call.scope.tenantId, call.scope.spaceId, serializeJson(call.record)],\n\t\t\t\t);\n\t\t\t\treturn inserted.rows.length === 1;\n\t\t\t},\n\t\t\tasync (_tx, _nowMs, inserted) => inserted,\n\t\t);\n\t}\n\n\tasync settleDeliveryIntent(\n\t\tinput: Parameters<WebhookDeliveryStore[\"settleDeliveryIntent\"]>[0],\n\t\toptions: WebhookCallOptions,\n\t): Promise<boolean> {\n\t\tconst call = readSettleCall(input, options);\n\t\treturn this.#write(\"settleDeliveryIntent\", call.bounds, (tx) => this.#lockIntent(tx, call.deliveryId), async (tx, nowMs, intent) => {\n\t\t\tif (intent === undefined || !holds(intent, call.fenced.owner, call.fenced.fence, nowMs)) return false;\n\t\t\tapplySettlement(intent, call.settlement);\n\t\t\tawait tx.query(\n\t\t\t\t`UPDATE ${this.#t.intents}\n\t\t\t\t SET status = $2, attempt_count = $3, available_at_ms = $4, last_outcome = $5, last_reason = $6,\n\t\t\t\t last_diagnostic = $7, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t WHERE delivery_id = $1`,\n\t\t\t\t[intent.key, intent.status, intent.attemptCount, intent.availableAtMs, intent.lastOutcome?.outcome ?? null,\n\t\t\t\t\tintent.lastOutcome?.reason ?? null, intent.lastDiagnostic ?? null],\n\t\t\t);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tasync cancelPendingIntents(\n\t\tinput: Parameters<WebhookDeliveryStore[\"cancelPendingIntents\"]>[0],\n\t\toptions: WebhookCallOptions,\n\t): Promise<number> {\n\t\tconst call = readCancelCall(input, options);\n\t\treturn this.#write(\n\t\t\t\"cancelPendingIntents\",\n\t\t\tcall.bounds,\n\t\t\t// Lock every matching pending intent first. A row another transaction\n\t\t\t// settles while this waits is re-checked by PostgreSQL and left out.\n\t\t\tasync (tx) => (await tx.query(\n\t\t\t\t`SELECT delivery_id FROM ${this.#t.intents}\n\t\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 AND status = 'pending' AND eligibility_revision < $4\n\t\t\t\t FOR UPDATE`,\n\t\t\t\t[call.scope.tenantId, call.scope.spaceId, call.subscriptionId, call.beforeRevision],\n\t\t\t)).rows.map((row) => textOf(row[\"delivery_id\"], \"row.delivery_id\")),\n\t\t\tasync (tx, _nowMs, locked) => {\n\t\t\t\tif (locked.length === 0) return 0;\n\t\t\t\tconst result = await tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.intents}\n\t\t\t\t\t SET status = 'cancelled', last_outcome = 'cancelled', last_reason = $2, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t\t WHERE delivery_id = ANY($1::text[]) AND status = 'pending'\n\t\t\t\t\t RETURNING delivery_id`,\n\t\t\t\t\t[locked, call.reason],\n\t\t\t\t);\n\t\t\t\treturn result.rows.length;\n\t\t\t},\n\t\t);\n\t}\n\n\tasync requeueDeliveryIntent(\n\t\tinput: WebhookScope & { readonly deliveryId: string; readonly request: WebhookRequeueRequest },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookRequeueResult> {\n\t\tconst call = readIntentRequeueCall(input, options);\n\t\treturn this.#write(\n\t\t\t\"requeueDeliveryIntent\",\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => {\n\t\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"share\");\n\t\t\t\tconst intent = await this.#lockIntent(tx, call.deliveryId);\n\t\t\t\tconst prior = await this.#priorEvidence(tx, call.scope, call.request.actionInvocationId, { target: \"delivery_intent\", deliveryId: call.deliveryId });\n\t\t\t\tawait this.#pause(\"requeueDeliveryIntent\", \"locked\");\n\t\t\t\treturn { purgedThroughMs, intent, prior };\n\t\t\t},\n\t\t\tasync (tx, nowMs, { purgedThroughMs, intent, prior }) => {\n\t\t\t\tif (prior !== undefined) return replayedResult<WebhookRequeueResult>(prior);\n\t\t\t\tif (intent === undefined || !inScope(intent, call.scope)) return requeueRefused(\"not_found\");\n\t\t\t\tconst refusal = requeueRefusal(intent, call.request, this.#floorMs(nowMs, purgedThroughMs));\n\t\t\t\tif (refusal !== undefined) return requeueRefused(refusal);\n\t\t\t\tconst evidence = intentRequeueEvidence(intent, call.request, nowMs);\n\t\t\t\tconst result = copyOut<WebhookRequeueResult>({ applied: true, evidence });\n\t\t\t\tapplyRequeue(intent, call.request);\n\t\t\t\tawait tx.query(\n\t\t\t\t\t`UPDATE ${this.#t.intents}\n\t\t\t\t\t SET status = 'pending', attempt_count = $2, available_at_ms = $3, processing_deadline_ms = $4,\n\t\t\t\t\t fence = $5, lease_owner = NULL, lease_expires_at_ms = NULL\n\t\t\t\t\t WHERE delivery_id = $1`,\n\t\t\t\t\t[intent.key, intent.attemptCount, intent.availableAtMs, intent.processingDeadlineMs, intent.fence],\n\t\t\t\t);\n\t\t\t\tawait this.#appendEvidence(tx, intent.eventId, intent.tenantId, intent.spaceId, evidence);\n\t\t\t\tawait this.#pause(\"requeueDeliveryIntent\", \"written\");\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n\n\tasync readDeliveryIntent(input: WebhookScope & { readonly deliveryId: string }, options: WebhookCallOptions): Promise<WebhookDeliveryIntent | null> {\n\t\tconst call = readDeliveryCall(input, options);\n\t\treturn this.#read(\"readDeliveryIntent\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT ${columns(INTENT_COLUMNS)} FROM ${this.#t.intents} WHERE delivery_id = $1 AND tenant_id = $2 AND space_id = $3`,\n\t\t\t\t[call.deliveryId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\treturn result.rows[0] === undefined ? null : copyOut<WebhookDeliveryIntent>(intentOut(intentFrom(result.rows[0])));\n\t\t});\n\t}\n\n\tasync listDeliveryAttempts(\n\t\tinput: WebhookScope & { readonly deliveryId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookDeliveryAttemptLogEntry[]> {\n\t\tconst call = readDeliveryCall(input, options);\n\t\treturn this.#read(\"listDeliveryAttempts\", call.bounds, async (db) => {\n\t\t\t// One statement, so the log and the outcomes come from one snapshot.\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT attempt.record::text AS record, attempt.fence::text AS fence, outcome.record::text AS outcome\n\t\t\t\t FROM ${this.#t.attempts} AS attempt\n\t\t\t\t LEFT JOIN ${this.#t.outcomes} AS outcome ON outcome.delivery_id = attempt.delivery_id AND outcome.fence = attempt.fence\n\t\t\t\t WHERE attempt.delivery_id = $1 AND attempt.tenant_id = $2 AND attempt.space_id = $3 ORDER BY attempt.seq`,\n\t\t\t\t[call.deliveryId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\treturn copyOut<readonly WebhookDeliveryAttemptLogEntry[]>(result.rows.map((row) => attemptEntryOut(\n\t\t\t\tjsonOf(row[\"record\"], \"row.record\") as Snapshot,\n\t\t\t\toptionalIntOf(row[\"fence\"], \"row.fence\"),\n\t\t\t\trow[\"outcome\"] === null || row[\"outcome\"] === undefined ? undefined : jsonOf(row[\"outcome\"], \"row.outcome\") as Snapshot,\n\t\t\t)));\n\t\t});\n\t}\n\n\tasync listRequeueEvidence(input: WebhookScope & { readonly eventId: string }, options: WebhookCallOptions): Promise<readonly WebhookRequeueEvidence[]> {\n\t\tconst call = readEventCall(input, options);\n\t\treturn this.#read(\"listRequeueEvidence\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT record::text AS record FROM ${this.#t.evidence}\n\t\t\t\t WHERE event_id = $1 AND tenant_id = $2 AND space_id = $3 ORDER BY seq`,\n\t\t\t\t[call.eventId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\treturn copyOut<readonly WebhookRequeueEvidence[]>(result.rows.map((row) => jsonOf(row[\"record\"], \"row.record\")));\n\t\t});\n\t}\n\n\tasync listInvocationRequeueEvidence(\n\t\tinput: WebhookScope & { readonly actionInvocationId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookRequeueEvidence[]> {\n\t\tconst call = readInvocationEvidenceCall(input, options);\n\t\treturn this.#read(\"listInvocationRequeueEvidence\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT record::text AS record FROM ${this.#t.evidence}\n\t\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND action_invocation_id = $3 ORDER BY seq`,\n\t\t\t\t[call.scope.tenantId, call.scope.spaceId, call.actionInvocationId],\n\t\t\t);\n\t\t\treturn copyOut<readonly WebhookRequeueEvidence[]>(result.rows.map((row) => jsonOf(row[\"record\"], \"row.record\")));\n\t\t});\n\t}\n\n\tasync readTombstone(\n\t\tinput: WebhookScope & { readonly subscriptionId: string; readonly eventId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookTombstone | null> {\n\t\tconst call = readTombstoneCall(input, options);\n\t\treturn this.#read(\"readTombstone\", call.bounds, async (db) => {\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT kind, subscription_id, event_id, tenant_id, space_id, anchor_ms::text AS anchor_ms FROM ${this.#t.tombstones}\n\t\t\t\t WHERE subscription_id = $1 AND event_id = $2 AND tenant_id = $3 AND space_id = $4`,\n\t\t\t\t[call.subscriptionId, call.eventId, call.scope.tenantId, call.scope.spaceId],\n\t\t\t);\n\t\t\tconst row = result.rows[0];\n\t\t\tif (row === undefined) return null;\n\t\t\tconst marker: MarkerState = {\n\t\t\t\tkind: textOf(row[\"kind\"], \"row.kind\") as MarkerState[\"kind\"],\n\t\t\t\tsubscriptionId: textOf(row[\"subscription_id\"], \"row.subscription_id\"),\n\t\t\t\teventId: textOf(row[\"event_id\"], \"row.event_id\"),\n\t\t\t\ttenantId: textOf(row[\"tenant_id\"], \"row.tenant_id\"),\n\t\t\t\tspaceId: textOf(row[\"space_id\"], \"row.space_id\"),\n\t\t\t\tanchorMs: intOf(row[\"anchor_ms\"], \"row.anchor_ms\"),\n\t\t\t};\n\t\t\treturn copyOut<WebhookTombstone>(tombstoneOut(marker, this.#horizonMs));\n\t\t});\n\t}\n\n\tasync purgeExpiredRecords(input: { readonly limit: number }, options: WebhookCallOptions): Promise<WebhookPurgeResult> {\n\t\tconst call = readPurgeCall(input, options);\n\t\treturn this.#write(\"purgeExpiredRecords\", call.bounds, async (tx) => {\n\t\t\tconst purgedThroughMs = await this.#lockHorizon(tx, \"exclusive\");\n\t\t\tawait this.#pause(\"purgeExpiredRecords\", \"locked\");\n\t\t\treturn purgedThroughMs;\n\t\t}, async (tx, nowMs, purgedThroughMs) => {\n\t\t\t// Which records to remove depends on the cutoff, and so on the clock,\n\t\t\t// so the purge cannot lock them before reading it. Its DELETEs can\n\t\t\t// wait on a row lock (a settle or append holding a terminal record);\n\t\t\t// runWrite's check before COMMIT refuses the purge if its signal\n\t\t\t// aborted or its deadline passed meanwhile. A wait only makes the\n\t\t\t// cutoff older than the clock at commit, which removes less, never more.\n\t\t\tconst cutoffMs = this.#floorMs(nowMs, purgedThroughMs);\n\t\t\tconst cutoff = isoOf(cutoffMs);\n\t\t\t// The memory store's candidate order: oldest anchor, then jobs,\n\t\t\t// denials and intents, then key in UTF-16 order. One more than the\n\t\t\t// limit is read, to answer `more`.\n\t\t\tconst candidates = await tx.query(\n\t\t\t\t`SELECT rank, key, subscription_id FROM (\n\t\t\t\t\tSELECT 0 AS rank, event_id AS key, NULL::text AS subscription_id, anchor_ms, sort_key\n\t\t\t\t\tFROM ${this.#t.jobs} WHERE anchor_ms < $1 AND status = ANY($3::text[])\n\t\t\t\t\tUNION ALL\n\t\t\t\t\tSELECT 1, event_id, subscription_id, anchor_ms, sort_key\n\t\t\t\t\tFROM ${this.#t.denials} WHERE anchor_ms < $1\n\t\t\t\t\tUNION ALL\n\t\t\t\t\tSELECT 2, delivery_id, NULL::text, anchor_ms, sort_key\n\t\t\t\t\tFROM ${this.#t.intents} WHERE anchor_ms < $1 AND status = ANY($4::text[])\n\t\t\t\t) AS candidate\n\t\t\t\tORDER BY anchor_ms, rank, sort_key\n\t\t\t\tLIMIT $2`,\n\t\t\t\t[cutoffMs, call.limit + 1, [...TERMINAL_JOB], [...TERMINAL_INTENT]],\n\t\t\t);\n\t\t\tconst take = candidates.rows.length < call.limit ? candidates.rows.length : call.limit;\n\t\t\tconst jobs: string[] = [];\n\t\t\tconst denialSubscriptions: string[] = [];\n\t\t\tconst denialEvents: string[] = [];\n\t\t\tconst intents: string[] = [];\n\t\t\tfor (let index = 0; index < take; index += 1) {\n\t\t\t\tconst row = candidates.rows[index]!;\n\t\t\t\tconst rank = intOf(row[\"rank\"], \"row.rank\");\n\t\t\t\tconst key = textOf(row[\"key\"], \"row.key\");\n\t\t\t\tif (rank === 0) jobs.push(key);\n\t\t\t\telse if (rank === 1) {\n\t\t\t\t\tdenialSubscriptions.push(textOf(row[\"subscription_id\"], \"row.subscription_id\"));\n\t\t\t\t\tdenialEvents.push(key);\n\t\t\t\t} else intents.push(key);\n\t\t\t}\n\t\t\t// Each DELETE repeats the terminal-status condition and the counts\n\t\t\t// are what was deleted. Under the horizon lock no requeue can move a\n\t\t\t// candidate back to pending in between, so they equal the candidate\n\t\t\t// counts; the repeat keeps a pending record from ever being removed.\n\t\t\tconst removed = { fanOutJobs: 0, deliveryIntents: 0, admissionDenials: 0 };\n\t\t\tif (jobs.length > 0) {\n\t\t\t\tconst deleted = await tx.query(\n\t\t\t\t\t`DELETE FROM ${this.#t.jobs} WHERE event_id = ANY($1::text[]) AND status = ANY($2::text[]) RETURNING event_id`,\n\t\t\t\t\t[jobs, [...TERMINAL_JOB]],\n\t\t\t\t);\n\t\t\t\tremoved.fanOutJobs = deleted.rows.length;\n\t\t\t}\n\t\t\tif (denialEvents.length > 0) {\n\t\t\t\tconst deleted = await tx.query(\n\t\t\t\t\t`WITH removed AS (\n\t\t\t\t\t\tDELETE FROM ${this.#t.denials} AS target USING unnest($1::text[], $2::text[]) AS pair(subscription_id, event_id)\n\t\t\t\t\t\tWHERE target.subscription_id = pair.subscription_id AND target.event_id = pair.event_id\n\t\t\t\t\t\tRETURNING target.subscription_id, target.event_id\n\t\t\t\t\t), tombstones AS (\n\t\t\t\t\t\tDELETE FROM ${this.#t.tombstones} AS target USING removed\n\t\t\t\t\t\tWHERE target.subscription_id = removed.subscription_id AND target.event_id = removed.event_id\n\t\t\t\t\t)\n\t\t\t\t\tSELECT count(*)::text AS removed FROM removed`,\n\t\t\t\t\t[denialSubscriptions, denialEvents],\n\t\t\t\t);\n\t\t\t\tremoved.admissionDenials = intOf(deleted.rows[0]?.[\"removed\"], \"row.removed\");\n\t\t\t}\n\t\t\tif (intents.length > 0) {\n\t\t\t\tconst deleted = await tx.query(\n\t\t\t\t\t`WITH removed AS (\n\t\t\t\t\t\tDELETE FROM ${this.#t.intents} WHERE delivery_id = ANY($1::text[]) AND status = ANY($2::text[])\n\t\t\t\t\t\tRETURNING subscription_id, event_id\n\t\t\t\t\t), tombstones AS (\n\t\t\t\t\t\tDELETE FROM ${this.#t.tombstones} AS target USING removed\n\t\t\t\t\t\tWHERE target.subscription_id = removed.subscription_id AND target.event_id = removed.event_id\n\t\t\t\t\t)\n\t\t\t\t\tSELECT count(*)::text AS removed FROM removed`,\n\t\t\t\t\t[intents, [...TERMINAL_INTENT]],\n\t\t\t\t);\n\t\t\t\tremoved.deliveryIntents = intOf(deleted.rows[0]?.[\"removed\"], \"row.removed\");\n\t\t\t}\n\t\t\tconst result = copyOut<WebhookPurgeResult>({ cutoff, removed, more: candidates.rows.length > take });\n\t\t\t// Raise the floor in the same transaction as the removals: once this\n\t\t\t// commits, no insert or requeue can recreate anything below it.\n\t\t\tawait tx.query(`UPDATE ${this.#t.horizon} SET purged_through_ms = $1`, [cutoffMs]);\n\t\t\tawait this.#pause(\"purgeExpiredRecords\", \"written\");\n\t\t\treturn result;\n\t\t});\n\t}\n}\n","import { readHookOption } from \"./delivery-store-core\";\nimport { guard, storeError } from \"./errors\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookConfigurationWriteResult,\n\tWebhookScope,\n\tWebhookSubscriptionStore,\n\tWebhookSubscriptionTransitionInput,\n\tWebhookSubscriptionWriteResult,\n\tWebhookSubscriptionWriter,\n} from \"./ports\";\nimport {\n\tapplyWebhookMigrations,\n\tawaitHook,\n\tintOf,\n\tjsonOf,\n\toptionalIntOf,\n\treadPoolOption,\n\treadSchemaOption,\n\trunRead,\n\trunWrite,\n\ttextOf,\n\ttype WebhookPostgresMigration,\n\ttype WebhookPostgresPool,\n\ttype WebhookPostgresQueryable,\n} from \"./postgres-sql\";\nimport { serializeJson } from \"./snapshot\";\nimport { captureClock, type CallBounds, type CapturedClock } from \"./store-input\";\nimport {\n\tcompareText,\n\tconfigurationOut,\n\tcopyOut,\n\tdecideTransition,\n\tDELETE,\n\tPAUSE,\n\treadChangePatternsCall,\n\treadCreateCall,\n\treadReplaceConfigurationCall,\n\treadRevisionsAtCall,\n\treadStatusChangeCall,\n\treadTargetCall,\n\trefused,\n\tRESUME,\n\trevisionOut,\n\tstatusRevisionChange,\n\ttype RevisionChange,\n\ttype RevisionState,\n\ttype StatusChange,\n\ttype Target,\n} from \"./subscription-store-core\";\nimport type {\n\tWebhookDeliveryConfiguration,\n\tWebhookDeliveryConfigurationInput,\n\tWebhookEligibilityRevision,\n\tWebhookSignatureScheme,\n\tWebhookSubscriptionSnapshot,\n\tWebhookSubscriptionStatus,\n} from \"./types\";\n\n/*\n * PostgreSQL subscription store: the read port and the writer port, like\n * the memory subscription store, with the same input readers and transition\n * rules (src/subscription-store-core.ts). Each write is one READ COMMITTED\n * transaction (`runWrite` in src/postgres-sql.ts) that first locks the\n * subscription's head row with `SELECT ... FOR UPDATE`, then reads the\n * store's clock and refuses an aborted or expired call, then checks the\n * transition against the current revision and appends, and checks the call\n * bounds once more before COMMIT. Two writes to one subscription therefore\n * run one after the other, so of several racing transitions with the same\n * `expectedRevision` exactly one applies. Create inserts the head row with\n * `ON CONFLICT DO NOTHING` before reading the clock (that insert can wait on\n * a racing create), so of two racing creates exactly one applies. A call\n * whose signal aborts or deadline passes while it waits for the head row\n * commits nothing (\"call bounds while waiting for a lock\" in\n * tests/postgres-live.test.ts). Revisions and configuration versions are\n * only ever inserted; `effectiveUntil` is derived from the next revision\n * when read. This store keeps no replay horizon.\n */\n\n/** Options for {@link PostgresWebhookSubscriptionStore}. */\nexport interface PostgresWebhookSubscriptionStoreOptions {\n\t/** The connection pool, for example a `pg.Pool`. The store never ends it. */\n\treadonly pool: WebhookPostgresPool;\n\t/** The store's clock: every revision takes effect at its time (decision 3). */\n\treadonly clock: WebhookClock;\n\t/** The schema the tables live in, default `fabric_webhook_delivery`. It may be the delivery store's schema. */\n\treadonly schema?: string;\n\t/** Test seam, with the memory store's meaning. Leave it unset outside tests. */\n\treadonly beforeAtomicStep?: (operation: string) => Promise<void> | void;\n}\n\ninterface Tables {\n\treadonly subscriptions: string;\n\treadonly revisions: string;\n\treadonly configurations: string;\n}\n\nconst SUBSCRIPTION_MIGRATIONS: readonly WebhookPostgresMigration[] = Object.freeze([{\n\tversion: 1,\n\tname: \"subscription_baseline\",\n\tsql: `\n\t\tCREATE TABLE {{schema}}.webhook_subscriptions (\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tPRIMARY KEY (tenant_id, space_id, subscription_id)\n\t\t);\n\t\tCREATE TABLE {{schema}}.webhook_subscription_revisions (\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tsubscription_id text NOT NULL,\n\t\t\trevision bigint NOT NULL,\n\t\t\tstatus text NOT NULL CHECK (status IN ('active', 'paused', 'deleted')),\n\t\t\tevent_type_patterns json NOT NULL,\n\t\t\teffective_from_ms bigint NOT NULL,\n\t\t\tPRIMARY KEY (tenant_id, space_id, subscription_id, revision),\n\t\t\tFOREIGN KEY (tenant_id, space_id, subscription_id) REFERENCES {{schema}}.webhook_subscriptions\n\t\t);\n\t\tCREATE INDEX webhook_subscription_revisions_at_idx\n\t\t\tON {{schema}}.webhook_subscription_revisions (tenant_id, space_id, effective_from_ms);\n\t\tCREATE TABLE {{schema}}.webhook_subscription_configurations (\n\t\t\ttenant_id text NOT NULL,\n\t\t\tspace_id text NOT NULL,\n\t\t\tsubscription_id text NOT NULL,\n\t\t\tversion bigint NOT NULL,\n\t\t\tdestination_url json NOT NULL,\n\t\t\tsignature_scheme text NOT NULL,\n\t\t\tsecret_ref json NOT NULL,\n\t\t\tPRIMARY KEY (tenant_id, space_id, subscription_id, version),\n\t\t\tFOREIGN KEY (tenant_id, space_id, subscription_id) REFERENCES {{schema}}.webhook_subscriptions\n\t\t);\n\t`,\n}]);\n\nfunction revisionColumns(alias: string): string {\n\treturn `${alias}.revision::text AS revision, ${alias}.status, ${alias}.event_type_patterns::text AS event_type_patterns, ${alias}.effective_from_ms::text AS effective_from_ms`;\n}\n\nfunction configurationColumns(alias: string): string {\n\treturn `${alias}.version::text AS version, ${alias}.destination_url::text AS destination_url, ${alias}.signature_scheme, ${alias}.secret_ref::text AS secret_ref`;\n}\n\ntype Row = Record<string, unknown>;\n\nfunction revisionFrom(row: Row): RevisionState {\n\tconst patterns = jsonOf(row[\"event_type_patterns\"], \"row.event_type_patterns\");\n\tif (!Array.isArray(patterns) || !patterns.every((pattern) => typeof pattern === \"string\")) throw storeError(\"store_failed\", \"row.event_type_patterns\");\n\treturn {\n\t\trevision: intOf(row[\"revision\"], \"row.revision\"),\n\t\tstatus: textOf(row[\"status\"], \"row.status\") as WebhookSubscriptionStatus,\n\t\teventTypePatterns: patterns as string[],\n\t\teffectiveFromMs: intOf(row[\"effective_from_ms\"], \"row.effective_from_ms\"),\n\t};\n}\n\nfunction configurationFrom(target: Target, row: Row): WebhookDeliveryConfiguration {\n\treturn configurationOut(target, intOf(row[\"version\"], \"row.version\"), {\n\t\tdestinationUrl: textOf(jsonOf(row[\"destination_url\"], \"row.destination_url\"), \"row.destination_url\"),\n\t\tsignatureScheme: textOf(row[\"signature_scheme\"], \"row.signature_scheme\") as WebhookSignatureScheme,\n\t\tsecretRef: textOf(jsonOf(row[\"secret_ref\"], \"row.secret_ref\"), \"row.secret_ref\"),\n\t});\n}\n\n/**\n * A PostgreSQL {@link WebhookSubscriptionStore} and {@link WebhookSubscriptionWriter}.\n * Subscriptions are keyed by (tenantId, spaceId, subscriptionId); a read or\n * write in another scope does not see them. Call {@link ensureSchema} once\n * before use.\n *\n * @throws {WebhookStoreError} `clock_invalid` when `clock` has no `now`\n * function; `input_invalid` when `pool`, `schema` or the test seam is not usable.\n */\nexport class PostgresWebhookSubscriptionStore implements WebhookSubscriptionStore, WebhookSubscriptionWriter {\n\treadonly #pool: WebhookPostgresPool;\n\treadonly #clock: CapturedClock;\n\treadonly #schema: string;\n\treadonly #t: Tables;\n\treadonly #beforeAtomicStep: ((operation: string) => Promise<void> | void) | undefined;\n\n\tconstructor(options: PostgresWebhookSubscriptionStoreOptions) {\n\t\tthis.#clock = guard(() => {\n\t\t\tif (options === null || typeof options !== \"object\") throw storeError(\"clock_invalid\", \"clock\");\n\t\t\treturn captureClock(options.clock);\n\t\t}, () => storeError(\"clock_invalid\", \"clock\"));\n\t\tthis.#pool = readPoolOption(options);\n\t\tthis.#schema = readSchemaOption(options);\n\t\tthis.#t = {\n\t\t\tsubscriptions: `${this.#schema}.webhook_subscriptions`,\n\t\t\trevisions: `${this.#schema}.webhook_subscription_revisions`,\n\t\t\tconfigurations: `${this.#schema}.webhook_subscription_configurations`,\n\t\t};\n\t\tthis.#beforeAtomicStep = readHookOption(options, \"beforeAtomicStep\");\n\t}\n\n\t/** Create the schema and tables, or check the applied migrations. Safe to call concurrently and repeatedly. */\n\tasync ensureSchema(): Promise<void> {\n\t\tawait applyWebhookMigrations(this.#pool, this.#schema, \"subscriptions\", SUBSCRIPTION_MIGRATIONS);\n\t}\n\n\t#boundary(operation: string): Promise<void> {\n\t\tconst hook = this.#beforeAtomicStep;\n\t\treturn awaitHook(hook === undefined ? undefined : () => hook(operation), \"beforeAtomicStep\");\n\t}\n\n\tasync #read<T>(operation: string, bounds: CallBounds, body: (db: WebhookPostgresQueryable) => Promise<T>): Promise<T> {\n\t\tawait this.#boundary(operation);\n\t\treturn runRead(this.#pool, this.#clock, bounds, (db) => body(db));\n\t}\n\n\t/** Lock the subscription's head row; `false` when it does not exist in this scope. */\n\tasync #lockHead(tx: WebhookPostgresQueryable, target: Target): Promise<boolean> {\n\t\tconst result = await tx.query(\n\t\t\t`SELECT 1 FROM ${this.#t.subscriptions} WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 FOR UPDATE`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t);\n\t\treturn result.rows.length === 1;\n\t}\n\n\tasync #currentRevision(db: WebhookPostgresQueryable, target: Target): Promise<RevisionState | undefined> {\n\t\tconst result = await db.query(\n\t\t\t`SELECT ${revisionColumns(\"revision\")} FROM ${this.#t.revisions} AS revision\n\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 ORDER BY revision.revision DESC LIMIT 1`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t);\n\t\treturn result.rows[0] === undefined ? undefined : revisionFrom(result.rows[0]);\n\t}\n\n\tasync #currentConfiguration(db: WebhookPostgresQueryable, target: Target): Promise<WebhookDeliveryConfiguration> {\n\t\tconst result = await db.query(\n\t\t\t`SELECT ${configurationColumns(\"configuration\")} FROM ${this.#t.configurations} AS configuration\n\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 ORDER BY configuration.version DESC LIMIT 1`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t);\n\t\tif (result.rows[0] === undefined) throw storeError(\"store_failed\", \"row.configuration\");\n\t\treturn configurationFrom(target, result.rows[0]);\n\t}\n\n\tasync #insertRevision(tx: WebhookPostgresQueryable, target: Target, revision: RevisionState): Promise<void> {\n\t\tawait tx.query(\n\t\t\t`INSERT INTO ${this.#t.revisions} (tenant_id, space_id, subscription_id, revision, status, event_type_patterns, effective_from_ms)\n\t\t\t VALUES ($1, $2, $3, $4, $5, $6::json, $7)`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId, revision.revision, revision.status, serializeJson(revision.eventTypePatterns), revision.effectiveFromMs],\n\t\t);\n\t}\n\n\tasync #insertConfiguration(tx: WebhookPostgresQueryable, target: Target, version: number, configuration: WebhookDeliveryConfigurationInput): Promise<void> {\n\t\tawait tx.query(\n\t\t\t`INSERT INTO ${this.#t.configurations} (tenant_id, space_id, subscription_id, version, destination_url, signature_scheme, secret_ref)\n\t\t\t VALUES ($1, $2, $3, $4, $5::json, $6, $7::json)`,\n\t\t\t[target.tenantId, target.spaceId, target.subscriptionId, version, serializeJson(configuration.destinationUrl), configuration.signatureScheme, serializeJson(configuration.secretRef)],\n\t\t);\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Reads\n\t// -------------------------------------------------------------------------\n\n\tasync listEligibilityRevisions(\n\t\tinput: WebhookScope & { readonly recordedAt: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookEligibilityRevision[]> {\n\t\tconst call = readRevisionsAtCall(input, options);\n\t\treturn this.#read(\"listEligibilityRevisions\", call.bounds, async (db) => {\n\t\t\t// Per subscription, the latest revision in effect at recordedAt\n\t\t\t// (effectiveFrom <= recordedAt), with its successor's start.\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT DISTINCT ON (revision.subscription_id)\n\t\t\t\t\trevision.subscription_id, ${revisionColumns(\"revision\")},\n\t\t\t\t\t(SELECT next.effective_from_ms::text FROM ${this.#t.revisions} AS next\n\t\t\t\t\t WHERE next.tenant_id = revision.tenant_id AND next.space_id = revision.space_id\n\t\t\t\t\t AND next.subscription_id = revision.subscription_id AND next.revision = revision.revision + 1) AS next_from_ms\n\t\t\t\t FROM ${this.#t.revisions} AS revision\n\t\t\t\t WHERE revision.tenant_id = $1 AND revision.space_id = $2 AND revision.effective_from_ms <= $3\n\t\t\t\t ORDER BY revision.subscription_id, revision.revision DESC`,\n\t\t\t\t[call.tenantId, call.spaceId, call.recordedAtMs],\n\t\t\t);\n\t\t\tconst found = result.rows.map((row) => ({\n\t\t\t\ttarget: { tenantId: call.tenantId, spaceId: call.spaceId, subscriptionId: textOf(row[\"subscription_id\"], \"row.subscription_id\") },\n\t\t\t\trevision: revisionFrom(row),\n\t\t\t\tnextFromMs: optionalIntOf(row[\"next_from_ms\"], \"row.next_from_ms\"),\n\t\t\t}))\n\t\t\t\t// Half-open: effectiveFrom <= recordedAt < next.effectiveFrom.\n\t\t\t\t.filter((item) => item.nextFromMs === undefined || call.recordedAtMs < item.nextFromMs)\n\t\t\t\t// The memory store's order (UTF-16 code units), not the database collation.\n\t\t\t\t.sort((left, right) => compareText(left.target.subscriptionId, right.target.subscriptionId));\n\t\t\treturn copyOut<readonly WebhookEligibilityRevision[]>(found.map((item) => revisionOut(item.target, item.revision, item.nextFromMs)));\n\t\t});\n\t}\n\n\tasync readSubscription(\n\t\tinput: WebhookScope & { readonly subscriptionId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionSnapshot | null> {\n\t\tconst call = readTargetCall(input, options);\n\t\treturn this.#read(\"readSubscription\", call.bounds, async (db) => {\n\t\t\tconst target = call.target;\n\t\t\tconst result = await db.query(\n\t\t\t\t// One statement, so the status and the revision it began at are\n\t\t\t\t// read from one snapshot. `status_since` is one past the last\n\t\t\t\t// revision with another status, or 1 (revisions are numbered\n\t\t\t\t// 1, 2, 3 … with no gaps; subscription-store-core.ts,\n\t\t\t\t// `statusSinceRevision`, is the memory store's twin).\n\t\t\t\t`SELECT current_revision.status, current_revision.status_since::text AS status_since,\n\t\t\t\t\t${configurationColumns(\"current_configuration\")}\n\t\t\t\t FROM ${this.#t.subscriptions} AS subscription\n\t\t\t\t CROSS JOIN LATERAL (\n\t\t\t\t\tSELECT latest.status,\n\t\t\t\t\t\tCOALESCE((\n\t\t\t\t\t\t\tSELECT max(prior.revision) FROM ${this.#t.revisions} AS prior\n\t\t\t\t\t\t\tWHERE prior.tenant_id = subscription.tenant_id AND prior.space_id = subscription.space_id\n\t\t\t\t\t\t\t AND prior.subscription_id = subscription.subscription_id AND prior.status <> latest.status\n\t\t\t\t\t\t), 0) + 1 AS status_since\n\t\t\t\t\tFROM (\n\t\t\t\t\t\tSELECT status FROM ${this.#t.revisions} AS revision\n\t\t\t\t\t\tWHERE revision.tenant_id = subscription.tenant_id AND revision.space_id = subscription.space_id\n\t\t\t\t\t\t AND revision.subscription_id = subscription.subscription_id\n\t\t\t\t\t\tORDER BY revision.revision DESC LIMIT 1\n\t\t\t\t\t) AS latest\n\t\t\t\t ) AS current_revision\n\t\t\t\t CROSS JOIN LATERAL (\n\t\t\t\t\tSELECT * FROM ${this.#t.configurations} AS configuration\n\t\t\t\t\tWHERE configuration.tenant_id = subscription.tenant_id AND configuration.space_id = subscription.space_id\n\t\t\t\t\t AND configuration.subscription_id = subscription.subscription_id\n\t\t\t\t\tORDER BY configuration.version DESC LIMIT 1\n\t\t\t\t ) AS current_configuration\n\t\t\t\t WHERE subscription.tenant_id = $1 AND subscription.space_id = $2 AND subscription.subscription_id = $3`,\n\t\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t\t);\n\t\t\tconst row = result.rows[0];\n\t\t\tif (row === undefined) return null;\n\t\t\treturn copyOut<WebhookSubscriptionSnapshot>({\n\t\t\t\tsubscriptionId: target.subscriptionId,\n\t\t\t\ttenantId: target.tenantId,\n\t\t\t\tspaceId: target.spaceId,\n\t\t\t\tstatus: textOf(row[\"status\"], \"row.status\"),\n\t\t\t\tstatusSinceRevision: intOf(row[\"status_since\"], \"row.status_since\"),\n\t\t\t\tconfiguration: configurationFrom(target, row),\n\t\t\t});\n\t\t});\n\t}\n\n\tasync listEligibilityHistory(\n\t\tinput: WebhookScope & { readonly subscriptionId: string },\n\t\toptions: WebhookCallOptions,\n\t): Promise<readonly WebhookEligibilityRevision[]> {\n\t\tconst call = readTargetCall(input, options);\n\t\treturn this.#read(\"listEligibilityHistory\", call.bounds, async (db) => {\n\t\t\tconst target = call.target;\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT ${revisionColumns(\"revision\")} FROM ${this.#t.revisions} AS revision\n\t\t\t\t WHERE tenant_id = $1 AND space_id = $2 AND subscription_id = $3 ORDER BY revision.revision`,\n\t\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t\t);\n\t\t\tconst revisions = result.rows.map(revisionFrom);\n\t\t\treturn copyOut<readonly WebhookEligibilityRevision[]>(revisions.map((revision, index) => revisionOut(target, revision, revisions[index + 1]?.effectiveFromMs)));\n\t\t});\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// Writes\n\t// -------------------------------------------------------------------------\n\n\tasync createSubscription(\n\t\tinput: WebhookScope & {\n\t\t\treadonly subscriptionId: string;\n\t\t\treadonly eventTypePatterns: readonly string[];\n\t\t\treadonly configuration: WebhookDeliveryConfigurationInput;\n\t\t},\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readCreateCall(input, options);\n\t\tawait this.#boundary(\"createSubscription\");\n\t\tconst target = call.target;\n\t\t// The head row is inserted before the clock is read, so the only work\n\t\t// between the clock read and the commit is one statement that writes\n\t\t// revision 1 and configuration version 1 together.\n\t\treturn runWrite(\n\t\t\tthis.#pool,\n\t\t\tthis.#clock,\n\t\t\tcall.bounds,\n\t\t\tasync (tx) => (await tx.query(\n\t\t\t\t`INSERT INTO ${this.#t.subscriptions} (tenant_id, space_id, subscription_id) VALUES ($1, $2, $3)\n\t\t\t\t ON CONFLICT DO NOTHING RETURNING subscription_id`,\n\t\t\t\t[target.tenantId, target.spaceId, target.subscriptionId],\n\t\t\t)).rows.length === 1,\n\t\t\tasync (tx, nowMs, created) => {\n\t\t\t\tif (!created) return refused(\"already_exists\");\n\t\t\t\tconst revision: RevisionState = { revision: 1, status: \"active\", eventTypePatterns: call.patterns, effectiveFromMs: nowMs };\n\t\t\t\tconst configuration = configurationOut(target, 1, call.configuration);\n\t\t\t\tconst result = copyOut<WebhookSubscriptionWriteResult>({ applied: true, revision: revisionOut(target, revision, undefined), configuration });\n\t\t\t\tawait tx.query(\n\t\t\t\t\t`WITH revision AS (\n\t\t\t\t\t\tINSERT INTO ${this.#t.revisions} (tenant_id, space_id, subscription_id, revision, status, event_type_patterns, effective_from_ms)\n\t\t\t\t\t\tVALUES ($1, $2, $3, 1, 'active', $4::json, $5)\n\t\t\t\t\t)\n\t\t\t\t\tINSERT INTO ${this.#t.configurations} (tenant_id, space_id, subscription_id, version, destination_url, signature_scheme, secret_ref)\n\t\t\t\t\tVALUES ($1, $2, $3, 1, $6::json, $7, $8::json)`,\n\t\t\t\t\t[target.tenantId, target.spaceId, target.subscriptionId, serializeJson(call.patterns), nowMs,\n\t\t\t\t\t\tserializeJson(call.configuration.destinationUrl), call.configuration.signatureScheme, serializeJson(call.configuration.secretRef)],\n\t\t\t\t);\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n\n\tasync changeEventTypePatterns(\n\t\tinput: WebhookSubscriptionTransitionInput & { readonly eventTypePatterns: readonly string[] },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readChangePatternsCall(input, options);\n\t\tawait this.#boundary(\"changeEventTypePatterns\");\n\t\treturn this.#transition(call.bounds, call.target, call.expectedRevision, (current) => ({ status: current.status, patterns: call.patterns }));\n\t}\n\n\tasync pauseSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"pauseSubscription\", input, options, PAUSE);\n\t}\n\n\tasync resumeSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"resumeSubscription\", input, options, RESUME);\n\t}\n\n\tasync deleteSubscription(input: WebhookSubscriptionTransitionInput, options: WebhookCallOptions): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn this.#statusChange(\"deleteSubscription\", input, options, DELETE);\n\t}\n\n\tasync replaceDeliveryConfiguration(\n\t\tinput: WebhookScope & { readonly subscriptionId: string; readonly configuration: WebhookDeliveryConfigurationInput; readonly expectedVersion?: number },\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookConfigurationWriteResult> {\n\t\tconst call = readReplaceConfigurationCall(input, options);\n\t\tawait this.#boundary(\"replaceDeliveryConfiguration\");\n\t\tconst target = call.target;\n\t\treturn runWrite(this.#pool, this.#clock, call.bounds, (tx) => this.#lockHead(tx, target), async (tx, _nowMs, exists) => {\n\t\t\tif (!exists) return copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"not_found\" });\n\t\t\tconst revision = await this.#currentRevision(tx, target);\n\t\t\tif (revision === undefined) throw storeError(\"store_failed\", \"row.revision\");\n\t\t\tif (revision.status === \"deleted\") return copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"deleted\" });\n\t\t\tconst current = await this.#currentConfiguration(tx, target);\n\t\t\tif (call.expectedVersion !== undefined && call.expectedVersion !== current.version) {\n\t\t\t\treturn copyOut<WebhookConfigurationWriteResult>({ applied: false, refusal: \"version_conflict\", currentVersion: current.version });\n\t\t\t}\n\t\t\tconst configuration = configurationOut(target, current.version + 1, call.configuration);\n\t\t\tconst result = copyOut<WebhookConfigurationWriteResult>({ applied: true, configuration });\n\t\t\tawait this.#insertConfiguration(tx, target, current.version + 1, call.configuration);\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tasync #statusChange(\n\t\toperation: string,\n\t\tinput: WebhookSubscriptionTransitionInput,\n\t\toptions: WebhookCallOptions,\n\t\tnext: StatusChange,\n\t): Promise<WebhookSubscriptionWriteResult> {\n\t\tconst call = readStatusChangeCall(input, options);\n\t\tawait this.#boundary(operation);\n\t\treturn this.#transition(call.bounds, call.target, call.expectedRevision, statusRevisionChange(next));\n\t}\n\n\t/**\n\t * Append one revision, checked against the current revision. The head\n\t * row is locked and the current revision and configuration are read\n\t * before the clock, so the clock read that stamps `effectiveFrom` is\n\t * followed only by the INSERT and the COMMIT.\n\t */\n\t#transition(bounds: CallBounds, target: Target, expectedRevision: number | undefined, change: RevisionChange): Promise<WebhookSubscriptionWriteResult> {\n\t\treturn runWrite(\n\t\t\tthis.#pool,\n\t\t\tthis.#clock,\n\t\t\tbounds,\n\t\t\tasync (tx) => {\n\t\t\t\tif (!(await this.#lockHead(tx, target))) return undefined;\n\t\t\t\tconst current = await this.#currentRevision(tx, target);\n\t\t\t\tif (current === undefined) throw storeError(\"store_failed\", \"row.revision\");\n\t\t\t\treturn { current, configuration: await this.#currentConfiguration(tx, target) };\n\t\t\t},\n\t\t\tasync (tx, nowMs, locked) => {\n\t\t\t\tconst decision = decideTransition(locked?.current, expectedRevision, nowMs, change);\n\t\t\t\tif (\"refusal\" in decision) return decision.refusal;\n\t\t\t\tconst result = copyOut<WebhookSubscriptionWriteResult>({ applied: true, revision: revisionOut(target, decision.appended, undefined), configuration: locked!.configuration });\n\t\t\t\tawait this.#insertRevision(tx, target, decision.appended);\n\t\t\t\treturn result;\n\t\t\t},\n\t\t);\n\t}\n}\n","import { guard, inputError } from \"./errors\";\nimport {\n\tassertDelaySchedule,\n\tassertJitteredScheduleRepresentable,\n\tassertJitterRatio,\n\tDEFAULT_WEBHOOK_DELIVERY_LIMITS,\n} from \"./limits\";\nimport type { WebhookRandomSource, WebhookRetryDelay } from \"./ports\";\nimport { apply, freeze, isPlainRecord, mathFloor, mathMin, numberIsSafeInteger, primitive, primitiveList, readOwn, type Fail } from \"./snapshot\";\n\n/** Options for {@link createWebhookRetryDelay}. */\nexport interface WebhookRetryDelayOptions {\n\t/** Base delays before attempts 2, 3, ...; defaults to the delivery schedule. The last entry repeats. */\n\treadonly delaysMs?: readonly number[];\n\t/** Jitter as a fraction of the base delay, in `(0, 1]`; defaults to 0.1. */\n\treadonly jitterRatio?: number;\n\t/** Random source in `[0, 1)`. Required so jitter is never hidden process state. */\n\treadonly random: WebhookRandomSource;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/**\n * Build the retry delay port. For the 1-based number of the attempt that just\n * failed, it returns `base + floor(base * jitterRatio * random())`, so a delay\n * lies in `[base, base * (1 + jitterRatio))` and never shortens the schedule.\n * Exhaustion is decided by `maxDeliveryAttempts`, not here. The options are\n * copied at entry into a snapshot, one descriptor read per option, and the\n * schedule copied by index; the port uses only that validated copy.\n *\n * @throws {WebhookDeliveryConfigError} for an empty or non-positive schedule or jitter.\n * @throws {TypeError} `random_source_missing` without a random source, or\n * `input_unreadable` for options that cannot be read.\n *\n * The port throws `RangeError` `attempt_invalid` or `random_sample_invalid`,\n * and `TypeError` `random_source_failed` when the random source throws; the\n * source's exception is dropped unread.\n */\nexport function createWebhookRetryDelay(options: WebhookRetryDelayOptions): WebhookRetryDelay {\n\treturn guard(() => {\n\t\tif (!isPlainRecord(options)) throw unreadable();\n\t\tconst rawDelays = primitiveList(readOwn(options, \"delaysMs\", \"delaysMs\", unreadableFail), \"delaysMs\", unreadableFail);\n\t\tconst rawJitter = primitive(readOwn(options, \"jitterRatio\", \"jitterRatio\", unreadableFail));\n\t\tconst random = readOwn(options, \"random\", \"random\", unreadableFail);\n\t\tconst delaysMs = rawDelays === undefined ? DEFAULT_WEBHOOK_DELIVERY_LIMITS.deliveryRetryDelaysMs : rawDelays;\n\t\tconst jitterRatio = rawJitter === undefined ? DEFAULT_WEBHOOK_DELIVERY_LIMITS.retryJitterRatio : rawJitter;\n\t\tassertDelaySchedule(delaysMs, \"delaysMs\");\n\t\tassertJitterRatio(jitterRatio, \"jitterRatio\");\n\t\tassertJitteredScheduleRepresentable(delaysMs, jitterRatio, \"delaysMs\");\n\t\tif (typeof random !== \"function\") throw inputError(\"type\", \"random_source_missing\");\n\t\tconst delay = (attempt: number): number =>\n\t\t\tguard(() => {\n\t\t\t\tconst value = primitive(attempt);\n\t\t\t\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < 1) throw inputError(\"range\", \"attempt_invalid\");\n\t\t\t\tconst base = delaysMs[mathMin(value, delaysMs.length) - 1]!;\n\t\t\t\tconst sample = apply(random, undefined, []) as unknown;\n\t\t\t\tif (typeof sample !== \"number\" || !(sample >= 0 && sample < 1)) throw inputError(\"range\", \"random_sample_invalid\");\n\t\t\t\treturn base + mathFloor(base * jitterRatio * sample);\n\t\t\t}, () => inputError(\"type\", \"random_source_failed\"));\n\t\treturn freeze(delay);\n\t}, unreadable);\n}\n","import type { WebhookAttemptOutcome, WebhookAttemptReasonCode } from \"./codes\";\nimport { guard, inputError } from \"./errors\";\nimport { assertPositiveFinite } from \"./limits\";\nimport type { WebhookTransportResult } from \"./ports\";\nimport {\n\tdateParse,\n\tisPlainRecord,\n\tmatches,\n\tmathMax,\n\tmathMin,\n\tNumberConstructor,\n\tnumberIsFinite,\n\tnumberIsSafeInteger,\n\tprimitive,\n\treadOwn,\n\trecord,\n\ttimeOf,\n\ttrim,\n\ttype Fail,\n} from \"./snapshot\";\n\n/**\n * Everything decision 10's table classifies: a transport observation that\n * reached the network, or a check that stopped the attempt. A transport\n * `not_sent` result is not here: the dispatcher releases that intent unsent\n * without spending budget.\n */\nexport type WebhookDeliveryObservation =\n\t| Exclude<WebhookTransportResult, { readonly kind: \"not_sent\" }>\n\t| { readonly kind: \"signer_unavailable\" | \"authorization_revoked\" | \"subscription_paused\" | \"subscription_deleted\" };\n\n/** The classified attempt. */\nexport interface WebhookDeliveryClassification {\n\treadonly outcome: WebhookAttemptOutcome;\n\treadonly reason: WebhookAttemptReasonCode;\n\t/** The HTTP status, when a response was received. */\n\treadonly httpStatus?: number;\n\t/**\n\t * For a 429 with a parseable `Retry-After`: the requested delay, clamped\n\t * to `[0, maxRetryAfterMs]`. The dispatcher is expected to schedule the\n\t * later of this and the retry schedule's delay.\n\t */\n\treadonly retryAfterMs?: number;\n\t/**\n\t * `true` for 401 and 403: still `retryable`, but usually needing the\n\t * receiver to act, so the caller surfaces it to operators before the retry\n\t * budget is exhausted.\n\t */\n\treadonly receiverActionLikely?: true;\n}\n\n/** Inputs the classifier needs beyond the observation. */\nexport interface WebhookClassifyOptions {\n\t/** Used to turn an HTTP-date `Retry-After` into a delay. */\n\treadonly now: Date;\n\t/** Upper bound on an honoured `Retry-After`. */\n\treadonly maxRetryAfterMs: number;\n}\n\n/** The classifier options as snapshotted. `nowMs` is `NaN` unless `now` is a real `Date`. */\ninterface OptionsSnapshot {\n\treadonly nowMs: number;\n\treadonly maxRetryAfterMs: number;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/**\n * Classify one attempt by ADR 0018 decision 10:\n *\n * | Observation | Outcome |\n * | --- | --- |\n * | 2xx | `delivered` |\n * | network error, timeout, DNS failure, 408, 425, 429, 5xx, signer unavailable | `retryable` |\n * | 401, 403 | `retryable`, with `receiverActionLikely: true` |\n * | 3xx, 410, other 4xx, invalid URL, private or reserved address | `dead_letter` |\n * | authorization revoked, subscription paused or deleted | `cancelled` |\n *\n * A final 1xx, which the table does not list, is `retryable` (`http_1xx`).\n * The options and the observation are copied into a snapshot at entry,\n * one descriptor read per field; an accessor is refused, not called.\n *\n * @throws {RangeError} `status_out_of_range` for a status that is not a whole number in 100-599.\n * @throws {TypeError} `observation_unknown` for an unknown kind, or\n * `input_unreadable` for an observation or options that cannot be read. The\n * message is constant and never repeats the input.\n * @throws {WebhookDeliveryConfigError} when `maxRetryAfterMs` is not positive and finite.\n */\nexport function classifyWebhookDeliveryObservation(\n\tobservation: WebhookDeliveryObservation,\n\toptions: WebhookClassifyOptions,\n): WebhookDeliveryClassification {\n\treturn guard(() => {\n\t\tconst settings = snapshotOptions(options);\n\t\tif (!isPlainRecord(observation)) throw unreadable();\n\t\tconst kind = primitive(readOwn(observation, \"kind\", \"kind\", unreadableFail));\n\t\tif (kind === \"response\") {\n\t\t\tconst status = primitive(readOwn(observation, \"status\", \"status\", unreadableFail));\n\t\t\tconst retryAfter = primitive(readOwn(observation, \"retryAfter\", \"retryAfter\", unreadableFail));\n\t\t\treturn classifyStatus(status, retryAfter, settings);\n\t\t}\n\t\tswitch (kind) {\n\t\t\tcase \"network_error\":\n\t\t\tcase \"timeout\":\n\t\t\tcase \"dns_failure\":\n\t\t\tcase \"signer_unavailable\":\n\t\t\t\treturn record<WebhookDeliveryClassification>({ outcome: \"retryable\", reason: kind });\n\t\t\tcase \"invalid_url\":\n\t\t\tcase \"private_address\":\n\t\t\t\treturn record<WebhookDeliveryClassification>({ outcome: \"dead_letter\", reason: kind });\n\t\t\tcase \"authorization_revoked\":\n\t\t\tcase \"subscription_paused\":\n\t\t\tcase \"subscription_deleted\":\n\t\t\t\treturn record<WebhookDeliveryClassification>({ outcome: \"cancelled\", reason: kind });\n\t\t\tdefault:\n\t\t\t\tthrow inputError(\"type\", \"observation_unknown\");\n\t\t}\n\t}, unreadable);\n}\n\n/** Snapshot the options and validate the cap. */\nfunction snapshotOptions(options: unknown): OptionsSnapshot {\n\tif (!isPlainRecord(options)) throw unreadable();\n\tconst now = readOwn(options, \"now\", \"now\", unreadableFail);\n\tconst maxRetryAfterMs = primitive(readOwn(options, \"maxRetryAfterMs\", \"maxRetryAfterMs\", unreadableFail));\n\tassertPositiveFinite(maxRetryAfterMs, \"maxRetryAfterMs\");\n\treturn record({ nowMs: timeOf(now), maxRetryAfterMs });\n}\n\nfunction classifyStatus(status: unknown, retryAfter: unknown, settings: OptionsSnapshot): WebhookDeliveryClassification {\n\tif (typeof status !== \"number\" || !numberIsSafeInteger(status) || status < 100 || status > 599) {\n\t\tthrow inputError(\"range\", \"status_out_of_range\");\n\t}\n\tconst httpStatus = status;\n\tconst result = (fields: WebhookDeliveryClassification): WebhookDeliveryClassification => record(fields);\n\tif (status < 200) return result({ outcome: \"retryable\", reason: \"http_1xx\", httpStatus });\n\tif (status < 300) return result({ outcome: \"delivered\", reason: \"http_2xx\", httpStatus });\n\tif (status < 400) return result({ outcome: \"dead_letter\", reason: \"http_3xx\", httpStatus });\n\tif (status >= 500) return result({ outcome: \"retryable\", reason: \"http_5xx\", httpStatus });\n\tswitch (status) {\n\t\tcase 401:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_401\", httpStatus, receiverActionLikely: true });\n\t\tcase 403:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_403\", httpStatus, receiverActionLikely: true });\n\t\tcase 408:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_408\", httpStatus });\n\t\tcase 425:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_425\", httpStatus });\n\t\tcase 429:\n\t\t\treturn result({ outcome: \"retryable\", reason: \"http_429\", httpStatus, retryAfterMs: retryAfterMsFrom(retryAfter, settings) });\n\t\tcase 410:\n\t\t\treturn result({ outcome: \"dead_letter\", reason: \"http_410\", httpStatus });\n\t\tdefault:\n\t\t\treturn result({ outcome: \"dead_letter\", reason: \"http_4xx\", httpStatus });\n\t}\n}\n\nconst IMF_FIXDATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \\d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \\d{4} \\d{2}:\\d{2}:\\d{2} GMT$/;\nconst DELTA_SECONDS = /^\\d+$/;\n\n/**\n * Parse `Retry-After` as delta-seconds or an IMF-fixdate HTTP-date and clamp\n * it to `[0, maxRetryAfterMs]`. An absent or unparseable value returns\n * `undefined`, leaving the retry schedule in charge. The options are\n * snapshotted as {@link classifyWebhookDeliveryObservation} snapshots them.\n *\n * @throws {WebhookDeliveryConfigError} when `maxRetryAfterMs` is not positive and finite.\n * @throws {TypeError} `input_unreadable` for options that cannot be read.\n */\nexport function parseRetryAfterMs(\n\tvalue: string | null | undefined,\n\toptions: WebhookClassifyOptions,\n): number | undefined {\n\treturn guard(() => retryAfterMsFrom(primitive(value), snapshotOptions(options)), unreadable);\n}\n\nfunction retryAfterMsFrom(value: unknown, settings: OptionsSnapshot): number | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst trimmed = trim(value);\n\tif (trimmed === \"\") return undefined;\n\tlet delayMs: number;\n\tif (matches(DELTA_SECONDS, trimmed)) {\n\t\tdelayMs = NumberConstructor(trimmed) * 1000;\n\t} else {\n\t\t// Only the IMF-fixdate form senders must generate (RFC 9110 5.6.7);\n\t\t// Date.parse alone would accept \"-5\" or \"1.5\" as dates.\n\t\tif (!matches(IMF_FIXDATE, trimmed)) return undefined;\n\t\tconst at = dateParse(trimmed);\n\t\tif (!numberIsFinite(at) || !numberIsFinite(settings.nowMs)) return undefined;\n\t\tdelayMs = at - settings.nowMs;\n\t}\n\tif (delayMs !== delayMs) return undefined;\n\treturn mathMin(mathMax(delayMs, 0), settings.maxRetryAfterMs);\n}\n","import type { WebhookProjectionErrorCode } from \"./codes\";\nimport { guard, projectionError } from \"./errors\";\nimport {\n\tdefine,\n\temptyMap,\n\tfreeze,\n\thasOwn,\n\tisoFromDateOrString,\n\tisPlainRecord,\n\tnumberIsSafeInteger,\n\treadOwn,\n\trecord,\n\tsnapshotJson,\n\tstringList,\n\ttype Fail,\n} from \"./snapshot\";\nimport type {\n\tWebhookEventMetadata,\n\tWebhookFanOutJobDraft,\n\tWebhookJobActor,\n\tWebhookJsonObject,\n\tWebhookJsonValue,\n\tWebhookPayloadPolicy,\n\tWebhookSourceEnvelope,\n} from \"./types\";\n\n/** Inputs to {@link projectWebhookFanOutJob}. */\nexport interface WebhookPersistenceProjectionOptions {\n\t/** The application's per-event-type egress allowlist and declared facts. */\n\treadonly policy: WebhookPayloadPolicy;\n\t/**\n\t * The actor Host passed with the envelope, or why it is absent. Defaults to\n\t * `{ state: \"absent\", reason: \"legacy\" }`.\n\t */\n\treadonly actor?: WebhookJobActor;\n}\n\nconst LEGACY_ACTOR: WebhookJobActor = record({ state: \"absent\", reason: \"legacy\" });\n\n/* Fault mapping. Data records (envelope, job, subscription, actor) report\n * accessors as `accessor_property` and anything else as `invalid_envelope`;\n * call and configuration records (options, input, policy) report\n * `inspection_failed`; JSON values report the code of the list naming them. */\n\n/** @internal */\nexport const dataFail: Fail = (fault, field) => {\n\tthrow projectionError(fault === \"accessor\" ? \"accessor_property\" : \"invalid_envelope\", field);\n};\n\n/** @internal */\nexport const callFail: Fail = (_fault, field) => {\n\tthrow projectionError(\"inspection_failed\", field);\n};\n\nfunction jsonFail(code: WebhookProjectionErrorCode): Fail {\n\treturn (fault, field) => {\n\t\tthrow projectionError(fault === \"accessor\" ? \"accessor_property\" : code, field);\n\t};\n}\n\n/** @internal */\nexport const payloadFail = jsonFail(\"payload_field_not_json\");\n/** @internal */\nexport const factFail = jsonFail(\"fact_field_not_json\");\n\n/** @internal Replacement for anything a projection did not throw itself. */\nexport function uninspectable(field: string): () => Error {\n\treturn () => projectionError(\"inspection_failed\", field);\n}\n\n/**\n * The persistence projection (ADR 0018 decision 2). Host copies\n * `event.payload` into the outbox unchanged, so the fan-out job keeps only:\n *\n * - envelope metadata (no trace context, provenance or payload);\n * - the payload fields allowlisted for the event type, when it has an entry;\n * - the payload fields the entry declares as admission and scope facts.\n *\n * A `restricted` event keeps neither payload fields nor facts unless its\n * entry sets `includeRestricted`. Everything else in the payload is dropped\n * before anything is stored, and the package never asks for it. The\n * envelope and options are copied at entry, through own data property\n * descriptors, into a snapshot (a faithful copy for plain data; a Proxy's\n * traps may run more than once, see README, P1); the job is built\n * from the snapshot and is frozen, with null-prototype records.\n *\n * @throws {WebhookProjectionError} when the envelope lacks a required field,\n * a kept field is not JSON or is an accessor, or an input cannot be\n * inspected. The message is constant for the code; no error keeps an input\n * value or an input-raised error.\n */\nexport function projectWebhookFanOutJob(\n\tenvelope: WebhookSourceEnvelope,\n\toptions: WebhookPersistenceProjectionOptions,\n): WebhookFanOutJobDraft {\n\treturn guard(() => fanOutJob(envelope, options), uninspectable(\"envelope\"));\n}\n\n/**\n * Envelope metadata as a serializable record: identifiers, ordering,\n * classification and consistency. Dates become ISO-8601 strings computed\n * with the `Date.prototype` intrinsics. Only own data properties are read.\n * The renderer runs a stored job's metadata through it again.\n *\n * @throws {WebhookProjectionError} for a missing identifier, an invalid\n * date, an accessor property or a value that cannot be inspected.\n */\nexport function projectWebhookEventMetadata(envelope: unknown): WebhookEventMetadata {\n\treturn guard(() => snapshotEventMetadata(envelope), uninspectable(\"envelope\"));\n}\n\nfunction fanOutJob(envelope: unknown, options: unknown): WebhookFanOutJobDraft {\n\t// Snapshot: options, then envelope metadata, then the policy entry and\n\t// actor, then only the payload fields that entry names.\n\tif (!isPlainRecord(options)) return callFail(\"not_plain\", \"options\");\n\tconst policy = readOwn(options, \"policy\", \"policy\", callFail);\n\tconst rawActor = readOwn(options, \"actor\", \"actor\", callFail);\n\tconst event = snapshotEventMetadata(envelope);\n\tconst entry = snapshotPolicyEntry(policy, event.eventType);\n\tconst actor = snapshotActor(rawActor);\n\tconst restrictedWithoutOptIn = event.payloadClassification === \"restricted\" && entry?.includeRestricted !== true;\n\n\tlet payload: WebhookJsonObject | null = null;\n\tlet facts: WebhookJsonObject = EMPTY;\n\tif (entry && !restrictedWithoutOptIn && (entry.fields || entry.facts)) {\n\t\tconst source = readOwn(envelope as object, \"payload\", \"payload\", dataFail);\n\t\tif (isPlainRecord(source)) {\n\t\t\tconst copies = emptyMap<WebhookJsonValue>();\n\t\t\tif (entry.fields) snapshotNamed(source, entry.fields, payloadFail, copies);\n\t\t\tif (entry.facts) snapshotNamed(source, entry.facts, factFail, copies);\n\t\t\tif (entry.fields) payload = pick(copies, entry.fields);\n\t\t\tif (entry.facts) facts = pick(copies, entry.facts);\n\t\t}\n\t}\n\treturn record({\n\t\teventId: event.eventId,\n\t\ttenantId: event.tenantId,\n\t\tspaceId: event.spaceId,\n\t\tevent,\n\t\tpayload,\n\t\tpayloadProjected: payload !== null,\n\t\tfacts,\n\t\tactor,\n\t});\n}\n\nconst EMPTY: WebhookJsonObject = record({});\n\n/** @internal The policy entry for one event type, as a snapshot. */\nexport interface PolicyEntrySnapshot {\n\t/** `undefined` when the entry has no `fields` list. */\n\treadonly fields?: readonly string[];\n\treadonly facts?: readonly string[];\n\treadonly includeRestricted: boolean;\n\treadonly scoped: boolean;\n}\n\n/**\n * @internal Read the entry for `eventType` from a policy, own data\n * properties only. A missing policy or entry, or a non-object entry, is no\n * entry.\n */\nexport function snapshotPolicyEntry(policy: unknown, eventType: string): PolicyEntrySnapshot | undefined {\n\tif (policy === null || policy === undefined || typeof policy !== \"object\") return undefined;\n\tif (!isPlainRecord(policy)) return callFail(\"not_plain\", \"policy\");\n\tconst entry = readOwn(policy, eventType, \"policy\", callFail);\n\tif (entry === null || entry === undefined || typeof entry !== \"object\") return undefined;\n\tif (!isPlainRecord(entry)) return callFail(\"not_plain\", \"policy\");\n\tconst fields = stringList(readOwn(entry, \"fields\", \"policy\", callFail), \"policy\", callFail);\n\tconst facts = stringList(readOwn(entry, \"facts\", \"policy\", callFail), \"policy\", callFail);\n\treturn record({\n\t\tfields,\n\t\tfacts,\n\t\tincludeRestricted: readOwn(entry, \"includeRestricted\", \"policy\", callFail) === true,\n\t\tscoped: readOwn(entry, \"scoped\", \"policy\", callFail) === true,\n\t});\n}\n\n/**\n * @internal Snapshot each named field of `source` into `copies` (absent\n * and `undefined` fields are left out). A name whose value was already\n * copied is not read again. A repeated name whose first read found nothing\n * is read again, so a Proxy source may answer the second read differently;\n * plain data cannot.\n */\nexport function snapshotNamed(source: object, names: readonly string[], fail: Fail, copies: Record<string, WebhookJsonValue>): void {\n\tfor (let index = 0; index < names.length; index += 1) {\n\t\tconst name = names[index]!;\n\t\tif (hasOwn(copies, name)) continue;\n\t\tconst value = readOwn(source, name, name, fail);\n\t\tif (value === undefined) continue;\n\t\tdefine(copies, name, snapshotJson(value, name, fail));\n\t}\n}\n\n/** @internal A frozen null-prototype object of the named copies, in `names` order. */\nexport function pick(copies: Record<string, WebhookJsonValue>, names: readonly string[]): WebhookJsonObject {\n\tconst picked = emptyMap<WebhookJsonValue>();\n\tfor (let index = 0; index < names.length; index += 1) {\n\t\tconst name = names[index]!;\n\t\tif (hasOwn(copies, name) && !hasOwn(picked, name)) define(picked, name, copies[name]);\n\t}\n\treturn freeze(picked);\n}\n\nconst METADATA_KEYS = freeze([\n\t\"eventId\",\n\t\"eventType\",\n\t\"eventSchemaVersion\",\n\t\"tenantId\",\n\t\"spaceId\",\n\t\"subjectType\",\n\t\"subjectId\",\n\t\"sequence\",\n\t\"actionInvocationId\",\n\t\"correlationId\",\n\t\"causationId\",\n\t\"occurredAt\",\n\t\"recordedAt\",\n\t\"producerModuleVersion\",\n\t\"payloadClassification\",\n\t\"consistency\",\n] as const);\n\n/**\n * @internal Snapshot and validate envelope (or stored job) metadata: every\n * metadata field is read with one descriptor read, then checked.\n */\nexport function snapshotEventMetadata(source: unknown): WebhookEventMetadata {\n\tif (source === null || typeof source !== \"object\") return dataFail(\"not_plain\", \"envelope\");\n\tif (!isPlainRecord(source)) return dataFail(\"not_plain\", \"envelope\");\n\tconst raw = emptyMap<unknown>();\n\tfor (let index = 0; index < METADATA_KEYS.length; index += 1) {\n\t\tconst key = METADATA_KEYS[index]!;\n\t\tdefine(raw, key, readOwn(source, key, key, dataFail));\n\t}\n\tconst classification = raw.payloadClassification;\n\tif (classification !== \"public\" && classification !== \"internal\" && classification !== \"confidential\" && classification !== \"restricted\") {\n\t\treturn dataFail(\"not_json\", \"payloadClassification\");\n\t}\n\tconst consistency = raw.consistency;\n\tif (consistency !== undefined && consistency !== \"authoritative-now\" && consistency !== \"provisional-until-reconciled\") {\n\t\treturn dataFail(\"not_json\", \"consistency\");\n\t}\n\treturn record<WebhookEventMetadata>({\n\t\teventId: requireString(raw.eventId, \"eventId\"),\n\t\teventType: requireString(raw.eventType, \"eventType\"),\n\t\teventSchemaVersion: requireInteger(raw.eventSchemaVersion, \"eventSchemaVersion\"),\n\t\ttenantId: requireString(raw.tenantId, \"tenantId\"),\n\t\tspaceId: requireString(raw.spaceId, \"spaceId\"),\n\t\tsubjectType: requireString(raw.subjectType, \"subjectType\"),\n\t\tsubjectId: requireString(raw.subjectId, \"subjectId\"),\n\t\tsequence: requireInteger(raw.sequence, \"sequence\"),\n\t\tactionInvocationId: optionalString(raw.actionInvocationId, \"actionInvocationId\"),\n\t\tcorrelationId: requireString(raw.correlationId, \"correlationId\"),\n\t\tcausationId: optionalString(raw.causationId, \"causationId\"),\n\t\toccurredAt: requireIsoDate(raw.occurredAt, \"occurredAt\"),\n\t\trecordedAt: requireIsoDate(raw.recordedAt, \"recordedAt\"),\n\t\tproducerModuleVersion: requireString(raw.producerModuleVersion, \"producerModuleVersion\"),\n\t\tpayloadClassification: classification,\n\t\tconsistency,\n\t});\n}\n\nfunction snapshotActor(raw: unknown): WebhookJobActor {\n\tif (raw === undefined) return LEGACY_ACTOR;\n\tif (!isPlainRecord(raw)) return dataFail(\"not_plain\", \"actor\");\n\tconst state = readOwn(raw, \"state\", \"actor\", dataFail);\n\tif (state === \"present\") {\n\t\tconst actorId = readOwn(raw, \"actorId\", \"actorId\", dataFail);\n\t\tconst actorType = readOwn(raw, \"actorType\", \"actorType\", dataFail);\n\t\treturn record<WebhookJobActor>({\n\t\t\tstate: \"present\",\n\t\t\tactorId: requireString(actorId, \"actorId\"),\n\t\t\tactorType: requireString(actorType, \"actorType\"),\n\t\t});\n\t}\n\tconst reason = readOwn(raw, \"reason\", \"actor\", dataFail);\n\tif (state !== \"absent\" || (reason !== \"suppressed\" && reason !== \"legacy\")) return dataFail(\"not_json\", \"actor\");\n\treturn record<WebhookJobActor>({ state: \"absent\", reason });\n}\n\n/** @internal */\nexport function requireString(value: unknown, field: string): string {\n\tif (typeof value !== \"string\" || value.length === 0) return dataFail(\"not_json\", field);\n\treturn value;\n}\n\nfunction optionalString(value: unknown, field: string): string | undefined {\n\treturn value === undefined ? undefined : requireString(value, field);\n}\n\nfunction requireInteger(value: unknown, field: string): number {\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value)) return dataFail(\"not_json\", field);\n\treturn value;\n}\n\n/** A real `Date` or a date string, read with the intrinsics; never calls the value's own methods. */\nfunction requireIsoDate(value: unknown, field: string): string {\n\tconst iso = isoFromDateOrString(value);\n\tif (iso === undefined) return dataFail(\"not_json\", field);\n\treturn iso;\n}\n","import { guard, projectionError } from \"./errors\";\nimport {\n\tcallFail,\n\tdataFail,\n\tfactFail,\n\tpayloadFail,\n\tpick,\n\trequireString,\n\tsnapshotEventMetadata,\n\tsnapshotNamed,\n\tsnapshotPolicyEntry,\n\tuninspectable,\n\ttype PolicyEntrySnapshot,\n} from \"./persistence-projection\";\nimport type { WebhookScopeInput, WebhookScopePredicate } from \"./ports\";\nimport { apply, emptyMap, isPlainRecord, readOwn, record, serializeJson } from \"./snapshot\";\nimport type {\n\tWebhookDeliveryBodyV1,\n\tWebhookEventMetadata,\n\tWebhookFanOutJobDraft,\n\tWebhookJsonObject,\n\tWebhookJsonValue,\n\tWebhookPayloadPolicy,\n} from \"./types\";\n\n/** The v1 body's `format` value. Receivers read it from the raw body. */\nexport const WEBHOOK_DELIVERY_FORMAT_V1 = \"fabric.webhook-delivery.v1\" as const;\n\n/** The subscription a body is rendered for. */\nexport interface WebhookEgressSubscription {\n\treadonly subscriptionId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n}\n\n/** Inputs to {@link projectWebhookEgressPayload}. */\nexport interface WebhookEgressProjectionInput {\n\t/** The fan-out job; only what the persistence projection kept can leave. */\n\treadonly job: WebhookFanOutJobDraft;\n\treadonly subscription: WebhookEgressSubscription;\n\t/** The current allowlist; it is re-applied, so a narrowed entry takes effect. */\n\treadonly policy: WebhookPayloadPolicy;\n\t/** Consulted only for event types whose entry sets `scoped`. */\n\treadonly scopePredicate?: WebhookScopePredicate;\n}\n\n/** The payload that may leave for one subscription, and why it is metadata-only when it is. */\nexport interface WebhookEgressPayload {\n\treadonly payload: WebhookJsonObject | null;\n\treadonly payloadProjected: boolean;\n\t/**\n\t * Why the payload was withheld: no allowlist entry, nothing persisted, a\n\t * restricted event without opt-in, or a scoped type whose predicate was\n\t * missing, threw, or did not return `true`.\n\t */\n\treadonly withheld?:\n\t\t| \"no_allowlist_entry\"\n\t\t| \"not_persisted\"\n\t\t| \"restricted\"\n\t\t| \"scope_predicate_missing\"\n\t\t| \"scope_predicate_failed\"\n\t\t| \"scope_predicate_false\";\n}\n\ninterface Egress extends WebhookEgressPayload {\n\treadonly event: WebhookEventMetadata;\n\treadonly subscriptionId: string;\n}\n\ntype Withheld = NonNullable<WebhookEgressPayload[\"withheld\"]>;\n\n/** Everything the egress decision and the renderer use, snapshotted at entry. */\ninterface EgressSnapshot {\n\treadonly event: WebhookEventMetadata;\n\treadonly subscriptionId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly deliveryId?: string;\n\treadonly entry?: PolicyEntrySnapshot;\n\treadonly payloadProjected: boolean;\n\treadonly payloadPersisted: boolean;\n\t/** The entry's fields copied from the stored payload; only when it may leave. */\n\treadonly payload?: WebhookJsonObject;\n\treadonly facts: WebhookJsonObject;\n\treadonly scopePredicate?: WebhookScopePredicate;\n}\n\n/**\n * The egress projection (ADR 0018 decision 9). The payload leaves only when\n * the event type has an allowlist entry, the job persisted a payload, a\n * `restricted` event's entry opted in, and, for a scoped type, the injected\n * predicate returned exactly `true`. Otherwise the body is metadata-only:\n * `payload: null, payloadProjected: false`. The job is treated as input: it\n * is copied at entry, through own data property descriptors, into a\n * snapshot (a faithful copy for plain data; README, P1); its\n * metadata is re-derived and its payload re-copied from that snapshot. The\n * predicate runs after the snapshot is complete and sees frozen copies.\n *\n * @throws {WebhookProjectionError} `scope_mismatch` when the subscription\n * names another tenant or space than the job; other codes when the job or\n * subscription cannot be read safely.\n */\nexport function projectWebhookEgressPayload(input: WebhookEgressProjectionInput): WebhookEgressPayload {\n\treturn guard(() => {\n\t\tconst egress = decideEgress(snapshotEgress(input, false));\n\t\treturn record({ payload: egress.payload, payloadProjected: egress.payloadProjected, withheld: egress.withheld });\n\t}, uninspectable(\"job\"));\n}\n\nconst EMPTY: WebhookJsonObject = record({});\n\nfunction snapshotEgress(input: unknown, withDeliveryId: boolean): EgressSnapshot {\n\tif (!isPlainRecord(input)) return callFail(\"not_plain\", \"input\");\n\tconst job = readOwn(input, \"job\", \"job\", callFail);\n\tconst subscription = readOwn(input, \"subscription\", \"subscription\", callFail);\n\tconst policy = readOwn(input, \"policy\", \"policy\", callFail);\n\tconst scopePredicate = readOwn(input, \"scopePredicate\", \"scopePredicate\", callFail);\n\tconst rawDeliveryId = withDeliveryId ? readOwn(input, \"deliveryId\", \"deliveryId\", callFail) : undefined;\n\n\tif (!isPlainRecord(job)) return dataFail(\"not_plain\", \"job\");\n\tconst event = snapshotEventMetadata(readOwn(job, \"event\", \"event\", dataFail));\n\tif (!isPlainRecord(subscription)) return dataFail(\"not_plain\", \"subscription\");\n\tconst subscriptionId = requireString(readOwn(subscription, \"subscriptionId\", \"subscriptionId\", dataFail), \"subscriptionId\");\n\tconst tenantId = requireString(readOwn(subscription, \"tenantId\", \"tenantId\", dataFail), \"tenantId\");\n\tconst spaceId = requireString(readOwn(subscription, \"spaceId\", \"spaceId\", dataFail), \"spaceId\");\n\tif (tenantId !== event.tenantId || spaceId !== event.spaceId) throw projectionError(\"scope_mismatch\", \"subscription\");\n\tconst deliveryId = withDeliveryId ? requireString(rawDeliveryId, \"deliveryId\") : undefined;\n\n\tconst entry = snapshotPolicyEntry(policy, event.eventType);\n\tlet payloadProjected = false;\n\tlet payloadPersisted = false;\n\tlet payload: WebhookJsonObject | undefined;\n\tlet facts = EMPTY;\n\tif (entry?.fields) {\n\t\tpayloadProjected = readOwn(job, \"payloadProjected\", \"payloadProjected\", dataFail) === true;\n\t\tconst storedPayload = readOwn(job, \"payload\", \"payload\", dataFail);\n\t\tpayloadPersisted = isPlainRecord(storedPayload);\n\t\tconst restricted = event.payloadClassification === \"restricted\" && !entry.includeRestricted;\n\t\tif (payloadProjected && payloadPersisted && !restricted) {\n\t\t\tconst copies = emptyMap<WebhookJsonValue>();\n\t\t\tsnapshotNamed(storedPayload as object, entry.fields, payloadFail, copies);\n\t\t\tpayload = pick(copies, entry.fields);\n\t\t\tif (entry.scoped && entry.facts) {\n\t\t\t\tconst storedFacts = readOwn(job, \"facts\", \"facts\", dataFail);\n\t\t\t\tif (isPlainRecord(storedFacts)) {\n\t\t\t\t\tconst factCopies = emptyMap<WebhookJsonValue>();\n\t\t\t\t\tsnapshotNamed(storedFacts, entry.facts, factFail, factCopies);\n\t\t\t\t\tfacts = pick(factCopies, entry.facts);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn record<EgressSnapshot>({\n\t\tevent,\n\t\tsubscriptionId,\n\t\ttenantId,\n\t\tspaceId,\n\t\tdeliveryId,\n\t\tentry,\n\t\tpayloadProjected,\n\t\tpayloadPersisted,\n\t\tpayload,\n\t\tfacts,\n\t\tscopePredicate: typeof scopePredicate === \"function\" ? (scopePredicate as WebhookScopePredicate) : undefined,\n\t});\n}\n\n/** The egress decision over a snapshot. The scope predicate is the only code it calls. */\nfunction decideEgress(snapshot: EgressSnapshot): Egress {\n\tconst { event, subscriptionId, entry } = snapshot;\n\tconst metadataOnly = (reason: Withheld): Egress => record({ event, subscriptionId, payload: null, payloadProjected: false, withheld: reason });\n\tif (!entry || !entry.fields) return metadataOnly(\"no_allowlist_entry\");\n\tif (!snapshot.payloadProjected || !snapshot.payloadPersisted) return metadataOnly(\"not_persisted\");\n\tif (event.payloadClassification === \"restricted\" && !entry.includeRestricted) return metadataOnly(\"restricted\");\n\tif (entry.scoped) {\n\t\tconst predicate = snapshot.scopePredicate;\n\t\tif (predicate === undefined) return metadataOnly(\"scope_predicate_missing\");\n\t\tconst scopeInput = record<WebhookScopeInput>({\n\t\t\tsubscriptionId,\n\t\t\ttenantId: snapshot.tenantId,\n\t\t\tspaceId: snapshot.spaceId,\n\t\t\tevent,\n\t\t\tfacts: snapshot.facts,\n\t\t});\n\t\tlet admitted: unknown;\n\t\ttry {\n\t\t\tadmitted = apply(predicate, undefined, [scopeInput]);\n\t\t} catch {\n\t\t\t// The thrown value is dropped unread.\n\t\t\treturn metadataOnly(\"scope_predicate_failed\");\n\t\t}\n\t\tif (admitted !== true) return metadataOnly(\"scope_predicate_false\");\n\t}\n\treturn record({ event, subscriptionId, payload: snapshot.payload ?? EMPTY, payloadProjected: true });\n}\n\n/** Inputs to {@link renderWebhookDeliveryBodyV1}. */\nexport interface WebhookRenderInput extends WebhookEgressProjectionInput {\n\treadonly deliveryId: string;\n}\n\n/** A rendered v1 body: the object and the exact string that is stored, signed and sent. */\nexport interface WebhookRenderedBody {\n\treadonly body: WebhookDeliveryBodyV1;\n\treadonly rawBody: string;\n\treadonly withheld?: WebhookEgressPayload[\"withheld\"];\n}\n\n/**\n * Render the `fabric.webhook-delivery.v1` body (ADR 0018 decision 7) in the\n * ADR's field order. `consistency` appears only for provisional events;\n * `actionInvocationId` only when the event has one. The body names no\n * eligibility revision, configuration version or actor. Every value in it\n * comes from the input's snapshot (see {@link projectWebhookEgressPayload}),\n * and `rawBody` is serialized by the package from that snapshot, so no\n * `toJSON`, getter or prototype member of any object takes part.\n */\nexport function renderWebhookDeliveryBodyV1(input: WebhookRenderInput): WebhookRenderedBody {\n\treturn guard(() => {\n\t\tconst snapshot = snapshotEgress(input, true);\n\t\tconst projected = decideEgress(snapshot);\n\t\tconst { event } = projected;\n\t\tconst body = record<WebhookDeliveryBodyV1>({\n\t\t\tformat: WEBHOOK_DELIVERY_FORMAT_V1,\n\t\t\teventId: event.eventId,\n\t\t\ttype: event.eventType,\n\t\t\ttenantId: event.tenantId,\n\t\t\tspaceId: event.spaceId,\n\t\t\tcorrelationId: event.correlationId,\n\t\t\toccurredAt: event.occurredAt,\n\t\t\tevent: record<WebhookDeliveryBodyV1[\"event\"]>({\n\t\t\t\ttype: event.eventType,\n\t\t\t\tschemaVersion: event.eventSchemaVersion,\n\t\t\t\tsubjectType: event.subjectType,\n\t\t\t\tsubjectId: event.subjectId,\n\t\t\t\tsequence: event.sequence,\n\t\t\t\trecordedAt: event.recordedAt,\n\t\t\t\tactionInvocationId: event.actionInvocationId,\n\t\t\t\tconsistency: event.consistency === \"provisional-until-reconciled\" ? event.consistency : undefined,\n\t\t\t\tpayload: projected.payload,\n\t\t\t\tpayloadProjected: projected.payloadProjected,\n\t\t\t}),\n\t\t\tdelivery: record({\n\t\t\t\tdeliveryId: snapshot.deliveryId!,\n\t\t\t\tsubscriptionId: projected.subscriptionId,\n\t\t\t}),\n\t\t});\n\t\treturn record({ body, rawBody: serializeJson(body), withheld: projected.withheld });\n\t}, uninspectable(\"job\"));\n}\n","import { guard, inputError } from \"./errors\";\nimport { isPlainRecord, matches, numberIsSafeInteger, primitive, readOwn, record, type Fail } from \"./snapshot\";\n\n/** Header names of a v1 delivery (ADR 0018 decision 7). Only the signature and timestamp are signed. */\nexport const WEBHOOK_HEADERS = Object.freeze({\n\tsignature: \"X-Fabric-Signature\",\n\ttimestamp: \"X-Fabric-Timestamp\",\n\teventId: \"X-Fabric-Event-Id\",\n\tdeliveryId: \"X-Fabric-Delivery-Id\",\n\tattempt: \"X-Fabric-Delivery-Attempt\",\n\tcontentType: \"Content-Type\",\n} as const);\n\nconst V1_SIGNATURE = /^v1=[0-9a-f]{64}$/;\n\n/**\n * A header-safe identifier: visible ASCII, inner spaces allowed, no CR, LF,\n * NUL or other control characters, and no leading or trailing space (which a\n * receiver's header parser would trim, making the header disagree with the\n * signed body).\n */\nconst HEADER_SAFE_ID = /^[\\x21-\\x7e](?:[\\x20-\\x7e]*[\\x21-\\x7e])?$/;\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/**\n * The exact string a `v1` signer MACs: `\"<timestampSeconds>.<rawBody>\"`. The\n * signature is `v1=` + hex(HMAC-SHA256(secret, this string as UTF-8)).\n *\n * @throws {RangeError} `timestamp_invalid` when the timestamp is not a\n * non-negative whole number of seconds.\n * @throws {TypeError} `raw_body_not_string` when the body is not a string.\n */\nexport function webhookSignedContentV1(timestampSeconds: number, rawBody: string): string {\n\treturn guard(() => {\n\t\tconst timestamp = primitive(timestampSeconds);\n\t\tconst body = primitive(rawBody);\n\t\tassertTimestampSeconds(timestamp);\n\t\tif (typeof body !== \"string\") throw inputError(\"type\", \"raw_body_not_string\");\n\t\treturn `${timestamp}.${body}`;\n\t}, unreadable);\n}\n\n/** Inputs to {@link buildWebhookRequestHeaders}. */\nexport interface WebhookRequestHeaderInput {\n\t/** The signer's `v1=<64 lowercase hex>` value. */\n\treadonly signature: string;\n\treadonly timestampSeconds: number;\n\treadonly eventId: string;\n\treadonly deliveryId: string;\n\t/** 1-based attempt number. */\n\treadonly attempt: number;\n}\n\n/**\n * Build the headers of one attempt. A signature that is not a well-formed\n * `v1` value is refused rather than sent, so a misbehaving signer cannot put\n * arbitrary text on the wire. The input is copied at entry into a snapshot,\n * one descriptor read per field (an accessor is refused, not called); the\n * headers are built from the snapshot values that were validated, never\n * from a second read.\n *\n * @throws {TypeError | RangeError} with a constant message and a `code` from\n * `WEBHOOK_INPUT_ERROR_CODES` for a malformed signature, timestamp,\n * identifier or attempt, or an input that cannot be read.\n */\nexport function buildWebhookRequestHeaders(input: WebhookRequestHeaderInput): Readonly<Record<string, string>> {\n\treturn guard(() => {\n\t\tif (!isPlainRecord(input)) throw unreadable();\n\t\tconst signature = primitive(readOwn(input, \"signature\", \"signature\", unreadableFail));\n\t\tconst timestampSeconds = primitive(readOwn(input, \"timestampSeconds\", \"timestampSeconds\", unreadableFail));\n\t\tconst eventId = primitive(readOwn(input, \"eventId\", \"eventId\", unreadableFail));\n\t\tconst deliveryId = primitive(readOwn(input, \"deliveryId\", \"deliveryId\", unreadableFail));\n\t\tconst attempt = primitive(readOwn(input, \"attempt\", \"attempt\", unreadableFail));\n\n\t\tif (typeof signature !== \"string\" || !matches(V1_SIGNATURE, signature)) throw inputError(\"type\", \"signature_malformed\");\n\t\tassertTimestampSeconds(timestampSeconds);\n\t\tif (typeof eventId !== \"string\" || !matches(HEADER_SAFE_ID, eventId)) throw inputError(\"type\", \"event_id_invalid\");\n\t\tif (typeof deliveryId !== \"string\" || !matches(HEADER_SAFE_ID, deliveryId)) throw inputError(\"type\", \"delivery_id_invalid\");\n\t\tif (typeof attempt !== \"number\" || !numberIsSafeInteger(attempt) || attempt < 1) throw inputError(\"range\", \"attempt_invalid\");\n\t\treturn record<Record<string, string>>({\n\t\t\t[WEBHOOK_HEADERS.contentType]: \"application/json\",\n\t\t\t[WEBHOOK_HEADERS.signature]: signature,\n\t\t\t[WEBHOOK_HEADERS.timestamp]: `${timestampSeconds}`,\n\t\t\t[WEBHOOK_HEADERS.eventId]: eventId,\n\t\t\t[WEBHOOK_HEADERS.deliveryId]: deliveryId,\n\t\t\t[WEBHOOK_HEADERS.attempt]: `${attempt}`,\n\t\t});\n\t}, unreadable);\n}\n\nfunction assertTimestampSeconds(value: unknown): asserts value is number {\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < 0) throw inputError(\"range\", \"timestamp_invalid\");\n}\n","import { apply, freeze, matches } from \"./snapshot\";\n\n/*\n * Which IP addresses a webhook may be sent to (ADR 0018 decision 6, R8).\n * Portable: no Node built-ins, so the main entry stays runtime-neutral.\n *\n * IPv4 is a deny list of every special-purpose block IANA marks as not\n * globally reachable, plus multicast and the reserved 240/4. IPv6 is an\n * allow list: only global unicast (2000::/3) can pass, so any block outside\n * it (unspecified, loopback, IPv4-mapped, IPv4-compatible, SIIT, the\n * local-use NAT64 prefix, discard-only, SRv6, unique-local, site-local,\n * link-local, multicast) is refused without being listed. Inside 2000::/3 the\n * non-global blocks are refused, and the three that embed an IPv4 address\n * (NAT64 well-known prefix, 6to4, Teredo) pass only when every embedded\n * address is itself public.\n */\n\nconst stringCharCodeAt = String.prototype.charCodeAt;\nconst stringIndexOf = String.prototype.indexOf;\nconst stringSlice = String.prototype.slice;\nconst stringSplit = String.prototype.split;\n\n/** Longest address text parsed: a full IPv6 form with an embedded IPv4 tail is 45 characters. */\nconst MAX_ADDRESS_LENGTH = 45;\n/** Longest text inspected at all, leaving room for a zone index. */\nconst MAX_TEXT_LENGTH = 64;\n\nconst IPV4_OCTET = \"(?:25[0-5]|2[0-4]\\\\d|1\\\\d\\\\d|[1-9]?\\\\d)\";\n/** Canonical dotted-quad only: no leading zeros, no shorthand, no hex. */\nconst IPV4_DOTTED = new RegExp(`^${IPV4_OCTET}(?:\\\\.${IPV4_OCTET}){3}$`);\nconst HEX_GROUP = /^[0-9A-Fa-f]{1,4}$/;\n\n/** An IPv4 block: network address as an unsigned 32-bit integer and prefix length. */\ninterface Ipv4Block {\n\treadonly base: number;\n\treadonly prefix: number;\n}\n\nfunction ipv4Block(a: number, b: number, c: number, d: number, prefix: number): Ipv4Block {\n\treturn freeze({ base: (((a << 24) | (b << 16) | (c << 8) | d) >>> 0), prefix });\n}\n\n/**\n * IPv4 blocks that are never a webhook destination. The IANA IPv4\n * Special-Purpose Address Registry's not-globally-reachable entries, plus\n * multicast (224.0.0.0/4) and reserved space (240.0.0.0/4, which holds the\n * limited broadcast address). 192.0.0.0/24 is refused whole, including the\n * two anycast /32s in it that IANA marks reachable; neither is a webhook\n * receiver.\n */\nconst REFUSED_IPV4_BLOCKS: readonly Ipv4Block[] = freeze([\n\tipv4Block(0, 0, 0, 0, 8), // \"this network\", including the unspecified 0.0.0.0\n\tipv4Block(10, 0, 0, 0, 8), // private\n\tipv4Block(100, 64, 0, 0, 10), // shared address space (CGNAT)\n\tipv4Block(127, 0, 0, 0, 8), // loopback\n\tipv4Block(169, 254, 0, 0, 16), // link-local, including cloud metadata endpoints\n\tipv4Block(172, 16, 0, 0, 12), // private\n\tipv4Block(192, 0, 0, 0, 24), // IETF protocol assignments\n\tipv4Block(192, 0, 2, 0, 24), // documentation (TEST-NET-1)\n\tipv4Block(192, 88, 99, 0, 24), // deprecated 6to4 relay anycast\n\tipv4Block(192, 168, 0, 0, 16), // private\n\tipv4Block(198, 18, 0, 0, 15), // benchmarking\n\tipv4Block(198, 51, 100, 0, 24), // documentation (TEST-NET-2)\n\tipv4Block(203, 0, 113, 0, 24), // documentation (TEST-NET-3)\n\tipv4Block(224, 0, 0, 0, 4), // multicast\n\tipv4Block(240, 0, 0, 0, 4), // reserved, including 255.255.255.255\n]);\n\nfunction inIpv4Block(value: number, block: Ipv4Block): boolean {\n\tconst mask = block.prefix === 0 ? 0 : (0xffffffff << (32 - block.prefix)) >>> 0;\n\treturn ((value & mask) >>> 0) === block.base;\n}\n\n/** `true` when an IPv4 address, as an unsigned 32-bit integer, is publicly routable. */\nfunction isPublicIpv4Value(value: number): boolean {\n\tfor (let index = 0; index < REFUSED_IPV4_BLOCKS.length; index += 1) {\n\t\tif (inIpv4Block(value, REFUSED_IPV4_BLOCKS[index]!)) return false;\n\t}\n\treturn true;\n}\n\n/** Parse a canonical dotted-quad to an unsigned 32-bit integer, or `undefined`. */\nfunction parseIpv4(text: string): number | undefined {\n\tif (!matches(IPV4_DOTTED, text)) return undefined;\n\tconst parts = apply(stringSplit, text, [\".\"]) as string[];\n\tlet value = 0;\n\tfor (let index = 0; index < 4; index += 1) value = value * 256 + decimal(parts[index]!);\n\treturn value >>> 0;\n}\n\nfunction decimal(text: string): number {\n\tlet value = 0;\n\tfor (let index = 0; index < text.length; index += 1) value = value * 10 + ((apply(stringCharCodeAt, text, [index]) as number) - 48);\n\treturn value;\n}\n\nfunction hex(text: string): number {\n\tlet value = 0;\n\tfor (let index = 0; index < text.length; index += 1) {\n\t\tconst code = apply(stringCharCodeAt, text, [index]) as number;\n\t\tconst digit = code <= 57 ? code - 48 : code <= 70 ? code - 55 : code - 87;\n\t\tvalue = value * 16 + digit;\n\t}\n\treturn value;\n}\n\n/** Parse one side of an IPv6 address (no `::`) into 16-bit words; `tailIpv4` allows a dotted last group. */\nfunction parseIpv6Groups(text: string, tailIpv4: boolean): number[] | undefined {\n\tconst words: number[] = [];\n\tif (text === \"\") return words;\n\tconst groups = apply(stringSplit, text, [\":\"]) as string[];\n\tfor (let index = 0; index < groups.length; index += 1) {\n\t\tconst group = groups[index]!;\n\t\tif (tailIpv4 && index === groups.length - 1 && (apply(stringIndexOf, group, [\".\"]) as number) !== -1) {\n\t\t\tconst v4 = parseIpv4(group);\n\t\t\tif (v4 === undefined) return undefined;\n\t\t\twords[words.length] = v4 >>> 16;\n\t\t\twords[words.length] = v4 & 0xffff;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!matches(HEX_GROUP, group)) return undefined;\n\t\twords[words.length] = hex(group);\n\t}\n\treturn words;\n}\n\n/** Parse an IPv6 address (no brackets, no zone) into eight 16-bit words, or `undefined`. */\nfunction parseIpv6(text: string): number[] | undefined {\n\tconst gap = apply(stringIndexOf, text, [\"::\"]) as number;\n\tif (gap === -1) {\n\t\tconst words = parseIpv6Groups(text, true);\n\t\treturn words !== undefined && words.length === 8 ? words : undefined;\n\t}\n\tif ((apply(stringIndexOf, text, [\"::\", gap + 1]) as number) !== -1) return undefined;\n\tconst head = parseIpv6Groups(apply(stringSlice, text, [0, gap]) as string, false);\n\tconst tail = parseIpv6Groups(apply(stringSlice, text, [gap + 2]) as string, true);\n\tif (head === undefined || tail === undefined || head.length + tail.length > 7) return undefined;\n\tconst words: number[] = [];\n\tfor (let index = 0; index < head.length; index += 1) words[words.length] = head[index]!;\n\tfor (let index = head.length + tail.length; index < 8; index += 1) words[words.length] = 0;\n\tfor (let index = 0; index < tail.length; index += 1) words[words.length] = tail[index]!;\n\treturn words;\n}\n\n/** The IPv4 address held in two consecutive 16-bit words. */\nfunction embeddedIpv4(high: number, low: number): number {\n\treturn ((high << 16) | low) >>> 0;\n}\n\n/** `true` when an IPv6 address, as eight 16-bit words, is publicly routable. */\nfunction isPublicIpv6Words(w: readonly number[]): boolean {\n\t// NAT64 well-known prefix 64:ff9b::/96 (RFC 6052): public only when the\n\t// IPv4 address in its last 32 bits is. The local-use prefix\n\t// 64:ff9b:1::/48 (RFC 8215) is outside 2000::/3 and refused below: the\n\t// operator picks the prefix length inside it, so the embedded address\n\t// cannot be decoded from the address alone.\n\tif (w[0] === 0x0064 && w[1] === 0xff9b && w[2] === 0 && w[3] === 0 && w[4] === 0 && w[5] === 0) {\n\t\treturn isPublicIpv4Value(embeddedIpv4(w[6]!, w[7]!));\n\t}\n\t// Only global unicast can pass.\n\tif ((w[0]! & 0xe000) !== 0x2000) return false;\n\tif (w[0] === 0x2001 && (w[1]! & 0xfe00) === 0) {\n\t\t// 2001::/23, IETF protocol assignments. Teredo (2001::/32, RFC 4380)\n\t\t// carries its server's IPv4 address in words 2-3 and its client's,\n\t\t// bit-inverted, in words 6-7; both must be public. The rest of the /23\n\t\t// (benchmarking, ORCHID, AMT, AS112 and later assignments) is not a\n\t\t// webhook destination.\n\t\tif (w[1] !== 0) return false;\n\t\tconst server = embeddedIpv4(w[2]!, w[3]!);\n\t\tconst client = (~embeddedIpv4(w[6]!, w[7]!)) >>> 0;\n\t\treturn isPublicIpv4Value(server) && isPublicIpv4Value(client);\n\t}\n\tif (w[0] === 0x2001 && w[1] === 0x0db8) return false; // documentation, 2001:db8::/32\n\tif (w[0] === 0x3fff && (w[1]! & 0xf000) === 0) return false; // documentation, 3fff::/20 (RFC 9637)\n\t// 6to4 (2002::/16, RFC 3056): the IPv4 address in words 1-2 must be public.\n\tif (w[0] === 0x2002) return isPublicIpv4Value(embeddedIpv4(w[1]!, w[2]!));\n\treturn true;\n}\n\n/** RFC 5952 text for eight 16-bit words: lowercase, no leading zeros, the longest zero run of two or more compressed. */\nfunction formatIpv6(w: readonly number[]): string {\n\tlet bestStart = -1;\n\tlet bestLength = 0;\n\tfor (let index = 0; index < 8; ) {\n\t\tif (w[index] !== 0) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tlet end = index;\n\t\twhile (end < 8 && w[end] === 0) end += 1;\n\t\tif (end - index > bestLength) {\n\t\t\tbestStart = index;\n\t\t\tbestLength = end - index;\n\t\t}\n\t\tindex = end;\n\t}\n\tif (bestLength < 2) bestStart = -1;\n\tlet text = \"\";\n\tfor (let index = 0; index < 8; index += 1) {\n\t\tif (index === bestStart) {\n\t\t\ttext += \"::\";\n\t\t\tindex += bestLength - 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (text !== \"\" && !endsWithColons(text)) text += \":\";\n\t\ttext += hexText(w[index]!);\n\t}\n\treturn text;\n}\n\nfunction endsWithColons(text: string): boolean {\n\treturn text.length >= 2 && (apply(stringSlice, text, [-2]) as string) === \"::\";\n}\n\nconst HEX_DIGITS = \"0123456789abcdef\";\n\nfunction hexText(value: number): string {\n\tif (value === 0) return \"0\";\n\tlet text = \"\";\n\tfor (let rest = value; rest > 0; rest = (rest - (rest % 16)) / 16) text = HEX_DIGITS[rest % 16]! + text;\n\treturn text;\n}\n\nfunction formatIpv4(value: number): string {\n\treturn `${value >>> 24}.${(value >>> 16) & 0xff}.${(value >>> 8) & 0xff}.${value & 0xff}`;\n}\n\n/**\n * @internal What one textual IP address is, for the destination rules.\n * `malformed` is anything that is not a canonical dotted-quad or a valid\n * IPv6 address; a zone index (`%eth0`) makes an address `non_public`, since\n * only link-scoped addresses carry one.\n */\nexport type WebhookAddressVerdict =\n\t| { readonly kind: \"public\"; readonly address: string; readonly family: 4 | 6 }\n\t| { readonly kind: \"non_public\"; readonly family: 4 | 6 }\n\t| { readonly kind: \"malformed\" };\n\nconst NON_PUBLIC_V4: WebhookAddressVerdict = freeze({ kind: \"non_public\", family: 4 });\nconst NON_PUBLIC_V6: WebhookAddressVerdict = freeze({ kind: \"non_public\", family: 6 });\nconst MALFORMED: WebhookAddressVerdict = freeze({ kind: \"malformed\" });\n\n/** @internal Classify a textual IP address (no brackets). The `address` of a public verdict is canonical. */\nexport function classifyAddress(text: unknown): WebhookAddressVerdict {\n\tif (typeof text !== \"string\" || text.length === 0 || text.length > MAX_TEXT_LENGTH) return MALFORMED;\n\tconst zone = apply(stringIndexOf, text, [\"%\"]) as number;\n\tif (zone !== -1) return parseIpv6(apply(stringSlice, text, [0, zone]) as string) === undefined ? MALFORMED : NON_PUBLIC_V6;\n\tif (text.length > MAX_ADDRESS_LENGTH) return MALFORMED;\n\tconst v4 = parseIpv4(text);\n\tif (v4 !== undefined) {\n\t\treturn isPublicIpv4Value(v4) ? freeze({ kind: \"public\", address: formatIpv4(v4), family: 4 }) : NON_PUBLIC_V4;\n\t}\n\tconst v6 = parseIpv6(text);\n\tif (v6 === undefined) return MALFORMED;\n\treturn isPublicIpv6Words(v6) ? freeze({ kind: \"public\", address: formatIpv6(v6), family: 6 }) : NON_PUBLIC_V6;\n}\n\n/** @internal `true` for a canonical dotted-quad, the form WHATWG URL parsing gives an IPv4 host. */\nexport function isIpv4Literal(text: string): boolean {\n\treturn matches(IPV4_DOTTED, text);\n}\n\n/**\n * `true` when `address` is a well-formed IPv4 (canonical dotted-quad) or\n * IPv6 address that a webhook may be sent to: not loopback, private,\n * link-local, shared (CGNAT), multicast, reserved, unspecified,\n * documentation, benchmarking, unique-local, site-local, IPv4-mapped,\n * IPv4-compatible, or outside IPv6 global unicast; and, for NAT64\n * (`64:ff9b::/96`), 6to4 (`2002::/16`) and Teredo (`2001::/32`), only when\n * every embedded IPv4 address is public. Anything that does not parse is\n * `false`. The README lists every refused block.\n */\nexport function isPublicWebhookAddress(address: string): boolean {\n\treturn classifyAddress(address).kind === \"public\";\n}\n","import { inputError } from \"./errors\";\nimport { WEBHOOK_MAX_TIMER_MS } from \"./limits\";\nimport type { WebhookClock } from \"./ports\";\nimport { apply, readOwn, timeOf, type Fail } from \"./snapshot\";\n\n/*\n * Deadline, signal, clock and timer handling shared by the destination\n * resolver and the Node transport. Portable: it uses only the WHATWG\n * `AbortSignal`/`EventTarget` and the timer globals every supported runtime\n * has, captured at module load.\n */\n\nconst reflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;\nconst abortedGetter = typeof AbortSignal === \"function\" ? reflectGetOwnPropertyDescriptor(AbortSignal.prototype, \"aborted\")?.get : undefined;\nconst eventTargetAdd = typeof EventTarget === \"function\" ? EventTarget.prototype.addEventListener : undefined;\nconst eventTargetRemove = typeof EventTarget === \"function\" ? EventTarget.prototype.removeEventListener : undefined;\nconst setTimer = setTimeout;\nconst clearTimer = clearTimeout;\nconst dateNow = Date.now;\nconst mathMax = Math.max;\nconst mathMin = Math.min;\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/** @internal The `{ deadline, signal }` of one call, read at entry. */\nexport interface CallBounds {\n\treadonly deadlineMs: number;\n\treadonly signal: AbortSignal;\n}\n\n/**\n * @internal Read `{ deadline, signal }` at entry, one descriptor read each.\n * The deadline must be a real `Date` with a finite time and the signal a real\n * `AbortSignal`; anything else throws `input_unreadable`.\n */\nexport function readCallBounds(options: unknown): CallBounds {\n\tif (options === null || typeof options !== \"object\") throw unreadable();\n\tconst deadlineMs = timeOf(readOwn(options, \"deadline\", \"deadline\", unreadableFail));\n\tif (!(deadlineMs === deadlineMs) || deadlineMs === Infinity || deadlineMs === -Infinity) throw unreadable();\n\tconst signal = readOwn(options, \"signal\", \"signal\", unreadableFail);\n\tif (signal === null || typeof signal !== \"object\") throw unreadable();\n\ttry {\n\t\tisAborted(signal as AbortSignal);\n\t} catch {\n\t\tthrow unreadable();\n\t}\n\treturn { deadlineMs, signal: signal as AbortSignal };\n}\n\n/**\n * @internal Whether a real `AbortSignal` has aborted, read through the\n * intrinsic getter (it throws for anything else and runs none of its code).\n */\nexport function isAborted(signal: AbortSignal): boolean {\n\tif (abortedGetter === undefined) throw unreadable();\n\treturn apply(abortedGetter, signal, []) === true;\n}\n\n/** @internal Call `listener` once when `signal` aborts; the returned function removes it. */\nexport function onAbort(signal: AbortSignal, listener: () => void): () => void {\n\tif (eventTargetAdd === undefined || eventTargetRemove === undefined) throw unreadable();\n\tapply(eventTargetAdd, signal, [\"abort\", listener, { once: true }]);\n\treturn () => {\n\t\tapply(eventTargetRemove, signal, [\"abort\", listener]);\n\t};\n}\n\n/** @internal A clock captured at construction, or the system clock when none was injected. */\nexport interface CapturedClock {\n\treadonly target: object | undefined;\n\treadonly now: ((...args: never[]) => unknown) | undefined;\n}\n\n/** @internal Capture an optional {@link WebhookClock}; a non-object or a missing `now` throws `input_unreadable`. */\nexport function captureOptionalClock(clock: unknown): CapturedClock {\n\tif (clock === undefined) return { target: undefined, now: undefined };\n\tif (clock === null || typeof clock !== \"object\") throw unreadable();\n\tconst now = (clock as Partial<WebhookClock>).now;\n\tif (typeof now !== \"function\") throw unreadable();\n\treturn { target: clock, now: now as (...args: never[]) => unknown };\n}\n\n/** @internal Epoch milliseconds from the clock, or `NaN` when it throws or returns no valid `Date`. Never throws. */\nexport function clockNowMs(clock: CapturedClock): number {\n\tif (clock.now === undefined) return dateNow();\n\ttry {\n\t\tconst ms = timeOf(apply(clock.now, clock.target, []));\n\t\treturn ms === Infinity || ms === -Infinity ? NaN : ms;\n\t} catch {\n\t\treturn NaN;\n\t}\n}\n\n/**\n * @internal Run `fire` after `ms`, clamped to `[0, WEBHOOK_MAX_TIMER_MS]` so a\n * far deadline cannot overflow into an immediate timer. Returns a cancel\n * function.\n */\nexport function startTimer(ms: number, fire: () => void): () => void {\n\tconst handle = setTimer(fire, mathMax(0, mathMin(ms, WEBHOOK_MAX_TIMER_MS)));\n\treturn () => {\n\t\tclearTimer(handle);\n\t};\n}\n","import { classifyAddress, isIpv4Literal } from \"./address\";\nimport { readCallBounds, captureOptionalClock, clockNowMs, isAborted, onAbort, startTimer, type CapturedClock } from \"./call-bounds\";\nimport { configError, guard, inputError } from \"./errors\";\nimport { WEBHOOK_MAX_TIMER_MS, assertPositiveFinite } from \"./limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookDestinationResolution,\n\tWebhookDestinationResolver,\n\tWebhookResolvedAddress,\n\tWebhookVettedDestination,\n} from \"./ports\";\nimport { apply, emptyMap, freeze, frozenList, isArray, isPlainRecord, matches, numberIsSafeInteger, primitive, readOwn, record, type Fail } from \"./snapshot\";\n\n/*\n * Destination rules and resolution (ADR 0018 decision 6, R8). Portable: the\n * DNS lookup is injected, so the main entry needs no Node built-in. The Node\n * lookup and transport are at `@fabricorg/webhook-delivery/node`.\n */\n\n/** The longest destination URL accepted, in UTF-16 code units. */\nexport const WEBHOOK_DESTINATION_MAX_URL_LENGTH = 2_048;\n/** The most addresses one lookup may return; a longer answer is refused as `dns_failure`. */\nexport const WEBHOOK_DESTINATION_MAX_ADDRESSES = 32;\n/** The default bound on one DNS lookup. */\nexport const DEFAULT_WEBHOOK_LOOKUP_TIMEOUT_MS = 5_000;\n\nconst URLConstructor = URL;\nconst urlGetter = (name: string): ((this: URL) => string) => {\n\tconst getter = Reflect.getOwnPropertyDescriptor(URL.prototype, name)?.get;\n\tif (getter === undefined) throw new TypeError(`URL.prototype.${name} is not an accessor.`);\n\treturn getter as (this: URL) => string;\n};\nconst urlProtocol = urlGetter(\"protocol\");\nconst urlUsername = urlGetter(\"username\");\nconst urlPassword = urlGetter(\"password\");\nconst urlPort = urlGetter(\"port\");\nconst urlHostname = urlGetter(\"hostname\");\nconst urlPathname = urlGetter(\"pathname\");\nconst urlSearch = urlGetter(\"search\");\nconst stringSlice = String.prototype.slice;\nconst stringEndsWith = String.prototype.endsWith;\nconst PromiseConstructor = Promise;\nconst promiseThen = Promise.prototype.then;\nconst AbortControllerConstructor = AbortController;\nconst abortControllerAbort = AbortController.prototype.abort;\nconst abortControllerSignal = Reflect.getOwnPropertyDescriptor(AbortController.prototype, \"signal\")!.get!;\nconst DateConstructor = Date;\n\n/** No ASCII control character or space anywhere: WHATWG parsing would strip or drop them silently. */\nconst URL_TEXT = /^[^\\x00-\\x20\\x7f]+$/;\n/**\n * `https://` then a host character. WHATWG parsing also accepts\n * `https:host`, `https:///host` and backslashes for a special scheme and\n * finds a host in them; requiring the plain form keeps the host an operator\n * sees in the URL the one that is checked.\n */\nconst URL_PREFIX = /^https:\\/\\/[^/\\\\?#@]/i;\n\n/** The result of checking a destination URL's rules, before any DNS lookup. */\nexport type WebhookDestinationUrlCheck =\n\t| {\n\t\t\treadonly ok: true;\n\t\t\t/** `https://<host><path><query>`: normalized by WHATWG URL parsing, fragment dropped. */\n\t\t\treadonly url: string;\n\t\t\t/** The host without IPv6 brackets: the SNI name and certificate identity. */\n\t\t\treadonly hostname: string;\n\t\t\t/** Set when the host is an IP literal; it is the only address the destination may use. */\n\t\t\treadonly literal?: WebhookResolvedAddress;\n\t }\n\t| { readonly ok: false; readonly code: \"invalid_url\" | \"private_address\" };\n\nconst INVALID_URL: WebhookDestinationUrlCheck = freeze({ ok: false, code: \"invalid_url\" });\nconst PRIVATE_URL: WebhookDestinationUrlCheck = freeze({ ok: false, code: \"private_address\" });\n\n/**\n * Check a destination URL against decision 6's rules without resolving it.\n * `invalid_url` when it is not a string of at most\n * {@link WEBHOOK_DESTINATION_MAX_URL_LENGTH} characters with no ASCII\n * control character or space, does not start with `https://` and a host\n * character (WHATWG would find a host in `https:host` or `https:///host`),\n * does not parse, is not `https:`, names a port\n * other than 443 (an explicit `:443` is the default and accepted), carries\n * userinfo, or has an empty host or one ending in `.`. `private_address` when\n * the host is `localhost` or a `.localhost` name, or an IP literal that is not\n * public ({@link isPublicWebhookAddress}). A public IP literal passes and is\n * returned as `literal`. IPv4 literals in decimal, hex, octal or shorthand\n * form are normalized to dotted-quad by URL parsing before they are checked.\n * Never throws.\n */\nexport function checkWebhookDestinationUrl(url: string): WebhookDestinationUrlCheck {\n\treturn checkDestinationUrl(url, false);\n}\n\n/**\n * @internal {@link checkWebhookDestinationUrl}, optionally accepting a\n * non-public host (an IP literal or a `localhost` name) while every other\n * rule still applies. `true` is passed only when the Node transport was built\n * by the internal test factory with its public-address re-check off.\n */\nexport function checkDestinationUrl(url: unknown, allowNonPublic: boolean): WebhookDestinationUrlCheck {\n\ttry {\n\t\treturn checkUrl(primitive(url), allowNonPublic);\n\t} catch {\n\t\treturn INVALID_URL;\n\t}\n}\n\nfunction checkUrl(text: unknown, allowNonPublic: boolean): WebhookDestinationUrlCheck {\n\tif (typeof text !== \"string\" || text.length === 0 || text.length > WEBHOOK_DESTINATION_MAX_URL_LENGTH) return INVALID_URL;\n\tif (!matches(URL_TEXT, text) || !matches(URL_PREFIX, text)) return INVALID_URL;\n\tlet parsed: URL;\n\ttry {\n\t\tparsed = new URLConstructor(text);\n\t} catch {\n\t\treturn INVALID_URL;\n\t}\n\tif (apply(urlProtocol, parsed, []) !== \"https:\") return INVALID_URL;\n\tif (apply(urlUsername, parsed, []) !== \"\" || apply(urlPassword, parsed, []) !== \"\") return INVALID_URL;\n\t// WHATWG parsing drops the scheme's default port, so `:443` reads as \"\".\n\tif (apply(urlPort, parsed, []) !== \"\") return INVALID_URL;\n\tconst host = apply(urlHostname, parsed, []) as string;\n\tif (host === \"\" || (apply(stringEndsWith, host, [\".\"]) as boolean)) return INVALID_URL;\n\tconst url = `https://${host}${apply(urlPathname, parsed, []) as string}${apply(urlSearch, parsed, []) as string}`;\n\t// WHATWG parsing serializes an IP-literal host canonically: IPv6 in\n\t// brackets (RFC 5952 form), IPv4 as a dotted-quad.\n\tconst v6 = host[0] === \"[\";\n\tif (v6 || isIpv4Literal(host)) {\n\t\tconst text = v6 ? (apply(stringSlice, host, [1, -1]) as string) : host;\n\t\tconst literal = classifyAddress(text);\n\t\tif (literal.kind === \"malformed\") return INVALID_URL;\n\t\tif (literal.kind === \"non_public\" && !allowNonPublic) return PRIVATE_URL;\n\t\tconst family: 4 | 6 = v6 ? 6 : 4;\n\t\treturn record({ ok: true as const, url, hostname: text, literal: record({ address: text, family }) });\n\t}\n\t// RFC 6761: these names resolve to loopback by definition.\n\tif (!allowNonPublic && (host === \"localhost\" || (apply(stringEndsWith, host, [\".localhost\"]) as boolean))) return PRIVATE_URL;\n\treturn record({ ok: true as const, url, hostname: host });\n}\n\n/**\n * Looks up a hostname's addresses. It is passed `{ deadline, signal }`; the\n * resolver aborts `signal` when it stops waiting, and ignores any answer that\n * arrives after that. Each answer is `{ address, family }` with a textual IPv4\n * or IPv6 address. `createNodeWebhookDnsLookup()` at\n * `@fabricorg/webhook-delivery/node` is one implementation.\n */\nexport type WebhookDnsLookup = (hostname: string, options: WebhookCallOptions) => Promise<readonly WebhookResolvedAddress[]>;\n\n/** Options for {@link createWebhookDestinationResolver}. */\nexport interface WebhookDestinationResolverOptions {\n\treadonly lookup: WebhookDnsLookup;\n\t/** The longest one lookup may take; default {@link DEFAULT_WEBHOOK_LOOKUP_TIMEOUT_MS}. The call's own deadline also applies. */\n\treadonly lookupTimeoutMs?: number;\n\t/** The clock the call's deadline is compared with; the system clock by default. */\n\treadonly clock?: WebhookClock;\n}\n\ninterface ResolverSettings {\n\treadonly lookup: (...args: never[]) => unknown;\n\treadonly lookupTimeoutMs: number;\n\treadonly clock: CapturedClock;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\nconst DNS_FAILURE: WebhookDestinationResolution = freeze({ ok: false, code: \"dns_failure\" });\nconst PRIVATE_ADDRESS: WebhookDestinationResolution = freeze({ ok: false, code: \"private_address\" });\n\n/**\n * A {@link WebhookDestinationResolver} that applies\n * {@link checkWebhookDestinationUrl}, then resolves the host through the\n * injected lookup and requires every answer to be public. The vetted\n * destination it returns carries the addresses the transport must connect\n * to; the transport never resolves the name again, so a later answer (a DNS\n * rebinding) cannot change where the request goes.\n *\n * A URL that passes the rules resolves to `dns_failure`, never a pass, when\n * the call's signal has aborted, its deadline has passed or the clock cannot\n * be read (no lookup is made; this applies to IP literals too), when the\n * lookup throws, rejects, or has not answered within `lookupTimeoutMs` or by\n * the deadline (its signal is then aborted and a late answer ignored), when\n * an answer arrives but, once read, the signal has aborted, the clock cannot\n * be read or that lookup deadline has passed, or when its answer is empty,\n * longer than {@link WEBHOOK_DESTINATION_MAX_ADDRESSES}, or not a list of\n * `{ address, family }` records whose family matches the address. It is\n * `private_address` when any answer is a well-formed address that is not\n * public, whatever the others are. A public IP-literal host is returned\n * without a lookup.\n *\n * @throws {TypeError} `input_unreadable` at construction when `lookup` is not\n * a function or `clock` has no `now` function, and from `resolve` (as a\n * rejected promise) when `{ deadline, signal }` is not a real `Date` and\n * `AbortSignal`.\n * @throws {WebhookDeliveryConfigError} when `lookupTimeoutMs` is not positive,\n * finite and at most `WEBHOOK_MAX_TIMER_MS`.\n */\nexport function createWebhookDestinationResolver(options: WebhookDestinationResolverOptions): WebhookDestinationResolver {\n\tconst settings = guard(() => readResolverOptions(options), unreadable);\n\tconst resolver = {\n\t\tresolve(url: string, callOptions: WebhookCallOptions): Promise<WebhookDestinationResolution> {\n\t\t\ttry {\n\t\t\t\treturn resolveWith(settings, url, callOptions);\n\t\t\t} catch {\n\t\t\t\treturn PromiseConstructor.reject(unreadable());\n\t\t\t}\n\t\t},\n\t};\n\treturn freeze(resolver);\n}\n\nfunction readResolverOptions(options: unknown): ResolverSettings {\n\tif (!isPlainRecord(options)) throw unreadable();\n\tconst lookup = readOwn(options, \"lookup\", \"lookup\", unreadableFail);\n\tif (typeof lookup !== \"function\") throw unreadable();\n\tconst rawTimeout = primitive(readOwn(options, \"lookupTimeoutMs\", \"lookupTimeoutMs\", unreadableFail));\n\tconst lookupTimeoutMs = rawTimeout === undefined ? DEFAULT_WEBHOOK_LOOKUP_TIMEOUT_MS : rawTimeout;\n\tassertPositiveFinite(lookupTimeoutMs, \"lookupTimeoutMs\");\n\tif (lookupTimeoutMs > WEBHOOK_MAX_TIMER_MS) throw configError(\"limit_out_of_range\", \"lookupTimeoutMs\");\n\tconst clock = captureOptionalClock(readOwn(options, \"clock\", \"clock\", unreadableFail));\n\treturn freeze({ lookup: lookup as (...args: never[]) => unknown, lookupTimeoutMs, clock });\n}\n\nfunction resolveWith(settings: ResolverSettings, url: unknown, callOptions: unknown): Promise<WebhookDestinationResolution> {\n\tconst bounds = readCallBounds(callOptions);\n\tconst check = checkWebhookDestinationUrl(url as string);\n\tif (!check.ok) return PromiseConstructor.resolve(record<WebhookDestinationResolution>({ ok: false, code: check.code }));\n\t// No success, a literal's included, for a call that is aborted, past its\n\t// deadline, or whose clock cannot be read.\n\tconst nowMs = clockNowMs(settings.clock);\n\tif (isAborted(bounds.signal) || !(bounds.deadlineMs > nowMs)) return PromiseConstructor.resolve(DNS_FAILURE);\n\tif (check.literal !== undefined) {\n\t\treturn PromiseConstructor.resolve(vetted(check.url, check.hostname, frozenList([check.literal])));\n\t}\n\tconst waitMs = bounds.deadlineMs - nowMs < settings.lookupTimeoutMs ? bounds.deadlineMs - nowMs : settings.lookupTimeoutMs;\n\t/** The earlier of the lookup timeout and the call's deadline. */\n\tconst lookupDeadlineMs = nowMs + waitMs;\n\tconst { url: vettedUrl, hostname } = check;\n\t// Checked again when an answer arrives: a lookup that blocks past the\n\t// deadline and then fulfils would otherwise win, because its fulfilment\n\t// runs as a microtask before the overdue timer.\n\tconst stillWanted = (): boolean => !isAborted(bounds.signal) && clockNowMs(settings.clock) < lookupDeadlineMs;\n\n\treturn new PromiseConstructor<WebhookDestinationResolution>((settle) => {\n\t\tconst controller = new AbortControllerConstructor();\n\t\tconst lookupSignal = apply(abortControllerSignal, controller, []) as AbortSignal;\n\t\tlet done = false;\n\t\tlet cancelTimer: () => void = () => {};\n\t\tlet removeAbort: () => void = () => {};\n\t\tconst finish = (result: WebhookDestinationResolution): void => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tcancelTimer();\n\t\t\tremoveAbort();\n\t\t\t// Tell the lookup to stop; whatever it answers later is ignored.\n\t\t\tapply(abortControllerAbort, controller, []);\n\t\t\tsettle(result);\n\t\t};\n\t\tcancelTimer = startTimer(waitMs, () => finish(DNS_FAILURE));\n\t\tremoveAbort = onAbort(bounds.signal, () => finish(DNS_FAILURE));\n\t\tif (done) return;\n\t\tlet pending: unknown;\n\t\ttry {\n\t\t\tpending = apply(settings.lookup, undefined, [hostname, freeze({ deadline: new DateConstructor(nowMs + waitMs), signal: lookupSignal })] as never[]);\n\t\t} catch {\n\t\t\tfinish(DNS_FAILURE);\n\t\t\treturn;\n\t\t}\n\t\tif (pending === null || (typeof pending !== \"object\" && typeof pending !== \"function\")) {\n\t\t\tfinish(DNS_FAILURE);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\t// Adopt the lookup's result through the intrinsic `then` of a fresh\n\t\t\t// promise, so a thenable's own code runs only as the lookup's code.\n\t\t\tapply(promiseThen, PromiseConstructor.resolve(pending), [\n\t\t\t\t(answer: unknown) => finish(acceptedVerdict(vettedUrl, hostname, answer, stillWanted)),\n\t\t\t\t() => finish(DNS_FAILURE),\n\t\t\t]);\n\t\t} catch {\n\t\t\tfinish(DNS_FAILURE);\n\t\t}\n\t});\n}\n\n/**\n * Judge an answer, then accept a pass only if the call is still wanted at\n * that moment (not aborted, clock valid, before the lookup deadline). The\n * check runs after the answer is read, so time spent reading it counts.\n */\nfunction acceptedVerdict(url: string, hostname: string, answer: unknown, stillWanted: () => boolean): WebhookDestinationResolution {\n\ttry {\n\t\tconst judged = verdict(url, hostname, answer);\n\t\tif (judged.ok && !stillWanted()) return DNS_FAILURE;\n\t\treturn judged;\n\t} catch {\n\t\treturn DNS_FAILURE;\n\t}\n}\n\n/** Judge a lookup answer: any non-public address refuses it; anything unreadable is `dns_failure`. */\nfunction verdict(url: string, hostname: string, answer: unknown): WebhookDestinationResolution {\n\tif (!isArray(answer)) return DNS_FAILURE;\n\tconst length = readOwn(answer, \"length\", \"length\", unreadableFail);\n\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > WEBHOOK_DESTINATION_MAX_ADDRESSES) return DNS_FAILURE;\n\tconst seen = emptyMap<true>();\n\tconst addresses: WebhookResolvedAddress[] = [];\n\tlet malformed = false;\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst entry = readOwn(answer, `${index}`, \"answer\", unreadableFail);\n\t\tif (!isPlainRecord(entry)) {\n\t\t\tmalformed = true;\n\t\t\tcontinue;\n\t\t}\n\t\tconst address = primitive(readOwn(entry, \"address\", \"address\", unreadableFail));\n\t\tconst family = primitive(readOwn(entry, \"family\", \"family\", unreadableFail));\n\t\tconst judged = classifyAddress(address);\n\t\tif (judged.kind === \"non_public\") return PRIVATE_ADDRESS;\n\t\tif (judged.kind === \"malformed\" || judged.family !== family) {\n\t\t\tmalformed = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (seen[judged.address] === true) continue;\n\t\tseen[judged.address] = true;\n\t\taddresses[addresses.length] = record({ address: judged.address, family: judged.family });\n\t}\n\tif (malformed) return DNS_FAILURE;\n\treturn vetted(url, hostname, frozenList(addresses));\n}\n\nfunction vetted(url: string, hostname: string, addresses: readonly WebhookResolvedAddress[]): WebhookDestinationResolution {\n\tconst destination = record<WebhookVettedDestination>({ url, hostname, port: 443, addresses });\n\treturn record<WebhookDestinationResolution>({ ok: true, destination });\n}\n","import {\n\tWEBHOOK_ADMISSION_DENIAL_CODES,\n\tWEBHOOK_REVOCATION_CODES,\n\ttype WebhookAdmissionDenialCode,\n\ttype WebhookRevocationCode,\n} from \"./codes\";\nimport { guard, guardOr, inputError } from \"./errors\";\nimport type { WebhookAdmissionDecision, WebhookDeliveryAuthorizationDecision } from \"./ports\";\nimport { freeze, isOneOf, isPlainRecord, primitive, readOwn, record, type Fail } from \"./snapshot\";\n\nconst ALLOW: WebhookAdmissionDecision = record({ decision: \"allow\" });\nconst ADMISSION_UNAVAILABLE: WebhookAdmissionDecision = record({ decision: \"unavailable\" });\nconst AUTHORIZED: WebhookDeliveryAuthorizationDecision = record({ decision: \"authorized\" });\nconst AUTHORIZATION_UNAVAILABLE: WebhookDeliveryAuthorizationDecision = record({ decision: \"unavailable\" });\n\n/** Thrown inside a normalizer only, and always caught there. */\nconst UNREADABLE = freeze(Object.create(null) as object);\nconst unreadableFail: Fail = () => {\n\tthrow UNREADABLE;\n};\n\n/** Admission allows the event. */\nexport function webhookAdmissionAllow(): WebhookAdmissionDecision {\n\treturn ALLOW;\n}\n\n/**\n * Admission denies the event with a fixed reason code; the denial is recorded.\n *\n * @throws {TypeError} `denial_code_unknown` for a code outside `WEBHOOK_ADMISSION_DENIAL_CODES`.\n */\nexport function webhookAdmissionDeny(code: WebhookAdmissionDenialCode): WebhookAdmissionDecision {\n\treturn guard(() => {\n\t\tconst value = primitive(code);\n\t\tif (!isOneOf(WEBHOOK_ADMISSION_DENIAL_CODES, value)) throw inputError(\"type\", \"denial_code_unknown\");\n\t\treturn record<WebhookAdmissionDecision>({ decision: \"deny\", code: value as WebhookAdmissionDenialCode });\n\t}, () => inputError(\"type\", \"denial_code_unknown\"));\n}\n\n/** Admission cannot decide now; the job retries without an intent. */\nexport function webhookAdmissionUnavailable(): WebhookAdmissionDecision {\n\treturn ADMISSION_UNAVAILABLE;\n}\n\n/** Snapshot `decision` and `code` from a plain answer; anything unreadable throws, to be caught. */\nfunction snapshotAnswer(value: unknown): { readonly decision: unknown; readonly code: unknown } {\n\tif (!isPlainRecord(value)) throw UNREADABLE;\n\tconst decision = primitive(readOwn(value, \"decision\", \"decision\", unreadableFail));\n\tconst code = primitive(readOwn(value, \"code\", \"code\", unreadableFail));\n\treturn record({ decision, code });\n}\n\n/**\n * Read an admission port's answer fail-closed. Anything other than a\n * well-formed `allow`, `deny` with a known code, or `unavailable`, including\n * a `deny` with an unknown code, an accessor, a non-plain object or an\n * answer whose inspection throws, becomes `unavailable`: it never becomes\n * `allow`, an unknown code is never stored, and this function never throws.\n */\nexport function normalizeWebhookAdmissionDecision(value: unknown): WebhookAdmissionDecision {\n\treturn guardOr(() => {\n\t\tconst { decision, code } = snapshotAnswer(value);\n\t\tif (decision === \"allow\") return ALLOW;\n\t\tif (decision === \"deny\" && isOneOf(WEBHOOK_ADMISSION_DENIAL_CODES, code)) {\n\t\t\treturn record<WebhookAdmissionDecision>({ decision: \"deny\", code: code as WebhookAdmissionDenialCode });\n\t\t}\n\t\treturn ADMISSION_UNAVAILABLE;\n\t}, () => ADMISSION_UNAVAILABLE);\n}\n\n/**\n * Read a delivery authorization port's answer fail-closed. Anything other\n * than a well-formed `authorized`, `revoked` with a known code, or\n * `unavailable`, including an unreadable answer, becomes `unavailable`,\n * which defers the intent unsent. This function never throws.\n */\nexport function normalizeWebhookDeliveryAuthorizationDecision(value: unknown): WebhookDeliveryAuthorizationDecision {\n\treturn guardOr(() => {\n\t\tconst { decision, code } = snapshotAnswer(value);\n\t\tif (decision === \"authorized\") return AUTHORIZED;\n\t\tif (decision === \"revoked\" && isOneOf(WEBHOOK_REVOCATION_CODES, code)) {\n\t\t\treturn record<WebhookDeliveryAuthorizationDecision>({ decision: \"revoked\", code: code as WebhookRevocationCode });\n\t\t}\n\t\treturn AUTHORIZATION_UNAVAILABLE;\n\t}, () => AUTHORIZATION_UNAVAILABLE);\n}\n","import { fanOutError } from \"./errors\";\nimport type { WebhookCallOptions, WebhookClock } from \"./ports\";\nimport { apply, isPlainRecord, numberIsFinite, readOwn, timeOf } from \"./snapshot\";\n\n/*\n * Bounded port calls for the fan-out publisher and cycle and the delivery\n * cycle (R4: each awaited port, stores included, is bounded).\n *\n * Each call gets an absolute `deadline` and its own `AbortSignal`. The\n * caller stops waiting at `timeoutMs` and aborts the signal, so a port that\n * honours it stops work; an answer that settles at or after the bound is a\n * timeout and is dropped (`boundedCall` says how the settle time is taken).\n * A store write that timed out may still have committed, so the cycles\n * treat it as unknown and never follow it with a second, conflicting\n * transition on the strength of the timeout. Every write the cycles make is\n * insert-if-absent or fenced, so a late write either lands once or is\n * refused. The transport\n * call (R3) is not only raced: the transport itself takes the deadline and\n * the signal, refuses an expired or cancelled handoff and stops a started\n * request at the deadline; the delivery cycle waits `settleGraceMs` past\n * the deadline for it to report what it observed (src/delivery-cycle.ts).\n *\n * A thrown value is never read: the outcome records only that it threw.\n * The port's promise has a rejection handler attached as soon as it is\n * returned (`work` in `boundedCall`), so a\n * port that rejects after the caller stopped waiting raises no unhandled\n * rejection.\n */\n\n/** How a bounded call ended. A thrown value is dropped unread. */\nexport type BoundedOutcome<T> =\n\t| { readonly ok: true; readonly value: T }\n\t| { readonly ok: false; readonly reason: \"threw\" | \"timeout\" | \"aborted\" };\n\nconst abortedGetter = typeof AbortSignal === \"function\" ? Reflect.getOwnPropertyDescriptor(AbortSignal.prototype, \"aborted\")?.get : undefined;\n\n/**\n * The caller's `signal` from a publish context, or `undefined`. Read as an\n * own data property; it counts only when the intrinsic `aborted` getter\n * accepts it, which is true of real `AbortSignal`s only and runs none of the\n * value's code. Anything that throws while it is read is dropped unread.\n */\nexport function readContextSignal(context: unknown): AbortSignal | undefined {\n\ttry {\n\t\tif (!isPlainRecord(context) || abortedGetter === undefined) return undefined;\n\t\tconst signal = readOwn(context, \"signal\", \"signal\", () => undefined as never);\n\t\tif (signal === null || typeof signal !== \"object\") return undefined;\n\t\tapply(abortedGetter, signal, []);\n\t\treturn signal as AbortSignal;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Whether a signal {@link readContextSignal} returned has aborted, read with\n * the intrinsic `aborted` getter, so an own `aborted` property on the\n * signal object is never consulted.\n */\nexport function signalAborted(signal: AbortSignal): boolean {\n\tif (abortedGetter === undefined) return false;\n\ttry {\n\t\treturn apply(abortedGetter, signal, []) === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** The context's `actorDisclosure` when it is one of Host's three values, else `undefined`; never throws. */\nexport function readContextDisclosure(context: unknown): \"included\" | \"suppressed\" | \"legacy\" | undefined {\n\ttry {\n\t\tif (!isPlainRecord(context)) return undefined;\n\t\tconst disclosure = readOwn(context, \"actorDisclosure\", \"actorDisclosure\", () => undefined as never);\n\t\treturn disclosure === \"included\" || disclosure === \"suppressed\" || disclosure === \"legacy\" ? disclosure : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** An injected clock captured at construction: the object and its `now` function. */\nexport interface FanOutClock {\n\treadonly target: object;\n\treadonly now: (...args: never[]) => unknown;\n}\n\n/** Capture an injected clock at construction; anything without a `now` function is `options_invalid`. */\nexport function captureFanOutClock(clock: WebhookClock | undefined): FanOutClock {\n\tif (clock === null || typeof clock !== \"object\") throw fanOutError(\"options_invalid\", \"clock\");\n\tconst now = (clock as { now?: unknown }).now;\n\tif (typeof now !== \"function\") throw fanOutError(\"options_invalid\", \"clock.now\");\n\treturn { target: clock, now: now as (...args: never[]) => unknown };\n}\n\n/** Read the captured clock, refusing a throw or an invalid time as `clock_invalid`. */\nexport function readFanOutClock(clock: FanOutClock): number {\n\tlet value: unknown;\n\ttry {\n\t\tvalue = apply(clock.now, clock.target, []);\n\t} catch {\n\t\tthrow fanOutError(\"clock_invalid\", \"clock\");\n\t}\n\tconst ms = timeOf(value);\n\tif (!numberIsFinite(ms)) throw fanOutError(\"clock_invalid\", \"clock\");\n\treturn ms;\n}\n\nconst performanceNow = typeof performance === \"object\" && performance !== null && typeof performance.now === \"function\"\n\t? performance.now.bind(performance)\n\t: Date.now;\n\nconst TIMEOUT: { readonly ok: false; readonly reason: \"timeout\" } = Object.freeze({ ok: false, reason: \"timeout\" });\nconst ABORTED: { readonly ok: false; readonly reason: \"aborted\" } = Object.freeze({ ok: false, reason: \"aborted\" });\nconst THREW: { readonly ok: false; readonly reason: \"threw\" } = Object.freeze({ ok: false, reason: \"threw\" });\n\n/**\n * Run `run` with an absolute deadline `nowMs + timeoutMs` and a signal that\n * aborts at the timeout or when `parent` aborts. Resolves with the outcome;\n * never rejects.\n *\n * An answer (a value or a throw) is classed by when a handler attached\n * directly to the port's promise runs, not by when this function's\n * continuation resumes. That handler records the time: an answer is accepted\n * when, at that handler, `readNow()` (the clock `nowMs` came from) is still\n * before `nowMs + timeoutMs + settleGraceMs` and fewer than\n * `timeoutMs + settleGraceMs` milliseconds have passed on the monotonic\n * clock since the call started. Otherwise it is a `timeout`, and so is an\n * answer whose `readNow()` throws. The classed answer settles the race as\n * soon as that handler returns, so a timer that fires later, or other work\n * that delays this function's own continuation after the handler ran, cannot\n * turn an answer the handler classed as on time into a timeout.\n * `settleGraceMs` (default 0) is the one stated exception, for the\n * transport: its answer is still accepted for that long after its deadline,\n * because the transport itself stops the request at the deadline and\n * reports what it saw.\n *\n * A parent abort settles the race at once, ahead of any answer whose\n * handler has not yet returned, so such an answer is `aborted`.\n *\n * The handler is attached as soon as the port returns, so it runs once the\n * promise settles and the microtasks already queued ahead of it (including\n * any handlers the port itself attached) have run. That delay counts\n * against the answer: it can make an answer late, never early.\n *\n * Whenever this resolves `timeout`, for any reason, the call's signal has\n * already been aborted (`controller.abort()` below runs before it returns),\n * so a port that honours the signal stops, and a store that has not yet\n * reached its atomic step refuses the write. A store write that times out\n * may still have committed: callers treat a timed-out write as unknown.\n */\nexport async function boundedCall<T>(\n\tnowMs: number,\n\ttimeoutMs: number,\n\tparent: AbortSignal | undefined,\n\trun: (options: WebhookCallOptions) => Promise<T>,\n\treadNow: () => number,\n\tsettleGraceMs = 0,\n): Promise<BoundedOutcome<T>> {\n\tif (parent?.aborted) return ABORTED;\n\tconst startedMonotonicMs = performanceNow();\n\tconst acceptWithinMs = timeoutMs + settleGraceMs;\n\tconst acceptUntilMs = nowMs + acceptWithinMs;\n\tconst controller = new AbortController();\n\tconst options: WebhookCallOptions = { deadline: new Date(nowMs + timeoutMs), signal: controller.signal };\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet graceTimer: ReturnType<typeof setTimeout> | undefined;\n\tlet onParentAbort: (() => void) | undefined;\n\tconst stop = new Promise<BoundedOutcome<T>>((resolve) => {\n\t\ttimer = setTimeout(() => {\n\t\t\tcontroller.abort();\n\t\t\tif (settleGraceMs > 0) graceTimer = setTimeout(() => resolve(TIMEOUT), settleGraceMs);\n\t\t\telse resolve(TIMEOUT);\n\t\t}, timeoutMs);\n\t\tif (parent) {\n\t\t\tonParentAbort = () => {\n\t\t\t\tcontroller.abort();\n\t\t\t\tresolve(ABORTED);\n\t\t\t};\n\t\t\tparent.addEventListener(\"abort\", onParentAbort, { once: true });\n\t\t}\n\t});\n\t/** Class an answer when its handler runs (see above). */\n\tconst classify = (outcome: BoundedOutcome<T>): BoundedOutcome<T> => {\n\t\tif (!(performanceNow() - startedMonotonicMs < acceptWithinMs)) return TIMEOUT;\n\t\ttry {\n\t\t\treturn readNow() < acceptUntilMs ? outcome : TIMEOUT;\n\t\t} catch {\n\t\t\treturn TIMEOUT;\n\t\t}\n\t};\n\ttry {\n\t\tlet work: Promise<BoundedOutcome<T>>;\n\t\ttry {\n\t\t\t// The handler is attached directly to what the port returned (a\n\t\t\t// thenable is adopted first, one turn later), so a rejection is\n\t\t\t// always handled. Adoption is inside this guard because it can throw\n\t\t\t// too (a promise whose `constructor` getter throws); that throw is\n\t\t\t// dropped unread, like any other, and cleanup below still runs. Such\n\t\t\t// a promise is outside the port contract (src/ports.ts): no handler\n\t\t\t// can be attached to it, so a rejection it carries stays unhandled.\n\t\t\twork = Promise.resolve(run(options)).then(\n\t\t\t\t(value) => classify({ ok: true, value }),\n\t\t\t\t() => classify(THREW),\n\t\t\t);\n\t\t} catch {\n\t\t\twork = Promise.resolve().then(() => classify(THREW));\n\t\t}\n\t\tconst outcome = await Promise.race([work, stop]);\n\t\tif (!outcome.ok && outcome.reason === \"timeout\") controller.abort();\n\t\treturn outcome;\n\t} finally {\n\t\tif (timer !== undefined) clearTimeout(timer);\n\t\tif (graceTimer !== undefined) clearTimeout(graceTimer);\n\t\tif (parent && onParentAbort) parent.removeEventListener(\"abort\", onParentAbort);\n\t}\n}\n","import { snapshotEventMetadata } from \"./persistence-projection\";\nimport {\n\tdateParse,\n\tisArray,\n\tisOneOf,\n\tisPlainRecord,\n\tnumberIsFinite,\n\tnumberIsSafeInteger,\n\treadOwn,\n\tsnapshotJson,\n\tsnapshotJsonPart,\n\ttype Fail,\n\ttype JsonNodeBudget,\n} from \"./snapshot\";\nimport type {\n\tWebhookEligibilityRevision,\n\tWebhookEventMetadata,\n\tWebhookJobActor,\n\tWebhookJsonObject,\n\tWebhookJsonValue,\n\tWebhookSubscriptionStatus,\n} from \"./types\";\n\n/*\n * Reading what a port returned, for the fan-out publisher and cycle.\n *\n * `boundedCall` (fan-out-call.ts) already turns a port's rejection into a\n * bare reason. A resolved value is still the port's object: inspecting it\n * through ordinary property access could run a getter or a Proxy trap whose\n * error, with whatever text it carries, would escape. So every result is\n * read here, inside one try/catch per reader: own data properties only,\n * through descriptors (an accessor is refused uncalled), copied into\n * package-owned frozen snapshots (`snapshotJson`). Anything that cannot be\n * read this way is `undefined`, and the caller maps that to a fixed code.\n * Nothing thrown inside a reader is kept or read.\n */\n\nconst refuse: Fail = () => {\n\tthrow REFUSED;\n};\nconst REFUSED = Object.freeze(Object.create(null) as object);\n\n/** The `outcome` field of an insert result when it is one of `allowed`, else `undefined`. */\nexport function readOutcome<T extends string>(value: unknown, allowed: readonly T[]): T | undefined {\n\ttry {\n\t\tif (!isPlainRecord(value)) return undefined;\n\t\tconst outcome = readOwn(value, \"outcome\", \"outcome\", refuse);\n\t\treturn isOneOf(allowed, outcome) ? (outcome as T) : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Own data property `key` of a snapshot (which is plain, frozen, null-prototype data). */\nfunction field(snapshot: WebhookJsonObject, key: string): WebhookJsonValue | undefined {\n\treturn readOwn(snapshot, key, key, refuse) as WebhookJsonValue | undefined;\n}\n\nfunction object(value: WebhookJsonValue | undefined): WebhookJsonObject {\n\tif (value === null || value === undefined || typeof value !== \"object\" || isArray(value)) throw REFUSED;\n\treturn value as WebhookJsonObject;\n}\n\nfunction nonEmpty(value: WebhookJsonValue | undefined): string {\n\tif (typeof value !== \"string\" || value === \"\") throw REFUSED;\n\treturn value;\n}\n\nfunction whole(value: WebhookJsonValue | undefined, min: number): number {\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < min) throw REFUSED;\n\treturn value;\n}\n\n/** A list result copied into a frozen snapshot, or `undefined`. */\nfunction snapshotList(value: unknown): readonly WebhookJsonValue[] | undefined {\n\tconst copy = snapshotJson(value, \"result\", refuse);\n\treturn isArray(copy) ? copy : undefined;\n}\n\n/**\n * What identifies a claimed record and the lease it was claimed under: the\n * fields a fenced transition needs. Read before, and independently of, the\n * rest of the record ({@link readClaimedJobs}).\n */\nexport interface ClaimedHeader {\n\treadonly eventId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly lease: { readonly owner: string; readonly fence: number };\n}\n\n/** A claimed fan-out job, as the cycle uses it: every field read from the record and validated. */\nexport interface ClaimedJob extends ClaimedHeader {\n\treadonly event: WebhookEventMetadata;\n\treadonly payload: WebhookJsonObject | null;\n\treadonly payloadProjected: boolean;\n\treadonly facts: WebhookJsonObject;\n\treadonly actor: WebhookJobActor;\n\treadonly attemptCount: number;\n\treadonly processingDeadline: string;\n\t/** `processingDeadline` and `event.recordedAt` as epoch milliseconds, both finite. */\n\treadonly processingDeadlineMs: number;\n\treadonly recordedAtMs: number;\n}\n\n/**\n * One entry of a claim result. `undefined`: the record's identity or lease\n * cannot be read, so no fenced write can name it. `job: undefined`: the\n * header was read but the rest of the record cannot be, so the cycle can\n * still end the job through its fenced dead-letter transition.\n */\nexport type ClaimedEntry = { readonly header: ClaimedHeader; readonly job: ClaimedJob | undefined } | undefined;\n\nconst ACTOR_REASONS = Object.freeze([\"suppressed\", \"legacy\"] as const);\n\nfunction readActor(value: WebhookJsonValue | undefined): WebhookJobActor {\n\tconst actor = object(value);\n\tconst state = field(actor, \"state\");\n\tif (state === \"present\") {\n\t\treturn Object.freeze({ state: \"present\", actorId: nonEmpty(field(actor, \"actorId\")), actorType: nonEmpty(field(actor, \"actorType\")) });\n\t}\n\tconst reason = field(actor, \"reason\");\n\tif (state !== \"absent\" || !isOneOf(ACTOR_REASONS, reason)) throw REFUSED;\n\treturn Object.freeze({ state: \"absent\", reason: reason as \"suppressed\" | \"legacy\" });\n}\n\n/** Own data property `key` of a port's record, read once through its descriptor. */\nfunction raw(record: object, key: string): unknown {\n\treturn readOwn(record, key, key, refuse);\n}\n\nfunction plain(value: unknown): object {\n\tif (!isPlainRecord(value)) throw REFUSED;\n\treturn value;\n}\n\n/**\n * The header: identity and lease, each an own data property read once. A\n * store adds the lease when it claims; it is read here as two scalars, with\n * no size budget, so nothing the store adds can make the header unreadable.\n */\nfunction readHeader(record: unknown): ClaimedHeader {\n\tconst job = plain(record);\n\tconst eventId = nonEmpty(raw(job, \"eventId\") as WebhookJsonValue | undefined);\n\tconst tenantId = nonEmpty(raw(job, \"tenantId\") as WebhookJsonValue | undefined);\n\tconst spaceId = nonEmpty(raw(job, \"spaceId\") as WebhookJsonValue | undefined);\n\tconst lease = plain(raw(job, \"lease\"));\n\tconst owner = nonEmpty(raw(lease, \"owner\") as WebhookJsonValue | undefined);\n\tconst fence = whole(raw(lease, \"fence\") as WebhookJsonValue | undefined, 0);\n\treturn Object.freeze({ eventId, tenantId, spaceId, lease: Object.freeze({ owner, fence }) });\n}\n\n/**\n * Containers the insert-side snapshot counted besides `payload` and `facts`:\n * the job record itself, `event` and `actor`. `event` and `actor` hold only\n * scalars once projected, so each is one container.\n */\nconst DRAFT_FIXED_CONTAINERS = 3;\n/** The depth at which the insert-side snapshot reached `payload` and `facts`: one below the job record. */\nconst DRAFT_FIELD_DEPTH = 1;\n\n/**\n * The rest of the record: the projected draft and the scalars the store\n * added (`attemptCount`, `processingDeadline`).\n *\n * Why this cannot refuse a record the store accepted (A1). The insert\n * (`readJobDraft` in the memory store, via `snapshotRecord`) holds the whole\n * submitted job to `snapshotJson`'s limits: at most `MAX_JSON_NODES`\n * containers and `MAX_JSON_DEPTH` levels, counted from the job record. A\n * claimed record is that draft plus whatever the store adds (a lease, a\n * fence, timestamps, an attempt count, a diagnostic), so budgeting the whole\n * claimed record would refuse a draft accepted at the limit. Instead only\n * the draft's open-ended parts, `payload` and `facts`, are snapshotted, with\n * one shared budget seeded with the draft's other containers and starting\n * at the depth the insert reached them. For a store that returns the draft\n * it accepted, the count and depth here are therefore at most the insert's\n * for that draft, whatever the store added; store-added fields are read as\n * scalars and never budgeted. Test:\n * \"a draft accepted at the node limit round-trips through a claim\".\n */\nfunction readBody(record: unknown, header: ClaimedHeader): ClaimedJob {\n\tconst job = plain(record);\n\t// The same validation the projection applies to an envelope.\n\tconst event = snapshotEventMetadata(raw(job, \"event\"));\n\tif (event.eventId !== header.eventId || event.tenantId !== header.tenantId || event.spaceId !== header.spaceId) throw REFUSED;\n\tconst budget: JsonNodeBudget = { nodes: DRAFT_FIXED_CONTAINERS };\n\tconst storedPayload = raw(job, \"payload\");\n\tconst payload = storedPayload === null ? null : object(snapshotJsonPart(storedPayload, \"payload\", refuse, DRAFT_FIELD_DEPTH, budget));\n\tconst facts = object(snapshotJsonPart(raw(job, \"facts\"), \"facts\", refuse, DRAFT_FIELD_DEPTH, budget));\n\tconst actor = readActor(snapshotJsonPart(raw(job, \"actor\"), \"actor\", refuse, DRAFT_FIELD_DEPTH, { nodes: 0 }));\n\tconst processingDeadline = nonEmpty(raw(job, \"processingDeadline\") as WebhookJsonValue | undefined);\n\tconst processingDeadlineMs = dateParse(processingDeadline);\n\tconst recordedAtMs = dateParse(event.recordedAt);\n\tif (!numberIsFinite(processingDeadlineMs) || !numberIsFinite(recordedAtMs)) throw REFUSED;\n\treturn Object.freeze({\n\t\t...header,\n\t\tevent,\n\t\tpayload,\n\t\tpayloadProjected: raw(job, \"payloadProjected\") === true,\n\t\tfacts,\n\t\tactor,\n\t\tattemptCount: whole(raw(job, \"attemptCount\") as WebhookJsonValue | undefined, 0),\n\t\tprocessingDeadline,\n\t\tprocessingDeadlineMs,\n\t\trecordedAtMs,\n\t});\n}\n\n/**\n * The claim result: `undefined` when the list itself cannot be read, and\n * otherwise one {@link ClaimedEntry} per claimed record. Each record's\n * header is read first, in its own try/catch, and its body after, in\n * another, so a body that cannot be read still leaves a header the cycle\n * can dead-letter by (A2). Whatever either read throws is dropped unread.\n */\nexport function readClaimedJobs(value: unknown): readonly ClaimedEntry[] | undefined {\n\tconst items: unknown[] = [];\n\ttry {\n\t\t// The list shallowly, so one unreadable job does not hide the others.\n\t\tif (!isArray(value)) return undefined;\n\t\tconst length = readOwn(value, \"length\", \"length\", refuse);\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 0 || length > MAX_CLAIMED) return undefined;\n\t\tfor (let index = 0; index < length; index += 1) items.push(readOwn(value, `${index}`, \"job\", refuse));\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn Object.freeze(items.map((item): ClaimedEntry => {\n\t\tlet header: ClaimedHeader;\n\t\ttry {\n\t\t\theader = readHeader(item);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\treturn Object.freeze({ header, job: readBody(item, header) });\n\t\t} catch {\n\t\t\treturn Object.freeze({ header, job: undefined });\n\t\t}\n\t}));\n}\n\n/** More jobs than any claim limit a cycle sends; a longer answer is not a claim result. */\nconst MAX_CLAIMED = 100_000;\n\nconst STATUSES = Object.freeze([\"active\", \"paused\", \"deleted\"] as const);\n\n/** The revision listing, or `undefined` when any part of it cannot be read: eligibility is then unknown. */\nexport function readRevisions(value: unknown): readonly WebhookEligibilityRevision[] | undefined {\n\ttry {\n\t\tconst list = snapshotList(value);\n\t\tif (list === undefined) return undefined;\n\t\treturn Object.freeze(list.map((item) => {\n\t\t\tconst revision = object(item);\n\t\t\tconst patterns = field(revision, \"eventTypePatterns\");\n\t\t\tif (!isArray(patterns)) throw REFUSED;\n\t\t\tconst status = field(revision, \"status\");\n\t\t\tif (!isOneOf(STATUSES, status)) throw REFUSED;\n\t\t\tconst effectiveUntil = field(revision, \"effectiveUntil\");\n\t\t\treturn Object.freeze({\n\t\t\t\tsubscriptionId: nonEmpty(field(revision, \"subscriptionId\")),\n\t\t\t\trevision: whole(field(revision, \"revision\"), 1),\n\t\t\t\ttenantId: nonEmpty(field(revision, \"tenantId\")),\n\t\t\t\tspaceId: nonEmpty(field(revision, \"spaceId\")),\n\t\t\t\tstatus: status as WebhookSubscriptionStatus,\n\t\t\t\teventTypePatterns: Object.freeze(patterns.map(nonEmpty)),\n\t\t\t\teffectiveFrom: nonEmpty(field(revision, \"effectiveFrom\")),\n\t\t\t\teffectiveUntil: effectiveUntil === null || effectiveUntil === undefined ? null : nonEmpty(effectiveUntil),\n\t\t\t});\n\t\t}));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * A tombstone read: `\"decided\"` when an intent or denial marker exists for\n * the pair, `\"undecided\"` for `null`, `undefined` when the answer cannot be read.\n */\nexport function readDecided(value: unknown): \"decided\" | \"undecided\" | undefined {\n\ttry {\n\t\tif (value === null) return \"undecided\";\n\t\tif (!isPlainRecord(value)) return undefined;\n\t\tconst kind = readOwn(value, \"kind\", \"kind\", refuse);\n\t\treturn kind === \"intent\" || kind === \"denial\" ? \"decided\" : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n","import type {\n\tEnterpriseEventEnvelope,\n\tEnterpriseEventPublishContext,\n\tEnterpriseEventPublisher,\n} from \"@fabricorg/platform-host\";\n\nimport { configError, fanOutError, guard } from \"./errors\";\nimport { boundedCall, captureFanOutClock, readContextDisclosure, readContextSignal, readFanOutClock, signalAborted, type FanOutClock } from \"./fan-out-call\";\nimport { readOutcome } from \"./fan-out-read\";\nimport { assertPositiveInteger, resolveWebhookDeliveryLimits, WEBHOOK_MAX_TIMER_MS, type WebhookDeliveryLimits } from \"./limits\";\nimport { callFail, dataFail, projectWebhookFanOutJob, uninspectable } from \"./persistence-projection\";\nimport type { WebhookDeliveryStore } from \"./ports\";\nimport { apply, define, emptyMap, freeze, hasOwn, isArray, isPlainRecord, primitive, readOwn, record, snapshotJsonPart, timeOf, type JsonNodeBudget } from \"./snapshot\";\nimport { isoOf } from \"./store-input\";\nimport type { WebhookJobActor, WebhookPayloadPolicy } from \"./types\";\n\n/*\n * Stage one of the two-stage fan-out (ADR 0018 decision 2), and the\n * composite publisher that lets the Host relay feed webhooks and a bus from\n * one outbox (decisions 2 and 5).\n *\n * The fan-out publisher resolves subscriptions not at all. It projects the\n * envelope (persistence projection) and inserts one fan-out job keyed by\n * `eventId`, insert-if-absent, and resolves only after the store answers\n * `inserted` or `already_present`. The Host relay marks the outbox record\n * published only after `publish()` resolves (`runOutboxRelayCycle`,\n * packages/platform-host/src/outbox.ts), so an acknowledged record has a\n * stored job. A crash between the insert and the acknowledgement leaves\n * the record for lease expiry; the relay republishes it under the same\n * `eventId`, the insert answers `already_present`, and nothing is added\n * (test \"crash before acknowledgement ...\", tests/fan-out-host.test.ts).\n *\n * Nothing a port, the caller's context or a sink throws reaches an error\n * this module throws: a rejection is dropped by `boundedCall`, a resolved\n * value is read by `src/fan-out-read.ts`, the context by the readers in\n * `src/fan-out-call.ts`, and the envelope inside the projection's guard.\n * Every failure is a package error with a fixed code.\n */\n\n/** Options for {@link createWebhookFanOutPublisher}. */\nexport interface WebhookFanOutPublisherOptions {\n\t/** Where jobs are inserted. Only `insertFanOutJob` is called. */\n\treadonly store: Pick<WebhookDeliveryStore, \"insertFanOutJob\">;\n\t/** Stamps the job's `createdAt` and processing deadline, and bounds the store call. */\n\treadonly clock: { now(): Date };\n\t/** The persistence projection's allowlist and declared facts (decision 9). */\n\treadonly policy: WebhookPayloadPolicy;\n\t/**\n\t * Overrides of {@link WebhookDeliveryLimits}; every limit is validated as\n\t * positive and finite at construction (R4). The publisher uses\n\t * `fanOutDeadlineMs` (the job's processing deadline) and `portTimeoutMs`\n\t * (the bound on the insert).\n\t */\n\treadonly limits?: Partial<WebhookDeliveryLimits>;\n}\n\n/**\n * The actor a job records, from the relay's disclosure (decision 5). Only an\n * explicit `included` disclosure with both fields present yields an actor.\n * `suppressed` stays `suppressed`. Anything else, including a missing\n * context (a bridge that passed none) and an `included` record whose\n * envelope lacks the fields, is `legacy`: the reason actor enrichment\n * (PR 9) repairs. An `actorId` on an envelope whose disclosure is not\n * `included` is ignored. Runs inside the projection's guard.\n */\nfunction jobActor(event: unknown, disclosure: ReturnType<typeof readContextDisclosure>): WebhookJobActor {\n\tif (disclosure === \"suppressed\") return record<WebhookJobActor>({ state: \"absent\", reason: \"suppressed\" });\n\tif (disclosure === \"included\" && isPlainRecord(event)) {\n\t\tconst actorId = readOwn(event, \"actorId\", \"actorId\", dataFail);\n\t\tconst actorType = readOwn(event, \"actorType\", \"actorType\", dataFail);\n\t\tif (typeof actorId === \"string\" && actorId !== \"\" && typeof actorType === \"string\" && actorType !== \"\") {\n\t\t\treturn record<WebhookJobActor>({ state: \"present\", actorId, actorType });\n\t\t}\n\t}\n\treturn record<WebhookJobActor>({ state: \"absent\", reason: \"legacy\" });\n}\n\ninterface PublisherConfig {\n\treadonly limits: WebhookDeliveryLimits;\n\treadonly store: object;\n\treadonly insertFanOutJob: (...args: never[]) => unknown;\n\treadonly clock: FanOutClock;\n\treadonly policy: WebhookPayloadPolicy;\n}\n\nfunction readPublisherOptions(options: WebhookFanOutPublisherOptions): PublisherConfig {\n\tif (options === null || typeof options !== \"object\") throw fanOutError(\"options_invalid\", \"options\");\n\tconst limits = resolveWebhookDeliveryLimits(options.limits ?? {});\n\tconst store = options.store;\n\tif (store === null || typeof store !== \"object\") throw fanOutError(\"options_invalid\", \"store\");\n\tconst insertFanOutJob = store.insertFanOutJob;\n\tif (typeof insertFanOutJob !== \"function\") throw fanOutError(\"options_invalid\", \"store\");\n\treturn freeze({ limits, store, insertFanOutJob: insertFanOutJob as (...args: never[]) => unknown, clock: captureFanOutClock(options.clock), policy: options.policy });\n}\n\nconst INSERT_OUTCOMES = freeze([\"inserted\", \"already_present\", \"past_horizon\"] as const);\n\n/**\n * Build the stage-one publisher: an `EnterpriseEventPublisher` to hand to\n * `runOutboxRelayCycle()` (alone or inside {@link createWebhookCompositePublisher}),\n * or to call from a bridge for events that do not reach the Host outbox.\n *\n * `publish(event, context)`:\n *\n * 1. projects the envelope with `projectWebhookFanOutJob()`, recording the\n * actor as the relay's `context.actorDisclosure` describes it;\n * 2. inserts the job with `createdAt` now and a processing deadline\n * `fanOutDeadlineMs` later, bounded by `portTimeoutMs` and the caller's\n * signal;\n * 3. resolves on `inserted` or `already_present` (a replay or a bridge\n * overlap: the first insert wins, and the stored job is not changed).\n *\n * It rejects, so the Host relay retries the record and eventually\n * dead-letters it, with a `WebhookProjectionError` when the envelope cannot\n * be projected, or a `WebhookFanOutError`:\n * `event_past_replay_horizon` when the store answered `past_horizon`,\n * `fan_out_store_failed` when the insert threw or its answer cannot be read,\n * `fan_out_store_timeout` when it timed out, `publish_aborted` when the\n * caller's signal aborted first, and `clock_invalid` for a failing clock.\n * An insert that threw, timed out or was aborted may still have committed;\n * the relay's retry of the same `eventId` then answers `already_present`.\n *\n * @throws {WebhookDeliveryConfigError} at construction, for any limit that\n * is not positive and finite.\n * @throws {WebhookFanOutError} `options_invalid` at construction, for a\n * missing or unreadable store, clock or options object.\n */\nexport function createWebhookFanOutPublisher(options: WebhookFanOutPublisherOptions): EnterpriseEventPublisher {\n\tconst config = guard(() => readPublisherOptions(options), () => fanOutError(\"options_invalid\", \"options\"));\n\tconst { limits, store, insertFanOutJob, clock, policy } = config;\n\n\tconst publish = async (event: EnterpriseEventEnvelope, context?: EnterpriseEventPublishContext): Promise<void> => {\n\t\tconst disclosure = readContextDisclosure(context);\n\t\tconst draft = guard(\n\t\t\t() => projectWebhookFanOutJob(event, { policy, actor: jobActor(event, disclosure) }),\n\t\t\tuninspectable(\"envelope\"),\n\t\t);\n\t\tconst nowMs = readFanOutClock(clock);\n\t\tconst job = { ...draft, createdAt: isoOf(nowMs), processingDeadline: isoOf(nowMs + limits.fanOutDeadlineMs) };\n\t\tconst outcome = await boundedCall(nowMs, limits.portTimeoutMs, readContextSignal(context), (callOptions) =>\n\t\t\tapply(insertFanOutJob, store, [job, callOptions] as never[]) as Promise<unknown>, () => readFanOutClock(clock));\n\t\tif (!outcome.ok) {\n\t\t\tthrow fanOutError(\n\t\t\t\toutcome.reason === \"timeout\" ? \"fan_out_store_timeout\" : outcome.reason === \"aborted\" ? \"publish_aborted\" : \"fan_out_store_failed\",\n\t\t\t\t\"insertFanOutJob\",\n\t\t\t);\n\t\t}\n\t\tconst answer = readOutcome(outcome.value, INSERT_OUTCOMES);\n\t\t// Acknowledge only a durable job: a new one, or the one a replay or a\n\t\t// bridge stored first.\n\t\tif (answer === \"inserted\" || answer === \"already_present\") return;\n\t\t// R5, carried from PR 4: an event older than the replay horizon cannot\n\t\t// get a job, so the publish fails and the Host record dead-letters\n\t\t// instead of counting as delivered.\n\t\tif (answer === \"past_horizon\") throw fanOutError(\"event_past_replay_horizon\", \"insertFanOutJob\");\n\t\tthrow fanOutError(\"fan_out_store_failed\", \"insertFanOutJob\");\n\t};\n\treturn freeze({ publish });\n}\n\n// ---------------------------------------------------------------------------\n// Composite\n// ---------------------------------------------------------------------------\n\n/** One sink of a composite publisher. */\nexport interface WebhookCompositeSink {\n\t/** Names the sink in a `sink_failed` or `sink_timeout` error: 1 to 64 printable ASCII characters, unique in the composite. */\n\treadonly name: string;\n\treadonly publisher: EnterpriseEventPublisher;\n\t/**\n\t * Only `true` passes `actorId` and `actorType` to this sink, with the\n\t * relay's `actorDisclosure` unchanged. Any other value gives the sink a\n\t * copy of the envelope without those keys, and reports an `included`\n\t * disclosure to it as `suppressed` (decision 5).\n\t */\n\treadonly includeActor?: boolean;\n\t/**\n\t * Defaults to `true`. The composite resolves only after every required\n\t * sink resolves. A sink with `required: false` is started with the others\n\t * but never waited for: its outcome, timeout included, is ignored, so an\n\t * event it fails is not retried for it.\n\t */\n\treadonly required?: boolean;\n}\n\n/** Options for {@link createWebhookCompositePublisher}. */\nexport interface WebhookCompositePublisherOptions {\n\t/** At least one sink, at most 16, called concurrently. */\n\treadonly sinks: readonly WebhookCompositeSink[];\n\t/**\n\t * How long each sink is given, in ms, before its signal is aborted and\n\t * it counts as timed out. A positive whole number up to\n\t * `WEBHOOK_MAX_TIMER_MS`; default 10 000, Host's default publish timeout.\n\t */\n\treadonly sinkTimeoutMs?: number;\n}\n\ninterface Sink {\n\treadonly name: string;\n\treadonly target: object;\n\treadonly publish: (...args: never[]) => unknown;\n\treadonly includeActor: boolean;\n\treadonly required: boolean;\n}\n\nconst MAX_SINKS = 16;\nconst SINK_NAME = /^[\\x21-\\x7e]{1,64}$/;\nconst DEFAULT_SINK_TIMEOUT_MS = 10_000;\n\nfunction readComposite(options: unknown): { readonly sinks: readonly Sink[]; readonly timeoutMs: number } {\n\tif (options === null || typeof options !== \"object\") throw fanOutError(\"options_invalid\", \"options\");\n\tconst rawTimeout = primitive((options as { sinkTimeoutMs?: unknown }).sinkTimeoutMs);\n\tconst timeoutMs = rawTimeout === undefined ? DEFAULT_SINK_TIMEOUT_MS : rawTimeout;\n\tassertPositiveInteger(timeoutMs, \"sinkTimeoutMs\");\n\tif (timeoutMs > WEBHOOK_MAX_TIMER_MS) throw configError(\"limit_out_of_range\", \"sinkTimeoutMs\");\n\tconst sinks = (options as { sinks?: unknown }).sinks;\n\tif (!isArray(sinks) || sinks.length === 0 || sinks.length > MAX_SINKS) throw fanOutError(\"options_invalid\", \"sinks\");\n\tconst read: Sink[] = [];\n\tconst names: string[] = [];\n\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\tconst sink = sinks[index] as Partial<WebhookCompositeSink> | undefined;\n\t\tif (sink === null || typeof sink !== \"object\") throw fanOutError(\"options_invalid\", `sinks[${index}]`);\n\t\tconst { name, publisher, includeActor, required } = sink;\n\t\tif (typeof name !== \"string\" || !SINK_NAME.test(name) || names.includes(name)) throw fanOutError(\"options_invalid\", `sinks[${index}].name`);\n\t\tif (publisher === null || typeof publisher !== \"object\" || typeof publisher.publish !== \"function\") {\n\t\t\tthrow fanOutError(\"options_invalid\", `sinks[${index}].publisher`);\n\t\t}\n\t\tif (includeActor !== undefined && typeof includeActor !== \"boolean\") throw fanOutError(\"options_invalid\", `sinks[${index}].includeActor`);\n\t\tif (required !== undefined && typeof required !== \"boolean\") throw fanOutError(\"options_invalid\", `sinks[${index}].required`);\n\t\tnames.push(name);\n\t\tread.push(freeze({ name, target: publisher, publish: publisher.publish as (...args: never[]) => unknown, includeActor: includeActor === true, required: required !== false }));\n\t}\n\treturn freeze({ sinks: freeze(read), timeoutMs });\n}\n\n/*\n * Trust model. Sinks are trusted application code wired at the composition\n * root, like Host's adapters. The composite isolates sinks from ordinary\n * sink behaviour: mutating the envelope or context it was handed, throwing\n * synchronously, returning a rejected promise or a thenable that calls its\n * reject callback, rejecting late, ignoring its signal, and hanging. It does\n * not confine code that subverts intrinsics: a returned promise with a\n * poisoned `constructor` getter, a thenable whose `then` throws\n * asynchronously, or a replaced `dispatchEvent` or other\n * `EventTarget` method on the signal it was handed (the intrinsic `abort`\n * below dispatches the abort event on that signal, so such a replacement\n * runs). Those are outside the composite's guarantees.\n *\n * The runtime functions the composite calls are captured when this module\n * loads, in keeping with the rest of the package (src/snapshot.ts). This is\n * consistency, not confinement. The composite installs no listener on a\n * sink's signal and its cleanup calls nothing on the envelope, context or\n * signal it handed a sink. Each capture is `undefined` on a runtime without\n * it, and construction then refuses the composite as `options_invalid`.\n */\nconst AbortControllerIntrinsic = typeof AbortController === \"function\" ? AbortController : undefined;\nconst abortIntrinsic = AbortControllerIntrinsic?.prototype.abort;\nconst controllerSignalGetter = AbortControllerIntrinsic === undefined ? undefined : Reflect.getOwnPropertyDescriptor(AbortControllerIntrinsic.prototype, \"signal\")?.get;\nconst addListenerIntrinsic = typeof EventTarget === \"function\" ? EventTarget.prototype.addEventListener : undefined;\nconst removeListenerIntrinsic = typeof EventTarget === \"function\" ? EventTarget.prototype.removeEventListener : undefined;\nconst setTimer = setTimeout;\nconst clearTimer = clearTimeout;\nconst PromiseIntrinsic = Promise;\nconst deleteProperty = Reflect.deleteProperty;\nconst DateIntrinsic = Date;\nconst reflectOwnKeys = Reflect.ownKeys;\nconst reflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;\nconst reflectDefineProperty = Reflect.defineProperty;\nconst numberIsFinite = Number.isFinite;\n\nfunction compositeRuntimeAvailable(): boolean {\n\treturn abortIntrinsic !== undefined && controllerSignalGetter !== undefined && addListenerIntrinsic !== undefined &&\n\t\tremoveListenerIntrinsic !== undefined;\n}\n\n/**\n * One envelope per sink (B1): no two sinks, and no sink and the caller, share\n * a mutable object through the envelope. What enforces it is an allowlist,\n * not a list of refused types. The caller's envelope is read once by the\n * package's plain-data snapshot (src/snapshot.ts: own data properties only,\n * no getter is called, depth and node budgets), which accepts `null`,\n * booleans, finite numbers, strings, arrays, plain objects and the envelope's\n * two top-level dates, and refuses everything else (typed arrays,\n * `ArrayBuffer`, `SharedArrayBuffer`, `Map`, `Set`, `Error`, class instances,\n * `WebAssembly.Memory`, functions, symbols, accessors, and proxies over any\n * of those; a proxy over plain data cannot be told apart and its traps run\n * while the envelope is read). A refusal\n * fails the publish as `inspection_failed` before any sink starts. A value\n * the snapshot accepts holds no reference to memory outside itself, so each\n * sink's copy, built from the snapshot by `thaw`, shares nothing with another\n * sink's copy or the caller.\n *\n * `occurredAt` and `recordedAt` are copied as new `Date`s. A `Date` anywhere\n * else (in `payload`, say) becomes its ISO-8601 string, as the persistence\n * projection treats it. Host types `payload` as `unknown` and does not\n * guarantee JSON, so an envelope whose payload is not plain data is refused,\n * not passed through. A sink without `includeActor` gets its copy with\n * `actorId` and `actorType` deleted, so the keys are absent, not `undefined`.\n * All copies exist before any sink runs, so a sink mutating its envelope\n * cannot change what another receives (tests \"a sink mutating its envelope\n * ...\", \"an envelope holding ... is refused\").\n */\nfunction sinkEnvelopes(event: unknown, sinks: readonly Sink[]): readonly EnterpriseEventEnvelope[] {\n\tif (!isPlainRecord(event)) throw uninspectable(\"envelope\")();\n\tconst budget: JsonNodeBudget = { nodes: 0 };\n\tconst keys = reflectOwnKeys(event);\n\tconst snapshot: Record<string, unknown> = emptyMap<unknown>();\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index];\n\t\tif (typeof key !== \"string\") continue;\n\t\tconst descriptor = reflectGetOwnPropertyDescriptor(event, key);\n\t\tif (descriptor === undefined || descriptor.enumerable !== true) continue;\n\t\tif (!hasOwn(descriptor, \"value\")) return callFail(\"accessor\", \"envelope\");\n\t\tif (descriptor.value === undefined) continue;\n\t\tif (key === \"occurredAt\" || key === \"recordedAt\") {\n\t\t\tconst time = timeOf(descriptor.value);\n\t\t\tif (!numberIsFinite(time)) return callFail(\"not_json\", \"envelope\");\n\t\t\tdefine(snapshot, key, time);\n\t\t} else {\n\t\t\tdefine(snapshot, key, snapshotJsonPart(descriptor.value, \"envelope\", callFail, 1, budget));\n\t\t}\n\t}\n\tconst copies: EnterpriseEventEnvelope[] = [];\n\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\tconst copy = thaw(snapshot) as Record<string, unknown>;\n\t\tif (typeof snapshot.occurredAt === \"number\") copy.occurredAt = new DateIntrinsic(snapshot.occurredAt);\n\t\tif (typeof snapshot.recordedAt === \"number\") copy.recordedAt = new DateIntrinsic(snapshot.recordedAt);\n\t\tif (!sinks[index]!.includeActor) {\n\t\t\tdeleteProperty(copy, \"actorId\");\n\t\t\tdeleteProperty(copy, \"actorType\");\n\t\t}\n\t\tcopies.push(copy as unknown as EnterpriseEventEnvelope);\n\t}\n\treturn copies;\n}\n\n/**\n * A fresh, mutable, ordinary copy of a package-built snapshot (arrays,\n * null-prototype objects, primitives). It walks only snapshot values, whose\n * depth the snapshot already bounded. A key such as `__proto__` is defined\n * as an own property, never assigned.\n */\nfunction thaw(value: unknown): unknown {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (isArray(value)) {\n\t\tconst list: unknown[] = [];\n\t\tfor (let index = 0; index < value.length; index += 1) list.push(thaw(value[index]));\n\t\treturn list;\n\t}\n\tconst keys = reflectOwnKeys(value);\n\tconst out: Record<string, unknown> = {};\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst key = keys[index] as string;\n\t\tdefineMutable(out, key, thaw((value as Record<string, unknown>)[key]));\n\t}\n\treturn out;\n}\n\nfunction defineMutable(target: object, key: string, value: unknown): void {\n\treflectDefineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n/** How one sink's run ended. A rejection reason is kept only to be passed to `guard`, which runs none of its code. */\ntype SinkOutcome =\n\t| { readonly status: \"ok\" }\n\t| { readonly status: \"failed\"; readonly reason: unknown }\n\t| { readonly status: \"timeout\" }\n\t| { readonly status: \"aborted\" };\n\nconst OK: SinkOutcome = freeze({ status: \"ok\" });\nconst TIMED_OUT: SinkOutcome = freeze({ status: \"timeout\" });\nconst ABORTED: SinkOutcome = freeze({ status: \"aborted\" });\n\n/** One sink's run: its outcome, and the two ways the composite drives it. */\ninterface SinkRun {\n\t/** Resolves once, with how the run ended. Never rejects. */\n\treadonly outcome: Promise<SinkOutcome>;\n\t/** Start the sink's timer and call it, unless the run already ended. */\n\treadonly start: () => void;\n\t/** End the run as aborted and abort the sink's signal; nothing once it ended. */\n\treadonly abort: () => void;\n}\n\n/**\n * Prepare one sink's run: its own controller and signal, its own context\n * object, and an outcome promise settled by `end` exactly once, by whichever\n * comes first of the sink settling, the timeout and `abort`.\n *\n * Rejections from ordinary sink behaviour are handled (B3, within the trust\n * model above). `outcome` is resolve-only. The sink is called inside an\n * `async` body whose `try` covers the call, a synchronous throw, and the\n * `await` of what it returned: a rejected promise, early or late, or a\n * thenable that calls its reject callback lands in that `catch`, and the\n * body itself never rejects. `end` catches every error its own cleanup\n * could throw. A returned value that subverts the promise machinery (a\n * poisoned `constructor` getter, a `then` that throws asynchronously) is\n * outside that guarantee.\n *\n * `end` clears the timer and calls `onEnd`, which releases the composite's\n * watch on the caller's signal once every run has ended (B4). A run the\n * composite does not wait for has its timer `unref()`'d where the runtime\n * supports it, so an optional sink still running after `publish()` settled\n * keeps both its timeout and its abort forwarding without keeping the\n * process alive. Tests: the \"fixed outcomes and handled rejections\" and\n * \"optional sinks after publish() settled\" blocks of\n * tests/fan-out-composite.test.ts.\n */\nfunction prepareRun(sink: Sink, envelope: EnterpriseEventEnvelope, disclosure: string | undefined, timeoutMs: number, onEnd: () => void): SinkRun {\n\tconst controller = new AbortControllerIntrinsic!();\n\tconst signal = apply(controllerSignalGetter!, controller, []) as AbortSignal;\n\tconst context = (disclosure === undefined ? { signal } : { signal, actorDisclosure: disclosure }) as EnterpriseEventPublishContext;\n\tlet settle: (outcome: SinkOutcome) => void = () => undefined;\n\tconst outcome = new PromiseIntrinsic<SinkOutcome>((resolve) => {\n\t\tsettle = resolve;\n\t});\n\tlet ended = false;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst end = (result: SinkOutcome, abortSignal: boolean): void => {\n\t\tif (ended) return;\n\t\tended = true;\n\t\tif (timer !== undefined) {\n\t\t\ttry {\n\t\t\t\tclearTimer(timer);\n\t\t\t} catch {\n\t\t\t\t// Nothing to do: the run has ended either way.\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tonEnd();\n\t\t} catch {\n\t\t\t// As above.\n\t\t}\n\t\tif (abortSignal) {\n\t\t\ttry {\n\t\t\t\tapply(abortIntrinsic!, controller, []);\n\t\t\t} catch {\n\t\t\t\t// As above.\n\t\t\t}\n\t\t}\n\t\tsettle(result);\n\t};\n\tconst start = (): void => {\n\t\tif (ended) return;\n\t\ttimer = setTimer(() => end(TIMED_OUT, true), timeoutMs);\n\t\tif (!sink.required) unrefTimer(timer);\n\t\tvoid (async (): Promise<void> => {\n\t\t\ttry {\n\t\t\t\tawait (apply(sink.publish, sink.target, [envelope, context] as never[]) as unknown);\n\t\t\t\tend(OK, false);\n\t\t\t} catch (reason) {\n\t\t\t\tend({ status: \"failed\", reason }, false);\n\t\t\t}\n\t\t})();\n\t};\n\treturn freeze({ outcome, start, abort: () => end(ABORTED, true) });\n}\n\n/** `timer.unref()` on runtimes whose timers have it (Node); a number timer (browsers) is left alone. */\nfunction unrefTimer(timer: unknown): void {\n\ttry {\n\t\tif (timer === null || typeof timer !== \"object\") return;\n\t\tconst unref = (timer as { unref?: unknown }).unref;\n\t\tif (typeof unref === \"function\") apply(unref, timer, []);\n\t} catch {\n\t\t// A timer that cannot be unref'd still fires and is still cleared.\n\t}\n}\n\n/**\n * Build a publisher that hands each event to several sinks, for example the\n * webhook fan-out publisher and a message bus, from one Host relay. A second\n * relay on the same outbox claims the same records, so it is no substitute\n * (decision 2).\n *\n * Sinks are trusted application code; see the trust model above for what\n * the isolation below covers. Every sink is called concurrently, each with\n * its own envelope copy, its own context and its own signal, which aborts\n * when the caller's signal aborts or the sink's `sinkTimeoutMs` runs out. That holds for an optional\n * sink still running after `publish()` settled, too. The composite resolves\n * once every required sink resolved; optional sinks are not waited for. It\n * rejects:\n *\n * - with `publish_aborted`, and no sink started, when the caller's signal\n * aborts at any point before the sinks start, copying the envelope\n * included;\n * - with `publish_aborted` as soon as the caller's signal aborts while a\n * required sink is still running;\n * - otherwise, once every required sink has settled, for the first required\n * sink in sink order that did not resolve: with that sink's error when\n * this package created it (for example `event_past_replay_horizon`),\n * `sink_failed` for any other error, dropped unread, and `sink_timeout`\n * when it did not settle in time;\n * - with a `WebhookProjectionError` (`inspection_failed`) when the envelope\n * is not plain data (see `sinkEnvelopes`) or cannot be read, before any sink is called.\n *\n * The relay then retries the whole record, so every sink sees the event\n * again under the same `eventId`: each sink must treat a repeated `eventId`\n * as a no-op, as the fan-out publisher does.\n *\n * Actor identity reaches only sinks with `includeActor: true` (decision 5;\n * test \"the composite strips actor identity ...\").\n *\n * @throws {WebhookFanOutError} `options_invalid` at construction for an\n * empty or oversized sink list, a duplicate or malformed name, a sink\n * without a `publish` function, or a runtime without `AbortController`,\n * or `EventTarget`.\n * @throws {WebhookDeliveryConfigError} at construction for a `sinkTimeoutMs`\n * that is not a positive whole number within the timer range.\n */\nexport function createWebhookCompositePublisher(options: WebhookCompositePublisherOptions): EnterpriseEventPublisher {\n\tconst { sinks, timeoutMs } = guard(() => readComposite(options), () => fanOutError(\"options_invalid\", \"options\"));\n\tif (!compositeRuntimeAvailable()) throw fanOutError(\"options_invalid\", \"runtime\");\n\tconst publish = async (event: EnterpriseEventEnvelope, context?: EnterpriseEventPublishContext): Promise<void> => {\n\t\tconst parent = readContextSignal(context);\n\t\tif (parent !== undefined && signalAborted(parent)) throw fanOutError(\"publish_aborted\", \"signal\");\n\t\tconst disclosure = readContextDisclosure(context);\n\t\tconst strippedDisclosure = disclosure === \"included\" ? \"suppressed\" : disclosure;\n\t\tconst envelopes = guard(() => sinkEnvelopes(event, sinks), uninspectable(\"envelope\"));\n\n\t\t// One listener on the caller's signal forwards its abort to every run\n\t\t// still going, and is removed when the last run ends, which may be\n\t\t// after `publish()` settled (B4).\n\t\tlet live = sinks.length;\n\t\tconst runs: SinkRun[] = [];\n\t\tconst onParentAbort = (): void => {\n\t\t\tfor (let index = 0; index < runs.length; index += 1) runs[index]!.abort();\n\t\t};\n\t\tconst release = (): void => {\n\t\t\tlive -= 1;\n\t\t\tif (live === 0 && parent !== undefined) {\n\t\t\t\ttry {\n\t\t\t\t\tapply(removeListenerIntrinsic!, parent, [\"abort\", onParentAbort]);\n\t\t\t\t} catch {\n\t\t\t\t\t// The listener only aborts runs that have all ended.\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\t\tconst sink = sinks[index]!;\n\t\t\truns.push(prepareRun(sink, envelopes[index]!, sink.includeActor ? disclosure : strippedDisclosure, timeoutMs, release));\n\t\t}\n\t\tif (parent !== undefined) {\n\t\t\tlet watching = true;\n\t\t\ttry {\n\t\t\t\tapply(addListenerIntrinsic!, parent, [\"abort\", onParentAbort]);\n\t\t\t} catch {\n\t\t\t\twatching = false;\n\t\t\t}\n\t\t\t// The caller's signal may have aborted after the entry check, for\n\t\t\t// example from a proxy trap that ran while the snapshot copied the\n\t\t\t// envelope (getters are refused, not called), before the listener\n\t\t\t// existed. A caller abort that cannot\n\t\t\t// be watched is treated the same way. Either ends every run before\n\t\t\t// any starts, which also releases the listener.\n\t\t\tif (!watching || signalAborted(parent)) {\n\t\t\t\tonParentAbort();\n\t\t\t\tthrow fanOutError(\"publish_aborted\", \"signal\");\n\t\t\t}\n\t\t}\n\t\t// A sink's synchronous code may abort the caller's signal; a run the\n\t\t// forwarding already ended is then not started.\n\t\tfor (let index = 0; index < runs.length; index += 1) runs[index]!.start();\n\n\t\t// Only required runs are awaited. Each outcome promise is resolved by\n\t\t// its sink, its timer or the caller's abort, so the waits end promptly\n\t\t// on an abort (B5).\n\t\tconst outcomes: SinkOutcome[] = [];\n\t\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\t\tif (sinks[index]!.required) outcomes.push(await runs[index]!.outcome);\n\t\t}\n\t\tlet position = 0;\n\t\tlet failure: { readonly name: string; readonly outcome: SinkOutcome } | undefined;\n\t\tfor (let index = 0; index < sinks.length; index += 1) {\n\t\t\tconst sink = sinks[index]!;\n\t\t\tif (!sink.required) continue;\n\t\t\tconst outcome = outcomes[position]!;\n\t\t\tposition += 1;\n\t\t\t// Only the forwarding of the caller's abort ends a run as aborted.\n\t\t\tif (outcome.status === \"aborted\") throw fanOutError(\"publish_aborted\", \"signal\");\n\t\t\tif (outcome.status !== \"ok\" && failure === undefined) failure = { name: sink.name, outcome };\n\t\t}\n\t\tif (failure === undefined) return;\n\t\tif (failure.outcome.status === \"timeout\") throw fanOutError(\"sink_timeout\", failure.name);\n\t\tconst reason = (failure.outcome as { readonly reason: unknown }).reason;\n\t\t// A package-made error passes through with its code; anything else is\n\t\t// replaced unread.\n\t\tguard(() => {\n\t\t\tthrow reason;\n\t\t}, () => fanOutError(\"sink_failed\", failure.name));\n\t};\n\treturn freeze({ publish });\n}\n","/**\n * The event types the package's governed actions emit (PR 9; README,\n * \"Governed actions\"). They are package constants, the same for every\n * module instance whatever its namespace, so the exclusion below does not\n * depend on how an application composed the module.\n *\n * ADR 0018 decision 9: these types are excluded from fan-out matching.\n * {@link matchesWebhookEventTypePattern} (src/fan-out-cycle.ts), the one\n * function that compares a subscription pattern with an event type, answers\n * `false` for each of them before it looks at the pattern, so no\n * subscription, `*` included, gets an intent or a denial for one. Test:\n * \"own-event exclusion: …\" in tests/governed-actions.test.ts.\n *\n * Kept free of `@fabricorg/platform` imports so the fan-out cycle can use it\n * without loading the module factory.\n */\nimport { apply } from \"./snapshot\";\n\nexport const WEBHOOK_DELIVERY_ACTION_EVENT_TYPES = Object.freeze([\n\t\"WebhookSubscriptionCreated\",\n\t\"WebhookSubscriptionUpdated\",\n\t\"WebhookSubscriptionPaused\",\n\t\"WebhookSubscriptionResumed\",\n\t\"WebhookSubscriptionDeleted\",\n\t\"WebhookSecretRotated\",\n\t\"WebhookDeliveryIntentRequeued\",\n\t\"WebhookFanOutJobRequeued\",\n\t\"WebhookFanOutJobActorEnriched\",\n] as const);\n\n/** An event type one of the package's governed actions emits. */\nexport type WebhookDeliveryActionEventType = (typeof WEBHOOK_DELIVERY_ACTION_EVENT_TYPES)[number];\n\nconst includes = Array.prototype.includes;\n\n/** `true` when `eventType` is emitted by one of the package's governed actions. */\nexport function isWebhookDeliveryActionEventType(eventType: unknown): eventType is WebhookDeliveryActionEventType {\n\treturn typeof eventType === \"string\" && apply(includes, WEBHOOK_DELIVERY_ACTION_EVENT_TYPES, [eventType]) === true;\n}\n","import { isWebhookDeliveryActionEventType } from \"./action-events\";\nimport type { WebhookAdmissionDenialCode, WebhookDiagnosticCode } from \"./codes\";\nimport { normalizeWebhookAdmissionDecision } from \"./decisions\";\nimport { renderWebhookDeliveryBodyV1 } from \"./egress\";\nimport { configError, fanOutError, guard } from \"./errors\";\nimport { boundedCall, captureFanOutClock, readFanOutClock, type BoundedOutcome, type FanOutClock } from \"./fan-out-call\";\nimport { readClaimedJobs, readDecided, readOutcome, readRevisions, type ClaimedHeader, type ClaimedJob } from \"./fan-out-read\";\nimport { assertPositiveInteger, resolveWebhookDeliveryLimits, type WebhookDeliveryLimits } from \"./limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookDeliveryStore,\n\tWebhookEventAdmission,\n\tWebhookFanOutJobFence,\n\tWebhookRandomSource,\n\tWebhookRetryDelay,\n\tWebhookScopePredicate,\n\tWebhookSubscriptionStore,\n} from \"./ports\";\nimport { createWebhookRetryDelay } from \"./retry\";\nimport { apply, freeze, mathMin, numberIsFinite, primitive } from \"./snapshot\";\nimport { isoOf } from \"./store-input\";\nimport type { WebhookEligibilityRevision, WebhookEventMetadata, WebhookPayloadPolicy } from \"./types\";\n\n/*\n * Stage two of the two-stage fan-out (ADR 0018 decisions 2, 3, 4 and 5).\n *\n * Completeness boundary (R1). A job binds each intent or denial to the\n * eligibility revision whose half-open interval contains the event's\n * `recordedAt`. Host stamps `recordedAt` with its clock; the subscription\n * store stamps each revision's `effectiveFrom` with its own. Until the\n * subscription store's clock has passed `recordedAt`, a pattern change,\n * pause, resume or create written now can still take effect at or before\n * `recordedAt` and change which revision contains it: a late-effective\n * revision. So the cycle evaluates a job only once its eligibility is\n * settled: the cycle's clock is at or past `recordedAt + eligibilitySettleMs`\n * (`settleAtMs` in `processJob` below). Before that it defers the job\n * unprocessed, writing no intent or denial.\n *\n * Two assumptions about clocks, which this package cannot enforce:\n *\n * - Skew. `eligibilitySettleMs` exceeds the skew between this worker's\n * clock and the subscription store's clock, plus the longest time a\n * revision write takes from reading that clock to becoming visible to\n * `listEligibilityRevisions` (a database store's transaction).\n * - No regression. The subscription store's clock never moves backward past\n * an event time this worker has already settled: in practice a monotonic,\n * NTP-slewed clock. A step backward larger than `eligibilitySettleMs` voids\n * the boundary for events settled inside the step.\n *\n * Host's clock does not enter either: `recordedAt` is only compared with\n * this worker's clock, so a Host clock running ahead delays evaluation and\n * nothing else.\n *\n * Under both assumptions the selection is final once settled: a revision\n * written later starts at the subscription store's clock\n * (WebhookSubscriptionWriter; `mathMax(nowMs, ...)` in the memory store's\n * `#transition`), which is then past `recordedAt`, so it cannot contain it.\n * If an assumption is broken and a revision is stamped at or before the\n * `recordedAt` of an event whose job already completed, the revision is not\n * applied to that event retroactively: the completed job stays completed\n * (test \"a revision stamped behind an already-settled event ...\"). The\n * job is complete when `completeFanOutJob` succeeds, which the cycle calls only\n * after every eligible revision has an intent or a recorded denial. After\n * that point nothing adds or removes intents for the event: claims take only\n * pending jobs, a job requeue accepts only dead letters, intent and denial\n * inserts are insert-if-absent per (subscriptionId, eventId), and a Host\n * outbox replay or a bridge insert of the same `eventId` answers\n * `already_present`. A pause, delete or resume written after `recordedAt`\n * does not change the event's revision; it acts on delivery instead\n * (`cancelPendingIntents` and the delivery cycle's pre-handoff check,\n * src/delivery-cycle.ts).\n * If the job cannot complete, it is rescheduled and finally dead-lettered: a\n * visible, recoverable failure (R1, decision 2).\n *\n * Processing deadline (R4). No intent, denial or completion is written for a\n * job at or after its persisted `processingDeadline`, on the store's clock.\n * Every port call made while processing a job is bounded by the smaller of\n * `portTimeoutMs` and the job's remaining lifetime, and its absolute\n * `deadline` is at most the processing deadline (`jobCall` below). The store\n * contract refuses a write whose call deadline has passed when it reaches the\n * write (store contract case \"a call whose signal aborted or whose deadline\n * passed writes nothing\"), and the cycle also rechecks the deadline before\n * each intent or denial write and before completion. Once the deadline has\n * passed, the job goes to the fenced dead-letter transition as\n * `processing_deadline_exceeded`, bounded by `portTimeoutMs` alone.\n *\n * Lease renewal (changed in PR 8). Every fenced write is refused once the\n * lease has expired on the store's clock, and a pass over a job can take\n * longer than one lease: it reads one tombstone per eligible revision on\n * every pass, decided pairs included. So before each port call made for a\n * job (`jobCall`, and the dead-letter transition), the worker renews the\n * job's lease when less than `RENEW_MARGIN_CALLS * portTimeoutMs` of it is\n * left (`keepLease`): enough for that call and the renewal before it. A\n * worker that keeps making calls therefore keeps its job, and each pass\n * gets as far as its port answers allow; a worker that stops (a crash, a\n * stalled event loop) stops renewing and loses the job when the lease runs\n * out. The store decides the renewal like any fenced write, on its own\n * clock, and never extends a lease past the job's processing deadline, so\n * that deadline still bounds the whole job. A refused renewal (literal\n * `false`) means the lease is gone: the pass stops on that job at once and\n * writes nothing more for it (`LEASE_LOST`). A renewal that throws, times\n * out or answers unreadably is unknown; the worker carries on with the\n * lease it last knew of, and the store's fence check decides its next\n * write. The worker tracks the lease's expiry on its own clock from the\n * `now` and `leaseDurationMs` it sent with the claim and each renewal; a\n * store clock running ahead of the worker's by more than `portTimeoutMs`\n * can still expire a lease the worker thinks it holds, which the store's\n * fence check then refuses (`lease_lost`).\n */\n\n/** What decides whether a subscription revision needs the event's actor identity. */\nexport interface WebhookActorRequirementInput {\n\treadonly subscriptionId: string;\n\treadonly eligibilityRevision: number;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly event: WebhookEventMetadata;\n}\n\n/** Options for {@link runWebhookFanOutCycle}. */\nexport interface WebhookFanOutCycleOptions {\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly subscriptions: WebhookSubscriptionStore;\n\treadonly admission: WebhookEventAdmission;\n\treadonly clock: { now(): Date };\n\t/** The lease owner this worker claims jobs as. */\n\treadonly workerId: string;\n\t/** The egress allowlist the intent bodies are rendered with (decision 9). */\n\treadonly policy: WebhookPayloadPolicy;\n\t/** Consulted for scoped event types when rendering a body. */\n\treadonly scopePredicate?: WebhookScopePredicate;\n\t/**\n\t * Whether admission for a revision needs actor identity (decision 5).\n\t * Required, so the choice is explicit. `true`, or a function returning\n\t * anything but a literal `false` (a throw included), makes a job whose\n\t * actor is `suppressed` or `legacy` `unavailable` for that revision\n\t * without calling admission: the job retries and finally dead-letters,\n\t * and actor enrichment (PR 9) repairs a legacy one.\n\t */\n\treadonly actorRequired: boolean | ((input: WebhookActorRequirementInput) => boolean);\n\t/**\n\t * Overrides of {@link WebhookDeliveryLimits}, all validated positive and\n\t * finite (R4). Used: `maxFanOutAttempts`, `fanOutRetryDelaysMs`,\n\t * `retryJitterRatio`, `portTimeoutMs`, `deliveryDeadlineMs` (each new\n\t * intent's processing deadline).\n\t */\n\treadonly limits?: Partial<WebhookDeliveryLimits>;\n\t/** Delay before the next attempt; defaults to `fanOutRetryDelaysMs` with jitter from `random`. */\n\treadonly retryDelay?: WebhookRetryDelay;\n\t/** Random source for the default retry delay's jitter; required when `retryDelay` is absent. */\n\treadonly random?: WebhookRandomSource;\n\t/** Jobs claimed per cycle. A positive whole number; default 25. */\n\treadonly batchSize?: number;\n\t/**\n\t * Lease on each claimed job, in ms; renewed while the job is processed\n\t * (see \"Lease renewal\" above). A positive whole number above\n\t * `3 * portTimeoutMs`; default 60 000.\n\t */\n\treadonly leaseDurationMs?: number;\n\t/**\n\t * How long after `recordedAt`, on this worker's clock, an event's\n\t * eligibility is treated as settled (see the completeness boundary\n\t * above). It must exceed the skew between this worker's clock and the\n\t * subscription store's, plus the longest revision write. A positive whole\n\t * number of ms below `fanOutDeadlineMs`; default 5 000.\n\t */\n\treadonly eligibilitySettleMs?: number;\n\t/** Creates each intent's `deliveryId`; defaults to `dlv_` plus a random UUID. */\n\treadonly createDeliveryId?: (input: { readonly subscriptionId: string; readonly eventId: string }) => string;\n\t/** Stops the cycle between jobs; the rest of the claimed jobs are reclaimed after their leases expire. */\n\treadonly signal?: AbortSignal;\n}\n\n/** What one cycle did. */\nexport interface WebhookFanOutCycleResult {\n\treadonly claimed: number;\n\t/** Jobs marked complete. */\n\treadonly completed: number;\n\t/** Jobs deferred unprocessed because their eligibility was not yet settled. */\n\treadonly deferred: number;\n\t/** Jobs returned to pending after an unavailable admission or a failed port. */\n\treadonly rescheduled: number;\n\treadonly deadLettered: number;\n\t/** Jobs this worker stopped on because a fenced write or a lease renewal found its lease gone. */\n\treadonly leaseLost: number;\n\t/**\n\t * Jobs left for lease expiry, with nothing more written: a record whose\n\t * identity or lease could not be read, one leased to another owner, or\n\t * one whose final fenced write threw or timed out. A final write that\n\t * timed out may have committed (README, \"Bounds and late results\"); the\n\t * job is then completed, rescheduled or dead-lettered as that write said.\n\t */\n\treadonly abandoned: number;\n\t/** Intent inserts the store confirmed. One that timed out may have committed and is not counted. */\n\treadonly intentsInserted: number;\n\t/** Denial inserts the store confirmed, counted like `intentsInserted`. */\n\treadonly denialsRecorded: number;\n}\n\n/** Defaults for the cycle's own options. */\nexport const DEFAULT_WEBHOOK_FAN_OUT_CYCLE = freeze({\n\tbatchSize: 25,\n\tleaseDurationMs: 60_000,\n\teligibilitySettleMs: 5_000,\n});\n\n/**\n * Whether an event type matches one subscription pattern. `*` matches every\n * type; a pattern ending in `.*` matches every type that starts with the\n * part before `*` (so `orders.*` matches `orders.OrderAccepted` and\n * `orders.lines.Added`, not `orders`); any other pattern must equal the type.\n * A `*` anywhere else is literal.\n *\n * The event types the package's own governed actions emit\n * (`WEBHOOK_DELIVERY_ACTION_EVENT_TYPES`) match no pattern, `*` included\n * (ADR 0018 decision 9). This is the only place a pattern is compared with\n * an event type (`isEligible` below calls it), so the exclusion holds for\n * every subscription whatever its patterns.\n */\nexport function matchesWebhookEventTypePattern(pattern: string, eventType: string): boolean {\n\tif (typeof pattern !== \"string\" || typeof eventType !== \"string\") return false;\n\tif (isWebhookDeliveryActionEventType(eventType)) return false;\n\tif (pattern === \"*\") return true;\n\tif (pattern.length > 2 && pattern.endsWith(\".*\")) return eventType.startsWith(pattern.slice(0, -1));\n\treturn pattern === eventType;\n}\n\nconst randomUUID: (() => string) | undefined =\n\ttypeof globalThis.crypto?.randomUUID === \"function\" ? globalThis.crypto.randomUUID.bind(globalThis.crypto) : undefined;\n\ninterface Config {\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly subscriptions: WebhookSubscriptionStore;\n\treadonly admission: WebhookEventAdmission;\n\treadonly clock: FanOutClock;\n\treadonly workerId: string;\n\treadonly policy: WebhookPayloadPolicy;\n\treadonly scopePredicate: WebhookScopePredicate | undefined;\n\treadonly actorRequired: boolean | ((input: WebhookActorRequirementInput) => boolean);\n\treadonly limits: WebhookDeliveryLimits;\n\treadonly retryDelay: WebhookRetryDelay;\n\treadonly batchSize: number;\n\treadonly leaseDurationMs: number;\n\treadonly settleMs: number;\n\treadonly createDeliveryId: (input: { readonly subscriptionId: string; readonly eventId: string }) => string;\n\treadonly signal: AbortSignal | undefined;\n}\n\nfunction hasMethods(value: unknown, names: readonly string[]): boolean {\n\tif (value === null || typeof value !== \"object\") return false;\n\tfor (const name of names) if (typeof (value as Record<string, unknown>)[name] !== \"function\") return false;\n\treturn true;\n}\n\n/** A cycle option that must be a positive whole number (R4), or its default. */\nfunction positiveWhole(value: unknown, fallback: number, field: string): number {\n\tconst read = primitive(value);\n\tconst resolved = read === undefined ? fallback : read;\n\tassertPositiveInteger(resolved, field);\n\treturn resolved;\n}\n\n/**\n * Read and validate the options. A package error (a limit, a missing port)\n * passes through with its code; anything else thrown while reading them, by\n * a getter or a Proxy trap, is replaced unread with `options_invalid`.\n */\nfunction readConfig(options: WebhookFanOutCycleOptions): Config {\n\treturn guard(() => readConfigUnguarded(options), () => fanOutError(\"options_invalid\", \"options\"));\n}\n\nfunction readConfigUnguarded(options: WebhookFanOutCycleOptions): Config {\n\tif (options === null || typeof options !== \"object\") throw fanOutError(\"options_invalid\", \"options\");\n\tconst limits = resolveWebhookDeliveryLimits(options.limits ?? {});\n\tconst batchSize = positiveWhole(options.batchSize, DEFAULT_WEBHOOK_FAN_OUT_CYCLE.batchSize, \"batchSize\");\n\tconst leaseDurationMs = positiveWhole(options.leaseDurationMs, DEFAULT_WEBHOOK_FAN_OUT_CYCLE.leaseDurationMs, \"leaseDurationMs\");\n\tconst settleMs = positiveWhole(options.eligibilitySettleMs, DEFAULT_WEBHOOK_FAN_OUT_CYCLE.eligibilitySettleMs, \"eligibilitySettleMs\");\n\t// A renewed lease must outlast the renewal call and the margin after it,\n\t// or the worker would renew before every call (see \"Lease renewal\").\n\tif (leaseDurationMs <= (RENEW_MARGIN_CALLS + 1) * limits.portTimeoutMs) throw configError(\"limit_out_of_range\", \"leaseDurationMs\");\n\t// A job whose settle point is past its processing deadline could never be evaluated.\n\tif (settleMs >= limits.fanOutDeadlineMs) throw configError(\"limit_out_of_range\", \"eligibilitySettleMs\");\n\tif (!hasMethods(options.deliveries, [\"claimFanOutJobs\", \"renewFanOutJobLease\", \"completeFanOutJob\", \"rescheduleFanOutJob\", \"deadLetterFanOutJob\", \"insertDeliveryIntent\", \"recordAdmissionDenial\", \"readTombstone\"])) {\n\t\tthrow fanOutError(\"options_invalid\", \"deliveries\");\n\t}\n\tif (!hasMethods(options.subscriptions, [\"listEligibilityRevisions\"])) throw fanOutError(\"options_invalid\", \"subscriptions\");\n\tif (!hasMethods(options.admission, [\"admit\"])) throw fanOutError(\"options_invalid\", \"admission\");\n\tif (typeof options.workerId !== \"string\" || options.workerId === \"\") throw fanOutError(\"options_invalid\", \"workerId\");\n\tconst actorRequired = options.actorRequired;\n\tif (typeof actorRequired !== \"boolean\" && typeof actorRequired !== \"function\") throw fanOutError(\"options_invalid\", \"actorRequired\");\n\tif (options.scopePredicate !== undefined && typeof options.scopePredicate !== \"function\") throw fanOutError(\"options_invalid\", \"scopePredicate\");\n\tif (options.signal !== undefined && !(options.signal instanceof AbortSignal)) throw fanOutError(\"options_invalid\", \"signal\");\n\tlet retryDelay: WebhookRetryDelay;\n\tif (options.retryDelay !== undefined) {\n\t\tif (typeof options.retryDelay !== \"function\") throw fanOutError(\"options_invalid\", \"retryDelay\");\n\t\tretryDelay = options.retryDelay;\n\t} else {\n\t\tretryDelay = createWebhookRetryDelay({ delaysMs: limits.fanOutRetryDelaysMs, jitterRatio: limits.retryJitterRatio, random: options.random! });\n\t}\n\tlet createDeliveryId = options.createDeliveryId;\n\tif (createDeliveryId === undefined) {\n\t\tif (randomUUID === undefined) throw fanOutError(\"options_invalid\", \"createDeliveryId\");\n\t\tconst uuid = randomUUID;\n\t\tcreateDeliveryId = () => `dlv_${uuid()}`;\n\t} else if (typeof createDeliveryId !== \"function\") {\n\t\tthrow fanOutError(\"options_invalid\", \"createDeliveryId\");\n\t}\n\treturn freeze({\n\t\tdeliveries: options.deliveries,\n\t\tsubscriptions: options.subscriptions,\n\t\tadmission: options.admission,\n\t\tclock: captureFanOutClock(options.clock),\n\t\tworkerId: options.workerId,\n\t\tpolicy: options.policy,\n\t\tscopePredicate: options.scopePredicate,\n\t\tactorRequired,\n\t\tlimits,\n\t\tretryDelay,\n\t\tbatchSize,\n\t\tleaseDurationMs,\n\t\tsettleMs,\n\t\tcreateDeliveryId,\n\t\tsignal: options.signal,\n\t});\n}\n\ninterface Counters {\n\tclaimed: number;\n\tcompleted: number;\n\tdeferred: number;\n\trescheduled: number;\n\tdeadLettered: number;\n\tleaseLost: number;\n\tabandoned: number;\n\tintentsInserted: number;\n\tdenialsRecorded: number;\n}\n\n/**\n * Run one fan-out cycle: claim up to `batchSize` pending jobs under a fenced\n * lease and process each in turn. A claimed record whose `eventId`,\n * `tenantId`, `spaceId` or lease cannot be read is left for lease expiry\n * (`abandoned`); one whose identity and lease can be read but whose body\n * cannot is dead-lettered as `job_unreadable` without being processed. For\n * each readable job, in order:\n *\n * 1. Past its processing deadline (persisted at creation; deferrals and\n * reclaims count toward it, R4): dead-letter `processing_deadline_exceeded`.\n * 2. Eligibility not yet settled (`recordedAt + eligibilitySettleMs` still\n * ahead): defer it to that time, unprocessed, as `eligibility_unsettled`.\n * The store's reschedule spends one attempt, so a deferred job has one\n * attempt fewer for failures.\n * 3. List the revisions containing `recordedAt` in the job's tenant and\n * space. Each `active` revision whose patterns match the event type is\n * eligible; a paused or deleted one gets neither intent nor denial.\n * 4. For each eligible revision, in `subscriptionId` order: a pair that\n * already has an intent or a denial (its tombstone) is decided and\n * admission is not asked again. Otherwise, when the revision needs an\n * actor and the job has none (`suppressed` or `legacy`), it is\n * `unavailable`; else admission decides, with a throw, a timeout or an\n * unreadable answer read as `unavailable`. `allow` renders the v1 body and\n * inserts an intent; `deny` records a denial with its code; `unavailable`\n * writes nothing and leaves the job incomplete.\n * 5. Every eligible revision decided: complete the job. Otherwise\n * reschedule it after `retryDelay(attempt)`, or dead-letter it when the\n * attempts are spent or the next attempt would fall past its deadline.\n *\n * Every port call in steps 3 to 5, except the dead-letter transition (bounded\n * by `portTimeoutMs` alone), is bounded by the smaller of\n * `portTimeoutMs` and the job's remaining lifetime; once the processing\n * deadline has passed the job is dead-lettered and nothing else is written\n * for it (see \"Processing deadline\" above). Every port result is read through\n * `src/fan-out-read.ts`, so a getter or Proxy trap in it cannot throw out of\n * the cycle; an unreadable result counts as that port being unavailable.\n *\n * Every write is fenced by the job's lease, which the worker renews while\n * it works (see \"Lease renewal\" above). When the store answers\n * `lease_lost`, a fenced transition answers `false`, or a renewal is\n * refused, the worker stops on that job and writes nothing more for it. A\n * read or an insert that throws or times out stops the job and reschedules\n * it; an insert that timed out may have committed, and the next attempt\n * finds it `already_present`. A final transition (completion, reschedule,\n * dead letter) that throws or times out may have committed too, so nothing\n * follows it: the job is `abandoned`, and a later claim finds it as that\n * transition left it. Inserts already made stay.\n *\n * @throws {WebhookDeliveryConfigError} for a limit or cycle option that is\n * not positive and finite (R4).\n * @throws {WebhookFanOutError} `options_invalid` for a missing port or\n * option; `fan_out_store_failed` or `fan_out_store_timeout` when the claim\n * fails; `clock_invalid` for a failing clock.\n */\nexport async function runWebhookFanOutCycle(options: WebhookFanOutCycleOptions): Promise<WebhookFanOutCycleResult> {\n\tconst config = readConfig(options);\n\tconst counters: Counters = { claimed: 0, completed: 0, deferred: 0, rescheduled: 0, deadLettered: 0, leaseLost: 0, abandoned: 0, intentsInserted: 0, denialsRecorded: 0 };\n\tconst nowMs = readFanOutClock(config.clock);\n\tconst claimed = await bounded(config, nowMs, (callOptions) => config.deliveries.claimFanOutJobs({\n\t\tworkerId: config.workerId,\n\t\tleaseDurationMs: config.leaseDurationMs,\n\t\tlimit: config.batchSize,\n\t\tnow: new Date(nowMs),\n\t}, callOptions));\n\tif (!claimed.ok) throw fanOutError(claimed.reason === \"timeout\" ? \"fan_out_store_timeout\" : \"fan_out_store_failed\", \"claimFanOutJobs\");\n\tconst jobs = readClaimedJobs(claimed.value);\n\tif (jobs === undefined) throw fanOutError(\"fan_out_store_failed\", \"claimFanOutJobs\");\n\tcounters.claimed = jobs.length;\n\t// The expiry this worker asked for; the store sets it from the same `now`.\n\tconst claimedUntilMs = nowMs + config.leaseDurationMs;\n\tfor (const entry of jobs) {\n\t\tif (config.signal?.aborted) break;\n\t\t// A record whose identity or lease cannot be read cannot be named by a\n\t\t// fenced write, and one leased to another owner is not this worker's:\n\t\t// either is left for lease expiry, with nothing written.\n\t\tif (entry === undefined || entry.header.lease.owner !== config.workerId) {\n\t\t\tcounters.abandoned += 1;\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\t// A readable header with a body that cannot be read (A2): the job can\n\t\t\t// never be processed, so it ends now through the fenced dead-letter\n\t\t\t// transition, instead of returning to pending on every lease expiry.\n\t\t\t// Its processing deadline is in the body, so it is unknown here; the\n\t\t\t// store still caps a renewal at it.\n\t\t\tif (entry.job === undefined) {\n\t\t\t\tawait deadLetter(config, jobLease(config, entry.header, claimedUntilMs, Infinity), counters, \"job_unreadable\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait processJob(config, entry.job, jobLease(config, entry.header, claimedUntilMs, entry.job.processingDeadlineMs), counters);\n\t\t} catch (stopped) {\n\t\t\t// A refused renewal: the lease is gone, and nothing more is written for this job.\n\t\t\tif (stopped !== LEASE_LOST) throw stopped;\n\t\t\tcounters.leaseLost += 1;\n\t\t}\n\t}\n\treturn freeze({ ...counters });\n}\n\n/** A port call bounded by `portTimeoutMs` only: the claim, and the dead-letter transition. */\nfunction bounded<T>(config: Config, nowMs: number, run: (options: WebhookCallOptions) => Promise<T>): Promise<BoundedOutcome<T>> {\n\treturn boundedCall(nowMs, config.limits.portTimeoutMs, config.signal, run, () => readFanOutClock(config.clock));\n}\n\n/**\n * The lease this worker holds on one claimed job: the fence every write for\n * it carries (its `eventId`, this worker, the claim's fence), the expiry\n * this worker last asked for, on its own clock, and the job's processing\n * deadline (`Infinity` when the body that holds it could not be read).\n */\ninterface JobLease {\n\treadonly parent: WebhookFanOutJobFence;\n\texpiresAtMs: number;\n\treadonly deadlineMs: number;\n}\n\nfunction jobLease(config: Config, header: ClaimedHeader, expiresAtMs: number, deadlineMs: number): JobLease {\n\treturn { parent: freeze({ eventId: header.eventId, owner: config.workerId, fence: header.lease.fence }), expiresAtMs, deadlineMs };\n}\n\n/**\n * Thrown by {@link keepLease} when the store refuses a renewal, and caught\n * only by `runWebhookFanOutCycle`'s loop: it unwinds the job's processing\n * at once, so nothing more is written for that job. A package-owned object,\n * so no port can throw it.\n */\nconst LEASE_LOST: object = freeze(Object.create(null) as object);\n\n/** Renew when less than this many `portTimeoutMs` of the lease is left: the renewal, then the call it precedes. */\nconst RENEW_MARGIN_CALLS = 2;\n\n/**\n * Keep the job's lease for the next call (see \"Lease renewal\" above). Renews\n * when less than `RENEW_MARGIN_CALLS * portTimeoutMs` is left. Throws\n * {@link LEASE_LOST} on a refusal; carries on when the renewal's outcome is\n * unknown.\n */\nasync function keepLease(config: Config, lease: JobLease): Promise<void> {\n\tconst nowMs = readFanOutClock(config.clock);\n\tif (lease.expiresAtMs - nowMs >= RENEW_MARGIN_CALLS * config.limits.portTimeoutMs) return;\n\tconst { parent } = lease;\n\tconst renewed = await bounded(config, nowMs, (callOptions) => config.deliveries.renewFanOutJobLease({\n\t\teventId: parent.eventId,\n\t\towner: parent.owner,\n\t\tfence: parent.fence,\n\t\tnow: new Date(nowMs),\n\t\tleaseDurationMs: config.leaseDurationMs,\n\t}, callOptions));\n\tif (renewed.ok && renewed.value === true) {\n\t\t// The store's rule: never shorter than before, never past the processing deadline.\n\t\tconst untilMs = mathMin(nowMs + config.leaseDurationMs, lease.deadlineMs);\n\t\tif (untilMs > lease.expiresAtMs) lease.expiresAtMs = untilMs;\n\t\treturn;\n\t}\n\tif (renewed.ok && renewed.value === false) throw LEASE_LOST;\n}\n\n/** One job being processed: its lease and its persisted processing deadline. */\ninterface JobRun {\n\treadonly config: Config;\n\treadonly job: ClaimedJob;\n\treadonly lease: JobLease;\n\treadonly parent: WebhookFanOutJobFence;\n\treadonly deadlineMs: number;\n\treadonly counters: Counters;\n}\n\ntype JobOutcome<T> = BoundedOutcome<T> | { readonly ok: false; readonly reason: \"deadline\" };\n\n/**\n * A port call made while processing a job (R4). It is not made at all once\n * the job's processing deadline has passed, and otherwise it is bounded by\n * the smaller of `portTimeoutMs` and the job's remaining lifetime, so its\n * absolute `deadline`, which the store checks at its write, is never later\n * than the processing deadline. The job's lease is renewed first when it\n * must be (`keepLease`), so the call can finish inside the lease.\n */\nasync function jobCall<T>(run: JobRun, call: (options: WebhookCallOptions, nowMs: number) => Promise<T>): Promise<JobOutcome<T>> {\n\tif (!(run.deadlineMs - readFanOutClock(run.config.clock) > 0)) return { ok: false, reason: \"deadline\" };\n\tawait keepLease(run.config, run.lease);\n\tconst nowMs = readFanOutClock(run.config.clock);\n\tconst remainingMs = run.deadlineMs - nowMs;\n\tif (!(remainingMs > 0)) return { ok: false, reason: \"deadline\" };\n\tconst timeoutMs = remainingMs < run.config.limits.portTimeoutMs ? remainingMs : run.config.limits.portTimeoutMs;\n\treturn boundedCall(nowMs, timeoutMs, run.config.signal, (options) => call(options, nowMs), () => readFanOutClock(run.config.clock));\n}\n\nfunction failureDiagnostic(reason: \"threw\" | \"timeout\" | \"aborted\" | \"deadline\", unavailable: WebhookDiagnosticCode): WebhookDiagnosticCode {\n\tif (reason === \"deadline\") return \"processing_deadline_exceeded\";\n\treturn reason === \"timeout\" ? \"port_timeout\" : unavailable;\n}\n\ntype Decision =\n\t| { readonly kind: \"allow\" }\n\t| { readonly kind: \"deny\"; readonly code: WebhookAdmissionDenialCode }\n\t| { readonly kind: \"decided\" }\n\t| { readonly kind: \"unavailable\"; readonly diagnostic: WebhookDiagnosticCode };\n\n/** Why processing a job stopped early. */\ntype Stop =\n\t| { readonly kind: \"lease_lost\" }\n\t| { readonly kind: \"past_horizon\" }\n\t| { readonly kind: \"failed\"; readonly diagnostic: WebhookDiagnosticCode };\n\nasync function processJob(config: Config, job: ClaimedJob, lease: JobLease, counters: Counters): Promise<void> {\n\t// Both are finite: `readClaimedJobs` refuses a body whose dates do not parse.\n\tconst deadlineMs = job.processingDeadlineMs;\n\tconst run: JobRun = { config, job, lease, parent: lease.parent, deadlineMs, counters };\n\tconst nowMs = readFanOutClock(config.clock);\n\n\t// R4: the processing deadline was persisted when the job was created.\n\tif (nowMs >= deadlineMs) return deadLetterRun(run, \"processing_deadline_exceeded\");\n\n\t// R1: the completeness boundary. Nothing is decided for this event until\n\t// no revision written from now on can take effect at or before recordedAt.\n\tconst settleAtMs = job.recordedAtMs + config.settleMs;\n\tif (nowMs < settleAtMs) {\n\t\tif (settleAtMs >= deadlineMs) return deadLetterRun(run, \"processing_deadline_exceeded\");\n\t\treturn reschedule(run, settleAtMs, \"eligibility_unsettled\", \"deferred\");\n\t}\n\n\tconst listed = await jobCall(run, (callOptions) => config.subscriptions.listEligibilityRevisions(\n\t\t{ tenantId: job.tenantId, spaceId: job.spaceId, recordedAt: job.event.recordedAt },\n\t\tcallOptions,\n\t));\n\tif (!listed.ok) return retryOrDeadLetter(run, failureDiagnostic(listed.reason, \"subscription_store_unavailable\"));\n\tconst revisions = readRevisions(listed.value);\n\tif (revisions === undefined) return retryOrDeadLetter(run, \"subscription_store_unavailable\");\n\n\tlet incomplete: WebhookDiagnosticCode | undefined;\n\tfor (const revision of revisions) {\n\t\tif (!isEligible(revision, job)) continue;\n\t\tconst decision = await decide(run, revision);\n\t\tif (decision.kind === \"decided\") continue;\n\t\tif (decision.kind === \"unavailable\") {\n\t\t\t// A store failure or the deadline stops the job; an admission outage\n\t\t\t// leaves this pair open and moves on to the next one.\n\t\t\tif (decision.diagnostic === \"processing_deadline_exceeded\" || decision.diagnostic === \"delivery_store_unavailable\") {\n\t\t\t\treturn retryOrDeadLetter(run, decision.diagnostic);\n\t\t\t}\n\t\t\tincomplete ??= decision.diagnostic;\n\t\t\tcontinue;\n\t\t}\n\t\tconst stop = decision.kind === \"allow\" ? await insertIntent(run, revision) : await recordDenial(run, revision, decision.code);\n\t\tif (stop === undefined) continue;\n\t\tif (stop.kind === \"lease_lost\") {\n\t\t\t// Another worker holds the job now; this one writes nothing more for it.\n\t\t\tcounters.leaseLost += 1;\n\t\t\treturn;\n\t\t}\n\t\tif (stop.kind === \"past_horizon\") return deadLetterRun(run, \"processing_deadline_exceeded\");\n\t\tif (stop.diagnostic === \"intent_build_failed\") {\n\t\t\tincomplete ??= stop.diagnostic;\n\t\t\tcontinue;\n\t\t}\n\t\treturn retryOrDeadLetter(run, stop.diagnostic);\n\t}\n\tif (incomplete !== undefined) return retryOrDeadLetter(run, incomplete);\n\n\t// `jobCall` rechecks the deadline here, and the store checks the call deadline again at its write.\n\tconst done = await jobCall(run, (callOptions, now) =>\n\t\tconfig.deliveries.completeFanOutJob({ eventId: job.eventId, owner: run.parent.owner, fence: run.parent.fence, now: new Date(now) }, callOptions));\n\t// Only a completion that was never sent is followed by the dead letter. One\n\t// that threw or timed out may have committed, so nothing follows it: the\n\t// job is `abandoned`, and if it is still pending a later claim finds it\n\t// past its deadline and dead-letters it then.\n\tif (!done.ok && done.reason === \"deadline\") return deadLetterRun(run, \"processing_deadline_exceeded\");\n\tsettleCount(done, counters, \"completed\");\n}\n\n/** An `active` revision in the job's own scope whose patterns match the event type. */\nfunction isEligible(revision: WebhookEligibilityRevision, job: ClaimedJob): boolean {\n\tif (revision.status !== \"active\") return false;\n\t// Decision 9: a job reads revisions only for its own tenant and space.\n\tif (revision.tenantId !== job.tenantId || revision.spaceId !== job.spaceId) return false;\n\tfor (const pattern of revision.eventTypePatterns) {\n\t\tif (matchesWebhookEventTypePattern(pattern, job.event.eventType)) return true;\n\t}\n\treturn false;\n}\n\nfunction actorRequiredFor(config: Config, job: ClaimedJob, revision: WebhookEligibilityRevision): boolean {\n\tconst required = config.actorRequired;\n\tif (typeof required === \"boolean\") return required;\n\ttry {\n\t\t// Fail closed: only a literal `false` waives the actor.\n\t\treturn apply(required, undefined, [freeze({\n\t\t\tsubscriptionId: revision.subscriptionId,\n\t\t\teligibilityRevision: revision.revision,\n\t\t\ttenantId: job.tenantId,\n\t\t\tspaceId: job.spaceId,\n\t\t\tevent: job.event,\n\t\t})]) !== false;\n\t} catch {\n\t\treturn true;\n\t}\n}\n\nasync function decide(run: JobRun, revision: WebhookEligibilityRevision): Promise<Decision> {\n\tconst { config, job } = run;\n\t// A pair with an intent or a denial (their tombstone) is decided: a retry\n\t// or a re-claim does not ask admission again, so an admission outage\n\t// after the decision cannot hold the job open.\n\tconst marker = await jobCall(run, (callOptions) => config.deliveries.readTombstone(\n\t\t{ tenantId: job.tenantId, spaceId: job.spaceId, subscriptionId: revision.subscriptionId, eventId: job.eventId },\n\t\tcallOptions,\n\t));\n\tif (!marker.ok) return { kind: \"unavailable\", diagnostic: failureDiagnostic(marker.reason, \"delivery_store_unavailable\") };\n\tconst decided = readDecided(marker.value);\n\tif (decided === undefined) return { kind: \"unavailable\", diagnostic: \"delivery_store_unavailable\" };\n\tif (decided === \"decided\") return { kind: \"decided\" };\n\n\t// Decision 5: suppressed and legacy absence are both `unavailable` for a\n\t// revision that needs the actor; admission is not asked.\n\tif (job.actor.state !== \"present\" && actorRequiredFor(config, job, revision)) {\n\t\treturn { kind: \"unavailable\", diagnostic: \"admission_unavailable\" };\n\t}\n\tconst answer = await jobCall(run, (callOptions) => config.admission.admit({\n\t\tsubscriptionId: revision.subscriptionId,\n\t\teligibilityRevision: revision.revision,\n\t\tevent: job.event,\n\t\tfacts: job.facts,\n\t\tactor: job.actor,\n\t}, callOptions));\n\t// Decision 4: a throw or a timeout is `unavailable`, and no intent is written.\n\tif (!answer.ok) return { kind: \"unavailable\", diagnostic: failureDiagnostic(answer.reason, \"admission_unavailable\") };\n\t// Total: an answer that cannot be read is `unavailable`, never `allow`.\n\tconst decision = normalizeWebhookAdmissionDecision(answer.value);\n\tif (decision.decision === \"allow\") return { kind: \"allow\" };\n\tif (decision.decision === \"deny\") return { kind: \"deny\", code: decision.code };\n\treturn { kind: \"unavailable\", diagnostic: \"admission_unavailable\" };\n}\n\nconst INSERT_OUTCOMES = freeze([\"inserted\", \"already_present\", \"lease_lost\", \"past_horizon\"] as const);\n\n/** Read a fenced insert's answer: `\"inserted\"`, `undefined` to continue, or why to stop. */\nfunction insertStop(outcome: JobOutcome<unknown>): Stop | undefined | \"inserted\" {\n\tif (!outcome.ok) return { kind: \"failed\", diagnostic: failureDiagnostic(outcome.reason, \"delivery_store_unavailable\") };\n\tconst answer = readOutcome(outcome.value, INSERT_OUTCOMES);\n\tif (answer === \"inserted\") return \"inserted\";\n\tif (answer === \"already_present\") return undefined;\n\tif (answer === \"lease_lost\") return { kind: \"lease_lost\" };\n\tif (answer === \"past_horizon\") return { kind: \"past_horizon\" };\n\treturn { kind: \"failed\", diagnostic: \"delivery_store_unavailable\" };\n}\n\nasync function insertIntent(run: JobRun, revision: WebhookEligibilityRevision): Promise<Stop | undefined> {\n\tconst { config, job } = run;\n\tlet deliveryId: string;\n\tlet body: string;\n\ttry {\n\t\tdeliveryId = apply(config.createDeliveryId, undefined, [freeze({ subscriptionId: revision.subscriptionId, eventId: job.eventId })]) as string;\n\t\tif (typeof deliveryId !== \"string\") throw fanOutError(\"options_invalid\", \"createDeliveryId\");\n\t\tbody = renderWebhookDeliveryBodyV1({\n\t\t\tjob,\n\t\t\tsubscription: { subscriptionId: revision.subscriptionId, tenantId: revision.tenantId, spaceId: revision.spaceId },\n\t\t\tpolicy: config.policy,\n\t\t\tscopePredicate: config.scopePredicate,\n\t\t\tdeliveryId,\n\t\t}).rawBody;\n\t} catch {\n\t\treturn { kind: \"failed\", diagnostic: \"intent_build_failed\" };\n\t}\n\t// `jobCall` refuses to start once the deadline has passed and caps the call deadline at it.\n\tconst outcome = await jobCall(run, (callOptions, nowMs) => config.deliveries.insertDeliveryIntent({\n\t\tdeliveryId,\n\t\tsubscriptionId: revision.subscriptionId,\n\t\teventId: job.eventId,\n\t\ttenantId: job.tenantId,\n\t\tspaceId: job.spaceId,\n\t\teligibilityRevision: revision.revision,\n\t\tbody,\n\t\tavailableAt: isoOf(nowMs),\n\t\tprocessingDeadline: isoOf(nowMs + config.limits.deliveryDeadlineMs),\n\t\tcreatedAt: isoOf(nowMs),\n\t}, run.parent, callOptions));\n\tconst stop = insertStop(outcome);\n\tif (stop === \"inserted\") {\n\t\trun.counters.intentsInserted += 1;\n\t\treturn undefined;\n\t}\n\treturn stop;\n}\n\nasync function recordDenial(run: JobRun, revision: WebhookEligibilityRevision, code: WebhookAdmissionDenialCode): Promise<Stop | undefined> {\n\tconst { config, job } = run;\n\tconst outcome = await jobCall(run, (callOptions, nowMs) => config.deliveries.recordAdmissionDenial({\n\t\tsubscriptionId: revision.subscriptionId,\n\t\teventId: job.eventId,\n\t\ttenantId: job.tenantId,\n\t\tspaceId: job.spaceId,\n\t\teligibilityRevision: revision.revision,\n\t\tcode,\n\t\trecordedAt: isoOf(nowMs),\n\t}, run.parent, callOptions));\n\tconst stop = insertStop(outcome);\n\tif (stop === \"inserted\") {\n\t\trun.counters.denialsRecorded += 1;\n\t\treturn undefined;\n\t}\n\treturn stop;\n}\n\n/**\n * Count a fenced transition. Only a literal `true` is done and a literal\n * `false` is a lost lease; anything else, a failed call included, leaves the\n * job for lease expiry. The comparisons run no code of the value.\n */\nfunction settleCount(outcome: JobOutcome<unknown>, counters: Counters, done: \"completed\" | \"deferred\" | \"rescheduled\" | \"deadLettered\"): void {\n\tif (outcome.ok && outcome.value === true) counters[done] += 1;\n\telse if (outcome.ok && outcome.value === false) counters.leaseLost += 1;\n\telse counters.abandoned += 1;\n}\n\nasync function retryOrDeadLetter(run: JobRun, diagnostic: WebhookDiagnosticCode): Promise<void> {\n\tconst { config, job } = run;\n\tconst nowMs = readFanOutClock(config.clock);\n\tif (nowMs >= run.deadlineMs) return deadLetterRun(run, \"processing_deadline_exceeded\");\n\tconst attempt = job.attemptCount + 1;\n\tif (attempt >= config.limits.maxFanOutAttempts) return deadLetterRun(run, diagnostic);\n\tlet delayMs: number;\n\ttry {\n\t\tdelayMs = apply(config.retryDelay, undefined, [attempt]) as number;\n\t} catch {\n\t\tdelayMs = NaN;\n\t}\n\t// A retry delay that is not a non-negative finite number falls back to\n\t// the longest configured delay rather than retrying at once.\n\tif (typeof delayMs !== \"number\" || !numberIsFinite(delayMs) || delayMs < 0) {\n\t\tconst delays = config.limits.fanOutRetryDelaysMs;\n\t\tdelayMs = delays[delays.length - 1]!;\n\t}\n\tconst availableAtMs = nowMs + delayMs;\n\tif (availableAtMs >= run.deadlineMs) return deadLetterRun(run, \"processing_deadline_exceeded\");\n\treturn reschedule(run, availableAtMs, diagnostic, \"rescheduled\");\n}\n\nasync function reschedule(run: JobRun, availableAtMs: number, diagnostic: WebhookDiagnosticCode, done: \"deferred\" | \"rescheduled\"): Promise<void> {\n\tconst { config, job, parent } = run;\n\tconst outcome = await jobCall(run, (callOptions, nowMs) => config.deliveries.rescheduleFanOutJob({\n\t\teventId: job.eventId,\n\t\towner: parent.owner,\n\t\tfence: parent.fence,\n\t\tnow: new Date(nowMs),\n\t\tavailableAt: new Date(availableAtMs),\n\t\tdiagnostic,\n\t}, callOptions));\n\t// As for completion: only a reschedule that was never sent is followed by\n\t// the dead letter; one that threw or timed out may have committed.\n\tif (!outcome.ok && outcome.reason === \"deadline\") return deadLetterRun(run, \"processing_deadline_exceeded\");\n\tsettleCount(outcome, run.counters, done);\n}\n\nfunction deadLetterRun(run: JobRun, diagnostic: WebhookDiagnosticCode): Promise<void> {\n\treturn deadLetter(run.config, run.lease, run.counters, diagnostic);\n}\n\n/**\n * The fenced dead-letter transition, bounded by `portTimeoutMs` alone: it is\n * how a job past its deadline ends, and how a job whose body cannot be read\n * ends (`job_unreadable`). It needs only the job's fence, never its body.\n */\nasync function deadLetter(config: Config, lease: JobLease, counters: Counters, diagnostic: WebhookDiagnosticCode): Promise<void> {\n\tawait keepLease(config, lease);\n\tconst parent = lease.parent;\n\tconst nowMs = readFanOutClock(config.clock);\n\tconst outcome = await bounded(config, nowMs, (callOptions) => config.deliveries.deadLetterFanOutJob({\n\t\teventId: parent.eventId,\n\t\towner: parent.owner,\n\t\tfence: parent.fence,\n\t\tnow: new Date(nowMs),\n\t\tdiagnostic,\n\t}, callOptions));\n\tsettleCount(outcome, counters, \"deadLettered\");\n}\n","import { buildWebhookRequestHeaders } from \"./headers\";\nimport type { WebhookResolvedAddress, WebhookTransportResult, WebhookVettedDestination } from \"./ports\";\nimport {\n\tdateParse,\n\tfreeze,\n\tfrozenList,\n\tisArray,\n\tisOneOf,\n\tisPlainRecord,\n\tnumberIsFinite,\n\tnumberIsSafeInteger,\n\treadOwn,\n\trecord,\n\ttype Fail,\n} from \"./snapshot\";\nimport type { WebhookSubscriptionStatus } from \"./types\";\n\n/*\n * Reading what a port returned, for the delivery cycle. The same rules as\n * src/fan-out-read.ts: own data properties only, read through descriptors\n * (an accessor is refused uncalled), copied into package-owned frozen\n * values, one try/catch per reader, and whatever a reader catches is\n * dropped unread. Anything that cannot be read is `undefined`, and the\n * cycle maps that to a fixed code.\n */\n\nconst REFUSED = freeze(Object.create(null) as object);\nconst refuse: Fail = () => {\n\tthrow REFUSED;\n};\n\nfunction raw(target: object, key: string): unknown {\n\treturn readOwn(target, key, key, refuse);\n}\n\nfunction plain(value: unknown): object {\n\tif (!isPlainRecord(value)) throw REFUSED;\n\treturn value;\n}\n\nfunction nonEmpty(value: unknown): string {\n\tif (typeof value !== \"string\" || value === \"\") throw REFUSED;\n\treturn value;\n}\n\nfunction whole(value: unknown, min: number): number {\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < min) throw REFUSED;\n\treturn value;\n}\n\nfunction instantMs(value: unknown): number {\n\tconst ms = dateParse(nonEmpty(value));\n\tif (!numberIsFinite(ms)) throw REFUSED;\n\treturn ms;\n}\n\n// ---------------------------------------------------------------------------\n// Claimed intents\n// ---------------------------------------------------------------------------\n\n/** What names a claimed intent and its lease: all a fenced settlement needs. */\nexport interface ClaimedIntentHeader {\n\treadonly deliveryId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly lease: { readonly owner: string; readonly fence: number };\n}\n\n/** A claimed intent as the cycle uses it, every field read and validated. */\nexport interface ClaimedIntent extends ClaimedIntentHeader {\n\treadonly subscriptionId: string;\n\treadonly eventId: string;\n\t/** The eligibility revision fan-out bound the intent to (decision 3); dispatch compares it with the snapshot's `statusSinceRevision`. */\n\treadonly eligibilityRevision: number;\n\t/** The rendered v1 body, signed and sent byte for byte. */\n\treadonly body: string;\n\treadonly attemptCount: number;\n\treadonly processingDeadlineMs: number;\n\treadonly leaseExpiresAtMs: number;\n}\n\n/**\n * One entry of a claim result. `undefined`: identity or lease cannot be\n * read, so no fenced write can name it. `intent: undefined`: the header\n * was read but the rest cannot be, so the cycle dead-letters it by its\n * header (`intent_unreadable`).\n */\nexport type ClaimedIntentEntry = { readonly header: ClaimedIntentHeader; readonly intent: ClaimedIntent | undefined } | undefined;\n\n/** More intents than any claim limit a cycle sends; a longer answer is not a claim result. */\nconst MAX_CLAIMED = 100_000;\n\n/** A placeholder `v1` value, used only to check that the intent's ids are header-safe before anything is signed. */\nconst PLACEHOLDER_SIGNATURE = `v1=${\"0\".repeat(64)}`;\n\nfunction readIntentHeader(item: unknown): ClaimedIntentHeader {\n\tconst intent = plain(item);\n\tconst lease = plain(raw(intent, \"lease\"));\n\treturn freeze({\n\t\tdeliveryId: nonEmpty(raw(intent, \"deliveryId\")),\n\t\ttenantId: nonEmpty(raw(intent, \"tenantId\")),\n\t\tspaceId: nonEmpty(raw(intent, \"spaceId\")),\n\t\tlease: freeze({ owner: nonEmpty(raw(lease, \"owner\")), fence: whole(raw(lease, \"fence\"), 0) }),\n\t});\n}\n\nfunction readIntentBody(item: unknown, header: ClaimedIntentHeader): ClaimedIntent {\n\tconst intent = plain(item);\n\tconst body = raw(intent, \"body\");\n\tif (typeof body !== \"string\") throw REFUSED;\n\tconst eventId = nonEmpty(raw(intent, \"eventId\"));\n\tconst attemptCount = whole(raw(intent, \"attemptCount\"), 0);\n\t// An intent whose ids cannot go into the unsigned headers can never be\n\t// sent; refusing it here keeps a header error from being blamed on the signer.\n\tbuildWebhookRequestHeaders({ signature: PLACEHOLDER_SIGNATURE, timestampSeconds: 0, eventId, deliveryId: header.deliveryId, attempt: attemptCount + 1 });\n\treturn freeze({\n\t\t...header,\n\t\tsubscriptionId: nonEmpty(raw(intent, \"subscriptionId\")),\n\t\teventId,\n\t\teligibilityRevision: whole(raw(intent, \"eligibilityRevision\"), 1),\n\t\tbody,\n\t\tattemptCount,\n\t\tprocessingDeadlineMs: instantMs(raw(intent, \"processingDeadline\")),\n\t\tleaseExpiresAtMs: instantMs(raw(plain(raw(intent, \"lease\")), \"expiresAt\")),\n\t});\n}\n\n/**\n * The claim result: `undefined` when the list itself cannot be read, and\n * otherwise one {@link ClaimedIntentEntry} per record. Each record's header\n * is read first, in its own try/catch, and its body after, in another.\n */\nexport function readClaimedIntents(value: unknown): readonly ClaimedIntentEntry[] | undefined {\n\tconst items: unknown[] = [];\n\ttry {\n\t\tif (!isArray(value)) return undefined;\n\t\tconst length = raw(value, \"length\");\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 0 || length > MAX_CLAIMED) return undefined;\n\t\tfor (let index = 0; index < length; index += 1) items.push(raw(value, `${index}`));\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn frozenList(items.map((item): ClaimedIntentEntry => {\n\t\tlet header: ClaimedIntentHeader;\n\t\ttry {\n\t\t\theader = readIntentHeader(item);\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\treturn freeze({ header, intent: readIntentBody(item, header) });\n\t\t} catch {\n\t\t\treturn freeze({ header, intent: undefined });\n\t\t}\n\t}));\n}\n\n// ---------------------------------------------------------------------------\n// Subscription state\n// ---------------------------------------------------------------------------\n\n/** The delivery configuration the cycle signs and addresses one attempt with. */\nexport interface DispatchConfiguration {\n\treadonly version: number;\n\treadonly destinationUrl: string;\n\treadonly signatureScheme: \"v1\";\n\treadonly secretRef: string;\n}\n\n/**\n * What a `readSubscription` answer means for one intent.\n * `not_in_scope`: `null` (no such subscription in the intent's tenant and\n * space), or an answer naming another subscription, tenant or space.\n * `unreadable`: anything else that is not a well-formed snapshot, a\n * missing or malformed `statusSinceRevision` included.\n */\nexport type SubscriptionRead =\n\t| {\n\t\treadonly kind: \"ok\";\n\t\treadonly status: WebhookSubscriptionStatus;\n\t\t/** The snapshot's `statusSinceRevision`, read from the same answer as `status`. */\n\t\treadonly statusSinceRevision: number;\n\t\treadonly configuration: DispatchConfiguration;\n\t}\n\t| { readonly kind: \"not_in_scope\" }\n\t| { readonly kind: \"unreadable\" };\n\nconst STATUSES = freeze([\"active\", \"paused\", \"deleted\"] as const);\nconst NOT_IN_SCOPE: SubscriptionRead = freeze({ kind: \"not_in_scope\" });\nconst UNREADABLE: SubscriptionRead = freeze({ kind: \"unreadable\" });\n\n/**\n * Read a `readSubscription` answer for the intent `owner`. The snapshot and\n * its configuration must both name the intent's subscription, tenant and\n * space (decision 9: the worker refuses an intent whose subscription now\n * names another tenant or space).\n */\nexport function readSubscriptionFor(value: unknown, owner: { readonly subscriptionId: string; readonly tenantId: string; readonly spaceId: string }): SubscriptionRead {\n\ttry {\n\t\tif (value === null) return NOT_IN_SCOPE;\n\t\tconst snapshot = plain(value);\n\t\tconst configuration = plain(raw(snapshot, \"configuration\"));\n\t\tconst named = [raw(snapshot, \"subscriptionId\"), raw(snapshot, \"tenantId\"), raw(snapshot, \"spaceId\"),\n\t\t\traw(configuration, \"subscriptionId\"), raw(configuration, \"tenantId\"), raw(configuration, \"spaceId\")];\n\t\tfor (const name of named) nonEmpty(name);\n\t\tif (named[0] !== owner.subscriptionId || named[1] !== owner.tenantId || named[2] !== owner.spaceId\n\t\t\t|| named[3] !== owner.subscriptionId || named[4] !== owner.tenantId || named[5] !== owner.spaceId) {\n\t\t\treturn NOT_IN_SCOPE;\n\t\t}\n\t\tconst status = raw(snapshot, \"status\");\n\t\tif (!isOneOf(STATUSES, status)) return UNREADABLE;\n\t\tif (raw(configuration, \"signatureScheme\") !== \"v1\") return UNREADABLE;\n\t\treturn freeze({\n\t\t\tkind: \"ok\",\n\t\t\tstatus: status as WebhookSubscriptionStatus,\n\t\t\tstatusSinceRevision: whole(raw(snapshot, \"statusSinceRevision\"), 1),\n\t\t\tconfiguration: freeze({\n\t\t\t\tversion: whole(raw(configuration, \"version\"), 1),\n\t\t\t\tdestinationUrl: nonEmpty(raw(configuration, \"destinationUrl\")),\n\t\t\t\tsignatureScheme: \"v1\" as const,\n\t\t\t\tsecretRef: nonEmpty(raw(configuration, \"secretRef\")),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn UNREADABLE;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Destination, signature and transport results\n// ---------------------------------------------------------------------------\n\n/** A resolver answer copied into package-owned frozen values. */\nexport type ResolutionRead =\n\t| { readonly ok: true; readonly destination: WebhookVettedDestination }\n\t| { readonly ok: false; readonly code: \"invalid_url\" | \"private_address\" | \"dns_failure\" };\n\nconst RESOLUTION_CODES = freeze([\"invalid_url\", \"private_address\", \"dns_failure\"] as const);\n/** The most addresses a destination may carry (the resolver's own cap). */\nconst MAX_ADDRESSES = 32;\n\n/** A resolver answer, or `undefined` when it cannot be read. */\nexport function readResolution(value: unknown): ResolutionRead | undefined {\n\ttry {\n\t\tconst answer = plain(value);\n\t\tconst ok = raw(answer, \"ok\");\n\t\tif (ok === false) {\n\t\t\tconst code = raw(answer, \"code\");\n\t\t\treturn isOneOf(RESOLUTION_CODES, code) ? freeze({ ok: false as const, code: code as \"invalid_url\" | \"private_address\" | \"dns_failure\" }) : undefined;\n\t\t}\n\t\tif (ok !== true) return undefined;\n\t\tconst destination = plain(raw(answer, \"destination\"));\n\t\tif (raw(destination, \"port\") !== 443) return undefined;\n\t\tconst list = raw(destination, \"addresses\");\n\t\tif (!isArray(list)) return undefined;\n\t\tconst length = raw(list, \"length\");\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > MAX_ADDRESSES) return undefined;\n\t\tconst addresses: WebhookResolvedAddress[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst item = plain(raw(list, `${index}`));\n\t\t\tconst family = raw(item, \"family\");\n\t\t\tif (family !== 4 && family !== 6) return undefined;\n\t\t\taddresses.push(record({ address: nonEmpty(raw(item, \"address\")), family }));\n\t\t}\n\t\treturn freeze({\n\t\t\tok: true as const,\n\t\t\tdestination: record<WebhookVettedDestination>({\n\t\t\t\turl: nonEmpty(raw(destination, \"url\")),\n\t\t\t\thostname: nonEmpty(raw(destination, \"hostname\")),\n\t\t\t\tport: 443,\n\t\t\t\taddresses: frozenList(addresses),\n\t\t\t}),\n\t\t});\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Longer than any receipt a package store makes (69 characters); a longer one is not a receipt. */\nconst MAX_RECEIPT_LENGTH = 256;\n\n/**\n * A `beginAttempt` answer: `{ begun: true, receipt }` with a non-empty\n * receipt, `{ begun: false }`, or `undefined` when it is neither. Only a\n * well-formed `begun: true` lets the cycle hand off.\n */\nexport function readBeginAnswer(value: unknown): { readonly begun: true; readonly receipt: string } | { readonly begun: false } | undefined {\n\ttry {\n\t\tconst answer = plain(value);\n\t\tconst begun = raw(answer, \"begun\");\n\t\tif (begun === false) return freeze({ begun: false as const });\n\t\tif (begun !== true) return undefined;\n\t\tconst receipt = nonEmpty(raw(answer, \"receipt\"));\n\t\treturn receipt.length > MAX_RECEIPT_LENGTH ? undefined : freeze({ begun: true as const, receipt });\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** A signer answer: the string it returned, or `undefined`. Its format is checked when the headers are built. */\nexport function readSignature(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nconst OBSERVATION_KINDS = freeze([\"network_error\", \"timeout\", \"dns_failure\", \"invalid_url\", \"private_address\"] as const);\nconst NOT_SENT_REASONS = freeze([\"deadline_expired\", \"aborted\"] as const);\n/** Longer than any `Retry-After` the Node transport returns (128); a longer value is dropped, not truncated. */\nconst MAX_RETRY_AFTER_LENGTH = 256;\n\n/**\n * A transport answer copied into a package-owned frozen value, or\n * `undefined` when it cannot be read. Only `kind`, `status`, `retryAfter`\n * and a `not_sent` reason are read; anything else the transport put on its\n * answer, a response body included, is never read.\n */\nexport function readTransportResult(value: unknown): WebhookTransportResult | undefined {\n\ttry {\n\t\tconst answer = plain(value);\n\t\tconst kind = raw(answer, \"kind\");\n\t\tif (kind === \"response\") {\n\t\t\tconst status = raw(answer, \"status\");\n\t\t\tif (typeof status !== \"number\" || !numberIsSafeInteger(status) || status < 100 || status > 599) return undefined;\n\t\t\tconst retryAfter = raw(answer, \"retryAfter\");\n\t\t\tconst kept = typeof retryAfter === \"string\" && retryAfter.length <= MAX_RETRY_AFTER_LENGTH ? retryAfter : null;\n\t\t\treturn record<WebhookTransportResult>({ kind: \"response\", status, retryAfter: kept });\n\t\t}\n\t\tif (kind === \"not_sent\") {\n\t\t\tconst reason = raw(answer, \"reason\");\n\t\t\treturn isOneOf(NOT_SENT_REASONS, reason) ? record<WebhookTransportResult>({ kind: \"not_sent\", reason: reason as \"deadline_expired\" | \"aborted\" }) : undefined;\n\t\t}\n\t\tif (isOneOf(OBSERVATION_KINDS, kind)) return record<WebhookTransportResult>({ kind: kind as \"network_error\" });\n\t\treturn undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n","import { classifyWebhookDeliveryObservation, type WebhookDeliveryClassification, type WebhookDeliveryObservation } from \"./classify\";\nimport type { WebhookAttemptReasonCode, WebhookDiagnosticCode } from \"./codes\";\nimport { normalizeWebhookDeliveryAuthorizationDecision } from \"./decisions\";\nimport {\n\treadBeginAnswer,\n\treadClaimedIntents,\n\treadResolution,\n\treadSignature,\n\treadSubscriptionFor,\n\treadTransportResult,\n\ttype ClaimedIntent,\n\ttype ClaimedIntentHeader,\n\ttype DispatchConfiguration,\n} from \"./delivery-read\";\nimport { configError, deliveryError, guard } from \"./errors\";\nimport { boundedCall, signalAborted, type BoundedOutcome } from \"./fan-out-call\";\nimport { buildWebhookRequestHeaders } from \"./headers\";\nimport { assertPositiveInteger, resolveWebhookDeliveryLimits, type WebhookDeliveryLimits } from \"./limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookDeliveryAuthorization,\n\tWebhookDeliveryStore,\n\tWebhookDestinationResolver,\n\tWebhookRandomSource,\n\tWebhookRetryDelay,\n\tWebhookSigner,\n\tWebhookSubscriptionStore,\n\tWebhookTransport,\n\tWebhookTransportRequest,\n} from \"./ports\";\nimport { createWebhookRetryDelay } from \"./retry\";\nimport { apply, freeze, mathFloor, mathMax, mathMin, numberIsFinite, primitive, record, timeOf } from \"./snapshot\";\nimport { isoOf } from \"./store-input\";\n\n/*\n * The delivery cycle (ADR 0018 decisions 3, 4, 8 and 10; R2, R4, R6, R7).\n *\n * Check order. For each claimed intent, in this order:\n *\n * 0. The claim: a fenced lease, the intent's fence advanced (store).\n * Then the lease is renewed when less than one whole attempt is left\n * of it (`keepLease`): an intent late in a batch has waited for the\n * ones before it under a lease taken at the claim.\n * 1. Processing deadline, persisted when fan-out created the intent: no\n * call before the handoff (preparation and guard calls, `intentCall`)\n * is started at or after it, and the first call it refuses\n * dead-letters the intent `processing_deadline_exceeded`. Outcome,\n * settlement and attempt-log writes after a handoff are not held to it.\n * 2. `readSubscription` in the intent's tenant and space: not there, or\n * naming another subscription, tenant or space, dead-letters it\n * `subscription_not_in_scope`; paused or deleted cancels it, and so\n * does an active subscription whose `statusSinceRevision` is above the\n * intent's `eligibilityRevision` (paused and resumed since the intent's\n * interval: `subscription_paused`). Otherwise it yields the\n * configuration version `v` this attempt uses.\n * 3. Resolve `v`'s destination and sign the body with `v`'s secret\n * reference (preparation; a refused destination or a failed signer\n * spends an attempt, per decision 10's table, without sending).\n * 4. Guards, immediately before the handoff, with nothing between them but\n * clock reads:\n * a. delivery authorization for this attempt and `v`: revoked cancels,\n * unavailable releases unsent;\n * b. `readSubscription` again: paused, deleted, resumed since the\n * intent's revision or out of scope as in 2;\n * a configuration version other than `v` releases unsent as\n * `configuration_conflict`;\n * c. the transport's deadline: the clock now plus `attemptTimeoutMs`,\n * and at most 4b's start plus `portTimeoutMs + attemptTimeoutMs`,\n * the processing deadline, and the lease's expiry (as claimed or\n * renewed in step 0) less three `portTimeoutMs` (the answer's\n * grace, the outcome write, the settlement);\n * d. `beginAttempt`: in one atomic store step, the lease is still this\n * worker's at this fence and unexpired on the store's clock, and an\n * in-flight attempt entry is written for (deliveryId, fence). The\n * store returns a receipt that only this worker holds.\n * 5. Handoff: `transport.send()` with the signed request. This is the\n * irrevocable point. A change committed after 4b's read (a revocation,\n * a pause, a configuration replacement), or after 4d's begin (a\n * reclaim), may race with the request, which can then reach the old\n * destination with the old secret (R2, decision 3). The transport may\n * still answer `not_sent` when its deadline passed or its signal\n * aborted before it started the request (R3); that attempt is\n * recorded `not_sent` and the intent released.\n * 6. Classify (decision 10), append the attempt's outcome with the\n * receipt (not fenced, so a worker that lost its lease during the\n * request still records it, and nobody else can), then settle under\n * the fence: delivered, retry, dead letter. A settlement the store\n * refuses (lease expired or reclaimed) leaves the intent to be sent\n * again after a reclaim: delivery is at least once.\n *\n * Releases (deferrals) spend no attempt; every deferral, reclaim and\n * configuration conflict counts toward the persisted processing deadline\n * (R4). Each port call before the handoff is bounded by the smaller of\n * `portTimeoutMs` and the intent's remaining lifetime; the transport by its\n * deadline from 4c plus a `portTimeoutMs` grace for its answer; each\n * outcome, settlement and attempt write by `portTimeoutMs`. `boundedCall`\n * accepts no answer that settles at or after its bound, on the injected\n * clock or on the monotonic clock, timed when the port's promise settles,\n * so a late result is dropped and nothing is written from it.\n *\n * A store write that timed out may have committed. The cycle never follows\n * one with a second transition of the intent on the strength of the\n * timeout: a timed-out settlement ends the intent's processing\n * (`abandoned`); a timed-out `beginAttempt` is followed by a release (begin\n * does not change the intent, so the release is the only transition, and a\n * begin that did commit leaves an `in_flight` entry with no request behind\n * it); a timed-out `appendAttempt` is followed by a release, so the log may\n * hold an entry for an attempt that spent nothing, and the next pass logs\n * the same attempt number again.\n */\n\n/** One intent's outcome, as reported to {@link WebhookDeliveryCycleOptions.observe}. */\nexport type WebhookDeliveryCycleResultKind =\n\t| \"delivered\"\n\t| \"retry_scheduled\"\n\t| \"dead_lettered\"\n\t| \"cancelled\"\n\t| \"released\"\n\t| \"lease_lost\"\n\t| \"abandoned\";\n\n/**\n * What the cycle reports for one claimed intent. Every field is an\n * identifier the store already holds, a number, or a fixed code: never a\n * destination, secret reference, signature, header, body or port error.\n */\nexport interface WebhookDeliveryCycleEvent {\n\treadonly deliveryId: string;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly subscriptionId?: string;\n\treadonly eventId?: string;\n\t/** The 1-based attempt number this processing was for. */\n\treadonly attempt?: number;\n\t/** The configuration version the attempt was prepared with, once read. */\n\treadonly configurationVersion?: number;\n\treadonly result: WebhookDeliveryCycleResultKind;\n\t/** `true` once the request was handed to the transport. */\n\treadonly handedOff: boolean;\n\treadonly reason?: WebhookAttemptReasonCode;\n\treadonly diagnostic?: WebhookDiagnosticCode;\n\treadonly httpStatus?: number;\n\t/** 401 or 403: still retried, but usually needing the receiver to act (decision 10). */\n\treadonly receiverActionLikely?: true;\n}\n\n/** Options for {@link runWebhookDeliveryCycle}. */\nexport interface WebhookDeliveryCycleOptions {\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly subscriptions: WebhookSubscriptionStore;\n\treadonly authorization: WebhookDeliveryAuthorization;\n\treadonly signer: WebhookSigner;\n\treadonly resolver: WebhookDestinationResolver;\n\treadonly transport: WebhookTransport;\n\treadonly clock: WebhookClock;\n\t/** The lease owner this worker claims intents as. */\n\treadonly workerId: string;\n\t/**\n\t * Overrides of {@link WebhookDeliveryLimits}, all validated positive and\n\t * finite (R4). Used: `maxDeliveryAttempts`, `deliveryRetryDelaysMs`,\n\t * `retryJitterRatio`, `attemptTimeoutMs`, `portTimeoutMs`, `maxRetryAfterMs`.\n\t */\n\treadonly limits?: Partial<WebhookDeliveryLimits>;\n\t/** Delay before the next attempt; defaults to `deliveryRetryDelaysMs` with jitter from `random`. */\n\treadonly retryDelay?: WebhookRetryDelay;\n\t/** Random source for the default retry delay's jitter; required when `retryDelay` is absent. */\n\treadonly random?: WebhookRandomSource;\n\t/** Intents claimed per cycle. A positive whole number; default 10. */\n\treadonly batchSize?: number;\n\t/**\n\t * Lease on each claimed intent, in ms. A positive whole number above\n\t * `attemptTimeoutMs + 10 * portTimeoutMs` (one whole attempt and the\n\t * renewal before it; see `ATTEMPT_PORT_CALLS`); default 120 000.\n\t */\n\treadonly leaseDurationMs?: number;\n\t/** Called once per claimed intent with fixed-code telemetry. A throw is ignored. */\n\treadonly observe?: (event: WebhookDeliveryCycleEvent) => void;\n\t/** Stops the cycle; intents not yet settled are reclaimed after their leases expire. */\n\treadonly signal?: AbortSignal;\n}\n\n/** What one cycle did. */\nexport interface WebhookDeliveryCycleResult {\n\treadonly claimed: number;\n\treadonly delivered: number;\n\t/** Settled for a later attempt, spending one. */\n\treadonly retried: number;\n\treadonly deadLettered: number;\n\treadonly cancelled: number;\n\t/** Returned to pending unsent, spending no attempt. */\n\treadonly released: number;\n\t/** Intents this worker stopped on because a fenced write found its lease gone. */\n\treadonly leaseLost: number;\n\t/** Intents left for lease expiry: unreadable, another owner's, or whose final write failed. */\n\treadonly abandoned: number;\n\t/** Requests handed to the transport. */\n\treadonly handedOff: number;\n}\n\n/**\n * What may follow the transport's deadline, in units of `portTimeoutMs`: the\n * grace the cycle waits for the transport's answer, then the outcome write\n * and the settlement, each bounded by `portTimeoutMs`. The transport's\n * deadline is kept this far inside the lease, so a request that answers in\n * time can be settled before the lease expires.\n */\nconst SETTLEMENT_WRITES = 3;\n\n/**\n * The port calls one attempt makes besides the transport, each bounded by\n * `portTimeoutMs`: before the handoff, `readSubscription`, the resolver, the\n * signer, authorization, `readSubscription` again and `beginAttempt` (6);\n * after it, the {@link SETTLEMENT_WRITES} (3). Each is cut off at its bound\n * by a timer, so one whole attempt takes about\n * `attemptTimeoutMs + ATTEMPT_PORT_CALLS * portTimeoutMs` at most, more\n * only when timers fire late.\n */\nconst ATTEMPT_PORT_CALLS = 6 + SETTLEMENT_WRITES;\n\n/** Defaults for the cycle's own options. */\nexport const DEFAULT_WEBHOOK_DELIVERY_CYCLE = freeze({\n\tbatchSize: 10,\n\tleaseDurationMs: 120_000,\n});\n\ninterface Clock {\n\treadonly target: object;\n\treadonly now: (...args: never[]) => unknown;\n}\n\ninterface Config {\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly subscriptions: WebhookSubscriptionStore;\n\treadonly authorization: WebhookDeliveryAuthorization;\n\treadonly signer: WebhookSigner;\n\treadonly resolver: WebhookDestinationResolver;\n\treadonly transport: WebhookTransport;\n\treadonly clock: Clock;\n\treadonly workerId: string;\n\treadonly limits: WebhookDeliveryLimits;\n\treadonly retryDelay: WebhookRetryDelay;\n\treadonly batchSize: number;\n\treadonly leaseDurationMs: number;\n\treadonly observe: ((event: WebhookDeliveryCycleEvent) => void) | undefined;\n\treadonly signal: AbortSignal | undefined;\n}\n\nfunction hasMethods(value: unknown, names: readonly string[]): boolean {\n\tif (value === null || typeof value !== \"object\") return false;\n\tfor (const name of names) if (typeof (value as Record<string, unknown>)[name] !== \"function\") return false;\n\treturn true;\n}\n\nfunction positiveWhole(value: unknown, fallback: number, field: string): number {\n\tconst read = primitive(value);\n\tconst resolved = read === undefined ? fallback : read;\n\tassertPositiveInteger(resolved, field);\n\treturn resolved;\n}\n\n/**\n * Read and validate the options. A package error (a limit, a missing random\n * source) passes through with its code; anything else thrown while reading\n * them, by a getter or a Proxy trap, is replaced unread with `options_invalid`.\n */\nfunction readConfig(options: WebhookDeliveryCycleOptions): Config {\n\treturn guard(() => readConfigUnguarded(options), () => deliveryError(\"options_invalid\", \"options\"));\n}\n\nfunction readConfigUnguarded(options: WebhookDeliveryCycleOptions): Config {\n\tif (options === null || typeof options !== \"object\") throw deliveryError(\"options_invalid\", \"options\");\n\tconst limits = resolveWebhookDeliveryLimits(options.limits ?? {});\n\tconst batchSize = positiveWhole(options.batchSize, DEFAULT_WEBHOOK_DELIVERY_CYCLE.batchSize, \"batchSize\");\n\tconst leaseDurationMs = positiveWhole(options.leaseDurationMs, DEFAULT_WEBHOOK_DELIVERY_CYCLE.leaseDurationMs, \"leaseDurationMs\");\n\t// The lease must fit one whole attempt (the calls before the handoff, the\n\t// transport call, its answer's grace, and the outcome and settlement\n\t// writes) after the renewal that precedes it; a shorter one would leave\n\t// an intent too little lease to hand off, on every claim.\n\tif (leaseDurationMs <= limits.attemptTimeoutMs + (ATTEMPT_PORT_CALLS + 1) * limits.portTimeoutMs) throw configError(\"limit_out_of_range\", \"leaseDurationMs\");\n\tif (!hasMethods(options.deliveries, [\"claimDeliveryIntents\", \"renewDeliveryIntentLease\", \"beginAttempt\", \"finishAttempt\", \"appendAttempt\", \"settleDeliveryIntent\"])) {\n\t\tthrow deliveryError(\"options_invalid\", \"deliveries\");\n\t}\n\tif (!hasMethods(options.subscriptions, [\"readSubscription\"])) throw deliveryError(\"options_invalid\", \"subscriptions\");\n\tif (!hasMethods(options.authorization, [\"authorize\"])) throw deliveryError(\"options_invalid\", \"authorization\");\n\tif (!hasMethods(options.signer, [\"sign\"])) throw deliveryError(\"options_invalid\", \"signer\");\n\tif (!hasMethods(options.resolver, [\"resolve\"])) throw deliveryError(\"options_invalid\", \"resolver\");\n\tif (!hasMethods(options.transport, [\"send\"])) throw deliveryError(\"options_invalid\", \"transport\");\n\tif (typeof options.workerId !== \"string\" || options.workerId === \"\") throw deliveryError(\"options_invalid\", \"workerId\");\n\tif (options.observe !== undefined && typeof options.observe !== \"function\") throw deliveryError(\"options_invalid\", \"observe\");\n\tif (options.signal !== undefined && !(options.signal instanceof AbortSignal)) throw deliveryError(\"options_invalid\", \"signal\");\n\tconst clock = options.clock as unknown;\n\tif (clock === null || typeof clock !== \"object\") throw deliveryError(\"options_invalid\", \"clock\");\n\tconst now = (clock as { now?: unknown }).now;\n\tif (typeof now !== \"function\") throw deliveryError(\"options_invalid\", \"clock.now\");\n\tlet retryDelay: WebhookRetryDelay;\n\tif (options.retryDelay !== undefined) {\n\t\tif (typeof options.retryDelay !== \"function\") throw deliveryError(\"options_invalid\", \"retryDelay\");\n\t\tretryDelay = options.retryDelay;\n\t} else {\n\t\tretryDelay = createWebhookRetryDelay({ delaysMs: limits.deliveryRetryDelaysMs, jitterRatio: limits.retryJitterRatio, random: options.random! });\n\t}\n\treturn freeze({\n\t\tdeliveries: options.deliveries,\n\t\tsubscriptions: options.subscriptions,\n\t\tauthorization: options.authorization,\n\t\tsigner: options.signer,\n\t\tresolver: options.resolver,\n\t\ttransport: options.transport,\n\t\tclock: freeze({ target: clock, now: now as (...args: never[]) => unknown }),\n\t\tworkerId: options.workerId,\n\t\tlimits,\n\t\tretryDelay,\n\t\tbatchSize,\n\t\tleaseDurationMs,\n\t\tobserve: options.observe,\n\t\tsignal: options.signal,\n\t});\n}\n\n/** Read the clock; a throw or an invalid time is `clock_invalid`. */\nfunction readClock(clock: Clock): number {\n\tlet value: unknown;\n\ttry {\n\t\tvalue = apply(clock.now, clock.target, []);\n\t} catch {\n\t\tthrow deliveryError(\"clock_invalid\", \"clock\");\n\t}\n\tconst ms = timeOf(value);\n\tif (!numberIsFinite(ms)) throw deliveryError(\"clock_invalid\", \"clock\");\n\treturn ms;\n}\n\ninterface Counters {\n\tclaimed: number;\n\tdelivered: number;\n\tretried: number;\n\tdeadLettered: number;\n\tcancelled: number;\n\treleased: number;\n\tleaseLost: number;\n\tabandoned: number;\n\thandedOff: number;\n}\n\n/**\n * Run one delivery cycle: claim up to `batchSize` pending intents under a\n * fenced lease and process each in turn, in the check order described at\n * the top of this file (and in the README, \"Delivery\"). A claimed record\n * whose `deliveryId`, `tenantId`, `spaceId` or lease cannot be read, or\n * that is leased to another owner, is left for lease expiry (`abandoned`);\n * one whose identity and lease can be read but whose body cannot is\n * dead-lettered as `intent_unreadable`.\n *\n * @throws {WebhookDeliveryConfigError} for a limit or cycle option that is not positive and finite (R4).\n * @throws {WebhookDeliveryError} `options_invalid` for a missing port or\n * option; `delivery_store_failed` or `delivery_store_timeout` when the claim\n * fails; `clock_invalid` for a failing clock.\n */\nexport async function runWebhookDeliveryCycle(options: WebhookDeliveryCycleOptions): Promise<WebhookDeliveryCycleResult> {\n\tconst config = readConfig(options);\n\tconst counters: Counters = { claimed: 0, delivered: 0, retried: 0, deadLettered: 0, cancelled: 0, released: 0, leaseLost: 0, abandoned: 0, handedOff: 0 };\n\tconst nowMs = readClock(config.clock);\n\tconst claimed = await boundedCall(nowMs, config.limits.portTimeoutMs, config.signal, (callOptions) => config.deliveries.claimDeliveryIntents({\n\t\tworkerId: config.workerId,\n\t\tleaseDurationMs: config.leaseDurationMs,\n\t\tlimit: config.batchSize,\n\t\tnow: new Date(nowMs),\n\t}, callOptions), () => readClock(config.clock));\n\tif (!claimed.ok) throw deliveryError(claimed.reason === \"timeout\" ? \"delivery_store_timeout\" : \"delivery_store_failed\", \"claimDeliveryIntents\");\n\tconst entries = readClaimedIntents(claimed.value);\n\tif (entries === undefined) throw deliveryError(\"delivery_store_failed\", \"claimDeliveryIntents\");\n\tcounters.claimed = entries.length;\n\tfor (const entry of entries) {\n\t\tif (config.signal !== undefined && signalAborted(config.signal)) break;\n\t\t// A record whose identity or lease cannot be read cannot be named by a\n\t\t// fenced write, and one leased to another owner is not this worker's.\n\t\tif (entry === undefined) {\n\t\t\tcounters.abandoned += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst run = newRun(config, entry.header, entry.intent, counters);\n\t\tif (entry.header.lease.owner !== config.workerId) {\n\t\t\tfinish(run, \"abandoned\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.intent === undefined) {\n\t\t\tawait settle(run, { kind: \"dead_letter\", reason: \"intent_unreadable\" }, \"dead_lettered\", { diagnostic: \"intent_unreadable\" });\n\t\t\tcontinue;\n\t\t}\n\t\tawait processIntent(run, entry.intent);\n\t}\n\treturn freeze({ ...counters });\n}\n\n/** One claimed intent being processed. */\ninterface Run {\n\treadonly config: Config;\n\treadonly header: ClaimedIntentHeader;\n\treadonly intent: ClaimedIntent | undefined;\n\treadonly counters: Counters;\n\t/** The configuration version read at step 2, once read. */\n\tversion: number | undefined;\n\t/** The lease's expiry as this worker last set it (claim or renewal), on its own clock. */\n\tleaseExpiresAtMs: number;\n\thandedOff: boolean;\n\treported: boolean;\n}\n\nfunction newRun(config: Config, header: ClaimedIntentHeader, intent: ClaimedIntent | undefined, counters: Counters): Run {\n\treturn { config, header, intent, counters, version: undefined, leaseExpiresAtMs: intent === undefined ? NaN : intent.leaseExpiresAtMs, handedOff: false, reported: false };\n}\n\ntype CallFailure = \"threw\" | \"timeout\" | \"aborted\" | \"deadline\";\ntype RunOutcome<T> = BoundedOutcome<T> | { readonly ok: false; readonly reason: \"deadline\" };\n\n/**\n * A port call made before the handoff (R4). It is not made at all once the\n * intent's processing deadline has passed, and otherwise it is bounded by\n * the smaller of `portTimeoutMs` and the intent's remaining lifetime.\n */\nfunction intentCall<T>(run: Run, intent: ClaimedIntent, call: (options: WebhookCallOptions, nowMs: number) => Promise<T>): Promise<RunOutcome<T>> {\n\tconst nowMs = readClock(run.config.clock);\n\tconst remainingMs = intent.processingDeadlineMs - nowMs;\n\tif (!(remainingMs > 0)) return Promise.resolve({ ok: false, reason: \"deadline\" });\n\tconst timeoutMs = mathMin(remainingMs, run.config.limits.portTimeoutMs);\n\treturn boundedCall(nowMs, timeoutMs, run.config.signal, (options) => call(options, nowMs), () => readClock(run.config.clock));\n}\n\n/** A settlement or attempt write: bounded by `portTimeoutMs` alone, so an outcome can be recorded after the deadline. */\nfunction storeWrite<T>(run: Run, call: (options: WebhookCallOptions, nowMs: number) => Promise<T>): Promise<BoundedOutcome<T>> {\n\tconst nowMs = readClock(run.config.clock);\n\treturn boundedCall(nowMs, run.config.limits.portTimeoutMs, run.config.signal, (options) => call(options, nowMs), () => readClock(run.config.clock));\n}\n\n/**\n * Step 0: make sure one whole attempt fits in what is left of the lease,\n * renewing it when it does not. Returns `false` when the intent is done\n * for this cycle: the store refused the renewal (the lease is gone, and\n * nothing more is written) or the cycle's signal aborted. A renewal whose\n * outcome is unknown (it threw, timed out or answered unreadably) is not a\n * refusal: the intent goes ahead under the lease last known, and the\n * transport deadline's lease cap (4c) and the store's fence check bound it.\n * The store never extends a lease past the processing deadline; an intent\n * past it is dead-lettered by its first guard call.\n */\nasync function keepLease(run: Run, intent: ClaimedIntent): Promise<boolean> {\n\tconst { config } = run;\n\tconst { attemptTimeoutMs, portTimeoutMs } = config.limits;\n\tconst nowMs = readClock(config.clock);\n\tif (run.leaseExpiresAtMs - nowMs >= attemptTimeoutMs + ATTEMPT_PORT_CALLS * portTimeoutMs) return true;\n\tlet askedAtMs = nowMs;\n\tconst renewed = await storeWrite(run, (options, callNowMs) => {\n\t\taskedAtMs = callNowMs;\n\t\treturn config.deliveries.renewDeliveryIntentLease({\n\t\t\tdeliveryId: intent.deliveryId,\n\t\t\towner: intent.lease.owner,\n\t\t\tfence: intent.lease.fence,\n\t\t\tnow: new Date(callNowMs),\n\t\t\tleaseDurationMs: config.leaseDurationMs,\n\t\t}, options);\n\t});\n\tif (renewed.ok && renewed.value === true) {\n\t\t// The store's rule: never shorter than before, never past the processing deadline.\n\t\tconst untilMs = mathMin(askedAtMs + config.leaseDurationMs, intent.processingDeadlineMs);\n\t\tif (untilMs > run.leaseExpiresAtMs) run.leaseExpiresAtMs = untilMs;\n\t\treturn true;\n\t}\n\tif (renewed.ok && renewed.value === false) {\n\t\tfinish(run, \"lease_lost\", { diagnostic: \"lease_lost\" });\n\t\treturn false;\n\t}\n\tif (!renewed.ok && renewed.reason === \"aborted\") {\n\t\tfinish(run, \"abandoned\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nasync function processIntent(run: Run, intent: ClaimedIntent): Promise<void> {\n\tconst { config } = run;\n\tconst attempt = intent.attemptCount + 1;\n\n\t// 0. Enough lease for one whole attempt, renewed if need be.\n\tif (!(await keepLease(run, intent))) return;\n\n\t// 1. The processing deadline persisted at creation (R4) is checked on every\n\t// claim by `intentCall`: no port call is made at or after it, and the first\n\t// refusal dead-letters the intent.\n\n\t// 2. Subscription state, scope and the configuration this attempt uses.\n\tconst first = await readState(run, intent);\n\tif (first === undefined) return;\n\tconst configuration = first.configuration;\n\trun.version = configuration.version;\n\n\t// 3a. Destination for that configuration.\n\tconst resolved = await intentCall(run, intent, (options) => config.resolver.resolve(configuration.destinationUrl, options));\n\tif (!resolved.ok) return portFailure(run, resolved.reason, \"resolver_unavailable\");\n\tconst resolution = readResolution(resolved.value);\n\tif (resolution === undefined) return release(run, intent, \"resolver_unavailable\");\n\tif (!resolution.ok) return spendUnsent(run, intent, { kind: resolution.code });\n\n\t// 3b. Sign this attempt with that configuration's secret reference (decision 7: per attempt, at send time).\n\tconst timestampSeconds = mathFloor(readClock(config.clock) / 1_000);\n\tconst signed = await intentCall(run, intent, (options) => config.signer.sign({\n\t\tscheme: configuration.signatureScheme,\n\t\tsecretRef: configuration.secretRef,\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\ttimestampSeconds,\n\t\trawBody: intent.body,\n\t}, options));\n\tif (!signed.ok && (signed.reason === \"deadline\" || signed.reason === \"aborted\")) return portFailure(run, signed.reason, \"signer_unavailable\");\n\tlet headers: Readonly<Record<string, string>> | undefined;\n\ttry {\n\t\t// A malformed signature is refused here rather than sent (headers.ts).\n\t\theaders = signed.ok\n\t\t\t? buildWebhookRequestHeaders({ signature: readSignature(signed.value)!, timestampSeconds, eventId: intent.eventId, deliveryId: intent.deliveryId, attempt })\n\t\t\t: undefined;\n\t} catch {\n\t\theaders = undefined;\n\t}\n\tif (headers === undefined) return spendUnsent(run, intent, { kind: \"signer_unavailable\" });\n\n\t// 4a. Guard: delivery authorization for this attempt (decision 4).\n\tconst authorized = await intentCall(run, intent, (options) => config.authorization.authorize({\n\t\tsubscriptionId: intent.subscriptionId,\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\teventId: intent.eventId,\n\t\tdeliveryId: intent.deliveryId,\n\t\tconfigurationVersion: configuration.version,\n\t\tattempt,\n\t}, options));\n\tif (!authorized.ok) return portFailure(run, authorized.reason, \"authorization_unavailable\");\n\tconst decision = normalizeWebhookDeliveryAuthorizationDecision(authorized.value);\n\tif (decision.decision === \"revoked\") return cancel(run, \"authorization_revoked\");\n\tif (decision.decision === \"unavailable\") return release(run, intent, \"authorization_unavailable\");\n\n\t// 4b. Guard: subscription state and configuration version, re-read (decision 3).\n\tconst second = await readState(run, intent);\n\tif (second === undefined) return;\n\tif (second.configuration.version !== configuration.version) return release(run, intent, \"configuration_conflict\");\n\n\t// 4c. The transport's deadline: the clock now plus `attemptTimeoutMs`, and\n\t// never later than the guard read's start plus `portTimeoutMs +\n\t// attemptTimeoutMs` (the old-secret retention bound, R6, holds even when a\n\t// continuation runs late), the processing deadline, or the lease's expiry\n\t// (as last claimed or renewed, step 0) less the answer's grace and the outcome and settlement writes, so a\n\t// request that answers in time can still be settled under the lease. (The\n\t// processing deadline itself is checked again by `intentCall` below.)\n\tconst { attemptTimeoutMs, portTimeoutMs } = config.limits;\n\tconst sendDeadlineMs = mathMin(\n\t\treadClock(config.clock) + attemptTimeoutMs,\n\t\tsecond.startedMs + portTimeoutMs + attemptTimeoutMs,\n\t\tintent.processingDeadlineMs,\n\t\trun.leaseExpiresAtMs - SETTLEMENT_WRITES * portTimeoutMs,\n\t);\n\n\t// 4d. Guard: the lease, checked and the attempt recorded in one atomic store step.\n\tconst begun = await intentCall(run, intent, (options, nowMs) => config.deliveries.beginAttempt({\n\t\towner: intent.lease.owner,\n\t\tfence: intent.lease.fence,\n\t\tnow: new Date(nowMs),\n\t\tattempt: {\n\t\t\tdeliveryId: intent.deliveryId,\n\t\t\tsubscriptionId: intent.subscriptionId,\n\t\t\teventId: intent.eventId,\n\t\t\tattempt,\n\t\t\tconfigurationVersion: configuration.version,\n\t\t\tstartedAt: isoOf(nowMs),\n\t\t},\n\t}, options));\n\tif (!begun.ok) return portFailure(run, begun.reason, \"delivery_store_unavailable\");\n\tconst answer = readBeginAnswer(begun.value);\n\tif (answer === undefined) return release(run, intent, \"delivery_store_unavailable\");\n\tif (!answer.begun) return finish(run, \"lease_lost\", { diagnostic: \"lease_lost\" });\n\t// The proof that this worker began the attempt: kept here only, never logged or reported.\n\tconst receipt = answer.receipt;\n\n\t// 5. The handoff: the irrevocable point. Nothing is awaited between the\n\t// begin above and this call except the clock read.\n\tconst request: WebhookTransportRequest = record({ destination: resolution.destination, method: \"POST\" as const, headers, body: intent.body });\n\tconst handoffMs = readClock(config.clock);\n\tconst timeoutMs = sendDeadlineMs - handoffMs;\n\tlet observation: WebhookDeliveryObservation;\n\tif (!(timeoutMs > 0)) {\n\t\t// Expired before the handoff: the transport would refuse it (R3), so it is not called.\n\t\treturn notSent(run, intent, receipt);\n\t}\n\trun.handedOff = true;\n\trun.counters.handedOff += 1;\n\tconst sent = await boundedCall(handoffMs, timeoutMs, config.signal, (options) => config.transport.send(request, options), () => readClock(config.clock), portTimeoutMs);\n\tif (!sent.ok && sent.reason === \"aborted\") return finish(run, \"abandoned\");\n\tif (!sent.ok) {\n\t\t// A throw or no answer by the deadline: the request may have been sent.\n\t\tobservation = { kind: sent.reason === \"timeout\" ? \"timeout\" : \"network_error\" };\n\t} else {\n\t\tconst result = readTransportResult(sent.value);\n\t\tif (result !== undefined && result.kind === \"not_sent\") return notSent(run, intent, receipt);\n\t\tobservation = result === undefined ? { kind: \"network_error\" } : result;\n\t}\n\n\t// 6. Classify, record the outcome (unfenced, with the receipt), settle\n\t// (fenced). The outcome is written first: if the settlement is refused\n\t// because the lease expired or was reclaimed, the attempt and what it\n\t// observed are still on record, and the intent is sent again after it is\n\t// reclaimed (at least once; receivers deduplicate by deliveryId).\n\tconst finishedMs = readClock(config.clock);\n\tlet classification: WebhookDeliveryClassification;\n\ttry {\n\t\tclassification = classifyWebhookDeliveryObservation(observation, { now: new Date(finishedMs), maxRetryAfterMs: config.limits.maxRetryAfterMs });\n\t} catch {\n\t\tclassification = record({ outcome: \"retryable\" as const, reason: \"network_error\" as const });\n\t}\n\tawait storeWrite(run, (options) => config.deliveries.finishAttempt({\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\tdeliveryId: intent.deliveryId,\n\t\tfence: intent.lease.fence,\n\t\treceipt,\n\t\tfinish: {\n\t\t\tfinishedAt: isoOf(finishedMs),\n\t\t\toutcome: classification.outcome,\n\t\t\treason: classification.reason,\n\t\t\t...(classification.httpStatus === undefined ? {} : { httpStatus: classification.httpStatus }),\n\t\t},\n\t}, options));\n\treturn applyClassification(run, intent, classification);\n}\n\n/**\n * Steps 2 and 4b: the subscription's state for this intent. Returns the\n * configuration when the subscription is active, in scope, and has been\n * active since the intent's eligibility revision or earlier; otherwise\n * settles the intent and returns `undefined`.\n */\nasync function readState(run: Run, intent: ClaimedIntent): Promise<{ readonly configuration: DispatchConfiguration; readonly startedMs: number } | undefined> {\n\tlet startedMs = Number.NaN;\n\tconst answer = await intentCall(run, intent, (options, nowMs) => {\n\t\tstartedMs = nowMs;\n\t\treturn run.config.subscriptions.readSubscription(\n\t\t\t{ tenantId: intent.tenantId, spaceId: intent.spaceId, subscriptionId: intent.subscriptionId },\n\t\t\toptions,\n\t\t);\n\t});\n\tif (!answer.ok) {\n\t\tawait portFailure(run, answer.reason, \"subscription_store_unavailable\");\n\t\treturn undefined;\n\t}\n\tconst state = readSubscriptionFor(answer.value, intent);\n\tif (state.kind === \"not_in_scope\") {\n\t\tawait deadLetter(run, \"subscription_not_in_scope\");\n\t\treturn undefined;\n\t}\n\tif (state.kind === \"unreadable\") {\n\t\tawait release(run, intent, \"subscription_store_unavailable\");\n\t\treturn undefined;\n\t}\n\tif (state.status === \"paused\") {\n\t\tawait cancel(run, \"subscription_paused\");\n\t\treturn undefined;\n\t}\n\tif (state.status === \"deleted\") {\n\t\tawait cancel(run, \"subscription_deleted\");\n\t\treturn undefined;\n\t}\n\t// Active, but since a revision later than the intent's: a pause ended the\n\t// intent's interval and a resume began a new one, which does not reopen\n\t// it (decision 3). This holds whatever the pause's `cancelPendingIntents`\n\t// did, and for intents fan-out wrote after it ran.\n\tif (intent.eligibilityRevision < state.statusSinceRevision) {\n\t\tawait cancel(run, \"subscription_paused\");\n\t\treturn undefined;\n\t}\n\treturn { configuration: state.configuration, startedMs };\n}\n\n/** A pre-handoff port call that did not answer: past the deadline, aborted, timed out or threw. */\nfunction portFailure(run: Run, reason: CallFailure, unavailable: WebhookDiagnosticCode): Promise<void> {\n\tif (reason === \"deadline\") return deadLetter(run, \"processing_deadline_exceeded\");\n\tif (reason === \"aborted\") {\n\t\tfinish(run, \"abandoned\");\n\t\treturn Promise.resolve();\n\t}\n\treturn release(run, run.intent!, reason === \"timeout\" ? \"port_timeout\" : unavailable);\n}\n\n/**\n * Decision 10 rows that end an attempt before the transport is reached (a\n * refused destination, a failed signer): logged as a complete attempt\n * under the lease, then settled. If the log write fails, nothing is spent:\n * the intent is released instead, so every spent attempt has a log entry.\n * A log write that timed out may still have committed; the release then\n * leaves an entry for an attempt that spent nothing (see the top of this\n * file).\n */\nasync function spendUnsent(run: Run, intent: ClaimedIntent, observation: WebhookDeliveryObservation): Promise<void> {\n\tconst nowMs = readClock(run.config.clock);\n\tconst classification = classifyWebhookDeliveryObservation(observation, { now: new Date(nowMs), maxRetryAfterMs: run.config.limits.maxRetryAfterMs });\n\tconst logged = await storeWrite(run, (options) => run.config.deliveries.appendAttempt({\n\t\towner: intent.lease.owner,\n\t\tfence: intent.lease.fence,\n\t\tnow: new Date(nowMs),\n\t\tattempt: {\n\t\t\tdeliveryId: intent.deliveryId,\n\t\t\tsubscriptionId: intent.subscriptionId,\n\t\t\teventId: intent.eventId,\n\t\t\tattempt: intent.attemptCount + 1,\n\t\t\tconfigurationVersion: run.version!,\n\t\t\tstartedAt: isoOf(nowMs),\n\t\t\tfinishedAt: isoOf(nowMs),\n\t\t\toutcome: classification.outcome,\n\t\t\treason: classification.reason,\n\t\t},\n\t}, options));\n\tif (logged.ok && logged.value === false) return finish(run, \"lease_lost\", { diagnostic: \"lease_lost\" });\n\tif (!logged.ok && logged.reason === \"aborted\") return finish(run, \"abandoned\");\n\tif (!logged.ok || logged.value !== true) return release(run, intent, logged.ok ? \"delivery_store_unavailable\" : logged.reason === \"timeout\" ? \"port_timeout\" : \"delivery_store_unavailable\");\n\treturn applyClassification(run, intent, classification);\n}\n\n/** The transport never started the request: record it `not_sent` and release, spending nothing. */\nasync function notSent(run: Run, intent: ClaimedIntent, receipt: string): Promise<void> {\n\tconst nowMs = readClock(run.config.clock);\n\tawait storeWrite(run, (options) => run.config.deliveries.finishAttempt({\n\t\ttenantId: intent.tenantId,\n\t\tspaceId: intent.spaceId,\n\t\tdeliveryId: intent.deliveryId,\n\t\tfence: intent.lease.fence,\n\t\treceipt,\n\t\tfinish: { finishedAt: isoOf(nowMs), outcome: \"not_sent\", reason: \"not_sent\" },\n\t}, options));\n\treturn release(run, intent, \"transport_not_sent\");\n}\n\n/** Settle an attempt's classification (decision 10). */\nfunction applyClassification(run: Run, intent: ClaimedIntent, classification: WebhookDeliveryClassification): Promise<void> {\n\tconst extra = { reason: classification.reason, httpStatus: classification.httpStatus, receiverActionLikely: classification.receiverActionLikely };\n\tswitch (classification.outcome) {\n\t\tcase \"delivered\":\n\t\t\treturn settle(run, { kind: \"delivered\" }, \"delivered\", extra);\n\t\tcase \"dead_letter\":\n\t\t\treturn settle(run, { kind: \"dead_letter\", reason: classification.reason }, \"dead_lettered\", extra);\n\t\tcase \"cancelled\":\n\t\t\treturn settle(run, { kind: \"cancelled\", reason: classification.reason }, \"cancelled\", extra);\n\t\tdefault:\n\t\t\treturn retryOrDeadLetter(run, intent, classification, extra);\n\t}\n}\n\n/** The delay before attempt `attempt + 1`, falling back to the longest configured delay when the port misbehaves. */\nfunction delayAfter(run: Run, attempt: number): number {\n\tlet delayMs: number;\n\ttry {\n\t\tdelayMs = apply(run.config.retryDelay, undefined, [attempt]) as number;\n\t} catch {\n\t\tdelayMs = NaN;\n\t}\n\tif (typeof delayMs !== \"number\" || !numberIsFinite(delayMs) || delayMs < 0) {\n\t\tconst delays = run.config.limits.deliveryRetryDelaysMs;\n\t\tdelayMs = delays[delays.length - 1]!;\n\t}\n\treturn delayMs;\n}\n\nfunction retryOrDeadLetter(\n\trun: Run,\n\tintent: ClaimedIntent,\n\tclassification: WebhookDeliveryClassification,\n\textra: Partial<WebhookDeliveryCycleEvent>,\n): Promise<void> {\n\tconst attempt = intent.attemptCount + 1;\n\tif (attempt >= run.config.limits.maxDeliveryAttempts) {\n\t\treturn settle(run, { kind: \"dead_letter\", reason: classification.reason }, \"dead_lettered\", extra);\n\t}\n\tconst nowMs = readClock(run.config.clock);\n\t// A 429's bounded Retry-After is honoured when it is longer than the schedule.\n\tconst delayMs = mathMax(delayAfter(run, attempt), classification.retryAfterMs ?? 0);\n\tconst availableAtMs = nowMs + delayMs;\n\tif (availableAtMs >= intent.processingDeadlineMs) return deadLetter(run, \"processing_deadline_exceeded\", extra);\n\treturn settle(run, { kind: \"retry\", availableAt: new Date(availableAtMs), outcome: \"retryable\", reason: classification.reason }, \"retry_scheduled\", extra);\n}\n\n/**\n * Return the intent to pending unsent, spending no attempt (decision 3).\n * It is available again after the delay the next attempt would wait; when\n * that falls at or past the processing deadline it is dead-lettered now,\n * because deferrals count toward that deadline (R4).\n */\nfunction release(run: Run, intent: ClaimedIntent, diagnostic: WebhookDiagnosticCode): Promise<void> {\n\tconst nowMs = readClock(run.config.clock);\n\tconst availableAtMs = nowMs + delayAfter(run, intent.attemptCount + 1);\n\tif (availableAtMs >= intent.processingDeadlineMs) return deadLetter(run, \"processing_deadline_exceeded\", { diagnostic });\n\treturn settle(run, { kind: \"release\", availableAt: new Date(availableAtMs), diagnostic }, \"released\", { diagnostic });\n}\n\nfunction cancel(run: Run, reason: \"authorization_revoked\" | \"subscription_paused\" | \"subscription_deleted\"): Promise<void> {\n\treturn settle(run, { kind: \"cancelled\", reason }, \"cancelled\", { reason });\n}\n\nfunction deadLetter(run: Run, diagnostic: WebhookDiagnosticCode, extra: Partial<WebhookDeliveryCycleEvent> = {}): Promise<void> {\n\treturn settle(run, { kind: \"dead_letter\", reason: diagnostic }, \"dead_lettered\", { ...extra, diagnostic });\n}\n\ntype Settlement = Parameters<WebhookDeliveryStore[\"settleDeliveryIntent\"]>[0][\"settlement\"];\n\n/**\n * The fenced settlement that ends this worker's hold on the intent. Only a\n * literal `true` counts as done and a literal `false` as a lost lease.\n * Anything else, a failed or late call included, is `abandoned`: the\n * settlement may or may not have applied, and nothing more is written\n * either way. If it did not apply, the intent is reclaimed after its lease\n * expires. The store clears the lease on every settlement, so at most one\n * settlement per claim applies.\n */\nasync function settle(\n\trun: Run,\n\tsettlement: Settlement,\n\tresult: Exclude<WebhookDeliveryCycleResultKind, \"lease_lost\" | \"abandoned\">,\n\textra: Partial<WebhookDeliveryCycleEvent>,\n): Promise<void> {\n\tconst outcome = await storeWrite(run, (options, nowMs) => run.config.deliveries.settleDeliveryIntent({\n\t\tdeliveryId: run.header.deliveryId,\n\t\towner: run.header.lease.owner,\n\t\tfence: run.header.lease.fence,\n\t\tnow: new Date(nowMs),\n\t\tsettlement,\n\t}, options));\n\tif (outcome.ok && outcome.value === true) return finish(run, result, extra);\n\tif (outcome.ok && outcome.value === false) return finish(run, \"lease_lost\", { ...extra, diagnostic: \"lease_lost\" });\n\treturn finish(run, \"abandoned\", extra);\n}\n\nconst COUNTER: Readonly<Record<WebhookDeliveryCycleResultKind, keyof Counters>> = freeze({\n\tdelivered: \"delivered\",\n\tretry_scheduled: \"retried\",\n\tdead_lettered: \"deadLettered\",\n\tcancelled: \"cancelled\",\n\treleased: \"released\",\n\tlease_lost: \"leaseLost\",\n\tabandoned: \"abandoned\",\n});\n\n/** Count the intent's result and report it once. A throwing observer is ignored. */\nfunction finish(run: Run, result: WebhookDeliveryCycleResultKind, extra: Partial<WebhookDeliveryCycleEvent> = {}): void {\n\tif (run.reported) return;\n\trun.reported = true;\n\trun.counters[COUNTER[result]] += 1;\n\tconst observe = run.config.observe;\n\tif (observe === undefined) return;\n\tconst intent = run.intent;\n\tconst event = record<WebhookDeliveryCycleEvent>({\n\t\tdeliveryId: run.header.deliveryId,\n\t\ttenantId: run.header.tenantId,\n\t\tspaceId: run.header.spaceId,\n\t\tsubscriptionId: intent?.subscriptionId,\n\t\teventId: intent?.eventId,\n\t\tattempt: intent === undefined ? undefined : intent.attemptCount + 1,\n\t\tconfigurationVersion: run.version,\n\t\tresult,\n\t\thandedOff: run.handedOff,\n\t\treason: extra.reason,\n\t\tdiagnostic: extra.diagnostic,\n\t\thttpStatus: extra.httpStatus,\n\t\treceiverActionLikely: extra.receiverActionLikely,\n\t});\n\ttry {\n\t\tapply(observe, undefined, [event]);\n\t} catch {\n\t\t// Telemetry never changes what the cycle did.\n\t}\n}\n","import { checkWebhookDestinationUrl } from \"./destination\";\nimport { guardOr } from \"./errors\";\nimport { freeze, isArray, isOneOf, matches, numberIsSafeInteger, snapshotJson, type Fail } from \"./snapshot\";\nimport { isWebhookIdentifier } from \"./store-input\";\n\n/*\n * Parameters of the governed actions (PR 9; README, \"Governed actions\").\n *\n * Each action's parameters are read here and nowhere else: by the action's\n * admission check (`admitSubmission`, src/governed-actions.ts), which Host\n * runs on every submission before it records anything, by the action's\n * schema (which Host runs before policies and the handler), and by the\n * handler itself (which reads again rather than trusting what it was handed).\n *\n * The reader copies the input with the package's plain-data snapshot (own\n * data properties only, accessors refused uncalled), refuses any key the\n * action does not declare, and checks every field. A refusal carries a fixed\n * code and the name of a declared field or `parameters`\n * (`webhookParameterRefusalMessage` keeps only those), not a caller value or\n * a caller key: Host writes a schema issue into the invocation's durable\n * `error` as `<path>: <message>`, and the path is always the root.\n *\n * Secret references (ADR 0018 decision 8, R7). Fields named `secretRef` take\n * a reference only. {@link isWebhookSecretReference} refuses the shapes key\n * material and ciphertext usually arrive in; it cannot tell an opaque\n * reference from random bytes of the same shape, so the actions also ask the\n * application's `secretReferences.verify` port, which must confirm that the\n * reference names a secret in the tenant's own secret store: at admission,\n * before Host persists the submission, and again before the handler writes.\n */\n\n/** The governed actions, by the name after the module namespace (`<namespace>.<name>`). */\nexport const WEBHOOK_DELIVERY_ACTION_NAMES = freeze([\n\t\"create_subscription\",\n\t\"update_subscription\",\n\t\"pause_subscription\",\n\t\"resume_subscription\",\n\t\"delete_subscription\",\n\t\"rotate_secret_staged\",\n\t\"rotate_secret_emergency\",\n\t\"requeue_delivery_intent\",\n\t\"requeue_fan_out_job\",\n\t\"enrich_fan_out_job_actor\",\n] as const);\n\n/** One governed action name. */\nexport type WebhookDeliveryActionName = (typeof WEBHOOK_DELIVERY_ACTION_NAMES)[number];\n\n/**\n * Why parameters were refused. `parameters_invalid`: not a plain-data\n * object, a field missing or malformed, or an id breaking the store\n * identifier rule. `unknown_parameter`: a key the action does not declare\n * (named in no message). `secret_ref_invalid`: a `secretRef` that is not a\n * secret reference. `destination_invalid`: a destination URL breaking the\n * URL rules (README, \"URL rules\"). `event_type_pattern_invalid`: a pattern\n * outside the pattern grammar. `update_ambiguous`: an update naming both or\n * neither of patterns and destination.\n */\nexport const WEBHOOK_ACTION_PARAMETER_CODES = freeze([\n\t\"parameters_invalid\",\n\t\"unknown_parameter\",\n\t\"secret_ref_invalid\",\n\t\"destination_invalid\",\n\t\"event_type_pattern_invalid\",\n\t\"update_ambiguous\",\n] as const);\n\n/** Why an action's parameters were refused. */\nexport type WebhookActionParameterCode = (typeof WEBHOOK_ACTION_PARAMETER_CODES)[number];\n\n/** `<namespace>.create_subscription` */\nexport interface WebhookCreateSubscriptionParameters {\n\treadonly subscriptionId: string;\n\treadonly eventTypePatterns: readonly string[];\n\treadonly destinationUrl: string;\n\t/** A secret reference, not key material or ciphertext (`isWebhookSecretReference`, then the verifier). */\n\treadonly secretRef: string;\n\t/** Only `v1` exists (decision 7); the default. */\n\treadonly signatureScheme?: \"v1\";\n}\n\n/** `<namespace>.update_subscription`: exactly one of the two changes per invocation. */\nexport type WebhookUpdateSubscriptionParameters =\n\t| { readonly subscriptionId: string; readonly eventTypePatterns: readonly string[]; readonly expectedRevision?: number }\n\t| { readonly subscriptionId: string; readonly destinationUrl: string; readonly expectedVersion?: number };\n\n/** `<namespace>.pause_subscription`, `resume_subscription` and `delete_subscription`. */\nexport interface WebhookSubscriptionTransitionParameters {\n\treadonly subscriptionId: string;\n\treadonly expectedRevision?: number;\n}\n\n/** `<namespace>.rotate_secret_staged` */\nexport interface WebhookStagedRotationParameters {\n\treadonly subscriptionId: string;\n\t/** The next secret's reference, not key material or ciphertext (`isWebhookSecretReference`, then the verifier). */\n\treadonly secretRef: string;\n\t/** The configuration version the operator read; the rotation applies only on it. */\n\treadonly expectedVersion: number;\n\t/** The operator's statement that the receiver already accepts the next secret (decision 8). */\n\treadonly receiverAcceptsNextSecret: true;\n}\n\n/** `<namespace>.rotate_secret_emergency` */\nexport interface WebhookEmergencyRotationParameters {\n\treadonly subscriptionId: string;\n\treadonly secretRef: string;\n\treadonly expectedVersion?: number;\n}\n\n/** `<namespace>.requeue_delivery_intent` */\nexport interface WebhookIntentRequeueParameters {\n\treadonly deliveryId: string;\n\t/** The intent's `fence` as the operator read it. */\n\treadonly expectedFence: number;\n}\n\n/** `<namespace>.requeue_fan_out_job` and `enrich_fan_out_job_actor`. */\nexport interface WebhookJobParameters {\n\treadonly eventId: string;\n\t/** The job's `fence` as the operator read it. */\n\treadonly expectedFence: number;\n}\n\n/** The parameters of each action, by name. */\nexport interface WebhookDeliveryActionParameters {\n\treadonly create_subscription: WebhookCreateSubscriptionParameters;\n\treadonly update_subscription: WebhookUpdateSubscriptionParameters;\n\treadonly pause_subscription: WebhookSubscriptionTransitionParameters;\n\treadonly resume_subscription: WebhookSubscriptionTransitionParameters;\n\treadonly delete_subscription: WebhookSubscriptionTransitionParameters;\n\treadonly rotate_secret_staged: WebhookStagedRotationParameters;\n\treadonly rotate_secret_emergency: WebhookEmergencyRotationParameters;\n\treadonly requeue_delivery_intent: WebhookIntentRequeueParameters;\n\treadonly requeue_fan_out_job: WebhookJobParameters;\n\treadonly enrich_fan_out_job_actor: WebhookJobParameters;\n}\n\n/** What reading one action's parameters found. */\nexport type WebhookActionParameterRead<N extends WebhookDeliveryActionName> =\n\t| { readonly ok: true; readonly value: WebhookDeliveryActionParameters[N] }\n\t| { readonly ok: false; readonly code: WebhookActionParameterCode; readonly field: string };\n\n// ---------------------------------------------------------------------------\n// Secret references and patterns\n// ---------------------------------------------------------------------------\n\n/** The longest secret reference accepted. */\nexport const WEBHOOK_SECRET_REF_MAX_LENGTH = 256;\n/** The longest run of characters between two separators (`:`, `/`, `@`, `#`) in a secret reference. */\nexport const WEBHOOK_SECRET_REF_MAX_SEGMENT = 64;\n\nconst SECRET_REF_SHAPE = /^[a-z][a-z0-9.-]{0,31}:[A-Za-z0-9._~:/@#-]+$/;\nconst SECRET_REF_LONG_SEGMENT = /[A-Za-z0-9._~-]{65,}/;\n\n/**\n * Whether `value` has the shape of a secret reference (ADR 0018 decision 8):\n * a lower-case scheme and `:` (`kms:`, `vault:`, `arn:`, `secret:` …), then\n * only `A–Z a–z 0–9 . _ ~ : / @ # -`, at most\n * {@link WEBHOOK_SECRET_REF_MAX_LENGTH} characters, with no run longer than\n * {@link WEBHOOK_SECRET_REF_MAX_SEGMENT} between separators.\n *\n * That refuses raw key bytes and their usual encodings: hex, base64 and\n * `whsec_…` values (no scheme), padded or standard base64 (`=`, `+`), PEM\n * armour and anything with whitespace or control characters, and long\n * encoded runs such as wrapped ciphertext. It cannot recognise key material\n * deliberately shaped like a reference (`x:` followed by 64 hex digits\n * passes), which is why the actions also require the application's\n * `secretReferences.verify` port to confirm the reference resolves in the\n * tenant's secret store.\n */\nexport function isWebhookSecretReference(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length <= WEBHOOK_SECRET_REF_MAX_LENGTH &&\n\t\tmatches(SECRET_REF_SHAPE, value) && !matches(SECRET_REF_LONG_SEGMENT, value);\n}\n\n/** The most patterns one subscription takes. */\nexport const WEBHOOK_MAX_EVENT_TYPE_PATTERNS = 64;\n\nconst PATTERN_SHAPE = /^(?:\\*|[A-Za-z0-9_:-]+(?:\\.[A-Za-z0-9_:-]+)*(?:\\.\\*)?)$/;\n\n/**\n * Whether `value` is an event type pattern the matcher understands: `*`,\n * `prefix.*`, or an exact type, built from `A–Z a–z 0–9 _ : -` segments\n * joined by `.`, at most 256 characters. A `*` anywhere else is refused,\n * since the matcher would treat it as a literal.\n */\nexport function isWebhookEventTypePattern(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length <= 256 && matches(PATTERN_SHAPE, value);\n}\n\n// ---------------------------------------------------------------------------\n// Reading\n// ---------------------------------------------------------------------------\n\ntype Read<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly code: WebhookActionParameterCode; readonly field: string };\n\n/**\n * Thrown inside a reader to stop it; `readWebhookActionParameters` catches\n * it. Recognized by its private field (`Refusal.is`), which only this class\n * can create and which a brand check reads without running any of the\n * value's code (no getter, no Proxy trap), so a caller's input that throws\n * a look-alike `{ refusal: true, code, … }` from a trap is not taken for\n * one. The class is not exported and keeps no registry (Boundary Guard G5).\n */\nclass Refusal {\n\treadonly #brand = true;\n\treadonly code: WebhookActionParameterCode;\n\treadonly field: string;\n\n\tconstructor(code: WebhookActionParameterCode, field: string) {\n\t\tthis.code = code;\n\t\tthis.field = field;\n\t\tfreeze(this);\n\t}\n\n\t/** Whether `value` was made by this class's constructor. Reads nothing of `value`. */\n\tstatic is(value: unknown): value is Refusal {\n\t\treturn value !== null && typeof value === \"object\" && #brand in value;\n\t}\n}\n\nconst objectKeys = Object.keys;\n\nfunction refuse(code: WebhookActionParameterCode, field: string): never {\n\tthrow new Refusal(code, field);\n}\n\nconst snapshotFail: Fail = () => refuse(\"parameters_invalid\", \"parameters\");\n\ntype Fields = { readonly [key: string]: unknown };\n\nconst ALLOWED_KEYS: { readonly [N in WebhookDeliveryActionName]: readonly string[] } = freeze({\n\tcreate_subscription: freeze([\"subscriptionId\", \"eventTypePatterns\", \"destinationUrl\", \"secretRef\", \"signatureScheme\"]),\n\tupdate_subscription: freeze([\"subscriptionId\", \"eventTypePatterns\", \"expectedRevision\", \"destinationUrl\", \"expectedVersion\"]),\n\tpause_subscription: freeze([\"subscriptionId\", \"expectedRevision\"]),\n\tresume_subscription: freeze([\"subscriptionId\", \"expectedRevision\"]),\n\tdelete_subscription: freeze([\"subscriptionId\", \"expectedRevision\"]),\n\trotate_secret_staged: freeze([\"subscriptionId\", \"secretRef\", \"expectedVersion\", \"receiverAcceptsNextSecret\"]),\n\trotate_secret_emergency: freeze([\"subscriptionId\", \"secretRef\", \"expectedVersion\"]),\n\trequeue_delivery_intent: freeze([\"deliveryId\", \"expectedFence\"]),\n\trequeue_fan_out_job: freeze([\"eventId\", \"expectedFence\"]),\n\tenrich_fan_out_job_actor: freeze([\"eventId\", \"expectedFence\"]),\n});\n\nfunction snapshotParameters(input: unknown): Fields {\n\tconst copy = snapshotJson(input, \"parameters\", snapshotFail);\n\tif (copy === null || typeof copy !== \"object\" || isArray(copy)) refuse(\"parameters_invalid\", \"parameters\");\n\treturn copy as Fields;\n}\n\nfunction idField(fields: Fields, key: string): string {\n\tconst value = fields[key];\n\tif (!isWebhookIdentifier(value)) refuse(\"parameters_invalid\", key);\n\treturn value;\n}\n\nfunction optionalWhole(fields: Fields, key: string, min: number): number | undefined {\n\tconst value = fields[key];\n\tif (value === undefined) return undefined;\n\tif (typeof value !== \"number\" || !numberIsSafeInteger(value) || value < min) refuse(\"parameters_invalid\", key);\n\treturn value;\n}\n\nfunction whole(fields: Fields, key: string, min: number): number {\n\tconst value = optionalWhole(fields, key, min);\n\tif (value === undefined) refuse(\"parameters_invalid\", key);\n\treturn value;\n}\n\nfunction secretRefField(fields: Fields): string {\n\tconst value = fields[\"secretRef\"];\n\tif (!isWebhookSecretReference(value)) refuse(\"secret_ref_invalid\", \"secretRef\");\n\treturn value;\n}\n\nfunction destinationField(fields: Fields): string {\n\tconst value = fields[\"destinationUrl\"];\n\tif (typeof value !== \"string\") refuse(\"destination_invalid\", \"destinationUrl\");\n\tconst check = guardOr(() => checkWebhookDestinationUrl(value), () => ({ ok: false as const, code: \"invalid_url\" as const }));\n\tif (!check.ok) refuse(\"destination_invalid\", \"destinationUrl\");\n\treturn value;\n}\n\nfunction patternsField(fields: Fields): readonly string[] {\n\tconst value = fields[\"eventTypePatterns\"];\n\tif (!isArray(value) || value.length === 0 || value.length > WEBHOOK_MAX_EVENT_TYPE_PATTERNS) refuse(\"event_type_pattern_invalid\", \"eventTypePatterns\");\n\tconst out: string[] = [];\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst pattern = value[index];\n\t\tif (!isWebhookEventTypePattern(pattern)) refuse(\"event_type_pattern_invalid\", \"eventTypePatterns\");\n\t\tout[index] = pattern;\n\t}\n\treturn freeze(out);\n}\n\n/** Refuse any key the action does not declare, without naming it. */\nfunction onlyKnownKeys(fields: Fields, name: WebhookDeliveryActionName): void {\n\tconst keys = objectKeys(fields);\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tif (!isOneOf(ALLOWED_KEYS[name], keys[index])) refuse(\"unknown_parameter\", \"parameters\");\n\t}\n}\n\nfunction readFields(name: WebhookDeliveryActionName, fields: Fields): object {\n\tswitch (name) {\n\t\tcase \"create_subscription\": {\n\t\t\tconst scheme = fields[\"signatureScheme\"];\n\t\t\tif (scheme !== undefined && scheme !== \"v1\") refuse(\"parameters_invalid\", \"signatureScheme\");\n\t\t\treturn {\n\t\t\t\tsubscriptionId: idField(fields, \"subscriptionId\"),\n\t\t\t\teventTypePatterns: patternsField(fields),\n\t\t\t\tdestinationUrl: destinationField(fields),\n\t\t\t\tsecretRef: secretRefField(fields),\n\t\t\t\t...(scheme === undefined ? {} : { signatureScheme: \"v1\" }),\n\t\t\t};\n\t\t}\n\t\tcase \"update_subscription\": {\n\t\t\tconst patterns = fields[\"eventTypePatterns\"] !== undefined;\n\t\t\tconst destination = fields[\"destinationUrl\"] !== undefined;\n\t\t\tif (patterns === destination) refuse(\"update_ambiguous\", \"parameters\");\n\t\t\tconst subscriptionId = idField(fields, \"subscriptionId\");\n\t\t\tif (patterns) {\n\t\t\t\tif (fields[\"expectedVersion\"] !== undefined) refuse(\"parameters_invalid\", \"expectedVersion\");\n\t\t\t\tconst expectedRevision = optionalWhole(fields, \"expectedRevision\", 1);\n\t\t\t\treturn { subscriptionId, eventTypePatterns: patternsField(fields), ...(expectedRevision === undefined ? {} : { expectedRevision }) };\n\t\t\t}\n\t\t\tif (fields[\"expectedRevision\"] !== undefined) refuse(\"parameters_invalid\", \"expectedRevision\");\n\t\t\tconst expectedVersion = optionalWhole(fields, \"expectedVersion\", 1);\n\t\t\treturn { subscriptionId, destinationUrl: destinationField(fields), ...(expectedVersion === undefined ? {} : { expectedVersion }) };\n\t\t}\n\t\tcase \"pause_subscription\":\n\t\tcase \"resume_subscription\":\n\t\tcase \"delete_subscription\": {\n\t\t\tconst expectedRevision = optionalWhole(fields, \"expectedRevision\", 1);\n\t\t\treturn { subscriptionId: idField(fields, \"subscriptionId\"), ...(expectedRevision === undefined ? {} : { expectedRevision }) };\n\t\t}\n\t\tcase \"rotate_secret_staged\": {\n\t\t\tif (fields[\"receiverAcceptsNextSecret\"] !== true) refuse(\"parameters_invalid\", \"receiverAcceptsNextSecret\");\n\t\t\treturn {\n\t\t\t\tsubscriptionId: idField(fields, \"subscriptionId\"),\n\t\t\t\tsecretRef: secretRefField(fields),\n\t\t\t\texpectedVersion: whole(fields, \"expectedVersion\", 1),\n\t\t\t\treceiverAcceptsNextSecret: true,\n\t\t\t};\n\t\t}\n\t\tcase \"rotate_secret_emergency\": {\n\t\t\tconst expectedVersion = optionalWhole(fields, \"expectedVersion\", 1);\n\t\t\treturn { subscriptionId: idField(fields, \"subscriptionId\"), secretRef: secretRefField(fields), ...(expectedVersion === undefined ? {} : { expectedVersion }) };\n\t\t}\n\t\tcase \"requeue_delivery_intent\":\n\t\t\treturn { deliveryId: idField(fields, \"deliveryId\"), expectedFence: whole(fields, \"expectedFence\", 0) };\n\t\tcase \"requeue_fan_out_job\":\n\t\tcase \"enrich_fan_out_job_actor\":\n\t\t\treturn { eventId: idField(fields, \"eventId\"), expectedFence: whole(fields, \"expectedFence\", 0) };\n\t}\n}\n\n/** The refusal `code` and `field` with each held to its fixed set: a parameter code, and a declared field or `parameters`. */\nfunction fixedRefusal(code: unknown, field: unknown): { readonly ok: false; readonly code: WebhookActionParameterCode; readonly field: string } {\n\treturn freeze({\n\t\tok: false as const,\n\t\tcode: isOneOf(WEBHOOK_ACTION_PARAMETER_CODES, code) ? (code as WebhookActionParameterCode) : \"parameters_invalid\",\n\t\tfield: typeof field === \"string\" && isPackageField(field) ? field : \"parameters\",\n\t});\n}\n\nconst PARAMETERS_INVALID = fixedRefusal(\"parameters_invalid\", \"parameters\");\n\n/**\n * Read one action's parameters. Never throws: the only thrown value whose\n * properties are read is the package's own `Refusal` (recognized by\n * `Refusal.is`, which runs none of a value's code); anything else thrown\n * while the input is read (an accessor, a Proxy trap, a look-alike refusal)\n * is dropped unread and reported as `parameters_invalid`. The code and field\n * returned are each checked against their fixed set (`fixedRefusal`). Tests:\n * \"forged refusals: …\".\n */\nexport function readWebhookActionParameters<N extends WebhookDeliveryActionName>(name: N, input: unknown): WebhookActionParameterRead<N> {\n\ttry {\n\t\tconst fields = snapshotParameters(input);\n\t\tonlyKnownKeys(fields, name);\n\t\treturn freeze({ ok: true as const, value: freeze(readFields(name, fields)) as WebhookDeliveryActionParameters[N] });\n\t} catch (thrown) {\n\t\treturn Refusal.is(thrown) ? fixedRefusal(thrown.code, thrown.field) : PARAMETERS_INVALID;\n\t}\n}\n\n/** A field name the reader itself reports: one of the declared keys, or `parameters`. */\nfunction isPackageField(field: string): boolean {\n\tif (field === \"parameters\") return true;\n\tfor (const name of WEBHOOK_DELIVERY_ACTION_NAMES) if (isOneOf(ALLOWED_KEYS[name], field)) return true;\n\treturn false;\n}\n\n/** The fixed text of a refusal: `<code> (<package field>)`. Never a caller value or key. */\nexport function webhookParameterRefusalMessage(code: WebhookActionParameterCode, field: string): string {\n\treturn `${code} (${isPackageField(field) ? field : \"parameters\"})`;\n}\n\n// ---------------------------------------------------------------------------\n// Schemas\n// ---------------------------------------------------------------------------\n\n/** A Platform `SchemaValidator`, structurally, with the portable JSON Schema discovery reads. */\nexport interface WebhookActionSchema<T> {\n\tparse(input: unknown): T;\n\tsafeParse(input: unknown):\n\t\t| { success: true; data: T }\n\t\t| { success: false; error: { issues: { path: PropertyKey[]; message: string }[] } };\n\ttoJSONSchema(): object;\n}\n\nconst ID_SCHEMA = freeze({ type: \"string\", minLength: 1, maxLength: 256 });\nconst FENCE_SCHEMA = freeze({ type: \"integer\", minimum: 0 });\nconst REVISION_SCHEMA = freeze({ type: \"integer\", minimum: 1 });\nconst SECRET_REF_SCHEMA = freeze({\n\ttype: \"string\",\n\tmaxLength: WEBHOOK_SECRET_REF_MAX_LENGTH,\n\tpattern: \"^[a-z][a-z0-9.-]{0,31}:[A-Za-z0-9._~:/@#-]+$\",\n\tdescription: \"A secret reference resolved in the tenant's secret store, not key material or ciphertext. No run between separators may exceed 64 characters.\",\n});\nconst PATTERNS_SCHEMA = freeze({\n\ttype: \"array\",\n\tminItems: 1,\n\tmaxItems: WEBHOOK_MAX_EVENT_TYPE_PATTERNS,\n\titems: { type: \"string\", maxLength: 256, pattern: \"^(?:\\\\*|[A-Za-z0-9_:-]+(?:\\\\.[A-Za-z0-9_:-]+)*(?:\\\\.\\\\*)?)$\" },\n});\nconst URL_SCHEMA = freeze({ type: \"string\", maxLength: 2048, pattern: \"^https://\" });\n\nfunction objectSchema(properties: Record<string, object>, required: readonly string[]): object {\n\treturn { type: \"object\", properties, required: [...required], additionalProperties: false };\n}\n\nconst JSON_SCHEMAS: { readonly [N in WebhookDeliveryActionName]: () => object } = freeze({\n\tcreate_subscription: () => objectSchema(\n\t\t{ subscriptionId: ID_SCHEMA, eventTypePatterns: PATTERNS_SCHEMA, destinationUrl: URL_SCHEMA, secretRef: SECRET_REF_SCHEMA, signatureScheme: { type: \"string\", enum: [\"v1\"] } },\n\t\t[\"subscriptionId\", \"eventTypePatterns\", \"destinationUrl\", \"secretRef\"],\n\t),\n\tupdate_subscription: () => ({\n\t\t...objectSchema({ subscriptionId: ID_SCHEMA, eventTypePatterns: PATTERNS_SCHEMA, expectedRevision: REVISION_SCHEMA, destinationUrl: URL_SCHEMA, expectedVersion: REVISION_SCHEMA }, [\"subscriptionId\"]),\n\t\toneOf: [{ required: [\"eventTypePatterns\"] }, { required: [\"destinationUrl\"] }],\n\t}),\n\tpause_subscription: () => objectSchema({ subscriptionId: ID_SCHEMA, expectedRevision: REVISION_SCHEMA }, [\"subscriptionId\"]),\n\tresume_subscription: () => objectSchema({ subscriptionId: ID_SCHEMA, expectedRevision: REVISION_SCHEMA }, [\"subscriptionId\"]),\n\tdelete_subscription: () => objectSchema({ subscriptionId: ID_SCHEMA, expectedRevision: REVISION_SCHEMA }, [\"subscriptionId\"]),\n\trotate_secret_staged: () => objectSchema(\n\t\t{ subscriptionId: ID_SCHEMA, secretRef: SECRET_REF_SCHEMA, expectedVersion: REVISION_SCHEMA, receiverAcceptsNextSecret: { type: \"boolean\", const: true } },\n\t\t[\"subscriptionId\", \"secretRef\", \"expectedVersion\", \"receiverAcceptsNextSecret\"],\n\t),\n\trotate_secret_emergency: () => objectSchema({ subscriptionId: ID_SCHEMA, secretRef: SECRET_REF_SCHEMA, expectedVersion: REVISION_SCHEMA }, [\"subscriptionId\", \"secretRef\"]),\n\trequeue_delivery_intent: () => objectSchema({ deliveryId: ID_SCHEMA, expectedFence: FENCE_SCHEMA }, [\"deliveryId\", \"expectedFence\"]),\n\trequeue_fan_out_job: () => objectSchema({ eventId: ID_SCHEMA, expectedFence: FENCE_SCHEMA }, [\"eventId\", \"expectedFence\"]),\n\tenrich_fan_out_job_actor: () => objectSchema({ eventId: ID_SCHEMA, expectedFence: FENCE_SCHEMA }, [\"eventId\", \"expectedFence\"]),\n});\n\n/** A thrown `parse` failure: fixed text only. */\nclass WebhookActionParameterError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"WebhookActionParameterError\";\n\t}\n}\n\n/**\n * The schema of one action. `safeParse` reports a refusal as one issue at\n * the root path whose message is {@link webhookParameterRefusalMessage}, so\n * Host's durable `validation_failed` error holds package text only.\n */\nexport function webhookActionSchema<N extends WebhookDeliveryActionName>(name: N): WebhookActionSchema<WebhookDeliveryActionParameters[N]> {\n\tconst safeParse = (input: unknown) => {\n\t\tconst read = readWebhookActionParameters(name, input);\n\t\tif (read.ok) return { success: true as const, data: read.value };\n\t\treturn { success: false as const, error: { issues: [{ path: [] as PropertyKey[], message: webhookParameterRefusalMessage(read.code, read.field) }] } };\n\t};\n\treturn freeze({\n\t\tparse(input: unknown) {\n\t\t\tconst result = safeParse(input);\n\t\t\tif (result.success) return result.data;\n\t\t\tthrow new WebhookActionParameterError(result.error.issues[0]!.message);\n\t\t},\n\t\tsafeParse,\n\t\ttoJSONSchema: JSON_SCHEMAS[name],\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Namespaces and action ids\n// ---------------------------------------------------------------------------\n\nconst NAMESPACE_SHAPE = /^[a-z][a-z0-9-]{0,63}$/;\n\n/** The default module namespace. */\nexport const DEFAULT_WEBHOOK_DELIVERY_NAMESPACE = \"webhook-delivery\";\n\n/** Whether `value` is a module namespace this package accepts (Platform's rule, at most 64 characters). */\nexport function isWebhookDeliveryNamespace(value: unknown): value is string {\n\treturn typeof value === \"string\" && matches(NAMESPACE_SHAPE, value);\n}\n\n/** The action name of `actionId` when it is one of this namespace's governed actions. */\nexport function webhookActionNameOf(namespace: string, actionId: unknown): WebhookDeliveryActionName | undefined {\n\tif (typeof actionId !== \"string\" || actionId.length <= namespace.length + 1 || actionId[namespace.length] !== \".\") return undefined;\n\tif (actionId.slice(0, namespace.length) !== namespace) return undefined;\n\tconst name = actionId.slice(namespace.length + 1);\n\tfor (const candidate of WEBHOOK_DELIVERY_ACTION_NAMES) if (candidate === name) return candidate;\n\treturn undefined;\n}\n","import type {\n\tActionAdmission,\n\tActionAdmissionDecision,\n\tActionContext,\n\tActionDefinition,\n\tActionResult,\n\tFabricModule,\n\tPolicyContext,\n\tPolicyEvaluator,\n\tPolicyOutcome,\n} from \"@fabricorg/platform\";\n\nimport { WEBHOOK_DELIVERY_ACTION_EVENT_TYPES, type WebhookDeliveryActionEventType } from \"./action-events\";\nimport {\n\tDEFAULT_WEBHOOK_DELIVERY_NAMESPACE,\n\tisWebhookDeliveryNamespace,\n\treadWebhookActionParameters,\n\tWEBHOOK_DELIVERY_ACTION_NAMES,\n\twebhookActionNameOf,\n\twebhookActionSchema,\n\ttype WebhookDeliveryActionName,\n\ttype WebhookDeliveryActionParameters,\n} from \"./action-parameters\";\nimport { WEBHOOK_ACTION_REFUSAL_CODES, type WebhookActionRefusalCode } from \"./codes\";\nimport { governedActionError } from \"./errors\";\nimport { boundedCall, captureFanOutClock, readFanOutClock, type FanOutClock } from \"./fan-out-call\";\nimport { assertPositiveInteger, resolveWebhookDeliveryLimits, type WebhookDeliveryLimits } from \"./limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookDeliveryStore,\n\tWebhookDestinationResolver,\n\tWebhookScope,\n\tWebhookSubscriptionStore,\n\tWebhookSubscriptionWriter,\n} from \"./ports\";\nimport { apply, freeze, isOneOf, numberIsSafeInteger } from \"./snapshot\";\nimport { isoOf, isWebhookIdentifier } from \"./store-input\";\n\n/*\n * The governed operator actions (ADR 0018 decisions 5, 8 and 10;\n * Consequences; README, \"Governed actions\"). `createWebhookDeliveryModule()`\n * builds one `FabricModule` from the ports it is given at the composition\n * root; nothing is registered in module scope (decision 6, ADR 0008), so two\n * modules built in one process share nothing but this code.\n *\n * Every action:\n *\n * - declares `admitSubmission` (`admissionFor`), which Host (7.3.0 and\n * later) runs on every submission before it records anything: it reads\n * the parameters with the package reader and, for an action that takes a\n * `secretRef`, asks the application's `secretReferences.verify` with\n * Host's trusted tenant and space. A refused submission leaves no\n * invocation, idempotency key, event or error in Host's store (tests\n * \"secret material in a secretRef is refused at admission …\" and \"key\n * material shaped like a reference …\" in tests/governed-actions.test.ts);\n * - refuses to run (`admission_not_enforced`, `handlerFor`) unless Host\n * hands it `ActionContext.admittedAt`, so under a Host that skipped the\n * check, nothing is written;\n * - runs through Host's governed path: Host validates the parameters with\n * the action's schema, records the module policy's decision, runs the\n * handler and appends the declared event;\n * - acts only in Host's trusted tenant and space: parameters declare no\n * tenant or space (`ALLOWED_KEYS`, src/action-parameters.ts), and\n * `handlerFor` hands each handler `scopeOf(ctx)` as the only scope its\n * store calls use, so a subscription, job or intent of another scope is\n * `not_found` to the store and the action refuses (test \"every action\n * that names a subscription, intent or job refuses one from another tenant\n * or space …\");\n * - makes at most one write to the subscription store and at most one\n * compare-and-set to the delivery store (each handler in `HANDLERS`), so\n * the change is one atomic store step; pause, resume and delete add\n * `cancelPendingIntents` as a best-effort cleanup (`cleanUp`), which\n * dispatch does not depend on;\n * - fails with `webhook_action_refused:<code>` (`WEBHOOK_ACTION_REFUSAL_CODES`)\n * and nothing else in the error (`refused`), emits no event when it\n * refuses, and builds events from ids, numbers, patterns and timestamps\n * only (test \"no secret bytes, reference or URL reaches an event …\").\n *\n * The stores are not Host's store, so a store write and Host's event append\n * are not one transaction. If Host fails after the handler's write (its\n * event append, or a crash before it commits), the write stands without its\n * event; the invocation is left `failed` or `running` for an operator to\n * reconcile. Subscription and rotation actions are declared not idempotent,\n * so Host refuses to re-run an interrupted one (\"manual reconciliation is\n * required\"). The requeue and enrichment actions are idempotent: every\n * attempt of one invocation, one after another or overlapping, reports the\n * change some attempt of it committed, from that change's evidence, even\n * after the record it names was purged (`oncePerInvocation`; the stores\n * recognize the invocation in their compare-and-set's atomic step).\n */\n\n// ---------------------------------------------------------------------------\n// Public options and ports\n// ---------------------------------------------------------------------------\n\n/** What the module's operator policy asks the application about one invocation. */\nexport interface WebhookOperatorAuthorizationInput {\n\t/** `<namespace>.<action name>`. */\n\treadonly actionId: string;\n\treadonly action: WebhookDeliveryActionName;\n\treadonly tenantId: string;\n\treadonly spaceId: string;\n\treadonly actorId: string;\n\treadonly actorType: string;\n\t/** The ids the action names, copied from three id fields by `operatorPolicy`; no URL or secret reference. */\n\treadonly target: {\n\t\treadonly subscriptionId?: string;\n\t\treadonly deliveryId?: string;\n\t\treadonly eventId?: string;\n\t};\n}\n\n/**\n * The module policy's question (`<namespace>.operator_authorized.v1`). Only a\n * literal `true` passes; `false`, any other answer, a throw or a timeout\n * blocks the invocation. Deny by default: the module cannot be built\n * without it.\n */\nexport type WebhookOperatorAuthorization = (\n\tinput: WebhookOperatorAuthorizationInput,\n\toptions: WebhookCallOptions,\n) => boolean | Promise<boolean>;\n\n/**\n * Confirms that a secret reference names a secret of this tenant in the\n * application's secret store (decision 8): at admission, before Host records\n * the submission, and again before the action writes it. Only a literal\n * `\"valid\"` passes. It must not return or log the secret, and it should honour\n * `options.signal`, which Host aborts at its admission deadline.\n */\nexport interface WebhookSecretReferenceVerifier {\n\tverify(input: WebhookScope & { readonly secretRef: string }, options: WebhookCallOptions): Promise<\"valid\" | \"invalid\">;\n}\n\n/**\n * What the application's actor reader found on the canonical event\n * (decision 5). `withheld`: the application's own actor-disclosure rule for\n * this event (the same rule as Host's `includeActor` hook) excludes the\n * actor, so enrichment must not add it. `not_found`: no such event in this\n * tenant and space.\n */\nexport type WebhookEventActorReading =\n\t| { readonly state: \"found\"; readonly actorId: string; readonly actorType: string }\n\t| { readonly state: \"withheld\" }\n\t| { readonly state: \"not_found\" };\n\n/** Reads the actor of the canonical event for a legacy job's tenant, space and `eventId` (decision 5). */\nexport interface WebhookEventActorReader {\n\treadEventActor(\n\t\tinput: WebhookScope & {\n\t\t\treadonly eventId: string;\n\t\t\treadonly eventType: string;\n\t\t\treadonly payloadClassification: string;\n\t\t},\n\t\toptions: WebhookCallOptions,\n\t): Promise<WebhookEventActorReading>;\n}\n\n/** Options for {@link createWebhookDeliveryModule}. */\nexport interface WebhookDeliveryModuleOptions {\n\t/** The module namespace; actions are `<namespace>.<name>`. Default `webhook-delivery`. */\n\treadonly namespace?: string;\n\treadonly subscriptions: WebhookSubscriptionStore & WebhookSubscriptionWriter;\n\treadonly deliveries: WebhookDeliveryStore;\n\t/** Re-validates a destination at configuration change and at intent requeue (decision 6). */\n\treadonly resolver: WebhookDestinationResolver;\n\treadonly secretReferences: WebhookSecretReferenceVerifier;\n\treadonly actorReader: WebhookEventActorReader;\n\treadonly authorizeOperatorAction: WebhookOperatorAuthorization;\n\treadonly clock: WebhookClock;\n\t/** `portTimeoutMs` bounds every port call; `fanOutDeadlineMs` and `deliveryDeadlineMs` set requeued deadlines; `attemptTimeoutMs` enters the staged rotation's retention. */\n\treadonly limits?: Partial<WebhookDeliveryLimits>;\n\t/** The receivers' signature timestamp tolerance, for a staged rotation's `previousSecretRetainUntil`. Default 300 000 (R6). */\n\treadonly verifierToleranceMs?: number;\n}\n\n/** The module policy's id for a namespace. */\nexport function webhookOperatorPolicyId(namespace: string = DEFAULT_WEBHOOK_DELIVERY_NAMESPACE): `${string}.v${number}` {\n\treturn `${namespace}.operator_authorized.v1`;\n}\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\ninterface Deps {\n\treadonly namespace: string;\n\treadonly subscriptions: WebhookSubscriptionStore & WebhookSubscriptionWriter;\n\treadonly deliveries: WebhookDeliveryStore;\n\treadonly resolver: WebhookDestinationResolver;\n\treadonly secretReferences: WebhookSecretReferenceVerifier;\n\treadonly actorReader: WebhookEventActorReader;\n\treadonly authorize: WebhookOperatorAuthorization;\n\treadonly clock: FanOutClock;\n\treadonly limits: WebhookDeliveryLimits;\n\treadonly verifierToleranceMs: number;\n}\n\nconst SUBSCRIPTION = \"WebhookSubscription\";\nconst INTENT = \"WebhookDeliveryIntent\";\nconst JOB = \"WebhookFanOutJob\";\n\n/** A refusal: the handler's result and Host's durable error. */\nfunction refused(code: WebhookActionRefusalCode): ActionResult {\n\treturn { success: false, error: `webhook_action_refused:${code}` };\n}\n\n/** A success with its one event (Host's default `_events` result field). */\nfunction emitted(eventType: WebhookDeliveryActionEventType, subjectType: string, subjectId: string, payload: Record<string, unknown>): ActionResult {\n\treturn {\n\t\tsuccess: true,\n\t\tdata: { ...payload, _events: [{ eventType, eventSchemaVersion: 1, subjectType, subjectId, payload }] },\n\t};\n}\n\n/**\n * A thrown marker that ends a handler with a refusal; `handlerFor`'s catch\n * turns it into the result. Recognized by its private field (`Stop.is`),\n * which only this class can create and which a brand check reads without\n * running any of the value's code, so a port answer that throws a\n * look-alike `{ stop: … }` (from an iterator or a Proxy trap) is not taken\n * for one. Not exported; keeps no registry (Boundary Guard G5).\n */\nclass Stop {\n\treadonly #brand = true;\n\treadonly code: WebhookActionRefusalCode;\n\n\tconstructor(code: WebhookActionRefusalCode) {\n\t\tthis.code = code;\n\t\tfreeze(this);\n\t}\n\n\t/** Whether `value` was made by this class's constructor. Reads nothing of `value`. */\n\tstatic is(value: unknown): value is Stop {\n\t\treturn value !== null && typeof value === \"object\" && #brand in value;\n\t}\n}\n\nfunction stop(code: WebhookActionRefusalCode): never {\n\tthrow new Stop(code);\n}\n\nconst getOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;\n\n/** An own data property of a port's answer, or `undefined`; a getter is not called, and a throwing Proxy trap reads as `undefined`. */\nfunction prop(value: unknown, key: string): unknown {\n\tif (value === null || typeof value !== \"object\") return undefined;\n\ttry {\n\t\tconst descriptor = getOwnPropertyDescriptor(value, key);\n\t\treturn descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction whole(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && numberIsSafeInteger(value) && value >= 0 ? value : undefined;\n}\n\nfunction nowMs(deps: Deps): number {\n\ttry {\n\t\treturn readFanOutClock(deps.clock);\n\t} catch {\n\t\treturn stop(\"action_failed\");\n\t}\n}\n\n/**\n * One port call, bounded by `portTimeoutMs` (R4) and aborted with `parent`.\n * `undefined` when it threw, timed out or was aborted; the thrown value is\n * never read.\n */\nasync function port<T>(deps: Deps, run: (options: WebhookCallOptions) => Promise<T>, parent?: AbortSignal): Promise<{ readonly value: T } | undefined> {\n\tconst outcome = await boundedCall(nowMs(deps), deps.limits.portTimeoutMs, parent, run, () => readFanOutClock(deps.clock));\n\treturn outcome.ok ? { value: outcome.value } : undefined;\n}\n\n/**\n * Host's trusted scope for the invocation. Every store call an action makes\n * is given this scope and no other: no action parameter names a tenant or a\n * space (`ALLOWED_KEYS` in src/action-parameters.ts refuses the keys).\n */\nfunction scopeOf(ctx: ActionContext<unknown>): WebhookScope {\n\tconst tenantId = prop(ctx, \"tenantId\");\n\tconst spaceId = prop(ctx, \"spaceId\");\n\tif (!isWebhookIdentifier(tenantId) || !isWebhookIdentifier(spaceId)) stop(\"scope_invalid\");\n\treturn freeze({ tenantId, spaceId });\n}\n\nfunction actorOf(ctx: ActionContext<unknown>): string {\n\tconst actorId = prop(ctx, \"actorId\");\n\tif (!isWebhookIdentifier(actorId)) stop(\"actor_invalid\");\n\treturn actorId;\n}\n\nfunction invocationOf(ctx: ActionContext<unknown>): string | undefined {\n\tconst id = prop(ctx, \"actionInvocationId\");\n\treturn isWebhookIdentifier(id) ? id : undefined;\n}\n\ninterface SubscriptionRead {\n\treadonly status: string;\n\t/** The revision the current status began at (`WebhookSubscriptionSnapshot.statusSinceRevision`). */\n\treadonly statusSinceRevision: number;\n\treadonly version: number;\n\treadonly destinationUrl: string;\n\treadonly signatureScheme: \"v1\";\n\treadonly secretRef: string;\n}\n\n/** The subscription's current status and configuration in `scope`; refuses when absent or unreadable. */\nasync function currentSubscription(deps: Deps, scope: WebhookScope, subscriptionId: string): Promise<SubscriptionRead> {\n\tconst answer = await port(deps, (options) => deps.subscriptions.readSubscription({ ...scope, subscriptionId }, options));\n\tif (answer === undefined) return stop(\"store_unavailable\");\n\tif (answer.value === null) return stop(\"subscription_not_found\");\n\tconst configuration = prop(answer.value, \"configuration\");\n\tconst read = {\n\t\tstatus: prop(answer.value, \"status\"),\n\t\tstatusSinceRevision: whole(prop(answer.value, \"statusSinceRevision\")),\n\t\tversion: whole(prop(configuration, \"version\")),\n\t\tdestinationUrl: prop(configuration, \"destinationUrl\"),\n\t\tsignatureScheme: prop(configuration, \"signatureScheme\"),\n\t\tsecretRef: prop(configuration, \"secretRef\"),\n\t};\n\t// The answer must be the subscription asked for, in this scope.\n\tif (prop(answer.value, \"subscriptionId\") !== subscriptionId || prop(answer.value, \"tenantId\") !== scope.tenantId || prop(answer.value, \"spaceId\") !== scope.spaceId) {\n\t\treturn stop(\"subscription_not_found\");\n\t}\n\tif (!isOneOf([\"active\", \"paused\", \"deleted\"], read.status) || read.statusSinceRevision === undefined || read.statusSinceRevision < 1 ||\n\t\tread.version === undefined || typeof read.destinationUrl !== \"string\" ||\n\t\tread.signatureScheme !== \"v1\" || typeof read.secretRef !== \"string\") {\n\t\treturn stop(\"store_unavailable\");\n\t}\n\treturn read as SubscriptionRead;\n}\n\n/** Ask the application's secret store whether `secretRef` names one of this tenant's secrets. */\nasync function verifySecretRef(deps: Deps, scope: WebhookScope, secretRef: string, parent?: AbortSignal): Promise<void> {\n\tconst answer = await port(deps, (options) => deps.secretReferences.verify({ ...scope, secretRef }, options), parent);\n\tif (answer === undefined) stop(\"secret_ref_unverified\");\n\tif (answer.value === \"invalid\") stop(\"secret_ref_invalid\");\n\tif (answer.value !== \"valid\") stop(\"secret_ref_unverified\");\n}\n\n/** Re-validate a destination with the resolver (decision 6): only a vetted answer passes. */\nasync function vetDestination(deps: Deps, url: string): Promise<void> {\n\tconst answer = await port(deps, (options) => deps.resolver.resolve(url, options));\n\tif (answer === undefined) stop(\"destination_unresolved\");\n\tif (prop(answer.value, \"ok\") === true) return;\n\tconst code = prop(answer.value, \"code\");\n\tstop(code === \"invalid_url\" || code === \"private_address\" ? \"destination_refused\" : \"destination_unresolved\");\n}\n\nconst SUBSCRIPTION_REFUSALS: { readonly [refusal: string]: WebhookActionRefusalCode } = freeze({\n\tnot_found: \"subscription_not_found\",\n\talready_exists: \"subscription_exists\",\n\tdeleted: \"subscription_deleted\",\n\tinvalid_transition: \"invalid_transition\",\n\trevision_conflict: \"revision_conflict\",\n\tversion_conflict: \"version_conflict\",\n});\n\nconst DELIVERY_REFUSALS: { readonly [refusal: string]: WebhookActionRefusalCode } = freeze({\n\tnot_found: \"not_found\",\n\tstale: \"stale\",\n\tnot_dead_letter: \"not_dead_letter\",\n\tpast_horizon: \"past_replay_horizon\",\n\tnot_enrichable: \"not_enrichable\",\n\tactor_present: \"actor_present\",\n\tactor_suppressed: \"actor_suppressed\",\n});\n\nfunction mapRefusal(table: { readonly [refusal: string]: WebhookActionRefusalCode }, refusal: unknown): WebhookActionRefusalCode {\n\treturn typeof refusal === \"string\" && isOneOf(Object.keys(table), refusal) ? table[refusal]! : \"store_outcome_unknown\";\n}\n\n/**\n * The answer of a store write. `undefined` (the write threw, timed out or\n * answered something unreadable) is `store_outcome_unknown`: it may have\n * applied, so nothing follows it.\n */\nfunction applied(answer: { readonly value: unknown } | undefined, refusals: { readonly [refusal: string]: WebhookActionRefusalCode }): unknown {\n\tif (answer === undefined) return stop(\"store_outcome_unknown\");\n\tconst flag = prop(answer.value, \"applied\");\n\tif (flag === true) return answer.value;\n\tif (flag === false) return stop(mapRefusal(refusals, prop(answer.value, \"refusal\")));\n\treturn stop(\"store_outcome_unknown\");\n}\n\n/** The record an idempotent action names, as its evidence names it. */\ntype EvidenceTarget =\n\t| { readonly target: \"delivery_intent\"; readonly deliveryId: string }\n\t| { readonly target: \"fan_out_job\" | \"fan_out_job_actor\"; readonly eventId: string };\n\n/**\n * Evidence this invocation appended for `target`, by any attempt of it, or\n * `undefined` (always, without an invocation id). Read with the invocation\n * id alone, so it is found whether or not the record it names still exists.\n */\nasync function priorEvidence(deps: Deps, scope: WebhookScope, invocationId: string | undefined, target: EvidenceTarget): Promise<unknown> {\n\tif (invocationId === undefined) return undefined;\n\tconst answer = await port(deps, (options) => deps.deliveries.listInvocationRequeueEvidence({ ...scope, actionInvocationId: invocationId }, options));\n\tif (answer === undefined) return stop(\"store_unavailable\");\n\tconst list = answer.value as unknown;\n\tif (!Array.isArray(list)) return stop(\"store_unavailable\");\n\tfor (const evidence of list) {\n\t\tif (prop(evidence, \"actionInvocationId\") !== invocationId || prop(evidence, \"target\") !== target.target) continue;\n\t\tif (prop(evidence, \"tenantId\") !== scope.tenantId || prop(evidence, \"spaceId\") !== scope.spaceId) continue;\n\t\tif (target.target === \"delivery_intent\" ? prop(evidence, \"deliveryId\") === target.deliveryId : prop(evidence, \"eventId\") === target.eventId) return evidence;\n\t}\n\treturn undefined;\n}\n\n/**\n * One attempt of an idempotent action (requeue, enrichment). Host may run\n * several attempts of one invocation, one after another or overlapping (a\n * worker whose lease expired is still running when recovery starts\n * another). An attempt reports the invocation's change when that change's\n * evidence is visible to one of its evidence reads (steps 1 and 3) or to its\n * store's atomic step (step 2); only the evidence decides it. Not covered:\n * an attempt that ended in a refusal while an older attempt was between its\n * checks and its compare-and-set, and the older attempt commits later. That\n * change stands while Host has recorded the refusal; the evidence names the\n * invocation for an operator to reconcile (README, \"Atomicity and re-runs\").\n * The steps:\n *\n * 1. Before anything about the record is read, the invocation's evidence:\n * the record may since have been claimed, delivered or purged, and the\n * subscription paused or deleted.\n * 2. Otherwise `apply` runs the action's checks and the store's\n * compare-and-set. The store answers a request of an invocation that\n * already applied with that evidence (`replayed`), in the same atomic step\n * as the compare (src/ports.ts, \"Re-runs of one invocation\").\n * 3. An attempt that `apply` ends with a refusal reads the evidence once\n * more: another attempt that committed after step 1 is why a check before\n * the compare-and-set saw the record or subscription changed. If that read\n * fails, the refusal stands.\n *\n * Returns the evidence of the change the invocation made.\n */\nasync function oncePerInvocation(\n\tdeps: Deps,\n\tscope: WebhookScope,\n\tinvocationId: string | undefined,\n\ttarget: EvidenceTarget,\n\tapply: () => Promise<unknown>,\n): Promise<unknown> {\n\tconst prior = await priorEvidence(deps, scope, invocationId, target);\n\tif (prior !== undefined) return prior;\n\ttry {\n\t\treturn await apply();\n\t} catch (thrown) {\n\t\tif (invocationId === undefined) throw thrown;\n\t\tlet committed: unknown;\n\t\ttry {\n\t\t\tcommitted = await priorEvidence(deps, scope, invocationId, target);\n\t\t} catch {\n\t\t\tthrow thrown;\n\t\t}\n\t\tif (committed !== undefined) return committed;\n\t\tthrow thrown;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\ntype Handler<N extends WebhookDeliveryActionName> = (\n\tdeps: Deps,\n\tctx: ActionContext<unknown>,\n\tscope: WebhookScope,\n\tparams: WebhookDeliveryActionParameters[N],\n) => Promise<ActionResult>;\n\ntype Handlers = { readonly [N in WebhookDeliveryActionName]: Handler<N> };\n\nfunction subscriptionEvent(\n\teventType: WebhookDeliveryActionEventType,\n\tsubscriptionId: string,\n\tpayload: Record<string, unknown>,\n): ActionResult {\n\treturn emitted(eventType, SUBSCRIPTION, subscriptionId, { subscriptionId, ...payload });\n}\n\nfunction revisionOf(result: unknown): number {\n\tconst revision = whole(prop(prop(result, \"revision\"), \"revision\"));\n\treturn revision ?? stop(\"store_outcome_unknown\");\n}\n\nfunction versionOf(result: unknown): number {\n\tconst version = whole(prop(prop(result, \"configuration\"), \"version\"));\n\treturn version ?? stop(\"store_outcome_unknown\");\n}\n\n/** Pause and delete: the transition, then `cancelPendingIntents` for the intents of the revisions it ended. */\nasync function stopSubscription(\n\tdeps: Deps,\n\tscope: WebhookScope,\n\tparams: WebhookDeliveryActionParameters[\"pause_subscription\"],\n\tkind: \"pause\" | \"delete\",\n): Promise<ActionResult> {\n\tconst write = kind === \"pause\"\n\t\t? (options: WebhookCallOptions) => deps.subscriptions.pauseSubscription({ ...scope, ...params }, options)\n\t\t: (options: WebhookCallOptions) => deps.subscriptions.deleteSubscription({ ...scope, ...params }, options);\n\tconst revision = revisionOf(applied(await port(deps, write), SUBSCRIPTION_REFUSALS));\n\tconst cancelledPendingIntents = await cleanUp(deps, scope, params.subscriptionId, kind === \"pause\" ? \"subscription_paused\" : \"subscription_deleted\", revision);\n\treturn subscriptionEvent(kind === \"pause\" ? \"WebhookSubscriptionPaused\" : \"WebhookSubscriptionDeleted\", params.subscriptionId, {\n\t\trevision,\n\t\tcancelledPendingIntents,\n\t});\n}\n\n/**\n * Pause, resume and delete: after the revision is written, cancel the\n * subscription's pending intents bound to revisions before it. A cleanup,\n * not the guarantee: the count, or `null` when the call threw, timed out or\n * answered something unreadable, and the action stands either way. What\n * stops those intents is dispatch (src/delivery-cycle.ts, `readState`):\n * it cancels an intent while the subscription is paused or deleted, and\n * while it is active since a revision later than the intent's (README,\n * \"Pause and resume are enforced at dispatch\"). Passing the revision just\n * written leaves intents of any later revision alone.\n */\nasync function cleanUp(\n\tdeps: Deps,\n\tscope: WebhookScope,\n\tsubscriptionId: string,\n\treason: \"subscription_paused\" | \"subscription_deleted\",\n\tbeforeRevision: number,\n): Promise<number | null> {\n\tconst cancelled = await port(deps, (options) => deps.deliveries.cancelPendingIntents({\n\t\t...scope,\n\t\tsubscriptionId,\n\t\treason,\n\t\tbeforeRevision,\n\t\tnow: new Date(nowMs(deps)),\n\t}, options));\n\treturn (cancelled === undefined ? undefined : whole(cancelled.value)) ?? null;\n}\n\n/** Staged and emergency rotation: a new configuration version with the same destination and scheme, and the next secret reference. */\nasync function rotate(\n\tdeps: Deps,\n\tscope: WebhookScope,\n\tparams: { readonly subscriptionId: string; readonly secretRef: string; readonly expectedVersion?: number },\n\tmode: \"staged\" | \"emergency\",\n): Promise<ActionResult> {\n\tconst current = await currentSubscription(deps, scope, params.subscriptionId);\n\tif (current.status === \"deleted\") stop(\"subscription_deleted\");\n\tif (params.expectedVersion !== undefined && params.expectedVersion !== current.version) stop(\"version_conflict\");\n\tif (params.secretRef === current.secretRef) stop(\"secret_ref_unchanged\");\n\tawait verifySecretRef(deps, scope, params.secretRef);\n\tconst result = applied(await port(deps, (options) => deps.subscriptions.replaceDeliveryConfiguration({\n\t\t...scope,\n\t\tsubscriptionId: params.subscriptionId,\n\t\tconfiguration: { destinationUrl: current.destinationUrl, signatureScheme: current.signatureScheme, secretRef: params.secretRef },\n\t\t// The version read above, so a concurrent change between the read and\n\t\t// the write is refused by the store's compare-and-set.\n\t\texpectedVersion: params.expectedVersion ?? current.version,\n\t}, options)), SUBSCRIPTION_REFUSALS);\n\tconst configurationVersion = versionOf(result);\n\tconst activatedAtMs = nowMs(deps);\n\t// R6 and README, \"Old-secret retention\": a request signed with the old\n\t// secret reaches a receiver at most portTimeoutMs + attemptTimeoutMs after\n\t// activation (worker's clock), plus the receiver's timestamp tolerance.\n\tconst retainMs = deps.limits.portTimeoutMs + deps.limits.attemptTimeoutMs + deps.verifierToleranceMs;\n\treturn subscriptionEvent(\"WebhookSecretRotated\", params.subscriptionId, {\n\t\tmode,\n\t\tconfigurationVersion,\n\t\tactivatedAt: isoOf(activatedAtMs),\n\t\tpreviousSecretRetainUntil: mode === \"staged\" ? isoOf(activatedAtMs + retainMs) : null,\n\t});\n}\n\nconst HANDLERS: Handlers = freeze({\n\tasync create_subscription(deps, _ctx, scope, params) {\n\t\tawait verifySecretRef(deps, scope, params.secretRef);\n\t\tawait vetDestination(deps, params.destinationUrl);\n\t\tconst result = applied(await port(deps, (options) => deps.subscriptions.createSubscription({\n\t\t\t...scope,\n\t\t\tsubscriptionId: params.subscriptionId,\n\t\t\teventTypePatterns: params.eventTypePatterns,\n\t\t\tconfiguration: { destinationUrl: params.destinationUrl, signatureScheme: \"v1\", secretRef: params.secretRef },\n\t\t}, options)), SUBSCRIPTION_REFUSALS);\n\t\treturn subscriptionEvent(\"WebhookSubscriptionCreated\", params.subscriptionId, {\n\t\t\trevision: revisionOf(result),\n\t\t\tconfigurationVersion: versionOf(result),\n\t\t\teventTypePatterns: [...params.eventTypePatterns],\n\t\t});\n\t},\n\n\tasync update_subscription(deps, _ctx, scope, params) {\n\t\tif (\"eventTypePatterns\" in params) {\n\t\t\tconst result = applied(await port(deps, (options) => deps.subscriptions.changeEventTypePatterns({ ...scope, ...params }, options)), SUBSCRIPTION_REFUSALS);\n\t\t\treturn subscriptionEvent(\"WebhookSubscriptionUpdated\", params.subscriptionId, {\n\t\t\t\tchange: \"event_type_patterns\",\n\t\t\t\trevision: revisionOf(result),\n\t\t\t\teventTypePatterns: [...params.eventTypePatterns],\n\t\t\t});\n\t\t}\n\t\tconst current = await currentSubscription(deps, scope, params.subscriptionId);\n\t\tif (current.status === \"deleted\") stop(\"subscription_deleted\");\n\t\tif (params.expectedVersion !== undefined && params.expectedVersion !== current.version) stop(\"version_conflict\");\n\t\tawait vetDestination(deps, params.destinationUrl);\n\t\tconst result = applied(await port(deps, (options) => deps.subscriptions.replaceDeliveryConfiguration({\n\t\t\t...scope,\n\t\t\tsubscriptionId: params.subscriptionId,\n\t\t\tconfiguration: { destinationUrl: params.destinationUrl, signatureScheme: current.signatureScheme, secretRef: current.secretRef },\n\t\t\texpectedVersion: params.expectedVersion ?? current.version,\n\t\t}, options)), SUBSCRIPTION_REFUSALS);\n\t\treturn subscriptionEvent(\"WebhookSubscriptionUpdated\", params.subscriptionId, {\n\t\t\tchange: \"destination\",\n\t\t\tconfigurationVersion: versionOf(result),\n\t\t});\n\t},\n\n\tpause_subscription: (deps, _ctx, scope, params) => stopSubscription(deps, scope, params, \"pause\"),\n\n\tasync resume_subscription(deps, _ctx, scope, params) {\n\t\t// Resume does not resurrect (decision 3): a cancelled intent is\n\t\t// terminal, dispatch cancels any intent bound to a revision before\n\t\t// this one (the pause's cleanup may have missed it, or fan-out written\n\t\t// it late), and intent requeue refuses one (`paused_since_intent`).\n\t\t// The cleanup below cancels what is pending now, so it does not sit\n\t\t// until a worker claims it.\n\t\tconst result = applied(await port(deps, (options) => deps.subscriptions.resumeSubscription({ ...scope, ...params }, options)), SUBSCRIPTION_REFUSALS);\n\t\tconst revision = revisionOf(result);\n\t\tconst cancelledPendingIntents = await cleanUp(deps, scope, params.subscriptionId, \"subscription_paused\", revision);\n\t\treturn subscriptionEvent(\"WebhookSubscriptionResumed\", params.subscriptionId, { revision, cancelledPendingIntents });\n\t},\n\n\tdelete_subscription: (deps, _ctx, scope, params) => stopSubscription(deps, scope, params, \"delete\"),\n\n\trotate_secret_staged: (deps, _ctx, scope, params) => rotate(deps, scope, params, \"staged\"),\n\n\trotate_secret_emergency: (deps, _ctx, scope, params) => rotate(deps, scope, params, \"emergency\"),\n\n\tasync requeue_delivery_intent(deps, ctx, scope, params) {\n\t\tconst requestedBy = actorOf(ctx);\n\t\tconst invocationId = invocationOf(ctx);\n\t\tconst evidence = await oncePerInvocation(deps, scope, invocationId, { target: \"delivery_intent\", deliveryId: params.deliveryId }, async () => {\n\t\t\tconst read = await port(deps, (options) => deps.deliveries.readDeliveryIntent({ ...scope, deliveryId: params.deliveryId }, options));\n\t\t\tif (read === undefined) return stop(\"store_unavailable\");\n\t\t\tif (read.value === null) return stop(\"not_found\");\n\t\t\tconst subscriptionId = prop(read.value, \"subscriptionId\");\n\t\t\tconst eligibilityRevision = whole(prop(read.value, \"eligibilityRevision\"));\n\t\t\tif (!isWebhookIdentifier(subscriptionId) || eligibilityRevision === undefined) return stop(\"store_unavailable\");\n\t\t\t// Decision 10: the destination is re-validated at requeue. Dispatch\n\t\t\t// resolves it again before every attempt regardless.\n\t\t\tconst subscription = await currentSubscription(deps, scope, subscriptionId);\n\t\t\tif (subscription.status !== \"active\") stop(\"subscription_not_active\");\n\t\t\t// Paused and resumed since the intent's revision: dispatch would\n\t\t\t// cancel it, so it is not requeued (decision 3). A pause and resume\n\t\t\t// between this read and the compare-and-set is still caught there.\n\t\t\tif (eligibilityRevision < subscription.statusSinceRevision) stop(\"paused_since_intent\");\n\t\t\tawait vetDestination(deps, subscription.destinationUrl);\n\t\t\tconst now = nowMs(deps);\n\t\t\treturn prop(applied(await port(deps, (options) => deps.deliveries.requeueDeliveryIntent({\n\t\t\t\t...scope,\n\t\t\t\tdeliveryId: params.deliveryId,\n\t\t\t\t// The compare-and-set is the store's: fence and status are checked\n\t\t\t\t// in the same atomic step as the transition (src/ports.ts).\n\t\t\t\trequest: {\n\t\t\t\t\texpectedStatus: \"dead_letter\",\n\t\t\t\t\texpectedFence: params.expectedFence,\n\t\t\t\t\trequestedBy,\n\t\t\t\t\trequestedAt: new Date(now),\n\t\t\t\t\tprocessingDeadline: new Date(now + deps.limits.deliveryDeadlineMs),\n\t\t\t\t\t...(invocationId === undefined ? {} : { actionInvocationId: invocationId }),\n\t\t\t\t},\n\t\t\t}, options)), DELIVERY_REFUSALS), \"evidence\");\n\t\t});\n\t\t// From the evidence, not the intent, which a re-run may find purged.\n\t\tconst eventId = prop(evidence, \"eventId\");\n\t\tif (!isWebhookIdentifier(eventId)) return stop(\"store_outcome_unknown\");\n\t\tconst subscriptionId = prop(evidence, \"subscriptionId\") ?? await legacyIntentSubscription(deps, scope, params.deliveryId, eventId);\n\t\tif (!isWebhookIdentifier(subscriptionId)) return stop(\"store_outcome_unknown\");\n\t\treturn emitted(\"WebhookDeliveryIntentRequeued\", INTENT, params.deliveryId, {\n\t\t\tdeliveryId: params.deliveryId,\n\t\t\tsubscriptionId,\n\t\t\teventId,\n\t\t\t...evidenceFields(evidence),\n\t\t});\n\t},\n\n\tasync requeue_fan_out_job(deps, ctx, scope, params) {\n\t\tconst requestedBy = actorOf(ctx);\n\t\tconst invocationId = invocationOf(ctx);\n\t\tconst evidence = await oncePerInvocation(deps, scope, invocationId, { target: \"fan_out_job\", eventId: params.eventId }, async () => {\n\t\t\tconst now = nowMs(deps);\n\t\t\treturn prop(applied(await port(deps, (options) => deps.deliveries.requeueFanOutJob({\n\t\t\t\t...scope,\n\t\t\t\teventId: params.eventId,\n\t\t\t\trequest: {\n\t\t\t\t\texpectedStatus: \"dead_letter\",\n\t\t\t\t\texpectedFence: params.expectedFence,\n\t\t\t\t\trequestedBy,\n\t\t\t\t\trequestedAt: new Date(now),\n\t\t\t\t\tprocessingDeadline: new Date(now + deps.limits.fanOutDeadlineMs),\n\t\t\t\t\t...(invocationId === undefined ? {} : { actionInvocationId: invocationId }),\n\t\t\t\t},\n\t\t\t}, options)), DELIVERY_REFUSALS), \"evidence\");\n\t\t});\n\t\treturn emitted(\"WebhookFanOutJobRequeued\", JOB, params.eventId, { eventId: params.eventId, ...evidenceFields(evidence) });\n\t},\n\n\tasync enrich_fan_out_job_actor(deps, ctx, scope, params) {\n\t\tconst requestedBy = actorOf(ctx);\n\t\tconst invocationId = invocationOf(ctx);\n\t\tconst evidence = await oncePerInvocation(deps, scope, invocationId, { target: \"fan_out_job_actor\", eventId: params.eventId }, async () => {\n\t\t\tconst read = await port(deps, (options) => deps.deliveries.readFanOutJob({ ...scope, eventId: params.eventId }, options));\n\t\t\tif (read === undefined) return stop(\"store_unavailable\");\n\t\t\tif (read.value === null) return stop(\"not_found\");\n\t\t\t// Early refusals, so the application's reader is not asked for an\n\t\t\t// actor that would be refused. The store re-checks each in its\n\t\t\t// atomic step; these are not the guard.\n\t\t\tconst actor = prop(read.value, \"actor\");\n\t\t\tif (prop(read.value, \"status\") === \"completed\") return stop(\"not_enrichable\");\n\t\t\tif (prop(actor, \"state\") === \"present\") return stop(\"actor_present\");\n\t\t\tif (prop(actor, \"reason\") === \"suppressed\") return stop(\"actor_suppressed\");\n\t\t\tconst event = prop(read.value, \"event\");\n\t\t\tconst eventType = prop(event, \"eventType\");\n\t\t\tconst payloadClassification = prop(event, \"payloadClassification\");\n\t\t\tif (typeof eventType !== \"string\" || typeof payloadClassification !== \"string\") return stop(\"store_unavailable\");\n\t\t\tconst found = await port(deps, (options) => deps.actorReader.readEventActor({ ...scope, eventId: params.eventId, eventType, payloadClassification }, options));\n\t\t\tif (found === undefined) return stop(\"actor_unavailable\");\n\t\t\tconst state = prop(found.value, \"state\");\n\t\t\tif (state === \"withheld\") return stop(\"actor_withheld\");\n\t\t\tif (state === \"not_found\") return stop(\"actor_not_found\");\n\t\t\tconst actorId = prop(found.value, \"actorId\");\n\t\t\tconst actorType = prop(found.value, \"actorType\");\n\t\t\tif (state !== \"found\" || !isWebhookIdentifier(actorId) || !isWebhookIdentifier(actorType)) return stop(\"actor_unavailable\");\n\t\t\tconst now = nowMs(deps);\n\t\t\treturn prop(applied(await port(deps, (options) => deps.deliveries.enrichFanOutJobActor({\n\t\t\t\t...scope,\n\t\t\t\teventId: params.eventId,\n\t\t\t\trequest: {\n\t\t\t\t\texpectedFence: params.expectedFence,\n\t\t\t\t\tactor: { actorId, actorType },\n\t\t\t\t\trequestedBy,\n\t\t\t\t\trequestedAt: new Date(now),\n\t\t\t\t\tprocessingDeadline: new Date(now + deps.limits.fanOutDeadlineMs),\n\t\t\t\t\t...(invocationId === undefined ? {} : { actionInvocationId: invocationId }),\n\t\t\t\t},\n\t\t\t}, options)), DELIVERY_REFUSALS), \"evidence\");\n\t\t});\n\t\t// The actor itself stays in the store's evidence, not in the event.\n\t\treturn emitted(\"WebhookFanOutJobActorEnriched\", JOB, params.eventId, { eventId: params.eventId, ...evidenceFields(evidence) });\n\t},\n});\n\n/**\n * The subscription of a requeued intent whose evidence was written before\n * evidence named it (`WebhookRequeueEvidence.subscriptionId`), read from the\n * intent in the invocation's scope. The requeue has applied, so a purged\n * intent, one of another event, or a read that fails is\n * `store_outcome_unknown`: the change stands without its event, for an\n * operator to reconcile from the evidence (README, \"Atomicity and re-runs\").\n */\nasync function legacyIntentSubscription(deps: Deps, scope: WebhookScope, deliveryId: string, eventId: string): Promise<string> {\n\tconst read = await port(deps, (options) => deps.deliveries.readDeliveryIntent({ ...scope, deliveryId }, options));\n\tconst subscriptionId = prop(read?.value, \"subscriptionId\");\n\tif (read === undefined || read.value === null || prop(read.value, \"eventId\") !== eventId || !isWebhookIdentifier(subscriptionId)) {\n\t\treturn stop(\"store_outcome_unknown\");\n\t}\n\treturn subscriptionId;\n}\n\n/** The event fields taken from requeue or enrichment evidence: numbers and timestamps only. */\nfunction evidenceFields(evidence: unknown): Record<string, unknown> {\n\tconst priorFence = whole(prop(evidence, \"priorFence\"));\n\tconst priorAttemptCount = whole(prop(evidence, \"priorAttemptCount\"));\n\tconst processingDeadline = prop(evidence, \"processingDeadline\");\n\tif (priorFence === undefined || priorAttemptCount === undefined || typeof processingDeadline !== \"string\") return stop(\"store_outcome_unknown\");\n\treturn { priorFence, priorAttemptCount, processingDeadline };\n}\n\nconst dateGetTime = Date.prototype.getTime;\n\n/**\n * Host's record that this invocation's submission passed the action's\n * admission check. A Host older than 7.3.0 ignores `admitSubmission` and\n * passes no `admittedAt`; such a Host may already have persisted unchecked\n * parameters, so the action refuses rather than act on them.\n */\nfunction requireAdmission(ctx: ActionContext<unknown>): void {\n\tconst admittedAt = prop(ctx, \"admittedAt\");\n\tif (!(admittedAt instanceof Date) || !Number.isFinite(Reflect.apply(dateGetTime, admittedAt, []))) stop(\"admission_not_enforced\");\n}\n\n/** The handler Host calls: requires Host's admission record, re-reads the parameters, takes the scope from Host's context, never lets a throw out. */\nfunction handlerFor<N extends WebhookDeliveryActionName>(deps: Deps, name: N) {\n\tconst run = HANDLERS[name] as Handler<N>;\n\treturn async (ctx: ActionContext<unknown>, parameters: unknown): Promise<ActionResult> => {\n\t\ttry {\n\t\t\trequireAdmission(ctx);\n\t\t\tconst read = readWebhookActionParameters(name, parameters);\n\t\t\tif (!read.ok) return { success: false, error: `webhook_parameters_refused:${read.code}` };\n\t\t\treturn await run(deps, ctx, scopeOf(ctx), read.value);\n\t\t} catch (thrown) {\n\t\t\t// Only a package `Stop` is read, and its code is checked against the\n\t\t\t// fixed set again; anything else is dropped unread.\n\t\t\treturn refused(Stop.is(thrown) && isOneOf(WEBHOOK_ACTION_REFUSAL_CODES, thrown.code) ? thrown.code : \"action_failed\");\n\t\t}\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Admission\n// ---------------------------------------------------------------------------\n\n/** The actions whose parameters carry a secret reference, verified at admission and again before the write. */\nconst TAKES_SECRET_REF: readonly WebhookDeliveryActionName[] = freeze([\"create_subscription\", \"rotate_secret_staged\", \"rotate_secret_emergency\"] as const);\n\nfunction refusedAdmission(code: string): ActionAdmissionDecision {\n\treturn freeze({ admitted: false as const, code });\n}\n\nconst ADMITTED: ActionAdmissionDecision = freeze({ admitted: true as const });\n\n/**\n * The action's `admitSubmission` (ADR 0018 decision 8). Host runs it on\n * every submission, after authorizing the submitter and before it records\n * anything, with its own copy of the parameters and the submission's trusted\n * tenant, space and actor. It admits only parameters the package reader\n * accepts and, for an action that takes a `secretRef`, only a reference the\n * application's `secretReferences.verify` confirms for that tenant and space.\n * A refusal's code is fixed text: `webhook_parameters_refused:<code>:<field>`\n * (`WEBHOOK_ACTION_PARAMETER_CODES`, a declared field or `parameters`) or\n * `webhook_action_refused:<code>` (`WEBHOOK_ACTION_REFUSAL_CODES`). Never\n * throws; nothing a port throws is read.\n */\nfunction admissionFor(deps: Deps, name: WebhookDeliveryActionName): ActionAdmission {\n\tconst takesSecretRef = TAKES_SECRET_REF.includes(name);\n\treturn async (input) => {\n\t\ttry {\n\t\t\tconst read = readWebhookActionParameters(name, prop(input, \"parameters\"));\n\t\t\tif (!read.ok) return refusedAdmission(`webhook_parameters_refused:${read.code}:${read.field}`);\n\t\t\tif (takesSecretRef) {\n\t\t\t\tconst tenantId = prop(input, \"tenantId\");\n\t\t\t\tconst spaceId = prop(input, \"spaceId\");\n\t\t\t\tif (!isWebhookIdentifier(tenantId) || !isWebhookIdentifier(spaceId)) stop(\"scope_invalid\");\n\t\t\t\tconst signal = prop(input, \"signal\");\n\t\t\t\tawait verifySecretRef(deps, freeze({ tenantId, spaceId }), (read.value as { readonly secretRef: string }).secretRef, signal instanceof AbortSignal ? signal : undefined);\n\t\t\t}\n\t\t\treturn ADMITTED;\n\t\t} catch (thrown) {\n\t\t\treturn refusedAdmission(`webhook_action_refused:${Stop.is(thrown) && isOneOf(WEBHOOK_ACTION_REFUSAL_CODES, thrown.code) ? thrown.code : \"action_failed\"}`);\n\t\t}\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Policy\n// ---------------------------------------------------------------------------\n\nfunction block(policyId: `${string}.v${number}`, reason: string): PolicyOutcome {\n\treturn { policyId, policyVersion: 1, policyKind: \"code\", result: \"block\", reason };\n}\n\nfunction operatorPolicy(deps: Deps): PolicyEvaluator {\n\tconst policyId = webhookOperatorPolicyId(deps.namespace);\n\treturn freeze({\n\t\tpolicyId,\n\t\tversion: 1,\n\t\tkind: \"code\" as const,\n\t\tasync evaluate(ctx: PolicyContext): Promise<PolicyOutcome> {\n\t\t\ttry {\n\t\t\t\tconst action = webhookActionNameOf(deps.namespace, ctx.actionId);\n\t\t\t\tif (action === undefined) return block(policyId, \"action_not_in_module\");\n\t\t\t\tconst read = readWebhookActionParameters(action, ctx.parameters);\n\t\t\t\tif (!read.ok) return block(policyId, \"parameters_invalid\");\n\t\t\t\tconst { tenantId, spaceId, actorId, actorType } = ctx;\n\t\t\t\tif (!isWebhookIdentifier(tenantId) || !isWebhookIdentifier(spaceId) || !isWebhookIdentifier(actorId) || typeof actorType !== \"string\") {\n\t\t\t\t\treturn block(policyId, \"operator_identity_unavailable\");\n\t\t\t\t}\n\t\t\t\tconst value = read.value as Record<string, unknown>;\n\t\t\t\tconst target = freeze({\n\t\t\t\t\t...(typeof value[\"subscriptionId\"] === \"string\" ? { subscriptionId: value[\"subscriptionId\"] } : {}),\n\t\t\t\t\t...(typeof value[\"deliveryId\"] === \"string\" ? { deliveryId: value[\"deliveryId\"] } : {}),\n\t\t\t\t\t...(typeof value[\"eventId\"] === \"string\" ? { eventId: value[\"eventId\"] } : {}),\n\t\t\t\t});\n\t\t\t\tconst input = freeze({ actionId: ctx.actionId, action, tenantId, spaceId, actorId, actorType, target });\n\t\t\t\tconst answer = await port(deps, async (options) => apply(deps.authorize, undefined, [input, options]));\n\t\t\t\tif (answer === undefined) return block(policyId, \"operator_authorization_unavailable\");\n\t\t\t\tif (answer.value !== true) return block(policyId, \"operator_not_authorized\");\n\t\t\t\treturn { policyId, policyVersion: 1, policyKind: \"code\", result: \"pass\" };\n\t\t\t} catch {\n\t\t\t\treturn block(policyId, \"operator_authorization_unavailable\");\n\t\t\t}\n\t\t},\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// The module\n// ---------------------------------------------------------------------------\n\nconst EVENT_FOR: { readonly [N in WebhookDeliveryActionName]: readonly WebhookDeliveryActionEventType[] } = freeze({\n\tcreate_subscription: freeze([\"WebhookSubscriptionCreated\"] as const),\n\tupdate_subscription: freeze([\"WebhookSubscriptionUpdated\"] as const),\n\tpause_subscription: freeze([\"WebhookSubscriptionPaused\"] as const),\n\tresume_subscription: freeze([\"WebhookSubscriptionResumed\"] as const),\n\tdelete_subscription: freeze([\"WebhookSubscriptionDeleted\"] as const),\n\trotate_secret_staged: freeze([\"WebhookSecretRotated\"] as const),\n\trotate_secret_emergency: freeze([\"WebhookSecretRotated\"] as const),\n\trequeue_delivery_intent: freeze([\"WebhookDeliveryIntentRequeued\"] as const),\n\trequeue_fan_out_job: freeze([\"WebhookFanOutJobRequeued\"] as const),\n\tenrich_fan_out_job_actor: freeze([\"WebhookFanOutJobActorEnriched\"] as const),\n});\n\n/** An attempt of one invocation of these reports the change another attempt committed when its evidence reads or the store's atomic step see it (`oncePerInvocation`, with its one exception); the others are not re-run by Host. */\nconst IDEMPOTENT: readonly WebhookDeliveryActionName[] = freeze([\"requeue_delivery_intent\", \"requeue_fan_out_job\", \"enrich_fan_out_job_actor\"] as const);\n\nfunction readDeps(options: WebhookDeliveryModuleOptions): Deps {\n\tconst fail = (field: string): never => {\n\t\tthrow governedActionError(\"options_invalid\", field);\n\t};\n\tif (options === null || typeof options !== \"object\") fail(\"options\");\n\tconst namespace = options.namespace ?? DEFAULT_WEBHOOK_DELIVERY_NAMESPACE;\n\tif (!isWebhookDeliveryNamespace(namespace)) fail(\"namespace\");\n\tconst needs = (value: unknown, field: string, methods: readonly string[]) => {\n\t\tif (value === null || typeof value !== \"object\") fail(field);\n\t\tfor (const method of methods) if (typeof (value as Record<string, unknown>)[method] !== \"function\") fail(`${field}.${method}`);\n\t};\n\tneeds(options.subscriptions, \"subscriptions\", [\n\t\t\"readSubscription\", \"createSubscription\", \"changeEventTypePatterns\", \"pauseSubscription\", \"resumeSubscription\", \"deleteSubscription\", \"replaceDeliveryConfiguration\",\n\t]);\n\tneeds(options.deliveries, \"deliveries\", [\n\t\t\"readDeliveryIntent\", \"readFanOutJob\", \"requeueDeliveryIntent\", \"requeueFanOutJob\", \"enrichFanOutJobActor\", \"cancelPendingIntents\", \"listInvocationRequeueEvidence\",\n\t]);\n\tneeds(options.resolver, \"resolver\", [\"resolve\"]);\n\tneeds(options.secretReferences, \"secretReferences\", [\"verify\"]);\n\tneeds(options.actorReader, \"actorReader\", [\"readEventActor\"]);\n\tif (typeof options.authorizeOperatorAction !== \"function\") fail(\"authorizeOperatorAction\");\n\tlet clock: FanOutClock;\n\ttry {\n\t\tclock = captureFanOutClock(options.clock);\n\t} catch {\n\t\treturn fail(\"clock\");\n\t}\n\tconst limits = resolveWebhookDeliveryLimits(options.limits ?? {});\n\tconst verifierToleranceMs = options.verifierToleranceMs ?? 300_000;\n\tassertPositiveInteger(verifierToleranceMs, \"verifierToleranceMs\");\n\treturn freeze({\n\t\tnamespace,\n\t\tsubscriptions: options.subscriptions,\n\t\tdeliveries: options.deliveries,\n\t\tresolver: options.resolver,\n\t\tsecretReferences: options.secretReferences,\n\t\tactorReader: options.actorReader,\n\t\tauthorize: options.authorizeOperatorAction,\n\t\tclock,\n\t\tlimits,\n\t\tverifierToleranceMs,\n\t});\n}\n\n/**\n * Build the package's governed operator actions as one `FabricModule`\n * (README, \"Governed actions\"). Register it with `createModuleRegistry()`\n * and run it through `createGovernedActionHost()` from\n * `@fabricorg/platform-host` 7.3.0 or later: every action declares\n * `admitSubmission`, which that Host runs before it records a submission,\n * and refuses to run without Host's admission record. Nothing needs wiring\n * into Host for it.\n *\n * @throws {WebhookGovernedActionError} `options_invalid` when a port or\n * option is missing or malformed.\n * @throws {WebhookDeliveryConfigError} when a limit or `verifierToleranceMs`\n * is not a positive whole number.\n */\nexport function createWebhookDeliveryModule<TDb = unknown>(options: WebhookDeliveryModuleOptions): FabricModule<TDb> {\n\tconst deps = readDeps(options);\n\tconst policy = operatorPolicy(deps);\n\tconst actions: ActionDefinition<TDb>[] = WEBHOOK_DELIVERY_ACTION_NAMES.map((name) => {\n\t\tconst idempotent = IDEMPOTENT.includes(name);\n\t\tconst definition: ActionDefinition<TDb> = {\n\t\t\tactionId: `${deps.namespace}.${name}`,\n\t\t\tnamespace: deps.namespace,\n\t\t\tversion: 1,\n\t\t\tkind: \"atomic\",\n\t\t\tschema: webhookActionSchema(name),\n\t\t\tadmitSubmission: admissionFor(deps, name),\n\t\t\tpolicies: [policy.policyId],\n\t\t\temitsEvents: [...EVENT_FOR[name]],\n\t\t\tidempotent,\n\t\t\tmutatesDomain: true,\n\t\t\texecution: {\n\t\t\t\tconnectivity: \"online-required\",\n\t\t\t\tauthorityMoment: \"execution\",\n\t\t\t\tidempotency: \"supported\",\n\t\t\t\tcompletion: \"immediate\",\n\t\t\t\tconsistency: \"authoritative-now\",\n\t\t\t\tsensitivity: \"confidential\",\n\t\t\t},\n\t\t\tsurface: \"internal\",\n\t\t\tsurfaceReason: \"Operator mutation of webhook subscriptions and delivery records.\",\n\t\t\thandler: handlerFor(deps, name) as ActionDefinition<TDb>[\"handler\"],\n\t\t};\n\t\treturn definition;\n\t});\n\treturn {\n\t\tnamespace: deps.namespace,\n\t\tversion: \"1.0.0\",\n\t\tdisplayName: \"Webhook delivery\",\n\t\tdescription: \"Governed operator actions for webhook subscriptions, secret rotation, requeue and actor enrichment (ADR 0018).\",\n\t\tsubjectTypes: [SUBSCRIPTION, INTENT, JOB],\n\t\teventTypes: WEBHOOK_DELIVERY_ACTION_EVENT_TYPES.map((eventType) => ({ eventType, schemaVersion: 1 })),\n\t\tactions,\n\t\tpolicies: [policy],\n\t};\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,iCAAiC,OAAO,OAAO;CAC3D;CACA;CACA;CACA;CACA;AACD,CAAU;;AAMV,MAAa,2BAA2B,OAAO,OAAO;CACrD;CACA;CACA;AACD,CAAU;;;;;;;;;;;;;;;;;;;;;AAyBV,MAAa,2BAA2B,OAAO,OAAO;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;;;;;AAaV,MAAa,2BAA2B,OAAO,OAAO;CACrD;CACA;CACA;CACA;CACA;AACD,CAAU;;AAWV,MAAa,+BAA+B,OAAO,OAAO;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;AAMV,MAAa,6BAA6B,OAAO,OAAO;CACvD;CACA;CACA;CACA;CACA;AACD,CAAU;;AAMV,MAAa,iCAAiC,OAAO,OAAO;CAC3D;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;;AAUV,MAAa,4BAA4B,OAAO,OAAO;CACtD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;;;;AAYV,MAAa,4BAA4B,OAAO,OAAO;CACtD;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;;;;;;;;;;;;;;;;;;AA0BV,MAAa,8BAA8B,OAAO,OAAO;CACxD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;;;;;;;AAeV,MAAa,+BAA+B,OAAO,OAAO;CACzD;CACA;CACA;CACA;AACD,CAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDV,MAAa,+BAA+B,OAAO,OAAO;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAU;;;;;AASV,MAAa,sCAAsC,OAAO,OAAO,CAAC,iBAAiB,CAAU;;;AC3S7F,MAAM,eAAe,QAAQ;AAC7B,MAAMA,mBAAiB,QAAQ;AAC/B,MAAMC,oCAAkC,QAAQ;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