@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,704 @@
1
+ // Browser-safe synthetic Interlace CARD_TRANSACTION fixtures, deterministic mapper,
2
+ // stateless replay helper, and in-memory Card sandbox runtime. Zero Node built-in imports.
3
+ import type { DeliveryScope, DeliverySigningKey, VerifyEventDeliveryInput } from '../server/card-delivery'
4
+ import { hmacSha256Hex, sha256Hex } from './pure-sha256'
5
+
6
+ export interface InterlaceClearingEvidence {
7
+ readonly profile: 'facto-interlace-v1'
8
+ readonly state: 'CLEARED'
9
+ readonly amount: string
10
+ readonly currency: 'USD' | 'USDC'
11
+ readonly occurredAt: string
12
+ readonly revision: number
13
+ readonly refundableAmount: string
14
+ }
15
+
16
+ export interface InterlaceCardTransactionEvent {
17
+ readonly event: 'CARD_TRANSACTION'
18
+ readonly id: string
19
+ readonly cardId: string
20
+ readonly accountId: string
21
+ readonly clientTransactionId: string
22
+ readonly relatedCardTransactionId?: string
23
+ /** Interlace transaction type: 1 = consumption, 14 = reversal, 0 = merchant refund. */
24
+ readonly type: 0 | 1 | 14
25
+ readonly status: 'PENDING' | 'CLOSED' | 'CLEARED' | 'FAILED'
26
+ readonly amount: string
27
+ readonly currency: 'USD' | 'USDC'
28
+ readonly merchantName: string
29
+ readonly merchantMcc: string
30
+ readonly merchantCountry: string
31
+ readonly transactionAt: string
32
+ readonly clearingEvidence?: InterlaceClearingEvidence
33
+ }
34
+
35
+ export type InterlaceCardTransactionFixtureName =
36
+ | 'authorizationApproved'
37
+ | 'authorizationDeclinedLimit'
38
+ | 'clearingEqualAmount'
39
+ | 'partialReversalUncleared'
40
+ | 'merchantRefundCleared'
41
+
42
+ const PARENT_CONSUMPTION_ID = '11111111-1111-4111-8111-111111111101'
43
+ const SYNTHETIC_ACCOUNT_ID = 'acct_interlace_synthetic_01'
44
+ const SYNTHETIC_CARD_ID = 'synthetic-card'
45
+ const SYNTHETIC_DECLINED_CARD_ID = 'synthetic-declined-card'
46
+
47
+ /** Synthetic Interlace CARD_TRANSACTION inbound webhook fixtures for offline sandbox testing. */
48
+ export const interlaceCardTransactionFixtures: Readonly<Record<InterlaceCardTransactionFixtureName, InterlaceCardTransactionEvent>> = Object.freeze({
49
+ authorizationApproved: Object.freeze({
50
+ event: 'CARD_TRANSACTION',
51
+ id: PARENT_CONSUMPTION_ID,
52
+ cardId: SYNTHETIC_CARD_ID,
53
+ accountId: SYNTHETIC_ACCOUNT_ID,
54
+ clientTransactionId: 'client-req-auth-0001',
55
+ type: 1,
56
+ status: 'PENDING',
57
+ amount: '12.50',
58
+ currency: 'USD',
59
+ merchantName: 'Meridian Coffee',
60
+ merchantMcc: '5814',
61
+ merchantCountry: 'US',
62
+ transactionAt: '2026-11-18T00:00:00Z',
63
+ }),
64
+ authorizationDeclinedLimit: Object.freeze({
65
+ event: 'CARD_TRANSACTION',
66
+ id: '11111111-1111-4111-8111-111111111102',
67
+ cardId: SYNTHETIC_DECLINED_CARD_ID,
68
+ accountId: SYNTHETIC_ACCOUNT_ID,
69
+ clientTransactionId: 'client-req-decline-0002',
70
+ type: 1,
71
+ status: 'PENDING',
72
+ amount: '9500.00',
73
+ currency: 'USD',
74
+ merchantName: 'Meridian Electronics',
75
+ merchantMcc: '5732',
76
+ merchantCountry: 'US',
77
+ transactionAt: '2026-11-18T00:05:00Z',
78
+ }),
79
+ clearingEqualAmount: Object.freeze({
80
+ event: 'CARD_TRANSACTION',
81
+ id: '11111111-1111-4111-8111-111111111103',
82
+ cardId: SYNTHETIC_CARD_ID,
83
+ accountId: SYNTHETIC_ACCOUNT_ID,
84
+ clientTransactionId: 'client-req-clearing-0003',
85
+ relatedCardTransactionId: PARENT_CONSUMPTION_ID,
86
+ type: 1,
87
+ status: 'CLEARED',
88
+ amount: '12.50',
89
+ currency: 'USD',
90
+ merchantName: 'Meridian Coffee',
91
+ merchantMcc: '5814',
92
+ merchantCountry: 'US',
93
+ transactionAt: '2026-11-18T01:00:00Z',
94
+ clearingEvidence: Object.freeze({
95
+ profile: 'facto-interlace-v1',
96
+ state: 'CLEARED',
97
+ amount: '12.50',
98
+ currency: 'USD',
99
+ occurredAt: '2026-11-18T01:00:00Z',
100
+ revision: 1,
101
+ refundableAmount: '12.50',
102
+ }),
103
+ }),
104
+ partialReversalUncleared: Object.freeze({
105
+ event: 'CARD_TRANSACTION',
106
+ id: '11111111-1111-4111-8111-111111111104',
107
+ cardId: SYNTHETIC_CARD_ID,
108
+ accountId: SYNTHETIC_ACCOUNT_ID,
109
+ clientTransactionId: 'client-req-reversal-0004',
110
+ relatedCardTransactionId: PARENT_CONSUMPTION_ID,
111
+ type: 14,
112
+ status: 'CLOSED',
113
+ amount: '5.00',
114
+ currency: 'USD',
115
+ merchantName: 'Meridian Coffee',
116
+ merchantMcc: '5814',
117
+ merchantCountry: 'US',
118
+ transactionAt: '2026-11-18T00:30:00Z',
119
+ }),
120
+ merchantRefundCleared: Object.freeze({
121
+ event: 'CARD_TRANSACTION',
122
+ id: '11111111-1111-4111-8111-111111111105',
123
+ cardId: SYNTHETIC_CARD_ID,
124
+ accountId: SYNTHETIC_ACCOUNT_ID,
125
+ clientTransactionId: 'client-req-refund-0005',
126
+ relatedCardTransactionId: PARENT_CONSUMPTION_ID,
127
+ type: 0,
128
+ status: 'CLOSED',
129
+ amount: '4.00',
130
+ currency: 'USD',
131
+ merchantName: 'Meridian Coffee',
132
+ merchantMcc: '5814',
133
+ merchantCountry: 'US',
134
+ transactionAt: '2026-11-18T02:00:00Z',
135
+ clearingEvidence: Object.freeze({
136
+ profile: 'facto-interlace-v1',
137
+ state: 'CLEARED',
138
+ amount: '12.50',
139
+ currency: 'USD',
140
+ occurredAt: '2026-11-18T01:00:00Z',
141
+ revision: 2,
142
+ refundableAmount: '8.50',
143
+ }),
144
+ }),
145
+ })
146
+
147
+ export interface InterlaceMappedAuthorizationRequest {
148
+ readonly endpoint: 'POST /api/card/authorizations'
149
+ readonly idempotencyKey: string
150
+ readonly payload: Readonly<{
151
+ program_id: string
152
+ external_card_id: string
153
+ external_authorization_id: string
154
+ supplier_transaction_id: string
155
+ client_transaction_id: string
156
+ amount: string
157
+ currency: 'USD' | 'USDC'
158
+ merchant_name: string
159
+ merchant_mcc: string
160
+ merchant_country: string
161
+ resource_version: string
162
+ mapping_revision: string
163
+ cardholder_verification: Readonly<{
164
+ method: 'provider_attested'
165
+ verified_at: string
166
+ evidence_id: string
167
+ }>
168
+ }>
169
+ }
170
+
171
+ export interface InterlaceMappedFactRequest {
172
+ readonly endpoint: 'POST /api/card/authorizations/{external_id}/facts'
173
+ readonly externalAuthorizationId: string
174
+ readonly idempotencyKey: string
175
+ readonly payload: Readonly<{
176
+ program_id: string
177
+ fact_type: 'clearing' | 'reversal' | 'refund'
178
+ supplier_transaction_id: string
179
+ parent_supplier_transaction_id: string
180
+ client_transaction_id: string
181
+ amount: string
182
+ currency: 'USD' | 'USDC'
183
+ resource_version: string
184
+ predecessor_version: string
185
+ mapping_revision: string
186
+ recorded_at: string
187
+ }>
188
+ }
189
+
190
+ export type InterlaceMappedCardRequest =
191
+ | InterlaceMappedAuthorizationRequest
192
+ | InterlaceMappedFactRequest
193
+
194
+ export interface InterlaceReplayOptions {
195
+ readonly programId?: string
196
+ readonly connectionId?: string
197
+ readonly mappingRevision?: string
198
+ readonly predecessorVersion?: string
199
+ readonly targetRevision?: string
200
+ readonly nowSeconds?: number
201
+ readonly isSandboxReplay?: boolean
202
+ }
203
+
204
+ export interface InterlaceReplayResult {
205
+ readonly fixtureName?: InterlaceCardTransactionFixtureName
206
+ readonly sourceEvent: InterlaceCardTransactionEvent
207
+ readonly mappedRequest: InterlaceMappedCardRequest
208
+ readonly simulatedHttpStatus: 200 | 402 | 409
209
+ readonly simulatedResponse: Readonly<Record<string, unknown>>
210
+ readonly outboundDelivery?: VerifyEventDeliveryInput
211
+ }
212
+
213
+ export interface CardSandboxRuntimeOptions {
214
+ readonly programId?: string
215
+ readonly connectionId?: string
216
+ readonly mappingRevision?: string
217
+ readonly targetRevision?: string
218
+ readonly deliverySecretUtf8?: string
219
+ readonly nowSeconds?: () => number
220
+ }
221
+
222
+ export interface CardSandboxRecordedEvent {
223
+ readonly sequence: number
224
+ readonly idempotencyKey: string
225
+ readonly endpoint: InterlaceMappedCardRequest['endpoint']
226
+ readonly httpStatus: 200 | 402 | 409
227
+ readonly response: Readonly<Record<string, unknown>>
228
+ readonly outboundDelivery?: VerifyEventDeliveryInput
229
+ }
230
+
231
+ export interface CardSandboxRuntime {
232
+ replayInterlaceTransaction(
233
+ eventOrFixture: InterlaceCardTransactionFixtureName | InterlaceCardTransactionEvent,
234
+ options?: InterlaceReplayOptions,
235
+ ): InterlaceReplayResult
236
+ listRecordedEvents(): readonly CardSandboxRecordedEvent[]
237
+ reset(): void
238
+ }
239
+
240
+ const DEFAULT_PROGRAM_ID = 'cprog_SYNTHETIC00000001'
241
+ const DEFAULT_CONNECTION_ID = 'pconn_SYNTHETIC00000001'
242
+ const DEFAULT_MAPPING_REVISION = 'facto-interlace-v1'
243
+ const DEFAULT_TARGET_REVISION = '00000000-0000-4000-8000-000000000001'
244
+ const DEFAULT_DELIVERY_SECRET = 'synthetic-delivery-test-key'
245
+
246
+ function deriveSyntheticIdempotencyKey(connectionId: string, externalAuthorizationId: string, supplierTransactionId: string, operation: string): string {
247
+ const digest = sha256Hex(JSON.stringify([connectionId, externalAuthorizationId, supplierTransactionId, operation]))
248
+ return `interlace-v1-${digest.slice(0, 32)}`
249
+ }
250
+
251
+ function deterministicUuid(seed: string): string {
252
+ const hex = sha256Hex(seed)
253
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`
254
+ }
255
+
256
+ function deterministicChargeId(seed: string): string {
257
+ return `0x${'0'.repeat(32)}${sha256Hex(seed).slice(0, 32)}`
258
+ }
259
+
260
+ type InterlaceSuccessorFactType = 'clearing' | 'reversal' | 'refund'
261
+
262
+ function unmappableInterlaceEvent(event: InterlaceCardTransactionEvent, reason: string): Error {
263
+ return new Error(
264
+ `Interlace CARD_TRANSACTION ${event.id} (type ${event.type}, status ${event.status}) cannot be mapped: ${reason}. ` +
265
+ 'Hold it for authoritative evidence; never submit it as a new authorization.',
266
+ )
267
+ }
268
+
269
+ /**
270
+ * Classify an event as a successor fact of an existing authorization, or
271
+ * `undefined` for an original consumption. Type alone proves neither
272
+ * parent-child linkage nor final status (Interlace adapter v1), so a record that
273
+ * claims a parent but lacks the evidence for a successor fact throws.
274
+ */
275
+ function resolveSuccessorFactType(event: InterlaceCardTransactionEvent): InterlaceSuccessorFactType | undefined {
276
+ const hasClearingEvidence = event.clearingEvidence?.state === 'CLEARED'
277
+ if (event.type === 1) {
278
+ if (hasClearingEvidence) return 'clearing'
279
+ if (event.relatedCardTransactionId !== undefined) {
280
+ throw unmappableInterlaceEvent(event, 'a consumption record linked to a parent maps only to a clearing fact, which requires clearingEvidence.state CLEARED')
281
+ }
282
+ return undefined
283
+ }
284
+ const factType = event.type === 14 ? 'reversal' : 'refund'
285
+ if (event.relatedCardTransactionId === undefined) {
286
+ throw unmappableInterlaceEvent(event, `a ${factType} child requires relatedCardTransactionId pointing to the original consumption`)
287
+ }
288
+ if (event.status !== 'CLOSED' && event.status !== 'CLEARED') {
289
+ throw unmappableInterlaceEvent(event, `status ${event.status} is not a final successful ${factType}`)
290
+ }
291
+ if (factType === 'refund' && !hasClearingEvidence) {
292
+ throw unmappableInterlaceEvent(event, 'a merchant refund requires clearingEvidence.state CLEARED for the original consumption')
293
+ }
294
+ return factType
295
+ }
296
+
297
+ /**
298
+ * Deterministically map an Interlace CARD_TRANSACTION event to the Facto Card API
299
+ * request of the synthetic `facto-interlace-v1` profile: an original consumption
300
+ * becomes `POST /api/card/authorizations`; a cleared consumption, a final
301
+ * reversal child or a cleared merchant refund child becomes a fact on the parent
302
+ * authorization. Throws when a record claims a parent (`relatedCardTransactionId`)
303
+ * or a successor type without the evidence that mapping requires, instead of
304
+ * creating a second authorization keyed by the child ID.
305
+ */
306
+ export function mapInterlaceCardTransactionToAuthorization(
307
+ event: InterlaceCardTransactionEvent,
308
+ options: InterlaceReplayOptions = {},
309
+ ): InterlaceMappedCardRequest {
310
+ const programId = options.programId ?? DEFAULT_PROGRAM_ID
311
+ const connectionId = options.connectionId ?? DEFAULT_CONNECTION_ID
312
+ const mappingRevision = options.mappingRevision ?? DEFAULT_MAPPING_REVISION
313
+
314
+ const factType = resolveSuccessorFactType(event)
315
+
316
+ if (factType !== undefined) {
317
+ const parentId = event.relatedCardTransactionId ?? event.id
318
+ const resourceVersion = `${factType}-${event.id}`
319
+ const predecessorVersion = options.predecessorVersion ?? (factType === 'refund' ? `clearing-${parentId}` : 'auth-v1')
320
+ const idempotencyKey = deriveSyntheticIdempotencyKey(connectionId, parentId, event.id, factType)
321
+ return {
322
+ endpoint: 'POST /api/card/authorizations/{external_id}/facts',
323
+ externalAuthorizationId: parentId,
324
+ idempotencyKey,
325
+ payload: {
326
+ program_id: programId,
327
+ fact_type: factType,
328
+ supplier_transaction_id: event.id,
329
+ parent_supplier_transaction_id: parentId,
330
+ client_transaction_id: event.clientTransactionId,
331
+ amount: event.amount,
332
+ currency: event.currency,
333
+ resource_version: resourceVersion,
334
+ predecessor_version: predecessorVersion,
335
+ mapping_revision: mappingRevision,
336
+ recorded_at: event.clearingEvidence?.occurredAt ?? event.transactionAt,
337
+ },
338
+ }
339
+ }
340
+
341
+ const idempotencyKey = deriveSyntheticIdempotencyKey(connectionId, event.id, event.id, 'create_authorization')
342
+ return {
343
+ endpoint: 'POST /api/card/authorizations',
344
+ idempotencyKey,
345
+ payload: {
346
+ program_id: programId,
347
+ external_card_id: event.cardId,
348
+ external_authorization_id: event.id,
349
+ supplier_transaction_id: event.id,
350
+ client_transaction_id: event.clientTransactionId,
351
+ amount: event.amount,
352
+ currency: event.currency,
353
+ merchant_name: event.merchantName,
354
+ merchant_mcc: event.merchantMcc,
355
+ merchant_country: event.merchantCountry,
356
+ resource_version: 'auth-v1',
357
+ mapping_revision: mappingRevision,
358
+ cardholder_verification: {
359
+ method: 'provider_attested',
360
+ verified_at: event.transactionAt,
361
+ evidence_id: `interlace:${event.clientTransactionId}`,
362
+ },
363
+ },
364
+ }
365
+ }
366
+
367
+ function resolveEvent(
368
+ eventOrFixture: InterlaceCardTransactionFixtureName | InterlaceCardTransactionEvent,
369
+ ): { fixtureName?: InterlaceCardTransactionFixtureName; sourceEvent: InterlaceCardTransactionEvent } {
370
+ if (typeof eventOrFixture === 'string') {
371
+ const fixture = interlaceCardTransactionFixtures[eventOrFixture]
372
+ if (!fixture) {
373
+ throw new RangeError(`Unknown Interlace CARD_TRANSACTION fixture: ${eventOrFixture}`)
374
+ }
375
+ return { fixtureName: eventOrFixture, sourceEvent: fixture }
376
+ }
377
+ return { sourceEvent: eventOrFixture }
378
+ }
379
+
380
+ function buildSignedOutboundDelivery(params: {
381
+ scope: DeliveryScope
382
+ secret: Uint8Array
383
+ sequence: number
384
+ nowSeconds: number
385
+ isSandboxReplay: boolean
386
+ externalAuthorizationId: string
387
+ supplierTransactionId: string
388
+ mappingRevision: string
389
+ resourceVersion: string
390
+ operationType: string
391
+ amount: string
392
+ currency: 'USD' | 'USDC'
393
+ chargeId: string
394
+ occurredAt: string
395
+ changeType: string
396
+ }): VerifyEventDeliveryInput {
397
+ const eventId = deterministicUuid(`${params.scope.connectionId}:${params.externalAuthorizationId}:${params.sequence}:${params.changeType}`)
398
+ const eventKind = 'card.authorization.updated'
399
+ const isClearing = params.operationType === 'clearing'
400
+ const isReversal = params.operationType === 'reversal'
401
+ const isRefund = params.operationType === 'refund'
402
+ const usdcAmount = Number(params.amount).toFixed(6)
403
+ const payload = {
404
+ envelope_version: 2 as const,
405
+ event_id: eventId,
406
+ event_kind: eventKind,
407
+ environment: params.scope.environment,
408
+ program_id: params.scope.programId,
409
+ origin_connection_id: params.scope.connectionId,
410
+ connection_sequence: params.sequence,
411
+ occurred_at: params.occurredAt,
412
+ data: {
413
+ lifecycle_revision: params.sequence,
414
+ operation_type: params.operationType,
415
+ resource_version: params.resourceVersion,
416
+ external_authorization_id: params.externalAuthorizationId,
417
+ mapping_revision: params.mappingRevision,
418
+ authorization: {
419
+ supplier_transaction_id: params.supplierTransactionId,
420
+ amount: usdcAmount,
421
+ currency: 'USDC',
422
+ },
423
+ charge: {
424
+ charge_id: params.chargeId,
425
+ status: 'processing',
426
+ amount: usdcAmount,
427
+ fee_total: '0.000000',
428
+ total_debited: usdcAmount,
429
+ currency: 'USDC',
430
+ updated_at: params.occurredAt,
431
+ },
432
+ issuer: {
433
+ state: isRefund ? 'refunded' : isReversal ? 'partially_reversed' : isClearing ? 'cleared' : 'authorized',
434
+ cleared_amount: isClearing ? usdcAmount : '0.000000',
435
+ reversed_amount: isReversal ? usdcAmount : '0.000000',
436
+ refunded_amount: isRefund ? usdcAmount : '0.000000',
437
+ entry_count: params.sequence,
438
+ unlinked_count: 0,
439
+ last_recorded_at: params.occurredAt,
440
+ },
441
+ refunds: {
442
+ case_count: isRefund ? 1 : 0,
443
+ status_counts: {
444
+ awaiting_charge_final: 0,
445
+ awaiting_funds: isRefund ? 1 : 0,
446
+ payable: 0,
447
+ paid: 0,
448
+ failed: 0,
449
+ not_payable: 0,
450
+ },
451
+ total_amount: isRefund ? usdcAmount : '0.000000',
452
+ total_paid_amount: '0.000000',
453
+ total_excess_amount: '0.000000',
454
+ },
455
+ change: {
456
+ type: params.changeType,
457
+ at: params.occurredAt,
458
+ ...(params.changeType === 'issuer_fact.recorded'
459
+ ? {
460
+ issuer_fact: {
461
+ operation_type: params.operationType,
462
+ resource_version: params.resourceVersion,
463
+ amount: usdcAmount,
464
+ currency: 'USDC',
465
+ recorded_at: params.occurredAt,
466
+ link_status: 'linked',
467
+ },
468
+ }
469
+ : {}),
470
+ },
471
+ },
472
+ }
473
+ const rawBody = new TextEncoder().encode(JSON.stringify(payload))
474
+ const timestamp = String(params.nowSeconds)
475
+ const digest = sha256Hex(rawBody)
476
+ const signature = hmacSha256Hex(
477
+ params.secret,
478
+ ['facto:card:outbound-delivery-signature', 'v1', eventId, eventKind, timestamp, digest].join('\n'),
479
+ )
480
+ const key: DeliverySigningKey = {
481
+ ...params.scope,
482
+ keyId: 'synthetic-sandbox-delivery-key',
483
+ secret: params.secret,
484
+ signerKeyVersion: 1,
485
+ notBefore: '2020-01-01T00:00:00Z',
486
+ expiresAt: '2099-01-01T00:00:00Z',
487
+ status: 'active',
488
+ eventKinds: [eventKind],
489
+ }
490
+ const headers: (readonly [string, string])[] = [
491
+ ['facto-signature', `v1=${signature}`],
492
+ ['facto-signature-key-id', key.keyId],
493
+ ['facto-event-id', eventId],
494
+ ['facto-event-kind', eventKind],
495
+ ['facto-event-timestamp-seconds', timestamp],
496
+ ['facto-delivery-attempt', params.isSandboxReplay ? '2' : '1'],
497
+ ]
498
+ if (params.isSandboxReplay) {
499
+ headers.push(['facto-redelivery-reason', 'sandbox_replay'])
500
+ }
501
+ return {
502
+ rawBody,
503
+ headers,
504
+ registry: [key],
505
+ expectedScope: params.scope,
506
+ nowSeconds: params.nowSeconds,
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Create a browser-safe, zero-dependency in-memory Card sandbox runtime that models
512
+ * asynchronous authorization admission, pre-admission 402 refusals, idempotency
513
+ * replay/conflict detection, subsequent fact recording, and signed Envelope v2 deliveries.
514
+ */
515
+ export function createCardSandboxRuntime(runtimeOptions: CardSandboxRuntimeOptions = {}): CardSandboxRuntime {
516
+ const defaultProgramId = runtimeOptions.programId ?? DEFAULT_PROGRAM_ID
517
+ const defaultConnectionId = runtimeOptions.connectionId ?? DEFAULT_CONNECTION_ID
518
+ const defaultMappingRevision = runtimeOptions.mappingRevision ?? DEFAULT_MAPPING_REVISION
519
+ const defaultTargetRevision = runtimeOptions.targetRevision ?? DEFAULT_TARGET_REVISION
520
+ const deliverySecret = new TextEncoder().encode(runtimeOptions.deliverySecretUtf8 ?? DEFAULT_DELIVERY_SECRET)
521
+ const nowSecondsFn = runtimeOptions.nowSeconds ?? (() => 1_795_000_000)
522
+
523
+ const idempotencyRecords = new Map<string, { bodyJson: string; result: InterlaceReplayResult }>()
524
+ const recorded: CardSandboxRecordedEvent[] = []
525
+ let sequence = 0
526
+
527
+ return {
528
+ replayInterlaceTransaction(eventOrFixture, options = {}) {
529
+ const { fixtureName, sourceEvent } = resolveEvent(eventOrFixture)
530
+ const programId = options.programId ?? defaultProgramId
531
+ const connectionId = options.connectionId ?? defaultConnectionId
532
+ const mappingRevision = options.mappingRevision ?? defaultMappingRevision
533
+ const targetRevision = options.targetRevision ?? defaultTargetRevision
534
+ const nowSeconds = options.nowSeconds ?? nowSecondsFn()
535
+
536
+ const mappedRequest = mapInterlaceCardTransactionToAuthorization(sourceEvent, {
537
+ ...options,
538
+ programId,
539
+ connectionId,
540
+ mappingRevision,
541
+ })
542
+ const bodyJson = JSON.stringify(mappedRequest.payload)
543
+ const existing = idempotencyRecords.get(mappedRequest.idempotencyKey)
544
+ if (existing) {
545
+ if (existing.bodyJson !== bodyJson) {
546
+ const conflictResponse = {
547
+ error: 'idempotency_payload_mismatch',
548
+ message: 'Idempotency-Key was previously used with different request bytes',
549
+ request_id: `req_sandbox_${deterministicUuid(bodyJson).slice(0, 8)}`,
550
+ }
551
+ const conflictResult: InterlaceReplayResult = {
552
+ ...(fixtureName ? { fixtureName } : {}),
553
+ sourceEvent,
554
+ mappedRequest,
555
+ simulatedHttpStatus: 409,
556
+ simulatedResponse: conflictResponse,
557
+ }
558
+ recorded.push({
559
+ sequence: recorded.length + 1,
560
+ idempotencyKey: mappedRequest.idempotencyKey,
561
+ endpoint: mappedRequest.endpoint,
562
+ httpStatus: 409,
563
+ response: conflictResponse,
564
+ })
565
+ return conflictResult
566
+ }
567
+ return existing.result
568
+ }
569
+
570
+ const scope: DeliveryScope = {
571
+ connectionId,
572
+ environment: 'dev',
573
+ programId,
574
+ targetRevision,
575
+ }
576
+
577
+ if (mappedRequest.endpoint === 'POST /api/card/authorizations') {
578
+ if (sourceEvent.cardId === SYNTHETIC_DECLINED_CARD_ID || Number(sourceEvent.amount) > 5000) {
579
+ const refusedResponse = {
580
+ error: 'spending_limit_exceeded',
581
+ message: 'Pre-admission spending limit exceeded',
582
+ request_id: `req_sandbox_${deterministicUuid(mappedRequest.idempotencyKey).slice(0, 8)}`,
583
+ }
584
+ const result: InterlaceReplayResult = {
585
+ ...(fixtureName ? { fixtureName } : {}),
586
+ sourceEvent,
587
+ mappedRequest,
588
+ simulatedHttpStatus: 402,
589
+ simulatedResponse: refusedResponse,
590
+ }
591
+ recorded.push({
592
+ sequence: recorded.length + 1,
593
+ idempotencyKey: mappedRequest.idempotencyKey,
594
+ endpoint: mappedRequest.endpoint,
595
+ httpStatus: 402,
596
+ response: refusedResponse,
597
+ })
598
+ return result
599
+ }
600
+ sequence += 1
601
+ const chargeId = deterministicChargeId(`${connectionId}:${mappedRequest.payload.external_authorization_id}`)
602
+ const acceptedResponse = { charge_id: chargeId, status: 'processing' }
603
+ const outboundDelivery = buildSignedOutboundDelivery({
604
+ scope,
605
+ secret: deliverySecret,
606
+ sequence,
607
+ nowSeconds,
608
+ isSandboxReplay: options.isSandboxReplay ?? false,
609
+ externalAuthorizationId: mappedRequest.payload.external_authorization_id,
610
+ supplierTransactionId: mappedRequest.payload.supplier_transaction_id,
611
+ mappingRevision,
612
+ resourceVersion: mappedRequest.payload.resource_version,
613
+ operationType: 'authorization_requested',
614
+ amount: mappedRequest.payload.amount,
615
+ currency: mappedRequest.payload.currency,
616
+ chargeId,
617
+ occurredAt: sourceEvent.transactionAt,
618
+ changeType: 'authorization.recorded',
619
+ })
620
+ const result: InterlaceReplayResult = {
621
+ ...(fixtureName ? { fixtureName } : {}),
622
+ sourceEvent,
623
+ mappedRequest,
624
+ simulatedHttpStatus: 200,
625
+ simulatedResponse: acceptedResponse,
626
+ outboundDelivery,
627
+ }
628
+ idempotencyRecords.set(mappedRequest.idempotencyKey, { bodyJson, result })
629
+ recorded.push({
630
+ sequence: recorded.length + 1,
631
+ idempotencyKey: mappedRequest.idempotencyKey,
632
+ endpoint: mappedRequest.endpoint,
633
+ httpStatus: 200,
634
+ response: acceptedResponse,
635
+ outboundDelivery,
636
+ })
637
+ return result
638
+ }
639
+
640
+ sequence += 1
641
+ const operationId = deterministicUuid(`${connectionId}:${mappedRequest.idempotencyKey}`)
642
+ const chargeId = deterministicChargeId(`${connectionId}:${mappedRequest.externalAuthorizationId}`)
643
+ const factReceipt = { operation_id: operationId, status: 'recorded' }
644
+ const outboundDelivery = buildSignedOutboundDelivery({
645
+ scope,
646
+ secret: deliverySecret,
647
+ sequence,
648
+ nowSeconds,
649
+ isSandboxReplay: options.isSandboxReplay ?? false,
650
+ externalAuthorizationId: mappedRequest.externalAuthorizationId,
651
+ supplierTransactionId: mappedRequest.payload.supplier_transaction_id,
652
+ mappingRevision,
653
+ resourceVersion: mappedRequest.payload.resource_version,
654
+ operationType: mappedRequest.payload.fact_type,
655
+ amount: mappedRequest.payload.amount,
656
+ currency: mappedRequest.payload.currency,
657
+ chargeId,
658
+ occurredAt: mappedRequest.payload.recorded_at,
659
+ changeType: 'issuer_fact.recorded',
660
+ })
661
+ const result: InterlaceReplayResult = {
662
+ ...(fixtureName ? { fixtureName } : {}),
663
+ sourceEvent,
664
+ mappedRequest,
665
+ simulatedHttpStatus: 200,
666
+ simulatedResponse: factReceipt,
667
+ outboundDelivery,
668
+ }
669
+ idempotencyRecords.set(mappedRequest.idempotencyKey, { bodyJson, result })
670
+ recorded.push({
671
+ sequence: recorded.length + 1,
672
+ idempotencyKey: mappedRequest.idempotencyKey,
673
+ endpoint: mappedRequest.endpoint,
674
+ httpStatus: 200,
675
+ response: factReceipt,
676
+ outboundDelivery,
677
+ })
678
+ return result
679
+ },
680
+ listRecordedEvents() {
681
+ return [...recorded]
682
+ },
683
+ reset() {
684
+ idempotencyRecords.clear()
685
+ recorded.length = 0
686
+ sequence = 0
687
+ },
688
+ }
689
+ }
690
+
691
+ /** Stateless one-shot helper that maps and simulates a single Interlace CARD_TRANSACTION event. */
692
+ export function replayInterlaceCardTransaction(
693
+ eventOrFixture: InterlaceCardTransactionFixtureName | InterlaceCardTransactionEvent,
694
+ options: InterlaceReplayOptions = {},
695
+ ): InterlaceReplayResult {
696
+ const runtime = createCardSandboxRuntime({
697
+ programId: options.programId,
698
+ connectionId: options.connectionId,
699
+ mappingRevision: options.mappingRevision,
700
+ targetRevision: options.targetRevision,
701
+ nowSeconds: options.nowSeconds !== undefined ? () => options.nowSeconds! : undefined,
702
+ })
703
+ return runtime.replayInterlaceTransaction(eventOrFixture, options)
704
+ }