@sunbay/checkout-sdk-js 0.0.4 → 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";
@@ -447,6 +531,10 @@ var CheckoutElement = class _CheckoutElement {
447
531
  iframe.src = this.resolveSrc();
448
532
  iframe.title = `sunbay-checkout-${this.type}`;
449
533
  iframe.setAttribute("data-element-id", this.elementId);
534
+ iframe.setAttribute(
535
+ "allow",
536
+ `payment 'self' ${this.hostOrigin}; publickey-credentials-get 'self' ${this.hostOrigin}`
537
+ );
450
538
  iframe.style.border = "0";
451
539
  iframe.style.width = "100%";
452
540
  iframe.style.display = "block";
@@ -454,8 +542,18 @@ var CheckoutElement = class _CheckoutElement {
454
542
  container.appendChild(iframe);
455
543
  this.iframe = iframe;
456
544
  this.installResizeListener();
545
+ const requested = opts?.timeoutMs;
546
+ const timeoutMs = typeof requested === "number" && Number.isFinite(requested) && requested > 0 ? requested : DEFAULT_MOUNT_TIMEOUT_MS;
457
547
  return new Promise((resolve, reject) => {
548
+ let settled = false;
549
+ let timer = null;
458
550
  const cleanup = () => {
551
+ settled = true;
552
+ if (timer !== null) {
553
+ clearTimeout(timer);
554
+ timer = null;
555
+ }
556
+ this.abortMount = null;
459
557
  if (this.readyHandler) {
460
558
  this.transport.off("elementReady", this.readyHandler);
461
559
  this.readyHandler = null;
@@ -466,7 +564,7 @@ var CheckoutElement = class _CheckoutElement {
466
564
  }
467
565
  };
468
566
  const onReady = (payload) => {
469
- if (!matchesElement(payload, this.elementId)) {
567
+ if (settled || !matchesElement(payload, this.elementId)) {
470
568
  return;
471
569
  }
472
570
  cleanup();
@@ -478,16 +576,17 @@ var CheckoutElement = class _CheckoutElement {
478
576
  resolve();
479
577
  };
480
578
  const onLoadError = (payload) => {
481
- if (!matchesElement(payload, this.elementId)) {
579
+ if (settled || !matchesElement(payload, this.elementId)) {
482
580
  return;
483
581
  }
484
582
  cleanup();
485
583
  this.status = "loadError";
486
584
  this.removeIframe();
585
+ this.releaseHostedElement();
487
586
  const err = payload?.error;
488
587
  reject(
489
588
  err ?? makeError2(
490
- import_checkout_sdk_protocol3.ErrorCode.RUNTIME_LOAD_FAILED,
589
+ import_checkout_sdk_protocol4.ErrorCode.RUNTIME_LOAD_FAILED,
491
590
  "Failed to load Element",
492
591
  this.elementId
493
592
  )
@@ -497,18 +596,56 @@ var CheckoutElement = class _CheckoutElement {
497
596
  this.loadErrorHandler = onLoadError;
498
597
  this.transport.on("elementReady", onReady);
499
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);
500
622
  this.transport.request("createElement", {
501
623
  elementId: this.elementId,
502
624
  type: this.type,
503
625
  options: this.options
504
- }).catch((cmdErr) => {
505
- cleanup();
506
- this.status = "loadError";
507
- this.removeIframe();
508
- reject(cmdErr);
509
- });
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
+ );
510
638
  });
511
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
+ }
512
649
  /**
513
650
  * Unmount: send destroyElement, remove the iframe; idempotent; keeps the handle and configuration.
514
651
  *
@@ -520,6 +657,13 @@ var CheckoutElement = class _CheckoutElement {
520
657
  if (this.status !== "ready" && this.status !== "loading") {
521
658
  return;
522
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
+ );
523
667
  try {
524
668
  await this.transport.request("destroyElement", { elementId: this.elementId });
525
669
  } finally {
@@ -535,6 +679,14 @@ var CheckoutElement = class _CheckoutElement {
535
679
  if (this.status === "destroyed") {
536
680
  return;
537
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
+ );
538
690
  if (this.readyHandler) {
539
691
  this.transport.off("elementReady", this.readyHandler);
540
692
  this.readyHandler = null;
@@ -547,9 +699,23 @@ var CheckoutElement = class _CheckoutElement {
547
699
  this.transport.off("expressAvailabilityChange", this.availabilityHandler);
548
700
  this.availabilityHandler = null;
549
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();
550
708
  this.removeIframe();
551
709
  this.container = null;
552
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
+ }
553
719
  this.onDestroy?.(this.elementId);
554
720
  }
555
721
  /**
@@ -579,7 +745,24 @@ var CheckoutElement = class _CheckoutElement {
579
745
  */
580
746
  on(event, handler) {
581
747
  this.assertAlive();
582
- 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);
583
766
  }
584
767
  /**
585
768
  * Unregister an event handler (still safe to call after destruction).
@@ -588,7 +771,13 @@ var CheckoutElement = class _CheckoutElement {
588
771
  * @param handler - The previously registered callback.
589
772
  */
590
773
  off(event, handler) {
591
- 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);
592
781
  }
593
782
  /** Install input-class action methods (automatically called after construction). */
594
783
  installInputActions() {
@@ -629,7 +818,7 @@ var CheckoutElement = class _CheckoutElement {
629
818
  /** Throw INSTANCE_DESTROYED if already destroyed. */
630
819
  assertAlive() {
631
820
  if (this.status === "destroyed") {
632
- 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);
633
822
  }
634
823
  }
635
824
  /** Resolve the mount container (the selector must uniquely match a single element). */
@@ -645,7 +834,7 @@ var CheckoutElement = class _CheckoutElement {
645
834
  return node instanceof HTMLElement ? node : null;
646
835
  }
647
836
  /**
648
- * 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
649
838
  * checkoutId and elementId; if an initial colorScheme is provided, append `&colorScheme=<value>`
650
839
  * (no flash on the first frame); if the initial appearance contains variables or rules, append
651
840
  * `&appearance=<encodeURIComponent(JSON.stringify(appearance))>` (takes effect on the first
@@ -677,7 +866,7 @@ var CheckoutElement = class _CheckoutElement {
677
866
  if (this.type === "expressCheckout") {
678
867
  query += this.resolveExpressQuery();
679
868
  }
680
- return `${this.hostOrigin}/sdk/${segment}/${this.type}${query}`;
869
+ return `${runtimeUrl(this.hostOrigin, segment, this.type)}${query}`;
681
870
  }
682
871
  /**
683
872
  * Extract a per-element appearance (from the Element's own options, i.e. the second
@@ -747,7 +936,7 @@ var CheckoutElement = class _CheckoutElement {
747
936
  if (event.origin !== this.hostOrigin) {
748
937
  return;
749
938
  }
750
- if (!(0, import_checkout_sdk_protocol3.isIframeResizeMessage)(event.data)) {
939
+ if (!(0, import_checkout_sdk_protocol4.isIframeResizeMessage)(event.data)) {
751
940
  return;
752
941
  }
753
942
  if (event.data.elementId !== this.elementId) {
@@ -786,7 +975,8 @@ var CheckoutElement = class _CheckoutElement {
786
975
  };
787
976
 
788
977
  // src/CheckoutInstance.ts
789
- 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;
790
980
  var CARD_FIELD_TYPES = ["cardNumber", "cardExpiry", "cardCvc"];
791
981
  function genId2(prefix) {
792
982
  const rand = Math.random().toString(36).slice(2);
@@ -859,34 +1049,100 @@ var CheckoutInstance = class {
859
1049
  return element;
860
1050
  }
861
1051
  /**
862
- * Initiate a payment confirmation. Generates an operationId, sends the confirm command to obtain
863
- * accepted, and the returned Promise is fulfilled by a later paymentResult event with the same
864
- * 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', ...)`.
865
1069
  *
866
- * @param opts - Optional parameters such as billing/shipping address, name, email, returnUrl.
867
- * @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.
868
1082
  * @throws rejects INSTANCE_DESTROYED when destroyed; rejects CHECKOUT_BUSY when in progress.
869
1083
  */
870
1084
  confirm(opts) {
871
1085
  if (this.destroyed) {
872
1086
  return Promise.reject(
873
- 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")
874
1088
  );
875
1089
  }
876
1090
  if (this.pendingConfirm) {
877
1091
  return Promise.reject(
878
- 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")
879
1093
  );
880
1094
  }
1095
+ const { onOperation, resultTimeoutMs, ...rest } = opts ?? {};
881
1096
  const operationId = genId2("op");
882
- 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;
883
1099
  return new Promise((resolve, reject) => {
884
- 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
+ }
885
1127
  this.transport.request("confirm", payload).catch((err) => {
886
- if (this.pendingConfirm && this.pendingConfirm.operationId === operationId) {
887
- 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);
888
1145
  }
889
- reject(err);
890
1146
  });
891
1147
  });
892
1148
  }
@@ -972,10 +1228,15 @@ var CheckoutInstance = class {
972
1228
  this.elements.clear();
973
1229
  this.transport.off("paymentResult", this.paymentResultHandler);
974
1230
  if (this.pendingConfirm) {
975
- this.pendingConfirm.reject(
976
- makeError3(import_checkout_sdk_protocol4.ErrorCode.INSTANCE_DESTROYED, "Checkout instance has been destroyed", "runtime")
977
- );
1231
+ const entry = this.pendingConfirm;
978
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
+ }
979
1240
  }
980
1241
  void Promise.resolve(this.transport.request("destroy", {})).catch(() => void 0);
981
1242
  this.transport.destroy();
@@ -983,7 +1244,7 @@ var CheckoutInstance = class {
983
1244
  /** Throw INSTANCE_DESTROYED if already destroyed. */
984
1245
  assertAlive() {
985
1246
  if (this.destroyed) {
986
- 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");
987
1248
  }
988
1249
  }
989
1250
  /** Mutual-exclusion check: throws ELEMENT_CONFLICT on conflict (derived live from the elements Map, does not mutate the registry). */
@@ -993,11 +1254,11 @@ var CheckoutInstance = class {
993
1254
  const hasCardField = () => existing.some((e) => CARD_FIELD_TYPES.includes(e.type));
994
1255
  if (type === "card") {
995
1256
  if (has("card")) {
996
- 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");
997
1258
  }
998
1259
  if (hasCardField()) {
999
1260
  throw makeError3(
1000
- import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
1261
+ import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT,
1001
1262
  "Combined card and split card fields are mutually exclusive; split card fields already exist"
1002
1263
  );
1003
1264
  }
@@ -1006,13 +1267,13 @@ var CheckoutInstance = class {
1006
1267
  if (CARD_FIELD_TYPES.includes(type)) {
1007
1268
  if (has("card")) {
1008
1269
  throw makeError3(
1009
- import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
1270
+ import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT,
1010
1271
  "Split card fields and combined card are mutually exclusive; a combined card already exists"
1011
1272
  );
1012
1273
  }
1013
1274
  if (has(type)) {
1014
1275
  throw makeError3(
1015
- import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
1276
+ import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT,
1016
1277
  `A split card field of type ${type} already exists`
1017
1278
  );
1018
1279
  }
@@ -1022,7 +1283,7 @@ var CheckoutInstance = class {
1022
1283
  const mode = options?.mode;
1023
1284
  if (mode && existing.some((e) => e.type === "address" && e.mode === mode)) {
1024
1285
  throw makeError3(
1025
- import_checkout_sdk_protocol4.ErrorCode.ELEMENT_CONFLICT,
1286
+ import_checkout_sdk_protocol5.ErrorCode.ELEMENT_CONFLICT,
1026
1287
  `An address Element with mode=${mode} already exists`
1027
1288
  );
1028
1289
  }
@@ -1030,7 +1291,7 @@ var CheckoutInstance = class {
1030
1291
  }
1031
1292
  if (type === "expressCheckout") {
1032
1293
  if (has("expressCheckout")) {
1033
- 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");
1034
1295
  }
1035
1296
  return;
1036
1297
  }
@@ -1063,29 +1324,35 @@ var CheckoutInstance = class {
1063
1324
  if (evt.operationId !== pending.operationId) {
1064
1325
  return;
1065
1326
  }
1066
- 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") {
1067
1336
  return;
1068
1337
  }
1069
1338
  this.pendingConfirm = null;
1070
- pending.resolve(evt.outcome);
1339
+ this.clearWatchdog(pending);
1340
+ if (!pending.settled) {
1341
+ pending.settled = true;
1342
+ pending.resolve(outcome);
1343
+ }
1071
1344
  }
1072
- };
1073
-
1074
- // src/config/env.ts
1075
- var HOST_ORIGINS = {
1076
- dev: "https://checkout.sunbay-dev.com",
1077
- test: "https://checkout.sunbay-uat.us",
1078
- prod: "https://checkout.sunbay.us"
1079
- };
1080
- function resolveHostOrigin(env = "prod", override) {
1081
- if (override) {
1082
- 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
+ }
1083
1351
  }
1084
- return HOST_ORIGINS[env];
1085
- }
1352
+ };
1086
1353
 
1087
1354
  // src/createCheckout.ts
1088
- var import_checkout_sdk_protocol5 = require("@sunbay/checkout-sdk-protocol");
1355
+ var import_checkout_sdk_protocol6 = require("@sunbay/checkout-sdk-protocol");
1089
1356
  var HANDSHAKE_TIMEOUT_MS = 15e3;
1090
1357
  function genId3(prefix) {
1091
1358
  const rand = Math.random().toString(36).slice(2);
@@ -1101,6 +1368,9 @@ function makeError4(code, message) {
1101
1368
  }
1102
1369
  var defaultTransportFactory = ({ checkoutId, hostOrigin }) => new MainFrameTransport({ checkoutId, hostOrigin });
1103
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
+ }
1104
1374
  const checkoutId = genId3("co");
1105
1375
  const hostOrigin = resolveHostOrigin(opts.env, opts.hostOrigin);
1106
1376
  const factory = opts.__transportFactory ?? defaultTransportFactory;
@@ -1113,16 +1383,17 @@ async function createCheckout(opts) {
1113
1383
  transport.destroy();
1114
1384
  throw err;
1115
1385
  }
1116
- if (!hello.supportedMajorVersions.includes(import_checkout_sdk_protocol5.PROTOCOL_MAJOR)) {
1386
+ if (!hello.supportedMajorVersions.includes(import_checkout_sdk_protocol6.PROTOCOL_MAJOR)) {
1117
1387
  transport.destroy();
1118
1388
  throw makeError4(
1119
- import_checkout_sdk_protocol5.ErrorCode.PROTOCOL_UNSUPPORTED,
1120
- `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)}`
1121
1391
  );
1122
1392
  }
1123
1393
  transport.setRuntimeId(hello.runtimeId);
1124
1394
  const initReq = {
1125
1395
  sessionId: opts.sessionId,
1396
+ checkoutClientSecret: opts.checkoutClientSecret,
1126
1397
  locale: opts.locale,
1127
1398
  appearance: opts.appearance,
1128
1399
  paymentMethods: opts.paymentMethods
@@ -1152,10 +1423,10 @@ function waitForHello(transport) {
1152
1423
  return;
1153
1424
  }
1154
1425
  settled = true;
1155
- 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"));
1156
1427
  }, HANDSHAKE_TIMEOUT_MS);
1157
1428
  transport.onHello((raw) => {
1158
- if (settled) {
1429
+ if (settled || !isValidRuntimeHello(raw)) {
1159
1430
  return;
1160
1431
  }
1161
1432
  settled = true;
@@ -1166,12 +1437,12 @@ function waitForHello(transport) {
1166
1437
  }
1167
1438
 
1168
1439
  // src/index.ts
1169
- var import_checkout_sdk_protocol6 = require("@sunbay/checkout-sdk-protocol");
1440
+ var import_checkout_sdk_protocol7 = require("@sunbay/checkout-sdk-protocol");
1170
1441
  if (typeof window !== "undefined") {
1171
1442
  const w = window;
1172
1443
  w.SunbayCheckout = { ...w.SunbayCheckout ?? {}, createCheckout };
1173
1444
  }
1174
- var version = true ? "0.0.4" : "0.0.0";
1445
+ var version = true ? "0.0.7" : "0.0.0";
1175
1446
  // Annotate the CommonJS export names for ESM import in node:
1176
1447
  0 && (module.exports = {
1177
1448
  CheckoutElement,