gt 2.27.3 → 2.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"upload.js","names":[],"sources":["../../../src/cli/commands/upload.ts"],"sourcesContent":["import {\n fileEncodingSkipReason,\n noDefaultLocaleError,\n} from '../../console/index.js';\nimport { exitSync, logErrorAndExit } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\nimport { getRelative, readFile } from '../../fs/findFilepath.js';\nimport { readFileContent } from '../../fs/fileContent.js';\nimport { Settings } from '../../types/index.js';\nimport { UploadOptions } from '../base.js';\nimport { extractJson } from '../../formats/json/extractJson.js';\nimport { validateJsonSchema } from '../../formats/json/utils.js';\nimport { runUploadFilesWorkflow } from '../../workflows/upload.js';\nimport { existsSync } from 'node:fs';\nimport { createFileMapping } from '../../formats/files/fileMapping.js';\nimport type { FileToUpload } from 'generaltranslation/types';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './utils/validation.js';\nimport { runPublishWorkflow } from '../../workflows/publish.js';\nimport {\n aggregateFiles,\n isUnparsableFile,\n} from '../../formats/files/aggregateFiles.js';\nimport { recordWarning } from '../../state/translateWarnings.js';\nimport {\n parseXcstringsCatalog,\n serializeXcstringsSlice,\n sliceTranslationCatalog,\n type XcstringsCatalog,\n} from '../../formats/xcstrings/parseXcstrings.js';\nimport { api } from '../../utils/api.js';\n\n/**\n * Sends multiple files to the API for translation\n * @param settings - Translation options including API settings\n * @returns Promise that resolves when translation is complete\n */\nexport async function upload(\n settings: Settings & UploadOptions\n): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n const additionalOptions = settings.options || {};\n const {\n resolvedPaths: filePaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n } = settings.files;\n\n // Reuse the same source aggregation path as translate/stage so source\n // parsing behavior stays consistent across commands.\n const { files: allFiles, publishMap } = await aggregateFiles(settings);\n const sourceFileNames = new Set(allFiles.map((file) => file.fileName));\n const compositeJsonFiles = new Map<\n string,\n { filePath: string; content: string }\n >();\n\n if (filePaths.json) {\n for (const filePath of filePaths.json) {\n const relativePath = getRelative(filePath);\n if (!sourceFileNames.has(relativePath)) continue;\n\n const jsonSchema = validateJsonSchema(additionalOptions, filePath);\n if (jsonSchema?.composite) {\n compositeJsonFiles.set(relativePath, {\n filePath,\n content: readFile(filePath),\n });\n }\n }\n }\n\n // Translation files are validated like their sources in aggregateFiles.\n const skipValidation = additionalOptions.skipFileValidation;\n const translationParseFormats = new Map<string, 'JSON' | 'YAML'>();\n if (!skipValidation?.json) {\n for (const filePath of [\n ...(filePaths.json ?? []),\n ...(filePaths.twilioContentJson ?? []),\n ]) {\n translationParseFormats.set(getRelative(filePath), 'JSON');\n }\n }\n if (!skipValidation?.yaml) {\n for (const filePath of filePaths.yaml ?? []) {\n translationParseFormats.set(getRelative(filePath), 'YAML');\n }\n }\n\n // An .xcstrings catalog carries its own translations, so each locale's\n // upload is a slice of the same file rather than a separate translation\n // file. Catalogs aggregateFiles could not parse are already reported.\n const xcstringsCatalogs = new Map<string, XcstringsCatalog>();\n if (filePaths.xcstrings) {\n for (const filePath of filePaths.xcstrings) {\n const relativePath = getRelative(filePath);\n if (!sourceFileNames.has(relativePath)) continue;\n xcstringsCatalogs.set(\n relativePath,\n parseXcstringsCatalog(readFile(filePath))\n );\n }\n }\n\n if (allFiles.length === 0) {\n logger.error(\n 'No files to upload were found. Check your configuration and try again.'\n );\n return;\n }\n\n if (!settings.defaultLocale) {\n return logErrorAndExit(noDefaultLocaleError);\n }\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n\n const locales = settings.locales || [];\n // Create file mapping for all file types\n const fileMapping = createFileMapping(\n filePaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n locales,\n settings.defaultLocale\n );\n\n // construct object\n const uploadData = allFiles.map((file) => {\n const sourceFile: FileToUpload = { ...file };\n\n const translations: FileToUpload[] = [];\n const compositeInfo = compositeJsonFiles.get(file.fileName);\n const xcstringsCatalog = xcstringsCatalogs.get(file.fileName);\n\n for (const locale of locales) {\n if (xcstringsCatalog) {\n // Catalog keys are canonical tags; the configured locale may be an alias.\n const slice = sliceTranslationCatalog(\n xcstringsCatalog,\n api.resolveCanonicalLocale(locale)\n );\n // A locale the catalog does not carry has nothing to upload\n if (!slice) continue;\n translations.push({\n content: serializeXcstringsSlice(slice),\n fileName: file.fileName,\n fileFormat: file.transformFormat ?? file.fileFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n } else if (compositeInfo) {\n // Composite JSON: extract translations from the same source file\n const extracted = extractJson(\n compositeInfo.content,\n compositeInfo.filePath,\n additionalOptions,\n locale,\n settings.defaultLocale\n );\n if (extracted) {\n translations.push({\n content: extracted,\n fileName: file.fileName,\n fileFormat: file.transformFormat ?? file.fileFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n }\n } else {\n // Non-composite: look for separate translation files\n const translatedFileName = fileMapping[locale]?.[file.fileName];\n if (translatedFileName && existsSync(translatedFileName)) {\n const translationFormat = file.transformFormat ?? file.fileFormat;\n let translatedContent: string;\n try {\n translatedContent = readFileContent(\n translatedFileName,\n translationFormat\n );\n } catch (error) {\n // One undecodable locale should not block the others: skip it and\n // report it in the summary.\n const relativePath = getRelative(translatedFileName);\n const reason = fileEncodingSkipReason(error);\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n const parseFormat = translationParseFormats.get(file.fileName);\n if (\n parseFormat &&\n isUnparsableFile(\n translatedContent,\n getRelative(translatedFileName),\n parseFormat\n )\n ) {\n continue;\n }\n translations.push({\n content: translatedContent,\n fileName: translatedFileName,\n fileFormat: translationFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n }\n }\n }\n return {\n source: sourceFile,\n translations,\n };\n });\n\n try {\n // Send all files in a single API call\n const { branchData } = await runUploadFilesWorkflow({\n files: uploadData,\n options: settings,\n });\n\n // Publish files to CDN if publish config exists\n await runPublishWorkflow(\n allFiles,\n publishMap,\n branchData.currentBranch.id,\n settings\n );\n } catch (error) {\n logErrorAndExit(`Error uploading files: ${error}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuCA,eAAsB,OACpB,UACe;AACf,KAAI,CAAC,SAAS,MACZ;CAGF,MAAM,oBAAoB,SAAS,WAAW,EAAE;CAChD,MAAM,EACJ,eAAe,WACf,kBACA,gBACA,qBACE,SAAS;CAIb,MAAM,EAAE,OAAO,UAAU,eAAe,MAAM,eAAe,SAAS;CACtE,MAAM,kBAAkB,IAAI,IAAI,SAAS,KAAK,SAAS,KAAK,SAAS,CAAC;CACtE,MAAM,qCAAqB,IAAI,KAG5B;AAEH,KAAI,UAAU,KACZ,MAAK,MAAM,YAAY,UAAU,MAAM;EACrC,MAAM,eAAe,YAAY,SAAS;AAC1C,MAAI,CAAC,gBAAgB,IAAI,aAAa,CAAE;AAGxC,MADmB,mBAAmB,mBAAmB,SAC3C,EAAE,UACd,oBAAmB,IAAI,cAAc;GACnC;GACA,SAAS,SAAS,SAAS;GAC5B,CAAC;;CAMR,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,0CAA0B,IAAI,KAA8B;AAClE,KAAI,CAAC,gBAAgB,KACnB,MAAK,MAAM,YAAY,CACrB,GAAI,UAAU,QAAQ,EAAE,EACxB,GAAI,UAAU,qBAAqB,EAAE,CACtC,CACC,yBAAwB,IAAI,YAAY,SAAS,EAAE,OAAO;AAG9D,KAAI,CAAC,gBAAgB,KACnB,MAAK,MAAM,YAAY,UAAU,QAAQ,EAAE,CACzC,yBAAwB,IAAI,YAAY,SAAS,EAAE,OAAO;CAO9D,MAAM,oCAAoB,IAAI,KAA+B;AAC7D,KAAI,UAAU,UACZ,MAAK,MAAM,YAAY,UAAU,WAAW;EAC1C,MAAM,eAAe,YAAY,SA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oBAAoB,KAAK,mBAAmB,KAAK;IACvD,IAAI;AACJ,QAAI;AACF,yBAAoB,gBAClB,oBACA,kBACD;aACM,OAAO;KAGd,MAAM,eAAe,YAAY,mBAAmB;KACpD,MAAM,SAAS,uBAAuB,MAAM;AAC5C,YAAO,KAAK,YAAY,aAAa,IAAI,SAAS;AAClD,mBAAc,gBAAgB,cAAc,OAAO;AACnD;;IAEF,MAAM,cAAc,wBAAwB,IAAI,KAAK,SAAS;AAC9D,QACE,eACA,iBACE,mBACA,YAAY,mBAAmB,EAC/B,YACD,CAED;AAEF,iBAAa,KAAK;KAChB,SAAS;KACT,UAAU;KACV,YAAY;KACZ,YAAY,KAAK;KACjB;KACA,QAAQ,KAAK;KACb,WAAW,KAAK;KACjB,CAAC;;;AAIR,SAAO;GACL,QAAQ;GACR;GACD;GACD;AAEF,KAAI;EAEF,MAAM,EAAE,eAAe,MAAM,uBAAuB;GAClD,OAAO;GACP,SAAS;GACV,CAAC;AAGF,QAAM,mBACJ,UACA,YACA,WAAW,cAAc,IACzB,SACD;UACM,OAAO;AACd,kBAAgB,0BAA0B,QAAQ"}
1
+ {"version":3,"file":"upload.js","names":[],"sources":["../../../src/cli/commands/upload.ts"],"sourcesContent":["import {\n fileEncodingSkipReason,\n noDefaultLocaleError,\n} from '../../console/index.js';\nimport { exitSync, logErrorAndExit } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\nimport { getRelative, readFile } from '../../fs/findFilepath.js';\nimport { readFileContent } from '../../fs/fileContent.js';\nimport { Settings } from '../../types/index.js';\nimport { UploadOptions } from '../base.js';\nimport { extractJson } from '../../formats/json/extractJson.js';\nimport { validateJsonSchema } from '../../formats/json/utils.js';\nimport { runUploadFilesWorkflow } from '../../workflows/upload.js';\nimport { existsSync } from 'node:fs';\nimport { createFileMapping } from '../../formats/files/fileMapping.js';\nimport type { FileToUpload } from 'generaltranslation/types';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './utils/validation.js';\nimport { runPublishWorkflow } from '../../workflows/publish.js';\nimport {\n aggregateFiles,\n isUnparsableFile,\n} from '../../formats/files/aggregateFiles.js';\nimport { recordWarning } from '../../state/translateWarnings.js';\nimport {\n parseXcstringsCatalog,\n serializeXcstringsSlice,\n sliceTranslationCatalog,\n type XcstringsCatalog,\n} from '../../formats/xcstrings/parseXcstrings.js';\nimport { api } from '../../utils/api.js';\nimport { collectParaglideContext } from '../../paraglide/collectParaglideContext.js';\n\n/**\n * Sends multiple files to the API for translation\n * @param settings - Translation options including API settings\n * @returns Promise that resolves when translation is complete\n */\nexport async function upload(\n settings: Settings & UploadOptions\n): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n const additionalOptions = settings.options || {};\n const {\n resolvedPaths: filePaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n } = settings.files;\n\n if (settings.files?.parsingFlags?.json?.includeSourceCodeContext) {\n await collectParaglideContext();\n }\n\n // Reuse the same source aggregation path as translate/stage so source\n // parsing behavior stays consistent across commands.\n const { files: allFiles, publishMap } = await aggregateFiles(settings);\n const sourceFileNames = new Set(allFiles.map((file) => file.fileName));\n const compositeJsonFiles = new Map<\n string,\n { filePath: string; content: string }\n >();\n\n if (filePaths.json) {\n for (const filePath of filePaths.json) {\n const relativePath = getRelative(filePath);\n if (!sourceFileNames.has(relativePath)) continue;\n\n const jsonSchema = validateJsonSchema(additionalOptions, filePath);\n if (jsonSchema?.composite) {\n compositeJsonFiles.set(relativePath, {\n filePath,\n content: readFile(filePath),\n });\n }\n }\n }\n\n // Translation files are validated like their sources in aggregateFiles.\n const skipValidation = additionalOptions.skipFileValidation;\n const translationParseFormats = new Map<string, 'JSON' | 'YAML'>();\n if (!skipValidation?.json) {\n for (const filePath of [\n ...(filePaths.json ?? []),\n ...(filePaths.twilioContentJson ?? []),\n ]) {\n translationParseFormats.set(getRelative(filePath), 'JSON');\n }\n }\n if (!skipValidation?.yaml) {\n for (const filePath of filePaths.yaml ?? []) {\n translationParseFormats.set(getRelative(filePath), 'YAML');\n }\n }\n\n // An .xcstrings catalog carries its own translations, so each locale's\n // upload is a slice of the same file rather than a separate translation\n // file. Catalogs aggregateFiles could not parse are already reported.\n const xcstringsCatalogs = new Map<string, XcstringsCatalog>();\n if (filePaths.xcstrings) {\n for (const filePath of filePaths.xcstrings) {\n const relativePath = getRelative(filePath);\n if (!sourceFileNames.has(relativePath)) continue;\n xcstringsCatalogs.set(\n relativePath,\n parseXcstringsCatalog(readFile(filePath))\n );\n }\n }\n\n if (allFiles.length === 0) {\n logger.error(\n 'No files to upload were found. Check your configuration and try again.'\n );\n return;\n }\n\n if (!settings.defaultLocale) {\n return logErrorAndExit(noDefaultLocaleError);\n }\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n\n const locales = settings.locales || [];\n // Create file mapping for all file types\n const fileMapping = createFileMapping(\n filePaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n locales,\n settings.defaultLocale\n );\n\n // construct object\n const uploadData = allFiles.map((file) => {\n const sourceFile: FileToUpload = { ...file };\n\n const translations: FileToUpload[] = [];\n const compositeInfo = compositeJsonFiles.get(file.fileName);\n const xcstringsCatalog = xcstringsCatalogs.get(file.fileName);\n\n for (const locale of locales) {\n if (xcstringsCatalog) {\n // Catalog keys are canonical tags; the configured locale may be an alias.\n const slice = sliceTranslationCatalog(\n xcstringsCatalog,\n api.resolveCanonicalLocale(locale)\n );\n // A locale the catalog does not carry has nothing to upload\n if (!slice) continue;\n translations.push({\n content: serializeXcstringsSlice(slice),\n fileName: file.fileName,\n fileFormat: file.transformFormat ?? file.fileFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n } else if (compositeInfo) {\n // Composite JSON: extract translations from the same source file\n const extracted = extractJson(\n compositeInfo.content,\n compositeInfo.filePath,\n additionalOptions,\n locale,\n settings.defaultLocale\n );\n if (extracted) {\n translations.push({\n content: extracted,\n fileName: file.fileName,\n fileFormat: file.transformFormat ?? file.fileFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n }\n } else {\n // Non-composite: look for separate translation files\n const translatedFileName = fileMapping[locale]?.[file.fileName];\n if (translatedFileName && existsSync(translatedFileName)) {\n const translationFormat = file.transformFormat ?? file.fileFormat;\n let translatedContent: string;\n try {\n translatedContent = readFileContent(\n translatedFileName,\n translationFormat\n );\n } catch (error) {\n // One undecodable locale should not block the others: skip it and\n // report it in the summary.\n const relativePath = getRelative(translatedFileName);\n const reason = fileEncodingSkipReason(error);\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n const parseFormat = translationParseFormats.get(file.fileName);\n if (\n parseFormat &&\n isUnparsableFile(\n translatedContent,\n getRelative(translatedFileName),\n parseFormat\n )\n ) {\n continue;\n }\n translations.push({\n content: translatedContent,\n fileName: translatedFileName,\n fileFormat: translationFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n }\n }\n }\n return {\n source: sourceFile,\n translations,\n };\n });\n\n try {\n // Send all files in a single API call\n const { branchData } = await runUploadFilesWorkflow({\n files: uploadData,\n options: settings,\n });\n\n // Publish files to CDN if publish config exists\n await runPublishWorkflow(\n allFiles,\n publishMap,\n branchData.currentBranch.id,\n settings\n );\n } catch (error) {\n logErrorAndExit(`Error uploading files: ${error}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwCA,eAAsB,OACpB,UACe;AACf,KAAI,CAAC,SAAS,MACZ;CAGF,MAAM,oBAAoB,SAAS,WAAW,EAAE;CAChD,MAAM,EACJ,eAAe,WACf,kBACA,gBACA,qBACE,SAAS;AAEb,KAAI,SAAS,OAAO,cAAc,MAAM,yBACtC,OAAM,yBAAyB;CAKjC,MAAM,EAAE,OAAO,UAAU,eAAe,MAAM,eAAe,SAAS;CACtE,MAAM,kBAAkB,IAAI,IAAI,SAAS,KAAK,SAAS,KAAK,SAAS,CAA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AAQ;GACR;GACD;GACD;AAEF,KAAI;EAEF,MAAM,EAAE,eAAe,MAAM,uBAAuB;GAClD,OAAO;GACP,SAAS;GACV,CAAC;AAGF,QAAM,mBACJ,UACA,YACA,WAAW,cAAc,IACzB,SACD;UACM,OAAO;AACd,kBAAgB,0BAA0B,QAAQ"}
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.27.3";
1
+ export declare const PACKAGE_VERSION = "2.28.0";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.27.3";
2
+ const PACKAGE_VERSION = "2.28.0";
3
3
  //#endregion
4
4
  export { PACKAGE_VERSION };
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.27.3';\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.0';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -3,7 +3,7 @@ import chalk from "chalk";
3
3
  //#region src/locadex/setupFlow.ts
4
4
  /** Opens the GitHub connection page unless the caller only hands off the URL. */
5
5
  async function setupLocadex(settings, { openBrowser = true } = {}) {
6
- const urlToOpen = `${settings.dashboardUrl}/api/integrations/github/start?returnTo=%2Fproject%2Flocadex`;
6
+ const urlToOpen = `${settings.dashboardUrl}/api/integrations/github/start`;
7
7
  if (openBrowser) await import("open").then((open) => open.default(urlToOpen, { wait: false }));
8
8
  logger.message(`${chalk.dim(openBrowser ? `If the browser window didn't open automatically, open the following link:` : "Open the following link to connect GitHub and finish setting up Locadex:")}\n\n${chalk.cyan(urlToOpen)}`);
9
9
  return urlToOpen;
@@ -1 +1 @@
1
- {"version":3,"file":"setupFlow.js","names":[],"sources":["../../src/locadex/setupFlow.ts"],"sourcesContent":["import { Settings } from '../types/index.js';\nimport { logger } from '../console/logger.js';\nimport chalk from 'chalk';\n\n/** Opens the GitHub connection page unless the caller only hands off the URL. */\nexport async function setupLocadex(\n settings: Settings,\n { openBrowser = true }: { openBrowser?: boolean } = {}\n): Promise<string> {\n const urlToOpen = `${settings.dashboardUrl}/api/integrations/github/start?returnTo=%2Fproject%2Flocadex`;\n if (openBrowser) {\n await import('open').then((open) =>\n open.default(urlToOpen, {\n wait: false,\n })\n );\n }\n\n logger.message(\n `${chalk.dim(\n openBrowser\n ? `If the browser window didn't open automatically, open the following link:`\n : 'Open the following link to connect GitHub and finish setting up Locadex:'\n )}\\n\\n${chalk.cyan(urlToOpen)}`\n );\n return urlToOpen;\n}\n"],"mappings":";;;;AAKA,eAAsB,aACpB,UACA,EAAE,cAAc,SAAoC,EAAE,EACrC;CACjB,MAAM,YAAY,GAAG,SAAS,aAAa;AAC3C,KAAI,YACF,OAAM,OAAO,QAAQ,MAAM,SACzB,KAAK,QAAQ,WAAW,EACtB,MAAM,OACP,CAAC,CACH;AAGH,QAAO,QACL,GAAG,MAAM,IACP,cACI,8EACA,2EACL,CAAC,MAAM,MAAM,KAAK,UAAU,GAC9B;AACD,QAAO"}
1
+ {"version":3,"file":"setupFlow.js","names":[],"sources":["../../src/locadex/setupFlow.ts"],"sourcesContent":["import { Settings } from '../types/index.js';\nimport { logger } from '../console/logger.js';\nimport chalk from 'chalk';\n\n/** Opens the GitHub connection page unless the caller only hands off the URL. */\nexport async function setupLocadex(\n settings: Settings,\n { openBrowser = true }: { openBrowser?: boolean } = {}\n): Promise<string> {\n // No returnTo: the dashboard reads /project/<segment> as a project ID, and\n // the route already returns to the dashboard home.\n const urlToOpen = `${settings.dashboardUrl}/api/integrations/github/start`;\n if (openBrowser) {\n await import('open').then((open) =>\n open.default(urlToOpen, {\n wait: false,\n })\n );\n }\n\n logger.message(\n `${chalk.dim(\n openBrowser\n ? `If the browser window didn't open automatically, open the following link:`\n : 'Open the following link to connect GitHub and finish setting up Locadex:'\n )}\\n\\n${chalk.cyan(urlToOpen)}`\n );\n return urlToOpen;\n}\n"],"mappings":";;;;AAKA,eAAsB,aACpB,UACA,EAAE,cAAc,SAAoC,EAAE,EACrC;CAGjB,MAAM,YAAY,GAAG,SAAS,aAAa;AAC3C,KAAI,YACF,OAAM,OAAO,QAAQ,MAAM,SACzB,KAAK,QAAQ,WAAW,EACtB,MAAM,OACP,CAAC,CACH;AAGH,QAAO,QACL,GAAG,MAAM,IACP,cACI,8EACA,2EACL,CAAC,MAAM,MAAM,KAAK,UAAU,GAC9B;AACD,QAAO"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Writes the Paraglide metadata files that file collection reads, so call it
3
+ * first. Failures only warn.
4
+ */
5
+ export declare function collectParaglideContext(projectRoot?: string): Promise<void>;
@@ -0,0 +1,43 @@
1
+ import { logger } from "../console/logger.js";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ //#region src/paraglide/collectParaglideContext.ts
6
+ const PARAGLIDE_COMPILER = "@generaltranslation/paraglide-js/compiler";
7
+ /**
8
+ * Writes the Paraglide metadata files that file collection reads, so call it
9
+ * first. Failures only warn.
10
+ */
11
+ async function collectParaglideContext(projectRoot = process.cwd()) {
12
+ const compilerPath = resolveParaglideCompiler(projectRoot);
13
+ if (!compilerPath) return;
14
+ const warnings = [];
15
+ const spinner = logger.createSpinner("dots");
16
+ spinner.start("Collecting source code context for Paraglide messages...");
17
+ try {
18
+ const { collectContext } = await import(pathToFileURL(compilerPath).href);
19
+ await collectContext({
20
+ root: projectRoot,
21
+ logger: {
22
+ warn: (message) => warnings.push(message),
23
+ info: () => {}
24
+ }
25
+ });
26
+ spinner.stop("Collected source code context for Paraglide messages");
27
+ } catch (error) {
28
+ spinner.stop("Source code context for Paraglide messages was skipped");
29
+ warnings.push(`Source code context for Paraglide messages could not be collected: ${error instanceof Error ? error.message : String(error)}`);
30
+ }
31
+ for (const warning of warnings) logger.warn(warning);
32
+ }
33
+ function resolveParaglideCompiler(projectRoot) {
34
+ try {
35
+ return createRequire(path.join(projectRoot, "package.json")).resolve(PARAGLIDE_COMPILER);
36
+ } catch {
37
+ return;
38
+ }
39
+ }
40
+ //#endregion
41
+ export { collectParaglideContext };
42
+
43
+ //# sourceMappingURL=collectParaglideContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collectParaglideContext.js","names":[],"sources":["../../src/paraglide/collectParaglideContext.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { logger } from '../console/logger.js';\n\nconst PARAGLIDE_COMPILER = '@generaltranslation/paraglide-js/compiler';\n\ntype ParaglideCompiler = {\n collectContext(options: {\n root: string;\n logger: {\n warn(message: string): void;\n info(message: string): void;\n };\n }): Promise<void>;\n};\n\n/**\n * Writes the Paraglide metadata files that file collection reads, so call it\n * first. Failures only warn.\n */\nexport async function collectParaglideContext(\n projectRoot: string = process.cwd()\n): Promise<void> {\n const compilerPath = resolveParaglideCompiler(projectRoot);\n if (!compilerPath) return;\n\n // Deferred so they do not break the spinner line\n const warnings: string[] = [];\n const spinner = logger.createSpinner('dots');\n spinner.start('Collecting source code context for Paraglide messages...');\n\n try {\n const { collectContext }: ParaglideCompiler = await import(\n pathToFileURL(compilerPath).href\n );\n await collectContext({\n root: projectRoot,\n logger: {\n warn: (message) => warnings.push(message),\n info: () => {},\n },\n });\n spinner.stop('Collected source code context for Paraglide messages');\n } catch (error) {\n spinner.stop('Source code context for Paraglide messages was skipped');\n warnings.push(\n `Source code context for Paraglide messages could not be collected: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n\n for (const warning of warnings) logger.warn(warning);\n}\n\nfunction resolveParaglideCompiler(projectRoot: string): string | undefined {\n try {\n return createRequire(path.join(projectRoot, 'package.json')).resolve(\n PARAGLIDE_COMPILER\n );\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;AAKA,MAAM,qBAAqB;;;;;AAgB3B,eAAsB,wBACpB,cAAsB,QAAQ,KAAK,EACpB;CACf,MAAM,eAAe,yBAAyB,YAAY;AAC1D,KAAI,CAAC,aAAc;CAGnB,MAAM,WAAqB,EAAE;CAC7B,MAAM,UAAU,OAAO,cAAc,OAAO;AAC5C,SAAQ,MAAM,2DAA2D;AAEzE,KAAI;EACF,MAAM,EAAE,mBAAsC,MAAM,OAClD,cAAc,aAAa,CAAC;AAE9B,QAAM,eAAe;GACnB,MAAM;GACN,QAAQ;IACN,OAAO,YAAY,SAAS,KAAK,QAAQ;IACzC,YAAY;IACb;GACF,CAAC;AACF,UAAQ,KAAK,uDAAuD;UAC7D,OAAO;AACd,UAAQ,KAAK,yDAAyD;AACtE,WAAS,KACP,sEACE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GAEzD;;AAGH,MAAK,MAAM,WAAW,SAAU,QAAO,KAAK,QAAQ;;AAGtD,SAAS,yBAAyB,aAAyC;AACzE,KAAI;AACF,SAAO,cAAc,KAAK,KAAK,aAAa,eAAe,CAAC,CAAC,QAC3D,mBACD;SACK;AACN"}
@@ -25,7 +25,9 @@ export type DevelopmentProjectOptions = {
25
25
  };
26
26
  /**
27
27
  * Records project inputs a noninteractive run is missing, before signing in,
28
- * so it never waits for approval only to fail on a missing flag.
28
+ * so it never waits for approval only to fail on a missing flag. --org-id is
29
+ * the exception: whether it is needed depends on the account's organizations,
30
+ * so its failure comes after sign-in and lists them.
29
31
  */
30
32
  export declare function checkDevelopmentProjectInputs(session: OnboardingSession, settings: Settings, options: DevelopmentProjectOptions,
31
33
  /** Where settings.projectId came from, so a person can remove it. */
@@ -93,10 +93,12 @@ const noProjectChosenError = createDiagnosticMessage({
93
93
  async function resolveNewProject(session, settings, options, cwd) {
94
94
  const orgs = await api.listOrgs();
95
95
  if (orgs.length === 0) throw new OnboardingError(noAccessibleOrgError(settings.dashboardUrl));
96
- if (options.orgId && !orgs.some((org) => org.id === options.orgId)) session.reject(`--org-id ${options.orgId} is not an accessible organization`);
96
+ const orgList = orgs.map((org) => `\n - ${org.name} (${org.id})`).join("");
97
+ if (options.orgId && !orgs.some((org) => org.id === options.orgId)) session.reject(`--org-id ${options.orgId} is not an accessible organization; use one of:${orgList}`);
97
98
  const orgId = await session.answer("--org-id", {
98
99
  explicit: options.orgId,
99
100
  configured: orgs.length === 1 ? orgs[0].id : void 0,
101
+ hint: `Accessible organizations for --org-id:${orgList}`,
100
102
  ask: () => promptSelect({
101
103
  message: "Which organization should own the new project?",
102
104
  options: orgs.map((org) => ({
@@ -119,7 +121,9 @@ async function resolveNewProject(session, settings, options, cwd) {
119
121
  }
120
122
  /**
121
123
  * Records project inputs a noninteractive run is missing, before signing in,
122
- * so it never waits for approval only to fail on a missing flag.
124
+ * so it never waits for approval only to fail on a missing flag. --org-id is
125
+ * the exception: whether it is needed depends on the account's organizations,
126
+ * so its failure comes after sign-in and lists them.
123
127
  */
124
128
  function checkDevelopmentProjectInputs(session, settings, options, projectIdSource) {
125
129
  if (settings.projectId && options.createProject) session.reject(`--create-project cannot be combined with project ${settings.projectId} from ${projectIdSource}; remove --create-project to keep using it, or remove the project ID from ${projectIdSource} to create a new project`);
@@ -1 +1 @@
1
- {"version":3,"file":"developmentCredentials.js","names":[],"sources":["../../src/setup/developmentCredentials.ts"],"sourcesContent":["import path from 'node:path';\nimport chalk from 'chalk';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { ApiError } from 'generaltranslation/errors';\nimport { logger } from '../console/logger.js';\nimport { promptConfirm, promptSelect, promptText } from '../console/logging.js';\nimport type { Settings, SupportedFrameworks } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { setCredentials } from '../utils/credentials.js';\nimport { envFiles } from '../utils/loadEnv.js';\nimport { createUserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { OnboardingError, type OnboardingSession } from './onboarding.js';\n\nconst DEVELOPMENT_KEY_NAME = 'Development key (gt init)';\n\n/** .env.local never reaches production; the runtime key there is set on the host. */\nexport function productionRuntimeKeyGuidance(dashboardUrl: string): string {\n return `${chalk.dim('For runtime translation in production, create an API key in the dashboard')} ${chalk.cyan(dashboardUrl)} ${chalk.dim('and set GT_API_KEY and GT_PROJECT_ID in your hosting environment.')}`;\n}\n\n/**\n * Interactive setup keeps the browser login with its device fallback;\n * noninteractive setup always shows a device code (and emits it as a JSON\n * event) and waits for a person to approve it, without opening a browser.\n */\nexport async function signInForSetup(\n session: OnboardingSession,\n baseUrl: string | undefined\n): Promise<void> {\n try {\n await loginInteractively(baseUrl, session.interactive, (deviceCode) =>\n session.emit({ type: 'authorization_required', ...deviceCode })\n );\n } catch (error) {\n throw new OnboardingError(createUserAuthError('Sign in failed', error));\n }\n logger.message('You are now signed in.');\n}\n\ntype ProjectChoice = Awaited<ReturnType<typeof api.listProjects>>[number];\n\n/** An existing project, or the inputs for creating one. */\nexport type DevelopmentProject =\n | { id: string; name?: string }\n | { create: { orgId: string; name: string } };\n\nexport type DevelopmentProjectOptions = {\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n};\n\nfunction noAccessibleOrgError(dashboardUrl: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No accessible organizations were found',\n fix: `Create an organization in the dashboard ${dashboardUrl} or ask an admin for access, then rerun the setup wizard`,\n });\n}\n\n/**\n * The API client sends GT_API_KEY instead of the sign-in whenever it is set,\n * so signing in alone cannot fix a denial; GT_API_KEY has to go first.\n */\nfunction apiKeyDeniedGuidance(created: string, permission: string) {\n return {\n why: `GT_API_KEY is set, so setup used that key instead of your sign-in, and creating ${created} requires ${permission}`,\n fix: `Remove GT_API_KEY from your shell and from ${envFiles.join(', ')}, then rerun the setup wizard to sign in`,\n wayOut: `set GT_API_KEY to an organization key with ${permission}`,\n };\n}\n\nfunction projectCreationDeniedError(\n orgId: string,\n usingApiKey: boolean,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Project creation was denied for organization ${orgId}`,\n ...(usingApiKey\n ? apiKeyDeniedGuidance('a project', 'org:projects:create')\n : {\n why: 'listing an organization does not confirm permission to create projects in it',\n fix: 'Ask an organization admin for org:projects:create, or use credentials that have that permission for this organization',\n }),\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nfunction keyCreationDeniedError(\n projectId: string,\n usingApiKey: boolean,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Development key creation was denied for project ${projectId}`,\n ...(usingApiKey\n ? apiKeyDeniedGuidance('a key', 'project:api_keys:write')\n : {\n why: 'creating a key requires project:api_keys:write for this project',\n fix: 'Ask a project admin for project:api_keys:write, then rerun the setup wizard',\n }),\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\n/** Replaces a 403 with setup guidance; other failures keep their own error. */\nfunction explainForbidden(diagnostic: (error: unknown) => string) {\n return (error: unknown): never => {\n if (!(error instanceof ApiError) || error.code !== 403) throw error;\n throw new OnboardingError(diagnostic(error));\n };\n}\n\nconst noProjectChosenError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No project was chosen for the development credentials',\n reassurance: 'No project files were changed',\n fix: 'Rerun with --project-id <id> or --create-project, or skip them with --no-dev-credentials',\n});\n\nasync function resolveNewProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string\n): Promise<DevelopmentProject | undefined> {\n // Discovery lists accessible organizations, not creation permissions.\n // The API enforces creation permission when provisioning the project.\n const orgs = await api.listOrgs();\n if (orgs.length === 0) {\n throw new OnboardingError(noAccessibleOrgError(settings.dashboardUrl));\n }\n if (options.orgId && !orgs.some((org) => org.id === options.orgId)) {\n session.reject(\n `--org-id ${options.orgId} is not an accessible organization`\n );\n }\n const orgId = await session.answer('--org-id', {\n explicit: options.orgId,\n // One organization is not a choice between options.\n configured: orgs.length === 1 ? orgs[0].id : undefined,\n ask: () =>\n promptSelect({\n message: 'Which organization should own the new project?',\n options: orgs.map((org) => ({ value: org.id, label: org.name })),\n }),\n });\n const name = await session.answer('--project-name', {\n explicit: options.projectName?.trim() || undefined,\n ask: async () =>\n (\n await promptText({\n message: 'What should the project be called?',\n defaultValue: path.basename(cwd),\n })\n ).trim() || path.basename(cwd),\n });\n return orgId && name ? { create: { orgId, name } } : undefined;\n}\n\n/**\n * Records project inputs a noninteractive run is missing, before signing in,\n * so it never waits for approval only to fail on a missing flag.\n */\nexport function checkDevelopmentProjectInputs(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n /** Where settings.projectId came from, so a person can remove it. */\n projectIdSource: string\n): void {\n if (settings.projectId && options.createProject) {\n session.reject(\n `--create-project cannot be combined with project ${settings.projectId} from ${projectIdSource}; remove --create-project to keep using it, or remove the project ID from ${projectIdSource} to create a new project`\n );\n }\n if (settings.projectId || session.interactive) return;\n if (!options.createProject) {\n session.require('--project-id or --create-project');\n } else if (!options.projectName?.trim()) {\n session.require('--project-name');\n }\n}\n\n/**\n * Chooses the project for development credentials without creating anything:\n * a supplied or configured ID, explicit creation inputs, or (interactively)\n * a selection among the account's projects.\n */\nexport async function resolveDevelopmentProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string = process.cwd()\n): Promise<DevelopmentProject | undefined> {\n if (settings.projectId) return { id: settings.projectId };\n if (options.createProject) {\n return resolveNewProject(session, settings, options, cwd);\n }\n const projects = await api.listProjects();\n if (projects.length === 0) {\n // Creating a project is its own choice, separate from creating a key.\n const create = await session.answer('--project-id or --create-project', {\n ask: () =>\n promptConfirm({\n message: 'No projects found for your account. Create a new project?',\n defaultValue: true,\n }),\n });\n if (create === false) throw new OnboardingError(noProjectChosenError);\n return create\n ? resolveNewProject(session, settings, options, cwd)\n : undefined;\n }\n const choice = await session.answer<ProjectChoice | null>(\n '--project-id or --create-project',\n {\n ask: () =>\n promptSelect<ProjectChoice | null>({\n message: 'Which project should this app use?',\n options: [\n ...projects.map((project) => ({\n value: project,\n label: project.name,\n hint: project.orgName,\n })),\n { value: null, label: 'Create a new project' },\n ],\n }),\n }\n );\n if (choice === undefined) return undefined;\n return choice\n ? { id: choice.id, name: choice.name }\n : resolveNewProject(session, settings, options, cwd);\n}\n\n/**\n * Creates the chosen project if needed, mints a development key limited to\n * runtime translation, and saves both to .env.local. Callers inspect\n * .env.local first; the key is never printed.\n */\nexport async function provisionDevelopmentCredentials(\n session: OnboardingSession,\n project: DevelopmentProject,\n settings: Settings,\n framework: SupportedFrameworks | undefined,\n cwd: string = process.cwd()\n): Promise<void> {\n // Set exactly when the API client sends it in place of the sign-in.\n const usingApiKey = Boolean(settings.apiKey);\n let projectId: string;\n let projectName: string | undefined;\n if ('id' in project) {\n projectId = project.id;\n projectName = project.name;\n } else {\n const { orgId, name } = project.create;\n const { project: created } = await api\n .createProject(orgId, { name, defaultLocale: settings.defaultLocale })\n .catch(\n explainForbidden((error) =>\n projectCreationDeniedError(orgId, usingApiKey, error)\n )\n );\n logger.info(`Created ${created.name} (${created.id})`);\n session.step(`created project ${created.id}`);\n projectId = created.id;\n projectName = created.name;\n }\n const { apiKey } = await api\n .createProjectApiKey(projectId, {\n name: DEVELOPMENT_KEY_NAME,\n permissions: [ProjectApiKeyPermission['PROJECT:TRANSLATIONS:GENERATE']],\n })\n .catch(\n explainForbidden((error) =>\n keyCreationDeniedError(projectId, usingApiKey, error)\n )\n );\n session.step('created a development key');\n await setCredentials({ projectId, apiKey: apiKey.key }, framework, cwd);\n session.step('saved development credentials to .env.local');\n const projectLabel = projectName\n ? `${projectName} (${projectId})`\n : projectId;\n logger.success(\n `Created development key \"${apiKey.name}\" for project ${projectLabel} and saved both to ${chalk.cyan('.env.local')}.`\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,MAAM,uBAAuB;;AAG7B,SAAgB,6BAA6B,cAA8B;AACzE,Q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AAK,IAAI,QAAQ,GAAG,GAAG;AACtD,UAAQ,KAAK,mBAAmB,QAAQ,KAAK;AAC7C,cAAY,QAAQ;AACpB,gBAAc,QAAQ;;CAExB,MAAM,EAAE,WAAW,MAAM,IACtB,oBAAoB,WAAW;EAC9B,MAAM;EACN,aAAa,CAAC,wBAAwB,iCAAiC;EACxE,CAAC,CACD,MACC,kBAAkB,UAChB,uBAAuB,WAAW,aAAa,MAAM,CACtD,CACF;AACH,SAAQ,KAAK,4BAA4B;AACzC,OAAM,eAAe;EAAE;EAAW,QAAQ,OAAO;EAAK,EAAE,WAAW,IAAI;AACvE,SAAQ,KAAK,8CAA8C;CAC3D,MAAM,eAAe,cACjB,GAAG,YAAY,IAAI,UAAU,KAC7B;AACJ,QAAO,QACL,4BAA4B,OAAO,KAAK,gBAAgB,aAAa,qBAAqB,MAAM,KAAK,aAAa,CAAC,GACpH"}
1
+ {"version":3,"file":"developmentCredentials.js","names":[],"sources":["../../src/setup/developmentCredentials.ts"],"sourcesContent":["import path from 'node:path';\nimport chalk from 'chalk';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { ApiError } from 'generaltranslation/errors';\nimport { logger } from '../console/logger.js';\nimport { promptConfirm, promptSelect, promptText } from '../console/logging.js';\nimport type { Settings, SupportedFrameworks } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { setCredentials } from '../utils/credentials.js';\nimport { envFiles } from '../utils/loadEnv.js';\nimport { createUserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { OnboardingError, type OnboardingSession } from './onboarding.js';\n\nconst DEVELOPMENT_KEY_NAME = 'Development key (gt init)';\n\n/** .env.local never reaches production; the runtime key there is set on the host. */\nexport function productionRuntimeKeyGuidance(dashboardUrl: string): string {\n return `${chalk.dim('For runtime translation in production, create an API key in the dashboard')} ${chalk.cyan(dashboardUrl)} ${chalk.dim('and set GT_API_KEY and GT_PROJECT_ID in your hosting environment.')}`;\n}\n\n/**\n * Interactive setup keeps the browser login with its device fallback;\n * noninteractive setup always shows a device code (and emits it as a JSON\n * event) and waits for a person to approve it, without opening a browser.\n */\nexport async function signInForSetup(\n session: OnboardingSession,\n baseUrl: string | undefined\n): Promise<void> {\n try {\n await loginInteractively(baseUrl, session.interactive, (deviceCode) =>\n session.emit({ type: 'authorization_required', ...deviceCode })\n );\n } catch (error) {\n throw new OnboardingError(createUserAuthError('Sign in failed', error));\n }\n logger.message('You are now signed in.');\n}\n\ntype ProjectChoice = Awaited<ReturnType<typeof api.listProjects>>[number];\n\n/** An existing project, or the inputs for creating one. */\nexport type DevelopmentProject =\n | { id: string; name?: string }\n | { create: { orgId: string; name: string } };\n\nexport type DevelopmentProjectOptions = {\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n};\n\nfunction noAccessibleOrgError(dashboardUrl: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No accessible organizations were found',\n fix: `Create an organization in the dashboard ${dashboardUrl} or ask an admin for access, then rerun the setup wizard`,\n });\n}\n\n/**\n * The API client sends GT_API_KEY instead of the sign-in whenever it is set,\n * so signing in alone cannot fix a denial; GT_API_KEY has to go first.\n */\nfunction apiKeyDeniedGuidance(created: string, permission: string) {\n return {\n why: `GT_API_KEY is set, so setup used that key instead of your sign-in, and creating ${created} requires ${permission}`,\n fix: `Remove GT_API_KEY from your shell and from ${envFiles.join(', ')}, then rerun the setup wizard to sign in`,\n wayOut: `set GT_API_KEY to an organization key with ${permission}`,\n };\n}\n\nfunction projectCreationDeniedError(\n orgId: string,\n usingApiKey: boolean,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Project creation was denied for organization ${orgId}`,\n ...(usingApiKey\n ? apiKeyDeniedGuidance('a project', 'org:projects:create')\n : {\n why: 'listing an organization does not confirm permission to create projects in it',\n fix: 'Ask an organization admin for org:projects:create, or use credentials that have that permission for this organization',\n }),\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nfunction keyCreationDeniedError(\n projectId: string,\n usingApiKey: boolean,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Development key creation was denied for project ${projectId}`,\n ...(usingApiKey\n ? apiKeyDeniedGuidance('a key', 'project:api_keys:write')\n : {\n why: 'creating a key requires project:api_keys:write for this project',\n fix: 'Ask a project admin for project:api_keys:write, then rerun the setup wizard',\n }),\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\n/** Replaces a 403 with setup guidance; other failures keep their own error. */\nfunction explainForbidden(diagnostic: (error: unknown) => string) {\n return (error: unknown): never => {\n if (!(error instanceof ApiError) || error.code !== 403) throw error;\n throw new OnboardingError(diagnostic(error));\n };\n}\n\nconst noProjectChosenError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No project was chosen for the development credentials',\n reassurance: 'No project files were changed',\n fix: 'Rerun with --project-id <id> or --create-project, or skip them with --no-dev-credentials',\n});\n\nasync function resolveNewProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string\n): Promise<DevelopmentProject | undefined> {\n // Discovery lists accessible organizations, not creation permissions.\n // The API enforces creation permission when provisioning the project.\n const orgs = await api.listOrgs();\n if (orgs.length === 0) {\n throw new OnboardingError(noAccessibleOrgError(settings.dashboardUrl));\n }\n // The CLI has no other way to look up organization IDs, so a run that\n // needs --org-id lists the ones this account can use, one per line.\n const orgList = orgs.map((org) => `\\n - ${org.name} (${org.id})`).join('');\n if (options.orgId && !orgs.some((org) => org.id === options.orgId)) {\n session.reject(\n `--org-id ${options.orgId} is not an accessible organization; use one of:${orgList}`\n );\n }\n const orgId = await session.answer('--org-id', {\n explicit: options.orgId,\n // One organization is not a choice between options.\n configured: orgs.length === 1 ? orgs[0].id : undefined,\n hint: `Accessible organizations for --org-id:${orgList}`,\n ask: () =>\n promptSelect({\n message: 'Which organization should own the new project?',\n options: orgs.map((org) => ({ value: org.id, label: org.name })),\n }),\n });\n const name = await session.answer('--project-name', {\n explicit: options.projectName?.trim() || undefined,\n ask: async () =>\n (\n await promptText({\n message: 'What should the project be called?',\n defaultValue: path.basename(cwd),\n })\n ).trim() || path.basename(cwd),\n });\n return orgId && name ? { create: { orgId, name } } : undefined;\n}\n\n/**\n * Records project inputs a noninteractive run is missing, before signing in,\n * so it never waits for approval only to fail on a missing flag. --org-id is\n * the exception: whether it is needed depends on the account's organizations,\n * so its failure comes after sign-in and lists them.\n */\nexport function checkDevelopmentProjectInputs(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n /** Where settings.projectId came from, so a person can remove it. */\n projectIdSource: string\n): void {\n if (settings.projectId && options.createProject) {\n session.reject(\n `--create-project cannot be combined with project ${settings.projectId} from ${projectIdSource}; remove --create-project to keep using it, or remove the project ID from ${projectIdSource} to create a new project`\n );\n }\n if (settings.projectId || session.interactive) return;\n if (!options.createProject) {\n session.require('--project-id or --create-project');\n } else if (!options.projectName?.trim()) {\n session.require('--project-name');\n }\n}\n\n/**\n * Chooses the project for development credentials without creating anything:\n * a supplied or configured ID, explicit creation inputs, or (interactively)\n * a selection among the account's projects.\n */\nexport async function resolveDevelopmentProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string = process.cwd()\n): Promise<DevelopmentProject | undefined> {\n if (settings.projectId) return { id: settings.projectId };\n if (options.createProject) {\n return resolveNewProject(session, settings, options, cwd);\n }\n const projects = await api.listProjects();\n if (projects.length === 0) {\n // Creating a project is its own choice, separate from creating a key.\n const create = await session.answer('--project-id or --create-project', {\n ask: () =>\n promptConfirm({\n message: 'No projects found for your account. Create a new project?',\n defaultValue: true,\n }),\n });\n if (create === false) throw new OnboardingError(noProjectChosenError);\n return create\n ? resolveNewProject(session, settings, options, cwd)\n : undefined;\n }\n const choice = await session.answer<ProjectChoice | null>(\n '--project-id or --create-project',\n {\n ask: () =>\n promptSelect<ProjectChoice | null>({\n message: 'Which project should this app use?',\n options: [\n ...projects.map((project) => ({\n value: project,\n label: project.name,\n hint: project.orgName,\n })),\n { value: null, label: 'Create a new project' },\n ],\n }),\n }\n );\n if (choice === undefined) return undefined;\n return choice\n ? { id: choice.id, name: choice.name }\n : resolveNewProject(session, settings, options, cwd);\n}\n\n/**\n * Creates the chosen project if needed, mints a development key limited to\n * runtime translation, and saves both to .env.local. Callers inspect\n * .env.local first; the key is never printed.\n */\nexport async function provisionDevelopmentCredentials(\n session: OnboardingSession,\n project: DevelopmentProject,\n settings: Settings,\n framework: SupportedFrameworks | undefined,\n cwd: string = process.cwd()\n): Promise<void> {\n // Set exactly when the API client sends it in place of the sign-in.\n const usingApiKey = Boolean(settings.apiKey);\n let projectId: string;\n let projectName: string | undefined;\n if ('id' in project) {\n projectId = project.id;\n projectName = project.name;\n } else {\n const { orgId, name } = project.create;\n const { project: created } = await api\n .createProject(orgId, { name, defaultLocale: settings.defaultLocale })\n .catch(\n explainForbidden((error) =>\n projectCreationDeniedError(orgId, usingApiKey, error)\n )\n );\n logger.info(`Created ${created.name} (${created.id})`);\n session.step(`created project ${created.id}`);\n projectId = created.id;\n projectName = created.name;\n }\n const { apiKey } = await api\n .createProjectApiKey(projectId, {\n name: DEVELOPMENT_KEY_NAME,\n permissions: [ProjectApiKeyPermission['PROJECT:TRANSLATIONS:GENERATE']],\n })\n .catch(\n explainForbidden((error) =>\n keyCreationDeniedError(projectId, usingApiKey, error)\n )\n );\n session.step('created a development key');\n await setCredentials({ projectId, apiKey: apiKey.key }, framework, cwd);\n session.step('saved development credentials to .env.local');\n const projectLabel = projectName\n ? `${projectName} (${projectId})`\n : projectId;\n logger.success(\n `Created development key \"${apiKey.name}\" for project ${projectLabel} and saved both to ${chalk.cyan('.env.local')}.`\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,MAAM,uBAAuB;;AAG7B,SAAgB,6BAA6B,cAA8B;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,OAAO;GAAE;GAAM,eAAe,SAAS;GAAe,CAAC,CACrE,MACC,kBAAkB,UAChB,2BAA2B,OAAO,aAAa,MAAM,CACtD,CACF;AACH,SAAO,KAAK,WAAW,QAAQ,KAAK,IAAI,QAAQ,GAAG,GAAG;AACtD,UAAQ,KAAK,mBAAmB,QAAQ,KAAK;AAC7C,cAAY,QAAQ;AACpB,gBAAc,QAAQ;;CAExB,MAAM,EAAE,WAAW,MAAM,IACtB,oBAAoB,WAAW;EAC9B,MAAM;EACN,aAAa,CAAC,wBAAwB,iCAAiC;EACxE,CAAC,CACD,MACC,kBAAkB,UAChB,uBAAuB,WAAW,aAAa,MAAM,CACtD,CACF;AACH,SAAQ,KAAK,4BAA4B;AACzC,OAAM,eAAe;EAAE;EAAW,QAAQ,OAAO;EAAK,EAAE,WAAW,IAAI;AACvE,SAAQ,KAAK,8CAA8C;CAC3D,MAAM,eAAe,cACjB,GAAG,YAAY,IAAI,UAAU,KAC7B;AACJ,QAAO,QACL,4BAA4B,OAAO,KAAK,gBAAgB,aAAa,qBAAqB,MAAM,KAAK,aAAa,CAAC,GACpH"}
@@ -81,6 +81,8 @@ export declare class OnboardingSession {
81
81
  readonly humanActions: string[];
82
82
  private readonly missing;
83
83
  private readonly invalid;
84
+ /** Accepted values for missing options, printed with the failure. */
85
+ private readonly hints;
84
86
  private reported;
85
87
  constructor(command: string, options: Pick<ConfigureOptions, 'json' | 'interactive'>);
86
88
  /**
@@ -88,14 +90,16 @@ export declare class OnboardingSession {
88
90
  * defaults were accepted, then a prompt. Noninteractive runs use the
89
91
  * fallback of an optional question, or record the option as missing.
90
92
  */
91
- answer<T>(option: string, { explicit, configured, recommended, fallback, ask, }: {
93
+ answer<T>(option: string, { explicit, configured, recommended, fallback, hint, ask, }: {
92
94
  explicit?: T;
93
95
  configured?: T;
94
96
  recommended?: T;
95
97
  fallback?: T;
98
+ /** The values the option accepts, when they are not discoverable. */
99
+ hint?: string;
96
100
  ask: () => Promise<T>;
97
101
  }): Promise<T | undefined>;
98
- require(option: string): void;
102
+ require(option: string, hint?: string): void;
99
103
  reject(problem: string): void;
100
104
  /** Stops before any change when an answer is missing or invalid. */
101
105
  assertResolved(): void;
@@ -84,6 +84,8 @@ var OnboardingSession = class {
84
84
  humanActions = [];
85
85
  missing = /* @__PURE__ */ new Set();
86
86
  invalid = [];
87
+ /** Accepted values for missing options, printed with the failure. */
88
+ hints = [];
87
89
  reported = false;
88
90
  constructor(command, options) {
89
91
  this.command = command;
@@ -95,16 +97,17 @@ var OnboardingSession = class {
95
97
  * defaults were accepted, then a prompt. Noninteractive runs use the
96
98
  * fallback of an optional question, or record the option as missing.
97
99
  */
98
- async answer(option, { explicit, configured, recommended, fallback, ask }) {
100
+ async answer(option, { explicit, configured, recommended, fallback, hint, ask }) {
99
101
  if (explicit !== void 0) return explicit;
100
102
  if (configured !== void 0) return configured;
101
103
  if (this.defaults && recommended !== void 0) return recommended;
102
104
  if (this.interactive) return ask();
103
105
  if (fallback !== void 0) return fallback;
104
- this.require(option);
106
+ this.require(option, hint);
105
107
  }
106
- require(option) {
108
+ require(option, hint) {
107
109
  this.missing.add(option);
110
+ if (hint) this.hints.push(hint);
108
111
  }
109
112
  reject(problem) {
110
113
  this.invalid.push(problem);
@@ -118,7 +121,7 @@ var OnboardingSession = class {
118
121
  severity: "Error",
119
122
  whatHappened: missingOptions.length > 0 ? `Setup needs these options: ${missingOptions.join(", ")}` : "Setup received invalid options",
120
123
  reassurance: "No project files were changed",
121
- details: this.invalid,
124
+ details: [...this.invalid, ...this.hints],
122
125
  fix: this.defaults ? "Pass the options (see --help), or rerun in an interactive terminal" : "Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal"
123
126
  }), missingOptions);
124
127
  }
@@ -230,6 +233,7 @@ function describeDefaults(framework) {
230
233
  const buildTool = getBuildToolSetup(framework?.name);
231
234
  const translationsDir = buildTool?.defaultTranslationsDir ?? "./public/_gt";
232
235
  if (framework?.type !== "react") return `Files saved locally in ${translationsDir}`;
236
+ if (framework.name === "next-pages") return `${getFrameworkDisplayName(framework)}, no app changes (follow the Pages Router quickstart)`;
233
237
  return `${getReactFrameworkLibrary(framework)} & ${buildTool?.initializer ?? "GTProvider"}, ${getFrameworkDisplayName(framework)}, Files saved locally in ${translationsDir}`;
234
238
  }
235
239
  /** Setup patterns name where each locale's files live, so they need [locale]. */
@@ -1 +1 @@
1
- {"version":3,"file":"onboarding.js","names":[],"sources":["../../src/setup/onboarding.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { Command, Option, type CommanderError } from 'commander';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport findFilepath from '../fs/findFilepath.js';\nimport { withJsonExtension } from '../fs/config/loadConfig.js';\nimport { logger } from '../console/logger.js';\nimport {\n displayHeader,\n getLastExitError,\n logErrorAndExit,\n stripAnsi,\n} from '../console/logging.js';\nimport {\n SUPPORTED_REACT_FRAMEWORKS,\n type FrameworkObject,\n type SupportedReactFrameworks,\n} from '../types/index.js';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport {\n SETUP_FILE_FORMATS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n getPackageManager,\n NoPackageManagerError,\n packageManagers,\n type PackageManager,\n} from '../utils/packageManager.js';\nimport { installPackage } from '../utils/installPackage.js';\n\n/** Answers accepted by `gt configure` (and the gt-vue `gt init`). */\nexport type ConfigureOptions = {\n config: string;\n src?: string[];\n interactive?: boolean;\n json?: boolean;\n defaults?: boolean;\n defaultLocale?: string;\n locales?: string[];\n storage?: 'local' | 'cdn';\n translationsDir?: string;\n fileFormats?: Array<SetupFileFormat | 'none'>;\n filePatterns?: string[];\n liveTranslations?: boolean;\n devCredentials?: boolean;\n projectId?: string;\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n packageManager?: string;\n};\n\n/** Answers accepted by the React-aware `gt init`. */\nexport type InitOptions = ConfigureOptions & {\n locadex?: boolean;\n reactSetup?: boolean;\n framework?: SupportedReactFrameworks;\n format?: boolean;\n};\n\n/** Flags for every configuration question; values prefill interactive runs. */\nexport function attachConfigureFlags(\n command: Command,\n sourceHelp: string\n): Command {\n return reportJsonArgumentErrors(command)\n .option('--src <paths...>', sourceHelp)\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option(\n '--no-interactive',\n 'Never prompt; fail listing the options still needed. Automatic when stdin or stdout is not a terminal'\n )\n .option(\n '--json',\n 'Write JSON events (sign-in, handoff, result) to stdout and all other output to stderr; implies --no-interactive'\n )\n .option(\n '--defaults',\n 'Accept the recommended value for every local choice that no flag or gt.config.json answers; never creates projects or keys'\n )\n .option('--no-defaults', 'Do not offer the recommended defaults')\n .option('--default-locale <locale>', 'Default locale, e.g. en')\n .option(\n '--locales <locales...>',\n 'Locales to translate into, e.g. fr es; replaces the configured list'\n )\n .addOption(\n new Option(\n '--storage <storage>',\n 'Where GT translations are stored for GT runtimes'\n ).choices(['local', 'cdn'])\n )\n .option(\n '--translations-dir <path>',\n 'Directory for local GT translation files'\n )\n .addOption(\n new Option(\n '--file-formats <formats...>',\n 'Additional file formats to translate, or none'\n ).choices([...SETUP_FILE_FORMATS, 'none'])\n )\n .option(\n '--file-patterns <patterns...>',\n 'Glob patterns as <format>=<glob> including [locale], e.g. json=./locales/[locale]/*.json; selects the format'\n )\n .option(\n '--live-translations',\n 'Local Vite storage: set up live development translations (creates a development key)'\n )\n .option('--no-live-translations', 'Skip live development translations')\n .addOption(\n new Option(\n '--dev-credentials',\n 'Save a project ID and a new development key to .env.local'\n ).conflicts('liveTranslations')\n )\n .option('--no-dev-credentials', 'Do not create development credentials')\n .option(\n '--project-id <id>',\n 'Existing project for the development credentials'\n )\n .option(\n '--create-project',\n 'Create a new project for the development credentials'\n )\n .option('--org-id <id>', 'Organization that owns --create-project')\n .option('--project-name <name>', 'Name for --create-project')\n .addOption(\n new Option(\n '--package-manager <id>',\n 'Package manager for installs when it cannot be detected'\n ).choices(packageManagers.map((packageManager) => packageManager.id))\n );\n}\n\nlet commandBeforeOnboarding: string | undefined;\n\nfunction reportExitBeforeOnboarding(code: number): void {\n if (code === 0 || commandBeforeOnboarding === undefined) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: commandBeforeOnboarding,\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it started; see stderr'\n ),\n } satisfies OnboardingEvent)}\\n`\n );\n}\n\n/**\n * Pre-action hooks, such as the monorepo version check, can exit before\n * runOnboarding installs its own result reporting; `--json` callers still\n * get a result. runOnboarding takes over once it starts.\n */\nexport function reportJsonExitsBeforeOnboarding(command: string): void {\n commandBeforeOnboarding = command;\n process.once('exit', reportExitBeforeOnboarding);\n}\n\n/**\n * Argument errors happen before the action runs, so `--json` callers would\n * otherwise get no result. Commander prints the error to stderr, then calls\n * this exit hook; returning lets it exit with the same code as before. The\n * hook replaces an exit override inherited from the program.\n */\nfunction reportJsonArgumentErrors(command: Command): Command {\n return command.exitOverride((error: CommanderError) => {\n if (error.exitCode === 0) return; // help and version output\n // An option after the failing argument is not parsed yet.\n const json =\n command.opts().json === true || process.argv.includes('--json');\n if (!json) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: command.name(),\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(error.message),\n } satisfies OnboardingEvent)}\\n`\n );\n });\n}\n\n/** Configuration flags plus the React application setup and Locadex choices. */\nexport function attachInitFlags(command: Command, sourceHelp: string) {\n return attachConfigureFlags(command, sourceHelp)\n .option(\n '--locadex',\n 'Mintlify and Next.js App Router: hand setup to the Locadex AI agent through GitHub instead'\n )\n .option('--no-locadex', 'Set up this project locally')\n .option(\n '--react-setup',\n 'React projects: install the GT library and add GTProvider or initializeGTSPA'\n )\n .option('--no-react-setup', 'Do not modify application source')\n .addOption(\n new Option(\n '--framework <framework>',\n 'React framework for --react-setup; overrides detection'\n ).choices(SUPPORTED_REACT_FRAMEWORKS)\n )\n .option(\n '--format',\n 'Next.js App Router: format files changed by setup with the detected formatter'\n )\n .option('--no-format', 'Leave files changed by setup unformatted');\n}\n\nexport type OnboardingEvent =\n | {\n type: 'authorization_required';\n verificationUri: string;\n verificationUriComplete?: string;\n userCode: string;\n }\n | { type: 'handoff'; url: string; reason: 'locadex' }\n | {\n type: 'result';\n command: string;\n outcome: 'success' | 'needs_human_action' | 'failed';\n completedSteps: string[];\n url?: string;\n /** Manual steps setup could not do, for needs_human_action. */\n actions?: string[];\n /** What to do next once setup succeeded, e.g. marking content for translation. */\n nextSteps?: string[];\n missingOptions?: string[];\n error?: string;\n };\n\n/** Needs-input and validation failures, raised before setup changes files. */\nexport class OnboardingError extends Error {\n constructor(\n message: string,\n readonly missingOptions: string[] = []\n ) {\n super(message);\n this.name = 'OnboardingError';\n }\n}\n\nfunction isInteractiveTerminal(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\n/**\n * One setup run: how unanswered questions are resolved, which options are\n * still missing, and which steps already changed the project.\n */\nexport class OnboardingSession {\n readonly interactive: boolean;\n readonly json: boolean;\n defaults = false;\n readonly completedSteps: string[] = [];\n /** Manual steps left for a person; they make the outcome needs_human_action. */\n readonly humanActions: string[] = [];\n private readonly missing = new Set<string>();\n private readonly invalid: string[] = [];\n private reported = false;\n\n constructor(\n readonly command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>\n ) {\n this.json = options.json === true;\n this.interactive =\n options.interactive !== false && !this.json && isInteractiveTerminal();\n }\n\n /**\n * Explicit flag, then existing config, then the recommended value when\n * defaults were accepted, then a prompt. Noninteractive runs use the\n * fallback of an optional question, or record the option as missing.\n */\n async answer<T>(\n option: string,\n {\n explicit,\n configured,\n recommended,\n fallback,\n ask,\n }: {\n explicit?: T;\n configured?: T;\n recommended?: T;\n fallback?: T;\n ask: () => Promise<T>;\n }\n ): Promise<T | undefined> {\n if (explicit !== undefined) return explicit;\n if (configured !== undefined) return configured;\n if (this.defaults && recommended !== undefined) return recommended;\n if (this.interactive) return ask();\n if (fallback !== undefined) return fallback;\n this.require(option);\n return undefined;\n }\n\n require(option: string): void {\n this.missing.add(option);\n }\n\n reject(problem: string): void {\n this.invalid.push(problem);\n }\n\n /** Stops before any change when an answer is missing or invalid. */\n assertResolved(): void {\n if (this.missing.size === 0 && this.invalid.length === 0) return;\n const missingOptions = [...this.missing];\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened:\n missingOptions.length > 0\n ? `Setup needs these options: ${missingOptions.join(', ')}`\n : 'Setup received invalid options',\n reassurance: 'No project files were changed',\n details: this.invalid,\n fix: this.defaults\n ? 'Pass the options (see --help), or rerun in an interactive terminal'\n : 'Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal',\n }),\n missingOptions\n );\n }\n\n step(name: string): void {\n this.completedSteps.push(name);\n }\n\n emit(event: OnboardingEvent): void {\n if (!this.json) return;\n if (event.type === 'result') this.reported = true;\n // Synchronous so events survive an immediate process.exit.\n fs.writeSync(process.stdout.fd, `${JSON.stringify(event)}\\n`);\n }\n\n /** A result for exits that bypass runOnboarding (e.g. settings validation). */\n reportUnexpectedExit(code: number): void {\n if (this.reported || code === 0) return;\n this.emit({\n type: 'result',\n command: this.command,\n outcome: 'failed',\n completedSteps: this.completedSteps,\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it finished; see stderr'\n ),\n });\n }\n}\n\nexport type OnboardingOutcome =\n | { outcome: 'success'; nextSteps?: string[] }\n | { outcome: 'needs_human_action'; url: string };\n\nfunction partialSetupWarning(session: OnboardingSession): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Setup stopped after these steps: ${session.completedSteps.join(', ')}`,\n why: 'the error below happened before the remaining steps ran',\n fix: `Review those changes, fix the error, then rerun \\`gt ${session.command}\\`; it reuses the saved configuration and credentials`,\n });\n}\n\n/**\n * Runs one setup command: selects prompt and output modes, then reports the\n * outcome. Failures exit nonzero with the steps that already ran.\n */\nexport async function runOnboarding(\n command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>,\n run: (session: OnboardingSession) => Promise<OnboardingOutcome>\n): Promise<void> {\n commandBeforeOnboarding = undefined;\n process.removeListener('exit', reportExitBeforeOnboarding);\n const session = new OnboardingSession(command, options);\n if (session.json) logger.setConsoleOutput('stderr');\n // Per-run modes; console routing is reset per command by BaseCLI.\n const progressWasAnimated = logger.setAnimatedProgress(session.interactive);\n const reportExit = (code: number) => session.reportUnexpectedExit(code);\n process.once('exit', reportExit);\n try {\n const result = await run(session);\n const needsHuman =\n result.outcome === 'needs_human_action' ||\n session.humanActions.length > 0;\n session.emit({\n type: 'result',\n command,\n outcome: needsHuman ? 'needs_human_action' : 'success',\n completedSteps: session.completedSteps,\n ...(result.outcome === 'needs_human_action' && { url: result.url }),\n ...(session.humanActions.length > 0 && {\n actions: session.humanActions,\n }),\n ...(result.outcome === 'success' &&\n result.nextSteps !== undefined &&\n result.nextSteps.length > 0 && { nextSteps: result.nextSteps }),\n });\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : (formatDiagnosticErrorDetails(error) ?? 'Setup failed');\n session.emit({\n type: 'result',\n command,\n outcome: 'failed',\n completedSteps: session.completedSteps,\n error: stripAnsi(message),\n ...(error instanceof OnboardingError &&\n error.missingOptions.length > 0 && {\n missingOptions: error.missingOptions,\n }),\n });\n if (session.completedSteps.length > 0) {\n logger.warn(partialSetupWarning(session));\n }\n return logErrorAndExit(message);\n } finally {\n process.removeListener('exit', reportExit);\n logger.setAnimatedProgress(progressWasAnimated);\n }\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Reads the setup config, failing before any change when it is unusable. */\nexport function readSetupConfig(\n configFilepath: string\n): Record<string, unknown> {\n if (!fs.existsSync(configFilepath)) return {};\n try {\n const config = asRecord(\n JSON.parse(fs.readFileSync(configFilepath, 'utf8'))\n );\n if (config) return config;\n throw new Error('the file does not contain a JSON object');\n } catch (error) {\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `${configFilepath} is not a valid JSON config`,\n reassurance: 'No project files were changed',\n details: formatDiagnosticErrorDetails(error),\n fix: 'Fix or remove the file, then rerun the command',\n })\n );\n }\n}\n\nexport const INIT_SOURCE_HELP =\n \"Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'\";\n\nexport function setupConfigPath(\n options: Pick<ConfigureOptions, 'config'>\n): string {\n return options.config ? withJsonExtension(options.config) : 'gt.config.json';\n}\n\nexport function getConfiguredFramework(\n config: Record<string, unknown>\n): SupportedReactFrameworks | 'mintlify' | undefined {\n const framework = config.framework;\n return typeof framework === 'string' &&\n [...SUPPORTED_REACT_FRAMEWORKS, 'mintlify'].includes(\n framework as SupportedReactFrameworks\n )\n ? (framework as SupportedReactFrameworks | 'mintlify')\n : undefined;\n}\n\n/** JSON mode keeps the banner off stdout. */\nexport function displaySetupHeader(\n session: OnboardingSession,\n message: string\n) {\n if (session.json) logger.startCommand(message);\n else displayHeader(message);\n}\n\nexport function describeDefaults(\n framework: FrameworkObject | undefined\n): string {\n const buildTool = getBuildToolSetup(framework?.name);\n const translationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n if (framework?.type !== 'react') {\n return `Files saved locally in ${translationsDir}`;\n }\n const library = getReactFrameworkLibrary(framework);\n const setup = buildTool?.initializer ?? 'GTProvider';\n return `${library} & ${setup}, ${getFrameworkDisplayName(framework)}, Files saved locally in ${translationsDir}`;\n}\n\n/** Setup patterns name where each locale's files live, so they need [locale]. */\nexport function validateSetupPattern(pattern: string): true | string {\n return (\n pattern.includes('[locale]') ||\n `\"${pattern}\" must include [locale], e.g. ./locales/[locale]/*.json`\n );\n}\n\n/** Parses `--file-patterns <format>=<glob>` values, grouped by format. */\nexport function parseFilePatterns(\n session: OnboardingSession,\n values: string[] = []\n): Map<SetupFileFormat, string[]> {\n const patterns = new Map<SetupFileFormat, string[]>();\n for (const value of values) {\n const separator = value.indexOf('=');\n const format = value.slice(0, separator) as SetupFileFormat;\n const pattern = value.slice(separator + 1).trim();\n if (separator < 0 || !SETUP_FILE_FORMATS.includes(format) || !pattern) {\n session.reject(\n `--file-patterns \"${value}\" must look like <format>=<glob> with a format of ${SETUP_FILE_FORMATS.join(', ')}`\n );\n continue;\n }\n const problem = validateSetupPattern(pattern);\n if (problem !== true) {\n session.reject(`--file-patterns \"${value}\": ${problem}`);\n continue;\n }\n patterns.set(format, [...(patterns.get(format) ?? []), pattern]);\n }\n return patterns;\n}\n\n/** Detects the package manager, or asks only when prompts are allowed. */\nexport async function resolvePackageManager(\n session: OnboardingSession,\n specified?: string\n): Promise<PackageManager | undefined> {\n try {\n return await getPackageManager(\n process.cwd(),\n specified,\n !session.interactive\n );\n } catch (error) {\n if (!(error instanceof NoPackageManagerError)) throw error;\n session.require('--package-manager');\n return undefined;\n }\n}\n\nexport async function installWithProgress(\n session: OnboardingSession,\n packageName: string,\n packageManager: PackageManager,\n asDevDependency: boolean\n): Promise<void> {\n const spinner = logger.createSpinner('timer');\n spinner.start(\n `Installing ${packageName}${asDevDependency ? ' as a dev dependency' : ''} with ${packageManager.name}...`\n );\n try {\n await installPackage(packageName, packageManager, asDevDependency);\n } catch (error) {\n spinner.stop(`Could not install ${packageName}.`, 2);\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Failed to install ${packageName}`,\n details: formatDiagnosticErrorDetails(error),\n fix: `Install it with \\`${packageManager.name} ${packageManager.installCommand} ${packageName}\\`, then rerun the command`,\n })\n );\n }\n spinner.stop(`Installed ${packageName}.`);\n session.step(`installed ${packageName}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqEA,SAAgB,qBACd,SACA,YACS;AACT,QAAO,yBAAyB,QAAQ,CACrC,OAAO,oBAAoB,WAAW,CACtC,OACC,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACA,OACC,oBACA,wGACD,CACA,OACC,UACA,kHACD,CACA,OACC,cACA,6HACD,CACA,OAAO,iBAAiB,wCAAwC,CAChE,OAAO,6BAA6B,0BAA0B,CAC9D,OACC,0BACA,sEACD,CACA,UACC,IAAI,OACF,uBACA,mDACD,CAAC,QAAQ,CAAC,SAAS,MAAM,CAAC,CAC5B,CACA,OACC,6BACA,2CACD,CACA,UACC,IAAI,OACF,+BACA,gDACD,CAAC,QAAQ,CAAC,GAAG,oBAAoB,OAAO,CAAC,CAC3C,CACA,OACC,iCACA,+GACD,CACA,OACC,uBACA,uFACD,CACA,OAAO,0BAA0B,qCAAqC,CACtE,UACC,IAAI,OACF,qBACA,4DACD,CAAC,UAAU,mBAAmB,CAChC,CACA,OAAO,wBAAwB,wCAAwC,CACvE,OACC,qBACA,mDACD,CACA,OACC,oBACA,uDACD,CACA,OAAO,iBAAiB,0CAA0C,CAClE,OAAO,yBAAyB,4BAA4B,CAC5D,UACC,IAAI,OACF,0BACA,0DACD,CAAC,QAAQ,gBAAgB,KAAK,mBAAmB,eAAe,GAAG,CAAC,CACtE;;AAGL,IAAI;AAEJ,SAAS,2BAA2B,MAAoB;AACtD,KAAI,SAAS,KAAK,4BAA4B,KAAA,EAAW;AACzD,IAAG,UACD,QAAQ,OAAO,IACf,GAAG,KAAK,UAAU;EAChB,MAAM;EACN,SAAS;EACT,SAAS;EACT,gBAAgB,EAAE;EAClB,OAAO,UACL,kBAAkB,IAAI,6CACvB;EACF,CAA2B,CAAC,IAC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Aa,cAAc"}
1
+ {"version":3,"file":"onboarding.js","names":[],"sources":["../../src/setup/onboarding.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { Command, Option, type CommanderError } from 'commander';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport findFilepath from '../fs/findFilepath.js';\nimport { withJsonExtension } from '../fs/config/loadConfig.js';\nimport { logger } from '../console/logger.js';\nimport {\n displayHeader,\n getLastExitError,\n logErrorAndExit,\n stripAnsi,\n} from '../console/logging.js';\nimport {\n SUPPORTED_REACT_FRAMEWORKS,\n type FrameworkObject,\n type SupportedReactFrameworks,\n} from '../types/index.js';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport {\n SETUP_FILE_FORMATS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n getPackageManager,\n NoPackageManagerError,\n packageManagers,\n type PackageManager,\n} from '../utils/packageManager.js';\nimport { installPackage } from '../utils/installPackage.js';\n\n/** Answers accepted by `gt configure` (and the gt-vue `gt init`). */\nexport type ConfigureOptions = {\n config: string;\n src?: string[];\n interactive?: boolean;\n json?: boolean;\n defaults?: boolean;\n defaultLocale?: string;\n locales?: string[];\n storage?: 'local' | 'cdn';\n translationsDir?: string;\n fileFormats?: Array<SetupFileFormat | 'none'>;\n filePatterns?: string[];\n liveTranslations?: boolean;\n devCredentials?: boolean;\n projectId?: string;\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n packageManager?: string;\n};\n\n/** Answers accepted by the React-aware `gt init`. */\nexport type InitOptions = ConfigureOptions & {\n locadex?: boolean;\n reactSetup?: boolean;\n framework?: SupportedReactFrameworks;\n format?: boolean;\n};\n\n/** Flags for every configuration question; values prefill interactive runs. */\nexport function attachConfigureFlags(\n command: Command,\n sourceHelp: string\n): Command {\n return reportJsonArgumentErrors(command)\n .option('--src <paths...>', sourceHelp)\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option(\n '--no-interactive',\n 'Never prompt; fail listing the options still needed. Automatic when stdin or stdout is not a terminal'\n )\n .option(\n '--json',\n 'Write JSON events (sign-in, handoff, result) to stdout and all other output to stderr; implies --no-interactive'\n )\n .option(\n '--defaults',\n 'Accept the recommended value for every local choice that no flag or gt.config.json answers; never creates projects or keys'\n )\n .option('--no-defaults', 'Do not offer the recommended defaults')\n .option('--default-locale <locale>', 'Default locale, e.g. en')\n .option(\n '--locales <locales...>',\n 'Locales to translate into, e.g. fr es; replaces the configured list'\n )\n .addOption(\n new Option(\n '--storage <storage>',\n 'Where GT translations are stored for GT runtimes'\n ).choices(['local', 'cdn'])\n )\n .option(\n '--translations-dir <path>',\n 'Directory for local GT translation files'\n )\n .addOption(\n new Option(\n '--file-formats <formats...>',\n 'Additional file formats to translate, or none'\n ).choices([...SETUP_FILE_FORMATS, 'none'])\n )\n .option(\n '--file-patterns <patterns...>',\n 'Glob patterns as <format>=<glob> including [locale], e.g. json=./locales/[locale]/*.json; selects the format'\n )\n .option(\n '--live-translations',\n 'Local Vite storage: set up live development translations (creates a development key)'\n )\n .option('--no-live-translations', 'Skip live development translations')\n .addOption(\n new Option(\n '--dev-credentials',\n 'Save a project ID and a new development key to .env.local'\n ).conflicts('liveTranslations')\n )\n .option('--no-dev-credentials', 'Do not create development credentials')\n .option(\n '--project-id <id>',\n 'Existing project for the development credentials'\n )\n .option(\n '--create-project',\n 'Create a new project for the development credentials'\n )\n .option('--org-id <id>', 'Organization that owns --create-project')\n .option('--project-name <name>', 'Name for --create-project')\n .addOption(\n new Option(\n '--package-manager <id>',\n 'Package manager for installs when it cannot be detected'\n ).choices(packageManagers.map((packageManager) => packageManager.id))\n );\n}\n\nlet commandBeforeOnboarding: string | undefined;\n\nfunction reportExitBeforeOnboarding(code: number): void {\n if (code === 0 || commandBeforeOnboarding === undefined) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: commandBeforeOnboarding,\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it started; see stderr'\n ),\n } satisfies OnboardingEvent)}\\n`\n );\n}\n\n/**\n * Pre-action hooks, such as the monorepo version check, can exit before\n * runOnboarding installs its own result reporting; `--json` callers still\n * get a result. runOnboarding takes over once it starts.\n */\nexport function reportJsonExitsBeforeOnboarding(command: string): void {\n commandBeforeOnboarding = command;\n process.once('exit', reportExitBeforeOnboarding);\n}\n\n/**\n * Argument errors happen before the action runs, so `--json` callers would\n * otherwise get no result. Commander prints the error to stderr, then calls\n * this exit hook; returning lets it exit with the same code as before. The\n * hook replaces an exit override inherited from the program.\n */\nfunction reportJsonArgumentErrors(command: Command): Command {\n return command.exitOverride((error: CommanderError) => {\n if (error.exitCode === 0) return; // help and version output\n // An option after the failing argument is not parsed yet.\n const json =\n command.opts().json === true || process.argv.includes('--json');\n if (!json) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: command.name(),\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(error.message),\n } satisfies OnboardingEvent)}\\n`\n );\n });\n}\n\n/** Configuration flags plus the React application setup and Locadex choices. */\nexport function attachInitFlags(command: Command, sourceHelp: string) {\n return attachConfigureFlags(command, sourceHelp)\n .option(\n '--locadex',\n 'Mintlify and Next.js App Router: hand setup to the Locadex AI agent through GitHub instead'\n )\n .option('--no-locadex', 'Set up this project locally')\n .option(\n '--react-setup',\n 'React projects: install the GT library and add GTProvider or initializeGTSPA'\n )\n .option('--no-react-setup', 'Do not modify application source')\n .addOption(\n new Option(\n '--framework <framework>',\n 'React framework for --react-setup; overrides detection'\n ).choices(SUPPORTED_REACT_FRAMEWORKS)\n )\n .option(\n '--format',\n 'Next.js App Router: format files changed by setup with the detected formatter'\n )\n .option('--no-format', 'Leave files changed by setup unformatted');\n}\n\nexport type OnboardingEvent =\n | {\n type: 'authorization_required';\n verificationUri: string;\n verificationUriComplete?: string;\n userCode: string;\n }\n | { type: 'handoff'; url: string; reason: 'locadex' }\n | {\n type: 'result';\n command: string;\n outcome: 'success' | 'needs_human_action' | 'failed';\n completedSteps: string[];\n url?: string;\n /** Manual steps setup could not do, for needs_human_action. */\n actions?: string[];\n /** What to do next once setup succeeded, e.g. marking content for translation. */\n nextSteps?: string[];\n missingOptions?: string[];\n error?: string;\n };\n\n/** Needs-input and validation failures, raised before setup changes files. */\nexport class OnboardingError extends Error {\n constructor(\n message: string,\n readonly missingOptions: string[] = []\n ) {\n super(message);\n this.name = 'OnboardingError';\n }\n}\n\nfunction isInteractiveTerminal(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\n/**\n * One setup run: how unanswered questions are resolved, which options are\n * still missing, and which steps already changed the project.\n */\nexport class OnboardingSession {\n readonly interactive: boolean;\n readonly json: boolean;\n defaults = false;\n readonly completedSteps: string[] = [];\n /** Manual steps left for a person; they make the outcome needs_human_action. */\n readonly humanActions: string[] = [];\n private readonly missing = new Set<string>();\n private readonly invalid: string[] = [];\n /** Accepted values for missing options, printed with the failure. */\n private readonly hints: string[] = [];\n private reported = false;\n\n constructor(\n readonly command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>\n ) {\n this.json = options.json === true;\n this.interactive =\n options.interactive !== false && !this.json && isInteractiveTerminal();\n }\n\n /**\n * Explicit flag, then existing config, then the recommended value when\n * defaults were accepted, then a prompt. Noninteractive runs use the\n * fallback of an optional question, or record the option as missing.\n */\n async answer<T>(\n option: string,\n {\n explicit,\n configured,\n recommended,\n fallback,\n hint,\n ask,\n }: {\n explicit?: T;\n configured?: T;\n recommended?: T;\n fallback?: T;\n /** The values the option accepts, when they are not discoverable. */\n hint?: string;\n ask: () => Promise<T>;\n }\n ): Promise<T | undefined> {\n if (explicit !== undefined) return explicit;\n if (configured !== undefined) return configured;\n if (this.defaults && recommended !== undefined) return recommended;\n if (this.interactive) return ask();\n if (fallback !== undefined) return fallback;\n this.require(option, hint);\n return undefined;\n }\n\n require(option: string, hint?: string): void {\n this.missing.add(option);\n if (hint) this.hints.push(hint);\n }\n\n reject(problem: string): void {\n this.invalid.push(problem);\n }\n\n /** Stops before any change when an answer is missing or invalid. */\n assertResolved(): void {\n if (this.missing.size === 0 && this.invalid.length === 0) return;\n const missingOptions = [...this.missing];\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened:\n missingOptions.length > 0\n ? `Setup needs these options: ${missingOptions.join(', ')}`\n : 'Setup received invalid options',\n reassurance: 'No project files were changed',\n details: [...this.invalid, ...this.hints],\n fix: this.defaults\n ? 'Pass the options (see --help), or rerun in an interactive terminal'\n : 'Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal',\n }),\n missingOptions\n );\n }\n\n step(name: string): void {\n this.completedSteps.push(name);\n }\n\n emit(event: OnboardingEvent): void {\n if (!this.json) return;\n if (event.type === 'result') this.reported = true;\n // Synchronous so events survive an immediate process.exit.\n fs.writeSync(process.stdout.fd, `${JSON.stringify(event)}\\n`);\n }\n\n /** A result for exits that bypass runOnboarding (e.g. settings validation). */\n reportUnexpectedExit(code: number): void {\n if (this.reported || code === 0) return;\n this.emit({\n type: 'result',\n command: this.command,\n outcome: 'failed',\n completedSteps: this.completedSteps,\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it finished; see stderr'\n ),\n });\n }\n}\n\nexport type OnboardingOutcome =\n | { outcome: 'success'; nextSteps?: string[] }\n | { outcome: 'needs_human_action'; url: string };\n\nfunction partialSetupWarning(session: OnboardingSession): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Setup stopped after these steps: ${session.completedSteps.join(', ')}`,\n why: 'the error below happened before the remaining steps ran',\n fix: `Review those changes, fix the error, then rerun \\`gt ${session.command}\\`; it reuses the saved configuration and credentials`,\n });\n}\n\n/**\n * Runs one setup command: selects prompt and output modes, then reports the\n * outcome. Failures exit nonzero with the steps that already ran.\n */\nexport async function runOnboarding(\n command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>,\n run: (session: OnboardingSession) => Promise<OnboardingOutcome>\n): Promise<void> {\n commandBeforeOnboarding = undefined;\n process.removeListener('exit', reportExitBeforeOnboarding);\n const session = new OnboardingSession(command, options);\n if (session.json) logger.setConsoleOutput('stderr');\n // Per-run modes; console routing is reset per command by BaseCLI.\n const progressWasAnimated = logger.setAnimatedProgress(session.interactive);\n const reportExit = (code: number) => session.reportUnexpectedExit(code);\n process.once('exit', reportExit);\n try {\n const result = await run(session);\n const needsHuman =\n result.outcome === 'needs_human_action' ||\n session.humanActions.length > 0;\n session.emit({\n type: 'result',\n command,\n outcome: needsHuman ? 'needs_human_action' : 'success',\n completedSteps: session.completedSteps,\n ...(result.outcome === 'needs_human_action' && { url: result.url }),\n ...(session.humanActions.length > 0 && {\n actions: session.humanActions,\n }),\n ...(result.outcome === 'success' &&\n result.nextSteps !== undefined &&\n result.nextSteps.length > 0 && { nextSteps: result.nextSteps }),\n });\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : (formatDiagnosticErrorDetails(error) ?? 'Setup failed');\n session.emit({\n type: 'result',\n command,\n outcome: 'failed',\n completedSteps: session.completedSteps,\n error: stripAnsi(message),\n ...(error instanceof OnboardingError &&\n error.missingOptions.length > 0 && {\n missingOptions: error.missingOptions,\n }),\n });\n if (session.completedSteps.length > 0) {\n logger.warn(partialSetupWarning(session));\n }\n return logErrorAndExit(message);\n } finally {\n process.removeListener('exit', reportExit);\n logger.setAnimatedProgress(progressWasAnimated);\n }\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Reads the setup config, failing before any change when it is unusable. */\nexport function readSetupConfig(\n configFilepath: string\n): Record<string, unknown> {\n if (!fs.existsSync(configFilepath)) return {};\n try {\n const config = asRecord(\n JSON.parse(fs.readFileSync(configFilepath, 'utf8'))\n );\n if (config) return config;\n throw new Error('the file does not contain a JSON object');\n } catch (error) {\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `${configFilepath} is not a valid JSON config`,\n reassurance: 'No project files were changed',\n details: formatDiagnosticErrorDetails(error),\n fix: 'Fix or remove the file, then rerun the command',\n })\n );\n }\n}\n\nexport const INIT_SOURCE_HELP =\n \"Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'\";\n\nexport function setupConfigPath(\n options: Pick<ConfigureOptions, 'config'>\n): string {\n return options.config ? withJsonExtension(options.config) : 'gt.config.json';\n}\n\nexport function getConfiguredFramework(\n config: Record<string, unknown>\n): SupportedReactFrameworks | 'mintlify' | undefined {\n const framework = config.framework;\n return typeof framework === 'string' &&\n [...SUPPORTED_REACT_FRAMEWORKS, 'mintlify'].includes(\n framework as SupportedReactFrameworks\n )\n ? (framework as SupportedReactFrameworks | 'mintlify')\n : undefined;\n}\n\n/** JSON mode keeps the banner off stdout. */\nexport function displaySetupHeader(\n session: OnboardingSession,\n message: string\n) {\n if (session.json) logger.startCommand(message);\n else displayHeader(message);\n}\n\nexport function describeDefaults(\n framework: FrameworkObject | undefined\n): string {\n const buildTool = getBuildToolSetup(framework?.name);\n const translationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n if (framework?.type !== 'react') {\n return `Files saved locally in ${translationsDir}`;\n }\n // The wizard leaves Pages Router apps to the quickstart (resolveReactSetup).\n if (framework.name === 'next-pages') {\n return `${getFrameworkDisplayName(framework)}, no app changes (follow the Pages Router quickstart)`;\n }\n const library = getReactFrameworkLibrary(framework);\n const setup = buildTool?.initializer ?? 'GTProvider';\n return `${library} & ${setup}, ${getFrameworkDisplayName(framework)}, Files saved locally in ${translationsDir}`;\n}\n\n/** Setup patterns name where each locale's files live, so they need [locale]. */\nexport function validateSetupPattern(pattern: string): true | string {\n return (\n pattern.includes('[locale]') ||\n `\"${pattern}\" must include [locale], e.g. ./locales/[locale]/*.json`\n );\n}\n\n/** Parses `--file-patterns <format>=<glob>` values, grouped by format. */\nexport function parseFilePatterns(\n session: OnboardingSession,\n values: string[] = []\n): Map<SetupFileFormat, string[]> {\n const patterns = new Map<SetupFileFormat, string[]>();\n for (const value of values) {\n const separator = value.indexOf('=');\n const format = value.slice(0, separator) as SetupFileFormat;\n const pattern = value.slice(separator + 1).trim();\n if (separator < 0 || !SETUP_FILE_FORMATS.includes(format) || !pattern) {\n session.reject(\n `--file-patterns \"${value}\" must look like <format>=<glob> with a format of ${SETUP_FILE_FORMATS.join(', ')}`\n );\n continue;\n }\n const problem = validateSetupPattern(pattern);\n if (problem !== true) {\n session.reject(`--file-patterns \"${value}\": ${problem}`);\n continue;\n }\n patterns.set(format, [...(patterns.get(format) ?? []), pattern]);\n }\n return patterns;\n}\n\n/** Detects the package manager, or asks only when prompts are allowed. */\nexport async function resolvePackageManager(\n session: OnboardingSession,\n specified?: string\n): Promise<PackageManager | undefined> {\n try {\n return await getPackageManager(\n process.cwd(),\n specified,\n !session.interactive\n );\n } catch (error) {\n if (!(error instanceof NoPackageManagerError)) throw error;\n session.require('--package-manager');\n return undefined;\n }\n}\n\nexport async function installWithProgress(\n session: OnboardingSession,\n packageName: string,\n packageManager: PackageManager,\n asDevDependency: boolean\n): Promise<void> {\n const spinner = logger.createSpinner('timer');\n spinner.start(\n `Installing ${packageName}${asDevDependency ? ' as a dev dependency' : ''} with ${packageManager.name}...`\n );\n try {\n await installPackage(packageName, packageManager, asDevDependency);\n } catch (error) {\n spinner.stop(`Could not install ${packageName}.`, 2);\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Failed to install ${packageName}`,\n details: formatDiagnosticErrorDetails(error),\n fix: `Install it with \\`${packageManager.name} ${packageManager.installCommand} ${packageName}\\`, then rerun the command`,\n })\n );\n }\n spinner.stop(`Installed ${packageName}.`);\n session.step(`installed ${packageName}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqEA,SAAgB,qBACd,SACA,YACS;AACT,QAAO,yBAAyB,QAAQ,CACrC,OAAO,oBAAoB,WAAW,CACtC,OACC,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACA,OACC,oBACA,wGACD,CACA,OACC,UACA,kHACD,CACA,OACC,cACA,6HACD,CACA,OAAO,iBAAiB,wCAAwC,CAChE,OAAO,6BAA6B,0BAA0B,CAC9D,OACC,0BACA,sEACD,CACA,UACC,IAAI,OACF,uBACA,mDACD,CAAC,QAAQ,CAAC,SAAS,MAAM,CAAC,CAC5B,CACA,OACC,6BACA,2CACD,CACA,UACC,IAAI,OACF,+BACA,gDACD,CAAC,QAAQ,CAAC,GAAG,oBAAoB,OAAO,CAAC,CAC3C,CACA,OACC,iCACA,+GACD,CACA,OACC,uBACA,uFACD,CACA,OAAO,0BAA0B,qCAAqC,CACtE,UACC,IAAI,OACF,qBACA,4DACD,CAAC,UAAU,mBAAmB,CAChC,CACA,OAAO,wBAAwB,wCAAwC,CACvE,OACC,qBACA,mDACD,CACA,OACC,oBACA,uDACD,CACA,OAAO,iBAAiB,0CAA0C,CAClE,OAAO,yBAAyB,4BAA4B,CAC5D,UACC,IAAI,OACF,0BACA,0DACD,CAAC,QAAQ,gBAAgB,KAAK,mBAAmB,eAAe,GAAG,CAAC,CACtE;;AAGL,IAAI;AAEJ,SAAS,2BAA2B,MAAoB;AACtD,KAAI,SAAS,KAAK,4BAA4B,KAAA,EAAW;AACzD,IAAG,UACD,QAAQ,OAAO,IACf,GAAG,KAAK,UAAU;EAChB,MAAM;EACN,SAAS;EACT,SAAS;EACT,gBAAgB,EAAE;EAClB,OAAO,UACL,kBAAkB,IAAI,6CACvB;EACF,CAA2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GACR,UAAU;GACV,cAAc,qBAAqB;GACnC,SAAS,6BAA6B,MAAM;GAC5C,KAAK,qBAAqB,eAAe,KAAK,GAAG,eAAe,eAAe,GAAG,YAAY;GAC/F,CAAC,CACH;;AAEH,SAAQ,KAAK,aAAa,YAAY,GAAG;AACzC,SAAQ,KAAK,aAAa,cAAc"}
@@ -10,10 +10,16 @@ export type ReactSetupPlan = {
10
10
  nextConfigPath?: string;
11
11
  formatter?: Formatter;
12
12
  };
13
+ /** The framework was chosen, but the wizard leaves its app setup to a person. */
14
+ export type SkippedReactSetup = {
15
+ framework: 'next-pages';
16
+ skipped: true;
17
+ };
13
18
  /**
14
19
  * Resolves whether and how to set up the React application. Returns
15
- * undefined when the setup is declined or an answer is still missing.
20
+ * undefined when the setup is declined or an answer is still missing, and
21
+ * a skipped setup for frameworks the wizard cannot configure.
16
22
  */
17
- export declare function resolveReactSetup(session: OnboardingSession, options: InitOptions, detected: ReactFrameworkObject, configuredFramework?: SupportedReactFrameworks): Promise<ReactSetupPlan | undefined>;
23
+ export declare function resolveReactSetup(session: OnboardingSession, options: InitOptions, detected: ReactFrameworkObject, configuredFramework?: SupportedReactFrameworks): Promise<ReactSetupPlan | SkippedReactSetup | undefined>;
18
24
  /** Adds GTProvider and withGTConfig() to a Next.js App Router app; installs happen first. */
19
25
  export declare function executeReactSetup(session: OnboardingSession, plan: ReactSetupPlan, options: InitOptions): Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import { logger } from "../console/logger.js";
2
2
  import { getPackageJson, isPackageInstalled } from "../utils/packageJson.js";
3
+ import { NEXT_PAGES_QUICKSTART_URL } from "../utils/constants.js";
3
4
  import "../types/libraries.js";
4
5
  import { exitSync, promptConfirm, promptSelect } from "../console/logging.js";
5
6
  import findFilepath from "../fs/findFilepath.js";
@@ -14,10 +15,33 @@ import { createDiagnosticMessage } from "generaltranslation/internal";
14
15
  //#region src/setup/wizard.ts
15
16
  const cancelledMessage = "Operation cancelled. You can re-run this wizard with: npx gt init";
16
17
  /**
18
+ * The wizard cannot wire the Pages Router yet, so it leaves the app (and its
19
+ * dependencies) unchanged and reports the quickstart as a manual step.
20
+ */
21
+ function skipPagesRouterSetup(session) {
22
+ const fix = `Install gt-next and wire your app by following the Next.js Pages Router quickstart: ${NEXT_PAGES_QUICKSTART_URL}`;
23
+ session.humanActions.push(fix);
24
+ logger.warn(createDiagnosticMessage({
25
+ source: "gt",
26
+ severity: "Warning",
27
+ whatHappened: "Setup will not install gt-next or wire it into your app",
28
+ why: "the wizard cannot configure the Next.js Pages Router yet",
29
+ reassurance: "It still sets up gt.config.json and your local translation files",
30
+ fix: "Install gt-next and wire your app by following the Next.js Pages Router quickstart",
31
+ docsUrl: NEXT_PAGES_QUICKSTART_URL
32
+ }));
33
+ return {
34
+ framework: "next-pages",
35
+ skipped: true
36
+ };
37
+ }
38
+ /**
17
39
  * Resolves whether and how to set up the React application. Returns
18
- * undefined when the setup is declined or an answer is still missing.
40
+ * undefined when the setup is declined or an answer is still missing, and
41
+ * a skipped setup for frameworks the wizard cannot configure.
19
42
  */
20
43
  async function resolveReactSetup(session, options, detected, configuredFramework) {
44
+ if (options.reactSetup !== false && (options.framework ?? configuredFramework ?? detected.name) === "next-pages") return skipPagesRouterSetup(session);
21
45
  const library = getReactFrameworkLibrary(detected);
22
46
  const initializer = getBuildToolSetup(detected.name)?.initializer;
23
47
  if (!await session.answer("--react-setup", {
@@ -94,6 +118,7 @@ Please let us know what you would like to see added at https://github.com/genera
94
118
  return exitSync(0);
95
119
  }
96
120
  if (!framework) return void 0;
121
+ if (framework === "next-pages") return skipPagesRouterSetup(session);
97
122
  const packageJson = await getPackageJson();
98
123
  if (!packageJson) {
99
124
  session.reject("No package.json found in the current directory. Run this command from the root of your project");