@devlab.group/agent-commerce 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +19 -17
  2. package/dist/ap2.js +2 -2
  3. package/dist/{chunk-WDD2ZUR3.js → chunk-46Y5M7BA.js} +3 -2
  4. package/dist/chunk-46Y5M7BA.js.map +1 -0
  5. package/dist/{chunk-QZW5YL3G.js → chunk-5Q6W7YTK.js} +3 -3
  6. package/dist/{chunk-QZW5YL3G.js.map → chunk-5Q6W7YTK.js.map} +1 -1
  7. package/dist/{chunk-ENK63GKR.js → chunk-JF45GSNA.js} +3 -3
  8. package/dist/{chunk-ENK63GKR.js.map → chunk-JF45GSNA.js.map} +1 -1
  9. package/dist/{cli/chunk-APC5BTQM.js → chunk-RF3DFVXH.js} +2 -2
  10. package/dist/{chunk-IWXVQYG5.js.map → chunk-RF3DFVXH.js.map} +1 -1
  11. package/dist/cli/{ap2-GYKFGE66.js → ap2-SJZAZQIR.js} +5 -5
  12. package/dist/cli/{ap2-GYKFGE66.js.map → ap2-SJZAZQIR.js.map} +1 -1
  13. package/dist/cli/chunk-25WJIUJU.js +8 -0
  14. package/dist/cli/{chunk-SAAT2XFX.js.map → chunk-25WJIUJU.js.map} +1 -1
  15. package/dist/cli/{chunk-DKWO6LLX.js → chunk-4WPHZLVO.js} +3 -2
  16. package/dist/cli/chunk-4WPHZLVO.js.map +1 -0
  17. package/dist/cli/chunk-IJFPWT4I.js +435 -0
  18. package/dist/cli/chunk-IJFPWT4I.js.map +1 -0
  19. package/dist/cli/{chunk-VWQMSWDF.js → chunk-K34CRXKX.js} +3 -3
  20. package/dist/cli/{chunk-VWQMSWDF.js.map → chunk-K34CRXKX.js.map} +1 -1
  21. package/dist/cli/{chunk-WFIR374D.js → chunk-L264N3ZV.js} +41 -5
  22. package/dist/cli/chunk-L264N3ZV.js.map +1 -0
  23. package/dist/cli/{chunk-SYXLQ5BS.js → chunk-NM7V2Y4I.js} +5 -5
  24. package/dist/cli/{chunk-SYXLQ5BS.js.map → chunk-NM7V2Y4I.js.map} +1 -1
  25. package/dist/cli/{chunk-3PGFOEVJ.js → chunk-SHIA2B6G.js} +32 -6
  26. package/dist/cli/chunk-SHIA2B6G.js.map +1 -0
  27. package/dist/cli/{chunk-YXXPZFWC.js → chunk-U3SEGD4H.js} +126 -18
  28. package/dist/cli/chunk-U3SEGD4H.js.map +1 -0
  29. package/dist/{chunk-IWXVQYG5.js → cli/chunk-UV23DWUY.js} +2 -2
  30. package/dist/cli/{chunk-APC5BTQM.js.map → chunk-UV23DWUY.js.map} +1 -1
  31. package/dist/cli/{config-JWMHWVRT.js → config-IBG46HTQ.js} +6 -6
  32. package/dist/cli/{config-JWMHWVRT.js.map → config-IBG46HTQ.js.map} +1 -1
  33. package/dist/cli/index.js +33 -13
  34. package/dist/cli/index.js.map +1 -1
  35. package/dist/cli/{mcp-OW5GY7TT.js → mcp-F3EQQWDZ.js} +3 -3
  36. package/dist/cli/{mcp-OW5GY7TT.js.map → mcp-F3EQQWDZ.js.map} +1 -1
  37. package/dist/cli/payment-providers-FPTGQBU7.js +6 -0
  38. package/dist/cli/{payment-providers-QL2BJYMD.js.map → payment-providers-FPTGQBU7.js.map} +1 -1
  39. package/dist/cli/{provider-3A2LVEQS.js → provider-XACFJ7MG.js} +4 -4
  40. package/dist/cli/{provider-3A2LVEQS.js.map → provider-XACFJ7MG.js.map} +1 -1
  41. package/dist/cli/receipts-AXCPPGOK.js +9 -0
  42. package/dist/cli/{receipts-FQUFGEQD.js.map → receipts-AXCPPGOK.js.map} +1 -1
  43. package/dist/cli/{run-KF5OQYPL.js → run-C3VWMM57.js} +830 -184
  44. package/dist/cli/run-C3VWMM57.js.map +1 -0
  45. package/dist/cli/{x402-5A7CVCIJ.js → x402-SUXWULOP.js} +5 -5
  46. package/dist/cli/{x402-5A7CVCIJ.js.map → x402-SUXWULOP.js.map} +1 -1
  47. package/dist/index.d.ts +74 -31
  48. package/dist/index.js +1290 -255
  49. package/dist/index.js.map +1 -1
  50. package/dist/mcp.js +1 -1
  51. package/dist/mpp.js +2 -2
  52. package/dist/{store-BzgwHOPu.d.ts → store-04pazhFP.d.ts} +52 -1
  53. package/dist/testing.js +468 -273
  54. package/dist/testing.js.map +1 -1
  55. package/dist/x402.js +3 -3
  56. package/package.json +1 -1
  57. package/dist/chunk-WDD2ZUR3.js.map +0 -1
  58. package/dist/cli/chunk-3PGFOEVJ.js.map +0 -1
  59. package/dist/cli/chunk-6BWEHQPJ.js +0 -215
  60. package/dist/cli/chunk-6BWEHQPJ.js.map +0 -1
  61. package/dist/cli/chunk-DKWO6LLX.js.map +0 -1
  62. package/dist/cli/chunk-SAAT2XFX.js +0 -8
  63. package/dist/cli/chunk-WFIR374D.js.map +0 -1
  64. package/dist/cli/chunk-YXXPZFWC.js.map +0 -1
  65. package/dist/cli/payment-providers-QL2BJYMD.js +0 -6
  66. package/dist/cli/receipts-FQUFGEQD.js +0 -9
  67. package/dist/cli/run-KF5OQYPL.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/config/env.ts","../../src/config/filename.ts","../../src/protocols/acp/constants.ts","../../src/core/execution/journal.ts","../../src/core/execution/merchant-key.ts","../../src/core/execution/pipeline/retry.ts","../../src/core/execution/backend-http.ts","../../src/core/execution/pipeline/authorization.ts","../../src/core/execution/pipeline/challenge.ts","../../src/core/execution/pipeline/admission.ts","../../src/core/execution/pipeline/context.ts","../../src/core/execution/pipeline/settlement.ts","../../src/core/execution/pipeline/index.ts","../../src/core/execution/registry.ts","../../src/core/execution/store-event-sink.ts"],"names":["createHash","durationMs"],"mappings":";;;;;;;;;AAqBA,IAAM,mBAAA,GAAsB,6CAAA;AAG5B,IAAM,WAAA,GAAc,eAAA;AAGpB,IAAM,eAAA,GAAkB,0CAAA;AAGxB,IAAM,kBAAA,GAAqB,gBAAA;AAEpB,SAAS,aAAA,CAAc,KAAA,EAAgB,GAAA,EA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KAAA,EAAqC;AAC9C,MAAA,IAAI;AACF,QAAA,MAAM,OAAA,CAAQ,KAAA,CAAM,WAAA,CAAY,KAAK,CAAA;AAAA,MACvC,SAAS,KAAA,EAAO;AACd,QAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,UACb,EAAE,GAAA,EAAK,aAAA,CAAc,KAAK,CAAA,EAAG,WAAW,KAAA,CAAM,IAAA,EAAM,SAAA,EAAW,KAAA,CAAM,SAAA,EAAU;AAAA,UAC/E;AAAA,SACF;AAAA,MACF;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-WFIR374D.js","sourcesContent":["/**\n * `${VAR}` / `${VAR:-default}` substitution over a parsed YAML value.\n *\n * Only string leaves change; the caller coerces numeric and boolean strings\n * afterwards. `${VAR}` requires `VAR` in `env`, where an empty string counts as\n * present. `${VAR:-default}` uses `default` when `VAR` is absent or empty, as a\n * shell does. An unresolved placeholder fails config loading, so startup never\n * proceeds with a missing secret. There is no escape for a literal `${NAME}`.\n *\n * Anything else brace-shaped is refused, including nesting (`${A:-${B}}`) and\n * shell forms (`${VAR-x}`, `${VAR:=x}`, `${VAR:?x}`) that would otherwise load\n * as literal text: `adminToken: ${ADMIN_TOKEN-fallback}` would make that\n * literal the ledger credential. A bare `$VAR` is left alone, so values may\n * contain a dollar sign.\n *\n * The template rules are checked before substitution, and errors name the\n * variable and the config path, never a resolved value.\n */\nimport { CommerceError } from '../core';\nimport { isRecord } from '../core/is-record';\n\nconst PLACEHOLDER_PATTERN = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\\}/g;\n\n// An innermost brace token: `${`, then no braces, then `}`\nconst BRACE_TOKEN = /\\$\\{[^{}]*\\}/g;\n\n// PLACEHOLDER_PATTERN's grammar, anchored, for validating one token\nconst SUPPORTED_TOKEN = /^\\$\\{[A-Za-z_][A-Za-z0-9_]*(:-[^}]*)?\\}$/;\n\n// A placeholder whose default segment opens another placeholder\nconst NESTED_PLACEHOLDER = /\\$\\{[^{}]*\\$\\{/;\n\nexport function substituteEnv(value: unknown, env: NodeJS.ProcessEnv, path = '$'): unknown {\n if (typeof value === 'string') {\n return substituteString(value, env, path);\n }\n if (Array.isArray(value)) {\n return value.map((entry, index) => substituteEnv(entry, env, `${path}[${index}]`));\n }\n if (isRecord(value)) {\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n result[key] = substituteEnv(entry, env, `${path}.${key}`);\n }\n return result;\n }\n return value;\n}\n\n/** Sorted placeholder names from raw config, grouped by how they resolve in the environment */\nexport interface EnvPlaceholders {\n /** `${VAR}` with `VAR` unset; config loading stops at the first missing variable */\n readonly missing: readonly string[];\n /** `${VAR:-default}` with `VAR` unset or empty */\n readonly defaulted: readonly string[];\n readonly set: readonly string[];\n}\n\n/**\n * Collect recognized placeholder names without validating template syntax;\n * config loading reports unsupported templates. Each name appears once, using\n * the most severe state: missing, then defaulted, then set. Return names only,\n * never values or defaults.\n */\nexport function listEnvPlaceholders(raw: unknown, env: NodeJS.ProcessEnv): EnvPlaceholders {\n // 0 set, 1 defaulted, 2 missing: a higher number is worse\n const worst = new Map<string, number>();\n const visit = (value: unknown): void => {\n if (typeof value === 'string') {\n for (const [, name = '', hasDefault] of value.matchAll(PLACEHOLDER_PATTERN)) {\n const envValue = env[name];\n const state =\n hasDefault !== undefined\n ? envValue === undefined || envValue === ''\n ? 1\n : 0\n : envValue === undefined\n ? 2\n : 0;\n worst.set(name, Math.max(state, worst.get(name) ?? 0));\n }\n } else if (Array.isArray(value)) {\n value.forEach(visit);\n } else if (isRecord(value)) {\n Object.values(value).forEach(visit);\n }\n };\n visit(raw);\n const names = [...worst.keys()].sort();\n const named = (state: number) => names.filter((name) => worst.get(name) === state);\n return { missing: named(2), defaulted: named(1), set: named(0) };\n}\n\nfunction substituteString(value: string, env: NodeJS.ProcessEnv, path: string): string {\n assertTemplateIsSupported(value, path);\n return substituteOnce(value, env, path);\n}\n\n/**\n * Refuses a template this module cannot honor, before any substitution runs.\n *\n * For `${A:-${B}}`, `[^}]*` cannot span the inner `}`, so the match consumes\n * `${A:-${B` and leaves a stray `}`. With `A` set, substitution would succeed\n * and append that `}` to the value unnoticed, so `adminToken` would become a\n * credential the operator does not hold.\n */\nfunction assertTemplateIsSupported(value: string, path: string): void {\n if (NESTED_PLACEHOLDER.test(value)) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" nests placeholders (e.g. \"\\${A:-\\${B}}\"), which is not supported: the inner one is not resolved and its closing brace ends up in the value. Use a plain default, or set the variable.`,\n { details: { path } },\n );\n }\n\n for (const [token] of value.matchAll(BRACE_TOKEN)) {\n if (SUPPORTED_TOKEN.test(token)) continue;\n // Quotes the token, not the value; before substitution it holds no secret\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Configuration value at \"${path}\" contains \"${token}\", which is not a supported placeholder. Only \"\\${VAR}\" and \"\\${VAR:-default}\" are recognized; shell forms such as \"\\${VAR-default}\", \"\\${VAR:=default}\" and \"\\${VAR:?message}\" would load as literal text.`,\n { details: { path, token } },\n );\n }\n}\n\nfunction substituteOnce(value: string, env: NodeJS.ProcessEnv, path: string): string {\n return value.replace(\n PLACEHOLDER_PATTERN,\n (_match, name: string, hasDefault: string | undefined, def: string | undefined) => {\n const envValue = env[name];\n\n if (hasDefault !== undefined) {\n if (envValue === undefined || envValue === '') return def ?? '';\n return envValue;\n }\n\n if (envValue === undefined) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Unresolved environment variable \"\\${${name}}\" referenced at config path \"${path}\"`,\n { details: { variable: name, path } },\n );\n }\n return envValue;\n },\n );\n}\n","/**\n * The default configuration filename, shared by the loader, `init`'s default\n * output path and the `--config` help text.\n *\n * Its own module with no imports: `src/cli` loads the rest of `src/config`\n * only through a dynamic import (`src/cli/lib/config-client.ts`), so a broken\n * config module cannot take down commands that never read configuration. A\n * leaf with no module graph can be imported statically without undoing that.\n */\nexport const DEFAULT_CONFIG_FILENAME = 'config.yaml';\n","/**\n * ACP protocol constants shared by the config layer and the adapter.\n *\n * Kept dependency-free: `src/config` reads the operation set at load time, so\n * anything imported here would become a config-load dependency too.\n */\n\n/**\n * The ACP stable snapshot this adapter implements, and the only value accepted\n * in the `API-Version` request header. Both name the same released snapshot;\n * they are separate constants because ACP versions the wire contract and the\n * header independently, and a future snapshot may accept more than one.\n *\n * Changing either means vendoring a new schema directory beside\n * `spec/2026-04-17/` - never editing the vendored one in place.\n */\nexport const ACP_SPEC_VERSION = '2026-04-17';\nexport const ACP_API_VERSION = '2026-04-17';\n\n/** Discovery path fixed by the ACP specification, never a configurable mount */\nexport const ACP_WELL_KNOWN_PATH = '/.well-known/acp.json';\n\n/**\n * The stable checkout operations, by ACP operation id. All five are required\n * when ACP is enabled: a partially configured checkout lifecycle would be\n * advertised as a whole service the seller cannot actually serve.\n */\nexport const ACP_CHECKOUT_OPERATIONS = [\n 'createCheckoutSession',\n 'updateCheckoutSession',\n 'getCheckoutSession',\n 'completeCheckoutSession',\n 'cancelCheckoutSession',\n] as const;\n\nexport type AcpCheckoutOperation = (typeof ACP_CHECKOUT_OPERATIONS)[number];\n\n/**\n * Top-level canonical-input properties each operation always supplies.\n *\n * `path` carries `{ checkout_session_id }`, `body` the ACP request document.\n */\nexport const ACP_OPERATION_INPUT_KEYS: Readonly<\n Record<AcpCheckoutOperation, readonly ('path' | 'body')[]>\n> = {\n createCheckoutSession: ['body'],\n updateCheckoutSession: ['path', 'body'],\n getCheckoutSession: ['path'],\n completeCheckoutSession: ['path', 'body'],\n cancelCheckoutSession: ['path'],\n};\n\n/**\n * Canonical-input properties an operation supplies only when the caller sends\n * them. The pinned schema lets a cancel omit its body, so a bare cancel has no\n * `body`, but one carrying `intent_trace` passes it on.\n */\nexport const ACP_OPERATION_OPTIONAL_INPUT_KEYS: Readonly<\n Partial<Record<AcpCheckoutOperation, readonly 'body'[]>>\n> = {\n cancelCheckoutSession: ['body'],\n};\n\n/** The key inside `path` that carries the checkout session id from the route */\nexport const ACP_SESSION_ID_INPUT_KEY = 'checkout_session_id';\n\n/** Media type for every ACP request and response body */\nexport const ACP_JSON_MEDIA_TYPE = 'application/json';\n\n/**\n * Protocol headers, lowercased as Node delivers them.\n *\n * `API-Version` is mandatory on checkout requests and is never defaulted:\n * answering an unversioned request as if it named the pinned snapshot would be\n * guessing on the caller's behalf about a contract that changes.\n */\nexport const ACP_API_VERSION_HEADER = 'api-version';\nexport const ACP_REQUEST_ID_HEADER = 'request-id';\nexport const ACP_IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\nexport const ACP_IDEMPOTENT_REPLAYED_HEADER = 'idempotent-replayed';\n\n/**\n * Seconds a client is told to wait before retrying a key whose first request is\n * still running. Short: the original is a live HTTP call, not a queue.\n */\nexport const ACP_IN_FLIGHT_RETRY_AFTER_SECONDS = 1;\n\n/**\n * Longest `Request-Id` echoed back. The value is the caller's, so it is\n * bounded and filtered before it is ever written into a response header.\n */\nexport const ACP_MAX_REQUEST_ID_LENGTH = 128;\n\n/** Caller headers forwarded to the merchant; the bearer token stays at the gateway */\nexport const ACP_FORWARDED_HEADERS = [\n 'accept-language',\n 'user-agent',\n ACP_REQUEST_ID_HEADER,\n ACP_API_VERSION_HEADER,\n 'signature',\n 'timestamp',\n] as const;\n\n/** Maximum forwarded header value length; longer values are dropped */\nexport const ACP_MAX_FORWARDED_HEADER_LENGTH = 2048;\n\n/** Fallback and maximum `Retry-After` seconds for merchant 429 or 503 */\nexport const ACP_MERCHANT_RETRY_AFTER_DEFAULT_SECONDS = 5;\nexport const ACP_MERCHANT_RETRY_AFTER_MAX_SECONDS = 300;\n","// Execution identity and digests for the transaction journal\nimport { createHash } from 'node:crypto';\nimport { canonicalJson } from '../canonical-json';\nimport type { PaymentRequirement, PaymentResult } from '../domain/payment';\nimport { RECONCILIATION_METADATA_KEY } from '../domain/payment';\nimport type { CanonicalRequest } from '../domain/request';\nimport type { CommerceResource } from '../domain/resource';\nimport type { PersistenceFailure } from '../domain/transaction';\nimport type { NewTransaction } from '../interfaces/store';\nimport { isRecord } from '../is-record';\nimport { SETTLE_AFTER_BACKEND_METADATA_KEY } from './settlement-order';\n\n/** One execute() call */\nexport interface Flow {\n readonly request: CanonicalRequest;\n readonly transactionId: string;\n /** Labels for failed writes, deduplicated in order of first failure */\n readonly persistenceFailures: PersistenceFailure[];\n /** True when the reserved attempt matches this ID and the store provides recordTransactionStep */\n journaled: boolean;\n /**\n * Set before calling provider.settle. Cleared on confirmed non-submission\n * or a non-settled result; unknown outcomes keep it true.\n */\n chargeRisk: boolean;\n}\n\nexport function createFlow(request: CanonicalRequest, transactionId: string): Flow {\n return { request, transactionId, persistenceFailures: [], journaled: false, chargeRisk: false };\n}\n\n/** Snapshot failure labels for events and outcomes, omitting the field when empty */\nexport function failuresOf(flow: Flow): { persistenceFailures?: readonly PersistenceFailure[] } {\n return flow.persistenceFailures.length > 0\n ? { persistenceFailures: [...flow.persistenceFailures] }\n : {};\n}\n\nfunction sha256(text: string): string {\n return `sha256:${createHash('sha256').update(text, 'utf8').digest('hex')}`;\n}\n\n/** Hash canonical JSON input, or return undefined when canonicalJson does */\nexport function inputDigest(input: unknown): string | undefined {\n const json = canonicalJson(input);\n return json !== undefined ? sha256(json) : undefined;\n}\n\n/**\n * Hash the resource's pricing, payment methods, authorization requirements and\n * selected payment terms. Exclude handler URLs and headers because they may\n * contain credentials.\n */\nexport function configDigest(resource: CommerceResource, requirement: PaymentRequirement): string {\n const terms = {\n resourceId: resource.id,\n pricing: resource.pricing,\n paymentMethods: resource.paymentMethods,\n authorization: resource.authorization?.required ?? [],\n requirement: {\n provider: requirement.provider,\n amount: requirement.amount,\n currency: requirement.currency,\n destination: requirement.destination ?? null,\n network: requirement.network ?? null,\n asset: requirement.asset ?? null,\n settleAfterBackend: requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true,\n },\n };\n // Fall back to JSON.stringify when terms cannot be canonicalized, such as\n // a configuration string containing a lone surrogate\n return sha256(canonicalJson(terms) ?? JSON.stringify(terms));\n}\n\n/** Build journal data for a verified payment's replay reservation */\nexport function newTransaction(\n flow: Flow,\n resource: CommerceResource,\n requirement: PaymentRequirement,\n verification: PaymentResult,\n digest: string | undefined,\n authorization: NewTransaction['authorization'],\n): NewTransaction {\n const raw = verification.metadata?.[RECONCILIATION_METADATA_KEY];\n const locator = isRecord(raw) ? raw : undefined;\n const expiresAt = typeof locator?.['expiresAt'] === 'string' ? locator['expiresAt'] : undefined;\n const network = verification.network ?? requirement.network;\n const asset = verification.asset ?? requirement.asset;\n return {\n id: flow.transactionId,\n protocol: flow.request.protocol,\n ...(network !== undefined ? { network } : {}),\n ...(asset !== undefined ? { asset } : {}),\n ...(locator !== undefined ? { locator } : {}),\n ...(expiresAt !== undefined ? { expiresAt } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n ...(digest !== undefined ? { inputDigest: digest } : {}),\n configDigest: configDigest(resource, requirement),\n };\n}\n","// The `Idempotency-Key` that names a paid operation to the merchant\nimport { createHash } from 'node:crypto';\n\nexport interface PaidOperation {\n /** `merchant.publicBaseUrl`, which outlives credential rotation */\n readonly deployment: string;\n readonly resourceId: string;\n readonly replayKey: string;\n /** `inputDigest` of the validated input */\n readonly inputDigest: string | undefined;\n /**\n * Client retry credential; only its hash enters the payment identity. Pass it\n * only with `redelivery`, so the retry gate reserves it before the merchant call.\n */\n readonly clientKey?: string;\n readonly payer?: string;\n}\n\nexport function sha256Hex(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n\n/**\n * Derive a merchant operation key, or return `undefined` without an input digest.\n *\n * Use the hash of `clientKey` with `payer` when both are nonempty; otherwise\n * use `replayKey`. The client key keeps the same identity across proof changes;\n * the payer distinguishes buyers sharing that key. The input digest separates\n * bodies when a rejected proof is retried. Serialize fields as a JSON array to\n * keep delimiters in URLs or resource IDs within their fields. Format changes\n * alter derived keys and can break merchant deduplication.\n */\nexport function paidOperationKey(operation: PaidOperation): string | undefined {\n const { deployment, resourceId, replayKey, inputDigest: digest, clientKey, payer } = operation;\n if (digest === undefined) return undefined;\n const identity = clientKey && payer ? `retry:${sha256Hex(clientKey)}:${payer}` : replayKey;\n return sha256Hex(JSON.stringify(['paid-operation', deployment, resourceId, identity, digest]));\n}\n","// The retry gate: a client key either unlocks a stored response or claims the purchase\nimport type { PaymentProvider, PaymentResult, PaymentSubmission } from '../../domain/payment';\nimport type { CommerceReceipt } from '../../domain/receipt';\nimport type { DeliveredOutcome } from '../../domain/request';\nimport type { CommerceResource } from '../../domain/resource';\nimport {\n type IdempotencyClaim,\n type IdempotencyScope,\n type IdempotencyUpdate,\n PAYMENT_KEY_ENDPOINT_PREFIX,\n} from '../../domain/store-records';\nimport { CommerceError, isCommerceError } from '../../errors';\nimport type { BackendResponse } from '../../interfaces/backend';\nimport type { ReceiptStore } from '../../interfaces/store';\nimport { isRecord } from '../../is-record';\nimport { hasMethodGroup, type StoreGroupMethods } from '../../store-method-groups';\nimport { type Flow, inputDigest } from '../journal';\nimport { sha256Hex } from '../merchant-key';\nimport type { PipelineContext } from './context';\n\ntype RetryStore = ReceiptStore &\n StoreGroupMethods<'idempotency_claims'> &\n StoreGroupMethods<'response_redelivery'>;\n\n/** Pipeline dependencies for merchant keys or response redelivery */\nexport interface RetrySupport {\n readonly deployment: string;\n /** Set on a resource that stores responses */\n readonly store?: RetryStore;\n}\n\n/** A presented client key and its claim data; finalize it after a successful claim */\nexport interface RetryTicket {\n readonly kind: 'retry';\n readonly store: RetryStore;\n readonly scope: IdempotencyScope;\n readonly fingerprint: string;\n readonly expiresAt: string;\n /** A credential: never log it, and never send it to a merchant or facilitator */\n readonly clientKey: string;\n /** Tags the claim; only this proof gets an answer before verification */\n readonly proofDigest: string;\n readonly authorizationDigest?: string;\n}\n\nexport interface RetryGate {\n /**\n * Read retry state without changing the claim. For the owning proof, return\n * the stored response or refuse an unfinished claim. Otherwise, return a\n * ticket for verification, or `undefined` if redelivery is disabled or the\n * proof or key is missing.\n */\n readonly open: (\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n validInput: unknown,\n support: RetrySupport | undefined,\n pipelineStart: number,\n ) => Promise<RetryTicket | DeliveredOutcome | undefined>;\n /**\n * Claim the key after proof verification. Return `undefined` when this request\n * owns the purchase. Reuse a stored response only if the verified payer is\n * defined and matches its recorded payer, and any required authorization is\n * the one recorded with it.\n */\n readonly claim: (\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n ticket: RetryTicket,\n verification: PaymentResult,\n pipelineStart: number,\n ) => Promise<DeliveredOutcome | undefined>;\n /** Store the response or attempt to mark its claim unresolved */\n readonly finishDelivered: (\n flow: Flow,\n ticket: RetryTicket,\n verification: PaymentResult,\n response: BackendResponse,\n receipt: CommerceReceipt,\n ) => Promise<void>;\n /** Attempt to release an uncharged claim or mark a possible charge unresolved */\n readonly finishFailed: (flow: Flow, ticket: RetryTicket) => Promise<void>;\n}\n\n// The stored row's body. Of the backend's headers, it keeps only the content type\ninterface StoredDelivery {\n readonly proofDigest: string;\n readonly authorizationDigest?: string;\n readonly payer?: string;\n readonly contentType?: string;\n readonly body: unknown;\n readonly receiptId: string;\n}\n\n/** The longest `redelivery.retentionHours` a resource may set: one year */\nexport const MAX_REDELIVERY_RETENTION_HOURS = 8760;\n\n// The delay ACP gives its own in-flight answer\nconst IN_FLIGHT_RETRY_AFTER_SECONDS = 1;\n\nconst REFUSALS = {\n conflict: {\n reason: 'payment_identifier_conflict',\n message: 'This payment identifier belongs to another request',\n },\n 'in-flight': {\n reason: 'payment_identifier_in_flight',\n message: 'A request with this payment identifier is in progress',\n },\n unresolved: {\n reason: 'payment_identifier_unresolved',\n message:\n 'The earlier request with this payment identifier may have been charged and has no stored response',\n },\n} as const;\n\ntype RefusedClaim = keyof typeof REFUSALS;\n\n/**\n * Validate deployment and store support for enabled retry features.\n * Return `undefined` when both features are disabled; throw `CONFIG_INVALID`\n * for missing dependencies.\n */\nexport function assertRetrySupport(\n resource: CommerceResource,\n store: ReceiptStore,\n deployment: string | undefined,\n requestId?: string,\n): RetrySupport | undefined {\n const { merchantKey, redelivery } = resource.idempotency ?? {};\n if (merchantKey !== true && redelivery === undefined) return undefined;\n const invalid = (message: string) =>\n new CommerceError('CONFIG_INVALID', message, {\n ...(requestId !== undefined ? { requestId } : {}),\n resourceId: resource.id,\n });\n const unsupported = (needs: string) =>\n invalid(`Resource \"${resource.id}\" sets idempotency, which requires ${needs}`);\n // Bound retention to one year before computing its deadline\n const hours = redelivery?.retentionHours;\n if (\n hours !== undefined &&\n !(Number.isInteger(hours) && hours >= 1 && hours <= MAX_REDELIVERY_RETENTION_HOURS)\n ) {\n throw invalid(\n `Resource \"${resource.id}\" sets idempotency.redelivery.retentionHours outside 1 to ${MAX_REDELIVERY_RETENTION_HOURS}`,\n );\n }\n if (deployment === undefined) throw unsupported(\"the pipeline's deployment option\");\n if (redelivery === undefined) return { deployment };\n if (\n !hasMethodGroup(store, 'idempotency_claims') ||\n !hasMethodGroup(store, 'response_redelivery')\n ) {\n throw unsupported('a store with idempotency claims and getIdempotencyKey');\n }\n return { deployment, store };\n}\n\nexport function createRetryGate(ctx: PipelineContext): RetryGate {\n const { options, safeEmit, safePersist, buildEvent } = ctx;\n\n async function open(\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n validInput: unknown,\n support: RetrySupport | undefined,\n pipelineStart: number,\n ): Promise<RetryTicket | DeliveredOutcome | undefined> {\n const { request } = flow;\n const retentionHours = resource.idempotency?.redelivery?.retentionHours;\n const { payment } = request;\n if (support?.store === undefined || retentionHours === undefined || payment === undefined) {\n return undefined;\n }\n const clientKey =\n request.retryKey ?? (await providerRetryKey(flow, resource, provider, payment));\n if (clientKey === undefined) return undefined;\n\n const fingerprint = inputDigest(validInput);\n if (fingerprint === undefined) {\n throw await rejected(\n flow,\n resource,\n provider,\n new CommerceError(\n 'INPUT_INVALID',\n `Input for resource \"${resource.id}\" is not I-JSON, so a retry key cannot identify it`,\n { requestId: request.requestId, resourceId: resource.id },\n ),\n );\n }\n\n const { store } = support;\n const { authorization } = request;\n const ticket: RetryTicket = {\n kind: 'retry',\n store,\n scope: {\n deployment: support.deployment,\n endpoint: `${PAYMENT_KEY_ENDPOINT_PREFIX}${resource.id}`,\n key: sha256Hex(clientKey),\n },\n fingerprint,\n expiresAt: new Date(\n options.clock.now().getTime() + retentionHours * 60 * 60 * 1000,\n ).toISOString(),\n clientKey,\n proofDigest: sha256Hex(`${payment.method}:${payment.payload}`),\n ...(authorization !== undefined\n ? { authorizationDigest: sha256Hex(`${authorization.method}:${authorization.payload}`) }\n : {}),\n };\n\n const existing = await reading(flow, resource, () =>\n store.getIdempotencyKey(ticket.scope, fingerprint),\n );\n // Refusing an unverified proof would reveal the key's existence or input\n if (existing?.kind === 'in-flight' || existing?.kind === 'unresolved') {\n if (existing.owner !== ticket.proofDigest) return ticket;\n throw await refusal(flow, resource, provider, existing.kind);\n }\n if (existing?.kind !== 'replay') return ticket;\n const stored = readStoredDelivery(existing.body);\n return stored?.proofDigest === ticket.proofDigest && authorizes(resource, stored, ticket)\n ? redeliver(flow, resource, provider, existing.status, stored, pipelineStart)\n : ticket;\n }\n\n async function claim(\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n ticket: RetryTicket,\n verification: PaymentResult,\n pipelineStart: number,\n ): Promise<DeliveredOutcome | undefined> {\n const { scope, fingerprint, expiresAt, proofDigest } = ticket;\n const claimed = await reading(flow, resource, () =>\n ticket.store.claimIdempotencyKey(scope, fingerprint, expiresAt, proofDigest),\n );\n const replay = await acceptOrRefuse(flow, resource, provider, claimed);\n if (replay === undefined) return undefined;\n const stored = await storedDelivery(flow, resource, provider, replay);\n const samePayer = verification.payer !== undefined && verification.payer === stored.payer;\n if (!samePayer || !authorizes(resource, stored, ticket)) {\n throw await refusal(flow, resource, provider, 'conflict');\n }\n return redeliver(flow, resource, provider, replay.status, stored, pipelineStart);\n }\n\n async function finishDelivered(\n flow: Flow,\n ticket: RetryTicket,\n verification: PaymentResult,\n response: BackendResponse,\n receipt: CommerceReceipt,\n ): Promise<void> {\n const contentType = response.headers['content-type'];\n const stored: StoredDelivery = {\n proofDigest: ticket.proofDigest,\n ...(ticket.authorizationDigest !== undefined\n ? { authorizationDigest: ticket.authorizationDigest }\n : {}),\n // Record the verified buyer; settlement may name a fee payer instead\n ...(verification.payer !== undefined ? { payer: verification.payer } : {}),\n // Keep only Content-Type; never persist a backend Set-Cookie header\n ...(contentType !== undefined ? { contentType } : {}),\n body: response.body ?? null,\n receiptId: receipt.id,\n };\n // Complete the claim only if its original receipt was saved\n const receiptSaved = !flow.persistenceFailures.includes('receipt');\n const update = { kind: 'completed', status: response.status, body: stored } as const;\n if (receiptSaved && (await write(flow, ticket, update))) return;\n if (!flow.persistenceFailures.includes('response')) flow.persistenceFailures.push('response');\n await write(flow, ticket, { kind: 'unresolved' });\n }\n\n async function finishFailed(flow: Flow, ticket: RetryTicket): Promise<void> {\n await write(flow, ticket, { kind: flow.chargeRisk ? 'unresolved' : 'released' });\n }\n\n // Record write failures without replacing a delivery or the original error\n function write(flow: Flow, ticket: RetryTicket, update: IdempotencyUpdate): Promise<boolean> {\n return safePersist(\n flow,\n () => ticket.store.updateIdempotencyKey(ticket.scope, update),\n `updateIdempotencyKey(${update.kind})`,\n 'response',\n );\n }\n\n async function reading<T>(\n flow: Flow,\n resource: CommerceResource,\n read: () => Promise<T>,\n ): Promise<T> {\n try {\n return await read();\n } catch (error) {\n throw new CommerceError('STORAGE_ERROR', 'Payment retry state could not be read', {\n requestId: flow.request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n }\n }\n\n // Returns a stored response to consider, or `undefined` for an open key\n async function acceptOrRefuse(\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n claimed: IdempotencyClaim | undefined,\n ): Promise<Extract<IdempotencyClaim, { kind: 'replay' }> | undefined> {\n if (claimed === undefined || claimed.kind === 'reserved') return undefined;\n if (claimed.kind === 'replay') return claimed;\n throw await refusal(flow, resource, provider, claimed.kind);\n }\n\n // A malformed stored response may represent a charge; refuse it as unresolved\n async function storedDelivery(\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n replay: Extract<IdempotencyClaim, { kind: 'replay' }>,\n ): Promise<StoredDelivery> {\n const stored = readStoredDelivery(replay.body);\n if (stored === undefined) throw await refusal(flow, resource, provider, 'unresolved');\n return stored;\n }\n\n // These 409s omit a payment challenge to avoid prompting another charge.\n // Only in-flight claims are retryable; the active request may finish on its own.\n function refusal(\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n kind: RefusedClaim,\n ): Promise<CommerceError> {\n const { reason, message } = REFUSALS[kind];\n const inFlight = kind === 'in-flight';\n return rejected(\n flow,\n resource,\n provider,\n new CommerceError('PAYMENT_REPLAYED', message, {\n requestId: flow.request.requestId,\n resourceId: resource.id,\n details: {\n reason,\n ...(inFlight ? { retryAfterSeconds: IN_FLIGHT_RETRY_AFTER_SECONDS } : {}),\n },\n ...(inFlight ? { retryable: true } : {}),\n }),\n );\n }\n\n // Emit the admission refusal with this request's ID\n async function rejected(\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n error: CommerceError,\n ): Promise<CommerceError> {\n const reason = error.details?.['reason'];\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: flow.request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: typeof reason === 'string' ? reason : error.code },\n }),\n );\n if (error.requestId !== undefined) return error;\n return new CommerceError(error.code, error.message, {\n requestId: flow.request.requestId,\n resourceId: error.resourceId ?? resource.id,\n httpStatus: error.httpStatus,\n retryable: error.retryable,\n ...(error.details !== undefined ? { details: error.details } : {}),\n ...(error.cause !== undefined ? { cause: error.cause } : {}),\n });\n }\n\n // Treat an untyped provider error as provider unavailability\n async function providerRetryKey(\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n submission: PaymentSubmission,\n ): Promise<string | undefined> {\n try {\n return provider.retryKey?.({ resource, submission });\n } catch (error) {\n const typed = isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'Payment provider is unavailable', {\n cause: error,\n });\n throw await rejected(flow, resource, provider, typed);\n }\n }\n\n // Write no new receipt, payment attempt or journal row. The outcome and events use\n // this request's transaction ID; the receipt and, when available, the event's\n // originalTransactionId identify the original purchase.\n async function redeliver(\n flow: Flow,\n resource: CommerceResource,\n provider: PaymentProvider,\n status: number,\n stored: StoredDelivery,\n pipelineStart: number,\n ): Promise<DeliveredOutcome> {\n const { request } = flow;\n const receipt = await reading(flow, resource, () => options.store.getReceipt(stored.receiptId));\n if (receipt?.payment === undefined) {\n throw await refusal(flow, resource, provider, 'unresolved');\n }\n const durationMs = Math.round(options.clock.monotonicMs() - pipelineStart);\n const original = receipt.transactionId;\n await safeEmit(\n buildEvent(flow, {\n type: 'resource.delivered',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs,\n data: {\n redelivered: true,\n ...(original !== undefined ? { originalTransactionId: original } : {}),\n },\n }),\n );\n return {\n kind: 'delivered',\n requestId: request.requestId,\n transactionId: flow.transactionId,\n resourceId: resource.id,\n backendStatus: status,\n body: stored.body,\n headers: stored.contentType !== undefined ? { 'content-type': stored.contentType } : {},\n payment: receipt.payment,\n receipt,\n durationMs,\n redelivered: true,\n };\n }\n\n return { open, claim, finishDelivered, finishFailed };\n}\n\n// Match required authorization by its original bytes: the purchase consumed\n// the mandate, so it cannot be verified again\nfunction authorizes(\n resource: CommerceResource,\n stored: StoredDelivery,\n ticket: RetryTicket,\n): boolean {\n if ((resource.authorization?.required.length ?? 0) === 0) return true;\n return (\n stored.authorizationDigest !== undefined &&\n stored.authorizationDigest === ticket.authorizationDigest\n );\n}\n\nfunction readStoredDelivery(value: unknown): StoredDelivery | undefined {\n if (!isRecord(value) || !Object.hasOwn(value, 'body')) return undefined;\n const { proofDigest, authorizationDigest, payer, contentType, body, receiptId } = value;\n if (typeof proofDigest !== 'string' || typeof receiptId !== 'string') return undefined;\n if (authorizationDigest !== undefined && typeof authorizationDigest !== 'string') {\n return undefined;\n }\n if (payer !== undefined && typeof payer !== 'string') return undefined;\n if (contentType !== undefined && typeof contentType !== 'string') return undefined;\n return {\n proofDigest,\n ...(authorizationDigest !== undefined ? { authorizationDigest } : {}),\n ...(payer !== undefined ? { payer } : {}),\n ...(contentType !== undefined ? { contentType } : {}),\n body,\n receiptId,\n };\n}\n","/**\n * The built-in outbound HTTP path to a merchant backend.\n *\n * - Global `fetch`, always bounded by `AbortSignal.timeout`.\n * - `redirect: 'manual'`: a 3xx response is a `BACKEND_ERROR`, never followed\n * (SSRF hardening).\n * - `{param}` segments in `handler.url` are filled from validated input and\n * URL-encoded; the rest is mapped as `BackendHandler.inputBindings`\n * describes (see `backend-request.ts`).\n */\nimport { type BackendHandler, DEFAULT_BACKEND_TIMEOUT_MS } from '../domain/resource';\nimport { CommerceError, isCommerceError } from '../errors';\nimport type { BackendExecutor, BackendRequest, BackendResponse } from '../interfaces/backend';\nimport { type Logger, NOOP_LOGGER } from '../interfaces/logger';\nimport { isRecord } from '../is-record';\nimport {\n buildBackendRequestParts,\n buildHeaders,\n checkQueryCollision,\n setHeader,\n stringifyPrimitive,\n} from './backend-request';\n\nconst MAX_BODY_SNIPPET_LENGTH = 512;\n\n// How a merchant recognizes a repeat of an operation. The de facto standard\n// name, and the one ACP requires inbound.\nconst IDEMPOTENCY_KEY_HEADER = 'idempotency-key';\n\n// The timeout bounds a response by time, not bytes; this stops a hostile or\n// broken backend from filling memory\nconst MAX_RESPONSE_BODY_BYTES = 1024 * 1024;\n\nexport interface HttpBackendExecutorOptions {\n /** Override for `fetch`, used in tests. Defaults to the global implementation */\n readonly fetchImpl?: typeof fetch;\n /** Receives a non-2xx backend body at debug level; it never reaches the client */\n readonly logger?: Logger;\n}\n\n/**\n * Merchant non-2xx response attached as the `BACKEND_ERROR` cause. Adapters\n * can inspect its body and headers; client errors omit the cause.\n */\nexport class BackendErrorResponse {\n constructor(\n readonly status: number,\n readonly body: unknown,\n /** Lowercase names, as `Headers` yields them */\n readonly headers: Readonly<Record<string, string>> = {},\n ) {}\n}\n\nexport class HttpBackendExecutor implements BackendExecutor {\n private readonly fetchImpl: typeof fetch;\n private readonly logger: Logger;\n\n constructor(options: HttpBackendExecutorOptions = {}) {\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.logger = options.logger ?? NOOP_LOGGER;\n }\n\n async call(handler: BackendHandler, request: BackendRequest): Promise<BackendResponse> {\n const timeoutMs = handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;\n const inputRecord = isRecord(request.input) ? request.input : {};\n\n const context = { requestId: request.requestId, resourceId: request.resourceId };\n // Throws INPUT_INVALID for every shape problem. The pipeline already ran it\n // before payment through validateBackendRequestShape(); this copy covers a\n // caller that bypasses the pipeline.\n const parts = buildBackendRequestParts(handler, inputRecord, context);\n\n let target: URL;\n try {\n target = new URL(parts.url);\n } catch (error) {\n throw new CommerceError('BACKEND_ERROR', 'Backend URL could not be constructed from input', {\n ...context,\n details: { reason: 'invalid-url' },\n cause: error,\n });\n }\n\n // Beyond the per-parameter check: the resolved path must stay under the\n // template's literal prefix (everything before the first `{`)\n const prefixPathname = literalPrefixPathname(handler);\n if (prefixPathname !== undefined && !target.pathname.startsWith(prefixPathname)) {\n throw new CommerceError(\n 'INPUT_INVALID',\n 'Path parameters resolved outside the configured backend path',\n context,\n );\n }\n\n const headers = buildHeaders(handler, context, request.backendHeaders);\n // Replaces a configured header of the same name, unlike content-type below:\n // a static key would make every request look like a retry of the first\n if (request.idempotencyKey !== undefined) {\n setHeader(headers, IDEMPOTENCY_KEY_HEADER, request.idempotencyKey, context);\n }\n let body: string | undefined;\n\n // searchParams.set() replaces an existing param, so a caller key named\n // like an operator's query param (`?apikey=SECRET` in handler.url) would\n // overwrite it. validateBackendRequestShape() runs the same check before\n // payment.\n checkQueryCollision(target, parts.query, context);\n for (const [key, value] of Object.entries(parts.query)) {\n target.searchParams.set(key, stringifyPrimitive(value));\n }\n if (parts.body !== undefined) {\n body = JSON.stringify(parts.body.value);\n // A configured Content-Type, such as `application/vnd.x+json`, wins\n if (!headers.has('content-type')) headers.set('content-type', 'application/json');\n }\n\n const started = performance.now();\n let response: Response;\n try {\n response = await this.fetchImpl(target, {\n method: handler.method,\n headers,\n ...(body !== undefined ? { body } : {}),\n redirect: 'manual',\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n const durationMs = Math.round(performance.now() - started);\n if (isAbortError(error)) {\n throw new CommerceError(\n 'BACKEND_TIMEOUT',\n `Backend request timed out after ${timeoutMs}ms`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { timeoutMs, durationMs },\n cause: error,\n },\n );\n }\n throw new CommerceError('BACKEND_ERROR', 'Backend request failed (transport error)', {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { durationMs },\n cause: error,\n });\n }\n const durationMs = Math.round(performance.now() - started);\n\n const isRedirect =\n response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400);\n if (isRedirect) {\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Backend responded with a redirect, which is not followed',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status, reason: 'redirect-not-followed' },\n },\n );\n }\n\n const responseHeaders = Object.fromEntries(response.headers);\n const contentType = response.headers.get('content-type') ?? '';\n let parsedBody: unknown;\n try {\n parsedBody = await parseBody(response, contentType);\n } catch (error) {\n const tooLarge = isCommerceError(error);\n throw new CommerceError(\n 'BACKEND_ERROR',\n tooLarge\n ? 'Backend response exceeded the maximum allowed size'\n : 'Backend response could not be read',\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: tooLarge\n ? { reason: 'response-too-large', maxBytes: MAX_RESPONSE_BODY_BYTES }\n : { reason: 'read-error' },\n cause: error,\n },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n // The status may reach the client, but the body is logged at debug level\n // only: a backend in verbose error mode emits stack traces, hostnames or\n // SQL fragments, and the caller may be anonymous\n this.logger.debug(\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n status: response.status,\n bodySnippet: truncateSnippet(parsedBody),\n },\n 'Backend responded with a non-2xx status',\n );\n throw new CommerceError('BACKEND_ERROR', `Backend responded with status ${response.status}`, {\n requestId: request.requestId,\n resourceId: request.resourceId,\n details: { status: response.status },\n cause: new BackendErrorResponse(response.status, parsedBody, responseHeaders),\n });\n }\n\n return {\n status: response.status,\n headers: responseHeaders,\n body: parsedBody,\n durationMs,\n };\n }\n}\n\n// `handler.url` never changes, so its literal prefix is parsed once per handler.\n// `null` records a prefix that is not a URL, as when a parameter sits in the\n// host (which config refuses); the containment check is then skipped.\nconst prefixPathnames = new WeakMap<BackendHandler, string | null>();\n\nfunction literalPrefixPathname(handler: BackendHandler): string | undefined {\n let cached = prefixPathnames.get(handler);\n if (cached === undefined) {\n try {\n cached = new URL(handler.url.split('{')[0] ?? handler.url).pathname;\n } catch {\n cached = null;\n }\n prefixPathnames.set(handler, cached);\n }\n return cached ?? undefined;\n}\n\nasync function readBodyCapped(response: Response, maxBytes: number): Promise<string> {\n if (!response.body) return '';\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n // The only CommerceError parseBody can throw, which is how its caller\n // tells an oversized body from a read failure\n throw new CommerceError('BACKEND_ERROR', `response body exceeded ${maxBytes} bytes`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nasync function parseBody(response: Response, contentType: string): Promise<unknown> {\n const text = await readBodyCapped(response, MAX_RESPONSE_BODY_BYTES);\n if (text.length === 0) return text;\n if (contentType.includes('json')) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction truncateSnippet(body: unknown): string {\n const text = typeof body === 'string' ? body : safeStringify(body);\n return text.length > MAX_BODY_SNIPPET_LENGTH\n ? `${text.slice(0, MAX_BODY_SNIPPET_LENGTH)}…`\n : text;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');\n}\n","// Verifies and reserves the authorization a resource requires, before its payment is reserved\nimport type { AuthorizationProvider, AuthorizationVerification } from '../../domain/authorization';\nimport type { AuthorizationMethodName } from '../../domain/common';\nimport type { PaymentRequirement } from '../../domain/payment';\nimport type { CanonicalRequest } from '../../domain/request';\nimport type { CommerceResource } from '../../domain/resource';\nimport { CommerceError, describeError, isCommerceError } from '../../errors';\nimport type { Flow } from '../journal';\nimport type { AuthorizationHold, PipelineContext } from './context';\n\n// The provider for each method a resource requires, in the resource's order.\n// Config refuses a method that is not enabled at load; it is checked again\n// because missing it here would serve the resource with no authorization.\nexport function resolveAuthorizationProviders(\n providers: readonly AuthorizationProvider[],\n resource: CommerceResource,\n requestId: string,\n): readonly AuthorizationProvider[] {\n const required = resource.authorization?.required ?? [];\n return required.map((method: AuthorizationMethodName) => {\n const found = providers.find((provider) => provider.name === method);\n if (!found) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" requires authorization method \"${method}\", which is not enabled`,\n { requestId, resourceId: resource.id },\n );\n }\n return found;\n });\n}\n\nexport type AuthorizeAndReserve = (\n flow: Flow,\n request: CanonicalRequest,\n resource: CommerceResource,\n providers: readonly AuthorizationProvider[],\n requirement: PaymentRequirement,\n input: unknown,\n) => Promise<AuthorizationHold | undefined>;\n\nexport function createAuthorizeAndReserve(ctx: PipelineContext): AuthorizeAndReserve {\n const { options, safeEmit, buildEvent } = ctx;\n\n // Verify and reserve what the resource requires, or undefined if it requires\n // none. Runs after payment verification, which has no side effect, so a bad\n // payment proof cannot burn a reservation.\n async function authorizeAndReserve(\n flow: Flow,\n request: CanonicalRequest,\n resource: CommerceResource,\n providers: readonly AuthorizationProvider[],\n requirement: PaymentRequirement,\n input: unknown,\n ): Promise<AuthorizationHold | undefined> {\n if (providers.length === 0) return undefined;\n\n const submission = request.authorization;\n const provider = providers.find((candidate) => candidate.name === submission?.method);\n // A request carries one proof, so a resource requiring two methods is\n // refused here rather than half-checked\n const unmet = providers.filter((candidate) => candidate !== provider).map((c) => c.name);\n\n if (submission === undefined || provider === undefined || unmet.length > 0) {\n await safeEmit(\n buildEvent(flow, {\n type: 'authorization.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n data: { reason: 'AUTHORIZATION_REQUIRED', methods: unmet },\n }),\n );\n throw new CommerceError(\n 'AUTHORIZATION_REQUIRED',\n `Resource \"${resource.id}\" requires authorization: ${unmet.join(', ')}`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { required: providers.map((candidate) => candidate.name), missing: unmet },\n },\n );\n }\n\n let verification: AuthorizationVerification;\n try {\n verification = await provider.verifyAndReserve({\n requestId: request.requestId,\n resourceId: resource.id,\n input,\n submission,\n requirement,\n });\n } catch (error) {\n // An untyped throw says nothing about whose fault it was. Unavailable is\n // honest and retryable; invalid would blame the buyer for our outage.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError(\n 'AUTHORIZATION_PROVIDER_UNAVAILABLE',\n 'Authorization provider is unavailable',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n },\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'authorization.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n data: { reason: mapped.code, method: provider.name },\n }),\n );\n throw mapped;\n }\n\n await safeEmit(\n buildEvent(flow, {\n type: 'authorization.verified',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n data: { method: verification.method, reference: verification.reference },\n }),\n );\n\n const context = { requestId: request.requestId, resourceId: resource.id };\n return {\n record: {\n method: verification.method,\n reference: verification.reference,\n ...(verification.metadata !== undefined ? { metadata: verification.metadata } : {}),\n },\n reservationId: verification.reservationId,\n async finalize(action) {\n try {\n await provider[action](verification.reservationId, context);\n return true;\n } catch (error) {\n // A failure leaves the reservation reserved, which is still\n // unspendable, so the caller's outcome stands\n options.logger.error(\n { err: describeError(error), requestId: request.requestId, action },\n 'Authorization finalization failed; the reservation stays reserved',\n );\n return false;\n }\n },\n };\n }\n\n return authorizeAndReserve;\n}\n","// What a refused or replayed payment answers with: the unused challenge, when one may be retried\nimport type { PaymentRequirement } from '../../domain/payment';\nimport { CommerceError } from '../../errors';\n\n// A refusal leaves this request's challenge unused. Return it with the\n// provider's reason so the client can retry without fetching another challenge\nexport function retryChallenge(\n requirement: PaymentRequirement,\n reason?: string,\n): { details?: Record<string, unknown> } {\n const envelope = requirement.challenge.envelope;\n if (envelope === undefined && reason === undefined) return {};\n return {\n details: {\n ...(envelope !== undefined ? { challenge: envelope } : {}),\n ...(reason !== undefined ? { reason } : {}),\n },\n };\n}\n\n// Attempt statuses the pipeline treats as finished when handling a replay. The\n// legacy `failed` is not one: it recorded any throw from settle(), so it may\n// hide a transfer, like `settlement-uncertain`.\nconst FINISHED_ATTEMPT_STATUSES: ReadonlySet<string> = new Set(['settled', 'rejected']);\n\nexport function isFinishedAttempt(status: unknown): boolean {\n return typeof status === 'string' && FINISHED_ATTEMPT_STATUSES.has(status);\n}\n\n// Include the paid offer's network for the rail's replay code. Finished\n// attempts get 402 with a fresh challenge; unfinished or unreadable attempts\n// keep 409 to avoid prompting a second payment.\nexport function replayError(error: CommerceError, requirement: PaymentRequirement): CommerceError {\n if (error.code !== 'PAYMENT_REPLAYED') return error;\n const finished = isFinishedAttempt(error.details?.['attemptStatus']);\n const network = requirement.network;\n if (!finished && network === undefined) return error;\n return new CommerceError('PAYMENT_REPLAYED', error.message, {\n ...(error.requestId !== undefined ? { requestId: error.requestId } : {}),\n ...(error.resourceId !== undefined ? { resourceId: error.resourceId } : {}),\n ...(finished ? { httpStatus: 402 } : {}),\n details: {\n ...error.details,\n ...(network !== undefined ? { network } : {}),\n ...(finished ? retryChallenge(requirement).details : {}),\n },\n });\n}\n","// The payment phase: challenge, offer selection, verification, and the authorization and replay reservations\n\nimport type { PaymentMethodName } from '../../domain/common';\nimport type { PaymentProvider, PaymentRequirement, PaymentResult } from '../../domain/payment';\nimport type { PaymentAttempt } from '../../domain/receipt';\nimport type {\n CanonicalRequest,\n DeliveredOutcome,\n PaymentRequiredOutcome,\n} from '../../domain/request';\nimport type { CommerceResource, Pricing } from '../../domain/resource';\nimport { CommerceError, isCommerceError, toCommerceError } from '../../errors';\nimport { type Flow, inputDigest, newTransaction } from '../journal';\nimport { paidOperationKey } from '../merchant-key';\nimport { REUSE_REJECTED_AUTHORIZATION_METADATA_KEY } from '../settlement-order';\nimport { type AuthorizeAndReserve, resolveAuthorizationProviders } from './authorization';\nimport { isFinishedAttempt, replayError, retryChallenge } from './challenge';\nimport type { PipelineContext, SettleArgs } from './context';\nimport { assertRetrySupport, type RetryGate } from './retry';\n\n/** A verified payment whose authorization and replay identity are reserved */\nexport interface AdmittedPayment {\n readonly kind: 'admitted';\n readonly settleArgs: SettleArgs;\n}\n\nexport type AdmitPayment = (\n flow: Flow,\n request: CanonicalRequest,\n resource: CommerceResource,\n pricing: Extract<Pricing, { type: 'fixed' }>,\n validInput: unknown,\n pipelineStart: number,\n) => Promise<PaymentRequiredOutcome | DeliveredOutcome | AdmittedPayment>;\n\n/**\n * Build payment admission. Return a challenge, a stored retry response or\n * verified claims for delivery; failures throw.\n */\nexport function createPaymentAdmission(\n ctx: PipelineContext,\n authorizeAndReserve: AuthorizeAndReserve,\n retryGate: RetryGate,\n): AdmitPayment {\n const { options, safeEmit, buildEvent } = ctx;\n\n return async function admitPayment(flow, request, resource, pricing, validInput, pipelineStart) {\n // Check retry dependencies before provider calls and before upfront settlement can charge\n const support = assertRetrySupport(\n resource,\n options.store,\n options.deployment,\n request.requestId,\n );\n const provider = pickProvider(options.paymentProviders, resource.paymentMethods);\n if (!provider) {\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n `No enabled payment provider for resource \"${resource.id}\"`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { paymentMethods: resource.paymentMethods },\n },\n );\n }\n\n // Resolve authorization before building the challenge, so the 402 lists required\n // methods and unsupported methods fail before payment starts\n const authProviders = resolveAuthorizationProviders(\n options.authorizationProviders ?? [],\n resource,\n request.requestId,\n );\n\n const retry = await retryGate.open(\n flow,\n resource,\n provider,\n validInput,\n support,\n pipelineStart,\n );\n if (retry?.kind === 'delivered') return retry;\n\n let requirement: PaymentRequirement;\n try {\n requirement = await provider.createRequirement({\n requestId: request.requestId,\n resource,\n amount: pricing.amount,\n currency: pricing.currency,\n requestedAt: options.clock.nowIso(),\n input: validInput,\n protocol: request.protocol,\n // Transport facts a rail may bind into its challenge, such as a body digest\n ...(request.metadata !== undefined ? { metadata: request.metadata } : {}),\n });\n } catch (error) {\n throw isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_PROVIDER_UNAVAILABLE', 'Payment provider is unavailable', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n });\n }\n\n if (!request.payment) {\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.required',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n }),\n );\n return {\n kind: 'payment-required',\n requestId: request.requestId,\n transactionId: flow.transactionId,\n resourceId: resource.id,\n requirement,\n ...(authProviders.length > 0\n ? { authorization: authProviders.map((p) => p.requirement) }\n : {}),\n };\n }\n\n const payment = request.payment;\n\n let verification: PaymentResult;\n try {\n // Later steps, including authorization and settlement order, use the\n // selected requirement with its full retry challenge\n if (provider.selectRequirement) {\n requirement = await provider.selectRequirement({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n }\n verification = await provider.verify({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n });\n } catch (error) {\n // A typed CommerceError is rethrown as is, keeping its code and its\n // possibly retryable status. Only an untyped throw is mapped, with a\n // fixed client-facing message.\n const mapped = isCommerceError(error)\n ? error\n : new CommerceError('PAYMENT_INVALID', 'Payment verification failed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n ...retryChallenge(requirement),\n });\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw mapped;\n }\n\n if (verification.status !== 'verified') {\n const refusal = await refusalFor(verification, requirement, request, resource);\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data:\n refusal.code !== 'PAYMENT_INVALID'\n ? { reason: refusal.code }\n : verification.rejectionReason\n ? { reason: verification.rejectionReason }\n : {},\n }),\n );\n throw refusal;\n }\n\n if (!verification.replayKey) {\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'missing-replay-key' },\n }),\n );\n throw new CommerceError('PAYMENT_INVALID', 'Payment provider did not return a replay key', {\n requestId: request.requestId,\n resourceId: resource.id,\n });\n }\n const replayKey = verification.replayKey;\n // Reuse one input digest for the retry claim, journal and merchant key\n const digest = retry?.fingerprint ?? inputDigest(validInput);\n\n // Claim the retry key before authorization holds or replay reservations, so a losing\n // request has no new reservation to release\n if (retry !== undefined) {\n const stored = await retryGate.claim(\n flow,\n resource,\n provider,\n retry,\n verification,\n pipelineStart,\n );\n if (stored !== undefined) return stored;\n }\n\n try {\n const hold = await authorizeAndReserve(\n flow,\n request,\n resource,\n authProviders,\n requirement,\n validInput,\n );\n\n try {\n const attempt = await options.store.reservePaymentAttempt({\n requestId: request.requestId,\n resourceId: resource.id,\n provider: provider.name,\n replayKey,\n amount: verification.amount,\n currency: verification.currency,\n ...(verification.payer !== undefined ? { payer: verification.payer } : {}),\n ...(verification.payee !== undefined ? { payee: verification.payee } : {}),\n ...(requirement.metadata?.[REUSE_REJECTED_AUTHORIZATION_METADATA_KEY] === true\n ? { reclaimRejected: true }\n : {}),\n transaction: newTransaction(\n flow,\n resource,\n requirement,\n verification,\n digest,\n hold !== undefined ? { ...hold.record, reservationId: hold.reservationId } : undefined,\n ),\n });\n // Require a matching transaction ID and recordTransactionStep before enabling\n // journaling; legacy stores can then ignore the transaction data\n flow.journaled =\n attempt.transactionId === flow.transactionId &&\n options.store.recordTransactionStep !== undefined;\n } catch (error) {\n // Preserve CommerceError codes, including PAYMENT_REPLAYED; map untyped\n // storage failures to STORAGE_ERROR\n const mapped = toCommerceError(\n error,\n 'STORAGE_ERROR',\n 'Payment attempt could not be recorded',\n );\n await hold?.finalize('release');\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: mapped.code },\n }),\n );\n throw replayError(mapped, requirement);\n }\n\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.verified',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n const merchantKey =\n support !== undefined && resource.idempotency?.merchantKey === true\n ? paidOperationKey({\n deployment: support.deployment,\n resourceId: resource.id,\n replayKey,\n inputDigest: digest,\n ...(retry !== undefined ? { clientKey: retry.clientKey } : {}),\n ...(verification.payer !== undefined ? { payer: verification.payer } : {}),\n })\n : undefined;\n\n return {\n kind: 'admitted',\n settleArgs: {\n flow,\n request,\n resource,\n provider,\n requirement,\n payment,\n verification,\n replayKey,\n hold,\n ...(merchantKey !== undefined ? { merchantKey } : {}),\n ...(retry !== undefined ? { retry } : {}),\n },\n };\n } catch (error) {\n if (retry !== undefined) await retryGate.finishFailed(flow, retry);\n throw error;\n }\n };\n\n // A spent authorization can fail verification before reaching the replay\n // reservation. If its key belongs to an unfinished attempt, return 409\n // without a challenge to avoid prompting another payment. A store without\n // the lookup keeps the 402 response.\n async function refusalFor(\n verification: PaymentResult,\n requirement: PaymentRequirement,\n request: CanonicalRequest,\n resource: CommerceResource,\n ): Promise<CommerceError> {\n const ids = { requestId: request.requestId, resourceId: resource.id };\n if (verification.replayKey !== undefined) {\n let attempt: PaymentAttempt | undefined;\n try {\n attempt = await options.store.findPaymentAttemptByReplayKey?.(verification.replayKey);\n } catch (error) {\n return new CommerceError('STORAGE_ERROR', 'Payment attempt could not be read', {\n ...ids,\n cause: error,\n });\n }\n if (attempt !== undefined && !isFinishedAttempt(attempt.status)) {\n return replayError(\n new CommerceError('PAYMENT_REPLAYED', 'Payment authorization has already been used', {\n ...ids,\n details: { attemptStatus: attempt.status },\n }),\n requirement,\n );\n }\n }\n return new CommerceError(\n 'PAYMENT_INVALID',\n verification.rejectionReason ?? 'Payment was rejected',\n {\n ...ids,\n ...retryChallenge(requirement, verification.rejectionReason),\n },\n );\n }\n}\n\nfunction pickProvider(\n providers: readonly PaymentProvider[],\n methods: readonly PaymentMethodName[],\n): PaymentProvider | undefined {\n for (const method of methods) {\n const found = providers.find((provider) => provider.name === method);\n if (found) return found;\n }\n return undefined;\n}\n","// What the pipeline's stages share: its options, and event and persistence writes that never fail a flow\nimport type { AuthorizationProvider, AuthorizationRecord } from '../../domain/authorization';\nimport type { CommerceEvent, EventSink } from '../../domain/event';\nimport type {\n PaymentProvider,\n PaymentRequirement,\n PaymentResult,\n PaymentSubmission,\n} from '../../domain/payment';\nimport type { CanonicalRequest } from '../../domain/request';\nimport type { CommerceResource, ResourceRegistry } from '../../domain/resource';\nimport type { AuthorizationHoldState, PersistenceFailure } from '../../domain/transaction';\nimport { describeError } from '../../errors';\nimport type { BackendExecutor } from '../../interfaces/backend';\nimport type { Logger } from '../../interfaces/logger';\nimport type { Clock, IdGenerator } from '../../interfaces/runtime';\nimport type { ReceiptStore, TransactionStep } from '../../interfaces/store';\nimport type { Flow } from '../journal';\nimport type { RetryTicket } from './retry';\n\nexport interface CreateExecutionPipelineOptions {\n readonly resources: ResourceRegistry;\n readonly paymentProviders: readonly PaymentProvider[];\n /** Defaults to none */\n readonly authorizationProviders?: readonly AuthorizationProvider[];\n readonly store: ReceiptStore;\n readonly backend: BackendExecutor;\n readonly events: EventSink;\n readonly logger: Logger;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n /**\n * Gateway public base URL (`merchant.publicBaseUrl`) used in merchant keys\n * and retry scopes. Required when `merchantKey` is true or `redelivery` is configured.\n */\n readonly deployment?: string;\n}\n\nexport type HoldAction = 'consume' | 'release' | 'markUncertain';\n\n/**\n * An authorization reservation and its receipt summary. `finalize` returns\n * false on provider errors; journal state changes only after it returns true.\n */\nexport interface AuthorizationHold {\n readonly record: AuthorizationRecord;\n /** Handle used to consume, release or mark the reservation uncertain */\n readonly reservationId: string;\n finalize(action: HoldAction): Promise<boolean>;\n}\n\n/** Journal step data before the pipeline adds its transaction ID and timestamp */\nexport type StepBody = TransactionStep extends infer S\n ? S extends TransactionStep\n ? Omit<S, 'transactionId' | 'at'>\n : never\n : never;\n\nconst HOLD_STATES: Readonly<Record<HoldAction, AuthorizationHoldState>> = {\n consume: 'consumed',\n release: 'released',\n markUncertain: 'uncertain',\n};\n\n/** A verified, reserved payment and everything its settlement needs */\nexport interface SettleArgs {\n readonly flow: Flow;\n readonly request: CanonicalRequest;\n readonly resource: CommerceResource;\n readonly provider: PaymentProvider;\n readonly requirement: PaymentRequirement;\n readonly payment: PaymentSubmission;\n readonly verification: PaymentResult;\n readonly replayKey: string;\n readonly hold: AuthorizationHold | undefined;\n /** Derived backend key for a resource with `idempotency.merchantKey` enabled */\n readonly merchantKey?: string;\n /** Retry claim to finalize after delivery or failure */\n readonly retry?: RetryTicket;\n}\n\nexport interface PipelineContext {\n readonly options: CreateExecutionPipelineOptions;\n /** Emits an event; a failing sink is logged, never thrown */\n readonly safeEmit: (event: CommerceEvent) => Promise<void>;\n /**\n * Run a store write, returning true on success and false on failure.\n * Write errors are logged at error level; a supplied `failure` label is\n * recorded once in `flow.persistenceFailures`.\n */\n readonly safePersist: (\n flow: Flow,\n op: () => Promise<void>,\n label: string,\n failure?: PersistenceFailure,\n ) => Promise<boolean>;\n /** Record a journal step when enabled, logging store errors instead of aborting */\n readonly recordStep: (flow: Flow, step: StepBody) => Promise<void>;\n /** Apply a hold action and attempt its journal step only after provider success */\n readonly finalizeHold: (\n flow: Flow,\n hold: AuthorizationHold | undefined,\n action: HoldAction,\n ) => Promise<void>;\n readonly buildEvent: (\n flow: Flow,\n partial: Omit<CommerceEvent, 'id' | 'at' | 'requestId' | 'transactionId'>,\n ) => CommerceEvent;\n}\n\nexport function createPipelineContext(options: CreateExecutionPipelineOptions): PipelineContext {\n async function safeEmit(event: CommerceEvent): Promise<void> {\n try {\n await options.events.emit(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Event sink failed; commerce flow continues',\n );\n }\n }\n\n async function safePersist(\n flow: Flow,\n op: () => Promise<void>,\n label: string,\n failure?: PersistenceFailure,\n ): Promise<boolean> {\n try {\n await op();\n return true;\n } catch (error) {\n options.logger.error(\n {\n err: describeError(error),\n requestId: flow.request.requestId,\n transactionId: flow.transactionId,\n },\n `Persistence failed: ${label}`,\n );\n if (failure !== undefined && !flow.persistenceFailures.includes(failure)) {\n flow.persistenceFailures.push(failure);\n }\n return false;\n }\n }\n\n async function recordStep(flow: Flow, step: StepBody): Promise<void> {\n const record = options.store.recordTransactionStep;\n if (!flow.journaled || record === undefined) return;\n const full = {\n ...step,\n transactionId: flow.transactionId,\n at: options.clock.nowIso(),\n } as TransactionStep;\n await safePersist(\n flow,\n () => record.call(options.store, full),\n `recordTransactionStep(${step.kind})`,\n 'journal',\n );\n }\n\n async function finalizeHold(\n flow: Flow,\n hold: AuthorizationHold | undefined,\n action: HoldAction,\n ): Promise<void> {\n if (hold !== undefined && (await hold.finalize(action))) {\n await recordStep(flow, { kind: 'hold', hold: HOLD_STATES[action] });\n }\n }\n\n function buildEvent(\n flow: Flow,\n partial: Omit<CommerceEvent, 'id' | 'at' | 'requestId' | 'transactionId'>,\n ): CommerceEvent {\n return {\n id: options.ids.next('evt'),\n at: options.clock.nowIso(),\n requestId: flow.request.requestId,\n transactionId: flow.transactionId,\n ...partial,\n };\n }\n\n return { options, safeEmit, safePersist, recordStep, finalizeHold, buildEvent };\n}\n","// Settles a verified, reserved payment, or records that the backend failed before it could\nimport type { PaymentRequirement, PaymentResult } from '../../domain/payment';\nimport { CommerceError, isCommerceError } from '../../errors';\nimport { failuresOf } from '../journal';\nimport { retryChallenge } from './challenge';\nimport type { PipelineContext, SettleArgs } from './context';\n\nexport interface Settlement {\n /** Settles and finalizes the authorization; a refusal or unknown outcome throws */\n readonly settle: (args: SettleArgs) => Promise<PaymentResult>;\n /** Records a backend failure before settlement and releases the authorization */\n readonly abandonSettlement: (args: SettleArgs, backendErrorCode: string) => Promise<void>;\n}\n\nexport function createSettlement(ctx: PipelineContext): Settlement {\n const { options, safeEmit, safePersist, recordStep, finalizeHold, buildEvent } = ctx;\n\n // Settle a verified, reserved payment and finalize its authorization.\n // Rejected or uncertain settlement throws before any response is delivered.\n async function settle(args: SettleArgs): Promise<PaymentResult> {\n const {\n flow,\n request,\n resource,\n provider,\n requirement,\n payment,\n verification,\n replayKey,\n hold,\n } = args;\n await recordStep(flow, { kind: 'settling' });\n flow.chargeRisk = true;\n let settlement: PaymentResult;\n try {\n settlement = await provider.settle({\n requestId: request.requestId,\n resource,\n requirement,\n submission: payment,\n verification,\n });\n } catch (error) {\n // Confirmed non-submission leaves the authorization spendable. Release\n // it for retry and report the provider failure.\n const notSubmitted = notSubmittedReason(error);\n if (notSubmitted !== undefined) {\n flow.chargeRisk = false;\n await finalizeHold(flow, hold, 'release');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n rejectionReason: notSubmitted,\n }),\n 'updatePaymentAttempt(not-submitted)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: {\n reason: 'settlement-not-submitted',\n providerReason: notSubmitted,\n ...failuresOf(flow),\n },\n }),\n );\n throw new CommerceError(\n 'PAYMENT_PROVIDER_UNAVAILABLE',\n 'The payment provider could not settle the payment; nothing was charged',\n { requestId: request.requestId, resourceId: resource.id, cause: error },\n );\n }\n // A throw gives no settlement verdict. The facilitator may have\n // broadcast before losing its response, even without a transaction\n // hash. Keep the authorization uncertain so it cannot be spent again.\n const txHash = settlementTxHash(error);\n await finalizeHold(flow, hold, 'markUncertain');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settlement-uncertain',\n ...(txHash !== undefined ? { externalReference: txHash } : {}),\n ...(error instanceof Error ? { rejectionReason: error.message } : {}),\n }),\n 'updatePaymentAttempt(settlement-uncertain)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: {\n reason: 'settlement-uncertain',\n ...(txHash !== undefined ? { transactionHash: txHash } : {}),\n ...failuresOf(flow),\n },\n }),\n );\n // The replay key remains reserved, so report an uncertain, non-retryable\n // outcome. Expose only the transaction hash from the underlying error.\n throw new CommerceError('PAYMENT_SETTLEMENT_FAILED', 'Settlement could not be confirmed', {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: error,\n details: {\n settlementUncertain: true,\n ...(txHash !== undefined ? { transactionHash: txHash } : {}),\n ...settlementParties(requirement, verification),\n },\n });\n }\n\n if (settlement.status !== 'settled') {\n flow.chargeRisk = false;\n await finalizeHold(flow, hold, 'release');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n ...(settlement.rejectionReason !== undefined\n ? { rejectionReason: settlement.rejectionReason }\n : {}),\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(rejected)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: {\n ...(settlement.rejectionReason ? { reason: settlement.rejectionReason } : {}),\n ...failuresOf(flow),\n },\n }),\n );\n // A returned rejection confirms no settlement. Both rails return 402.\n const rejectionDetails = retryChallenge(requirement, settlement.rejectionReason).details;\n throw new CommerceError(\n 'PAYMENT_SETTLEMENT_FAILED',\n settlement.rejectionReason ?? 'Settlement was rejected',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n httpStatus: 402,\n details: {\n ...rejectionDetails,\n ...settlementParties(requirement, settlement, verification),\n },\n },\n );\n }\n\n await finalizeHold(flow, hold, 'consume');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'settled',\n ...(settlement.externalReference !== undefined\n ? { externalReference: settlement.externalReference }\n : {}),\n }),\n 'updatePaymentAttempt(settled)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.settled',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'ok',\n }),\n );\n\n return settlement;\n }\n\n // Record the pre-settlement backend failure and release the authorization\n // hold. Rails with reuse metadata can reserve the unspent replay key again,\n // as after any rejection.\n async function abandonSettlement(args: SettleArgs, backendErrorCode: string): Promise<void> {\n const { flow, request, resource, provider, replayKey, hold } = args;\n await finalizeHold(flow, hold, 'release');\n await safePersist(\n flow,\n () =>\n options.store.updatePaymentAttempt({\n replayKey,\n status: 'rejected',\n rejectionReason: 'backend_failed',\n }),\n 'updatePaymentAttempt(backend-failed)',\n 'payment-attempt',\n );\n await safeEmit(\n buildEvent(flow, {\n type: 'payment.rejected',\n resourceId: resource.id,\n adapter: request.protocol,\n paymentProvider: provider.name,\n status: 'error',\n data: { reason: 'backend-failed', backendErrorCode, ...failuresOf(flow) },\n }),\n );\n }\n\n return { settle, abandonSettlement };\n}\n\n// The reason a provider gave when it threw before submitting anything\nfunction notSubmittedReason(error: unknown): string | undefined {\n if (!isCommerceError(error) || error.details?.['settlementNotSubmitted'] !== true) {\n return undefined;\n }\n const reason = error.details['reason'];\n return typeof reason === 'string' ? reason : 'settlement_not_submitted';\n}\n\n// The broadcast transaction hash a provider attached to a settlement throw,\n// when it knows one\nfunction settlementTxHash(error: unknown): string | undefined {\n const hash = isCommerceError(error) ? error.details?.['transactionHash'] : undefined;\n return typeof hash === 'string' ? hash : undefined;\n}\n\n// Prefer the network and payer reported by settlement or verification, then\n// fall back to the requirement's network\nfunction settlementParties(\n requirement: PaymentRequirement,\n ...results: readonly PaymentResult[]\n): { network?: string; payer?: string } {\n const network = results.find((r) => r.network !== undefined)?.network ?? requirement.network;\n const payer = results.find((r) => r.payer !== undefined)?.payer;\n return {\n ...(network !== undefined ? { network } : {}),\n ...(payer !== undefined ? { payer } : {}),\n };\n}\n","/**\n * The single execution path every protocol adapter converges on. The order is a\n * security boundary; do not reorder:\n *\n * 1. resolve resource (RESOURCE_NOT_FOUND)\n * 2. strip reserved input fields, validate input and the backend request shape\n * (INPUT_INVALID, or BACKEND_ERROR for an illegal configured header)\n * 3. resolve price\n * 4. free: straight to the backend\n * 5. paid: validate retry support, pick provider and resolve authorization\n * providers, then check retry state for an exact proof resend. Otherwise\n * createRequirement and return a challenge for a missing proof, or select\n * the offer and verify the proof. Claim the retry key, which may also return\n * a stored response, before reserving authorization and replay identities\n * 6. settle before calling the backend, or call the backend first and settle\n * only if it succeeds. Finalize authorization according to the outcome\n * (BACKEND_TIMEOUT / BACKEND_ERROR)\n * 7. persist receipt, finish the retry claim, emit events, return outcome\n */\n\nimport type { AuthorizationRecord } from '../../domain/authorization';\nimport type { PaymentResult } from '../../domain/payment';\nimport type { CommerceReceipt } from '../../domain/receipt';\nimport type { CanonicalRequest, ExecutionOutcome, ExecutionPipeline } from '../../domain/request';\nimport { type CommerceResource, DEFAULT_BACKEND_TIMEOUT_MS } from '../../domain/resource';\nimport { RESERVED_INPUT_FIELDS } from '../../domain/wire';\nimport { CommerceError, toCommerceError } from '../../errors';\nimport type { BackendResponse } from '../../interfaces/backend';\nimport { isRecord } from '../../is-record';\nimport { validateBackendRequestShape } from '../backend-request';\nimport { createFlow, type Flow, failuresOf } from '../journal';\nimport { SETTLE_AFTER_BACKEND_METADATA_KEY } from '../settlement-order';\nimport { compileJsonSchema, type Validator } from '../validation';\nimport { createPaymentAdmission } from './admission';\nimport { createAuthorizeAndReserve } from './authorization';\nimport {\n type CreateExecutionPipelineOptions,\n createPipelineContext,\n type SettleArgs,\n} from './context';\nimport { createRetryGate } from './retry';\nimport { createSettlement } from './settlement';\n\nexport type { CreateExecutionPipelineOptions } from './context';\n\nexport function createExecutionPipeline(\n options: CreateExecutionPipelineOptions,\n): ExecutionPipeline {\n const validators = new Map<string, Validator>();\n\n function getValidator(resource: CommerceResource): Validator {\n const cached = validators.get(resource.id);\n if (cached) return cached;\n const compiled = compileJsonSchema(resource.inputSchema);\n validators.set(resource.id, compiled);\n return compiled;\n }\n\n const ctx = createPipelineContext(options);\n const { safeEmit, safePersist, recordStep, buildEvent } = ctx;\n const { settle, abandonSettlement } = createSettlement(ctx);\n const retryGate = createRetryGate(ctx);\n const admitPayment = createPaymentAdmission(ctx, createAuthorizeAndReserve(ctx), retryGate);\n\n async function execute(request: CanonicalRequest): Promise<ExecutionOutcome> {\n const pipelineStart = options.clock.monotonicMs();\n\n // 1. resolve resource\n const resource = options.resources.get(request.resourceId);\n // Same code and message as an unknown id: a caller on a protocol the\n // resource is not exposed via must not learn that it exists\n if (!resource?.exposedVia.includes(request.protocol)) {\n throw new CommerceError(\n 'RESOURCE_NOT_FOUND',\n `Resource \"${request.resourceId}\" was not found`,\n {\n requestId: request.requestId,\n resourceId: request.resourceId,\n },\n );\n }\n\n // Allocate one ID per resolved execution for events, returned outcomes and\n // receipts. Only paid executions that reach replay reservation can open a\n // journal row.\n const flow = createFlow(request, options.ids.next('txn'));\n\n await safeEmit(\n buildEvent(flow, {\n type: 'resource.requested',\n resourceId: resource.id,\n adapter: request.protocol,\n }),\n );\n\n // 2. strip reserved gateway fields, then validate input\n const strippedInput = stripReservedFields(request.input);\n const validation = getValidator(resource)(strippedInput);\n if (!validation.valid) {\n throw new CommerceError(\n 'INPUT_INVALID',\n `Input for resource \"${resource.id}\" failed validation`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n details: { errors: validation.errors },\n },\n );\n }\n const validInput = validation.value;\n\n // Before pricing, so a request the backend cannot receive fails before\n // payment (see validateBackendRequestShape)\n validateBackendRequestShape(\n resource.handler,\n validInput,\n { requestId: request.requestId, resourceId: resource.id },\n request.backendHeaders,\n );\n\n // 3. resolve price\n if (resource.pricing.type === 'dynamic') {\n // Config validation rejects this at load; this is defense in depth\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" uses unsupported dynamic pricing`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n // Authorization gates settlement, so on a free resource nothing would read\n // the proof. Config refuses this at load; this is defense in depth.\n if (resource.pricing.type !== 'fixed' && (resource.authorization?.required.length ?? 0) > 0) {\n throw new CommerceError(\n 'CONFIG_INVALID',\n `Resource \"${resource.id}\" requires authorization but is not a paid resource`,\n {\n requestId: request.requestId,\n resourceId: resource.id,\n },\n );\n }\n\n let settleArgs: SettleArgs | undefined;\n if (resource.pricing.type === 'fixed') {\n const admission = await admitPayment(\n flow,\n request,\n resource,\n resource.pricing,\n validInput,\n pipelineStart,\n );\n if (admission.kind !== 'admitted') return admission;\n settleArgs = admission.settleArgs;\n }\n\n try {\n return await settleAndDeliver(flow, resource, validInput, settleArgs, pipelineStart);\n } catch (error) {\n if (settleArgs?.retry !== undefined) await retryGate.finishFailed(flow, settleArgs.retry);\n throw error;\n } finally {\n // Attempt the final journal step after settleAndDeliver returns or throws.\n // A failure is logged after the outcome and event snapshots are built, so\n // it cannot appear in those snapshots.\n await recordStep(flow, { kind: 'completed', ...failuresOf(flow) });\n }\n }\n\n async function settleAndDeliver(\n flow: Flow,\n resource: CommerceResource,\n validInput: unknown,\n settleArgs: SettleArgs | undefined,\n pipelineStart: number,\n ): Promise<ExecutionOutcome> {\n const { request } = flow;\n const authorization: AuthorizationRecord | undefined = settleArgs?.hold?.record;\n let paymentResult: PaymentResult | undefined;\n let deferredSettlement: SettleArgs | undefined;\n if (settleArgs !== undefined) {\n if (settleArgs.requirement.metadata?.[SETTLE_AFTER_BACKEND_METADATA_KEY] === true) {\n deferredSettlement = settleArgs;\n } else {\n paymentResult = await settle(settleArgs);\n }\n }\n\n // 6. call backend\n await recordStep(flow, {\n kind: 'backend-dispatched',\n deadlineAt: backendDeadline(options.clock.now(), resource),\n });\n const backendStart = options.clock.monotonicMs();\n const idempotencyKey = request.idempotencyKey ?? settleArgs?.merchantKey;\n let backendResponse: BackendResponse;\n try {\n backendResponse = await options.backend.call(resource.handler, {\n requestId: request.requestId,\n resourceId: resource.id,\n input: validInput,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(request.backendHeaders !== undefined ? { backendHeaders: request.backendHeaders } : {}),\n });\n } catch (error) {\n const commerceError = toCommerceError(error, 'BACKEND_ERROR', 'Backend call failed');\n await recordStep(flow, {\n kind: 'backend-result',\n status: backendErrorStatus(commerceError),\n errorCode: commerceError.code,\n });\n const backendFailed = (data: Record<string, unknown> = {}) =>\n safeEmit(\n buildEvent(flow, {\n type: 'backend.failed',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'error',\n durationMs: Math.round(options.clock.monotonicMs() - backendStart),\n data: { code: commerceError.code, ...data },\n }),\n );\n\n if (deferredSettlement !== undefined) {\n await backendFailed();\n await abandonSettlement(deferredSettlement, commerceError.code);\n throw commerceError;\n }\n\n if (paymentResult !== undefined) {\n // Payment settled before the backend failed. Include its details and\n // any settlement reference in the buyer's error. Attempt to save the\n // merchant's undelivered receipt before backend.failed so that event\n // can report a failed save.\n const failedReceipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendErrorStatus(commerceError),\n protocol: request.protocol,\n payment: paymentResult,\n ...(authorization !== undefined ? { authorization } : {}),\n metadata: { delivered: false, backendErrorCode: commerceError.code },\n transactionId: flow.transactionId,\n };\n await saveReceipt(flow, failedReceipt, 'saveReceipt(backend-failed-after-settlement)');\n await backendFailed(failuresOf(flow));\n\n throw new CommerceError(\n 'BACKEND_ERROR',\n 'Payment settled but the backend call failed; the payment was not refunded automatically',\n {\n requestId: request.requestId,\n resourceId: resource.id,\n cause: commerceError,\n details: {\n payment: {\n status: paymentResult.status,\n provider: paymentResult.provider,\n amount: paymentResult.amount,\n currency: paymentResult.currency,\n ...(paymentResult.network !== undefined ? { network: paymentResult.network } : {}),\n ...(paymentResult.externalReference !== undefined\n ? { externalReference: paymentResult.externalReference }\n : {}),\n ...(paymentResult.payer !== undefined ? { payer: paymentResult.payer } : {}),\n ...(typeof paymentResult.metadata?.['amountBaseUnits'] === 'string'\n ? { amountBaseUnits: paymentResult.metadata['amountBaseUnits'] }\n : {}),\n ...(typeof paymentResult.metadata?.['receipt'] === 'string'\n ? { receipt: paymentResult.metadata['receipt'] }\n : {}),\n },\n },\n },\n );\n }\n\n await backendFailed();\n throw commerceError;\n }\n await recordStep(flow, { kind: 'backend-result', status: backendResponse.status });\n\n await safeEmit(\n buildEvent(flow, {\n type: 'backend.called',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: backendResponse.durationMs,\n data: { status: backendResponse.status },\n }),\n );\n\n // Hold the backend response until settlement succeeds. A refusal or\n // uncertain outcome throws before delivery.\n if (deferredSettlement !== undefined) {\n paymentResult = await settle(deferredSettlement);\n }\n\n // 7. persist receipt, emit final event, return outcome\n const receipt: CommerceReceipt = {\n id: options.ids.next('receipt'),\n requestId: request.requestId,\n resourceId: resource.id,\n deliveredAt: options.clock.nowIso(),\n backendStatus: backendResponse.status,\n durationMs: backendResponse.durationMs,\n protocol: request.protocol,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n ...(authorization !== undefined ? { authorization } : {}),\n transactionId: flow.transactionId,\n };\n\n await saveReceipt(flow, receipt, 'saveReceipt');\n if (settleArgs?.retry !== undefined) {\n await retryGate.finishDelivered(\n flow,\n settleArgs.retry,\n settleArgs.verification,\n backendResponse,\n receipt,\n );\n }\n\n const totalDurationMs = Math.round(options.clock.monotonicMs() - pipelineStart);\n const failures = failuresOf(flow);\n\n await safeEmit(\n buildEvent(flow, {\n type: 'resource.delivered',\n resourceId: resource.id,\n adapter: request.protocol,\n status: 'ok',\n durationMs: totalDurationMs,\n ...(failures.persistenceFailures !== undefined ? { data: failures } : {}),\n }),\n );\n\n return {\n kind: 'delivered',\n requestId: request.requestId,\n transactionId: flow.transactionId,\n resourceId: resource.id,\n backendStatus: backendResponse.status,\n body: backendResponse.body,\n headers: backendResponse.headers,\n ...(paymentResult !== undefined ? { payment: paymentResult } : {}),\n receipt,\n durationMs: totalDurationMs,\n ...failures,\n };\n }\n\n async function saveReceipt(flow: Flow, receipt: CommerceReceipt, label: string): Promise<void> {\n if (await safePersist(flow, () => options.store.saveReceipt(receipt), label, 'receipt')) {\n await recordStep(flow, { kind: 'receipt', receiptId: receipt.id });\n }\n }\n\n return { execute };\n}\n\n// Add a scheduling margin to the backend timeout when setting the journal's\n// waiting deadline; a missing result before then may still be in progress\nconst BACKEND_DEADLINE_MARGIN_MS = 5_000;\n\nfunction backendDeadline(dispatchedAt: Date, resource: CommerceResource): string {\n const timeoutMs = resource.handler.timeoutMs ?? DEFAULT_BACKEND_TIMEOUT_MS;\n return new Date(dispatchedAt.getTime() + timeoutMs + BACKEND_DEADLINE_MARGIN_MS).toISOString();\n}\n\n// The status the backend returned, which backend-http.ts puts on\n// `details.status` for a non-2xx or redirect response. 0 means no status is\n// known, as after a timeout, a transport failure or an unreadable or oversized\n// body.\nfunction backendErrorStatus(error: CommerceError): number {\n const status = error.details?.['status'];\n return typeof status === 'number' ? status : 0;\n}\n\nconst RESERVED_INPUT_KEYS: readonly string[] = [...RESERVED_INPUT_FIELDS, '__proto__'];\n\nfunction stripReservedFields(input: unknown): unknown {\n if (!isRecord(input)) return input;\n // Object.hasOwn, not `in`, which also matches inherited names\n if (!RESERVED_INPUT_KEYS.some((key) => Object.hasOwn(input, key))) return input;\n const rest: Record<string, unknown> = {};\n for (const key of Object.keys(input)) {\n // \"__proto__\" is dropped too: assigning it would call the inherited setter\n // and replace `rest`'s prototype instead of creating a data property.\n // validation.ts's own-property lookups are the primary control.\n if (!RESERVED_INPUT_KEYS.includes(key)) rest[key] = input[key];\n }\n return rest;\n}\n","// In-memory implementation of the frozen `ResourceRegistry` interface\nimport type { ProtocolName } from '../domain/common';\nimport type { CommerceResource, ResourceRegistry } from '../domain/resource';\nimport { CommerceError } from '../errors';\n\nclass ResourceRegistryImpl implements ResourceRegistry {\n private readonly byId = new Map<string, CommerceResource>();\n private readonly ordered: readonly CommerceResource[];\n\n constructor(resources: readonly CommerceResource[]) {\n for (const resource of resources) {\n if (this.byId.has(resource.id)) {\n throw new CommerceError('CONFIG_INVALID', `Duplicate resource id \"${resource.id}\"`, {\n details: { resourceId: resource.id },\n });\n }\n this.byId.set(resource.id, resource);\n }\n this.ordered = [...resources];\n }\n\n get(id: string): CommerceResource | undefined {\n return this.byId.get(id);\n }\n\n list(): readonly CommerceResource[] {\n return this.ordered;\n }\n\n listExposedVia(protocol: ProtocolName): readonly CommerceResource[] {\n return this.ordered.filter((resource) => resource.exposedVia.includes(protocol));\n }\n\n has(id: string): boolean {\n return this.byId.has(id);\n }\n}\n\n/** Build a `ResourceRegistry` from a validated list of canonical resources */\nexport function createResourceRegistry(resources: readonly CommerceResource[]): ResourceRegistry {\n return new ResourceRegistryImpl(resources);\n}\n","/**\n * `EventSink` that persists every event to the receipt store. A store failure\n * is logged, never thrown to the caller.\n */\nimport type { CommerceEvent, EventSink } from '../domain/event';\nimport { describeError } from '../errors';\nimport type { Logger } from '../interfaces/logger';\nimport type { ReceiptStore } from '../interfaces/store';\n\nexport interface CreateStoreEventSinkOptions {\n readonly store: ReceiptStore;\n readonly logger: Logger;\n}\n\nexport function createStoreEventSink(options: CreateStoreEventSinkOptions): EventSink {\n return {\n async emit(event: CommerceEvent): Promise<void> {\n try {\n await options.store.appendEvent(event);\n } catch (error) {\n options.logger.error(\n { err: describeError(error), eventType: event.type, requestId: event.requestId },\n 'Failed to persist commerce event',\n );\n }\n },\n };\n}\n"]}