gt 2.26.8 → 2.26.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # gtx-cli
2
2
 
3
+ ## 2.26.9
4
+
5
+ ### Patch Changes
6
+
7
+ - [#2525](https://github.com/generaltranslation/gt/pull/2525) [`aee1350`](https://github.com/generaltranslation/gt/commit/aee135077ebef9d98378b68d5898df548d83f137) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Limit how many files postprocessing reads and writes at once so large docs projects no longer fail with `EMFILE: too many open files`
8
+
9
+ - Updated dependencies []:
10
+ - generaltranslation@9.5.8
11
+ - @generaltranslation/python-extractor@0.2.63
12
+ - @generaltranslation/supported-locales@2.1.44
13
+ - @generaltranslation/vue-extractor@0.1.22
14
+
3
15
  ## 2.26.8
4
16
 
5
17
  ### Patch Changes
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.26.8";
1
+ export declare const PACKAGE_VERSION = "2.26.9";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.26.8";
2
+ const PACKAGE_VERSION = "2.26.9";
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.26.8';\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.26.9';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -0,0 +1,10 @@
1
+ export declare const FILE_IO_CONCURRENCY = 512;
2
+ /**
3
+ * Keeps up to `batchSize` items in flight and returns results in input order.
4
+ * Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.
5
+ * @param items - The items to process
6
+ * @param processor - Processes one item
7
+ * @param batchSize - The maximum number of items in flight at once
8
+ * @returns The processor results, in input order
9
+ */
10
+ export declare function batchProcess<T, R>(items: T[], processor: (item: T, index: number) => Promise<R>, batchSize?: number): Promise<R[]>;
@@ -0,0 +1,29 @@
1
+ //#region src/utils/batchProcess.ts
2
+ const FILE_IO_CONCURRENCY = 512;
3
+ /**
4
+ * Keeps up to `batchSize` items in flight and returns results in input order.
5
+ * Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.
6
+ * @param items - The items to process
7
+ * @param processor - Processes one item
8
+ * @param batchSize - The maximum number of items in flight at once
9
+ * @returns The processor results, in input order
10
+ */
11
+ async function batchProcess(items, processor, batchSize = 25) {
12
+ if (items.length === 0) return [];
13
+ const results = Array.from({ length: items.length });
14
+ const executing = /* @__PURE__ */ new Set();
15
+ for (let i = 0; i < items.length; i++) {
16
+ const promise = processor(items[i], i).then((result) => {
17
+ results[i] = result;
18
+ executing.delete(promise);
19
+ });
20
+ executing.add(promise);
21
+ if (executing.size >= batchSize) await Promise.race(executing);
22
+ }
23
+ await Promise.all(executing);
24
+ return results;
25
+ }
26
+ //#endregion
27
+ export { FILE_IO_CONCURRENCY, batchProcess };
28
+
29
+ //# sourceMappingURL=batchProcess.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batchProcess.js","names":[],"sources":["../../src/utils/batchProcess.ts"],"sourcesContent":["// Max files a postprocess pass reads or writes at once. Unbounded\n// Promise.all over every translated file opens a descriptor per file and\n// fails with EMFILE on large projects.\nexport const FILE_IO_CONCURRENCY = 512;\n\n/**\n * Keeps up to `batchSize` items in flight and returns results in input order.\n * Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.\n * @param items - The items to process\n * @param processor - Processes one item\n * @param batchSize - The maximum number of items in flight at once\n * @returns The processor results, in input order\n */\nexport async function batchProcess<T, R>(\n items: T[],\n processor: (item: T, index: number) => Promise<R>,\n batchSize: number = 25\n): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n const results = Array.from({ length: items.length }) as R[];\n const executing = new Set<Promise<void>>();\n\n for (let i = 0; i < items.length; i++) {\n const promise = processor(items[i], i).then((result) => {\n results[i] = result;\n executing.delete(promise);\n });\n\n executing.add(promise);\n\n if (executing.size >= batchSize) {\n await Promise.race(executing);\n }\n }\n\n await Promise.all(executing);\n\n return results;\n}\n"],"mappings":";AAGA,MAAa,sBAAsB;;;;;;;;;AAUnC,eAAsB,aACpB,OACA,WACA,YAAoB,IACN;AACd,KAAI,MAAM,WAAW,EACnB,QAAO,EAAE;CAEX,MAAM,UAAU,MAAM,KAAK,EAAE,QAAQ,MAAM,QAAQ,CAAC;CACpD,MAAM,4BAAY,IAAI,KAAoB;AAE1C,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,UAAU,UAAU,MAAM,IAAI,EAAE,CAAC,MAAM,WAAW;AACtD,WAAQ,KAAK;AACb,aAAU,OAAO,QAAQ;IACzB;AAEF,YAAU,IAAI,QAAQ;AAEtB,MAAI,UAAU,QAAQ,UACpB,OAAM,QAAQ,KAAK,UAAU;;AAIjC,OAAM,QAAQ,IAAI,UAAU;AAE5B,QAAO"}
@@ -1,18 +1,16 @@
1
1
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
+ import { batchProcess } from "./batchProcess.js";
2
3
  import fs from "node:fs";
3
4
  //#region src/utils/flattenJsonFiles.ts
4
5
  async function flattenJsonFiles(settings, includeFiles) {
5
6
  if (!settings.files || Object.keys(settings.files.placeholderPaths).length === 1 && settings.files.placeholderPaths.gt) return;
6
7
  const { resolvedPaths: sourceFiles } = settings.files;
7
8
  const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths, settings.files.transformFormats, settings.locales, settings.defaultLocale);
8
- await Promise.all(Object.values(fileMapping).map(async (filesMap) => {
9
- const targetFiles = Object.values(filesMap).filter((p) => p.endsWith(".json") && (!includeFiles || includeFiles.has(p)));
10
- await Promise.all(targetFiles.map(async (file) => {
11
- const flattenedJson = flattenJson(JSON.parse(fs.readFileSync(file, "utf8")));
12
- await fs.promises.writeFile(file, JSON.stringify(flattenedJson, null, 2));
13
- return flattenedJson;
14
- }));
15
- }));
9
+ for (const filesMap of Object.values(fileMapping)) await batchProcess(Object.values(filesMap).filter((p) => p.endsWith(".json") && (!includeFiles || includeFiles.has(p))), async (file) => {
10
+ const flattenedJson = flattenJson(JSON.parse(fs.readFileSync(file, "utf8")));
11
+ await fs.promises.writeFile(file, JSON.stringify(flattenedJson, null, 2));
12
+ return flattenedJson;
13
+ }, 512);
16
14
  }
17
15
  function flattenJson(json, prefix = "") {
18
16
  const result = {};
@@ -1 +1 @@
1
- {"version":3,"file":"flattenJsonFiles.js","names":[],"sources":["../../src/utils/flattenJsonFiles.ts"],"sourcesContent":["import { createFileMapping } from '../formats/files/fileMapping.js';\nimport fs from 'node:fs';\nimport { Settings } from '../types/index.js';\n\nexport default async function flattenJsonFiles(\n settings: Settings,\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\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n await Promise.all(\n Object.values(fileMapping).map(async (filesMap) => {\n const targetFiles = Object.values(filesMap).filter(\n (p) => p.endsWith('.json') && (!includeFiles || includeFiles.has(p))\n );\n\n await Promise.all(\n targetFiles.map(async (file) => {\n // Read each json file\n const json = JSON.parse(fs.readFileSync(file, 'utf8'));\n // Flatten the json\n const flattenedJson = flattenJson(json);\n\n // Write the flattened json to the target file\n await fs.promises.writeFile(\n file,\n JSON.stringify(flattenedJson, null, 2)\n );\n return flattenedJson;\n })\n );\n })\n );\n}\n\nfunction flattenJson(json: unknown, prefix = ''): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(json as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(result, flattenJson(value, newKey));\n } else {\n result[newKey] = value;\n }\n }\n\n return result;\n}\n"],"mappings":";;;AAIA,eAA8B,iBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC;CAEF,MAAM,EAAE,eAAe,gBAAgB,SAAS;CAEhD,MAAM,cAAc,kBAClB,aACA,SAAS,MAAM,kBACf,SAAS,MAAM,gBACf,SAAS,MAAM,kBACf,SAAS,SACT,SAAS,cACV;AAED,OAAM,QAAQ,IACZ,OAAO,OAAO,YAAY,CAAC,IAAI,OAAO,aAAa;EACjD,MAAM,cAAc,OAAO,OAAO,SAAS,CAAC,QACzC,MAAM,EAAE,SAAS,QAAQ,KAAK,CAAC,gBAAgB,aAAa,IAAI,EAAE,EACpE;AAED,QAAM,QAAQ,IACZ,YAAY,IAAI,OAAO,SAAS;GAI9B,MAAM,gBAAgB,YAFT,KAAK,MAAM,GAAG,aAAa,MAAM,OAAO,CAEf,CAAC;AAGvC,SAAM,GAAG,SAAS,UAChB,MACA,KAAK,UAAU,eAAe,MAAM,EAAE,CACvC;AACD,UAAO;IACP,CACH;GACD,CACH;;AAGH,SAAS,YAAY,MAAe,SAAS,IAA6B;CACxE,MAAM,SAAkC,EAAE;AAE1C,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,EAAE;EAC1E,MAAM,SAAS,SAAS,GAAG,OAAO,GAAG,QAAQ;AAE7C,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,CACtE,QAAO,OAAO,QAAQ,YAAY,OAAO,OAAO,CAAC;MAEjD,QAAO,UAAU;;AAIrB,QAAO"}
1
+ {"version":3,"file":"flattenJsonFiles.js","names":[],"sources":["../../src/utils/flattenJsonFiles.ts"],"sourcesContent":["import { createFileMapping } from '../formats/files/fileMapping.js';\nimport fs from 'node:fs';\nimport { Settings } from '../types/index.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nexport default async function flattenJsonFiles(\n settings: Settings,\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\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n // One locale at a time so the concurrency bound covers the whole pass\n for (const filesMap of Object.values(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (p) => p.endsWith('.json') && (!includeFiles || includeFiles.has(p))\n );\n\n await batchProcess(\n targetFiles,\n async (file) => {\n // Read each json file\n const json = JSON.parse(fs.readFileSync(file, 'utf8'));\n // Flatten the json\n const flattenedJson = flattenJson(json);\n\n // Write the flattened json to the target file\n await fs.promises.writeFile(\n file,\n JSON.stringify(flattenedJson, null, 2)\n );\n return flattenedJson;\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n\nfunction flattenJson(json: unknown, prefix = ''): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(json as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(result, flattenJson(value, newKey));\n } else {\n result[newKey] = value;\n }\n }\n\n return result;\n}\n"],"mappings":";;;;AAKA,eAA8B,iBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC;CAEF,MAAM,EAAE,eAAe,gBAAgB,SAAS;CAEhD,MAAM,cAAc,kBAClB,aACA,SAAS,MAAM,kBACf,SAAS,MAAM,gBACf,SAAS,MAAM,kBACf,SAAS,SACT,SAAS,cACV;AAGD,MAAK,MAAM,YAAY,OAAO,OAAO,YAAY,CAK/C,OAAM,aAJc,OAAO,OAAO,SAAS,CAAC,QACzC,MAAM,EAAE,SAAS,QAAQ,KAAK,CAAC,gBAAgB,aAAa,IAAI,EAAE,EAIxD,EACX,OAAO,SAAS;EAId,MAAM,gBAAgB,YAFT,KAAK,MAAM,GAAG,aAAa,MAAM,OAAO,CAEf,CAAC;AAGvC,QAAM,GAAG,SAAS,UAChB,MACA,KAAK,UAAU,eAAe,MAAM,EAAE,CACvC;AACD,SAAO;QAGV;;AAIL,SAAS,YAAY,MAAe,SAAS,IAA6B;CACxE,MAAM,SAAkC,EAAE;AAE1C,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,EAAE;EAC1E,MAAM,SAAS,SAAS,GAAG,OAAO,GAAG,QAAQ;AAE7C,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,CACtE,QAAO,OAAO,QAAQ,YAAY,OAAO,OAAO,CAAC;MAEjD,QAAO,UAAU;;AAIrB,QAAO"}
@@ -1,4 +1,5 @@
1
1
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
+ import { batchProcess } from "./batchProcess.js";
2
3
  import path from "node:path";
3
4
  import fs from "node:fs";
4
5
  import YAML, { isMap, isScalar } from "yaml";
@@ -77,14 +78,11 @@ async function localizeMintlifyFrontmatterUrls(settings, includeFiles) {
77
78
  if (settings.framework !== "mintlify" || !settings.files) return;
78
79
  const fileMapping = createFileMapping(settings.files.resolvedPaths, settings.files.placeholderPaths, settings.files.transformPaths ?? {}, settings.files.transformFormats ?? {}, settings.locales, settings.defaultLocale);
79
80
  const knownLocaleValues = [settings.defaultLocale, ...settings.locales];
80
- for (const [locale, filesMap] of Object.entries(fileMapping)) {
81
- const targetFiles = Object.values(filesMap).filter((filePath) => (filePath.endsWith(".md") || filePath.endsWith(".mdx")) && shouldProcessFile(filePath, includeFiles));
82
- await Promise.all(targetFiles.map(async (filePath) => {
83
- if (!fs.existsSync(filePath)) return;
84
- const result = localizeMintlifyFrontmatterUrlForContent(await fs.promises.readFile(filePath, "utf8"), locale, knownLocaleValues);
85
- if (result.changed) await fs.promises.writeFile(filePath, result.content, "utf8");
86
- }));
87
- }
81
+ for (const [locale, filesMap] of Object.entries(fileMapping)) await batchProcess(Object.values(filesMap).filter((filePath) => (filePath.endsWith(".md") || filePath.endsWith(".mdx")) && shouldProcessFile(filePath, includeFiles)), async (filePath) => {
82
+ if (!fs.existsSync(filePath)) return;
83
+ const result = localizeMintlifyFrontmatterUrlForContent(await fs.promises.readFile(filePath, "utf8"), locale, knownLocaleValues);
84
+ if (result.changed) await fs.promises.writeFile(filePath, result.content, "utf8");
85
+ }, 512);
88
86
  }
89
87
  //#endregion
90
88
  export { localizeMintlifyFrontmatterUrls as default, localizeMintlifyFrontmatterUrlForContent };
@@ -1 +1 @@
1
- {"version":3,"file":"localizeMintlifyFrontmatterUrls.js","names":[],"sources":["../../src/utils/localizeMintlifyFrontmatterUrls.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport YAML, { isMap, isScalar } from 'yaml';\nimport type { Content, Root, Yaml } from 'mdast';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport type { Settings } from '../types/index.js';\n\nconst SKIPPABLE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#|\\.\\/|\\.\\.\\/)/i;\n\nfunction getYamlFrontmatter(content: string): Yaml | null {\n let tree: Root;\n try {\n tree = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, ['yaml'])\n .parse(content) as Root;\n } catch {\n return null;\n }\n\n const yamlNode = (tree.children as Content[]).find(\n (node): node is Yaml => (node as Yaml).type === 'yaml'\n );\n if (\n !yamlNode ||\n !yamlNode.position ||\n yamlNode.position.start?.offset === undefined ||\n yamlNode.position.end?.offset === undefined\n ) {\n return null;\n }\n return yamlNode;\n}\n\nfunction normalizeMintlifyFrontmatterUrl(\n url: string,\n targetLocale: string,\n knownLocales: Set<string>\n): string | null {\n const trimmed = url.trim();\n if (!trimmed || SKIPPABLE_URL_REGEX.test(trimmed)) {\n return null;\n }\n\n const leadingWhitespace = url.match(/^\\s*/)?.[0] ?? '';\n const trailingWhitespace = url.match(/\\s*$/)?.[0] ?? '';\n const leadingSlash = trimmed.startsWith('/') ? '/' : '';\n const pathBody = trimmed.replace(/^\\/+/, '');\n const [firstSegment, ...restSegments] = pathBody.split('/');\n\n if (firstSegment === targetLocale) {\n const normalized = `${leadingWhitespace}${leadingSlash}${pathBody}${trailingWhitespace}`;\n return normalized === url ? null : normalized;\n }\n\n const unprefixedPath = knownLocales.has(firstSegment)\n ? restSegments.join('/')\n : pathBody;\n const localizedPath = unprefixedPath\n ? `${targetLocale}/${unprefixedPath}`\n : `${targetLocale}/`;\n const normalized = `${leadingWhitespace}${leadingSlash}${localizedPath}${trailingWhitespace}`;\n\n return normalized === url ? null : normalized;\n}\n\nexport function localizeMintlifyFrontmatterUrlForContent(\n content: string,\n targetLocale: string,\n knownLocaleValues: string[]\n): { content: string; changed: boolean } {\n const yamlNode = getYamlFrontmatter(content);\n if (!yamlNode) {\n return { content, changed: false };\n }\n\n const frontmatterRaw: string = yamlNode.value || '';\n const doc = YAML.parseDocument(frontmatterRaw, {\n prettyErrors: false,\n keepSourceTokens: true,\n });\n if (doc.errors?.length || !isMap(doc.contents)) {\n return { content, changed: false };\n }\n\n const urlNode = doc.get('url', true);\n if (!isScalar(urlNode) || typeof urlNode.value !== 'string') {\n return { content, changed: false };\n }\n\n const localizedUrl = normalizeMintlifyFrontmatterUrl(\n urlNode.value,\n targetLocale,\n new Set(knownLocaleValues)\n );\n if (!localizedUrl) {\n return { content, changed: false };\n }\n\n urlNode.value = localizedUrl;\n\n const start = yamlNode.position!.start.offset as number;\n const end = yamlNode.position!.end.offset as number;\n const newline = content.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const frontmatter = doc.toString().trimEnd().replace(/\\n/g, newline);\n return {\n content: `${content.slice(0, start)}---${newline}${frontmatter}${newline}---${content.slice(end)}`,\n changed: true,\n };\n}\n\nfunction shouldProcessFile(filePath: string, includeFiles?: Set<string>) {\n if (!includeFiles) return true;\n return includeFiles.has(filePath) || includeFiles.has(path.resolve(filePath));\n}\n\nexport default async function localizeMintlifyFrontmatterUrls(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (settings.framework !== 'mintlify' || !settings.files) return;\n\n const fileMapping = createFileMapping(\n settings.files.resolvedPaths,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales,\n settings.defaultLocale\n );\n const knownLocaleValues = [settings.defaultLocale, ...settings.locales];\n\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (filePath) =>\n (filePath.endsWith('.md') || filePath.endsWith('.mdx')) &&\n shouldProcessFile(filePath, includeFiles)\n );\n\n await Promise.all(\n targetFiles.map(async (filePath) => {\n if (!fs.existsSync(filePath)) return;\n\n const content = await fs.promises.readFile(filePath, 'utf8');\n const result = localizeMintlifyFrontmatterUrlForContent(\n content,\n locale,\n knownLocaleValues\n );\n if (result.changed) {\n await fs.promises.writeFile(filePath, result.content, 'utf8');\n }\n })\n );\n }\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,sBAAsB;AAE5B,SAAS,mBAAmB,SAA8B;CACxD,IAAI;AACJ,KAAI;AACF,SAAO,SAAS,CACb,IAAI,YAAY,CAChB,IAAI,mBAAmB,CAAC,OAAO,CAAC,CAChC,MAAM,QAAQ;SACX;AACN,SAAO;;CAGT,MAAM,WAAY,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,WAAW,SAAS,CAAE;GAG9B,MAAM,SAAS,yCACb,MAFoB,GAAG,SAAS,SAAS,UAAU,OAAO,EAG1D,QACA,kBACD;AACD,OAAI,OAAO,QACT,OAAM,GAAG,SAAS,UAAU,UAAU,OAAO,SAAS,OAAO;IAE/D,CACH"}
1
+ {"version":3,"file":"localizeMintlifyFrontmatterUrls.js","names":[],"sources":["../../src/utils/localizeMintlifyFrontmatterUrls.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport YAML, { isMap, isScalar } from 'yaml';\nimport type { Content, Root, Yaml } from 'mdast';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport type { Settings } from '../types/index.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nconst SKIPPABLE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#|\\.\\/|\\.\\.\\/)/i;\n\nfunction getYamlFrontmatter(content: string): Yaml | null {\n let tree: Root;\n try {\n tree = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, ['yaml'])\n .parse(content) as Root;\n } catch {\n return null;\n }\n\n const yamlNode = (tree.children as Content[]).find(\n (node): node is Yaml => (node as Yaml).type === 'yaml'\n );\n if (\n !yamlNode ||\n !yamlNode.position ||\n yamlNode.position.start?.offset === undefined ||\n yamlNode.position.end?.offset === undefined\n ) {\n return null;\n }\n return yamlNode;\n}\n\nfunction normalizeMintlifyFrontmatterUrl(\n url: string,\n targetLocale: string,\n knownLocales: Set<string>\n): string | null {\n const trimmed = url.trim();\n if (!trimmed || SKIPPABLE_URL_REGEX.test(trimmed)) {\n return null;\n }\n\n const leadingWhitespace = url.match(/^\\s*/)?.[0] ?? '';\n const trailingWhitespace = url.match(/\\s*$/)?.[0] ?? '';\n const leadingSlash = trimmed.startsWith('/') ? '/' : '';\n const pathBody = trimmed.replace(/^\\/+/, '');\n const [firstSegment, ...restSegments] = pathBody.split('/');\n\n if (firstSegment === targetLocale) {\n const normalized = `${leadingWhitespace}${leadingSlash}${pathBody}${trailingWhitespace}`;\n return normalized === url ? null : normalized;\n }\n\n const unprefixedPath = knownLocales.has(firstSegment)\n ? restSegments.join('/')\n : pathBody;\n const localizedPath = unprefixedPath\n ? `${targetLocale}/${unprefixedPath}`\n : `${targetLocale}/`;\n const normalized = `${leadingWhitespace}${leadingSlash}${localizedPath}${trailingWhitespace}`;\n\n return normalized === url ? null : normalized;\n}\n\nexport function localizeMintlifyFrontmatterUrlForContent(\n content: string,\n targetLocale: string,\n knownLocaleValues: string[]\n): { content: string; changed: boolean } {\n const yamlNode = getYamlFrontmatter(content);\n if (!yamlNode) {\n return { content, changed: false };\n }\n\n const frontmatterRaw: string = yamlNode.value || '';\n const doc = YAML.parseDocument(frontmatterRaw, {\n prettyErrors: false,\n keepSourceTokens: true,\n });\n if (doc.errors?.length || !isMap(doc.contents)) {\n return { content, changed: false };\n }\n\n const urlNode = doc.get('url', true);\n if (!isScalar(urlNode) || typeof urlNode.value !== 'string') {\n return { content, changed: false };\n }\n\n const localizedUrl = normalizeMintlifyFrontmatterUrl(\n urlNode.value,\n targetLocale,\n new Set(knownLocaleValues)\n );\n if (!localizedUrl) {\n return { content, changed: false };\n }\n\n urlNode.value = localizedUrl;\n\n const start = yamlNode.position!.start.offset as number;\n const end = yamlNode.position!.end.offset as number;\n const newline = content.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const frontmatter = doc.toString().trimEnd().replace(/\\n/g, newline);\n return {\n content: `${content.slice(0, start)}---${newline}${frontmatter}${newline}---${content.slice(end)}`,\n changed: true,\n };\n}\n\nfunction shouldProcessFile(filePath: string, includeFiles?: Set<string>) {\n if (!includeFiles) return true;\n return includeFiles.has(filePath) || includeFiles.has(path.resolve(filePath));\n}\n\nexport default async function localizeMintlifyFrontmatterUrls(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (settings.framework !== 'mintlify' || !settings.files) return;\n\n const fileMapping = createFileMapping(\n settings.files.resolvedPaths,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales,\n settings.defaultLocale\n );\n const knownLocaleValues = [settings.defaultLocale, ...settings.locales];\n\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (filePath) =>\n (filePath.endsWith('.md') || filePath.endsWith('.mdx')) &&\n shouldProcessFile(filePath, includeFiles)\n );\n\n await batchProcess(\n targetFiles,\n async (filePath) => {\n if (!fs.existsSync(filePath)) return;\n\n const content = await fs.promises.readFile(filePath, 'utf8');\n const result = localizeMintlifyFrontmatterUrlForContent(\n content,\n locale,\n knownLocaleValues\n );\n if (result.changed) {\n await fs.promises.writeFile(filePath, result.content, 'utf8');\n }\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,sBAAsB;AAE5B,SAAS,mBAAmB,SAA8B;CACxD,IAAI;AACJ,KAAI;AACF,SAAO,SAAS,CACb,IAAI,YAAY,CAChB,IAAI,mBAAmB,CAAC,OAAO,CAAC,CAChC,MAAM,QAAQ;SACX;AACN,SAAO;;CAGT,MAAM,WAAY,KAAK,SAAuB,MAC3C,SAAwB,KAAc,SAAS,OACjD;AACD,KACE,CAAC,YACD,CAAC,SAAS,YACV,SAAS,SAAS,OAAO,WAAW,KAAA,KACpC,SAAS,SAAS,KAAK,WAAW,KAAA,EAElC,QAAO;AAET,QAAO;;AAGT,SAAS,gCACP,KACA,cACA,cACe;CACf,MAAM,UAAU,IAAI,MAAM;AAC1B,KAAI,CAAC,WAAW,oBAAoB,KAAK,QAAQ,CAC/C,QAAO;CAGT,MAAM,oBAAoB,IAAI,MAAM,OAAO,GAAG,MAAM;CACpD,MAAM,qBAAqB,IAAI,MAAM,OAAO,GAAG,MAAM;CACrD,MAAM,eAAe,QAAQ,WAAW,IAAI,GAAG,MAAM;CACrD,MAAM,WAA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,MAAM,CAAC,KAAK,UAAU,cAAc,QAAQ,KAAK,QAAQ,MAAM,IAAI;EAChG,SAAS;EACV;;AAGH,SAAS,kBAAkB,UAAkB,cAA4B;AACvE,KAAI,CAAC,aAAc,QAAO;AAC1B,QAAO,aAAa,IAAI,SAAS,IAAI,aAAa,IAAI,KAAK,QAAQ,SAAS,CAAC;;AAG/E,eAA8B,gCAC5B,UACA,cACA;AACA,KAAI,SAAS,cAAc,cAAc,CAAC,SAAS,MAAO;CAE1D,MAAM,cAAc,kBAClB,SAAS,MAAM,eACf,SAAS,MAAM,kBACf,SAAS,MAAM,kBAAkB,EAAE,EACnC,SAAS,MAAM,oBAAoB,EAAE,EACrC,SAAS,SACT,SAAS,cACV;CACD,MAAM,oBAAoB,CAAC,SAAS,eAAe,GAAG,SAAS,QAAQ;AAEvE,MAAK,MAAM,CAAC,QAAQ,aAAa,OAAO,QAAQ,YAAY,CAO1D,OAAM,aANc,OAAO,OAAO,SAAS,CAAC,QACzC,cACE,SAAS,SAAS,MAAM,IAAI,SAAS,SAAS,OAAO,KACtD,kBAAkB,UAAU,aAAa,CAIhC,EACX,OAAO,aAAa;AAClB,MAAI,CAAC,GAAG,WAAW,SAAS,CAAE;EAG9B,MAAM,SAAS,yCACb,MAFoB,GAAG,SAAS,SAAS,UAAU,OAAO,EAG1D,QACA,kBACD;AACD,MAAI,OAAO,QACT,OAAM,GAAG,SAAS,UAAU,UAAU,OAAO,SAAS,OAAO;QAIlE"}
@@ -1,5 +1,6 @@
1
1
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
2
  import { parseMdxForRoundTrip, restoreAnchorIds } from "./mdxAnchorSyntax.js";
3
+ import { batchProcess } from "./batchProcess.js";
3
4
  import path from "node:path";
4
5
  import * as fs$1 from "fs";
5
6
  import { unified } from "unified";
@@ -106,20 +107,19 @@ async function localizeRelativeAssets(settings, targetLocales, includeFiles) {
106
107
  const locales = targetLocales || settings.locales;
107
108
  const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths ?? {}, settings.files.transformFormats ?? {}, settings.locales, settings.defaultLocale);
108
109
  const cwd = process.cwd();
109
- const processPromises = Object.entries(fileMapping).filter(([locale]) => locales.includes(locale)).map(async ([, filesMap]) => {
110
+ const targetMappings = Object.entries(fileMapping).filter(([locale]) => locales.includes(locale));
111
+ for (const [, filesMap] of targetMappings) {
110
112
  const reverseMap = /* @__PURE__ */ new Map();
111
113
  for (const [sourcePath, targetPath] of Object.entries(filesMap)) reverseMap.set(targetPath, sourcePath);
112
- const targetFiles = Object.values(filesMap).filter((p) => (p.endsWith(".md") || p.endsWith(".mdx")) && (!includeFiles || includeFiles.has(p)));
113
- await Promise.all(targetFiles.map(async (targetPath) => {
114
+ await batchProcess(Object.values(filesMap).filter((p) => (p.endsWith(".md") || p.endsWith(".mdx")) && (!includeFiles || includeFiles.has(p))), async (targetPath) => {
114
115
  if (!fs$1.existsSync(targetPath)) return;
115
116
  const sourcePath = reverseMap.get(targetPath);
116
117
  if (!sourcePath) return;
117
118
  if (!fs$1.existsSync(sourcePath)) return;
118
119
  const result = localizeRelativeAssetsForContent(await fs$1.promises.readFile(targetPath, "utf8"), sourcePath, targetPath, cwd);
119
120
  if (result.hasChanges) await fs$1.promises.writeFile(targetPath, result.content);
120
- }));
121
- });
122
- await Promise.all(processPromises);
121
+ }, 512);
122
+ }
123
123
  }
124
124
  //#endregion
125
125
  export { localizeRelativeAssets as default, localizeRelativeAssetsForContent };
@@ -1 +1 @@
1
- {"version":3,"file":"localizeRelativeAssets.js","names":["fs"],"sources":["../../src/utils/localizeRelativeAssets.ts"],"sourcesContent":["import * as fs from 'fs';\nimport path from 'node:path';\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 { Literal, Root } from 'mdast';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\nimport type { StaticLocalizationSettings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\n\ntype RewriteResult = { content: string; hasChanges: boolean };\nexport type RelativeAssetSettings = StaticLocalizationSettings;\n\ntype MdxAssetNode = {\n type?: string;\n name?: unknown;\n attributes?: unknown;\n url?: unknown;\n};\n\ntype MdxAttribute = {\n type?: string;\n name?: string;\n value?: unknown;\n};\n\nfunction stripQueryAndHash(url: string): { base: string; suffix: string } {\n const match = url.match(/^[^?#]+/);\n const base = match ? match[0] : url;\n const suffix = url.slice(base.length);\n return { base, suffix };\n}\n\nfunction isSkippableUrl(url: string): boolean {\n if (!url) return true;\n if (url.startsWith('/')) return true;\n if (/^(https?:)?\\/\\//i.test(url)) return true;\n if (url.startsWith('data:')) return true;\n if (url.startsWith('#')) return true;\n if (url.startsWith('mailto:')) return true;\n if (url.startsWith('tel:')) return true;\n return false;\n}\n\nfunction toPosix(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\nfunction isSubPath(child: string, parent: string): boolean {\n const rel = path.relative(parent, child);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n}\n\nexport function localizeRelativeAssetsForContent(\n content: string,\n sourcePath: string,\n targetPath: string,\n cwd: string\n): RewriteResult {\n let changed = false;\n\n let ast: Root;\n let neutralizedAnchors: boolean;\n try {\n const parsed = parseMdxForRoundTrip(content);\n ast = parsed.ast;\n neutralizedAnchors = parsed.neutralized;\n } catch {\n return { content, hasChanges: false };\n }\n\n const sourceDir = path.dirname(sourcePath);\n const targetDir = path.dirname(targetPath);\n\n const maybeRewrite = (url: string): string | null => {\n if (isSkippableUrl(url)) return null;\n const { base, suffix } = stripQueryAndHash(url);\n if (isSkippableUrl(base)) return null;\n\n const targetResolved = path.resolve(targetDir, base);\n if (fs.existsSync(targetResolved)) {\n return null;\n }\n\n const sourceResolved = path.resolve(sourceDir, base);\n if (!fs.existsSync(sourceResolved)) {\n return null;\n }\n\n let newPath: string;\n if (isSubPath(sourceResolved, cwd)) {\n newPath = '/' + toPosix(path.relative(cwd, sourceResolved));\n } else {\n const rel = toPosix(path.relative(targetDir, sourceResolved));\n newPath = rel || toPosix(path.basename(sourceResolved));\n }\n\n if (newPath === base) return null;\n changed = true;\n return newPath + suffix;\n };\n\n visit(ast, (node) => {\n const assetNode = node as MdxAssetNode;\n if (assetNode.type === 'image' && typeof assetNode.url === 'string') {\n const newUrl = maybeRewrite(assetNode.url);\n if (newUrl) assetNode.url = newUrl;\n return;\n }\n if (\n (assetNode.type === 'mdxJsxFlowElement' ||\n assetNode.type === 'mdxJsxTextElement') &&\n assetNode.name === 'img' &&\n Array.isArray(assetNode.attributes)\n ) {\n for (const attr of assetNode.attributes) {\n const attribute = attr as MdxAttribute;\n if (\n attribute.type === 'mdxJsxAttribute' &&\n attribute.name === 'src' &&\n typeof attribute.value === 'string'\n ) {\n const newUrl = maybeRewrite(attribute.value);\n if (newUrl) attribute.value = newUrl;\n }\n }\n }\n });\n\n try {\n const s = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n text(node: Literal) {\n return node.value;\n },\n },\n });\n const outTree = s.runSync(ast) as Root;\n let out = s.stringify(outTree);\n if (neutralizedAnchors) out = restoreAnchorIds(out);\n if (out.endsWith('\\n') && !content.endsWith('\\n')) out = out.slice(0, -1);\n if (content.startsWith('\\n') && !out.startsWith('\\n')) out = '\\n' + out;\n return { content: out, hasChanges: changed };\n } catch {\n return { content, hasChanges: false };\n }\n}\n\nexport default async function localizeRelativeAssets(\n settings: RelativeAssetSettings,\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\n const { resolvedPaths: sourceFiles } = settings.files;\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,\n settings.defaultLocale\n );\n\n const cwd = process.cwd();\n const processPromises = Object.entries(fileMapping)\n .filter(([locale]) => locales.includes(locale))\n .map(async ([, filesMap]) => {\n const reverseMap = new Map<string, string>();\n for (const [sourcePath, targetPath] of Object.entries(filesMap)) {\n reverseMap.set(targetPath, sourcePath);\n }\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n (p.endsWith('.md') || p.endsWith('.mdx')) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n await Promise.all(\n targetFiles.map(async (targetPath) => {\n if (!fs.existsSync(targetPath)) return;\n const sourcePath = reverseMap.get(targetPath);\n if (!sourcePath) return;\n if (!fs.existsSync(sourcePath)) return;\n\n const content = await fs.promises.readFile(targetPath, 'utf8');\n const result = localizeRelativeAssetsForContent(\n content,\n sourcePath,\n targetPath,\n cwd\n );\n if (result.hasChanges) {\n await fs.promises.writeFile(targetPath, result.content);\n }\n })\n );\n });\n\n await Promise.all(processPromises);\n}\n"],"mappings":";;;;;;;;;;;AA6BA,SAAS,kBAAkB,KAA+C;CACxE,MAAM,QAAQ,IAAI,MAAM,UAAU;CAClC,MAAM,OAAO,QAAQ,MAAM,KAAK;AAEhC,QAAO;EAAE;EAAM,QADA,IAAI,MAAM,KAAK,OACT;EAAE;;AAGzB,SAAS,eAAe,KAAsB;AAC5C,KAAI,CAAC,IAAK,QAAO;AACjB,KAAI,IAAI,WAAW,IAAI,CAAE,QAAO;AAChC,KAAI,mBAAmB,KAAK,IAAI,CAAE,QAAO;AACzC,KAAI,IAAI,WAAW,QAAQ,CAAE,QAAO;AACpC,KAAI,IAAI,WAAW,IAAI,CAAE,QAAO;AAChC,KAAI,IAAI,WAAW,UAAU,CAAE,QAAO;AACtC,KAAI,IAAI,WAAW,OAAO,CAAE,QAAO;AACnC,QAAO;;AAGT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AAM,oBAAoB,EAAE,EACrC,SAAS,SACT,SAAS,cACV;CAED,MAAM,MAAM,QAAQ,KAAK;CACzB,MAAM,kBAAkB,OAAO,QAAQ,YAAY,CAChD,QAAQ,CAAC,YAAY,QAAQ,SAAS,OAAO,CAAC,CAC9C,IAAI,OAAO,GAAG,cAAc;EAC3B,MAAM,6BAAa,IAAI,KAAqB;AAC5C,OAAK,MAAM,CAAC,YAAY,eAAe,OAAO,QAAQ,SAAS,CAC7D,YAAW,IAAI,YAAY,WAAW;EAExC,MAAM,cAAc,OAAO,OAAO,SAAS,CAAC,QACzC,OACE,EAAE,SAAS,MAAM,IAAI,EAAE,SAAS,OAAO,MACvC,CAAC,gBAAgB,aAAa,IAAI,EAAE,EACxC;AAED,QAAM,QAAQ,IACZ,YAAY,IAAI,OAAO,eAAe;AACpC,OAAI,CAACA,KAAG,WAAW,WAAW,CAAE;GAChC,MAAM,aAAa,WAAW,IAAI,WAAW;AAC7C,OAAI,CAAC,WAAY;AACjB,OAAI,CAACA,KAAG,WAAW,WAAW,CAAE;GAGhC,MAAM,SAAS,iCACb,MAFoBA,KAAG,SAAS,SAAS,YAAY,OAAO,EAG5D,YACA,YACA,IACD;AACD,OAAI,OAAO,WACT,OAAMA,KAAG,SAAS,UAAU,YAAY,OAAO,QAAQ;IAEzD,CACH;GACD;AAEJ,OAAM,QAAQ,IAAI,gBAAgB"}
1
+ {"version":3,"file":"localizeRelativeAssets.js","names":["fs"],"sources":["../../src/utils/localizeRelativeAssets.ts"],"sourcesContent":["import * as fs from 'fs';\nimport path from 'node:path';\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 { Literal, Root } from 'mdast';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\nimport type { StaticLocalizationSettings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\n\ntype RewriteResult = { content: string; hasChanges: boolean };\nexport type RelativeAssetSettings = StaticLocalizationSettings;\n\ntype MdxAssetNode = {\n type?: string;\n name?: unknown;\n attributes?: unknown;\n url?: unknown;\n};\n\ntype MdxAttribute = {\n type?: string;\n name?: string;\n value?: unknown;\n};\n\nfunction stripQueryAndHash(url: string): { base: string; suffix: string } {\n const match = url.match(/^[^?#]+/);\n const base = match ? match[0] : url;\n const suffix = url.slice(base.length);\n return { base, suffix };\n}\n\nfunction isSkippableUrl(url: string): boolean {\n if (!url) return true;\n if (url.startsWith('/')) return true;\n if (/^(https?:)?\\/\\//i.test(url)) return true;\n if (url.startsWith('data:')) return true;\n if (url.startsWith('#')) return true;\n if (url.startsWith('mailto:')) return true;\n if (url.startsWith('tel:')) return true;\n return false;\n}\n\nfunction toPosix(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\nfunction isSubPath(child: string, parent: string): boolean {\n const rel = path.relative(parent, child);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n}\n\nexport function localizeRelativeAssetsForContent(\n content: string,\n sourcePath: string,\n targetPath: string,\n cwd: string\n): RewriteResult {\n let changed = false;\n\n let ast: Root;\n let neutralizedAnchors: boolean;\n try {\n const parsed = parseMdxForRoundTrip(content);\n ast = parsed.ast;\n neutralizedAnchors = parsed.neutralized;\n } catch {\n return { content, hasChanges: false };\n }\n\n const sourceDir = path.dirname(sourcePath);\n const targetDir = path.dirname(targetPath);\n\n const maybeRewrite = (url: string): string | null => {\n if (isSkippableUrl(url)) return null;\n const { base, suffix } = stripQueryAndHash(url);\n if (isSkippableUrl(base)) return null;\n\n const targetResolved = path.resolve(targetDir, base);\n if (fs.existsSync(targetResolved)) {\n return null;\n }\n\n const sourceResolved = path.resolve(sourceDir, base);\n if (!fs.existsSync(sourceResolved)) {\n return null;\n }\n\n let newPath: string;\n if (isSubPath(sourceResolved, cwd)) {\n newPath = '/' + toPosix(path.relative(cwd, sourceResolved));\n } else {\n const rel = toPosix(path.relative(targetDir, sourceResolved));\n newPath = rel || toPosix(path.basename(sourceResolved));\n }\n\n if (newPath === base) return null;\n changed = true;\n return newPath + suffix;\n };\n\n visit(ast, (node) => {\n const assetNode = node as MdxAssetNode;\n if (assetNode.type === 'image' && typeof assetNode.url === 'string') {\n const newUrl = maybeRewrite(assetNode.url);\n if (newUrl) assetNode.url = newUrl;\n return;\n }\n if (\n (assetNode.type === 'mdxJsxFlowElement' ||\n assetNode.type === 'mdxJsxTextElement') &&\n assetNode.name === 'img' &&\n Array.isArray(assetNode.attributes)\n ) {\n for (const attr of assetNode.attributes) {\n const attribute = attr as MdxAttribute;\n if (\n attribute.type === 'mdxJsxAttribute' &&\n attribute.name === 'src' &&\n typeof attribute.value === 'string'\n ) {\n const newUrl = maybeRewrite(attribute.value);\n if (newUrl) attribute.value = newUrl;\n }\n }\n }\n });\n\n try {\n const s = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n text(node: Literal) {\n return node.value;\n },\n },\n });\n const outTree = s.runSync(ast) as Root;\n let out = s.stringify(outTree);\n if (neutralizedAnchors) out = restoreAnchorIds(out);\n if (out.endsWith('\\n') && !content.endsWith('\\n')) out = out.slice(0, -1);\n if (content.startsWith('\\n') && !out.startsWith('\\n')) out = '\\n' + out;\n return { content: out, hasChanges: changed };\n } catch {\n return { content, hasChanges: false };\n }\n}\n\nexport default async function localizeRelativeAssets(\n settings: RelativeAssetSettings,\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\n const { resolvedPaths: sourceFiles } = settings.files;\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,\n settings.defaultLocale\n );\n\n const cwd = process.cwd();\n // One locale at a time so the concurrency bound covers the whole pass\n const targetMappings = Object.entries(fileMapping).filter(([locale]) =>\n locales.includes(locale)\n );\n for (const [, filesMap] of targetMappings) {\n const reverseMap = new Map<string, string>();\n for (const [sourcePath, targetPath] of Object.entries(filesMap)) {\n reverseMap.set(targetPath, sourcePath);\n }\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n (p.endsWith('.md') || p.endsWith('.mdx')) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n await batchProcess(\n targetFiles,\n async (targetPath) => {\n if (!fs.existsSync(targetPath)) return;\n const sourcePath = reverseMap.get(targetPath);\n if (!sourcePath) return;\n if (!fs.existsSync(sourcePath)) return;\n\n const content = await fs.promises.readFile(targetPath, 'utf8');\n const result = localizeRelativeAssetsForContent(\n content,\n sourcePath,\n targetPath,\n cwd\n );\n if (result.hasChanges) {\n await fs.promises.writeFile(targetPath, result.content);\n }\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;AA8BA,SAAS,kBAAkB,KAA+C;CACxE,MAAM,QAAQ,IAAI,MAAM,UAAU;CAClC,MAAM,OAAO,QAAQ,MAAM,KAAK;AAEhC,QAAO;EAAE;EAAM,QADA,IAAI,MAAM,KAAK,OACT;EAAE;;AAGzB,SAAS,eAAe,KAAsB;AAC5C,KAAI,CAAC,IAAK,QAAO;AACjB,KAAI,IAAI,WAAW,IAAI,CAAE,QAAO;AAChC,KAAI,mBAAmB,KAAK,IAAI,CAAE,QAAO;AACzC,KAAI,IAAI,WAAW,QAAQ,CAAE,QAAO;AACpC,KAAI,IAAI,WAAW,IAAI,CAAE,QAAO;AAChC,KAAI,IAAI,WAAW,UAAU,CAAE,QAAO;AACtC,KAAI,IAAI,WAAW,OAAO,CAAE,QA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B,EAAE,EACnC,SAAS,MAAM,oBAAoB,EAAE,EACrC,SAAS,SACT,SAAS,cACV;CAED,MAAM,MAAM,QAAQ,KAAK;CAEzB,MAAM,iBAAiB,OAAO,QAAQ,YAAY,CAAC,QAAQ,CAAC,YAC1D,QAAQ,SAAS,OAAO,CACzB;AACD,MAAK,MAAM,GAAG,aAAa,gBAAgB;EACzC,MAAM,6BAAa,IAAI,KAAqB;AAC5C,OAAK,MAAM,CAAC,YAAY,eAAe,OAAO,QAAQ,SAAS,CAC7D,YAAW,IAAI,YAAY,WAAW;AAQxC,QAAM,aANc,OAAO,OAAO,SAAS,CAAC,QACzC,OACE,EAAE,SAAS,MAAM,IAAI,EAAE,SAAS,OAAO,MACvC,CAAC,gBAAgB,aAAa,IAAI,EAAE,EAI5B,EACX,OAAO,eAAe;AACpB,OAAI,CAACA,KAAG,WAAW,WAAW,CAAE;GAChC,MAAM,aAAa,WAAW,IAAI,WAAW;AAC7C,OAAI,CAAC,WAAY;AACjB,OAAI,CAACA,KAAG,WAAW,WAAW,CAAE;GAGhC,MAAM,SAAS,iCACb,MAFoBA,KAAG,SAAS,SAAS,YAAY,OAAO,EAG5D,YACA,YACA,IACD;AACD,OAAI,OAAO,WACT,OAAMA,KAAG,SAAS,UAAU,YAAY,OAAO,QAAQ;SAI5D"}
@@ -1,5 +1,6 @@
1
1
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
2
  import { parseMdxTolerantly } from "./mdxAnchorSyntax.js";
3
+ import { batchProcess } from "./batchProcess.js";
3
4
  import * as fs$1 from "fs";
4
5
  import micromatch from "micromatch";
5
6
  import * as path$1 from "path";
@@ -23,30 +24,21 @@ async function localizeStaticImports(settings, includeFiles) {
23
24
  if (!settings.files || Object.keys(settings.files.placeholderPaths).length === 1 && settings.files.placeholderPaths.gt) return;
24
25
  const { resolvedPaths: sourceFiles } = settings.files;
25
26
  const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths ?? {}, settings.files.transformFormats ?? {}, settings.locales, settings.defaultLocale);
26
- const processPromises = [];
27
27
  if (!fileMapping[settings.defaultLocale] && !includeFiles) {
28
28
  const defaultLocaleFiles = [];
29
29
  if (sourceFiles.md) defaultLocaleFiles.push(...sourceFiles.md);
30
30
  if (sourceFiles.mdx) defaultLocaleFiles.push(...sourceFiles.mdx);
31
- if (defaultLocaleFiles.length > 0) {
32
- const defaultPromise = Promise.all(defaultLocaleFiles.map(async (filePath) => {
33
- if (!fs$1.existsSync(filePath)) return;
34
- const localizedFile = localizeStaticImportsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, settings.defaultLocale, settings.options?.docsHideDefaultLocaleImport || false, settings.options?.docsImportPattern, settings.options?.excludeStaticImports, filePath, settings.options);
35
- await fs$1.promises.writeFile(filePath, localizedFile);
36
- }));
37
- processPromises.push(defaultPromise);
38
- }
39
- }
40
- const mappingPromises = Object.entries(fileMapping).map(async ([locale, filesMap]) => {
41
- const targetFiles = Object.values(filesMap).filter((p) => (p.endsWith(".md") || p.endsWith(".mdx")) && (!includeFiles || includeFiles.has(p)));
42
- await Promise.all(targetFiles.map(async (filePath) => {
31
+ if (defaultLocaleFiles.length > 0) await batchProcess(defaultLocaleFiles, async (filePath) => {
43
32
  if (!fs$1.existsSync(filePath)) return;
44
- const localizedFile = localizeStaticImportsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, locale, settings.options?.docsHideDefaultLocaleImport || false, settings.options?.docsImportPattern, settings.options?.excludeStaticImports, filePath, settings.options);
33
+ const localizedFile = localizeStaticImportsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, settings.defaultLocale, settings.options?.docsHideDefaultLocaleImport || false, settings.options?.docsImportPattern, settings.options?.excludeStaticImports, filePath, settings.options);
45
34
  await fs$1.promises.writeFile(filePath, localizedFile);
46
- }));
47
- });
48
- processPromises.push(...mappingPromises);
49
- await Promise.all(processPromises);
35
+ }, 512);
36
+ }
37
+ for (const [locale, filesMap] of Object.entries(fileMapping)) await batchProcess(Object.values(filesMap).filter((p) => (p.endsWith(".md") || p.endsWith(".mdx")) && (!includeFiles || includeFiles.has(p))), async (filePath) => {
38
+ if (!fs$1.existsSync(filePath)) return;
39
+ const localizedFile = localizeStaticImportsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, locale, settings.options?.docsHideDefaultLocaleImport || false, settings.options?.docsImportPattern, settings.options?.excludeStaticImports, filePath, settings.options);
40
+ await fs$1.promises.writeFile(filePath, localizedFile);
41
+ }, 512);
50
42
  }
51
43
  /**
52
44
  * Determines if an import path should be processed based on pattern matching
@@ -1 +1 @@
1
- {"version":3,"file":"localizeStaticImports.js","names":["fs","path"],"sources":["../../src/utils/localizeStaticImports.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type {\n AdditionalOptions,\n StaticLocalizationSettings,\n} from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport micromatch from 'micromatch';\nimport { visit } from 'unist-util-visit';\nimport type { Root } from 'mdast';\nimport type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\nimport { parseMdxTolerantly } from './mdxAnchorSyntax.js';\n\nconst { isMatch } = micromatch;\n\nexport type StaticImportSettings = StaticLocalizationSettings;\n\n/**\n * Localizes static imports 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 localizeStaticImports(\n settings: StaticImportSettings,\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\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales,\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 if (!fileMapping[settings.defaultLocale] && !includeFiles) {\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 localizedFile = localizeStaticImportsForFile(\n fileContent,\n settings.defaultLocale,\n settings.defaultLocale, // Process as default locale\n settings.options?.docsHideDefaultLocaleImport || false,\n settings.options?.docsImportPattern,\n settings.options?.excludeStaticImports,\n filePath,\n settings.options\n );\n // Write the localized file back to the same path\n await fs.promises.writeFile(filePath, localizedFile);\n })\n );\n processPromises.push(defaultPromise);\n }\n }\n\n // Then process all other locales from fileMapping\n const mappingPromises = Object.entries(fileMapping).map(\n async ([locale, filesMap]) => {\n // Get all files that are md or mdx\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n (p.endsWith('.md') || p.endsWith('.mdx')) &&\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\n const localizedFile = localizeStaticImportsForFile(\n fileContent,\n settings.defaultLocale,\n locale,\n settings.options?.docsHideDefaultLocaleImport || false,\n settings.options?.docsImportPattern,\n settings.options?.excludeStaticImports,\n filePath,\n settings.options\n );\n // Write the localized file to the target path\n await fs.promises.writeFile(filePath, localizedFile);\n })\n );\n }\n );\n processPromises.push(...mappingPromises);\n\n await Promise.all(processPromises);\n}\n\ninterface ImportTransformResult {\n content: string;\n hasChanges: boolean;\n transformedImports: Array<{\n originalPath: string;\n newPath: string;\n }>;\n}\n\n/**\n * Determines if an import path should be processed based on pattern matching\n */\nfunction shouldProcessImportPath(\n importPath: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string\n): boolean {\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n\n if (targetLocale === defaultLocale) {\n // For default locale processing, check if path contains the pattern\n return importPath.includes(patternWithoutSlash);\n } else {\n // For non-default locales, check if path starts with pattern\n return importPath.includes(patternWithoutSlash);\n }\n}\n\n/**\n * Checks if an import path should be excluded based on exclusion patterns\n */\nfunction isImportPathExcluded(\n importPath: 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(importPath, pattern));\n}\n\n/**\n * Transforms import path for default locale processing\n */\nfunction transformDefaultLocaleImportPath(\n fullPath: string,\n patternHead: string,\n defaultLocale: string,\n hideDefaultLocale: boolean\n): string | null {\n if (hideDefaultLocale) {\n // Remove locale from imports that have it: '/snippets/en/file.mdx' -> '/snippets/file.mdx'\n if (fullPath.includes(`/${defaultLocale}/`)) {\n return fullPath.replace(`/${defaultLocale}/`, '/');\n } else if (fullPath.endsWith(`/${defaultLocale}`)) {\n return fullPath.replace(`/${defaultLocale}`, '');\n }\n return null; // Path doesn't have default locale\n } else {\n // Add locale to imports that don't have it: '/snippets/file.mdx' -> '/snippets/en/file.mdx'\n if (\n fullPath.includes(`/${defaultLocale}/`) ||\n fullPath.endsWith(`/${defaultLocale}`)\n ) {\n return null; // Already has default locale\n }\n\n if (fullPath.startsWith(patternHead)) {\n const pathAfterHead = fullPath.slice(patternHead.length);\n if (pathAfterHead) {\n return `${patternHead}${defaultLocale}/${pathAfterHead}`;\n } else {\n return `${patternHead.replace(/\\/$/, '')}/${defaultLocale}`;\n }\n }\n return null; // Path doesn't match pattern\n }\n}\n\n/**\n * Transforms import path for non-default locale processing with hideDefaultLocale=true\n */\nfunction transformNonDefaultLocaleImportPathWithHidden(\n fullPath: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string\n): string | null {\n // Check if already localized\n if (\n fullPath.startsWith(`${patternHead}${targetLocale}/`) ||\n fullPath === `${patternHead}${targetLocale}`\n ) {\n return null;\n }\n\n // Replace default locale with target locale\n const expectedPathWithDefaultLocale = `${patternHead}${defaultLocale}`;\n if (\n fullPath.startsWith(`${expectedPathWithDefaultLocale}/`) ||\n fullPath === expectedPathWithDefaultLocale\n ) {\n return fullPath.replace(\n `${patternHead}${defaultLocale}`,\n `${patternHead}${targetLocale}`\n );\n }\n\n // Handle exact pattern match\n if (fullPath === patternHead.replace(/\\/$/, '')) {\n return `${patternHead.replace(/\\/$/, '')}/${targetLocale}`;\n }\n\n // Add target locale to path without any locale\n const pathAfterHead = fullPath.slice(patternHead.length);\n return pathAfterHead\n ? `${patternHead}${targetLocale}/${pathAfterHead}`\n : `${patternHead}${targetLocale}`;\n}\n\n/**\n * Transforms import path for non-default locale processing with hideDefaultLocale=false\n */\nfunction transformNonDefaultLocaleImportPath(\n fullPath: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string\n): string | null {\n // If already localized to target, skip\n const expectedPathWithTarget = `${patternHead}${targetLocale}`;\n if (\n fullPath.startsWith(`${expectedPathWithTarget}/`) ||\n fullPath === expectedPathWithTarget\n ) {\n return null;\n }\n const expectedPathWithLocale = `${patternHead}${defaultLocale}`;\n\n if (\n fullPath.startsWith(`${expectedPathWithLocale}/`) ||\n fullPath === expectedPathWithLocale\n ) {\n // Replace existing default locale with target locale\n return fullPath.replace(\n `${patternHead}${defaultLocale}`,\n `${patternHead}${targetLocale}`\n );\n } else if (fullPath.startsWith(patternHead)) {\n // Add target locale to path that doesn't have any locale\n const pathAfterHead = fullPath.slice(patternHead.length);\n if (pathAfterHead) {\n return `${patternHead}${targetLocale}/${pathAfterHead}`;\n } else {\n return `${patternHead.replace(/\\/$/, '')}/${targetLocale}`;\n }\n }\n\n return null; // Path doesn't match pattern\n}\n\n/**\n * Main import path transformation function that delegates to specific scenarios\n */\nfunction transformImportPath(\n fullPath: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean,\n currentFilePath?: string,\n projectRoot: string = process.cwd(), // fallback if not provided\n rewrites?: Array<{ match: string; replace: string }>\n): string | null {\n // Apply explicit rewrites first (e.g., Docusaurus @site/docs -> @site/i18n/[locale]/...)\n if (rewrites && rewrites.length > 0) {\n const localeMap: Record<string, string> = {\n '[locale]': targetLocale,\n '[defaultLocale]': defaultLocale,\n };\n\n for (const { match, replace } of rewrites) {\n const resolvedMatch = match.replace(\n /\\[locale\\]|\\[defaultLocale\\]/g,\n (token) => localeMap[token] || token\n );\n if (fullPath.startsWith(resolvedMatch)) {\n const remainder = fullPath.slice(resolvedMatch.length);\n const resolvedReplace = replace.replace(\n /\\[locale\\]|\\[defaultLocale\\]/g,\n (token) => localeMap[token] || token\n );\n let newPath: string;\n if (resolvedReplace.endsWith('/')) {\n newPath = `${resolvedReplace}${remainder.replace(/^\\//, '')}`;\n } else if (remainder.startsWith('/')) {\n newPath = `${resolvedReplace}${remainder}`;\n } else {\n newPath = `${resolvedReplace}/${remainder}`;\n }\n return newPath;\n }\n }\n }\n\n let newPath: string | null;\n\n if (targetLocale === defaultLocale) {\n newPath = transformDefaultLocaleImportPath(\n fullPath,\n patternHead,\n defaultLocale,\n hideDefaultLocale\n );\n } else if (hideDefaultLocale) {\n newPath = transformNonDefaultLocaleImportPathWithHidden(\n fullPath,\n patternHead,\n targetLocale,\n defaultLocale\n );\n } else {\n newPath = transformNonDefaultLocaleImportPath(\n fullPath,\n patternHead,\n targetLocale,\n defaultLocale\n );\n }\n\n if (!newPath) return null;\n\n if (currentFilePath) {\n let resolvedPath: string;\n if (newPath.startsWith('/')) {\n // Interpret as project-root relative\n resolvedPath = path.join(projectRoot, newPath.replace(/^\\//, ''));\n } else {\n // Relative to current file\n const currentDir = path.dirname(currentFilePath);\n resolvedPath = path.resolve(currentDir, newPath);\n }\n\n if (!fs.existsSync(resolvedPath)) {\n return null;\n }\n }\n\n return newPath;\n}\n\n/**\n * AST-based transformation for MDX files using remark-mdx\n */\nfunction transformMdxImports(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n currentFilePath?: string,\n options?: AdditionalOptions\n): ImportTransformResult {\n const transformedImports: Array<{ originalPath: string; newPath: string }> =\n [];\n\n // Don't auto-prefix relative patterns that start with . or ..\n if (!pattern.startsWith('/') && !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 transformedImports: [],\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 transformedImports: [],\n };\n }\n }\n\n // Parse the MDX content into an AST\n let processedAst: Root;\n try {\n // Parsed only to locate import nodes; edits below are applied to the\n // original string, so a neutralized parse cannot leak into the output.\n processedAst = parseMdxTolerantly(mdxContent);\n } catch {\n return transformImportsStringFallback(\n mdxContent,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n currentFilePath,\n options\n );\n }\n\n let content = mdxContent;\n\n // Visit only mdxjsEsm nodes (import/export statements) to collect replacements\n visit(processedAst, 'mdxjsEsm', (node: MdxjsEsm) => {\n if (node.value && node.value.includes(patternHead.replace(/\\/$/, ''))) {\n // Find import lines that need transformation\n const lines = node.value.split('\\n');\n\n lines.forEach((line: string) => {\n // Only process import lines that match our pattern\n if (!line.trim().startsWith('import ')) {\n return;\n }\n\n // Check if this line should be processed\n if (\n !shouldProcessImportPath(\n line,\n patternHead,\n targetLocale,\n defaultLocale\n )\n ) {\n return;\n }\n\n // Extract the path from the import statement\n const quotes = ['\"', \"'\", '`'];\n\n for (const quote of quotes) {\n // Try both with and without trailing slash\n let startPattern = `${quote}${patternHead}`;\n let startIndex = line.indexOf(startPattern);\n\n // If pattern has trailing slash but path doesn't, try without slash\n if (startIndex === -1 && patternHead.endsWith('/')) {\n const patternWithoutSlash = patternHead.slice(0, -1);\n startPattern = `${quote}${patternWithoutSlash}`;\n startIndex = line.indexOf(startPattern);\n }\n\n if (startIndex === -1) continue;\n\n const pathStart = startIndex + 1; // After the quote\n const pathEnd = line.indexOf(quote, pathStart);\n\n if (pathEnd === -1) continue;\n\n const fullPath = line.slice(pathStart, pathEnd);\n\n // Transform the import path\n const newPath = transformImportPath(\n fullPath,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale,\n currentFilePath,\n process.cwd(),\n options?.docsImportRewrites\n );\n\n if (!newPath) {\n continue; // No transformation needed\n }\n\n // Check exclusions\n if (isImportPathExcluded(fullPath, exclude, defaultLocale)) {\n continue;\n }\n\n // Apply the transformation to the original content\n // Simply replace the import path with the new path\n content = content.replace(\n `${quote}${fullPath}${quote}`,\n `${quote}${newPath}${quote}`\n );\n transformedImports.push({ originalPath: fullPath, newPath });\n break;\n }\n });\n }\n });\n\n return {\n content,\n hasChanges: transformedImports.length > 0,\n transformedImports,\n };\n}\n\n/**\n * String-based fallback for import localization when MDX parsing fails (e.g., on .md files)\n */\nfunction transformImportsStringFallback(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n currentFilePath?: string,\n options?: AdditionalOptions\n): ImportTransformResult {\n const transformedImports: Array<{ originalPath: string; newPath: string }> =\n [];\n\n if (!pattern.startsWith('/') && !pattern.startsWith('.')) {\n pattern = '/' + pattern;\n }\n const patternHead = pattern.split('[locale]')[0];\n\n let content = mdxContent;\n const importRegex = /import\\s+[^'\"]*['\"]([^'\"]+)['\"]\\s*;?/g;\n let match: RegExpExecArray | null;\n\n while ((match = importRegex.exec(mdxContent)) !== null) {\n const fullMatch = match[0];\n const importPath = match[1];\n\n if (\n !shouldProcessImportPath(\n importPath,\n patternHead,\n targetLocale,\n defaultLocale\n )\n ) {\n continue;\n }\n\n if (isImportPathExcluded(importPath, exclude, defaultLocale)) {\n continue;\n }\n\n const newPath = transformImportPath(\n importPath,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale,\n currentFilePath,\n process.cwd(),\n options?.docsImportRewrites\n );\n\n if (!newPath) continue;\n\n const updatedImport = fullMatch.replace(importPath, newPath);\n content = content.replace(fullMatch, updatedImport);\n transformedImports.push({ originalPath: importPath, newPath });\n }\n\n return {\n content,\n hasChanges: transformedImports.length > 0,\n transformedImports,\n };\n}\n\n/**\n * AST-based transformation for MDX files only\n */\nfunction localizeStaticImportsForFile(\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 currentFilePath?: string,\n options?: AdditionalOptions\n): string {\n // For MDX files, use AST-based transformation\n const result = transformMdxImports(\n file,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n currentFilePath,\n options\n );\n return result.content;\n}\n"],"mappings":";;;;;;;AAaA,MAAM,EAAE,YAAY;;;;;;;;;;;;;;AAiBpB,eAA8B,sBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK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A,SACuB;CACvB,MAAM,qBACJ,EAAE;AAEJ,KAAI,CAAC,QAAQ,WAAW,IAAI,IAAI,CAAC,QAAQ,WAAW,IAAI,CACtD,WAAU,MAAM;CAElB,MAAM,cAAc,QAAQ,MAAM,WAAW,CAAC;CAE9C,IAAI,UAAU;CACd,MAAM,cAAc;CACpB,IAAI;AAEJ,SAAQ,QAAQ,YAAY,KAAK,WAAW,MAAM,MAAM;EACtD,MAAM,YAAY,MAAM;EACxB,MAAM,aAAa,MAAM;AAEzB,MACE,CAAC,wBACC,YACA,aACA,cACA,cACD,CAED;AAGF,MAAI,qBAAqB,YAAY,SAAS,cAAc,CAC1D;EAGF,MAAM,UAAU,oBACd,YACA,aACA,cACA,eACA,mBACA,iBACA,QAAQ,KAAK,EACb,SAAS,mBACV;AAED,MAAI,CAAC,QAAS;EAEd,MAAM,gBAAgB,UAAU,QAAQ,YAAY,QAAQ;AAC5D,YAAU,QAAQ,QAAQ,WAAW,cAAc;AACnD,qBAAmB,KAAK;GAAE,cAAc;GAAY;GAAS,CAAC;;AAGhE,QAAO;EACL;EACA,YAAY,mBAAmB,SAAS;EACxC;EACD;;;;;AAMH,SAAS,6BACP,MACA,eACA,cACA,mBACA,UAAkB,aAClB,UAAoB,EAAE,EACtB,iBACA,SACQ;AAYR,QAVe,oBACb,MACA,eACA,cACA,mBACA,SACA,SACA,iBACA,QAEW,CAAC"}
1
+ {"version":3,"file":"localizeStaticImports.js","names":["fs","path"],"sources":["../../src/utils/localizeStaticImports.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type {\n AdditionalOptions,\n StaticLocalizationSettings,\n} from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport micromatch from 'micromatch';\nimport { visit } from 'unist-util-visit';\nimport type { Root } from 'mdast';\nimport type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\nimport { parseMdxTolerantly } from './mdxAnchorSyntax.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nconst { isMatch } = micromatch;\n\nexport type StaticImportSettings = StaticLocalizationSettings;\n\n/**\n * Localizes static imports 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 localizeStaticImports(\n settings: StaticImportSettings,\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\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales,\n settings.defaultLocale\n );\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 if (!fileMapping[settings.defaultLocale] && !includeFiles) {\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 await batchProcess(\n defaultLocaleFiles,\n 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 using default locale\n const localizedFile = localizeStaticImportsForFile(\n fileContent,\n settings.defaultLocale,\n settings.defaultLocale, // Process as default locale\n settings.options?.docsHideDefaultLocaleImport || false,\n settings.options?.docsImportPattern,\n settings.options?.excludeStaticImports,\n filePath,\n settings.options\n );\n // Write the localized file back to the same path\n await fs.promises.writeFile(filePath, localizedFile);\n },\n FILE_IO_CONCURRENCY\n );\n }\n }\n\n // Then process all other locales from fileMapping, one locale at a time so\n // the concurrency bound covers the whole pass\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n // Get all files that are md or mdx\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n (p.endsWith('.md') || p.endsWith('.mdx')) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n // Replace the placeholder path with the target path\n await batchProcess(\n targetFiles,\n 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\n const localizedFile = localizeStaticImportsForFile(\n fileContent,\n settings.defaultLocale,\n locale,\n settings.options?.docsHideDefaultLocaleImport || false,\n settings.options?.docsImportPattern,\n settings.options?.excludeStaticImports,\n filePath,\n settings.options\n );\n // Write the localized file to the target path\n await fs.promises.writeFile(filePath, localizedFile);\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n\ninterface ImportTransformResult {\n content: string;\n hasChanges: boolean;\n transformedImports: Array<{\n originalPath: string;\n newPath: string;\n }>;\n}\n\n/**\n * Determines if an import path should be processed based on pattern matching\n */\nfunction shouldProcessImportPath(\n importPath: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string\n): boolean {\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n\n if (targetLocale === defaultLocale) {\n // For default locale processing, check if path contains the pattern\n return importPath.includes(patternWithoutSlash);\n } else {\n // For non-default locales, check if path starts with pattern\n return importPath.includes(patternWithoutSlash);\n }\n}\n\n/**\n * Checks if an import path should be excluded based on exclusion patterns\n */\nfunction isImportPathExcluded(\n importPath: 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(importPath, pattern));\n}\n\n/**\n * Transforms import path for default locale processing\n */\nfunction transformDefaultLocaleImportPath(\n fullPath: string,\n patternHead: string,\n defaultLocale: string,\n hideDefaultLocale: boolean\n): string | null {\n if (hideDefaultLocale) {\n // Remove locale from imports that have it: '/snippets/en/file.mdx' -> '/snippets/file.mdx'\n if (fullPath.includes(`/${defaultLocale}/`)) {\n return fullPath.replace(`/${defaultLocale}/`, '/');\n } else if (fullPath.endsWith(`/${defaultLocale}`)) {\n return fullPath.replace(`/${defaultLocale}`, '');\n }\n return null; // Path doesn't have default locale\n } else {\n // Add locale to imports that don't have it: '/snippets/file.mdx' -> '/snippets/en/file.mdx'\n if (\n fullPath.includes(`/${defaultLocale}/`) ||\n fullPath.endsWith(`/${defaultLocale}`)\n ) {\n return null; // Already has default locale\n }\n\n if (fullPath.startsWith(patternHead)) {\n const pathAfterHead = fullPath.slice(patternHead.length);\n if (pathAfterHead) {\n return `${patternHead}${defaultLocale}/${pathAfterHead}`;\n } else {\n return `${patternHead.replace(/\\/$/, '')}/${defaultLocale}`;\n }\n }\n return null; // Path doesn't match pattern\n }\n}\n\n/**\n * Transforms import path for non-default locale processing with hideDefaultLocale=true\n */\nfunction transformNonDefaultLocaleImportPathWithHidden(\n fullPath: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string\n): string | null {\n // Check if already localized\n if (\n fullPath.startsWith(`${patternHead}${targetLocale}/`) ||\n fullPath === `${patternHead}${targetLocale}`\n ) {\n return null;\n }\n\n // Replace default locale with target locale\n const expectedPathWithDefaultLocale = `${patternHead}${defaultLocale}`;\n if (\n fullPath.startsWith(`${expectedPathWithDefaultLocale}/`) ||\n fullPath === expectedPathWithDefaultLocale\n ) {\n return fullPath.replace(\n `${patternHead}${defaultLocale}`,\n `${patternHead}${targetLocale}`\n );\n }\n\n // Handle exact pattern match\n if (fullPath === patternHead.replace(/\\/$/, '')) {\n return `${patternHead.replace(/\\/$/, '')}/${targetLocale}`;\n }\n\n // Add target locale to path without any locale\n const pathAfterHead = fullPath.slice(patternHead.length);\n return pathAfterHead\n ? `${patternHead}${targetLocale}/${pathAfterHead}`\n : `${patternHead}${targetLocale}`;\n}\n\n/**\n * Transforms import path for non-default locale processing with hideDefaultLocale=false\n */\nfunction transformNonDefaultLocaleImportPath(\n fullPath: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string\n): string | null {\n // If already localized to target, skip\n const expectedPathWithTarget = `${patternHead}${targetLocale}`;\n if (\n fullPath.startsWith(`${expectedPathWithTarget}/`) ||\n fullPath === expectedPathWithTarget\n ) {\n return null;\n }\n const expectedPathWithLocale = `${patternHead}${defaultLocale}`;\n\n if (\n fullPath.startsWith(`${expectedPathWithLocale}/`) ||\n fullPath === expectedPathWithLocale\n ) {\n // Replace existing default locale with target locale\n return fullPath.replace(\n `${patternHead}${defaultLocale}`,\n `${patternHead}${targetLocale}`\n );\n } else if (fullPath.startsWith(patternHead)) {\n // Add target locale to path that doesn't have any locale\n const pathAfterHead = fullPath.slice(patternHead.length);\n if (pathAfterHead) {\n return `${patternHead}${targetLocale}/${pathAfterHead}`;\n } else {\n return `${patternHead.replace(/\\/$/, '')}/${targetLocale}`;\n }\n }\n\n return null; // Path doesn't match pattern\n}\n\n/**\n * Main import path transformation function that delegates to specific scenarios\n */\nfunction transformImportPath(\n fullPath: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean,\n currentFilePath?: string,\n projectRoot: string = process.cwd(), // fallback if not provided\n rewrites?: Array<{ match: string; replace: string }>\n): string | null {\n // Apply explicit rewrites first (e.g., Docusaurus @site/docs -> @site/i18n/[locale]/...)\n if (rewrites && rewrites.length > 0) {\n const localeMap: Record<string, string> = {\n '[locale]': targetLocale,\n '[defaultLocale]': defaultLocale,\n };\n\n for (const { match, replace } of rewrites) {\n const resolvedMatch = match.replace(\n /\\[locale\\]|\\[defaultLocale\\]/g,\n (token) => localeMap[token] || token\n );\n if (fullPath.startsWith(resolvedMatch)) {\n const remainder = fullPath.slice(resolvedMatch.length);\n const resolvedReplace = replace.replace(\n /\\[locale\\]|\\[defaultLocale\\]/g,\n (token) => localeMap[token] || token\n );\n let newPath: string;\n if (resolvedReplace.endsWith('/')) {\n newPath = `${resolvedReplace}${remainder.replace(/^\\//, '')}`;\n } else if (remainder.startsWith('/')) {\n newPath = `${resolvedReplace}${remainder}`;\n } else {\n newPath = `${resolvedReplace}/${remainder}`;\n }\n return newPath;\n }\n }\n }\n\n let newPath: string | null;\n\n if (targetLocale === defaultLocale) {\n newPath = transformDefaultLocaleImportPath(\n fullPath,\n patternHead,\n defaultLocale,\n hideDefaultLocale\n );\n } else if (hideDefaultLocale) {\n newPath = transformNonDefaultLocaleImportPathWithHidden(\n fullPath,\n patternHead,\n targetLocale,\n defaultLocale\n );\n } else {\n newPath = transformNonDefaultLocaleImportPath(\n fullPath,\n patternHead,\n targetLocale,\n defaultLocale\n );\n }\n\n if (!newPath) return null;\n\n if (currentFilePath) {\n let resolvedPath: string;\n if (newPath.startsWith('/')) {\n // Interpret as project-root relative\n resolvedPath = path.join(projectRoot, newPath.replace(/^\\//, ''));\n } else {\n // Relative to current file\n const currentDir = path.dirname(currentFilePath);\n resolvedPath = path.resolve(currentDir, newPath);\n }\n\n if (!fs.existsSync(resolvedPath)) {\n return null;\n }\n }\n\n return newPath;\n}\n\n/**\n * AST-based transformation for MDX files using remark-mdx\n */\nfunction transformMdxImports(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n currentFilePath?: string,\n options?: AdditionalOptions\n): ImportTransformResult {\n const transformedImports: Array<{ originalPath: string; newPath: string }> =\n [];\n\n // Don't auto-prefix relative patterns that start with . or ..\n if (!pattern.startsWith('/') && !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 transformedImports: [],\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 transformedImports: [],\n };\n }\n }\n\n // Parse the MDX content into an AST\n let processedAst: Root;\n try {\n // Parsed only to locate import nodes; edits below are applied to the\n // original string, so a neutralized parse cannot leak into the output.\n processedAst = parseMdxTolerantly(mdxContent);\n } catch {\n return transformImportsStringFallback(\n mdxContent,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n currentFilePath,\n options\n );\n }\n\n let content = mdxContent;\n\n // Visit only mdxjsEsm nodes (import/export statements) to collect replacements\n visit(processedAst, 'mdxjsEsm', (node: MdxjsEsm) => {\n if (node.value && node.value.includes(patternHead.replace(/\\/$/, ''))) {\n // Find import lines that need transformation\n const lines = node.value.split('\\n');\n\n lines.forEach((line: string) => {\n // Only process import lines that match our pattern\n if (!line.trim().startsWith('import ')) {\n return;\n }\n\n // Check if this line should be processed\n if (\n !shouldProcessImportPath(\n line,\n patternHead,\n targetLocale,\n defaultLocale\n )\n ) {\n return;\n }\n\n // Extract the path from the import statement\n const quotes = ['\"', \"'\", '`'];\n\n for (const quote of quotes) {\n // Try both with and without trailing slash\n let startPattern = `${quote}${patternHead}`;\n let startIndex = line.indexOf(startPattern);\n\n // If pattern has trailing slash but path doesn't, try without slash\n if (startIndex === -1 && patternHead.endsWith('/')) {\n const patternWithoutSlash = patternHead.slice(0, -1);\n startPattern = `${quote}${patternWithoutSlash}`;\n startIndex = line.indexOf(startPattern);\n }\n\n if (startIndex === -1) continue;\n\n const pathStart = startIndex + 1; // After the quote\n const pathEnd = line.indexOf(quote, pathStart);\n\n if (pathEnd === -1) continue;\n\n const fullPath = line.slice(pathStart, pathEnd);\n\n // Transform the import path\n const newPath = transformImportPath(\n fullPath,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale,\n currentFilePath,\n process.cwd(),\n options?.docsImportRewrites\n );\n\n if (!newPath) {\n continue; // No transformation needed\n }\n\n // Check exclusions\n if (isImportPathExcluded(fullPath, exclude, defaultLocale)) {\n continue;\n }\n\n // Apply the transformation to the original content\n // Simply replace the import path with the new path\n content = content.replace(\n `${quote}${fullPath}${quote}`,\n `${quote}${newPath}${quote}`\n );\n transformedImports.push({ originalPath: fullPath, newPath });\n break;\n }\n });\n }\n });\n\n return {\n content,\n hasChanges: transformedImports.length > 0,\n transformedImports,\n };\n}\n\n/**\n * String-based fallback for import localization when MDX parsing fails (e.g., on .md files)\n */\nfunction transformImportsStringFallback(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n currentFilePath?: string,\n options?: AdditionalOptions\n): ImportTransformResult {\n const transformedImports: Array<{ originalPath: string; newPath: string }> =\n [];\n\n if (!pattern.startsWith('/') && !pattern.startsWith('.')) {\n pattern = '/' + pattern;\n }\n const patternHead = pattern.split('[locale]')[0];\n\n let content = mdxContent;\n const importRegex = /import\\s+[^'\"]*['\"]([^'\"]+)['\"]\\s*;?/g;\n let match: RegExpExecArray | null;\n\n while ((match = importRegex.exec(mdxContent)) !== null) {\n const fullMatch = match[0];\n const importPath = match[1];\n\n if (\n !shouldProcessImportPath(\n importPath,\n patternHead,\n targetLocale,\n defaultLocale\n )\n ) {\n continue;\n }\n\n if (isImportPathExcluded(importPath, exclude, defaultLocale)) {\n continue;\n }\n\n const newPath = transformImportPath(\n importPath,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale,\n currentFilePath,\n process.cwd(),\n options?.docsImportRewrites\n );\n\n if (!newPath) continue;\n\n const updatedImport = fullMatch.replace(importPath, newPath);\n content = content.replace(fullMatch, updatedImport);\n transformedImports.push({ originalPath: importPath, newPath });\n }\n\n return {\n content,\n hasChanges: transformedImports.length > 0,\n transformedImports,\n };\n}\n\n/**\n * AST-based transformation for MDX files only\n */\nfunction localizeStaticImportsForFile(\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 currentFilePath?: string,\n options?: AdditionalOptions\n): string {\n // For MDX files, use AST-based transformation\n const result = transformMdxImports(\n file,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n currentFilePath,\n options\n );\n return result.content;\n}\n"],"mappings":";;;;;;;;AAcA,MAAM,EAAE,YAAY;;;;;;;;;;;;;;AAiBpB,eAA8B,sBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC;CAEF,MAAM,EAAE,eAAe,gBAAgB,SAAS;CAEhD,MAAM,cAAc,kBAClB,aACA,SAAS,MAAM,kBACf,SAAS,MAAM,kBAAkB,EAAE,EACnC,SAAS,MAAM,oBAAoB,EAAE,EACrC,SAAS,SACT,SAAS,cACV;AAID,KAAI,CAAC,YAAY,SAAS,kBAAkB,CAAC,cAAc;EACzD,MAAM,qBAA+B,EAAE;AAGvC,MAAI,YAAY,GACd,oBAAmB,KAAK,GAAG,YAAY,GAAG;AAE5C,MAAI,YAAY,IACd,oBAAmB,KAAK,GAAG,YAAY,IAAI;AAG7C,MAAI,mBAAmB,SAAS,EAC9B,OAAM,aACJ,oBACA,OAAO,aAAa;AAElB,OAAI,CAACA,KAAG,WAAW,SAAS,CAC1B;GAKF,MAAM,gBAAgB,6BACpB,MAHwBA,KAAG,SAAS,SAAS,UAAU,OAAO,EAI9D,SAAS,eACT,SAAS,eACT,SAAS,SAAS,+BAA+B,OACjD,SAAS,SAAS,mBAClB,SAAS,SAAS,sBAClB,UACA,SAAS,QACV;AAED,SAAMA,KAAG,SAAS,UAAU,UAAU,cAAc;SAGvD;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AAQ,WAAW,SACtB,GAAG,QAAQ,UAAU,QACtB;AACD,uBAAmB,KAAK;KAAE,cAAc;KAAU;KAAS,CAAC;AAC5D;;IAEF;GAEJ;AAEF,QAAO;EACL;EACA,YAAY,mBAAmB,SAAS;EACxC;EACD;;;;;AAMH,SAAS,+BACP,YACA,eACA,cACA,mBACA,UAAkB,aAClB,UAAoB,EAAE,EACtB,iBACA,SACuB;CACvB,MAAM,qBACJ,EAAE;AAEJ,KAAI,CAAC,QAAQ,WAAW,IAAI,IAAI,CAAC,QAAQ,WAAW,IAAI,CACtD,WAAU,MAAM;CAElB,MAAM,cAAc,QAAQ,MAAM,WAAW,CAAC;CAE9C,IAAI,UAAU;CACd,MAAM,cAAc;CACpB,IAAI;AAEJ,SAAQ,QAAQ,YAAY,KAAK,WAAW,MAAM,MAAM;EACtD,MAAM,YAAY,MAAM;EACxB,MAAM,aAAa,MAAM;AAEzB,MACE,CAAC,wBACC,YACA,aACA,cACA,cACD,CAED;AAGF,MAAI,qBAAqB,YAAY,SAAS,cAAc,CAC1D;EAGF,MAAM,UAAU,oBACd,YACA,aACA,cACA,eACA,mBACA,iBACA,QAAQ,KAAK,EACb,SAAS,mBACV;AAED,MAAI,CAAC,QAAS;EAEd,MAAM,gBAAgB,UAAU,QAAQ,YAAY,QAAQ;AAC5D,YAAU,QAAQ,QAAQ,WAAW,cAAc;AACnD,qBAAmB,KAAK;GAAE,cAAc;GAAY;GAAS,CAAC;;AAGhE,QAAO;EACL;EACA,YAAY,mBAAmB,SAAS;EACxC;EACD;;;;;AAMH,SAAS,6BACP,MACA,eACA,cACA,mBACA,UAAkB,aAClB,UAAoB,EAAE,EACtB,iBACA,SACQ;AAYR,QAVe,oBACb,MACA,eACA,cACA,mBACA,SACA,SACA,iBACA,QAEW,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
2
  import { parseMdxForRoundTrip, restoreAnchorIds } from "./mdxAnchorSyntax.js";
3
+ import { batchProcess } from "./batchProcess.js";
3
4
  import * as fs$1 from "fs";
4
5
  import { parse } from "@babel/parser";
5
6
  import micromatch from "micromatch";
@@ -139,30 +140,22 @@ async function localizeStaticUrls(settings, targetLocales, includeFiles) {
139
140
  const urlAttributes = [...DEFAULT_URL_ATTRIBUTES, ...typeof localizeOptions === "object" && localizeOptions.attributes || []];
140
141
  const locales = targetLocales || settings.locales;
141
142
  const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths ?? {}, settings.files.transformFormats ?? {}, settings.locales, settings.defaultLocale);
142
- const processPromises = [];
143
143
  if (!fileMapping[settings.defaultLocale] && locales.includes(settings.defaultLocale) && !includeFiles) {
144
144
  const defaultLocaleFiles = [];
145
145
  if (sourceFiles.md) defaultLocaleFiles.push(...sourceFiles.md);
146
146
  if (sourceFiles.mdx) defaultLocaleFiles.push(...sourceFiles.mdx);
147
- if (defaultLocaleFiles.length > 0) {
148
- const defaultPromise = Promise.all(defaultLocaleFiles.map(async (filePath) => {
149
- if (!fs$1.existsSync(filePath)) return;
150
- const result = localizeStaticUrlsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, settings.defaultLocale, settings.options?.experimentalHideDefaultLocale || false, settings.options?.docsUrlPattern, settings.options?.excludeStaticUrls, settings.options?.baseDomain, void 0, urlAttributes);
151
- if (result.hasChanges) await fs$1.promises.writeFile(filePath, result.content);
152
- }));
153
- processPromises.push(defaultPromise);
154
- }
155
- }
156
- const mappingPromises = Object.entries(fileMapping).filter(([locale]) => locales.includes(locale)).map(async ([locale, filesMap]) => {
157
- const targetFiles = Object.values(filesMap).filter((p) => PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) && (!includeFiles || includeFiles.has(p)));
158
- await Promise.all(targetFiles.map(async (filePath) => {
147
+ if (defaultLocaleFiles.length > 0) await batchProcess(defaultLocaleFiles, async (filePath) => {
159
148
  if (!fs$1.existsSync(filePath)) return;
160
- const result = localizeStaticUrlsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, locale, settings.options?.experimentalHideDefaultLocale || false, settings.options?.docsUrlPattern, settings.options?.excludeStaticUrls, settings.options?.baseDomain, skipUntranslatedPages ? filesMap : void 0, urlAttributes);
149
+ const result = localizeStaticUrlsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, settings.defaultLocale, settings.options?.experimentalHideDefaultLocale || false, settings.options?.docsUrlPattern, settings.options?.excludeStaticUrls, settings.options?.baseDomain, void 0, urlAttributes);
161
150
  if (result.hasChanges) await fs$1.promises.writeFile(filePath, result.content);
162
- }));
163
- });
164
- processPromises.push(...mappingPromises);
165
- await Promise.all(processPromises);
151
+ }, 512);
152
+ }
153
+ const targetMappings = Object.entries(fileMapping).filter(([locale]) => locales.includes(locale));
154
+ for (const [locale, filesMap] of targetMappings) await batchProcess(Object.values(filesMap).filter((p) => PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) && (!includeFiles || includeFiles.has(p))), async (filePath) => {
155
+ if (!fs$1.existsSync(filePath)) return;
156
+ const result = localizeStaticUrlsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, locale, settings.options?.experimentalHideDefaultLocale || false, settings.options?.docsUrlPattern, settings.options?.excludeStaticUrls, settings.options?.baseDomain, skipUntranslatedPages ? filesMap : void 0, urlAttributes);
157
+ if (result.hasChanges) await fs$1.promises.writeFile(filePath, result.content);
158
+ }, 512);
166
159
  }
167
160
  /**
168
161
  * Determines if a URL should be processed based on pattern matching
@@ -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 by default. Intentionally limited\n * to link attributes (`href`) — NOT asset attributes like `src`, which usually\n * point at shared, locale-agnostic assets (e.g. `/docs/images/...`) that would\n * 404 if a locale prefix were added. Projects add their own link attributes\n * with `experimentalLocalizeStaticUrls.attributes`.\n */\nconst DEFAULT_URL_ATTRIBUTES = ['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'];\nexport const 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 */\nexport function 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 urlAttributes: string[],\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 isMatch(node.name.name, urlAttributes) &&\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 const urlAttributes = [\n ...DEFAULT_URL_ATTRIBUTES,\n ...((typeof localizeOptions === 'object' && localizeOptions.attributes) ||\n []),\n ];\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 undefined,\n urlAttributes\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 urlAttributes\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 | string[] = '/[locale]',\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: string[]\n): UrlTransformResult {\n const transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }> = [];\n\n const patternHeads = getPatternHeads(pattern);\n\n // Quick check: if the file doesn't contain any pattern, skip expensive AST parsing\n if (\n !patternHeads.some((patternHead) =>\n mdxContent.includes(patternHead.replace(/\\/$/, ''))\n )\n ) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\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 // Localize with the pattern that matches this URL\n const patternHead = findPatternHead(\n baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n ? originalUrl.substring(baseDomain.length)\n : originalUrl,\n patternHeads\n );\n if (!patternHead) {\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 (isMatch(attr.name, urlAttributes)) {\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 urlAttributes,\n isMatch(attr.name, urlAttributes)\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 urlAttributes\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 | string[] = '/[locale]', // eg /docs/[locale] or /[locale]\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: 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 urlAttributes\n );\n}\n\n/**\n * The part of each docsUrlPattern before `[locale]`, with a leading slash,\n * longest first so the most specific pattern matches a URL.\n */\nexport function getPatternHeads(pattern: string | string[]): string[] {\n return (Array.isArray(pattern) ? pattern : [pattern])\n .map((p) => (p.startsWith('/') ? p : `/${p}`).split('[locale]')[0])\n .sort((a, b) => pathSegments(b).length - pathSegments(a).length);\n}\n\n/**\n * The most specific pattern head a URL falls under. URLs are localized with\n * that pattern only, so a URL a longer pattern leaves alone (e.g. one already\n * localized) never falls through to a shorter one.\n */\nexport function findPatternHead(\n url: string,\n patternHeads: string[]\n): string | undefined {\n // Query strings and fragments are not part of the path\n const urlSegments = pathSegments(url.split(/[?#]/)[0]);\n return patternHeads.find((patternHead) =>\n checkIfPathMatchesPattern(urlSegments, pathSegments(patternHead))\n );\n}\n\nfunction pathSegments(url: string): string[] {\n return url.split('/').filter((segment) => segment !== '');\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;;;;;;;;AASpB,MAAM,yBAAyB,CAAC,OAAO;AAIvC,MAAa,kBAAkB,CAAC,QAAQ,MAAM;AAC9C,MAAa,aAAa;;;;;;AAO1B,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,SAAgB,mBACd,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,eACA,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;CAG5E,MAAM,0BAA0B,YAAiB;AAC/C,MACE,CAAC,WAGA,QAAQ,SAAS,mBAChB,QAAQ,SAAS,sBACnB,OAAO,QAAQ,UAAU,YACzB,OAAO,QAAQ,UAAU,YACzB,OAAO,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O;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';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nconst { isMatch } = micromatch;\n\n/**\n * URL-bearing JSX attributes that we localize by default. Intentionally limited\n * to link attributes (`href`) — NOT asset attributes like `src`, which usually\n * point at shared, locale-agnostic assets (e.g. `/docs/images/...`) that would\n * 404 if a locale prefix were added. Projects add their own link attributes\n * with `experimentalLocalizeStaticUrls.attributes`.\n */\nconst DEFAULT_URL_ATTRIBUTES = ['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'];\nexport const 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 */\nexport function 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 urlAttributes: string[],\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 isMatch(node.name.name, urlAttributes) &&\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 const urlAttributes = [\n ...DEFAULT_URL_ATTRIBUTES,\n ...((typeof localizeOptions === 'object' && localizeOptions.attributes) ||\n []),\n ];\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 // 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 await batchProcess(\n defaultLocaleFiles,\n 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 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 undefined,\n urlAttributes\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 FILE_IO_CONCURRENCY\n );\n }\n }\n\n // Then process all other locales from fileMapping, one locale at a time so\n // the concurrency bound covers the whole pass\n const targetMappings = Object.entries(fileMapping).filter(([locale]) =>\n locales.includes(locale)\n );\n for (const [locale, filesMap] of targetMappings) {\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 batchProcess(\n targetFiles,\n 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 urlAttributes\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 FILE_IO_CONCURRENCY\n );\n }\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 | string[] = '/[locale]',\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: string[]\n): UrlTransformResult {\n const transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }> = [];\n\n const patternHeads = getPatternHeads(pattern);\n\n // Quick check: if the file doesn't contain any pattern, skip expensive AST parsing\n if (\n !patternHeads.some((patternHead) =>\n mdxContent.includes(patternHead.replace(/\\/$/, ''))\n )\n ) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\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 // Localize with the pattern that matches this URL\n const patternHead = findPatternHead(\n baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n ? originalUrl.substring(baseDomain.length)\n : originalUrl,\n patternHeads\n );\n if (!patternHead) {\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 (isMatch(attr.name, urlAttributes)) {\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 urlAttributes,\n isMatch(attr.name, urlAttributes)\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 urlAttributes\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 | string[] = '/[locale]', // eg /docs/[locale] or /[locale]\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: 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 urlAttributes\n );\n}\n\n/**\n * The part of each docsUrlPattern before `[locale]`, with a leading slash,\n * longest first so the most specific pattern matches a URL.\n */\nexport function getPatternHeads(pattern: string | string[]): string[] {\n return (Array.isArray(pattern) ? pattern : [pattern])\n .map((p) => (p.startsWith('/') ? p : `/${p}`).split('[locale]')[0])\n .sort((a, b) => pathSegments(b).length - pathSegments(a).length);\n}\n\n/**\n * The most specific pattern head a URL falls under. URLs are localized with\n * that pattern only, so a URL a longer pattern leaves alone (e.g. one already\n * localized) never falls through to a shorter one.\n */\nexport function findPatternHead(\n url: string,\n patternHeads: string[]\n): string | undefined {\n // Query strings and fragments are not part of the path\n const urlSegments = pathSegments(url.split(/[?#]/)[0]);\n return patternHeads.find((patternHead) =>\n checkIfPathMatchesPattern(urlSegments, pathSegments(patternHead))\n );\n}\n\nfunction pathSegments(url: string): string[] {\n return url.split('/').filter((segment) => segment !== '');\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":";;;;;;;;;;;;;;AAiBA,MAAM,EAAE,YAAY;;;;;;;;AASpB,MAAM,yBAAyB,CAAC,OAAO;AAIvC,MAAa,kBAAkB,CAAC,QAAQ,MAAM;AAC9C,MAAa,aAAa;;;;;;AAO1B,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,SAAgB,mBACd,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,eACA,kBAA2B,OACnB;AACR,KAAI,CAAC,OAAO,MAAM,CAAE,QA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BACA,kBACS;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,IAC3C,KAAI,iBAAiB,OAAO,mBAAmB,GAC7C,QAAO;AAIX,QAAO"}
@@ -1,5 +1,6 @@
1
1
  import "./constants.js";
2
2
  import { createFileMapping } from "../formats/files/fileMapping.js";
3
+ import { batchProcess } from "./batchProcess.js";
3
4
  import path from "node:path";
4
5
  import fs from "node:fs";
5
6
  import fg from "fast-glob";
@@ -258,12 +259,11 @@ async function processSharedStaticAssets(settings) {
258
259
  await removeEmptyDirsUpwards(path.dirname(abs), cwd);
259
260
  }
260
261
  const resolved = settings.files?.resolvedPaths || {};
261
- const mdFiles = [...resolved.mdx || [], ...resolved.md || []];
262
- await Promise.all(mdFiles.map(async (filePath) => {
262
+ await batchProcess([...resolved.mdx || [], ...resolved.md || []], async (filePath) => {
263
263
  if (!await fs.promises.stat(filePath).then(() => true).catch(() => false)) return;
264
264
  const { content: out, changed } = rewriteMdxContent(await fs.promises.readFile(filePath, "utf8"), filePath, originalToPublic);
265
265
  if (changed) await fs.promises.writeFile(filePath, out, "utf8");
266
- }));
266
+ }, 512);
267
267
  }
268
268
  //#endregion
269
269
  export { processSharedStaticAssets as default, mirrorAssetsToLocales };
@@ -1 +1 @@
1
- {"version":3,"file":"sharedStaticAssets.js","names":[],"sources":["../../src/utils/sharedStaticAssets.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\nimport fg from 'fast-glob';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkMdx from 'remark-mdx';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkStringify from 'remark-stringify';\nimport { visit } from 'unist-util-visit';\nimport type { Literal, Root } from 'mdast';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport type { Settings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport { TEMPLATE_FILE_NAME } from './constants.js';\n\ntype MdxAssetNode = {\n type?: string;\n name?: unknown;\n attributes?: unknown;\n url?: unknown;\n};\n\ntype MdxAttribute = {\n type?: string;\n name?: string;\n value?: unknown;\n};\n\nfunction derivePublicPath(outDir: string, provided?: string): string {\n if (provided) return provided;\n const norm = outDir.replace(/\\\\/g, '/');\n if (norm.startsWith('public/')) return '/' + norm.slice('public/'.length);\n if (norm.startsWith('static/')) return '/' + norm.slice('static/'.length);\n if (norm.startsWith('/')) return norm; // already absolute URL path\n return '/' + path.basename(norm);\n}\n\nfunction toArray<T>(val: T | T[] | undefined): T[] {\n if (!val) return [];\n return Array.isArray(val) ? val : [val];\n}\n\nasync function ensureDir(dir: string) {\n await fs.promises.mkdir(dir, { recursive: true });\n}\n\nasync function moveFile(src: string, dest: string) {\n if (src === dest) return;\n try {\n await ensureDir(path.dirname(dest));\n await fs.promises.rename(src, dest);\n } catch (err: unknown) {\n const code = (err as NodeJS.ErrnoException | undefined)?.code;\n // Fallback to copy+unlink for cross-device or existing files\n if (code === 'EXDEV' || code === 'EEXIST' || code === 'ENOTEMPTY') {\n const data = await fs.promises.readFile(src);\n await ensureDir(path.dirname(dest));\n await fs.promises.writeFile(dest, data);\n try {\n await fs.promises.unlink(src);\n } catch {\n // Ignore cleanup errors for source files that were already moved.\n }\n } else if (code === 'ENOENT') {\n // already moved or missing; ignore\n return;\n } else {\n throw err;\n }\n }\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await fs.promises.stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function isDirEmpty(dir: string): Promise<boolean> {\n try {\n const entries = await fs.promises.readdir(dir);\n return entries.length === 0;\n } catch {\n return false;\n }\n}\n\nasync function removeEmptyDirsUpwards(startDir: string, stopDir: string) {\n let current = path.resolve(startDir);\n const stop = path.resolve(stopDir);\n while (current.startsWith(stop)) {\n if (current === stop) break;\n const exists = await pathExists(current);\n if (!exists) break;\n const empty = await isDirEmpty(current);\n if (!empty) break;\n try {\n await fs.promises.rmdir(current);\n } catch {\n break;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n}\n\nfunction stripQueryAndHash(url: string): { base: string; suffix: string } {\n const match = url.match(/^[^?#]+/);\n const base = match ? match[0] : url;\n const suffix = url.slice(base.length);\n return { base, suffix };\n}\n\nfunction rewriteMdxContent(\n content: string,\n filePath: string,\n pathMap: Map<string, string>\n): { content: string; changed: boolean } {\n let changed = false;\n\n let ast: Root;\n try {\n const processor = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx);\n ast = processor.runSync(processor.parse(content)) as Root;\n } catch {\n return { content, changed: false };\n }\n\n const fileDir = path.dirname(filePath);\n\n // Helper to resolve and possibly rewrite a URL\n const maybeRewrite = (url: string): string | null => {\n if (\n !url ||\n /^(https?:)?\\/\\//i.test(url) ||\n url.startsWith('data:') ||\n url.startsWith('#') ||\n url.startsWith('mailto:') ||\n url.startsWith('tel:')\n ) {\n return null;\n }\n const { base, suffix } = stripQueryAndHash(url);\n // Only handle relative paths\n if (base.startsWith('/')) return null;\n const abs = path.resolve(fileDir, base);\n const normAbs = path.normalize(abs);\n const mapped = pathMap.get(normAbs);\n if (mapped) {\n changed = true;\n return mapped + suffix;\n }\n return null;\n };\n\n visit(ast, (node) => {\n const assetNode = node as MdxAssetNode;\n // Markdown image: ![alt](url)\n if (assetNode.type === 'image' && typeof assetNode.url === 'string') {\n const newUrl = maybeRewrite(assetNode.url);\n if (newUrl) assetNode.url = newUrl;\n return;\n }\n // Markdown link: [text](url) — useful for PDFs and other downloadable assets\n if (assetNode.type === 'link' && typeof assetNode.url === 'string') {\n const newUrl = maybeRewrite(assetNode.url);\n if (newUrl) assetNode.url = newUrl;\n return;\n }\n // MDX <img src=\"...\" />\n if (\n (assetNode.type === 'mdxJsxFlowElement' ||\n assetNode.type === 'mdxJsxTextElement') &&\n Array.isArray(assetNode.attributes)\n ) {\n for (const attr of assetNode.attributes) {\n const attribute = attr as MdxAttribute;\n if (\n attribute.type === 'mdxJsxAttribute' &&\n (attribute.name === 'src' || attribute.name === 'href') &&\n typeof attribute.value === 'string'\n ) {\n const newUrl = maybeRewrite(attribute.value);\n if (newUrl) attribute.value = newUrl;\n }\n }\n }\n });\n\n try {\n const s = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n text(node: Literal) {\n return node.value;\n },\n },\n });\n const outTree = s.runSync(ast) as Root;\n let out = s.stringify(outTree);\n // Preserve trailing/leading newlines similar to localizeStaticUrls\n if (out.endsWith('\\n') && !content.endsWith('\\n')) out = out.slice(0, -1);\n if (content.startsWith('\\n') && !out.startsWith('\\n')) out = '\\n' + out;\n return { content: out, changed };\n } catch {\n return { content, changed: false };\n }\n}\n\nfunction resolveAssetPaths(include: string[], cwd: string): Set<string> {\n const assetPaths = new Set<string>();\n for (let pattern of include) {\n if (pattern.startsWith('/')) pattern = pattern.slice(1);\n const matches = fg.sync(path.resolve(cwd, pattern), { absolute: true });\n for (const m of matches) assetPaths.add(path.normalize(m));\n }\n return assetPaths;\n}\n\nexport async function mirrorAssetsToLocales(settings: Settings) {\n const cfg = settings.sharedStaticAssets;\n if (!cfg?.mirrorToLocales) return;\n if (!settings.files) return;\n\n const cwd = process.cwd();\n const include = toArray(cfg.include);\n if (include.length === 0) return;\n\n const assetPaths = resolveAssetPaths(include, cwd);\n if (assetPaths.size === 0) return;\n\n const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } =\n settings.files;\n const targetLocales = settings.locales.filter(\n (l) => l !== settings.defaultLocale\n );\n if (targetLocales.length === 0) return;\n\n const fileMapping = createFileMapping(\n resolvedPaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n targetLocales,\n settings.defaultLocale\n );\n\n for (const locale of targetLocales) {\n const filesMap = fileMapping[locale];\n if (!filesMap) continue;\n\n // Extract unique (sourceDir, targetDir) pairs from the file mapping\n const dirPairs = new Map<string, string>();\n for (const [sourcePath, targetPath] of Object.entries(filesMap)) {\n if (sourcePath === TEMPLATE_FILE_NAME) continue;\n const sourceDir = path.dirname(path.resolve(cwd, sourcePath));\n const targetDir = path.dirname(path.resolve(cwd, targetPath));\n if (sourceDir !== targetDir) {\n dirPairs.set(sourceDir, targetDir);\n }\n }\n\n if (dirPairs.size === 0) continue;\n\n // Derive ancestor directory pairs by walking up from each known pair.\n // e.g. if docs/guide → ja/docs/guide, infer docs → ja/docs.\n // Stop at cwd or when an existing pair conflicts.\n const ancestorPairs = new Map<string, string>();\n for (const [sourceDir, targetDir] of dirPairs) {\n let s = path.dirname(sourceDir);\n let t = path.dirname(targetDir);\n while (s.startsWith(cwd) && s !== cwd) {\n const existing = dirPairs.get(s) ?? ancestorPairs.get(s);\n if (existing !== undefined) {\n if (existing !== t) break; // conflict — different transforms\n } else {\n ancestorPairs.set(s, t);\n }\n s = path.dirname(s);\n t = path.dirname(t);\n }\n }\n for (const [s, t] of ancestorPairs) {\n dirPairs.set(s, t);\n }\n\n // Sort source dirs by length descending so longest prefix matches first\n const sortedPairs = [...dirPairs.entries()].sort(\n (a, b) => b[0].length - a[0].length\n );\n\n for (const assetAbs of assetPaths) {\n // Find the directory pair whose sourceDir is the longest prefix of the asset\n let bestSource: string | undefined;\n let bestTarget: string | undefined;\n for (const [sourceDir, targetDir] of sortedPairs) {\n if (\n assetAbs.startsWith(sourceDir + path.sep) ||\n assetAbs.startsWith(sourceDir + '/')\n ) {\n bestSource = sourceDir;\n bestTarget = targetDir;\n break;\n }\n }\n if (!bestSource || !bestTarget) continue;\n\n const relFromSource = path.relative(bestSource, assetAbs);\n const targetAsset = path.resolve(bestTarget, relFromSource);\n\n // Skip if target already exists with same size\n try {\n const [srcStat, dstStat] = await Promise.all([\n fs.promises.stat(assetAbs),\n fs.promises.stat(targetAsset),\n ]);\n if (dstStat.isFile() && srcStat.size === dstStat.size) continue;\n } catch {\n // target doesn't exist, proceed with copy\n }\n\n await ensureDir(path.dirname(targetAsset));\n await fs.promises.copyFile(assetAbs, targetAsset);\n }\n }\n}\n\n/**\n * If you specify in config you have blob patterns pointing to assets (jpg, png, etc.)\n * Moves static assets into a specified directory and goes thru src files and updates refrence to static assets\n * @param settings\n * @returns\n */\nexport default async function processSharedStaticAssets(settings: Settings) {\n const cfg = settings.sharedStaticAssets;\n if (!cfg) return;\n\n // mirrorToLocales is handled separately after translations are downloaded\n if (cfg.mirrorToLocales) return;\n\n const cwd = process.cwd();\n const include = toArray(cfg.include);\n if (include.length === 0) return;\n\n // Resolve assets\n const assetPaths = resolveAssetPaths(include, cwd);\n if (assetPaths.size === 0) return;\n\n if (!cfg.outDir) return;\n\n const outDirInput = cfg.outDir.startsWith('/')\n ? cfg.outDir.slice(1)\n : cfg.outDir;\n const outDirAbs = path.resolve(cwd, outDirInput);\n const publicPath = derivePublicPath(outDirInput, cfg.publicPath);\n\n // Map original absolute path -> public URL\n const originalToPublic = new Map<string, string>();\n for (const abs of assetPaths) {\n const relFromRoot = path.relative(cwd, abs).replace(/\\\\/g, '/');\n const publicUrl =\n (publicPath.endsWith('/') ? publicPath.slice(0, -1) : publicPath) +\n '/' +\n relFromRoot;\n originalToPublic.set(path.normalize(abs), publicUrl);\n }\n\n // Move assets to outDir, preserving relative structure\n for (const abs of assetPaths) {\n const relFromRoot = path.relative(cwd, abs);\n const destAbs = path.resolve(outDirAbs, relFromRoot);\n // Skip if already in destination\n if (path.normalize(abs) === path.normalize(destAbs)) continue;\n // If destination exists, assume already moved\n try {\n const st = await fs.promises.stat(destAbs).catch(() => null);\n if (st && st.isFile()) {\n // Remove source if it still exists\n await fs.promises.unlink(abs).catch(() => {\n // Ignore missing source files.\n });\n await removeEmptyDirsUpwards(path.dirname(abs), cwd);\n continue;\n }\n } catch {\n // If stat/removal fails, fall through to the normal move path.\n }\n await moveFile(abs, destAbs);\n await removeEmptyDirsUpwards(path.dirname(abs), cwd);\n }\n\n // Rewrite references in default-locale files we send for translation\n const resolved = settings.files?.resolvedPaths || {};\n const mdFiles = [...(resolved.mdx || []), ...(resolved.md || [])];\n\n await Promise.all(\n mdFiles.map(async (filePath) => {\n // only rewrite existing files\n const exists = await fs.promises\n .stat(filePath)\n .then(() => true)\n .catch(() => false);\n if (!exists) return;\n const orig = await fs.promises.readFile(filePath, 'utf8');\n const { content: out, changed } = rewriteMdxContent(\n orig,\n filePath,\n originalToPublic\n );\n if (changed) {\n await fs.promises.writeFile(filePath, out, 'utf8');\n }\n })\n );\n}\n"],"mappings":";;;;;;;;;;;;;AA4BA,SAAS,iBAAiB,QAAgB,UAA2B;AACnE,KAAI,SAAU,QAAO;CACrB,MAAM,OAAO,OAAO,QAAQ,OAAO,IAAI;AACvC,KAAI,KAAK,WAAW,UAAU,CAAE,QAAO,MAAM,KAAK,MAAM,EAAiB;AACzE,KAAI,KAAK,WAAW,UAAU,CAAE,QAAO,MAAM,KAAK,MAAM,EAAiB;AACzE,KAAI,KAAK,WAAW,IAAI,CAAE,QAAO;AACjC,QAAO,MAAM,KAAK,SAAS,KAAK;;AAGlC,SAAS,QAAW,KAA+B;AACjD,KAAI,CAAC,IAAK,QAAO,EAAE;AACnB,QAAO,MAAM,QAAQ,IAAI,GAAG,MAAM,CAAC,IAAI;;AAGzC,eAAe,UAAU,KAAa;AACpC,OAAM,GAAG,SAAS,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC;;AAGnD,eAAe,SAAS,KAAa,MAAc;AACjD,KAAI,QAAQ,KAAM;AAClB,KAAI;AACF,QAAM,UAAU,KAAK,QAAQ,KAAK,CAAC;AACnC,QAAM,GAAG,SAAS,OAAO,KAAK,KAAK;UAC5B,KAAc;EACrB,MAAM,OAAQ,KAA2C;AAEzD,MAAI,SAAS,WAAW,SAAS,YAAY,SAAS,aAAa;GACjE,MAAM,OAAO,MAAM,GAAG,SAAS,SAAS,IAAI;AAC5C,SAAM,UAAU,KAAK,QAAQ,KAAK,CAAC;AACnC,SAAM,GAAG,SAAS,UAAU,MAAM,KAAK;AACvC,OAAI;AACF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GACF,MAAM,KAAK,MAAM,GAAG,SAAS,KAAK,QAAQ,CAAC,YAAY,KAAK;AAC5D,OAAI,MAAM,GAAG,QAAQ,EAAE;AAErB,UAAM,GAAG,SAAS,OAAO,IAAI,CAAC,YAAY,GAExC;AACF,UAAM,uBAAuB,KAAK,QAAQ,IAAI,EAAE,IAAI;AACpD;;UAEI;AAGR,QAAM,SAAS,KAAK,QAAQ;AAC5B,QAAM,uBAAuB,KAAK,QAAQ,IAAI,EAAE,IAAI;;CAItD,MAAM,WAAW,SAAS,OAAO,iBAAiB,EAAE;CACpD,MAAM,UAAU,CAAC,GAAI,SAAS,OAAO,EAAE,EAAG,GAAI,SAAS,MAAM,EAAE,CAAE;AAEjE,OAAM,QAAQ,IACZ,QAAQ,IAAI,OAAO,aAAa;AAM9B,MAAI,CAAC,MAJgB,GAAG,SACrB,KAAK,SAAS,CACd,WAAW,KAAK,CAChB,YAAY,MAAM,CACR;EAEb,MAAM,EAAE,SAAS,KAAK,YAAY,kBAChC,MAFiB,GAAG,SAAS,SAAS,UAAU,OAAO,EAGvD,UACA,iBACD;AACD,MAAI,QACF,OAAM,GAAG,SAAS,UAAU,UAAU,KAAK,OAAO;GAEpD,CACH"}
1
+ {"version":3,"file":"sharedStaticAssets.js","names":[],"sources":["../../src/utils/sharedStaticAssets.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\nimport fg from 'fast-glob';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkMdx from 'remark-mdx';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkStringify from 'remark-stringify';\nimport { visit } from 'unist-util-visit';\nimport type { Literal, Root } from 'mdast';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport type { Settings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport { TEMPLATE_FILE_NAME } from './constants.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\ntype MdxAssetNode = {\n type?: string;\n name?: unknown;\n attributes?: unknown;\n url?: unknown;\n};\n\ntype MdxAttribute = {\n type?: string;\n name?: string;\n value?: unknown;\n};\n\nfunction derivePublicPath(outDir: string, provided?: string): string {\n if (provided) return provided;\n const norm = outDir.replace(/\\\\/g, '/');\n if (norm.startsWith('public/')) return '/' + norm.slice('public/'.length);\n if (norm.startsWith('static/')) return '/' + norm.slice('static/'.length);\n if (norm.startsWith('/')) return norm; // already absolute URL path\n return '/' + path.basename(norm);\n}\n\nfunction toArray<T>(val: T | T[] | undefined): T[] {\n if (!val) return [];\n return Array.isArray(val) ? val : [val];\n}\n\nasync function ensureDir(dir: string) {\n await fs.promises.mkdir(dir, { recursive: true });\n}\n\nasync function moveFile(src: string, dest: string) {\n if (src === dest) return;\n try {\n await ensureDir(path.dirname(dest));\n await fs.promises.rename(src, dest);\n } catch (err: unknown) {\n const code = (err as NodeJS.ErrnoException | undefined)?.code;\n // Fallback to copy+unlink for cross-device or existing files\n if (code === 'EXDEV' || code === 'EEXIST' || code === 'ENOTEMPTY') {\n const data = await fs.promises.readFile(src);\n await ensureDir(path.dirname(dest));\n await fs.promises.writeFile(dest, data);\n try {\n await fs.promises.unlink(src);\n } catch {\n // Ignore cleanup errors for source files that were already moved.\n }\n } else if (code === 'ENOENT') {\n // already moved or missing; ignore\n return;\n } else {\n throw err;\n }\n }\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await fs.promises.stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function isDirEmpty(dir: string): Promise<boolean> {\n try {\n const entries = await fs.promises.readdir(dir);\n return entries.length === 0;\n } catch {\n return false;\n }\n}\n\nasync function removeEmptyDirsUpwards(startDir: string, stopDir: string) {\n let current = path.resolve(startDir);\n const stop = path.resolve(stopDir);\n while (current.startsWith(stop)) {\n if (current === stop) break;\n const exists = await pathExists(current);\n if (!exists) break;\n const empty = await isDirEmpty(current);\n if (!empty) break;\n try {\n await fs.promises.rmdir(current);\n } catch {\n break;\n }\n const parent = path.dirname(current);\n if (parent === current) break;\n current = parent;\n }\n}\n\nfunction stripQueryAndHash(url: string): { base: string; suffix: string } {\n const match = url.match(/^[^?#]+/);\n const base = match ? match[0] : url;\n const suffix = url.slice(base.length);\n return { base, suffix };\n}\n\nfunction rewriteMdxContent(\n content: string,\n filePath: string,\n pathMap: Map<string, string>\n): { content: string; changed: boolean } {\n let changed = false;\n\n let ast: Root;\n try {\n const processor = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx);\n ast = processor.runSync(processor.parse(content)) as Root;\n } catch {\n return { content, changed: false };\n }\n\n const fileDir = path.dirname(filePath);\n\n // Helper to resolve and possibly rewrite a URL\n const maybeRewrite = (url: string): string | null => {\n if (\n !url ||\n /^(https?:)?\\/\\//i.test(url) ||\n url.startsWith('data:') ||\n url.startsWith('#') ||\n url.startsWith('mailto:') ||\n url.startsWith('tel:')\n ) {\n return null;\n }\n const { base, suffix } = stripQueryAndHash(url);\n // Only handle relative paths\n if (base.startsWith('/')) return null;\n const abs = path.resolve(fileDir, base);\n const normAbs = path.normalize(abs);\n const mapped = pathMap.get(normAbs);\n if (mapped) {\n changed = true;\n return mapped + suffix;\n }\n return null;\n };\n\n visit(ast, (node) => {\n const assetNode = node as MdxAssetNode;\n // Markdown image: ![alt](url)\n if (assetNode.type === 'image' && typeof assetNode.url === 'string') {\n const newUrl = maybeRewrite(assetNode.url);\n if (newUrl) assetNode.url = newUrl;\n return;\n }\n // Markdown link: [text](url) — useful for PDFs and other downloadable assets\n if (assetNode.type === 'link' && typeof assetNode.url === 'string') {\n const newUrl = maybeRewrite(assetNode.url);\n if (newUrl) assetNode.url = newUrl;\n return;\n }\n // MDX <img src=\"...\" />\n if (\n (assetNode.type === 'mdxJsxFlowElement' ||\n assetNode.type === 'mdxJsxTextElement') &&\n Array.isArray(assetNode.attributes)\n ) {\n for (const attr of assetNode.attributes) {\n const attribute = attr as MdxAttribute;\n if (\n attribute.type === 'mdxJsxAttribute' &&\n (attribute.name === 'src' || attribute.name === 'href') &&\n typeof attribute.value === 'string'\n ) {\n const newUrl = maybeRewrite(attribute.value);\n if (newUrl) attribute.value = newUrl;\n }\n }\n }\n });\n\n try {\n const s = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n text(node: Literal) {\n return node.value;\n },\n },\n });\n const outTree = s.runSync(ast) as Root;\n let out = s.stringify(outTree);\n // Preserve trailing/leading newlines similar to localizeStaticUrls\n if (out.endsWith('\\n') && !content.endsWith('\\n')) out = out.slice(0, -1);\n if (content.startsWith('\\n') && !out.startsWith('\\n')) out = '\\n' + out;\n return { content: out, changed };\n } catch {\n return { content, changed: false };\n }\n}\n\nfunction resolveAssetPaths(include: string[], cwd: string): Set<string> {\n const assetPaths = new Set<string>();\n for (let pattern of include) {\n if (pattern.startsWith('/')) pattern = pattern.slice(1);\n const matches = fg.sync(path.resolve(cwd, pattern), { absolute: true });\n for (const m of matches) assetPaths.add(path.normalize(m));\n }\n return assetPaths;\n}\n\nexport async function mirrorAssetsToLocales(settings: Settings) {\n const cfg = settings.sharedStaticAssets;\n if (!cfg?.mirrorToLocales) return;\n if (!settings.files) return;\n\n const cwd = process.cwd();\n const include = toArray(cfg.include);\n if (include.length === 0) return;\n\n const assetPaths = resolveAssetPaths(include, cwd);\n if (assetPaths.size === 0) return;\n\n const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } =\n settings.files;\n const targetLocales = settings.locales.filter(\n (l) => l !== settings.defaultLocale\n );\n if (targetLocales.length === 0) return;\n\n const fileMapping = createFileMapping(\n resolvedPaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n targetLocales,\n settings.defaultLocale\n );\n\n for (const locale of targetLocales) {\n const filesMap = fileMapping[locale];\n if (!filesMap) continue;\n\n // Extract unique (sourceDir, targetDir) pairs from the file mapping\n const dirPairs = new Map<string, string>();\n for (const [sourcePath, targetPath] of Object.entries(filesMap)) {\n if (sourcePath === TEMPLATE_FILE_NAME) continue;\n const sourceDir = path.dirname(path.resolve(cwd, sourcePath));\n const targetDir = path.dirname(path.resolve(cwd, targetPath));\n if (sourceDir !== targetDir) {\n dirPairs.set(sourceDir, targetDir);\n }\n }\n\n if (dirPairs.size === 0) continue;\n\n // Derive ancestor directory pairs by walking up from each known pair.\n // e.g. if docs/guide → ja/docs/guide, infer docs → ja/docs.\n // Stop at cwd or when an existing pair conflicts.\n const ancestorPairs = new Map<string, string>();\n for (const [sourceDir, targetDir] of dirPairs) {\n let s = path.dirname(sourceDir);\n let t = path.dirname(targetDir);\n while (s.startsWith(cwd) && s !== cwd) {\n const existing = dirPairs.get(s) ?? ancestorPairs.get(s);\n if (existing !== undefined) {\n if (existing !== t) break; // conflict — different transforms\n } else {\n ancestorPairs.set(s, t);\n }\n s = path.dirname(s);\n t = path.dirname(t);\n }\n }\n for (const [s, t] of ancestorPairs) {\n dirPairs.set(s, t);\n }\n\n // Sort source dirs by length descending so longest prefix matches first\n const sortedPairs = [...dirPairs.entries()].sort(\n (a, b) => b[0].length - a[0].length\n );\n\n for (const assetAbs of assetPaths) {\n // Find the directory pair whose sourceDir is the longest prefix of the asset\n let bestSource: string | undefined;\n let bestTarget: string | undefined;\n for (const [sourceDir, targetDir] of sortedPairs) {\n if (\n assetAbs.startsWith(sourceDir + path.sep) ||\n assetAbs.startsWith(sourceDir + '/')\n ) {\n bestSource = sourceDir;\n bestTarget = targetDir;\n break;\n }\n }\n if (!bestSource || !bestTarget) continue;\n\n const relFromSource = path.relative(bestSource, assetAbs);\n const targetAsset = path.resolve(bestTarget, relFromSource);\n\n // Skip if target already exists with same size\n try {\n const [srcStat, dstStat] = await Promise.all([\n fs.promises.stat(assetAbs),\n fs.promises.stat(targetAsset),\n ]);\n if (dstStat.isFile() && srcStat.size === dstStat.size) continue;\n } catch {\n // target doesn't exist, proceed with copy\n }\n\n await ensureDir(path.dirname(targetAsset));\n await fs.promises.copyFile(assetAbs, targetAsset);\n }\n }\n}\n\n/**\n * If you specify in config you have blob patterns pointing to assets (jpg, png, etc.)\n * Moves static assets into a specified directory and goes thru src files and updates refrence to static assets\n * @param settings\n * @returns\n */\nexport default async function processSharedStaticAssets(settings: Settings) {\n const cfg = settings.sharedStaticAssets;\n if (!cfg) return;\n\n // mirrorToLocales is handled separately after translations are downloaded\n if (cfg.mirrorToLocales) return;\n\n const cwd = process.cwd();\n const include = toArray(cfg.include);\n if (include.length === 0) return;\n\n // Resolve assets\n const assetPaths = resolveAssetPaths(include, cwd);\n if (assetPaths.size === 0) return;\n\n if (!cfg.outDir) return;\n\n const outDirInput = cfg.outDir.startsWith('/')\n ? cfg.outDir.slice(1)\n : cfg.outDir;\n const outDirAbs = path.resolve(cwd, outDirInput);\n const publicPath = derivePublicPath(outDirInput, cfg.publicPath);\n\n // Map original absolute path -> public URL\n const originalToPublic = new Map<string, string>();\n for (const abs of assetPaths) {\n const relFromRoot = path.relative(cwd, abs).replace(/\\\\/g, '/');\n const publicUrl =\n (publicPath.endsWith('/') ? publicPath.slice(0, -1) : publicPath) +\n '/' +\n relFromRoot;\n originalToPublic.set(path.normalize(abs), publicUrl);\n }\n\n // Move assets to outDir, preserving relative structure\n for (const abs of assetPaths) {\n const relFromRoot = path.relative(cwd, abs);\n const destAbs = path.resolve(outDirAbs, relFromRoot);\n // Skip if already in destination\n if (path.normalize(abs) === path.normalize(destAbs)) continue;\n // If destination exists, assume already moved\n try {\n const st = await fs.promises.stat(destAbs).catch(() => null);\n if (st && st.isFile()) {\n // Remove source if it still exists\n await fs.promises.unlink(abs).catch(() => {\n // Ignore missing source files.\n });\n await removeEmptyDirsUpwards(path.dirname(abs), cwd);\n continue;\n }\n } catch {\n // If stat/removal fails, fall through to the normal move path.\n }\n await moveFile(abs, destAbs);\n await removeEmptyDirsUpwards(path.dirname(abs), cwd);\n }\n\n // Rewrite references in default-locale files we send for translation\n const resolved = settings.files?.resolvedPaths || {};\n const mdFiles = [...(resolved.mdx || []), ...(resolved.md || [])];\n\n await batchProcess(\n mdFiles,\n async (filePath) => {\n // only rewrite existing files\n const exists = await fs.promises\n .stat(filePath)\n .then(() => true)\n .catch(() => false);\n if (!exists) return;\n const orig = await fs.promises.readFile(filePath, 'utf8');\n const { content: out, changed } = rewriteMdxContent(\n orig,\n filePath,\n originalToPublic\n );\n if (changed) {\n await fs.promises.writeFile(filePath, out, 'utf8');\n }\n },\n FILE_IO_CONCURRENCY\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AA6BA,SAAS,iBAAiB,QAAgB,UAA2B;AACnE,KAAI,SAAU,QAAO;CACrB,MAAM,OAAO,OAAO,QAAQ,OAAO,IAAI;AACvC,KAAI,KAAK,WAAW,UAAU,CAAE,QAAO,MAAM,KAAK,MAAM,EAAiB;AACzE,KAAI,KAAK,WAAW,UAAU,CAAE,QAAO,MAAM,KAAK,MAAM,EAAiB;AACzE,KAAI,KAAK,WAAW,IAAI,CAAE,QAAO;AACjC,QAAO,MAAM,KAAK,SAAS,KAAK;;AAGlC,SAAS,QAAW,KAA+B;AACjD,KAAI,CAAC,IAAK,QAAO,EAAE;AACnB,QAAO,MAAM,QAAQ,IAAI,GAAG,MAAM,CAAC,IAAI;;AAGzC,eAAe,UAAU,KAAa;AACpC,OAAM,GAAG,SAAS,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC;;AAGnD,eAAe,SAAS,KAAa,MAAc;AACjD,KAAI,QAAQ,KAAM;AAClB,KAAI;AACF,QAAM,UAAU,KAAK,QAAQ,KAAK,CAAC;AACnC,QAAM,GAAG,SAAS,OAAO,KAAK,KAAK;UAC5B,KAAc;EACrB,MAAM,OAAQ,KAA2C;AAEzD,MAAI,SAAS,WAAW,SAAS,YAAY,SAAS,aAAa;GACjE,MAAM,OAAO,MAAM,GAAG,SAAS,SAAS,IAAI;AAC5C,SAAM,UAAU,KAAK,QAAQ,KAAK,CAAC;AACnC,SAAM,GAAG,SAAS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AK,UAAU,QAAQ,CAAE;AAErD,MAAI;GACF,MAAM,KAAK,MAAM,GAAG,SAAS,KAAK,QAAQ,CAAC,YAAY,KAAK;AAC5D,OAAI,MAAM,GAAG,QAAQ,EAAE;AAErB,UAAM,GAAG,SAAS,OAAO,IAAI,CAAC,YAAY,GAExC;AACF,UAAM,uBAAuB,KAAK,QAAQ,IAAI,EAAE,IAAI;AACpD;;UAEI;AAGR,QAAM,SAAS,KAAK,QAAQ;AAC5B,QAAM,uBAAuB,KAAK,QAAQ,IAAI,EAAE,IAAI;;CAItD,MAAM,WAAW,SAAS,OAAO,iBAAiB,EAAE;AAGpD,OAAM,aACJ,CAHe,GAAI,SAAS,OAAO,EAAE,EAAG,GAAI,SAAS,MAAM,EAAE,CAGtD,EACP,OAAO,aAAa;AAMlB,MAAI,CAAC,MAJgB,GAAG,SACrB,KAAK,SAAS,CACd,WAAW,KAAK,CAChB,YAAY,MAAM,CACR;EAEb,MAAM,EAAE,SAAS,KAAK,YAAY,kBAChC,MAFiB,GAAG,SAAS,SAAS,UAAU,OAAO,EAGvD,UACA,iBACD;AACD,MAAI,QACF,OAAM,GAAG,SAAS,UAAU,UAAU,KAAK,OAAO;QAIvD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gt",
3
- "version": "2.26.8",
3
+ "version": "2.26.9",
4
4
  "main": "dist/index.js",
5
5
  "bin": "bin/main.js",
6
6
  "files": [
@@ -117,10 +117,10 @@
117
117
  "yaml": "^2.8.0",
118
118
  "@generaltranslation/format": "0.1.9",
119
119
  "@generaltranslation/icu": "0.1.2",
120
- "@generaltranslation/python-extractor": "0.2.62",
121
- "@generaltranslation/supported-locales": "2.1.43",
122
- "@generaltranslation/vue-extractor": "0.1.21",
123
- "generaltranslation": "9.5.7",
120
+ "@generaltranslation/python-extractor": "0.2.63",
121
+ "@generaltranslation/supported-locales": "2.1.44",
122
+ "@generaltranslation/vue-extractor": "0.1.22",
123
+ "generaltranslation": "9.5.8",
124
124
  "gt-remark": "1.0.12"
125
125
  },
126
126
  "devDependencies": {