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

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.
@@ -491,7 +491,7 @@ exports.PaymentMethod = void 0;
491
491
  /**
492
492
  * @fileoverview Constants for Funnefox SDK
493
493
  */
494
- const SDK_VERSION = '0.9.1';
494
+ const SDK_VERSION = '0.9.3-feat-defer-session-on-interaction.34';
495
495
  const DEFAULTS = {
496
496
  BASE_URL: 'https://billing.funnelfox.com',
497
497
  REGION: 'default',
@@ -628,6 +628,141 @@ function requireString(value, fieldName) {
628
628
  return true;
629
629
  }
630
630
 
631
+ /**
632
+ * @fileoverview Support for Apple's official <apple-pay-button> custom element.
633
+ *
634
+ * Primer's checkout-web v2 renders the Apple Pay button through the CSS
635
+ * approach (-webkit-appearance: -apple-pay-button), and WebKit only accepts
636
+ * the 7 legacy values for -apple-pay-button-type. Newer types such as
637
+ * 'continue' are silently dropped and fall back to 'plain' (verified in
638
+ * Safari 26 on macOS and iOS — see PRD-1426).
639
+ *
640
+ * Apple's official custom element supports the full set of button types, so
641
+ * for "native-only" types we overlay it on top of the (visually hidden)
642
+ * Primer button and forward clicks, keeping Primer's payment flow untouched.
643
+ */
644
+ const APPLE_PAY_SDK_URL = 'https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js';
645
+ /** How long to wait for the <apple-pay-button> element definition before
646
+ * giving up and falling back to Primer's own button. */
647
+ const ELEMENT_DEFINITION_TIMEOUT_MS = 4000;
648
+ /**
649
+ * Button types WebKit can render through Primer's CSS approach.
650
+ * Everything outside this list requires the native <apple-pay-button> element.
651
+ */
652
+ const CSS_RENDERABLE_APPLE_PAY_TYPES = [
653
+ 'plain',
654
+ 'buy',
655
+ 'set-up',
656
+ 'donate',
657
+ 'check-out',
658
+ 'book',
659
+ 'subscribe',
660
+ ];
661
+ /**
662
+ * Returns true when the requested Apple Pay buttonType can only be rendered
663
+ * with Apple's native <apple-pay-button> element.
664
+ */
665
+ function isNativeOnlyApplePayButtonType(type) {
666
+ return !!type && !CSS_RENDERABLE_APPLE_PAY_TYPES.includes(type);
667
+ }
668
+ /**
669
+ * Loads Apple's apple-pay-sdk.js (defines the <apple-pay-button> custom
670
+ * element). Resolves to true when the element is available.
671
+ */
672
+ async function loadApplePayButtonElement() {
673
+ if (typeof window === 'undefined' || !window.customElements) {
674
+ return false;
675
+ }
676
+ if (window.customElements.get('apple-pay-button')) {
677
+ return true;
678
+ }
679
+ try {
680
+ await loadScript$1({
681
+ src: APPLE_PAY_SDK_URL,
682
+ crossOrigin: 'anonymous',
683
+ appendTo: 'head',
684
+ });
685
+ // Never hang on a script that loaded but did not define the element —
686
+ // fall back to Primer's own button instead.
687
+ const defined = window.customElements
688
+ .whenDefined('apple-pay-button')
689
+ .then(() => true);
690
+ const timeout = new Promise(resolve => {
691
+ setTimeout(() => resolve(false), ELEMENT_DEFINITION_TIMEOUT_MS);
692
+ });
693
+ return await Promise.race([defined, timeout]);
694
+ }
695
+ catch {
696
+ return false;
697
+ }
698
+ }
699
+ function createNativeApplePayElement(options) {
700
+ const native = document.createElement('apple-pay-button');
701
+ native.setAttribute('type', options.buttonType);
702
+ native.setAttribute('buttonstyle', options.buttonStyle || 'black');
703
+ native.setAttribute('locale', (typeof navigator !== 'undefined' && navigator.language) || 'en-US');
704
+ native.style.cssText = [
705
+ 'position:absolute',
706
+ 'inset:0',
707
+ 'width:100%',
708
+ 'height:100%',
709
+ '--apple-pay-button-width:100%',
710
+ '--apple-pay-button-height:100%',
711
+ '--apple-pay-button-border-radius:28px',
712
+ 'display:block',
713
+ 'cursor:pointer',
714
+ 'z-index:1',
715
+ ].join(';');
716
+ return native;
717
+ }
718
+ /**
719
+ * Renders Apple's native <apple-pay-button> stretched over `wrapper` and
720
+ * forwards clicks to the Primer-rendered <button> inside it. The synchronous
721
+ * forwarded click preserves the user activation required by ApplePaySession.
722
+ *
723
+ * Returns the overlay element, or null when the Apple Pay SDK could not be
724
+ * loaded (callers should keep Primer's own button visible as a fallback).
725
+ */
726
+ async function overlayNativeApplePayButton(wrapper, options) {
727
+ const available = await loadApplePayButtonElement();
728
+ if (!available) {
729
+ return null;
730
+ }
731
+ // The overlay is only safe when Primer's own clickable button is present —
732
+ // otherwise there is nothing to forward the click to.
733
+ if (!wrapper.querySelector('button')) {
734
+ return null;
735
+ }
736
+ const native = createNativeApplePayElement(options);
737
+ wrapper.style.position = 'relative';
738
+ native.addEventListener('click', () => {
739
+ const primerButton = wrapper.querySelector('button');
740
+ primerButton?.click();
741
+ });
742
+ wrapper.appendChild(native);
743
+ return native;
744
+ }
745
+ /**
746
+ * Renders the native button with no Primer button behind it, for the deferred
747
+ * flow: the visitor sees the real Apple Pay button immediately while the
748
+ * client session is still un-created. `onActivate` fires on tap so the caller
749
+ * can start (or await) initialization.
750
+ *
751
+ * Returns null when Apple's SDK is unavailable — callers must fall back to
752
+ * creating the session eagerly so a button of some kind is always rendered.
753
+ */
754
+ async function renderPlaceholderApplePayButton(wrapper, options) {
755
+ const available = await loadApplePayButtonElement();
756
+ if (!available) {
757
+ return null;
758
+ }
759
+ const native = createNativeApplePayElement(options);
760
+ wrapper.style.position = 'relative';
761
+ native.addEventListener('click', options.onActivate);
762
+ wrapper.appendChild(native);
763
+ return native;
764
+ }
765
+
631
766
  /**
632
767
  * @fileoverview Primer SDK integration wrapper
633
768
  */
@@ -666,6 +801,7 @@ class PrimerWrapper {
666
801
  }
667
802
  async createHeadlessCheckout(clientToken, options, method) {
668
803
  await this.ensurePrimerLoaded();
804
+ this.applePayOptions = options.applePay;
669
805
  this.currentHeadless = PrimerWrapper.headlessManager.getOrCreate(clientToken, options, method);
670
806
  return this.currentHeadless;
671
807
  }
@@ -712,16 +848,53 @@ class PrimerWrapper {
712
848
  }
713
849
  htmlNode.appendChild(wrapper);
714
850
  /* end hack */
851
+ /* PRD-1426: WebKit cannot render newer Apple Pay button types (e.g.
852
+ * 'continue') through the CSS approach Primer v2 uses. For those types
853
+ * we overlay Apple's official <apple-pay-button> element on top of the
854
+ * visually hidden Primer button and forward clicks, keeping Primer's
855
+ * payment flow untouched. The Primer button is hidden BEFORE it renders
856
+ * to avoid a flash of the plain button; if the Apple SDK fails to load,
857
+ * the rule is removed and Primer's own button stays visible (graceful
858
+ * fallback to 'plain'). */
859
+ const applePayConfig = this.applePayOptions;
860
+ const nativeButtonType = allowedPaymentMethod === exports.PaymentMethod.APPLE_PAY &&
861
+ applePayConfig?.buttonType &&
862
+ isNativeOnlyApplePayButtonType(applePayConfig.buttonType)
863
+ ? applePayConfig.buttonType
864
+ : null;
865
+ let hideRuleIndex = null;
866
+ if (nativeButtonType && sheet) {
867
+ hideRuleIndex = sheet.insertRule(`
868
+ .${wrapper.className} > button {
869
+ opacity: 0 !important;
870
+ }
871
+ `);
872
+ }
715
873
  button = pmManager.createButton();
716
874
  await button.render(wrapper, {});
875
+ let nativeOverlay = null;
876
+ if (nativeButtonType) {
877
+ nativeOverlay = await overlayNativeApplePayButton(wrapper, {
878
+ buttonType: nativeButtonType,
879
+ buttonStyle: applePayConfig?.buttonStyle,
880
+ });
881
+ if (!nativeOverlay && sheet && hideRuleIndex !== null) {
882
+ sheet.deleteRule(hideRuleIndex);
883
+ }
884
+ }
717
885
  this.destroyCallbacks.push(() => button.clean());
718
886
  onMethodRender(allowedPaymentMethod);
719
887
  return {
720
888
  setDisabled: (disabled) => {
721
889
  button.setDisabled(disabled);
890
+ if (nativeOverlay) {
891
+ nativeOverlay.style.pointerEvents = disabled ? 'none' : '';
892
+ nativeOverlay.style.opacity = disabled ? '0.5' : '';
893
+ }
722
894
  },
723
895
  destroy: () => {
724
896
  styleEl.remove();
897
+ nativeOverlay?.remove();
725
898
  button.clean();
726
899
  },
727
900
  };
@@ -1068,6 +1241,32 @@ class PrimerWrapper {
1068
1241
  }
1069
1242
  PrimerWrapper.headlessManager = new HeadlessManager();
1070
1243
 
1244
+ /**
1245
+ * @fileoverview Tags the deferred session request so the warm-up trigger can
1246
+ * be measured without adding a single extra network call.
1247
+ *
1248
+ * The backend already logs every request header, so `X-FF-Warmup` lands in
1249
+ * Elasticsearch for free. That gives us, per session actually created:
1250
+ * - which signal started it (dwell vs interaction vs a cold tap)
1251
+ * - how long after mount it fired
1252
+ *
1253
+ * Which is what tells us whether the dwell can be lengthened (more savings)
1254
+ * or must stay short (cold-tap risk), instead of guessing at an interaction
1255
+ * rate nobody has measured.
1256
+ */
1257
+ const WARMUP_HEADER = 'X-FF-Warmup';
1258
+ let pendingTag = null;
1259
+ /** Records the trigger for the session request that is about to be sent. */
1260
+ function setWarmupTag(trigger, msSinceMount) {
1261
+ pendingTag = `${trigger};${Math.max(0, Math.round(msSinceMount))}`;
1262
+ }
1263
+ /** Consumes the tag — it describes one request only. */
1264
+ function takeWarmupTag() {
1265
+ const tag = pendingTag;
1266
+ pendingTag = null;
1267
+ return tag;
1268
+ }
1269
+
1071
1270
  /**
1072
1271
  * @fileoverview API client for Funnefox backend integration
1073
1272
  */
@@ -1085,6 +1284,7 @@ class APIClient {
1085
1284
  headers: {
1086
1285
  'Content-Type': 'application/json',
1087
1286
  'X-SDK-Version': SDK_VERSION,
1287
+ ...warmupHeader(),
1088
1288
  ...(options.headers || {}),
1089
1289
  },
1090
1290
  ...options,
@@ -1299,6 +1499,10 @@ class APIClient {
1299
1499
  }));
1300
1500
  }
1301
1501
  }
1502
+ function warmupHeader() {
1503
+ const tag = takeWarmupTag();
1504
+ return tag ? { [WARMUP_HEADER]: tag } : {};
1505
+ }
1302
1506
 
1303
1507
  class SessionService {
1304
1508
  constructor() {
@@ -1381,6 +1585,96 @@ const hideLoader = () => {
1381
1585
  }
1382
1586
  };
1383
1587
 
1588
+ /**
1589
+ * @fileoverview Decides when a deferred client session should be created.
1590
+ *
1591
+ * Fires on whichever comes first: the visitor's first interaction, or a short
1592
+ * dwell once the page is actually visible. The dwell is what makes the
1593
+ * deferral safe — ApplePaySession must be constructed inside the tap gesture,
1594
+ * so the session has to exist *before* the first tap. A human cannot read a
1595
+ * price and tap in under ~800ms, whereas prerenders, background tabs, crawlers
1596
+ * and instant bounces never reach the dwell at all and so never cost a
1597
+ * session (nor the order row behind it).
1598
+ */
1599
+ const INTERACTION_EVENTS = [
1600
+ 'pointerdown',
1601
+ 'touchstart',
1602
+ 'keydown',
1603
+ 'wheel',
1604
+ 'scroll',
1605
+ ];
1606
+ /** Long enough to filter prerenders and instant bounces, far shorter than
1607
+ * any realistic time-to-tap on a paywall. */
1608
+ const DEFAULT_WARMUP_DWELL_MS = 800;
1609
+ /** True while the page is prerendering or not visible to the user. */
1610
+ function isPageHidden() {
1611
+ if (typeof document === 'undefined') {
1612
+ return true;
1613
+ }
1614
+ if (document.prerendering) {
1615
+ return true;
1616
+ }
1617
+ return document.visibilityState === 'hidden';
1618
+ }
1619
+ /**
1620
+ * Invokes `handler` once — on first interaction, or after `dwellMs` of visible
1621
+ * time, whichever happens first. Returns a cleanup for the un-fired case.
1622
+ */
1623
+ function onSessionWarmup(handler, dwellMs = DEFAULT_WARMUP_DWELL_MS) {
1624
+ if (typeof document === 'undefined') {
1625
+ return () => { };
1626
+ }
1627
+ let fired = false;
1628
+ let timer;
1629
+ const cleanup = () => {
1630
+ if (timer !== undefined) {
1631
+ clearTimeout(timer);
1632
+ timer = undefined;
1633
+ }
1634
+ for (const event of INTERACTION_EVENTS) {
1635
+ document.removeEventListener(event, onInteraction, true);
1636
+ }
1637
+ document.removeEventListener('visibilitychange', onVisibilityChange);
1638
+ document.removeEventListener('prerenderingchange', onVisibilityChange);
1639
+ };
1640
+ const fire = (source) => {
1641
+ if (fired) {
1642
+ return;
1643
+ }
1644
+ fired = true;
1645
+ cleanup();
1646
+ handler(source);
1647
+ };
1648
+ function onInteraction() {
1649
+ if (!isPageHidden()) {
1650
+ fire('interaction');
1651
+ }
1652
+ }
1653
+ function startDwell() {
1654
+ if (fired || timer !== undefined) {
1655
+ return;
1656
+ }
1657
+ timer = setTimeout(() => fire('dwell'), dwellMs);
1658
+ }
1659
+ function onVisibilityChange() {
1660
+ if (!isPageHidden()) {
1661
+ startDwell();
1662
+ }
1663
+ }
1664
+ for (const event of INTERACTION_EVENTS) {
1665
+ document.addEventListener(event, onInteraction, {
1666
+ capture: true,
1667
+ passive: true,
1668
+ });
1669
+ }
1670
+ document.addEventListener('visibilitychange', onVisibilityChange);
1671
+ document.addEventListener('prerenderingchange', onVisibilityChange);
1672
+ if (!isPageHidden()) {
1673
+ startDwell();
1674
+ }
1675
+ return cleanup;
1676
+ }
1677
+
1384
1678
  var V3_URL = 'https://js.stripe.com/v3';
1385
1679
  var V3_URL_REGEX = /^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;
1386
1680
  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';
@@ -2538,6 +2832,98 @@ class CheckoutInstance extends EventEmitter {
2538
2832
  }
2539
2833
  async initMethod(method, element, callbacks) {
2540
2834
  this._ensureNotDestroyed();
2835
+ const deferred = await this.initMethodDeferred(method, element, callbacks);
2836
+ if (deferred) {
2837
+ return deferred;
2838
+ }
2839
+ return await this.initMethodNow(method, element, callbacks);
2840
+ }
2841
+ /**
2842
+ * Renders Apple's native button immediately and postpones session creation
2843
+ * until the visitor interacts. Returns null when deferral does not apply, so
2844
+ * the caller falls back to creating the session on mount.
2845
+ */
2846
+ async initMethodDeferred(method, element, callbacks) {
2847
+ const applePay = this.checkoutConfig.applePay;
2848
+ const buttonType = applePay?.buttonType;
2849
+ if (this.checkoutConfig.sessionCreation !== 'onInteraction' ||
2850
+ method !== exports.PaymentMethod.APPLE_PAY ||
2851
+ this.isReady() ||
2852
+ !buttonType ||
2853
+ !isNativeOnlyApplePayButtonType(buttonType)) {
2854
+ return null;
2855
+ }
2856
+ let started = null;
2857
+ let real = null;
2858
+ let disabled = false;
2859
+ let stopWaiting = () => { };
2860
+ let placeholder = null;
2861
+ const mountedAt = Date.now();
2862
+ const start = (trigger) => {
2863
+ const fromTap = trigger === 'tap';
2864
+ if (!started) {
2865
+ setWarmupTag(trigger, Date.now() - mountedAt);
2866
+ started = (async () => {
2867
+ stopWaiting();
2868
+ if (fromTap) {
2869
+ callbacks.onLoaderChange?.(true);
2870
+ }
2871
+ try {
2872
+ placeholder?.remove();
2873
+ placeholder = null;
2874
+ const methodInterface = await this.initMethodNow(method, element, callbacks);
2875
+ real = methodInterface;
2876
+ if (disabled) {
2877
+ methodInterface.setDisabled(true);
2878
+ }
2879
+ return methodInterface;
2880
+ }
2881
+ finally {
2882
+ if (fromTap) {
2883
+ callbacks.onLoaderChange?.(false);
2884
+ }
2885
+ }
2886
+ })();
2887
+ }
2888
+ return started;
2889
+ };
2890
+ placeholder = await renderPlaceholderApplePayButton(element, {
2891
+ buttonType,
2892
+ buttonStyle: applePay?.buttonStyle,
2893
+ // Cold tap: the visitor's first interaction is the button itself, so the
2894
+ // session cannot exist yet and ApplePaySession would lose the gesture.
2895
+ // Start now and let the loader cover the (rare) second tap.
2896
+ onActivate: () => void start('tap'),
2897
+ });
2898
+ if (!placeholder) {
2899
+ return null;
2900
+ }
2901
+ // Free head start: Primer's SDK is a static asset on their CDN, so
2902
+ // fetching it now costs no backend call and leaves only the session
2903
+ // request to complete before the first tap.
2904
+ void loadPrimerSDK().catch(() => { });
2905
+ stopWaiting = onSessionWarmup(trigger => void start(trigger));
2906
+ return {
2907
+ setDisabled: (value) => {
2908
+ disabled = value;
2909
+ real?.setDisabled(value);
2910
+ if (placeholder) {
2911
+ placeholder.style.pointerEvents = value ? 'none' : '';
2912
+ placeholder.style.opacity = value ? '0.5' : '';
2913
+ }
2914
+ },
2915
+ destroy: async () => {
2916
+ stopWaiting();
2917
+ placeholder?.remove();
2918
+ placeholder = null;
2919
+ if (started) {
2920
+ await (await started).destroy?.();
2921
+ }
2922
+ await this.destroy();
2923
+ },
2924
+ };
2925
+ }
2926
+ async initMethodNow(method, element, callbacks) {
2541
2927
  if (!this.isReady()) {
2542
2928
  await this.createSession();
2543
2929
  }
@@ -2755,6 +3141,7 @@ async function initMethod(method, element, options) {
2755
3141
  ...DEFAULT_BUTTONS_OPTIONS[exports.PaymentMethod.GOOGLE_PAY],
2756
3142
  ...(options.googlePay || {}),
2757
3143
  },
3144
+ sessionCreation: options.sessionCreation,
2758
3145
  },
2759
3146
  });
2760
3147
  return await checkoutInstance.initMethod(method, element, {