@funnelfox/billing 0.9.3-feat-defer-session-on-interaction.34 → 0.10.0

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.
@@ -117,6 +117,8 @@ class APIError extends FunnefoxSDKError {
117
117
  this.errorType = options.errorType || null;
118
118
  this.requestId = options.requestId || null;
119
119
  this.response = options.response || null;
120
+ this.declineCode = options.declineCode || null;
121
+ this.declineCodeSource = options.declineCodeSource || null;
120
122
  }
121
123
  }
122
124
  class PrimerError extends FunnefoxSDKError {
@@ -321,6 +323,48 @@ async function loadPrimerSDK(version) {
321
323
  /**
322
324
  * @fileoverview Helper utilities for Funnefox SDK
323
325
  */
326
+ // Mirrors Stripe Elements: a card number that can never become valid is reported while the buyer
327
+ // types, an incomplete value only after they leave the field, and an empty one only after a submit
328
+ // attempt. Primer reports every error on every keystroke, even for fields the buyer has not reached
329
+ // yet, and its expiry codes cannot tell a typo from a half-typed date ("1" is already
330
+ // expiryYearInvalid, "01/2" is cardExpired), so expiry errors wait for the buyer to leave the field.
331
+ const HOSTED_INPUT_ERRORS_SHOWN_WHILE_TYPING = new Set(['cardInvalid']);
332
+ const HOSTED_INPUT_ERRORS_FOR_EMPTY_FIELD = new Set([
333
+ 'cardRequired',
334
+ 'expiryRequired',
335
+ 'cvvRequired',
336
+ ]);
337
+ function getVisibleHostedInputError(input) {
338
+ if (!input.error) {
339
+ return null;
340
+ }
341
+ if (input.errorCode &&
342
+ HOSTED_INPUT_ERRORS_SHOWN_WHILE_TYPING.has(input.errorCode)) {
343
+ return input.error;
344
+ }
345
+ if (input.active) {
346
+ return null;
347
+ }
348
+ if (input.submitted) {
349
+ return input.error;
350
+ }
351
+ if (input.errorCode &&
352
+ HOSTED_INPUT_ERRORS_FOR_EMPTY_FIELD.has(input.errorCode)) {
353
+ return null;
354
+ }
355
+ return input.touched ? input.error : null;
356
+ }
357
+ function resolveTaxDisplay(source) {
358
+ const taxBehavior = source.tax_behavior ??
359
+ ((source.tax_amount ?? 0) > 0 ? 'exclusive' : undefined);
360
+ if (taxBehavior === 'inclusive') {
361
+ return { taxBehavior, taxAmount: source.tax_inclusive_amount ?? 0 };
362
+ }
363
+ if (taxBehavior === 'exclusive') {
364
+ return { taxBehavior, taxAmount: source.tax_amount ?? 0 };
365
+ }
366
+ return { taxAmount: 0 };
367
+ }
324
368
  function merge(...objects) {
325
369
  const result = {};
326
370
  for (const obj of objects) {
@@ -489,7 +533,7 @@ var PaymentMethod;
489
533
  /**
490
534
  * @fileoverview Constants for Funnefox SDK
491
535
  */
492
- const SDK_VERSION = '0.9.3-feat-defer-session-on-interaction.34';
536
+ const SDK_VERSION = '0.10.0';
493
537
  const DEFAULTS = {
494
538
  BASE_URL: 'https://billing.funnelfox.com',
495
539
  REGION: 'default',
@@ -626,141 +670,6 @@ function requireString(value, fieldName) {
626
670
  return true;
627
671
  }
628
672
 
629
- /**
630
- * @fileoverview Support for Apple's official <apple-pay-button> custom element.
631
- *
632
- * Primer's checkout-web v2 renders the Apple Pay button through the CSS
633
- * approach (-webkit-appearance: -apple-pay-button), and WebKit only accepts
634
- * the 7 legacy values for -apple-pay-button-type. Newer types such as
635
- * 'continue' are silently dropped and fall back to 'plain' (verified in
636
- * Safari 26 on macOS and iOS — see PRD-1426).
637
- *
638
- * Apple's official custom element supports the full set of button types, so
639
- * for "native-only" types we overlay it on top of the (visually hidden)
640
- * Primer button and forward clicks, keeping Primer's payment flow untouched.
641
- */
642
- const APPLE_PAY_SDK_URL = 'https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js';
643
- /** How long to wait for the <apple-pay-button> element definition before
644
- * giving up and falling back to Primer's own button. */
645
- const ELEMENT_DEFINITION_TIMEOUT_MS = 4000;
646
- /**
647
- * Button types WebKit can render through Primer's CSS approach.
648
- * Everything outside this list requires the native <apple-pay-button> element.
649
- */
650
- const CSS_RENDERABLE_APPLE_PAY_TYPES = [
651
- 'plain',
652
- 'buy',
653
- 'set-up',
654
- 'donate',
655
- 'check-out',
656
- 'book',
657
- 'subscribe',
658
- ];
659
- /**
660
- * Returns true when the requested Apple Pay buttonType can only be rendered
661
- * with Apple's native <apple-pay-button> element.
662
- */
663
- function isNativeOnlyApplePayButtonType(type) {
664
- return !!type && !CSS_RENDERABLE_APPLE_PAY_TYPES.includes(type);
665
- }
666
- /**
667
- * Loads Apple's apple-pay-sdk.js (defines the <apple-pay-button> custom
668
- * element). Resolves to true when the element is available.
669
- */
670
- async function loadApplePayButtonElement() {
671
- if (typeof window === 'undefined' || !window.customElements) {
672
- return false;
673
- }
674
- if (window.customElements.get('apple-pay-button')) {
675
- return true;
676
- }
677
- try {
678
- await loadScript$1({
679
- src: APPLE_PAY_SDK_URL,
680
- crossOrigin: 'anonymous',
681
- appendTo: 'head',
682
- });
683
- // Never hang on a script that loaded but did not define the element —
684
- // fall back to Primer's own button instead.
685
- const defined = window.customElements
686
- .whenDefined('apple-pay-button')
687
- .then(() => true);
688
- const timeout = new Promise(resolve => {
689
- setTimeout(() => resolve(false), ELEMENT_DEFINITION_TIMEOUT_MS);
690
- });
691
- return await Promise.race([defined, timeout]);
692
- }
693
- catch {
694
- return false;
695
- }
696
- }
697
- function createNativeApplePayElement(options) {
698
- const native = document.createElement('apple-pay-button');
699
- native.setAttribute('type', options.buttonType);
700
- native.setAttribute('buttonstyle', options.buttonStyle || 'black');
701
- native.setAttribute('locale', (typeof navigator !== 'undefined' && navigator.language) || 'en-US');
702
- native.style.cssText = [
703
- 'position:absolute',
704
- 'inset:0',
705
- 'width:100%',
706
- 'height:100%',
707
- '--apple-pay-button-width:100%',
708
- '--apple-pay-button-height:100%',
709
- '--apple-pay-button-border-radius:28px',
710
- 'display:block',
711
- 'cursor:pointer',
712
- 'z-index:1',
713
- ].join(';');
714
- return native;
715
- }
716
- /**
717
- * Renders Apple's native <apple-pay-button> stretched over `wrapper` and
718
- * forwards clicks to the Primer-rendered <button> inside it. The synchronous
719
- * forwarded click preserves the user activation required by ApplePaySession.
720
- *
721
- * Returns the overlay element, or null when the Apple Pay SDK could not be
722
- * loaded (callers should keep Primer's own button visible as a fallback).
723
- */
724
- async function overlayNativeApplePayButton(wrapper, options) {
725
- const available = await loadApplePayButtonElement();
726
- if (!available) {
727
- return null;
728
- }
729
- // The overlay is only safe when Primer's own clickable button is present —
730
- // otherwise there is nothing to forward the click to.
731
- if (!wrapper.querySelector('button')) {
732
- return null;
733
- }
734
- const native = createNativeApplePayElement(options);
735
- wrapper.style.position = 'relative';
736
- native.addEventListener('click', () => {
737
- const primerButton = wrapper.querySelector('button');
738
- primerButton?.click();
739
- });
740
- wrapper.appendChild(native);
741
- return native;
742
- }
743
- /**
744
- * Renders the native button with no Primer button behind it, for the deferred
745
- * flow: the visitor sees the real Apple Pay button immediately while the
746
- * client session is still un-created. `onActivate` fires on tap so the caller
747
- * can start (or await) initialization.
748
- *
749
- * Returns null when Apple's SDK is unavailable — callers must fall back to
750
- * creating the session eagerly so a button of some kind is always rendered.
751
- */
752
- async function renderPlaceholderApplePayButton(wrapper, options) {
753
- const available = await loadApplePayButtonElement();
754
- if (!available) {
755
- return null;
756
- }
757
- const native = createNativeApplePayElement(options);
758
- wrapper.style.position = 'relative';
759
- native.addEventListener('click', options.onActivate);
760
- wrapper.appendChild(native);
761
- return native;
762
- }
763
-
764
673
  /**
765
674
  * @fileoverview Primer SDK integration wrapper
766
675
  */
@@ -799,7 +708,6 @@ class PrimerWrapper {
799
708
  }
800
709
  async createHeadlessCheckout(clientToken, options, method) {
801
710
  await this.ensurePrimerLoaded();
802
- this.applePayOptions = options.applePay;
803
711
  this.currentHeadless = PrimerWrapper.headlessManager.getOrCreate(clientToken, options, method);
804
712
  return this.currentHeadless;
805
713
  }
@@ -846,53 +754,16 @@ class PrimerWrapper {
846
754
  }
847
755
  htmlNode.appendChild(wrapper);
848
756
  /* end hack */
849
- /* PRD-1426: WebKit cannot render newer Apple Pay button types (e.g.
850
- * 'continue') through the CSS approach Primer v2 uses. For those types
851
- * we overlay Apple's official <apple-pay-button> element on top of the
852
- * visually hidden Primer button and forward clicks, keeping Primer's
853
- * payment flow untouched. The Primer button is hidden BEFORE it renders
854
- * to avoid a flash of the plain button; if the Apple SDK fails to load,
855
- * the rule is removed and Primer's own button stays visible (graceful
856
- * fallback to 'plain'). */
857
- const applePayConfig = this.applePayOptions;
858
- const nativeButtonType = allowedPaymentMethod === PaymentMethod.APPLE_PAY &&
859
- applePayConfig?.buttonType &&
860
- isNativeOnlyApplePayButtonType(applePayConfig.buttonType)
861
- ? applePayConfig.buttonType
862
- : null;
863
- let hideRuleIndex = null;
864
- if (nativeButtonType && sheet) {
865
- hideRuleIndex = sheet.insertRule(`
866
- .${wrapper.className} > button {
867
- opacity: 0 !important;
868
- }
869
- `);
870
- }
871
757
  button = pmManager.createButton();
872
758
  await button.render(wrapper, {});
873
- let nativeOverlay = null;
874
- if (nativeButtonType) {
875
- nativeOverlay = await overlayNativeApplePayButton(wrapper, {
876
- buttonType: nativeButtonType,
877
- buttonStyle: applePayConfig?.buttonStyle,
878
- });
879
- if (!nativeOverlay && sheet && hideRuleIndex !== null) {
880
- sheet.deleteRule(hideRuleIndex);
881
- }
882
- }
883
759
  this.destroyCallbacks.push(() => button.clean());
884
760
  onMethodRender(allowedPaymentMethod);
885
761
  return {
886
762
  setDisabled: (disabled) => {
887
763
  button.setDisabled(disabled);
888
- if (nativeOverlay) {
889
- nativeOverlay.style.pointerEvents = disabled ? 'none' : '';
890
- nativeOverlay.style.opacity = disabled ? '0.5' : '';
891
- }
892
764
  },
893
765
  destroy: () => {
894
766
  styleEl.remove();
895
- nativeOverlay?.remove();
896
767
  button.clean();
897
768
  },
898
769
  };
@@ -977,11 +848,22 @@ class PrimerWrapper {
977
848
  ? 'Please enter a postal code'
978
849
  : null;
979
850
  };
851
+ const focusedHostedInputs = new Set();
980
852
  const onHostedInputChange = (name) => (event) => {
981
853
  const input = event;
982
- if (input.submitted) {
983
- dispatchError(name, input.error);
854
+ const justFocused = input.active && !focusedHostedInputs.has(name);
855
+ if (input.active) {
856
+ focusedHostedInputs.add(name);
857
+ }
858
+ else {
859
+ focusedHostedInputs.delete(name);
984
860
  }
861
+ // Primer sends a change on focus before any keystroke; like Stripe, the error the buyer
862
+ // came back to fix stays visible until they start typing.
863
+ if (justFocused) {
864
+ return;
865
+ }
866
+ dispatchError(name, getVisibleHostedInputError(input));
985
867
  };
986
868
  const cardHolderOnChange = async (e) => {
987
869
  pmManager.setCardholderName(e.target.value);
@@ -1240,29 +1122,34 @@ class PrimerWrapper {
1240
1122
  PrimerWrapper.headlessManager = new HeadlessManager();
1241
1123
 
1242
1124
  /**
1243
- * @fileoverview Tags the deferred session request so the warm-up trigger can
1244
- * be measured without adding a single extra network call.
1245
- *
1246
- * The backend already logs every request header, so `X-FF-Warmup` lands in
1247
- * Elasticsearch for free. That gives us, per session actually created:
1248
- * - which signal started it (dwell vs interaction vs a cold tap)
1249
- * - how long after mount it fired
1250
- *
1251
- * Which is what tells us whether the dwell can be lengthened (more savings)
1252
- * or must stay short (cold-tap risk), instead of guessing at an interaction
1253
- * rate nobody has measured.
1125
+ * @fileoverview Normalization of payment failure errors
1254
1126
  */
1255
- const WARMUP_HEADER = 'X-FF-Warmup';
1256
- let pendingTag = null;
1257
- /** Records the trigger for the session request that is about to be sent. */
1258
- function setWarmupTag(trigger, msSinceMount) {
1259
- pendingTag = `${trigger};${Math.max(0, Math.round(msSinceMount))}`;
1127
+ const STRIPE_CARD_ERROR = 'card_error';
1128
+ function declineCodeFromStripeError(error) {
1129
+ const { type, code } = error;
1130
+ if (type !== STRIPE_CARD_ERROR || typeof code !== 'string' || !code) {
1131
+ return null;
1132
+ }
1133
+ return code.toUpperCase();
1260
1134
  }
1261
- /** Consumes the tag — it describes one request only. */
1262
- function takeWarmupTag() {
1263
- const tag = pendingTag;
1264
- pendingTag = null;
1265
- return tag;
1135
+ function toPaymentFailure(error) {
1136
+ const failure = new Error(error?.message || 'Payment processing failed');
1137
+ if (error instanceof APIError) {
1138
+ if (error.declineCode) {
1139
+ failure.declineCode = error.declineCode;
1140
+ }
1141
+ if (error.declineCodeSource) {
1142
+ failure.declineCodeSource = error.declineCodeSource;
1143
+ }
1144
+ }
1145
+ else if (error instanceof Error) {
1146
+ const declineCode = declineCodeFromStripeError(error);
1147
+ if (declineCode) {
1148
+ failure.declineCode = declineCode;
1149
+ failure.declineCodeSource = 'stripe';
1150
+ }
1151
+ }
1152
+ return failure;
1266
1153
  }
1267
1154
 
1268
1155
  /**
@@ -1282,7 +1169,6 @@ class APIClient {
1282
1169
  headers: {
1283
1170
  'Content-Type': 'application/json',
1284
1171
  'X-SDK-Version': SDK_VERSION,
1285
- ...warmupHeader(),
1286
1172
  ...(options.headers || {}),
1287
1173
  },
1288
1174
  ...options,
@@ -1463,7 +1349,11 @@ class APIClient {
1463
1349
  status: 'succeeded',
1464
1350
  };
1465
1351
  case 'failed':
1466
- throw new APIError(data.failed_message_for_user || 'Payment failed', null, { response });
1352
+ throw new APIError(data.failed_message_for_user || 'Payment failed', null, {
1353
+ response,
1354
+ declineCode: data.decline_code,
1355
+ declineCodeSource: data.decline_code_source,
1356
+ });
1467
1357
  case 'cancelled':
1468
1358
  throw new APIError('Payment was cancelled by user', null, {
1469
1359
  response,
@@ -1497,10 +1387,6 @@ class APIClient {
1497
1387
  }));
1498
1388
  }
1499
1389
  }
1500
- function warmupHeader() {
1501
- const tag = takeWarmupTag();
1502
- return tag ? { [WARMUP_HEADER]: tag } : {};
1503
- }
1504
1390
 
1505
1391
  class SessionService {
1506
1392
  constructor() {
@@ -1583,96 +1469,6 @@ const hideLoader = () => {
1583
1469
  }
1584
1470
  };
1585
1471
 
1586
- /**
1587
- * @fileoverview Decides when a deferred client session should be created.
1588
- *
1589
- * Fires on whichever comes first: the visitor's first interaction, or a short
1590
- * dwell once the page is actually visible. The dwell is what makes the
1591
- * deferral safe — ApplePaySession must be constructed inside the tap gesture,
1592
- * so the session has to exist *before* the first tap. A human cannot read a
1593
- * price and tap in under ~800ms, whereas prerenders, background tabs, crawlers
1594
- * and instant bounces never reach the dwell at all and so never cost a
1595
- * session (nor the order row behind it).
1596
- */
1597
- const INTERACTION_EVENTS = [
1598
- 'pointerdown',
1599
- 'touchstart',
1600
- 'keydown',
1601
- 'wheel',
1602
- 'scroll',
1603
- ];
1604
- /** Long enough to filter prerenders and instant bounces, far shorter than
1605
- * any realistic time-to-tap on a paywall. */
1606
- const DEFAULT_WARMUP_DWELL_MS = 800;
1607
- /** True while the page is prerendering or not visible to the user. */
1608
- function isPageHidden() {
1609
- if (typeof document === 'undefined') {
1610
- return true;
1611
- }
1612
- if (document.prerendering) {
1613
- return true;
1614
- }
1615
- return document.visibilityState === 'hidden';
1616
- }
1617
- /**
1618
- * Invokes `handler` once — on first interaction, or after `dwellMs` of visible
1619
- * time, whichever happens first. Returns a cleanup for the un-fired case.
1620
- */
1621
- function onSessionWarmup(handler, dwellMs = DEFAULT_WARMUP_DWELL_MS) {
1622
- if (typeof document === 'undefined') {
1623
- return () => { };
1624
- }
1625
- let fired = false;
1626
- let timer;
1627
- const cleanup = () => {
1628
- if (timer !== undefined) {
1629
- clearTimeout(timer);
1630
- timer = undefined;
1631
- }
1632
- for (const event of INTERACTION_EVENTS) {
1633
- document.removeEventListener(event, onInteraction, true);
1634
- }
1635
- document.removeEventListener('visibilitychange', onVisibilityChange);
1636
- document.removeEventListener('prerenderingchange', onVisibilityChange);
1637
- };
1638
- const fire = (source) => {
1639
- if (fired) {
1640
- return;
1641
- }
1642
- fired = true;
1643
- cleanup();
1644
- handler(source);
1645
- };
1646
- function onInteraction() {
1647
- if (!isPageHidden()) {
1648
- fire('interaction');
1649
- }
1650
- }
1651
- function startDwell() {
1652
- if (fired || timer !== undefined) {
1653
- return;
1654
- }
1655
- timer = setTimeout(() => fire('dwell'), dwellMs);
1656
- }
1657
- function onVisibilityChange() {
1658
- if (!isPageHidden()) {
1659
- startDwell();
1660
- }
1661
- }
1662
- for (const event of INTERACTION_EVENTS) {
1663
- document.addEventListener(event, onInteraction, {
1664
- capture: true,
1665
- passive: true,
1666
- });
1667
- }
1668
- document.addEventListener('visibilitychange', onVisibilityChange);
1669
- document.addEventListener('prerenderingchange', onVisibilityChange);
1670
- if (!isPageHidden()) {
1671
- startDwell();
1672
- }
1673
- return cleanup;
1674
- }
1675
-
1676
1472
  var V3_URL = 'https://js.stripe.com/v3';
1677
1473
  var V3_URL_REGEX = /^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;
1678
1474
  var EXISTING_SCRIPT_MESSAGE = 'loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used';
@@ -2158,8 +1954,8 @@ class CheckoutInstance extends EventEmitter {
2158
1954
  }
2159
1955
  return {
2160
1956
  amountTotal: data.amount_total,
2161
- taxAmount: data.tax_amount ?? 0,
2162
1957
  currency: data.currency ?? '',
1958
+ ...resolveTaxDisplay(data),
2163
1959
  };
2164
1960
  };
2165
1961
  this.emitTaxInfo = (info) => {
@@ -2192,8 +1988,8 @@ class CheckoutInstance extends EventEmitter {
2192
1988
  }
2193
1989
  this.emitTaxInfo({
2194
1990
  amountTotal: tax.amount_total,
2195
- taxAmount: tax.tax_amount,
2196
1991
  currency: tax.currency,
1992
+ ...resolveTaxDisplay(tax),
2197
1993
  });
2198
1994
  }
2199
1995
  catch (err) {
@@ -2212,6 +2008,7 @@ class CheckoutInstance extends EventEmitter {
2212
2008
  if (this.taxRecalcDebounce) {
2213
2009
  clearTimeout(this.taxRecalcDebounce);
2214
2010
  }
2011
+ this.checkoutConfig.onTaxPending?.();
2215
2012
  this.emit(EVENTS.TAX_PENDING);
2216
2013
  this.taxRecalcDebounce = setTimeout(this.runTaxRecalc, TAX_RECALC_DEBOUNCE_MS);
2217
2014
  };
@@ -2269,8 +2066,8 @@ class CheckoutInstance extends EventEmitter {
2269
2066
  }
2270
2067
  catch (error) {
2271
2068
  this._setState('error');
2272
- this.emit(EVENTS.PURCHASE_FAILURE, new Error(error.message || 'Payment processing failed'));
2273
- primerHandler.handleFailure(error.message || 'Payment processing failed');
2069
+ this.emit(EVENTS.PURCHASE_FAILURE, toPaymentFailure(error));
2070
+ primerHandler.handleFailure(error?.message || 'Payment processing failed');
2274
2071
  }
2275
2072
  finally {
2276
2073
  this.onLoaderChangeWithRace(false);
@@ -2294,8 +2091,8 @@ class CheckoutInstance extends EventEmitter {
2294
2091
  }
2295
2092
  catch (error) {
2296
2093
  this._setState('error');
2297
- this.emit(EVENTS.PURCHASE_FAILURE, new Error(error.message || 'Payment processing failed'));
2298
- primerHandler.handleFailure(error.message || 'Payment processing failed');
2094
+ this.emit(EVENTS.PURCHASE_FAILURE, toPaymentFailure(error));
2095
+ primerHandler.handleFailure(error?.message || 'Payment processing failed');
2299
2096
  }
2300
2097
  finally {
2301
2098
  this.emit(EVENTS.PURCHASE_COMPLETED);
@@ -2830,98 +2627,6 @@ class CheckoutInstance extends EventEmitter {
2830
2627
  }
2831
2628
  async initMethod(method, element, callbacks) {
2832
2629
  this._ensureNotDestroyed();
2833
- const deferred = await this.initMethodDeferred(method, element, callbacks);
2834
- if (deferred) {
2835
- return deferred;
2836
- }
2837
- return await this.initMethodNow(method, element, callbacks);
2838
- }
2839
- /**
2840
- * Renders Apple's native button immediately and postpones session creation
2841
- * until the visitor interacts. Returns null when deferral does not apply, so
2842
- * the caller falls back to creating the session on mount.
2843
- */
2844
- async initMethodDeferred(method, element, callbacks) {
2845
- const applePay = this.checkoutConfig.applePay;
2846
- const buttonType = applePay?.buttonType;
2847
- if (this.checkoutConfig.sessionCreation !== 'onInteraction' ||
2848
- method !== PaymentMethod.APPLE_PAY ||
2849
- this.isReady() ||
2850
- !buttonType ||
2851
- !isNativeOnlyApplePayButtonType(buttonType)) {
2852
- return null;
2853
- }
2854
- let started = null;
2855
- let real = null;
2856
- let disabled = false;
2857
- let stopWaiting = () => { };
2858
- let placeholder = null;
2859
- const mountedAt = Date.now();
2860
- const start = (trigger) => {
2861
- const fromTap = trigger === 'tap';
2862
- if (!started) {
2863
- setWarmupTag(trigger, Date.now() - mountedAt);
2864
- started = (async () => {
2865
- stopWaiting();
2866
- if (fromTap) {
2867
- callbacks.onLoaderChange?.(true);
2868
- }
2869
- try {
2870
- placeholder?.remove();
2871
- placeholder = null;
2872
- const methodInterface = await this.initMethodNow(method, element, callbacks);
2873
- real = methodInterface;
2874
- if (disabled) {
2875
- methodInterface.setDisabled(true);
2876
- }
2877
- return methodInterface;
2878
- }
2879
- finally {
2880
- if (fromTap) {
2881
- callbacks.onLoaderChange?.(false);
2882
- }
2883
- }
2884
- })();
2885
- }
2886
- return started;
2887
- };
2888
- placeholder = await renderPlaceholderApplePayButton(element, {
2889
- buttonType,
2890
- buttonStyle: applePay?.buttonStyle,
2891
- // Cold tap: the visitor's first interaction is the button itself, so the
2892
- // session cannot exist yet and ApplePaySession would lose the gesture.
2893
- // Start now and let the loader cover the (rare) second tap.
2894
- onActivate: () => void start('tap'),
2895
- });
2896
- if (!placeholder) {
2897
- return null;
2898
- }
2899
- // Free head start: Primer's SDK is a static asset on their CDN, so
2900
- // fetching it now costs no backend call and leaves only the session
2901
- // request to complete before the first tap.
2902
- void loadPrimerSDK().catch(() => { });
2903
- stopWaiting = onSessionWarmup(trigger => void start(trigger));
2904
- return {
2905
- setDisabled: (value) => {
2906
- disabled = value;
2907
- real?.setDisabled(value);
2908
- if (placeholder) {
2909
- placeholder.style.pointerEvents = value ? 'none' : '';
2910
- placeholder.style.opacity = value ? '0.5' : '';
2911
- }
2912
- },
2913
- destroy: async () => {
2914
- stopWaiting();
2915
- placeholder?.remove();
2916
- placeholder = null;
2917
- if (started) {
2918
- await (await started).destroy?.();
2919
- }
2920
- await this.destroy();
2921
- },
2922
- };
2923
- }
2924
- async initMethodNow(method, element, callbacks) {
2925
2630
  if (!this.isReady()) {
2926
2631
  await this.createSession();
2927
2632
  }
@@ -2976,6 +2681,9 @@ class CheckoutInstance extends EventEmitter {
2976
2681
  await this.primerWrapper.initializeHeadlessCheckout(this.clientToken, checkoutOptions, method);
2977
2682
  const methodInterface = await this.primerWrapper.initMethod(method, element, methodOptions);
2978
2683
  this.startUnhandledTelemetry(method);
2684
+ if (this.isTaxEnabled() && !this.lastTaxInfo) {
2685
+ this.emitSessionTaxEstimate();
2686
+ }
2979
2687
  return {
2980
2688
  ...methodInterface,
2981
2689
  destroy: async () => {
@@ -3139,7 +2847,9 @@ async function initMethod(method, element, options) {
3139
2847
  ...DEFAULT_BUTTONS_OPTIONS[PaymentMethod.GOOGLE_PAY],
3140
2848
  ...(options.googlePay || {}),
3141
2849
  },
3142
- sessionCreation: options.sessionCreation,
2850
+ onTaxChange: options.onTaxChange,
2851
+ onTaxError: options.onTaxError,
2852
+ onTaxPending: options.onTaxPending,
3143
2853
  },
3144
2854
  });
3145
2855
  return await checkoutInstance.initMethod(method, element, {
@@ -3316,4 +3026,4 @@ if (typeof window !== 'undefined') {
3316
3026
  }
3317
3027
  console.debug('Billing SDK inited');
3318
3028
 
3319
- export { APIError as A, Billing as B, CheckoutError as C, DEFAULT_BUTTONS_OPTIONS as D, EVENTS as E, FunnefoxSDKError as F, NetworkError as N, PaymentMethod as P, SDK_VERSION as S, ValidationError as V, PrimerError as a, ConfigurationError as b, DEFAULTS as c, CHECKOUT_STATES as d, ERROR_CODES as e, configure as f, createCheckout as g, createClientSession as h, getAvailablePaymentMethods as i, loadStripe as l };
3029
+ export { APIError as A, Billing as B, CheckoutError as C, DEFAULT_BUTTONS_OPTIONS as D, EVENTS as E, FunnefoxSDKError as F, NetworkError as N, PaymentMethod as P, SDK_VERSION as S, ValidationError as V, PrimerError as a, ConfigurationError as b, DEFAULTS as c, CHECKOUT_STATES as d, ERROR_CODES as e, configure as f, createCheckout as g, createClientSession as h, getAvailablePaymentMethods as i, loadStripe as l, resolveTaxDisplay as r, toPaymentFailure as t };