gt 2.28.7 → 2.29.0

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,22 @@
1
1
  # gtx-cli
2
2
 
3
+ ## 2.29.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#3145](https://github.com/generaltranslation/gt/pull/3145) [`bca6cde`](https://github.com/generaltranslation/gt/commit/bca6cde376fd8b27df9f97d19c6c79a31548dcd0) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - `experimentalLocalizeStaticUrls` now points image references in translated md/mdx files at the translated image. A root-relative URL of an image configured under an image `files` key is rewritten to the locale's translated file when that file exists, and left on the source image otherwise.
8
+
9
+ ## 2.28.8
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [[`1629092`](https://github.com/generaltranslation/gt/commit/16290925bb73460be5c05cfb5a7ba79d9b6eb60f)]:
14
+ - @generaltranslation/format@0.1.13
15
+ - @generaltranslation/python-extractor@0.2.70
16
+ - generaltranslation@9.5.15
17
+ - @generaltranslation/vue-extractor@0.1.29
18
+ - @generaltranslation/supported-locales@2.1.51
19
+
3
20
  ## 2.28.7
4
21
 
5
22
  ### Patch Changes
@@ -1,6 +1,8 @@
1
1
  export declare const SUPPORTED_FILE_EXTENSIONS: readonly ["json", "pot", "mdx", "md", "ts", "js", "yaml", "html", "txt", "twilioContentJson", "lottie", "dotStrings", "dotStringsdict", "androidStrings", "xcstrings", "srt", "resx", "png", "jpeg", "webp", "tiff", "bmp", "avif", "heic"];
2
2
  /** The file types uploaded as image bytes and translated by the image translation agent. */
3
3
  export declare const IMAGE_FILE_TYPES: readonly ["png", "jpeg", "webp", "tiff", "bmp", "avif", "heic"];
4
+ /** The file types served at their own path, so a root-relative URL to one is its file path. */
5
+ export declare const STATIC_ASSET_FILE_TYPES: readonly ["png", "jpeg", "webp", "tiff", "bmp", "avif", "heic"];
4
6
  /** The formats setup offers: an intentional subset of the supported ones. */
5
7
  export declare const SETUP_FILE_FORMATS: readonly ["json", "md", "mdx", "ts", "js", "yaml"];
6
8
  export type SetupFileFormat = (typeof SETUP_FILE_FORMATS)[number];
@@ -35,6 +35,8 @@ const IMAGE_FILE_TYPES = [
35
35
  "avif",
36
36
  "heic"
37
37
  ];
38
+ /** The file types served at their own path, so a root-relative URL to one is its file path. */
39
+ const STATIC_ASSET_FILE_TYPES = [...IMAGE_FILE_TYPES];
38
40
  /** The formats setup offers: an intentional subset of the supported ones. */
39
41
  const SETUP_FILE_FORMATS = [
40
42
  "json",
@@ -71,6 +73,6 @@ const FILE_EXT_TO_EXT_LABEL = {
71
73
  heic: "HEIC images"
72
74
  };
73
75
  //#endregion
74
- export { FILE_EXT_TO_EXT_LABEL, IMAGE_FILE_TYPES, SETUP_FILE_FORMATS, SUPPORTED_FILE_EXTENSIONS };
76
+ export { FILE_EXT_TO_EXT_LABEL, IMAGE_FILE_TYPES, SETUP_FILE_FORMATS, STATIC_ASSET_FILE_TYPES, SUPPORTED_FILE_EXTENSIONS };
75
77
 
76
78
  //# sourceMappingURL=supportedFiles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"supportedFiles.js","names":[],"sources":["../../../src/formats/files/supportedFiles.ts"],"sourcesContent":["export const SUPPORTED_FILE_EXTENSIONS = [\n 'json',\n 'pot',\n 'mdx',\n 'md',\n 'ts',\n 'js',\n 'yaml',\n 'html',\n 'txt',\n 'twilioContentJson',\n 'lottie',\n 'dotStrings',\n 'dotStringsdict',\n 'androidStrings',\n 'xcstrings',\n 'srt',\n 'resx',\n 'png',\n 'jpeg',\n 'webp',\n 'tiff',\n 'bmp',\n 'avif',\n 'heic',\n] as const;\n\n/** The file types uploaded as image bytes and translated by the image translation agent. */\nexport const IMAGE_FILE_TYPES = [\n 'png',\n 'jpeg',\n 'webp',\n 'tiff',\n 'bmp',\n 'avif',\n 'heic',\n] as const satisfies readonly (typeof SUPPORTED_FILE_EXTENSIONS)[number][];\n\n/** The formats setup offers: an intentional subset of the supported ones. */\nexport const SETUP_FILE_FORMATS = [\n 'json',\n 'md',\n 'mdx',\n 'ts',\n 'js',\n 'yaml',\n] as const satisfies readonly (typeof SUPPORTED_FILE_EXTENSIONS)[number][];\nexport type SetupFileFormat = (typeof SETUP_FILE_FORMATS)[number];\n\nexport const FILE_EXT_TO_EXT_LABEL = {\n json: 'JSON',\n pot: 'POT',\n mdx: 'MDX',\n md: 'Markdown',\n ts: 'TypeScript',\n js: 'JavaScript',\n yaml: 'YAML',\n html: 'HTML',\n txt: 'Text',\n twilioContentJson: 'Twilio Content JSON',\n lottie: 'Lottie',\n dotStrings: '.strings',\n dotStringsdict: '.stringsdict',\n androidStrings: 'Android strings.xml',\n xcstrings: '.xcstrings',\n srt: 'SubRip subtitles (.srt)',\n resx: '.NET resources (.resx)',\n png: 'PNG images',\n jpeg: 'JPEG images',\n webp: 'WebP images',\n tiff: 'TIFF images',\n bmp: 'BMP images',\n avif: 'AVIF images',\n heic: 'HEIC images',\n};\n"],"mappings":";AAAA,MAAa,4BAA4B;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;AAGD,MAAa,mBAAmB;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;AAGD,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACD;AAGD,MAAa,wBAAwB;CACnC,MAAM;CACN,KAAK;CACL,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,KAAK;CACL,mBAAmB;CACnB,QAAQ;CACR,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,WAAW;CACX,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;CACN,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;CACP"}
1
+ {"version":3,"file":"supportedFiles.js","names":[],"sources":["../../../src/formats/files/supportedFiles.ts"],"sourcesContent":["export const SUPPORTED_FILE_EXTENSIONS = [\n 'json',\n 'pot',\n 'mdx',\n 'md',\n 'ts',\n 'js',\n 'yaml',\n 'html',\n 'txt',\n 'twilioContentJson',\n 'lottie',\n 'dotStrings',\n 'dotStringsdict',\n 'androidStrings',\n 'xcstrings',\n 'srt',\n 'resx',\n 'png',\n 'jpeg',\n 'webp',\n 'tiff',\n 'bmp',\n 'avif',\n 'heic',\n] as const;\n\n/** The file types uploaded as image bytes and translated by the image translation agent. */\nexport const IMAGE_FILE_TYPES = [\n 'png',\n 'jpeg',\n 'webp',\n 'tiff',\n 'bmp',\n 'avif',\n 'heic',\n] as const satisfies readonly (typeof SUPPORTED_FILE_EXTENSIONS)[number][];\n\n/** The file types served at their own path, so a root-relative URL to one is its file path. */\nexport const STATIC_ASSET_FILE_TYPES = [\n ...IMAGE_FILE_TYPES,\n] as const satisfies readonly (typeof SUPPORTED_FILE_EXTENSIONS)[number][];\n\n/** The formats setup offers: an intentional subset of the supported ones. */\nexport const SETUP_FILE_FORMATS = [\n 'json',\n 'md',\n 'mdx',\n 'ts',\n 'js',\n 'yaml',\n] as const satisfies readonly (typeof SUPPORTED_FILE_EXTENSIONS)[number][];\nexport type SetupFileFormat = (typeof SETUP_FILE_FORMATS)[number];\n\nexport const FILE_EXT_TO_EXT_LABEL = {\n json: 'JSON',\n pot: 'POT',\n mdx: 'MDX',\n md: 'Markdown',\n ts: 'TypeScript',\n js: 'JavaScript',\n yaml: 'YAML',\n html: 'HTML',\n txt: 'Text',\n twilioContentJson: 'Twilio Content JSON',\n lottie: 'Lottie',\n dotStrings: '.strings',\n dotStringsdict: '.stringsdict',\n androidStrings: 'Android strings.xml',\n xcstrings: '.xcstrings',\n srt: 'SubRip subtitles (.srt)',\n resx: '.NET resources (.resx)',\n png: 'PNG images',\n jpeg: 'JPEG images',\n webp: 'WebP images',\n tiff: 'TIFF images',\n bmp: 'BMP images',\n avif: 'AVIF images',\n heic: 'HEIC images',\n};\n"],"mappings":";AAAA,MAAa,4BAA4B;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;AAGD,MAAa,mBAAmB;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;AAGD,MAAa,0BAA0B,CACrC,GAAG,iBACJ;;AAGD,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACD;AAGD,MAAa,wBAAwB;CACnC,MAAM;CACN,KAAK;CACL,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,KAAK;CACL,mBAAmB;CACnB,QAAQ;CACR,YAAY;CACZ,gBAAgB;CAChB,gBAAgB;CAChB,WAAW;CACX,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;CACN,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;CACP"}
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.28.7";
1
+ export declare const PACKAGE_VERSION = "2.29.0";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.28.7";
2
+ const PACKAGE_VERSION = "2.29.0";
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.28.7';\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.29.0';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -1,10 +1,13 @@
1
+ import { STATIC_ASSET_FILE_TYPES } from "../formats/files/supportedFiles.js";
1
2
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
3
  import { parseMdxForRoundTrip, restoreAnchorIds } from "./mdxAnchorSyntax.js";
3
4
  import { batchProcess } from "./batchProcess.js";
4
5
  import * as fs$1 from "fs";
5
6
  import micromatch from "micromatch";
6
7
  import { parse } from "@babel/parser";
8
+ import traverseModule from "@babel/traverse";
7
9
  import * as path$1 from "path";
10
+ import YAML, { isScalar } from "yaml";
8
11
  import { unified } from "unified";
9
12
  import remarkMdx from "remark-mdx";
10
13
  import remarkFrontmatter from "remark-frontmatter";
@@ -13,6 +16,7 @@ import remarkStringify from "remark-stringify";
13
16
  import { escapeHtmlInTextNodes, normalizeCJKCharacters } from "gt-remark";
14
17
  //#region src/utils/localizeStaticUrls.ts
15
18
  const { isMatch } = micromatch;
19
+ const traverse = traverseModule.default || traverseModule;
16
20
  /**
17
21
  * URL-bearing JSX attributes that we localize by default. Intentionally limited
18
22
  * to link attributes (`href`) — NOT asset attributes like `src`, which usually
@@ -43,6 +47,77 @@ function translationMissing(url, localizedUrl, localizedFiles) {
43
47
  const mappedPage = localizedFiles[sourcePage];
44
48
  return !(mappedPage && fs$1.existsSync(mappedPage)) && !findPage(localizedUrl);
45
49
  }
50
+ function toRootRelativeUrl(filePath) {
51
+ return "/" + path$1.relative(process.cwd(), filePath).split(path$1.sep).join("/");
52
+ }
53
+ function decodeUrlPath(urlPath) {
54
+ try {
55
+ return urlPath.split("/").map(decodeURIComponent).join("/");
56
+ } catch {
57
+ return urlPath;
58
+ }
59
+ }
60
+ function percentEncode(char) {
61
+ return `%${char.charCodeAt(0).toString(16).toUpperCase()}`;
62
+ }
63
+ function encodeUrlPath(urlPath) {
64
+ return urlPath.split("/").map((segment) => encodeURIComponent(segment).replace(/['()]/g, percentEncode)).join("/");
65
+ }
66
+ /**
67
+ * Maps root-relative URLs of static assets configured for translation to the
68
+ * URL of the locale's translated file, wherever the file mapping puts it.
69
+ */
70
+ function createAssetLocalizer(sourceFiles, filesMap) {
71
+ const translatedFiles = /* @__PURE__ */ new Map();
72
+ const translatedUrls = /* @__PURE__ */ new Set();
73
+ for (const fileType of STATIC_ASSET_FILE_TYPES) for (const source of sourceFiles[fileType] ?? []) {
74
+ const translatedFile = filesMap[path$1.relative(process.cwd(), source)] ?? filesMap[source];
75
+ if (translatedFile) {
76
+ translatedFiles.set(toRootRelativeUrl(source), translatedFile);
77
+ translatedUrls.add(toRootRelativeUrl(translatedFile));
78
+ }
79
+ }
80
+ if (translatedFiles.size === 0) return void 0;
81
+ return (url) => {
82
+ if (!url.startsWith("/")) return void 0;
83
+ const urlPath = url.split(/[?#]/)[0];
84
+ const decodedPath = decodeUrlPath(urlPath);
85
+ const translatedFile = translatedFiles.get(decodedPath);
86
+ if (translatedFile === void 0) return translatedUrls.has(decodedPath) ? null : void 0;
87
+ if (!fs$1.existsSync(translatedFile)) return null;
88
+ const translatedUrl = toRootRelativeUrl(translatedFile);
89
+ if (translatedUrl === decodedPath) return null;
90
+ return (decodedPath === urlPath ? translatedUrl.replace(/['"]/g, percentEncode) : encodeUrlPath(translatedUrl)) + url.slice(urlPath.length);
91
+ };
92
+ }
93
+ /**
94
+ * Localizes frontmatter values that are asset URLs, such as `og:image`,
95
+ * replacing only the value's own characters so the YAML keeps its formatting.
96
+ */
97
+ function localizeFrontmatterAssetUrls(frontmatter, transformUrl) {
98
+ const doc = YAML.parseDocument(frontmatter, { prettyErrors: false });
99
+ if (doc.errors.length) return frontmatter;
100
+ const replacements = [];
101
+ YAML.visit(doc, { Scalar(key, node) {
102
+ if (key === "key" || !isScalar(node) || !node.range) return;
103
+ if (typeof node.value !== "string") return;
104
+ const [start, end] = node.range;
105
+ const raw = frontmatter.slice(start, end);
106
+ if (!raw.includes(node.value)) return;
107
+ const newUrl = transformUrl(node.value, "asset");
108
+ if (!newUrl) return;
109
+ replacements.push({
110
+ start,
111
+ end,
112
+ text: raw.replace(node.value, newUrl)
113
+ });
114
+ } });
115
+ let result = frontmatter;
116
+ replacements.sort((a, b) => b.start - a.start).forEach(({ start, end, text }) => {
117
+ result = result.slice(0, start) + text + result.slice(end);
118
+ });
119
+ return result;
120
+ }
46
121
  /**
47
122
  * Localize URL string literals that live inside an MDX expression's raw source.
48
123
  *
@@ -61,57 +136,65 @@ function translationMissing(url, localizedUrl, localizedFiles) {
61
136
  * Only static string literals are localized; dynamically-computed URLs
62
137
  * (template literals, identifiers, concatenation) are left untouched — a
63
138
  * fundamental limit of static localization, not a parser shortcoming.
139
+ *
140
+ * Every other string literal is offered as an `asset`, so an asset URL is
141
+ * localized whichever attribute or data structure holds it.
64
142
  */
65
143
  function localizeUrlsInExpressionSource(source, transformUrl, urlAttributes, rootStringIsUrl = false) {
66
144
  if (!source.trim()) return source;
145
+ const parse$1 = (code) => parse(code, {
146
+ sourceType: "module",
147
+ errorRecovery: true,
148
+ plugins: ["jsx", "typescript"]
149
+ });
67
150
  let ast;
151
+ let offset = 1;
68
152
  try {
69
- ast = parse(source, {
70
- sourceType: "module",
71
- errorRecovery: true,
72
- plugins: ["jsx", "typescript"]
73
- });
153
+ ast = parse$1(`(${source}\n)`);
154
+ if (ast.errors?.length) throw new Error("Not a single expression");
74
155
  } catch {
75
- return source;
156
+ offset = 0;
157
+ try {
158
+ ast = parse$1(source);
159
+ } catch {
160
+ return source;
161
+ }
76
162
  }
77
163
  const replacements = [];
78
- const pushLiteralReplacement = (literal) => {
79
- if (!literal || literal.type !== "StringLiteral" && literal.type !== "DirectiveLiteral" || typeof literal.value !== "string" || typeof literal.start !== "number" || typeof literal.end !== "number") return;
80
- const newUrl = transformUrl(literal.value, "href");
164
+ const visitedLiterals = /* @__PURE__ */ new Set();
165
+ const jsxAttributeStrings = /* @__PURE__ */ new Set();
166
+ const pushLiteralReplacement = (literal, position = "href") => {
167
+ if (!literal || literal.type !== "StringLiteral" && literal.type !== "DirectiveLiteral" || typeof literal.start !== "number" || typeof literal.end !== "number") return;
168
+ if (visitedLiterals.has(literal.start)) return;
169
+ visitedLiterals.add(literal.start);
170
+ const newUrl = transformUrl(literal.value, position);
81
171
  if (!newUrl) return;
82
- const quote = source[literal.start] === "'" ? "'" : "\"";
172
+ const quote = source[literal.start - offset] === "'" ? "'" : "\"";
173
+ const isUnescaped = literal.type === "StringLiteral" && !jsxAttributeStrings.has(literal);
83
174
  replacements.push({
84
- start: literal.start,
85
- end: literal.end,
86
- text: `${quote}${newUrl}${quote}`
175
+ start: literal.start - offset,
176
+ end: literal.end - offset,
177
+ text: isUnescaped ? JSON.stringify(newUrl) : `${quote}${newUrl}${quote}`
87
178
  });
88
179
  };
89
180
  if (rootStringIsUrl) {
90
- const program = ast.program;
91
- const body = program?.body ?? [];
92
- if (body.length === 1 && body[0]?.type === "ExpressionStatement") pushLiteralReplacement(body[0].expression);
93
- else if (body.length === 0 && program?.directives?.length === 1) pushLiteralReplacement(program.directives[0]?.value);
181
+ const { body, directives } = ast.program;
182
+ if (body.length === 1 && body[0].type === "ExpressionStatement") pushLiteralReplacement(body[0].expression);
183
+ else if (body.length === 0 && directives.length === 1) pushLiteralReplacement(directives[0].value);
94
184
  }
95
- const seen = /* @__PURE__ */ new Set();
96
- const walk = (node) => {
97
- if (!node || typeof node !== "object") return;
98
- if (Array.isArray(node)) {
99
- for (const item of node) walk(item);
100
- return;
101
- }
102
- if (seen.has(node)) return;
103
- seen.add(node);
104
- if (node.type === "JSXAttribute" && node.name?.type === "JSXIdentifier" && isMatch(node.name.name, urlAttributes) && node.value) {
105
- if (node.value.type === "StringLiteral") pushLiteralReplacement(node.value);
106
- else if (node.value.type === "JSXExpressionContainer" && node.value.expression?.type === "StringLiteral") pushLiteralReplacement(node.value.expression);
107
- }
108
- for (const key in node) {
109
- if (key === "loc" || key === "start" || key === "end" || key === "range") continue;
110
- const child = node[key];
111
- if (child && typeof child === "object") walk(child);
112
- }
113
- };
114
- walk(ast.program ?? ast);
185
+ const offerAsAsset = ({ node }) => pushLiteralReplacement(node, "asset");
186
+ traverse(ast, {
187
+ noScope: true,
188
+ JSXAttribute({ node }) {
189
+ const { name, value } = node;
190
+ if (value?.type === "StringLiteral") jsxAttributeStrings.add(value);
191
+ if (name.type !== "JSXIdentifier" || !isMatch(name.name, urlAttributes)) return;
192
+ if (value?.type === "StringLiteral") pushLiteralReplacement(value);
193
+ else if (value?.type === "JSXExpressionContainer") pushLiteralReplacement(value.expression);
194
+ },
195
+ StringLiteral: offerAsAsset,
196
+ DirectiveLiteral: offerAsAsset
197
+ });
115
198
  if (replacements.length === 0) return source;
116
199
  let result = source;
117
200
  replacements.sort((a, b) => b.start - a.start).forEach(({ start, end, text }) => {
@@ -151,11 +234,15 @@ async function localizeStaticUrls(settings, targetLocales, includeFiles) {
151
234
  }, 512);
152
235
  }
153
236
  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);
237
+ for (const [locale, filesMap] of targetMappings) {
238
+ const targetFiles = Object.values(filesMap).filter((p) => PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) && (!includeFiles || includeFiles.has(p)));
239
+ const localizeAsset = createAssetLocalizer(sourceFiles, filesMap);
240
+ await batchProcess(targetFiles, async (filePath) => {
241
+ if (!fs$1.existsSync(filePath)) return;
242
+ 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, localizeAsset);
243
+ if (result.hasChanges) await fs$1.promises.writeFile(filePath, result.content);
244
+ }, 512);
245
+ }
159
246
  }
160
247
  /**
161
248
  * Determines if a URL should be processed based on pattern matching
@@ -220,10 +307,10 @@ function transformUrlPath(originalUrl, patternHead, targetLocale, defaultLocale,
220
307
  /**
221
308
  * AST-based transformation for MDX files using remark-mdx
222
309
  */
223
- function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles, urlAttributes) {
310
+ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles, urlAttributes, localizeAsset) {
224
311
  const transformedUrls = [];
225
312
  const patternHeads = getPatternHeads(pattern);
226
- if (!patternHeads.some((patternHead) => mdxContent.includes(patternHead.replace(/\/$/, "")))) return {
313
+ if (!localizeAsset && !patternHeads.some((patternHead) => mdxContent.includes(patternHead.replace(/\/$/, "")))) return {
227
314
  content: mdxContent,
228
315
  hasChanges: false,
229
316
  transformedUrls: []
@@ -242,6 +329,16 @@ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLo
242
329
  };
243
330
  }
244
331
  const transformUrl = (originalUrl, linkType) => {
332
+ const assetUrl = localizeAsset?.(originalUrl);
333
+ if (assetUrl !== void 0 || linkType === "asset") {
334
+ if (!assetUrl) return null;
335
+ transformedUrls.push({
336
+ originalPath: originalUrl,
337
+ newPath: assetUrl,
338
+ type: "asset"
339
+ });
340
+ return assetUrl;
341
+ }
245
342
  if (linkType === "markdown") {
246
343
  const isFragment = /^\s*#/.test(originalUrl);
247
344
  const isAbsoluteRoot = originalUrl.startsWith("/");
@@ -281,16 +378,25 @@ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLo
281
378
  if (newUrl) node.url = newUrl;
282
379
  }
283
380
  });
381
+ if (localizeAsset) {
382
+ visit(processedAst, ["image", "definition"], (node) => {
383
+ const assetNode = node;
384
+ const newUrl = assetNode.url && transformUrl(assetNode.url, "asset");
385
+ if (newUrl) assetNode.url = newUrl;
386
+ });
387
+ visit(processedAst, "yaml", (node) => {
388
+ const yamlNode = node;
389
+ yamlNode.value = localizeFrontmatterAssetUrls(yamlNode.value, transformUrl);
390
+ });
391
+ }
284
392
  visit(processedAst, ["mdxJsxFlowElement", "mdxJsxTextElement"], (node) => {
285
393
  const jsxNode = node;
286
394
  if (!jsxNode.attributes) return;
287
395
  for (const attr of jsxNode.attributes) {
288
396
  if (attr.type !== "mdxJsxAttribute" || !attr.value) continue;
289
397
  if (typeof attr.value === "string") {
290
- if (isMatch(attr.name, urlAttributes)) {
291
- const newUrl = transformUrl(attr.value, "href");
292
- if (newUrl) attr.value = newUrl;
293
- }
398
+ const newUrl = transformUrl(attr.value, isMatch(attr.name, urlAttributes) ? "href" : "asset");
399
+ if (newUrl) attr.value = newUrl;
294
400
  continue;
295
401
  }
296
402
  if (typeof attr.value === "object" && attr.value.type === "mdxJsxAttributeValueExpression" && typeof attr.value.value === "string") {
@@ -362,8 +468,8 @@ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLo
362
468
  transformedUrls
363
469
  };
364
470
  }
365
- function localizeStaticUrlsForFile(file, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles, urlAttributes) {
366
- return transformMdxUrls(file, defaultLocale, targetLocale, hideDefaultLocale, pattern, exclude, baseDomain || "", localizedFiles, urlAttributes);
471
+ function localizeStaticUrlsForFile(file, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles, urlAttributes, localizeAsset) {
472
+ return transformMdxUrls(file, defaultLocale, targetLocale, hideDefaultLocale, pattern, exclude, baseDomain || "", localizedFiles, urlAttributes, localizeAsset);
367
473
  }
368
474
  /**
369
475
  * The part of each docsUrlPattern before `[locale]`, with a leading slash,
@@ -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';\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,QAAO;CAG3B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;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,IAC3C,KAAI,iBAAiB,OAAO,mBAAmB,GAC7C,QAAO;AAIX,QAAO"}
1
+ {"version":3,"file":"localizeStaticUrls.js","names":["path","fs","parse","parseBabel"],"sources":["../../src/utils/localizeStaticUrls.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type {\n ResolvedFiles,\n StaticLocalizationSettings,\n} 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, Image, Definition, Yaml } from 'mdast';\nimport YAML, { isScalar } from 'yaml';\nimport type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parse as parseBabel, type ParseResult } from '@babel/parser';\nimport traverseModule from '@babel/traverse';\nimport type * as t from '@babel/types';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\nimport { STATIC_ASSET_FILE_TYPES } from '../formats/files/supportedFiles.js';\n\nconst { isMatch } = micromatch;\nconst traverse = traverseModule.default || traverseModule;\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 * The localized URL of a static asset configured for translation, `null` when\n * its translation is not on disk, or `undefined` when the URL is not such an\n * asset.\n */\ntype AssetLocalizer = (url: string) => string | null | undefined;\n\n/** Where a URL was found: a link, or (`asset`) a value only a static asset URL can localize. */\ntype UrlPosition = 'markdown' | 'href' | 'asset';\ntype TransformUrl = (url: string, position: UrlPosition) => string | null;\n\nfunction toRootRelativeUrl(filePath: string): string {\n return '/' + path.relative(process.cwd(), filePath).split(path.sep).join('/');\n}\n\nfunction decodeUrlPath(urlPath: string): string {\n try {\n return urlPath.split('/').map(decodeURIComponent).join('/');\n } catch {\n return urlPath;\n }\n}\n\nfunction percentEncode(char: string): string {\n return `%${char.charCodeAt(0).toString(16).toUpperCase()}`;\n}\n\nfunction encodeUrlPath(urlPath: string): string {\n return urlPath\n .split('/')\n .map((segment) =>\n encodeURIComponent(segment).replace(/['()]/g, percentEncode)\n )\n .join('/');\n}\n\n/**\n * Maps root-relative URLs of static assets configured for translation to the\n * URL of the locale's translated file, wherever the file mapping puts it.\n */\nfunction createAssetLocalizer(\n sourceFiles: ResolvedFiles,\n filesMap: Record<string, string>\n): AssetLocalizer | undefined {\n const translatedFiles = new Map<string, string>();\n const translatedUrls = new Set<string>();\n for (const fileType of STATIC_ASSET_FILE_TYPES) {\n for (const source of sourceFiles[fileType] ?? []) {\n const translatedFile =\n filesMap[path.relative(process.cwd(), source)] ?? filesMap[source];\n if (translatedFile) {\n translatedFiles.set(toRootRelativeUrl(source), translatedFile);\n translatedUrls.add(toRootRelativeUrl(translatedFile));\n }\n }\n }\n if (translatedFiles.size === 0) return undefined;\n\n return (url) => {\n if (!url.startsWith('/')) return undefined;\n const urlPath = url.split(/[?#]/)[0];\n const decodedPath = decodeUrlPath(urlPath);\n const translatedFile = translatedFiles.get(decodedPath);\n if (translatedFile === undefined) {\n // An already localized asset URL is not a page link.\n return translatedUrls.has(decodedPath) ? null : undefined;\n }\n if (!fs.existsSync(translatedFile)) return null;\n const translatedUrl = toRootRelativeUrl(translatedFile);\n if (translatedUrl === decodedPath) return null;\n // Quotes stay encoded so the URL is safe inside any quoted value.\n return (\n (decodedPath === urlPath\n ? translatedUrl.replace(/['\"]/g, percentEncode)\n : encodeUrlPath(translatedUrl)) + url.slice(urlPath.length)\n );\n };\n}\n\n/**\n * Localizes frontmatter values that are asset URLs, such as `og:image`,\n * replacing only the value's own characters so the YAML keeps its formatting.\n */\nfunction localizeFrontmatterAssetUrls(\n frontmatter: string,\n transformUrl: TransformUrl\n): string {\n const doc = YAML.parseDocument(frontmatter, { prettyErrors: false });\n if (doc.errors.length) return frontmatter;\n\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n YAML.visit(doc, {\n Scalar(key, node) {\n if (key === 'key' || !isScalar(node) || !node.range) return;\n if (typeof node.value !== 'string') return;\n const [start, end] = node.range;\n const raw = frontmatter.slice(start, end);\n if (!raw.includes(node.value)) return;\n const newUrl = transformUrl(node.value, 'asset');\n if (!newUrl) return;\n replacements.push({ start, end, text: raw.replace(node.value, newUrl) });\n },\n });\n\n let result = frontmatter;\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\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 *\n * Every other string literal is offered as an `asset`, so an asset URL is\n * localized whichever attribute or data structure holds it.\n */\nfunction localizeUrlsInExpressionSource(\n source: string,\n transformUrl: TransformUrl,\n urlAttributes: string[],\n rootStringIsUrl: boolean = false\n): string {\n if (!source.trim()) return source;\n\n const parse = (code: string): ParseResult<t.File> =>\n parseBabel(code, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['jsx', 'typescript'],\n });\n\n // Parenthesized, the source parses as an expression, so `{ src: \"/a.png\" }`\n // is an object and not a block. Sources that are not one expression fall\n // back to parsing as written.\n let ast: ParseResult<t.File>;\n let offset = 1;\n try {\n ast = parse(`(${source}\\n)`);\n if (ast.errors?.length) throw new Error('Not a single expression');\n } catch {\n offset = 0;\n try {\n ast = parse(source);\n } catch {\n // Dynamic / unparseable expression — leave it untouched.\n return source;\n }\n }\n\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n const visitedLiterals = new Set<number>();\n const jsxAttributeStrings = new Set<t.StringLiteral>();\n\n const pushLiteralReplacement = (\n literal: t.Node | null | undefined,\n position: UrlPosition = 'href'\n ) => {\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.start !== 'number' ||\n typeof literal.end !== 'number'\n ) {\n return;\n }\n if (visitedLiterals.has(literal.start)) return;\n visitedLiterals.add(literal.start);\n const newUrl = transformUrl(literal.value, position);\n if (!newUrl) return;\n const quote = source[literal.start - offset] === \"'\" ? \"'\" : '\"';\n // Babel resolves backslash escapes in a StringLiteral's value only; a\n // DirectiveLiteral keeps them as written and a JSX attribute has none.\n const isUnescaped =\n literal.type === 'StringLiteral' && !jsxAttributeStrings.has(literal);\n replacements.push({\n start: literal.start - offset,\n end: literal.end - offset,\n text: isUnescaped ? JSON.stringify(newUrl) : `${quote}${newUrl}${quote}`,\n });\n };\n\n // `href={\"/docs/x\"}`: the entire expression is the URL string.\n if (rootStringIsUrl) {\n const { body, directives } = ast.program;\n if (body.length === 1 && body[0].type === 'ExpressionStatement') {\n pushLiteralReplacement(body[0].expression);\n } else if (body.length === 0 && directives.length === 1) {\n // Babel parses a lone string literal as a directive, not a statement.\n pushLiteralReplacement(directives[0].value);\n }\n }\n\n const offerAsAsset = ({ node }: { node: t.Node }) =>\n pushLiteralReplacement(node, 'asset');\n traverse(ast, {\n noScope: true,\n JSXAttribute({ node }) {\n const { name, value } = node;\n if (value?.type === 'StringLiteral') jsxAttributeStrings.add(value);\n if (name.type !== 'JSXIdentifier' || !isMatch(name.name, urlAttributes)) {\n return;\n }\n if (value?.type === 'StringLiteral') {\n pushLiteralReplacement(value);\n } else if (value?.type === 'JSXExpressionContainer') {\n pushLiteralReplacement(value.expression);\n }\n },\n StringLiteral: offerAsAsset,\n DirectiveLiteral: offerAsAsset,\n });\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 const localizeAsset = createAssetLocalizer(sourceFiles, filesMap);\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 localizeAsset\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' | 'asset';\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 localizeAsset?: AssetLocalizer\n): UrlTransformResult {\n const transformedUrls: UrlTransformResult['transformedUrls'] = [];\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 !localizeAsset &&\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: TransformUrl = (originalUrl, linkType) => {\n // A static asset URL follows the asset's file, not the page URL pattern.\n const assetUrl = localizeAsset?.(originalUrl);\n if (assetUrl !== undefined || linkType === 'asset') {\n if (!assetUrl) return null;\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: assetUrl,\n type: 'asset',\n });\n return assetUrl;\n }\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 if (localizeAsset) {\n // Markdown images and reference definitions: ![alt](url), [ref]: url\n visit(processedAst, ['image', 'definition'], (node) => {\n const assetNode = node as Image | Definition;\n const newUrl = assetNode.url && transformUrl(assetNode.url, 'asset');\n if (newUrl) assetNode.url = newUrl;\n });\n\n visit(processedAst, 'yaml', (node) => {\n const yamlNode = node as Yaml;\n yamlNode.value = localizeFrontmatterAssetUrls(\n yamlNode.value,\n transformUrl\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 const newUrl = transformUrl(\n attr.value,\n isMatch(attr.name, urlAttributes) ? 'href' : 'asset'\n );\n if (newUrl) {\n attr.value = newUrl;\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 localizeAsset?: AssetLocalizer\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 localizeAsset\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":";;;;;;;;;;;;;;;;;AAwBA,MAAM,EAAE,YAAY;AACpB,MAAM,WAAW,eAAe,WAAW;;;;;;;;AAS3C,MAAM,yBAAyB,CAAC,OAAO;AAIvC,MAAa,kBAAkB,CAAC,QAAQ,MAAM;AAC9C,MAAa,aAAa;;;;;;AAO1B,SAAS,SAAS,KAAiC;CACjD,MAAM,OA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CACtD,WAAU,QAAQ,MAAM,GAAG,GAAG;AAIhC,KAAI,WAAW,WAAW,KAAK,IAAI,CAAC,QAAQ,WAAW,KAAK,CAC1D,WAAU,OAAO;AAGnB,QAAO;EACL;EACA,YAAY,gBAAgB,SAAS;EACrC;EACD;;AAIH,SAAS,0BACP,MACA,eACA,cACA,mBACA,UAA6B,aAC7B,UAAoB,EAAE,EACtB,YACA,gBACA,eACA,eACoB;AAEpB,QAAO,iBACL,MACA,eACA,cACA,mBACA,SACA,SACA,cAAc,IACd,gBACA,eACA,cACD;;;;;;AAOH,SAAgB,gBAAgB,SAAsC;AACpE,SAAQ,MAAM,QAAQ,QAAQ,GAAG,UAAU,CAAC,QAAQ,EACjD,KAAK,OAAO,EAAE,WAAW,IAAI,GAAG,IAAI,IAAI,KAAK,MAAM,WAAW,CAAC,GAAG,CAClE,MAAM,GAAG,MAAM,aAAa,EAAE,CAAC,SAAS,aAAa,EAAE,CAAC,OAAO;;;;;;;AAQpE,SAAgB,gBACd,KACA,cACoB;CAEpB,MAAM,cAAc,aAAa,IAAI,MAAM,OAAO,CAAC,GAAG;AACtD,QAAO,aAAa,MAAM,gBACxB,0BAA0B,aAAa,aAAa,YAAY,CAAC,CAClE;;AAGH,SAAS,aAAa,KAAuB;AAC3C,QAAO,IAAI,MAAM,IAAI,CAAC,QAAQ,YAAY,YAAY,GAAG;;AAG3D,SAAS,0BACP,kBACA,kBACS;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,IAC3C,KAAI,iBAAiB,OAAO,mBAAmB,GAC7C,QAAO;AAIX,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gt",
3
- "version": "2.28.7",
3
+ "version": "2.29.0",
4
4
  "main": "dist/index.js",
5
5
  "bin": "bin/main.js",
6
6
  "files": [
@@ -116,12 +116,12 @@
116
116
  "unified": "^11.0.5",
117
117
  "unist-util-visit": "^5.0.0",
118
118
  "yaml": "^2.8.0",
119
- "@generaltranslation/format": "0.1.12",
119
+ "@generaltranslation/format": "0.1.13",
120
120
  "@generaltranslation/icu": "0.1.2",
121
- "@generaltranslation/python-extractor": "0.2.69",
122
- "@generaltranslation/supported-locales": "2.1.50",
123
- "@generaltranslation/vue-extractor": "0.1.28",
124
- "generaltranslation": "9.5.14",
121
+ "@generaltranslation/python-extractor": "0.2.70",
122
+ "@generaltranslation/supported-locales": "2.1.51",
123
+ "@generaltranslation/vue-extractor": "0.1.29",
124
+ "generaltranslation": "9.5.15",
125
125
  "gt-remark": "1.0.12"
126
126
  },
127
127
  "devDependencies": {