@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.
- package/dist/cjs/interpreter/getInsertion.cjs +2 -1
- package/dist/cjs/interpreter/getInsertion.cjs.map +1 -1
- package/dist/cjs/messageFormat/i18next.cjs +59 -251
- package/dist/cjs/messageFormat/i18next.cjs.map +1 -1
- package/dist/cjs/messageFormat/resolveMessage.cjs +40 -27
- package/dist/cjs/messageFormat/resolveMessage.cjs.map +1 -1
- package/dist/esm/interpreter/getInsertion.mjs +2 -1
- package/dist/esm/interpreter/getInsertion.mjs.map +1 -1
- package/dist/esm/messageFormat/i18next.mjs +59 -251
- package/dist/esm/messageFormat/i18next.mjs.map +1 -1
- package/dist/esm/messageFormat/resolveMessage.mjs +40 -27
- package/dist/esm/messageFormat/resolveMessage.mjs.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/messageFormat/i18next.d.ts.map +1 -1
- package/dist/types/messageFormat/index.d.ts +2 -2
- package/dist/types/messageFormat/resolveMessage.d.ts +14 -5
- package/dist/types/messageFormat/resolveMessage.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveMessage.mjs","names":[],"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,OAAO,cAAc,gBAAgB,QAAQ,EAC3C,OAAO,UACT,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,IAA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wB,CAAC,GACzB,SAAwB,MACxB,eACW;CACX,MAAM,WAAW,mBAAmB,MAAM,QAAQ,QAAQ,UAAU;CAEpE,OAAO,OAAO,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,KAAK;CACL,SAAS;CACT,YAAY;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.mjs","names":[],"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,OAAO,cAAc,gBAAgB,QAAQ,EAC3C,OAAO,UACT,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,IAAI,UAAU,WACZ,OAAO,cAAc,gBAAgB,QAAQ,EAC3C,uBAAuB,EACzB,CAAC,CAAC,CAAC,OAAO,WAAW;GAEvB,OAA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SAAS,CAAC;CAGtC,OAAO;AACT"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -116,7 +116,7 @@ import { JsonValue, icuToIntlayerFormatter, intlayerToICUFormatter } from "./mes
|
|
|
116
116
|
import { i18nextToIntlayerFormatter, intlayerToI18nextFormatter } from "./messageFormat/i18next.js";
|
|
117
117
|
import { navigatePath } from "./messageFormat/navigatePath.js";
|
|
118
118
|
import { PortableObject, intlayerToPortableObjectFormatter, portableObjectToIntlayerFormatter } from "./messageFormat/po.js";
|
|
119
|
-
import { MessageArgumentFormatter, MessageArgumentFormatterContext, MessageArgumentFormatters, MessageFormatDialect, MessageFormatter, MessageResolver, MessageValues, TaggedMessageToken, createMessageResolver, interpolateMessage, parseTaggedMessage, resolveMessage, resolveMessageNode, resolveMessageNodeToString } from "./messageFormat/resolveMessage.js";
|
|
119
|
+
import { MessageArgumentFormatter, MessageArgumentFormatterContext, MessageArgumentFormatters, MessageFormatDialect, MessageFormatter, MessageInterpolation, MessageResolver, MessageValues, TaggedMessageToken, createMessageResolver, interpolateMessage, parseTaggedMessage, resolveMessage, resolveMessageNode, resolveMessageNodeToString } from "./messageFormat/resolveMessage.js";
|
|
120
120
|
import { intlayerToVueI18nFormatter, vueI18nToIntlayerFormatter } from "./messageFormat/vue-i18n.js";
|
|
121
121
|
import "./transpiler/index.js";
|
|
122
122
|
import { checkIsURLAbsolute } from "./utils/checkIsURLAbsolute.js";
|
|
@@ -128,4 +128,4 @@ import { CookieBuildAttributes, LocaleStorage, LocaleStorageClient, LocaleStorag
|
|
|
128
128
|
import { YamlRecord, YamlValue, parseYaml } from "./utils/parseYaml.js";
|
|
129
129
|
import { stringifyYaml } from "./utils/stringifyYaml.js";
|
|
130
130
|
import "./utils/index.js";
|
|
131
|
-
export { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_NAME_START_R, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, AmbientLocaleResolver, AsyncAmbientLocaleResolver, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, type BlockQuoteNode, BlockSyntaxProbe, type BoldTextNode, type BreakLineNode, type BreakThematicNode, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, COMPOSITE_ID_SEPARATOR, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CachedIntl, CachedIntl as Intl, ChunkSuspenseCache, type CodeBlockNode, type CodeFencedNode, type CodeInlineNode, CollectedChunk, CollectedChunks, type CompileOptions, type ComponentOverrides, ConditionCond, ConditionContent, ConditionContentStates, CookieBuildAttributes, type CustomComponentNode, DEFAULT_PLURAL_VARIABLE, DEFAULT_VARIANT_ID, DO_NOT_PROCESS_HTML_ELEMENTS, DateTimePreset, DeepTransformContent, DictionaryRead, DotPath, DynamicChunkTransform, DynamicContent, DynamicContentStore, DynamicDictionaryLoader, DynamicLoaderMap, DynamicReadContext, DynamicReadParams, DynamicReader, DynamicStoreRead, type ElementType, EnterFormat, EnumerationCond, EnumerationContent, EnumerationContentState, type EscapedTextNode, FENCE_DELIMITER_R, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, FileCond, type FileContent, type FileContentConstructor, type FootnoteNode, type FootnoteReferenceNode, type GFMTaskNode, GFM_TASK_R, Gender, GenderCond, GenderContent, GenderContentStates, type GenerateSitemapOptions, GetNestingResult, type GetPrefixOptions, type GetPrefixResult, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, type HTMLCommentNode, HTMLContent, HTMLContentConstructor, type HTMLNode, type HTMLSelfClosingNode, type HTMLTag, HTMLTagsType, HTMLValidationIssue, HTMLValidationResult, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_TAGS, type HeadingNode, type HeadingSetextNode, IInterpreterPlugin, IInterpreterPluginState, INLINE_SKIP_R, INTERPOLATION_R, type ImageNode, InsertionCond, InsertionContent, InsertionContentConstructor, InterpolableNode, IntlConstructorName, IsAny, type ItalicTextNode, JsonValue, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LOOKAHEAD, type LinkAngleBraceNode, type LinkBareURLNode, type LinkNode, ListFormatOptions, ListType, type LocaleDomainMap, type LocaleRequest, LocaleStorage, LocaleStorageClient, LocaleStorageClientOptions, LocaleStorageOptions, LocaleStorageServer, LocaleStorageServerOptions, type LocalizedPathResult, MarkdownContent, MarkdownContentConstructor, type MarkdownContext, type MarkdownOptions, MarkdownReferences, type MarkdownRuntime, type HTMLValidationIssue as MarkdownValidationIssue, MarkdownValidationResult, type MarkedTextNode, MatchedQualifiedEntryIds, MessageArgumentFormatter, MessageArgumentFormatterContext, MessageArgumentFormatters, MessageFormatDialect, MessageFormatter, MessageResolver, MessageValues, NAMED_CODES_TO_UNICODE, NP_TABLE_R, NestedCond, NestedContent, NestedContentState, NestedFieldReferences, type NestedParser, type NewlineNode, NodeProps, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, type OrderedListNode, PARAGRAPH_R, PRELOADED_DYNAMIC_KEY, type ParagraphNode, type ParseState, ParsedMarkdown, type Parser, type ParserResult, PlainDynamicLoaderMap, Plugins, PluralCategory, PluralCond, PluralContent, PluralContentState, PluralOptions, PortableObject, PreloadableDynamicLoaderMap, PreloadedDynamicEntry, Priority, PriorityValue, type ProxyMode, type ProxyStorageSuppressionPurpose, QUALIFIER_DYNAMIC_METADATA_KEY, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, QualifiedDynamicLoaderMap, QualifiedDynamicLoaderTree, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, type ReferenceImageNode, type ReferenceLinkNode, type ReferenceNode, type RenderRuleHook, ResolvedDynamicLoader, type Rule, type RuleOutput, RuleScope, RuleScopeValue, RuleType, RuleTypeValue, type Rules, SCOPE_BLOCK, SCOPE_BOTH, SCOPE_INLINE, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, SelectCond, SelectContent, SelectContentStates, SelectSelector, SettledDynamicContent, type SitemapUrlEntry, type StrikethroughTextNode, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, type TableNode, type TableSeparatorNode, TaggedMessageToken, type TextNode, TransformCacheWrite, TranslationCond, TranslationContent, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, UnionKeys, type UnorderedListNode, VOID_HTML_ELEMENTS, ValidDotPathsFor, ValueAtKey, WrappedIntl, YamlRecord, YamlValue, allowInline, anyScopeRegex, attributeValueToNodePropValue, bindInsertedValues, bindIntl, blockRegex, buildMaskPlugin, captureNothing, checkIsURLAbsolute, checkMissingLocalesPlugin, collectQualifiedChunks, collectTransformCacheWrites, compact, compareItemIds, compareItemSegments, comparePaths, compile, compileWithOptions, condition as cond, conditionPlugin, createChunkSuspenseCache, createCompiler, createDynamicContentStore, createMessageResolver, createRenderer, currency, cx, date, deepTransformNode, deleteTransformCacheWrites, editDictionaryByKeyPath, enumeration as enu, enumerationPlugin, fallbackPlugin, type file, type fileContent, filePlugin, filterMissingTranslationsOnlyPlugin, filterTranslationsOnlyPlugin, findMatchingCondition, findPlainDynamicLoader, formatProxyEnabledMessage, gender, genderPlugin, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex, generateSitemap, generateSitemapUrl, get, getBasePlugins, getBrowserLocale, getCachedIntl, getCachedLocaleFromStorageClient, getCanonicalPath, getCondition, getContent, getContentNodeByKeyPath, getCookie, getDefaultNode, getDictionary, getDictionaryAsync, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getDictionaryTransformCacheKey, getDomainHostname, getDomainOrigin, getDynamicChunkArgument, getDynamicChunks, getEditedContent, getEditedDictionary, getEmptyNode, getEnumeration, getFilterMissingTranslationsContent, getFilterMissingTranslationsDictionary, getFilterTranslationsOnlyContent, getFilterTranslationsOnlyDictionary, getFilteredLocalesContent, getFilteredLocalesDictionary, getGender, getHTML, getHTMLTextDir, getInsertion, getInsertionValues, getInternalPath, getInterpolableContent, getIntlayer, getIntlayerAsync, getIntlayerNodePrototype, getLocale, getLocaleFromDomain, getLocaleFromPath, getLocaleFromRequest, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, getLocaleLang, getLocaleName, getLocalizedContent, getLocalizedMetadata, getLocalizedPath, getLocalizedUrl, getMarkdownMetadata, getMaskContent, getMissingLocalesContent, getMissingLocalesContentFromDictionary, getMultilingualDictionary, getMultilingualUrls, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNesting, getNodeChildren, getNodeType, getPathWithoutLocale, getPerLocaleDictionary, getPluginsCacheKey, getPlural, getPrefix, getPreloadLocale, getPreloadedDictionary, getReplacedValuesContent, getRewritePath, getRewriteRules, getRuleSet, getSelect, getSplittedContent, getSplittedDictionaryContent, getTranslation, getVariantIds, html, i18nextToIntlayerFormatter, icuToIntlayerFormatter, inlineRegex, insertion as insert, insertContentInDictionary, insertionPlugin, interpolateMessage, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, isDeclaredItem, isDeclaredLocale, isInterpolableWrapperNode, isLocaleExclusiveOnDomain, isProxyStorageLocaleEnabled, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, isSameKeyPath, isValidElement, list, loadDynamicDictionary, loadingContentPlaceholder, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, matchQualifiedEntryIds, markdown as md, mergeDictionaries, mergeQualifiedDictionaries, navigatePath, nesting as nest, nestedPlugin, normalizeAttributeKey, normalizeDictionaries, normalizeDictionary, normalizePath, normalizeWhitespace, number, orderDictionaries, parseBlock, parseCaptureInline, parseDictionarySelector, parseInline, parseItemId, parseItemSegment, parseMarkdown, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, parseTaggedMessage, parseYaml, parserFor, percentage, plural, pluralPlugin, portableObjectToIntlayerFormatter, presets, qualifies, readMetadataIndex, readTransformCache, rebuildInterpolableContent, reconstructQualifiedEntry, registerAmbientLocaleResolver, registerAsyncAmbientLocaleResolver, relativeTime, removeContentNodeByKeyPath, renameContentNodeByKeyPath, renderFor, renderMarkdownAst, renderNothing, resolveBrowserLocale, resolveDictionaryArgument, resolveDictionaryRead, resolveDynamicContent, resolveDynamicContentAsync, resolveEffectiveVariantId, resolveInsertedSelector, resolveInterpreterLocale, resolveInterpreterLocaleAsync, resolveLocalizedPath, resolveMessage, resolveMessageNode, resolveMessageNodeToString, resolvePlainDynamicLoader, resolveProviderVariant, resolveProxyMode, resolveQualifiedDictionary, sanitizer, select, selectPlugin, serializeItem, serializeVariant, serializeVariantChain, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer, simpleInlineRegex, slugify, some, splitInsertionTemplate, startsWith, stringifyYaml, translation as t, transformInterpolableNode, translationPlugin, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, units, unquote, updateNodeChildren, validateHTML, validateMarkdown, validatePrefix, vueI18nToIntlayerFormatter, writeTransformCache };
|
|
131
|
+
export { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_NAME_START_R, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, AmbientLocaleResolver, AsyncAmbientLocaleResolver, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, type BlockQuoteNode, BlockSyntaxProbe, type BoldTextNode, type BreakLineNode, type BreakThematicNode, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, COMPOSITE_ID_SEPARATOR, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CachedIntl, CachedIntl as Intl, ChunkSuspenseCache, type CodeBlockNode, type CodeFencedNode, type CodeInlineNode, CollectedChunk, CollectedChunks, type CompileOptions, type ComponentOverrides, ConditionCond, ConditionContent, ConditionContentStates, CookieBuildAttributes, type CustomComponentNode, DEFAULT_PLURAL_VARIABLE, DEFAULT_VARIANT_ID, DO_NOT_PROCESS_HTML_ELEMENTS, DateTimePreset, DeepTransformContent, DictionaryRead, DotPath, DynamicChunkTransform, DynamicContent, DynamicContentStore, DynamicDictionaryLoader, DynamicLoaderMap, DynamicReadContext, DynamicReadParams, DynamicReader, DynamicStoreRead, type ElementType, EnterFormat, EnumerationCond, EnumerationContent, EnumerationContentState, type EscapedTextNode, FENCE_DELIMITER_R, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, FileCond, type FileContent, type FileContentConstructor, type FootnoteNode, type FootnoteReferenceNode, type GFMTaskNode, GFM_TASK_R, Gender, GenderCond, GenderContent, GenderContentStates, type GenerateSitemapOptions, GetNestingResult, type GetPrefixOptions, type GetPrefixResult, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, type HTMLCommentNode, HTMLContent, HTMLContentConstructor, type HTMLNode, type HTMLSelfClosingNode, type HTMLTag, HTMLTagsType, HTMLValidationIssue, HTMLValidationResult, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_TAGS, type HeadingNode, type HeadingSetextNode, IInterpreterPlugin, IInterpreterPluginState, INLINE_SKIP_R, INTERPOLATION_R, type ImageNode, InsertionCond, InsertionContent, InsertionContentConstructor, InterpolableNode, IntlConstructorName, IsAny, type ItalicTextNode, JsonValue, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LOOKAHEAD, type LinkAngleBraceNode, type LinkBareURLNode, type LinkNode, ListFormatOptions, ListType, type LocaleDomainMap, type LocaleRequest, LocaleStorage, LocaleStorageClient, LocaleStorageClientOptions, LocaleStorageOptions, LocaleStorageServer, LocaleStorageServerOptions, type LocalizedPathResult, MarkdownContent, MarkdownContentConstructor, type MarkdownContext, type MarkdownOptions, MarkdownReferences, type MarkdownRuntime, type HTMLValidationIssue as MarkdownValidationIssue, MarkdownValidationResult, type MarkedTextNode, MatchedQualifiedEntryIds, MessageArgumentFormatter, MessageArgumentFormatterContext, MessageArgumentFormatters, MessageFormatDialect, MessageFormatter, MessageInterpolation, MessageResolver, MessageValues, NAMED_CODES_TO_UNICODE, NP_TABLE_R, NestedCond, NestedContent, NestedContentState, NestedFieldReferences, type NestedParser, type NewlineNode, NodeProps, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, type OrderedListNode, PARAGRAPH_R, PRELOADED_DYNAMIC_KEY, type ParagraphNode, type ParseState, ParsedMarkdown, type Parser, type ParserResult, PlainDynamicLoaderMap, Plugins, PluralCategory, PluralCond, PluralContent, PluralContentState, PluralOptions, PortableObject, PreloadableDynamicLoaderMap, PreloadedDynamicEntry, Priority, PriorityValue, type ProxyMode, type ProxyStorageSuppressionPurpose, QUALIFIER_DYNAMIC_METADATA_KEY, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, QualifiedDynamicLoaderMap, QualifiedDynamicLoaderTree, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, type ReferenceImageNode, type ReferenceLinkNode, type ReferenceNode, type RenderRuleHook, ResolvedDynamicLoader, type Rule, type RuleOutput, RuleScope, RuleScopeValue, RuleType, RuleTypeValue, type Rules, SCOPE_BLOCK, SCOPE_BOTH, SCOPE_INLINE, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, SelectCond, SelectContent, SelectContentStates, SelectSelector, SettledDynamicContent, type SitemapUrlEntry, type StrikethroughTextNode, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, type TableNode, type TableSeparatorNode, TaggedMessageToken, type TextNode, TransformCacheWrite, TranslationCond, TranslationContent, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, UnionKeys, type UnorderedListNode, VOID_HTML_ELEMENTS, ValidDotPathsFor, ValueAtKey, WrappedIntl, YamlRecord, YamlValue, allowInline, anyScopeRegex, attributeValueToNodePropValue, bindInsertedValues, bindIntl, blockRegex, buildMaskPlugin, captureNothing, checkIsURLAbsolute, checkMissingLocalesPlugin, collectQualifiedChunks, collectTransformCacheWrites, compact, compareItemIds, compareItemSegments, comparePaths, compile, compileWithOptions, condition as cond, conditionPlugin, createChunkSuspenseCache, createCompiler, createDynamicContentStore, createMessageResolver, createRenderer, currency, cx, date, deepTransformNode, deleteTransformCacheWrites, editDictionaryByKeyPath, enumeration as enu, enumerationPlugin, fallbackPlugin, type file, type fileContent, filePlugin, filterMissingTranslationsOnlyPlugin, filterTranslationsOnlyPlugin, findMatchingCondition, findPlainDynamicLoader, formatProxyEnabledMessage, gender, genderPlugin, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex, generateSitemap, generateSitemapUrl, get, getBasePlugins, getBrowserLocale, getCachedIntl, getCachedLocaleFromStorageClient, getCanonicalPath, getCondition, getContent, getContentNodeByKeyPath, getCookie, getDefaultNode, getDictionary, getDictionaryAsync, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getDictionaryTransformCacheKey, getDomainHostname, getDomainOrigin, getDynamicChunkArgument, getDynamicChunks, getEditedContent, getEditedDictionary, getEmptyNode, getEnumeration, getFilterMissingTranslationsContent, getFilterMissingTranslationsDictionary, getFilterTranslationsOnlyContent, getFilterTranslationsOnlyDictionary, getFilteredLocalesContent, getFilteredLocalesDictionary, getGender, getHTML, getHTMLTextDir, getInsertion, getInsertionValues, getInternalPath, getInterpolableContent, getIntlayer, getIntlayerAsync, getIntlayerNodePrototype, getLocale, getLocaleFromDomain, getLocaleFromPath, getLocaleFromRequest, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, getLocaleLang, getLocaleName, getLocalizedContent, getLocalizedMetadata, getLocalizedPath, getLocalizedUrl, getMarkdownMetadata, getMaskContent, getMissingLocalesContent, getMissingLocalesContentFromDictionary, getMultilingualDictionary, getMultilingualUrls, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNesting, getNodeChildren, getNodeType, getPathWithoutLocale, getPerLocaleDictionary, getPluginsCacheKey, getPlural, getPrefix, getPreloadLocale, getPreloadedDictionary, getReplacedValuesContent, getRewritePath, getRewriteRules, getRuleSet, getSelect, getSplittedContent, getSplittedDictionaryContent, getTranslation, getVariantIds, html, i18nextToIntlayerFormatter, icuToIntlayerFormatter, inlineRegex, insertion as insert, insertContentInDictionary, insertionPlugin, interpolateMessage, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, isDeclaredItem, isDeclaredLocale, isInterpolableWrapperNode, isLocaleExclusiveOnDomain, isProxyStorageLocaleEnabled, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, isSameKeyPath, isValidElement, list, loadDynamicDictionary, loadingContentPlaceholder, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, matchQualifiedEntryIds, markdown as md, mergeDictionaries, mergeQualifiedDictionaries, navigatePath, nesting as nest, nestedPlugin, normalizeAttributeKey, normalizeDictionaries, normalizeDictionary, normalizePath, normalizeWhitespace, number, orderDictionaries, parseBlock, parseCaptureInline, parseDictionarySelector, parseInline, parseItemId, parseItemSegment, parseMarkdown, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, parseTaggedMessage, parseYaml, parserFor, percentage, plural, pluralPlugin, portableObjectToIntlayerFormatter, presets, qualifies, readMetadataIndex, readTransformCache, rebuildInterpolableContent, reconstructQualifiedEntry, registerAmbientLocaleResolver, registerAsyncAmbientLocaleResolver, relativeTime, removeContentNodeByKeyPath, renameContentNodeByKeyPath, renderFor, renderMarkdownAst, renderNothing, resolveBrowserLocale, resolveDictionaryArgument, resolveDictionaryRead, resolveDynamicContent, resolveDynamicContentAsync, resolveEffectiveVariantId, resolveInsertedSelector, resolveInterpreterLocale, resolveInterpreterLocaleAsync, resolveLocalizedPath, resolveMessage, resolveMessageNode, resolveMessageNodeToString, resolvePlainDynamicLoader, resolveProviderVariant, resolveProxyMode, resolveQualifiedDictionary, sanitizer, select, selectPlugin, serializeItem, serializeVariant, serializeVariantChain, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer, simpleInlineRegex, slugify, some, splitInsertionTemplate, startsWith, stringifyYaml, translation as t, transformInterpolableNode, translationPlugin, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, units, unquote, updateNodeChildren, validateHTML, validateMarkdown, validatePrefix, vueI18nToIntlayerFormatter, writeTransformCache };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"i18next.d.ts","names":[],"sources":["../../../src/messageFormat/i18next.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"i18next.d.ts","names":[],"sources":["../../../src/messageFormat/i18next.ts"],"mappings":";;qBA+Wa,6BAA0B,SAC5B,0BACR;qBAQU,6BAA0B,SAC5B,cACR"}
|
|
@@ -2,6 +2,6 @@ import { JsonValue, icuToIntlayerFormatter, intlayerToICUFormatter } from "./ICU
|
|
|
2
2
|
import { i18nextToIntlayerFormatter, intlayerToI18nextFormatter } from "./i18next.js";
|
|
3
3
|
import { navigatePath } from "./navigatePath.js";
|
|
4
4
|
import { PortableObject, intlayerToPortableObjectFormatter, portableObjectToIntlayerFormatter } from "./po.js";
|
|
5
|
-
import { MessageArgumentFormatter, MessageArgumentFormatterContext, MessageArgumentFormatters, MessageFormatDialect, MessageFormatter, MessageResolver, MessageValues, TaggedMessageToken, createMessageResolver, interpolateMessage, parseTaggedMessage, resolveMessage, resolveMessageNode, resolveMessageNodeToString } from "./resolveMessage.js";
|
|
5
|
+
import { MessageArgumentFormatter, MessageArgumentFormatterContext, MessageArgumentFormatters, MessageFormatDialect, MessageFormatter, MessageInterpolation, MessageResolver, MessageValues, TaggedMessageToken, createMessageResolver, interpolateMessage, parseTaggedMessage, resolveMessage, resolveMessageNode, resolveMessageNodeToString } from "./resolveMessage.js";
|
|
6
6
|
import { intlayerToVueI18nFormatter, vueI18nToIntlayerFormatter } from "./vue-i18n.js";
|
|
7
|
-
export { JsonValue, MessageArgumentFormatter, MessageArgumentFormatterContext, MessageArgumentFormatters, MessageFormatDialect, MessageFormatter, MessageResolver, MessageValues, PortableObject, TaggedMessageToken, createMessageResolver, i18nextToIntlayerFormatter, icuToIntlayerFormatter, interpolateMessage, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, navigatePath, parseTaggedMessage, portableObjectToIntlayerFormatter, resolveMessage, resolveMessageNode, resolveMessageNodeToString, vueI18nToIntlayerFormatter };
|
|
7
|
+
export { JsonValue, MessageArgumentFormatter, MessageArgumentFormatterContext, MessageArgumentFormatters, MessageFormatDialect, MessageFormatter, MessageInterpolation, MessageResolver, MessageValues, PortableObject, TaggedMessageToken, createMessageResolver, i18nextToIntlayerFormatter, icuToIntlayerFormatter, interpolateMessage, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, navigatePath, parseTaggedMessage, portableObjectToIntlayerFormatter, resolveMessage, resolveMessageNode, resolveMessageNodeToString, vueI18nToIntlayerFormatter };
|
|
@@ -29,6 +29,12 @@ export type MessageArgumentFormatterContext = {
|
|
|
29
29
|
export type MessageArgumentFormatter = (value: unknown, context: MessageArgumentFormatterContext) => unknown;
|
|
30
30
|
/** Custom argument formatters, keyed by argument type. */
|
|
31
31
|
export type MessageArgumentFormatters = Record<string, MessageArgumentFormatter>;
|
|
32
|
+
/**
|
|
33
|
+
* Placeholders read in plain strings: `'default'` reads `{{name}}`, `{name}`
|
|
34
|
+
* and `{value, number}`; `'double-brace'` reads only `{{…}}`, like i18next,
|
|
35
|
+
* which prints single braces (and ICU blocks) as text.
|
|
36
|
+
*/
|
|
37
|
+
export type MessageInterpolation = 'default' | 'double-brace';
|
|
32
38
|
/**
|
|
33
39
|
* Interpolates a message template with values.
|
|
34
40
|
*
|
|
@@ -37,8 +43,10 @@ export type MessageArgumentFormatters = Record<string, MessageArgumentFormatter>
|
|
|
37
43
|
* optionally formatted the i18next way (`{{price, number}}`)
|
|
38
44
|
* 2. ICU formatted arguments `{value, number}` / `{ts, date, long}`
|
|
39
45
|
* 3. Bare single-brace arguments `{name}` (ICU / vue-i18n simple args)
|
|
46
|
+
*
|
|
47
|
+
* With `'double-brace'` interpolation, only step 1 runs.
|
|
40
48
|
*/
|
|
41
|
-
export declare const interpolateMessage: (template: string, values?: MessageValues, locale?: LocalesValues, formatters?: MessageArgumentFormatters) => string;
|
|
49
|
+
export declare const interpolateMessage: (template: string, values?: MessageValues, locale?: LocalesValues, formatters?: MessageArgumentFormatters, interpolation?: MessageInterpolation) => string;
|
|
42
50
|
/**
|
|
43
51
|
* Resolves an intlayer message node tree (as produced by the
|
|
44
52
|
* `*ToIntlayerFormatter` converters, or already present in a built
|
|
@@ -47,7 +55,7 @@ export declare const interpolateMessage: (template: string, values?: MessageValu
|
|
|
47
55
|
* Function nodes (produced by the interpreter plugins for `insertion`,
|
|
48
56
|
* `enumeration` and `plural` content) are invoked with the values.
|
|
49
57
|
*/
|
|
50
|
-
export declare const resolveMessageNode: (node: unknown, values?: MessageValues, locale?: LocalesValues, formatters?: MessageArgumentFormatters) => unknown;
|
|
58
|
+
export declare const resolveMessageNode: (node: unknown, values?: MessageValues, locale?: LocalesValues, formatters?: MessageArgumentFormatters, interpolation?: MessageInterpolation) => unknown;
|
|
51
59
|
/**
|
|
52
60
|
* {@link resolveMessageNode} coerced to a string.
|
|
53
61
|
*
|
|
@@ -55,9 +63,10 @@ export declare const resolveMessageNode: (node: unknown, values?: MessageValues,
|
|
|
55
63
|
* the bundle through a built dictionary: the build already converted every
|
|
56
64
|
* dialect construct into intlayer nodes, and the interpreter turned those into
|
|
57
65
|
* callables, so no message parser is involved. Plain strings still get
|
|
58
|
-
* `{{name}}` / `{name}` / `{value, number}` interpolation
|
|
66
|
+
* `{{name}}` / `{name}` / `{value, number}` interpolation (only `{{…}}` with
|
|
67
|
+
* `'double-brace'` interpolation).
|
|
59
68
|
*/
|
|
60
|
-
export declare const resolveMessageNodeToString: (node: unknown, values?: MessageValues, locale?: LocalesValues, formatters?: MessageArgumentFormatters) => string;
|
|
69
|
+
export declare const resolveMessageNodeToString: (node: unknown, values?: MessageValues, locale?: LocalesValues, formatters?: MessageArgumentFormatters, interpolation?: MessageInterpolation) => string;
|
|
61
70
|
/** Converts a raw message string of one dialect into an intlayer node tree. */
|
|
62
71
|
export type MessageFormatter = (message: string) => unknown;
|
|
63
72
|
/**
|
|
@@ -78,7 +87,7 @@ export type MessageResolver = (message: unknown, values?: MessageValues, locale?
|
|
|
78
87
|
* resolveIcuMessage('Hello {name}', { name: 'John' }, 'en'); // 'Hello John'
|
|
79
88
|
* ```
|
|
80
89
|
*/
|
|
81
|
-
export declare const createMessageResolver: (formatter: MessageFormatter) => MessageResolver;
|
|
90
|
+
export declare const createMessageResolver: (formatter: MessageFormatter, interpolation?: MessageInterpolation) => MessageResolver;
|
|
82
91
|
/**
|
|
83
92
|
* Resolves a raw message — string in a library dialect, or an intlayer node
|
|
84
93
|
* tree — into a final string using interpolation values and locale.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveMessage.d.ts","names":[],"sources":["../../../src/messageFormat/resolveMessage.ts"],"mappings":";;;;;;;;;;;;;;YA+BY;;YAGA,gBAAgB;;YA8BhB;;EAEV,QAAQ;;EAER;;;;;;YAOU,4BACV,gBACA,SAAS;;YAIC,4BAA4B,eAEtC
|
|
1
|
+
{"version":3,"file":"resolveMessage.d.ts","names":[],"sources":["../../../src/messageFormat/resolveMessage.ts"],"mappings":";;;;;;;;;;;;;;YA+BY;;YAGA,gBAAgB;;YA8BhB;;EAEV,QAAQ;;EAER;;;;;;YAOU,4BACV,gBACA,SAAS;;YAIC,4BAA4B,eAEtC;;;;;;YA8EU;;;;;;;;;;;;qBAaC,qBAAkB,kBACb,SACR,eAAa,SACb,eAAa,aACR,2BAAyB,gBACvB;;;;;;;;;qBA+CJ,qBAAkB,eAChB,SACL,eAAa,SACb,eAAa,aACR,2BAAyB,gBACvB;;;;;;;;;;;qBAgMJ,6BAA0B,eACxB,SACL,eAAa,SACb,eAAa,aACR,2BAAyB,gBACvB;;YAcL,oBAAoB;;;;;YAMpB,mBACV,kBACA,SAAS,eACT,SAAS,eACT,aAAa;;;;;;;;;;;;;;qBAgBF,wBAAqB,WAEnB,kBAAgB,gBACZ,yBACd;;;;;;;;;;;;;;;;;;;;;;qBA+CQ,iBAAc,kBACT,SACR,eAAa,SACb,eAAa,UACZ;;YAQC;EAEN;EAAa,UAAU;;;;;;;;;qBAShB,qBAAkB,oBAAsB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/core",
|
|
3
|
-
"version": "9.9.3
|
|
3
|
+
"version": "9.9.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Includes core Intlayer functions like translation, dictionary, and utility functions shared across multiple packages.",
|
|
6
6
|
"keywords": [
|
|
@@ -176,10 +176,10 @@
|
|
|
176
176
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
177
177
|
},
|
|
178
178
|
"dependencies": {
|
|
179
|
-
"@intlayer/api": "9.9.3
|
|
180
|
-
"@intlayer/config": "9.9.3
|
|
181
|
-
"@intlayer/dictionaries-entry": "9.9.3
|
|
182
|
-
"@intlayer/types": "9.9.3
|
|
179
|
+
"@intlayer/api": "9.9.3",
|
|
180
|
+
"@intlayer/config": "9.9.3",
|
|
181
|
+
"@intlayer/dictionaries-entry": "9.9.3",
|
|
182
|
+
"@intlayer/types": "9.9.3",
|
|
183
183
|
"defu": "6.1.7"
|
|
184
184
|
},
|
|
185
185
|
"devDependencies": {
|