@vindhq/sloud-payment-sdk 1.0.0 → 1.0.2

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.
Files changed (163) hide show
  1. package/README.md +87 -20
  2. package/dist/index.cjs.js +24 -51295
  3. package/dist/index.d.ts +258 -3
  4. package/dist/index.esm.js +24 -51293
  5. package/dist/index.umd.js +2981 -79
  6. package/package.json +5 -4
  7. package/dist/index.cjs.js.map +0 -1
  8. package/dist/index.esm.js.map +0 -1
  9. package/dist/index.umd.js.map +0 -1
  10. package/dist/react/index.esm.js +0 -51440
  11. package/dist/react/index.esm.js.map +0 -1
  12. package/dist/react/rollup.config.d.ts +0 -8
  13. package/dist/react/rollup.config.dts.d.ts +0 -3
  14. package/dist/react/src/components/Button/Button.types.d.ts +0 -6
  15. package/dist/react/src/components/Button/index.d.ts +0 -3
  16. package/dist/react/src/components/CopyToClipboardSpan/CopyToClipboard.types.d.ts +0 -4
  17. package/dist/react/src/components/CopyToClipboardSpan/index.d.ts +0 -3
  18. package/dist/react/src/components/Input/Input.types.d.ts +0 -17
  19. package/dist/react/src/components/Input/index.d.ts +0 -3
  20. package/dist/react/src/components/Skeleton/PaymentOptionSkeletons.d.ts +0 -6
  21. package/dist/react/src/components/TextArea/TextArea.types.d.ts +0 -19
  22. package/dist/react/src/components/TextArea/index.d.ts +0 -3
  23. package/dist/react/src/components/Widget.d.ts +0 -6
  24. package/dist/react/src/components/modals/AwaitingPaymentModal/AwaitingPaymentModal.d.ts +0 -2
  25. package/dist/react/src/components/modals/AwaitingPaymentTimeoutModal/AwaitingPaymentTimeoutModal.d.ts +0 -2
  26. package/dist/react/src/components/modals/Modal.d.ts +0 -10
  27. package/dist/react/src/components/modals/PaymentDetailsModal/PaymentDetailsModal.d.ts +0 -2
  28. package/dist/react/src/components/modals/PaymentDetailsModal/hooks/useTimer.d.ts +0 -7
  29. package/dist/react/src/components/modals/PaymentOptionsModal/PaymentOptionsModal.d.ts +0 -2
  30. package/dist/react/src/components/modals/PaymentOptionsModal/RadioButton.d.ts +0 -11
  31. package/dist/react/src/components/modals/PaymentOptionsModal/paymentOptionsMap.d.ts +0 -5
  32. package/dist/react/src/components/modals/SuccessModal/SuccessModal.d.ts +0 -2
  33. package/dist/react/src/components/modals/state/actions/data.d.ts +0 -10
  34. package/dist/react/src/components/modals/state/actions/index.d.ts +0 -5
  35. package/dist/react/src/components/modals/state/actions/modal.d.ts +0 -5
  36. package/dist/react/src/components/modals/state/actions/payment.d.ts +0 -7
  37. package/dist/react/src/components/modals/state/constants/actionTypes.d.ts +0 -24
  38. package/dist/react/src/components/modals/state/constants/index.d.ts +0 -2
  39. package/dist/react/src/components/modals/state/constants/initialState.d.ts +0 -36
  40. package/dist/react/src/components/modals/state/reducers/data.d.ts +0 -2
  41. package/dist/react/src/components/modals/state/reducers/index.d.ts +0 -2
  42. package/dist/react/src/components/modals/state/reducers/modal.d.ts +0 -2
  43. package/dist/react/src/components/modals/state/reducers/payment.d.ts +0 -2
  44. package/dist/react/src/components/modals/state/types/common.d.ts +0 -12
  45. package/dist/react/src/components/modals/state/types/data.d.ts +0 -34
  46. package/dist/react/src/components/modals/state/types/index.d.ts +0 -8
  47. package/dist/react/src/components/modals/state/types/modal.d.ts +0 -12
  48. package/dist/react/src/components/modals/state/types/payment.d.ts +0 -14
  49. package/dist/react/src/components/modals/state/utils/index.d.ts +0 -37
  50. package/dist/react/src/context/ModalProvider.d.ts +0 -4
  51. package/dist/react/src/context/PaymentInfoContext.d.ts +0 -26
  52. package/dist/react/src/context/PaymentWidgetContext.d.ts +0 -13
  53. package/dist/react/src/context/modal.d.ts +0 -4
  54. package/dist/react/src/context/types.d.ts +0 -28
  55. package/dist/react/src/hooks/types.d.ts +0 -34
  56. package/dist/react/src/hooks/useModalControl.d.ts +0 -27
  57. package/dist/react/src/hooks/usePaymentAPI.d.ts +0 -10
  58. package/dist/react/src/hooks/useShortPolling.d.ts +0 -4
  59. package/dist/react/src/index.d.ts +0 -2
  60. package/dist/react/src/services/config/endpoints.d.ts +0 -9
  61. package/dist/react/src/services/config/error.d.ts +0 -5
  62. package/dist/react/src/services/index.d.ts +0 -27
  63. package/dist/react/src/services/payments/index.d.ts +0 -4
  64. package/dist/react/src/services/payments/types.d.ts +0 -68
  65. package/dist/react/src/services/products/index.d.ts +0 -1
  66. package/dist/react/src/services/products/types.d.ts +0 -124
  67. package/dist/react/src/services/store/index.d.ts +0 -2
  68. package/dist/react/src/services/store/types.d.ts +0 -57
  69. package/dist/react/src/services/utils/widgetConfig.d.ts +0 -20
  70. package/dist/react/src/svg_components/ArrowLeftIcon.d.ts +0 -3
  71. package/dist/react/src/svg_components/BankTransferIcon.d.ts +0 -2
  72. package/dist/react/src/svg_components/CancelIcon.d.ts +0 -7
  73. package/dist/react/src/svg_components/CardIcon.d.ts +0 -2
  74. package/dist/react/src/svg_components/CloseIcon.d.ts +0 -3
  75. package/dist/react/src/svg_components/CopyIcon.d.ts +0 -2
  76. package/dist/react/src/svg_components/EyeCloseIcon.d.ts +0 -5
  77. package/dist/react/src/svg_components/EyeOpenIcon.d.ts +0 -5
  78. package/dist/react/src/svg_components/SloudIcon.d.ts +0 -2
  79. package/dist/react/src/utils/enums/AxiosErrorCodes.d.ts +0 -7
  80. package/dist/react/src/utils/enums/AxiosMethods.d.ts +0 -7
  81. package/dist/react/src/utils/helpers/classNames.d.ts +0 -7
  82. package/dist/react/src/utils/helpers/formatCurrency.d.ts +0 -10
  83. package/dist/react/src/utils/helpers/phoneDefaults.d.ts +0 -3
  84. package/dist/react/src/utils/helpers/validatePhone.d.ts +0 -7
  85. package/dist/react/src/utils/image_utils/index.d.ts +0 -9
  86. package/dist/react/src/utils/storage/index.d.ts +0 -9
  87. package/dist/react/src/widget.d.ts +0 -27
  88. package/dist/rollup.config.d.ts +0 -8
  89. package/dist/rollup.config.dts.d.ts +0 -3
  90. package/dist/src/components/Button/Button.types.d.ts +0 -6
  91. package/dist/src/components/Button/index.d.ts +0 -3
  92. package/dist/src/components/CopyToClipboardSpan/CopyToClipboard.types.d.ts +0 -4
  93. package/dist/src/components/CopyToClipboardSpan/index.d.ts +0 -3
  94. package/dist/src/components/Input/Input.types.d.ts +0 -17
  95. package/dist/src/components/Input/index.d.ts +0 -3
  96. package/dist/src/components/Skeleton/PaymentOptionSkeletons.d.ts +0 -6
  97. package/dist/src/components/TextArea/TextArea.types.d.ts +0 -19
  98. package/dist/src/components/TextArea/index.d.ts +0 -3
  99. package/dist/src/components/Widget.d.ts +0 -6
  100. package/dist/src/components/modals/AwaitingPaymentModal/AwaitingPaymentModal.d.ts +0 -2
  101. package/dist/src/components/modals/AwaitingPaymentTimeoutModal/AwaitingPaymentTimeoutModal.d.ts +0 -2
  102. package/dist/src/components/modals/Modal.d.ts +0 -10
  103. package/dist/src/components/modals/PaymentDetailsModal/PaymentDetailsModal.d.ts +0 -2
  104. package/dist/src/components/modals/PaymentDetailsModal/hooks/useTimer.d.ts +0 -7
  105. package/dist/src/components/modals/PaymentOptionsModal/PaymentOptionsModal.d.ts +0 -2
  106. package/dist/src/components/modals/PaymentOptionsModal/RadioButton.d.ts +0 -11
  107. package/dist/src/components/modals/PaymentOptionsModal/paymentOptionsMap.d.ts +0 -5
  108. package/dist/src/components/modals/SuccessModal/SuccessModal.d.ts +0 -2
  109. package/dist/src/components/modals/state/actions/data.d.ts +0 -10
  110. package/dist/src/components/modals/state/actions/index.d.ts +0 -5
  111. package/dist/src/components/modals/state/actions/modal.d.ts +0 -5
  112. package/dist/src/components/modals/state/actions/payment.d.ts +0 -7
  113. package/dist/src/components/modals/state/constants/actionTypes.d.ts +0 -24
  114. package/dist/src/components/modals/state/constants/index.d.ts +0 -2
  115. package/dist/src/components/modals/state/constants/initialState.d.ts +0 -36
  116. package/dist/src/components/modals/state/reducers/data.d.ts +0 -2
  117. package/dist/src/components/modals/state/reducers/index.d.ts +0 -2
  118. package/dist/src/components/modals/state/reducers/modal.d.ts +0 -2
  119. package/dist/src/components/modals/state/reducers/payment.d.ts +0 -2
  120. package/dist/src/components/modals/state/types/common.d.ts +0 -12
  121. package/dist/src/components/modals/state/types/data.d.ts +0 -34
  122. package/dist/src/components/modals/state/types/index.d.ts +0 -8
  123. package/dist/src/components/modals/state/types/modal.d.ts +0 -12
  124. package/dist/src/components/modals/state/types/payment.d.ts +0 -14
  125. package/dist/src/components/modals/state/utils/index.d.ts +0 -37
  126. package/dist/src/context/ModalProvider.d.ts +0 -4
  127. package/dist/src/context/PaymentInfoContext.d.ts +0 -26
  128. package/dist/src/context/PaymentWidgetContext.d.ts +0 -13
  129. package/dist/src/context/modal.d.ts +0 -4
  130. package/dist/src/context/types.d.ts +0 -28
  131. package/dist/src/hooks/types.d.ts +0 -34
  132. package/dist/src/hooks/useModalControl.d.ts +0 -27
  133. package/dist/src/hooks/usePaymentAPI.d.ts +0 -10
  134. package/dist/src/hooks/useShortPolling.d.ts +0 -4
  135. package/dist/src/index.d.ts +0 -2
  136. package/dist/src/services/config/endpoints.d.ts +0 -9
  137. package/dist/src/services/config/error.d.ts +0 -5
  138. package/dist/src/services/index.d.ts +0 -27
  139. package/dist/src/services/payments/index.d.ts +0 -4
  140. package/dist/src/services/payments/types.d.ts +0 -68
  141. package/dist/src/services/products/index.d.ts +0 -1
  142. package/dist/src/services/products/types.d.ts +0 -124
  143. package/dist/src/services/store/index.d.ts +0 -2
  144. package/dist/src/services/store/types.d.ts +0 -57
  145. package/dist/src/services/utils/widgetConfig.d.ts +0 -20
  146. package/dist/src/svg_components/ArrowLeftIcon.d.ts +0 -3
  147. package/dist/src/svg_components/BankTransferIcon.d.ts +0 -2
  148. package/dist/src/svg_components/CancelIcon.d.ts +0 -7
  149. package/dist/src/svg_components/CardIcon.d.ts +0 -2
  150. package/dist/src/svg_components/CloseIcon.d.ts +0 -3
  151. package/dist/src/svg_components/CopyIcon.d.ts +0 -2
  152. package/dist/src/svg_components/EyeCloseIcon.d.ts +0 -5
  153. package/dist/src/svg_components/EyeOpenIcon.d.ts +0 -5
  154. package/dist/src/svg_components/SloudIcon.d.ts +0 -2
  155. package/dist/src/utils/enums/AxiosErrorCodes.d.ts +0 -7
  156. package/dist/src/utils/enums/AxiosMethods.d.ts +0 -7
  157. package/dist/src/utils/helpers/classNames.d.ts +0 -7
  158. package/dist/src/utils/helpers/formatCurrency.d.ts +0 -10
  159. package/dist/src/utils/helpers/phoneDefaults.d.ts +0 -3
  160. package/dist/src/utils/helpers/validatePhone.d.ts +0 -7
  161. package/dist/src/utils/image_utils/index.d.ts +0 -9
  162. package/dist/src/utils/storage/index.d.ts +0 -9
  163. package/dist/src/widget.d.ts +0 -27
package/dist/index.umd.js CHANGED
@@ -1,10 +1,10 @@
1
1
 
2
2
  (function(l, r) { if (!l || l.getElementById('livereloadscript')) return; r = l.createElement('script'); r.async = 1; r.src = '//' + (self.location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1'; r.id = 'livereloadscript'; l.getElementsByTagName('head')[0].appendChild(r) })(self.document);
3
3
  (function (global, factory) {
4
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
5
- typeof define === 'function' && define.amd ? define(factory) :
6
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.PaymentWidget = factory());
7
- })(this, (function () { 'use strict';
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
5
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.PaymentWidget = {}));
7
+ })(this, (function (exports) { 'use strict';
8
8
 
9
9
  var global$1 = (typeof global !== "undefined" ? global :
10
10
  typeof self !== "undefined" ? self :
@@ -44614,12 +44614,12 @@ to {
44614
44614
 
44615
44615
  // utils is a library of generic helper functions non-specific to axios
44616
44616
 
44617
- const {toString: toString$1} = Object.prototype;
44617
+ const {toString: toString$2} = Object.prototype;
44618
44618
  const {getPrototypeOf} = Object;
44619
44619
  const {iterator, toStringTag} = Symbol;
44620
44620
 
44621
44621
  const kindOf = (cache => thing => {
44622
- const str = toString$1.call(thing);
44622
+ const str = toString$2.call(thing);
44623
44623
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
44624
44624
  })(Object.create(null));
44625
44625
 
@@ -44720,7 +44720,7 @@ to {
44720
44720
  *
44721
44721
  * @returns {boolean} True if value is an Object, otherwise false
44722
44722
  */
44723
- const isObject = (thing) => thing !== null && typeof thing === 'object';
44723
+ const isObject$1 = (thing) => thing !== null && typeof thing === 'object';
44724
44724
 
44725
44725
  /**
44726
44726
  * Determine if a value is a Boolean
@@ -44755,7 +44755,7 @@ to {
44755
44755
  */
44756
44756
  const isEmptyObject = (val) => {
44757
44757
  // Early return for non-objects or Buffers to prevent RangeError
44758
- if (!isObject(val) || isBuffer$1(val)) {
44758
+ if (!isObject$1(val) || isBuffer$1(val)) {
44759
44759
  return false;
44760
44760
  }
44761
44761
 
@@ -44774,7 +44774,7 @@ to {
44774
44774
  *
44775
44775
  * @returns {boolean} True if value is a Date, otherwise false
44776
44776
  */
44777
- const isDate = kindOfTest('Date');
44777
+ const isDate$1 = kindOfTest('Date');
44778
44778
 
44779
44779
  /**
44780
44780
  * Determine if a value is a File
@@ -44810,7 +44810,7 @@ to {
44810
44810
  *
44811
44811
  * @returns {boolean} True if value is a Stream, otherwise false
44812
44812
  */
44813
- const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
44813
+ const isStream = (val) => isObject$1(val) && isFunction$1(val.pipe);
44814
44814
 
44815
44815
  /**
44816
44816
  * Determine if a value is a FormData
@@ -44868,7 +44868,7 @@ to {
44868
44868
  * @param {Boolean} [allOwnKeys = false]
44869
44869
  * @returns {any}
44870
44870
  */
44871
- function forEach(obj, fn, {allOwnKeys = false} = {}) {
44871
+ function forEach$1(obj, fn, {allOwnKeys = false} = {}) {
44872
44872
  // Don't bother if no value provided
44873
44873
  if (obj === null || typeof obj === 'undefined') {
44874
44874
  return;
@@ -44967,7 +44967,7 @@ to {
44967
44967
  };
44968
44968
 
44969
44969
  for (let i = 0, l = arguments.length; i < l; i++) {
44970
- arguments[i] && forEach(arguments[i], assignValue);
44970
+ arguments[i] && forEach$1(arguments[i], assignValue);
44971
44971
  }
44972
44972
  return result;
44973
44973
  }
@@ -44983,7 +44983,7 @@ to {
44983
44983
  * @returns {Object} The resulting value of object a
44984
44984
  */
44985
44985
  const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
44986
- forEach(b, (val, key) => {
44986
+ forEach$1(b, (val, key) => {
44987
44987
  if (thisArg && isFunction$1(val)) {
44988
44988
  a[key] = bind(val, thisArg);
44989
44989
  } else {
@@ -45087,7 +45087,7 @@ to {
45087
45087
  *
45088
45088
  * @returns {?Array}
45089
45089
  */
45090
- const toArray = (thing) => {
45090
+ const toArray$1 = (thing) => {
45091
45091
  if (!thing) return null;
45092
45092
  if (isArray$1(thing)) return thing;
45093
45093
  let i = thing.length;
@@ -45182,7 +45182,7 @@ to {
45182
45182
  const descriptors = Object.getOwnPropertyDescriptors(obj);
45183
45183
  const reducedDescriptors = {};
45184
45184
 
45185
- forEach(descriptors, (descriptor, name) => {
45185
+ forEach$1(descriptors, (descriptor, name) => {
45186
45186
  let ret;
45187
45187
  if ((ret = reducer(descriptor, name, obj)) !== false) {
45188
45188
  reducedDescriptors[name] = ret || descriptor;
@@ -45261,7 +45261,7 @@ to {
45261
45261
 
45262
45262
  const visit = (source, i) => {
45263
45263
 
45264
- if (isObject(source)) {
45264
+ if (isObject$1(source)) {
45265
45265
  if (stack.indexOf(source) >= 0) {
45266
45266
  return;
45267
45267
  }
@@ -45275,7 +45275,7 @@ to {
45275
45275
  stack[i] = source;
45276
45276
  const target = isArray$1(source) ? [] : {};
45277
45277
 
45278
- forEach(source, (value, key) => {
45278
+ forEach$1(source, (value, key) => {
45279
45279
  const reducedValue = visit(value, i + 1);
45280
45280
  !isUndefined(reducedValue) && (target[key] = reducedValue);
45281
45281
  });
@@ -45295,7 +45295,7 @@ to {
45295
45295
  const isAsyncFn = kindOfTest('AsyncFunction');
45296
45296
 
45297
45297
  const isThenable = (thing) =>
45298
- thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
45298
+ thing && (isObject$1(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
45299
45299
 
45300
45300
  // original code
45301
45301
  // https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
@@ -45340,7 +45340,7 @@ to {
45340
45340
  isString,
45341
45341
  isNumber,
45342
45342
  isBoolean,
45343
- isObject,
45343
+ isObject: isObject$1,
45344
45344
  isPlainObject,
45345
45345
  isEmptyObject,
45346
45346
  isReadableStream,
@@ -45348,7 +45348,7 @@ to {
45348
45348
  isResponse,
45349
45349
  isHeaders,
45350
45350
  isUndefined,
45351
- isDate,
45351
+ isDate: isDate$1,
45352
45352
  isFile,
45353
45353
  isBlob,
45354
45354
  isRegExp,
@@ -45357,7 +45357,7 @@ to {
45357
45357
  isURLSearchParams,
45358
45358
  isTypedArray,
45359
45359
  isFileList,
45360
- forEach,
45360
+ forEach: forEach$1,
45361
45361
  merge,
45362
45362
  extend,
45363
45363
  trim,
@@ -45367,7 +45367,7 @@ to {
45367
45367
  kindOf,
45368
45368
  kindOfTest,
45369
45369
  endsWith,
45370
- toArray,
45370
+ toArray: toArray$1,
45371
45371
  forEachEntry,
45372
45372
  matchAll,
45373
45373
  isHTMLForm,
@@ -45586,10 +45586,10 @@ to {
45586
45586
  buffer[offset + i - d] |= s * 128;
45587
45587
  }
45588
45588
 
45589
- var toString = {}.toString;
45589
+ var toString$1 = {}.toString;
45590
45590
 
45591
45591
  var isArray = Array.isArray || function (arr) {
45592
- return toString.call(arr) == '[object Array]';
45592
+ return toString$1.call(arr) == '[object Array]';
45593
45593
  };
45594
45594
 
45595
45595
  /*!
@@ -50634,6 +50634,157 @@ to {
50634
50634
  return (jsxRuntimeExports.jsx(PaymentWidgetContext.Provider, { value: value, children: children }));
50635
50635
  };
50636
50636
 
50637
+ /**
50638
+ * Builder for external payment payloads
50639
+ */
50640
+ class ExternalPaymentPayloadBuilder {
50641
+ build(options, payment_method) {
50642
+ return {
50643
+ type: "external",
50644
+ amount: options.amount,
50645
+ customer: options.customer,
50646
+ };
50647
+ }
50648
+ }
50649
+ /**
50650
+ * Builder for storefront payment payloads
50651
+ */
50652
+ class StorefrontPaymentPayloadBuilder {
50653
+ build(options, payment_method) {
50654
+ return {
50655
+ type: "storefront",
50656
+ slug: options.slug,
50657
+ order: {
50658
+ additional_amount: Math.round(options.amount) || 0,
50659
+ discount: options.discount || 0,
50660
+ items: options.products.map((product) => ({
50661
+ product_id: product.product_id,
50662
+ quantity: product.quantity,
50663
+ variation: product.variation,
50664
+ })),
50665
+ payment_method: payment_method || "",
50666
+ channel: options.channel,
50667
+ buyer_details: {
50668
+ first_name: options.customer.first_name,
50669
+ last_name: options.customer.last_name,
50670
+ email: options.customer.email,
50671
+ phone_number: options.customer.phone_number,
50672
+ },
50673
+ delivery_details: options.delivery_details,
50674
+ },
50675
+ };
50676
+ }
50677
+ }
50678
+ /**
50679
+ * Builder for storefront payment payloads
50680
+ */
50681
+ class SloudfrontPaymentPayloadBuilder {
50682
+ build(options, payment_method) {
50683
+ return {
50684
+ type: "sloudfront",
50685
+ manual_order: {
50686
+ additional_amount: Math.round(options.amount) || 0,
50687
+ discount: options.discount || 0,
50688
+ items: options.products.map((product) => ({
50689
+ product_id: product.product_id,
50690
+ quantity: product.quantity,
50691
+ variation: product.variation,
50692
+ })),
50693
+ payment_method: payment_method || "",
50694
+ channel: options.channel,
50695
+ buyer_details: {
50696
+ first_name: options.customer.first_name,
50697
+ last_name: options.customer.last_name,
50698
+ email: options.customer.email,
50699
+ phone_number: options.customer.phone_number,
50700
+ },
50701
+ delivery_details: options.delivery_details,
50702
+ // transaction_id: options.transaction_id,
50703
+ customer_id: options.customer_id,
50704
+ business_id: options.business_id,
50705
+ },
50706
+ };
50707
+ }
50708
+ }
50709
+ /**
50710
+ * Registry of payload builders by payment type
50711
+ */
50712
+ const payloadBuilders = {
50713
+ external: new ExternalPaymentPayloadBuilder(),
50714
+ storefront: new StorefrontPaymentPayloadBuilder(),
50715
+ sloudfront: new SloudfrontPaymentPayloadBuilder(),
50716
+ };
50717
+ /**
50718
+ * Factory function to build payment instrument payload based on options type
50719
+ *
50720
+ * @param options - Payment widget options
50721
+ * @returns Constructed payload for the payment instrument API
50722
+ * @throws Error if the payment type is not supported
50723
+ *
50724
+ * @example
50725
+ * // External payment
50726
+ * const payload = buildPaymentInstrumentPayload({
50727
+ * type: "external",
50728
+ * amount: 25000,
50729
+ * // ... other options
50730
+ * });
50731
+ *
50732
+ * @example
50733
+ * // Storefront payment
50734
+ * const payload = buildPaymentInstrumentPayload({
50735
+ * type: "storefront",
50736
+ * slug: "my-store",
50737
+ * products: [...],
50738
+ * // ... other options
50739
+ * });
50740
+ */
50741
+ function buildPaymentInstrumentPayload(options, payment_method) {
50742
+ const builder = payloadBuilders[options.type];
50743
+ if (!builder) {
50744
+ throw new Error(`Unsupported payment type: ${options.type}. Available types: ${Object.keys(payloadBuilders).join(", ")}`);
50745
+ }
50746
+ // TypeScript will narrow the type based on options.type
50747
+ return builder.build(options, payment_method);
50748
+ }
50749
+ /**
50750
+ * Register a new payload builder for a custom payment type
50751
+ * This allows for extending the system with new payment types without modifying existing code
50752
+ *
50753
+ * @param type - The payment type identifier
50754
+ * @param builder - The payload builder instance
50755
+ *
50756
+ * @example
50757
+ * class SubscriptionPaymentPayloadBuilder implements PayloadBuilder<ISubscriptionPaymentPayload> {
50758
+ * build(options: PaymentWidgetOptions): ISubscriptionPaymentPayload {
50759
+ * return {
50760
+ * type: "subscription",
50761
+ * plan_id: options.plan_id,
50762
+ * // ... other fields
50763
+ * };
50764
+ * }
50765
+ * }
50766
+ *
50767
+ * registerPayloadBuilder("subscription", new SubscriptionPaymentPayloadBuilder());
50768
+ */
50769
+ function registerPayloadBuilder(type, builder) {
50770
+ payloadBuilders[type] = builder;
50771
+ }
50772
+ /**
50773
+ * Get all registered payment types
50774
+ *
50775
+ * @returns Array of registered payment type identifiers
50776
+ */
50777
+ function getRegisteredPaymentTypes() {
50778
+ return Object.keys(payloadBuilders);
50779
+ }
50780
+
50781
+ const getAxiosErrorMessage = (err) => {
50782
+ const error = err;
50783
+ const responseError = error?.response?.data?.message;
50784
+ const requestError = error?.message;
50785
+ return responseError ?? requestError;
50786
+ };
50787
+
50637
50788
  const usePaymentAPI = () => {
50638
50789
  const { updateCollectionAccount, updateTransactionDetails } = usePaymentInfoContext();
50639
50790
  const [isFetchingMethods, setIsFetchingMethods] = reactExports.useState(false);
@@ -50659,25 +50810,26 @@ to {
50659
50810
  }
50660
50811
  }
50661
50812
  catch (error) {
50813
+ zt.error(String(getAxiosErrorMessage(error)));
50662
50814
  }
50663
50815
  finally {
50664
50816
  setIsFetchingMethods(false);
50665
50817
  }
50666
50818
  }, [options.public_key]);
50667
- const generatePaymentInstrument = reactExports.useCallback(async () => {
50819
+ const generatePaymentInstrument = reactExports.useCallback(async (payment_method) => {
50668
50820
  setIsLoading(true);
50669
- const payload = {
50670
- amount: options.amount,
50671
- customer: {
50672
- first_name: options.first_name,
50673
- last_name: options.last_name,
50674
- phone_number: options.phone_number,
50675
- email: options.email,
50676
- },
50677
- };
50821
+ setSuccess(false);
50678
50822
  try {
50679
- const { response } = await generatePaymentInstrumentService(options.public_key, payload);
50680
- setIsLoading(false);
50823
+ const payload = buildPaymentInstrumentPayload(options, payment_method);
50824
+ const { response, error } = await generatePaymentInstrumentService(options.public_key, payload);
50825
+ if (error) {
50826
+ const errorMessage = error.response?.data?.message ||
50827
+ error.message ||
50828
+ "Failed to generate payment instrument";
50829
+ zt.error(errorMessage);
50830
+ setIsLoading(false);
50831
+ return;
50832
+ }
50681
50833
  if (response?.status === "success" && response?.data) {
50682
50834
  const collectionAccount = {
50683
50835
  accountName: response.data.account_name,
@@ -50697,13 +50849,12 @@ to {
50697
50849
  }
50698
50850
  }
50699
50851
  catch (error) {
50700
- console.error(error);
50852
+ zt.error(String(getAxiosErrorMessage(error)));
50701
50853
  }
50702
50854
  finally {
50703
50855
  setIsLoading(false);
50704
- setSuccess(true);
50705
50856
  }
50706
- }, [options.public_key]);
50857
+ }, [options, updateCollectionAccount, updateTransactionDetails]);
50707
50858
  reactExports.useEffect(() => {
50708
50859
  fetchPaymentMethods$1();
50709
50860
  }, []);
@@ -50776,8 +50927,8 @@ to {
50776
50927
  return (jsxRuntimeExports.jsxs("label", { className: getClassName(disabled), children: [jsxRuntimeExports.jsxs("div", { className: styles$1.radioButton__item, children: [jsxRuntimeExports.jsx("div", { children: jsxRuntimeExports.jsx("input", { className: styles$1.radioButton__input, type: "radio", name: name, value: value, disabled: disabled, id: id, checked: checked, onChange: onChange }) }), jsxRuntimeExports.jsx("div", { children: jsxRuntimeExports.jsx("p", { className: styles$1.radioButton__label, children: label }) })] }), jsxRuntimeExports.jsx("div", { className: styles$1.radioButton__icon, children: Icons[value] })] }));
50777
50928
  };
50778
50929
 
50779
- var css_248z$3 = ".PaymentOptionsModal-module_paymentOptionsModal__body__u2eOb {\n margin-bottom: 30px;\n}\n.PaymentOptionsModal-module_paymentOptionsModal__bodyOptions__SfvwI p {\n font-size: 0.875rem;\n}\n.PaymentOptionsModal-module_paymentOptionsModal__continueButton__-2Nry {\n background: rgb(19, 18, 18);\n width: 100%;\n color: white;\n margin-top: 50px;\n padding: 15px;\n border-radius: 30px;\n border: none;\n cursor: pointer;\n font-weight: bold;\n font-family: inherit;\n}\n.PaymentOptionsModal-module_paymentOptionsModal__continueButton__-2Nry:disabled {\n cursor: not-allowed;\n}\n.PaymentOptionsModal-module_paymentOptionsModal__skeleton__ElGQb {\n height: 60px;\n width: 100%;\n}\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlBheW1lbnRPcHRpb25zTW9kYWwubW9kdWxlLnNjc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7RUFDRSxtQkFBbUI7QUFDckI7QUFDQTtFQUNFLG1CQUFtQjtBQUNyQjtBQUNBO0VBQ0UsMkJBQTJCO0VBQzNCLFdBQVc7RUFDWCxZQUFZO0VBQ1osZ0JBQWdCO0VBQ2hCLGFBQWE7RUFDYixtQkFBbUI7RUFDbkIsWUFBWTtFQUNaLGVBQWU7RUFDZixpQkFBaUI7RUFDakIsb0JBQW9CO0FBQ3RCO0FBQ0E7RUFDRSxtQkFBbUI7QUFDckI7QUFDQTtFQUNFLFlBQVk7RUFDWixXQUFXO0FBQ2IiLCJmaWxlIjoiUGF5bWVudE9wdGlvbnNNb2RhbC5tb2R1bGUuc2NzcyIsInNvdXJjZXNDb250ZW50IjpbIi5wYXltZW50T3B0aW9uc01vZGFsX19ib2R5IHtcbiAgbWFyZ2luLWJvdHRvbTogMzBweDtcbn1cbi5wYXltZW50T3B0aW9uc01vZGFsX19ib2R5T3B0aW9ucyBwIHtcbiAgZm9udC1zaXplOiAwLjg3NXJlbTtcbn1cbi5wYXltZW50T3B0aW9uc01vZGFsX19jb250aW51ZUJ1dHRvbiB7XG4gIGJhY2tncm91bmQ6IHJnYigxOSwgMTgsIDE4KTtcbiAgd2lkdGg6IDEwMCU7XG4gIGNvbG9yOiB3aGl0ZTtcbiAgbWFyZ2luLXRvcDogNTBweDtcbiAgcGFkZGluZzogMTVweDtcbiAgYm9yZGVyLXJhZGl1czogMzBweDtcbiAgYm9yZGVyOiBub25lO1xuICBjdXJzb3I6IHBvaW50ZXI7XG4gIGZvbnQtd2VpZ2h0OiBib2xkO1xuICBmb250LWZhbWlseTogaW5oZXJpdDtcbn1cbi5wYXltZW50T3B0aW9uc01vZGFsX19jb250aW51ZUJ1dHRvbjpkaXNhYmxlZCB7XG4gIGN1cnNvcjogbm90LWFsbG93ZWQ7XG59XG4ucGF5bWVudE9wdGlvbnNNb2RhbF9fc2tlbGV0b24ge1xuICBoZWlnaHQ6IDYwcHg7XG4gIHdpZHRoOiAxMDAlO1xufSJdfQ== */";
50780
- var PayOptionsStyles = {"paymentOptionsModal__body":"PaymentOptionsModal-module_paymentOptionsModal__body__u2eOb","paymentOptionsModal__continueButton":"PaymentOptionsModal-module_paymentOptionsModal__continueButton__-2Nry"};
50930
+ var css_248z$3 = ".PaymentOptionsModal-module_paymentOptionsModal__body__u2eOb {\n margin-bottom: 30px;\n}\n.PaymentOptionsModal-module_paymentOptionsModal__comingSoonText__HBOa2 {\n font-size: 0.875rem;\n margin: 0px;\n}\n.PaymentOptionsModal-module_paymentOptionsModal__continueButton__-2Nry {\n background: rgb(19, 18, 18);\n width: 100%;\n color: white;\n margin-top: 50px;\n padding: 15px;\n border-radius: 30px;\n border: none;\n cursor: pointer;\n font-weight: bold;\n font-family: inherit;\n}\n.PaymentOptionsModal-module_paymentOptionsModal__continueButton__-2Nry:disabled {\n cursor: not-allowed;\n}\n.PaymentOptionsModal-module_paymentOptionsModal__skeleton__ElGQb {\n height: 60px;\n width: 100%;\n}\n/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIlBheW1lbnRPcHRpb25zTW9kYWwubW9kdWxlLnNjc3MiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7RUFDRSxtQkFBbUI7QUFDckI7QUFDQTtFQUNFLG1CQUFtQjtFQUNuQixXQUFXO0FBQ2I7QUFDQTtFQUNFLDJCQUEyQjtFQUMzQixXQUFXO0VBQ1gsWUFBWTtFQUNaLGdCQUFnQjtFQUNoQixhQUFhO0VBQ2IsbUJBQW1CO0VBQ25CLFlBQVk7RUFDWixlQUFlO0VBQ2YsaUJBQWlCO0VBQ2pCLG9CQUFvQjtBQUN0QjtBQUNBO0VBQ0UsbUJBQW1CO0FBQ3JCO0FBQ0E7RUFDRSxZQUFZO0VBQ1osV0FBVztBQUNiIiwiZmlsZSI6IlBheW1lbnRPcHRpb25zTW9kYWwubW9kdWxlLnNjc3MiLCJzb3VyY2VzQ29udGVudCI6WyIucGF5bWVudE9wdGlvbnNNb2RhbF9fYm9keSB7XG4gIG1hcmdpbi1ib3R0b206IDMwcHg7XG59XG4ucGF5bWVudE9wdGlvbnNNb2RhbF9fY29taW5nU29vblRleHQge1xuICBmb250LXNpemU6IDAuODc1cmVtO1xuICBtYXJnaW46IDBweDtcbn1cbi5wYXltZW50T3B0aW9uc01vZGFsX19jb250aW51ZUJ1dHRvbiB7XG4gIGJhY2tncm91bmQ6IHJnYigxOSwgMTgsIDE4KTtcbiAgd2lkdGg6IDEwMCU7XG4gIGNvbG9yOiB3aGl0ZTtcbiAgbWFyZ2luLXRvcDogNTBweDtcbiAgcGFkZGluZzogMTVweDtcbiAgYm9yZGVyLXJhZGl1czogMzBweDtcbiAgYm9yZGVyOiBub25lO1xuICBjdXJzb3I6IHBvaW50ZXI7XG4gIGZvbnQtd2VpZ2h0OiBib2xkO1xuICBmb250LWZhbWlseTogaW5oZXJpdDtcbn1cbi5wYXltZW50T3B0aW9uc01vZGFsX19jb250aW51ZUJ1dHRvbjpkaXNhYmxlZCB7XG4gIGN1cnNvcjogbm90LWFsbG93ZWQ7XG59XG4ucGF5bWVudE9wdGlvbnNNb2RhbF9fc2tlbGV0b24ge1xuICBoZWlnaHQ6IDYwcHg7XG4gIHdpZHRoOiAxMDAlO1xufSJdfQ== */";
50931
+ var PayOptionsStyles = {"paymentOptionsModal__body":"PaymentOptionsModal-module_paymentOptionsModal__body__u2eOb","paymentOptionsModal__comingSoonText":"PaymentOptionsModal-module_paymentOptionsModal__comingSoonText__HBOa2","paymentOptionsModal__continueButton":"PaymentOptionsModal-module_paymentOptionsModal__continueButton__-2Nry"};
50781
50932
  styleInject(css_248z$3);
50782
50933
 
50783
50934
  /**
@@ -50893,7 +51044,7 @@ to {
50893
51044
  };
50894
51045
 
50895
51046
  const PaymentOptionsModal = () => {
50896
- const { open, currentModal, moveNext } = useModalContext();
51047
+ const { open, currentModal, moveNext, setPaymentMethod } = useModalContext();
50897
51048
  const { paymentMethods, isFetchingMethods, generatePaymentInstrument, isLoading, isSuccess, } = usePaymentAPI();
50898
51049
  const [selectedOption, setSelectedOption] = reactExports.useState("");
50899
51050
  const isModalOpen = open && currentModal === ModalNames.Payment;
@@ -50906,13 +51057,19 @@ to {
50906
51057
  setSelectedOption(e.target.value);
50907
51058
  };
50908
51059
  const handleSubmit = async () => {
50909
- await generatePaymentInstrument();
51060
+ setPaymentMethod(selectedOption);
51061
+ await generatePaymentInstrument(selectedOption);
50910
51062
  };
50911
51063
  const renderPaymentOptions = reactExports.useMemo(() => {
50912
- const availableOptions = Object.entries(paymentOptionsMap).filter(([key]) => paymentMethods[key]);
51064
+ const availableOptions = Object.entries(paymentOptionsMap);
50913
51065
  if (availableOptions.length === 0)
50914
51066
  return null;
50915
- return availableOptions.map(([key, { label, value, disabled }]) => (jsxRuntimeExports.jsx(RadioButton, { label: label, name: "payment-options", id: key, value: value, disabled: disabled, checked: selectedOption === value, onChange: handleChange }, key)));
51067
+ // Find the index of the first disabled option
51068
+ const firstDisabledIndex = availableOptions.findIndex(([, option]) => option.disabled);
51069
+ return availableOptions.map(([key, { label, value, disabled }], i) => {
51070
+ const showComingSoon = i === firstDisabledIndex && firstDisabledIndex !== -1;
51071
+ return (jsxRuntimeExports.jsxs(React.Fragment, { children: [showComingSoon ? (jsxRuntimeExports.jsx("p", { className: PayOptionsStyles.paymentOptionsModal__comingSoonText, children: "Coming Soon" })) : null, jsxRuntimeExports.jsx(RadioButton, { label: label, name: "payment-options", id: key, value: value, disabled: disabled, checked: selectedOption === value, onChange: handleChange })] }, key));
51072
+ });
50916
51073
  }, [paymentMethods, selectedOption]);
50917
51074
  return (jsxRuntimeExports.jsx(Modal, { title: "Payment Options", isOpen: isModalOpen, children: jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsxs("div", { className: PayOptionsStyles.paymentOptionsModal__body, children: [isFetchingMethods && (jsxRuntimeExports.jsx(PaymentOptionsSkeleton, { numberOfSkeletons: 3 })), !isFetchingMethods && renderPaymentOptions] }), jsxRuntimeExports.jsx(Button, { type: "button", disabled: !selectedOption || isLoading, className: PayOptionsStyles.paymentOptionsModal__continueButton, onClick: handleSubmit, mode: "solid", loading: isLoading, children: "Continue" })] }) }));
50918
51075
  };
@@ -50928,28 +51085,29 @@ to {
50928
51085
  };
50929
51086
 
50930
51087
  const PAYMENT_ACTIONS = {
50931
- SET_PAYMENT_STATUS: 'SET_PAYMENT_STATUS',
50932
- SET_PAYMENT_DETAILS: 'SET_PAYMENT_DETAILS',
50933
- SET_ADDITIONAL_AMOUNT: 'SET_ADDITIONAL_AMOUNT',
50934
- RESET_PAYMENT: 'RESET_PAYMENT',
51088
+ SET_PAYMENT_STATUS: "SET_PAYMENT_STATUS",
51089
+ SET_PAYMENT_DETAILS: "SET_PAYMENT_DETAILS",
51090
+ SET_ADDITIONAL_AMOUNT: "SET_ADDITIONAL_AMOUNT",
51091
+ RESET_PAYMENT: "RESET_PAYMENT",
50935
51092
  };
50936
51093
  const MODAL_ACTIONS = {
50937
- SET_OPEN: 'SET_OPEN',
50938
- SET_CURRENT_INDEX: 'SET_CURRENT_INDEX',
50939
- SET_ABOUT_MODAL: 'SET_ABOUT_MODAL',
50940
- RESET_MODAL: 'RESET_MODAL',
51094
+ SET_OPEN: "SET_OPEN",
51095
+ SET_CURRENT_INDEX: "SET_CURRENT_INDEX",
51096
+ SET_ABOUT_MODAL: "SET_ABOUT_MODAL",
51097
+ RESET_MODAL: "RESET_MODAL",
50941
51098
  };
50942
51099
  const DATA_ACTIONS = {
50943
- SET_DATA: 'SET_DATA',
50944
- SET_STORE: 'SET_STORE',
50945
- SET_LOADING: 'SET_LOADING',
50946
- SET_DELIVERY_DETAILS: 'SET_DELIVERY_DETAILS',
50947
- EDIT_ITEM: 'EDIT_ITEM',
50948
- REMOVE_ITEM: 'REMOVE_ITEM',
50949
- RESET_DATA: 'RESET_DATA',
51100
+ SET_DATA: "SET_DATA",
51101
+ SET_STORE: "SET_STORE",
51102
+ SET_LOADING: "SET_LOADING",
51103
+ SET_DELIVERY_DETAILS: "SET_DELIVERY_DETAILS",
51104
+ EDIT_ITEM: "EDIT_ITEM",
51105
+ REMOVE_ITEM: "REMOVE_ITEM",
51106
+ RESET_DATA: "RESET_DATA",
51107
+ SET_PAYMENT_METHOD: "SET_PAYMENT_METHOD",
50950
51108
  };
50951
51109
  const GLOBAL_ACTIONS = {
50952
- RESET_ALL: 'RESET_ALL',
51110
+ RESET_ALL: "RESET_ALL",
50953
51111
  };
50954
51112
 
50955
51113
  /* eslint-disable no-console */
@@ -51045,6 +51203,7 @@ to {
51045
51203
  data: loadCartFromStorage(),
51046
51204
  store: undefined,
51047
51205
  isLoading: false,
51206
+ payment_method: "",
51048
51207
  deliveryDetails: {
51049
51208
  channel: "pickup",
51050
51209
  first_name: "",
@@ -51065,37 +51224,42 @@ to {
51065
51224
  saveCartToStorage(action.payload);
51066
51225
  return {
51067
51226
  ...state,
51068
- data: action.payload
51227
+ data: action.payload,
51069
51228
  };
51070
51229
  case DATA_ACTIONS.SET_STORE:
51071
51230
  return {
51072
51231
  ...state,
51073
- store: action.payload
51232
+ store: action.payload,
51074
51233
  };
51075
51234
  case DATA_ACTIONS.SET_LOADING:
51076
51235
  return {
51077
51236
  ...state,
51078
- isLoading: action.payload
51237
+ isLoading: action.payload,
51238
+ };
51239
+ case DATA_ACTIONS.SET_PAYMENT_METHOD:
51240
+ return {
51241
+ ...state,
51242
+ payment_method: action.payload,
51079
51243
  };
51080
51244
  case DATA_ACTIONS.SET_DELIVERY_DETAILS:
51081
51245
  return {
51082
51246
  ...state,
51083
51247
  deliveryDetails: {
51084
51248
  ...state.deliveryDetails,
51085
- ...action.payload
51086
- }
51249
+ ...action.payload,
51250
+ },
51087
51251
  };
51088
51252
  case DATA_ACTIONS.EDIT_ITEM: {
51089
51253
  const { index, quantity } = action.payload;
51090
51254
  const updatedData = [...state.data];
51091
51255
  updatedData[index] = {
51092
51256
  ...updatedData[index],
51093
- quantity: quantity ?? updatedData[index].quantity
51257
+ quantity: quantity ?? updatedData[index].quantity,
51094
51258
  };
51095
51259
  saveCartToStorage(updatedData);
51096
51260
  return {
51097
51261
  ...state,
51098
- data: updatedData
51262
+ data: updatedData,
51099
51263
  };
51100
51264
  }
51101
51265
  case DATA_ACTIONS.REMOVE_ITEM: {
@@ -51103,7 +51267,7 @@ to {
51103
51267
  saveCartToStorage(filteredData);
51104
51268
  return {
51105
51269
  ...state,
51106
- data: filteredData
51270
+ data: filteredData,
51107
51271
  };
51108
51272
  }
51109
51273
  case DATA_ACTIONS.RESET_DATA:
@@ -51184,23 +51348,27 @@ to {
51184
51348
 
51185
51349
  const setData = (data) => ({
51186
51350
  type: DATA_ACTIONS.SET_DATA,
51187
- payload: data
51351
+ payload: data,
51188
51352
  });
51189
51353
  const setLoading = (isLoading) => ({
51190
51354
  type: DATA_ACTIONS.SET_LOADING,
51191
- payload: isLoading
51355
+ payload: isLoading,
51356
+ });
51357
+ const setPaymentMethod = (method) => ({
51358
+ type: DATA_ACTIONS.SET_PAYMENT_METHOD,
51359
+ payload: method,
51192
51360
  });
51193
51361
  const setDeliveryDetails = (details) => ({
51194
51362
  type: DATA_ACTIONS.SET_DELIVERY_DETAILS,
51195
- payload: details
51363
+ payload: details,
51196
51364
  });
51197
51365
  const editItemQuantity = (index, quantity) => ({
51198
51366
  type: DATA_ACTIONS.EDIT_ITEM,
51199
- payload: { index, quantity }
51367
+ payload: { index, quantity },
51200
51368
  });
51201
51369
  const removeItem = (index) => ({
51202
51370
  type: DATA_ACTIONS.REMOVE_ITEM,
51203
- payload: index
51371
+ payload: index,
51204
51372
  });
51205
51373
 
51206
51374
  const setOpen = (isOpen) => ({
@@ -51233,7 +51401,7 @@ to {
51233
51401
  data: initialDataState,
51234
51402
  };
51235
51403
  const [state, dispatch] = reactExports.useReducer(rootReducer, initialState);
51236
- const { payment: { paymentStatus, paymentDetails, additionalAmount }, modal: { open, currentIndex, isOpenAboutModal }, data: { data, store, isLoading, deliveryDetails }, } = state;
51404
+ const { payment: { paymentStatus, paymentDetails, additionalAmount }, modal: { open, currentIndex, isOpenAboutModal }, data: { data, store, isLoading, deliveryDetails, payment_method }, } = state;
51237
51405
  const currentModal = ModalNames[Object.values(ModalNames)[currentIndex]];
51238
51406
  // const router = useRouter();
51239
51407
  const openModal = () => {
@@ -51330,6 +51498,9 @@ to {
51330
51498
  const setPaymentStatus$1 = (status) => {
51331
51499
  dispatch(setPaymentStatus(status));
51332
51500
  };
51501
+ const setPaymentMethod$1 = (method) => {
51502
+ dispatch(setPaymentMethod(method));
51503
+ };
51333
51504
  const setAdditionalAmount$1 = (amount) => {
51334
51505
  dispatch(setAdditionalAmount(amount));
51335
51506
  };
@@ -51353,6 +51524,7 @@ to {
51353
51524
  paymentDetails,
51354
51525
  paymentStatus,
51355
51526
  setPaymentStatus: setPaymentStatus$1,
51527
+ setPaymentMethod: setPaymentMethod$1,
51356
51528
  additionalAmount,
51357
51529
  setAdditionalAmount: setAdditionalAmount$1,
51358
51530
  editItemQuantity: editItemQuantity$1,
@@ -51377,6 +51549,7 @@ to {
51377
51549
  paymentDetails,
51378
51550
  paymentStatus,
51379
51551
  setPaymentStatus$1,
51552
+ setPaymentMethod$1,
51380
51553
  additionalAmount,
51381
51554
  setAdditionalAmount$1,
51382
51555
  editItemQuantity$1,
@@ -51396,15 +51569,2728 @@ to {
51396
51569
  return (jsxRuntimeExports.jsx(ModalContext.Provider, { value: value, children: jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx(Modals, {}), children] }) }));
51397
51570
  };
51398
51571
 
51572
+ /**
51573
+ * Based on Kendo UI Core expression code <https://github.com/telerik/kendo-ui-core#license-information>
51574
+ */
51575
+
51576
+ function Cache(maxSize) {
51577
+ this._maxSize = maxSize;
51578
+ this.clear();
51579
+ }
51580
+ Cache.prototype.clear = function () {
51581
+ this._size = 0;
51582
+ this._values = Object.create(null);
51583
+ };
51584
+ Cache.prototype.get = function (key) {
51585
+ return this._values[key]
51586
+ };
51587
+ Cache.prototype.set = function (key, value) {
51588
+ this._size >= this._maxSize && this.clear();
51589
+ if (!(key in this._values)) this._size++;
51590
+
51591
+ return (this._values[key] = value)
51592
+ };
51593
+
51594
+ var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g,
51595
+ DIGIT_REGEX = /^\d+$/,
51596
+ LEAD_DIGIT_REGEX = /^\d/,
51597
+ SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g,
51598
+ CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/,
51599
+ MAX_CACHE_SIZE = 512;
51600
+
51601
+ var pathCache = new Cache(MAX_CACHE_SIZE),
51602
+ setCache = new Cache(MAX_CACHE_SIZE),
51603
+ getCache = new Cache(MAX_CACHE_SIZE);
51604
+
51605
+ var propertyExpr = {
51606
+ Cache: Cache,
51607
+
51608
+ split: split,
51609
+
51610
+ normalizePath: normalizePath,
51611
+
51612
+ setter: function (path) {
51613
+ var parts = normalizePath(path);
51614
+
51615
+ return (
51616
+ setCache.get(path) ||
51617
+ setCache.set(path, function setter(obj, value) {
51618
+ var index = 0;
51619
+ var len = parts.length;
51620
+ var data = obj;
51621
+
51622
+ while (index < len - 1) {
51623
+ var part = parts[index];
51624
+ if (
51625
+ part === '__proto__' ||
51626
+ part === 'constructor' ||
51627
+ part === 'prototype'
51628
+ ) {
51629
+ return obj
51630
+ }
51631
+
51632
+ data = data[parts[index++]];
51633
+ }
51634
+ data[parts[index]] = value;
51635
+ })
51636
+ )
51637
+ },
51638
+
51639
+ getter: function (path, safe) {
51640
+ var parts = normalizePath(path);
51641
+ return (
51642
+ getCache.get(path) ||
51643
+ getCache.set(path, function getter(data) {
51644
+ var index = 0,
51645
+ len = parts.length;
51646
+ while (index < len) {
51647
+ if (data != null || !safe) data = data[parts[index++]];
51648
+ else return
51649
+ }
51650
+ return data
51651
+ })
51652
+ )
51653
+ },
51654
+
51655
+ join: function (segments) {
51656
+ return segments.reduce(function (path, part) {
51657
+ return (
51658
+ path +
51659
+ (isQuoted(part) || DIGIT_REGEX.test(part)
51660
+ ? '[' + part + ']'
51661
+ : (path ? '.' : '') + part)
51662
+ )
51663
+ }, '')
51664
+ },
51665
+
51666
+ forEach: function (path, cb, thisArg) {
51667
+ forEach(Array.isArray(path) ? path : split(path), cb, thisArg);
51668
+ },
51669
+ };
51670
+
51671
+ function normalizePath(path) {
51672
+ return (
51673
+ pathCache.get(path) ||
51674
+ pathCache.set(
51675
+ path,
51676
+ split(path).map(function (part) {
51677
+ return part.replace(CLEAN_QUOTES_REGEX, '$2')
51678
+ })
51679
+ )
51680
+ )
51681
+ }
51682
+
51683
+ function split(path) {
51684
+ return path.match(SPLIT_REGEX) || ['']
51685
+ }
51686
+
51687
+ function forEach(parts, iter, thisArg) {
51688
+ var len = parts.length,
51689
+ part,
51690
+ idx,
51691
+ isArray,
51692
+ isBracket;
51693
+
51694
+ for (idx = 0; idx < len; idx++) {
51695
+ part = parts[idx];
51696
+
51697
+ if (part) {
51698
+ if (shouldBeQuoted(part)) {
51699
+ part = '"' + part + '"';
51700
+ }
51701
+
51702
+ isBracket = isQuoted(part);
51703
+ isArray = !isBracket && /^\d+$/.test(part);
51704
+
51705
+ iter.call(thisArg, part, isBracket, isArray, idx, parts);
51706
+ }
51707
+ }
51708
+ }
51709
+
51710
+ function isQuoted(str) {
51711
+ return (
51712
+ typeof str === 'string' && str && ["'", '"'].indexOf(str.charAt(0)) !== -1
51713
+ )
51714
+ }
51715
+
51716
+ function hasLeadingNumber(part) {
51717
+ return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX)
51718
+ }
51719
+
51720
+ function hasSpecialChars(part) {
51721
+ return SPEC_CHAR_REGEX.test(part)
51722
+ }
51723
+
51724
+ function shouldBeQuoted(part) {
51725
+ return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part))
51726
+ }
51727
+
51728
+ const reWords = /[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g;
51729
+
51730
+ const words = (str) => str.match(reWords) || [];
51731
+
51732
+ const upperFirst = (str) => str[0].toUpperCase() + str.slice(1);
51733
+
51734
+ const join = (str, d) => words(str).join(d).toLowerCase();
51735
+
51736
+ const camelCase = (str) =>
51737
+ words(str).reduce(
51738
+ (acc, next) =>
51739
+ `${acc}${
51740
+ !acc
51741
+ ? next.toLowerCase()
51742
+ : next[0].toUpperCase() + next.slice(1).toLowerCase()
51743
+ }`,
51744
+ '',
51745
+ );
51746
+
51747
+ const pascalCase = (str) => upperFirst(camelCase(str));
51748
+
51749
+ const snakeCase = (str) => join(str, '_');
51750
+
51751
+ const kebabCase = (str) => join(str, '-');
51752
+
51753
+ const sentenceCase = (str) => upperFirst(join(str, ' '));
51754
+
51755
+ const titleCase = (str) => words(str).map(upperFirst).join(' ');
51756
+
51757
+ var tinyCase = {
51758
+ words,
51759
+ upperFirst,
51760
+ camelCase,
51761
+ pascalCase,
51762
+ snakeCase,
51763
+ kebabCase,
51764
+ sentenceCase,
51765
+ titleCase,
51766
+ };
51767
+
51768
+ var toposort$2 = {exports: {}};
51769
+
51770
+ /**
51771
+ * Topological sorting function
51772
+ *
51773
+ * @param {Array} edges
51774
+ * @returns {Array}
51775
+ */
51776
+
51777
+ toposort$2.exports = function(edges) {
51778
+ return toposort(uniqueNodes(edges), edges)
51779
+ };
51780
+
51781
+ toposort$2.exports.array = toposort;
51782
+
51783
+ function toposort(nodes, edges) {
51784
+ var cursor = nodes.length
51785
+ , sorted = new Array(cursor)
51786
+ , visited = {}
51787
+ , i = cursor
51788
+ // Better data structures make algorithm much faster.
51789
+ , outgoingEdges = makeOutgoingEdges(edges)
51790
+ , nodesHash = makeNodesHash(nodes);
51791
+
51792
+ // check for unknown nodes
51793
+ edges.forEach(function(edge) {
51794
+ if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {
51795
+ throw new Error('Unknown node. There is an unknown node in the supplied edges.')
51796
+ }
51797
+ });
51798
+
51799
+ while (i--) {
51800
+ if (!visited[i]) visit(nodes[i], i, new Set());
51801
+ }
51802
+
51803
+ return sorted
51804
+
51805
+ function visit(node, i, predecessors) {
51806
+ if(predecessors.has(node)) {
51807
+ var nodeRep;
51808
+ try {
51809
+ nodeRep = ", node was:" + JSON.stringify(node);
51810
+ } catch(e) {
51811
+ nodeRep = "";
51812
+ }
51813
+ throw new Error('Cyclic dependency' + nodeRep)
51814
+ }
51815
+
51816
+ if (!nodesHash.has(node)) {
51817
+ throw new Error('Found unknown node. Make sure to provided all involved nodes. Unknown node: '+JSON.stringify(node))
51818
+ }
51819
+
51820
+ if (visited[i]) return;
51821
+ visited[i] = true;
51822
+
51823
+ var outgoing = outgoingEdges.get(node) || new Set();
51824
+ outgoing = Array.from(outgoing);
51825
+
51826
+ if (i = outgoing.length) {
51827
+ predecessors.add(node);
51828
+ do {
51829
+ var child = outgoing[--i];
51830
+ visit(child, nodesHash.get(child), predecessors);
51831
+ } while (i)
51832
+ predecessors.delete(node);
51833
+ }
51834
+
51835
+ sorted[--cursor] = node;
51836
+ }
51837
+ }
51838
+
51839
+ function uniqueNodes(arr){
51840
+ var res = new Set();
51841
+ for (var i = 0, len = arr.length; i < len; i++) {
51842
+ var edge = arr[i];
51843
+ res.add(edge[0]);
51844
+ res.add(edge[1]);
51845
+ }
51846
+ return Array.from(res)
51847
+ }
51848
+
51849
+ function makeOutgoingEdges(arr){
51850
+ var edges = new Map();
51851
+ for (var i = 0, len = arr.length; i < len; i++) {
51852
+ var edge = arr[i];
51853
+ if (!edges.has(edge[0])) edges.set(edge[0], new Set());
51854
+ if (!edges.has(edge[1])) edges.set(edge[1], new Set());
51855
+ edges.get(edge[0]).add(edge[1]);
51856
+ }
51857
+ return edges
51858
+ }
51859
+
51860
+ function makeNodesHash(arr){
51861
+ var res = new Map();
51862
+ for (var i = 0, len = arr.length; i < len; i++) {
51863
+ res.set(arr[i], i);
51864
+ }
51865
+ return res
51866
+ }
51867
+
51868
+ var toposortExports = toposort$2.exports;
51869
+ var toposort$1 = /*@__PURE__*/getDefaultExportFromCjs(toposortExports);
51870
+
51871
+ const toString = Object.prototype.toString;
51872
+ const errorToString = Error.prototype.toString;
51873
+ const regExpToString = RegExp.prototype.toString;
51874
+ const symbolToString = typeof Symbol !== 'undefined' ? Symbol.prototype.toString : () => '';
51875
+ const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
51876
+ function printNumber(val) {
51877
+ if (val != +val) return 'NaN';
51878
+ const isNegativeZero = val === 0 && 1 / val < 0;
51879
+ return isNegativeZero ? '-0' : '' + val;
51880
+ }
51881
+ function printSimpleValue(val, quoteStrings = false) {
51882
+ if (val == null || val === true || val === false) return '' + val;
51883
+ const typeOf = typeof val;
51884
+ if (typeOf === 'number') return printNumber(val);
51885
+ if (typeOf === 'string') return quoteStrings ? `"${val}"` : val;
51886
+ if (typeOf === 'function') return '[Function ' + (val.name || 'anonymous') + ']';
51887
+ if (typeOf === 'symbol') return symbolToString.call(val).replace(SYMBOL_REGEXP, 'Symbol($1)');
51888
+ const tag = toString.call(val).slice(8, -1);
51889
+ if (tag === 'Date') return isNaN(val.getTime()) ? '' + val : val.toISOString(val);
51890
+ if (tag === 'Error' || val instanceof Error) return '[' + errorToString.call(val) + ']';
51891
+ if (tag === 'RegExp') return regExpToString.call(val);
51892
+ return null;
51893
+ }
51894
+ function printValue(value, quoteStrings) {
51895
+ let result = printSimpleValue(value, quoteStrings);
51896
+ if (result !== null) return result;
51897
+ return JSON.stringify(value, function (key, value) {
51898
+ let result = printSimpleValue(this[key], quoteStrings);
51899
+ if (result !== null) return result;
51900
+ return value;
51901
+ }, 2);
51902
+ }
51903
+
51904
+ function toArray(value) {
51905
+ return value == null ? [] : [].concat(value);
51906
+ }
51907
+
51908
+ let _Symbol$toStringTag, _Symbol$hasInstance, _Symbol$toStringTag2;
51909
+ let strReg = /\$\{\s*(\w+)\s*\}/g;
51910
+ _Symbol$toStringTag = Symbol.toStringTag;
51911
+ class ValidationErrorNoStack {
51912
+ constructor(errorOrErrors, value, field, type) {
51913
+ this.name = void 0;
51914
+ this.message = void 0;
51915
+ this.value = void 0;
51916
+ this.path = void 0;
51917
+ this.type = void 0;
51918
+ this.params = void 0;
51919
+ this.errors = void 0;
51920
+ this.inner = void 0;
51921
+ this[_Symbol$toStringTag] = 'Error';
51922
+ this.name = 'ValidationError';
51923
+ this.value = value;
51924
+ this.path = field;
51925
+ this.type = type;
51926
+ this.errors = [];
51927
+ this.inner = [];
51928
+ toArray(errorOrErrors).forEach(err => {
51929
+ if (ValidationError.isError(err)) {
51930
+ this.errors.push(...err.errors);
51931
+ const innerErrors = err.inner.length ? err.inner : [err];
51932
+ this.inner.push(...innerErrors);
51933
+ } else {
51934
+ this.errors.push(err);
51935
+ }
51936
+ });
51937
+ this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];
51938
+ }
51939
+ }
51940
+ _Symbol$hasInstance = Symbol.hasInstance;
51941
+ _Symbol$toStringTag2 = Symbol.toStringTag;
51942
+ class ValidationError extends Error {
51943
+ static formatError(message, params) {
51944
+ // Attempt to make the path more friendly for error message interpolation.
51945
+ const path = params.label || params.path || 'this';
51946
+ // Store the original path under `originalPath` so it isn't lost to custom
51947
+ // message functions; e.g., ones provided in `setLocale()` calls.
51948
+ params = Object.assign({}, params, {
51949
+ path,
51950
+ originalPath: params.path
51951
+ });
51952
+ if (typeof message === 'string') return message.replace(strReg, (_, key) => printValue(params[key]));
51953
+ if (typeof message === 'function') return message(params);
51954
+ return message;
51955
+ }
51956
+ static isError(err) {
51957
+ return err && err.name === 'ValidationError';
51958
+ }
51959
+ constructor(errorOrErrors, value, field, type, disableStack) {
51960
+ const errorNoStack = new ValidationErrorNoStack(errorOrErrors, value, field, type);
51961
+ if (disableStack) {
51962
+ return errorNoStack;
51963
+ }
51964
+ super();
51965
+ this.value = void 0;
51966
+ this.path = void 0;
51967
+ this.type = void 0;
51968
+ this.params = void 0;
51969
+ this.errors = [];
51970
+ this.inner = [];
51971
+ this[_Symbol$toStringTag2] = 'Error';
51972
+ this.name = errorNoStack.name;
51973
+ this.message = errorNoStack.message;
51974
+ this.type = errorNoStack.type;
51975
+ this.value = errorNoStack.value;
51976
+ this.path = errorNoStack.path;
51977
+ this.errors = errorNoStack.errors;
51978
+ this.inner = errorNoStack.inner;
51979
+ if (Error.captureStackTrace) {
51980
+ Error.captureStackTrace(this, ValidationError);
51981
+ }
51982
+ }
51983
+ static [_Symbol$hasInstance](inst) {
51984
+ return ValidationErrorNoStack[Symbol.hasInstance](inst) || super[Symbol.hasInstance](inst);
51985
+ }
51986
+ }
51987
+
51988
+ let mixed = {
51989
+ default: '${path} is invalid',
51990
+ required: '${path} is a required field',
51991
+ defined: '${path} must be defined',
51992
+ notNull: '${path} cannot be null',
51993
+ oneOf: '${path} must be one of the following values: ${values}',
51994
+ notOneOf: '${path} must not be one of the following values: ${values}',
51995
+ notType: ({
51996
+ path,
51997
+ type,
51998
+ value,
51999
+ originalValue
52000
+ }) => {
52001
+ const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : '.';
52002
+ return type !== 'mixed' ? `${path} must be a \`${type}\` type, ` + `but the final value was: \`${printValue(value, true)}\`` + castMsg : `${path} must match the configured type. ` + `The validated value was: \`${printValue(value, true)}\`` + castMsg;
52003
+ }
52004
+ };
52005
+ let string = {
52006
+ length: '${path} must be exactly ${length} characters',
52007
+ min: '${path} must be at least ${min} characters',
52008
+ max: '${path} must be at most ${max} characters',
52009
+ matches: '${path} must match the following: "${regex}"',
52010
+ email: '${path} must be a valid email',
52011
+ url: '${path} must be a valid URL',
52012
+ uuid: '${path} must be a valid UUID',
52013
+ datetime: '${path} must be a valid ISO date-time',
52014
+ datetime_precision: '${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits',
52015
+ datetime_offset: '${path} must be a valid ISO date-time with UTC "Z" timezone',
52016
+ trim: '${path} must be a trimmed string',
52017
+ lowercase: '${path} must be a lowercase string',
52018
+ uppercase: '${path} must be a upper case string'
52019
+ };
52020
+ let number = {
52021
+ min: '${path} must be greater than or equal to ${min}',
52022
+ max: '${path} must be less than or equal to ${max}',
52023
+ lessThan: '${path} must be less than ${less}',
52024
+ moreThan: '${path} must be greater than ${more}',
52025
+ positive: '${path} must be a positive number',
52026
+ negative: '${path} must be a negative number',
52027
+ integer: '${path} must be an integer'
52028
+ };
52029
+ let date = {
52030
+ min: '${path} field must be later than ${min}',
52031
+ max: '${path} field must be at earlier than ${max}'
52032
+ };
52033
+ let boolean = {
52034
+ isValue: '${path} field must be ${value}'
52035
+ };
52036
+ let object = {
52037
+ noUnknown: '${path} field has unspecified keys: ${unknown}',
52038
+ exact: '${path} object contains unknown properties: ${properties}'
52039
+ };
52040
+ let array = {
52041
+ min: '${path} field must have at least ${min} items',
52042
+ max: '${path} field must have less than or equal to ${max} items',
52043
+ length: '${path} must have ${length} items'
52044
+ };
52045
+ let tuple = {
52046
+ notType: params => {
52047
+ const {
52048
+ path,
52049
+ value,
52050
+ spec
52051
+ } = params;
52052
+ const typeLen = spec.types.length;
52053
+ if (Array.isArray(value)) {
52054
+ if (value.length < typeLen) return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
52055
+ if (value.length > typeLen) return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
52056
+ }
52057
+ return ValidationError.formatError(mixed.notType, params);
52058
+ }
52059
+ };
52060
+ Object.assign(Object.create(null), {
52061
+ mixed,
52062
+ string,
52063
+ number,
52064
+ date,
52065
+ object,
52066
+ array,
52067
+ boolean,
52068
+ tuple
52069
+ });
52070
+
52071
+ const isSchema = obj => obj && obj.__isYupSchema__;
52072
+
52073
+ class Condition {
52074
+ static fromOptions(refs, config) {
52075
+ if (!config.then && !config.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');
52076
+ let {
52077
+ is,
52078
+ then,
52079
+ otherwise
52080
+ } = config;
52081
+ let check = typeof is === 'function' ? is : (...values) => values.every(value => value === is);
52082
+ return new Condition(refs, (values, schema) => {
52083
+ var _branch;
52084
+ let branch = check(...values) ? then : otherwise;
52085
+ return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;
52086
+ });
52087
+ }
52088
+ constructor(refs, builder) {
52089
+ this.fn = void 0;
52090
+ this.refs = refs;
52091
+ this.refs = refs;
52092
+ this.fn = builder;
52093
+ }
52094
+ resolve(base, options) {
52095
+ let values = this.refs.map(ref =>
52096
+ // TODO: ? operator here?
52097
+ ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context));
52098
+ let schema = this.fn(values, base, options);
52099
+ if (schema === undefined ||
52100
+ // @ts-ignore this can be base
52101
+ schema === base) {
52102
+ return base;
52103
+ }
52104
+ if (!isSchema(schema)) throw new TypeError('conditions must return a schema object');
52105
+ return schema.resolve(options);
52106
+ }
52107
+ }
52108
+
52109
+ const prefixes = {
52110
+ context: '$',
52111
+ value: '.'
52112
+ };
52113
+ class Reference {
52114
+ constructor(key, options = {}) {
52115
+ this.key = void 0;
52116
+ this.isContext = void 0;
52117
+ this.isValue = void 0;
52118
+ this.isSibling = void 0;
52119
+ this.path = void 0;
52120
+ this.getter = void 0;
52121
+ this.map = void 0;
52122
+ if (typeof key !== 'string') throw new TypeError('ref must be a string, got: ' + key);
52123
+ this.key = key.trim();
52124
+ if (key === '') throw new TypeError('ref must be a non-empty string');
52125
+ this.isContext = this.key[0] === prefixes.context;
52126
+ this.isValue = this.key[0] === prefixes.value;
52127
+ this.isSibling = !this.isContext && !this.isValue;
52128
+ let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : '';
52129
+ this.path = this.key.slice(prefix.length);
52130
+ this.getter = this.path && propertyExpr.getter(this.path, true);
52131
+ this.map = options.map;
52132
+ }
52133
+ getValue(value, parent, context) {
52134
+ let result = this.isContext ? context : this.isValue ? value : parent;
52135
+ if (this.getter) result = this.getter(result || {});
52136
+ if (this.map) result = this.map(result);
52137
+ return result;
52138
+ }
52139
+
52140
+ /**
52141
+ *
52142
+ * @param {*} value
52143
+ * @param {Object} options
52144
+ * @param {Object=} options.context
52145
+ * @param {Object=} options.parent
52146
+ */
52147
+ cast(value, options) {
52148
+ return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);
52149
+ }
52150
+ resolve() {
52151
+ return this;
52152
+ }
52153
+ describe() {
52154
+ return {
52155
+ type: 'ref',
52156
+ key: this.key
52157
+ };
52158
+ }
52159
+ toString() {
52160
+ return `Ref(${this.key})`;
52161
+ }
52162
+ static isRef(value) {
52163
+ return value && value.__isYupRef;
52164
+ }
52165
+ }
52166
+
52167
+ // @ts-ignore
52168
+ Reference.prototype.__isYupRef = true;
52169
+
52170
+ const isAbsent = value => value == null;
52171
+
52172
+ function createValidation(config) {
52173
+ function validate({
52174
+ value,
52175
+ path = '',
52176
+ options,
52177
+ originalValue,
52178
+ schema
52179
+ }, panic, next) {
52180
+ const {
52181
+ name,
52182
+ test,
52183
+ params,
52184
+ message,
52185
+ skipAbsent
52186
+ } = config;
52187
+ let {
52188
+ parent,
52189
+ context,
52190
+ abortEarly = schema.spec.abortEarly,
52191
+ disableStackTrace = schema.spec.disableStackTrace
52192
+ } = options;
52193
+ const resolveOptions = {
52194
+ value,
52195
+ parent,
52196
+ context
52197
+ };
52198
+ function createError(overrides = {}) {
52199
+ const nextParams = resolveParams(Object.assign({
52200
+ value,
52201
+ originalValue,
52202
+ label: schema.spec.label,
52203
+ path: overrides.path || path,
52204
+ spec: schema.spec,
52205
+ disableStackTrace: overrides.disableStackTrace || disableStackTrace
52206
+ }, params, overrides.params), resolveOptions);
52207
+ const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, nextParams.disableStackTrace);
52208
+ error.params = nextParams;
52209
+ return error;
52210
+ }
52211
+ const invalid = abortEarly ? panic : next;
52212
+ let ctx = {
52213
+ path,
52214
+ parent,
52215
+ type: name,
52216
+ from: options.from,
52217
+ createError,
52218
+ resolve(item) {
52219
+ return resolveMaybeRef(item, resolveOptions);
52220
+ },
52221
+ options,
52222
+ originalValue,
52223
+ schema
52224
+ };
52225
+ const handleResult = validOrError => {
52226
+ if (ValidationError.isError(validOrError)) invalid(validOrError);else if (!validOrError) invalid(createError());else next(null);
52227
+ };
52228
+ const handleError = err => {
52229
+ if (ValidationError.isError(err)) invalid(err);else panic(err);
52230
+ };
52231
+ const shouldSkip = skipAbsent && isAbsent(value);
52232
+ if (shouldSkip) {
52233
+ return handleResult(true);
52234
+ }
52235
+ let result;
52236
+ try {
52237
+ var _result;
52238
+ result = test.call(ctx, value, ctx);
52239
+ if (typeof ((_result = result) == null ? void 0 : _result.then) === 'function') {
52240
+ if (options.sync) {
52241
+ throw new Error(`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. ` + `This test will finish after the validate call has returned`);
52242
+ }
52243
+ return Promise.resolve(result).then(handleResult, handleError);
52244
+ }
52245
+ } catch (err) {
52246
+ handleError(err);
52247
+ return;
52248
+ }
52249
+ handleResult(result);
52250
+ }
52251
+ validate.OPTIONS = config;
52252
+ return validate;
52253
+ }
52254
+
52255
+ // Warning: mutates the input
52256
+ function resolveParams(params, options) {
52257
+ if (!params) return params;
52258
+ for (const key of Object.keys(params)) {
52259
+ params[key] = resolveMaybeRef(params[key], options);
52260
+ }
52261
+ return params;
52262
+ }
52263
+ function resolveMaybeRef(item, options) {
52264
+ return Reference.isRef(item) ? item.getValue(options.value, options.parent, options.context) : item;
52265
+ }
52266
+
52267
+ function getIn(schema, path, value, context = value) {
52268
+ let parent, lastPart, lastPartDebug;
52269
+
52270
+ // root path: ''
52271
+ if (!path) return {
52272
+ parent,
52273
+ parentPath: path,
52274
+ schema
52275
+ };
52276
+ propertyExpr.forEach(path, (_part, isBracket, isArray) => {
52277
+ let part = isBracket ? _part.slice(1, _part.length - 1) : _part;
52278
+ schema = schema.resolve({
52279
+ context,
52280
+ parent,
52281
+ value
52282
+ });
52283
+ let isTuple = schema.type === 'tuple';
52284
+ let idx = isArray ? parseInt(part, 10) : 0;
52285
+ if (schema.innerType || isTuple) {
52286
+ if (isTuple && !isArray) throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${lastPartDebug}" must contain an index to the tuple element, e.g. "${lastPartDebug}[0]"`);
52287
+ if (value && idx >= value.length) {
52288
+ throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. ` + `because there is no value at that index. `);
52289
+ }
52290
+ parent = value;
52291
+ value = value && value[idx];
52292
+ schema = isTuple ? schema.spec.types[idx] : schema.innerType;
52293
+ }
52294
+
52295
+ // sometimes the array index part of a path doesn't exist: "nested.arr.child"
52296
+ // in these cases the current part is the next schema and should be processed
52297
+ // in this iteration. For cases where the index signature is included this
52298
+ // check will fail and we'll handle the `child` part on the next iteration like normal
52299
+ if (!isArray) {
52300
+ if (!schema.fields || !schema.fields[part]) throw new Error(`The schema does not contain the path: ${path}. ` + `(failed at: ${lastPartDebug} which is a type: "${schema.type}")`);
52301
+ parent = value;
52302
+ value = value && value[part];
52303
+ schema = schema.fields[part];
52304
+ }
52305
+ lastPart = part;
52306
+ lastPartDebug = isBracket ? '[' + _part + ']' : '.' + _part;
52307
+ });
52308
+ return {
52309
+ schema,
52310
+ parent,
52311
+ parentPath: lastPart
52312
+ };
52313
+ }
52314
+
52315
+ class ReferenceSet extends Set {
52316
+ describe() {
52317
+ const description = [];
52318
+ for (const item of this.values()) {
52319
+ description.push(Reference.isRef(item) ? item.describe() : item);
52320
+ }
52321
+ return description;
52322
+ }
52323
+ resolveAll(resolve) {
52324
+ let result = [];
52325
+ for (const item of this.values()) {
52326
+ result.push(resolve(item));
52327
+ }
52328
+ return result;
52329
+ }
52330
+ clone() {
52331
+ return new ReferenceSet(this.values());
52332
+ }
52333
+ merge(newItems, removeItems) {
52334
+ const next = this.clone();
52335
+ newItems.forEach(value => next.add(value));
52336
+ removeItems.forEach(value => next.delete(value));
52337
+ return next;
52338
+ }
52339
+ }
52340
+
52341
+ // tweaked from https://github.com/Kelin2025/nanoclone/blob/0abeb7635bda9b68ef2277093f76dbe3bf3948e1/src/index.js
52342
+ function clone(src, seen = new Map()) {
52343
+ if (isSchema(src) || !src || typeof src !== 'object') return src;
52344
+ if (seen.has(src)) return seen.get(src);
52345
+ let copy;
52346
+ if (src instanceof Date) {
52347
+ // Date
52348
+ copy = new Date(src.getTime());
52349
+ seen.set(src, copy);
52350
+ } else if (src instanceof RegExp) {
52351
+ // RegExp
52352
+ copy = new RegExp(src);
52353
+ seen.set(src, copy);
52354
+ } else if (Array.isArray(src)) {
52355
+ // Array
52356
+ copy = new Array(src.length);
52357
+ seen.set(src, copy);
52358
+ for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);
52359
+ } else if (src instanceof Map) {
52360
+ // Map
52361
+ copy = new Map();
52362
+ seen.set(src, copy);
52363
+ for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));
52364
+ } else if (src instanceof Set) {
52365
+ // Set
52366
+ copy = new Set();
52367
+ seen.set(src, copy);
52368
+ for (const v of src) copy.add(clone(v, seen));
52369
+ } else if (src instanceof Object) {
52370
+ // Object
52371
+ copy = {};
52372
+ seen.set(src, copy);
52373
+ for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);
52374
+ } else {
52375
+ throw Error(`Unable to clone ${src}`);
52376
+ }
52377
+ return copy;
52378
+ }
52379
+
52380
+ /**
52381
+ * Copied from @standard-schema/spec to avoid having a dependency on it.
52382
+ * https://github.com/standard-schema/standard-schema/blob/main/packages/spec/src/index.ts
52383
+ */
52384
+
52385
+ function createStandardPath(path) {
52386
+ if (!(path != null && path.length)) {
52387
+ return undefined;
52388
+ }
52389
+
52390
+ // Array to store the final path segments
52391
+ const segments = [];
52392
+ // Buffer for building the current segment
52393
+ let currentSegment = '';
52394
+ // Track if we're inside square brackets (array/property access)
52395
+ let inBrackets = false;
52396
+ // Track if we're inside quotes (for property names with special chars)
52397
+ let inQuotes = false;
52398
+ for (let i = 0; i < path.length; i++) {
52399
+ const char = path[i];
52400
+ if (char === '[' && !inQuotes) {
52401
+ // When entering brackets, push any accumulated segment after splitting on dots
52402
+ if (currentSegment) {
52403
+ segments.push(...currentSegment.split('.').filter(Boolean));
52404
+ currentSegment = '';
52405
+ }
52406
+ inBrackets = true;
52407
+ continue;
52408
+ }
52409
+ if (char === ']' && !inQuotes) {
52410
+ if (currentSegment) {
52411
+ // Handle numeric indices (e.g. arr[0])
52412
+ if (/^\d+$/.test(currentSegment)) {
52413
+ segments.push(currentSegment);
52414
+ } else {
52415
+ // Handle quoted property names (e.g. obj["foo.bar"])
52416
+ segments.push(currentSegment.replace(/^"|"$/g, ''));
52417
+ }
52418
+ currentSegment = '';
52419
+ }
52420
+ inBrackets = false;
52421
+ continue;
52422
+ }
52423
+ if (char === '"') {
52424
+ // Toggle quote state for handling quoted property names
52425
+ inQuotes = !inQuotes;
52426
+ continue;
52427
+ }
52428
+ if (char === '.' && !inBrackets && !inQuotes) {
52429
+ // On dots outside brackets/quotes, push current segment
52430
+ if (currentSegment) {
52431
+ segments.push(currentSegment);
52432
+ currentSegment = '';
52433
+ }
52434
+ continue;
52435
+ }
52436
+ currentSegment += char;
52437
+ }
52438
+
52439
+ // Push any remaining segment after splitting on dots
52440
+ if (currentSegment) {
52441
+ segments.push(...currentSegment.split('.').filter(Boolean));
52442
+ }
52443
+ return segments;
52444
+ }
52445
+ function createStandardIssues(error, parentPath) {
52446
+ const path = parentPath ? `${parentPath}.${error.path}` : error.path;
52447
+ return error.errors.map(err => ({
52448
+ message: err,
52449
+ path: createStandardPath(path)
52450
+ }));
52451
+ }
52452
+ function issuesFromValidationError(error, parentPath) {
52453
+ var _error$inner;
52454
+ if (!((_error$inner = error.inner) != null && _error$inner.length) && error.errors.length) {
52455
+ return createStandardIssues(error, parentPath);
52456
+ }
52457
+ const path = parentPath ? `${parentPath}.${error.path}` : error.path;
52458
+ return error.inner.flatMap(err => issuesFromValidationError(err, path));
52459
+ }
52460
+
52461
+ // If `CustomSchemaMeta` isn't extended with any keys, we'll fall back to a
52462
+ // loose Record definition allowing free form usage.
52463
+ class Schema {
52464
+ constructor(options) {
52465
+ this.type = void 0;
52466
+ this.deps = [];
52467
+ this.tests = void 0;
52468
+ this.transforms = void 0;
52469
+ this.conditions = [];
52470
+ this._mutate = void 0;
52471
+ this.internalTests = {};
52472
+ this._whitelist = new ReferenceSet();
52473
+ this._blacklist = new ReferenceSet();
52474
+ this.exclusiveTests = Object.create(null);
52475
+ this._typeCheck = void 0;
52476
+ this.spec = void 0;
52477
+ this.tests = [];
52478
+ this.transforms = [];
52479
+ this.withMutation(() => {
52480
+ this.typeError(mixed.notType);
52481
+ });
52482
+ this.type = options.type;
52483
+ this._typeCheck = options.check;
52484
+ this.spec = Object.assign({
52485
+ strip: false,
52486
+ strict: false,
52487
+ abortEarly: true,
52488
+ recursive: true,
52489
+ disableStackTrace: false,
52490
+ nullable: false,
52491
+ optional: true,
52492
+ coerce: true
52493
+ }, options == null ? void 0 : options.spec);
52494
+ this.withMutation(s => {
52495
+ s.nonNullable();
52496
+ });
52497
+ }
52498
+
52499
+ // TODO: remove
52500
+ get _type() {
52501
+ return this.type;
52502
+ }
52503
+ clone(spec) {
52504
+ if (this._mutate) {
52505
+ if (spec) Object.assign(this.spec, spec);
52506
+ return this;
52507
+ }
52508
+
52509
+ // if the nested value is a schema we can skip cloning, since
52510
+ // they are already immutable
52511
+ const next = Object.create(Object.getPrototypeOf(this));
52512
+
52513
+ // @ts-expect-error this is readonly
52514
+ next.type = this.type;
52515
+ next._typeCheck = this._typeCheck;
52516
+ next._whitelist = this._whitelist.clone();
52517
+ next._blacklist = this._blacklist.clone();
52518
+ next.internalTests = Object.assign({}, this.internalTests);
52519
+ next.exclusiveTests = Object.assign({}, this.exclusiveTests);
52520
+
52521
+ // @ts-expect-error this is readonly
52522
+ next.deps = [...this.deps];
52523
+ next.conditions = [...this.conditions];
52524
+ next.tests = [...this.tests];
52525
+ next.transforms = [...this.transforms];
52526
+ next.spec = clone(Object.assign({}, this.spec, spec));
52527
+ return next;
52528
+ }
52529
+ label(label) {
52530
+ let next = this.clone();
52531
+ next.spec.label = label;
52532
+ return next;
52533
+ }
52534
+ meta(...args) {
52535
+ if (args.length === 0) return this.spec.meta;
52536
+ let next = this.clone();
52537
+ next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);
52538
+ return next;
52539
+ }
52540
+ withMutation(fn) {
52541
+ let before = this._mutate;
52542
+ this._mutate = true;
52543
+ let result = fn(this);
52544
+ this._mutate = before;
52545
+ return result;
52546
+ }
52547
+ concat(schema) {
52548
+ if (!schema || schema === this) return this;
52549
+ if (schema.type !== this.type && this.type !== 'mixed') throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`);
52550
+ let base = this;
52551
+ let combined = schema.clone();
52552
+ const mergedSpec = Object.assign({}, base.spec, combined.spec);
52553
+ combined.spec = mergedSpec;
52554
+ combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests);
52555
+
52556
+ // manually merge the blacklist/whitelist (the other `schema` takes
52557
+ // precedence in case of conflicts)
52558
+ combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);
52559
+ combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist);
52560
+
52561
+ // start with the current tests
52562
+ combined.tests = base.tests;
52563
+ combined.exclusiveTests = base.exclusiveTests;
52564
+
52565
+ // manually add the new tests to ensure
52566
+ // the deduping logic is consistent
52567
+ combined.withMutation(next => {
52568
+ schema.tests.forEach(fn => {
52569
+ next.test(fn.OPTIONS);
52570
+ });
52571
+ });
52572
+ combined.transforms = [...base.transforms, ...combined.transforms];
52573
+ return combined;
52574
+ }
52575
+ isType(v) {
52576
+ if (v == null) {
52577
+ if (this.spec.nullable && v === null) return true;
52578
+ if (this.spec.optional && v === undefined) return true;
52579
+ return false;
52580
+ }
52581
+ return this._typeCheck(v);
52582
+ }
52583
+ resolve(options) {
52584
+ let schema = this;
52585
+ if (schema.conditions.length) {
52586
+ let conditions = schema.conditions;
52587
+ schema = schema.clone();
52588
+ schema.conditions = [];
52589
+ schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);
52590
+ schema = schema.resolve(options);
52591
+ }
52592
+ return schema;
52593
+ }
52594
+ resolveOptions(options) {
52595
+ var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack;
52596
+ return Object.assign({}, options, {
52597
+ from: options.from || [],
52598
+ strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,
52599
+ abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,
52600
+ recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive,
52601
+ disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace
52602
+ });
52603
+ }
52604
+
52605
+ /**
52606
+ * Run the configured transform pipeline over an input value.
52607
+ */
52608
+
52609
+ cast(value, options = {}) {
52610
+ let resolvedSchema = this.resolve(Object.assign({}, options, {
52611
+ value
52612
+ // parent: options.parent,
52613
+ // context: options.context,
52614
+ }));
52615
+
52616
+ let allowOptionality = options.assert === 'ignore-optionality';
52617
+ let result = resolvedSchema._cast(value, options);
52618
+ if (options.assert !== false && !resolvedSchema.isType(result)) {
52619
+ if (allowOptionality && isAbsent(result)) {
52620
+ return result;
52621
+ }
52622
+ let formattedValue = printValue(value);
52623
+ let formattedResult = printValue(result);
52624
+ throw new TypeError(`The value of ${options.path || 'field'} could not be cast to a value ` + `that satisfies the schema type: "${resolvedSchema.type}". \n\n` + `attempted value: ${formattedValue} \n` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ''));
52625
+ }
52626
+ return result;
52627
+ }
52628
+ _cast(rawValue, options) {
52629
+ let value = rawValue === undefined ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this, options), rawValue);
52630
+ if (value === undefined) {
52631
+ value = this.getDefault(options);
52632
+ }
52633
+ return value;
52634
+ }
52635
+ _validate(_value, options = {}, panic, next) {
52636
+ let {
52637
+ path,
52638
+ originalValue = _value,
52639
+ strict = this.spec.strict
52640
+ } = options;
52641
+ let value = _value;
52642
+ if (!strict) {
52643
+ value = this._cast(value, Object.assign({
52644
+ assert: false
52645
+ }, options));
52646
+ }
52647
+ let initialTests = [];
52648
+ for (let test of Object.values(this.internalTests)) {
52649
+ if (test) initialTests.push(test);
52650
+ }
52651
+ this.runTests({
52652
+ path,
52653
+ value,
52654
+ originalValue,
52655
+ options,
52656
+ tests: initialTests
52657
+ }, panic, initialErrors => {
52658
+ // even if we aren't ending early we can't proceed further if the types aren't correct
52659
+ if (initialErrors.length) {
52660
+ return next(initialErrors, value);
52661
+ }
52662
+ this.runTests({
52663
+ path,
52664
+ value,
52665
+ originalValue,
52666
+ options,
52667
+ tests: this.tests
52668
+ }, panic, next);
52669
+ });
52670
+ }
52671
+
52672
+ /**
52673
+ * Executes a set of validations, either schema, produced Tests or a nested
52674
+ * schema validate result.
52675
+ */
52676
+ runTests(runOptions, panic, next) {
52677
+ let fired = false;
52678
+ let {
52679
+ tests,
52680
+ value,
52681
+ originalValue,
52682
+ path,
52683
+ options
52684
+ } = runOptions;
52685
+ let panicOnce = arg => {
52686
+ if (fired) return;
52687
+ fired = true;
52688
+ panic(arg, value);
52689
+ };
52690
+ let nextOnce = arg => {
52691
+ if (fired) return;
52692
+ fired = true;
52693
+ next(arg, value);
52694
+ };
52695
+ let count = tests.length;
52696
+ let nestedErrors = [];
52697
+ if (!count) return nextOnce([]);
52698
+ let args = {
52699
+ value,
52700
+ originalValue,
52701
+ path,
52702
+ options,
52703
+ schema: this
52704
+ };
52705
+ for (let i = 0; i < tests.length; i++) {
52706
+ const test = tests[i];
52707
+ test(args, panicOnce, function finishTestRun(err) {
52708
+ if (err) {
52709
+ Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err);
52710
+ }
52711
+ if (--count <= 0) {
52712
+ nextOnce(nestedErrors);
52713
+ }
52714
+ });
52715
+ }
52716
+ }
52717
+ asNestedTest({
52718
+ key,
52719
+ index,
52720
+ parent,
52721
+ parentPath,
52722
+ originalParent,
52723
+ options
52724
+ }) {
52725
+ const k = key != null ? key : index;
52726
+ if (k == null) {
52727
+ throw TypeError('Must include `key` or `index` for nested validations');
52728
+ }
52729
+ const isIndex = typeof k === 'number';
52730
+ let value = parent[k];
52731
+ const testOptions = Object.assign({}, options, {
52732
+ // Nested validations fields are always strict:
52733
+ // 1. parent isn't strict so the casting will also have cast inner values
52734
+ // 2. parent is strict in which case the nested values weren't cast either
52735
+ strict: true,
52736
+ parent,
52737
+ value,
52738
+ originalValue: originalParent[k],
52739
+ // FIXME: tests depend on `index` being passed around deeply,
52740
+ // we should not let the options.key/index bleed through
52741
+ key: undefined,
52742
+ // index: undefined,
52743
+ [isIndex ? 'index' : 'key']: k,
52744
+ path: isIndex || k.includes('.') ? `${parentPath || ''}[${isIndex ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : '') + key
52745
+ });
52746
+ return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);
52747
+ }
52748
+ validate(value, options) {
52749
+ var _options$disableStack2;
52750
+ let schema = this.resolve(Object.assign({}, options, {
52751
+ value
52752
+ }));
52753
+ let disableStackTrace = (_options$disableStack2 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace;
52754
+ return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {
52755
+ if (ValidationError.isError(error)) error.value = parsed;
52756
+ reject(error);
52757
+ }, (errors, validated) => {
52758
+ if (errors.length) reject(new ValidationError(errors, validated, undefined, undefined, disableStackTrace));else resolve(validated);
52759
+ }));
52760
+ }
52761
+ validateSync(value, options) {
52762
+ var _options$disableStack3;
52763
+ let schema = this.resolve(Object.assign({}, options, {
52764
+ value
52765
+ }));
52766
+ let result;
52767
+ let disableStackTrace = (_options$disableStack3 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace;
52768
+ schema._validate(value, Object.assign({}, options, {
52769
+ sync: true
52770
+ }), (error, parsed) => {
52771
+ if (ValidationError.isError(error)) error.value = parsed;
52772
+ throw error;
52773
+ }, (errors, validated) => {
52774
+ if (errors.length) throw new ValidationError(errors, value, undefined, undefined, disableStackTrace);
52775
+ result = validated;
52776
+ });
52777
+ return result;
52778
+ }
52779
+ isValid(value, options) {
52780
+ return this.validate(value, options).then(() => true, err => {
52781
+ if (ValidationError.isError(err)) return false;
52782
+ throw err;
52783
+ });
52784
+ }
52785
+ isValidSync(value, options) {
52786
+ try {
52787
+ this.validateSync(value, options);
52788
+ return true;
52789
+ } catch (err) {
52790
+ if (ValidationError.isError(err)) return false;
52791
+ throw err;
52792
+ }
52793
+ }
52794
+ _getDefault(options) {
52795
+ let defaultValue = this.spec.default;
52796
+ if (defaultValue == null) {
52797
+ return defaultValue;
52798
+ }
52799
+ return typeof defaultValue === 'function' ? defaultValue.call(this, options) : clone(defaultValue);
52800
+ }
52801
+ getDefault(options
52802
+ // If schema is defaulted we know it's at least not undefined
52803
+ ) {
52804
+ let schema = this.resolve(options || {});
52805
+ return schema._getDefault(options);
52806
+ }
52807
+ default(def) {
52808
+ if (arguments.length === 0) {
52809
+ return this._getDefault();
52810
+ }
52811
+ let next = this.clone({
52812
+ default: def
52813
+ });
52814
+ return next;
52815
+ }
52816
+ strict(isStrict = true) {
52817
+ return this.clone({
52818
+ strict: isStrict
52819
+ });
52820
+ }
52821
+ nullability(nullable, message) {
52822
+ const next = this.clone({
52823
+ nullable
52824
+ });
52825
+ next.internalTests.nullable = createValidation({
52826
+ message,
52827
+ name: 'nullable',
52828
+ test(value) {
52829
+ return value === null ? this.schema.spec.nullable : true;
52830
+ }
52831
+ });
52832
+ return next;
52833
+ }
52834
+ optionality(optional, message) {
52835
+ const next = this.clone({
52836
+ optional
52837
+ });
52838
+ next.internalTests.optionality = createValidation({
52839
+ message,
52840
+ name: 'optionality',
52841
+ test(value) {
52842
+ return value === undefined ? this.schema.spec.optional : true;
52843
+ }
52844
+ });
52845
+ return next;
52846
+ }
52847
+ optional() {
52848
+ return this.optionality(true);
52849
+ }
52850
+ defined(message = mixed.defined) {
52851
+ return this.optionality(false, message);
52852
+ }
52853
+ nullable() {
52854
+ return this.nullability(true);
52855
+ }
52856
+ nonNullable(message = mixed.notNull) {
52857
+ return this.nullability(false, message);
52858
+ }
52859
+ required(message = mixed.required) {
52860
+ return this.clone().withMutation(next => next.nonNullable(message).defined(message));
52861
+ }
52862
+ notRequired() {
52863
+ return this.clone().withMutation(next => next.nullable().optional());
52864
+ }
52865
+ transform(fn) {
52866
+ let next = this.clone();
52867
+ next.transforms.push(fn);
52868
+ return next;
52869
+ }
52870
+
52871
+ /**
52872
+ * Adds a test function to the schema's queue of tests.
52873
+ * tests can be exclusive or non-exclusive.
52874
+ *
52875
+ * - exclusive tests, will replace any existing tests of the same name.
52876
+ * - non-exclusive: can be stacked
52877
+ *
52878
+ * If a non-exclusive test is added to a schema with an exclusive test of the same name
52879
+ * the exclusive test is removed and further tests of the same name will be stacked.
52880
+ *
52881
+ * If an exclusive test is added to a schema with non-exclusive tests of the same name
52882
+ * the previous tests are removed and further tests of the same name will replace each other.
52883
+ */
52884
+
52885
+ test(...args) {
52886
+ let opts;
52887
+ if (args.length === 1) {
52888
+ if (typeof args[0] === 'function') {
52889
+ opts = {
52890
+ test: args[0]
52891
+ };
52892
+ } else {
52893
+ opts = args[0];
52894
+ }
52895
+ } else if (args.length === 2) {
52896
+ opts = {
52897
+ name: args[0],
52898
+ test: args[1]
52899
+ };
52900
+ } else {
52901
+ opts = {
52902
+ name: args[0],
52903
+ message: args[1],
52904
+ test: args[2]
52905
+ };
52906
+ }
52907
+ if (opts.message === undefined) opts.message = mixed.default;
52908
+ if (typeof opts.test !== 'function') throw new TypeError('`test` is a required parameters');
52909
+ let next = this.clone();
52910
+ let validate = createValidation(opts);
52911
+ let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;
52912
+ if (opts.exclusive) {
52913
+ if (!opts.name) throw new TypeError('Exclusive tests must provide a unique `name` identifying the test');
52914
+ }
52915
+ if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;
52916
+ next.tests = next.tests.filter(fn => {
52917
+ if (fn.OPTIONS.name === opts.name) {
52918
+ if (isExclusive) return false;
52919
+ if (fn.OPTIONS.test === validate.OPTIONS.test) return false;
52920
+ }
52921
+ return true;
52922
+ });
52923
+ next.tests.push(validate);
52924
+ return next;
52925
+ }
52926
+ when(keys, options) {
52927
+ if (!Array.isArray(keys) && typeof keys !== 'string') {
52928
+ options = keys;
52929
+ keys = '.';
52930
+ }
52931
+ let next = this.clone();
52932
+ let deps = toArray(keys).map(key => new Reference(key));
52933
+ deps.forEach(dep => {
52934
+ // @ts-ignore readonly array
52935
+ if (dep.isSibling) next.deps.push(dep.key);
52936
+ });
52937
+ next.conditions.push(typeof options === 'function' ? new Condition(deps, options) : Condition.fromOptions(deps, options));
52938
+ return next;
52939
+ }
52940
+ typeError(message) {
52941
+ let next = this.clone();
52942
+ next.internalTests.typeError = createValidation({
52943
+ message,
52944
+ name: 'typeError',
52945
+ skipAbsent: true,
52946
+ test(value) {
52947
+ if (!this.schema._typeCheck(value)) return this.createError({
52948
+ params: {
52949
+ type: this.schema.type
52950
+ }
52951
+ });
52952
+ return true;
52953
+ }
52954
+ });
52955
+ return next;
52956
+ }
52957
+ oneOf(enums, message = mixed.oneOf) {
52958
+ let next = this.clone();
52959
+ enums.forEach(val => {
52960
+ next._whitelist.add(val);
52961
+ next._blacklist.delete(val);
52962
+ });
52963
+ next.internalTests.whiteList = createValidation({
52964
+ message,
52965
+ name: 'oneOf',
52966
+ skipAbsent: true,
52967
+ test(value) {
52968
+ let valids = this.schema._whitelist;
52969
+ let resolved = valids.resolveAll(this.resolve);
52970
+ return resolved.includes(value) ? true : this.createError({
52971
+ params: {
52972
+ values: Array.from(valids).join(', '),
52973
+ resolved
52974
+ }
52975
+ });
52976
+ }
52977
+ });
52978
+ return next;
52979
+ }
52980
+ notOneOf(enums, message = mixed.notOneOf) {
52981
+ let next = this.clone();
52982
+ enums.forEach(val => {
52983
+ next._blacklist.add(val);
52984
+ next._whitelist.delete(val);
52985
+ });
52986
+ next.internalTests.blacklist = createValidation({
52987
+ message,
52988
+ name: 'notOneOf',
52989
+ test(value) {
52990
+ let invalids = this.schema._blacklist;
52991
+ let resolved = invalids.resolveAll(this.resolve);
52992
+ if (resolved.includes(value)) return this.createError({
52993
+ params: {
52994
+ values: Array.from(invalids).join(', '),
52995
+ resolved
52996
+ }
52997
+ });
52998
+ return true;
52999
+ }
53000
+ });
53001
+ return next;
53002
+ }
53003
+ strip(strip = true) {
53004
+ let next = this.clone();
53005
+ next.spec.strip = strip;
53006
+ return next;
53007
+ }
53008
+
53009
+ /**
53010
+ * Return a serialized description of the schema including validations, flags, types etc.
53011
+ *
53012
+ * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).
53013
+ */
53014
+ describe(options) {
53015
+ const next = (options ? this.resolve(options) : this).clone();
53016
+ const {
53017
+ label,
53018
+ meta,
53019
+ optional,
53020
+ nullable
53021
+ } = next.spec;
53022
+ const description = {
53023
+ meta,
53024
+ label,
53025
+ optional,
53026
+ nullable,
53027
+ default: next.getDefault(options),
53028
+ type: next.type,
53029
+ oneOf: next._whitelist.describe(),
53030
+ notOneOf: next._blacklist.describe(),
53031
+ tests: next.tests.filter((n, idx, list) => list.findIndex(c => c.OPTIONS.name === n.OPTIONS.name) === idx).map(fn => {
53032
+ const params = fn.OPTIONS.params && options ? resolveParams(Object.assign({}, fn.OPTIONS.params), options) : fn.OPTIONS.params;
53033
+ return {
53034
+ name: fn.OPTIONS.name,
53035
+ params
53036
+ };
53037
+ })
53038
+ };
53039
+ return description;
53040
+ }
53041
+ get ['~standard']() {
53042
+ const schema = this;
53043
+ const standard = {
53044
+ version: 1,
53045
+ vendor: 'yup',
53046
+ async validate(value) {
53047
+ try {
53048
+ const result = await schema.validate(value, {
53049
+ abortEarly: false
53050
+ });
53051
+ return {
53052
+ value: result
53053
+ };
53054
+ } catch (err) {
53055
+ if (err instanceof ValidationError) {
53056
+ return {
53057
+ issues: issuesFromValidationError(err)
53058
+ };
53059
+ }
53060
+ throw err;
53061
+ }
53062
+ }
53063
+ };
53064
+ return standard;
53065
+ }
53066
+ }
53067
+ // @ts-expect-error
53068
+ Schema.prototype.__isYupSchema__ = true;
53069
+ for (const method of ['validate', 'validateSync']) Schema.prototype[`${method}At`] = function (path, value, options = {}) {
53070
+ const {
53071
+ parent,
53072
+ parentPath,
53073
+ schema
53074
+ } = getIn(this, path, value, options.context);
53075
+ return schema[method](parent && parent[parentPath], Object.assign({}, options, {
53076
+ parent,
53077
+ path
53078
+ }));
53079
+ };
53080
+ for (const alias of ['equals', 'is']) Schema.prototype[alias] = Schema.prototype.oneOf;
53081
+ for (const alias of ['not', 'nope']) Schema.prototype[alias] = Schema.prototype.notOneOf;
53082
+
53083
+ const returnsTrue = () => true;
53084
+ function create$8(spec) {
53085
+ return new MixedSchema(spec);
53086
+ }
53087
+ class MixedSchema extends Schema {
53088
+ constructor(spec) {
53089
+ super(typeof spec === 'function' ? {
53090
+ type: 'mixed',
53091
+ check: spec
53092
+ } : Object.assign({
53093
+ type: 'mixed',
53094
+ check: returnsTrue
53095
+ }, spec));
53096
+ }
53097
+ }
53098
+ create$8.prototype = MixedSchema.prototype;
53099
+
53100
+ /**
53101
+ * This file is a modified version of the file from the following repository:
53102
+ * Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
53103
+ * NON-CONFORMANT EDITION.
53104
+ * © 2011 Colin Snover <http://zetafleet.com>
53105
+ * Released under MIT license.
53106
+ */
53107
+
53108
+ // prettier-ignore
53109
+ // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
53110
+ const isoReg = /^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
53111
+ function parseIsoDate(date) {
53112
+ const struct = parseDateStruct(date);
53113
+ if (!struct) return Date.parse ? Date.parse(date) : Number.NaN;
53114
+
53115
+ // timestamps without timezone identifiers should be considered local time
53116
+ if (struct.z === undefined && struct.plusMinus === undefined) {
53117
+ return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf();
53118
+ }
53119
+ let totalMinutesOffset = 0;
53120
+ if (struct.z !== 'Z' && struct.plusMinus !== undefined) {
53121
+ totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset;
53122
+ if (struct.plusMinus === '+') totalMinutesOffset = 0 - totalMinutesOffset;
53123
+ }
53124
+ return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond);
53125
+ }
53126
+ function parseDateStruct(date) {
53127
+ var _regexResult$7$length, _regexResult$;
53128
+ const regexResult = isoReg.exec(date);
53129
+ if (!regexResult) return null;
53130
+
53131
+ // use of toNumber() avoids NaN timestamps caused by “undefined”
53132
+ // values being passed to Date constructor
53133
+ return {
53134
+ year: toNumber(regexResult[1]),
53135
+ month: toNumber(regexResult[2], 1) - 1,
53136
+ day: toNumber(regexResult[3], 1),
53137
+ hour: toNumber(regexResult[4]),
53138
+ minute: toNumber(regexResult[5]),
53139
+ second: toNumber(regexResult[6]),
53140
+ millisecond: regexResult[7] ?
53141
+ // allow arbitrary sub-second precision beyond milliseconds
53142
+ toNumber(regexResult[7].substring(0, 3)) : 0,
53143
+ precision: (_regexResult$7$length = (_regexResult$ = regexResult[7]) == null ? void 0 : _regexResult$.length) != null ? _regexResult$7$length : undefined,
53144
+ z: regexResult[8] || undefined,
53145
+ plusMinus: regexResult[9] || undefined,
53146
+ hourOffset: toNumber(regexResult[10]),
53147
+ minuteOffset: toNumber(regexResult[11])
53148
+ };
53149
+ }
53150
+ function toNumber(str, defaultValue = 0) {
53151
+ return Number(str) || defaultValue;
53152
+ }
53153
+
53154
+ // Taken from HTML spec: https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
53155
+ let rEmail =
53156
+ // eslint-disable-next-line
53157
+ /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
53158
+ let rUrl =
53159
+ // eslint-disable-next-line
53160
+ /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
53161
+
53162
+ // eslint-disable-next-line
53163
+ let rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
53164
+ let yearMonthDay = '^\\d{4}-\\d{2}-\\d{2}';
53165
+ let hourMinuteSecond = '\\d{2}:\\d{2}:\\d{2}';
53166
+ let zOrOffset = '(([+-]\\d{2}(:?\\d{2})?)|Z)';
53167
+ let rIsoDateTime = new RegExp(`${yearMonthDay}T${hourMinuteSecond}(\\.\\d+)?${zOrOffset}$`);
53168
+ let isTrimmed = value => isAbsent(value) || value === value.trim();
53169
+ let objStringTag = {}.toString();
53170
+ function create$6() {
53171
+ return new StringSchema();
53172
+ }
53173
+ class StringSchema extends Schema {
53174
+ constructor() {
53175
+ super({
53176
+ type: 'string',
53177
+ check(value) {
53178
+ if (value instanceof String) value = value.valueOf();
53179
+ return typeof value === 'string';
53180
+ }
53181
+ });
53182
+ this.withMutation(() => {
53183
+ this.transform((value, _raw) => {
53184
+ if (!this.spec.coerce || this.isType(value)) return value;
53185
+
53186
+ // don't ever convert arrays
53187
+ if (Array.isArray(value)) return value;
53188
+ const strValue = value != null && value.toString ? value.toString() : value;
53189
+
53190
+ // no one wants plain objects converted to [Object object]
53191
+ if (strValue === objStringTag) return value;
53192
+ return strValue;
53193
+ });
53194
+ });
53195
+ }
53196
+ required(message) {
53197
+ return super.required(message).withMutation(schema => schema.test({
53198
+ message: message || mixed.required,
53199
+ name: 'required',
53200
+ skipAbsent: true,
53201
+ test: value => !!value.length
53202
+ }));
53203
+ }
53204
+ notRequired() {
53205
+ return super.notRequired().withMutation(schema => {
53206
+ schema.tests = schema.tests.filter(t => t.OPTIONS.name !== 'required');
53207
+ return schema;
53208
+ });
53209
+ }
53210
+ length(length, message = string.length) {
53211
+ return this.test({
53212
+ message,
53213
+ name: 'length',
53214
+ exclusive: true,
53215
+ params: {
53216
+ length
53217
+ },
53218
+ skipAbsent: true,
53219
+ test(value) {
53220
+ return value.length === this.resolve(length);
53221
+ }
53222
+ });
53223
+ }
53224
+ min(min, message = string.min) {
53225
+ return this.test({
53226
+ message,
53227
+ name: 'min',
53228
+ exclusive: true,
53229
+ params: {
53230
+ min
53231
+ },
53232
+ skipAbsent: true,
53233
+ test(value) {
53234
+ return value.length >= this.resolve(min);
53235
+ }
53236
+ });
53237
+ }
53238
+ max(max, message = string.max) {
53239
+ return this.test({
53240
+ name: 'max',
53241
+ exclusive: true,
53242
+ message,
53243
+ params: {
53244
+ max
53245
+ },
53246
+ skipAbsent: true,
53247
+ test(value) {
53248
+ return value.length <= this.resolve(max);
53249
+ }
53250
+ });
53251
+ }
53252
+ matches(regex, options) {
53253
+ let excludeEmptyString = false;
53254
+ let message;
53255
+ let name;
53256
+ if (options) {
53257
+ if (typeof options === 'object') {
53258
+ ({
53259
+ excludeEmptyString = false,
53260
+ message,
53261
+ name
53262
+ } = options);
53263
+ } else {
53264
+ message = options;
53265
+ }
53266
+ }
53267
+ return this.test({
53268
+ name: name || 'matches',
53269
+ message: message || string.matches,
53270
+ params: {
53271
+ regex
53272
+ },
53273
+ skipAbsent: true,
53274
+ test: value => value === '' && excludeEmptyString || value.search(regex) !== -1
53275
+ });
53276
+ }
53277
+ email(message = string.email) {
53278
+ return this.matches(rEmail, {
53279
+ name: 'email',
53280
+ message,
53281
+ excludeEmptyString: true
53282
+ });
53283
+ }
53284
+ url(message = string.url) {
53285
+ return this.matches(rUrl, {
53286
+ name: 'url',
53287
+ message,
53288
+ excludeEmptyString: true
53289
+ });
53290
+ }
53291
+ uuid(message = string.uuid) {
53292
+ return this.matches(rUUID, {
53293
+ name: 'uuid',
53294
+ message,
53295
+ excludeEmptyString: false
53296
+ });
53297
+ }
53298
+ datetime(options) {
53299
+ let message = '';
53300
+ let allowOffset;
53301
+ let precision;
53302
+ if (options) {
53303
+ if (typeof options === 'object') {
53304
+ ({
53305
+ message = '',
53306
+ allowOffset = false,
53307
+ precision = undefined
53308
+ } = options);
53309
+ } else {
53310
+ message = options;
53311
+ }
53312
+ }
53313
+ return this.matches(rIsoDateTime, {
53314
+ name: 'datetime',
53315
+ message: message || string.datetime,
53316
+ excludeEmptyString: true
53317
+ }).test({
53318
+ name: 'datetime_offset',
53319
+ message: message || string.datetime_offset,
53320
+ params: {
53321
+ allowOffset
53322
+ },
53323
+ skipAbsent: true,
53324
+ test: value => {
53325
+ if (!value || allowOffset) return true;
53326
+ const struct = parseDateStruct(value);
53327
+ if (!struct) return false;
53328
+ return !!struct.z;
53329
+ }
53330
+ }).test({
53331
+ name: 'datetime_precision',
53332
+ message: message || string.datetime_precision,
53333
+ params: {
53334
+ precision
53335
+ },
53336
+ skipAbsent: true,
53337
+ test: value => {
53338
+ if (!value || precision == undefined) return true;
53339
+ const struct = parseDateStruct(value);
53340
+ if (!struct) return false;
53341
+ return struct.precision === precision;
53342
+ }
53343
+ });
53344
+ }
53345
+
53346
+ //-- transforms --
53347
+ ensure() {
53348
+ return this.default('').transform(val => val === null ? '' : val);
53349
+ }
53350
+ trim(message = string.trim) {
53351
+ return this.transform(val => val != null ? val.trim() : val).test({
53352
+ message,
53353
+ name: 'trim',
53354
+ test: isTrimmed
53355
+ });
53356
+ }
53357
+ lowercase(message = string.lowercase) {
53358
+ return this.transform(value => !isAbsent(value) ? value.toLowerCase() : value).test({
53359
+ message,
53360
+ name: 'string_case',
53361
+ exclusive: true,
53362
+ skipAbsent: true,
53363
+ test: value => isAbsent(value) || value === value.toLowerCase()
53364
+ });
53365
+ }
53366
+ uppercase(message = string.uppercase) {
53367
+ return this.transform(value => !isAbsent(value) ? value.toUpperCase() : value).test({
53368
+ message,
53369
+ name: 'string_case',
53370
+ exclusive: true,
53371
+ skipAbsent: true,
53372
+ test: value => isAbsent(value) || value === value.toUpperCase()
53373
+ });
53374
+ }
53375
+ }
53376
+ create$6.prototype = StringSchema.prototype;
53377
+
53378
+ //
53379
+ // String Interfaces
53380
+ //
53381
+
53382
+ let isNaN$1 = value => value != +value;
53383
+ function create$5() {
53384
+ return new NumberSchema();
53385
+ }
53386
+ class NumberSchema extends Schema {
53387
+ constructor() {
53388
+ super({
53389
+ type: 'number',
53390
+ check(value) {
53391
+ if (value instanceof Number) value = value.valueOf();
53392
+ return typeof value === 'number' && !isNaN$1(value);
53393
+ }
53394
+ });
53395
+ this.withMutation(() => {
53396
+ this.transform((value, _raw) => {
53397
+ if (!this.spec.coerce) return value;
53398
+ let parsed = value;
53399
+ if (typeof parsed === 'string') {
53400
+ parsed = parsed.replace(/\s/g, '');
53401
+ if (parsed === '') return NaN;
53402
+ // don't use parseFloat to avoid positives on alpha-numeric strings
53403
+ parsed = +parsed;
53404
+ }
53405
+
53406
+ // null -> NaN isn't useful; treat all nulls as null and let it fail on
53407
+ // nullability check vs TypeErrors
53408
+ if (this.isType(parsed) || parsed === null) return parsed;
53409
+ return parseFloat(parsed);
53410
+ });
53411
+ });
53412
+ }
53413
+ min(min, message = number.min) {
53414
+ return this.test({
53415
+ message,
53416
+ name: 'min',
53417
+ exclusive: true,
53418
+ params: {
53419
+ min
53420
+ },
53421
+ skipAbsent: true,
53422
+ test(value) {
53423
+ return value >= this.resolve(min);
53424
+ }
53425
+ });
53426
+ }
53427
+ max(max, message = number.max) {
53428
+ return this.test({
53429
+ message,
53430
+ name: 'max',
53431
+ exclusive: true,
53432
+ params: {
53433
+ max
53434
+ },
53435
+ skipAbsent: true,
53436
+ test(value) {
53437
+ return value <= this.resolve(max);
53438
+ }
53439
+ });
53440
+ }
53441
+ lessThan(less, message = number.lessThan) {
53442
+ return this.test({
53443
+ message,
53444
+ name: 'max',
53445
+ exclusive: true,
53446
+ params: {
53447
+ less
53448
+ },
53449
+ skipAbsent: true,
53450
+ test(value) {
53451
+ return value < this.resolve(less);
53452
+ }
53453
+ });
53454
+ }
53455
+ moreThan(more, message = number.moreThan) {
53456
+ return this.test({
53457
+ message,
53458
+ name: 'min',
53459
+ exclusive: true,
53460
+ params: {
53461
+ more
53462
+ },
53463
+ skipAbsent: true,
53464
+ test(value) {
53465
+ return value > this.resolve(more);
53466
+ }
53467
+ });
53468
+ }
53469
+ positive(msg = number.positive) {
53470
+ return this.moreThan(0, msg);
53471
+ }
53472
+ negative(msg = number.negative) {
53473
+ return this.lessThan(0, msg);
53474
+ }
53475
+ integer(message = number.integer) {
53476
+ return this.test({
53477
+ name: 'integer',
53478
+ message,
53479
+ skipAbsent: true,
53480
+ test: val => Number.isInteger(val)
53481
+ });
53482
+ }
53483
+ truncate() {
53484
+ return this.transform(value => !isAbsent(value) ? value | 0 : value);
53485
+ }
53486
+ round(method) {
53487
+ var _method;
53488
+ let avail = ['ceil', 'floor', 'round', 'trunc'];
53489
+ method = ((_method = method) == null ? void 0 : _method.toLowerCase()) || 'round';
53490
+
53491
+ // this exists for symemtry with the new Math.trunc
53492
+ if (method === 'trunc') return this.truncate();
53493
+ if (avail.indexOf(method.toLowerCase()) === -1) throw new TypeError('Only valid options for round() are: ' + avail.join(', '));
53494
+ return this.transform(value => !isAbsent(value) ? Math[method](value) : value);
53495
+ }
53496
+ }
53497
+ create$5.prototype = NumberSchema.prototype;
53498
+
53499
+ //
53500
+ // Number Interfaces
53501
+ //
53502
+
53503
+ let invalidDate = new Date('');
53504
+ let isDate = obj => Object.prototype.toString.call(obj) === '[object Date]';
53505
+ class DateSchema extends Schema {
53506
+ constructor() {
53507
+ super({
53508
+ type: 'date',
53509
+ check(v) {
53510
+ return isDate(v) && !isNaN(v.getTime());
53511
+ }
53512
+ });
53513
+ this.withMutation(() => {
53514
+ this.transform((value, _raw) => {
53515
+ // null -> InvalidDate isn't useful; treat all nulls as null and let it fail on
53516
+ // nullability check vs TypeErrors
53517
+ if (!this.spec.coerce || this.isType(value) || value === null) return value;
53518
+ value = parseIsoDate(value);
53519
+
53520
+ // 0 is a valid timestamp equivalent to 1970-01-01T00:00:00Z(unix epoch) or before.
53521
+ return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE;
53522
+ });
53523
+ });
53524
+ }
53525
+ prepareParam(ref, name) {
53526
+ let param;
53527
+ if (!Reference.isRef(ref)) {
53528
+ let cast = this.cast(ref);
53529
+ if (!this._typeCheck(cast)) throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`);
53530
+ param = cast;
53531
+ } else {
53532
+ param = ref;
53533
+ }
53534
+ return param;
53535
+ }
53536
+ min(min, message = date.min) {
53537
+ let limit = this.prepareParam(min, 'min');
53538
+ return this.test({
53539
+ message,
53540
+ name: 'min',
53541
+ exclusive: true,
53542
+ params: {
53543
+ min
53544
+ },
53545
+ skipAbsent: true,
53546
+ test(value) {
53547
+ return value >= this.resolve(limit);
53548
+ }
53549
+ });
53550
+ }
53551
+ max(max, message = date.max) {
53552
+ let limit = this.prepareParam(max, 'max');
53553
+ return this.test({
53554
+ message,
53555
+ name: 'max',
53556
+ exclusive: true,
53557
+ params: {
53558
+ max
53559
+ },
53560
+ skipAbsent: true,
53561
+ test(value) {
53562
+ return value <= this.resolve(limit);
53563
+ }
53564
+ });
53565
+ }
53566
+ }
53567
+ DateSchema.INVALID_DATE = invalidDate;
53568
+
53569
+ // @ts-expect-error
53570
+ function sortFields(fields, excludedEdges = []) {
53571
+ let edges = [];
53572
+ let nodes = new Set();
53573
+ let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));
53574
+ function addNode(depPath, key) {
53575
+ let node = propertyExpr.split(depPath)[0];
53576
+ nodes.add(node);
53577
+ if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);
53578
+ }
53579
+ for (const key of Object.keys(fields)) {
53580
+ let value = fields[key];
53581
+ nodes.add(key);
53582
+ if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);else if (isSchema(value) && 'deps' in value) value.deps.forEach(path => addNode(path, key));
53583
+ }
53584
+ return toposort$1.array(Array.from(nodes), edges).reverse();
53585
+ }
53586
+
53587
+ function findIndex(arr, err) {
53588
+ let idx = Infinity;
53589
+ arr.some((key, ii) => {
53590
+ var _err$path;
53591
+ if ((_err$path = err.path) != null && _err$path.includes(key)) {
53592
+ idx = ii;
53593
+ return true;
53594
+ }
53595
+ });
53596
+ return idx;
53597
+ }
53598
+ function sortByKeyOrder(keys) {
53599
+ return (a, b) => {
53600
+ return findIndex(keys, a) - findIndex(keys, b);
53601
+ };
53602
+ }
53603
+
53604
+ const parseJson = (value, _, schema) => {
53605
+ if (typeof value !== 'string') {
53606
+ return value;
53607
+ }
53608
+ let parsed = value;
53609
+ try {
53610
+ parsed = JSON.parse(value);
53611
+ } catch (err) {
53612
+ /* */
53613
+ }
53614
+ return schema.isType(parsed) ? parsed : value;
53615
+ };
53616
+
53617
+ // @ts-ignore
53618
+ function deepPartial(schema) {
53619
+ if ('fields' in schema) {
53620
+ const partial = {};
53621
+ for (const [key, fieldSchema] of Object.entries(schema.fields)) {
53622
+ partial[key] = deepPartial(fieldSchema);
53623
+ }
53624
+ return schema.setFields(partial);
53625
+ }
53626
+ if (schema.type === 'array') {
53627
+ const nextArray = schema.optional();
53628
+ if (nextArray.innerType) nextArray.innerType = deepPartial(nextArray.innerType);
53629
+ return nextArray;
53630
+ }
53631
+ if (schema.type === 'tuple') {
53632
+ return schema.optional().clone({
53633
+ types: schema.spec.types.map(deepPartial)
53634
+ });
53635
+ }
53636
+ if ('optional' in schema) {
53637
+ return schema.optional();
53638
+ }
53639
+ return schema;
53640
+ }
53641
+ const deepHas = (obj, p) => {
53642
+ const path = [...propertyExpr.normalizePath(p)];
53643
+ if (path.length === 1) return path[0] in obj;
53644
+ let last = path.pop();
53645
+ let parent = propertyExpr.getter(propertyExpr.join(path), true)(obj);
53646
+ return !!(parent && last in parent);
53647
+ };
53648
+ let isObject = obj => Object.prototype.toString.call(obj) === '[object Object]';
53649
+ function unknown(ctx, value) {
53650
+ let known = Object.keys(ctx.fields);
53651
+ return Object.keys(value).filter(key => known.indexOf(key) === -1);
53652
+ }
53653
+ const defaultSort = sortByKeyOrder([]);
53654
+ function create$3(spec) {
53655
+ return new ObjectSchema(spec);
53656
+ }
53657
+ class ObjectSchema extends Schema {
53658
+ constructor(spec) {
53659
+ super({
53660
+ type: 'object',
53661
+ check(value) {
53662
+ return isObject(value) || typeof value === 'function';
53663
+ }
53664
+ });
53665
+ this.fields = Object.create(null);
53666
+ this._sortErrors = defaultSort;
53667
+ this._nodes = [];
53668
+ this._excludedEdges = [];
53669
+ this.withMutation(() => {
53670
+ if (spec) {
53671
+ this.shape(spec);
53672
+ }
53673
+ });
53674
+ }
53675
+ _cast(_value, options = {}) {
53676
+ var _options$stripUnknown;
53677
+ let value = super._cast(_value, options);
53678
+
53679
+ //should ignore nulls here
53680
+ if (value === undefined) return this.getDefault(options);
53681
+ if (!this._typeCheck(value)) return value;
53682
+ let fields = this.fields;
53683
+ let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;
53684
+ let props = [].concat(this._nodes, Object.keys(value).filter(v => !this._nodes.includes(v)));
53685
+ let intermediateValue = {}; // is filled during the transform below
53686
+ let innerOptions = Object.assign({}, options, {
53687
+ parent: intermediateValue,
53688
+ __validating: options.__validating || false
53689
+ });
53690
+ let isChanged = false;
53691
+ for (const prop of props) {
53692
+ let field = fields[prop];
53693
+ let exists = (prop in value);
53694
+ let inputValue = value[prop];
53695
+ if (field) {
53696
+ let fieldValue;
53697
+
53698
+ // safe to mutate since this is fired in sequence
53699
+ innerOptions.path = (options.path ? `${options.path}.` : '') + prop;
53700
+ field = field.resolve({
53701
+ value: inputValue,
53702
+ context: options.context,
53703
+ parent: intermediateValue
53704
+ });
53705
+ let fieldSpec = field instanceof Schema ? field.spec : undefined;
53706
+ let strict = fieldSpec == null ? void 0 : fieldSpec.strict;
53707
+ if (fieldSpec != null && fieldSpec.strip) {
53708
+ isChanged = isChanged || prop in value;
53709
+ continue;
53710
+ }
53711
+ fieldValue = !options.__validating || !strict ? field.cast(inputValue, innerOptions) : inputValue;
53712
+ if (fieldValue !== undefined) {
53713
+ intermediateValue[prop] = fieldValue;
53714
+ }
53715
+ } else if (exists && !strip) {
53716
+ intermediateValue[prop] = inputValue;
53717
+ }
53718
+ if (exists !== prop in intermediateValue || intermediateValue[prop] !== inputValue) {
53719
+ isChanged = true;
53720
+ }
53721
+ }
53722
+ return isChanged ? intermediateValue : value;
53723
+ }
53724
+ _validate(_value, options = {}, panic, next) {
53725
+ let {
53726
+ from = [],
53727
+ originalValue = _value,
53728
+ recursive = this.spec.recursive
53729
+ } = options;
53730
+ options.from = [{
53731
+ schema: this,
53732
+ value: originalValue
53733
+ }, ...from];
53734
+ // this flag is needed for handling `strict` correctly in the context of
53735
+ // validation vs just casting. e.g strict() on a field is only used when validating
53736
+ options.__validating = true;
53737
+ options.originalValue = originalValue;
53738
+ super._validate(_value, options, panic, (objectErrors, value) => {
53739
+ if (!recursive || !isObject(value)) {
53740
+ next(objectErrors, value);
53741
+ return;
53742
+ }
53743
+ originalValue = originalValue || value;
53744
+ let tests = [];
53745
+ for (let key of this._nodes) {
53746
+ let field = this.fields[key];
53747
+ if (!field || Reference.isRef(field)) {
53748
+ continue;
53749
+ }
53750
+ tests.push(field.asNestedTest({
53751
+ options,
53752
+ key,
53753
+ parent: value,
53754
+ parentPath: options.path,
53755
+ originalParent: originalValue
53756
+ }));
53757
+ }
53758
+ this.runTests({
53759
+ tests,
53760
+ value,
53761
+ originalValue,
53762
+ options
53763
+ }, panic, fieldErrors => {
53764
+ next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);
53765
+ });
53766
+ });
53767
+ }
53768
+ clone(spec) {
53769
+ const next = super.clone(spec);
53770
+ next.fields = Object.assign({}, this.fields);
53771
+ next._nodes = this._nodes;
53772
+ next._excludedEdges = this._excludedEdges;
53773
+ next._sortErrors = this._sortErrors;
53774
+ return next;
53775
+ }
53776
+ concat(schema) {
53777
+ let next = super.concat(schema);
53778
+ let nextFields = next.fields;
53779
+ for (let [field, schemaOrRef] of Object.entries(this.fields)) {
53780
+ const target = nextFields[field];
53781
+ nextFields[field] = target === undefined ? schemaOrRef : target;
53782
+ }
53783
+ return next.withMutation(s =>
53784
+ // XXX: excludes here is wrong
53785
+ s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges]));
53786
+ }
53787
+ _getDefault(options) {
53788
+ if ('default' in this.spec) {
53789
+ return super._getDefault(options);
53790
+ }
53791
+
53792
+ // if there is no default set invent one
53793
+ if (!this._nodes.length) {
53794
+ return undefined;
53795
+ }
53796
+ let dft = {};
53797
+ this._nodes.forEach(key => {
53798
+ var _innerOptions;
53799
+ const field = this.fields[key];
53800
+ let innerOptions = options;
53801
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
53802
+ innerOptions = Object.assign({}, innerOptions, {
53803
+ parent: innerOptions.value,
53804
+ value: innerOptions.value[key]
53805
+ });
53806
+ }
53807
+ dft[key] = field && 'getDefault' in field ? field.getDefault(innerOptions) : undefined;
53808
+ });
53809
+ return dft;
53810
+ }
53811
+ setFields(shape, excludedEdges) {
53812
+ let next = this.clone();
53813
+ next.fields = shape;
53814
+ next._nodes = sortFields(shape, excludedEdges);
53815
+ next._sortErrors = sortByKeyOrder(Object.keys(shape));
53816
+ // XXX: this carries over edges which may not be what you want
53817
+ if (excludedEdges) next._excludedEdges = excludedEdges;
53818
+ return next;
53819
+ }
53820
+ shape(additions, excludes = []) {
53821
+ return this.clone().withMutation(next => {
53822
+ let edges = next._excludedEdges;
53823
+ if (excludes.length) {
53824
+ if (!Array.isArray(excludes[0])) excludes = [excludes];
53825
+ edges = [...next._excludedEdges, ...excludes];
53826
+ }
53827
+
53828
+ // XXX: excludes here is wrong
53829
+ return next.setFields(Object.assign(next.fields, additions), edges);
53830
+ });
53831
+ }
53832
+ partial() {
53833
+ const partial = {};
53834
+ for (const [key, schema] of Object.entries(this.fields)) {
53835
+ partial[key] = 'optional' in schema && schema.optional instanceof Function ? schema.optional() : schema;
53836
+ }
53837
+ return this.setFields(partial);
53838
+ }
53839
+ deepPartial() {
53840
+ const next = deepPartial(this);
53841
+ return next;
53842
+ }
53843
+ pick(keys) {
53844
+ const picked = {};
53845
+ for (const key of keys) {
53846
+ if (this.fields[key]) picked[key] = this.fields[key];
53847
+ }
53848
+ return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b)));
53849
+ }
53850
+ omit(keys) {
53851
+ const remaining = [];
53852
+ for (const key of Object.keys(this.fields)) {
53853
+ if (keys.includes(key)) continue;
53854
+ remaining.push(key);
53855
+ }
53856
+ return this.pick(remaining);
53857
+ }
53858
+ from(from, to, alias) {
53859
+ let fromGetter = propertyExpr.getter(from, true);
53860
+ return this.transform(obj => {
53861
+ if (!obj) return obj;
53862
+ let newObj = obj;
53863
+ if (deepHas(obj, from)) {
53864
+ newObj = Object.assign({}, obj);
53865
+ if (!alias) delete newObj[from];
53866
+ newObj[to] = fromGetter(obj);
53867
+ }
53868
+ return newObj;
53869
+ });
53870
+ }
53871
+
53872
+ /** Parse an input JSON string to an object */
53873
+ json() {
53874
+ return this.transform(parseJson);
53875
+ }
53876
+
53877
+ /**
53878
+ * Similar to `noUnknown` but only validates that an object is the right shape without stripping the unknown keys
53879
+ */
53880
+ exact(message) {
53881
+ return this.test({
53882
+ name: 'exact',
53883
+ exclusive: true,
53884
+ message: message || object.exact,
53885
+ test(value) {
53886
+ if (value == null) return true;
53887
+ const unknownKeys = unknown(this.schema, value);
53888
+ return unknownKeys.length === 0 || this.createError({
53889
+ params: {
53890
+ properties: unknownKeys.join(', ')
53891
+ }
53892
+ });
53893
+ }
53894
+ });
53895
+ }
53896
+ stripUnknown() {
53897
+ return this.clone({
53898
+ noUnknown: true
53899
+ });
53900
+ }
53901
+ noUnknown(noAllow = true, message = object.noUnknown) {
53902
+ if (typeof noAllow !== 'boolean') {
53903
+ message = noAllow;
53904
+ noAllow = true;
53905
+ }
53906
+ let next = this.test({
53907
+ name: 'noUnknown',
53908
+ exclusive: true,
53909
+ message: message,
53910
+ test(value) {
53911
+ if (value == null) return true;
53912
+ const unknownKeys = unknown(this.schema, value);
53913
+ return !noAllow || unknownKeys.length === 0 || this.createError({
53914
+ params: {
53915
+ unknown: unknownKeys.join(', ')
53916
+ }
53917
+ });
53918
+ }
53919
+ });
53920
+ next.spec.noUnknown = noAllow;
53921
+ return next;
53922
+ }
53923
+ unknown(allow = true, message = object.noUnknown) {
53924
+ return this.noUnknown(!allow, message);
53925
+ }
53926
+ transformKeys(fn) {
53927
+ return this.transform(obj => {
53928
+ if (!obj) return obj;
53929
+ const result = {};
53930
+ for (const key of Object.keys(obj)) result[fn(key)] = obj[key];
53931
+ return result;
53932
+ });
53933
+ }
53934
+ camelCase() {
53935
+ return this.transformKeys(tinyCase.camelCase);
53936
+ }
53937
+ snakeCase() {
53938
+ return this.transformKeys(tinyCase.snakeCase);
53939
+ }
53940
+ constantCase() {
53941
+ return this.transformKeys(key => tinyCase.snakeCase(key).toUpperCase());
53942
+ }
53943
+ describe(options) {
53944
+ const next = (options ? this.resolve(options) : this).clone();
53945
+ const base = super.describe(options);
53946
+ base.fields = {};
53947
+ for (const [key, value] of Object.entries(next.fields)) {
53948
+ var _innerOptions2;
53949
+ let innerOptions = options;
53950
+ if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) {
53951
+ innerOptions = Object.assign({}, innerOptions, {
53952
+ parent: innerOptions.value,
53953
+ value: innerOptions.value[key]
53954
+ });
53955
+ }
53956
+ base.fields[key] = value.describe(innerOptions);
53957
+ }
53958
+ return base;
53959
+ }
53960
+ }
53961
+ create$3.prototype = ObjectSchema.prototype;
53962
+
53963
+ function create$2(type) {
53964
+ return new ArraySchema(type);
53965
+ }
53966
+ class ArraySchema extends Schema {
53967
+ constructor(type) {
53968
+ super({
53969
+ type: 'array',
53970
+ spec: {
53971
+ types: type
53972
+ },
53973
+ check(v) {
53974
+ return Array.isArray(v);
53975
+ }
53976
+ });
53977
+
53978
+ // `undefined` specifically means uninitialized, as opposed to "no subtype"
53979
+ this.innerType = void 0;
53980
+ this.innerType = type;
53981
+ }
53982
+ _cast(_value, _opts) {
53983
+ const value = super._cast(_value, _opts);
53984
+
53985
+ // should ignore nulls here
53986
+ if (!this._typeCheck(value) || !this.innerType) {
53987
+ return value;
53988
+ }
53989
+ let isChanged = false;
53990
+ const castArray = value.map((v, idx) => {
53991
+ const castElement = this.innerType.cast(v, Object.assign({}, _opts, {
53992
+ path: `${_opts.path || ''}[${idx}]`,
53993
+ parent: value,
53994
+ originalValue: v,
53995
+ value: v,
53996
+ index: idx
53997
+ }));
53998
+ if (castElement !== v) {
53999
+ isChanged = true;
54000
+ }
54001
+ return castElement;
54002
+ });
54003
+ return isChanged ? castArray : value;
54004
+ }
54005
+ _validate(_value, options = {}, panic, next) {
54006
+ var _options$recursive;
54007
+ // let sync = options.sync;
54008
+ // let path = options.path;
54009
+ let innerType = this.innerType;
54010
+ // let endEarly = options.abortEarly ?? this.spec.abortEarly;
54011
+ let recursive = (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive;
54012
+ options.originalValue != null ? options.originalValue : _value;
54013
+ super._validate(_value, options, panic, (arrayErrors, value) => {
54014
+ var _options$originalValu2;
54015
+ if (!recursive || !innerType || !this._typeCheck(value)) {
54016
+ next(arrayErrors, value);
54017
+ return;
54018
+ }
54019
+
54020
+ // #950 Ensure that sparse array empty slots are validated
54021
+ let tests = new Array(value.length);
54022
+ for (let index = 0; index < value.length; index++) {
54023
+ var _options$originalValu;
54024
+ tests[index] = innerType.asNestedTest({
54025
+ options,
54026
+ index,
54027
+ parent: value,
54028
+ parentPath: options.path,
54029
+ originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value
54030
+ });
54031
+ }
54032
+ this.runTests({
54033
+ value,
54034
+ tests,
54035
+ originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value,
54036
+ options
54037
+ }, panic, innerTypeErrors => next(innerTypeErrors.concat(arrayErrors), value));
54038
+ });
54039
+ }
54040
+ clone(spec) {
54041
+ const next = super.clone(spec);
54042
+ // @ts-expect-error readonly
54043
+ next.innerType = this.innerType;
54044
+ return next;
54045
+ }
54046
+
54047
+ /** Parse an input JSON string to an object */
54048
+ json() {
54049
+ return this.transform(parseJson);
54050
+ }
54051
+ concat(schema) {
54052
+ let next = super.concat(schema);
54053
+
54054
+ // @ts-expect-error readonly
54055
+ next.innerType = this.innerType;
54056
+ if (schema.innerType)
54057
+ // @ts-expect-error readonly
54058
+ next.innerType = next.innerType ?
54059
+ // @ts-expect-error Lazy doesn't have concat and will break
54060
+ next.innerType.concat(schema.innerType) : schema.innerType;
54061
+ return next;
54062
+ }
54063
+ of(schema) {
54064
+ // FIXME: this should return a new instance of array without the default to be
54065
+ let next = this.clone();
54066
+ if (!isSchema(schema)) throw new TypeError('`array.of()` sub-schema must be a valid yup schema not: ' + printValue(schema));
54067
+
54068
+ // @ts-expect-error readonly
54069
+ next.innerType = schema;
54070
+ next.spec = Object.assign({}, next.spec, {
54071
+ types: schema
54072
+ });
54073
+ return next;
54074
+ }
54075
+ length(length, message = array.length) {
54076
+ return this.test({
54077
+ message,
54078
+ name: 'length',
54079
+ exclusive: true,
54080
+ params: {
54081
+ length
54082
+ },
54083
+ skipAbsent: true,
54084
+ test(value) {
54085
+ return value.length === this.resolve(length);
54086
+ }
54087
+ });
54088
+ }
54089
+ min(min, message) {
54090
+ message = message || array.min;
54091
+ return this.test({
54092
+ message,
54093
+ name: 'min',
54094
+ exclusive: true,
54095
+ params: {
54096
+ min
54097
+ },
54098
+ skipAbsent: true,
54099
+ // FIXME(ts): Array<typeof T>
54100
+ test(value) {
54101
+ return value.length >= this.resolve(min);
54102
+ }
54103
+ });
54104
+ }
54105
+ max(max, message) {
54106
+ message = message || array.max;
54107
+ return this.test({
54108
+ message,
54109
+ name: 'max',
54110
+ exclusive: true,
54111
+ params: {
54112
+ max
54113
+ },
54114
+ skipAbsent: true,
54115
+ test(value) {
54116
+ return value.length <= this.resolve(max);
54117
+ }
54118
+ });
54119
+ }
54120
+ ensure() {
54121
+ return this.default(() => []).transform((val, original) => {
54122
+ // We don't want to return `null` for nullable schema
54123
+ if (this._typeCheck(val)) return val;
54124
+ return original == null ? [] : [].concat(original);
54125
+ });
54126
+ }
54127
+ compact(rejector) {
54128
+ let reject = !rejector ? v => !!v : (v, i, a) => !rejector(v, i, a);
54129
+ return this.transform(values => values != null ? values.filter(reject) : values);
54130
+ }
54131
+ describe(options) {
54132
+ const next = (options ? this.resolve(options) : this).clone();
54133
+ const base = super.describe(options);
54134
+ if (next.innerType) {
54135
+ var _innerOptions;
54136
+ let innerOptions = options;
54137
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
54138
+ innerOptions = Object.assign({}, innerOptions, {
54139
+ parent: innerOptions.value,
54140
+ value: innerOptions.value[0]
54141
+ });
54142
+ }
54143
+ base.innerType = next.innerType.describe(innerOptions);
54144
+ }
54145
+ return base;
54146
+ }
54147
+ }
54148
+ create$2.prototype = ArraySchema.prototype;
54149
+
54150
+ class PaymentWidgetValidationError extends Error {
54151
+ constructor(message) {
54152
+ super(message);
54153
+ this.name = "PaymentWidgetValidationError";
54154
+ }
54155
+ }
54156
+ // Common schemas
54157
+ const phoneRegex = /^\+?[1-9]\d{1,14}$/;
54158
+ const customerSchema = create$3({
54159
+ first_name: create$6().trim().required("first_name is required"),
54160
+ last_name: create$6().trim().required("last_name is required"),
54161
+ email: create$6()
54162
+ .trim()
54163
+ .email("Invalid email format")
54164
+ .required("email is required"),
54165
+ phone_number: create$6()
54166
+ .trim()
54167
+ .required("phone_number is required")
54168
+ .test("phone-format", "Invalid phone_number format. Should start with + and contain digits", (value) => {
54169
+ if (!value)
54170
+ return false;
54171
+ return phoneRegex.test(value.replace(/[\s-]/g, ""));
54172
+ }),
54173
+ });
54174
+ const productSchema = create$3({
54175
+ product_id: create$6().trim().required("product_id is required"),
54176
+ quantity: create$5().integer().required("quantity is required"),
54177
+ });
54178
+ const deliveryDetailsSchema = create$3({
54179
+ street: create$6().trim().required("delivery_details.street is required"),
54180
+ city: create$6().trim().required("delivery_details.city is required"),
54181
+ state: create$6().trim().required("delivery_details.state is required"),
54182
+ country: create$6().trim().required("delivery_details.country is required"),
54183
+ });
54184
+ const optionalDeliveryDetailsSchema = create$3({
54185
+ street: create$6().trim(),
54186
+ city: create$6().trim(),
54187
+ state: create$6().trim(),
54188
+ country: create$6().trim(),
54189
+ })
54190
+ .nullable()
54191
+ .notRequired();
54192
+ // Type-specific schemas
54193
+ const externalSchema = create$3({
54194
+ public_key: create$6()
54195
+ .trim()
54196
+ .required("public_key is required and cannot be empty"),
54197
+ type: create$6().oneOf(["external"]).required("type is required"),
54198
+ amount: create$5()
54199
+ .required("amount is required and must be a positive number for external payment type"),
54200
+ customer: customerSchema.required(),
54201
+ });
54202
+ const storefrontSchema = create$3({
54203
+ public_key: create$6()
54204
+ .trim()
54205
+ .required("public_key is required and cannot be empty"),
54206
+ type: create$6().oneOf(["storefront"]).required("type is required"),
54207
+ slug: create$6()
54208
+ .trim()
54209
+ .required("slug is required for storefront payment type"),
54210
+ channel: create$6()
54211
+ .oneOf(["pickup", "delivery"])
54212
+ .required("channel is required for storefront payment type"),
54213
+ customer: customerSchema.required(),
54214
+ products: create$2()
54215
+ .of(productSchema)
54216
+ .min(1, "At least one product is required for storefront payment type")
54217
+ .required("products array is required for storefront payment type"),
54218
+ delivery_details: create$8().when("channel", {
54219
+ is: "delivery",
54220
+ then: () => deliveryDetailsSchema.required("delivery_details is required when channel is delivery"),
54221
+ otherwise: () => optionalDeliveryDetailsSchema,
54222
+ }),
54223
+ });
54224
+ const sloudfrontSchema = create$3({
54225
+ public_key: create$6()
54226
+ .trim()
54227
+ .required("public_key is required and cannot be empty"),
54228
+ type: create$6().oneOf(["sloudfront"]).required("type is required"),
54229
+ // transaction_id: yup
54230
+ // .string()
54231
+ // .trim()
54232
+ // .required("transaction_id is required for sloudfront payment type"),
54233
+ customer_id: create$6()
54234
+ .trim()
54235
+ .required("customer_id is required for sloudfront payment type"),
54236
+ business_id: create$6()
54237
+ .trim()
54238
+ .required("business_id is required for sloudfront payment type"),
54239
+ amount: create$5()
54240
+ .required("amount is required and must be a positive number for sloudfront payment type"),
54241
+ channel: create$6()
54242
+ .oneOf(["pickup", "delivery"])
54243
+ .required("channel is required for sloudfront payment type"),
54244
+ customer: customerSchema.required(),
54245
+ products: create$2()
54246
+ .of(productSchema)
54247
+ .min(1, "At least one product is required for sloudfront payment type")
54248
+ .required("products array is required for sloudfront payment type"),
54249
+ delivery_details: create$8().when("channel", {
54250
+ is: "delivery",
54251
+ then: () => deliveryDetailsSchema.required("delivery_details is required when channel is delivery"),
54252
+ otherwise: () => optionalDeliveryDetailsSchema,
54253
+ }),
54254
+ });
54255
+ /**
54256
+ * Validates payment widget options based on the type
54257
+ * @throws {PaymentWidgetValidationError} if validation fails
54258
+ */
54259
+ function validatePaymentWidgetOptions(options) {
54260
+ try {
54261
+ // Validate based on type
54262
+ if (options.type === "external") {
54263
+ externalSchema.validateSync(options, { abortEarly: false });
54264
+ }
54265
+ else if (options.type === "storefront") {
54266
+ storefrontSchema.validateSync(options, { abortEarly: false });
54267
+ }
54268
+ else if (options.type === "sloudfront") {
54269
+ sloudfrontSchema.validateSync(options, { abortEarly: false });
54270
+ }
54271
+ else {
54272
+ throw new PaymentWidgetValidationError(`Invalid type: ${options.type}. Must be "external", "storefront", or "sloudfront"`);
54273
+ }
54274
+ }
54275
+ catch (error) {
54276
+ if (error instanceof ValidationError) {
54277
+ // Throw the first validation error message
54278
+ throw new PaymentWidgetValidationError(error.errors[0] || "Validation failed");
54279
+ }
54280
+ throw error;
54281
+ }
54282
+ }
54283
+
51399
54284
  class PaymentWidget {
51400
54285
  options;
51401
54286
  container = null;
51402
54287
  root = null;
51403
54288
  constructor(options) {
54289
+ // Validate options before proceeding
54290
+ validatePaymentWidgetOptions(options);
51404
54291
  this.options = options;
51405
54292
  // Set widget options immediately for services to use
51406
54293
  setWidgetOptions(options);
51407
- console.log("PaymentWidget initialized with key:", this.options.public_key);
51408
54294
  }
51409
54295
  /**
51410
54296
  * Creates the container div if it doesn’t exist.
@@ -51426,7 +54312,6 @@ to {
51426
54312
  this.ensureContainer();
51427
54313
  if (this.root && this.container) {
51428
54314
  this.root.render(jsxRuntimeExports.jsx(PaymentWidgetProvider, { options: this.options, children: jsxRuntimeExports.jsx(PaymentInfoProvider, { children: jsxRuntimeExports.jsx(ModalProvider, { children: jsxRuntimeExports.jsx(Widget, { isOpen: true }, Date.now()) }) }) }));
51429
- console.log(`PaymentWidget popup shown [env=${this.options.isLocalEnv ? "local" : "prod"}]`);
51430
54315
  }
51431
54316
  }
51432
54317
  /**
@@ -51442,7 +54327,24 @@ to {
51442
54327
  }
51443
54328
  }
51444
54329
 
51445
- return PaymentWidget;
54330
+ /**
54331
+ * Enum for backward compatibility and convenience
54332
+ * Use either string literals or enum values
54333
+ */
54334
+ exports.ModeType = void 0;
54335
+ (function (ModeType) {
54336
+ ModeType["Storefront"] = "storefront";
54337
+ ModeType["External"] = "external";
54338
+ ModeType["Sloudfront"] = "sloudfront";
54339
+ })(exports.ModeType || (exports.ModeType = {}));
54340
+
54341
+ exports.PaymentWidgetValidationError = PaymentWidgetValidationError;
54342
+ exports.buildPaymentInstrumentPayload = buildPaymentInstrumentPayload;
54343
+ exports.default = PaymentWidget;
54344
+ exports.getRegisteredPaymentTypes = getRegisteredPaymentTypes;
54345
+ exports.registerPayloadBuilder = registerPayloadBuilder;
54346
+ exports.validatePaymentWidgetOptions = validatePaymentWidgetOptions;
54347
+
54348
+ Object.defineProperty(exports, '__esModule', { value: true });
51446
54349
 
51447
54350
  }));
51448
- //# sourceMappingURL=index.umd.js.map