@intlayer/core 9.1.0 → 9.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/dictionaryManipulator/index.cjs +4 -0
- package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs +25 -2
- package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs +116 -14
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.test-d.cjs +92 -0
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.test-d.cjs.map +1 -0
- package/dist/cjs/index.cjs +4 -0
- package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
- package/dist/cjs/interpreter/getIntlayer.cjs.map +1 -1
- package/dist/esm/dictionaryManipulator/index.mjs +2 -2
- package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs +26 -3
- package/dist/esm/dictionaryManipulator/mergeQualifiedDictionaries.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs +113 -15
- package/dist/esm/dictionaryManipulator/qualifiedDictionary.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/qualifiedDictionary.test-d.mjs +92 -0
- package/dist/esm/dictionaryManipulator/qualifiedDictionary.test-d.mjs.map +1 -0
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
- package/dist/esm/interpreter/getIntlayer.mjs.map +1 -1
- package/dist/types/dictionaryManipulator/index.d.ts +2 -2
- package/dist/types/dictionaryManipulator/mergeQualifiedDictionaries.d.ts +4 -1
- package/dist/types/dictionaryManipulator/mergeQualifiedDictionaries.d.ts.map +1 -1
- package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts +66 -9
- package/dist/types/dictionaryManipulator/qualifiedDictionary.d.ts.map +1 -1
- package/dist/types/dictionaryManipulator/qualifiedDictionary.test-d.d.ts +1 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/interpreter/getDictionary.d.ts +2 -2
- package/dist/types/interpreter/getDictionary.d.ts.map +1 -1
- package/dist/types/interpreter/getIntlayer.d.ts +2 -2
- package/dist/types/interpreter/getIntlayer.d.ts.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getIntlayer.cjs","names":["parseDictionarySelector","getDictionarySelectorCacheKey","getDictionary"],"sources":["../../../src/interpreter/getIntlayer.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { DictionarySelector } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryResult,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport {\n getDictionarySelectorCacheKey,\n parseDictionarySelector,\n} from '../dictionaryManipulator/qualifiedDictionary';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n Plugins,\n} from './getContent';\nimport { getDictionary } from './getDictionary';\n\n/**\n * Creates a Recursive Proxy that returns the path of the accessed key\n * stringified. This prevents the app from crashing on undefined access.\n */\nconst createSafeFallback = (path = ''): any => {\n return new Proxy({} as Record<string | symbol, unknown>, {\n get: (_target, prop) => {\n if (\n prop === 'toJSON' ||\n prop === Symbol.toPrimitive ||\n prop === 'toString' ||\n prop === 'valueOf'\n ) {\n return () => path;\n }\n if (prop === 'then') {\n return undefined; // Prevent it from being treated as a Promise\n }\n if (prop === Symbol.iterator) {\n return function* () {\n yield path;\n };\n }\n\n // Recursively build the path (e.g., \"myDictionary.home.title\")\n const nextPath = path ? `${path}.${String(prop)}` : String(prop);\n return createSafeFallback(nextPath);\n },\n });\n};\n\nconst dictionaryCache = new Map<string, any>();\nconst warnedMissingDictionaries = new Set<string>();\n\n/**\n * Picks one dictionary by its key and returns its content for the given\n * locale or selector.\n *\n * The second argument is either a locale (`'fr'`) or a selector object:\n * - `{ item: 2 }` — collection item (omit `item` to get every item as array)\n * - `{ variant: 'black-friday' }` — named variant (omit for the `default` one)\n * - `{ variant: { id: 'prod_abc', userId: '123' } }` — structured variant\n * - `locale` can be combined with any selector: `{ item: 2, locale: 'fr' }`\n */\nexport const getIntlayer = <\n const T extends DictionaryKeys,\n const A extends
|
|
1
|
+
{"version":3,"file":"getIntlayer.cjs","names":["parseDictionarySelector","getDictionarySelectorCacheKey","getDictionary"],"sources":["../../../src/interpreter/getIntlayer.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type { DictionarySelector } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryResult,\n ExtractSelectorLocale,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport {\n getDictionarySelectorCacheKey,\n parseDictionarySelector,\n} from '../dictionaryManipulator/qualifiedDictionary';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n Plugins,\n} from './getContent';\nimport { getDictionary } from './getDictionary';\n\n/**\n * Creates a Recursive Proxy that returns the path of the accessed key\n * stringified. This prevents the app from crashing on undefined access.\n */\nconst createSafeFallback = (path = ''): any => {\n return new Proxy({} as Record<string | symbol, unknown>, {\n get: (_target, prop) => {\n if (\n prop === 'toJSON' ||\n prop === Symbol.toPrimitive ||\n prop === 'toString' ||\n prop === 'valueOf'\n ) {\n return () => path;\n }\n if (prop === 'then') {\n return undefined; // Prevent it from being treated as a Promise\n }\n if (prop === Symbol.iterator) {\n return function* () {\n yield path;\n };\n }\n\n // Recursively build the path (e.g., \"myDictionary.home.title\")\n const nextPath = path ? `${path}.${String(prop)}` : String(prop);\n return createSafeFallback(nextPath);\n },\n });\n};\n\nconst dictionaryCache = new Map<string, any>();\nconst warnedMissingDictionaries = new Set<string>();\n\n/**\n * Picks one dictionary by its key and returns its content for the given\n * locale or selector.\n *\n * The second argument is either a locale (`'fr'`) or a selector object:\n * - `{ item: 2 }` — collection item (omit `item` to get every item as array)\n * - `{ variant: 'black-friday' }` — named variant (omit for the `default` one)\n * - `{ variant: { id: 'prod_abc', userId: '123' } }` — structured variant\n * - `locale` can be combined with any selector: `{ item: 2, locale: 'fr' }`\n */\nexport const getIntlayer = <\n const T extends DictionaryKeys,\n const A extends DeclaredLocales | DictionarySelector = DeclaredLocales,\n>(\n key: T,\n localeOrSelector?: A,\n plugins?: Plugins[]\n): DeepTransformContent<\n DictionaryRegistryResult<T, A>,\n IInterpreterPluginState,\n ExtractSelectorLocale<A>\n> => {\n const dictionaries = getDictionaries();\n const dictionary = dictionaries[key as T];\n\n if (!dictionary && process.env.NODE_ENV === 'development') {\n if (!warnedMissingDictionaries.has(key as string)) {\n // Log a warning instead of throwing (so developers know it's missing)\n const logger = getAppLogger({ log });\n logger(\n typeof window === 'undefined'\n ? `Dictionary ${colorizeKey(key)} was not found. Using fallback proxy.`\n : `Dictionary ${key} was not found. Using fallback proxy.`,\n {\n level: 'warn',\n }\n );\n warnedMissingDictionaries.add(key as string);\n }\n\n return createSafeFallback(key as string);\n }\n\n let locale: LocalesValues | undefined;\n let selectorCacheKey = '';\n\n if (process.env.INTLAYER_DICTIONARY_SELECTOR !== 'false') {\n const parsed = parseDictionarySelector(localeOrSelector);\n locale = parsed.locale;\n selectorCacheKey = getDictionarySelectorCacheKey(parsed.selector);\n } else {\n // Selectors are unused in this project (build-time flag): the second\n // argument can only be a locale, so the selector parsing is dead code.\n locale = localeOrSelector as LocalesValues | undefined;\n }\n\n const cacheKey = `${key}_${locale ?? 'default'}_${selectorCacheKey}_${plugins ? 'custom_plugins' : 'default_plugins'}`;\n\n if (dictionaryCache.has(cacheKey)) {\n return dictionaryCache.get(cacheKey);\n }\n\n const result = getDictionary(dictionary, localeOrSelector, plugins);\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Ac,YAAY,kBAAkB,OAAO;CAElE,gBAAgB,IAAI,UAAU,MAAM;CAEpC,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { COMPOSITE_ID_SEPARATOR, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, parseDictionarySelector, reconstructQualifiedEntry, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant } from "./qualifiedDictionary.mjs";
|
|
1
|
+
import { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, parseDictionarySelector, reconstructQualifiedEntry, resolveDictionaryArgument, resolveProviderVariant, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, serializeVariantChain } from "./qualifiedDictionary.mjs";
|
|
2
2
|
import { editDictionaryByKeyPath } from "./editDictionaryByKeyPath.mjs";
|
|
3
3
|
import { getContentNodeByKeyPath } from "./getContentNodeByKeyPath.mjs";
|
|
4
4
|
import { getDefaultNode } from "./getDefaultNode.mjs";
|
|
@@ -13,4 +13,4 @@ import { removeContentNodeByKeyPath } from "./removeContentNodeByKeyPath.mjs";
|
|
|
13
13
|
import { renameContentNodeByKeyPath } from "./renameContentNodeByKeyPath.mjs";
|
|
14
14
|
import { updateNodeChildren } from "./updateNodeChildren.mjs";
|
|
15
15
|
|
|
16
|
-
export { COMPOSITE_ID_SEPARATOR, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, editDictionaryByKeyPath, getContentNodeByKeyPath, getDefaultNode, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getEmptyNode, getNodeChildren, getNodeType, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, mergeDictionaries, mergeQualifiedDictionaries, normalizeDictionaries, normalizeDictionary, orderDictionaries, parseDictionarySelector, reconstructQualifiedEntry, removeContentNodeByKeyPath, renameContentNodeByKeyPath, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, updateNodeChildren };
|
|
16
|
+
export { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, editDictionaryByKeyPath, getContentNodeByKeyPath, getDefaultNode, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getEmptyNode, getNodeChildren, getNodeType, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, mergeDictionaries, mergeQualifiedDictionaries, normalizeDictionaries, normalizeDictionary, orderDictionaries, parseDictionarySelector, reconstructQualifiedEntry, removeContentNodeByKeyPath, renameContentNodeByKeyPath, resolveDictionaryArgument, resolveProviderVariant, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, serializeVariantChain, updateNodeChildren };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierTypes } from "./qualifiedDictionary.mjs";
|
|
1
|
+
import { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierTypes } from "./qualifiedDictionary.mjs";
|
|
2
2
|
import { mergeDictionaries } from "./mergeDictionaries.mjs";
|
|
3
3
|
import { log } from "@intlayer/config/built";
|
|
4
4
|
import { colorizeKey, getAppLogger } from "@intlayer/config/logger";
|
|
@@ -14,7 +14,10 @@ import { colorizeKey, getAppLogger } from "@intlayer/config/logger";
|
|
|
14
14
|
* `variant → item`). Dictionaries are grouped by their composite id
|
|
15
15
|
* (one segment per dimension), merged within each group (locale completion /
|
|
16
16
|
* priority overrides preserved), and a `QualifiedDictionaryGroup` is returned.
|
|
17
|
-
* Unqualified siblings act as shared base content merged into every entry
|
|
17
|
+
* Unqualified siblings act as shared base content merged into every entry —
|
|
18
|
+
* and, on a variant-only key, also materialize the `default` entry when no
|
|
19
|
+
* declaration claims it. Every other variant entry then inherits from that
|
|
20
|
+
* `default` entry, so a variant only declares the fields it overrides.
|
|
18
21
|
*
|
|
19
22
|
* Every qualified entry must declare ALL dimensions of the group; an entry that
|
|
20
23
|
* declares only a subset is ambiguous and is rejected with an error log.
|
|
@@ -44,10 +47,30 @@ const mergeQualifiedDictionaries = (dictionaries) => {
|
|
|
44
47
|
entriesDictionaries.set(compositeId, existingEntries);
|
|
45
48
|
}
|
|
46
49
|
});
|
|
50
|
+
if (groupQualifierTypes.length === 1 && groupQualifierTypes[0] === "variant" && baseDictionaries.length > 0 && !entriesDictionaries.has("default")) entriesDictionaries.set(DEFAULT_VARIANT_ID, []);
|
|
47
51
|
const content = {};
|
|
48
52
|
let importMode;
|
|
53
|
+
const variantIndex = groupQualifierTypes.indexOf("variant");
|
|
54
|
+
/**
|
|
55
|
+
* The id of the entry a composite id inherits from — itself with its variant
|
|
56
|
+
* segment swapped for `default` (`'promo/2'` → `'default/2'`). `undefined`
|
|
57
|
+
* for the default entries themselves and for keys with no variant dimension.
|
|
58
|
+
*/
|
|
59
|
+
const getInheritedEntryId = (compositeId) => {
|
|
60
|
+
if (variantIndex === -1) return void 0;
|
|
61
|
+
const segments = compositeId.split("/");
|
|
62
|
+
if (segments[variantIndex] === "default") return void 0;
|
|
63
|
+
segments[variantIndex] = DEFAULT_VARIANT_ID;
|
|
64
|
+
return segments.join("/");
|
|
65
|
+
};
|
|
49
66
|
for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {
|
|
50
|
-
|
|
67
|
+
const inheritedEntryId = getInheritedEntryId(compositeId);
|
|
68
|
+
const inheritedDictionaries = inheritedEntryId ? entriesDictionaries.get(inheritedEntryId) ?? [] : [];
|
|
69
|
+
content[compositeId] = mergeDictionaries([
|
|
70
|
+
...qualifiedDictionaries,
|
|
71
|
+
...inheritedDictionaries,
|
|
72
|
+
...baseDictionaries
|
|
73
|
+
]).content;
|
|
51
74
|
const [firstQualified] = qualifiedDictionaries;
|
|
52
75
|
importMode ??= firstQualified?.importMode;
|
|
53
76
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeQualifiedDictionaries.mjs","names":[],"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 getDictionaryCompositeIds,\n getDictionaryQualifierTypes,\n QUALIFIER_ORDER,\n} from './qualifiedDictionary';\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 *\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 // `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 for (const [compositeId, qualifiedDictionaries] of entriesDictionaries) {\n //
|
|
1
|
+
{"version":3,"file":"mergeQualifiedDictionaries.mjs","names":[],"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 getDictionaryCompositeIds,\n getDictionaryQualifierTypes,\n QUALIFIER_ORDER,\n} from './qualifiedDictionary';\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":";;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,8BACX,iBAC0C;CAC1C,MAAM,qBAAqB,aAAa,IAAI,2BAA2B;CAEvE,MAAM,qCAAqB,IAAI,IAA6B;CAC5D,KAAK,MAAM,SAAS,oBAClB,KAAK,MAAM,QAAQ,OAAO,mBAAmB,IAAI,IAAI;CAIvD,MAAM,sBAAsB,gBAAgB,QAAQ,kBAClD,mBAAmB,IAAI,aAAa,CACtC;CAEA,IAAI,oBAAoB,WAAW,GACjC,OAAO,kBAAkB,YAAY;CAGvC,MAAM,YAAY,aAAa,EAAE,IAAI,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,eAA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CAC5C,CACF;CAEA,OAAO;EACL,KAAK,aAAa,EAAE,CAAE;EACtB,gBAAgB;EAChB;EACA,GAAI,eAAe,UAAa,EAAE,WAAW;EAC7C;CACF;AACF"}
|
|
@@ -11,6 +11,12 @@ const QUALIFIER_ORDER = ["variant", "item"];
|
|
|
11
11
|
*/
|
|
12
12
|
const COMPOSITE_ID_SEPARATOR = "/";
|
|
13
13
|
/**
|
|
14
|
+
* Identity of the implicit fallback variant. A selector that pins no variant
|
|
15
|
+
* resolves to it, and a variant that declares no entry of its own falls back to
|
|
16
|
+
* it — so a key only has to ship the entries that actually differ.
|
|
17
|
+
*/
|
|
18
|
+
const DEFAULT_VARIANT_ID = "default";
|
|
19
|
+
/**
|
|
14
20
|
* Characters kept verbatim in an encoded qualifier segment. Everything else is
|
|
15
21
|
* percent-encoded so a segment can never contain the composite-id separator
|
|
16
22
|
* (`/`), path-hostile characters (`\` `:` `*` `?` `"` `<` `>` `|`, control
|
|
@@ -49,7 +55,7 @@ const encodeSegmentText = (raw, unsafeChars) => {
|
|
|
49
55
|
* an object variant in a selector must equal the one declared on the dictionary.
|
|
50
56
|
*/
|
|
51
57
|
const serializeVariant = (variant) => {
|
|
52
|
-
if (variant === void 0) return
|
|
58
|
+
if (variant === void 0) return DEFAULT_VARIANT_ID;
|
|
53
59
|
if (typeof variant === "string") return encodeSegmentText(variant, SEGMENT_UNSAFE_CHARS);
|
|
54
60
|
return Object.keys(variant).sort().map((field) => `${encodeSegmentText(field, COMPONENT_UNSAFE_CHARS)}=${encodeSegmentText(String(variant[field]), COMPONENT_UNSAFE_CHARS)}`).join("&");
|
|
55
61
|
};
|
|
@@ -105,16 +111,53 @@ const getDictionaryCompositeIds = (dictionary, qualifierTypes) => {
|
|
|
105
111
|
return compositeIds;
|
|
106
112
|
};
|
|
107
113
|
/**
|
|
114
|
+
* Serializes the variant coordinate of a selector into the ordered list of
|
|
115
|
+
* candidate ids to try, so a single value and a preference chain share one code
|
|
116
|
+
* path downstream.
|
|
117
|
+
*
|
|
118
|
+
* - `undefined` → `['default']`
|
|
119
|
+
* - a single value → its one serialization
|
|
120
|
+
* - a chain → one serialization per entry, order preserved
|
|
121
|
+
*
|
|
122
|
+
* An empty chain is treated as "no variant pinned" (`['default']`) rather than
|
|
123
|
+
* as an unsatisfiable request.
|
|
124
|
+
*/
|
|
125
|
+
const serializeVariantChain = (variant) => {
|
|
126
|
+
if (!Array.isArray(variant)) return [serializeVariant(variant)];
|
|
127
|
+
if (variant.length === 0) return [DEFAULT_VARIANT_ID];
|
|
128
|
+
return variant.map(serializeVariant);
|
|
129
|
+
};
|
|
130
|
+
/**
|
|
131
|
+
* Resolves the variant id a selector actually targets among the ids a key
|
|
132
|
+
* declares — the sparse-override fallback.
|
|
133
|
+
*
|
|
134
|
+
* Candidates are tried in order and the first one the key declares wins.
|
|
135
|
+
* Otherwise the key falls back to its `default` entry, so a variant only has to
|
|
136
|
+
* be declared where its wording differs. When the key declares no `default`
|
|
137
|
+
* either, the first candidate is returned unchanged and the caller resolves to
|
|
138
|
+
* `null` / `[]`.
|
|
139
|
+
*
|
|
140
|
+
* @param requestedVariantIds - The serialized ids the selector asks for, in
|
|
141
|
+
* preference order (a single value is a 1-element
|
|
142
|
+
* list).
|
|
143
|
+
* @param isVariantIdDeclared - Whether the key declares an entry for an id.
|
|
144
|
+
*/
|
|
145
|
+
const resolveEffectiveVariantId = (requestedVariantIds, isVariantIdDeclared) => {
|
|
146
|
+
for (const requestedVariantId of requestedVariantIds) if (isVariantIdDeclared(requestedVariantId)) return requestedVariantId;
|
|
147
|
+
return isVariantIdDeclared("default") ? DEFAULT_VARIANT_ID : requestedVariantIds[0] ?? "default";
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
108
150
|
* Tests whether a composite entry id matches a selector across every declared
|
|
109
151
|
* dimension. Segments are compared in their encoded form (both the stored id
|
|
110
152
|
* and the selector go through {@link serializeVariant}). The `item` dimension
|
|
111
153
|
* matches any value when the selector does not provide one (open collection
|
|
112
|
-
* axis)
|
|
154
|
+
* axis); the `variant` dimension is compared against the already-resolved
|
|
155
|
+
* effective id, so the fallback is applied consistently across dimensions.
|
|
113
156
|
*/
|
|
114
|
-
const compositeIdMatchesSelector = (compositeId, qualifierTypes, selector) => {
|
|
157
|
+
const compositeIdMatchesSelector = (compositeId, qualifierTypes, selector, effectiveVariantId) => {
|
|
115
158
|
const segments = compositeId.split("/");
|
|
116
159
|
return qualifierTypes.every((qualifierType, index) => {
|
|
117
|
-
if (qualifierType === "variant") return segments[index] ===
|
|
160
|
+
if (qualifierType === "variant") return segments[index] === effectiveVariantId;
|
|
118
161
|
return selector?.item === void 0 || segments[index] === String(selector.item);
|
|
119
162
|
});
|
|
120
163
|
};
|
|
@@ -154,8 +197,10 @@ const reconstructQualifiedEntry = (group, compositeId) => {
|
|
|
154
197
|
* - Plain dictionary → returned as-is (selector ignored)
|
|
155
198
|
* - `item` declared but not selected → every matching entry ordered by index
|
|
156
199
|
* - `item` selected → the matching entry or null
|
|
157
|
-
* - `variant` defaults to the `default` entry when not selected
|
|
158
|
-
*
|
|
200
|
+
* - `variant` defaults to the `default` entry when not selected, and falls back
|
|
201
|
+
* to it when the selected variant declares no entry of its own; an object
|
|
202
|
+
* variant resolves only when the selector provides an equal object (or, again,
|
|
203
|
+
* through the `default` fallback)
|
|
159
204
|
*
|
|
160
205
|
* Dimensions compose: e.g. a variant × item key with `{ variant: 'promo' }`
|
|
161
206
|
* returns every promo item as an array; adding `{ item: 2 }` narrows to one.
|
|
@@ -164,7 +209,10 @@ const resolveQualifiedDictionary = (dictionaryOrGroup, selector) => {
|
|
|
164
209
|
if (!isQualifiedDictionaryGroup(dictionaryOrGroup)) return dictionaryOrGroup;
|
|
165
210
|
const { qualifierTypes, content } = dictionaryOrGroup;
|
|
166
211
|
const itemAxisOpen = qualifierTypes.includes("item") && selector?.item === void 0;
|
|
167
|
-
const
|
|
212
|
+
const compositeIds = Object.keys(content);
|
|
213
|
+
const variantIndex = qualifierTypes.indexOf("variant");
|
|
214
|
+
const effectiveVariantId = variantIndex === -1 ? DEFAULT_VARIANT_ID : resolveEffectiveVariantId(serializeVariantChain(selector?.variant), (variantId) => compositeIds.some((compositeId) => compositeId.split("/")[variantIndex] === variantId));
|
|
215
|
+
const matchedEntries = compositeIds.filter((compositeId) => compositeIdMatchesSelector(compositeId, qualifierTypes, selector, effectiveVariantId)).map((compositeId) => reconstructQualifiedEntry(dictionaryOrGroup, compositeId));
|
|
168
216
|
if (itemAxisOpen) return matchedEntries.sort((left, right) => (left.item ?? 0) - (right.item ?? 0));
|
|
169
217
|
return matchedEntries[0] ?? null;
|
|
170
218
|
};
|
|
@@ -180,6 +228,56 @@ const parseDictionarySelector = (localeOrSelector) => {
|
|
|
180
228
|
return { locale: localeOrSelector };
|
|
181
229
|
};
|
|
182
230
|
/**
|
|
231
|
+
* Resolves the variant a provider pins for one dictionary key.
|
|
232
|
+
*
|
|
233
|
+
* A string or a chain applies to every key as-is. A plain object is the per-key
|
|
234
|
+
* map: the entry for `dictionaryKey` wins, falling back to the reserved
|
|
235
|
+
* `default` entry, and `undefined` when neither is present (the key then
|
|
236
|
+
* resolves to its own `default` variant, i.e. the behaviour without a provider
|
|
237
|
+
* variant at all).
|
|
238
|
+
*
|
|
239
|
+
* A plain object is **always** the map here — never a structured variant value,
|
|
240
|
+
* which is why a structured variant has to be nested (`{ default: { id } }`).
|
|
241
|
+
*
|
|
242
|
+
* @param providerVariant - The `variant` prop of the surrounding provider.
|
|
243
|
+
* @param dictionaryKey - The key being read.
|
|
244
|
+
*/
|
|
245
|
+
const resolveProviderVariant = (providerVariant, dictionaryKey) => {
|
|
246
|
+
if (providerVariant === void 0) return void 0;
|
|
247
|
+
if (typeof providerVariant === "string" || Array.isArray(providerVariant)) return providerVariant;
|
|
248
|
+
const variantMap = providerVariant;
|
|
249
|
+
return variantMap[dictionaryKey] ?? variantMap["default"];
|
|
250
|
+
};
|
|
251
|
+
/**
|
|
252
|
+
* Builds the effective second argument of a dictionary read by layering the
|
|
253
|
+
* provider defaults under the call-site one — the single place the `locale` and
|
|
254
|
+
* `variant` context defaults are applied, shared by every framework binding.
|
|
255
|
+
*
|
|
256
|
+
* Precedence, per dimension independently:
|
|
257
|
+
* - a call-site selector always wins; `{ variant: 'x' }` **replaces** the
|
|
258
|
+
* provider chain rather than extending it
|
|
259
|
+
* - otherwise the provider value applies
|
|
260
|
+
*
|
|
261
|
+
* Returns a bare locale (not a selector object) whenever no variant is in play,
|
|
262
|
+
* so the existing fast path — and the cache keys built from it — are unchanged
|
|
263
|
+
* for projects that never use variants.
|
|
264
|
+
*/
|
|
265
|
+
const resolveDictionaryArgument = (params) => {
|
|
266
|
+
const { localeOrSelector, contextLocale, contextVariant, dictionaryKey } = params;
|
|
267
|
+
const callSelector = typeof localeOrSelector === "object" && localeOrSelector !== null ? localeOrSelector : void 0;
|
|
268
|
+
const locale = (callSelector ? callSelector.locale : localeOrSelector) ?? contextLocale;
|
|
269
|
+
const variant = callSelector?.variant ?? resolveProviderVariant(contextVariant, dictionaryKey);
|
|
270
|
+
if (variant === void 0) return callSelector ? {
|
|
271
|
+
...callSelector,
|
|
272
|
+
locale
|
|
273
|
+
} : locale;
|
|
274
|
+
return {
|
|
275
|
+
...callSelector,
|
|
276
|
+
locale,
|
|
277
|
+
variant
|
|
278
|
+
};
|
|
279
|
+
};
|
|
280
|
+
/**
|
|
183
281
|
* Builds a stable string identity of a selector (excluding `locale`), suitable
|
|
184
282
|
* for cache keys and memoization dependencies.
|
|
185
283
|
*/
|
|
@@ -187,7 +285,7 @@ const getDictionarySelectorCacheKey = (selector) => {
|
|
|
187
285
|
if (!selector) return "";
|
|
188
286
|
return Object.keys(selector).filter((selectorKey) => selectorKey !== "locale").sort().map((selectorKey) => {
|
|
189
287
|
const value = selector[selectorKey];
|
|
190
|
-
return `${selectorKey}:${selectorKey === "variant" ?
|
|
288
|
+
return `${selectorKey}:${selectorKey === "variant" ? serializeVariantChain(value).join(",") : String(value)}`;
|
|
191
289
|
}).join("|");
|
|
192
290
|
};
|
|
193
291
|
/**
|
|
@@ -231,7 +329,7 @@ const collectQualifiedChunks = (loaderMap, key, locale, selector) => {
|
|
|
231
329
|
for (const segment of Object.keys(tree).sort((left, right) => Number(left) - Number(right))) walk(tree[segment], rest, [...segments, segment]);
|
|
232
330
|
return true;
|
|
233
331
|
}
|
|
234
|
-
const segment = dimension === "variant" ?
|
|
332
|
+
const segment = dimension === "variant" ? resolveEffectiveVariantId(serializeVariantChain(selector?.variant), (variantId) => tree[variantId] !== void 0) : String(selector?.item);
|
|
235
333
|
const child = tree[segment];
|
|
236
334
|
if (!child) return false;
|
|
237
335
|
return walk(child, rest, [...segments, segment]);
|
|
@@ -247,11 +345,11 @@ const collectQualifiedChunks = (loaderMap, key, locale, selector) => {
|
|
|
247
345
|
* loading only the chunk(s) the selector actually targets.
|
|
248
346
|
*
|
|
249
347
|
* Walks the nested loader tree one dimension at a time (canonical order
|
|
250
|
-
* `variant → item`): `variant`
|
|
251
|
-
*
|
|
252
|
-
* or — when no item is given — expands
|
|
253
|
-
* axis). Semantics mirror
|
|
254
|
-
* static modes behave alike.
|
|
348
|
+
* `variant → item`): `variant` descends by the serialized id, falling back to
|
|
349
|
+
* `default` when the selected variant has no chunk of its own, and `item`
|
|
350
|
+
* either narrows to the selected index or — when no item is given — expands
|
|
351
|
+
* into every sibling chunk (the collection axis). Semantics mirror
|
|
352
|
+
* {@link resolveQualifiedDictionary} so dynamic and static modes behave alike.
|
|
255
353
|
*
|
|
256
354
|
* The Suspense mechanism is injected through `loadChunk` so the same logic
|
|
257
355
|
* serves both the client (suspender cache) and the server (`react.use`). Every
|
|
@@ -296,5 +394,5 @@ const resolveQualifiedDynamicContentAsync = async (params) => {
|
|
|
296
394
|
};
|
|
297
395
|
|
|
298
396
|
//#endregion
|
|
299
|
-
export { COMPOSITE_ID_SEPARATOR, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, parseDictionarySelector, reconstructQualifiedEntry, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant };
|
|
397
|
+
export { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, parseDictionarySelector, reconstructQualifiedEntry, resolveDictionaryArgument, resolveProviderVariant, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, serializeVariantChain };
|
|
300
398
|
//# sourceMappingURL=qualifiedDictionary.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"qualifiedDictionary.mjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n DictionaryVariantValue,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\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 * 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 * 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';\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 * 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\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).\n */\nconst compositeIdMatchesSelector = (\n compositeId: string,\n qualifierTypes: DictionaryQualifierType[],\n selector: DictionarySelector | undefined\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] === serializeVariant(selector?.variant);\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; an object\n * variant resolves only when the selector provides an equal object\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 matchedEntries = Object.keys(content)\n .filter((compositeId) =>\n compositeIdMatchesSelector(compositeId, qualifierTypes, selector)\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 };\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 ? serializeVariant(value as Parameters<typeof serializeVariant>[0])\n : String(value);\n return `${selectorKey}:${serialized}`;\n })\n .join('|');\n};\n\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Its presence distinguishes a qualified group loader map (a nested tree\n * of chunks) from a plain dynamic loader map (one chunk per `locale`). Prefixed\n * and unlikely to collide with a real locale code.\n */\nexport const QUALIFIER_DYNAMIC_TYPES_KEY = '__intlayerQualifierTypes';\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/**\n/** One targeted chunk: its stable cache key and lazy loader. */\ntype 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 const segment =\n dimension === 'variant'\n ? serializeVariant(selector?.variant)\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 * 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` defaults to `default` (or descends by the\n * serialized object identity), and `item` either narrows to the selected index\n * or — when no item is given — expands into every sibling chunk (the collection\n * axis). Semantics mirror {@link resolveQualifiedDictionary} so dynamic and\n * 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.\n const dictionaries = chunks.map(({ cacheKey, loader }) =>\n loadChunk(cacheKey, loader())\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":";;;;;;AAcA,MAAa,kBAAkB,CAC7B,WACA,MACF;;;;;AAMA,MAAa,yBAAyB;;;;;;;AAQtC,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,O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AAa,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;CAGvC,MAAM,eAAe,OAAO,KAAK,EAAE,UAAU,aAC3C,UAAU,UAAU,OAAO,CAAC,CAC9B;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":"qualifiedDictionary.mjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDictionary.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n DictionaryVariantChain,\n DictionaryVariantValue,\n ProviderVariant,\n ProviderVariantMap,\n QualifiedDictionaryGroup,\n} from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\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 * 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 * 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\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 */\nconst 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 };\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: ProviderVariant | 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?: ProviderVariant;\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\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Its presence distinguishes a qualified group loader map (a nested tree\n * of chunks) from a plain dynamic loader map (one chunk per `locale`). Prefixed\n * and unlikely to collide with a real locale code.\n */\nexport const QUALIFIER_DYNAMIC_TYPES_KEY = '__intlayerQualifierTypes';\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/**\n/** One targeted chunk: its stable cache key and lazy loader. */\ntype 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 * 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 * {@link 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.\n const dictionaries = chunks.map(({ cacheKey, loader }) =>\n loadChunk(cacheKey, loader())\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":";;;;;;AAiBA,MAAa,kBAAkB,CAC7B,WACA,MACF;;;;;AAMA,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;;;;;;;;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,IAAI,gBAAgB,CAAC,CAAC;AAClD;;;;;;AAOA,MAAa,+BACX,eAC8B;CAC9B,MAAM,qBAAgD,CAAC;CAEvD,IAAI,cAAc,WAAW,OAA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AAQ,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"}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { describe, expectTypeOf, it } from "vitest";
|
|
2
|
+
|
|
3
|
+
//#region src/dictionaryManipulator/qualifiedDictionary.test-d.ts
|
|
4
|
+
describe("ResolveQualifiedDictionaryContent", () => {
|
|
5
|
+
it("should resolve a plain dictionary to its content, ignoring the selector", () => {
|
|
6
|
+
expectTypeOf().toEqualTypeOf();
|
|
7
|
+
});
|
|
8
|
+
describe("variant", () => {
|
|
9
|
+
it("should resolve to the default entry when no variant is selected", () => {
|
|
10
|
+
expectTypeOf().toEqualTypeOf();
|
|
11
|
+
});
|
|
12
|
+
it("should resolve a locale-only selector like no selector", () => {
|
|
13
|
+
expectTypeOf().toEqualTypeOf();
|
|
14
|
+
});
|
|
15
|
+
it("should resolve a declared variant to its own entry", () => {
|
|
16
|
+
expectTypeOf().toEqualTypeOf();
|
|
17
|
+
});
|
|
18
|
+
it("should fall back to the default entry for an undeclared variant", () => {
|
|
19
|
+
expectTypeOf().toEqualTypeOf();
|
|
20
|
+
});
|
|
21
|
+
it("should resolve to null when no default entry is declared", () => {
|
|
22
|
+
expectTypeOf().toEqualTypeOf();
|
|
23
|
+
});
|
|
24
|
+
it("should resolve an object variant to its entry", () => {
|
|
25
|
+
expectTypeOf().toEqualTypeOf();
|
|
26
|
+
});
|
|
27
|
+
it("should resolve to null when an object-variant key has no default", () => {
|
|
28
|
+
expectTypeOf().toEqualTypeOf();
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
describe("item", () => {
|
|
32
|
+
it("should resolve to an array of every item when the axis is left open", () => {
|
|
33
|
+
expectTypeOf().toEqualTypeOf();
|
|
34
|
+
});
|
|
35
|
+
it("should narrow to the selected item", () => {
|
|
36
|
+
expectTypeOf().toEqualTypeOf();
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
describe("composite (variant × item)", () => {
|
|
40
|
+
it("should narrow to a single entry when both dimensions are pinned", () => {
|
|
41
|
+
expectTypeOf().toEqualTypeOf();
|
|
42
|
+
});
|
|
43
|
+
it("should fan the item axis out for the selected variant", () => {
|
|
44
|
+
expectTypeOf().toEqualTypeOf();
|
|
45
|
+
});
|
|
46
|
+
it("should fall back to the default variant then fan out its items", () => {
|
|
47
|
+
expectTypeOf().toEqualTypeOf();
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
describe("DictionarySelectorForGroup", () => {
|
|
52
|
+
it("should accept a variant this key declares", () => {
|
|
53
|
+
expectTypeOf().toExtend();
|
|
54
|
+
});
|
|
55
|
+
it("should accept a variant declared elsewhere in the project", () => {
|
|
56
|
+
expectTypeOf().toExtend();
|
|
57
|
+
});
|
|
58
|
+
it("should reject a variant no dictionary declares", () => {
|
|
59
|
+
expectTypeOf().not.toExtend();
|
|
60
|
+
});
|
|
61
|
+
it("should reject an object variant on a key that declares none", () => {
|
|
62
|
+
expectTypeOf().not.toExtend();
|
|
63
|
+
});
|
|
64
|
+
describe("object variants", () => {
|
|
65
|
+
it("should accept the object the key declares", () => {
|
|
66
|
+
expectTypeOf().toExtend();
|
|
67
|
+
});
|
|
68
|
+
it("should reject the serialized form as a string", () => {
|
|
69
|
+
expectTypeOf().not.toExtend();
|
|
70
|
+
});
|
|
71
|
+
it("should reject a partial or mismatched object", () => {
|
|
72
|
+
expectTypeOf().not.toExtend();
|
|
73
|
+
expectTypeOf().not.toExtend();
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
it("should reject an undeclared locale", () => {
|
|
77
|
+
expectTypeOf().not.toExtend();
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
describe("DictionarySelectorForGroup — keys without a default entry", () => {
|
|
81
|
+
it("should reject a project variant on a key with no default entry", () => {
|
|
82
|
+
expectTypeOf().not.toExtend();
|
|
83
|
+
expectTypeOf().not.toExtend();
|
|
84
|
+
expectTypeOf().not.toExtend();
|
|
85
|
+
});
|
|
86
|
+
it("should still accept the names such a key declares itself", () => {
|
|
87
|
+
expectTypeOf().toExtend();
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
//#endregion
|
|
92
|
+
//# sourceMappingURL=qualifiedDictionary.test-d.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"qualifiedDictionary.test-d.mjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDictionary.test-d.ts"],"sourcesContent":["import type {\n DictionarySelectorForGroup,\n ResolveQualifiedDictionaryContent,\n} from '@intlayer/types/dictionary';\nimport { describe, expectTypeOf, it } from 'vitest';\n\n/**\n * Compile-time counterpart of `qualifiedDictionary.test.ts`. The runtime\n * resolver and `ResolveQualifiedDictionaryContent` implement the same rules\n * twice — once in value space, once in type space — so a divergence between\n * them is invisible to the runtime suite. These assertions pin the type side.\n *\n * Groups are written the way `createTypes` emits them (`as const`, hence\n * readonly tuples of qualifier dimensions and literal composite-id keys).\n */\n\ntype LessonGroup = {\n key: 'lesson';\n qualifierTypes: readonly ['variant'];\n content: {\n default: { title: 'Lesson'; teacher: 'Teacher' };\n preschool: { title: 'Lesson'; teacher: 'Pedagogue' };\n };\n};\n\ntype NoDefaultGroup = {\n key: 'promoOnly';\n qualifierTypes: readonly ['variant'];\n content: { promo: { title: 'Promo' } };\n};\n\ntype BannerGroup = {\n key: 'banner';\n qualifierTypes: readonly ['variant', 'item'];\n content: {\n 'default/1': { title: 'D1' };\n 'promo/1': { title: 'P1' };\n 'promo/2': { title: 'P2' };\n };\n};\n\ntype FaqGroup = {\n key: 'faq';\n qualifierTypes: readonly ['item'];\n content: { '1': { question: 'Q1' }; '2': { question: 'Q2' } };\n};\n\ntype ProductGroup = {\n key: 'product';\n qualifierTypes: readonly ['variant'];\n content: { 'id=abc&userId=123': { name: 'ABC' } };\n};\n\ndescribe('ResolveQualifiedDictionaryContent', () => {\n it('should resolve a plain dictionary to its content, ignoring the selector', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<{ key: 'home'; content: { a: 'b' } }>\n >().toEqualTypeOf<{ a: 'b' }>();\n });\n\n describe('variant', () => {\n it('should resolve to the default entry when no variant is selected', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<LessonGroup>\n >().toEqualTypeOf<{ title: 'Lesson'; teacher: 'Teacher' }>();\n });\n\n it('should resolve a locale-only selector like no selector', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<LessonGroup, { locale: 'sv' }>\n >().toEqualTypeOf<{ title: 'Lesson'; teacher: 'Teacher' }>();\n });\n\n it('should resolve a declared variant to its own entry', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<LessonGroup, { variant: 'preschool' }>\n >().toEqualTypeOf<{ title: 'Lesson'; teacher: 'Pedagogue' }>();\n });\n\n it('should fall back to the default entry for an undeclared variant', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<\n LessonGroup,\n { variant: 'upperSecondary' }\n >\n >().toEqualTypeOf<{ title: 'Lesson'; teacher: 'Teacher' }>();\n });\n\n it('should resolve to null when no default entry is declared', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<\n NoDefaultGroup,\n { variant: 'unknown' }\n >\n >().toEqualTypeOf<null>();\n });\n\n it('should resolve an object variant to its entry', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<\n ProductGroup,\n { variant: { id: 'abc'; userId: '123' } }\n >\n >().toEqualTypeOf<{ name: 'ABC' }>();\n });\n\n it('should resolve to null when an object-variant key has no default', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<ProductGroup>\n >().toEqualTypeOf<null>();\n });\n });\n\n describe('item', () => {\n it('should resolve to an array of every item when the axis is left open', () => {\n expectTypeOf<ResolveQualifiedDictionaryContent<FaqGroup>>().toEqualTypeOf<\n ({ question: 'Q1' } | { question: 'Q2' })[]\n >();\n });\n\n it('should narrow to the selected item', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<FaqGroup, { item: 2 }>\n >().toEqualTypeOf<{ question: 'Q2' }>();\n });\n });\n\n describe('composite (variant × item)', () => {\n it('should narrow to a single entry when both dimensions are pinned', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<\n BannerGroup,\n { variant: 'promo'; item: 2 }\n >\n >().toEqualTypeOf<{ title: 'P2' }>();\n });\n\n it('should fan the item axis out for the selected variant', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<BannerGroup, { variant: 'promo' }>\n >().toEqualTypeOf<({ title: 'P1' } | { title: 'P2' })[]>();\n });\n\n it('should fall back to the default variant then fan out its items', () => {\n expectTypeOf<\n ResolveQualifiedDictionaryContent<BannerGroup, { variant: 'unknown' }>\n >().toEqualTypeOf<{ title: 'D1' }[]>();\n });\n });\n});\n\ndescribe('DictionarySelectorForGroup', () => {\n /** Stands in for the project-wide variant vocabulary (`DeclaredVariants`). */\n type ProjectVariants = 'default' | 'preschool' | 'promo';\n\n type LessonSelector = DictionarySelectorForGroup<\n LessonGroup,\n ProjectVariants\n >;\n\n it('should accept a variant this key declares', () => {\n expectTypeOf<{ variant: 'preschool' }>().toExtend<LessonSelector>();\n });\n\n it('should accept a variant declared elsewhere in the project', () => {\n // `LessonGroup` has no `promo` entry — it resolves to `default` at runtime,\n // which is what makes one session-wide variant usable across every key.\n expectTypeOf<{ variant: 'promo' }>().toExtend<LessonSelector>();\n });\n\n it('should reject a variant no dictionary declares', () => {\n expectTypeOf<{ variant: 'promoo' }>().not.toExtend<LessonSelector>();\n });\n\n it('should reject an object variant on a key that declares none', () => {\n expectTypeOf<{ variant: { id: 'abc' } }>().not.toExtend<LessonSelector>();\n });\n\n describe('object variants', () => {\n // `ProductGroup` stores `'id=abc&userId=123'` — the serialized form of\n // `{ id: 'abc', userId: '123' }`.\n type ProductSelector = DictionarySelectorForGroup<\n ProductGroup,\n ProjectVariants\n >;\n\n it('should accept the object the key declares', () => {\n expectTypeOf<{\n variant: { id: 'abc'; userId: '123' };\n }>().toExtend<ProductSelector>();\n });\n\n it('should reject the serialized form as a string', () => {\n // `'id=abc&userId=123'` is a storage encoding, not part of the API.\n expectTypeOf<{\n variant: 'id=abc&userId=123';\n }>().not.toExtend<ProductSelector>();\n });\n\n it('should reject a partial or mismatched object', () => {\n expectTypeOf<{\n variant: { id: 'abc' };\n }>().not.toExtend<ProductSelector>();\n expectTypeOf<{\n variant: { id: 'abc'; userId: 'other' };\n }>().not.toExtend<ProductSelector>();\n });\n });\n\n it('should reject an undeclared locale', () => {\n expectTypeOf<{ locale: 'not-a-locale' }>().not.toExtend<LessonSelector>();\n });\n});\n\ndescribe('DictionarySelectorForGroup — keys without a default entry', () => {\n type ProjectVariants = 'default' | 'preschool' | 'promo';\n\n // Declares only object variants: an undeclared name resolves to `null`, so\n // the project vocabulary must not be accepted here.\n type ProductSelector = DictionarySelectorForGroup<\n ProductGroup,\n ProjectVariants\n >;\n\n // Declares `promo` but no `default` — same reasoning.\n type NoDefaultSelector = DictionarySelectorForGroup<\n NoDefaultGroup,\n ProjectVariants\n >;\n\n it('should reject a project variant on a key with no default entry', () => {\n expectTypeOf<{ variant: 'promo' }>().not.toExtend<ProductSelector>();\n expectTypeOf<{ variant: 'default' }>().not.toExtend<ProductSelector>();\n expectTypeOf<{ variant: 'preschool' }>().not.toExtend<NoDefaultSelector>();\n });\n\n it('should still accept the names such a key declares itself', () => {\n expectTypeOf<{ variant: 'promo' }>().toExtend<NoDefaultSelector>();\n });\n});\n"],"mappings":";;;AAqDA,SAAS,2CAA2C;CAClD,GAAG,iFAAiF;EAClF,aAEE,CAAC,CAAC,cAA0B;C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