@intlayer/core 9.9.3-canary.1 → 9.9.3

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.
@@ -77,19 +77,25 @@ const formatArgument = (value, type, style, locale, formatters) => {
77
77
  * optionally formatted the i18next way (`{{price, number}}`)
78
78
  * 2. ICU formatted arguments `{value, number}` / `{ts, date, long}`
79
79
  * 3. Bare single-brace arguments `{name}` (ICU / vue-i18n simple args)
80
+ *
81
+ * With `'double-brace'` interpolation, only step 1 runs.
80
82
  */
81
- const interpolateMessage = (template, values = {}, locale = "en", formatters) => template.replace(/\{\{\s*([^{},]+?)\s*(?:,\s*(\w+)\s*(?:,\s*([^{}]+?)\s*)?)?\}\}/g, (match, path, type, style) => {
82
- const value = resolveValuePath(values, path);
83
- if (value === void 0) return match;
84
- return type ? formatArgument(value, type, style, locale, formatters) : String(value);
85
- }).replace(/\{\s*([\w.]+)\s*,\s*(\w+)\s*(?:,\s*([^}]+?)\s*)?\}/g, (match, path, type, style) => {
86
- const value = resolveValuePath(values, path);
87
- if (value === void 0) return match;
88
- return formatArgument(value, type, style, locale, formatters);
89
- }).replace(/\{\s*([\w.]+)\s*\}/g, (match, path) => {
90
- const value = resolveValuePath(values, path);
91
- return value === void 0 ? match : String(value);
92
- });
83
+ const interpolateMessage = (template, values = {}, locale = "en", formatters, interpolation = "default") => {
84
+ const interpolated = template.replace(/\{\{\s*([^{},]+?)\s*(?:,\s*(\w+)\s*(?:,\s*([^{}]+?)\s*)?)?\}\}/g, (match, path, type, style) => {
85
+ const value = resolveValuePath(values, path) ?? resolveValuePath(values, path.replace(/^-\s+/, "-"));
86
+ if (value === void 0) return match;
87
+ return type ? formatArgument(value, type, style, locale, formatters) : String(value);
88
+ });
89
+ if (interpolation === "double-brace") return interpolated;
90
+ return interpolated.replace(/\{\s*([\w.]+)\s*,\s*(\w+)\s*(?:,\s*([^}]+?)\s*)?\}/g, (match, path, type, style) => {
91
+ const value = resolveValuePath(values, path);
92
+ if (value === void 0) return match;
93
+ return formatArgument(value, type, style, locale, formatters);
94
+ }).replace(/\{\s*([\w.]+)\s*\}/g, (match, path) => {
95
+ const value = resolveValuePath(values, path);
96
+ return value === void 0 ? match : String(value);
97
+ });
98
+ };
93
99
  /** Reads the selector value of an enumeration/plural node from the values. */
94
100
  const getSelectorValue = (values, variableName) => values[variableName] ?? values.count ?? values.n;
95
101
  /**
@@ -100,25 +106,25 @@ const getSelectorValue = (values, variableName) => values[variableName] ?? value
100
106
  * Function nodes (produced by the interpreter plugins for `insertion`,
101
107
  * `enumeration` and `plural` content) are invoked with the values.
102
108
  */
103
- const resolveMessageNode = (node, values = {}, locale = "en", formatters) => {
109
+ const resolveMessageNode = (node, values = {}, locale = "en", formatters, interpolation = "default") => {
104
110
  if (node === null || node === void 0) return node;
105
- if (typeof node === "string") return interpolateMessage(node, values, locale, formatters);
111
+ if (typeof node === "string") return interpolateMessage(node, values, locale, formatters, interpolation);
106
112
  if (typeof node === "number" || typeof node === "boolean") return String(node);
107
113
  if (typeof node === "function") try {
108
- return resolveMessageNode(node(values), values, locale, formatters);
114
+ return resolveMessageNode(node(values), values, locale, formatters, interpolation);
109
115
  } catch {
110
116
  return;
111
117
  }
112
- if (Array.isArray(node)) return node.map((item) => String(resolveMessageNode(item, values, locale, formatters) ?? "")).join("");
118
+ if (Array.isArray(node)) return node.map((item) => String(resolveMessageNode(item, values, locale, formatters, interpolation) ?? "")).join("");
113
119
  const typedNode = node;
114
- if (typedNode.nodeType === _intlayer_types_nodeType.INSERTION) return resolveMessageNode(typedNode[_intlayer_types_nodeType.INSERTION], values, locale, formatters);
115
- if (typedNode.nodeType === _intlayer_types_nodeType.HTML) return resolveMessageNode(typedNode[_intlayer_types_nodeType.HTML], values, locale, formatters);
120
+ if (typedNode.nodeType === _intlayer_types_nodeType.INSERTION) return resolveMessageNode(typedNode[_intlayer_types_nodeType.INSERTION], values, locale, formatters, interpolation);
121
+ if (typedNode.nodeType === _intlayer_types_nodeType.HTML) return resolveMessageNode(typedNode[_intlayer_types_nodeType.HTML], values, locale, formatters, interpolation);
116
122
  if (typedNode.nodeType === _intlayer_types_nodeType.PLURAL) {
117
123
  const pluralState = typedNode[_intlayer_types_nodeType.PLURAL];
118
124
  const variableName = typeof typedNode.variable === "string" ? typedNode.variable : require_transpiler_plural_plural.DEFAULT_PLURAL_VARIABLE;
119
125
  const count = Number(getSelectorValue(values, variableName) ?? 1);
120
126
  const selected = require_interpreter_getPlural.getPlural(pluralState, count, locale);
121
- return resolveMessageNode(selected, values, locale, formatters);
127
+ return resolveMessageNode(selected, values, locale, formatters, interpolation);
122
128
  }
123
129
  if (typedNode.nodeType === _intlayer_types_nodeType.ENUMERATION) {
124
130
  const enumerationState = typedNode[_intlayer_types_nodeType.ENUMERATION];
@@ -137,19 +143,19 @@ const resolveMessageNode = (node, values = {}, locale = "en", formatters) => {
137
143
  const matchedKey = require_interpreter_getEnumeration.findMatchingCondition(options, count);
138
144
  selected = matchedKey ? options[matchedKey] : options[require_utils_intl.getCachedIntl("PluralRules", locale).select(count)] ?? require_interpreter_getEnumeration.getEnumeration(options, count);
139
145
  } else selected = options[String(selector)] ?? options.fallback ?? options.other;
140
- return resolveMessageNode(selected, values, locale, formatters);
146
+ return resolveMessageNode(selected, values, locale, formatters, interpolation);
141
147
  }
142
148
  if (typedNode.nodeType === _intlayer_types_nodeType.SELECT) {
143
149
  const selectState = typedNode[_intlayer_types_nodeType.SELECT];
144
150
  const variableName = typeof typedNode.variable === "string" ? typedNode.variable : "value";
145
151
  const selector = getSelectorValue(values, variableName);
146
152
  const selected = require_interpreter_getSelect.getSelect(selectState, String(selector ?? ""));
147
- return resolveMessageNode(selected, values, locale, formatters);
153
+ return resolveMessageNode(selected, values, locale, formatters, interpolation);
148
154
  }
149
155
  if (typedNode.nodeType === _intlayer_types_nodeType.GENDER) {
150
156
  const genderState = typedNode[_intlayer_types_nodeType.GENDER];
151
157
  const selected = genderState[String(values.gender ?? "")] ?? genderState.fallback ?? genderState.other;
152
- return resolveMessageNode(selected, values, locale, formatters);
158
+ return resolveMessageNode(selected, values, locale, formatters, interpolation);
153
159
  }
154
160
  return node;
155
161
  };
@@ -160,10 +166,11 @@ const resolveMessageNode = (node, values = {}, locale = "en", formatters) => {
160
166
  * the bundle through a built dictionary: the build already converted every
161
167
  * dialect construct into intlayer nodes, and the interpreter turned those into
162
168
  * callables, so no message parser is involved. Plain strings still get
163
- * `{{name}}` / `{name}` / `{value, number}` interpolation.
169
+ * `{{name}}` / `{name}` / `{value, number}` interpolation (only `{{…}}` with
170
+ * `'double-brace'` interpolation).
164
171
  */
165
- const resolveMessageNodeToString = (node, values = {}, locale = "en", formatters) => {
166
- const resolved = resolveMessageNode(node, values, locale, formatters);
172
+ const resolveMessageNodeToString = (node, values = {}, locale = "en", formatters, interpolation = "default") => {
173
+ const resolved = resolveMessageNode(node, values, locale, formatters, interpolation);
167
174
  return typeof resolved === "string" ? resolved : String(resolved ?? "");
168
175
  };
169
176
  /**
@@ -179,12 +186,18 @@ const resolveMessageNodeToString = (node, values = {}, locale = "en", formatters
179
186
  * resolveIcuMessage('Hello {name}', { name: 'John' }, 'en'); // 'Hello John'
180
187
  * ```
181
188
  */
182
- const createMessageResolver = (formatter) => (message, values = {}, locale = "en", formatters) => resolveMessageNodeToString(typeof message === "string" ? formatter(message) : message, values, locale, formatters);
189
+ const createMessageResolver = (formatter, interpolation = "default") => (message, values = {}, locale = "en", formatters) => resolveMessageNodeToString(typeof message === "string" ? formatter(message) : message, values, locale, formatters, interpolation);
183
190
  const DIALECT_FORMATTERS = {
184
191
  icu: require_messageFormat_ICU.icuToIntlayerFormatter,
185
192
  i18next: require_messageFormat_i18next.i18nextToIntlayerFormatter,
186
193
  "vue-i18n": require_messageFormat_vue_i18n.vueI18nToIntlayerFormatter
187
194
  };
195
+ /** i18next reads only `{{…}}`; the other dialects use single braces too. */
196
+ const DIALECT_INTERPOLATION = {
197
+ icu: "default",
198
+ i18next: "double-brace",
199
+ "vue-i18n": "default"
200
+ };
188
201
  /**
189
202
  * Resolves a raw message — string in a library dialect, or an intlayer node
190
203
  * tree — into a final string using interpolation values and locale.
@@ -206,7 +219,7 @@ const DIALECT_FORMATTERS = {
206
219
  * // '3 items'
207
220
  * ```
208
221
  */
209
- const resolveMessage = (message, values = {}, locale = "en", dialect = "icu") => createMessageResolver(DIALECT_FORMATTERS[dialect])(message, values, locale);
222
+ const resolveMessage = (message, values = {}, locale = "en", dialect = "icu") => createMessageResolver(DIALECT_FORMATTERS[dialect], DIALECT_INTERPOLATION[dialect])(message, values, locale);
210
223
  /**
211
224
  * Tokenizes a message containing XML-like tags (`'Visit <link>the docs</link>'`,
212
225
  * `'hello <1>{{name}}</1>'`, `'line<br/>break'`) into a token tree.
@@ -1 +1 @@
1
- {"version":3,"file":"resolveMessage.cjs","names":["getCachedIntl","NodeTypes","DEFAULT_PLURAL_VARIABLE","getPlural","findMatchingCondition","getEnumeration","getSelect","icuToIntlayerFormatter","i18nextToIntlayerFormatter","vueI18nToIntlayerFormatter"],"sources":["../../../src/messageFormat/resolveMessage.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { getCachedIntl } from '../formatters';\nimport {\n findMatchingCondition,\n getEnumeration,\n} from '../interpreter/getEnumeration';\nimport { getPlural } from '../interpreter/getPlural';\nimport { getSelect } from '../interpreter/getSelect';\nimport {\n DEFAULT_PLURAL_VARIABLE,\n type PluralContentState,\n} from '../transpiler/plural/plural';\nimport { i18nextToIntlayerFormatter } from './i18next';\nimport { icuToIntlayerFormatter } from './ICU';\nimport { vueI18nToIntlayerFormatter } from './vue-i18n';\n\n/**\n * Runtime counterpart of the `messageFormat` converters.\n *\n * The converters (`icuToIntlayerFormatter`, `i18nextToIntlayerFormatter`,\n * `vueI18nToIntlayerFormatter`) turn library-specific message syntax into\n * intlayer nodes (`insert`, `plural`, `enu`, `gender`, `html`). This module\n * resolves those nodes — or raw message strings — into a final string using\n * the provided interpolation values and locale.\n *\n * It is the mutualized resolution engine used by the compat adapter packages\n * (`@intlayer/i18next`, `@intlayer/next-intl`, `@intlayer/vue-i18n`, …).\n */\n\n/** Message syntax dialect of the source i18n library. */\nexport type MessageFormatDialect = 'icu' | 'i18next' | 'vue-i18n';\n\n/** Interpolation values passed alongside a translation lookup. */\nexport type MessageValues = Record<string, unknown>;\n\n/** Internal enumeration metadata keys injected by the converters. */\nconst ENUMERATION_METADATA_KEYS = [\n '__intlayer_icu_var',\n '__intlayer_icu_ordinal',\n '__intlayer_vue_i18n_var',\n] as const;\n\n/**\n * Resolves a possibly-dotted path (`user.name`) inside the values object.\n */\nconst resolveValuePath = (values: MessageValues, path: string): unknown => {\n if (path in values) return values[path];\n\n let current: unknown = values;\n for (const part of path.split('.')) {\n if (\n current === null ||\n current === undefined ||\n typeof current !== 'object'\n ) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n};\n\n/** Context handed to a {@link MessageArgumentFormatter}. */\nexport type MessageArgumentFormatterContext = {\n /** Active locale. */\n locale: LocalesValues;\n /** Third segment of the argument (`EUR` in `{price, currency, EUR}`). */\n style?: string;\n};\n\n/**\n * Formats an argument whose type is not built in, e.g. `currency` in\n * `{price, currency, EUR}`.\n */\nexport type MessageArgumentFormatter = (\n value: unknown,\n context: MessageArgumentFormatterContext\n) => unknown;\n\n/** Custom argument formatters, keyed by argument type. */\nexport type MessageArgumentFormatters = Record<\n string,\n MessageArgumentFormatter\n>;\n\n/** Argument types handled natively; custom formatters cannot override them. */\nconst BUILT_IN_ARGUMENT_TYPES = ['number', 'date', 'time'];\n\n/**\n * Formats an ICU-style formatted argument (`{value, number, percent}`).\n * Types that are not built in go to the matching custom formatter, if any.\n */\nconst formatArgument = (\n value: unknown,\n type: string,\n style: string | undefined,\n locale: LocalesValues,\n formatters?: MessageArgumentFormatters\n): string => {\n const customFormatter =\n !BUILT_IN_ARGUMENT_TYPES.includes(type) &&\n formatters &&\n Object.hasOwn(formatters, type)\n ? formatters[type]\n : undefined;\n\n if (customFormatter) {\n const formatted = customFormatter(value, { locale, style });\n return formatted === null || formatted === undefined\n ? ''\n : String(formatted);\n }\n\n try {\n if (type === 'number') {\n const numberValue = Number(value);\n if (style === 'percent') {\n return getCachedIntl('NumberFormat', locale, {\n style: 'percent',\n }).format(numberValue);\n }\n if (style === 'integer') {\n return getCachedIntl('NumberFormat', locale, {\n maximumFractionDigits: 0,\n }).format(numberValue);\n }\n return getCachedIntl('NumberFormat', locale).format(numberValue);\n }\n\n if (type === 'date' || type === 'time') {\n const dateValue =\n value instanceof Date ? value : new Date(value as string | number);\n const dateTimeStyle = (\n ['short', 'medium', 'long', 'full'].includes(style ?? '')\n ? style\n : type === 'date'\n ? 'medium'\n : 'short'\n ) as 'short' | 'medium' | 'long' | 'full';\n\n return getCachedIntl(\n 'DateTimeFormat',\n locale,\n type === 'date'\n ? { dateStyle: dateTimeStyle }\n : { timeStyle: dateTimeStyle }\n ).format(dateValue);\n }\n } catch {\n // Fall through to the raw string representation below\n }\n\n return String(value);\n};\n\n/**\n * Interpolates a message template with values.\n *\n * Handles, in order:\n * 1. Intlayer insertions `{{name}}` (whitespace-tolerant, dotted paths),\n * optionally formatted the i18next way (`{{price, number}}`)\n * 2. ICU formatted arguments `{value, number}` / `{ts, date, long}`\n * 3. Bare single-brace arguments `{name}` (ICU / vue-i18n simple args)\n */\nexport const interpolateMessage = (\n template: string,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters\n): string =>\n template\n .replace(\n /\\{\\{\\s*([^{},]+?)\\s*(?:,\\s*(\\w+)\\s*(?:,\\s*([^{}]+?)\\s*)?)?\\}\\}/g,\n (match, path: string, type: string | undefined, style?: string) => {\n const value = resolveValuePath(values, path);\n if (value === undefined) return match;\n return type\n ? formatArgument(value, type, style, locale, formatters)\n : String(value);\n }\n )\n .replace(\n /\\{\\s*([\\w.]+)\\s*,\\s*(\\w+)\\s*(?:,\\s*([^}]+?)\\s*)?\\}/g,\n (match, path: string, type: string, style: string | undefined) => {\n const value = resolveValuePath(values, path);\n if (value === undefined) return match;\n return formatArgument(value, type, style, locale, formatters);\n }\n )\n .replace(/\\{\\s*([\\w.]+)\\s*\\}/g, (match, path: string) => {\n const value = resolveValuePath(values, path);\n return value === undefined ? match : String(value);\n });\n\n/** Reads the selector value of an enumeration/plural node from the values. */\nconst getSelectorValue = (\n values: MessageValues,\n variableName: string\n): unknown => values[variableName] ?? values.count ?? values.n;\n\n/**\n * Resolves an intlayer message node tree (as produced by the\n * `*ToIntlayerFormatter` converters, or already present in a built\n * dictionary) into its final value using interpolation values and locale.\n *\n * Function nodes (produced by the interpreter plugins for `insertion`,\n * `enumeration` and `plural` content) are invoked with the values.\n */\nexport const resolveMessageNode = (\n node: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters\n): unknown => {\n if (node === null || node === undefined) return node;\n\n if (typeof node === 'string') {\n return interpolateMessage(node, values, locale, formatters);\n }\n\n if (typeof node === 'number' || typeof node === 'boolean') {\n return String(node);\n }\n\n // Interpreter-transformed nodes (insertion/enumeration/plural plugins)\n // are exposed as callables taking the interpolation values.\n if (typeof node === 'function') {\n try {\n return resolveMessageNode(\n (node as (arg: MessageValues) => unknown)(values),\n values,\n locale,\n formatters\n );\n } catch {\n return undefined;\n }\n }\n\n if (Array.isArray(node)) {\n return node\n .map((item) =>\n String(resolveMessageNode(item, values, locale, formatters) ?? '')\n )\n .join('');\n }\n\n const typedNode = node as Record<string, unknown> & { nodeType?: string };\n\n if (typedNode.nodeType === NodeTypes.INSERTION) {\n return resolveMessageNode(\n typedNode[NodeTypes.INSERTION],\n values,\n locale,\n formatters\n );\n }\n\n if (typedNode.nodeType === NodeTypes.HTML) {\n // Tags are kept intact — rich rendering is handled by the caller\n return resolveMessageNode(\n typedNode[NodeTypes.HTML],\n values,\n locale,\n formatters\n );\n }\n\n if (typedNode.nodeType === NodeTypes.PLURAL) {\n const pluralState = typedNode[\n NodeTypes.PLURAL\n ] as PluralContentState<unknown>;\n const variableName =\n typeof typedNode.variable === 'string'\n ? typedNode.variable\n : DEFAULT_PLURAL_VARIABLE;\n const count = Number(getSelectorValue(values, variableName) ?? 1);\n const selected = getPlural(\n pluralState as PluralContentState<string>,\n count,\n locale\n );\n return resolveMessageNode(selected, values, locale, formatters);\n }\n\n if (typedNode.nodeType === NodeTypes.ENUMERATION) {\n const enumerationState = typedNode[NodeTypes.ENUMERATION] as Record<\n string,\n unknown\n >;\n\n const variableName = (ENUMERATION_METADATA_KEYS.map(\n (metadataKey) => enumerationState[metadataKey]\n ).find((name) => typeof name === 'string') ?? 'count') as string;\n\n const isOrdinal = enumerationState.__intlayer_icu_ordinal === true;\n\n const options: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(enumerationState)) {\n if (!(ENUMERATION_METADATA_KEYS as readonly string[]).includes(key)) {\n options[key] = value;\n }\n }\n\n const selector = getSelectorValue(values, variableName);\n\n let selected: unknown;\n if (isOrdinal && !Number.isNaN(Number(selector))) {\n // ICU `selectordinal` — exact numeric match first, then the CLDR\n // ordinal category, then the fallback\n const ordinalCount = Number(selector);\n const ordinalCategory = getCachedIntl('PluralRules', locale, {\n type: 'ordinal',\n }).select(ordinalCount);\n selected =\n options[String(ordinalCount)] ??\n options[ordinalCategory] ??\n options.fallback ??\n options.other;\n } else if (\n typeof selector === 'number' ||\n !Number.isNaN(Number(selector))\n ) {\n // Exact / range keys first, then a CLDR category kept by the ICU\n // converter (`=1 {…} one {…}`), then the fallback\n const count = Number(selector);\n const matchedKey = findMatchingCondition(options, count);\n selected = matchedKey\n ? options[matchedKey]\n : (options[getCachedIntl('PluralRules', locale).select(count)] ??\n getEnumeration(options, count));\n } else {\n // String selector — ICU `select` converted to an enumeration\n selected = options[String(selector)] ?? options.fallback ?? options.other;\n }\n\n return resolveMessageNode(selected, values, locale, formatters);\n }\n\n if (typedNode.nodeType === NodeTypes.SELECT) {\n const selectState = typedNode[NodeTypes.SELECT] as Record<string, unknown>;\n\n // The node records the ICU variable it was imported from; fall back to\n // `value` for nodes authored directly with `select()`.\n const variableName =\n typeof typedNode.variable === 'string' ? typedNode.variable : 'value';\n\n const selector = getSelectorValue(values, variableName);\n const selected = getSelect(selectState, String(selector ?? ''));\n\n return resolveMessageNode(selected, values, locale, formatters);\n }\n\n if (typedNode.nodeType === NodeTypes.GENDER) {\n const genderState = typedNode[NodeTypes.GENDER] as Record<string, unknown>;\n const genderValue = String(values.gender ?? '');\n const selected =\n genderState[genderValue] ?? genderState.fallback ?? genderState.other;\n return resolveMessageNode(selected, values, locale, formatters);\n }\n\n return node;\n};\n\n/**\n * {@link resolveMessageNode} coerced to a string.\n *\n * This is the whole runtime a compat adapter needs for content that reached\n * the bundle through a built dictionary: the build already converted every\n * dialect construct into intlayer nodes, and the interpreter turned those into\n * callables, so no message parser is involved. Plain strings still get\n * `{{name}}` / `{name}` / `{value, number}` interpolation.\n */\nexport const resolveMessageNodeToString = (\n node: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters\n): string => {\n const resolved = resolveMessageNode(node, values, locale, formatters);\n\n return typeof resolved === 'string' ? resolved : String(resolved ?? '');\n};\n\n/** Converts a raw message string of one dialect into an intlayer node tree. */\nexport type MessageFormatter = (message: string) => unknown;\n\n/**\n * Resolves a raw message — string, or an intlayer node tree — into a final\n * string using interpolation values and locale.\n */\nexport type MessageResolver = (\n message: unknown,\n values?: MessageValues,\n locale?: LocalesValues,\n formatters?: MessageArgumentFormatters\n) => string;\n\n/**\n * Binds {@link resolveMessageNode} to one dialect converter.\n *\n * The compat adapters each speak a single dialect, and referencing the\n * converter directly — rather than picking it from a record keyed by dialect —\n * is what lets a bundler drop the two parsers the adapter never uses.\n *\n * @example\n * ```ts\n * const resolveIcuMessage = createMessageResolver(icuToIntlayerFormatter);\n * resolveIcuMessage('Hello {name}', { name: 'John' }, 'en'); // 'Hello John'\n * ```\n */\nexport const createMessageResolver =\n (formatter: MessageFormatter): MessageResolver =>\n (message, values = {}, locale = 'en' as LocalesValues, formatters) =>\n resolveMessageNodeToString(\n typeof message === 'string' ? formatter(message) : message,\n values,\n locale,\n formatters\n );\n\nconst DIALECT_FORMATTERS: Record<MessageFormatDialect, MessageFormatter> = {\n icu: icuToIntlayerFormatter,\n i18next: i18nextToIntlayerFormatter,\n 'vue-i18n': vueI18nToIntlayerFormatter,\n};\n\n/**\n * Resolves a raw message — string in a library dialect, or an intlayer node\n * tree — into a final string using interpolation values and locale.\n *\n * Selecting the dialect at runtime keeps every converter reachable; a package\n * that only ever needs one should bind it with {@link createMessageResolver}.\n *\n * @example\n * ```ts\n * resolveMessage('Hello {name}', { name: 'John' }, 'en', 'icu');\n * // 'Hello John'\n *\n * resolveMessage(\n * '{count, plural, one {# item} other {# items}}',\n * { count: 3 },\n * 'en',\n * 'icu'\n * );\n * // '3 items'\n * ```\n */\nexport const resolveMessage = (\n message: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n dialect: MessageFormatDialect = 'icu'\n): string =>\n createMessageResolver(DIALECT_FORMATTERS[dialect])(message, values, locale);\n\n/** A parsed token of a tagged message: plain text or a tag with children. */\nexport type TaggedMessageToken =\n | string\n | { tag: string; children: TaggedMessageToken[] };\n\n/**\n * Tokenizes a message containing XML-like tags (`'Visit <link>the docs</link>'`,\n * `'hello <1>{{name}}</1>'`, `'line<br/>break'`) into a token tree.\n *\n * Used by rich-text renderers (`t.rich`, `<Trans components>`,\n * `<i18n-t>` slots) to map tags to framework elements.\n */\nexport const parseTaggedMessage = (message: string): TaggedMessageToken[] => {\n const tokens: TaggedMessageToken[] = [];\n const tagRegex = /<([\\w-]+)\\s*\\/>|<([\\w-]+)[^>]*>([\\s\\S]*?)<\\/\\2>/g;\n let lastIndex = 0;\n let match = tagRegex.exec(message);\n\n while (match !== null) {\n if (match.index > lastIndex) {\n tokens.push(message.slice(lastIndex, match.index));\n }\n\n const [, selfClosingTag, tag, inner] = match;\n\n if (selfClosingTag) {\n tokens.push({ tag: selfClosingTag, children: [] });\n } else if (tag) {\n tokens.push({ tag, children: parseTaggedMessage(inner ?? '') });\n }\n\n lastIndex = match.index + match[0].length;\n match = tagRegex.exec(message);\n }\n\n if (lastIndex < message.length) {\n tokens.push(message.slice(lastIndex));\n }\n\n return tokens;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAqCA,MAAM,4BAA4B;CAChC;CACA;CACA;AACF;;;;AAKA,MAAM,oBAAoB,QAAuB,SAA0B;CACzE,IAAI,QAAQ,QAAQ,OAAO,OAAO;CAElC,IAAI,UAAmB;CACvB,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG;EAClC,IACE,YAAY,QACZ,YAAY,UACZ,OAAO,YAAY,UAEnB;EAEF,UAAW,QAAoC;CACjD;CACA,OAAO;AACT;;AA0BA,MAAM,0BAA0B;CAAC;CAAU;CAAQ;AAAM;;;;;AAMzD,MAAM,kBACJ,OACA,MACA,OACA,QACA,eACW;CACX,MAAM,kBACJ,CAAC,wBAAwB,SAAS,IAAI,KACtC,cACA,OAAO,OAAO,YAAY,IAAI,IAC1B,WAAW,QACX;CAEN,IAAI,iBAAiB;EACnB,MAAM,YAAY,gBAAgB,OAAO;GAAE;GAAQ;EAAM,CAAC;EAC1D,OAAO,cAAc,QAAQ,cAAc,SACvC,KACA,OAAO,SAAS;CACtB;CAEA,IAAI;EACF,IAAI,SAAS,UAAU;GACrB,MAAM,cAAc,OAAO,KAAK;GAChC,IAAI,UAAU,WACZ,OAAOA,iCAAc,gBAAgB,QAAQ,EAC3C,OAAO,UACT,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,IAAI,UAAU,WACZ,OAAOA,iCAAc,gBAAgB,QAAQ,EAC3C,uBAAuB,EACzB,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,OAAOA,iCAAc,gBAAgB,MAAM,CAAC,CAAC,OAAO,WAAW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,aAAa,WAAW,WAAW,OAAO,YAAY,EAAE;AACxE;;;;;;;;;;;;;;AA6BA,MAAa,yBACV,eACA,SAAS,SAAS,CAAC,GAAG,SAAS,MAAuB,eACrD,2BACE,OAAO,YAAY,WAAW,UAAU,OAAO,IAAI,SACnD,QACA,QACA,UACF;AAEJ,MAAM,qBAAqE;CACzE,KAAKM;CACL,SAASC;CACT,YAAYC;AACd;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,kBACX,SACA,SAAwB,CAAC,GACzB,SAAwB,MACxB,UAAgC,UAEhC,sBAAsB,mBAAmB,QAAQ,CAAC,CAAC,SAAS,QAAQ,MAAM;;;;;;;;AAc5E,MAAa,sBAAsB,YAA0C;CAC3E,MAAM,SAA+B,CAAC;CACtC,MAAM,WAAW;CACjB,IAAI,YAAY;CAChB,IAAI,QAAQ,SAAS,KAAK,OAAO;CAEjC,OAAO,UAAU,MAAM;EACrB,IAAI,MAAM,QAAQ,WAChB,OAAO,KAAK,QAAQ,MAAM,WAAW,MAAM,KAAK,CAAC;EAGnD,MAAM,GAAG,gBAAgB,KAAK,SAAS;EAEvC,IAAI,gBACF,OAAO,KAAK;GAAE,KAAK;GAAgB,UAAU,CAAC;EAAE,CAAC;OAC5C,IAAI,KACT,OAAO,KAAK;GAAE;GAAK,UAAU,mBAAmB,SAAS,EAAE;EAAE,CAAC;EAGhE,YAAY,MAAM,QAAQ,MAAM,EAAE,CAAC;EACnC,QAAQ,SAAS,KAAK,OAAO;CAC/B;CAEA,IAAI,YAAY,QAAQ,QACtB,OAAO,KAAK,QAAQ,MAAM,SAAS,CAAC;CAGtC,OAAO;AACT"}
1
+ {"version":3,"file":"resolveMessage.cjs","names":["getCachedIntl","NodeTypes","DEFAULT_PLURAL_VARIABLE","getPlural","findMatchingCondition","getEnumeration","getSelect","icuToIntlayerFormatter","i18nextToIntlayerFormatter","vueI18nToIntlayerFormatter"],"sources":["../../../src/messageFormat/resolveMessage.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { getCachedIntl } from '../formatters';\nimport {\n findMatchingCondition,\n getEnumeration,\n} from '../interpreter/getEnumeration';\nimport { getPlural } from '../interpreter/getPlural';\nimport { getSelect } from '../interpreter/getSelect';\nimport {\n DEFAULT_PLURAL_VARIABLE,\n type PluralContentState,\n} from '../transpiler/plural/plural';\nimport { i18nextToIntlayerFormatter } from './i18next';\nimport { icuToIntlayerFormatter } from './ICU';\nimport { vueI18nToIntlayerFormatter } from './vue-i18n';\n\n/**\n * Runtime counterpart of the `messageFormat` converters.\n *\n * The converters (`icuToIntlayerFormatter`, `i18nextToIntlayerFormatter`,\n * `vueI18nToIntlayerFormatter`) turn library-specific message syntax into\n * intlayer nodes (`insert`, `plural`, `enu`, `gender`, `html`). This module\n * resolves those nodes — or raw message strings — into a final string using\n * the provided interpolation values and locale.\n *\n * It is the mutualized resolution engine used by the compat adapter packages\n * (`@intlayer/i18next`, `@intlayer/next-intl`, `@intlayer/vue-i18n`, …).\n */\n\n/** Message syntax dialect of the source i18n library. */\nexport type MessageFormatDialect = 'icu' | 'i18next' | 'vue-i18n';\n\n/** Interpolation values passed alongside a translation lookup. */\nexport type MessageValues = Record<string, unknown>;\n\n/** Internal enumeration metadata keys injected by the converters. */\nconst ENUMERATION_METADATA_KEYS = [\n '__intlayer_icu_var',\n '__intlayer_icu_ordinal',\n '__intlayer_vue_i18n_var',\n] as const;\n\n/**\n * Resolves a possibly-dotted path (`user.name`) inside the values object.\n */\nconst resolveValuePath = (values: MessageValues, path: string): unknown => {\n if (path in values) return values[path];\n\n let current: unknown = values;\n for (const part of path.split('.')) {\n if (\n current === null ||\n current === undefined ||\n typeof current !== 'object'\n ) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n};\n\n/** Context handed to a {@link MessageArgumentFormatter}. */\nexport type MessageArgumentFormatterContext = {\n /** Active locale. */\n locale: LocalesValues;\n /** Third segment of the argument (`EUR` in `{price, currency, EUR}`). */\n style?: string;\n};\n\n/**\n * Formats an argument whose type is not built in, e.g. `currency` in\n * `{price, currency, EUR}`.\n */\nexport type MessageArgumentFormatter = (\n value: unknown,\n context: MessageArgumentFormatterContext\n) => unknown;\n\n/** Custom argument formatters, keyed by argument type. */\nexport type MessageArgumentFormatters = Record<\n string,\n MessageArgumentFormatter\n>;\n\n/** Argument types handled natively; custom formatters cannot override them. */\nconst BUILT_IN_ARGUMENT_TYPES = ['number', 'date', 'time'];\n\n/**\n * Formats an ICU-style formatted argument (`{value, number, percent}`).\n * Types that are not built in go to the matching custom formatter, if any.\n */\nconst formatArgument = (\n value: unknown,\n type: string,\n style: string | undefined,\n locale: LocalesValues,\n formatters?: MessageArgumentFormatters\n): string => {\n const customFormatter =\n !BUILT_IN_ARGUMENT_TYPES.includes(type) &&\n formatters &&\n Object.hasOwn(formatters, type)\n ? formatters[type]\n : undefined;\n\n if (customFormatter) {\n const formatted = customFormatter(value, { locale, style });\n return formatted === null || formatted === undefined\n ? ''\n : String(formatted);\n }\n\n try {\n if (type === 'number') {\n const numberValue = Number(value);\n if (style === 'percent') {\n return getCachedIntl('NumberFormat', locale, {\n style: 'percent',\n }).format(numberValue);\n }\n if (style === 'integer') {\n return getCachedIntl('NumberFormat', locale, {\n maximumFractionDigits: 0,\n }).format(numberValue);\n }\n return getCachedIntl('NumberFormat', locale).format(numberValue);\n }\n\n if (type === 'date' || type === 'time') {\n const dateValue =\n value instanceof Date ? value : new Date(value as string | number);\n const dateTimeStyle = (\n ['short', 'medium', 'long', 'full'].includes(style ?? '')\n ? style\n : type === 'date'\n ? 'medium'\n : 'short'\n ) as 'short' | 'medium' | 'long' | 'full';\n\n return getCachedIntl(\n 'DateTimeFormat',\n locale,\n type === 'date'\n ? { dateStyle: dateTimeStyle }\n : { timeStyle: dateTimeStyle }\n ).format(dateValue);\n }\n } catch {\n // Fall through to the raw string representation below\n }\n\n return String(value);\n};\n\n/**\n * Placeholders read in plain strings: `'default'` reads `{{name}}`, `{name}`\n * and `{value, number}`; `'double-brace'` reads only `{{…}}`, like i18next,\n * which prints single braces (and ICU blocks) as text.\n */\nexport type MessageInterpolation = 'default' | 'double-brace';\n\n/**\n * Interpolates a message template with values.\n *\n * Handles, in order:\n * 1. Intlayer insertions `{{name}}` (whitespace-tolerant, dotted paths),\n * optionally formatted the i18next way (`{{price, number}}`)\n * 2. ICU formatted arguments `{value, number}` / `{ts, date, long}`\n * 3. Bare single-brace arguments `{name}` (ICU / vue-i18n simple args)\n *\n * With `'double-brace'` interpolation, only step 1 runs.\n */\nexport const interpolateMessage = (\n template: string,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters,\n interpolation: MessageInterpolation = 'default'\n): string => {\n const interpolated = template.replace(\n /\\{\\{\\s*([^{},]+?)\\s*(?:,\\s*(\\w+)\\s*(?:,\\s*([^{}]+?)\\s*)?)?\\}\\}/g,\n (match, path: string, type: string | undefined, style?: string) => {\n // i18next's unescaped `{{- name}}` is read as `-name`\n const value =\n resolveValuePath(values, path) ??\n resolveValuePath(values, path.replace(/^-\\s+/, '-'));\n if (value === undefined) return match;\n return type\n ? formatArgument(value, type, style, locale, formatters)\n : String(value);\n }\n );\n\n if (interpolation === 'double-brace') return interpolated;\n\n return interpolated\n .replace(\n /\\{\\s*([\\w.]+)\\s*,\\s*(\\w+)\\s*(?:,\\s*([^}]+?)\\s*)?\\}/g,\n (match, path: string, type: string, style: string | undefined) => {\n const value = resolveValuePath(values, path);\n if (value === undefined) return match;\n return formatArgument(value, type, style, locale, formatters);\n }\n )\n .replace(/\\{\\s*([\\w.]+)\\s*\\}/g, (match, path: string) => {\n const value = resolveValuePath(values, path);\n return value === undefined ? match : String(value);\n });\n};\n\n/** Reads the selector value of an enumeration/plural node from the values. */\nconst getSelectorValue = (\n values: MessageValues,\n variableName: string\n): unknown => values[variableName] ?? values.count ?? values.n;\n\n/**\n * Resolves an intlayer message node tree (as produced by the\n * `*ToIntlayerFormatter` converters, or already present in a built\n * dictionary) into its final value using interpolation values and locale.\n *\n * Function nodes (produced by the interpreter plugins for `insertion`,\n * `enumeration` and `plural` content) are invoked with the values.\n */\nexport const resolveMessageNode = (\n node: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters,\n interpolation: MessageInterpolation = 'default'\n): unknown => {\n if (node === null || node === undefined) return node;\n\n if (typeof node === 'string') {\n return interpolateMessage(node, values, locale, formatters, interpolation);\n }\n\n if (typeof node === 'number' || typeof node === 'boolean') {\n return String(node);\n }\n\n // Interpreter-transformed nodes (insertion/enumeration/plural plugins)\n // are exposed as callables taking the interpolation values.\n if (typeof node === 'function') {\n try {\n return resolveMessageNode(\n (node as (arg: MessageValues) => unknown)(values),\n values,\n locale,\n formatters,\n interpolation\n );\n } catch {\n return undefined;\n }\n }\n\n if (Array.isArray(node)) {\n return node\n .map((item) =>\n String(\n resolveMessageNode(item, values, locale, formatters, interpolation) ??\n ''\n )\n )\n .join('');\n }\n\n const typedNode = node as Record<string, unknown> & { nodeType?: string };\n\n if (typedNode.nodeType === NodeTypes.INSERTION) {\n return resolveMessageNode(\n typedNode[NodeTypes.INSERTION],\n values,\n locale,\n formatters,\n interpolation\n );\n }\n\n if (typedNode.nodeType === NodeTypes.HTML) {\n // Tags are kept intact — rich rendering is handled by the caller\n return resolveMessageNode(\n typedNode[NodeTypes.HTML],\n values,\n locale,\n formatters,\n interpolation\n );\n }\n\n if (typedNode.nodeType === NodeTypes.PLURAL) {\n const pluralState = typedNode[\n NodeTypes.PLURAL\n ] as PluralContentState<unknown>;\n const variableName =\n typeof typedNode.variable === 'string'\n ? typedNode.variable\n : DEFAULT_PLURAL_VARIABLE;\n const count = Number(getSelectorValue(values, variableName) ?? 1);\n const selected = getPlural(\n pluralState as PluralContentState<string>,\n count,\n locale\n );\n return resolveMessageNode(\n selected,\n values,\n locale,\n formatters,\n interpolation\n );\n }\n\n if (typedNode.nodeType === NodeTypes.ENUMERATION) {\n const enumerationState = typedNode[NodeTypes.ENUMERATION] as Record<\n string,\n unknown\n >;\n\n const variableName = (ENUMERATION_METADATA_KEYS.map(\n (metadataKey) => enumerationState[metadataKey]\n ).find((name) => typeof name === 'string') ?? 'count') as string;\n\n const isOrdinal = enumerationState.__intlayer_icu_ordinal === true;\n\n const options: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(enumerationState)) {\n if (!(ENUMERATION_METADATA_KEYS as readonly string[]).includes(key)) {\n options[key] = value;\n }\n }\n\n const selector = getSelectorValue(values, variableName);\n\n let selected: unknown;\n if (isOrdinal && !Number.isNaN(Number(selector))) {\n // ICU `selectordinal` — exact numeric match first, then the CLDR\n // ordinal category, then the fallback\n const ordinalCount = Number(selector);\n const ordinalCategory = getCachedIntl('PluralRules', locale, {\n type: 'ordinal',\n }).select(ordinalCount);\n selected =\n options[String(ordinalCount)] ??\n options[ordinalCategory] ??\n options.fallback ??\n options.other;\n } else if (\n typeof selector === 'number' ||\n !Number.isNaN(Number(selector))\n ) {\n // Exact / range keys first, then a CLDR category kept by the ICU\n // converter (`=1 {…} one {…}`), then the fallback\n const count = Number(selector);\n const matchedKey = findMatchingCondition(options, count);\n selected = matchedKey\n ? options[matchedKey]\n : (options[getCachedIntl('PluralRules', locale).select(count)] ??\n getEnumeration(options, count));\n } else {\n // String selector — ICU `select` converted to an enumeration\n selected = options[String(selector)] ?? options.fallback ?? options.other;\n }\n\n return resolveMessageNode(\n selected,\n values,\n locale,\n formatters,\n interpolation\n );\n }\n\n if (typedNode.nodeType === NodeTypes.SELECT) {\n const selectState = typedNode[NodeTypes.SELECT] as Record<string, unknown>;\n\n // The node records the ICU variable it was imported from; fall back to\n // `value` for nodes authored directly with `select()`.\n const variableName =\n typeof typedNode.variable === 'string' ? typedNode.variable : 'value';\n\n const selector = getSelectorValue(values, variableName);\n const selected = getSelect(selectState, String(selector ?? ''));\n\n return resolveMessageNode(\n selected,\n values,\n locale,\n formatters,\n interpolation\n );\n }\n\n if (typedNode.nodeType === NodeTypes.GENDER) {\n const genderState = typedNode[NodeTypes.GENDER] as Record<string, unknown>;\n const genderValue = String(values.gender ?? '');\n const selected =\n genderState[genderValue] ?? genderState.fallback ?? genderState.other;\n return resolveMessageNode(\n selected,\n values,\n locale,\n formatters,\n interpolation\n );\n }\n\n return node;\n};\n\n/**\n * {@link resolveMessageNode} coerced to a string.\n *\n * This is the whole runtime a compat adapter needs for content that reached\n * the bundle through a built dictionary: the build already converted every\n * dialect construct into intlayer nodes, and the interpreter turned those into\n * callables, so no message parser is involved. Plain strings still get\n * `{{name}}` / `{name}` / `{value, number}` interpolation (only `{{…}}` with\n * `'double-brace'` interpolation).\n */\nexport const resolveMessageNodeToString = (\n node: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n formatters?: MessageArgumentFormatters,\n interpolation: MessageInterpolation = 'default'\n): string => {\n const resolved = resolveMessageNode(\n node,\n values,\n locale,\n formatters,\n interpolation\n );\n\n return typeof resolved === 'string' ? resolved : String(resolved ?? '');\n};\n\n/** Converts a raw message string of one dialect into an intlayer node tree. */\nexport type MessageFormatter = (message: string) => unknown;\n\n/**\n * Resolves a raw message — string, or an intlayer node tree — into a final\n * string using interpolation values and locale.\n */\nexport type MessageResolver = (\n message: unknown,\n values?: MessageValues,\n locale?: LocalesValues,\n formatters?: MessageArgumentFormatters\n) => string;\n\n/**\n * Binds {@link resolveMessageNode} to one dialect converter.\n *\n * The compat adapters each speak a single dialect, and referencing the\n * converter directly — rather than picking it from a record keyed by dialect —\n * is what lets a bundler drop the two parsers the adapter never uses.\n *\n * @example\n * ```ts\n * const resolveIcuMessage = createMessageResolver(icuToIntlayerFormatter);\n * resolveIcuMessage('Hello {name}', { name: 'John' }, 'en'); // 'Hello John'\n * ```\n */\nexport const createMessageResolver =\n (\n formatter: MessageFormatter,\n interpolation: MessageInterpolation = 'default'\n ): MessageResolver =>\n (message, values = {}, locale = 'en' as LocalesValues, formatters) =>\n resolveMessageNodeToString(\n typeof message === 'string' ? formatter(message) : message,\n values,\n locale,\n formatters,\n interpolation\n );\n\nconst DIALECT_FORMATTERS: Record<MessageFormatDialect, MessageFormatter> = {\n icu: icuToIntlayerFormatter,\n i18next: i18nextToIntlayerFormatter,\n 'vue-i18n': vueI18nToIntlayerFormatter,\n};\n\n/** i18next reads only `{{…}}`; the other dialects use single braces too. */\nconst DIALECT_INTERPOLATION: Record<\n MessageFormatDialect,\n MessageInterpolation\n> = {\n icu: 'default',\n i18next: 'double-brace',\n 'vue-i18n': 'default',\n};\n\n/**\n * Resolves a raw message — string in a library dialect, or an intlayer node\n * tree — into a final string using interpolation values and locale.\n *\n * Selecting the dialect at runtime keeps every converter reachable; a package\n * that only ever needs one should bind it with {@link createMessageResolver}.\n *\n * @example\n * ```ts\n * resolveMessage('Hello {name}', { name: 'John' }, 'en', 'icu');\n * // 'Hello John'\n *\n * resolveMessage(\n * '{count, plural, one {# item} other {# items}}',\n * { count: 3 },\n * 'en',\n * 'icu'\n * );\n * // '3 items'\n * ```\n */\nexport const resolveMessage = (\n message: unknown,\n values: MessageValues = {},\n locale: LocalesValues = 'en' as LocalesValues,\n dialect: MessageFormatDialect = 'icu'\n): string =>\n createMessageResolver(\n DIALECT_FORMATTERS[dialect],\n DIALECT_INTERPOLATION[dialect]\n )(message, values, locale);\n\n/** A parsed token of a tagged message: plain text or a tag with children. */\nexport type TaggedMessageToken =\n | string\n | { tag: string; children: TaggedMessageToken[] };\n\n/**\n * Tokenizes a message containing XML-like tags (`'Visit <link>the docs</link>'`,\n * `'hello <1>{{name}}</1>'`, `'line<br/>break'`) into a token tree.\n *\n * Used by rich-text renderers (`t.rich`, `<Trans components>`,\n * `<i18n-t>` slots) to map tags to framework elements.\n */\nexport const parseTaggedMessage = (message: string): TaggedMessageToken[] => {\n const tokens: TaggedMessageToken[] = [];\n const tagRegex = /<([\\w-]+)\\s*\\/>|<([\\w-]+)[^>]*>([\\s\\S]*?)<\\/\\2>/g;\n let lastIndex = 0;\n let match = tagRegex.exec(message);\n\n while (match !== null) {\n if (match.index > lastIndex) {\n tokens.push(message.slice(lastIndex, match.index));\n }\n\n const [, selfClosingTag, tag, inner] = match;\n\n if (selfClosingTag) {\n tokens.push({ tag: selfClosingTag, children: [] });\n } else if (tag) {\n tokens.push({ tag, children: parseTaggedMessage(inner ?? '') });\n }\n\n lastIndex = match.index + match[0].length;\n match = tagRegex.exec(message);\n }\n\n if (lastIndex < message.length) {\n tokens.push(message.slice(lastIndex));\n }\n\n return tokens;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAqCA,MAAM,4BAA4B;CAChC;CACA;CACA;AACF;;;;AAKA,MAAM,oBAAoB,QAAuB,SAA0B;CACzE,IAAI,QAAQ,QAAQ,OAAO,OAAO;CAElC,IAAI,UAAmB;CACvB,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG;EAClC,IACE,YAAY,QACZ,YAAY,UACZ,OAAO,YAAY,UAEnB;EAEF,UAAW,QAAoC;CACjD;CACA,OAAO;AACT;;AA0BA,MAAM,0BAA0B;CAAC;CAAU;CAAQ;AAAM;;;;;AAMzD,MAAM,kBACJ,OACA,MACA,OACA,QACA,eACW;CACX,MAAM,kBACJ,CAAC,wBAAwB,SAAS,IAAI,KACtC,cACA,OAAO,OAAO,YAAY,IAAI,IAC1B,WAAW,QACX;CAEN,IAAI,iBAAiB;EACnB,MAAM,YAAY,gBAAgB,OAAO;GAAE;GAAQ;EAAM,CAAC;EAC1D,OAAO,cAAc,QAAQ,cAAc,SACvC,KACA,OAAO,SAAS;CACtB;CAEA,IAAI;EACF,IAAI,SAAS,UAAU;GACrB,MAAM,cAAc,OAAO,KAAK;GAChC,IAAI,UAAU,WACZ,OAAOA,iCAAc,gBAAgB,QAAQ,EAC3C,OAAO,UACT,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,IAAI,UAAU,WACZ,OAAOA,iCAAc,gBAAgB,QAAQ,EAC3C,uBAAuB,EACzB,CAAC,CAAC,CA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S,KAAK,OAAO;CAC/B;CAEA,IAAI,YAAY,QAAQ,QACtB,OAAO,KAAK,QAAQ,MAAM,SAAS,CAAC;CAGtC,OAAO;AACT"}
@@ -13,7 +13,8 @@
13
13
  *
14
14
  */
15
15
  const getInsertion = (content, values) => content.replace(/\{\{\s*(.*?)\s*\}\}/g, (_, key) => {
16
- return (values[key.trim()] ?? "").toString();
16
+ const trimmedKey = key.trim();
17
+ return (values[trimmedKey] ?? values[trimmedKey.replace(/^-\s+/, "-")] ?? "").toString();
17
18
  });
18
19
 
19
20
  export { getInsertion };
@@ -1 +1 @@
1
- {"version":3,"file":"getInsertion.mjs","names":[],"sources":["../../../src/interpreter/getInsertion.ts"],"sourcesContent":["import type { InsertionContent } from '../transpiler';\n\n/**\n * Allow to insert values in a string.\n *\n * Usage:\n *\n * ```ts\n * const content = getInsertion('Hello {{name}}!', {\n * name: 'John',\n * });\n * // 'Hello John!'\n * ```\n *\n */\nexport const getInsertion = (\n content: string,\n values: { [K in InsertionContent['fields'][number]]: string | number }\n) =>\n content.replace(/\\{\\{\\s*(.*?)\\s*\\}\\}/g, (_, key) => {\n const trimmedKey = key.trim();\n return (values[trimmedKey] ?? '').toString();\n });\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,gBACX,SACA,WAEA,QAAQ,QAAQ,yBAAyB,GAAG,QAAQ;CAElD,QAAQ,OADW,IAAI,KACC,MAAM,GAAE,CAAE,SAAS;AAC7C,CAAC"}
1
+ {"version":3,"file":"getInsertion.mjs","names":[],"sources":["../../../src/interpreter/getInsertion.ts"],"sourcesContent":["import type { InsertionContent } from '../transpiler';\n\n/**\n * Allow to insert values in a string.\n *\n * Usage:\n *\n * ```ts\n * const content = getInsertion('Hello {{name}}!', {\n * name: 'John',\n * });\n * // 'Hello John!'\n * ```\n *\n */\nexport const getInsertion = (\n content: string,\n values: { [K in InsertionContent['fields'][number]]: string | number }\n) =>\n content.replace(/\\{\\{\\s*(.*?)\\s*\\}\\}/g, (_, key) => {\n const trimmedKey = key.trim();\n\n // i18next's unescaped `{{- name}}` is read as `-name`\n const value =\n values[trimmedKey] ?? values[trimmedKey.replace(/^-\\s+/, '-')];\n\n return (value ?? '').toString();\n });\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,gBACX,SACA,WAEA,QAAQ,QAAQ,yBAAyB,GAAG,QAAQ;CAClD,MAAM,aAAa,IAAI,KAAK;CAM5B,QAFE,OAAO,eAAe,OAAO,WAAW,QAAQ,SAAS,GAAG,MAE7C,GAAE,CAAE,SAAS;AAChC,CAAC"}