@funnelfox/billing 0.5.3 → 0.5.4

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.
@@ -151,61 +151,6 @@ class NetworkError extends FunnefoxSDKError {
151
151
  }
152
152
  }
153
153
 
154
- /* eslint-disable @typescript-eslint/no-explicit-any */
155
- /**
156
- * @fileoverview Helper utilities for Funnefox SDK
157
- */
158
- function merge(...objects) {
159
- const result = {};
160
- for (const obj of objects) {
161
- if (obj && typeof obj === 'object') {
162
- for (const key in obj) {
163
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
164
- if (typeof obj[key] === 'object' &&
165
- !Array.isArray(obj[key]) &&
166
- obj[key] !== null) {
167
- result[key] = merge(result[key] || {}, obj[key]);
168
- }
169
- else {
170
- result[key] = obj[key];
171
- }
172
- }
173
- }
174
- }
175
- }
176
- return result;
177
- }
178
- function generateId(prefix = '') {
179
- const timestamp = Date.now().toString(36);
180
- const random = Math.random().toString(36).substr(2, 5);
181
- return `${prefix}${timestamp}_${random}`;
182
- }
183
- function sleep(ms) {
184
- return new Promise(resolve => setTimeout(resolve, ms));
185
- }
186
- async function retry(fn, maxAttempts = 3, baseDelay = 1000) {
187
- let lastError;
188
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
189
- try {
190
- return await fn();
191
- }
192
- catch (error) {
193
- lastError = error;
194
- if (attempt === maxAttempts)
195
- throw lastError;
196
- const delay = baseDelay * Math.pow(2, attempt - 1);
197
- await sleep(delay);
198
- }
199
- }
200
- throw lastError;
201
- }
202
- function withTimeout(promise, timeoutMs, message = 'Operation timed out') {
203
- const timeoutPromise = new Promise((_, reject) => {
204
- setTimeout(() => reject(new Error(message)), timeoutMs);
205
- });
206
- return Promise.race([promise, timeoutPromise]);
207
- }
208
-
209
154
  /**
210
155
  * @fileoverview Dynamic loader for Primer SDK
211
156
  * Loads Primer script and CSS from CDN independently of bundler
@@ -332,6 +277,142 @@ async function loadPrimerSDK(version) {
332
277
  return loadingPromise;
333
278
  }
334
279
 
280
+ /* eslint-disable @typescript-eslint/no-explicit-any */
281
+ /**
282
+ * @fileoverview Helper utilities for Funnefox SDK
283
+ */
284
+ function merge(...objects) {
285
+ const result = {};
286
+ for (const obj of objects) {
287
+ if (obj && typeof obj === 'object') {
288
+ for (const key in obj) {
289
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
290
+ if (typeof obj[key] === 'object' &&
291
+ !Array.isArray(obj[key]) &&
292
+ obj[key] !== null) {
293
+ result[key] = merge(result[key] || {}, obj[key]);
294
+ }
295
+ else {
296
+ result[key] = obj[key];
297
+ }
298
+ }
299
+ }
300
+ }
301
+ }
302
+ return result;
303
+ }
304
+ function generateId(prefix = '') {
305
+ const timestamp = Date.now().toString(36);
306
+ const random = Math.random().toString(36).substr(2, 5);
307
+ return `${prefix}${timestamp}_${random}`;
308
+ }
309
+ function sleep(ms) {
310
+ return new Promise(resolve => setTimeout(resolve, ms));
311
+ }
312
+ async function retry(fn, maxAttempts = 3, baseDelay = 1000) {
313
+ let lastError;
314
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
315
+ try {
316
+ return await fn();
317
+ }
318
+ catch (error) {
319
+ lastError = error;
320
+ if (attempt === maxAttempts)
321
+ throw lastError;
322
+ const delay = baseDelay * Math.pow(2, attempt - 1);
323
+ await sleep(delay);
324
+ }
325
+ }
326
+ throw lastError;
327
+ }
328
+ function withTimeout(promise, timeoutMs, message = 'Operation timed out') {
329
+ const timeoutPromise = new Promise((_, reject) => {
330
+ setTimeout(() => reject(new Error(message)), timeoutMs);
331
+ });
332
+ return Promise.race([promise, timeoutPromise]);
333
+ }
334
+
335
+ /**
336
+ * @fileoverview Headless checkout cache manager
337
+ */
338
+ /**
339
+ * Manages caching and sequential creation of Primer headless checkout instances.
340
+ * Ensures that multiple checkouts with the same configuration reuse the same instance,
341
+ * and that creations happen sequentially to avoid race conditions.
342
+ */
343
+ class HeadlessManager {
344
+ constructor() {
345
+ this.cache = new Map();
346
+ this.queue = Promise.resolve();
347
+ }
348
+ /**
349
+ * Generates a cache key from clientToken and serializable options
350
+ */
351
+ generateKey(clientToken, options) {
352
+ const serializableOptions = {
353
+ paymentHandling: options.paymentHandling,
354
+ apiVersion: options.apiVersion,
355
+ style: options.style,
356
+ card: options.card,
357
+ applePay: options.applePay,
358
+ paypal: options.paypal,
359
+ googlePay: options.googlePay,
360
+ };
361
+ return `${clientToken}:${JSON.stringify(serializableOptions)}`;
362
+ }
363
+ /**
364
+ * Gets a cached headless instance or creates a new one.
365
+ * Ensures sequential creation order to avoid race conditions.
366
+ */
367
+ getOrCreate(clientToken, options) {
368
+ const key = this.generateKey(clientToken, options);
369
+ // Return cached promise if exists
370
+ const cached = this.cache.get(key);
371
+ if (cached)
372
+ return cached;
373
+ // Create new headless in sequential order
374
+ const previousQueue = this.queue;
375
+ const promise = (async () => {
376
+ await previousQueue; // Wait for previous creation
377
+ const primerOptions = merge({
378
+ paymentHandling: 'MANUAL',
379
+ apiVersion: '2.4',
380
+ }, options);
381
+ try {
382
+ const headlessResult = await window.Primer.createHeadless(clientToken, primerOptions);
383
+ const headless = await headlessResult;
384
+ await headless.start();
385
+ return headless;
386
+ }
387
+ catch (error) {
388
+ // Remove from cache on failure
389
+ this.cache.delete(key);
390
+ throw new PrimerError('Failed to create Primer headless checkout', error);
391
+ }
392
+ })();
393
+ this.cache.set(key, promise);
394
+ this.queue = promise.catch(() => { }); // Update queue, ignore errors
395
+ return promise;
396
+ }
397
+ /**
398
+ * Removes a headless instance from the cache
399
+ */
400
+ remove(headlessPromise) {
401
+ for (const [key, value] of this.cache.entries()) {
402
+ if (value === headlessPromise) {
403
+ this.cache.delete(key);
404
+ break;
405
+ }
406
+ }
407
+ }
408
+ /**
409
+ * Clears all cached instances
410
+ */
411
+ clear() {
412
+ this.cache.clear();
413
+ }
414
+ }
415
+
335
416
  exports.PaymentMethod = void 0;
336
417
  (function (PaymentMethod) {
337
418
  PaymentMethod["GOOGLE_PAY"] = "GOOGLE_PAY";
@@ -343,7 +424,7 @@ exports.PaymentMethod = void 0;
343
424
  /**
344
425
  * @fileoverview Constants for Funnefox SDK
345
426
  */
346
- const SDK_VERSION = '0.5.3';
427
+ const SDK_VERSION = '0.5.4';
347
428
  const DEFAULTS = {
348
429
  BASE_URL: 'https://billing.funnelfox.com',
349
430
  REGION: 'default',
@@ -436,6 +517,7 @@ class PrimerWrapper {
436
517
  constructor() {
437
518
  this.isInitialized = false;
438
519
  this.destroyCallbacks = [];
520
+ this.currentHeadless = null;
439
521
  this.availableMethods = [];
440
522
  this.paymentMethodsInterfaces = [];
441
523
  }
@@ -465,26 +547,9 @@ class PrimerWrapper {
465
547
  }
466
548
  }
467
549
  async createHeadlessCheckout(clientToken, options) {
468
- if (PrimerWrapper.headless) {
469
- return PrimerWrapper.headless;
470
- }
471
- // Load Primer SDK if not already available
472
550
  await this.ensurePrimerLoaded();
473
- const primerOptions = merge({
474
- paymentHandling: 'MANUAL',
475
- apiVersion: '2.4',
476
- }, options);
477
- try {
478
- PrimerWrapper.headless = window.Primer.createHeadless(clientToken, primerOptions).then(async (headlessPromise) => {
479
- const headless = await headlessPromise;
480
- await headless.start();
481
- return headless;
482
- });
483
- return await PrimerWrapper.headless;
484
- }
485
- catch (error) {
486
- throw new PrimerError('Failed to create Primer headless checkout', error);
487
- }
551
+ this.currentHeadless = PrimerWrapper.headlessManager.getOrCreate(clientToken, options);
552
+ return this.currentHeadless;
488
553
  }
489
554
  disableButtons(disabled) {
490
555
  if (!this.paymentMethodsInterfaces)
@@ -497,11 +562,11 @@ class PrimerWrapper {
497
562
  let button;
498
563
  // Ensure Primer SDK is loaded
499
564
  await this.ensurePrimerLoaded();
500
- if (!PrimerWrapper.headless) {
565
+ if (!this.currentHeadless) {
501
566
  throw new PrimerError('Headless checkout not found');
502
567
  }
503
568
  try {
504
- const headless = await PrimerWrapper.headless;
569
+ const headless = await this.currentHeadless;
505
570
  const pmManager = await headless.createPaymentMethodManager(allowedPaymentMethod);
506
571
  if (!pmManager) {
507
572
  throw new Error('Payment method manager is not available');
@@ -555,7 +620,10 @@ class PrimerWrapper {
555
620
  }
556
621
  async renderCardCheckoutWithElements(elements, { onSubmit, onInputChange, onMethodRenderError, onMethodRender, }) {
557
622
  try {
558
- const headless = await PrimerWrapper.headless;
623
+ if (!this.currentHeadless) {
624
+ throw new PrimerError('Headless checkout not found');
625
+ }
626
+ const headless = await this.currentHeadless;
559
627
  const pmManager = await headless.createPaymentMethodManager('PAYMENT_CARD');
560
628
  if (!pmManager) {
561
629
  throw new Error('Payment method manager is not available');
@@ -731,7 +799,10 @@ class PrimerWrapper {
731
799
  };
732
800
  }
733
801
  async destroy() {
734
- PrimerWrapper.headless = null;
802
+ if (this.currentHeadless) {
803
+ PrimerWrapper.headlessManager.remove(this.currentHeadless);
804
+ this.currentHeadless = null;
805
+ }
735
806
  if (this.destroyCallbacks) {
736
807
  try {
737
808
  Promise.all(this.destroyCallbacks.map(destroy => destroy()));
@@ -779,7 +850,7 @@ class PrimerWrapper {
779
850
  return element;
780
851
  }
781
852
  }
782
- PrimerWrapper.headless = null;
853
+ PrimerWrapper.headlessManager = new HeadlessManager();
783
854
 
784
855
  /**
785
856
  * @fileoverview Input validation utilities for Funnefox SDK
@@ -1146,9 +1217,9 @@ class CheckoutInstance extends EventEmitter {
1146
1217
  ].join('-');
1147
1218
  let sessionResponse;
1148
1219
  // Return cached response if payload hasn't changed
1149
- const cachedResponse = await CheckoutInstance.sessionCache.get(cacheKey);
1220
+ const cachedResponse = CheckoutInstance.sessionCache.get(cacheKey);
1150
1221
  if (cachedResponse) {
1151
- sessionResponse = cachedResponse;
1222
+ sessionResponse = await cachedResponse;
1152
1223
  }
1153
1224
  else {
1154
1225
  const sessionRequest = this.apiClient.createClientSession(sessionParams);
@@ -1285,6 +1356,7 @@ class CheckoutInstance extends EventEmitter {
1285
1356
  this.emit(EVENTS.PURCHASE_FAILURE, error);
1286
1357
  },
1287
1358
  onTokenizeShouldStart: data => {
1359
+ wasPaymentProcessedStarted = true;
1288
1360
  this.emit(EVENTS.ERROR, undefined);
1289
1361
  this.emit(EVENTS.START_PURCHASE, data.paymentMethodType);
1290
1362
  return true;
@@ -1405,6 +1477,7 @@ class CheckoutInstance extends EventEmitter {
1405
1477
  this.on(EVENTS.INPUT_ERROR, skin.onInputError);
1406
1478
  this.on(EVENTS.METHOD_RENDER, skin.onMethodRender);
1407
1479
  this.on(EVENTS.SUCCESS, skin.onDestroy);
1480
+ this.on(EVENTS.DESTROY, skin.onDestroy);
1408
1481
  return skin.getCheckoutOptions();
1409
1482
  }
1410
1483
  showInitializingLoader() {
@@ -1413,6 +1486,48 @@ class CheckoutInstance extends EventEmitter {
1413
1486
  hideInitializingLoader() {
1414
1487
  hideLoader();
1415
1488
  }
1489
+ async initMethod(method, element, callbacks) {
1490
+ this._ensureNotDestroyed();
1491
+ if (!this.isReady()) {
1492
+ await this.createSession();
1493
+ }
1494
+ this.on(EVENTS.METHOD_RENDER, callbacks.onRenderSuccess);
1495
+ this.on(EVENTS.METHOD_RENDER_ERROR, callbacks.onRenderError);
1496
+ this.on(EVENTS.LOADER_CHANGE, callbacks.onLoaderChange);
1497
+ this.on(EVENTS.SUCCESS, callbacks.onPaymentSuccess);
1498
+ this.on(EVENTS.PURCHASE_FAILURE, callbacks.onPaymentFail);
1499
+ this.on(EVENTS.PURCHASE_CANCELLED, callbacks.onPaymentCancel);
1500
+ this.on(EVENTS.ERROR, callbacks.onErrorMessageChange);
1501
+ this.on(EVENTS.START_PURCHASE, callbacks.onPaymentStarted);
1502
+ this.on(EVENTS.METHODS_AVAILABLE, callbacks.onMethodsAvailable);
1503
+ let checkoutOptions = this.getCheckoutOptions({});
1504
+ let methodOptions = {
1505
+ onMethodRender: this.handleMethodRender,
1506
+ onMethodRenderError: this.handleMethodRenderError,
1507
+ };
1508
+ if (method === exports.PaymentMethod.PAYMENT_CARD) {
1509
+ const cardDefaultOptions = await this.getCardDefaultSkinCheckoutOptions(element);
1510
+ checkoutOptions = this.getCheckoutOptions({
1511
+ ...cardDefaultOptions,
1512
+ });
1513
+ methodOptions = {
1514
+ cardElements: cardDefaultOptions.cardElements,
1515
+ onSubmit: this.handleSubmit,
1516
+ onInputChange: this.handleInputChange,
1517
+ onMethodRender: this.handleMethodRender,
1518
+ onMethodRenderError: this.handleMethodRenderError,
1519
+ };
1520
+ }
1521
+ await this.primerWrapper.initializeHeadlessCheckout(this.clientToken, checkoutOptions);
1522
+ const methodInterface = await this.primerWrapper.initMethod(method, element, methodOptions);
1523
+ return {
1524
+ ...methodInterface,
1525
+ destroy: async () => {
1526
+ await methodInterface.destroy();
1527
+ await this.destroy();
1528
+ },
1529
+ };
1530
+ }
1416
1531
  }
1417
1532
  CheckoutInstance.sessionCache = new Map();
1418
1533
 
@@ -1494,9 +1609,6 @@ async function silentPurchase(options) {
1494
1609
  return true;
1495
1610
  }
1496
1611
  async function initMethod(method, element, options) {
1497
- // Ensure Primer SDK is loaded before initializing payment method
1498
- const primerWrapper = new PrimerWrapper();
1499
- await primerWrapper.ensurePrimerLoaded();
1500
1612
  const checkoutInstance = new CheckoutInstance({
1501
1613
  orgId: options.orgId,
1502
1614
  baseUrl: options.baseUrl,
@@ -1515,36 +1627,16 @@ async function initMethod(method, element, options) {
1515
1627
  googlePay: options.googlePay,
1516
1628
  },
1517
1629
  });
1518
- checkoutInstance._ensureNotDestroyed();
1519
- if (!checkoutInstance.isReady()) {
1520
- await checkoutInstance['createSession']();
1521
- }
1522
- checkoutInstance.on(EVENTS.METHOD_RENDER, options.onRenderSuccess);
1523
- checkoutInstance.on(EVENTS.METHOD_RENDER_ERROR, options.onRenderError);
1524
- checkoutInstance.on(EVENTS.LOADER_CHANGE, options.onLoaderChange);
1525
- checkoutInstance.on(EVENTS.SUCCESS, options.onPaymentSuccess);
1526
- checkoutInstance.on(EVENTS.PURCHASE_FAILURE, options.onPaymentFail);
1527
- checkoutInstance.on(EVENTS.PURCHASE_CANCELLED, options.onPaymentCancel);
1528
- checkoutInstance.on(EVENTS.ERROR, options.onErrorMessageChange);
1529
- checkoutInstance.on(EVENTS.START_PURCHASE, options.onPaymentStarted);
1530
- if (method === exports.PaymentMethod.PAYMENT_CARD) {
1531
- const cardDefaultOptions = await checkoutInstance['getCardDefaultSkinCheckoutOptions'](element);
1532
- const checkoutOptions = checkoutInstance['getCheckoutOptions']({
1533
- ...cardDefaultOptions,
1534
- });
1535
- await checkoutInstance.primerWrapper.initializeHeadlessCheckout(checkoutInstance.clientToken, checkoutOptions);
1536
- return checkoutInstance.primerWrapper.initMethod(method, element, {
1537
- cardElements: cardDefaultOptions.cardElements,
1538
- onSubmit: checkoutInstance['handleSubmit'],
1539
- onInputChange: checkoutInstance['handleInputChange'],
1540
- onMethodRender: checkoutInstance['handleMethodRender'],
1541
- onMethodRenderError: checkoutInstance['handleMethodRenderError'],
1542
- });
1543
- }
1544
- await checkoutInstance.primerWrapper.initializeHeadlessCheckout(checkoutInstance.clientToken, checkoutInstance['getCheckoutOptions']({}));
1545
- return checkoutInstance.primerWrapper.initMethod(method, element, {
1546
- onMethodRender: checkoutInstance['handleMethodRender'],
1547
- onMethodRenderError: checkoutInstance['handleMethodRenderError'],
1630
+ return checkoutInstance.initMethod(method, element, {
1631
+ onRenderSuccess: options.onRenderSuccess,
1632
+ onRenderError: options.onRenderError,
1633
+ onLoaderChange: options.onLoaderChange,
1634
+ onPaymentSuccess: options.onPaymentSuccess,
1635
+ onPaymentFail: options.onPaymentFail,
1636
+ onPaymentCancel: options.onPaymentCancel,
1637
+ onErrorMessageChange: options.onErrorMessageChange,
1638
+ onPaymentStarted: options.onPaymentStarted,
1639
+ onMethodsAvailable: options.onMethodsAvailable,
1548
1640
  });
1549
1641
  }
1550
1642