@intlayer/core 9.8.5 → 9.9.1

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 (76) hide show
  1. package/dist/cjs/deepTransformPlugins/getLocalizedContent.cjs +3 -1
  2. package/dist/cjs/deepTransformPlugins/getLocalizedContent.cjs.map +1 -1
  3. package/dist/cjs/deepTransformPlugins/getMultilingualDictionary.cjs +2 -1
  4. package/dist/cjs/deepTransformPlugins/getMultilingualDictionary.cjs.map +1 -1
  5. package/dist/cjs/dictionaryManipulator/dynamicDictionary.cjs +262 -0
  6. package/dist/cjs/dictionaryManipulator/dynamicDictionary.cjs.map +1 -0
  7. package/dist/cjs/dictionaryManipulator/getLocalizedMetadata.cjs +25 -0
  8. package/dist/cjs/dictionaryManipulator/getLocalizedMetadata.cjs.map +1 -0
  9. package/dist/cjs/dictionaryManipulator/index.cjs +27 -3
  10. package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs +3 -0
  11. package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs.map +1 -1
  12. package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs +6 -2
  13. package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs.map +1 -1
  14. package/dist/cjs/dictionaryManipulator/normalizeDictionary.cjs +2 -1
  15. package/dist/cjs/dictionaryManipulator/normalizeDictionary.cjs.map +1 -1
  16. package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs +80 -12
  17. package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs.map +1 -1
  18. package/dist/cjs/dictionaryManipulator/qualifiedDictionaryDeclaration.cjs +9 -3
  19. package/dist/cjs/dictionaryManipulator/qualifiedDictionaryDeclaration.cjs.map +1 -1
  20. package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs +38 -68
  21. package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs.map +1 -1
  22. package/dist/cjs/index.cjs +27 -3
  23. package/dist/cjs/interpreter/getContent/plugins.cjs.map +1 -1
  24. package/dist/cjs/interpreter/getDictionary.cjs +3 -0
  25. package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
  26. package/dist/cjs/interpreter/getDictionaryAsync.cjs +5 -19
  27. package/dist/cjs/interpreter/getDictionaryAsync.cjs.map +1 -1
  28. package/dist/esm/deepTransformPlugins/getLocalizedContent.mjs +3 -1
  29. package/dist/esm/deepTransformPlugins/getLocalizedContent.mjs.map +1 -1
  30. package/dist/esm/deepTransformPlugins/getMultilingualDictionary.mjs +2 -1
  31. package/dist/esm/deepTransformPlugins/getMultilingualDictionary.mjs.map +1 -1
  32. package/dist/esm/dictionaryManipulator/dynamicDictionary.mjs +252 -0
  33. package/dist/esm/dictionaryManipulator/dynamicDictionary.mjs.map +1 -0
  34. package/dist/esm/dictionaryManipulator/getLocalizedMetadata.mjs +22 -0
  35. package/dist/esm/dictionaryManipulator/getLocalizedMetadata.mjs.map +1 -0
  36. package/dist/esm/dictionaryManipulator/index.mjs +6 -4
  37. package/dist/esm/dictionaryManipulator/mergeDictionaries.mjs +3 -0
  38. package/dist/esm/dictionaryManipulator/mergeDictionaries.mjs.map +1 -1
  39. package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs +6 -2
  40. package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs.map +1 -1
  41. package/dist/esm/dictionaryManipulator/normalizeDictionary.mjs +2 -1
  42. package/dist/esm/dictionaryManipulator/normalizeDictionary.mjs.map +1 -1
  43. package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs +75 -13
  44. package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs.map +1 -1
  45. package/dist/esm/dictionaryManipulator/qualifiedDictionaryDeclaration.mjs +10 -5
  46. package/dist/esm/dictionaryManipulator/qualifiedDictionaryDeclaration.mjs.map +1 -1
  47. package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs +33 -68
  48. package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs.map +1 -1
  49. package/dist/esm/index.mjs +6 -4
  50. package/dist/esm/interpreter/getContent/plugins.mjs.map +1 -1
  51. package/dist/esm/interpreter/getDictionary.mjs +3 -0
  52. package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
  53. package/dist/esm/interpreter/getDictionaryAsync.mjs +5 -19
  54. package/dist/esm/interpreter/getDictionaryAsync.mjs.map +1 -1
  55. package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts +2 -1
  56. package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts +2 -1
  57. package/dist/types/deepTransformPlugins/getFilteredLocalesContent.d.ts +2 -1
  58. package/dist/types/deepTransformPlugins/getLocalizedContent.d.ts.map +1 -1
  59. package/dist/types/dictionaryManipulator/dynamicDictionary.d.ts +159 -0
  60. package/dist/types/dictionaryManipulator/dynamicDictionary.d.ts.map +1 -0
  61. package/dist/types/dictionaryManipulator/getLocalizedMetadata.d.ts +14 -0
  62. package/dist/types/dictionaryManipulator/getLocalizedMetadata.d.ts.map +1 -0
  63. package/dist/types/dictionaryManipulator/index.d.ts +6 -4
  64. package/dist/types/dictionaryManipulator/normalizeDictionary.d.ts.map +1 -1
  65. package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts +51 -5
  66. package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts.map +1 -1
  67. package/dist/types/dictionaryManipulator/qualifiedDictionaryDeclaration.d.ts +7 -2
  68. package/dist/types/dictionaryManipulator/qualifiedDictionaryDeclaration.d.ts.map +1 -1
  69. package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts +34 -54
  70. package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts.map +1 -1
  71. package/dist/types/index.d.ts +6 -4
  72. package/dist/types/interpreter/getContent/plugins.d.ts +2 -1
  73. package/dist/types/interpreter/getContent/plugins.d.ts.map +1 -1
  74. package/dist/types/interpreter/getDictionary.d.ts.map +1 -1
  75. package/dist/types/interpreter/getDictionaryAsync.d.ts.map +1 -1
  76. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"mergeQualifiedDictionaries.cjs","names":["getDictionaryQualifierTypes","QUALIFIER_ORDER","mergeDictionaries","getAppLogger","getDictionaryCompositeIds","colorizeKey","DEFAULT_VARIANT_ID"],"sources":["../../../src/dictionaryManipulator/mergeQualifiedDictionaries.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport type {\n Dictionary,\n DictionaryQualifierType,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport { mergeDictionaries } from './mergeDictionaries';\nimport {\n COMPOSITE_ID_SEPARATOR,\n DEFAULT_VARIANT_ID,\n} from './qualifiedDictionary';\nimport {\n getDictionaryCompositeIds,\n getDictionaryQualifierTypes,\n QUALIFIER_ORDER,\n} from './qualifiedDictionaryDeclaration';\n\n/**\n * Merges sibling dictionaries sharing the same key, honouring qualifiers.\n *\n * - No dictionary declares a qualifier → behaves exactly like\n * `mergeDictionaries` (single merged dictionary).\n * - At least one dictionary declares a qualifier → the group's dimension set is\n * the union of every declared dimension (in canonical order\n * `variant → item`). Dictionaries are grouped by their composite id\n * (one segment per dimension), merged within each group (locale completion /\n * priority overrides preserved), and a `QualifiedDictionaryGroup` is returned.\n * Unqualified siblings act as shared base content merged into every entry —\n * and, on a variant-only key, also materialize the `default` entry when no\n * declaration claims it. Every other variant entry then inherits from that\n * `default` entry, so a variant only declares the fields it overrides.\n *\n * Every qualified entry must declare ALL dimensions of the group; an entry that\n * declares only a subset is ambiguous and is rejected with an error log.\n */\nexport const mergeQualifiedDictionaries = (\n dictionaries: Dictionary[]\n): Dictionary | QualifiedDictionaryGroup => {\n const perDictionaryTypes = dictionaries.map(getDictionaryQualifierTypes);\n\n const declaredDimensions = new Set<DictionaryQualifierType>();\n for (const types of perDictionaryTypes) {\n for (const type of types) declaredDimensions.add(type);\n }\n\n // Canonical order, restricted to the dimensions actually declared.\n const groupQualifierTypes = QUALIFIER_ORDER.filter((qualifierType) =>\n declaredDimensions.has(qualifierType)\n );\n\n if (groupQualifierTypes.length === 0) {\n return mergeDictionaries(dictionaries);\n }\n\n const appLogger = getAppLogger({ log });\n\n const baseDictionaries: Dictionary[] = [];\n const entriesDictionaries = new Map<string, Dictionary[]>();\n\n dictionaries.forEach((dictionary, index) => {\n if (perDictionaryTypes[index]?.length === 0) {\n baseDictionaries.push(dictionary);\n return;\n }\n\n // A dictionary may map to several composite ids (array variant fan-out):\n // its content is registered under every id it lists.\n const compositeIds = getDictionaryCompositeIds(\n dictionary,\n groupQualifierTypes\n );\n\n if (compositeIds === undefined) {\n appLogger(\n `Dictionary ${colorizeKey(dictionary.key)} declares (${perDictionaryTypes[index].join(', ')}) but the key's dimensions are (${groupQualifierTypes.join(', ')}); every entry must declare all of them. Entry ignored${dictionary.filePath ? ` - ${dictionary.filePath}` : ''}.`,\n { level: 'error' }\n );\n return;\n }\n\n for (const compositeId of compositeIds) {\n const existingEntries = entriesDictionaries.get(compositeId) ?? [];\n existingEntries.push(dictionary);\n entriesDictionaries.set(compositeId, existingEntries);\n }\n });\n\n // Unqualified siblings are the key's base content. On a variant key they also\n // materialize the `default` entry when no declaration claims it, so the key\n // still resolves when no variant is selected — and so variants that declare\n // no entry of their own can fall back to it. Registering an empty entry list\n // is enough: the merge loop below appends the base dictionaries to it.\n //\n // Composite (variant × item) keys are excluded: base content carries no item\n // index, so it cannot be placed on the collection axis.\n const isVariantOnlyGroup =\n groupQualifierTypes.length === 1 && groupQualifierTypes[0] === 'variant';\n\n if (\n isVariantOnlyGroup &&\n baseDictionaries.length > 0 &&\n !entriesDictionaries.has(DEFAULT_VARIANT_ID)\n ) {\n entriesDictionaries.set(DEFAULT_VARIANT_ID, []);\n }\n\n // `content` maps each composite id to its resolved content node directly; the\n // qualifier coordinates live in the key, not in a per-entry wrapper. For an\n // object variant the variant segment is the canonical serialization of the\n // object, so it fully identifies the entry — no side-map is needed.\n const content: Record<string, unknown> = {};\n\n let importMode: Dictionary['importMode'];\n\n const variantIndex = groupQualifierTypes.indexOf('variant');\n\n /**\n * The id of the entry a composite id inherits from — itself with its variant\n * segment swapped for `default` (`'promo/2'` → `'default/2'`). `undefined`\n * for the default entries themselves and for keys with no variant dimension.\n */\n const getInheritedEntryId = (compositeId: string): string | undefined => {\n if (variantIndex === -1) return undefined;\n\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n if (segments[variantIndex] === DEFAULT_VARIANT_ID) return undefined;\n\n segments[variantIndex] = DEFAULT_VARIANT_ID;\n return segments.join(COMPOSITE_ID_SEPARATOR);\n };\n\n for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {\n // Precedence, highest first: the entry's own declarations, then the\n // `default` variant it inherits from, then the unqualified siblings shared\n // by the whole key (mergeDictionaries prefers the first occurrence).\n //\n // Inheriting from `default` is what makes a variant declaration partial: it\n // only has to declare the fields whose wording actually differs, and every\n // other field is completed from the default entry.\n const inheritedEntryId = getInheritedEntryId(compositeId);\n const inheritedDictionaries = inheritedEntryId\n ? (entriesDictionaries.get(inheritedEntryId) ?? [])\n : [];\n\n const mergedEntry = mergeDictionaries([\n ...qualifiedDictionaries,\n ...inheritedDictionaries,\n ...baseDictionaries,\n ]);\n\n content[compositeId] = mergedEntry.content;\n\n const [firstQualified] = qualifiedDictionaries;\n\n importMode ??= firstQualified?.importMode;\n }\n\n const localIds = Array.from(\n new Set(\n dictionaries\n .filter((dictionary) => dictionary.localId)\n .map((dictionary) => dictionary.localId!)\n )\n );\n\n return {\n key: dictionaries[0]!.key,\n qualifierTypes: groupQualifierTypes,\n content,\n ...(importMode !== undefined && { importMode }),\n localIds,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,8BACX,iBAC0C;CAC1C,MAAM,qBAAqB,aAAa,IAAIA,wFAA2B;CAEvE,MAAM,qCAAqB,IAAI,IAA6B;CAC5D,KAAK,MAAM,SAA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,SAAS,QAA2B;CAC7C;CAEA,KAAK,MAAM,CAAC,aAAa,0BAA0B,qBAAqB;EAQtE,MAAM,mBAAmB,oBAAoB,WAAW;EACxD,MAAM,wBAAwB,mBACzB,oBAAoB,IAAI,gBAAgB,KAAK,CAAC,IAC/C,CAAC;EAQL,QAAQ,eANYJ,kEAAkB;GACpC,GAAG;GACH,GAAG;GACH,GAAG;EACL,CAEiC,CAAC,CAAC;EAEnC,MAAM,CAAC,kBAAkB;EAEzB,eAAe,gBAAgB;CACjC;CAEA,MAAM,WAAW,MAAM,KACrB,IAAI,IACF,aACG,QAAQ,eAAe,WAAW,OAAO,CAAC,CAC1C,KAAK,eAAe,WAAW,OAAQ,CAC5C,CACF;CAEA,OAAO;EACL,KAAK,aAAa,EAAE,CAAE;EACtB,gBAAgB;EAChB;EACA,GAAI,eAAe,UAAa,EAAE,WAAW;EAC7C;CACF;AACF"}
1
+ {"version":3,"file":"mergeQualifiedDictionaries.cjs","names":["getDictionaryQualifierTypes","QUALIFIER_ORDER","mergeDictionaries","getAppLogger","getDictionaryCompositeIds","colorizeKey","DEFAULT_VARIANT_ID"],"sources":["../../../src/dictionaryManipulator/mergeQualifiedDictionaries.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport type {\n Dictionary,\n DictionaryQualifierType,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport { mergeDictionaries } from './mergeDictionaries';\nimport {\n COMPOSITE_ID_SEPARATOR,\n DEFAULT_VARIANT_ID,\n} from './qualifiedDictionary';\nimport {\n getDictionaryCompositeIds,\n getDictionaryQualifierTypes,\n QUALIFIER_ORDER,\n} from './qualifiedDictionaryDeclaration';\n\n/**\n * Merges sibling dictionaries sharing the same key, honouring qualifiers.\n *\n * - No dictionary declares a qualifier → behaves exactly like\n * `mergeDictionaries` (single merged dictionary).\n * - At least one dictionary declares a qualifier → the group's dimension set is\n * the union of every declared dimension (in canonical order\n * `variant → item`). Dictionaries are grouped by their composite id\n * (one segment per dimension), merged within each group (locale completion /\n * priority overrides preserved), and a `QualifiedDictionaryGroup` is returned.\n * Unqualified siblings act as shared base content merged into every entry —\n * and, on a variant-only key, also materialize the `default` entry when no\n * declaration claims it. Every other variant entry then inherits from that\n * `default` entry, so a variant only declares the fields it overrides.\n *\n * Every qualified entry must declare ALL dimensions of the group; an entry that\n * declares only a subset is ambiguous and is rejected with an error log.\n */\nexport const mergeQualifiedDictionaries = (\n dictionaries: Dictionary[]\n): Dictionary | QualifiedDictionaryGroup => {\n const perDictionaryTypes = dictionaries.map(getDictionaryQualifierTypes);\n\n const declaredDimensions = new Set<DictionaryQualifierType>();\n for (const types of perDictionaryTypes) {\n for (const type of types) declaredDimensions.add(type);\n }\n\n // Canonical order, restricted to the dimensions actually declared.\n const groupQualifierTypes = QUALIFIER_ORDER.filter((qualifierType) =>\n declaredDimensions.has(qualifierType)\n );\n\n if (groupQualifierTypes.length === 0) {\n return mergeDictionaries(dictionaries);\n }\n\n const appLogger = getAppLogger({ log });\n\n const baseDictionaries: Dictionary[] = [];\n const entriesDictionaries = new Map<string, Dictionary[]>();\n\n dictionaries.forEach((dictionary, index) => {\n if (perDictionaryTypes[index]?.length === 0) {\n baseDictionaries.push(dictionary);\n return;\n }\n\n // A dictionary may map to several composite ids (array variant fan-out):\n // its content is registered under every id it lists.\n const compositeIds = getDictionaryCompositeIds(\n dictionary,\n groupQualifierTypes\n );\n\n if (compositeIds === undefined) {\n appLogger(\n `Dictionary ${colorizeKey(dictionary.key)} declares (${perDictionaryTypes[index].join(', ')}) but the key's dimensions are (${groupQualifierTypes.join(', ')}); every entry must declare all of them. Entry ignored${dictionary.filePath ? ` - ${dictionary.filePath}` : ''}.`,\n { level: 'error' }\n );\n return;\n }\n\n for (const compositeId of compositeIds) {\n const existingEntries = entriesDictionaries.get(compositeId) ?? [];\n existingEntries.push(dictionary);\n entriesDictionaries.set(compositeId, existingEntries);\n }\n });\n\n // Unqualified siblings are the key's base content. On a variant key they also\n // materialize the `default` entry when no declaration claims it, so the key\n // still resolves when no variant is selected — and so variants that declare\n // no entry of their own can fall back to it. Registering an empty entry list\n // is enough: the merge loop below appends the base dictionaries to it.\n //\n // Composite (variant × item) keys are excluded: base content carries no item\n // index, so it cannot be placed on the collection axis.\n const isVariantOnlyGroup =\n groupQualifierTypes.length === 1 && groupQualifierTypes[0] === 'variant';\n\n if (\n isVariantOnlyGroup &&\n baseDictionaries.length > 0 &&\n !entriesDictionaries.has(DEFAULT_VARIANT_ID)\n ) {\n entriesDictionaries.set(DEFAULT_VARIANT_ID, []);\n }\n\n // `content` maps each composite id to its resolved content node directly; the\n // qualifier coordinates live in the key, not in a per-entry wrapper. For an\n // object variant the variant segment is the canonical serialization of the\n // object, so it fully identifies the entry — no side-map is needed.\n const content: Record<string, unknown> = {};\n const metadata: Record<string, unknown> = {};\n\n let importMode: Dictionary['importMode'];\n\n const variantIndex = groupQualifierTypes.indexOf('variant');\n\n /**\n * The id of the entry a composite id inherits from — itself with its variant\n * segment swapped for `default` (`'promo/2'` → `'default/2'`). `undefined`\n * for the default entries themselves and for keys with no variant dimension.\n */\n const getInheritedEntryId = (compositeId: string): string | undefined => {\n if (variantIndex === -1) return undefined;\n\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n if (segments[variantIndex] === DEFAULT_VARIANT_ID) return undefined;\n\n segments[variantIndex] = DEFAULT_VARIANT_ID;\n return segments.join(COMPOSITE_ID_SEPARATOR);\n };\n\n for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {\n // Precedence, highest first: the entry's own declarations, then the\n // `default` variant it inherits from, then the unqualified siblings shared\n // by the whole key (mergeDictionaries prefers the first occurrence).\n //\n // Inheriting from `default` is what makes a variant declaration partial: it\n // only has to declare the fields whose wording actually differs, and every\n // other field is completed from the default entry.\n const inheritedEntryId = getInheritedEntryId(compositeId);\n const inheritedDictionaries = inheritedEntryId\n ? (entriesDictionaries.get(inheritedEntryId) ?? [])\n : [];\n\n const mergedEntry = mergeDictionaries([\n ...qualifiedDictionaries,\n ...inheritedDictionaries,\n ...baseDictionaries,\n ]);\n\n content[compositeId] = mergedEntry.content;\n\n if (mergedEntry.metadata !== undefined) {\n metadata[compositeId] = mergedEntry.metadata;\n }\n\n const [firstQualified] = qualifiedDictionaries;\n\n importMode ??= firstQualified?.importMode;\n }\n\n const localIds = Array.from(\n new Set(\n dictionaries\n .filter((dictionary) => dictionary.localId)\n .map((dictionary) => dictionary.localId!)\n )\n );\n\n return {\n key: dictionaries[0]!.key,\n qualifierTypes: groupQualifierTypes,\n content,\n ...(Object.keys(metadata).length > 0 && { metadata }),\n ...(importMode !== undefined && { importMode }),\n localIds,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,8BACX,iBAC0C;CAC1C,MAAM,qBAAqB,aAAa,IAAIA,wFAA2B;CAEvE,MAAM,qCAAqB,IAAI,IAA6B;CAC5D,KAAK,MAAM,SAAS,oBAClB,KAAK,MAAM,QAAQ,OAAO,mBAAmB,IAAI,IAAI;CAIvD,MAAM,sBAAsBC,6EAAgB,QAAQ,kBAClD,mBAAmB,IAAI,aAAa,CACtC;CAEA,IAAI,oBAAoB,WAAW,GACjC,OAAOC,kEAAkB,YAAY;CAGvC,MAAM,gBAAYC,sCAAa,EAAE,gCAAI,CAAC;CAEtC,MAAM,mBAAiC,CAAC;CACxC,MAAM,sCAAsB,IAAI,IAA0B;CAE1D,aAAa,SAAS,YAAY,UAAU;EAC1C,IAAI,mBAAmB,MAAM,EAAE,WAAW,GAAG;GAC3C,iBAAiB,KAAK,UAAU;GAChC;EACF;EAIA,MAAM,eAAeC,uFACnB,YACA,mBACF;EAEA,IAAI,iBAAiB,QAAW;GAC9B,UACE,kBAAcC,qCAAY,WAAW,GAAG,EAAE,aAAa,mBAAmB,MAAM,CAAC,KAAK,IAAI,EAAE,kCAAkC,oBAAoB,KAAK,IAAI,EAAE,wDAAwD,WAAW,WAAW,MAA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Q,CAAC,CAAC,SAAS,KAAK,EAAE,SAAS;EACnD,GAAI,eAAe,UAAa,EAAE,WAAW;EAC7C;CACF;AACF"}
@@ -10,7 +10,8 @@ const normalizeDictionary = (dictionary, configuration) => {
10
10
  if (dictionary.locale) return {
11
11
  ...dictionary,
12
12
  locale: void 0,
13
- content: require_transpiler_translation_translation.t({ [dictionary.locale]: dictionary.content })
13
+ content: require_transpiler_translation_translation.t({ [dictionary.locale]: dictionary.content }),
14
+ ...dictionary.metadata !== void 0 && { metadata: require_transpiler_translation_translation.t({ [dictionary.locale]: dictionary.metadata }) }
14
15
  };
15
16
  const perLocaleContent = locales.reduce((acc, locale) => {
16
17
  acc[locale] = require_deepTransformPlugins_getLocalizedContent.getPerLocaleDictionary(parsedDictionary, locale).content;
@@ -1 +1 @@
1
- {"version":3,"file":"normalizeDictionary.cjs","names":["t","getPerLocaleDictionary","orderDictionaries"],"sources":["../../../src/dictionaryManipulator/normalizeDictionary.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getPerLocaleDictionary } from '../deepTransformPlugins';\nimport { t } from '../transpiler/translation';\nimport { orderDictionaries } from './orderDictionaries';\n\nexport const normalizeDictionary = (\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Dictionary => {\n const { locales } = configuration.internationalization;\n\n const parsedDictionary = JSON.parse(JSON.stringify(dictionary));\n\n // If the dictionary is a per-locale dictionary, transform it to a partial multilingual dictionary\n if (dictionary.locale) {\n return {\n ...dictionary,\n locale: undefined,\n content: t({\n [dictionary.locale]: dictionary.content,\n }),\n };\n }\n\n const perLocaleContent = locales.reduce(\n (acc, locale) => {\n const perLocaleDictionary = getPerLocaleDictionary(\n parsedDictionary,\n locale\n );\n\n acc[locale] = perLocaleDictionary.content;\n return acc;\n },\n {} as Record<Locale, Dictionary['content']>\n );\n\n return {\n ...dictionary,\n content: t(perLocaleContent),\n };\n};\n\nexport const normalizeDictionaries = (\n dictionaries: Dictionary[],\n configuration: IntlayerConfig\n): Dictionary[] => {\n const orderedDictionaries = orderDictionaries(dictionaries, configuration);\n\n const structuredDictionaries = orderedDictionaries.map((dictionary) =>\n normalizeDictionary(dictionary, configuration)\n );\n\n return structuredDictionaries;\n};\n"],"mappings":";;;;;;AAOA,MAAa,uBACX,YACA,kBACe;CACf,MAAM,EAAE,YAAY,cAAc;CAElC,MAAM,mBAAmB,KAAK,MAAM,KAAK,UAAU,UAAU,CAAC;CAG9D,IAAI,WAAW,QACb,OAAO;EACL,GAAG;EACH,QAAQ;EACR,SAASA,6CAAE,GACR,WAAW,SAAS,WAAW,QAClC,CAAC;CACH;CAGF,MAAM,mBAAmB,QAAQ,QAC9B,KAAK,WAAW;EAMf,IAAI,UALwBC,wEAC1B,kBACA,MAG8B,CAAC,CAAC;EAClC,OAAO;CACT,GACA,CAAC,CACH;CAEA,OAAO;EACL,GAAG;EACH,SAASD,6CAAE,gBAAgB;CAC7B;AACF;AAEA,MAAa,yBACX,cACA,kBACiB;CAOjB,OAN4BE,kEAAkB,cAAc,aAEX,CAAC,CAAC,KAAK,eACtD,oBAAoB,YAAY,aAAa,CAGnB;AAC9B"}
1
+ {"version":3,"file":"normalizeDictionary.cjs","names":["t","getPerLocaleDictionary","orderDictionaries"],"sources":["../../../src/dictionaryManipulator/normalizeDictionary.ts"],"sourcesContent":["import type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { getPerLocaleDictionary } from '../deepTransformPlugins';\nimport { t } from '../transpiler/translation';\nimport { orderDictionaries } from './orderDictionaries';\n\nexport const normalizeDictionary = (\n dictionary: Dictionary,\n configuration: IntlayerConfig\n): Dictionary => {\n const { locales } = configuration.internationalization;\n\n const parsedDictionary = JSON.parse(JSON.stringify(dictionary));\n\n // If the dictionary is a per-locale dictionary, transform it to a partial multilingual dictionary\n if (dictionary.locale) {\n return {\n ...dictionary,\n locale: undefined,\n content: t({\n [dictionary.locale]: dictionary.content,\n }),\n // Merged with the other locales' metadata, like the content\n ...(dictionary.metadata !== undefined && {\n metadata: t({ [dictionary.locale]: dictionary.metadata }),\n }),\n };\n }\n\n const perLocaleContent = locales.reduce(\n (acc, locale) => {\n const perLocaleDictionary = getPerLocaleDictionary(\n parsedDictionary,\n locale\n );\n\n acc[locale] = perLocaleDictionary.content;\n return acc;\n },\n {} as Record<Locale, Dictionary['content']>\n );\n\n return {\n ...dictionary,\n content: t(perLocaleContent),\n };\n};\n\nexport const normalizeDictionaries = (\n dictionaries: Dictionary[],\n configuration: IntlayerConfig\n): Dictionary[] => {\n const orderedDictionaries = orderDictionaries(dictionaries, configuration);\n\n const structuredDictionaries = orderedDictionaries.map((dictionary) =>\n normalizeDictionary(dictionary, configuration)\n );\n\n return structuredDictionaries;\n};\n"],"mappings":";;;;;;AAOA,MAAa,uBACX,YACA,kBACe;CACf,MAAM,EAAE,YAAY,cAAc;CAElC,MAAM,mBAAmB,KAAK,MAAM,KAAK,UAAU,UAAU,CAAC;CAG9D,IAAI,WAAW,QACb,OAAO;EACL,GAAG;EACH,QAAQ;EACR,SAASA,6CAAE,GACR,WAAW,SAAS,WAAW,QAClC,CAAC;EAED,GAAI,WAAW,aAAa,UAAa,EACvC,UAAUA,6CAAE,GAAG,WAAW,SAAS,WAAW,SAAS,CAAC,EAC1D;CACF;CAGF,MAAM,mBAAmB,QAAQ,QAC9B,KAAK,WAAW;EAMf,IAAI,UALwBC,wEAC1B,kBACA,MAG8B,CAAC,CAAC;EAClC,OAAO;CACT,GACA,CAAC,CACH;CAEA,OAAO;EACL,GAAG;EACH,SAASD,6CAAE,gBAAgB;CAC7B;AACF;AAEA,MAAa,yBACX,cACA,kBACiB;CAOjB,OAN4BE,kEAAkB,cAAc,aAEX,CAAC,CAAC,KAAK,eACtD,oBAAoB,YAAY,aAAa,CAGnB;AAC9B"}
@@ -54,6 +54,43 @@ const serializeVariant = (variant) => {
54
54
  if (typeof variant === "string") return encodeSegmentText(variant, SEGMENT_UNSAFE_CHARS);
55
55
  return Object.keys(variant).sort().map((field) => `${encodeSegmentText(field, COMPONENT_UNSAFE_CHARS)}=${encodeSegmentText(String(variant[field]), COMPONENT_UNSAFE_CHARS)}`).join("&");
56
56
  };
57
+ /** Reverses `encodeSegmentText`: decodes the `%XXXX` runs and the `%` stand-in. */
58
+ const decodeSegmentText = (segment) => segment === "%" ? "" : segment.replace(/%([0-9A-F]{4})/g, (_match, charCode) => String.fromCharCode(Number.parseInt(charCode, 16)));
59
+ /**
60
+ * Normalizes a raw item id: a string holding a number's exact canonical form
61
+ * becomes that number (`'2'` → `2`), anything else stays a string id
62
+ * (`'007'`, `'65f1c0a2'`, `'Infinity'`).
63
+ *
64
+ * @param rawItem - The item id as text (a composite id segment, a form input…).
65
+ */
66
+ const parseItemId = (rawItem) => {
67
+ const numericItem = Number(rawItem);
68
+ return rawItem !== "" && Number.isFinite(numericItem) && String(numericItem) === rawItem ? numericItem : rawItem;
69
+ };
70
+ /**
71
+ * Canonical serialization of an item id — the item segment of a composite id,
72
+ * the chunk directory name in dynamic mode, and the runtime matching key.
73
+ *
74
+ * A number and its digits serialize identically (`2` and `'2'` → `'2'`).
75
+ * Characters unsafe in file paths or generated code are percent-encoded like
76
+ * variant names, so database ids (hex, UUID, nanoid…) are kept verbatim.
77
+ */
78
+ const serializeItem = (item) => encodeSegmentText(String(item), SEGMENT_UNSAFE_CHARS);
79
+ /** Decodes the item segment of a composite id back into its item id. */
80
+ const parseItemSegment = (segment) => parseItemId(decodeSegmentText(segment));
81
+ /**
82
+ * Collection order of two item ids: numeric ids by value first, then string
83
+ * ids by UTF-16 code unit (locale-independent, so every build agrees).
84
+ */
85
+ const compareItemIds = (leftItem, rightItem) => {
86
+ if (typeof leftItem === "number" && typeof rightItem === "number") return leftItem - rightItem;
87
+ if (typeof leftItem === "number") return -1;
88
+ if (typeof rightItem === "number") return 1;
89
+ if (leftItem === rightItem) return 0;
90
+ return leftItem < rightItem ? -1 : 1;
91
+ };
92
+ /** Collection order of two serialized item segments (see {@link compareItemIds}). */
93
+ const compareItemSegments = (leftSegment, rightSegment) => compareItemIds(parseItemSegment(leftSegment), parseItemSegment(rightSegment));
57
94
  /**
58
95
  * Serializes the variant coordinate of a selector into the ordered list of
59
96
  * candidate ids to try, so a single value and a preference chain share one code
@@ -102,7 +139,7 @@ const compositeIdMatchesSelector = (compositeId, qualifierTypes, selector, effec
102
139
  const segments = compositeId.split("/");
103
140
  return qualifierTypes.every((qualifierType, index) => {
104
141
  if (qualifierType === "variant") return segments[index] === effectiveVariantId;
105
- return selector?.item === void 0 || segments[index] === String(selector.item);
142
+ return selector?.item === void 0 || segments[index] === serializeItem(selector.item);
106
143
  });
107
144
  };
108
145
  /**
@@ -120,7 +157,8 @@ const isQualifiedDictionaryGroup = (value) => typeof value === "object" && value
120
157
  * `{ key, content, variant?, item? }` shape, even though the stored format no
121
158
  * longer duplicates those fields per entry. The `variant` coordinate stays in
122
159
  * its serialized (encoded) form, e.g. `'id=abc&userId=123'` — matching happens
123
- * on the composite id segments, never on this reconstructed field.
160
+ * on the composite id segments, never on this reconstructed field. The `item`
161
+ * coordinate is decoded back to its id (`2`, `'65f1c0a2'`).
124
162
  */
125
163
  const reconstructQualifiedEntry = (group, compositeId) => {
126
164
  const segments = compositeId.split("/");
@@ -128,9 +166,11 @@ const reconstructQualifiedEntry = (group, compositeId) => {
128
166
  key: group.key,
129
167
  content: group.content[compositeId]
130
168
  };
169
+ const entryMetadata = group.metadata?.[compositeId];
170
+ if (entryMetadata !== void 0) entry.metadata = entryMetadata;
131
171
  group.qualifierTypes.forEach((qualifierType, index) => {
132
172
  if (qualifierType === "variant") entry.variant = segments[index];
133
- else if (qualifierType === "item") entry.item = Number(segments[index]);
173
+ else if (qualifierType === "item") entry.item = parseItemSegment(segments[index] ?? "");
134
174
  });
135
175
  return entry;
136
176
  };
@@ -139,7 +179,8 @@ const reconstructQualifiedEntry = (group, compositeId) => {
139
179
  * across every declared dimension.
140
180
  *
141
181
  * - Plain dictionary → returned as-is (selector ignored)
142
- * - `item` declared but not selected → every matching entry ordered by index
182
+ * - `item` declared but not selected → every matching entry, in collection
183
+ * order (see `compareItemIds`)
143
184
  * - `item` selected → the matching entry or null
144
185
  * - `variant` defaults to the `default` entry when not selected, and falls back
145
186
  * to it when the selected variant declares no entry of its own; an object
@@ -151,14 +192,34 @@ const reconstructQualifiedEntry = (group, compositeId) => {
151
192
  */
152
193
  const resolveQualifiedDictionary = (dictionaryOrGroup, selector) => {
153
194
  if (!isQualifiedDictionaryGroup(dictionaryOrGroup)) return dictionaryOrGroup;
154
- const { qualifierTypes, content } = dictionaryOrGroup;
195
+ const { itemAxisOpen, matchedIds } = matchQualifiedEntryIds(Object.keys(dictionaryOrGroup.content), dictionaryOrGroup.qualifierTypes, selector);
196
+ const matchedEntries = matchedIds.map((compositeId) => reconstructQualifiedEntry(dictionaryOrGroup, compositeId));
197
+ if (itemAxisOpen) return matchedEntries;
198
+ return matchedEntries[0] ?? null;
199
+ };
200
+ /**
201
+ * Selects the composite ids a selector targets across every declared
202
+ * dimension — the matching shared by the static resolver and the dynamic
203
+ * metadata index, so both modes resolve the same entries.
204
+ *
205
+ * @param compositeIds - Every composite id the key declares.
206
+ * @param qualifierTypes - The key's dimensions, in canonical order.
207
+ * @param selector - The selector splitting the dimensions.
208
+ */
209
+ const matchQualifiedEntryIds = (compositeIds, qualifierTypes, selector) => {
155
210
  const itemAxisOpen = qualifierTypes.includes("item") && selector?.item === void 0;
156
- const compositeIds = Object.keys(content);
157
211
  const variantIndex = qualifierTypes.indexOf("variant");
212
+ const itemIndex = qualifierTypes.indexOf("item");
158
213
  const effectiveVariantId = variantIndex === -1 ? DEFAULT_VARIANT_ID : resolveEffectiveVariantId(serializeVariantChain(selector?.variant), (variantId) => compositeIds.some((compositeId) => compositeId.split("/")[variantIndex] === variantId));
159
- const matchedEntries = compositeIds.filter((compositeId) => compositeIdMatchesSelector(compositeId, qualifierTypes, selector, effectiveVariantId)).map((compositeId) => reconstructQualifiedEntry(dictionaryOrGroup, compositeId));
160
- if (itemAxisOpen) return matchedEntries.sort((left, right) => (left.item ?? 0) - (right.item ?? 0));
161
- return matchedEntries[0] ?? null;
214
+ const matchedIds = compositeIds.filter((compositeId) => compositeIdMatchesSelector(compositeId, qualifierTypes, selector, effectiveVariantId));
215
+ if (itemAxisOpen) {
216
+ const getItemSegment = (compositeId) => compositeId.split("/")[itemIndex] ?? "";
217
+ matchedIds.sort((left, right) => compareItemSegments(getItemSegment(left), getItemSegment(right)));
218
+ }
219
+ return {
220
+ itemAxisOpen,
221
+ matchedIds
222
+ };
162
223
  };
163
224
  /**
164
225
  * Splits the second argument of `getIntlayer` / `getDictionary` into the
@@ -222,12 +283,13 @@ const resolveDictionaryArgument = (params) => {
222
283
  };
223
284
  };
224
285
  /**
225
- * Builds a stable string identity of a selector (excluding `locale`), suitable
226
- * for cache keys and memoization dependencies.
286
+ * Builds a stable string identity of a selector (excluding `locale`, and the
287
+ * dimensions left `undefined`), suitable for cache keys and memoization
288
+ * dependencies.
227
289
  */
228
290
  const getDictionarySelectorCacheKey = (selector) => {
229
291
  if (!selector) return "";
230
- return Object.keys(selector).filter((selectorKey) => selectorKey !== "locale").sort().map((selectorKey) => {
292
+ return Object.keys(selector).filter((selectorKey) => selectorKey !== "locale" && selector[selectorKey] !== void 0).sort().map((selectorKey) => {
231
293
  const value = selector[selectorKey];
232
294
  return `${selectorKey}:${selectorKey === "variant" ? serializeVariantChain(value).join(",") : String(value)}`;
233
295
  }).join("|");
@@ -235,14 +297,20 @@ const getDictionarySelectorCacheKey = (selector) => {
235
297
 
236
298
  exports.COMPOSITE_ID_SEPARATOR = COMPOSITE_ID_SEPARATOR;
237
299
  exports.DEFAULT_VARIANT_ID = DEFAULT_VARIANT_ID;
300
+ exports.compareItemIds = compareItemIds;
301
+ exports.compareItemSegments = compareItemSegments;
238
302
  exports.getDictionarySelectorCacheKey = getDictionarySelectorCacheKey;
239
303
  exports.isQualifiedDictionaryGroup = isQualifiedDictionaryGroup;
304
+ exports.matchQualifiedEntryIds = matchQualifiedEntryIds;
240
305
  exports.parseDictionarySelector = parseDictionarySelector;
306
+ exports.parseItemId = parseItemId;
307
+ exports.parseItemSegment = parseItemSegment;
241
308
  exports.reconstructQualifiedEntry = reconstructQualifiedEntry;
242
309
  exports.resolveDictionaryArgument = resolveDictionaryArgument;
243
310
  exports.resolveEffectiveVariantId = resolveEffectiveVariantId;
244
311
  exports.resolveProviderVariant = resolveProviderVariant;
245
312
  exports.resolveQualifiedDictionary = resolveQualifiedDictionary;
313
+ exports.serializeItem = serializeItem;
246
314
  exports.serializeVariant = serializeVariant;
247
315
  exports.serializeVariantChain = serializeVariantChain;
248
316
  //# sourceMappingURL=qualifiedDictionary.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"qualifiedDictionary.cjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n DictionaryVariantChain,\n DictionaryVariantValue,\n ProviderVariantBase,\n ProviderVariantMap,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Separator joining per-dimension ids into a composite entry id. Also used as\n * the chunk path separator in dynamic mode.\n */\nexport const COMPOSITE_ID_SEPARATOR = '/';\n\n/**\n * Identity of the implicit fallback variant. A selector that pins no variant\n * resolves to it, and a variant that declares no entry of its own falls back to\n * it — so a key only has to ship the entries that actually differ.\n */\nexport const DEFAULT_VARIANT_ID = 'default';\n\n/**\n * Characters kept verbatim in an encoded qualifier segment. Everything else is\n * percent-encoded so a segment can never contain the composite-id separator\n * (`/`), path-hostile characters (`\\` `:` `*` `?` `\"` `<` `>` `|`, control\n * chars), or characters that would break the generated loader modules (`'`).\n */\nconst SEGMENT_UNSAFE_CHARS = /[^A-Za-z0-9._&=-]/g;\n\n/**\n * Stricter set for the components of an object variant: also encodes `&` and\n * `=` so the `field=value&field=value` serialization stays unambiguous.\n */\nconst COMPONENT_UNSAFE_CHARS = /[^A-Za-z0-9._-]/g;\n\n/** Percent-encodes one UTF-16 code unit as a fixed-width `%XXXX` run. */\nconst percentEncodeChar = (char: string): string =>\n `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}`;\n\nconst encodeSegmentText = (raw: string, unsafeChars: RegExp): string => {\n // Bare '%' cannot be produced by encoding (every encoded run is %XXXX),\n // so it is a safe stand-in for the empty string.\n if (raw === '') return '%';\n\n const encoded = raw.replace(unsafeChars, percentEncodeChar);\n\n // '.' and '..' are path navigation on every filesystem — encode the dots.\n if (encoded === '.' || encoded === '..') {\n return encoded.replace(/\\./g, '%002E');\n }\n\n return encoded;\n};\n\n/**\n * Canonical serialization of a single variant value into its identity string —\n * the variant segment of a composite id, the chunk directory name in dynamic\n * mode, and the runtime matching key.\n *\n * - `undefined` → `'default'` (the implicit fallback variant)\n * - a string → the string itself (a named variant)\n * - an object → its sorted `key=value` pairs joined by `&`\n * (e.g. `{ userId: '123', id: 'abc' }` → `'id=abc&userId=123'`)\n *\n * Characters that are unsafe in file paths or generated code are\n * percent-encoded (fixed-width `%XXXX` runs, injective). Common names —\n * letters, digits, `-` `_` `.` — are left untouched. Both the declaration and\n * the selector go through this function, so encoding never affects matching.\n *\n * Two variants resolve to the same entry iff their serializations are equal, so\n * an object variant in a selector must equal the one declared on the dictionary.\n */\nexport const serializeVariant = (\n variant: DictionaryVariantValue | undefined\n): string => {\n if (variant === undefined) return DEFAULT_VARIANT_ID;\n if (typeof variant === 'string') {\n return encodeSegmentText(variant, SEGMENT_UNSAFE_CHARS);\n }\n\n return Object.keys(variant)\n .sort()\n .map(\n (field) =>\n `${encodeSegmentText(field, COMPONENT_UNSAFE_CHARS)}=${encodeSegmentText(String(variant[field]), COMPONENT_UNSAFE_CHARS)}`\n )\n .join('&');\n};\n\n/**\n * Serializes the variant coordinate of a selector into the ordered list of\n * candidate ids to try, so a single value and a preference chain share one code\n * path downstream.\n *\n * - `undefined` → `['default']`\n * - a single value → its one serialization\n * - a chain → one serialization per entry, order preserved\n *\n * An empty chain is treated as \"no variant pinned\" (`['default']`) rather than\n * as an unsatisfiable request.\n */\nexport const serializeVariantChain = (\n variant: DictionaryVariantChain | undefined\n): string[] => {\n if (!Array.isArray(variant)) {\n return [serializeVariant(variant as DictionaryVariantValue | undefined)];\n }\n\n if (variant.length === 0) return [DEFAULT_VARIANT_ID];\n\n return variant.map(serializeVariant);\n};\n\n/**\n * Resolves the variant id a selector actually targets among the ids a key\n * declares — the sparse-override fallback.\n *\n * Candidates are tried in order and the first one the key declares wins.\n * Otherwise the key falls back to its `default` entry, so a variant only has to\n * be declared where its wording differs. When the key declares no `default`\n * either, the first candidate is returned unchanged and the caller resolves to\n * `null` / `[]`.\n *\n * @param requestedVariantIds - The serialized ids the selector asks for, in\n * preference order (a single value is a 1-element\n * list).\n * @param isVariantIdDeclared - Whether the key declares an entry for an id.\n */\nexport const resolveEffectiveVariantId = (\n requestedVariantIds: string[],\n isVariantIdDeclared: (variantId: string) => boolean\n): string => {\n for (const requestedVariantId of requestedVariantIds) {\n if (isVariantIdDeclared(requestedVariantId)) return requestedVariantId;\n }\n\n return isVariantIdDeclared(DEFAULT_VARIANT_ID)\n ? DEFAULT_VARIANT_ID\n : (requestedVariantIds[0] ?? DEFAULT_VARIANT_ID);\n};\n\n/**\n * Tests whether a composite entry id matches a selector across every declared\n * dimension. Segments are compared in their encoded form (both the stored id\n * and the selector go through {@link serializeVariant}). The `item` dimension\n * matches any value when the selector does not provide one (open collection\n * axis); the `variant` dimension is compared against the already-resolved\n * effective id, so the fallback is applied consistently across dimensions.\n */\nconst compositeIdMatchesSelector = (\n compositeId: string,\n qualifierTypes: DictionaryQualifierType[],\n selector: DictionarySelector | undefined,\n effectiveVariantId: string\n): boolean => {\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n\n return qualifierTypes.every((qualifierType, index) => {\n if (qualifierType === 'variant') {\n return segments[index] === effectiveVariantId;\n }\n\n // qualifierType === 'item'\n return (\n selector?.item === undefined || segments[index] === String(selector.item)\n );\n });\n};\n\n/**\n * Type guard discriminating a `QualifiedDictionaryGroup` (merge output of a\n * qualified key) from a plain `Dictionary`. Both carry a `content` field; only\n * the group declares `qualifierTypes`, which is therefore the discriminator.\n */\nexport const isQualifiedDictionaryGroup = (\n value: unknown\n): value is QualifiedDictionaryGroup =>\n typeof value === 'object' &&\n value !== null &&\n 'qualifierTypes' in value &&\n Array.isArray((value as { qualifierTypes: unknown }).qualifierTypes) &&\n 'content' in value;\n\n/**\n * Reconstructs a resolvable {@link Dictionary} from a single entry of a\n * qualified group: the content node stored under its composite id, plus the\n * qualifier coordinates decoded from that id (`variant`, `item`).\n *\n * This keeps the resolver's transform code unchanged: it still sees a\n * `{ key, content, variant?, item? }` shape, even though the stored format no\n * longer duplicates those fields per entry. The `variant` coordinate stays in\n * its serialized (encoded) form, e.g. `'id=abc&userId=123'` — matching happens\n * on the composite id segments, never on this reconstructed field.\n */\nexport const reconstructQualifiedEntry = (\n group: QualifiedDictionaryGroup,\n compositeId: string\n): Dictionary => {\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n\n const entry = {\n key: group.key,\n content: group.content[compositeId],\n } as Dictionary;\n\n group.qualifierTypes.forEach((qualifierType, index) => {\n if (qualifierType === 'variant') {\n entry.variant = segments[index];\n } else if (qualifierType === 'item') {\n entry.item = Number(segments[index]);\n }\n });\n\n return entry;\n};\n\n/**\n * Resolves a dictionary (or qualified dictionary group) against a selector,\n * across every declared dimension.\n *\n * - Plain dictionary → returned as-is (selector ignored)\n * - `item` declared but not selected → every matching entry ordered by index\n * - `item` selected → the matching entry or null\n * - `variant` defaults to the `default` entry when not selected, and falls back\n * to it when the selected variant declares no entry of its own; an object\n * variant resolves only when the selector provides an equal object (or, again,\n * through the `default` fallback)\n *\n * Dimensions compose: e.g. a variant × item key with `{ variant: 'promo' }`\n * returns every promo item as an array; adding `{ item: 2 }` narrows to one.\n */\nexport const resolveQualifiedDictionary = (\n dictionaryOrGroup: Dictionary | QualifiedDictionaryGroup,\n selector?: DictionarySelector\n): Dictionary | Dictionary[] | null => {\n if (!isQualifiedDictionaryGroup(dictionaryOrGroup)) {\n return dictionaryOrGroup;\n }\n\n const { qualifierTypes, content } = dictionaryOrGroup;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n const compositeIds = Object.keys(content);\n const variantIndex = qualifierTypes.indexOf('variant');\n\n const effectiveVariantId =\n variantIndex === -1\n ? DEFAULT_VARIANT_ID\n : resolveEffectiveVariantId(\n serializeVariantChain(selector?.variant),\n (variantId) =>\n compositeIds.some(\n (compositeId) =>\n compositeId.split(COMPOSITE_ID_SEPARATOR)[variantIndex] ===\n variantId\n )\n );\n\n const matchedEntries = compositeIds\n .filter((compositeId) =>\n compositeIdMatchesSelector(\n compositeId,\n qualifierTypes,\n selector,\n effectiveVariantId\n )\n )\n .map((compositeId) =>\n reconstructQualifiedEntry(dictionaryOrGroup, compositeId)\n );\n\n if (itemAxisOpen) {\n return matchedEntries.sort(\n (left, right) => (left.item ?? 0) - (right.item ?? 0)\n );\n }\n\n return matchedEntries[0] ?? null;\n};\n\n/**\n * Splits the second argument of `getIntlayer` / `getDictionary` into the\n * effective locale and the selector object (if any).\n */\nexport const parseDictionarySelector = <L extends LocalesValues>(\n localeOrSelector?: L | DictionarySelector\n): { locale?: L; selector?: DictionarySelector } => {\n if (typeof localeOrSelector === 'object' && localeOrSelector !== null) {\n return {\n locale: localeOrSelector.locale as L | undefined,\n selector: localeOrSelector,\n };\n }\n\n return { locale: localeOrSelector as L | undefined };\n};\n\n/**\n * Resolves the variant a provider pins for one dictionary key.\n *\n * A string or a chain applies to every key as-is. A plain object is the per-key\n * map: the entry for `dictionaryKey` wins, falling back to the reserved\n * `default` entry, and `undefined` when neither is present (the key then\n * resolves to its own `default` variant, i.e. the behaviour without a provider\n * variant at all).\n *\n * A plain object is **always** the map here — never a structured variant value,\n * which is why a structured variant has to be nested (`{ default: { id } }`).\n *\n * @param providerVariant - The `variant` prop of the surrounding provider.\n * @param dictionaryKey - The key being read.\n */\nexport const resolveProviderVariant = (\n providerVariant: ProviderVariantBase | undefined,\n dictionaryKey: string\n): DictionaryVariantChain | undefined => {\n if (providerVariant === undefined) return undefined;\n\n if (typeof providerVariant === 'string' || Array.isArray(providerVariant)) {\n return providerVariant as DictionaryVariantChain;\n }\n\n const variantMap = providerVariant as ProviderVariantMap;\n\n return variantMap[dictionaryKey] ?? variantMap[DEFAULT_VARIANT_ID];\n};\n\n/**\n * Builds the effective second argument of a dictionary read by layering the\n * provider defaults under the call-site one — the single place the `locale` and\n * `variant` context defaults are applied, shared by every framework binding.\n *\n * Precedence, per dimension independently:\n * - a call-site selector always wins; `{ variant: 'x' }` **replaces** the\n * provider chain rather than extending it\n * - otherwise the provider value applies\n *\n * Returns a bare locale (not a selector object) whenever no variant is in play,\n * so the existing fast path — and the cache keys built from it — are unchanged\n * for projects that never use variants.\n */\nexport const resolveDictionaryArgument = (params: {\n localeOrSelector?: LocalesValues | DictionarySelector;\n contextLocale?: LocalesValues;\n contextVariant?: ProviderVariantBase;\n dictionaryKey: string;\n}): LocalesValues | DictionarySelector | undefined => {\n const { localeOrSelector, contextLocale, contextVariant, dictionaryKey } =\n params;\n\n const callSelector =\n typeof localeOrSelector === 'object' && localeOrSelector !== null\n ? localeOrSelector\n : undefined;\n\n const callLocale = callSelector\n ? callSelector.locale\n : (localeOrSelector as LocalesValues | undefined);\n\n // The context locale is typed as widely as the runtime allows, while a\n // selector narrows `locale` to the declared ones — the value is the same.\n const locale = (callLocale ?? contextLocale) as DictionarySelector['locale'];\n\n // A call-site variant is authoritative; the provider only fills the gap.\n const variant =\n callSelector?.variant ??\n resolveProviderVariant(contextVariant, dictionaryKey);\n\n if (variant === undefined) {\n // Nothing to add: keep the argument in its original shape so the identity\n // built from it stays byte-identical to the pre-variant behaviour.\n return callSelector\n ? { ...callSelector, locale }\n : (locale as LocalesValues | undefined);\n }\n\n return { ...callSelector, locale, variant };\n};\n\n/**\n * Builds a stable string identity of a selector (excluding `locale`), suitable\n * for cache keys and memoization dependencies.\n */\nexport const getDictionarySelectorCacheKey = (\n selector?: DictionarySelector\n): string => {\n if (!selector) return '';\n\n return Object.keys(selector)\n .filter((selectorKey) => selectorKey !== 'locale')\n .sort()\n .map((selectorKey) => {\n const value = selector[selectorKey as keyof DictionarySelector];\n const serialized =\n selectorKey === 'variant'\n ? serializeVariantChain(\n value as DictionaryVariantChain | undefined\n ).join(',')\n : String(value);\n return `${selectorKey}:${serialized}`;\n })\n .join('|');\n};\n"],"mappings":";;;;;;AAgBA,MAAa,yBAAyB;;;;;;AAOtC,MAAa,qBAAqB;;;;;;;AAQlC,MAAM,uBAAuB;;;;;AAM7B,MAAM,yBAAyB;;AAG/B,MAAM,qBAAqB,SACzB,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS,GAAG,GAAG;AAEnE,MAAM,qBAAqB,KAAa,gBAAgC;CAGtE,IAAI,QAAQ,IAAI,OAAO;CAEvB,MAAM,UAAU,IAAI,QAAQ,aAAa,iBAAiB;CAG1D,IAAI,YAAY,OAAO,YAAY,MACjC,OAAO,QAAQ,QAAQ,OAAO,OAAO;CAGvC,OAAO;AACT;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,oBACX,YACW;CACX,IAAI,YAAY,QAAW,OAAO;CAClC,IAAI,OAAO,YAAY,UACrB,OAAO,kBAAkB,SAAS,oBAAoB;CAGxD,OAAO,OAAO,KAAK,OAAO,CAAC,CACxB,KAAK,CAAC,CACN,KACE,UACC,GAAG,kBAAkB,OAAO,sBAAsB,EAAE,GAAG,kBAAkB,OAAO,QAAQ,MAAM,GAAG,sBAAsB,GAC3H,CAAC,CACA,KAAK,GAAG;AACb;;;;;;;;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AAO,KAAK,QAAQ,CAAC,CACzB,QAAQ,gBAAgB,gBAAgB,QAAQ,CAAC,CACjD,KAAK,CAAC,CACN,KAAK,gBAAgB;EACpB,MAAM,QAAQ,SAAS;EAOvB,OAAO,GAAG,YAAY,GALpB,gBAAgB,YACZ,sBACE,KACF,CAAC,CAAC,KAAK,GAAG,IACV,OAAO,KAAK;CAEpB,CAAC,CAAC,CACD,KAAK,GAAG;AACb"}
1
+ {"version":3,"file":"qualifiedDictionary.cjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionaryItemId,\n DictionaryQualifierType,\n DictionarySelector,\n DictionaryVariantChain,\n DictionaryVariantValue,\n ProviderVariantBase,\n ProviderVariantMap,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Separator joining per-dimension ids into a composite entry id. Also used as\n * the chunk path separator in dynamic mode.\n */\nexport const COMPOSITE_ID_SEPARATOR = '/';\n\n/**\n * Identity of the implicit fallback variant. A selector that pins no variant\n * resolves to it, and a variant that declares no entry of its own falls back to\n * it — so a key only has to ship the entries that actually differ.\n */\nexport const DEFAULT_VARIANT_ID = 'default';\n\n/**\n * Characters kept verbatim in an encoded qualifier segment. Everything else is\n * percent-encoded so a segment can never contain the composite-id separator\n * (`/`), path-hostile characters (`\\` `:` `*` `?` `\"` `<` `>` `|`, control\n * chars), or characters that would break the generated loader modules (`'`).\n */\nconst SEGMENT_UNSAFE_CHARS = /[^A-Za-z0-9._&=-]/g;\n\n/**\n * Stricter set for the components of an object variant: also encodes `&` and\n * `=` so the `field=value&field=value` serialization stays unambiguous.\n */\nconst COMPONENT_UNSAFE_CHARS = /[^A-Za-z0-9._-]/g;\n\n/** Percent-encodes one UTF-16 code unit as a fixed-width `%XXXX` run. */\nconst percentEncodeChar = (char: string): string =>\n `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}`;\n\nconst encodeSegmentText = (raw: string, unsafeChars: RegExp): string => {\n // Bare '%' cannot be produced by encoding (every encoded run is %XXXX),\n // so it is a safe stand-in for the empty string.\n if (raw === '') return '%';\n\n const encoded = raw.replace(unsafeChars, percentEncodeChar);\n\n // '.' and '..' are path navigation on every filesystem — encode the dots.\n if (encoded === '.' || encoded === '..') {\n return encoded.replace(/\\./g, '%002E');\n }\n\n return encoded;\n};\n\n/**\n * Canonical serialization of a single variant value into its identity string —\n * the variant segment of a composite id, the chunk directory name in dynamic\n * mode, and the runtime matching key.\n *\n * - `undefined` → `'default'` (the implicit fallback variant)\n * - a string → the string itself (a named variant)\n * - an object → its sorted `key=value` pairs joined by `&`\n * (e.g. `{ userId: '123', id: 'abc' }` → `'id=abc&userId=123'`)\n *\n * Characters that are unsafe in file paths or generated code are\n * percent-encoded (fixed-width `%XXXX` runs, injective). Common names —\n * letters, digits, `-` `_` `.` — are left untouched. Both the declaration and\n * the selector go through this function, so encoding never affects matching.\n *\n * Two variants resolve to the same entry iff their serializations are equal, so\n * an object variant in a selector must equal the one declared on the dictionary.\n */\nexport const serializeVariant = (\n variant: DictionaryVariantValue | undefined\n): string => {\n if (variant === undefined) return DEFAULT_VARIANT_ID;\n if (typeof variant === 'string') {\n return encodeSegmentText(variant, SEGMENT_UNSAFE_CHARS);\n }\n\n return Object.keys(variant)\n .sort()\n .map(\n (field) =>\n `${encodeSegmentText(field, COMPONENT_UNSAFE_CHARS)}=${encodeSegmentText(String(variant[field]), COMPONENT_UNSAFE_CHARS)}`\n )\n .join('&');\n};\n\n/** Reverses `encodeSegmentText`: decodes the `%XXXX` runs and the `%` stand-in. */\nconst decodeSegmentText = (segment: string): string =>\n segment === '%'\n ? ''\n : segment.replace(/%([0-9A-F]{4})/g, (_match, charCode: string) =>\n String.fromCharCode(Number.parseInt(charCode, 16))\n );\n\n/**\n * Normalizes a raw item id: a string holding a number's exact canonical form\n * becomes that number (`'2'` → `2`), anything else stays a string id\n * (`'007'`, `'65f1c0a2'`, `'Infinity'`).\n *\n * @param rawItem - The item id as text (a composite id segment, a form input…).\n */\nexport const parseItemId = (rawItem: string): DictionaryItemId => {\n const numericItem = Number(rawItem);\n\n return rawItem !== '' &&\n Number.isFinite(numericItem) &&\n String(numericItem) === rawItem\n ? numericItem\n : rawItem;\n};\n\n/**\n * Canonical serialization of an item id — the item segment of a composite id,\n * the chunk directory name in dynamic mode, and the runtime matching key.\n *\n * A number and its digits serialize identically (`2` and `'2'` → `'2'`).\n * Characters unsafe in file paths or generated code are percent-encoded like\n * variant names, so database ids (hex, UUID, nanoid…) are kept verbatim.\n */\nexport const serializeItem = (item: DictionaryItemId): string =>\n encodeSegmentText(String(item), SEGMENT_UNSAFE_CHARS);\n\n/** Decodes the item segment of a composite id back into its item id. */\nexport const parseItemSegment = (segment: string): DictionaryItemId =>\n parseItemId(decodeSegmentText(segment));\n\n/**\n * Collection order of two item ids: numeric ids by value first, then string\n * ids by UTF-16 code unit (locale-independent, so every build agrees).\n */\nexport const compareItemIds = (\n leftItem: DictionaryItemId,\n rightItem: DictionaryItemId\n): number => {\n if (typeof leftItem === 'number' && typeof rightItem === 'number') {\n return leftItem - rightItem;\n }\n\n if (typeof leftItem === 'number') return -1;\n if (typeof rightItem === 'number') return 1;\n if (leftItem === rightItem) return 0;\n\n return leftItem < rightItem ? -1 : 1;\n};\n\n/** Collection order of two serialized item segments (see {@link compareItemIds}). */\nexport const compareItemSegments = (\n leftSegment: string,\n rightSegment: string\n): number =>\n compareItemIds(parseItemSegment(leftSegment), parseItemSegment(rightSegment));\n\n/**\n * Serializes the variant coordinate of a selector into the ordered list of\n * candidate ids to try, so a single value and a preference chain share one code\n * path downstream.\n *\n * - `undefined` → `['default']`\n * - a single value → its one serialization\n * - a chain → one serialization per entry, order preserved\n *\n * An empty chain is treated as \"no variant pinned\" (`['default']`) rather than\n * as an unsatisfiable request.\n */\nexport const serializeVariantChain = (\n variant: DictionaryVariantChain | undefined\n): string[] => {\n if (!Array.isArray(variant)) {\n return [serializeVariant(variant as DictionaryVariantValue | undefined)];\n }\n\n if (variant.length === 0) return [DEFAULT_VARIANT_ID];\n\n return variant.map(serializeVariant);\n};\n\n/**\n * Resolves the variant id a selector actually targets among the ids a key\n * declares — the sparse-override fallback.\n *\n * Candidates are tried in order and the first one the key declares wins.\n * Otherwise the key falls back to its `default` entry, so a variant only has to\n * be declared where its wording differs. When the key declares no `default`\n * either, the first candidate is returned unchanged and the caller resolves to\n * `null` / `[]`.\n *\n * @param requestedVariantIds - The serialized ids the selector asks for, in\n * preference order (a single value is a 1-element\n * list).\n * @param isVariantIdDeclared - Whether the key declares an entry for an id.\n */\nexport const resolveEffectiveVariantId = (\n requestedVariantIds: string[],\n isVariantIdDeclared: (variantId: string) => boolean\n): string => {\n for (const requestedVariantId of requestedVariantIds) {\n if (isVariantIdDeclared(requestedVariantId)) return requestedVariantId;\n }\n\n return isVariantIdDeclared(DEFAULT_VARIANT_ID)\n ? DEFAULT_VARIANT_ID\n : (requestedVariantIds[0] ?? DEFAULT_VARIANT_ID);\n};\n\n/**\n * Tests whether a composite entry id matches a selector across every declared\n * dimension. Segments are compared in their encoded form (both the stored id\n * and the selector go through {@link serializeVariant}). The `item` dimension\n * matches any value when the selector does not provide one (open collection\n * axis); the `variant` dimension is compared against the already-resolved\n * effective id, so the fallback is applied consistently across dimensions.\n */\nconst compositeIdMatchesSelector = (\n compositeId: string,\n qualifierTypes: DictionaryQualifierType[],\n selector: DictionarySelector | undefined,\n effectiveVariantId: string\n): boolean => {\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n\n return qualifierTypes.every((qualifierType, index) => {\n if (qualifierType === 'variant') {\n return segments[index] === effectiveVariantId;\n }\n\n // qualifierType === 'item'\n return (\n selector?.item === undefined ||\n segments[index] === serializeItem(selector.item)\n );\n });\n};\n\n/**\n * Type guard discriminating a `QualifiedDictionaryGroup` (merge output of a\n * qualified key) from a plain `Dictionary`. Both carry a `content` field; only\n * the group declares `qualifierTypes`, which is therefore the discriminator.\n */\nexport const isQualifiedDictionaryGroup = (\n value: unknown\n): value is QualifiedDictionaryGroup =>\n typeof value === 'object' &&\n value !== null &&\n 'qualifierTypes' in value &&\n Array.isArray((value as { qualifierTypes: unknown }).qualifierTypes) &&\n 'content' in value;\n\n/**\n * Reconstructs a resolvable {@link Dictionary} from a single entry of a\n * qualified group: the content node stored under its composite id, plus the\n * qualifier coordinates decoded from that id (`variant`, `item`).\n *\n * This keeps the resolver's transform code unchanged: it still sees a\n * `{ key, content, variant?, item? }` shape, even though the stored format no\n * longer duplicates those fields per entry. The `variant` coordinate stays in\n * its serialized (encoded) form, e.g. `'id=abc&userId=123'` — matching happens\n * on the composite id segments, never on this reconstructed field. The `item`\n * coordinate is decoded back to its id (`2`, `'65f1c0a2'`).\n */\nexport const reconstructQualifiedEntry = (\n group: QualifiedDictionaryGroup,\n compositeId: string\n): Dictionary => {\n const segments = compositeId.split(COMPOSITE_ID_SEPARATOR);\n\n const entry = {\n key: group.key,\n content: group.content[compositeId],\n } as Dictionary;\n\n const entryMetadata = group.metadata?.[compositeId];\n\n if (entryMetadata !== undefined) {\n entry.metadata = entryMetadata as Dictionary['metadata'];\n }\n\n group.qualifierTypes.forEach((qualifierType, index) => {\n if (qualifierType === 'variant') {\n entry.variant = segments[index];\n } else if (qualifierType === 'item') {\n entry.item = parseItemSegment(segments[index] ?? '');\n }\n });\n\n return entry;\n};\n\n/**\n * Resolves a dictionary (or qualified dictionary group) against a selector,\n * across every declared dimension.\n *\n * - Plain dictionary → returned as-is (selector ignored)\n * - `item` declared but not selected → every matching entry, in collection\n * order (see `compareItemIds`)\n * - `item` selected → the matching entry or null\n * - `variant` defaults to the `default` entry when not selected, and falls back\n * to it when the selected variant declares no entry of its own; an object\n * variant resolves only when the selector provides an equal object (or, again,\n * through the `default` fallback)\n *\n * Dimensions compose: e.g. a variant × item key with `{ variant: 'promo' }`\n * returns every promo item as an array; adding `{ item: 2 }` narrows to one.\n */\nexport const resolveQualifiedDictionary = (\n dictionaryOrGroup: Dictionary | QualifiedDictionaryGroup,\n selector?: DictionarySelector\n): Dictionary | Dictionary[] | null => {\n if (!isQualifiedDictionaryGroup(dictionaryOrGroup)) {\n return dictionaryOrGroup;\n }\n\n const { itemAxisOpen, matchedIds } = matchQualifiedEntryIds(\n Object.keys(dictionaryOrGroup.content),\n dictionaryOrGroup.qualifierTypes,\n selector\n );\n\n const matchedEntries = matchedIds.map((compositeId) =>\n reconstructQualifiedEntry(dictionaryOrGroup, compositeId)\n );\n\n if (itemAxisOpen) return matchedEntries;\n\n return matchedEntries[0] ?? null;\n};\n\n/** Ids a selector targets among a qualified key's entries. */\nexport type MatchedQualifiedEntryIds = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** Matching composite ids, in collection order when the axis is open. */\n matchedIds: string[];\n};\n\n/**\n * Selects the composite ids a selector targets across every declared\n * dimension — the matching shared by the static resolver and the dynamic\n * metadata index, so both modes resolve the same entries.\n *\n * @param compositeIds - Every composite id the key declares.\n * @param qualifierTypes - The key's dimensions, in canonical order.\n * @param selector - The selector splitting the dimensions.\n */\nexport const matchQualifiedEntryIds = (\n compositeIds: string[],\n qualifierTypes: DictionaryQualifierType[],\n selector?: DictionarySelector\n): MatchedQualifiedEntryIds => {\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n const variantIndex = qualifierTypes.indexOf('variant');\n const itemIndex = qualifierTypes.indexOf('item');\n\n const effectiveVariantId =\n variantIndex === -1\n ? DEFAULT_VARIANT_ID\n : resolveEffectiveVariantId(\n serializeVariantChain(selector?.variant),\n (variantId) =>\n compositeIds.some(\n (compositeId) =>\n compositeId.split(COMPOSITE_ID_SEPARATOR)[variantIndex] ===\n variantId\n )\n );\n\n const matchedIds = compositeIds.filter((compositeId) =>\n compositeIdMatchesSelector(\n compositeId,\n qualifierTypes,\n selector,\n effectiveVariantId\n )\n );\n\n if (itemAxisOpen) {\n const getItemSegment = (compositeId: string): string =>\n compositeId.split(COMPOSITE_ID_SEPARATOR)[itemIndex] ?? '';\n\n matchedIds.sort((left, right) =>\n compareItemSegments(getItemSegment(left), getItemSegment(right))\n );\n }\n\n return { itemAxisOpen, matchedIds };\n};\n\n/**\n * Splits the second argument of `getIntlayer` / `getDictionary` into the\n * effective locale and the selector object (if any).\n */\nexport const parseDictionarySelector = <L extends LocalesValues>(\n localeOrSelector?: L | DictionarySelector\n): { locale?: L; selector?: DictionarySelector } => {\n if (typeof localeOrSelector === 'object' && localeOrSelector !== null) {\n return {\n locale: localeOrSelector.locale as L | undefined,\n selector: localeOrSelector,\n };\n }\n\n return { locale: localeOrSelector as L | undefined };\n};\n\n/**\n * Resolves the variant a provider pins for one dictionary key.\n *\n * A string or a chain applies to every key as-is. A plain object is the per-key\n * map: the entry for `dictionaryKey` wins, falling back to the reserved\n * `default` entry, and `undefined` when neither is present (the key then\n * resolves to its own `default` variant, i.e. the behaviour without a provider\n * variant at all).\n *\n * A plain object is **always** the map here — never a structured variant value,\n * which is why a structured variant has to be nested (`{ default: { id } }`).\n *\n * @param providerVariant - The `variant` prop of the surrounding provider.\n * @param dictionaryKey - The key being read.\n */\nexport const resolveProviderVariant = (\n providerVariant: ProviderVariantBase | undefined,\n dictionaryKey: string\n): DictionaryVariantChain | undefined => {\n if (providerVariant === undefined) return undefined;\n\n if (typeof providerVariant === 'string' || Array.isArray(providerVariant)) {\n return providerVariant as DictionaryVariantChain;\n }\n\n const variantMap = providerVariant as ProviderVariantMap;\n\n return variantMap[dictionaryKey] ?? variantMap[DEFAULT_VARIANT_ID];\n};\n\n/**\n * Builds the effective second argument of a dictionary read by layering the\n * provider defaults under the call-site one — the single place the `locale` and\n * `variant` context defaults are applied, shared by every framework binding.\n *\n * Precedence, per dimension independently:\n * - a call-site selector always wins; `{ variant: 'x' }` **replaces** the\n * provider chain rather than extending it\n * - otherwise the provider value applies\n *\n * Returns a bare locale (not a selector object) whenever no variant is in play,\n * so the existing fast path — and the cache keys built from it — are unchanged\n * for projects that never use variants.\n */\nexport const resolveDictionaryArgument = (params: {\n localeOrSelector?: LocalesValues | DictionarySelector;\n contextLocale?: LocalesValues;\n contextVariant?: ProviderVariantBase;\n dictionaryKey: string;\n}): LocalesValues | DictionarySelector | undefined => {\n const { localeOrSelector, contextLocale, contextVariant, dictionaryKey } =\n params;\n\n const callSelector =\n typeof localeOrSelector === 'object' && localeOrSelector !== null\n ? localeOrSelector\n : undefined;\n\n const callLocale = callSelector\n ? callSelector.locale\n : (localeOrSelector as LocalesValues | undefined);\n\n // The context locale is typed as widely as the runtime allows, while a\n // selector narrows `locale` to the declared ones — the value is the same.\n const locale = (callLocale ?? contextLocale) as DictionarySelector['locale'];\n\n // A call-site variant is authoritative; the provider only fills the gap.\n const variant =\n callSelector?.variant ??\n resolveProviderVariant(contextVariant, dictionaryKey);\n\n if (variant === undefined) {\n // Nothing to add: keep the argument in its original shape so the identity\n // built from it stays byte-identical to the pre-variant behaviour.\n return callSelector\n ? { ...callSelector, locale }\n : (locale as LocalesValues | undefined);\n }\n\n return { ...callSelector, locale, variant };\n};\n\n/**\n * Builds a stable string identity of a selector (excluding `locale`, and the\n * dimensions left `undefined`), suitable for cache keys and memoization\n * dependencies.\n */\nexport const getDictionarySelectorCacheKey = (\n selector?: DictionarySelector\n): string => {\n if (!selector) return '';\n\n return Object.keys(selector)\n .filter(\n (selectorKey) =>\n selectorKey !== 'locale' &&\n selector[selectorKey as keyof DictionarySelector] !== undefined\n )\n .sort()\n .map((selectorKey) => {\n const value = selector[selectorKey as keyof DictionarySelector];\n const serialized =\n selectorKey === 'variant'\n ? serializeVariantChain(\n value as DictionaryVariantChain | undefined\n ).join(',')\n : String(value);\n return `${selectorKey}:${serialized}`;\n })\n .join('|');\n};\n"],"mappings":";;;;;;AAiBA,MAAa,yBAAyB;;;;;;AAOtC,MAAa,qBAAqB;;;;;;;AAQlC,MAAM,uBAAuB;;;;;AAM7B,MAAM,yBAAyB;;AAG/B,MAAM,qBAAqB,SACzB,IAAI,KAAK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kBAAkB;AACtC;;;;;;;;;;;;;;;AAgBA,MAAa,6BAA6B,WAKY;CACpD,MAAM,EAAE,kBAAkB,eAAe,gBAAgB,kBACvD;CAEF,MAAM,eACJ,OAAO,qBAAqB,YAAY,qBAAqB,OACzD,mBACA;CAQN,MAAM,UANa,eACf,aAAa,SACZ,qBAIyB;CAG9B,MAAM,UACJ,cAAc,WACd,uBAAuB,gBAAgB,aAAa;CAEtD,IAAI,YAAY,QAGd,OAAO,eACH;EAAE,GAAG;EAAc;CAAO,IACzB;CAGP,OAAO;EAAE,GAAG;EAAc;EAAQ;CAAQ;AAC5C;;;;;;AAOA,MAAa,iCACX,aACW;CACX,IAAI,CAAC,UAAU,OAAO;CAEtB,OAAO,OAAO,KAAK,QAAQ,CAAC,CACzB,QACE,gBACC,gBAAgB,YAChB,SAAS,iBAA6C,MAC1D,CAAC,CACA,KAAK,CAAC,CACN,KAAK,gBAAgB;EACpB,MAAM,QAAQ,SAAS;EAOvB,OAAO,GAAG,YAAY,GALpB,gBAAgB,YACZ,sBACE,KACF,CAAC,CAAC,KAAK,GAAG,IACV,OAAO,KAAK;CAEpB,CAAC,CAAC,CACD,KAAK,GAAG;AACb"}
@@ -22,6 +22,11 @@ const getVariantIds = (variant) => {
22
22
  return [...new Set(values.map(require_dictionaryManipulator_qualifiedDictionary.serializeVariant))];
23
23
  };
24
24
  /**
25
+ * Whether an `item` field declares the collection dimension: a number, or a
26
+ * non-empty string id. An empty string (a blank form field) declares nothing.
27
+ */
28
+ const isDeclaredItem = (item) => typeof item === "number" || typeof item === "string" && item !== "";
29
+ /**
25
30
  * Returns the qualifier dimensions declared on a dictionary, in canonical
26
31
  * order (`variant → item`). Empty when the dictionary is unqualified
27
32
  * (plain dictionary or shared base content of a qualified group).
@@ -29,7 +34,7 @@ const getVariantIds = (variant) => {
29
34
  const getDictionaryQualifierTypes = (dictionary) => {
30
35
  const declaredQualifiers = [];
31
36
  if (getVariantIds(dictionary.variant) !== void 0) declaredQualifiers.push("variant");
32
- if (typeof dictionary.item === "number") declaredQualifiers.push("item");
37
+ if (isDeclaredItem(dictionary.item)) declaredQualifiers.push("item");
33
38
  return declaredQualifiers;
34
39
  };
35
40
  /**
@@ -38,11 +43,11 @@ const getDictionaryQualifierTypes = (dictionary) => {
38
43
  *
39
44
  * - 'variant' → the serialized variant id(s); an array variant yields one id
40
45
  * per element (declaration-side fan-out)
41
- * - 'item' → the item index as a single-element list
46
+ * - 'item' → the serialized item id as a single-element list
42
47
  */
43
48
  const getDictionaryQualifierIds = (dictionary, qualifierType) => {
44
49
  if (qualifierType === "variant") return getVariantIds(dictionary.variant);
45
- return dictionary.item === void 0 ? void 0 : [String(dictionary.item)];
50
+ return isDeclaredItem(dictionary.item) ? [require_dictionaryManipulator_qualifiedDictionary.serializeItem(dictionary.item)] : void 0;
46
51
  };
47
52
  /**
48
53
  * Builds every composite entry id of a dictionary — the cartesian product of
@@ -65,4 +70,5 @@ exports.getDictionaryCompositeIds = getDictionaryCompositeIds;
65
70
  exports.getDictionaryQualifierIds = getDictionaryQualifierIds;
66
71
  exports.getDictionaryQualifierTypes = getDictionaryQualifierTypes;
67
72
  exports.getVariantIds = getVariantIds;
73
+ exports.isDeclaredItem = isDeclaredItem;
68
74
  //# sourceMappingURL=qualifiedDictionaryDeclaration.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"qualifiedDictionaryDeclaration.cjs","names":["serializeVariant"],"sources":["../../../src/dictionaryManipulator/qualifiedDictionaryDeclaration.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionaryQualifierType,\n} from '@intlayer/types/dictionary';\nimport {\n COMPOSITE_ID_SEPARATOR,\n serializeVariant,\n} from './qualifiedDictionary';\n\n/**\n * Canonical order of qualifier dimensions. A key that declares both dimensions\n * always nests them in this order, with `item` innermost so it can act as the\n * collection (array) axis.\n */\nexport const QUALIFIER_ORDER = [\n 'variant',\n 'item',\n] as const satisfies readonly DictionaryQualifierType[];\n\n/**\n * Normalizes the `variant` field of a dictionary into the list of variant ids\n * the declaration registers under. A single value yields one id; an **array**\n * fans out into one id per element (duplicates collapsed). Returns `undefined`\n * when the dictionary does not declare the variant dimension (no `variant`\n * field, or an empty array).\n */\nexport const getVariantIds = (\n variant: Dictionary['variant']\n): string[] | undefined => {\n if (variant === undefined) return undefined;\n\n const values = Array.isArray(variant) ? variant : [variant];\n if (values.length === 0) return undefined;\n\n return [...new Set(values.map(serializeVariant))];\n};\n\n/**\n * Returns the qualifier dimensions declared on a dictionary, in canonical\n * order (`variant → item`). Empty when the dictionary is unqualified\n * (plain dictionary or shared base content of a qualified group).\n */\nexport const getDictionaryQualifierTypes = (\n dictionary: Dictionary\n): DictionaryQualifierType[] => {\n const declaredQualifiers: DictionaryQualifierType[] = [];\n\n if (getVariantIds(dictionary.variant) !== undefined) {\n declaredQualifiers.push('variant');\n }\n if (typeof dictionary.item === 'number') declaredQualifiers.push('item');\n\n return declaredQualifiers;\n};\n\n/**\n * Returns the qualifier identifiers of a dictionary for the given qualifier\n * dimension — the candidate segments of the composite entry ids.\n *\n * - 'variant' → the serialized variant id(s); an array variant yields one id\n * per element (declaration-side fan-out)\n * - 'item' → the item index as a single-element list\n */\nexport const getDictionaryQualifierIds = (\n dictionary: Dictionary,\n qualifierType: DictionaryQualifierType\n): string[] | undefined => {\n if (qualifierType === 'variant') {\n return getVariantIds(dictionary.variant);\n }\n return dictionary.item === undefined ? undefined : [String(dictionary.item)];\n};\n\n/**\n * Builds every composite entry id of a dictionary — the cartesian product of\n * its per-dimension id lists, joined in canonical order. A dictionary with a\n * plain (non-array) variant yields exactly one id; an array variant fans out\n * into one id per element. `undefined` when a dimension of the set is missing.\n */\nexport const getDictionaryCompositeIds = (\n dictionary: Dictionary,\n qualifierTypes: DictionaryQualifierType[]\n): string[] | undefined => {\n let compositeIds: string[] = [''];\n\n for (const qualifierType of qualifierTypes) {\n const ids = getDictionaryQualifierIds(dictionary, qualifierType);\n if (ids === undefined) return undefined;\n\n compositeIds = compositeIds.flatMap((prefix) =>\n ids.map((id) =>\n prefix === '' ? id : `${prefix}${COMPOSITE_ID_SEPARATOR}${id}`\n )\n );\n }\n\n return compositeIds;\n};\n"],"mappings":";;;;;;;;;AAcA,MAAa,kBAAkB,CAC7B,WACA,MACF;;;;;;;;AASA,MAAa,iBACX,YACyB;CACzB,IAAI,YAAY,QAAW,OAAO;CAElC,MAAM,SAAS,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO;CAC1D,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAO,CAAC,GAAG,IAAI,IAAI,OAAO,IAAIA,kEAAgB,CAAC,CAAC;AAClD;;;;;;AAOA,MAAa,+BACX,eAC8B;CAC9B,MAAM,qBAAgD,CAAC;CAEvD,IAAI,cAAc,WAAW,OAAO,MAAM,QACxC,mBAAmB,KAAK,SAAS;CAEnC,IAAI,OAAO,WAAW,SAAS,UAAU,mBAAmB,KAAK,MAAM;CAEvE,OAAO;AACT;;;;;;;;;AAUA,MAAa,6BACX,YACA,kBACyB;CACzB,IAAI,kBAAkB,WACpB,OAAO,cAAc,WAAW,OAAO;CAEzC,OAAO,WAAW,SAAS,SAAY,SAAY,CAAC,OAAO,WAAW,IAAI,CAAC;AAC7E;;;;;;;AAQA,MAAa,6BACX,YACA,mBACyB;CACzB,IAAI,eAAyB,CAAC,EAAE;CAEhC,KAAK,MAAM,iBAAiB,gBAAgB;EAC1C,MAAM,MAAM,0BAA0B,YAAY,aAAa;EAC/D,IAAI,QAAQ,QAAW,OAAO;EAE9B,eAAe,aAAa,SAAS,WACnC,IAAI,KAAK,OACP,WAAW,KAAK,KAAK,GAAG,eAAkC,IAC5D,CACF;CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"qualifiedDictionaryDeclaration.cjs","names":["serializeVariant","serializeItem"],"sources":["../../../src/dictionaryManipulator/qualifiedDictionaryDeclaration.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionaryItemId,\n DictionaryQualifierType,\n} from '@intlayer/types/dictionary';\nimport {\n COMPOSITE_ID_SEPARATOR,\n serializeItem,\n serializeVariant,\n} from './qualifiedDictionary';\n\n/**\n * Canonical order of qualifier dimensions. A key that declares both dimensions\n * always nests them in this order, with `item` innermost so it can act as the\n * collection (array) axis.\n */\nexport const QUALIFIER_ORDER = [\n 'variant',\n 'item',\n] as const satisfies readonly DictionaryQualifierType[];\n\n/**\n * Normalizes the `variant` field of a dictionary into the list of variant ids\n * the declaration registers under. A single value yields one id; an **array**\n * fans out into one id per element (duplicates collapsed). Returns `undefined`\n * when the dictionary does not declare the variant dimension (no `variant`\n * field, or an empty array).\n */\nexport const getVariantIds = (\n variant: Dictionary['variant']\n): string[] | undefined => {\n if (variant === undefined) return undefined;\n\n const values = Array.isArray(variant) ? variant : [variant];\n if (values.length === 0) return undefined;\n\n return [...new Set(values.map(serializeVariant))];\n};\n\n/**\n * Whether an `item` field declares the collection dimension: a number, or a\n * non-empty string id. An empty string (a blank form field) declares nothing.\n */\nexport const isDeclaredItem = (\n item: Dictionary['item']\n): item is DictionaryItemId =>\n typeof item === 'number' || (typeof item === 'string' && item !== '');\n\n/**\n * Returns the qualifier dimensions declared on a dictionary, in canonical\n * order (`variant → item`). Empty when the dictionary is unqualified\n * (plain dictionary or shared base content of a qualified group).\n */\nexport const getDictionaryQualifierTypes = (\n dictionary: Dictionary\n): DictionaryQualifierType[] => {\n const declaredQualifiers: DictionaryQualifierType[] = [];\n\n if (getVariantIds(dictionary.variant) !== undefined) {\n declaredQualifiers.push('variant');\n }\n if (isDeclaredItem(dictionary.item)) declaredQualifiers.push('item');\n\n return declaredQualifiers;\n};\n\n/**\n * Returns the qualifier identifiers of a dictionary for the given qualifier\n * dimension — the candidate segments of the composite entry ids.\n *\n * - 'variant' → the serialized variant id(s); an array variant yields one id\n * per element (declaration-side fan-out)\n * - 'item' → the serialized item id as a single-element list\n */\nexport const getDictionaryQualifierIds = (\n dictionary: Dictionary,\n qualifierType: DictionaryQualifierType\n): string[] | undefined => {\n if (qualifierType === 'variant') {\n return getVariantIds(dictionary.variant);\n }\n return isDeclaredItem(dictionary.item)\n ? [serializeItem(dictionary.item)]\n : undefined;\n};\n\n/**\n * Builds every composite entry id of a dictionary — the cartesian product of\n * its per-dimension id lists, joined in canonical order. A dictionary with a\n * plain (non-array) variant yields exactly one id; an array variant fans out\n * into one id per element. `undefined` when a dimension of the set is missing.\n */\nexport const getDictionaryCompositeIds = (\n dictionary: Dictionary,\n qualifierTypes: DictionaryQualifierType[]\n): string[] | undefined => {\n let compositeIds: string[] = [''];\n\n for (const qualifierType of qualifierTypes) {\n const ids = getDictionaryQualifierIds(dictionary, qualifierType);\n if (ids === undefined) return undefined;\n\n compositeIds = compositeIds.flatMap((prefix) =>\n ids.map((id) =>\n prefix === '' ? id : `${prefix}${COMPOSITE_ID_SEPARATOR}${id}`\n )\n );\n }\n\n return compositeIds;\n};\n"],"mappings":";;;;;;;;;AAgBA,MAAa,kBAAkB,CAC7B,WACA,MACF;;;;;;;;AASA,MAAa,iBACX,YACyB;CACzB,IAAI,YAAY,QAAW,OAAO;CAElC,MAAM,SAAS,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO;CAC1D,IAAI,OAAO,WAAW,GAAG,OAAO;CAEhC,OAAO,CAAC,GAAG,IAAI,IAAI,OAAO,IAAIA,kEAAgB,CAAC,CAAC;AAClD;;;;;AAMA,MAAa,kBACX,SAEA,OAAO,SAAS,YAAa,OAAO,SAAS,YAAY,SAAS;;;;;;AAOpE,MAAa,+BACX,eAC8B;CAC9B,MAAM,qBAAgD,CAAC;CAEvD,IAAI,cAAc,WAAW,OAAO,MAAM,QACxC,mBAAmB,KAAK,SAAS;CAEnC,IAAI,eAAe,WAAW,IAAI,GAAG,mBAAmB,KAAK,MAAM;CAEnE,OAAO;AACT;;;;;;;;;AAUA,MAAa,6BACX,YACA,kBACyB;CACzB,IAAI,kBAAkB,WACpB,OAAO,cAAc,WAAW,OAAO;CAEzC,OAAO,eAAe,WAAW,IAAI,IACjC,CAACC,gEAAc,WAAW,IAAI,CAAC,IAC/B;AACN;;;;;;;AAQA,MAAa,6BACX,YACA,mBACyB;CACzB,IAAI,eAAyB,CAAC,EAAE;CAEhC,KAAK,MAAM,iBAAiB,gBAAgB;EAC1C,MAAM,MAAM,0BAA0B,YAAY,aAAa;EAC/D,IAAI,QAAQ,QAAW,OAAO;EAE9B,eAAe,aAAa,SAAS,WACnC,IAAI,KAAK,OACP,WAAW,KAAK,KAAK,GAAG,eAAkC,IAC5D,CACF;CACF;CAEA,OAAO;AACT"}
@@ -3,6 +3,8 @@ const require_dictionaryManipulator_qualifiedDictionary = require("./qualifiedDi
3
3
  let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
4
4
 
5
5
  // src/dictionaryManipulator/qualifiedDynamicLoader.ts
6
+ /** Cache-key suffix of a metadata index chunk (never a valid composite id). */
7
+ const METADATA_INDEX_CACHE_SEGMENT = "#metadata";
6
8
  /**
7
9
  * Type guard discriminating a qualified dynamic loader map (collections /
8
10
  * variants, possibly combined) from a plain dynamic loader map.
@@ -10,13 +12,29 @@ let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
10
12
  const isQualifiedDynamicLoaderMap = (value) => typeof value === "object" && value !== null && _intlayer_config_defaultValues.QUALIFIER_DYNAMIC_TYPES_KEY in value;
11
13
  /**
12
14
  * Walks the loader tree following the selector and collects the chunk loaders
13
- * it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and
14
- * async ({@link resolveQualifiedDynamicContentAsync}) resolvers.
15
+ * it targets.
16
+ *
17
+ * Walks one dimension at a time (canonical order `variant → item`): `variant`
18
+ * descends by the serialized id, falling back to `default` when the selected
19
+ * variant has no chunk of its own, and `item` either narrows to the selected
20
+ * index or — when no item is given — expands into every sibling chunk (the
21
+ * collection axis). Semantics mirror `resolveQualifiedDictionary` so dynamic
22
+ * and static modes behave alike.
15
23
  */
16
24
  const collectQualifiedChunks = (loaderMap, key, locale, selector) => {
17
25
  const qualifierTypes = loaderMap[_intlayer_config_defaultValues.QUALIFIER_DYNAMIC_TYPES_KEY];
18
26
  const localeTree = loaderMap[locale];
19
27
  const itemAxisOpen = qualifierTypes.includes("item") && selector?.item === void 0;
28
+ const metadataIndexLoader = selector?.metadataOnly && itemAxisOpen ? loaderMap[_intlayer_config_defaultValues.QUALIFIER_DYNAMIC_METADATA_KEY]?.[locale] : void 0;
29
+ if (metadataIndexLoader) return {
30
+ itemAxisOpen,
31
+ missed: false,
32
+ readsMetadataIndex: true,
33
+ chunks: [{
34
+ cacheKey: `${key}.${locale}.${METADATA_INDEX_CACHE_SEGMENT}`,
35
+ loader: metadataIndexLoader
36
+ }]
37
+ };
20
38
  if (!localeTree) return {
21
39
  itemAxisOpen,
22
40
  missed: true,
@@ -34,10 +52,10 @@ const collectQualifiedChunks = (loaderMap, key, locale, selector) => {
34
52
  const [dimension, ...rest] = dimensions;
35
53
  const tree = node;
36
54
  if (dimension === "item" && selector?.item === void 0) {
37
- for (const segment of Object.keys(tree).sort((left, right) => Number(left) - Number(right))) walk(tree[segment], rest, [...segments, segment]);
55
+ for (const segment of Object.keys(tree).sort(require_dictionaryManipulator_qualifiedDictionary.compareItemSegments)) walk(tree[segment], rest, [...segments, segment]);
38
56
  return true;
39
57
  }
40
- const segment = dimension === "variant" ? require_dictionaryManipulator_qualifiedDictionary.resolveEffectiveVariantId(require_dictionaryManipulator_qualifiedDictionary.serializeVariantChain(selector?.variant), (variantId) => tree[variantId] !== void 0) : String(selector?.item);
58
+ const segment = dimension === "item" && selector?.item !== void 0 ? require_dictionaryManipulator_qualifiedDictionary.serializeItem(selector.item) : require_dictionaryManipulator_qualifiedDictionary.resolveEffectiveVariantId(require_dictionaryManipulator_qualifiedDictionary.serializeVariantChain(selector?.variant), (variantId) => tree[variantId] !== void 0);
41
59
  const child = tree[segment];
42
60
  if (!child) return false;
43
61
  return walk(child, rest, [...segments, segment]);
@@ -49,79 +67,31 @@ const collectQualifiedChunks = (loaderMap, key, locale, selector) => {
49
67
  };
50
68
  };
51
69
  /**
52
- * Lists the chunks a selector targets in a qualified dynamic loader map,
53
- * without loading them — lets a caller warm a suspender cache ahead of render.
54
- *
55
- * @returns The targeted chunks, empty when a required coordinate is absent.
56
- */
57
- const getQualifiedDynamicChunks = (loaderMap, key, locale, selector) => {
58
- const { missed, chunks } = collectQualifiedChunks(loaderMap, key, locale, selector);
59
- return missed ? [] : chunks;
60
- };
61
- /**
62
- * Resolves the content of a qualified dynamic loader map against a selector,
63
- * loading only the chunk(s) the selector actually targets.
64
- *
65
- * Walks the nested loader tree one dimension at a time (canonical order
66
- * `variant → item`): `variant` descends by the serialized id, falling back to
67
- * `default` when the selected variant has no chunk of its own, and `item`
68
- * either narrows to the selected index or — when no item is given — expands
69
- * into every sibling chunk (the collection axis). Semantics mirror
70
- * `resolveQualifiedDictionary` so dynamic and static modes behave alike.
71
- *
72
- * The Suspense mechanism is injected through `loadChunk` so the same logic
73
- * serves both the client (suspender cache) and the server (`react.use`). Every
74
- * targeted loader is started before the first chunk is read, so sibling chunks
75
- * load in parallel rather than waterfalling.
70
+ * Reads the metadata a selector targets out of a loaded metadata index, with
71
+ * the same entry matching as static mode.
76
72
  *
77
- * @param loaderMap - The qualified dynamic loader map (entry point default export).
78
- * @param key - The dictionary key (used to build stable chunk cache keys).
79
- * @param locale - The resolved locale to load chunks for.
80
- * @param selector - The selector splitting the qualifier dimensions.
81
- * @param loadChunk - Reads a started chunk promise, suspending until it resolves.
82
- * @param transform - Turns a resolved chunk dictionary into final content.
73
+ * @param metadataIndex - The loaded index chunk (`metadata` maps composite ids).
74
+ * @param qualifierTypes - The key's dimensions, in canonical order.
75
+ * @param selector - The selector splitting the dimensions.
83
76
  */
84
- const resolveQualifiedDynamicContent = (params) => {
85
- const { loaderMap, key, locale, selector, loadChunk, transform } = params;
86
- const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(loaderMap, key, locale, selector);
87
- if (missed) return itemAxisOpen ? [] : null;
88
- const dictionaries = chunks.map(({ cacheKey, loader }) => ({
89
- cacheKey,
90
- promise: loader()
91
- })).map(({ cacheKey, promise }) => loadChunk(cacheKey, promise));
92
- if (itemAxisOpen) return dictionaries.map(transform);
93
- const [dictionary] = dictionaries;
94
- return dictionary ? transform(dictionary) : null;
95
- };
96
- /**
97
- * Async counterpart of {@link resolveQualifiedDynamicContent} for frameworks
98
- * that load dictionaries with `await` instead of Suspense (Vue, Svelte, Lit,
99
- * vanilla). Awaits every targeted chunk in parallel, then resolves identically.
100
- *
101
- * @param loaderMap - The qualified dynamic loader map.
102
- * @param key - The dictionary key (used to build stable chunk cache keys).
103
- * @param locale - The resolved locale to load chunks for.
104
- * @param selector - The selector splitting the qualifier dimensions.
105
- * @param transform - Turns a resolved chunk dictionary into final content.
106
- */
107
- const resolveQualifiedDynamicContentAsync = async (params) => {
108
- const { loaderMap, key, locale, selector, transform } = params;
109
- const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(loaderMap, key, locale, selector);
110
- if (missed) return itemAxisOpen ? [] : null;
111
- const dictionaries = await Promise.all(chunks.map(({ loader }) => loader()));
112
- if (itemAxisOpen) return dictionaries.map(transform);
113
- const [dictionary] = dictionaries;
114
- return dictionary ? transform(dictionary) : null;
77
+ const readMetadataIndex = (metadataIndex, qualifierTypes, selector) => {
78
+ const indexMetadata = metadataIndex?.metadata ?? {};
79
+ return require_dictionaryManipulator_qualifiedDictionary.matchQualifiedEntryIds(Object.keys(indexMetadata), qualifierTypes, selector).matchedIds.map((compositeId) => indexMetadata[compositeId]);
115
80
  };
116
81
 
82
+ Object.defineProperty(exports, "QUALIFIER_DYNAMIC_METADATA_KEY", {
83
+ enumerable: true,
84
+ get: function () {
85
+ return _intlayer_config_defaultValues.QUALIFIER_DYNAMIC_METADATA_KEY;
86
+ }
87
+ });
117
88
  Object.defineProperty(exports, "QUALIFIER_DYNAMIC_TYPES_KEY", {
118
89
  enumerable: true,
119
90
  get: function () {
120
91
  return _intlayer_config_defaultValues.QUALIFIER_DYNAMIC_TYPES_KEY;
121
92
  }
122
93
  });
123
- exports.getQualifiedDynamicChunks = getQualifiedDynamicChunks;
94
+ exports.collectQualifiedChunks = collectQualifiedChunks;
124
95
  exports.isQualifiedDynamicLoaderMap = isQualifiedDynamicLoaderMap;
125
- exports.resolveQualifiedDynamicContent = resolveQualifiedDynamicContent;
126
- exports.resolveQualifiedDynamicContentAsync = resolveQualifiedDynamicContentAsync;
96
+ exports.readMetadataIndex = readMetadataIndex;
127
97
  //# sourceMappingURL=qualifiedDynamicLoader.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"qualifiedDynamicLoader.cjs","names":["QUALIFIER_DYNAMIC_TYPES_KEY","resolveEffectiveVariantId","serializeVariantChain"],"sources":["../../../src/dictionaryManipulator/qualifiedDynamicLoader.ts"],"sourcesContent":["import { QUALIFIER_DYNAMIC_TYPES_KEY } from '@intlayer/config/defaultValues';\nimport type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport {\n COMPOSITE_ID_SEPARATOR,\n resolveEffectiveVariantId,\n serializeVariantChain,\n} from './qualifiedDictionary';\n\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Defined in `@intlayer/config` so the code generator and the build\n * plugins can read it without pulling the runtime in, and re-exported here\n * where its consumers live.\n */\nexport { QUALIFIER_DYNAMIC_TYPES_KEY };\n\n/**\n * A lazily-imported per-locale dictionary chunk loader.\n */\nexport type DynamicDictionaryLoader = () => Promise<Dictionary>;\n\n/**\n * Nested tree of chunk loaders: one nesting level per declared dimension (in\n * canonical order), leaves are loaders.\n */\nexport type QualifiedDynamicLoaderTree = {\n [segment: string]: QualifiedDynamicLoaderTree | DynamicDictionaryLoader;\n};\n\n/**\n * Default export shape of a generated dynamic entry point for a qualified key.\n * One nesting level per dimension under each locale, plus the dimension marker.\n *\n * ```ts\n * {\n * __intlayerQualifierTypes: ['variant', 'item'],\n * en: { promo: { '1': () => import('./json/x/promo/1/en.json'), … }, … },\n * fr: { … },\n * }\n * ```\n */\nexport type QualifiedDynamicLoaderMap = {\n [QUALIFIER_DYNAMIC_TYPES_KEY]: DictionaryQualifierType[];\n [locale: string]: QualifiedDynamicLoaderTree | DictionaryQualifierType[];\n};\n\n/**\n * Type guard discriminating a qualified dynamic loader map (collections /\n * variants, possibly combined) from a plain dynamic loader map.\n */\nexport const isQualifiedDynamicLoaderMap = (\n value: unknown\n): value is QualifiedDynamicLoaderMap =>\n typeof value === 'object' &&\n value !== null &&\n QUALIFIER_DYNAMIC_TYPES_KEY in value;\n\n/** One targeted chunk: its stable cache key and lazy loader. */\nexport type CollectedChunk = {\n cacheKey: string;\n loader: DynamicDictionaryLoader;\n};\n\ntype CollectedChunks = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** True when a required coordinate is absent (result → [] or null). */\n missed: boolean;\n /** The chunks the selector targets (in collection order for the item axis). */\n chunks: CollectedChunk[];\n};\n\n/**\n * Walks the loader tree following the selector and collects the chunk loaders\n * it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and\n * async ({@link resolveQualifiedDynamicContentAsync}) resolvers.\n */\nconst collectQualifiedChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n const qualifierTypes = loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY];\n const localeTree = loaderMap[locale] as\n | QualifiedDynamicLoaderTree\n | undefined;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n if (!localeTree) return { itemAxisOpen, missed: true, chunks: [] };\n\n const chunks: CollectedChunk[] = [];\n\n const walk = (\n node: QualifiedDynamicLoaderTree | DynamicDictionaryLoader,\n dimensions: DictionaryQualifierType[],\n segments: string[]\n ): boolean => {\n if (dimensions.length === 0) {\n chunks.push({\n cacheKey: `${key}.${locale}.${segments.join(COMPOSITE_ID_SEPARATOR)}`,\n loader: node as DynamicDictionaryLoader,\n });\n return true;\n }\n\n const [dimension, ...rest] = dimensions;\n const tree = node as QualifiedDynamicLoaderTree;\n\n if (dimension === 'item' && selector?.item === undefined) {\n // Open collection axis: fan out into every sibling chunk, ordered.\n for (const segment of Object.keys(tree).sort(\n (left, right) => Number(left) - Number(right)\n )) {\n walk(tree[segment]!, rest, [...segments, segment]);\n }\n return true;\n }\n\n // A variant with no chunk of its own falls back to the `default` chunk, so\n // only the entries that actually differ need to be emitted.\n const segment =\n dimension === 'variant'\n ? resolveEffectiveVariantId(\n serializeVariantChain(selector?.variant),\n (variantId) => tree[variantId] !== undefined\n )\n : String(selector?.item);\n\n const child = tree[segment];\n if (!child) return false;\n\n return walk(child, rest, [...segments, segment]);\n };\n\n const found = walk(localeTree, qualifierTypes, []);\n\n return { itemAxisOpen, missed: !found, chunks };\n};\n\n/**\n * Lists the chunks a selector targets in a qualified dynamic loader map,\n * without loading them — lets a caller warm a suspender cache ahead of render.\n *\n * @returns The targeted chunks, empty when a required coordinate is absent.\n */\nexport const getQualifiedDynamicChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunk[] => {\n const { missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n return missed ? [] : chunks;\n};\n\n/**\n * Resolves the content of a qualified dynamic loader map against a selector,\n * loading only the chunk(s) the selector actually targets.\n *\n * Walks the nested loader tree one dimension at a time (canonical order\n * `variant → item`): `variant` descends by the serialized id, falling back to\n * `default` when the selected variant has no chunk of its own, and `item`\n * either narrows to the selected index or — when no item is given — expands\n * into every sibling chunk (the collection axis). Semantics mirror\n * `resolveQualifiedDictionary` so dynamic and static modes behave alike.\n *\n * The Suspense mechanism is injected through `loadChunk` so the same logic\n * serves both the client (suspender cache) and the server (`react.use`). Every\n * targeted loader is started before the first chunk is read, so sibling chunks\n * load in parallel rather than waterfalling.\n *\n * @param loaderMap - The qualified dynamic loader map (entry point default export).\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param loadChunk - Reads a started chunk promise, suspending until it resolves.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContent = <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n loadChunk: (cacheKey: string, promise: Promise<Dictionary>) => Dictionary;\n transform: (dictionary: Dictionary) => Content;\n}): Content | Content[] | null => {\n const { loaderMap, key, locale, selector, loadChunk, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n // Start every loader before reading, so siblings load in parallel: the first\n // `loadChunk` that suspends throws, and would leave later loaders unstarted.\n const startedChunks = chunks.map(({ cacheKey, loader }) => ({\n cacheKey,\n promise: loader(),\n }));\n const dictionaries = startedChunks.map(({ cacheKey, promise }) =>\n loadChunk(cacheKey, promise)\n );\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n\n/**\n * Async counterpart of {@link resolveQualifiedDynamicContent} for frameworks\n * that load dictionaries with `await` instead of Suspense (Vue, Svelte, Lit,\n * vanilla). Awaits every targeted chunk in parallel, then resolves identically.\n *\n * @param loaderMap - The qualified dynamic loader map.\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContentAsync = async <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n transform: (dictionary: Dictionary) => Content;\n}): Promise<Content | Content[] | null> => {\n const { loaderMap, key, locale, selector, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n const dictionaries = await Promise.all(chunks.map(({ loader }) => loader()));\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n"],"mappings":";;;;;;;;;AAsDA,MAAa,+BACX,UAEA,OAAO,UAAU,YACjB,UAAU,QACVA,8DAA+B;;;;;;AAsBjC,MAAM,0BACJ,WACA,KACA,QACA,aACoB;CACpB,MAAM,iBAAiB,UAAUA;CACjC,MAAM,aAAa,UAAU;CAI7B,MAAM,eACJ,eAAe,SAAS,MAAM,KAAK,UAAU,SAAS;CAExD,IAAI,CAAC,YAAY,OAAO;EAAE;EAAc,QAAQ;EAAM,QAAQ,CAAC;CAAE;CAEjE,MAAM,SAA2B,CAAC;CAElC,MAAM,QACJ,MACA,YACA,aACY;EACZ,IAAI,WAAW,WAAW,GAAG;GAC3B,OAAO,KAAK;IACV,UAAU,GAAG,IAAI,GAAG,OAAO,GAAG,SAAS,QAA2B;IAClE,QAAQ;GACV,CAAC;GACD,OAAO;EACT;EAEA,MAAM,CAAC,WAAW,GAAG,QAAQ;EAC7B,MAAM,OAAO;EAEb,IAAI,cAAc,UAAU,UAAU,SAAS,QAAW;GAExD,KAAK,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,MACrC,MAAM,UAAU,OAAO,IAAI,IAAI,OAAO,KAAK,CAC9C,GACE,KAAK,KAAK,UAAW,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC;GAEnD,OAAO;EACT;EAIA,MAAM,UACJ,cAAc,YACVC,4EACEC,wEAAsB,UAAU,OAAO,IACtC,cAAc,KAAK,eAAe,MACrC,IACA,OAAO,UAAU,IAAI;EAE3B,MAAM,QAAQ,KAAK;EACnB,IAAI,CAAC,OAAO,OAAO;EAEnB,OAAO,KAAK,OAAO,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC;CACjD;CAIA,OAAO;EAAE;EAAc,QAAQ,CAFjB,KAAK,YAAY,gBAAgB,CAAC,CAEZ;EAAG;CAAO;AAChD;;;;;;;AAQA,MAAa,6BACX,WACA,KACA,QACA,aACqB;CACrB,MAAM,EAAE,QAAQ,WAAW,uBACzB,WACA,KACA,QACA,QACF;CAEA,OAAO,SAAS,CAAC,IAAI;AACvB;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kCAA2C,WAOtB;CAChC,MAAM,EAAE,WAAW,KAAK,QAAQ,UAAU,WAAW,cAAc;CAEnE,MAAM,EAAE,cAAc,QAAQ,WAAW,uBACvC,WACA,KACA,QACA,QACF;CAEA,IAAI,QAAQ,OAAO,eAAe,CAAC,IAAI;CAQvC,MAAM,eAJgB,OAAO,KAAK,EAAE,UAAU,cAAc;EAC1D;EACA,SAAS,OAAO;CAClB,EACiC,CAAC,CAAC,KAAK,EAAE,UAAU,cAClD,UAAU,UAAU,OAAO,CAC7B;CAEA,IAAI,cAAc,OAAO,aAAa,IAAI,SAAS;CAEnD,MAAM,CAAC,cAAc;CACrB,OAAO,aAAa,UAAU,UAAU,IAAI;AAC9C;;;;;;;;;;;;AAaA,MAAa,sCAAsC,OAAgB,WAMxB;CACzC,MAAM,EAAE,WAAW,KAAK,QAAQ,UAAU,cAAc;CAExD,MAAM,EAAE,cAAc,QAAQ,WAAW,uBACvC,WACA,KACA,QACA,QACF;CAEA,IAAI,QAAQ,OAAO,eAAe,CAAC,IAAI;CAEvC,MAAM,eAAe,MAAM,QAAQ,IAAI,OAAO,KAAK,EAAE,aAAa,OAAO,CAAC,CAAC;CAE3E,IAAI,cAAc,OAAO,aAAa,IAAI,SAAS;CAEnD,MAAM,CAAC,cAAc;CACrB,OAAO,aAAa,UAAU,UAAU,IAAI;AAC9C"}
1
+ {"version":3,"file":"qualifiedDynamicLoader.cjs","names":["QUALIFIER_DYNAMIC_TYPES_KEY","QUALIFIER_DYNAMIC_METADATA_KEY","compareItemSegments","serializeItem","resolveEffectiveVariantId","serializeVariantChain","matchQualifiedEntryIds"],"sources":["../../../src/dictionaryManipulator/qualifiedDynamicLoader.ts"],"sourcesContent":["import {\n QUALIFIER_DYNAMIC_METADATA_KEY,\n QUALIFIER_DYNAMIC_TYPES_KEY,\n} from '@intlayer/config/defaultValues';\nimport type {\n Dictionary,\n DictionaryMetadata,\n DictionaryQualifierType,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport {\n COMPOSITE_ID_SEPARATOR,\n compareItemSegments,\n matchQualifiedEntryIds,\n resolveEffectiveVariantId,\n serializeItem,\n serializeVariantChain,\n} from './qualifiedDictionary';\n\n/**\n * Marker properties of a qualified dynamic loader map: the ordered qualifier\n * dimensions, and the per-locale metadata index loaders. Defined in\n * `@intlayer/config` so the code generator and the build plugins can read them\n * without pulling the runtime in, and re-exported here where their consumers\n * live.\n */\nexport { QUALIFIER_DYNAMIC_METADATA_KEY, QUALIFIER_DYNAMIC_TYPES_KEY };\n\n/** Cache-key suffix of a metadata index chunk (never a valid composite id). */\nconst METADATA_INDEX_CACHE_SEGMENT = '#metadata';\n\n/**\n * A lazily-imported per-locale dictionary chunk loader.\n */\nexport type DynamicDictionaryLoader = () => Promise<Dictionary>;\n\n/**\n * Nested tree of chunk loaders: one nesting level per declared dimension (in\n * canonical order), leaves are loaders.\n */\nexport type QualifiedDynamicLoaderTree = {\n [segment: string]: QualifiedDynamicLoaderTree | DynamicDictionaryLoader;\n};\n\n/**\n * Default export shape of a generated dynamic entry point for a qualified key.\n * One nesting level per dimension under each locale, plus the dimension marker.\n *\n * ```ts\n * {\n * __intlayerQualifierTypes: ['variant', 'item'],\n * en: { promo: { '1': () => import('./json/x/promo/1/en.json'), … }, … },\n * fr: { … },\n * }\n * ```\n */\nexport type QualifiedDynamicLoaderMap = {\n [QUALIFIER_DYNAMIC_TYPES_KEY]: DictionaryQualifierType[];\n /** Per-locale loaders of the metadata index (absent in older builds). */\n [QUALIFIER_DYNAMIC_METADATA_KEY]?: Record<string, DynamicDictionaryLoader>;\n [locale: string]:\n | QualifiedDynamicLoaderTree\n | DictionaryQualifierType[]\n | Record<string, DynamicDictionaryLoader>\n | undefined;\n};\n\n/**\n * Type guard discriminating a qualified dynamic loader map (collections /\n * variants, possibly combined) from a plain dynamic loader map.\n */\nexport const isQualifiedDynamicLoaderMap = (\n value: unknown\n): value is QualifiedDynamicLoaderMap =>\n typeof value === 'object' &&\n value !== null &&\n QUALIFIER_DYNAMIC_TYPES_KEY in value;\n\n/** One targeted chunk: its stable cache key and lazy loader. */\nexport type CollectedChunk = {\n cacheKey: string;\n loader: DynamicDictionaryLoader;\n /** The chunk, already loaded by the entry point's preload. */\n preloaded?: Dictionary;\n};\n\n/** The chunks a dynamic read targets. */\nexport type CollectedChunks = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** True when a required coordinate is absent (result → [] or null). */\n missed: boolean;\n /** The chunks the selector targets (in collection order for the item axis). */\n chunks: CollectedChunk[];\n /** True when the single chunk is the metadata index, not entry chunks. */\n readsMetadataIndex?: boolean;\n};\n\n/**\n * Walks the loader tree following the selector and collects the chunk loaders\n * it targets.\n *\n * Walks one dimension at a time (canonical order `variant → item`): `variant`\n * descends by the serialized id, falling back to `default` when the selected\n * variant has no chunk of its own, and `item` either narrows to the selected\n * index or — when no item is given — expands into every sibling chunk (the\n * collection axis). Semantics mirror `resolveQualifiedDictionary` so dynamic\n * and static modes behave alike.\n */\nexport const collectQualifiedChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n const qualifierTypes = loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY];\n const localeTree = loaderMap[locale] as\n | QualifiedDynamicLoaderTree\n | undefined;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n // Listing a collection's metadata reads the per-locale index instead of\n // every entry chunk. A pinned entry keeps loading its own chunk, which\n // carries its metadata and is usually loaded for its content anyway.\n const metadataIndexLoader =\n selector?.metadataOnly && itemAxisOpen\n ? loaderMap[QUALIFIER_DYNAMIC_METADATA_KEY]?.[locale]\n : undefined;\n\n if (metadataIndexLoader) {\n return {\n itemAxisOpen,\n missed: false,\n readsMetadataIndex: true,\n chunks: [\n {\n cacheKey: `${key}.${locale}.${METADATA_INDEX_CACHE_SEGMENT}`,\n loader: metadataIndexLoader,\n },\n ],\n };\n }\n\n if (!localeTree) return { itemAxisOpen, missed: true, chunks: [] };\n\n const chunks: CollectedChunk[] = [];\n\n const walk = (\n node: QualifiedDynamicLoaderTree | DynamicDictionaryLoader,\n dimensions: DictionaryQualifierType[],\n segments: string[]\n ): boolean => {\n if (dimensions.length === 0) {\n chunks.push({\n cacheKey: `${key}.${locale}.${segments.join(COMPOSITE_ID_SEPARATOR)}`,\n loader: node as DynamicDictionaryLoader,\n });\n return true;\n }\n\n const [dimension, ...rest] = dimensions;\n const tree = node as QualifiedDynamicLoaderTree;\n\n if (dimension === 'item' && selector?.item === undefined) {\n // Open collection axis: fan out into every sibling chunk, ordered.\n for (const segment of Object.keys(tree).sort(compareItemSegments)) {\n walk(tree[segment]!, rest, [...segments, segment]);\n }\n return true;\n }\n\n // A pinned item descends by its serialized id. A variant with no chunk of\n // its own falls back to the `default` chunk, so only the entries that\n // actually differ need to be emitted.\n const segment =\n dimension === 'item' && selector?.item !== undefined\n ? serializeItem(selector.item)\n : resolveEffectiveVariantId(\n serializeVariantChain(selector?.variant),\n (variantId) => tree[variantId] !== undefined\n );\n\n const child = tree[segment];\n if (!child) return false;\n\n return walk(child, rest, [...segments, segment]);\n };\n\n const found = walk(localeTree, qualifierTypes, []);\n\n return { itemAxisOpen, missed: !found, chunks };\n};\n\n/**\n * Reads the metadata a selector targets out of a loaded metadata index, with\n * the same entry matching as static mode.\n *\n * @param metadataIndex - The loaded index chunk (`metadata` maps composite ids).\n * @param qualifierTypes - The key's dimensions, in canonical order.\n * @param selector - The selector splitting the dimensions.\n */\nexport const readMetadataIndex = (\n metadataIndex: Dictionary | undefined,\n qualifierTypes: DictionaryQualifierType[],\n selector: DictionarySelector | undefined\n): DictionaryMetadata[] => {\n const indexMetadata = (metadataIndex?.metadata ?? {}) as Record<\n string,\n DictionaryMetadata\n >;\n\n return matchQualifiedEntryIds(\n Object.keys(indexMetadata),\n qualifierTypes,\n selector\n ).matchedIds.map((compositeId) => indexMetadata[compositeId]!);\n};\n"],"mappings":";;;;;;AA6BA,MAAM,+BAA+B;;;;;AA0CrC,MAAa,+BACX,UAEA,OAAO,UAAU,YACjB,UAAU,QACVA,8DAA+B;;;;;;;;;;;;AAiCjC,MAAa,0BACX,WACA,KACA,QACA,aACoB;CACpB,MAAM,iBAAiB,UAAUA;CACjC,MAAM,aAAa,UAAU;CAI7B,MAAM,eACJ,eAAe,SAAS,MAAM,KAAK,UAAU,SAAS;CAKxD,MAAM,sBACJ,UAAU,gBAAgB,eACtB,UAAUC,8DAA+B,GAAG,UAC5C;CAEN,IAAI,qBACF,OAAO;EACL;EACA,QAAQ;EACR,oBAAoB;EACpB,QAAQ,CACN;GACE,UAAU,GAAG,IAAI,GAAG,OAAO,GAAG;GAC9B,QAAQ;EACV,CACF;CACF;CAGF,IAAI,CAAC,YAAY,OAAO;EAAE;EAAc,QAAQ;EAAM,QAAQ,CAAC;CAAE;CAEjE,MAAM,SAA2B,CAAC;CAElC,MAAM,QACJ,MACA,YACA,aACY;EACZ,IAAI,WAAW,WAAW,GAAG;GAC3B,OAAO,KAAK;IACV,UAAU,GAAG,IAAI,GAAG,OAAO,GAAG,SAAS,QAA2B;IAClE,QAAQ;GACV,CAAC;GACD,OAAO;EACT;EAEA,MAAM,CAAC,WAAW,GAAG,QAAQ;EAC7B,MAAM,OAAO;EAEb,IAAI,cAAc,UAAU,UAAU,SAAS,QAAW;GAExD,KAAK,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,KAAKC,qEAAmB,GAC9D,KAAK,KAAK,UAAW,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC;GAEnD,OAAO;EACT;EAKA,MAAM,U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