@intlayer/core 7.5.6 → 7.5.8
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 +10 -7
- package/dist/cjs/dictionaryManipulator/editDictionaryByKeyPath.cjs.map +1 -1
- package/dist/cjs/interpreter/getContent/getContent.cjs +1 -1
- package/dist/cjs/interpreter/getContent/getContent.cjs.map +1 -1
- package/dist/cjs/interpreter/getContent/plugins.cjs +6 -3
- package/dist/cjs/interpreter/getContent/plugins.cjs.map +1 -1
- package/dist/cjs/localization/getLocaleFromPath.cjs +26 -23
- package/dist/cjs/localization/getLocaleFromPath.cjs.map +1 -1
- package/dist/cjs/localization/getLocalizedUrl.cjs.map +1 -1
- package/dist/cjs/localization/getMultilingualUrls.cjs.map +1 -1
- package/dist/cjs/localization/getPrefix.cjs.map +1 -1
- package/dist/cjs/transpiler/insertion/getInsertionValues.cjs +1 -1
- package/dist/cjs/transpiler/insertion/getInsertionValues.cjs.map +1 -1
- package/dist/cjs/utils/intl.cjs +38 -35
- package/dist/cjs/utils/intl.cjs.map +1 -1
- package/dist/esm/dictionaryManipulator/editDictionaryByKeyPath.mjs +10 -7
- package/dist/esm/dictionaryManipulator/editDictionaryByKeyPath.mjs.map +1 -1
- package/dist/esm/interpreter/getContent/getContent.mjs +1 -1
- package/dist/esm/interpreter/getContent/getContent.mjs.map +1 -1
- package/dist/esm/interpreter/getContent/plugins.mjs +6 -3
- package/dist/esm/interpreter/getContent/plugins.mjs.map +1 -1
- package/dist/esm/localization/getLocaleFromPath.mjs +26 -23
- package/dist/esm/localization/getLocaleFromPath.mjs.map +1 -1
- package/dist/esm/localization/getLocalizedUrl.mjs.map +1 -1
- package/dist/esm/localization/getMultilingualUrls.mjs.map +1 -1
- package/dist/esm/localization/getPrefix.mjs.map +1 -1
- package/dist/esm/transpiler/insertion/getInsertionValues.mjs +1 -1
- package/dist/esm/transpiler/insertion/getInsertionValues.mjs.map +1 -1
- package/dist/esm/utils/intl.mjs +38 -35
- package/dist/esm/utils/intl.mjs.map +1 -1
- package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts +8 -8
- package/dist/types/deepTransformPlugins/getFilterMissingTranslationsContent.d.ts.map +1 -1
- package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts +8 -8
- package/dist/types/deepTransformPlugins/getFilterTranslationsOnlyContent.d.ts.map +1 -1
- package/dist/types/interpreter/getContent/getContent.d.ts.map +1 -1
- package/dist/types/interpreter/getContent/plugins.d.ts +1 -1
- package/dist/types/interpreter/getContent/plugins.d.ts.map +1 -1
- package/dist/types/localization/getLocaleFromPath.d.ts +14 -17
- package/dist/types/localization/getLocaleFromPath.d.ts.map +1 -1
- package/dist/types/localization/getLocalizedUrl.d.ts +2 -2
- package/dist/types/localization/getLocalizedUrl.d.ts.map +1 -1
- package/dist/types/localization/getMultilingualUrls.d.ts +2 -2
- package/dist/types/localization/getMultilingualUrls.d.ts.map +1 -1
- package/dist/types/localization/getPrefix.d.ts +3 -3
- package/dist/types/localization/getPrefix.d.ts.map +1 -1
- package/dist/types/messageFormat/ICU.d.ts.map +1 -1
- package/dist/types/transpiler/enumeration/enumeration.d.ts.map +1 -1
- package/dist/types/utils/intl.d.ts +3 -0
- package/dist/types/utils/intl.d.ts.map +1 -1
- package/package.json +6 -6
|
@@ -23,10 +23,10 @@ const editDictionaryByKeyPath = (dictionaryContent, keyPath, newValue) => {
|
|
|
23
23
|
currentValue = currentValue[keyObj.type][keyObj.key];
|
|
24
24
|
}
|
|
25
25
|
if (keyObj.type === _intlayer_types.NodeType.Enumeration || keyObj.type === _intlayer_types.NodeType.Condition) {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
if (keyObj.type !== _intlayer_types.NodeType.Enumeration) {
|
|
27
|
+
lastKeys = [keyObj.type, keyObj.key];
|
|
28
|
+
currentValue = currentValue[keyObj.type][keyObj.key];
|
|
29
|
+
}
|
|
30
30
|
}
|
|
31
31
|
if (keyObj.type === _intlayer_types.NodeType.Markdown || keyObj.type === _intlayer_types.NodeType.Insertion) {
|
|
32
32
|
lastKeys = [keyObj.type];
|
|
@@ -37,12 +37,15 @@ const editDictionaryByKeyPath = (dictionaryContent, keyPath, newValue) => {
|
|
|
37
37
|
lastKeys = ["content"];
|
|
38
38
|
currentValue = currentValue.content;
|
|
39
39
|
}
|
|
40
|
-
if (keyObj.type) {}
|
|
41
40
|
if (i === keyPath.length - 1 && parentValue && lastKeys.length > 0) {
|
|
42
41
|
let target = parentValue;
|
|
43
42
|
for (const key of lastKeys.slice(0, -1)) target = target[key];
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
const finalKey = lastKeys[lastKeys.length - 1];
|
|
44
|
+
if (typeof newValue === "undefined") if (Array.isArray(target)) {
|
|
45
|
+
const index = Number(finalKey);
|
|
46
|
+
if (!isNaN(index) && index >= 0 && index < target.length) target.splice(index, 1);
|
|
47
|
+
} else delete target[finalKey];
|
|
48
|
+
else target[finalKey] = newValue;
|
|
46
49
|
}
|
|
47
50
|
}
|
|
48
51
|
return dictionaryContent;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editDictionaryByKeyPath.cjs","names":["currentValue: any","parentValue: any","lastKeys: LastKeyType[]","NodeType"],"sources":["../../../src/dictionaryManipulator/editDictionaryByKeyPath.ts"],"sourcesContent":["import { type ContentNode, type KeyPath, NodeType } from '@intlayer/types';\n\ntype LastKeyType = string | number;\n\nexport const editDictionaryByKeyPath = (\n dictionaryContent: ContentNode,\n keyPath: KeyPath[],\n newValue: ContentNode\n): ContentNode => {\n let currentValue: any = dictionaryContent;\n let parentValue: any = null;\n let lastKeys: LastKeyType[] = [];\n\n if (keyPath.length === 0) {\n return newValue;\n }\n\n try {\n for (let i = 0; i < keyPath.length; i++) {\n const keyObj = keyPath[i];\n parentValue = currentValue;\n\n if (keyObj.type === NodeType.Object || keyObj.type === NodeType.Array) {\n lastKeys = [keyObj.key];\n if (\n !currentValue[keyObj.key] ||\n typeof currentValue[keyObj.key] !== 'object'\n ) {\n currentValue[keyObj.key] = {};\n }\n currentValue = currentValue[keyObj.key];\n }\n\n if (\n keyObj.type === NodeType.Translation ||\n keyObj.type === NodeType.Enumeration\n ) {\n lastKeys = [keyObj.type, keyObj.key];\n if (\n !currentValue[keyObj.type] ||\n typeof currentValue[keyObj.type] !== 'object'\n ) {\n currentValue[keyObj.type] = {};\n }\n if (\n !currentValue[keyObj.type][keyObj.key] ||\n typeof currentValue[keyObj.type][keyObj.key] !== 'object'\n ) {\n currentValue[keyObj.type][keyObj.key] = {};\n }\n currentValue = currentValue[keyObj.type][keyObj.key];\n }\n\n if (\n keyObj.type === NodeType.Enumeration ||\n keyObj.type === NodeType.Condition\n ) {\n
|
|
1
|
+
{"version":3,"file":"editDictionaryByKeyPath.cjs","names":["currentValue: any","parentValue: any","lastKeys: LastKeyType[]","NodeType"],"sources":["../../../src/dictionaryManipulator/editDictionaryByKeyPath.ts"],"sourcesContent":["import { type ContentNode, type KeyPath, NodeType } from '@intlayer/types';\n\ntype LastKeyType = string | number;\n\nexport const editDictionaryByKeyPath = (\n dictionaryContent: ContentNode,\n keyPath: KeyPath[],\n newValue: ContentNode\n): ContentNode => {\n let currentValue: any = dictionaryContent;\n let parentValue: any = null;\n let lastKeys: LastKeyType[] = [];\n\n if (keyPath.length === 0) {\n return newValue;\n }\n\n try {\n for (let i = 0; i < keyPath.length; i++) {\n const keyObj = keyPath[i];\n parentValue = currentValue;\n\n if (keyObj.type === NodeType.Object || keyObj.type === NodeType.Array) {\n lastKeys = [keyObj.key];\n if (\n !currentValue[keyObj.key] ||\n typeof currentValue[keyObj.key] !== 'object'\n ) {\n currentValue[keyObj.key] = {};\n }\n currentValue = currentValue[keyObj.key];\n }\n\n if (\n keyObj.type === NodeType.Translation ||\n keyObj.type === NodeType.Enumeration\n ) {\n lastKeys = [keyObj.type, keyObj.key];\n if (\n !currentValue[keyObj.type] ||\n typeof currentValue[keyObj.type] !== 'object'\n ) {\n currentValue[keyObj.type] = {};\n }\n if (\n !currentValue[keyObj.type][keyObj.key] ||\n typeof currentValue[keyObj.type][keyObj.key] !== 'object'\n ) {\n currentValue[keyObj.type][keyObj.key] = {};\n }\n currentValue = currentValue[keyObj.type][keyObj.key];\n }\n\n if (\n keyObj.type === NodeType.Enumeration ||\n keyObj.type === NodeType.Condition\n ) {\n // Note: Logic above already handles Enumeration, ensure no duplication in your actual file\n // or keep the specific block if your logic differs.\n // The important part is below in the final update block.\n\n // Assuming this block runs for Condition/Gender/etc:\n if (keyObj.type !== NodeType.Enumeration) {\n lastKeys = [keyObj.type, keyObj.key];\n currentValue = currentValue[keyObj.type][keyObj.key];\n }\n }\n\n if (\n keyObj.type === NodeType.Markdown ||\n keyObj.type === NodeType.Insertion\n ) {\n lastKeys = [keyObj.type];\n if (\n !currentValue[keyObj.type] ||\n typeof currentValue[keyObj.type] !== 'object'\n ) {\n currentValue[keyObj.type] = '';\n }\n currentValue = currentValue[keyObj.type];\n }\n\n if (keyObj.type === NodeType.File) {\n lastKeys = ['content'];\n currentValue = currentValue.content;\n }\n\n // Only update the value when processing the last key in the keyPath.\n if (i === keyPath.length - 1 && parentValue && lastKeys.length > 0) {\n let target = parentValue;\n\n // Drill down to the container holding the value to be changed\n for (const key of lastKeys.slice(0, -1)) {\n target = target[key];\n }\n\n const finalKey = lastKeys[lastKeys.length - 1];\n\n if (typeof newValue === 'undefined') {\n // Use splice for arrays to re-index the list, use delete for objects\n if (Array.isArray(target)) {\n const index = Number(finalKey);\n if (!isNaN(index) && index >= 0 && index < target.length) {\n target.splice(index, 1);\n }\n } else {\n delete target[finalKey];\n }\n } else {\n target[finalKey] = newValue;\n }\n }\n }\n\n return dictionaryContent;\n } catch (error) {\n console.error(\n 'Cannot edit dictionary by key path',\n { dictionaryContent, keyPath, newValue },\n error\n );\n return dictionaryContent;\n }\n};\n"],"mappings":";;;;AAIA,MAAa,2BACX,mBACA,SACA,aACgB;CAChB,IAAIA,eAAoB;CACxB,IAAIC,cAAmB;CACvB,IAAIC,WAA0B,EAAE;AAEhC,KAAI,QAAQ,WAAW,EACrB,QAAO;AAGT,KAAI;AACF,OAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;GACvC,MAAM,SAAS,QAAQ;AACvB,iBAAc;AAEd,OAAI,OAAO,SAASC,yBAAS,UAAU,OAAO,SAASA,yBAAS,OAAO;AACrE,eAAW,CAAC,OAAO,IAAI;AACvB,QACE,CAAC,aAAa,OAAO,QACrB,OAAO,aAAa,OAAO,SAAS,SAEpC,cAAa,OAAO,OAAO,EAAE;AAE/B,mBAAe,aAAa,OAAO;;AAGrC,OACE,OAAO,SAASA,yBAAS,eACzB,OAAO,SAASA,yBAAS,aACzB;AACA,eAAW,CAAC,OAAO,MAAM,OAAO,IAAI;AACpC,QACE,CAAC,aAAa,OAAO,SACrB,OAAO,aAAa,OAAO,UAAU,SAErC,cAAa,OAAO,QAAQ,EAAE;AAEhC,QACE,CAAC,aAAa,OAAO,MAAM,OAAO,QAClC,OAAO,aAAa,OAAO,MAAM,OAAO,SAAS,SAEjD,cAAa,OAAO,MAAM,OAAO,OAAO,EAAE;AAE5C,mBAAe,aAAa,OAAO,MAAM,OAAO;;AAGlD,OACE,OAAO,SAASA,yBAAS,eACzB,OAAO,SAASA,yBAAS,WAOzB;QAAI,OAAO,SAASA,yBAAS,aAAa;AACxC,gBAAW,CAAC,OAAO,MAAM,OAAO,IAAI;AACpC,oBAAe,aAAa,OAAO,MAAM,OAAO;;;AAIpD,OACE,OAAO,SAASA,yBAAS,YACzB,OAAO,SAASA,yBAAS,WACzB;AACA,eAAW,CAAC,OAAO,KAAK;AACxB,QACE,CAAC,aAAa,OAAO,SACrB,OAAO,aAAa,OAAO,UAAU,SAErC,cAAa,OAAO,QAAQ;AAE9B,mBAAe,aAAa,OAAO;;AAGrC,OAAI,OAAO,SAASA,yBAAS,MAAM;AACjC,eAAW,CAAC,UAAU;AACtB,mBAAe,aAAa;;AAI9B,OAAI,MAAM,QAAQ,SAAS,KAAK,eAAe,SAAS,SAAS,GAAG;IAClE,IAAI,SAAS;AAGb,SAAK,MAAM,OAAO,SAAS,MAAM,GAAG,GAAG,CACrC,UAAS,OAAO;IAGlB,MAAM,WAAW,SAAS,SAAS,SAAS;AAE5C,QAAI,OAAO,aAAa,YAEtB,KAAI,MAAM,QAAQ,OAAO,EAAE;KACzB,MAAM,QAAQ,OAAO,SAAS;AAC9B,SAAI,CAAC,MAAM,MAAM,IAAI,SAAS,KAAK,QAAQ,OAAO,OAChD,QAAO,OAAO,OAAO,EAAE;UAGzB,QAAO,OAAO;QAGhB,QAAO,YAAY;;;AAKzB,SAAO;UACA,OAAO;AACd,UAAQ,MACN,sCACA;GAAE;GAAmB;GAAS;GAAU,EACxC,MACD;AACD,SAAO"}
|
|
@@ -18,7 +18,7 @@ const getContent = (node, nodeProps, locale) => {
|
|
|
18
18
|
require_interpreter_getContent_plugins.translationPlugin(locale ?? defaultLocale, defaultLocale),
|
|
19
19
|
require_interpreter_getContent_plugins.enumerationPlugin,
|
|
20
20
|
require_interpreter_getContent_plugins.conditionPlugin,
|
|
21
|
-
require_interpreter_getContent_plugins.nestedPlugin,
|
|
21
|
+
require_interpreter_getContent_plugins.nestedPlugin(locale ?? defaultLocale),
|
|
22
22
|
require_interpreter_getContent_plugins.filePlugin,
|
|
23
23
|
...nodeProps.plugins ?? []
|
|
24
24
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getContent.cjs","names":["configuration","plugins: Plugins[]","insertionPlugin","translationPlugin","enumerationPlugin","conditionPlugin","nestedPlugin","filePlugin","deepTransformNode"],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport
|
|
1
|
+
{"version":3,"file":"getContent.cjs","names":["configuration","plugins: Plugins[]","insertionPlugin","translationPlugin","enumerationPlugin","conditionPlugin","nestedPlugin","filePlugin","deepTransformNode"],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type {\n ContentNode,\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types';\nimport { deepTransformNode } from './deepTransform';\nimport {\n conditionPlugin,\n type DeepTransformContent,\n enumerationPlugin,\n filePlugin,\n type IInterpreterPluginState,\n insertionPlugin,\n type NodeProps,\n nestedPlugin,\n type Plugins,\n translationPlugin,\n} from './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 T extends ContentNode,\n L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n nodeProps: NodeProps,\n locale?: L\n) => {\n const defaultLocale = configuration?.internationalization?.defaultLocale;\n\n const plugins: Plugins[] = [\n insertionPlugin,\n translationPlugin(locale ?? defaultLocale, defaultLocale),\n enumerationPlugin,\n conditionPlugin,\n nestedPlugin(locale ?? defaultLocale),\n filePlugin,\n ...(nodeProps.plugins ?? []),\n ];\n\n return deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T, IInterpreterPluginState, L>;\n};\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAa,cAIX,MACA,WACA,WACG;CACH,MAAM,gBAAgBA,gCAAe,sBAAsB;CAE3D,MAAMC,UAAqB;EACzBC;EACAC,yDAAkB,UAAU,eAAe,cAAc;EACzDC;EACAC;EACAC,oDAAa,UAAU,cAAc;EACrCC;EACA,GAAI,UAAU,WAAW,EAAE;EAC5B;AAED,QAAOC,+DAAkB,MAAM;EAC7B,GAAG;EACH;EACD,CAAC"}
|
|
@@ -123,11 +123,14 @@ const insertionPlugin = {
|
|
|
123
123
|
}
|
|
124
124
|
};
|
|
125
125
|
/** Nested plugin. Replaces node with the result of `getNesting`. */
|
|
126
|
-
const nestedPlugin = {
|
|
126
|
+
const nestedPlugin = (locale) => ({
|
|
127
127
|
id: "nested-plugin",
|
|
128
128
|
canHandle: (node) => typeof node === "object" && node?.nodeType === _intlayer_types.NodeType.Nested,
|
|
129
|
-
transform: (node, props) => require_interpreter_getNesting.getNesting(node.nested.dictionaryKey, node.nested.path,
|
|
130
|
-
|
|
129
|
+
transform: (node, props) => require_interpreter_getNesting.getNesting(node.nested.dictionaryKey, node.nested.path, {
|
|
130
|
+
...props,
|
|
131
|
+
locale: locale ?? props.locale
|
|
132
|
+
})
|
|
133
|
+
});
|
|
131
134
|
/** File plugin. Replaces node with the result of `getNesting`. */
|
|
132
135
|
const filePlugin = {
|
|
133
136
|
id: "file-plugin",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.cjs","names":["NodeType","getTranslation","enumerationPlugin: Plugins","getEnumeration","conditionPlugin: Plugins","getCondition","genderPlugin: Plugins","getGender","insertionPlugin: Plugins","newKeyPath: KeyPath[]","insertionStringPlugin: Plugins","node","deepTransformNode","children","getInsertion","nestedPlugin: Plugins","getNesting","filePlugin: Plugins"],"sources":["../../../../src/interpreter/getContent/plugins.ts"],"sourcesContent":["import {\n type DeclaredLocales,\n type DictionaryKeys,\n type KeyPath,\n type Locale,\n type LocalesValues,\n NodeType,\n} from '@intlayer/types';\nimport type {\n ConditionContent,\n EnumerationContent,\n FileContent,\n Gender,\n GenderContent,\n InsertionContent,\n NestedContent,\n TranslationContent,\n} from '../../transpiler';\nimport { getCondition } from '../getCondition';\nimport { getEnumeration } from '../getEnumeration';\nimport { getGender } from '../getGender';\nimport { getInsertion } from '../getInsertion';\nimport { type GetNestingResult, getNesting } from '../getNesting';\nimport { getTranslation } from '../getTranslation';\n\n/** ---------------------------------------------\n * PLUGIN DEFINITION\n * --------------------------------------------- */\n\n/**\n * A plugin/transformer that can optionally transform a node during a single DFS pass.\n * - `canHandle` decides if the node is transformable by this plugin.\n * - `transform` returns the transformed node (and does not recurse further).\n *\n * > `transformFn` is a function that can be used to deeply transform inside the plugin.\n */\nexport type Plugins = {\n id: string;\n canHandle: (node: any) => boolean;\n transform: (\n node: any,\n props: NodeProps,\n transformFn: (node: any, props: NodeProps) => any\n ) => any;\n};\n\n/** ---------------------------------------------\n * TRANSLATION PLUGIN\n * --------------------------------------------- */\n\nexport type TranslationCond<T, S, L extends LocalesValues> = T extends {\n nodeType: NodeType | string;\n [NodeType.Translation]: infer U;\n}\n ? U extends Record<PropertyKey, unknown>\n ? L extends keyof U\n ? DeepTransformContent<U[L], S>\n : DeepTransformContent<U[keyof U], S>\n : never\n : never;\n\n/** Translation plugin. Replaces node with a locale string if nodeType = Translation. */\nexport const translationPlugin = (\n locale: LocalesValues,\n fallback?: LocalesValues,\n onContentNotFound?: (\n locale: LocalesValues,\n fallback: LocalesValues,\n keyPath: KeyPath[]\n ) => void\n): Plugins => ({\n id: 'translation-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Translation,\n transform: (node: TranslationContent, props, deepTransformNode) => {\n const result = structuredClone(node[NodeType.Translation]);\n\n for (const key in result) {\n const childProps = {\n ...props,\n children: result[key as keyof typeof result],\n keyPath: [\n ...props.keyPath,\n { type: NodeType.Translation, key } as KeyPath,\n ],\n };\n result[key as keyof typeof result] = deepTransformNode(\n result[key as keyof typeof result],\n childProps\n );\n }\n\n return getTranslation(result, locale, fallback);\n },\n});\n\n/** ---------------------------------------------\n * ENUMERATION PLUGIN\n * --------------------------------------------- */\n\nexport type EnumerationCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Enumeration]: object;\n}\n ? (\n quantity: number\n ) => DeepTransformContent<\n T[NodeType.Enumeration][keyof T[NodeType.Enumeration]],\n S\n >\n : never;\n\n/** Enumeration plugin. Replaces node with a function that takes quantity => string. */\nexport const enumerationPlugin: Plugins = {\n id: 'enumeration-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Enumeration,\n transform: (node: EnumerationContent, props, deepTransformNode) => {\n const result = structuredClone(node[NodeType.Enumeration]);\n\n for (const key in result) {\n const child = result[key as unknown as keyof typeof result];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeType.Enumeration, key } as KeyPath,\n ],\n };\n result[key as unknown as keyof typeof result] = deepTransformNode(\n child,\n childProps\n );\n }\n\n return (quantity: number) => getEnumeration(result, quantity);\n },\n};\n\n/** ---------------------------------------------\n * CONDITION PLUGIN\n * --------------------------------------------- */\n\nexport type ConditionCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Condition]: object;\n}\n ? (\n value: boolean\n ) => DeepTransformContent<\n T[NodeType.Condition][keyof T[NodeType.Condition]],\n S\n >\n : never;\n\n/** Condition plugin. Replaces node with a function that takes boolean => string. */\nexport const conditionPlugin: Plugins = {\n id: 'condition-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Condition,\n transform: (node: ConditionContent, props, deepTransformNode) => {\n const result = structuredClone(node[NodeType.Condition]);\n\n for (const key in result) {\n const child = result[key as keyof typeof result];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeType.Condition, key } as KeyPath,\n ],\n };\n result[key as unknown as keyof typeof result] = deepTransformNode(\n child,\n childProps\n );\n }\n\n return (value: boolean) => getCondition(result, value);\n },\n};\n\n/** ---------------------------------------------\n * GENDER PLUGIN\n * --------------------------------------------- */\n\nexport type GenderCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Gender]: object;\n}\n ? (\n value: Gender\n ) => DeepTransformContent<T[NodeType.Gender][keyof T[NodeType.Gender]], S>\n : never;\n\n/** Gender plugin. Replaces node with a function that takes gender => string. */\nexport const genderPlugin: Plugins = {\n id: 'gender-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Gender,\n transform: (node: GenderContent, props, deepTransformNode) => {\n const result = structuredClone(node[NodeType.Gender]);\n\n for (const key in result) {\n const child = result[key as keyof typeof result];\n const childProps = {\n ...props,\n children: child,\n keyPath: [...props.keyPath, { type: NodeType.Gender, key } as KeyPath],\n };\n result[key as unknown as keyof typeof result] = deepTransformNode(\n child,\n childProps\n );\n }\n\n return (value: Gender) => getGender(result, value);\n },\n};\n\n/** ---------------------------------------------\n * INSERTION PLUGIN\n * --------------------------------------------- */\n\nexport type InsertionCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Insertion]: infer I;\n fields?: infer U;\n}\n ? U extends readonly string[]\n ? (data: Record<U[number], string | number>) => DeepTransformContent<I, S>\n : (data: Record<string, string | number>) => DeepTransformContent<I, S>\n : never;\n\nexport const insertionPlugin: Plugins = {\n id: 'insertion-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Insertion,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n {\n type: NodeType.Insertion,\n },\n ];\n\n const children = node[NodeType.Insertion];\n\n /** Insertion string plugin. Replaces string node with a component that render the insertion. */\n const insertionStringPlugin: Plugins = {\n id: 'insertion-string-plugin',\n canHandle: (node) => typeof node === 'string',\n transform: (node: string, subProps, deepTransformNode) => {\n const transformedResult = deepTransformNode(node, {\n ...subProps,\n children: node,\n plugins: [\n ...(props.plugins ?? ([] as Plugins[])).filter(\n (plugin) => plugin.id !== 'intlayer-node-plugin'\n ),\n ],\n });\n\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) => {\n const children = getInsertion(transformedResult, values);\n\n return deepTransformNode(children, {\n ...subProps,\n plugins: props.plugins,\n children,\n });\n };\n },\n };\n\n return deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [insertionStringPlugin, ...(props.plugins ?? [])],\n });\n },\n};\n\n/** ---------------------------------------------\n * NESTED PLUGIN\n * --------------------------------------------- */\n\nexport type NestedCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Nested]: infer U;\n}\n ? U extends {\n dictionaryKey: infer K extends DictionaryKeys;\n path?: infer P;\n }\n ? GetNestingResult<K, P, S>\n : never\n : never;\n\n/** Nested plugin. Replaces node with the result of `getNesting`. */\nexport const nestedPlugin: Plugins = {\n id: 'nested-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Nested,\n transform: (node: NestedContent, props) =>\n getNesting(node.nested.dictionaryKey, node.nested.path, props),\n};\n\n// /** ---------------------------------------------\n// * FILE PLUGIN\n// * --------------------------------------------- */\n\nexport type FileCond<T> = T extends {\n nodeType: NodeType | string;\n [NodeType.File]: string;\n content?: string;\n}\n ? string\n : never;\n\n/** File plugin. Replaces node with the result of `getNesting`. */\nexport const filePlugin: Plugins = {\n id: 'file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.File,\n transform: (node: FileContent, props, deepTransform) =>\n deepTransform(node.content, {\n ...props,\n children: node.content,\n }),\n};\n\n/**\n * PLUGIN RESULT\n */\n\n/**\n * Interface that defines the properties of a node.\n * This interface can be augmented in other packages, such as `react-intlayer`.\n */\nexport interface NodeProps {\n dictionaryKey: string;\n keyPath: KeyPath[];\n plugins?: Plugins[];\n locale?: Locale;\n dictionaryPath?: string;\n children?: any;\n}\n\n/**\n * Interface that defines the plugins that can be used to transform a node.\n * This interface can be augmented in other packages, such as `react-intlayer`.\n */\nexport interface IInterpreterPlugin<T, S, L extends LocalesValues> {\n translation: TranslationCond<T, S, L>;\n insertion: InsertionCond<T, S, L>;\n enumeration: EnumerationCond<T, S, L>;\n condition: ConditionCond<T, S, L>;\n nested: NestedCond<T, S, L>;\n // file: FileCond<T>;\n}\n\n/**\n * Allow to avoid overwriting import from `intlayer` package when `IInterpreterPlugin<T>` interface is augmented in another package, such as `react-intlayer`.\n */\nexport type IInterpreterPluginState = {\n translation: true;\n enumeration: true;\n condition: true;\n insertion: true;\n nested: true;\n // file: true;\n};\n\n/**\n * Utility type to check if a plugin can be applied to a node.\n */\ntype CheckApplyPlugin<\n T,\n K extends keyof IInterpreterPlugin<T, S, L>,\n S,\n L extends LocalesValues = DeclaredLocales,\n> = K extends keyof S // Test if the key is a key of S.\n ? // Test if the key of S is true. Then the plugin can be applied.\n S[K] extends true\n ? // Test if the key of S exist\n IInterpreterPlugin<T, S, L>[K] extends never\n ? never\n : // Test if the plugin condition is true (if it's not, the plugin is skipped for this node)\n IInterpreterPlugin<T, S, L>[K]\n : never\n : never;\n\n/**\n * Traverse recursively through an object or array, applying each plugin as needed.\n */\ntype Traverse<\n T,\n S,\n L extends LocalesValues = DeclaredLocales,\n> = T extends ReadonlyArray<infer U> // Turn any read-only array into a plain mutable array\n ? Array<DeepTransformContent<U, S, L>>\n : T extends object\n ? { [K in keyof T]: DeepTransformContent<T[K], S, L> }\n : T;\n\nexport type IsAny<T> = 0 extends 1 & T ? true : false;\n\n/**\n * Traverse recursively through an object or array, applying each plugin as needed.\n */\nexport type DeepTransformContent<\n T,\n S = IInterpreterPluginState,\n L extends LocalesValues = DeclaredLocales,\n> = IsAny<T> extends true\n ? T\n : CheckApplyPlugin<T, keyof IInterpreterPlugin<T, S, L>, S> extends never // Check if there is a plugin for T:\n ? // No plugin was found, so try to transform T recursively:\n Traverse<T, S, L>\n : // A plugin was found – use the plugin’s transformation.\n IInterpreterPlugin<T, S, L>[keyof IInterpreterPlugin<T, S, L>];\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"plugins.cjs","names":["NodeType","getTranslation","enumerationPlugin: Plugins","getEnumeration","conditionPlugin: Plugins","getCondition","genderPlugin: Plugins","getGender","insertionPlugin: Plugins","newKeyPath: KeyPath[]","insertionStringPlugin: Plugins","node","deepTransformNode","children","getInsertion","getNesting","filePlugin: Plugins"],"sources":["../../../../src/interpreter/getContent/plugins.ts"],"sourcesContent":["import {\n type DeclaredLocales,\n type DictionaryKeys,\n type KeyPath,\n type Locale,\n type LocalesValues,\n NodeType,\n} from '@intlayer/types';\nimport type {\n ConditionContent,\n EnumerationContent,\n FileContent,\n Gender,\n GenderContent,\n InsertionContent,\n NestedContent,\n TranslationContent,\n} from '../../transpiler';\nimport { getCondition } from '../getCondition';\nimport { getEnumeration } from '../getEnumeration';\nimport { getGender } from '../getGender';\nimport { getInsertion } from '../getInsertion';\nimport { type GetNestingResult, getNesting } from '../getNesting';\nimport { getTranslation } from '../getTranslation';\n\n/** ---------------------------------------------\n * PLUGIN DEFINITION\n * --------------------------------------------- */\n\n/**\n * A plugin/transformer that can optionally transform a node during a single DFS pass.\n * - `canHandle` decides if the node is transformable by this plugin.\n * - `transform` returns the transformed node (and does not recurse further).\n *\n * > `transformFn` is a function that can be used to deeply transform inside the plugin.\n */\nexport type Plugins = {\n id: string;\n canHandle: (node: any) => boolean;\n transform: (\n node: any,\n props: NodeProps,\n transformFn: (node: any, props: NodeProps) => any\n ) => any;\n};\n\n/** ---------------------------------------------\n * TRANSLATION PLUGIN\n * --------------------------------------------- */\n\nexport type TranslationCond<T, S, L extends LocalesValues> = T extends {\n nodeType: NodeType | string;\n [NodeType.Translation]: infer U;\n}\n ? U extends Record<PropertyKey, unknown>\n ? L extends keyof U\n ? DeepTransformContent<U[L], S>\n : DeepTransformContent<U[keyof U], S>\n : never\n : never;\n\n/** Translation plugin. Replaces node with a locale string if nodeType = Translation. */\nexport const translationPlugin = (\n locale: LocalesValues,\n fallback?: LocalesValues,\n onContentNotFound?: (\n locale: LocalesValues,\n fallback: LocalesValues,\n keyPath: KeyPath[]\n ) => void\n): Plugins => ({\n id: 'translation-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Translation,\n transform: (node: TranslationContent, props, deepTransformNode) => {\n const result = structuredClone(node[NodeType.Translation]);\n\n for (const key in result) {\n const childProps = {\n ...props,\n children: result[key as keyof typeof result],\n keyPath: [\n ...props.keyPath,\n { type: NodeType.Translation, key } as KeyPath,\n ],\n };\n result[key as keyof typeof result] = deepTransformNode(\n result[key as keyof typeof result],\n childProps\n );\n }\n\n return getTranslation(result, locale, fallback);\n },\n});\n\n/** ---------------------------------------------\n * ENUMERATION PLUGIN\n * --------------------------------------------- */\n\nexport type EnumerationCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Enumeration]: object;\n}\n ? (\n quantity: number\n ) => DeepTransformContent<\n T[NodeType.Enumeration][keyof T[NodeType.Enumeration]],\n S\n >\n : never;\n\n/** Enumeration plugin. Replaces node with a function that takes quantity => string. */\nexport const enumerationPlugin: Plugins = {\n id: 'enumeration-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Enumeration,\n transform: (node: EnumerationContent, props, deepTransformNode) => {\n const result = structuredClone(node[NodeType.Enumeration]);\n\n for (const key in result) {\n const child = result[key as unknown as keyof typeof result];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeType.Enumeration, key } as KeyPath,\n ],\n };\n result[key as unknown as keyof typeof result] = deepTransformNode(\n child,\n childProps\n );\n }\n\n return (quantity: number) => getEnumeration(result, quantity);\n },\n};\n\n/** ---------------------------------------------\n * CONDITION PLUGIN\n * --------------------------------------------- */\n\nexport type ConditionCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Condition]: object;\n}\n ? (\n value: boolean\n ) => DeepTransformContent<\n T[NodeType.Condition][keyof T[NodeType.Condition]],\n S\n >\n : never;\n\n/** Condition plugin. Replaces node with a function that takes boolean => string. */\nexport const conditionPlugin: Plugins = {\n id: 'condition-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Condition,\n transform: (node: ConditionContent, props, deepTransformNode) => {\n const result = structuredClone(node[NodeType.Condition]);\n\n for (const key in result) {\n const child = result[key as keyof typeof result];\n const childProps = {\n ...props,\n children: child,\n keyPath: [\n ...props.keyPath,\n { type: NodeType.Condition, key } as KeyPath,\n ],\n };\n result[key as unknown as keyof typeof result] = deepTransformNode(\n child,\n childProps\n );\n }\n\n return (value: boolean) => getCondition(result, value);\n },\n};\n\n/** ---------------------------------------------\n * GENDER PLUGIN\n * --------------------------------------------- */\n\nexport type GenderCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Gender]: object;\n}\n ? (\n value: Gender\n ) => DeepTransformContent<T[NodeType.Gender][keyof T[NodeType.Gender]], S>\n : never;\n\n/** Gender plugin. Replaces node with a function that takes gender => string. */\nexport const genderPlugin: Plugins = {\n id: 'gender-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Gender,\n transform: (node: GenderContent, props, deepTransformNode) => {\n const result = structuredClone(node[NodeType.Gender]);\n\n for (const key in result) {\n const child = result[key as keyof typeof result];\n const childProps = {\n ...props,\n children: child,\n keyPath: [...props.keyPath, { type: NodeType.Gender, key } as KeyPath],\n };\n result[key as unknown as keyof typeof result] = deepTransformNode(\n child,\n childProps\n );\n }\n\n return (value: Gender) => getGender(result, value);\n },\n};\n\n/** ---------------------------------------------\n * INSERTION PLUGIN\n * --------------------------------------------- */\n\nexport type InsertionCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Insertion]: infer I;\n fields?: infer U;\n}\n ? U extends readonly string[]\n ? (data: Record<U[number], string | number>) => DeepTransformContent<I, S>\n : (data: Record<string, string | number>) => DeepTransformContent<I, S>\n : never;\n\nexport const insertionPlugin: Plugins = {\n id: 'insertion-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Insertion,\n transform: (node: InsertionContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n {\n type: NodeType.Insertion,\n },\n ];\n\n const children = node[NodeType.Insertion];\n\n /** Insertion string plugin. Replaces string node with a component that render the insertion. */\n const insertionStringPlugin: Plugins = {\n id: 'insertion-string-plugin',\n canHandle: (node) => typeof node === 'string',\n transform: (node: string, subProps, deepTransformNode) => {\n const transformedResult = deepTransformNode(node, {\n ...subProps,\n children: node,\n plugins: [\n ...(props.plugins ?? ([] as Plugins[])).filter(\n (plugin) => plugin.id !== 'intlayer-node-plugin'\n ),\n ],\n });\n\n return (\n values: {\n [K in InsertionContent['fields'][number]]: string | number;\n }\n ) => {\n const children = getInsertion(transformedResult, values);\n\n return deepTransformNode(children, {\n ...subProps,\n plugins: props.plugins,\n children,\n });\n };\n },\n };\n\n return deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [insertionStringPlugin, ...(props.plugins ?? [])],\n });\n },\n};\n\n/** ---------------------------------------------\n * NESTED PLUGIN\n * --------------------------------------------- */\n\nexport type NestedCond<T, S, L> = T extends {\n nodeType: NodeType | string;\n [NodeType.Nested]: infer U;\n}\n ? U extends {\n dictionaryKey: infer K extends DictionaryKeys;\n path?: infer P;\n }\n ? GetNestingResult<K, P, S>\n : never\n : never;\n\n/** Nested plugin. Replaces node with the result of `getNesting`. */\nexport const nestedPlugin = (locale?: LocalesValues): Plugins => ({\n id: 'nested-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.Nested,\n transform: (node: NestedContent, props) =>\n getNesting(node.nested.dictionaryKey, node.nested.path, {\n ...props,\n locale: (locale ?? props.locale) as Locale,\n }),\n});\n\n// /** ---------------------------------------------\n// * FILE PLUGIN\n// * --------------------------------------------- */\n\nexport type FileCond<T> = T extends {\n nodeType: NodeType | string;\n [NodeType.File]: string;\n content?: string;\n}\n ? string\n : never;\n\n/** File plugin. Replaces node with the result of `getNesting`. */\nexport const filePlugin: Plugins = {\n id: 'file-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeType.File,\n transform: (node: FileContent, props, deepTransform) =>\n deepTransform(node.content, {\n ...props,\n children: node.content,\n }),\n};\n\n/**\n * PLUGIN RESULT\n */\n\n/**\n * Interface that defines the properties of a node.\n * This interface can be augmented in other packages, such as `react-intlayer`.\n */\nexport interface NodeProps {\n dictionaryKey: string;\n keyPath: KeyPath[];\n plugins?: Plugins[];\n locale?: Locale;\n dictionaryPath?: string;\n children?: any;\n}\n\n/**\n * Interface that defines the plugins that can be used to transform a node.\n * This interface can be augmented in other packages, such as `react-intlayer`.\n */\nexport interface IInterpreterPlugin<T, S, L extends LocalesValues> {\n translation: TranslationCond<T, S, L>;\n insertion: InsertionCond<T, S, L>;\n enumeration: EnumerationCond<T, S, L>;\n condition: ConditionCond<T, S, L>;\n nested: NestedCond<T, S, L>;\n // file: FileCond<T>;\n}\n\n/**\n * Allow to avoid overwriting import from `intlayer` package when `IInterpreterPlugin<T>` interface is augmented in another package, such as `react-intlayer`.\n */\nexport type IInterpreterPluginState = {\n translation: true;\n enumeration: true;\n condition: true;\n insertion: true;\n nested: true;\n // file: true;\n};\n\n/**\n * Utility type to check if a plugin can be applied to a node.\n */\ntype CheckApplyPlugin<\n T,\n K extends keyof IInterpreterPlugin<T, S, L>,\n S,\n L extends LocalesValues = DeclaredLocales,\n> = K extends keyof S // Test if the key is a key of S.\n ? // Test if the key of S is true. Then the plugin can be applied.\n S[K] extends true\n ? // Test if the key of S exist\n IInterpreterPlugin<T, S, L>[K] extends never\n ? never\n : // Test if the plugin condition is true (if it's not, the plugin is skipped for this node)\n IInterpreterPlugin<T, S, L>[K]\n : never\n : never;\n\n/**\n * Traverse recursively through an object or array, applying each plugin as needed.\n */\ntype Traverse<\n T,\n S,\n L extends LocalesValues = DeclaredLocales,\n> = T extends ReadonlyArray<infer U> // Turn any read-only array into a plain mutable array\n ? Array<DeepTransformContent<U, S, L>>\n : T extends object\n ? { [K in keyof T]: DeepTransformContent<T[K], S, L> }\n : T;\n\nexport type IsAny<T> = 0 extends 1 & T ? true : false;\n\n/**\n * Traverse recursively through an object or array, applying each plugin as needed.\n */\nexport type DeepTransformContent<\n T,\n S = IInterpreterPluginState,\n L extends LocalesValues = DeclaredLocales,\n> = IsAny<T> extends true\n ? T\n : CheckApplyPlugin<T, keyof IInterpreterPlugin<T, S, L>, S> extends never // Check if there is a plugin for T:\n ? // No plugin was found, so try to transform T recursively:\n Traverse<T, S, L>\n : // A plugin was found – use the plugin’s transformation.\n IInterpreterPlugin<T, S, L>[keyof IInterpreterPlugin<T, S, L>];\n"],"mappings":"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"}
|
|
@@ -1,40 +1,43 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_utils_checkIsURLAbsolute = require('../utils/checkIsURLAbsolute.cjs');
|
|
3
|
-
let
|
|
3
|
+
let _intlayer_config_client = require("@intlayer/config/client");
|
|
4
4
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
5
5
|
_intlayer_config_built = require_rolldown_runtime.__toESM(_intlayer_config_built);
|
|
6
6
|
|
|
7
7
|
//#region src/localization/getLocaleFromPath.ts
|
|
8
8
|
/**
|
|
9
|
-
* Extracts the locale segment from the given URL or pathname
|
|
10
|
-
* If no locale is present, returns the default locale (en).
|
|
9
|
+
* Extracts the locale segment from the given URL or pathname based on the routing mode.
|
|
11
10
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* getLocaleFromPath('/dashboard') // Returns 'en'
|
|
18
|
-
* getLocaleFromPath('dashboard') // Returns 'en'
|
|
19
|
-
* getLocaleFromPath('https://example.com/es/dashboard') // Returns 'es'
|
|
20
|
-
* getLocaleFromPath('https://example.com/fr/dashboard') // Returns 'fr'
|
|
21
|
-
* getLocaleFromPath('https://example.com/dashboard') // Returns 'en'
|
|
22
|
-
* ```
|
|
11
|
+
* Mode Behaviors:
|
|
12
|
+
* - 'prefix-no-default': Checks path prefiIf no prefix found, assumes default locale.
|
|
13
|
+
* - 'prefix-all': Checks path prefix.
|
|
14
|
+
* - 'search-params': Checks for 'locale' query parameter.
|
|
15
|
+
* - 'no-prefix': Returns undefined (or default if fallback is true).
|
|
23
16
|
*
|
|
24
17
|
* @param inputUrl - The complete URL string or pathname to process.
|
|
25
|
-
* @returns The detected locale
|
|
18
|
+
* @returns The detected locale, default locale (if fallback/implicit), or undefined.
|
|
26
19
|
*/
|
|
27
|
-
const getLocaleFromPath = (inputUrl = "/") => {
|
|
28
|
-
const { defaultLocale, locales } =
|
|
29
|
-
|
|
20
|
+
const getLocaleFromPath = (inputUrl = "/", options) => {
|
|
21
|
+
const { defaultLocale, locales, mode } = {
|
|
22
|
+
defaultLocale: _intlayer_config_built.default?.internationalization?.defaultLocale ?? _intlayer_config_client.DefaultValues.Internationalization.DEFAULT_LOCALE,
|
|
23
|
+
mode: _intlayer_config_built.default?.routing?.mode ?? _intlayer_config_client.DefaultValues.Routing.ROUTING_MODE,
|
|
24
|
+
locales: _intlayer_config_built.default?.internationalization?.locales ?? _intlayer_config_client.DefaultValues.Internationalization.LOCALES,
|
|
25
|
+
...options
|
|
26
|
+
};
|
|
27
|
+
if (!defaultLocale || !locales) return _intlayer_config_client.DefaultValues.Internationalization.DEFAULT_LOCALE;
|
|
30
28
|
const isAbsoluteUrl = require_utils_checkIsURLAbsolute.checkIsURLAbsolute(inputUrl);
|
|
31
29
|
let fixedInputUrl = inputUrl;
|
|
32
|
-
if (inputUrl?.endsWith("/")) fixedInputUrl = inputUrl.slice(0, -1);
|
|
33
|
-
const
|
|
34
|
-
if (
|
|
35
|
-
|
|
30
|
+
if (inputUrl?.endsWith("/") && inputUrl.length > 1) fixedInputUrl = inputUrl.slice(0, -1);
|
|
31
|
+
const url = isAbsoluteUrl ? new URL(fixedInputUrl) : new URL(fixedInputUrl, "http://example.com");
|
|
32
|
+
if (mode === "search-params") {
|
|
33
|
+
const localeParam = url.searchParams.get("locale");
|
|
34
|
+
if (localeParam && locales.includes(localeParam)) return localeParam;
|
|
35
|
+
return defaultLocale;
|
|
36
|
+
}
|
|
37
|
+
if (mode === "no-prefix") return defaultLocale;
|
|
38
|
+
const firstSegment = url.pathname.split("/")[1];
|
|
36
39
|
if (firstSegment && locales.includes(firstSegment)) return firstSegment;
|
|
37
|
-
return defaultLocale;
|
|
40
|
+
if (mode === "prefix-no-default") return defaultLocale;
|
|
38
41
|
};
|
|
39
42
|
|
|
40
43
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocaleFromPath.cjs","names":["configuration","
|
|
1
|
+
{"version":3,"file":"getLocaleFromPath.cjs","names":["configuration","DefaultValues","checkIsURLAbsolute"],"sources":["../../../src/localization/getLocaleFromPath.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport type { Locale, LocalesValues, RoutingConfig } from '@intlayer/types';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\n\ntype GetLocaleFromPathOptions = {\n defaultLocale?: LocalesValues;\n locales?: LocalesValues[];\n mode?: RoutingConfig['mode'];\n};\n\n/**\n * Extracts the locale segment from the given URL or pathname based on the routing mode.\n *\n * Mode Behaviors:\n * - 'prefix-no-default': Checks path prefiIf no prefix found, assumes default locale.\n * - 'prefix-all': Checks path prefix.\n * - 'search-params': Checks for 'locale' query parameter.\n * - 'no-prefix': Returns undefined (or default if fallback is true).\n *\n * @param inputUrl - The complete URL string or pathname to process.\n * @returns The detected locale, default locale (if fallback/implicit), or undefined.\n */\nexport const getLocaleFromPath = (\n inputUrl: string = '/',\n options?: GetLocaleFromPathOptions\n): Locale | undefined => {\n const { defaultLocale, locales, mode } = {\n defaultLocale:\n configuration?.internationalization?.defaultLocale ??\n DefaultValues.Internationalization.DEFAULT_LOCALE,\n mode: configuration?.routing?.mode ?? DefaultValues.Routing.ROUTING_MODE,\n locales:\n configuration?.internationalization?.locales ??\n DefaultValues.Internationalization.LOCALES,\n ...options,\n };\n\n if (!defaultLocale || !locales) {\n return DefaultValues.Internationalization.DEFAULT_LOCALE;\n }\n\n // Prepare the URL object\n const isAbsoluteUrl = checkIsURLAbsolute(inputUrl);\n let fixedInputUrl = inputUrl;\n\n if (inputUrl?.endsWith('/') && inputUrl.length > 1) {\n fixedInputUrl = inputUrl.slice(0, -1);\n }\n\n // For relative URLs, use a dummy base to leverage the URL API\n const url = isAbsoluteUrl\n ? new URL(fixedInputUrl)\n : new URL(fixedInputUrl, 'http://example.com');\n\n // Handle 'search-params' mode\n // Example: /dashboard?locale=fr\n if (mode === 'search-params') {\n const localeParam = url.searchParams.get('locale');\n\n if (localeParam && locales.includes(localeParam)) {\n return localeParam as Locale;\n }\n\n return defaultLocale as Locale;\n }\n\n // Handle 'no-prefix' mode\n // The locale is not stored in the URL path.\n if (mode === 'no-prefix') {\n return defaultLocale as Locale;\n }\n\n // Handle Prefix Modes ('prefix-all' | 'prefix-no-default')\n const pathname = url.pathname;\n\n // Split the pathname to extract the first segment\n // pathSegments[0] is empty string because path starts with /\n const pathSegments = pathname.split('/');\n const firstSegment = pathSegments[1];\n\n // Check if the first segment is a valid supported locale\n const isSegmentLocale = firstSegment && locales.includes(firstSegment);\n\n if (isSegmentLocale) {\n return firstSegment as Locale;\n }\n\n // If the first segment is NOT a locale (e./dashboard), handle based on mode\n if (mode === 'prefix-no-default') {\n // In this mode, absence of a prefix implies the default locale\n return defaultLocale as Locale;\n }\n\n return undefined;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,MAAa,qBACX,WAAmB,KACnB,YACuB;CACvB,MAAM,EAAE,eAAe,SAAS,SAAS;EACvC,eACEA,gCAAe,sBAAsB,iBACrCC,sCAAc,qBAAqB;EACrC,MAAMD,gCAAe,SAAS,QAAQC,sCAAc,QAAQ;EAC5D,SACED,gCAAe,sBAAsB,WACrCC,sCAAc,qBAAqB;EACrC,GAAG;EACJ;AAED,KAAI,CAAC,iBAAiB,CAAC,QACrB,QAAOA,sCAAc,qBAAqB;CAI5C,MAAM,gBAAgBC,oDAAmB,SAAS;CAClD,IAAI,gBAAgB;AAEpB,KAAI,UAAU,SAAS,IAAI,IAAI,SAAS,SAAS,EAC/C,iBAAgB,SAAS,MAAM,GAAG,GAAG;CAIvC,MAAM,MAAM,gBACR,IAAI,IAAI,cAAc,GACtB,IAAI,IAAI,eAAe,qBAAqB;AAIhD,KAAI,SAAS,iBAAiB;EAC5B,MAAM,cAAc,IAAI,aAAa,IAAI,SAAS;AAElD,MAAI,eAAe,QAAQ,SAAS,YAAY,CAC9C,QAAO;AAGT,SAAO;;AAKT,KAAI,SAAS,YACX,QAAO;CAST,MAAM,eALW,IAAI,SAIS,MAAM,IAAI,CACN;AAKlC,KAFwB,gBAAgB,QAAQ,SAAS,aAAa,CAGpE,QAAO;AAIT,KAAI,SAAS,oBAEX,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocalizedUrl.cjs","names":["configuration","DefaultValues","getPathWithoutLocale","checkIsURLAbsolute","getPrefix"],"sources":["../../../src/localization/getLocalizedUrl.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport type { LocalesValues } from '@intlayer/types';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\nimport { getPathWithoutLocale } from './getPathWithoutLocale';\nimport { getPrefix } from './getPrefix';\n\n/**\n * Generate URL by prefixing the given URL with the referenced locale or adding search parameters\n * based on the routing mode. Handles both absolute and relative URLs appropriately.\n *\n * This function gets the locales, default locale, and routing mode from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * // prefix-no-default mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-no-default' });\n * // Returns '/fr/about' for the French locale\n * // Returns '/about' for the English locale (default)\n *\n * // prefix-all mode\n * getLocalizedUrl('/about', 'en', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-all' });\n * // Returns '/en/about' for the English locale\n * // Returns '/fr/about' for the French locale\n *\n * // search-params mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'search-params' });\n * // Returns '/about?locale=fr' for the French locale\n *\n * // no-prefix mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'no-prefix' });\n * // Returns '/about' for any locale\n * ```\n *\n * @param url - The original URL string to be processed.\n * @param currentLocale - The current locale.\n * @param options - Configuration options\n * @param options.locales - Optional array of supported locales. Defaults to configured locales.\n * @param options.defaultLocale - The default locale. Defaults to configured default locale.\n * @param options.mode - URL routing mode for locale handling. Defaults to configured mode.\n * @returns The localized URL for the current locale.\n */\nexport const getLocalizedUrl = (\n url: string,\n currentLocale: LocalesValues,\n options: {\n locales?: LocalesValues[];\n defaultLocale?: LocalesValues;\n mode?: '
|
|
1
|
+
{"version":3,"file":"getLocalizedUrl.cjs","names":["configuration","DefaultValues","getPathWithoutLocale","checkIsURLAbsolute","getPrefix"],"sources":["../../../src/localization/getLocalizedUrl.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport type { LocalesValues, RoutingConfig } from '@intlayer/types';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\nimport { getPathWithoutLocale } from './getPathWithoutLocale';\nimport { getPrefix } from './getPrefix';\n\n/**\n * Generate URL by prefixing the given URL with the referenced locale or adding search parameters\n * based on the routing mode. Handles both absolute and relative URLs appropriately.\n *\n * This function gets the locales, default locale, and routing mode from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * // prefix-no-default mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-no-default' });\n * // Returns '/fr/about' for the French locale\n * // Returns '/about' for the English locale (default)\n *\n * // prefix-all mode\n * getLocalizedUrl('/about', 'en', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-all' });\n * // Returns '/en/about' for the English locale\n * // Returns '/fr/about' for the French locale\n *\n * // search-params mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'search-params' });\n * // Returns '/about?locale=fr' for the French locale\n *\n * // no-prefix mode\n * getLocalizedUrl('/about', 'fr', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'no-prefix' });\n * // Returns '/about' for any locale\n * ```\n *\n * @param url - The original URL string to be processed.\n * @param currentLocale - The current locale.\n * @param options - Configuration options\n * @param options.locales - Optional array of supported locales. Defaults to configured locales.\n * @param options.defaultLocale - The default locale. Defaults to configured default locale.\n * @param options.mode - URL routing mode for locale handling. Defaults to configured mode.\n * @returns The localized URL for the current locale.\n */\nexport const getLocalizedUrl = (\n url: string,\n currentLocale: LocalesValues,\n options: {\n locales?: LocalesValues[];\n defaultLocale?: LocalesValues;\n mode?: RoutingConfig['mode'];\n } = {}\n): string => {\n const { defaultLocale, mode, locales } = {\n defaultLocale:\n configuration?.internationalization?.defaultLocale ??\n DefaultValues.Internationalization.DEFAULT_LOCALE,\n mode: configuration?.routing?.mode ?? DefaultValues.Routing.ROUTING_MODE,\n locales:\n configuration?.internationalization?.locales ??\n DefaultValues.Internationalization.LOCALES,\n ...options,\n };\n\n // Remove any existing locale segment from the URL\n const urlWithoutLocale = getPathWithoutLocale(url, locales);\n\n if (mode === 'no-prefix') {\n // No locale prefixing\n return urlWithoutLocale;\n }\n\n // Determine if the original URL is absolute (includes protocol)\n const isAbsoluteUrl = checkIsURLAbsolute(urlWithoutLocale);\n\n // Initialize a URL object if the URL is absolute\n // For relative URLs, use a dummy base to leverage the URL API\n const parsedUrl = isAbsoluteUrl\n ? new URL(urlWithoutLocale)\n : new URL(urlWithoutLocale, 'http://example.com');\n\n // Prepare the base URL (protocol + host) if it's absolute\n const baseUrl = isAbsoluteUrl\n ? `${parsedUrl.protocol}//${parsedUrl.host}`\n : '';\n\n if (mode === 'search-params') {\n // Use search parameters for locale handling\n const searchParams = new URLSearchParams(parsedUrl.search);\n searchParams.set('locale', currentLocale.toString());\n\n const queryString = searchParams.toString();\n const pathWithQuery = queryString\n ? `${parsedUrl.pathname}?${queryString}`\n : parsedUrl.pathname;\n\n if (isAbsoluteUrl) {\n return `${baseUrl}${pathWithQuery}${parsedUrl.hash}`;\n }\n\n return `${pathWithQuery}${parsedUrl.hash}`;\n }\n\n const { prefix } = getPrefix(currentLocale, {\n defaultLocale,\n mode,\n locales,\n });\n\n // Construct the new pathname with or without the locale prefix\n let localizedPath = `/${prefix}${parsedUrl.pathname}`;\n\n // Remove double slashes\n localizedPath = localizedPath.replaceAll(/\\/+/g, '/');\n\n // Remove trailing slash for non-root paths\n if (localizedPath.length > 1 && localizedPath.endsWith('/')) {\n localizedPath = localizedPath.slice(0, -1);\n }\n\n // Combine with the base URL if the original URL was absolute\n if (isAbsoluteUrl) {\n return `${baseUrl}${localizedPath}${parsedUrl.search}${parsedUrl.hash}`;\n }\n\n return `${localizedPath}${parsedUrl.search}${parsedUrl.hash}`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAa,mBACX,KACA,eACA,UAII,EAAE,KACK;CACX,MAAM,EAAE,eAAe,MAAM,YAAY;EACvC,eACEA,gCAAe,sBAAsB,iBACrCC,sCAAc,qBAAqB;EACrC,MAAMD,gCAAe,SAAS,QAAQC,sCAAc,QAAQ;EAC5D,SACED,gCAAe,sBAAsB,WACrCC,sCAAc,qBAAqB;EACrC,GAAG;EACJ;CAGD,MAAM,mBAAmBC,+DAAqB,KAAK,QAAQ;AAE3D,KAAI,SAAS,YAEX,QAAO;CAIT,MAAM,gBAAgBC,oDAAmB,iBAAiB;CAI1D,MAAM,YAAY,gBACd,IAAI,IAAI,iBAAiB,GACzB,IAAI,IAAI,kBAAkB,qBAAqB;CAGnD,MAAM,UAAU,gBACZ,GAAG,UAAU,SAAS,IAAI,UAAU,SACpC;AAEJ,KAAI,SAAS,iBAAiB;EAE5B,MAAM,eAAe,IAAI,gBAAgB,UAAU,OAAO;AAC1D,eAAa,IAAI,UAAU,cAAc,UAAU,CAAC;EAEpD,MAAM,cAAc,aAAa,UAAU;EAC3C,MAAM,gBAAgB,cAClB,GAAG,UAAU,SAAS,GAAG,gBACzB,UAAU;AAEd,MAAI,cACF,QAAO,GAAG,UAAU,gBAAgB,UAAU;AAGhD,SAAO,GAAG,gBAAgB,UAAU;;CAGtC,MAAM,EAAE,WAAWC,yCAAU,eAAe;EAC1C;EACA;EACA;EACD,CAAC;CAGF,IAAI,gBAAgB,IAAI,SAAS,UAAU;AAG3C,iBAAgB,cAAc,WAAW,QAAQ,IAAI;AAGrD,KAAI,cAAc,SAAS,KAAK,cAAc,SAAS,IAAI,CACzD,iBAAgB,cAAc,MAAM,GAAG,GAAG;AAI5C,KAAI,cACF,QAAO,GAAG,UAAU,gBAAgB,UAAU,SAAS,UAAU;AAGnE,QAAO,GAAG,gBAAgB,UAAU,SAAS,UAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getMultilingualUrls.cjs","names":["configuration","DefaultValues","getLocalizedUrl"],"sources":["../../../src/localization/getMultilingualUrls.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport type {
|
|
1
|
+
{"version":3,"file":"getMultilingualUrls.cjs","names":["configuration","DefaultValues","getLocalizedUrl"],"sources":["../../../src/localization/getMultilingualUrls.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport type {\n LocalesValues,\n RoutingConfig,\n StrictModeLocaleMap,\n} from '@intlayer/types';\nimport { getLocalizedUrl } from './getLocalizedUrl';\n\n/**\n * Generates multilingual URLs by prefixing the given URL with each supported locale\n * or adding search parameters based on the routing mode.\n * Handles both absolute and relative URLs appropriately.\n *\n * This function gets the locales, default locale, and routing mode from the configuration if not provided.\n *\n * Example:\n *\n * ```ts\n * // prefix-no-default mode\n * getMultilingualUrls('/dashboard', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-no-default' })\n * // Returns { en: '/dashboard', fr: '/fr/dashboard' }\n *\n * // prefix-all mode\n * getMultilingualUrls('/dashboard', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'prefix-all' })\n * // Returns { en: '/en/dashboard', fr: '/fr/dashboard' }\n *\n * // search-params mode\n * getMultilingualUrls('/dashboard', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'search-params' })\n * // Returns { en: '/dashboard?locale=en', fr: '/dashboard?locale=fr' }\n *\n * // no-prefix mode\n * getMultilingualUrls('/dashboard', { locales: ['en', 'fr'], defaultLocale: 'en', mode: 'no-prefix' })\n * // Returns { en: '/dashboard', fr: '/dashboard' }\n * ```\n *\n * @param url - The original URL string to be processed.\n * @param options - Configuration options\n * @param options.locales - Optional array of supported locales. Defaults to configured locales.\n * @param options.defaultLocale - The default locale. Defaults to configured default locale.\n * @param options.mode - URL routing mode for locale handling. Defaults to configured mode.\n * @returns An object mapping each locale to its corresponding multilingual URL.\n */\nexport const getMultilingualUrls = (\n url: string,\n options: {\n locales?: LocalesValues[];\n defaultLocale?: LocalesValues;\n mode?: RoutingConfig['mode'];\n } = {}\n): StrictModeLocaleMap<string> => {\n const { defaultLocale, mode, locales } = {\n defaultLocale:\n configuration?.internationalization?.defaultLocale ??\n DefaultValues.Internationalization.DEFAULT_LOCALE,\n mode: configuration?.routing?.mode ?? DefaultValues.Routing.ROUTING_MODE,\n locales:\n configuration?.internationalization?.locales ??\n DefaultValues.Internationalization.LOCALES,\n ...options,\n };\n\n // Generate multilingual URLs by iterating over each locale and calling getLocalizedUrl\n const multilingualUrls = (locales ?? []).reduce<StrictModeLocaleMap<string>>(\n (acc, locale) => {\n // Get the localized URL for this locale\n const localizedUrl = getLocalizedUrl(url, locale, {\n locales,\n defaultLocale,\n mode,\n });\n\n // Assign the constructed URL to the corresponding locale key\n acc[locale as unknown as keyof typeof acc] = localizedUrl;\n\n return acc;\n },\n {} as StrictModeLocaleMap<string>\n );\n\n return multilingualUrls;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAa,uBACX,KACA,UAII,EAAE,KAC0B;CAChC,MAAM,EAAE,eAAe,MAAM,YAAY;EACvC,eACEA,gCAAe,sBAAsB,iBACrCC,sCAAc,qBAAqB;EACrC,MAAMD,gCAAe,SAAS,QAAQC,sCAAc,QAAQ;EAC5D,SACED,gCAAe,sBAAsB,WACrCC,sCAAc,qBAAqB;EACrC,GAAG;EACJ;AAoBD,SAjB0B,WAAW,EAAE,EAAE,QACtC,KAAK,WAAW;AASf,MAAI,UAPiBC,qDAAgB,KAAK,QAAQ;GAChD;GACA;GACA;GACD,CAAC;AAKF,SAAO;IAET,EAAE,CACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getPrefix.cjs","names":["configuration","DefaultValues"],"sources":["../../../src/localization/getPrefix.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport type { Locale, LocalesValues } from '@intlayer/types';\n\nexport type GetPrefixOptions = {\n defaultLocale?: LocalesValues;\n mode?: '
|
|
1
|
+
{"version":3,"file":"getPrefix.cjs","names":["configuration","DefaultValues"],"sources":["../../../src/localization/getPrefix.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport { DefaultValues } from '@intlayer/config/client';\nimport type { Locale, LocalesValues, RoutingConfig } from '@intlayer/types';\n\nexport type GetPrefixOptions = {\n defaultLocale?: LocalesValues;\n mode?: RoutingConfig['mode'];\n};\n\nexport type GetPrefixResult = {\n /**\n * The complete base URL path with leading and trailing slashes.\n *\n * @example\n * // https://example.com/fr/about -> '/fr'\n * // https://example.com/about -> ''\n */\n prefix: string;\n /**\n * The locale identifier without slashes.\n *\n * @example\n * // https://example.com/fr/about -> 'fr'\n * // https://example.com/about -> undefined\n */\n localePrefix: Locale | undefined;\n};\n\n/**\n * Determines the URL prefix for a given locale based on the routing mode configuration.\n *\n * Example:\n *\n * ```ts\n * // prefix-no-default mode with default locale\n * getPrefix('en', { defaultLocale: 'en', mode: 'prefix-no-default' })\n * // Returns { prefix: '', localePrefix: undefined }\n *\n * // prefix-no-default mode with non-default locale\n * getPrefix('fr', { defaultLocale: 'en', mode: 'prefix-no-default' })\n * // Returns { prefix: '/fr', localePrefix: 'fr' }\n *\n * // prefix-all mode\n * getPrefix('en', { defaultLocale: 'en', mode: 'prefix-all' })\n * // Returns { prefix: '/en', localePrefix: locale }\n *\n * // search-params mode\n * getPrefix('en', { defaultLocale: 'en', mode: 'search-params' })\n * // Returns { prefix: '', localePrefix: undefined }\n *\n * // no-prefix mode\n * getPrefix('en', { defaultLocale: 'en', mode: 'no-prefix' })\n * // Returns { prefix: '', localePrefix: undefined }\n * ```\n *\n * @param locale - The locale to check for prefix. If not provided, uses configured default locale.\n * @param options - Configuration options\n * @param options.defaultLocale - The default locale. Defaults to configured default locale.\n * @param options.mode - URL routing mode for locale handling. Defaults to configured mode.\n * @returns An object containing pathPrefix, prefix, and localePrefix for the given locale.\n */\nexport const getPrefix = (\n locale: LocalesValues | undefined,\n options: {\n defaultLocale?: LocalesValues;\n locales?: LocalesValues[];\n mode?: RoutingConfig['mode'];\n } = {}\n): GetPrefixResult => {\n const { defaultLocale, mode, locales } = {\n defaultLocale:\n configuration?.internationalization?.defaultLocale ??\n DefaultValues.Internationalization.DEFAULT_LOCALE,\n mode: configuration?.routing?.mode ?? DefaultValues.Routing.ROUTING_MODE,\n locales:\n configuration?.internationalization?.locales ??\n DefaultValues.Internationalization.LOCALES,\n ...options,\n };\n\n if (!locale || !locales.includes(locale)) {\n return {\n prefix: '',\n localePrefix: undefined,\n };\n }\n\n // Handle prefix-based modes (prefix-all or prefix-no-default)\n const shouldPrefix =\n mode === 'prefix-all' ||\n (mode === 'prefix-no-default' && defaultLocale !== locale);\n\n if (shouldPrefix) {\n return {\n prefix: `${locale}/`,\n localePrefix: locale as Locale,\n };\n }\n\n return {\n prefix: '',\n localePrefix: undefined,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAa,aACX,QACA,UAII,EAAE,KACc;CACpB,MAAM,EAAE,eAAe,MAAM,YAAY;EACvC,eACEA,gCAAe,sBAAsB,iBACrCC,sCAAc,qBAAqB;EACrC,MAAMD,gCAAe,SAAS,QAAQC,sCAAc,QAAQ;EAC5D,SACED,gCAAe,sBAAsB,WACrCC,sCAAc,qBAAqB;EACrC,GAAG;EACJ;AAED,KAAI,CAAC,UAAU,CAAC,QAAQ,SAAS,OAAO,CACtC,QAAO;EACL,QAAQ;EACR,cAAc;EACf;AAQH,KAHE,SAAS,gBACR,SAAS,uBAAuB,kBAAkB,OAGnD,QAAO;EACL,QAAQ,GAAG,OAAO;EAClB,cAAc;EACf;AAGH,QAAO;EACL,QAAQ;EACR,cAAc;EACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getInsertionValues.cjs","names":[],"sources":["../../../../src/transpiler/insertion/getInsertionValues.ts"],"sourcesContent":["export const getInsertionValues = (content: string): string[] => {\n // Regular expression to match {{field}} patterns\n const regex = /{{\\s*(\\w+)\\s*}}/g;\n const matches = [...content.matchAll(regex)];\n\n // If no matches are found, return undefined\n if (matches.length === 0) return [];\n\n // Extract field names from matches and return as an object with the field names\n return matches.map((match) => match[1]);\n};\n"],"mappings":";;AAAA,MAAa,sBAAsB,YAA8B;CAG/D,MAAM,UAAU,CAAC,GAAG,QAAQ,SADd,mBAC6B,CAAC;AAG5C,KAAI,QAAQ,WAAW,EAAG,QAAO,EAAE;AAGnC,QAAO,QAAQ,KAAK,UAAU,MAAM,GAAG"}
|
|
1
|
+
{"version":3,"file":"getInsertionValues.cjs","names":[],"sources":["../../../../src/transpiler/insertion/getInsertionValues.ts"],"sourcesContent":["export const getInsertionValues = (content: string): string[] => {\n // Regular expression to match {{field}} patterns\n const regex = /{{\\s*(\\w+)\\s*}}/g;\n const matches = [...content.matchAll(regex)];\n\n // If no matches are found, return undefined\n if (matches.length === 0) return [];\n\n // Extract field names from matches and return as an object with the field names\n return [...new Set(matches.map((match) => match[1]))];\n};\n"],"mappings":";;AAAA,MAAa,sBAAsB,YAA8B;CAG/D,MAAM,UAAU,CAAC,GAAG,QAAQ,SADd,mBAC6B,CAAC;AAG5C,KAAI,QAAQ,WAAW,EAAG,QAAO,EAAE;AAGnC,QAAO,CAAC,GAAG,IAAI,IAAI,QAAQ,KAAK,UAAU,MAAM,GAAG,CAAC,CAAC"}
|
package/dist/cjs/utils/intl.cjs
CHANGED
|
@@ -2,51 +2,54 @@ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
|
2
2
|
let _intlayer_types = require("@intlayer/types");
|
|
3
3
|
|
|
4
4
|
//#region src/utils/intl.ts
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* Optimized Cache Key Generator
|
|
7
|
+
* 1. Fast path: If no options, just use the locale string.
|
|
8
|
+
* 2. Normal path: JSON.stringify for deterministic object comparison.
|
|
9
|
+
*/
|
|
10
|
+
const getCacheKey = (locales, options) => {
|
|
11
|
+
const localeKey = locales ? String(locales) : _intlayer_types.Locales.ENGLISH;
|
|
12
|
+
if (!options) return localeKey;
|
|
13
|
+
return `${localeKey}|${JSON.stringify(options)}`;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Generic wrapper for any `new Intl.*()` constructor.
|
|
17
|
+
*/
|
|
6
18
|
const createCachedConstructor = (Ctor) => {
|
|
7
19
|
const cache = /* @__PURE__ */ new Map();
|
|
20
|
+
const MAX_CACHE_SIZE = 50;
|
|
8
21
|
function Wrapped(locales, options) {
|
|
9
|
-
if (Ctor.name === "DisplayNames" && typeof Intl?.DisplayNames !== "function")
|
|
10
|
-
|
|
11
|
-
const message = [
|
|
12
|
-
`// Intl.DisplayNames is not supported; falling back to raw locale (${locales}). `,
|
|
13
|
-
`// Consider adding a polyfill as https://formatjs.io/docs/polyfills/intl-displaynames/`,
|
|
14
|
-
``,
|
|
15
|
-
`import 'intl';`,
|
|
16
|
-
`import '@formatjs/intl-displaynames/polyfill';`,
|
|
17
|
-
`import '@formatjs/intl-getcanonicallocales/polyfill';`,
|
|
18
|
-
`import '@formatjs/intl-locale/polyfill';`,
|
|
19
|
-
`import '@formatjs/intl-pluralrules/polyfill';`,
|
|
20
|
-
`import '@formatjs/intl-listformat/polyfill';`,
|
|
21
|
-
`import '@formatjs/intl-numberformat/polyfill';`,
|
|
22
|
-
`import '@formatjs/intl-relativetimeformat/polyfill';`,
|
|
23
|
-
`import '@formatjs/intl-datetimeformat/polyfill';`,
|
|
24
|
-
``,
|
|
25
|
-
`// Optionally add locale data`,
|
|
26
|
-
`import '@formatjs/intl-pluralrules/locale-data/fr';`,
|
|
27
|
-
`import '@formatjs/intl-numberformat/locale-data/fr';`,
|
|
28
|
-
`import '@formatjs/intl-datetimeformat/locale-data/fr';`
|
|
29
|
-
].join("\n");
|
|
30
|
-
console.warn(message);
|
|
31
|
-
throw new Error(message);
|
|
32
|
-
}
|
|
33
|
-
return locales;
|
|
34
|
-
}
|
|
35
|
-
const key = cacheKey(locales ?? _intlayer_types.Locales.ENGLISH, options);
|
|
22
|
+
if (Ctor.name === "DisplayNames" && typeof Intl?.DisplayNames !== "function") return locales;
|
|
23
|
+
const key = getCacheKey(locales, options);
|
|
36
24
|
let instance = cache.get(key);
|
|
37
|
-
if (
|
|
38
|
-
|
|
39
|
-
|
|
25
|
+
if (instance) return instance;
|
|
26
|
+
instance = new Ctor(locales, options);
|
|
27
|
+
if (cache.size >= MAX_CACHE_SIZE) {
|
|
28
|
+
const oldestKey = cache.keys().next().value;
|
|
29
|
+
if (oldestKey) cache.delete(oldestKey);
|
|
40
30
|
}
|
|
31
|
+
cache.set(key, instance);
|
|
41
32
|
return instance;
|
|
42
33
|
}
|
|
43
34
|
Wrapped.prototype = Ctor.prototype;
|
|
44
35
|
return Wrapped;
|
|
45
36
|
};
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Factory that turns the global `Intl` into a cached clone.
|
|
39
|
+
*/
|
|
40
|
+
const createCachedIntl = () => {
|
|
41
|
+
const constructorCache = /* @__PURE__ */ new Map();
|
|
42
|
+
return new Proxy(Intl, { get: (target, prop, receiver) => {
|
|
43
|
+
if (constructorCache.has(prop)) return constructorCache.get(prop);
|
|
44
|
+
const value = Reflect.get(target, prop, receiver);
|
|
45
|
+
if (typeof value === "function" && typeof prop === "string" && /^[A-Z]/.test(prop)) {
|
|
46
|
+
const wrapped = createCachedConstructor(value);
|
|
47
|
+
constructorCache.set(prop, wrapped);
|
|
48
|
+
return wrapped;
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
} });
|
|
52
|
+
};
|
|
50
53
|
const CachedIntl = createCachedIntl();
|
|
51
54
|
|
|
52
55
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intl.cjs","names":["Locales"
|
|
1
|
+
{"version":3,"file":"intl.cjs","names":["Locales"],"sources":["../../../src/utils/intl.ts"],"sourcesContent":["// Cached Intl helper – drop‑in replacement for the global `Intl` object.\n// ‑‑‑\n// • Uses a `Proxy` to lazily wrap every *constructor* hanging off `Intl` (NumberFormat, DateTimeFormat, …).\n// • Each wrapped constructor keeps an in‑memory cache keyed by `[locales, options]` so that identical requests\n// reuse the same heavy instance instead of reparsing CLDR data every time.\n// • A polyfill warning for `Intl.DisplayNames` is emitted only once and only in dev.\n// • The public API is fully type‑safe and mirrors the native `Intl` surface exactly –\n// you can treat `CachedIntl` just like the built‑in `Intl`.\n//\n// Usage examples:\n// ---------------\n// import { CachedIntl } from \"./cached-intl\";\n//\n// const nf = CachedIntl.NumberFormat(\"en-US\", { style: \"currency\", currency: \"USD\" });\n// console.log(nf.format(1234));\n//\n// const dn = CachedIntl.DisplayNames([\"fr\"], { type: \"language\" });\n// console.log(dn.of(\"en\")); // → \"anglais\"\n//\n// You can also spin up an isolated instance with its own caches (handy in test suites):\n// const TestIntl = createCachedIntl();\n//\n// ---------------------------------------------------------------------\n\nimport { Locales, type LocalesValues } from '@intlayer/types';\n\n// Helper type that picks just the constructor members off `typeof Intl`.\n// The \"capital‑letter\" heuristic is 100 % accurate today and keeps the\n// mapping short‑lived, so we don't have to manually list every constructor.\ntype IntlConstructors = {\n [K in keyof typeof Intl as (typeof Intl)[K] extends new (\n ...args: any\n ) => any\n ? K\n : never]: (typeof Intl)[K];\n};\n\n// Type wrapper to replace locale arguments with LocalesValues\ntype ReplaceLocaleWithLocalesValues<T> = T extends new (\n locales: any,\n options?: infer Options\n) => infer Instance\n ? new (\n locales?: LocalesValues,\n options?: Options\n ) => Instance\n : T extends new (\n locales: any\n ) => infer Instance\n ? new (\n locales?: LocalesValues\n ) => Instance\n : T;\n\n// Wrapped Intl type with LocalesValues\ntype WrappedIntl = {\n [K in keyof typeof Intl]: K extends keyof IntlConstructors\n ? ReplaceLocaleWithLocalesValues<(typeof Intl)[K]>\n : (typeof Intl)[K];\n};\n\n// ... (Keep your Type Helper definitions here: IntlConstructors, ReplaceLocaleWithLocalesValues, WrappedIntl) ...\n\n/**\n * Optimized Cache Key Generator\n * 1. Fast path: If no options, just use the locale string.\n * 2. Normal path: JSON.stringify for deterministic object comparison.\n */\nconst getCacheKey = (\n locales: LocalesValues | undefined,\n options: unknown\n): string => {\n const localeKey = locales ? String(locales) : Locales.ENGLISH;\n\n if (!options) return localeKey;\n\n // JSON.stringify is the most robust way to handle nested options objects\n // without a heavy custom hashing function.\n return `${localeKey}|${JSON.stringify(options)}`;\n};\n\n/**\n * Generic wrapper for any `new Intl.*()` constructor.\n */\nconst createCachedConstructor = <T extends new (...args: any[]) => any>(\n Ctor: T\n) => {\n // The cache lives here, inside the closure of the wrapped constructor.\n const cache = new Map<string, InstanceType<T>>();\n const MAX_CACHE_SIZE = 50;\n\n function Wrapped(locales?: LocalesValues, options?: any) {\n // 1. Handle DisplayNames Polyfill warning (Keep your existing logic here)\n if (\n Ctor.name === 'DisplayNames' &&\n typeof (Intl as any)?.DisplayNames !== 'function'\n ) {\n // ... (Your existing polyfill warning logic) ...\n return locales as any;\n }\n\n // 2. Generate Key\n const key = getCacheKey(locales, options);\n\n // 3. Check Cache\n let instance = cache.get(key);\n if (instance) return instance;\n\n // 4. Create New Instance\n instance = new Ctor(locales as never, options as never);\n\n // 5. Smart Eviction (LRU-ish)\n // Map iterates in insertion order. Deleting the first key removes the \"oldest\".\n if (cache.size >= MAX_CACHE_SIZE) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey) cache.delete(oldestKey);\n }\n\n cache.set(key, instance as InstanceType<T>);\n return instance as InstanceType<T>;\n }\n\n // Preserve prototype for `instanceof` checks\n (Wrapped as any).prototype = (Ctor as any).prototype;\n\n return Wrapped as unknown as ReplaceLocaleWithLocalesValues<T>;\n};\n\n/**\n * Factory that turns the global `Intl` into a cached clone.\n */\nexport const createCachedIntl = (): WrappedIntl => {\n // 🔥 CRITICAL OPTIMIZATION:\n // We must cache the *wrapped constructors* themselves.\n // Otherwise, the Proxy creates a new `Wrapped` function (and a new empty Map)\n // on every single property access.\n const constructorCache = new Map<string | symbol, any>();\n\n return new Proxy(Intl as IntlConstructors, {\n get: (target, prop, receiver) => {\n // 1. Fast return if we already wrapped this constructor\n if (constructorCache.has(prop)) {\n return constructorCache.get(prop);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n // 2. Wrap only Constructors (Heuristic: Function + starts with Uppercase)\n // This prevents wrapping static methods like `Intl.getCanonicalLocales`\n if (\n typeof value === 'function' &&\n typeof prop === 'string' &&\n /^[A-Z]/.test(prop)\n ) {\n const wrapped = createCachedConstructor(value);\n constructorCache.set(prop, wrapped);\n return wrapped;\n }\n\n // 3. Pass through everything else (static methods, constants)\n return value;\n },\n }) as unknown as WrappedIntl;\n};\n\nexport const CachedIntl = createCachedIntl();\n\n// new CachedIntl.DisplayNames(Locales.FRENCH, { type: 'language' });\n// new CachedIntl.DisplayNames('fr', { type: 'language' });\n// new CachedIntl.DateTimeFormat('fr', {\n// year: 'numeric',\n// month: 'long',\n// day: 'numeric',\n// });\n// new CachedIntl.NumberFormat('fr', {\n// style: 'currency',\n// currency: 'EUR',\n// });\n// new CachedIntl.Collator('fr', { sensitivity: 'base' });\n// new CachedIntl.PluralRules('fr');\n// new CachedIntl.RelativeTimeFormat('fr', { numeric: 'auto' });\n// new CachedIntl.ListFormat('fr', { type: 'conjunction' });\nexport { CachedIntl as Intl };\n"],"mappings":";;;;;;;;;AAoEA,MAAM,eACJ,SACA,YACW;CACX,MAAM,YAAY,UAAU,OAAO,QAAQ,GAAGA,wBAAQ;AAEtD,KAAI,CAAC,QAAS,QAAO;AAIrB,QAAO,GAAG,UAAU,GAAG,KAAK,UAAU,QAAQ;;;;;AAMhD,MAAM,2BACJ,SACG;CAEH,MAAM,wBAAQ,IAAI,KAA8B;CAChD,MAAM,iBAAiB;CAEvB,SAAS,QAAQ,SAAyB,SAAe;AAEvD,MACE,KAAK,SAAS,kBACd,OAAQ,MAAc,iBAAiB,WAGvC,QAAO;EAIT,MAAM,MAAM,YAAY,SAAS,QAAQ;EAGzC,IAAI,WAAW,MAAM,IAAI,IAAI;AAC7B,MAAI,SAAU,QAAO;AAGrB,aAAW,IAAI,KAAK,SAAkB,QAAiB;AAIvD,MAAI,MAAM,QAAQ,gBAAgB;GAChC,MAAM,YAAY,MAAM,MAAM,CAAC,MAAM,CAAC;AACtC,OAAI,UAAW,OAAM,OAAO,UAAU;;AAGxC,QAAM,IAAI,KAAK,SAA4B;AAC3C,SAAO;;AAIT,CAAC,QAAgB,YAAa,KAAa;AAE3C,QAAO;;;;;AAMT,MAAa,yBAAsC;CAKjD,MAAM,mCAAmB,IAAI,KAA2B;AAExD,QAAO,IAAI,MAAM,MAA0B,EACzC,MAAM,QAAQ,MAAM,aAAa;AAE/B,MAAI,iBAAiB,IAAI,KAAK,CAC5B,QAAO,iBAAiB,IAAI,KAAK;EAGnC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,MAAM,SAAS;AAIjD,MACE,OAAO,UAAU,cACjB,OAAO,SAAS,YAChB,SAAS,KAAK,KAAK,EACnB;GACA,MAAM,UAAU,wBAAwB,MAAM;AAC9C,oBAAiB,IAAI,MAAM,QAAQ;AACnC,UAAO;;AAIT,SAAO;IAEV,CAAC;;AAGJ,MAAa,aAAa,kBAAkB"}
|
|
@@ -22,10 +22,10 @@ const editDictionaryByKeyPath = (dictionaryContent, keyPath, newValue) => {
|
|
|
22
22
|
currentValue = currentValue[keyObj.type][keyObj.key];
|
|
23
23
|
}
|
|
24
24
|
if (keyObj.type === NodeType.Enumeration || keyObj.type === NodeType.Condition) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
25
|
+
if (keyObj.type !== NodeType.Enumeration) {
|
|
26
|
+
lastKeys = [keyObj.type, keyObj.key];
|
|
27
|
+
currentValue = currentValue[keyObj.type][keyObj.key];
|
|
28
|
+
}
|
|
29
29
|
}
|
|
30
30
|
if (keyObj.type === NodeType.Markdown || keyObj.type === NodeType.Insertion) {
|
|
31
31
|
lastKeys = [keyObj.type];
|
|
@@ -36,12 +36,15 @@ const editDictionaryByKeyPath = (dictionaryContent, keyPath, newValue) => {
|
|
|
36
36
|
lastKeys = ["content"];
|
|
37
37
|
currentValue = currentValue.content;
|
|
38
38
|
}
|
|
39
|
-
if (keyObj.type) {}
|
|
40
39
|
if (i === keyPath.length - 1 && parentValue && lastKeys.length > 0) {
|
|
41
40
|
let target = parentValue;
|
|
42
41
|
for (const key of lastKeys.slice(0, -1)) target = target[key];
|
|
43
|
-
|
|
44
|
-
|
|
42
|
+
const finalKey = lastKeys[lastKeys.length - 1];
|
|
43
|
+
if (typeof newValue === "undefined") if (Array.isArray(target)) {
|
|
44
|
+
const index = Number(finalKey);
|
|
45
|
+
if (!isNaN(index) && index >= 0 && index < target.length) target.splice(index, 1);
|
|
46
|
+
} else delete target[finalKey];
|
|
47
|
+
else target[finalKey] = newValue;
|
|
45
48
|
}
|
|
46
49
|
}
|
|
47
50
|
return dictionaryContent;
|