@aidc-toolkit/gs1 1.0.25-beta → 1.0.27-beta

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 (273) hide show
  1. package/dist/abstract-identifier-creator.d.ts +75 -0
  2. package/dist/abstract-identifier-creator.d.ts.map +1 -0
  3. package/dist/abstract-identifier-creator.js +79 -0
  4. package/dist/abstract-identifier-creator.js.map +1 -0
  5. package/dist/abstract-non-gtin-numeric-identifier-creator.d.ts +42 -0
  6. package/dist/abstract-non-gtin-numeric-identifier-creator.d.ts.map +1 -0
  7. package/dist/abstract-non-gtin-numeric-identifier-creator.js +40 -0
  8. package/dist/abstract-non-gtin-numeric-identifier-creator.js.map +1 -0
  9. package/dist/abstract-numeric-identifier-creator.d.ts +43 -0
  10. package/dist/abstract-numeric-identifier-creator.d.ts.map +1 -0
  11. package/dist/abstract-numeric-identifier-creator.js +160 -0
  12. package/dist/abstract-numeric-identifier-creator.js.map +1 -0
  13. package/dist/character-set.d.ts +27 -0
  14. package/dist/character-set.d.ts.map +1 -0
  15. package/dist/character-set.js +50 -0
  16. package/dist/character-set.js.map +1 -0
  17. package/dist/check.d.ts +81 -0
  18. package/dist/check.d.ts.map +1 -0
  19. package/dist/check.js +218 -0
  20. package/dist/check.js.map +1 -0
  21. package/dist/content-character-set-creators.d.ts +4 -0
  22. package/dist/content-character-set-creators.d.ts.map +1 -0
  23. package/dist/content-character-set-creators.js +9 -0
  24. package/dist/content-character-set-creators.js.map +1 -0
  25. package/dist/content-character-set.d.ts +26 -0
  26. package/dist/content-character-set.d.ts.map +1 -0
  27. package/dist/content-character-set.js +18 -0
  28. package/dist/content-character-set.js.map +1 -0
  29. package/dist/gtin-creator.d.ts +64 -0
  30. package/dist/gtin-creator.d.ts.map +1 -0
  31. package/dist/gtin-creator.js +156 -0
  32. package/dist/gtin-creator.js.map +1 -0
  33. package/dist/gtin-descriptor.d.ts +22 -0
  34. package/dist/gtin-descriptor.d.ts.map +1 -0
  35. package/dist/gtin-descriptor.js +2 -0
  36. package/dist/gtin-descriptor.js.map +1 -0
  37. package/dist/gtin-length.d.ts +64 -0
  38. package/dist/gtin-length.d.ts.map +1 -0
  39. package/dist/gtin-length.js +36 -0
  40. package/dist/gtin-length.js.map +1 -0
  41. package/dist/gtin-type.d.ts +26 -0
  42. package/dist/gtin-type.d.ts.map +1 -0
  43. package/dist/gtin-type.js +7 -0
  44. package/dist/gtin-type.js.map +1 -0
  45. package/dist/gtin-validator.d.ts +177 -0
  46. package/dist/gtin-validator.d.ts.map +1 -0
  47. package/dist/gtin-validator.js +443 -0
  48. package/dist/gtin-validator.js.map +1 -0
  49. package/dist/identifier-creator.d.ts +31 -0
  50. package/dist/identifier-creator.d.ts.map +1 -0
  51. package/dist/identifier-creator.js +2 -0
  52. package/dist/identifier-creator.js.map +1 -0
  53. package/dist/identifier-creators.d.ts +90 -0
  54. package/dist/identifier-creators.d.ts.map +1 -0
  55. package/dist/identifier-creators.js +74 -0
  56. package/dist/identifier-creators.js.map +1 -0
  57. package/dist/identifier-descriptor.d.ts +27 -0
  58. package/dist/identifier-descriptor.d.ts.map +1 -0
  59. package/dist/identifier-descriptor.js +2 -0
  60. package/dist/identifier-descriptor.js.map +1 -0
  61. package/dist/identifier-descriptors.d.ts +106 -0
  62. package/dist/identifier-descriptors.d.ts.map +1 -0
  63. package/dist/identifier-descriptors.js +262 -0
  64. package/dist/identifier-descriptors.js.map +1 -0
  65. package/dist/identifier-extension.d.ts +82 -0
  66. package/dist/identifier-extension.d.ts.map +1 -0
  67. package/dist/identifier-extension.js +79 -0
  68. package/dist/identifier-extension.js.map +1 -0
  69. package/dist/identifier-type.d.ts +62 -0
  70. package/dist/identifier-type.d.ts.map +1 -0
  71. package/dist/identifier-type.js +54 -0
  72. package/dist/identifier-type.js.map +1 -0
  73. package/dist/identifier-validator.d.ts +88 -0
  74. package/dist/identifier-validator.d.ts.map +1 -0
  75. package/dist/identifier-validator.js +110 -0
  76. package/dist/identifier-validator.js.map +1 -0
  77. package/dist/identifier-validators.d.ts +106 -0
  78. package/dist/identifier-validators.d.ts.map +1 -0
  79. package/dist/identifier-validators.js +153 -0
  80. package/dist/identifier-validators.js.map +1 -0
  81. package/dist/index.d.ts +58 -1949
  82. package/dist/index.d.ts.map +1 -0
  83. package/dist/index.js +30 -4727
  84. package/dist/index.js.map +1 -1
  85. package/dist/leader-type.d.ts +26 -0
  86. package/dist/leader-type.d.ts.map +1 -0
  87. package/dist/leader-type.js +18 -0
  88. package/dist/leader-type.js.map +1 -0
  89. package/dist/locale/en/locale-resources.d.ts +42 -0
  90. package/dist/locale/en/locale-resources.d.ts.map +1 -0
  91. package/dist/locale/en/locale-resources.js +41 -0
  92. package/dist/locale/en/locale-resources.js.map +1 -0
  93. package/dist/locale/fr/locale-resources.d.ts +42 -0
  94. package/dist/locale/fr/locale-resources.d.ts.map +1 -0
  95. package/dist/locale/fr/locale-resources.js +41 -0
  96. package/dist/locale/fr/locale-resources.js.map +1 -0
  97. package/dist/locale/i18n.d.ts +27 -0
  98. package/dist/locale/i18n.d.ts.map +1 -0
  99. package/dist/locale/i18n.js +36 -0
  100. package/dist/locale/i18n.js.map +1 -0
  101. package/dist/non-gtin-numeric-identifier-creator.d.ts +12 -0
  102. package/dist/non-gtin-numeric-identifier-creator.d.ts.map +1 -0
  103. package/dist/non-gtin-numeric-identifier-creator.js +2 -0
  104. package/dist/non-gtin-numeric-identifier-creator.js.map +1 -0
  105. package/dist/non-gtin-numeric-identifier-descriptor.d.ts +22 -0
  106. package/dist/non-gtin-numeric-identifier-descriptor.d.ts.map +1 -0
  107. package/dist/non-gtin-numeric-identifier-descriptor.js +2 -0
  108. package/dist/non-gtin-numeric-identifier-descriptor.js.map +1 -0
  109. package/dist/non-gtin-numeric-identifier-type.d.ts +26 -0
  110. package/dist/non-gtin-numeric-identifier-type.d.ts.map +1 -0
  111. package/dist/non-gtin-numeric-identifier-type.js +8 -0
  112. package/dist/non-gtin-numeric-identifier-type.js.map +1 -0
  113. package/dist/non-gtin-numeric-identifier-validator.d.ts +12 -0
  114. package/dist/non-gtin-numeric-identifier-validator.d.ts.map +1 -0
  115. package/dist/non-gtin-numeric-identifier-validator.js +10 -0
  116. package/dist/non-gtin-numeric-identifier-validator.js.map +1 -0
  117. package/dist/non-numeric-identifier-creator.d.ts +40 -0
  118. package/dist/non-numeric-identifier-creator.d.ts.map +1 -0
  119. package/dist/non-numeric-identifier-creator.js +82 -0
  120. package/dist/non-numeric-identifier-creator.js.map +1 -0
  121. package/dist/non-numeric-identifier-descriptor.d.ts +26 -0
  122. package/dist/non-numeric-identifier-descriptor.d.ts.map +1 -0
  123. package/dist/non-numeric-identifier-descriptor.js +2 -0
  124. package/dist/non-numeric-identifier-descriptor.js.map +1 -0
  125. package/dist/non-numeric-identifier-type.d.ts +26 -0
  126. package/dist/non-numeric-identifier-type.d.ts.map +1 -0
  127. package/dist/non-numeric-identifier-type.js +8 -0
  128. package/dist/non-numeric-identifier-type.js.map +1 -0
  129. package/dist/non-numeric-identifier-validator.d.ts +41 -0
  130. package/dist/non-numeric-identifier-validator.d.ts.map +1 -0
  131. package/dist/non-numeric-identifier-validator.js +69 -0
  132. package/dist/non-numeric-identifier-validator.js.map +1 -0
  133. package/dist/non-serializable-numeric-identifier-creator.d.ts +10 -0
  134. package/dist/non-serializable-numeric-identifier-creator.d.ts.map +1 -0
  135. package/dist/non-serializable-numeric-identifier-creator.js +8 -0
  136. package/dist/non-serializable-numeric-identifier-creator.js.map +1 -0
  137. package/dist/non-serializable-numeric-identifier-descriptor.d.ts +7 -0
  138. package/dist/non-serializable-numeric-identifier-descriptor.d.ts.map +1 -0
  139. package/dist/non-serializable-numeric-identifier-descriptor.js +2 -0
  140. package/dist/non-serializable-numeric-identifier-descriptor.js.map +1 -0
  141. package/dist/non-serializable-numeric-identifier-type.d.ts +26 -0
  142. package/dist/non-serializable-numeric-identifier-type.d.ts.map +1 -0
  143. package/dist/non-serializable-numeric-identifier-type.js +7 -0
  144. package/dist/non-serializable-numeric-identifier-type.js.map +1 -0
  145. package/dist/non-serializable-numeric-identifier-validator.d.ts +16 -0
  146. package/dist/non-serializable-numeric-identifier-validator.d.ts.map +1 -0
  147. package/dist/non-serializable-numeric-identifier-validator.js +17 -0
  148. package/dist/non-serializable-numeric-identifier-validator.js.map +1 -0
  149. package/dist/numeric-identifier-creator.d.ts +53 -0
  150. package/dist/numeric-identifier-creator.d.ts.map +1 -0
  151. package/dist/numeric-identifier-creator.js +2 -0
  152. package/dist/numeric-identifier-creator.js.map +1 -0
  153. package/dist/numeric-identifier-descriptor.d.ts +22 -0
  154. package/dist/numeric-identifier-descriptor.d.ts.map +1 -0
  155. package/dist/numeric-identifier-descriptor.js +2 -0
  156. package/dist/numeric-identifier-descriptor.js.map +1 -0
  157. package/dist/numeric-identifier-type.d.ts +26 -0
  158. package/dist/numeric-identifier-type.d.ts.map +1 -0
  159. package/dist/numeric-identifier-type.js +7 -0
  160. package/dist/numeric-identifier-type.js.map +1 -0
  161. package/dist/numeric-identifier-validator.d.ts +38 -0
  162. package/dist/numeric-identifier-validator.d.ts.map +1 -0
  163. package/dist/numeric-identifier-validator.js +61 -0
  164. package/dist/numeric-identifier-validator.js.map +1 -0
  165. package/dist/prefix-manager.d.ts +136 -0
  166. package/dist/prefix-manager.d.ts.map +1 -0
  167. package/dist/prefix-manager.js +339 -0
  168. package/dist/prefix-manager.js.map +1 -0
  169. package/dist/prefix-provider.d.ts +27 -0
  170. package/dist/prefix-provider.d.ts.map +1 -0
  171. package/dist/prefix-provider.js +2 -0
  172. package/dist/prefix-provider.js.map +1 -0
  173. package/dist/prefix-type.d.ts +26 -0
  174. package/dist/prefix-type.d.ts.map +1 -0
  175. package/dist/prefix-type.js +18 -0
  176. package/dist/prefix-type.js.map +1 -0
  177. package/dist/prefix-validator.d.ts +70 -0
  178. package/dist/prefix-validator.d.ts.map +1 -0
  179. package/dist/prefix-validator.js +208 -0
  180. package/dist/prefix-validator.js.map +1 -0
  181. package/dist/serializable-numeric-identifier-creator.d.ts +48 -0
  182. package/dist/serializable-numeric-identifier-creator.d.ts.map +1 -0
  183. package/dist/serializable-numeric-identifier-creator.js +93 -0
  184. package/dist/serializable-numeric-identifier-creator.js.map +1 -0
  185. package/dist/serializable-numeric-identifier-descriptor.d.ts +26 -0
  186. package/dist/serializable-numeric-identifier-descriptor.d.ts.map +1 -0
  187. package/dist/serializable-numeric-identifier-descriptor.js +2 -0
  188. package/dist/serializable-numeric-identifier-descriptor.js.map +1 -0
  189. package/dist/serializable-numeric-identifier-type.d.ts +26 -0
  190. package/dist/serializable-numeric-identifier-type.d.ts.map +1 -0
  191. package/dist/serializable-numeric-identifier-type.js +8 -0
  192. package/dist/serializable-numeric-identifier-type.js.map +1 -0
  193. package/dist/serializable-numeric-identifier-validator.d.ts +41 -0
  194. package/dist/serializable-numeric-identifier-validator.d.ts.map +1 -0
  195. package/dist/serializable-numeric-identifier-validator.js +78 -0
  196. package/dist/serializable-numeric-identifier-validator.js.map +1 -0
  197. package/package.json +11 -8
  198. package/src/abstract-identifier-creator.ts +157 -76
  199. package/src/abstract-non-gtin-numeric-identifier-creator.ts +86 -0
  200. package/src/abstract-numeric-identifier-creator.ts +205 -136
  201. package/src/check.ts +2 -2
  202. package/src/content-character-set-creators.ts +9 -0
  203. package/src/gtin-creator.ts +20 -19
  204. package/src/gtin-descriptor.ts +10 -4
  205. package/src/gtin-length.ts +61 -0
  206. package/src/gtin-type.ts +6 -37
  207. package/src/gtin-validator.ts +39 -46
  208. package/src/identifier-creator.ts +6 -6
  209. package/src/{creators.ts → identifier-creators.ts} +45 -31
  210. package/src/identifier-descriptor.ts +3 -3
  211. package/src/{descriptors.ts → identifier-descriptors.ts} +65 -63
  212. package/src/identifier-extension.ts +155 -0
  213. package/src/identifier-validator.ts +94 -11
  214. package/src/{validators.ts → identifier-validators.ts} +56 -41
  215. package/src/index.ts +50 -43
  216. package/src/leader-type.ts +29 -0
  217. package/src/locale/i18n.ts +3 -3
  218. package/src/locale/i18next.d.ts +1 -1
  219. package/src/non-gtin-numeric-identifier-creator.ts +8 -23
  220. package/src/non-gtin-numeric-identifier-descriptor.ts +4 -4
  221. package/src/non-gtin-numeric-identifier-type.ts +14 -3
  222. package/src/non-gtin-numeric-identifier-validator.ts +7 -15
  223. package/src/non-numeric-identifier-creator.ts +21 -16
  224. package/src/non-numeric-identifier-descriptor.ts +4 -4
  225. package/src/non-numeric-identifier-type.ts +14 -3
  226. package/src/non-numeric-identifier-validator.ts +12 -13
  227. package/src/non-serializable-numeric-identifier-creator.ts +12 -0
  228. package/src/non-serializable-numeric-identifier-descriptor.ts +7 -0
  229. package/src/non-serializable-numeric-identifier-type.ts +22 -0
  230. package/src/non-serializable-numeric-identifier-validator.ts +19 -0
  231. package/src/numeric-identifier-creator.ts +9 -8
  232. package/src/numeric-identifier-descriptor.ts +4 -3
  233. package/src/numeric-identifier-type.ts +17 -35
  234. package/src/numeric-identifier-validator.ts +62 -7
  235. package/src/prefix-manager.ts +79 -76
  236. package/src/prefix-provider.ts +1 -1
  237. package/src/prefix-validator.ts +3 -3
  238. package/src/serializable-numeric-identifier-creator.ts +13 -27
  239. package/src/serializable-numeric-identifier-descriptor.ts +4 -4
  240. package/src/serializable-numeric-identifier-type.ts +14 -5
  241. package/src/serializable-numeric-identifier-validator.ts +22 -21
  242. package/test/check.test.ts +1 -1
  243. package/test/creator.test.ts +5 -5
  244. package/test/gtin-creator.ts +10 -3
  245. package/test/gtin-validator.test.ts +10 -12
  246. package/test/identifier-creator.ts +12 -12
  247. package/test/identifier-validator.ts +1 -1
  248. package/test/non-gtin-numeric-identifier-creator.ts +3 -3
  249. package/test/non-gtin-numeric-identifier-validator.ts +8 -3
  250. package/test/non-numeric-identifier-creator.ts +1 -1
  251. package/test/non-numeric-identifier-validator.ts +3 -3
  252. package/test/non-serializable-numeric-identifier-creator.ts +64 -0
  253. package/test/non-serializable-numeric-identifier-validator.ts +6 -0
  254. package/test/numeric-identifier-creator.ts +9 -4
  255. package/test/numeric-identifier-validator.ts +2 -2
  256. package/test/prefix-manager.test.ts +2 -2
  257. package/test/serializable-numeric-identifier-creator.ts +2 -2
  258. package/test/serializable-numeric-identifier-validator.ts +3 -3
  259. package/test/setup.ts +1 -1
  260. package/test/sparse.test.ts +1 -1
  261. package/test/utility.ts +1 -1
  262. package/test/validator.test.ts +16 -15
  263. package/test/variable-measure-rcn.test.ts +24 -24
  264. package/tsconfig-config.json +4 -0
  265. package/tsconfig-src.json +8 -0
  266. package/tsconfig-test.json +9 -0
  267. package/tsconfig.json +12 -1
  268. package/tsup.config.ts +3 -2
  269. package/dist/index.cjs +0 -4813
  270. package/dist/index.cjs.map +0 -1
  271. package/dist/index.d.cts +0 -1949
  272. package/src/abstract-identifier-validator.ts +0 -140
  273. package/src/abstract-numeric-identifier-validator.ts +0 -69
package/dist/index.cjs DELETED
@@ -1,4813 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- AI39_CREATOR: () => AI39_CREATOR,
24
- AI39_VALIDATOR: () => AI39_VALIDATOR,
25
- AI64_VALIDATOR: () => AI64_VALIDATOR,
26
- AI82_CREATOR: () => AI82_CREATOR,
27
- AI82_VALIDATOR: () => AI82_VALIDATOR,
28
- ContentCharacterSets: () => ContentCharacterSets,
29
- GTINCreator: () => GTINCreator,
30
- GTINLevels: () => GTINLevels,
31
- GTINTypes: () => GTINTypes,
32
- GTINValidator: () => GTINValidator,
33
- GTIN_BASE_TYPES: () => GTIN_BASE_TYPES,
34
- IdentifierDescriptors: () => IdentifierDescriptors,
35
- IdentifierTypes: () => IdentifierTypes,
36
- IdentifierValidators: () => IdentifierValidators,
37
- LeaderTypes: () => LeaderTypes,
38
- NonGTINNumericIdentifierCreator: () => NonGTINNumericIdentifierCreator,
39
- NonGTINNumericIdentifierValidator: () => NonGTINNumericIdentifierValidator,
40
- NonNumericIdentifierCreator: () => NonNumericIdentifierCreator,
41
- NonNumericIdentifierValidator: () => NonNumericIdentifierValidator,
42
- PrefixManager: () => PrefixManager,
43
- PrefixTypes: () => PrefixTypes,
44
- PrefixValidator: () => PrefixValidator,
45
- SerializableNumericIdentifierCreator: () => SerializableNumericIdentifierCreator,
46
- SerializableNumericIdentifierValidator: () => SerializableNumericIdentifierValidator,
47
- checkCharacterPair: () => checkCharacterPair,
48
- checkDigit: () => checkDigit,
49
- checkDigitSum: () => checkDigitSum,
50
- gs1NS: () => gs1NS,
51
- gs1Resources: () => gs1Resources,
52
- hasValidCheckCharacterPair: () => hasValidCheckCharacterPair,
53
- hasValidCheckDigit: () => hasValidCheckDigit,
54
- i18nGS1Init: () => i18nGS1Init,
55
- i18nextGS1: () => i18nextGS1,
56
- isGTINCreator: () => isGTINCreator,
57
- isGTINDescriptor: () => isGTINDescriptor,
58
- isGTINDescriptors: () => isGTINDescriptors,
59
- isGTINValidator: () => isGTINValidator,
60
- isGTINValidators: () => isGTINValidators,
61
- isNonGTINNumericIdentifierCreator: () => isNonGTINNumericIdentifierCreator,
62
- isNonGTINNumericIdentifierDescriptor: () => isNonGTINNumericIdentifierDescriptor,
63
- isNonGTINNumericIdentifierValidator: () => isNonGTINNumericIdentifierValidator,
64
- isNonNumericIdentifierCreator: () => isNonNumericIdentifierCreator,
65
- isNonNumericIdentifierDescriptor: () => isNonNumericIdentifierDescriptor,
66
- isNonNumericIdentifierValidator: () => isNonNumericIdentifierValidator,
67
- isNumericIdentifierCreator: () => isNumericIdentifierCreator,
68
- isNumericIdentifierDescriptor: () => isNumericIdentifierDescriptor,
69
- isNumericIdentifierValidator: () => isNumericIdentifierValidator,
70
- isSerializableNumericIdentifierCreator: () => isSerializableNumericIdentifierCreator,
71
- isSerializableNumericIdentifierDescriptor: () => isSerializableNumericIdentifierDescriptor,
72
- isSerializableNumericIdentifierValidator: () => isSerializableNumericIdentifierValidator,
73
- isValidPriceOrWeightCheckDigit: () => isValidPriceOrWeightCheckDigit,
74
- priceOrWeightCheckDigit: () => priceOrWeightCheckDigit
75
- });
76
- module.exports = __toCommonJS(index_exports);
77
-
78
- // src/locale/i18n.ts
79
- var import_core = require("@aidc-toolkit/core");
80
- var import_utility = require("@aidc-toolkit/utility");
81
-
82
- // node_modules/i18next/dist/esm/i18next.js
83
- var isString = (obj) => typeof obj === "string";
84
- var defer = () => {
85
- let res;
86
- let rej;
87
- const promise = new Promise((resolve, reject) => {
88
- res = resolve;
89
- rej = reject;
90
- });
91
- promise.resolve = res;
92
- promise.reject = rej;
93
- return promise;
94
- };
95
- var makeString = (object) => {
96
- if (object == null) return "";
97
- return "" + object;
98
- };
99
- var copy = (a, s, t2) => {
100
- a.forEach((m) => {
101
- if (s[m]) t2[m] = s[m];
102
- });
103
- };
104
- var lastOfPathSeparatorRegExp = /###/g;
105
- var cleanKey = (key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key;
106
- var canNotTraverseDeeper = (object) => !object || isString(object);
107
- var getLastOfPath = (object, path, Empty) => {
108
- const stack = !isString(path) ? path : path.split(".");
109
- let stackIndex = 0;
110
- while (stackIndex < stack.length - 1) {
111
- if (canNotTraverseDeeper(object)) return {};
112
- const key = cleanKey(stack[stackIndex]);
113
- if (!object[key] && Empty) object[key] = new Empty();
114
- if (Object.prototype.hasOwnProperty.call(object, key)) {
115
- object = object[key];
116
- } else {
117
- object = {};
118
- }
119
- ++stackIndex;
120
- }
121
- if (canNotTraverseDeeper(object)) return {};
122
- return {
123
- obj: object,
124
- k: cleanKey(stack[stackIndex])
125
- };
126
- };
127
- var setPath = (object, path, newValue) => {
128
- const {
129
- obj,
130
- k
131
- } = getLastOfPath(object, path, Object);
132
- if (obj !== void 0 || path.length === 1) {
133
- obj[k] = newValue;
134
- return;
135
- }
136
- let e = path[path.length - 1];
137
- let p = path.slice(0, path.length - 1);
138
- let last = getLastOfPath(object, p, Object);
139
- while (last.obj === void 0 && p.length) {
140
- e = `${p[p.length - 1]}.${e}`;
141
- p = p.slice(0, p.length - 1);
142
- last = getLastOfPath(object, p, Object);
143
- if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") {
144
- last.obj = void 0;
145
- }
146
- }
147
- last.obj[`${last.k}.${e}`] = newValue;
148
- };
149
- var pushPath = (object, path, newValue, concat) => {
150
- const {
151
- obj,
152
- k
153
- } = getLastOfPath(object, path, Object);
154
- obj[k] = obj[k] || [];
155
- obj[k].push(newValue);
156
- };
157
- var getPath = (object, path) => {
158
- const {
159
- obj,
160
- k
161
- } = getLastOfPath(object, path);
162
- if (!obj) return void 0;
163
- if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0;
164
- return obj[k];
165
- };
166
- var getPathWithDefaults = (data, defaultData, key) => {
167
- const value = getPath(data, key);
168
- if (value !== void 0) {
169
- return value;
170
- }
171
- return getPath(defaultData, key);
172
- };
173
- var deepExtend = (target, source, overwrite) => {
174
- for (const prop in source) {
175
- if (prop !== "__proto__" && prop !== "constructor") {
176
- if (prop in target) {
177
- if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {
178
- if (overwrite) target[prop] = source[prop];
179
- } else {
180
- deepExtend(target[prop], source[prop], overwrite);
181
- }
182
- } else {
183
- target[prop] = source[prop];
184
- }
185
- }
186
- }
187
- return target;
188
- };
189
- var regexEscape = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
190
- var _entityMap = {
191
- "&": "&amp;",
192
- "<": "&lt;",
193
- ">": "&gt;",
194
- '"': "&quot;",
195
- "'": "&#39;",
196
- "/": "&#x2F;"
197
- };
198
- var escape = (data) => {
199
- if (isString(data)) {
200
- return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
201
- }
202
- return data;
203
- };
204
- var RegExpCache = class {
205
- constructor(capacity) {
206
- this.capacity = capacity;
207
- this.regExpMap = /* @__PURE__ */ new Map();
208
- this.regExpQueue = [];
209
- }
210
- getRegExp(pattern) {
211
- const regExpFromCache = this.regExpMap.get(pattern);
212
- if (regExpFromCache !== void 0) {
213
- return regExpFromCache;
214
- }
215
- const regExpNew = new RegExp(pattern);
216
- if (this.regExpQueue.length === this.capacity) {
217
- this.regExpMap.delete(this.regExpQueue.shift());
218
- }
219
- this.regExpMap.set(pattern, regExpNew);
220
- this.regExpQueue.push(pattern);
221
- return regExpNew;
222
- }
223
- };
224
- var chars = [" ", ",", "?", "!", ";"];
225
- var looksLikeObjectPathRegExpCache = new RegExpCache(20);
226
- var looksLikeObjectPath = (key, nsSeparator, keySeparator) => {
227
- nsSeparator = nsSeparator || "";
228
- keySeparator = keySeparator || "";
229
- const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
230
- if (possibleChars.length === 0) return true;
231
- const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
232
- let matched = !r.test(key);
233
- if (!matched) {
234
- const ki = key.indexOf(keySeparator);
235
- if (ki > 0 && !r.test(key.substring(0, ki))) {
236
- matched = true;
237
- }
238
- }
239
- return matched;
240
- };
241
- var deepFind = (obj, path, keySeparator = ".") => {
242
- if (!obj) return void 0;
243
- if (obj[path]) {
244
- if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0;
245
- return obj[path];
246
- }
247
- const tokens = path.split(keySeparator);
248
- let current = obj;
249
- for (let i = 0; i < tokens.length; ) {
250
- if (!current || typeof current !== "object") {
251
- return void 0;
252
- }
253
- let next;
254
- let nextPath = "";
255
- for (let j = i; j < tokens.length; ++j) {
256
- if (j !== i) {
257
- nextPath += keySeparator;
258
- }
259
- nextPath += tokens[j];
260
- next = current[nextPath];
261
- if (next !== void 0) {
262
- if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) {
263
- continue;
264
- }
265
- i += j - i + 1;
266
- break;
267
- }
268
- }
269
- current = next;
270
- }
271
- return current;
272
- };
273
- var getCleanedCode = (code) => code?.replace("_", "-");
274
- var consoleLogger = {
275
- type: "logger",
276
- log(args) {
277
- this.output("log", args);
278
- },
279
- warn(args) {
280
- this.output("warn", args);
281
- },
282
- error(args) {
283
- this.output("error", args);
284
- },
285
- output(type, args) {
286
- console?.[type]?.apply?.(console, args);
287
- }
288
- };
289
- var Logger = class _Logger {
290
- constructor(concreteLogger, options = {}) {
291
- this.init(concreteLogger, options);
292
- }
293
- init(concreteLogger, options = {}) {
294
- this.prefix = options.prefix || "i18next:";
295
- this.logger = concreteLogger || consoleLogger;
296
- this.options = options;
297
- this.debug = options.debug;
298
- }
299
- log(...args) {
300
- return this.forward(args, "log", "", true);
301
- }
302
- warn(...args) {
303
- return this.forward(args, "warn", "", true);
304
- }
305
- error(...args) {
306
- return this.forward(args, "error", "");
307
- }
308
- deprecate(...args) {
309
- return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
310
- }
311
- forward(args, lvl, prefix, debugOnly) {
312
- if (debugOnly && !this.debug) return null;
313
- if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;
314
- return this.logger[lvl](args);
315
- }
316
- create(moduleName) {
317
- return new _Logger(this.logger, {
318
- ...{
319
- prefix: `${this.prefix}:${moduleName}:`
320
- },
321
- ...this.options
322
- });
323
- }
324
- clone(options) {
325
- options = options || this.options;
326
- options.prefix = options.prefix || this.prefix;
327
- return new _Logger(this.logger, options);
328
- }
329
- };
330
- var baseLogger = new Logger();
331
- var EventEmitter = class {
332
- constructor() {
333
- this.observers = {};
334
- }
335
- on(events, listener) {
336
- events.split(" ").forEach((event) => {
337
- if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map();
338
- const numListeners = this.observers[event].get(listener) || 0;
339
- this.observers[event].set(listener, numListeners + 1);
340
- });
341
- return this;
342
- }
343
- off(event, listener) {
344
- if (!this.observers[event]) return;
345
- if (!listener) {
346
- delete this.observers[event];
347
- return;
348
- }
349
- this.observers[event].delete(listener);
350
- }
351
- emit(event, ...args) {
352
- if (this.observers[event]) {
353
- const cloned = Array.from(this.observers[event].entries());
354
- cloned.forEach(([observer, numTimesAdded]) => {
355
- for (let i = 0; i < numTimesAdded; i++) {
356
- observer(...args);
357
- }
358
- });
359
- }
360
- if (this.observers["*"]) {
361
- const cloned = Array.from(this.observers["*"].entries());
362
- cloned.forEach(([observer, numTimesAdded]) => {
363
- for (let i = 0; i < numTimesAdded; i++) {
364
- observer.apply(observer, [event, ...args]);
365
- }
366
- });
367
- }
368
- }
369
- };
370
- var ResourceStore = class extends EventEmitter {
371
- constructor(data, options = {
372
- ns: ["translation"],
373
- defaultNS: "translation"
374
- }) {
375
- super();
376
- this.data = data || {};
377
- this.options = options;
378
- if (this.options.keySeparator === void 0) {
379
- this.options.keySeparator = ".";
380
- }
381
- if (this.options.ignoreJSONStructure === void 0) {
382
- this.options.ignoreJSONStructure = true;
383
- }
384
- }
385
- addNamespaces(ns) {
386
- if (this.options.ns.indexOf(ns) < 0) {
387
- this.options.ns.push(ns);
388
- }
389
- }
390
- removeNamespaces(ns) {
391
- const index = this.options.ns.indexOf(ns);
392
- if (index > -1) {
393
- this.options.ns.splice(index, 1);
394
- }
395
- }
396
- getResource(lng, ns, key, options = {}) {
397
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
398
- const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
399
- let path;
400
- if (lng.indexOf(".") > -1) {
401
- path = lng.split(".");
402
- } else {
403
- path = [lng, ns];
404
- if (key) {
405
- if (Array.isArray(key)) {
406
- path.push(...key);
407
- } else if (isString(key) && keySeparator) {
408
- path.push(...key.split(keySeparator));
409
- } else {
410
- path.push(key);
411
- }
412
- }
413
- }
414
- const result = getPath(this.data, path);
415
- if (!result && !ns && !key && lng.indexOf(".") > -1) {
416
- lng = path[0];
417
- ns = path[1];
418
- key = path.slice(2).join(".");
419
- }
420
- if (result || !ignoreJSONStructure || !isString(key)) return result;
421
- return deepFind(this.data?.[lng]?.[ns], key, keySeparator);
422
- }
423
- addResource(lng, ns, key, value, options = {
424
- silent: false
425
- }) {
426
- const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
427
- let path = [lng, ns];
428
- if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
429
- if (lng.indexOf(".") > -1) {
430
- path = lng.split(".");
431
- value = ns;
432
- ns = path[1];
433
- }
434
- this.addNamespaces(ns);
435
- setPath(this.data, path, value);
436
- if (!options.silent) this.emit("added", lng, ns, key, value);
437
- }
438
- addResources(lng, ns, resources, options = {
439
- silent: false
440
- }) {
441
- for (const m in resources) {
442
- if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {
443
- silent: true
444
- });
445
- }
446
- if (!options.silent) this.emit("added", lng, ns, resources);
447
- }
448
- addResourceBundle(lng, ns, resources, deep, overwrite, options = {
449
- silent: false,
450
- skipCopy: false
451
- }) {
452
- let path = [lng, ns];
453
- if (lng.indexOf(".") > -1) {
454
- path = lng.split(".");
455
- deep = resources;
456
- resources = ns;
457
- ns = path[1];
458
- }
459
- this.addNamespaces(ns);
460
- let pack = getPath(this.data, path) || {};
461
- if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));
462
- if (deep) {
463
- deepExtend(pack, resources, overwrite);
464
- } else {
465
- pack = {
466
- ...pack,
467
- ...resources
468
- };
469
- }
470
- setPath(this.data, path, pack);
471
- if (!options.silent) this.emit("added", lng, ns, resources);
472
- }
473
- removeResourceBundle(lng, ns) {
474
- if (this.hasResourceBundle(lng, ns)) {
475
- delete this.data[lng][ns];
476
- }
477
- this.removeNamespaces(ns);
478
- this.emit("removed", lng, ns);
479
- }
480
- hasResourceBundle(lng, ns) {
481
- return this.getResource(lng, ns) !== void 0;
482
- }
483
- getResourceBundle(lng, ns) {
484
- if (!ns) ns = this.options.defaultNS;
485
- return this.getResource(lng, ns);
486
- }
487
- getDataByLanguage(lng) {
488
- return this.data[lng];
489
- }
490
- hasLanguageSomeTranslations(lng) {
491
- const data = this.getDataByLanguage(lng);
492
- const n = data && Object.keys(data) || [];
493
- return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
494
- }
495
- toJSON() {
496
- return this.data;
497
- }
498
- };
499
- var postProcessor = {
500
- processors: {},
501
- addPostProcessor(module2) {
502
- this.processors[module2.name] = module2;
503
- },
504
- handle(processors, value, key, options, translator) {
505
- processors.forEach((processor) => {
506
- value = this.processors[processor]?.process(value, key, options, translator) ?? value;
507
- });
508
- return value;
509
- }
510
- };
511
- var PATH_KEY = /* @__PURE__ */ Symbol("i18next/PATH_KEY");
512
- function createProxy() {
513
- const state = [];
514
- const handler = /* @__PURE__ */ Object.create(null);
515
- let proxy;
516
- handler.get = (target, key) => {
517
- proxy?.revoke?.();
518
- if (key === PATH_KEY) return state;
519
- state.push(key);
520
- proxy = Proxy.revocable(target, handler);
521
- return proxy.proxy;
522
- };
523
- return Proxy.revocable(/* @__PURE__ */ Object.create(null), handler).proxy;
524
- }
525
- function keysFromSelector(selector, opts) {
526
- const {
527
- [PATH_KEY]: path
528
- } = selector(createProxy());
529
- return path.join(opts?.keySeparator ?? ".");
530
- }
531
- var checkedLoadedFor = {};
532
- var shouldHandleAsObject = (res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number";
533
- var Translator = class _Translator extends EventEmitter {
534
- constructor(services, options = {}) {
535
- super();
536
- copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
537
- this.options = options;
538
- if (this.options.keySeparator === void 0) {
539
- this.options.keySeparator = ".";
540
- }
541
- this.logger = baseLogger.create("translator");
542
- }
543
- changeLanguage(lng) {
544
- if (lng) this.language = lng;
545
- }
546
- exists(key, o = {
547
- interpolation: {}
548
- }) {
549
- const opt = {
550
- ...o
551
- };
552
- if (key == null) return false;
553
- const resolved = this.resolve(key, opt);
554
- if (resolved?.res === void 0) return false;
555
- const isObject = shouldHandleAsObject(resolved.res);
556
- if (opt.returnObjects === false && isObject) {
557
- return false;
558
- }
559
- return true;
560
- }
561
- extractFromKey(key, opt) {
562
- let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
563
- if (nsSeparator === void 0) nsSeparator = ":";
564
- const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
565
- let namespaces = opt.ns || this.options.defaultNS || [];
566
- const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
567
- const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
568
- if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
569
- const m = key.match(this.interpolator.nestingRegexp);
570
- if (m && m.length > 0) {
571
- return {
572
- key,
573
- namespaces: isString(namespaces) ? [namespaces] : namespaces
574
- };
575
- }
576
- const parts = key.split(nsSeparator);
577
- if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
578
- key = parts.join(keySeparator);
579
- }
580
- return {
581
- key,
582
- namespaces: isString(namespaces) ? [namespaces] : namespaces
583
- };
584
- }
585
- translate(keys, o, lastKey) {
586
- let opt = typeof o === "object" ? {
587
- ...o
588
- } : o;
589
- if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) {
590
- opt = this.options.overloadTranslationOptionHandler(arguments);
591
- }
592
- if (typeof opt === "object") opt = {
593
- ...opt
594
- };
595
- if (!opt) opt = {};
596
- if (keys == null) return "";
597
- if (typeof keys === "function") keys = keysFromSelector(keys, {
598
- ...this.options,
599
- ...opt
600
- });
601
- if (!Array.isArray(keys)) keys = [String(keys)];
602
- const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails;
603
- const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator;
604
- const {
605
- key,
606
- namespaces
607
- } = this.extractFromKey(keys[keys.length - 1], opt);
608
- const namespace = namespaces[namespaces.length - 1];
609
- let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator;
610
- if (nsSeparator === void 0) nsSeparator = ":";
611
- const lng = opt.lng || this.language;
612
- const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
613
- if (lng?.toLowerCase() === "cimode") {
614
- if (appendNamespaceToCIMode) {
615
- if (returnDetails) {
616
- return {
617
- res: `${namespace}${nsSeparator}${key}`,
618
- usedKey: key,
619
- exactUsedKey: key,
620
- usedLng: lng,
621
- usedNS: namespace,
622
- usedParams: this.getUsedParamsDetails(opt)
623
- };
624
- }
625
- return `${namespace}${nsSeparator}${key}`;
626
- }
627
- if (returnDetails) {
628
- return {
629
- res: key,
630
- usedKey: key,
631
- exactUsedKey: key,
632
- usedLng: lng,
633
- usedNS: namespace,
634
- usedParams: this.getUsedParamsDetails(opt)
635
- };
636
- }
637
- return key;
638
- }
639
- const resolved = this.resolve(keys, opt);
640
- let res = resolved?.res;
641
- const resUsedKey = resolved?.usedKey || key;
642
- const resExactUsedKey = resolved?.exactUsedKey || key;
643
- const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
644
- const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays;
645
- const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
646
- const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
647
- const hasDefaultValue = _Translator.hasDefaultValue(opt);
648
- const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : "";
649
- const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {
650
- ordinal: false
651
- }) : "";
652
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
653
- const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;
654
- let resForObjHndl = res;
655
- if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {
656
- resForObjHndl = defaultValue;
657
- }
658
- const handleAsObject = shouldHandleAsObject(resForObjHndl);
659
- const resType = Object.prototype.toString.apply(resForObjHndl);
660
- if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {
661
- if (!opt.returnObjects && !this.options.returnObjects) {
662
- if (!this.options.returnedObjectHandler) {
663
- this.logger.warn("accessing an object - but returnObjects options is not enabled!");
664
- }
665
- const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {
666
- ...opt,
667
- ns: namespaces
668
- }) : `key '${key} (${this.language})' returned an object instead of string.`;
669
- if (returnDetails) {
670
- resolved.res = r;
671
- resolved.usedParams = this.getUsedParamsDetails(opt);
672
- return resolved;
673
- }
674
- return r;
675
- }
676
- if (keySeparator) {
677
- const resTypeIsArray = Array.isArray(resForObjHndl);
678
- const copy2 = resTypeIsArray ? [] : {};
679
- const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
680
- for (const m in resForObjHndl) {
681
- if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {
682
- const deepKey = `${newKeyToUse}${keySeparator}${m}`;
683
- if (hasDefaultValue && !res) {
684
- copy2[m] = this.translate(deepKey, {
685
- ...opt,
686
- defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : void 0,
687
- ...{
688
- joinArrays: false,
689
- ns: namespaces
690
- }
691
- });
692
- } else {
693
- copy2[m] = this.translate(deepKey, {
694
- ...opt,
695
- ...{
696
- joinArrays: false,
697
- ns: namespaces
698
- }
699
- });
700
- }
701
- if (copy2[m] === deepKey) copy2[m] = resForObjHndl[m];
702
- }
703
- }
704
- res = copy2;
705
- }
706
- } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {
707
- res = res.join(joinArrays);
708
- if (res) res = this.extendTranslation(res, keys, opt, lastKey);
709
- } else {
710
- let usedDefault = false;
711
- let usedKey = false;
712
- if (!this.isValidLookup(res) && hasDefaultValue) {
713
- usedDefault = true;
714
- res = defaultValue;
715
- }
716
- if (!this.isValidLookup(res)) {
717
- usedKey = true;
718
- res = key;
719
- }
720
- const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
721
- const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
722
- const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
723
- if (usedKey || usedDefault || updateMissing) {
724
- this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
725
- if (keySeparator) {
726
- const fk = this.resolve(key, {
727
- ...opt,
728
- keySeparator: false
729
- });
730
- 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.");
731
- }
732
- let lngs = [];
733
- const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);
734
- if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
735
- for (let i = 0; i < fallbackLngs.length; i++) {
736
- lngs.push(fallbackLngs[i]);
737
- }
738
- } else if (this.options.saveMissingTo === "all") {
739
- lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);
740
- } else {
741
- lngs.push(opt.lng || this.language);
742
- }
743
- const send = (l, k, specificDefaultValue) => {
744
- const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
745
- if (this.options.missingKeyHandler) {
746
- this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);
747
- } else if (this.backendConnector?.saveMissing) {
748
- this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);
749
- }
750
- this.emit("missingKey", l, namespace, k, res);
751
- };
752
- if (this.options.saveMissing) {
753
- if (this.options.saveMissingPlurals && needsPluralHandling) {
754
- lngs.forEach((language) => {
755
- const suffixes = this.pluralResolver.getSuffixes(language, opt);
756
- if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {
757
- suffixes.push(`${this.options.pluralSeparator}zero`);
758
- }
759
- suffixes.forEach((suffix) => {
760
- send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);
761
- });
762
- });
763
- } else {
764
- send(lngs, key, defaultValue);
765
- }
766
- }
767
- }
768
- res = this.extendTranslation(res, keys, opt, resolved, lastKey);
769
- if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {
770
- res = `${namespace}${nsSeparator}${key}`;
771
- }
772
- if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
773
- res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt);
774
- }
775
- }
776
- if (returnDetails) {
777
- resolved.res = res;
778
- resolved.usedParams = this.getUsedParamsDetails(opt);
779
- return resolved;
780
- }
781
- return res;
782
- }
783
- extendTranslation(res, key, opt, resolved, lastKey) {
784
- if (this.i18nFormat?.parse) {
785
- res = this.i18nFormat.parse(res, {
786
- ...this.options.interpolation.defaultVariables,
787
- ...opt
788
- }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {
789
- resolved
790
- });
791
- } else if (!opt.skipInterpolation) {
792
- if (opt.interpolation) this.interpolator.init({
793
- ...opt,
794
- ...{
795
- interpolation: {
796
- ...this.options.interpolation,
797
- ...opt.interpolation
798
- }
799
- }
800
- });
801
- const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
802
- let nestBef;
803
- if (skipOnVariables) {
804
- const nb = res.match(this.interpolator.nestingRegexp);
805
- nestBef = nb && nb.length;
806
- }
807
- let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;
808
- if (this.options.interpolation.defaultVariables) data = {
809
- ...this.options.interpolation.defaultVariables,
810
- ...data
811
- };
812
- res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);
813
- if (skipOnVariables) {
814
- const na = res.match(this.interpolator.nestingRegexp);
815
- const nestAft = na && na.length;
816
- if (nestBef < nestAft) opt.nest = false;
817
- }
818
- if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;
819
- if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {
820
- if (lastKey?.[0] === args[0] && !opt.context) {
821
- this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
822
- return null;
823
- }
824
- return this.translate(...args, key);
825
- }, opt);
826
- if (opt.interpolation) this.interpolator.reset();
827
- }
828
- const postProcess = opt.postProcess || this.options.postProcess;
829
- const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;
830
- if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {
831
- res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
832
- i18nResolved: {
833
- ...resolved,
834
- usedParams: this.getUsedParamsDetails(opt)
835
- },
836
- ...opt
837
- } : opt, this);
838
- }
839
- return res;
840
- }
841
- resolve(keys, opt = {}) {
842
- let found;
843
- let usedKey;
844
- let exactUsedKey;
845
- let usedLng;
846
- let usedNS;
847
- if (isString(keys)) keys = [keys];
848
- keys.forEach((k) => {
849
- if (this.isValidLookup(found)) return;
850
- const extracted = this.extractFromKey(k, opt);
851
- const key = extracted.key;
852
- usedKey = key;
853
- let namespaces = extracted.namespaces;
854
- if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);
855
- const needsPluralHandling = opt.count !== void 0 && !isString(opt.count);
856
- const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;
857
- const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== "";
858
- const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);
859
- namespaces.forEach((ns) => {
860
- if (this.isValidLookup(found)) return;
861
- usedNS = ns;
862
- if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {
863
- checkedLoadedFor[`${codes[0]}-${ns}`] = true;
864
- 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!!!");
865
- }
866
- codes.forEach((code) => {
867
- if (this.isValidLookup(found)) return;
868
- usedLng = code;
869
- const finalKeys = [key];
870
- if (this.i18nFormat?.addLookupKeys) {
871
- this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);
872
- } else {
873
- let pluralSuffix;
874
- if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);
875
- const zeroSuffix = `${this.options.pluralSeparator}zero`;
876
- const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
877
- if (needsPluralHandling) {
878
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
879
- finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
880
- }
881
- finalKeys.push(key + pluralSuffix);
882
- if (needsZeroSuffixLookup) {
883
- finalKeys.push(key + zeroSuffix);
884
- }
885
- }
886
- if (needsContextHandling) {
887
- const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`;
888
- finalKeys.push(contextKey);
889
- if (needsPluralHandling) {
890
- if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
891
- finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
892
- }
893
- finalKeys.push(contextKey + pluralSuffix);
894
- if (needsZeroSuffixLookup) {
895
- finalKeys.push(contextKey + zeroSuffix);
896
- }
897
- }
898
- }
899
- }
900
- let possibleKey;
901
- while (possibleKey = finalKeys.pop()) {
902
- if (!this.isValidLookup(found)) {
903
- exactUsedKey = possibleKey;
904
- found = this.getResource(code, ns, possibleKey, opt);
905
- }
906
- }
907
- });
908
- });
909
- });
910
- return {
911
- res: found,
912
- usedKey,
913
- exactUsedKey,
914
- usedLng,
915
- usedNS
916
- };
917
- }
918
- isValidLookup(res) {
919
- return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
920
- }
921
- getResource(code, ns, key, options = {}) {
922
- if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);
923
- return this.resourceStore.getResource(code, ns, key, options);
924
- }
925
- getUsedParamsDetails(options = {}) {
926
- const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"];
927
- const useOptionsReplaceForData = options.replace && !isString(options.replace);
928
- let data = useOptionsReplaceForData ? options.replace : options;
929
- if (useOptionsReplaceForData && typeof options.count !== "undefined") {
930
- data.count = options.count;
931
- }
932
- if (this.options.interpolation.defaultVariables) {
933
- data = {
934
- ...this.options.interpolation.defaultVariables,
935
- ...data
936
- };
937
- }
938
- if (!useOptionsReplaceForData) {
939
- data = {
940
- ...data
941
- };
942
- for (const key of optionsKeys) {
943
- delete data[key];
944
- }
945
- }
946
- return data;
947
- }
948
- static hasDefaultValue(options) {
949
- const prefix = "defaultValue";
950
- for (const option in options) {
951
- if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
952
- return true;
953
- }
954
- }
955
- return false;
956
- }
957
- };
958
- var LanguageUtil = class {
959
- constructor(options) {
960
- this.options = options;
961
- this.supportedLngs = this.options.supportedLngs || false;
962
- this.logger = baseLogger.create("languageUtils");
963
- }
964
- getScriptPartFromCode(code) {
965
- code = getCleanedCode(code);
966
- if (!code || code.indexOf("-") < 0) return null;
967
- const p = code.split("-");
968
- if (p.length === 2) return null;
969
- p.pop();
970
- if (p[p.length - 1].toLowerCase() === "x") return null;
971
- return this.formatLanguageCode(p.join("-"));
972
- }
973
- getLanguagePartFromCode(code) {
974
- code = getCleanedCode(code);
975
- if (!code || code.indexOf("-") < 0) return code;
976
- const p = code.split("-");
977
- return this.formatLanguageCode(p[0]);
978
- }
979
- formatLanguageCode(code) {
980
- if (isString(code) && code.indexOf("-") > -1) {
981
- let formattedCode;
982
- try {
983
- formattedCode = Intl.getCanonicalLocales(code)[0];
984
- } catch (e) {
985
- }
986
- if (formattedCode && this.options.lowerCaseLng) {
987
- formattedCode = formattedCode.toLowerCase();
988
- }
989
- if (formattedCode) return formattedCode;
990
- if (this.options.lowerCaseLng) {
991
- return code.toLowerCase();
992
- }
993
- return code;
994
- }
995
- return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
996
- }
997
- isSupportedCode(code) {
998
- if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
999
- code = this.getLanguagePartFromCode(code);
1000
- }
1001
- return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
1002
- }
1003
- getBestMatchFromCodes(codes) {
1004
- if (!codes) return null;
1005
- let found;
1006
- codes.forEach((code) => {
1007
- if (found) return;
1008
- const cleanedLng = this.formatLanguageCode(code);
1009
- if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;
1010
- });
1011
- if (!found && this.options.supportedLngs) {
1012
- codes.forEach((code) => {
1013
- if (found) return;
1014
- const lngScOnly = this.getScriptPartFromCode(code);
1015
- if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;
1016
- const lngOnly = this.getLanguagePartFromCode(code);
1017
- if (this.isSupportedCode(lngOnly)) return found = lngOnly;
1018
- found = this.options.supportedLngs.find((supportedLng) => {
1019
- if (supportedLng === lngOnly) return supportedLng;
1020
- if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return;
1021
- if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng;
1022
- if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;
1023
- });
1024
- });
1025
- }
1026
- if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];
1027
- return found;
1028
- }
1029
- getFallbackCodes(fallbacks, code) {
1030
- if (!fallbacks) return [];
1031
- if (typeof fallbacks === "function") fallbacks = fallbacks(code);
1032
- if (isString(fallbacks)) fallbacks = [fallbacks];
1033
- if (Array.isArray(fallbacks)) return fallbacks;
1034
- if (!code) return fallbacks.default || [];
1035
- let found = fallbacks[code];
1036
- if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
1037
- if (!found) found = fallbacks[this.formatLanguageCode(code)];
1038
- if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
1039
- if (!found) found = fallbacks.default;
1040
- return found || [];
1041
- }
1042
- toResolveHierarchy(code, fallbackCode) {
1043
- const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);
1044
- const codes = [];
1045
- const addCode = (c) => {
1046
- if (!c) return;
1047
- if (this.isSupportedCode(c)) {
1048
- codes.push(c);
1049
- } else {
1050
- this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
1051
- }
1052
- };
1053
- if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
1054
- if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code));
1055
- if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code));
1056
- if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code));
1057
- } else if (isString(code)) {
1058
- addCode(this.formatLanguageCode(code));
1059
- }
1060
- fallbackCodes.forEach((fc) => {
1061
- if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));
1062
- });
1063
- return codes;
1064
- }
1065
- };
1066
- var suffixesOrder = {
1067
- zero: 0,
1068
- one: 1,
1069
- two: 2,
1070
- few: 3,
1071
- many: 4,
1072
- other: 5
1073
- };
1074
- var dummyRule = {
1075
- select: (count) => count === 1 ? "one" : "other",
1076
- resolvedOptions: () => ({
1077
- pluralCategories: ["one", "other"]
1078
- })
1079
- };
1080
- var PluralResolver = class {
1081
- constructor(languageUtils, options = {}) {
1082
- this.languageUtils = languageUtils;
1083
- this.options = options;
1084
- this.logger = baseLogger.create("pluralResolver");
1085
- this.pluralRulesCache = {};
1086
- }
1087
- addRule(lng, obj) {
1088
- this.rules[lng] = obj;
1089
- }
1090
- clearCache() {
1091
- this.pluralRulesCache = {};
1092
- }
1093
- getRule(code, options = {}) {
1094
- const cleanedCode = getCleanedCode(code === "dev" ? "en" : code);
1095
- const type = options.ordinal ? "ordinal" : "cardinal";
1096
- const cacheKey = JSON.stringify({
1097
- cleanedCode,
1098
- type
1099
- });
1100
- if (cacheKey in this.pluralRulesCache) {
1101
- return this.pluralRulesCache[cacheKey];
1102
- }
1103
- let rule;
1104
- try {
1105
- rule = new Intl.PluralRules(cleanedCode, {
1106
- type
1107
- });
1108
- } catch (err) {
1109
- if (!Intl) {
1110
- this.logger.error("No Intl support, please use an Intl polyfill!");
1111
- return dummyRule;
1112
- }
1113
- if (!code.match(/-|_/)) return dummyRule;
1114
- const lngPart = this.languageUtils.getLanguagePartFromCode(code);
1115
- rule = this.getRule(lngPart, options);
1116
- }
1117
- this.pluralRulesCache[cacheKey] = rule;
1118
- return rule;
1119
- }
1120
- needsPlural(code, options = {}) {
1121
- let rule = this.getRule(code, options);
1122
- if (!rule) rule = this.getRule("dev", options);
1123
- return rule?.resolvedOptions().pluralCategories.length > 1;
1124
- }
1125
- getPluralFormsOfKey(code, key, options = {}) {
1126
- return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
1127
- }
1128
- getSuffixes(code, options = {}) {
1129
- let rule = this.getRule(code, options);
1130
- if (!rule) rule = this.getRule("dev", options);
1131
- if (!rule) return [];
1132
- return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
1133
- }
1134
- getSuffix(code, count, options = {}) {
1135
- const rule = this.getRule(code, options);
1136
- if (rule) {
1137
- return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
1138
- }
1139
- this.logger.warn(`no plural rule found for: ${code}`);
1140
- return this.getSuffix("dev", count, options);
1141
- }
1142
- };
1143
- var deepFindWithDefaults = (data, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => {
1144
- let path = getPathWithDefaults(data, defaultData, key);
1145
- if (!path && ignoreJSONStructure && isString(key)) {
1146
- path = deepFind(data, key, keySeparator);
1147
- if (path === void 0) path = deepFind(defaultData, key, keySeparator);
1148
- }
1149
- return path;
1150
- };
1151
- var regexSafe = (val) => val.replace(/\$/g, "$$$$");
1152
- var Interpolator = class {
1153
- constructor(options = {}) {
1154
- this.logger = baseLogger.create("interpolator");
1155
- this.options = options;
1156
- this.format = options?.interpolation?.format || ((value) => value);
1157
- this.init(options);
1158
- }
1159
- init(options = {}) {
1160
- if (!options.interpolation) options.interpolation = {
1161
- escapeValue: true
1162
- };
1163
- const {
1164
- escape: escape$1,
1165
- escapeValue,
1166
- useRawValueToEscape,
1167
- prefix,
1168
- prefixEscaped,
1169
- suffix,
1170
- suffixEscaped,
1171
- formatSeparator,
1172
- unescapeSuffix,
1173
- unescapePrefix,
1174
- nestingPrefix,
1175
- nestingPrefixEscaped,
1176
- nestingSuffix,
1177
- nestingSuffixEscaped,
1178
- nestingOptionsSeparator,
1179
- maxReplaces,
1180
- alwaysFormat
1181
- } = options.interpolation;
1182
- this.escape = escape$1 !== void 0 ? escape$1 : escape;
1183
- this.escapeValue = escapeValue !== void 0 ? escapeValue : true;
1184
- this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false;
1185
- this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{";
1186
- this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}";
1187
- this.formatSeparator = formatSeparator || ",";
1188
- this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-";
1189
- this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || "";
1190
- this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t(");
1191
- this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")");
1192
- this.nestingOptionsSeparator = nestingOptionsSeparator || ",";
1193
- this.maxReplaces = maxReplaces || 1e3;
1194
- this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false;
1195
- this.resetRegExp();
1196
- }
1197
- reset() {
1198
- if (this.options) this.init(this.options);
1199
- }
1200
- resetRegExp() {
1201
- const getOrResetRegExp = (existingRegExp, pattern) => {
1202
- if (existingRegExp?.source === pattern) {
1203
- existingRegExp.lastIndex = 0;
1204
- return existingRegExp;
1205
- }
1206
- return new RegExp(pattern, "g");
1207
- };
1208
- this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);
1209
- this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);
1210
- this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`);
1211
- }
1212
- interpolate(str, data, lng, options) {
1213
- let match;
1214
- let value;
1215
- let replaces;
1216
- const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
1217
- const handleFormat = (key) => {
1218
- if (key.indexOf(this.formatSeparator) < 0) {
1219
- const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
1220
- return this.alwaysFormat ? this.format(path, void 0, lng, {
1221
- ...options,
1222
- ...data,
1223
- interpolationkey: key
1224
- }) : path;
1225
- }
1226
- const p = key.split(this.formatSeparator);
1227
- const k = p.shift().trim();
1228
- const f = p.join(this.formatSeparator).trim();
1229
- return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
1230
- ...options,
1231
- ...data,
1232
- interpolationkey: k
1233
- });
1234
- };
1235
- this.resetRegExp();
1236
- const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;
1237
- const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
1238
- const todos = [{
1239
- regex: this.regexpUnescape,
1240
- safeValue: (val) => regexSafe(val)
1241
- }, {
1242
- regex: this.regexp,
1243
- safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
1244
- }];
1245
- todos.forEach((todo) => {
1246
- replaces = 0;
1247
- while (match = todo.regex.exec(str)) {
1248
- const matchedVar = match[1].trim();
1249
- value = handleFormat(matchedVar);
1250
- if (value === void 0) {
1251
- if (typeof missingInterpolationHandler === "function") {
1252
- const temp = missingInterpolationHandler(str, match, options);
1253
- value = isString(temp) ? temp : "";
1254
- } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
1255
- value = "";
1256
- } else if (skipOnVariables) {
1257
- value = match[0];
1258
- continue;
1259
- } else {
1260
- this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
1261
- value = "";
1262
- }
1263
- } else if (!isString(value) && !this.useRawValueToEscape) {
1264
- value = makeString(value);
1265
- }
1266
- const safeValue = todo.safeValue(value);
1267
- str = str.replace(match[0], safeValue);
1268
- if (skipOnVariables) {
1269
- todo.regex.lastIndex += value.length;
1270
- todo.regex.lastIndex -= match[0].length;
1271
- } else {
1272
- todo.regex.lastIndex = 0;
1273
- }
1274
- replaces++;
1275
- if (replaces >= this.maxReplaces) {
1276
- break;
1277
- }
1278
- }
1279
- });
1280
- return str;
1281
- }
1282
- nest(str, fc, options = {}) {
1283
- let match;
1284
- let value;
1285
- let clonedOptions;
1286
- const handleHasOptions = (key, inheritedOptions) => {
1287
- const sep = this.nestingOptionsSeparator;
1288
- if (key.indexOf(sep) < 0) return key;
1289
- const c = key.split(new RegExp(`${sep}[ ]*{`));
1290
- let optionsString = `{${c[1]}`;
1291
- key = c[0];
1292
- optionsString = this.interpolate(optionsString, clonedOptions);
1293
- const matchedSingleQuotes = optionsString.match(/'/g);
1294
- const matchedDoubleQuotes = optionsString.match(/"/g);
1295
- if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
1296
- optionsString = optionsString.replace(/'/g, '"');
1297
- }
1298
- try {
1299
- clonedOptions = JSON.parse(optionsString);
1300
- if (inheritedOptions) clonedOptions = {
1301
- ...inheritedOptions,
1302
- ...clonedOptions
1303
- };
1304
- } catch (e) {
1305
- this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
1306
- return `${key}${sep}${optionsString}`;
1307
- }
1308
- if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;
1309
- return key;
1310
- };
1311
- while (match = this.nestingRegexp.exec(str)) {
1312
- let formatters = [];
1313
- clonedOptions = {
1314
- ...options
1315
- };
1316
- clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;
1317
- clonedOptions.applyPostProcessor = false;
1318
- delete clonedOptions.defaultValue;
1319
- const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf("}") + 1 : match[1].indexOf(this.formatSeparator);
1320
- if (keyEndIndex !== -1) {
1321
- formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean);
1322
- match[1] = match[1].slice(0, keyEndIndex);
1323
- }
1324
- value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
1325
- if (value && match[0] === str && !isString(value)) return value;
1326
- if (!isString(value)) value = makeString(value);
1327
- if (!value) {
1328
- this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
1329
- value = "";
1330
- }
1331
- if (formatters.length) {
1332
- value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
1333
- ...options,
1334
- interpolationkey: match[1].trim()
1335
- }), value.trim());
1336
- }
1337
- str = str.replace(match[0], value);
1338
- this.regexp.lastIndex = 0;
1339
- }
1340
- return str;
1341
- }
1342
- };
1343
- var parseFormatStr = (formatStr) => {
1344
- let formatName = formatStr.toLowerCase().trim();
1345
- const formatOptions = {};
1346
- if (formatStr.indexOf("(") > -1) {
1347
- const p = formatStr.split("(");
1348
- formatName = p[0].toLowerCase().trim();
1349
- const optStr = p[1].substring(0, p[1].length - 1);
1350
- if (formatName === "currency" && optStr.indexOf(":") < 0) {
1351
- if (!formatOptions.currency) formatOptions.currency = optStr.trim();
1352
- } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
1353
- if (!formatOptions.range) formatOptions.range = optStr.trim();
1354
- } else {
1355
- const opts = optStr.split(";");
1356
- opts.forEach((opt) => {
1357
- if (opt) {
1358
- const [key, ...rest] = opt.split(":");
1359
- const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
1360
- const trimmedKey = key.trim();
1361
- if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;
1362
- if (val === "false") formatOptions[trimmedKey] = false;
1363
- if (val === "true") formatOptions[trimmedKey] = true;
1364
- if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);
1365
- }
1366
- });
1367
- }
1368
- }
1369
- return {
1370
- formatName,
1371
- formatOptions
1372
- };
1373
- };
1374
- var createCachedFormatter = (fn) => {
1375
- const cache = {};
1376
- return (v, l, o) => {
1377
- let optForCache = o;
1378
- if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {
1379
- optForCache = {
1380
- ...optForCache,
1381
- [o.interpolationkey]: void 0
1382
- };
1383
- }
1384
- const key = l + JSON.stringify(optForCache);
1385
- let frm = cache[key];
1386
- if (!frm) {
1387
- frm = fn(getCleanedCode(l), o);
1388
- cache[key] = frm;
1389
- }
1390
- return frm(v);
1391
- };
1392
- };
1393
- var createNonCachedFormatter = (fn) => (v, l, o) => fn(getCleanedCode(l), o)(v);
1394
- var Formatter = class {
1395
- constructor(options = {}) {
1396
- this.logger = baseLogger.create("formatter");
1397
- this.options = options;
1398
- this.init(options);
1399
- }
1400
- init(services, options = {
1401
- interpolation: {}
1402
- }) {
1403
- this.formatSeparator = options.interpolation.formatSeparator || ",";
1404
- const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;
1405
- this.formats = {
1406
- number: cf((lng, opt) => {
1407
- const formatter = new Intl.NumberFormat(lng, {
1408
- ...opt
1409
- });
1410
- return (val) => formatter.format(val);
1411
- }),
1412
- currency: cf((lng, opt) => {
1413
- const formatter = new Intl.NumberFormat(lng, {
1414
- ...opt,
1415
- style: "currency"
1416
- });
1417
- return (val) => formatter.format(val);
1418
- }),
1419
- datetime: cf((lng, opt) => {
1420
- const formatter = new Intl.DateTimeFormat(lng, {
1421
- ...opt
1422
- });
1423
- return (val) => formatter.format(val);
1424
- }),
1425
- relativetime: cf((lng, opt) => {
1426
- const formatter = new Intl.RelativeTimeFormat(lng, {
1427
- ...opt
1428
- });
1429
- return (val) => formatter.format(val, opt.range || "day");
1430
- }),
1431
- list: cf((lng, opt) => {
1432
- const formatter = new Intl.ListFormat(lng, {
1433
- ...opt
1434
- });
1435
- return (val) => formatter.format(val);
1436
- })
1437
- };
1438
- }
1439
- add(name, fc) {
1440
- this.formats[name.toLowerCase().trim()] = fc;
1441
- }
1442
- addCached(name, fc) {
1443
- this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
1444
- }
1445
- format(value, format, lng, options = {}) {
1446
- const formats = format.split(this.formatSeparator);
1447
- if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) {
1448
- const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1);
1449
- formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);
1450
- }
1451
- const result = formats.reduce((mem, f) => {
1452
- const {
1453
- formatName,
1454
- formatOptions
1455
- } = parseFormatStr(f);
1456
- if (this.formats[formatName]) {
1457
- let formatted = mem;
1458
- try {
1459
- const valOptions = options?.formatParams?.[options.interpolationkey] || {};
1460
- const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
1461
- formatted = this.formats[formatName](mem, l, {
1462
- ...formatOptions,
1463
- ...options,
1464
- ...valOptions
1465
- });
1466
- } catch (error) {
1467
- this.logger.warn(error);
1468
- }
1469
- return formatted;
1470
- } else {
1471
- this.logger.warn(`there was no format function for ${formatName}`);
1472
- }
1473
- return mem;
1474
- }, value);
1475
- return result;
1476
- }
1477
- };
1478
- var removePending = (q, name) => {
1479
- if (q.pending[name] !== void 0) {
1480
- delete q.pending[name];
1481
- q.pendingCount--;
1482
- }
1483
- };
1484
- var Connector = class extends EventEmitter {
1485
- constructor(backend, store, services, options = {}) {
1486
- super();
1487
- this.backend = backend;
1488
- this.store = store;
1489
- this.services = services;
1490
- this.languageUtils = services.languageUtils;
1491
- this.options = options;
1492
- this.logger = baseLogger.create("backendConnector");
1493
- this.waitingReads = [];
1494
- this.maxParallelReads = options.maxParallelReads || 10;
1495
- this.readingCalls = 0;
1496
- this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
1497
- this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
1498
- this.state = {};
1499
- this.queue = [];
1500
- this.backend?.init?.(services, options.backend, options);
1501
- }
1502
- queueLoad(languages, namespaces, options, callback) {
1503
- const toLoad = {};
1504
- const pending = {};
1505
- const toLoadLanguages = {};
1506
- const toLoadNamespaces = {};
1507
- languages.forEach((lng) => {
1508
- let hasAllNamespaces = true;
1509
- namespaces.forEach((ns) => {
1510
- const name = `${lng}|${ns}`;
1511
- if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
1512
- this.state[name] = 2;
1513
- } else if (this.state[name] < 0) ;
1514
- else if (this.state[name] === 1) {
1515
- if (pending[name] === void 0) pending[name] = true;
1516
- } else {
1517
- this.state[name] = 1;
1518
- hasAllNamespaces = false;
1519
- if (pending[name] === void 0) pending[name] = true;
1520
- if (toLoad[name] === void 0) toLoad[name] = true;
1521
- if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true;
1522
- }
1523
- });
1524
- if (!hasAllNamespaces) toLoadLanguages[lng] = true;
1525
- });
1526
- if (Object.keys(toLoad).length || Object.keys(pending).length) {
1527
- this.queue.push({
1528
- pending,
1529
- pendingCount: Object.keys(pending).length,
1530
- loaded: {},
1531
- errors: [],
1532
- callback
1533
- });
1534
- }
1535
- return {
1536
- toLoad: Object.keys(toLoad),
1537
- pending: Object.keys(pending),
1538
- toLoadLanguages: Object.keys(toLoadLanguages),
1539
- toLoadNamespaces: Object.keys(toLoadNamespaces)
1540
- };
1541
- }
1542
- loaded(name, err, data) {
1543
- const s = name.split("|");
1544
- const lng = s[0];
1545
- const ns = s[1];
1546
- if (err) this.emit("failedLoading", lng, ns, err);
1547
- if (!err && data) {
1548
- this.store.addResourceBundle(lng, ns, data, void 0, void 0, {
1549
- skipCopy: true
1550
- });
1551
- }
1552
- this.state[name] = err ? -1 : 2;
1553
- if (err && data) this.state[name] = 0;
1554
- const loaded = {};
1555
- this.queue.forEach((q) => {
1556
- pushPath(q.loaded, [lng], ns);
1557
- removePending(q, name);
1558
- if (err) q.errors.push(err);
1559
- if (q.pendingCount === 0 && !q.done) {
1560
- Object.keys(q.loaded).forEach((l) => {
1561
- if (!loaded[l]) loaded[l] = {};
1562
- const loadedKeys = q.loaded[l];
1563
- if (loadedKeys.length) {
1564
- loadedKeys.forEach((n) => {
1565
- if (loaded[l][n] === void 0) loaded[l][n] = true;
1566
- });
1567
- }
1568
- });
1569
- q.done = true;
1570
- if (q.errors.length) {
1571
- q.callback(q.errors);
1572
- } else {
1573
- q.callback();
1574
- }
1575
- }
1576
- });
1577
- this.emit("loaded", loaded);
1578
- this.queue = this.queue.filter((q) => !q.done);
1579
- }
1580
- read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {
1581
- if (!lng.length) return callback(null, {});
1582
- if (this.readingCalls >= this.maxParallelReads) {
1583
- this.waitingReads.push({
1584
- lng,
1585
- ns,
1586
- fcName,
1587
- tried,
1588
- wait,
1589
- callback
1590
- });
1591
- return;
1592
- }
1593
- this.readingCalls++;
1594
- const resolver = (err, data) => {
1595
- this.readingCalls--;
1596
- if (this.waitingReads.length > 0) {
1597
- const next = this.waitingReads.shift();
1598
- this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
1599
- }
1600
- if (err && data && tried < this.maxRetries) {
1601
- setTimeout(() => {
1602
- this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
1603
- }, wait);
1604
- return;
1605
- }
1606
- callback(err, data);
1607
- };
1608
- const fc = this.backend[fcName].bind(this.backend);
1609
- if (fc.length === 2) {
1610
- try {
1611
- const r = fc(lng, ns);
1612
- if (r && typeof r.then === "function") {
1613
- r.then((data) => resolver(null, data)).catch(resolver);
1614
- } else {
1615
- resolver(null, r);
1616
- }
1617
- } catch (err) {
1618
- resolver(err);
1619
- }
1620
- return;
1621
- }
1622
- return fc(lng, ns, resolver);
1623
- }
1624
- prepareLoading(languages, namespaces, options = {}, callback) {
1625
- if (!this.backend) {
1626
- this.logger.warn("No backend was added via i18next.use. Will not load resources.");
1627
- return callback && callback();
1628
- }
1629
- if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);
1630
- if (isString(namespaces)) namespaces = [namespaces];
1631
- const toLoad = this.queueLoad(languages, namespaces, options, callback);
1632
- if (!toLoad.toLoad.length) {
1633
- if (!toLoad.pending.length) callback();
1634
- return null;
1635
- }
1636
- toLoad.toLoad.forEach((name) => {
1637
- this.loadOne(name);
1638
- });
1639
- }
1640
- load(languages, namespaces, callback) {
1641
- this.prepareLoading(languages, namespaces, {}, callback);
1642
- }
1643
- reload(languages, namespaces, callback) {
1644
- this.prepareLoading(languages, namespaces, {
1645
- reload: true
1646
- }, callback);
1647
- }
1648
- loadOne(name, prefix = "") {
1649
- const s = name.split("|");
1650
- const lng = s[0];
1651
- const ns = s[1];
1652
- this.read(lng, ns, "read", void 0, void 0, (err, data) => {
1653
- if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
1654
- if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
1655
- this.loaded(name, err, data);
1656
- });
1657
- }
1658
- saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {
1659
- }) {
1660
- if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {
1661
- 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!!!");
1662
- return;
1663
- }
1664
- if (key === void 0 || key === null || key === "") return;
1665
- if (this.backend?.create) {
1666
- const opts = {
1667
- ...options,
1668
- isUpdate
1669
- };
1670
- const fc = this.backend.create.bind(this.backend);
1671
- if (fc.length < 6) {
1672
- try {
1673
- let r;
1674
- if (fc.length === 5) {
1675
- r = fc(languages, namespace, key, fallbackValue, opts);
1676
- } else {
1677
- r = fc(languages, namespace, key, fallbackValue);
1678
- }
1679
- if (r && typeof r.then === "function") {
1680
- r.then((data) => clb(null, data)).catch(clb);
1681
- } else {
1682
- clb(null, r);
1683
- }
1684
- } catch (err) {
1685
- clb(err);
1686
- }
1687
- } else {
1688
- fc(languages, namespace, key, fallbackValue, clb, opts);
1689
- }
1690
- }
1691
- if (!languages || !languages[0]) return;
1692
- this.store.addResource(languages[0], namespace, key, fallbackValue);
1693
- }
1694
- };
1695
- var get = () => ({
1696
- debug: false,
1697
- initAsync: true,
1698
- ns: ["translation"],
1699
- defaultNS: ["translation"],
1700
- fallbackLng: ["dev"],
1701
- fallbackNS: false,
1702
- supportedLngs: false,
1703
- nonExplicitSupportedLngs: false,
1704
- load: "all",
1705
- preload: false,
1706
- simplifyPluralSuffix: true,
1707
- keySeparator: ".",
1708
- nsSeparator: ":",
1709
- pluralSeparator: "_",
1710
- contextSeparator: "_",
1711
- partialBundledLanguages: false,
1712
- saveMissing: false,
1713
- updateMissing: false,
1714
- saveMissingTo: "fallback",
1715
- saveMissingPlurals: true,
1716
- missingKeyHandler: false,
1717
- missingInterpolationHandler: false,
1718
- postProcess: false,
1719
- postProcessPassResolved: false,
1720
- returnNull: false,
1721
- returnEmptyString: true,
1722
- returnObjects: false,
1723
- joinArrays: false,
1724
- returnedObjectHandler: false,
1725
- parseMissingKeyHandler: false,
1726
- appendNamespaceToMissingKey: false,
1727
- appendNamespaceToCIMode: false,
1728
- overloadTranslationOptionHandler: (args) => {
1729
- let ret = {};
1730
- if (typeof args[1] === "object") ret = args[1];
1731
- if (isString(args[1])) ret.defaultValue = args[1];
1732
- if (isString(args[2])) ret.tDescription = args[2];
1733
- if (typeof args[2] === "object" || typeof args[3] === "object") {
1734
- const options = args[3] || args[2];
1735
- Object.keys(options).forEach((key) => {
1736
- ret[key] = options[key];
1737
- });
1738
- }
1739
- return ret;
1740
- },
1741
- interpolation: {
1742
- escapeValue: true,
1743
- format: (value) => value,
1744
- prefix: "{{",
1745
- suffix: "}}",
1746
- formatSeparator: ",",
1747
- unescapePrefix: "-",
1748
- nestingPrefix: "$t(",
1749
- nestingSuffix: ")",
1750
- nestingOptionsSeparator: ",",
1751
- maxReplaces: 1e3,
1752
- skipOnVariables: true
1753
- },
1754
- cacheInBuiltFormats: true
1755
- });
1756
- var transformOptions = (options) => {
1757
- if (isString(options.ns)) options.ns = [options.ns];
1758
- if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];
1759
- if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];
1760
- if (options.supportedLngs?.indexOf?.("cimode") < 0) {
1761
- options.supportedLngs = options.supportedLngs.concat(["cimode"]);
1762
- }
1763
- if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate;
1764
- return options;
1765
- };
1766
- var noop = () => {
1767
- };
1768
- var bindMemberFunctions = (inst) => {
1769
- const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
1770
- mems.forEach((mem) => {
1771
- if (typeof inst[mem] === "function") {
1772
- inst[mem] = inst[mem].bind(inst);
1773
- }
1774
- });
1775
- };
1776
- var I18n = class _I18n extends EventEmitter {
1777
- constructor(options = {}, callback) {
1778
- super();
1779
- this.options = transformOptions(options);
1780
- this.services = {};
1781
- this.logger = baseLogger;
1782
- this.modules = {
1783
- external: []
1784
- };
1785
- bindMemberFunctions(this);
1786
- if (callback && !this.isInitialized && !options.isClone) {
1787
- if (!this.options.initAsync) {
1788
- this.init(options, callback);
1789
- return this;
1790
- }
1791
- setTimeout(() => {
1792
- this.init(options, callback);
1793
- }, 0);
1794
- }
1795
- }
1796
- init(options = {}, callback) {
1797
- this.isInitializing = true;
1798
- if (typeof options === "function") {
1799
- callback = options;
1800
- options = {};
1801
- }
1802
- if (options.defaultNS == null && options.ns) {
1803
- if (isString(options.ns)) {
1804
- options.defaultNS = options.ns;
1805
- } else if (options.ns.indexOf("translation") < 0) {
1806
- options.defaultNS = options.ns[0];
1807
- }
1808
- }
1809
- const defOpts = get();
1810
- this.options = {
1811
- ...defOpts,
1812
- ...this.options,
1813
- ...transformOptions(options)
1814
- };
1815
- this.options.interpolation = {
1816
- ...defOpts.interpolation,
1817
- ...this.options.interpolation
1818
- };
1819
- if (options.keySeparator !== void 0) {
1820
- this.options.userDefinedKeySeparator = options.keySeparator;
1821
- }
1822
- if (options.nsSeparator !== void 0) {
1823
- this.options.userDefinedNsSeparator = options.nsSeparator;
1824
- }
1825
- const createClassOnDemand = (ClassOrObject) => {
1826
- if (!ClassOrObject) return null;
1827
- if (typeof ClassOrObject === "function") return new ClassOrObject();
1828
- return ClassOrObject;
1829
- };
1830
- if (!this.options.isClone) {
1831
- if (this.modules.logger) {
1832
- baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
1833
- } else {
1834
- baseLogger.init(null, this.options);
1835
- }
1836
- let formatter;
1837
- if (this.modules.formatter) {
1838
- formatter = this.modules.formatter;
1839
- } else {
1840
- formatter = Formatter;
1841
- }
1842
- const lu = new LanguageUtil(this.options);
1843
- this.store = new ResourceStore(this.options.resources, this.options);
1844
- const s = this.services;
1845
- s.logger = baseLogger;
1846
- s.resourceStore = this.store;
1847
- s.languageUtils = lu;
1848
- s.pluralResolver = new PluralResolver(lu, {
1849
- prepend: this.options.pluralSeparator,
1850
- simplifyPluralSuffix: this.options.simplifyPluralSuffix
1851
- });
1852
- const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;
1853
- if (usingLegacyFormatFunction) {
1854
- this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);
1855
- }
1856
- if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
1857
- s.formatter = createClassOnDemand(formatter);
1858
- if (s.formatter.init) s.formatter.init(s, this.options);
1859
- this.options.interpolation.format = s.formatter.format.bind(s.formatter);
1860
- }
1861
- s.interpolator = new Interpolator(this.options);
1862
- s.utils = {
1863
- hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
1864
- };
1865
- s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
1866
- s.backendConnector.on("*", (event, ...args) => {
1867
- this.emit(event, ...args);
1868
- });
1869
- if (this.modules.languageDetector) {
1870
- s.languageDetector = createClassOnDemand(this.modules.languageDetector);
1871
- if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);
1872
- }
1873
- if (this.modules.i18nFormat) {
1874
- s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
1875
- if (s.i18nFormat.init) s.i18nFormat.init(this);
1876
- }
1877
- this.translator = new Translator(this.services, this.options);
1878
- this.translator.on("*", (event, ...args) => {
1879
- this.emit(event, ...args);
1880
- });
1881
- this.modules.external.forEach((m) => {
1882
- if (m.init) m.init(this);
1883
- });
1884
- }
1885
- this.format = this.options.interpolation.format;
1886
- if (!callback) callback = noop;
1887
- if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
1888
- const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1889
- if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0];
1890
- }
1891
- if (!this.services.languageDetector && !this.options.lng) {
1892
- this.logger.warn("init: no languageDetector is used and no lng is defined");
1893
- }
1894
- const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
1895
- storeApi.forEach((fcName) => {
1896
- this[fcName] = (...args) => this.store[fcName](...args);
1897
- });
1898
- const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
1899
- storeApiChained.forEach((fcName) => {
1900
- this[fcName] = (...args) => {
1901
- this.store[fcName](...args);
1902
- return this;
1903
- };
1904
- });
1905
- const deferred = defer();
1906
- const load = () => {
1907
- const finish = (err, t2) => {
1908
- this.isInitializing = false;
1909
- if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!");
1910
- this.isInitialized = true;
1911
- if (!this.options.isClone) this.logger.log("initialized", this.options);
1912
- this.emit("initialized", this.options);
1913
- deferred.resolve(t2);
1914
- callback(err, t2);
1915
- };
1916
- if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));
1917
- this.changeLanguage(this.options.lng, finish);
1918
- };
1919
- if (this.options.resources || !this.options.initAsync) {
1920
- load();
1921
- } else {
1922
- setTimeout(load, 0);
1923
- }
1924
- return deferred;
1925
- }
1926
- loadResources(language, callback = noop) {
1927
- let usedCallback = callback;
1928
- const usedLng = isString(language) ? language : this.language;
1929
- if (typeof language === "function") usedCallback = language;
1930
- if (!this.options.resources || this.options.partialBundledLanguages) {
1931
- if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();
1932
- const toLoad = [];
1933
- const append = (lng) => {
1934
- if (!lng) return;
1935
- if (lng === "cimode") return;
1936
- const lngs = this.services.languageUtils.toResolveHierarchy(lng);
1937
- lngs.forEach((l) => {
1938
- if (l === "cimode") return;
1939
- if (toLoad.indexOf(l) < 0) toLoad.push(l);
1940
- });
1941
- };
1942
- if (!usedLng) {
1943
- const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
1944
- fallbacks.forEach((l) => append(l));
1945
- } else {
1946
- append(usedLng);
1947
- }
1948
- this.options.preload?.forEach?.((l) => append(l));
1949
- this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
1950
- if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);
1951
- usedCallback(e);
1952
- });
1953
- } else {
1954
- usedCallback(null);
1955
- }
1956
- }
1957
- reloadResources(lngs, ns, callback) {
1958
- const deferred = defer();
1959
- if (typeof lngs === "function") {
1960
- callback = lngs;
1961
- lngs = void 0;
1962
- }
1963
- if (typeof ns === "function") {
1964
- callback = ns;
1965
- ns = void 0;
1966
- }
1967
- if (!lngs) lngs = this.languages;
1968
- if (!ns) ns = this.options.ns;
1969
- if (!callback) callback = noop;
1970
- this.services.backendConnector.reload(lngs, ns, (err) => {
1971
- deferred.resolve();
1972
- callback(err);
1973
- });
1974
- return deferred;
1975
- }
1976
- use(module2) {
1977
- if (!module2) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
1978
- if (!module2.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
1979
- if (module2.type === "backend") {
1980
- this.modules.backend = module2;
1981
- }
1982
- if (module2.type === "logger" || module2.log && module2.warn && module2.error) {
1983
- this.modules.logger = module2;
1984
- }
1985
- if (module2.type === "languageDetector") {
1986
- this.modules.languageDetector = module2;
1987
- }
1988
- if (module2.type === "i18nFormat") {
1989
- this.modules.i18nFormat = module2;
1990
- }
1991
- if (module2.type === "postProcessor") {
1992
- postProcessor.addPostProcessor(module2);
1993
- }
1994
- if (module2.type === "formatter") {
1995
- this.modules.formatter = module2;
1996
- }
1997
- if (module2.type === "3rdParty") {
1998
- this.modules.external.push(module2);
1999
- }
2000
- return this;
2001
- }
2002
- setResolvedLanguage(l) {
2003
- if (!l || !this.languages) return;
2004
- if (["cimode", "dev"].indexOf(l) > -1) return;
2005
- for (let li = 0; li < this.languages.length; li++) {
2006
- const lngInLngs = this.languages[li];
2007
- if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue;
2008
- if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
2009
- this.resolvedLanguage = lngInLngs;
2010
- break;
2011
- }
2012
- }
2013
- if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {
2014
- this.resolvedLanguage = l;
2015
- this.languages.unshift(l);
2016
- }
2017
- }
2018
- changeLanguage(lng, callback) {
2019
- this.isLanguageChangingTo = lng;
2020
- const deferred = defer();
2021
- this.emit("languageChanging", lng);
2022
- const setLngProps = (l) => {
2023
- this.language = l;
2024
- this.languages = this.services.languageUtils.toResolveHierarchy(l);
2025
- this.resolvedLanguage = void 0;
2026
- this.setResolvedLanguage(l);
2027
- };
2028
- const done = (err, l) => {
2029
- if (l) {
2030
- if (this.isLanguageChangingTo === lng) {
2031
- setLngProps(l);
2032
- this.translator.changeLanguage(l);
2033
- this.isLanguageChangingTo = void 0;
2034
- this.emit("languageChanged", l);
2035
- this.logger.log("languageChanged", l);
2036
- }
2037
- } else {
2038
- this.isLanguageChangingTo = void 0;
2039
- }
2040
- deferred.resolve((...args) => this.t(...args));
2041
- if (callback) callback(err, (...args) => this.t(...args));
2042
- };
2043
- const setLng = (lngs) => {
2044
- if (!lng && !lngs && this.services.languageDetector) lngs = [];
2045
- const fl = isString(lngs) ? lngs : lngs && lngs[0];
2046
- const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);
2047
- if (l) {
2048
- if (!this.language) {
2049
- setLngProps(l);
2050
- }
2051
- if (!this.translator.language) this.translator.changeLanguage(l);
2052
- this.services.languageDetector?.cacheUserLanguage?.(l);
2053
- }
2054
- this.loadResources(l, (err) => {
2055
- done(err, l);
2056
- });
2057
- };
2058
- if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
2059
- setLng(this.services.languageDetector.detect());
2060
- } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
2061
- if (this.services.languageDetector.detect.length === 0) {
2062
- this.services.languageDetector.detect().then(setLng);
2063
- } else {
2064
- this.services.languageDetector.detect(setLng);
2065
- }
2066
- } else {
2067
- setLng(lng);
2068
- }
2069
- return deferred;
2070
- }
2071
- getFixedT(lng, ns, keyPrefix) {
2072
- const fixedT = (key, opts, ...rest) => {
2073
- let o;
2074
- if (typeof opts !== "object") {
2075
- o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));
2076
- } else {
2077
- o = {
2078
- ...opts
2079
- };
2080
- }
2081
- o.lng = o.lng || fixedT.lng;
2082
- o.lngs = o.lngs || fixedT.lngs;
2083
- o.ns = o.ns || fixedT.ns;
2084
- if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;
2085
- const keySeparator = this.options.keySeparator || ".";
2086
- let resultKey;
2087
- if (o.keyPrefix && Array.isArray(key)) {
2088
- resultKey = key.map((k) => {
2089
- if (typeof k === "function") k = keysFromSelector(k, {
2090
- ...this.options,
2091
- ...opts
2092
- });
2093
- return `${o.keyPrefix}${keySeparator}${k}`;
2094
- });
2095
- } else {
2096
- if (typeof key === "function") key = keysFromSelector(key, {
2097
- ...this.options,
2098
- ...opts
2099
- });
2100
- resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;
2101
- }
2102
- return this.t(resultKey, o);
2103
- };
2104
- if (isString(lng)) {
2105
- fixedT.lng = lng;
2106
- } else {
2107
- fixedT.lngs = lng;
2108
- }
2109
- fixedT.ns = ns;
2110
- fixedT.keyPrefix = keyPrefix;
2111
- return fixedT;
2112
- }
2113
- t(...args) {
2114
- return this.translator?.translate(...args);
2115
- }
2116
- exists(...args) {
2117
- return this.translator?.exists(...args);
2118
- }
2119
- setDefaultNamespace(ns) {
2120
- this.options.defaultNS = ns;
2121
- }
2122
- hasLoadedNamespace(ns, options = {}) {
2123
- if (!this.isInitialized) {
2124
- this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
2125
- return false;
2126
- }
2127
- if (!this.languages || !this.languages.length) {
2128
- this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
2129
- return false;
2130
- }
2131
- const lng = options.lng || this.resolvedLanguage || this.languages[0];
2132
- const fallbackLng = this.options ? this.options.fallbackLng : false;
2133
- const lastLng = this.languages[this.languages.length - 1];
2134
- if (lng.toLowerCase() === "cimode") return true;
2135
- const loadNotPending = (l, n) => {
2136
- const loadState = this.services.backendConnector.state[`${l}|${n}`];
2137
- return loadState === -1 || loadState === 0 || loadState === 2;
2138
- };
2139
- if (options.precheck) {
2140
- const preResult = options.precheck(this, loadNotPending);
2141
- if (preResult !== void 0) return preResult;
2142
- }
2143
- if (this.hasResourceBundle(lng, ns)) return true;
2144
- if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;
2145
- if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
2146
- return false;
2147
- }
2148
- loadNamespaces(ns, callback) {
2149
- const deferred = defer();
2150
- if (!this.options.ns) {
2151
- if (callback) callback();
2152
- return Promise.resolve();
2153
- }
2154
- if (isString(ns)) ns = [ns];
2155
- ns.forEach((n) => {
2156
- if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);
2157
- });
2158
- this.loadResources((err) => {
2159
- deferred.resolve();
2160
- if (callback) callback(err);
2161
- });
2162
- return deferred;
2163
- }
2164
- loadLanguages(lngs, callback) {
2165
- const deferred = defer();
2166
- if (isString(lngs)) lngs = [lngs];
2167
- const preloaded = this.options.preload || [];
2168
- const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));
2169
- if (!newLngs.length) {
2170
- if (callback) callback();
2171
- return Promise.resolve();
2172
- }
2173
- this.options.preload = preloaded.concat(newLngs);
2174
- this.loadResources((err) => {
2175
- deferred.resolve();
2176
- if (callback) callback(err);
2177
- });
2178
- return deferred;
2179
- }
2180
- dir(lng) {
2181
- if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);
2182
- if (!lng) return "rtl";
2183
- try {
2184
- const l = new Intl.Locale(lng);
2185
- if (l && l.getTextInfo) {
2186
- const ti = l.getTextInfo();
2187
- if (ti && ti.direction) return ti.direction;
2188
- }
2189
- } catch (e) {
2190
- }
2191
- 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"];
2192
- const languageUtils = this.services?.languageUtils || new LanguageUtil(get());
2193
- if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr";
2194
- return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
2195
- }
2196
- static createInstance(options = {}, callback) {
2197
- const instance2 = new _I18n(options, callback);
2198
- instance2.createInstance = _I18n.createInstance;
2199
- return instance2;
2200
- }
2201
- cloneInstance(options = {}, callback = noop) {
2202
- const forkResourceStore = options.forkResourceStore;
2203
- if (forkResourceStore) delete options.forkResourceStore;
2204
- const mergedOptions = {
2205
- ...this.options,
2206
- ...options,
2207
- ...{
2208
- isClone: true
2209
- }
2210
- };
2211
- const clone = new _I18n(mergedOptions);
2212
- if (options.debug !== void 0 || options.prefix !== void 0) {
2213
- clone.logger = clone.logger.clone(options);
2214
- }
2215
- const membersToCopy = ["store", "services", "language"];
2216
- membersToCopy.forEach((m) => {
2217
- clone[m] = this[m];
2218
- });
2219
- clone.services = {
2220
- ...this.services
2221
- };
2222
- clone.services.utils = {
2223
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2224
- };
2225
- if (forkResourceStore) {
2226
- const clonedData = Object.keys(this.store.data).reduce((prev, l) => {
2227
- prev[l] = {
2228
- ...this.store.data[l]
2229
- };
2230
- prev[l] = Object.keys(prev[l]).reduce((acc, n) => {
2231
- acc[n] = {
2232
- ...prev[l][n]
2233
- };
2234
- return acc;
2235
- }, prev[l]);
2236
- return prev;
2237
- }, {});
2238
- clone.store = new ResourceStore(clonedData, mergedOptions);
2239
- clone.services.resourceStore = clone.store;
2240
- }
2241
- if (options.interpolation) clone.services.interpolator = new Interpolator(mergedOptions);
2242
- clone.translator = new Translator(clone.services, mergedOptions);
2243
- clone.translator.on("*", (event, ...args) => {
2244
- clone.emit(event, ...args);
2245
- });
2246
- clone.init(mergedOptions, callback);
2247
- clone.translator.options = mergedOptions;
2248
- clone.translator.backendConnector.services.utils = {
2249
- hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
2250
- };
2251
- return clone;
2252
- }
2253
- toJSON() {
2254
- return {
2255
- options: this.options,
2256
- store: this.store,
2257
- language: this.language,
2258
- languages: this.languages,
2259
- resolvedLanguage: this.resolvedLanguage
2260
- };
2261
- }
2262
- };
2263
- var instance = I18n.createInstance();
2264
- var createInstance = instance.createInstance;
2265
- var dir = instance.dir;
2266
- var init = instance.init;
2267
- var loadResources = instance.loadResources;
2268
- var reloadResources = instance.reloadResources;
2269
- var use = instance.use;
2270
- var changeLanguage = instance.changeLanguage;
2271
- var getFixedT = instance.getFixedT;
2272
- var t = instance.t;
2273
- var exists = instance.exists;
2274
- var setDefaultNamespace = instance.setDefaultNamespace;
2275
- var hasLoadedNamespace = instance.hasLoadedNamespace;
2276
- var loadNamespaces = instance.loadNamespaces;
2277
- var loadLanguages = instance.loadLanguages;
2278
-
2279
- // src/locale/en/locale-resources.ts
2280
- var locale_resources_default = {
2281
- Check: {
2282
- lengthOfStringForPriceOrWeightMustBeExactly: "Length {{length, number}} of string for price or weight must be 4 or 5",
2283
- priceOrWeightComponent: "price or weight",
2284
- lengthOfStringForCheckCharacterPairMustBeLessThanOrEqualTo: "Length {{length, number}} of string for check character pair must be less than or equal to {{maximumLength, number}}"
2285
- },
2286
- Identifier: {
2287
- identifierTypeLength: "{{identifierType}} must be {{length, number}} digits long",
2288
- invalidCheckDigit: "Invalid check digit",
2289
- invalidGTINLength: "GTIN must be 13, 12, 8, or 14 digits long",
2290
- invalidGTIN14Length: "GTIN must be 14 digits long",
2291
- invalidZeroSuppressedGTIN12: "Invalid zero-suppressed GTIN-12",
2292
- invalidZeroSuppressibleGTIN12: "GTIN-12 not zero-suppressible",
2293
- invalidZeroSuppressedGTIN12AsGTIN13: "Invalid zero-suppressed GTIN-12 as GTIN-13",
2294
- invalidZeroSuppressedGTIN12AsGTIN14: "Invalid zero-suppressed GTIN-12 as GTIN-14",
2295
- invalidGTIN13AtRetail: "GTIN-13 at retail consumer trade item level can't start with zero",
2296
- invalidGTINAtRetail: "GTIN not supported at retail consumer trade item level",
2297
- invalidGTINAtOtherThanRetail: "GTIN not supported at other than retail consumer trade item level",
2298
- invalidRCNLength: "RCN length must match format length",
2299
- invalidVariableMeasureRCNFormat: "Invalid variable measure RCN format",
2300
- invalidVariableMeasureRCNPrefix: "Invalid variable measure RCN prefix",
2301
- invalidVariableMeasurePriceOrWeight: "Invalid variable measure price or weight",
2302
- indicatorDigit: "indicator digit",
2303
- serialComponent: "serial component",
2304
- reference: "reference",
2305
- referenceCantBeAllNumeric: "Reference can't be all-numeric",
2306
- invalidCheckCharacterPair: "Invalid check character pair"
2307
- },
2308
- Prefix: {
2309
- gs1CompanyPrefix: "GS1 Company Prefix",
2310
- upcCompanyPrefix: "U.P.C. Company Prefix",
2311
- gs18Prefix: "GS1-8 Prefix",
2312
- gs1CompanyPrefixCantStartWith0: `GS1 Company Prefix can't start with "0"`,
2313
- gs1CompanyPrefixCantStartWith00000: `GS1 Company Prefix can't start with "00000"`,
2314
- gs1CompanyPrefixCantStartWith000000: `GS1 Company Prefix can't start with "000000"`,
2315
- upcCompanyPrefixCantStartWith0000: `U.P.C. Company Prefix can't start with "0000"`,
2316
- gs18PrefixCantStartWith0: `GS1-8 Prefix can't start with "0"`,
2317
- identifierTypeNotSupportedByGS18Prefix: "{{identifierType}} not supported by GS1-8 Prefix"
2318
- }
2319
- };
2320
-
2321
- // src/locale/fr/locale-resources.ts
2322
- var locale_resources_default2 = {
2323
- Check: {
2324
- lengthOfStringForPriceOrWeightMustBeExactly: "La longueur {{length, number}} de la cha\xEEne pour le prix ou le poids doit \xEAtre 4 ou 5",
2325
- priceOrWeightComponent: "prix ou poids",
2326
- lengthOfStringForCheckCharacterPairMustBeLessThanOrEqualTo: "La longueur {{length, number}} de la cha\xEEne pour la paire de caract\xE8res de v\xE9rification doit \xEAtre inf\xE9rieure ou \xE9gale \xE0 {{maximumLength, number}}"
2327
- },
2328
- Identifier: {
2329
- identifierTypeLength: "{{identifierType}} doit comporter {{length, number}} chiffres",
2330
- invalidCheckDigit: "Chiffre de contr\xF4le non valide",
2331
- invalidGTINLength: "Le GTIN doit comporter 13, 12, 8 ou 14 chiffres",
2332
- invalidGTIN14Length: "Le GTIN doit comporter 14 chiffres",
2333
- invalidZeroSuppressedGTIN12: "Code GTIN-12 non valide avec z\xE9ro supprim\xE9",
2334
- invalidZeroSuppressibleGTIN12: "Le GTIN-12 ne peut pas \xEAtre supprim\xE9 par z\xE9ro",
2335
- invalidZeroSuppressedGTIN12AsGTIN13: "GTIN-12 non valide avec z\xE9ro supprim\xE9 en tant que GTIN-13",
2336
- invalidZeroSuppressedGTIN12AsGTIN14: "GTIN-12 non valide avec z\xE9ro supprim\xE9 en tant que GTIN-14",
2337
- invalidGTIN13AtRetail: "Le GTIN-13 au niveau des articles de consommation au d\xE9tail ne peut pas commencer par z\xE9ro",
2338
- invalidGTINAtRetail: "Le GTIN n'est pas pris en charge au niveau des articles de consommation au d\xE9tail",
2339
- invalidGTINAtOtherThanRetail: "Le GTIN n'est pas pris en charge \xE0 d'autres niveaux que ceux des articles de consommation au d\xE9tail",
2340
- invalidRCNLength: "La longueur du RCN doit correspondre \xE0 la longueur du format",
2341
- invalidVariableMeasureRCNFormat: "Format RCN de mesure variable non valide",
2342
- invalidVariableMeasureRCNPrefix: "Pr\xE9fixe RCN de mesure variable non valide",
2343
- invalidVariableMeasurePriceOrWeight: "Mesure variable invalide : prix ou poids",
2344
- indicatorDigit: "chiffre indicateur",
2345
- serialComponent: "composant s\xE9rie",
2346
- reference: "r\xE9f\xE9rence",
2347
- referenceCantBeAllNumeric: "La r\xE9f\xE9rence ne peut pas \xEAtre enti\xE8rement num\xE9rique",
2348
- invalidCheckCharacterPair: "Paire de caract\xE8res de contr\xF4le non valide"
2349
- },
2350
- Prefix: {
2351
- gs1CompanyPrefix: "Pr\xE9fixe de l'entreprise GS1",
2352
- upcCompanyPrefix: "Pr\xE9fixe de l'entreprise U.P.C.",
2353
- gs18Prefix: "Pr\xE9fixe GS1-8",
2354
- gs1CompanyPrefixCantStartWith0: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "0"`,
2355
- gs1CompanyPrefixCantStartWith00000: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "00000"`,
2356
- gs1CompanyPrefixCantStartWith000000: `Le pr\xE9fixe de l'entreprise GS1 ne peut pas commencer par "000000"`,
2357
- upcCompanyPrefixCantStartWith0000: `Le pr\xE9fixe de l'entreprise U.P.C. ne peut pas commencer par "0000"`,
2358
- gs18PrefixCantStartWith0: 'Le pr\xE9fixe GS1-8 ne peut pas commencer par "0"',
2359
- identifierTypeNotSupportedByGS18Prefix: "{{identifierType}} non pris en charge par le pr\xE9fixe GS1-8"
2360
- }
2361
- };
2362
-
2363
- // src/locale/i18n.ts
2364
- var gs1NS = "aidct_gs1";
2365
- var gs1Resources = {
2366
- en: {
2367
- aidct_gs1: locale_resources_default
2368
- },
2369
- fr: {
2370
- aidct_gs1: locale_resources_default2
2371
- }
2372
- };
2373
- var i18nextGS1 = instance.createInstance();
2374
- async function i18nGS1Init(environment, debug = false) {
2375
- await (0, import_utility.i18nUtilityInit)(environment, debug);
2376
- await (0, import_core.i18nCoreInit)(i18nextGS1, environment, debug, gs1NS, import_utility.utilityResources, gs1Resources);
2377
- }
2378
-
2379
- // src/character-set.ts
2380
- var import_utility2 = require("@aidc-toolkit/utility");
2381
- var AI82_CREATOR = new import_utility2.CharacterSetCreator([
2382
- "!",
2383
- '"',
2384
- "%",
2385
- "&",
2386
- "'",
2387
- "(",
2388
- ")",
2389
- "*",
2390
- "+",
2391
- ",",
2392
- "-",
2393
- ".",
2394
- "/",
2395
- "0",
2396
- "1",
2397
- "2",
2398
- "3",
2399
- "4",
2400
- "5",
2401
- "6",
2402
- "7",
2403
- "8",
2404
- "9",
2405
- ":",
2406
- ";",
2407
- "<",
2408
- "=",
2409
- ">",
2410
- "?",
2411
- "A",
2412
- "B",
2413
- "C",
2414
- "D",
2415
- "E",
2416
- "F",
2417
- "G",
2418
- "H",
2419
- "I",
2420
- "J",
2421
- "K",
2422
- "L",
2423
- "M",
2424
- "N",
2425
- "O",
2426
- "P",
2427
- "Q",
2428
- "R",
2429
- "S",
2430
- "T",
2431
- "U",
2432
- "V",
2433
- "W",
2434
- "X",
2435
- "Y",
2436
- "Z",
2437
- "_",
2438
- "a",
2439
- "b",
2440
- "c",
2441
- "d",
2442
- "e",
2443
- "f",
2444
- "g",
2445
- "h",
2446
- "i",
2447
- "j",
2448
- "k",
2449
- "l",
2450
- "m",
2451
- "n",
2452
- "o",
2453
- "p",
2454
- "q",
2455
- "r",
2456
- "s",
2457
- "t",
2458
- "u",
2459
- "v",
2460
- "w",
2461
- "x",
2462
- "y",
2463
- "z"
2464
- ], import_utility2.Exclusions.AllNumeric);
2465
- var AI82_VALIDATOR = AI82_CREATOR;
2466
- var AI39_CREATOR = new import_utility2.CharacterSetCreator([
2467
- "#",
2468
- "-",
2469
- "/",
2470
- "0",
2471
- "1",
2472
- "2",
2473
- "3",
2474
- "4",
2475
- "5",
2476
- "6",
2477
- "7",
2478
- "8",
2479
- "9",
2480
- "A",
2481
- "B",
2482
- "C",
2483
- "D",
2484
- "E",
2485
- "F",
2486
- "G",
2487
- "H",
2488
- "I",
2489
- "J",
2490
- "K",
2491
- "L",
2492
- "M",
2493
- "N",
2494
- "O",
2495
- "P",
2496
- "Q",
2497
- "R",
2498
- "S",
2499
- "T",
2500
- "U",
2501
- "V",
2502
- "W",
2503
- "X",
2504
- "Y",
2505
- "Z"
2506
- ], import_utility2.Exclusions.AllNumeric);
2507
- var AI39_VALIDATOR = AI39_CREATOR;
2508
- var AI64_VALIDATOR = new import_utility2.CharacterSetValidator([
2509
- "-",
2510
- "0",
2511
- "1",
2512
- "2",
2513
- "3",
2514
- "4",
2515
- "5",
2516
- "6",
2517
- "7",
2518
- "8",
2519
- "9",
2520
- "=",
2521
- "A",
2522
- "B",
2523
- "C",
2524
- "D",
2525
- "E",
2526
- "F",
2527
- "G",
2528
- "H",
2529
- "I",
2530
- "J",
2531
- "K",
2532
- "L",
2533
- "M",
2534
- "N",
2535
- "O",
2536
- "P",
2537
- "Q",
2538
- "R",
2539
- "S",
2540
- "T",
2541
- "U",
2542
- "V",
2543
- "W",
2544
- "X",
2545
- "Y",
2546
- "Z",
2547
- "_",
2548
- "a",
2549
- "b",
2550
- "c",
2551
- "d",
2552
- "e",
2553
- "f",
2554
- "g",
2555
- "h",
2556
- "i",
2557
- "j",
2558
- "k",
2559
- "l",
2560
- "m",
2561
- "n",
2562
- "o",
2563
- "p",
2564
- "q",
2565
- "r",
2566
- "s",
2567
- "t",
2568
- "u",
2569
- "v",
2570
- "w",
2571
- "x",
2572
- "y",
2573
- "z"
2574
- ]);
2575
-
2576
- // src/check.ts
2577
- var import_utility3 = require("@aidc-toolkit/utility");
2578
- var THREE_WEIGHT_RESULTS = [
2579
- 0,
2580
- 3,
2581
- 6,
2582
- 9,
2583
- 12,
2584
- 15,
2585
- 18,
2586
- 21,
2587
- 24,
2588
- 27
2589
- ];
2590
- var TWO_MINUS_WEIGHT_RESULTS = [
2591
- 0,
2592
- 2,
2593
- 4,
2594
- 6,
2595
- 8,
2596
- 9,
2597
- 1,
2598
- 3,
2599
- 5,
2600
- 7
2601
- ];
2602
- var FIVE_PLUS_WEIGHT_RESULTS = [
2603
- 0,
2604
- 5,
2605
- 1,
2606
- 6,
2607
- 2,
2608
- 7,
2609
- 3,
2610
- 8,
2611
- 4,
2612
- 9
2613
- ];
2614
- var FIVE_MINUS_WEIGHT_RESULTS = [
2615
- 0,
2616
- 5,
2617
- 9,
2618
- 4,
2619
- 8,
2620
- 3,
2621
- 7,
2622
- 2,
2623
- 6,
2624
- 1
2625
- ];
2626
- var INVERSE_FIVE_MINUS_WEIGHT_RESULTS = [
2627
- 0,
2628
- 9,
2629
- 7,
2630
- 5,
2631
- 3,
2632
- 1,
2633
- 8,
2634
- 6,
2635
- 4,
2636
- 2
2637
- ];
2638
- function checkDigitSum(exchangeWeights, s) {
2639
- let weight3 = (s.length + Number(exchangeWeights)) % 2 === 0;
2640
- return import_utility3.NUMERIC_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2641
- if (characterIndex === void 0) {
2642
- throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPosition", {
2643
- ns: import_utility3.utilityNS,
2644
- c: s.charAt(index),
2645
- position: index + 1
2646
- }));
2647
- }
2648
- weight3 = !weight3;
2649
- return accumulator + (weight3 ? THREE_WEIGHT_RESULTS[characterIndex] : characterIndex);
2650
- }, 0);
2651
- }
2652
- function checkDigit(s) {
2653
- return import_utility3.NUMERIC_CREATOR.character(9 - (checkDigitSum(false, s) + 9) % 10);
2654
- }
2655
- function hasValidCheckDigit(s) {
2656
- return checkDigitSum(true, s) % 10 === 0;
2657
- }
2658
- function priceOrWeightSum(weightsResults, s) {
2659
- return import_utility3.NUMERIC_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2660
- if (characterIndex === void 0) {
2661
- throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPositionOfComponent", {
2662
- ns: import_utility3.utilityNS,
2663
- c: s.charAt(index),
2664
- position: index + 1,
2665
- component: i18nextGS1.t("Check.priceOrWeightComponent")
2666
- }));
2667
- }
2668
- return accumulator + weightsResults[index][characterIndex];
2669
- }, 0);
2670
- }
2671
- function priceOrWeightCheckDigit(s) {
2672
- let checkDigit2;
2673
- switch (s.length) {
2674
- case 4:
2675
- checkDigit2 = import_utility3.NUMERIC_CREATOR.character(priceOrWeightSum([TWO_MINUS_WEIGHT_RESULTS, TWO_MINUS_WEIGHT_RESULTS, THREE_WEIGHT_RESULTS, FIVE_MINUS_WEIGHT_RESULTS], s) * 3 % 10);
2676
- break;
2677
- case 5:
2678
- checkDigit2 = import_utility3.NUMERIC_CREATOR.character(INVERSE_FIVE_MINUS_WEIGHT_RESULTS[9 - (priceOrWeightSum([FIVE_PLUS_WEIGHT_RESULTS, TWO_MINUS_WEIGHT_RESULTS, FIVE_MINUS_WEIGHT_RESULTS, FIVE_PLUS_WEIGHT_RESULTS, TWO_MINUS_WEIGHT_RESULTS], s) + 9) % 10]);
2679
- break;
2680
- default:
2681
- throw new RangeError(i18nextGS1.t("Check.lengthOfStringForPriceOrWeightMustBeExactly", {
2682
- length: s.length
2683
- }));
2684
- }
2685
- return checkDigit2;
2686
- }
2687
- function isValidPriceOrWeightCheckDigit(s, checkDigit2) {
2688
- return priceOrWeightCheckDigit(s) === checkDigit2;
2689
- }
2690
- var CHECK_CHARACTER_WEIGHTS = [
2691
- 107,
2692
- 103,
2693
- 101,
2694
- 97,
2695
- 89,
2696
- 83,
2697
- 79,
2698
- 73,
2699
- 71,
2700
- 67,
2701
- 61,
2702
- 59,
2703
- 53,
2704
- 47,
2705
- 43,
2706
- 41,
2707
- 37,
2708
- 31,
2709
- 29,
2710
- 23,
2711
- 19,
2712
- 17,
2713
- 13,
2714
- 11,
2715
- 7,
2716
- 5,
2717
- 3,
2718
- 2
2719
- ];
2720
- var CHECK_CHARACTERS = [
2721
- "2",
2722
- "3",
2723
- "4",
2724
- "5",
2725
- "6",
2726
- "7",
2727
- "8",
2728
- "9",
2729
- "A",
2730
- "B",
2731
- "C",
2732
- "D",
2733
- "E",
2734
- "F",
2735
- "G",
2736
- "H",
2737
- "J",
2738
- "K",
2739
- "L",
2740
- "M",
2741
- "N",
2742
- "P",
2743
- "Q",
2744
- "R",
2745
- "S",
2746
- "T",
2747
- "U",
2748
- "V",
2749
- "W",
2750
- "X",
2751
- "Y",
2752
- "Z"
2753
- ];
2754
- function checkCharacterPair(s) {
2755
- const weightIndexStart = CHECK_CHARACTER_WEIGHTS.length - s.length;
2756
- if (weightIndexStart < 0) {
2757
- throw new RangeError(i18nextGS1.t("Check.lengthOfStringForCheckCharacterPairMustBeLessThanOrEqualTo", {
2758
- length: s.length,
2759
- maximumLength: CHECK_CHARACTER_WEIGHTS.length
2760
- }));
2761
- }
2762
- const checkCharacterPairSum = AI82_CREATOR.characterIndexes(s).reduce((accumulator, characterIndex, index) => {
2763
- if (characterIndex === void 0) {
2764
- throw new RangeError(i18nextGS1.t("CharacterSetValidator.invalidCharacterAtPosition", {
2765
- ns: import_utility3.utilityNS,
2766
- c: s.charAt(index),
2767
- position: index + 1
2768
- }));
2769
- }
2770
- return accumulator + characterIndex * CHECK_CHARACTER_WEIGHTS[weightIndexStart + index];
2771
- }, 0) % 1021;
2772
- const checkCharacterPairSumMod32 = checkCharacterPairSum % 32;
2773
- return CHECK_CHARACTERS[(checkCharacterPairSum - checkCharacterPairSumMod32) / 32] + CHECK_CHARACTERS[checkCharacterPairSumMod32];
2774
- }
2775
- function hasValidCheckCharacterPair(s) {
2776
- const checkCharacterPairIndex = s.length - 2;
2777
- return checkCharacterPair(s.substring(0, checkCharacterPairIndex)) === s.substring(checkCharacterPairIndex);
2778
- }
2779
-
2780
- // src/prefix-type.ts
2781
- var PrefixTypes = {
2782
- /**
2783
- * GS1 Company Prefix.
2784
- */
2785
- GS1CompanyPrefix: "GS1 Company Prefix",
2786
- /**
2787
- * U.P.C. Company Prefix.
2788
- */
2789
- UPCCompanyPrefix: "U.P.C. Company Prefix",
2790
- /**
2791
- * GS1-8 Prefix.
2792
- */
2793
- GS18Prefix: "GS1-8 Prefix"
2794
- };
2795
-
2796
- // src/prefix-validator.ts
2797
- var import_utility4 = require("@aidc-toolkit/utility");
2798
- var GS1_COMPANY_PREFIX_MINIMUM_LENGTH = 4;
2799
- var GS1_COMPANY_PREFIX_MAXIMUM_LENGTH = 12;
2800
- var UPC_COMPANY_PREFIX_MINIMUM_LENGTH = 6;
2801
- var UPC_COMPANY_PREFIX_MAXIMUM_LENGTH = 11;
2802
- var GS1_8_PREFIX_MINIMUM_LENGTH = 2;
2803
- var GS1_8_PREFIX_MAXIMUM_LENGTH = 7;
2804
- var GS1_COMPANY_PREFIX_VALIDATION = {
2805
- minimumLength: GS1_COMPANY_PREFIX_MINIMUM_LENGTH,
2806
- maximumLength: GS1_COMPANY_PREFIX_MAXIMUM_LENGTH,
2807
- component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2808
- };
2809
- var UPC_COMPANY_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION = {
2810
- minimumLength: UPC_COMPANY_PREFIX_MINIMUM_LENGTH + 1,
2811
- maximumLength: UPC_COMPANY_PREFIX_MAXIMUM_LENGTH + 1,
2812
- component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2813
- };
2814
- var GS1_8_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION = {
2815
- minimumLength: GS1_8_PREFIX_MINIMUM_LENGTH + 5,
2816
- maximumLength: GS1_8_PREFIX_MAXIMUM_LENGTH + 5,
2817
- component: () => i18nextGS1.t("Prefix.gs1CompanyPrefix")
2818
- };
2819
- var UPC_COMPANY_PREFIX_VALIDATION = {
2820
- minimumLength: UPC_COMPANY_PREFIX_MINIMUM_LENGTH,
2821
- maximumLength: UPC_COMPANY_PREFIX_MAXIMUM_LENGTH,
2822
- component: () => i18nextGS1.t("Prefix.upcCompanyPrefix")
2823
- };
2824
- var GS1_8_PREFIX_VALIDATION = {
2825
- minimumLength: GS1_8_PREFIX_MINIMUM_LENGTH,
2826
- maximumLength: GS1_8_PREFIX_MAXIMUM_LENGTH,
2827
- component: () => i18nextGS1.t("Prefix.gs18Prefix")
2828
- };
2829
- var PrefixValidator = {
2830
- GS1_COMPANY_PREFIX_MINIMUM_LENGTH,
2831
- GS1_COMPANY_PREFIX_MAXIMUM_LENGTH,
2832
- UPC_COMPANY_PREFIX_MINIMUM_LENGTH,
2833
- UPC_COMPANY_PREFIX_MAXIMUM_LENGTH,
2834
- GS1_8_PREFIX_MINIMUM_LENGTH,
2835
- GS1_8_PREFIX_MAXIMUM_LENGTH,
2836
- /**
2837
- * Validate a prefix.
2838
- *
2839
- * @param prefixType
2840
- * Prefix type.
2841
- *
2842
- * @param allowUPCCompanyPrefix
2843
- * If true, a U.P.C. Company Prefix expressed as a GS1 Company Prefix is permitted.
2844
- *
2845
- * @param allowGS18Prefix
2846
- * If true, a GS1-8 Prefix expressed as a GS1 Company Prefix is permitted.
2847
- *
2848
- * @param prefix
2849
- * Prefix.
2850
- *
2851
- * @param isFromIdentifier
2852
- * If true, the prefix is from an identifier and should be trimmed before its character set is validated.
2853
- *
2854
- * @param isNumericIdentifier
2855
- * If true, the prefix is from a numeric identifier and its character set will be validated by the caller.
2856
- *
2857
- * @param positionOffset
2858
- * Position offset within a larger string.
2859
- */
2860
- validate(prefixType, allowUPCCompanyPrefix, allowGS18Prefix, prefix, isFromIdentifier = false, isNumericIdentifier = false, positionOffset) {
2861
- let baseValidation;
2862
- switch (prefixType) {
2863
- case PrefixTypes.GS1CompanyPrefix:
2864
- if (!prefix.startsWith("0")) {
2865
- baseValidation = GS1_COMPANY_PREFIX_VALIDATION;
2866
- } else if (!prefix.startsWith("00000")) {
2867
- if (!allowUPCCompanyPrefix) {
2868
- throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith0"));
2869
- }
2870
- baseValidation = UPC_COMPANY_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION;
2871
- } else if (!prefix.startsWith("000000")) {
2872
- if (!allowGS18Prefix) {
2873
- throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith00000"));
2874
- }
2875
- baseValidation = GS1_8_PREFIX_AS_GS1_COMPANY_PREFIX_VALIDATION;
2876
- } else {
2877
- throw new RangeError(i18nextGS1.t("Prefix.gs1CompanyPrefixCantStartWith000000"));
2878
- }
2879
- break;
2880
- case PrefixTypes.UPCCompanyPrefix:
2881
- if (prefix.startsWith("0000")) {
2882
- throw new RangeError(i18nextGS1.t("Prefix.upcCompanyPrefixCantStartWith0000"));
2883
- }
2884
- baseValidation = UPC_COMPANY_PREFIX_VALIDATION;
2885
- break;
2886
- case PrefixTypes.GS18Prefix:
2887
- if (prefix.startsWith("0")) {
2888
- throw new RangeError(i18nextGS1.t("Prefix.gs18PrefixCantStartWith0"));
2889
- }
2890
- baseValidation = GS1_8_PREFIX_VALIDATION;
2891
- break;
2892
- }
2893
- const mergedValidation = {
2894
- ...baseValidation,
2895
- positionOffset
2896
- };
2897
- if (!isFromIdentifier) {
2898
- import_utility4.NUMERIC_CREATOR.validate(prefix, mergedValidation);
2899
- } else if (!isNumericIdentifier) {
2900
- import_utility4.NUMERIC_CREATOR.validate(prefix.substring(0, Math.min(mergedValidation.minimumLength, prefix.length - 1)), mergedValidation);
2901
- }
2902
- },
2903
- /**
2904
- * Normalize a prefix.
2905
- *
2906
- * @param prefixType
2907
- * Prefix type.
2908
- *
2909
- * @param prefix
2910
- * Prefix.
2911
- *
2912
- * @returns
2913
- * Prefix provider with normalized prefix type and prefix.
2914
- */
2915
- normalize(prefixType, prefix) {
2916
- this.validate(prefixType, true, true, prefix);
2917
- let gs1CompanyPrefix;
2918
- switch (prefixType) {
2919
- case PrefixTypes.GS1CompanyPrefix:
2920
- gs1CompanyPrefix = prefix;
2921
- break;
2922
- case PrefixTypes.UPCCompanyPrefix:
2923
- gs1CompanyPrefix = "0" + prefix;
2924
- break;
2925
- case PrefixTypes.GS18Prefix:
2926
- gs1CompanyPrefix = "00000" + prefix;
2927
- break;
2928
- }
2929
- let normalizedPrefixType;
2930
- let normalizedPrefix;
2931
- let upcCompanyPrefix = void 0;
2932
- let gs18Prefix = void 0;
2933
- if (!gs1CompanyPrefix.startsWith("0")) {
2934
- normalizedPrefixType = PrefixTypes.GS1CompanyPrefix;
2935
- normalizedPrefix = gs1CompanyPrefix;
2936
- } else if (!gs1CompanyPrefix.startsWith("00000")) {
2937
- normalizedPrefixType = PrefixTypes.UPCCompanyPrefix;
2938
- upcCompanyPrefix = gs1CompanyPrefix.substring(1);
2939
- normalizedPrefix = upcCompanyPrefix;
2940
- } else {
2941
- normalizedPrefixType = PrefixTypes.GS18Prefix;
2942
- gs18Prefix = gs1CompanyPrefix.substring(5);
2943
- normalizedPrefix = gs18Prefix;
2944
- }
2945
- return {
2946
- prefixType: normalizedPrefixType,
2947
- prefix: normalizedPrefix,
2948
- gs1CompanyPrefix,
2949
- upcCompanyPrefix,
2950
- gs18Prefix
2951
- };
2952
- }
2953
- };
2954
-
2955
- // src/content-character-set.ts
2956
- var ContentCharacterSets = {
2957
- /**
2958
- * Numeric.
2959
- */
2960
- Numeric: "Numeric",
2961
- /**
2962
- * GS1 AI encodable character set 82.
2963
- */
2964
- AI82: "AI82",
2965
- /**
2966
- * GS1 AI encodable character set 39.
2967
- */
2968
- AI39: "AI39"
2969
- };
2970
-
2971
- // src/identifier-type.ts
2972
- var IdentifierTypes = {
2973
- /**
2974
- * Global Trade Item Number.
2975
- */
2976
- GTIN: "GTIN",
2977
- /**
2978
- * Global Location Number.
2979
- */
2980
- GLN: "GLN",
2981
- /**
2982
- * Serial Shipping Container Code.
2983
- */
2984
- SSCC: "SSCC",
2985
- /**
2986
- * Global Returnable Asset Identifier.
2987
- */
2988
- GRAI: "GRAI",
2989
- /**
2990
- * Global Individual Asset Identifier.
2991
- */
2992
- GIAI: "GIAI",
2993
- /**
2994
- * Global Service Relation Number.
2995
- */
2996
- GSRN: "GSRN",
2997
- /**
2998
- * Global Document Type Identifier.
2999
- */
3000
- GDTI: "GDTI",
3001
- /**
3002
- * Global Identification Number for Consignment.
3003
- */
3004
- GINC: "GINC",
3005
- /**
3006
- * Global Shipment Identification Number.
3007
- */
3008
- GSIN: "GSIN",
3009
- /**
3010
- * Global Coupon Number.
3011
- */
3012
- GCN: "GCN",
3013
- /**
3014
- * Component/Part Identifier.
3015
- */
3016
- CPID: "CPID",
3017
- /**
3018
- * Global Model Number.
3019
- */
3020
- GMN: "GMN"
3021
- };
3022
-
3023
- // src/numeric-identifier-type.ts
3024
- var LeaderTypes = {
3025
- /**
3026
- * No leader.
3027
- */
3028
- None: "None",
3029
- /**
3030
- * Indicator digit (GTIN only).
3031
- */
3032
- IndicatorDigit: "Indicator digit",
3033
- /**
3034
- * Extension digit (SSCC only).
3035
- */
3036
- ExtensionDigit: "Extension digit"
3037
- };
3038
-
3039
- // src/gtin-type.ts
3040
- var GTINTypes = {
3041
- /**
3042
- * GTIN-13.
3043
- */
3044
- GTIN13: 13,
3045
- /**
3046
- * GTIN-12.
3047
- */
3048
- GTIN12: 12,
3049
- /**
3050
- * GTIN-8.
3051
- */
3052
- GTIN8: 8,
3053
- /**
3054
- * GTIN-14.
3055
- */
3056
- GTIN14: 14
3057
- };
3058
- var GTIN_BASE_TYPES = {
3059
- [PrefixTypes.GS1CompanyPrefix]: GTINTypes.GTIN13,
3060
- [PrefixTypes.UPCCompanyPrefix]: GTINTypes.GTIN12,
3061
- [PrefixTypes.GS18Prefix]: GTINTypes.GTIN8
3062
- };
3063
-
3064
- // src/descriptors.ts
3065
- var GTIN13_DESCRIPTOR = {
3066
- identifierType: IdentifierTypes.GTIN,
3067
- prefixType: PrefixTypes.GS1CompanyPrefix,
3068
- length: GTINTypes.GTIN13,
3069
- referenceCharacterSet: ContentCharacterSets.Numeric,
3070
- leaderType: LeaderTypes.IndicatorDigit
3071
- };
3072
- var GTIN12_DESCRIPTOR = {
3073
- identifierType: IdentifierTypes.GTIN,
3074
- prefixType: PrefixTypes.UPCCompanyPrefix,
3075
- length: GTINTypes.GTIN12,
3076
- referenceCharacterSet: ContentCharacterSets.Numeric,
3077
- leaderType: LeaderTypes.IndicatorDigit
3078
- };
3079
- var GTIN8_DESCRIPTOR = {
3080
- identifierType: IdentifierTypes.GTIN,
3081
- prefixType: PrefixTypes.GS18Prefix,
3082
- length: GTINTypes.GTIN8,
3083
- referenceCharacterSet: ContentCharacterSets.Numeric,
3084
- leaderType: LeaderTypes.IndicatorDigit
3085
- };
3086
- var GTIN_DESCRIPTORS = {
3087
- [GTINTypes.GTIN13]: GTIN13_DESCRIPTOR,
3088
- [GTINTypes.GTIN12]: GTIN12_DESCRIPTOR,
3089
- [GTINTypes.GTIN8]: GTIN8_DESCRIPTOR
3090
- };
3091
- var GLN_DESCRIPTOR = {
3092
- identifierType: IdentifierTypes.GLN,
3093
- prefixType: PrefixTypes.GS1CompanyPrefix,
3094
- length: 13,
3095
- referenceCharacterSet: ContentCharacterSets.Numeric,
3096
- leaderType: LeaderTypes.None
3097
- };
3098
- var SSCC_DESCRIPTOR = {
3099
- identifierType: IdentifierTypes.SSCC,
3100
- prefixType: PrefixTypes.GS1CompanyPrefix,
3101
- length: 18,
3102
- referenceCharacterSet: ContentCharacterSets.Numeric,
3103
- leaderType: LeaderTypes.ExtensionDigit
3104
- };
3105
- var GRAI_DESCRIPTOR = {
3106
- identifierType: IdentifierTypes.GRAI,
3107
- prefixType: PrefixTypes.GS1CompanyPrefix,
3108
- length: 13,
3109
- referenceCharacterSet: ContentCharacterSets.Numeric,
3110
- leaderType: LeaderTypes.None,
3111
- serialComponentLength: 16,
3112
- serialComponentCharacterSet: ContentCharacterSets.AI82
3113
- };
3114
- var GIAI_DESCRIPTOR = {
3115
- identifierType: IdentifierTypes.GIAI,
3116
- prefixType: PrefixTypes.GS1CompanyPrefix,
3117
- length: 30,
3118
- referenceCharacterSet: ContentCharacterSets.AI82,
3119
- requiresCheckCharacterPair: false
3120
- };
3121
- var GSRN_DESCRIPTOR = {
3122
- identifierType: IdentifierTypes.GSRN,
3123
- prefixType: PrefixTypes.GS1CompanyPrefix,
3124
- length: 18,
3125
- referenceCharacterSet: ContentCharacterSets.Numeric,
3126
- leaderType: LeaderTypes.None
3127
- };
3128
- var GDTI_DESCRIPTOR = {
3129
- identifierType: IdentifierTypes.GDTI,
3130
- prefixType: PrefixTypes.GS1CompanyPrefix,
3131
- length: 13,
3132
- referenceCharacterSet: ContentCharacterSets.Numeric,
3133
- leaderType: LeaderTypes.None,
3134
- serialComponentLength: 17,
3135
- serialComponentCharacterSet: ContentCharacterSets.AI82
3136
- };
3137
- var GINC_DESCRIPTOR = {
3138
- identifierType: IdentifierTypes.GINC,
3139
- prefixType: PrefixTypes.GS1CompanyPrefix,
3140
- length: 30,
3141
- referenceCharacterSet: ContentCharacterSets.AI82,
3142
- requiresCheckCharacterPair: false
3143
- };
3144
- var GSIN_DESCRIPTOR = {
3145
- identifierType: IdentifierTypes.GSIN,
3146
- prefixType: PrefixTypes.GS1CompanyPrefix,
3147
- length: 17,
3148
- referenceCharacterSet: ContentCharacterSets.Numeric,
3149
- leaderType: LeaderTypes.None
3150
- };
3151
- var GCN_DESCRIPTOR = {
3152
- identifierType: IdentifierTypes.GCN,
3153
- prefixType: PrefixTypes.GS1CompanyPrefix,
3154
- length: 13,
3155
- referenceCharacterSet: ContentCharacterSets.Numeric,
3156
- leaderType: LeaderTypes.None,
3157
- serialComponentLength: 12,
3158
- serialComponentCharacterSet: ContentCharacterSets.Numeric
3159
- };
3160
- var CPID_DESCRIPTOR = {
3161
- identifierType: IdentifierTypes.CPID,
3162
- prefixType: PrefixTypes.GS1CompanyPrefix,
3163
- length: 30,
3164
- referenceCharacterSet: ContentCharacterSets.AI39,
3165
- requiresCheckCharacterPair: false
3166
- };
3167
- var GMN_DESCRIPTOR = {
3168
- identifierType: IdentifierTypes.GMN,
3169
- prefixType: PrefixTypes.GS1CompanyPrefix,
3170
- length: 25,
3171
- referenceCharacterSet: ContentCharacterSets.AI82,
3172
- requiresCheckCharacterPair: true
3173
- };
3174
- var IdentifierDescriptors = {
3175
- [IdentifierTypes.GTIN]: GTIN_DESCRIPTORS,
3176
- [IdentifierTypes.GLN]: GLN_DESCRIPTOR,
3177
- [IdentifierTypes.SSCC]: SSCC_DESCRIPTOR,
3178
- [IdentifierTypes.GRAI]: GRAI_DESCRIPTOR,
3179
- [IdentifierTypes.GIAI]: GIAI_DESCRIPTOR,
3180
- [IdentifierTypes.GSRN]: GSRN_DESCRIPTOR,
3181
- [IdentifierTypes.GDTI]: GDTI_DESCRIPTOR,
3182
- [IdentifierTypes.GINC]: GINC_DESCRIPTOR,
3183
- [IdentifierTypes.GSIN]: GSIN_DESCRIPTOR,
3184
- [IdentifierTypes.GCN]: GCN_DESCRIPTOR,
3185
- [IdentifierTypes.CPID]: CPID_DESCRIPTOR,
3186
- [IdentifierTypes.GMN]: GMN_DESCRIPTOR
3187
- };
3188
- function isGTINDescriptors(identifierDescriptorsOrDescriptor) {
3189
- return !("identifierType" in identifierDescriptorsOrDescriptor);
3190
- }
3191
- function identifierTypesIncludes(identifierTypes, identifierType) {
3192
- return identifierTypes.includes(identifierType);
3193
- }
3194
- var NUMERIC_IDENTIFIER_TYPES = [IdentifierTypes.GTIN, IdentifierTypes.GLN, IdentifierTypes.SSCC, IdentifierTypes.GRAI, IdentifierTypes.GSRN, IdentifierTypes.GDTI, IdentifierTypes.GSIN, IdentifierTypes.GCN];
3195
- function isNumericIdentifierDescriptor(identifierDescriptor) {
3196
- return identifierTypesIncludes(NUMERIC_IDENTIFIER_TYPES, identifierDescriptor.identifierType);
3197
- }
3198
- function isGTINDescriptor(identifierDescriptor) {
3199
- return identifierDescriptor.identifierType === IdentifierTypes.GTIN;
3200
- }
3201
- function isNonGTINNumericIdentifierDescriptor(identifierDescriptor) {
3202
- return isNumericIdentifierDescriptor(identifierDescriptor) && !isGTINDescriptor(identifierDescriptor);
3203
- }
3204
- var SERIALIZABLE_NUMERIC_IDENTIFIER_TYPES = [IdentifierTypes.GRAI, IdentifierTypes.GDTI, IdentifierTypes.GCN];
3205
- function isSerializableNumericIdentifierDescriptor(identifierDescriptor) {
3206
- return identifierTypesIncludes(SERIALIZABLE_NUMERIC_IDENTIFIER_TYPES, identifierDescriptor.identifierType);
3207
- }
3208
- function isNonNumericIdentifierDescriptor(identifierDescriptor) {
3209
- return !isNumericIdentifierDescriptor(identifierDescriptor);
3210
- }
3211
-
3212
- // src/gtin-validator.ts
3213
- var import_utility6 = require("@aidc-toolkit/utility");
3214
-
3215
- // src/abstract-identifier-validator.ts
3216
- var import_utility5 = require("@aidc-toolkit/utility");
3217
- var AbstractIdentifierValidator = class _AbstractIdentifierValidator {
3218
- static CHARACTER_SET_CREATORS = {
3219
- [ContentCharacterSets.Numeric]: import_utility5.NUMERIC_CREATOR,
3220
- [ContentCharacterSets.AI82]: AI82_CREATOR,
3221
- [ContentCharacterSets.AI39]: AI39_CREATOR
3222
- };
3223
- /**
3224
- * Identifier type.
3225
- */
3226
- _identifierType;
3227
- /**
3228
- * Length.
3229
- */
3230
- _length;
3231
- /**
3232
- * Reference character set.
3233
- */
3234
- _referenceCharacterSet;
3235
- /**
3236
- * Reference creator.
3237
- */
3238
- _referenceCreator;
3239
- /**
3240
- * Get the character set creator for a character set.
3241
- *
3242
- * @param characterSet
3243
- * Character set.
3244
- *
3245
- * @returns
3246
- * Character set creator.
3247
- */
3248
- static creatorFor(characterSet) {
3249
- return _AbstractIdentifierValidator.CHARACTER_SET_CREATORS[characterSet];
3250
- }
3251
- /**
3252
- * Constructor.
3253
- *
3254
- * @param identifierDescriptor
3255
- * Identifier descriptor.
3256
- */
3257
- constructor(identifierDescriptor) {
3258
- this._identifierType = identifierDescriptor.identifierType;
3259
- this._length = identifierDescriptor.length;
3260
- this._referenceCharacterSet = identifierDescriptor.referenceCharacterSet;
3261
- this._referenceCreator = _AbstractIdentifierValidator.creatorFor(identifierDescriptor.referenceCharacterSet);
3262
- }
3263
- /**
3264
- * @inheritDoc
3265
- */
3266
- get identifierType() {
3267
- return this._identifierType;
3268
- }
3269
- /**
3270
- * @inheritDoc
3271
- */
3272
- get prefixType() {
3273
- return PrefixTypes.GS1CompanyPrefix;
3274
- }
3275
- /**
3276
- * @inheritDoc
3277
- */
3278
- get length() {
3279
- return this._length;
3280
- }
3281
- /**
3282
- * @inheritDoc
3283
- */
3284
- get referenceCharacterSet() {
3285
- return this._referenceCharacterSet;
3286
- }
3287
- /**
3288
- * @inheritDoc
3289
- */
3290
- get referenceCreator() {
3291
- return this._referenceCreator;
3292
- }
3293
- /**
3294
- * Pad an identifier on the left with zero-value character for validation purposes. This is done to align an
3295
- * identifier with a position offset for any error message that may be thrown by the reference validator.
3296
- *
3297
- * @param identifier
3298
- * Identifier.
3299
- *
3300
- * @param positionOffset
3301
- * Position offset within a larger string.
3302
- *
3303
- * @returns
3304
- * Padded identifier.
3305
- */
3306
- padIdentifier(identifier, positionOffset) {
3307
- return positionOffset === void 0 ? identifier : this.referenceCreator.character(0).repeat(positionOffset).concat(identifier);
3308
- }
3309
- /**
3310
- * Validate the prefix within an identifier.
3311
- *
3312
- * @param partialIdentifier
3313
- * Partial identifier.
3314
- *
3315
- * @param positionOffset
3316
- * Position offset within a larger string.
3317
- */
3318
- validatePrefix(partialIdentifier, positionOffset) {
3319
- PrefixValidator.validate(this.prefixType, true, false, partialIdentifier, true, this.referenceCharacterSet === ContentCharacterSets.Numeric, positionOffset);
3320
- }
3321
- };
3322
-
3323
- // src/abstract-numeric-identifier-validator.ts
3324
- var AbstractNumericIdentifierValidator = class extends AbstractIdentifierValidator {
3325
- /**
3326
- * Leader type.
3327
- */
3328
- _leaderType;
3329
- /**
3330
- * Prefix position, determined by the leader type.
3331
- */
3332
- _prefixPosition;
3333
- /**
3334
- * Constructor.
3335
- *
3336
- * @param identifierDescriptor
3337
- * Identifier descriptor.
3338
- */
3339
- constructor(identifierDescriptor) {
3340
- super(identifierDescriptor);
3341
- this._leaderType = identifierDescriptor.leaderType;
3342
- this._prefixPosition = Number(this.leaderType === LeaderTypes.ExtensionDigit);
3343
- }
3344
- /**
3345
- * @inheritDoc
3346
- */
3347
- get leaderType() {
3348
- return this._leaderType;
3349
- }
3350
- /**
3351
- * @inheritDoc
3352
- */
3353
- validate(identifier, validation) {
3354
- if (this._prefixPosition === 0) {
3355
- super.validatePrefix(identifier, validation?.positionOffset);
3356
- } else {
3357
- super.validatePrefix(identifier.substring(this._prefixPosition), validation?.positionOffset === void 0 ? this._prefixPosition : validation.positionOffset + this._prefixPosition);
3358
- }
3359
- if (identifier.length !== this.length) {
3360
- throw new RangeError(i18nextGS1.t("Identifier.identifierTypeLength", {
3361
- identifierType: this.identifierType,
3362
- length: this.length
3363
- }));
3364
- }
3365
- if (!hasValidCheckDigit(this.padIdentifier(identifier, validation?.positionOffset))) {
3366
- throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3367
- }
3368
- }
3369
- };
3370
-
3371
- // src/gtin-validator.ts
3372
- var GTINLevels = {
3373
- /**
3374
- * Any level (level is ignored).
3375
- */
3376
- Any: 0,
3377
- /**
3378
- * Retail consumer trade item level, supporting GTIN-13, GTIN-12 (optionally zero-suppressed), and GTIN-8.
3379
- */
3380
- RetailConsumer: 1,
3381
- /**
3382
- * Other than retail consumer trade item level, supporting GTIN-13, GTIN-12 (not zero-suppressed), and GTIN-14.
3383
- */
3384
- OtherThanRetailConsumer: 2
3385
- };
3386
- var GTINValidator = class _GTINValidator extends AbstractNumericIdentifierValidator {
3387
- /**
3388
- * Validation parameters for optional indicator digit.
3389
- */
3390
- static OPTIONAL_INDICATOR_DIGIT_VALIDATION = {
3391
- minimumLength: 0,
3392
- maximumLength: 1,
3393
- component: () => i18nextGS1.t("Identifier.indicatorDigit")
3394
- };
3395
- /**
3396
- * Validation parameters for zero-suppressed GTIN-12.
3397
- */
3398
- static ZERO_SUPPRESSED_GTIN12_VALIDATION = {
3399
- minimumLength: 8,
3400
- maximumLength: 8
3401
- };
3402
- /**
3403
- * Prefix type.
3404
- */
3405
- _prefixType;
3406
- /**
3407
- * Constructor.
3408
- *
3409
- * @param gtinBaseType
3410
- * GTIN base type (all except GTIN-14).
3411
- */
3412
- constructor(gtinBaseType) {
3413
- const identifierDescriptor = IdentifierDescriptors.GTIN[gtinBaseType];
3414
- super(identifierDescriptor);
3415
- this._prefixType = identifierDescriptor.prefixType;
3416
- }
3417
- /**
3418
- * @inheritDoc
3419
- */
3420
- get prefixType() {
3421
- return this._prefixType;
3422
- }
3423
- /**
3424
- * @inheritDoc
3425
- */
3426
- get gtinType() {
3427
- return this.length;
3428
- }
3429
- /**
3430
- * @inheritDoc
3431
- */
3432
- validatePrefix(partialIdentifier, positionOffset) {
3433
- PrefixValidator.validate(this.prefixType, false, false, partialIdentifier, true, true, positionOffset);
3434
- }
3435
- /**
3436
- * Zero suppress a GTIN-12.
3437
- *
3438
- * @param gtin12
3439
- * GTIN-12.
3440
- *
3441
- * @returns
3442
- * Zero-suppressed GTIN-12.
3443
- */
3444
- static zeroSuppress(gtin12) {
3445
- GTIN12_VALIDATOR.validate(gtin12);
3446
- const d = Array.from(gtin12);
3447
- let zeroSuppressedGTIN12;
3448
- if (d[0] === "0" && d[6] === "0" && d[7] === "0") {
3449
- if (d[10] >= "5" && d[8] === "0" && d[9] === "0" && d[5] !== "0") {
3450
- zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[5]}${d[10]}${d[11]}`;
3451
- } else if (d[5] === "0" && d[8] === "0" && d[9] === "0" && d[4] !== "0") {
3452
- zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[10]}4${d[11]}`;
3453
- } else if (d[3] <= "2" && d[4] === "0" && d[5] === "0") {
3454
- zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[8]}${d[9]}${d[10]}${d[3]}${d[11]}`;
3455
- } else if (d[3] >= "3" && d[4] === "0" && d[5] === "0" && d[8] === "0") {
3456
- zeroSuppressedGTIN12 = `0${d[1]}${d[2]}${d[3]}${d[9]}${d[10]}3${d[11]}`;
3457
- }
3458
- }
3459
- if (zeroSuppressedGTIN12 === void 0) {
3460
- throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressibleGTIN12"));
3461
- }
3462
- return zeroSuppressedGTIN12;
3463
- }
3464
- /**
3465
- * Zero expand a zero-suppressed GTIN-12.
3466
- *
3467
- * @param zeroSuppressedGTIN12
3468
- * Zero-suppressed GTIN-12.
3469
- *
3470
- * @returns
3471
- * GTIN-12.
3472
- */
3473
- static zeroExpand(zeroSuppressedGTIN12) {
3474
- import_utility6.NUMERIC_CREATOR.validate(zeroSuppressedGTIN12, _GTINValidator.ZERO_SUPPRESSED_GTIN12_VALIDATION);
3475
- const d = Array.from(zeroSuppressedGTIN12);
3476
- let gtin12;
3477
- if (d[0] === "0") {
3478
- if (d[6] >= "5" && d[5] !== "0") {
3479
- gtin12 = `0${d[1]}${d[2]}${d[3]}${d[4]}${d[5]}0000${d[6]}${d[7]}`;
3480
- } else if (d[6] === "4" && d[4] !== "0") {
3481
- gtin12 = `0${d[1]}${d[2]}${d[3]}${d[4]}00000${d[5]}${d[7]}`;
3482
- } else if (d[6] <= "2") {
3483
- gtin12 = `0${d[1]}${d[2]}${d[6]}0000${d[3]}${d[4]}${d[5]}${d[7]}`;
3484
- } else if (d[6] === "3" && d[3] >= "3") {
3485
- gtin12 = `0${d[1]}${d[2]}${d[3]}00000${d[4]}${d[5]}${d[7]}`;
3486
- }
3487
- }
3488
- if (gtin12 === void 0) {
3489
- throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12"));
3490
- }
3491
- GTIN12_VALIDATOR.validate(gtin12);
3492
- return gtin12;
3493
- }
3494
- /**
3495
- * Convert a GTIN of any length to a GTIN-14 with an optional indicator digit.
3496
- *
3497
- * @param indicatorDigit
3498
- * Indicator digit. If blank, assumes "0" if the GTIN is not already a GTIN-14.
3499
- *
3500
- * @param gtin
3501
- * GTIN.
3502
- *
3503
- * @returns
3504
- * GTIN-14.
3505
- */
3506
- static convertToGTIN14(indicatorDigit, gtin) {
3507
- _GTINValidator.validateAny(gtin);
3508
- import_utility6.NUMERIC_CREATOR.validate(indicatorDigit, _GTINValidator.OPTIONAL_INDICATOR_DIGIT_VALIDATION);
3509
- let gtin14 = gtin.padStart(GTINTypes.GTIN14, "0");
3510
- if (indicatorDigit.length !== 0 && indicatorDigit !== gtin14.charAt(0)) {
3511
- const partialGTIN14 = indicatorDigit + gtin14.substring(1, GTINTypes.GTIN14 - 1);
3512
- gtin14 = partialGTIN14 + checkDigit(partialGTIN14);
3513
- }
3514
- return gtin14;
3515
- }
3516
- /**
3517
- * Normalize a GTIN of any length.
3518
- * - A GTIN-14 that starts with six zeros or a GTIN-13 that starts with five zeros is normalized to GTIN-8.
3519
- * - A GTIN-14 that starts with two zeros or a GTIN-13 that starts with one zero is normalized to GTIN-12.
3520
- * - A GTIN-14 that starts with one zero is normalized to GTIN-13.
3521
- * - Otherwise, the GTIN is unchanged.
3522
- *
3523
- * @param gtin
3524
- * GTIN.
3525
- *
3526
- * @returns
3527
- * Normalized GTIN.
3528
- */
3529
- static normalize(gtin) {
3530
- const gtinLength = gtin.length;
3531
- let normalizedGTIN;
3532
- switch (gtinLength) {
3533
- case GTINTypes.GTIN13:
3534
- if (!gtin.startsWith("0")) {
3535
- normalizedGTIN = gtin;
3536
- } else if (!gtin.startsWith("00000")) {
3537
- normalizedGTIN = gtin.substring(1);
3538
- } else if (!gtin.startsWith("000000")) {
3539
- normalizedGTIN = gtin.substring(5);
3540
- } else {
3541
- throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12AsGTIN13"));
3542
- }
3543
- break;
3544
- case GTINTypes.GTIN12:
3545
- normalizedGTIN = gtin;
3546
- break;
3547
- case GTINTypes.GTIN8:
3548
- if (!gtin.startsWith("0")) {
3549
- normalizedGTIN = gtin;
3550
- } else {
3551
- normalizedGTIN = _GTINValidator.zeroExpand(gtin);
3552
- }
3553
- break;
3554
- case GTINTypes.GTIN14:
3555
- if (!gtin.startsWith("0")) {
3556
- normalizedGTIN = gtin;
3557
- } else if (!gtin.startsWith("00")) {
3558
- normalizedGTIN = gtin.substring(1);
3559
- } else if (!gtin.startsWith("000000")) {
3560
- normalizedGTIN = gtin.substring(2);
3561
- } else if (!gtin.startsWith("0000000")) {
3562
- normalizedGTIN = gtin.substring(6);
3563
- } else {
3564
- throw new RangeError(i18nextGS1.t("Identifier.invalidZeroSuppressedGTIN12AsGTIN14"));
3565
- }
3566
- break;
3567
- default:
3568
- throw new RangeError(i18nextGS1.t("Identifier.invalidGTINLength"));
3569
- }
3570
- _GTINValidator.validateAny(normalizedGTIN);
3571
- return normalizedGTIN;
3572
- }
3573
- /**
3574
- * Validate any GTIN, optionally against a level.
3575
- *
3576
- * @param gtin
3577
- * GTIN.
3578
- *
3579
- * @param gtinLevel
3580
- * Level at which GTIN is to be validated.
3581
- */
3582
- static validateAny(gtin, gtinLevel = GTINLevels.Any) {
3583
- let lengthValidatedGTIN = gtin;
3584
- let gtinLevelRestriction;
3585
- switch (gtin.length) {
3586
- case GTINTypes.GTIN13:
3587
- if (gtin.startsWith("0")) {
3588
- throw new RangeError(i18nextGS1.t("Identifier.invalidGTIN13AtRetail"));
3589
- }
3590
- PrefixValidator.validate(PrefixTypes.GS1CompanyPrefix, false, false, gtin, true, true);
3591
- gtinLevelRestriction = GTINLevels.Any;
3592
- break;
3593
- case GTINTypes.GTIN12:
3594
- PrefixValidator.validate(PrefixTypes.UPCCompanyPrefix, false, false, gtin, true, true);
3595
- gtinLevelRestriction = GTINLevels.Any;
3596
- break;
3597
- case GTINTypes.GTIN8:
3598
- if (!gtin.startsWith("0")) {
3599
- PrefixValidator.validate(PrefixTypes.GS18Prefix, false, false, gtin, true, true);
3600
- } else {
3601
- lengthValidatedGTIN = _GTINValidator.zeroExpand(gtin);
3602
- }
3603
- gtinLevelRestriction = GTINLevels.RetailConsumer;
3604
- break;
3605
- case GTINTypes.GTIN14:
3606
- PrefixValidator.validate(PrefixTypes.GS1CompanyPrefix, true, true, gtin.substring(1), true, true);
3607
- gtinLevelRestriction = GTINLevels.OtherThanRetailConsumer;
3608
- break;
3609
- default:
3610
- throw new RangeError(i18nextGS1.t("Identifier.invalidGTINLength"));
3611
- }
3612
- if (!hasValidCheckDigit(lengthValidatedGTIN)) {
3613
- throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3614
- }
3615
- if (gtinLevel !== GTINLevels.Any && gtinLevelRestriction !== GTINLevels.Any && gtinLevelRestriction !== gtinLevel) {
3616
- throw new RangeError(i18nextGS1.t(gtinLevel === GTINLevels.RetailConsumer ? "Identifier.invalidGTINAtRetail" : "Identifier.invalidGTINAtOtherThanRetail"));
3617
- }
3618
- }
3619
- /**
3620
- * Validate a GTIN-14.
3621
- *
3622
- * @param gtin14
3623
- * GTIN-14.
3624
- */
3625
- static validateGTIN14(gtin14) {
3626
- if (gtin14.length !== GTINTypes.GTIN14) {
3627
- throw new RangeError(i18nextGS1.t("Identifier.invalidGTIN14Length"));
3628
- }
3629
- _GTINValidator.validateAny(gtin14);
3630
- }
3631
- /**
3632
- * Parse a Restricted Circulation Number (RCN) using a variable measure trade item format. The format is a 12- or
3633
- * 13-character string (for RCN-12 or RCN-13 respectively), containing the following:
3634
- *
3635
- * - '2' - The first character of the RCN.
3636
- * - '0'-'9' - The second character of the RCN (RCN-13 only).
3637
- * - 'I' - One or more, in sequence, for the item reference.
3638
- * - 'P' - One or more, in sequence, for the price or weight.
3639
- * - 'V' - Zero or one, for the price or weight check digit.
3640
- * - 'C' - The check digit of the entire RCN.
3641
- *
3642
- * The 'I', 'P', and 'V' formats may be in any order.
3643
- *
3644
- * Some examples:
3645
- *
3646
- * - 2IIIIIVPPPPC - RCN-12 with a five-digit item reference, a price or weight check digit, and a four-digit price
3647
- * or weight.
3648
- * - 23IIIIVPPPPPC - RCN-13 with a four-digit item reference, a price or weight check digit, and a five-digit price
3649
- * or weight.
3650
- * - 2IIIIIIPPPPC - RCN-12 with a six-digit item reference and a four-digit price or eight.
3651
- * - 29IIIIIPPPPPC - RCN-13 with a five-digit item reference and a five-digit price or weight.
3652
- *
3653
- * @param format
3654
- * Format.
3655
- *
3656
- * @param rcn
3657
- * RCN.
3658
- *
3659
- * @returns
3660
- * RCN reference.
3661
- */
3662
- static parseVariableMeasureRCN(format, rcn) {
3663
- const formatLength = format.length;
3664
- if (rcn.length !== formatLength) {
3665
- throw new RangeError(i18nextGS1.t("Identifier.invalidRCNLength"));
3666
- }
3667
- let validFormat = formatLength === 12 || formatLength === 13;
3668
- let validRCNPrefix = true;
3669
- let buildingItemReference = false;
3670
- let itemReference = "";
3671
- let buildingPriceOrWeight = false;
3672
- let priceOrWeight = "";
3673
- let priceOrWeightCheckDigit2 = "";
3674
- for (let index = 0; validFormat && index < formatLength; index++) {
3675
- const formatChar = format.charAt(index);
3676
- const rcnChar = rcn.charAt(index);
3677
- if (index === 0) {
3678
- validFormat = formatChar === "2";
3679
- validRCNPrefix = rcnChar === "2";
3680
- } else if (formatLength === 13 && index === 1) {
3681
- validFormat = import_utility6.NUMERIC_CREATOR.characterIndex(formatChar) !== void 0;
3682
- validRCNPrefix = rcnChar === formatChar;
3683
- } else if (index === formatLength - 1) {
3684
- validFormat = formatChar === "C";
3685
- } else {
3686
- switch (formatChar) {
3687
- case "I":
3688
- if (!buildingItemReference) {
3689
- validFormat = itemReference === "";
3690
- buildingItemReference = true;
3691
- buildingPriceOrWeight = false;
3692
- }
3693
- itemReference += rcnChar;
3694
- break;
3695
- case "P":
3696
- if (!buildingPriceOrWeight) {
3697
- validFormat = priceOrWeight === "";
3698
- buildingPriceOrWeight = true;
3699
- buildingItemReference = false;
3700
- }
3701
- priceOrWeight += rcnChar;
3702
- break;
3703
- case "V":
3704
- validFormat = priceOrWeightCheckDigit2 === "";
3705
- buildingItemReference = false;
3706
- buildingPriceOrWeight = false;
3707
- priceOrWeightCheckDigit2 = rcnChar;
3708
- break;
3709
- default:
3710
- validFormat = false;
3711
- break;
3712
- }
3713
- }
3714
- }
3715
- validFormat &&= itemReference !== "" && priceOrWeight !== "";
3716
- if (!validFormat) {
3717
- throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNFormat"));
3718
- }
3719
- if (!validRCNPrefix) {
3720
- throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNPrefix"));
3721
- }
3722
- if (priceOrWeightCheckDigit2 !== "" && !isValidPriceOrWeightCheckDigit(priceOrWeight, priceOrWeightCheckDigit2)) {
3723
- throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasurePriceOrWeight"));
3724
- }
3725
- if (!hasValidCheckDigit(rcn)) {
3726
- throw new RangeError(i18nextGS1.t("Identifier.invalidCheckDigit"));
3727
- }
3728
- return {
3729
- itemReference: Number(itemReference),
3730
- priceOrWeight: Number(priceOrWeight)
3731
- };
3732
- }
3733
- };
3734
- var GTIN13_VALIDATOR = new GTINValidator(GTINTypes.GTIN13);
3735
- var GTIN12_VALIDATOR = new GTINValidator(GTINTypes.GTIN12);
3736
- var GTIN8_VALIDATOR = new GTINValidator(GTINTypes.GTIN8);
3737
- var GTIN_VALIDATORS = {
3738
- [GTINTypes.GTIN13]: GTIN13_VALIDATOR,
3739
- [GTINTypes.GTIN12]: GTIN12_VALIDATOR,
3740
- [GTINTypes.GTIN8]: GTIN8_VALIDATOR
3741
- };
3742
-
3743
- // src/non-gtin-numeric-identifier-validator.ts
3744
- var NonGTINNumericIdentifierValidator = class extends AbstractNumericIdentifierValidator {
3745
- /**
3746
- * Constructor.
3747
- *
3748
- * @param identifierType
3749
- * Identifier type.
3750
- */
3751
- constructor(identifierType) {
3752
- super(IdentifierDescriptors[identifierType]);
3753
- }
3754
- };
3755
-
3756
- // src/serializable-numeric-identifier-validator.ts
3757
- var SerializableNumericIdentifierValidator = class _SerializableNumericIdentifierValidator extends AbstractNumericIdentifierValidator {
3758
- /**
3759
- * Serial component length.
3760
- */
3761
- _serialComponentLength;
3762
- /**
3763
- * Serial component character set.
3764
- */
3765
- _serialComponentCharacterSet;
3766
- /**
3767
- * Serial component validation parameters.
3768
- */
3769
- _serialComponentValidation;
3770
- /**
3771
- * Serial component creator.
3772
- */
3773
- _serialComponentCreator;
3774
- /**
3775
- * Constructor.
3776
- *
3777
- * @param identifierType
3778
- * Identifier type.
3779
- */
3780
- constructor(identifierType) {
3781
- const identifierDescriptor = IdentifierDescriptors[identifierType];
3782
- super(identifierDescriptor);
3783
- this._serialComponentLength = identifierDescriptor.serialComponentLength;
3784
- this._serialComponentCharacterSet = identifierDescriptor.serialComponentCharacterSet;
3785
- this._serialComponentValidation = {
3786
- minimumLength: 1,
3787
- maximumLength: identifierDescriptor.serialComponentLength,
3788
- component: () => i18nextGS1.t("Identifier.serialComponent")
3789
- };
3790
- this._serialComponentCreator = _SerializableNumericIdentifierValidator.creatorFor(identifierDescriptor.serialComponentCharacterSet);
3791
- }
3792
- /**
3793
- * Get the serial component length.
3794
- */
3795
- get serialComponentLength() {
3796
- return this._serialComponentLength;
3797
- }
3798
- /**
3799
- * Get the serial component character set.
3800
- */
3801
- get serialComponentCharacterSet() {
3802
- return this._serialComponentCharacterSet;
3803
- }
3804
- /**
3805
- * Get the serial component validation parameters.
3806
- */
3807
- get serialComponentValidation() {
3808
- return this._serialComponentValidation;
3809
- }
3810
- /**
3811
- * Get the serial component creator.
3812
- */
3813
- get serialComponentCreator() {
3814
- return this._serialComponentCreator;
3815
- }
3816
- /**
3817
- * @inheritDoc
3818
- */
3819
- validate(identifier, validation) {
3820
- super.validate(identifier.substring(0, this.length), validation);
3821
- if (identifier.length > this.length) {
3822
- this.serialComponentCreator.validate(identifier.substring(this.length), this._serialComponentValidation);
3823
- }
3824
- }
3825
- };
3826
-
3827
- // src/non-numeric-identifier-validator.ts
3828
- var import_utility7 = require("@aidc-toolkit/utility");
3829
- var NonNumericIdentifierValidator = class _NonNumericIdentifierValidator extends AbstractIdentifierValidator {
3830
- /**
3831
- * Validator to ensure that an identifier (minus check character pair) is not all numeric.
3832
- */
3833
- static NOT_ALL_NUMERIC_VALIDATOR = new class extends import_utility7.RegExpValidator {
3834
- /**
3835
- * @inheritDoc
3836
- */
3837
- createErrorMessage(_s) {
3838
- return i18nextGS1.t("Identifier.referenceCantBeAllNumeric");
3839
- }
3840
- }(/\D/);
3841
- /**
3842
- * True if the identifier requires a check character pair.
3843
- */
3844
- _requiresCheckCharacterPair;
3845
- /**
3846
- * Constructor.
3847
- *
3848
- * @param identifierType
3849
- * Identifier type.
3850
- */
3851
- constructor(identifierType) {
3852
- const identifierDescriptor = IdentifierDescriptors[identifierType];
3853
- super(identifierDescriptor);
3854
- this._requiresCheckCharacterPair = identifierDescriptor.requiresCheckCharacterPair;
3855
- }
3856
- /**
3857
- * Determine if the identifier requires a check character pair.
3858
- */
3859
- get requiresCheckCharacterPair() {
3860
- return this._requiresCheckCharacterPair;
3861
- }
3862
- /**
3863
- * Validate a non-numeric identifier and throw an error if validation fails.
3864
- *
3865
- * @param identifier
3866
- * Identifier.
3867
- *
3868
- * @param validation
3869
- * Validation parameters.
3870
- */
3871
- validate(identifier, validation) {
3872
- const partialIdentifier = this.requiresCheckCharacterPair ? identifier.substring(0, identifier.length - 2) : identifier;
3873
- super.validatePrefix(partialIdentifier);
3874
- if (!this.requiresCheckCharacterPair) {
3875
- this.referenceCreator.validate(identifier, {
3876
- maximumLength: this.length
3877
- });
3878
- } else if (!hasValidCheckCharacterPair(this.padIdentifier(identifier))) {
3879
- throw new RangeError(i18nextGS1.t("Identifier.invalidCheckCharacterPair"));
3880
- }
3881
- if (validation?.exclusion === import_utility7.Exclusions.AllNumeric) {
3882
- _NonNumericIdentifierValidator.NOT_ALL_NUMERIC_VALIDATOR.validate(partialIdentifier);
3883
- }
3884
- }
3885
- };
3886
-
3887
- // src/validators.ts
3888
- var GLN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GLN);
3889
- var SSCC_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.SSCC);
3890
- var GRAI_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GRAI);
3891
- var GIAI_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GIAI);
3892
- var GSRN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GSRN);
3893
- var GDTI_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GDTI);
3894
- var GINC_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GINC);
3895
- var GSIN_VALIDATOR = new NonGTINNumericIdentifierValidator(IdentifierTypes.GSIN);
3896
- var GCN_VALIDATOR = new SerializableNumericIdentifierValidator(IdentifierTypes.GCN);
3897
- var CPID_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.CPID);
3898
- var GMN_VALIDATOR = new NonNumericIdentifierValidator(IdentifierTypes.GMN);
3899
- var IdentifierValidators = {
3900
- [IdentifierTypes.GTIN]: GTIN_VALIDATORS,
3901
- [IdentifierTypes.GLN]: GLN_VALIDATOR,
3902
- [IdentifierTypes.SSCC]: SSCC_VALIDATOR,
3903
- [IdentifierTypes.GRAI]: GRAI_VALIDATOR,
3904
- [IdentifierTypes.GIAI]: GIAI_VALIDATOR,
3905
- [IdentifierTypes.GSRN]: GSRN_VALIDATOR,
3906
- [IdentifierTypes.GDTI]: GDTI_VALIDATOR,
3907
- [IdentifierTypes.GINC]: GINC_VALIDATOR,
3908
- [IdentifierTypes.GSIN]: GSIN_VALIDATOR,
3909
- [IdentifierTypes.GCN]: GCN_VALIDATOR,
3910
- [IdentifierTypes.CPID]: CPID_VALIDATOR,
3911
- [IdentifierTypes.GMN]: GMN_VALIDATOR
3912
- };
3913
- function isGTINValidators(identifierValidatorsOrValidator) {
3914
- return isGTINDescriptors(identifierValidatorsOrValidator);
3915
- }
3916
- function isNumericIdentifierValidator(identifierValidator) {
3917
- return isNumericIdentifierDescriptor(identifierValidator);
3918
- }
3919
- function isGTINValidator(identifierValidator) {
3920
- return isGTINDescriptor(identifierValidator);
3921
- }
3922
- function isNonGTINNumericIdentifierValidator(identifierValidator) {
3923
- return isNonGTINNumericIdentifierDescriptor(identifierValidator);
3924
- }
3925
- function isSerializableNumericIdentifierValidator(identifierValidator) {
3926
- return isSerializableNumericIdentifierDescriptor(identifierValidator);
3927
- }
3928
- function isNonNumericIdentifierValidator(identifierValidator) {
3929
- return isNonNumericIdentifierDescriptor(identifierValidator);
3930
- }
3931
-
3932
- // src/gtin-creator.ts
3933
- var import_utility9 = require("@aidc-toolkit/utility");
3934
- var import_ts_mixer = require("ts-mixer");
3935
-
3936
- // src/abstract-numeric-identifier-creator.ts
3937
- var import_utility8 = require("@aidc-toolkit/utility");
3938
-
3939
- // src/abstract-identifier-creator.ts
3940
- var AbstractIdentifierCreator = class {
3941
- /**
3942
- * Prefix provider.
3943
- */
3944
- _prefixProvider;
3945
- /**
3946
- * Reference length.
3947
- */
3948
- _referenceLength;
3949
- /**
3950
- * Initialize the prefix provider. This method is in lieu of a constructor due to the mixin architecture.
3951
- *
3952
- * @param prefixProvider
3953
- * Prefix provider.
3954
- *
3955
- * @param prefix
3956
- * Prefix within prefix provider to use to calculate reference length.
3957
- *
3958
- * @param checkAllowance
3959
- * Number of characters to allow for check digit or check character pair.
3960
- */
3961
- init(prefixProvider, prefix, checkAllowance) {
3962
- this._prefixProvider = prefixProvider;
3963
- this._referenceLength = this.length - prefix.length - checkAllowance;
3964
- }
3965
- /**
3966
- * @inheritDoc
3967
- */
3968
- get prefixProvider() {
3969
- return this._prefixProvider;
3970
- }
3971
- /**
3972
- * @inheritDoc
3973
- */
3974
- get prefix() {
3975
- return this.prefixProvider.gs1CompanyPrefix;
3976
- }
3977
- /**
3978
- * @inheritDoc
3979
- */
3980
- get referenceLength() {
3981
- return this._referenceLength;
3982
- }
3983
- };
3984
-
3985
- // src/abstract-numeric-identifier-creator.ts
3986
- var AbstractNumericIdentifierCreator = class _AbstractNumericIdentifierCreator extends AbstractIdentifierCreator {
3987
- /**
3988
- * Capacity.
3989
- */
3990
- _capacity;
3991
- /**
3992
- * Tweak for sparse creation.
3993
- */
3994
- _tweak = 0n;
3995
- /**
3996
- * Initialize the prefix provider. This method is in lieu of a constructor due to the mixin architecture.
3997
- *
3998
- * @param prefixProvider
3999
- * Prefix provider.
4000
- *
4001
- * @param prefix
4002
- * Prefix within prefix manager to use to calculate reference length.
4003
- */
4004
- init(prefixProvider, prefix) {
4005
- super.init(prefixProvider, prefix, 1);
4006
- this._capacity = Number(import_utility8.CharacterSetCreator.powerOf10(this.referenceLength));
4007
- }
4008
- /**
4009
- * @inheritDoc
4010
- */
4011
- get capacity() {
4012
- return this._capacity;
4013
- }
4014
- /**
4015
- * @inheritDoc
4016
- */
4017
- get tweak() {
4018
- return this._tweak;
4019
- }
4020
- /**
4021
- * @inheritDoc
4022
- */
4023
- set tweak(value) {
4024
- this._tweak = value;
4025
- }
4026
- /**
4027
- * Build an identifier from a reference by merging it with the prefix and adding the check digit.
4028
- *
4029
- * @param reference
4030
- * Identifier reference.
4031
- *
4032
- * @returns
4033
- * Identifier.
4034
- */
4035
- buildIdentifier(reference) {
4036
- const partialIdentifier = this.leaderType === LeaderTypes.ExtensionDigit ? reference.substring(0, 1) + this.prefix + reference.substring(1) : this.prefix + reference;
4037
- return partialIdentifier + checkDigit(partialIdentifier);
4038
- }
4039
- /**
4040
- * @inheritDoc
4041
- */
4042
- create(valueOrValues, sparse = false) {
4043
- return import_utility8.NUMERIC_CREATOR.create(this.referenceLength, valueOrValues, import_utility8.Exclusions.None, sparse ? this.tweak : void 0, (reference) => this.buildIdentifier(reference));
4044
- }
4045
- /**
4046
- * Create all identifiers from a partial identifier. Call is recursive until remaining reference
4047
- * length is 0.
4048
- *
4049
- * @param partialIdentifier
4050
- * Partial identifier. Initial value is `this.prefix`.
4051
- *
4052
- * @param remainingReferenceLength
4053
- * Remaining reference length. Initial value is `this.referenceLength`.
4054
- *
4055
- * @param extensionWeight
4056
- * If this value is not zero, the identifier has an extension digit, this call is setting it, and this value is
4057
- * applied to the calculation of the check digit.
4058
- *
4059
- * @param weight
4060
- * If the extension weight is zero, this value is applied to the calculation of the check digit.
4061
- *
4062
- * @param partialCheckDigitSum
4063
- * Partial check digit sum for the partial identifier.
4064
- *
4065
- * @yields
4066
- * Identifier.
4067
- */
4068
- static *createAllPartial(partialIdentifier, remainingReferenceLength, extensionWeight, weight, partialCheckDigitSum) {
4069
- if (remainingReferenceLength === 0) {
4070
- yield partialIdentifier + import_utility8.NUMERIC_CREATOR.character(9 - (partialCheckDigitSum + 9) % 10);
4071
- } else {
4072
- const nextRemainingReferenceLength = remainingReferenceLength - 1;
4073
- let nextPartialCheckDigitSum = partialCheckDigitSum;
4074
- if (extensionWeight !== 0) {
4075
- for (const c of import_utility8.NUMERIC_CREATOR.characterSet) {
4076
- yield* _AbstractNumericIdentifierCreator.createAllPartial(c + partialIdentifier, nextRemainingReferenceLength, 0, weight, nextPartialCheckDigitSum);
4077
- nextPartialCheckDigitSum += extensionWeight;
4078
- }
4079
- } else {
4080
- const nextWeight = 4 - weight;
4081
- for (const c of import_utility8.NUMERIC_CREATOR.characterSet) {
4082
- yield* _AbstractNumericIdentifierCreator.createAllPartial(partialIdentifier + c, nextRemainingReferenceLength, 0, nextWeight, nextPartialCheckDigitSum);
4083
- nextPartialCheckDigitSum += weight;
4084
- }
4085
- }
4086
- }
4087
- }
4088
- /**
4089
- * @inheritDoc
4090
- */
4091
- createAll() {
4092
- const hasExtensionDigit = this.leaderType === LeaderTypes.ExtensionDigit;
4093
- const prefix = this.prefix;
4094
- const length = this.length;
4095
- const referenceLength = this.referenceLength;
4096
- const startWeight = 3 - 2 * ((referenceLength + 1 - Number(hasExtensionDigit)) % 2);
4097
- return {
4098
- [Symbol.iterator]() {
4099
- return _AbstractNumericIdentifierCreator.createAllPartial(prefix, referenceLength, hasExtensionDigit ? 3 - 2 * length % 2 : 0, startWeight, checkDigitSum(startWeight === 3, prefix));
4100
- }
4101
- };
4102
- }
4103
- };
4104
-
4105
- // src/gtin-creator.ts
4106
- var GTINCreator = class _GTINCreator extends (0, import_ts_mixer.Mixin)(GTINValidator, AbstractNumericIdentifierCreator) {
4107
- /**
4108
- * Validation parameters for required indicator digit.
4109
- */
4110
- static REQUIRED_INDICATOR_DIGIT_VALIDATION = {
4111
- minimumLength: 1,
4112
- maximumLength: 1,
4113
- component: () => i18nextGS1.t("Identifier.indicatorDigit")
4114
- };
4115
- /**
4116
- * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4117
- * provider type.
4118
- *
4119
- * @param prefixProvider
4120
- * Prefix provider.
4121
- *
4122
- * @param gtinBaseType
4123
- * GTIN base type (all except GTIN-14).
4124
- */
4125
- constructor(prefixProvider, gtinBaseType) {
4126
- super(gtinBaseType);
4127
- this.init(prefixProvider, prefixProvider.prefix);
4128
- }
4129
- /**
4130
- * @inheritDoc
4131
- */
4132
- get prefix() {
4133
- return this.prefixProvider.prefix;
4134
- }
4135
- /**
4136
- * Create GTIN-14(s) with an indicator digit and reference(s) based on numeric value(s). The value(s) is/are
4137
- * converted to reference(s) of the appropriate length using {@linkcode NUMERIC_CREATOR}.
4138
- *
4139
- * @template TTransformerInput
4140
- * Transformer input type.
4141
- *
4142
- * @param indicatorDigit
4143
- * Indicator digit.
4144
- *
4145
- * @param valueOrValues
4146
- * Numeric value(s).
4147
- *
4148
- * @param sparse
4149
- * If true, the value(s) is/are mapped to a sparse sequence resistant to discovery. Default is false.
4150
- *
4151
- * @returns
4152
- * GTIN-14(s).
4153
- */
4154
- createGTIN14(indicatorDigit, valueOrValues, sparse = false) {
4155
- import_utility9.NUMERIC_CREATOR.validate(indicatorDigit, _GTINCreator.REQUIRED_INDICATOR_DIGIT_VALIDATION);
4156
- return import_utility9.NUMERIC_CREATOR.create(GTINTypes.GTIN13 - this.prefixProvider.gs1CompanyPrefix.length - 1, valueOrValues, import_utility9.Exclusions.None, sparse ? this.tweak : void 0, (reference) => {
4157
- const partialIdentifier = indicatorDigit + this.prefixProvider.gs1CompanyPrefix + reference;
4158
- return partialIdentifier + checkDigit(partialIdentifier);
4159
- });
4160
- }
4161
- /**
4162
- * Create a Restricted Circulation Number (RCN) using a variable measure trade item format. See {@linkcode
4163
- * GTINValidator.parseVariableMeasureRCN} for format details.
4164
- *
4165
- * @param format
4166
- * Format.
4167
- *
4168
- * @param itemReference
4169
- * Item reference.
4170
- *
4171
- * @param priceOrWeight
4172
- * Price or weight (whole number only).
4173
- *
4174
- * @returns
4175
- * RCN-12 or RCN-13.
4176
- */
4177
- static createVariableMeasureRCN(format, itemReference, priceOrWeight) {
4178
- const formatLength = format.length;
4179
- let validFormat = formatLength === 12 || formatLength === 13;
4180
- let rcnPrefix = "";
4181
- let buildingItemReference = false;
4182
- let itemReferenceString = "";
4183
- let itemReferenceLength = 0;
4184
- let buildingPriceOrWeight = false;
4185
- let priceOrWeightString = "";
4186
- let priceOrWeightLength = 0;
4187
- let calculatePriceOrWeightCheckDigit = false;
4188
- const rcnPrefixBuilder = (partialRCN) => partialRCN + rcnPrefix;
4189
- const itemReferenceBuilder = (partialRCN) => partialRCN + itemReferenceString;
4190
- const priceOrWeightBuilder = (partialRCN) => partialRCN + priceOrWeightString;
4191
- const priceOrWeightCheckDigitBuilder = (partialRCN) => partialRCN + priceOrWeightCheckDigit(priceOrWeightString);
4192
- const checkDigitBuilder = (partialRCN) => partialRCN + checkDigit(partialRCN);
4193
- const rcnBuilders = [rcnPrefixBuilder];
4194
- for (let index = 0; validFormat && index < formatLength; index++) {
4195
- const formatChar = format.charAt(index);
4196
- if (index === 0) {
4197
- validFormat = formatChar === "2";
4198
- rcnPrefix = formatChar;
4199
- } else if (formatLength === 13 && index === 1) {
4200
- validFormat = import_utility9.NUMERIC_CREATOR.characterIndex(formatChar) !== void 0;
4201
- rcnPrefix += formatChar;
4202
- } else if (index === formatLength - 1) {
4203
- validFormat = formatChar === "C";
4204
- } else {
4205
- switch (formatChar) {
4206
- case "I":
4207
- if (!buildingItemReference) {
4208
- validFormat = itemReferenceLength === 0;
4209
- buildingItemReference = true;
4210
- buildingPriceOrWeight = false;
4211
- rcnBuilders.push(itemReferenceBuilder);
4212
- }
4213
- itemReferenceLength++;
4214
- break;
4215
- case "P":
4216
- if (!buildingPriceOrWeight) {
4217
- validFormat = priceOrWeightLength === 0;
4218
- buildingPriceOrWeight = true;
4219
- buildingItemReference = false;
4220
- rcnBuilders.push(priceOrWeightBuilder);
4221
- }
4222
- priceOrWeightLength++;
4223
- break;
4224
- case "V":
4225
- validFormat = !calculatePriceOrWeightCheckDigit;
4226
- buildingItemReference = false;
4227
- buildingPriceOrWeight = false;
4228
- calculatePriceOrWeightCheckDigit = true;
4229
- rcnBuilders.push(priceOrWeightCheckDigitBuilder);
4230
- break;
4231
- default:
4232
- validFormat = false;
4233
- break;
4234
- }
4235
- }
4236
- }
4237
- validFormat &&= itemReferenceLength !== 0 && priceOrWeightLength !== 0;
4238
- if (!validFormat) {
4239
- throw new RangeError(i18nextGS1.t("Identifier.invalidVariableMeasureRCNFormat"));
4240
- }
4241
- itemReferenceString = import_utility9.NUMERIC_CREATOR.create(itemReferenceLength, itemReference);
4242
- priceOrWeightString = import_utility9.NUMERIC_CREATOR.create(priceOrWeightLength, priceOrWeight);
4243
- rcnBuilders.push(checkDigitBuilder);
4244
- return rcnBuilders.reduce((partialRCN, rcnBuilder) => rcnBuilder(partialRCN), "");
4245
- }
4246
- };
4247
-
4248
- // src/non-gtin-numeric-identifier-creator.ts
4249
- var import_ts_mixer2 = require("ts-mixer");
4250
- var NonGTINNumericIdentifierCreator = class extends (0, import_ts_mixer2.Mixin)(NonGTINNumericIdentifierValidator, AbstractNumericIdentifierCreator) {
4251
- /**
4252
- * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4253
- * provider type.
4254
- *
4255
- * @param prefixProvider
4256
- * Prefix provider.
4257
- *
4258
- * @param identifierType
4259
- * Identifier type.
4260
- */
4261
- constructor(prefixProvider, identifierType) {
4262
- super(identifierType);
4263
- this.init(prefixProvider, prefixProvider.gs1CompanyPrefix);
4264
- }
4265
- };
4266
-
4267
- // src/serializable-numeric-identifier-creator.ts
4268
- var import_utility10 = require("@aidc-toolkit/utility");
4269
- var import_ts_mixer3 = require("ts-mixer");
4270
- var SerializableNumericIdentifierCreator = class extends (0, import_ts_mixer3.Mixin)(SerializableNumericIdentifierValidator, AbstractNumericIdentifierCreator) {
4271
- /**
4272
- * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4273
- * provider type.
4274
- *
4275
- * @param prefixProvider
4276
- * Prefix provider.
4277
- *
4278
- * @param identifierType
4279
- * Identifier type.
4280
- */
4281
- constructor(prefixProvider, identifierType) {
4282
- super(identifierType);
4283
- this.init(prefixProvider, prefixProvider.gs1CompanyPrefix);
4284
- }
4285
- /**
4286
- * Concatenate a validated base identifier with serial component(s).
4287
- *
4288
- * @template TTransformerInput
4289
- * Transformer input type.
4290
- *
4291
- * @param baseIdentifier
4292
- * Base identifier.
4293
- *
4294
- * @param serialComponentOrComponents
4295
- * Serial component(s).
4296
- *
4297
- * @returns
4298
- * Serialized identifier(s).
4299
- */
4300
- concatenateValidated(baseIdentifier, serialComponentOrComponents) {
4301
- let result;
4302
- const serialComponentCreator = this.serialComponentCreator;
4303
- const serialComponentValidation = this.serialComponentValidation;
4304
- function validateAndConcatenate(serialComponent) {
4305
- serialComponentCreator.validate(serialComponent, serialComponentValidation);
4306
- return baseIdentifier + serialComponent;
4307
- }
4308
- if (typeof serialComponentOrComponents !== "object") {
4309
- result = validateAndConcatenate(serialComponentOrComponents);
4310
- } else {
4311
- result = (0, import_utility10.mapIterable)(serialComponentOrComponents, validateAndConcatenate);
4312
- }
4313
- return result;
4314
- }
4315
- /**
4316
- * Create serialized identifier(s) with a reference based on a numeric value concatenated with serial component(s).
4317
- * The value is converted to a reference of the appropriate length using a numeric creator.
4318
- *
4319
- * @template TTransformerInput
4320
- * Transformer input type.
4321
- *
4322
- * @param value
4323
- * Numeric value of the reference.
4324
- *
4325
- * @param serialComponentOrComponents
4326
- * Serial component(s).
4327
- *
4328
- * @param sparse
4329
- * If true, the value is mapped to a sparse sequence resistant to discovery. Default is false.
4330
- *
4331
- * @returns
4332
- * Serialized identifiers.
4333
- */
4334
- createSerialized(value, serialComponentOrComponents, sparse) {
4335
- return this.concatenateValidated(this.create(value, sparse), serialComponentOrComponents);
4336
- }
4337
- /**
4338
- * Concatenate a base identifier with serial component(s).
4339
- *
4340
- * @template TTransformerInput
4341
- * Transformer input type.
4342
- *
4343
- * @param baseIdentifier
4344
- * Base identifier.
4345
- *
4346
- * @param serialComponentOrComponents
4347
- * Serial component(s).
4348
- *
4349
- * @returns
4350
- * Serialized identifier(s).
4351
- */
4352
- concatenate(baseIdentifier, serialComponentOrComponents) {
4353
- this.validate(baseIdentifier);
4354
- return this.concatenateValidated(baseIdentifier, serialComponentOrComponents);
4355
- }
4356
- };
4357
-
4358
- // src/non-numeric-identifier-creator.ts
4359
- var import_utility11 = require("@aidc-toolkit/utility");
4360
- var import_ts_mixer4 = require("ts-mixer");
4361
- var NonNumericIdentifierCreator = class extends (0, import_ts_mixer4.Mixin)(NonNumericIdentifierValidator, AbstractIdentifierCreator) {
4362
- /**
4363
- * Reference validation parameters.
4364
- */
4365
- _referenceValidation;
4366
- /**
4367
- * Constructor. Typically called internally by a prefix manager but may be called by other code with another prefix
4368
- * provider type.
4369
- *
4370
- * @param prefixProvider
4371
- * Prefix provider.
4372
- *
4373
- * @param identifierType
4374
- * Identifier type.
4375
- */
4376
- constructor(prefixProvider, identifierType) {
4377
- super(identifierType);
4378
- this.init(prefixProvider, prefixProvider.gs1CompanyPrefix, 2 * Number(this.requiresCheckCharacterPair));
4379
- this._referenceValidation = {
4380
- minimumLength: 1,
4381
- // Maximum reference length has to account for prefix and check character pair.
4382
- maximumLength: this.referenceLength,
4383
- component: () => i18nextGS1.t("Identifier.reference")
4384
- };
4385
- }
4386
- /**
4387
- * Get the reference validation parameters.
4388
- */
4389
- get referenceValidation() {
4390
- return this._referenceValidation;
4391
- }
4392
- /**
4393
- * Create identifier(s) with reference(s).
4394
- *
4395
- * @template TTransformerInput
4396
- * Transformer input type.
4397
- *
4398
- * @param referenceOrReferences
4399
- * Reference(s).
4400
- *
4401
- * @returns
4402
- * Identifier(s).
4403
- */
4404
- create(referenceOrReferences) {
4405
- let result;
4406
- const referenceCreator = this.referenceCreator;
4407
- const referenceValidation = this.referenceValidation;
4408
- const prefix = this.prefix;
4409
- const requiresCheckCharacterPair = this.requiresCheckCharacterPair;
4410
- function validateAndCreate(reference) {
4411
- referenceCreator.validate(reference, referenceValidation);
4412
- const partialIdentifier = prefix + reference;
4413
- return requiresCheckCharacterPair ? partialIdentifier + checkCharacterPair(partialIdentifier) : partialIdentifier;
4414
- }
4415
- if (typeof referenceOrReferences !== "object") {
4416
- result = validateAndCreate(referenceOrReferences);
4417
- } else {
4418
- result = (0, import_utility11.mapIterable)(referenceOrReferences, validateAndCreate);
4419
- }
4420
- return result;
4421
- }
4422
- };
4423
-
4424
- // src/creators.ts
4425
- function isNumericIdentifierCreator(identifierCreator) {
4426
- return isNumericIdentifierDescriptor(identifierCreator);
4427
- }
4428
- function isGTINCreator(identifierCreator) {
4429
- return isGTINDescriptor(identifierCreator);
4430
- }
4431
- function isNonGTINNumericIdentifierCreator(identifierCreator) {
4432
- return isNonGTINNumericIdentifierDescriptor(identifierCreator);
4433
- }
4434
- function isSerializableNumericIdentifierCreator(identifierCreator) {
4435
- return isSerializableNumericIdentifierDescriptor(identifierCreator);
4436
- }
4437
- function isNonNumericIdentifierCreator(identifierCreator) {
4438
- return isNonNumericIdentifierDescriptor(identifierCreator);
4439
- }
4440
-
4441
- // src/prefix-manager.ts
4442
- var PrefixManager = class _PrefixManager {
4443
- /**
4444
- * Cached prefix managers, keyed by GS1 Company Prefix.
4445
- */
4446
- static PREFIX_MANAGERS_MAP = /* @__PURE__ */ new Map();
4447
- /**
4448
- * Creator tweak factors. Different numeric identifier types have different tweak factors so that sparse creation
4449
- * generates different sequences for each.
4450
- */
4451
- static CREATOR_TWEAK_FACTORS = {
4452
- GTIN: 1987n,
4453
- GLN: 4241n,
4454
- SSCC: 8087n,
4455
- GRAI: 3221n,
4456
- GSRN: 2341n,
4457
- GDTI: 7333n,
4458
- GSIN: 5623n,
4459
- GCN: 6869n
4460
- };
4461
- /**
4462
- * Normalized prefix type.
4463
- */
4464
- _prefixType;
4465
- /**
4466
- * Normalized prefix.
4467
- */
4468
- _prefix;
4469
- /**
4470
- * Prefix as GS1 Company Prefix.
4471
- */
4472
- _gs1CompanyPrefix;
4473
- /**
4474
- * U.P.C. Company Prefix if prefix type is {@linkcode PrefixTypes.UPCCompanyPrefix}.
4475
- */
4476
- _upcCompanyPrefix;
4477
- /**
4478
- * GS1-8 Prefix if prefix type is {@linkcode PrefixTypes.GS18Prefix}.
4479
- */
4480
- _gs18Prefix;
4481
- /**
4482
- * Default tweak factor.
4483
- */
4484
- _defaultTweakFactor;
4485
- /**
4486
- * Tweak factor.
4487
- */
4488
- _tweakFactor = 0n;
4489
- /**
4490
- * Cached identifier creators.
4491
- */
4492
- _identifierCreators = {};
4493
- /**
4494
- * Constructor.
4495
- *
4496
- * @param prefixType
4497
- * Prefix type.
4498
- *
4499
- * @param prefix
4500
- * Prefix.
4501
- */
4502
- constructor(prefixType, prefix) {
4503
- const normalizedPrefixProvider = PrefixValidator.normalize(prefixType, prefix);
4504
- this._prefixType = normalizedPrefixProvider.prefixType;
4505
- this._prefix = normalizedPrefixProvider.prefix;
4506
- this._gs1CompanyPrefix = normalizedPrefixProvider.gs1CompanyPrefix;
4507
- this._upcCompanyPrefix = normalizedPrefixProvider.upcCompanyPrefix;
4508
- this._gs18Prefix = normalizedPrefixProvider.gs18Prefix;
4509
- this._defaultTweakFactor = BigInt(`1${this.gs1CompanyPrefix}`);
4510
- this.resetTweakFactor();
4511
- }
4512
- /**
4513
- * Get the prefix type.
4514
- */
4515
- get prefixType() {
4516
- return this._prefixType;
4517
- }
4518
- /**
4519
- * Get the prefix.
4520
- */
4521
- get prefix() {
4522
- return this._prefix;
4523
- }
4524
- /**
4525
- * Get the GS1 Company Prefix.
4526
- */
4527
- get gs1CompanyPrefix() {
4528
- return this._gs1CompanyPrefix;
4529
- }
4530
- /**
4531
- * Get the U.P.C. Company Prefix if prefix type is {@linkcode PrefixTypes.UPCCompanyPrefix} or undefined if not.
4532
- */
4533
- get upcCompanyPrefix() {
4534
- return this._upcCompanyPrefix;
4535
- }
4536
- /**
4537
- * Get the GS1-8 Prefix if prefix type is {@linkcode PrefixTypes.GS18Prefix} or undefined if not.
4538
- */
4539
- get gs18Prefix() {
4540
- return this._gs18Prefix;
4541
- }
4542
- /**
4543
- * Set the tweak for an identifier creator if it's a numeric identifier creator.
4544
- *
4545
- * @param identifierCreator
4546
- * Identifier creator.
4547
- */
4548
- setCreatorTweak(identifierCreator) {
4549
- if (isNumericIdentifierCreator(identifierCreator)) {
4550
- identifierCreator.tweak = this.tweakFactor * _PrefixManager.CREATOR_TWEAK_FACTORS[identifierCreator.identifierType];
4551
- }
4552
- }
4553
- /**
4554
- * Get the tweak factor.
4555
- */
4556
- get tweakFactor() {
4557
- return this._tweakFactor;
4558
- }
4559
- /**
4560
- * Set the tweak factor.
4561
- *
4562
- * @param value
4563
- * Tweak factor.
4564
- */
4565
- set tweakFactor(value) {
4566
- const tweakFactor = BigInt(value);
4567
- if (this._tweakFactor !== tweakFactor) {
4568
- this._tweakFactor = tweakFactor;
4569
- for (const creator of Object.values(this._identifierCreators)) {
4570
- this.setCreatorTweak(creator);
4571
- }
4572
- }
4573
- }
4574
- /**
4575
- * Reset the tweak factor to its default (numeric value of the GS1 Company Prefix preceded by '1').
4576
- */
4577
- resetTweakFactor() {
4578
- this.tweakFactor = this._defaultTweakFactor;
4579
- }
4580
- /**
4581
- * Get a prefix manager.
4582
- *
4583
- * @param prefixType
4584
- * Prefix type.
4585
- *
4586
- * @param prefix
4587
- * Prefix.
4588
- *
4589
- * @returns
4590
- * Prefix manager with normalized prefix type and prefix.
4591
- */
4592
- static get(prefixType, prefix) {
4593
- const normalizedPrefixProvider = PrefixValidator.normalize(prefixType, prefix);
4594
- let prefixManager = _PrefixManager.PREFIX_MANAGERS_MAP.get(normalizedPrefixProvider.gs1CompanyPrefix);
4595
- if (prefixManager === void 0) {
4596
- prefixManager = new _PrefixManager(normalizedPrefixProvider.prefixType, normalizedPrefixProvider.prefix);
4597
- _PrefixManager.PREFIX_MANAGERS_MAP.set(normalizedPrefixProvider.gs1CompanyPrefix, prefixManager);
4598
- }
4599
- return prefixManager;
4600
- }
4601
- /**
4602
- * Get an identifier creator.
4603
- *
4604
- * @template TIdentifierType
4605
- * Identifier type type.
4606
- *
4607
- * @param identifierType
4608
- * Identifier type used to construct identifier creator.
4609
- *
4610
- * @param constructorParameter
4611
- * Second constructor parameter passed to constructor callback alongside this.
4612
- *
4613
- * @param ConstructorCallback
4614
- * Constructor callback.
4615
- *
4616
- * @returns
4617
- * Identifier creator.
4618
- */
4619
- getIdentifierCreator(identifierType, constructorParameter, ConstructorCallback) {
4620
- let creator = this._identifierCreators[identifierType];
4621
- if (creator === void 0) {
4622
- if (this.prefixType === PrefixTypes.GS18Prefix && identifierType !== IdentifierTypes.GTIN) {
4623
- throw new RangeError(i18nextGS1.t("Prefix.identifierTypeNotSupportedByGS18Prefix", {
4624
- identifierType
4625
- }));
4626
- }
4627
- creator = new ConstructorCallback(this, constructorParameter);
4628
- this.setCreatorTweak(creator);
4629
- this._identifierCreators[identifierType] = creator;
4630
- }
4631
- return creator;
4632
- }
4633
- /**
4634
- * Get non-GTIN numeric identifier creator.
4635
- *
4636
- * @param identifierType
4637
- * Identifier type used to construct identifier creator.
4638
- *
4639
- * @returns
4640
- * Identifier creator.
4641
- */
4642
- getNonGTINNumericIdentifierCreator(identifierType) {
4643
- return this.getIdentifierCreator(identifierType, identifierType, NonGTINNumericIdentifierCreator);
4644
- }
4645
- /**
4646
- * Get serialized numeric identifier creator.
4647
- *
4648
- * @param identifierType
4649
- * Identifier type used to construct identifier creator.
4650
- *
4651
- * @returns
4652
- * Identifier creator.
4653
- */
4654
- getSerializableNumericIdentifierCreator(identifierType) {
4655
- return this.getIdentifierCreator(identifierType, identifierType, SerializableNumericIdentifierCreator);
4656
- }
4657
- /**
4658
- * Get non-numeric identifier creator.
4659
- *
4660
- * @param identifierType
4661
- * Identifier type used to construct identifier creator.
4662
- *
4663
- * @returns
4664
- * Identifier creator.
4665
- */
4666
- getNonNumericIdentifierCreator(identifierType) {
4667
- return this.getIdentifierCreator(identifierType, identifierType, NonNumericIdentifierCreator);
4668
- }
4669
- /**
4670
- * Get GTIN creator.
4671
- */
4672
- get gtinCreator() {
4673
- return this.getIdentifierCreator(IdentifierTypes.GTIN, GTIN_BASE_TYPES[this.prefixType], GTINCreator);
4674
- }
4675
- /**
4676
- * Get GLN creator.
4677
- */
4678
- get glnCreator() {
4679
- return this.getNonGTINNumericIdentifierCreator(IdentifierTypes.GLN);
4680
- }
4681
- /**
4682
- * Get SSCC creator.
4683
- */
4684
- get ssccCreator() {
4685
- return this.getNonGTINNumericIdentifierCreator(IdentifierTypes.SSCC);
4686
- }
4687
- /**
4688
- * Get GRAI creator.
4689
- */
4690
- get graiCreator() {
4691
- return this.getSerializableNumericIdentifierCreator(IdentifierTypes.GRAI);
4692
- }
4693
- /**
4694
- * Get GIAI creator.
4695
- */
4696
- get giaiCreator() {
4697
- return this.getNonNumericIdentifierCreator(IdentifierTypes.GIAI);
4698
- }
4699
- /**
4700
- * Get GSRN creator.
4701
- */
4702
- get gsrnCreator() {
4703
- return this.getNonGTINNumericIdentifierCreator(IdentifierTypes.GSRN);
4704
- }
4705
- /**
4706
- * Get GDTI creator.
4707
- */
4708
- get gdtiCreator() {
4709
- return this.getSerializableNumericIdentifierCreator(IdentifierTypes.GDTI);
4710
- }
4711
- /**
4712
- * Get GINC creator.
4713
- */
4714
- get gincCreator() {
4715
- return this.getNonNumericIdentifierCreator(IdentifierTypes.GINC);
4716
- }
4717
- /**
4718
- * Get GSIN creator.
4719
- */
4720
- get gsinCreator() {
4721
- return this.getNonGTINNumericIdentifierCreator(IdentifierTypes.GSIN);
4722
- }
4723
- /**
4724
- * Get GCN creator.
4725
- */
4726
- get gcnCreator() {
4727
- return this.getSerializableNumericIdentifierCreator(IdentifierTypes.GCN);
4728
- }
4729
- /**
4730
- * Get CPID creator.
4731
- */
4732
- get cpidCreator() {
4733
- return this.getNonNumericIdentifierCreator(IdentifierTypes.CPID);
4734
- }
4735
- /**
4736
- * Get GMN creator.
4737
- */
4738
- get gmnCreator() {
4739
- return this.getNonNumericIdentifierCreator(IdentifierTypes.GMN);
4740
- }
4741
- };
4742
- // Annotate the CommonJS export names for ESM import in node:
4743
- 0 && (module.exports = {
4744
- AI39_CREATOR,
4745
- AI39_VALIDATOR,
4746
- AI64_VALIDATOR,
4747
- AI82_CREATOR,
4748
- AI82_VALIDATOR,
4749
- ContentCharacterSets,
4750
- GTINCreator,
4751
- GTINLevels,
4752
- GTINTypes,
4753
- GTINValidator,
4754
- GTIN_BASE_TYPES,
4755
- IdentifierDescriptors,
4756
- IdentifierTypes,
4757
- IdentifierValidators,
4758
- LeaderTypes,
4759
- NonGTINNumericIdentifierCreator,
4760
- NonGTINNumericIdentifierValidator,
4761
- NonNumericIdentifierCreator,
4762
- NonNumericIdentifierValidator,
4763
- PrefixManager,
4764
- PrefixTypes,
4765
- PrefixValidator,
4766
- SerializableNumericIdentifierCreator,
4767
- SerializableNumericIdentifierValidator,
4768
- checkCharacterPair,
4769
- checkDigit,
4770
- checkDigitSum,
4771
- gs1NS,
4772
- gs1Resources,
4773
- hasValidCheckCharacterPair,
4774
- hasValidCheckDigit,
4775
- i18nGS1Init,
4776
- i18nextGS1,
4777
- isGTINCreator,
4778
- isGTINDescriptor,
4779
- isGTINDescriptors,
4780
- isGTINValidator,
4781
- isGTINValidators,
4782
- isNonGTINNumericIdentifierCreator,
4783
- isNonGTINNumericIdentifierDescriptor,
4784
- isNonGTINNumericIdentifierValidator,
4785
- isNonNumericIdentifierCreator,
4786
- isNonNumericIdentifierDescriptor,
4787
- isNonNumericIdentifierValidator,
4788
- isNumericIdentifierCreator,
4789
- isNumericIdentifierDescriptor,
4790
- isNumericIdentifierValidator,
4791
- isSerializableNumericIdentifierCreator,
4792
- isSerializableNumericIdentifierDescriptor,
4793
- isSerializableNumericIdentifierValidator,
4794
- isValidPriceOrWeightCheckDigit,
4795
- priceOrWeightCheckDigit
4796
- });
4797
- /*!
4798
- * Copyright © 2024-2025 Dolphin Data Development Ltd. and AIDC Toolkit
4799
- * contributors
4800
- *
4801
- * Licensed under the Apache License, Version 2.0 (the "License");
4802
- * you may not use this file except in compliance with the License.
4803
- * You may obtain a copy of the License at
4804
- *
4805
- * https://www.apache.org/licenses/LICENSE-2.0
4806
- *
4807
- * Unless required by applicable law or agreed to in writing, software
4808
- * distributed under the License is distributed on an "AS IS" BASIS,
4809
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4810
- * See the License for the specific language governing permissions and
4811
- * limitations under the License.
4812
- */
4813
- //# sourceMappingURL=index.cjs.map