gt 2.28.6 → 2.28.7

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,18 @@
1
1
  # gtx-cli
2
2
 
3
+ ## 2.28.7
4
+
5
+ ### Patch Changes
6
+
7
+ - [#3129](https://github.com/generaltranslation/gt/pull/3129) [`b7547d9`](https://github.com/generaltranslation/gt/commit/b7547d9b175143c0431fa575022d390827cb46db) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Add PNG, JPEG, WebP, TIFF, BMP, AVIF and HEIC images as supported file types, uploaded as bytes and translated by the image translation agent
8
+
9
+ - Updated dependencies [[`a812817`](https://github.com/generaltranslation/gt/commit/a81281746b2624c95c685a40bfc0ec0297f2b0b7), [`b7547d9`](https://github.com/generaltranslation/gt/commit/b7547d9b175143c0431fa575022d390827cb46db)]:
10
+ - @generaltranslation/format@0.1.12
11
+ - generaltranslation@9.5.14
12
+ - @generaltranslation/vue-extractor@0.1.28
13
+ - @generaltranslation/python-extractor@0.2.69
14
+ - @generaltranslation/supported-locales@2.1.50
15
+
3
16
  ## 2.28.6
4
17
 
5
18
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"collectUserEditDiffs.js","names":["path","fs"],"sources":["../../src/api/collectUserEditDiffs.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport {\n readLockfile,\n EntryMap,\n DownloadedTranslation,\n} from '../fs/config/downloadedVersions.js';\nimport { Settings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport { getGitUnifiedDiff } from '../utils/gitDiff.js';\nimport { api } from '../utils/api.js';\nimport {\n FileReference,\n isBinaryFileFormat,\n SubmitUserEditDiff,\n type FileFormat,\n} from 'generaltranslation/types';\nimport { readFileContent } from '../fs/fileContent.js';\nimport os from 'node:os';\nimport { randomUUID } from 'node:crypto';\nimport { hashStringSync } from '../utils/hash.js';\nimport { extractJson } from '../formats/json/extractJson.js';\nimport {\n emptyLocaleContent,\n localeContent,\n} from '../formats/files/localeContent.js';\nimport { extractYaml } from '../formats/yaml/extractYaml.js';\nimport { logger } from '../console/logger.js';\nimport { recordWarning } from '../state/translateWarnings.js';\nimport { getRelative } from '../fs/findFilepath.js';\nimport {\n resolveMintlifyRefs,\n shouldResolveRefs,\n type UnreadableRef,\n} from '../utils/resolveMintlifyRefs.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n validateJsonSchema,\n} from '../formats/json/utils.js';\nimport type { JSONObject, JSONValue } from '../types/data/json.js';\nimport { getJSONPathMatches } from '../formats/json/jsonPath.js';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { isDeepStrictEqual } from 'node:util';\n\nconst unsavedJsonEditsWarning = (\n relativePath: string,\n locale: string,\n reason: string\n) =>\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Local edits to ${relativePath} were not saved for ${locale}`,\n why: reason,\n reassurance: 'The stored translation was left unchanged',\n });\n\nconst resolveLocalRefs = (\n content: string,\n outputPath: string,\n settings: Settings\n): { content: string; unreadableRefs: UnreadableRef[] } => {\n if (!shouldResolveRefs(outputPath, settings.options)) {\n return { content, unreadableRefs: [] };\n }\n try {\n const { resolved, unreadableRefs } = resolveMintlifyRefs(\n JSON.parse(content),\n outputPath\n );\n return { content: JSON.stringify(resolved, null, 2), unreadableRefs };\n } catch {\n return { content, unreadableRefs: [] };\n }\n};\n\n/**\n * The unreadable refs that could hold values of the locale: all of them,\n * except those inside an entry of a composite file known to belong to another\n * locale.\n */\nconst unreadableRefsForLocale = (\n unreadableRefs: UnreadableRef[],\n resolvedContent: string,\n fileName: string,\n locale: string,\n settings: Settings\n): UnreadableRef[] => {\n if (unreadableRefs.length === 0) return [];\n const composite = validateJsonSchema(\n settings.options ?? {},\n fileName\n )?.composite;\n const json = parseJson(resolvedContent) as JSONValue | undefined;\n if (!composite || json === undefined) return unreadableRefs;\n\n const localeKey = settings.options?.experimentalCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(locale)\n : locale;\n const otherLocalePointers: string[] = [];\n for (const [\n pointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(generateSourceObjectPointers(composite, json))) {\n if (sourceObjectOptions.type === 'array') {\n if (!Array.isArray(sourceObjectValue)) continue;\n const ownItems = findMatchingItemArray(\n localeKey,\n sourceObjectOptions,\n pointer,\n sourceObjectValue\n );\n sourceObjectValue.forEach((item, index) => {\n // An entry whose locale key sat in the unreadable file has no key\n // left, so it may be the locale's own.\n const hasLocaleKey =\n !!sourceObjectOptions.key &&\n (getJSONPathMatches(item, sourceObjectOptions.key)?.length ?? 0) > 0;\n if (hasLocaleKey && !(`/${index}` in ownItems)) {\n otherLocalePointers.push(`${pointer}/${index}`);\n }\n });\n } else if (sourceObjectValue && typeof sourceObjectValue === 'object') {\n const { keyParentProperty } = findMatchingItemObject(\n localeKey,\n pointer,\n sourceObjectOptions,\n sourceObjectValue as JSONObject\n );\n for (const key of Object.keys(sourceObjectValue)) {\n if (key !== keyParentProperty) {\n otherLocalePointers.push(`${pointer}/${key}`);\n }\n }\n }\n }\n return unreadableRefs.filter(\n (ref) =>\n !otherLocalePointers.some(\n (pointer) =>\n ref.pointer === pointer || ref.pointer.startsWith(`${pointer}/`)\n )\n );\n};\n\nconst hasLeafValue = (value: unknown): boolean =>\n value !== null && typeof value === 'object'\n ? Object.values(value).some(hasLeafValue)\n : value !== undefined;\n\nconst parseJson = (content: string): unknown => {\n try {\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n};\n\ntype LatestDownloadedVersion = {\n versionId: string;\n entry: DownloadedTranslation;\n};\n\n/**\n * The bytes a file's pipeline content stands for: binary formats carry base64,\n * everything else carries UTF-8 text. Applied to both sides of the comparison\n * so they are measured the same way.\n */\nconst contentBytes = (content: string, fileFormat: FileFormat): Buffer =>\n isBinaryFileFormat(fileFormat)\n ? Buffer.from(content, 'base64')\n : Buffer.from(content, 'utf8');\n\n/**\n * The branch these files were uploaded under. `readLockfile` needs it to pick\n * the matching entries out of a v1 lockfile, which keeps every branch it has\n * seen; without it the file's entries are read from whichever branch is listed\n * first. The files carry the branch resolved for this invocation, while\n * `settings._branchId` can still hold the value persisted by an earlier run.\n */\nconst lockfileBranchId = (\n files: FileReference[],\n settings: Settings\n): string | undefined =>\n files.find((file) => file.branchId)?.branchId ?? settings._branchId;\n\nconst findLatestDownloadedVersion = (\n entryMap: EntryMap,\n fileId: string,\n locale: string\n): LatestDownloadedVersion | null => {\n const entry = entryMap.get(fileId);\n if (!entry) return null;\n\n const translation = entry.translations[locale];\n if (!translation) return null;\n\n return { versionId: entry.versionId, entry: translation };\n};\n\n/**\n * Collects local user edits by diffing the latest downloaded server translation version\n * against the current local translation file, and submits the diffs upstream.\n * A file that holds every locale is compared one locale slice at a time, so an\n * edit to one locale is submitted under that locale alone.\n *\n * Must run before enqueueing new translations so rules are available to the generator.\n */\nexport async function collectAndSendUserEditDiffs(\n files: FileReference[],\n settings: Settings\n): Promise<boolean> {\n if (!settings.files) return false;\n\n const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } =\n settings.files;\n const fileMapping = createFileMapping(\n resolvedPaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n // readLockfile uses _branchId to select branch-specific entries. Keep it on a\n // scoped copy so the caller's settings object is not mutated.\n const branchId = lockfileBranchId(files, settings);\n const { entryMap } = readLockfile(\n branchId ? { ...settings, _branchId: branchId } : settings\n );\n\n const tempDir = path.join(os.tmpdir(), randomUUID());\n if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });\n\n // Build candidates for diff and batch-fetch server contents\n type DiffCandidate = {\n branchId: string;\n fileName: string;\n fileId: string;\n versionId: string;\n locale: string; // resolved\n outputPath: string;\n fileFormat: FileFormat;\n /** The recorded hash did not match, so this locale is known to be edited. */\n knownEdited: boolean;\n };\n const candidates: DiffCandidate[] = [];\n\n for (const uploadedFile of files) {\n for (const locale of settings.locales) {\n const outputPath = fileMapping[locale]?.[uploadedFile.fileName] ?? null;\n if (!outputPath) continue;\n if (!fs.existsSync(outputPath)) continue;\n\n const latestDownloaded = findLatestDownloadedVersion(\n entryMap,\n uploadedFile.fileId,\n locale\n );\n\n if (!latestDownloaded) continue;\n const downloadedVersion = latestDownloaded.entry;\n\n // Skip if the locale's local content matches the last recorded hash\n let knownEdited = false;\n if (downloadedVersion.postProcessHash) {\n try {\n // Hashed from the locale's share of the pipeline content, which is\n // what was recorded, so an untouched locale matches regardless of\n // the file's encoding or of edits to its other locales.\n const localFile = readFileContent(\n outputPath,\n uploadedFile.fileFormat\n );\n const localHash = hashStringSync(\n localeContent(localFile, uploadedFile.fileFormat, locale) ??\n emptyLocaleContent(localFile, uploadedFile.fileFormat)\n );\n if (localHash === downloadedVersion.postProcessHash) {\n continue;\n }\n knownEdited = true;\n } catch {\n // If hash check fails, fall through to diff\n }\n }\n\n candidates.push({\n branchId: uploadedFile.branchId,\n fileName: uploadedFile.fileName,\n fileId: uploadedFile.fileId,\n versionId: latestDownloaded.versionId,\n locale: locale,\n outputPath,\n fileFormat: uploadedFile.fileFormat,\n knownEdited,\n });\n }\n }\n\n const collectedDiffs: SubmitUserEditDiff[] = [];\n\n if (candidates.length > 0) {\n const fileQueryData = candidates.map((c) => ({\n versionId: c.versionId,\n locale: c.locale,\n fileId: c.fileId,\n branchId: c.branchId,\n }));\n\n // Single batched check to obtain translation IDs\n const checkResponse = await api.queryFileData({\n translatedFiles: fileQueryData,\n });\n const translatedFiles =\n checkResponse.translatedFiles?.filter((t) => t.completedAt) ?? [];\n\n // The server's copy of each candidate, keyed like the candidates\n type ServerPayload = { data: string; fileFormat: FileFormat };\n const serverPayloadByKey = new Map<string, ServerPayload>();\n try {\n const resp = await api.downloadFileBatch(\n translatedFiles.map((file) => ({\n branchId: file.branchId,\n fileId: file.fileId,\n locale: file.locale,\n versionId: file.versionId,\n }))\n );\n for (const f of resp?.files || []) {\n if (!f.locale) continue;\n serverPayloadByKey.set(\n `${f.branchId}:${f.fileId}:${f.versionId}:${f.locale}`,\n { data: f.data, fileFormat: f.fileFormat }\n );\n }\n } catch {\n // Ignore chunk failures; proceed with what we have\n }\n\n // Compute diffs using fetched server contents\n for (const c of candidates) {\n const key = `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`;\n const payload = serverPayloadByKey.get(key);\n // Absent means the batch did not return this file, so there is no\n // baseline. An empty payload is a baseline of nothing, which the user\n // may well have written against. When the recorded hash already showed\n // an edit, say so rather than leaving the run looking clean. An empty\n // map cannot tell a version the server does not have from a batch that\n // failed to return it, so the message covers both.\n if (!payload) {\n if (c.knownEdited) {\n const relativePath = getRelative(c.outputPath);\n const reason = `the ${c.locale} baseline recorded in the lockfile could not be retrieved, so the edit could not be compared`;\n logger.warn(unsavedJsonEditsWarning(relativePath, c.locale, reason));\n recordWarning('skipped_file', relativePath, reason);\n }\n continue;\n }\n\n // The locale's share of the payload, read on its own so a payload the\n // server sent malformed costs only its own locale. A catalog payload\n // that carries nothing for the locale is that file's empty payload, and\n // a baseline of nothing like any other.\n let serverContent: string;\n try {\n serverContent =\n localeContent(payload.data, payload.fileFormat, c.locale) ??\n emptyLocaleContent(payload.data, payload.fileFormat);\n } catch (error) {\n const relativePath = getRelative(c.outputPath);\n const reason = `The downloaded ${c.locale} translation could not be read (${\n error instanceof Error ? error.message : String(error)\n })`;\n logger.warn(`Skipping local edits to ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n const serverBytes = contentBytes(serverContent, payload.fileFormat);\n\n try {\n // Read the local file the same way the pipeline read it originally, so\n // a file stored differently on disk than the server's copy is compared\n // as content rather than as bytes. Otherwise every such file would read\n // as edited on every run. Then cut to this locale's share, so a file\n // that holds every locale is compared slice to slice.\n const local = localeContent(\n readFileContent(c.outputPath, c.fileFormat),\n c.fileFormat,\n c.locale\n );\n // A catalog that no longer carries the locale has nothing to submit\n if (local === undefined) continue;\n const localBytes = contentBytes(local, c.fileFormat);\n\n // Nothing was edited, so there is no diff to compute or report.\n if (localBytes.equals(serverBytes)) continue;\n\n // A unified diff and localContent are both UTF-8 text, and every text\n // format's content is UTF-8 by the time it reaches here. Only a binary\n // format's bytes — a Lottie zip — have no text form at all. Say so:\n // the edit is real and will be lost on the next download.\n if (isBinaryFileFormat(c.fileFormat)) {\n const relativePath = getRelative(c.outputPath);\n const reason =\n 'Edited file is a binary format, so its changes cannot be submitted';\n logger.warn(`Skipping local edits to ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n\n const safeName = Buffer.from(\n `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`\n )\n .toString('base64')\n .replace(/=+$/g, '');\n const tempServerFile = path.join(tempDir, `${safeName}.server`);\n await fs.promises.writeFile(tempServerFile, serverBytes);\n\n // git diff reads bytes, so both sides are written from the content\n // they represent rather than diffing the file as it sits on disk.\n const tempLocalFile = path.join(tempDir, `${safeName}.local`);\n await fs.promises.writeFile(tempLocalFile, localBytes);\n\n const diff = await getGitUnifiedDiff(tempServerFile, tempLocalFile);\n for (const tempFile of [tempServerFile, tempLocalFile]) {\n try {\n await fs.promises.unlink(tempFile);\n } catch {\n // Ignore cleanup errors for temporary comparison files.\n }\n }\n\n if (diff && diff.trim().length > 0) {\n const rawLocalContent = localBytes.toString('utf8');\n\n // For JSON files with jsonSchema config, extract to composite format\n let localContent = rawLocalContent;\n if (\n c.fileName.endsWith('.json') &&\n settings.options?.jsonSchema &&\n c.locale !== settings.defaultLocale\n ) {\n const resolvedLocal = resolveLocalRefs(\n rawLocalContent,\n c.outputPath,\n settings\n );\n const extractedContent = extractJson(\n resolvedLocal.content,\n c.fileName,\n settings.options,\n c.locale,\n settings.defaultLocale\n );\n if (extractedContent) {\n const extracted = parseJson(extractedContent);\n // The submitted content replaces the stored translation, so\n // values missing from it would be erased.\n const unreadableRefs = unreadableRefsForLocale(\n resolvedLocal.unreadableRefs,\n resolvedLocal.content,\n c.fileName,\n c.locale,\n settings\n );\n const reason =\n unreadableRefs.length > 0\n ? `these $ref files could not be read: ${unreadableRefs.map((ref) => ref.refPath).join(', ')}`\n : !hasLeafValue(extracted)\n ? 'no translated values for that locale could be read from the file'\n : undefined;\n if (reason) {\n const relativePath = getRelative(c.outputPath);\n logger.warn(\n unsavedJsonEditsWarning(relativePath, c.locale, reason)\n );\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n if (isDeepStrictEqual(extracted, parseJson(serverContent))) {\n continue;\n }\n localContent = extractedContent;\n }\n } else if (\n (c.fileName.endsWith('.yaml') || c.fileName.endsWith('.yml')) &&\n settings.options?.yamlSchema &&\n c.locale !== settings.defaultLocale\n ) {\n const extractedContent = extractYaml(\n rawLocalContent,\n c.fileName,\n settings.options\n );\n if (extractedContent) {\n localContent = extractedContent;\n }\n }\n\n collectedDiffs.push({\n fileName: c.fileName,\n locale: c.locale,\n diff,\n branchId: c.branchId,\n versionId: c.versionId,\n fileId: c.fileId,\n localContent,\n } satisfies SubmitUserEditDiff);\n }\n } catch {\n // Ignore failures for this file\n }\n }\n }\n\n if (collectedDiffs.length > 0) {\n await api.submitUserEditDiffs({ diffs: collectedDiffs });\n }\n\n return collectedDiffs.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,2BACJ,cACA,QACA,WAEA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,kBAAkB,aAAa,sBAAsB;CACnE,KAAK;CACL,aAAa;CACd,CAAC;AAEJ,MAAM,oBACJ,SACA,YACA,aACyD;AACzD,KAAI,CAAC,kBAAkB,YAAY,SAAS,QAAQ,CAClD,QAAO;EAAE;EAAS,gBAAgB,EAAE;EAAE;AAExC,KAAI;EACF,MAAM,EAAE,UAAU,mBAAmB,oBACnC,KAAK,MAAM,QAAQ,EACnB,WACD;AACD,SAAO;GAAE,SAAS,KAAK,UAAU,UAAU,M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WAAW,SAAS,eACtB;MACA,MAAM,mBAAmB,YACvB,iBACA,EAAE,UACF,SAAS,QACV;AACD,UAAI,iBACF,gBAAe;;AAInB,oBAAe,KAAK;MAClB,UAAU,EAAE;MACZ,QAAQ,EAAE;MACV;MACA,UAAU,EAAE;MACZ,WAAW,EAAE;MACb,QAAQ,EAAE;MACV;MACD,CAA8B;;WAE3B;;;AAMZ,KAAI,eAAe,SAAS,EAC1B,OAAM,IAAI,oBAAoB,EAAE,OAAO,gBAAgB,CAAC;AAG1D,QAAO,eAAe,SAAS"}
1
+ {"version":3,"file":"collectUserEditDiffs.js","names":["path","fs"],"sources":["../../src/api/collectUserEditDiffs.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport {\n readLockfile,\n EntryMap,\n DownloadedTranslation,\n} from '../fs/config/downloadedVersions.js';\nimport { Settings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport { getGitUnifiedDiff } from '../utils/gitDiff.js';\nimport { api } from '../utils/api.js';\nimport {\n FileReference,\n isBinaryFileFormat,\n SubmitUserEditDiff,\n type FileFormat,\n} from 'generaltranslation/types';\nimport { readFileContent } from '../fs/fileContent.js';\nimport os from 'node:os';\nimport { randomUUID } from 'node:crypto';\nimport { hashStringSync } from '../utils/hash.js';\nimport { extractJson } from '../formats/json/extractJson.js';\nimport {\n emptyLocaleContent,\n localeContent,\n} from '../formats/files/localeContent.js';\nimport { extractYaml } from '../formats/yaml/extractYaml.js';\nimport { logger } from '../console/logger.js';\nimport { recordWarning } from '../state/translateWarnings.js';\nimport { getRelative } from '../fs/findFilepath.js';\nimport {\n resolveMintlifyRefs,\n shouldResolveRefs,\n type UnreadableRef,\n} from '../utils/resolveMintlifyRefs.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n validateJsonSchema,\n} from '../formats/json/utils.js';\nimport type { JSONObject, JSONValue } from '../types/data/json.js';\nimport { getJSONPathMatches } from '../formats/json/jsonPath.js';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { isDeepStrictEqual } from 'node:util';\n\nconst unsavedJsonEditsWarning = (\n relativePath: string,\n locale: string,\n reason: string\n) =>\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Local edits to ${relativePath} were not saved for ${locale}`,\n why: reason,\n reassurance: 'The stored translation was left unchanged',\n });\n\nconst resolveLocalRefs = (\n content: string,\n outputPath: string,\n settings: Settings\n): { content: string; unreadableRefs: UnreadableRef[] } => {\n if (!shouldResolveRefs(outputPath, settings.options)) {\n return { content, unreadableRefs: [] };\n }\n try {\n const { resolved, unreadableRefs } = resolveMintlifyRefs(\n JSON.parse(content),\n outputPath\n );\n return { content: JSON.stringify(resolved, null, 2), unreadableRefs };\n } catch {\n return { content, unreadableRefs: [] };\n }\n};\n\n/**\n * The unreadable refs that could hold values of the locale: all of them,\n * except those inside an entry of a composite file known to belong to another\n * locale.\n */\nconst unreadableRefsForLocale = (\n unreadableRefs: UnreadableRef[],\n resolvedContent: string,\n fileName: string,\n locale: string,\n settings: Settings\n): UnreadableRef[] => {\n if (unreadableRefs.length === 0) return [];\n const composite = validateJsonSchema(\n settings.options ?? {},\n fileName\n )?.composite;\n const json = parseJson(resolvedContent) as JSONValue | undefined;\n if (!composite || json === undefined) return unreadableRefs;\n\n const localeKey = settings.options?.experimentalCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(locale)\n : locale;\n const otherLocalePointers: string[] = [];\n for (const [\n pointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(generateSourceObjectPointers(composite, json))) {\n if (sourceObjectOptions.type === 'array') {\n if (!Array.isArray(sourceObjectValue)) continue;\n const ownItems = findMatchingItemArray(\n localeKey,\n sourceObjectOptions,\n pointer,\n sourceObjectValue\n );\n sourceObjectValue.forEach((item, index) => {\n // An entry whose locale key sat in the unreadable file has no key\n // left, so it may be the locale's own.\n const hasLocaleKey =\n !!sourceObjectOptions.key &&\n (getJSONPathMatches(item, sourceObjectOptions.key)?.length ?? 0) > 0;\n if (hasLocaleKey && !(`/${index}` in ownItems)) {\n otherLocalePointers.push(`${pointer}/${index}`);\n }\n });\n } else if (sourceObjectValue && typeof sourceObjectValue === 'object') {\n const { keyParentProperty } = findMatchingItemObject(\n localeKey,\n pointer,\n sourceObjectOptions,\n sourceObjectValue as JSONObject\n );\n for (const key of Object.keys(sourceObjectValue)) {\n if (key !== keyParentProperty) {\n otherLocalePointers.push(`${pointer}/${key}`);\n }\n }\n }\n }\n return unreadableRefs.filter(\n (ref) =>\n !otherLocalePointers.some(\n (pointer) =>\n ref.pointer === pointer || ref.pointer.startsWith(`${pointer}/`)\n )\n );\n};\n\nconst hasLeafValue = (value: unknown): boolean =>\n value !== null && typeof value === 'object'\n ? Object.values(value).some(hasLeafValue)\n : value !== undefined;\n\nconst parseJson = (content: string): unknown => {\n try {\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n};\n\ntype LatestDownloadedVersion = {\n versionId: string;\n entry: DownloadedTranslation;\n};\n\n/**\n * The bytes a file's pipeline content stands for: binary formats carry base64,\n * everything else carries UTF-8 text. Applied to both sides of the comparison\n * so they are measured the same way.\n */\nconst contentBytes = (content: string, fileFormat: FileFormat): Buffer =>\n isBinaryFileFormat(fileFormat)\n ? Buffer.from(content, 'base64')\n : Buffer.from(content, 'utf8');\n\n/**\n * The branch these files were uploaded under. `readLockfile` needs it to pick\n * the matching entries out of a v1 lockfile, which keeps every branch it has\n * seen; without it the file's entries are read from whichever branch is listed\n * first. The files carry the branch resolved for this invocation, while\n * `settings._branchId` can still hold the value persisted by an earlier run.\n */\nconst lockfileBranchId = (\n files: FileReference[],\n settings: Settings\n): string | undefined =>\n files.find((file) => file.branchId)?.branchId ?? settings._branchId;\n\nconst findLatestDownloadedVersion = (\n entryMap: EntryMap,\n fileId: string,\n locale: string\n): LatestDownloadedVersion | null => {\n const entry = entryMap.get(fileId);\n if (!entry) return null;\n\n const translation = entry.translations[locale];\n if (!translation) return null;\n\n return { versionId: entry.versionId, entry: translation };\n};\n\n/**\n * Collects local user edits by diffing the latest downloaded server translation version\n * against the current local translation file, and submits the diffs upstream.\n * A file that holds every locale is compared one locale slice at a time, so an\n * edit to one locale is submitted under that locale alone.\n *\n * Must run before enqueueing new translations so rules are available to the generator.\n */\nexport async function collectAndSendUserEditDiffs(\n files: FileReference[],\n settings: Settings\n): Promise<boolean> {\n if (!settings.files) return false;\n\n const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } =\n settings.files;\n const fileMapping = createFileMapping(\n resolvedPaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n // readLockfile uses _branchId to select branch-specific entries. Keep it on a\n // scoped copy so the caller's settings object is not mutated.\n const branchId = lockfileBranchId(files, settings);\n const { entryMap } = readLockfile(\n branchId ? { ...settings, _branchId: branchId } : settings\n );\n\n const tempDir = path.join(os.tmpdir(), randomUUID());\n if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });\n\n // Build candidates for diff and batch-fetch server contents\n type DiffCandidate = {\n branchId: string;\n fileName: string;\n fileId: string;\n versionId: string;\n locale: string; // resolved\n outputPath: string;\n fileFormat: FileFormat;\n /** The recorded hash did not match, so this locale is known to be edited. */\n knownEdited: boolean;\n };\n const candidates: DiffCandidate[] = [];\n\n for (const uploadedFile of files) {\n for (const locale of settings.locales) {\n const outputPath = fileMapping[locale]?.[uploadedFile.fileName] ?? null;\n if (!outputPath) continue;\n if (!fs.existsSync(outputPath)) continue;\n\n const latestDownloaded = findLatestDownloadedVersion(\n entryMap,\n uploadedFile.fileId,\n locale\n );\n\n if (!latestDownloaded) continue;\n const downloadedVersion = latestDownloaded.entry;\n\n // Skip if the locale's local content matches the last recorded hash\n let knownEdited = false;\n if (downloadedVersion.postProcessHash) {\n try {\n // Hashed from the locale's share of the pipeline content, which is\n // what was recorded, so an untouched locale matches regardless of\n // the file's encoding or of edits to its other locales.\n const localFile = readFileContent(\n outputPath,\n uploadedFile.fileFormat\n );\n const localHash = hashStringSync(\n localeContent(localFile, uploadedFile.fileFormat, locale) ??\n emptyLocaleContent(localFile, uploadedFile.fileFormat)\n );\n if (localHash === downloadedVersion.postProcessHash) {\n continue;\n }\n knownEdited = true;\n } catch {\n // If hash check fails, fall through to diff\n }\n }\n\n candidates.push({\n branchId: uploadedFile.branchId,\n fileName: uploadedFile.fileName,\n fileId: uploadedFile.fileId,\n versionId: latestDownloaded.versionId,\n locale: locale,\n outputPath,\n fileFormat: uploadedFile.fileFormat,\n knownEdited,\n });\n }\n }\n\n const collectedDiffs: SubmitUserEditDiff[] = [];\n\n if (candidates.length > 0) {\n const fileQueryData = candidates.map((c) => ({\n versionId: c.versionId,\n locale: c.locale,\n fileId: c.fileId,\n branchId: c.branchId,\n }));\n\n // Single batched check to obtain translation IDs\n const checkResponse = await api.queryFileData({\n translatedFiles: fileQueryData,\n });\n const translatedFiles =\n checkResponse.translatedFiles?.filter((t) => t.completedAt) ?? [];\n\n // The server's copy of each candidate, keyed like the candidates\n type ServerPayload = { data: string; fileFormat: FileFormat };\n const serverPayloadByKey = new Map<string, ServerPayload>();\n try {\n const resp = await api.downloadFileBatch(\n translatedFiles.map((file) => ({\n branchId: file.branchId,\n fileId: file.fileId,\n locale: file.locale,\n versionId: file.versionId,\n }))\n );\n for (const f of resp?.files || []) {\n if (!f.locale) continue;\n serverPayloadByKey.set(\n `${f.branchId}:${f.fileId}:${f.versionId}:${f.locale}`,\n { data: f.data, fileFormat: f.fileFormat }\n );\n }\n } catch {\n // Ignore chunk failures; proceed with what we have\n }\n\n // Compute diffs using fetched server contents\n for (const c of candidates) {\n const key = `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`;\n const payload = serverPayloadByKey.get(key);\n // Absent means the batch did not return this file, so there is no\n // baseline. An empty payload is a baseline of nothing, which the user\n // may well have written against. When the recorded hash already showed\n // an edit, say so rather than leaving the run looking clean. An empty\n // map cannot tell a version the server does not have from a batch that\n // failed to return it, so the message covers both.\n if (!payload) {\n if (c.knownEdited) {\n const relativePath = getRelative(c.outputPath);\n const reason = `the ${c.locale} baseline recorded in the lockfile could not be retrieved, so the edit could not be compared`;\n logger.warn(unsavedJsonEditsWarning(relativePath, c.locale, reason));\n recordWarning('skipped_file', relativePath, reason);\n }\n continue;\n }\n\n // The locale's share of the payload, read on its own so a payload the\n // server sent malformed costs only its own locale. A catalog payload\n // that carries nothing for the locale is that file's empty payload, and\n // a baseline of nothing like any other.\n let serverContent: string;\n try {\n serverContent =\n localeContent(payload.data, payload.fileFormat, c.locale) ??\n emptyLocaleContent(payload.data, payload.fileFormat);\n } catch (error) {\n const relativePath = getRelative(c.outputPath);\n const reason = `The downloaded ${c.locale} translation could not be read (${\n error instanceof Error ? error.message : String(error)\n })`;\n logger.warn(`Skipping local edits to ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n const serverBytes = contentBytes(serverContent, payload.fileFormat);\n\n try {\n // Read the local file the same way the pipeline read it originally, so\n // a file stored differently on disk than the server's copy is compared\n // as content rather than as bytes. Otherwise every such file would read\n // as edited on every run. Then cut to this locale's share, so a file\n // that holds every locale is compared slice to slice.\n const local = localeContent(\n readFileContent(c.outputPath, c.fileFormat),\n c.fileFormat,\n c.locale\n );\n // A catalog that no longer carries the locale has nothing to submit\n if (local === undefined) continue;\n const localBytes = contentBytes(local, c.fileFormat);\n\n // Nothing was edited, so there is no diff to compute or report.\n if (localBytes.equals(serverBytes)) continue;\n\n // A unified diff and localContent are both UTF-8 text, and every text\n // format's content is UTF-8 by the time it reaches here. Only a binary\n // format's bytes — a Lottie zip, an image — have no text form at all. Say so:\n // the edit is real and will be lost on the next download.\n if (isBinaryFileFormat(c.fileFormat)) {\n const relativePath = getRelative(c.outputPath);\n const reason =\n 'Edited file is a binary format, so its changes cannot be submitted';\n logger.warn(`Skipping local edits to ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n\n const safeName = Buffer.from(\n `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`\n )\n .toString('base64')\n .replace(/=+$/g, '');\n const tempServerFile = path.join(tempDir, `${safeName}.server`);\n await fs.promises.writeFile(tempServerFile, serverBytes);\n\n // git diff reads bytes, so both sides are written from the content\n // they represent rather than diffing the file as it sits on disk.\n const tempLocalFile = path.join(tempDir, `${safeName}.local`);\n await fs.promises.writeFile(tempLocalFile, localBytes);\n\n const diff = await getGitUnifiedDiff(tempServerFile, tempLocalFile);\n for (const tempFile of [tempServerFile, tempLocalFile]) {\n try {\n await fs.promises.unlink(tempFile);\n } catch {\n // Ignore cleanup errors for temporary comparison files.\n }\n }\n\n if (diff && diff.trim().length > 0) {\n const rawLocalContent = localBytes.toString('utf8');\n\n // For JSON files with jsonSchema config, extract to composite format\n let localContent = rawLocalContent;\n if (\n c.fileName.endsWith('.json') &&\n settings.options?.jsonSchema &&\n c.locale !== settings.defaultLocale\n ) {\n const resolvedLocal = resolveLocalRefs(\n rawLocalContent,\n c.outputPath,\n settings\n );\n const extractedContent = extractJson(\n resolvedLocal.content,\n c.fileName,\n settings.options,\n c.locale,\n settings.defaultLocale\n );\n if (extractedContent) {\n const extracted = parseJson(extractedContent);\n // The submitted content replaces the stored translation, so\n // values missing from it would be erased.\n const unreadableRefs = unreadableRefsForLocale(\n resolvedLocal.unreadableRefs,\n resolvedLocal.content,\n c.fileName,\n c.locale,\n settings\n );\n const reason =\n unreadableRefs.length > 0\n ? `these $ref files could not be read: ${unreadableRefs.map((ref) => ref.refPath).join(', ')}`\n : !hasLeafValue(extracted)\n ? 'no translated values for that locale could be read from the file'\n : undefined;\n if (reason) {\n const relativePath = getRelative(c.outputPath);\n logger.warn(\n unsavedJsonEditsWarning(relativePath, c.locale, reason)\n );\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n if (isDeepStrictEqual(extracted, parseJson(serverContent))) {\n continue;\n }\n localContent = extractedContent;\n }\n } else if (\n (c.fileName.endsWith('.yaml') || c.fileName.endsWith('.yml')) &&\n settings.options?.yamlSchema &&\n c.locale !== settings.defaultLocale\n ) {\n const extractedContent = extractYaml(\n rawLocalContent,\n c.fileName,\n settings.options\n );\n if (extractedContent) {\n localContent = extractedContent;\n }\n }\n\n collectedDiffs.push({\n fileName: c.fileName,\n locale: c.locale,\n diff,\n branchId: c.branchId,\n versionId: c.versionId,\n fileId: c.fileId,\n localContent,\n } satisfies SubmitUserEditDiff);\n }\n } catch {\n // Ignore failures for this file\n }\n }\n }\n\n if (collectedDiffs.length > 0) {\n await api.submitUserEditDiffs({ diffs: collectedDiffs });\n }\n\n return collectedDiffs.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,2BACJ,cACA,QACA,WAEA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,kBAAkB,aAAa,sBAAsB;CACnE,KAAK;CACL,aAAa;CACd,CAAC;AAEJ,MAAM,oBACJ,SACA,YACA,aACyD;AACzD,KAAI,CAAC,kBAAkB,YAAY,SAAS,QAAQ,CAClD,QAAO;EAAE;EAAS,gBAAgB,EAAE;EAAE;AAExC,KAAI;EACF,MAAM,EAAE,UAAU,mBAAmB,oBACnC,KAAK,MAAM,QAAQ,EACnB,WACD;AACD,SAAO;GAAE,SAAS,KAAK,UAAU,UAAU,MAAM,EAAE;GAAE;GAAgB;SAC/D;AACN,SAAO;GAAE;GAAS,gBAAgB,EAAE;GAAE;;;;;;;;AAS1C,MAAM,2BACJ,gBACA,iBACA,UACA,QACA,aACoB;AACpB,KAAI,eAAe,WAAW,EAAG,QAAO,EAAE;CAC1C,MAAM,YAAY,mBAChB,SAAS,WAAW,EAAE,EACtB,SACD,EAAE;CACH,MAAM,OAAO,UAAU,gBAAgB;AACvC,KAAI,CAAC,aAAa,SAAS,KAAA,EAAW,QAAO;CAE7C,MAAM,YAAY,SAAS,SAAS,kCAChC,IAAI,uBAAuB,OAAO,GAClC;CACJ,MAAM,sBAAgC,EAAE;AACxC,M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} from "../../utils/hash.js";
2
+ import { hashBytesSync, hashStringSync, hashVersionId } from "../../utils/hash.js";
3
3
  import { logErrorAndExit } from "../../console/logging.js";
4
4
  import { getRelative, readBinaryFileBase64, readFile } from "../../fs/findFilepath.js";
5
5
  import { fileEncodingSkipReason, lottieExpressionsError, xcstringsSourceLanguageMismatchError } from "../../console/index.js";
6
- import { SUPPORTED_FILE_EXTENSIONS } from "./supportedFiles.js";
6
+ import { IMAGE_FILE_TYPES, SUPPORTED_FILE_EXTENSIONS } from "./supportedFiles.js";
7
7
  import { CONFIG_FILE_TYPE_TO_FILE_FORMAT, getTransformFormatProperty } from "./transformFormat.js";
8
8
  import { api } from "../../utils/api.js";
9
9
  import { readFileContent } from "../../fs/fileContent.js";
@@ -208,6 +208,28 @@ async function aggregateFiles(settings) {
208
208
  if (expressionOffenders.length > 0) logErrorAndExit(lottieExpressionsError(expressionOffenders));
209
209
  files.push(...lottieFiles);
210
210
  }
211
+ for (const fileType of IMAGE_FILE_TYPES) {
212
+ if (!filePaths[fileType]) continue;
213
+ const imageFiles = filePaths[fileType].map((filePath) => {
214
+ const relativePath = getRelative(filePath);
215
+ const content = readBinaryFileBase64(filePath);
216
+ if (!content) {
217
+ logger.warn(`Skipping ${relativePath}: file is empty or unreadable`);
218
+ recordWarning("skipped_file", relativePath, "File is empty or unreadable");
219
+ return null;
220
+ }
221
+ return {
222
+ content,
223
+ fileName: relativePath,
224
+ fileFormat: CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType],
225
+ ...getTransformFormatProperty(settings, fileType),
226
+ fileId: hashStringSync(relativePath),
227
+ versionId: hashBytesSync(Buffer.from(content, "base64")),
228
+ locale: settings.defaultLocale
229
+ };
230
+ }).filter((file) => file !== null);
231
+ files.push(...imageFiles);
232
+ }
211
233
  for (const [fileType, fileFormat] of [
212
234
  ["dotStrings", "DOT_STRINGS"],
213
235
  ["dotStringsdict", "DOT_STRINGSDICT"],
@@ -283,7 +305,7 @@ async function aggregateFiles(settings) {
283
305
  files.push(...xcstringsFiles);
284
306
  }
285
307
  for (const fileType of SUPPORTED_FILE_EXTENSIONS) {
286
- if (fileType === "json" || fileType === "yaml" || fileType === "twilioContentJson" || fileType === "lottie" || fileType === "dotStrings" || fileType === "dotStringsdict" || fileType === "androidStrings" || fileType === "xcstrings" || fileType === "srt" || fileType === "resx") continue;
308
+ if (fileType === "json" || fileType === "yaml" || fileType === "twilioContentJson" || fileType === "lottie" || fileType === "dotStrings" || fileType === "dotStringsdict" || fileType === "androidStrings" || fileType === "xcstrings" || fileType === "srt" || fileType === "resx" || IMAGE_FILE_TYPES.includes(fileType)) continue;
287
309
  if (filePaths[fileType]) {
288
310
  const parsed = filePaths[fileType].map((filePath) => {
289
311
  const content = readFile(filePath);
@@ -1 +1 @@
1
- {"version":3,"file":"aggregateFiles.js","names":[],"sources":["../../../src/formats/files/aggregateFiles.ts"],"sourcesContent":["import { logger } from '../../console/logger.js';\nimport { logErrorAndExit } from '../../console/logging.js';\nimport {\n fileEncodingSkipReason,\n lottieExpressionsError,\n xcstringsSourceLanguageMismatchError,\n} from '../../console/index.js';\nimport { recordWarning } from '../../state/translateWarnings.js';\nimport { lottieHasExpressions } from './detectLottieExpressions.js';\nimport {\n getRelative,\n readFile,\n readBinaryFileBase64,\n} from '../../fs/findFilepath.js';\nimport { readFileContent } from '../../fs/fileContent.js';\nimport { Settings } from '../../types/index.js';\nimport type { DataFormat, FileToUpload } from '../../types/data.js';\nimport { SUPPORTED_FILE_EXTENSIONS } from './supportedFiles.js';\nimport { parseJson } from '../json/parseJson.js';\nimport {\n parseXcstringsCatalog,\n serializeXcstringsSlice,\n sliceSourceCatalog,\n type XcstringsCatalog,\n} from '../xcstrings/parseXcstrings.js';\nimport {\n resolveMintlifyRefs,\n shouldResolveRefs,\n} from '../../utils/resolveMintlifyRefs.js';\nimport { storeRefMap } from '../../state/mintlifyRefMap.js';\nimport parseYaml from '../yaml/parseYaml.js';\nimport { validateYamlSchema } from '../yaml/utils.js';\nimport { flattenJson } from '../json/flattenJson.js';\nimport type { JSONObject } from '../../types/data/json.js';\nimport YAML from 'yaml';\nimport { determineLibrary } from '../../fs/determineFramework/index.js';\nimport { hashStringSync, hashVersionId } from '../../utils/hash.js';\nimport { api } from '../../utils/api.js';\nimport { preprocessContent } from './preprocessContent.js';\nimport {\n parseKeyedMetadata,\n type KeyedMetadata,\n} from '../parseKeyedMetadata.js';\nimport { buildPublishMap } from '../../utils/resolvePublish.js';\nimport {\n CONFIG_FILE_TYPE_TO_FILE_FORMAT,\n getTransformFormatProperty,\n} from './transformFormat.js';\n\n/**\n * Checks if a file path is a metadata companion file (e.g. foo.metadata.json)\n * AND its corresponding source file (e.g. foo.json) exists in the file list.\n * If both conditions are true, the metadata file should be skipped as a translation source.\n */\nfunction isCompanionMetadataFile(\n filePath: string,\n allFilePaths: string[]\n): boolean {\n const metadataPattern = /\\.metadata\\.(json|yaml|yml)$/;\n if (!metadataPattern.test(filePath)) return false;\n\n // Derive the source file path: foo.metadata.json -> foo.json\n const sourceFilePath = filePath.replace(\n /\\.metadata\\.(json|yaml|yml)$/,\n '.$1'\n );\n return allFilePaths.includes(sourceFilePath);\n}\n\n/**\n * Warns and records a skipped file when its content does not parse as JSON or\n * YAML, so the caller can leave the file out of the upload.\n */\nexport function isUnparsableFile(\n content: string,\n relativePath: string,\n format: 'JSON' | 'YAML'\n): boolean {\n try {\n if (format === 'JSON') JSON.parse(content);\n else YAML.parse(content);\n return false;\n } catch {\n const reason = `${format} file is not parsable`;\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n return true;\n }\n}\n\nexport async function aggregateFiles(\n settings: Settings\n): Promise<{ files: FileToUpload[]; publishMap: Map<string, boolean> }> {\n // Aggregate all files to translate\n const files: FileToUpload[] = [];\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return { files, publishMap: new Map<string, boolean>() };\n }\n\n const { resolvedPaths: filePaths } = settings.files;\n // Tolerate partially-constructed settings from programmatic callers\n const requiresReviewPaths =\n settings.files.requiresReviewPaths ?? new Set<string>();\n const skipValidation = settings.options?.skipFileValidation;\n\n // Build publish map upfront from resolved paths.\n const publishMap = buildPublishMap(filePaths, settings);\n\n // Process JSON files\n if (filePaths.json) {\n const { library, additionalModules } = determineLibrary();\n\n // Determine dataFormat for JSONs\n let dataFormat: DataFormat;\n if (library === 'next-intl') {\n dataFormat = 'ICU';\n } else if (library === 'i18next') {\n if (additionalModules.includes('i18next-icu')) {\n dataFormat = 'ICU';\n } else {\n dataFormat = 'I18NEXT';\n }\n } else {\n dataFormat = 'STRING';\n }\n\n const jsonFiles = filePaths.json\n .filter((filePath) => !isCompanionMetadataFile(filePath, filePaths.json!))\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n if (\n !skipValidation?.json &&\n isUnparsableFile(content, relativePath, 'JSON')\n ) {\n return null;\n }\n\n // Resolve $ref before parsing if configured\n let contentForParsing = content;\n if (shouldResolveRefs(filePath, settings.options)) {\n try {\n const json = JSON.parse(content);\n const { resolved, refMap } = resolveMintlifyRefs(json, filePath);\n storeRefMap(refMap);\n contentForParsing = JSON.stringify(resolved, null, 2);\n } catch {\n // JSON parse errors are handled below by parseJson\n }\n }\n\n const parsedJson = parseJson(\n contentForParsing,\n filePath,\n settings.options || {},\n settings.defaultLocale\n );\n\n // Detect companion metadata file\n let keyedMetadata: KeyedMetadata | undefined;\n let parsedContent: JSONObject | undefined;\n try {\n parsedContent = JSON.parse(content) as JSONObject;\n } catch {\n // Content not parsable — skip metadata detection\n }\n if (parsedContent) {\n const rawMetadata = parseKeyedMetadata(filePath, parsedContent);\n if (rawMetadata) {\n // Run metadata through the same include/composite schema as the source\n // so key paths align at translation time\n const transformed = parseJson(\n JSON.stringify(rawMetadata),\n filePath,\n settings.options || {},\n settings.defaultLocale,\n false\n );\n const transformedMetadata = JSON.parse(transformed);\n\n // Filter metadata to only keep keys that exist in the transformed source\n // This prevents misaligned entries from wide JSONPath patterns\n const sourceKeys = new Set(Object.keys(JSON.parse(parsedJson)));\n const filtered = Object.fromEntries(\n Object.entries(transformedMetadata).filter(([k]) =>\n sourceKeys.has(k)\n )\n ) as KeyedMetadata;\n\n if (Object.keys(filtered).length > 0) {\n keyedMetadata = filtered;\n } else {\n logger.warn(\n `Companion metadata found for ${relativePath} but no keys aligned with the JSON schema — metadata was not attached`\n );\n }\n }\n }\n\n return {\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n parsedJson,\n requiresReviewPaths.has(filePath)\n ),\n content: parsedJson,\n fileName: relativePath,\n fileFormat: 'JSON' as const,\n ...getTransformFormatProperty(settings, 'json'),\n dataFormat,\n locale: settings.defaultLocale,\n ...(keyedMetadata && {\n formatMetadata: { keyedMetadata },\n }),\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (!file) return false;\n if (typeof file.content !== 'string' || !file.content.trim()) {\n logger.warn(`Skipping ${file.fileName}: JSON file is empty`);\n recordWarning('skipped_file', file.fileName, 'JSON file is empty');\n return false;\n }\n return true;\n });\n files.push(...jsonFiles.filter((file) => file !== null));\n }\n\n // Process YAML files\n if (filePaths.yaml) {\n const yamlFiles = filePaths.yaml\n .filter((filePath) => !isCompanionMetadataFile(filePath, filePaths.yaml!))\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n if (\n !skipValidation?.yaml &&\n isUnparsableFile(content, relativePath, 'YAML')\n ) {\n return null;\n }\n\n const { content: parsedYaml, fileFormat } = parseYaml(\n content,\n filePath,\n settings.options || {}\n );\n\n // Detect companion metadata file\n let keyedMetadata: KeyedMetadata | undefined;\n try {\n const parsedYamlContent = YAML.parse(content);\n const rawMetadata = parseKeyedMetadata(filePath, parsedYamlContent);\n if (rawMetadata) {\n const yamlSchema = validateYamlSchema(\n settings.options || {},\n filePath\n );\n if (yamlSchema?.include) {\n // Flatten metadata through the same include schema as the source\n const flattened = flattenJson(rawMetadata, yamlSchema.include);\n // Filter to only keep keys that exist in the transformed source\n const sourceKeys = new Set(Object.keys(JSON.parse(parsedYaml)));\n const filtered = Object.fromEntries(\n Object.entries(flattened).filter(([k]) => sourceKeys.has(k))\n ) as KeyedMetadata;\n if (Object.keys(filtered).length > 0) {\n keyedMetadata = filtered;\n } else {\n logger.warn(\n `Companion metadata found for ${relativePath} but no keys aligned with the YAML schema — metadata was not attached`\n );\n }\n } else {\n keyedMetadata = rawMetadata;\n }\n }\n } catch {\n // Content not parsable as YAML — skip metadata detection\n }\n\n return {\n content: parsedYaml,\n fileName: relativePath,\n fileFormat,\n ...getTransformFormatProperty(settings, 'yaml'),\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n parsedYaml,\n requiresReviewPaths.has(filePath)\n ),\n locale: settings.defaultLocale,\n ...(keyedMetadata && {\n formatMetadata: { keyedMetadata },\n }),\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (!file || typeof file.content !== 'string' || !file.content.trim()) {\n logger.warn(\n `Skipping ${file?.fileName ?? 'unknown'}: YAML file is empty`\n );\n recordWarning(\n 'skipped_file',\n file?.fileName ?? 'unknown',\n 'YAML file is empty'\n );\n return false;\n }\n return true;\n });\n files.push(...yamlFiles.filter((file) => file !== null));\n }\n\n // Process Twilio Content JSON files\n if (filePaths.twilioContentJson) {\n const twilioContentJsonFiles = filePaths.twilioContentJson\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n if (\n !skipValidation?.json &&\n isUnparsableFile(content, relativePath, 'JSON')\n ) {\n return null;\n }\n\n const parsedJson = parseJson(\n content,\n filePath,\n settings.options || {},\n settings.defaultLocale\n );\n\n return {\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n parsedJson,\n requiresReviewPaths.has(filePath)\n ),\n content: parsedJson,\n fileName: relativePath,\n fileFormat: 'TWILIO_CONTENT_JSON' as const,\n ...getTransformFormatProperty(settings, 'twilioContentJson'),\n dataFormat: 'STRING' as const,\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (!file) return false;\n if (typeof file.content !== 'string' || !file.content.trim()) {\n logger.warn(`Skipping ${file.fileName}: JSON file is empty`);\n recordWarning('skipped_file', file.fileName, 'JSON file is empty');\n return false;\n }\n return true;\n });\n files.push(...twilioContentJsonFiles.filter((file) => file !== null));\n }\n\n // Process Lottie files (binary zip bundles). Content is read as raw bytes and\n // carried base64-encoded end-to-end; the downloaded translation is written\n // back as bytes. No text parsing/merge.\n if (filePaths.lottie) {\n // Lottie files carrying After Effects expressions (executable JS) are\n // rejected outright — collect every offender, then fail once with all of\n // them named rather than aborting on the first.\n const expressionOffenders: string[] = [];\n const lottieFiles = filePaths.lottie\n .map((filePath) => {\n const content = readBinaryFileBase64(filePath);\n const relativePath = getRelative(filePath);\n if (!content) {\n logger.warn(`Skipping ${relativePath}: file is empty or unreadable`);\n recordWarning(\n 'skipped_file',\n relativePath,\n 'File is empty or unreadable'\n );\n return null;\n }\n if (lottieHasExpressions(content)) {\n expressionOffenders.push(relativePath);\n return null;\n }\n return {\n content,\n fileName: relativePath,\n fileFormat: 'LOTTIE' as const,\n ...getTransformFormatProperty(settings, 'lottie'),\n fileId: hashStringSync(relativePath),\n versionId: hashStringSync(content),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => file !== null);\n if (expressionOffenders.length > 0) {\n logErrorAndExit(lottieExpressionsError(expressionOffenders));\n }\n files.push(...lottieFiles);\n }\n\n // These formats are uploaded verbatim. Their backslash escapes, format\n // specifiers, timing lines, entity escapes and line breaks must survive\n // byte-for-byte, so they skip the generic markdown-oriented preprocessing\n // below.\n for (const [fileType, fileFormat] of [\n ['dotStrings', 'DOT_STRINGS'],\n ['dotStringsdict', 'DOT_STRINGSDICT'],\n ['androidStrings', 'ANDROID_STRINGS'],\n ['srt', 'SRT'],\n ['resx', 'RESX'],\n ] as const) {\n if (!filePaths[fileType]) continue;\n const verbatimFiles = filePaths[fileType]\n .map((filePath) => {\n const relativePath = getRelative(filePath);\n // Reading is the one place an encoding is resolved; from here on the\n // content is a UTF-8 string like every other format's.\n let content: string;\n try {\n content = readFileContent(filePath, fileFormat);\n } catch (error) {\n // One unreadable file should not abort the whole run: skip it and\n // report it in the summary\n const reason = fileEncodingSkipReason(error);\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n return null;\n }\n return {\n content,\n fileName: relativePath,\n fileFormat,\n ...getTransformFormatProperty(settings, fileType),\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(content, requiresReviewPaths.has(filePath)),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (!file) return false;\n if (!file.content.trim()) {\n logger.warn(`Skipping ${file.fileName}: File is empty`);\n recordWarning('skipped_file', file.fileName, 'File is empty');\n return false;\n }\n return true;\n });\n files.push(...verbatimFiles.filter((file) => file !== null));\n }\n\n // Process Apple .xcstrings catalogs. One catalog holds every locale; only the\n // source-language slice is uploaded as the source document. The slice is\n // hashed into versionId, so an unchanged catalog re-slices byte-identically\n // and does not re-upload.\n if (filePaths.xcstrings) {\n const sourceLanguageMismatches: { file: string; sourceLanguage: string }[] =\n [];\n const xcstringsFiles = filePaths.xcstrings\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n let catalog: XcstringsCatalog;\n try {\n catalog = parseXcstringsCatalog(content);\n } catch (error) {\n const reason =\n error instanceof Error\n ? error.message\n : 'xcstrings file is not parsable';\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n return null;\n }\n // Slicing follows the catalog's own sourceLanguage while the upload is\n // labeled settings.defaultLocale; a mismatch would upload mislabeled\n // source content, so it is a configuration error that stops the run\n // rather than a skipped file. The configured locale may be a custom\n // alias, so canonical forms are compared.\n if (\n api.resolveCanonicalLocale(catalog.sourceLanguage) !==\n api.resolveCanonicalLocale(settings.defaultLocale)\n ) {\n sourceLanguageMismatches.push({\n file: relativePath,\n sourceLanguage: catalog.sourceLanguage,\n });\n return null;\n }\n const sourceSlice = serializeXcstringsSlice(\n sliceSourceCatalog(catalog)\n );\n\n return {\n content: sourceSlice,\n fileName: relativePath,\n fileFormat: 'XCSTRINGS' as const,\n ...getTransformFormatProperty(settings, 'xcstrings'),\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n sourceSlice,\n requiresReviewPaths.has(filePath)\n ),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => file !== null);\n if (sourceLanguageMismatches.length > 0) {\n logErrorAndExit(\n xcstringsSourceLanguageMismatchError(\n sourceLanguageMismatches,\n settings.defaultLocale\n )\n );\n }\n files.push(...xcstringsFiles);\n }\n\n for (const fileType of SUPPORTED_FILE_EXTENSIONS) {\n if (\n fileType === 'json' ||\n fileType === 'yaml' ||\n fileType === 'twilioContentJson' ||\n fileType === 'lottie' ||\n fileType === 'dotStrings' ||\n fileType === 'dotStringsdict' ||\n fileType === 'androidStrings' ||\n fileType === 'xcstrings' ||\n fileType === 'srt' ||\n fileType === 'resx'\n )\n continue;\n if (filePaths[fileType]) {\n const parsed = filePaths[fileType]\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n const processed = preprocessContent(\n content,\n relativePath,\n fileType,\n settings\n );\n\n if (typeof processed !== 'string') {\n logger.warn(`Skipping ${relativePath}: ${processed.skip}`);\n recordWarning('skipped_file', relativePath, processed.skip);\n return null;\n }\n\n return {\n content: processed,\n fileName: relativePath,\n fileFormat: CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType],\n ...getTransformFormatProperty(settings, fileType),\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n processed,\n requiresReviewPaths.has(filePath)\n ),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (\n !file ||\n typeof file.content !== 'string' ||\n !file.content.trim()\n ) {\n logger.warn(\n `Skipping ${file?.fileName ?? 'unknown'}: File is empty after sanitization`\n );\n recordWarning(\n 'skipped_file',\n file?.fileName ?? 'unknown',\n 'File is empty after sanitization'\n );\n return false;\n }\n return true;\n });\n files.push(...parsed.filter((file) => file !== null));\n }\n }\n\n // Remove stale entries for files that were skipped during validation\n const validFileIds = new Set(files.map((f) => f.fileId));\n for (const fileId of publishMap.keys()) {\n if (!validFileIds.has(fileId)) {\n publishMap.delete(fileId);\n }\n }\n\n return { files, publishMap };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAS,wBACP,UACA,cACS;AAET,KAAI,CAAC,+BAAgB,KAAK,SAAS,CAAE,QAAO;CAG5C,MAAM,iBAAiB,SAAS,QAC9B,gCACA,MACD;AACD,QAAO,aAAa,SAAS,eAAe;;;;;;AAO9C,SAAgB,iBACd,SACA,cACA,QACS;AACT,KAAI;AACF,MAAI,WAAW,OAAQ,MAAK,MAAM,QAAQ;MACrC,MAAK,MAAM,QAAQ;AACxB,SAAO;SACD;EACN,MAAM,SAAS,GAAG,OAAO;AACzB,SAAO,KAAK,YAAY,aAAa,IAAI,SAAS;AAClD,gBAAc,gBAAgB,cAAc,OAAO;AACnD,SAAO;;;AAIX,eAAsB,eACpB,UACsE;CAEtE,MAAM,QAAwB,EAAE;AAChC,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC,QAAO;EAAE;EAAO,4BAAY,IAAI,KAAsB;EAAE;CAG1D,MAAM,EAAE,eAAe,cAAc,SAAS;CAE9C,MAAM,sBACJ,SAAS,MAAM,uCAAuB,IAAI,KAAa;CACzD,MAAM,iBAAiB,SAAS,SAAS;CAGzC,MAAM,aAAa,gBAAgB,WAAW,SAAS;AAGvD,KAAI,UAAU,MAAM;EAClB,MAAM,EAAE,SAAS,sBAAsB,kBAAkB;EAGzD,IAAI;AACJ,MAAI,YAAY,YACd,cAAa;WACJ,YAAY,UACrB,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AAM,KAAK,GAAG,eAAe;;AAG/B,MAAK,MAAM,YAAY,2BAA2B;AAChD,MACE,aAAa,UACb,aAAa,UACb,aAAa,uBACb,aAAa,YACb,aAAa,gBACb,aAAa,oBACb,aAAa,oBACb,aAAa,eACb,aAAa,SACb,aAAa,OAEb;AACF,MAAI,UAAU,WAAW;GACvB,MAAM,SAAS,UAAU,UACtB,KAAK,aAAa;IACjB,MAAM,UAAU,SAAS,SAAS;IAClC,MAAM,eAAe,YAAY,SAAS;IAE1C,MAAM,YAAY,kBAChB,SACA,cACA,UACA,SACD;AAED,QAAI,OAAO,cAAc,UAAU;AACjC,YAAO,KAAK,YAAY,aAAa,IAAI,UAAU,OAAO;AAC1D,mBAAc,gBAAgB,cAAc,UAAU,KAAK;AAC3D,YAAO;;AAGT,WAAO;KACL,SAAS;KACT,UAAU;KACV,YAAY,gCAAgC;KAC5C,GAAG,2BAA2B,UAAU,SAAS;KACjD,QAAQ,eAAe,aAAa;KACpC,WAAW,cACT,WACA,oBAAoB,IAAI,SAAS,CAClC;KACD,QAAQ,SAAS;KAClB;KACD,CACD,QAAQ,SAAS;AAChB,QACE,CAAC,QACD,OAAO,KAAK,YAAY,YACxB,CAAC,KAAK,QAAQ,MAAM,EACpB;AACA,YAAO,KACL,YAAY,MAAM,YAAY,UAAU,oCACzC;AACD,mBACE,gBACA,MAAM,YAAY,WAClB,mCACD;AACD,YAAO;;AAET,WAAO;KACP;AACJ,SAAM,KAAK,GAAG,OAAO,QAAQ,SAAS,SAAS,KAAK,CAAC;;;CAKzD,MAAM,eAAe,IAAI,IAAI,MAAM,KAAK,MAAM,EAAE,OAAO,CAAC;AACxD,MAAK,MAAM,UAAU,WAAW,MAAM,CACpC,KAAI,CAAC,aAAa,IAAI,OAAO,CAC3B,YAAW,OAAO,OAAO;AAI7B,QAAO;EAAE;EAAO;EAAY"}
1
+ {"version":3,"file":"aggregateFiles.js","names":[],"sources":["../../../src/formats/files/aggregateFiles.ts"],"sourcesContent":["import { logger } from '../../console/logger.js';\nimport { logErrorAndExit } from '../../console/logging.js';\nimport {\n fileEncodingSkipReason,\n lottieExpressionsError,\n xcstringsSourceLanguageMismatchError,\n} from '../../console/index.js';\nimport { recordWarning } from '../../state/translateWarnings.js';\nimport { lottieHasExpressions } from './detectLottieExpressions.js';\nimport {\n getRelative,\n readFile,\n readBinaryFileBase64,\n} from '../../fs/findFilepath.js';\nimport { readFileContent } from '../../fs/fileContent.js';\nimport { Settings } from '../../types/index.js';\nimport type { DataFormat, FileToUpload } from '../../types/data.js';\nimport {\n IMAGE_FILE_TYPES,\n SUPPORTED_FILE_EXTENSIONS,\n} from './supportedFiles.js';\nimport { parseJson } from '../json/parseJson.js';\nimport {\n parseXcstringsCatalog,\n serializeXcstringsSlice,\n sliceSourceCatalog,\n type XcstringsCatalog,\n} from '../xcstrings/parseXcstrings.js';\nimport {\n resolveMintlifyRefs,\n shouldResolveRefs,\n} from '../../utils/resolveMintlifyRefs.js';\nimport { storeRefMap } from '../../state/mintlifyRefMap.js';\nimport parseYaml from '../yaml/parseYaml.js';\nimport { validateYamlSchema } from '../yaml/utils.js';\nimport { flattenJson } from '../json/flattenJson.js';\nimport type { JSONObject } from '../../types/data/json.js';\nimport YAML from 'yaml';\nimport { determineLibrary } from '../../fs/determineFramework/index.js';\nimport {\n hashBytesSync,\n hashStringSync,\n hashVersionId,\n} from '../../utils/hash.js';\nimport { api } from '../../utils/api.js';\nimport { preprocessContent } from './preprocessContent.js';\nimport {\n parseKeyedMetadata,\n type KeyedMetadata,\n} from '../parseKeyedMetadata.js';\nimport { buildPublishMap } from '../../utils/resolvePublish.js';\nimport {\n CONFIG_FILE_TYPE_TO_FILE_FORMAT,\n getTransformFormatProperty,\n} from './transformFormat.js';\n\n/**\n * Checks if a file path is a metadata companion file (e.g. foo.metadata.json)\n * AND its corresponding source file (e.g. foo.json) exists in the file list.\n * If both conditions are true, the metadata file should be skipped as a translation source.\n */\nfunction isCompanionMetadataFile(\n filePath: string,\n allFilePaths: string[]\n): boolean {\n const metadataPattern = /\\.metadata\\.(json|yaml|yml)$/;\n if (!metadataPattern.test(filePath)) return false;\n\n // Derive the source file path: foo.metadata.json -> foo.json\n const sourceFilePath = filePath.replace(\n /\\.metadata\\.(json|yaml|yml)$/,\n '.$1'\n );\n return allFilePaths.includes(sourceFilePath);\n}\n\n/**\n * Warns and records a skipped file when its content does not parse as JSON or\n * YAML, so the caller can leave the file out of the upload.\n */\nexport function isUnparsableFile(\n content: string,\n relativePath: string,\n format: 'JSON' | 'YAML'\n): boolean {\n try {\n if (format === 'JSON') JSON.parse(content);\n else YAML.parse(content);\n return false;\n } catch {\n const reason = `${format} file is not parsable`;\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n return true;\n }\n}\n\nexport async function aggregateFiles(\n settings: Settings\n): Promise<{ files: FileToUpload[]; publishMap: Map<string, boolean> }> {\n // Aggregate all files to translate\n const files: FileToUpload[] = [];\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return { files, publishMap: new Map<string, boolean>() };\n }\n\n const { resolvedPaths: filePaths } = settings.files;\n // Tolerate partially-constructed settings from programmatic callers\n const requiresReviewPaths =\n settings.files.requiresReviewPaths ?? new Set<string>();\n const skipValidation = settings.options?.skipFileValidation;\n\n // Build publish map upfront from resolved paths.\n const publishMap = buildPublishMap(filePaths, settings);\n\n // Process JSON files\n if (filePaths.json) {\n const { library, additionalModules } = determineLibrary();\n\n // Determine dataFormat for JSONs\n let dataFormat: DataFormat;\n if (library === 'next-intl') {\n dataFormat = 'ICU';\n } else if (library === 'i18next') {\n if (additionalModules.includes('i18next-icu')) {\n dataFormat = 'ICU';\n } else {\n dataFormat = 'I18NEXT';\n }\n } else {\n dataFormat = 'STRING';\n }\n\n const jsonFiles = filePaths.json\n .filter((filePath) => !isCompanionMetadataFile(filePath, filePaths.json!))\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n if (\n !skipValidation?.json &&\n isUnparsableFile(content, relativePath, 'JSON')\n ) {\n return null;\n }\n\n // Resolve $ref before parsing if configured\n let contentForParsing = content;\n if (shouldResolveRefs(filePath, settings.options)) {\n try {\n const json = JSON.parse(content);\n const { resolved, refMap } = resolveMintlifyRefs(json, filePath);\n storeRefMap(refMap);\n contentForParsing = JSON.stringify(resolved, null, 2);\n } catch {\n // JSON parse errors are handled below by parseJson\n }\n }\n\n const parsedJson = parseJson(\n contentForParsing,\n filePath,\n settings.options || {},\n settings.defaultLocale\n );\n\n // Detect companion metadata file\n let keyedMetadata: KeyedMetadata | undefined;\n let parsedContent: JSONObject | undefined;\n try {\n parsedContent = JSON.parse(content) as JSONObject;\n } catch {\n // Content not parsable — skip metadata detection\n }\n if (parsedContent) {\n const rawMetadata = parseKeyedMetadata(filePath, parsedContent);\n if (rawMetadata) {\n // Run metadata through the same include/composite schema as the source\n // so key paths align at translation time\n const transformed = parseJson(\n JSON.stringify(rawMetadata),\n filePath,\n settings.options || {},\n settings.defaultLocale,\n false\n );\n const transformedMetadata = JSON.parse(transformed);\n\n // Filter metadata to only keep keys that exist in the transformed source\n // This prevents misaligned entries from wide JSONPath patterns\n const sourceKeys = new Set(Object.keys(JSON.parse(parsedJson)));\n const filtered = Object.fromEntries(\n Object.entries(transformedMetadata).filter(([k]) =>\n sourceKeys.has(k)\n )\n ) as KeyedMetadata;\n\n if (Object.keys(filtered).length > 0) {\n keyedMetadata = filtered;\n } else {\n logger.warn(\n `Companion metadata found for ${relativePath} but no keys aligned with the JSON schema — metadata was not attached`\n );\n }\n }\n }\n\n return {\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n parsedJson,\n requiresReviewPaths.has(filePath)\n ),\n content: parsedJson,\n fileName: relativePath,\n fileFormat: 'JSON' as const,\n ...getTransformFormatProperty(settings, 'json'),\n dataFormat,\n locale: settings.defaultLocale,\n ...(keyedMetadata && {\n formatMetadata: { keyedMetadata },\n }),\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (!file) return false;\n if (typeof file.content !== 'string' || !file.content.trim()) {\n logger.warn(`Skipping ${file.fileName}: JSON file is empty`);\n recordWarning('skipped_file', file.fileName, 'JSON file is empty');\n return false;\n }\n return true;\n });\n files.push(...jsonFiles.filter((file) => file !== null));\n }\n\n // Process YAML files\n if (filePaths.yaml) {\n const yamlFiles = filePaths.yaml\n .filter((filePath) => !isCompanionMetadataFile(filePath, filePaths.yaml!))\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n if (\n !skipValidation?.yaml &&\n isUnparsableFile(content, relativePath, 'YAML')\n ) {\n return null;\n }\n\n const { content: parsedYaml, fileFormat } = parseYaml(\n content,\n filePath,\n settings.options || {}\n );\n\n // Detect companion metadata file\n let keyedMetadata: KeyedMetadata | undefined;\n try {\n const parsedYamlContent = YAML.parse(content);\n const rawMetadata = parseKeyedMetadata(filePath, parsedYamlContent);\n if (rawMetadata) {\n const yamlSchema = validateYamlSchema(\n settings.options || {},\n filePath\n );\n if (yamlSchema?.include) {\n // Flatten metadata through the same include schema as the source\n const flattened = flattenJson(rawMetadata, yamlSchema.include);\n // Filter to only keep keys that exist in the transformed source\n const sourceKeys = new Set(Object.keys(JSON.parse(parsedYaml)));\n const filtered = Object.fromEntries(\n Object.entries(flattened).filter(([k]) => sourceKeys.has(k))\n ) as KeyedMetadata;\n if (Object.keys(filtered).length > 0) {\n keyedMetadata = filtered;\n } else {\n logger.warn(\n `Companion metadata found for ${relativePath} but no keys aligned with the YAML schema — metadata was not attached`\n );\n }\n } else {\n keyedMetadata = rawMetadata;\n }\n }\n } catch {\n // Content not parsable as YAML — skip metadata detection\n }\n\n return {\n content: parsedYaml,\n fileName: relativePath,\n fileFormat,\n ...getTransformFormatProperty(settings, 'yaml'),\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n parsedYaml,\n requiresReviewPaths.has(filePath)\n ),\n locale: settings.defaultLocale,\n ...(keyedMetadata && {\n formatMetadata: { keyedMetadata },\n }),\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (!file || typeof file.content !== 'string' || !file.content.trim()) {\n logger.warn(\n `Skipping ${file?.fileName ?? 'unknown'}: YAML file is empty`\n );\n recordWarning(\n 'skipped_file',\n file?.fileName ?? 'unknown',\n 'YAML file is empty'\n );\n return false;\n }\n return true;\n });\n files.push(...yamlFiles.filter((file) => file !== null));\n }\n\n // Process Twilio Content JSON files\n if (filePaths.twilioContentJson) {\n const twilioContentJsonFiles = filePaths.twilioContentJson\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n if (\n !skipValidation?.json &&\n isUnparsableFile(content, relativePath, 'JSON')\n ) {\n return null;\n }\n\n const parsedJson = parseJson(\n content,\n filePath,\n settings.options || {},\n settings.defaultLocale\n );\n\n return {\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n parsedJson,\n requiresReviewPaths.has(filePath)\n ),\n content: parsedJson,\n fileName: relativePath,\n fileFormat: 'TWILIO_CONTENT_JSON' as const,\n ...getTransformFormatProperty(settings, 'twilioContentJson'),\n dataFormat: 'STRING' as const,\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (!file) return false;\n if (typeof file.content !== 'string' || !file.content.trim()) {\n logger.warn(`Skipping ${file.fileName}: JSON file is empty`);\n recordWarning('skipped_file', file.fileName, 'JSON file is empty');\n return false;\n }\n return true;\n });\n files.push(...twilioContentJsonFiles.filter((file) => file !== null));\n }\n\n // Process Lottie files (binary zip bundles). Content is read as raw bytes and\n // carried base64-encoded end-to-end; the downloaded translation is written\n // back as bytes. No text parsing/merge.\n if (filePaths.lottie) {\n // Lottie files carrying After Effects expressions (executable JS) are\n // rejected outright — collect every offender, then fail once with all of\n // them named rather than aborting on the first.\n const expressionOffenders: string[] = [];\n const lottieFiles = filePaths.lottie\n .map((filePath) => {\n const content = readBinaryFileBase64(filePath);\n const relativePath = getRelative(filePath);\n if (!content) {\n logger.warn(`Skipping ${relativePath}: file is empty or unreadable`);\n recordWarning(\n 'skipped_file',\n relativePath,\n 'File is empty or unreadable'\n );\n return null;\n }\n if (lottieHasExpressions(content)) {\n expressionOffenders.push(relativePath);\n return null;\n }\n return {\n content,\n fileName: relativePath,\n fileFormat: 'LOTTIE' as const,\n ...getTransformFormatProperty(settings, 'lottie'),\n fileId: hashStringSync(relativePath),\n versionId: hashStringSync(content),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => file !== null);\n if (expressionOffenders.length > 0) {\n logErrorAndExit(lottieExpressionsError(expressionOffenders));\n }\n files.push(...lottieFiles);\n }\n\n // Images are carried base64-encoded like Lottie bundles; the API versions\n // media by the hash of its bytes, so the same image uploaded elsewhere\n // resolves to the same version.\n for (const fileType of IMAGE_FILE_TYPES) {\n if (!filePaths[fileType]) continue;\n const imageFiles = filePaths[fileType]\n .map((filePath) => {\n const relativePath = getRelative(filePath);\n const content = readBinaryFileBase64(filePath);\n if (!content) {\n logger.warn(`Skipping ${relativePath}: file is empty or unreadable`);\n recordWarning(\n 'skipped_file',\n relativePath,\n 'File is empty or unreadable'\n );\n return null;\n }\n return {\n content,\n fileName: relativePath,\n fileFormat: CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType],\n ...getTransformFormatProperty(settings, fileType),\n fileId: hashStringSync(relativePath),\n versionId: hashBytesSync(Buffer.from(content, 'base64')),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => file !== null);\n files.push(...imageFiles);\n }\n\n // These formats are uploaded verbatim. Their backslash escapes, format\n // specifiers, timing lines, entity escapes and line breaks must survive\n // byte-for-byte, so they skip the generic markdown-oriented preprocessing\n // below.\n for (const [fileType, fileFormat] of [\n ['dotStrings', 'DOT_STRINGS'],\n ['dotStringsdict', 'DOT_STRINGSDICT'],\n ['androidStrings', 'ANDROID_STRINGS'],\n ['srt', 'SRT'],\n ['resx', 'RESX'],\n ] as const) {\n if (!filePaths[fileType]) continue;\n const verbatimFiles = filePaths[fileType]\n .map((filePath) => {\n const relativePath = getRelative(filePath);\n // Reading is the one place an encoding is resolved; from here on the\n // content is a UTF-8 string like every other format's.\n let content: string;\n try {\n content = readFileContent(filePath, fileFormat);\n } catch (error) {\n // One unreadable file should not abort the whole run: skip it and\n // report it in the summary\n const reason = fileEncodingSkipReason(error);\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n return null;\n }\n return {\n content,\n fileName: relativePath,\n fileFormat,\n ...getTransformFormatProperty(settings, fileType),\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(content, requiresReviewPaths.has(filePath)),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (!file) return false;\n if (!file.content.trim()) {\n logger.warn(`Skipping ${file.fileName}: File is empty`);\n recordWarning('skipped_file', file.fileName, 'File is empty');\n return false;\n }\n return true;\n });\n files.push(...verbatimFiles.filter((file) => file !== null));\n }\n\n // Process Apple .xcstrings catalogs. One catalog holds every locale; only the\n // source-language slice is uploaded as the source document. The slice is\n // hashed into versionId, so an unchanged catalog re-slices byte-identically\n // and does not re-upload.\n if (filePaths.xcstrings) {\n const sourceLanguageMismatches: { file: string; sourceLanguage: string }[] =\n [];\n const xcstringsFiles = filePaths.xcstrings\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n let catalog: XcstringsCatalog;\n try {\n catalog = parseXcstringsCatalog(content);\n } catch (error) {\n const reason =\n error instanceof Error\n ? error.message\n : 'xcstrings file is not parsable';\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n return null;\n }\n // Slicing follows the catalog's own sourceLanguage while the upload is\n // labeled settings.defaultLocale; a mismatch would upload mislabeled\n // source content, so it is a configuration error that stops the run\n // rather than a skipped file. The configured locale may be a custom\n // alias, so canonical forms are compared.\n if (\n api.resolveCanonicalLocale(catalog.sourceLanguage) !==\n api.resolveCanonicalLocale(settings.defaultLocale)\n ) {\n sourceLanguageMismatches.push({\n file: relativePath,\n sourceLanguage: catalog.sourceLanguage,\n });\n return null;\n }\n const sourceSlice = serializeXcstringsSlice(\n sliceSourceCatalog(catalog)\n );\n\n return {\n content: sourceSlice,\n fileName: relativePath,\n fileFormat: 'XCSTRINGS' as const,\n ...getTransformFormatProperty(settings, 'xcstrings'),\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n sourceSlice,\n requiresReviewPaths.has(filePath)\n ),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => file !== null);\n if (sourceLanguageMismatches.length > 0) {\n logErrorAndExit(\n xcstringsSourceLanguageMismatchError(\n sourceLanguageMismatches,\n settings.defaultLocale\n )\n );\n }\n files.push(...xcstringsFiles);\n }\n\n for (const fileType of SUPPORTED_FILE_EXTENSIONS) {\n if (\n fileType === 'json' ||\n fileType === 'yaml' ||\n fileType === 'twilioContentJson' ||\n fileType === 'lottie' ||\n fileType === 'dotStrings' ||\n fileType === 'dotStringsdict' ||\n fileType === 'androidStrings' ||\n fileType === 'xcstrings' ||\n fileType === 'srt' ||\n fileType === 'resx' ||\n (IMAGE_FILE_TYPES as readonly string[]).includes(fileType)\n )\n continue;\n if (filePaths[fileType]) {\n const parsed = filePaths[fileType]\n .map((filePath) => {\n const content = readFile(filePath);\n const relativePath = getRelative(filePath);\n\n const processed = preprocessContent(\n content,\n relativePath,\n fileType,\n settings\n );\n\n if (typeof processed !== 'string') {\n logger.warn(`Skipping ${relativePath}: ${processed.skip}`);\n recordWarning('skipped_file', relativePath, processed.skip);\n return null;\n }\n\n return {\n content: processed,\n fileName: relativePath,\n fileFormat: CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType],\n ...getTransformFormatProperty(settings, fileType),\n fileId: hashStringSync(relativePath),\n versionId: hashVersionId(\n processed,\n requiresReviewPaths.has(filePath)\n ),\n locale: settings.defaultLocale,\n } satisfies FileToUpload;\n })\n .filter((file) => {\n if (\n !file ||\n typeof file.content !== 'string' ||\n !file.content.trim()\n ) {\n logger.warn(\n `Skipping ${file?.fileName ?? 'unknown'}: File is empty after sanitization`\n );\n recordWarning(\n 'skipped_file',\n file?.fileName ?? 'unknown',\n 'File is empty after sanitization'\n );\n return false;\n }\n return true;\n });\n files.push(...parsed.filter((file) => file !== null));\n }\n }\n\n // Remove stale entries for files that were skipped during validation\n const validFileIds = new Set(files.map((f) => f.fileId));\n for (const fileId of publishMap.keys()) {\n if (!validFileIds.has(fileId)) {\n publishMap.delete(fileId);\n }\n }\n\n return { files, publishMap };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,SAAS,wBACP,UACA,cACS;AAET,KAAI,CAAC,+BAAgB,KAAK,SAAS,CAAE,QAAO;CAG5C,MAAM,iBAAiB,SAAS,QAC9B,gCACA,MACD;AACD,QAAO,aAAa,SAAS,eAAe;;;;;;AAO9C,SAAgB,iBACd,SACA,cACA,QACS;AACT,KAAI;AACF,MAAI,WAAW,OAAQ,MAAK,MAAM,QAAQ;MACrC,MAAK,MAAM,QAAQ;AACxB,SAAO;SACD;EACN,MAAM,SAAS,GAAG,OAAO;AACzB,SAAO,KAAK,YAAY,aAAa,IAAI,SAAS;AAClD,gBAAc,gBAAgB,cAAc,OAAO;AACnD,SAAO;;;AAIX,eAAsB,eACpB,UACsE;CAEtE,MAAM,QAAwB,EAAE;AAChC,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC,QAAO;EAAE;EAAO,4BAAY,IAAI,KAAsB;EAAE;CAG1D,MAAM,EAAE,eAAe,cAAc,SAAS;CAE9C,MAAM,sBACJ,SAAS,MAAM,uCAAuB,IAAI,KAAa;CACzD,MAAM,iBAAiB,SAAS,SAAS;CAGzC,MAAM,aAAa,gBAAgB,WAAW,SAAS;AAGvD,KAAI,UAAU,MAAM;EAClB,MAAM,EAAE,SAAS,sBA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cACT,WACA,oBAAoB,IAAI,SAAS,CAClC;KACD,QAAQ,SAAS;KAClB;KACD,CACD,QAAQ,SAAS;AAChB,QACE,CAAC,QACD,OAAO,KAAK,YAAY,YACxB,CAAC,KAAK,QAAQ,MAAM,EACpB;AACA,YAAO,KACL,YAAY,MAAM,YAAY,UAAU,oCACzC;AACD,mBACE,gBACA,MAAM,YAAY,WAClB,mCACD;AACD,YAAO;;AAET,WAAO;KACP;AACJ,SAAM,KAAK,GAAG,OAAO,QAAQ,SAAS,SAAS,KAAK,CAAC;;;CAKzD,MAAM,eAAe,IAAI,IAAI,MAAM,KAAK,MAAM,EAAE,OAAO,CAAC;AACxD,MAAK,MAAM,UAAU,WAAW,MAAM,CACpC,KAAI,CAAC,aAAa,IAAI,OAAO,CAC3B,YAAW,OAAO,OAAO;AAI7B,QAAO;EAAE;EAAO;EAAY"}
@@ -1,4 +1,6 @@
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"];
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
+ /** The file types uploaded as image bytes and translated by the image translation agent. */
3
+ export declare const IMAGE_FILE_TYPES: readonly ["png", "jpeg", "webp", "tiff", "bmp", "avif", "heic"];
2
4
  /** The formats setup offers: an intentional subset of the supported ones. */
3
5
  export declare const SETUP_FILE_FORMATS: readonly ["json", "md", "mdx", "ts", "js", "yaml"];
4
6
  export type SetupFileFormat = (typeof SETUP_FILE_FORMATS)[number];
@@ -20,4 +22,11 @@ export declare const FILE_EXT_TO_EXT_LABEL: {
20
22
  xcstrings: string;
21
23
  srt: string;
22
24
  resx: string;
25
+ png: string;
26
+ jpeg: string;
27
+ webp: string;
28
+ tiff: string;
29
+ bmp: string;
30
+ avif: string;
31
+ heic: string;
23
32
  };
@@ -16,7 +16,24 @@ const SUPPORTED_FILE_EXTENSIONS = [
16
16
  "androidStrings",
17
17
  "xcstrings",
18
18
  "srt",
19
- "resx"
19
+ "resx",
20
+ "png",
21
+ "jpeg",
22
+ "webp",
23
+ "tiff",
24
+ "bmp",
25
+ "avif",
26
+ "heic"
27
+ ];
28
+ /** The file types uploaded as image bytes and translated by the image translation agent. */
29
+ const IMAGE_FILE_TYPES = [
30
+ "png",
31
+ "jpeg",
32
+ "webp",
33
+ "tiff",
34
+ "bmp",
35
+ "avif",
36
+ "heic"
20
37
  ];
21
38
  /** The formats setup offers: an intentional subset of the supported ones. */
22
39
  const SETUP_FILE_FORMATS = [
@@ -44,9 +61,16 @@ const FILE_EXT_TO_EXT_LABEL = {
44
61
  androidStrings: "Android strings.xml",
45
62
  xcstrings: ".xcstrings",
46
63
  srt: "SubRip subtitles (.srt)",
47
- resx: ".NET resources (.resx)"
64
+ resx: ".NET resources (.resx)",
65
+ png: "PNG images",
66
+ jpeg: "JPEG images",
67
+ webp: "WebP images",
68
+ tiff: "TIFF images",
69
+ bmp: "BMP images",
70
+ avif: "AVIF images",
71
+ heic: "HEIC images"
48
72
  };
49
73
  //#endregion
50
- export { FILE_EXT_TO_EXT_LABEL, SETUP_FILE_FORMATS, SUPPORTED_FILE_EXTENSIONS };
74
+ export { FILE_EXT_TO_EXT_LABEL, IMAGE_FILE_TYPES, SETUP_FILE_FORMATS, SUPPORTED_FILE_EXTENSIONS };
51
75
 
52
76
  //# 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] as const;\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};\n"],"mappings":";AAAA,MAAa,4BAA4B;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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;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 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"}
@@ -23,6 +23,13 @@ export declare const CONFIG_FILE_TYPE_TO_FILE_FORMAT: {
23
23
  readonly xcstrings: "XCSTRINGS";
24
24
  readonly srt: "SRT";
25
25
  readonly resx: "RESX";
26
+ readonly png: "PNG";
27
+ readonly jpeg: "JPEG";
28
+ readonly webp: "WEBP";
29
+ readonly tiff: "TIFF";
30
+ readonly bmp: "BMP";
31
+ readonly avif: "AVIF";
32
+ readonly heic: "HEIC";
26
33
  };
27
34
  /**
28
35
  * Maps uppercase config aliases to the CLI's canonical lowercase file keys.
@@ -45,6 +52,13 @@ export declare const FILE_FORMAT_TO_CONFIG_FILE_TYPE: {
45
52
  readonly XCSTRINGS: "xcstrings";
46
53
  readonly SRT: "srt";
47
54
  readonly RESX: "resx";
55
+ readonly PNG: "png";
56
+ readonly JPEG: "jpeg";
57
+ readonly WEBP: "webp";
58
+ readonly TIFF: "tiff";
59
+ readonly BMP: "bmp";
60
+ readonly AVIF: "avif";
61
+ readonly HEIC: "heic";
48
62
  };
49
63
  /**
50
64
  * Converts uppercase file format config keys into the CLI's canonical lowercase keys.
@@ -26,7 +26,14 @@ const CONFIG_FILE_TYPE_TO_FILE_FORMAT = {
26
26
  androidStrings: "ANDROID_STRINGS",
27
27
  xcstrings: "XCSTRINGS",
28
28
  srt: "SRT",
29
- resx: "RESX"
29
+ resx: "RESX",
30
+ png: "PNG",
31
+ jpeg: "JPEG",
32
+ webp: "WEBP",
33
+ tiff: "TIFF",
34
+ bmp: "BMP",
35
+ avif: "AVIF",
36
+ heic: "HEIC"
30
37
  };
31
38
  /**
32
39
  * Maps uppercase config aliases to the CLI's canonical lowercase file keys.
@@ -48,7 +55,14 @@ const FILE_FORMAT_TO_CONFIG_FILE_TYPE = {
48
55
  ANDROID_STRINGS: "androidStrings",
49
56
  XCSTRINGS: "xcstrings",
50
57
  SRT: "srt",
51
- RESX: "resx"
58
+ RESX: "resx",
59
+ PNG: "png",
60
+ JPEG: "jpeg",
61
+ WEBP: "webp",
62
+ TIFF: "tiff",
63
+ BMP: "bmp",
64
+ AVIF: "avif",
65
+ HEIC: "heic"
52
66
  };
53
67
  /**
54
68
  * Maps API file format enum values to the extension the CLI should write.
@@ -73,7 +87,14 @@ const FILE_FORMAT_EXTENSIONS = {
73
87
  ANDROID_STRINGS: "xml",
74
88
  XCSTRINGS: "xcstrings",
75
89
  SRT: "srt",
76
- RESX: "resx"
90
+ RESX: "resx",
91
+ PNG: "png",
92
+ JPEG: "jpg",
93
+ WEBP: "webp",
94
+ TIFF: "tif",
95
+ BMP: "bmp",
96
+ AVIF: "avif",
97
+ HEIC: "heic"
77
98
  };
78
99
  /**
79
100
  * Converts uppercase file format config keys into the CLI's canonical lowercase keys.
@@ -1 +1 @@
1
- {"version":3,"file":"transformFormat.js","names":["FILE_FORMATS"],"sources":["../../../src/formats/files/transformFormat.ts"],"sourcesContent":["import type { FileFormat } from '../../types/data.js';\nimport type {\n FilesOptions,\n Settings,\n SupportedFileExtension,\n} from '../../types/index.js';\nimport { FileFormat as FILE_FORMATS } from 'generaltranslation/api';\nimport { isSupportedFileFormatTransform } from 'generaltranslation/internal';\n\nconst fileFormatValues = new Set<string>(Object.values(FILE_FORMATS));\n\n/** Narrows a user-supplied string to a FileFormat the API contract knows. */\nexport function isFileFormat(value: string): value is FileFormat {\n return fileFormatValues.has(value);\n}\n\n/**\n * Maps CLI config file keys to API file format enum values.\n */\nexport const CONFIG_FILE_TYPE_TO_FILE_FORMAT = {\n json: 'JSON',\n pot: 'POT',\n mdx: 'MDX',\n md: 'MD',\n ts: 'TS',\n js: 'JS',\n yaml: 'YAML',\n html: 'HTML',\n txt: 'TXT',\n twilioContentJson: 'TWILIO_CONTENT_JSON',\n lottie: 'LOTTIE',\n dotStrings: 'DOT_STRINGS',\n dotStringsdict: 'DOT_STRINGSDICT',\n androidStrings: 'ANDROID_STRINGS',\n xcstrings: 'XCSTRINGS',\n srt: 'SRT',\n resx: 'RESX',\n} as const satisfies Record<SupportedFileExtension, FileFormat>;\n\n/**\n * Maps uppercase config aliases to the CLI's canonical lowercase file keys.\n */\nexport const FILE_FORMAT_TO_CONFIG_FILE_TYPE = {\n JSON: 'json',\n POT: 'pot',\n MDX: 'mdx',\n MD: 'md',\n TS: 'ts',\n JS: 'js',\n YAML: 'yaml',\n HTML: 'html',\n TXT: 'txt',\n TWILIO_CONTENT_JSON: 'twilioContentJson',\n LOTTIE: 'lottie',\n DOT_STRINGS: 'dotStrings',\n DOT_STRINGSDICT: 'dotStringsdict',\n ANDROID_STRINGS: 'androidStrings',\n XCSTRINGS: 'xcstrings',\n SRT: 'srt',\n RESX: 'resx',\n} as const satisfies Partial<Record<FileFormat, SupportedFileExtension>>;\n\n/**\n * Maps API file format enum values to the extension the CLI should write.\n */\nconst FILE_FORMAT_EXTENSIONS = {\n GTJSON: 'json',\n JSON: 'json',\n PO: 'po',\n POT: 'pot',\n YAML: 'yaml',\n MDX: 'mdx',\n MD: 'md',\n TS: 'ts',\n JS: 'js',\n HTML: 'html',\n TXT: 'txt',\n TWILIO_CONTENT_JSON: 'json',\n LOTTIE: 'lottie',\n SVG: 'svg',\n DOT_STRINGS: 'strings',\n DOT_STRINGSDICT: 'stringsdict',\n ANDROID_STRINGS: 'xml',\n XCSTRINGS: 'xcstrings',\n SRT: 'srt',\n RESX: 'resx',\n} as const satisfies Record<FileFormat, string>;\n\n/**\n * Converts uppercase file format config keys into the CLI's canonical lowercase keys.\n *\n * This lets users write either `files.POT` or `files.pot` while keeping the\n * rest of the CLI on its existing lowercase file-type convention.\n */\nexport function normalizeFilesOptions(files: FilesOptions): FilesOptions {\n const normalized = { ...files } as FilesOptions & Record<string, unknown>;\n\n for (const [fileFormat, fileType] of Object.entries(\n FILE_FORMAT_TO_CONFIG_FILE_TYPE\n ) as [string, SupportedFileExtension][]) {\n const uppercaseConfig = normalized[fileFormat] as\n | FilesOptions[SupportedFileExtension]\n | undefined;\n if (!normalized[fileType] && uppercaseConfig) {\n normalized[fileType] = uppercaseConfig;\n }\n delete normalized[fileFormat];\n }\n\n return normalized;\n}\n\n/**\n * Validates and resolves a configured output format for a source file type.\n *\n * Throws when the requested source -> output format is not supported by\n * `generaltranslation/internal`.\n */\nexport function resolveTransformationFormat(\n fileType: SupportedFileExtension,\n transformationFormat: string | undefined\n): FileFormat | undefined {\n if (!transformationFormat) return undefined;\n\n // Normalize to uppercase to match the FileFormat enum (e.g. \"po\" -> \"PO\")\n const normalized = transformationFormat.toUpperCase();\n const fileFormat = CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType];\n\n if (\n !isFileFormat(normalized) ||\n !isSupportedFileFormatTransform(fileFormat, normalized)\n ) {\n throw new Error(\n `Unsupported file format transform: ${fileFormat} -> ${normalized} in files.${fileType}. ` +\n `\"${normalized}\" is not a valid transformationFormat for ${fileFormat} source files.`\n );\n }\n\n return normalized;\n}\n\n/**\n * Returns the API upload/enqueue property for a file type when one is configured.\n */\nexport function getTransformFormatProperty(\n settings: Settings,\n fileType: SupportedFileExtension\n): { transformFormat?: FileFormat } {\n const transformFormat = settings.files?.transformFormats?.[fileType];\n return transformFormat ? { transformFormat } : {};\n}\n\n/**\n * Returns the preferred file extension for a translated file format.\n */\nexport function getFileExtensionForFormat(format: FileFormat): string {\n return FILE_FORMAT_EXTENSIONS[format];\n}\n\n/**\n * Rewrites a path's extension to match the translated file format.\n */\nexport function replaceFileExtensionForFormat(\n filePath: string,\n format: FileFormat\n): string {\n const extension = getFileExtensionForFormat(format);\n return /\\.[^/.]+$/.test(filePath)\n ? filePath.replace(/\\.[^/.]+$/, `.${extension}`)\n : `${filePath}.${extension}`;\n}\n\n/**\n * Detects whether any configured format transform changes the output file type.\n */\nexport function hasNonIdentityFileFormatTransform(settings: Settings): boolean {\n return Object.entries(settings.files?.transformFormats || {}).some(\n ([fileType, transformFormat]) =>\n transformFormat &&\n CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType as SupportedFileExtension] !==\n transformFormat\n );\n}\n\n/**\n * Returns true when the configured transform for a file type changes its format.\n */\nexport function hasNonIdentityFileFormatTransformForType(\n settings: Settings,\n fileType: SupportedFileExtension\n): boolean {\n const transformFormat = settings.files?.transformFormats?.[fileType];\n return !!(\n transformFormat &&\n CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType] !== transformFormat\n );\n}\n"],"mappings":";;;AASA,MAAM,mBAAmB,IAAI,IAAY,OAAO,OAAOA,WAAa,CAAC;;AAGrE,SAAgB,aAAa,OAAoC;AAC/D,QAAO,iBAAiB,IAAI,MAAM;;;;;AAMpC,MAAa,kCAAkC;CAC7C,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;CACP;;;;AAKD,MAAa,kCAAkC;CAC7C,MAAM;CACN,KAAK;CACL,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,KAAK;CACL,qBAAqB;CACrB,QAAQ;CACR,aAAa;CACb,iBAAiB;CACjB,iBAAiB;CACjB,WAAW;CACX,KAAK;CACL,MAAM;CACP;;;;AAKD,MAAM,yBAAyB;CAC7B,QAAQ;CACR,MAAM;CACN,IAAI;CACJ,KAAK;CACL,MAAM;CACN,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,KAAK;CACL,qBAAqB;CACrB,QAAQ;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N,mBACA,gCAAgC,cAAc"}
1
+ {"version":3,"file":"transformFormat.js","names":["FILE_FORMATS"],"sources":["../../../src/formats/files/transformFormat.ts"],"sourcesContent":["import type { FileFormat } from '../../types/data.js';\nimport type {\n FilesOptions,\n Settings,\n SupportedFileExtension,\n} from '../../types/index.js';\nimport { FileFormat as FILE_FORMATS } from 'generaltranslation/api';\nimport { isSupportedFileFormatTransform } from 'generaltranslation/internal';\n\nconst fileFormatValues = new Set<string>(Object.values(FILE_FORMATS));\n\n/** Narrows a user-supplied string to a FileFormat the API contract knows. */\nexport function isFileFormat(value: string): value is FileFormat {\n return fileFormatValues.has(value);\n}\n\n/**\n * Maps CLI config file keys to API file format enum values.\n */\nexport const CONFIG_FILE_TYPE_TO_FILE_FORMAT = {\n json: 'JSON',\n pot: 'POT',\n mdx: 'MDX',\n md: 'MD',\n ts: 'TS',\n js: 'JS',\n yaml: 'YAML',\n html: 'HTML',\n txt: 'TXT',\n twilioContentJson: 'TWILIO_CONTENT_JSON',\n lottie: 'LOTTIE',\n dotStrings: 'DOT_STRINGS',\n dotStringsdict: 'DOT_STRINGSDICT',\n androidStrings: 'ANDROID_STRINGS',\n xcstrings: 'XCSTRINGS',\n srt: 'SRT',\n resx: 'RESX',\n png: 'PNG',\n jpeg: 'JPEG',\n webp: 'WEBP',\n tiff: 'TIFF',\n bmp: 'BMP',\n avif: 'AVIF',\n heic: 'HEIC',\n} as const satisfies Record<SupportedFileExtension, FileFormat>;\n\n/**\n * Maps uppercase config aliases to the CLI's canonical lowercase file keys.\n */\nexport const FILE_FORMAT_TO_CONFIG_FILE_TYPE = {\n JSON: 'json',\n POT: 'pot',\n MDX: 'mdx',\n MD: 'md',\n TS: 'ts',\n JS: 'js',\n YAML: 'yaml',\n HTML: 'html',\n TXT: 'txt',\n TWILIO_CONTENT_JSON: 'twilioContentJson',\n LOTTIE: 'lottie',\n DOT_STRINGS: 'dotStrings',\n DOT_STRINGSDICT: 'dotStringsdict',\n ANDROID_STRINGS: 'androidStrings',\n XCSTRINGS: 'xcstrings',\n SRT: 'srt',\n RESX: 'resx',\n PNG: 'png',\n JPEG: 'jpeg',\n WEBP: 'webp',\n TIFF: 'tiff',\n BMP: 'bmp',\n AVIF: 'avif',\n HEIC: 'heic',\n} as const satisfies Partial<Record<FileFormat, SupportedFileExtension>>;\n\n/**\n * Maps API file format enum values to the extension the CLI should write.\n */\nconst FILE_FORMAT_EXTENSIONS = {\n GTJSON: 'json',\n JSON: 'json',\n PO: 'po',\n POT: 'pot',\n YAML: 'yaml',\n MDX: 'mdx',\n MD: 'md',\n TS: 'ts',\n JS: 'js',\n HTML: 'html',\n TXT: 'txt',\n TWILIO_CONTENT_JSON: 'json',\n LOTTIE: 'lottie',\n SVG: 'svg',\n DOT_STRINGS: 'strings',\n DOT_STRINGSDICT: 'stringsdict',\n ANDROID_STRINGS: 'xml',\n XCSTRINGS: 'xcstrings',\n SRT: 'srt',\n RESX: 'resx',\n PNG: 'png',\n JPEG: 'jpg',\n WEBP: 'webp',\n TIFF: 'tif',\n BMP: 'bmp',\n AVIF: 'avif',\n HEIC: 'heic',\n} as const satisfies Record<FileFormat, string>;\n\n/**\n * Converts uppercase file format config keys into the CLI's canonical lowercase keys.\n *\n * This lets users write either `files.POT` or `files.pot` while keeping the\n * rest of the CLI on its existing lowercase file-type convention.\n */\nexport function normalizeFilesOptions(files: FilesOptions): FilesOptions {\n const normalized = { ...files } as FilesOptions & Record<string, unknown>;\n\n for (const [fileFormat, fileType] of Object.entries(\n FILE_FORMAT_TO_CONFIG_FILE_TYPE\n ) as [string, SupportedFileExtension][]) {\n const uppercaseConfig = normalized[fileFormat] as\n | FilesOptions[SupportedFileExtension]\n | undefined;\n if (!normalized[fileType] && uppercaseConfig) {\n normalized[fileType] = uppercaseConfig;\n }\n delete normalized[fileFormat];\n }\n\n return normalized;\n}\n\n/**\n * Validates and resolves a configured output format for a source file type.\n *\n * Throws when the requested source -> output format is not supported by\n * `generaltranslation/internal`.\n */\nexport function resolveTransformationFormat(\n fileType: SupportedFileExtension,\n transformationFormat: string | undefined\n): FileFormat | undefined {\n if (!transformationFormat) return undefined;\n\n // Normalize to uppercase to match the FileFormat enum (e.g. \"po\" -> \"PO\")\n const normalized = transformationFormat.toUpperCase();\n const fileFormat = CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType];\n\n if (\n !isFileFormat(normalized) ||\n !isSupportedFileFormatTransform(fileFormat, normalized)\n ) {\n throw new Error(\n `Unsupported file format transform: ${fileFormat} -> ${normalized} in files.${fileType}. ` +\n `\"${normalized}\" is not a valid transformationFormat for ${fileFormat} source files.`\n );\n }\n\n return normalized;\n}\n\n/**\n * Returns the API upload/enqueue property for a file type when one is configured.\n */\nexport function getTransformFormatProperty(\n settings: Settings,\n fileType: SupportedFileExtension\n): { transformFormat?: FileFormat } {\n const transformFormat = settings.files?.transformFormats?.[fileType];\n return transformFormat ? { transformFormat } : {};\n}\n\n/**\n * Returns the preferred file extension for a translated file format.\n */\nexport function getFileExtensionForFormat(format: FileFormat): string {\n return FILE_FORMAT_EXTENSIONS[format];\n}\n\n/**\n * Rewrites a path's extension to match the translated file format.\n */\nexport function replaceFileExtensionForFormat(\n filePath: string,\n format: FileFormat\n): string {\n const extension = getFileExtensionForFormat(format);\n return /\\.[^/.]+$/.test(filePath)\n ? filePath.replace(/\\.[^/.]+$/, `.${extension}`)\n : `${filePath}.${extension}`;\n}\n\n/**\n * Detects whether any configured format transform changes the output file type.\n */\nexport function hasNonIdentityFileFormatTransform(settings: Settings): boolean {\n return Object.entries(settings.files?.transformFormats || {}).some(\n ([fileType, transformFormat]) =>\n transformFormat &&\n CONFIG_FILE_TYPE_TO_FILE_FORMAT[fileType as SupportedFileExtension] !==\n transformFormat\n );\n}\n\n/**\n * Returns true when the configured transform for a file type changes its format.\n */\nexport function hasNonIdentityFileFormatTransformForType(\n settings: Settings,\n fileType: SupportedFileExtension\n): boolean {\n const transformFormat = settings.files?.transformFormats?.[fileType];\n return !!(\n transformFormat &&\n CONFI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,CAAC,YAAY,aAAa,OAAO,QAC1C,gCACD,EAAwC;EACvC,MAAM,kBAAkB,WAAW;AAGnC,MAAI,CAAC,WAAW,aAAa,gBAC3B,YAAW,YAAY;AAEzB,SAAO,WAAW;;AAGpB,QAAO;;;;;;;;AAST,SAAgB,4BACd,UACA,sBACwB;AACxB,KAAI,CAAC,qBAAsB,QAAO,KAAA;CAGlC,MAAM,aAAa,qBAAqB,aAAa;CACrD,MAAM,aAAa,gCAAgC;AAEnD,KACE,CAAC,aAAa,WAAW,IACzB,CAAC,+BAA+B,YAAY,WAAW,CAEvD,OAAM,IAAI,MACR,sCAAsC,WAAW,MAAM,WAAW,YAAY,SAAS,KACjF,WAAW,4CAA4C,WAAW,gBACzE;AAGH,QAAO;;;;;AAMT,SAAgB,2BACd,UACA,UACkC;CAClC,MAAM,kBAAkB,SAAS,OAAO,mBAAmB;AAC3D,QAAO,kBAAkB,EAAE,iBAAiB,GAAG,EAAE;;;;;AAMnD,SAAgB,0BAA0B,QAA4B;AACpE,QAAO,uBAAuB;;;;;AAMhC,SAAgB,8BACd,UACA,QACQ;CACR,MAAM,YAAY,0BAA0B,OAAO;AACnD,QAAO,YAAY,KAAK,SAAS,GAC7B,SAAS,QAAQ,aAAa,IAAI,YAAY,GAC9C,GAAG,SAAS,GAAG;;;;;AAMrB,SAAgB,kCAAkC,UAA6B;AAC7E,QAAO,OAAO,QAAQ,SAAS,OAAO,oBAAoB,EAAE,CAAC,CAAC,MAC3D,CAAC,UAAU,qBACV,mBACA,gCAAgC,cAC9B,gBACL;;;;;AAMH,SAAgB,yCACd,UACA,UACS;CACT,MAAM,kBAAkB,SAAS,OAAO,mBAAmB;AAC3D,QAAO,CAAC,EACN,mBACA,gCAAgC,cAAc"}
@@ -28,7 +28,7 @@ export declare function findFile(filePattern: string, file: string): string;
28
28
  export declare function readFile(filePath: string): string;
29
29
  /**
30
30
  * Read a file as raw bytes and return it base64-encoded. Used for binary
31
- * formats (e.g. Lottie zip bundles) whose content must not be decoded as UTF-8.
31
+ * formats (e.g. Lottie zip bundles, images) whose content must not be decoded as UTF-8.
32
32
  * @param {string} filePath - The path to the file to read.
33
33
  * @returns {string} - The base64-encoded contents, or '' if the file is absent.
34
34
  */
@@ -52,7 +52,7 @@ function readFile(filePath) {
52
52
  }
53
53
  /**
54
54
  * Read a file as raw bytes and return it base64-encoded. Used for binary
55
- * formats (e.g. Lottie zip bundles) whose content must not be decoded as UTF-8.
55
+ * formats (e.g. Lottie zip bundles, images) whose content must not be decoded as UTF-8.
56
56
  * @param {string} filePath - The path to the file to read.
57
57
  * @returns {string} - The base64-encoded contents, or '' if the file is absent.
58
58
  */
@@ -1 +1 @@
1
- {"version":3,"file":"findFilepath.js","names":[],"sources":["../../src/fs/findFilepath.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport { exitSync } from '../console/logging.js';\n\n/**\n * Resolve the file path from the given file path or default paths.\n * @param {string} filePath - The file path to resolve.\n * @param {string[]} defaultPaths - The default paths to check.\n * @returns {string} - The resolved file path.\n */\nexport default function findFilepath(\n paths: string[],\n errorMessage: string = ''\n): string {\n return findFilepaths(paths, errorMessage)?.[0] || '';\n}\n\n/**\n * Resolve the file paths from the given file paths or default paths.\n * @param {string[]} paths - The file paths to resolve.\n * @param {string} errorMessage - The error message to throw if no paths are found.\n * @returns {string[]} - The resolved file paths.\n */\nexport function findFilepaths(\n paths: string[],\n errorMessage: string = ''\n): string[] {\n const resolvedPaths: string[] = [];\n for (const possiblePath of paths) {\n if (fs.existsSync(possiblePath)) {\n resolvedPaths.push(possiblePath);\n }\n }\n if (errorMessage) {\n logger.error(errorMessage);\n exitSync(1);\n }\n return resolvedPaths;\n}\n\nexport function getRelativePath(file: string, srcDirectory: string): string {\n // Create relative path from src directory and remove extension\n return path\n .relative(\n srcDirectory,\n file.replace(/\\.[^/.]+$/, '') // Remove file extension\n )\n .replace(/\\\\/g, '.') // Replace Windows backslashes with dots\n .split(/[./]/) // Split on dots or forward slashes\n .filter(Boolean) // Remove empty segments that might cause extra dots\n .map((segment) => segment.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase()) // Convert each segment to snake case\n .join('.'); // Rejoin with dots\n}\n\n/**\n * Find a file in a directory based on a wildcard pattern.\n * @param {string} filePattern - The wildcard pattern to search for.\n * @param {string} file - The file to search for.\n * @returns {string} - The path to the file.\n */\nexport function findFile(filePattern: string, file: string): string {\n // Handle wildcard pattern by replacing the wildcard with the file parameter\n const resolvedPath = filePattern.replace(/\\*/, file);\n\n if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {\n return fs.readFileSync(resolvedPath, 'utf8');\n }\n return '';\n}\n\n/**\n * Read a file and return the contents.\n * @param {string} filePath - The path to the file to read.\n * @returns {string} - The contents of the file.\n */\nexport function readFile(filePath: string): string {\n if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {\n return fs.readFileSync(filePath, 'utf8');\n }\n return '';\n}\n\n/**\n * Read a file as raw bytes and return it base64-encoded. Used for binary\n * formats (e.g. Lottie zip bundles) whose content must not be decoded as UTF-8.\n * @param {string} filePath - The path to the file to read.\n * @returns {string} - The base64-encoded contents, or '' if the file is absent.\n */\nexport function readBinaryFileBase64(filePath: string): string {\n if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {\n return fs.readFileSync(filePath).toString('base64');\n }\n return '';\n}\n\n/**\n * Find a file in a directory.\n * @param {string} dir - The directory to search in.\n * @param {string} file - The file to search for.\n * @returns {string} - The path to the file.\n */\nexport function findFileInDir(dir: string, file: string): string {\n const resolvedPath = path.join(dir, file);\n try {\n if (fs.existsSync(resolvedPath)) {\n return fs.readFileSync(resolvedPath, 'utf8');\n }\n } catch (error) {\n logger.error('Error finding file in directory: ' + String(error));\n }\n return '';\n}\n\nexport function getRelative(absolutePath: string): string {\n const path2 = path.resolve(absolutePath);\n return path.relative(process.cwd(), path2);\n}\n"],"mappings":";;;;;;;;;;;AAWA,SAAwB,aACtB,OACA,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AAsC,OAAO,MAAM,CAAC;;AAEnE,QAAO;;AAGT,SAAgB,YAAY,cAA8B;CACxD,MAAM,QAAQ,KAAK,QAAQ,aAAa;AACxC,QAAO,KAAK,SAAS,QAAQ,KAAK,EAAE,MAAM"}
1
+ {"version":3,"file":"findFilepath.js","names":[],"sources":["../../src/fs/findFilepath.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport { exitSync } from '../console/logging.js';\n\n/**\n * Resolve the file path from the given file path or default paths.\n * @param {string} filePath - The file path to resolve.\n * @param {string[]} defaultPaths - The default paths to check.\n * @returns {string} - The resolved file path.\n */\nexport default function findFilepath(\n paths: string[],\n errorMessage: string = ''\n): string {\n return findFilepaths(paths, errorMessage)?.[0] || '';\n}\n\n/**\n * Resolve the file paths from the given file paths or default paths.\n * @param {string[]} paths - The file paths to resolve.\n * @param {string} errorMessage - The error message to throw if no paths are found.\n * @returns {string[]} - The resolved file paths.\n */\nexport function findFilepaths(\n paths: string[],\n errorMessage: string = ''\n): string[] {\n const resolvedPaths: string[] = [];\n for (const possiblePath of paths) {\n if (fs.existsSync(possiblePath)) {\n resolvedPaths.push(possiblePath);\n }\n }\n if (errorMessage) {\n logger.error(errorMessage);\n exitSync(1);\n }\n return resolvedPaths;\n}\n\nexport function getRelativePath(file: string, srcDirectory: string): string {\n // Create relative path from src directory and remove extension\n return path\n .relative(\n srcDirectory,\n file.replace(/\\.[^/.]+$/, '') // Remove file extension\n )\n .replace(/\\\\/g, '.') // Replace Windows backslashes with dots\n .split(/[./]/) // Split on dots or forward slashes\n .filter(Boolean) // Remove empty segments that might cause extra dots\n .map((segment) => segment.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase()) // Convert each segment to snake case\n .join('.'); // Rejoin with dots\n}\n\n/**\n * Find a file in a directory based on a wildcard pattern.\n * @param {string} filePattern - The wildcard pattern to search for.\n * @param {string} file - The file to search for.\n * @returns {string} - The path to the file.\n */\nexport function findFile(filePattern: string, file: string): string {\n // Handle wildcard pattern by replacing the wildcard with the file parameter\n const resolvedPath = filePattern.replace(/\\*/, file);\n\n if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {\n return fs.readFileSync(resolvedPath, 'utf8');\n }\n return '';\n}\n\n/**\n * Read a file and return the contents.\n * @param {string} filePath - The path to the file to read.\n * @returns {string} - The contents of the file.\n */\nexport function readFile(filePath: string): string {\n if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {\n return fs.readFileSync(filePath, 'utf8');\n }\n return '';\n}\n\n/**\n * Read a file as raw bytes and return it base64-encoded. Used for binary\n * formats (e.g. Lottie zip bundles, images) whose content must not be decoded as UTF-8.\n * @param {string} filePath - The path to the file to read.\n * @returns {string} - The base64-encoded contents, or '' if the file is absent.\n */\nexport function readBinaryFileBase64(filePath: string): string {\n if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {\n return fs.readFileSync(filePath).toString('base64');\n }\n return '';\n}\n\n/**\n * Find a file in a directory.\n * @param {string} dir - The directory to search in.\n * @param {string} file - The file to search for.\n * @returns {string} - The path to the file.\n */\nexport function findFileInDir(dir: string, file: string): string {\n const resolvedPath = path.join(dir, file);\n try {\n if (fs.existsSync(resolvedPath)) {\n return fs.readFileSync(resolvedPath, 'utf8');\n }\n } catch (error) {\n logger.error('Error finding file in directory: ' + String(error));\n }\n return '';\n}\n\nexport function getRelative(absolutePath: string): string {\n const path2 = path.resolve(absolutePath);\n return path.relative(process.cwd(), path2);\n}\n"],"mappings":";;;;;;;;;;;AAWA,SAAwB,aACtB,OACA,eAAuB,IACf;AACR,QAAO,cAAc,OAAO,aAAa,GAAG,MAAM;;;;;;;;AASpD,SAAgB,cACd,OACA,eAAuB,IACb;CACV,MAAM,gBAA0B,EAAE;AAClC,MAAK,MAAM,gBAAgB,MACzB,KAAI,GAAG,WAAW,aAAa,CAC7B,eAAc,KAAK,aAAa;AAGpC,KAAI,cAAc;AAChB,SAAO,MAAM,aAAa;AAC1B,WAA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
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.28.6";
2
+ const PACKAGE_VERSION = "2.28.7";
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.6';\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.28.7';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -12,3 +12,5 @@ export declare function hashStringSync(string: string): string;
12
12
  * preserving pre-requiresReview version IDs.
13
13
  */
14
14
  export declare function hashVersionId(content: string, requiresReview: boolean): string;
15
+ /** Hashes raw bytes with SHA-256, as the API versions media files. */
16
+ export declare function hashBytesSync(bytes: Uint8Array): string;
@@ -20,7 +20,11 @@ function hashStringSync(string) {
20
20
  function hashVersionId(content, requiresReview) {
21
21
  return requiresReview ? hashStringSync(content + "\0requiresReview:true") : hashStringSync(content);
22
22
  }
23
+ /** Hashes raw bytes with SHA-256, as the API versions media files. */
24
+ function hashBytesSync(bytes) {
25
+ return crypto.createHash("sha256").update(bytes).digest("hex");
26
+ }
23
27
  //#endregion
24
- export { hashStringSync, hashVersionId };
28
+ export { hashBytesSync, hashStringSync, hashVersionId };
25
29
 
26
30
  //# sourceMappingURL=hash.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hash.js","names":[],"sources":["../../src/utils/hash.ts"],"sourcesContent":["import crypto from 'crypto';\n\n/**\n * Hashes a string using SHA-256 algorithm.\n * @param {string} string - The string to be hashed.\n * @returns {string} The hashed string.\n */\nexport function hashStringSync(string: string): string {\n const hash = crypto.createHash('sha256');\n hash.update(string);\n return hash.digest('hex');\n}\n\n/**\n * Computes a file content version hash. When the file's effective\n * requiresReview policy is true, the policy is mixed into the hash so\n * review-policy changes produce a new version identity even for unchanged\n * content. A false policy hashes identically to the plain content hash,\n * preserving pre-requiresReview version IDs.\n */\nexport function hashVersionId(\n content: string,\n requiresReview: boolean\n): string {\n return requiresReview\n ? hashStringSync(content + '\\u0000requiresReview:true')\n : hashStringSync(content);\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,eAAe,QAAwB;CACrD,MAAM,OAAO,OAAO,WAAW,SAAS;AACxC,MAAK,OAAO,OAAO;AACnB,QAAO,KAAK,OAAO,MAAM;;;;;;;;;AAU3B,SAAgB,cACd,SACA,gBACQ;AACR,QAAO,iBACH,eAAe,UAAU,wBAA4B,GACrD,eAAe,QAAQ"}
1
+ {"version":3,"file":"hash.js","names":[],"sources":["../../src/utils/hash.ts"],"sourcesContent":["import crypto from 'crypto';\n\n/**\n * Hashes a string using SHA-256 algorithm.\n * @param {string} string - The string to be hashed.\n * @returns {string} The hashed string.\n */\nexport function hashStringSync(string: string): string {\n const hash = crypto.createHash('sha256');\n hash.update(string);\n return hash.digest('hex');\n}\n\n/**\n * Computes a file content version hash. When the file's effective\n * requiresReview policy is true, the policy is mixed into the hash so\n * review-policy changes produce a new version identity even for unchanged\n * content. A false policy hashes identically to the plain content hash,\n * preserving pre-requiresReview version IDs.\n */\nexport function hashVersionId(\n content: string,\n requiresReview: boolean\n): string {\n return requiresReview\n ? hashStringSync(content + '\\u0000requiresReview:true')\n : hashStringSync(content);\n}\n\n/** Hashes raw bytes with SHA-256, as the API versions media files. */\nexport function hashBytesSync(bytes: Uint8Array): string {\n return crypto.createHash('sha256').update(bytes).digest('hex');\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,eAAe,QAAwB;CACrD,MAAM,OAAO,OAAO,WAAW,SAAS;AACxC,MAAK,OAAO,OAAO;AACnB,QAAO,KAAK,OAAO,MAAM;;;;;;;;;AAU3B,SAAgB,cACd,SACA,gBACQ;AACR,QAAO,iBACH,eAAe,UAAU,wBAA4B,GACrD,eAAe,QAAQ;;;AAI7B,SAAgB,cAAc,OAA2B;AACvD,QAAO,OAAO,WAAW,SAAS,CAAC,OAAO,MAAM,CAAC,OAAO,MAAM"}
@@ -1,4 +1,5 @@
1
1
  import "./constants.js";
2
+ import { IMAGE_FILE_TYPES } from "../formats/files/supportedFiles.js";
2
3
  import { createFileMapping } from "../formats/files/fileMapping.js";
3
4
  import { batchProcess } from "./batchProcess.js";
4
5
  import path from "node:path";
@@ -150,12 +151,29 @@ function rewriteMdxContent(content, filePath, pathMap) {
150
151
  };
151
152
  }
152
153
  }
153
- function resolveAssetPaths(include, cwd) {
154
+ /** An image configured for translation has its own file per locale, so neither its source nor those files are shared. */
155
+ function translatedImagePaths(settings, cwd) {
156
+ const paths = /* @__PURE__ */ new Set();
157
+ const files = settings.files;
158
+ const sources = IMAGE_FILE_TYPES.flatMap((fileType) => files?.resolvedPaths?.[fileType] ?? []);
159
+ if (!files || sources.length === 0) return paths;
160
+ for (const source of sources) paths.add(path.normalize(source));
161
+ const targetLocales = (settings.locales ?? []).filter((locale) => locale !== settings.defaultLocale);
162
+ const fileMapping = createFileMapping(files.resolvedPaths, files.placeholderPaths, files.transformPaths, files.transformFormats, targetLocales, settings.defaultLocale);
163
+ const sourceNames = new Set(sources.map((source) => path.relative(cwd, source)));
164
+ for (const locale of targetLocales) for (const [sourceName, targetName] of Object.entries(fileMapping?.[locale] ?? {})) if (sourceNames.has(sourceName)) paths.add(path.normalize(path.resolve(cwd, targetName)));
165
+ return paths;
166
+ }
167
+ function resolveAssetPaths(include, cwd, settings) {
168
+ const translated = translatedImagePaths(settings, cwd);
154
169
  const assetPaths = /* @__PURE__ */ new Set();
155
170
  for (let pattern of include) {
156
171
  if (pattern.startsWith("/")) pattern = pattern.slice(1);
157
172
  const matches = fg.sync(path.resolve(cwd, pattern), { absolute: true });
158
- for (const m of matches) assetPaths.add(path.normalize(m));
173
+ for (const m of matches) {
174
+ const assetPath = path.normalize(m);
175
+ if (!translated.has(assetPath)) assetPaths.add(assetPath);
176
+ }
159
177
  }
160
178
  return assetPaths;
161
179
  }
@@ -166,7 +184,7 @@ async function mirrorAssetsToLocales(settings) {
166
184
  const cwd = process.cwd();
167
185
  const include = toArray(cfg.include);
168
186
  if (include.length === 0) return;
169
- const assetPaths = resolveAssetPaths(include, cwd);
187
+ const assetPaths = resolveAssetPaths(include, cwd, settings);
170
188
  if (assetPaths.size === 0) return;
171
189
  const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } = settings.files;
172
190
  const targetLocales = settings.locales.filter((l) => l !== settings.defaultLocale);
@@ -231,7 +249,7 @@ async function processSharedStaticAssets(settings) {
231
249
  const cwd = process.cwd();
232
250
  const include = toArray(cfg.include);
233
251
  if (include.length === 0) return;
234
- const assetPaths = resolveAssetPaths(include, cwd);
252
+ const assetPaths = resolveAssetPaths(include, cwd, settings);
235
253
  if (assetPaths.size === 0) return;
236
254
  if (!cfg.outDir) return;
237
255
  const outDirInput = cfg.outDir.startsWith("/") ? cfg.outDir.slice(1) : cfg.outDir;
@@ -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';\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,UAAU,MAAM,KAAK;AACvC,OAAI;AACF,UAAM,GAAG,SAAS,OAAO,IAAI;WACvB;aAGC,SAAS,SAElB;MAEA,OAAM;;;AAKZ,eA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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"}
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 { IMAGE_FILE_TYPES } from '../formats/files/supportedFiles.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\n/** An image configured for translation has its own file per locale, so neither its source nor those files are shared. */\nfunction translatedImagePaths(settings: Settings, cwd: string): Set<string> {\n const paths = new Set<string>();\n const files = settings.files;\n const sources = IMAGE_FILE_TYPES.flatMap(\n (fileType) => files?.resolvedPaths?.[fileType] ?? []\n );\n if (!files || sources.length === 0) return paths;\n\n for (const source of sources) paths.add(path.normalize(source));\n\n const targetLocales = (settings.locales ?? []).filter(\n (locale) => locale !== settings.defaultLocale\n );\n const fileMapping = createFileMapping(\n files.resolvedPaths,\n files.placeholderPaths,\n files.transformPaths,\n files.transformFormats,\n targetLocales,\n settings.defaultLocale\n );\n const sourceNames = new Set(\n sources.map((source) => path.relative(cwd, source))\n );\n for (const locale of targetLocales) {\n for (const [sourceName, targetName] of Object.entries(\n fileMapping?.[locale] ?? {}\n )) {\n if (sourceNames.has(sourceName)) {\n paths.add(path.normalize(path.resolve(cwd, targetName)));\n }\n }\n }\n return paths;\n}\n\nfunction resolveAssetPaths(\n include: string[],\n cwd: string,\n settings: Settings\n): Set<string> {\n const translated = translatedImagePaths(settings, cwd);\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) {\n const assetPath = path.normalize(m);\n if (!translated.has(assetPath)) assetPaths.add(assetPath);\n }\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, settings);\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, settings);\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":";;;;;;;;;;;;;;;AA8BA,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,QA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GAAG,cACtD,MACA;AACF,mBAAiB,IAAI,KAAK,UAAU,IAAI,EAAE,UAAU;;AAItD,MAAK,MAAM,OAAO,YAAY;EAC5B,MAAM,cAAc,KAAK,SAAS,KAAK,IAAI;EAC3C,MAAM,UAAU,KAAK,QAAQ,WAAW,YAAY;AAEpD,MAAI,KAAK,UAAU,IAAI,KAAK,KAAK,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.28.6",
3
+ "version": "2.28.7",
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.11",
119
+ "@generaltranslation/format": "0.1.12",
120
120
  "@generaltranslation/icu": "0.1.2",
121
- "@generaltranslation/python-extractor": "0.2.68",
122
- "@generaltranslation/supported-locales": "2.1.49",
123
- "@generaltranslation/vue-extractor": "0.1.27",
124
- "generaltranslation": "9.5.13",
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",
125
125
  "gt-remark": "1.0.12"
126
126
  },
127
127
  "devDependencies": {