@facto-to/card 0.0.0-stage → 0.0.1-beta.2

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 (69) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +63 -2
  5. package/dist/card-inbox-DzsHFRPT.d.cts +312 -0
  6. package/dist/card-inbox-DzsHFRPT.d.ts +312 -0
  7. package/dist/chunk-KBS2PWM4.js +2 -0
  8. package/dist/cli/index.js +6 -0
  9. package/dist/docs/README.md +9 -0
  10. package/dist/docs/authentication.md +96 -0
  11. package/dist/docs/authorization-binding.md +182 -0
  12. package/dist/docs/authorizations.md +182 -0
  13. package/dist/docs/concepts.md +36 -0
  14. package/dist/docs/deliveries.md +170 -0
  15. package/dist/docs/errors.md +100 -0
  16. package/dist/docs/getting-access.md +56 -0
  17. package/dist/docs/idempotency.md +78 -0
  18. package/dist/docs/integration-checklist.md +15 -0
  19. package/dist/docs/integration.zh.md +59 -0
  20. package/dist/docs/interlace-adapter-v1.md +87 -0
  21. package/dist/docs/interlace-adapter-v1.zh.md +87 -0
  22. package/dist/docs/not-yet-available.md +13 -0
  23. package/dist/docs/quickstart.md +126 -0
  24. package/dist/docs/reconciliation.md +86 -0
  25. package/dist/docs/reference/api.md +2541 -0
  26. package/dist/docs/reference/events.md +639 -0
  27. package/dist/docs/reference/schemas.json +6603 -0
  28. package/dist/docs/reference/schemas.md +1001 -0
  29. package/dist/docs/simulator.md +235 -0
  30. package/dist/docs/versioning.md +9 -0
  31. package/dist/index.cjs +3 -0
  32. package/dist/index.d.cts +987 -0
  33. package/dist/index.d.ts +987 -0
  34. package/dist/index.js +2 -0
  35. package/dist/source/build.mjs +5 -0
  36. package/dist/source/package.json +16 -0
  37. package/dist/source/src/connect/cli/deliveries.ts +48 -0
  38. package/dist/source/src/connect/cli/index.ts +57 -0
  39. package/dist/source/src/connect/server/card-binding-assertion.ts +312 -0
  40. package/dist/source/src/connect/server/card-client.ts +1018 -0
  41. package/dist/source/src/connect/server/card-delivery.ts +301 -0
  42. package/dist/source/src/connect/server/card-events.ts +473 -0
  43. package/dist/source/src/connect/server/card-idempotency.ts +27 -0
  44. package/dist/source/src/connect/server/card-inbox.ts +82 -0
  45. package/dist/source/src/connect/server/card-intent-token.ts +588 -0
  46. package/dist/source/src/connect/server/card-polling.ts +69 -0
  47. package/dist/source/src/connect/server/card-signing.ts +115 -0
  48. package/dist/source/src/connect/server/card-transport.ts +282 -0
  49. package/dist/source/src/connect/server/errors.ts +280 -0
  50. package/dist/source/src/connect/server/fixtures/engine/card-events.synthetic.ts +84 -0
  51. package/dist/source/src/connect/server/retry-after.ts +12 -0
  52. package/dist/source/src/connect/testing/card-inbox.ts +124 -0
  53. package/dist/source/src/connect/testing/card-scenarios.ts +243 -0
  54. package/dist/source/src/connect/testing/card-simulator-vectors.ts +262 -0
  55. package/dist/source/src/connect/testing/card-simulator.ts +531 -0
  56. package/dist/source/src/connect/testing/interlace-card-transactions.ts +704 -0
  57. package/dist/source/src/connect/testing/pure-sha256.ts +123 -0
  58. package/dist/source/src/connect/wire.d.ts +544 -0
  59. package/dist/source/src/index.ts +163 -0
  60. package/dist/source/src/testing-browser.ts +24 -0
  61. package/dist/source/src/testing.ts +26 -0
  62. package/dist/source/tsconfig.json +20 -0
  63. package/dist/testing-browser.d.ts +220 -0
  64. package/dist/testing-browser.js +5 -0
  65. package/dist/testing.cjs +6 -0
  66. package/dist/testing.d.cts +199 -0
  67. package/dist/testing.d.ts +199 -0
  68. package/dist/testing.js +5 -0
  69. package/package.json +60 -4
@@ -0,0 +1,115 @@
1
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto'
2
+ import { CardError } from './errors'
3
+
4
+ type CardRequestMethod = 'GET' | 'PUT' | 'POST'
5
+ type CardRequestBody = string | Uint8Array
6
+
7
+ /**
8
+ * Explicit API key secret representation. Bare strings are rejected at both
9
+ * compile time and runtime so the key encoding is always stated, never guessed.
10
+ *
11
+ * Pass a Facto-issued `hmac_secret` as `{ encoding: 'utf8', value }`: Engine
12
+ * verifies the request HMAC with the UTF-8 bytes of the stored secret string.
13
+ * Use `{ encoding: 'hex', value }` or `Uint8Array` only for keys an integration
14
+ * contract provisions out-of-band as hex-encoded or raw bytes.
15
+ */
16
+ export type CardApiKeySecret =
17
+ | { readonly encoding: 'hex'; readonly value: string }
18
+ | { readonly encoding: 'utf8'; readonly value: string }
19
+ | Uint8Array
20
+
21
+ const HEX_BYTES_PATTERN = /^(?:[0-9a-fA-F]{2})+$/
22
+
23
+ function configError(message: string): CardError {
24
+ return new CardError('FACTO_CONFIG_INVALID', message, { retryable: false })
25
+ }
26
+
27
+ /** Decode an explicit CardApiKeySecret into raw key bytes, failing closed on bare strings or malformed hex. */
28
+ export function resolveCardApiKeySecret(secret: CardApiKeySecret): Uint8Array {
29
+ if (typeof secret === 'string') {
30
+ throw configError("apiKeySecret cannot be a bare string; pass { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array")
31
+ }
32
+ if (secret instanceof Uint8Array) {
33
+ if (secret.byteLength === 0) {
34
+ throw configError('apiKeySecret Uint8Array must not be empty')
35
+ }
36
+ return new Uint8Array(secret)
37
+ }
38
+ if (typeof secret !== 'object' || secret === null || Array.isArray(secret)) {
39
+ throw configError("apiKeySecret must be { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array")
40
+ }
41
+ const keys = Object.keys(secret)
42
+ if (keys.length !== 2 || !Object.hasOwn(secret, 'encoding') || !Object.hasOwn(secret, 'value')) {
43
+ throw configError("apiKeySecret must contain only { encoding: 'hex' | 'utf8', value: string }")
44
+ }
45
+ const { encoding, value } = secret as { encoding: unknown; value: unknown }
46
+ if (encoding === 'utf8') {
47
+ if (typeof value !== 'string' || value.length === 0) {
48
+ throw configError("apiKeySecret with encoding 'utf8' must have a non-empty string value")
49
+ }
50
+ return new TextEncoder().encode(value)
51
+ }
52
+ if (encoding === 'hex') {
53
+ if (typeof value !== 'string' || !HEX_BYTES_PATTERN.test(value)) {
54
+ throw configError("apiKeySecret with encoding 'hex' must be a non-empty, even-length hexadecimal string")
55
+ }
56
+ const bytes = new Uint8Array(value.length / 2)
57
+ for (let i = 0; i < value.length; i += 2) {
58
+ bytes[i / 2] = Number.parseInt(value.slice(i, i + 2), 16)
59
+ }
60
+ return bytes
61
+ }
62
+ throw configError("apiKeySecret encoding must be 'hex' or 'utf8', or pass a Uint8Array")
63
+ }
64
+
65
+ export interface CardSigningInput {
66
+ readonly secret: CardApiKeySecret
67
+ readonly apiKeyId: string
68
+ readonly method: CardRequestMethod
69
+ readonly target: string
70
+ readonly timestamp: number
71
+ readonly nonce: string
72
+ readonly body: CardRequestBody
73
+ readonly idempotencyKey?: string
74
+ }
75
+
76
+ /** Sign exact request bytes and canonical path/query; the idempotency header is separate from HMAC V2. */
77
+ export function signCardRequest(input: CardSigningInput): Headers {
78
+ const secretBytes = resolveCardApiKeySecret(input.secret)
79
+ const digest = createHash('sha256').update(input.body).digest('hex')
80
+ const canonical = ['FACTO-HMAC-V2', input.method, input.target, String(input.timestamp), input.nonce, digest].join('\n')
81
+ const headers = new Headers({
82
+ 'x-api-key': input.apiKeyId,
83
+ 'x-api-timestamp': String(input.timestamp),
84
+ 'x-api-nonce': input.nonce,
85
+ 'x-api-signature': createHmac('sha256', secretBytes).update(canonical, 'utf8').digest('hex'),
86
+ })
87
+ if (input.idempotencyKey !== undefined) headers.set('Idempotency-Key', input.idempotencyKey)
88
+ return headers
89
+ }
90
+
91
+ export interface CardVerificationInput {
92
+ readonly secret: CardApiKeySecret
93
+ readonly apiKeyId: string
94
+ readonly method: CardRequestMethod
95
+ readonly target: string
96
+ readonly body: CardRequestBody
97
+ readonly headers: HeadersInit
98
+ }
99
+
100
+ /** Verify authenticity only; callers must separately enforce timestamp freshness and nonce replay protection. */
101
+ export function verifyCardRequest(input: CardVerificationInput): boolean {
102
+ const secretBytes = resolveCardApiKeySecret(input.secret)
103
+ const headers = new Headers(input.headers)
104
+ const timestamp = headers.get('x-api-timestamp')
105
+ const nonce = headers.get('x-api-nonce')
106
+ const signature = headers.get('x-api-signature')
107
+ if (
108
+ headers.get('x-api-key') !== input.apiKeyId ||
109
+ !timestamp || !/^\d{10}$/.test(timestamp) ||
110
+ !nonce || !/^[\x21-\x7e]{1,128}$/.test(nonce) ||
111
+ !signature || !/^[a-f0-9]{64}$/.test(signature)
112
+ ) return false
113
+ const expected = signCardRequest({ ...input, secret: secretBytes, timestamp: Number(timestamp), nonce }).get('x-api-signature')!
114
+ return timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'))
115
+ }
@@ -0,0 +1,282 @@
1
+ import { CardError, type CardServerRetryOptions } from './errors'
2
+ import { parseRetryAfterSeconds } from './retry-after'
3
+
4
+ // Shared Card machine transport, validation helpers, and error envelopes.
5
+ // Nothing here may depend on non-machine session types or vocabularies.
6
+
7
+ export type CardEnvironment = 'dev' | 'production'
8
+ export type OpenVocabulary<T extends string> = T | (string & {})
9
+ export interface CardRequestOptions {
10
+ readonly signal?: AbortSignal
11
+ }
12
+
13
+ /** Default ceiling for one Card API response body; see `maxResponseBytes`. */
14
+ const DEFAULT_MAX_RESPONSE_BYTES = 1_048_576
15
+
16
+ export interface TransportOptions {
17
+ readonly environment: CardEnvironment
18
+ readonly apiBaseUrl?: string
19
+ readonly timeoutMs?: number
20
+ readonly retry?: CardServerRetryOptions
21
+ /**
22
+ * Largest response body accepted, in bytes (default 1048576). The body is
23
+ * read incrementally and the request fails with `FACTO_ENGINE_RESPONSE_INVALID`
24
+ * as soon as it exceeds this size.
25
+ */
26
+ readonly maxResponseBytes?: number
27
+ readonly fetch?: (input: string, init?: RequestInit) => Promise<Response>
28
+ }
29
+ type RecordValue = Record<string, unknown>
30
+ export const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
31
+ export const pconnPattern = /^pconn_[A-Za-z0-9_-]{16,}$/
32
+ export const sha256HexPattern = /^[a-f0-9]{64}$/
33
+ export const digestPattern = /^sha256:[a-f0-9]{64}$/
34
+ export const transportKeys = ['environment', 'apiBaseUrl', 'timeoutMs', 'retry', 'maxResponseBytes', 'fetch']
35
+
36
+ export function object(value: unknown): value is RecordValue {
37
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
38
+ }
39
+
40
+ export function text(value: unknown, min = 1, max = 255): value is string {
41
+ return typeof value === 'string' && [...value].length >= min && [...value].length <= max
42
+ }
43
+
44
+ export function header(value: unknown, min = 1, max = 255): value is string {
45
+ return text(value, min, max) && /^[\x21-\x7e]+$/.test(value)
46
+ }
47
+
48
+ export function uuid(value: unknown): value is string {
49
+ return typeof value === 'string' && uuidPattern.test(value) && value !== '00000000-0000-0000-0000-000000000000'
50
+ }
51
+
52
+ export function revision(value: unknown): value is number {
53
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= 2147483647
54
+ }
55
+
56
+ export function time(value: unknown): value is string {
57
+ return typeof value === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value)
58
+ && Number.isFinite(Date.parse(value))
59
+ }
60
+
61
+ export function closed(value: unknown, required: readonly string[], optional: readonly string[] = []): value is RecordValue {
62
+ return object(value) && required.every((key) => Object.hasOwn(value, key))
63
+ && Object.keys(value).every((key) => required.includes(key) || optional.includes(key))
64
+ }
65
+
66
+ export function responseFields(value: unknown, required: readonly string[], _optional: readonly string[] = []): value is RecordValue {
67
+ return object(value) && required.every((key) => Object.hasOwn(value, key))
68
+ }
69
+
70
+ export function config(valid: unknown, message: string): asserts valid {
71
+ if (!valid) throw new CardError('FACTO_CONFIG_INVALID', message, { retryable: false })
72
+ }
73
+
74
+ function retryableHttpStatus(status: number): boolean {
75
+ return status === 429 || status >= 500
76
+ }
77
+
78
+ function responseRequestId(response?: Response): string | undefined {
79
+ const value = response?.headers.get('x-request-id')?.trim()
80
+ return value && value.length > 0 ? value : undefined
81
+ }
82
+
83
+ export function invalidResponse(status: number, response?: Response): CardError {
84
+ return new CardError('FACTO_ENGINE_RESPONSE_INVALID', 'Card API response does not match the producer contract', {
85
+ retryable: retryableHttpStatus(status), status,
86
+ retryAfterSeconds: response ? parseRetryAfterSeconds(response) : undefined,
87
+ requestId: responseRequestId(response),
88
+ })
89
+ }
90
+
91
+ function responseTooLarge(response: Response, maxResponseBytes: number): CardError {
92
+ return new CardError('FACTO_ENGINE_RESPONSE_INVALID', `Card API response body exceeds maxResponseBytes (${maxResponseBytes} bytes)`, {
93
+ retryable: retryableHttpStatus(response.status), status: response.status,
94
+ details: { reason: 'response_body_too_large', maxResponseBytes },
95
+ retryAfterSeconds: parseRetryAfterSeconds(response),
96
+ requestId: responseRequestId(response),
97
+ })
98
+ }
99
+
100
+ /** Read the body incrementally, stopping as soon as it exceeds the limit. */
101
+ async function boundedText(response: Response, maxResponseBytes: number, signal: AbortSignal): Promise<string> {
102
+ const declared = response.headers.get('content-length')?.trim()
103
+ if (declared !== undefined && /^\d+$/.test(declared) && Number(declared) > maxResponseBytes) {
104
+ await response.body?.cancel().catch(() => undefined)
105
+ throw responseTooLarge(response, maxResponseBytes)
106
+ }
107
+ if (!response.body) return ''
108
+ const reader = response.body.getReader()
109
+ const chunks: Uint8Array[] = []
110
+ let received = 0
111
+ try {
112
+ while (true) {
113
+ const { done, value } = await reader.read()
114
+ if (done) break
115
+ received += value.byteLength
116
+ if (received > maxResponseBytes || signal.aborted) {
117
+ await reader.cancel().catch(() => undefined)
118
+ if (signal.aborted) throw new CardError('FACTO_REQUEST_ABORTED', 'Card API request aborted or timed out', { retryable: false })
119
+ throw responseTooLarge(response, maxResponseBytes)
120
+ }
121
+ chunks.push(value)
122
+ }
123
+ } finally {
124
+ reader.releaseLock()
125
+ }
126
+ const bytes = new Uint8Array(received)
127
+ let offset = 0
128
+ for (const chunk of chunks) {
129
+ bytes.set(chunk, offset)
130
+ offset += chunk.byteLength
131
+ }
132
+ return new TextDecoder().decode(bytes)
133
+ }
134
+
135
+ const authorizationErrorCodes = [
136
+ 'integrity_conflict',
137
+ 'idempotency_payload_mismatch',
138
+ 'version_already_recorded',
139
+ 'mapping_revision_not_approved',
140
+ 'fact_type_not_allowed',
141
+ 'managed_route_refused',
142
+ 'ambiguous_lookup_selector',
143
+ 'stale_revision',
144
+ 'intent_token_rejected',
145
+ 'authorization_admission_closed',
146
+ 'route_not_payable',
147
+ 'consent_scope_not_payable',
148
+ 'spending_limit_exceeded',
149
+ 'onchain_insufficient_balance',
150
+ 'yield_source_underfunded',
151
+ 'too_many_requests',
152
+ 'rate_limited',
153
+ 'internal_error',
154
+ ] as const
155
+
156
+ export type CardAuthorizationErrorCode = (typeof authorizationErrorCodes)[number] | (string & {})
157
+ export interface CardErrorEnvelope {
158
+ readonly error: CardAuthorizationErrorCode
159
+ readonly message: string
160
+ readonly request_id: string
161
+ }
162
+ /** Nested AppError envelope. `category` and `code` are open strings; preserve unknown values. */
163
+ export interface CardNestedErrorEnvelope {
164
+ error: {
165
+ category: string
166
+ code: string
167
+ message: string
168
+ request_id: string
169
+ retryable: boolean
170
+ details?: unknown
171
+ }
172
+ }
173
+ const engineErrorMessageMaxLength = 512
174
+
175
+ /** Validate only the flat Card error envelope; nested AppError envelopes use isCardNestedErrorEnvelope. */
176
+ export function isCardErrorEnvelope(value: unknown): value is CardErrorEnvelope {
177
+ return responseFields(value, ['error', 'message', 'request_id'])
178
+ && text(value.error, 1, 128) && /^[a-z][a-z0-9_]*$/.test(value.error)
179
+ && text(value.message, 1, engineErrorMessageMaxLength) && text(value.request_id, 1, 128)
180
+ }
181
+
182
+ export function isCardNestedErrorEnvelope(value: unknown): value is CardNestedErrorEnvelope {
183
+ if (!responseFields(value, ['error']) || !responseFields(
184
+ value.error,
185
+ ['category', 'code', 'message', 'request_id', 'retryable'],
186
+ ['details'],
187
+ )) return false
188
+ const error = value.error
189
+ if (
190
+ typeof error.category !== 'string' || typeof error.code !== 'string'
191
+ || typeof error.message !== 'string' || typeof error.request_id !== 'string'
192
+ || typeof error.retryable !== 'boolean'
193
+ ) return false
194
+ return true
195
+ }
196
+
197
+ function validateRetryOptions(retry: CardServerRetryOptions | undefined): void {
198
+ if (retry === undefined) return
199
+ config(object(retry), 'retry options must be an object')
200
+ if (retry.maxRetries !== undefined) config(typeof retry.maxRetries === 'number' && Number.isSafeInteger(retry.maxRetries) && retry.maxRetries >= 0, 'retry.maxRetries must be a non-negative integer')
201
+ if (retry.baseDelayMs !== undefined) config(typeof retry.baseDelayMs === 'number' && Number.isFinite(retry.baseDelayMs) && retry.baseDelayMs >= 0, 'retry.baseDelayMs must be non-negative')
202
+ if (retry.maxDelayMs !== undefined) config(typeof retry.maxDelayMs === 'number' && Number.isFinite(retry.maxDelayMs) && retry.maxDelayMs >= 0, 'retry.maxDelayMs must be non-negative')
203
+ if (retry.maxRetryAfterMs !== undefined) config(typeof retry.maxRetryAfterMs === 'number' && Number.isFinite(retry.maxRetryAfterMs) && retry.maxRetryAfterMs >= 0 && retry.maxRetryAfterMs <= 2_147_483_647, 'retry.maxRetryAfterMs is out of range')
204
+ }
205
+
206
+ export function transport(options: TransportOptions, identity: string) {
207
+ config(typeof window === 'undefined', 'Card API credentials require a server runtime')
208
+ config(options.environment === 'dev' || options.environment === 'production', 'An explicit dev or production environment is required')
209
+ validateRetryOptions(options.retry)
210
+ const defaults = { dev: 'https://dev-api.facto.to', production: 'https://api.facto.to' }
211
+ let url: URL
212
+ config(options.environment !== 'production' || typeof options.apiBaseUrl === 'string', 'Production requires an explicit apiBaseUrl')
213
+ try { url = new URL(options.apiBaseUrl ?? defaults.dev) } catch {
214
+ throw new CardError('FACTO_CONFIG_INVALID', 'apiBaseUrl must be an absolute HTTP(S) origin', { retryable: false })
215
+ }
216
+ config(!url.username && !url.password && !url.search && !url.hash && url.pathname === '/'
217
+ && (url.protocol === 'https:' || (url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))), 'apiBaseUrl must be an HTTPS origin or an explicit loopback HTTP origin')
218
+ // A fully qualified name (`api.facto.to.`) addresses the same host; compare without the root dot.
219
+ const comparableOrigin = `${url.protocol}//${url.hostname.replace(/\.+$/, '')}${url.port ? `:${url.port}` : ''}`
220
+ config(!Object.values(defaults).includes(comparableOrigin) || comparableOrigin === defaults[options.environment], 'The published endpoint must match the client environment')
221
+ const origin = url.origin
222
+ const timeoutMs = options.timeoutMs ?? 30_000
223
+ config(Number.isSafeInteger(timeoutMs) && timeoutMs > 0, 'timeoutMs must be a positive integer')
224
+ const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES
225
+ config(Number.isSafeInteger(maxResponseBytes) && maxResponseBytes > 0, 'maxResponseBytes must be a positive integer')
226
+ const fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis)
227
+ config(typeof fetchImpl === 'function', 'A server fetch implementation is required')
228
+
229
+ return async function request<T>(method: 'GET' | 'PUT' | 'POST', path: string, headers: Headers,
230
+ rawBody: string | undefined, expectedStatuses: readonly number[], parse: (value: unknown, status: number) => value is T,
231
+ requestOptions: CardRequestOptions = {}): Promise<T> {
232
+ const controller = new AbortController()
233
+ const abort = () => controller.abort()
234
+ requestOptions.signal?.addEventListener('abort', abort, { once: true })
235
+ if (requestOptions.signal?.aborted) abort()
236
+ const timer = setTimeout(abort, timeoutMs)
237
+ let rejectAbort: (() => void) | undefined
238
+ const aborted = new Promise<never>((_, reject) => {
239
+ rejectAbort = () => reject(new CardError('FACTO_REQUEST_ABORTED', 'Card API request aborted or timed out', { retryable: false }))
240
+ controller.signal.addEventListener('abort', rejectAbort, { once: true })
241
+ if (controller.signal.aborted) rejectAbort()
242
+ })
243
+ try {
244
+ if (controller.signal.aborted) return await aborted
245
+ headers.set('accept', 'application/json')
246
+ if (rawBody !== undefined) headers.set('content-type', 'application/json')
247
+ // Redirects must not forward machine credentials to another origin.
248
+ const response = await Promise.race([fetchImpl(`${origin}${path}`, {
249
+ method, headers, redirect: 'error', signal: controller.signal,
250
+ ...(rawBody !== undefined ? { body: rawBody } : {}),
251
+ }), aborted])
252
+ const raw = await Promise.race([boundedText(response, maxResponseBytes, controller.signal), aborted])
253
+ let body: unknown
254
+ try { body = JSON.parse(raw) } catch { throw invalidResponse(response.status, response) }
255
+ if (expectedStatuses.includes(response.status) && parse(body, response.status)) return body
256
+ if (!response.ok) {
257
+ if (isCardErrorEnvelope(body)) {
258
+ throw new CardError('FACTO_ENGINE_REQUEST_FAILED', `Card API ${identity} request failed with status ${response.status}`, {
259
+ retryable: retryableHttpStatus(response.status), status: response.status, details: body,
260
+ retryAfterSeconds: parseRetryAfterSeconds(response),
261
+ requestId: body.request_id || responseRequestId(response),
262
+ })
263
+ }
264
+ if (isCardNestedErrorEnvelope(body)) {
265
+ throw new CardError('FACTO_ENGINE_REQUEST_FAILED', `Card API ${identity} request failed with status ${response.status}`, {
266
+ retryable: retryableHttpStatus(response.status), status: response.status, details: body,
267
+ retryAfterSeconds: parseRetryAfterSeconds(response),
268
+ requestId: body.error.request_id || responseRequestId(response),
269
+ })
270
+ }
271
+ }
272
+ throw invalidResponse(response.status, response)
273
+ } catch (error) {
274
+ if (error instanceof CardError) throw error
275
+ throw new CardError('FACTO_ENGINE_REQUEST_FAILED', 'Card API transport failed; inspect the original operation before any new action', { retryable: false })
276
+ } finally {
277
+ clearTimeout(timer)
278
+ requestOptions.signal?.removeEventListener('abort', abort)
279
+ if (rejectAbort) controller.signal.removeEventListener('abort', rejectAbort)
280
+ }
281
+ }
282
+ }
@@ -0,0 +1,280 @@
1
+ export type FactoConnectServerErrorCode =
2
+ | 'FACTO_CONFIG_INVALID'
3
+ | 'FACTO_ENGINE_REQUEST_FAILED'
4
+ | 'FACTO_ENGINE_RESPONSE_INVALID'
5
+ | 'FACTO_REQUEST_ABORTED'
6
+ | 'FACTO_STATUS_POLL_ABORTED'
7
+
8
+ /**
9
+ * Classification of a {@link CardError}:
10
+ * - `'config_invalid'`: local configuration or argument failure; fix it, do not retry.
11
+ * - `'refused'`: deterministic server refusal of this request; fix inputs or start a
12
+ * new operation with a new `external_authorization_id` and `Idempotency-Key`.
13
+ * Lookup precondition: `409 idempotency_payload_mismatch` by itself proves the
14
+ * `Idempotency-Key` already exists on the server, so an earlier request under it
15
+ * may have been admitted, whether or not the caller remembers sending it. Always
16
+ * call `POST /api/card/authorizations/lookup` first, and allocate a new
17
+ * `external_authorization_id` and key only when lookup shows no admitted authorization.
18
+ * - `'unknown'`: the result is uncertain; never start a second authorization. Retry
19
+ * with the original key and identical bytes, or call the lookup endpoint.
20
+ */
21
+ export type CardErrorOutcome = 'refused' | 'unknown' | 'config_invalid'
22
+
23
+ const REFUSED_HTTP_STATUSES = new Set([400, 401, 402, 403, 404, 410, 412, 422, 423])
24
+
25
+ /**
26
+ * HTTP 409 codes classified as `'refused'`. For
27
+ * `idempotency_payload_mismatch` the classification stays `'refused'`, but see the
28
+ * lookup precondition on {@link CardErrorOutcome}.
29
+ */
30
+ const REFUSED_CONFLICT_CODES = new Set([
31
+ 'idempotency_payload_mismatch',
32
+ 'mapping_revision_not_approved',
33
+ 'fact_type_not_allowed',
34
+ 'managed_route_refused',
35
+ 'ambiguous_lookup_selector',
36
+ ])
37
+
38
+ function extractCardErrorEnvelopeFields(details: unknown): {
39
+ engineCode: string | undefined
40
+ requestId: string | undefined
41
+ } {
42
+ if (typeof details !== 'object' || details === null || Array.isArray(details)) {
43
+ return { engineCode: undefined, requestId: undefined }
44
+ }
45
+ const record = details as Record<string, unknown>
46
+ if (typeof record.error === 'string' && record.error.length > 0) {
47
+ return {
48
+ engineCode: record.error,
49
+ requestId: typeof record.request_id === 'string' && record.request_id.length > 0 ? record.request_id : undefined,
50
+ }
51
+ }
52
+ if (typeof record.error === 'object' && record.error !== null && !Array.isArray(record.error)) {
53
+ const nested = record.error as Record<string, unknown>
54
+ return {
55
+ engineCode: typeof nested.code === 'string' && nested.code.length > 0 ? nested.code : undefined,
56
+ requestId: typeof nested.request_id === 'string' && nested.request_id.length > 0 ? nested.request_id : undefined,
57
+ }
58
+ }
59
+ return {
60
+ engineCode: typeof record.code === 'string' && record.code.length > 0 ? record.code : undefined,
61
+ requestId: typeof record.request_id === 'string' && record.request_id.length > 0 ? record.request_id : undefined,
62
+ }
63
+ }
64
+
65
+ function classifyCardErrorOutcome(
66
+ code: FactoConnectServerErrorCode,
67
+ httpStatus: number | undefined,
68
+ engineCode: string | undefined,
69
+ ): CardErrorOutcome {
70
+ if (code === 'FACTO_CONFIG_INVALID') return 'config_invalid'
71
+ if (
72
+ code === 'FACTO_ENGINE_RESPONSE_INVALID'
73
+ || code === 'FACTO_REQUEST_ABORTED'
74
+ || code === 'FACTO_STATUS_POLL_ABORTED'
75
+ ) {
76
+ return 'unknown'
77
+ }
78
+ if (httpStatus === undefined) return 'unknown'
79
+ if (REFUSED_HTTP_STATUSES.has(httpStatus)) return 'refused'
80
+ if (httpStatus === 409) {
81
+ return engineCode !== undefined && REFUSED_CONFLICT_CODES.has(engineCode) ? 'refused' : 'unknown'
82
+ }
83
+ return 'unknown'
84
+ }
85
+
86
+ export class FactoConnectServerError extends Error {
87
+ readonly code: FactoConnectServerErrorCode
88
+ readonly retryable: boolean
89
+ readonly status?: number
90
+ readonly details?: unknown
91
+ /** The server's original `Retry-After` delta-seconds value, when present and valid. */
92
+ readonly retryAfterSeconds?: number
93
+
94
+ constructor(
95
+ code: FactoConnectServerErrorCode,
96
+ message: string,
97
+ options: {
98
+ retryable: boolean
99
+ status?: number
100
+ details?: unknown
101
+ retryAfterSeconds?: number
102
+ },
103
+ ) {
104
+ super(message)
105
+ this.name = 'FactoConnectServerError'
106
+ this.code = code
107
+ this.retryable = options.retryable
108
+ this.status = options.status
109
+ this.details = options.details
110
+ this.retryAfterSeconds = options.retryAfterSeconds
111
+ }
112
+ }
113
+
114
+ export class CardError extends FactoConnectServerError {
115
+ readonly outcome: CardErrorOutcome
116
+ readonly engineCode: string | undefined
117
+ readonly httpStatus: number | undefined
118
+ readonly requestId: string | undefined
119
+
120
+ constructor(
121
+ code: FactoConnectServerErrorCode,
122
+ message: string,
123
+ options: {
124
+ retryable: boolean
125
+ status?: number
126
+ httpStatus?: number
127
+ details?: unknown
128
+ retryAfterSeconds?: number
129
+ outcome?: CardErrorOutcome
130
+ engineCode?: string
131
+ requestId?: string
132
+ },
133
+ ) {
134
+ const httpStatus = options.httpStatus ?? options.status
135
+ super(code, message, {
136
+ retryable: options.retryable,
137
+ status: httpStatus,
138
+ details: options.details,
139
+ retryAfterSeconds: options.retryAfterSeconds,
140
+ })
141
+ this.name = 'CardError'
142
+ this.httpStatus = httpStatus
143
+ const extracted = extractCardErrorEnvelopeFields(options.details)
144
+ this.engineCode = options.engineCode ?? extracted.engineCode
145
+ this.requestId = options.requestId ?? extracted.requestId
146
+ this.outcome = options.outcome ?? classifyCardErrorOutcome(code, httpStatus, this.engineCode)
147
+ }
148
+ }
149
+
150
+ /** Default and largest accepted `maxRetryAfterMs`. */
151
+ const DEFAULT_MAX_RETRY_AFTER_MS = 60_000
152
+ const MAX_TIMER_MS = 2_147_483_647
153
+
154
+ /**
155
+ * Options for {@link withServerRetry} and the server client's safe automatic
156
+ * retry policy. GET calls and idempotency-keyed POST calls use these defaults.
157
+ * `TError` is the error class the wrapper retries and reports to `onRetry`.
158
+ */
159
+ export interface ServerRetryOptions<TError extends FactoConnectServerError = FactoConnectServerError> {
160
+ /** Max retry attempts after the first try (default 2). */
161
+ maxRetries?: number
162
+ /** Base backoff in ms for the exponential fallback (default 200). */
163
+ baseDelayMs?: number
164
+ /** Backoff cap in ms (default 5000). */
165
+ maxDelayMs?: number
166
+ /** Honor the server's `Retry-After` when present (default true). */
167
+ respectRetryAfter?: boolean
168
+ /**
169
+ * Longest `Retry-After` wait honored before a retry (default 60000 ms). When the
170
+ * server asks for a longer wait, no retry is made: the error is rethrown with
171
+ * its original `retryAfterSeconds` so the caller can schedule a later attempt.
172
+ */
173
+ maxRetryAfterMs?: number
174
+ /** Abort waiting/retrying. */
175
+ signal?: AbortSignal
176
+ /** Invoked before each retry sleep with the retryable error that was thrown. */
177
+ onRetry?: (info: { attempt: number; error: TError; delayMs: number }) => void
178
+ /** Injectable delay (tests). Defaults to a `setTimeout` sleep that respects `signal`. */
179
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>
180
+ }
181
+
182
+ function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {
183
+ if (ms <= 0) return Promise.resolve()
184
+ return new Promise((resolve, reject) => {
185
+ if (signal?.aborted) {
186
+ reject(new CardError('FACTO_STATUS_POLL_ABORTED', 'aborted', { retryable: false }))
187
+ return
188
+ }
189
+ const timer = setTimeout(() => {
190
+ signal?.removeEventListener('abort', onAbort)
191
+ resolve()
192
+ }, ms)
193
+ const onAbort = () => {
194
+ clearTimeout(timer)
195
+ reject(new CardError('FACTO_STATUS_POLL_ABORTED', 'aborted', { retryable: false }))
196
+ }
197
+ signal?.addEventListener('abort', onAbort, { once: true })
198
+ })
199
+ }
200
+
201
+ /** Retry options of the Card surface: `onRetry` receives the {@link CardError} that was thrown. */
202
+ export type CardServerRetryOptions = ServerRetryOptions<CardError>
203
+
204
+ /**
205
+ * Opt-in retry wrapper for any server-client call. Retries a
206
+ * {@link FactoConnectServerError} whose `retryable` is true (429 / 5xx),
207
+ * honoring `Retry-After` when the server sent it, otherwise exponential backoff
208
+ * with jitter. A `Retry-After` longer than `maxRetryAfterMs` ends retrying and
209
+ * rethrows the error unchanged. Non-retryable errors and non-Facto errors are
210
+ * rethrown immediately. The server client applies the same policy only to GET
211
+ * calls and POST calls carrying `Idempotency-Key`; this standalone wrapper
212
+ * remains useful for callers composing their own safe operation:
213
+ *
214
+ * ```ts
215
+ * const status = await withServerRetry(() => program.authorizations.getStatus(input))
216
+ * ```
217
+ */
218
+ export function withServerRetry<T>(
219
+ fn: () => Promise<T>,
220
+ options: ServerRetryOptions = {},
221
+ ): Promise<T> {
222
+ return retryRetryableErrors(fn, options, FactoConnectServerError)
223
+ }
224
+
225
+ /**
226
+ * Card-surface variant of {@link withServerRetry} (published by `@facto-to/card`
227
+ * as `withServerRetry`): retries only a retryable {@link CardError}, so
228
+ * `onRetry` receives the exported error type with `.outcome`.
229
+ */
230
+ export function withCardServerRetry<T>(
231
+ fn: () => Promise<T>,
232
+ options: CardServerRetryOptions = {},
233
+ ): Promise<T> {
234
+ return retryRetryableErrors(fn, options, CardError)
235
+ }
236
+
237
+ async function retryRetryableErrors<T, TError extends FactoConnectServerError>(
238
+ fn: () => Promise<T>,
239
+ options: ServerRetryOptions<TError>,
240
+ errorClass: abstract new (...args: never[]) => TError,
241
+ ): Promise<T> {
242
+ const maxRetries = options.maxRetries ?? 2
243
+ const baseDelayMs = options.baseDelayMs ?? 200
244
+ const maxDelayMs = options.maxDelayMs ?? 5000
245
+ const respectRetryAfter = options.respectRetryAfter ?? true
246
+ const maxRetryAfterMs = options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS
247
+ if (!Number.isFinite(maxRetryAfterMs) || maxRetryAfterMs < 0 || maxRetryAfterMs > MAX_TIMER_MS) {
248
+ throw new CardError('FACTO_CONFIG_INVALID', `maxRetryAfterMs must be a number from 0 to ${MAX_TIMER_MS}`, { retryable: false })
249
+ }
250
+ const sleep = options.sleep ?? defaultSleep
251
+
252
+ let attempt = 0
253
+ // eslint-disable-next-line no-constant-condition
254
+ while (true) {
255
+ try {
256
+ return await fn()
257
+ } catch (error) {
258
+ const isFacto = error instanceof errorClass
259
+ if (!isFacto || !error.retryable || attempt >= maxRetries) {
260
+ throw error
261
+ }
262
+ const retryAfterMs =
263
+ respectRetryAfter && typeof error.retryAfterSeconds === 'number'
264
+ ? error.retryAfterSeconds * 1000
265
+ : undefined
266
+ // The server's Retry-After is authoritative: retrying before it just
267
+ // re-triggers the 429. A wait beyond maxRetryAfterMs (including values a
268
+ // timer cannot represent) is not slept through; the caller decides when
269
+ // to try again. `maxDelayMs` caps only the exponential fallback used when
270
+ // the server gave no Retry-After.
271
+ if (retryAfterMs !== undefined && !(retryAfterMs <= maxRetryAfterMs)) throw error
272
+ attempt += 1
273
+ const backoff = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))
274
+ const jitter = backoff * 0.25 * Math.random()
275
+ const delayMs = retryAfterMs ?? backoff + jitter
276
+ options.onRetry?.({ attempt, error, delayMs })
277
+ await sleep(delayMs, options.signal)
278
+ }
279
+ }
280
+ }