@intlayer/core 9.0.2 → 9.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/dictionaryManipulator/editDictionaryByKeyPath.cjs +5 -5
- package/dist/cjs/dictionaryManipulator/editDictionaryByKeyPath.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/getContentNodeByKeyPath.cjs +1 -1
- package/dist/cjs/dictionaryManipulator/getContentNodeByKeyPath.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/getDefaultNode.cjs +15 -0
- package/dist/cjs/dictionaryManipulator/getDefaultNode.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/getEmptyNode.cjs +1 -1
- package/dist/cjs/dictionaryManipulator/getEmptyNode.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/getNodeChildren.cjs +1 -1
- package/dist/cjs/dictionaryManipulator/getNodeChildren.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/getNodeType.cjs +30 -22
- package/dist/cjs/dictionaryManipulator/getNodeType.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/index.cjs +1 -0
- package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs +25 -2
- package/dist/cjs/dictionaryManipulator/mergeQualifiedDictionaries.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/qualifiedDictionary.cjs +42 -13
- 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/dictionaryManipulator/removeContentNodeByKeyPath.cjs +1 -1
- package/dist/cjs/dictionaryManipulator/removeContentNodeByKeyPath.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/renameContentNodeByKeyPath.cjs +1 -1
- package/dist/cjs/dictionaryManipulator/renameContentNodeByKeyPath.cjs.map +1 -1
- package/dist/cjs/dictionaryManipulator/updateNodeChildren.cjs +1 -1
- package/dist/cjs/dictionaryManipulator/updateNodeChildren.cjs.map +1 -1
- package/dist/cjs/index.cjs +8 -0
- package/dist/cjs/interpreter/getContent/getContent.cjs +2 -1
- package/dist/cjs/interpreter/getContent/getContent.cjs.map +1 -1
- package/dist/cjs/interpreter/getContent/index.cjs +1 -0
- package/dist/cjs/interpreter/getContent/plugins.cjs +28 -0
- package/dist/cjs/interpreter/getContent/plugins.cjs.map +1 -1
- package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
- package/dist/cjs/interpreter/getIntlayer.cjs.map +1 -1
- package/dist/cjs/interpreter/getSelect.cjs +36 -0
- package/dist/cjs/interpreter/getSelect.cjs.map +1 -0
- package/dist/cjs/interpreter/index.cjs +5 -0
- package/dist/cjs/messageFormat/ICU.cjs +23 -6
- package/dist/cjs/messageFormat/ICU.cjs.map +1 -1
- package/dist/cjs/messageFormat/i18next.cjs +24 -6
- package/dist/cjs/messageFormat/i18next.cjs.map +1 -1
- package/dist/cjs/messageFormat/resolveMessage.cjs +8 -0
- package/dist/cjs/messageFormat/resolveMessage.cjs.map +1 -1
- package/dist/cjs/messageFormat/vue-i18n.cjs +11 -2
- package/dist/cjs/messageFormat/vue-i18n.cjs.map +1 -1
- package/dist/cjs/transpiler/index.cjs +2 -0
- package/dist/cjs/transpiler/select/index.cjs +4 -0
- package/dist/cjs/transpiler/select/select.cjs +42 -0
- package/dist/cjs/transpiler/select/select.cjs.map +1 -0
- package/dist/esm/dictionaryManipulator/editDictionaryByKeyPath.mjs +5 -5
- package/dist/esm/dictionaryManipulator/editDictionaryByKeyPath.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/getContentNodeByKeyPath.mjs +1 -1
- package/dist/esm/dictionaryManipulator/getContentNodeByKeyPath.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/getDefaultNode.mjs +15 -0
- package/dist/esm/dictionaryManipulator/getDefaultNode.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/getEmptyNode.mjs +1 -1
- package/dist/esm/dictionaryManipulator/getEmptyNode.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/getNodeChildren.mjs +1 -1
- package/dist/esm/dictionaryManipulator/getNodeChildren.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/getNodeType.mjs +30 -22
- package/dist/esm/dictionaryManipulator/getNodeType.mjs.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 +42 -14
- 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/dictionaryManipulator/removeContentNodeByKeyPath.mjs +1 -1
- package/dist/esm/dictionaryManipulator/removeContentNodeByKeyPath.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/renameContentNodeByKeyPath.mjs +1 -1
- package/dist/esm/dictionaryManipulator/renameContentNodeByKeyPath.mjs.map +1 -1
- package/dist/esm/dictionaryManipulator/updateNodeChildren.mjs +1 -1
- package/dist/esm/dictionaryManipulator/updateNodeChildren.mjs.map +1 -1
- package/dist/esm/index.mjs +6 -3
- package/dist/esm/interpreter/getContent/getContent.mjs +3 -2
- package/dist/esm/interpreter/getContent/getContent.mjs.map +1 -1
- package/dist/esm/interpreter/getContent/index.mjs +2 -2
- package/dist/esm/interpreter/getContent/plugins.mjs +28 -1
- package/dist/esm/interpreter/getContent/plugins.mjs.map +1 -1
- package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
- package/dist/esm/interpreter/getIntlayer.mjs.map +1 -1
- package/dist/esm/interpreter/getSelect.mjs +34 -0
- package/dist/esm/interpreter/getSelect.mjs.map +1 -0
- package/dist/esm/interpreter/index.mjs +4 -2
- package/dist/esm/messageFormat/ICU.mjs +23 -6
- package/dist/esm/messageFormat/ICU.mjs.map +1 -1
- package/dist/esm/messageFormat/i18next.mjs +24 -6
- package/dist/esm/messageFormat/i18next.mjs.map +1 -1
- package/dist/esm/messageFormat/resolveMessage.mjs +8 -0
- package/dist/esm/messageFormat/resolveMessage.mjs.map +1 -1
- package/dist/esm/messageFormat/vue-i18n.mjs +11 -2
- package/dist/esm/messageFormat/vue-i18n.mjs.map +1 -1
- package/dist/esm/transpiler/index.mjs +2 -1
- package/dist/esm/transpiler/select/index.mjs +3 -0
- package/dist/esm/transpiler/select/select.mjs +41 -0
- package/dist/esm/transpiler/select/select.mjs.map +1 -0
- package/dist/types/dictionaryManipulator/getNodeType.d.ts.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 +16 -8
- 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 +6 -3
- package/dist/types/interpreter/getContent/getContent.d.ts.map +1 -1
- package/dist/types/interpreter/getContent/index.d.ts +2 -2
- package/dist/types/interpreter/getContent/plugins.d.ts +22 -1
- package/dist/types/interpreter/getContent/plugins.d.ts.map +1 -1
- 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/dist/types/interpreter/getSelect.d.ts +31 -0
- package/dist/types/interpreter/getSelect.d.ts.map +1 -0
- package/dist/types/interpreter/index.d.ts +4 -2
- package/dist/types/messageFormat/ICU.d.ts.map +1 -1
- package/dist/types/messageFormat/i18next.d.ts.map +1 -1
- package/dist/types/messageFormat/resolveMessage.d.ts.map +1 -1
- package/dist/types/messageFormat/vue-i18n.d.ts.map +1 -1
- package/dist/types/transpiler/index.d.ts +3 -1
- package/dist/types/transpiler/select/index.d.ts +2 -0
- package/dist/types/transpiler/select/select.d.ts +62 -0
- package/dist/types/transpiler/select/select.d.ts.map +1 -0
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"qualifiedDictionary.cjs","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,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,I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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.cjs","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 * 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 * Resolves the variant id a selector actually targets among the ids a key\n * declares — the sparse-override fallback.\n *\n * The requested id wins when the key declares it. Otherwise the key falls back\n * to its `default` entry, so a variant only has to be declared where its\n * wording differs. When the key declares no `default` either, the requested id\n * is returned unchanged and the caller resolves to `null` / `[]`.\n *\n * @param requestedVariantId - The serialized variant id the selector asks for.\n * @param isVariantIdDeclared - Whether the key declares an entry for an id.\n */\nconst resolveEffectiveVariantId = (\n requestedVariantId: string,\n isVariantIdDeclared: (variantId: string) => boolean\n): string => {\n if (isVariantIdDeclared(requestedVariantId)) return requestedVariantId;\n\n return isVariantIdDeclared(DEFAULT_VARIANT_ID)\n ? DEFAULT_VARIANT_ID\n : requestedVariantId;\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 serializeVariant(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 * 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 // 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 serializeVariant(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":";;;;;;;;AAcA,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,W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IA,OAAO;EAAE;EAAc,QAAQ,CAFjB,KAAK,YAAY,gBAAgB,CAAC,CAEZ;EAAG;CAAO;AAChD;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kCAA2C,WAOtB;CAChC,MAAM,EAAE,WAAW,KAAK,QAAQ,UAAU,WAAW,cAAc;CAEnE,MAAM,EAAE,cAAc,QAAQ,WAAW,uBACvC,WACA,KACA,QACA,QACF;CAEA,IAAI,QAAQ,OAAO,eAAe,CAAC,IAAI;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"}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
let vitest = require("vitest");
|
|
2
|
+
|
|
3
|
+
//#region src/dictionaryManipulator/qualifiedDictionary.test-d.ts
|
|
4
|
+
(0, vitest.describe)("ResolveQualifiedDictionaryContent", () => {
|
|
5
|
+
(0, vitest.it)("should resolve a plain dictionary to its content, ignoring the selector", () => {
|
|
6
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
7
|
+
});
|
|
8
|
+
(0, vitest.describe)("variant", () => {
|
|
9
|
+
(0, vitest.it)("should resolve to the default entry when no variant is selected", () => {
|
|
10
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
11
|
+
});
|
|
12
|
+
(0, vitest.it)("should resolve a locale-only selector like no selector", () => {
|
|
13
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
14
|
+
});
|
|
15
|
+
(0, vitest.it)("should resolve a declared variant to its own entry", () => {
|
|
16
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
17
|
+
});
|
|
18
|
+
(0, vitest.it)("should fall back to the default entry for an undeclared variant", () => {
|
|
19
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
20
|
+
});
|
|
21
|
+
(0, vitest.it)("should resolve to null when no default entry is declared", () => {
|
|
22
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
23
|
+
});
|
|
24
|
+
(0, vitest.it)("should resolve an object variant to its entry", () => {
|
|
25
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
26
|
+
});
|
|
27
|
+
(0, vitest.it)("should resolve to null when an object-variant key has no default", () => {
|
|
28
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
(0, vitest.describe)("item", () => {
|
|
32
|
+
(0, vitest.it)("should resolve to an array of every item when the axis is left open", () => {
|
|
33
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
34
|
+
});
|
|
35
|
+
(0, vitest.it)("should narrow to the selected item", () => {
|
|
36
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
(0, vitest.describe)("composite (variant × item)", () => {
|
|
40
|
+
(0, vitest.it)("should narrow to a single entry when both dimensions are pinned", () => {
|
|
41
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
42
|
+
});
|
|
43
|
+
(0, vitest.it)("should fan the item axis out for the selected variant", () => {
|
|
44
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
45
|
+
});
|
|
46
|
+
(0, vitest.it)("should fall back to the default variant then fan out its items", () => {
|
|
47
|
+
(0, vitest.expectTypeOf)().toEqualTypeOf();
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
(0, vitest.describe)("DictionarySelectorForGroup", () => {
|
|
52
|
+
(0, vitest.it)("should accept a variant this key declares", () => {
|
|
53
|
+
(0, vitest.expectTypeOf)().toExtend();
|
|
54
|
+
});
|
|
55
|
+
(0, vitest.it)("should accept a variant declared elsewhere in the project", () => {
|
|
56
|
+
(0, vitest.expectTypeOf)().toExtend();
|
|
57
|
+
});
|
|
58
|
+
(0, vitest.it)("should reject a variant no dictionary declares", () => {
|
|
59
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
60
|
+
});
|
|
61
|
+
(0, vitest.it)("should reject an object variant on a key that declares none", () => {
|
|
62
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
63
|
+
});
|
|
64
|
+
(0, vitest.describe)("object variants", () => {
|
|
65
|
+
(0, vitest.it)("should accept the object the key declares", () => {
|
|
66
|
+
(0, vitest.expectTypeOf)().toExtend();
|
|
67
|
+
});
|
|
68
|
+
(0, vitest.it)("should reject the serialized form as a string", () => {
|
|
69
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
70
|
+
});
|
|
71
|
+
(0, vitest.it)("should reject a partial or mismatched object", () => {
|
|
72
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
73
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
(0, vitest.it)("should reject an undeclared locale", () => {
|
|
77
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
(0, vitest.describe)("DictionarySelectorForGroup — keys without a default entry", () => {
|
|
81
|
+
(0, vitest.it)("should reject a project variant on a key with no default entry", () => {
|
|
82
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
83
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
84
|
+
(0, vitest.expectTypeOf)().not.toExtend();
|
|
85
|
+
});
|
|
86
|
+
(0, vitest.it)("should still accept the names such a key declares itself", () => {
|
|
87
|
+
(0, vitest.expectTypeOf)().toExtend();
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
//#endregion
|
|
92
|
+
//# sourceMappingURL=qualifiedDictionary.test-d.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"qualifiedDictionary.test-d.cjs","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":";;;qBAqDS,2CAA2C;CAClD,eAAG,iFAAiF;EAClF,yBAEE,CAAC,CAAC,cAA0B;CAChC,CAAC;CAED,qBAAS,iBAAiB;EACxB,eAAG,yEAAyE;GAC1E,yBAEE,CAAC,CAAC,cAAuD;EAC7D,CAAC;EAED,eAAG,gEAAgE;GACjE,yBAE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,sDAAsD;GACvD,yBAEG,CAAC,CAAC,IAAI,SAA0B;GACnC,yBAEG,CAAC,CAAC,IAAI,SAA0B;EACrC,CAAC;CACH,CAAC;CAED,eAAG,4CAA4C;EAC7C,yBAAyC,CAAC,CAAC,IAAI,SAAyB;CAC1E,CAAC;AACH,CAAC;qBAEQ,mEAAmE;CAgB1E,eAAG,wEAAwE;EACzE,yBAAmC,CAAC,CAAC,IAAI,SAA0B;EACnE,yBAAqC,CAAC,CAAC,IAAI,SAA0B;EACrE,yBAAuC,CAAC,CAAC,IAAI,SAA4B;CAC3E,CAAC;CAED,eAAG,kEAAkE;EACnE,yBAAmC,CAAC,CAAC,SAA4B;CACnE,CAAC;AACH,CAAC"}
|
|
@@ -14,7 +14,7 @@ const removeContentNodeByKeyPath = (dictionaryContent, keyPath) => {
|
|
|
14
14
|
lastKey = keyObj.key;
|
|
15
15
|
currentValue = currentValue[keyObj.key];
|
|
16
16
|
}
|
|
17
|
-
if (keyObj.type === _intlayer_types_nodeType.TRANSLATION || keyObj.type === _intlayer_types_nodeType.ENUMERATION || keyObj.type === _intlayer_types_nodeType.PLURAL || keyObj.type === _intlayer_types_nodeType.CONDITION) {
|
|
17
|
+
if (keyObj.type === _intlayer_types_nodeType.TRANSLATION || keyObj.type === _intlayer_types_nodeType.ENUMERATION || keyObj.type === _intlayer_types_nodeType.PLURAL || keyObj.type === _intlayer_types_nodeType.CONDITION || keyObj.type === _intlayer_types_nodeType.GENDER || keyObj.type === _intlayer_types_nodeType.SELECT) {
|
|
18
18
|
lastKey = keyObj.type;
|
|
19
19
|
currentValue = currentValue[keyObj.type][keyObj.key];
|
|
20
20
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"removeContentNodeByKeyPath.cjs","names":["NodeTypes"],"sources":["../../../src/dictionaryManipulator/removeContentNodeByKeyPath.ts"],"sourcesContent":["import type { ContentNode } from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\n\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\nexport const removeContentNodeByKeyPath = (\n dictionaryContent: ContentNode,\n keyPath: KeyPath[]\n): ContentNode => {\n let currentValue: any = dictionaryContent;\n let parentValue: any = null;\n let lastKey: string | number | null = null;\n\n for (const keyObj of keyPath) {\n parentValue = currentValue;\n\n if (keyObj.type === NodeTypes.OBJECT || keyObj.type === NodeTypes.ARRAY) {\n lastKey = keyObj.key;\n currentValue = currentValue[keyObj.key];\n }\n\n if (\n keyObj.type === NodeTypes.TRANSLATION ||\n keyObj.type === NodeTypes.ENUMERATION ||\n keyObj.type === NodeTypes.PLURAL ||\n keyObj.type === NodeTypes.CONDITION\n ) {\n lastKey = keyObj.type;\n currentValue = currentValue[keyObj.type][keyObj.key];\n }\n\n if (\n keyObj.type === NodeTypes.MARKDOWN ||\n keyObj.type === NodeTypes.REACT_NODE ||\n keyObj.type === NodeTypes.HTML ||\n keyObj.type === NodeTypes.INSERTION ||\n keyObj.type === NodeTypes.FILE\n ) {\n lastKey = keyObj.type;\n currentValue = currentValue[keyObj.type];\n }\n }\n\n if (parentValue && lastKey !== null) {\n if (Array.isArray(parentValue)) {\n parentValue.splice(lastKey as unknown as number, 1);\n } else {\n delete parentValue[lastKey];\n }\n }\n\n return dictionaryContent;\n};\n"],"mappings":";;;;;;AAKA,MAAa,8BACX,mBACA,YACgB;CAChB,IAAI,eAAoB;CACxB,IAAI,cAAmB;CACvB,IAAI,UAAkC;CAEtC,KAAK,MAAM,UAAU,SAAS;EAC5B,cAAc;EAEd,IAAI,OAAO,SAASA,yBAAU,UAAU,OAAO,SAASA,yBAAU,OAAO;GACvE,UAAU,OAAO;GACjB,eAAe,aAAa,OAAO;EACrC;EAEA,IACE,OAAO,SAASA,yBAAU,eAC1B,OAAO,SAASA,yBAAU,eAC1B,OAAO,SAASA,yBAAU,UAC1B,OAAO,SAASA,yBAAU,
|
|
1
|
+
{"version":3,"file":"removeContentNodeByKeyPath.cjs","names":["NodeTypes"],"sources":["../../../src/dictionaryManipulator/removeContentNodeByKeyPath.ts"],"sourcesContent":["import type { ContentNode } from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\n\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\nexport const removeContentNodeByKeyPath = (\n dictionaryContent: ContentNode,\n keyPath: KeyPath[]\n): ContentNode => {\n let currentValue: any = dictionaryContent;\n let parentValue: any = null;\n let lastKey: string | number | null = null;\n\n for (const keyObj of keyPath) {\n parentValue = currentValue;\n\n if (keyObj.type === NodeTypes.OBJECT || keyObj.type === NodeTypes.ARRAY) {\n lastKey = keyObj.key;\n currentValue = currentValue[keyObj.key];\n }\n\n if (\n keyObj.type === NodeTypes.TRANSLATION ||\n keyObj.type === NodeTypes.ENUMERATION ||\n keyObj.type === NodeTypes.PLURAL ||\n keyObj.type === NodeTypes.CONDITION ||\n keyObj.type === NodeTypes.GENDER ||\n keyObj.type === NodeTypes.SELECT\n ) {\n lastKey = keyObj.type;\n currentValue = currentValue[keyObj.type][keyObj.key];\n }\n\n if (\n keyObj.type === NodeTypes.MARKDOWN ||\n keyObj.type === NodeTypes.REACT_NODE ||\n keyObj.type === NodeTypes.HTML ||\n keyObj.type === NodeTypes.INSERTION ||\n keyObj.type === NodeTypes.FILE\n ) {\n lastKey = keyObj.type;\n currentValue = currentValue[keyObj.type];\n }\n }\n\n if (parentValue && lastKey !== null) {\n if (Array.isArray(parentValue)) {\n parentValue.splice(lastKey as unknown as number, 1);\n } else {\n delete parentValue[lastKey];\n }\n }\n\n return dictionaryContent;\n};\n"],"mappings":";;;;;;AAKA,MAAa,8BACX,mBACA,YACgB;CAChB,IAAI,eAAoB;CACxB,IAAI,cAAmB;CACvB,IAAI,UAAkC;CAEtC,KAAK,MAAM,UAAU,SAAS;EAC5B,cAAc;EAEd,IAAI,OAAO,SAASA,yBAAU,UAAU,OAAO,SAASA,yBAAU,OAAO;GACvE,UAAU,OAAO;GACjB,eAAe,aAAa,OAAO;EACrC;EAEA,IACE,OAAO,SAASA,yBAAU,eAC1B,OAAO,SAASA,yBAAU,eAC1B,OAAO,SAASA,yBAAU,UAC1B,OAAO,SAASA,yBAAU,aAC1B,OAAO,SAASA,yBAAU,UAC1B,OAAO,SAASA,yBAAU,QAC1B;GACA,UAAU,OAAO;GACjB,eAAe,aAAa,OAAO,KAAK,CAAC,OAAO;EAClD;EAEA,IACE,OAAO,SAASA,yBAAU,YAC1B,OAAO,SAASA,yBAAU,cAC1B,OAAO,SAASA,yBAAU,QAC1B,OAAO,SAASA,yBAAU,aAC1B,OAAO,SAASA,yBAAU,MAC1B;GACA,UAAU,OAAO;GACjB,eAAe,aAAa,OAAO;EACrC;CACF;CAEA,IAAI,eAAe,YAAY,MAC7B,IAAI,MAAM,QAAQ,WAAW,GAC3B,YAAY,OAAO,SAA8B,CAAC;MAElD,OAAO,YAAY;CAIvB,OAAO;AACT"}
|
|
@@ -14,7 +14,7 @@ const renameContentNodeByKeyPath = (dictionaryContent, newKey, keyPath) => {
|
|
|
14
14
|
lastKey = keyObj.key;
|
|
15
15
|
currentValue = currentValue[keyObj.key];
|
|
16
16
|
}
|
|
17
|
-
if (keyObj.type === _intlayer_types_nodeType.TRANSLATION || keyObj.type === _intlayer_types_nodeType.ENUMERATION || keyObj.type === _intlayer_types_nodeType.PLURAL || keyObj.type === _intlayer_types_nodeType.CONDITION) {
|
|
17
|
+
if (keyObj.type === _intlayer_types_nodeType.TRANSLATION || keyObj.type === _intlayer_types_nodeType.ENUMERATION || keyObj.type === _intlayer_types_nodeType.PLURAL || keyObj.type === _intlayer_types_nodeType.CONDITION || keyObj.type === _intlayer_types_nodeType.GENDER || keyObj.type === _intlayer_types_nodeType.SELECT) {
|
|
18
18
|
lastKey = keyObj.type;
|
|
19
19
|
currentValue = currentValue[keyObj.type][keyObj.key];
|
|
20
20
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renameContentNodeByKeyPath.cjs","names":["NodeTypes"],"sources":["../../../src/dictionaryManipulator/renameContentNodeByKeyPath.ts"],"sourcesContent":["import type { ContentNode } from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\n\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\nexport const renameContentNodeByKeyPath = (\n dictionaryContent: ContentNode,\n newKey: KeyPath['key'],\n keyPath: KeyPath[]\n): ContentNode => {\n let currentValue: any = dictionaryContent;\n let parentValue: any = null;\n let lastKey: string | number | null = null;\n\n for (const keyObj of keyPath) {\n parentValue = currentValue;\n\n if (keyObj.type === NodeTypes.OBJECT || keyObj.type === NodeTypes.ARRAY) {\n lastKey = keyObj.key;\n currentValue = currentValue[keyObj.key];\n }\n\n if (\n keyObj.type === NodeTypes.TRANSLATION ||\n keyObj.type === NodeTypes.ENUMERATION ||\n keyObj.type === NodeTypes.PLURAL ||\n keyObj.type === NodeTypes.CONDITION\n ) {\n lastKey = keyObj.type;\n currentValue = currentValue[keyObj.type][keyObj.key];\n }\n\n if (\n keyObj.type === NodeTypes.MARKDOWN ||\n keyObj.type === NodeTypes.REACT_NODE ||\n keyObj.type === NodeTypes.HTML ||\n keyObj.type === NodeTypes.INSERTION ||\n keyObj.type === NodeTypes.FILE\n ) {\n lastKey = keyObj.type;\n currentValue = currentValue[keyObj.type];\n }\n }\n\n // Assign the new value to the last key of the parent while preserving the order\n if (parentValue && lastKey !== null) {\n if (Array.isArray(parentValue)) {\n parentValue[lastKey as number] = currentValue;\n } else {\n const newParentValue: any = {};\n for (const key of Object.keys(parentValue)) {\n if (key === lastKey && typeof newKey !== 'undefined') {\n newParentValue[newKey] = currentValue;\n } else {\n newParentValue[key] = parentValue[key];\n }\n }\n // Replace the contents of parentValue with newParentValue\n Object.keys(parentValue).forEach((key) => {\n delete parentValue[key];\n });\n Object.assign(parentValue, newParentValue);\n }\n }\n\n return dictionaryContent;\n};\n"],"mappings":";;;;;;AAKA,MAAa,8BACX,mBACA,QACA,YACgB;CAChB,IAAI,eAAoB;CACxB,IAAI,cAAmB;CACvB,IAAI,UAAkC;CAEtC,KAAK,MAAM,UAAU,SAAS;EAC5B,cAAc;EAEd,IAAI,OAAO,SAASA,yBAAU,UAAU,OAAO,SAASA,yBAAU,OAAO;GACvE,UAAU,OAAO;GACjB,eAAe,aAAa,OAAO;EACrC;EAEA,IACE,OAAO,SAASA,yBAAU,eAC1B,OAAO,SAASA,yBAAU,eAC1B,OAAO,SAASA,yBAAU,UAC1B,OAAO,SAASA,yBAAU,
|
|
1
|
+
{"version":3,"file":"renameContentNodeByKeyPath.cjs","names":["NodeTypes"],"sources":["../../../src/dictionaryManipulator/renameContentNodeByKeyPath.ts"],"sourcesContent":["import type { ContentNode } from '@intlayer/types/dictionary';\nimport type { KeyPath } from '@intlayer/types/keyPath';\n\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\nexport const renameContentNodeByKeyPath = (\n dictionaryContent: ContentNode,\n newKey: KeyPath['key'],\n keyPath: KeyPath[]\n): ContentNode => {\n let currentValue: any = dictionaryContent;\n let parentValue: any = null;\n let lastKey: string | number | null = null;\n\n for (const keyObj of keyPath) {\n parentValue = currentValue;\n\n if (keyObj.type === NodeTypes.OBJECT || keyObj.type === NodeTypes.ARRAY) {\n lastKey = keyObj.key;\n currentValue = currentValue[keyObj.key];\n }\n\n if (\n keyObj.type === NodeTypes.TRANSLATION ||\n keyObj.type === NodeTypes.ENUMERATION ||\n keyObj.type === NodeTypes.PLURAL ||\n keyObj.type === NodeTypes.CONDITION ||\n keyObj.type === NodeTypes.GENDER ||\n keyObj.type === NodeTypes.SELECT\n ) {\n lastKey = keyObj.type;\n currentValue = currentValue[keyObj.type][keyObj.key];\n }\n\n if (\n keyObj.type === NodeTypes.MARKDOWN ||\n keyObj.type === NodeTypes.REACT_NODE ||\n keyObj.type === NodeTypes.HTML ||\n keyObj.type === NodeTypes.INSERTION ||\n keyObj.type === NodeTypes.FILE\n ) {\n lastKey = keyObj.type;\n currentValue = currentValue[keyObj.type];\n }\n }\n\n // Assign the new value to the last key of the parent while preserving the order\n if (parentValue && lastKey !== null) {\n if (Array.isArray(parentValue)) {\n parentValue[lastKey as number] = currentValue;\n } else {\n const newParentValue: any = {};\n for (const key of Object.keys(parentValue)) {\n if (key === lastKey && typeof newKey !== 'undefined') {\n newParentValue[newKey] = currentValue;\n } else {\n newParentValue[key] = parentValue[key];\n }\n }\n // Replace the contents of parentValue with newParentValue\n Object.keys(parentValue).forEach((key) => {\n delete parentValue[key];\n });\n Object.assign(parentValue, newParentValue);\n }\n }\n\n return dictionaryContent;\n};\n"],"mappings":";;;;;;AAKA,MAAa,8BACX,mBACA,QACA,YACgB;CAChB,IAAI,eAAoB;CACxB,IAAI,cAAmB;CACvB,IAAI,UAAkC;CAEtC,KAAK,MAAM,UAAU,SAAS;EAC5B,cAAc;EAEd,IAAI,OAAO,SAASA,yBAAU,UAAU,OAAO,SAASA,yBAAU,OAAO;GACvE,UAAU,OAAO;GACjB,eAAe,aAAa,OAAO;EACrC;EAEA,IACE,OAAO,SAASA,yBAAU,eAC1B,OAAO,SAASA,yBAAU,eAC1B,OAAO,SAASA,yBAAU,UAC1B,OAAO,SAASA,yBAAU,aAC1B,OAAO,SAASA,yBAAU,UAC1B,OAAO,SAASA,yBAAU,QAC1B;GACA,UAAU,OAAO;GACjB,eAAe,aAAa,OAAO,KAAK,CAAC,OAAO;EAClD;EAEA,IACE,OAAO,SAASA,yBAAU,YAC1B,OAAO,SAASA,yBAAU,cAC1B,OAAO,SAASA,yBAAU,QAC1B,OAAO,SAASA,yBAAU,aAC1B,OAAO,SAASA,yBAAU,MAC1B;GACA,UAAU,OAAO;GACjB,eAAe,aAAa,OAAO;EACrC;CACF;CAGA,IAAI,eAAe,YAAY,MAC7B,IAAI,MAAM,QAAQ,WAAW,GAC3B,YAAY,WAAqB;MAC5B;EACL,MAAM,iBAAsB,CAAC;EAC7B,KAAK,MAAM,OAAO,OAAO,KAAK,WAAW,GACvC,IAAI,QAAQ,WAAW,OAAO,WAAW,aACvC,eAAe,UAAU;OAEzB,eAAe,OAAO,YAAY;EAItC,OAAO,KAAK,WAAW,CAAC,CAAC,SAAS,QAAQ;GACxC,OAAO,YAAY;EACrB,CAAC;EACD,OAAO,OAAO,aAAa,cAAc;CAC3C;CAGF,OAAO;AACT"}
|
|
@@ -11,7 +11,7 @@ const updateNodeChildren = (section, newChildren) => {
|
|
|
11
11
|
if (typeof section?.nodeType === "string") {
|
|
12
12
|
const typedNode = section;
|
|
13
13
|
const content = typedNode[typedNode.nodeType];
|
|
14
|
-
if (typedNode.nodeType === _intlayer_types_nodeType.TRANSLATION || typedNode.nodeType === _intlayer_types_nodeType.ENUMERATION || typedNode.nodeType === _intlayer_types_nodeType.PLURAL || typedNode.nodeType === _intlayer_types_nodeType.CONDITION) {
|
|
14
|
+
if (typedNode.nodeType === _intlayer_types_nodeType.TRANSLATION || typedNode.nodeType === _intlayer_types_nodeType.ENUMERATION || typedNode.nodeType === _intlayer_types_nodeType.PLURAL || typedNode.nodeType === _intlayer_types_nodeType.CONDITION || typedNode.nodeType === _intlayer_types_nodeType.GENDER || typedNode.nodeType === _intlayer_types_nodeType.SELECT) {
|
|
15
15
|
const newContent = Object.entries(content).reduce((acc, [key]) => {
|
|
16
16
|
acc[key] = newChildren;
|
|
17
17
|
return acc;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"updateNodeChildren.cjs","names":["NodeTypes"],"sources":["../../../src/dictionaryManipulator/updateNodeChildren.ts"],"sourcesContent":["import type { ContentNode, TypedNode } from '@intlayer/types/dictionary';\n\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\nexport const updateNodeChildren = <\n T extends ContentNode,\n U extends ContentNode,\n>(\n section: T,\n newChildren: U\n): ContentNode => {\n if (typeof section === 'string') {\n return newChildren;\n }\n if (typeof section === 'number') {\n return newChildren;\n }\n if (typeof section === 'boolean') {\n return newChildren;\n }\n if (typeof (section as TypedNode)?.nodeType === 'string') {\n const typedNode = section as TypedNode;\n const content =\n typedNode[typedNode.nodeType as unknown as keyof typeof typedNode];\n\n if (\n typedNode.nodeType === NodeTypes.TRANSLATION ||\n typedNode.nodeType === NodeTypes.ENUMERATION ||\n typedNode.nodeType === NodeTypes.PLURAL ||\n typedNode.nodeType === NodeTypes.CONDITION\n ) {\n const newContent = Object.entries(content).reduce(\n (acc, [key]) => {\n acc[key] = newChildren;\n return acc;\n },\n {} as Record<string, ContentNode>\n );\n\n return {\n ...typedNode,\n [typedNode.nodeType]: newContent,\n };\n }\n\n if (typedNode.nodeType === NodeTypes.NESTED) {\n return typedNode;\n }\n\n return {\n ...typedNode,\n [typedNode.nodeType]: newChildren,\n };\n }\n\n if (!section || typeof section !== 'object') {\n return newChildren;\n }\n\n if (Array.isArray(section)) {\n return section.map(() => newChildren) as unknown as ContentNode;\n }\n\n return Object.entries(\n section as unknown as Record<string, ContentNode>\n ).reduce(\n (acc, [key]) => ({\n ...acc,\n [key]: newChildren,\n }),\n {} as Record<string, ContentNode>\n ) as unknown as ContentNode;\n};\n"],"mappings":";;;;;;AAIA,MAAa,sBAIX,SACA,gBACgB;CAChB,IAAI,OAAO,YAAY,UACrB,OAAO;CAET,IAAI,OAAO,YAAY,UACrB,OAAO;CAET,IAAI,OAAO,YAAY,WACrB,OAAO;CAET,IAAI,OAAQ,SAAuB,aAAa,UAAU;EACxD,MAAM,YAAY;EAClB,MAAM,UACJ,UAAU,UAAU;EAEtB,IACE,UAAU,aAAaA,yBAAU,eACjC,UAAU,aAAaA,yBAAU,eACjC,UAAU,aAAaA,yBAAU,UACjC,UAAU,aAAaA,yBAAU,
|
|
1
|
+
{"version":3,"file":"updateNodeChildren.cjs","names":["NodeTypes"],"sources":["../../../src/dictionaryManipulator/updateNodeChildren.ts"],"sourcesContent":["import type { ContentNode, TypedNode } from '@intlayer/types/dictionary';\n\nimport * as NodeTypes from '@intlayer/types/nodeType';\n\nexport const updateNodeChildren = <\n T extends ContentNode,\n U extends ContentNode,\n>(\n section: T,\n newChildren: U\n): ContentNode => {\n if (typeof section === 'string') {\n return newChildren;\n }\n if (typeof section === 'number') {\n return newChildren;\n }\n if (typeof section === 'boolean') {\n return newChildren;\n }\n if (typeof (section as TypedNode)?.nodeType === 'string') {\n const typedNode = section as TypedNode;\n const content =\n typedNode[typedNode.nodeType as unknown as keyof typeof typedNode];\n\n if (\n typedNode.nodeType === NodeTypes.TRANSLATION ||\n typedNode.nodeType === NodeTypes.ENUMERATION ||\n typedNode.nodeType === NodeTypes.PLURAL ||\n typedNode.nodeType === NodeTypes.CONDITION ||\n typedNode.nodeType === NodeTypes.GENDER ||\n typedNode.nodeType === NodeTypes.SELECT\n ) {\n const newContent = Object.entries(content).reduce(\n (acc, [key]) => {\n acc[key] = newChildren;\n return acc;\n },\n {} as Record<string, ContentNode>\n );\n\n return {\n ...typedNode,\n [typedNode.nodeType]: newContent,\n };\n }\n\n if (typedNode.nodeType === NodeTypes.NESTED) {\n return typedNode;\n }\n\n return {\n ...typedNode,\n [typedNode.nodeType]: newChildren,\n };\n }\n\n if (!section || typeof section !== 'object') {\n return newChildren;\n }\n\n if (Array.isArray(section)) {\n return section.map(() => newChildren) as unknown as ContentNode;\n }\n\n return Object.entries(\n section as unknown as Record<string, ContentNode>\n ).reduce(\n (acc, [key]) => ({\n ...acc,\n [key]: newChildren,\n }),\n {} as Record<string, ContentNode>\n ) as unknown as ContentNode;\n};\n"],"mappings":";;;;;;AAIA,MAAa,sBAIX,SACA,gBACgB;CAChB,IAAI,OAAO,YAAY,UACrB,OAAO;CAET,IAAI,OAAO,YAAY,UACrB,OAAO;CAET,IAAI,OAAO,YAAY,WACrB,OAAO;CAET,IAAI,OAAQ,SAAuB,aAAa,UAAU;EACxD,MAAM,YAAY;EAClB,MAAM,UACJ,UAAU,UAAU;EAEtB,IACE,UAAU,aAAaA,yBAAU,eACjC,UAAU,aAAaA,yBAAU,eACjC,UAAU,aAAaA,yBAAU,UACjC,UAAU,aAAaA,yBAAU,aACjC,UAAU,aAAaA,yBAAU,UACjC,UAAU,aAAaA,yBAAU,QACjC;GACA,MAAM,aAAa,OAAO,QAAQ,OAAO,CAAC,CAAC,QACxC,KAAK,CAAC,SAAS;IACd,IAAI,OAAO;IACX,OAAO;GACT,GACA,CAAC,CACH;GAEA,OAAO;IACL,GAAG;KACF,UAAU,WAAW;GACxB;EACF;EAEA,IAAI,UAAU,aAAaA,yBAAU,QACnC,OAAO;EAGT,OAAO;GACL,GAAG;IACF,UAAU,WAAW;EACxB;CACF;CAEA,IAAI,CAAC,WAAW,OAAO,YAAY,UACjC,OAAO;CAGT,IAAI,MAAM,QAAQ,OAAO,GACvB,OAAO,QAAQ,UAAU,WAAW;CAGtC,OAAO,OAAO,QACZ,OACF,CAAC,CAAC,QACC,KAAK,CAAC,UAAU;EACf,GAAG;GACF,MAAM;CACT,IACA,CAAC,CACH;AACF"}
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -3,6 +3,7 @@ const require_deepTransformPlugins_getEditedContent = require('./deepTransformPl
|
|
|
3
3
|
const require_interpreter_getCondition = require('./interpreter/getCondition.cjs');
|
|
4
4
|
const require_interpreter_getContent_deepTransform = require('./interpreter/getContent/deepTransform.cjs');
|
|
5
5
|
const require_interpreter_getEnumeration = require('./interpreter/getEnumeration.cjs');
|
|
6
|
+
const require_interpreter_getGender = require('./interpreter/getGender.cjs');
|
|
6
7
|
const require_interpreter_getInsertion = require('./interpreter/getInsertion.cjs');
|
|
7
8
|
const require_dictionaryManipulator_qualifiedDictionary = require('./dictionaryManipulator/qualifiedDictionary.cjs');
|
|
8
9
|
const require_interpreter_getDictionary = require('./interpreter/getDictionary.cjs');
|
|
@@ -18,6 +19,7 @@ const require_formatters_percentage = require('./formatters/percentage.cjs');
|
|
|
18
19
|
const require_formatters_relativeTime = require('./formatters/relativeTime.cjs');
|
|
19
20
|
const require_formatters_units = require('./formatters/units.cjs');
|
|
20
21
|
const require_interpreter_getPlural = require('./interpreter/getPlural.cjs');
|
|
22
|
+
const require_interpreter_getSelect = require('./interpreter/getSelect.cjs');
|
|
21
23
|
const require_interpreter_getTranslation = require('./interpreter/getTranslation.cjs');
|
|
22
24
|
const require_interpreter_interpolableNode = require('./interpreter/interpolableNode.cjs');
|
|
23
25
|
const require_interpreter_getContent_plugins = require('./interpreter/getContent/plugins.cjs');
|
|
@@ -39,6 +41,7 @@ const require_transpiler_markdown_validateMarkdown = require('./transpiler/markd
|
|
|
39
41
|
const require_transpiler_markdown_markdown = require('./transpiler/markdown/markdown.cjs');
|
|
40
42
|
const require_transpiler_nesting_nesting = require('./transpiler/nesting/nesting.cjs');
|
|
41
43
|
const require_transpiler_plural_plural = require('./transpiler/plural/plural.cjs');
|
|
44
|
+
const require_transpiler_select_select = require('./transpiler/select/select.cjs');
|
|
42
45
|
const require_transpiler_translation_translation = require('./transpiler/translation/translation.cjs');
|
|
43
46
|
const require_deepTransformPlugins_getFilterMissingTranslationsContent = require('./deepTransformPlugins/getFilterMissingTranslationsContent.cjs');
|
|
44
47
|
const require_deepTransformPlugins_getFilterTranslationsOnlyContent = require('./deepTransformPlugins/getFilterTranslationsOnlyContent.cjs');
|
|
@@ -117,6 +120,7 @@ exports.CR_NEWLINE_R = require_markdown_constants.CR_NEWLINE_R;
|
|
|
117
120
|
exports.CUSTOM_COMPONENT_R = require_markdown_constants.CUSTOM_COMPONENT_R;
|
|
118
121
|
exports.CachedIntl = require_utils_intl.CachedIntl;
|
|
119
122
|
exports.Intl = require_utils_intl.CachedIntl;
|
|
123
|
+
exports.DEFAULT_VARIANT_ID = require_dictionaryManipulator_qualifiedDictionary.DEFAULT_VARIANT_ID;
|
|
120
124
|
exports.DO_NOT_PROCESS_HTML_ELEMENTS = require_markdown_constants.DO_NOT_PROCESS_HTML_ELEMENTS;
|
|
121
125
|
exports.DURATION_DELAY_TRIGGER = require_markdown_constants.DURATION_DELAY_TRIGGER;
|
|
122
126
|
exports.FOOTNOTE_R = require_markdown_constants.FOOTNOTE_R;
|
|
@@ -245,6 +249,7 @@ exports.getFilterTranslationsOnlyContent = require_deepTransformPlugins_getFilte
|
|
|
245
249
|
exports.getFilterTranslationsOnlyDictionary = require_deepTransformPlugins_getFilterTranslationsOnlyContent.getFilterTranslationsOnlyDictionary;
|
|
246
250
|
exports.getFilteredLocalesContent = require_deepTransformPlugins_getFilteredLocalesContent.getFilteredLocalesContent;
|
|
247
251
|
exports.getFilteredLocalesDictionary = require_deepTransformPlugins_getFilteredLocalesContent.getFilteredLocalesDictionary;
|
|
252
|
+
exports.getGender = require_interpreter_getGender.getGender;
|
|
248
253
|
exports.getHTML = require_interpreter_getHTML.getHTML;
|
|
249
254
|
exports.getHTMLTextDir = require_localization_getHTMLTextDir.getHTMLTextDir;
|
|
250
255
|
exports.getInsertion = require_interpreter_getInsertion.getInsertion;
|
|
@@ -279,6 +284,7 @@ exports.getPrefix = require_localization_getPrefix.getPrefix;
|
|
|
279
284
|
exports.getReplacedValuesContent = require_deepTransformPlugins_getReplacedValuesContent.getReplacedValuesContent;
|
|
280
285
|
exports.getRewritePath = require_localization_rewriteUtils.getRewritePath;
|
|
281
286
|
exports.getRewriteRules = require_localization_rewriteUtils.getRewriteRules;
|
|
287
|
+
exports.getSelect = require_interpreter_getSelect.getSelect;
|
|
282
288
|
exports.getSplittedContent = require_deepTransformPlugins_getSplittedContent.getSplittedContent;
|
|
283
289
|
exports.getSplittedDictionaryContent = require_deepTransformPlugins_getSplittedContent.getSplittedDictionaryContent;
|
|
284
290
|
exports.getTranslation = require_interpreter_getTranslation.getTranslation;
|
|
@@ -355,6 +361,8 @@ exports.resolveQualifiedDictionary = require_dictionaryManipulator_qualifiedDict
|
|
|
355
361
|
exports.resolveQualifiedDynamicContent = require_dictionaryManipulator_qualifiedDictionary.resolveQualifiedDynamicContent;
|
|
356
362
|
exports.resolveQualifiedDynamicContentAsync = require_dictionaryManipulator_qualifiedDictionary.resolveQualifiedDynamicContentAsync;
|
|
357
363
|
exports.sanitizer = require_markdown_utils.sanitizer;
|
|
364
|
+
exports.select = require_transpiler_select_select.select;
|
|
365
|
+
exports.selectPlugin = require_interpreter_getContent_plugins.selectPlugin;
|
|
358
366
|
exports.serializeVariant = require_dictionaryManipulator_qualifiedDictionary.serializeVariant;
|
|
359
367
|
exports.setLocaleInStorage = require_utils_localeStorage.setLocaleInStorage;
|
|
360
368
|
exports.setLocaleInStorageClient = require_utils_localeStorage.setLocaleInStorageClient;
|
|
@@ -11,7 +11,8 @@ const getBasePlugins = (locale, fallback = true) => [
|
|
|
11
11
|
require_interpreter_getContent_plugins.insertionPlugin,
|
|
12
12
|
require_interpreter_getContent_plugins.nestedPlugin(locale ?? _intlayer_config_built.internationalization.defaultLocale),
|
|
13
13
|
require_interpreter_getContent_plugins.filePlugin,
|
|
14
|
-
require_interpreter_getContent_plugins.genderPlugin
|
|
14
|
+
require_interpreter_getContent_plugins.genderPlugin,
|
|
15
|
+
require_interpreter_getContent_plugins.selectPlugin
|
|
15
16
|
];
|
|
16
17
|
/**
|
|
17
18
|
* Transforms a node in a single pass, applying each plugin as needed.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getContent.cjs","names":["translationPlugin","internationalization","enumerationPlugin","conditionPlugin","insertionPlugin","nestedPlugin","filePlugin","genderPlugin","deepTransformNode"],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { deepTransformNode } from './deepTransform';\nimport {\n conditionPlugin,\n type DeepTransformContent,\n enumerationPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState,\n insertionPlugin,\n type NodeProps,\n nestedPlugin,\n type Plugins,\n translationPlugin,\n} from './plugins';\n\nexport const getBasePlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] =>\n [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n conditionPlugin,\n insertionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n ] as Plugins[];\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getContent = <\n const T extends ContentNode,\n const L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n nodeProps: NodeProps,\n plugins: Plugins[] = []\n) =>\n deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T, IInterpreterPluginState, L>;\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"getContent.cjs","names":["translationPlugin","internationalization","enumerationPlugin","conditionPlugin","insertionPlugin","nestedPlugin","filePlugin","genderPlugin","selectPlugin","deepTransformNode"],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { deepTransformNode } from './deepTransform';\nimport {\n conditionPlugin,\n type DeepTransformContent,\n enumerationPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState,\n insertionPlugin,\n type NodeProps,\n nestedPlugin,\n type Plugins,\n selectPlugin,\n translationPlugin,\n} from './plugins';\n\nexport const getBasePlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] =>\n [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n conditionPlugin,\n insertionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n selectPlugin,\n ] as Plugins[];\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getContent = <\n const T extends ContentNode,\n const L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n nodeProps: NodeProps,\n plugins: Plugins[] = []\n) =>\n deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T, IInterpreterPluginState, L>;\n"],"mappings":";;;;;;AAsBA,MAAa,kBACX,QACA,WAAoB,SAEpB;CACEA,yDACE,UAAUC,4CAAqB,eAC/B,WAAWA,4CAAqB,gBAAgB,MAClD;CACAC;CACAC;CACAC;CACAC,oDAAa,UAAUJ,4CAAqB,aAAa;CACzDK;CACAC;CACAC;AACF;;;;;;;AAQF,MAAa,cAIX,MACA,WACA,UAAqB,CAAC,MAEtBC,+DAAkB,MAAM;CACtB,GAAG;CACH;AACF,CAAC"}
|
|
@@ -14,4 +14,5 @@ exports.getContent = require_interpreter_getContent_getContent.getContent;
|
|
|
14
14
|
exports.insertionPlugin = require_interpreter_getContent_plugins.insertionPlugin;
|
|
15
15
|
exports.nestedPlugin = require_interpreter_getContent_plugins.nestedPlugin;
|
|
16
16
|
exports.pluralPlugin = require_interpreter_getContent_plugins.pluralPlugin;
|
|
17
|
+
exports.selectPlugin = require_interpreter_getContent_plugins.selectPlugin;
|
|
17
18
|
exports.translationPlugin = require_interpreter_getContent_plugins.translationPlugin;
|
|
@@ -6,6 +6,7 @@ const require_interpreter_getGender = require('../getGender.cjs');
|
|
|
6
6
|
const require_interpreter_getInsertion = require('../getInsertion.cjs');
|
|
7
7
|
const require_interpreter_getNesting = require('../getNesting.cjs');
|
|
8
8
|
const require_interpreter_getPlural = require('../getPlural.cjs');
|
|
9
|
+
const require_interpreter_getSelect = require('../getSelect.cjs');
|
|
9
10
|
const require_interpreter_getTranslation = require('../getTranslation.cjs');
|
|
10
11
|
const require_interpreter_interpolableNode = require('../interpolableNode.cjs');
|
|
11
12
|
let _intlayer_types_nodeType = require("@intlayer/types/nodeType");
|
|
@@ -206,6 +207,32 @@ const genderPlugin = process.env.INTLAYER_NODE_TYPE_GENDER === "false" ? fallbac
|
|
|
206
207
|
return (value) => require_interpreter_getGender.getGender(result, value);
|
|
207
208
|
}
|
|
208
209
|
};
|
|
210
|
+
/** Select plugin. Replaces node with a function that takes a string => content. */
|
|
211
|
+
const selectPlugin = process.env.INTLAYER_NODE_TYPE_SELECT === "false" ? fallbackPlugin : {
|
|
212
|
+
id: "select-plugin",
|
|
213
|
+
canHandle: (node) => typeof node === "object" && node?.nodeType === _intlayer_types_nodeType.SELECT,
|
|
214
|
+
transform: (node, props, deepTransformNode) => {
|
|
215
|
+
const original = node[_intlayer_types_nodeType.SELECT];
|
|
216
|
+
const result = {};
|
|
217
|
+
for (const key in original) {
|
|
218
|
+
const child = original[key];
|
|
219
|
+
result[key] = deepTransformNode(child, {
|
|
220
|
+
...props,
|
|
221
|
+
children: child,
|
|
222
|
+
keyPath: [...props.keyPath, {
|
|
223
|
+
type: _intlayer_types_nodeType.SELECT,
|
|
224
|
+
key
|
|
225
|
+
}]
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return (arg) => {
|
|
229
|
+
const value = typeof arg === "string" ? arg : arg?.value;
|
|
230
|
+
const subResult = require_interpreter_getSelect.getSelect(result, value);
|
|
231
|
+
if (typeof subResult === "function" && typeof arg === "object") return subResult(arg);
|
|
232
|
+
return subResult;
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
};
|
|
209
236
|
/** Nested plugin. Replaces node with the result of `getNesting`. */
|
|
210
237
|
const nestedPlugin = (locale) => process.env.INTLAYER_NODE_TYPE_NESTED === "false" ? fallbackPlugin : {
|
|
211
238
|
id: "nested-plugin",
|
|
@@ -234,5 +261,6 @@ exports.genderPlugin = genderPlugin;
|
|
|
234
261
|
exports.insertionPlugin = insertionPlugin;
|
|
235
262
|
exports.nestedPlugin = nestedPlugin;
|
|
236
263
|
exports.pluralPlugin = pluralPlugin;
|
|
264
|
+
exports.selectPlugin = selectPlugin;
|
|
237
265
|
exports.translationPlugin = translationPlugin;
|
|
238
266
|
//# sourceMappingURL=plugins.cjs.map
|