@intlayer/core 9.5.9-canary.0 → 9.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs.map +1 -1
  2. package/dist/cjs/index.cjs +4 -0
  3. package/dist/cjs/interpreter/getContent/deepTransform.cjs +17 -22
  4. package/dist/cjs/interpreter/getContent/deepTransform.cjs.map +1 -1
  5. package/dist/cjs/interpreter/getContent/getContent.cjs +2 -1
  6. package/dist/cjs/interpreter/getContent/getContent.cjs.map +1 -1
  7. package/dist/cjs/interpreter/getContent/plugins.cjs +32 -37
  8. package/dist/cjs/interpreter/getContent/plugins.cjs.map +1 -1
  9. package/dist/cjs/interpreter/getDictionary.cjs +20 -5
  10. package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
  11. package/dist/cjs/interpreter/getTranslation.cjs +31 -27
  12. package/dist/cjs/interpreter/getTranslation.cjs.map +1 -1
  13. package/dist/cjs/localization/getPathWithoutLocale.cjs.map +1 -1
  14. package/dist/cjs/localization/localeResolver.cjs +1 -0
  15. package/dist/cjs/localization/localeResolver.cjs.map +1 -1
  16. package/dist/cjs/markdown/compiler.cjs +12 -3
  17. package/dist/cjs/markdown/compiler.cjs.map +1 -1
  18. package/dist/cjs/markdown/constants.cjs +3 -0
  19. package/dist/cjs/markdown/constants.cjs.map +1 -1
  20. package/dist/cjs/markdown/index.cjs +1 -0
  21. package/dist/cjs/markdown/utils.cjs +1 -1
  22. package/dist/cjs/markdown/utils.cjs.map +1 -1
  23. package/dist/cjs/messageFormat/ICU.cjs +10 -10
  24. package/dist/cjs/messageFormat/ICU.cjs.map +1 -1
  25. package/dist/cjs/messageFormat/i18next.cjs +7 -7
  26. package/dist/cjs/messageFormat/i18next.cjs.map +1 -1
  27. package/dist/cjs/messageFormat/po.cjs +1 -1
  28. package/dist/cjs/messageFormat/po.cjs.map +1 -1
  29. package/dist/cjs/messageFormat/resolveMessage.cjs +2 -2
  30. package/dist/cjs/messageFormat/resolveMessage.cjs.map +1 -1
  31. package/dist/cjs/messageFormat/verify-icu-format.cjs +4 -4
  32. package/dist/cjs/messageFormat/verify-icu-format.cjs.map +1 -1
  33. package/dist/cjs/messageFormat/vue-i18n.cjs +4 -4
  34. package/dist/cjs/messageFormat/vue-i18n.cjs.map +1 -1
  35. package/dist/cjs/utils/index.cjs +3 -0
  36. package/dist/cjs/utils/intlayerNodePrototype.cjs +66 -0
  37. package/dist/cjs/utils/intlayerNodePrototype.cjs.map +1 -0
  38. package/dist/cjs/utils/localeStorage.cjs +20 -0
  39. package/dist/cjs/utils/localeStorage.cjs.map +1 -1
  40. package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs.map +1 -1
  41. package/dist/esm/index.mjs +4 -3
  42. package/dist/esm/interpreter/getContent/deepTransform.mjs +17 -22
  43. package/dist/esm/interpreter/getContent/deepTransform.mjs.map +1 -1
  44. package/dist/esm/interpreter/getContent/getContent.mjs +3 -2
  45. package/dist/esm/interpreter/getContent/getContent.mjs.map +1 -1
  46. package/dist/esm/interpreter/getContent/plugins.mjs +32 -37
  47. package/dist/esm/interpreter/getContent/plugins.mjs.map +1 -1
  48. package/dist/esm/interpreter/getDictionary.mjs +20 -5
  49. package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
  50. package/dist/esm/interpreter/getTranslation.mjs +31 -27
  51. package/dist/esm/interpreter/getTranslation.mjs.map +1 -1
  52. package/dist/esm/localization/getPathWithoutLocale.mjs.map +1 -1
  53. package/dist/esm/localization/localeResolver.mjs +1 -0
  54. package/dist/esm/localization/localeResolver.mjs.map +1 -1
  55. package/dist/esm/markdown/compiler.mjs +13 -4
  56. package/dist/esm/markdown/compiler.mjs.map +1 -1
  57. package/dist/esm/markdown/constants.mjs +3 -1
  58. package/dist/esm/markdown/constants.mjs.map +1 -1
  59. package/dist/esm/markdown/index.mjs +2 -2
  60. package/dist/esm/markdown/utils.mjs +1 -1
  61. package/dist/esm/markdown/utils.mjs.map +1 -1
  62. package/dist/esm/messageFormat/ICU.mjs +10 -10
  63. package/dist/esm/messageFormat/ICU.mjs.map +1 -1
  64. package/dist/esm/messageFormat/i18next.mjs +7 -7
  65. package/dist/esm/messageFormat/i18next.mjs.map +1 -1
  66. package/dist/esm/messageFormat/po.mjs +1 -1
  67. package/dist/esm/messageFormat/po.mjs.map +1 -1
  68. package/dist/esm/messageFormat/resolveMessage.mjs +2 -2
  69. package/dist/esm/messageFormat/resolveMessage.mjs.map +1 -1
  70. package/dist/esm/messageFormat/verify-icu-format.mjs +4 -4
  71. package/dist/esm/messageFormat/verify-icu-format.mjs.map +1 -1
  72. package/dist/esm/messageFormat/vue-i18n.mjs +4 -4
  73. package/dist/esm/messageFormat/vue-i18n.mjs.map +1 -1
  74. package/dist/esm/utils/index.mjs +3 -2
  75. package/dist/esm/utils/intlayerNodePrototype.mjs +65 -0
  76. package/dist/esm/utils/intlayerNodePrototype.mjs.map +1 -0
  77. package/dist/esm/utils/localeStorage.mjs +20 -1
  78. package/dist/esm/utils/localeStorage.mjs.map +1 -1
  79. package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts +1 -1
  80. package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts +1 -1
  81. package/dist/types/deepTransformPlugins/getFilteredLocalesContent.d.ts +1 -1
  82. package/dist/types/index.d.ts +4 -3
  83. package/dist/types/interpreter/getContent/deepTransform.d.ts.map +1 -1
  84. package/dist/types/interpreter/getContent/getContent.d.ts.map +1 -1
  85. package/dist/types/interpreter/getContent/plugins.d.ts +3 -1
  86. package/dist/types/interpreter/getContent/plugins.d.ts.map +1 -1
  87. package/dist/types/interpreter/getDictionary.d.ts.map +1 -1
  88. package/dist/types/interpreter/getTranslation.d.ts.map +1 -1
  89. package/dist/types/markdown/compiler.d.ts +1 -0
  90. package/dist/types/markdown/compiler.d.ts.map +1 -1
  91. package/dist/types/markdown/constants.d.ts +2 -0
  92. package/dist/types/markdown/constants.d.ts.map +1 -1
  93. package/dist/types/markdown/index.d.ts +2 -2
  94. package/dist/types/messageFormat/ICU.d.ts.map +1 -1
  95. package/dist/types/messageFormat/i18next.d.ts.map +1 -1
  96. package/dist/types/messageFormat/vue-i18n.d.ts.map +1 -1
  97. package/dist/types/utils/index.d.ts +3 -2
  98. package/dist/types/utils/intlayerNodePrototype.d.ts +15 -0
  99. package/dist/types/utils/intlayerNodePrototype.d.ts.map +1 -0
  100. package/dist/types/utils/localeStorage.d.ts +9 -0
  101. package/dist/types/utils/localeStorage.d.ts.map +1 -1
  102. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"po.cjs","names":["NodeTypes","html","insert","gender","enu","plural","deepTransformNode"],"sources":["../../../src/messageFormat/po.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { deepTransformNode } from '../interpreter';\nimport { enu, gender, html, insert, plural } from '../transpiler';\nimport type { JsonValue } from './ICU';\n\nexport type PortableObject = {\n msgid: string;\n msgctxt?: string;\n msgid_plural?: string;\n msgstr: string[];\n};\n\n/**\n * Extracts the string value from a transformed AST node or generic object.\n */\nconst extractStringValue = (val: any): string => {\n if (typeof val === 'string') return val;\n if (val && typeof val === 'object' && 'msgstr' in val) {\n return val.msgstr[0] || '';\n }\n return JSON.stringify(val);\n};\n\nconst intlayerToPoPlugin = {\n canHandle: (node: any) => {\n if (typeof node === 'string') return true;\n\n if (\n node &&\n typeof node === 'object' &&\n (node.nodeType === NodeTypes.INSERTION ||\n node.nodeType === NodeTypes.HTML ||\n node.nodeType === NodeTypes.ENUMERATION ||\n node.nodeType === NodeTypes.PLURAL ||\n node.nodeType === NodeTypes.GENDER ||\n node.nodeType === 'composite')\n ) {\n return true;\n }\n\n // Handle structural string arrays (composite phrases)\n if (Array.isArray(node)) {\n if (node.length === 0) return false;\n let hasNode = false;\n let hasPlainObjectOrArray = false;\n\n for (const item of node) {\n if (typeof item === 'string') {\n } else if (\n item &&\n typeof item === 'object' &&\n (item.nodeType === NodeTypes.INSERTION ||\n item.nodeType === NodeTypes.HTML ||\n item.nodeType === NodeTypes.ENUMERATION ||\n item.nodeType === NodeTypes.PLURAL ||\n item.nodeType === NodeTypes.GENDER ||\n item.nodeType === 'composite')\n ) {\n hasNode = true;\n } else {\n hasPlainObjectOrArray = true;\n }\n }\n\n if (hasPlainObjectOrArray) return false;\n if (!hasNode) return false;\n return true;\n }\n\n return false;\n },\n transform: (node: any, props: any, next: any): PortableObject => {\n // 1. Strings\n if (typeof node === 'string') {\n const poVal = node.replace(/\\{\\{([^}]+)\\}\\}/g, '%($1)s');\n return { msgid: poVal, msgstr: [poVal] };\n }\n\n // 2. Insertions & Variables\n if (node.nodeType === NodeTypes.INSERTION) {\n return next(node[NodeTypes.INSERTION], props);\n }\n\n // 3. HTML\n if (node.nodeType === NodeTypes.HTML) {\n const val = node[NodeTypes.HTML];\n return { msgid: val, msgstr: [val] };\n }\n\n // 4. Plurals & Enumerations\n if (\n node.nodeType === NodeTypes.PLURAL ||\n node.nodeType === NodeTypes.ENUMERATION\n ) {\n const isPlural = node.nodeType === NodeTypes.PLURAL;\n const options = isPlural\n ? node[NodeTypes.PLURAL]\n : node[NodeTypes.ENUMERATION];\n\n const rawMsgid = isPlural\n ? options.one || options.other || options.fallback\n : options.fallback || options['0'];\n\n const msgid = extractStringValue(next(rawMsgid, props));\n const msgid_plural = isPlural\n ? extractStringValue(\n next(options.other || options.fallback || rawMsgid, props)\n )\n : extractStringValue(next(options.fallback || rawMsgid, props));\n\n const msgstr: string[] = [];\n\n if (isPlural) {\n // Standard CLDR/Gettext mapping fallback\n if ('zero' in options)\n msgstr.push(extractStringValue(next(options.zero, props)));\n msgstr.push(\n extractStringValue(next(options.one || options.fallback, props))\n );\n if ('two' in options)\n msgstr.push(extractStringValue(next(options.two, props)));\n if ('few' in options)\n msgstr.push(extractStringValue(next(options.few, props)));\n if ('many' in options)\n msgstr.push(extractStringValue(next(options.many, props)));\n\n // Ensure 'other' is always the last fallback if others are missing\n const otherVal = extractStringValue(\n next(options.other || options.fallback, props)\n );\n if (!msgstr.includes(otherVal)) msgstr.push(otherVal);\n } else {\n // Enums don't have standard PO mapping, pack linearly\n msgstr[0] = extractStringValue(\n next(options.fallback || options['0'], props)\n );\n msgstr[1] = msgstr[0];\n }\n\n return {\n msgctxt: isPlural ? undefined : 'enumeration',\n msgid,\n msgid_plural,\n msgstr,\n };\n }\n\n // 5. Gender (mapped to PO via msgctxt)\n if (node.nodeType === NodeTypes.GENDER) {\n const options = node[NodeTypes.GENDER];\n const fallback = extractStringValue(next(options.fallback, props));\n return {\n msgctxt: 'gender',\n msgid: fallback,\n msgstr: [\n extractStringValue(next(options.male || options.fallback, props)),\n extractStringValue(next(options.female || options.fallback, props)),\n fallback,\n ],\n };\n }\n\n // 6. Arrays / Composites\n if (\n Array.isArray(node) ||\n (node.nodeType === 'composite' && Array.isArray(node.composite))\n ) {\n const arr = Array.isArray(node) ? node : node.composite;\n const combined = arr\n .map((item: any) => extractStringValue(next(item, props)))\n .join('');\n return { msgid: combined, msgstr: [combined] };\n }\n\n return node;\n },\n};\n\nconst poToIntlayerPlugin = {\n canHandle: (node: any) =>\n node && typeof node === 'object' && 'msgid' in node && 'msgstr' in node,\n\n transform: (node: PortableObject) => {\n const msgstr = node.msgstr || [];\n const isPlural = Boolean(node.msgid_plural) || msgstr.length > 1;\n\n const processString = (str: string) => {\n if (!str) return '';\n // Convert Python/C-style gettext variables %(name)s or %(name)d -> {{name}}\n const parsed = str.replace(/%\\(([a-zA-Z0-9_-]+)\\)[sdf]/g, '{{$1}}');\n\n if (/<[a-zA-Z0-9-]+[^>]*>/.test(parsed)) return html(parsed);\n if (parsed.includes('{{')) return insert(parsed);\n return parsed;\n };\n\n // Fast-path: Single string translation\n if (!isPlural) {\n return processString(msgstr[0] || node.msgid || '');\n }\n\n // Handle Plural/Enum/Gender matrix\n const options: Record<string, any> = {};\n\n if (node.msgctxt === 'gender') {\n return gender({\n male: processString(msgstr[0] || node.msgid),\n female: processString(msgstr[1] || msgstr[0]),\n fallback: processString(msgstr[2] || msgstr[msgstr.length - 1]),\n });\n }\n\n if (node.msgctxt === 'enumeration') {\n return enu({\n '0': processString(msgstr[0]),\n fallback: processString(msgstr[msgstr.length - 1]),\n });\n }\n\n // Plural Form Mapping based on array length (Gettext Plural-Forms approximation)\n if (msgstr.length === 2) {\n options.one = processString(msgstr[0]);\n options.other = processString(msgstr[1]);\n } else if (msgstr.length === 3) {\n // E.g., Polish/Russian: one, few, many/other\n options.one = processString(msgstr[0]);\n options.few = processString(msgstr[1]);\n options.other = processString(msgstr[2]);\n } else if (msgstr.length === 6) {\n // E.g., Arabic: zero, one, two, few, many, other\n options.zero = processString(msgstr[0]);\n options.one = processString(msgstr[1]);\n options.two = processString(msgstr[2]);\n options.few = processString(msgstr[3]);\n options.many = processString(msgstr[4]);\n options.other = processString(msgstr[5]);\n } else {\n // Generic arbitrary length mapping\n options.one = processString(msgstr[0]);\n options.other = processString(msgstr[msgstr.length - 1]);\n for (let i = 1; i < msgstr.length - 1; i++) {\n options[`${i + 1}`] = processString(msgstr[i]);\n }\n }\n\n return plural(options as any);\n },\n};\n\nexport const intlayerToPortableObjectFormatter = (\n dictionary: Dictionary['content']\n): JsonValue => {\n return deepTransformNode(dictionary, {\n dictionaryKey: 'po',\n keyPath: [],\n plugins: [{ id: 'po', ...intlayerToPoPlugin }],\n });\n};\n\nexport const portableObjectToIntlayerFormatter = (\n message: JsonValue\n): Dictionary['content'] => {\n return deepTransformNode(message, {\n dictionaryKey: 'po',\n keyPath: [],\n plugins: [{ id: 'po', ...poToIntlayerPlugin }],\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAM,sBAAsB,QAAqB;CAC/C,IAAI,OAAO,QAAQ,UAAU,OAAO;CACpC,IAAI,OAAO,OAAO,QAAQ,YAAY,YAAY,KAChD,OAAO,IAAI,OAAO,MAAM;CAE1B,OAAO,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":["NodeTypes","html","insert","gender","enu","plural","deepTransformNode"],"sources":["../../../src/messageFormat/po.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { deepTransformNode } from '../interpreter';\nimport { enu, gender, html, insert, plural } from '../transpiler';\nimport type { JsonValue } from './ICU';\n\nexport type PortableObject = {\n msgid: string;\n msgctxt?: string;\n msgid_plural?: string;\n msgstr: string[];\n};\n\n/**\n * Extracts the string value from a transformed AST node or generic object.\n */\nconst extractStringValue = (val: any): string => {\n if (typeof val === 'string') return val;\n if (val && typeof val === 'object' && 'msgstr' in val) {\n return val.msgstr[0] || '';\n }\n return JSON.stringify(val);\n};\n\nconst intlayerToPoPlugin = {\n canHandle: (node: any) => {\n if (typeof node === 'string') return true;\n\n if (\n node &&\n typeof node === 'object' &&\n (node.nodeType === NodeTypes.INSERTION ||\n node.nodeType === NodeTypes.HTML ||\n node.nodeType === NodeTypes.ENUMERATION ||\n node.nodeType === NodeTypes.PLURAL ||\n node.nodeType === NodeTypes.GENDER ||\n node.nodeType === 'composite')\n ) {\n return true;\n }\n\n // Handle structural string arrays (composite phrases)\n if (Array.isArray(node)) {\n if (node.length === 0) return false;\n let hasNode = false;\n let hasPlainObjectOrArray = false;\n\n for (const item of node) {\n if (typeof item === 'string') {\n } else if (\n item &&\n typeof item === 'object' &&\n (item.nodeType === NodeTypes.INSERTION ||\n item.nodeType === NodeTypes.HTML ||\n item.nodeType === NodeTypes.ENUMERATION ||\n item.nodeType === NodeTypes.PLURAL ||\n item.nodeType === NodeTypes.GENDER ||\n item.nodeType === 'composite')\n ) {\n hasNode = true;\n } else {\n hasPlainObjectOrArray = true;\n }\n }\n\n if (hasPlainObjectOrArray) return false;\n if (!hasNode) return false;\n return true;\n }\n\n return false;\n },\n transform: (node: any, props: any, next: any): PortableObject => {\n // 1. Strings\n if (typeof node === 'string') {\n const poVal = node.replace(/\\{\\{([^}]+)\\}\\}/g, '%($1)s');\n return { msgid: poVal, msgstr: [poVal] };\n }\n\n // 2. Insertions & Variables\n if (node.nodeType === NodeTypes.INSERTION) {\n return next(node[NodeTypes.INSERTION], props);\n }\n\n // 3. HTML\n if (node.nodeType === NodeTypes.HTML) {\n const val = node[NodeTypes.HTML];\n return { msgid: val, msgstr: [val] };\n }\n\n // 4. Plurals & Enumerations\n if (\n node.nodeType === NodeTypes.PLURAL ||\n node.nodeType === NodeTypes.ENUMERATION\n ) {\n const isPlural = node.nodeType === NodeTypes.PLURAL;\n const options = isPlural\n ? node[NodeTypes.PLURAL]\n : node[NodeTypes.ENUMERATION];\n\n const rawMsgid = isPlural\n ? options.one || options.other || options.fallback\n : options.fallback || options['0'];\n\n const msgid = extractStringValue(next(rawMsgid, props));\n const msgid_plural = isPlural\n ? extractStringValue(\n next(options.other || options.fallback || rawMsgid, props)\n )\n : extractStringValue(next(options.fallback || rawMsgid, props));\n\n const msgstr: string[] = [];\n\n if (isPlural) {\n // Standard CLDR/Gettext mapping fallback\n if ('zero' in options)\n msgstr.push(extractStringValue(next(options.zero, props)));\n msgstr.push(\n extractStringValue(next(options.one || options.fallback, props))\n );\n if ('two' in options)\n msgstr.push(extractStringValue(next(options.two, props)));\n if ('few' in options)\n msgstr.push(extractStringValue(next(options.few, props)));\n if ('many' in options)\n msgstr.push(extractStringValue(next(options.many, props)));\n\n // Ensure 'other' is always the last fallback if others are missing\n const otherVal = extractStringValue(\n next(options.other || options.fallback, props)\n );\n if (!msgstr.includes(otherVal)) msgstr.push(otherVal);\n } else {\n // Enums don't have standard PO mapping, pack linearly\n msgstr[0] = extractStringValue(\n next(options.fallback || options['0'], props)\n );\n msgstr[1] = msgstr[0];\n }\n\n return {\n msgctxt: isPlural ? undefined : 'enumeration',\n msgid,\n msgid_plural,\n msgstr,\n };\n }\n\n // 5. Gender (mapped to PO via msgctxt)\n if (node.nodeType === NodeTypes.GENDER) {\n const options = node[NodeTypes.GENDER];\n const fallback = extractStringValue(next(options.fallback, props));\n return {\n msgctxt: 'gender',\n msgid: fallback,\n msgstr: [\n extractStringValue(next(options.male || options.fallback, props)),\n extractStringValue(next(options.female || options.fallback, props)),\n fallback,\n ],\n };\n }\n\n // 6. Arrays / Composites\n if (\n Array.isArray(node) ||\n (node.nodeType === 'composite' && Array.isArray(node.composite))\n ) {\n const arr = Array.isArray(node) ? node : node.composite;\n const combined = arr\n .map((item: any) => extractStringValue(next(item, props)))\n .join('');\n return { msgid: combined, msgstr: [combined] };\n }\n\n return node;\n },\n};\n\nconst poToIntlayerPlugin = {\n canHandle: (node: any) =>\n node && typeof node === 'object' && 'msgid' in node && 'msgstr' in node,\n\n transform: (node: PortableObject) => {\n const msgstr = node.msgstr || [];\n const isPlural = Boolean(node.msgid_plural) || msgstr.length > 1;\n\n const processString = (str: string = '') => {\n if (!str) return '';\n // Convert Python/C-style gettext variables %(name)s or %(name)d -> {{name}}\n const parsed = str.replace(/%\\(([a-zA-Z0-9_-]+)\\)[sdf]/g, '{{$1}}');\n\n if (/<[a-zA-Z0-9-]+[^>]*>/.test(parsed)) return html(parsed);\n if (parsed.includes('{{')) return insert(parsed);\n return parsed;\n };\n\n // Fast-path: Single string translation\n if (!isPlural) {\n return processString(msgstr[0] || node.msgid || '');\n }\n\n // Handle Plural/Enum/Gender matrix\n const options: Record<string, any> = {};\n\n if (node.msgctxt === 'gender') {\n return gender({\n male: processString(msgstr[0] || node.msgid),\n female: processString(msgstr[1] || msgstr[0]),\n fallback: processString(msgstr[2] || msgstr[msgstr.length - 1]),\n });\n }\n\n if (node.msgctxt === 'enumeration') {\n return enu({\n '0': processString(msgstr[0]),\n fallback: processString(msgstr[msgstr.length - 1]),\n });\n }\n\n // Plural Form Mapping based on array length (Gettext Plural-Forms approximation)\n if (msgstr.length === 2) {\n options.one = processString(msgstr[0]);\n options.other = processString(msgstr[1]);\n } else if (msgstr.length === 3) {\n // E.g., Polish/Russian: one, few, many/other\n options.one = processString(msgstr[0]);\n options.few = processString(msgstr[1]);\n options.other = processString(msgstr[2]);\n } else if (msgstr.length === 6) {\n // E.g., Arabic: zero, one, two, few, many, other\n options.zero = processString(msgstr[0]);\n options.one = processString(msgstr[1]);\n options.two = processString(msgstr[2]);\n options.few = processString(msgstr[3]);\n options.many = processString(msgstr[4]);\n options.other = processString(msgstr[5]);\n } else {\n // Generic arbitrary length mapping\n options.one = processString(msgstr[0]);\n options.other = processString(msgstr[msgstr.length - 1]);\n for (let i = 1; i < msgstr.length - 1; i++) {\n options[`${i + 1}`] = processString(msgstr[i]);\n }\n }\n\n return plural(options as any);\n },\n};\n\nexport const intlayerToPortableObjectFormatter = (\n dictionary: Dictionary['content']\n): JsonValue => {\n return deepTransformNode(dictionary, {\n dictionaryKey: 'po',\n keyPath: [],\n plugins: [{ id: 'po', ...intlayerToPoPlugin }],\n });\n};\n\nexport const portableObjectToIntlayerFormatter = (\n message: JsonValue\n): Dictionary['content'] => {\n return deepTransformNode(message, {\n dictionaryKey: 'po',\n keyPath: [],\n plugins: [{ id: 'po', ...poToIntlayerPlugin }],\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAM,sBAAsB,QAAqB;CAC/C,IAAI,OAAO,QAAQ,UAAU,OAAO;CACpC,IAAI,OAAO,OAAO,QAAQ,YAAY,YAAY,KAChD,OAAO,IAAI,OAAO,MAAM;CAE1B,OAAO,KAAK,UAAU,GAAG;AAC3B;AAEA,MAAM,qBAAqB;CACzB,YAAY,SAAc;EACxB,IAAI,OAAO,SAAS,UAAU,OAAO;EAErC,IACE,QACA,OAAO,SAAS,aACf,KAAK,aAAaA,yBAAU,aAC3B,KAAK,aAAaA,yBAAU,QAC5B,KAAK,aAAaA,yBAAU,eAC5B,KAAK,aAAaA,yBAAU,UAC5B,KAAK,aAAaA,yBAAU,UAC5B,KAAK,aAAa,cAEpB,OAAO;EAIT,IAAI,MAAM,QAAQ,IAAI,GAAG;GACvB,IAAI,KAAK,WAAW,GAAG,OAAO;GAC9B,IAAI,UAAU;GACd,IAAI,wBAAwB;GAE5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AAO,WAAW,GAAG;GAE9B,QAAQ,OAAO,cAAc,OAAO,EAAE;GACtC,QAAQ,MAAM,cAAc,OAAO,EAAE;GACrC,QAAQ,MAAM,cAAc,OAAO,EAAE;GACrC,QAAQ,MAAM,cAAc,OAAO,EAAE;GACrC,QAAQ,OAAO,cAAc,OAAO,EAAE;GACtC,QAAQ,QAAQ,cAAc,OAAO,EAAE;EACzC,OAAO;GAEL,QAAQ,MAAM,cAAc,OAAO,EAAE;GACrC,QAAQ,QAAQ,cAAc,OAAO,OAAO,SAAS,EAAE;GACvD,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,SAAS,GAAG,KACrC,QAAQ,GAAG,IAAI,OAAO,cAAc,OAAO,EAAE;EAEjD;EAEA,OAAOC,wCAAO,OAAc;CAC9B;AACF;AAEA,MAAa,qCACX,eACc;CACd,OAAOC,+DAAkB,YAAY;EACnC,eAAe;EACf,SAAS,CAAC;EACV,SAAS,CAAC;GAAE,IAAI;GAAM,GAAG;EAAmB,CAAC;CAC/C,CAAC;AACH;AAEA,MAAa,qCACX,YAC0B;CAC1B,OAAOA,+DAAkB,SAAS;EAChC,eAAe;EACf,SAAS,CAAC;EACV,SAAS,CAAC;GAAE,IAAI;GAAM,GAAG;EAAmB,CAAC;CAC/C,CAAC;AACH"}
@@ -204,9 +204,9 @@ const parseTaggedMessage = (message) => {
204
204
  tag: selfClosingTag,
205
205
  children: []
206
206
  });
207
- else tokens.push({
207
+ else if (tag) tokens.push({
208
208
  tag,
209
- children: parseTaggedMessage(inner)
209
+ children: parseTaggedMessage(inner ?? "")
210
210
  });
211
211
  lastIndex = match.index + match[0].length;
212
212
  match = tagRegex.exec(message);
@@ -1 +1 @@
1
- {"version":3,"file":"resolveMessage.cjs","names":["getCachedIntl","NodeTypes","getPlural","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 { getEnumeration } from '../interpreter/getEnumeration';\nimport { getPlural } from '../interpreter/getPlural';\nimport { getSelect } from '../interpreter/getSelect';\nimport type { PluralContentState } from '../transpiler/plural/plural';\nimport { icuToIntlayerFormatter } from './ICU';\nimport { i18nextToIntlayerFormatter } from './i18next';\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/** Formats an ICU-style formatted argument (`{value, number, percent}`). */\nconst formatArgument = (\n value: unknown,\n type: string,\n style: string | undefined,\n locale: LocalesValues\n): string => {\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): 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)\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);\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): unknown => {\n if (node === null || node === undefined) return node;\n\n if (typeof node === 'string') {\n return interpolateMessage(node, values, locale);\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 );\n } catch {\n return undefined;\n }\n }\n\n if (Array.isArray(node)) {\n return node\n .map((item) => String(resolveMessageNode(item, values, locale) ?? ''))\n .join('');\n }\n\n const typedNode = node as Record<string, unknown> & { nodeType?: string };\n\n if (typedNode.nodeType === NodeTypes.INSERTION) {\n return resolveMessageNode(typedNode[NodeTypes.INSERTION], values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.HTML) {\n // Tags are kept intact — rich rendering is handled by the caller\n return resolveMessageNode(typedNode[NodeTypes.HTML], values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.PLURAL) {\n const pluralState = typedNode[\n NodeTypes.PLURAL\n ] as PluralContentState<unknown>;\n const count = Number(getSelectorValue(values, 'count') ?? 1);\n const selected = getPlural(\n pluralState as PluralContentState<string>,\n count,\n locale\n );\n return resolveMessageNode(selected, values, locale);\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 selected = getEnumeration(options, Number(selector));\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);\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);\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);\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): string => {\n const resolved = resolveMessageNode(node, values, locale);\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) => 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) =>\n resolveMessageNodeToString(\n typeof message === 'string' ? formatter(message) : message,\n values,\n locale\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 {\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":";;;;;;;;;;;;;;AA+BA,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;;AAGA,MAAM,kBACJ,OACA,MACA,OACA,WACW;CACX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mBAAmB,MAAM,QAAQ,MAAM;CAExD,OAAO,OAAO,aAAa,WAAW,WAAW,OAAO,YAAY,EAAE;AACxE;;;;;;;;;;;;;;AA4BA,MAAa,yBACV,eACA,SAAS,SAAS,CAAC,GAAG,SAAS,SAC9B,2BACE,OAAO,YAAY,WAAW,UAAU,OAAO,IAAI,SACnD,QACA,MACF;AAEJ,MAAM,qBAAqE;CACzE,KAAKI;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;OAEjD,OAAO,KAAK;GAAE;GAAK,UAAU,mBAAmB,KAAK;EAAE,CAAC;EAG1D,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","getPlural","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 { getEnumeration } from '../interpreter/getEnumeration';\nimport { getPlural } from '../interpreter/getPlural';\nimport { getSelect } from '../interpreter/getSelect';\nimport type { PluralContentState } from '../transpiler/plural/plural';\nimport { icuToIntlayerFormatter } from './ICU';\nimport { i18nextToIntlayerFormatter } from './i18next';\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/** Formats an ICU-style formatted argument (`{value, number, percent}`). */\nconst formatArgument = (\n value: unknown,\n type: string,\n style: string | undefined,\n locale: LocalesValues\n): string => {\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): 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)\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);\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): unknown => {\n if (node === null || node === undefined) return node;\n\n if (typeof node === 'string') {\n return interpolateMessage(node, values, locale);\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 );\n } catch {\n return undefined;\n }\n }\n\n if (Array.isArray(node)) {\n return node\n .map((item) => String(resolveMessageNode(item, values, locale) ?? ''))\n .join('');\n }\n\n const typedNode = node as Record<string, unknown> & { nodeType?: string };\n\n if (typedNode.nodeType === NodeTypes.INSERTION) {\n return resolveMessageNode(typedNode[NodeTypes.INSERTION], values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.HTML) {\n // Tags are kept intact — rich rendering is handled by the caller\n return resolveMessageNode(typedNode[NodeTypes.HTML], values, locale);\n }\n\n if (typedNode.nodeType === NodeTypes.PLURAL) {\n const pluralState = typedNode[\n NodeTypes.PLURAL\n ] as PluralContentState<unknown>;\n const count = Number(getSelectorValue(values, 'count') ?? 1);\n const selected = getPlural(\n pluralState as PluralContentState<string>,\n count,\n locale\n );\n return resolveMessageNode(selected, values, locale);\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 selected = getEnumeration(options, Number(selector));\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);\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);\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);\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): string => {\n const resolved = resolveMessageNode(node, values, locale);\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) => 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) =>\n resolveMessageNodeToString(\n typeof message === 'string' ? formatter(message) : message,\n values,\n locale\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":";;;;;;;;;;;;;;AA+BA,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;;AAGA,MAAM,kBACJ,OACA,MACA,OACA,WACW;CACX,IAAI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B,MAAM,QAAQ,MAAM;CAExD,OAAO,OAAO,aAAa,WAAW,WAAW,OAAO,YAAY,EAAE;AACxE;;;;;;;;;;;;;;AA4BA,MAAa,yBACV,eACA,SAAS,SAAS,CAAC,GAAG,SAAS,SAC9B,2BACE,OAAO,YAAY,WAAW,UAAU,OAAO,IAAI,SACnD,QACA,MACF;AAEJ,MAAM,qBAAqE;CACzE,KAAKI;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"}
@@ -12,14 +12,14 @@ const require_messageFormat_ICU = require('./ICU.cjs');
12
12
  console.log("=== ICU Format Verification ===\n");
13
13
  console.log("Test 1: Simple Interpolation");
14
14
  console.log("Intlayer input:", require_transpiler_insertion_insertion.insert("Hello {{name}}"));
15
- const test1 = require_messageFormat_ICU.intlayerToICUFormatter(require_transpiler_insertion_insertion.insert("Hello {{name}}"));
15
+ const test1 = String(require_messageFormat_ICU.intlayerToICUFormatter(require_transpiler_insertion_insertion.insert("Hello {{name}}")));
16
16
  console.log("ICU output:", test1);
17
17
  console.log("✓ Expected: Single braces {name}");
18
18
  console.log("✓ Result:", test1.includes("{name}") && !test1.includes("{{name}}") ? "PASS" : "FAIL");
19
19
  console.log();
20
20
  console.log("Test 2: Formatted Variable");
21
21
  console.log("Intlayer input:", require_transpiler_insertion_insertion.insert("Price: {amount, number, currency}"));
22
- const test2 = require_messageFormat_ICU.intlayerToICUFormatter(require_transpiler_insertion_insertion.insert("Price: {amount, number, currency}"));
22
+ const test2 = String(require_messageFormat_ICU.intlayerToICUFormatter(require_transpiler_insertion_insertion.insert("Price: {amount, number, currency}")));
23
23
  console.log("ICU output:", test2);
24
24
  console.log("✓ Expected: Single braces {amount, number, currency}");
25
25
  console.log("✓ Result:", test2.includes("{amount, number, currency}") ? "PASS" : "FAIL");
@@ -31,7 +31,7 @@ const pluralInput = require_transpiler_enumeration_enumeration.enu({
31
31
  fallback: "{{count}} items"
32
32
  });
33
33
  console.log("Intlayer input:", JSON.stringify(pluralInput, null, 2));
34
- const test3 = require_messageFormat_ICU.intlayerToICUFormatter(pluralInput);
34
+ const test3 = String(require_messageFormat_ICU.intlayerToICUFormatter(pluralInput));
35
35
  console.log("ICU output:", test3);
36
36
  console.log("✓ Expected: {count, plural, ...} with # for count");
37
37
  console.log("✓ Result:", test3.includes("{count, plural,") && test3.includes("# items") && !test3.includes("{{") ? "PASS" : "FAIL");
@@ -52,7 +52,7 @@ const genderInput = require_transpiler_gender_gender.gender({
52
52
  female: "She has items",
53
53
  fallback: "They have items"
54
54
  });
55
- const test5 = require_messageFormat_ICU.intlayerToICUFormatter(genderInput);
55
+ const test5 = String(require_messageFormat_ICU.intlayerToICUFormatter(genderInput));
56
56
  console.log("ICU output:", test5);
57
57
  console.log("✓ Expected: Single braces only");
58
58
  console.log("✓ Result:", !test5.includes("{{") ? "PASS" : "FAIL");
@@ -1 +1 @@
1
- {"version":3,"file":"verify-icu-format.cjs","names":["insert","intlayerToICUFormatter","enu","icuToIntlayerFormatter","gender"],"sources":["../../../src/messageFormat/verify-icu-format.ts"],"sourcesContent":["/**\n * Verification script to demonstrate ICU format conversion\n * This script shows that Intlayer correctly converts {{var}} (internal format)\n * to {var} (ICU format) when outputting.\n */\n\nimport { enu, gender, insert } from '../transpiler';\nimport { icuToIntlayerFormatter, intlayerToICUFormatter } from './ICU';\n\nconsole.log('=== ICU Format Verification ===\\n');\n\n// Test 1: Simple interpolation\nconsole.log('Test 1: Simple Interpolation');\nconsole.log('Intlayer input:', insert('Hello {{name}}'));\nconst test1 = intlayerToICUFormatter(insert('Hello {{name}}'));\nconsole.log('ICU output:', test1);\nconsole.log('✓ Expected: Single braces {name}');\nconsole.log(\n '✓ Result:',\n test1.includes('{name}') && !test1.includes('{{name}}') ? 'PASS' : 'FAIL'\n);\nconsole.log();\n\n// Test 2: Formatted variable\nconsole.log('Test 2: Formatted Variable');\nconsole.log('Intlayer input:', insert('Price: {amount, number, currency}'));\nconst test2 = intlayerToICUFormatter(\n insert('Price: {amount, number, currency}')\n);\nconsole.log('ICU output:', test2);\nconsole.log('✓ Expected: Single braces {amount, number, currency}');\nconsole.log(\n '✓ Result:',\n test2.includes('{amount, number, currency}') ? 'PASS' : 'FAIL'\n);\nconsole.log();\n\n// Test 3: Plural with variable\nconsole.log('Test 3: Plural with Variable');\nconst pluralInput = enu({\n '0': 'No items',\n '1': 'One item',\n fallback: '{{count}} items',\n});\nconsole.log('Intlayer input:', JSON.stringify(pluralInput, null, 2));\nconst test3 = intlayerToICUFormatter(pluralInput);\nconsole.log('ICU output:', test3);\nconsole.log('✓ Expected: {count, plural, ...} with # for count');\nconsole.log(\n '✓ Result:',\n test3.includes('{count, plural,') &&\n test3.includes('# items') &&\n !test3.includes('{{')\n ? 'PASS'\n : 'FAIL'\n);\nconsole.log();\n\n// Test 4: Roundtrip conversion\nconsole.log('Test 4: Roundtrip Conversion (ICU → Intlayer → ICU)');\nconst original =\n 'Hello {name}, you have {count, plural, =0 {no messages} =1 {one message} other {# messages}}';\nconsole.log('Original ICU:', original);\nconst toIntlayer = icuToIntlayerFormatter(original);\nconsole.log('Converted to Intlayer:', JSON.stringify(toIntlayer, null, 2));\nconst backToICU = intlayerToICUFormatter(toIntlayer);\nconsole.log('Back to ICU:', backToICU);\nconsole.log('✓ Expected: No {{...}} in output');\nconsole.log('✓ Result:', !String(backToICU).includes('{{') ? 'PASS' : 'FAIL');\nconsole.log();\n\n// Test 5: Gender with nested plural\nconsole.log('Test 5: Gender with Nested Structures');\nconst genderInput = gender({\n male: 'He has items',\n female: 'She has items',\n fallback: 'They have items',\n});\nconst test5 = intlayerToICUFormatter(genderInput);\nconsole.log('ICU output:', test5);\nconsole.log('✓ Expected: Single braces only');\nconsole.log('✓ Result:', !test5.includes('{{') ? 'PASS' : 'FAIL');\nconsole.log();\n\nconsole.log('=== Summary ===');\nconsole.log('ICU MessageFormat uses single braces: {var}');\nconsole.log('Intlayer internal format uses double braces: {{var}}');\nconsole.log('The conversion between these formats is handled automatically.');\n"],"mappings":";;;;;;;;;;;AASA,QAAQ,IAAI,mCAAmC;AAG/C,QAAQ,IAAI,8BAA8B;AAC1C,QAAQ,IAAI,mBAAmBA,8CAAO,gBAAgB,CAAC;AACvD,MAAM,QAAQC,iDAAuBD,8CAAO,gBAAgB,CAAC;AAC7D,QAAQ,IAAI,eAAe,KAAK;AAChC,QAAQ,IAAI,kCAAkC;AAC9C,QAAQ,IACN,aACA,MAAM,SAAS,QAAQ,KAAK,CAAC,MAAM,SAAS,UAAU,IAAI,SAAS,MACrE;AACA,QAAQ,IAAI;AAGZ,QAAQ,IAAI,4BAA4B;AACxC,QAAQ,IAAI,mBAAmBA,8CAAO,mCAAmC,CAAC;AAC1E,MAAM,QAAQC,iDACZD,8CAAO,mCAAmC,CAC5C;AACA,QAAQ,IAAI,eAAe,KA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AQ,IAAI,sDAAsD;AAClE,QAAQ,IAAI,gEAAgE"}
1
+ {"version":3,"file":"verify-icu-format.cjs","names":["insert","intlayerToICUFormatter","enu","icuToIntlayerFormatter","gender"],"sources":["../../../src/messageFormat/verify-icu-format.ts"],"sourcesContent":["/**\n * Verification script to demonstrate ICU format conversion\n * This script shows that Intlayer correctly converts {{var}} (internal format)\n * to {var} (ICU format) when outputting.\n */\n\nimport { enu, gender, insert } from '../transpiler';\nimport { icuToIntlayerFormatter, intlayerToICUFormatter } from './ICU';\n\nconsole.log('=== ICU Format Verification ===\\n');\n\n// Test 1: Simple interpolation\nconsole.log('Test 1: Simple Interpolation');\nconsole.log('Intlayer input:', insert('Hello {{name}}'));\nconst test1 = String(intlayerToICUFormatter(insert('Hello {{name}}')));\nconsole.log('ICU output:', test1);\nconsole.log('✓ Expected: Single braces {name}');\nconsole.log(\n '✓ Result:',\n test1.includes('{name}') && !test1.includes('{{name}}') ? 'PASS' : 'FAIL'\n);\nconsole.log();\n\n// Test 2: Formatted variable\nconsole.log('Test 2: Formatted Variable');\nconsole.log('Intlayer input:', insert('Price: {amount, number, currency}'));\nconst test2 = String(\n intlayerToICUFormatter(insert('Price: {amount, number, currency}'))\n);\nconsole.log('ICU output:', test2);\nconsole.log('✓ Expected: Single braces {amount, number, currency}');\nconsole.log(\n '✓ Result:',\n test2.includes('{amount, number, currency}') ? 'PASS' : 'FAIL'\n);\nconsole.log();\n\n// Test 3: Plural with variable\nconsole.log('Test 3: Plural with Variable');\nconst pluralInput = enu({\n '0': 'No items',\n '1': 'One item',\n fallback: '{{count}} items',\n});\nconsole.log('Intlayer input:', JSON.stringify(pluralInput, null, 2));\nconst test3 = String(intlayerToICUFormatter(pluralInput));\nconsole.log('ICU output:', test3);\nconsole.log('✓ Expected: {count, plural, ...} with # for count');\nconsole.log(\n '✓ Result:',\n test3.includes('{count, plural,') &&\n test3.includes('# items') &&\n !test3.includes('{{')\n ? 'PASS'\n : 'FAIL'\n);\nconsole.log();\n\n// Test 4: Roundtrip conversion\nconsole.log('Test 4: Roundtrip Conversion (ICU → Intlayer → ICU)');\nconst original =\n 'Hello {name}, you have {count, plural, =0 {no messages} =1 {one message} other {# messages}}';\nconsole.log('Original ICU:', original);\nconst toIntlayer = icuToIntlayerFormatter(original);\nconsole.log('Converted to Intlayer:', JSON.stringify(toIntlayer, null, 2));\nconst backToICU = intlayerToICUFormatter(toIntlayer);\nconsole.log('Back to ICU:', backToICU);\nconsole.log('✓ Expected: No {{...}} in output');\nconsole.log('✓ Result:', !String(backToICU).includes('{{') ? 'PASS' : 'FAIL');\nconsole.log();\n\n// Test 5: Gender with nested plural\nconsole.log('Test 5: Gender with Nested Structures');\nconst genderInput = gender({\n male: 'He has items',\n female: 'She has items',\n fallback: 'They have items',\n});\nconst test5 = String(intlayerToICUFormatter(genderInput));\nconsole.log('ICU output:', test5);\nconsole.log('✓ Expected: Single braces only');\nconsole.log('✓ Result:', !test5.includes('{{') ? 'PASS' : 'FAIL');\nconsole.log();\n\nconsole.log('=== Summary ===');\nconsole.log('ICU MessageFormat uses single braces: {var}');\nconsole.log('Intlayer internal format uses double braces: {{var}}');\nconsole.log('The conversion between these formats is handled automatically.');\n"],"mappings":";;;;;;;;;;;AASA,QAAQ,IAAI,mCAAmC;AAG/C,QAAQ,IAAI,8BAA8B;AAC1C,QAAQ,IAAI,mBAAmBA,8CAAO,gBAAgB,CAAC;AACvD,MAAM,QAAQ,OAAOC,iDAAuBD,8CAAO,gBAAgB,CAAC,CAAC;AACrE,QAAQ,IAAI,eAAe,KAAK;AAChC,QAAQ,IAAI,kCAAkC;AAC9C,QAAQ,IACN,aACA,MAAM,SAAS,QAAQ,KAAK,CAAC,MAAM,SAAS,UAAU,IAAI,SAAS,MACrE;AACA,QAAQ,IAAI;AAGZ,QAAQ,IAAI,4BAA4B;AACxC,QAAQ,IAAI,mBAAmBA,8CAAO,mCAAmC,CAAC;AAC1E,MAAM,QAAQ,OACZC,iDAAuBD,8CAAO,mCAAmC,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AEZ,QAAQ,IAAI,iBAAiB;AAC7B,QAAQ,IAAI,6CAA6C;AACzD,QAAQ,IAAI,sDAAsD;AAClE,QAAQ,IAAI,gEAAgE"}
@@ -67,14 +67,14 @@ const vueI18nPartToIntlayer = (nodes) => {
67
67
  return require_transpiler_insertion_insertion.insert(str);
68
68
  };
69
69
  const vueI18nNodesToIntlayer = (parts) => {
70
- if (parts.length === 1) return vueI18nPartToIntlayer(parts[0]);
70
+ if (parts.length === 1 && parts[0]) return vueI18nPartToIntlayer(parts[0]);
71
71
  const options = {};
72
72
  const varName = "count";
73
- if (parts.length === 2) return require_transpiler_enumeration_enumeration.enu({
73
+ if (parts.length === 2 && parts[0] && parts[1]) return require_transpiler_enumeration_enumeration.enu({
74
74
  "1": vueI18nPartToIntlayer(parts[0]),
75
75
  fallback: vueI18nPartToIntlayer(parts[1])
76
76
  });
77
- if (parts.length === 3) return require_transpiler_enumeration_enumeration.enu({
77
+ if (parts.length === 3 && parts[0] && parts[1] && parts[2]) return require_transpiler_enumeration_enumeration.enu({
78
78
  "0": vueI18nPartToIntlayer(parts[0]),
79
79
  "1": vueI18nPartToIntlayer(parts[1]),
80
80
  fallback: vueI18nPartToIntlayer(parts[2])
@@ -105,7 +105,7 @@ const intlayerToVueI18nPlugin = {
105
105
  if (node.length === 0) return false;
106
106
  let hasNode = false;
107
107
  let hasPlainObjectOrArray = false;
108
- for (const item of node) if (typeof item === "string") {} else if (item && typeof item === "object" && (item.nodeType === _intlayer_types_nodeType.INSERTION || item.nodeType === _intlayer_types_nodeType.ENUMERATION || item.nodeType === _intlayer_types_nodeType.GENDER || item.nodeType === _intlayer_types_nodeType.SELECT || item.nodeType === "composite")) hasNode = true;
108
+ for (const item of node) if (typeof item === "string") {} else if (item && typeof item === "object" && (item.nodeType === _intlayer_types_nodeType.INSERTION || item.nodeType === _intlayer_types_nodeType.ENUMERATION || item.nodeType === _intlayer_types_nodeType.PLURAL || item.nodeType === _intlayer_types_nodeType.GENDER || item.nodeType === _intlayer_types_nodeType.SELECT || item.nodeType === "composite")) hasNode = true;
109
109
  else hasPlainObjectOrArray = true;
110
110
  if (hasPlainObjectOrArray) return false;
111
111
  if (!hasNode) return false;
@@ -1 +1 @@
1
- {"version":3,"file":"vue-i18n.cjs","names":["insert","enu","NodeTypes","deepTransformNode"],"sources":["../../../src/messageFormat/vue-i18n.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { deepTransformNode } from '../interpreter';\nimport { enu, insert } from '../transpiler';\nimport type { JsonValue } from './ICU';\n\n// Types for our AST\ntype VueI18nNode =\n | string\n | {\n type: 'argument';\n name: string;\n };\n\nconst parseVueI18nPart = (text: string): VueI18nNode[] => {\n let index = 0;\n const nodes: VueI18nNode[] = [];\n let currentText = '';\n\n while (index < text.length) {\n const char = text[index];\n\n if (char === '{') {\n if (currentText) {\n nodes.push(currentText);\n currentText = '';\n }\n index++; // skip {\n let name = '';\n while (index < text.length && text[index] !== '}') {\n name += text[index];\n index++;\n }\n if (index < text.length) {\n index++; // skip }\n }\n nodes.push({ type: 'argument', name: name.trim() });\n } else {\n currentText += char;\n index++;\n }\n }\n\n if (currentText) {\n nodes.push(currentText);\n }\n\n return nodes;\n};\n\nconst parseVueI18n = (text: string): VueI18nNode[][] => {\n // Split by | but handle escaped \\|\n const parts: string[] = [];\n let currentPart = '';\n let index = 0;\n\n while (index < text.length) {\n const char = text[index];\n if (char === '\\\\' && index + 1 < text.length && text[index + 1] === '|') {\n currentPart += '|';\n index += 2;\n } else if (char === '|') {\n parts.push(currentPart.trim()); // Trim to remove surrounding spaces\n currentPart = '';\n index++;\n } else {\n currentPart += char;\n index++;\n }\n }\n parts.push(currentPart.trim()); // Trim last part too\n\n return parts.map(parseVueI18nPart);\n};\n\nconst vueI18nPartToIntlayer = (nodes: VueI18nNode[]): any => {\n if (nodes.length === 0) return '';\n if (nodes.length === 1 && typeof nodes[0] === 'string') return nodes[0];\n\n let str = '';\n for (const node of nodes) {\n if (typeof node === 'string') {\n str += node;\n } else {\n str += `{{${node.name}}}`;\n }\n }\n return insert(str);\n};\n\nconst vueI18nNodesToIntlayer = (parts: VueI18nNode[][]): any => {\n if (parts.length === 1) {\n return vueI18nPartToIntlayer(parts[0]);\n }\n\n // Handle pluralization (choice).\n // vue-i18n's choice rule is POSITIONAL (0 | 1 | other), not CLDR-based:\n // an enumeration node preserves those semantics in every locale, whereas\n // a plural node would select by CLDR category (e.g. count 0 resolves to\n // 'one' in French, 'other' in English — never 'zero').\n const options: Record<string, any> = {};\n const varName = 'count'; // Default variable for vue-i18n choices\n\n if (parts.length === 2) {\n // 2 choices: 1 | other\n return enu({\n '1': vueI18nPartToIntlayer(parts[0]),\n fallback: vueI18nPartToIntlayer(parts[1]),\n });\n }\n\n if (parts.length === 3) {\n // 3 choices: 0 | 1 | other\n return enu({\n '0': vueI18nPartToIntlayer(parts[0]),\n '1': vueI18nPartToIntlayer(parts[1]),\n fallback: vueI18nPartToIntlayer(parts[2]),\n });\n }\n\n // > 3 choices: 0 | 1 | 2 | ... | other\n parts.forEach((part, index) => {\n if (index === parts.length - 1) {\n options.fallback = vueI18nPartToIntlayer(part);\n } else {\n options[index.toString()] = vueI18nPartToIntlayer(part);\n }\n });\n\n // Preserve variable name\n options.__intlayer_vue_i18n_var = varName;\n\n return enu(options);\n};\n\nconst vueI18nToIntlayerPlugin = {\n canHandle: (node: any) =>\n typeof node === 'string' && (node.includes('{') || node.includes('|')),\n transform: (node: any) => {\n try {\n const ast = parseVueI18n(node);\n return vueI18nNodesToIntlayer(ast);\n } catch {\n return node;\n }\n },\n};\n\nconst intlayerToVueI18nPlugin = {\n canHandle: (node: any) => {\n if (typeof node === 'string') return true;\n\n if (\n node &&\n typeof node === 'object' &&\n (node.nodeType === NodeTypes.INSERTION ||\n node.nodeType === NodeTypes.ENUMERATION ||\n node.nodeType === NodeTypes.PLURAL ||\n node.nodeType === NodeTypes.GENDER ||\n node.nodeType === NodeTypes.SELECT ||\n node.nodeType === 'composite')\n ) {\n return true;\n }\n\n if (Array.isArray(node)) {\n if (node.length === 0) return false;\n\n let hasNode = false;\n let hasPlainObjectOrArray = false;\n\n for (const item of node) {\n if (typeof item === 'string') {\n } else if (\n item &&\n typeof item === 'object' &&\n (item.nodeType === NodeTypes.INSERTION ||\n item.nodeType === NodeTypes.ENUMERATION ||\n item.nodeType === NodeTypes.GENDER ||\n item.nodeType === NodeTypes.SELECT ||\n item.nodeType === 'composite')\n ) {\n hasNode = true;\n } else {\n hasPlainObjectOrArray = true;\n }\n }\n\n // If it contains plain objects or nested arrays, it's a structural array\n if (hasPlainObjectOrArray) return false;\n // If it contains ONLY strings, it's a structural array, not a composite string\n if (!hasNode) return false;\n\n return true;\n }\n\n return false;\n },\n transform: (node: any, props: any, next: any) => {\n if (typeof node === 'string') {\n // replace {{...}} with {...} even in strings\n return node.replace(/\\{\\{([^}]+)\\}\\}/g, '{$1}');\n }\n\n if (node.nodeType === NodeTypes.INSERTION) {\n // {{name}} -> {name}\n return node[NodeTypes.INSERTION].replace(/\\{\\{([^}]+)\\}\\}/g, '{$1}');\n }\n\n if (node.nodeType === NodeTypes.PLURAL) {\n const options = node[NodeTypes.PLURAL];\n\n const transformedOptions: Record<string, string> = {};\n for (const [key, val] of Object.entries(options)) {\n const childVal = next(val, props);\n transformedOptions[key] =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n }\n\n if (\n transformedOptions.zero &&\n transformedOptions.one &&\n transformedOptions.other\n ) {\n return `${transformedOptions.zero} | ${transformedOptions.one} | ${transformedOptions.other}`;\n }\n\n if (transformedOptions.one && transformedOptions.other) {\n return `${transformedOptions.one} | ${transformedOptions.other}`;\n }\n\n return transformedOptions.other || Object.values(transformedOptions)[0];\n }\n\n if (node.nodeType === NodeTypes.ENUMERATION) {\n const options = node[NodeTypes.ENUMERATION];\n\n const transformedOptions: Record<string, string> = {};\n for (const [key, val] of Object.entries(options)) {\n if (\n key === '__intlayer_vue_i18n_var' ||\n key === '__intlayer_icu_var' ||\n key === '__intlayer_icu_ordinal'\n )\n continue;\n const childVal = next(val, props);\n transformedOptions[key] =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n }\n\n const keys = Object.keys(transformedOptions);\n\n if (keys.includes('0')) {\n const indices = keys.filter((key) => /^\\d+$/.test(key)).map(Number);\n const maxIndex = Math.max(...indices);\n\n const fallback =\n transformedOptions.fallback || transformedOptions.other;\n const resultParts = [];\n\n if (maxIndex <= 1 && !keys.includes('2')) {\n const zero = transformedOptions['0'] || '';\n const one = transformedOptions['1'] || '';\n return `${zero} | ${one} | ${fallback}`;\n }\n\n const limit = Math.max(1, maxIndex);\n\n for (let i = 0; i <= limit; i++) {\n const key = i.toString();\n if (transformedOptions[key]) {\n resultParts.push(transformedOptions[key]);\n } else {\n resultParts.push('');\n }\n }\n resultParts.push(fallback);\n return resultParts.join(' | ').replace(/ \\| {2}\\| /g, ' | | ');\n }\n\n if (\n keys.includes('1') &&\n (keys.includes('fallback') || keys.includes('other'))\n ) {\n return `${transformedOptions['1']} | ${transformedOptions.fallback || transformedOptions.other}`;\n }\n\n if (\n keys.length === 1 &&\n (keys.includes('fallback') || keys.includes('other'))\n ) {\n return transformedOptions.fallback || transformedOptions.other;\n }\n\n return (\n transformedOptions.fallback || Object.values(transformedOptions)[0]\n );\n }\n\n if (node.nodeType === NodeTypes.GENDER) {\n const options = node[NodeTypes.GENDER];\n const transformedOptions: Record<string, any> = {};\n\n for (const [key, val] of Object.entries(options)) {\n let newKey = key;\n if (key === 'fallback') newKey = 'other';\n\n const childVal = next(val, props);\n transformedOptions[newKey] = childVal;\n }\n return transformedOptions;\n }\n\n if (node.nodeType === NodeTypes.SELECT) {\n const options = node[NodeTypes.SELECT];\n const transformedOptions: Record<string, any> = {};\n\n // vue-i18n has no `select` syntax: the cases become a nested message\n // object, resolved by the caller with `t('key.Draft')`.\n for (const [key, val] of Object.entries(options)) {\n const newKey = key === 'fallback' ? 'other' : key;\n\n transformedOptions[newKey] = next(val, props);\n }\n return transformedOptions;\n }\n\n if (\n Array.isArray(node) ||\n (node.nodeType === 'composite' && Array.isArray(node.composite))\n ) {\n const arr = Array.isArray(node) ? node : node.composite;\n const items = arr.map((item: any) => next(item, props));\n return items.join('');\n }\n\n return next(node, props);\n },\n};\n\nexport const intlayerToVueI18nFormatter = (\n message: Dictionary['content']\n): JsonValue => {\n return deepTransformNode(message, {\n dictionaryKey: 'vue-i18n',\n keyPath: [],\n plugins: [{ id: 'vue-i18n', ...intlayerToVueI18nPlugin }],\n });\n};\n\nexport const vueI18nToIntlayerFormatter = (\n message: JsonValue\n): Dictionary['content'] => {\n return deepTransformNode(message, {\n dictionaryKey: 'vue-i18n',\n keyPath: [],\n plugins: [{ id: 'vue-i18n', ...vueI18nToIntlayerPlugin }],\n });\n};\n"],"mappings":";;;;;;;;;AAcA,MAAM,oBAAoB,SAAgC;CACxD,IAAI,QAAQ;CACZ,MAAM,QAAuB,CAAC;CAC9B,IAAI,cAAc;CAElB,OAAO,QAAQ,KAAK,QAAQ;EAC1B,MAAM,OAAO,KAAK;EAElB,IAAI,SAAS,KAAK;GAChB,IAAI,aAAa;IACf,MAAM,KAAK,WAAW;IACtB,cAAc;GAChB;GACA;GACA,IAAI,OAAO;GACX,OAAO,QAAQ,KAAK,UAAU,KAAK,WAAW,KAAK;IACjD,QAAQ,KAAK;IACb;GACF;GACA,IAAI,QAAQ,KAAK,QACf;GAEF,MAAM,KAAK;IAAE,MAAM;IAAY,MAAM,KAAK,KAAK;GAAE,CAAC;EACpD,OAAO;GACL,eAAe;GACf;EACF;CACF;CAEA,IAAI,aACF,MAAM,KAAK,WAAW;CAGxB,OAAO;AACT;AAEA,MAAM,gBAAgB,SAAkC;CAEtD,MAAM,QAAkB,CAAC;CACzB,IAAI,cAAc;CAClB,IAAI,QAAQ;CAEZ,OAAO,QAAQ,KAAK,QAAQ;EAC1B,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,QAAQ,QAAQ,I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MAAM,KAAK;CACzB;AACF;AAEA,MAAa,8BACX,YACc;CACd,OAAOC,+DAAkB,SAAS;EAChC,eAAe;EACf,SAAS,CAAC;EACV,SAAS,CAAC;GAAE,IAAI;GAAY,GAAG;EAAwB,CAAC;CAC1D,CAAC;AACH;AAEA,MAAa,8BACX,YAC0B;CAC1B,OAAOA,+DAAkB,SAAS;EAChC,eAAe;EACf,SAAS,CAAC;EACV,SAAS,CAAC;GAAE,IAAI;GAAY,GAAG;EAAwB,CAAC;CAC1D,CAAC;AACH"}
1
+ {"version":3,"file":"vue-i18n.cjs","names":["insert","enu","NodeTypes","deepTransformNode"],"sources":["../../../src/messageFormat/vue-i18n.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { deepTransformNode } from '../interpreter';\nimport { enu, insert } from '../transpiler';\nimport type { JsonValue } from './ICU';\n\n// Types for our AST\ntype VueI18nNode =\n | string\n | {\n type: 'argument';\n name: string;\n };\n\nconst parseVueI18nPart = (text: string): VueI18nNode[] => {\n let index = 0;\n const nodes: VueI18nNode[] = [];\n let currentText = '';\n\n while (index < text.length) {\n const char = text[index];\n\n if (char === '{') {\n if (currentText) {\n nodes.push(currentText);\n currentText = '';\n }\n index++; // skip {\n let name = '';\n while (index < text.length && text[index] !== '}') {\n name += text[index];\n index++;\n }\n if (index < text.length) {\n index++; // skip }\n }\n nodes.push({ type: 'argument', name: name.trim() });\n } else {\n currentText += char;\n index++;\n }\n }\n\n if (currentText) {\n nodes.push(currentText);\n }\n\n return nodes;\n};\n\nconst parseVueI18n = (text: string): VueI18nNode[][] => {\n // Split by | but handle escaped \\|\n const parts: string[] = [];\n let currentPart = '';\n let index = 0;\n\n while (index < text.length) {\n const char = text[index];\n if (char === '\\\\' && index + 1 < text.length && text[index + 1] === '|') {\n currentPart += '|';\n index += 2;\n } else if (char === '|') {\n parts.push(currentPart.trim()); // Trim to remove surrounding spaces\n currentPart = '';\n index++;\n } else {\n currentPart += char;\n index++;\n }\n }\n parts.push(currentPart.trim()); // Trim last part too\n\n return parts.map(parseVueI18nPart);\n};\n\nconst vueI18nPartToIntlayer = (nodes: VueI18nNode[]): any => {\n if (nodes.length === 0) return '';\n if (nodes.length === 1 && typeof nodes[0] === 'string') return nodes[0];\n\n let str = '';\n for (const node of nodes) {\n if (typeof node === 'string') {\n str += node;\n } else {\n str += `{{${node.name}}}`;\n }\n }\n return insert(str);\n};\n\nconst vueI18nNodesToIntlayer = (parts: VueI18nNode[][]): any => {\n if (parts.length === 1 && parts[0]) {\n return vueI18nPartToIntlayer(parts[0]);\n }\n\n // Handle pluralization (choice).\n // vue-i18n's choice rule is POSITIONAL (0 | 1 | other), not CLDR-based:\n // an enumeration node preserves those semantics in every locale, whereas\n // a plural node would select by CLDR category (e.g. count 0 resolves to\n // 'one' in French, 'other' in English — never 'zero').\n const options: Record<string, any> = {};\n const varName = 'count'; // Default variable for vue-i18n choices\n\n if (parts.length === 2 && parts[0] && parts[1]) {\n // 2 choices: 1 | other\n return enu({\n '1': vueI18nPartToIntlayer(parts[0]),\n fallback: vueI18nPartToIntlayer(parts[1]),\n });\n }\n\n if (parts.length === 3 && parts[0] && parts[1] && parts[2]) {\n // 3 choices: 0 | 1 | other\n return enu({\n '0': vueI18nPartToIntlayer(parts[0]),\n '1': vueI18nPartToIntlayer(parts[1]),\n fallback: vueI18nPartToIntlayer(parts[2]),\n });\n }\n\n // > 3 choices: 0 | 1 | 2 | ... | other\n parts.forEach((part, index) => {\n if (index === parts.length - 1) {\n options.fallback = vueI18nPartToIntlayer(part);\n } else {\n options[index.toString()] = vueI18nPartToIntlayer(part);\n }\n });\n\n // Preserve variable name\n options.__intlayer_vue_i18n_var = varName;\n\n return enu(options);\n};\n\nconst vueI18nToIntlayerPlugin = {\n canHandle: (node: any) =>\n typeof node === 'string' && (node.includes('{') || node.includes('|')),\n transform: (node: any) => {\n try {\n const ast = parseVueI18n(node);\n return vueI18nNodesToIntlayer(ast);\n } catch {\n return node;\n }\n },\n};\n\nconst intlayerToVueI18nPlugin = {\n canHandle: (node: any) => {\n if (typeof node === 'string') return true;\n\n if (\n node &&\n typeof node === 'object' &&\n (node.nodeType === NodeTypes.INSERTION ||\n node.nodeType === NodeTypes.ENUMERATION ||\n node.nodeType === NodeTypes.PLURAL ||\n node.nodeType === NodeTypes.GENDER ||\n node.nodeType === NodeTypes.SELECT ||\n node.nodeType === 'composite')\n ) {\n return true;\n }\n\n if (Array.isArray(node)) {\n if (node.length === 0) return false;\n\n let hasNode = false;\n let hasPlainObjectOrArray = false;\n\n for (const item of node) {\n if (typeof item === 'string') {\n } else if (\n item &&\n typeof item === 'object' &&\n (item.nodeType === NodeTypes.INSERTION ||\n item.nodeType === NodeTypes.ENUMERATION ||\n item.nodeType === NodeTypes.PLURAL ||\n item.nodeType === NodeTypes.GENDER ||\n item.nodeType === NodeTypes.SELECT ||\n item.nodeType === 'composite')\n ) {\n hasNode = true;\n } else {\n hasPlainObjectOrArray = true;\n }\n }\n\n // If it contains plain objects or nested arrays, it's a structural array\n if (hasPlainObjectOrArray) return false;\n // If it contains ONLY strings, it's a structural array, not a composite string\n if (!hasNode) return false;\n\n return true;\n }\n\n return false;\n },\n transform: (node: any, props: any, next: any) => {\n if (typeof node === 'string') {\n // replace {{...}} with {...} even in strings\n return node.replace(/\\{\\{([^}]+)\\}\\}/g, '{$1}');\n }\n\n if (node.nodeType === NodeTypes.INSERTION) {\n // {{name}} -> {name}\n return node[NodeTypes.INSERTION].replace(/\\{\\{([^}]+)\\}\\}/g, '{$1}');\n }\n\n if (node.nodeType === NodeTypes.PLURAL) {\n const options = node[NodeTypes.PLURAL];\n\n const transformedOptions: Record<string, string> = {};\n for (const [key, val] of Object.entries(options)) {\n const childVal = next(val, props);\n transformedOptions[key] =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n }\n\n if (\n transformedOptions.zero &&\n transformedOptions.one &&\n transformedOptions.other\n ) {\n return `${transformedOptions.zero} | ${transformedOptions.one} | ${transformedOptions.other}`;\n }\n\n if (transformedOptions.one && transformedOptions.other) {\n return `${transformedOptions.one} | ${transformedOptions.other}`;\n }\n\n return transformedOptions.other || Object.values(transformedOptions)[0];\n }\n\n if (node.nodeType === NodeTypes.ENUMERATION) {\n const options = node[NodeTypes.ENUMERATION];\n\n const transformedOptions: Record<string, string> = {};\n for (const [key, val] of Object.entries(options)) {\n if (\n key === '__intlayer_vue_i18n_var' ||\n key === '__intlayer_icu_var' ||\n key === '__intlayer_icu_ordinal'\n )\n continue;\n const childVal = next(val, props);\n transformedOptions[key] =\n typeof childVal === 'string' ? childVal : JSON.stringify(childVal);\n }\n\n const keys = Object.keys(transformedOptions);\n\n if (keys.includes('0')) {\n const indices = keys.filter((key) => /^\\d+$/.test(key)).map(Number);\n const maxIndex = Math.max(...indices);\n\n const fallback =\n transformedOptions.fallback || transformedOptions.other;\n const resultParts = [];\n\n if (maxIndex <= 1 && !keys.includes('2')) {\n const zero = transformedOptions['0'] || '';\n const one = transformedOptions['1'] || '';\n return `${zero} | ${one} | ${fallback}`;\n }\n\n const limit = Math.max(1, maxIndex);\n\n for (let i = 0; i <= limit; i++) {\n const key = i.toString();\n if (transformedOptions[key]) {\n resultParts.push(transformedOptions[key]);\n } else {\n resultParts.push('');\n }\n }\n resultParts.push(fallback);\n return resultParts.join(' | ').replace(/ \\| {2}\\| /g, ' | | ');\n }\n\n if (\n keys.includes('1') &&\n (keys.includes('fallback') || keys.includes('other'))\n ) {\n return `${transformedOptions['1']} | ${transformedOptions.fallback || transformedOptions.other}`;\n }\n\n if (\n keys.length === 1 &&\n (keys.includes('fallback') || keys.includes('other'))\n ) {\n return transformedOptions.fallback || transformedOptions.other;\n }\n\n return (\n transformedOptions.fallback || Object.values(transformedOptions)[0]\n );\n }\n\n if (node.nodeType === NodeTypes.GENDER) {\n const options = node[NodeTypes.GENDER];\n const transformedOptions: Record<string, any> = {};\n\n for (const [key, val] of Object.entries(options)) {\n let newKey = key;\n if (key === 'fallback') newKey = 'other';\n\n const childVal = next(val, props);\n transformedOptions[newKey] = childVal;\n }\n return transformedOptions;\n }\n\n if (node.nodeType === NodeTypes.SELECT) {\n const options = node[NodeTypes.SELECT];\n const transformedOptions: Record<string, any> = {};\n\n // vue-i18n has no `select` syntax: the cases become a nested message\n // object, resolved by the caller with `t('key.Draft')`.\n for (const [key, val] of Object.entries(options)) {\n const newKey = key === 'fallback' ? 'other' : key;\n\n transformedOptions[newKey] = next(val, props);\n }\n return transformedOptions;\n }\n\n if (\n Array.isArray(node) ||\n (node.nodeType === 'composite' && Array.isArray(node.composite))\n ) {\n const arr = Array.isArray(node) ? node : node.composite;\n const items = arr.map((item: any) => next(item, props));\n return items.join('');\n }\n\n return next(node, props);\n },\n};\n\nexport const intlayerToVueI18nFormatter = (\n message: Dictionary['content']\n): JsonValue => {\n return deepTransformNode(message, {\n dictionaryKey: 'vue-i18n',\n keyPath: [],\n plugins: [{ id: 'vue-i18n', ...intlayerToVueI18nPlugin }],\n });\n};\n\nexport const vueI18nToIntlayerFormatter = (\n message: JsonValue\n): Dictionary['content'] => {\n return deepTransformNode(message, {\n dictionaryKey: 'vue-i18n',\n keyPath: [],\n plugins: [{ id: 'vue-i18n', ...vueI18nToIntlayerPlugin }],\n });\n};\n"],"mappings":";;;;;;;;;AAcA,MAAM,oBAAoB,SAAgC;CACxD,IAAI,QAAQ;CACZ,MAAM,QAAuB,CAAC;CAC9B,IAAI,cAAc;CAElB,OAAO,QAAQ,KAAK,QAAQ;EAC1B,MAAM,OAAO,KAAK;EAElB,IAAI,SAAS,KAAK;GAChB,IAAI,aAAa;IACf,MAAM,KAAK,WAAW;IACtB,cAAc;GAChB;GACA;GACA,IAAI,OAAO;GACX,OAAO,QAAQ,KAAK,UAAU,KAAK,WAAW,KAAK;IACjD,QAAQ,KAAK;IACb;GACF;GACA,IAAI,QAAQ,KAAK,QACf;GAEF,MAAM,KAAK;IAAE,MAAM;IAAY,MAAM,KAAK,KAAK;GAAE,CAAC;EAC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AAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,OAAO,GAAG;IAChD,MAAM,SAAS,QAAQ,aAAa,UAAU;IAE9C,mBAAmB,UAAU,KAAK,KAAK,KAAK;GAC9C;GACA,OAAO;EACT;EAEA,IACE,MAAM,QAAQ,IAAI,KACjB,KAAK,aAAa,eAAe,MAAM,QAAQ,KAAK,SAAS,GAI9D,QAFY,MAAM,QAAQ,IAAI,IAAI,OAAO,KAAK,UAC7B,CAAC,KAAK,SAAc,KAAK,MAAM,KAAK,CAC1C,CAAC,CAAC,KAAK,EAAE;EAGtB,OAAO,KAAK,MAAM,KAAK;CACzB;AACF;AAEA,MAAa,8BACX,YACc;CACd,OAAOC,+DAAkB,SAAS;EAChC,eAAe;EACf,SAAS,CAAC;EACV,SAAS,CAAC;GAAE,IAAI;GAAY,GAAG;EAAwB,CAAC;CAC1D,CAAC;AACH;AAEA,MAAa,8BACX,YAC0B;CAC1B,OAAOA,+DAAkB,SAAS;EAChC,eAAe;EACf,SAAS,CAAC;EACV,SAAS,CAAC;GAAE,IAAI;GAAY,GAAG;EAAwB,CAAC;CAC1D,CAAC;AACH"}
@@ -5,6 +5,7 @@ const require_utils_isValidReactElement = require('./isValidReactElement.cjs');
5
5
  const require_utils_checkIsURLAbsolute = require('./checkIsURLAbsolute.cjs');
6
6
  const require_utils_getCookie = require('./getCookie.cjs');
7
7
  const require_utils_localeStorage = require('./localeStorage.cjs');
8
+ const require_utils_intlayerNodePrototype = require('./intlayerNodePrototype.cjs');
8
9
  const require_utils_isSameKeyPath = require('./isSameKeyPath.cjs');
9
10
  const require_utils_stringifyYaml = require('./stringifyYaml.cjs');
10
11
 
@@ -16,7 +17,9 @@ exports.LocaleStorageServer = require_utils_localeStorage.LocaleStorageServer;
16
17
  exports.bindIntl = require_utils_intl.bindIntl;
17
18
  exports.checkIsURLAbsolute = require_utils_checkIsURLAbsolute.checkIsURLAbsolute;
18
19
  exports.getCachedIntl = require_utils_intl.getCachedIntl;
20
+ exports.getCachedLocaleFromStorageClient = require_utils_localeStorage.getCachedLocaleFromStorageClient;
19
21
  exports.getCookie = require_utils_getCookie.getCookie;
22
+ exports.getIntlayerNodePrototype = require_utils_intlayerNodePrototype.getIntlayerNodePrototype;
20
23
  exports.getLocaleFromStorage = require_utils_localeStorage.getLocaleFromStorage;
21
24
  exports.getLocaleFromStorageClient = require_utils_localeStorage.getLocaleFromStorageClient;
22
25
  exports.getLocaleFromStorageServer = require_utils_localeStorage.getLocaleFromStorageServer;
@@ -0,0 +1,66 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ //#region src/utils/intlayerNodePrototype.ts
3
+ /**
4
+ * Built prototypes, per base prototype, then per value type (`'string'`…) or,
5
+ * for objects, per value prototype.
6
+ */
7
+ const prototypeCache = /* @__PURE__ */ new Map();
8
+ /**
9
+ * Creates the prototype of every node sharing a base and a value type.
10
+ *
11
+ * Its own members answer the conversions. Any other member missing from the
12
+ * node reaches a Proxy at the end of the chain: the base prototype wins, then
13
+ * the value's members (`title.toUpperCase()`, `title.length`, `price.toFixed`)
14
+ * are served from `node.value`. Reads of the node's own fields never go through
15
+ * the Proxy, which is what keeps framework renderers on their fast path.
16
+ */
17
+ const createIntlayerNodePrototype = (basePrototype, valuePrototype) => Object.create(new Proxy(basePrototype, {
18
+ get: (target, property, receiver) => {
19
+ if (typeof property !== "string" || property === "constructor" || property in target) return Reflect.get(target, property, receiver);
20
+ const { value } = receiver;
21
+ if (value === null || value === void 0) return void 0;
22
+ const member = Object(value)[property];
23
+ return typeof member === "function" ? member.bind(value) : member;
24
+ },
25
+ has: (target, property) => property in target || typeof property === "string" && property !== "constructor" && valuePrototype !== null && property in valuePrototype
26
+ }), {
27
+ toString: { value() {
28
+ return String(this.value ?? "");
29
+ } },
30
+ valueOf: { value() {
31
+ return this.value;
32
+ } },
33
+ [Symbol.toPrimitive]: { value() {
34
+ return this.value ?? "";
35
+ } }
36
+ });
37
+ /**
38
+ * Returns the prototype an Intlayer node is built on, so the node behaves like
39
+ * its `value` (`${node}`, `node.toUpperCase()`, `'trim' in node`) while staying
40
+ * a plain framework object.
41
+ *
42
+ * @param value - The node value; its type decides which members are served.
43
+ * @param basePrototype - The prototype the node would have had, kept ahead of
44
+ * the value's members (e.g. `Function.prototype` for a
45
+ * callable node).
46
+ * @returns The shared prototype to create the node with.
47
+ */
48
+ const getIntlayerNodePrototype = (value, basePrototype = Object.prototype) => {
49
+ const valueType = typeof value;
50
+ const valueKey = value === null || value === void 0 ? null : valueType === "object" || valueType === "function" ? Object.getPrototypeOf(value) : valueType;
51
+ let prototypes = prototypeCache.get(basePrototype);
52
+ if (!prototypes) {
53
+ prototypes = /* @__PURE__ */ new Map();
54
+ prototypeCache.set(basePrototype, prototypes);
55
+ }
56
+ let prototype = prototypes.get(valueKey);
57
+ if (!prototype) {
58
+ prototype = createIntlayerNodePrototype(basePrototype, valueKey === null ? null : Object.getPrototypeOf(Object(value)));
59
+ prototypes.set(valueKey, prototype);
60
+ }
61
+ return prototype;
62
+ };
63
+
64
+ //#endregion
65
+ exports.getIntlayerNodePrototype = getIntlayerNodePrototype;
66
+ //# sourceMappingURL=intlayerNodePrototype.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intlayerNodePrototype.cjs","names":[],"sources":["../../../src/utils/intlayerNodePrototype.ts"],"sourcesContent":["/** A node exposing its underlying value, as every framework's node does. */\ntype ValueNode = { value: unknown };\n\n/**\n * Built prototypes, per base prototype, then per value type (`'string'`…) or,\n * for objects, per value prototype.\n */\nconst prototypeCache = new Map<object, Map<unknown, object>>();\n\n/**\n * Creates the prototype of every node sharing a base and a value type.\n *\n * Its own members answer the conversions. Any other member missing from the\n * node reaches a Proxy at the end of the chain: the base prototype wins, then\n * the value's members (`title.toUpperCase()`, `title.length`, `price.toFixed`)\n * are served from `node.value`. Reads of the node's own fields never go through\n * the Proxy, which is what keeps framework renderers on their fast path.\n */\nconst createIntlayerNodePrototype = (\n basePrototype: object,\n valuePrototype: object | null\n): object =>\n Object.create(\n new Proxy(basePrototype, {\n get: (target, property, receiver: ValueNode) => {\n if (\n typeof property !== 'string' ||\n property === 'constructor' ||\n property in target\n ) {\n return Reflect.get(target, property, receiver);\n }\n\n const { value } = receiver;\n\n if (value === null || value === undefined) return undefined;\n\n const member = Object(value)[property];\n\n return typeof member === 'function' ? member.bind(value) : member;\n },\n has: (target, property) =>\n property in target ||\n (typeof property === 'string' &&\n property !== 'constructor' &&\n valuePrototype !== null &&\n property in valuePrototype),\n }),\n {\n toString: {\n value(this: ValueNode) {\n return String(this.value ?? '');\n },\n },\n valueOf: {\n value(this: ValueNode) {\n return this.value;\n },\n },\n [Symbol.toPrimitive]: {\n value(this: ValueNode) {\n return this.value ?? '';\n },\n },\n }\n );\n\n/**\n * Returns the prototype an Intlayer node is built on, so the node behaves like\n * its `value` (`${node}`, `node.toUpperCase()`, `'trim' in node`) while staying\n * a plain framework object.\n *\n * @param value - The node value; its type decides which members are served.\n * @param basePrototype - The prototype the node would have had, kept ahead of\n * the value's members (e.g. `Function.prototype` for a\n * callable node).\n * @returns The shared prototype to create the node with.\n */\nexport const getIntlayerNodePrototype = (\n value: unknown,\n basePrototype: object = Object.prototype\n): object => {\n // Primitives are keyed by type, so a leaf never boxes its value\n const valueType = typeof value;\n const valueKey =\n value === null || value === undefined\n ? null\n : valueType === 'object' || valueType === 'function'\n ? Object.getPrototypeOf(value)\n : valueType;\n\n let prototypes = prototypeCache.get(basePrototype);\n\n if (!prototypes) {\n prototypes = new Map();\n prototypeCache.set(basePrototype, prototypes);\n }\n\n let prototype = prototypes.get(valueKey);\n\n if (!prototype) {\n prototype = createIntlayerNodePrototype(\n basePrototype,\n valueKey === null ? null : Object.getPrototypeOf(Object(value))\n );\n prototypes.set(valueKey, prototype);\n }\n\n return prototype;\n};\n"],"mappings":";;;;;;AAOA,MAAM,iCAAiB,IAAI,IAAkC;;;;;;;;;;AAW7D,MAAM,+BACJ,eACA,mBAEA,OAAO,OACL,IAAI,MAAM,eAAe;CACvB,MAAM,QAAQ,UAAU,aAAwB;EAC9C,IACE,OAAO,aAAa,YACpB,aAAa,iBACb,YAAY,QAEZ,OAAO,QAAQ,IAAI,QAAQ,UAAU,QAAQ;EAG/C,MAAM,EAAE,UAAU;EAElB,IAAI,UAAU,QAAQ,UAAU,QAAW,OAAO;EAElD,MAAM,SAAS,OAAO,KAAK,CAAC,CAAC;EAE7B,OAAO,OAAO,WAAW,aAAa,OAAO,KAAK,KAAK,IAAI;CAC7D;CACA,MAAM,QAAQ,aACZ,YAAY,UACX,OAAO,aAAa,YACnB,aAAa,iBACb,mBAAmB,QACnB,YAAY;AAClB,CAAC,GACD;CACE,UAAU,EACR,QAAuB;EACrB,OAAO,OAAO,KAAK,SAAS,EAAE;CAChC,EACF;CACA,SAAS,EACP,QAAuB;EACrB,OAAO,KAAK;CACd,EACF;EACC,OAAO,cAAc,EACpB,QAAuB;EACrB,OAAO,KAAK,SAAS;CACvB,EACF;AACF,CACF;;;;;;;;;;;;AAaF,MAAa,4BACX,OACA,gBAAwB,OAAO,cACpB;CAEX,MAAM,YAAY,OAAO;CACzB,MAAM,WACJ,UAAU,QAAQ,UAAU,SACxB,OACA,cAAc,YAAY,cAAc,aACtC,OAAO,eAAe,KAAK,IAC3B;CAER,IAAI,aAAa,eAAe,IAAI,aAAa;CAEjD,IAAI,CAAC,YAAY;EACf,6BAAa,IAAI,IAAI;EACrB,eAAe,IAAI,eAAe,UAAU;CAC9C;CAEA,IAAI,YAAY,WAAW,IAAI,QAAQ;CAEvC,IAAI,CAAC,WAAW;EACd,YAAY,4BACV,eACA,aAAa,OAAO,OAAO,OAAO,eAAe,OAAO,KAAK,CAAC,CAChE;EACA,WAAW,IAAI,UAAU,SAAS;CACpC;CAEA,OAAO;AACT"}
@@ -61,6 +61,24 @@ const getLocaleFromStorageClient = (options = localeStorageOptions) => {
61
61
  if (isValidLocale(value)) return value;
62
62
  } catch {}
63
63
  };
64
+ let isStoredLocaleCached = false;
65
+ let storedLocale;
66
+ /**
67
+ * Returns the locale persisted in the browser storage, read with the default
68
+ * options.
69
+ *
70
+ * The read is cached until the next `setLocaleInStorageClient`, so callers can
71
+ * use it on every render without reading the cookie each time. On the server
72
+ * nothing is cached: module state is shared by every request.
73
+ */
74
+ const getCachedLocaleFromStorageClient = () => {
75
+ if (typeof window === "undefined") return getLocaleFromStorageClient(localeStorageOptions);
76
+ if (!isStoredLocaleCached) {
77
+ storedLocale = getLocaleFromStorageClient(localeStorageOptions);
78
+ isStoredLocaleCached = true;
79
+ }
80
+ return storedLocale;
81
+ };
64
82
  /**
65
83
  * Stores the locale in browser storage mechanisms
66
84
  * (cookies, localStorage, sessionStorage).
@@ -68,6 +86,7 @@ const getLocaleFromStorageClient = (options = localeStorageOptions) => {
68
86
  */
69
87
  const setLocaleInStorageClient = (locale, options) => {
70
88
  if (options?.isCookieEnabled === false) return;
89
+ isStoredLocaleCached = false;
71
90
  if (!TREE_SHAKE_STORAGE_COOKIES && _intlayer_config_built.routing.storage.cookies) for (let i = 0; i < _intlayer_config_built.routing.storage.cookies.length; i++) {
72
91
  const { name, attributes } = _intlayer_config_built.routing.storage.cookies[i];
73
92
  try {
@@ -272,6 +291,7 @@ const LocaleStorage = (options) => ({
272
291
  exports.LocaleStorage = LocaleStorage;
273
292
  exports.LocaleStorageClient = LocaleStorageClient;
274
293
  exports.LocaleStorageServer = LocaleStorageServer;
294
+ exports.getCachedLocaleFromStorageClient = getCachedLocaleFromStorageClient;
275
295
  exports.getLocaleFromStorage = getLocaleFromStorage;
276
296
  exports.getLocaleFromStorageClient = getLocaleFromStorageClient;
277
297
  exports.getLocaleFromStorageServer = getLocaleFromStorageServer;