gt 2.22.0 → 2.22.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.
@@ -1 +1 @@
1
- {"version":3,"file":"mergeJson.js","names":[],"sources":["../../../src/formats/json/mergeJson.ts"],"sourcesContent":["import { AdditionalOptions, SourceObjectOptions } from '../../types/index.js';\nimport { exitSync } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n getIdentifyingLocaleProperty,\n getSourceObjectOptionsArray,\n validateJsonSchema,\n} from './utils.js';\nimport {\n getConfiguredLocaleProperties,\n replaceLocalePlaceholders,\n} from '../utils.js';\nimport { api } from '../../utils/api.js';\nimport {\n applyStructuralTransforms,\n unapplyStructuralTransforms,\n} from './transformJson.js';\nimport type { JSONObject, JSONValue } from '../../types/data/json.js';\nimport { getJSONPathMatches, getJSONPathValues } from './jsonPath.js';\nimport { getJSONPointerValue, setJSONPointerValue } from './jsonPointer.js';\n\ntype ParsedTarget = {\n translatedContent: string;\n targetLocale: string;\n parsedContent: JSONObject;\n};\n\nexport function mergeJson(\n originalContent: string,\n inputPath: string,\n options: AdditionalOptions,\n targets: {\n translatedContent: string;\n targetLocale: string;\n }[],\n defaultLocale: string,\n localeOrder: string[] = []\n): string[] {\n const jsonSchema = validateJsonSchema(options, inputPath);\n if (!jsonSchema) {\n return targets.map((target) => target.translatedContent);\n }\n\n let originalJson: JSONValue;\n try {\n originalJson = JSON.parse(originalContent);\n } catch {\n logger.error(`Invalid JSON file: ${inputPath}`);\n return exitSync(1);\n }\n\n const useCanonicalLocaleKeys =\n options?.experimentalCanonicalLocaleKeys ?? false;\n const canonicalDefaultLocale = useCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(defaultLocale)\n : defaultLocale;\n const canonicalLocaleOrder = useCanonicalLocaleKeys\n ? localeOrder.map((locale) => api.resolveCanonicalLocale(locale))\n : localeOrder;\n\n if (jsonSchema.structuralTransform && jsonSchema.composite) {\n applyStructuralTransforms(\n originalJson,\n jsonSchema.structuralTransform,\n jsonSchema.composite\n );\n }\n\n // Handle include\n if (jsonSchema.include) {\n const output: string[] = [];\n for (const target of targets) {\n // Must clone the original JSON to avoid mutations\n const mergedJson = structuredClone(originalJson);\n const translatedJson = JSON.parse(target.translatedContent) as JSONObject;\n for (const [jsonPointer, translatedValue] of Object.entries(\n translatedJson\n )) {\n try {\n const value = getJSONPointerValue(mergedJson, jsonPointer);\n if (!value) continue;\n setJSONPointerValue(mergedJson, jsonPointer, translatedValue);\n } catch {\n /* empty */\n }\n }\n output.push(JSON.stringify(mergedJson, null, 2));\n }\n return output;\n }\n\n if (!jsonSchema.composite) {\n logger.error('No composite property found in JSON schema');\n return exitSync(1);\n }\n\n // Handle composite\n // Create a deep copy of the original JSON to avoid mutations\n const mergedJson = structuredClone(originalJson);\n\n // Pre-parse all target contents ONCE (avoid re-parsing per pointer)\n const parsedTargets = targets.map((target) => ({\n ...target,\n parsedContent: JSON.parse(target.translatedContent) as JSONObject,\n })) satisfies ParsedTarget[];\n\n // Create mapping of sourceObjectPointer to SourceObjectOptions\n const sourceObjectPointers = generateSourceObjectPointers(\n jsonSchema.composite,\n originalJson\n );\n\n // Find the source object\n for (const [\n sourceObjectPointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(sourceObjectPointers)) {\n // Find the source item\n if (sourceObjectOptions.type === 'array') {\n // Validate type\n if (!Array.isArray(sourceObjectValue)) {\n logger.error(\n `Source object value is not an array at path: ${sourceObjectPointer}`\n );\n return exitSync(1);\n }\n\n // Get source item for default locale\n const matchingDefaultLocaleItems = findMatchingItemArray(\n canonicalDefaultLocale,\n sourceObjectOptions,\n sourceObjectPointer,\n sourceObjectValue\n );\n if (!Object.keys(matchingDefaultLocaleItems).length) {\n logger.warn(\n `Matching sourceItems not found at path: ${sourceObjectPointer}. Check that your JSON file includes the key field. Skipping this target`\n );\n continue;\n }\n\n const matchingDefaultLocaleItemKeys = new Set(\n Object.keys(matchingDefaultLocaleItems)\n );\n\n // For each target:\n // 1. Get the target items\n // 2. Track all array indecies to remove (will be overwritten)\n // 3. Merge matchingDefaultLocaleItems and targetItems\n // 4. Validate that the mergedItems is not empty\n // For each target item:\n // 5. Validate that all the array indecies are still present in the source json\n // 6. Override the source item with the translated values\n // 7. Apply additional mutations to the sourceItem\n // 8. Track all items to add\n // 9. Check that items to add is >= items to remove\n // 10. Remove all items for the target locale (they can be identified by the key)\n const indiciesToRemove = new Set<number>();\n const itemsToAdd: JSONValue[] = [];\n for (const target of parsedTargets) {\n let targetItems = target.parsedContent[sourceObjectPointer];\n // 1. Get the target items\n if (!targetItems) {\n // If no translation can be found, a transformation may need to happen still\n targetItems = {};\n }\n\n // 2. Track all array indecies to remove (will be overwritten)\n const targetItemsToRemove = findMatchingItemArray(\n useCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(target.targetLocale)\n : target.targetLocale,\n sourceObjectOptions,\n sourceObjectPointer,\n sourceObjectValue\n );\n Object.values(targetItemsToRemove).forEach(({ index }) =>\n indiciesToRemove.add(index)\n );\n\n // Remap mismatched positional keys to current source positions\n const sourceKeys = [...matchingDefaultLocaleItemKeys];\n const remappedTargetItems: Record<string, JSONValue> = {};\n for (const [key, value] of Object.entries(targetItems as JSONObject)) {\n if (matchingDefaultLocaleItemKeys.has(key)) {\n remappedTargetItems[key] = value;\n } else if (\n sourceKeys.length === 1 &&\n !(sourceKeys[0] in remappedTargetItems)\n ) {\n remappedTargetItems[sourceKeys[0]] = value;\n } else {\n logger.warn(\n `Skipping translated item at ${key}: cannot map to source item at path ${sourceObjectPointer}`\n );\n }\n }\n\n // Merge matchingDefaultLocaleItems and remapped targetItems\n const mergedItems = {\n ...(sourceObjectOptions.transform ? matchingDefaultLocaleItems : {}),\n ...remappedTargetItems,\n };\n // 4. Validate that the mergedItems is not empty\n if (Object.keys(mergedItems).length === 0) {\n logger.warn(\n `Translated JSON for locale: ${target.targetLocale} does not have a valid sourceObjectPointer: ${sourceObjectPointer}. Skipping this target`\n );\n continue;\n }\n\n for (const [sourceItemPointer, targetItem] of Object.entries(\n mergedItems\n )) {\n // 5. Validate that all the array indecies are still present in the source json\n if (!matchingDefaultLocaleItemKeys.has(sourceItemPointer)) {\n logger.warn(\n `Skipping translated item at ${sourceItemPointer}: not present in source json at path ${sourceObjectPointer}`\n );\n continue;\n }\n\n // 6. Override the source item with the translated values\n const defaultLocaleSourceItem =\n matchingDefaultLocaleItems[sourceItemPointer].sourceItem;\n const defaultLocaleKeyPointer =\n matchingDefaultLocaleItems[sourceItemPointer].keyPointer;\n const mutatedSourceItem = structuredClone(defaultLocaleSourceItem);\n const { identifyingLocaleProperty: targetLocaleKeyProperty } =\n getSourceObjectOptionsArray(\n useCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(target.targetLocale)\n : target.targetLocale,\n sourceObjectPointer,\n sourceObjectOptions\n );\n setJSONPointerValue(\n mutatedSourceItem,\n defaultLocaleKeyPointer,\n targetLocaleKeyProperty\n );\n omitProperties(mutatedSourceItem, sourceObjectOptions.omitProperties);\n for (const [\n translatedKeyJsonPointer,\n translatedValue,\n ] of Object.entries((targetItem || {}) as JSONObject)) {\n const valueToSet =\n useCanonicalLocaleKeys &&\n defaultLocaleKeyPointer &&\n translatedKeyJsonPointer === defaultLocaleKeyPointer\n ? targetLocaleKeyProperty\n : translatedValue;\n try {\n const value = getJSONPointerValue(\n mutatedSourceItem,\n translatedKeyJsonPointer\n );\n if (!value) continue;\n setJSONPointerValue(\n mutatedSourceItem,\n translatedKeyJsonPointer,\n valueToSet\n );\n } catch {\n /* empty */\n }\n }\n\n // 7. Apply additional mutations to the sourceItem\n applyTransformations(\n mutatedSourceItem,\n sourceObjectOptions.transform,\n target.targetLocale,\n defaultLocale\n );\n\n itemsToAdd.push(mutatedSourceItem);\n }\n }\n\n // 8. Check that items to add is >= items to remove\n if (itemsToAdd.length < indiciesToRemove.size) {\n logger.warn(\n `Items to add (${itemsToAdd.length}) is less than items to remove (${indiciesToRemove.size}) at path: ${sourceObjectPointer}. Some translated items may have been skipped.`\n );\n }\n\n // 9. Remove all items for the target locale (they can be identified by the key)\n const filteredSourceObjectValue = sourceObjectValue.filter(\n (_, index: number) => !indiciesToRemove.has(index)\n );\n\n // 10. Add all items to the original JSON\n filteredSourceObjectValue.push(...itemsToAdd);\n\n setJSONPointerValue(\n mergedJson,\n sourceObjectPointer,\n sortByLocaleOrder(\n filteredSourceObjectValue,\n sourceObjectOptions,\n canonicalLocaleOrder,\n sourceObjectPointer,\n canonicalDefaultLocale\n )\n );\n } else {\n // Validate type\n if (typeof sourceObjectValue !== 'object' || sourceObjectValue === null) {\n logger.error(\n `Source object value is not an object at path: ${sourceObjectPointer}`\n );\n return exitSync(1);\n }\n const sourceObjectRecord = sourceObjectValue as JSONObject;\n // Validate localeProperty\n const matchingDefaultLocaleItem = findMatchingItemObject(\n canonicalDefaultLocale,\n sourceObjectPointer,\n sourceObjectOptions,\n sourceObjectRecord\n );\n // Validate source item exists\n if (!matchingDefaultLocaleItem.sourceItem) {\n logger.error(\n `Source item not found at path: ${sourceObjectPointer}. You must specify a source item where its key matches the default locale`\n );\n return exitSync(1);\n }\n const { sourceItem: defaultLocaleSourceItem } = matchingDefaultLocaleItem;\n\n // For each target:\n // 1. Get the target items\n // 2. Find the source item for the target locale\n // 3. Merge the target items with the source item\n // 4. Validate that the mergedItems is not empty\n // 5. Override the source item with the translated values\n // 6. Apply additional mutations to the sourceItem\n // 7. Merge the source item with the original JSON (if the source item is not a new item)\n for (const target of parsedTargets) {\n // 1. Get the target items\n let targetItems = target.parsedContent[sourceObjectPointer];\n if (targetItems == null) {\n targetItems = {};\n }\n\n // 2. Find the source item for the target locale\n const matchingTargetItem = findMatchingItemObject(\n useCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(target.targetLocale)\n : target.targetLocale,\n sourceObjectPointer,\n sourceObjectOptions,\n sourceObjectRecord\n );\n const mutateSourceItemKey = matchingTargetItem.keyParentProperty;\n\n // If the source item is a string, use the translated string directly\n if (typeof defaultLocaleSourceItem === 'string') {\n if (typeof targetItems === 'string') {\n sourceObjectRecord[mutateSourceItemKey] = targetItems;\n }\n // If no translation found, leave the locale slot unchanged\n continue;\n }\n\n // If the target locale has a matching source item, use it to mutate the source item\n // Otherwise, fallback to the default locale source item\n const mutateSourceItem = structuredClone(defaultLocaleSourceItem);\n omitProperties(mutateSourceItem, sourceObjectOptions.omitProperties);\n\n // 3. Merge the target items with the source item (if there are transformations to perform)\n const mergedItems: Record<string, JSONValue> = {\n ...(sourceObjectOptions.transform\n ? (defaultLocaleSourceItem as JSONObject)\n : {}),\n ...(targetItems as JSONObject),\n };\n\n // 4. Validate that the mergedItems is not empty\n if (Object.keys(mergedItems).length === 0) {\n logger.warn(\n `Translated JSON for locale: ${target.targetLocale} does not have a valid sourceObjectPointer: ${sourceObjectPointer}. Skipping this target`\n );\n continue;\n }\n\n // 5. Override the source item with the translated values\n for (const [\n translatedKeyJsonPointer,\n translatedValue,\n ] of Object.entries(mergedItems || {})) {\n try {\n const value = getJSONPointerValue(\n mutateSourceItem,\n translatedKeyJsonPointer\n );\n if (!value) continue;\n setJSONPointerValue(\n mutateSourceItem,\n translatedKeyJsonPointer,\n translatedValue\n );\n } catch {\n /* empty */\n }\n }\n // 6. Apply additional mutations to the sourceItem\n applyTransformations(\n mutateSourceItem,\n sourceObjectOptions.transform,\n target.targetLocale,\n defaultLocale\n );\n\n // 7. Merge the source item with the original JSON\n sourceObjectRecord[mutateSourceItemKey] = mutateSourceItem;\n }\n setJSONPointerValue(mergedJson, sourceObjectPointer, sourceObjectValue);\n }\n }\n if (jsonSchema.structuralTransform && jsonSchema.composite) {\n unapplyStructuralTransforms(\n mergedJson,\n jsonSchema.structuralTransform,\n jsonSchema.composite\n );\n }\n\n return [JSON.stringify(mergedJson, null, 2)];\n}\n\nfunction sortByLocaleOrder(\n items: JSONValue[],\n sourceObjectOptions: SourceObjectOptions,\n localeOrder: string[],\n sourceObjectPointer: string,\n defaultLocale: string\n): JSONValue[] {\n const sortMode = sourceObjectOptions.experimentalSort;\n if (!sortMode || !sourceObjectOptions.key) {\n return items;\n }\n\n const itemsWithLocale = items.map((item) => {\n let localeValue: string | undefined;\n try {\n const values = getJSONPathValues(item, sourceObjectOptions.key as string);\n const value = values?.[0];\n if (typeof value === 'string') {\n localeValue = value;\n }\n } catch {\n /* empty */\n }\n return { item, localeValue };\n });\n\n if (sortMode === 'locales') {\n if (!localeOrder.length) {\n return items;\n }\n\n const orderedLocaleList = [\n defaultLocale,\n ...localeOrder.filter((locale) => locale !== defaultLocale),\n ];\n const localeOrderValues = orderedLocaleList.map((locale) =>\n getIdentifyingLocaleProperty(\n locale,\n sourceObjectPointer,\n sourceObjectOptions\n )\n );\n\n const orderedItems: JSONValue[] = [];\n const remainingItems = [...itemsWithLocale];\n\n for (const localeValue of localeOrderValues) {\n for (let i = 0; i < remainingItems.length; ) {\n const entry = remainingItems[i];\n if (entry.localeValue === localeValue) {\n orderedItems.push(entry.item);\n remainingItems.splice(i, 1);\n continue;\n }\n i += 1;\n }\n }\n\n remainingItems.forEach((entry) => orderedItems.push(entry.item));\n\n return orderedItems;\n }\n\n if (sortMode === 'localesAlphabetical') {\n const defaultLocaleValue = getIdentifyingLocaleProperty(\n defaultLocale,\n sourceObjectPointer,\n sourceObjectOptions\n );\n\n const defaultItems: typeof itemsWithLocale = [];\n const sortableItems: typeof itemsWithLocale = [];\n const remainingItems: typeof itemsWithLocale = [];\n\n for (const entry of itemsWithLocale) {\n if (entry.localeValue === defaultLocaleValue) {\n defaultItems.push(entry);\n continue;\n }\n if (entry.localeValue) {\n sortableItems.push(entry);\n continue;\n }\n remainingItems.push(entry);\n }\n\n sortableItems.sort((a, b) => {\n if (!a.localeValue || !b.localeValue) {\n return 0;\n }\n return a.localeValue.localeCompare(b.localeValue);\n });\n\n return [...defaultItems, ...sortableItems, ...remainingItems].map(\n (entry) => entry.item\n );\n }\n\n return items;\n}\n\n/**\n * Remove top-level properties from a generated non-default-locale entry\n * (e.g. Mintlify's `default: true` flag, which is only valid on one entry)\n */\nfunction omitProperties(\n item: JSONValue,\n properties: string[] | undefined\n): void {\n if (!properties?.length) return;\n if (!item || typeof item !== 'object' || Array.isArray(item)) return;\n for (const property of properties) {\n delete (item as JSONObject)[property];\n }\n}\n\n/**\n * Apply transformations to the sourceItem in-place\n * @param sourceItem - The source item to apply transformations to\n * @param transform - The transformations to apply\n * @param targetLocale - The target locale\n * @param defaultLocale - The default locale\n */\nexport function applyTransformations(\n sourceItem: JSONValue,\n transform: SourceObjectOptions['transform'],\n targetLocale: string,\n defaultLocale: string\n): void {\n if (!transform) return;\n\n const targetLocaleProperties = getConfiguredLocaleProperties(targetLocale);\n const defaultLocaleProperties = getConfiguredLocaleProperties(defaultLocale);\n\n for (const [transformPath, transformOptions] of Object.entries(transform)) {\n if (\n !transformOptions.replace ||\n typeof transformOptions.replace !== 'string'\n ) {\n continue;\n }\n const results = getJSONPathMatches(sourceItem, transformPath);\n if (!results || results.length === 0) {\n continue;\n }\n results.forEach((result) => {\n if (typeof result.value !== 'string') {\n return;\n }\n // Replace locale placeholders in the replace string\n let replaceString = transformOptions.replace;\n\n // Replace all locale property placeholders\n replaceString = replaceLocalePlaceholders(\n replaceString,\n targetLocaleProperties\n );\n\n if (\n transformOptions.match &&\n typeof transformOptions.match === 'string'\n ) {\n // Replace locale placeholders in the match string using defaultLocale properties\n let matchString = transformOptions.match;\n matchString = replaceLocalePlaceholders(\n matchString,\n defaultLocaleProperties\n );\n\n result.value = result.value.replace(\n new RegExp(matchString, 'g'),\n replaceString\n );\n } else {\n result.value = replaceString;\n }\n\n // Update the actual sourceItem using JSONPointer\n setJSONPointerValue(sourceItem, result.pointer, result.value);\n });\n }\n}\n"],"mappings":";;;;;;;;;AA8BA,SAAgB,UACd,iBACA,WACA,SACA,SAIA,eACA,cAAwB,EAAE,EAChB;CACV,MAAM,aAAa,mBAAmB,SAAS,UAAU;AACzD,KAAI,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MAAK,MAAM,YAAY,WACrB,QAAQ,KAAoB;;;;;;;;;AAWhC,SAAgB,qBACd,YACA,WACA,cACA,eACM;AACN,KAAI,CAAC,UAAW;CAEhB,MAAM,yBAAyB,8BAA8B,aAAa;CAC1E,MAAM,0BAA0B,8BAA8B,cAAc;AAE5E,MAAK,MAAM,CAAC,eAAe,qBAAqB,OAAO,QAAQ,UAAU,EAAE;AACzE,MACE,CAAC,iBAAiB,WAClB,OAAO,iBAAiB,YAAY,SAEpC;EAEF,MAAM,UAAU,mBAAmB,YAAY,cAAc;AAC7D,MAAI,CAAC,WAAW,QAAQ,WAAW,EACjC;AAEF,UAAQ,SAAS,WAAW;AAC1B,OAAI,OAAO,OAAO,UAAU,SAC1B;GAGF,IAAI,gBAAgB,iBAAiB;AAGrC,mBAAgB,0BACd,eACA,uBACD;AAED,OACE,iBAAiB,SACjB,OAAO,iBAAiB,UAAU,UAClC;IAEA,IAAI,cAAc,iBAAiB;AACnC,kBAAc,0BACZ,aACA,wBACD;AAED,WAAO,QAAQ,OAAO,MAAM,QAC1B,IAAI,OAAO,aAAa,IAAI,EAC5B,cACD;SAED,QAAO,QAAQ;AAIjB,uBAAoB,YAAY,OAAO,SAAS,OAAO,MAAM;IAC7D"}
1
+ {"version":3,"file":"mergeJson.js","names":[],"sources":["../../../src/formats/json/mergeJson.ts"],"sourcesContent":["import type { LocaleProperties } from '@generaltranslation/format/types';\nimport {\n AdditionalOptions,\n SourceObjectOptions,\n TransformOption,\n} from '../../types/index.js';\nimport { exitSync } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n getIdentifyingLocaleProperty,\n getSourceObjectOptionsArray,\n validateJsonSchema,\n} from './utils.js';\nimport {\n getConfiguredLocaleProperties,\n replaceLocalePlaceholders,\n} from '../utils.js';\nimport { api } from '../../utils/api.js';\nimport {\n applyStructuralTransforms,\n unapplyStructuralTransforms,\n} from './transformJson.js';\nimport type { JSONObject, JSONValue } from '../../types/data/json.js';\nimport { getJSONPathMatches, getJSONPathValues } from './jsonPath.js';\nimport { getJSONPointerValue, setJSONPointerValue } from './jsonPointer.js';\n\ntype ParsedTarget = {\n translatedContent: string;\n targetLocale: string;\n parsedContent: JSONObject;\n};\n\nexport function mergeJson(\n originalContent: string,\n inputPath: string,\n options: AdditionalOptions,\n targets: {\n translatedContent: string;\n targetLocale: string;\n }[],\n defaultLocale: string,\n localeOrder: string[] = []\n): string[] {\n const jsonSchema = validateJsonSchema(options, inputPath);\n if (!jsonSchema) {\n return targets.map((target) => target.translatedContent);\n }\n\n let originalJson: JSONValue;\n try {\n originalJson = JSON.parse(originalContent);\n } catch {\n logger.error(`Invalid JSON file: ${inputPath}`);\n return exitSync(1);\n }\n\n const useCanonicalLocaleKeys =\n options?.experimentalCanonicalLocaleKeys ?? false;\n const canonicalDefaultLocale = useCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(defaultLocale)\n : defaultLocale;\n const canonicalLocaleOrder = useCanonicalLocaleKeys\n ? localeOrder.map((locale) => api.resolveCanonicalLocale(locale))\n : localeOrder;\n\n if (jsonSchema.structuralTransform && jsonSchema.composite) {\n applyStructuralTransforms(\n originalJson,\n jsonSchema.structuralTransform,\n jsonSchema.composite\n );\n }\n\n // Handle include\n if (jsonSchema.include) {\n const output: string[] = [];\n for (const target of targets) {\n // Must clone the original JSON to avoid mutations\n const mergedJson = structuredClone(originalJson);\n const translatedJson = JSON.parse(target.translatedContent) as JSONObject;\n for (const [jsonPointer, translatedValue] of Object.entries(\n translatedJson\n )) {\n try {\n const value = getJSONPointerValue(mergedJson, jsonPointer);\n if (!value) continue;\n setJSONPointerValue(mergedJson, jsonPointer, translatedValue);\n } catch {\n /* empty */\n }\n }\n output.push(JSON.stringify(mergedJson, null, 2));\n }\n return output;\n }\n\n if (!jsonSchema.composite) {\n logger.error('No composite property found in JSON schema');\n return exitSync(1);\n }\n\n // Handle composite\n // Create a deep copy of the original JSON to avoid mutations\n const mergedJson = structuredClone(originalJson);\n\n // Pre-parse all target contents ONCE (avoid re-parsing per pointer)\n const parsedTargets = targets.map((target) => ({\n ...target,\n parsedContent: JSON.parse(target.translatedContent) as JSONObject,\n })) satisfies ParsedTarget[];\n\n // Create mapping of sourceObjectPointer to SourceObjectOptions\n const sourceObjectPointers = generateSourceObjectPointers(\n jsonSchema.composite,\n originalJson\n );\n\n // Find the source object\n for (const [\n sourceObjectPointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(sourceObjectPointers)) {\n // Find the source item\n if (sourceObjectOptions.type === 'array') {\n // Validate type\n if (!Array.isArray(sourceObjectValue)) {\n logger.error(\n `Source object value is not an array at path: ${sourceObjectPointer}`\n );\n return exitSync(1);\n }\n\n // Get source item for default locale\n const matchingDefaultLocaleItems = findMatchingItemArray(\n canonicalDefaultLocale,\n sourceObjectOptions,\n sourceObjectPointer,\n sourceObjectValue\n );\n if (!Object.keys(matchingDefaultLocaleItems).length) {\n logger.warn(\n `Matching sourceItems not found at path: ${sourceObjectPointer}. Check that your JSON file includes the key field. Skipping this target`\n );\n continue;\n }\n\n const matchingDefaultLocaleItemKeys = new Set(\n Object.keys(matchingDefaultLocaleItems)\n );\n\n // For each target:\n // 1. Get the target items\n // 2. Track all array indecies to remove (will be overwritten)\n // 3. Merge matchingDefaultLocaleItems and targetItems\n // 4. Validate that the mergedItems is not empty\n // For each target item:\n // 5. Validate that all the array indecies are still present in the source json\n // 6. Override the source item with the translated values\n // 7. Apply additional mutations to the sourceItem\n // 8. Track all items to add\n // 9. Check that items to add is >= items to remove\n // 10. Remove all items for the target locale (they can be identified by the key)\n const indiciesToRemove = new Set<number>();\n const itemsToAdd: JSONValue[] = [];\n for (const target of parsedTargets) {\n let targetItems = target.parsedContent[sourceObjectPointer];\n // 1. Get the target items\n if (!targetItems) {\n // If no translation can be found, a transformation may need to happen still\n targetItems = {};\n }\n\n // 2. Track all array indecies to remove (will be overwritten)\n const targetItemsToRemove = findMatchingItemArray(\n useCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(target.targetLocale)\n : target.targetLocale,\n sourceObjectOptions,\n sourceObjectPointer,\n sourceObjectValue\n );\n Object.values(targetItemsToRemove).forEach(({ index }) =>\n indiciesToRemove.add(index)\n );\n\n // Remap mismatched positional keys to current source positions\n const sourceKeys = [...matchingDefaultLocaleItemKeys];\n const remappedTargetItems: Record<string, JSONValue> = {};\n for (const [key, value] of Object.entries(targetItems as JSONObject)) {\n if (matchingDefaultLocaleItemKeys.has(key)) {\n remappedTargetItems[key] = value;\n } else if (\n sourceKeys.length === 1 &&\n !(sourceKeys[0] in remappedTargetItems)\n ) {\n remappedTargetItems[sourceKeys[0]] = value;\n } else {\n logger.warn(\n `Skipping translated item at ${key}: cannot map to source item at path ${sourceObjectPointer}`\n );\n }\n }\n\n // Merge matchingDefaultLocaleItems and remapped targetItems\n const mergedItems = {\n ...(sourceObjectOptions.transform ? matchingDefaultLocaleItems : {}),\n ...remappedTargetItems,\n };\n // 4. Validate that the mergedItems is not empty\n if (Object.keys(mergedItems).length === 0) {\n logger.warn(\n `Translated JSON for locale: ${target.targetLocale} does not have a valid sourceObjectPointer: ${sourceObjectPointer}. Skipping this target`\n );\n continue;\n }\n\n for (const [sourceItemPointer, targetItem] of Object.entries(\n mergedItems\n )) {\n // 5. Validate that all the array indecies are still present in the source json\n if (!matchingDefaultLocaleItemKeys.has(sourceItemPointer)) {\n logger.warn(\n `Skipping translated item at ${sourceItemPointer}: not present in source json at path ${sourceObjectPointer}`\n );\n continue;\n }\n\n // 6. Override the source item with the translated values\n const defaultLocaleSourceItem =\n matchingDefaultLocaleItems[sourceItemPointer].sourceItem;\n const defaultLocaleKeyPointer =\n matchingDefaultLocaleItems[sourceItemPointer].keyPointer;\n const mutatedSourceItem = structuredClone(defaultLocaleSourceItem);\n const { identifyingLocaleProperty: targetLocaleKeyProperty } =\n getSourceObjectOptionsArray(\n useCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(target.targetLocale)\n : target.targetLocale,\n sourceObjectPointer,\n sourceObjectOptions\n );\n setJSONPointerValue(\n mutatedSourceItem,\n defaultLocaleKeyPointer,\n targetLocaleKeyProperty\n );\n omitProperties(mutatedSourceItem, sourceObjectOptions.omitProperties);\n for (const [\n translatedKeyJsonPointer,\n translatedValue,\n ] of Object.entries((targetItem || {}) as JSONObject)) {\n const valueToSet =\n useCanonicalLocaleKeys &&\n defaultLocaleKeyPointer &&\n translatedKeyJsonPointer === defaultLocaleKeyPointer\n ? targetLocaleKeyProperty\n : translatedValue;\n try {\n const value = getJSONPointerValue(\n mutatedSourceItem,\n translatedKeyJsonPointer\n );\n if (!value) continue;\n setJSONPointerValue(\n mutatedSourceItem,\n translatedKeyJsonPointer,\n valueToSet\n );\n } catch {\n /* empty */\n }\n }\n\n // 7. Apply additional mutations to the sourceItem\n applyTransformations(\n mutatedSourceItem,\n sourceObjectOptions.transform,\n target.targetLocale,\n defaultLocale\n );\n\n itemsToAdd.push(mutatedSourceItem);\n }\n }\n\n // 8. Check that items to add is >= items to remove\n if (itemsToAdd.length < indiciesToRemove.size) {\n logger.warn(\n `Items to add (${itemsToAdd.length}) is less than items to remove (${indiciesToRemove.size}) at path: ${sourceObjectPointer}. Some translated items may have been skipped.`\n );\n }\n\n // 9. Remove all items for the target locale (they can be identified by the key)\n const filteredSourceObjectValue = sourceObjectValue.filter(\n (_, index: number) => !indiciesToRemove.has(index)\n );\n\n // 10. Add all items to the original JSON\n filteredSourceObjectValue.push(...itemsToAdd);\n\n setJSONPointerValue(\n mergedJson,\n sourceObjectPointer,\n sortByLocaleOrder(\n filteredSourceObjectValue,\n sourceObjectOptions,\n canonicalLocaleOrder,\n sourceObjectPointer,\n canonicalDefaultLocale\n )\n );\n } else {\n // Validate type\n if (typeof sourceObjectValue !== 'object' || sourceObjectValue === null) {\n logger.error(\n `Source object value is not an object at path: ${sourceObjectPointer}`\n );\n return exitSync(1);\n }\n const sourceObjectRecord = sourceObjectValue as JSONObject;\n // Validate localeProperty\n const matchingDefaultLocaleItem = findMatchingItemObject(\n canonicalDefaultLocale,\n sourceObjectPointer,\n sourceObjectOptions,\n sourceObjectRecord\n );\n // Validate source item exists\n if (!matchingDefaultLocaleItem.sourceItem) {\n logger.error(\n `Source item not found at path: ${sourceObjectPointer}. You must specify a source item where its key matches the default locale`\n );\n return exitSync(1);\n }\n const { sourceItem: defaultLocaleSourceItem } = matchingDefaultLocaleItem;\n\n // For each target:\n // 1. Get the target items\n // 2. Find the source item for the target locale\n // 3. Merge the target items with the source item\n // 4. Validate that the mergedItems is not empty\n // 5. Override the source item with the translated values\n // 6. Apply additional mutations to the sourceItem\n // 7. Merge the source item with the original JSON (if the source item is not a new item)\n for (const target of parsedTargets) {\n // 1. Get the target items\n let targetItems = target.parsedContent[sourceObjectPointer];\n if (targetItems == null) {\n targetItems = {};\n }\n\n // 2. Find the source item for the target locale\n const matchingTargetItem = findMatchingItemObject(\n useCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(target.targetLocale)\n : target.targetLocale,\n sourceObjectPointer,\n sourceObjectOptions,\n sourceObjectRecord\n );\n const mutateSourceItemKey = matchingTargetItem.keyParentProperty;\n\n // If the source item is a string, use the translated string directly\n if (typeof defaultLocaleSourceItem === 'string') {\n if (typeof targetItems === 'string') {\n sourceObjectRecord[mutateSourceItemKey] = targetItems;\n }\n // If no translation found, leave the locale slot unchanged\n continue;\n }\n\n // If the target locale has a matching source item, use it to mutate the source item\n // Otherwise, fallback to the default locale source item\n const mutateSourceItem = structuredClone(defaultLocaleSourceItem);\n omitProperties(mutateSourceItem, sourceObjectOptions.omitProperties);\n\n // 3. Merge the target items with the source item (if there are transformations to perform)\n const mergedItems: Record<string, JSONValue> = {\n ...(sourceObjectOptions.transform\n ? (defaultLocaleSourceItem as JSONObject)\n : {}),\n ...(targetItems as JSONObject),\n };\n\n // 4. Validate that the mergedItems is not empty\n if (Object.keys(mergedItems).length === 0) {\n logger.warn(\n `Translated JSON for locale: ${target.targetLocale} does not have a valid sourceObjectPointer: ${sourceObjectPointer}. Skipping this target`\n );\n continue;\n }\n\n // 5. Override the source item with the translated values\n for (const [\n translatedKeyJsonPointer,\n translatedValue,\n ] of Object.entries(mergedItems || {})) {\n try {\n const value = getJSONPointerValue(\n mutateSourceItem,\n translatedKeyJsonPointer\n );\n if (!value) continue;\n setJSONPointerValue(\n mutateSourceItem,\n translatedKeyJsonPointer,\n translatedValue\n );\n } catch {\n /* empty */\n }\n }\n // 6. Apply additional mutations to the sourceItem\n applyTransformations(\n mutateSourceItem,\n sourceObjectOptions.transform,\n target.targetLocale,\n defaultLocale\n );\n\n // 7. Merge the source item with the original JSON\n sourceObjectRecord[mutateSourceItemKey] = mutateSourceItem;\n }\n setJSONPointerValue(mergedJson, sourceObjectPointer, sourceObjectValue);\n }\n }\n if (jsonSchema.structuralTransform && jsonSchema.composite) {\n unapplyStructuralTransforms(\n mergedJson,\n jsonSchema.structuralTransform,\n jsonSchema.composite\n );\n }\n\n return [JSON.stringify(mergedJson, null, 2)];\n}\n\nfunction sortByLocaleOrder(\n items: JSONValue[],\n sourceObjectOptions: SourceObjectOptions,\n localeOrder: string[],\n sourceObjectPointer: string,\n defaultLocale: string\n): JSONValue[] {\n const sortMode = sourceObjectOptions.experimentalSort;\n if (!sortMode || !sourceObjectOptions.key) {\n return items;\n }\n\n const itemsWithLocale = items.map((item) => {\n let localeValue: string | undefined;\n try {\n const values = getJSONPathValues(item, sourceObjectOptions.key as string);\n const value = values?.[0];\n if (typeof value === 'string') {\n localeValue = value;\n }\n } catch {\n /* empty */\n }\n return { item, localeValue };\n });\n\n if (sortMode === 'locales') {\n if (!localeOrder.length) {\n return items;\n }\n\n const orderedLocaleList = [\n defaultLocale,\n ...localeOrder.filter((locale) => locale !== defaultLocale),\n ];\n const localeOrderValues = orderedLocaleList.map((locale) =>\n getIdentifyingLocaleProperty(\n locale,\n sourceObjectPointer,\n sourceObjectOptions\n )\n );\n\n const orderedItems: JSONValue[] = [];\n const remainingItems = [...itemsWithLocale];\n\n for (const localeValue of localeOrderValues) {\n for (let i = 0; i < remainingItems.length; ) {\n const entry = remainingItems[i];\n if (entry.localeValue === localeValue) {\n orderedItems.push(entry.item);\n remainingItems.splice(i, 1);\n continue;\n }\n i += 1;\n }\n }\n\n remainingItems.forEach((entry) => orderedItems.push(entry.item));\n\n return orderedItems;\n }\n\n if (sortMode === 'localesAlphabetical') {\n const defaultLocaleValue = getIdentifyingLocaleProperty(\n defaultLocale,\n sourceObjectPointer,\n sourceObjectOptions\n );\n\n const defaultItems: typeof itemsWithLocale = [];\n const sortableItems: typeof itemsWithLocale = [];\n const remainingItems: typeof itemsWithLocale = [];\n\n for (const entry of itemsWithLocale) {\n if (entry.localeValue === defaultLocaleValue) {\n defaultItems.push(entry);\n continue;\n }\n if (entry.localeValue) {\n sortableItems.push(entry);\n continue;\n }\n remainingItems.push(entry);\n }\n\n sortableItems.sort((a, b) => {\n if (!a.localeValue || !b.localeValue) {\n return 0;\n }\n return a.localeValue.localeCompare(b.localeValue);\n });\n\n return [...defaultItems, ...sortableItems, ...remainingItems].map(\n (entry) => entry.item\n );\n }\n\n return items;\n}\n\n/**\n * Remove top-level properties from a generated non-default-locale entry\n * (e.g. Mintlify's `default: true` flag, which is only valid on one entry)\n */\nfunction omitProperties(\n item: JSONValue,\n properties: string[] | undefined\n): void {\n if (!properties?.length) return;\n if (!item || typeof item !== 'object' || Array.isArray(item)) return;\n for (const property of properties) {\n delete (item as JSONObject)[property];\n }\n}\n\n/**\n * Apply transformations to the sourceItem in-place\n * @param sourceItem - The source item to apply transformations to\n * @param transform - The transformations to apply\n * @param targetLocale - The target locale\n * @param defaultLocale - The default locale\n */\nexport function applyTransformations(\n sourceItem: JSONValue,\n transform: SourceObjectOptions['transform'],\n targetLocale: string,\n defaultLocale: string\n): void {\n if (!transform) return;\n\n const targetLocaleProperties = getConfiguredLocaleProperties(targetLocale);\n const defaultLocaleProperties = getConfiguredLocaleProperties(defaultLocale);\n\n for (const [transformPath, transformOptions] of Object.entries(transform)) {\n if (\n !transformOptions.replace ||\n typeof transformOptions.replace !== 'string'\n ) {\n continue;\n }\n const results = getJSONPathMatches(sourceItem, transformPath);\n if (!results || results.length === 0) {\n continue;\n }\n results.forEach((result) => {\n if (typeof result.value !== 'string') {\n return;\n }\n result.value = transformValue(\n result.value,\n transformOptions,\n targetLocaleProperties,\n defaultLocaleProperties\n );\n\n // Update the actual sourceItem using JSONPointer\n setJSONPointerValue(sourceItem, result.pointer, result.value);\n });\n }\n}\n\n/**\n * Apply one transform to a string value. Locale placeholders in `replace`\n * take the target locale's properties; those in `match` take the default\n * locale's. Without `match`, the value is replaced outright.\n */\nexport function transformValue(\n value: string,\n transformOptions: TransformOption,\n targetLocaleProperties: LocaleProperties,\n defaultLocaleProperties: LocaleProperties\n): string {\n const replaceString = replaceLocalePlaceholders(\n transformOptions.replace,\n targetLocaleProperties\n );\n if (!transformOptions.match || typeof transformOptions.match !== 'string') {\n return replaceString;\n }\n const matchString = replaceLocalePlaceholders(\n transformOptions.match,\n defaultLocaleProperties\n );\n return value.replace(new RegExp(matchString, 'g'), replaceString);\n}\n"],"mappings":";;;;;;;;;AAmCA,SAAgB,UACd,iBACA,WACA,SACA,SAIA,eACA,cAAwB,EAAE,EAChB;CACV,MAAM,aAAa,mBAAmB,SAAS,UAAU;AACzD,KAAI,CAAC,WACH,QAAO,QAAQ,KAAK,WAAW,OAAO,kBAAkB;CAG1D,IAAI;AACJ,KAAI;AACF,iBAAe,KAAK,MAAM,gBAAgB;SACpC;AACN,SAAO,MAAM,sBAAsB,YAAY;AAC/C,SAAO,SAAS,EAAE;;CAGpB,MAAM,yBACJ,SAAS,mCAAmC;CAC9C,MAAM,yBAAyB,yBAC3B,IAAI,uBAAuB,cAAc,GACzC;CACJ,MAAM,uBAAuB,yBACzB,YAAY,KAAK,WAAW,IAAI,uBAAuB,OAAO,CAAC,GAC/D;AAEJ,KAAI,WAAW,uBAAuB,WAAW,UAC/C,2BACE,cACA,WAAW,qBACX,WAA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AAW;AAC1B,OAAI,OAAO,OAAO,UAAU,SAC1B;AAEF,UAAO,QAAQ,eACb,OAAO,OACP,kBACA,wBACA,wBACD;AAGD,uBAAoB,YAAY,OAAO,SAAS,OAAO,MAAM;IAC7D;;;;;;;;AASN,SAAgB,eACd,OACA,kBACA,wBACA,yBACQ;CACR,MAAM,gBAAgB,0BACpB,iBAAiB,SACjB,uBACD;AACD,KAAI,CAAC,iBAAiB,SAAS,OAAO,iBAAiB,UAAU,SAC/D,QAAO;CAET,MAAM,cAAc,0BAClB,iBAAiB,OACjB,wBACD;AACD,QAAO,MAAM,QAAQ,IAAI,OAAO,aAAa,IAAI,EAAE,cAAc"}
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.22.0";
1
+ export declare const PACKAGE_VERSION = "2.22.1";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.22.0";
2
+ const PACKAGE_VERSION = "2.22.1";
3
3
  //#endregion
4
4
  export { PACKAGE_VERSION };
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.22.0';\n"],"mappings":";AACA,MAAa,kBAAkB"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.22.1';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -1,4 +1,5 @@
1
1
  import type { StaticLocalizationSettings } from '../types/index.js';
2
+ export declare const PAGE_EXTENSIONS: string[];
2
3
  export type StaticUrlSettings = StaticLocalizationSettings;
3
4
  /**
4
5
  * Localizes static urls in content files.
@@ -381,6 +381,6 @@ function checkIfPathMatchesPattern(originalUrlArray, patternHeadArray) {
381
381
  return true;
382
382
  }
383
383
  //#endregion
384
- export { localizeStaticUrls as default, transformUrlPath };
384
+ export { PAGE_EXTENSIONS, localizeStaticUrls as default, transformUrlPath };
385
385
 
386
386
  //# sourceMappingURL=localizeStaticUrls.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"localizeStaticUrls.js","names":["path","fs","parseBabel"],"sources":["../../src/utils/localizeStaticUrls.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { StaticLocalizationSettings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport micromatch from 'micromatch';\nimport { unified } from 'unified';\nimport remarkMdx from 'remark-mdx';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkStringify from 'remark-stringify';\nimport { visit } from 'unist-util-visit';\nimport type { Root, Link, Literal } from 'mdast';\nimport type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parse as parseBabel } from '@babel/parser';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\n\nconst { isMatch } = micromatch;\n\n/**\n * URL-bearing JSX attributes that we localize. Intentionally limited to link\n * attributes (`href`) — NOT asset attributes like `src`, which usually point at\n * shared, locale-agnostic assets (e.g. `/docs/images/...`) that would 404 if a\n * locale prefix were added. Extend deliberately.\n */\nconst LOCALIZABLE_URL_ATTRIBUTES = new Set(['href']);\n\n// Docs routing conventions: page file formats, and the file that serves a\n// folder URL (`/a/` -> `a/index.mdx`).\nconst PAGE_EXTENSIONS = ['.mdx', '.md'];\nconst INDEX_PAGE = 'index';\n\n/**\n * The page file a root-relative docs URL points to, relative to the working\n * directory like file mapping keys: `/a/b#x` -> `a/b.mdx`, `a/b.md`, or\n * `a/b/index.mdx`.\n */\nfunction findPage(url: string): string | undefined {\n const base = url.split(/[?#]/)[0].replace(/^\\/+|\\/+$/g, '');\n return PAGE_EXTENSIONS.flatMap((ext) => [\n `${base}${ext}`,\n path.join(base, `${INDEX_PAGE}${ext}`),\n ]).find((page) => fs.existsSync(page));\n}\n\n/**\n * Whether a URL points to a source page with no translation on disk, either at\n * its mapped output path or at the localized URL. URLs with no source page,\n * such as pages generated from an OpenAPI spec, are not missing a translation.\n */\nfunction translationMissing(\n url: string,\n localizedUrl: string,\n localizedFiles: Record<string, string>\n): boolean {\n const sourcePage = findPage(url);\n if (!sourcePage) return false;\n const mappedPage = localizedFiles[sourcePage];\n return !(mappedPage && fs.existsSync(mappedPage)) && !findPage(localizedUrl);\n}\n\n/**\n * Localize URL string literals that live inside an MDX expression's raw source.\n *\n * URLs can be nested arbitrarily deep inside `{...}` expressions — e.g. an\n * `<a href>` buried inside a component prop:\n * <ParamField type={<span><a href=\"/docs/x\">Error</a></span>} />\n * Such hrefs never appear as mdast nodes (they live in the expression's embedded\n * JS), so the mdast visitors can't reach them. We re-parse the expression source\n * with Babel — positions are local to `source`, which avoids any document-offset\n * mapping — find JSX url-attribute string literals at any depth, and surgically\n * rewrite them in place.\n *\n * `rootStringIsUrl` covers `href={\"/docs/x\"}`, where the expression itself is a\n * bare string literal that a url-named attribute should treat as a URL.\n *\n * Only static string literals are localized; dynamically-computed URLs\n * (template literals, identifiers, concatenation) are left untouched — a\n * fundamental limit of static localization, not a parser shortcoming.\n */\nfunction localizeUrlsInExpressionSource(\n source: string,\n transformUrl: (url: string, linkType: 'markdown' | 'href') => string | null,\n rootStringIsUrl: boolean = false\n): string {\n if (!source.trim()) return source;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ast: any;\n try {\n ast = parseBabel(source, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['jsx', 'typescript'],\n });\n } catch {\n // Dynamic / unparseable expression — leave it untouched.\n return source;\n }\n\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const pushLiteralReplacement = (literal: any) => {\n if (\n !literal ||\n // A bare string at statement position is parsed by Babel as a\n // DirectiveLiteral (cf. \"use strict\") rather than a StringLiteral.\n (literal.type !== 'StringLiteral' &&\n literal.type !== 'DirectiveLiteral') ||\n typeof literal.value !== 'string' ||\n typeof literal.start !== 'number' ||\n typeof literal.end !== 'number'\n ) {\n return;\n }\n const newUrl = transformUrl(literal.value, 'href');\n if (!newUrl) return;\n // Preserve the original quote style; URLs never contain quote chars.\n const quote = source[literal.start] === \"'\" ? \"'\" : '\"';\n replacements.push({\n start: literal.start,\n end: literal.end,\n text: `${quote}${newUrl}${quote}`,\n });\n };\n\n // `href={\"/docs/x\"}`: the entire expression is the URL string.\n if (rootStringIsUrl) {\n const program = ast.program;\n const body = (program?.body ?? []) as Array<{\n type: string;\n expression?: unknown;\n }>;\n if (body.length === 1 && body[0]?.type === 'ExpressionStatement') {\n pushLiteralReplacement(body[0].expression);\n } else if (body.length === 0 && program?.directives?.length === 1) {\n // Babel parses a lone string literal as a directive, not a statement.\n pushLiteralReplacement(program.directives[0]?.value);\n }\n }\n\n // Walk the AST for JSX url-attributes anywhere in the expression.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const seen = new Set<any>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const walk = (node: any) => {\n if (!node || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (seen.has(node)) return;\n seen.add(node);\n\n if (\n node.type === 'JSXAttribute' &&\n node.name?.type === 'JSXIdentifier' &&\n LOCALIZABLE_URL_ATTRIBUTES.has(node.name.name) &&\n node.value\n ) {\n if (node.value.type === 'StringLiteral') {\n pushLiteralReplacement(node.value);\n } else if (\n node.value.type === 'JSXExpressionContainer' &&\n node.value.expression?.type === 'StringLiteral'\n ) {\n pushLiteralReplacement(node.value.expression);\n }\n }\n\n for (const key in node) {\n if (\n key === 'loc' ||\n key === 'start' ||\n key === 'end' ||\n key === 'range'\n ) {\n continue;\n }\n const child = node[key];\n if (child && typeof child === 'object') walk(child);\n }\n };\n walk(ast.program ?? ast);\n\n if (replacements.length === 0) return source;\n\n // Apply end-to-start so earlier offsets remain valid.\n let result = source;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, text }) => {\n result = result.slice(0, start) + text + result.slice(end);\n });\n return result;\n}\n\nexport type StaticUrlSettings = StaticLocalizationSettings;\n\n/**\n * Localizes static urls in content files.\n * Currently only supported for md and mdx files. (/docs/ -> /[locale]/docs/)\n * @param settings - The settings object containing the project configuration.\n * @returns void\n *\n * @TODO This is an experimental feature, and only works in very specific cases. This needs to be improved before\n * it can be enabled by default.\n *\n * Before this becomes a non-experimental feature, we need to:\n * - Support more file types\n * - Support more complex paths\n */\nexport default async function localizeStaticUrls(\n settings: StaticUrlSettings,\n targetLocales?: string[],\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n const localizeOptions = settings.options?.experimentalLocalizeStaticUrls;\n const skipUntranslatedPages =\n typeof localizeOptions === 'object' &&\n localizeOptions.skipUntranslatedPages === true;\n\n // Use filtered locales if provided, otherwise use all locales\n const locales = targetLocales || settings.locales;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales, // Always use all locales for mapping, filter later\n settings.defaultLocale\n );\n\n // Process all file types at once with a single call\n const processPromises = [];\n\n // First, process default locale files (from source files)\n // This is needed because they might not be in the fileMapping if they're not being translated\n // Only process default locale if it's in the target locales filter\n if (\n !fileMapping[settings.defaultLocale] &&\n locales.includes(settings.defaultLocale) &&\n !includeFiles // when filtering, skip default-locale pass\n ) {\n const defaultLocaleFiles: string[] = [];\n\n // Collect all .md and .mdx files from sourceFiles\n if (sourceFiles.md) {\n defaultLocaleFiles.push(...sourceFiles.md);\n }\n if (sourceFiles.mdx) {\n defaultLocaleFiles.push(...sourceFiles.mdx);\n }\n\n if (defaultLocaleFiles.length > 0) {\n const defaultPromise = Promise.all(\n defaultLocaleFiles.map(async (filePath: string) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file using default locale\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n settings.defaultLocale, // Process as default locale\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n processPromises.push(defaultPromise);\n }\n }\n\n // Then process all other locales from fileMapping\n const mappingPromises = Object.entries(fileMapping)\n .filter(([locale]) => locales.includes(locale)) // Filter by target locales\n .map(async ([locale, filesMap]) => {\n // Get all files that are md or mdx\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n // Replace the placeholder path with the target path\n await Promise.all(\n targetFiles.map(async (filePath) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file (handles both URLs and hrefs in single AST pass)\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n locale,\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n skipUntranslatedPages ? filesMap : undefined\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n });\n processPromises.push(...mappingPromises);\n\n await Promise.all(processPromises);\n}\n\ninterface UrlTransformResult {\n content: string;\n hasChanges: boolean;\n transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }>;\n}\n\n/**\n * Determines if a URL should be processed based on pattern matching\n */\nfunction shouldProcessUrl(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n baseDomain?: string\n): boolean {\n // Check fragment-only URLs like \"#id-name\"\n if (/^\\s*#/.test(originalUrl)) {\n return false;\n }\n\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n\n // Handle absolute URLs with baseDomain\n let urlToCheck = originalUrl;\n if (baseDomain && originalUrl.startsWith(baseDomain)) {\n urlToCheck = originalUrl.substring(baseDomain.length);\n }\n\n if (targetLocale === defaultLocale) {\n // For default locale processing, check if URL contains the pattern\n return urlToCheck.includes(patternWithoutSlash);\n } else {\n // For non-default locales, check if URL starts with pattern\n return urlToCheck.startsWith(patternWithoutSlash);\n }\n}\n\n/**\n * Determines if a URL should be processed based on the base domain\n */\nfunction shouldProcessAbsoluteUrl(\n originalUrl: string,\n baseDomain: string\n): boolean {\n return originalUrl.startsWith(baseDomain);\n}\n\n/**\n * Checks if a URL should be excluded based on exclusion patterns\n */\nfunction isUrlExcluded(\n originalUrl: string,\n exclude: string[],\n defaultLocale: string\n): boolean {\n const excludePatterns = exclude.map((p) =>\n p.replace(/\\[locale\\]/g, defaultLocale)\n );\n return excludePatterns.some((pattern) => isMatch(originalUrl, pattern));\n}\n\n/**\n * Main URL transformation function that delegates to specific scenarios\n */\nexport function transformUrlPath(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean\n): string | null {\n const originalPathArray = originalUrl\n .split('/')\n .filter((path) => path !== '');\n const patternHeadArray = patternHead.split('/').filter((path) => path !== '');\n\n // check if the pattern head matches the original path\n if (!checkIfPathMatchesPattern(originalPathArray, patternHeadArray)) {\n return null;\n }\n\n if (patternHeadArray.length > originalPathArray.length) {\n return null; // Pattern is longer than the URL path\n }\n\n let result = null;\n if (targetLocale === defaultLocale) {\n if (hideDefaultLocale) {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // remove default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n ...originalPathArray.slice(patternHeadArray.length + 1),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] === defaultLocale) {\n return null;\n }\n\n // insert default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n defaultLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n }\n } else if (hideDefaultLocale) {\n // Avoid duplicating target locale if already present\n if (originalPathArray?.[patternHeadArray.length] === targetLocale) {\n return null;\n }\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n targetLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check default locale\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // replace default locale with target locale\n const newPathArray = [...originalPathArray];\n newPathArray[patternHeadArray.length] = targetLocale;\n\n result = newPathArray.join('/');\n }\n\n // check for leading and trailing slashes\n if (originalUrl.startsWith('/')) {\n result = '/' + result;\n }\n if (originalUrl.endsWith('/')) {\n result = result + '/';\n }\n\n return result;\n}\n\n/**\n * AST-based transformation for MDX files using remark-mdx\n */\nfunction transformMdxUrls(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n baseDomain?: string,\n localizedFiles?: Record<string, string>\n): UrlTransformResult {\n const transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }> = [];\n\n if (!pattern.startsWith('/')) {\n pattern = '/' + pattern;\n }\n\n const patternHead = pattern.split('[locale]')[0];\n\n // Quick check: if the file doesn't contain the pattern, skip expensive AST parsing\n // For default locale processing, we also need to check if content might need adjustment\n if (targetLocale === defaultLocale) {\n // For default locale files, we always need to check as we're looking for either:\n // - paths without locale (when hideDefaultLocale=false)\n // - paths with default locale (when hideDefaultLocale=true)\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n if (!mdxContent.includes(patternWithoutSlash)) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n } else {\n // For non-default locales, use the original logic\n if (!mdxContent.includes(patternHead.replace(/\\/$/, ''))) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n }\n\n // Parse the MDX content into an AST\n let processedAst: Root;\n let neutralizedAnchors: boolean;\n try {\n const parsed = parseMdxForRoundTrip(mdxContent);\n processedAst = parsed.ast;\n neutralizedAnchors = parsed.neutralized;\n } catch {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls,\n };\n }\n\n // Helper function to transform URL based on pattern\n const transformUrl = (\n originalUrl: string,\n linkType: 'markdown' | 'href'\n ): string | null => {\n // For Markdown links [text](path), only process absolute-root paths starting with '/'\n // Relative markdown links should remain relative to the current page and not be localized.\n if (linkType === 'markdown') {\n const isFragment = /^\\s*#/.test(originalUrl);\n const isAbsoluteRoot = originalUrl.startsWith('/');\n const looksAbsoluteWithDomain = baseDomain\n ? shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n : false;\n if (!isAbsoluteRoot && !looksAbsoluteWithDomain && !isFragment) {\n return null;\n }\n }\n // Check if URL should be processed\n if (\n !shouldProcessUrl(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n baseDomain\n )\n ) {\n return null;\n }\n\n // Skip absolute URLs (http://, https://, //, etc.)\n if (baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)) {\n // Get everything after the base domain\n const afterDomain = originalUrl.substring(baseDomain.length);\n\n const transformedPath = transformUrlPath(\n afterDomain,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n if (!transformedPath) {\n return null;\n }\n if (\n localizedFiles &&\n translationMissing(afterDomain, transformedPath, localizedFiles)\n ) {\n return null;\n }\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: transformedPath,\n type: linkType,\n });\n return transformedPath ? baseDomain + transformedPath : null;\n }\n\n // Exclude colon-prefixed URLs (http://, https://, //, etc.)\n if (originalUrl.split('?')[0].includes(':')) {\n return null;\n }\n\n // Transform the URL based on locale and configuration\n const newUrl = transformUrlPath(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n\n if (!newUrl) {\n return null;\n }\n\n // Check exclusions\n if (isUrlExcluded(originalUrl, exclude, defaultLocale)) {\n return null;\n }\n\n // Links to pages with no translation keep the default locale.\n if (\n localizedFiles &&\n translationMissing(originalUrl, newUrl, localizedFiles)\n ) {\n return null;\n }\n\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: newUrl,\n type: linkType,\n });\n return newUrl;\n };\n\n // Visit markdown link nodes: [text](url)\n visit(processedAst, 'link', (node: Link) => {\n if (node.url) {\n const newUrl = transformUrl(node.url, 'markdown');\n if (newUrl) {\n node.url = newUrl;\n }\n }\n });\n\n // Visit JSX/HTML elements for href attributes: <a href=\"url\"> or <Card href=\"url\">\n visit(processedAst, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node) => {\n const jsxNode = node as MdxJsxFlowElement | MdxJsxTextElement;\n if (!jsxNode.attributes) return;\n for (const attr of jsxNode.attributes) {\n if (attr.type !== 'mdxJsxAttribute' || !attr.value) continue;\n\n // Plain string attribute value, e.g. <a href=\"/docs/x\">\n if (typeof attr.value === 'string') {\n if (LOCALIZABLE_URL_ATTRIBUTES.has(attr.name)) {\n const newUrl = transformUrl(attr.value, 'href');\n if (newUrl) {\n attr.value = newUrl;\n }\n }\n continue;\n }\n\n // Expression attribute value. Two shapes are handled:\n // href={\"/docs/x\"} (url attr, bare string)\n // type={<span><a href=\"/docs/x\">…</a></span>} (url attr nested deep\n // inside a non-url prop)\n // The nested case never surfaces as an mdast node — it lives in the\n // expression's embedded JS — so it's localized via the source-level walk.\n if (\n typeof attr.value === 'object' &&\n attr.value.type === 'mdxJsxAttributeValueExpression' &&\n typeof attr.value.value === 'string'\n ) {\n const newValue = localizeUrlsInExpressionSource(\n attr.value.value,\n transformUrl,\n LOCALIZABLE_URL_ATTRIBUTES.has(attr.name)\n );\n if (newValue !== attr.value.value) {\n attr.value.value = newValue;\n }\n }\n }\n });\n\n // Visit standalone MDX expressions for URLs inside embedded JSX, e.g.\n // {isBeta && <a href=\"/docs/x\">Beta</a>}\n visit(processedAst, ['mdxFlowExpression', 'mdxTextExpression'], (node) => {\n const exprNode = node as unknown as Literal;\n if (typeof exprNode.value === 'string' && exprNode.value) {\n const newValue = localizeUrlsInExpressionSource(\n exprNode.value,\n transformUrl\n );\n if (newValue !== exprNode.value) {\n exprNode.value = newValue;\n }\n }\n });\n\n // Visit raw JSX nodes for href attributes in JSX strings\n visit(processedAst, 'jsx', (node: Literal) => {\n if (node.value && typeof node.value === 'string') {\n const jsxContent = node.value;\n\n // Use regex to find href attributes in the JSX string\n const hrefRegex = /href\\s*=\\s*[\"']([^\"']+)[\"']/g;\n let match;\n const replacements: Array<{\n start: number;\n end: number;\n oldHrefAttr: string;\n newHrefAttr: string;\n }> = [];\n\n // Reset regex lastIndex to avoid issues with global flag\n hrefRegex.lastIndex = 0;\n\n while ((match = hrefRegex.exec(jsxContent)) !== null) {\n const originalHref = match[1];\n const newUrl = transformUrl(originalHref, 'href');\n\n if (newUrl) {\n // Store replacement info\n const oldHrefAttr = match[0]; // The full match like 'href=\"/quickstart\"'\n const quote = oldHrefAttr.includes('\"') ? '\"' : \"'\";\n const newHrefAttr = `href=${quote}${newUrl}${quote}`;\n\n replacements.push({\n start: match.index!,\n end: match.index! + oldHrefAttr.length,\n oldHrefAttr,\n newHrefAttr,\n });\n }\n }\n\n // Apply replacements in reverse order (from end to start) to avoid position shifts\n if (replacements.length > 0) {\n let newJsxContent = jsxContent;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, newHrefAttr }) => {\n newJsxContent =\n newJsxContent.slice(0, start) +\n newHrefAttr +\n newJsxContent.slice(end);\n });\n\n node.value = newJsxContent;\n }\n }\n });\n\n // Convert the modified AST back to MDX string\n let content: string;\n try {\n const stringifyProcessor = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n // Handler to prevent escaping (avoids '&lt;' -> '\\&lt;')\n text(node: Literal) {\n return node.value;\n },\n },\n });\n\n const outTree = stringifyProcessor.runSync(processedAst) as Root;\n content = stringifyProcessor.stringify(outTree);\n if (neutralizedAnchors) {\n content = restoreAnchorIds(content);\n }\n } catch (error) {\n console.warn(\n `Failed to stringify MDX content: ${error instanceof Error ? error.message : String(error)}`\n );\n console.warn(\n 'Returning original content unchanged due to stringify error.'\n );\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n\n // Handle newline formatting to match original input\n if (content.endsWith('\\n') && !mdxContent.endsWith('\\n')) {\n content = content.slice(0, -1);\n }\n\n // Preserve leading newlines from original content\n if (mdxContent.startsWith('\\n') && !content.startsWith('\\n')) {\n content = '\\n' + content;\n }\n\n return {\n content,\n hasChanges: transformedUrls.length > 0,\n transformedUrls,\n };\n}\n\n// AST-based transformation for MDX files using remark\nfunction localizeStaticUrlsForFile(\n file: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]', // eg /docs/[locale] or /[locale]\n exclude: string[] = [],\n baseDomain?: string,\n localizedFiles?: Record<string, string>\n): UrlTransformResult {\n // Use AST-based transformation for MDX files\n return transformMdxUrls(\n file,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n baseDomain || '',\n localizedFiles\n );\n}\n\nfunction checkIfPathMatchesPattern(\n originalUrlArray: string[],\n patternHeadArray: string[]\n): boolean {\n // check if the pattern head matches the original path\n for (let i = 0; i < patternHeadArray.length; i++) {\n if (patternHeadArray[i] !== originalUrlArray?.[i]) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;A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,CACtD,WAAU,QAAQ,MAAM,GAAG,GAAG;AAIhC,KAAI,WAAW,WAAW,KAAK,IAAI,CAAC,QAAQ,WAAW,KAAK,CAC1D,WAAU,OAAO;AAGnB,QAAO;EACL;EACA,YAAY,gBAAgB,SAAS;EACrC;EACD;;AAIH,SAAS,0BACP,MACA,eACA,cACA,mBACA,UAAkB,aAClB,UAAoB,EAAE,EACtB,YACA,gBACoB;AAEpB,QAAO,iBACL,MACA,eACA,cACA,mBACA,SACA,SACA,cAAc,IACd,eACD;;AAGH,SAAS,0BACP,kBACA,kBACS;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,IAC3C,KAAI,iBAAiB,OAAO,mBAAmB,GAC7C,QAAO;AAIX,QAAO"}
1
+ {"version":3,"file":"localizeStaticUrls.js","names":["path","fs","parseBabel"],"sources":["../../src/utils/localizeStaticUrls.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { StaticLocalizationSettings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport micromatch from 'micromatch';\nimport { unified } from 'unified';\nimport remarkMdx from 'remark-mdx';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkStringify from 'remark-stringify';\nimport { visit } from 'unist-util-visit';\nimport type { Root, Link, Literal } from 'mdast';\nimport type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parse as parseBabel } from '@babel/parser';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\n\nconst { isMatch } = micromatch;\n\n/**\n * URL-bearing JSX attributes that we localize. Intentionally limited to link\n * attributes (`href`) — NOT asset attributes like `src`, which usually point at\n * shared, locale-agnostic assets (e.g. `/docs/images/...`) that would 404 if a\n * locale prefix were added. Extend deliberately.\n */\nconst LOCALIZABLE_URL_ATTRIBUTES = new Set(['href']);\n\n// Docs routing conventions: page file formats, and the file that serves a\n// folder URL (`/a/` -> `a/index.mdx`).\nexport const PAGE_EXTENSIONS = ['.mdx', '.md'];\nconst INDEX_PAGE = 'index';\n\n/**\n * The page file a root-relative docs URL points to, relative to the working\n * directory like file mapping keys: `/a/b#x` -> `a/b.mdx`, `a/b.md`, or\n * `a/b/index.mdx`.\n */\nfunction findPage(url: string): string | undefined {\n const base = url.split(/[?#]/)[0].replace(/^\\/+|\\/+$/g, '');\n return PAGE_EXTENSIONS.flatMap((ext) => [\n `${base}${ext}`,\n path.join(base, `${INDEX_PAGE}${ext}`),\n ]).find((page) => fs.existsSync(page));\n}\n\n/**\n * Whether a URL points to a source page with no translation on disk, either at\n * its mapped output path or at the localized URL. URLs with no source page,\n * such as pages generated from an OpenAPI spec, are not missing a translation.\n */\nfunction translationMissing(\n url: string,\n localizedUrl: string,\n localizedFiles: Record<string, string>\n): boolean {\n const sourcePage = findPage(url);\n if (!sourcePage) return false;\n const mappedPage = localizedFiles[sourcePage];\n return !(mappedPage && fs.existsSync(mappedPage)) && !findPage(localizedUrl);\n}\n\n/**\n * Localize URL string literals that live inside an MDX expression's raw source.\n *\n * URLs can be nested arbitrarily deep inside `{...}` expressions — e.g. an\n * `<a href>` buried inside a component prop:\n * <ParamField type={<span><a href=\"/docs/x\">Error</a></span>} />\n * Such hrefs never appear as mdast nodes (they live in the expression's embedded\n * JS), so the mdast visitors can't reach them. We re-parse the expression source\n * with Babel — positions are local to `source`, which avoids any document-offset\n * mapping — find JSX url-attribute string literals at any depth, and surgically\n * rewrite them in place.\n *\n * `rootStringIsUrl` covers `href={\"/docs/x\"}`, where the expression itself is a\n * bare string literal that a url-named attribute should treat as a URL.\n *\n * Only static string literals are localized; dynamically-computed URLs\n * (template literals, identifiers, concatenation) are left untouched — a\n * fundamental limit of static localization, not a parser shortcoming.\n */\nfunction localizeUrlsInExpressionSource(\n source: string,\n transformUrl: (url: string, linkType: 'markdown' | 'href') => string | null,\n rootStringIsUrl: boolean = false\n): string {\n if (!source.trim()) return source;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ast: any;\n try {\n ast = parseBabel(source, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['jsx', 'typescript'],\n });\n } catch {\n // Dynamic / unparseable expression — leave it untouched.\n return source;\n }\n\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const pushLiteralReplacement = (literal: any) => {\n if (\n !literal ||\n // A bare string at statement position is parsed by Babel as a\n // DirectiveLiteral (cf. \"use strict\") rather than a StringLiteral.\n (literal.type !== 'StringLiteral' &&\n literal.type !== 'DirectiveLiteral') ||\n typeof literal.value !== 'string' ||\n typeof literal.start !== 'number' ||\n typeof literal.end !== 'number'\n ) {\n return;\n }\n const newUrl = transformUrl(literal.value, 'href');\n if (!newUrl) return;\n // Preserve the original quote style; URLs never contain quote chars.\n const quote = source[literal.start] === \"'\" ? \"'\" : '\"';\n replacements.push({\n start: literal.start,\n end: literal.end,\n text: `${quote}${newUrl}${quote}`,\n });\n };\n\n // `href={\"/docs/x\"}`: the entire expression is the URL string.\n if (rootStringIsUrl) {\n const program = ast.program;\n const body = (program?.body ?? []) as Array<{\n type: string;\n expression?: unknown;\n }>;\n if (body.length === 1 && body[0]?.type === 'ExpressionStatement') {\n pushLiteralReplacement(body[0].expression);\n } else if (body.length === 0 && program?.directives?.length === 1) {\n // Babel parses a lone string literal as a directive, not a statement.\n pushLiteralReplacement(program.directives[0]?.value);\n }\n }\n\n // Walk the AST for JSX url-attributes anywhere in the expression.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const seen = new Set<any>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const walk = (node: any) => {\n if (!node || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (seen.has(node)) return;\n seen.add(node);\n\n if (\n node.type === 'JSXAttribute' &&\n node.name?.type === 'JSXIdentifier' &&\n LOCALIZABLE_URL_ATTRIBUTES.has(node.name.name) &&\n node.value\n ) {\n if (node.value.type === 'StringLiteral') {\n pushLiteralReplacement(node.value);\n } else if (\n node.value.type === 'JSXExpressionContainer' &&\n node.value.expression?.type === 'StringLiteral'\n ) {\n pushLiteralReplacement(node.value.expression);\n }\n }\n\n for (const key in node) {\n if (\n key === 'loc' ||\n key === 'start' ||\n key === 'end' ||\n key === 'range'\n ) {\n continue;\n }\n const child = node[key];\n if (child && typeof child === 'object') walk(child);\n }\n };\n walk(ast.program ?? ast);\n\n if (replacements.length === 0) return source;\n\n // Apply end-to-start so earlier offsets remain valid.\n let result = source;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, text }) => {\n result = result.slice(0, start) + text + result.slice(end);\n });\n return result;\n}\n\nexport type StaticUrlSettings = StaticLocalizationSettings;\n\n/**\n * Localizes static urls in content files.\n * Currently only supported for md and mdx files. (/docs/ -> /[locale]/docs/)\n * @param settings - The settings object containing the project configuration.\n * @returns void\n *\n * @TODO This is an experimental feature, and only works in very specific cases. This needs to be improved before\n * it can be enabled by default.\n *\n * Before this becomes a non-experimental feature, we need to:\n * - Support more file types\n * - Support more complex paths\n */\nexport default async function localizeStaticUrls(\n settings: StaticUrlSettings,\n targetLocales?: string[],\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n const localizeOptions = settings.options?.experimentalLocalizeStaticUrls;\n const skipUntranslatedPages =\n typeof localizeOptions === 'object' &&\n localizeOptions.skipUntranslatedPages === true;\n\n // Use filtered locales if provided, otherwise use all locales\n const locales = targetLocales || settings.locales;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales, // Always use all locales for mapping, filter later\n settings.defaultLocale\n );\n\n // Process all file types at once with a single call\n const processPromises = [];\n\n // First, process default locale files (from source files)\n // This is needed because they might not be in the fileMapping if they're not being translated\n // Only process default locale if it's in the target locales filter\n if (\n !fileMapping[settings.defaultLocale] &&\n locales.includes(settings.defaultLocale) &&\n !includeFiles // when filtering, skip default-locale pass\n ) {\n const defaultLocaleFiles: string[] = [];\n\n // Collect all .md and .mdx files from sourceFiles\n if (sourceFiles.md) {\n defaultLocaleFiles.push(...sourceFiles.md);\n }\n if (sourceFiles.mdx) {\n defaultLocaleFiles.push(...sourceFiles.mdx);\n }\n\n if (defaultLocaleFiles.length > 0) {\n const defaultPromise = Promise.all(\n defaultLocaleFiles.map(async (filePath: string) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file using default locale\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n settings.defaultLocale, // Process as default locale\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n processPromises.push(defaultPromise);\n }\n }\n\n // Then process all other locales from fileMapping\n const mappingPromises = Object.entries(fileMapping)\n .filter(([locale]) => locales.includes(locale)) // Filter by target locales\n .map(async ([locale, filesMap]) => {\n // Get all files that are md or mdx\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n // Replace the placeholder path with the target path\n await Promise.all(\n targetFiles.map(async (filePath) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file (handles both URLs and hrefs in single AST pass)\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n locale,\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n skipUntranslatedPages ? filesMap : undefined\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n });\n processPromises.push(...mappingPromises);\n\n await Promise.all(processPromises);\n}\n\ninterface UrlTransformResult {\n content: string;\n hasChanges: boolean;\n transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }>;\n}\n\n/**\n * Determines if a URL should be processed based on pattern matching\n */\nfunction shouldProcessUrl(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n baseDomain?: string\n): boolean {\n // Check fragment-only URLs like \"#id-name\"\n if (/^\\s*#/.test(originalUrl)) {\n return false;\n }\n\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n\n // Handle absolute URLs with baseDomain\n let urlToCheck = originalUrl;\n if (baseDomain && originalUrl.startsWith(baseDomain)) {\n urlToCheck = originalUrl.substring(baseDomain.length);\n }\n\n if (targetLocale === defaultLocale) {\n // For default locale processing, check if URL contains the pattern\n return urlToCheck.includes(patternWithoutSlash);\n } else {\n // For non-default locales, check if URL starts with pattern\n return urlToCheck.startsWith(patternWithoutSlash);\n }\n}\n\n/**\n * Determines if a URL should be processed based on the base domain\n */\nfunction shouldProcessAbsoluteUrl(\n originalUrl: string,\n baseDomain: string\n): boolean {\n return originalUrl.startsWith(baseDomain);\n}\n\n/**\n * Checks if a URL should be excluded based on exclusion patterns\n */\nfunction isUrlExcluded(\n originalUrl: string,\n exclude: string[],\n defaultLocale: string\n): boolean {\n const excludePatterns = exclude.map((p) =>\n p.replace(/\\[locale\\]/g, defaultLocale)\n );\n return excludePatterns.some((pattern) => isMatch(originalUrl, pattern));\n}\n\n/**\n * Main URL transformation function that delegates to specific scenarios\n */\nexport function transformUrlPath(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean\n): string | null {\n const originalPathArray = originalUrl\n .split('/')\n .filter((path) => path !== '');\n const patternHeadArray = patternHead.split('/').filter((path) => path !== '');\n\n // check if the pattern head matches the original path\n if (!checkIfPathMatchesPattern(originalPathArray, patternHeadArray)) {\n return null;\n }\n\n if (patternHeadArray.length > originalPathArray.length) {\n return null; // Pattern is longer than the URL path\n }\n\n let result = null;\n if (targetLocale === defaultLocale) {\n if (hideDefaultLocale) {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // remove default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n ...originalPathArray.slice(patternHeadArray.length + 1),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] === defaultLocale) {\n return null;\n }\n\n // insert default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n defaultLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n }\n } else if (hideDefaultLocale) {\n // Avoid duplicating target locale if already present\n if (originalPathArray?.[patternHeadArray.length] === targetLocale) {\n return null;\n }\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n targetLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check default locale\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // replace default locale with target locale\n const newPathArray = [...originalPathArray];\n newPathArray[patternHeadArray.length] = targetLocale;\n\n result = newPathArray.join('/');\n }\n\n // check for leading and trailing slashes\n if (originalUrl.startsWith('/')) {\n result = '/' + result;\n }\n if (originalUrl.endsWith('/')) {\n result = result + '/';\n }\n\n return result;\n}\n\n/**\n * AST-based transformation for MDX files using remark-mdx\n */\nfunction transformMdxUrls(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n baseDomain?: string,\n localizedFiles?: Record<string, string>\n): UrlTransformResult {\n const transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }> = [];\n\n if (!pattern.startsWith('/')) {\n pattern = '/' + pattern;\n }\n\n const patternHead = pattern.split('[locale]')[0];\n\n // Quick check: if the file doesn't contain the pattern, skip expensive AST parsing\n // For default locale processing, we also need to check if content might need adjustment\n if (targetLocale === defaultLocale) {\n // For default locale files, we always need to check as we're looking for either:\n // - paths without locale (when hideDefaultLocale=false)\n // - paths with default locale (when hideDefaultLocale=true)\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n if (!mdxContent.includes(patternWithoutSlash)) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n } else {\n // For non-default locales, use the original logic\n if (!mdxContent.includes(patternHead.replace(/\\/$/, ''))) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n }\n\n // Parse the MDX content into an AST\n let processedAst: Root;\n let neutralizedAnchors: boolean;\n try {\n const parsed = parseMdxForRoundTrip(mdxContent);\n processedAst = parsed.ast;\n neutralizedAnchors = parsed.neutralized;\n } catch {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls,\n };\n }\n\n // Helper function to transform URL based on pattern\n const transformUrl = (\n originalUrl: string,\n linkType: 'markdown' | 'href'\n ): string | null => {\n // For Markdown links [text](path), only process absolute-root paths starting with '/'\n // Relative markdown links should remain relative to the current page and not be localized.\n if (linkType === 'markdown') {\n const isFragment = /^\\s*#/.test(originalUrl);\n const isAbsoluteRoot = originalUrl.startsWith('/');\n const looksAbsoluteWithDomain = baseDomain\n ? shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n : false;\n if (!isAbsoluteRoot && !looksAbsoluteWithDomain && !isFragment) {\n return null;\n }\n }\n // Check if URL should be processed\n if (\n !shouldProcessUrl(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n baseDomain\n )\n ) {\n return null;\n }\n\n // Skip absolute URLs (http://, https://, //, etc.)\n if (baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)) {\n // Get everything after the base domain\n const afterDomain = originalUrl.substring(baseDomain.length);\n\n const transformedPath = transformUrlPath(\n afterDomain,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n if (!transformedPath) {\n return null;\n }\n if (\n localizedFiles &&\n translationMissing(afterDomain, transformedPath, localizedFiles)\n ) {\n return null;\n }\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: transformedPath,\n type: linkType,\n });\n return transformedPath ? baseDomain + transformedPath : null;\n }\n\n // Exclude colon-prefixed URLs (http://, https://, //, etc.)\n if (originalUrl.split('?')[0].includes(':')) {\n return null;\n }\n\n // Transform the URL based on locale and configuration\n const newUrl = transformUrlPath(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n\n if (!newUrl) {\n return null;\n }\n\n // Check exclusions\n if (isUrlExcluded(originalUrl, exclude, defaultLocale)) {\n return null;\n }\n\n // Links to pages with no translation keep the default locale.\n if (\n localizedFiles &&\n translationMissing(originalUrl, newUrl, localizedFiles)\n ) {\n return null;\n }\n\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: newUrl,\n type: linkType,\n });\n return newUrl;\n };\n\n // Visit markdown link nodes: [text](url)\n visit(processedAst, 'link', (node: Link) => {\n if (node.url) {\n const newUrl = transformUrl(node.url, 'markdown');\n if (newUrl) {\n node.url = newUrl;\n }\n }\n });\n\n // Visit JSX/HTML elements for href attributes: <a href=\"url\"> or <Card href=\"url\">\n visit(processedAst, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node) => {\n const jsxNode = node as MdxJsxFlowElement | MdxJsxTextElement;\n if (!jsxNode.attributes) return;\n for (const attr of jsxNode.attributes) {\n if (attr.type !== 'mdxJsxAttribute' || !attr.value) continue;\n\n // Plain string attribute value, e.g. <a href=\"/docs/x\">\n if (typeof attr.value === 'string') {\n if (LOCALIZABLE_URL_ATTRIBUTES.has(attr.name)) {\n const newUrl = transformUrl(attr.value, 'href');\n if (newUrl) {\n attr.value = newUrl;\n }\n }\n continue;\n }\n\n // Expression attribute value. Two shapes are handled:\n // href={\"/docs/x\"} (url attr, bare string)\n // type={<span><a href=\"/docs/x\">…</a></span>} (url attr nested deep\n // inside a non-url prop)\n // The nested case never surfaces as an mdast node — it lives in the\n // expression's embedded JS — so it's localized via the source-level walk.\n if (\n typeof attr.value === 'object' &&\n attr.value.type === 'mdxJsxAttributeValueExpression' &&\n typeof attr.value.value === 'string'\n ) {\n const newValue = localizeUrlsInExpressionSource(\n attr.value.value,\n transformUrl,\n LOCALIZABLE_URL_ATTRIBUTES.has(attr.name)\n );\n if (newValue !== attr.value.value) {\n attr.value.value = newValue;\n }\n }\n }\n });\n\n // Visit standalone MDX expressions for URLs inside embedded JSX, e.g.\n // {isBeta && <a href=\"/docs/x\">Beta</a>}\n visit(processedAst, ['mdxFlowExpression', 'mdxTextExpression'], (node) => {\n const exprNode = node as unknown as Literal;\n if (typeof exprNode.value === 'string' && exprNode.value) {\n const newValue = localizeUrlsInExpressionSource(\n exprNode.value,\n transformUrl\n );\n if (newValue !== exprNode.value) {\n exprNode.value = newValue;\n }\n }\n });\n\n // Visit raw JSX nodes for href attributes in JSX strings\n visit(processedAst, 'jsx', (node: Literal) => {\n if (node.value && typeof node.value === 'string') {\n const jsxContent = node.value;\n\n // Use regex to find href attributes in the JSX string\n const hrefRegex = /href\\s*=\\s*[\"']([^\"']+)[\"']/g;\n let match;\n const replacements: Array<{\n start: number;\n end: number;\n oldHrefAttr: string;\n newHrefAttr: string;\n }> = [];\n\n // Reset regex lastIndex to avoid issues with global flag\n hrefRegex.lastIndex = 0;\n\n while ((match = hrefRegex.exec(jsxContent)) !== null) {\n const originalHref = match[1];\n const newUrl = transformUrl(originalHref, 'href');\n\n if (newUrl) {\n // Store replacement info\n const oldHrefAttr = match[0]; // The full match like 'href=\"/quickstart\"'\n const quote = oldHrefAttr.includes('\"') ? '\"' : \"'\";\n const newHrefAttr = `href=${quote}${newUrl}${quote}`;\n\n replacements.push({\n start: match.index!,\n end: match.index! + oldHrefAttr.length,\n oldHrefAttr,\n newHrefAttr,\n });\n }\n }\n\n // Apply replacements in reverse order (from end to start) to avoid position shifts\n if (replacements.length > 0) {\n let newJsxContent = jsxContent;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, newHrefAttr }) => {\n newJsxContent =\n newJsxContent.slice(0, start) +\n newHrefAttr +\n newJsxContent.slice(end);\n });\n\n node.value = newJsxContent;\n }\n }\n });\n\n // Convert the modified AST back to MDX string\n let content: string;\n try {\n const stringifyProcessor = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n // Handler to prevent escaping (avoids '&lt;' -> '\\&lt;')\n text(node: Literal) {\n return node.value;\n },\n },\n });\n\n const outTree = stringifyProcessor.runSync(processedAst) as Root;\n content = stringifyProcessor.stringify(outTree);\n if (neutralizedAnchors) {\n content = restoreAnchorIds(content);\n }\n } catch (error) {\n console.warn(\n `Failed to stringify MDX content: ${error instanceof Error ? error.message : String(error)}`\n );\n console.warn(\n 'Returning original content unchanged due to stringify error.'\n );\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n\n // Handle newline formatting to match original input\n if (content.endsWith('\\n') && !mdxContent.endsWith('\\n')) {\n content = content.slice(0, -1);\n }\n\n // Preserve leading newlines from original content\n if (mdxContent.startsWith('\\n') && !content.startsWith('\\n')) {\n content = '\\n' + content;\n }\n\n return {\n content,\n hasChanges: transformedUrls.length > 0,\n transformedUrls,\n };\n}\n\n// AST-based transformation for MDX files using remark\nfunction localizeStaticUrlsForFile(\n file: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]', // eg /docs/[locale] or /[locale]\n exclude: string[] = [],\n baseDomain?: string,\n localizedFiles?: Record<string, string>\n): UrlTransformResult {\n // Use AST-based transformation for MDX files\n return transformMdxUrls(\n file,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n baseDomain || '',\n localizedFiles\n );\n}\n\nfunction checkIfPathMatchesPattern(\n originalUrlArray: string[],\n patternHeadArray: string[]\n): boolean {\n // check if the pattern head matches the original path\n for (let i = 0; i < patternHeadArray.length; i++) {\n if (patternHeadArray[i] !== originalUrlArray?.[i]) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,EAAE,YAAY;;;;;;;AAQpB,MAAM,6BAA6B,IAAI,IAAI,CAAC,OAAO,CAAC;AAIpD,MAAa,kBAAkB,CAAC,QAAQ,MAAM;AAC9C,MAAM,aAAa;;;;;;AAOnB,SAAS,SAAS,KAAiC;CACjD,MAAM,OAAO,IAAI,MAAM,OAAO,CAAC,GAAG,QAAQ,cAAc,GAAG;AAC3D,QAAO,gBAAgB,SAAS,QAAQ,CACtC,GAAG,OAAO,OACVA,OAAK,KAAK,MAAM,GAAG,aAAa,MAAM,CACvC,CAAC,CAAC,MAAM,SAASC,KAAG,WAAW,KAAK,CAAC;;;;;;;AAQxC,SAAS,mBACP,KACA,cACA,gBACS;CACT,MAAM,aAAa,SAAS,IAAI;AAChC,KAAI,CAAC,WAAY,QAAO;CACxB,MAAM,aAAa,eAAe;AAClC,QAAO,EAAE,cAAcA,KAAG,WAAW,WAAW,KAAK,CAAC,SAAS,aAAa;;;;;;;;;;;;;;;;;;;;;AAsB9E,SAAS,+BACP,QACA,cACA,kBAA2B,OACnB;AACR,KAAI,CAAC,OAAO,MAAM,CAAE,QAAO;CAG3B,IAAI;AACJ,KAAI;AACF,QAAMC,MAAW,QAAQ;GACvB,YAAY;GACZ,eAAe;GACf,SAAS,CAAC,OAAO,aAAa;GAC/B,CAAC;SACI;AAEN,SAAO;;CAGT,MAAM,eAAoE,EAAE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;AAClB,UAAO,KAAK;KAEf,EACF,CAAC;EAEJ,MAAM,UAAU,mBAAmB,QAAQ,aAAa;AACxD,YAAU,mBAAmB,UAAU,QAAQ;AAC/C,MAAI,mBACF,WAAU,iBAAiB,QAAQ;UAE9B,OAAO;AACd,UAAQ,KACN,oCAAoC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GAC3F;AACD,UAAQ,KACN,+DACD;AACD,SAAO;GACL,SAAS;GACT,YAAY;GACZ,iBAAiB,EAAE;GACpB;;AAIH,KAAI,QAAQ,SAAS,KAAK,IAAI,CAAC,WAAW,SAAS,KAAK,CACtD,WAAU,QAAQ,MAAM,GAAG,GAAG;AAIhC,KAAI,WAAW,WAAW,KAAK,IAAI,CAAC,QAAQ,WAAW,KAAK,CAC1D,WAAU,OAAO;AAGnB,QAAO;EACL;EACA,YAAY,gBAAgB,SAAS;EACrC;EACD;;AAIH,SAAS,0BACP,MACA,eACA,cACA,mBACA,UAAkB,aAClB,UAAoB,EAAE,EACtB,YACA,gBACoB;AAEpB,QAAO,iBACL,MACA,eACA,cACA,mBACA,SACA,SACA,cAAc,IACd,eACD;;AAGH,SAAS,0BACP,kBACA,kBACS;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,IAC3C,KAAI,iBAAiB,OAAO,mBAAmB,GAC7C,QAAO;AAIX,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gt",
3
- "version": "2.22.0",
3
+ "version": "2.22.1",
4
4
  "main": "dist/index.js",
5
5
  "bin": "bin/main.js",
6
6
  "files": [