@sunbay/checkout-sdk-js 0.0.5 → 0.0.7

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.cjs CHANGED
@@ -22,20 +22,68 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  CheckoutElement: () => CheckoutElement,
24
24
  CheckoutInstance: () => CheckoutInstance,
25
- ErrorCode: () => import_checkout_sdk_protocol6.ErrorCode,
25
+ ErrorCode: () => import_checkout_sdk_protocol7.ErrorCode,
26
26
  createCheckout: () => createCheckout,
27
27
  version: () => version
28
28
  });
29
29
  module.exports = __toCommonJS(index_exports);
30
30
 
31
31
  // src/transport/MainFrameTransport.ts
32
- var import_checkout_sdk_protocol = require("@sunbay/checkout-sdk-protocol");
33
32
  var import_checkout_sdk_protocol2 = require("@sunbay/checkout-sdk-protocol");
33
+ var import_checkout_sdk_protocol3 = require("@sunbay/checkout-sdk-protocol");
34
+
35
+ // src/config/env.ts
36
+ var HOST_ORIGINS = {
37
+ dev: "https://checkout.sunbay-dev.com",
38
+ test: "https://checkout.sunbay-uat.us",
39
+ prod: "https://checkout.sunbay.us"
40
+ };
41
+ function resolveHostOrigin(env = "prod", override) {
42
+ if (override) {
43
+ return override.replace(/\/+$/, "");
44
+ }
45
+ return HOST_ORIGINS[env];
46
+ }
47
+ var RUNTIME_BASE_PATH = "/embed/sdk";
48
+ function runtimeUrl(hostOrigin, segment, type) {
49
+ const origin = hostOrigin.replace(/\/+$/, "");
50
+ const path = type ? `${segment}/${type}` : segment;
51
+ return `${origin}${RUNTIME_BASE_PATH}/${path}`;
52
+ }
53
+
54
+ // src/transport/hello.ts
55
+ var import_checkout_sdk_protocol = require("@sunbay/checkout-sdk-protocol");
56
+ function isValidRuntimeHello(value) {
57
+ if (typeof value !== "object" || value === null) {
58
+ return false;
59
+ }
60
+ const r = value;
61
+ if (r.protocol !== import_checkout_sdk_protocol.PROTOCOL_NAME || r.kind !== "hello") {
62
+ return false;
63
+ }
64
+ if (typeof r.runtimeId !== "string" || r.runtimeId.length === 0) {
65
+ return false;
66
+ }
67
+ if (!Array.isArray(r.supportedMajorVersions) || !r.supportedMajorVersions.every((v) => typeof v === "number" && Number.isFinite(v))) {
68
+ return false;
69
+ }
70
+ if (r.capabilities !== void 0 && (!Array.isArray(r.capabilities) || !r.capabilities.every((c) => typeof c === "string"))) {
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+
76
+ // src/transport/MainFrameTransport.ts
34
77
  var DEFAULT_REQUEST_TIMEOUTS = {
35
78
  default: 1e4,
36
79
  initialize: 3e4,
37
80
  handshake: 15e3
38
81
  };
82
+ function rethrowAsync(err) {
83
+ setTimeout(() => {
84
+ throw err;
85
+ }, 0);
86
+ }
39
87
  function genId(prefix) {
40
88
  const rand = Math.random().toString(36).slice(2);
41
89
  return `${prefix}_${Date.now().toString(36)}_${rand}`;
@@ -53,7 +101,7 @@ function isRuntimeHello(value) {
53
101
  return false;
54
102
  }
55
103
  const record = value;
56
- return record.protocol === import_checkout_sdk_protocol.PROTOCOL_NAME && record.kind === "hello";
104
+ return record.protocol === import_checkout_sdk_protocol2.PROTOCOL_NAME && record.kind === "hello";
57
105
  }
58
106
  var MainFrameTransport = class {
59
107
  constructor(options, timeouts = DEFAULT_REQUEST_TIMEOUTS) {
@@ -88,7 +136,7 @@ var MainFrameTransport = class {
88
136
  return this.iframe;
89
137
  }
90
138
  const iframe = document.createElement("iframe");
91
- iframe.src = `${this.hostOrigin}/sdk/main?checkoutId=${this.checkoutId}`;
139
+ iframe.src = `${runtimeUrl(this.hostOrigin, "main")}?checkoutId=${this.checkoutId}`;
92
140
  iframe.setAttribute("aria-hidden", "true");
93
141
  iframe.title = "sunbay-checkout-main";
94
142
  iframe.style.position = "absolute";
@@ -112,14 +160,14 @@ var MainFrameTransport = class {
112
160
  request(name, payload) {
113
161
  return new Promise((resolve, reject) => {
114
162
  if (this.destroyed) {
115
- reject(makeError(import_checkout_sdk_protocol2.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed"));
163
+ reject(makeError(import_checkout_sdk_protocol3.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed"));
116
164
  return;
117
165
  }
118
166
  const contentWindow = this.iframe?.contentWindow;
119
167
  if (!contentWindow) {
120
168
  reject(
121
169
  makeError(
122
- import_checkout_sdk_protocol2.ErrorCode.RUNTIME_LOAD_FAILED,
170
+ import_checkout_sdk_protocol3.ErrorCode.RUNTIME_LOAD_FAILED,
123
171
  "main iframe not created or contentWindow unavailable"
124
172
  )
125
173
  );
@@ -127,8 +175,8 @@ var MainFrameTransport = class {
127
175
  }
128
176
  const requestId = genId("req");
129
177
  const envelope = {
130
- protocol: import_checkout_sdk_protocol.PROTOCOL_NAME,
131
- major: import_checkout_sdk_protocol.PROTOCOL_MAJOR,
178
+ protocol: import_checkout_sdk_protocol2.PROTOCOL_NAME,
179
+ major: import_checkout_sdk_protocol2.PROTOCOL_MAJOR,
132
180
  runtimeId: this.runtimeId,
133
181
  checkoutId: this.checkoutId,
134
182
  kind: "request",
@@ -139,10 +187,10 @@ var MainFrameTransport = class {
139
187
  const timeoutMs = this.resolveTimeout(name);
140
188
  const timer = setTimeout(() => {
141
189
  this.pending.delete(requestId);
142
- reject(makeError(import_checkout_sdk_protocol2.ErrorCode.REQUEST_TIMEOUT, `Command ${name} timed out`));
190
+ reject(makeError(import_checkout_sdk_protocol3.ErrorCode.REQUEST_TIMEOUT, `Command ${name} timed out`));
143
191
  }, timeoutMs);
144
192
  this.pending.set(requestId, { resolve, reject, timer });
145
- contentWindow.postMessage((0, import_checkout_sdk_protocol.encodeEnvelope)(envelope), this.hostOrigin);
193
+ contentWindow.postMessage((0, import_checkout_sdk_protocol2.encodeEnvelope)(envelope), this.hostOrigin);
146
194
  });
147
195
  }
148
196
  /**
@@ -176,7 +224,8 @@ var MainFrameTransport = class {
176
224
  }
177
225
  /**
178
226
  * Register the handshake (RuntimeHello) callback. The hello phase has no checkoutId yet and is
179
- * handled separately.
227
+ * handled separately. The callback is one-shot: it is cleared after the first valid hello from
228
+ * this transport's own iframe; malformed hellos are ignored.
180
229
  *
181
230
  * @param handler - Called when a hello is received.
182
231
  */
@@ -204,7 +253,7 @@ var MainFrameTransport = class {
204
253
  window.removeEventListener("message", this.messageListener);
205
254
  for (const [, entry] of this.pending) {
206
255
  clearTimeout(entry.timer);
207
- entry.reject(makeError(import_checkout_sdk_protocol2.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed"));
256
+ entry.reject(makeError(import_checkout_sdk_protocol3.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed"));
208
257
  }
209
258
  this.pending.clear();
210
259
  this.eventHandlers.clear();
@@ -280,6 +329,10 @@ var MainFrameTransport = class {
280
329
  if (typeof event.data !== "string") {
281
330
  return;
282
331
  }
332
+ const mainWindow = this.iframe?.contentWindow;
333
+ if (!mainWindow || event.source !== mainWindow) {
334
+ return;
335
+ }
283
336
  let raw;
284
337
  try {
285
338
  raw = JSON.parse(event.data);
@@ -287,20 +340,32 @@ var MainFrameTransport = class {
287
340
  return;
288
341
  }
289
342
  if (isRuntimeHello(raw)) {
290
- if (this.helloHandler) {
291
- this.helloHandler(raw);
343
+ if (!isValidRuntimeHello(raw)) {
344
+ return;
345
+ }
346
+ const handler = this.helloHandler;
347
+ this.helloHandler = null;
348
+ if (handler) {
349
+ try {
350
+ handler(raw);
351
+ } catch (err) {
352
+ rethrowAsync(err);
353
+ }
292
354
  }
293
355
  return;
294
356
  }
295
357
  let envelope;
296
358
  try {
297
- envelope = (0, import_checkout_sdk_protocol.decodeEnvelope)(event.data);
359
+ envelope = (0, import_checkout_sdk_protocol2.decodeEnvelope)(event.data);
298
360
  } catch {
299
361
  return;
300
362
  }
301
363
  if (envelope.checkoutId !== this.checkoutId) {
302
364
  return;
303
365
  }
366
+ if (this.runtimeId !== "" && envelope.runtimeId !== this.runtimeId) {
367
+ return;
368
+ }
304
369
  if (envelope.kind === "response") {
305
370
  this.handleResponse(envelope);
306
371
  } else if (envelope.kind === "event") {
@@ -327,14 +392,19 @@ var MainFrameTransport = class {
327
392
  if (!set) {
328
393
  return;
329
394
  }
330
- for (const handler of set) {
331
- handler(envelope.payload);
395
+ for (const handler of [...set]) {
396
+ try {
397
+ handler(envelope.payload);
398
+ } catch (err) {
399
+ rethrowAsync(err);
400
+ }
332
401
  }
333
402
  }
334
403
  };
335
404
 
336
405
  // src/Element.ts
337
- var import_checkout_sdk_protocol3 = require("@sunbay/checkout-sdk-protocol");
406
+ var import_checkout_sdk_protocol4 = require("@sunbay/checkout-sdk-protocol");
407
+ var DEFAULT_MOUNT_TIMEOUT_MS = 3e4;
338
408
  var FIELD_TYPES = ["cardNumber", "cardExpiry", "cardCvc"];
339
409
  var INPUT_TYPES = [
340
410
  "cardNumber",
@@ -367,8 +437,15 @@ var CheckoutElement = class _CheckoutElement {
367
437
  /** Event handlers temporarily subscribed during mount (unbound after resolve/reject). */
368
438
  this.readyHandler = null;
369
439
  this.loadErrorHandler = null;
440
+ /**
441
+ * Cancels the in-flight mount (clears its timer/listeners and rejects its promise). Null when no
442
+ * mount is in flight. Used by `unmount()` / `destroy()` while the Element is still loading.
443
+ */
444
+ this.abortMount = null;
370
445
  /** expressCheckout only: the persistently subscribed expressAvailabilityChange handler (unbound on destroy). */
371
446
  this.availabilityHandler = null;
447
+ /** Merchant listeners registered via `on`: event → (original handler → transport wrapper). Cleared on destroy. */
448
+ this.userListeners = /* @__PURE__ */ new Map();
372
449
  /**
373
450
  * iframe auto-height: the window 'message' listener that stays resident during mount (unbound
374
451
  * when the iframe disappears/is destroyed). Keeps a reference so removeEventListener can be
@@ -409,18 +486,25 @@ var CheckoutElement = class _CheckoutElement {
409
486
  /**
410
487
  * Mount at the merchant DOM target: insert a visible iframe, send createElement, await elementReady.
411
488
  *
489
+ * Failure modes: a hosted `loadError` / command failure rejects with that error; waiting longer
490
+ * than `opts.timeoutMs` (default 30000ms) removes the iframe and rejects `RUNTIME_LOAD_FAILED`;
491
+ * calling `unmount()` while loading rejects with `RUNTIME_LOAD_FAILED` ("mount cancelled");
492
+ * calling `destroy()` (or destroying the instance) while loading rejects `INSTANCE_DESTROYED`.
493
+ * A late `elementReady` after any of these is ignored and never flips the status to ready.
494
+ *
412
495
  * @param selectorOrEl - A CSS selector or an HTMLElement container; the container must be unique and empty.
496
+ * @param opts - Optional mount options (`timeoutMs`).
413
497
  * @returns Resolves after elementReady; on failure removes the node and rejects (loadError / INVALID_OPTIONS).
414
498
  * @throws INSTANCE_DESTROYED when already destroyed.
415
499
  * @example
416
- * await element.mount('#card-field');
500
+ * await element.mount('#card-field', { timeoutMs: 20000 });
417
501
  */
418
- mount(selectorOrEl) {
502
+ mount(selectorOrEl, opts) {
419
503
  this.assertAlive();
420
504
  if (this.status === "loading" || this.status === "ready") {
421
505
  return Promise.reject(
422
506
  makeError2(
423
- import_checkout_sdk_protocol3.ErrorCode.ELEMENT_CONFLICT,
507
+ import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
424
508
  "This Element is already mounted; mount cannot be called twice",
425
509
  this.elementId
426
510
  )
@@ -430,7 +514,7 @@ var CheckoutElement = class _CheckoutElement {
430
514
  if (!container) {
431
515
  return Promise.reject(
432
516
  makeError2(
433
- import_checkout_sdk_protocol3.ErrorCode.INVALID_OPTIONS,
517
+ import_checkout_sdk_protocol4.ErrorCode.INVALID_OPTIONS,
434
518
  "Target container not found or not uniquely resolvable",
435
519
  this.elementId
436
520
  )
@@ -438,7 +522,7 @@ var CheckoutElement = class _CheckoutElement {
438
522
  }
439
523
  if (container.childElementCount > 0) {
440
524
  return Promise.reject(
441
- makeError2(import_checkout_sdk_protocol3.ErrorCode.INVALID_OPTIONS, "Target container is not empty", this.elementId)
525
+ makeError2(import_checkout_sdk_protocol4.ErrorCode.INVALID_OPTIONS, "Target container is not empty", this.elementId)
442
526
  );
443
527
  }
444
528
  this.status = "loading";
@@ -458,8 +542,18 @@ var CheckoutElement = class _CheckoutElement {
458
542
  container.appendChild(iframe);
459
543
  this.iframe = iframe;
460
544
  this.installResizeListener();
545
+ const requested = opts?.timeoutMs;
546
+ const timeoutMs = typeof requested === "number" && Number.isFinite(requested) && requested > 0 ? requested : DEFAULT_MOUNT_TIMEOUT_MS;
461
547
  return new Promise((resolve, reject) => {
548
+ let settled = false;
549
+ let timer = null;
462
550
  const cleanup = () => {
551
+ settled = true;
552
+ if (timer !== null) {
553
+ clearTimeout(timer);
554
+ timer = null;
555
+ }
556
+ this.abortMount = null;
463
557
  if (this.readyHandler) {
464
558
  this.transport.off("elementReady", this.readyHandler);
465
559
  this.readyHandler = null;
@@ -470,7 +564,7 @@ var CheckoutElement = class _CheckoutElement {
470
564
  }
471
565
  };
472
566
  const onReady = (payload) => {
473
- if (!matchesElement(payload, this.elementId)) {
567
+ if (settled || !matchesElement(payload, this.elementId)) {
474
568
  return;
475
569
  }
476
570
  cleanup();
@@ -482,16 +576,17 @@ var CheckoutElement = class _CheckoutElement {
482
576
  resolve();
483
577
  };
484
578
  const onLoadError = (payload) => {
485
- if (!matchesElement(payload, this.elementId)) {
579
+ if (settled || !matchesElement(payload, this.elementId)) {
486
580
  return;
487
581
  }
488
582
  cleanup();
489
583
  this.status = "loadError";
490
584
  this.removeIframe();
585
+ this.releaseHostedElement();
491
586
  const err = payload?.error;
492
587
  reject(
493
588
  err ?? makeError2(
494
- import_checkout_sdk_protocol3.ErrorCode.RUNTIME_LOAD_FAILED,
589
+ import_checkout_sdk_protocol4.ErrorCode.RUNTIME_LOAD_FAILED,
495
590
  "Failed to load Element",
496
591
  this.elementId
497
592
  )
@@ -501,18 +596,56 @@ var CheckoutElement = class _CheckoutElement {
501
596
  this.loadErrorHandler = onLoadError;
502
597
  this.transport.on("elementReady", onReady);
503
598
  this.transport.on("loadError", onLoadError);
599
+ this.abortMount = (reason) => {
600
+ if (settled) {
601
+ return;
602
+ }
603
+ cleanup();
604
+ reject(reason);
605
+ };
606
+ timer = setTimeout(() => {
607
+ if (settled) {
608
+ return;
609
+ }
610
+ cleanup();
611
+ this.status = "loadError";
612
+ this.removeIframe();
613
+ this.releaseHostedElement();
614
+ reject(
615
+ makeError2(
616
+ import_checkout_sdk_protocol4.ErrorCode.RUNTIME_LOAD_FAILED,
617
+ `Element did not become ready within ${timeoutMs}ms`,
618
+ this.elementId
619
+ )
620
+ );
621
+ }, timeoutMs);
504
622
  this.transport.request("createElement", {
505
623
  elementId: this.elementId,
506
624
  type: this.type,
507
625
  options: this.options
508
- }).catch((cmdErr) => {
509
- cleanup();
510
- this.status = "loadError";
511
- this.removeIframe();
512
- reject(cmdErr);
513
- });
626
+ }).then(
627
+ () => void 0,
628
+ (cmdErr) => {
629
+ if (settled) {
630
+ return;
631
+ }
632
+ cleanup();
633
+ this.status = "loadError";
634
+ this.removeIframe();
635
+ reject(cmdErr);
636
+ }
637
+ );
514
638
  });
515
639
  }
640
+ /** Best-effort, fire-and-forget release of the hosted element registration; never throws. */
641
+ releaseHostedElement() {
642
+ try {
643
+ void Promise.resolve(
644
+ this.transport.request("destroyElement", { elementId: this.elementId })
645
+ ).catch(() => void 0);
646
+ } catch {
647
+ }
648
+ }
516
649
  /**
517
650
  * Unmount: send destroyElement, remove the iframe; idempotent; keeps the handle and configuration.
518
651
  *
@@ -524,6 +657,13 @@ var CheckoutElement = class _CheckoutElement {
524
657
  if (this.status !== "ready" && this.status !== "loading") {
525
658
  return;
526
659
  }
660
+ this.abortMount?.(
661
+ makeError2(
662
+ import_checkout_sdk_protocol4.ErrorCode.RUNTIME_LOAD_FAILED,
663
+ "Mount cancelled: the Element was unmounted while loading",
664
+ this.elementId
665
+ )
666
+ );
527
667
  try {
528
668
  await this.transport.request("destroyElement", { elementId: this.elementId });
529
669
  } finally {
@@ -539,6 +679,14 @@ var CheckoutElement = class _CheckoutElement {
539
679
  if (this.status === "destroyed") {
540
680
  return;
541
681
  }
682
+ const wasHosted = this.status === "loading" || this.status === "ready";
683
+ this.abortMount?.(
684
+ makeError2(
685
+ import_checkout_sdk_protocol4.ErrorCode.INSTANCE_DESTROYED,
686
+ "Mount cancelled: the Element was destroyed while loading",
687
+ this.elementId
688
+ )
689
+ );
542
690
  if (this.readyHandler) {
543
691
  this.transport.off("elementReady", this.readyHandler);
544
692
  this.readyHandler = null;
@@ -551,9 +699,23 @@ var CheckoutElement = class _CheckoutElement {
551
699
  this.transport.off("expressAvailabilityChange", this.availabilityHandler);
552
700
  this.availabilityHandler = null;
553
701
  }
702
+ for (const [event, wrappers] of this.userListeners) {
703
+ for (const wrapper of wrappers.values()) {
704
+ this.transport.off(event, wrapper);
705
+ }
706
+ }
707
+ this.userListeners.clear();
554
708
  this.removeIframe();
555
709
  this.container = null;
556
710
  this.status = "destroyed";
711
+ if (wasHosted) {
712
+ try {
713
+ void Promise.resolve(
714
+ this.transport.request("destroyElement", { elementId: this.elementId })
715
+ ).catch(() => void 0);
716
+ } catch {
717
+ }
718
+ }
557
719
  this.onDestroy?.(this.elementId);
558
720
  }
559
721
  /**
@@ -583,7 +745,24 @@ var CheckoutElement = class _CheckoutElement {
583
745
  */
584
746
  on(event, handler) {
585
747
  this.assertAlive();
586
- this.transport.on(event, handler);
748
+ let wrappers = this.userListeners.get(event);
749
+ if (!wrappers) {
750
+ wrappers = /* @__PURE__ */ new Map();
751
+ this.userListeners.set(event, wrappers);
752
+ }
753
+ if (wrappers.has(handler)) {
754
+ return;
755
+ }
756
+ const typed = handler;
757
+ const wrapper = (payload) => {
758
+ const target = payload?.elementId;
759
+ if (target !== void 0 && target !== this.elementId) {
760
+ return;
761
+ }
762
+ typed(payload);
763
+ };
764
+ wrappers.set(typed, wrapper);
765
+ this.transport.on(event, wrapper);
587
766
  }
588
767
  /**
589
768
  * Unregister an event handler (still safe to call after destruction).
@@ -592,7 +771,13 @@ var CheckoutElement = class _CheckoutElement {
592
771
  * @param handler - The previously registered callback.
593
772
  */
594
773
  off(event, handler) {
595
- this.transport.off(event, handler);
774
+ const wrappers = this.userListeners.get(event);
775
+ const wrapper = wrappers?.get(handler);
776
+ if (!wrappers || !wrapper) {
777
+ return;
778
+ }
779
+ wrappers.delete(handler);
780
+ this.transport.off(event, wrapper);
596
781
  }
597
782
  /** Install input-class action methods (automatically called after construction). */
598
783
  installInputActions() {
@@ -633,7 +818,7 @@ var CheckoutElement = class _CheckoutElement {
633
818
  /** Throw INSTANCE_DESTROYED if already destroyed. */
634
819
  assertAlive() {
635
820
  if (this.status === "destroyed") {
636
- throw makeError2(import_checkout_sdk_protocol3.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", this.elementId);
821
+ throw makeError2(import_checkout_sdk_protocol4.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", this.elementId);
637
822
  }
638
823
  }
639
824
  /** Resolve the mount container (the selector must uniquely match a single element). */
@@ -649,7 +834,7 @@ var CheckoutElement = class _CheckoutElement {
649
834
  return node instanceof HTMLElement ? node : null;
650
835
  }
651
836
  /**
652
- * Resolve the iframe src: split fields go to /sdk/field/, the rest to /sdk/element/, with
837
+ * Resolve the iframe src: split fields go to /embed/sdk/field/, the rest to /embed/sdk/element/, with
653
838
  * checkoutId and elementId; if an initial colorScheme is provided, append `&colorScheme=<value>`
654
839
  * (no flash on the first frame); if the initial appearance contains variables or rules, append
655
840
  * `&appearance=<encodeURIComponent(JSON.stringify(appearance))>` (takes effect on the first
@@ -681,7 +866,7 @@ var CheckoutElement = class _CheckoutElement {
681
866
  if (this.type === "expressCheckout") {
682
867
  query += this.resolveExpressQuery();
683
868
  }
684
- return `${this.hostOrigin}/sdk/${segment}/${this.type}${query}`;
869
+ return `${runtimeUrl(this.hostOrigin, segment, this.type)}${query}`;
685
870
  }
686
871
  /**
687
872
  * Extract a per-element appearance (from the Element's own options, i.e. the second
@@ -751,7 +936,7 @@ var CheckoutElement = class _CheckoutElement {
751
936
  if (event.origin !== this.hostOrigin) {
752
937
  return;
753
938
  }
754
- if (!(0, import_checkout_sdk_protocol3.isIframeResizeMessage)(event.data)) {
939
+ if (!(0, import_checkout_sdk_protocol4.isIframeResizeMessage)(event.data)) {
755
940
  return;
756
941
  }
757
942
  if (event.data.elementId !== this.elementId) {
@@ -790,7 +975,8 @@ var CheckoutElement = class _CheckoutElement {
790
975
  };
791
976
 
792
977
  // src/CheckoutInstance.ts
793
- var import_checkout_sdk_protocol4 = require("@sunbay/checkout-sdk-protocol");
978
+ var import_checkout_sdk_protocol5 = require("@sunbay/checkout-sdk-protocol");
979
+ var CONFIRM_RESULT_DEADLINE_MS = 12e4;
794
980
  var CARD_FIELD_TYPES = ["cardNumber", "cardExpiry", "cardCvc"];
795
981
  function genId2(prefix) {
796
982
  const rand = Math.random().toString(36).slice(2);
@@ -863,34 +1049,100 @@ var CheckoutInstance = class {
863
1049
  return element;
864
1050
  }
865
1051
  /**
866
- * Initiate a payment confirmation. Generates an operationId, sends the confirm command to obtain
867
- * accepted, and the returned Promise is fulfilled by a later paymentResult event with the same
868
- * operationId. Calling again while in progress → CHECKOUT_BUSY.
1052
+ * Initiate a payment confirmation. Generates an operationId, sends the `confirm` command, and
1053
+ * returns a Promise fulfilled by `paymentResult` events with the same operationId.
1054
+ *
1055
+ * Behavior changes in 0.0.7: previously the Promise resolved on the first `paymentResult`,
1056
+ * including a non-final `pending` outcome. Now it resolves ONLY on a terminal outcome
1057
+ * (`succeeded` | `failed` | `canceled`); a `pending` outcome keeps it waiting.
1058
+ *
1059
+ * Watchdog: if no terminal outcome arrives within `resultTimeoutMs` (default
1060
+ * {@link CONFIRM_RESULT_DEADLINE_MS} = 120000ms) the Promise resolves
1061
+ * `{ status: 'pending', operationId, txnId? }`. This is NOT a failure: the payment may still
1062
+ * complete, so never treat it as failed and never retry blindly. Reconcile with
1063
+ * `getPaymentStatus()` or the `paymentResult` event.
1064
+ *
1065
+ * Slot semantics (duplicate-submit protection): the confirm slot stays occupied until a
1066
+ * terminal outcome arrives or `destroy()` is called. While it is occupied another `confirm()`
1067
+ * rejects with `CHECKOUT_BUSY`; this also holds after the watchdog resolved `pending`, and later
1068
+ * terminal outcomes are still delivered through `on('paymentResult', ...)`.
869
1069
  *
870
- * @param opts - Optional parameters such as billing/shipping address, name, email, returnUrl.
871
- * @returns The terminal PaymentOutcome.
1070
+ * If the `confirm` command is rejected by the runtime the payment was not started: the Promise
1071
+ * rejects with that error and the slot is freed. If the command itself times out
1072
+ * (`REQUEST_TIMEOUT`) the runtime may have started the payment: the Promise rejects with the
1073
+ * error augmented with `paymentStateKnown: false`, the slot stays occupied and a later terminal
1074
+ * `paymentResult` for this operation frees it. Do not retry; reconcile with `getPaymentStatus()`.
1075
+ *
1076
+ * `error` events with `paymentStateKnown === false` are informational and do not settle the
1077
+ * Promise.
1078
+ *
1079
+ * @param opts - Optional billing/shipping address, name, email, returnUrl, plus `onOperation`
1080
+ * and `resultTimeoutMs`.
1081
+ * @returns The terminal PaymentOutcome, or `{ status: 'pending' }` when the watchdog fires.
872
1082
  * @throws rejects INSTANCE_DESTROYED when destroyed; rejects CHECKOUT_BUSY when in progress.
873
1083
  */
874
1084
  confirm(opts) {
875
1085
  if (this.destroyed) {
876
1086
  return Promise.reject(
877
- makeError3(import_checkout_sdk_protocol4.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", "runtime")
1087
+ makeError3(import_checkout_sdk_protocol5.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", "runtime")
878
1088
  );
879
1089
  }
880
1090
  if (this.pendingConfirm) {
881
1091
  return Promise.reject(
882
- makeError3(import_checkout_sdk_protocol4.ErrorCode.CHECKOUT_BUSY, "A payment confirmation is already in progress", "runtime")
1092
+ makeError3(import_checkout_sdk_protocol5.ErrorCode.CHECKOUT_BUSY, "A payment confirmation is already in progress", "runtime")
883
1093
  );
884
1094
  }
1095
+ const { onOperation, resultTimeoutMs, ...rest } = opts ?? {};
885
1096
  const operationId = genId2("op");
886
- const payload = { ...opts, operationId };
1097
+ const payload = { ...rest, operationId };
1098
+ const deadline = typeof resultTimeoutMs === "number" && Number.isFinite(resultTimeoutMs) && resultTimeoutMs > 0 ? resultTimeoutMs : CONFIRM_RESULT_DEADLINE_MS;
887
1099
  return new Promise((resolve, reject) => {
888
- this.pendingConfirm = { operationId, resolve, reject };
1100
+ const entry = {
1101
+ operationId,
1102
+ settled: false,
1103
+ resolve,
1104
+ reject,
1105
+ watchdog: null,
1106
+ lastPendingTxnId: void 0
1107
+ };
1108
+ this.pendingConfirm = entry;
1109
+ entry.watchdog = setTimeout(() => {
1110
+ entry.watchdog = null;
1111
+ if (entry.settled) {
1112
+ return;
1113
+ }
1114
+ entry.settled = true;
1115
+ const outcome = entry.lastPendingTxnId !== void 0 ? { status: "pending", operationId, txnId: entry.lastPendingTxnId } : { status: "pending", operationId };
1116
+ resolve(outcome);
1117
+ }, deadline);
1118
+ if (typeof onOperation === "function") {
1119
+ try {
1120
+ onOperation(operationId);
1121
+ } catch (err) {
1122
+ setTimeout(() => {
1123
+ throw err;
1124
+ }, 0);
1125
+ }
1126
+ }
889
1127
  this.transport.request("confirm", payload).catch((err) => {
890
- if (this.pendingConfirm && this.pendingConfirm.operationId === operationId) {
891
- this.pendingConfirm = null;
1128
+ if (this.pendingConfirm !== entry) {
1129
+ return;
1130
+ }
1131
+ const error = err;
1132
+ if (error && error.code === import_checkout_sdk_protocol5.ErrorCode.REQUEST_TIMEOUT) {
1133
+ if (!entry.settled) {
1134
+ entry.settled = true;
1135
+ this.clearWatchdog(entry);
1136
+ reject({ ...error, paymentStateKnown: false });
1137
+ }
1138
+ return;
1139
+ }
1140
+ this.pendingConfirm = null;
1141
+ this.clearWatchdog(entry);
1142
+ if (!entry.settled) {
1143
+ entry.settled = true;
1144
+ reject(error);
892
1145
  }
893
- reject(err);
894
1146
  });
895
1147
  });
896
1148
  }
@@ -976,10 +1228,15 @@ var CheckoutInstance = class {
976
1228
  this.elements.clear();
977
1229
  this.transport.off("paymentResult", this.paymentResultHandler);
978
1230
  if (this.pendingConfirm) {
979
- this.pendingConfirm.reject(
980
- makeError3(import_checkout_sdk_protocol4.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", "runtime")
981
- );
1231
+ const entry = this.pendingConfirm;
982
1232
  this.pendingConfirm = null;
1233
+ this.clearWatchdog(entry);
1234
+ if (!entry.settled) {
1235
+ entry.settled = true;
1236
+ entry.reject(
1237
+ makeError3(import_checkout_sdk_protocol5.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", "runtime")
1238
+ );
1239
+ }
983
1240
  }
984
1241
  void Promise.resolve(this.transport.request("destroy", {})).catch(() => void 0);
985
1242
  this.transport.destroy();
@@ -987,7 +1244,7 @@ var CheckoutInstance = class {
987
1244
  /** Throw INSTANCE_DESTROYED if already destroyed. */
988
1245
  assertAlive() {
989
1246
  if (this.destroyed) {
990
- throw makeError3(import_checkout_sdk_protocol4.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", "runtime");
1247
+ throw makeError3(import_checkout_sdk_protocol5.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", "runtime");
991
1248
  }
992
1249
  }
993
1250
  /** Mutual-exclusion check: throws ELEMENT_CONFLICT on conflict (derived live from the elements Map, does not mutate the registry). */
@@ -997,11 +1254,11 @@ var CheckoutInstance = class {
997
1254
  const hasCardField = () => existing.some((e) => CARD_FIELD_TYPES.includes(e.type));
998
1255
  if (type === "card") {
999
1256
  if (has("card")) {
1000
- throw makeError3(import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT, "A combined card Element already exists");
1257
+ throw makeError3(import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT, "A combined card Element already exists");
1001
1258
  }
1002
1259
  if (hasCardField()) {
1003
1260
  throw makeError3(
1004
- import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
1261
+ import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT,
1005
1262
  "Combined card and split card fields are mutually exclusive; split card fields already exist"
1006
1263
  );
1007
1264
  }
@@ -1010,13 +1267,13 @@ var CheckoutInstance = class {
1010
1267
  if (CARD_FIELD_TYPES.includes(type)) {
1011
1268
  if (has("card")) {
1012
1269
  throw makeError3(
1013
- import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
1270
+ import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT,
1014
1271
  "Split card fields and combined card are mutually exclusive; a combined card already exists"
1015
1272
  );
1016
1273
  }
1017
1274
  if (has(type)) {
1018
1275
  throw makeError3(
1019
- import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
1276
+ import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT,
1020
1277
  `A split card field of type ${type} already exists`
1021
1278
  );
1022
1279
  }
@@ -1026,7 +1283,7 @@ var CheckoutInstance = class {
1026
1283
  const mode = options?.mode;
1027
1284
  if (mode && existing.some((e) => e.type === "address" && e.mode === mode)) {
1028
1285
  throw makeError3(
1029
- import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
1286
+ import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT,
1030
1287
  `An address Element with mode=${mode} already exists`
1031
1288
  );
1032
1289
  }
@@ -1034,7 +1291,7 @@ var CheckoutInstance = class {
1034
1291
  }
1035
1292
  if (type === "expressCheckout") {
1036
1293
  if (has("expressCheckout")) {
1037
- throw makeError3(import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT, "An expressCheckout Element already exists");
1294
+ throw makeError3(import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT, "An expressCheckout Element already exists");
1038
1295
  }
1039
1296
  return;
1040
1297
  }
@@ -1067,29 +1324,35 @@ var CheckoutInstance = class {
1067
1324
  if (evt.operationId !== pending.operationId) {
1068
1325
  return;
1069
1326
  }
1070
- if (!evt.outcome) {
1327
+ const outcome = evt.outcome;
1328
+ if (!outcome) {
1329
+ return;
1330
+ }
1331
+ if (outcome.status === "pending") {
1332
+ pending.lastPendingTxnId = outcome.txnId ?? pending.lastPendingTxnId;
1333
+ return;
1334
+ }
1335
+ if (outcome.status !== "succeeded" && outcome.status !== "failed" && outcome.status !== "canceled") {
1071
1336
  return;
1072
1337
  }
1073
1338
  this.pendingConfirm = null;
1074
- pending.resolve(evt.outcome);
1339
+ this.clearWatchdog(pending);
1340
+ if (!pending.settled) {
1341
+ pending.settled = true;
1342
+ pending.resolve(outcome);
1343
+ }
1075
1344
  }
1076
- };
1077
-
1078
- // src/config/env.ts
1079
- var HOST_ORIGINS = {
1080
- dev: "https://checkout.sunbay-dev.com",
1081
- test: "https://checkout.sunbay-uat.us",
1082
- prod: "https://checkout.sunbay.us"
1083
- };
1084
- function resolveHostOrigin(env = "prod", override) {
1085
- if (override) {
1086
- return override;
1345
+ /** Clear a pending confirm's watchdog timer (idempotent). */
1346
+ clearWatchdog(entry) {
1347
+ if (entry.watchdog !== null) {
1348
+ clearTimeout(entry.watchdog);
1349
+ entry.watchdog = null;
1350
+ }
1087
1351
  }
1088
- return HOST_ORIGINS[env];
1089
- }
1352
+ };
1090
1353
 
1091
1354
  // src/createCheckout.ts
1092
- var import_checkout_sdk_protocol5 = require("@sunbay/checkout-sdk-protocol");
1355
+ var import_checkout_sdk_protocol6 = require("@sunbay/checkout-sdk-protocol");
1093
1356
  var HANDSHAKE_TIMEOUT_MS = 15e3;
1094
1357
  function genId3(prefix) {
1095
1358
  const rand = Math.random().toString(36).slice(2);
@@ -1105,6 +1368,9 @@ function makeError4(code, message) {
1105
1368
  }
1106
1369
  var defaultTransportFactory = ({ checkoutId, hostOrigin }) => new MainFrameTransport({ checkoutId, hostOrigin });
1107
1370
  async function createCheckout(opts) {
1371
+ if (typeof opts.checkoutClientSecret !== "string" || opts.checkoutClientSecret.trim() === "") {
1372
+ throw makeError4(import_checkout_sdk_protocol6.ErrorCode.INVALID_OPTIONS, "checkoutClientSecret is required");
1373
+ }
1108
1374
  const checkoutId = genId3("co");
1109
1375
  const hostOrigin = resolveHostOrigin(opts.env, opts.hostOrigin);
1110
1376
  const factory = opts.__transportFactory ?? defaultTransportFactory;
@@ -1117,16 +1383,17 @@ async function createCheckout(opts) {
1117
1383
  transport.destroy();
1118
1384
  throw err;
1119
1385
  }
1120
- if (!hello.supportedMajorVersions.includes(import_checkout_sdk_protocol5.PROTOCOL_MAJOR)) {
1386
+ if (!hello.supportedMajorVersions.includes(import_checkout_sdk_protocol6.PROTOCOL_MAJOR)) {
1121
1387
  transport.destroy();
1122
1388
  throw makeError4(
1123
- import_checkout_sdk_protocol5.ErrorCode.PROTOCOL_UNSUPPORTED,
1124
- `No common major protocol version: SDK=${import_checkout_sdk_protocol5.PROTOCOL_MAJOR}, runtime=${JSON.stringify(hello.supportedMajorVersions)}`
1389
+ import_checkout_sdk_protocol6.ErrorCode.PROTOCOL_UNSUPPORTED,
1390
+ `No common major protocol version: SDK=${import_checkout_sdk_protocol6.PROTOCOL_MAJOR}, runtime=${JSON.stringify(hello.supportedMajorVersions)}`
1125
1391
  );
1126
1392
  }
1127
1393
  transport.setRuntimeId(hello.runtimeId);
1128
1394
  const initReq = {
1129
1395
  sessionId: opts.sessionId,
1396
+ checkoutClientSecret: opts.checkoutClientSecret,
1130
1397
  locale: opts.locale,
1131
1398
  appearance: opts.appearance,
1132
1399
  paymentMethods: opts.paymentMethods
@@ -1156,10 +1423,10 @@ function waitForHello(transport) {
1156
1423
  return;
1157
1424
  }
1158
1425
  settled = true;
1159
- reject(makeError4(import_checkout_sdk_protocol5.ErrorCode.RUNTIME_LOAD_FAILED, "Timed out waiting for hosted runtime handshake"));
1426
+ reject(makeError4(import_checkout_sdk_protocol6.ErrorCode.RUNTIME_LOAD_FAILED, "Timed out waiting for hosted runtime handshake"));
1160
1427
  }, HANDSHAKE_TIMEOUT_MS);
1161
1428
  transport.onHello((raw) => {
1162
- if (settled) {
1429
+ if (settled || !isValidRuntimeHello(raw)) {
1163
1430
  return;
1164
1431
  }
1165
1432
  settled = true;
@@ -1170,12 +1437,12 @@ function waitForHello(transport) {
1170
1437
  }
1171
1438
 
1172
1439
  // src/index.ts
1173
- var import_checkout_sdk_protocol6 = require("@sunbay/checkout-sdk-protocol");
1440
+ var import_checkout_sdk_protocol7 = require("@sunbay/checkout-sdk-protocol");
1174
1441
  if (typeof window !== "undefined") {
1175
1442
  const w = window;
1176
1443
  w.SunbayCheckout = { ...w.SunbayCheckout ?? {}, createCheckout };
1177
1444
  }
1178
- var version = true ? "0.0.5" : "0.0.0";
1445
+ var version = true ? "0.0.7" : "0.0.0";
1179
1446
  // Annotate the CommonJS export names for ESM import in node:
1180
1447
  0 && (module.exports = {
1181
1448
  CheckoutElement,