stripe-pwa-elements 3.2.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/dist/cjs/app-globals-V2Kpy_OQ.js +0 -3
  2. package/dist/cjs/error-FFC4kSs5.js +0 -3
  3. package/dist/cjs/{factory-CbbbSvkg.js → factory-da3xAKkz.js} +194 -73
  4. package/dist/cjs/{index-Ba1pBePA.js → index-CYbA1N_k.js} +24 -6
  5. package/dist/cjs/index-Dkb0SxZc.js +4694 -0
  6. package/dist/cjs/index.cjs.js +0 -1
  7. package/dist/cjs/ion-icon.cjs.entry.js +22 -13
  8. package/dist/cjs/loader.cjs.js +2 -3
  9. package/dist/cjs/stripe-address-element.cjs.entry.js +34 -26
  10. package/dist/cjs/stripe-card-element-modal.cjs.entry.js +6 -7
  11. package/dist/cjs/stripe-card-element_2.cjs.entry.js +106 -67
  12. package/dist/cjs/stripe-currency-selector.cjs.entry.js +13 -10
  13. package/dist/cjs/stripe-elements.cjs.js +31 -5
  14. package/dist/cjs/stripe-express-checkout-element.cjs.entry.js +25 -22
  15. package/dist/cjs/stripe-link-authentication-element.cjs.entry.js +13 -10
  16. package/dist/cjs/stripe-payment-element.cjs.entry.js +190 -131
  17. package/dist/cjs/stripe-payment-request-button.cjs.entry.js +12 -7
  18. package/dist/collection/collection-manifest.json +3 -2
  19. package/dist/collection/components/stripe-address-element/stripe-address-element.js +29 -21
  20. package/dist/collection/components/stripe-card-element/stripe-card-element.helpers.js +57 -0
  21. package/dist/collection/components/stripe-card-element/stripe-card-element.js +55 -68
  22. package/dist/collection/components/stripe-card-element-modal/stripe-card-element-modal.js +15 -11
  23. package/dist/collection/components/stripe-currency-selector/stripe-currency-selector.js +10 -6
  24. package/dist/collection/components/stripe-express-checkout-element/stripe-express-checkout-element.js +28 -20
  25. package/dist/collection/components/stripe-link-authentication-element/stripe-link-authentication-element.js +12 -7
  26. package/dist/collection/components/stripe-modal/stripe-modal.js +0 -1
  27. package/dist/collection/components/stripe-payment-element/stripe-payment-element.helpers.js +114 -0
  28. package/dist/collection/components/stripe-payment-element/stripe-payment-element.js +69 -126
  29. package/dist/collection/components/stripe-payment-request-button/stripe-payment-request-button.js +34 -12
  30. package/dist/collection/index.js +0 -1
  31. package/dist/collection/interfaces.js +0 -1
  32. package/dist/collection/services/address-element-manager.js +3 -4
  33. package/dist/collection/services/card-element-manager.js +3 -4
  34. package/dist/collection/services/currency-selector-element-manager.js +3 -4
  35. package/dist/collection/services/express-checkout-element-manager.js +9 -10
  36. package/dist/collection/services/factory.js +0 -1
  37. package/dist/collection/services/interfaces.js +0 -1
  38. package/dist/collection/services/link-authentication-element-manager.js +3 -4
  39. package/dist/collection/services/payment-element-manager.js +4 -5
  40. package/dist/collection/services/stripe-service.js +5 -6
  41. package/dist/collection/utils/element-finder.js +2 -3
  42. package/dist/collection/utils/error.js +0 -1
  43. package/dist/collection/utils/i18n.js +0 -1
  44. package/dist/collection/utils/platform.js +0 -1
  45. package/dist/collection/utils/test-setup.js +0 -1
  46. package/dist/collection/utils/utils.js +2 -3
  47. package/dist/components/error.js +1 -16
  48. package/dist/components/factory.js +1 -3736
  49. package/dist/components/icon.js +1 -459
  50. package/dist/components/index.d.ts +2 -0
  51. package/dist/components/index.js +1 -4
  52. package/dist/components/index2.js +1 -192
  53. package/dist/components/ion-icon.js +1 -9
  54. package/dist/components/stripe-address-element.js +1 -327
  55. package/dist/components/stripe-card-element-modal.js +1 -174
  56. package/dist/components/stripe-card-element.js +1 -9
  57. package/dist/components/stripe-card-element2.js +1 -440
  58. package/dist/components/stripe-currency-selector.js +1 -218
  59. package/dist/components/stripe-express-checkout-element.js +1 -332
  60. package/dist/components/stripe-link-authentication-element.js +1 -256
  61. package/dist/components/stripe-modal.js +1 -9
  62. package/dist/components/stripe-modal2.js +1 -112
  63. package/dist/components/stripe-payment-element.js +1 -510
  64. package/dist/components/stripe-payment-request-button.js +1 -9
  65. package/dist/components/stripe-payment-request-button2.js +1 -224
  66. package/dist/components/utils.js +1 -89
  67. package/dist/esm/app-globals-DQuL1Twl.js +0 -3
  68. package/dist/esm/error-XRfh5Wrs.js +0 -3
  69. package/dist/esm/{factory-Drde6-y7.js → factory-DeqoYLf_.js} +194 -73
  70. package/dist/esm/index-C6bbmyga.js +4677 -0
  71. package/dist/esm/{index-BHDCxQOb.js → index-CBXaOfXU.js} +24 -6
  72. package/dist/esm/index.js +0 -1
  73. package/dist/esm/ion-icon.entry.js +22 -13
  74. package/dist/esm/loader.js +3 -4
  75. package/dist/esm/stripe-address-element.entry.js +34 -26
  76. package/dist/esm/stripe-card-element-modal.entry.js +6 -7
  77. package/dist/esm/stripe-card-element_2.entry.js +106 -67
  78. package/dist/esm/stripe-currency-selector.entry.js +13 -10
  79. package/dist/esm/stripe-elements.js +32 -6
  80. package/dist/esm/stripe-express-checkout-element.entry.js +25 -22
  81. package/dist/esm/stripe-link-authentication-element.entry.js +13 -10
  82. package/dist/esm/stripe-payment-element.entry.js +190 -131
  83. package/dist/esm/stripe-payment-request-button.entry.js +12 -7
  84. package/dist/stripe-elements/index.esm.js +0 -2
  85. package/dist/stripe-elements/p--sA2m1ad.js +1 -0
  86. package/dist/stripe-elements/p-38e7b187.entry.js +1 -0
  87. package/dist/stripe-elements/p-44495284.entry.js +1 -0
  88. package/dist/stripe-elements/p-4ba675fa.entry.js +1 -0
  89. package/dist/stripe-elements/p-5cf62945.entry.js +1 -0
  90. package/dist/stripe-elements/p-C6bbmyga.js +2 -0
  91. package/dist/stripe-elements/p-CBXaOfXU.js +1 -0
  92. package/dist/stripe-elements/p-DQuL1Twl.js +1 -2
  93. package/dist/stripe-elements/p-XRfh5Wrs.js +1 -2
  94. package/dist/stripe-elements/p-c24ae181.entry.js +1 -0
  95. package/dist/stripe-elements/p-d9e86451.entry.js +1 -0
  96. package/dist/stripe-elements/p-f09c86a0.entry.js +1 -0
  97. package/dist/stripe-elements/p-f64f394d.entry.js +1 -0
  98. package/dist/stripe-elements/p-f6d2425e.entry.js +1 -0
  99. package/dist/stripe-elements/stripe-elements.esm.js +1 -2
  100. package/dist/stripe-elements/svg/.gitignore +4 -0
  101. package/dist/types/components/stripe-card-element/stripe-card-element.d.ts +5 -1
  102. package/dist/types/components/stripe-card-element/stripe-card-element.helpers.d.ts +29 -0
  103. package/dist/types/components/stripe-card-element-modal/stripe-card-element-modal.d.ts +4 -4
  104. package/dist/types/components/stripe-payment-element/stripe-payment-element.d.ts +2 -2
  105. package/dist/types/components/stripe-payment-element/stripe-payment-element.helpers.d.ts +54 -0
  106. package/dist/types/components/stripe-payment-request-button/stripe-payment-request-button.d.ts +8 -0
  107. package/dist/types/components.d.ts +139 -29
  108. package/dist/types/index.d.ts +1 -0
  109. package/dist/types/services/interfaces.d.ts +3 -3
  110. package/dist/types/services/stripe-service.d.ts +2 -2
  111. package/dist/types/stencil-public-runtime.d.ts +110 -5
  112. package/package.json +50 -30
  113. package/readme.md +386 -133
  114. package/dist/cjs/app-globals-V2Kpy_OQ.js.map +0 -1
  115. package/dist/cjs/error-FFC4kSs5.js.map +0 -1
  116. package/dist/cjs/factory-CbbbSvkg.js.map +0 -1
  117. package/dist/cjs/index-BXVW_rzh.js +0 -1932
  118. package/dist/cjs/index-BXVW_rzh.js.map +0 -1
  119. package/dist/cjs/index-Ba1pBePA.js.map +0 -1
  120. package/dist/cjs/index.cjs.js.map +0 -1
  121. package/dist/cjs/ion-icon.entry.cjs.js.map +0 -1
  122. package/dist/cjs/loader.cjs.js.map +0 -1
  123. package/dist/cjs/stripe-address-element.entry.cjs.js.map +0 -1
  124. package/dist/cjs/stripe-card-element-modal.entry.cjs.js.map +0 -1
  125. package/dist/cjs/stripe-card-element.stripe-modal.entry.cjs.js.map +0 -1
  126. package/dist/cjs/stripe-currency-selector.entry.cjs.js.map +0 -1
  127. package/dist/cjs/stripe-elements.cjs.js.map +0 -1
  128. package/dist/cjs/stripe-express-checkout-element.entry.cjs.js.map +0 -1
  129. package/dist/cjs/stripe-link-authentication-element.entry.cjs.js.map +0 -1
  130. package/dist/cjs/stripe-payment-element.entry.cjs.js.map +0 -1
  131. package/dist/cjs/stripe-payment-request-button.entry.cjs.js.map +0 -1
  132. package/dist/collection/components/stripe-address-element/stripe-address-element.js.map +0 -1
  133. package/dist/collection/components/stripe-card-element/stripe-card-element.js.map +0 -1
  134. package/dist/collection/components/stripe-card-element-modal/stripe-card-element-modal.js.map +0 -1
  135. package/dist/collection/components/stripe-currency-selector/stripe-currency-selector.js.map +0 -1
  136. package/dist/collection/components/stripe-express-checkout-element/stripe-express-checkout-element.js.map +0 -1
  137. package/dist/collection/components/stripe-link-authentication-element/stripe-link-authentication-element.js.map +0 -1
  138. package/dist/collection/components/stripe-modal/stripe-modal.js.map +0 -1
  139. package/dist/collection/components/stripe-payment-element/stripe-payment-element.js.map +0 -1
  140. package/dist/collection/components/stripe-payment-request-button/stripe-payment-request-button.js.map +0 -1
  141. package/dist/collection/index.js.map +0 -1
  142. package/dist/collection/interfaces.js.map +0 -1
  143. package/dist/collection/services/address-element-manager.js.map +0 -1
  144. package/dist/collection/services/card-element-manager.js.map +0 -1
  145. package/dist/collection/services/currency-selector-element-manager.js.map +0 -1
  146. package/dist/collection/services/express-checkout-element-manager.js.map +0 -1
  147. package/dist/collection/services/factory.js.map +0 -1
  148. package/dist/collection/services/interfaces.js.map +0 -1
  149. package/dist/collection/services/link-authentication-element-manager.js.map +0 -1
  150. package/dist/collection/services/payment-element-manager.js.map +0 -1
  151. package/dist/collection/services/stripe-service.js.map +0 -1
  152. package/dist/collection/utils/element-finder.js.map +0 -1
  153. package/dist/collection/utils/error.js.map +0 -1
  154. package/dist/collection/utils/i18n.js.map +0 -1
  155. package/dist/collection/utils/platform.js.map +0 -1
  156. package/dist/collection/utils/test-setup.js.map +0 -1
  157. package/dist/collection/utils/utils.js.map +0 -1
  158. package/dist/components/error.js.map +0 -1
  159. package/dist/components/factory.js.map +0 -1
  160. package/dist/components/icon.js.map +0 -1
  161. package/dist/components/index.js.map +0 -1
  162. package/dist/components/index2.js.map +0 -1
  163. package/dist/components/ion-icon.js.map +0 -1
  164. package/dist/components/stripe-address-element.js.map +0 -1
  165. package/dist/components/stripe-card-element-modal.js.map +0 -1
  166. package/dist/components/stripe-card-element.js.map +0 -1
  167. package/dist/components/stripe-card-element2.js.map +0 -1
  168. package/dist/components/stripe-currency-selector.js.map +0 -1
  169. package/dist/components/stripe-express-checkout-element.js.map +0 -1
  170. package/dist/components/stripe-link-authentication-element.js.map +0 -1
  171. package/dist/components/stripe-modal.js.map +0 -1
  172. package/dist/components/stripe-modal2.js.map +0 -1
  173. package/dist/components/stripe-payment-element.js.map +0 -1
  174. package/dist/components/stripe-payment-request-button.js.map +0 -1
  175. package/dist/components/stripe-payment-request-button2.js.map +0 -1
  176. package/dist/components/utils.js.map +0 -1
  177. package/dist/esm/app-globals-DQuL1Twl.js.map +0 -1
  178. package/dist/esm/error-XRfh5Wrs.js.map +0 -1
  179. package/dist/esm/factory-Drde6-y7.js.map +0 -1
  180. package/dist/esm/index-BHDCxQOb.js.map +0 -1
  181. package/dist/esm/index-DJwTOfxZ.js +0 -1920
  182. package/dist/esm/index-DJwTOfxZ.js.map +0 -1
  183. package/dist/esm/index.js.map +0 -1
  184. package/dist/esm/ion-icon.entry.js.map +0 -1
  185. package/dist/esm/loader.js.map +0 -1
  186. package/dist/esm/stripe-address-element.entry.js.map +0 -1
  187. package/dist/esm/stripe-card-element-modal.entry.js.map +0 -1
  188. package/dist/esm/stripe-card-element.stripe-modal.entry.js.map +0 -1
  189. package/dist/esm/stripe-currency-selector.entry.js.map +0 -1
  190. package/dist/esm/stripe-elements.js.map +0 -1
  191. package/dist/esm/stripe-express-checkout-element.entry.js.map +0 -1
  192. package/dist/esm/stripe-link-authentication-element.entry.js.map +0 -1
  193. package/dist/esm/stripe-payment-element.entry.js.map +0 -1
  194. package/dist/esm/stripe-payment-request-button.entry.js.map +0 -1
  195. package/dist/stripe-elements/index.esm.js.map +0 -1
  196. package/dist/stripe-elements/ion-icon.entry.esm.js.map +0 -1
  197. package/dist/stripe-elements/loader.esm.js.map +0 -1
  198. package/dist/stripe-elements/p-02f6e421.entry.js +0 -2
  199. package/dist/stripe-elements/p-02f6e421.entry.js.map +0 -1
  200. package/dist/stripe-elements/p-19888fa6.entry.js +0 -2
  201. package/dist/stripe-elements/p-19888fa6.entry.js.map +0 -1
  202. package/dist/stripe-elements/p-4d505729.entry.js +0 -2
  203. package/dist/stripe-elements/p-4d505729.entry.js.map +0 -1
  204. package/dist/stripe-elements/p-7e7ad92a.entry.js +0 -2
  205. package/dist/stripe-elements/p-7e7ad92a.entry.js.map +0 -1
  206. package/dist/stripe-elements/p-8bb4212c.entry.js +0 -2
  207. package/dist/stripe-elements/p-8bb4212c.entry.js.map +0 -1
  208. package/dist/stripe-elements/p-9aee2b6b.entry.js +0 -2
  209. package/dist/stripe-elements/p-9aee2b6b.entry.js.map +0 -1
  210. package/dist/stripe-elements/p-BHDCxQOb.js +0 -2
  211. package/dist/stripe-elements/p-BHDCxQOb.js.map +0 -1
  212. package/dist/stripe-elements/p-DI2vmGaI.js +0 -2
  213. package/dist/stripe-elements/p-DI2vmGaI.js.map +0 -1
  214. package/dist/stripe-elements/p-DJwTOfxZ.js +0 -3
  215. package/dist/stripe-elements/p-DJwTOfxZ.js.map +0 -1
  216. package/dist/stripe-elements/p-DQuL1Twl.js.map +0 -1
  217. package/dist/stripe-elements/p-XRfh5Wrs.js.map +0 -1
  218. package/dist/stripe-elements/p-ba251393.entry.js +0 -2
  219. package/dist/stripe-elements/p-ba251393.entry.js.map +0 -1
  220. package/dist/stripe-elements/p-c649edfc.entry.js +0 -2
  221. package/dist/stripe-elements/p-c649edfc.entry.js.map +0 -1
  222. package/dist/stripe-elements/p-e8bb43ae.entry.js +0 -2
  223. package/dist/stripe-elements/p-e8bb43ae.entry.js.map +0 -1
  224. package/dist/stripe-elements/stripe-address-element.entry.esm.js.map +0 -1
  225. package/dist/stripe-elements/stripe-card-element-modal.entry.esm.js.map +0 -1
  226. package/dist/stripe-elements/stripe-card-element.stripe-modal.entry.esm.js.map +0 -1
  227. package/dist/stripe-elements/stripe-currency-selector.entry.esm.js.map +0 -1
  228. package/dist/stripe-elements/stripe-elements.esm.js.map +0 -1
  229. package/dist/stripe-elements/stripe-express-checkout-element.entry.esm.js.map +0 -1
  230. package/dist/stripe-elements/stripe-link-authentication-element.entry.esm.js.map +0 -1
  231. package/dist/stripe-elements/stripe-payment-element.entry.esm.js.map +0 -1
  232. package/dist/stripe-elements/stripe-payment-request-button.entry.esm.js.map +0 -1
@@ -1,3736 +1 @@
1
- import { getRenderingRef, forceUpdate } from '@stencil/core/internal/client';
2
- import { l as loadStripe } from './index2.js';
3
-
4
- const isString = obj => typeof obj === 'string';
5
- const defer = () => {
6
- let res;
7
- let rej;
8
- const promise = new Promise((resolve, reject) => {
9
- res = resolve;
10
- rej = reject;
11
- });
12
- promise.resolve = res;
13
- promise.reject = rej;
14
- return promise;
15
- };
16
- const makeString = object => {
17
- if (object == null) return '';
18
- return '' + object;
19
- };
20
- const copy = (a, s, t) => {
21
- a.forEach(m => {
22
- if (s[m]) t[m] = s[m];
23
- });
24
- };
25
- const lastOfPathSeparatorRegExp = /###/g;
26
- const cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;
27
- const canNotTraverseDeeper = object => !object || isString(object);
28
- const getLastOfPath = (object, path, Empty) => {
29
- const stack = !isString(path) ? path : path.split('.');
30
- let stackIndex = 0;
31
- while (stackIndex < stack.length - 1) {
32
- if (canNotTraverseDeeper(object)) return {};
33
- const key = cleanKey(stack[stackIndex]);
34
- if (!object[key] && Empty) object[key] = new Empty();
35
- if (Object.prototype.hasOwnProperty.call(object, key)) {
36
- object = object[key];
37
- } else {
38
- object = {};
39
- }
40
- ++stackIndex;
41
- }
42
- if (canNotTraverseDeeper(object)) return {};
43
- return {
44
- obj: object,
45
- k: cleanKey(stack[stackIndex])
46
- };
47
- };
48
- const setPath = (object, path, newValue) => {
49
- const {
50
- obj,
51
- k
52
- } = getLastOfPath(object, path, Object);
53
- if (obj !== undefined || path.length === 1) {
54
- obj[k] = newValue;
55
- return;
56
- }
57
- let e = path[path.length - 1];
58
- let p = path.slice(0, path.length - 1);
59
- let last = getLastOfPath(object, p, Object);
60
- while (last.obj === undefined && p.length) {
61
- e = `${p[p.length - 1]}.${e}`;
62
- p = p.slice(0, p.length - 1);
63
- last = getLastOfPath(object, p, Object);
64
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {
65
- last.obj = undefined;
66
- }
67
- }
68
- last.obj[`${last.k}.${e}`] = newValue;
69
- };
70
- const pushPath = (object, path, newValue, concat) => {
71
- const {
72
- obj,
73
- k
74
- } = getLastOfPath(object, path, Object);
75
- obj[k] = obj[k] || [];
76
- obj[k].push(newValue);
77
- };
78
- const getPath = (object, path) => {
79
- const {
80
- obj,
81
- k
82
- } = getLastOfPath(object, path);
83
- if (!obj) return undefined;
84
- if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;
85
- return obj[k];
86
- };
87
- const getPathWithDefaults = (data, defaultData, key) => {
88
- const value = getPath(data, key);
89
- if (value !== undefined) {
90
- return value;
91
- }
92
- return getPath(defaultData, key);
93
- };
94
- const deepExtend = (target, source, overwrite) => {
95
- for (const prop in source) {
96
- if (prop !== '__proto__' && prop !== 'constructor') {
97
- if (prop in target) {
98
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
99
- if (overwrite) target[prop] = source[prop];
100
- } else {
101
- deepExtend(target[prop], source[prop], overwrite);
102
- }
103
- } else {
104
- target[prop] = source[prop];
105
- }
106
- }
107
- }
108
- return target;
109
- };
110
- const regexEscape = str => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
111
- var _entityMap = {
112
- '&': '&amp;',
113
- '<': '&lt;',
114
- '>': '&gt;',
115
- '"': '&quot;',
116
- "'": '&#39;',
117
- '/': '&#x2F;'
118
- };
119
- const escape = data => {
120
- if (isString(data)) {
121
- return data.replace(/[&<>"'\/]/g, s => _entityMap[s]);
122
- }
123
- return data;
124
- };
125
- class RegExpCache {
126
- constructor(capacity) {
127
- this.capacity = capacity;
128
- this.regExpMap = new Map();
129
- this.regExpQueue = [];
130
- }
131
- getRegExp(pattern) {
132
- const regExpFromCache = this.regExpMap.get(pattern);
133
- if (regExpFromCache !== undefined) {
134
- return regExpFromCache;
135
- }
136
- const regExpNew = new RegExp(pattern);
137
- if (this.regExpQueue.length === this.capacity) {
138
- this.regExpMap.delete(this.regExpQueue.shift());
139
- }
140
- this.regExpMap.set(pattern, regExpNew);
141
- this.regExpQueue.push(pattern);
142
- return regExpNew;
143
- }
144
- }
145
- const chars = [' ', ',', '?', '!', ';'];
146
- const looksLikeObjectPathRegExpCache = new RegExpCache(20);
147
- const looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
148
- nsSeparator = nsSeparator || '';
149
- keySeparator = keySeparator || '';
150
- const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
151
- if (possibleChars.length === 0) return true;
152
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\?' : c).join('|')})`);
153
- let matched = !r.test(key);
154
- if (!matched) {
155
- const ki = key.indexOf(keySeparator);
156
- if (ki > 0 && !r.test(key.substring(0, ki))) {
157
- matched = true;
158
- }
159
- }
160
- return matched;
161
- };
162
- const deepFind = (obj, path, keySeparator = '.') => {
163
- if (!obj) return undefined;
164
- if (obj[path]) {
165
- if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;
166
- return obj[path];
167
- }
168
- const tokens = path.split(keySeparator);
169
- let current = obj;
170
- for (let i = 0; i < tokens.length;) {
171
- if (!current || typeof current !== 'object') {
172
- return undefined;
173
- }
174
- let next;
175
- let nextPath = '';
176
- for (let j = i; j < tokens.length; ++j) {
177
- if (j !== i) {
178
- nextPath += keySeparator;
179
- }
180
- nextPath += tokens[j];
181
- next = current[nextPath];
182
- if (next !== undefined) {
183
- if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {
184
- continue;
185
- }
186
- i += j - i + 1;
187
- break;
188
- }
189
- }
190
- current = next;
191
- }
192
- return current;
193
- };
194
- const getCleanedCode = code => code?.replace('_', '-');
195
-
196
- const consoleLogger = {
197
- type: 'logger',
198
- log(args) {
199
- this.output('log', args);
200
- },
201
- warn(args) {
202
- this.output('warn', args);
203
- },
204
- error(args) {
205
- this.output('error', args);
206
- },
207
- output(type, args) {
208
- console?.[type]?.apply?.(console, args);
209
- }
210
- };
211
- class Logger {
212
- constructor(concreteLogger, options = {}) {
213
- this.init(concreteLogger, options);
214
- }
215
- init(concreteLogger, options = {}) {
216
- this.prefix = options.prefix || 'i18next:';
217
- this.logger = concreteLogger || consoleLogger;
218
- this.options = options;
219
- this.debug = options.debug;
220
- }
221
- log(...args) {
222
- return this.forward(args, 'log', '', true);
223
- }
224
- warn(...args) {
225
- return this.forward(args, 'warn', '', true);
226
- }
227
- error(...args) {
228
- return this.forward(args, 'error', '');
229
- }
230
- deprecate(...args) {
231
- return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
232
- }
233
- forward(args, lvl, prefix, debugOnly) {
234
- if (debugOnly && !this.debug) return null;
235
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
236
- return this.logger[lvl](args);
237
- }
238
- create(moduleName) {
239
- return new Logger(this.logger, {
240
- ...{
241
- prefix: `${this.prefix}:${moduleName}:`
242
- },
243
- ...this.options
244
- });
245
- }
246
- clone(options) {
247
- options = options || this.options;
248
- options.prefix = options.prefix || this.prefix;
249
- return new Logger(this.logger, options);
250
- }
251
- }
252
- var baseLogger = new Logger();
253
-
254
- class EventEmitter {
255
- constructor() {
256
- this.observers = {};
257
- }
258
- on(events, listener) {
259
- events.split(' ').forEach(event => {
260
- if (!this.observers[event]) this.observers[event] = new Map();
261
- const numListeners = this.observers[event].get(listener) || 0;
262
- this.observers[event].set(listener, numListeners + 1);
263
- });
264
- return this;
265
- }
266
- off(event, listener) {
267
- if (!this.observers[event]) return;
268
- if (!listener) {
269
- delete this.observers[event];
270
- return;
271
- }
272
- this.observers[event].delete(listener);
273
- }
274
- emit(event, ...args) {
275
- if (this.observers[event]) {
276
- const cloned = Array.from(this.observers[event].entries());
277
- cloned.forEach(([observer, numTimesAdded]) => {
278
- for (let i = 0; i < numTimesAdded; i++) {
279
- observer(...args);
280
- }
281
- });
282
- }
283
- if (this.observers['*']) {
284
- const cloned = Array.from(this.observers['*'].entries());
285
- cloned.forEach(([observer, numTimesAdded]) => {
286
- for (let i = 0; i < numTimesAdded; i++) {
287
- observer.apply(observer, [event, ...args]);
288
- }
289
- });
290
- }
291
- }
292
- }
293
-
294
- class ResourceStore extends EventEmitter {
295
- constructor(data, options = {
296
- ns: ['translation'],
297
- defaultNS: 'translation'
298
- }) {
299
- super();
300
- this.data = data || {};
301
- this.options = options;
302
- if (this.options.keySeparator === undefined) {
303
- this.options.keySeparator = '.';
304
- }
305
- if (this.options.ignoreJSONStructure === undefined) {
306
- this.options.ignoreJSONStructure = true;
307
- }
308
- }
309
- addNamespaces(ns) {
310
- if (this.options.ns.indexOf(ns) < 0) {
311
- this.options.ns.push(ns);
312
- }
313
- }
314
- removeNamespaces(ns) {
315
- const index = this.options.ns.indexOf(ns);
316
- if (index > -1) {
317
- this.options.ns.splice(index, 1);
318
- }
319
- }
320
- getResource(lng, ns, key, options = {}) {
321
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
322
- const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
323
- let path;
324
- if (lng.indexOf('.') > -1) {
325
- path = lng.split('.');
326
- } else {
327
- path = [lng, ns];
328
- if (key) {
329
- if (Array.isArray(key)) {
330
- path.push(...key);
331
- } else if (isString(key) && keySeparator) {
332
- path.push(...key.split(keySeparator));
333
- } else {
334
- path.push(key);
335
- }
336
- }
337
- }
338
- const result = getPath(this.data, path);
339
- if (!result && !ns && !key && lng.indexOf('.') > -1) {
340
- lng = path[0];
341
- ns = path[1];
342
- key = path.slice(2).join('.');
343
- }
344
- if (result || !ignoreJSONStructure || !isString(key)) return result;
345
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
346
- }
347
- addResource(lng, ns, key, value, options = {
348
- silent: false
349
- }) {
350
- const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
351
- let path = [lng, ns];
352
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
353
- if (lng.indexOf('.') > -1) {
354
- path = lng.split('.');
355
- value = ns;
356
- ns = path[1];
357
- }
358
- this.addNamespaces(ns);
359
- setPath(this.data, path, value);
360
- if (!options.silent) this.emit('added', lng, ns, key, value);
361
- }
362
- addResources(lng, ns, resources, options = {
363
- silent: false
364
- }) {
365
- for (const m in resources) {
366
- if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
367
- silent: true
368
- });
369
- }
370
- if (!options.silent) this.emit('added', lng, ns, resources);
371
- }
372
- addResourceBundle(lng, ns, resources, deep, overwrite, options = {
373
- silent: false,
374
- skipCopy: false
375
- }) {
376
- let path = [lng, ns];
377
- if (lng.indexOf('.') > -1) {
378
- path = lng.split('.');
379
- deep = resources;
380
- resources = ns;
381
- ns = path[1];
382
- }
383
- this.addNamespaces(ns);
384
- let pack = getPath(this.data, path) || {};
385
- if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
386
- if (deep) {
387
- deepExtend(pack, resources, overwrite);
388
- } else {
389
- pack = {
390
- ...pack,
391
- ...resources
392
- };
393
- }
394
- setPath(this.data, path, pack);
395
- if (!options.silent) this.emit('added', lng, ns, resources);
396
- }
397
- removeResourceBundle(lng, ns) {
398
- if (this.hasResourceBundle(lng, ns)) {
399
- delete this.data[lng][ns];
400
- }
401
- this.removeNamespaces(ns);
402
- this.emit('removed', lng, ns);
403
- }
404
- hasResourceBundle(lng, ns) {
405
- return this.getResource(lng, ns) !== undefined;
406
- }
407
- getResourceBundle(lng, ns) {
408
- if (!ns) ns = this.options.defaultNS;
409
- return this.getResource(lng, ns);
410
- }
411
- getDataByLanguage(lng) {
412
- return this.data[lng];
413
- }
414
- hasLanguageSomeTranslations(lng) {
415
- const data = this.getDataByLanguage(lng);
416
- const n = data && Object.keys(data) || [];
417
- return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);
418
- }
419
- toJSON() {
420
- return this.data;
421
- }
422
- }
423
-
424
- var postProcessor = {
425
- processors: {},
426
- addPostProcessor(module) {
427
- this.processors[module.name] = module;
428
- },
429
- handle(processors, value, key, options, translator) {
430
- processors.forEach(processor => {
431
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
432
- });
433
- return value;
434
- }
435
- };
436
-
437
- const PATH_KEY = Symbol('i18next/PATH_KEY');
438
- function createProxy() {
439
- const state = [];
440
- const handler = Object.create(null);
441
- let proxy;
442
- handler.get = (target, key) => {
443
- proxy?.revoke?.();
444
- if (key === PATH_KEY) return state;
445
- state.push(key);
446
- proxy = Proxy.revocable(target, handler);
447
- return proxy.proxy;
448
- };
449
- return Proxy.revocable(Object.create(null), handler).proxy;
450
- }
451
- function keysFromSelector(selector, opts) {
452
- const {
453
- [PATH_KEY]: path
454
- } = selector(createProxy());
455
- return path.join(opts?.keySeparator ?? '.');
456
- }
457
-
458
- const checkedLoadedFor = {};
459
- const shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';
460
- class Translator extends EventEmitter {
461
- constructor(services, options = {}) {
462
- super();
463
- copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);
464
- this.options = options;
465
- if (this.options.keySeparator === undefined) {
466
- this.options.keySeparator = '.';
467
- }
468
- this.logger = baseLogger.create('translator');
469
- }
470
- changeLanguage(lng) {
471
- if (lng) this.language = lng;
472
- }
473
- exists(key, o = {
474
- interpolation: {}
475
- }) {
476
- const opt = {
477
- ...o
478
- };
479
- if (key == null) return false;
480
- const resolved = this.resolve(key, opt);
481
- if (resolved?.res === undefined) return false;
482
- const isObject = shouldHandleAsObject(resolved.res);
483
- if (opt.returnObjects === false && isObject) {
484
- return false;
485
- }
486
- return true;
487
- }
488
- extractFromKey(key, opt) {
489
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
490
- if (nsSeparator === undefined) nsSeparator = ':';
491
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
492
- let namespaces = opt.ns || this.options.defaultNS || [];
493
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
494
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
495
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
496
- const m = key.match(this.interpolator.nestingRegexp);
497
- if (m && m.length > 0) {
498
- return {
499
- key,
500
- namespaces: isString(namespaces) ? [namespaces] : namespaces
501
- };
502
- }
503
- const parts = key.split(nsSeparator);
504
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
505
- key = parts.join(keySeparator);
506
- }
507
- return {
508
- key,
509
- namespaces: isString(namespaces) ? [namespaces] : namespaces
510
- };
511
- }
512
- translate(keys, o, lastKey) {
513
- let opt = typeof o === 'object' ? {
514
- ...o
515
- } : o;
516
- if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {
517
- opt = this.options.overloadTranslationOptionHandler(arguments);
518
- }
519
- if (typeof opt === 'object') opt = {
520
- ...opt
521
- };
522
- if (!opt) opt = {};
523
- if (keys == null) return '';
524
- if (typeof keys === 'function') keys = keysFromSelector(keys, {
525
- ...this.options,
526
- ...opt
527
- });
528
- if (!Array.isArray(keys)) keys = [String(keys)];
529
- const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;
530
- const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;
531
- const {
532
- key,
533
- namespaces
534
- } = this.extractFromKey(keys[keys.length - 1], opt);
535
- const namespace = namespaces[namespaces.length - 1];
536
- let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;
537
- if (nsSeparator === undefined) nsSeparator = ':';
538
- const lng = opt.lng || this.language;
539
- const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
540
- if (lng?.toLowerCase() === 'cimode') {
541
- if (appendNamespaceToCIMode) {
542
- if (returnDetails) {
543
- return {
544
- res: `${namespace}${nsSeparator}${key}`,
545
- usedKey: key,
546
- exactUsedKey: key,
547
- usedLng: lng,
548
- usedNS: namespace,
549
- usedParams: this.getUsedParamsDetails(opt)
550
- };
551
- }
552
- return `${namespace}${nsSeparator}${key}`;
553
- }
554
- if (returnDetails) {
555
- return {
556
- res: key,
557
- usedKey: key,
558
- exactUsedKey: key,
559
- usedLng: lng,
560
- usedNS: namespace,
561
- usedParams: this.getUsedParamsDetails(opt)
562
- };
563
- }
564
- return key;
565
- }
566
- const resolved = this.resolve(keys, opt);
567
- let res = resolved?.res;
568
- const resUsedKey = resolved?.usedKey || key;
569
- const resExactUsedKey = resolved?.exactUsedKey || key;
570
- const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
571
- const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;
572
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
573
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
574
- const hasDefaultValue = Translator.hasDefaultValue(opt);
575
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';
576
- const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
577
- ordinal: false
578
- }) : '';
579
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
580
- const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
581
- let resForObjHndl = res;
582
- if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
583
- resForObjHndl = defaultValue;
584
- }
585
- const handleAsObject = shouldHandleAsObject(resForObjHndl);
586
- const resType = Object.prototype.toString.apply(resForObjHndl);
587
- if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
588
- if (!opt.returnObjects && !this.options.returnObjects) {
589
- if (!this.options.returnedObjectHandler) {
590
- this.logger.warn('accessing an object - but returnObjects options is not enabled!');
591
- }
592
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
593
- ...opt,
594
- ns: namespaces
595
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
596
- if (returnDetails) {
597
- resolved.res = r;
598
- resolved.usedParams = this.getUsedParamsDetails(opt);
599
- return resolved;
600
- }
601
- return r;
602
- }
603
- if (keySeparator) {
604
- const resTypeIsArray = Array.isArray(resForObjHndl);
605
- const copy = resTypeIsArray ? [] : {};
606
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
607
- for (const m in resForObjHndl) {
608
- if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
609
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
610
- if (hasDefaultValue && !res) {
611
- copy[m] = this.translate(deepKey, {
612
- ...opt,
613
- defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,
614
- ...{
615
- joinArrays: false,
616
- ns: namespaces
617
- }
618
- });
619
- } else {
620
- copy[m] = this.translate(deepKey, {
621
- ...opt,
622
- ...{
623
- joinArrays: false,
624
- ns: namespaces
625
- }
626
- });
627
- }
628
- if (copy[m] === deepKey) copy[m] = resForObjHndl[m];
629
- }
630
- }
631
- res = copy;
632
- }
633
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
634
- res = res.join(joinArrays);
635
- if (res) res = this.extendTranslation(res, keys, opt, lastKey);
636
- } else {
637
- let usedDefault = false;
638
- let usedKey = false;
639
- if (!this.isValidLookup(res) && hasDefaultValue) {
640
- usedDefault = true;
641
- res = defaultValue;
642
- }
643
- if (!this.isValidLookup(res)) {
644
- usedKey = true;
645
- res = key;
646
- }
647
- const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
648
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;
649
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
650
- if (usedKey || usedDefault || updateMissing) {
651
- this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);
652
- if (keySeparator) {
653
- const fk = this.resolve(key, {
654
- ...opt,
655
- keySeparator: false
656
- });
657
- if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');
658
- }
659
- let lngs = [];
660
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
661
- if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
662
- for (let i = 0; i < fallbackLngs.length; i++) {
663
- lngs.push(fallbackLngs[i]);
664
- }
665
- } else if (this.options.saveMissingTo === 'all') {
666
- lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
667
- } else {
668
- lngs.push(opt.lng || this.language);
669
- }
670
- const send = (l, k, specificDefaultValue) => {
671
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
672
- if (this.options.missingKeyHandler) {
673
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
674
- } else if (this.backendConnector?.saveMissing) {
675
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
676
- }
677
- this.emit('missingKey', l, namespace, k, res);
678
- };
679
- if (this.options.saveMissing) {
680
- if (this.options.saveMissingPlurals && needsPluralHandling) {
681
- lngs.forEach(language => {
682
- const suffixes = this.pluralResolver.getSuffixes(language, opt);
683
- if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
684
- suffixes.push(`${this.options.pluralSeparator}zero`);
685
- }
686
- suffixes.forEach(suffix => {
687
- send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
688
- });
689
- });
690
- } else {
691
- send(lngs, key, defaultValue);
692
- }
693
- }
694
- }
695
- res = this.extendTranslation(res, keys, opt, resolved, lastKey);
696
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
697
- res = `${namespace}${nsSeparator}${key}`;
698
- }
699
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
700
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);
701
- }
702
- }
703
- if (returnDetails) {
704
- resolved.res = res;
705
- resolved.usedParams = this.getUsedParamsDetails(opt);
706
- return resolved;
707
- }
708
- return res;
709
- }
710
- extendTranslation(res, key, opt, resolved, lastKey) {
711
- if (this.i18nFormat?.parse) {
712
- res = this.i18nFormat.parse(res, {
713
- ...this.options.interpolation.defaultVariables,
714
- ...opt
715
- }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
716
- resolved
717
- });
718
- } else if (!opt.skipInterpolation) {
719
- if (opt.interpolation) this.interpolator.init({
720
- ...opt,
721
- ...{
722
- interpolation: {
723
- ...this.options.interpolation,
724
- ...opt.interpolation
725
- }
726
- }
727
- });
728
- const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
729
- let nestBef;
730
- if (skipOnVariables) {
731
- const nb = res.match(this.interpolator.nestingRegexp);
732
- nestBef = nb && nb.length;
733
- }
734
- let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
735
- if (this.options.interpolation.defaultVariables) data = {
736
- ...this.options.interpolation.defaultVariables,
737
- ...data
738
- };
739
- res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
740
- if (skipOnVariables) {
741
- const na = res.match(this.interpolator.nestingRegexp);
742
- const nestAft = na && na.length;
743
- if (nestBef < nestAft) opt.nest = false;
744
- }
745
- if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
746
- if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
747
- if (lastKey?.[0] === args[0] && !opt.context) {
748
- this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
749
- return null;
750
- }
751
- return this.translate(...args, key);
752
- }, opt);
753
- if (opt.interpolation) this.interpolator.reset();
754
- }
755
- const postProcess = opt.postProcess || this.options.postProcess;
756
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
757
- if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
758
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
759
- i18nResolved: {
760
- ...resolved,
761
- usedParams: this.getUsedParamsDetails(opt)
762
- },
763
- ...opt
764
- } : opt, this);
765
- }
766
- return res;
767
- }
768
- resolve(keys, opt = {}) {
769
- let found;
770
- let usedKey;
771
- let exactUsedKey;
772
- let usedLng;
773
- let usedNS;
774
- if (isString(keys)) keys = [keys];
775
- keys.forEach(k => {
776
- if (this.isValidLookup(found)) return;
777
- const extracted = this.extractFromKey(k, opt);
778
- const key = extracted.key;
779
- usedKey = key;
780
- let namespaces = extracted.namespaces;
781
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
782
- const needsPluralHandling = opt.count !== undefined && !isString(opt.count);
783
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
784
- const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';
785
- const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
786
- namespaces.forEach(ns => {
787
- if (this.isValidLookup(found)) return;
788
- usedNS = ns;
789
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
790
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
791
- this.logger.warn(`key "${usedKey}" for languages "${codes.join(', ')}" won't get resolved as namespace "${usedNS}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
792
- }
793
- codes.forEach(code => {
794
- if (this.isValidLookup(found)) return;
795
- usedLng = code;
796
- const finalKeys = [key];
797
- if (this.i18nFormat?.addLookupKeys) {
798
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
799
- } else {
800
- let pluralSuffix;
801
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
802
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
803
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
804
- if (needsPluralHandling) {
805
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
806
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
807
- }
808
- finalKeys.push(key + pluralSuffix);
809
- if (needsZeroSuffixLookup) {
810
- finalKeys.push(key + zeroSuffix);
811
- }
812
- }
813
- if (needsContextHandling) {
814
- const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;
815
- finalKeys.push(contextKey);
816
- if (needsPluralHandling) {
817
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
818
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
819
- }
820
- finalKeys.push(contextKey + pluralSuffix);
821
- if (needsZeroSuffixLookup) {
822
- finalKeys.push(contextKey + zeroSuffix);
823
- }
824
- }
825
- }
826
- }
827
- let possibleKey;
828
- while (possibleKey = finalKeys.pop()) {
829
- if (!this.isValidLookup(found)) {
830
- exactUsedKey = possibleKey;
831
- found = this.getResource(code, ns, possibleKey, opt);
832
- }
833
- }
834
- });
835
- });
836
- });
837
- return {
838
- res: found,
839
- usedKey,
840
- exactUsedKey,
841
- usedLng,
842
- usedNS
843
- };
844
- }
845
- isValidLookup(res) {
846
- return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
847
- }
848
- getResource(code, ns, key, options = {}) {
849
- if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
850
- return this.resourceStore.getResource(code, ns, key, options);
851
- }
852
- getUsedParamsDetails(options = {}) {
853
- const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];
854
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
855
- let data = useOptionsReplaceForData ? options.replace : options;
856
- if (useOptionsReplaceForData && typeof options.count !== 'undefined') {
857
- data.count = options.count;
858
- }
859
- if (this.options.interpolation.defaultVariables) {
860
- data = {
861
- ...this.options.interpolation.defaultVariables,
862
- ...data
863
- };
864
- }
865
- if (!useOptionsReplaceForData) {
866
- data = {
867
- ...data
868
- };
869
- for (const key of optionsKeys) {
870
- delete data[key];
871
- }
872
- }
873
- return data;
874
- }
875
- static hasDefaultValue(options) {
876
- const prefix = 'defaultValue';
877
- for (const option in options) {
878
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {
879
- return true;
880
- }
881
- }
882
- return false;
883
- }
884
- }
885
-
886
- class LanguageUtil {
887
- constructor(options) {
888
- this.options = options;
889
- this.supportedLngs = this.options.supportedLngs || false;
890
- this.logger = baseLogger.create('languageUtils');
891
- }
892
- getScriptPartFromCode(code) {
893
- code = getCleanedCode(code);
894
- if (!code || code.indexOf('-') < 0) return null;
895
- const p = code.split('-');
896
- if (p.length === 2) return null;
897
- p.pop();
898
- if (p[p.length - 1].toLowerCase() === 'x') return null;
899
- return this.formatLanguageCode(p.join('-'));
900
- }
901
- getLanguagePartFromCode(code) {
902
- code = getCleanedCode(code);
903
- if (!code || code.indexOf('-') < 0) return code;
904
- const p = code.split('-');
905
- return this.formatLanguageCode(p[0]);
906
- }
907
- formatLanguageCode(code) {
908
- if (isString(code) && code.indexOf('-') > -1) {
909
- let formattedCode;
910
- try {
911
- formattedCode = Intl.getCanonicalLocales(code)[0];
912
- } catch (e) {}
913
- if (formattedCode && this.options.lowerCaseLng) {
914
- formattedCode = formattedCode.toLowerCase();
915
- }
916
- if (formattedCode) return formattedCode;
917
- if (this.options.lowerCaseLng) {
918
- return code.toLowerCase();
919
- }
920
- return code;
921
- }
922
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
923
- }
924
- isSupportedCode(code) {
925
- if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {
926
- code = this.getLanguagePartFromCode(code);
927
- }
928
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
929
- }
930
- getBestMatchFromCodes(codes) {
931
- if (!codes) return null;
932
- let found;
933
- codes.forEach(code => {
934
- if (found) return;
935
- const cleanedLng = this.formatLanguageCode(code);
936
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
937
- });
938
- if (!found && this.options.supportedLngs) {
939
- codes.forEach(code => {
940
- if (found) return;
941
- const lngScOnly = this.getScriptPartFromCode(code);
942
- if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
943
- const lngOnly = this.getLanguagePartFromCode(code);
944
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
945
- found = this.options.supportedLngs.find(supportedLng => {
946
- if (supportedLng === lngOnly) return supportedLng;
947
- if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;
948
- if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;
949
- if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
950
- });
951
- });
952
- }
953
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
954
- return found;
955
- }
956
- getFallbackCodes(fallbacks, code) {
957
- if (!fallbacks) return [];
958
- if (typeof fallbacks === 'function') fallbacks = fallbacks(code);
959
- if (isString(fallbacks)) fallbacks = [fallbacks];
960
- if (Array.isArray(fallbacks)) return fallbacks;
961
- if (!code) return fallbacks.default || [];
962
- let found = fallbacks[code];
963
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
964
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
965
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
966
- if (!found) found = fallbacks.default;
967
- return found || [];
968
- }
969
- toResolveHierarchy(code, fallbackCode) {
970
- const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
971
- const codes = [];
972
- const addCode = c => {
973
- if (!c) return;
974
- if (this.isSupportedCode(c)) {
975
- codes.push(c);
976
- } else {
977
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
978
- }
979
- };
980
- if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {
981
- if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
982
- if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
983
- if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
984
- } else if (isString(code)) {
985
- addCode(this.formatLanguageCode(code));
986
- }
987
- fallbackCodes.forEach(fc => {
988
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
989
- });
990
- return codes;
991
- }
992
- }
993
-
994
- const suffixesOrder = {
995
- zero: 0,
996
- one: 1,
997
- two: 2,
998
- few: 3,
999
- many: 4,
1000
- other: 5
1001
- };
1002
- const dummyRule = {
1003
- select: count => count === 1 ? 'one' : 'other',
1004
- resolvedOptions: () => ({
1005
- pluralCategories: ['one', 'other']
1006
- })
1007
- };
1008
- class PluralResolver {
1009
- constructor(languageUtils, options = {}) {
1010
- this.languageUtils = languageUtils;
1011
- this.options = options;
1012
- this.logger = baseLogger.create('pluralResolver');
1013
- this.pluralRulesCache = {};
1014
- }
1015
- addRule(lng, obj) {
1016
- this.rules[lng] = obj;
1017
- }
1018
- clearCache() {
1019
- this.pluralRulesCache = {};
1020
- }
1021
- getRule(code, options = {}) {
1022
- const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);
1023
- const type = options.ordinal ? 'ordinal' : 'cardinal';
1024
- const cacheKey = JSON.stringify({
1025
- cleanedCode,
1026
- type
1027
- });
1028
- if (cacheKey in this.pluralRulesCache) {
1029
- return this.pluralRulesCache[cacheKey];
1030
- }
1031
- let rule;
1032
- try {
1033
- rule = new Intl.PluralRules(cleanedCode, {
1034
- type
1035
- });
1036
- } catch (err) {
1037
- if (!Intl) {
1038
- this.logger.error('No Intl support, please use an Intl polyfill!');
1039
- return dummyRule;
1040
- }
1041
- if (!code.match(/-|_/)) return dummyRule;
1042
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1043
- rule = this.getRule(lngPart, options);
1044
- }
1045
- this.pluralRulesCache[cacheKey] = rule;
1046
- return rule;
1047
- }
1048
- needsPlural(code, options = {}) {
1049
- let rule = this.getRule(code, options);
1050
- if (!rule) rule = this.getRule('dev', options);
1051
- return rule?.resolvedOptions().pluralCategories.length > 1;
1052
- }
1053
- getPluralFormsOfKey(code, key, options = {}) {
1054
- return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);
1055
- }
1056
- getSuffixes(code, options = {}) {
1057
- let rule = this.getRule(code, options);
1058
- if (!rule) rule = this.getRule('dev', options);
1059
- if (!rule) return [];
1060
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);
1061
- }
1062
- getSuffix(code, count, options = {}) {
1063
- const rule = this.getRule(code, options);
1064
- if (rule) {
1065
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;
1066
- }
1067
- this.logger.warn(`no plural rule found for: ${code}`);
1068
- return this.getSuffix('dev', count, options);
1069
- }
1070
- }
1071
-
1072
- const deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {
1073
- let path = getPathWithDefaults(data, defaultData, key);
1074
- if (!path && ignoreJSONStructure && isString(key)) {
1075
- path = deepFind(data, key, keySeparator);
1076
- if (path === undefined) path = deepFind(defaultData, key, keySeparator);
1077
- }
1078
- return path;
1079
- };
1080
- const regexSafe = val => val.replace(/\$/g, '$$$$');
1081
- class Interpolator {
1082
- constructor(options = {}) {
1083
- this.logger = baseLogger.create('interpolator');
1084
- this.options = options;
1085
- this.format = options?.interpolation?.format || (value => value);
1086
- this.init(options);
1087
- }
1088
- init(options = {}) {
1089
- if (!options.interpolation) options.interpolation = {
1090
- escapeValue: true
1091
- };
1092
- const {
1093
- escape: escape$1,
1094
- escapeValue,
1095
- useRawValueToEscape,
1096
- prefix,
1097
- prefixEscaped,
1098
- suffix,
1099
- suffixEscaped,
1100
- formatSeparator,
1101
- unescapeSuffix,
1102
- unescapePrefix,
1103
- nestingPrefix,
1104
- nestingPrefixEscaped,
1105
- nestingSuffix,
1106
- nestingSuffixEscaped,
1107
- nestingOptionsSeparator,
1108
- maxReplaces,
1109
- alwaysFormat
1110
- } = options.interpolation;
1111
- this.escape = escape$1 !== undefined ? escape$1 : escape;
1112
- this.escapeValue = escapeValue !== undefined ? escapeValue : true;
1113
- this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;
1114
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';
1115
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';
1116
- this.formatSeparator = formatSeparator || ',';
1117
- this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';
1118
- this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';
1119
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');
1120
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');
1121
- this.nestingOptionsSeparator = nestingOptionsSeparator || ',';
1122
- this.maxReplaces = maxReplaces || 1000;
1123
- this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;
1124
- this.resetRegExp();
1125
- }
1126
- reset() {
1127
- if (this.options) this.init(this.options);
1128
- }
1129
- resetRegExp() {
1130
- const getOrResetRegExp = (existingRegExp, pattern) => {
1131
- if (existingRegExp?.source === pattern) {
1132
- existingRegExp.lastIndex = 0;
1133
- return existingRegExp;
1134
- }
1135
- return new RegExp(pattern, 'g');
1136
- };
1137
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1138
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1139
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1140
- }
1141
- interpolate(str, data, lng, options) {
1142
- let match;
1143
- let value;
1144
- let replaces;
1145
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1146
- const handleFormat = key => {
1147
- if (key.indexOf(this.formatSeparator) < 0) {
1148
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1149
- return this.alwaysFormat ? this.format(path, undefined, lng, {
1150
- ...options,
1151
- ...data,
1152
- interpolationkey: key
1153
- }) : path;
1154
- }
1155
- const p = key.split(this.formatSeparator);
1156
- const k = p.shift().trim();
1157
- const f = p.join(this.formatSeparator).trim();
1158
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1159
- ...options,
1160
- ...data,
1161
- interpolationkey: k
1162
- });
1163
- };
1164
- this.resetRegExp();
1165
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1166
- const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1167
- const todos = [{
1168
- regex: this.regexpUnescape,
1169
- safeValue: val => regexSafe(val)
1170
- }, {
1171
- regex: this.regexp,
1172
- safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1173
- }];
1174
- todos.forEach(todo => {
1175
- replaces = 0;
1176
- while (match = todo.regex.exec(str)) {
1177
- const matchedVar = match[1].trim();
1178
- value = handleFormat(matchedVar);
1179
- if (value === undefined) {
1180
- if (typeof missingInterpolationHandler === 'function') {
1181
- const temp = missingInterpolationHandler(str, match, options);
1182
- value = isString(temp) ? temp : '';
1183
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1184
- value = '';
1185
- } else if (skipOnVariables) {
1186
- value = match[0];
1187
- continue;
1188
- } else {
1189
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1190
- value = '';
1191
- }
1192
- } else if (!isString(value) && !this.useRawValueToEscape) {
1193
- value = makeString(value);
1194
- }
1195
- const safeValue = todo.safeValue(value);
1196
- str = str.replace(match[0], safeValue);
1197
- if (skipOnVariables) {
1198
- todo.regex.lastIndex += value.length;
1199
- todo.regex.lastIndex -= match[0].length;
1200
- } else {
1201
- todo.regex.lastIndex = 0;
1202
- }
1203
- replaces++;
1204
- if (replaces >= this.maxReplaces) {
1205
- break;
1206
- }
1207
- }
1208
- });
1209
- return str;
1210
- }
1211
- nest(str, fc, options = {}) {
1212
- let match;
1213
- let value;
1214
- let clonedOptions;
1215
- const handleHasOptions = (key, inheritedOptions) => {
1216
- const sep = this.nestingOptionsSeparator;
1217
- if (key.indexOf(sep) < 0) return key;
1218
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1219
- let optionsString = `{${c[1]}`;
1220
- key = c[0];
1221
- optionsString = this.interpolate(optionsString, clonedOptions);
1222
- const matchedSingleQuotes = optionsString.match(/'/g);
1223
- const matchedDoubleQuotes = optionsString.match(/"/g);
1224
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1225
- optionsString = optionsString.replace(/'/g, '"');
1226
- }
1227
- try {
1228
- clonedOptions = JSON.parse(optionsString);
1229
- if (inheritedOptions) clonedOptions = {
1230
- ...inheritedOptions,
1231
- ...clonedOptions
1232
- };
1233
- } catch (e) {
1234
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1235
- return `${key}${sep}${optionsString}`;
1236
- }
1237
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1238
- return key;
1239
- };
1240
- while (match = this.nestingRegexp.exec(str)) {
1241
- let formatters = [];
1242
- clonedOptions = {
1243
- ...options
1244
- };
1245
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1246
- clonedOptions.applyPostProcessor = false;
1247
- delete clonedOptions.defaultValue;
1248
- const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);
1249
- if (keyEndIndex !== -1) {
1250
- formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);
1251
- match[1] = match[1].slice(0, keyEndIndex);
1252
- }
1253
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1254
- if (value && match[0] === str && !isString(value)) return value;
1255
- if (!isString(value)) value = makeString(value);
1256
- if (!value) {
1257
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1258
- value = '';
1259
- }
1260
- if (formatters.length) {
1261
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1262
- ...options,
1263
- interpolationkey: match[1].trim()
1264
- }), value.trim());
1265
- }
1266
- str = str.replace(match[0], value);
1267
- this.regexp.lastIndex = 0;
1268
- }
1269
- return str;
1270
- }
1271
- }
1272
-
1273
- const parseFormatStr = formatStr => {
1274
- let formatName = formatStr.toLowerCase().trim();
1275
- const formatOptions = {};
1276
- if (formatStr.indexOf('(') > -1) {
1277
- const p = formatStr.split('(');
1278
- formatName = p[0].toLowerCase().trim();
1279
- const optStr = p[1].substring(0, p[1].length - 1);
1280
- if (formatName === 'currency' && optStr.indexOf(':') < 0) {
1281
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1282
- } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {
1283
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1284
- } else {
1285
- const opts = optStr.split(';');
1286
- opts.forEach(opt => {
1287
- if (opt) {
1288
- const [key, ...rest] = opt.split(':');
1289
- const val = rest.join(':').trim().replace(/^'+|'+$/g, '');
1290
- const trimmedKey = key.trim();
1291
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1292
- if (val === 'false') formatOptions[trimmedKey] = false;
1293
- if (val === 'true') formatOptions[trimmedKey] = true;
1294
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1295
- }
1296
- });
1297
- }
1298
- }
1299
- return {
1300
- formatName,
1301
- formatOptions
1302
- };
1303
- };
1304
- const createCachedFormatter = fn => {
1305
- const cache = {};
1306
- return (v, l, o) => {
1307
- let optForCache = o;
1308
- if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1309
- optForCache = {
1310
- ...optForCache,
1311
- [o.interpolationkey]: undefined
1312
- };
1313
- }
1314
- const key = l + JSON.stringify(optForCache);
1315
- let frm = cache[key];
1316
- if (!frm) {
1317
- frm = fn(getCleanedCode(l), o);
1318
- cache[key] = frm;
1319
- }
1320
- return frm(v);
1321
- };
1322
- };
1323
- const createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);
1324
- class Formatter {
1325
- constructor(options = {}) {
1326
- this.logger = baseLogger.create('formatter');
1327
- this.options = options;
1328
- this.init(options);
1329
- }
1330
- init(services, options = {
1331
- interpolation: {}
1332
- }) {
1333
- this.formatSeparator = options.interpolation.formatSeparator || ',';
1334
- const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1335
- this.formats = {
1336
- number: cf((lng, opt) => {
1337
- const formatter = new Intl.NumberFormat(lng, {
1338
- ...opt
1339
- });
1340
- return val => formatter.format(val);
1341
- }),
1342
- currency: cf((lng, opt) => {
1343
- const formatter = new Intl.NumberFormat(lng, {
1344
- ...opt,
1345
- style: 'currency'
1346
- });
1347
- return val => formatter.format(val);
1348
- }),
1349
- datetime: cf((lng, opt) => {
1350
- const formatter = new Intl.DateTimeFormat(lng, {
1351
- ...opt
1352
- });
1353
- return val => formatter.format(val);
1354
- }),
1355
- relativetime: cf((lng, opt) => {
1356
- const formatter = new Intl.RelativeTimeFormat(lng, {
1357
- ...opt
1358
- });
1359
- return val => formatter.format(val, opt.range || 'day');
1360
- }),
1361
- list: cf((lng, opt) => {
1362
- const formatter = new Intl.ListFormat(lng, {
1363
- ...opt
1364
- });
1365
- return val => formatter.format(val);
1366
- })
1367
- };
1368
- }
1369
- add(name, fc) {
1370
- this.formats[name.toLowerCase().trim()] = fc;
1371
- }
1372
- addCached(name, fc) {
1373
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1374
- }
1375
- format(value, format, lng, options = {}) {
1376
- const formats = format.split(this.formatSeparator);
1377
- if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {
1378
- const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);
1379
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1380
- }
1381
- const result = formats.reduce((mem, f) => {
1382
- const {
1383
- formatName,
1384
- formatOptions
1385
- } = parseFormatStr(f);
1386
- if (this.formats[formatName]) {
1387
- let formatted = mem;
1388
- try {
1389
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1390
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1391
- formatted = this.formats[formatName](mem, l, {
1392
- ...formatOptions,
1393
- ...options,
1394
- ...valOptions
1395
- });
1396
- } catch (error) {
1397
- this.logger.warn(error);
1398
- }
1399
- return formatted;
1400
- } else {
1401
- this.logger.warn(`there was no format function for ${formatName}`);
1402
- }
1403
- return mem;
1404
- }, value);
1405
- return result;
1406
- }
1407
- }
1408
-
1409
- const removePending = (q, name) => {
1410
- if (q.pending[name] !== undefined) {
1411
- delete q.pending[name];
1412
- q.pendingCount--;
1413
- }
1414
- };
1415
- class Connector extends EventEmitter {
1416
- constructor(backend, store, services, options = {}) {
1417
- super();
1418
- this.backend = backend;
1419
- this.store = store;
1420
- this.services = services;
1421
- this.languageUtils = services.languageUtils;
1422
- this.options = options;
1423
- this.logger = baseLogger.create('backendConnector');
1424
- this.waitingReads = [];
1425
- this.maxParallelReads = options.maxParallelReads || 10;
1426
- this.readingCalls = 0;
1427
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1428
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1429
- this.state = {};
1430
- this.queue = [];
1431
- this.backend?.init?.(services, options.backend, options);
1432
- }
1433
- queueLoad(languages, namespaces, options, callback) {
1434
- const toLoad = {};
1435
- const pending = {};
1436
- const toLoadLanguages = {};
1437
- const toLoadNamespaces = {};
1438
- languages.forEach(lng => {
1439
- let hasAllNamespaces = true;
1440
- namespaces.forEach(ns => {
1441
- const name = `${lng}|${ns}`;
1442
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1443
- this.state[name] = 2;
1444
- } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {
1445
- if (pending[name] === undefined) pending[name] = true;
1446
- } else {
1447
- this.state[name] = 1;
1448
- hasAllNamespaces = false;
1449
- if (pending[name] === undefined) pending[name] = true;
1450
- if (toLoad[name] === undefined) toLoad[name] = true;
1451
- if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;
1452
- }
1453
- });
1454
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1455
- });
1456
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1457
- this.queue.push({
1458
- pending,
1459
- pendingCount: Object.keys(pending).length,
1460
- loaded: {},
1461
- errors: [],
1462
- callback
1463
- });
1464
- }
1465
- return {
1466
- toLoad: Object.keys(toLoad),
1467
- pending: Object.keys(pending),
1468
- toLoadLanguages: Object.keys(toLoadLanguages),
1469
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1470
- };
1471
- }
1472
- loaded(name, err, data) {
1473
- const s = name.split('|');
1474
- const lng = s[0];
1475
- const ns = s[1];
1476
- if (err) this.emit('failedLoading', lng, ns, err);
1477
- if (!err && data) {
1478
- this.store.addResourceBundle(lng, ns, data, undefined, undefined, {
1479
- skipCopy: true
1480
- });
1481
- }
1482
- this.state[name] = err ? -1 : 2;
1483
- if (err && data) this.state[name] = 0;
1484
- const loaded = {};
1485
- this.queue.forEach(q => {
1486
- pushPath(q.loaded, [lng], ns);
1487
- removePending(q, name);
1488
- if (err) q.errors.push(err);
1489
- if (q.pendingCount === 0 && !q.done) {
1490
- Object.keys(q.loaded).forEach(l => {
1491
- if (!loaded[l]) loaded[l] = {};
1492
- const loadedKeys = q.loaded[l];
1493
- if (loadedKeys.length) {
1494
- loadedKeys.forEach(n => {
1495
- if (loaded[l][n] === undefined) loaded[l][n] = true;
1496
- });
1497
- }
1498
- });
1499
- q.done = true;
1500
- if (q.errors.length) {
1501
- q.callback(q.errors);
1502
- } else {
1503
- q.callback();
1504
- }
1505
- }
1506
- });
1507
- this.emit('loaded', loaded);
1508
- this.queue = this.queue.filter(q => !q.done);
1509
- }
1510
- read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1511
- if (!lng.length) return callback(null, {});
1512
- if (this.readingCalls >= this.maxParallelReads) {
1513
- this.waitingReads.push({
1514
- lng,
1515
- ns,
1516
- fcName,
1517
- tried,
1518
- wait,
1519
- callback
1520
- });
1521
- return;
1522
- }
1523
- this.readingCalls++;
1524
- const resolver = (err, data) => {
1525
- this.readingCalls--;
1526
- if (this.waitingReads.length > 0) {
1527
- const next = this.waitingReads.shift();
1528
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1529
- }
1530
- if (err && data && tried < this.maxRetries) {
1531
- setTimeout(() => {
1532
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1533
- }, wait);
1534
- return;
1535
- }
1536
- callback(err, data);
1537
- };
1538
- const fc = this.backend[fcName].bind(this.backend);
1539
- if (fc.length === 2) {
1540
- try {
1541
- const r = fc(lng, ns);
1542
- if (r && typeof r.then === 'function') {
1543
- r.then(data => resolver(null, data)).catch(resolver);
1544
- } else {
1545
- resolver(null, r);
1546
- }
1547
- } catch (err) {
1548
- resolver(err);
1549
- }
1550
- return;
1551
- }
1552
- return fc(lng, ns, resolver);
1553
- }
1554
- prepareLoading(languages, namespaces, options = {}, callback) {
1555
- if (!this.backend) {
1556
- this.logger.warn('No backend was added via i18next.use. Will not load resources.');
1557
- return callback && callback();
1558
- }
1559
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1560
- if (isString(namespaces)) namespaces = [namespaces];
1561
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1562
- if (!toLoad.toLoad.length) {
1563
- if (!toLoad.pending.length) callback();
1564
- return null;
1565
- }
1566
- toLoad.toLoad.forEach(name => {
1567
- this.loadOne(name);
1568
- });
1569
- }
1570
- load(languages, namespaces, callback) {
1571
- this.prepareLoading(languages, namespaces, {}, callback);
1572
- }
1573
- reload(languages, namespaces, callback) {
1574
- this.prepareLoading(languages, namespaces, {
1575
- reload: true
1576
- }, callback);
1577
- }
1578
- loadOne(name, prefix = '') {
1579
- const s = name.split('|');
1580
- const lng = s[0];
1581
- const ns = s[1];
1582
- this.read(lng, ns, 'read', undefined, undefined, (err, data) => {
1583
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1584
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1585
- this.loaded(name, err, data);
1586
- });
1587
- }
1588
- saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {
1589
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1590
- this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
1591
- return;
1592
- }
1593
- if (key === undefined || key === null || key === '') return;
1594
- if (this.backend?.create) {
1595
- const opts = {
1596
- ...options,
1597
- isUpdate
1598
- };
1599
- const fc = this.backend.create.bind(this.backend);
1600
- if (fc.length < 6) {
1601
- try {
1602
- let r;
1603
- if (fc.length === 5) {
1604
- r = fc(languages, namespace, key, fallbackValue, opts);
1605
- } else {
1606
- r = fc(languages, namespace, key, fallbackValue);
1607
- }
1608
- if (r && typeof r.then === 'function') {
1609
- r.then(data => clb(null, data)).catch(clb);
1610
- } else {
1611
- clb(null, r);
1612
- }
1613
- } catch (err) {
1614
- clb(err);
1615
- }
1616
- } else {
1617
- fc(languages, namespace, key, fallbackValue, clb, opts);
1618
- }
1619
- }
1620
- if (!languages || !languages[0]) return;
1621
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1622
- }
1623
- }
1624
-
1625
- const get = () => ({
1626
- debug: false,
1627
- initAsync: true,
1628
- ns: ['translation'],
1629
- defaultNS: ['translation'],
1630
- fallbackLng: ['dev'],
1631
- fallbackNS: false,
1632
- supportedLngs: false,
1633
- nonExplicitSupportedLngs: false,
1634
- load: 'all',
1635
- preload: false,
1636
- simplifyPluralSuffix: true,
1637
- keySeparator: '.',
1638
- nsSeparator: ':',
1639
- pluralSeparator: '_',
1640
- contextSeparator: '_',
1641
- partialBundledLanguages: false,
1642
- saveMissing: false,
1643
- updateMissing: false,
1644
- saveMissingTo: 'fallback',
1645
- saveMissingPlurals: true,
1646
- missingKeyHandler: false,
1647
- missingInterpolationHandler: false,
1648
- postProcess: false,
1649
- postProcessPassResolved: false,
1650
- returnNull: false,
1651
- returnEmptyString: true,
1652
- returnObjects: false,
1653
- joinArrays: false,
1654
- returnedObjectHandler: false,
1655
- parseMissingKeyHandler: false,
1656
- appendNamespaceToMissingKey: false,
1657
- appendNamespaceToCIMode: false,
1658
- overloadTranslationOptionHandler: args => {
1659
- let ret = {};
1660
- if (typeof args[1] === 'object') ret = args[1];
1661
- if (isString(args[1])) ret.defaultValue = args[1];
1662
- if (isString(args[2])) ret.tDescription = args[2];
1663
- if (typeof args[2] === 'object' || typeof args[3] === 'object') {
1664
- const options = args[3] || args[2];
1665
- Object.keys(options).forEach(key => {
1666
- ret[key] = options[key];
1667
- });
1668
- }
1669
- return ret;
1670
- },
1671
- interpolation: {
1672
- escapeValue: true,
1673
- format: value => value,
1674
- prefix: '{{',
1675
- suffix: '}}',
1676
- formatSeparator: ',',
1677
- unescapePrefix: '-',
1678
- nestingPrefix: '$t(',
1679
- nestingSuffix: ')',
1680
- nestingOptionsSeparator: ',',
1681
- maxReplaces: 1000,
1682
- skipOnVariables: true
1683
- },
1684
- cacheInBuiltFormats: true
1685
- });
1686
- const transformOptions = options => {
1687
- if (isString(options.ns)) options.ns = [options.ns];
1688
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1689
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1690
- if (options.supportedLngs?.indexOf?.('cimode') < 0) {
1691
- options.supportedLngs = options.supportedLngs.concat(['cimode']);
1692
- }
1693
- if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;
1694
- return options;
1695
- };
1696
-
1697
- const noop = () => {};
1698
- const bindMemberFunctions = inst => {
1699
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1700
- mems.forEach(mem => {
1701
- if (typeof inst[mem] === 'function') {
1702
- inst[mem] = inst[mem].bind(inst);
1703
- }
1704
- });
1705
- };
1706
- class I18n extends EventEmitter {
1707
- constructor(options = {}, callback) {
1708
- super();
1709
- this.options = transformOptions(options);
1710
- this.services = {};
1711
- this.logger = baseLogger;
1712
- this.modules = {
1713
- external: []
1714
- };
1715
- bindMemberFunctions(this);
1716
- if (callback && !this.isInitialized && !options.isClone) {
1717
- if (!this.options.initAsync) {
1718
- this.init(options, callback);
1719
- return this;
1720
- }
1721
- setTimeout(() => {
1722
- this.init(options, callback);
1723
- }, 0);
1724
- }
1725
- }
1726
- init(options = {}, callback) {
1727
- this.isInitializing = true;
1728
- if (typeof options === 'function') {
1729
- callback = options;
1730
- options = {};
1731
- }
1732
- if (options.defaultNS == null && options.ns) {
1733
- if (isString(options.ns)) {
1734
- options.defaultNS = options.ns;
1735
- } else if (options.ns.indexOf('translation') < 0) {
1736
- options.defaultNS = options.ns[0];
1737
- }
1738
- }
1739
- const defOpts = get();
1740
- this.options = {
1741
- ...defOpts,
1742
- ...this.options,
1743
- ...transformOptions(options)
1744
- };
1745
- this.options.interpolation = {
1746
- ...defOpts.interpolation,
1747
- ...this.options.interpolation
1748
- };
1749
- if (options.keySeparator !== undefined) {
1750
- this.options.userDefinedKeySeparator = options.keySeparator;
1751
- }
1752
- if (options.nsSeparator !== undefined) {
1753
- this.options.userDefinedNsSeparator = options.nsSeparator;
1754
- }
1755
- const createClassOnDemand = ClassOrObject => {
1756
- if (!ClassOrObject) return null;
1757
- if (typeof ClassOrObject === 'function') return new ClassOrObject();
1758
- return ClassOrObject;
1759
- };
1760
- if (!this.options.isClone) {
1761
- if (this.modules.logger) {
1762
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1763
- } else {
1764
- baseLogger.init(null, this.options);
1765
- }
1766
- let formatter;
1767
- if (this.modules.formatter) {
1768
- formatter = this.modules.formatter;
1769
- } else {
1770
- formatter = Formatter;
1771
- }
1772
- const lu = new LanguageUtil(this.options);
1773
- this.store = new ResourceStore(this.options.resources, this.options);
1774
- const s = this.services;
1775
- s.logger = baseLogger;
1776
- s.resourceStore = this.store;
1777
- s.languageUtils = lu;
1778
- s.pluralResolver = new PluralResolver(lu, {
1779
- prepend: this.options.pluralSeparator,
1780
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1781
- });
1782
- const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
1783
- if (usingLegacyFormatFunction) {
1784
- this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1785
- }
1786
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1787
- s.formatter = createClassOnDemand(formatter);
1788
- if (s.formatter.init) s.formatter.init(s, this.options);
1789
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1790
- }
1791
- s.interpolator = new Interpolator(this.options);
1792
- s.utils = {
1793
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1794
- };
1795
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1796
- s.backendConnector.on('*', (event, ...args) => {
1797
- this.emit(event, ...args);
1798
- });
1799
- if (this.modules.languageDetector) {
1800
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1801
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1802
- }
1803
- if (this.modules.i18nFormat) {
1804
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1805
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1806
- }
1807
- this.translator = new Translator(this.services, this.options);
1808
- this.translator.on('*', (event, ...args) => {
1809
- this.emit(event, ...args);
1810
- });
1811
- this.modules.external.forEach(m => {
1812
- if (m.init) m.init(this);
1813
- });
1814
- }
1815
- this.format = this.options.interpolation.format;
1816
- if (!callback) callback = noop;
1817
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1818
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1819
- if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];
1820
- }
1821
- if (!this.services.languageDetector && !this.options.lng) {
1822
- this.logger.warn('init: no languageDetector is used and no lng is defined');
1823
- }
1824
- const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
1825
- storeApi.forEach(fcName => {
1826
- this[fcName] = (...args) => this.store[fcName](...args);
1827
- });
1828
- const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];
1829
- storeApiChained.forEach(fcName => {
1830
- this[fcName] = (...args) => {
1831
- this.store[fcName](...args);
1832
- return this;
1833
- };
1834
- });
1835
- const deferred = defer();
1836
- const load = () => {
1837
- const finish = (err, t) => {
1838
- this.isInitializing = false;
1839
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');
1840
- this.isInitialized = true;
1841
- if (!this.options.isClone) this.logger.log('initialized', this.options);
1842
- this.emit('initialized', this.options);
1843
- deferred.resolve(t);
1844
- callback(err, t);
1845
- };
1846
- if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1847
- this.changeLanguage(this.options.lng, finish);
1848
- };
1849
- if (this.options.resources || !this.options.initAsync) {
1850
- load();
1851
- } else {
1852
- setTimeout(load, 0);
1853
- }
1854
- return deferred;
1855
- }
1856
- loadResources(language, callback = noop) {
1857
- let usedCallback = callback;
1858
- const usedLng = isString(language) ? language : this.language;
1859
- if (typeof language === 'function') usedCallback = language;
1860
- if (!this.options.resources || this.options.partialBundledLanguages) {
1861
- if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1862
- const toLoad = [];
1863
- const append = lng => {
1864
- if (!lng) return;
1865
- if (lng === 'cimode') return;
1866
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1867
- lngs.forEach(l => {
1868
- if (l === 'cimode') return;
1869
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
1870
- });
1871
- };
1872
- if (!usedLng) {
1873
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1874
- fallbacks.forEach(l => append(l));
1875
- } else {
1876
- append(usedLng);
1877
- }
1878
- this.options.preload?.forEach?.(l => append(l));
1879
- this.services.backendConnector.load(toLoad, this.options.ns, e => {
1880
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1881
- usedCallback(e);
1882
- });
1883
- } else {
1884
- usedCallback(null);
1885
- }
1886
- }
1887
- reloadResources(lngs, ns, callback) {
1888
- const deferred = defer();
1889
- if (typeof lngs === 'function') {
1890
- callback = lngs;
1891
- lngs = undefined;
1892
- }
1893
- if (typeof ns === 'function') {
1894
- callback = ns;
1895
- ns = undefined;
1896
- }
1897
- if (!lngs) lngs = this.languages;
1898
- if (!ns) ns = this.options.ns;
1899
- if (!callback) callback = noop;
1900
- this.services.backendConnector.reload(lngs, ns, err => {
1901
- deferred.resolve();
1902
- callback(err);
1903
- });
1904
- return deferred;
1905
- }
1906
- use(module) {
1907
- if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
1908
- if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
1909
- if (module.type === 'backend') {
1910
- this.modules.backend = module;
1911
- }
1912
- if (module.type === 'logger' || module.log && module.warn && module.error) {
1913
- this.modules.logger = module;
1914
- }
1915
- if (module.type === 'languageDetector') {
1916
- this.modules.languageDetector = module;
1917
- }
1918
- if (module.type === 'i18nFormat') {
1919
- this.modules.i18nFormat = module;
1920
- }
1921
- if (module.type === 'postProcessor') {
1922
- postProcessor.addPostProcessor(module);
1923
- }
1924
- if (module.type === 'formatter') {
1925
- this.modules.formatter = module;
1926
- }
1927
- if (module.type === '3rdParty') {
1928
- this.modules.external.push(module);
1929
- }
1930
- return this;
1931
- }
1932
- setResolvedLanguage(l) {
1933
- if (!l || !this.languages) return;
1934
- if (['cimode', 'dev'].indexOf(l) > -1) return;
1935
- for (let li = 0; li < this.languages.length; li++) {
1936
- const lngInLngs = this.languages[li];
1937
- if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;
1938
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
1939
- this.resolvedLanguage = lngInLngs;
1940
- break;
1941
- }
1942
- }
1943
- if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
1944
- this.resolvedLanguage = l;
1945
- this.languages.unshift(l);
1946
- }
1947
- }
1948
- changeLanguage(lng, callback) {
1949
- this.isLanguageChangingTo = lng;
1950
- const deferred = defer();
1951
- this.emit('languageChanging', lng);
1952
- const setLngProps = l => {
1953
- this.language = l;
1954
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
1955
- this.resolvedLanguage = undefined;
1956
- this.setResolvedLanguage(l);
1957
- };
1958
- const done = (err, l) => {
1959
- if (l) {
1960
- if (this.isLanguageChangingTo === lng) {
1961
- setLngProps(l);
1962
- this.translator.changeLanguage(l);
1963
- this.isLanguageChangingTo = undefined;
1964
- this.emit('languageChanged', l);
1965
- this.logger.log('languageChanged', l);
1966
- }
1967
- } else {
1968
- this.isLanguageChangingTo = undefined;
1969
- }
1970
- deferred.resolve((...args) => this.t(...args));
1971
- if (callback) callback(err, (...args) => this.t(...args));
1972
- };
1973
- const setLng = lngs => {
1974
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
1975
- const fl = isString(lngs) ? lngs : lngs && lngs[0];
1976
- const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
1977
- if (l) {
1978
- if (!this.language) {
1979
- setLngProps(l);
1980
- }
1981
- if (!this.translator.language) this.translator.changeLanguage(l);
1982
- this.services.languageDetector?.cacheUserLanguage?.(l);
1983
- }
1984
- this.loadResources(l, err => {
1985
- done(err, l);
1986
- });
1987
- };
1988
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
1989
- setLng(this.services.languageDetector.detect());
1990
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
1991
- if (this.services.languageDetector.detect.length === 0) {
1992
- this.services.languageDetector.detect().then(setLng);
1993
- } else {
1994
- this.services.languageDetector.detect(setLng);
1995
- }
1996
- } else {
1997
- setLng(lng);
1998
- }
1999
- return deferred;
2000
- }
2001
- getFixedT(lng, ns, keyPrefix) {
2002
- const fixedT = (key, opts, ...rest) => {
2003
- let o;
2004
- if (typeof opts !== 'object') {
2005
- o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2006
- } else {
2007
- o = {
2008
- ...opts
2009
- };
2010
- }
2011
- o.lng = o.lng || fixedT.lng;
2012
- o.lngs = o.lngs || fixedT.lngs;
2013
- o.ns = o.ns || fixedT.ns;
2014
- if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2015
- const keySeparator = this.options.keySeparator || '.';
2016
- let resultKey;
2017
- if (o.keyPrefix && Array.isArray(key)) {
2018
- resultKey = key.map(k => {
2019
- if (typeof k === 'function') k = keysFromSelector(k, {
2020
- ...this.options,
2021
- ...opts
2022
- });
2023
- return `${o.keyPrefix}${keySeparator}${k}`;
2024
- });
2025
- } else {
2026
- if (typeof key === 'function') key = keysFromSelector(key, {
2027
- ...this.options,
2028
- ...opts
2029
- });
2030
- resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2031
- }
2032
- return this.t(resultKey, o);
2033
- };
2034
- if (isString(lng)) {
2035
- fixedT.lng = lng;
2036
- } else {
2037
- fixedT.lngs = lng;
2038
- }
2039
- fixedT.ns = ns;
2040
- fixedT.keyPrefix = keyPrefix;
2041
- return fixedT;
2042
- }
2043
- t(...args) {
2044
- return this.translator?.translate(...args);
2045
- }
2046
- exists(...args) {
2047
- return this.translator?.exists(...args);
2048
- }
2049
- setDefaultNamespace(ns) {
2050
- this.options.defaultNS = ns;
2051
- }
2052
- hasLoadedNamespace(ns, options = {}) {
2053
- if (!this.isInitialized) {
2054
- this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
2055
- return false;
2056
- }
2057
- if (!this.languages || !this.languages.length) {
2058
- this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
2059
- return false;
2060
- }
2061
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2062
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2063
- const lastLng = this.languages[this.languages.length - 1];
2064
- if (lng.toLowerCase() === 'cimode') return true;
2065
- const loadNotPending = (l, n) => {
2066
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2067
- return loadState === -1 || loadState === 0 || loadState === 2;
2068
- };
2069
- if (options.precheck) {
2070
- const preResult = options.precheck(this, loadNotPending);
2071
- if (preResult !== undefined) return preResult;
2072
- }
2073
- if (this.hasResourceBundle(lng, ns)) return true;
2074
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2075
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2076
- return false;
2077
- }
2078
- loadNamespaces(ns, callback) {
2079
- const deferred = defer();
2080
- if (!this.options.ns) {
2081
- if (callback) callback();
2082
- return Promise.resolve();
2083
- }
2084
- if (isString(ns)) ns = [ns];
2085
- ns.forEach(n => {
2086
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2087
- });
2088
- this.loadResources(err => {
2089
- deferred.resolve();
2090
- if (callback) callback(err);
2091
- });
2092
- return deferred;
2093
- }
2094
- loadLanguages(lngs, callback) {
2095
- const deferred = defer();
2096
- if (isString(lngs)) lngs = [lngs];
2097
- const preloaded = this.options.preload || [];
2098
- const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2099
- if (!newLngs.length) {
2100
- if (callback) callback();
2101
- return Promise.resolve();
2102
- }
2103
- this.options.preload = preloaded.concat(newLngs);
2104
- this.loadResources(err => {
2105
- deferred.resolve();
2106
- if (callback) callback(err);
2107
- });
2108
- return deferred;
2109
- }
2110
- dir(lng) {
2111
- if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2112
- if (!lng) return 'rtl';
2113
- try {
2114
- const l = new Intl.Locale(lng);
2115
- if (l && l.getTextInfo) {
2116
- const ti = l.getTextInfo();
2117
- if (ti && ti.direction) return ti.direction;
2118
- }
2119
- } catch (e) {}
2120
- const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];
2121
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2122
- if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';
2123
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';
2124
- }
2125
- static createInstance(options = {}, callback) {
2126
- const instance = new I18n(options, callback);
2127
- instance.createInstance = I18n.createInstance;
2128
- return instance;
2129
- }
2130
- cloneInstance(options = {}, callback = noop) {
2131
- const forkResourceStore = options.forkResourceStore;
2132
- if (forkResourceStore) delete options.forkResourceStore;
2133
- const mergedOptions = {
2134
- ...this.options,
2135
- ...options,
2136
- ...{
2137
- isClone: true
2138
- }
2139
- };
2140
- const clone = new I18n(mergedOptions);
2141
- if (options.debug !== undefined || options.prefix !== undefined) {
2142
- clone.logger = clone.logger.clone(options);
2143
- }
2144
- const membersToCopy = ['store', 'services', 'language'];
2145
- membersToCopy.forEach(m => {
2146
- clone[m] = this[m];
2147
- });
2148
- clone.services = {
2149
- ...this.services
2150
- };
2151
- clone.services.utils = {
2152
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2153
- };
2154
- if (forkResourceStore) {
2155
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2156
- prev[l] = {
2157
- ...this.store.data[l]
2158
- };
2159
- prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2160
- acc[n] = {
2161
- ...prev[l][n]
2162
- };
2163
- return acc;
2164
- }, prev[l]);
2165
- return prev;
2166
- }, {});
2167
- clone.store = new ResourceStore(clonedData, mergedOptions);
2168
- clone.services.resourceStore = clone.store;
2169
- }
2170
- clone.translator = new Translator(clone.services, mergedOptions);
2171
- clone.translator.on('*', (event, ...args) => {
2172
- clone.emit(event, ...args);
2173
- });
2174
- clone.init(mergedOptions, callback);
2175
- clone.translator.options = mergedOptions;
2176
- clone.translator.backendConnector.services.utils = {
2177
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2178
- };
2179
- return clone;
2180
- }
2181
- toJSON() {
2182
- return {
2183
- options: this.options,
2184
- store: this.store,
2185
- language: this.language,
2186
- languages: this.languages,
2187
- resolvedLanguage: this.resolvedLanguage
2188
- };
2189
- }
2190
- }
2191
- const instance = I18n.createInstance();
2192
-
2193
- const {
2194
- slice,
2195
- forEach
2196
- } = [];
2197
- function defaults(obj) {
2198
- forEach.call(slice.call(arguments, 1), source => {
2199
- if (source) {
2200
- for (const prop in source) {
2201
- if (obj[prop] === undefined) obj[prop] = source[prop];
2202
- }
2203
- }
2204
- });
2205
- return obj;
2206
- }
2207
- function hasXSS(input) {
2208
- if (typeof input !== 'string') return false;
2209
-
2210
- // Common XSS attack patterns
2211
- const xssPatterns = [/<\s*script.*?>/i, /<\s*\/\s*script\s*>/i, /<\s*img.*?on\w+\s*=/i, /<\s*\w+\s*on\w+\s*=.*?>/i, /javascript\s*:/i, /vbscript\s*:/i, /expression\s*\(/i, /eval\s*\(/i, /alert\s*\(/i, /document\.cookie/i, /document\.write\s*\(/i, /window\.location/i, /innerHTML/i];
2212
- return xssPatterns.some(pattern => pattern.test(input));
2213
- }
2214
-
2215
- // eslint-disable-next-line no-control-regex
2216
- const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
2217
- const serializeCookie = function (name, val) {
2218
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
2219
- path: '/'
2220
- };
2221
- const opt = options;
2222
- const value = encodeURIComponent(val);
2223
- let str = `${name}=${value}`;
2224
- if (opt.maxAge > 0) {
2225
- const maxAge = opt.maxAge - 0;
2226
- if (Number.isNaN(maxAge)) throw new Error('maxAge should be a Number');
2227
- str += `; Max-Age=${Math.floor(maxAge)}`;
2228
- }
2229
- if (opt.domain) {
2230
- if (!fieldContentRegExp.test(opt.domain)) {
2231
- throw new TypeError('option domain is invalid');
2232
- }
2233
- str += `; Domain=${opt.domain}`;
2234
- }
2235
- if (opt.path) {
2236
- if (!fieldContentRegExp.test(opt.path)) {
2237
- throw new TypeError('option path is invalid');
2238
- }
2239
- str += `; Path=${opt.path}`;
2240
- }
2241
- if (opt.expires) {
2242
- if (typeof opt.expires.toUTCString !== 'function') {
2243
- throw new TypeError('option expires is invalid');
2244
- }
2245
- str += `; Expires=${opt.expires.toUTCString()}`;
2246
- }
2247
- if (opt.httpOnly) str += '; HttpOnly';
2248
- if (opt.secure) str += '; Secure';
2249
- if (opt.sameSite) {
2250
- const sameSite = typeof opt.sameSite === 'string' ? opt.sameSite.toLowerCase() : opt.sameSite;
2251
- switch (sameSite) {
2252
- case true:
2253
- str += '; SameSite=Strict';
2254
- break;
2255
- case 'lax':
2256
- str += '; SameSite=Lax';
2257
- break;
2258
- case 'strict':
2259
- str += '; SameSite=Strict';
2260
- break;
2261
- case 'none':
2262
- str += '; SameSite=None';
2263
- break;
2264
- default:
2265
- throw new TypeError('option sameSite is invalid');
2266
- }
2267
- }
2268
- if (opt.partitioned) str += '; Partitioned';
2269
- return str;
2270
- };
2271
- const cookie = {
2272
- create(name, value, minutes, domain) {
2273
- let cookieOptions = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
2274
- path: '/',
2275
- sameSite: 'strict'
2276
- };
2277
- if (minutes) {
2278
- cookieOptions.expires = new Date();
2279
- cookieOptions.expires.setTime(cookieOptions.expires.getTime() + minutes * 60 * 1000);
2280
- }
2281
- if (domain) cookieOptions.domain = domain;
2282
- document.cookie = serializeCookie(name, value, cookieOptions);
2283
- },
2284
- read(name) {
2285
- const nameEQ = `${name}=`;
2286
- const ca = document.cookie.split(';');
2287
- for (let i = 0; i < ca.length; i++) {
2288
- let c = ca[i];
2289
- while (c.charAt(0) === ' ') c = c.substring(1, c.length);
2290
- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
2291
- }
2292
- return null;
2293
- },
2294
- remove(name, domain) {
2295
- this.create(name, '', -1, domain);
2296
- }
2297
- };
2298
- var cookie$1 = {
2299
- name: 'cookie',
2300
- // Deconstruct the options object and extract the lookupCookie property
2301
- lookup(_ref) {
2302
- let {
2303
- lookupCookie
2304
- } = _ref;
2305
- if (lookupCookie && typeof document !== 'undefined') {
2306
- return cookie.read(lookupCookie) || undefined;
2307
- }
2308
- return undefined;
2309
- },
2310
- // Deconstruct the options object and extract the lookupCookie, cookieMinutes, cookieDomain, and cookieOptions properties
2311
- cacheUserLanguage(lng, _ref2) {
2312
- let {
2313
- lookupCookie,
2314
- cookieMinutes,
2315
- cookieDomain,
2316
- cookieOptions
2317
- } = _ref2;
2318
- if (lookupCookie && typeof document !== 'undefined') {
2319
- cookie.create(lookupCookie, lng, cookieMinutes, cookieDomain, cookieOptions);
2320
- }
2321
- }
2322
- };
2323
-
2324
- var querystring = {
2325
- name: 'querystring',
2326
- // Deconstruct the options object and extract the lookupQuerystring property
2327
- lookup(_ref) {
2328
- let {
2329
- lookupQuerystring
2330
- } = _ref;
2331
- let found;
2332
- if (typeof window !== 'undefined') {
2333
- let {
2334
- search
2335
- } = window.location;
2336
- if (!window.location.search && window.location.hash?.indexOf('?') > -1) {
2337
- search = window.location.hash.substring(window.location.hash.indexOf('?'));
2338
- }
2339
- const query = search.substring(1);
2340
- const params = query.split('&');
2341
- for (let i = 0; i < params.length; i++) {
2342
- const pos = params[i].indexOf('=');
2343
- if (pos > 0) {
2344
- const key = params[i].substring(0, pos);
2345
- if (key === lookupQuerystring) {
2346
- found = params[i].substring(pos + 1);
2347
- }
2348
- }
2349
- }
2350
- }
2351
- return found;
2352
- }
2353
- };
2354
-
2355
- var hash = {
2356
- name: 'hash',
2357
- // Deconstruct the options object and extract the lookupHash property and the lookupFromHashIndex property
2358
- lookup(_ref) {
2359
- let {
2360
- lookupHash,
2361
- lookupFromHashIndex
2362
- } = _ref;
2363
- let found;
2364
- if (typeof window !== 'undefined') {
2365
- const {
2366
- hash
2367
- } = window.location;
2368
- if (hash && hash.length > 2) {
2369
- const query = hash.substring(1);
2370
- if (lookupHash) {
2371
- const params = query.split('&');
2372
- for (let i = 0; i < params.length; i++) {
2373
- const pos = params[i].indexOf('=');
2374
- if (pos > 0) {
2375
- const key = params[i].substring(0, pos);
2376
- if (key === lookupHash) {
2377
- found = params[i].substring(pos + 1);
2378
- }
2379
- }
2380
- }
2381
- }
2382
- if (found) return found;
2383
- if (!found && lookupFromHashIndex > -1) {
2384
- const language = hash.match(/\/([a-zA-Z-]*)/g);
2385
- if (!Array.isArray(language)) return undefined;
2386
- const index = typeof lookupFromHashIndex === 'number' ? lookupFromHashIndex : 0;
2387
- return language[index]?.replace('/', '');
2388
- }
2389
- }
2390
- }
2391
- return found;
2392
- }
2393
- };
2394
-
2395
- let hasLocalStorageSupport = null;
2396
- const localStorageAvailable = () => {
2397
- if (hasLocalStorageSupport !== null) return hasLocalStorageSupport;
2398
- try {
2399
- hasLocalStorageSupport = typeof window !== 'undefined' && window.localStorage !== null;
2400
- if (!hasLocalStorageSupport) {
2401
- return false;
2402
- }
2403
- const testKey = 'i18next.translate.boo';
2404
- window.localStorage.setItem(testKey, 'foo');
2405
- window.localStorage.removeItem(testKey);
2406
- } catch (e) {
2407
- hasLocalStorageSupport = false;
2408
- }
2409
- return hasLocalStorageSupport;
2410
- };
2411
- var localStorage = {
2412
- name: 'localStorage',
2413
- // Deconstruct the options object and extract the lookupLocalStorage property
2414
- lookup(_ref) {
2415
- let {
2416
- lookupLocalStorage
2417
- } = _ref;
2418
- if (lookupLocalStorage && localStorageAvailable()) {
2419
- return window.localStorage.getItem(lookupLocalStorage) || undefined; // Undefined ensures type consistency with the previous version of this function
2420
- }
2421
- return undefined;
2422
- },
2423
- // Deconstruct the options object and extract the lookupLocalStorage property
2424
- cacheUserLanguage(lng, _ref2) {
2425
- let {
2426
- lookupLocalStorage
2427
- } = _ref2;
2428
- if (lookupLocalStorage && localStorageAvailable()) {
2429
- window.localStorage.setItem(lookupLocalStorage, lng);
2430
- }
2431
- }
2432
- };
2433
-
2434
- let hasSessionStorageSupport = null;
2435
- const sessionStorageAvailable = () => {
2436
- if (hasSessionStorageSupport !== null) return hasSessionStorageSupport;
2437
- try {
2438
- hasSessionStorageSupport = typeof window !== 'undefined' && window.sessionStorage !== null;
2439
- if (!hasSessionStorageSupport) {
2440
- return false;
2441
- }
2442
- const testKey = 'i18next.translate.boo';
2443
- window.sessionStorage.setItem(testKey, 'foo');
2444
- window.sessionStorage.removeItem(testKey);
2445
- } catch (e) {
2446
- hasSessionStorageSupport = false;
2447
- }
2448
- return hasSessionStorageSupport;
2449
- };
2450
- var sessionStorage = {
2451
- name: 'sessionStorage',
2452
- lookup(_ref) {
2453
- let {
2454
- lookupSessionStorage
2455
- } = _ref;
2456
- if (lookupSessionStorage && sessionStorageAvailable()) {
2457
- return window.sessionStorage.getItem(lookupSessionStorage) || undefined;
2458
- }
2459
- return undefined;
2460
- },
2461
- cacheUserLanguage(lng, _ref2) {
2462
- let {
2463
- lookupSessionStorage
2464
- } = _ref2;
2465
- if (lookupSessionStorage && sessionStorageAvailable()) {
2466
- window.sessionStorage.setItem(lookupSessionStorage, lng);
2467
- }
2468
- }
2469
- };
2470
-
2471
- var navigator$1 = {
2472
- name: 'navigator',
2473
- lookup(options) {
2474
- const found = [];
2475
- if (typeof navigator !== 'undefined') {
2476
- const {
2477
- languages,
2478
- userLanguage,
2479
- language
2480
- } = navigator;
2481
- if (languages) {
2482
- // chrome only; not an array, so can't use .push.apply instead of iterating
2483
- for (let i = 0; i < languages.length; i++) {
2484
- found.push(languages[i]);
2485
- }
2486
- }
2487
- if (userLanguage) {
2488
- found.push(userLanguage);
2489
- }
2490
- if (language) {
2491
- found.push(language);
2492
- }
2493
- }
2494
- return found.length > 0 ? found : undefined;
2495
- }
2496
- };
2497
-
2498
- var htmlTag = {
2499
- name: 'htmlTag',
2500
- // Deconstruct the options object and extract the htmlTag property
2501
- lookup(_ref) {
2502
- let {
2503
- htmlTag
2504
- } = _ref;
2505
- let found;
2506
- const internalHtmlTag = htmlTag || (typeof document !== 'undefined' ? document.documentElement : null);
2507
- if (internalHtmlTag && typeof internalHtmlTag.getAttribute === 'function') {
2508
- found = internalHtmlTag.getAttribute('lang');
2509
- }
2510
- return found;
2511
- }
2512
- };
2513
-
2514
- var path = {
2515
- name: 'path',
2516
- // Deconstruct the options object and extract the lookupFromPathIndex property
2517
- lookup(_ref) {
2518
- let {
2519
- lookupFromPathIndex
2520
- } = _ref;
2521
- if (typeof window === 'undefined') return undefined;
2522
- const language = window.location.pathname.match(/\/([a-zA-Z-]*)/g);
2523
- if (!Array.isArray(language)) return undefined;
2524
- const index = typeof lookupFromPathIndex === 'number' ? lookupFromPathIndex : 0;
2525
- return language[index]?.replace('/', '');
2526
- }
2527
- };
2528
-
2529
- var subdomain = {
2530
- name: 'subdomain',
2531
- lookup(_ref) {
2532
- let {
2533
- lookupFromSubdomainIndex
2534
- } = _ref;
2535
- // If given get the subdomain index else 1
2536
- const internalLookupFromSubdomainIndex = typeof lookupFromSubdomainIndex === 'number' ? lookupFromSubdomainIndex + 1 : 1;
2537
- // get all matches if window.location. is existing
2538
- // first item of match is the match itself and the second is the first group match which should be the first subdomain match
2539
- // is the hostname no public domain get the or option of localhost
2540
- const language = typeof window !== 'undefined' && window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);
2541
-
2542
- // if there is no match (null) return undefined
2543
- if (!language) return undefined;
2544
- // return the given group match
2545
- return language[internalLookupFromSubdomainIndex];
2546
- }
2547
- };
2548
-
2549
- // some environments, throws when accessing document.cookie
2550
- let canCookies = false;
2551
- try {
2552
- canCookies = true;
2553
- // eslint-disable-next-line no-empty
2554
- } catch (e) {}
2555
- const order = ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'];
2556
- if (!canCookies) order.splice(1, 1);
2557
- const getDefaults = () => ({
2558
- order,
2559
- lookupQuerystring: 'lng',
2560
- lookupCookie: 'i18next',
2561
- lookupLocalStorage: 'i18nextLng',
2562
- lookupSessionStorage: 'i18nextLng',
2563
- // cache user language
2564
- caches: ['localStorage'],
2565
- excludeCacheFor: ['cimode'],
2566
- // cookieMinutes: 10,
2567
- // cookieDomain: 'myDomain'
2568
-
2569
- convertDetectedLanguage: l => l
2570
- });
2571
- class Browser {
2572
- constructor(services) {
2573
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2574
- this.type = 'languageDetector';
2575
- this.detectors = {};
2576
- this.init(services, options);
2577
- }
2578
- init() {
2579
- let services = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
2580
- languageUtils: {}
2581
- };
2582
- let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2583
- let i18nOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2584
- this.services = services;
2585
- this.options = defaults(options, this.options || {}, getDefaults());
2586
- if (typeof this.options.convertDetectedLanguage === 'string' && this.options.convertDetectedLanguage.indexOf('15897') > -1) {
2587
- this.options.convertDetectedLanguage = l => l.replace('-', '_');
2588
- }
2589
-
2590
- // backwards compatibility
2591
- if (this.options.lookupFromUrlIndex) this.options.lookupFromPathIndex = this.options.lookupFromUrlIndex;
2592
- this.i18nOptions = i18nOptions;
2593
- this.addDetector(cookie$1);
2594
- this.addDetector(querystring);
2595
- this.addDetector(localStorage);
2596
- this.addDetector(sessionStorage);
2597
- this.addDetector(navigator$1);
2598
- this.addDetector(htmlTag);
2599
- this.addDetector(path);
2600
- this.addDetector(subdomain);
2601
- this.addDetector(hash);
2602
- }
2603
- addDetector(detector) {
2604
- this.detectors[detector.name] = detector;
2605
- return this;
2606
- }
2607
- detect() {
2608
- let detectionOrder = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.options.order;
2609
- let detected = [];
2610
- detectionOrder.forEach(detectorName => {
2611
- if (this.detectors[detectorName]) {
2612
- let lookup = this.detectors[detectorName].lookup(this.options);
2613
- if (lookup && typeof lookup === 'string') lookup = [lookup];
2614
- if (lookup) detected = detected.concat(lookup);
2615
- }
2616
- });
2617
- detected = detected.filter(d => d !== undefined && d !== null && !hasXSS(d)).map(d => this.options.convertDetectedLanguage(d));
2618
- if (this.services && this.services.languageUtils && this.services.languageUtils.getBestMatchFromCodes) return detected; // new i18next v19.5.0
2619
- return detected.length > 0 ? detected[0] : null; // a little backward compatibility
2620
- }
2621
- cacheUserLanguage(lng) {
2622
- let caches = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.options.caches;
2623
- if (!caches) return;
2624
- if (this.options.excludeCacheFor && this.options.excludeCacheFor.indexOf(lng) > -1) return;
2625
- caches.forEach(cacheName => {
2626
- if (this.detectors[cacheName]) this.detectors[cacheName].cacheUserLanguage(lng, this.options);
2627
- });
2628
- }
2629
- }
2630
- Browser.type = 'languageDetector';
2631
-
2632
- instance.use(Browser).init({
2633
- fallbackLng: 'en',
2634
- debug: false,
2635
- resources: {
2636
- 'en': {
2637
- translation: {},
2638
- },
2639
- 'ja': {
2640
- translation: {
2641
- 'Pay': '支払う',
2642
- 'Failed to load Stripe': 'ライブラリの読み込みに失敗しました。',
2643
- 'Add your payment information': '支払情報を追加',
2644
- 'Add card': 'カードを追加',
2645
- 'Add a card': 'カードを追加',
2646
- 'Add': '追加',
2647
- 'Card information': 'カード情報',
2648
- 'Card Number': 'カード番号',
2649
- 'MM / YY': '月 / 年',
2650
- 'CVC': 'セキュリティコード(CVC)',
2651
- 'Country or region': '地域',
2652
- 'Postal Code': '郵便番号',
2653
- },
2654
- },
2655
- 'pt-BR': {
2656
- translation: {
2657
- 'Pay': 'Pagar',
2658
- 'Failed to load Stripe': 'Falha ao ler Stripe',
2659
- 'Add your payment information': 'Informações do seu Pagamento',
2660
- 'Add card': 'Adicionar Cartão',
2661
- 'Add a card': 'Adicionar um Cartão',
2662
- 'Add': 'Adicionar',
2663
- 'Card information': 'Informações do Cartão',
2664
- 'Card Number': 'Número do Cartão',
2665
- 'MM / YY': 'MM / AA',
2666
- 'CVC': 'Número de Segurança(CVC)',
2667
- 'Country or region': 'País ou região',
2668
- 'Postal Code': 'Cep',
2669
- },
2670
- },
2671
- },
2672
- });
2673
- const i18n = instance;
2674
-
2675
- const appendToMap = (map, propName, value) => {
2676
- const items = map.get(propName);
2677
- if (!items) {
2678
- map.set(propName, [value]);
2679
- }
2680
- else if (!items.includes(value)) {
2681
- items.push(value);
2682
- }
2683
- };
2684
- const debounce = (fn, ms) => {
2685
- let timeoutId;
2686
- return (...args) => {
2687
- if (timeoutId) {
2688
- clearTimeout(timeoutId);
2689
- }
2690
- timeoutId = setTimeout(() => {
2691
- timeoutId = 0;
2692
- fn(...args);
2693
- }, ms);
2694
- };
2695
- };
2696
-
2697
- /**
2698
- * Check if a possible element isConnected.
2699
- * The property might not be there, so we check for it.
2700
- *
2701
- * We want it to return true if isConnected is not a property,
2702
- * otherwise we would remove these elements and would not update.
2703
- *
2704
- * Better leak in Edge than to be useless.
2705
- */
2706
- const isConnected = (maybeElement) => !('isConnected' in maybeElement) || maybeElement.isConnected;
2707
- const cleanupElements = debounce((map) => {
2708
- for (let key of map.keys()) {
2709
- map.set(key, map.get(key).filter(isConnected));
2710
- }
2711
- }, 2_000);
2712
- const stencilSubscription = () => {
2713
- if (typeof getRenderingRef !== 'function') {
2714
- // If we are not in a stencil project, we do nothing.
2715
- // This function is not really exported by @stencil/core.
2716
- return {};
2717
- }
2718
- const elmsToUpdate = new Map();
2719
- return {
2720
- dispose: () => elmsToUpdate.clear(),
2721
- get: (propName) => {
2722
- const elm = getRenderingRef();
2723
- if (elm) {
2724
- appendToMap(elmsToUpdate, propName, elm);
2725
- }
2726
- },
2727
- set: (propName) => {
2728
- const elements = elmsToUpdate.get(propName);
2729
- if (elements) {
2730
- elmsToUpdate.set(propName, elements.filter(forceUpdate));
2731
- }
2732
- cleanupElements(elmsToUpdate);
2733
- },
2734
- reset: () => {
2735
- elmsToUpdate.forEach((elms) => elms.forEach(forceUpdate));
2736
- cleanupElements(elmsToUpdate);
2737
- },
2738
- };
2739
- };
2740
-
2741
- const unwrap = (val) => (typeof val === 'function' ? val() : val);
2742
- const createObservableMap = (defaultState, shouldUpdate = (a, b) => a !== b) => {
2743
- const unwrappedState = unwrap(defaultState);
2744
- let states = new Map(Object.entries(unwrappedState ?? {}));
2745
- const handlers = {
2746
- dispose: [],
2747
- get: [],
2748
- set: [],
2749
- reset: [],
2750
- };
2751
- // Track onChange listeners to enable removeListener functionality
2752
- const changeListeners = new Map();
2753
- const reset = () => {
2754
- // When resetting the state, the default state may be a function - unwrap it to invoke it.
2755
- // otherwise, the state won't be properly reset
2756
- states = new Map(Object.entries(unwrap(defaultState) ?? {}));
2757
- handlers.reset.forEach((cb) => cb());
2758
- };
2759
- const dispose = () => {
2760
- // Call first dispose as resetting the state would
2761
- // cause less updates ;)
2762
- handlers.dispose.forEach((cb) => cb());
2763
- reset();
2764
- };
2765
- const get = (propName) => {
2766
- handlers.get.forEach((cb) => cb(propName));
2767
- return states.get(propName);
2768
- };
2769
- const set = (propName, value) => {
2770
- const oldValue = states.get(propName);
2771
- if (shouldUpdate(value, oldValue, propName)) {
2772
- states.set(propName, value);
2773
- handlers.set.forEach((cb) => cb(propName, value, oldValue));
2774
- }
2775
- };
2776
- const state = (typeof Proxy === 'undefined'
2777
- ? {}
2778
- : new Proxy(unwrappedState, {
2779
- get(_, propName) {
2780
- return get(propName);
2781
- },
2782
- ownKeys(_) {
2783
- return Array.from(states.keys());
2784
- },
2785
- getOwnPropertyDescriptor() {
2786
- return {
2787
- enumerable: true,
2788
- configurable: true,
2789
- };
2790
- },
2791
- has(_, propName) {
2792
- return states.has(propName);
2793
- },
2794
- set(_, propName, value) {
2795
- set(propName, value);
2796
- return true;
2797
- },
2798
- }));
2799
- const on = (eventName, callback) => {
2800
- handlers[eventName].push(callback);
2801
- return () => {
2802
- removeFromArray(handlers[eventName], callback);
2803
- };
2804
- };
2805
- const onChange = (propName, cb) => {
2806
- const setHandler = (key, newValue) => {
2807
- if (key === propName) {
2808
- cb(newValue);
2809
- }
2810
- };
2811
- const resetHandler = () => cb(unwrap(defaultState)[propName]);
2812
- // Register the handlers
2813
- const unSet = on('set', setHandler);
2814
- const unReset = on('reset', resetHandler);
2815
- // Track the relationship between the user callback and internal handlers
2816
- changeListeners.set(cb, { setHandler, resetHandler, propName });
2817
- return () => {
2818
- unSet();
2819
- unReset();
2820
- changeListeners.delete(cb);
2821
- };
2822
- };
2823
- const use = (...subscriptions) => {
2824
- const unsubs = subscriptions.reduce((unsubs, subscription) => {
2825
- if (subscription.set) {
2826
- unsubs.push(on('set', subscription.set));
2827
- }
2828
- if (subscription.get) {
2829
- unsubs.push(on('get', subscription.get));
2830
- }
2831
- if (subscription.reset) {
2832
- unsubs.push(on('reset', subscription.reset));
2833
- }
2834
- if (subscription.dispose) {
2835
- unsubs.push(on('dispose', subscription.dispose));
2836
- }
2837
- return unsubs;
2838
- }, []);
2839
- return () => unsubs.forEach((unsub) => unsub());
2840
- };
2841
- const forceUpdate = (key) => {
2842
- const oldValue = states.get(key);
2843
- handlers.set.forEach((cb) => cb(key, oldValue, oldValue));
2844
- };
2845
- const removeListener = (propName, listener) => {
2846
- const listenerInfo = changeListeners.get(listener);
2847
- if (listenerInfo && listenerInfo.propName === propName) {
2848
- // Remove the specific handlers that were created for this listener
2849
- removeFromArray(handlers.set, listenerInfo.setHandler);
2850
- removeFromArray(handlers.reset, listenerInfo.resetHandler);
2851
- changeListeners.delete(listener);
2852
- }
2853
- };
2854
- return {
2855
- state,
2856
- get,
2857
- set,
2858
- on,
2859
- onChange,
2860
- use,
2861
- dispose,
2862
- reset,
2863
- forceUpdate,
2864
- removeListener,
2865
- };
2866
- };
2867
- const removeFromArray = (array, item) => {
2868
- const index = array.indexOf(item);
2869
- if (index >= 0) {
2870
- array[index] = array[array.length - 1];
2871
- array.length--;
2872
- }
2873
- };
2874
-
2875
- const createStore = (defaultState, shouldUpdate) => {
2876
- const map = createObservableMap(defaultState, shouldUpdate);
2877
- map.use(stencilSubscription());
2878
- return map;
2879
- };
2880
-
2881
- /**
2882
- * Core Stripe Service
2883
- * Manages Stripe.js initialization and Elements instance only
2884
- * Does NOT manage specific element types (Card, Payment, etc.)
2885
- */
2886
- class StripeServiceClass {
2887
- constructor() {
2888
- this.store = createStore({
2889
- loadStripeStatus: '',
2890
- applicationName: 'stripe-pwa-elements',
2891
- isCheckoutSession: false,
2892
- });
2893
- this.changeListeners = new Map();
2894
- }
2895
- /**
2896
- * Get the reactive state object
2897
- * Components can use this directly in render() for automatic reactivity
2898
- */
2899
- get state() {
2900
- return this.store.state;
2901
- }
2902
- /**
2903
- * Register a callback for when a specific state property changes
2904
- * @param key - The state property to watch
2905
- * @param callback - Function to call when the property changes
2906
- * @returns Unsubscribe function
2907
- */
2908
- onChange(key, callback) {
2909
- const dispose = this.store.onChange(key, callback);
2910
- // Track listeners for cleanup
2911
- if (!this.changeListeners.has(key)) {
2912
- this.changeListeners.set(key, []);
2913
- }
2914
- this.changeListeners.get(key).push(dispose);
2915
- return dispose;
2916
- }
2917
- /**
2918
- * Initialize Stripe.js client with Payment Intent mode
2919
- * @param publishableKey - Your Stripe publishable API key
2920
- * @param options - Optional configuration
2921
- */
2922
- async initialize(publishableKey, options) {
2923
- // Update configuration
2924
- this.store.state.publishableKey = publishableKey;
2925
- this.store.state.isCheckoutSession = false;
2926
- if (options === null || options === void 0 ? void 0 : options.stripeAccount) {
2927
- this.store.state.stripeAccount = options.stripeAccount;
2928
- }
2929
- if (options === null || options === void 0 ? void 0 : options.applicationName) {
2930
- this.store.state.applicationName = options.applicationName;
2931
- }
2932
- // If Stripe.js already loaded with same config, do nothing
2933
- if (this.store.state.stripe && this.store.state.publishableKey === publishableKey && this.store.state.stripeAccount === (options === null || options === void 0 ? void 0 : options.stripeAccount) && !this.store.state.isCheckoutSession) {
2934
- return;
2935
- }
2936
- this.store.state.loadStripeStatus = 'loading';
2937
- try {
2938
- const stripe = await loadStripe(publishableKey, {
2939
- stripeAccount: options === null || options === void 0 ? void 0 : options.stripeAccount,
2940
- });
2941
- // Register app info
2942
- stripe.registerAppInfo({
2943
- name: this.store.state.applicationName,
2944
- });
2945
- this.store.state.stripe = stripe;
2946
- this.store.state.elements = stripe.elements();
2947
- this.store.state.checkout = undefined;
2948
- this.store.state.loadStripeStatus = 'success';
2949
- }
2950
- catch (e) {
2951
- console.error('Failed to load Stripe.js:', e);
2952
- this.store.state.loadStripeStatus = 'failure';
2953
- }
2954
- }
2955
- /**
2956
- * Initialize Stripe.js client with Checkout Session mode
2957
- * @param publishableKey - Your Stripe publishable API key
2958
- * @param checkoutSessionClientSecret - The client secret from Checkout Session
2959
- * @param options - Optional configuration
2960
- */
2961
- async initializeWithCheckoutSession(publishableKey, checkoutSessionClientSecret, options) {
2962
- // Update configuration
2963
- this.store.state.publishableKey = publishableKey;
2964
- this.store.state.isCheckoutSession = true;
2965
- if (options === null || options === void 0 ? void 0 : options.stripeAccount) {
2966
- this.store.state.stripeAccount = options.stripeAccount;
2967
- }
2968
- if (options === null || options === void 0 ? void 0 : options.applicationName) {
2969
- this.store.state.applicationName = options.applicationName;
2970
- }
2971
- this.store.state.loadStripeStatus = 'loading';
2972
- try {
2973
- const stripe = await loadStripe(publishableKey, {
2974
- stripeAccount: options === null || options === void 0 ? void 0 : options.stripeAccount,
2975
- });
2976
- // Register app info
2977
- stripe.registerAppInfo({
2978
- name: this.store.state.applicationName,
2979
- });
2980
- this.store.state.stripe = stripe;
2981
- // Initialize Checkout instance instead of Elements
2982
- const checkout = stripe.initCheckout({
2983
- clientSecret: checkoutSessionClientSecret,
2984
- elementsOptions: options === null || options === void 0 ? void 0 : options.elementsOptions,
2985
- });
2986
- this.store.state.checkout = checkout;
2987
- this.store.state.elements = undefined;
2988
- this.store.state.loadStripeStatus = 'success';
2989
- }
2990
- catch (e) {
2991
- console.error('Failed to initialize Stripe Checkout:', e);
2992
- this.store.state.loadStripeStatus = 'failure';
2993
- }
2994
- }
2995
- /**
2996
- * Get the current Stripe instance
2997
- */
2998
- getStripe() {
2999
- return this.store.state.stripe;
3000
- }
3001
- /**
3002
- * Get the current Elements instance
3003
- */
3004
- getElements() {
3005
- return this.store.state.elements;
3006
- }
3007
- /**
3008
- * Get the current Checkout instance (for Checkout Session mode)
3009
- */
3010
- getCheckout() {
3011
- return this.store.state.checkout;
3012
- }
3013
- /**
3014
- * Reset the service to initial state
3015
- * Useful for testing and cleanup
3016
- */
3017
- reset() {
3018
- this.store.reset();
3019
- }
3020
- /**
3021
- * Dispose of all listeners and reset state
3022
- * Should be called in test cleanup
3023
- */
3024
- dispose() {
3025
- // Dispose all onChange listeners
3026
- this.changeListeners.forEach(listeners => {
3027
- listeners.forEach(dispose => dispose());
3028
- });
3029
- this.changeListeners.clear();
3030
- // Dispose the store
3031
- this.store.dispose();
3032
- }
3033
- }
3034
- /**
3035
- * Singleton instance of StripeService (for backward compatibility)
3036
- * New code should use ServiceFactory for better testability
3037
- *
3038
- * @deprecated Use ServiceFactory.createStripeService() for better DI support
3039
- */
3040
- new StripeServiceClass();
3041
-
3042
- /**
3043
- * Wait for an element to appear in the DOM
3044
- * @param containerElement - Parent element to search in
3045
- * @param selector - CSS selector
3046
- * @param timeout - Timeout in milliseconds (default: 5000ms)
3047
- * @returns Promise that resolves to the found element or rejects on timeout
3048
- */
3049
- function findElement(containerElement, selector, timeout = 5000) {
3050
- return new Promise((resolve, reject) => {
3051
- const elem = containerElement.querySelector(selector);
3052
- if (elem) {
3053
- return resolve(elem);
3054
- }
3055
- const timeoutId = setTimeout(() => {
3056
- observer.disconnect();
3057
- reject(new Error(`Element "${selector}" not found within ${timeout}ms`));
3058
- }, timeout);
3059
- const observer = new MutationObserver(() => {
3060
- const elem = containerElement.querySelector(selector);
3061
- if (elem) {
3062
- clearTimeout(timeoutId);
3063
- observer.disconnect();
3064
- resolve(elem);
3065
- }
3066
- });
3067
- observer.observe(containerElement, {
3068
- childList: true,
3069
- subtree: true,
3070
- });
3071
- });
3072
- }
3073
-
3074
- /**
3075
- * Card Element Manager
3076
- * Manages Stripe Card Elements (cardNumber, cardExpiry, cardCvc)
3077
- * with dependency injection of StripeService
3078
- */
3079
- class CardElementManager {
3080
- /**
3081
- * Constructor with dependency injection
3082
- * @param stripeService - Injected Stripe service instance
3083
- */
3084
- constructor(stripeService) {
3085
- this.stripeService = stripeService;
3086
- this.store = createStore({
3087
- errorMessage: '',
3088
- errorSource: undefined,
3089
- });
3090
- }
3091
- /**
3092
- * Get current card element state (reactive)
3093
- */
3094
- getState() {
3095
- return this.store.state;
3096
- }
3097
- /**
3098
- * Initialize and mount card elements to DOM
3099
- * @param containerElement - Parent element containing mount points
3100
- * @returns Promise resolving to card element instances
3101
- */
3102
- async initialize(containerElement) {
3103
- const elements = this.stripeService.getElements();
3104
- if (!elements) {
3105
- throw new Error('StripeService not initialized. Call StripeService.initialize() first.');
3106
- }
3107
- // Unmount if already initialized
3108
- if (this.cardElements) {
3109
- this.unmount();
3110
- }
3111
- // Create and mount card number element
3112
- const cardNumber = elements.create('cardNumber', {
3113
- placeholder: i18n.t('Card Number'),
3114
- });
3115
- const cardNumberElement = await findElement(containerElement, '#card-number');
3116
- cardNumber.mount(cardNumberElement);
3117
- cardNumber.on('change', this.handleCardError('cardNumber'));
3118
- // Create and mount card expiry element
3119
- const cardExpiry = elements.create('cardExpiry');
3120
- const cardExpiryElement = await findElement(containerElement, '#card-expiry');
3121
- cardExpiry.mount(cardExpiryElement);
3122
- cardExpiry.on('change', this.handleCardError('cardExpiry'));
3123
- // Create and mount card CVC element
3124
- const cardCVC = elements.create('cardCvc');
3125
- const cardCVCElement = await findElement(containerElement, '#card-cvc');
3126
- cardCVC.mount(cardCVCElement);
3127
- cardCVC.on('change', this.handleCardError('cardCvc'));
3128
- this.cardElements = {
3129
- cardNumber,
3130
- cardExpiry,
3131
- cardCVC,
3132
- };
3133
- return this.cardElements;
3134
- }
3135
- /**
3136
- * Get mounted card element instances
3137
- */
3138
- getElements() {
3139
- return this.cardElements;
3140
- }
3141
- /**
3142
- * Set error message (triggers reactivity)
3143
- */
3144
- setError(message) {
3145
- this.store.set('errorMessage', message);
3146
- }
3147
- /**
3148
- * Clear error message (triggers reactivity)
3149
- */
3150
- clearError() {
3151
- this.store.set('errorMessage', '');
3152
- this.store.set('errorSource', undefined);
3153
- }
3154
- /**
3155
- * Unmount all card elements
3156
- */
3157
- unmount() {
3158
- var _a, _b, _c;
3159
- if (!this.cardElements) {
3160
- return;
3161
- }
3162
- (_a = this.cardElements.cardNumber) === null || _a === void 0 ? void 0 : _a.unmount();
3163
- (_b = this.cardElements.cardExpiry) === null || _b === void 0 ? void 0 : _b.unmount();
3164
- (_c = this.cardElements.cardCVC) === null || _c === void 0 ? void 0 : _c.unmount();
3165
- this.cardElements = undefined;
3166
- }
3167
- /**
3168
- * Handle card element errors
3169
- * Only clears error if it's from the same element type
3170
- * Uses store.set() to trigger reactivity
3171
- */
3172
- handleCardError(elementType) {
3173
- return ({ error }) => {
3174
- if (error) {
3175
- this.store.set('errorMessage', error.message);
3176
- this.store.set('errorSource', elementType);
3177
- return;
3178
- }
3179
- // Only clear error if it originated from the same element
3180
- if (this.store.state.errorSource === elementType) {
3181
- this.store.set('errorMessage', '');
3182
- this.store.set('errorSource', undefined);
3183
- }
3184
- };
3185
- }
3186
- }
3187
-
3188
- /**
3189
- * Payment Element Manager
3190
- * Manages Stripe Payment Element (unified payment form)
3191
- * with dependency injection of StripeService
3192
- * Supports both Payment Intent mode and Checkout Session mode
3193
- */
3194
- class PaymentElementManager {
3195
- /**
3196
- * Constructor with dependency injection
3197
- * @param stripeService - Injected Stripe service instance
3198
- */
3199
- constructor(stripeService) {
3200
- this.stripeService = stripeService;
3201
- this.store = createStore({
3202
- errorMessage: '',
3203
- });
3204
- }
3205
- /**
3206
- * Get current payment element state (reactive)
3207
- */
3208
- getState() {
3209
- return this.store.state;
3210
- }
3211
- /**
3212
- * Initialize and mount payment element to DOM
3213
- * Supports both Payment Intent mode and Checkout Session mode
3214
- * @param containerElement - Parent element containing mount point
3215
- * @param options - Optional payment element options
3216
- * @returns Promise resolving to payment element instance
3217
- */
3218
- async initialize(containerElement, options) {
3219
- const isCheckoutSession = this.stripeService.state.isCheckoutSession;
3220
- // Unmount if already initialized
3221
- if (this.paymentElement) {
3222
- this.unmount();
3223
- }
3224
- if (isCheckoutSession) {
3225
- // Checkout Session mode: use checkout.createPaymentElement()
3226
- const checkout = this.stripeService.getCheckout();
3227
- if (!checkout) {
3228
- throw new Error('StripeService not initialized with Checkout Session. Call StripeService.initializeWithCheckoutSession() first.');
3229
- }
3230
- // Create payment element using Checkout instance
3231
- this.paymentElement = checkout.createPaymentElement(options);
3232
- }
3233
- else {
3234
- // Payment Intent mode: use elements.create('payment')
3235
- const elements = this.stripeService.getElements();
3236
- if (!elements) {
3237
- throw new Error('StripeService not initialized. Call StripeService.initialize() first.');
3238
- }
3239
- // Create payment element with options
3240
- const elementOptions = options || {};
3241
- // Create the payment element
3242
- this.paymentElement = elements.create('payment', elementOptions);
3243
- }
3244
- // Find mount point and mount
3245
- const paymentElementContainer = await findElement(containerElement, '#payment-element');
3246
- this.paymentElement.mount(paymentElementContainer);
3247
- // Note: Payment Element errors are handled during submission
3248
- // Use setError() method to manually set errors if needed
3249
- return this.paymentElement;
3250
- }
3251
- /**
3252
- * Get mounted payment element instance
3253
- */
3254
- getElement() {
3255
- return this.paymentElement;
3256
- }
3257
- /**
3258
- * Set error message (triggers reactivity)
3259
- */
3260
- setError(message) {
3261
- this.store.set('errorMessage', message);
3262
- }
3263
- /**
3264
- * Clear error message (triggers reactivity)
3265
- */
3266
- clearError() {
3267
- this.store.set('errorMessage', '');
3268
- }
3269
- /**
3270
- * Unmount payment element
3271
- */
3272
- unmount() {
3273
- if (!this.paymentElement) {
3274
- return;
3275
- }
3276
- this.paymentElement.unmount();
3277
- this.paymentElement = undefined;
3278
- }
3279
- }
3280
-
3281
- /**
3282
- * Address Element Manager
3283
- * Manages Stripe Address Element
3284
- * with dependency injection of StripeService
3285
- */
3286
- class AddressElementManager {
3287
- /**
3288
- * Constructor with dependency injection
3289
- * @param stripeService - Injected Stripe service instance
3290
- */
3291
- constructor(stripeService) {
3292
- this.stripeService = stripeService;
3293
- this.store = createStore({
3294
- errorMessage: '',
3295
- isComplete: false,
3296
- });
3297
- }
3298
- /**
3299
- * Get current address element state (reactive)
3300
- */
3301
- getState() {
3302
- return this.store.state;
3303
- }
3304
- /**
3305
- * Initialize and mount address element to DOM
3306
- * @param containerElement - Parent element containing mount point
3307
- * @param options - Address element options
3308
- * @returns Promise resolving to address element instance
3309
- */
3310
- async initialize(containerElement, options) {
3311
- const elements = this.stripeService.getElements();
3312
- if (!elements) {
3313
- throw new Error('StripeService not initialized. Call StripeService.initialize() first.');
3314
- }
3315
- // Unmount if already initialized
3316
- if (this.addressElement) {
3317
- this.unmount();
3318
- }
3319
- // Create and mount address element
3320
- this.addressElement = elements.create('address', options || { mode: 'billing' });
3321
- const addressElementContainer = await findElement(containerElement, '#address-element');
3322
- this.addressElement.mount(addressElementContainer);
3323
- // Listen for changes
3324
- this.addressElement.on('change', event => {
3325
- // StripeAddressElementChangeEvent doesn't have an error property
3326
- // Errors are handled through the complete property and validation
3327
- this.store.set('errorMessage', '');
3328
- this.store.set('isComplete', event.complete);
3329
- });
3330
- return this.addressElement;
3331
- }
3332
- /**
3333
- * Get mounted address element instance
3334
- */
3335
- getElement() {
3336
- return this.addressElement;
3337
- }
3338
- /**
3339
- * Set error message (triggers reactivity)
3340
- */
3341
- setError(message) {
3342
- this.store.set('errorMessage', message);
3343
- }
3344
- /**
3345
- * Clear error message (triggers reactivity)
3346
- */
3347
- clearError() {
3348
- this.store.set('errorMessage', '');
3349
- }
3350
- /**
3351
- * Unmount address element
3352
- */
3353
- unmount() {
3354
- if (!this.addressElement) {
3355
- return;
3356
- }
3357
- this.addressElement.unmount();
3358
- this.addressElement = undefined;
3359
- }
3360
- }
3361
-
3362
- /**
3363
- * Link Authentication Element Manager
3364
- * Manages Stripe Link Authentication Element for email collection and Link authentication
3365
- * with dependency injection of StripeService
3366
- */
3367
- class LinkAuthenticationElementManager {
3368
- /**
3369
- * Constructor with dependency injection
3370
- * @param stripeService - Injected Stripe service instance
3371
- */
3372
- constructor(stripeService) {
3373
- this.stripeService = stripeService;
3374
- this.store = createStore({
3375
- errorMessage: '',
3376
- email: undefined,
3377
- });
3378
- }
3379
- /**
3380
- * Get current link authentication element state (reactive)
3381
- */
3382
- getState() {
3383
- return this.store.state;
3384
- }
3385
- /**
3386
- * Register state change listener
3387
- * @param key - State property to watch
3388
- * @param callback - Callback function invoked when property changes
3389
- * @returns Unsubscribe function
3390
- */
3391
- onChange(key, callback) {
3392
- return this.store.onChange(key, callback);
3393
- }
3394
- /**
3395
- * Initialize and mount link authentication element to DOM
3396
- * @param containerElement - Parent element containing mount point
3397
- * @param options - Optional configuration for Link Authentication Element
3398
- * @returns Promise resolving to link authentication element instance
3399
- */
3400
- async initialize(containerElement, options) {
3401
- const elements = this.stripeService.getElements();
3402
- if (!elements) {
3403
- throw new Error('StripeService not initialized. Call StripeService.initialize() first.');
3404
- }
3405
- // Unmount if already initialized
3406
- if (this.linkAuthenticationElement) {
3407
- this.unmount();
3408
- }
3409
- // Create link authentication element
3410
- const linkAuthentication = elements.create('linkAuthentication', options);
3411
- const linkAuthenticationElementDiv = await findElement(containerElement, '#link-authentication-element');
3412
- linkAuthentication.mount(linkAuthenticationElementDiv);
3413
- // Listen for change events
3414
- linkAuthentication.on('change', event => {
3415
- var _a;
3416
- // Unconditionally set email from event.value.email
3417
- // This handles all cases: valid email, empty string, or undefined
3418
- this.store.set('email', (_a = event.value) === null || _a === void 0 ? void 0 : _a.email);
3419
- });
3420
- this.linkAuthenticationElement = linkAuthentication;
3421
- return this.linkAuthenticationElement;
3422
- }
3423
- /**
3424
- * Get mounted link authentication element instance
3425
- */
3426
- getElement() {
3427
- return this.linkAuthenticationElement;
3428
- }
3429
- /**
3430
- * Set error message (triggers reactivity)
3431
- */
3432
- setError(message) {
3433
- this.store.set('errorMessage', message);
3434
- }
3435
- /**
3436
- * Clear error message (triggers reactivity)
3437
- */
3438
- clearError() {
3439
- this.store.set('errorMessage', '');
3440
- }
3441
- /**
3442
- * Unmount link authentication element
3443
- */
3444
- unmount() {
3445
- if (!this.linkAuthenticationElement) {
3446
- return;
3447
- }
3448
- this.linkAuthenticationElement.unmount();
3449
- this.linkAuthenticationElement = undefined;
3450
- }
3451
- }
3452
-
3453
- /**
3454
- * Currency Selector Element Manager
3455
- * Manages Stripe Currency Selector Element
3456
- * with dependency injection of StripeService
3457
- */
3458
- class CurrencySelectorElementManager {
3459
- /**
3460
- * Constructor with dependency injection
3461
- * @param stripeService - Injected Stripe service instance
3462
- */
3463
- constructor(stripeService) {
3464
- this.stripeService = stripeService;
3465
- this.store = createStore({
3466
- errorMessage: '',
3467
- selectedCurrency: undefined,
3468
- });
3469
- }
3470
- /**
3471
- * Get current currency selector element state (reactive)
3472
- */
3473
- getState() {
3474
- return this.store.state;
3475
- }
3476
- /**
3477
- * Initialize and mount currency selector element to DOM
3478
- * @param containerElement - Parent element containing mount point
3479
- * @param options - Currency selector element options
3480
- * @returns Promise resolving to currency selector element instance
3481
- * Note: StripeCurrencySelectorElementOptions is not yet exported in @stripe/stripe-js v8.6.0
3482
- */
3483
- async initialize(containerElement, options) {
3484
- const elements = this.stripeService.getElements();
3485
- if (!elements) {
3486
- throw new Error('StripeService not initialized. Call StripeService.initialize() first.');
3487
- }
3488
- // Unmount if already initialized
3489
- if (this.currencySelectorElement) {
3490
- this.unmount();
3491
- }
3492
- // Find mount point first to avoid element leak if findElement throws
3493
- const currencySelectorElementContainer = await findElement(containerElement, '#currency-selector');
3494
- // Create and mount currency selector element
3495
- // Note: 'currencySelector' type is not yet in @stripe/stripe-js v8.6.0 type definitions
3496
- // but is documented in Stripe's Currency Selector Element documentation
3497
- this.currencySelectorElement = elements.create('currencySelector', options || {});
3498
- this.currencySelectorElement.mount(currencySelectorElementContainer);
3499
- // Listen for changes
3500
- // Note: The 'change' event type is not yet in @stripe/stripe-js type definitions
3501
- // but is documented in Stripe's Currency Selector Element documentation
3502
- this.currencySelectorElement.on('change', (event) => {
3503
- var _a;
3504
- // Clear error on change
3505
- this.store.set('errorMessage', '');
3506
- // Update selected currency if available
3507
- if ((_a = event === null || event === void 0 ? void 0 : event.value) === null || _a === void 0 ? void 0 : _a.currency) {
3508
- this.store.set('selectedCurrency', event.value.currency);
3509
- }
3510
- });
3511
- return this.currencySelectorElement;
3512
- }
3513
- /**
3514
- * Get mounted currency selector element instance
3515
- */
3516
- getElement() {
3517
- return this.currencySelectorElement;
3518
- }
3519
- /**
3520
- * Set error message (triggers reactivity)
3521
- */
3522
- setError(message) {
3523
- this.store.set('errorMessage', message);
3524
- }
3525
- /**
3526
- * Clear error message (triggers reactivity)
3527
- */
3528
- clearError() {
3529
- this.store.set('errorMessage', '');
3530
- }
3531
- /**
3532
- * Unmount currency selector element
3533
- */
3534
- unmount() {
3535
- if (!this.currencySelectorElement) {
3536
- return;
3537
- }
3538
- this.currencySelectorElement.unmount();
3539
- this.currencySelectorElement = undefined;
3540
- }
3541
- }
3542
-
3543
- /**
3544
- * Express Checkout Element Manager
3545
- * Manages Stripe Express Checkout Element
3546
- * with dependency injection of StripeService
3547
- */
3548
- class ExpressCheckoutElementManager {
3549
- /**
3550
- * Constructor with dependency injection
3551
- * @param stripeService - Injected Stripe service instance
3552
- */
3553
- constructor(stripeService) {
3554
- this.stripeService = stripeService;
3555
- this.store = createStore({
3556
- errorMessage: '',
3557
- isReady: false,
3558
- });
3559
- }
3560
- /**
3561
- * Get current express checkout element state (reactive)
3562
- */
3563
- getState() {
3564
- return this.store.state;
3565
- }
3566
- /**
3567
- * Initialize and mount express checkout element to DOM
3568
- * @param containerElement - Parent element containing mount point
3569
- * @param options - Express Checkout Element configuration options
3570
- * @param eventHandlers - Event handlers for element events
3571
- * @returns Promise resolving to express checkout element instance
3572
- */
3573
- async initialize(containerElement, options, eventHandlers) {
3574
- const elements = this.stripeService.getElements();
3575
- if (!elements) {
3576
- throw new Error('StripeService not initialized. Call StripeService.initialize() first.');
3577
- }
3578
- // Unmount if already initialized
3579
- if (this.expressCheckoutElement) {
3580
- this.unmount();
3581
- }
3582
- // Convert buttonHeight from string to number if present
3583
- const createOptions = Object.assign({}, options);
3584
- if (createOptions.buttonHeight && typeof createOptions.buttonHeight === 'string') {
3585
- const height = parseInt(createOptions.buttonHeight.replace('px', ''), 10);
3586
- if (!isNaN(height)) {
3587
- createOptions.buttonHeight = height;
3588
- }
3589
- }
3590
- // Create express checkout element
3591
- // Note: 'expressCheckout' is not yet in the official Stripe type definitions
3592
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3593
- const expressCheckout = elements.create('expressCheckout', createOptions);
3594
- // Find the mount point
3595
- const mountPoint = await findElement(containerElement, '#express-checkout-element');
3596
- // Set up event handlers before mounting
3597
- if (eventHandlers === null || eventHandlers === void 0 ? void 0 : eventHandlers.onConfirm) {
3598
- expressCheckout.on('confirm', eventHandlers.onConfirm);
3599
- }
3600
- if (eventHandlers === null || eventHandlers === void 0 ? void 0 : eventHandlers.onClick) {
3601
- expressCheckout.on('click', eventHandlers.onClick);
3602
- }
3603
- if (eventHandlers === null || eventHandlers === void 0 ? void 0 : eventHandlers.onCancel) {
3604
- expressCheckout.on('cancel', eventHandlers.onCancel);
3605
- }
3606
- if (eventHandlers === null || eventHandlers === void 0 ? void 0 : eventHandlers.onShippingAddressChange) {
3607
- expressCheckout.on('shippingaddresschange', eventHandlers.onShippingAddressChange);
3608
- }
3609
- if (eventHandlers === null || eventHandlers === void 0 ? void 0 : eventHandlers.onShippingRateChange) {
3610
- expressCheckout.on('shippingratechange', eventHandlers.onShippingRateChange);
3611
- }
3612
- // Add ready event handler
3613
- expressCheckout.on('ready', () => {
3614
- this.store.set('isReady', true);
3615
- });
3616
- // Mount the element
3617
- expressCheckout.mount(mountPoint);
3618
- this.expressCheckoutElement = expressCheckout;
3619
- return this.expressCheckoutElement;
3620
- }
3621
- /**
3622
- * Get mounted express checkout element instance
3623
- */
3624
- getElement() {
3625
- return this.expressCheckoutElement;
3626
- }
3627
- /**
3628
- * Update element options dynamically
3629
- * @param options - Partial options to update
3630
- */
3631
- update(options) {
3632
- if (!this.expressCheckoutElement) {
3633
- console.warn('Express Checkout Element not initialized. Cannot update options.');
3634
- return;
3635
- }
3636
- // Convert buttonHeight from string to number if present
3637
- const updateOptions = Object.assign({}, options);
3638
- if (updateOptions.buttonHeight && typeof updateOptions.buttonHeight === 'string') {
3639
- const height = parseInt(updateOptions.buttonHeight.replace('px', ''), 10);
3640
- if (!isNaN(height)) {
3641
- updateOptions.buttonHeight = height;
3642
- }
3643
- }
3644
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
3645
- this.expressCheckoutElement.update(updateOptions);
3646
- }
3647
- /**
3648
- * Set error message (triggers reactivity)
3649
- */
3650
- setError(message) {
3651
- this.store.set('errorMessage', message);
3652
- }
3653
- /**
3654
- * Clear error message (triggers reactivity)
3655
- */
3656
- clearError() {
3657
- this.store.set('errorMessage', '');
3658
- }
3659
- /**
3660
- * Unmount express checkout element
3661
- */
3662
- unmount() {
3663
- if (!this.expressCheckoutElement) {
3664
- return;
3665
- }
3666
- this.expressCheckoutElement.unmount();
3667
- this.expressCheckoutElement = undefined;
3668
- this.store.set('isReady', false);
3669
- }
3670
- }
3671
-
3672
- /**
3673
- * Service Factory
3674
- * Creates service instances with proper dependency injection
3675
- * Can be mocked in tests for better testability
3676
- */
3677
- class ServiceFactory {
3678
- /**
3679
- * Create a new StripeService instance
3680
- */
3681
- createStripeService() {
3682
- return new StripeServiceClass();
3683
- }
3684
- /**
3685
- * Create a new CardElementManager instance
3686
- * @param stripeService - Injected StripeService dependency
3687
- */
3688
- createCardElementManager(stripeService) {
3689
- return new CardElementManager(stripeService);
3690
- }
3691
- /**
3692
- * Create a new PaymentElementManager instance
3693
- * @param stripeService - Injected StripeService dependency
3694
- */
3695
- createPaymentElementManager(stripeService) {
3696
- return new PaymentElementManager(stripeService);
3697
- }
3698
- /**
3699
- * Create a new AddressElementManager instance
3700
- * @param stripeService - Injected StripeService dependency
3701
- */
3702
- createAddressElementManager(stripeService) {
3703
- return new AddressElementManager(stripeService);
3704
- }
3705
- /**
3706
- * Create a new LinkAuthenticationElementManager instance
3707
- * @param stripeService - Injected StripeService dependency
3708
- */
3709
- createLinkAuthenticationElementManager(stripeService) {
3710
- return new LinkAuthenticationElementManager(stripeService);
3711
- }
3712
- /**
3713
- * Create a new CurrencySelectorElementManager instance
3714
- * @param stripeService - Injected StripeService dependency
3715
- */
3716
- createCurrencySelectorElementManager(stripeService) {
3717
- return new CurrencySelectorElementManager(stripeService);
3718
- }
3719
- /**
3720
- * Create a new ExpressCheckoutElementManager instance
3721
- * @param stripeService - Injected StripeService dependency
3722
- */
3723
- createExpressCheckoutElementManager(stripeService) {
3724
- return new ExpressCheckoutElementManager(stripeService);
3725
- }
3726
- }
3727
- /**
3728
- * Default factory instance
3729
- * Can be replaced with a mock in tests
3730
- */
3731
- const serviceFactory = new ServiceFactory();
3732
-
3733
- export { i18n as i, serviceFactory as s };
3734
- //# sourceMappingURL=factory.js.map
3735
-
3736
- //# sourceMappingURL=factory.js.map
1
+ import*as t from"@stencil/core/internal/client";import{l as e}from"./index2.js";const i=t=>"string"==typeof t,s=()=>{let t,e;const i=new Promise(((i,s)=>{t=i,e=s}));return i.resolve=t,i.reject=e,i},n=t=>null==t?"":""+t,r=/###/g,o=t=>t&&t.indexOf("###")>-1?t.replace(r,"."):t,a=t=>!t||i(t),h=(t,e,s)=>{const n=i(e)?e.split("."):e;let r=0;for(;r<n.length-1;){if(a(t))return{};const e=o(n[r]);!t[e]&&s&&(t[e]=new s),t=Object.prototype.hasOwnProperty.call(t,e)?t[e]:{},++r}return a(t)?{}:{obj:t,k:o(n[r])}},l=(t,e,i)=>{const{obj:s,k:n}=h(t,e,Object);if(void 0!==s||1===e.length)return void(s[n]=i);let r=e[e.length-1],o=e.slice(0,e.length-1),a=h(t,o,Object);for(;void 0===a.obj&&o.length;)r=`${o[o.length-1]}.${r}`,o=o.slice(0,o.length-1),a=h(t,o,Object),a?.obj&&void 0!==a.obj[`${a.k}.${r}`]&&(a.obj=void 0);a.obj[`${a.k}.${r}`]=i},c=(t,e)=>{const{obj:i,k:s}=h(t,e);if(i&&Object.prototype.hasOwnProperty.call(i,s))return i[s]},u=(t,e,s)=>{for(const n in e)"__proto__"!==n&&"constructor"!==n&&(n in t?i(t[n])||t[n]instanceof String||i(e[n])||e[n]instanceof String?s&&(t[n]=e[n]):u(t[n],e[n],s):t[n]=e[n]);return t},d=t=>t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var f={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};const p=t=>i(t)?t.replace(/[&<>"'\/]/g,(t=>f[t])):t,g=[" ",",","?","!",";"],m=new class{constructor(t){this.capacity=t,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(t){const e=this.regExpMap.get(t);if(void 0!==e)return e;const i=new RegExp(t);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(t,i),this.regExpQueue.push(t),i}}(20),y=(t,e,i=".")=>{if(!t)return;if(t[e]){if(!Object.prototype.hasOwnProperty.call(t,e))return;return t[e]}const s=e.split(i);let n=t;for(let t=0;t<s.length;){if(!n||"object"!=typeof n)return;let e,r="";for(let o=t;o<s.length;++o)if(o!==t&&(r+=i),r+=s[o],e=n[r],void 0!==e){if(["string","number","boolean"].indexOf(typeof e)>-1&&o<s.length-1)continue;t+=o-t+1;break}n=e}return n},v=t=>t?.replace(/_/g,"-"),w={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console?.[t]?.apply?.(console,e)}};class b{constructor(t,e={}){this.init(t,e)}init(t,e={}){this.prefix=e.prefix||"i18next:",this.logger=t||w,this.options=e,this.debug=e.debug}log(...t){return this.forward(t,"log","",!0)}warn(...t){return this.forward(t,"warn","",!0)}error(...t){return this.forward(t,"error","")}deprecate(...t){return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}forward(t,e,s,n){return n&&!this.debug?null:(i(t[0])&&(t[0]=`${s}${this.prefix} ${t[0]}`),this.logger[e](t))}create(t){return new b(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return(t=t||this.options).prefix=t.prefix||this.prefix,new b(this.logger,t)}}var S=new b;class ${constructor(){this.observers={}}on(t,e){return t.split(" ").forEach((t=>{this.observers[t]||(this.observers[t]=new Map);const i=this.observers[t].get(e)||0;this.observers[t].set(e,i+1)})),this}off(t,e){this.observers[t]&&(e?this.observers[t].delete(e):delete this.observers[t])}emit(t,...e){this.observers[t]&&Array.from(this.observers[t].entries()).forEach((([t,i])=>{for(let s=0;s<i;s++)t(...e)})),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach((([i,s])=>{for(let n=0;n<s;n++)i.apply(i,[t,...e])}))}}class x extends ${constructor(t,e={ns:["translation"],defaultNS:"translation"}){super(),this.data=t||{},this.options=e,void 0===this.options.keySeparator&&(this.options.keySeparator="."),void 0===this.options.ignoreJSONStructure&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const e=this.options.ns.indexOf(t);e>-1&&this.options.ns.splice(e,1)}getResource(t,e,s,n={}){const r=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator,o=void 0!==n.ignoreJSONStructure?n.ignoreJSONStructure:this.options.ignoreJSONStructure;let a;t.indexOf(".")>-1?a=t.split("."):(a=[t,e],s&&(Array.isArray(s)?a.push(...s):i(s)&&r?a.push(...s.split(r)):a.push(s)));const h=c(this.data,a);return!h&&!e&&!s&&t.indexOf(".")>-1&&(t=a[0],e=a[1],s=a.slice(2).join(".")),!h&&o&&i(s)?y(this.data?.[t]?.[e],s,r):h}addResource(t,e,i,s,n={silent:!1}){const r=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator;let o=[t,e];i&&(o=o.concat(r?i.split(r):i)),t.indexOf(".")>-1&&(o=t.split("."),s=e,e=o[1]),this.addNamespaces(e),l(this.data,o,s),n.silent||this.emit("added",t,e,i,s)}addResources(t,e,s,n={silent:!1}){for(const n in s)(i(s[n])||Array.isArray(s[n]))&&this.addResource(t,e,n,s[n],{silent:!0});n.silent||this.emit("added",t,e,s)}addResourceBundle(t,e,i,s,n,r={silent:!1,skipCopy:!1}){let o=[t,e];t.indexOf(".")>-1&&(o=t.split("."),s=i,i=e,e=o[1]),this.addNamespaces(e);let a=c(this.data,o)||{};r.skipCopy||(i=JSON.parse(JSON.stringify(i))),s?u(a,i,n):a={...a,...i},l(this.data,o,a),r.silent||this.emit("added",t,e,i)}removeResourceBundle(t,e){this.hasResourceBundle(t,e)&&delete this.data[t][e],this.removeNamespaces(e),this.emit("removed",t,e)}hasResourceBundle(t,e){return void 0!==this.getResource(t,e)}getResourceBundle(t,e){return e||(e=this.options.defaultNS),this.getResource(t,e)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const e=this.getDataByLanguage(t);return!!(e&&Object.keys(e)||[]).find((t=>e[t]&&Object.keys(e[t]).length>0))}toJSON(){return this.data}}var k={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,i,s,n){return t.forEach((t=>{e=this.processors[t]?.process(e,i,s,n)??e})),e}};const C=Symbol("i18next/PATH_KEY");function j(t,e){const{[C]:i}=t(function(){const t=[],e=Object.create(null);let i;return e.get=(s,n)=>(i?.revoke?.(),n===C?t:(t.push(n),i=Proxy.revocable(s,e),i.proxy)),Proxy.revocable(Object.create(null),e).proxy}()),s=e?.keySeparator??".",n=e?.nsSeparator??":";if(i.length>1&&n){const t=e?.ns,r=Array.isArray(t)?t:null;if(r&&r.length>1&&r.slice(1).includes(i[0]))return`${i[0]}${n}${i.slice(1).join(s)}`}return i.join(s)}const E={},O=t=>!i(t)&&"boolean"!=typeof t&&"number"!=typeof t;class N extends ${constructor(t,e={}){var i,s;super(),i=t,s=this,["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"].forEach((t=>{i[t]&&(s[t]=i[t])})),this.options=e,void 0===this.options.keySeparator&&(this.options.keySeparator="."),this.logger=S.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t,e={interpolation:{}}){const i={...e};if(null==t)return!1;const s=this.resolve(t,i);if(void 0===s?.res)return!1;const n=O(s.res);return!1!==i.returnObjects||!n}extractFromKey(t,e){let s=void 0!==e.nsSeparator?e.nsSeparator:this.options.nsSeparator;void 0===s&&(s=":");const n=void 0!==e.keySeparator?e.keySeparator:this.options.keySeparator;let r=e.ns||this.options.defaultNS||[];const o=s&&t.indexOf(s)>-1,a=!(this.options.userDefinedKeySeparator||e.keySeparator||this.options.userDefinedNsSeparator||e.nsSeparator||((t,e,i)=>{e=e||"",i=i||"";const s=g.filter((t=>e.indexOf(t)<0&&i.indexOf(t)<0));if(0===s.length)return!0;const n=m.getRegExp(`(${s.map((t=>"?"===t?"\\?":t)).join("|")})`);let r=!n.test(t);if(!r){const e=t.indexOf(i);e>0&&!n.test(t.substring(0,e))&&(r=!0)}return r})(t,s,n));if(o&&!a){const e=t.match(this.interpolator.nestingRegexp);if(e&&e.length>0)return{key:t,namespaces:i(r)?[r]:r};const o=t.split(s);(s!==n||s===n&&this.options.ns.indexOf(o[0])>-1)&&(r=o.shift()),t=o.join(n)}return{key:t,namespaces:i(r)?[r]:r}}translate(t,e,s){let n="object"==typeof e?{...e}:e;if("object"!=typeof n&&this.options.overloadTranslationOptionHandler&&(n=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof n&&(n={...n}),n||(n={}),null==t)return"";"function"==typeof t&&(t=j(t,{...this.options,...n})),Array.isArray(t)||(t=[String(t)]),t=t.map((t=>"function"==typeof t?j(t,{...this.options,...n}):String(t)));const r=void 0!==n.returnDetails?n.returnDetails:this.options.returnDetails,o=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator,{key:a,namespaces:h}=this.extractFromKey(t[t.length-1],n),l=h[h.length-1];let c=void 0!==n.nsSeparator?n.nsSeparator:this.options.nsSeparator;void 0===c&&(c=":");const u=n.lng||this.language,d=n.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if("cimode"===u?.toLowerCase())return d?r?{res:`${l}${c}${a}`,usedKey:a,exactUsedKey:a,usedLng:u,usedNS:l,usedParams:this.getUsedParamsDetails(n)}:`${l}${c}${a}`:r?{res:a,usedKey:a,exactUsedKey:a,usedLng:u,usedNS:l,usedParams:this.getUsedParamsDetails(n)}:a;const f=this.resolve(t,n);let p=f?.res;const g=f?.usedKey||a,m=f?.exactUsedKey||a,y=void 0!==n.joinArrays?n.joinArrays:this.options.joinArrays,v=!this.i18nFormat||this.i18nFormat.handleAsObject,w=void 0!==n.count&&!i(n.count),b=N.hasDefaultValue(n),S=w?this.pluralResolver.getSuffix(u,n.count,n):"",$=n.ordinal&&w?this.pluralResolver.getSuffix(u,n.count,{ordinal:!1}):"",x=w&&!n.ordinal&&0===n.count,k=x&&n[`defaultValue${this.options.pluralSeparator}zero`]||n[`defaultValue${S}`]||n[`defaultValue${$}`]||n.defaultValue;let C=p;v&&!p&&b&&(C=k);const E=O(C),L=Object.prototype.toString.apply(C);if(!(v&&C&&E&&["[object Number]","[object Function]","[object RegExp]"].indexOf(L)<0)||i(y)&&Array.isArray(C))if(v&&i(y)&&Array.isArray(p))p=p.join(y),p&&(p=this.extendTranslation(p,t,n,s));else{let e=!1,i=!1;!this.isValidLookup(p)&&b&&(e=!0,p=k),this.isValidLookup(p)||(i=!0,p=a);const r=(n.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&i?void 0:p,h=b&&k!==p&&this.options.updateMissing;if(i||e||h){if(this.logger.log(h?"updateKey":"missingKey",u,l,a,h?k:p),o){const t=this.resolve(a,{...n,keySeparator:!1});t&&t.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let t=[];const e=this.languageUtils.getFallbackCodes(this.options.fallbackLng,n.lng||this.language);if("fallback"===this.options.saveMissingTo&&e&&e[0])for(let i=0;i<e.length;i++)t.push(e[i]);else"all"===this.options.saveMissingTo?t=this.languageUtils.toResolveHierarchy(n.lng||this.language):t.push(n.lng||this.language);const i=(t,e,i)=>{const s=b&&i!==p?i:r;this.options.missingKeyHandler?this.options.missingKeyHandler(t,l,e,s,h,n):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(t,l,e,s,h,n),this.emit("missingKey",t,l,e,p)};this.options.saveMissing&&(this.options.saveMissingPlurals&&w?t.forEach((t=>{const e=this.pluralResolver.getSuffixes(t,n);x&&n[`defaultValue${this.options.pluralSeparator}zero`]&&e.indexOf(`${this.options.pluralSeparator}zero`)<0&&e.push(`${this.options.pluralSeparator}zero`),e.forEach((e=>{i([t],a+e,n[`defaultValue${e}`]||k)}))})):i(t,a,k))}p=this.extendTranslation(p,t,n,f,s),i&&p===a&&this.options.appendNamespaceToMissingKey&&(p=`${l}${c}${a}`),(i||e)&&this.options.parseMissingKeyHandler&&(p=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${l}${c}${a}`:a,e?p:void 0,n))}else{if(!n.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const t=this.options.returnedObjectHandler?this.options.returnedObjectHandler(g,C,{...n,ns:h}):`key '${a} (${this.language})' returned an object instead of string.`;return r?(f.res=t,f.usedParams=this.getUsedParamsDetails(n),f):t}if(o){const t=Array.isArray(C),e=t?[]:{},i=t?m:g;for(const t in C)if(Object.prototype.hasOwnProperty.call(C,t)){const s=`${i}${o}${t}`;e[t]=this.translate(s,b&&!p?{...n,defaultValue:O(k)?k[t]:void 0,joinArrays:!1,ns:h}:{...n,joinArrays:!1,ns:h}),e[t]===s&&(e[t]=C[t])}p=e}}return r?(f.res=p,f.usedParams=this.getUsedParamsDetails(n),f):p}extendTranslation(t,e,s,n,r){if(this.i18nFormat?.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||n.usedLng,n.usedNS,n.usedKey,{resolved:n});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init({...s,interpolation:{...this.options.interpolation,...s.interpolation}});const o=i(t)&&(void 0!==s?.interpolation?.skipOnVariables?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let a;if(o){const e=t.match(this.interpolator.nestingRegexp);a=e&&e.length}let h=s.replace&&!i(s.replace)?s.replace:s;if(this.options.interpolation.defaultVariables&&(h={...this.options.interpolation.defaultVariables,...h}),t=this.interpolator.interpolate(t,h,s.lng||this.language||n.usedLng,s),o){const e=t.match(this.interpolator.nestingRegexp);a<(e&&e.length)&&(s.nest=!1)}!s.lng&&n&&n.res&&(s.lng=this.language||n.usedLng),!1!==s.nest&&(t=this.interpolator.nest(t,((...t)=>r?.[0]!==t[0]||s.context?this.translate(...t,e):(this.logger.warn(`It seems you are nesting recursively key: ${t[0]} in key: ${e[0]}`),null)),s)),s.interpolation&&this.interpolator.reset()}const o=s.postProcess||this.options.postProcess,a=i(o)?[o]:o;return null!=t&&a?.length&&!1!==s.applyPostProcessor&&(t=k.handle(a,t,e,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...n,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),t}resolve(t,e={}){let s,n,r,o,a;return i(t)&&(t=[t]),Array.isArray(t)&&(t=t.map((t=>"function"==typeof t?j(t,{...this.options,...e}):t))),t.forEach((t=>{if(this.isValidLookup(s))return;const h=this.extractFromKey(t,e),l=h.key;n=l;let c=h.namespaces;this.options.fallbackNS&&(c=c.concat(this.options.fallbackNS));const u=void 0!==e.count&&!i(e.count),d=u&&!e.ordinal&&0===e.count,f=void 0!==e.context&&(i(e.context)||"number"==typeof e.context)&&""!==e.context,p=e.lngs?e.lngs:this.languageUtils.toResolveHierarchy(e.lng||this.language,e.fallbackLng);c.forEach((t=>{this.isValidLookup(s)||(a=t,E[`${p[0]}-${t}`]||!this.utils?.hasLoadedNamespace||this.utils?.hasLoadedNamespace(a)||(E[`${p[0]}-${t}`]=!0,this.logger.warn(`key "${n}" for languages "${p.join(", ")}" won't get resolved as namespace "${a}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),p.forEach((i=>{if(this.isValidLookup(s))return;o=i;const n=[l];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(n,l,i,t,e);else{let t;u&&(t=this.pluralResolver.getSuffix(i,e.count,e));const s=`${this.options.pluralSeparator}zero`,r=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(u&&(e.ordinal&&0===t.indexOf(r)&&n.push(l+t.replace(r,this.options.pluralSeparator)),n.push(l+t),d&&n.push(l+s)),f){const i=`${l}${this.options.contextSeparator||"_"}${e.context}`;n.push(i),u&&(e.ordinal&&0===t.indexOf(r)&&n.push(i+t.replace(r,this.options.pluralSeparator)),n.push(i+t),d&&n.push(i+s))}}let a;for(;a=n.pop();)this.isValidLookup(s)||(r=a,s=this.getResource(i,t,a,e))})))}))})),{res:s,usedKey:n,exactUsedKey:r,usedLng:o,usedNS:a}}isValidLookup(t){return!(void 0===t||!this.options.returnNull&&null===t||!this.options.returnEmptyString&&""===t)}getResource(t,e,i,s={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(t,e,i,s):this.resourceStore.getResource(t,e,i,s)}getUsedParamsDetails(t={}){const e=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],s=t.replace&&!i(t.replace);let n=s?t.replace:t;if(s&&void 0!==t.count&&(n.count=t.count),this.options.interpolation.defaultVariables&&(n={...this.options.interpolation.defaultVariables,...n}),!s){n={...n};for(const t of e)delete n[t]}return n}static hasDefaultValue(t){for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&"defaultValue"===e.substring(0,12)&&void 0!==t[e])return!0;return!1}}class L{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=S.create("languageUtils")}getScriptPartFromCode(t){if(!(t=v(t))||t.indexOf("-")<0)return null;const e=t.split("-");return 2===e.length?null:(e.pop(),"x"===e[e.length-1].toLowerCase()?null:this.formatLanguageCode(e.join("-")))}getLanguagePartFromCode(t){if(!(t=v(t))||t.indexOf("-")<0)return t;const e=t.split("-");return this.formatLanguageCode(e[0])}formatLanguageCode(t){if(i(t)&&t.indexOf("-")>-1){let e;try{e=Intl.getCanonicalLocales(t)[0]}catch(t){}return e&&this.options.lowerCaseLng&&(e=e.toLowerCase()),e||(this.options.lowerCaseLng?t.toLowerCase():t)}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let e;return t.forEach((t=>{if(e)return;const i=this.formatLanguageCode(t);this.options.supportedLngs&&!this.isSupportedCode(i)||(e=i)})),!e&&this.options.supportedLngs&&t.forEach((t=>{if(e)return;const i=this.getScriptPartFromCode(t);if(this.isSupportedCode(i))return e=i;const s=this.getLanguagePartFromCode(t);if(this.isSupportedCode(s))return e=s;e=this.options.supportedLngs.find((t=>t===s?t:t.indexOf("-")<0&&s.indexOf("-")<0?void 0:t.indexOf("-")>0&&s.indexOf("-")<0&&t.substring(0,t.indexOf("-"))===s||0===t.indexOf(s)&&s.length>1?t:void 0))})),e||(e=this.getFallbackCodes(this.options.fallbackLng)[0]),e}getFallbackCodes(t,e){if(!t)return[];if("function"==typeof t&&(t=t(e)),i(t)&&(t=[t]),Array.isArray(t))return t;if(!e)return t.default||[];let s=t[e];return s||(s=t[this.getScriptPartFromCode(e)]),s||(s=t[this.formatLanguageCode(e)]),s||(s=t[this.getLanguagePartFromCode(e)]),s||(s=t.default),s||[]}toResolveHierarchy(t,e){const s=this.getFallbackCodes((!1===e?[]:e)||this.options.fallbackLng||[],t),n=[],r=t=>{t&&(this.isSupportedCode(t)?n.push(t):this.logger.warn(`rejecting language code not found in supportedLngs: ${t}`))};return i(t)&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?("languageOnly"!==this.options.load&&r(this.formatLanguageCode(t)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&r(this.getScriptPartFromCode(t)),"currentOnly"!==this.options.load&&r(this.getLanguagePartFromCode(t))):i(t)&&r(this.formatLanguageCode(t)),s.forEach((t=>{n.indexOf(t)<0&&r(this.formatLanguageCode(t))})),n}}const M={zero:0,one:1,two:2,few:3,many:4,other:5},P={select:t=>1===t?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class z{constructor(t,e={}){this.languageUtils=t,this.options=e,this.logger=S.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(t,e={}){const i=v("dev"===t?"en":t),s=e.ordinal?"ordinal":"cardinal",n=JSON.stringify({cleanedCode:i,type:s});if(n in this.pluralRulesCache)return this.pluralRulesCache[n];let r;try{r=new Intl.PluralRules(i,{type:s})}catch(i){if("undefined"==typeof Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),P;if(!t.match(/-|_/))return P;const s=this.languageUtils.getLanguagePartFromCode(t);r=this.getRule(s,e)}return this.pluralRulesCache[n]=r,r}needsPlural(t,e={}){let i=this.getRule(t,e);return i||(i=this.getRule("dev",e)),i?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(t,e,i={}){return this.getSuffixes(t,i).map((t=>`${e}${t}`))}getSuffixes(t,e={}){let i=this.getRule(t,e);return i||(i=this.getRule("dev",e)),i?i.resolvedOptions().pluralCategories.sort(((t,e)=>M[t]-M[e])).map((t=>`${this.options.prepend}${e.ordinal?`ordinal${this.options.prepend}`:""}${t}`)):[]}getSuffix(t,e,i={}){const s=this.getRule(t,i);return s?`${this.options.prepend}${i.ordinal?`ordinal${this.options.prepend}`:""}${s.select(e)}`:(this.logger.warn(`no plural rule found for: ${t}`),this.getSuffix("dev",e,i))}}const A=(t,e,s,n=".",r=!0)=>{let o=((t,e,i)=>{const s=c(t,i);return void 0!==s?s:c(e,i)})(t,e,s);return!o&&r&&i(s)&&(o=y(t,s,n),void 0===o&&(o=y(e,s,n))),o},R=t=>t.replace(/\$/g,"$$$$");class T{constructor(t={}){this.logger=S.create("interpolator"),this.options=t,this.format=t?.interpolation?.format||(t=>t),this.init(t)}init(t={}){t.interpolation||(t.interpolation={escapeValue:!0});const{escape:e,escapeValue:i,useRawValueToEscape:s,prefix:n,prefixEscaped:r,suffix:o,suffixEscaped:a,formatSeparator:h,unescapeSuffix:l,unescapePrefix:c,nestingPrefix:u,nestingPrefixEscaped:f,nestingSuffix:g,nestingSuffixEscaped:m,nestingOptionsSeparator:y,maxReplaces:v,alwaysFormat:w}=t.interpolation;this.escape=void 0!==e?e:p,this.escapeValue=void 0===i||i,this.useRawValueToEscape=void 0!==s&&s,this.prefix=n?d(n):r||"{{",this.suffix=o?d(o):a||"}}",this.formatSeparator=h||",",this.unescapePrefix=l?"":c||"-",this.unescapeSuffix=this.unescapePrefix?"":l||"",this.nestingPrefix=u?d(u):f||d("$t("),this.nestingSuffix=g?d(g):m||d(")"),this.nestingOptionsSeparator=y||",",this.maxReplaces=v||1e3,this.alwaysFormat=void 0!==w&&w,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=(t,e)=>t?.source===e?(t.lastIndex=0,t):new RegExp(e,"g");this.regexp=t(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=t(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=t(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(t,e,s,r){let o,a,h;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=t=>{if(t.indexOf(this.formatSeparator)<0){const i=A(e,l,t,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(i,void 0,s,{...r,...e,interpolationkey:t}):i}const i=t.split(this.formatSeparator),n=i.shift().trim(),o=i.join(this.formatSeparator).trim();return this.format(A(e,l,n,this.options.keySeparator,this.options.ignoreJSONStructure),o,s,{...r,...e,interpolationkey:n})};this.resetRegExp();const u=r?.missingInterpolationHandler||this.options.missingInterpolationHandler,d=void 0!==r?.interpolation?.skipOnVariables?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:t=>R(t)},{regex:this.regexp,safeValue:t=>R(this.escapeValue?this.escape(t):t)}].forEach((e=>{for(h=0;o=e.regex.exec(t);){const s=o[1].trim();if(a=c(s),void 0===a)if("function"==typeof u){const e=u(t,o,r);a=i(e)?e:""}else if(r&&Object.prototype.hasOwnProperty.call(r,s))a="";else{if(d){a=o[0];continue}this.logger.warn(`missed to pass in variable ${s} for interpolating ${t}`),a=""}else i(a)||this.useRawValueToEscape||(a=n(a));const l=e.safeValue(a);if(t=t.replace(o[0],l),d?(e.regex.lastIndex+=a.length,e.regex.lastIndex-=o[0].length):e.regex.lastIndex=0,h++,h>=this.maxReplaces)break}})),t}nest(t,e,s={}){let r,o,a;const h=(t,e)=>{const i=this.nestingOptionsSeparator;if(t.indexOf(i)<0)return t;const s=t.split(new RegExp(`${d(i)}[ ]*{`));let n=`{${s[1]}`;t=s[0],n=this.interpolate(n,a);const r=n.match(/'/g),o=n.match(/"/g);((r?.length??0)%2==0&&!o||(o?.length??0)%2!=0)&&(n=n.replace(/'/g,'"'));try{a=JSON.parse(n),e&&(a={...e,...a})}catch(e){return this.logger.warn(`failed parsing options string in nesting for key ${t}`,e),`${t}${i}${n}`}return a.defaultValue&&a.defaultValue.indexOf(this.prefix)>-1&&delete a.defaultValue,t};for(;r=this.nestingRegexp.exec(t);){let l=[];a={...s},a=a.replace&&!i(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const c=/{.*}/.test(r[1])?r[1].lastIndexOf("}")+1:r[1].indexOf(this.formatSeparator);if(-1!==c&&(l=r[1].slice(c).split(this.formatSeparator).map((t=>t.trim())).filter(Boolean),r[1]=r[1].slice(0,c)),o=e(h.call(this,r[1].trim(),a),a),o&&r[0]===t&&!i(o))return o;i(o)||(o=n(o)),o||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${t}`),o=""),l.length&&(o=l.reduce(((t,e)=>this.format(t,e,s.lng,{...s,interpolationkey:r[1].trim()})),o.trim())),t=t.replace(r[0],o),this.regexp.lastIndex=0}return t}}const I=t=>{const e={};return(i,s,n)=>{let r=n;n&&n.interpolationkey&&n.formatParams&&n.formatParams[n.interpolationkey]&&n[n.interpolationkey]&&(r={...r,[n.interpolationkey]:void 0});const o=s+JSON.stringify(r);let a=e[o];return a||(a=t(v(s),n),e[o]=a),a(i)}},F=t=>(e,i,s)=>t(v(i),s)(e);class V{constructor(t={}){this.logger=S.create("formatter"),this.options=t,this.init(t)}init(t,e={interpolation:{}}){this.formatSeparator=e.interpolation.formatSeparator||",";const i=e.cacheInBuiltFormats?I:F;this.formats={number:i(((t,e)=>{const i=new Intl.NumberFormat(t,{...e});return t=>i.format(t)})),currency:i(((t,e)=>{const i=new Intl.NumberFormat(t,{...e,style:"currency"});return t=>i.format(t)})),datetime:i(((t,e)=>{const i=new Intl.DateTimeFormat(t,{...e});return t=>i.format(t)})),relativetime:i(((t,e)=>{const i=new Intl.RelativeTimeFormat(t,{...e});return t=>i.format(t,e.range||"day")})),list:i(((t,e)=>{const i=new Intl.ListFormat(t,{...e});return t=>i.format(t)}))}}add(t,e){this.formats[t.toLowerCase().trim()]=e}addCached(t,e){this.formats[t.toLowerCase().trim()]=I(e)}format(t,e,i,s={}){const n=e.split(this.formatSeparator);if(n.length>1&&n[0].indexOf("(")>1&&n[0].indexOf(")")<0&&n.find((t=>t.indexOf(")")>-1))){const t=n.findIndex((t=>t.indexOf(")")>-1));n[0]=[n[0],...n.splice(1,t)].join(this.formatSeparator)}return n.reduce(((t,e)=>{const{formatName:n,formatOptions:r}=(t=>{let e=t.toLowerCase().trim();const i={};if(t.indexOf("(")>-1){const s=t.split("(");e=s[0].toLowerCase().trim();const n=s[1].substring(0,s[1].length-1);"currency"===e&&n.indexOf(":")<0?i.currency||(i.currency=n.trim()):"relativetime"===e&&n.indexOf(":")<0?i.range||(i.range=n.trim()):n.split(";").forEach((t=>{if(t){const[e,...s]=t.split(":"),n=s.join(":").trim().replace(/^'+|'+$/g,""),r=e.trim();i[r]||(i[r]=n),"false"===n&&(i[r]=!1),"true"===n&&(i[r]=!0),isNaN(n)||(i[r]=parseInt(n,10))}}))}return{formatName:e,formatOptions:i}})(e);if(this.formats[n]){let e=t;try{const o=s?.formatParams?.[s.interpolationkey]||{};e=this.formats[n](t,o.locale||o.lng||s.locale||s.lng||i,{...r,...s,...o})}catch(t){this.logger.warn(t)}return e}return this.logger.warn(`there was no format function for ${n}`),t}),t)}}class D extends ${constructor(t,e,i,s={}){super(),this.backend=t,this.store=e,this.services=i,this.languageUtils=i.languageUtils,this.options=s,this.logger=S.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=s.maxParallelReads||10,this.readingCalls=0,this.maxRetries=s.maxRetries>=0?s.maxRetries:5,this.retryTimeout=s.retryTimeout>=1?s.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(i,s.backend,s)}queueLoad(t,e,i,s){const n={},r={},o={},a={};return t.forEach((t=>{let s=!0;e.forEach((e=>{const o=`${t}|${e}`;!i.reload&&this.store.hasResourceBundle(t,e)?this.state[o]=2:this.state[o]<0||(1===this.state[o]?void 0===r[o]&&(r[o]=!0):(this.state[o]=1,s=!1,void 0===r[o]&&(r[o]=!0),void 0===n[o]&&(n[o]=!0),void 0===a[e]&&(a[e]=!0)))})),s||(o[t]=!0)})),(Object.keys(n).length||Object.keys(r).length)&&this.queue.push({pending:r,pendingCount:Object.keys(r).length,loaded:{},errors:[],callback:s}),{toLoad:Object.keys(n),pending:Object.keys(r),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(a)}}loaded(t,e,i){const s=t.split("|"),n=s[0],r=s[1];e&&this.emit("failedLoading",n,r,e),!e&&i&&this.store.addResourceBundle(n,r,i,void 0,void 0,{skipCopy:!0}),this.state[t]=e?-1:2,e&&i&&(this.state[t]=0);const o={};this.queue.forEach((i=>{((t,e,i)=>{const{obj:s,k:n}=h(t,e,Object);s[n]=s[n]||[],s[n].push(i)})(i.loaded,[n],r),((t,e)=>{void 0!==t.pending[e]&&(delete t.pending[e],t.pendingCount--)})(i,t),e&&i.errors.push(e),0!==i.pendingCount||i.done||(Object.keys(i.loaded).forEach((t=>{o[t]||(o[t]={});const e=i.loaded[t];e.length&&e.forEach((e=>{void 0===o[t][e]&&(o[t][e]=!0)}))})),i.done=!0,i.errors.length?i.callback(i.errors):i.callback())})),this.emit("loaded",o),this.queue=this.queue.filter((t=>!t.done))}read(t,e,i,s=0,n=this.retryTimeout,r){if(!t.length)return r(null,{});if(this.readingCalls>=this.maxParallelReads)return void this.waitingReads.push({lng:t,ns:e,fcName:i,tried:s,wait:n,callback:r});this.readingCalls++;const o=(o,a)=>{if(this.readingCalls--,this.waitingReads.length>0){const t=this.waitingReads.shift();this.read(t.lng,t.ns,t.fcName,t.tried,t.wait,t.callback)}o&&a&&s<this.maxRetries?setTimeout((()=>{this.read.call(this,t,e,i,s+1,2*n,r)}),n):r(o,a)},a=this.backend[i].bind(this.backend);if(2!==a.length)return a(t,e,o);try{const i=a(t,e);i&&"function"==typeof i.then?i.then((t=>o(null,t))).catch(o):o(null,i)}catch(t){o(t)}}prepareLoading(t,e,s={},n){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),n&&n();i(t)&&(t=this.languageUtils.toResolveHierarchy(t)),i(e)&&(e=[e]);const r=this.queueLoad(t,e,s,n);if(!r.toLoad.length)return r.pending.length||n(),null;r.toLoad.forEach((t=>{this.loadOne(t)}))}load(t,e,i){this.prepareLoading(t,e,{},i)}reload(t,e,i){this.prepareLoading(t,e,{reload:!0},i)}loadOne(t,e=""){const i=t.split("|"),s=i[0],n=i[1];this.read(s,n,"read",void 0,void 0,((i,r)=>{i&&this.logger.warn(`${e}loading namespace ${n} for language ${s} failed`,i),!i&&r&&this.logger.log(`${e}loaded namespace ${n} for language ${s}`,r),this.loaded(t,i,r)}))}saveMissing(t,e,i,s,n,r={},o=()=>{}){if(!this.services?.utils?.hasLoadedNamespace||this.services?.utils?.hasLoadedNamespace(e)){if(null!=i&&""!==i){if(this.backend?.create){const a={...r,isUpdate:n},h=this.backend.create.bind(this.backend);if(h.length<6)try{let n;n=5===h.length?h(t,e,i,s,a):h(t,e,i,s),n&&"function"==typeof n.then?n.then((t=>o(null,t))).catch(o):o(null,n)}catch(t){o(t)}else h(t,e,i,s,o,a)}t&&t[0]&&this.store.addResource(t[0],e,i,s)}}else this.logger.warn(`did not save key "${i}" as the namespace "${e}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")}}const K=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:t=>{let e={};if("object"==typeof t[1]&&(e=t[1]),i(t[1])&&(e.defaultValue=t[1]),i(t[2])&&(e.tDescription=t[2]),"object"==typeof t[2]||"object"==typeof t[3]){const i=t[3]||t[2];Object.keys(i).forEach((t=>{e[t]=i[t]}))}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),B=t=>(i(t.ns)&&(t.ns=[t.ns]),i(t.fallbackLng)&&(t.fallbackLng=[t.fallbackLng]),i(t.fallbackNS)&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs?.indexOf?.("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),"boolean"==typeof t.initImmediate&&(t.initAsync=t.initImmediate),t),_=()=>{},U="__i18next_supportNoticeShown";class H extends ${constructor(t={},e){var i;if(super(),this.options=B(t),this.services={},this.logger=S,this.modules={external:[]},i=this,Object.getOwnPropertyNames(Object.getPrototypeOf(i)).forEach((t=>{"function"==typeof i[t]&&(i[t]=i[t].bind(i))})),e&&!this.isInitialized&&!t.isClone){if(!this.options.initAsync)return this.init(t,e),this;setTimeout((()=>{this.init(t,e)}),0)}}init(t={},e){this.isInitializing=!0,"function"==typeof t&&(e=t,t={}),null==t.defaultNS&&t.ns&&(i(t.ns)?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));const n=K();var r;this.options={...n,...this.options,...B(t)},this.options.interpolation={...n.interpolation,...this.options.interpolation},void 0!==t.keySeparator&&(this.options.userDefinedKeySeparator=t.keySeparator),void 0!==t.nsSeparator&&(this.options.userDefinedNsSeparator=t.nsSeparator),"function"!=typeof this.options.overloadTranslationOptionHandler&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler),!1===this.options.showSupportNotice||(r=this,r?.modules?.backend?.name?.indexOf("Locize")>0||r?.modules?.backend?.constructor?.name?.indexOf("Locize")>0||r?.options?.backend?.backends&&r.options.backend.backends.some((t=>t?.name?.indexOf("Locize")>0||t?.constructor?.name?.indexOf("Locize")>0))||r?.options?.backend?.projectId||r?.options?.backend?.backendOptions&&r.options.backend.backendOptions.some((t=>t?.projectId)))||"undefined"!=typeof globalThis&&globalThis[U]||"undefined"!=typeof process&&process.env&&process.env.I18NEXT_NO_SUPPORT_NOTICE||"undefined"!=typeof process&&process.env||("undefined"!=typeof console&&void 0!==console.info&&console.info("🌐 i18next is made possible by our own product, Locize — consider powering your project with managed localization (AI, CDN, integrations): https://locize.com 💙"),"undefined"!=typeof globalThis&&(globalThis[U]=!0));const o=t=>t?"function"==typeof t?new t:t:null;if(!this.options.isClone){let t;S.init(this.modules.logger?o(this.modules.logger):null,this.options),t=this.modules.formatter?this.modules.formatter:V;const e=new L(this.options);this.store=new x(this.options.resources,this.options);const i=this.services;i.logger=S,i.resourceStore=this.store,i.languageUtils=e,i.pluralResolver=new z(e,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),!t||this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format||(i.formatter=o(t),i.formatter.init&&i.formatter.init(i,this.options),this.options.interpolation.format=i.formatter.format.bind(i.formatter)),i.interpolator=new T(this.options),i.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},i.backendConnector=new D(o(this.modules.backend),i.resourceStore,i,this.options),i.backendConnector.on("*",((t,...e)=>{this.emit(t,...e)})),this.modules.languageDetector&&(i.languageDetector=o(this.modules.languageDetector),i.languageDetector.init&&i.languageDetector.init(i,this.options.detection,this.options)),this.modules.i18nFormat&&(i.i18nFormat=o(this.modules.i18nFormat),i.i18nFormat.init&&i.i18nFormat.init(this)),this.translator=new N(this.services,this.options),this.translator.on("*",((t,...e)=>{this.emit(t,...e)})),this.modules.external.forEach((t=>{t.init&&t.init(this)}))}if(this.format=this.options.interpolation.format,e||(e=_),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const t=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);t.length>0&&"dev"!==t[0]&&(this.options.lng=t[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach((t=>{this[t]=(...e)=>this.store[t](...e)})),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach((t=>{this[t]=(...e)=>(this.store[t](...e),this)}));const a=s(),h=()=>{const t=(t,i)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(i),e(t,i)};if(this.languages&&!this.isInitialized)return t(null,this.t.bind(this));this.changeLanguage(this.options.lng,t)};return this.options.resources||!this.options.initAsync?h():setTimeout(h,0),a}loadResources(t,e=_){let s=e;const n=i(t)?t:this.language;if("function"==typeof t&&(s=t),!this.options.resources||this.options.partialBundledLanguages){if("cimode"===n?.toLowerCase()&&(!this.options.preload||0===this.options.preload.length))return s();const t=[],e=e=>{e&&"cimode"!==e&&this.services.languageUtils.toResolveHierarchy(e).forEach((e=>{"cimode"!==e&&t.indexOf(e)<0&&t.push(e)}))};n?e(n):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((t=>e(t))),this.options.preload?.forEach?.((t=>e(t))),this.services.backendConnector.load(t,this.options.ns,(t=>{t||this.resolvedLanguage||!this.language||this.setResolvedLanguage(this.language),s(t)}))}else s(null)}reloadResources(t,e,i){const n=s();return"function"==typeof t&&(i=t,t=void 0),"function"==typeof e&&(i=e,e=void 0),t||(t=this.languages),e||(e=this.options.ns),i||(i=_),this.services.backendConnector.reload(t,e,(t=>{n.resolve(),i(t)})),n}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===t.type&&(this.modules.backend=t),("logger"===t.type||t.log&&t.warn&&t.error)&&(this.modules.logger=t),"languageDetector"===t.type&&(this.modules.languageDetector=t),"i18nFormat"===t.type&&(this.modules.i18nFormat=t),"postProcessor"===t.type&&k.addPostProcessor(t),"formatter"===t.type&&(this.modules.formatter=t),"3rdParty"===t.type&&this.modules.external.push(t),this}setResolvedLanguage(t){if(t&&this.languages&&!(["cimode","dev"].indexOf(t)>-1)){for(let t=0;t<this.languages.length;t++){const e=this.languages[t];if(!(["cimode","dev"].indexOf(e)>-1)&&this.store.hasLanguageSomeTranslations(e)){this.resolvedLanguage=e;break}}!this.resolvedLanguage&&this.languages.indexOf(t)<0&&this.store.hasLanguageSomeTranslations(t)&&(this.resolvedLanguage=t,this.languages.unshift(t))}}changeLanguage(t,e){this.isLanguageChangingTo=t;const n=s();this.emit("languageChanging",t);const r=t=>{this.language=t,this.languages=this.services.languageUtils.toResolveHierarchy(t),this.resolvedLanguage=void 0,this.setResolvedLanguage(t)},o=(i,s)=>{s?this.isLanguageChangingTo===t&&(r(s),this.translator.changeLanguage(s),this.isLanguageChangingTo=void 0,this.emit("languageChanged",s),this.logger.log("languageChanged",s)):this.isLanguageChangingTo=void 0,n.resolve(((...t)=>this.t(...t))),e&&e(i,((...t)=>this.t(...t)))},a=e=>{t||e||!this.services.languageDetector||(e=[]);const s=i(e)?e:e&&e[0],n=this.store.hasLanguageSomeTranslations(s)?s:this.services.languageUtils.getBestMatchFromCodes(i(e)?[e]:e);n&&(this.language||r(n),this.translator.language||this.translator.changeLanguage(n),this.services.languageDetector?.cacheUserLanguage?.(n)),this.loadResources(n,(t=>{o(t,n)}))};return t||!this.services.languageDetector||this.services.languageDetector.async?!t&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(t):a(this.services.languageDetector.detect()),n}getFixedT(t,e,s){const n=(t,e,...i)=>{let r;r="object"!=typeof e?this.options.overloadTranslationOptionHandler([t,e].concat(i)):{...e},r.lng=r.lng||n.lng,r.lngs=r.lngs||n.lngs,r.ns=r.ns||n.ns,""!==r.keyPrefix&&(r.keyPrefix=r.keyPrefix||s||n.keyPrefix);const o={...this.options,...r};"function"==typeof r.keyPrefix&&(r.keyPrefix=j(r.keyPrefix,o));const a=this.options.keySeparator||".";let h;return r.keyPrefix&&Array.isArray(t)?h=t.map((t=>("function"==typeof t&&(t=j(t,o)),`${r.keyPrefix}${a}${t}`))):("function"==typeof t&&(t=j(t,o)),h=r.keyPrefix?`${r.keyPrefix}${a}${t}`:t),this.t(h,r)};return i(t)?n.lng=t:n.lngs=t,n.ns=e,n.keyPrefix=s,n}t(...t){return this.translator?.translate(...t)}exists(...t){return this.translator?.exists(...t)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t,e={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const i=e.lng||this.resolvedLanguage||this.languages[0],s=!!this.options&&this.options.fallbackLng,n=this.languages[this.languages.length-1];if("cimode"===i.toLowerCase())return!0;const r=(t,e)=>{const i=this.services.backendConnector.state[`${t}|${e}`];return-1===i||0===i||2===i};if(e.precheck){const t=e.precheck(this,r);if(void 0!==t)return t}return!(!this.hasResourceBundle(i,t)&&this.services.backendConnector.backend&&(!this.options.resources||this.options.partialBundledLanguages)&&(!r(i,t)||s&&!r(n,t)))}loadNamespaces(t,e){const n=s();return this.options.ns?(i(t)&&(t=[t]),t.forEach((t=>{this.options.ns.indexOf(t)<0&&this.options.ns.push(t)})),this.loadResources((t=>{n.resolve(),e&&e(t)})),n):(e&&e(),Promise.resolve())}loadLanguages(t,e){const n=s();i(t)&&(t=[t]);const r=this.options.preload||[],o=t.filter((t=>r.indexOf(t)<0&&this.services.languageUtils.isSupportedCode(t)));return o.length?(this.options.preload=r.concat(o),this.loadResources((t=>{n.resolve(),e&&e(t)})),n):(e&&e(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!t)return"rtl";try{const e=new Intl.Locale(t);if(e&&e.getTextInfo){const t=e.getTextInfo();if(t&&t.direction)return t.direction}}catch(t){}const e=this.services?.languageUtils||new L(K());return t.toLowerCase().indexOf("-latn")>1?"ltr":["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].indexOf(e.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(t={},e){const i=new H(t,e);return i.createInstance=H.createInstance,i}cloneInstance(t={},e=_){const i=t.forkResourceStore;i&&delete t.forkResourceStore;const s={...this.options,...t,isClone:!0},n=new H(s);if(void 0===t.debug&&void 0===t.prefix||(n.logger=n.logger.clone(t)),["store","services","language"].forEach((t=>{n[t]=this[t]})),n.services={...this.services},n.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},i){const t=Object.keys(this.store.data).reduce(((t,e)=>(t[e]={...this.store.data[e]},t[e]=Object.keys(t[e]).reduce(((i,s)=>(i[s]={...t[e][s]},i)),t[e]),t)),{});n.store=new x(t,s),n.services.resourceStore=n.store}if(t.interpolation){const e={...K().interpolation,...this.options.interpolation,...t.interpolation},i={...s,interpolation:e};n.services.interpolator=new T(i)}return n.translator=new N(n.services,s),n.translator.on("*",((t,...e)=>{n.emit(t,...e)})),n.init(s,e),n.translator.options=s,n.translator.backendConnector.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},n}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const Y=H.createInstance(),{slice:W,forEach:J}=[],q=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,G={create(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{path:"/",sameSite:"strict"};i&&(n.expires=new Date,n.expires.setTime(n.expires.getTime()+60*i*1e3)),s&&(n.domain=s),document.cookie=function(t,e){const i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{path:"/"};let s=`${t}=${encodeURIComponent(e)}`;if(i.maxAge>0){const t=i.maxAge-0;if(Number.isNaN(t))throw new Error("maxAge should be a Number");s+=`; Max-Age=${Math.floor(t)}`}if(i.domain){if(!q.test(i.domain))throw new TypeError("option domain is invalid");s+=`; Domain=${i.domain}`}if(i.path){if(!q.test(i.path))throw new TypeError("option path is invalid");s+=`; Path=${i.path}`}if(i.expires){if("function"!=typeof i.expires.toUTCString)throw new TypeError("option expires is invalid");s+=`; Expires=${i.expires.toUTCString()}`}if(i.httpOnly&&(s+="; HttpOnly"),i.secure&&(s+="; Secure"),i.sameSite)switch("string"==typeof i.sameSite?i.sameSite.toLowerCase():i.sameSite){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return i.partitioned&&(s+="; Partitioned"),s}(t,e,n)},read(t){const e=`${t}=`,i=document.cookie.split(";");for(let t=0;t<i.length;t++){let s=i[t];for(;" "===s.charAt(0);)s=s.substring(1,s.length);if(0===s.indexOf(e))return s.substring(e.length,s.length)}return null},remove(t,e){this.create(t,"",-1,e)}};var Q={name:"cookie",lookup(t){let{lookupCookie:e}=t;if(e&&"undefined"!=typeof document)return G.read(e)||void 0},cacheUserLanguage(t,e){let{lookupCookie:i,cookieMinutes:s,cookieDomain:n,cookieOptions:r}=e;i&&"undefined"!=typeof document&&G.create(i,t,s,n,r)}},Z={name:"querystring",lookup(t){let e,{lookupQuerystring:i}=t;if("undefined"!=typeof window){let{search:t}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(t=window.location.hash.substring(window.location.hash.indexOf("?")));const s=t.substring(1).split("&");for(let t=0;t<s.length;t++){const n=s[t].indexOf("=");n>0&&s[t].substring(0,n)===i&&(e=s[t].substring(n+1))}}return e}},X={name:"hash",lookup(t){let e,{lookupHash:i,lookupFromHashIndex:s}=t;if("undefined"!=typeof window){const{hash:t}=window.location;if(t&&t.length>2){const n=t.substring(1);if(i){const t=n.split("&");for(let s=0;s<t.length;s++){const n=t[s].indexOf("=");n>0&&t[s].substring(0,n)===i&&(e=t[s].substring(n+1))}}if(e)return e;if(!e&&s>-1){const e=t.match(/\/([a-zA-Z-]*)/g);if(!Array.isArray(e))return;const i="number"==typeof s?s:0;return e[i]?.replace("/","")}}}return e}};let tt=null;const et=()=>{if(null!==tt)return tt;try{if(tt="undefined"!=typeof window&&null!==window.localStorage,!tt)return!1;const t="i18next.translate.boo";window.localStorage.setItem(t,"foo"),window.localStorage.removeItem(t)}catch(t){tt=!1}return tt};var it={name:"localStorage",lookup(t){let{lookupLocalStorage:e}=t;if(e&&et())return window.localStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupLocalStorage:i}=e;i&&et()&&window.localStorage.setItem(i,t)}};let st=null;const nt=()=>{if(null!==st)return st;try{if(st="undefined"!=typeof window&&null!==window.sessionStorage,!st)return!1;const t="i18next.translate.boo";window.sessionStorage.setItem(t,"foo"),window.sessionStorage.removeItem(t)}catch(t){st=!1}return st};var rt={name:"sessionStorage",lookup(t){let{lookupSessionStorage:e}=t;if(e&&nt())return window.sessionStorage.getItem(e)||void 0},cacheUserLanguage(t,e){let{lookupSessionStorage:i}=e;i&&nt()&&window.sessionStorage.setItem(i,t)}},ot={name:"navigator",lookup(t){const e=[];if("undefined"!=typeof navigator){const{languages:t,userLanguage:i,language:s}=navigator;if(t)for(let i=0;i<t.length;i++)e.push(t[i]);i&&e.push(i),s&&e.push(s)}return e.length>0?e:void 0}},at={name:"htmlTag",lookup(t){let e,{htmlTag:i}=t;const s=i||("undefined"!=typeof document?document.documentElement:null);return s&&"function"==typeof s.getAttribute&&(e=s.getAttribute("lang")),e}},ht={name:"path",lookup(t){let{lookupFromPathIndex:e}=t;if("undefined"==typeof window)return;const i=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(!Array.isArray(i))return;const s="number"==typeof e?e:0;return i[s]?.replace("/","")}},lt={name:"subdomain",lookup(t){let{lookupFromSubdomainIndex:e}=t;const i="number"==typeof e?e+1:1,s="undefined"!=typeof window&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(s)return s[i]}};let ct=!1;try{ct=!0}catch(t){}const ut=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];ct||ut.splice(1,1);class dt{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(t,e)}init(){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},e=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.services=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{languageUtils:{}},this.options=function(t){return J.call(W.call(arguments,1),(e=>{if(e)for(const i in e)void 0===t[i]&&(t[i]=e[i])})),t}(t,this.options||{},{order:ut,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:t=>t}),"string"==typeof this.options.convertDetectedLanguage&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=t=>t.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=e,this.addDetector(Q),this.addDetector(Z),this.addDetector(it),this.addDetector(rt),this.addDetector(ot),this.addDetector(at),this.addDetector(ht),this.addDetector(lt),this.addDetector(X)}addDetector(t){return this.detectors[t.name]=t,this}detect(){let t=[];return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.options.order).forEach((e=>{if(this.detectors[e]){let i=this.detectors[e].lookup(this.options);i&&"string"==typeof i&&(i=[i]),i&&(t=t.concat(i))}})),t=t.filter((t=>{return null!=t&&!("string"==typeof(e=t)&&[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some((t=>t.test(e))));var e})).map((t=>this.options.convertDetectedLanguage(t))),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}cacheUserLanguage(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.options.caches;e&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(t)>-1||e.forEach((e=>{this.detectors[e]&&this.detectors[e].cacheUserLanguage(t,this.options)})))}}dt.type="languageDetector",Y.use(dt).init({fallbackLng:"en",debug:!1,resources:{en:{translation:{}},ja:{translation:{Pay:"支払う","Failed to load Stripe":"ライブラリの読み込みに失敗しました。","Add your payment information":"支払情報を追加","Add card":"カードを追加","Add a card":"カードを追加",Add:"追加","Card information":"カード情報","Card Number":"カード番号","MM / YY":"月 / 年",CVC:"セキュリティコード(CVC)","Country or region":"地域","Postal Code":"郵便番号"}},"pt-BR":{translation:{Pay:"Pagar","Failed to load Stripe":"Falha ao ler Stripe","Add your payment information":"Informações do seu Pagamento","Add card":"Adicionar Cartão","Add a card":"Adicionar um Cartão",Add:"Adicionar","Card information":"Informações do Cartão","Card Number":"Número do Cartão","MM / YY":"MM / AA",CVC:"Número de Segurança(CVC)","Country or region":"País ou região","Postal Code":"Cep"}}}});const ft=Y,pt=(()=>{let t;return(...e)=>{t&&clearTimeout(t),t=setTimeout((()=>{t=0,(t=>{for(let e of t.keys()){const i=t.get(e).filter((t=>{const e=t.deref();return e&&(!("isConnected"in(i=e))||i.isConnected);var i}));t.set(e,i)}})(...e)}),2e3)}})(),gt=t.forceUpdate,mt=t.getRenderingRef,yt=(t,e)=>{const i=t.indexOf(e);i>=0&&(t[i]=t[t.length-1],t.length--)},vt=(t,e)=>{const i=((t,e=(t,e)=>t!==e)=>{const i=()=>{return("function"==typeof(e=t)?e():e)??{};var e},s=i();let n=new Map(Object.entries(s));const r="undefined"!=typeof Proxy,o=r?null:{},a={dispose:[],get:[],set:[],reset:[]},h=new Map,l=()=>{n=new Map(Object.entries(i())),r||g(),a.reset.forEach((t=>t()))},c=t=>(a.get.forEach((e=>e(t))),n.get(t)),u=(t,i)=>{const s=n.get(t);e(i,s,t)&&(n.set(t,i),r||p(t),a.set.forEach((e=>e(t,i,s))))},d=r?new Proxy(s,{get:(t,e)=>c(e),ownKeys:()=>Array.from(n.keys()),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),has:(t,e)=>n.has(e),set:(t,e,i)=>(u(e,i),!0)}):(g(),o),f=(t,e)=>(a[t].push(e),()=>{yt(a[t],e)});function p(t){!r&&o&&(Object.prototype.hasOwnProperty.call(o,t)||Object.defineProperty(o,t,{configurable:!0,enumerable:!0,get:()=>c(t),set(e){u(t,e)}}))}function g(){if(r||!o)return;const t=new Set(n.keys());for(const e of Object.keys(o))t.has(e)||delete o[e];for(const e of t)p(e)}return{state:d,get:c,set:u,on:f,onChange:(t,e)=>{const s=(i,s)=>{i===t&&e(s)},n=()=>{const s=i();e(s[t])},r=f("set",s),o=f("reset",n);return h.set(e,{setHandler:s,resetHandler:n,propName:t}),()=>{r(),o(),h.delete(e)}},use:(...t)=>{const e=t.reduce(((t,e)=>(e.set&&t.push(f("set",e.set)),e.get&&t.push(f("get",e.get)),e.reset&&t.push(f("reset",e.reset)),e.dispose&&t.push(f("dispose",e.dispose)),t)),[]);return()=>e.forEach((t=>t()))},dispose:()=>{a.dispose.forEach((t=>t())),l()},reset:l,forceUpdate:t=>{const e=n.get(t);a.set.forEach((i=>i(t,e,e)))},removeListener:(t,e)=>{const i=h.get(e);i&&i.propName===t&&(yt(a.set,i.setHandler),yt(a.reset,i.resetHandler),h.delete(e))}}})(t,e);return i.use((()=>{if("function"!=typeof mt||"function"!=typeof gt)return{};const t=gt,e=mt,i=new Map;return{dispose:()=>i.clear(),get:t=>{const s=e();s&&((t,e,i)=>{let s=t.get(e);s||(s=[],t.set(e,s)),s.some((t=>t.deref()===i))||s.push(new WeakRef(i))})(i,t,s)},set:e=>{const s=i.get(e);if(s){const n=s.filter((e=>{const i=e.deref();return!!i&&t(i)}));i.set(e,n)}pt(i)},reset:()=>{i.forEach((e=>{e.forEach((e=>{const i=e.deref();i&&t(i)}))})),pt(i)}}})()),i};class wt{constructor(){this.store=vt({loadStripeStatus:"",applicationName:"stripe-pwa-elements",isCheckoutSession:!1}),this.changeListeners=new Map}get state(){return this.store.state}onChange(t,e){const i=this.store.onChange(t,e);return this.changeListeners.has(t)||this.changeListeners.set(t,[]),this.changeListeners.get(t).push(i),i}async initialize(t,i){if(this.store.state.publishableKey=t,this.store.state.isCheckoutSession=!1,null!=(null==i?void 0:i.stripeAccount)&&""!==(null==i?void 0:i.stripeAccount)&&(this.store.state.stripeAccount=i.stripeAccount),null!=(null==i?void 0:i.applicationName)&&""!==(null==i?void 0:i.applicationName)&&(this.store.state.applicationName=i.applicationName),!this.store.state.stripe||this.store.state.publishableKey!==t||this.store.state.stripeAccount!==(null==i?void 0:i.stripeAccount)||this.store.state.isCheckoutSession){this.store.state.loadStripeStatus="loading";try{const s=await e(t,{stripeAccount:null==i?void 0:i.stripeAccount});s.registerAppInfo({name:this.store.state.applicationName}),this.store.state.stripe=s,this.store.state.elements=s.elements(),this.store.state.checkout=void 0,this.store.state.loadStripeStatus="success"}catch(t){console.error("Failed to load Stripe.js:",t),this.store.state.loadStripeStatus="failure"}}}async initializeWithCheckoutSession(t,i,s){this.store.state.publishableKey=t,this.store.state.isCheckoutSession=!0,null!=(null==s?void 0:s.stripeAccount)&&""!==(null==s?void 0:s.stripeAccount)&&(this.store.state.stripeAccount=s.stripeAccount),null!=(null==s?void 0:s.applicationName)&&""!==(null==s?void 0:s.applicationName)&&(this.store.state.applicationName=s.applicationName),this.store.state.loadStripeStatus="loading";try{const n=await e(t,{stripeAccount:null==s?void 0:s.stripeAccount});n.registerAppInfo({name:this.store.state.applicationName}),this.store.state.stripe=n;const r=n.initCheckoutElementsSdk({clientSecret:i,elementsOptions:null==s?void 0:s.elementsOptions});this.store.state.checkout=r,this.store.state.elements=void 0,this.store.state.loadStripeStatus="success"}catch(t){console.error("Failed to initialize Stripe Checkout:",t),this.store.state.loadStripeStatus="failure"}}getStripe(){return this.store.state.stripe}getElements(){return this.store.state.elements}getCheckout(){return this.store.state.checkout}reset(){this.store.reset()}dispose(){this.changeListeners.forEach((t=>{t.forEach((t=>t()))})),this.changeListeners.clear(),this.store.dispose()}}function bt(t,e,i=5e3){return new Promise(((s,n)=>{const r=t.querySelector(e);if(null!=r)return s(r);const o=setTimeout((()=>{a.disconnect(),n(new Error(`Element "${e}" not found within ${i}ms`))}),i),a=new MutationObserver((()=>{const i=t.querySelector(e);null!=i&&(clearTimeout(o),a.disconnect(),s(i))}));a.observe(t,{childList:!0,subtree:!0})}))}new wt;class St{constructor(t){this.stripeService=t,this.store=vt({errorMessage:"",errorSource:void 0})}getState(){return this.store.state}async initialize(t){const e=this.stripeService.getElements();if(null==e)throw new Error("StripeService not initialized. Call StripeService.initialize() first.");null!=this.cardElements&&this.unmount();const i=e.create("cardNumber",{placeholder:ft.t("Card Number")}),s=await bt(t,"#card-number");i.mount(s),i.on("change",this.handleCardError("cardNumber"));const n=e.create("cardExpiry"),r=await bt(t,"#card-expiry");n.mount(r),n.on("change",this.handleCardError("cardExpiry"));const o=e.create("cardCvc"),a=await bt(t,"#card-cvc");return o.mount(a),o.on("change",this.handleCardError("cardCvc")),this.cardElements={cardNumber:i,cardExpiry:n,cardCVC:o},this.cardElements}getElements(){return this.cardElements}setError(t){this.store.set("errorMessage",t)}clearError(){this.store.set("errorMessage",""),this.store.set("errorSource",void 0)}unmount(){var t,e,i;null!=this.cardElements&&(null===(t=this.cardElements.cardNumber)||void 0===t||t.unmount(),null===(e=this.cardElements.cardExpiry)||void 0===e||e.unmount(),null===(i=this.cardElements.cardCVC)||void 0===i||i.unmount(),this.cardElements=void 0)}handleCardError(t){return({error:e})=>{if(e)return this.store.set("errorMessage",e.message),void this.store.set("errorSource",t);this.store.state.errorSource===t&&(this.store.set("errorMessage",""),this.store.set("errorSource",void 0))}}}class $t{constructor(t){this.stripeService=t,this.store=vt({errorMessage:""})}getState(){return this.store.state}async initialize(t,e){const i=this.stripeService.state.isCheckoutSession;if(null!=this.paymentElement&&this.unmount(),i){const t=this.stripeService.getCheckout();if(null==t)throw new Error("StripeService not initialized with Checkout Session. Call StripeService.initializeWithCheckoutSession() first.");this.paymentElement=t.createPaymentElement(e)}else{const t=this.stripeService.getElements();if(null==t)throw new Error("StripeService not initialized. Call StripeService.initialize() first.");this.paymentElement=t.create("payment",e||{})}const s=await bt(t,"#payment-element");return this.paymentElement.mount(s),this.paymentElement}getElement(){return this.paymentElement}setError(t){this.store.set("errorMessage",t)}clearError(){this.store.set("errorMessage","")}unmount(){null!=this.paymentElement&&(this.paymentElement.unmount(),this.paymentElement=void 0)}}class xt{constructor(t){this.stripeService=t,this.store=vt({errorMessage:"",isComplete:!1})}getState(){return this.store.state}async initialize(t,e){const i=this.stripeService.getElements();if(null==i)throw new Error("StripeService not initialized. Call StripeService.initialize() first.");null!=this.addressElement&&this.unmount(),this.addressElement=i.create("address",e||{mode:"billing"});const s=await bt(t,"#address-element");return this.addressElement.mount(s),this.addressElement.on("change",(t=>{this.store.set("errorMessage",""),this.store.set("isComplete",t.complete)})),this.addressElement}getElement(){return this.addressElement}setError(t){this.store.set("errorMessage",t)}clearError(){this.store.set("errorMessage","")}unmount(){null!=this.addressElement&&(this.addressElement.unmount(),this.addressElement=void 0)}}class kt{constructor(t){this.stripeService=t,this.store=vt({errorMessage:"",email:void 0})}getState(){return this.store.state}onChange(t,e){return this.store.onChange(t,e)}async initialize(t,e){const i=this.stripeService.getElements();if(null==i)throw new Error("StripeService not initialized. Call StripeService.initialize() first.");null!=this.linkAuthenticationElement&&this.unmount();const s=i.create("linkAuthentication",e),n=await bt(t,"#link-authentication-element");return s.mount(n),s.on("change",(t=>{var e;this.store.set("email",null===(e=t.value)||void 0===e?void 0:e.email)})),this.linkAuthenticationElement=s,this.linkAuthenticationElement}getElement(){return this.linkAuthenticationElement}setError(t){this.store.set("errorMessage",t)}clearError(){this.store.set("errorMessage","")}unmount(){null!=this.linkAuthenticationElement&&(this.linkAuthenticationElement.unmount(),this.linkAuthenticationElement=void 0)}}class Ct{constructor(t){this.stripeService=t,this.store=vt({errorMessage:"",selectedCurrency:void 0})}getState(){return this.store.state}async initialize(t,e){const i=this.stripeService.getElements();if(null==i)throw new Error("StripeService not initialized. Call StripeService.initialize() first.");null!=this.currencySelectorElement&&this.unmount();const s=await bt(t,"#currency-selector");return this.currencySelectorElement=i.create("currencySelector",e||{}),this.currencySelectorElement.mount(s),this.currencySelectorElement.on("change",(t=>{var e;this.store.set("errorMessage",""),(null===(e=null==t?void 0:t.value)||void 0===e?void 0:e.currency)&&this.store.set("selectedCurrency",t.value.currency)})),this.currencySelectorElement}getElement(){return this.currencySelectorElement}setError(t){this.store.set("errorMessage",t)}clearError(){this.store.set("errorMessage","")}unmount(){null!=this.currencySelectorElement&&(this.currencySelectorElement.unmount(),this.currencySelectorElement=void 0)}}class jt{constructor(t){this.stripeService=t,this.store=vt({errorMessage:"",isReady:!1})}getState(){return this.store.state}async initialize(t,e,i){const s=this.stripeService.getElements();if(null==s)throw new Error("StripeService not initialized. Call StripeService.initialize() first.");null!=this.expressCheckoutElement&&this.unmount();const n=Object.assign({},e);if(n.buttonHeight&&"string"==typeof n.buttonHeight){const t=parseInt(n.buttonHeight.replace("px",""),10);isNaN(t)||(n.buttonHeight=t)}const r=s.create("expressCheckout",n),o=await bt(t,"#express-checkout-element");return null!=(null==i?void 0:i.onConfirm)&&r.on("confirm",i.onConfirm),null!=(null==i?void 0:i.onClick)&&r.on("click",i.onClick),null!=(null==i?void 0:i.onCancel)&&r.on("cancel",i.onCancel),null!=(null==i?void 0:i.onShippingAddressChange)&&r.on("shippingaddresschange",i.onShippingAddressChange),null!=(null==i?void 0:i.onShippingRateChange)&&r.on("shippingratechange",i.onShippingRateChange),r.on("ready",(()=>{this.store.set("isReady",!0)})),r.mount(o),this.expressCheckoutElement=r,this.expressCheckoutElement}getElement(){return this.expressCheckoutElement}update(t){if(null==this.expressCheckoutElement)return void console.warn("Express Checkout Element not initialized. Cannot update options.");const e=Object.assign({},t);if(e.buttonHeight&&"string"==typeof e.buttonHeight){const t=parseInt(e.buttonHeight.replace("px",""),10);isNaN(t)||(e.buttonHeight=t)}this.expressCheckoutElement.update(e)}setError(t){this.store.set("errorMessage",t)}clearError(){this.store.set("errorMessage","")}unmount(){null!=this.expressCheckoutElement&&(this.expressCheckoutElement.unmount(),this.expressCheckoutElement=void 0,this.store.set("isReady",!1))}}const Et=new class{createStripeService(){return new wt}createCardElementManager(t){return new St(t)}createPaymentElementManager(t){return new $t(t)}createAddressElementManager(t){return new xt(t)}createLinkAuthenticationElementManager(t){return new kt(t)}createCurrencySelectorElementManager(t){return new Ct(t)}createExpressCheckoutElementManager(t){return new jt(t)}};export{ft as i,Et as s}