@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.
@@ -489,7 +489,7 @@ var PaymentMethod;
489
489
  /**
490
490
  * @fileoverview Constants for Funnefox SDK
491
491
  */
492
- const SDK_VERSION = '0.9.1';
492
+ const SDK_VERSION = '0.9.3-feat-defer-session-on-interaction.34';
493
493
  const DEFAULTS = {
494
494
  BASE_URL: 'https://billing.funnelfox.com',
495
495
  REGION: 'default',
@@ -626,6 +626,141 @@ function requireString(value, fieldName) {
626
626
  return true;
627
627
  }
628
628
 
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
+
629
764
  /**
630
765
  * @fileoverview Primer SDK integration wrapper
631
766
  */
@@ -664,6 +799,7 @@ class PrimerWrapper {
664
799
  }
665
800
  async createHeadlessCheckout(clientToken, options, method) {
666
801
  await this.ensurePrimerLoaded();
802
+ this.applePayOptions = options.applePay;
667
803
  this.currentHeadless = PrimerWrapper.headlessManager.getOrCreate(clientToken, options, method);
668
804
  return this.currentHeadless;
669
805
  }
@@ -710,16 +846,53 @@ class PrimerWrapper {
710
846
  }
711
847
  htmlNode.appendChild(wrapper);
712
848
  /* 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
+ }
713
871
  button = pmManager.createButton();
714
872
  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
+ }
715
883
  this.destroyCallbacks.push(() => button.clean());
716
884
  onMethodRender(allowedPaymentMethod);
717
885
  return {
718
886
  setDisabled: (disabled) => {
719
887
  button.setDisabled(disabled);
888
+ if (nativeOverlay) {
889
+ nativeOverlay.style.pointerEvents = disabled ? 'none' : '';
890
+ nativeOverlay.style.opacity = disabled ? '0.5' : '';
891
+ }
720
892
  },
721
893
  destroy: () => {
722
894
  styleEl.remove();
895
+ nativeOverlay?.remove();
723
896
  button.clean();
724
897
  },
725
898
  };
@@ -1066,6 +1239,32 @@ class PrimerWrapper {
1066
1239
  }
1067
1240
  PrimerWrapper.headlessManager = new HeadlessManager();
1068
1241
 
1242
+ /**
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.
1254
+ */
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))}`;
1260
+ }
1261
+ /** Consumes the tag — it describes one request only. */
1262
+ function takeWarmupTag() {
1263
+ const tag = pendingTag;
1264
+ pendingTag = null;
1265
+ return tag;
1266
+ }
1267
+
1069
1268
  /**
1070
1269
  * @fileoverview API client for Funnefox backend integration
1071
1270
  */
@@ -1083,6 +1282,7 @@ class APIClient {
1083
1282
  headers: {
1084
1283
  'Content-Type': 'application/json',
1085
1284
  'X-SDK-Version': SDK_VERSION,
1285
+ ...warmupHeader(),
1086
1286
  ...(options.headers || {}),
1087
1287
  },
1088
1288
  ...options,
@@ -1297,6 +1497,10 @@ class APIClient {
1297
1497
  }));
1298
1498
  }
1299
1499
  }
1500
+ function warmupHeader() {
1501
+ const tag = takeWarmupTag();
1502
+ return tag ? { [WARMUP_HEADER]: tag } : {};
1503
+ }
1300
1504
 
1301
1505
  class SessionService {
1302
1506
  constructor() {
@@ -1379,6 +1583,96 @@ const hideLoader = () => {
1379
1583
  }
1380
1584
  };
1381
1585
 
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
+
1382
1676
  var V3_URL = 'https://js.stripe.com/v3';
1383
1677
  var V3_URL_REGEX = /^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;
1384
1678
  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';
@@ -2536,6 +2830,98 @@ class CheckoutInstance extends EventEmitter {
2536
2830
  }
2537
2831
  async initMethod(method, element, callbacks) {
2538
2832
  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) {
2539
2925
  if (!this.isReady()) {
2540
2926
  await this.createSession();
2541
2927
  }
@@ -2753,6 +3139,7 @@ async function initMethod(method, element, options) {
2753
3139
  ...DEFAULT_BUTTONS_OPTIONS[PaymentMethod.GOOGLE_PAY],
2754
3140
  ...(options.googlePay || {}),
2755
3141
  },
3142
+ sessionCreation: options.sessionCreation,
2756
3143
  },
2757
3144
  });
2758
3145
  return await checkoutInstance.initMethod(method, element, {