gt 2.28.4 → 2.28.5

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,11 @@
1
1
  # gtx-cli
2
2
 
3
+ ## 2.28.5
4
+
5
+ ### Patch Changes
6
+
7
+ - [#2987](https://github.com/generaltranslation/gt/pull/2987) [`5cc2d0e`](https://github.com/generaltranslation/gt/commit/5cc2d0e20aeae715c460edafdfa2514ae1ce4ec0) Thanks [@Goldloli](https://github.com/Goldloli)! - Resolve the current branch before reading `gt-lock.json` in `gt save-local`, so the `files.gt` template is looked up and published under the branch the files belong to. Also warn, and avoid reporting a clean success, when a locale whose recorded hash already differs cannot be compared because the server has no copy of the version in the lockfile.
8
+
3
9
  ## 2.28.4
4
10
 
5
11
  ### Patch Changes
@@ -84,6 +84,14 @@ const parseJson = (content) => {
84
84
  * so they are measured the same way.
85
85
  */
86
86
  const contentBytes = (content, fileFormat) => isBinaryFileFormat(fileFormat) ? Buffer.from(content, "base64") : Buffer.from(content, "utf8");
87
+ /**
88
+ * The branch these files were uploaded under. `readLockfile` needs it to pick
89
+ * the matching entries out of a v1 lockfile, which keeps every branch it has
90
+ * seen; without it the file's entries are read from whichever branch is listed
91
+ * first. The files carry the branch resolved for this invocation, while
92
+ * `settings._branchId` can still hold the value persisted by an earlier run.
93
+ */
94
+ const lockfileBranchId = (files, settings) => files.find((file) => file.branchId)?.branchId ?? settings._branchId;
87
95
  const findLatestDownloadedVersion = (entryMap, fileId, locale) => {
88
96
  const entry = entryMap.get(fileId);
89
97
  if (!entry) return null;
@@ -106,7 +114,11 @@ async function collectAndSendUserEditDiffs(files, settings) {
106
114
  if (!settings.files) return false;
107
115
  const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } = settings.files;
108
116
  const fileMapping = createFileMapping(resolvedPaths, placeholderPaths, transformPaths, transformFormats, settings.locales, settings.defaultLocale);
109
- const { entryMap } = readLockfile(settings);
117
+ const branchId = lockfileBranchId(files, settings);
118
+ const { entryMap } = readLockfile(branchId ? {
119
+ ...settings,
120
+ _branchId: branchId
121
+ } : settings);
110
122
  const tempDir = path$1.join(os.tmpdir(), randomUUID());
111
123
  if (!fs$1.existsSync(tempDir)) fs$1.mkdirSync(tempDir, { recursive: true });
112
124
  const candidates = [];
@@ -117,9 +129,11 @@ async function collectAndSendUserEditDiffs(files, settings) {
117
129
  const latestDownloaded = findLatestDownloadedVersion(entryMap, uploadedFile.fileId, locale);
118
130
  if (!latestDownloaded) continue;
119
131
  const downloadedVersion = latestDownloaded.entry;
132
+ let knownEdited = false;
120
133
  if (downloadedVersion.postProcessHash) try {
121
134
  const localFile = readFileContent(outputPath, uploadedFile.fileFormat);
122
135
  if (hashStringSync(localeContent(localFile, uploadedFile.fileFormat, locale) ?? emptyLocaleContent(localFile, uploadedFile.fileFormat)) === downloadedVersion.postProcessHash) continue;
136
+ knownEdited = true;
123
137
  } catch {}
124
138
  candidates.push({
125
139
  branchId: uploadedFile.branchId,
@@ -128,7 +142,8 @@ async function collectAndSendUserEditDiffs(files, settings) {
128
142
  versionId: latestDownloaded.versionId,
129
143
  locale,
130
144
  outputPath,
131
- fileFormat: uploadedFile.fileFormat
145
+ fileFormat: uploadedFile.fileFormat,
146
+ knownEdited
132
147
  });
133
148
  }
134
149
  const collectedDiffs = [];
@@ -159,7 +174,15 @@ async function collectAndSendUserEditDiffs(files, settings) {
159
174
  for (const c of candidates) {
160
175
  const key = `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`;
161
176
  const payload = serverPayloadByKey.get(key);
162
- if (!payload) continue;
177
+ if (!payload) {
178
+ if (c.knownEdited) {
179
+ const relativePath = getRelative(c.outputPath);
180
+ const reason = `the ${c.locale} baseline recorded in the lockfile could not be retrieved, so the edit could not be compared`;
181
+ logger.warn(unsavedJsonEditsWarning(relativePath, c.locale, reason));
182
+ recordWarning("skipped_file", relativePath, reason);
183
+ }
184
+ continue;
185
+ }
163
186
  let serverContent;
164
187
  try {
165
188
  serverContent = localeContent(payload.data, payload.fileFormat, c.locale) ?? emptyLocaleContent(payload.data, payload.fileFormat);
@@ -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\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 const { entryMap } = readLockfile(settings);\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 };\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 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 } 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 });\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.\n if (!payload) continue;\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,MAAM,EAAE;GAAE;GAAgB;SAC/D;AACN,SAAO;GAAE;GAAS,gBAAgB,EAAE;GAAE;;;;;;;;AAS1C,MAAM,2BACJ,gBACA,iBACA,UACA,QACA,aACoB;AACpB,KAA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BAAgB,iBACpB,iBACA,EAAE,YACF,SACD;MACD,MAAM,mBAAmB,YACvB,cAAc,SACd,EAAE,UACF,SAAS,SACT,EAAE,QACF,SAAS,cACV;AACD,UAAI,kBAAkB;OACpB,MAAM,YAAY,UAAU,iBAAiB;OAG7C,MAAM,iBAAiB,wBACrB,cAAc,gBACd,cAAc,SACd,EAAE,UACF,EAAE,QACF,SACD;OACD,MAAM,SACJ,eAAe,SAAS,IACpB,uCAAuC,eAAe,KAAK,QAAQ,IAAI,QAAQ,CAAC,KAAK,KAAK,KAC1F,CAAC,aAAa,UAAU,GACtB,qEACA,KAAA;AACR,WAAI,QAAQ;QACV,MAAM,eAAe,YAAY,EAAE,WAAW;AAC9C,eAAO,KACL,wBAAwB,cAAc,EAAE,QAAQ,OAAO,CACxD;AACD,sBAAc,gBAAgB,cAAc,OAAO;AACnD;;AAEF,WAAI,kBAAkB,WAAW,UAAU,cAAc,CAAC,CACxD;AAEF,sBAAe;;iBAGhB,EAAE,SAAS,SAAS,QAAQ,IAAI,EAAE,SAAS,SAAS,OAAO,KAC5D,SAAS,SAAS,cAClB,EAAE,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 — 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,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,YAAY,EAAE,WAAW;AAC9C,eAAO,KACL,wBAAwB,cAAc,EAAE,QAAQ,OAAO,CACxD;AACD,sBAAc,gBAAgB,cAAc,OAAO;AACnD;;AAEF,WAAI,kBAAkB,WAAW,UAAU,cAAc,CAAC,CACxD;AAEF,sBAAe;;iBAGhB,EAAE,SAAS,SAAS,QAAQ,IAAI,EAAE,SAAS,SAAS,OAAO,KAC5D,SAAS,SAAS,cAClB,EAAE,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"}
@@ -3,4 +3,12 @@ import { Settings } from '../types/index.js';
3
3
  * Uploads current source files to obtain file references, then collects and sends
4
4
  * diffs for all locales based on last downloaded versions. Does not enqueue translations.
5
5
  */
6
- export declare function saveLocalEdits(settings: Settings): Promise<void>;
6
+ export declare function saveLocalEdits(settings: Settings): Promise<SaveLocalEditsOutcome>;
7
+ export type SaveLocalEditsOutcome = {
8
+ /** At least one diff was submitted. */
9
+ saved: boolean;
10
+ /** Locales the collector could not save, each already warned about. */
11
+ skipped: number;
12
+ };
13
+ /** The one completion message the command footer also uses. */
14
+ export declare const saveLocalEditsMessage: (outcome: SaveLocalEditsOutcome) => string;
@@ -4,27 +4,41 @@ import { logErrorAndExit } from "../console/logging.js";
4
4
  import { branchResolutionError } from "../console/index.js";
5
5
  import { api } from "../utils/api.js";
6
6
  import { BranchStep } from "../workflows/steps/BranchStep.js";
7
+ import { getWarnings } from "../state/translateWarnings.js";
7
8
  import { readLockfile } from "../fs/config/downloadedVersions.js";
8
9
  import { shouldPublishGt } from "../utils/resolvePublish.js";
9
10
  import { runPublishWorkflow } from "../workflows/publish.js";
10
11
  import { aggregateFiles } from "../formats/files/aggregateFiles.js";
11
12
  import { collectAndSendUserEditDiffs } from "./collectUserEditDiffs.js";
12
- import chalk from "chalk";
13
13
  //#region src/api/saveLocalEdits.ts
14
14
  /**
15
15
  * Uploads current source files to obtain file references, then collects and sends
16
16
  * diffs for all locales based on last downloaded versions. Does not enqueue translations.
17
17
  */
18
18
  async function saveLocalEdits(settings) {
19
- if (!settings.files) return;
19
+ if (!settings.files) return {
20
+ saved: false,
21
+ skipped: 0
22
+ };
20
23
  const { files, publishMap } = await aggregateFiles(settings);
24
+ if (!files.length && !settings.files.placeholderPaths.gt) return {
25
+ saved: false,
26
+ skipped: 0
27
+ };
28
+ const branchResult = await new BranchStep(api, settings).run();
29
+ if (!branchResult) return logErrorAndExit(branchResolutionError);
30
+ const branchId = branchResult.currentBranch.id;
31
+ const branchSettings = {
32
+ ...settings,
33
+ _branchId: branchId
34
+ };
21
35
  const fileRefs = files.map((file) => ({
22
36
  fileName: file.fileName,
23
37
  fileFormat: file.fileFormat,
24
38
  fileId: file.fileId,
25
39
  versionId: file.versionId
26
40
  }));
27
- const gtJsonEntry = settings.files.placeholderPaths.gt ? readLockfile(settings).entryMap.get(TEMPLATE_FILE_ID) : void 0;
41
+ const gtJsonEntry = settings.files.placeholderPaths.gt ? readLockfile(branchSettings).entryMap.get(TEMPLATE_FILE_ID) : void 0;
28
42
  if (gtJsonEntry) {
29
43
  fileRefs.push({
30
44
  fileName: TEMPLATE_FILE_NAME,
@@ -35,20 +49,32 @@ async function saveLocalEdits(settings) {
35
49
  const gtPublishValue = shouldPublishGt(settings);
36
50
  if (gtPublishValue !== void 0) publishMap.set(TEMPLATE_FILE_ID, gtPublishValue);
37
51
  }
38
- if (!fileRefs.length) return;
39
- const branchResult = await new BranchStep(api, settings).run();
40
- if (!branchResult) return logErrorAndExit(branchResolutionError);
52
+ if (!fileRefs.length) return {
53
+ saved: false,
54
+ skipped: 0
55
+ };
41
56
  const uploads = fileRefs.map((file) => ({
42
57
  ...file,
43
- branchId: branchResult.currentBranch.id
58
+ branchId
44
59
  }));
45
60
  const spinner = logger.createSpinner("dots");
46
61
  spinner.start("Saving local edits...");
62
+ const warningsBefore = getWarnings().length;
47
63
  const hadDiffs = await collectAndSendUserEditDiffs(uploads, settings);
48
- spinner.stop(chalk.green("Local edits saved successfully"));
49
- if (hadDiffs) await runPublishWorkflow(fileRefs, publishMap, branchResult.currentBranch.id, settings);
64
+ const outcome = {
65
+ saved: hadDiffs,
66
+ skipped: getWarnings().slice(warningsBefore).length
67
+ };
68
+ spinner.stop(saveLocalEditsMessage(outcome));
69
+ if (hadDiffs) await runPublishWorkflow(fileRefs, publishMap, branchId, settings);
70
+ return outcome;
50
71
  }
72
+ /** The one completion message the command footer also uses. */
73
+ const saveLocalEditsMessage = (outcome) => {
74
+ const skipped = outcome.skipped > 0 ? ` (skipped: ${outcome.skipped})` : "";
75
+ return outcome.saved ? `Local edits saved successfully${skipped}` : `No local edits were saved${skipped}`;
76
+ };
51
77
  //#endregion
52
- export { saveLocalEdits };
78
+ export { saveLocalEdits, saveLocalEditsMessage };
53
79
 
54
80
  //# sourceMappingURL=saveLocalEdits.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"saveLocalEdits.js","names":[],"sources":["../../src/api/saveLocalEdits.ts"],"sourcesContent":["import { Settings } from '../types/index.js';\nimport { aggregateFiles } from '../formats/files/aggregateFiles.js';\nimport { collectAndSendUserEditDiffs } from './collectUserEditDiffs.js';\nimport { api } from '../utils/api.js';\nimport { BranchStep } from '../workflows/steps/BranchStep.js';\nimport { logErrorAndExit } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { branchResolutionError } from '../console/index.js';\nimport type { FileReference } from 'generaltranslation/types';\nimport chalk from 'chalk';\nimport { runPublishWorkflow } from '../workflows/publish.js';\nimport { readLockfile } from '../fs/config/downloadedVersions.js';\nimport { TEMPLATE_FILE_ID, TEMPLATE_FILE_NAME } from '../utils/constants.js';\nimport { shouldPublishGt } from '../utils/resolvePublish.js';\n\n/**\n * Uploads current source files to obtain file references, then collects and sends\n * diffs for all locales based on last downloaded versions. Does not enqueue translations.\n */\nexport async function saveLocalEdits(settings: Settings): Promise<void> {\n if (!settings.files) return;\n\n // Collect current files from config\n const { files, publishMap } = await aggregateFiles(settings);\n const fileRefs = files.map((file) => ({\n fileName: file.fileName,\n fileFormat: file.fileFormat,\n fileId: file.fileId,\n versionId: file.versionId,\n }));\n\n // Include the GT JSON at its last downloaded version\n const gtJsonEntry = settings.files.placeholderPaths.gt\n ? readLockfile(settings).entryMap.get(TEMPLATE_FILE_ID)\n : undefined;\n if (gtJsonEntry) {\n fileRefs.push({\n fileName: TEMPLATE_FILE_NAME,\n fileFormat: 'GTJSON',\n fileId: TEMPLATE_FILE_ID,\n versionId: gtJsonEntry.versionId,\n });\n const gtPublishValue = shouldPublishGt(settings);\n if (gtPublishValue !== undefined) {\n publishMap.set(TEMPLATE_FILE_ID, gtPublishValue);\n }\n }\n if (!fileRefs.length) return;\n\n // run branch query to get branch id\n // Run the branch step\n const branchStep = new BranchStep(api, settings);\n const branchResult = await branchStep.run();\n if (!branchResult) {\n return logErrorAndExit(branchResolutionError);\n }\n\n const uploads = fileRefs.map((file) => ({\n ...file,\n branchId: branchResult.currentBranch.id,\n })) satisfies FileReference[];\n\n const spinner = logger.createSpinner('dots');\n spinner.start('Saving local edits...');\n\n const hadDiffs = await collectAndSendUserEditDiffs(uploads, settings);\n spinner.stop(chalk.green('Local edits saved successfully'));\n\n // Publish files to CDN if diffs were detected and publish config exists\n if (hadDiffs) {\n await runPublishWorkflow(\n fileRefs,\n publishMap,\n branchResult.currentBranch.id,\n settings\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,eAAsB,eAAe,UAAmC;AACtE,KAAI,CAAC,SAAS,MAAO;CAGrB,MAAM,EAAE,OAAO,eAAe,MAAM,eAAe,SAAS;CAC5D,MAAM,WAAW,MAAM,KAAK,UAAU;EACpC,UAAU,KAAK;EACf,YAAY,KAAK;EACjB,QAAQ,KAAK;EACb,WAAW,KAAK;EACjB,EAAE;CAGH,MAAM,cAAc,SAAS,MAAM,iBAAiB,KAChD,aAAa,SAAS,CAAC,SAAS,IAAI,iBAAiB,GACrD,KAAA;AACJ,KAAI,aAAa;AACf,WAAS,KAAK;GACZ,UAAU;GACV,YAAY;GACZ,QAAQ;GACR,WAAW,YAAY;GACxB,CAAC;EACF,MAAM,iBAAiB,gBAAgB,SAAS;AAChD,MAAI,mBAAmB,KAAA,EACrB,YAAW,IAAI,kBAAkB,eAAe;;AAGpD,KAAI,CAAC,SAAS,OAAQ;CAKtB,MAAM,eAAe,MAAM,IADJ,WAAW,KAAK,SACF,CAAC,KAAK;AAC3C,KAAI,CAAC,aACH,QAAO,gBAAgB,sBAAsB;CAG/C,MAAM,UAAU,SAAS,KAAK,UAAU;EACtC,GAAG;EACH,UAAU,aAAa,cAAc;EACtC,EAAE;CAEH,MAAM,UAAU,OAAO,cAAc,OAAO;AAC5C,SAAQ,MAAM,wBAAwB;CAEtC,MAAM,WAAW,MAAM,4BAA4B,SAAS,SAAS;AACrE,SAAQ,KAAK,MAAM,MAAM,iCAAiC,CAAC;AAG3D,KAAI,SACF,OAAM,mBACJ,UACA,YACA,aAAa,cAAc,IAC3B,SACD"}
1
+ {"version":3,"file":"saveLocalEdits.js","names":[],"sources":["../../src/api/saveLocalEdits.ts"],"sourcesContent":["import { Settings } from '../types/index.js';\nimport { aggregateFiles } from '../formats/files/aggregateFiles.js';\nimport { collectAndSendUserEditDiffs } from './collectUserEditDiffs.js';\nimport { api } from '../utils/api.js';\nimport { BranchStep } from '../workflows/steps/BranchStep.js';\nimport { logErrorAndExit } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { branchResolutionError } from '../console/index.js';\nimport type { FileReference } from 'generaltranslation/types';\nimport { runPublishWorkflow } from '../workflows/publish.js';\nimport { readLockfile } from '../fs/config/downloadedVersions.js';\nimport { TEMPLATE_FILE_ID, TEMPLATE_FILE_NAME } from '../utils/constants.js';\nimport { shouldPublishGt } from '../utils/resolvePublish.js';\nimport { getWarnings } from '../state/translateWarnings.js';\n\n/**\n * Uploads current source files to obtain file references, then collects and sends\n * diffs for all locales based on last downloaded versions. Does not enqueue translations.\n */\nexport async function saveLocalEdits(\n settings: Settings\n): Promise<SaveLocalEditsOutcome> {\n if (!settings.files) return { saved: false, skipped: 0 };\n\n // Collect current files from config\n const { files, publishMap } = await aggregateFiles(settings);\n // Nothing to save and no template to include: resolve the branch only once\n // there is something to read from the lockfile, since resolving it can\n // create the branch on the remote.\n if (!files.length && !settings.files.placeholderPaths.gt) {\n return { saved: false, skipped: 0 };\n }\n\n // Resolve the branch before reading anything out of the lockfile: a v1\n // lockfile keeps every branch it has seen, and without a branch it is read\n // from whichever one is listed first.\n const branchStep = new BranchStep(api, settings);\n const branchResult = await branchStep.run();\n if (!branchResult) {\n return logErrorAndExit(branchResolutionError);\n }\n const branchId = branchResult.currentBranch.id;\n const branchSettings: Settings = { ...settings, _branchId: branchId };\n\n const fileRefs = files.map((file) => ({\n fileName: file.fileName,\n fileFormat: file.fileFormat,\n fileId: file.fileId,\n versionId: file.versionId,\n }));\n\n // Include the GT JSON at its last downloaded version\n const gtJsonEntry = settings.files.placeholderPaths.gt\n ? readLockfile(branchSettings).entryMap.get(TEMPLATE_FILE_ID)\n : undefined;\n if (gtJsonEntry) {\n fileRefs.push({\n fileName: TEMPLATE_FILE_NAME,\n fileFormat: 'GTJSON',\n fileId: TEMPLATE_FILE_ID,\n versionId: gtJsonEntry.versionId,\n });\n const gtPublishValue = shouldPublishGt(settings);\n if (gtPublishValue !== undefined) {\n publishMap.set(TEMPLATE_FILE_ID, gtPublishValue);\n }\n }\n if (!fileRefs.length) return { saved: false, skipped: 0 };\n\n const uploads = fileRefs.map((file) => ({\n ...file,\n branchId,\n })) satisfies FileReference[];\n\n const spinner = logger.createSpinner('dots');\n spinner.start('Saving local edits...');\n\n // Only the warnings this collection adds describe locales it could not save;\n // earlier runs leave their own warnings in the same list.\n const warningsBefore = getWarnings().length;\n const hadDiffs = await collectAndSendUserEditDiffs(uploads, settings);\n const skipped = getWarnings().slice(warningsBefore).length;\n const outcome: SaveLocalEditsOutcome = { saved: hadDiffs, skipped };\n spinner.stop(saveLocalEditsMessage(outcome));\n\n // Publish files to CDN if diffs were detected and publish config exists\n if (hadDiffs) {\n await runPublishWorkflow(fileRefs, publishMap, branchId, settings);\n }\n\n return outcome;\n}\n\nexport type SaveLocalEditsOutcome = {\n /** At least one diff was submitted. */\n saved: boolean;\n /** Locales the collector could not save, each already warned about. */\n skipped: number;\n};\n\n/** The one completion message the command footer also uses. */\nexport const saveLocalEditsMessage = (\n outcome: SaveLocalEditsOutcome\n): string => {\n // The count covers locales the collector skipped, which can include an\n // untouched file whose baseline only failed to parse. Name the count\n // instead of claiming the edits themselves were unsaved.\n const skipped = outcome.skipped > 0 ? ` (skipped: ${outcome.skipped})` : '';\n return outcome.saved\n ? `Local edits saved successfully${skipped}`\n : `No local edits were saved${skipped}`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,eAAsB,eACpB,UACgC;AAChC,KAAI,CAAC,SAAS,MAAO,QAAO;EAAE,OAAO;EAAO,SAAS;EAAG;CAGxD,MAAM,EAAE,OAAO,eAAe,MAAM,eAAe,SAAS;AAI5D,KAAI,CAAC,MAAM,UAAU,CAAC,SAAS,MAAM,iBAAiB,GACpD,QAAO;EAAE,OAAO;EAAO,SAAS;EAAG;CAOrC,MAAM,eAAe,MAAM,IADJ,WAAW,KAAK,SACF,CAAC,KAAK;AAC3C,KAAI,CAAC,aACH,QAAO,gBAAgB,sBAAsB;CAE/C,MAAM,WAAW,aAAa,cAAc;CAC5C,MAAM,iBAA2B;EAAE,GAAG;EAAU,WAAW;EAAU;CAErE,MAAM,WAAW,MAAM,KAAK,UAAU;EACpC,UAAU,KAAK;EACf,YAAY,KAAK;EACjB,QAAQ,KAAK;EACb,WAAW,KAAK;EACjB,EAAE;CAGH,MAAM,cAAc,SAAS,MAAM,iBAAiB,KAChD,aAAa,eAAe,CAAC,SAAS,IAAI,iBAAiB,GAC3D,KAAA;AACJ,KAAI,aAAa;AACf,WAAS,KAAK;GACZ,UAAU;GACV,YAAY;GACZ,QAAQ;GACR,WAAW,YAAY;GACxB,CAAC;EACF,MAAM,iBAAiB,gBAAgB,SAAS;AAChD,MAAI,mBAAmB,KAAA,EACrB,YAAW,IAAI,kBAAkB,eAAe;;AAGpD,KAAI,CAAC,SAAS,OAAQ,QAAO;EAAE,OAAO;EAAO,SAAS;EAAG;CAEzD,MAAM,UAAU,SAAS,KAAK,UAAU;EACtC,GAAG;EACH;EACD,EAAE;CAEH,MAAM,UAAU,OAAO,cAAc,OAAO;AAC5C,SAAQ,MAAM,wBAAwB;CAItC,MAAM,iBAAiB,aAAa,CAAC;CACrC,MAAM,WAAW,MAAM,4BAA4B,SAAS,SAAS;CAErE,MAAM,UAAiC;EAAE,OAAO;EAAU,SAD1C,aAAa,CAAC,MAAM,eAAe,CAAC;EACe;AACnE,SAAQ,KAAK,sBAAsB,QAAQ,CAAC;AAG5C,KAAI,SACF,OAAM,mBAAmB,UAAU,YAAY,UAAU,SAAS;AAGpE,QAAO;;;AAWT,MAAa,yBACX,YACW;CAIX,MAAM,UAAU,QAAQ,UAAU,IAAI,cAAc,QAAQ,QAAQ,KAAK;AACzE,QAAO,QAAQ,QACX,iCAAiC,YACjC,4BAA4B"}
package/dist/cli/base.js CHANGED
@@ -39,7 +39,7 @@ import { handleDownload } from "./commands/download.js";
39
39
  import { handleTranslate, postProcessTranslations } from "./commands/translate.js";
40
40
  import { displayTranslateSummary } from "../console/displayTranslateSummary.js";
41
41
  import { createLoadTranslationsFile, findLoadTranslationsFiles } from "../fs/createLoadTranslationsFile.js";
42
- import { saveLocalEdits } from "../api/saveLocalEdits.js";
42
+ import { saveLocalEdits, saveLocalEditsMessage } from "../api/saveLocalEdits.js";
43
43
  import processSharedStaticAssets, { mirrorAssetsToLocales } from "../utils/sharedStaticAssets.js";
44
44
  import { setupLocadex } from "../locadex/setupFlow.js";
45
45
  import { detectFramework } from "../setup/detectFramework.js";
@@ -188,8 +188,8 @@ var BaseCLI = class {
188
188
  displayHeader("Saving local edits...");
189
189
  const settings = await generateSettings(initOptions, void 0, { requireConfig: true });
190
190
  if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings)) return exitSync(1);
191
- await saveLocalEdits(settings);
192
- logger.endCommand("Saved local edits");
191
+ const outcome = await saveLocalEdits(settings);
192
+ logger.endCommand(saveLocalEditsMessage(outcome));
193
193
  });
194
194
  }
195
195
  setupApiCommand() {
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../src/cli/base.ts"],"sourcesContent":["import { Argument, Command, InvalidArgumentError, Option } from 'commander';\nimport {\n OrgApiKeyPermission,\n ProjectApiKeyPermission,\n} from 'generaltranslation/api';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport {\n applySetupConfig,\n mergeSetupConfig,\n type SetupConfigUpdate,\n} from '../fs/config/setupConfig.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport {\n displayHeader,\n promptText,\n logErrorAndExit,\n exitSync,\n promptConfirm,\n promptMultiSelect,\n promptSelect,\n promptGlobPatterns,\n} from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { lottieTranslateError } from '../console/index.js';\nimport { parseGlobPatterns } from '../console/promptParsing.js';\nimport path from 'node:path';\nimport {\n FilesOptions,\n Settings,\n SupportedFrameworks,\n SupportedLibraries,\n TranslateFlags,\n SharedFlags,\n} from '../types/index.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport chalk from 'chalk';\nimport {\n FILE_EXT_TO_EXT_LABEL,\n SETUP_FILE_FORMATS,\n SUPPORTED_FILE_EXTENSIONS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n executeReactSetup,\n resolveReactSetup,\n type ReactSetupPlan,\n} from '../setup/wizard.js';\nimport { formatInitNextSteps, getInitNextSteps } from '../setup/nextSteps.js';\nimport { getPackageManager } from '../utils/packageManager.js';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { getDesiredLocales } from '../setup/userInput.js';\nimport {\n areCredentialsSet,\n getDevelopmentEnvNames,\n inspectCredentialsEnvFile,\n} from '../utils/credentials.js';\nimport {\n checkDevelopmentProjectInputs,\n productionRuntimeKeyGuidance,\n provisionDevelopmentCredentials,\n resolveDevelopmentProject,\n signInForSetup,\n} from '../setup/developmentCredentials.js';\nimport {\n exitIfUnsupportedSetupTarget,\n reactNativeSetupError,\n} from '../setup/setupTarget.js';\nimport {\n asRecord,\n attachConfigureFlags,\n attachInitFlags,\n describeDefaults,\n displaySetupHeader,\n getConfiguredFramework,\n INIT_SOURCE_HELP,\n installWithProgress,\n OnboardingError,\n parseFilePatterns,\n readSetupConfig,\n reportJsonExitsBeforeOnboarding,\n resolvePackageManager,\n runOnboarding,\n setupConfigPath,\n validateSetupPattern,\n type ConfigureOptions,\n type InitOptions,\n type OnboardingSession,\n} from '../setup/onboarding.js';\nimport { upload } from './commands/upload.js';\nimport { attachSharedFlags, attachTranslateFlags } from './flags.js';\nimport { handleStage } from './commands/stage.js';\nimport { handleSetupProject } from './commands/setupProject.js';\nimport { handleDownload } from './commands/download.js';\nimport {\n handleTranslate,\n postProcessTranslations,\n} from './commands/translate.js';\nimport {\n getNeedsPostprocessing,\n clearDownloaded,\n} from '../state/recentDownloads.js';\nimport { clearWarnings } from '../state/translateWarnings.js';\nimport { displayTranslateSummary } from '../console/displayTranslateSummary.js';\nimport updateConfig from '../fs/config/updateConfig.js';\nimport {\n createLoadTranslationsFile,\n findLoadTranslationsFiles,\n} from '../fs/createLoadTranslationsFile.js';\nimport { saveLocalEdits } from '../api/saveLocalEdits.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './commands/utils/validation.js';\nimport processSharedStaticAssets, {\n mirrorAssetsToLocales,\n} from '../utils/sharedStaticAssets.js';\nimport { setupLocadex } from '../locadex/setupFlow.js';\nimport { detectFramework } from '../setup/detectFramework.js';\nimport { INLINE_LIBRARIES, Libraries } from '../types/libraries.js';\nimport { handleEnqueue } from './commands/enqueue.js';\nimport { splitMintlifyLanguageRefs } from '../utils/splitMintlifyLanguageRefs.js';\nimport { localizeMintlifyRedirects } from '../formats/files/postprocess/localizeMintlifyRedirects.js';\nimport {\n clearOrphanedFileNames,\n getOrphanedFileNames,\n} from '../state/orphanedFileNames.js';\nimport { runMergeDriver, type MergeDriverName } from '../git/mergeDrivers.js';\nimport { setupGitMergeDrivers } from '../git/setupMergeDrivers.js';\nimport { warnReactPackageCompatibility } from '../utils/reactPackageCompatibility.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { hasLogin, logout, whoAmI } from '../auth/oauth.js';\nimport { createUserAuthError, UserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { resolveConfig } from '../config/resolveConfig.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport {\n getBuildToolSetup,\n getSetupDocsUrl,\n type ManualAction,\n type SetupResult,\n} from '../setup/buildTools/index.js';\nimport { manifestDirectlyDeclaresGTVue } from '@generaltranslation/vue-extractor/integration';\nimport { api, configureApiClient } from '../utils/api.js';\nimport { handleApiCommand, type ApiCommandOptions } from './commands/api.js';\n\nconst ID_COMPATIBILITY_WARNING_COMMANDS = new Set([\n 'download',\n 'enqueue',\n 'generate',\n 'setup',\n 'stage',\n 'translate',\n 'validate',\n]);\nfunction createProjectCommandError(\n whatHappened: string,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened,\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst emptyApiKeyNameError = createDiagnosticMessage({\n whatHappened: 'The key name cannot be empty',\n fix: 'Pass a non-empty value with --name',\n});\n\nconst projectApiKeyPermissions = new Set<string>(\n Object.values(ProjectApiKeyPermission)\n);\n\nfunction isProjectApiKeyPermission(\n permission: OrgApiKeyPermission\n): permission is ProjectApiKeyPermission {\n return projectApiKeyPermissions.has(permission);\n}\n\nfunction parseApiKeyName(value: string): string {\n const name = value.trim();\n if (!name) throw new InvalidArgumentError(emptyApiKeyNameError);\n return name;\n}\n\n/** Credential failures keep their own diagnostic or get the setup context. */\nasync function withCredentialsError<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof OnboardingError) throw error;\n throw new Error(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError(\n 'Failed to set up the development credentials',\n error\n )\n );\n }\n}\n\nexport type UploadOptions = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n defaultLocale?: string;\n};\n\nexport type GitSetupOptions = {\n config?: string;\n dryRun?: boolean;\n omitConfigIds?: boolean;\n driverCommand?: string;\n};\n\ntype LocalTranslationGuidanceOptions = {\n generatedLoader: boolean;\n runtimeSetup: InlineRuntimeSetup;\n translationsDir: string;\n};\n\ntype InlineRuntimeSetup = {\n hasOtherInlineRuntime: boolean;\n hasVueRuntime: boolean;\n ranReactSetup: boolean;\n};\n\nexport class BaseCLI {\n protected library: SupportedLibraries;\n protected additionalModules: SupportedLibraries[];\n protected program: Command;\n // Constructor is shared amongst all CLI class types\n public constructor(\n program: Command,\n library: SupportedLibraries,\n additionalModules?: SupportedLibraries[]\n ) {\n this.program = program;\n this.library = library;\n this.additionalModules = additionalModules || [];\n\n this.program.option(\n '--skip-version-check',\n 'Skip the monorepo GT package version consistency check'\n );\n this.program.option(\n '--suppress-id-compatibility-warning',\n 'Suppress the React package ID compatibility warning'\n );\n this.program.option(\n '-q, --quiet',\n 'Suppress informational output; only warnings and errors are shown'\n );\n // Select console routing for this command before anything else logs:\n // root hooks run before subclass hooks (version checks) and the action's\n // settings resolution. `gt api-key create` prints the new secret on\n // stdout, so its diagnostics go to stderr, as do setup commands writing\n // JSON events; every other command gets the historical default back\n // (main() routes startup output to stderr).\n this.program.hook('preAction', (thisCommand, actionCommand) => {\n logger.setConsoleOutput(\n actionCommand.parent?.name() === 'api-key' || actionCommand.opts().json\n ? 'stderr'\n : 'stdout'\n );\n if (\n actionCommand.opts().json &&\n actionCommand.parent === thisCommand &&\n ['init', 'configure'].includes(actionCommand.name())\n ) {\n reportJsonExitsBeforeOnboarding(actionCommand.name());\n }\n });\n // Apply --quiet before any other hook or command action runs so the\n // singleton logger is muted for the rest of the invocation. The flag is a\n // global root option, so commander resolves it in any position and for\n // nested commands (e.g. `gt git setup --quiet`).\n this.program.hook('preAction', () => {\n logger.setQuiet(Boolean(this.program.opts().quiet));\n });\n this.program.hook('preAction', async (thisCommand, actionCommand) => {\n // Nested commands (e.g. `gt git setup`) can share leaf names with\n // translation commands; only direct children of the root qualify\n if (actionCommand.parent !== thisCommand) return;\n if (!ID_COMPATIBILITY_WARNING_COMMANDS.has(actionCommand.name())) return;\n await warnReactPackageCompatibility(\n Boolean(this.program.opts().suppressIdCompatibilityWarning)\n );\n });\n\n this.setupInitCommand();\n this.setupConfigureCommand();\n this.setupUploadCommand();\n this.setupUserAuthCommands();\n this.setupSendDiffsCommand();\n this.setupApiCommand();\n this.setupProjectCommands();\n this.setupApiKeyCommands();\n this.setupGitCommand();\n }\n // Init is never called in a child class\n public init() {\n this.setupSetupProjectCommand();\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n // Execute is called by the main program\n public execute() {\n // If no command is specified, run 'init'\n if (process.argv.length <= 2) {\n process.argv.push('init');\n }\n }\n\n protected setupSetupProjectCommand(): void {\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupStageCommand(): void {\n attachTranslateFlags(\n this.program\n .command('stage')\n .description(\n 'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupEnqueueCommand(): void {\n attachTranslateFlags(\n this.program\n .command('enqueue')\n .description('Enqueues translations for a given set of files')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Enqueuing translations...');\n await this.handleEnqueue(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupDownloadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('download')\n .description('Download translations that were originally staged')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Downloading translations...');\n await this.handleDownload(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachTranslateFlags(\n this.program\n .command('translate')\n .description('Translate your project using General Translation')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Starting translation...');\n await this.handleTranslate(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupSendDiffsCommand(): void {\n attachSharedFlags(\n this.program\n .command('save-local')\n .description(\n 'Save local edits for all configured files by sending diffs (no translation enqueued)'\n )\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .action(async (initOptions: SharedFlags) => {\n displayHeader('Saving local edits...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n await saveLocalEdits(settings);\n logger.endCommand('Saved local edits');\n });\n }\n\n protected setupApiCommand(): void {\n attachSharedFlags(\n this.program\n .command('api [endpoint]')\n .description('Make an authenticated request to the GT API')\n .option('-X, --method <method>', 'HTTP method', 'GET')\n .option('--input <file>', 'Request body file, or - for standard input')\n .option(\n '-H, --header <header>',\n 'Request header in \"Key: Value\" format',\n (header, headers: string[] | undefined) => [\n ...(headers ?? []),\n header,\n ]\n )\n .option('-i, --include', 'Include response status and headers')\n .option(\n '--spec',\n 'Print the bundled OpenAPI specification, or only the operations matching [endpoint] (path or operation ID) with references resolved'\n )\n .addOption(\n new Option(\n '--list',\n 'List the method, path, operation ID, and summary of every API operation'\n ).conflicts('spec')\n )\n ).action((endpoint, options: ApiCommandOptions) =>\n handleApiCommand(endpoint, options)\n );\n }\n\n protected setupProjectCommands(): void {\n const projectCommand = this.program\n .command('project')\n .description('Manage General Translation projects');\n\n attachSharedFlags(\n projectCommand\n .command('create')\n .description(\n 'Create a General Translation project using an organization API key'\n )\n .requiredOption('--org-id <orgId>', 'Organization ID')\n .requiredOption('--name <name>', 'Project name')\n .requiredOption('--default-locale <locale>', 'Project default locale')\n .option('--cdn-enabled', 'Enable CDN delivery', false)\n ).action(async (options) => {\n try {\n const settings = await generateSettings(options);\n // Project creation happens before a project ID exists.\n if (!hasValidServiceLocales(settings)) return exitSync(1);\n const { project } = await api.createProject(options.orgId, {\n name: options.name,\n defaultLocale: options.defaultLocale,\n cdnEnabled: options.cdnEnabled,\n });\n logger.info(`Created ${project.name} (${project.id})`);\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError('Failed to create the project', error)\n );\n }\n });\n\n attachSharedFlags(\n projectCommand\n .command('status')\n .description('Check the status of a project setup job')\n .argument('<job-id>', 'Setup job ID')\n ).action(async (jobId, options) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const [status] = await api.checkJobStatus([jobId]);\n logger.info(status?.status ?? 'unknown');\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError(\n 'Failed to check the project setup status',\n error\n )\n );\n }\n });\n }\n\n protected setupApiKeyCommands(): void {\n const apiKeyCommand = this.program\n .command('api-key')\n .description(\n 'Manage API keys for the configured project or an organization'\n );\n\n attachSharedFlags(\n apiKeyCommand\n .command('create')\n .description(\n 'Create a project API key, or an organization API key with --org-id, with the requested permissions and print it once'\n )\n .requiredOption('--name <name>', 'Key name', parseApiKeyName)\n .option(\n '--org-id <orgId>',\n 'Create an organization API key for this organization instead (requires gt login)'\n )\n // Validated before any request; the server grants the requested set\n // all-or-nothing, so omitting permissions would delegate everything.\n .addOption(\n new Option('--permission <permissions...>', 'Permissions to grant')\n .choices(Object.values(OrgApiKeyPermission))\n .makeOptionMandatory()\n )\n ).action(\n async (\n options: SharedFlags & {\n name: string;\n orgId?: string;\n permission: OrgApiKeyPermission[];\n }\n ) => {\n const projectPermissions = options.permission.filter(\n isProjectApiKeyPermission\n );\n const orgOnlyPermissions = options.permission.filter(\n (permission) => !isProjectApiKeyPermission(permission)\n );\n if (!options.orgId && orgOnlyPermissions.length > 0) {\n return logErrorAndExit(\n createDiagnosticMessage({\n whatHappened: `${orgOnlyPermissions.join(', ')} can only be granted to organization API keys`,\n fix: 'Pass --org-id, or remove those permissions',\n })\n );\n }\n try {\n const settings = await generateSettings(options);\n let key: string;\n if (options.orgId) {\n // No API key can create organization keys, so always send the\n // signed-in user's token, even when an API key is configured.\n configureApiClient({\n baseUrl: settings.baseUrl,\n userTokenProvider: settings.userTokenProvider,\n });\n const { apiKey } = await api.createOrgApiKey(options.orgId, {\n name: options.name,\n permissions: options.permission,\n });\n key = apiKey.key;\n } else {\n if (!hasValidCredentials(settings)) return exitSync(1);\n const { apiKey } = await api.createProjectApiKey(\n settings.projectId,\n { name: options.name, permissions: projectPermissions }\n );\n key = apiKey.key;\n }\n // Raw stdout: the secret is shown once and never reaches the log file.\n process.stdout.write(`${key}\\n`);\n } catch (error) {\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError('Failed to create the API key', error)\n );\n }\n }\n );\n }\n\n protected setupGitCommand(): void {\n const gitCommand = this.program\n .command('git')\n .description('Configure Git integrations for General Translation');\n\n gitCommand\n .command('setup')\n .description('Set up GT merge drivers for generated translation files')\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--dry-run', 'Print changes without writing files', false)\n .option(\n '--omit-config-ids',\n 'Persist omitConfigIds and remove generated config IDs'\n )\n .option(\n '--driver-command <command>',\n 'Command Git should use to invoke gt, e.g. \"pnpm exec gt\"'\n )\n .action(async (options: GitSetupOptions) => {\n displayHeader('Setting up GT Git merge drivers...');\n const settings = await generateSettings(options, undefined, {\n requireConfig: true,\n });\n const omitConfigIds = await this.resolveGitSetupOmitConfigIds(\n options,\n settings\n );\n const result = await setupGitMergeDrivers(settings, {\n dryRun: options.dryRun,\n omitConfigIds,\n driverCommand: options.driverCommand,\n });\n\n for (const line of result.addedAttributes) {\n logger.step(\n `${options.dryRun ? 'Would add' : 'Added'} ${chalk.cyan(\n line\n )} to ${chalk.cyan(result.gitattributesPath)}`\n );\n }\n if (result.addedAttributes.length === 0) {\n logger.info(`${chalk.cyan('.gitattributes')} is already configured.`);\n }\n\n for (const args of result.gitConfigCommands) {\n logger.step(\n `${options.dryRun ? 'Would run' : 'Configured'} ${chalk.cyan(\n `git config --local ${args.join(' ')}`\n )}`\n );\n }\n\n if (result.updatedConfig) {\n logger.step(\n `${options.dryRun ? 'Would persist' : 'Persisted'} ${chalk.cyan(\n 'omitConfigIds: true'\n )} in ${chalk.cyan(settings.config)}`\n );\n } else if (options.dryRun && !settings.omitConfigIds) {\n logger.info(\n `Run without ${chalk.cyan('--dry-run')} to be prompted to persist ${chalk.cyan(\n 'omitConfigIds: true'\n )}, or pass ${chalk.cyan('--omit-config-ids')}.`\n );\n }\n\n for (const warning of result.warnings) {\n logger.warn(chalk.yellow(warning));\n }\n\n logger.endCommand(\n options.dryRun\n ? 'Dry run complete.'\n : 'GT Git merge drivers configured.'\n );\n });\n\n gitCommand\n .command('merge-driver', { hidden: true })\n .addArgument(\n new Argument('<driver>', 'Merge driver name').choices([\n 'gt-lock',\n 'gtjson',\n ])\n )\n .argument('<base>', 'Common ancestor file')\n .argument('<ours>', 'Current branch file')\n .argument('<theirs>', 'Incoming branch file')\n .argument('[path]', 'Merged path')\n .action(\n (\n driver: MergeDriverName,\n base: string,\n ours: string,\n theirs: string\n ) => {\n const result = runMergeDriver(driver, base, ours, theirs);\n if (!result.ok) {\n logger.error(result.reason);\n exitSync(1);\n }\n }\n );\n }\n\n protected async resolveGitSetupOmitConfigIds(\n options: GitSetupOptions,\n settings: Settings\n ): Promise<boolean> {\n if (options.omitConfigIds) return true;\n // Already opted in: persist again so stale config IDs still get removed\n if (settings.omitConfigIds) return true;\n if (options.dryRun || !process.stdin.isTTY || !process.stdout.isTTY) {\n return false;\n }\n return promptConfirm({\n message:\n 'Also set omitConfigIds: true to reduce gt.config.json merge conflicts?',\n defaultValue: true,\n });\n }\n\n protected async handleSetupProject(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n await handleSetupProject(initOptions, settings, this.library);\n }\n\n protected async handleStage(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Update settings.stageTranslations to true\n settings.stageTranslations = true;\n await updateConfig(settings.config, {\n stageTranslations: true,\n });\n }\n await handleStage(initOptions, settings, this.library, true);\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleEnqueue(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleEnqueue(initOptions, settings, this.library);\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleDownload(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleDownload(initOptions, settings, this.library);\n await this.finalizeDownloadedTranslations(settings);\n }\n\n protected async handleTranslate(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Lottie translations finish asynchronously server-side (layout\n // refinement runs after the translation job completes), so the immediate\n // translate flow would try to download them before they're ready. Only\n // the stage + download flow supports them.\n if (settings.files?.resolvedPaths.lottie?.length) {\n return logErrorAndExit(lottieTranslateError);\n }\n const results = await handleStage(\n initOptions,\n settings,\n this.library,\n false\n );\n if (results) {\n await handleTranslate(\n initOptions,\n settings,\n results.fileVersionData,\n results.jobData,\n results.branchData,\n results.publishMap,\n results.inlineLibrary\n );\n }\n } else {\n await handleDownload(initOptions, settings, this.library);\n }\n await this.finalizeDownloadedTranslations(settings);\n }\n\n /**\n * Postprocesses the translations downloaded in this run and reports the\n * summary. Shared by translate and download so both write the same output.\n * @param settings - The settings for the command\n */\n protected async finalizeDownloadedTranslations(\n settings: Settings\n ): Promise<void> {\n // Only postprocess files downloaded in this run\n const include = getNeedsPostprocessing();\n if (include.size > 0) {\n await postProcessTranslations(settings, include);\n }\n // Split Mintlify language entries into $ref files to keep docs.json small\n await splitMintlifyLanguageRefs(settings);\n // Localize redirects for pages this run renamed or removed. Runs after the\n // split, which can rewrite $ref files such as redirects.json\n const orphanedFileNames = getOrphanedFileNames();\n if (orphanedFileNames) {\n const added = localizeMintlifyRedirects(settings, orphanedFileNames);\n if (added.length > 0) {\n logger.success(\n `Added ${added.length} localized redirect${added.length === 1 ? '' : 's'}`\n );\n }\n }\n clearOrphanedFileNames();\n // Mirror assets after translations are downloaded and locale dirs are populated\n await mirrorAssetsToLocales(settings);\n clearDownloaded();\n displayTranslateSummary();\n clearWarnings();\n }\n\n protected setupUploadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('upload')\n .description(\n 'Upload source files and translations to the General Translation platform'\n )\n ).action(async (initOptions: UploadOptions) => {\n displayHeader('Starting upload...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const options = { ...initOptions, ...settings };\n\n await this.handleUploadCommand(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupUserAuthCommands(): void {\n this.program\n .command('login')\n .description('Sign in to your General Translation account')\n .option(\n '--no-browser',\n 'Do not open a browser; show a sign-in URL to use on any device instead'\n )\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json'\n )\n .action(async (options: { browser: boolean; config?: string }) => {\n displayHeader('Signing in to General Translation...');\n try {\n // Tokens are bound to one API resource, so log in to the configured one.\n const baseUrl = (\n options.config\n ? loadConfig(withJsonExtension(options.config))\n : resolveConfig(process.cwd())?.config\n )?.baseUrl;\n await loginInteractively(\n typeof baseUrl === 'string' ? baseUrl : undefined,\n options.browser\n );\n logger.endCommand('You are now signed in.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign in failed', error));\n }\n });\n\n this.program\n .command('logout')\n .description('Sign out of your General Translation account')\n .action(async () => {\n try {\n await logout();\n logger.endCommand('Signed out successfully.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign out failed', error));\n }\n });\n\n this.program\n .command('whoami')\n .description('Show the signed-in General Translation account')\n .action(async () => {\n try {\n const user = await whoAmI();\n logger.message(user.email ?? user.name ?? user.sub);\n } catch (error) {\n logErrorAndExit(\n createUserAuthError('Could not load your account', error)\n );\n }\n });\n }\n\n protected setupInitCommand(): void {\n attachInitFlags(\n this.program\n .command('init')\n .description(\n 'Run the setup wizard to configure your project for General Translation. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: InitOptions) => this.handleInitWizard(options));\n }\n\n protected async handleInitWizard(options: InitOptions): Promise<void> {\n await runOnboarding('init', options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Running setup wizard...');\n\n const detected = await detectFramework();\n // Stop before any change rather than set React Native up as web React.\n if (detected.type === 'react-native') {\n throw new OnboardingError(reactNativeSetupError);\n }\n const reactDetected = detected.type === 'react' ? detected : undefined;\n if (options.framework && !reactDetected) {\n session.reject(\n '--framework applies only to projects detected as React applications'\n );\n }\n const configFilepath = setupConfigPath(options);\n const configured = getConfiguredFramework(\n readSetupConfig(configFilepath)\n );\n const configuredReact =\n configured !== 'mintlify' ? configured : undefined;\n // Explicit --defaults / --no-defaults also answer the Locadex gate.\n if (options.defaults !== undefined) session.defaults = options.defaults;\n const gateFramework = options.framework ?? configured ?? detected.name;\n if (gateFramework === 'mintlify' || gateFramework === 'next-app') {\n const useLocadex = await session.answer('--locadex', {\n explicit: options.locadex,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n gateFramework === 'mintlify'\n ? `Mintlify project detected. Would you like to connect to GitHub so that the Locadex AI Agent can translate your project automatically?`\n : `Next.js App Router detected. Would you like to connect to GitHub so that the Locadex AI Agent can set up your project automatically?`,\n defaultValue: false,\n }),\n });\n if (useLocadex) {\n session.assertResolved();\n const url = await setupLocadex(\n await generateSettings({ config: options.config }),\n { openBrowser: session.interactive }\n );\n session.emit({ type: 'handoff', url, reason: 'locadex' });\n logger.endCommand(\n 'Once installed, Locadex will open a PR to your repository. See the docs for more information: https://generaltranslation.com/docs/locadex'\n );\n return { outcome: 'needs_human_action', url };\n }\n } else if (options.locadex) {\n session.reject(\n '--locadex applies only to Mintlify and Next.js App Router projects'\n );\n }\n\n const shownFramework = reactDetected && {\n ...reactDetected,\n name: options.framework ?? configuredReact ?? reactDetected.name,\n };\n // Without --defaults, a noninteractive run uses no defaults.\n session.defaults =\n (await session.answer('--defaults', {\n explicit: options.defaults,\n fallback: false,\n ask: () =>\n promptConfirm({\n message: `Would you like to use the recommended General Translation defaults? ${chalk.dim(`(${describeDefaults(shownFramework)})`)}`,\n defaultValue: true,\n }),\n })) === true;\n\n const resolvedSetup = reactDetected\n ? await resolveReactSetup(\n session,\n options,\n reactDetected,\n configuredReact\n )\n : undefined;\n // A skipped setup only names the framework; the app is left unchanged.\n const reactSetup =\n resolvedSetup && !('skipped' in resolvedSetup)\n ? resolvedSetup\n : undefined;\n // flag > gt.config.json > detection, used for every later step.\n const framework =\n resolvedSetup?.framework ??\n options.framework ??\n configured ??\n detected.name;\n const nextSteps = await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n saveFramework: Boolean(resolvedSetup || options.framework),\n reactSetup,\n skippedReactSetup: Boolean(resolvedSetup && !reactSetup),\n keepAppSource: !reactSetup,\n });\n\n if (nextSteps) {\n logger.endCommand(formatInitNextSteps(nextSteps));\n return { outcome: 'success', nextSteps };\n }\n logger.endCommand(\n 'Done! Check out our docs for more information on how to use General Translation: https://generaltranslation.com/docs'\n );\n return { outcome: 'success' };\n });\n }\n\n protected setupConfigureCommand(): void {\n attachConfigureFlags(\n this.program\n .command('configure')\n .description(\n 'Configure your project for General Translation. This will create a gt.config.json file in your codebase. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: ConfigureOptions) =>\n this.handleConfigureCommand(options)\n );\n }\n\n protected async handleConfigureCommand(\n options: ConfigureOptions,\n command: string = 'configure'\n ): Promise<void> {\n await runOnboarding(command, options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Configuring project...');\n\n logger.info(\n 'Welcome! This tool will help you configure your gt.config.json file. See the docs: https://generaltranslation.com/docs/cli/reference/config for more information.'\n );\n\n // Configure only offers the defaults when asked with --defaults.\n session.defaults = options.defaults ?? false;\n const detected = await detectFramework();\n const configFilepath = setupConfigPath(options);\n // Detection only picks env names here; it is not saved. React Native\n // keeps the generic React env names configure has always written.\n const framework =\n getConfiguredFramework(readSetupConfig(configFilepath)) ??\n (detected.type === 'react-native' ? 'react' : detected.name);\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n });\n\n logger.endCommand(\n 'Done! Make sure you have an API key and project ID to use General Translation. Get them on the dashboard: https://generaltranslation.com/dashboard'\n );\n return { outcome: 'success' };\n });\n }\n\n protected async handleUploadCommand(\n settings: Settings & UploadOptions\n ): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n // Process all file types at once with a single call\n await upload(settings);\n }\n\n /** Describes installed runtimes without changing historical package lookup. */\n protected getInlineRuntimeSetup(\n packageJson: Record<string, unknown>,\n ranReactSetup: boolean = false\n ): InlineRuntimeSetup {\n return {\n hasOtherInlineRuntime: INLINE_LIBRARIES.some(\n (lib) =>\n lib !== Libraries.GT_VUE && isPackageInstalled(lib, packageJson)\n ),\n hasVueRuntime: manifestDirectlyDeclaresGTVue(packageJson),\n ranReactSetup,\n };\n }\n\n /** Returns whether any inline runtime is installed for setup. */\n protected isInlineRuntimeInstalled(\n packageJson: Record<string, unknown>\n ): boolean {\n const { hasOtherInlineRuntime, hasVueRuntime } =\n this.getInlineRuntimeSetup(packageJson);\n return hasOtherInlineRuntime || hasVueRuntime;\n }\n\n /** Returns whether every installed runtime can consume CDN translations. */\n protected supportsCDNStorage(runtimeSetup: InlineRuntimeSetup): boolean {\n return !runtimeSetup.hasVueRuntime;\n }\n\n /** Returns whether setup should generate a local runtime loader. */\n protected shouldGenerateLocalTranslationLoader(\n buildToolOwnsLoader: boolean,\n runtimeSetup: InlineRuntimeSetup\n ): boolean {\n if (buildToolOwnsLoader) return false;\n if (!runtimeSetup.hasVueRuntime) return true;\n return runtimeSetup.hasOtherInlineRuntime || runtimeSetup.ranReactSetup;\n }\n\n /** Returns framework guidance after selecting local translation storage. */\n protected getLocalTranslationGuidance({\n generatedLoader,\n runtimeSetup,\n translationsDir,\n }: LocalTranslationGuidanceOptions): string | undefined {\n const guidance: string[] = [];\n if (generatedLoader) {\n guidance.push(`Created ${chalk.cyan('loadTranslations.js')} file for local translations.\nMake sure to add this function to your app configuration.\nSee https://generaltranslation.com/en/docs/next/guides/local-tx`);\n }\n if (runtimeSetup.hasVueRuntime) {\n guidance.push(`GT will write local translation files to ${translationsDir}.\nConfigure createGT({ loadTranslations }) to load files from that directory.\nSee https://www.npmjs.com/package/gt-vue`);\n }\n return guidance.length > 0 ? guidance.join('\\n') : undefined;\n }\n\n /**\n * Resolves every configuration answer and validates the resulting config,\n * checks the project and signs in before the first change, then applies\n * the React setup, gt.config.json, installs and development credentials.\n */\n protected async handleInitCommand(\n session: OnboardingSession,\n options: ConfigureOptions,\n setup: {\n /** Chosen once by the entry point from the detected framework. */\n configFilepath: string;\n /** Resolved framework; drives storage, env names and build-tool setup. */\n framework?: SupportedFrameworks;\n /** Write the framework even when no build-tool setup saves it. */\n saveFramework?: boolean;\n reactSetup?: ReactSetupPlan;\n /** The app still needs a GT runtime the wizard could not set up. */\n skippedReactSetup?: boolean;\n /** Init without the React setup never changes application source. */\n keepAppSource?: boolean;\n }\n ): Promise<string[] | undefined> {\n const { configFilepath, reactSetup } = setup;\n const buildTool = getBuildToolSetup(setup.framework);\n const cwd = process.cwd();\n const existingConfig = readSetupConfig(configFilepath);\n const desiredLocales = await getDesiredLocales(\n session,\n existingConfig,\n options\n );\n const { defaultLocale } = desiredLocales;\n // Next.js i18n routing requires its default locale in locales, and the\n // Pages Router quickstart passes the gt.config.json locales to it.\n const locales =\n setup.framework === 'next-pages' &&\n defaultLocale &&\n desiredLocales.locales &&\n !desiredLocales.locales.includes(defaultLocale)\n ? [defaultLocale, ...desiredLocales.locales]\n : desiredLocales.locales;\n\n const packageJson =\n reactSetup?.packageJson ?? (await searchForPackageJson());\n const runtimeSetup: InlineRuntimeSetup = packageJson\n ? this.getInlineRuntimeSetup(\n packageJson,\n Boolean(reactSetup || setup.skippedReactSetup)\n )\n : {\n hasOtherInlineRuntime: false,\n hasVueRuntime: false,\n ranReactSetup: false,\n };\n const isUsingGT =\n runtimeSetup.ranReactSetup ||\n runtimeSetup.hasOtherInlineRuntime ||\n runtimeSetup.hasVueRuntime;\n const supportsCDN = this.supportsCDNStorage(runtimeSetup);\n const existingFiles = asRecord(existingConfig.files) ?? {};\n const existingGtOutput = asRecord(existingFiles.gt)?.output;\n const configuredOutput =\n typeof existingGtOutput === 'string' ? existingGtOutput : undefined;\n const configuredStorage = configuredOutput\n ? 'local'\n : existingConfig.publish === true\n ? 'cdn'\n : undefined;\n\n if (isUsingGT && !supportsCDN && options.storage === 'cdn') {\n session.reject(\n 'gt-vue cannot load translations from the CDN; use --storage local'\n );\n }\n // Where GT translations are stored\n const storage = !isUsingGT\n ? undefined\n : !supportsCDN\n ? 'local'\n : await session.answer<'local' | 'cdn'>('--storage', {\n explicit: options.storage,\n configured: configuredStorage,\n recommended: 'local',\n ask: () =>\n promptSelect<'local' | 'cdn'>({\n message: `Would you like to save translation files locally or use the General Translation CDN to store them?`,\n options: [\n { value: 'local', label: 'Save locally' },\n { value: 'cdn', label: 'Use CDN' },\n ],\n defaultValue: 'local',\n }),\n });\n\n const defaultTranslationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n const outputMatch = configuredOutput?.match(\n /^(?:(.+)[\\\\/])?\\[locale\\]\\.json$/\n );\n const configuredTranslationsDir = outputMatch\n ? (outputMatch[1] ?? '.')\n : undefined;\n const translationsDir =\n storage === 'local'\n ? await session.answer('--translations-dir', {\n explicit: options.translationsDir?.trim() || undefined,\n configured: configuredTranslationsDir,\n recommended: defaultTranslationsDir,\n ask: async () =>\n (\n await promptText({\n message:\n 'What is the path to the directory where you would like to store your translation files?',\n defaultValue: defaultTranslationsDir,\n })\n ).trim() || defaultTranslationsDir,\n })\n : undefined;\n\n const filePatterns = parseFilePatterns(session, options.filePatterns);\n const selectedFormats = options.fileFormats?.filter(\n (format): format is SetupFileFormat => format !== 'none'\n );\n if (\n options.fileFormats?.includes('none') &&\n (selectedFormats?.length ?? 0) > 0\n ) {\n session.reject('--file-formats none cannot be combined with formats');\n }\n const configuredFormats = SETUP_FILE_FORMATS.filter(\n (format) => format in existingFiles\n );\n // Formats setup does not offer stay as configured and count as files.\n const otherFormats = SUPPORTED_FILE_EXTENSIONS.filter(\n (format) =>\n format in existingFiles &&\n !(SETUP_FILE_FORMATS as readonly string[]).includes(format)\n );\n const hasOtherFormats = otherFormats.length > 0;\n if (options.fileFormats && hasOtherFormats) {\n const kept = otherFormats.map((format) => `files.${format}`).join(', ');\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `${kept} stays in ${configFilepath}`,\n why: '--file-formats only changes the formats setup offers',\n fix: `Remove ${kept} from ${configFilepath} to stop translating those files`,\n })\n );\n }\n const fileFormats = await session.answer<SetupFileFormat[]>(\n '--file-formats',\n {\n explicit:\n selectedFormats ??\n (filePatterns.size > 0 ? [...filePatterns.keys()] : undefined),\n configured:\n configuredFormats.length > 0 || hasOtherFormats\n ? configuredFormats\n : undefined,\n // GT projects need no other files; others must choose a format.\n recommended: isUsingGT ? [] : undefined,\n ask: () =>\n promptMultiSelect({\n message: !isUsingGT\n ? 'What is the format of your language resource files? Select as many as applicable.\\nAdditionally, you can translate any other files you have in your project.'\n : `Do you have any additional files in this project to translate? For example, Markdown files for docs. ${chalk.dim(\n '(To continue without selecting press Enter)'\n )}`,\n options: SETUP_FILE_FORMATS.map((format) => ({\n value: format,\n label: FILE_EXT_TO_EXT_LABEL[format],\n })),\n required: !isUsingGT,\n }),\n }\n );\n if (\n fileFormats &&\n fileFormats.length === 0 &&\n !isUsingGT &&\n !hasOtherFormats\n ) {\n session.reject(\n 'No GT runtime is installed, so select at least one file format to translate'\n );\n }\n for (const format of filePatterns.keys()) {\n if (fileFormats && !fileFormats.includes(format)) {\n session.reject(\n `--file-patterns ${format}= needs ${format} in --file-formats`\n );\n }\n }\n\n const files: FilesOptions = {};\n for (const fileExtension of fileFormats ?? []) {\n const existingFormat = asRecord(existingFiles[fileExtension]);\n const configuredInclude = Array.isArray(existingFormat?.include)\n ? (existingFormat.include as string[])\n : undefined;\n const include = await session.answer(\n `--file-patterns ${fileExtension}=<glob>`,\n {\n explicit: filePatterns.get(fileExtension),\n configured: configuredInclude,\n recommended: [`./**/[locale]/*.${fileExtension}`],\n ask: async () =>\n parseGlobPatterns(\n await promptGlobPatterns({\n label: FILE_EXT_TO_EXT_LABEL[fileExtension],\n message: `${chalk.cyan(FILE_EXT_TO_EXT_LABEL[fileExtension])}: Enter a space-separated list of glob patterns matching the location of the ${FILE_EXT_TO_EXT_LABEL[fileExtension]} files you would like to translate.\\nMake sure to include [locale] in the patterns.\\nSee https://generaltranslation.com/docs/cli/reference/config#include for more information.`,\n defaultValue: `./**/[locale]/*.${fileExtension}`,\n validate: (value) =>\n parseGlobPatterns(value)\n .map(validateSetupPattern)\n .find((problem) => problem !== true) ?? true,\n })\n ),\n }\n );\n // Configured patterns stay untouched; new ones keep other entry options.\n if (include && include !== configuredInclude) {\n files[fileExtension] = { ...existingFormat, include };\n }\n }\n if (translationsDir && translationsDir !== configuredTranslationsDir) {\n files.gt = { output: path.join(translationsDir, `[locale].json`) };\n }\n\n const envFramework =\n setup.framework ?? getConfiguredFramework(existingConfig);\n // The effective project: an explicit ID replaces a configured one. The\n // framework's runtime project outranks a stale generic GT_PROJECT_ID.\n const projectId =\n options.projectId ||\n (typeof existingConfig.projectId === 'string'\n ? existingConfig.projectId\n : undefined) ||\n process.env[getDevelopmentEnvNames(envFramework).projectId];\n const configUpdate: SetupConfigUpdate = {\n defaultLocale,\n locales,\n src: options.src,\n files: Object.keys(files).length > 0 ? files : undefined,\n framework:\n (setup.saveFramework && setup.framework) || buildTool?.framework,\n publish: storage === 'cdn',\n // Selecting local storage drops stale CDN intent; a config that\n // already combines local files with publishing keeps it.\n clearPublish:\n storage === 'local' &&\n (options.storage === 'local' ||\n configuredStorage !== 'local' ||\n !supportsCDN),\n // An explicit switch to the CDN stops later runs inferring local files.\n clearGtOutput: storage === 'cdn' && configuredOutput !== undefined,\n // An explicit format list replaces the configured selection.\n removeFiles: selectedFormats\n ? configuredFormats.filter(\n (format) => !selectedFormats.includes(format)\n )\n : undefined,\n };\n session.assertResolved();\n\n // Validate what will be written, and use it for every later step.\n const { projectId: _writtenProjectId, ...effectiveConfig } =\n mergeSetupConfig(existingConfig, configUpdate);\n const settings = await generateSettings(\n { config: configFilepath, ...(projectId && { projectId }) },\n cwd,\n { resolvedConfig: effectiveConfig }\n );\n // Runtime credentials only count for the project this setup uses; the\n // framework's project variable is the one paired with its dev key.\n const runtimeProjectId =\n process.env[getDevelopmentEnvNames(envFramework).projectId] ??\n resolveProjectId();\n const runtimeProjectMatches =\n runtimeProjectId === undefined || runtimeProjectId === settings.projectId;\n const credentialsSet =\n runtimeProjectMatches && areCredentialsSet(settings, envFramework);\n const credentialsOption =\n (storage === 'local' && buildTool?.devCredentialsOption) ||\n '--dev-credentials';\n // Creating credentials talks to GT as the signed-in user unless an API\n // key is set. A development key in .env.local never stands in. An\n // obsolete stored login counts as signed out, so signing in replaces it.\n const canAuthenticate = async () =>\n Boolean(settings.apiKey) ||\n (await hasLogin({ baseUrl: settings.baseUrl }).catch((error) => {\n if (\n error instanceof UserAuthError &&\n error.code === 'obsolete_credentials'\n )\n return false;\n throw error;\n }));\n const provision =\n !credentialsSet &&\n (credentialsOption === '--live-translations'\n ? await session.answer('--live-translations', {\n explicit: options.liveTranslations ?? options.devCredentials,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n 'Would you like to set up live development translations? This requires signing in or an API key.',\n defaultValue: false,\n }),\n })\n : await session.answer('--dev-credentials or --no-dev-credentials', {\n explicit: options.devCredentials,\n // Creating a key is never a default, so --defaults leaves this open.\n // The prompt names the sign-in so its Yes default is informed.\n ask: async () =>\n promptConfirm({\n message: (await canAuthenticate())\n ? 'Would you like to set up a project ID and hot-reload key in .env.local?'\n : 'Would you like to sign in to General Translation and set up a project ID and hot-reload key in .env.local?',\n defaultValue: true,\n }),\n })) === true;\n if (!runtimeProjectMatches && !provision) {\n session.reject(\n `The runtime credentials in the environment belong to project ${runtimeProjectId}, not ${settings.projectId}; pass --dev-credentials to replace them in .env.local`\n );\n }\n // An explicit ID is saved to gt.config.json when it replaces a\n // configured one or no new credentials will record it in .env.local.\n if (options.projectId && (existingConfig.projectId || !provision)) {\n configUpdate.projectId = options.projectId;\n }\n if (provision) {\n checkDevelopmentProjectInputs(\n session,\n settings,\n options,\n options.projectId\n ? '--project-id'\n : // An empty configured ID falls through to the environment.\n typeof existingConfig.projectId === 'string' &&\n existingConfig.projectId\n ? configFilepath\n : 'the environment'\n );\n await withCredentialsError(() =>\n inspectCredentialsEnvFile(cwd, { framework: envFramework })\n );\n }\n\n if (reactSetup && buildTool) await buildTool.preflight(cwd);\n const installGT =\n packageJson !== null &&\n !isPackageInstalled('gt', packageJson, true, true) &&\n !buildTool?.skipsGTInstall(isUsingGT);\n const packageManager =\n reactSetup?.install || installGT\n ? await resolvePackageManager(session, options.packageManager)\n : undefined;\n\n session.assertResolved();\n\n if (provision && !(await canAuthenticate())) {\n await signInForSetup(session, settings.baseUrl);\n }\n const project = provision\n ? await withCredentialsError(() =>\n resolveDevelopmentProject(session, settings, options, cwd)\n )\n : undefined;\n session.assertResolved();\n\n // ----- Changes start here ----- //\n const resolvedLocales = locales as string[];\n\n if (reactSetup) {\n logger.info(`${chalk.yellow('[EXPERIMENTAL]')} Configuring project...`);\n if (reactSetup.install && packageManager) {\n await installWithProgress(\n session,\n reactSetup.install,\n packageManager,\n false\n );\n }\n await executeReactSetup(session, reactSetup, options);\n logger.step('Setting up project config...');\n }\n\n const reportManualAction = ({ whatHappened, fix }: ManualAction) => {\n session.humanActions.push(fix);\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened,\n fix,\n })\n );\n };\n const reportSetupResult = ({ steps, manualActions }: SetupResult) => {\n for (const step of steps) session.step(step);\n manualActions.forEach(reportManualAction);\n };\n const translationFilesError = (error: unknown) =>\n new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not create the translation files in ${translationsDir}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Choose another --translations-dir or fix the path, then rerun the command',\n })\n );\n const buildToolContext = {\n appDirectory: cwd,\n configFilepath,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n previousTranslationsDir: configuredTranslationsDir,\n };\n\n if (storage === 'local' && translationsDir) {\n if (buildTool && !reactSetup) {\n reportSetupResult(\n await buildTool\n .syncLoader({\n ...buildToolContext,\n translationsDir,\n keepAppSource: setup.keepAppSource,\n })\n .catch((error: unknown) => {\n throw translationFilesError(error);\n })\n );\n }\n const generatedLoader = this.shouldGenerateLocalTranslationLoader(\n buildTool?.ownsLoader ?? false,\n runtimeSetup\n );\n const loader = generatedLoader\n ? await createLoadTranslationsFile({\n appDirectory: cwd,\n translationsDir,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n previousTranslationsDir: configuredTranslationsDir,\n }).catch((error: unknown) => {\n throw translationFilesError(error);\n })\n : undefined;\n if (loader === 'created' || loader === 'updated') {\n session.step(`${loader} loadTranslations.js`);\n }\n // A loader left unchanged may not read the newly chosen directory.\n if (\n loader === 'custom' &&\n translationsDir !== configuredTranslationsDir\n ) {\n const loaderFile = path.relative(\n cwd,\n findLoadTranslationsFiles(cwd)[0] ?? 'loadTranslations.js'\n );\n reportManualAction({\n whatHappened: `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`,\n fix: `Update your custom ${loaderFile} to load translations from ${translationsDir}`,\n });\n }\n const guidance = this.getLocalTranslationGuidance({\n generatedLoader: generatedLoader && loader !== 'custom',\n runtimeSetup,\n translationsDir,\n });\n if (guidance) logger.message(guidance);\n } else if (\n storage === 'cdn' &&\n buildTool &&\n !reactSetup &&\n configuredTranslationsDir !== undefined\n ) {\n // Only the application setup rewrites the initializer; a loader passed\n // to it takes precedence over CDN loading.\n const action = await buildTool.getCDNStorageAction?.(buildToolContext);\n if (action !== null) {\n reportManualAction(\n action ?? {\n whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,\n fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`,\n }\n );\n }\n } else if (\n storage === 'cdn' &&\n !buildTool &&\n configuredTranslationsDir !== undefined\n ) {\n // gt-next uses a loadTranslations file whenever one exists, and a\n // loader passed to GTProvider takes precedence over the CDN. Name every\n // one: deleting only the first makes gt-next fall back to the next.\n const loaders = findLoadTranslationsFiles(cwd).map((loader) =>\n path.relative(cwd, loader)\n );\n if (loaders.length > 0) {\n const loaderFiles = loaders.join(', ');\n const [them, loads] =\n loaders.length === 1 ? ['it', 'loads'] : ['them', 'load'];\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${loaderFiles} still ${loads} them from ${configuredTranslationsDir}`,\n fix: `Delete ${loaderFiles}, and remove ${them} from your GT setup if you pass ${them} there, so translations load from the CDN`,\n });\n }\n }\n\n const configChange = await applySetupConfig(configFilepath, configUpdate);\n if (configChange !== 'unchanged') {\n session.step(`${configChange} ${configFilepath}`);\n }\n\n logger.success(\n `Edit ${chalk.cyan(\n configFilepath\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n if (reactSetup && buildTool) {\n reportSetupResult(await buildTool.apply(buildToolContext));\n }\n\n if (installGT && packageManager) {\n await installWithProgress(session, 'gt', packageManager, true);\n }\n\n if (project) {\n await withCredentialsError(() =>\n provisionDevelopmentCredentials(\n session,\n project,\n settings,\n envFramework,\n cwd\n )\n );\n logger.message(productionRuntimeKeyGuidance(settings.dashboardUrl));\n }\n\n if (!reactSetup) return undefined;\n // The React setup configures the app entry but never marks content for\n // translation, so what is left is reported as next steps.\n const devPackageManager =\n packageManager ??\n (await getPackageManager(cwd, options.packageManager, true).catch(\n () => undefined\n ));\n const scripts = asRecord(reactSetup.packageJson.scripts);\n return getInitNextSteps({\n framework: reactSetup.framework,\n configuredAppEntry:\n reactSetup.framework === 'next-app' || buildTool !== undefined,\n docsUrl: getSetupDocsUrl(reactSetup.framework),\n locales: resolvedLocales,\n configFilepath,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n devCommand:\n typeof scripts?.dev === 'string'\n ? `${devPackageManager?.runScriptCommand ?? 'npm run'} dev`\n : undefined,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAM,oCAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,SAAS,0BACP,cACA,OACQ;AACR,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV;EACA,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,uBAAuB,wBAAwB;CACnD,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAM,2BAA2B,IAAI,IACnC,OAAO,OAAO,wBAAwB,CACvC;AAED,SAAS,0BACP,YACuC;AACvC,QAAO,yBAAyB,IAAI,WAAW;;AAGjD,SAAS,gBAAgB,OAAuB;CAC9C,MAAM,OAAO,MAAM,MAAM;AACzB,KAAI,CAAC,KAAM,OAAM,IAAI,qBAAqB,qBAAqB;AAC/D,QAAO;;;AAIT,eAAe,qBAAwB,KAAmC;AACxE,KAAI;AACF,SAAO,MAAM,KAAK;UACX,OAAO;AACd,MAAI,iBAAiB,gBAAiB,OAAM;AAC5C,QAAM,IAAI,MACR,iBAAiB,gBACb,MAAM,UACN,0BACE,gDACA,MACD,CACN;;;AA8BL,IAAa,UAAb,MAAqB;CACnB;CACA;CACA;CAEA,YACE,SACA,SACA,mBACA;AACA,OAAK,UAAU;AACf,OAAK,UAAU;AACf,OAAK,oBAAoB,qBAAqB,EAAE;AAEhD,OAAK,QAAQ,OACX,wBACA,yDACD;AACD,OAAK,QAAQ,OACX,uCACA,sDACD;AACD,OAAK,QAAQ,OACX,eACA,oEACD;AAOD,OAAK,QAAQ,KAAK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,MAAI,iBAAiB,YACnB,SAAQ,KAAK,GAAG,aAAa,GAAG,iBAAiB;AAGnD,SAAO,QACL,QAAQ,MAAM,KACZ,eACD,CAAC,sGACH;AAED,MAAI,cAAc,UAChB,mBAAkB,MAAM,UAAU,MAAM,iBAAiB,CAAC;AAG5D,MAAI,aAAa,eACf,OAAM,oBAAoB,SAAS,MAAM,gBAAgB,KAAK;AAGhE,MAAI,SAAS;AACX,SAAM,2BACJ,gCACE,SACA,SACA,UACA,cACA,IACD,CACF;AACD,UAAO,QAAQ,6BAA6B,SAAS,aAAa,CAAC;;AAGrE,MAAI,CAAC,WAAY,QAAO,KAAA;EAGxB,MAAM,oBACJ,kBACC,MAAM,kBAAkB,KAAK,QAAQ,gBAAgB,KAAK,CAAC,YACpD,KAAA,EACP;EACH,MAAM,UAAU,SAAS,WAAW,YAAY,QAAQ;AACxD,SAAO,iBAAiB;GACtB,WAAW,WAAW;GACtB,oBACE,WAAW,cAAc,cAAc,cAAc,KAAA;GACvD,SAAS,gBAAgB,WAAW,UAAU;GAC9C,SAAS;GACT;GACA,iBAAiB,YAAY,UAAU,kBAAkB,KAAA;GACzD,YACE,OAAO,SAAS,QAAQ,WACpB,GAAG,mBAAmB,oBAAoB,UAAU,QACpD,KAAA;GACP,CAAC"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../src/cli/base.ts"],"sourcesContent":["import { Argument, Command, InvalidArgumentError, Option } from 'commander';\nimport {\n OrgApiKeyPermission,\n ProjectApiKeyPermission,\n} from 'generaltranslation/api';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport {\n applySetupConfig,\n mergeSetupConfig,\n type SetupConfigUpdate,\n} from '../fs/config/setupConfig.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport {\n displayHeader,\n promptText,\n logErrorAndExit,\n exitSync,\n promptConfirm,\n promptMultiSelect,\n promptSelect,\n promptGlobPatterns,\n} from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { lottieTranslateError } from '../console/index.js';\nimport { parseGlobPatterns } from '../console/promptParsing.js';\nimport path from 'node:path';\nimport {\n FilesOptions,\n Settings,\n SupportedFrameworks,\n SupportedLibraries,\n TranslateFlags,\n SharedFlags,\n} from '../types/index.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport chalk from 'chalk';\nimport {\n FILE_EXT_TO_EXT_LABEL,\n SETUP_FILE_FORMATS,\n SUPPORTED_FILE_EXTENSIONS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n executeReactSetup,\n resolveReactSetup,\n type ReactSetupPlan,\n} from '../setup/wizard.js';\nimport { formatInitNextSteps, getInitNextSteps } from '../setup/nextSteps.js';\nimport { getPackageManager } from '../utils/packageManager.js';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { getDesiredLocales } from '../setup/userInput.js';\nimport {\n areCredentialsSet,\n getDevelopmentEnvNames,\n inspectCredentialsEnvFile,\n} from '../utils/credentials.js';\nimport {\n checkDevelopmentProjectInputs,\n productionRuntimeKeyGuidance,\n provisionDevelopmentCredentials,\n resolveDevelopmentProject,\n signInForSetup,\n} from '../setup/developmentCredentials.js';\nimport {\n exitIfUnsupportedSetupTarget,\n reactNativeSetupError,\n} from '../setup/setupTarget.js';\nimport {\n asRecord,\n attachConfigureFlags,\n attachInitFlags,\n describeDefaults,\n displaySetupHeader,\n getConfiguredFramework,\n INIT_SOURCE_HELP,\n installWithProgress,\n OnboardingError,\n parseFilePatterns,\n readSetupConfig,\n reportJsonExitsBeforeOnboarding,\n resolvePackageManager,\n runOnboarding,\n setupConfigPath,\n validateSetupPattern,\n type ConfigureOptions,\n type InitOptions,\n type OnboardingSession,\n} from '../setup/onboarding.js';\nimport { upload } from './commands/upload.js';\nimport { attachSharedFlags, attachTranslateFlags } from './flags.js';\nimport { handleStage } from './commands/stage.js';\nimport { handleSetupProject } from './commands/setupProject.js';\nimport { handleDownload } from './commands/download.js';\nimport {\n handleTranslate,\n postProcessTranslations,\n} from './commands/translate.js';\nimport {\n getNeedsPostprocessing,\n clearDownloaded,\n} from '../state/recentDownloads.js';\nimport { clearWarnings } from '../state/translateWarnings.js';\nimport { displayTranslateSummary } from '../console/displayTranslateSummary.js';\nimport updateConfig from '../fs/config/updateConfig.js';\nimport {\n createLoadTranslationsFile,\n findLoadTranslationsFiles,\n} from '../fs/createLoadTranslationsFile.js';\nimport {\n saveLocalEdits,\n saveLocalEditsMessage,\n} from '../api/saveLocalEdits.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './commands/utils/validation.js';\nimport processSharedStaticAssets, {\n mirrorAssetsToLocales,\n} from '../utils/sharedStaticAssets.js';\nimport { setupLocadex } from '../locadex/setupFlow.js';\nimport { detectFramework } from '../setup/detectFramework.js';\nimport { INLINE_LIBRARIES, Libraries } from '../types/libraries.js';\nimport { handleEnqueue } from './commands/enqueue.js';\nimport { splitMintlifyLanguageRefs } from '../utils/splitMintlifyLanguageRefs.js';\nimport { localizeMintlifyRedirects } from '../formats/files/postprocess/localizeMintlifyRedirects.js';\nimport {\n clearOrphanedFileNames,\n getOrphanedFileNames,\n} from '../state/orphanedFileNames.js';\nimport { runMergeDriver, type MergeDriverName } from '../git/mergeDrivers.js';\nimport { setupGitMergeDrivers } from '../git/setupMergeDrivers.js';\nimport { warnReactPackageCompatibility } from '../utils/reactPackageCompatibility.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { hasLogin, logout, whoAmI } from '../auth/oauth.js';\nimport { createUserAuthError, UserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { resolveConfig } from '../config/resolveConfig.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport {\n getBuildToolSetup,\n getSetupDocsUrl,\n type ManualAction,\n type SetupResult,\n} from '../setup/buildTools/index.js';\nimport { manifestDirectlyDeclaresGTVue } from '@generaltranslation/vue-extractor/integration';\nimport { api, configureApiClient } from '../utils/api.js';\nimport { handleApiCommand, type ApiCommandOptions } from './commands/api.js';\n\nconst ID_COMPATIBILITY_WARNING_COMMANDS = new Set([\n 'download',\n 'enqueue',\n 'generate',\n 'setup',\n 'stage',\n 'translate',\n 'validate',\n]);\nfunction createProjectCommandError(\n whatHappened: string,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened,\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst emptyApiKeyNameError = createDiagnosticMessage({\n whatHappened: 'The key name cannot be empty',\n fix: 'Pass a non-empty value with --name',\n});\n\nconst projectApiKeyPermissions = new Set<string>(\n Object.values(ProjectApiKeyPermission)\n);\n\nfunction isProjectApiKeyPermission(\n permission: OrgApiKeyPermission\n): permission is ProjectApiKeyPermission {\n return projectApiKeyPermissions.has(permission);\n}\n\nfunction parseApiKeyName(value: string): string {\n const name = value.trim();\n if (!name) throw new InvalidArgumentError(emptyApiKeyNameError);\n return name;\n}\n\n/** Credential failures keep their own diagnostic or get the setup context. */\nasync function withCredentialsError<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof OnboardingError) throw error;\n throw new Error(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError(\n 'Failed to set up the development credentials',\n error\n )\n );\n }\n}\n\nexport type UploadOptions = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n defaultLocale?: string;\n};\n\nexport type GitSetupOptions = {\n config?: string;\n dryRun?: boolean;\n omitConfigIds?: boolean;\n driverCommand?: string;\n};\n\ntype LocalTranslationGuidanceOptions = {\n generatedLoader: boolean;\n runtimeSetup: InlineRuntimeSetup;\n translationsDir: string;\n};\n\ntype InlineRuntimeSetup = {\n hasOtherInlineRuntime: boolean;\n hasVueRuntime: boolean;\n ranReactSetup: boolean;\n};\n\nexport class BaseCLI {\n protected library: SupportedLibraries;\n protected additionalModules: SupportedLibraries[];\n protected program: Command;\n // Constructor is shared amongst all CLI class types\n public constructor(\n program: Command,\n library: SupportedLibraries,\n additionalModules?: SupportedLibraries[]\n ) {\n this.program = program;\n this.library = library;\n this.additionalModules = additionalModules || [];\n\n this.program.option(\n '--skip-version-check',\n 'Skip the monorepo GT package version consistency check'\n );\n this.program.option(\n '--suppress-id-compatibility-warning',\n 'Suppress the React package ID compatibility warning'\n );\n this.program.option(\n '-q, --quiet',\n 'Suppress informational output; only warnings and errors are shown'\n );\n // Select console routing for this command before anything else logs:\n // root hooks run before subclass hooks (version checks) and the action's\n // settings resolution. `gt api-key create` prints the new secret on\n // stdout, so its diagnostics go to stderr, as do setup commands writing\n // JSON events; every other command gets the historical default back\n // (main() routes startup output to stderr).\n this.program.hook('preAction', (thisCommand, actionCommand) => {\n logger.setConsoleOutput(\n actionCommand.parent?.name() === 'api-key' || actionCommand.opts().json\n ? 'stderr'\n : 'stdout'\n );\n if (\n actionCommand.opts().json &&\n actionCommand.parent === thisCommand &&\n ['init', 'configure'].includes(actionCommand.name())\n ) {\n reportJsonExitsBeforeOnboarding(actionCommand.name());\n }\n });\n // Apply --quiet before any other hook or command action runs so the\n // singleton logger is muted for the rest of the invocation. The flag is a\n // global root option, so commander resolves it in any position and for\n // nested commands (e.g. `gt git setup --quiet`).\n this.program.hook('preAction', () => {\n logger.setQuiet(Boolean(this.program.opts().quiet));\n });\n this.program.hook('preAction', async (thisCommand, actionCommand) => {\n // Nested commands (e.g. `gt git setup`) can share leaf names with\n // translation commands; only direct children of the root qualify\n if (actionCommand.parent !== thisCommand) return;\n if (!ID_COMPATIBILITY_WARNING_COMMANDS.has(actionCommand.name())) return;\n await warnReactPackageCompatibility(\n Boolean(this.program.opts().suppressIdCompatibilityWarning)\n );\n });\n\n this.setupInitCommand();\n this.setupConfigureCommand();\n this.setupUploadCommand();\n this.setupUserAuthCommands();\n this.setupSendDiffsCommand();\n this.setupApiCommand();\n this.setupProjectCommands();\n this.setupApiKeyCommands();\n this.setupGitCommand();\n }\n // Init is never called in a child class\n public init() {\n this.setupSetupProjectCommand();\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n // Execute is called by the main program\n public execute() {\n // If no command is specified, run 'init'\n if (process.argv.length <= 2) {\n process.argv.push('init');\n }\n }\n\n protected setupSetupProjectCommand(): void {\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupStageCommand(): void {\n attachTranslateFlags(\n this.program\n .command('stage')\n .description(\n 'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupEnqueueCommand(): void {\n attachTranslateFlags(\n this.program\n .command('enqueue')\n .description('Enqueues translations for a given set of files')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Enqueuing translations...');\n await this.handleEnqueue(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupDownloadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('download')\n .description('Download translations that were originally staged')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Downloading translations...');\n await this.handleDownload(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachTranslateFlags(\n this.program\n .command('translate')\n .description('Translate your project using General Translation')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Starting translation...');\n await this.handleTranslate(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupSendDiffsCommand(): void {\n attachSharedFlags(\n this.program\n .command('save-local')\n .description(\n 'Save local edits for all configured files by sending diffs (no translation enqueued)'\n )\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .action(async (initOptions: SharedFlags) => {\n displayHeader('Saving local edits...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n const outcome = await saveLocalEdits(settings);\n logger.endCommand(saveLocalEditsMessage(outcome));\n });\n }\n\n protected setupApiCommand(): void {\n attachSharedFlags(\n this.program\n .command('api [endpoint]')\n .description('Make an authenticated request to the GT API')\n .option('-X, --method <method>', 'HTTP method', 'GET')\n .option('--input <file>', 'Request body file, or - for standard input')\n .option(\n '-H, --header <header>',\n 'Request header in \"Key: Value\" format',\n (header, headers: string[] | undefined) => [\n ...(headers ?? []),\n header,\n ]\n )\n .option('-i, --include', 'Include response status and headers')\n .option(\n '--spec',\n 'Print the bundled OpenAPI specification, or only the operations matching [endpoint] (path or operation ID) with references resolved'\n )\n .addOption(\n new Option(\n '--list',\n 'List the method, path, operation ID, and summary of every API operation'\n ).conflicts('spec')\n )\n ).action((endpoint, options: ApiCommandOptions) =>\n handleApiCommand(endpoint, options)\n );\n }\n\n protected setupProjectCommands(): void {\n const projectCommand = this.program\n .command('project')\n .description('Manage General Translation projects');\n\n attachSharedFlags(\n projectCommand\n .command('create')\n .description(\n 'Create a General Translation project using an organization API key'\n )\n .requiredOption('--org-id <orgId>', 'Organization ID')\n .requiredOption('--name <name>', 'Project name')\n .requiredOption('--default-locale <locale>', 'Project default locale')\n .option('--cdn-enabled', 'Enable CDN delivery', false)\n ).action(async (options) => {\n try {\n const settings = await generateSettings(options);\n // Project creation happens before a project ID exists.\n if (!hasValidServiceLocales(settings)) return exitSync(1);\n const { project } = await api.createProject(options.orgId, {\n name: options.name,\n defaultLocale: options.defaultLocale,\n cdnEnabled: options.cdnEnabled,\n });\n logger.info(`Created ${project.name} (${project.id})`);\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError('Failed to create the project', error)\n );\n }\n });\n\n attachSharedFlags(\n projectCommand\n .command('status')\n .description('Check the status of a project setup job')\n .argument('<job-id>', 'Setup job ID')\n ).action(async (jobId, options) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const [status] = await api.checkJobStatus([jobId]);\n logger.info(status?.status ?? 'unknown');\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError(\n 'Failed to check the project setup status',\n error\n )\n );\n }\n });\n }\n\n protected setupApiKeyCommands(): void {\n const apiKeyCommand = this.program\n .command('api-key')\n .description(\n 'Manage API keys for the configured project or an organization'\n );\n\n attachSharedFlags(\n apiKeyCommand\n .command('create')\n .description(\n 'Create a project API key, or an organization API key with --org-id, with the requested permissions and print it once'\n )\n .requiredOption('--name <name>', 'Key name', parseApiKeyName)\n .option(\n '--org-id <orgId>',\n 'Create an organization API key for this organization instead (requires gt login)'\n )\n // Validated before any request; the server grants the requested set\n // all-or-nothing, so omitting permissions would delegate everything.\n .addOption(\n new Option('--permission <permissions...>', 'Permissions to grant')\n .choices(Object.values(OrgApiKeyPermission))\n .makeOptionMandatory()\n )\n ).action(\n async (\n options: SharedFlags & {\n name: string;\n orgId?: string;\n permission: OrgApiKeyPermission[];\n }\n ) => {\n const projectPermissions = options.permission.filter(\n isProjectApiKeyPermission\n );\n const orgOnlyPermissions = options.permission.filter(\n (permission) => !isProjectApiKeyPermission(permission)\n );\n if (!options.orgId && orgOnlyPermissions.length > 0) {\n return logErrorAndExit(\n createDiagnosticMessage({\n whatHappened: `${orgOnlyPermissions.join(', ')} can only be granted to organization API keys`,\n fix: 'Pass --org-id, or remove those permissions',\n })\n );\n }\n try {\n const settings = await generateSettings(options);\n let key: string;\n if (options.orgId) {\n // No API key can create organization keys, so always send the\n // signed-in user's token, even when an API key is configured.\n configureApiClient({\n baseUrl: settings.baseUrl,\n userTokenProvider: settings.userTokenProvider,\n });\n const { apiKey } = await api.createOrgApiKey(options.orgId, {\n name: options.name,\n permissions: options.permission,\n });\n key = apiKey.key;\n } else {\n if (!hasValidCredentials(settings)) return exitSync(1);\n const { apiKey } = await api.createProjectApiKey(\n settings.projectId,\n { name: options.name, permissions: projectPermissions }\n );\n key = apiKey.key;\n }\n // Raw stdout: the secret is shown once and never reaches the log file.\n process.stdout.write(`${key}\\n`);\n } catch (error) {\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError('Failed to create the API key', error)\n );\n }\n }\n );\n }\n\n protected setupGitCommand(): void {\n const gitCommand = this.program\n .command('git')\n .description('Configure Git integrations for General Translation');\n\n gitCommand\n .command('setup')\n .description('Set up GT merge drivers for generated translation files')\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--dry-run', 'Print changes without writing files', false)\n .option(\n '--omit-config-ids',\n 'Persist omitConfigIds and remove generated config IDs'\n )\n .option(\n '--driver-command <command>',\n 'Command Git should use to invoke gt, e.g. \"pnpm exec gt\"'\n )\n .action(async (options: GitSetupOptions) => {\n displayHeader('Setting up GT Git merge drivers...');\n const settings = await generateSettings(options, undefined, {\n requireConfig: true,\n });\n const omitConfigIds = await this.resolveGitSetupOmitConfigIds(\n options,\n settings\n );\n const result = await setupGitMergeDrivers(settings, {\n dryRun: options.dryRun,\n omitConfigIds,\n driverCommand: options.driverCommand,\n });\n\n for (const line of result.addedAttributes) {\n logger.step(\n `${options.dryRun ? 'Would add' : 'Added'} ${chalk.cyan(\n line\n )} to ${chalk.cyan(result.gitattributesPath)}`\n );\n }\n if (result.addedAttributes.length === 0) {\n logger.info(`${chalk.cyan('.gitattributes')} is already configured.`);\n }\n\n for (const args of result.gitConfigCommands) {\n logger.step(\n `${options.dryRun ? 'Would run' : 'Configured'} ${chalk.cyan(\n `git config --local ${args.join(' ')}`\n )}`\n );\n }\n\n if (result.updatedConfig) {\n logger.step(\n `${options.dryRun ? 'Would persist' : 'Persisted'} ${chalk.cyan(\n 'omitConfigIds: true'\n )} in ${chalk.cyan(settings.config)}`\n );\n } else if (options.dryRun && !settings.omitConfigIds) {\n logger.info(\n `Run without ${chalk.cyan('--dry-run')} to be prompted to persist ${chalk.cyan(\n 'omitConfigIds: true'\n )}, or pass ${chalk.cyan('--omit-config-ids')}.`\n );\n }\n\n for (const warning of result.warnings) {\n logger.warn(chalk.yellow(warning));\n }\n\n logger.endCommand(\n options.dryRun\n ? 'Dry run complete.'\n : 'GT Git merge drivers configured.'\n );\n });\n\n gitCommand\n .command('merge-driver', { hidden: true })\n .addArgument(\n new Argument('<driver>', 'Merge driver name').choices([\n 'gt-lock',\n 'gtjson',\n ])\n )\n .argument('<base>', 'Common ancestor file')\n .argument('<ours>', 'Current branch file')\n .argument('<theirs>', 'Incoming branch file')\n .argument('[path]', 'Merged path')\n .action(\n (\n driver: MergeDriverName,\n base: string,\n ours: string,\n theirs: string\n ) => {\n const result = runMergeDriver(driver, base, ours, theirs);\n if (!result.ok) {\n logger.error(result.reason);\n exitSync(1);\n }\n }\n );\n }\n\n protected async resolveGitSetupOmitConfigIds(\n options: GitSetupOptions,\n settings: Settings\n ): Promise<boolean> {\n if (options.omitConfigIds) return true;\n // Already opted in: persist again so stale config IDs still get removed\n if (settings.omitConfigIds) return true;\n if (options.dryRun || !process.stdin.isTTY || !process.stdout.isTTY) {\n return false;\n }\n return promptConfirm({\n message:\n 'Also set omitConfigIds: true to reduce gt.config.json merge conflicts?',\n defaultValue: true,\n });\n }\n\n protected async handleSetupProject(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n await handleSetupProject(initOptions, settings, this.library);\n }\n\n protected async handleStage(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Update settings.stageTranslations to true\n settings.stageTranslations = true;\n await updateConfig(settings.config, {\n stageTranslations: true,\n });\n }\n await handleStage(initOptions, settings, this.library, true);\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleEnqueue(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleEnqueue(initOptions, settings, this.library);\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleDownload(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleDownload(initOptions, settings, this.library);\n await this.finalizeDownloadedTranslations(settings);\n }\n\n protected async handleTranslate(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Lottie translations finish asynchronously server-side (layout\n // refinement runs after the translation job completes), so the immediate\n // translate flow would try to download them before they're ready. Only\n // the stage + download flow supports them.\n if (settings.files?.resolvedPaths.lottie?.length) {\n return logErrorAndExit(lottieTranslateError);\n }\n const results = await handleStage(\n initOptions,\n settings,\n this.library,\n false\n );\n if (results) {\n await handleTranslate(\n initOptions,\n settings,\n results.fileVersionData,\n results.jobData,\n results.branchData,\n results.publishMap,\n results.inlineLibrary\n );\n }\n } else {\n await handleDownload(initOptions, settings, this.library);\n }\n await this.finalizeDownloadedTranslations(settings);\n }\n\n /**\n * Postprocesses the translations downloaded in this run and reports the\n * summary. Shared by translate and download so both write the same output.\n * @param settings - The settings for the command\n */\n protected async finalizeDownloadedTranslations(\n settings: Settings\n ): Promise<void> {\n // Only postprocess files downloaded in this run\n const include = getNeedsPostprocessing();\n if (include.size > 0) {\n await postProcessTranslations(settings, include);\n }\n // Split Mintlify language entries into $ref files to keep docs.json small\n await splitMintlifyLanguageRefs(settings);\n // Localize redirects for pages this run renamed or removed. Runs after the\n // split, which can rewrite $ref files such as redirects.json\n const orphanedFileNames = getOrphanedFileNames();\n if (orphanedFileNames) {\n const added = localizeMintlifyRedirects(settings, orphanedFileNames);\n if (added.length > 0) {\n logger.success(\n `Added ${added.length} localized redirect${added.length === 1 ? '' : 's'}`\n );\n }\n }\n clearOrphanedFileNames();\n // Mirror assets after translations are downloaded and locale dirs are populated\n await mirrorAssetsToLocales(settings);\n clearDownloaded();\n displayTranslateSummary();\n clearWarnings();\n }\n\n protected setupUploadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('upload')\n .description(\n 'Upload source files and translations to the General Translation platform'\n )\n ).action(async (initOptions: UploadOptions) => {\n displayHeader('Starting upload...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const options = { ...initOptions, ...settings };\n\n await this.handleUploadCommand(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupUserAuthCommands(): void {\n this.program\n .command('login')\n .description('Sign in to your General Translation account')\n .option(\n '--no-browser',\n 'Do not open a browser; show a sign-in URL to use on any device instead'\n )\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json'\n )\n .action(async (options: { browser: boolean; config?: string }) => {\n displayHeader('Signing in to General Translation...');\n try {\n // Tokens are bound to one API resource, so log in to the configured one.\n const baseUrl = (\n options.config\n ? loadConfig(withJsonExtension(options.config))\n : resolveConfig(process.cwd())?.config\n )?.baseUrl;\n await loginInteractively(\n typeof baseUrl === 'string' ? baseUrl : undefined,\n options.browser\n );\n logger.endCommand('You are now signed in.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign in failed', error));\n }\n });\n\n this.program\n .command('logout')\n .description('Sign out of your General Translation account')\n .action(async () => {\n try {\n await logout();\n logger.endCommand('Signed out successfully.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign out failed', error));\n }\n });\n\n this.program\n .command('whoami')\n .description('Show the signed-in General Translation account')\n .action(async () => {\n try {\n const user = await whoAmI();\n logger.message(user.email ?? user.name ?? user.sub);\n } catch (error) {\n logErrorAndExit(\n createUserAuthError('Could not load your account', error)\n );\n }\n });\n }\n\n protected setupInitCommand(): void {\n attachInitFlags(\n this.program\n .command('init')\n .description(\n 'Run the setup wizard to configure your project for General Translation. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: InitOptions) => this.handleInitWizard(options));\n }\n\n protected async handleInitWizard(options: InitOptions): Promise<void> {\n await runOnboarding('init', options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Running setup wizard...');\n\n const detected = await detectFramework();\n // Stop before any change rather than set React Native up as web React.\n if (detected.type === 'react-native') {\n throw new OnboardingError(reactNativeSetupError);\n }\n const reactDetected = detected.type === 'react' ? detected : undefined;\n if (options.framework && !reactDetected) {\n session.reject(\n '--framework applies only to projects detected as React applications'\n );\n }\n const configFilepath = setupConfigPath(options);\n const configured = getConfiguredFramework(\n readSetupConfig(configFilepath)\n );\n const configuredReact =\n configured !== 'mintlify' ? configured : undefined;\n // Explicit --defaults / --no-defaults also answer the Locadex gate.\n if (options.defaults !== undefined) session.defaults = options.defaults;\n const gateFramework = options.framework ?? configured ?? detected.name;\n if (gateFramework === 'mintlify' || gateFramework === 'next-app') {\n const useLocadex = await session.answer('--locadex', {\n explicit: options.locadex,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n gateFramework === 'mintlify'\n ? `Mintlify project detected. Would you like to connect to GitHub so that the Locadex AI Agent can translate your project automatically?`\n : `Next.js App Router detected. Would you like to connect to GitHub so that the Locadex AI Agent can set up your project automatically?`,\n defaultValue: false,\n }),\n });\n if (useLocadex) {\n session.assertResolved();\n const url = await setupLocadex(\n await generateSettings({ config: options.config }),\n { openBrowser: session.interactive }\n );\n session.emit({ type: 'handoff', url, reason: 'locadex' });\n logger.endCommand(\n 'Once installed, Locadex will open a PR to your repository. See the docs for more information: https://generaltranslation.com/docs/locadex'\n );\n return { outcome: 'needs_human_action', url };\n }\n } else if (options.locadex) {\n session.reject(\n '--locadex applies only to Mintlify and Next.js App Router projects'\n );\n }\n\n const shownFramework = reactDetected && {\n ...reactDetected,\n name: options.framework ?? configuredReact ?? reactDetected.name,\n };\n // Without --defaults, a noninteractive run uses no defaults.\n session.defaults =\n (await session.answer('--defaults', {\n explicit: options.defaults,\n fallback: false,\n ask: () =>\n promptConfirm({\n message: `Would you like to use the recommended General Translation defaults? ${chalk.dim(`(${describeDefaults(shownFramework)})`)}`,\n defaultValue: true,\n }),\n })) === true;\n\n const resolvedSetup = reactDetected\n ? await resolveReactSetup(\n session,\n options,\n reactDetected,\n configuredReact\n )\n : undefined;\n // A skipped setup only names the framework; the app is left unchanged.\n const reactSetup =\n resolvedSetup && !('skipped' in resolvedSetup)\n ? resolvedSetup\n : undefined;\n // flag > gt.config.json > detection, used for every later step.\n const framework =\n resolvedSetup?.framework ??\n options.framework ??\n configured ??\n detected.name;\n const nextSteps = await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n saveFramework: Boolean(resolvedSetup || options.framework),\n reactSetup,\n skippedReactSetup: Boolean(resolvedSetup && !reactSetup),\n keepAppSource: !reactSetup,\n });\n\n if (nextSteps) {\n logger.endCommand(formatInitNextSteps(nextSteps));\n return { outcome: 'success', nextSteps };\n }\n logger.endCommand(\n 'Done! Check out our docs for more information on how to use General Translation: https://generaltranslation.com/docs'\n );\n return { outcome: 'success' };\n });\n }\n\n protected setupConfigureCommand(): void {\n attachConfigureFlags(\n this.program\n .command('configure')\n .description(\n 'Configure your project for General Translation. This will create a gt.config.json file in your codebase. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: ConfigureOptions) =>\n this.handleConfigureCommand(options)\n );\n }\n\n protected async handleConfigureCommand(\n options: ConfigureOptions,\n command: string = 'configure'\n ): Promise<void> {\n await runOnboarding(command, options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Configuring project...');\n\n logger.info(\n 'Welcome! This tool will help you configure your gt.config.json file. See the docs: https://generaltranslation.com/docs/cli/reference/config for more information.'\n );\n\n // Configure only offers the defaults when asked with --defaults.\n session.defaults = options.defaults ?? false;\n const detected = await detectFramework();\n const configFilepath = setupConfigPath(options);\n // Detection only picks env names here; it is not saved. React Native\n // keeps the generic React env names configure has always written.\n const framework =\n getConfiguredFramework(readSetupConfig(configFilepath)) ??\n (detected.type === 'react-native' ? 'react' : detected.name);\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n });\n\n logger.endCommand(\n 'Done! Make sure you have an API key and project ID to use General Translation. Get them on the dashboard: https://generaltranslation.com/dashboard'\n );\n return { outcome: 'success' };\n });\n }\n\n protected async handleUploadCommand(\n settings: Settings & UploadOptions\n ): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n // Process all file types at once with a single call\n await upload(settings);\n }\n\n /** Describes installed runtimes without changing historical package lookup. */\n protected getInlineRuntimeSetup(\n packageJson: Record<string, unknown>,\n ranReactSetup: boolean = false\n ): InlineRuntimeSetup {\n return {\n hasOtherInlineRuntime: INLINE_LIBRARIES.some(\n (lib) =>\n lib !== Libraries.GT_VUE && isPackageInstalled(lib, packageJson)\n ),\n hasVueRuntime: manifestDirectlyDeclaresGTVue(packageJson),\n ranReactSetup,\n };\n }\n\n /** Returns whether any inline runtime is installed for setup. */\n protected isInlineRuntimeInstalled(\n packageJson: Record<string, unknown>\n ): boolean {\n const { hasOtherInlineRuntime, hasVueRuntime } =\n this.getInlineRuntimeSetup(packageJson);\n return hasOtherInlineRuntime || hasVueRuntime;\n }\n\n /** Returns whether every installed runtime can consume CDN translations. */\n protected supportsCDNStorage(runtimeSetup: InlineRuntimeSetup): boolean {\n return !runtimeSetup.hasVueRuntime;\n }\n\n /** Returns whether setup should generate a local runtime loader. */\n protected shouldGenerateLocalTranslationLoader(\n buildToolOwnsLoader: boolean,\n runtimeSetup: InlineRuntimeSetup\n ): boolean {\n if (buildToolOwnsLoader) return false;\n if (!runtimeSetup.hasVueRuntime) return true;\n return runtimeSetup.hasOtherInlineRuntime || runtimeSetup.ranReactSetup;\n }\n\n /** Returns framework guidance after selecting local translation storage. */\n protected getLocalTranslationGuidance({\n generatedLoader,\n runtimeSetup,\n translationsDir,\n }: LocalTranslationGuidanceOptions): string | undefined {\n const guidance: string[] = [];\n if (generatedLoader) {\n guidance.push(`Created ${chalk.cyan('loadTranslations.js')} file for local translations.\nMake sure to add this function to your app configuration.\nSee https://generaltranslation.com/en/docs/next/guides/local-tx`);\n }\n if (runtimeSetup.hasVueRuntime) {\n guidance.push(`GT will write local translation files to ${translationsDir}.\nConfigure createGT({ loadTranslations }) to load files from that directory.\nSee https://www.npmjs.com/package/gt-vue`);\n }\n return guidance.length > 0 ? guidance.join('\\n') : undefined;\n }\n\n /**\n * Resolves every configuration answer and validates the resulting config,\n * checks the project and signs in before the first change, then applies\n * the React setup, gt.config.json, installs and development credentials.\n */\n protected async handleInitCommand(\n session: OnboardingSession,\n options: ConfigureOptions,\n setup: {\n /** Chosen once by the entry point from the detected framework. */\n configFilepath: string;\n /** Resolved framework; drives storage, env names and build-tool setup. */\n framework?: SupportedFrameworks;\n /** Write the framework even when no build-tool setup saves it. */\n saveFramework?: boolean;\n reactSetup?: ReactSetupPlan;\n /** The app still needs a GT runtime the wizard could not set up. */\n skippedReactSetup?: boolean;\n /** Init without the React setup never changes application source. */\n keepAppSource?: boolean;\n }\n ): Promise<string[] | undefined> {\n const { configFilepath, reactSetup } = setup;\n const buildTool = getBuildToolSetup(setup.framework);\n const cwd = process.cwd();\n const existingConfig = readSetupConfig(configFilepath);\n const desiredLocales = await getDesiredLocales(\n session,\n existingConfig,\n options\n );\n const { defaultLocale } = desiredLocales;\n // Next.js i18n routing requires its default locale in locales, and the\n // Pages Router quickstart passes the gt.config.json locales to it.\n const locales =\n setup.framework === 'next-pages' &&\n defaultLocale &&\n desiredLocales.locales &&\n !desiredLocales.locales.includes(defaultLocale)\n ? [defaultLocale, ...desiredLocales.locales]\n : desiredLocales.locales;\n\n const packageJson =\n reactSetup?.packageJson ?? (await searchForPackageJson());\n const runtimeSetup: InlineRuntimeSetup = packageJson\n ? this.getInlineRuntimeSetup(\n packageJson,\n Boolean(reactSetup || setup.skippedReactSetup)\n )\n : {\n hasOtherInlineRuntime: false,\n hasVueRuntime: false,\n ranReactSetup: false,\n };\n const isUsingGT =\n runtimeSetup.ranReactSetup ||\n runtimeSetup.hasOtherInlineRuntime ||\n runtimeSetup.hasVueRuntime;\n const supportsCDN = this.supportsCDNStorage(runtimeSetup);\n const existingFiles = asRecord(existingConfig.files) ?? {};\n const existingGtOutput = asRecord(existingFiles.gt)?.output;\n const configuredOutput =\n typeof existingGtOutput === 'string' ? existingGtOutput : undefined;\n const configuredStorage = configuredOutput\n ? 'local'\n : existingConfig.publish === true\n ? 'cdn'\n : undefined;\n\n if (isUsingGT && !supportsCDN && options.storage === 'cdn') {\n session.reject(\n 'gt-vue cannot load translations from the CDN; use --storage local'\n );\n }\n // Where GT translations are stored\n const storage = !isUsingGT\n ? undefined\n : !supportsCDN\n ? 'local'\n : await session.answer<'local' | 'cdn'>('--storage', {\n explicit: options.storage,\n configured: configuredStorage,\n recommended: 'local',\n ask: () =>\n promptSelect<'local' | 'cdn'>({\n message: `Would you like to save translation files locally or use the General Translation CDN to store them?`,\n options: [\n { value: 'local', label: 'Save locally' },\n { value: 'cdn', label: 'Use CDN' },\n ],\n defaultValue: 'local',\n }),\n });\n\n const defaultTranslationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n const outputMatch = configuredOutput?.match(\n /^(?:(.+)[\\\\/])?\\[locale\\]\\.json$/\n );\n const configuredTranslationsDir = outputMatch\n ? (outputMatch[1] ?? '.')\n : undefined;\n const translationsDir =\n storage === 'local'\n ? await session.answer('--translations-dir', {\n explicit: options.translationsDir?.trim() || undefined,\n configured: configuredTranslationsDir,\n recommended: defaultTranslationsDir,\n ask: async () =>\n (\n await promptText({\n message:\n 'What is the path to the directory where you would like to store your translation files?',\n defaultValue: defaultTranslationsDir,\n })\n ).trim() || defaultTranslationsDir,\n })\n : undefined;\n\n const filePatterns = parseFilePatterns(session, options.filePatterns);\n const selectedFormats = options.fileFormats?.filter(\n (format): format is SetupFileFormat => format !== 'none'\n );\n if (\n options.fileFormats?.includes('none') &&\n (selectedFormats?.length ?? 0) > 0\n ) {\n session.reject('--file-formats none cannot be combined with formats');\n }\n const configuredFormats = SETUP_FILE_FORMATS.filter(\n (format) => format in existingFiles\n );\n // Formats setup does not offer stay as configured and count as files.\n const otherFormats = SUPPORTED_FILE_EXTENSIONS.filter(\n (format) =>\n format in existingFiles &&\n !(SETUP_FILE_FORMATS as readonly string[]).includes(format)\n );\n const hasOtherFormats = otherFormats.length > 0;\n if (options.fileFormats && hasOtherFormats) {\n const kept = otherFormats.map((format) => `files.${format}`).join(', ');\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `${kept} stays in ${configFilepath}`,\n why: '--file-formats only changes the formats setup offers',\n fix: `Remove ${kept} from ${configFilepath} to stop translating those files`,\n })\n );\n }\n const fileFormats = await session.answer<SetupFileFormat[]>(\n '--file-formats',\n {\n explicit:\n selectedFormats ??\n (filePatterns.size > 0 ? [...filePatterns.keys()] : undefined),\n configured:\n configuredFormats.length > 0 || hasOtherFormats\n ? configuredFormats\n : undefined,\n // GT projects need no other files; others must choose a format.\n recommended: isUsingGT ? [] : undefined,\n ask: () =>\n promptMultiSelect({\n message: !isUsingGT\n ? 'What is the format of your language resource files? Select as many as applicable.\\nAdditionally, you can translate any other files you have in your project.'\n : `Do you have any additional files in this project to translate? For example, Markdown files for docs. ${chalk.dim(\n '(To continue without selecting press Enter)'\n )}`,\n options: SETUP_FILE_FORMATS.map((format) => ({\n value: format,\n label: FILE_EXT_TO_EXT_LABEL[format],\n })),\n required: !isUsingGT,\n }),\n }\n );\n if (\n fileFormats &&\n fileFormats.length === 0 &&\n !isUsingGT &&\n !hasOtherFormats\n ) {\n session.reject(\n 'No GT runtime is installed, so select at least one file format to translate'\n );\n }\n for (const format of filePatterns.keys()) {\n if (fileFormats && !fileFormats.includes(format)) {\n session.reject(\n `--file-patterns ${format}= needs ${format} in --file-formats`\n );\n }\n }\n\n const files: FilesOptions = {};\n for (const fileExtension of fileFormats ?? []) {\n const existingFormat = asRecord(existingFiles[fileExtension]);\n const configuredInclude = Array.isArray(existingFormat?.include)\n ? (existingFormat.include as string[])\n : undefined;\n const include = await session.answer(\n `--file-patterns ${fileExtension}=<glob>`,\n {\n explicit: filePatterns.get(fileExtension),\n configured: configuredInclude,\n recommended: [`./**/[locale]/*.${fileExtension}`],\n ask: async () =>\n parseGlobPatterns(\n await promptGlobPatterns({\n label: FILE_EXT_TO_EXT_LABEL[fileExtension],\n message: `${chalk.cyan(FILE_EXT_TO_EXT_LABEL[fileExtension])}: Enter a space-separated list of glob patterns matching the location of the ${FILE_EXT_TO_EXT_LABEL[fileExtension]} files you would like to translate.\\nMake sure to include [locale] in the patterns.\\nSee https://generaltranslation.com/docs/cli/reference/config#include for more information.`,\n defaultValue: `./**/[locale]/*.${fileExtension}`,\n validate: (value) =>\n parseGlobPatterns(value)\n .map(validateSetupPattern)\n .find((problem) => problem !== true) ?? true,\n })\n ),\n }\n );\n // Configured patterns stay untouched; new ones keep other entry options.\n if (include && include !== configuredInclude) {\n files[fileExtension] = { ...existingFormat, include };\n }\n }\n if (translationsDir && translationsDir !== configuredTranslationsDir) {\n files.gt = { output: path.join(translationsDir, `[locale].json`) };\n }\n\n const envFramework =\n setup.framework ?? getConfiguredFramework(existingConfig);\n // The effective project: an explicit ID replaces a configured one. The\n // framework's runtime project outranks a stale generic GT_PROJECT_ID.\n const projectId =\n options.projectId ||\n (typeof existingConfig.projectId === 'string'\n ? existingConfig.projectId\n : undefined) ||\n process.env[getDevelopmentEnvNames(envFramework).projectId];\n const configUpdate: SetupConfigUpdate = {\n defaultLocale,\n locales,\n src: options.src,\n files: Object.keys(files).length > 0 ? files : undefined,\n framework:\n (setup.saveFramework && setup.framework) || buildTool?.framework,\n publish: storage === 'cdn',\n // Selecting local storage drops stale CDN intent; a config that\n // already combines local files with publishing keeps it.\n clearPublish:\n storage === 'local' &&\n (options.storage === 'local' ||\n configuredStorage !== 'local' ||\n !supportsCDN),\n // An explicit switch to the CDN stops later runs inferring local files.\n clearGtOutput: storage === 'cdn' && configuredOutput !== undefined,\n // An explicit format list replaces the configured selection.\n removeFiles: selectedFormats\n ? configuredFormats.filter(\n (format) => !selectedFormats.includes(format)\n )\n : undefined,\n };\n session.assertResolved();\n\n // Validate what will be written, and use it for every later step.\n const { projectId: _writtenProjectId, ...effectiveConfig } =\n mergeSetupConfig(existingConfig, configUpdate);\n const settings = await generateSettings(\n { config: configFilepath, ...(projectId && { projectId }) },\n cwd,\n { resolvedConfig: effectiveConfig }\n );\n // Runtime credentials only count for the project this setup uses; the\n // framework's project variable is the one paired with its dev key.\n const runtimeProjectId =\n process.env[getDevelopmentEnvNames(envFramework).projectId] ??\n resolveProjectId();\n const runtimeProjectMatches =\n runtimeProjectId === undefined || runtimeProjectId === settings.projectId;\n const credentialsSet =\n runtimeProjectMatches && areCredentialsSet(settings, envFramework);\n const credentialsOption =\n (storage === 'local' && buildTool?.devCredentialsOption) ||\n '--dev-credentials';\n // Creating credentials talks to GT as the signed-in user unless an API\n // key is set. A development key in .env.local never stands in. An\n // obsolete stored login counts as signed out, so signing in replaces it.\n const canAuthenticate = async () =>\n Boolean(settings.apiKey) ||\n (await hasLogin({ baseUrl: settings.baseUrl }).catch((error) => {\n if (\n error instanceof UserAuthError &&\n error.code === 'obsolete_credentials'\n )\n return false;\n throw error;\n }));\n const provision =\n !credentialsSet &&\n (credentialsOption === '--live-translations'\n ? await session.answer('--live-translations', {\n explicit: options.liveTranslations ?? options.devCredentials,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n 'Would you like to set up live development translations? This requires signing in or an API key.',\n defaultValue: false,\n }),\n })\n : await session.answer('--dev-credentials or --no-dev-credentials', {\n explicit: options.devCredentials,\n // Creating a key is never a default, so --defaults leaves this open.\n // The prompt names the sign-in so its Yes default is informed.\n ask: async () =>\n promptConfirm({\n message: (await canAuthenticate())\n ? 'Would you like to set up a project ID and hot-reload key in .env.local?'\n : 'Would you like to sign in to General Translation and set up a project ID and hot-reload key in .env.local?',\n defaultValue: true,\n }),\n })) === true;\n if (!runtimeProjectMatches && !provision) {\n session.reject(\n `The runtime credentials in the environment belong to project ${runtimeProjectId}, not ${settings.projectId}; pass --dev-credentials to replace them in .env.local`\n );\n }\n // An explicit ID is saved to gt.config.json when it replaces a\n // configured one or no new credentials will record it in .env.local.\n if (options.projectId && (existingConfig.projectId || !provision)) {\n configUpdate.projectId = options.projectId;\n }\n if (provision) {\n checkDevelopmentProjectInputs(\n session,\n settings,\n options,\n options.projectId\n ? '--project-id'\n : // An empty configured ID falls through to the environment.\n typeof existingConfig.projectId === 'string' &&\n existingConfig.projectId\n ? configFilepath\n : 'the environment'\n );\n await withCredentialsError(() =>\n inspectCredentialsEnvFile(cwd, { framework: envFramework })\n );\n }\n\n if (reactSetup && buildTool) await buildTool.preflight(cwd);\n const installGT =\n packageJson !== null &&\n !isPackageInstalled('gt', packageJson, true, true) &&\n !buildTool?.skipsGTInstall(isUsingGT);\n const packageManager =\n reactSetup?.install || installGT\n ? await resolvePackageManager(session, options.packageManager)\n : undefined;\n\n session.assertResolved();\n\n if (provision && !(await canAuthenticate())) {\n await signInForSetup(session, settings.baseUrl);\n }\n const project = provision\n ? await withCredentialsError(() =>\n resolveDevelopmentProject(session, settings, options, cwd)\n )\n : undefined;\n session.assertResolved();\n\n // ----- Changes start here ----- //\n const resolvedLocales = locales as string[];\n\n if (reactSetup) {\n logger.info(`${chalk.yellow('[EXPERIMENTAL]')} Configuring project...`);\n if (reactSetup.install && packageManager) {\n await installWithProgress(\n session,\n reactSetup.install,\n packageManager,\n false\n );\n }\n await executeReactSetup(session, reactSetup, options);\n logger.step('Setting up project config...');\n }\n\n const reportManualAction = ({ whatHappened, fix }: ManualAction) => {\n session.humanActions.push(fix);\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened,\n fix,\n })\n );\n };\n const reportSetupResult = ({ steps, manualActions }: SetupResult) => {\n for (const step of steps) session.step(step);\n manualActions.forEach(reportManualAction);\n };\n const translationFilesError = (error: unknown) =>\n new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not create the translation files in ${translationsDir}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Choose another --translations-dir or fix the path, then rerun the command',\n })\n );\n const buildToolContext = {\n appDirectory: cwd,\n configFilepath,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n previousTranslationsDir: configuredTranslationsDir,\n };\n\n if (storage === 'local' && translationsDir) {\n if (buildTool && !reactSetup) {\n reportSetupResult(\n await buildTool\n .syncLoader({\n ...buildToolContext,\n translationsDir,\n keepAppSource: setup.keepAppSource,\n })\n .catch((error: unknown) => {\n throw translationFilesError(error);\n })\n );\n }\n const generatedLoader = this.shouldGenerateLocalTranslationLoader(\n buildTool?.ownsLoader ?? false,\n runtimeSetup\n );\n const loader = generatedLoader\n ? await createLoadTranslationsFile({\n appDirectory: cwd,\n translationsDir,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n previousTranslationsDir: configuredTranslationsDir,\n }).catch((error: unknown) => {\n throw translationFilesError(error);\n })\n : undefined;\n if (loader === 'created' || loader === 'updated') {\n session.step(`${loader} loadTranslations.js`);\n }\n // A loader left unchanged may not read the newly chosen directory.\n if (\n loader === 'custom' &&\n translationsDir !== configuredTranslationsDir\n ) {\n const loaderFile = path.relative(\n cwd,\n findLoadTranslationsFiles(cwd)[0] ?? 'loadTranslations.js'\n );\n reportManualAction({\n whatHappened: `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`,\n fix: `Update your custom ${loaderFile} to load translations from ${translationsDir}`,\n });\n }\n const guidance = this.getLocalTranslationGuidance({\n generatedLoader: generatedLoader && loader !== 'custom',\n runtimeSetup,\n translationsDir,\n });\n if (guidance) logger.message(guidance);\n } else if (\n storage === 'cdn' &&\n buildTool &&\n !reactSetup &&\n configuredTranslationsDir !== undefined\n ) {\n // Only the application setup rewrites the initializer; a loader passed\n // to it takes precedence over CDN loading.\n const action = await buildTool.getCDNStorageAction?.(buildToolContext);\n if (action !== null) {\n reportManualAction(\n action ?? {\n whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,\n fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`,\n }\n );\n }\n } else if (\n storage === 'cdn' &&\n !buildTool &&\n configuredTranslationsDir !== undefined\n ) {\n // gt-next uses a loadTranslations file whenever one exists, and a\n // loader passed to GTProvider takes precedence over the CDN. Name every\n // one: deleting only the first makes gt-next fall back to the next.\n const loaders = findLoadTranslationsFiles(cwd).map((loader) =>\n path.relative(cwd, loader)\n );\n if (loaders.length > 0) {\n const loaderFiles = loaders.join(', ');\n const [them, loads] =\n loaders.length === 1 ? ['it', 'loads'] : ['them', 'load'];\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${loaderFiles} still ${loads} them from ${configuredTranslationsDir}`,\n fix: `Delete ${loaderFiles}, and remove ${them} from your GT setup if you pass ${them} there, so translations load from the CDN`,\n });\n }\n }\n\n const configChange = await applySetupConfig(configFilepath, configUpdate);\n if (configChange !== 'unchanged') {\n session.step(`${configChange} ${configFilepath}`);\n }\n\n logger.success(\n `Edit ${chalk.cyan(\n configFilepath\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n if (reactSetup && buildTool) {\n reportSetupResult(await buildTool.apply(buildToolContext));\n }\n\n if (installGT && packageManager) {\n await installWithProgress(session, 'gt', packageManager, true);\n }\n\n if (project) {\n await withCredentialsError(() =>\n provisionDevelopmentCredentials(\n session,\n project,\n settings,\n envFramework,\n cwd\n )\n );\n logger.message(productionRuntimeKeyGuidance(settings.dashboardUrl));\n }\n\n if (!reactSetup) return undefined;\n // The React setup configures the app entry but never marks content for\n // translation, so what is left is reported as next steps.\n const devPackageManager =\n packageManager ??\n (await getPackageManager(cwd, options.packageManager, true).catch(\n () => undefined\n ));\n const scripts = asRecord(reactSetup.packageJson.scripts);\n return getInitNextSteps({\n framework: reactSetup.framework,\n configuredAppEntry:\n reactSetup.framework === 'next-app' || buildTool !== undefined,\n docsUrl: getSetupDocsUrl(reactSetup.framework),\n locales: resolvedLocales,\n configFilepath,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n devCommand:\n typeof scripts?.dev === 'string'\n ? `${devPackageManager?.runScriptCommand ?? 'npm run'} dev`\n : undefined,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2JA,MAAM,oCAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,SAAS,0BACP,cACA,OACQ;AACR,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV;EACA,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,uBAAuB,wBAAwB;CACnD,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAM,2BAA2B,IAAI,IACnC,OAAO,OAAO,wBAAwB,CACvC;AAED,SAAS,0BACP,YACuC;AACvC,QAAO,yBAAyB,IAAI,WAAW;;AAGjD,SAAS,gBAAgB,OAAuB;CAC9C,MAAM,OAAO,MAAM,MAAM;AACzB,KAAI,CAAC,KAAM,OAAM,IAAI,qBAAqB,qBAAqB;AAC/D,QAAO;;;AAIT,eAAe,qBAAwB,KAAmC;AACxE,KAAI;AACF,SAAO,MAAM,KAAK;UACX,OAAO;AAC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.4";
1
+ export declare const PACKAGE_VERSION = "2.28.5";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.28.4";
2
+ const PACKAGE_VERSION = "2.28.5";
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.4';\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.5';\n"],"mappings":";AACA,MAAa,kBAAkB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gt",
3
- "version": "2.28.4",
3
+ "version": "2.28.5",
4
4
  "main": "dist/index.js",
5
5
  "bin": "bin/main.js",
6
6
  "files": [