@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.
- package/CHANGELOG.md +20 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +63 -2
- package/dist/card-inbox-DzsHFRPT.d.cts +312 -0
- package/dist/card-inbox-DzsHFRPT.d.ts +312 -0
- package/dist/chunk-KBS2PWM4.js +2 -0
- package/dist/cli/index.js +6 -0
- package/dist/docs/README.md +9 -0
- package/dist/docs/authentication.md +96 -0
- package/dist/docs/authorization-binding.md +182 -0
- package/dist/docs/authorizations.md +182 -0
- package/dist/docs/concepts.md +36 -0
- package/dist/docs/deliveries.md +170 -0
- package/dist/docs/errors.md +100 -0
- package/dist/docs/getting-access.md +56 -0
- package/dist/docs/idempotency.md +78 -0
- package/dist/docs/integration-checklist.md +15 -0
- package/dist/docs/integration.zh.md +59 -0
- package/dist/docs/interlace-adapter-v1.md +87 -0
- package/dist/docs/interlace-adapter-v1.zh.md +87 -0
- package/dist/docs/not-yet-available.md +13 -0
- package/dist/docs/quickstart.md +126 -0
- package/dist/docs/reconciliation.md +86 -0
- package/dist/docs/reference/api.md +2541 -0
- package/dist/docs/reference/events.md +639 -0
- package/dist/docs/reference/schemas.json +6603 -0
- package/dist/docs/reference/schemas.md +1001 -0
- package/dist/docs/simulator.md +235 -0
- package/dist/docs/versioning.md +9 -0
- package/dist/index.cjs +3 -0
- package/dist/index.d.cts +987 -0
- package/dist/index.d.ts +987 -0
- package/dist/index.js +2 -0
- package/dist/source/build.mjs +5 -0
- package/dist/source/package.json +16 -0
- package/dist/source/src/connect/cli/deliveries.ts +48 -0
- package/dist/source/src/connect/cli/index.ts +57 -0
- package/dist/source/src/connect/server/card-binding-assertion.ts +312 -0
- package/dist/source/src/connect/server/card-client.ts +1018 -0
- package/dist/source/src/connect/server/card-delivery.ts +301 -0
- package/dist/source/src/connect/server/card-events.ts +473 -0
- package/dist/source/src/connect/server/card-idempotency.ts +27 -0
- package/dist/source/src/connect/server/card-inbox.ts +82 -0
- package/dist/source/src/connect/server/card-intent-token.ts +588 -0
- package/dist/source/src/connect/server/card-polling.ts +69 -0
- package/dist/source/src/connect/server/card-signing.ts +115 -0
- package/dist/source/src/connect/server/card-transport.ts +282 -0
- package/dist/source/src/connect/server/errors.ts +280 -0
- package/dist/source/src/connect/server/fixtures/engine/card-events.synthetic.ts +84 -0
- package/dist/source/src/connect/server/retry-after.ts +12 -0
- package/dist/source/src/connect/testing/card-inbox.ts +124 -0
- package/dist/source/src/connect/testing/card-scenarios.ts +243 -0
- package/dist/source/src/connect/testing/card-simulator-vectors.ts +262 -0
- package/dist/source/src/connect/testing/card-simulator.ts +531 -0
- package/dist/source/src/connect/testing/interlace-card-transactions.ts +704 -0
- package/dist/source/src/connect/testing/pure-sha256.ts +123 -0
- package/dist/source/src/connect/wire.d.ts +544 -0
- package/dist/source/src/index.ts +163 -0
- package/dist/source/src/testing-browser.ts +24 -0
- package/dist/source/src/testing.ts +26 -0
- package/dist/source/tsconfig.json +20 -0
- package/dist/testing-browser.d.ts +220 -0
- package/dist/testing-browser.js +5 -0
- package/dist/testing.cjs +6 -0
- package/dist/testing.d.cts +199 -0
- package/dist/testing.d.ts +199 -0
- package/dist/testing.js +5 -0
- package/package.json +60 -4
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
interface DeliveryScope {
|
|
2
|
+
readonly connectionId: string;
|
|
3
|
+
readonly environment: 'dev' | 'production';
|
|
4
|
+
readonly programId: string;
|
|
5
|
+
readonly targetRevision: string;
|
|
6
|
+
}
|
|
7
|
+
interface DeliverySigningKey extends DeliveryScope {
|
|
8
|
+
readonly keyId: string;
|
|
9
|
+
readonly secret: Uint8Array;
|
|
10
|
+
readonly signerKeyVersion: number;
|
|
11
|
+
readonly notBefore: string;
|
|
12
|
+
readonly expiresAt: string;
|
|
13
|
+
readonly status: 'active' | 'overlap' | 'revoked' | 'expired';
|
|
14
|
+
readonly eventKinds: readonly string[];
|
|
15
|
+
}
|
|
16
|
+
type DeliveryVerificationFailureReason = 'missing_header' | 'header_invalid' | 'key_not_allowed' | 'timestamp_out_of_window' | 'signature_invalid' | 'envelope_mismatch' | 'scope_mismatch';
|
|
17
|
+
declare const CARD_REDELIVERY_REASONS: readonly ["retry", "approved_replay", "sandbox_replay", "dead_letter_replay"];
|
|
18
|
+
type CardRedeliveryReason = (typeof CARD_REDELIVERY_REASONS)[number];
|
|
19
|
+
interface VerifyEventDeliveryInput {
|
|
20
|
+
readonly rawBody: Uint8Array;
|
|
21
|
+
readonly headers: readonly (readonly [string, string])[];
|
|
22
|
+
readonly registry: readonly DeliverySigningKey[];
|
|
23
|
+
readonly expectedScope: DeliveryScope;
|
|
24
|
+
readonly nowSeconds?: number;
|
|
25
|
+
readonly toleranceSeconds?: number;
|
|
26
|
+
}
|
|
27
|
+
type VerifiedEventDelivery = {
|
|
28
|
+
readonly verified: true;
|
|
29
|
+
readonly scope: Readonly<DeliveryScope>;
|
|
30
|
+
readonly eventId: string;
|
|
31
|
+
readonly eventKind: string;
|
|
32
|
+
readonly bodyDigest: string;
|
|
33
|
+
readonly eventJson: string;
|
|
34
|
+
readonly redeliveryReason?: CardRedeliveryReason;
|
|
35
|
+
};
|
|
36
|
+
type EventDeliveryVerification = {
|
|
37
|
+
readonly verified: false;
|
|
38
|
+
readonly reason: DeliveryVerificationFailureReason;
|
|
39
|
+
} | VerifiedEventDelivery;
|
|
40
|
+
interface CreateDeliveryVerifierOptions {
|
|
41
|
+
readonly registry: readonly DeliverySigningKey[];
|
|
42
|
+
readonly expectedScope: DeliveryScope;
|
|
43
|
+
readonly nowSeconds?: () => number;
|
|
44
|
+
readonly toleranceSeconds?: number;
|
|
45
|
+
}
|
|
46
|
+
interface DeliveryVerifierInput {
|
|
47
|
+
readonly rawBody: Uint8Array;
|
|
48
|
+
readonly headers: readonly (readonly [string, string])[];
|
|
49
|
+
readonly nowSeconds?: number;
|
|
50
|
+
readonly toleranceSeconds?: number;
|
|
51
|
+
}
|
|
52
|
+
type DeliveryVerifier = (input: DeliveryVerifierInput) => EventDeliveryVerification;
|
|
53
|
+
declare function verifyEventDelivery(input: VerifyEventDeliveryInput): EventDeliveryVerification;
|
|
54
|
+
declare function createDeliveryVerifier(options: CreateDeliveryVerifierOptions): DeliveryVerifier;
|
|
55
|
+
declare function getBusinessPayloadDigest(verifiedDelivery: VerifiedEventDelivery): string;
|
|
56
|
+
|
|
57
|
+
declare const CARD_EVENT_KINDS: readonly ["card.binding.linked", "card.binding.relinked", "card.binding.revoked", "card.binding.route_changed", "card.binding.limits_changed", "card.binding.ownership_transferred", "card.charge.finalized", "card.charge.facts_updated", "card.authorization.updated"];
|
|
58
|
+
type CardEventKind = (typeof CARD_EVENT_KINDS)[number];
|
|
59
|
+
type BindingKind = Extract<CardEventKind, `card.binding.${string}`>;
|
|
60
|
+
type JsonObject = Readonly<Record<string, unknown>>;
|
|
61
|
+
type CardUsdcAmount = string;
|
|
62
|
+
interface DeliveredCardDisplay {
|
|
63
|
+
readonly network: string | null;
|
|
64
|
+
readonly type: 'virtual' | 'physical' | 'unknown' | (string & {}) | null;
|
|
65
|
+
readonly last4: string | null;
|
|
66
|
+
}
|
|
67
|
+
interface Envelope<K extends string> {
|
|
68
|
+
readonly envelope_version: 2;
|
|
69
|
+
readonly event_id: string;
|
|
70
|
+
readonly event_kind: K;
|
|
71
|
+
readonly environment: 'dev' | 'production';
|
|
72
|
+
readonly program_id: string;
|
|
73
|
+
readonly origin_connection_id?: string;
|
|
74
|
+
readonly connection_sequence: number | null;
|
|
75
|
+
readonly occurred_at: string;
|
|
76
|
+
}
|
|
77
|
+
type BindingData<K extends BindingKind> = K extends 'card.binding.linked' | 'card.binding.relinked' ? {
|
|
78
|
+
readonly external_card_id: string;
|
|
79
|
+
readonly binding_id: string;
|
|
80
|
+
readonly card: DeliveredCardDisplay;
|
|
81
|
+
readonly intent_id?: string | null;
|
|
82
|
+
readonly environment?: 'dev' | 'production';
|
|
83
|
+
readonly subject_link_id?: string;
|
|
84
|
+
readonly approved_scopes?: readonly string[];
|
|
85
|
+
readonly consent_revision?: string;
|
|
86
|
+
readonly ownership_transfer?: boolean;
|
|
87
|
+
readonly previous_binding_id?: string;
|
|
88
|
+
} : K extends 'card.binding.revoked' ? {
|
|
89
|
+
readonly external_card_id: string;
|
|
90
|
+
readonly binding_id: string;
|
|
91
|
+
readonly card: DeliveredCardDisplay;
|
|
92
|
+
readonly environment?: 'dev' | 'production';
|
|
93
|
+
readonly binding_revision?: number;
|
|
94
|
+
readonly intent_id?: string | null;
|
|
95
|
+
readonly reason_code?: string;
|
|
96
|
+
readonly revocation_source?: string;
|
|
97
|
+
readonly payable_projections_closed?: number;
|
|
98
|
+
readonly routes_detached?: number;
|
|
99
|
+
readonly route_associations_detached?: number;
|
|
100
|
+
} : K extends 'card.binding.route_changed' ? {
|
|
101
|
+
readonly binding_id: string;
|
|
102
|
+
readonly association_status: 'associated' | 'unassociated';
|
|
103
|
+
readonly environment?: 'dev' | 'production';
|
|
104
|
+
readonly binding_revision?: number;
|
|
105
|
+
} : K extends 'card.binding.limits_changed' ? {
|
|
106
|
+
readonly binding_id: string;
|
|
107
|
+
readonly per_tx_limit: CardUsdcAmount;
|
|
108
|
+
readonly period_limit: CardUsdcAmount;
|
|
109
|
+
readonly period: string;
|
|
110
|
+
readonly expires_at: string | null;
|
|
111
|
+
readonly environment?: 'dev' | 'production';
|
|
112
|
+
readonly binding_revision?: number;
|
|
113
|
+
} : {
|
|
114
|
+
readonly previous_binding_id: string;
|
|
115
|
+
readonly new_binding_id: string;
|
|
116
|
+
readonly external_card_id: string;
|
|
117
|
+
readonly card: DeliveredCardDisplay;
|
|
118
|
+
readonly transferred_at: string;
|
|
119
|
+
};
|
|
120
|
+
type CardBindingEvent<K extends BindingKind = BindingKind> = Envelope<K> & {
|
|
121
|
+
readonly binding_id: string;
|
|
122
|
+
readonly binding_revision: number;
|
|
123
|
+
readonly data: BindingData<K>;
|
|
124
|
+
};
|
|
125
|
+
interface ChargeFact {
|
|
126
|
+
readonly kind: string;
|
|
127
|
+
readonly state: string;
|
|
128
|
+
readonly recorded_at: string;
|
|
129
|
+
readonly source_system: string;
|
|
130
|
+
readonly observed_at?: string;
|
|
131
|
+
readonly safe_code?: string;
|
|
132
|
+
}
|
|
133
|
+
interface DeliveredChargeFinalReceipt {
|
|
134
|
+
readonly receipt_event_id: string;
|
|
135
|
+
readonly charge_id: string;
|
|
136
|
+
readonly external_authorization_id: string;
|
|
137
|
+
readonly mapping_revision: string;
|
|
138
|
+
readonly operation_type: string;
|
|
139
|
+
readonly resource_version: string;
|
|
140
|
+
readonly execution_outcome: string;
|
|
141
|
+
readonly terminal_action: string;
|
|
142
|
+
readonly finalized_at: string;
|
|
143
|
+
readonly facts_at_finality: readonly ChargeFact[];
|
|
144
|
+
}
|
|
145
|
+
interface SequencedEnvelope<K extends string> extends Envelope<K> {
|
|
146
|
+
readonly connection_sequence: number;
|
|
147
|
+
readonly origin_connection_id: string;
|
|
148
|
+
}
|
|
149
|
+
type ChargeFinalizedEvent = SequencedEnvelope<'card.charge.finalized'> & {
|
|
150
|
+
readonly data: {
|
|
151
|
+
readonly authorization_revision: number;
|
|
152
|
+
readonly operation_type: string;
|
|
153
|
+
readonly resource_version: string;
|
|
154
|
+
readonly external_authorization_id: string;
|
|
155
|
+
readonly mapping_revision: string;
|
|
156
|
+
readonly final_receipt: DeliveredChargeFinalReceipt;
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
type ChargeFactsUpdatedEvent = SequencedEnvelope<'card.charge.facts_updated'> & {
|
|
160
|
+
readonly data: {
|
|
161
|
+
readonly authorization_revision: number;
|
|
162
|
+
readonly operation_type: string;
|
|
163
|
+
readonly resource_version: string;
|
|
164
|
+
readonly external_authorization_id: string;
|
|
165
|
+
readonly mapping_revision: string;
|
|
166
|
+
readonly charge_id: string;
|
|
167
|
+
readonly final_receipt_event_id: string;
|
|
168
|
+
readonly previous_authorization_revision: number;
|
|
169
|
+
readonly facts: readonly ChargeFact[];
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
interface CipLifecycleSummary {
|
|
173
|
+
readonly state: string;
|
|
174
|
+
readonly cleared_amount: CardUsdcAmount;
|
|
175
|
+
readonly reversed_amount: CardUsdcAmount;
|
|
176
|
+
readonly refunded_amount: CardUsdcAmount;
|
|
177
|
+
readonly entry_count: number;
|
|
178
|
+
readonly unlinked_count: number;
|
|
179
|
+
readonly last_recorded_at?: string;
|
|
180
|
+
}
|
|
181
|
+
interface RefundSummary {
|
|
182
|
+
readonly case_count: number;
|
|
183
|
+
readonly status_counts: Readonly<{
|
|
184
|
+
awaiting_charge_final: number;
|
|
185
|
+
awaiting_funds: number;
|
|
186
|
+
payable: number;
|
|
187
|
+
paid: number;
|
|
188
|
+
failed: number;
|
|
189
|
+
not_payable: number;
|
|
190
|
+
}>;
|
|
191
|
+
readonly total_amount: CardUsdcAmount;
|
|
192
|
+
readonly total_paid_amount: CardUsdcAmount;
|
|
193
|
+
readonly total_excess_amount: CardUsdcAmount;
|
|
194
|
+
readonly last_updated_at?: string;
|
|
195
|
+
}
|
|
196
|
+
interface AuthorizationChange {
|
|
197
|
+
readonly type: string;
|
|
198
|
+
readonly at: string;
|
|
199
|
+
readonly ref?: string;
|
|
200
|
+
readonly issuer_fact?: Readonly<{
|
|
201
|
+
operation_type: string;
|
|
202
|
+
resource_version: string;
|
|
203
|
+
amount: CardUsdcAmount;
|
|
204
|
+
currency: string;
|
|
205
|
+
recorded_at: string;
|
|
206
|
+
link_status: string;
|
|
207
|
+
unlinked_reason?: string;
|
|
208
|
+
}>;
|
|
209
|
+
readonly refund_case?: Readonly<{
|
|
210
|
+
case_id: string;
|
|
211
|
+
source_operation_type: string;
|
|
212
|
+
status: string;
|
|
213
|
+
amount: CardUsdcAmount;
|
|
214
|
+
excess_amount: CardUsdcAmount;
|
|
215
|
+
paid_amount?: CardUsdcAmount;
|
|
216
|
+
not_payable_reason?: string;
|
|
217
|
+
updated_at: string;
|
|
218
|
+
refund_payment?: Readonly<{
|
|
219
|
+
chain_id: number;
|
|
220
|
+
tx_hash: string;
|
|
221
|
+
paid_amount: CardUsdcAmount;
|
|
222
|
+
recorded_by: string;
|
|
223
|
+
}>;
|
|
224
|
+
}>;
|
|
225
|
+
}
|
|
226
|
+
interface AuthorizationUpdateData {
|
|
227
|
+
readonly lifecycle_revision: number;
|
|
228
|
+
readonly operation_type: string;
|
|
229
|
+
readonly resource_version: string;
|
|
230
|
+
readonly external_authorization_id: string;
|
|
231
|
+
readonly mapping_revision: string;
|
|
232
|
+
readonly authorization: Readonly<{
|
|
233
|
+
supplier_transaction_id?: string;
|
|
234
|
+
amount: CardUsdcAmount;
|
|
235
|
+
currency: string;
|
|
236
|
+
decision?: string;
|
|
237
|
+
}>;
|
|
238
|
+
readonly charge: Readonly<{
|
|
239
|
+
charge_id: string;
|
|
240
|
+
status: string;
|
|
241
|
+
amount: CardUsdcAmount;
|
|
242
|
+
fee_total: CardUsdcAmount;
|
|
243
|
+
total_debited: CardUsdcAmount;
|
|
244
|
+
currency: string;
|
|
245
|
+
user_payment?: Readonly<{
|
|
246
|
+
chain_id: number;
|
|
247
|
+
asset_symbol?: string;
|
|
248
|
+
tx_hash: string;
|
|
249
|
+
}>;
|
|
250
|
+
failure_code?: string;
|
|
251
|
+
updated_at: string;
|
|
252
|
+
}> | null;
|
|
253
|
+
readonly issuer: CipLifecycleSummary;
|
|
254
|
+
readonly refunds: RefundSummary;
|
|
255
|
+
readonly change: AuthorizationChange;
|
|
256
|
+
}
|
|
257
|
+
type AuthorizationUpdatedEvent = SequencedEnvelope<'card.authorization.updated'> & {
|
|
258
|
+
readonly data: AuthorizationUpdateData;
|
|
259
|
+
};
|
|
260
|
+
type CardKnownEvent = {
|
|
261
|
+
[K in BindingKind]: CardBindingEvent<K>;
|
|
262
|
+
}[BindingKind] | ChargeFinalizedEvent | ChargeFactsUpdatedEvent | AuthorizationUpdatedEvent;
|
|
263
|
+
type DecodedDeliveryEvent = {
|
|
264
|
+
readonly type: 'known';
|
|
265
|
+
readonly event: CardKnownEvent;
|
|
266
|
+
} | {
|
|
267
|
+
readonly type: 'unknown';
|
|
268
|
+
readonly eventKind: string;
|
|
269
|
+
readonly rawJson: string;
|
|
270
|
+
readonly event: JsonObject;
|
|
271
|
+
};
|
|
272
|
+
declare function decodeDeliveryEvent(delivery: Extract<EventDeliveryVerification, {
|
|
273
|
+
verified: true;
|
|
274
|
+
}>): DecodedDeliveryEvent;
|
|
275
|
+
|
|
276
|
+
type Verified = Extract<EventDeliveryVerification, {
|
|
277
|
+
verified: true;
|
|
278
|
+
}>;
|
|
279
|
+
interface DeliveryInboxTransaction<Context = unknown> {
|
|
280
|
+
readonly context: Context;
|
|
281
|
+
readonly fence: number;
|
|
282
|
+
getDigest(eventId: string): Promise<string | undefined>;
|
|
283
|
+
getObservedMaxSequence(): Promise<number | null>;
|
|
284
|
+
markProcessed(eventId: string, digest: string, sequence: number | null): Promise<void>;
|
|
285
|
+
}
|
|
286
|
+
interface DeliveryInboxStore<Context = unknown> {
|
|
287
|
+
withConnection<T>(scope: Readonly<DeliveryScope>, operation: (transaction: DeliveryInboxTransaction<Context>) => Promise<T>): Promise<T>;
|
|
288
|
+
}
|
|
289
|
+
type DeliveryEventRevision = {
|
|
290
|
+
readonly field: 'binding_revision' | 'authorization_revision' | 'lifecycle_revision';
|
|
291
|
+
readonly value: number;
|
|
292
|
+
} | null;
|
|
293
|
+
interface DeliveryInboxMetadata {
|
|
294
|
+
readonly connectionSequence: number | null;
|
|
295
|
+
readonly eventRevision: DeliveryEventRevision;
|
|
296
|
+
}
|
|
297
|
+
interface DeliveryInboxOptions<Context = unknown> {
|
|
298
|
+
readonly store: DeliveryInboxStore<Context>;
|
|
299
|
+
readonly handle: (event: DecodedDeliveryEvent, transaction: DeliveryInboxTransaction<Context>, metadata: DeliveryInboxMetadata) => Promise<void>;
|
|
300
|
+
}
|
|
301
|
+
interface ObservedSequenceGap {
|
|
302
|
+
readonly previousMaxSequence: number;
|
|
303
|
+
readonly currentSequence: number;
|
|
304
|
+
}
|
|
305
|
+
type DeliveryInboxResult = {
|
|
306
|
+
readonly status: 'processed' | 'duplicate_ignored';
|
|
307
|
+
readonly connectionSequence: number | null;
|
|
308
|
+
readonly observedSequenceGap: ObservedSequenceGap | null;
|
|
309
|
+
};
|
|
310
|
+
declare function receiveEventDelivery<Context>(delivery: Verified, options: DeliveryInboxOptions<Context>): Promise<DeliveryInboxResult>;
|
|
311
|
+
|
|
312
|
+
export { type AuthorizationChange as A, createDeliveryVerifier as B, CARD_EVENT_KINDS as C, type DecodedDeliveryEvent as D, type EventDeliveryVerification as E, decodeDeliveryEvent as F, getBusinessPayloadDigest as G, receiveEventDelivery as H, verifyEventDelivery as I, type ObservedSequenceGap as O, type RefundSummary as R, type VerifiedEventDelivery as V, type AuthorizationUpdateData as a, type AuthorizationUpdatedEvent as b, CARD_REDELIVERY_REASONS as c, type CardBindingEvent as d, type CardEventKind as e, type CardKnownEvent as f, type CardRedeliveryReason as g, type ChargeFact as h, type ChargeFactsUpdatedEvent as i, type ChargeFinalizedEvent as j, type CipLifecycleSummary as k, type CreateDeliveryVerifierOptions as l, type DeliveredCardDisplay as m, type DeliveredChargeFinalReceipt as n, type DeliveryEventRevision as o, type DeliveryInboxMetadata as p, type DeliveryInboxOptions as q, type DeliveryInboxResult as r, type DeliveryInboxStore as s, type DeliveryInboxTransaction as t, type DeliveryScope as u, type DeliverySigningKey as v, type DeliveryVerificationFailureReason as w, type DeliveryVerifier as x, type DeliveryVerifierInput as y, type VerifyEventDeliveryInput as z };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var Oe=new Set([400,401,402,403,404,410,412,422,423]),Re=new Set(["idempotency_payload_mismatch","mapping_revision_not_approved","fact_type_not_allowed","managed_route_refused","ambiguous_lookup_selector"]);function ve(e){if(typeof e!="object"||e===null||Array.isArray(e))return{engineCode:void 0,requestId:void 0};let n=e;if(typeof n.error=="string"&&n.error.length>0)return{engineCode:n.error,requestId:typeof n.request_id=="string"&&n.request_id.length>0?n.request_id:void 0};if(typeof n.error=="object"&&n.error!==null&&!Array.isArray(n.error)){let r=n.error;return{engineCode:typeof r.code=="string"&&r.code.length>0?r.code:void 0,requestId:typeof r.request_id=="string"&&r.request_id.length>0?r.request_id:void 0}}return{engineCode:typeof n.code=="string"&&n.code.length>0?n.code:void 0,requestId:typeof n.request_id=="string"&&n.request_id.length>0?n.request_id:void 0}}function ke(e,n,r){return e==="FACTO_CONFIG_INVALID"?"config_invalid":e==="FACTO_ENGINE_RESPONSE_INVALID"||e==="FACTO_REQUEST_ABORTED"||e==="FACTO_STATUS_POLL_ABORTED"||n===void 0?"unknown":Oe.has(n)||n===409&&r!==void 0&&Re.has(r)?"refused":"unknown"}var ne=class extends Error{code;retryable;status;details;retryAfterSeconds;constructor(n,r,t){super(r),this.name="FactoConnectServerError",this.code=n,this.retryable=t.retryable,this.status=t.status,this.details=t.details,this.retryAfterSeconds=t.retryAfterSeconds}},I=class extends ne{outcome;engineCode;httpStatus;requestId;constructor(n,r,t){let c=t.httpStatus??t.status;super(n,r,{retryable:t.retryable,status:c,details:t.details,retryAfterSeconds:t.retryAfterSeconds}),this.name="CardError",this.httpStatus=c;let _=ve(t.details);this.engineCode=t.engineCode??_.engineCode,this.requestId=t.requestId??_.requestId,this.outcome=t.outcome??ke(n,c,this.engineCode)}},Ee=6e4,ae=2147483647;function ze(e,n){return e<=0?Promise.resolve():new Promise((r,t)=>{if(n?.aborted){t(new I("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}));return}let c=setTimeout(()=>{n?.removeEventListener("abort",_),r()},e),_=()=>{clearTimeout(c),t(new I("FACTO_STATUS_POLL_ABORTED","aborted",{retryable:!1}))};n?.addEventListener("abort",_,{once:!0})})}function Fn(e,n={}){return Pe(e,n,I)}async function Pe(e,n,r){let t=n.maxRetries??2,c=n.baseDelayMs??200,_=n.maxDelayMs??5e3,A=n.respectRetryAfter??!0,f=n.maxRetryAfterMs??Ee;if(!Number.isFinite(f)||f<0||f>ae)throw new I("FACTO_CONFIG_INVALID",`maxRetryAfterMs must be a number from 0 to ${ae}`,{retryable:!1});let s=n.sleep??ze,a=0;for(;;)try{return await e()}catch(o){if(!(o instanceof r)||!o.retryable||a>=t)throw o;let d=A&&typeof o.retryAfterSeconds=="number"?o.retryAfterSeconds*1e3:void 0;if(d!==void 0&&!(d<=f))throw o;a+=1;let l=Math.min(_,c*2**(a-1)),C=l*.25*Math.random(),S=d??l+C;n.onRetry?.({attempt:a,error:o,delayMs:S}),await s(S,n.signal)}}function L(e){let n=e.headers.get("retry-after");if(!(n===null||!/^[0-9]+$/.test(n)))return Number(n)}var Te=1048576,te=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,K=/^pconn_[A-Za-z0-9_-]{16,}$/,re=/^[a-f0-9]{64}$/,M=/^sha256:[a-f0-9]{64}$/,ce=["environment","apiBaseUrl","timeoutMs","retry","maxResponseBytes","fetch"];function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function u(e,n=1,r=255){return typeof e=="string"&&[...e].length>=n&&[...e].length<=r}function E(e,n=1,r=255){return u(e,n,r)&&/^[\x21-\x7e]+$/.test(e)}function O(e){return typeof e=="string"&&te.test(e)&&e!=="00000000-0000-0000-0000-000000000000"}function ue(e){return typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=2147483647}function m(e){return typeof e=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(e)&&Number.isFinite(Date.parse(e))}function g(e,n,r=[]){return w(e)&&n.every(t=>Object.hasOwn(e,t))&&Object.keys(e).every(t=>n.includes(t)||r.includes(t))}function y(e,n,r=[]){return w(e)&&n.every(t=>Object.hasOwn(e,t))}function i(e,n){if(!e)throw new I("FACTO_CONFIG_INVALID",n,{retryable:!1})}function U(e){return e===429||e>=500}function $(e){let n=e?.headers.get("x-request-id")?.trim();return n&&n.length>0?n:void 0}function x(e,n){return new I("FACTO_ENGINE_RESPONSE_INVALID","Card API response does not match the producer contract",{retryable:U(e),status:e,retryAfterSeconds:n?L(n):void 0,requestId:$(n)})}function de(e,n){return new I("FACTO_ENGINE_RESPONSE_INVALID",`Card API response body exceeds maxResponseBytes (${n} bytes)`,{retryable:U(e.status),status:e.status,details:{reason:"response_body_too_large",maxResponseBytes:n},retryAfterSeconds:L(e),requestId:$(e)})}async function De(e,n,r){let t=e.headers.get("content-length")?.trim();if(t!==void 0&&/^\d+$/.test(t)&&Number(t)>n)throw await e.body?.cancel().catch(()=>{}),de(e,n);if(!e.body)return"";let c=e.body.getReader(),_=[],A=0;try{for(;;){let{done:a,value:o}=await c.read();if(a)break;if(A+=o.byteLength,A>n||r.aborted)throw await c.cancel().catch(()=>{}),r.aborted?new I("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1}):de(e,n);_.push(o)}}finally{c.releaseLock()}let f=new Uint8Array(A),s=0;for(let a of _)f.set(a,s),s+=a.byteLength;return new TextDecoder().decode(f)}var qe=512;function pe(e){return y(e,["error","message","request_id"])&&u(e.error,1,128)&&/^[a-z][a-z0-9_]*$/.test(e.error)&&u(e.message,1,qe)&&u(e.request_id,1,128)}function le(e){if(!y(e,["error"])||!y(e.error,["category","code","message","request_id","retryable"],["details"]))return!1;let n=e.error;return!(typeof n.category!="string"||typeof n.code!="string"||typeof n.message!="string"||typeof n.request_id!="string"||typeof n.retryable!="boolean")}function Le(e){e!==void 0&&(i(w(e),"retry options must be an object"),e.maxRetries!==void 0&&i(typeof e.maxRetries=="number"&&Number.isSafeInteger(e.maxRetries)&&e.maxRetries>=0,"retry.maxRetries must be a non-negative integer"),e.baseDelayMs!==void 0&&i(typeof e.baseDelayMs=="number"&&Number.isFinite(e.baseDelayMs)&&e.baseDelayMs>=0,"retry.baseDelayMs must be non-negative"),e.maxDelayMs!==void 0&&i(typeof e.maxDelayMs=="number"&&Number.isFinite(e.maxDelayMs)&&e.maxDelayMs>=0,"retry.maxDelayMs must be non-negative"),e.maxRetryAfterMs!==void 0&&i(typeof e.maxRetryAfterMs=="number"&&Number.isFinite(e.maxRetryAfterMs)&&e.maxRetryAfterMs>=0&&e.maxRetryAfterMs<=2147483647,"retry.maxRetryAfterMs is out of range"))}function _e(e,n){i(typeof window>"u","Card API credentials require a server runtime"),i(e.environment==="dev"||e.environment==="production","An explicit dev or production environment is required"),Le(e.retry);let r={dev:"https://dev-api.facto.to",production:"https://api.facto.to"},t;i(e.environment!=="production"||typeof e.apiBaseUrl=="string","Production requires an explicit apiBaseUrl");try{t=new URL(e.apiBaseUrl??r.dev)}catch{throw new I("FACTO_CONFIG_INVALID","apiBaseUrl must be an absolute HTTP(S) origin",{retryable:!1})}i(!t.username&&!t.password&&!t.search&&!t.hash&&t.pathname==="/"&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)),"apiBaseUrl must be an HTTPS origin or an explicit loopback HTTP origin");let c=`${t.protocol}//${t.hostname.replace(/\.+$/,"")}${t.port?`:${t.port}`:""}`;i(!Object.values(r).includes(c)||c===r[e.environment],"The published endpoint must match the client environment");let _=t.origin,A=e.timeoutMs??3e4;i(Number.isSafeInteger(A)&&A>0,"timeoutMs must be a positive integer");let f=e.maxResponseBytes??Te;i(Number.isSafeInteger(f)&&f>0,"maxResponseBytes must be a positive integer");let s=e.fetch??globalThis.fetch?.bind(globalThis);return i(typeof s=="function","A server fetch implementation is required"),async function(o,p,d,l,C,S,T={}){let R=new AbortController,D=()=>R.abort();T.signal?.addEventListener("abort",D,{once:!0}),T.signal?.aborted&&D();let X=setTimeout(D,A),q,Y=new Promise((b,ee)=>{q=()=>ee(new I("FACTO_REQUEST_ABORTED","Card API request aborted or timed out",{retryable:!1})),R.signal.addEventListener("abort",q,{once:!0}),R.signal.aborted&&q()});try{if(R.signal.aborted)return await Y;d.set("accept","application/json"),l!==void 0&&d.set("content-type","application/json");let b=await Promise.race([s(`${_}${p}`,{method:o,headers:d,redirect:"error",signal:R.signal,...l!==void 0?{body:l}:{}}),Y]),ee=await Promise.race([De(b,f,R.signal),Y]),v;try{v=JSON.parse(ee)}catch{throw x(b.status,b)}if(C.includes(b.status)&&S(v,b.status))return v;if(!b.ok){if(pe(v))throw new I("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${b.status}`,{retryable:U(b.status),status:b.status,details:v,retryAfterSeconds:L(b),requestId:v.request_id||$(b)});if(le(v))throw new I("FACTO_ENGINE_REQUEST_FAILED",`Card API ${n} request failed with status ${b.status}`,{retryable:U(b.status),status:b.status,details:v,retryAfterSeconds:L(b),requestId:v.error.request_id||$(b)})}throw x(b.status,b)}catch(b){throw b instanceof I?b:new I("FACTO_ENGINE_REQUEST_FAILED","Card API transport failed; inspect the original operation before any new action",{retryable:!1})}finally{clearTimeout(X),T.signal?.removeEventListener("abort",D),q&&R.signal.removeEventListener("abort",q)}}}import{createPrivateKey as Be,sign as Ne}from"node:crypto";var Fe="facto-card-binding+jwt",je=/^pc_[A-Za-z0-9_-]{16,}$/,Ue=/^cbs_[A-Za-z0-9_-]{16,}$/,$e=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ke=/^[A-Za-z0-9_-]+$/,Me=/^[0-9]{4}$/,ye=300,fe=600,We=["card.metadata.view","card.use_for_facto_payments"],Ve=["passkey","mfa","reauthenticated_session"],Ge=["provider_authenticated_app","device_bound_confirmation"],Je={dev:"urn:facto:sandbox:card-program-connect:binding-proof",production:"urn:facto:production:card-program-connect:binding-proof"};function ge(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function B(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1e9&&e<=9999999999}function me(e){return typeof e=="string"&&Ke.test(e)&&Buffer.from(e,"base64url").byteLength===32}function He(e){return/^[0-9]{12,19}$/.test(e)||/[0-9]{13}/.test(e)}function Ze(e,n){return i(w(e),"Binding assertion proof claim is required"),e.mode==="provider_reauthentication"?(i(g(e,["mode","authenticatedAtSeconds","assurance"])&&B(e.authenticatedAtSeconds)&&e.authenticatedAtSeconds<=n&&n-e.authenticatedAtSeconds<=fe&&Ve.includes(e.assurance),"Reauthentication proof requires valid authenticatedAtSeconds (within 600 seconds before issuedAtSeconds) and assurance"),{mode:"provider_reauthentication",authenticated_at:e.authenticatedAtSeconds,assurance:e.assurance}):(i(e.mode==="provider_second_channel"&&g(e,["mode","approvedAtSeconds","approvalRef","channelType"])&&B(e.approvedAtSeconds)&&e.approvedAtSeconds<=n&&n-e.approvedAtSeconds<=fe&&u(e.approvalRef,16,255)&&Ge.includes(e.channelType),"Second-channel proof requires valid approvedAtSeconds (within 600 seconds before issuedAtSeconds), approvalRef (16-255 chars), and channelType"),{mode:"provider_second_channel",approved_at:e.approvedAtSeconds,approval_ref:e.approvalRef,channel_type:e.channelType})}function Qe(e){i(Array.isArray(e)&&e.length>=1&&e.length<=20,"Binding assertion requires 1 to 20 asserted cards");let n=new Set,r=0;return e.map(t=>{i(g(t,["externalCardId"],["isEntryCard","display"])&&u(t.externalCardId,8,512)&&!He(t.externalCardId)&&(t.isEntryCard===void 0||typeof t.isEntryCard=="boolean"),"Each asserted card requires an opaque externalCardId (8-512 non-PAN chars) and optional boolean isEntryCard"),i(!n.has(t.externalCardId),"Asserted cards must have unique externalCardId values"),n.add(t.externalCardId),t.isEntryCard===!0&&(r+=1,i(r<=1,"At most one asserted card may set isEntryCard to true"));let c;if(t.display!==void 0){i(g(t.display,[],["network","cardType","last4"]),"Asserted card display accepts only network, cardType, and last4");let _=t.display;i((_.network===void 0||u(_.network,1,32))&&(_.cardType===void 0||u(_.cardType,1,32))&&(_.last4===void 0||typeof _.last4=="string"&&Me.test(_.last4)),"Asserted card display fields are out of contract bounds");let A={};_.network!==void 0&&(A.network=_.network),_.cardType!==void 0&&(A.card_type=_.cardType),_.last4!==void 0&&(A.last4=_.last4),Object.keys(A).length>0&&(c=A)}return{card_ref:t.externalCardId,relationship_type:"owner",...t.isEntryCard===!0?{is_entry_card:!0}:{},...c!==void 0?{display:c}:{}}})}async function Xe(e,n,r){if(typeof e=="function"){let t=await e(n);return i(t instanceof Uint8Array&&t.byteLength===64,"Binding assertion signer must return a 64-byte Ed25519 signature"),t}i(g(e,["kty","crv","x","d"],["kid","alg","use","key_ops","ext"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&(e.alg===void 0||e.alg==="EdDSA"||e.alg==="Ed25519")&&(e.use===void 0||e.use==="sig")&&(e.key_ops===void 0||Array.isArray(e.key_ops)&&e.key_ops.every(t=>typeof t=="string")&&e.key_ops.includes("sign"))&&(e.ext===void 0||typeof e.ext=="boolean")&&(e.kid===void 0||e.kid===r)&&me(e.x)&&me(e.d),"Binding assertion signer must be a valid Ed25519 private JWK (matching signingKeyId when kid is present) or async signing callback");try{let t=Be({key:{kty:"OKP",crv:"Ed25519",x:e.x,d:e.d},format:"jwk"});return new Uint8Array(Ne(null,n,t))}catch{throw new I("FACTO_CONFIG_INVALID","Invalid Ed25519 private JWK for binding assertion signing",{retryable:!1})}}async function he(e){i(g(e,["environment","providerConnectionId","programId","bindingSessionId","issuer","subject","jti","factoChallenge","sessionRequestDigest","requestedUserConsents","proof","cards","signingKeyId","signer"],["issuedAtSeconds","notBeforeSeconds","expiresAtSeconds"]),"Binding assertion input contains missing or unknown fields"),i(e.environment==="dev"||e.environment==="production","environment must be dev or production"),i(typeof e.providerConnectionId=="string"&&je.test(e.providerConnectionId),"providerConnectionId must be a pc_ provider connection identifier (not a pconn_ program connection identifier)"),i(u(e.programId,1,255),"programId must be 1 to 255 characters"),i(typeof e.bindingSessionId=="string"&&Ue.test(e.bindingSessionId),"bindingSessionId must be a cbs_ identifier"),i(u(e.issuer,1,512),"issuer is required"),i(u(e.subject,16,512),"subject must be a pairwise opaque identifier of 16 to 512 characters"),i(u(e.jti,16,255),"jti must be 16 to 255 characters"),i(u(e.factoChallenge,1,512),"factoChallenge is required"),i(typeof e.sessionRequestDigest=="string"&&M.test(e.sessionRequestDigest),"sessionRequestDigest must be a sha256:<hex> digest"),i(u(e.signingKeyId,1,255)&&e.signingKeyId.trim()===e.signingKeyId&&!e.signingKeyId.includes("\0"),"signingKeyId must be a non-empty trimmed identifier without NUL bytes");let n=e.requestedUserConsents;i(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(d=>We.includes(d)),"requestedUserConsents must be a non-empty unique set of supported consent purposes");let r=e.issuedAtSeconds??Math.floor(Date.now()/1e3),t=e.notBeforeSeconds??r,c=e.expiresAtSeconds??r+ye;i(B(r)&&B(t)&&B(c)&&t<=r&&r<=c&&c-r<=ye,"Binding assertion timestamps must satisfy nbf <= iat <= exp with lifetime <= 300 seconds");let _=Ze(e.proof,r),A=Qe(e.cards),f=ge({typ:Fe,alg:"EdDSA",kid:e.signingKeyId}),s=ge({iss:e.issuer,aud:Je[e.environment],sub:e.subject,iat:r,nbf:t,exp:c,jti:e.jti,binding_session_id:e.bindingSessionId,facto_challenge:e.factoChallenge,session_request_digest:e.sessionRequestDigest,connection_id:e.providerConnectionId,environment:e.environment,program_ref:e.programId,proof:_,cards:A,requested_user_consents:[...n]}),a=new TextEncoder().encode(`${f}.${s}`),o=await Xe(e.signer,a,e.signingKeyId),p=`${f}.${s}.${Buffer.from(o).toString("base64url")}`;return i(p.length>=128&&p.length<=16384&&$e.test(p),"Signed binding assertion exceeds compact JWS bounds"),p}import{createHash as Ye,createHmac as en,timingSafeEqual as nn}from"node:crypto";var tn=/^(?:[0-9a-fA-F]{2})+$/;function z(e){return new I("FACTO_CONFIG_INVALID",e,{retryable:!1})}function W(e){if(typeof e=="string")throw z("apiKeySecret cannot be a bare string; pass { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(e instanceof Uint8Array){if(e.byteLength===0)throw z("apiKeySecret Uint8Array must not be empty");return new Uint8Array(e)}if(typeof e!="object"||e===null||Array.isArray(e))throw z("apiKeySecret must be { encoding: 'hex', value }, { encoding: 'utf8', value }, or Uint8Array");if(Object.keys(e).length!==2||!Object.hasOwn(e,"encoding")||!Object.hasOwn(e,"value"))throw z("apiKeySecret must contain only { encoding: 'hex' | 'utf8', value: string }");let{encoding:r,value:t}=e;if(r==="utf8"){if(typeof t!="string"||t.length===0)throw z("apiKeySecret with encoding 'utf8' must have a non-empty string value");return new TextEncoder().encode(t)}if(r==="hex"){if(typeof t!="string"||!tn.test(t))throw z("apiKeySecret with encoding 'hex' must be a non-empty, even-length hexadecimal string");let c=new Uint8Array(t.length/2);for(let _=0;_<t.length;_+=2)c[_/2]=Number.parseInt(t.slice(_,_+2),16);return c}throw z("apiKeySecret encoding must be 'hex' or 'utf8', or pass a Uint8Array")}function ie(e){let n=W(e.secret),r=Ye("sha256").update(e.body).digest("hex"),t=["FACTO-HMAC-V2",e.method,e.target,String(e.timestamp),e.nonce,r].join(`
|
|
2
|
+
`),c=new Headers({"x-api-key":e.apiKeyId,"x-api-timestamp":String(e.timestamp),"x-api-nonce":e.nonce,"x-api-signature":en("sha256",n).update(t,"utf8").digest("hex")});return e.idempotencyKey!==void 0&&c.set("Idempotency-Key",e.idempotencyKey),c}function Qn(e){let n=W(e.secret),r=new Headers(e.headers),t=r.get("x-api-timestamp"),c=r.get("x-api-nonce"),_=r.get("x-api-signature");if(r.get("x-api-key")!==e.apiKeyId||!t||!/^\d{10}$/.test(t)||!c||!/^[\x21-\x7e]{1,128}$/.test(c)||!_||!/^[a-f0-9]{64}$/.test(_))return!1;let A=ie({...e,secret:n,timestamp:Number(t),nonce:c}).get("x-api-signature");return nn(Buffer.from(_,"hex"),Buffer.from(A,"hex"))}import{randomUUID as rn}from"node:crypto";var j=/^cbs_[A-Za-z0-9_-]{16,}$/,Z=/^cint_[A-Za-z0-9_-]{16,}$/,Q=/^cb_[A-Za-z0-9_-]{16,}$/,se=/^sha256:[a-fA-F0-9]{64}$/,Se=["authorization_updated","clearing","reversal","refund","chargeback","settlement"],H=["authorization_requested",...Se],on=["facto_admission","durable_commit","provider_authorization","chain_finality","provider_settlement"],sn=["active","frozen","closed","replaced"],an=/^[A-Za-z0-9_.:-]{1,64}$/,dn=/^[0-9]+\.[0-9]{2,6}$/,cn=/^-?[0-9]+\.[0-9]{2,6}$/;function h(e,n){return typeof e=="string"&&n.test(e)}function Ie(e){return e===null||typeof e=="string"}function G(e,n=-2147483648){return typeof e=="number"&&Number.isInteger(e)&&e>=n&&e<=2147483647}function F(e,n=128){return u(e,1,n)&&!/[0-9]{13}/.test(e)}function N(e,n){return e==null||n(e)}function J(e){return Array.isArray(e)&&e.every(n=>h(n,Q))}function we(e){return y(e,["network","type","last4"])&&Ie(e.network)&&(e.type===null||["virtual","physical","unknown"].includes(String(e.type)))&&(e.last4===null||typeof e.last4=="string"&&/^[0-9]{4}$/.test(e.last4))}function k(e){return typeof e=="string"&&/^0x0{32}[0-9a-fA-F]{32}$/.test(e)}function un(e){return typeof e=="string"&&an.test(e)}function pn(e){return!y(e,["snapshot_token","snapshot_at","to_at","items","next_cursor","complete"])||!u(e.snapshot_token,16,4096)||!m(e.snapshot_at)||!m(e.to_at)||typeof e.complete!="boolean"||e.next_cursor!==null&&!u(e.next_cursor,1,4096)||e.complete&&e.next_cursor!==null||!Array.isArray(e.items)||e.items.length>100?!1:e.items.every(n=>y(n,["event_id","origin_connection_id","connection_sequence","event_sha256","target_revision","delivery_state"],["accepted_at"])&&O(n.event_id)&&typeof n.origin_connection_id=="string"&&K.test(n.origin_connection_id)&&(n.connection_sequence===null||typeof n.connection_sequence=="number"&&Number.isSafeInteger(n.connection_sequence)&&n.connection_sequence>=1)&&typeof n.event_sha256=="string"&&re.test(n.event_sha256)&&O(n.target_revision)&&typeof n.delivery_state=="string"&&(n.accepted_at===void 0||m(n.accepted_at)))}function ln(e){return y(e,["replay_id","selection_id","target_revision","status"])&&O(e.replay_id)&&O(e.selection_id)&&O(e.target_revision)&&e.status==="accepted"}function _n(e){i(g(e,["target_revision","page_size"],["selection_id","from_at","to_at","snapshot_token","cursor"]),"Reconciliation requires only the generated query fields"),i(O(e.target_revision)&&typeof e.page_size=="number"&&Number.isInteger(e.page_size)&&e.page_size>=1&&e.page_size<=100,"Reconciliation target_revision and page_size are invalid"),i(O(e.selection_id)&&!Object.hasOwn(e,"from_at")&&!Object.hasOwn(e,"to_at")||!Object.hasOwn(e,"selection_id")&&m(e.from_at)&&m(e.to_at)&&Date.parse(e.from_at)<=Date.parse(e.to_at),"Select exactly one fixed selection or explicit time window"),i((e.snapshot_token===void 0||u(e.snapshot_token,16,4096))&&(e.cursor===void 0||u(e.cursor,16,4096)&&u(e.snapshot_token,16,4096)),"A cursor requires its original snapshot token")}function yn(e){i(w(e),"Authorization lookup requires criteria");let n=Object.hasOwn(e,"criteria")?(i(g(e,["criteria"])&&w(e.criteria),"Authorization lookup wrapper requires only criteria"),e.criteria):e;i(w(n),"Authorization lookup requires criteria");let r=n.by==="external_authorization_id"?g(n,["by","external_authorization_id","resource_version","mapping_revision"],["fact_type"])&&u(n.external_authorization_id,1,256)&&u(n.resource_version,1,255)&&u(n.mapping_revision,1,255)&&(n.fact_type===void 0||H.includes(String(n.fact_type))):n.by==="supplier_transaction_id"?g(n,["by","supplier_transaction_id","resource_version","mapping_revision"],["fact_type"])&&typeof n.supplier_transaction_id=="string"&&u(n.supplier_transaction_id.trim(),1,256)&&u(n.resource_version,1,255)&&u(n.mapping_revision,1,255)&&(n.fact_type===void 0||H.includes(String(n.fact_type))):n.by==="idempotency_key"?g(n,["by","idempotency_key","original_credential_key_id"],["operation"])&&u(n.idempotency_key,16,255)&&u(n.original_credential_key_id,1,255)&&(n.operation===void 0||n.operation==="create_authorization"):n.by==="charge_id"&&g(n,["by","charge_id"])&&k(n.charge_id);return i(r,"Select exactly one complete external_authorization_id, supplier_transaction_id, idempotency_key, or public charge_id"),n}function fn(e){i(g(e,["external_card_id","external_authorization_id","amount","currency","resource_version","mapping_revision","cardholder_verification"],["supplier_transaction_id","client_transaction_id","merchant_name","merchant_mcc","merchant_country","occurred_at","decision_mode","decision_timeout_ms","deadline_at"]),"Authorization create requires the complete generated request");let t=e.cardholder_verification;i(F(e.external_card_id,512)&&u(e.external_authorization_id,1,256)&&h(e.amount,dn)&&(e.currency==="USD"||e.currency==="USDC")&&u(e.resource_version,1,255)&&u(e.mapping_revision,1,255)&&(e.merchant_name===void 0||u(e.merchant_name,0,256))&&(e.merchant_mcc===void 0||h(e.merchant_mcc,/^[0-9]{4}$/))&&(e.merchant_country===void 0||u(e.merchant_country,2,3))&&(e.occurred_at===void 0||m(e.occurred_at))&&[e.supplier_transaction_id,e.client_transaction_id].every(c=>c===void 0||typeof c=="string"&&u(c.trim(),1,256))&&(e.decision_mode===void 0||e.decision_mode==="asynchronous"||e.decision_mode==="synchronous")&&(e.decision_timeout_ms===void 0||e.decision_mode==="synchronous"&&typeof e.decision_timeout_ms=="number"&&Number.isInteger(e.decision_timeout_ms)&&e.decision_timeout_ms>=50&&e.decision_timeout_ms<=5e3)&&(e.deadline_at===void 0||e.decision_mode==="synchronous"&&m(e.deadline_at))&&g(t,["method","verified_at","evidence_id"])&&["pin","biometric","cdcvm","signature","no_cvm","provider_attested"].includes(String(t.method))&&m(t.verified_at)&&u(t.evidence_id,1,256),"Authorization fields, currency, mapping/version, or cardholder verification is invalid")}function gn(e,n){i(u(e,1,255)&&e!=="."&&e!==".."&&!e.includes("/"),"externalId must be a valid external authorization identifier"),i(g(n,["fact_type","amount","currency","resource_version","predecessor_version","mapping_revision","recorded_at"],["supplier_transaction_id","parent_supplier_transaction_id","client_transaction_id","merchant_name","merchant_mcc","merchant_country"]),"Authorization fact requires the complete generated request"),i(Se.includes(String(n.fact_type))&&h(n.amount,cn)&&(n.currency==="USD"||n.currency==="USDC")&&u(n.resource_version,1,255)&&typeof n.predecessor_version=="string"&&u(n.predecessor_version.trim(),1,255)&&n.predecessor_version!==n.resource_version&&u(n.mapping_revision,1,255)&&m(n.recorded_at)&&(n.merchant_name===void 0||u(n.merchant_name,1,255))&&(n.merchant_mcc===void 0||h(n.merchant_mcc,/^[0-9]{4}$/))&&(n.merchant_country===void 0||u(n.merchant_country,2,3))&&[n.supplier_transaction_id,n.parent_supplier_transaction_id,n.client_transaction_id].every(c=>c===void 0||typeof c=="string"&&u(c.trim(),1,255)),"Authorization fact type, predecessor version, amount, or timestamp is invalid")}function xe(e){return Array.isArray(e)&&e.length===5&&e.every((n,r)=>y(n,["kind","state","recorded_at","source_system"],["observed_at","safe_code"])&&n.kind===on[r]&&["unobserved","pending","confirmed","rejected","indeterminate"].includes(String(n.state))&&m(n.recorded_at)&&["facto","provider","chain"].includes(String(n.source_system))&&(n.safe_code===void 0||u(n.safe_code,1,64))&&(n.observed_at===void 0||m(n.observed_at))&&(n.state!=="confirmed"||m(n.observed_at))&&(n.state!=="unobserved"||!Object.hasOwn(n,"observed_at")))}function mn(e){return!y(e,["receipt_event_id","charge_id","mapping_revision","operation_type","resource_version","execution_outcome","terminal_action","finalized_at","facts_at_finality"],["external_authorization_id","authorization_ref"])||!O(e.receipt_event_id)||!k(e.charge_id)||!(u(e.external_authorization_id,1,256)||u(e.authorization_ref,1,256))||!u(e.mapping_revision,1,255)||!H.includes(String(e.operation_type))||!u(e.resource_version,1,255)||!m(e.finalized_at)||!xe(e.facts_at_finality)||e.facts_at_finality[3].state!=="confirmed"?!1:e.terminal_action==="releaseFor"?e.execution_outcome==="succeeded"&&e.facts_at_finality[0].state==="confirmed"&&e.facts_at_finality[1].state==="confirmed":e.terminal_action==="cancelReservation"&&e.execution_outcome==="failed"}function hn(e){if(e===void 0)return!0;if(!w(e)||!w(e.issuer)||!Array.isArray(e.issuer.entries)||!Array.isArray(e.refund_cases))return!1;let n=e.issuer,r=n.entries;return["state","cleared_amount","reversed_amount","refunded_amount"].every(t=>typeof n[t]=="string")&&r.every(t=>w(t)&&["operation_type","resource_version","amount","currency","recorded_at","link_status"].every(c=>typeof t[c]=="string")&&t.currency==="USDC"&&(t.unlinked_reason===void 0||typeof t.unlinked_reason=="string"))&&e.refund_cases.every(t=>w(t)&&["case_id","source_operation_type","source_resource_version","status","amount","excess_amount","updated_at"].every(c=>typeof t[c]=="string")&&(t.paid_amount===void 0||typeof t.paid_amount=="string")&&(t.not_payable_reason===void 0||typeof t.not_payable_reason=="string"))}function bn(e,n){if(e===void 0)return!0;if(!w(e)||typeof e.fee_total!="string"||!w(e.fee_breakdown))return!1;let r=e.fee_breakdown;if(!["base_fee","fast_pay_fee","pooled_surcharge"].every(c=>typeof r[c]=="string"))return!1;let t=e.user_payment;return t!==void 0&&(!w(t)||!Number.isSafeInteger(t.chain_id)||typeof t.tx_hash!="string"||!/^0x[0-9a-fA-F]{64}$/.test(t.tx_hash)||t.asset_symbol!==void 0&&typeof t.asset_symbol!="string")?!1:e.refund_payments===void 0||n&&Array.isArray(e.refund_payments)&&e.refund_payments.every(c=>w(c)&&Number.isSafeInteger(c.chain_id)&&typeof c.case_id=="string"&&typeof c.paid_amount=="string"&&typeof c.recorded_by=="string"&&typeof c.tx_hash=="string"&&/^0x[0-9a-fA-F]{64}$/.test(c.tx_hash))}function An(e){if(!y(e,["external_authorization_id","processing_status","origin_connection_id","resource_version","mapping_revision"],["charge_id","final_receipt","decline_reason_code","supplier_transaction_id","facts","revision","operation_type","decision","lifecycle","payment_details"])||!u(e.external_authorization_id,1,256)||typeof e.origin_connection_id!="string"||!K.test(e.origin_connection_id)||!u(e.resource_version,1,255)||!u(e.mapping_revision,1,255)||e.charge_id!==void 0&&e.charge_id!==null&&!k(e.charge_id)||e.supplier_transaction_id!==void 0&&!u(e.supplier_transaction_id,1,256)||e.facts!==void 0&&!xe(e.facts)||e.revision!==void 0&&!ue(e.revision)||e.operation_type!==void 0&&!H.includes(String(e.operation_type))||e.decision!==void 0&&!["approved","declined","self_reversed_timeout"].includes(String(e.decision))||e.decline_reason_code!==void 0&&!un(e.decline_reason_code)||!hn(e.lifecycle)||!bn(e.payment_details,e.lifecycle!==void 0))return!1;if(e.processing_status==="succeeded"||e.processing_status==="failed"){if(Object.hasOwn(e,"final_receipt")&&e.final_receipt!==void 0){if(!k(e.charge_id)||!mn(e.final_receipt)||Object.hasOwn(e,"decline_reason_code"))return!1;let n=e.final_receipt,r=n.external_authorization_id??n.authorization_ref;return n.execution_outcome===e.processing_status&&n.charge_id===e.charge_id&&r===e.external_authorization_id&&n.mapping_revision===e.mapping_revision&&n.resource_version===e.resource_version&&(e.operation_type===void 0||n.operation_type===e.operation_type)}return e.processing_status==="succeeded"?!Object.hasOwn(e,"decline_reason_code")&&(e.charge_id===void 0||k(e.charge_id)):k(e.charge_id)||(e.charge_id===void 0||e.charge_id===null)&&(e.decision==="declined"||e.decision==="self_reversed_timeout"||e.decline_reason_code!==void 0)}return!Object.hasOwn(e,"final_receipt")&&!Object.hasOwn(e,"decline_reason_code")&&(e.processing_status==="processing"||e.processing_status==="indeterminate"&&(e.charge_id===void 0||e.charge_id===null))}function Cn(e){return!y(e,["observed_at","resolution"],["authorization"])||!m(e.observed_at)?!1:e.resolution==="not_observed"?!Object.hasOwn(e,"authorization")||e.authorization===void 0:An(e.authorization)?e.resolution==="resolved"?["succeeded","failed"].includes(e.authorization.processing_status):e.resolution==="pending"?e.authorization.processing_status==="processing":e.resolution==="unknown"&&e.authorization.processing_status==="indeterminate":!1}function Sn(e){return y(e,["charge_id","status"])&&k(e.charge_id)&&["processing","approved","declined"].includes(String(e.status))&&!Object.hasOwn(e,"final_receipt")}function In(e){return y(e,["operation_id","status"])&&O(e.operation_id)&&e.status==="recorded"}function wn(e,n){return!y(e,["deadline_at","decision_id"])||!m(e.deadline_at)||!O(e.decision_id)?!1:n===200?e.decision==="approved"&&e.status==="approved"&&k(e.charge_id)&&m(e.decided_at):typeof e.error!="string"||typeof e.message!="string"||typeof e.request_id!="string"?!1:n===408&&e.error==="decision_deadline_exceeded"&&!Object.hasOwn(e,"decision")?!0:m(e.decided_at)&&(n===422&&e.decision==="declined"||n===408&&e.decision==="self_reversed_timeout")}function xn(e){if(!y(e,["binding_session_id","status","binding_url","expires_at","proof_policy"])||!h(e.binding_session_id,j)||e.status!=="pending"||typeof e.binding_url!="string"||!m(e.expires_at))return!1;let n=e.proof_policy;return y(n,["allowed_modes","challenge_after_facto_auth","challenge_delivery"],["card_selection_supported"])&&Array.isArray(n.allowed_modes)&&n.allowed_modes.length>0&&new Set(n.allowed_modes).size===n.allowed_modes.length&&n.allowed_modes.every(r=>r==="provider_reauthentication"||r==="provider_second_channel")&&n.challenge_after_facto_auth===!0&&(n.challenge_delivery==="browser_handoff"||n.challenge_delivery==="provider_backend")&&(n.card_selection_supported===void 0||n.card_selection_supported===!0)}function be(e){if(!w(e)||!h(e.binding_session_id,j)||!m(e.expires_at))return!1;let n=["binding_session_id","status","expires_at"];return["pending","proof_pending","consent_pending"].includes(String(e.status))?y(e,n)&&!["outcome","binding_ids","failure_reason","completed_at"].some(r=>Object.hasOwn(e,r)):e.status==="completed"?Object.hasOwn(e,"completed_at")&&!m(e.completed_at)?!1:e.outcome==="bound"?y(e,[...n,"outcome","binding_ids"],["completed_at"])&&!Object.hasOwn(e,"failure_reason")&&J(e.binding_ids):e.outcome==="declined"&&y(e,[...n,"outcome","failure_reason"],["completed_at"])&&!Object.hasOwn(e,"binding_ids")&&e.failure_reason==="declined_by_user":e.status==="cancelled"?y(e,n,["completed_at","failure_reason"])&&!["outcome","binding_ids"].some(r=>Object.hasOwn(e,r))&&(!Object.hasOwn(e,"completed_at")||m(e.completed_at))&&(!Object.hasOwn(e,"failure_reason")||["cancelled_by_user","cancelled_by_partner","proof_rejected","admission_closed","no_eligible_cards","integrity_conflict"].includes(String(e.failure_reason))):e.status==="expired"&&y(e,n,["failure_reason"])&&!["completed_at","outcome","binding_ids"].some(r=>Object.hasOwn(e,r))&&(!Object.hasOwn(e,"failure_reason")||e.failure_reason==="expired"||e.failure_reason==="proof_timeout")}function On(e){return y(e,["binding_session_id","status","proof_received_at"])&&h(e.binding_session_id,j)&&e.status==="consent_pending"&&m(e.proof_received_at)}function Rn(e){return y(e,["binding_session_id","facto_challenge","session_request_digest","expires_at"])&&h(e.binding_session_id,j)&&u(e.facto_challenge,1,512)&&h(e.session_request_digest,M)&&m(e.expires_at)}function vn(e){i(g(e,["requested_user_consents","return_uri"]),"Binding session requires the generated consent and return URI fields");let n=e.requested_user_consents;i(Array.isArray(n)&&n.length>0&&new Set(n).size===n.length&&n.every(r=>r==="card.metadata.view"||r==="card.use_for_facto_payments"),"Binding session consents are invalid"),i(typeof e.return_uri=="string"&&Buffer.byteLength(e.return_uri,"utf8")<=2048&&e.return_uri.startsWith("https://")&&!/[#\r\n]/.test(e.return_uri)&&e.return_uri.slice(8).split(/[/?]/,1)[0].length>0&&!e.return_uri.slice(8).split(/[/?]/,1)[0].includes("@"),"An exact registered HTTPS return URI is required")}function Ae(e){i(g(e,["proof_format","binding_assertion"])&&e.proof_format==="compact-jws"&&typeof e.binding_assertion=="string"&&e.binding_assertion.length>=128&&e.binding_assertion.length<=16384&&/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e.binding_assertion),"The original compact JWS provider proof is required")}function kn(e){return y(e,["id","revision","cards"])&&h(e.id,Z)&&h(e.revision,se)&&Array.isArray(e.cards)&&e.cards.every(n=>y(n,["binding_id","status","card"])&&h(n.binding_id,Q)&&typeof n.status=="string"&&we(n.card))}function En(e){return y(e,["id","status","revision","added_binding_ids","removed_binding_ids","kept_binding_ids"])&&h(e.id,Z)&&["applied","no_change"].includes(String(e.status))&&h(e.revision,se)&&J(e.added_binding_ids)&&J(e.removed_binding_ids)&&J(e.kept_binding_ids)}function zn(e){return y(e,["id","status"])&&h(e.id,Z)&&e.status==="cancelled"}function Pn(e){return e===void 0||y(e,["configured","state"],["reason"])&&typeof e.configured=="boolean"&&["ready","not_configured","unavailable"].includes(String(e.state))&&(e.reason===void 0||e.reason===null||typeof e.reason=="string")}function Tn(e){if(!y(e,["binding"],["found"])||e.found!==void 0&&typeof e.found!="boolean")return!1;let n=e.binding;return n===null?e.found!==!0:(e.found===void 0||e.found===!0)&&y(n,["id","status","revision","card"],["funding"])&&h(n.id,Q)&&typeof n.status=="string"&&G(n.revision,1)&&we(n.card)&&Pn(n.funding)}function Dn(e){return y(e,["items"])&&Array.isArray(e.items)&&e.items.every(n=>y(n,["id","event_kind","binding_id","binding_revision","connection_sequence","delivery_attempts","last_delivery_error","dead_lettered_at","replay_count"])&&h(n.id,te)&&typeof n.event_kind=="string"&&h(n.binding_id,Q)&&G(n.binding_revision,1)&&(n.connection_sequence===null||typeof n.connection_sequence=="number"&&Number.isSafeInteger(n.connection_sequence)&&n.connection_sequence>=1)&&G(n.delivery_attempts,1)&&Ie(n.last_delivery_error)&&(n.dead_lettered_at===null||m(n.dead_lettered_at))&&G(n.replay_count,0))}function qn(e){return y(e,["id","status"])&&O(e.id)&&e.status==="accepted"}function Ln(e){return y(e,["delivery_id","disposition","effect"])&&O(e.delivery_id)&&(e.disposition==="duplicate"?e.effect===null:e.disposition==="applied"&&["revoked","status_updated","released","none"].includes(String(e.effect)))}function Bn(e){i(g(e,["intent_token","approval_id","approval_sha256","revision","cards"],["external_account_id"])&&E(e.intent_token,32,8192)&&u(e.approval_id,1,255)&&h(e.approval_sha256,re)&&h(e.revision,se)&&N(e.external_account_id,n=>typeof n=="string"&&n.length>0&&Buffer.byteLength(n,"utf8")<=512),"Card replacement requires the original complete approved request"),i(Array.isArray(e.cards)&&e.cards.length<=50&&e.cards.every(n=>g(n,["external_card_id"],["network","type","last4"])&&F(n.external_card_id,255)&&N(n.network,r=>F(r,40))&&N(n.type,r=>r==="virtual"||r==="physical"||r==="unknown")&&N(n.last4,r=>typeof r=="string"&&/^[0-9]{4}$/.test(r))),"Target cards must match the generated safe card projection")}function Nn(e){i(g(e,["delivery_id","kind","assertion_jws"],["external_card_id","lifecycle_status","external_account_id"])&&O(e.delivery_id)&&typeof e.assertion_jws=="string"&&e.assertion_jws.trim().length>=32,"Inbound event requires a UUID delivery_id and signed assertion_jws");let n=r=>r==null;i(e.kind==="account.released"?u(e.external_account_id,1,512)&&n(e.external_card_id)&&n(e.lifecycle_status):F(e.external_card_id)&&n(e.external_account_id)&&(e.kind==="card.unbound"?n(e.lifecycle_status):e.kind==="card.lifecycle_changed"&&sn.includes(String(e.lifecycle_status))),"Inbound event fields must match the declared event kind")}function P(e){return i(e&&E(e.idempotencyKey,16,255),"An explicit original Idempotency-Key of 16 to 255 characters is required"),e.idempotencyKey}function V(e){return i(h(e,j),"id must be the original binding session identifier"),`/api/card/connect/sessions/${e}`}function oe(e){return i(h(e,Z),"id must be the original connect intent identifier"),`/api/card/connect/intents/${e}`}function Ce(e){return i(e?.rawBody===void 0||typeof e?.rawBody=="string","rawBody must preserve the original authenticated request bytes"),e?.rawBody}function rt(e){i(g(e,["environment","connectionId","programId","apiKeyId","apiKeySecret"],[...ce,"nowSeconds","createNonce"]),"Card client options cannot contain human session or arbitrary authentication fields"),i(typeof e.connectionId=="string"&&K.test(e.connectionId),"connectionId must be a pconn_ connection identifier"),i(u(e.programId,1,128)&&E(e.apiKeyId),"programId and apiKeyId are required");let n=W(e.apiKeySecret),r=_e(e,"program"),t=Object.freeze({connectionId:e.connectionId,environment:e.environment,programId:e.programId}),c=e.apiKeyId,_=e.nowSeconds??(()=>Math.floor(Date.now()/1e3)),A=e.createNonce??rn;function f(s,a,o,p="POST"){let d=_(),l=A();return i(Number.isSafeInteger(d)&&d>=1e9&&d<=9999999999,"nowSeconds must return a ten-digit Unix timestamp in seconds"),i(E(l,1,128),"createNonce must return a bounded canonical nonce"),ie({secret:n,apiKeyId:c,method:p,target:s,timestamp:d,nonce:l,body:a,idempotencyKey:o})}return Object.freeze({scope:t,sessions:Object.freeze({async create(s,a){vn(s),i(g(a,["idempotencyKey"],["cardSelection","signal"]),"Binding session create options accept only idempotencyKey, optional cardSelection, and optional signal");let o=P(a);i(a.cardSelection===void 0||typeof a.cardSelection=="boolean","cardSelection must be a boolean when provided");let p={...s,program_ref:t.programId},d=JSON.stringify(p),l="/api/card/connect/sessions",C=f(l,d,o);return a.cardSelection===!0&&C.set("x-facto-card-selection","1"),r("POST",l,C,d,[201],xn,a)},async get(s,a){let o=V(s),p=await r("GET",o,f(o,"",void 0,"GET"),void 0,[200],be,a);if(p.binding_session_id!==s)throw x(200);return p},async submitProof(s,a,o){let p=`${V(s)}/provider-proof`,d=P(o);i(w(a),"Provider proof input is required");let l;if(Object.hasOwn(a,"proof_format")||Object.hasOwn(a,"binding_assertion"))Ae(a),l=a;else{i(!["environment","programId","bindingSessionId","connectionId"].some(X=>Object.hasOwn(a,X)),"Provider proof assertion inherits environment, programId, and bindingSessionId from client scope and session id, and requires explicit providerConnectionId (pc_...)");let T=a,R=T.issuedAtSeconds??_();l={proof_format:"compact-jws",binding_assertion:await he({...T,environment:t.environment,programId:t.programId,bindingSessionId:s,issuedAtSeconds:R})},Ae(l)}let C=JSON.stringify(l),S=await r("POST",p,f(p,C,d),C,[202],On,o);if(S.binding_session_id!==s)throw x(202);return S},async getProofChallenge(s,a){let o=`${V(s)}/proof-challenge`,p=await r("GET",o,f(o,"",void 0,"GET"),void 0,[200],Rn,a);if(p.binding_session_id!==s)throw x(200);return p},async cancel(s,a){let o=`${V(s)}/cancel`,p=P(a),d=Ce(a)??"{}",l=await r("POST",o,f(o,d,p),d,[200],be,a);if(l.binding_session_id!==s)throw x(200);return l}}),intents:Object.freeze({async listCards(s,a){let o=`${oe(s)}/cards`;i(g(a,["intentToken"],["signal"])&&E(a.intentToken,32,8192),"intentToken must be a valid HTTP header value of at least 32 characters");let p=f(o,"",void 0,"GET");p.set("x-facto-intent-token",a.intentToken);let d=await r("GET",o,p,void 0,[200],kn,a);if(d.id!==s)throw x(200);return d},async replaceCards(s,a,o){let p=`${oe(s)}/cards`;Bn(a);let d=P(o),l=JSON.stringify(a),C=await r("PUT",p,f(p,l,d,"PUT"),l,[200],En,o);if(C.id!==s)throw x(200);return C},async cancel(s,a,o){let p=`${oe(s)}/cancel`;i(g(a,["intent_token"])&&E(a.intent_token,32,8192),"Cancel requires the original intent_token body of at least 32 characters");let d=JSON.stringify(a),l=await r("POST",p,f(p,d),d,[200],zn,o);if(l.id!==s)throw x(200);return l}}),bindings:Object.freeze({async lookup(s,a){i(g(s,["external_card_id"])&&F(s.external_card_id),"Binding lookup requires only an opaque external_card_id in its body");let o=JSON.stringify(s),p="/api/card/bindings/lookup";return r("POST",p,f(p,o),o,[200],Tn,a)}}),authorizations:Object.freeze({create:(async(s,a)=>{fn(s);let o=P(a),p={...s,program_id:t.programId},d=JSON.stringify(p),l="/api/card/authorizations";return s.decision_mode==="synchronous"?r("POST",l,f(l,d,o),d,[200,422,408],wn,a):r("POST",l,f(l,d,o),d,[200],Sn,a)}),async recordFact(s,a,o){gn(s,a);let p=P(o),d={...a,program_id:t.programId},l=JSON.stringify(d),C=`/api/card/authorizations/${encodeURIComponent(s)}/facts`;return r("POST",C,f(C,l,p),l,[200],In,o)},async lookup(s,a){let o=yn(s),p={program_id:t.programId,criteria:o},d=JSON.stringify(p),l="/api/card/authorizations/lookup",C=await r("POST",l,f(l,d),d,[200],Cn,a),S=C.authorization;if(S&&(S.origin_connection_id!==t.connectionId||o.by==="charge_id"&&S.charge_id?.toLowerCase()!==o.charge_id.toLowerCase()||o.by==="external_authorization_id"&&(S.external_authorization_id!==o.external_authorization_id||S.resource_version!==o.resource_version||S.mapping_revision!==o.mapping_revision||o.fact_type!==void 0&&S.operation_type!==void 0&&S.operation_type!==o.fact_type)||o.by==="supplier_transaction_id"&&(S.supplier_transaction_id!==o.supplier_transaction_id.trim()||S.resource_version!==o.resource_version||S.mapping_revision!==o.mapping_revision||o.fact_type!==void 0&&S.operation_type!==void 0&&S.operation_type!==o.fact_type)))throw x(200);return C}}),events:Object.freeze({async record(s,a){Nn(s);let o=JSON.stringify(s),p="/api/card/events",d=await r("POST",p,f(p,o),o,[200],Ln,a),l=s.kind==="card.unbound"?"revoked":s.kind==="card.lifecycle_changed"?"status_updated":"released";if(d.delivery_id!==s.delivery_id||d.disposition==="applied"&&d.effect!=="none"&&d.effect!==l)throw x(200);return d}}),deliveries:Object.freeze({async list(s,a){_n(s);let o={...s,program_id:t.programId},p=JSON.stringify(o),d="/api/card/deliveries/reconciliations/list",l=await r("POST",d,f(d,p),p,[200],pn,a);if(l.items.length>s.page_size)throw x(200);return l}}),deliveryReplays:Object.freeze({async create(s,a){i(g(s,["selection_id"])&&O(s.selection_id),"Delivery replay requires a fixed selection_id UUID");let o=P(a),p={...s,program_id:t.programId},d=JSON.stringify(p),l="/api/card/deliveries/replays",C=await r("POST",l,f(l,d,o),d,[202],ln,a);if(C.selection_id!==s.selection_id)throw x(202);return C}}),deadLetters:Object.freeze({async list(s,a){i(s===void 0||g(s,[],["limit"])&&N(s.limit,l=>typeof l=="number"&&Number.isInteger(l)&&l>=1&&l<=100),"Dead-letter limit must be null, absent, or an integer from 1 to 100");let o=typeof s?.limit=="number"?s.limit:void 0,p=o!==void 0?`/api/card/deliveries/dead-letters?limit=${o}`:"/api/card/deliveries/dead-letters",d=await r("GET",p,f(p,"",void 0,"GET"),void 0,[200],Dn,a);if(d.items.length>(o??50))throw x(200);return d},async replay(s,a){i(O(s),"The dead-letter path identifier must be a UUID");let o=`/api/card/deliveries/dead-letters/${s}/replay`,p=Ce(a),d=await r("POST",o,f(o,p??""),p,[202],qn,a);if(d.id!==s)throw x(202);return d}})})}export{I as a,Fn as b,pe as c,le as d,Fe as e,he as f,ie as g,Qn as h,rt as i};
|