generaltranslation 8.2.6 → 8.2.7

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 (162) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/ApiError-4zIP-twr.cjs +24 -0
  3. package/dist/ApiError-4zIP-twr.cjs.map +1 -0
  4. package/dist/ApiError-Bv7vlzyQ.mjs +19 -0
  5. package/dist/ApiError-Bv7vlzyQ.mjs.map +1 -0
  6. package/dist/errors.cjs +3 -0
  7. package/dist/errors.d.cts +11 -0
  8. package/dist/errors.d.mts +11 -0
  9. package/dist/errors.mjs +2 -0
  10. package/dist/id-CPbVYREY.mjs +74 -0
  11. package/dist/id-CPbVYREY.mjs.map +1 -0
  12. package/dist/id-VXBgyXu2.cjs +89 -0
  13. package/dist/id-VXBgyXu2.cjs.map +1 -0
  14. package/dist/id.cjs +5 -0
  15. package/dist/{id/hashSource.d.ts → id.d.cts} +20 -5
  16. package/dist/id.d.mts +40 -0
  17. package/dist/id.mjs +2 -0
  18. package/dist/index.cjs +3354 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +1157 -0
  21. package/dist/index.d.mts +1157 -0
  22. package/dist/index.mjs +3305 -0
  23. package/dist/index.mjs.map +1 -0
  24. package/dist/internal-CTeI8uLd.mjs +774 -0
  25. package/dist/internal-CTeI8uLd.mjs.map +1 -0
  26. package/dist/internal-PCKq4YMW.cjs +1012 -0
  27. package/dist/internal-PCKq4YMW.cjs.map +1 -0
  28. package/dist/internal.cjs +43 -0
  29. package/dist/{internal.d.ts → internal.d.cts} +62 -114
  30. package/dist/internal.d.mts +242 -0
  31. package/dist/internal.mjs +3 -0
  32. package/dist/sha2-DKowBr6H.cjs +747 -0
  33. package/dist/sha2-DKowBr6H.cjs.map +1 -0
  34. package/dist/stableStringify-DgDlE_pD.mjs +53 -0
  35. package/dist/stableStringify-DgDlE_pD.mjs.map +1 -0
  36. package/dist/types-D2fTTTvZ.d.cts +737 -0
  37. package/dist/types-fUW4_Ole.d.mts +737 -0
  38. package/dist/types.cjs +17 -0
  39. package/dist/types.cjs.map +1 -0
  40. package/dist/types.d.cts +2 -0
  41. package/dist/types.d.mts +2 -0
  42. package/dist/types.mjs +16 -0
  43. package/dist/types.mjs.map +1 -0
  44. package/package.json +52 -32
  45. package/dist/backwards-compatability/dataConversion.d.ts +0 -23
  46. package/dist/backwards-compatability/oldHashJsxChildren.d.ts +0 -23
  47. package/dist/backwards-compatability/oldTypes.d.ts +0 -21
  48. package/dist/backwards-compatability/typeChecking.d.ts +0 -21
  49. package/dist/cache/IntlCache.d.ts +0 -26
  50. package/dist/cache/types.d.ts +0 -32
  51. package/dist/derive/condenseVars.d.ts +0 -7
  52. package/dist/derive/declareVar.d.ts +0 -26
  53. package/dist/derive/decodeVars.d.ts +0 -9
  54. package/dist/derive/derive.d.ts +0 -38
  55. package/dist/derive/extractVars.d.ts +0 -9
  56. package/dist/derive/index.d.ts +0 -7
  57. package/dist/derive/indexVars.d.ts +0 -6
  58. package/dist/derive/utils/constants.d.ts +0 -2
  59. package/dist/derive/utils/regex.d.ts +0 -2
  60. package/dist/derive/utils/sanitizeVar.d.ts +0 -12
  61. package/dist/derive/utils/traverseHelpers.d.ts +0 -4
  62. package/dist/derive/utils/traverseIcu.d.ts +0 -20
  63. package/dist/derive/utils/types.d.ts +0 -23
  64. package/dist/errors/ApiError.d.ts +0 -7
  65. package/dist/errors/formattingErrors.d.ts +0 -1
  66. package/dist/errors.cjs.min.cjs +0 -2
  67. package/dist/errors.cjs.min.cjs.map +0 -1
  68. package/dist/errors.d.ts +0 -9
  69. package/dist/errors.esm.min.mjs +0 -2
  70. package/dist/errors.esm.min.mjs.map +0 -1
  71. package/dist/formatting/custom-formats/CutoffFormat/CutoffFormat.d.ts +0 -59
  72. package/dist/formatting/custom-formats/CutoffFormat/constants.d.ts +0 -4
  73. package/dist/formatting/custom-formats/CutoffFormat/types.d.ts +0 -48
  74. package/dist/formatting/format.d.ts +0 -1
  75. package/dist/id/hashTemplate.d.ts +0 -4
  76. package/dist/id/types.d.ts +0 -7
  77. package/dist/id.cjs.min.cjs +0 -2
  78. package/dist/id.cjs.min.cjs.map +0 -1
  79. package/dist/id.d.ts +0 -86
  80. package/dist/id.esm.min.mjs +0 -2
  81. package/dist/id.esm.min.mjs.map +0 -1
  82. package/dist/index.cjs.min.cjs +0 -2
  83. package/dist/index.cjs.min.cjs.map +0 -1
  84. package/dist/index.d.ts +0 -1627
  85. package/dist/index.esm.min.mjs +0 -2
  86. package/dist/index.esm.min.mjs.map +0 -1
  87. package/dist/internal.cjs.min.cjs +0 -2
  88. package/dist/internal.cjs.min.cjs.map +0 -1
  89. package/dist/internal.esm.min.mjs +0 -2
  90. package/dist/internal.esm.min.mjs.map +0 -1
  91. package/dist/locales/customLocaleMapping.d.ts +0 -11
  92. package/dist/locales/determineLocale.d.ts +0 -1
  93. package/dist/locales/getLocaleDirection.d.ts +0 -1
  94. package/dist/locales/getLocaleEmoji.d.ts +0 -2
  95. package/dist/locales/getLocaleName.d.ts +0 -1
  96. package/dist/locales/getLocaleProperties.d.ts +0 -32
  97. package/dist/locales/getPluralForm.d.ts +0 -9
  98. package/dist/locales/getRegionProperties.d.ts +0 -7
  99. package/dist/locales/isSameDialect.d.ts +0 -1
  100. package/dist/locales/isSameLanguage.d.ts +0 -1
  101. package/dist/locales/isSupersetLocale.d.ts +0 -1
  102. package/dist/locales/isValidLocale.d.ts +0 -1
  103. package/dist/locales/requiresTranslation.d.ts +0 -1
  104. package/dist/locales/resolveAliasLocale.d.ts +0 -8
  105. package/dist/locales/resolveCanonicalLocale.d.ts +0 -8
  106. package/dist/logging/errors.d.ts +0 -10
  107. package/dist/logging/logger.d.ts +0 -117
  108. package/dist/logging/warnings.d.ts +0 -2
  109. package/dist/projects/getProjectData.d.ts +0 -1
  110. package/dist/settings/plurals.d.ts +0 -3
  111. package/dist/settings/settings.d.ts +0 -2
  112. package/dist/settings/settingsUrls.d.ts +0 -3
  113. package/dist/translate/api.d.ts +0 -1
  114. package/dist/translate/awaitJobs.d.ts +0 -19
  115. package/dist/translate/checkJobStatus.d.ts +0 -8
  116. package/dist/translate/createBranch.d.ts +0 -10
  117. package/dist/translate/createTag.d.ts +0 -19
  118. package/dist/translate/downloadFileBatch.d.ts +0 -1
  119. package/dist/translate/enqueueFiles.d.ts +0 -8
  120. package/dist/translate/getOrphanedFiles.d.ts +0 -8
  121. package/dist/translate/processFileMoves.d.ts +0 -25
  122. package/dist/translate/publishFiles.d.ts +0 -17
  123. package/dist/translate/queryBranchData.d.ts +0 -3
  124. package/dist/translate/queryFileData.d.ts +0 -42
  125. package/dist/translate/querySourceFile.d.ts +0 -1
  126. package/dist/translate/setupProject.d.ts +0 -11
  127. package/dist/translate/submitUserEditDiffs.d.ts +0 -12
  128. package/dist/translate/translateMany.d.ts +0 -1
  129. package/dist/translate/uploadSourceFiles.d.ts +0 -1
  130. package/dist/translate/uploadTranslations.d.ts +0 -1
  131. package/dist/translate/utils/apiRequest.d.ts +0 -1
  132. package/dist/translate/utils/batch.d.ts +0 -52
  133. package/dist/translate/utils/fetchWithTimeout.d.ts +0 -1
  134. package/dist/translate/utils/generateRequestHeaders.d.ts +0 -2
  135. package/dist/translate/utils/handleFetchError.d.ts +0 -1
  136. package/dist/translate/utils/validateResponse.d.ts +0 -1
  137. package/dist/types-dir/api/branch.d.ts +0 -10
  138. package/dist/types-dir/api/checkFileTranslations.d.ts +0 -37
  139. package/dist/types-dir/api/downloadFile.d.ts +0 -3
  140. package/dist/types-dir/api/downloadFileBatch.d.ts +0 -34
  141. package/dist/types-dir/api/enqueueEntries.d.ts +0 -21
  142. package/dist/types-dir/api/enqueueFiles.d.ts +0 -56
  143. package/dist/types-dir/api/entry.d.ts +0 -36
  144. package/dist/types-dir/api/fetchTranslations.d.ts +0 -11
  145. package/dist/types-dir/api/file.d.ts +0 -54
  146. package/dist/types-dir/api/project.d.ts +0 -7
  147. package/dist/types-dir/api/translate.d.ts +0 -34
  148. package/dist/types-dir/api/translateMany.d.ts +0 -5
  149. package/dist/types-dir/api/translationStatus.d.ts +0 -9
  150. package/dist/types-dir/api/uploadFiles.d.ts +0 -43
  151. package/dist/types-dir/jsx/content.d.ts +0 -61
  152. package/dist/types-dir/jsx/variables.d.ts +0 -9
  153. package/dist/types-dir/transformations.d.ts +0 -8
  154. package/dist/types.cjs.min.cjs +0 -2
  155. package/dist/types.cjs.min.cjs.map +0 -1
  156. package/dist/types.d.ts +0 -652
  157. package/dist/types.esm.min.mjs +0 -2
  158. package/dist/types.esm.min.mjs.map +0 -1
  159. package/dist/utils/base64.d.ts +0 -2
  160. package/dist/utils/isVariable.d.ts +0 -2
  161. package/dist/utils/minify.d.ts +0 -2
  162. package/dist/utils/stableStringify.d.ts +0 -1
@@ -0,0 +1,774 @@
1
+ import { t as stableStringify } from "./stableStringify-DgDlE_pD.mjs";
2
+ import { TYPE, parse } from "@formatjs/icu-messageformat-parser";
3
+ import { TYPE as TYPE$1 } from "@formatjs/icu-messageformat-parser/types.js";
4
+ import { printAST } from "@formatjs/icu-messageformat-parser/printer.js";
5
+ import { sha256 } from "@noble/hashes/sha2.js";
6
+ import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
7
+ //#region src/settings/settings.ts
8
+ const libraryDefaultLocale = "en";
9
+ const defaultTimeout = 6e4;
10
+ //#endregion
11
+ //#region src/errors/formattingErrors.ts
12
+ const createInvalidCutoffStyleError = (style) => `generaltranslation Formatting Error: Invalid cutoff style: ${style}.`;
13
+ const DEFAULT_TERMINATOR_KEY = "DEFAULT_TERMINATOR_KEY";
14
+ const TERMINATOR_MAP = {
15
+ ellipsis: {
16
+ fr: {
17
+ terminator: "…",
18
+ separator: " "
19
+ },
20
+ zh: {
21
+ terminator: "……",
22
+ separator: void 0
23
+ },
24
+ ja: {
25
+ terminator: "……",
26
+ separator: void 0
27
+ },
28
+ [DEFAULT_TERMINATOR_KEY]: {
29
+ terminator: "…",
30
+ separator: void 0
31
+ }
32
+ },
33
+ none: { [DEFAULT_TERMINATOR_KEY]: {
34
+ terminator: void 0,
35
+ separator: void 0
36
+ } }
37
+ };
38
+ //#endregion
39
+ //#region src/formatting/custom-formats/CutoffFormat/CutoffFormat.ts
40
+ var CutoffFormatConstructor = class {
41
+ /**
42
+ * Constructor
43
+ * @param {string | string[]} locales - The locales to use for formatting.
44
+ * @param {CutoffFormatOptions} options - The options for formatting.
45
+ * @param {number} [option.maxChars] - The maximum number of characters to display.
46
+ * - Undefined values are treated as no cutoff.
47
+ * - Negative values follow .slice() behavior and terminator will be added before the value.
48
+ * - 0 will result in an empty string.
49
+ * - If cutoff results in an empty string, no terminator is added.
50
+ * @param {CutoffFormatStyle} [option.style='ellipsis'] - The style of the terminator.
51
+ * @param {string} [option.terminator] - Optional override the terminator to use.
52
+ * @param {string} [option.separator] - Optional override the separator to use between the terminator and the value.
53
+ * - If no terminator is provided, then separator is ignored.
54
+ *
55
+ * @example
56
+ * const format = new CutoffFormat('en', { maxChars: 5 });
57
+ * format.format('Hello, world!'); // 'Hello...'
58
+ *
59
+ * const format = new CutoffFormat('en', { maxChars: -3 });
60
+ * format.format('Hello, world!'); // '...ld!'
61
+ */
62
+ constructor(locales, options = {}) {
63
+ try {
64
+ const localesList = !locales ? ["en"] : Array.isArray(locales) ? locales.map((l) => String(l)) : [String(locales)];
65
+ const canonicalLocales = Intl.getCanonicalLocales(localesList);
66
+ this.locale = canonicalLocales.length ? canonicalLocales[0] : "en";
67
+ } catch {
68
+ this.locale = "en";
69
+ }
70
+ if (!TERMINATOR_MAP[options.style ?? "ellipsis"]) throw new Error(createInvalidCutoffStyleError(options.style ?? "ellipsis"));
71
+ let style;
72
+ let presetTerminatorOptions;
73
+ if (options.maxChars !== void 0) {
74
+ style = options.style ?? "ellipsis";
75
+ const languageCode = new Intl.Locale(this.locale).language;
76
+ presetTerminatorOptions = TERMINATOR_MAP[style][languageCode] || TERMINATOR_MAP[style]["DEFAULT_TERMINATOR_KEY"];
77
+ }
78
+ let terminator = options.terminator ?? presetTerminatorOptions?.terminator;
79
+ let separator = terminator != null ? options.separator ?? presetTerminatorOptions?.separator : void 0;
80
+ this.additionLength = (terminator?.length ?? 0) + (separator?.length ?? 0);
81
+ if (options.maxChars !== void 0 && Math.abs(options.maxChars) < this.additionLength) {
82
+ terminator = void 0;
83
+ separator = void 0;
84
+ }
85
+ this.options = {
86
+ maxChars: options.maxChars,
87
+ style,
88
+ terminator,
89
+ separator
90
+ };
91
+ }
92
+ /**
93
+ * Format a value according to the cutoff options, returning a formatted string.
94
+ *
95
+ * @param {string} value - The string value to format with cutoff behavior.
96
+ * @returns {string} The formatted string with terminator applied if cutoff occurs.
97
+ *
98
+ * @example
99
+ * const formatter = new CutoffFormatConstructor('en', { maxChars: 8, style: 'ellipsis' });
100
+ * formatter.format('Hello, world!'); // Returns 'Hello, w...'
101
+ */
102
+ format(value) {
103
+ return this.formatToParts(value).join("");
104
+ }
105
+ /**
106
+ * Format a value to parts according to the cutoff options, returning an array of string parts.
107
+ * This method breaks down the formatted result into individual components for more granular control.
108
+ *
109
+ * @param {string} value - The string value to format with cutoff behavior.
110
+ * @returns {PrependedCutoffParts | PostpendedCutoffParts} An array of string parts representing the formatted result.
111
+ * - For positive maxChars: [cutoffValue, separator?, terminator?]
112
+ * - For negative maxChars: [terminator?, separator?, cutoffValue]
113
+ * - For no cutoff: [originalValue]
114
+ *
115
+ * @example
116
+ * const formatter = new CutoffFormatConstructor('en', { maxChars: 5, style: 'ellipsis' });
117
+ * formatter.formatToParts('Hello, world!'); // Returns ['Hello', '...']
118
+ */
119
+ formatToParts(value) {
120
+ const { maxChars, terminator, separator } = this.options;
121
+ const adjustedChars = maxChars === void 0 || Math.abs(maxChars) >= value.length ? maxChars : maxChars >= 0 ? Math.max(0, maxChars - this.additionLength) : Math.min(0, maxChars + this.additionLength);
122
+ const slicedValue = adjustedChars !== void 0 && adjustedChars > -1 ? value.slice(0, adjustedChars) : value.slice(adjustedChars);
123
+ if (maxChars == null || adjustedChars == null || adjustedChars === 0 || terminator == null || value.length <= Math.abs(maxChars)) return [slicedValue];
124
+ if (adjustedChars > 0) return separator != null ? [
125
+ slicedValue,
126
+ separator,
127
+ terminator
128
+ ] : [slicedValue, terminator];
129
+ else return separator != null ? [
130
+ terminator,
131
+ separator,
132
+ slicedValue
133
+ ] : [terminator, slicedValue];
134
+ }
135
+ /**
136
+ * Get the resolved options
137
+ * @returns {ResolvedCutoffFormatOptions} The resolved options.
138
+ */
139
+ resolvedOptions() {
140
+ return this.options;
141
+ }
142
+ };
143
+ //#endregion
144
+ //#region src/cache/IntlCache.ts
145
+ /**
146
+ * Object mapping constructor names to their respective constructor functions
147
+ * Includes all native Intl constructors plus custom ones like CutoffFormat
148
+ */
149
+ const CustomIntl = {
150
+ Collator: Intl.Collator,
151
+ DateTimeFormat: Intl.DateTimeFormat,
152
+ DisplayNames: Intl.DisplayNames,
153
+ ListFormat: Intl.ListFormat,
154
+ Locale: Intl.Locale,
155
+ NumberFormat: Intl.NumberFormat,
156
+ PluralRules: Intl.PluralRules,
157
+ RelativeTimeFormat: Intl.RelativeTimeFormat,
158
+ Segmenter: Intl.Segmenter,
159
+ CutoffFormat: CutoffFormatConstructor
160
+ };
161
+ /**
162
+ * Cache for Intl and custom format instances to avoid repeated instantiation
163
+ * Uses a two-level structure: constructor name -> cache key -> instance
164
+ */
165
+ var IntlCache = class {
166
+ constructor() {
167
+ this.cache = {};
168
+ }
169
+ /**
170
+ * Generates a consistent cache key from locales and options
171
+ * Handles all LocalesArgument types (string, Locale, array, undefined)
172
+ */
173
+ _generateKey(locales, options = {}) {
174
+ return `${!locales ? "undefined" : Array.isArray(locales) ? locales.map((l) => String(l)).join(",") : String(locales)}:${options ? JSON.stringify(options, Object.keys(options).sort()) : "{}"}`;
175
+ }
176
+ /**
177
+ * Gets a cached Intl instance or creates a new one if not found
178
+ * @param constructor The name of the Intl constructor to use
179
+ * @param args Constructor arguments (locales, options)
180
+ * @returns Cached or newly created Intl instance
181
+ */
182
+ get(constructor, ...args) {
183
+ const [locales = "en", options = {}] = args;
184
+ const key = this._generateKey(locales, options);
185
+ let intlObject = this.cache[constructor]?.[key];
186
+ if (intlObject === void 0) {
187
+ intlObject = new CustomIntl[constructor](...args);
188
+ if (!this.cache[constructor]) this.cache[constructor] = {};
189
+ this.cache[constructor][key] = intlObject;
190
+ }
191
+ return intlObject;
192
+ }
193
+ };
194
+ /**
195
+ * Global instance of the Intl cache for use throughout the application
196
+ */
197
+ const intlCache = new IntlCache();
198
+ //#endregion
199
+ //#region src/settings/settingsUrls.ts
200
+ const defaultCacheUrl = "https://cdn.gtx.dev";
201
+ const defaultBaseUrl = "https://api2.gtx.dev";
202
+ const defaultRuntimeApiUrl = "https://runtime2.gtx.dev";
203
+ //#endregion
204
+ //#region src/settings/plurals.ts
205
+ const pluralForms = [
206
+ "singular",
207
+ "plural",
208
+ "dual",
209
+ "zero",
210
+ "one",
211
+ "two",
212
+ "few",
213
+ "many",
214
+ "other"
215
+ ];
216
+ function isAcceptedPluralForm(form) {
217
+ return pluralForms.includes(form);
218
+ }
219
+ //#endregion
220
+ //#region src/locales/getPluralForm.ts
221
+ /**
222
+ * Given a number and a list of allowed plural forms, return the plural form that best fits the number.
223
+ *
224
+ * @param {number} n - The number to determine the plural form for.
225
+ * @param {locales[]} forms - The allowed plural forms.
226
+ * @returns {PluralType} The determined plural form, or an empty string if none fit.
227
+ */
228
+ function _getPluralForm(n, forms = pluralForms, locales = ["en"]) {
229
+ const provisionalBranchName = intlCache.get("PluralRules", locales).select(n);
230
+ const absN = Math.abs(n);
231
+ if (absN === 0 && forms.includes("zero")) return "zero";
232
+ if (absN === 1) {
233
+ if (forms.includes("singular")) return "singular";
234
+ if (forms.includes("one")) return "one";
235
+ }
236
+ if (provisionalBranchName === "one" && forms.includes("singular")) return "singular";
237
+ if (absN === 2) {
238
+ if (forms.includes("dual")) return "dual";
239
+ if (forms.includes("two")) return "two";
240
+ }
241
+ if (provisionalBranchName === "two" && forms.includes("dual")) return "dual";
242
+ if (forms.includes(provisionalBranchName)) return provisionalBranchName;
243
+ if (provisionalBranchName === "two" && forms.includes("dual")) return "dual";
244
+ if (provisionalBranchName === "two" && forms.includes("plural")) return "plural";
245
+ if (provisionalBranchName === "two" && forms.includes("other")) return "other";
246
+ if (provisionalBranchName === "few" && forms.includes("plural")) return "plural";
247
+ if (provisionalBranchName === "few" && forms.includes("other")) return "other";
248
+ if (provisionalBranchName === "many" && forms.includes("plural")) return "plural";
249
+ if (provisionalBranchName === "many" && forms.includes("other")) return "other";
250
+ if (provisionalBranchName === "other" && forms.includes("plural")) return "plural";
251
+ return "";
252
+ }
253
+ //#endregion
254
+ //#region src/utils/minify.ts
255
+ const VARIABLE_TRANSFORMATION_SUFFIXES_TO_MINIFIED_NAMES = {
256
+ variable: "v",
257
+ number: "n",
258
+ datetime: "d",
259
+ currency: "c",
260
+ "relative-time": "rt"
261
+ };
262
+ function minifyVariableType(variableType) {
263
+ return VARIABLE_TRANSFORMATION_SUFFIXES_TO_MINIFIED_NAMES[variableType];
264
+ }
265
+ //#endregion
266
+ //#region src/utils/base64.ts
267
+ function encode(data) {
268
+ if (typeof Buffer !== "undefined") return Buffer.from(data, "utf8").toString("base64");
269
+ const bytes = new TextEncoder().encode(data);
270
+ let binary = "";
271
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
272
+ return btoa(binary);
273
+ }
274
+ function decode(base64) {
275
+ if (typeof Buffer !== "undefined") return Buffer.from(base64, "base64").toString("utf8");
276
+ const binary = atob(base64);
277
+ const bytes = new Uint8Array(binary.length);
278
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
279
+ return new TextDecoder().decode(bytes);
280
+ }
281
+ //#endregion
282
+ //#region src/derive/utils/traverseIcu.ts
283
+ /**
284
+ * Given an ICU string, traverse the AST and call the visitor function for each element that matches the type T
285
+ * @param icu - The ICU string to traverse
286
+ * @param shouldVisit - A function that returns true if the element should be visited
287
+ * @param visitor - A function that is called for each element that matches the type T
288
+ * @returns The modified AST of the ICU string
289
+ *
290
+ * @note This function is a heavy operation, use sparingly
291
+ */
292
+ function traverseIcu({ icuString, shouldVisit, visitor, options: { recurseIntoVisited = true, ...otherOptions } }) {
293
+ const ast = parse(icuString, otherOptions);
294
+ handleChildren(ast);
295
+ return ast;
296
+ function handleChildren(children) {
297
+ children.map(handleChild);
298
+ }
299
+ function handleChild(child) {
300
+ let visited = false;
301
+ if (shouldVisit(child)) {
302
+ visitor(child);
303
+ visited = true;
304
+ }
305
+ if (!visited || recurseIntoVisited) {
306
+ if (child.type === TYPE.select || child.type === TYPE.plural) Object.values(child.options).map((option) => option.value).map(handleChildren);
307
+ else if (child.type === TYPE.tag) handleChildren(child.children);
308
+ }
309
+ }
310
+ }
311
+ //#endregion
312
+ //#region src/derive/utils/constants.ts
313
+ const VAR_IDENTIFIER = "_gt_";
314
+ const VAR_NAME_IDENTIFIER = "_gt_var_name";
315
+ //#endregion
316
+ //#region src/derive/utils/regex.ts
317
+ const GT_INDEXED_IDENTIFIER_REGEX = new RegExp(`^${VAR_IDENTIFIER}\\d+$`);
318
+ const GT_UNINDEXED_IDENTIFIER_REGEX = new RegExp(`^${VAR_IDENTIFIER}$`);
319
+ //#endregion
320
+ //#region src/derive/utils/traverseHelpers.ts
321
+ function isGTIndexedSelectElement(child) {
322
+ return child.type === TYPE$1.select && GT_INDEXED_IDENTIFIER_REGEX.test(child.value) && !!child.options.other && (child.options.other.value.length === 0 || child.options.other.value.length > 0 && child.options.other.value[0]?.type === TYPE$1.literal);
323
+ }
324
+ function isGTUnindexedSelectElement(child) {
325
+ return child.type === TYPE$1.select && GT_UNINDEXED_IDENTIFIER_REGEX.test(child.value) && !!child.options.other && (child.options.other.value.length === 0 || child.options.other.value.length > 0 && child.options.other.value[0]?.type === TYPE$1.literal);
326
+ }
327
+ //#endregion
328
+ //#region src/derive/decodeVars.ts
329
+ /**
330
+ * Given an encoded ICU string, interpolate only _gt_ variables that have been marked with declareVar()
331
+ * @example
332
+ * const encodedIcu = "Hi" + declareVar("Brian") + ", my name is {name}"
333
+ * // 'Hi {_gt_, select, other {Brian}}, my name is {name}'
334
+ * decodeVars(encodedIcu)
335
+ * // 'Hi Brian, my name is {name}'
336
+ */
337
+ function decodeVars(icuString) {
338
+ if (!icuString.includes("_gt_")) return icuString;
339
+ const variableLocations = [];
340
+ function visitor(child) {
341
+ variableLocations.push({
342
+ start: child.location?.start.offset ?? 0,
343
+ end: child.location?.end.offset ?? 0,
344
+ value: child.options.other.value.length > 0 ? child.options.other.value[0].value : ""
345
+ });
346
+ }
347
+ traverseIcu({
348
+ icuString,
349
+ shouldVisit: isGTUnindexedSelectElement,
350
+ visitor,
351
+ options: {
352
+ recurseIntoVisited: false,
353
+ captureLocation: true
354
+ }
355
+ });
356
+ let previousIndex = 0;
357
+ const outputList = [];
358
+ for (let i = 0; i < variableLocations.length; i++) {
359
+ outputList.push(icuString.slice(previousIndex, variableLocations[i].start));
360
+ outputList.push(variableLocations[i].value);
361
+ previousIndex = variableLocations[i].end;
362
+ }
363
+ if (previousIndex < icuString.length) outputList.push(icuString.slice(previousIndex));
364
+ return outputList.join("");
365
+ }
366
+ //#endregion
367
+ //#region src/derive/utils/sanitizeVar.ts
368
+ /**
369
+ * Sanitizes string by escaping ICU syntax
370
+ *
371
+ * Sanitize arbitrary string so it does not break the following ICU message syntax:
372
+ * {_gt_, select, other {string_here}}
373
+ *
374
+ * Escapes ICU special characters by:
375
+ * 1. Doubling all single quotes (U+0027 ')
376
+ * 2. Adding a single quote before the first special character ({}<>)
377
+ * 3. Adding a single quote after the last special character ({}<>)
378
+ */
379
+ function sanitizeVar(string) {
380
+ let result = string.replace(/['\']/g, "''");
381
+ const specialChars = /[{}<>]/;
382
+ const firstSpecialIndex = result.search(specialChars);
383
+ if (firstSpecialIndex === -1) return result;
384
+ let lastSpecialIndex = -1;
385
+ for (let i = result.length - 1; i >= 0; i--) if (specialChars.test(result[i])) {
386
+ lastSpecialIndex = i;
387
+ break;
388
+ }
389
+ result = result.slice(0, firstSpecialIndex) + "'" + result.slice(firstSpecialIndex, lastSpecialIndex + 1) + "'" + result.slice(lastSpecialIndex + 1);
390
+ return result;
391
+ }
392
+ //#endregion
393
+ //#region src/derive/declareVar.ts
394
+ /**
395
+ * Mark as a non-translatable string. Use within a derive() call to mark content as not derivable (e.g., not possible to statically analyze).
396
+ *
397
+ * @example
398
+ * function nonDerivableFunction() {
399
+ * return Math.random();
400
+ * }
401
+ *
402
+ * function derivableFunction() {
403
+ * if (condition) {
404
+ * return declareVar(nonDerivableFunction())
405
+ * }
406
+ * return 'John Doe';
407
+ * }
408
+ *
409
+ * const gt = useGT();
410
+ * gt(`My name is ${derive(derivableFunction())}`);
411
+ *
412
+ * @param {string | number | boolean | null | undefined} variable - The variable to sanitize.
413
+ * @param {Object} [options] - The options for the sanitization.
414
+ * @param {string} [options.$name] - The name of the variable.
415
+ * @returns {string} The sanitized value.
416
+ */
417
+ function declareVar(variable, options) {
418
+ const variableSection = ` other {${sanitizeVar(String(variable ?? ""))}}`;
419
+ let nameSection = "";
420
+ if (options?.$name) nameSection = ` ${VAR_NAME_IDENTIFIER} {${sanitizeVar(options.$name)}}`;
421
+ return `{${VAR_IDENTIFIER}, select,${variableSection}${nameSection}}`;
422
+ }
423
+ //#endregion
424
+ //#region src/derive/derive.ts
425
+ /**
426
+ * derive() is a powerful but dangerous function which marks its argument as derivable (statically analyzable) for the compiler and CLI tool.
427
+ *
428
+ * This function is dangerous because it can cause the compiler and CLI tool to throw an error if the argument is not derivable.
429
+ *
430
+ * @example
431
+ * ```jsx
432
+ * function getSubject() {
433
+ * return (Math.random() > 0.5) ? "Alice" : "Brian";
434
+ * }
435
+ * ...
436
+ * gt(`My name is ${derive(getSubject())}`);
437
+ * ```
438
+ *
439
+ * @param {T extends string | boolean | number | null | undefined} content - Content to mark as derivable.
440
+ * @returns content
441
+ */
442
+ function derive(content) {
443
+ return content;
444
+ }
445
+ /**
446
+ * @deprecated Use derive() instead.
447
+ *
448
+ * declareStatic() is a powerful but dangerous function which marks its argument as derivable (statically analyzable) for the compiler and CLI tool.
449
+ *
450
+ * This function is dangerous because it can cause the compiler and CLI tool to throw an error if the argument is not derivable.
451
+ *
452
+ * @example
453
+ * ```jsx
454
+ * function getSubject() {
455
+ * return (Math.random() > 0.5) ? "Alice" : "Brian";
456
+ * }
457
+ * ...
458
+ * gt(`My name is ${declareStatic(getSubject())}`);
459
+ * ```
460
+ *
461
+ * @param {T extends string | boolean | number | null | undefined} content - Content to mark as derivable.
462
+ * @returns content
463
+ */
464
+ const declareStatic = derive;
465
+ //#endregion
466
+ //#region src/derive/indexVars.ts
467
+ /**
468
+ * Given an ICU string adds identifiers to each _gt_ placeholder
469
+ * indexVars('Hello {_gt_} {_gt_} World') => 'Hello {_gt_1_} {_gt_2_} World'
470
+ */
471
+ function indexVars(icuString) {
472
+ if (!icuString.includes("_gt_")) return icuString;
473
+ const variableLocations = [];
474
+ function visitor(child) {
475
+ variableLocations.push({
476
+ start: child.location?.start.offset ?? 0,
477
+ end: child.location?.end.offset ?? 0,
478
+ otherStart: child.options.other.location?.start.offset ?? 0,
479
+ otherEnd: child.options.other.location?.end.offset ?? 0
480
+ });
481
+ }
482
+ traverseIcu({
483
+ icuString,
484
+ shouldVisit: isGTUnindexedSelectElement,
485
+ visitor,
486
+ options: {
487
+ recurseIntoVisited: false,
488
+ captureLocation: true
489
+ }
490
+ });
491
+ const result = [];
492
+ let current = 0;
493
+ for (let i = 0; i < variableLocations.length; i++) {
494
+ const { start, end, otherStart, otherEnd } = variableLocations[i];
495
+ result.push(icuString.slice(current, start));
496
+ result.push(icuString.slice(start, start + 4 + 1));
497
+ result.push(String(i + 1));
498
+ result.push(icuString.slice(start + 4 + 1, otherStart));
499
+ result.push("{}");
500
+ result.push(icuString.slice(otherEnd, end));
501
+ current = end;
502
+ }
503
+ result.push(icuString.slice(current, icuString.length));
504
+ return result.join("");
505
+ }
506
+ //#endregion
507
+ //#region src/derive/extractVars.ts
508
+ /**
509
+ * Given an unindexed ICU string, extracts all the _gt_ variables and an indexed mapping of the variable to the values
510
+ *
511
+ * extractVars('Hello {_gt_, select, other {World}}') => { _gt_1: 'World' }
512
+ *
513
+ * @param {string} icuString - The ICU string to extract variables from.
514
+ * @returns {Record<string, string>} A mapping of the variable to the value.
515
+ */
516
+ function extractVars(icuString) {
517
+ if (!icuString.includes("_gt_")) return {};
518
+ let index = 1;
519
+ const variables = {};
520
+ function visitor(child) {
521
+ variables[child.value + index] = child.options.other.value.length ? child.options.other.value[0]?.value : "";
522
+ index += 1;
523
+ }
524
+ traverseIcu({
525
+ icuString,
526
+ shouldVisit: isGTUnindexedSelectElement,
527
+ visitor,
528
+ options: { recurseIntoVisited: false }
529
+ });
530
+ return variables;
531
+ }
532
+ //#endregion
533
+ //#region src/derive/condenseVars.ts
534
+ /**
535
+ * Given an indexed ICU string, condenses any select to an argument
536
+ * indexVars('Hello {_gt_1, select, other {World}}') => 'Hello {_gt_1}'
537
+ * @param {string} icuString - The ICU string to condense.
538
+ * @returns {string} The condensed ICU string.
539
+ */
540
+ function condenseVars(icuString) {
541
+ if (!icuString.includes("_gt_")) return icuString;
542
+ function visitor(child) {
543
+ child.type = TYPE$1.argument;
544
+ delete child.options;
545
+ }
546
+ return printAST(traverseIcu({
547
+ icuString,
548
+ shouldVisit: isGTIndexedSelectElement,
549
+ visitor,
550
+ options: { recurseIntoVisited: false }
551
+ }));
552
+ }
553
+ //#endregion
554
+ //#region src/backwards-compatability/typeChecking.ts
555
+ /**
556
+ * Checks if a JSX child is an old variable object format
557
+ * @param child - The JSX child to check
558
+ * @returns True if the child is an old variable object (has 'key' property)
559
+ */
560
+ function isOldVariableObject(child) {
561
+ return typeof child === "object" && child != null && "key" in child;
562
+ }
563
+ /**
564
+ * Checks if a JSX child is a new variable object format
565
+ * @param child - The JSX child to check
566
+ * @returns True if the child is a new variable object (has 'k' property)
567
+ */
568
+ function isNewVariableObject(child) {
569
+ return typeof child === "object" && child != null && "k" in child;
570
+ }
571
+ /**
572
+ * Checks if a JSX child is an old JSX element format
573
+ * @param child - The JSX child to check
574
+ * @returns True if the child is an old JSX element (has 'type' and 'props' properties)
575
+ */
576
+ function isOldJsxElement(child) {
577
+ return typeof child === "object" && child != null && "type" in child && "props" in child;
578
+ }
579
+ /**
580
+ * Checks if a JSX child follows the old format (string, old variable object, or old JSX element)
581
+ * @param child - The JSX child to check
582
+ * @returns True if the child is in the old format
583
+ */
584
+ function isOldJsxChild(child) {
585
+ if (typeof child === "string") return true;
586
+ if (isOldVariableObject(child)) return true;
587
+ return isOldJsxElement(child);
588
+ }
589
+ /**
590
+ * Checks if JSX children follow the old format
591
+ * @param children - The JSX children to check (can be string, array, or single child)
592
+ * @returns True if all children are in the old format
593
+ */
594
+ function isOldJsxChildren(children) {
595
+ if (typeof children === "string") return true;
596
+ if (Array.isArray(children)) return !children.some((child) => !isOldJsxChild(child));
597
+ return isOldJsxChild(children);
598
+ }
599
+ //#endregion
600
+ //#region src/backwards-compatability/dataConversion.ts
601
+ /**
602
+ * Convert request data from old format to new format
603
+ */
604
+ function getNewJsxChild(child) {
605
+ if (typeof child === "string") return child;
606
+ if (isOldVariableObject(child)) return getNewVariableObject(child);
607
+ return getNewJsxElement(child);
608
+ }
609
+ function getNewJsxChildren(children) {
610
+ if (typeof children === "string") return children;
611
+ if (Array.isArray(children)) return children.map(getNewJsxChild);
612
+ return getNewJsxChild(children);
613
+ }
614
+ function getNewJsxElement(element) {
615
+ if (typeof element === "string") return element;
616
+ let t = void 0;
617
+ if (element.type != null) t = element.type;
618
+ let c = void 0;
619
+ if (element.props?.children != null) c = getNewJsxChildren(element.props.children);
620
+ return {
621
+ ...t && { t },
622
+ ...c && { c },
623
+ d: getNewGTProp(element.props["data-_gt"]),
624
+ i: element.props["data-_gt"].id
625
+ };
626
+ }
627
+ function getNewBranchType(branch) {
628
+ if (branch === "branch") return "b";
629
+ return "p";
630
+ }
631
+ function getNewVariableType(variable) {
632
+ switch (variable) {
633
+ case "number": return "n";
634
+ case "variable": return "v";
635
+ case "datetime": return "d";
636
+ case "currency": return "c";
637
+ default: return "v";
638
+ }
639
+ }
640
+ function getNewVariableObject(variable) {
641
+ let v = void 0;
642
+ if (variable.variable != null) v = getNewVariableType(variable.variable);
643
+ let i = void 0;
644
+ if (variable.id != null) i = variable.id;
645
+ return {
646
+ k: variable.key,
647
+ ...v && { v },
648
+ ...i && { i }
649
+ };
650
+ }
651
+ function getNewGTProp(dataGT) {
652
+ let b = void 0;
653
+ if (dataGT.branches) b = Object.fromEntries(Object.entries(dataGT.branches).map(([key, value]) => [key, getNewJsxChildren(value)]));
654
+ let t;
655
+ if (dataGT.transformation) t = getNewBranchType(dataGT.transformation);
656
+ return {
657
+ ...b && { b },
658
+ ...t && { t }
659
+ };
660
+ }
661
+ /**
662
+ * Convert response data from old format to new format
663
+ */
664
+ function getOldJsxChild(child) {
665
+ if (typeof child === "string") return child;
666
+ if (isNewVariableObject(child)) return getOldVariableObject(child);
667
+ return getOldJsxElement(child);
668
+ }
669
+ function getOldJsxChildren(children) {
670
+ if (isOldJsxChildren(children)) return children;
671
+ if (typeof children === "string") return children;
672
+ if (Array.isArray(children)) return children.map(getOldJsxChild);
673
+ return getOldJsxChild(children);
674
+ }
675
+ function getOldJsxElement(element) {
676
+ const type = element.t;
677
+ let children = void 0;
678
+ if (element.c != null) children = getOldJsxChildren(element.c);
679
+ const dataGT = getOldGTProp(element.d || {}, element.i);
680
+ return {
681
+ type,
682
+ props: {
683
+ children,
684
+ "data-_gt": dataGT
685
+ }
686
+ };
687
+ }
688
+ function getOldBranchType(branch) {
689
+ if (branch === "b") return "branch";
690
+ return "plural";
691
+ }
692
+ function getOldVariableType(variable) {
693
+ switch (variable) {
694
+ case "n": return "number";
695
+ case "v": return "variable";
696
+ case "d": return "datetime";
697
+ case "c": return "currency";
698
+ default: return "variable";
699
+ }
700
+ }
701
+ function getOldVariableObject(variable) {
702
+ let v = void 0;
703
+ if (variable.v != null) v = getOldVariableType(variable.v);
704
+ let i = void 0;
705
+ if (variable.i != null) i = variable.i;
706
+ return {
707
+ key: variable.k,
708
+ ...v && { variable: v },
709
+ ...i && { id: i }
710
+ };
711
+ }
712
+ function getOldGTProp(dataGT, i) {
713
+ let transformation = void 0;
714
+ if (dataGT.t != null) transformation = getOldBranchType(dataGT.t);
715
+ let branches = void 0;
716
+ if (dataGT.b != null) branches = Object.fromEntries(Object.entries(dataGT.b).map(([key, value]) => [key, getOldJsxChildren(value)]));
717
+ return {
718
+ id: i,
719
+ ...transformation && { transformation },
720
+ ...branches && { branches }
721
+ };
722
+ }
723
+ //#endregion
724
+ //#region src/backwards-compatability/oldHashJsxChildren.ts
725
+ /**
726
+ * Calculates a unique hash for a given string using sha256.
727
+ *
728
+ * @param {string} string - The string to be hashed.
729
+ * @returns {string} - The resulting hash as a hexadecimal string.
730
+ */
731
+ function oldHashString(string) {
732
+ return bytesToHex(sha256(utf8ToBytes(string)));
733
+ }
734
+ /**
735
+ * Calculates a unique ID for the given children objects by hashing their sanitized JSON string representation.
736
+ *
737
+ * @param {any} childrenAsObjects - The children objects to be hashed.
738
+ * @param {string} context - The context for the children
739
+ * @param {string} id - The id for the JSX Children object
740
+ * @param {function} hashFunction custom hash function
741
+ * @returns {string} - The unique has of the children.
742
+ */
743
+ function oldHashJsxChildren({ source, context, id, dataFormat }, hashFunction = oldHashString) {
744
+ return hashFunction(stableStringify({
745
+ source: sanitizeJsxChildren(source),
746
+ ...id && { id },
747
+ ...context && { context },
748
+ ...dataFormat && { dataFormat }
749
+ }));
750
+ }
751
+ const sanitizeChild = (child) => {
752
+ if (child && typeof child === "object") {
753
+ if ("props" in child) {
754
+ const newChild = {};
755
+ const dataGt = child?.props?.["data-_gt"];
756
+ if (dataGt?.branches) newChild.branches = Object.fromEntries(Object.entries(dataGt.branches).map(([key, value]) => [key, sanitizeJsxChildren(value)]));
757
+ if (child?.props?.children) newChild.children = sanitizeJsxChildren(child.props.children);
758
+ if (child?.props?.["data-_gt"]?.transformation) newChild.transformation = child.props["data-_gt"].transformation;
759
+ return newChild;
760
+ }
761
+ if ("key" in child) return {
762
+ key: child.key,
763
+ ...child.variable && { variable: child.variable }
764
+ };
765
+ }
766
+ return child;
767
+ };
768
+ function sanitizeJsxChildren(childrenAsObjects) {
769
+ return Array.isArray(childrenAsObjects) ? childrenAsObjects.map(sanitizeChild) : sanitizeChild(childrenAsObjects);
770
+ }
771
+ //#endregion
772
+ export { encode as A, libraryDefaultLocale as B, declareStatic as C, VAR_IDENTIFIER as D, decodeVars as E, defaultBaseUrl as F, defaultCacheUrl as I, defaultRuntimeApiUrl as L, _getPluralForm as M, isAcceptedPluralForm as N, VAR_NAME_IDENTIFIER as O, pluralForms as P, intlCache as R, indexVars as S, declareVar as T, isNewVariableObject as _, getNewJsxChild as a, condenseVars as b, getNewVariableObject as c, getOldGTProp as d, getOldJsxChild as f, getOldVariableType as g, getOldVariableObject as h, getNewGTProp as i, minifyVariableType as j, decode as k, getNewVariableType as l, getOldJsxElement as m, oldHashString as n, getNewJsxChildren as o, getOldJsxChildren as p, getNewBranchType as r, getNewJsxElement as s, oldHashJsxChildren as t, getOldBranchType as u, isOldJsxChildren as v, derive as w, extractVars as x, isOldVariableObject as y, defaultTimeout as z };
773
+
774
+ //# sourceMappingURL=internal-CTeI8uLd.mjs.map