@fabricorg/webhook-delivery 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +174 -11
- package/dist/index.cjs +8545 -7218
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +410 -153
- package/dist/index.d.ts +410 -153
- package/dist/index.js +8544 -7219
- package/dist/index.js.map +1 -1
- package/dist/node.cjs.map +1 -1
- package/dist/node.js.map +1 -1
- package/package.json +3 -3
package/dist/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","names":["reflectGetOwnPropertyDescriptor","reflectDefineProperty","objectCreate","stringSlice","unreadable","unreadableFail","INVALID_URL","PRIVATE_ADDRESS","unreadable","unreadableFail","request","httpsRequest"],"sources":["../src/snapshot.ts","../src/address.ts","../src/errors.ts","../src/limits.ts","../src/call-bounds.ts","../src/destination.ts","../src/node/transport.ts","../src/node/lookup.ts"],"sourcesContent":["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 { 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 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 { 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 { Buffer } from \"node:buffer\";\nimport type { ClientRequest, IncomingMessage, OutgoingHttpHeaders } from \"node:http\";\nimport { request as httpsRequest } from \"node:https\";\nimport type { LookupFunction } from \"node:net\";\n\nimport { classifyAddress } from \"../address\";\nimport { captureOptionalClock, clockNowMs, isAborted, onAbort, readCallBounds, startTimer, type CallBounds, type CapturedClock } from \"../call-bounds\";\nimport { checkDestinationUrl } from \"../destination\";\nimport { configError, guard, inputError } from \"../errors\";\nimport { assertPositiveInteger } from \"../limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookResolvedAddress,\n\tWebhookTransport,\n\tWebhookTransportRequest,\n\tWebhookTransportResult,\n} from \"../ports\";\nimport { emptyMap, freeze, frozenList, isArray, isPlainRecord, matches, numberIsSafeInteger, primitive, readOwn, record, type Fail } from \"../snapshot\";\n\n/** The default response body cap: past it the connection is closed (the crossing chunk is already read). */\nexport const DEFAULT_NODE_WEBHOOK_MAX_RESPONSE_BYTES = 65_536;\n/** The default number of requests one transport runs at once; later calls wait in its queue. */\nexport const DEFAULT_NODE_WEBHOOK_MAX_CONCURRENT_REQUESTS = 16;\n\nconst MAX_CONCURRENT_REQUESTS_LIMIT = 1_024;\nconst MAX_HEADERS = 64;\nconst MAX_RETRY_AFTER_LENGTH = 128;\nconst MAX_RESPONSE_HEADER_BYTES = 16_384;\n\n/** Options for {@link createNodeWebhookTransport}. */\nexport interface NodeWebhookTransportOptions {\n\t/**\n\t * Response body bytes after which the connection is closed; default\n\t * {@link DEFAULT_NODE_WEBHOOK_MAX_RESPONSE_BYTES}. The check runs per\n\t * chunk, so the bytes read can exceed it by up to one chunk. The body is\n\t * discarded as it arrives and never kept or returned: only the status and\n\t * `Retry-After` are.\n\t */\n\treadonly maxResponseBytes?: number;\n\t/** Requests in flight at once; default {@link DEFAULT_NODE_WEBHOOK_MAX_CONCURRENT_REQUESTS}. */\n\treadonly maxConcurrentRequests?: number;\n\t/**\n\t * PEM trust anchors that replace Node's bundled roots, for a receiver\n\t * behind a private CA. Certificate and hostname verification stay on.\n\t */\n\treadonly ca?: string | readonly string[];\n\t/** The clock the call's deadline is compared with; the system clock by default. */\n\treadonly clock?: WebhookClock;\n}\n\n/**\n * @internal Test-only switches, accepted only by the package's own test\n * factory (`src/node/test-transport.ts`, not part of any package entry).\n * The public constructor never reads them.\n */\nexport interface UnsafeTestTransportSwitches {\n\t/** Connect to loopback, private and other non-public addresses. */\n\treadonly allowNonPublicAddresses: boolean;\n\t/** Connect to this TCP port instead of 443. */\n\treadonly port: number;\n}\n\n/** @internal */\nexport interface TransportSettings {\n\treadonly maxResponseBytes: number;\n\treadonly maxConcurrentRequests: number;\n\treadonly ca: readonly string[] | undefined;\n\treadonly clock: CapturedClock;\n\treadonly allowNonPublic: boolean;\n\treadonly port: number;\n}\n\n/** One request after its input was read and checked. */\ninterface PreparedRequest {\n\treadonly hostname: string;\n\treadonly path: string;\n\treadonly headers: OutgoingHttpHeaders;\n\treadonly body: Buffer;\n\treadonly addresses: readonly WebhookResolvedAddress[];\n\treadonly literal: boolean;\n}\n\n/** A call waiting for a free slot. */\ninterface QueuedCall {\n\tstart: () => void;\n\tnext: QueuedCall | undefined;\n\tprev: QueuedCall | undefined;\n}\n\n/** Per-instance concurrency state. Lives in the transport's closure, never in module scope. */\ninterface Slots {\n\tactive: number;\n\t/** `true` while {@link pump} is draining, so a re-entrant call returns at once. */\n\tpumping: boolean;\n\thead: QueuedCall | undefined;\n\ttail: QueuedCall | undefined;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\nconst PromiseConstructor = Promise;\nconst bufferFrom = Buffer.from;\nconst NumberConstructor = Number;\n\n/** RFC 9110 token characters. */\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n/** Visible ASCII, space and tab: no CR, LF, NUL or other control characters. */\nconst HEADER_VALUE = /^[\\t\\x20-\\x7e]*$/;\n/** Header names the transport sets itself; a caller's copy is dropped. */\nconst RESERVED_HEADER = /^(?:host|content-length|connection|transfer-encoding|keep-alive|upgrade|te|expect|proxy-.*)$/i;\nconst DECIMAL = /^\\d+$/;\n\nconst NOT_SENT_DEADLINE: WebhookTransportResult = freeze({ kind: \"not_sent\", reason: \"deadline_expired\" });\nconst NOT_SENT_ABORTED: WebhookTransportResult = freeze({ kind: \"not_sent\", reason: \"aborted\" });\nconst TIMEOUT: WebhookTransportResult = freeze({ kind: \"timeout\" });\nconst NETWORK_ERROR: WebhookTransportResult = freeze({ kind: \"network_error\" });\nconst INVALID_URL: WebhookTransportResult = freeze({ kind: \"invalid_url\" });\nconst PRIVATE_ADDRESS: WebhookTransportResult = freeze({ kind: \"private_address\" });\n\n/**\n * The Node `WebhookTransport` (ADR 0018 decision 6, R3, R8).\n *\n * - **Pinned addresses.** It connects only to `destination.addresses`,\n * through a lookup function that answers with those addresses and nothing\n * else; it never resolves the hostname. The hostname is kept for SNI (left\n * out for an IP literal, as RFC 6066 requires), certificate verification and\n * the `Host` header. Certificate and hostname verification are always on.\n * - **Re-checked destination.** It refuses as `private_address` a destination with no addresses\n * or any address that is not public, and as `invalid_url` one whose URL\n * breaks decision 6's rules or whose hostname does not match it. Nothing is\n * sent.\n * - **No redirects.** A 3xx is returned as a response for the classifier;\n * `Location` is never followed.\n * - **Bounded response.** Body bytes are counted and discarded as they\n * arrive. As soon as the count passes `maxResponseBytes`, or a declared\n * `Content-Length` exceeds it, the connection is closed. The chunk that\n * crosses the cap has already been read, so the bytes read can exceed the\n * cap by up to one chunk as the socket delivered it. Only the status and a\n * `Retry-After` of at most 128 characters are returned; once the status\n * has arrived, the result is that response whatever happens to the body.\n * - **Deadline and cancellation.** A call whose signal has already aborted,\n * or whose deadline has passed, returns `not_sent` without connecting. A\n * call waiting in the queue that is aborted, or whose deadline passes, is\n * removed and returns `not_sent` without ever starting; the same check runs\n * again immediately before the connection is opened. Once started, the\n * request is destroyed at the deadline or on abort and returns `timeout`\n * (or the response, if its status had arrived).\n *\n * Each request uses its own connection (`agent: false`, `Connection:\n * close`), so no pooled socket opened for an earlier resolution is reused.\n * Transport failures (refused connection, TLS or certificate failure, reset)\n * are `network_error`; nothing is logged.\n *\n * @throws {TypeError} `input_unreadable` at construction for unreadable\n * options or `ca`, and from `send` (as a rejected promise) when the request\n * or `{ deadline, signal }` cannot be read: no destination record, a\n * non-string body, a header name or value that is not header-safe, more than\n * 64 headers, or a deadline and signal that are not a real `Date` and\n * `AbortSignal`.\n * @throws {WebhookDeliveryConfigError} when `maxResponseBytes` or\n * `maxConcurrentRequests` (at most 1024) is not a positive whole number.\n */\nexport function createNodeWebhookTransport(options: NodeWebhookTransportOptions = {}): WebhookTransport {\n\treturn buildTransport(guard(() => readTransportOptions(options, PRODUCTION_SWITCHES), unreadable));\n}\n\n/** What the public constructor always uses: the public-address re-check on, port 443. */\nconst PRODUCTION_SWITCHES: UnsafeTestTransportSwitches = freeze({ allowNonPublicAddresses: false, port: 443 });\n\n/** @internal Build a transport from validated settings. Not exported from any package entry. */\nexport function buildTransport(settings: TransportSettings): WebhookTransport {\n\tconst slots: Slots = { active: 0, pumping: false, head: undefined, tail: undefined };\n\tconst transport = {\n\t\tsend(request: WebhookTransportRequest, callOptions: WebhookCallOptions): Promise<WebhookTransportResult> {\n\t\t\tlet bounds: CallBounds;\n\t\t\tlet prepared: PreparedRequest | WebhookTransportResult;\n\t\t\ttry {\n\t\t\t\tbounds = readCallBounds(callOptions);\n\t\t\t\tprepared = prepareRequest(request, settings);\n\t\t\t} catch {\n\t\t\t\treturn PromiseConstructor.reject(unreadable());\n\t\t\t}\n\t\t\tif (\"kind\" in prepared) return PromiseConstructor.resolve(prepared);\n\t\t\tconst refused = notWanted(bounds, settings.clock);\n\t\t\tif (refused !== undefined) return PromiseConstructor.resolve(refused);\n\t\t\treturn dispatch(slots, settings, prepared, bounds);\n\t\t},\n\t};\n\treturn freeze(transport);\n}\n\n/**\n * @internal Read the public options by name, one descriptor read each; no\n * other key of `options` is read, so a test switch placed on it has no\n * effect. The switches come from the caller as a separate argument.\n */\nexport function readTransportOptions(options: unknown, switches: UnsafeTestTransportSwitches): TransportSettings {\n\tif (!isPlainRecord(options)) throw unreadable();\n\tconst rawMax = primitive(readOwn(options, \"maxResponseBytes\", \"maxResponseBytes\", unreadableFail));\n\tconst maxResponseBytes = rawMax === undefined ? DEFAULT_NODE_WEBHOOK_MAX_RESPONSE_BYTES : rawMax;\n\tassertPositiveInteger(maxResponseBytes, \"maxResponseBytes\");\n\tconst rawConcurrency = primitive(readOwn(options, \"maxConcurrentRequests\", \"maxConcurrentRequests\", unreadableFail));\n\tconst maxConcurrentRequests = rawConcurrency === undefined ? DEFAULT_NODE_WEBHOOK_MAX_CONCURRENT_REQUESTS : rawConcurrency;\n\tassertPositiveInteger(maxConcurrentRequests, \"maxConcurrentRequests\");\n\tif (maxConcurrentRequests > MAX_CONCURRENT_REQUESTS_LIMIT) throw configError(\"limit_out_of_range\", \"maxConcurrentRequests\");\n\tconst ca = readCa(readOwn(options, \"ca\", \"ca\", unreadableFail));\n\tconst clock = captureOptionalClock(readOwn(options, \"clock\", \"clock\", unreadableFail));\n\treturn freeze({\n\t\tmaxResponseBytes,\n\t\tmaxConcurrentRequests,\n\t\tca,\n\t\tclock,\n\t\tallowNonPublic: switches.allowNonPublicAddresses === true,\n\t\tport: switches.port,\n\t});\n}\n\nfunction readCa(value: unknown): readonly string[] | undefined {\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"string\") return value === \"\" ? unreadableFail(\"not_plain\", \"ca\") : frozenList([value]);\n\tif (!isArray(value)) throw unreadable();\n\tconst length = readOwn(value, \"length\", \"ca\", unreadableFail);\n\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > 1_024) throw unreadable();\n\tconst copy: string[] = [];\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst item = readOwn(value, `${index}`, \"ca\", unreadableFail);\n\t\tif (typeof item !== \"string\" || item === \"\") throw unreadable();\n\t\tcopy[copy.length] = item;\n\t}\n\treturn frozenList(copy);\n}\n\n/** Read the request into a snapshot and re-check its destination. A refusal is returned as a result. */\nfunction prepareRequest(request: unknown, settings: TransportSettings): PreparedRequest | WebhookTransportResult {\n\tif (!isPlainRecord(request)) throw unreadable();\n\tconst destination = readOwn(request, \"destination\", \"destination\", unreadableFail);\n\tconst method = primitive(readOwn(request, \"method\", \"method\", unreadableFail));\n\tconst body = primitive(readOwn(request, \"body\", \"body\", unreadableFail));\n\tconst headers = readOwn(request, \"headers\", \"headers\", unreadableFail);\n\tif (!isPlainRecord(destination) || method !== \"POST\" || typeof body !== \"string\") throw unreadable();\n\tconst outgoing = readHeaders(headers);\n\n\tconst url = primitive(readOwn(destination, \"url\", \"destination.url\", unreadableFail));\n\tconst hostname = primitive(readOwn(destination, \"hostname\", \"destination.hostname\", unreadableFail));\n\tconst port = primitive(readOwn(destination, \"port\", \"destination.port\", unreadableFail));\n\tconst rawAddresses = readOwn(destination, \"addresses\", \"destination.addresses\", unreadableFail);\n\n\tconst check = checkDestinationUrl(url, settings.allowNonPublic);\n\tif (!check.ok) return check.code === \"private_address\" ? PRIVATE_ADDRESS : INVALID_URL;\n\tif (port !== 443 || hostname !== check.hostname) return INVALID_URL;\n\n\tconst addresses = readAddresses(rawAddresses, settings.allowNonPublic);\n\tif (addresses === undefined) return PRIVATE_ADDRESS;\n\tif (check.literal !== undefined) {\n\t\t// An IP-literal host has exactly one address: itself.\n\t\tfor (let index = 0; index < addresses.length; index += 1) {\n\t\t\tif (addresses[index]!.address !== check.literal.address) return INVALID_URL;\n\t\t}\n\t}\n\tconst hostHeader = check.literal !== undefined && check.literal.family === 6 ? `[${check.hostname}]` : check.hostname;\n\tconst path = check.url.slice(`https://${hostHeader}`.length);\n\tconst encoded = bufferFrom(body, \"utf8\");\n\toutgoing[\"Host\"] = hostHeader;\n\toutgoing[\"Content-Length\"] = `${encoded.length}`;\n\toutgoing[\"Connection\"] = \"close\";\n\treturn freeze({ hostname: check.hostname, path, headers: outgoing, body: encoded, addresses, literal: check.literal !== undefined });\n}\n\nfunction readHeaders(value: unknown): OutgoingHttpHeaders {\n\tif (!isPlainRecord(value)) throw unreadable();\n\tconst out = emptyMap<string>();\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.length > MAX_HEADERS) throw unreadable();\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst name = keys[index];\n\t\tif (typeof name !== \"string\") throw unreadable();\n\t\tconst headerValue = primitive(readOwn(value, name, \"headers\", unreadableFail));\n\t\tif (typeof headerValue !== \"string\" || !matches(HEADER_NAME, name) || !matches(HEADER_VALUE, headerValue)) throw unreadable();\n\t\tif (matches(RESERVED_HEADER, name)) continue;\n\t\tout[name] = headerValue;\n\t}\n\treturn out as OutgoingHttpHeaders;\n}\n\n/** The vetted addresses, canonical; `undefined` when there are none or one is not public (unless allowed). */\nfunction readAddresses(value: unknown, allowNonPublic: boolean): readonly WebhookResolvedAddress[] | undefined {\n\tif (!isArray(value)) return undefined;\n\tconst length = readOwn(value, \"length\", \"destination.addresses\", unreadableFail);\n\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > 32) return undefined;\n\tconst out: WebhookResolvedAddress[] = [];\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst entry = readOwn(value, `${index}`, \"destination.addresses\", unreadableFail);\n\t\tif (!isPlainRecord(entry)) return undefined;\n\t\tconst address = primitive(readOwn(entry, \"address\", \"destination.addresses\", unreadableFail));\n\t\tconst family = primitive(readOwn(entry, \"family\", \"destination.addresses\", unreadableFail));\n\t\tconst judged = classifyAddress(address);\n\t\tif (judged.kind === \"public\" && judged.family === family) {\n\t\t\tout[out.length] = record({ address: judged.address, family: judged.family });\n\t\t\tcontinue;\n\t\t}\n\t\t// Zone-scoped addresses are refused even here: a zone is not an address the pinned lookup can return.\n\t\tif (allowNonPublic && judged.kind === \"non_public\" && judged.family === family && typeof address === \"string\" && !address.includes(\"%\")) {\n\t\t\tout[out.length] = record({ address, family: judged.family });\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\treturn frozenList(out);\n}\n\n/** `not_sent` when the call is no longer wanted: aborted, past its deadline, or the clock cannot tell. */\nfunction notWanted(bounds: CallBounds, clock: CapturedClock): WebhookTransportResult | undefined {\n\tif (isAborted(bounds.signal)) return NOT_SENT_ABORTED;\n\tif (!(bounds.deadlineMs > clockNowMs(clock))) return NOT_SENT_DEADLINE;\n\treturn undefined;\n}\n\nfunction dispatch(slots: Slots, settings: TransportSettings, prepared: PreparedRequest, bounds: CallBounds): Promise<WebhookTransportResult> {\n\treturn new PromiseConstructor<WebhookTransportResult>((resolve) => {\n\t\tconst release = (): void => {\n\t\t\tslots.active -= 1;\n\t\t\tpump(slots, settings);\n\t\t};\n\t\tconst begin = (): void => {\n\t\t\tperform(settings, prepared, bounds, (result) => {\n\t\t\t\trelease();\n\t\t\t\tresolve(result);\n\t\t\t});\n\t\t};\n\t\tif (slots.active < settings.maxConcurrentRequests) {\n\t\t\tslots.active += 1;\n\t\t\tbegin();\n\t\t\treturn;\n\t\t}\n\t\tenqueue(slots, settings, bounds, begin, resolve);\n\t});\n}\n\nfunction enqueue(\n\tslots: Slots,\n\tsettings: TransportSettings,\n\tbounds: CallBounds,\n\tbegin: () => void,\n\tresolve: (result: WebhookTransportResult) => void,\n): void {\n\tlet cancelTimer: () => void = () => {};\n\tlet removeAbort: () => void = () => {};\n\tconst call: QueuedCall = {\n\t\tstart: () => {\n\t\t\tcancelTimer();\n\t\t\tremoveAbort();\n\t\t\tbegin();\n\t\t},\n\t\tnext: undefined,\n\t\tprev: undefined,\n\t};\n\tconst drop = (result: WebhookTransportResult): void => {\n\t\tunlink(slots, call);\n\t\tcancelTimer();\n\t\tremoveAbort();\n\t\tresolve(result);\n\t};\n\tif (slots.tail === undefined) {\n\t\tslots.head = call;\n\t\tslots.tail = call;\n\t} else {\n\t\tcall.prev = slots.tail;\n\t\tslots.tail.next = call;\n\t\tslots.tail = call;\n\t}\n\tcancelTimer = startTimer(bounds.deadlineMs - clockNowMs(settings.clock), () => drop(NOT_SENT_DEADLINE));\n\tremoveAbort = onAbort(bounds.signal, () => drop(NOT_SENT_ABORTED));\n}\n\nfunction unlink(slots: Slots, call: QueuedCall): void {\n\tif (call.prev !== undefined) call.prev.next = call.next;\n\telse if (slots.head === call) slots.head = call.next;\n\tif (call.next !== undefined) call.next.prev = call.prev;\n\telse if (slots.tail === call) slots.tail = call.prev;\n\tcall.next = undefined;\n\tcall.prev = undefined;\n}\n\n/**\n * Start queued calls, oldest first, while slots are free. A started call\n * that fails its last check settles synchronously and releases its slot,\n * which calls `pump` again; the `pumping` flag turns that re-entry into\n * another turn of this loop, so draining any backlog uses constant stack\n * depth.\n */\nfunction pump(slots: Slots, settings: TransportSettings): void {\n\tif (slots.pumping) return;\n\tslots.pumping = true;\n\ttry {\n\t\twhile (slots.head !== undefined && slots.active < settings.maxConcurrentRequests) {\n\t\t\tconst call = slots.head;\n\t\t\tunlink(slots, call);\n\t\t\tslots.active += 1;\n\t\t\tcall.start();\n\t\t}\n\t} finally {\n\t\tslots.pumping = false;\n\t}\n}\n\n/**\n * The lookup Node's socket uses: it answers with the vetted addresses for\n * the vetted name and refuses any other name. Node connects synchronously\n * from inside this callback, so a throw there (an address it cannot use)\n * would escape as an uncaught exception; it is caught and reported through\n * `onFault` instead.\n */\nfunction pinnedLookup(hostname: string, addresses: readonly WebhookResolvedAddress[], onFault: () => void): LookupFunction {\n\treturn (host, options, callback) => {\n\t\ttry {\n\t\t\tif (host !== hostname) {\n\t\t\t\tconst error = new Error(\"Webhook transport refused a lookup for a name other than the vetted one.\") as NodeJS.ErrnoException;\n\t\t\t\terror.code = \"ENOTFOUND\";\n\t\t\t\tcallback(error, \"\", 4);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (options.all === true) {\n\t\t\t\tconst all: { address: string; family: number }[] = [];\n\t\t\t\tfor (let index = 0; index < addresses.length; index += 1) all[all.length] = { address: addresses[index]!.address, family: addresses[index]!.family };\n\t\t\t\t(callback as unknown as (error: null, addresses: { address: string; family: number }[]) => void)(null, all);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcallback(null, addresses[0]!.address, addresses[0]!.family);\n\t\t} catch {\n\t\t\tonFault();\n\t\t}\n\t};\n}\n\nfunction perform(settings: TransportSettings, prepared: PreparedRequest, bounds: CallBounds, done: (result: WebhookTransportResult) => void): void {\n\tlet settled = false;\n\tlet status: number | undefined;\n\tlet retryAfter: string | null = null;\n\tlet request: ClientRequest | undefined;\n\tlet response: IncomingMessage | undefined;\n\tlet cancelTimer: () => void = () => {};\n\tlet removeAbort: () => void = () => {};\n\n\tconst responseResult = (): WebhookTransportResult => record({ kind: \"response\" as const, status: status!, retryAfter });\n\tconst finish = (result: WebhookTransportResult): void => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tcancelTimer();\n\t\tremoveAbort();\n\t\t// Stop all further work and reading; nothing of the body is kept.\n\t\tresponse?.destroy();\n\t\trequest?.destroy();\n\t\tdone(result);\n\t};\n\tconst stop = (): void => finish(status === undefined ? TIMEOUT : responseResult());\n\n\t// The last check, immediately before the connection is opened: a call\n\t// that waited in the queue may have been aborted or run out of time.\n\tif (isAborted(bounds.signal)) {\n\t\tfinish(NOT_SENT_ABORTED);\n\t\treturn;\n\t}\n\tconst remaining = bounds.deadlineMs - clockNowMs(settings.clock);\n\tif (!(remaining > 0)) {\n\t\tfinish(NOT_SENT_DEADLINE);\n\t\treturn;\n\t}\n\tcancelTimer = startTimer(remaining, stop);\n\tremoveAbort = onAbort(bounds.signal, stop);\n\n\ttry {\n\t\trequest = httpsRequest({\n\t\t\thost: prepared.hostname,\n\t\t\tport: settings.port,\n\t\t\tmethod: \"POST\",\n\t\t\tpath: prepared.path,\n\t\t\theaders: prepared.headers,\n\t\t\tsetHost: false,\n\t\t\tagent: false,\n\t\t\tlookup: pinnedLookup(prepared.hostname, prepared.addresses, () => finish(status === undefined ? NETWORK_ERROR : responseResult())),\n\t\t\t// RFC 6066 forbids an IP address as SNI; the certificate is then checked against the IP.\n\t\t\tservername: prepared.literal ? \"\" : prepared.hostname,\n\t\t\trejectUnauthorized: true,\n\t\t\tminVersion: \"TLSv1.2\",\n\t\t\tmaxHeaderSize: MAX_RESPONSE_HEADER_BYTES,\n\t\t\t...(settings.ca === undefined ? {} : { ca: settings.ca as string[] }),\n\t\t});\n\t} catch {\n\t\tfinish(NETWORK_ERROR);\n\t\treturn;\n\t}\n\trequest.on(\"error\", () => finish(status === undefined ? NETWORK_ERROR : responseResult()));\n\trequest.on(\"response\", (incoming: IncomingMessage) => {\n\t\tresponse = incoming;\n\t\tincoming.on(\"error\", () => finish(responseResult()));\n\t\tconst code = incoming.statusCode;\n\t\tif (typeof code !== \"number\" || !numberIsSafeInteger(code) || code < 100 || code > 599) {\n\t\t\tfinish(NETWORK_ERROR);\n\t\t\treturn;\n\t\t}\n\t\tstatus = code;\n\t\tconst header = incoming.headers[\"retry-after\"];\n\t\tretryAfter = typeof header === \"string\" && header.length <= MAX_RETRY_AFTER_LENGTH ? header : null;\n\t\tconst declared = incoming.headers[\"content-length\"];\n\t\tif (typeof declared === \"string\" && matches(DECIMAL, declared) && NumberConstructor(declared) > settings.maxResponseBytes) {\n\t\t\tfinish(responseResult());\n\t\t\treturn;\n\t\t}\n\t\tlet received = 0;\n\t\tincoming.on(\"data\", (chunk: Buffer) => {\n\t\t\treceived += chunk.length;\n\t\t\tif (received > settings.maxResponseBytes) finish(responseResult());\n\t\t});\n\t\tincoming.on(\"end\", () => finish(responseResult()));\n\t\tincoming.on(\"close\", () => finish(responseResult()));\n\t});\n\tif (settled) return;\n\trequest.end(prepared.body);\n}\n","import { Resolver } from \"node:dns/promises\";\n\nimport { isAborted, onAbort } from \"../call-bounds\";\nimport type { WebhookDnsLookup } from \"../destination\";\nimport { configError, guard, inputError } from \"../errors\";\nimport { WEBHOOK_MAX_TIMER_MS, assertPositiveInteger } from \"../limits\";\nimport type { WebhookCallOptions, WebhookResolvedAddress } from \"../ports\";\nimport { frozenList, isArray, isPlainRecord, numberIsSafeInteger, primitive, readOwn, record, type Fail } from \"../snapshot\";\n\n/** The default per-query timeout of {@link createNodeWebhookDnsLookup}. */\nexport const DEFAULT_NODE_WEBHOOK_DNS_TIMEOUT_MS = 5_000;\n\n/** Options for {@link createNodeWebhookDnsLookup}. */\nexport interface NodeWebhookDnsLookupOptions {\n\t/** DNS servers (`\"ip\"` or `\"ip:port\"`), as `Resolver.setServers` takes them; the system's by default. */\n\treadonly servers?: readonly string[];\n\t/** Timeout of each A and AAAA query; default {@link DEFAULT_NODE_WEBHOOK_DNS_TIMEOUT_MS}. */\n\treadonly timeoutMs?: number;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/**\n * \"The name exists but has no records of this type\": an empty half of the\n * answer, not a failure. \"No such name\" (`ENOTFOUND`) is a failure: the two\n * queries disagreeing about whether the name exists is a partial answer.\n */\nfunction isNoRecords(error: unknown): boolean {\n\treturn (error as { code?: unknown } | null)?.code === \"ENODATA\";\n}\n\n/**\n * A {@link WebhookDnsLookup} for `createWebhookDestinationResolver()` built on\n * a fresh `node:dns` `Resolver` per call, asking for A and AAAA records\n * together. It uses c-ares rather than `dns.lookup()` because a c-ares query\n * can be cancelled: when the resolver aborts the call's signal, the queries\n * are cancelled instead of holding a libuv thread-pool thread until the\n * operating system gives up, so a slow authoritative server named in a\n * destination cannot starve the pool. It therefore does not consult\n * `/etc/hosts`.\n *\n * The answer is every A and AAAA address. A query that fails for any reason\n * other than \"no records of this type\" (`ENODATA`), \"no such name\"\n * (`ENOTFOUND`) included, rejects the whole lookup, so a half-answered name\n * is a `dns_failure` behind the resolver, never a partial pass.\n *\n * @throws {TypeError} `input_unreadable` when `servers` is not a list of\n * server strings `Resolver.setServers` accepts.\n * @throws {WebhookDeliveryConfigError} when `timeoutMs` is not a positive\n * whole number of at most `WEBHOOK_MAX_TIMER_MS`.\n */\nexport function createNodeWebhookDnsLookup(options: NodeWebhookDnsLookupOptions = {}): WebhookDnsLookup {\n\tconst settings = guard(() => readLookupOptions(options), unreadable);\n\tconst lookup = async (hostname: string, callOptions: WebhookCallOptions): Promise<readonly WebhookResolvedAddress[]> => {\n\t\tconst signal = callOptions.signal;\n\t\tif (isAborted(signal)) throw unreadable();\n\t\tconst resolver = new Resolver({ timeout: settings.timeoutMs, tries: 1 });\n\t\tif (settings.servers !== undefined) resolver.setServers(settings.servers as string[]);\n\t\tconst removeAbort = onAbort(signal, () => resolver.cancel());\n\t\ttry {\n\t\t\tconst [v4, v6] = await Promise.all([records(resolver.resolve4(hostname)), records(resolver.resolve6(hostname))]);\n\t\t\tconst answer: WebhookResolvedAddress[] = [];\n\t\t\tfor (const address of v4) answer[answer.length] = record({ address, family: 4 as const });\n\t\t\tfor (const address of v6) answer[answer.length] = record({ address, family: 6 as const });\n\t\t\treturn frozenList(answer);\n\t\t} finally {\n\t\t\tremoveAbort();\n\t\t\tresolver.cancel();\n\t\t}\n\t};\n\treturn lookup;\n}\n\nasync function records(query: Promise<string[]>): Promise<readonly string[]> {\n\ttry {\n\t\treturn await query;\n\t} catch (error) {\n\t\tif (isNoRecords(error)) return [];\n\t\tthrow error;\n\t}\n}\n\ninterface LookupSettings {\n\treadonly servers: readonly string[] | undefined;\n\treadonly timeoutMs: number;\n}\n\nfunction readLookupOptions(options: unknown): LookupSettings {\n\tif (!isPlainRecord(options)) throw unreadable();\n\tconst rawTimeout = primitive(readOwn(options, \"timeoutMs\", \"timeoutMs\", unreadableFail));\n\tconst timeoutMs = rawTimeout === undefined ? DEFAULT_NODE_WEBHOOK_DNS_TIMEOUT_MS : rawTimeout;\n\tassertPositiveInteger(timeoutMs, \"timeoutMs\");\n\tif (timeoutMs > WEBHOOK_MAX_TIMER_MS) throw configError(\"limit_out_of_range\", \"timeoutMs\");\n\tconst rawServers = readOwn(options, \"servers\", \"servers\", unreadableFail);\n\tlet servers: readonly string[] | undefined;\n\tif (rawServers !== undefined) {\n\t\tif (!isArray(rawServers)) throw unreadable();\n\t\tconst length = readOwn(rawServers, \"length\", \"servers\", unreadableFail);\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > 16) throw unreadable();\n\t\tconst copy: string[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst item = primitive(readOwn(rawServers, `${index}`, \"servers\", unreadableFail));\n\t\t\tif (typeof item !== \"string\") throw unreadable();\n\t\t\tcopy[copy.length] = item;\n\t\t}\n\t\t// Validate once at construction, so a bad server list fails here and not per call.\n\t\tnew Resolver().setServers(copy);\n\t\tservers = frozenList(copy);\n\t}\n\treturn { servers, timeoutMs };\n}\n"],"mappings":";;;;AAkCA,MAAM,eAAe,QAAQ;AAC7B,MAAM,iBAAiB,QAAQ;AAC/B,MAAMA,oCAAkC,QAAQ;AAChD,MAAM,wBAAwB,QAAQ;AACtC,MAAMC,0BAAwB,QAAQ;AACtC,MAAMC,iBAAe,OAAO;AAC5B,MAAM,eAAe,OAAO;AAC5B,MAAM,eAAe,OAAO;AAC5B,MAAM,kBAAkB,OAAO;AAC/B,MAAM,eAAe,MAAM;AAC3B,MAAM,cAAc,KAAK,UAAU;AACX,KAAK,UAAU;AAEvC,MAAM,aAAa,OAAO,UAAU;AACjB,OAAO,UAAU;;AAIpC,MAAa,QAAQ;;AAErB,MAAa,iBAAiB,OAAO;AACrC,MAAa,sBAAsB,OAAO;AAKjB,KAAK;AAC9B,MAAa,SAAS;AACtB,MAAa,SAAS;AACtB,MAAa,UAAU;;AAgBvB,MAAa,gBAA+B,OAAO,gCAAgC;;AAGnF,SAAS,eAAe,OAAoC;CAC3D,MAAM,aAAaA,eAAa,IAAI;CACpC,WAAW,QAAQ;CACnB,WAAW,aAAa;CACxB,WAAW,WAAW;CACtB,WAAW,eAAe;CAC1B,OAAO;AACR;;AA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,GAAG;GAC/C,MAAM,OAAO,UAAU,QAAQ,YAAY,GAAG,SAAS,WAAW,cAAc,CAAC;GACjF,IAAI,OAAO,SAAS,UAAU,MAAM,WAAW;GAC/C,KAAK,KAAK,UAAU;EACrB;EAEA,IAAI,SAAS,CAAC,CAAC,WAAW,IAAI;EAC9B,UAAU,WAAW,IAAI;CAC1B;CACA,OAAO;EAAE;EAAS;CAAU;AAC7B"}
|
|
1
|
+
{"version":3,"file":"node.js","names":["reflectGetOwnPropertyDescriptor","reflectDefineProperty","objectCreate","stringSlice","unreadable","unreadableFail","INVALID_URL","PRIVATE_ADDRESS","unreadable","unreadableFail","request","httpsRequest"],"sources":["../src/snapshot.ts","../src/address.ts","../src/errors.ts","../src/limits.ts","../src/call-bounds.ts","../src/destination.ts","../src/node/transport.ts","../src/node/lookup.ts"],"sourcesContent":["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 { 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 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\n/** Maximum event identifiers in one atomic redaction call. */\nexport const WEBHOOK_MAX_REDACTION_EVENTS = 100;\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 { 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 { Buffer } from \"node:buffer\";\nimport type { ClientRequest, IncomingMessage, OutgoingHttpHeaders } from \"node:http\";\nimport { request as httpsRequest } from \"node:https\";\nimport type { LookupFunction } from \"node:net\";\n\nimport { classifyAddress } from \"../address\";\nimport { captureOptionalClock, clockNowMs, isAborted, onAbort, readCallBounds, startTimer, type CallBounds, type CapturedClock } from \"../call-bounds\";\nimport { checkDestinationUrl } from \"../destination\";\nimport { configError, guard, inputError } from \"../errors\";\nimport { assertPositiveInteger } from \"../limits\";\nimport type {\n\tWebhookCallOptions,\n\tWebhookClock,\n\tWebhookResolvedAddress,\n\tWebhookTransport,\n\tWebhookTransportRequest,\n\tWebhookTransportResult,\n} from \"../ports\";\nimport { emptyMap, freeze, frozenList, isArray, isPlainRecord, matches, numberIsSafeInteger, primitive, readOwn, record, type Fail } from \"../snapshot\";\n\n/** The default response body cap: past it the connection is closed (the crossing chunk is already read). */\nexport const DEFAULT_NODE_WEBHOOK_MAX_RESPONSE_BYTES = 65_536;\n/** The default number of requests one transport runs at once; later calls wait in its queue. */\nexport const DEFAULT_NODE_WEBHOOK_MAX_CONCURRENT_REQUESTS = 16;\n\nconst MAX_CONCURRENT_REQUESTS_LIMIT = 1_024;\nconst MAX_HEADERS = 64;\nconst MAX_RETRY_AFTER_LENGTH = 128;\nconst MAX_RESPONSE_HEADER_BYTES = 16_384;\n\n/** Options for {@link createNodeWebhookTransport}. */\nexport interface NodeWebhookTransportOptions {\n\t/**\n\t * Response body bytes after which the connection is closed; default\n\t * {@link DEFAULT_NODE_WEBHOOK_MAX_RESPONSE_BYTES}. The check runs per\n\t * chunk, so the bytes read can exceed it by up to one chunk. The body is\n\t * discarded as it arrives and never kept or returned: only the status and\n\t * `Retry-After` are.\n\t */\n\treadonly maxResponseBytes?: number;\n\t/** Requests in flight at once; default {@link DEFAULT_NODE_WEBHOOK_MAX_CONCURRENT_REQUESTS}. */\n\treadonly maxConcurrentRequests?: number;\n\t/**\n\t * PEM trust anchors that replace Node's bundled roots, for a receiver\n\t * behind a private CA. Certificate and hostname verification stay on.\n\t */\n\treadonly ca?: string | readonly string[];\n\t/** The clock the call's deadline is compared with; the system clock by default. */\n\treadonly clock?: WebhookClock;\n}\n\n/**\n * @internal Test-only switches, accepted only by the package's own test\n * factory (`src/node/test-transport.ts`, not part of any package entry).\n * The public constructor never reads them.\n */\nexport interface UnsafeTestTransportSwitches {\n\t/** Connect to loopback, private and other non-public addresses. */\n\treadonly allowNonPublicAddresses: boolean;\n\t/** Connect to this TCP port instead of 443. */\n\treadonly port: number;\n}\n\n/** @internal */\nexport interface TransportSettings {\n\treadonly maxResponseBytes: number;\n\treadonly maxConcurrentRequests: number;\n\treadonly ca: readonly string[] | undefined;\n\treadonly clock: CapturedClock;\n\treadonly allowNonPublic: boolean;\n\treadonly port: number;\n}\n\n/** One request after its input was read and checked. */\ninterface PreparedRequest {\n\treadonly hostname: string;\n\treadonly path: string;\n\treadonly headers: OutgoingHttpHeaders;\n\treadonly body: Buffer;\n\treadonly addresses: readonly WebhookResolvedAddress[];\n\treadonly literal: boolean;\n}\n\n/** A call waiting for a free slot. */\ninterface QueuedCall {\n\tstart: () => void;\n\tnext: QueuedCall | undefined;\n\tprev: QueuedCall | undefined;\n}\n\n/** Per-instance concurrency state. Lives in the transport's closure, never in module scope. */\ninterface Slots {\n\tactive: number;\n\t/** `true` while {@link pump} is draining, so a re-entrant call returns at once. */\n\tpumping: boolean;\n\thead: QueuedCall | undefined;\n\ttail: QueuedCall | undefined;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\nconst PromiseConstructor = Promise;\nconst bufferFrom = Buffer.from;\nconst NumberConstructor = Number;\n\n/** RFC 9110 token characters. */\nconst HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n/** Visible ASCII, space and tab: no CR, LF, NUL or other control characters. */\nconst HEADER_VALUE = /^[\\t\\x20-\\x7e]*$/;\n/** Header names the transport sets itself; a caller's copy is dropped. */\nconst RESERVED_HEADER = /^(?:host|content-length|connection|transfer-encoding|keep-alive|upgrade|te|expect|proxy-.*)$/i;\nconst DECIMAL = /^\\d+$/;\n\nconst NOT_SENT_DEADLINE: WebhookTransportResult = freeze({ kind: \"not_sent\", reason: \"deadline_expired\" });\nconst NOT_SENT_ABORTED: WebhookTransportResult = freeze({ kind: \"not_sent\", reason: \"aborted\" });\nconst TIMEOUT: WebhookTransportResult = freeze({ kind: \"timeout\" });\nconst NETWORK_ERROR: WebhookTransportResult = freeze({ kind: \"network_error\" });\nconst INVALID_URL: WebhookTransportResult = freeze({ kind: \"invalid_url\" });\nconst PRIVATE_ADDRESS: WebhookTransportResult = freeze({ kind: \"private_address\" });\n\n/**\n * The Node `WebhookTransport` (ADR 0018 decision 6, R3, R8).\n *\n * - **Pinned addresses.** It connects only to `destination.addresses`,\n * through a lookup function that answers with those addresses and nothing\n * else; it never resolves the hostname. The hostname is kept for SNI (left\n * out for an IP literal, as RFC 6066 requires), certificate verification and\n * the `Host` header. Certificate and hostname verification are always on.\n * - **Re-checked destination.** It refuses as `private_address` a destination with no addresses\n * or any address that is not public, and as `invalid_url` one whose URL\n * breaks decision 6's rules or whose hostname does not match it. Nothing is\n * sent.\n * - **No redirects.** A 3xx is returned as a response for the classifier;\n * `Location` is never followed.\n * - **Bounded response.** Body bytes are counted and discarded as they\n * arrive. As soon as the count passes `maxResponseBytes`, or a declared\n * `Content-Length` exceeds it, the connection is closed. The chunk that\n * crosses the cap has already been read, so the bytes read can exceed the\n * cap by up to one chunk as the socket delivered it. Only the status and a\n * `Retry-After` of at most 128 characters are returned; once the status\n * has arrived, the result is that response whatever happens to the body.\n * - **Deadline and cancellation.** A call whose signal has already aborted,\n * or whose deadline has passed, returns `not_sent` without connecting. A\n * call waiting in the queue that is aborted, or whose deadline passes, is\n * removed and returns `not_sent` without ever starting; the same check runs\n * again immediately before the connection is opened. Once started, the\n * request is destroyed at the deadline or on abort and returns `timeout`\n * (or the response, if its status had arrived).\n *\n * Each request uses its own connection (`agent: false`, `Connection:\n * close`), so no pooled socket opened for an earlier resolution is reused.\n * Transport failures (refused connection, TLS or certificate failure, reset)\n * are `network_error`; nothing is logged.\n *\n * @throws {TypeError} `input_unreadable` at construction for unreadable\n * options or `ca`, and from `send` (as a rejected promise) when the request\n * or `{ deadline, signal }` cannot be read: no destination record, a\n * non-string body, a header name or value that is not header-safe, more than\n * 64 headers, or a deadline and signal that are not a real `Date` and\n * `AbortSignal`.\n * @throws {WebhookDeliveryConfigError} when `maxResponseBytes` or\n * `maxConcurrentRequests` (at most 1024) is not a positive whole number.\n */\nexport function createNodeWebhookTransport(options: NodeWebhookTransportOptions = {}): WebhookTransport {\n\treturn buildTransport(guard(() => readTransportOptions(options, PRODUCTION_SWITCHES), unreadable));\n}\n\n/** What the public constructor always uses: the public-address re-check on, port 443. */\nconst PRODUCTION_SWITCHES: UnsafeTestTransportSwitches = freeze({ allowNonPublicAddresses: false, port: 443 });\n\n/** @internal Build a transport from validated settings. Not exported from any package entry. */\nexport function buildTransport(settings: TransportSettings): WebhookTransport {\n\tconst slots: Slots = { active: 0, pumping: false, head: undefined, tail: undefined };\n\tconst transport = {\n\t\tsend(request: WebhookTransportRequest, callOptions: WebhookCallOptions): Promise<WebhookTransportResult> {\n\t\t\tlet bounds: CallBounds;\n\t\t\tlet prepared: PreparedRequest | WebhookTransportResult;\n\t\t\ttry {\n\t\t\t\tbounds = readCallBounds(callOptions);\n\t\t\t\tprepared = prepareRequest(request, settings);\n\t\t\t} catch {\n\t\t\t\treturn PromiseConstructor.reject(unreadable());\n\t\t\t}\n\t\t\tif (\"kind\" in prepared) return PromiseConstructor.resolve(prepared);\n\t\t\tconst refused = notWanted(bounds, settings.clock);\n\t\t\tif (refused !== undefined) return PromiseConstructor.resolve(refused);\n\t\t\treturn dispatch(slots, settings, prepared, bounds);\n\t\t},\n\t};\n\treturn freeze(transport);\n}\n\n/**\n * @internal Read the public options by name, one descriptor read each; no\n * other key of `options` is read, so a test switch placed on it has no\n * effect. The switches come from the caller as a separate argument.\n */\nexport function readTransportOptions(options: unknown, switches: UnsafeTestTransportSwitches): TransportSettings {\n\tif (!isPlainRecord(options)) throw unreadable();\n\tconst rawMax = primitive(readOwn(options, \"maxResponseBytes\", \"maxResponseBytes\", unreadableFail));\n\tconst maxResponseBytes = rawMax === undefined ? DEFAULT_NODE_WEBHOOK_MAX_RESPONSE_BYTES : rawMax;\n\tassertPositiveInteger(maxResponseBytes, \"maxResponseBytes\");\n\tconst rawConcurrency = primitive(readOwn(options, \"maxConcurrentRequests\", \"maxConcurrentRequests\", unreadableFail));\n\tconst maxConcurrentRequests = rawConcurrency === undefined ? DEFAULT_NODE_WEBHOOK_MAX_CONCURRENT_REQUESTS : rawConcurrency;\n\tassertPositiveInteger(maxConcurrentRequests, \"maxConcurrentRequests\");\n\tif (maxConcurrentRequests > MAX_CONCURRENT_REQUESTS_LIMIT) throw configError(\"limit_out_of_range\", \"maxConcurrentRequests\");\n\tconst ca = readCa(readOwn(options, \"ca\", \"ca\", unreadableFail));\n\tconst clock = captureOptionalClock(readOwn(options, \"clock\", \"clock\", unreadableFail));\n\treturn freeze({\n\t\tmaxResponseBytes,\n\t\tmaxConcurrentRequests,\n\t\tca,\n\t\tclock,\n\t\tallowNonPublic: switches.allowNonPublicAddresses === true,\n\t\tport: switches.port,\n\t});\n}\n\nfunction readCa(value: unknown): readonly string[] | undefined {\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"string\") return value === \"\" ? unreadableFail(\"not_plain\", \"ca\") : frozenList([value]);\n\tif (!isArray(value)) throw unreadable();\n\tconst length = readOwn(value, \"length\", \"ca\", unreadableFail);\n\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > 1_024) throw unreadable();\n\tconst copy: string[] = [];\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst item = readOwn(value, `${index}`, \"ca\", unreadableFail);\n\t\tif (typeof item !== \"string\" || item === \"\") throw unreadable();\n\t\tcopy[copy.length] = item;\n\t}\n\treturn frozenList(copy);\n}\n\n/** Read the request into a snapshot and re-check its destination. A refusal is returned as a result. */\nfunction prepareRequest(request: unknown, settings: TransportSettings): PreparedRequest | WebhookTransportResult {\n\tif (!isPlainRecord(request)) throw unreadable();\n\tconst destination = readOwn(request, \"destination\", \"destination\", unreadableFail);\n\tconst method = primitive(readOwn(request, \"method\", \"method\", unreadableFail));\n\tconst body = primitive(readOwn(request, \"body\", \"body\", unreadableFail));\n\tconst headers = readOwn(request, \"headers\", \"headers\", unreadableFail);\n\tif (!isPlainRecord(destination) || method !== \"POST\" || typeof body !== \"string\") throw unreadable();\n\tconst outgoing = readHeaders(headers);\n\n\tconst url = primitive(readOwn(destination, \"url\", \"destination.url\", unreadableFail));\n\tconst hostname = primitive(readOwn(destination, \"hostname\", \"destination.hostname\", unreadableFail));\n\tconst port = primitive(readOwn(destination, \"port\", \"destination.port\", unreadableFail));\n\tconst rawAddresses = readOwn(destination, \"addresses\", \"destination.addresses\", unreadableFail);\n\n\tconst check = checkDestinationUrl(url, settings.allowNonPublic);\n\tif (!check.ok) return check.code === \"private_address\" ? PRIVATE_ADDRESS : INVALID_URL;\n\tif (port !== 443 || hostname !== check.hostname) return INVALID_URL;\n\n\tconst addresses = readAddresses(rawAddresses, settings.allowNonPublic);\n\tif (addresses === undefined) return PRIVATE_ADDRESS;\n\tif (check.literal !== undefined) {\n\t\t// An IP-literal host has exactly one address: itself.\n\t\tfor (let index = 0; index < addresses.length; index += 1) {\n\t\t\tif (addresses[index]!.address !== check.literal.address) return INVALID_URL;\n\t\t}\n\t}\n\tconst hostHeader = check.literal !== undefined && check.literal.family === 6 ? `[${check.hostname}]` : check.hostname;\n\tconst path = check.url.slice(`https://${hostHeader}`.length);\n\tconst encoded = bufferFrom(body, \"utf8\");\n\toutgoing[\"Host\"] = hostHeader;\n\toutgoing[\"Content-Length\"] = `${encoded.length}`;\n\toutgoing[\"Connection\"] = \"close\";\n\treturn freeze({ hostname: check.hostname, path, headers: outgoing, body: encoded, addresses, literal: check.literal !== undefined });\n}\n\nfunction readHeaders(value: unknown): OutgoingHttpHeaders {\n\tif (!isPlainRecord(value)) throw unreadable();\n\tconst out = emptyMap<string>();\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.length > MAX_HEADERS) throw unreadable();\n\tfor (let index = 0; index < keys.length; index += 1) {\n\t\tconst name = keys[index];\n\t\tif (typeof name !== \"string\") throw unreadable();\n\t\tconst headerValue = primitive(readOwn(value, name, \"headers\", unreadableFail));\n\t\tif (typeof headerValue !== \"string\" || !matches(HEADER_NAME, name) || !matches(HEADER_VALUE, headerValue)) throw unreadable();\n\t\tif (matches(RESERVED_HEADER, name)) continue;\n\t\tout[name] = headerValue;\n\t}\n\treturn out as OutgoingHttpHeaders;\n}\n\n/** The vetted addresses, canonical; `undefined` when there are none or one is not public (unless allowed). */\nfunction readAddresses(value: unknown, allowNonPublic: boolean): readonly WebhookResolvedAddress[] | undefined {\n\tif (!isArray(value)) return undefined;\n\tconst length = readOwn(value, \"length\", \"destination.addresses\", unreadableFail);\n\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > 32) return undefined;\n\tconst out: WebhookResolvedAddress[] = [];\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst entry = readOwn(value, `${index}`, \"destination.addresses\", unreadableFail);\n\t\tif (!isPlainRecord(entry)) return undefined;\n\t\tconst address = primitive(readOwn(entry, \"address\", \"destination.addresses\", unreadableFail));\n\t\tconst family = primitive(readOwn(entry, \"family\", \"destination.addresses\", unreadableFail));\n\t\tconst judged = classifyAddress(address);\n\t\tif (judged.kind === \"public\" && judged.family === family) {\n\t\t\tout[out.length] = record({ address: judged.address, family: judged.family });\n\t\t\tcontinue;\n\t\t}\n\t\t// Zone-scoped addresses are refused even here: a zone is not an address the pinned lookup can return.\n\t\tif (allowNonPublic && judged.kind === \"non_public\" && judged.family === family && typeof address === \"string\" && !address.includes(\"%\")) {\n\t\t\tout[out.length] = record({ address, family: judged.family });\n\t\t\tcontinue;\n\t\t}\n\t\treturn undefined;\n\t}\n\treturn frozenList(out);\n}\n\n/** `not_sent` when the call is no longer wanted: aborted, past its deadline, or the clock cannot tell. */\nfunction notWanted(bounds: CallBounds, clock: CapturedClock): WebhookTransportResult | undefined {\n\tif (isAborted(bounds.signal)) return NOT_SENT_ABORTED;\n\tif (!(bounds.deadlineMs > clockNowMs(clock))) return NOT_SENT_DEADLINE;\n\treturn undefined;\n}\n\nfunction dispatch(slots: Slots, settings: TransportSettings, prepared: PreparedRequest, bounds: CallBounds): Promise<WebhookTransportResult> {\n\treturn new PromiseConstructor<WebhookTransportResult>((resolve) => {\n\t\tconst release = (): void => {\n\t\t\tslots.active -= 1;\n\t\t\tpump(slots, settings);\n\t\t};\n\t\tconst begin = (): void => {\n\t\t\tperform(settings, prepared, bounds, (result) => {\n\t\t\t\trelease();\n\t\t\t\tresolve(result);\n\t\t\t});\n\t\t};\n\t\tif (slots.active < settings.maxConcurrentRequests) {\n\t\t\tslots.active += 1;\n\t\t\tbegin();\n\t\t\treturn;\n\t\t}\n\t\tenqueue(slots, settings, bounds, begin, resolve);\n\t});\n}\n\nfunction enqueue(\n\tslots: Slots,\n\tsettings: TransportSettings,\n\tbounds: CallBounds,\n\tbegin: () => void,\n\tresolve: (result: WebhookTransportResult) => void,\n): void {\n\tlet cancelTimer: () => void = () => {};\n\tlet removeAbort: () => void = () => {};\n\tconst call: QueuedCall = {\n\t\tstart: () => {\n\t\t\tcancelTimer();\n\t\t\tremoveAbort();\n\t\t\tbegin();\n\t\t},\n\t\tnext: undefined,\n\t\tprev: undefined,\n\t};\n\tconst drop = (result: WebhookTransportResult): void => {\n\t\tunlink(slots, call);\n\t\tcancelTimer();\n\t\tremoveAbort();\n\t\tresolve(result);\n\t};\n\tif (slots.tail === undefined) {\n\t\tslots.head = call;\n\t\tslots.tail = call;\n\t} else {\n\t\tcall.prev = slots.tail;\n\t\tslots.tail.next = call;\n\t\tslots.tail = call;\n\t}\n\tcancelTimer = startTimer(bounds.deadlineMs - clockNowMs(settings.clock), () => drop(NOT_SENT_DEADLINE));\n\tremoveAbort = onAbort(bounds.signal, () => drop(NOT_SENT_ABORTED));\n}\n\nfunction unlink(slots: Slots, call: QueuedCall): void {\n\tif (call.prev !== undefined) call.prev.next = call.next;\n\telse if (slots.head === call) slots.head = call.next;\n\tif (call.next !== undefined) call.next.prev = call.prev;\n\telse if (slots.tail === call) slots.tail = call.prev;\n\tcall.next = undefined;\n\tcall.prev = undefined;\n}\n\n/**\n * Start queued calls, oldest first, while slots are free. A started call\n * that fails its last check settles synchronously and releases its slot,\n * which calls `pump` again; the `pumping` flag turns that re-entry into\n * another turn of this loop, so draining any backlog uses constant stack\n * depth.\n */\nfunction pump(slots: Slots, settings: TransportSettings): void {\n\tif (slots.pumping) return;\n\tslots.pumping = true;\n\ttry {\n\t\twhile (slots.head !== undefined && slots.active < settings.maxConcurrentRequests) {\n\t\t\tconst call = slots.head;\n\t\t\tunlink(slots, call);\n\t\t\tslots.active += 1;\n\t\t\tcall.start();\n\t\t}\n\t} finally {\n\t\tslots.pumping = false;\n\t}\n}\n\n/**\n * The lookup Node's socket uses: it answers with the vetted addresses for\n * the vetted name and refuses any other name. Node connects synchronously\n * from inside this callback, so a throw there (an address it cannot use)\n * would escape as an uncaught exception; it is caught and reported through\n * `onFault` instead.\n */\nfunction pinnedLookup(hostname: string, addresses: readonly WebhookResolvedAddress[], onFault: () => void): LookupFunction {\n\treturn (host, options, callback) => {\n\t\ttry {\n\t\t\tif (host !== hostname) {\n\t\t\t\tconst error = new Error(\"Webhook transport refused a lookup for a name other than the vetted one.\") as NodeJS.ErrnoException;\n\t\t\t\terror.code = \"ENOTFOUND\";\n\t\t\t\tcallback(error, \"\", 4);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (options.all === true) {\n\t\t\t\tconst all: { address: string; family: number }[] = [];\n\t\t\t\tfor (let index = 0; index < addresses.length; index += 1) all[all.length] = { address: addresses[index]!.address, family: addresses[index]!.family };\n\t\t\t\t(callback as unknown as (error: null, addresses: { address: string; family: number }[]) => void)(null, all);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcallback(null, addresses[0]!.address, addresses[0]!.family);\n\t\t} catch {\n\t\t\tonFault();\n\t\t}\n\t};\n}\n\nfunction perform(settings: TransportSettings, prepared: PreparedRequest, bounds: CallBounds, done: (result: WebhookTransportResult) => void): void {\n\tlet settled = false;\n\tlet status: number | undefined;\n\tlet retryAfter: string | null = null;\n\tlet request: ClientRequest | undefined;\n\tlet response: IncomingMessage | undefined;\n\tlet cancelTimer: () => void = () => {};\n\tlet removeAbort: () => void = () => {};\n\n\tconst responseResult = (): WebhookTransportResult => record({ kind: \"response\" as const, status: status!, retryAfter });\n\tconst finish = (result: WebhookTransportResult): void => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tcancelTimer();\n\t\tremoveAbort();\n\t\t// Stop all further work and reading; nothing of the body is kept.\n\t\tresponse?.destroy();\n\t\trequest?.destroy();\n\t\tdone(result);\n\t};\n\tconst stop = (): void => finish(status === undefined ? TIMEOUT : responseResult());\n\n\t// The last check, immediately before the connection is opened: a call\n\t// that waited in the queue may have been aborted or run out of time.\n\tif (isAborted(bounds.signal)) {\n\t\tfinish(NOT_SENT_ABORTED);\n\t\treturn;\n\t}\n\tconst remaining = bounds.deadlineMs - clockNowMs(settings.clock);\n\tif (!(remaining > 0)) {\n\t\tfinish(NOT_SENT_DEADLINE);\n\t\treturn;\n\t}\n\tcancelTimer = startTimer(remaining, stop);\n\tremoveAbort = onAbort(bounds.signal, stop);\n\n\ttry {\n\t\trequest = httpsRequest({\n\t\t\thost: prepared.hostname,\n\t\t\tport: settings.port,\n\t\t\tmethod: \"POST\",\n\t\t\tpath: prepared.path,\n\t\t\theaders: prepared.headers,\n\t\t\tsetHost: false,\n\t\t\tagent: false,\n\t\t\tlookup: pinnedLookup(prepared.hostname, prepared.addresses, () => finish(status === undefined ? NETWORK_ERROR : responseResult())),\n\t\t\t// RFC 6066 forbids an IP address as SNI; the certificate is then checked against the IP.\n\t\t\tservername: prepared.literal ? \"\" : prepared.hostname,\n\t\t\trejectUnauthorized: true,\n\t\t\tminVersion: \"TLSv1.2\",\n\t\t\tmaxHeaderSize: MAX_RESPONSE_HEADER_BYTES,\n\t\t\t...(settings.ca === undefined ? {} : { ca: settings.ca as string[] }),\n\t\t});\n\t} catch {\n\t\tfinish(NETWORK_ERROR);\n\t\treturn;\n\t}\n\trequest.on(\"error\", () => finish(status === undefined ? NETWORK_ERROR : responseResult()));\n\trequest.on(\"response\", (incoming: IncomingMessage) => {\n\t\tresponse = incoming;\n\t\tincoming.on(\"error\", () => finish(responseResult()));\n\t\tconst code = incoming.statusCode;\n\t\tif (typeof code !== \"number\" || !numberIsSafeInteger(code) || code < 100 || code > 599) {\n\t\t\tfinish(NETWORK_ERROR);\n\t\t\treturn;\n\t\t}\n\t\tstatus = code;\n\t\tconst header = incoming.headers[\"retry-after\"];\n\t\tretryAfter = typeof header === \"string\" && header.length <= MAX_RETRY_AFTER_LENGTH ? header : null;\n\t\tconst declared = incoming.headers[\"content-length\"];\n\t\tif (typeof declared === \"string\" && matches(DECIMAL, declared) && NumberConstructor(declared) > settings.maxResponseBytes) {\n\t\t\tfinish(responseResult());\n\t\t\treturn;\n\t\t}\n\t\tlet received = 0;\n\t\tincoming.on(\"data\", (chunk: Buffer) => {\n\t\t\treceived += chunk.length;\n\t\t\tif (received > settings.maxResponseBytes) finish(responseResult());\n\t\t});\n\t\tincoming.on(\"end\", () => finish(responseResult()));\n\t\tincoming.on(\"close\", () => finish(responseResult()));\n\t});\n\tif (settled) return;\n\trequest.end(prepared.body);\n}\n","import { Resolver } from \"node:dns/promises\";\n\nimport { isAborted, onAbort } from \"../call-bounds\";\nimport type { WebhookDnsLookup } from \"../destination\";\nimport { configError, guard, inputError } from \"../errors\";\nimport { WEBHOOK_MAX_TIMER_MS, assertPositiveInteger } from \"../limits\";\nimport type { WebhookCallOptions, WebhookResolvedAddress } from \"../ports\";\nimport { frozenList, isArray, isPlainRecord, numberIsSafeInteger, primitive, readOwn, record, type Fail } from \"../snapshot\";\n\n/** The default per-query timeout of {@link createNodeWebhookDnsLookup}. */\nexport const DEFAULT_NODE_WEBHOOK_DNS_TIMEOUT_MS = 5_000;\n\n/** Options for {@link createNodeWebhookDnsLookup}. */\nexport interface NodeWebhookDnsLookupOptions {\n\t/** DNS servers (`\"ip\"` or `\"ip:port\"`), as `Resolver.setServers` takes them; the system's by default. */\n\treadonly servers?: readonly string[];\n\t/** Timeout of each A and AAAA query; default {@link DEFAULT_NODE_WEBHOOK_DNS_TIMEOUT_MS}. */\n\treadonly timeoutMs?: number;\n}\n\nconst unreadable = (): Error => inputError(\"type\", \"input_unreadable\");\nconst unreadableFail: Fail = () => {\n\tthrow unreadable();\n};\n\n/**\n * \"The name exists but has no records of this type\": an empty half of the\n * answer, not a failure. \"No such name\" (`ENOTFOUND`) is a failure: the two\n * queries disagreeing about whether the name exists is a partial answer.\n */\nfunction isNoRecords(error: unknown): boolean {\n\treturn (error as { code?: unknown } | null)?.code === \"ENODATA\";\n}\n\n/**\n * A {@link WebhookDnsLookup} for `createWebhookDestinationResolver()` built on\n * a fresh `node:dns` `Resolver` per call, asking for A and AAAA records\n * together. It uses c-ares rather than `dns.lookup()` because a c-ares query\n * can be cancelled: when the resolver aborts the call's signal, the queries\n * are cancelled instead of holding a libuv thread-pool thread until the\n * operating system gives up, so a slow authoritative server named in a\n * destination cannot starve the pool. It therefore does not consult\n * `/etc/hosts`.\n *\n * The answer is every A and AAAA address. A query that fails for any reason\n * other than \"no records of this type\" (`ENODATA`), \"no such name\"\n * (`ENOTFOUND`) included, rejects the whole lookup, so a half-answered name\n * is a `dns_failure` behind the resolver, never a partial pass.\n *\n * @throws {TypeError} `input_unreadable` when `servers` is not a list of\n * server strings `Resolver.setServers` accepts.\n * @throws {WebhookDeliveryConfigError} when `timeoutMs` is not a positive\n * whole number of at most `WEBHOOK_MAX_TIMER_MS`.\n */\nexport function createNodeWebhookDnsLookup(options: NodeWebhookDnsLookupOptions = {}): WebhookDnsLookup {\n\tconst settings = guard(() => readLookupOptions(options), unreadable);\n\tconst lookup = async (hostname: string, callOptions: WebhookCallOptions): Promise<readonly WebhookResolvedAddress[]> => {\n\t\tconst signal = callOptions.signal;\n\t\tif (isAborted(signal)) throw unreadable();\n\t\tconst resolver = new Resolver({ timeout: settings.timeoutMs, tries: 1 });\n\t\tif (settings.servers !== undefined) resolver.setServers(settings.servers as string[]);\n\t\tconst removeAbort = onAbort(signal, () => resolver.cancel());\n\t\ttry {\n\t\t\tconst [v4, v6] = await Promise.all([records(resolver.resolve4(hostname)), records(resolver.resolve6(hostname))]);\n\t\t\tconst answer: WebhookResolvedAddress[] = [];\n\t\t\tfor (const address of v4) answer[answer.length] = record({ address, family: 4 as const });\n\t\t\tfor (const address of v6) answer[answer.length] = record({ address, family: 6 as const });\n\t\t\treturn frozenList(answer);\n\t\t} finally {\n\t\t\tremoveAbort();\n\t\t\tresolver.cancel();\n\t\t}\n\t};\n\treturn lookup;\n}\n\nasync function records(query: Promise<string[]>): Promise<readonly string[]> {\n\ttry {\n\t\treturn await query;\n\t} catch (error) {\n\t\tif (isNoRecords(error)) return [];\n\t\tthrow error;\n\t}\n}\n\ninterface LookupSettings {\n\treadonly servers: readonly string[] | undefined;\n\treadonly timeoutMs: number;\n}\n\nfunction readLookupOptions(options: unknown): LookupSettings {\n\tif (!isPlainRecord(options)) throw unreadable();\n\tconst rawTimeout = primitive(readOwn(options, \"timeoutMs\", \"timeoutMs\", unreadableFail));\n\tconst timeoutMs = rawTimeout === undefined ? DEFAULT_NODE_WEBHOOK_DNS_TIMEOUT_MS : rawTimeout;\n\tassertPositiveInteger(timeoutMs, \"timeoutMs\");\n\tif (timeoutMs > WEBHOOK_MAX_TIMER_MS) throw configError(\"limit_out_of_range\", \"timeoutMs\");\n\tconst rawServers = readOwn(options, \"servers\", \"servers\", unreadableFail);\n\tlet servers: readonly string[] | undefined;\n\tif (rawServers !== undefined) {\n\t\tif (!isArray(rawServers)) throw unreadable();\n\t\tconst length = readOwn(rawServers, \"length\", \"servers\", unreadableFail);\n\t\tif (typeof length !== \"number\" || !numberIsSafeInteger(length) || length < 1 || length > 16) throw unreadable();\n\t\tconst copy: string[] = [];\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tconst item = primitive(readOwn(rawServers, `${index}`, \"servers\", unreadableFail));\n\t\t\tif (typeof item !== \"string\") throw unreadable();\n\t\t\tcopy[copy.length] = item;\n\t\t}\n\t\t// Validate once at construction, so a bad server list fails here and not per call.\n\t\tnew Resolver().setServers(copy);\n\t\tservers = frozenList(copy);\n\t}\n\treturn { servers, timeoutMs };\n}\n"],"mappings":";;;;AAkCA,MAAM,eAAe,QAAQ;AAC7B,MAAM,iBAAiB,QAAQ;AAC/B,MAAMA,oCAAkC,QAAQ;AAChD,MAAM,wBAAwB,QAAQ;AACtC,MAAMC,0BAAwB,QAAQ;AACtC,MAAMC,iBAAe,OAAO;AAC5B,MAAM,eAAe,OAAO;AAC5B,MAAM,eAAe,OAAO;AAC5B,MAAM,kBAAkB,OAAO;AAC/B,MAAM,eAAe,MAAM;AAC3B,MAAM,cAAc,KAAK,UAAU;AACX,KAAK,UAAU;AAEvC,MAAM,aAAa,OAAO,UAAU;AACjB,OAAO,UAAU;;AAIpC,MAAa,QAAQ;;AAErB,MAAa,iBAAiB,OAAO;AACrC,MAAa,sBAAsB,OAAO;AAKjB,KAAK;AAC9B,MAAa,SAAS;AACtB,MAAa,SAAS;AACtB,MAAa,UAAU;;AAgBvB,MAAa,gBAA+B,OAAO,gCAAgC;;AAGnF,SAAS,eAAe,OAAoC;CAC3D,MAAM,aAAaA,eAAa,IAAI;CACpC,WAAW,QAAQ;CACnB,WAAW,aAAa;CACxB,WAAW,WAAW;CACtB,WAAW,eAAe;CAC1B,OAAO;AACR;;AAGA,SAAgB,OAAO,QAAgB,KAAsB,OAAsB;CAClF,wBAA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