@flopay/js 1.4.2 → 1.4.4

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/dist/index.mjs CHANGED
@@ -1,3757 +1 @@
1
- // src/load.ts
2
- import { FloPayError as FloPayError6, resolveBillingApiUrl as resolveBillingApiUrl3, SDK_VERSION as SDK_VERSION4 } from "@flopay/shared";
3
-
4
- // src/stripe-adapter.ts
5
- import { loadStripe } from "@stripe/stripe-js";
6
- import { FloPayError as FloPayError2, isSetupIntentClientSecret } from "@flopay/shared";
7
-
8
- // src/payment-api.ts
9
- import {
10
- FloPayError,
11
- SDK_VERSION,
12
- FLO_SDK_VERSION_HEADER,
13
- IDEMPOTENCY_KEY_HEADER,
14
- IDEMPOTENCY_IN_PROGRESS_CODE,
15
- buildProductPayload,
16
- foldIntoProducts,
17
- isUuidV4,
18
- randomUuidV4,
19
- resolveIdempotencyKey,
20
- resolveSessionCurrency
21
- } from "@flopay/shared";
22
-
23
- // src/api-error.ts
24
- function readErrorString(value) {
25
- return typeof value === "string" && value.trim() ? value : void 0;
26
- }
27
- function readErrorMessage(value) {
28
- if (typeof value === "string") return value.trim() ? value : void 0;
29
- if (Array.isArray(value)) {
30
- const joined = value.filter((entry) => typeof entry === "string" && entry.trim().length > 0).join("; ");
31
- return joined || void 0;
32
- }
33
- return void 0;
34
- }
35
-
36
- // src/session-display-cache.ts
37
- var STORAGE_KEY_PREFIX = "flopay_session_display:";
38
- var DEFAULT_TTL_MS = 60 * 60 * 1e3;
39
- var memoryStore = /* @__PURE__ */ new Map();
40
- function storageKey(sessionId) {
41
- return `${STORAGE_KEY_PREFIX}${sessionId}`;
42
- }
43
- function getSessionStorage() {
44
- if (typeof window === "undefined") return null;
45
- try {
46
- return window.sessionStorage;
47
- } catch {
48
- return null;
49
- }
50
- }
51
- function cacheSessionDisplayData(sessionId, data, options) {
52
- if (!sessionId) return;
53
- const ttl = options?.ttlMs ?? DEFAULT_TTL_MS;
54
- const entry = { data, expiresAt: Date.now() + ttl };
55
- const storage = getSessionStorage();
56
- if (storage) {
57
- try {
58
- storage.setItem(storageKey(sessionId), JSON.stringify(entry));
59
- return;
60
- } catch {
61
- }
62
- }
63
- memoryStore.set(sessionId, entry);
64
- }
65
- function getSessionDisplayData(sessionId) {
66
- if (!sessionId) return null;
67
- const storage = getSessionStorage();
68
- if (storage) {
69
- try {
70
- const raw = storage.getItem(storageKey(sessionId));
71
- if (raw) {
72
- const entry = JSON.parse(raw);
73
- if (entry && typeof entry.expiresAt === "number" && entry.expiresAt > Date.now()) {
74
- return entry.data;
75
- }
76
- storage.removeItem(storageKey(sessionId));
77
- }
78
- } catch {
79
- }
80
- }
81
- const memEntry = memoryStore.get(sessionId);
82
- if (memEntry) {
83
- if (memEntry.expiresAt > Date.now()) {
84
- return memEntry.data;
85
- }
86
- memoryStore.delete(sessionId);
87
- }
88
- return null;
89
- }
90
- function clearSessionDisplayData(sessionId) {
91
- if (!sessionId) return;
92
- memoryStore.delete(sessionId);
93
- const storage = getSessionStorage();
94
- if (storage) {
95
- try {
96
- storage.removeItem(storageKey(sessionId));
97
- } catch {
98
- }
99
- }
100
- }
101
-
102
- // src/telemetry-reporter.ts
103
- import {
104
- buildTelemetryErrorEvent,
105
- buildTelemetryLogEvent,
106
- buildTelemetryPerformanceEvent,
107
- buildTelemetryTerminalEvent,
108
- serializeTelemetryBatch,
109
- TELEMETRY_MAX_BATCH_BYTES
110
- } from "@flopay/shared";
111
- var TELEMETRY_PATH = "/v1/sdk-telemetry/events";
112
- var MAX_BATCH_SIZE = 16;
113
- var MAX_QUEUE_SIZE = 64;
114
- var UPLOAD_TIMEOUT_MS = 1500;
115
- var ERROR_DEDUPLICATION_WINDOW_MS = 1e3;
116
- var MAX_REPORTED_FAILURES = 64;
117
- var DEDUPLICATION_EVENT_ID = "00000000-0000-4000-8000-000000000000";
118
- var EVENT_BUDGETS = {
119
- technical_error: 8,
120
- lifecycle: 32,
121
- expected_outcome: 32,
122
- performance: 24
123
- };
124
- function createUuidV4() {
125
- try {
126
- return globalThis.crypto.randomUUID();
127
- } catch {
128
- const bytes = new Uint8Array(16);
129
- try {
130
- globalThis.crypto.getRandomValues(bytes);
131
- } catch {
132
- for (let index = 0; index < bytes.length; index += 1) {
133
- bytes[index] = Math.floor(Math.random() * 256);
134
- }
135
- }
136
- bytes[6] = bytes[6] & 15 | 64;
137
- bytes[8] = bytes[8] & 63 | 128;
138
- const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
139
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
140
- }
141
- }
142
- function bodyByteLength(body) {
143
- try {
144
- return new TextEncoder().encode(body).byteLength;
145
- } catch {
146
- return body.length;
147
- }
148
- }
149
- function failureDeduplicationKey(event) {
150
- return JSON.stringify([
151
- event.code,
152
- event.stage,
153
- event.provider,
154
- event.attempt,
155
- event.statusClass,
156
- event.requestCategory,
157
- event.paymentMethodCategory,
158
- event.checkoutMode,
159
- event.layout
160
- ]);
161
- }
162
- function telemetryNow() {
163
- return globalThis.performance?.now() ?? 0;
164
- }
165
- var TelemetryReporter = class {
166
- constructor(options) {
167
- this.ingestionDisabled = false;
168
- this.queue = [];
169
- this.sequence = 0;
170
- this.flushTimer = null;
171
- this.flushInFlight = null;
172
- this.reportedFailures = /* @__PURE__ */ new Map();
173
- this.checkoutContext = {};
174
- this.checkoutStartedAt = null;
175
- this.destroyed = false;
176
- this.pageExitHandler = () => {
177
- this.drainQueue();
178
- };
179
- this.visibilityHandler = () => {
180
- if (document.visibilityState === "hidden") void this.flush();
181
- };
182
- this.eventCounts = {
183
- technical_error: 0,
184
- lifecycle: 0,
185
- expected_outcome: 0,
186
- performance: 0
187
- };
188
- this.endpoint = `${options.billingApiUrl.replace(/\/+$/, "")}${TELEMETRY_PATH}`;
189
- this.sdkPackage = options.sdkPackage ?? "@flopay/js";
190
- this.sdkVersion = options.sdkVersion;
191
- this.correlationId = createUuidV4();
192
- this.merchantEnabled = options.enabled !== false;
193
- this.clock = options.clock ?? telemetryNow;
194
- this.browserTransportAvailable = typeof window !== "undefined" && typeof document !== "undefined";
195
- if (this.browserTransportAvailable) {
196
- window.addEventListener("pagehide", this.pageExitHandler);
197
- document.addEventListener("visibilitychange", this.visibilityHandler);
198
- }
199
- }
200
- log(input) {
201
- if (!this.canCollect()) return;
202
- this.enqueue(buildTelemetryLogEvent({
203
- ...this.checkoutContext,
204
- ...input,
205
- eventId: createUuidV4(),
206
- sequence: this.sequence++
207
- }));
208
- }
209
- error(input) {
210
- if (!this.canCollect()) return;
211
- const normalizedFailure = buildTelemetryErrorEvent({
212
- ...this.checkoutContext,
213
- ...input,
214
- eventId: DEDUPLICATION_EVENT_ID,
215
- sequence: 0
216
- });
217
- const deduplicationKey = failureDeduplicationKey(normalizedFailure);
218
- const now = this.now();
219
- this.pruneReportedFailures(now);
220
- const previouslyReportedAt = this.reportedFailures.get(deduplicationKey);
221
- if (previouslyReportedAt !== void 0 && now >= previouslyReportedAt && now - previouslyReportedAt < ERROR_DEDUPLICATION_WINDOW_MS) {
222
- this.log({
223
- name: "operation.deduplicated",
224
- stage: input.stage,
225
- provider: input.provider,
226
- paymentMethodCategory: input.paymentMethodCategory,
227
- attempt: input.attempt
228
- });
229
- return;
230
- }
231
- this.rememberReportedFailure(deduplicationKey, now);
232
- this.enqueue(buildTelemetryErrorEvent({
233
- ...this.checkoutContext,
234
- ...input,
235
- eventId: createUuidV4(),
236
- sequence: this.sequence++
237
- }));
238
- }
239
- performance(input) {
240
- if (!this.canCollect()) return;
241
- this.enqueue(buildTelemetryPerformanceEvent({
242
- ...this.checkoutContext,
243
- ...input,
244
- eventId: createUuidV4(),
245
- sequence: this.sequence++
246
- }));
247
- }
248
- terminal(input) {
249
- if (!this.canCollect()) return;
250
- this.enqueue(buildTelemetryTerminalEvent({
251
- ...this.checkoutContext,
252
- ...input,
253
- eventId: createUuidV4(),
254
- sequence: this.sequence++
255
- }));
256
- if (input.outcome !== "action_required" && this.checkoutStartedAt !== null) {
257
- const checkoutStartedAt = this.checkoutStartedAt;
258
- this.checkoutStartedAt = null;
259
- this.performance({
260
- stage: "total_journey",
261
- durationMs: Math.max(0, this.now() - checkoutStartedAt),
262
- durationMode: "total",
263
- provider: input.provider,
264
- paymentMethodCategory: input.paymentMethodCategory
265
- });
266
- }
267
- }
268
- /** @internal Read the reporter's monotonic clock without Resource Timing. */
269
- now() {
270
- try {
271
- return this.clock();
272
- } catch {
273
- return telemetryNow();
274
- }
275
- }
276
- pruneReportedFailures(now) {
277
- for (const [key, reportedAt] of this.reportedFailures) {
278
- if (now < reportedAt || now - reportedAt >= ERROR_DEDUPLICATION_WINDOW_MS) {
279
- this.reportedFailures.delete(key);
280
- }
281
- }
282
- }
283
- rememberReportedFailure(key, reportedAt) {
284
- while (this.reportedFailures.size >= MAX_REPORTED_FAILURES) {
285
- const oldest = this.reportedFailures.keys().next();
286
- if (oldest.done) break;
287
- this.reportedFailures.delete(oldest.value);
288
- }
289
- this.reportedFailures.set(key, reportedAt);
290
- }
291
- /** @internal Add closed checkout dimensions to subsequent SDK events. */
292
- setCheckoutContext(context) {
293
- this.checkoutContext = {
294
- checkoutMode: context.checkoutMode,
295
- layout: context.layout
296
- };
297
- }
298
- /** @internal Start a fresh checkout budget, dedupe window, and total span. */
299
- beginCheckout(context = {}) {
300
- if (!this.canCollect()) return 0;
301
- this.drainQueue();
302
- this.setCheckoutContext(context);
303
- this.sequence = 0;
304
- this.reportedFailures.clear();
305
- this.eventCounts = {
306
- technical_error: 0,
307
- lifecycle: 0,
308
- expected_outcome: 0,
309
- performance: 0
310
- };
311
- this.checkoutStartedAt = this.now();
312
- return this.checkoutStartedAt;
313
- }
314
- enqueue(event) {
315
- if (!this.canCollect()) return;
316
- if (this.queue.length >= MAX_QUEUE_SIZE || this.eventCounts[event.class] >= EVENT_BUDGETS[event.class]) return;
317
- this.eventCounts[event.class] += 1;
318
- this.queue.push(event);
319
- if (this.queue.length >= MAX_BATCH_SIZE) {
320
- void this.flush();
321
- return;
322
- }
323
- this.scheduleFlush();
324
- }
325
- canCollect() {
326
- return this.browserTransportAvailable && this.merchantEnabled && !this.ingestionDisabled && !this.destroyed;
327
- }
328
- /** Flush one bounded batch. Failures are intentionally dropped. */
329
- async flush() {
330
- if (this.flushInFlight) return this.flushInFlight;
331
- if (!this.browserTransportAvailable || this.destroyed || this.ingestionDisabled || this.queue.length === 0) return;
332
- this.clearFlushTimer();
333
- const events = this.queue.splice(0, MAX_BATCH_SIZE);
334
- this.flushInFlight = this.sendBatch(events).finally(() => {
335
- this.flushInFlight = null;
336
- if (this.queue.length > 0) this.scheduleFlush();
337
- });
338
- return this.flushInFlight;
339
- }
340
- /** Flush pending work and detach browser lifecycle listeners. */
341
- destroy() {
342
- if (this.destroyed) return;
343
- this.drainQueue();
344
- this.destroyed = true;
345
- this.clearFlushTimer();
346
- if (this.browserTransportAvailable) {
347
- window.removeEventListener("pagehide", this.pageExitHandler);
348
- document.removeEventListener("visibilitychange", this.visibilityHandler);
349
- }
350
- this.queue.splice(0);
351
- this.reportedFailures.clear();
352
- }
353
- /** Permanently honor a merchant opt-out and discard queued events. */
354
- disable() {
355
- this.merchantEnabled = false;
356
- this.queue.splice(0);
357
- this.reportedFailures.clear();
358
- this.clearFlushTimer();
359
- }
360
- /** Start every bounded keepalive request synchronously before page teardown. */
361
- drainQueue() {
362
- if (!this.browserTransportAvailable || this.destroyed || this.ingestionDisabled || this.queue.length === 0) return;
363
- this.clearFlushTimer();
364
- while (this.queue.length > 0) {
365
- const events = this.queue.splice(0, MAX_BATCH_SIZE);
366
- void this.sendBatch(events);
367
- }
368
- }
369
- async sendBatch(events) {
370
- if (!this.browserTransportAvailable || this.ingestionDisabled) return;
371
- const body = serializeTelemetryBatch(events, {
372
- correlationId: this.correlationId,
373
- sdkPackage: this.sdkPackage,
374
- sdkVersion: this.sdkVersion,
375
- batchId: createUuidV4()
376
- });
377
- if (bodyByteLength(body) > TELEMETRY_MAX_BATCH_BYTES) return;
378
- const controller = typeof AbortController === "undefined" ? null : new AbortController();
379
- let timeout = null;
380
- try {
381
- const request = fetch(this.endpoint, {
382
- method: "POST",
383
- headers: { "content-type": "text/plain;charset=UTF-8" },
384
- body,
385
- credentials: "omit",
386
- keepalive: true,
387
- referrerPolicy: "no-referrer",
388
- signal: controller?.signal
389
- }).then(async (response) => {
390
- if (response.status !== 202) return null;
391
- const payload = await response.json().catch(() => null);
392
- return payload?.status === "disabled" ? "disabled" : null;
393
- }).catch(() => null);
394
- const expired = new Promise((resolve) => {
395
- timeout = setTimeout(() => {
396
- controller?.abort();
397
- resolve(null);
398
- }, UPLOAD_TIMEOUT_MS);
399
- });
400
- const status = await Promise.race([request, expired]);
401
- if (status === "disabled") this.disableFromIngestion();
402
- } catch {
403
- } finally {
404
- if (timeout) clearTimeout(timeout);
405
- }
406
- }
407
- disableFromIngestion() {
408
- this.ingestionDisabled = true;
409
- this.queue.splice(0);
410
- this.reportedFailures.clear();
411
- this.clearFlushTimer();
412
- }
413
- scheduleFlush() {
414
- if (this.flushTimer || this.destroyed || this.ingestionDisabled) return;
415
- this.flushTimer = setTimeout(() => {
416
- this.flushTimer = null;
417
- void this.flush();
418
- }, 0);
419
- }
420
- clearFlushTimer() {
421
- if (!this.flushTimer) return;
422
- clearTimeout(this.flushTimer);
423
- this.flushTimer = null;
424
- }
425
- };
426
- var TELEMETRY_REPORTER_FACTORY = /* @__PURE__ */ Symbol.for("@flopay/js.telemetry.reporter-factory.v1");
427
- var telemetryGlobal = globalThis;
428
- if (telemetryGlobal[TELEMETRY_REPORTER_FACTORY] === void 0) {
429
- Object.defineProperty(telemetryGlobal, TELEMETRY_REPORTER_FACTORY, {
430
- configurable: true,
431
- enumerable: false,
432
- writable: false,
433
- value: (options) => new TelemetryReporter(options)
434
- });
435
- }
436
-
437
- // src/payment-api.ts
438
- var DEFAULT_PROCESSING_RETRY_AFTER_MS = 1e3;
439
- var MIN_PROCESSING_RETRY_AFTER_MS = 500;
440
- var DEFAULT_PROCESSING_TIMEOUT_MS = 15e3;
441
- var MAX_PROCESSING_RETRY_AFTER_MS = 3e3;
442
- var DEFAULT_ACCOUNT_SNAPSHOT_TIMEOUT_MS = 1e4;
443
- function isRecord(value) {
444
- return typeof value === "object" && value !== null;
445
- }
446
- function telemetryStatusClass(status) {
447
- if (status === void 0) return "network_error";
448
- const statusClass = `${Math.floor(status / 100)}xx`;
449
- return statusClass === "2xx" || statusClass === "3xx" || statusClass === "4xx" || statusClass === "5xx" ? statusClass : "unknown";
450
- }
451
- function telemetryFailure(error, fallbackCode) {
452
- if (error instanceof Error && (error.name === "AbortError" || error instanceof FloPayError && error.code === "checkout_processing_timeout")) {
453
- return { errorCode: "REQUEST_TIMEOUT", statusClass: "timeout" };
454
- }
455
- if (error instanceof TypeError) {
456
- return { errorCode: "NETWORK_REQUEST_FAILED", statusClass: "network_error" };
457
- }
458
- return {
459
- errorCode: fallbackCode,
460
- statusClass: telemetryStatusClass(
461
- error instanceof FloPayError ? error.statusCode : void 0
462
- )
463
- };
464
- }
465
- function readString(payload, key) {
466
- return readErrorString(payload?.[key]);
467
- }
468
- function readMessage(payload, key) {
469
- return readErrorMessage(payload?.[key]);
470
- }
471
- function readNumber(payload, key) {
472
- const value = payload?.[key];
473
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
474
- }
475
- function delay(ms) {
476
- return new Promise((resolve) => setTimeout(resolve, ms));
477
- }
478
- function createCheckoutProcessingTimeoutError() {
479
- return new FloPayError(
480
- "Checkout is still processing. Please try again shortly.",
481
- "api_error",
482
- { code: "checkout_processing_timeout" }
483
- );
484
- }
485
- async function buildApiErrorFromResponse(response, fallbackMessage) {
486
- const payload = await response.json().catch(() => null);
487
- const nestedError = isRecord(payload?.error) ? payload.error : null;
488
- const message = readMessage(payload, "message") ?? readMessage(nestedError, "message") ?? fallbackMessage;
489
- const code = readString(payload, "code") ?? readString(payload, "gatewayErrorCode") ?? readString(nestedError, "code") ?? `http_${response.status}`;
490
- return new FloPayError(message, "api_error", {
491
- code,
492
- statusCode: response.status
493
- });
494
- }
495
- var NETWORK_RETRY_ATTEMPTS = 2;
496
- var IDEMPOTENCY_IN_PROGRESS_RETRY_ATTEMPTS = 2;
497
- async function fetchWithNetworkRetry(input, init, attempts = NETWORK_RETRY_ATTEMPTS, onRetry) {
498
- let lastErr;
499
- for (let attempt = 0; ; attempt++) {
500
- try {
501
- return await fetch(input, init);
502
- } catch (err) {
503
- if (err instanceof Error && err.name === "AbortError") throw err;
504
- lastErr = err;
505
- if (attempt >= attempts) throw lastErr;
506
- try {
507
- onRetry?.(attempt + 1);
508
- } catch {
509
- }
510
- await delay(150 * 2 ** attempt);
511
- }
512
- }
513
- }
514
- function isPaymentApiTelemetryHooks(value) {
515
- return "now" in value || "onFirstByte" in value || "onSessionCreateFailure" in value || "onRetry" in value;
516
- }
517
- var PaymentAPI = class {
518
- constructor(billingApiUrl, telemetryOptionsOrHooks = {}) {
519
- this.baseUrl = billingApiUrl.replace(/\/+$/, "");
520
- const hasInternalHooks = isPaymentApiTelemetryHooks(telemetryOptionsOrHooks);
521
- this.telemetryHooks = hasInternalHooks ? telemetryOptionsOrHooks : void 0;
522
- this.directTelemetry = hasInternalHooks || telemetryOptionsOrHooks.telemetry === false ? void 0 : new TelemetryReporter({
523
- billingApiUrl: this.baseUrl,
524
- sdkVersion: SDK_VERSION
525
- });
526
- }
527
- /** Dispose the reporter owned by direct public usage. Internal hooks are never disposed here. */
528
- destroy() {
529
- this.directTelemetry?.destroy();
530
- }
531
- reportDirectFailure(error, fallbackCode, stage, requestCategory, paymentMethodCategory = "unknown") {
532
- const failure = telemetryFailure(error, fallbackCode);
533
- this.directTelemetry?.error({
534
- ...failure,
535
- stage,
536
- requestCategory,
537
- paymentMethodCategory
538
- });
539
- }
540
- telemetryTimestamp() {
541
- try {
542
- return this.telemetryHooks?.now?.() ?? this.directTelemetry?.now() ?? telemetryNow();
543
- } catch {
544
- return telemetryNow();
545
- }
546
- }
547
- beginDirectTelemetryCheckout(checkoutSessionId) {
548
- if (!this.directTelemetry || this.directTelemetryCheckoutId === checkoutSessionId) return;
549
- this.directTelemetryCheckoutId = checkoutSessionId;
550
- this.directTelemetry.beginCheckout();
551
- }
552
- beginDirectTelemetryOperation() {
553
- if (!this.directTelemetry) return;
554
- this.directTelemetryCheckoutId = void 0;
555
- this.directTelemetry.beginCheckout();
556
- }
557
- adoptDirectTelemetryCheckout(checkoutSessionId) {
558
- if (checkoutSessionId) this.directTelemetryCheckoutId = checkoutSessionId;
559
- }
560
- /**
561
- * Fetch a raw checkout session by ID.
562
- *
563
- * `nonce` is the session-bound checkout token returned when the session
564
- * was created. When supplied it is sent as the `x-checkout-session-token`
565
- * header that post-#640 backends match against `checkout_session.nonce`
566
- * before returning the row — the UUID alone is no longer sufficient.
567
- * Backends that don't yet enforce it ignore the extra header.
568
- */
569
- async getCheckoutSession(checkoutSessionId, nonce) {
570
- this.beginDirectTelemetryCheckout(checkoutSessionId);
571
- const requestStarted = this.telemetryTimestamp();
572
- this.directTelemetry?.log({
573
- name: "session.read.started",
574
- stage: "session_read",
575
- requestCategory: "session_read"
576
- });
577
- const headers = { [FLO_SDK_VERSION_HEADER]: SDK_VERSION };
578
- if (nonce) headers["x-checkout-session-token"] = nonce;
579
- try {
580
- const response = await fetchWithNetworkRetry(
581
- `${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(checkoutSessionId)}`,
582
- { headers },
583
- NETWORK_RETRY_ATTEMPTS,
584
- (attempt) => {
585
- this.telemetryHooks?.onRetry?.("session_read", attempt);
586
- this.directTelemetry?.log({
587
- name: "operation.retry",
588
- stage: "session_read",
589
- requestCategory: "session_read",
590
- attempt
591
- });
592
- }
593
- );
594
- const firstByteDuration = Math.max(0, this.telemetryTimestamp() - requestStarted);
595
- try {
596
- this.telemetryHooks?.onFirstByte?.(firstByteDuration);
597
- } catch {
598
- }
599
- const statusClass = `${Math.floor(response.status / 100)}xx`;
600
- this.directTelemetry?.log({
601
- name: "session.request.first_byte",
602
- stage: "session_first_byte",
603
- requestCategory: "session_read",
604
- statusClass
605
- });
606
- this.directTelemetry?.performance({
607
- stage: "session_first_byte",
608
- durationMs: firstByteDuration,
609
- durationMode: "machine",
610
- requestCategory: "session_read",
611
- statusClass
612
- });
613
- if (!response.ok) {
614
- throw await buildApiErrorFromResponse(response, "Failed to get checkout session");
615
- }
616
- const body = await response.json();
617
- this.directTelemetry?.log({
618
- name: "session.request.completed",
619
- stage: "session_complete",
620
- requestCategory: "session_read",
621
- statusClass
622
- });
623
- this.directTelemetry?.performance({
624
- stage: "session_complete",
625
- durationMs: Math.max(0, this.telemetryTimestamp() - requestStarted),
626
- durationMode: "machine",
627
- requestCategory: "session_read",
628
- statusClass
629
- });
630
- return { ...body, data: this.mergeCachedDisplayData(body.data) };
631
- } catch (error) {
632
- const statusCode = error instanceof FloPayError ? error.statusCode : void 0;
633
- this.directTelemetry?.error({
634
- errorCode: error instanceof FloPayError && error.code === "checkout_processing_timeout" ? "REQUEST_TIMEOUT" : "NETWORK_REQUEST_FAILED",
635
- stage: "session_read",
636
- requestCategory: "session_read",
637
- statusClass: statusCode ? `${Math.floor(statusCode / 100)}xx` : "network_error"
638
- });
639
- throw error;
640
- }
641
- }
642
- /**
643
- * Stash display-only data for a session so subsequent fetches can fill in
644
- * fields the backend no longer persists (`overrideAmount`, `totalAmount`,
645
- * `providerItemName`, `providerPlanName`).
646
- *
647
- * Backed by `sessionStorage` in the browser, with an in-memory fallback in
648
- * Node/SSR contexts. Default TTL: 1 hour.
649
- *
650
- * Server-returned values always win — cached values fill in only where the
651
- * server returned `null` / `undefined`.
652
- *
653
- * @example
654
- * ```ts
655
- * paymentAPI.cacheSessionDisplayData(sessionId, {
656
- * currency: 'USD',
657
- * items: [{ code: 'pro_plan', overrideAmount: 24.99, providerItemName: 'Pro' }],
658
- * });
659
- * ```
660
- */
661
- cacheSessionDisplayData(sessionId, data, options) {
662
- cacheSessionDisplayData(sessionId, data, options);
663
- }
664
- /**
665
- * Drop any cached display data for a session. Call after the payment
666
- * completes; otherwise the TTL handles cleanup.
667
- */
668
- clearSessionDisplayData(sessionId) {
669
- clearSessionDisplayData(sessionId);
670
- }
671
- /**
672
- * Fetch (re-mint) the hosted vault capture widget for a session
673
- * (TeamFloPay/backend#823).
674
- *
675
- * `POST /v1/checkouts/sessions/{id}/vault/capture` returns the SDK-ready
676
- * {@link VaultCaptureBlock} (`html` + `url`, plus `messageToken` /
677
- * `expectedOrigin` once the backend mints them). The SDK injects `html` as
678
- * the card-capture widget. This is the fallback path for sessions that did
679
- * not receive the embedded `vault` block on create (e.g. a session loaded by
680
- * id via `GET`, or a pre-1.3.0 create); the endpoint is idempotent and reuses
681
- * session-cached creds when available.
682
- *
683
- * Because the endpoint is idempotent, the request is wrapped in
684
- * `fetchWithNetworkRetry`: a transient network blip (dropped connection, DNS
685
- * hiccup, failed CORS preflight) would otherwise leave the secure card form
686
- * unable to load and hard-block checkout.
687
- *
688
- * The PCIVault submit *secret* the backend may include in the response is
689
- * intentionally **not** read or surfaced — it is server-only and never enters
690
- * the SDK runtime.
691
- *
692
- * `nonce` is forwarded as `x-checkout-session-token` (required by post-#640
693
- * backends, matched against the session's stored nonce).
694
- */
695
- async getVaultCapture(checkoutSessionId, nonce) {
696
- this.beginDirectTelemetryCheckout(checkoutSessionId);
697
- const startedAt = this.telemetryTimestamp();
698
- this.directTelemetry?.log({
699
- name: "vault.capture.requested",
700
- stage: "vault_request",
701
- requestCategory: "vault_capture",
702
- paymentMethodCategory: "card"
703
- });
704
- const headers = { "Content-Type": "application/json" };
705
- if (nonce) headers["x-checkout-session-token"] = nonce;
706
- try {
707
- const response = await fetchWithNetworkRetry(
708
- `${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(checkoutSessionId)}/vault/capture`,
709
- { method: "POST", headers },
710
- NETWORK_RETRY_ATTEMPTS,
711
- (attempt) => {
712
- this.telemetryHooks?.onRetry?.("vault_capture", attempt);
713
- this.directTelemetry?.log({
714
- name: "operation.retry",
715
- stage: "vault_request",
716
- requestCategory: "vault_capture",
717
- paymentMethodCategory: "card",
718
- attempt
719
- });
720
- }
721
- );
722
- if (!response.ok) {
723
- throw await buildApiErrorFromResponse(response, "Failed to load the secure card form");
724
- }
725
- const block = await response.json();
726
- this.directTelemetry?.performance({
727
- stage: "vault_request",
728
- durationMs: Math.max(0, this.telemetryTimestamp() - startedAt),
729
- durationMode: "machine",
730
- requestCategory: "vault_capture",
731
- paymentMethodCategory: "card",
732
- statusClass: "2xx"
733
- });
734
- return this.toVaultBlock(block);
735
- } catch (error) {
736
- this.reportDirectFailure(
737
- error,
738
- "VAULT_LOAD_FAILED",
739
- "vault_request",
740
- "vault_capture",
741
- "card"
742
- );
743
- throw error;
744
- }
745
- }
746
- /**
747
- * Fetch and normalize a checkout session.
748
- *
749
- * Reads the backend's `gateways` map to enumerate provider-specific data,
750
- * then wraps the session in a `NormalizedCheckoutSession` for provider-
751
- * agnostic consumption.
752
- */
753
- async getUnifiedCheckoutSession(checkoutSessionId, nonce) {
754
- const res = await this.getCheckoutSession(checkoutSessionId, nonce);
755
- const normalized = this.normalizeRawSession(res.data);
756
- const vault = res.vault;
757
- if (vault && normalized.data.session) {
758
- normalized.data.session.vault = this.toVaultBlock(vault);
759
- }
760
- return normalized;
761
- }
762
- /**
763
- * Submit a tokenized payment to the billing backend.
764
- *
765
- * The backend will either succeed, return `type: '3ds_required'`
766
- * (with a `threeDSecureToken`), or return `type: 'paypal_redirect_required'`.
767
- *
768
- * Hits the session-scoped route `POST /v1/checkouts/sessions/:id/process`
769
- * and forwards `data.nonce` as `x-checkout-session-token`. Backend
770
- * `TeamFloPay/backend#640` rejects callers without a matching nonce with a
771
- * 401 — this method throws synchronously when `data.nonce` is missing so the
772
- * problem surfaces before the network round trip.
773
- *
774
- * @param userId Vestigial — backend's GatewayInterceptor routes via session,
775
- * not headers, so this value is no longer sent on the wire. Kept in the
776
- * signature for back-compat with existing callers; will be removed in a
777
- * future major version.
778
- */
779
- async processPayment(_userId, data, options) {
780
- this.beginDirectTelemetryCheckout(data.sessionId);
781
- if (!data.nonce) {
782
- this.directTelemetry?.terminal({
783
- outcome: "validation_rejected",
784
- stage: "processing",
785
- requestCategory: "process_payment"
786
- });
787
- throw new FloPayError(
788
- "processPayment requires `nonce` \u2014 pass the value returned from session creation.",
789
- "validation_error",
790
- { code: "MissingCheckoutSessionToken", param: "nonce" }
791
- );
792
- }
793
- const startedAt = this.telemetryTimestamp();
794
- this.directTelemetry?.log({
795
- name: "payment.processing.started",
796
- stage: "processing",
797
- requestCategory: "process_payment"
798
- });
799
- const { nonce, ...processBody } = data;
800
- let response;
801
- try {
802
- response = await fetch(
803
- `${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(data.sessionId)}/process`,
804
- {
805
- method: "POST",
806
- headers: {
807
- "Content-Type": "application/json",
808
- "x-checkout-session-token": nonce
809
- },
810
- body: JSON.stringify(processBody)
811
- }
812
- );
813
- } catch (error) {
814
- this.reportDirectFailure(
815
- error,
816
- "PAYMENT_PROCESSING_FAILED",
817
- "processing",
818
- "process_payment"
819
- );
820
- throw error;
821
- }
822
- if (!response.ok && response.status !== 202) {
823
- this.directTelemetry?.error({
824
- errorCode: "PAYMENT_PROCESSING_FAILED",
825
- stage: "processing",
826
- requestCategory: "process_payment",
827
- statusClass: telemetryStatusClass(response.status)
828
- });
829
- return response;
830
- }
831
- try {
832
- const result = await this.resolveProcessResponse(
833
- response,
834
- data.sessionId,
835
- { ...options, nonce }
836
- );
837
- this.directTelemetry?.log({
838
- name: "payment.processing.completed",
839
- stage: "processing",
840
- requestCategory: "process_payment",
841
- statusClass: telemetryStatusClass(result.status)
842
- });
843
- this.directTelemetry?.performance({
844
- stage: "processing",
845
- durationMs: Math.max(0, this.telemetryTimestamp() - startedAt),
846
- durationMode: "machine",
847
- requestCategory: "process_payment",
848
- statusClass: telemetryStatusClass(result.status)
849
- });
850
- return result;
851
- } catch (error) {
852
- if (!(error instanceof FloPayError && error.code === "checkout_processing_timeout")) {
853
- this.reportDirectFailure(
854
- error,
855
- "PAYMENT_PROCESSING_FAILED",
856
- "processing",
857
- "process_payment"
858
- );
859
- }
860
- throw error;
861
- }
862
- }
863
- /**
864
- * Patch the buyer's account snapshot (email, name, billing address, AVS
865
- * intent) onto a checkout session via
866
- * `PATCH /v1/checkouts/sessions/{id}/account` (TeamFloPay/backend#823).
867
- *
868
- * The vault path's hosted form owns the charge end-to-end so the SDK
869
- * never calls `/process` on this path; the buyer-typed AVS / billing
870
- * address would otherwise be lost. The SDK calls this just before
871
- * submitting the vault widget so the downstream listener mints the
872
- * Stripe PaymentMethod with the right `billing_details.address` and the
873
- * per-attempt + per-PM address snapshots are populated.
874
- *
875
- * Body shape mirrors the relevant subset of `/process`'s
876
- * `ProcessCheckoutBodyDto` — same keys, same validators. The endpoint
877
- * is idempotent: empty/undefined fields are not written, addresses are
878
- * last-writer-wins, AVS analytics are first-writer-wins.
879
- *
880
- * Wrapped in `fetchWithNetworkRetry` because a transient blip on this
881
- * pre-pay PATCH would silently leave AVS unsent and cause an
882
- * AVS-protected charge to decline downstream.
883
- */
884
- async patchAccountSnapshot(sessionId, nonce, body, options) {
885
- this.beginDirectTelemetryCheckout(sessionId);
886
- const startedAt = this.telemetryTimestamp();
887
- this.directTelemetry?.log({
888
- name: "operation.state_transition",
889
- stage: "processing",
890
- requestCategory: "account_snapshot"
891
- });
892
- const timeoutMs = options?.timeoutMs ?? DEFAULT_ACCOUNT_SNAPSHOT_TIMEOUT_MS;
893
- const controller = new AbortController();
894
- const onCallerAbort = () => controller.abort();
895
- if (options?.signal) {
896
- if (options.signal.aborted) controller.abort();
897
- else options.signal.addEventListener("abort", onCallerAbort, { once: true });
898
- }
899
- const timer = setTimeout(() => controller.abort(), timeoutMs);
900
- try {
901
- let response;
902
- try {
903
- response = await fetchWithNetworkRetry(
904
- `${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(sessionId)}/account`,
905
- {
906
- method: "PATCH",
907
- headers: {
908
- "Content-Type": "application/json",
909
- "x-checkout-session-token": nonce
910
- },
911
- body: JSON.stringify(body),
912
- signal: controller.signal
913
- },
914
- NETWORK_RETRY_ATTEMPTS,
915
- (attempt) => {
916
- this.telemetryHooks?.onRetry?.("account_snapshot", attempt);
917
- this.directTelemetry?.log({
918
- name: "operation.retry",
919
- stage: "processing",
920
- requestCategory: "account_snapshot",
921
- attempt
922
- });
923
- }
924
- );
925
- } finally {
926
- clearTimeout(timer);
927
- options?.signal?.removeEventListener("abort", onCallerAbort);
928
- }
929
- if (!response.ok) {
930
- throw await buildApiErrorFromResponse(response, "Failed to persist account snapshot");
931
- }
932
- this.directTelemetry?.performance({
933
- stage: "processing",
934
- durationMs: Math.max(0, this.telemetryTimestamp() - startedAt),
935
- durationMode: "machine",
936
- requestCategory: "account_snapshot",
937
- statusClass: "2xx"
938
- });
939
- } catch (error) {
940
- this.reportDirectFailure(
941
- error,
942
- "NETWORK_REQUEST_FAILED",
943
- "processing",
944
- "account_snapshot"
945
- );
946
- throw error;
947
- }
948
- }
949
- /** Create a wallet/APM/PayPal intent through the session-scoped contract. */
950
- async createSessionIntent(sessionId, nonce, request, options) {
951
- if (!nonce) {
952
- throw new FloPayError(
953
- "createSessionIntent requires the checkout session nonce.",
954
- "validation_error",
955
- { code: "MissingCheckoutSessionToken", param: "nonce" }
956
- );
957
- }
958
- const rawRequest = request;
959
- const paymentMethodType = rawRequest["paymentMethodType"];
960
- const directCardType = typeof paymentMethodType === "string" && paymentMethodType.trim().toLowerCase() === "card";
961
- const commonRequestFieldsValid = typeof paymentMethodType === "string" && paymentMethodType.length > 0 && !directCardType && (typeof rawRequest["paymentMethodId"] === "string" || rawRequest["paymentMethodId"] === null);
962
- const stripeRequestValid = rawRequest["provider"] === "stripe" && (rawRequest["paymentMethodCategory"] === "wallet" || rawRequest["paymentMethodCategory"] === "apm") && (rawRequest["intentKind"] === "payment" || rawRequest["intentKind"] === "setup");
963
- const paypalRequestValid = rawRequest["provider"] === "paypal" && rawRequest["paymentMethodCategory"] === "wallet" && rawRequest["paymentMethodType"] === "paypal" && rawRequest["paymentMethodId"] === null && (rawRequest["intentKind"] === "order" || rawRequest["intentKind"] === "subscription");
964
- if (!commonRequestFieldsValid || !stripeRequestValid && !paypalRequestValid) {
965
- throw new FloPayError(
966
- "Only wallet, APM, and PayPal session intents are supported.",
967
- "validation_error",
968
- { code: "InvalidSessionIntentRequest" }
969
- );
970
- }
971
- const suppliedAttemptId = rawRequest["authorizationAttemptId"];
972
- if (suppliedAttemptId !== void 0 && !isUuidV4(suppliedAttemptId)) {
973
- throw new FloPayError(
974
- "authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.",
975
- "validation_error",
976
- { code: "InvalidAuthorizationAttemptId", param: "authorizationAttemptId" }
977
- );
978
- }
979
- const authorizationAttemptId = isUuidV4(suppliedAttemptId) ? suppliedAttemptId : randomUuidV4();
980
- this.beginDirectTelemetryCheckout(sessionId);
981
- const startedAt = this.telemetryTimestamp();
982
- this.directTelemetry?.log({
983
- name: "payment.intent.started",
984
- stage: "processing",
985
- requestCategory: "intent_create"
986
- });
987
- const headers = {
988
- "Content-Type": "application/json",
989
- "x-checkout-session-token": nonce,
990
- [IDEMPOTENCY_KEY_HEADER]: options?.idempotencyKey || authorizationAttemptId
991
- };
992
- let failureReported = false;
993
- try {
994
- const response = await fetch(
995
- `${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(sessionId)}/intents`,
996
- {
997
- method: "POST",
998
- headers,
999
- body: JSON.stringify({ ...request, authorizationAttemptId }),
1000
- signal: options?.signal
1001
- }
1002
- );
1003
- if (!response.ok) {
1004
- failureReported = true;
1005
- this.directTelemetry?.error({
1006
- errorCode: "PAYMENT_PROCESSING_FAILED",
1007
- stage: "processing",
1008
- requestCategory: "intent_create",
1009
- statusClass: telemetryStatusClass(response.status)
1010
- });
1011
- throw await buildApiErrorFromResponse(response, "Failed to create checkout intent");
1012
- }
1013
- const body = await response.json();
1014
- const data = body.data;
1015
- if (!data || typeof data !== "object") {
1016
- throw new FloPayError("Invalid checkout intent response.", "api_error", {
1017
- code: "InvalidSessionIntentResponse"
1018
- });
1019
- }
1020
- const intent = data;
1021
- const responsePaymentMethodType = intent["paymentMethodType"];
1022
- const commonFieldsValid = (intent["paymentMethodCategory"] === "wallet" || intent["paymentMethodCategory"] === "apm") && typeof responsePaymentMethodType === "string" && responsePaymentMethodType.trim().toLowerCase() !== "card" && (typeof intent["paymentMethodId"] === "string" || intent["paymentMethodId"] === null) && typeof intent["providerObjectId"] === "string";
1023
- const stripeValid = intent["provider"] === "stripe" && (intent["intentKind"] === "payment" || intent["intentKind"] === "setup") && typeof intent["clientSecret"] === "string";
1024
- const paypalValid = intent["provider"] === "paypal" && intent["paymentMethodCategory"] === "wallet" && intent["paymentMethodType"] === "paypal" && intent["paymentMethodId"] === null && (intent["intentKind"] === "order" || intent["intentKind"] === "subscription") && intent["clientSecret"] === null;
1025
- const discriminantsMatchRequest = intent["provider"] === request.provider && intent["paymentMethodCategory"] === request.paymentMethodCategory && intent["paymentMethodType"] === request.paymentMethodType && intent["paymentMethodId"] === request.paymentMethodId && intent["intentKind"] === request.intentKind;
1026
- if (!commonFieldsValid || !stripeValid && !paypalValid || !discriminantsMatchRequest) {
1027
- throw new FloPayError("Invalid checkout intent response.", "api_error", {
1028
- code: "InvalidSessionIntentResponse"
1029
- });
1030
- }
1031
- this.directTelemetry?.log({
1032
- name: "payment.intent.completed",
1033
- stage: "processing",
1034
- requestCategory: "intent_create",
1035
- statusClass: telemetryStatusClass(response.status)
1036
- });
1037
- this.directTelemetry?.performance({
1038
- stage: "processing",
1039
- durationMs: Math.max(0, this.telemetryTimestamp() - startedAt),
1040
- durationMode: "machine",
1041
- requestCategory: "intent_create",
1042
- statusClass: telemetryStatusClass(response.status)
1043
- });
1044
- return intent;
1045
- } catch (error) {
1046
- if (!failureReported) {
1047
- this.reportDirectFailure(
1048
- error,
1049
- "PAYMENT_PROCESSING_FAILED",
1050
- "processing",
1051
- "intent_create"
1052
- );
1053
- }
1054
- throw error;
1055
- }
1056
- }
1057
- /** Record a provider-neutral non-card decline without sensitive identifiers. */
1058
- async reportSessionIntentDecline(sessionId, nonce, request, options) {
1059
- if (!nonce) {
1060
- throw new FloPayError(
1061
- "reportSessionIntentDecline requires the checkout session nonce.",
1062
- "validation_error",
1063
- { code: "MissingCheckoutSessionToken", param: "nonce" }
1064
- );
1065
- }
1066
- const rawRequest = request;
1067
- const reason = rawRequest["providerDeclineReason"];
1068
- const paymentMethodType = rawRequest["paymentMethodType"];
1069
- const safeReason = typeof reason === "string" && /^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(reason) && !/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(reason);
1070
- const commonFieldsValid = typeof paymentMethodType === "string" && paymentMethodType.length > 0 && paymentMethodType.trim().toLowerCase() !== "card" && safeReason;
1071
- const stripeFieldsValid = rawRequest["provider"] === "stripe" && (rawRequest["paymentMethodCategory"] === "wallet" || rawRequest["paymentMethodCategory"] === "apm");
1072
- const paypalFieldsValid = rawRequest["provider"] === "paypal" && rawRequest["paymentMethodCategory"] === "wallet" && rawRequest["paymentMethodType"] === "paypal";
1073
- if (!commonFieldsValid || !stripeFieldsValid && !paypalFieldsValid) {
1074
- throw new FloPayError(
1075
- "Invalid non-card decline classification.",
1076
- "validation_error",
1077
- { code: "InvalidSessionIntentDeclineRequest" }
1078
- );
1079
- }
1080
- const safeRequest = paypalFieldsValid ? {
1081
- provider: "paypal",
1082
- paymentMethodCategory: "wallet",
1083
- paymentMethodType: "paypal",
1084
- providerDeclineReason: reason
1085
- } : {
1086
- provider: "stripe",
1087
- paymentMethodCategory: rawRequest["paymentMethodCategory"],
1088
- paymentMethodType: rawRequest["paymentMethodType"],
1089
- providerDeclineReason: reason
1090
- };
1091
- const response = await fetch(
1092
- `${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(sessionId)}/intents/decline`,
1093
- {
1094
- method: "POST",
1095
- headers: {
1096
- "Content-Type": "application/json",
1097
- "x-checkout-session-token": nonce
1098
- },
1099
- body: JSON.stringify(safeRequest),
1100
- signal: options?.signal
1101
- }
1102
- );
1103
- if (!response.ok) {
1104
- throw await buildApiErrorFromResponse(response, "Failed to report checkout decline");
1105
- }
1106
- }
1107
- /**
1108
- * Fetch user's prior payments by email.
1109
- * Used to determine if saved card UX should be shown.
1110
- */
1111
- async getPaymentsByEmail(email, options) {
1112
- this.beginDirectTelemetryOperation();
1113
- const startedAt = this.telemetryTimestamp();
1114
- this.directTelemetry?.log({
1115
- name: "operation.recovery.started",
1116
- stage: "recovery",
1117
- requestCategory: "other",
1118
- paymentMethodCategory: "saved"
1119
- });
1120
- const page = options?.page ?? 1;
1121
- const limit = options?.limit ?? 1;
1122
- const params = new URLSearchParams({
1123
- email,
1124
- page: String(page),
1125
- limit: String(limit),
1126
- sortField: "createdAt",
1127
- sortDirection: "DESC"
1128
- });
1129
- try {
1130
- const response = await fetch(
1131
- `${this.baseUrl}/v1/payments?${params.toString()}`,
1132
- {
1133
- method: "GET",
1134
- signal: options?.signal,
1135
- keepalive: true
1136
- }
1137
- );
1138
- if (!response.ok) {
1139
- throw new FloPayError(
1140
- "Failed to fetch payments",
1141
- "api_error",
1142
- { statusCode: response.status }
1143
- );
1144
- }
1145
- const result = await response.json();
1146
- this.directTelemetry?.log({
1147
- name: "operation.recovery.completed",
1148
- stage: "recovery",
1149
- requestCategory: "other",
1150
- paymentMethodCategory: "saved",
1151
- statusClass: "2xx"
1152
- });
1153
- this.directTelemetry?.performance({
1154
- stage: "recovery",
1155
- durationMs: Math.max(0, this.telemetryTimestamp() - startedAt),
1156
- durationMode: "machine",
1157
- requestCategory: "other",
1158
- paymentMethodCategory: "saved",
1159
- statusClass: "2xx"
1160
- });
1161
- return result;
1162
- } catch (error) {
1163
- this.reportDirectFailure(error, "RECOVERY_FAILED", "recovery", "other", "saved");
1164
- throw error;
1165
- }
1166
- }
1167
- /**
1168
- * Create a checkout session AND return the full session data in one call.
1169
- * Uses `?expand=true` so the backend returns the complete session
1170
- * instead of just a UUID — eliminating the need for a second GET.
1171
- *
1172
- * Falls back to create + GET if the backend doesn't support `expand`.
1173
- */
1174
- async createAndFetchSession(params) {
1175
- this.beginDirectTelemetryOperation();
1176
- const startedAt = this.telemetryTimestamp();
1177
- this.directTelemetry?.log({
1178
- name: "session.create.started",
1179
- stage: "session_create",
1180
- requestCategory: "session_create"
1181
- });
1182
- try {
1183
- const result = await this.createAndFetchSessionRequest(params, startedAt);
1184
- this.adoptDirectTelemetryCheckout(result.data.session?.id);
1185
- this.directTelemetry?.log({
1186
- name: "session.request.completed",
1187
- stage: "session_complete",
1188
- requestCategory: "session_create",
1189
- statusClass: "2xx"
1190
- });
1191
- this.directTelemetry?.performance({
1192
- stage: "session_create",
1193
- durationMs: this.telemetryTimestamp() - startedAt,
1194
- durationMode: "machine",
1195
- requestCategory: "session_create",
1196
- statusClass: "2xx"
1197
- });
1198
- return result;
1199
- } catch (error) {
1200
- if (!(error instanceof FloPayError && error.code === "session_auto_completed")) {
1201
- try {
1202
- this.telemetryHooks?.onSessionCreateFailure?.(error);
1203
- } catch {
1204
- }
1205
- }
1206
- if (error instanceof FloPayError && error.type === "validation_error") {
1207
- this.directTelemetry?.terminal({
1208
- outcome: "validation_rejected",
1209
- stage: "session_create",
1210
- requestCategory: "session_create"
1211
- });
1212
- } else if (!(error instanceof FloPayError && error.code === "session_auto_completed")) {
1213
- const statusCode = error instanceof FloPayError ? error.statusCode : void 0;
1214
- this.directTelemetry?.error({
1215
- errorCode: error instanceof Error && error.name === "AbortError" ? "REQUEST_TIMEOUT" : error instanceof TypeError ? "NETWORK_REQUEST_FAILED" : "CHECKOUT_SESSION_CREATE_FAILED",
1216
- stage: "session_create",
1217
- requestCategory: "session_create",
1218
- statusClass: error instanceof Error && error.name === "AbortError" ? "timeout" : statusCode ? `${Math.floor(statusCode / 100)}xx` : "network_error"
1219
- });
1220
- }
1221
- throw error;
1222
- }
1223
- }
1224
- async createAndFetchSessionRequest(params, telemetryStartedAt) {
1225
- const wireProducts = params.products ?? foldIntoProducts(params.items, params.subscriptions);
1226
- const sessionCurrency = resolveSessionCurrency(
1227
- params.currency,
1228
- params.items,
1229
- params.subscriptions,
1230
- wireProducts
1231
- );
1232
- if (!sessionCurrency) {
1233
- throw new FloPayError(
1234
- "currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.",
1235
- "validation_error",
1236
- { code: "CurrencyRequired", param: "currency" }
1237
- );
1238
- }
1239
- const payload = {
1240
- clientId: params.clientId,
1241
- checkoutVersion: SDK_VERSION,
1242
- successUrl: params.successUrl,
1243
- cancelUrl: params.cancelUrl,
1244
- currency: sessionCurrency,
1245
- checkoutMode: params.checkoutMode ?? "full",
1246
- products: wireProducts.map((product) => buildProductPayload(product, sessionCurrency)),
1247
- accountData: {
1248
- userId: params.account.userId,
1249
- firstName: params.account.firstName ?? null,
1250
- lastName: params.account.lastName ?? null,
1251
- email: params.account.email,
1252
- country: params.account.country ?? null,
1253
- gender: params.account.gender ?? null,
1254
- city: params.account.city ?? null,
1255
- state: params.account.state ?? null,
1256
- zip: params.account.zip ?? null,
1257
- addressLine1: params.account.addressLine1 ?? null,
1258
- addressLine2: params.account.addressLine2 ?? null
1259
- },
1260
- couponCodes: params.couponCodes ?? []
1261
- };
1262
- if (params.tokenizedData) payload["tokenizedData"] = params.tokenizedData;
1263
- if (params.tagsData) payload["tagsData"] = params.tagsData;
1264
- if (params.utmMetadata?.length) payload["utmMetadata"] = params.utmMetadata;
1265
- if (params.avsCheck !== void 0) payload["avsCheck"] = params.avsCheck;
1266
- if (params.checkoutType) payload["checkoutType"] = params.checkoutType;
1267
- if (params.checkoutLayout) payload["checkoutLayout"] = params.checkoutLayout;
1268
- if (params.avsConfig) payload["avsConfig"] = params.avsConfig;
1269
- const headers = {
1270
- "Content-Type": "application/json",
1271
- // Retain the SDK version header for compatibility visibility. Backends
1272
- // must not gate the hosted vault block on this value.
1273
- [FLO_SDK_VERSION_HEADER]: SDK_VERSION
1274
- };
1275
- const idempotencyKey = resolveIdempotencyKey(params.idempotencyKey);
1276
- if (idempotencyKey) {
1277
- headers[IDEMPOTENCY_KEY_HEADER] = idempotencyKey;
1278
- }
1279
- let response;
1280
- let firstByteReported = false;
1281
- for (let attempt = 0; ; attempt++) {
1282
- response = await fetchWithNetworkRetry(
1283
- `${this.baseUrl}/v1/checkouts/sessions?expand=true`,
1284
- {
1285
- method: "POST",
1286
- headers,
1287
- body: JSON.stringify(payload)
1288
- },
1289
- NETWORK_RETRY_ATTEMPTS,
1290
- (networkAttempt) => {
1291
- this.telemetryHooks?.onRetry?.("session_create", networkAttempt);
1292
- this.directTelemetry?.log({
1293
- name: "operation.retry",
1294
- stage: "session_create",
1295
- requestCategory: "session_create",
1296
- attempt: networkAttempt
1297
- });
1298
- }
1299
- );
1300
- if (!firstByteReported) {
1301
- firstByteReported = true;
1302
- const statusClass = `${Math.floor(response.status / 100)}xx`;
1303
- this.directTelemetry?.log({
1304
- name: "session.request.first_byte",
1305
- stage: "session_first_byte",
1306
- requestCategory: "session_create",
1307
- statusClass
1308
- });
1309
- this.directTelemetry?.performance({
1310
- stage: "session_first_byte",
1311
- durationMs: this.telemetryTimestamp() - telemetryStartedAt,
1312
- durationMode: "machine",
1313
- requestCategory: "session_create",
1314
- statusClass
1315
- });
1316
- }
1317
- if (response.status === 204) {
1318
- throw new FloPayError(
1319
- "Session auto-completed \u2014 payment method already on file",
1320
- "api_error",
1321
- { code: "session_auto_completed" }
1322
- );
1323
- }
1324
- if (response.ok) break;
1325
- const error = await buildApiErrorFromResponse(response, "Failed to create checkout session");
1326
- if (error.code === IDEMPOTENCY_IN_PROGRESS_CODE && attempt < IDEMPOTENCY_IN_PROGRESS_RETRY_ATTEMPTS) {
1327
- try {
1328
- this.telemetryHooks?.onRetry?.("session_create", attempt + 1);
1329
- this.directTelemetry?.log({
1330
- name: "operation.retry",
1331
- stage: "session_create",
1332
- requestCategory: "session_create",
1333
- attempt: attempt + 1
1334
- });
1335
- } catch {
1336
- }
1337
- await delay(150 * 2 ** attempt);
1338
- continue;
1339
- }
1340
- throw error;
1341
- }
1342
- const body = await response.json();
1343
- if (body.data && "gateways" in body.data) {
1344
- this.autoCacheDisplayData(body.data.uuid, params);
1345
- const merged = this.mergeCachedDisplayData(body.data);
1346
- const normalized = this.normalizeRawSession(merged);
1347
- if (body.vault && normalized.data.session) {
1348
- normalized.data.session.vault = this.toVaultBlock(body.vault);
1349
- }
1350
- return {
1351
- ...normalized,
1352
- autoProcessingError: body.autoProcessingError,
1353
- autoProcessingAttempted: body.autoProcessingAttempted,
1354
- autoProcessingPending: body.autoProcessingPending
1355
- };
1356
- }
1357
- const uuid = body.data?.uuid;
1358
- if (!uuid) {
1359
- throw new FloPayError("No session ID returned", "api_error");
1360
- }
1361
- this.autoCacheDisplayData(uuid, params);
1362
- this.adoptDirectTelemetryCheckout(uuid);
1363
- const unifiedSession = await this.getUnifiedCheckoutSession(uuid);
1364
- return {
1365
- ...unifiedSession,
1366
- autoProcessingError: body.autoProcessingError,
1367
- autoProcessingAttempted: body.autoProcessingAttempted,
1368
- autoProcessingPending: body.autoProcessingPending
1369
- };
1370
- }
1371
- async waitForCheckoutSessionCompletion(checkoutSessionId, options) {
1372
- this.beginDirectTelemetryCheckout(checkoutSessionId);
1373
- const startedAt = this.telemetryTimestamp();
1374
- this.directTelemetry?.log({
1375
- name: "operation.recovery.started",
1376
- stage: "recovery",
1377
- requestCategory: "session_read",
1378
- paymentMethodCategory: "saved"
1379
- });
1380
- const timeoutMs = options?.timeoutMs ?? DEFAULT_PROCESSING_TIMEOUT_MS;
1381
- const deadline = Date.now() + timeoutMs;
1382
- let nextDelayMs = this.clampRetryAfterMs(options?.initialDelayMs ?? DEFAULT_PROCESSING_RETRY_AFTER_MS);
1383
- let pollAttempt = 0;
1384
- try {
1385
- while (true) {
1386
- const remainingMs = deadline - Date.now();
1387
- if (remainingMs <= 0) {
1388
- throw createCheckoutProcessingTimeoutError();
1389
- }
1390
- if (nextDelayMs > 0) {
1391
- try {
1392
- pollAttempt += 1;
1393
- this.telemetryHooks?.onRetry?.("session_read", pollAttempt);
1394
- this.directTelemetry?.log({
1395
- name: "operation.retry",
1396
- stage: "recovery",
1397
- requestCategory: "session_read",
1398
- paymentMethodCategory: "saved",
1399
- attempt: pollAttempt
1400
- });
1401
- } catch {
1402
- }
1403
- await delay(Math.min(nextDelayMs, remainingMs));
1404
- if (Date.now() >= deadline) {
1405
- throw createCheckoutProcessingTimeoutError();
1406
- }
1407
- }
1408
- const session = await this.getUnifiedCheckoutSession(checkoutSessionId, options?.nonce);
1409
- const status = session.data.session?.status;
1410
- if (status === "complete" || status === "expired") {
1411
- this.directTelemetry?.log({
1412
- name: "operation.recovery.completed",
1413
- stage: "recovery",
1414
- requestCategory: "session_read",
1415
- paymentMethodCategory: "saved"
1416
- });
1417
- this.directTelemetry?.performance({
1418
- stage: "recovery",
1419
- durationMs: Math.max(0, this.telemetryTimestamp() - startedAt),
1420
- durationMode: "machine",
1421
- requestCategory: "session_read",
1422
- paymentMethodCategory: "saved"
1423
- });
1424
- return session;
1425
- }
1426
- if (Date.now() >= deadline) {
1427
- throw createCheckoutProcessingTimeoutError();
1428
- }
1429
- nextDelayMs = this.clampRetryAfterMs(
1430
- Math.max(nextDelayMs * 2, MIN_PROCESSING_RETRY_AFTER_MS)
1431
- );
1432
- }
1433
- } catch (error) {
1434
- if (error instanceof FloPayError && error.code === "checkout_processing_timeout") {
1435
- this.reportDirectFailure(
1436
- error,
1437
- "RECOVERY_FAILED",
1438
- "recovery",
1439
- "session_read",
1440
- "saved"
1441
- );
1442
- }
1443
- throw error;
1444
- }
1445
- }
1446
- /** Normalize a raw session into a provider-agnostic shape. */
1447
- normalizeRawSession(session) {
1448
- const gateways = session.gateways ?? {};
1449
- const providers = [];
1450
- const data = {
1451
- session: this.toCheckoutSession(session)
1452
- };
1453
- const stripeGateway = gateways.stripe;
1454
- if (stripeGateway?.publishableKey) {
1455
- providers.push("stripe");
1456
- const rawSession = session;
1457
- const stripeClientSecret = [
1458
- rawSession["stripeClientSecret"],
1459
- stripeGateway.stripeClientSecret
1460
- ].find((value) => typeof value === "string" && value.length > 0);
1461
- data.stripe = {
1462
- clientSecret: stripeClientSecret ?? "",
1463
- publishableKey: stripeGateway.publishableKey ?? void 0,
1464
- paypalPublishableKey: stripeGateway.paypalPublishableKey ?? void 0,
1465
- environment: stripeGateway.environment,
1466
- enabledPaymentMethods: Array.isArray(stripeGateway.enabledPaymentMethods) ? stripeGateway.enabledPaymentMethods.filter((m) => typeof m === "string") : void 0
1467
- };
1468
- }
1469
- const paypalGateway = gateways.paypal;
1470
- if (paypalGateway?.publishableKey) {
1471
- providers.push("paypal");
1472
- data.paypal = {
1473
- publishableKey: paypalGateway.publishableKey,
1474
- environment: paypalGateway.environment
1475
- };
1476
- }
1477
- return {
1478
- providers,
1479
- mode: "tokenize",
1480
- data,
1481
- raw: { data: session }
1482
- };
1483
- }
1484
- /** Convert raw session to the SDK CheckoutSession shape. */
1485
- toCheckoutSession(raw) {
1486
- const rawProducts = raw.products ?? [];
1487
- const hasBackendTotal = typeof raw.totalAmount === "number" && Number.isFinite(raw.totalAmount);
1488
- const computedTotal = rawProducts.reduce(
1489
- (sum, p) => sum + (p.overrideAmount ?? p.totalAmount ?? 0),
1490
- 0
1491
- );
1492
- const totalAmount = hasBackendTotal ? raw.totalAmount : computedTotal;
1493
- const amountInCents = Math.round(totalAmount * 100);
1494
- const currency = raw.currency ?? rawProducts[0]?.currency ?? "USD";
1495
- const mode = rawProducts.some((p) => p.type === "subscription") ? "subscription" : "payment";
1496
- return {
1497
- id: raw.uuid,
1498
- clientSecret: raw.nonce,
1499
- mode,
1500
- status: this.toCheckoutSessionStatus(raw.status),
1501
- amount: amountInCents,
1502
- currency,
1503
- customer: {
1504
- id: raw.accountData.userId,
1505
- email: raw.accountData.email,
1506
- firstName: raw.accountData.firstName,
1507
- lastName: raw.accountData.lastName,
1508
- country: raw.accountData.country ?? void 0,
1509
- city: raw.accountData.city ?? void 0,
1510
- state: raw.accountData.state ?? void 0,
1511
- zip: raw.accountData.zip ?? void 0,
1512
- gender: raw.accountData.gender ?? void 0,
1513
- line1: raw.accountData.addressLine1 ?? void 0,
1514
- line2: raw.accountData.addressLine2 ?? void 0
1515
- },
1516
- metadata: {},
1517
- checkoutMode: raw.checkoutMode,
1518
- providerPaymentMethodId: typeof raw.providerPaymentMethodId === "string" ? raw.providerPaymentMethodId : null,
1519
- products: rawProducts.map((p) => ({
1520
- ...p,
1521
- totalAmount: typeof p.totalAmount === "number" ? p.totalAmount : void 0,
1522
- overrideAmount: typeof p.overrideAmount === "number" ? p.overrideAmount : null,
1523
- currency: typeof p.currency === "string" ? p.currency : void 0,
1524
- metadata: p.metadata ?? null
1525
- })),
1526
- successUrl: raw.successUrl,
1527
- cancelUrl: raw.cancelUrl,
1528
- coupons: raw.coupons,
1529
- subtotalAmount: raw.subtotalAmount,
1530
- discountAmount: raw.discountAmount,
1531
- totalAmount: raw.totalAmount,
1532
- createdAt: raw.createdAt,
1533
- gateways: raw.gateways,
1534
- accountData: raw.accountData,
1535
- tagsData: raw.tagsData
1536
- };
1537
- }
1538
- /**
1539
- * Coerce a raw vault block into a typed {@link VaultCaptureBlock}. The
1540
- * server-only PCIVault submit `secret` is deliberately dropped so it never
1541
- * lands on the public session surface (logs / telemetry / client inspection).
1542
- */
1543
- toVaultBlock(raw) {
1544
- return {
1545
- html: typeof raw.html === "string" ? raw.html : void 0,
1546
- url: typeof raw.url === "string" ? raw.url : void 0,
1547
- messageToken: typeof raw.messageToken === "string" ? raw.messageToken : void 0,
1548
- expectedOrigin: typeof raw.expectedOrigin === "string" ? raw.expectedOrigin : void 0
1549
- };
1550
- }
1551
- toCheckoutSessionStatus(status) {
1552
- if (status === "completed") {
1553
- return "complete";
1554
- }
1555
- if (status === "expired") {
1556
- return "expired";
1557
- }
1558
- return "open";
1559
- }
1560
- async resolveProcessResponse(response, checkoutSessionId, options) {
1561
- if (response.status !== 202) {
1562
- return response;
1563
- }
1564
- const payload = await response.json().catch(() => null);
1565
- const pending = this.toCheckoutProcessingPending(payload, response, checkoutSessionId);
1566
- const session = await this.waitForCheckoutSessionCompletion(pending.sessionId, {
1567
- initialDelayMs: pending.retryAfterMs,
1568
- timeoutMs: options?.pollTimeoutMs,
1569
- nonce: options?.nonce
1570
- });
1571
- if (session.data.session?.status === "complete") {
1572
- return new Response(null, { status: 204, statusText: "No Content" });
1573
- }
1574
- if (session.data.session?.status === "expired") {
1575
- throw new FloPayError(
1576
- "Checkout session has expired.",
1577
- "api_error",
1578
- { code: "checkout_session_expired" }
1579
- );
1580
- }
1581
- throw createCheckoutProcessingTimeoutError();
1582
- }
1583
- toCheckoutProcessingPending(payload, response, checkoutSessionId) {
1584
- const retryAfterHeader = response.headers.get("Retry-After");
1585
- const headerRetryAfterSeconds = retryAfterHeader === null || retryAfterHeader.trim() === "" ? void 0 : Number(retryAfterHeader);
1586
- const headerRetryAfterMs = headerRetryAfterSeconds !== void 0 && Number.isFinite(headerRetryAfterSeconds) ? headerRetryAfterSeconds * 1e3 : void 0;
1587
- return {
1588
- type: "checkout_processing",
1589
- sessionId: readString(payload, "sessionId") ?? checkoutSessionId,
1590
- retryAfterMs: this.clampRetryAfterMs(
1591
- readNumber(payload, "retryAfterMs") ?? headerRetryAfterMs ?? DEFAULT_PROCESSING_RETRY_AFTER_MS
1592
- ),
1593
- statusUrl: readString(payload, "statusUrl"),
1594
- sessionUrl: readString(payload, "sessionUrl")
1595
- };
1596
- }
1597
- clampRetryAfterMs(retryAfterMs) {
1598
- return Math.max(0, Math.min(retryAfterMs, MAX_PROCESSING_RETRY_AFTER_MS));
1599
- }
1600
- /**
1601
- * Stash the display-only fields the consumer passed into a create-session
1602
- * call. Runs after the backend assigns a UUID so a later GET on the same
1603
- * session (typically after a redirect) can fill in fields the backend no
1604
- * longer persists — `overrideAmount`, `totalAmount`, `name`, etc.
1605
- *
1606
- * No-op when no UUID is available.
1607
- */
1608
- autoCacheDisplayData(sessionId, params) {
1609
- if (!sessionId) return;
1610
- const products = params.products ?? foldIntoProducts(params.items, params.subscriptions);
1611
- if (products.length === 0 && !params.currency) {
1612
- return;
1613
- }
1614
- const usingUnifiedProducts = params.products !== void 0;
1615
- const sessionCurrency = resolveSessionCurrency(
1616
- params.currency,
1617
- usingUnifiedProducts ? void 0 : params.items,
1618
- usingUnifiedProducts ? void 0 : params.subscriptions,
1619
- products
1620
- );
1621
- cacheSessionDisplayData(sessionId, {
1622
- currency: sessionCurrency ?? void 0,
1623
- products: products.map((p) => ({
1624
- code: p.code ?? p.providerItemId ?? p.providerPlanId,
1625
- type: p.type,
1626
- name: p.name ?? p.itemName ?? p.providerItemName ?? p.subscriptionName ?? p.providerPlanName ?? null,
1627
- totalAmount: p.totalAmount,
1628
- overrideAmount: p.overrideAmount,
1629
- currency: p.currency ?? sessionCurrency ?? void 0
1630
- }))
1631
- });
1632
- }
1633
- /**
1634
- * Merge cached display-only fields (set by {@link cacheSessionDisplayData})
1635
- * into a raw session response. Server values always win — cache fills in
1636
- * only where the server returned `null` / `undefined`.
1637
- */
1638
- mergeCachedDisplayData(raw) {
1639
- const cached = getSessionDisplayData(raw.uuid);
1640
- const cachedProducts = /* @__PURE__ */ new Map();
1641
- const productKey = (code) => code ? `code:${code}` : void 0;
1642
- for (const p of cached?.products ?? []) {
1643
- const key = productKey(p.code);
1644
- if (key) cachedProducts.set(key, p);
1645
- }
1646
- const mergedProducts = (raw.products ?? []).map((p) => {
1647
- const key = productKey(p.code);
1648
- const fallback = key ? cachedProducts.get(key) : void 0;
1649
- return {
1650
- ...p,
1651
- name: p.name ?? fallback?.name ?? null,
1652
- totalAmount: p.totalAmount ?? fallback?.totalAmount,
1653
- overrideAmount: p.overrideAmount ?? fallback?.overrideAmount,
1654
- currency: p.currency ?? fallback?.currency
1655
- };
1656
- });
1657
- return {
1658
- ...raw,
1659
- currency: raw.currency ?? cached?.currency,
1660
- products: mergedProducts
1661
- };
1662
- }
1663
- };
1664
- function createInstrumentedPaymentAPI(billingApiUrl, hooks) {
1665
- const InstrumentedPaymentAPI = PaymentAPI;
1666
- return new InstrumentedPaymentAPI(billingApiUrl, hooks);
1667
- }
1668
-
1669
- // src/stripe-adapter.ts
1670
- function toStripeElementType(type) {
1671
- const map = {
1672
- payment: "payment",
1673
- address: "address"
1674
- };
1675
- return map[type];
1676
- }
1677
- function toStripeAppearanceTheme(theme) {
1678
- switch (theme) {
1679
- case "night":
1680
- return "night";
1681
- case "flat":
1682
- return "flat";
1683
- // 'default', 'none', undefined, or any unexpected value → Stripe's baseline.
1684
- default:
1685
- return "stripe";
1686
- }
1687
- }
1688
- function paymentMethodTypesKey(paymentMethodTypes) {
1689
- return paymentMethodTypes ? JSON.stringify(paymentMethodTypes.map((paymentMethodType) => paymentMethodType.trim().toLowerCase())) : null;
1690
- }
1691
- function wrapStripeElement(stripeElement) {
1692
- const el = stripeElement;
1693
- return {
1694
- mount(container) {
1695
- el.mount(container);
1696
- },
1697
- unmount() {
1698
- el.unmount();
1699
- },
1700
- update(options) {
1701
- el.update(options);
1702
- },
1703
- on(event, handler) {
1704
- el["on"]?.(event, handler);
1705
- },
1706
- off(event, handler) {
1707
- el["off"]?.(event, handler);
1708
- },
1709
- destroy() {
1710
- el.destroy();
1711
- }
1712
- };
1713
- }
1714
- function toStripeBillingDetails(billing) {
1715
- return {
1716
- billing_details: {
1717
- ...billing.email ? { email: billing.email } : {},
1718
- ...billing.name ? { name: billing.name } : {},
1719
- ...billing.address ? {
1720
- address: {
1721
- ...billing.address.country ? { country: billing.address.country } : {},
1722
- ...billing.address.postal_code ? { postal_code: billing.address.postal_code } : {},
1723
- ...billing.address.city ? { city: billing.address.city } : {},
1724
- ...billing.address.line1 ? { line1: billing.address.line1 } : {},
1725
- ...billing.address.line2 ? { line2: billing.address.line2 } : {},
1726
- ...billing.address.state ? { state: billing.address.state } : {}
1727
- }
1728
- } : {}
1729
- }
1730
- };
1731
- }
1732
- var StripeAdapter = class {
1733
- constructor() {
1734
- this.name = "stripe";
1735
- this.stripe = null;
1736
- this.elements = null;
1737
- // Serialized appearance currently applied to `this.elements`. Used to detect
1738
- // when consumers swap themes mid-session so we can live-update the Stripe
1739
- // Elements group instead of returning a stale-styled cache. `null` while no
1740
- // elements group exists.
1741
- this.appliedAppearanceKey = null;
1742
- this.appliedPaymentMethodTypesKey = null;
1743
- this.appliedClientSecret = null;
1744
- this.verifiedClientSecret = null;
1745
- this.verifiedPaymentMethodTypesKey = null;
1746
- }
1747
- async initialize(config) {
1748
- if (typeof window === "undefined") {
1749
- return;
1750
- }
1751
- const stripe = await loadStripe(config.publishableKey, {
1752
- locale: config.locale ?? "auto"
1753
- });
1754
- if (!stripe) {
1755
- throw new FloPayError2(
1756
- "Failed to initialize Stripe. Check your publishable key.",
1757
- "authentication_error"
1758
- );
1759
- }
1760
- this.stripe = stripe;
1761
- }
1762
- /** Lazily creates the Stripe Elements group for the given options. */
1763
- getElements(options) {
1764
- if (!this.stripe) {
1765
- throw new FloPayError2(
1766
- "StripeAdapter not initialized. Call initialize() first.",
1767
- "api_error"
1768
- );
1769
- }
1770
- const stripeAppearance = options?.appearance ? {
1771
- theme: toStripeAppearanceTheme(options.appearance.theme),
1772
- variables: options.appearance.variables,
1773
- rules: options.appearance.rules
1774
- } : void 0;
1775
- const nextAppearanceKey = stripeAppearance ? JSON.stringify(stripeAppearance) : null;
1776
- const nextPaymentMethodTypesKey = paymentMethodTypesKey(options?.paymentMethodTypes);
1777
- const nextClientSecret = options?.clientSecret ?? null;
1778
- if (this.elements && nextPaymentMethodTypesKey && (nextPaymentMethodTypesKey !== this.appliedPaymentMethodTypesKey || nextClientSecret !== this.appliedClientSecret)) {
1779
- this.elements = null;
1780
- this.appliedAppearanceKey = null;
1781
- this.appliedPaymentMethodTypesKey = null;
1782
- this.appliedClientSecret = null;
1783
- this.verifiedClientSecret = null;
1784
- this.verifiedPaymentMethodTypesKey = null;
1785
- }
1786
- if (!this.elements) {
1787
- let elementsOptions;
1788
- const deferredAmount = options?.amount ?? 0;
1789
- const deferredCurrency = (options?.currency ?? "usd").toLowerCase();
1790
- const paymentMethodCreation = options?.paymentMethodCreation ?? "manual";
1791
- if (options?.clientSecret) {
1792
- elementsOptions = { clientSecret: options.clientSecret };
1793
- } else if (deferredAmount > 0) {
1794
- elementsOptions = {
1795
- mode: "payment",
1796
- amount: deferredAmount,
1797
- currency: deferredCurrency,
1798
- paymentMethodCreation
1799
- };
1800
- if (options?.setupFutureUsage) {
1801
- elementsOptions["setupFutureUsage"] = options.setupFutureUsage;
1802
- }
1803
- } else {
1804
- elementsOptions = {
1805
- mode: "setup",
1806
- currency: deferredCurrency,
1807
- paymentMethodCreation
1808
- };
1809
- }
1810
- if (!options?.clientSecret && options?.paymentMethodTypes) {
1811
- elementsOptions["paymentMethodTypes"] = options.paymentMethodTypes;
1812
- }
1813
- if (stripeAppearance) {
1814
- elementsOptions["appearance"] = stripeAppearance;
1815
- }
1816
- this.elements = this.stripe.elements(elementsOptions);
1817
- this.appliedAppearanceKey = nextAppearanceKey;
1818
- this.appliedPaymentMethodTypesKey = nextPaymentMethodTypesKey;
1819
- this.appliedClientSecret = nextClientSecret;
1820
- this.verifiedClientSecret = null;
1821
- this.verifiedPaymentMethodTypesKey = null;
1822
- } else if (nextAppearanceKey !== this.appliedAppearanceKey) {
1823
- this.elements.update({
1824
- appearance: stripeAppearance ?? {}
1825
- });
1826
- this.appliedAppearanceKey = nextAppearanceKey;
1827
- }
1828
- return this.elements;
1829
- }
1830
- async assertClientSecretPaymentMethods(clientSecret, allowedPaymentMethodTypes) {
1831
- if (!this.stripe) {
1832
- throw new FloPayError2(
1833
- "StripeAdapter not initialized. Call initialize() first.",
1834
- "api_error"
1835
- );
1836
- }
1837
- let intent;
1838
- let retrievalFailed = false;
1839
- if (isSetupIntentClientSecret(clientSecret)) {
1840
- const { setupIntent, error } = await this.stripe.retrieveSetupIntent(clientSecret);
1841
- intent = setupIntent;
1842
- retrievalFailed = Boolean(error);
1843
- } else {
1844
- const { paymentIntent, error } = await this.stripe.retrievePaymentIntent(clientSecret);
1845
- intent = paymentIntent;
1846
- retrievalFailed = Boolean(error);
1847
- }
1848
- const providerPaymentMethodTypes = intent?.payment_method_types;
1849
- if (retrievalFailed || !Array.isArray(providerPaymentMethodTypes)) {
1850
- throw new FloPayError2(
1851
- "Unable to verify the payment methods configured for this client secret.",
1852
- "api_error",
1853
- { param: "clientSecret" }
1854
- );
1855
- }
1856
- const allowlist = new Set(
1857
- allowedPaymentMethodTypes.map((paymentMethodType) => paymentMethodType.toLowerCase())
1858
- );
1859
- const hasDisallowedProviderMethod = providerPaymentMethodTypes.some(
1860
- (paymentMethodType) => typeof paymentMethodType !== "string" || !allowlist.has(paymentMethodType.trim().toLowerCase())
1861
- );
1862
- if (hasDisallowedProviderMethod || providerPaymentMethodTypes.length === 0) {
1863
- throw new FloPayError2(
1864
- "The client-secret intent must enable only declared non-card payment methods.",
1865
- "validation_error",
1866
- { param: "clientSecret" }
1867
- );
1868
- }
1869
- }
1870
- async createElement(type, options) {
1871
- let resolvedOptions = options;
1872
- if (type === "payment") {
1873
- const paymentMethodTypes = options.paymentMethodTypes?.map((paymentMethodType) => paymentMethodType.trim()).filter((paymentMethodType) => paymentMethodType && paymentMethodType.toLowerCase() !== "card");
1874
- if (!paymentMethodTypes?.length) {
1875
- throw new FloPayError2(
1876
- "At least one supported non-card payment method is required.",
1877
- "validation_error",
1878
- { param: "paymentMethodTypes" }
1879
- );
1880
- }
1881
- resolvedOptions = { ...options, paymentMethodTypes };
1882
- if (resolvedOptions.clientSecret) {
1883
- const resolvedPaymentMethodTypesKey = paymentMethodTypesKey(paymentMethodTypes);
1884
- const verificationIsCached = Boolean(
1885
- this.elements && this.appliedClientSecret === resolvedOptions.clientSecret && this.appliedPaymentMethodTypesKey === resolvedPaymentMethodTypesKey && this.verifiedClientSecret === resolvedOptions.clientSecret && this.verifiedPaymentMethodTypesKey === resolvedPaymentMethodTypesKey
1886
- );
1887
- if (!verificationIsCached) {
1888
- await this.assertClientSecretPaymentMethods(
1889
- resolvedOptions.clientSecret,
1890
- paymentMethodTypes
1891
- );
1892
- }
1893
- }
1894
- }
1895
- const elements = this.getElements(resolvedOptions);
1896
- if (type === "payment" && resolvedOptions.clientSecret) {
1897
- this.verifiedClientSecret = resolvedOptions.clientSecret;
1898
- this.verifiedPaymentMethodTypesKey = paymentMethodTypesKey(
1899
- resolvedOptions.paymentMethodTypes
1900
- );
1901
- }
1902
- const stripeType = toStripeElementType(type);
1903
- const elementOptions = {};
1904
- if (resolvedOptions.layout) {
1905
- elementOptions["layout"] = resolvedOptions.layout;
1906
- }
1907
- if (resolvedOptions.defaultValues) {
1908
- elementOptions["defaultValues"] = resolvedOptions.defaultValues;
1909
- }
1910
- if (resolvedOptions.readOnly) {
1911
- elementOptions["readOnly"] = resolvedOptions.readOnly;
1912
- }
1913
- if (resolvedOptions.mode) {
1914
- elementOptions["mode"] = resolvedOptions.mode;
1915
- }
1916
- const stripeElement = elements.create(stripeType, elementOptions);
1917
- return wrapStripeElement(stripeElement);
1918
- }
1919
- getElement(type) {
1920
- if (!this.elements) return null;
1921
- const stripeType = toStripeElementType(type);
1922
- const existing = this.elements.getElement(stripeType);
1923
- if (!existing) return null;
1924
- return wrapStripeElement(existing);
1925
- }
1926
- async submitElements() {
1927
- if (!this.stripe || !this.elements) {
1928
- return { error: new FloPayError2("Stripe not initialized", "api_error") };
1929
- }
1930
- const { error } = await this.elements.submit();
1931
- if (error) {
1932
- return {
1933
- error: new FloPayError2(error.message ?? "Validation failed", "validation_error")
1934
- };
1935
- }
1936
- return {};
1937
- }
1938
- async confirmPayment(params) {
1939
- if (!this.stripe || !this.elements) {
1940
- throw new FloPayError2(
1941
- "StripeAdapter not initialized or no elements created.",
1942
- "api_error"
1943
- );
1944
- }
1945
- const billing = params.billingDetails;
1946
- const paymentMethodData = billing ? toStripeBillingDetails(billing) : void 0;
1947
- const { error, paymentIntent } = await this.stripe.confirmPayment({
1948
- elements: this.elements,
1949
- clientSecret: params.clientSecret,
1950
- confirmParams: {
1951
- return_url: params.returnUrl ?? window.location.href,
1952
- ...paymentMethodData ? { payment_method_data: paymentMethodData } : {}
1953
- },
1954
- redirect: "if_required"
1955
- });
1956
- if (error) {
1957
- return {
1958
- status: "failed",
1959
- error: new FloPayError2(
1960
- error.message ?? "Payment failed",
1961
- "api_error",
1962
- {
1963
- code: error.code,
1964
- declineCode: error.decline_code
1965
- }
1966
- )
1967
- };
1968
- }
1969
- if (!paymentIntent) {
1970
- return { status: "failed", error: new FloPayError2("No payment intent returned", "api_error") };
1971
- }
1972
- const statusMap = {
1973
- succeeded: "succeeded",
1974
- processing: "processing",
1975
- requires_action: "requires_action",
1976
- requires_payment_method: "failed",
1977
- canceled: "failed"
1978
- };
1979
- return {
1980
- status: statusMap[paymentIntent.status] ?? "failed",
1981
- paymentIntentId: paymentIntent.id,
1982
- paymentMethodId: this.extractPaymentMethodId(paymentIntent.payment_method)
1983
- };
1984
- }
1985
- extractPaymentMethodId(paymentMethod) {
1986
- if (typeof paymentMethod === "string" && paymentMethod.startsWith("pm_")) {
1987
- return paymentMethod;
1988
- }
1989
- if (paymentMethod && typeof paymentMethod === "object" && typeof paymentMethod.id === "string") {
1990
- return paymentMethod.id;
1991
- }
1992
- return void 0;
1993
- }
1994
- async confirmPayPalPayment(params) {
1995
- if (!this.stripe) {
1996
- return { status: "failed", error: new FloPayError2("Stripe not initialized", "api_error") };
1997
- }
1998
- const baseUrl = params.billingApiUrl.replace(/\/+$/, "");
1999
- if (this.elements) {
2000
- const { error: submitError } = await this.elements.submit();
2001
- if (submitError) {
2002
- return {
2003
- status: "failed",
2004
- error: new FloPayError2(
2005
- submitError.message ?? "PayPal payment failed",
2006
- "validation_error",
2007
- { code: submitError.code }
2008
- )
2009
- };
2010
- }
2011
- }
2012
- let intentClientSecret;
2013
- try {
2014
- const intent = await new PaymentAPI(baseUrl).createSessionIntent(
2015
- params.sessionId,
2016
- params.nonce ?? "",
2017
- {
2018
- provider: "stripe",
2019
- paymentMethodCategory: "wallet",
2020
- paymentMethodType: "paypal",
2021
- paymentMethodId: null,
2022
- intentKind: "payment"
2023
- }
2024
- );
2025
- if (intent.provider !== "stripe") {
2026
- throw new FloPayError2("Invalid provider returned for PayPal intent", "api_error");
2027
- }
2028
- intentClientSecret = intent.clientSecret;
2029
- } catch (error2) {
2030
- return {
2031
- status: "failed",
2032
- error: error2 instanceof FloPayError2 ? error2 : new FloPayError2("Failed to create PayPal payment intent", "api_error")
2033
- };
2034
- }
2035
- const { error } = await this.stripe.confirmPayment({
2036
- clientSecret: intentClientSecret,
2037
- elements: this.elements ?? void 0,
2038
- confirmParams: { return_url: params.returnUrl }
2039
- });
2040
- if (error) {
2041
- if (params.nonce) {
2042
- try {
2043
- await new PaymentAPI(baseUrl).reportSessionIntentDecline(
2044
- params.sessionId,
2045
- params.nonce,
2046
- {
2047
- provider: "stripe",
2048
- paymentMethodCategory: "wallet",
2049
- paymentMethodType: "paypal",
2050
- providerDeclineReason: error.code ?? "provider_declined"
2051
- }
2052
- );
2053
- } catch {
2054
- }
2055
- }
2056
- return {
2057
- status: "failed",
2058
- error: new FloPayError2(error.message ?? "PayPal payment failed", "api_error", { code: error.code })
2059
- };
2060
- }
2061
- return {
2062
- status: "processing"
2063
- };
2064
- }
2065
- async resumePayPalPayment() {
2066
- if (!this.stripe || typeof window === "undefined") return null;
2067
- const params = new URLSearchParams(window.location.search);
2068
- const paymentIntentId = params.get("payment_intent");
2069
- const clientSecret = params.get("payment_intent_client_secret");
2070
- const redirectStatus = params.get("redirect_status");
2071
- if (!paymentIntentId || !clientSecret) return null;
2072
- if (redirectStatus === "failed") {
2073
- return {
2074
- status: "failed",
2075
- error: new FloPayError2("PayPal payment was declined. Please try again.", "api_error")
2076
- };
2077
- }
2078
- const { paymentIntent, error } = await this.stripe.retrievePaymentIntent(clientSecret);
2079
- if (error) {
2080
- return {
2081
- status: "failed",
2082
- error: new FloPayError2(error.message ?? "Failed to retrieve PayPal payment", "api_error")
2083
- };
2084
- }
2085
- if (paymentIntent && (paymentIntent.status === "requires_capture" || paymentIntent.status === "succeeded")) {
2086
- const pmId = typeof paymentIntent.payment_method === "string" ? paymentIntent.payment_method : paymentIntent.payment_method?.id;
2087
- const url = new URL(window.location.href);
2088
- url.searchParams.delete("payment_intent");
2089
- url.searchParams.delete("payment_intent_client_secret");
2090
- url.searchParams.delete("redirect_status");
2091
- window.history.replaceState({}, "", url.toString());
2092
- return {
2093
- status: paymentIntent.status,
2094
- paymentIntentId: paymentIntent.id,
2095
- paymentMethodId: pmId
2096
- };
2097
- }
2098
- return {
2099
- status: "failed",
2100
- error: new FloPayError2("PayPal payment was not completed. Please try again.", "api_error")
2101
- };
2102
- }
2103
- getRawProvider() {
2104
- return this.stripe;
2105
- }
2106
- createPayPalElements(options) {
2107
- if (!this.stripe) return null;
2108
- const elementsOptions = {
2109
- mode: "payment",
2110
- amount: options.amount ?? 0,
2111
- currency: (options.currency ?? "usd").toLowerCase(),
2112
- captureMethod: "manual"
2113
- };
2114
- if (options.setupFutureUsage) {
2115
- elementsOptions["setupFutureUsage"] = options.setupFutureUsage;
2116
- }
2117
- if (options.appearance) {
2118
- elementsOptions["appearance"] = {
2119
- theme: toStripeAppearanceTheme(options.appearance.theme),
2120
- variables: options.appearance.variables,
2121
- rules: options.appearance.rules
2122
- };
2123
- }
2124
- return this.stripe.elements(elementsOptions);
2125
- }
2126
- destroy() {
2127
- this.elements = null;
2128
- this.appliedAppearanceKey = null;
2129
- this.appliedPaymentMethodTypesKey = null;
2130
- this.appliedClientSecret = null;
2131
- this.verifiedClientSecret = null;
2132
- this.verifiedPaymentMethodTypesKey = null;
2133
- this.stripe = null;
2134
- }
2135
- };
2136
-
2137
- // src/flopay.ts
2138
- import { FloPayError as FloPayError5, resolveBillingApiUrl as resolveBillingApiUrl2, SDK_VERSION as SDK_VERSION3 } from "@flopay/shared";
2139
-
2140
- // src/elements.ts
2141
- import { FloPayError as FloPayError3 } from "@flopay/shared";
2142
- var FloPayElements = class {
2143
- constructor(provider, options) {
2144
- this.elementMap = /* @__PURE__ */ new Map();
2145
- this.provider = provider;
2146
- this.baseOptions = options ?? {};
2147
- }
2148
- /**
2149
- * Creates a new element of the given type.
2150
- * If an element of that type already exists, it is destroyed first.
2151
- */
2152
- async create(type, options) {
2153
- const merged = { ...this.baseOptions, ...options };
2154
- if (type === "payment") {
2155
- const paymentMethodTypes = merged.paymentMethodTypes?.map((paymentMethodType) => paymentMethodType.trim()).filter((paymentMethodType) => paymentMethodType && paymentMethodType.toLowerCase() !== "card");
2156
- if (!paymentMethodTypes?.length) {
2157
- throw new FloPayError3(
2158
- "At least one supported non-card payment method is required.",
2159
- "validation_error",
2160
- { param: "paymentMethodTypes" }
2161
- );
2162
- }
2163
- merged.paymentMethodTypes = paymentMethodTypes;
2164
- }
2165
- const providerExisting = this.provider.getElement(type);
2166
- if (providerExisting) {
2167
- this.elementMap.set(type, providerExisting);
2168
- return providerExisting;
2169
- }
2170
- const existing = this.elementMap.get(type);
2171
- if (existing) {
2172
- existing.destroy();
2173
- }
2174
- const element = await this.provider.createElement(type, merged);
2175
- this.elementMap.set(type, element);
2176
- return element;
2177
- }
2178
- /** Returns a previously created element, or `null`. */
2179
- getElement(type) {
2180
- return this.elementMap.get(type) ?? null;
2181
- }
2182
- /**
2183
- * Submits all mounted elements for validation.
2184
- *
2185
- * Returns an object with an optional error if validation fails.
2186
- * This does NOT confirm the payment — call `floPay.confirmPayment()` for that.
2187
- */
2188
- async submit() {
2189
- return {};
2190
- }
2191
- /** Destroys all created elements and clears the internal map. */
2192
- destroy() {
2193
- for (const element of this.elementMap.values()) {
2194
- element.destroy();
2195
- }
2196
- this.elementMap.clear();
2197
- }
2198
- };
2199
-
2200
- // src/pci-vault-card-capture.ts
2201
- import {
2202
- buildTelemetryErrorEvent as buildTelemetryErrorEvent2,
2203
- buildTelemetryLogEvent as buildTelemetryLogEvent2,
2204
- buildTelemetryTerminalEvent as buildTelemetryTerminalEvent2,
2205
- FloPayError as FloPayError4,
2206
- resolveBillingApiUrl,
2207
- SDK_VERSION as SDK_VERSION2
2208
- } from "@flopay/shared";
2209
- var VAULT_MESSAGE_SOURCE = "flopay-vault";
2210
- var VAULT_NON_TERMINAL_OUTCOME_LOGS = {
2211
- ready: ["vault.widget.ready", "vault_ready"],
2212
- submitting: ["vault.submission.started", "vault_submit"],
2213
- blocked: ["operation.state_transition", "vault_submit"],
2214
- action_required: ["vault.action.required", "three_ds_handoff"]
2215
- };
2216
- function addBreadcrumb(event) {
2217
- const data = {
2218
- class: event.class,
2219
- stage: event.stage
2220
- };
2221
- if ("code" in event) data["code"] = event.code;
2222
- if ("provider" in event && event.provider) data["provider"] = event.provider;
2223
- if ("paymentMethodCategory" in event && event.paymentMethodCategory) {
2224
- data["paymentMethodCategory"] = event.paymentMethodCategory;
2225
- }
2226
- if ("outcome" in event) data["outcome"] = event.outcome;
2227
- if ("durationMs" in event && event.durationMs !== void 0) data["durationMs"] = event.durationMs;
2228
- if ("durationMode" in event && event.durationMode) data["durationMode"] = event.durationMode;
2229
- try {
2230
- const sentry = globalThis.Sentry;
2231
- sentry?.addBreadcrumb?.({
2232
- category: "flopay.telemetry",
2233
- level: event.class === "technical_error" ? "error" : "info",
2234
- message: event.class === "lifecycle" ? event.name : event.class === "technical_error" ? event.code : event.class === "expected_outcome" ? event.outcome : "sdk.performance",
2235
- data
2236
- });
2237
- } catch {
2238
- }
2239
- }
2240
- function vaultLog(name, stage) {
2241
- return buildTelemetryLogEvent2({
2242
- eventId: "11111111-1111-4111-8111-111111111111",
2243
- name,
2244
- stage,
2245
- sequence: 0,
2246
- provider: "pcivault",
2247
- paymentMethodCategory: "card"
2248
- });
2249
- }
2250
- function vaultErrorClassification(submissionStarted) {
2251
- return submissionStarted ? { errorCode: "VAULT_SUBMIT_FAILED", stage: "vault_submit" } : { errorCode: "VAULT_LOAD_FAILED", stage: "vault_mount" };
2252
- }
2253
- function vaultOutcomeBreadcrumb(type, submissionStarted) {
2254
- if (type === "complete" || type === "decline") {
2255
- return buildTelemetryTerminalEvent2({
2256
- eventId: "22222222-2222-4222-8222-222222222222",
2257
- outcome: type === "complete" ? "payment_succeeded" : "payment_declined",
2258
- sequence: 0,
2259
- provider: "pcivault",
2260
- paymentMethodCategory: "card"
2261
- });
2262
- }
2263
- if (type === "error") {
2264
- const classification = vaultErrorClassification(submissionStarted);
2265
- return buildTelemetryErrorEvent2({
2266
- eventId: "33333333-3333-4333-8333-333333333333",
2267
- ...classification,
2268
- sequence: 0,
2269
- provider: "pcivault",
2270
- paymentMethodCategory: "card"
2271
- });
2272
- }
2273
- const [name, stage] = VAULT_NON_TERMINAL_OUTCOME_LOGS[type];
2274
- return vaultLog(name, stage);
2275
- }
2276
- function isVaultResultMessage(value) {
2277
- if (typeof value !== "object" || value === null) return false;
2278
- const record = value;
2279
- return record["source"] === VAULT_MESSAGE_SOURCE && (record["type"] === "ready" || record["type"] === "submitting" || record["type"] === "blocked" || record["type"] === "complete" || record["type"] === "decline" || record["type"] === "error" || record["type"] === "action_required");
2280
- }
2281
- function isVaultValidationMessage(value) {
2282
- if (typeof value !== "object" || value === null) return false;
2283
- const record = value;
2284
- return record["source"] === VAULT_MESSAGE_SOURCE && record["type"] === "validation" && Array.isArray(record["messages"]);
2285
- }
2286
- function isVaultResizeMessage(value) {
2287
- if (typeof value !== "object" || value === null) return false;
2288
- const record = value;
2289
- return record["source"] === VAULT_MESSAGE_SOURCE && record["type"] === "resize" && typeof record["height"] === "number" && Number.isFinite(record["height"]);
2290
- }
2291
- var PciVaultCardCapture = class {
2292
- constructor(config = {}, internalTelemetry) {
2293
- this.provider = "pcivault";
2294
- this.container = null;
2295
- this.messageHandler = null;
2296
- /**
2297
- * Parent-page-level overlay rendering the provider's verification challenge
2298
- * (3DS-2 iframe) on `action_required`. Owned by the adapter — not the
2299
- * widget — so it can sit above the host SDK's processing backdrop, which
2300
- * would otherwise visually cover an in-widget challenge iframe.
2301
- */
2302
- this.actionOverlay = null;
2303
- /**
2304
- * Listener that catches the `flopay-vault-3ds-return` postMessage from the
2305
- * provider's challenge return page. When the SDK owns the challenge iframe
2306
- * the return page lives inside *that* iframe (not the widget's), so
2307
- * `window.parent` is the host page — the widget's existing message
2308
- * listener can't see it. The SDK forwards completion into the widget via
2309
- * `action_completed` so the widget kicks `/3ds/complete` immediately
2310
- * instead of waiting on the eventual provider webhook.
2311
- */
2312
- this.threeDsReturnHandler = null;
2313
- /** Per-session integrity token to require on outcomes (from mount options). */
2314
- this.messageToken = null;
2315
- /** Strict origin to require on outcomes, when configured. */
2316
- this.expectedOrigin = null;
2317
- /** Latest merchant theme to push into the (cross-origin) widget. */
2318
- this.theme = null;
2319
- /** Latest host submit-gate state to push into the widget (block its submit). */
2320
- this.submitGateBlocked = false;
2321
- /** Latest card-field order + autofocus directive to push into the widget. */
2322
- this.cardFieldOrder = null;
2323
- this.cardAutoFocus = true;
2324
- this.captureRequestedAt = 0;
2325
- this.vaultReadyReported = false;
2326
- this.submissionStarted = false;
2327
- this.submissionStartedAt = null;
2328
- this.listeners = /* @__PURE__ */ new Map();
2329
- this.config = config;
2330
- this.ownsTelemetryReporter = !internalTelemetry && config.telemetry !== false;
2331
- this.telemetryReporter = internalTelemetry?.reporter ?? (this.ownsTelemetryReporter ? new TelemetryReporter({
2332
- billingApiUrl: resolveBillingApiUrl(),
2333
- sdkVersion: SDK_VERSION2
2334
- }) : void 0);
2335
- this.requestedAt = internalTelemetry?.requestedAt;
2336
- }
2337
- async mount(container, options) {
2338
- if (this.ownsTelemetryReporter && !this.telemetryReporter) {
2339
- this.telemetryReporter = new TelemetryReporter({
2340
- billingApiUrl: resolveBillingApiUrl(),
2341
- sdkVersion: SDK_VERSION2
2342
- });
2343
- }
2344
- const mountedAt = this.telemetryReporter?.now?.() ?? telemetryNow();
2345
- this.captureRequestedAt = this.requestedAt ?? mountedAt;
2346
- this.vaultReadyReported = false;
2347
- this.submissionStarted = false;
2348
- this.submissionStartedAt = null;
2349
- if (typeof window === "undefined" || typeof document === "undefined") {
2350
- this.reportVaultLoadFailure();
2351
- throw new FloPayError4(
2352
- "The vault card form is only available in the browser.",
2353
- "api_error",
2354
- { code: "card_capture_no_window" }
2355
- );
2356
- }
2357
- if (!options?.html || !options.html.trim()) {
2358
- this.reportVaultLoadFailure();
2359
- throw new FloPayError4(
2360
- "No vault capture widget HTML was provided to mount the secure card form.",
2361
- "api_error",
2362
- { code: "card_capture_no_widget_html" }
2363
- );
2364
- }
2365
- this.container = container;
2366
- this.messageToken = options.messageToken ?? null;
2367
- this.expectedOrigin = options.expectedOrigin ?? this.config.expectedOrigin ?? null;
2368
- this.theme = options.theme ?? null;
2369
- try {
2370
- this.attachMessageListener();
2371
- this.injectWidget(container, options.html);
2372
- } catch (error) {
2373
- this.reportVaultLoadFailure();
2374
- throw error;
2375
- }
2376
- this.postTheme();
2377
- this.postSubmitGate();
2378
- this.postCardFieldOrder();
2379
- addBreadcrumb(vaultLog("vault.widget.mounted", "vault_mount"));
2380
- this.telemetryReporter?.log({
2381
- name: "vault.widget.mounted",
2382
- stage: "vault_mount",
2383
- provider: "pcivault",
2384
- paymentMethodCategory: "card"
2385
- });
2386
- this.emit("ready", { sessionId: this.config.sessionId });
2387
- }
2388
- reportVaultLoadFailure() {
2389
- this.telemetryReporter?.error({
2390
- errorCode: "VAULT_LOAD_FAILED",
2391
- stage: "vault_mount",
2392
- provider: "pcivault",
2393
- paymentMethodCategory: "card"
2394
- });
2395
- }
2396
- on(event, handler) {
2397
- let set = this.listeners.get(event);
2398
- if (!set) {
2399
- set = /* @__PURE__ */ new Set();
2400
- this.listeners.set(event, set);
2401
- }
2402
- set.add(handler);
2403
- return () => {
2404
- this.listeners.get(event)?.delete(handler);
2405
- };
2406
- }
2407
- unmount() {
2408
- this.hideActionRequiredOverlay();
2409
- if (this.messageHandler) {
2410
- window.removeEventListener("message", this.messageHandler);
2411
- this.messageHandler = null;
2412
- }
2413
- if (this.container) {
2414
- this.container.replaceChildren();
2415
- this.container = null;
2416
- }
2417
- this.messageToken = null;
2418
- this.expectedOrigin = null;
2419
- if (this.ownsTelemetryReporter) {
2420
- this.telemetryReporter?.destroy();
2421
- this.telemetryReporter = void 0;
2422
- }
2423
- }
2424
- // ── internals ──
2425
- /**
2426
- * Inject the server-rendered widget HTML. `innerHTML` does not execute
2427
- * embedded `<script>` tags, so each script node is replaced with a freshly
2428
- * created element that the browser will load and run (this is what boots the
2429
- * PCIVault form bundle against the `data-flopay-config` container).
2430
- */
2431
- injectWidget(container, html) {
2432
- container.innerHTML = html;
2433
- const scripts = Array.from(container.querySelectorAll("script"));
2434
- for (const oldScript of scripts) {
2435
- const script = document.createElement("script");
2436
- for (const attr of Array.from(oldScript.attributes)) {
2437
- script.setAttribute(attr.name, attr.value);
2438
- }
2439
- script.text = oldScript.text;
2440
- oldScript.replaceWith(script);
2441
- }
2442
- }
2443
- attachMessageListener() {
2444
- if (this.messageHandler) return;
2445
- const handler = (event) => {
2446
- if (this.expectedOrigin && event.origin !== this.expectedOrigin) return;
2447
- const data = event.data;
2448
- if (isVaultResizeMessage(data)) {
2449
- if (this.messageToken && data.messageToken !== this.messageToken) return;
2450
- this.applyHeight(data.height);
2451
- return;
2452
- }
2453
- if (isVaultValidationMessage(data)) {
2454
- if (this.messageToken && data.messageToken !== this.messageToken) return;
2455
- const text = data.messages.filter((m) => typeof m === "string" && m.trim()).join(" ");
2456
- this.emit("validation", { sessionId: this.config.sessionId, message: text || void 0 });
2457
- return;
2458
- }
2459
- if (!isVaultResultMessage(data)) return;
2460
- if (this.messageToken && data.messageToken !== this.messageToken) return;
2461
- const boundSession = this.config.sessionId;
2462
- const incomingSession = typeof data.sessionId === "string" ? data.sessionId : void 0;
2463
- if (boundSession && incomingSession && incomingSession !== boundSession) {
2464
- return;
2465
- }
2466
- if ((data.type === "complete" || data.type === "decline") && boundSession && incomingSession !== boundSession) {
2467
- return;
2468
- }
2469
- const outcome = {
2470
- sessionId: data.sessionId ?? this.config.sessionId,
2471
- intentId: data.intentId,
2472
- declineReason: data.declineReason,
2473
- message: data.message,
2474
- nextActionRedirectUrl: data.nextActionRedirectUrl
2475
- };
2476
- if (data.type === "submitting") {
2477
- this.submissionStarted = true;
2478
- this.submissionStartedAt = this.telemetryReporter?.now?.() ?? telemetryNow();
2479
- }
2480
- addBreadcrumb(vaultOutcomeBreadcrumb(data.type, this.submissionStarted));
2481
- this.reportOutcome(data.type);
2482
- if (data.type === "ready") {
2483
- this.postTheme();
2484
- this.postSubmitGate();
2485
- this.postCardFieldOrder();
2486
- }
2487
- if (data.type === "action_required" && data.nextActionRedirectUrl) {
2488
- this.showActionRequiredOverlay(data.nextActionRedirectUrl);
2489
- }
2490
- if (data.type === "complete" || data.type === "decline" || data.type === "error" || data.type === "submitting") {
2491
- this.hideActionRequiredOverlay();
2492
- }
2493
- this.emit(data.type, outcome);
2494
- };
2495
- this.messageHandler = handler;
2496
- window.addEventListener("message", handler);
2497
- }
2498
- reportOutcome(type) {
2499
- const reporter = this.telemetryReporter;
2500
- if (!reporter) return;
2501
- if (type === "ready" && !this.vaultReadyReported) {
2502
- this.vaultReadyReported = true;
2503
- reporter.performance({
2504
- stage: "vault_ready",
2505
- durationMs: Math.max(0, reporter.now() - this.captureRequestedAt),
2506
- durationMode: "machine",
2507
- provider: "pcivault",
2508
- paymentMethodCategory: "card"
2509
- });
2510
- }
2511
- if (type === "complete" || type === "decline") {
2512
- reporter.log({
2513
- name: "vault.terminal",
2514
- stage: "completion",
2515
- provider: "pcivault",
2516
- paymentMethodCategory: "card"
2517
- });
2518
- reporter.terminal({
2519
- outcome: type === "complete" ? "payment_succeeded" : "payment_declined",
2520
- provider: "pcivault",
2521
- paymentMethodCategory: "card"
2522
- });
2523
- return;
2524
- }
2525
- if (type === "error") {
2526
- const classification = vaultErrorClassification(this.submissionStarted);
2527
- reporter.log({
2528
- name: "vault.terminal",
2529
- stage: classification.stage,
2530
- provider: "pcivault",
2531
- paymentMethodCategory: "card"
2532
- });
2533
- reporter.error({
2534
- ...classification,
2535
- provider: "pcivault",
2536
- paymentMethodCategory: "card"
2537
- });
2538
- return;
2539
- }
2540
- if (type === "action_required") {
2541
- reporter.log({
2542
- name: "vault.action.required",
2543
- stage: "three_ds_handoff",
2544
- provider: "pcivault",
2545
- paymentMethodCategory: "card"
2546
- });
2547
- reporter.log({
2548
- name: "vault.three_ds.handoff",
2549
- stage: "three_ds_handoff",
2550
- provider: "pcivault",
2551
- paymentMethodCategory: "card"
2552
- });
2553
- const submissionStartedAt = this.submissionStartedAt;
2554
- this.submissionStartedAt = null;
2555
- if (submissionStartedAt !== null) {
2556
- reporter.performance({
2557
- stage: "three_ds_handoff",
2558
- durationMs: Math.max(0, reporter.now() - submissionStartedAt),
2559
- durationMode: "machine",
2560
- provider: "pcivault",
2561
- paymentMethodCategory: "card"
2562
- });
2563
- }
2564
- reporter.terminal({
2565
- outcome: "action_required",
2566
- stage: "three_ds_handoff",
2567
- provider: "pcivault",
2568
- paymentMethodCategory: "card"
2569
- });
2570
- return;
2571
- }
2572
- const [name, stage] = VAULT_NON_TERMINAL_OUTCOME_LOGS[type];
2573
- reporter.log({
2574
- name,
2575
- stage,
2576
- provider: "pcivault",
2577
- paymentMethodCategory: "card"
2578
- });
2579
- }
2580
- /**
2581
- * Push merchant theme colors into the hosted widget (live). The host calls
2582
- * this on a runtime theme switch; the widget applies them to its CSS variables
2583
- * without a remount. Stores the latest theme so `ready` can re-push it.
2584
- */
2585
- applyTheme(theme) {
2586
- this.theme = theme;
2587
- this.postTheme();
2588
- }
2589
- /** postMessage the current theme to the widget's (cross-origin) document. */
2590
- postTheme() {
2591
- if (!this.theme || !this.container) return;
2592
- const iframe = this.container.querySelector("iframe");
2593
- const target = iframe?.contentWindow;
2594
- if (!target) return;
2595
- try {
2596
- target.postMessage({ source: "flopay-vault-host", type: "theme", theme: this.theme }, "*");
2597
- } catch {
2598
- }
2599
- }
2600
- /**
2601
- * Gate the widget's submit from the host. When `blocked`, the widget cancels
2602
- * its next submit and emits `'blocked'` instead of `'submitting'` so the host
2603
- * can validate merchant-DOM fields (AVS) first. Stored so `ready` re-pushes it.
2604
- */
2605
- setSubmitGate(blocked) {
2606
- this.submitGateBlocked = blocked;
2607
- this.postSubmitGate();
2608
- }
2609
- /** postMessage the current submit-gate state to the widget's document. */
2610
- postSubmitGate() {
2611
- if (!this.container) return;
2612
- const iframe = this.container.querySelector("iframe");
2613
- const target = iframe?.contentWindow;
2614
- if (!target) return;
2615
- try {
2616
- target.postMessage(
2617
- { source: "flopay-vault-host", type: "gate", blocked: this.submitGateBlocked },
2618
- "*"
2619
- );
2620
- } catch {
2621
- }
2622
- }
2623
- /**
2624
- * Push the card-field order + autofocus directive into the widget (live). The
2625
- * widget re-sequences its rows (DOM order, so tab order follows) and focuses
2626
- * its first field unless `autoFocus` is false. Stored so `ready` re-pushes it.
2627
- */
2628
- setCardFieldOrder(order, autoFocus) {
2629
- this.cardFieldOrder = order;
2630
- this.cardAutoFocus = autoFocus;
2631
- this.postCardFieldOrder();
2632
- }
2633
- /** postMessage the current field order + autofocus to the widget's document. */
2634
- postCardFieldOrder() {
2635
- if (!this.container) return;
2636
- const iframe = this.container.querySelector("iframe");
2637
- const target = iframe?.contentWindow;
2638
- if (!target) return;
2639
- try {
2640
- target.postMessage(
2641
- {
2642
- source: "flopay-vault-host",
2643
- type: "fieldOrder",
2644
- order: this.cardFieldOrder,
2645
- autoFocus: this.cardAutoFocus
2646
- },
2647
- "*"
2648
- );
2649
- } catch {
2650
- }
2651
- }
2652
- emit(event, payload) {
2653
- for (const handler of this.listeners.get(event) ?? []) {
2654
- handler(payload);
2655
- }
2656
- }
2657
- /**
2658
- * Render the provider-hosted verification challenge (e.g. Stripe 3DS-2) in a
2659
- * full-page overlay at the PARENT page level. The widget's inline-iframe
2660
- * approach is unusable because the SDK's processing backdrop sits above the
2661
- * vault iframe, hiding any challenge mounted inside it — by lifting the
2662
- * iframe to the host page the adapter can give it a z-index that wins.
2663
- *
2664
- * The overlay tears down on the next terminal outcome
2665
- * (`complete`/`decline`/`error`) or when the buyer closes it via the backdrop
2666
- * close button. Closing manually is a soft abandon — the next `/status` poll
2667
- * either reveals a real outcome (the challenge completed via the issuer's
2668
- * own redirect to `/vault/3ds/return`, which posts back into the widget) or
2669
- * surfaces `requires_action` again so the host can decide what to do.
2670
- */
2671
- showActionRequiredOverlay(challengeUrl) {
2672
- if (typeof document === "undefined") return;
2673
- if (this.actionOverlay) {
2674
- const existingIframe = this.actionOverlay.querySelector("iframe");
2675
- if (existingIframe instanceof HTMLIFrameElement) {
2676
- existingIframe.src = challengeUrl;
2677
- }
2678
- return;
2679
- }
2680
- const backdrop = document.createElement("div");
2681
- backdrop.setAttribute("data-flopay-action-required", "1");
2682
- backdrop.style.cssText = [
2683
- "position:fixed",
2684
- "inset:0",
2685
- // Maximum signed 32-bit z-index; the SDK's own processing backdrop sits
2686
- // well below this so the challenge is visible and interactive.
2687
- "z-index:2147483647",
2688
- "background:rgba(15,23,42,0.6)",
2689
- "display:flex",
2690
- "align-items:center",
2691
- "justify-content:center",
2692
- "padding:16px"
2693
- ].join(";");
2694
- const frame = document.createElement("iframe");
2695
- frame.setAttribute("title", "Card authentication");
2696
- frame.setAttribute("allow", "payment");
2697
- frame.style.cssText = [
2698
- "width:min(100%,460px)",
2699
- "height:min(100%,640px)",
2700
- "border:0",
2701
- "border-radius:12px",
2702
- "background:#fff",
2703
- "box-shadow:0 12px 30px rgba(0,0,0,0.35)"
2704
- ].join(";");
2705
- frame.src = challengeUrl;
2706
- backdrop.appendChild(frame);
2707
- const closeButton = document.createElement("button");
2708
- closeButton.type = "button";
2709
- closeButton.setAttribute("aria-label", "Close card authentication");
2710
- closeButton.textContent = "\xD7";
2711
- closeButton.style.cssText = [
2712
- "position:fixed",
2713
- "top:20px",
2714
- "right:20px",
2715
- "width:40px",
2716
- "height:40px",
2717
- "border:0",
2718
- "border-radius:9999px",
2719
- "background:#fff",
2720
- "color:#0f172a",
2721
- "font-size:28px",
2722
- "line-height:40px",
2723
- "cursor:pointer",
2724
- "box-shadow:0 4px 14px rgba(0,0,0,0.25)"
2725
- ].join(";");
2726
- closeButton.addEventListener("click", () => this.abandonActionRequiredOverlay());
2727
- backdrop.appendChild(closeButton);
2728
- backdrop.addEventListener("click", (event) => {
2729
- if (event.target === backdrop) this.abandonActionRequiredOverlay();
2730
- });
2731
- const returnHandler = (event) => {
2732
- if (event.source !== frame.contentWindow) return;
2733
- const data = event.data;
2734
- if (!data || typeof data !== "object") return;
2735
- const record = data;
2736
- if (record["source"] !== "flopay-vault-3ds-return") return;
2737
- addBreadcrumb(vaultLog("vault.three_ds.returned", "three_ds_return"));
2738
- this.telemetryReporter?.log({
2739
- name: "vault.three_ds.returned",
2740
- stage: "three_ds_return",
2741
- provider: "pcivault",
2742
- paymentMethodCategory: "card"
2743
- });
2744
- this.hideActionRequiredOverlay();
2745
- this.postActionCompleted(record["status"]);
2746
- };
2747
- window.addEventListener("message", returnHandler);
2748
- this.threeDsReturnHandler = returnHandler;
2749
- document.body.appendChild(backdrop);
2750
- this.actionOverlay = backdrop;
2751
- addBreadcrumb(vaultLog("vault.three_ds.handoff", "three_ds_handoff"));
2752
- }
2753
- /**
2754
- * Tell the vault widget that the buyer has completed (or abandoned) the
2755
- * challenge. The widget responds by POSTing `/3ds/complete` — its
2756
- * sub-300ms sync resolver writes the follow-up attempt row immediately,
2757
- * so the next `/status` poll resolves to a terminal outcome instead of
2758
- * waiting for the eventual provider webhook.
2759
- */
2760
- postActionCompleted(status) {
2761
- if (!this.container) return;
2762
- const iframe = this.container.querySelector("iframe");
2763
- const target = iframe?.contentWindow;
2764
- if (!target) return;
2765
- try {
2766
- target.postMessage(
2767
- {
2768
- source: "flopay-vault-host",
2769
- type: "action_completed",
2770
- status: typeof status === "string" ? status : "unknown"
2771
- },
2772
- "*"
2773
- );
2774
- } catch {
2775
- }
2776
- }
2777
- abandonActionRequiredOverlay() {
2778
- if (!this.actionOverlay) return;
2779
- const breadcrumb = buildTelemetryTerminalEvent2({
2780
- eventId: "77777777-7777-4777-8777-777777777777",
2781
- outcome: "customer_abandoned",
2782
- stage: "three_ds_handoff",
2783
- sequence: 0,
2784
- provider: "pcivault",
2785
- paymentMethodCategory: "card"
2786
- });
2787
- addBreadcrumb(breadcrumb);
2788
- this.telemetryReporter?.terminal({
2789
- outcome: "customer_abandoned",
2790
- stage: "three_ds_handoff",
2791
- provider: "pcivault",
2792
- paymentMethodCategory: "card"
2793
- });
2794
- this.hideActionRequiredOverlay();
2795
- this.postActionCompleted("abandoned");
2796
- }
2797
- hideActionRequiredOverlay() {
2798
- if (this.threeDsReturnHandler) {
2799
- window.removeEventListener("message", this.threeDsReturnHandler);
2800
- this.threeDsReturnHandler = null;
2801
- }
2802
- if (!this.actionOverlay) return;
2803
- this.actionOverlay.parentNode?.removeChild(this.actionOverlay);
2804
- this.actionOverlay = null;
2805
- }
2806
- /**
2807
- * Size the hosted-widget iframe to the height reported by the form inside it.
2808
- * Cross-origin iframes don't auto-size to their content, so the widget posts
2809
- * its measured height and we apply it here (clamped to a sane range). This is
2810
- * what lets the card form shrink/grow to fit instead of sitting at a fixed
2811
- * height.
2812
- */
2813
- applyHeight(height) {
2814
- const iframe = this.container?.querySelector("iframe");
2815
- if (!iframe) return;
2816
- const clamped = Math.max(0, Math.min(Math.ceil(height), 2e3));
2817
- iframe.style.height = `${clamped}px`;
2818
- }
2819
- };
2820
- function createInstrumentedPciVaultCardCapture(config, reporter, requestedAt) {
2821
- const InstrumentedCapture = PciVaultCardCapture;
2822
- return new InstrumentedCapture(config, { reporter, requestedAt });
2823
- }
2824
-
2825
- // src/telemetry-bridge.ts
2826
- var FLOPAY_TELEMETRY_BRIDGE = /* @__PURE__ */ Symbol.for("@flopay/js.telemetry.bridge.v1");
2827
- function attachFloPayTelemetryBridge(target, reporter, fallbackNow) {
2828
- const now = () => reporter?.now() ?? fallbackNow();
2829
- const bridge = {
2830
- error: (input) => reporter?.error(input),
2831
- log: (input) => reporter?.log(input),
2832
- performance: (input) => reporter?.performance(input),
2833
- terminal: (input) => reporter?.terminal(input),
2834
- now,
2835
- elapsed: (startedAt) => Math.max(0, now() - startedAt),
2836
- setCheckoutContext: (context) => reporter?.setCheckoutContext(context),
2837
- beginCheckout: (context = {}) => reporter?.beginCheckout(context) ?? now(),
2838
- disable: () => reporter?.disable()
2839
- };
2840
- Object.defineProperty(target, FLOPAY_TELEMETRY_BRIDGE, {
2841
- configurable: false,
2842
- enumerable: false,
2843
- writable: false,
2844
- value: bridge
2845
- });
2846
- }
2847
- function getFloPayTelemetryBridge(target) {
2848
- return target[FLOPAY_TELEMETRY_BRIDGE];
2849
- }
2850
-
2851
- // src/flopay.ts
2852
- function isExpectedDecline(error) {
2853
- if (!error) return false;
2854
- const code = error.code?.toLowerCase() ?? "";
2855
- return Boolean(error.declineCode) || code.includes("declin");
2856
- }
2857
- function telemetryProvider(name) {
2858
- if (name === "stripe" || name === "paypal" || name === "pcivault") return name;
2859
- return "other";
2860
- }
2861
- var FloPay = class {
2862
- constructor(provider, config, telemetryReporter) {
2863
- this.currentElements = null;
2864
- this.provider = provider;
2865
- this.config = config;
2866
- this.telemetryReporter = telemetryReporter ?? new TelemetryReporter({
2867
- billingApiUrl: resolveBillingApiUrl2(config.billingApiUrl),
2868
- sdkVersion: SDK_VERSION3,
2869
- enabled: config.telemetry !== false
2870
- });
2871
- attachFloPayTelemetryBridge(this, this.telemetryReporter, telemetryNow);
2872
- }
2873
- now() {
2874
- return this.telemetryReporter?.now?.() ?? telemetryNow();
2875
- }
2876
- /**
2877
- * Creates a new `FloPayElements` group for mounting payment fields.
2878
- *
2879
- * Only one elements group is active at a time. Creating a new one
2880
- * destroys the previous group.
2881
- */
2882
- elements(options) {
2883
- if (this.currentElements) {
2884
- this.currentElements.destroy();
2885
- }
2886
- this.currentElements = new FloPayElements(this.provider, {
2887
- appearance: this.config.appearance,
2888
- ...options
2889
- });
2890
- return this.currentElements;
2891
- }
2892
- /** Submit elements for validation. */
2893
- async submitElements() {
2894
- return this.provider.submitElements();
2895
- }
2896
- /**
2897
- * Create a {@link CardCaptureAdapter} for collecting card details through the
2898
- * backend-rendered hosted vault PCI widget (TeamFloPay/backend#823).
2899
- *
2900
- * The returned adapter injects the server-supplied widget HTML (the session's
2901
- * {@link CheckoutSession.vault} block, or one fetched via
2902
- * `PaymentAPI.getVaultCapture`) and relays the widget's terminal outcome. The
2903
- * backend owns tokenization, the PaymentIntent, 3DS, and fulfilment — no
2904
- * Stripe.js is involved on the card path and PCI-sensitive fields never enter
2905
- * the SDK runtime.
2906
- */
2907
- cardCapture(options) {
2908
- const requestedAt = this.now();
2909
- this.telemetryReporter?.log({
2910
- name: "vault.capture.requested",
2911
- stage: "vault_request",
2912
- provider: "pcivault",
2913
- paymentMethodCategory: "card"
2914
- });
2915
- if (this.telemetryReporter) {
2916
- return createInstrumentedPciVaultCardCapture(
2917
- { sessionId: options?.sessionId },
2918
- this.telemetryReporter,
2919
- requestedAt
2920
- );
2921
- }
2922
- return new PciVaultCardCapture({
2923
- sessionId: options?.sessionId,
2924
- telemetry: false
2925
- });
2926
- }
2927
- /** Confirm a PayPal payment: create intent via billing API → confirm → redirect if needed. */
2928
- async confirmPayPalPayment(params) {
2929
- const startedAt = this.now();
2930
- this.telemetryReporter?.log({
2931
- name: "payment.method.selected",
2932
- stage: "processing",
2933
- provider: "paypal",
2934
- paymentMethodCategory: "paypal"
2935
- });
2936
- this.telemetryReporter?.log({
2937
- name: "payment.intent.started",
2938
- stage: "processing",
2939
- provider: "paypal",
2940
- paymentMethodCategory: "paypal",
2941
- requestCategory: "intent_create"
2942
- });
2943
- try {
2944
- const result = await this.provider.confirmPayPalPayment(params);
2945
- this.telemetryReporter?.performance({
2946
- stage: "processing",
2947
- durationMs: this.now() - startedAt,
2948
- durationMode: "machine",
2949
- provider: "paypal",
2950
- paymentMethodCategory: "paypal"
2951
- });
2952
- if (!result.error) {
2953
- this.telemetryReporter?.log({
2954
- name: "payment.intent.completed",
2955
- stage: "processing",
2956
- provider: "paypal",
2957
- paymentMethodCategory: "paypal",
2958
- requestCategory: "intent_create",
2959
- statusClass: "2xx"
2960
- });
2961
- }
2962
- if (result.status === "requires_action") {
2963
- this.telemetryReporter?.log({
2964
- name: "provider.redirect.started",
2965
- stage: "redirect",
2966
- provider: "paypal",
2967
- paymentMethodCategory: "paypal"
2968
- });
2969
- this.telemetryReporter?.terminal({
2970
- outcome: "action_required",
2971
- stage: "redirect",
2972
- provider: "paypal",
2973
- paymentMethodCategory: "paypal"
2974
- });
2975
- } else if (result.status === "succeeded") {
2976
- this.telemetryReporter?.terminal({
2977
- outcome: "payment_succeeded",
2978
- provider: "paypal",
2979
- paymentMethodCategory: "paypal"
2980
- });
2981
- } else if (result.status !== "processing") {
2982
- if (isExpectedDecline(result.error)) {
2983
- this.telemetryReporter?.terminal({
2984
- outcome: "payment_declined",
2985
- provider: "paypal",
2986
- paymentMethodCategory: "paypal"
2987
- });
2988
- } else if (result.error?.type === "validation_error") {
2989
- this.telemetryReporter?.terminal({
2990
- outcome: "validation_rejected",
2991
- provider: "paypal",
2992
- paymentMethodCategory: "paypal"
2993
- });
2994
- } else if (result.error) {
2995
- this.telemetryReporter?.error({
2996
- errorCode: "PAYMENT_PROCESSING_FAILED",
2997
- stage: "processing",
2998
- provider: "paypal",
2999
- paymentMethodCategory: "paypal",
3000
- requestCategory: "intent_create"
3001
- });
3002
- }
3003
- }
3004
- return result;
3005
- } catch (error) {
3006
- this.telemetryReporter?.performance({
3007
- stage: "processing",
3008
- durationMs: this.now() - startedAt,
3009
- durationMode: "machine",
3010
- provider: "paypal",
3011
- paymentMethodCategory: "paypal"
3012
- });
3013
- this.telemetryReporter?.error({
3014
- errorCode: "NETWORK_REQUEST_FAILED",
3015
- stage: "processing",
3016
- provider: "paypal",
3017
- paymentMethodCategory: "paypal",
3018
- requestCategory: "intent_create",
3019
- statusClass: "network_error"
3020
- });
3021
- throw error;
3022
- }
3023
- }
3024
- /** Resume a PayPal payment after redirect return. Returns null if no PayPal params in URL. */
3025
- async resumePayPalPayment() {
3026
- const startedAt = this.now();
3027
- try {
3028
- const result = await this.provider.resumePayPalPayment();
3029
- if (result === null) return null;
3030
- this.telemetryReporter?.log({
3031
- name: "provider.redirect.resumed",
3032
- stage: "redirect_resume",
3033
- provider: "paypal",
3034
- paymentMethodCategory: "paypal"
3035
- });
3036
- this.telemetryReporter?.performance({
3037
- stage: "redirect_resume",
3038
- durationMs: this.now() - startedAt,
3039
- durationMode: "machine",
3040
- provider: "paypal",
3041
- paymentMethodCategory: "paypal"
3042
- });
3043
- if (result.status === "succeeded") {
3044
- this.telemetryReporter?.terminal({
3045
- outcome: "payment_succeeded",
3046
- provider: "paypal",
3047
- paymentMethodCategory: "paypal"
3048
- });
3049
- } else if (isExpectedDecline(result.error)) {
3050
- this.telemetryReporter?.terminal({
3051
- outcome: "payment_declined",
3052
- provider: "paypal",
3053
- paymentMethodCategory: "paypal"
3054
- });
3055
- } else if (result.error?.type === "validation_error") {
3056
- this.telemetryReporter?.terminal({
3057
- outcome: "validation_rejected",
3058
- provider: "paypal",
3059
- paymentMethodCategory: "paypal"
3060
- });
3061
- } else if (result.error) {
3062
- this.telemetryReporter?.error({
3063
- errorCode: "REDIRECT_RESUME_FAILED",
3064
- stage: "redirect_resume",
3065
- provider: "paypal",
3066
- paymentMethodCategory: "paypal"
3067
- });
3068
- }
3069
- return result;
3070
- } catch (error) {
3071
- this.telemetryReporter?.performance({
3072
- stage: "redirect_resume",
3073
- durationMs: this.now() - startedAt,
3074
- durationMode: "machine",
3075
- provider: "paypal",
3076
- paymentMethodCategory: "paypal"
3077
- });
3078
- this.telemetryReporter?.error({
3079
- errorCode: "REDIRECT_RESUME_FAILED",
3080
- stage: "redirect_resume",
3081
- provider: "paypal",
3082
- paymentMethodCategory: "paypal"
3083
- });
3084
- throw error;
3085
- }
3086
- }
3087
- /** Confirms a non-card wallet/APM payment using the mounted PaymentElement. */
3088
- async confirmPayment(params) {
3089
- if (params.paymentMethodCategory !== "wallet" && params.paymentMethodCategory !== "apm" || !params.paymentMethodType?.trim() || params.paymentMethodType.trim().toLowerCase() === "card") {
3090
- throw new FloPayError5(
3091
- "A supported non-card payment method is required.",
3092
- "validation_error",
3093
- { param: "paymentMethodType" }
3094
- );
3095
- }
3096
- const started = this.now();
3097
- const provider = telemetryProvider(this.provider.name);
3098
- this.telemetryReporter?.log({
3099
- name: "payment.processing.started",
3100
- stage: "processing",
3101
- provider,
3102
- paymentMethodCategory: params.paymentMethodCategory
3103
- });
3104
- try {
3105
- const result = await this.provider.confirmPayment(params);
3106
- const durationMs = this.now() - started;
3107
- this.telemetryReporter?.performance({
3108
- stage: "processing",
3109
- durationMs,
3110
- durationMode: "machine",
3111
- provider,
3112
- paymentMethodCategory: params.paymentMethodCategory
3113
- });
3114
- if (result.status === "succeeded") {
3115
- this.telemetryReporter?.terminal({
3116
- outcome: "payment_succeeded",
3117
- provider,
3118
- paymentMethodCategory: params.paymentMethodCategory
3119
- });
3120
- } else if (isExpectedDecline(result.error)) {
3121
- this.telemetryReporter?.terminal({
3122
- outcome: "payment_declined",
3123
- provider,
3124
- paymentMethodCategory: params.paymentMethodCategory
3125
- });
3126
- } else if (result.error?.type === "validation_error") {
3127
- this.telemetryReporter?.terminal({
3128
- outcome: "validation_rejected",
3129
- provider,
3130
- paymentMethodCategory: params.paymentMethodCategory
3131
- });
3132
- } else if (result.status === "requires_action") {
3133
- this.telemetryReporter?.terminal({
3134
- outcome: "action_required",
3135
- stage: "three_ds_handoff",
3136
- provider,
3137
- paymentMethodCategory: params.paymentMethodCategory
3138
- });
3139
- } else if (result.status === "failed" && result.error) {
3140
- this.telemetryReporter?.error({
3141
- errorCode: "PAYMENT_PROCESSING_FAILED",
3142
- stage: "processing",
3143
- provider,
3144
- paymentMethodCategory: params.paymentMethodCategory
3145
- });
3146
- }
3147
- if (result.status === "succeeded" || result.status === "failed") {
3148
- this.telemetryReporter?.log({
3149
- name: "payment.processing.completed",
3150
- stage: "processing",
3151
- provider,
3152
- paymentMethodCategory: params.paymentMethodCategory
3153
- });
3154
- } else {
3155
- this.telemetryReporter?.log({
3156
- name: "operation.state_transition",
3157
- stage: result.status === "requires_action" ? "three_ds_handoff" : "processing",
3158
- provider,
3159
- paymentMethodCategory: params.paymentMethodCategory
3160
- });
3161
- }
3162
- return result;
3163
- } catch (error) {
3164
- this.telemetryReporter?.performance({
3165
- stage: "processing",
3166
- durationMs: this.now() - started,
3167
- durationMode: "machine",
3168
- provider,
3169
- paymentMethodCategory: params.paymentMethodCategory
3170
- });
3171
- this.telemetryReporter?.error({
3172
- errorCode: "PAYMENT_PROCESSING_FAILED",
3173
- stage: "processing",
3174
- provider,
3175
- paymentMethodCategory: params.paymentMethodCategory
3176
- });
3177
- throw error;
3178
- }
3179
- }
3180
- /**
3181
- * Retrieves a checkout session by ID via the billing API.
3182
- *
3183
- * Returns the normalized `CheckoutSession` with amount, currency,
3184
- * customer data, and status.
3185
- *
3186
- * Requires `billingApiUrl` to be set — either via `loadFloPay(key, { billingApiUrl })`
3187
- * or passed directly as the second argument.
3188
- */
3189
- async retrieveSession(sessionId, billingApiUrl) {
3190
- if (!sessionId) {
3191
- throw new FloPayError5(
3192
- "sessionId is required to retrieve a session.",
3193
- "validation_error",
3194
- { param: "sessionId" }
3195
- );
3196
- }
3197
- const unified = await this.retrieveUnifiedSession(sessionId, billingApiUrl);
3198
- if (!unified.data.session) {
3199
- throw new FloPayError5("Session not found", "api_error");
3200
- }
3201
- return unified.data.session;
3202
- }
3203
- /**
3204
- * Retrieves and normalizes a checkout session, including provider-specific
3205
- * data (Stripe clientSecret/publishableKey, Chargebee site, etc.).
3206
- *
3207
- * The billing API URL is resolved from: explicit param → `loadFloPay()` config
3208
- * → `NEXT_PUBLIC_FLOPAY_ENV` env var → `configureFlopay()` → staging fallback.
3209
- */
3210
- async retrieveUnifiedSession(sessionId, billingApiUrl) {
3211
- if (!sessionId) {
3212
- throw new FloPayError5(
3213
- "sessionId is required.",
3214
- "validation_error",
3215
- { param: "sessionId" }
3216
- );
3217
- }
3218
- const apiUrl = resolveBillingApiUrl2(billingApiUrl ?? this.config.billingApiUrl);
3219
- const started = this.now();
3220
- this.telemetryReporter?.log({
3221
- name: "session.read.started",
3222
- stage: "session_read",
3223
- requestCategory: "session_read"
3224
- });
3225
- let firstByteDuration;
3226
- const api = createInstrumentedPaymentAPI(apiUrl, {
3227
- now: () => this.telemetryReporter?.now() ?? telemetryNow(),
3228
- onFirstByte: (durationMs) => {
3229
- firstByteDuration = durationMs;
3230
- },
3231
- onRetry: (requestCategory, attempt) => {
3232
- this.telemetryReporter?.log({
3233
- name: "operation.retry",
3234
- stage: requestCategory === "session_read" ? "session_read" : "processing",
3235
- requestCategory,
3236
- attempt
3237
- });
3238
- }
3239
- });
3240
- try {
3241
- const result = await api.getUnifiedCheckoutSession(sessionId);
3242
- if (firstByteDuration !== void 0) {
3243
- this.telemetryReporter?.log({
3244
- name: "session.request.first_byte",
3245
- stage: "session_first_byte",
3246
- requestCategory: "session_read",
3247
- statusClass: "2xx"
3248
- });
3249
- this.telemetryReporter?.performance({
3250
- stage: "session_first_byte",
3251
- durationMs: firstByteDuration,
3252
- durationMode: "machine",
3253
- requestCategory: "session_read",
3254
- statusClass: "2xx"
3255
- });
3256
- }
3257
- this.telemetryReporter?.log({
3258
- name: "session.request.completed",
3259
- stage: "session_complete",
3260
- requestCategory: "session_read",
3261
- statusClass: "2xx"
3262
- });
3263
- this.telemetryReporter?.log({
3264
- name: "checkout.data.ready",
3265
- stage: "checkout_data_ready"
3266
- });
3267
- this.telemetryReporter?.performance({
3268
- stage: "session_complete",
3269
- durationMs: this.now() - started,
3270
- durationMode: "machine",
3271
- requestCategory: "session_read",
3272
- statusClass: "2xx"
3273
- });
3274
- return result;
3275
- } catch (error) {
3276
- const statusCode = error instanceof FloPayError5 ? error.statusCode : void 0;
3277
- this.telemetryReporter?.error({
3278
- errorCode: error instanceof FloPayError5 && error.code === "checkout_processing_timeout" ? "REQUEST_TIMEOUT" : "NETWORK_REQUEST_FAILED",
3279
- stage: "session_read",
3280
- provider: "flo",
3281
- paymentMethodCategory: "unknown"
3282
- });
3283
- this.telemetryReporter?.performance({
3284
- stage: "session_complete",
3285
- durationMs: this.now() - started,
3286
- durationMode: "machine",
3287
- requestCategory: "session_read",
3288
- statusClass: statusCode ? `${Math.floor(statusCode / 100)}xx` : "network_error"
3289
- });
3290
- throw error;
3291
- }
3292
- }
3293
- /**
3294
- * Returns the raw underlying provider instance (e.g. Stripe object).
3295
- * Used internally by components that need direct provider access,
3296
- * such as PayPal which requires its own Elements instance.
3297
- */
3298
- getRawProvider() {
3299
- return this.provider.getRawProvider();
3300
- }
3301
- /** Tears down the SDK instance and releases resources. */
3302
- destroy() {
3303
- this.telemetryReporter?.log({ name: "checkout.unmount", stage: "unmount" });
3304
- this.telemetryReporter?.destroy();
3305
- this.currentElements?.destroy();
3306
- this.currentElements = null;
3307
- this.provider.destroy();
3308
- }
3309
- };
3310
- function createInstrumentedFloPay(provider, config, reporter) {
3311
- const InstrumentedFloPay = FloPay;
3312
- return new InstrumentedFloPay(provider, config, reporter);
3313
- }
3314
-
3315
- // src/load.ts
3316
- var instanceCache = /* @__PURE__ */ new Map();
3317
- function stableCacheValue(value) {
3318
- if (Array.isArray(value)) return value.map(stableCacheValue);
3319
- if (value && typeof value === "object") {
3320
- return Object.fromEntries(
3321
- Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, stableCacheValue(entry)])
3322
- );
3323
- }
3324
- return value;
3325
- }
3326
- function instanceCacheKey(publishableKey, options) {
3327
- return JSON.stringify([
3328
- publishableKey,
3329
- resolveBillingApiUrl3(options?.billingApiUrl),
3330
- options?.telemetry !== false,
3331
- options?.locale ?? "auto",
3332
- options?.apiVersion ?? null,
3333
- stableCacheValue(options?.appearance ?? null)
3334
- ]);
3335
- }
3336
- var initializationCache = /* @__PURE__ */ new Map();
3337
- async function loadFloPay(publishableKey, options) {
3338
- if (!publishableKey) {
3339
- const reporter = new TelemetryReporter({
3340
- billingApiUrl: resolveBillingApiUrl3(options?.billingApiUrl),
3341
- sdkVersion: SDK_VERSION4,
3342
- enabled: options?.telemetry !== false
3343
- });
3344
- reporter.error({
3345
- errorCode: "CONFIGURATION_INVALID",
3346
- stage: "sdk_initialize",
3347
- paymentMethodCategory: "unknown"
3348
- });
3349
- void reporter.flush().catch(() => {
3350
- }).finally(() => reporter.destroy());
3351
- throw new FloPayError6(
3352
- "A publishable key is required to initialize FloPay.",
3353
- "validation_error",
3354
- { param: "publishableKey" }
3355
- );
3356
- }
3357
- const cacheKey = instanceCacheKey(publishableKey, options);
3358
- const cached = instanceCache.get(cacheKey);
3359
- if (cached) {
3360
- if (options?.telemetry !== false) {
3361
- getFloPayTelemetryBridge(cached)?.log({
3362
- name: "sdk.cache.hit",
3363
- stage: "sdk_initialize"
3364
- });
3365
- }
3366
- return cached;
3367
- }
3368
- const initializing = initializationCache.get(cacheKey);
3369
- if (initializing) return initializing;
3370
- const config = {
3371
- ...options,
3372
- publishableKey
3373
- };
3374
- const initialization = (async () => {
3375
- const reporter = new TelemetryReporter({
3376
- billingApiUrl: resolveBillingApiUrl3(config.billingApiUrl),
3377
- sdkVersion: SDK_VERSION4,
3378
- enabled: config.telemetry !== false
3379
- });
3380
- const initializationStarted = reporter.now();
3381
- reporter.log({ name: "sdk.initialize.started", stage: "sdk_initialize" });
3382
- reporter.log({ name: "sdk.cache.miss", stage: "sdk_initialize" });
3383
- reporter.log({
3384
- name: "provider.load.started",
3385
- stage: "provider_load",
3386
- provider: "stripe"
3387
- });
3388
- const adapter = new StripeAdapter();
3389
- try {
3390
- await adapter.initialize(config);
3391
- } catch (error) {
3392
- reporter.error({
3393
- errorCode: "SDK_INITIALIZATION_FAILED",
3394
- stage: "sdk_initialize",
3395
- provider: "stripe",
3396
- paymentMethodCategory: "unknown"
3397
- });
3398
- reporter.destroy();
3399
- throw error;
3400
- }
3401
- reporter.log({ name: "provider.ready", stage: "provider_ready", provider: "stripe" });
3402
- reporter.log({
3403
- name: "provider.availability.checked",
3404
- stage: "provider_ready",
3405
- provider: "stripe"
3406
- });
3407
- reporter.log({ name: "sdk.initialize.ready", stage: "sdk_initialize" });
3408
- const initializationDuration = reporter.now() - initializationStarted;
3409
- reporter.performance({
3410
- stage: "sdk_initialize",
3411
- durationMs: initializationDuration,
3412
- durationMode: "machine",
3413
- provider: "stripe"
3414
- });
3415
- reporter.performance({
3416
- stage: "provider_ready",
3417
- durationMs: initializationDuration,
3418
- durationMode: "machine",
3419
- provider: "stripe"
3420
- });
3421
- const instance = createInstrumentedFloPay(adapter, config, reporter);
3422
- instanceCache.set(cacheKey, instance);
3423
- return instance;
3424
- })();
3425
- initializationCache.set(cacheKey, initialization);
3426
- try {
3427
- return await initialization;
3428
- } finally {
3429
- if (initializationCache.get(cacheKey) === initialization) {
3430
- initializationCache.delete(cacheKey);
3431
- }
3432
- }
3433
- }
3434
-
3435
- // src/create-checkout-session.ts
3436
- import {
3437
- FloPayError as FloPayError7,
3438
- IDEMPOTENCY_IN_PROGRESS_CODE as IDEMPOTENCY_IN_PROGRESS_CODE2,
3439
- IDEMPOTENCY_KEY_HEADER as IDEMPOTENCY_KEY_HEADER2,
3440
- SDK_VERSION as SDK_VERSION5,
3441
- buildProductPayload as buildProductPayload2,
3442
- foldIntoProducts as foldIntoProducts2,
3443
- resolveIdempotencyKey as resolveIdempotencyKey2,
3444
- resolveSessionCurrency as resolveSessionCurrency2
3445
- } from "@flopay/shared";
3446
- var MAX_COUPON_CODES = 5;
3447
- function buildCheckoutSessionError(status, payload) {
3448
- const nested = payload?.error;
3449
- const code = readErrorString(payload?.code) ?? readErrorString(nested?.code) ?? `http_${status}`;
3450
- const message = readErrorString(payload?.message) ?? readErrorString(nested?.message) ?? defaultMessageForCode(code, status);
3451
- return new FloPayError7(message, "api_error", { code, statusCode: status });
3452
- }
3453
- function defaultMessageForCode(code, status) {
3454
- switch (code) {
3455
- case "CouponLimitExceeded":
3456
- return `Too many coupon codes \u2014 a checkout session accepts at most ${MAX_COUPON_CODES}.`;
3457
- case "CouponCurrencyUnsupported":
3458
- return "One of the applied coupons has no price configured for the cart currency.";
3459
- default:
3460
- return `Failed to create checkout session (HTTP ${status}).`;
3461
- }
3462
- }
3463
- async function createCheckoutSessionCore(options, onFirstByte) {
3464
- const {
3465
- billingApiUrl,
3466
- checkoutBaseUrl,
3467
- items = [],
3468
- subscriptions = [],
3469
- products,
3470
- account,
3471
- successUrl,
3472
- cancelUrl,
3473
- checkoutMode = "confirm",
3474
- couponCodes = [],
3475
- tagsData,
3476
- redirectParams = {},
3477
- setCookie = true,
3478
- timeoutMs = 12e3,
3479
- clientId,
3480
- currency,
3481
- utmMetadata,
3482
- idempotencyKey
3483
- } = options;
3484
- const resolvedIdempotencyKey = resolveIdempotencyKey2(idempotencyKey);
3485
- if (couponCodes.length > MAX_COUPON_CODES) {
3486
- throw new FloPayError7(
3487
- `Too many coupon codes \u2014 a checkout session accepts at most ${MAX_COUPON_CODES}.`,
3488
- "validation_error",
3489
- { code: "CouponLimitExceeded", param: "couponCodes" }
3490
- );
3491
- }
3492
- const wireProducts = products ?? foldIntoProducts2(items, subscriptions);
3493
- const sessionCurrency = resolveSessionCurrency2(currency, items, subscriptions, wireProducts);
3494
- if (!sessionCurrency) {
3495
- throw new FloPayError7(
3496
- "currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.",
3497
- "validation_error",
3498
- { code: "CurrencyRequired", param: "currency" }
3499
- );
3500
- }
3501
- const payload = {
3502
- clientId,
3503
- checkoutVersion: SDK_VERSION5,
3504
- successUrl,
3505
- cancelUrl,
3506
- currency: sessionCurrency,
3507
- checkoutMode,
3508
- products: wireProducts.map((product) => buildProductPayload2(product, sessionCurrency)),
3509
- accountData: {
3510
- userId: account.userId,
3511
- firstName: account.firstName ?? null,
3512
- lastName: account.lastName ?? null,
3513
- email: account.email,
3514
- country: account.country ?? null,
3515
- gender: account.gender ?? null,
3516
- city: account.city ?? null,
3517
- state: account.state ?? null,
3518
- zip: account.zip ?? null,
3519
- addressLine1: account.addressLine1 ?? null,
3520
- addressLine2: account.addressLine2 ?? null
3521
- },
3522
- couponCodes
3523
- };
3524
- if (tagsData) {
3525
- payload["tagsData"] = tagsData;
3526
- }
3527
- if (utmMetadata?.length) {
3528
- payload["utmMetadata"] = utmMetadata;
3529
- }
3530
- const url = `${billingApiUrl.replace(/\/+$/, "")}/v1/checkouts/sessions`;
3531
- const controller = new AbortController();
3532
- const timer = setTimeout(() => controller.abort(), timeoutMs);
3533
- const headers = { "Content-Type": "application/json" };
3534
- if (resolvedIdempotencyKey) {
3535
- headers[IDEMPOTENCY_KEY_HEADER2] = resolvedIdempotencyKey;
3536
- }
3537
- let status;
3538
- let body;
3539
- try {
3540
- const response = await fetch(url, {
3541
- method: "POST",
3542
- headers,
3543
- body: JSON.stringify(payload),
3544
- signal: controller.signal
3545
- });
3546
- try {
3547
- onFirstByte?.(response.status);
3548
- } catch {
3549
- }
3550
- status = response.status;
3551
- try {
3552
- body = await response.json();
3553
- } catch {
3554
- }
3555
- } finally {
3556
- clearTimeout(timer);
3557
- }
3558
- if (status >= 400) {
3559
- throw buildCheckoutSessionError(status, body);
3560
- }
3561
- if (status === 201) {
3562
- const uuid = body?.data?.uuid;
3563
- const nonce = body?.data?.nonce;
3564
- if (!uuid) {
3565
- throw new Error("Checkout session created but no UUID was returned by the billing API");
3566
- }
3567
- if (!nonce) {
3568
- throw new FloPayError7(
3569
- "Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.",
3570
- "api_error",
3571
- { code: "MissingCheckoutSessionToken" }
3572
- );
3573
- }
3574
- if (wireProducts.length || sessionCurrency) {
3575
- cacheSessionDisplayData(uuid, {
3576
- currency: sessionCurrency,
3577
- products: wireProducts.map((p) => ({
3578
- code: p.code ?? p.providerItemId ?? p.providerPlanId,
3579
- type: p.type,
3580
- name: p.name ?? p.itemName ?? p.providerItemName ?? p.subscriptionName ?? p.providerPlanName ?? null,
3581
- totalAmount: p.totalAmount,
3582
- overrideAmount: p.overrideAmount,
3583
- currency: p.currency ?? sessionCurrency
3584
- }))
3585
- });
3586
- }
3587
- const redirectUrl = new URL(`${checkoutBaseUrl.replace(/\/+$/, "")}/secure`);
3588
- redirectUrl.searchParams.set("id", uuid);
3589
- for (const [key, value] of Object.entries(redirectParams)) {
3590
- redirectUrl.searchParams.set(key, value);
3591
- }
3592
- if (setCookie && typeof window !== "undefined" && typeof document !== "undefined") {
3593
- const checkoutData = JSON.stringify({ origin_url: cancelUrl });
3594
- const domain = window.location.hostname.split(".").slice(-2).join(".");
3595
- document.cookie = `checkout_data=${encodeURIComponent(checkoutData)}; domain=.${domain}; path=/; max-age=3600; SameSite=Lax; Secure;`;
3596
- document.cookie = `flopay_checkout_token=${encodeURIComponent(nonce)}; domain=.${domain}; path=/; max-age=3600; SameSite=Lax; Secure;`;
3597
- }
3598
- if (typeof window !== "undefined") {
3599
- window.location.href = redirectUrl.toString();
3600
- }
3601
- return { status: 201, redirectUrl: redirectUrl.toString(), nonce };
3602
- }
3603
- if (status === 204) {
3604
- if (typeof window !== "undefined") {
3605
- window.location.href = successUrl;
3606
- }
3607
- return { status: 204 };
3608
- }
3609
- return { status };
3610
- }
3611
- async function createCheckoutSession(options) {
3612
- const telemetry = beginCreateSessionTelemetry(options);
3613
- const recordFirstByte = createFirstByteRecorder(telemetry);
3614
- try {
3615
- const result = await createCheckoutSessionCore(options, recordFirstByte);
3616
- completeCreateSessionTelemetry(telemetry, result);
3617
- return result;
3618
- } catch (error) {
3619
- failCreateSessionTelemetry(telemetry.reporter, error);
3620
- throw error;
3621
- } finally {
3622
- finishCreateSessionTelemetry(telemetry.reporter);
3623
- }
3624
- }
3625
- function createFirstByteRecorder(telemetry) {
3626
- let recorded = false;
3627
- return (status) => {
3628
- if (recorded) return;
3629
- recorded = true;
3630
- const statusClass = `${Math.floor(status / 100)}xx`;
3631
- telemetry.reporter.log({
3632
- name: "session.request.first_byte",
3633
- stage: "session_first_byte",
3634
- requestCategory: "session_create",
3635
- statusClass
3636
- });
3637
- telemetry.reporter.performance({
3638
- stage: "session_first_byte",
3639
- durationMs: telemetry.reporter.now() - telemetry.startedAt,
3640
- durationMode: "machine",
3641
- requestCategory: "session_create",
3642
- statusClass
3643
- });
3644
- };
3645
- }
3646
- function beginCreateSessionTelemetry(options) {
3647
- const reporter = new TelemetryReporter({
3648
- billingApiUrl: options.billingApiUrl,
3649
- sdkVersion: SDK_VERSION5,
3650
- enabled: options.telemetry !== false
3651
- });
3652
- const startedAt = reporter.now();
3653
- reporter.log({
3654
- name: "session.create.started",
3655
- stage: "session_create",
3656
- requestCategory: "session_create"
3657
- });
3658
- return { reporter, startedAt };
3659
- }
3660
- function completeCreateSessionTelemetry(telemetry, result) {
3661
- const statusClass = `${Math.floor(result.status / 100)}xx`;
3662
- telemetry.reporter.log({
3663
- name: "session.request.completed",
3664
- stage: "session_complete",
3665
- requestCategory: "session_create",
3666
- statusClass
3667
- });
3668
- telemetry.reporter.performance({
3669
- stage: "session_complete",
3670
- durationMs: telemetry.reporter.now() - telemetry.startedAt,
3671
- durationMode: "machine",
3672
- requestCategory: "session_create",
3673
- statusClass
3674
- });
3675
- }
3676
- function failCreateSessionTelemetry(reporter, error) {
3677
- if (error instanceof FloPayError7 && error.type === "validation_error") {
3678
- reporter.terminal({
3679
- outcome: "validation_rejected",
3680
- stage: "session_create",
3681
- requestCategory: "session_create"
3682
- });
3683
- return;
3684
- }
3685
- const statusCode = error instanceof FloPayError7 ? error.statusCode : void 0;
3686
- reporter.error({
3687
- errorCode: error instanceof Error && error.name === "AbortError" ? "REQUEST_TIMEOUT" : error instanceof TypeError ? "NETWORK_REQUEST_FAILED" : "CHECKOUT_SESSION_CREATE_FAILED",
3688
- stage: "session_create",
3689
- requestCategory: "session_create",
3690
- statusClass: error instanceof Error && error.name === "AbortError" ? "timeout" : statusCode ? `${Math.floor(statusCode / 100)}xx` : "network_error"
3691
- });
3692
- }
3693
- function finishCreateSessionTelemetry(reporter) {
3694
- void reporter.flush().catch(() => {
3695
- }).finally(() => reporter.destroy());
3696
- }
3697
- async function createCheckoutSessionWithRetries(options) {
3698
- const { maxRetries = 3, ...sessionOptions } = options;
3699
- const telemetry = beginCreateSessionTelemetry(options);
3700
- const recordFirstByte = createFirstByteRecorder(telemetry);
3701
- if (!Number.isFinite(maxRetries) || !Number.isInteger(maxRetries) || maxRetries <= 0) {
3702
- telemetry.reporter.terminal({
3703
- outcome: "validation_rejected",
3704
- stage: "session_create",
3705
- requestCategory: "session_create"
3706
- });
3707
- finishCreateSessionTelemetry(telemetry.reporter);
3708
- throw new Error("Number of retries must be greater than 0");
3709
- }
3710
- const attemptOptions = {
3711
- ...sessionOptions,
3712
- idempotencyKey: resolveIdempotencyKey2(sessionOptions.idempotencyKey)
3713
- };
3714
- let lastErr;
3715
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
3716
- try {
3717
- const result = await createCheckoutSessionCore(attemptOptions, recordFirstByte);
3718
- completeCreateSessionTelemetry(telemetry, result);
3719
- finishCreateSessionTelemetry(telemetry.reporter);
3720
- return result;
3721
- } catch (err) {
3722
- lastErr = err;
3723
- const isTransportAbort = err instanceof Error && err.name === "AbortError";
3724
- const isInProgressReplay = err instanceof FloPayError7 && err.code === IDEMPOTENCY_IN_PROGRESS_CODE2;
3725
- if ((isTransportAbort || isInProgressReplay) && attempt < maxRetries) {
3726
- telemetry.reporter.log({
3727
- name: "operation.retry",
3728
- stage: "session_create",
3729
- requestCategory: "session_create",
3730
- attempt: attempt + 1
3731
- });
3732
- await new Promise((r) => setTimeout(r, 100 * Math.pow(2, attempt)));
3733
- continue;
3734
- }
3735
- failCreateSessionTelemetry(telemetry.reporter, err);
3736
- finishCreateSessionTelemetry(telemetry.reporter);
3737
- throw err;
3738
- }
3739
- }
3740
- failCreateSessionTelemetry(telemetry.reporter, lastErr);
3741
- finishCreateSessionTelemetry(telemetry.reporter);
3742
- throw lastErr ?? new Error("Unknown error during checkout session creation");
3743
- }
3744
- export {
3745
- FloPay,
3746
- FloPayElements,
3747
- PaymentAPI,
3748
- PciVaultCardCapture,
3749
- StripeAdapter,
3750
- cacheSessionDisplayData,
3751
- clearSessionDisplayData,
3752
- createCheckoutSession,
3753
- createCheckoutSessionWithRetries,
3754
- getSessionDisplayData,
3755
- loadFloPay
3756
- };
3757
- //# sourceMappingURL=index.mjs.map
1
+ import{FloPayError as Kt,resolveBillingApiUrl as pe,SDK_VERSION as Ge}from"@flopay/shared";import{loadStripe as St}from"@stripe/stripe-js";import{FloPayError as y,isSetupIntentClientSecret as At}from"@flopay/shared";import{FloPayError as p,SDK_VERSION as Q,FLO_SDK_VERSION_HEADER as be,IDEMPOTENCY_KEY_HEADER as Ee,IDEMPOTENCY_IN_PROGRESS_CODE as gt,buildProductPayload as ft,foldIntoProducts as ke,isUuidV4 as Me,randomUuidV4 as Ct,resolveIdempotencyKey as vt,resolveSessionCurrency as Re}from"@flopay/shared";function E(n){return typeof n=="string"&&n.trim()?n:void 0}function ve(n){if(typeof n=="string")return n.trim()?n:void 0;if(Array.isArray(n))return n.filter(t=>typeof t=="string"&&t.trim().length>0).join("; ")||void 0}var rt="flopay_session_display:";var Y=new Map;function W(n){return`${rt}${n}`}function oe(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function x(n,e,t){if(!n)return;let r=t?.ttlMs??36e5,s={data:e,expiresAt:Date.now()+r},o=oe();if(o)try{o.setItem(W(n),JSON.stringify(s));return}catch{}Y.set(n,s)}function se(n){if(!n)return null;let e=oe();if(e)try{let r=e.getItem(W(n));if(r){let s=JSON.parse(r);if(s&&typeof s.expiresAt=="number"&&s.expiresAt>Date.now())return s.data;e.removeItem(W(n))}}catch{}let t=Y.get(n);if(t){if(t.expiresAt>Date.now())return t.data;Y.delete(n)}return null}function ie(n){if(!n)return;Y.delete(n);let e=oe();if(e)try{e.removeItem(W(n))}catch{}}import{buildTelemetryErrorEvent as Te,buildTelemetryLogEvent as nt,buildTelemetryPerformanceEvent as ot,buildTelemetryTerminalEvent as st,serializeTelemetryBatch as it,TELEMETRY_MAX_BATCH_BYTES as at}from"@flopay/shared";var lt="/v1/sdk-telemetry/events",ae=16,ct=64,dt=1500,_e=1e3,ut=64,pt="00000000-0000-4000-8000-000000000000",mt={technical_error:8,lifecycle:32,expected_outcome:32,performance:24};function D(){try{return globalThis.crypto.randomUUID()}catch{let n=new Uint8Array(16);try{globalThis.crypto.getRandomValues(n)}catch{for(let t=0;t<n.length;t+=1)n[t]=Math.floor(Math.random()*256)}n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[...n].map(t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}function yt(n){try{return new TextEncoder().encode(n).byteLength}catch{return n.length}}function ht(n){return JSON.stringify([n.code,n.stage,n.provider,n.attempt,n.statusClass,n.requestCategory,n.paymentMethodCategory,n.checkoutMode,n.layout])}function C(){return globalThis.performance?.now()??0}var f=class{constructor(e){this.ingestionDisabled=!1;this.queue=[];this.sequence=0;this.flushTimer=null;this.flushInFlight=null;this.reportedFailures=new Map;this.checkoutContext={};this.checkoutStartedAt=null;this.destroyed=!1;this.pageExitHandler=()=>{this.drainQueue()};this.visibilityHandler=()=>{document.visibilityState==="hidden"&&this.flush()};this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0};this.endpoint=`${e.billingApiUrl.replace(/\/+$/,"")}${lt}`,this.sdkPackage=e.sdkPackage??"@flopay/js",this.sdkVersion=e.sdkVersion,this.correlationId=D(),this.merchantEnabled=e.enabled!==!1,this.clock=e.clock??C,this.browserTransportAvailable=typeof window<"u"&&typeof document<"u",this.browserTransportAvailable&&(window.addEventListener("pagehide",this.pageExitHandler),document.addEventListener("visibilitychange",this.visibilityHandler))}log(e){this.canCollect()&&this.enqueue(nt({...this.checkoutContext,...e,eventId:D(),sequence:this.sequence++}))}error(e){if(!this.canCollect())return;let t=Te({...this.checkoutContext,...e,eventId:pt,sequence:0}),r=ht(t),s=this.now();this.pruneReportedFailures(s);let o=this.reportedFailures.get(r);if(o!==void 0&&s>=o&&s-o<_e){this.log({name:"operation.deduplicated",stage:e.stage,provider:e.provider,paymentMethodCategory:e.paymentMethodCategory,attempt:e.attempt});return}this.rememberReportedFailure(r,s),this.enqueue(Te({...this.checkoutContext,...e,eventId:D(),sequence:this.sequence++}))}performance(e){this.canCollect()&&this.enqueue(ot({...this.checkoutContext,...e,eventId:D(),sequence:this.sequence++}))}terminal(e){if(this.canCollect()&&(this.enqueue(st({...this.checkoutContext,...e,eventId:D(),sequence:this.sequence++})),e.outcome!=="action_required"&&this.checkoutStartedAt!==null)){let t=this.checkoutStartedAt;this.checkoutStartedAt=null,this.performance({stage:"total_journey",durationMs:Math.max(0,this.now()-t),durationMode:"total",provider:e.provider,paymentMethodCategory:e.paymentMethodCategory})}}now(){try{return this.clock()}catch{return C()}}pruneReportedFailures(e){for(let[t,r]of this.reportedFailures)(e<r||e-r>=_e)&&this.reportedFailures.delete(t)}rememberReportedFailure(e,t){for(;this.reportedFailures.size>=ut;){let r=this.reportedFailures.keys().next();if(r.done)break;this.reportedFailures.delete(r.value)}this.reportedFailures.set(e,t)}setCheckoutContext(e){this.checkoutContext={checkoutMode:e.checkoutMode,layout:e.layout}}beginCheckout(e={}){return this.canCollect()?(this.drainQueue(),this.setCheckoutContext(e),this.sequence=0,this.reportedFailures.clear(),this.eventCounts={technical_error:0,lifecycle:0,expected_outcome:0,performance:0},this.checkoutStartedAt=this.now(),this.checkoutStartedAt):0}enqueue(e){if(this.canCollect()&&!(this.queue.length>=ct||this.eventCounts[e.class]>=mt[e.class])){if(this.eventCounts[e.class]+=1,this.queue.push(e),this.queue.length>=ae){this.flush();return}this.scheduleFlush()}}canCollect(){return this.browserTransportAvailable&&this.merchantEnabled&&!this.ingestionDisabled&&!this.destroyed}async flush(){if(this.flushInFlight)return this.flushInFlight;if(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0)return;this.clearFlushTimer();let e=this.queue.splice(0,ae);return this.flushInFlight=this.sendBatch(e).finally(()=>{this.flushInFlight=null,this.queue.length>0&&this.scheduleFlush()}),this.flushInFlight}destroy(){this.destroyed||(this.drainQueue(),this.destroyed=!0,this.clearFlushTimer(),this.browserTransportAvailable&&(window.removeEventListener("pagehide",this.pageExitHandler),document.removeEventListener("visibilitychange",this.visibilityHandler)),this.queue.splice(0),this.reportedFailures.clear())}disable(){this.merchantEnabled=!1,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}drainQueue(){if(!(!this.browserTransportAvailable||this.destroyed||this.ingestionDisabled||this.queue.length===0))for(this.clearFlushTimer();this.queue.length>0;){let e=this.queue.splice(0,ae);this.sendBatch(e)}}async sendBatch(e){if(!this.browserTransportAvailable||this.ingestionDisabled)return;let t=it(e,{correlationId:this.correlationId,sdkPackage:this.sdkPackage,sdkVersion:this.sdkVersion,batchId:D()});if(yt(t)>at)return;let r=typeof AbortController>"u"?null:new AbortController,s=null;try{let o=fetch(this.endpoint,{method:"POST",headers:{"content-type":"text/plain;charset=UTF-8"},body:t,credentials:"omit",keepalive:!0,referrerPolicy:"no-referrer",signal:r?.signal}).then(async l=>l.status!==202?null:(await l.json().catch(()=>null))?.status==="disabled"?"disabled":null).catch(()=>null),i=new Promise(l=>{s=setTimeout(()=>{r?.abort(),l(null)},dt)});await Promise.race([o,i])==="disabled"&&this.disableFromIngestion()}catch{}finally{s&&clearTimeout(s)}}disableFromIngestion(){this.ingestionDisabled=!0,this.queue.splice(0),this.reportedFailures.clear(),this.clearFlushTimer()}scheduleFlush(){this.flushTimer||this.destroyed||this.ingestionDisabled||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.flush()},0))}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}},we=Symbol.for("@flopay/js.telemetry.reporter-factory.v1"),Pe=globalThis;Pe[we]===void 0&&Object.defineProperty(Pe,we,{configurable:!0,enumerable:!1,writable:!1,value:n=>new f(n)});var Se=1e3,Tt=500,_t=15e3,wt=3e3,Pt=1e4;function bt(n){return typeof n=="object"&&n!==null}function k(n){if(n===void 0)return"network_error";let e=`${Math.floor(n/100)}xx`;return e==="2xx"||e==="3xx"||e==="4xx"||e==="5xx"?e:"unknown"}function Et(n,e){return n instanceof Error&&(n.name==="AbortError"||n instanceof p&&n.code==="checkout_processing_timeout")?{errorCode:"REQUEST_TIMEOUT",statusClass:"timeout"}:n instanceof TypeError?{errorCode:"NETWORK_REQUEST_FAILED",statusClass:"network_error"}:{errorCode:e,statusClass:k(n instanceof p?n.statusCode:void 0)}}function O(n,e){return E(n?.[e])}function Ae(n,e){return ve(n?.[e])}function kt(n,e){let t=n?.[e];return typeof t=="number"&&Number.isFinite(t)?t:void 0}function le(n){return new Promise(e=>setTimeout(e,n))}function J(){return new p("Checkout is still processing. Please try again shortly.","api_error",{code:"checkout_processing_timeout"})}async function F(n,e){let t=await n.json().catch(()=>null),r=bt(t?.error)?t.error:null,s=Ae(t,"message")??Ae(r,"message")??e,o=O(t,"code")??O(t,"gatewayErrorCode")??O(r,"code")??`http_${n.status}`;return new p(s,"api_error",{code:o,statusCode:n.status})}var V=2,Mt=2;async function X(n,e,t=V,r){let s;for(let o=0;;o++)try{return await fetch(n,e)}catch(i){if(i instanceof Error&&i.name==="AbortError")throw i;if(s=i,o>=t)throw s;try{r?.(o+1)}catch{}await le(150*2**o)}}function Rt(n){return"now"in n||"onFirstByte"in n||"onSessionCreateFailure"in n||"onRetry"in n}var M=class{constructor(e,t={}){this.baseUrl=e.replace(/\/+$/,"");let r=Rt(t);this.telemetryHooks=r?t:void 0,this.directTelemetry=r||t.telemetry===!1?void 0:new f({billingApiUrl:this.baseUrl,sdkVersion:Q})}destroy(){this.directTelemetry?.destroy()}reportDirectFailure(e,t,r,s,o="unknown"){let i=Et(e,t);this.directTelemetry?.error({...i,stage:r,requestCategory:s,paymentMethodCategory:o})}telemetryTimestamp(){try{return this.telemetryHooks?.now?.()??this.directTelemetry?.now()??C()}catch{return C()}}beginDirectTelemetryCheckout(e){!this.directTelemetry||this.directTelemetryCheckoutId===e||(this.directTelemetryCheckoutId=e,this.directTelemetry.beginCheckout())}beginDirectTelemetryOperation(){this.directTelemetry&&(this.directTelemetryCheckoutId=void 0,this.directTelemetry.beginCheckout())}adoptDirectTelemetryCheckout(e){e&&(this.directTelemetryCheckoutId=e)}async getCheckoutSession(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let s={[be]:Q};t&&(s["x-checkout-session-token"]=t);try{let o=await X(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}`,{headers:s},V,c=>{this.telemetryHooks?.onRetry?.("session_read",c),this.directTelemetry?.log({name:"operation.retry",stage:"session_read",requestCategory:"session_read",attempt:c})}),i=Math.max(0,this.telemetryTimestamp()-r);try{this.telemetryHooks?.onFirstByte?.(i)}catch{}let a=`${Math.floor(o.status/100)}xx`;if(this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:i,durationMode:"machine",requestCategory:"session_read",statusClass:a}),!o.ok)throw await F(o,"Failed to get checkout session");let l=await o.json();return this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:a}),this.directTelemetry?.performance({stage:"session_complete",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",statusClass:a}),{...l,data:this.mergeCachedDisplayData(l.data)}}catch(o){let i=o instanceof p?o.statusCode:void 0;throw this.directTelemetry?.error({errorCode:o instanceof p&&o.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED",stage:"session_read",requestCategory:"session_read",statusClass:i?`${Math.floor(i/100)}xx`:"network_error"}),o}}cacheSessionDisplayData(e,t,r){x(e,t,r)}clearSessionDisplayData(e){ie(e)}async getVaultCapture(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"vault.capture.requested",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card"});let s={"Content-Type":"application/json"};t&&(s["x-checkout-session-token"]=t);try{let o=await X(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/vault/capture`,{method:"POST",headers:s},V,a=>{this.telemetryHooks?.onRetry?.("vault_capture",a),this.directTelemetry?.log({name:"operation.retry",stage:"vault_request",requestCategory:"vault_capture",paymentMethodCategory:"card",attempt:a})});if(!o.ok)throw await F(o,"Failed to load the secure card form");let i=await o.json();return this.directTelemetry?.performance({stage:"vault_request",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"vault_capture",paymentMethodCategory:"card",statusClass:"2xx"}),this.toVaultBlock(i)}catch(o){throw this.reportDirectFailure(o,"VAULT_LOAD_FAILED","vault_request","vault_capture","card"),o}}async getUnifiedCheckoutSession(e,t){let r=await this.getCheckoutSession(e,t),s=this.normalizeRawSession(r.data),o=r.vault;return o&&s.data.session&&(s.data.session.vault=this.toVaultBlock(o)),s}async processPayment(e,t,r){if(this.beginDirectTelemetryCheckout(t.sessionId),!t.nonce)throw this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"processing",requestCategory:"process_payment"}),new p("processPayment requires `nonce` \u2014 pass the value returned from session creation.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let s=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.processing.started",stage:"processing",requestCategory:"process_payment"});let{nonce:o,...i}=t,a;try{a=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(t.sessionId)}/process`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":o},body:JSON.stringify(i)})}catch(l){throw this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}if(!a.ok&&a.status!==202)return this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"process_payment",statusClass:k(a.status)}),a;try{let l=await this.resolveProcessResponse(a,t.sessionId,{...r,nonce:o});return this.directTelemetry?.log({name:"payment.processing.completed",stage:"processing",requestCategory:"process_payment",statusClass:k(l.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-s),durationMode:"machine",requestCategory:"process_payment",statusClass:k(l.status)}),l}catch(l){throw l instanceof p&&l.code==="checkout_processing_timeout"||this.reportDirectFailure(l,"PAYMENT_PROCESSING_FAILED","processing","process_payment"),l}}async patchAccountSnapshot(e,t,r,s){this.beginDirectTelemetryCheckout(e);let o=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.state_transition",stage:"processing",requestCategory:"account_snapshot"});let i=s?.timeoutMs??Pt,a=new AbortController,l=()=>a.abort();s?.signal&&(s.signal.aborted?a.abort():s.signal.addEventListener("abort",l,{once:!0}));let c=setTimeout(()=>a.abort(),i);try{let d;try{d=await X(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/account`,{method:"PATCH",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(r),signal:a.signal},V,m=>{this.telemetryHooks?.onRetry?.("account_snapshot",m),this.directTelemetry?.log({name:"operation.retry",stage:"processing",requestCategory:"account_snapshot",attempt:m})})}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",l)}if(!d.ok)throw await F(d,"Failed to persist account snapshot");this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-o),durationMode:"machine",requestCategory:"account_snapshot",statusClass:"2xx"})}catch(d){throw this.reportDirectFailure(d,"NETWORK_REQUEST_FAILED","processing","account_snapshot"),d}}async createSessionIntent(e,t,r,s){if(!t)throw new p("createSessionIntent requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.paymentMethodType,a=typeof i=="string"&&i.trim().toLowerCase()==="card",l=typeof i=="string"&&i.length>0&&!a&&(typeof o.paymentMethodId=="string"||o.paymentMethodId===null),c=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm")&&(o.intentKind==="payment"||o.intentKind==="setup"),d=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal"&&o.paymentMethodId===null&&o.intentKind==="payment";if(!l||!c&&!d)throw new p("Only wallet, APM, and PayPal session intents are supported.","validation_error",{code:"InvalidSessionIntentRequest"});let m=o.authorizationAttemptId;if(m!==void 0&&!Me(m))throw new p("authorizationAttemptId must be a v4 UUID identifying one buyer authorization attempt.","validation_error",{code:"InvalidAuthorizationAttemptId",param:"authorizationAttemptId"});let T=Me(m)?m:Ct();this.beginDirectTelemetryCheckout(e);let h=this.telemetryTimestamp();this.directTelemetry?.log({name:"payment.intent.started",stage:"processing",requestCategory:"intent_create"});let _={"Content-Type":"application/json","x-checkout-session-token":t,[Ee]:s?.idempotencyKey||T},w=!1;try{let v=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents`,{method:"POST",headers:_,body:JSON.stringify({...r,authorizationAttemptId:T}),signal:s?.signal});if(!v.ok)throw w=!0,this.directTelemetry?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",requestCategory:"intent_create",statusClass:k(v.status)}),await F(v,"Failed to create checkout intent");let S=(await v.json()).data;if(!S||typeof S!="object")throw new p("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});let u=S,L=u.paymentMethodType,A=(u.paymentMethodCategory==="wallet"||u.paymentMethodCategory==="apm")&&typeof L=="string"&&L.trim().toLowerCase()!=="card"&&(typeof u.paymentMethodId=="string"||u.paymentMethodId===null)&&typeof u.providerObjectId=="string",b=u.provider==="stripe"&&(u.intentKind==="payment"||u.intentKind==="setup")&&typeof u.clientSecret=="string",N=u.provider==="paypal"&&u.paymentMethodCategory==="wallet"&&u.paymentMethodType==="paypal"&&u.paymentMethodId===null&&u.intentKind==="payment"&&(u.providerObjectType==="order"||u.providerObjectType==="subscription")&&u.clientSecret===null,re=u.provider===r.provider&&u.paymentMethodCategory===r.paymentMethodCategory&&u.paymentMethodType===r.paymentMethodType&&u.paymentMethodId===r.paymentMethodId&&u.intentKind===r.intentKind;if(!A||!b&&!N||!re)throw new p("Invalid checkout intent response.","api_error",{code:"InvalidSessionIntentResponse"});return this.directTelemetry?.log({name:"payment.intent.completed",stage:"processing",requestCategory:"intent_create",statusClass:k(v.status)}),this.directTelemetry?.performance({stage:"processing",durationMs:Math.max(0,this.telemetryTimestamp()-h),durationMode:"machine",requestCategory:"intent_create",statusClass:k(v.status)}),u}catch(v){throw w||this.reportDirectFailure(v,"PAYMENT_PROCESSING_FAILED","processing","intent_create"),v}}async reportSessionIntentDecline(e,t,r,s){if(!t)throw new p("reportSessionIntentDecline requires the checkout session nonce.","validation_error",{code:"MissingCheckoutSessionToken",param:"nonce"});let o=r,i=o.providerDeclineReason,a=o.paymentMethodType,l=typeof i=="string"&&/^[a-z0-9][a-z0-9_.:-]{0,63}$/i.test(i)&&!/^(?:pm|pi|seti|tok|src|cus|sess|sk|pk)_/i.test(i),c=typeof a=="string"&&a.length>0&&a.trim().toLowerCase()!=="card"&&l,d=o.provider==="stripe"&&(o.paymentMethodCategory==="wallet"||o.paymentMethodCategory==="apm"),m=o.provider==="paypal"&&o.paymentMethodCategory==="wallet"&&o.paymentMethodType==="paypal";if(!c||!d&&!m)throw new p("Invalid non-card decline classification.","validation_error",{code:"InvalidSessionIntentDeclineRequest"});let T=m?{provider:"paypal",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:i}:{provider:"stripe",paymentMethodCategory:o.paymentMethodCategory,paymentMethodType:o.paymentMethodType,providerDeclineReason:i},h=await fetch(`${this.baseUrl}/v1/checkouts/sessions/${encodeURIComponent(e)}/intents/decline`,{method:"POST",headers:{"Content-Type":"application/json","x-checkout-session-token":t},body:JSON.stringify(T),signal:s?.signal});if(!h.ok)throw await F(h,"Failed to report checkout decline")}async getPaymentsByEmail(e,t){this.beginDirectTelemetryOperation();let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved"});let s=t?.page??1,o=t?.limit??1,i=new URLSearchParams({email:e,page:String(s),limit:String(o),sortField:"createdAt",sortDirection:"DESC"});try{let a=await fetch(`${this.baseUrl}/v1/payments?${i.toString()}`,{method:"GET",signal:t?.signal,keepalive:!0});if(!a.ok)throw new p("Failed to fetch payments","api_error",{statusCode:a.status});let l=await a.json();return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"other",paymentMethodCategory:"saved",statusClass:"2xx"}),l}catch(a){throw this.reportDirectFailure(a,"RECOVERY_FAILED","recovery","other","saved"),a}}async createAndFetchSession(e){this.beginDirectTelemetryOperation();let t=this.telemetryTimestamp();this.directTelemetry?.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"});try{let r=await this.createAndFetchSessionRequest(e,t);return this.adoptDirectTelemetryCheckout(r.data.session?.id),this.directTelemetry?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:"2xx"}),this.directTelemetry?.performance({stage:"session_create",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:"2xx"}),r}catch(r){if(!(r instanceof p&&r.code==="session_auto_completed"))try{this.telemetryHooks?.onSessionCreateFailure?.(r)}catch{}if(r instanceof p&&r.type==="validation_error")this.directTelemetry?.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});else if(!(r instanceof p&&r.code==="session_auto_completed")){let s=r instanceof p?r.statusCode:void 0;this.directTelemetry?.error({errorCode:r instanceof Error&&r.name==="AbortError"?"REQUEST_TIMEOUT":r instanceof TypeError?"NETWORK_REQUEST_FAILED":"CHECKOUT_SESSION_CREATE_FAILED",stage:"session_create",requestCategory:"session_create",statusClass:r instanceof Error&&r.name==="AbortError"?"timeout":s?`${Math.floor(s/100)}xx`:"network_error"})}throw r}}async createAndFetchSessionRequest(e,t){let r=e.products??ke(e.items,e.subscriptions),s=Re(e.currency,e.items,e.subscriptions,r);if(!s)throw new p("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let o={clientId:e.clientId,checkoutVersion:Q,successUrl:e.successUrl,cancelUrl:e.cancelUrl,currency:s,checkoutMode:e.checkoutMode??"full",products:r.map(h=>ft(h,s)),accountData:{userId:e.account.userId,firstName:e.account.firstName??null,lastName:e.account.lastName??null,email:e.account.email,country:e.account.country??null,gender:e.account.gender??null,city:e.account.city??null,state:e.account.state??null,zip:e.account.zip??null,addressLine1:e.account.addressLine1??null,addressLine2:e.account.addressLine2??null},couponCodes:e.couponCodes??[]};e.tokenizedData&&(o.tokenizedData=e.tokenizedData),e.tagsData&&(o.tagsData=e.tagsData),e.utmMetadata?.length&&(o.utmMetadata=e.utmMetadata),e.avsCheck!==void 0&&(o.avsCheck=e.avsCheck),e.checkoutType&&(o.checkoutType=e.checkoutType),e.checkoutLayout&&(o.checkoutLayout=e.checkoutLayout),e.avsConfig&&(o.avsConfig=e.avsConfig);let i={"Content-Type":"application/json",[be]:Q},a=vt(e.idempotencyKey);a&&(i[Ee]=a);let l,c=!1;for(let h=0;;h++){if(l=await X(`${this.baseUrl}/v1/checkouts/sessions?expand=true`,{method:"POST",headers:i,body:JSON.stringify(o)},V,w=>{this.telemetryHooks?.onRetry?.("session_create",w),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:w})}),!c){c=!0;let w=`${Math.floor(l.status/100)}xx`;this.directTelemetry?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:w}),this.directTelemetry?.performance({stage:"session_first_byte",durationMs:this.telemetryTimestamp()-t,durationMode:"machine",requestCategory:"session_create",statusClass:w})}if(l.status===204)throw new p("Session auto-completed \u2014 payment method already on file","api_error",{code:"session_auto_completed"});if(l.ok)break;let _=await F(l,"Failed to create checkout session");if(_.code===gt&&h<Mt){try{this.telemetryHooks?.onRetry?.("session_create",h+1),this.directTelemetry?.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:h+1})}catch{}await le(150*2**h);continue}throw _}let d=await l.json();if(d.data&&"gateways"in d.data){this.autoCacheDisplayData(d.data.uuid,e);let h=this.mergeCachedDisplayData(d.data),_=this.normalizeRawSession(h);return d.vault&&_.data.session&&(_.data.session.vault=this.toVaultBlock(d.vault)),{..._,autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}let m=d.data?.uuid;if(!m)throw new p("No session ID returned","api_error");return this.autoCacheDisplayData(m,e),this.adoptDirectTelemetryCheckout(m),{...await this.getUnifiedCheckoutSession(m),autoProcessingError:d.autoProcessingError,autoProcessingAttempted:d.autoProcessingAttempted,autoProcessingPending:d.autoProcessingPending}}async waitForCheckoutSessionCompletion(e,t){this.beginDirectTelemetryCheckout(e);let r=this.telemetryTimestamp();this.directTelemetry?.log({name:"operation.recovery.started",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"});let s=t?.timeoutMs??_t,o=Date.now()+s,i=this.clampRetryAfterMs(t?.initialDelayMs??Se),a=0;try{for(;;){let l=o-Date.now();if(l<=0)throw J();if(i>0){try{a+=1,this.telemetryHooks?.onRetry?.("session_read",a),this.directTelemetry?.log({name:"operation.retry",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved",attempt:a})}catch{}if(await le(Math.min(i,l)),Date.now()>=o)throw J()}let c=await this.getUnifiedCheckoutSession(e,t?.nonce),d=c.data.session?.status;if(d==="complete"||d==="expired")return this.directTelemetry?.log({name:"operation.recovery.completed",stage:"recovery",requestCategory:"session_read",paymentMethodCategory:"saved"}),this.directTelemetry?.performance({stage:"recovery",durationMs:Math.max(0,this.telemetryTimestamp()-r),durationMode:"machine",requestCategory:"session_read",paymentMethodCategory:"saved"}),c;if(Date.now()>=o)throw J();i=this.clampRetryAfterMs(Math.max(i*2,Tt))}}catch(l){throw l instanceof p&&l.code==="checkout_processing_timeout"&&this.reportDirectFailure(l,"RECOVERY_FAILED","recovery","session_read","saved"),l}}normalizeRawSession(e){let t=e.gateways??{},r=[],s={session:this.toCheckoutSession(e)},o=t.stripe;if(o?.publishableKey){r.push("stripe");let l=[e.stripeClientSecret,o.stripeClientSecret].find(c=>typeof c=="string"&&c.length>0);s.stripe={clientSecret:l??"",publishableKey:o.publishableKey??void 0,paypalPublishableKey:o.paypalPublishableKey??void 0,environment:o.environment,enabledPaymentMethods:Array.isArray(o.enabledPaymentMethods)?o.enabledPaymentMethods.filter(c=>typeof c=="string"):void 0}}let i=t.paypal;return i?.publishableKey&&(r.push("paypal"),s.paypal={publishableKey:i.publishableKey,environment:i.environment}),{providers:r,mode:"tokenize",data:s,raw:{data:e}}}toCheckoutSession(e){let t=e.products??[],r=typeof e.totalAmount=="number"&&Number.isFinite(e.totalAmount),s=t.reduce((c,d)=>c+(d.overrideAmount??d.totalAmount??0),0),o=r?e.totalAmount:s,i=Math.round(o*100),a=e.currency??t[0]?.currency??"USD",l=t.some(c=>c.type==="subscription")?"subscription":"payment";return{id:e.uuid,clientSecret:e.nonce,mode:l,status:this.toCheckoutSessionStatus(e.status),amount:i,currency:a,customer:{id:e.accountData.userId,email:e.accountData.email,firstName:e.accountData.firstName,lastName:e.accountData.lastName,country:e.accountData.country??void 0,city:e.accountData.city??void 0,state:e.accountData.state??void 0,zip:e.accountData.zip??void 0,gender:e.accountData.gender??void 0,line1:e.accountData.addressLine1??void 0,line2:e.accountData.addressLine2??void 0},metadata:{},checkoutMode:e.checkoutMode,providerPaymentMethodId:typeof e.providerPaymentMethodId=="string"?e.providerPaymentMethodId:null,products:t.map(c=>({...c,totalAmount:typeof c.totalAmount=="number"?c.totalAmount:void 0,overrideAmount:typeof c.overrideAmount=="number"?c.overrideAmount:null,currency:typeof c.currency=="string"?c.currency:void 0,metadata:c.metadata??null})),successUrl:e.successUrl,cancelUrl:e.cancelUrl,coupons:e.coupons,subtotalAmount:e.subtotalAmount,discountAmount:e.discountAmount,totalAmount:e.totalAmount,createdAt:e.createdAt,gateways:e.gateways,accountData:e.accountData,tagsData:e.tagsData}}toVaultBlock(e){return{html:typeof e.html=="string"?e.html:void 0,url:typeof e.url=="string"?e.url:void 0,messageToken:typeof e.messageToken=="string"?e.messageToken:void 0,expectedOrigin:typeof e.expectedOrigin=="string"?e.expectedOrigin:void 0}}toCheckoutSessionStatus(e){return e==="completed"?"complete":e==="expired"?"expired":"open"}async resolveProcessResponse(e,t,r){if(e.status!==202)return e;let s=await e.json().catch(()=>null),o=this.toCheckoutProcessingPending(s,e,t),i=await this.waitForCheckoutSessionCompletion(o.sessionId,{initialDelayMs:o.retryAfterMs,timeoutMs:r?.pollTimeoutMs,nonce:r?.nonce});if(i.data.session?.status==="complete")return new Response(null,{status:204,statusText:"No Content"});throw i.data.session?.status==="expired"?new p("Checkout session has expired.","api_error",{code:"checkout_session_expired"}):J()}toCheckoutProcessingPending(e,t,r){let s=t.headers.get("Retry-After"),o=s===null||s.trim()===""?void 0:Number(s),i=o!==void 0&&Number.isFinite(o)?o*1e3:void 0;return{type:"checkout_processing",sessionId:O(e,"sessionId")??r,retryAfterMs:this.clampRetryAfterMs(kt(e,"retryAfterMs")??i??Se),statusUrl:O(e,"statusUrl"),sessionUrl:O(e,"sessionUrl")}}clampRetryAfterMs(e){return Math.max(0,Math.min(e,wt))}autoCacheDisplayData(e,t){if(!e)return;let r=t.products??ke(t.items,t.subscriptions);if(r.length===0&&!t.currency)return;let s=t.products!==void 0,o=Re(t.currency,s?void 0:t.items,s?void 0:t.subscriptions,r);x(e,{currency:o??void 0,products:r.map(i=>({code:i.code??i.providerItemId??i.providerPlanId,type:i.type,name:i.name??i.itemName??i.providerItemName??i.subscriptionName??i.providerPlanName??null,totalAmount:i.totalAmount,overrideAmount:i.overrideAmount,currency:i.currency??o??void 0}))})}mergeCachedDisplayData(e){let t=se(e.uuid),r=new Map,s=i=>i?`code:${i}`:void 0;for(let i of t?.products??[]){let a=s(i.code);a&&r.set(a,i)}let o=(e.products??[]).map(i=>{let a=s(i.code),l=a?r.get(a):void 0;return{...i,name:i.name??l?.name??null,totalAmount:i.totalAmount??l?.totalAmount,overrideAmount:i.overrideAmount??l?.overrideAmount,currency:i.currency??l?.currency}});return{...e,currency:e.currency??t?.currency,products:o}}};function Ie(n,e){let t=M;return new t(n,e)}function xe(n){return{payment:"payment",address:"address"}[n]}function De(n){switch(n){case"night":return"night";case"flat":return"flat";default:return"stripe"}}function ce(n){return n?JSON.stringify(n.map(e=>e.trim().toLowerCase())):null}function Fe(n){let e=n;return{mount(t){e.mount(t)},unmount(){e.unmount()},update(t){e.update(t)},on(t,r){e.on?.(t,r)},off(t,r){e.off?.(t,r)},destroy(){e.destroy()}}}function It(n){return{billing_details:{...n.email?{email:n.email}:{},...n.name?{name:n.name}:{},...n.address?{address:{...n.address.country?{country:n.address.country}:{},...n.address.postal_code?{postal_code:n.address.postal_code}:{},...n.address.city?{city:n.address.city}:{},...n.address.line1?{line1:n.address.line1}:{},...n.address.line2?{line2:n.address.line2}:{},...n.address.state?{state:n.address.state}:{}}}:{}}}}var K=class{constructor(){this.name="stripe";this.stripe=null;this.elements=null;this.appliedAppearanceKey=null;this.appliedPaymentMethodTypesKey=null;this.appliedClientSecret=null;this.verifiedClientSecret=null;this.verifiedPaymentMethodTypesKey=null}async initialize(e){if(typeof window>"u")return;let t=await St(e.publishableKey,{locale:e.locale??"auto"});if(!t)throw new y("Failed to initialize Stripe. Check your publishable key.","authentication_error");this.stripe=t}getElements(e){if(!this.stripe)throw new y("StripeAdapter not initialized. Call initialize() first.","api_error");let t=e?.appearance?{theme:De(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}:void 0,r=t?JSON.stringify(t):null,s=ce(e?.paymentMethodTypes),o=e?.clientSecret??null;if(this.elements&&s&&(s!==this.appliedPaymentMethodTypesKey||o!==this.appliedClientSecret)&&(this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null),this.elements)r!==this.appliedAppearanceKey&&(this.elements.update({appearance:t??{}}),this.appliedAppearanceKey=r);else{let i,a=e?.amount??0,l=(e?.currency??"usd").toLowerCase(),c=e?.paymentMethodCreation??"manual";e?.clientSecret?i={clientSecret:e.clientSecret}:a>0?(i={mode:"payment",amount:a,currency:l,paymentMethodCreation:c},e?.setupFutureUsage&&(i.setupFutureUsage=e.setupFutureUsage)):i={mode:"setup",currency:l,paymentMethodCreation:c},!e?.clientSecret&&e?.paymentMethodTypes&&(i.paymentMethodTypes=e.paymentMethodTypes),t&&(i.appearance=t),this.elements=this.stripe.elements(i),this.appliedAppearanceKey=r,this.appliedPaymentMethodTypesKey=s,this.appliedClientSecret=o,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null}return this.elements}async assertClientSecretPaymentMethods(e,t){if(!this.stripe)throw new y("StripeAdapter not initialized. Call initialize() first.","api_error");let r,s=!1;if(At(e)){let{setupIntent:l,error:c}=await this.stripe.retrieveSetupIntent(e);r=l,s=!!c}else{let{paymentIntent:l,error:c}=await this.stripe.retrievePaymentIntent(e);r=l,s=!!c}let o=r?.payment_method_types;if(s||!Array.isArray(o))throw new y("Unable to verify the payment methods configured for this client secret.","api_error",{param:"clientSecret"});let i=new Set(t.map(l=>l.toLowerCase()));if(o.some(l=>typeof l!="string"||!i.has(l.trim().toLowerCase()))||o.length===0)throw new y("The client-secret intent must enable only declared non-card payment methods.","validation_error",{param:"clientSecret"})}async createElement(e,t){let r=t;if(e==="payment"){let l=t.paymentMethodTypes?.map(c=>c.trim()).filter(c=>c&&c.toLowerCase()!=="card");if(!l?.length)throw new y("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});if(r={...t,paymentMethodTypes:l},r.clientSecret){let c=ce(l);this.elements&&this.appliedClientSecret===r.clientSecret&&this.appliedPaymentMethodTypesKey===c&&this.verifiedClientSecret===r.clientSecret&&this.verifiedPaymentMethodTypesKey===c||await this.assertClientSecretPaymentMethods(r.clientSecret,l)}}let s=this.getElements(r);e==="payment"&&r.clientSecret&&(this.verifiedClientSecret=r.clientSecret,this.verifiedPaymentMethodTypesKey=ce(r.paymentMethodTypes));let o=xe(e),i={};r.layout&&(i.layout=r.layout),r.defaultValues&&(i.defaultValues=r.defaultValues),r.readOnly&&(i.readOnly=r.readOnly),r.mode&&(i.mode=r.mode);let a=s.create(o,i);return Fe(a)}getElement(e){if(!this.elements)return null;let t=xe(e),r=this.elements.getElement(t);return r?Fe(r):null}async submitElements(){if(!this.stripe||!this.elements)return{error:new y("Stripe not initialized","api_error")};let{error:e}=await this.elements.submit();return e?{error:new y(e.message??"Validation failed","validation_error")}:{}}async confirmPayment(e){if(!this.stripe||!this.elements)throw new y("StripeAdapter not initialized or no elements created.","api_error");let t=e.billingDetails,r=t?It(t):void 0,{error:s,paymentIntent:o}=await this.stripe.confirmPayment({elements:this.elements,clientSecret:e.clientSecret,confirmParams:{return_url:e.returnUrl??window.location.href,...r?{payment_method_data:r}:{}},redirect:"if_required"});return s?{status:"failed",error:new y(s.message??"Payment failed","api_error",{code:s.code,declineCode:s.decline_code})}:o?{status:{succeeded:"succeeded",processing:"processing",requires_action:"requires_action",requires_payment_method:"failed",canceled:"failed"}[o.status]??"failed",paymentIntentId:o.id,paymentMethodId:this.extractPaymentMethodId(o.payment_method)}:{status:"failed",error:new y("No payment intent returned","api_error")}}extractPaymentMethodId(e){if(typeof e=="string"&&e.startsWith("pm_"))return e;if(e&&typeof e=="object"&&typeof e.id=="string")return e.id}async confirmPayPalPayment(e){if(!this.stripe)return{status:"failed",error:new y("Stripe not initialized","api_error")};let t=e.billingApiUrl.replace(/\/+$/,"");if(this.elements){let{error:o}=await this.elements.submit();if(o)return{status:"failed",error:new y(o.message??"PayPal payment failed","validation_error",{code:o.code})}}let r;try{let o=await new M(t).createSessionIntent(e.sessionId,e.nonce??"",{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",paymentMethodId:null,intentKind:"payment"});if(o.provider!=="stripe")throw new y("Invalid provider returned for PayPal intent","api_error");r=o.clientSecret}catch(o){return{status:"failed",error:o instanceof y?o:new y("Failed to create PayPal payment intent","api_error")}}let{error:s}=await this.stripe.confirmPayment({clientSecret:r,elements:this.elements??void 0,confirmParams:{return_url:e.returnUrl}});if(s){if(e.nonce)try{await new M(t).reportSessionIntentDecline(e.sessionId,e.nonce,{provider:"stripe",paymentMethodCategory:"wallet",paymentMethodType:"paypal",providerDeclineReason:s.code??"provider_declined"})}catch{}return{status:"failed",error:new y(s.message??"PayPal payment failed","api_error",{code:s.code})}}return{status:"processing"}}async resumePayPalPayment(){if(!this.stripe||typeof window>"u")return null;let e=new URLSearchParams(window.location.search),t=e.get("payment_intent"),r=e.get("payment_intent_client_secret"),s=e.get("redirect_status");if(!t||!r)return null;if(s==="failed")return{status:"failed",error:new y("PayPal payment was declined. Please try again.","api_error")};let{paymentIntent:o,error:i}=await this.stripe.retrievePaymentIntent(r);if(i)return{status:"failed",error:new y(i.message??"Failed to retrieve PayPal payment","api_error")};if(o&&(o.status==="requires_capture"||o.status==="succeeded")){let a=typeof o.payment_method=="string"?o.payment_method:o.payment_method?.id,l=new URL(window.location.href);return l.searchParams.delete("payment_intent"),l.searchParams.delete("payment_intent_client_secret"),l.searchParams.delete("redirect_status"),window.history.replaceState({},"",l.toString()),{status:o.status,paymentIntentId:o.id,paymentMethodId:a}}return{status:"failed",error:new y("PayPal payment was not completed. Please try again.","api_error")}}getRawProvider(){return this.stripe}createPayPalElements(e){if(!this.stripe)return null;let t={mode:"payment",amount:e.amount??0,currency:(e.currency??"usd").toLowerCase(),captureMethod:"manual"};return e.setupFutureUsage&&(t.setupFutureUsage=e.setupFutureUsage),e.appearance&&(t.appearance={theme:De(e.appearance.theme),variables:e.appearance.variables,rules:e.appearance.rules}),this.stripe.elements(t)}destroy(){this.elements=null,this.appliedAppearanceKey=null,this.appliedPaymentMethodTypesKey=null,this.appliedClientSecret=null,this.verifiedClientSecret=null,this.verifiedPaymentMethodTypesKey=null,this.stripe=null}};import{FloPayError as U,resolveBillingApiUrl as He,SDK_VERSION as Nt}from"@flopay/shared";import{FloPayError as xt}from"@flopay/shared";var B=class{constructor(e,t){this.elementMap=new Map;this.provider=e,this.baseOptions=t??{}}async create(e,t){let r={...this.baseOptions,...t};if(e==="payment"){let a=r.paymentMethodTypes?.map(l=>l.trim()).filter(l=>l&&l.toLowerCase()!=="card");if(!a?.length)throw new xt("At least one supported non-card payment method is required.","validation_error",{param:"paymentMethodTypes"});r.paymentMethodTypes=a}let s=this.provider.getElement(e);if(s)return this.elementMap.set(e,s),s;let o=this.elementMap.get(e);o&&o.destroy();let i=await this.provider.createElement(e,r);return this.elementMap.set(e,i),i}getElement(e){return this.elementMap.get(e)??null}async submit(){return{}}destroy(){for(let e of this.elementMap.values())e.destroy();this.elementMap.clear()}};import{buildTelemetryErrorEvent as Dt,buildTelemetryLogEvent as Ft,buildTelemetryTerminalEvent as Le,FloPayError as Oe,resolveBillingApiUrl as qe,SDK_VERSION as Ue}from"@flopay/shared";var de="flopay-vault",Ne={ready:["vault.widget.ready","vault_ready"],submitting:["vault.submission.started","vault_submit"],blocked:["operation.state_transition","vault_submit"],action_required:["vault.action.required","three_ds_handoff"]};function z(n){let e={class:n.class,stage:n.stage};"code"in n&&(e.code=n.code),"provider"in n&&n.provider&&(e.provider=n.provider),"paymentMethodCategory"in n&&n.paymentMethodCategory&&(e.paymentMethodCategory=n.paymentMethodCategory),"outcome"in n&&(e.outcome=n.outcome),"durationMs"in n&&n.durationMs!==void 0&&(e.durationMs=n.durationMs),"durationMode"in n&&n.durationMode&&(e.durationMode=n.durationMode);try{globalThis.Sentry?.addBreadcrumb?.({category:"flopay.telemetry",level:n.class==="technical_error"?"error":"info",message:n.class==="lifecycle"?n.name:n.class==="technical_error"?n.code:n.class==="expected_outcome"?n.outcome:"sdk.performance",data:e})}catch{}}function Z(n,e){return Ft({eventId:"11111111-1111-4111-8111-111111111111",name:n,stage:e,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}function Ve(n){return n?{errorCode:"VAULT_SUBMIT_FAILED",stage:"vault_submit"}:{errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount"}}function Ot(n,e){if(n==="complete"||n==="decline")return Le({eventId:"22222222-2222-4222-8222-222222222222",outcome:n==="complete"?"payment_succeeded":"payment_declined",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});if(n==="error"){let s=Ve(e);return Dt({eventId:"33333333-3333-4333-8333-333333333333",...s,sequence:0,provider:"pcivault",paymentMethodCategory:"card"})}let[t,r]=Ne[n];return Z(t,r)}function qt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===de&&(e.type==="ready"||e.type==="submitting"||e.type==="blocked"||e.type==="complete"||e.type==="decline"||e.type==="error"||e.type==="action_required")}function Ut(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===de&&e.type==="validation"&&Array.isArray(e.messages)}function Lt(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.source===de&&e.type==="resize"&&typeof e.height=="number"&&Number.isFinite(e.height)}var q=class{constructor(e={},t){this.provider="pcivault";this.container=null;this.messageHandler=null;this.actionOverlay=null;this.threeDsReturnHandler=null;this.messageToken=null;this.expectedOrigin=null;this.theme=null;this.submitGateBlocked=!1;this.cardFieldOrder=null;this.cardAutoFocus=!0;this.captureRequestedAt=0;this.vaultReadyReported=!1;this.submissionStarted=!1;this.submissionStartedAt=null;this.listeners=new Map;this.config=e,this.ownsTelemetryReporter=!t&&e.telemetry!==!1,this.telemetryReporter=t?.reporter??(this.ownsTelemetryReporter?new f({billingApiUrl:qe(),sdkVersion:Ue}):void 0),this.requestedAt=t?.requestedAt}async mount(e,t){this.ownsTelemetryReporter&&!this.telemetryReporter&&(this.telemetryReporter=new f({billingApiUrl:qe(),sdkVersion:Ue}));let r=this.telemetryReporter?.now?.()??C();if(this.captureRequestedAt=this.requestedAt??r,this.vaultReadyReported=!1,this.submissionStarted=!1,this.submissionStartedAt=null,typeof window>"u"||typeof document>"u")throw this.reportVaultLoadFailure(),new Oe("The vault card form is only available in the browser.","api_error",{code:"card_capture_no_window"});if(!t?.html||!t.html.trim())throw this.reportVaultLoadFailure(),new Oe("No vault capture widget HTML was provided to mount the secure card form.","api_error",{code:"card_capture_no_widget_html"});this.container=e,this.messageToken=t.messageToken??null,this.expectedOrigin=t.expectedOrigin??this.config.expectedOrigin??null,this.theme=t.theme??null;try{this.attachMessageListener(),this.injectWidget(e,t.html)}catch(s){throw this.reportVaultLoadFailure(),s}this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder(),z(Z("vault.widget.mounted","vault_mount")),this.telemetryReporter?.log({name:"vault.widget.mounted",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"}),this.emit("ready",{sessionId:this.config.sessionId})}reportVaultLoadFailure(){this.telemetryReporter?.error({errorCode:"VAULT_LOAD_FAILED",stage:"vault_mount",provider:"pcivault",paymentMethodCategory:"card"})}on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>{this.listeners.get(e)?.delete(t)}}unmount(){this.hideActionRequiredOverlay(),this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.container&&(this.container.replaceChildren(),this.container=null),this.messageToken=null,this.expectedOrigin=null,this.ownsTelemetryReporter&&(this.telemetryReporter?.destroy(),this.telemetryReporter=void 0)}injectWidget(e,t){e.innerHTML=t;let r=Array.from(e.querySelectorAll("script"));for(let s of r){let o=document.createElement("script");for(let i of Array.from(s.attributes))o.setAttribute(i.name,i.value);o.text=s.text,s.replaceWith(o)}}attachMessageListener(){if(this.messageHandler)return;let e=t=>{if(this.expectedOrigin&&t.origin!==this.expectedOrigin)return;let r=t.data;if(Lt(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;this.applyHeight(r.height);return}if(Ut(r)){if(this.messageToken&&r.messageToken!==this.messageToken)return;let a=r.messages.filter(l=>typeof l=="string"&&l.trim()).join(" ");this.emit("validation",{sessionId:this.config.sessionId,message:a||void 0});return}if(!qt(r)||this.messageToken&&r.messageToken!==this.messageToken)return;let s=this.config.sessionId,o=typeof r.sessionId=="string"?r.sessionId:void 0;if(s&&o&&o!==s||(r.type==="complete"||r.type==="decline")&&s&&o!==s)return;let i={sessionId:r.sessionId??this.config.sessionId,intentId:r.intentId,declineReason:r.declineReason,message:r.message,nextActionRedirectUrl:r.nextActionRedirectUrl};r.type==="submitting"&&(this.submissionStarted=!0,this.submissionStartedAt=this.telemetryReporter?.now?.()??C()),z(Ot(r.type,this.submissionStarted)),this.reportOutcome(r.type),r.type==="ready"&&(this.postTheme(),this.postSubmitGate(),this.postCardFieldOrder()),r.type==="action_required"&&r.nextActionRedirectUrl&&this.showActionRequiredOverlay(r.nextActionRedirectUrl),(r.type==="complete"||r.type==="decline"||r.type==="error"||r.type==="submitting")&&this.hideActionRequiredOverlay(),this.emit(r.type,i)};this.messageHandler=e,window.addEventListener("message",e)}reportOutcome(e){let t=this.telemetryReporter;if(!t)return;if(e==="ready"&&!this.vaultReadyReported&&(this.vaultReadyReported=!0,t.performance({stage:"vault_ready",durationMs:Math.max(0,t.now()-this.captureRequestedAt),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"})),e==="complete"||e==="decline"){t.log({name:"vault.terminal",stage:"completion",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:e==="complete"?"payment_succeeded":"payment_declined",provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="error"){let o=Ve(this.submissionStarted);t.log({name:"vault.terminal",stage:o.stage,provider:"pcivault",paymentMethodCategory:"card"}),t.error({...o,provider:"pcivault",paymentMethodCategory:"card"});return}if(e==="action_required"){t.log({name:"vault.action.required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),t.log({name:"vault.three_ds.handoff",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});let o=this.submissionStartedAt;this.submissionStartedAt=null,o!==null&&t.performance({stage:"three_ds_handoff",durationMs:Math.max(0,t.now()-o),durationMode:"machine",provider:"pcivault",paymentMethodCategory:"card"}),t.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"});return}let[r,s]=Ne[e];t.log({name:r,stage:s,provider:"pcivault",paymentMethodCategory:"card"})}applyTheme(e){this.theme=e,this.postTheme()}postTheme(){if(!this.theme||!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"theme",theme:this.theme},"*")}catch{}}setSubmitGate(e){this.submitGateBlocked=e,this.postSubmitGate()}postSubmitGate(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"gate",blocked:this.submitGateBlocked},"*")}catch{}}setCardFieldOrder(e,t){this.cardFieldOrder=e,this.cardAutoFocus=t,this.postCardFieldOrder()}postCardFieldOrder(){if(!this.container)return;let t=this.container.querySelector("iframe")?.contentWindow;if(t)try{t.postMessage({source:"flopay-vault-host",type:"fieldOrder",order:this.cardFieldOrder,autoFocus:this.cardAutoFocus},"*")}catch{}}emit(e,t){for(let r of this.listeners.get(e)??[])r(t)}showActionRequiredOverlay(e){if(typeof document>"u")return;if(this.actionOverlay){let i=this.actionOverlay.querySelector("iframe");i instanceof HTMLIFrameElement&&(i.src=e);return}let t=document.createElement("div");t.setAttribute("data-flopay-action-required","1"),t.style.cssText=["position:fixed","inset:0","z-index:2147483647","background:rgba(15,23,42,0.6)","display:flex","align-items:center","justify-content:center","padding:16px"].join(";");let r=document.createElement("iframe");r.setAttribute("title","Card authentication"),r.setAttribute("allow","payment"),r.style.cssText=["width:min(100%,460px)","height:min(100%,640px)","border:0","border-radius:12px","background:#fff","box-shadow:0 12px 30px rgba(0,0,0,0.35)"].join(";"),r.src=e,t.appendChild(r);let s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Close card authentication"),s.textContent="\xD7",s.style.cssText=["position:fixed","top:20px","right:20px","width:40px","height:40px","border:0","border-radius:9999px","background:#fff","color:#0f172a","font-size:28px","line-height:40px","cursor:pointer","box-shadow:0 4px 14px rgba(0,0,0,0.25)"].join(";"),s.addEventListener("click",()=>this.abandonActionRequiredOverlay()),t.appendChild(s),t.addEventListener("click",i=>{i.target===t&&this.abandonActionRequiredOverlay()});let o=i=>{if(i.source!==r.contentWindow)return;let a=i.data;if(!a||typeof a!="object")return;let l=a;l.source==="flopay-vault-3ds-return"&&(z(Z("vault.three_ds.returned","three_ds_return")),this.telemetryReporter?.log({name:"vault.three_ds.returned",stage:"three_ds_return",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted(l.status))};window.addEventListener("message",o),this.threeDsReturnHandler=o,document.body.appendChild(t),this.actionOverlay=t,z(Z("vault.three_ds.handoff","three_ds_handoff"))}postActionCompleted(e){if(!this.container)return;let r=this.container.querySelector("iframe")?.contentWindow;if(r)try{r.postMessage({source:"flopay-vault-host",type:"action_completed",status:typeof e=="string"?e:"unknown"},"*")}catch{}}abandonActionRequiredOverlay(){if(!this.actionOverlay)return;let e=Le({eventId:"77777777-7777-4777-8777-777777777777",outcome:"customer_abandoned",stage:"three_ds_handoff",sequence:0,provider:"pcivault",paymentMethodCategory:"card"});z(e),this.telemetryReporter?.terminal({outcome:"customer_abandoned",stage:"three_ds_handoff",provider:"pcivault",paymentMethodCategory:"card"}),this.hideActionRequiredOverlay(),this.postActionCompleted("abandoned")}hideActionRequiredOverlay(){this.threeDsReturnHandler&&(window.removeEventListener("message",this.threeDsReturnHandler),this.threeDsReturnHandler=null),this.actionOverlay&&(this.actionOverlay.parentNode?.removeChild(this.actionOverlay),this.actionOverlay=null)}applyHeight(e){let t=this.container?.querySelector("iframe");if(!t)return;let r=Math.max(0,Math.min(Math.ceil(e),2e3));t.style.height=`${r}px`}};function Ke(n,e,t){let r=q;return new r(n,{reporter:e,requestedAt:t})}var Be=Symbol.for("@flopay/js.telemetry.bridge.v1");function ze(n,e,t){let r=()=>e?.now()??t();Object.defineProperty(n,Be,{configurable:!1,enumerable:!1,writable:!1,value:{error:o=>e?.error(o),log:o=>e?.log(o),performance:o=>e?.performance(o),terminal:o=>e?.terminal(o),now:r,elapsed:o=>Math.max(0,r()-o),setCheckoutContext:o=>e?.setCheckoutContext(o),beginCheckout:(o={})=>e?.beginCheckout(o)??r(),disable:()=>e?.disable()}})}function je(n){return n[Be]}function ue(n){if(!n)return!1;let e=n.code?.toLowerCase()??"";return!!n.declineCode||e.includes("declin")}function Vt(n){return n==="stripe"||n==="paypal"||n==="pcivault"?n:"other"}var ee=class{constructor(e,t,r){this.currentElements=null;this.provider=e,this.config=t,this.telemetryReporter=r??new f({billingApiUrl:He(t.billingApiUrl),sdkVersion:Nt,enabled:t.telemetry!==!1}),ze(this,this.telemetryReporter,C)}now(){return this.telemetryReporter?.now?.()??C()}elements(e){return this.currentElements&&this.currentElements.destroy(),this.currentElements=new B(this.provider,{appearance:this.config.appearance,...e}),this.currentElements}async submitElements(){return this.provider.submitElements()}cardCapture(e){let t=this.now();return this.telemetryReporter?.log({name:"vault.capture.requested",stage:"vault_request",provider:"pcivault",paymentMethodCategory:"card"}),this.telemetryReporter?Ke({sessionId:e?.sessionId},this.telemetryReporter,t):new q({sessionId:e?.sessionId,telemetry:!1})}async confirmPayPalPayment(e){let t=this.now();this.telemetryReporter?.log({name:"payment.method.selected",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.log({name:"payment.intent.started",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"});try{let r=await this.provider.confirmPayPalPayment(e);return this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),r.error||this.telemetryReporter?.log({name:"payment.intent.completed",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"2xx"}),r.status==="requires_action"?(this.telemetryReporter?.log({name:"provider.redirect.started",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.terminal({outcome:"action_required",stage:"redirect",provider:"paypal",paymentMethodCategory:"paypal"})):r.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):r.status!=="processing"&&(ue(r.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):r.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):r.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create"})),r}catch(r){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.error({errorCode:"NETWORK_REQUEST_FAILED",stage:"processing",provider:"paypal",paymentMethodCategory:"paypal",requestCategory:"intent_create",statusClass:"network_error"}),r}}async resumePayPalPayment(){let e=this.now();try{let t=await this.provider.resumePayPalPayment();return t===null?null:(this.telemetryReporter?.log({name:"provider.redirect.resumed",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),t.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:"paypal",paymentMethodCategory:"paypal"}):ue(t.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:"paypal",paymentMethodCategory:"paypal"}):t.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:"paypal",paymentMethodCategory:"paypal"}):t.error&&this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),t)}catch(t){throw this.telemetryReporter?.performance({stage:"redirect_resume",durationMs:this.now()-e,durationMode:"machine",provider:"paypal",paymentMethodCategory:"paypal"}),this.telemetryReporter?.error({errorCode:"REDIRECT_RESUME_FAILED",stage:"redirect_resume",provider:"paypal",paymentMethodCategory:"paypal"}),t}}async confirmPayment(e){if(e.paymentMethodCategory!=="wallet"&&e.paymentMethodCategory!=="apm"||!e.paymentMethodType?.trim()||e.paymentMethodType.trim().toLowerCase()==="card")throw new U("A supported non-card payment method is required.","validation_error",{param:"paymentMethodType"});let t=this.now(),r=Vt(this.provider.name);this.telemetryReporter?.log({name:"payment.processing.started",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory});try{let s=await this.provider.confirmPayment(e),o=this.now()-t;return this.telemetryReporter?.performance({stage:"processing",durationMs:o,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s.status==="succeeded"?this.telemetryReporter?.terminal({outcome:"payment_succeeded",provider:r,paymentMethodCategory:e.paymentMethodCategory}):ue(s.error)?this.telemetryReporter?.terminal({outcome:"payment_declined",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s.error?.type==="validation_error"?this.telemetryReporter?.terminal({outcome:"validation_rejected",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s.status==="requires_action"?this.telemetryReporter?.terminal({outcome:"action_required",stage:"three_ds_handoff",provider:r,paymentMethodCategory:e.paymentMethodCategory}):s.status==="failed"&&s.error&&this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s.status==="succeeded"||s.status==="failed"?this.telemetryReporter?.log({name:"payment.processing.completed",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}):this.telemetryReporter?.log({name:"operation.state_transition",stage:s.status==="requires_action"?"three_ds_handoff":"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s}catch(s){throw this.telemetryReporter?.performance({stage:"processing",durationMs:this.now()-t,durationMode:"machine",provider:r,paymentMethodCategory:e.paymentMethodCategory}),this.telemetryReporter?.error({errorCode:"PAYMENT_PROCESSING_FAILED",stage:"processing",provider:r,paymentMethodCategory:e.paymentMethodCategory}),s}}async retrieveSession(e,t){if(!e)throw new U("sessionId is required to retrieve a session.","validation_error",{param:"sessionId"});let r=await this.retrieveUnifiedSession(e,t);if(!r.data.session)throw new U("Session not found","api_error");return r.data.session}async retrieveUnifiedSession(e,t){if(!e)throw new U("sessionId is required.","validation_error",{param:"sessionId"});let r=He(t??this.config.billingApiUrl),s=this.now();this.telemetryReporter?.log({name:"session.read.started",stage:"session_read",requestCategory:"session_read"});let o,i=Ie(r,{now:()=>this.telemetryReporter?.now()??C(),onFirstByte:a=>{o=a},onRetry:(a,l)=>{this.telemetryReporter?.log({name:"operation.retry",stage:a==="session_read"?"session_read":"processing",requestCategory:a,attempt:l})}});try{let a=await i.getUnifiedCheckoutSession(e);return o!==void 0&&(this.telemetryReporter?.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.performance({stage:"session_first_byte",durationMs:o,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"})),this.telemetryReporter?.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_read",statusClass:"2xx"}),this.telemetryReporter?.log({name:"checkout.data.ready",stage:"checkout_data_ready"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:"2xx"}),a}catch(a){let l=a instanceof U?a.statusCode:void 0;throw this.telemetryReporter?.error({errorCode:a instanceof U&&a.code==="checkout_processing_timeout"?"REQUEST_TIMEOUT":"NETWORK_REQUEST_FAILED",stage:"session_read",provider:"flo",paymentMethodCategory:"unknown"}),this.telemetryReporter?.performance({stage:"session_complete",durationMs:this.now()-s,durationMode:"machine",requestCategory:"session_read",statusClass:l?`${Math.floor(l/100)}xx`:"network_error"}),a}}getRawProvider(){return this.provider.getRawProvider()}destroy(){this.telemetryReporter?.log({name:"checkout.unmount",stage:"unmount"}),this.telemetryReporter?.destroy(),this.currentElements?.destroy(),this.currentElements=null,this.provider.destroy()}};function $e(n,e,t){let r=ee;return new r(n,e,t)}var Ye=new Map;function me(n){return Array.isArray(n)?n.map(me):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,me(t)])):n}function Bt(n,e){return JSON.stringify([n,pe(e?.billingApiUrl),e?.telemetry!==!1,e?.locale??"auto",e?.apiVersion??null,me(e?.appearance??null)])}var te=new Map;async function zt(n,e){if(!n){let a=new f({billingApiUrl:pe(e?.billingApiUrl),sdkVersion:Ge,enabled:e?.telemetry!==!1});throw a.error({errorCode:"CONFIGURATION_INVALID",stage:"sdk_initialize",paymentMethodCategory:"unknown"}),a.flush().catch(()=>{}).finally(()=>a.destroy()),new Kt("A publishable key is required to initialize FloPay.","validation_error",{param:"publishableKey"})}let t=Bt(n,e),r=Ye.get(t);if(r)return e?.telemetry!==!1&&je(r)?.log({name:"sdk.cache.hit",stage:"sdk_initialize"}),r;let s=te.get(t);if(s)return s;let o={...e,publishableKey:n},i=(async()=>{let a=new f({billingApiUrl:pe(o.billingApiUrl),sdkVersion:Ge,enabled:o.telemetry!==!1}),l=a.now();a.log({name:"sdk.initialize.started",stage:"sdk_initialize"}),a.log({name:"sdk.cache.miss",stage:"sdk_initialize"}),a.log({name:"provider.load.started",stage:"provider_load",provider:"stripe"});let c=new K;try{await c.initialize(o)}catch(T){throw a.error({errorCode:"SDK_INITIALIZATION_FAILED",stage:"sdk_initialize",provider:"stripe",paymentMethodCategory:"unknown"}),a.destroy(),T}a.log({name:"provider.ready",stage:"provider_ready",provider:"stripe"}),a.log({name:"provider.availability.checked",stage:"provider_ready",provider:"stripe"}),a.log({name:"sdk.initialize.ready",stage:"sdk_initialize"});let d=a.now()-l;a.performance({stage:"sdk_initialize",durationMs:d,durationMode:"machine",provider:"stripe"}),a.performance({stage:"provider_ready",durationMs:d,durationMode:"machine",provider:"stripe"});let m=$e(c,o,a);return Ye.set(t,m),m})();te.set(t,i);try{return await i}finally{te.get(t)===i&&te.delete(t)}}import{FloPayError as R,IDEMPOTENCY_IN_PROGRESS_CODE as jt,IDEMPOTENCY_KEY_HEADER as Ht,SDK_VERSION as We,buildProductPayload as $t,foldIntoProducts as Gt,resolveIdempotencyKey as Qe,resolveSessionCurrency as Yt}from"@flopay/shared";var ye=5;function Wt(n,e){let t=e?.error,r=E(e?.code)??E(t?.code)??`http_${n}`,s=E(e?.message)??E(t?.message)??Qt(r,n);return new R(s,"api_error",{code:r,statusCode:n})}function Qt(n,e){switch(n){case"CouponLimitExceeded":return`Too many coupon codes \u2014 a checkout session accepts at most ${ye}.`;case"CouponCurrencyUnsupported":return"One of the applied coupons has no price configured for the cart currency.";default:return`Failed to create checkout session (HTTP ${e}).`}}async function Je(n,e){let{billingApiUrl:t,checkoutBaseUrl:r,items:s=[],subscriptions:o=[],products:i,account:a,successUrl:l,cancelUrl:c,checkoutMode:d="confirm",couponCodes:m=[],tagsData:T,redirectParams:h={},setCookie:_=!0,timeoutMs:w=12e3,clientId:v,currency:ge,utmMetadata:S,idempotencyKey:u}=n,L=Qe(u);if(m.length>ye)throw new R(`Too many coupon codes \u2014 a checkout session accepts at most ${ye}.`,"validation_error",{code:"CouponLimitExceeded",param:"couponCodes"});let A=i??Gt(s,o),b=Yt(ge,s,o,A);if(!b)throw new R("currency is required: pass `currency` on the session, or include a `currency` on the first item/subscription/product.","validation_error",{code:"CurrencyRequired",param:"currency"});let N={clientId:v,checkoutVersion:We,successUrl:l,cancelUrl:c,currency:b,checkoutMode:d,products:A.map(P=>$t(P,b)),accountData:{userId:a.userId,firstName:a.firstName??null,lastName:a.lastName??null,email:a.email,country:a.country??null,gender:a.gender??null,city:a.city??null,state:a.state??null,zip:a.zip??null,addressLine1:a.addressLine1??null,addressLine2:a.addressLine2??null},couponCodes:m};T&&(N.tagsData=T),S?.length&&(N.utmMetadata=S);let re=`${t.replace(/\/+$/,"")}/v1/checkouts/sessions`,fe=new AbortController,tt=setTimeout(()=>fe.abort(),w),Ce={"Content-Type":"application/json"};L&&(Ce[Ht]=L);let I,H;try{let P=await fetch(re,{method:"POST",headers:Ce,body:JSON.stringify(N),signal:fe.signal});try{e?.(P.status)}catch{}I=P.status;try{H=await P.json()}catch{}}finally{clearTimeout(tt)}if(I>=400)throw Wt(I,H);if(I===201){let P=H?.data?.uuid,ne=H?.data?.nonce;if(!P)throw new Error("Checkout session created but no UUID was returned by the billing API");if(!ne)throw new R("Checkout session created but no `nonce` was returned by the billing API. Upgrade the billing service to TeamFloPay/backend#640 or later.","api_error",{code:"MissingCheckoutSessionToken"});(A.length||b)&&x(P,{currency:b,products:A.map(g=>({code:g.code??g.providerItemId??g.providerPlanId,type:g.type,name:g.name??g.itemName??g.providerItemName??g.subscriptionName??g.providerPlanName??null,totalAmount:g.totalAmount,overrideAmount:g.overrideAmount,currency:g.currency??b}))});let $=new URL(`${r.replace(/\/+$/,"")}/secure`);$.searchParams.set("id",P);for(let[g,G]of Object.entries(h))$.searchParams.set(g,G);if(_&&typeof window<"u"&&typeof document<"u"){let g=JSON.stringify({origin_url:c}),G=window.location.hostname.split(".").slice(-2).join(".");document.cookie=`checkout_data=${encodeURIComponent(g)}; domain=.${G}; path=/; max-age=3600; SameSite=Lax; Secure;`,document.cookie=`flopay_checkout_token=${encodeURIComponent(ne)}; domain=.${G}; path=/; max-age=3600; SameSite=Lax; Secure;`}return typeof window<"u"&&(window.location.href=$.toString()),{status:201,redirectUrl:$.toString(),nonce:ne}}return I===204?(typeof window<"u"&&(window.location.href=l),{status:204}):{status:I}}async function Jt(n){let e=Ze(n),t=Xe(e);try{let r=await Je(n,t);return et(e,r),r}catch(r){throw he(e.reporter,r),r}finally{j(e.reporter)}}function Xe(n){let e=!1;return t=>{if(e)return;e=!0;let r=`${Math.floor(t/100)}xx`;n.reporter.log({name:"session.request.first_byte",stage:"session_first_byte",requestCategory:"session_create",statusClass:r}),n.reporter.performance({stage:"session_first_byte",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:r})}}function Ze(n){let e=new f({billingApiUrl:n.billingApiUrl,sdkVersion:We,enabled:n.telemetry!==!1}),t=e.now();return e.log({name:"session.create.started",stage:"session_create",requestCategory:"session_create"}),{reporter:e,startedAt:t}}function et(n,e){let t=`${Math.floor(e.status/100)}xx`;n.reporter.log({name:"session.request.completed",stage:"session_complete",requestCategory:"session_create",statusClass:t}),n.reporter.performance({stage:"session_complete",durationMs:n.reporter.now()-n.startedAt,durationMode:"machine",requestCategory:"session_create",statusClass:t})}function he(n,e){if(e instanceof R&&e.type==="validation_error"){n.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"});return}let t=e instanceof R?e.statusCode:void 0;n.error({errorCode:e instanceof Error&&e.name==="AbortError"?"REQUEST_TIMEOUT":e instanceof TypeError?"NETWORK_REQUEST_FAILED":"CHECKOUT_SESSION_CREATE_FAILED",stage:"session_create",requestCategory:"session_create",statusClass:e instanceof Error&&e.name==="AbortError"?"timeout":t?`${Math.floor(t/100)}xx`:"network_error"})}function j(n){n.flush().catch(()=>{}).finally(()=>n.destroy())}async function Xt(n){let{maxRetries:e=3,...t}=n,r=Ze(n),s=Xe(r);if(!Number.isFinite(e)||!Number.isInteger(e)||e<=0)throw r.reporter.terminal({outcome:"validation_rejected",stage:"session_create",requestCategory:"session_create"}),j(r.reporter),new Error("Number of retries must be greater than 0");let o={...t,idempotencyKey:Qe(t.idempotencyKey)},i;for(let a=0;a<=e;a++)try{let l=await Je(o,s);return et(r,l),j(r.reporter),l}catch(l){i=l;let c=l instanceof Error&&l.name==="AbortError",d=l instanceof R&&l.code===jt;if((c||d)&&a<e){r.reporter.log({name:"operation.retry",stage:"session_create",requestCategory:"session_create",attempt:a+1}),await new Promise(m=>setTimeout(m,100*Math.pow(2,a)));continue}throw he(r.reporter,l),j(r.reporter),l}throw he(r.reporter,i),j(r.reporter),i??new Error("Unknown error during checkout session creation")}export{ee as FloPay,B as FloPayElements,M as PaymentAPI,q as PciVaultCardCapture,K as StripeAdapter,x as cacheSessionDisplayData,ie as clearSessionDisplayData,Jt as createCheckoutSession,Xt as createCheckoutSessionWithRetries,se as getSessionDisplayData,zt as loadFloPay};