gt 2.26.7 → 2.26.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # gtx-cli
2
2
 
3
+ ## 2.26.9
4
+
5
+ ### Patch Changes
6
+
7
+ - [#2525](https://github.com/generaltranslation/gt/pull/2525) [`aee1350`](https://github.com/generaltranslation/gt/commit/aee135077ebef9d98378b68d5898df548d83f137) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Limit how many files postprocessing reads and writes at once so large docs projects no longer fail with `EMFILE: too many open files`
8
+
9
+ - Updated dependencies []:
10
+ - generaltranslation@9.5.8
11
+ - @generaltranslation/python-extractor@0.2.63
12
+ - @generaltranslation/supported-locales@2.1.44
13
+ - @generaltranslation/vue-extractor@0.1.22
14
+
15
+ ## 2.26.8
16
+
17
+ ### Patch Changes
18
+
19
+ - [#2522](https://github.com/generaltranslation/gt/pull/2522) [`a0ba4ab`](https://github.com/generaltranslation/gt/commit/a0ba4aba791a99026b2900991fa6608c3cf1bd93) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - `gt download` performs same postprocessing as `gt translate`
20
+
3
21
  ## 2.26.7
4
22
 
5
23
  ### Patch Changes
@@ -67,6 +67,12 @@ export declare class BaseCLI {
67
67
  */
68
68
  protected handleDownload(initOptions: TranslateFlags): Promise<void>;
69
69
  protected handleTranslate(initOptions: TranslateFlags): Promise<void>;
70
+ /**
71
+ * Postprocesses the translations downloaded in this run and reports the
72
+ * summary. Shared by translate and download so both write the same output.
73
+ * @param settings - The settings for the command
74
+ */
75
+ protected finalizeDownloadedTranslations(settings: Settings): Promise<void>;
70
76
  protected setupUploadCommand(): void;
71
77
  protected setupUserAuthCommands(): void;
72
78
  protected setupInitCommand(): void;
package/dist/cli/base.js CHANGED
@@ -293,7 +293,9 @@ var BaseCLI = class {
293
293
  * @returns The results of the command
294
294
  */
295
295
  async handleDownload(initOptions) {
296
- await handleDownload(initOptions, await generateSettings(initOptions, void 0, { requireConfig: true }), this.library);
296
+ const settings = await generateSettings(initOptions, void 0, { requireConfig: true });
297
+ await handleDownload(initOptions, settings, this.library);
298
+ await this.finalizeDownloadedTranslations(settings);
297
299
  }
298
300
  async handleTranslate(initOptions) {
299
301
  const settings = await generateSettings(initOptions, void 0, { requireConfig: true });
@@ -303,6 +305,14 @@ var BaseCLI = class {
303
305
  const results = await handleStage(initOptions, settings, this.library, false);
304
306
  if (results) await handleTranslate(initOptions, settings, results.fileVersionData, results.jobData, results.branchData, results.publishMap, results.inlineLibrary);
305
307
  } else await handleDownload(initOptions, settings, this.library);
308
+ await this.finalizeDownloadedTranslations(settings);
309
+ }
310
+ /**
311
+ * Postprocesses the translations downloaded in this run and reports the
312
+ * summary. Shared by translate and download so both write the same output.
313
+ * @param settings - The settings for the command
314
+ */
315
+ async finalizeDownloadedTranslations(settings) {
306
316
  const include = getNeedsPostprocessing();
307
317
  if (include.size > 0) await postProcessTranslations(settings, include);
308
318
  await splitMintlifyLanguageRefs(settings);
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../src/cli/base.ts"],"sourcesContent":["import { Argument, Command, InvalidArgumentError, Option } from 'commander';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n DEFAULT_TRANSLATIONS_DIR,\n REACT_QUICKSTART_URL,\n} from '../utils/constants.js';\nimport {\n applySetupConfig,\n mergeSetupConfig,\n type SetupConfigUpdate,\n} from '../fs/config/setupConfig.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport {\n displayHeader,\n promptText,\n logErrorAndExit,\n exitSync,\n promptConfirm,\n promptMultiSelect,\n promptSelect,\n promptGlobPatterns,\n} from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { lottieTranslateError } from '../console/index.js';\nimport { parseGlobPatterns } from '../console/promptParsing.js';\nimport path from 'node:path';\nimport {\n FilesOptions,\n Settings,\n SupportedFrameworks,\n SupportedLibraries,\n TranslateFlags,\n SharedFlags,\n} from '../types/index.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport chalk from 'chalk';\nimport {\n FILE_EXT_TO_EXT_LABEL,\n SETUP_FILE_FORMATS,\n SUPPORTED_FILE_EXTENSIONS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n executeReactSetup,\n resolveReactSetup,\n type ReactSetupPlan,\n} from '../setup/wizard.js';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { getDesiredLocales } from '../setup/userInput.js';\nimport {\n areCredentialsSet,\n getDevelopmentEnvNames,\n inspectCredentialsEnvFile,\n} from '../utils/credentials.js';\nimport {\n checkDevelopmentProjectInputs,\n productionRuntimeKeyGuidance,\n provisionDevelopmentCredentials,\n resolveDevelopmentProject,\n signInForSetup,\n} from '../setup/developmentCredentials.js';\nimport { exitIfUnsupportedSetupTarget } from '../setup/setupTarget.js';\nimport {\n asRecord,\n attachConfigureFlags,\n attachInitFlags,\n describeDefaults,\n displaySetupHeader,\n getConfiguredFramework,\n INIT_SOURCE_HELP,\n installWithProgress,\n OnboardingError,\n parseFilePatterns,\n readSetupConfig,\n reportJsonExitsBeforeOnboarding,\n resolvePackageManager,\n runOnboarding,\n setupConfigPath,\n validateSetupPattern,\n type ConfigureOptions,\n type InitOptions,\n type OnboardingSession,\n} from '../setup/onboarding.js';\nimport { upload } from './commands/upload.js';\nimport { attachSharedFlags, attachTranslateFlags } from './flags.js';\nimport { handleStage } from './commands/stage.js';\nimport { handleSetupProject } from './commands/setupProject.js';\nimport { handleDownload } from './commands/download.js';\nimport {\n handleTranslate,\n postProcessTranslations,\n} from './commands/translate.js';\nimport {\n getNeedsPostprocessing,\n clearDownloaded,\n} from '../state/recentDownloads.js';\nimport { clearWarnings } from '../state/translateWarnings.js';\nimport { displayTranslateSummary } from '../console/displayTranslateSummary.js';\nimport updateConfig from '../fs/config/updateConfig.js';\nimport {\n createLoadTranslationsFile,\n findLoadTranslationsFiles,\n} from '../fs/createLoadTranslationsFile.js';\nimport { saveLocalEdits } from '../api/saveLocalEdits.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './commands/utils/validation.js';\nimport processSharedStaticAssets, {\n mirrorAssetsToLocales,\n} from '../utils/sharedStaticAssets.js';\nimport { setupLocadex } from '../locadex/setupFlow.js';\nimport { detectFramework } from '../setup/detectFramework.js';\nimport { INLINE_LIBRARIES, Libraries } from '../types/libraries.js';\nimport { handleEnqueue } from './commands/enqueue.js';\nimport { splitMintlifyLanguageRefs } from '../utils/splitMintlifyLanguageRefs.js';\nimport { localizeMintlifyRedirects } from '../formats/files/postprocess/localizeMintlifyRedirects.js';\nimport {\n clearOrphanedFileNames,\n getOrphanedFileNames,\n} from '../state/orphanedFileNames.js';\nimport { runMergeDriver, type MergeDriverName } from '../git/mergeDrivers.js';\nimport { setupGitMergeDrivers } from '../git/setupMergeDrivers.js';\nimport { warnReactPackageCompatibility } from '../utils/reactPackageCompatibility.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { hasLogin, logout, whoAmI } from '../auth/oauth.js';\nimport { createUserAuthError, UserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { resolveConfig } from '../config/resolveConfig.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport {\n getBuildToolSetup,\n type ManualAction,\n type SetupResult,\n} from '../setup/buildTools/index.js';\nimport { manifestDirectlyDeclaresGTVue } from '@generaltranslation/vue-extractor/integration';\nimport { api } from '../utils/api.js';\nimport { handleApiCommand, type ApiCommandOptions } from './commands/api.js';\n\nconst ID_COMPATIBILITY_WARNING_COMMANDS = new Set([\n 'download',\n 'enqueue',\n 'generate',\n 'setup',\n 'stage',\n 'translate',\n 'validate',\n]);\nfunction createProjectCommandError(\n whatHappened: string,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened,\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst emptyApiKeyNameError = createDiagnosticMessage({\n whatHappened: 'The key name cannot be empty',\n fix: 'Pass a non-empty value with --name',\n});\n\nfunction parseApiKeyName(value: string): string {\n const name = value.trim();\n if (!name) throw new InvalidArgumentError(emptyApiKeyNameError);\n return name;\n}\n\n/** Credential failures keep their own diagnostic or get the setup context. */\nasync function withCredentialsError<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof OnboardingError) throw error;\n throw new Error(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError(\n 'Failed to set up the development credentials',\n error\n )\n );\n }\n}\n\nexport type UploadOptions = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n defaultLocale?: string;\n};\n\nexport type GitSetupOptions = {\n config?: string;\n dryRun?: boolean;\n omitConfigIds?: boolean;\n driverCommand?: string;\n};\n\ntype LocalTranslationGuidanceOptions = {\n generatedLoader: boolean;\n runtimeSetup: InlineRuntimeSetup;\n translationsDir: string;\n};\n\ntype InlineRuntimeSetup = {\n hasOtherInlineRuntime: boolean;\n hasVueRuntime: boolean;\n ranReactSetup: boolean;\n};\n\nexport class BaseCLI {\n protected library: SupportedLibraries;\n protected additionalModules: SupportedLibraries[];\n protected program: Command;\n // Constructor is shared amongst all CLI class types\n public constructor(\n program: Command,\n library: SupportedLibraries,\n additionalModules?: SupportedLibraries[]\n ) {\n this.program = program;\n this.library = library;\n this.additionalModules = additionalModules || [];\n\n this.program.option(\n '--skip-version-check',\n 'Skip the monorepo GT package version consistency check'\n );\n this.program.option(\n '--suppress-id-compatibility-warning',\n 'Suppress the React package ID compatibility warning'\n );\n this.program.option(\n '-q, --quiet',\n 'Suppress informational output; only warnings and errors are shown'\n );\n // Select console routing for this command before anything else logs:\n // root hooks run before subclass hooks (version checks) and the action's\n // settings resolution. `gt api-key create` prints the new secret on\n // stdout, so its diagnostics go to stderr, as do setup commands writing\n // JSON events; every other command gets the historical default back\n // (main() routes startup output to stderr).\n this.program.hook('preAction', (thisCommand, actionCommand) => {\n logger.setConsoleOutput(\n actionCommand.parent?.name() === 'api-key' || actionCommand.opts().json\n ? 'stderr'\n : 'stdout'\n );\n if (\n actionCommand.opts().json &&\n actionCommand.parent === thisCommand &&\n ['init', 'configure'].includes(actionCommand.name())\n ) {\n reportJsonExitsBeforeOnboarding(actionCommand.name());\n }\n });\n // Apply --quiet before any other hook or command action runs so the\n // singleton logger is muted for the rest of the invocation. The flag is a\n // global root option, so commander resolves it in any position and for\n // nested commands (e.g. `gt git setup --quiet`).\n this.program.hook('preAction', () => {\n logger.setQuiet(Boolean(this.program.opts().quiet));\n });\n this.program.hook('preAction', async (thisCommand, actionCommand) => {\n // Nested commands (e.g. `gt git setup`) can share leaf names with\n // translation commands; only direct children of the root qualify\n if (actionCommand.parent !== thisCommand) return;\n if (!ID_COMPATIBILITY_WARNING_COMMANDS.has(actionCommand.name())) return;\n await warnReactPackageCompatibility(\n Boolean(this.program.opts().suppressIdCompatibilityWarning)\n );\n });\n\n this.setupInitCommand();\n this.setupConfigureCommand();\n this.setupUploadCommand();\n this.setupUserAuthCommands();\n this.setupSendDiffsCommand();\n this.setupApiCommand();\n this.setupProjectCommands();\n this.setupApiKeyCommands();\n this.setupGitCommand();\n }\n // Init is never called in a child class\n public init() {\n this.setupSetupProjectCommand();\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n // Execute is called by the main program\n public execute() {\n // If no command is specified, run 'init'\n if (process.argv.length <= 2) {\n process.argv.push('init');\n }\n }\n\n protected setupSetupProjectCommand(): void {\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupStageCommand(): void {\n attachTranslateFlags(\n this.program\n .command('stage')\n .description(\n 'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupEnqueueCommand(): void {\n attachTranslateFlags(\n this.program\n .command('enqueue')\n .description('Enqueues translations for a given set of files')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Enqueuing translations...');\n await this.handleEnqueue(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupDownloadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('download')\n .description('Download translations that were originally staged')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Downloading translations...');\n await this.handleDownload(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachTranslateFlags(\n this.program\n .command('translate')\n .description('Translate your project using General Translation')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Starting translation...');\n await this.handleTranslate(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupSendDiffsCommand(): void {\n attachSharedFlags(\n this.program\n .command('save-local')\n .description(\n 'Save local edits for all configured files by sending diffs (no translation enqueued)'\n )\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .action(async (initOptions: SharedFlags) => {\n displayHeader('Saving local edits...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n await saveLocalEdits(settings);\n logger.endCommand('Saved local edits');\n });\n }\n\n protected setupApiCommand(): void {\n attachSharedFlags(\n this.program\n .command('api [endpoint]')\n .description('Make an authenticated request to the GT API')\n .option('-X, --method <method>', 'HTTP method', 'GET')\n .option('--input <file>', 'Request body file, or - for standard input')\n .option(\n '-H, --header <header>',\n 'Request header in \"Key: Value\" format',\n (header, headers: string[] | undefined) => [\n ...(headers ?? []),\n header,\n ]\n )\n .option('-i, --include', 'Include response status and headers')\n .option(\n '--spec',\n 'Print the bundled OpenAPI specification, or only the operations matching [endpoint] (path or operation ID) with references resolved'\n )\n .addOption(\n new Option(\n '--list',\n 'List the method, path, operation ID, and summary of every API operation'\n ).conflicts('spec')\n )\n ).action((endpoint, options: ApiCommandOptions) =>\n handleApiCommand(endpoint, options)\n );\n }\n\n protected setupProjectCommands(): void {\n const projectCommand = this.program\n .command('project')\n .description('Manage General Translation projects');\n\n attachSharedFlags(\n projectCommand\n .command('create')\n .description(\n 'Create a General Translation project using an organization API key'\n )\n .requiredOption('--org-id <orgId>', 'Organization ID')\n .requiredOption('--name <name>', 'Project name')\n .requiredOption('--default-locale <locale>', 'Project default locale')\n .option('--cdn-enabled', 'Enable CDN delivery', false)\n ).action(async (options) => {\n try {\n const settings = await generateSettings(options);\n // Project creation happens before a project ID exists.\n if (!hasValidServiceLocales(settings)) return exitSync(1);\n const { project } = await api.createProject(options.orgId, {\n name: options.name,\n defaultLocale: options.defaultLocale,\n cdnEnabled: options.cdnEnabled,\n });\n logger.info(`Created ${project.name} (${project.id})`);\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError('Failed to create the project', error)\n );\n }\n });\n\n attachSharedFlags(\n projectCommand\n .command('status')\n .description('Check the status of a project setup job')\n .argument('<job-id>', 'Setup job ID')\n ).action(async (jobId, options) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const [status] = await api.checkJobStatus([jobId]);\n logger.info(status?.status ?? 'unknown');\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError(\n 'Failed to check the project setup status',\n error\n )\n );\n }\n });\n }\n\n protected setupApiKeyCommands(): void {\n const apiKeyCommand = this.program\n .command('api-key')\n .description('Manage API keys for the configured project');\n\n attachSharedFlags(\n apiKeyCommand\n .command('create')\n .description(\n 'Create a project API key with the requested permissions and print it once'\n )\n .requiredOption('--name <name>', 'Key name', parseApiKeyName)\n // Validated before any request; the server grants the requested set\n // all-or-nothing, so omitting permissions would delegate everything.\n .addOption(\n new Option('--permission <permissions...>', 'Permissions to grant')\n .choices(Object.values(ProjectApiKeyPermission))\n .makeOptionMandatory()\n )\n ).action(\n async (\n options: SharedFlags & {\n name: string;\n permission: ProjectApiKeyPermission[];\n }\n ) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const { apiKey } = await api.createProjectApiKey(settings.projectId, {\n name: options.name,\n permissions: options.permission,\n });\n // Raw stdout: the secret is shown once and never reaches the log file.\n process.stdout.write(`${apiKey.key}\\n`);\n } catch (error) {\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError('Failed to create the API key', error)\n );\n }\n }\n );\n }\n\n protected setupGitCommand(): void {\n const gitCommand = this.program\n .command('git')\n .description('Configure Git integrations for General Translation');\n\n gitCommand\n .command('setup')\n .description('Set up GT merge drivers for generated translation files')\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--dry-run', 'Print changes without writing files', false)\n .option(\n '--omit-config-ids',\n 'Persist omitConfigIds and remove generated config IDs'\n )\n .option(\n '--driver-command <command>',\n 'Command Git should use to invoke gt, e.g. \"pnpm exec gt\"'\n )\n .action(async (options: GitSetupOptions) => {\n displayHeader('Setting up GT Git merge drivers...');\n const settings = await generateSettings(options, undefined, {\n requireConfig: true,\n });\n const omitConfigIds = await this.resolveGitSetupOmitConfigIds(\n options,\n settings\n );\n const result = await setupGitMergeDrivers(settings, {\n dryRun: options.dryRun,\n omitConfigIds,\n driverCommand: options.driverCommand,\n });\n\n for (const line of result.addedAttributes) {\n logger.step(\n `${options.dryRun ? 'Would add' : 'Added'} ${chalk.cyan(\n line\n )} to ${chalk.cyan(result.gitattributesPath)}`\n );\n }\n if (result.addedAttributes.length === 0) {\n logger.info(`${chalk.cyan('.gitattributes')} is already configured.`);\n }\n\n for (const args of result.gitConfigCommands) {\n logger.step(\n `${options.dryRun ? 'Would run' : 'Configured'} ${chalk.cyan(\n `git config --local ${args.join(' ')}`\n )}`\n );\n }\n\n if (result.updatedConfig) {\n logger.step(\n `${options.dryRun ? 'Would persist' : 'Persisted'} ${chalk.cyan(\n 'omitConfigIds: true'\n )} in ${chalk.cyan(settings.config)}`\n );\n } else if (options.dryRun && !settings.omitConfigIds) {\n logger.info(\n `Run without ${chalk.cyan('--dry-run')} to be prompted to persist ${chalk.cyan(\n 'omitConfigIds: true'\n )}, or pass ${chalk.cyan('--omit-config-ids')}.`\n );\n }\n\n for (const warning of result.warnings) {\n logger.warn(chalk.yellow(warning));\n }\n\n logger.endCommand(\n options.dryRun\n ? 'Dry run complete.'\n : 'GT Git merge drivers configured.'\n );\n });\n\n gitCommand\n .command('merge-driver', { hidden: true })\n .addArgument(\n new Argument('<driver>', 'Merge driver name').choices([\n 'gt-lock',\n 'gtjson',\n ])\n )\n .argument('<base>', 'Common ancestor file')\n .argument('<ours>', 'Current branch file')\n .argument('<theirs>', 'Incoming branch file')\n .argument('[path]', 'Merged path')\n .action(\n (\n driver: MergeDriverName,\n base: string,\n ours: string,\n theirs: string\n ) => {\n const result = runMergeDriver(driver, base, ours, theirs);\n if (!result.ok) {\n logger.error(result.reason);\n exitSync(1);\n }\n }\n );\n }\n\n protected async resolveGitSetupOmitConfigIds(\n options: GitSetupOptions,\n settings: Settings\n ): Promise<boolean> {\n if (options.omitConfigIds) return true;\n // Already opted in: persist again so stale config IDs still get removed\n if (settings.omitConfigIds) return true;\n if (options.dryRun || !process.stdin.isTTY || !process.stdout.isTTY) {\n return false;\n }\n return promptConfirm({\n message:\n 'Also set omitConfigIds: true to reduce gt.config.json merge conflicts?',\n defaultValue: true,\n });\n }\n\n protected async handleSetupProject(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n await handleSetupProject(initOptions, settings, this.library);\n }\n\n protected async handleStage(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Update settings.stageTranslations to true\n settings.stageTranslations = true;\n await updateConfig(settings.config, {\n stageTranslations: true,\n });\n }\n await handleStage(initOptions, settings, this.library, true);\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleEnqueue(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleEnqueue(initOptions, settings, this.library);\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleDownload(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleDownload(initOptions, settings, this.library);\n }\n\n protected async handleTranslate(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Lottie translations finish asynchronously server-side (layout\n // refinement runs after the translation job completes), so the immediate\n // translate flow would try to download them before they're ready. Only\n // the stage + download flow supports them.\n if (settings.files?.resolvedPaths.lottie?.length) {\n return logErrorAndExit(lottieTranslateError);\n }\n const results = await handleStage(\n initOptions,\n settings,\n this.library,\n false\n );\n if (results) {\n await handleTranslate(\n initOptions,\n settings,\n results.fileVersionData,\n results.jobData,\n results.branchData,\n results.publishMap,\n results.inlineLibrary\n );\n }\n } else {\n await handleDownload(initOptions, settings, this.library);\n }\n // Only postprocess files downloaded in this run\n const include = getNeedsPostprocessing();\n if (include.size > 0) {\n await postProcessTranslations(settings, include);\n }\n // Split Mintlify language entries into $ref files to keep docs.json small\n await splitMintlifyLanguageRefs(settings);\n // Localize redirects for pages this run renamed or removed. Runs after the\n // split, which can rewrite $ref files such as redirects.json\n const orphanedFileNames = getOrphanedFileNames();\n if (orphanedFileNames) {\n const added = localizeMintlifyRedirects(settings, orphanedFileNames);\n if (added.length > 0) {\n logger.success(\n `Added ${added.length} localized redirect${added.length === 1 ? '' : 's'}`\n );\n }\n }\n clearOrphanedFileNames();\n // Mirror assets after translations are downloaded and locale dirs are populated\n await mirrorAssetsToLocales(settings);\n clearDownloaded();\n displayTranslateSummary();\n clearWarnings();\n }\n\n protected setupUploadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('upload')\n .description(\n 'Upload source files and translations to the General Translation platform'\n )\n ).action(async (initOptions: UploadOptions) => {\n displayHeader('Starting upload...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const options = { ...initOptions, ...settings };\n\n await this.handleUploadCommand(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupUserAuthCommands(): void {\n this.program\n .command('login')\n .description('Sign in to your General Translation account')\n .option(\n '--no-browser',\n 'Do not open a browser; show a sign-in URL to use on any device instead'\n )\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json'\n )\n .action(async (options: { browser: boolean; config?: string }) => {\n displayHeader('Signing in to General Translation...');\n try {\n // Tokens are bound to one API resource, so log in to the configured one.\n const baseUrl = (\n options.config\n ? loadConfig(withJsonExtension(options.config))\n : resolveConfig(process.cwd())?.config\n )?.baseUrl;\n await loginInteractively(\n typeof baseUrl === 'string' ? baseUrl : undefined,\n options.browser\n );\n logger.endCommand('You are now signed in.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign in failed', error));\n }\n });\n\n this.program\n .command('logout')\n .description('Sign out of your General Translation account')\n .action(async () => {\n try {\n await logout();\n logger.endCommand('Signed out successfully.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign out failed', error));\n }\n });\n\n this.program\n .command('whoami')\n .description('Show the signed-in General Translation account')\n .action(async () => {\n try {\n const user = await whoAmI();\n logger.message(user.email ?? user.name ?? user.sub);\n } catch (error) {\n logErrorAndExit(\n createUserAuthError('Could not load your account', error)\n );\n }\n });\n }\n\n protected setupInitCommand(): void {\n attachInitFlags(\n this.program\n .command('init')\n .description(\n 'Run the setup wizard to configure your project for General Translation. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: InitOptions) => this.handleInitWizard(options));\n }\n\n protected async handleInitWizard(options: InitOptions): Promise<void> {\n await runOnboarding('init', options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Running setup wizard...');\n\n const detected = await detectFramework();\n const reactDetected = detected.type === 'react' ? detected : undefined;\n if (options.framework && !reactDetected) {\n session.reject(\n '--framework applies only to projects detected as React applications'\n );\n }\n const configFilepath = setupConfigPath(options);\n const configured = getConfiguredFramework(\n readSetupConfig(configFilepath)\n );\n const configuredReact =\n configured !== 'mintlify' ? configured : undefined;\n // Explicit --defaults / --no-defaults also answer the Locadex gate.\n if (options.defaults !== undefined) session.defaults = options.defaults;\n const gateFramework = options.framework ?? configured ?? detected.name;\n if (gateFramework === 'mintlify' || gateFramework === 'next-app') {\n const useLocadex = await session.answer('--locadex', {\n explicit: options.locadex,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n gateFramework === 'mintlify'\n ? `Mintlify project detected. Would you like to connect to GitHub so that the Locadex AI Agent can translate your project automatically?`\n : `Next.js App Router detected. Would you like to connect to GitHub so that the Locadex AI Agent can set up your project automatically?`,\n defaultValue: false,\n }),\n });\n if (useLocadex) {\n session.assertResolved();\n const url = await setupLocadex(\n await generateSettings({ config: options.config }),\n { openBrowser: session.interactive }\n );\n session.emit({ type: 'handoff', url, reason: 'locadex' });\n logger.endCommand(\n 'Once installed, Locadex will open a PR to your repository. See the docs for more information: https://generaltranslation.com/docs/locadex'\n );\n return { outcome: 'needs_human_action', url };\n }\n } else if (options.locadex) {\n session.reject(\n '--locadex applies only to Mintlify and Next.js App Router projects'\n );\n }\n\n const shownFramework = reactDetected && {\n ...reactDetected,\n name: options.framework ?? configuredReact ?? reactDetected.name,\n };\n // Without --defaults, a noninteractive run uses no defaults.\n session.defaults =\n (await session.answer('--defaults', {\n explicit: options.defaults,\n fallback: false,\n ask: () =>\n promptConfirm({\n message: `Would you like to use the recommended General Translation defaults? ${chalk.dim(`(${describeDefaults(shownFramework)})`)}`,\n defaultValue: true,\n }),\n })) === true;\n\n const reactSetup = reactDetected\n ? await resolveReactSetup(\n session,\n options,\n reactDetected,\n configuredReact\n )\n : undefined;\n // flag > gt.config.json > detection, used for every later step.\n const framework =\n reactSetup?.framework ??\n options.framework ??\n configured ??\n detected.name;\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n saveFramework: Boolean(reactSetup || options.framework),\n reactSetup,\n keepAppSource: !reactSetup,\n });\n\n logger.endCommand(\n 'Done! Check out our docs for more information on how to use General Translation: https://generaltranslation.com/docs'\n );\n return { outcome: 'success' };\n });\n }\n\n protected setupConfigureCommand(): void {\n attachConfigureFlags(\n this.program\n .command('configure')\n .description(\n 'Configure your project for General Translation. This will create a gt.config.json file in your codebase. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: ConfigureOptions) =>\n this.handleConfigureCommand(options)\n );\n }\n\n protected async handleConfigureCommand(\n options: ConfigureOptions,\n command: string = 'configure'\n ): Promise<void> {\n await runOnboarding(command, options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Configuring project...');\n\n logger.info(\n 'Welcome! This tool will help you configure your gt.config.json file. See the docs: https://generaltranslation.com/docs/cli/reference/config for more information.'\n );\n\n // Configure only offers the defaults when asked with --defaults.\n session.defaults = options.defaults ?? false;\n const detected = await detectFramework();\n const configFilepath = setupConfigPath(options);\n // Detection only picks env names here; it is not saved.\n const framework =\n getConfiguredFramework(readSetupConfig(configFilepath)) ??\n detected.name;\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n });\n\n logger.endCommand(\n 'Done! Make sure you have an API key and project ID to use General Translation. Get them on the dashboard: https://generaltranslation.com/dashboard'\n );\n return { outcome: 'success' };\n });\n }\n\n protected async handleUploadCommand(\n settings: Settings & UploadOptions\n ): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n // Process all file types at once with a single call\n await upload(settings);\n }\n\n /** Describes installed runtimes without changing historical package lookup. */\n protected getInlineRuntimeSetup(\n packageJson: Record<string, unknown>,\n ranReactSetup: boolean = false\n ): InlineRuntimeSetup {\n return {\n hasOtherInlineRuntime: INLINE_LIBRARIES.some(\n (lib) =>\n lib !== Libraries.GT_VUE && isPackageInstalled(lib, packageJson)\n ),\n hasVueRuntime: manifestDirectlyDeclaresGTVue(packageJson),\n ranReactSetup,\n };\n }\n\n /** Returns whether any inline runtime is installed for setup. */\n protected isInlineRuntimeInstalled(\n packageJson: Record<string, unknown>\n ): boolean {\n const { hasOtherInlineRuntime, hasVueRuntime } =\n this.getInlineRuntimeSetup(packageJson);\n return hasOtherInlineRuntime || hasVueRuntime;\n }\n\n /** Returns whether every installed runtime can consume CDN translations. */\n protected supportsCDNStorage(runtimeSetup: InlineRuntimeSetup): boolean {\n return !runtimeSetup.hasVueRuntime;\n }\n\n /** Returns whether setup should generate a local runtime loader. */\n protected shouldGenerateLocalTranslationLoader(\n buildToolOwnsLoader: boolean,\n runtimeSetup: InlineRuntimeSetup\n ): boolean {\n if (buildToolOwnsLoader) return false;\n if (!runtimeSetup.hasVueRuntime) return true;\n return runtimeSetup.hasOtherInlineRuntime || runtimeSetup.ranReactSetup;\n }\n\n /** Returns framework guidance after selecting local translation storage. */\n protected getLocalTranslationGuidance({\n generatedLoader,\n runtimeSetup,\n translationsDir,\n }: LocalTranslationGuidanceOptions): string | undefined {\n const guidance: string[] = [];\n if (generatedLoader) {\n guidance.push(`Created ${chalk.cyan('loadTranslations.js')} file for local translations.\nMake sure to add this function to your app configuration.\nSee https://generaltranslation.com/en/docs/next/guides/local-tx`);\n }\n if (runtimeSetup.hasVueRuntime) {\n guidance.push(`GT will write local translation files to ${translationsDir}.\nConfigure createGT({ loadTranslations }) to load files from that directory.\nSee https://www.npmjs.com/package/gt-vue`);\n }\n return guidance.length > 0 ? guidance.join('\\n') : undefined;\n }\n\n /**\n * Resolves every configuration answer and validates the resulting config,\n * checks the project and signs in before the first change, then applies\n * the React setup, gt.config.json, installs and development credentials.\n */\n protected async handleInitCommand(\n session: OnboardingSession,\n options: ConfigureOptions,\n setup: {\n /** Chosen once by the entry point from the detected framework. */\n configFilepath: string;\n /** Resolved framework; drives storage, env names and build-tool setup. */\n framework?: SupportedFrameworks;\n /** Write the framework even when no build-tool setup saves it. */\n saveFramework?: boolean;\n reactSetup?: ReactSetupPlan;\n /** Init without the React setup never changes application source. */\n keepAppSource?: boolean;\n }\n ): Promise<void> {\n const { configFilepath, reactSetup } = setup;\n const buildTool = getBuildToolSetup(setup.framework);\n const cwd = process.cwd();\n const existingConfig = readSetupConfig(configFilepath);\n const { defaultLocale, locales } = await getDesiredLocales(\n session,\n existingConfig,\n options\n );\n\n const packageJson =\n reactSetup?.packageJson ?? (await searchForPackageJson());\n const runtimeSetup: InlineRuntimeSetup = packageJson\n ? this.getInlineRuntimeSetup(packageJson, Boolean(reactSetup))\n : {\n hasOtherInlineRuntime: false,\n hasVueRuntime: false,\n ranReactSetup: false,\n };\n const isUsingGT =\n runtimeSetup.ranReactSetup ||\n runtimeSetup.hasOtherInlineRuntime ||\n runtimeSetup.hasVueRuntime;\n const supportsCDN = this.supportsCDNStorage(runtimeSetup);\n const existingFiles = asRecord(existingConfig.files) ?? {};\n const existingGtOutput = asRecord(existingFiles.gt)?.output;\n const configuredOutput =\n typeof existingGtOutput === 'string' ? existingGtOutput : undefined;\n const configuredStorage = configuredOutput\n ? 'local'\n : existingConfig.publish === true\n ? 'cdn'\n : undefined;\n\n if (isUsingGT && !supportsCDN && options.storage === 'cdn') {\n session.reject(\n 'gt-vue cannot load translations from the CDN; use --storage local'\n );\n }\n // Where GT translations are stored\n const storage = !isUsingGT\n ? undefined\n : !supportsCDN\n ? 'local'\n : await session.answer<'local' | 'cdn'>('--storage', {\n explicit: options.storage,\n configured: configuredStorage,\n recommended: 'local',\n ask: () =>\n promptSelect<'local' | 'cdn'>({\n message: `Would you like to save translation files locally or use the General Translation CDN to store them?`,\n options: [\n { value: 'local', label: 'Save locally' },\n { value: 'cdn', label: 'Use CDN' },\n ],\n defaultValue: 'local',\n }),\n });\n\n const defaultTranslationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n const outputMatch = configuredOutput?.match(\n /^(?:(.+)[\\\\/])?\\[locale\\]\\.json$/\n );\n const configuredTranslationsDir = outputMatch\n ? (outputMatch[1] ?? '.')\n : undefined;\n const translationsDir =\n storage === 'local'\n ? await session.answer('--translations-dir', {\n explicit: options.translationsDir?.trim() || undefined,\n configured: configuredTranslationsDir,\n recommended: defaultTranslationsDir,\n ask: async () =>\n (\n await promptText({\n message:\n 'What is the path to the directory where you would like to store your translation files?',\n defaultValue: defaultTranslationsDir,\n })\n ).trim() || defaultTranslationsDir,\n })\n : undefined;\n\n const filePatterns = parseFilePatterns(session, options.filePatterns);\n const selectedFormats = options.fileFormats?.filter(\n (format): format is SetupFileFormat => format !== 'none'\n );\n if (\n options.fileFormats?.includes('none') &&\n (selectedFormats?.length ?? 0) > 0\n ) {\n session.reject('--file-formats none cannot be combined with formats');\n }\n const configuredFormats = SETUP_FILE_FORMATS.filter(\n (format) => format in existingFiles\n );\n // Formats setup does not offer stay as configured and count as files.\n const otherFormats = SUPPORTED_FILE_EXTENSIONS.filter(\n (format) =>\n format in existingFiles &&\n !(SETUP_FILE_FORMATS as readonly string[]).includes(format)\n );\n const hasOtherFormats = otherFormats.length > 0;\n if (options.fileFormats && hasOtherFormats) {\n const kept = otherFormats.map((format) => `files.${format}`).join(', ');\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `${kept} stays in ${configFilepath}`,\n why: '--file-formats only changes the formats setup offers',\n fix: `Remove ${kept} from ${configFilepath} to stop translating those files`,\n })\n );\n }\n const fileFormats = await session.answer<SetupFileFormat[]>(\n '--file-formats',\n {\n explicit:\n selectedFormats ??\n (filePatterns.size > 0 ? [...filePatterns.keys()] : undefined),\n configured:\n configuredFormats.length > 0 || hasOtherFormats\n ? configuredFormats\n : undefined,\n // GT projects need no other files; others must choose a format.\n recommended: isUsingGT ? [] : undefined,\n ask: () =>\n promptMultiSelect({\n message: !isUsingGT\n ? 'What is the format of your language resource files? Select as many as applicable.\\nAdditionally, you can translate any other files you have in your project.'\n : `Do you have any additional files in this project to translate? For example, Markdown files for docs. ${chalk.dim(\n '(To continue without selecting press Enter)'\n )}`,\n options: SETUP_FILE_FORMATS.map((format) => ({\n value: format,\n label: FILE_EXT_TO_EXT_LABEL[format],\n })),\n required: !isUsingGT,\n }),\n }\n );\n if (\n fileFormats &&\n fileFormats.length === 0 &&\n !isUsingGT &&\n !hasOtherFormats\n ) {\n session.reject(\n 'No GT runtime is installed, so select at least one file format to translate'\n );\n }\n for (const format of filePatterns.keys()) {\n if (fileFormats && !fileFormats.includes(format)) {\n session.reject(\n `--file-patterns ${format}= needs ${format} in --file-formats`\n );\n }\n }\n\n const files: FilesOptions = {};\n for (const fileExtension of fileFormats ?? []) {\n const existingFormat = asRecord(existingFiles[fileExtension]);\n const configuredInclude = Array.isArray(existingFormat?.include)\n ? (existingFormat.include as string[])\n : undefined;\n const include = await session.answer(\n `--file-patterns ${fileExtension}=<glob>`,\n {\n explicit: filePatterns.get(fileExtension),\n configured: configuredInclude,\n recommended: [`./**/[locale]/*.${fileExtension}`],\n ask: async () =>\n parseGlobPatterns(\n await promptGlobPatterns({\n label: FILE_EXT_TO_EXT_LABEL[fileExtension],\n message: `${chalk.cyan(FILE_EXT_TO_EXT_LABEL[fileExtension])}: Enter a space-separated list of glob patterns matching the location of the ${FILE_EXT_TO_EXT_LABEL[fileExtension]} files you would like to translate.\\nMake sure to include [locale] in the patterns.\\nSee https://generaltranslation.com/docs/cli/reference/config#include for more information.`,\n defaultValue: `./**/[locale]/*.${fileExtension}`,\n validate: (value) =>\n parseGlobPatterns(value)\n .map(validateSetupPattern)\n .find((problem) => problem !== true) ?? true,\n })\n ),\n }\n );\n // Configured patterns stay untouched; new ones keep other entry options.\n if (include && include !== configuredInclude) {\n files[fileExtension] = { ...existingFormat, include };\n }\n }\n if (translationsDir && translationsDir !== configuredTranslationsDir) {\n files.gt = { output: path.join(translationsDir, `[locale].json`) };\n }\n\n const envFramework =\n setup.framework ?? getConfiguredFramework(existingConfig);\n // The effective project: an explicit ID replaces a configured one. The\n // framework's runtime project outranks a stale generic GT_PROJECT_ID.\n const projectId =\n options.projectId ||\n (typeof existingConfig.projectId === 'string'\n ? existingConfig.projectId\n : undefined) ||\n process.env[getDevelopmentEnvNames(envFramework).projectId];\n const configUpdate: SetupConfigUpdate = {\n defaultLocale,\n locales,\n src: options.src,\n files: Object.keys(files).length > 0 ? files : undefined,\n framework:\n (setup.saveFramework && setup.framework) || buildTool?.framework,\n publish: storage === 'cdn',\n // Selecting local storage drops stale CDN intent; a config that\n // already combines local files with publishing keeps it.\n clearPublish:\n storage === 'local' &&\n (options.storage === 'local' ||\n configuredStorage !== 'local' ||\n !supportsCDN),\n // An explicit switch to the CDN stops later runs inferring local files.\n clearGtOutput: storage === 'cdn' && configuredOutput !== undefined,\n // An explicit format list replaces the configured selection.\n removeFiles: selectedFormats\n ? configuredFormats.filter(\n (format) => !selectedFormats.includes(format)\n )\n : undefined,\n };\n session.assertResolved();\n\n // Validate what will be written, and use it for every later step.\n const { projectId: _writtenProjectId, ...effectiveConfig } =\n mergeSetupConfig(existingConfig, configUpdate);\n const settings = await generateSettings(\n { config: configFilepath, ...(projectId && { projectId }) },\n cwd,\n { resolvedConfig: effectiveConfig }\n );\n // Runtime credentials only count for the project this setup uses; the\n // framework's project variable is the one paired with its dev key.\n const runtimeProjectId =\n process.env[getDevelopmentEnvNames(envFramework).projectId] ??\n resolveProjectId();\n const runtimeProjectMatches =\n runtimeProjectId === undefined || runtimeProjectId === settings.projectId;\n const credentialsSet =\n runtimeProjectMatches && areCredentialsSet(settings, envFramework);\n const credentialsOption =\n (storage === 'local' && buildTool?.devCredentialsOption) ||\n '--dev-credentials';\n // Creating credentials talks to GT as the signed-in user unless an API\n // key is set. A development key in .env.local never stands in. An\n // obsolete stored login counts as signed out, so signing in replaces it.\n const canAuthenticate = async () =>\n Boolean(settings.apiKey) ||\n (await hasLogin({ baseUrl: settings.baseUrl }).catch((error) => {\n if (\n error instanceof UserAuthError &&\n error.code === 'obsolete_credentials'\n )\n return false;\n throw error;\n }));\n const provision =\n !credentialsSet &&\n (credentialsOption === '--live-translations'\n ? await session.answer('--live-translations', {\n explicit: options.liveTranslations ?? options.devCredentials,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n 'Would you like to set up live development translations? This requires signing in or an API key.',\n defaultValue: false,\n }),\n })\n : await session.answer('--dev-credentials or --no-dev-credentials', {\n explicit: options.devCredentials,\n // Creating a key is never a default, so --defaults leaves this open.\n // The prompt names the sign-in so its Yes default is informed.\n ask: async () =>\n promptConfirm({\n message: (await canAuthenticate())\n ? 'Would you like to set up a project ID and hot-reload key in .env.local?'\n : 'Would you like to sign in to General Translation and set up a project ID and hot-reload key in .env.local?',\n defaultValue: true,\n }),\n })) === true;\n if (!runtimeProjectMatches && !provision) {\n session.reject(\n `The runtime credentials in the environment belong to project ${runtimeProjectId}, not ${settings.projectId}; pass --dev-credentials to replace them in .env.local`\n );\n }\n // An explicit ID is saved to gt.config.json when it replaces a\n // configured one or no new credentials will record it in .env.local.\n if (options.projectId && (existingConfig.projectId || !provision)) {\n configUpdate.projectId = options.projectId;\n }\n if (provision) {\n checkDevelopmentProjectInputs(\n session,\n settings,\n options,\n options.projectId\n ? '--project-id'\n : // An empty configured ID falls through to the environment.\n typeof existingConfig.projectId === 'string' &&\n existingConfig.projectId\n ? configFilepath\n : 'the environment'\n );\n await withCredentialsError(() =>\n inspectCredentialsEnvFile(cwd, { framework: envFramework })\n );\n }\n\n if (reactSetup && buildTool) await buildTool.preflight(cwd);\n const installGT =\n packageJson !== null &&\n !isPackageInstalled('gt', packageJson, true, true) &&\n !buildTool?.skipsGTInstall(isUsingGT);\n const packageManager =\n reactSetup?.install || installGT\n ? await resolvePackageManager(session, options.packageManager)\n : undefined;\n\n session.assertResolved();\n\n if (provision && !(await canAuthenticate())) {\n await signInForSetup(session, settings.baseUrl);\n }\n const project = provision\n ? await withCredentialsError(() =>\n resolveDevelopmentProject(session, settings, options, cwd)\n )\n : undefined;\n session.assertResolved();\n\n // ----- Changes start here ----- //\n const resolvedLocales = locales as string[];\n\n if (reactSetup) {\n logger.info(`${chalk.yellow('[EXPERIMENTAL]')} Configuring project...`);\n if (reactSetup.install && packageManager) {\n await installWithProgress(\n session,\n reactSetup.install,\n packageManager,\n false\n );\n }\n await executeReactSetup(session, reactSetup, options);\n logger.endCommand(\n `Done! Since this wizard is experimental, please review the changes and make modifications as needed.\n\\nNext step: start internationalizing! See the docs for more information: ${buildTool?.docsUrl ?? REACT_QUICKSTART_URL}`\n );\n logger.startCommand('Setting up project config...');\n }\n\n const reportManualAction = ({ whatHappened, fix }: ManualAction) => {\n session.humanActions.push(fix);\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened,\n fix,\n })\n );\n };\n const reportSetupResult = ({ steps, manualActions }: SetupResult) => {\n for (const step of steps) session.step(step);\n manualActions.forEach(reportManualAction);\n };\n const translationFilesError = (error: unknown) =>\n new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not create the translation files in ${translationsDir}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Choose another --translations-dir or fix the path, then rerun the command',\n })\n );\n const buildToolContext = {\n appDirectory: cwd,\n configFilepath,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n previousTranslationsDir: configuredTranslationsDir,\n };\n\n if (storage === 'local' && translationsDir) {\n if (buildTool && !reactSetup) {\n reportSetupResult(\n await buildTool\n .syncLoader({\n ...buildToolContext,\n translationsDir,\n keepAppSource: setup.keepAppSource,\n })\n .catch((error: unknown) => {\n throw translationFilesError(error);\n })\n );\n }\n const generatedLoader = this.shouldGenerateLocalTranslationLoader(\n buildTool?.ownsLoader ?? false,\n runtimeSetup\n );\n const loader = generatedLoader\n ? await createLoadTranslationsFile({\n appDirectory: cwd,\n translationsDir,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n previousTranslationsDir: configuredTranslationsDir,\n }).catch((error: unknown) => {\n throw translationFilesError(error);\n })\n : undefined;\n if (loader === 'created' || loader === 'updated') {\n session.step(`${loader} loadTranslations.js`);\n }\n // A loader left unchanged may not read the newly chosen directory.\n if (\n loader === 'custom' &&\n translationsDir !== configuredTranslationsDir\n ) {\n const loaderFile = path.relative(\n cwd,\n findLoadTranslationsFiles(cwd)[0] ?? 'loadTranslations.js'\n );\n reportManualAction({\n whatHappened: `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`,\n fix: `Update your custom ${loaderFile} to load translations from ${translationsDir}`,\n });\n }\n const guidance = this.getLocalTranslationGuidance({\n generatedLoader: generatedLoader && loader !== 'custom',\n runtimeSetup,\n translationsDir,\n });\n if (guidance) logger.message(guidance);\n } else if (\n storage === 'cdn' &&\n buildTool &&\n !reactSetup &&\n configuredTranslationsDir !== undefined\n ) {\n // Only the application setup rewrites the initializer; a loader passed\n // to it takes precedence over CDN loading.\n const action = await buildTool.getCDNStorageAction?.(buildToolContext);\n if (action !== null) {\n reportManualAction(\n action ?? {\n whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,\n fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`,\n }\n );\n }\n } else if (\n storage === 'cdn' &&\n !buildTool &&\n configuredTranslationsDir !== undefined\n ) {\n // gt-next uses a loadTranslations file whenever one exists, and a\n // loader passed to GTProvider takes precedence over the CDN. Name every\n // one: deleting only the first makes gt-next fall back to the next.\n const loaders = findLoadTranslationsFiles(cwd).map((loader) =>\n path.relative(cwd, loader)\n );\n if (loaders.length > 0) {\n const loaderFiles = loaders.join(', ');\n const [them, loads] =\n loaders.length === 1 ? ['it', 'loads'] : ['them', 'load'];\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${loaderFiles} still ${loads} them from ${configuredTranslationsDir}`,\n fix: `Delete ${loaderFiles}, and remove ${them} from your GT setup if you pass ${them} there, so translations load from the CDN`,\n });\n }\n }\n\n const configChange = await applySetupConfig(configFilepath, configUpdate);\n if (configChange !== 'unchanged') {\n session.step(`${configChange} ${configFilepath}`);\n }\n\n logger.success(\n `Edit ${chalk.cyan(\n configFilepath\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n if (reactSetup && buildTool) {\n reportSetupResult(await buildTool.apply(buildToolContext));\n }\n\n if (installGT && packageManager) {\n await installWithProgress(session, 'gt', packageManager, true);\n }\n\n if (project) {\n await withCredentialsError(() =>\n provisionDevelopmentCredentials(\n session,\n project,\n settings,\n envFramework,\n cwd\n )\n );\n logger.message(productionRuntimeKeyGuidance(settings.dashboardUrl));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,MAAM,oCAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,SAAS,0BACP,cACA,OACQ;AACR,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV;EACA,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,u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ArgumentError, Option } from 'commander';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n DEFAULT_TRANSLATIONS_DIR,\n REACT_QUICKSTART_URL,\n} from '../utils/constants.js';\nimport {\n applySetupConfig,\n mergeSetupConfig,\n type SetupConfigUpdate,\n} from '../fs/config/setupConfig.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport {\n displayHeader,\n promptText,\n logErrorAndExit,\n exitSync,\n promptConfirm,\n promptMultiSelect,\n promptSelect,\n promptGlobPatterns,\n} from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { lottieTranslateError } from '../console/index.js';\nimport { parseGlobPatterns } from '../console/promptParsing.js';\nimport path from 'node:path';\nimport {\n FilesOptions,\n Settings,\n SupportedFrameworks,\n SupportedLibraries,\n TranslateFlags,\n SharedFlags,\n} from '../types/index.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport chalk from 'chalk';\nimport {\n FILE_EXT_TO_EXT_LABEL,\n SETUP_FILE_FORMATS,\n SUPPORTED_FILE_EXTENSIONS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n executeReactSetup,\n resolveReactSetup,\n type ReactSetupPlan,\n} from '../setup/wizard.js';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { getDesiredLocales } from '../setup/userInput.js';\nimport {\n areCredentialsSet,\n getDevelopmentEnvNames,\n inspectCredentialsEnvFile,\n} from '../utils/credentials.js';\nimport {\n checkDevelopmentProjectInputs,\n productionRuntimeKeyGuidance,\n provisionDevelopmentCredentials,\n resolveDevelopmentProject,\n signInForSetup,\n} from '../setup/developmentCredentials.js';\nimport { exitIfUnsupportedSetupTarget } from '../setup/setupTarget.js';\nimport {\n asRecord,\n attachConfigureFlags,\n attachInitFlags,\n describeDefaults,\n displaySetupHeader,\n getConfiguredFramework,\n INIT_SOURCE_HELP,\n installWithProgress,\n OnboardingError,\n parseFilePatterns,\n readSetupConfig,\n reportJsonExitsBeforeOnboarding,\n resolvePackageManager,\n runOnboarding,\n setupConfigPath,\n validateSetupPattern,\n type ConfigureOptions,\n type InitOptions,\n type OnboardingSession,\n} from '../setup/onboarding.js';\nimport { upload } from './commands/upload.js';\nimport { attachSharedFlags, attachTranslateFlags } from './flags.js';\nimport { handleStage } from './commands/stage.js';\nimport { handleSetupProject } from './commands/setupProject.js';\nimport { handleDownload } from './commands/download.js';\nimport {\n handleTranslate,\n postProcessTranslations,\n} from './commands/translate.js';\nimport {\n getNeedsPostprocessing,\n clearDownloaded,\n} from '../state/recentDownloads.js';\nimport { clearWarnings } from '../state/translateWarnings.js';\nimport { displayTranslateSummary } from '../console/displayTranslateSummary.js';\nimport updateConfig from '../fs/config/updateConfig.js';\nimport {\n createLoadTranslationsFile,\n findLoadTranslationsFiles,\n} from '../fs/createLoadTranslationsFile.js';\nimport { saveLocalEdits } from '../api/saveLocalEdits.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './commands/utils/validation.js';\nimport processSharedStaticAssets, {\n mirrorAssetsToLocales,\n} from '../utils/sharedStaticAssets.js';\nimport { setupLocadex } from '../locadex/setupFlow.js';\nimport { detectFramework } from '../setup/detectFramework.js';\nimport { INLINE_LIBRARIES, Libraries } from '../types/libraries.js';\nimport { handleEnqueue } from './commands/enqueue.js';\nimport { splitMintlifyLanguageRefs } from '../utils/splitMintlifyLanguageRefs.js';\nimport { localizeMintlifyRedirects } from '../formats/files/postprocess/localizeMintlifyRedirects.js';\nimport {\n clearOrphanedFileNames,\n getOrphanedFileNames,\n} from '../state/orphanedFileNames.js';\nimport { runMergeDriver, type MergeDriverName } from '../git/mergeDrivers.js';\nimport { setupGitMergeDrivers } from '../git/setupMergeDrivers.js';\nimport { warnReactPackageCompatibility } from '../utils/reactPackageCompatibility.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { hasLogin, logout, whoAmI } from '../auth/oauth.js';\nimport { createUserAuthError, UserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { resolveConfig } from '../config/resolveConfig.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport {\n getBuildToolSetup,\n type ManualAction,\n type SetupResult,\n} from '../setup/buildTools/index.js';\nimport { manifestDirectlyDeclaresGTVue } from '@generaltranslation/vue-extractor/integration';\nimport { api } from '../utils/api.js';\nimport { handleApiCommand, type ApiCommandOptions } from './commands/api.js';\n\nconst ID_COMPATIBILITY_WARNING_COMMANDS = new Set([\n 'download',\n 'enqueue',\n 'generate',\n 'setup',\n 'stage',\n 'translate',\n 'validate',\n]);\nfunction createProjectCommandError(\n whatHappened: string,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened,\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst emptyApiKeyNameError = createDiagnosticMessage({\n whatHappened: 'The key name cannot be empty',\n fix: 'Pass a non-empty value with --name',\n});\n\nfunction parseApiKeyName(value: string): string {\n const name = value.trim();\n if (!name) throw new InvalidArgumentError(emptyApiKeyNameError);\n return name;\n}\n\n/** Credential failures keep their own diagnostic or get the setup context. */\nasync function withCredentialsError<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof OnboardingError) throw error;\n throw new Error(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError(\n 'Failed to set up the development credentials',\n error\n )\n );\n }\n}\n\nexport type UploadOptions = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n defaultLocale?: string;\n};\n\nexport type GitSetupOptions = {\n config?: string;\n dryRun?: boolean;\n omitConfigIds?: boolean;\n driverCommand?: string;\n};\n\ntype LocalTranslationGuidanceOptions = {\n generatedLoader: boolean;\n runtimeSetup: InlineRuntimeSetup;\n translationsDir: string;\n};\n\ntype InlineRuntimeSetup = {\n hasOtherInlineRuntime: boolean;\n hasVueRuntime: boolean;\n ranReactSetup: boolean;\n};\n\nexport class BaseCLI {\n protected library: SupportedLibraries;\n protected additionalModules: SupportedLibraries[];\n protected program: Command;\n // Constructor is shared amongst all CLI class types\n public constructor(\n program: Command,\n library: SupportedLibraries,\n additionalModules?: SupportedLibraries[]\n ) {\n this.program = program;\n this.library = library;\n this.additionalModules = additionalModules || [];\n\n this.program.option(\n '--skip-version-check',\n 'Skip the monorepo GT package version consistency check'\n );\n this.program.option(\n '--suppress-id-compatibility-warning',\n 'Suppress the React package ID compatibility warning'\n );\n this.program.option(\n '-q, --quiet',\n 'Suppress informational output; only warnings and errors are shown'\n );\n // Select console routing for this command before anything else logs:\n // root hooks run before subclass hooks (version checks) and the action's\n // settings resolution. `gt api-key create` prints the new secret on\n // stdout, so its diagnostics go to stderr, as do setup commands writing\n // JSON events; every other command gets the historical default back\n // (main() routes startup output to stderr).\n this.program.hook('preAction', (thisCommand, actionCommand) => {\n logger.setConsoleOutput(\n actionCommand.parent?.name() === 'api-key' || actionCommand.opts().json\n ? 'stderr'\n : 'stdout'\n );\n if (\n actionCommand.opts().json &&\n actionCommand.parent === thisCommand &&\n ['init', 'configure'].includes(actionCommand.name())\n ) {\n reportJsonExitsBeforeOnboarding(actionCommand.name());\n }\n });\n // Apply --quiet before any other hook or command action runs so the\n // singleton logger is muted for the rest of the invocation. The flag is a\n // global root option, so commander resolves it in any position and for\n // nested commands (e.g. `gt git setup --quiet`).\n this.program.hook('preAction', () => {\n logger.setQuiet(Boolean(this.program.opts().quiet));\n });\n this.program.hook('preAction', async (thisCommand, actionCommand) => {\n // Nested commands (e.g. `gt git setup`) can share leaf names with\n // translation commands; only direct children of the root qualify\n if (actionCommand.parent !== thisCommand) return;\n if (!ID_COMPATIBILITY_WARNING_COMMANDS.has(actionCommand.name())) return;\n await warnReactPackageCompatibility(\n Boolean(this.program.opts().suppressIdCompatibilityWarning)\n );\n });\n\n this.setupInitCommand();\n this.setupConfigureCommand();\n this.setupUploadCommand();\n this.setupUserAuthCommands();\n this.setupSendDiffsCommand();\n this.setupApiCommand();\n this.setupProjectCommands();\n this.setupApiKeyCommands();\n this.setupGitCommand();\n }\n // Init is never called in a child class\n public init() {\n this.setupSetupProjectCommand();\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n // Execute is called by the main program\n public execute() {\n // If no command is specified, run 'init'\n if (process.argv.length <= 2) {\n process.argv.push('init');\n }\n }\n\n protected setupSetupProjectCommand(): void {\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupStageCommand(): void {\n attachTranslateFlags(\n this.program\n .command('stage')\n .description(\n 'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupEnqueueCommand(): void {\n attachTranslateFlags(\n this.program\n .command('enqueue')\n .description('Enqueues translations for a given set of files')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Enqueuing translations...');\n await this.handleEnqueue(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupDownloadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('download')\n .description('Download translations that were originally staged')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Downloading translations...');\n await this.handleDownload(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachTranslateFlags(\n this.program\n .command('translate')\n .description('Translate your project using General Translation')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Starting translation...');\n await this.handleTranslate(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupSendDiffsCommand(): void {\n attachSharedFlags(\n this.program\n .command('save-local')\n .description(\n 'Save local edits for all configured files by sending diffs (no translation enqueued)'\n )\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .action(async (initOptions: SharedFlags) => {\n displayHeader('Saving local edits...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n await saveLocalEdits(settings);\n logger.endCommand('Saved local edits');\n });\n }\n\n protected setupApiCommand(): void {\n attachSharedFlags(\n this.program\n .command('api [endpoint]')\n .description('Make an authenticated request to the GT API')\n .option('-X, --method <method>', 'HTTP method', 'GET')\n .option('--input <file>', 'Request body file, or - for standard input')\n .option(\n '-H, --header <header>',\n 'Request header in \"Key: Value\" format',\n (header, headers: string[] | undefined) => [\n ...(headers ?? []),\n header,\n ]\n )\n .option('-i, --include', 'Include response status and headers')\n .option(\n '--spec',\n 'Print the bundled OpenAPI specification, or only the operations matching [endpoint] (path or operation ID) with references resolved'\n )\n .addOption(\n new Option(\n '--list',\n 'List the method, path, operation ID, and summary of every API operation'\n ).conflicts('spec')\n )\n ).action((endpoint, options: ApiCommandOptions) =>\n handleApiCommand(endpoint, options)\n );\n }\n\n protected setupProjectCommands(): void {\n const projectCommand = this.program\n .command('project')\n .description('Manage General Translation projects');\n\n attachSharedFlags(\n projectCommand\n .command('create')\n .description(\n 'Create a General Translation project using an organization API key'\n )\n .requiredOption('--org-id <orgId>', 'Organization ID')\n .requiredOption('--name <name>', 'Project name')\n .requiredOption('--default-locale <locale>', 'Project default locale')\n .option('--cdn-enabled', 'Enable CDN delivery', false)\n ).action(async (options) => {\n try {\n const settings = await generateSettings(options);\n // Project creation happens before a project ID exists.\n if (!hasValidServiceLocales(settings)) return exitSync(1);\n const { project } = await api.createProject(options.orgId, {\n name: options.name,\n defaultLocale: options.defaultLocale,\n cdnEnabled: options.cdnEnabled,\n });\n logger.info(`Created ${project.name} (${project.id})`);\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError('Failed to create the project', error)\n );\n }\n });\n\n attachSharedFlags(\n projectCommand\n .command('status')\n .description('Check the status of a project setup job')\n .argument('<job-id>', 'Setup job ID')\n ).action(async (jobId, options) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const [status] = await api.checkJobStatus([jobId]);\n logger.info(status?.status ?? 'unknown');\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError(\n 'Failed to check the project setup status',\n error\n )\n );\n }\n });\n }\n\n protected setupApiKeyCommands(): void {\n const apiKeyCommand = this.program\n .command('api-key')\n .description('Manage API keys for the configured project');\n\n attachSharedFlags(\n apiKeyCommand\n .command('create')\n .description(\n 'Create a project API key with the requested permissions and print it once'\n )\n .requiredOption('--name <name>', 'Key name', parseApiKeyName)\n // Validated before any request; the server grants the requested set\n // all-or-nothing, so omitting permissions would delegate everything.\n .addOption(\n new Option('--permission <permissions...>', 'Permissions to grant')\n .choices(Object.values(ProjectApiKeyPermission))\n .makeOptionMandatory()\n )\n ).action(\n async (\n options: SharedFlags & {\n name: string;\n permission: ProjectApiKeyPermission[];\n }\n ) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const { apiKey } = await api.createProjectApiKey(settings.projectId, {\n name: options.name,\n permissions: options.permission,\n });\n // Raw stdout: the secret is shown once and never reaches the log file.\n process.stdout.write(`${apiKey.key}\\n`);\n } catch (error) {\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError('Failed to create the API key', error)\n );\n }\n }\n );\n }\n\n protected setupGitCommand(): void {\n const gitCommand = this.program\n .command('git')\n .description('Configure Git integrations for General Translation');\n\n gitCommand\n .command('setup')\n .description('Set up GT merge drivers for generated translation files')\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--dry-run', 'Print changes without writing files', false)\n .option(\n '--omit-config-ids',\n 'Persist omitConfigIds and remove generated config IDs'\n )\n .option(\n '--driver-command <command>',\n 'Command Git should use to invoke gt, e.g. \"pnpm exec gt\"'\n )\n .action(async (options: GitSetupOptions) => {\n displayHeader('Setting up GT Git merge drivers...');\n const settings = await generateSettings(options, undefined, {\n requireConfig: true,\n });\n const omitConfigIds = await this.resolveGitSetupOmitConfigIds(\n options,\n settings\n );\n const result = await setupGitMergeDrivers(settings, {\n dryRun: options.dryRun,\n omitConfigIds,\n driverCommand: options.driverCommand,\n });\n\n for (const line of result.addedAttributes) {\n logger.step(\n `${options.dryRun ? 'Would add' : 'Added'} ${chalk.cyan(\n line\n )} to ${chalk.cyan(result.gitattributesPath)}`\n );\n }\n if (result.addedAttributes.length === 0) {\n logger.info(`${chalk.cyan('.gitattributes')} is already configured.`);\n }\n\n for (const args of result.gitConfigCommands) {\n logger.step(\n `${options.dryRun ? 'Would run' : 'Configured'} ${chalk.cyan(\n `git config --local ${args.join(' ')}`\n )}`\n );\n }\n\n if (result.updatedConfig) {\n logger.step(\n `${options.dryRun ? 'Would persist' : 'Persisted'} ${chalk.cyan(\n 'omitConfigIds: true'\n )} in ${chalk.cyan(settings.config)}`\n );\n } else if (options.dryRun && !settings.omitConfigIds) {\n logger.info(\n `Run without ${chalk.cyan('--dry-run')} to be prompted to persist ${chalk.cyan(\n 'omitConfigIds: true'\n )}, or pass ${chalk.cyan('--omit-config-ids')}.`\n );\n }\n\n for (const warning of result.warnings) {\n logger.warn(chalk.yellow(warning));\n }\n\n logger.endCommand(\n options.dryRun\n ? 'Dry run complete.'\n : 'GT Git merge drivers configured.'\n );\n });\n\n gitCommand\n .command('merge-driver', { hidden: true })\n .addArgument(\n new Argument('<driver>', 'Merge driver name').choices([\n 'gt-lock',\n 'gtjson',\n ])\n )\n .argument('<base>', 'Common ancestor file')\n .argument('<ours>', 'Current branch file')\n .argument('<theirs>', 'Incoming branch file')\n .argument('[path]', 'Merged path')\n .action(\n (\n driver: MergeDriverName,\n base: string,\n ours: string,\n theirs: string\n ) => {\n const result = runMergeDriver(driver, base, ours, theirs);\n if (!result.ok) {\n logger.error(result.reason);\n exitSync(1);\n }\n }\n );\n }\n\n protected async resolveGitSetupOmitConfigIds(\n options: GitSetupOptions,\n settings: Settings\n ): Promise<boolean> {\n if (options.omitConfigIds) return true;\n // Already opted in: persist again so stale config IDs still get removed\n if (settings.omitConfigIds) return true;\n if (options.dryRun || !process.stdin.isTTY || !process.stdout.isTTY) {\n return false;\n }\n return promptConfirm({\n message:\n 'Also set omitConfigIds: true to reduce gt.config.json merge conflicts?',\n defaultValue: true,\n });\n }\n\n protected async handleSetupProject(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n await handleSetupProject(initOptions, settings, this.library);\n }\n\n protected async handleStage(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Update settings.stageTranslations to true\n settings.stageTranslations = true;\n await updateConfig(settings.config, {\n stageTranslations: true,\n });\n }\n await handleStage(initOptions, settings, this.library, true);\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleEnqueue(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleEnqueue(initOptions, settings, this.library);\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleDownload(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleDownload(initOptions, settings, this.library);\n await this.finalizeDownloadedTranslations(settings);\n }\n\n protected async handleTranslate(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Lottie translations finish asynchronously server-side (layout\n // refinement runs after the translation job completes), so the immediate\n // translate flow would try to download them before they're ready. Only\n // the stage + download flow supports them.\n if (settings.files?.resolvedPaths.lottie?.length) {\n return logErrorAndExit(lottieTranslateError);\n }\n const results = await handleStage(\n initOptions,\n settings,\n this.library,\n false\n );\n if (results) {\n await handleTranslate(\n initOptions,\n settings,\n results.fileVersionData,\n results.jobData,\n results.branchData,\n results.publishMap,\n results.inlineLibrary\n );\n }\n } else {\n await handleDownload(initOptions, settings, this.library);\n }\n await this.finalizeDownloadedTranslations(settings);\n }\n\n /**\n * Postprocesses the translations downloaded in this run and reports the\n * summary. Shared by translate and download so both write the same output.\n * @param settings - The settings for the command\n */\n protected async finalizeDownloadedTranslations(\n settings: Settings\n ): Promise<void> {\n // Only postprocess files downloaded in this run\n const include = getNeedsPostprocessing();\n if (include.size > 0) {\n await postProcessTranslations(settings, include);\n }\n // Split Mintlify language entries into $ref files to keep docs.json small\n await splitMintlifyLanguageRefs(settings);\n // Localize redirects for pages this run renamed or removed. Runs after the\n // split, which can rewrite $ref files such as redirects.json\n const orphanedFileNames = getOrphanedFileNames();\n if (orphanedFileNames) {\n const added = localizeMintlifyRedirects(settings, orphanedFileNames);\n if (added.length > 0) {\n logger.success(\n `Added ${added.length} localized redirect${added.length === 1 ? '' : 's'}`\n );\n }\n }\n clearOrphanedFileNames();\n // Mirror assets after translations are downloaded and locale dirs are populated\n await mirrorAssetsToLocales(settings);\n clearDownloaded();\n displayTranslateSummary();\n clearWarnings();\n }\n\n protected setupUploadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('upload')\n .description(\n 'Upload source files and translations to the General Translation platform'\n )\n ).action(async (initOptions: UploadOptions) => {\n displayHeader('Starting upload...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const options = { ...initOptions, ...settings };\n\n await this.handleUploadCommand(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupUserAuthCommands(): void {\n this.program\n .command('login')\n .description('Sign in to your General Translation account')\n .option(\n '--no-browser',\n 'Do not open a browser; show a sign-in URL to use on any device instead'\n )\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json'\n )\n .action(async (options: { browser: boolean; config?: string }) => {\n displayHeader('Signing in to General Translation...');\n try {\n // Tokens are bound to one API resource, so log in to the configured one.\n const baseUrl = (\n options.config\n ? loadConfig(withJsonExtension(options.config))\n : resolveConfig(process.cwd())?.config\n )?.baseUrl;\n await loginInteractively(\n typeof baseUrl === 'string' ? baseUrl : undefined,\n options.browser\n );\n logger.endCommand('You are now signed in.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign in failed', error));\n }\n });\n\n this.program\n .command('logout')\n .description('Sign out of your General Translation account')\n .action(async () => {\n try {\n await logout();\n logger.endCommand('Signed out successfully.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign out failed', error));\n }\n });\n\n this.program\n .command('whoami')\n .description('Show the signed-in General Translation account')\n .action(async () => {\n try {\n const user = await whoAmI();\n logger.message(user.email ?? user.name ?? user.sub);\n } catch (error) {\n logErrorAndExit(\n createUserAuthError('Could not load your account', error)\n );\n }\n });\n }\n\n protected setupInitCommand(): void {\n attachInitFlags(\n this.program\n .command('init')\n .description(\n 'Run the setup wizard to configure your project for General Translation. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: InitOptions) => this.handleInitWizard(options));\n }\n\n protected async handleInitWizard(options: InitOptions): Promise<void> {\n await runOnboarding('init', options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Running setup wizard...');\n\n const detected = await detectFramework();\n const reactDetected = detected.type === 'react' ? detected : undefined;\n if (options.framework && !reactDetected) {\n session.reject(\n '--framework applies only to projects detected as React applications'\n );\n }\n const configFilepath = setupConfigPath(options);\n const configured = getConfiguredFramework(\n readSetupConfig(configFilepath)\n );\n const configuredReact =\n configured !== 'mintlify' ? configured : undefined;\n // Explicit --defaults / --no-defaults also answer the Locadex gate.\n if (options.defaults !== undefined) session.defaults = options.defaults;\n const gateFramework = options.framework ?? configured ?? detected.name;\n if (gateFramework === 'mintlify' || gateFramework === 'next-app') {\n const useLocadex = await session.answer('--locadex', {\n explicit: options.locadex,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n gateFramework === 'mintlify'\n ? `Mintlify project detected. Would you like to connect to GitHub so that the Locadex AI Agent can translate your project automatically?`\n : `Next.js App Router detected. Would you like to connect to GitHub so that the Locadex AI Agent can set up your project automatically?`,\n defaultValue: false,\n }),\n });\n if (useLocadex) {\n session.assertResolved();\n const url = await setupLocadex(\n await generateSettings({ config: options.config }),\n { openBrowser: session.interactive }\n );\n session.emit({ type: 'handoff', url, reason: 'locadex' });\n logger.endCommand(\n 'Once installed, Locadex will open a PR to your repository. See the docs for more information: https://generaltranslation.com/docs/locadex'\n );\n return { outcome: 'needs_human_action', url };\n }\n } else if (options.locadex) {\n session.reject(\n '--locadex applies only to Mintlify and Next.js App Router projects'\n );\n }\n\n const shownFramework = reactDetected && {\n ...reactDetected,\n name: options.framework ?? configuredReact ?? reactDetected.name,\n };\n // Without --defaults, a noninteractive run uses no defaults.\n session.defaults =\n (await session.answer('--defaults', {\n explicit: options.defaults,\n fallback: false,\n ask: () =>\n promptConfirm({\n message: `Would you like to use the recommended General Translation defaults? ${chalk.dim(`(${describeDefaults(shownFramework)})`)}`,\n defaultValue: true,\n }),\n })) === true;\n\n const reactSetup = reactDetected\n ? await resolveReactSetup(\n session,\n options,\n reactDetected,\n configuredReact\n )\n : undefined;\n // flag > gt.config.json > detection, used for every later step.\n const framework =\n reactSetup?.framework ??\n options.framework ??\n configured ??\n detected.name;\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n saveFramework: Boolean(reactSetup || options.framework),\n reactSetup,\n keepAppSource: !reactSetup,\n });\n\n logger.endCommand(\n 'Done! Check out our docs for more information on how to use General Translation: https://generaltranslation.com/docs'\n );\n return { outcome: 'success' };\n });\n }\n\n protected setupConfigureCommand(): void {\n attachConfigureFlags(\n this.program\n .command('configure')\n .description(\n 'Configure your project for General Translation. This will create a gt.config.json file in your codebase. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: ConfigureOptions) =>\n this.handleConfigureCommand(options)\n );\n }\n\n protected async handleConfigureCommand(\n options: ConfigureOptions,\n command: string = 'configure'\n ): Promise<void> {\n await runOnboarding(command, options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Configuring project...');\n\n logger.info(\n 'Welcome! This tool will help you configure your gt.config.json file. See the docs: https://generaltranslation.com/docs/cli/reference/config for more information.'\n );\n\n // Configure only offers the defaults when asked with --defaults.\n session.defaults = options.defaults ?? false;\n const detected = await detectFramework();\n const configFilepath = setupConfigPath(options);\n // Detection only picks env names here; it is not saved.\n const framework =\n getConfiguredFramework(readSetupConfig(configFilepath)) ??\n detected.name;\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n });\n\n logger.endCommand(\n 'Done! Make sure you have an API key and project ID to use General Translation. Get them on the dashboard: https://generaltranslation.com/dashboard'\n );\n return { outcome: 'success' };\n });\n }\n\n protected async handleUploadCommand(\n settings: Settings & UploadOptions\n ): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n // Process all file types at once with a single call\n await upload(settings);\n }\n\n /** Describes installed runtimes without changing historical package lookup. */\n protected getInlineRuntimeSetup(\n packageJson: Record<string, unknown>,\n ranReactSetup: boolean = false\n ): InlineRuntimeSetup {\n return {\n hasOtherInlineRuntime: INLINE_LIBRARIES.some(\n (lib) =>\n lib !== Libraries.GT_VUE && isPackageInstalled(lib, packageJson)\n ),\n hasVueRuntime: manifestDirectlyDeclaresGTVue(packageJson),\n ranReactSetup,\n };\n }\n\n /** Returns whether any inline runtime is installed for setup. */\n protected isInlineRuntimeInstalled(\n packageJson: Record<string, unknown>\n ): boolean {\n const { hasOtherInlineRuntime, hasVueRuntime } =\n this.getInlineRuntimeSetup(packageJson);\n return hasOtherInlineRuntime || hasVueRuntime;\n }\n\n /** Returns whether every installed runtime can consume CDN translations. */\n protected supportsCDNStorage(runtimeSetup: InlineRuntimeSetup): boolean {\n return !runtimeSetup.hasVueRuntime;\n }\n\n /** Returns whether setup should generate a local runtime loader. */\n protected shouldGenerateLocalTranslationLoader(\n buildToolOwnsLoader: boolean,\n runtimeSetup: InlineRuntimeSetup\n ): boolean {\n if (buildToolOwnsLoader) return false;\n if (!runtimeSetup.hasVueRuntime) return true;\n return runtimeSetup.hasOtherInlineRuntime || runtimeSetup.ranReactSetup;\n }\n\n /** Returns framework guidance after selecting local translation storage. */\n protected getLocalTranslationGuidance({\n generatedLoader,\n runtimeSetup,\n translationsDir,\n }: LocalTranslationGuidanceOptions): string | undefined {\n const guidance: string[] = [];\n if (generatedLoader) {\n guidance.push(`Created ${chalk.cyan('loadTranslations.js')} file for local translations.\nMake sure to add this function to your app configuration.\nSee https://generaltranslation.com/en/docs/next/guides/local-tx`);\n }\n if (runtimeSetup.hasVueRuntime) {\n guidance.push(`GT will write local translation files to ${translationsDir}.\nConfigure createGT({ loadTranslations }) to load files from that directory.\nSee https://www.npmjs.com/package/gt-vue`);\n }\n return guidance.length > 0 ? guidance.join('\\n') : undefined;\n }\n\n /**\n * Resolves every configuration answer and validates the resulting config,\n * checks the project and signs in before the first change, then applies\n * the React setup, gt.config.json, installs and development credentials.\n */\n protected async handleInitCommand(\n session: OnboardingSession,\n options: ConfigureOptions,\n setup: {\n /** Chosen once by the entry point from the detected framework. */\n configFilepath: string;\n /** Resolved framework; drives storage, env names and build-tool setup. */\n framework?: SupportedFrameworks;\n /** Write the framework even when no build-tool setup saves it. */\n saveFramework?: boolean;\n reactSetup?: ReactSetupPlan;\n /** Init without the React setup never changes application source. */\n keepAppSource?: boolean;\n }\n ): Promise<void> {\n const { configFilepath, reactSetup } = setup;\n const buildTool = getBuildToolSetup(setup.framework);\n const cwd = process.cwd();\n const existingConfig = readSetupConfig(configFilepath);\n const { defaultLocale, locales } = await getDesiredLocales(\n session,\n existingConfig,\n options\n );\n\n const packageJson =\n reactSetup?.packageJson ?? (await searchForPackageJson());\n const runtimeSetup: InlineRuntimeSetup = packageJson\n ? this.getInlineRuntimeSetup(packageJson, Boolean(reactSetup))\n : {\n hasOtherInlineRuntime: false,\n hasVueRuntime: false,\n ranReactSetup: false,\n };\n const isUsingGT =\n runtimeSetup.ranReactSetup ||\n runtimeSetup.hasOtherInlineRuntime ||\n runtimeSetup.hasVueRuntime;\n const supportsCDN = this.supportsCDNStorage(runtimeSetup);\n const existingFiles = asRecord(existingConfig.files) ?? {};\n const existingGtOutput = asRecord(existingFiles.gt)?.output;\n const configuredOutput =\n typeof existingGtOutput === 'string' ? existingGtOutput : undefined;\n const configuredStorage = configuredOutput\n ? 'local'\n : existingConfig.publish === true\n ? 'cdn'\n : undefined;\n\n if (isUsingGT && !supportsCDN && options.storage === 'cdn') {\n session.reject(\n 'gt-vue cannot load translations from the CDN; use --storage local'\n );\n }\n // Where GT translations are stored\n const storage = !isUsingGT\n ? undefined\n : !supportsCDN\n ? 'local'\n : await session.answer<'local' | 'cdn'>('--storage', {\n explicit: options.storage,\n configured: configuredStorage,\n recommended: 'local',\n ask: () =>\n promptSelect<'local' | 'cdn'>({\n message: `Would you like to save translation files locally or use the General Translation CDN to store them?`,\n options: [\n { value: 'local', label: 'Save locally' },\n { value: 'cdn', label: 'Use CDN' },\n ],\n defaultValue: 'local',\n }),\n });\n\n const defaultTranslationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n const outputMatch = configuredOutput?.match(\n /^(?:(.+)[\\\\/])?\\[locale\\]\\.json$/\n );\n const configuredTranslationsDir = outputMatch\n ? (outputMatch[1] ?? '.')\n : undefined;\n const translationsDir =\n storage === 'local'\n ? await session.answer('--translations-dir', {\n explicit: options.translationsDir?.trim() || undefined,\n configured: configuredTranslationsDir,\n recommended: defaultTranslationsDir,\n ask: async () =>\n (\n await promptText({\n message:\n 'What is the path to the directory where you would like to store your translation files?',\n defaultValue: defaultTranslationsDir,\n })\n ).trim() || defaultTranslationsDir,\n })\n : undefined;\n\n const filePatterns = parseFilePatterns(session, options.filePatterns);\n const selectedFormats = options.fileFormats?.filter(\n (format): format is SetupFileFormat => format !== 'none'\n );\n if (\n options.fileFormats?.includes('none') &&\n (selectedFormats?.length ?? 0) > 0\n ) {\n session.reject('--file-formats none cannot be combined with formats');\n }\n const configuredFormats = SETUP_FILE_FORMATS.filter(\n (format) => format in existingFiles\n );\n // Formats setup does not offer stay as configured and count as files.\n const otherFormats = SUPPORTED_FILE_EXTENSIONS.filter(\n (format) =>\n format in existingFiles &&\n !(SETUP_FILE_FORMATS as readonly string[]).includes(format)\n );\n const hasOtherFormats = otherFormats.length > 0;\n if (options.fileFormats && hasOtherFormats) {\n const kept = otherFormats.map((format) => `files.${format}`).join(', ');\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `${kept} stays in ${configFilepath}`,\n why: '--file-formats only changes the formats setup offers',\n fix: `Remove ${kept} from ${configFilepath} to stop translating those files`,\n })\n );\n }\n const fileFormats = await session.answer<SetupFileFormat[]>(\n '--file-formats',\n {\n explicit:\n selectedFormats ??\n (filePatterns.size > 0 ? [...filePatterns.keys()] : undefined),\n configured:\n configuredFormats.length > 0 || hasOtherFormats\n ? configuredFormats\n : undefined,\n // GT projects need no other files; others must choose a format.\n recommended: isUsingGT ? [] : undefined,\n ask: () =>\n promptMultiSelect({\n message: !isUsingGT\n ? 'What is the format of your language resource files? Select as many as applicable.\\nAdditionally, you can translate any other files you have in your project.'\n : `Do you have any additional files in this project to translate? For example, Markdown files for docs. ${chalk.dim(\n '(To continue without selecting press Enter)'\n )}`,\n options: SETUP_FILE_FORMATS.map((format) => ({\n value: format,\n label: FILE_EXT_TO_EXT_LABEL[format],\n })),\n required: !isUsingGT,\n }),\n }\n );\n if (\n fileFormats &&\n fileFormats.length === 0 &&\n !isUsingGT &&\n !hasOtherFormats\n ) {\n session.reject(\n 'No GT runtime is installed, so select at least one file format to translate'\n );\n }\n for (const format of filePatterns.keys()) {\n if (fileFormats && !fileFormats.includes(format)) {\n session.reject(\n `--file-patterns ${format}= needs ${format} in --file-formats`\n );\n }\n }\n\n const files: FilesOptions = {};\n for (const fileExtension of fileFormats ?? []) {\n const existingFormat = asRecord(existingFiles[fileExtension]);\n const configuredInclude = Array.isArray(existingFormat?.include)\n ? (existingFormat.include as string[])\n : undefined;\n const include = await session.answer(\n `--file-patterns ${fileExtension}=<glob>`,\n {\n explicit: filePatterns.get(fileExtension),\n configured: configuredInclude,\n recommended: [`./**/[locale]/*.${fileExtension}`],\n ask: async () =>\n parseGlobPatterns(\n await promptGlobPatterns({\n label: FILE_EXT_TO_EXT_LABEL[fileExtension],\n message: `${chalk.cyan(FILE_EXT_TO_EXT_LABEL[fileExtension])}: Enter a space-separated list of glob patterns matching the location of the ${FILE_EXT_TO_EXT_LABEL[fileExtension]} files you would like to translate.\\nMake sure to include [locale] in the patterns.\\nSee https://generaltranslation.com/docs/cli/reference/config#include for more information.`,\n defaultValue: `./**/[locale]/*.${fileExtension}`,\n validate: (value) =>\n parseGlobPatterns(value)\n .map(validateSetupPattern)\n .find((problem) => problem !== true) ?? true,\n })\n ),\n }\n );\n // Configured patterns stay untouched; new ones keep other entry options.\n if (include && include !== configuredInclude) {\n files[fileExtension] = { ...existingFormat, include };\n }\n }\n if (translationsDir && translationsDir !== configuredTranslationsDir) {\n files.gt = { output: path.join(translationsDir, `[locale].json`) };\n }\n\n const envFramework =\n setup.framework ?? getConfiguredFramework(existingConfig);\n // The effective project: an explicit ID replaces a configured one. The\n // framework's runtime project outranks a stale generic GT_PROJECT_ID.\n const projectId =\n options.projectId ||\n (typeof existingConfig.projectId === 'string'\n ? existingConfig.projectId\n : undefined) ||\n process.env[getDevelopmentEnvNames(envFramework).projectId];\n const configUpdate: SetupConfigUpdate = {\n defaultLocale,\n locales,\n src: options.src,\n files: Object.keys(files).length > 0 ? files : undefined,\n framework:\n (setup.saveFramework && setup.framework) || buildTool?.framework,\n publish: storage === 'cdn',\n // Selecting local storage drops stale CDN intent; a config that\n // already combines local files with publishing keeps it.\n clearPublish:\n storage === 'local' &&\n (options.storage === 'local' ||\n configuredStorage !== 'local' ||\n !supportsCDN),\n // An explicit switch to the CDN stops later runs inferring local files.\n clearGtOutput: storage === 'cdn' && configuredOutput !== undefined,\n // An explicit format list replaces the configured selection.\n removeFiles: selectedFormats\n ? configuredFormats.filter(\n (format) => !selectedFormats.includes(format)\n )\n : undefined,\n };\n session.assertResolved();\n\n // Validate what will be written, and use it for every later step.\n const { projectId: _writtenProjectId, ...effectiveConfig } =\n mergeSetupConfig(existingConfig, configUpdate);\n const settings = await generateSettings(\n { config: configFilepath, ...(projectId && { projectId }) },\n cwd,\n { resolvedConfig: effectiveConfig }\n );\n // Runtime credentials only count for the project this setup uses; the\n // framework's project variable is the one paired with its dev key.\n const runtimeProjectId =\n process.env[getDevelopmentEnvNames(envFramework).projectId] ??\n resolveProjectId();\n const runtimeProjectMatches =\n runtimeProjectId === undefined || runtimeProjectId === settings.projectId;\n const credentialsSet =\n runtimeProjectMatches && areCredentialsSet(settings, envFramework);\n const credentialsOption =\n (storage === 'local' && buildTool?.devCredentialsOption) ||\n '--dev-credentials';\n // Creating credentials talks to GT as the signed-in user unless an API\n // key is set. A development key in .env.local never stands in. An\n // obsolete stored login counts as signed out, so signing in replaces it.\n const canAuthenticate = async () =>\n Boolean(settings.apiKey) ||\n (await hasLogin({ baseUrl: settings.baseUrl }).catch((error) => {\n if (\n error instanceof UserAuthError &&\n error.code === 'obsolete_credentials'\n )\n return false;\n throw error;\n }));\n const provision =\n !credentialsSet &&\n (credentialsOption === '--live-translations'\n ? await session.answer('--live-translations', {\n explicit: options.liveTranslations ?? options.devCredentials,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n 'Would you like to set up live development translations? This requires signing in or an API key.',\n defaultValue: false,\n }),\n })\n : await session.answer('--dev-credentials or --no-dev-credentials', {\n explicit: options.devCredentials,\n // Creating a key is never a default, so --defaults leaves this open.\n // The prompt names the sign-in so its Yes default is informed.\n ask: async () =>\n promptConfirm({\n message: (await canAuthenticate())\n ? 'Would you like to set up a project ID and hot-reload key in .env.local?'\n : 'Would you like to sign in to General Translation and set up a project ID and hot-reload key in .env.local?',\n defaultValue: true,\n }),\n })) === true;\n if (!runtimeProjectMatches && !provision) {\n session.reject(\n `The runtime credentials in the environment belong to project ${runtimeProjectId}, not ${settings.projectId}; pass --dev-credentials to replace them in .env.local`\n );\n }\n // An explicit ID is saved to gt.config.json when it replaces a\n // configured one or no new credentials will record it in .env.local.\n if (options.projectId && (existingConfig.projectId || !provision)) {\n configUpdate.projectId = options.projectId;\n }\n if (provision) {\n checkDevelopmentProjectInputs(\n session,\n settings,\n options,\n options.projectId\n ? '--project-id'\n : // An empty configured ID falls through to the environment.\n typeof existingConfig.projectId === 'string' &&\n existingConfig.projectId\n ? configFilepath\n : 'the environment'\n );\n await withCredentialsError(() =>\n inspectCredentialsEnvFile(cwd, { framework: envFramework })\n );\n }\n\n if (reactSetup && buildTool) await buildTool.preflight(cwd);\n const installGT =\n packageJson !== null &&\n !isPackageInstalled('gt', packageJson, true, true) &&\n !buildTool?.skipsGTInstall(isUsingGT);\n const packageManager =\n reactSetup?.install || installGT\n ? await resolvePackageManager(session, options.packageManager)\n : undefined;\n\n session.assertResolved();\n\n if (provision && !(await canAuthenticate())) {\n await signInForSetup(session, settings.baseUrl);\n }\n const project = provision\n ? await withCredentialsError(() =>\n resolveDevelopmentProject(session, settings, options, cwd)\n )\n : undefined;\n session.assertResolved();\n\n // ----- Changes start here ----- //\n const resolvedLocales = locales as string[];\n\n if (reactSetup) {\n logger.info(`${chalk.yellow('[EXPERIMENTAL]')} Configuring project...`);\n if (reactSetup.install && packageManager) {\n await installWithProgress(\n session,\n reactSetup.install,\n packageManager,\n false\n );\n }\n await executeReactSetup(session, reactSetup, options);\n logger.endCommand(\n `Done! Since this wizard is experimental, please review the changes and make modifications as needed.\n\\nNext step: start internationalizing! See the docs for more information: ${buildTool?.docsUrl ?? REACT_QUICKSTART_URL}`\n );\n logger.startCommand('Setting up project config...');\n }\n\n const reportManualAction = ({ whatHappened, fix }: ManualAction) => {\n session.humanActions.push(fix);\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened,\n fix,\n })\n );\n };\n const reportSetupResult = ({ steps, manualActions }: SetupResult) => {\n for (const step of steps) session.step(step);\n manualActions.forEach(reportManualAction);\n };\n const translationFilesError = (error: unknown) =>\n new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not create the translation files in ${translationsDir}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Choose another --translations-dir or fix the path, then rerun the command',\n })\n );\n const buildToolContext = {\n appDirectory: cwd,\n configFilepath,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n previousTranslationsDir: configuredTranslationsDir,\n };\n\n if (storage === 'local' && translationsDir) {\n if (buildTool && !reactSetup) {\n reportSetupResult(\n await buildTool\n .syncLoader({\n ...buildToolContext,\n translationsDir,\n keepAppSource: setup.keepAppSource,\n })\n .catch((error: unknown) => {\n throw translationFilesError(error);\n })\n );\n }\n const generatedLoader = this.shouldGenerateLocalTranslationLoader(\n buildTool?.ownsLoader ?? false,\n runtimeSetup\n );\n const loader = generatedLoader\n ? await createLoadTranslationsFile({\n appDirectory: cwd,\n translationsDir,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n previousTranslationsDir: configuredTranslationsDir,\n }).catch((error: unknown) => {\n throw translationFilesError(error);\n })\n : undefined;\n if (loader === 'created' || loader === 'updated') {\n session.step(`${loader} loadTranslations.js`);\n }\n // A loader left unchanged may not read the newly chosen directory.\n if (\n loader === 'custom' &&\n translationsDir !== configuredTranslationsDir\n ) {\n const loaderFile = path.relative(\n cwd,\n findLoadTranslationsFiles(cwd)[0] ?? 'loadTranslations.js'\n );\n reportManualAction({\n whatHappened: `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`,\n fix: `Update your custom ${loaderFile} to load translations from ${translationsDir}`,\n });\n }\n const guidance = this.getLocalTranslationGuidance({\n generatedLoader: generatedLoader && loader !== 'custom',\n runtimeSetup,\n translationsDir,\n });\n if (guidance) logger.message(guidance);\n } else if (\n storage === 'cdn' &&\n buildTool &&\n !reactSetup &&\n configuredTranslationsDir !== undefined\n ) {\n // Only the application setup rewrites the initializer; a loader passed\n // to it takes precedence over CDN loading.\n const action = await buildTool.getCDNStorageAction?.(buildToolContext);\n if (action !== null) {\n reportManualAction(\n action ?? {\n whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,\n fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`,\n }\n );\n }\n } else if (\n storage === 'cdn' &&\n !buildTool &&\n configuredTranslationsDir !== undefined\n ) {\n // gt-next uses a loadTranslations file whenever one exists, and a\n // loader passed to GTProvider takes precedence over the CDN. Name every\n // one: deleting only the first makes gt-next fall back to the next.\n const loaders = findLoadTranslationsFiles(cwd).map((loader) =>\n path.relative(cwd, loader)\n );\n if (loaders.length > 0) {\n const loaderFiles = loaders.join(', ');\n const [them, loads] =\n loaders.length === 1 ? ['it', 'loads'] : ['them', 'load'];\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${loaderFiles} still ${loads} them from ${configuredTranslationsDir}`,\n fix: `Delete ${loaderFiles}, and remove ${them} from your GT setup if you pass ${them} there, so translations load from the CDN`,\n });\n }\n }\n\n const configChange = await applySetupConfig(configFilepath, configUpdate);\n if (configChange !== 'unchanged') {\n session.step(`${configChange} ${configFilepath}`);\n }\n\n logger.success(\n `Edit ${chalk.cyan(\n configFilepath\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n if (reactSetup && buildTool) {\n reportSetupResult(await buildTool.apply(buildToolContext));\n }\n\n if (installGT && packageManager) {\n await installWithProgress(session, 'gt', packageManager, true);\n }\n\n if (project) {\n await withCredentialsError(() =>\n provisionDevelopmentCredentials(\n session,\n project,\n settings,\n envFramework,\n cwd\n )\n );\n logger.message(productionRuntimeKeyGuidance(settings.dashboardUrl));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,MAAM,oCAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,SAAS,0BACP,cACA,OACQ;AACR,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV;EACA,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,uBAAuB,wBAAwB;CACnD,cAAc;CACd,KAAK;CACN,CAAC;AAEF,SAAS,gBAAgB,OAAuB;CAC9C,MAAM,OAAO,MAAM,MAAM;AACzB,KAAI,CAAC,KAAM,OAAM,IAAI,qBAAqB,qBAAqB;AAC/D,QAAO;;;AAIT,eAAe,qBAAwB,KAAmC;AACxE,KAAI;AACF,SAAO,MAAM,KAAK;UACX,OAAO;AACd,MAAI,iBAAiB,gBAAiB,OAAM;AAC5C,QAAM,IAAI,MACR,iBAAiB,gBACb,MAAM,UACN,0BACE,gDACA,MACD,CACN;;;AA8BL,IAAa,UAAb,MAAqB;CACnB;CACA;CACA;CAEA,YACE,SACA,SACA,mBACA;AACA,OAAK,UAAU;AACf,OAAK,UAAU;AACf,OAAK,oBAAoB,qBAAqB,EAAE;AAEhD,OAAK,QAAQ,OACX,wBACA,yDACD;AACD,OAAK,QAAQ,OACX,uCACA,sDAC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AC3B;AACD,OAAI,QAAQ,SAAS,GAAG;IACtB,MAAM,cAAc,QAAQ,KAAK,KAAK;IACtC,MAAM,CAAC,MAAM,SACX,QAAQ,WAAW,IAAI,CAAC,MAAM,QAAQ,GAAG,CAAC,QAAQ,OAAO;AAC3D,uBAAmB;KACjB,cAAc,2CAA2C,YAAY,SAAS,MAAM,aAAa;KACjG,KAAK,UAAU,YAAY,eAAe,KAAK,kCAAkC,KAAK;KACvF,CAAC;;;EAIN,MAAM,eAAe,MAAM,iBAAiB,gBAAgB,aAAa;AACzE,MAAI,iBAAiB,YACnB,SAAQ,KAAK,GAAG,aAAa,GAAG,iBAAiB;AAGnD,SAAO,QACL,QAAQ,MAAM,KACZ,eACD,CAAC,sGACH;AAED,MAAI,cAAc,UAChB,mBAAkB,MAAM,UAAU,MAAM,iBAAiB,CAAC;AAG5D,MAAI,aAAa,eACf,OAAM,oBAAoB,SAAS,MAAM,gBAAgB,KAAK;AAGhE,MAAI,SAAS;AACX,SAAM,2BACJ,gCACE,SACA,SACA,UACA,cACA,IACD,CACF;AACD,UAAO,QAAQ,6BAA6B,SAAS,aAAa,CAAC"}
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.26.7";
1
+ export declare const PACKAGE_VERSION = "2.26.9";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.26.7";
2
+ const PACKAGE_VERSION = "2.26.9";
3
3
  //#endregion
4
4
  export { PACKAGE_VERSION };
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.26.7';\n"],"mappings":";AACA,MAAa,kBAAkB"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.26.9';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -0,0 +1,10 @@
1
+ export declare const FILE_IO_CONCURRENCY = 512;
2
+ /**
3
+ * Keeps up to `batchSize` items in flight and returns results in input order.
4
+ * Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.
5
+ * @param items - The items to process
6
+ * @param processor - Processes one item
7
+ * @param batchSize - The maximum number of items in flight at once
8
+ * @returns The processor results, in input order
9
+ */
10
+ export declare function batchProcess<T, R>(items: T[], processor: (item: T, index: number) => Promise<R>, batchSize?: number): Promise<R[]>;
@@ -0,0 +1,29 @@
1
+ //#region src/utils/batchProcess.ts
2
+ const FILE_IO_CONCURRENCY = 512;
3
+ /**
4
+ * Keeps up to `batchSize` items in flight and returns results in input order.
5
+ * Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.
6
+ * @param items - The items to process
7
+ * @param processor - Processes one item
8
+ * @param batchSize - The maximum number of items in flight at once
9
+ * @returns The processor results, in input order
10
+ */
11
+ async function batchProcess(items, processor, batchSize = 25) {
12
+ if (items.length === 0) return [];
13
+ const results = Array.from({ length: items.length });
14
+ const executing = /* @__PURE__ */ new Set();
15
+ for (let i = 0; i < items.length; i++) {
16
+ const promise = processor(items[i], i).then((result) => {
17
+ results[i] = result;
18
+ executing.delete(promise);
19
+ });
20
+ executing.add(promise);
21
+ if (executing.size >= batchSize) await Promise.race(executing);
22
+ }
23
+ await Promise.all(executing);
24
+ return results;
25
+ }
26
+ //#endregion
27
+ export { FILE_IO_CONCURRENCY, batchProcess };
28
+
29
+ //# sourceMappingURL=batchProcess.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batchProcess.js","names":[],"sources":["../../src/utils/batchProcess.ts"],"sourcesContent":["// Max files a postprocess pass reads or writes at once. Unbounded\n// Promise.all over every translated file opens a descriptor per file and\n// fails with EMFILE on large projects.\nexport const FILE_IO_CONCURRENCY = 512;\n\n/**\n * Keeps up to `batchSize` items in flight and returns results in input order.\n * Mirrors `batchProcess` in gt-cloud's `packages/node/src/utils`.\n * @param items - The items to process\n * @param processor - Processes one item\n * @param batchSize - The maximum number of items in flight at once\n * @returns The processor results, in input order\n */\nexport async function batchProcess<T, R>(\n items: T[],\n processor: (item: T, index: number) => Promise<R>,\n batchSize: number = 25\n): Promise<R[]> {\n if (items.length === 0) {\n return [];\n }\n const results = Array.from({ length: items.length }) as R[];\n const executing = new Set<Promise<void>>();\n\n for (let i = 0; i < items.length; i++) {\n const promise = processor(items[i], i).then((result) => {\n results[i] = result;\n executing.delete(promise);\n });\n\n executing.add(promise);\n\n if (executing.size >= batchSize) {\n await Promise.race(executing);\n }\n }\n\n await Promise.all(executing);\n\n return results;\n}\n"],"mappings":";AAGA,MAAa,sBAAsB;;;;;;;;;AAUnC,eAAsB,aACpB,OACA,WACA,YAAoB,IACN;AACd,KAAI,MAAM,WAAW,EACnB,QAAO,EAAE;CAEX,MAAM,UAAU,MAAM,KAAK,EAAE,QAAQ,MAAM,QAAQ,CAAC;CACpD,MAAM,4BAAY,IAAI,KAAoB;AAE1C,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,UAAU,UAAU,MAAM,IAAI,EAAE,CAAC,MAAM,WAAW;AACtD,WAAQ,KAAK;AACb,aAAU,OAAO,QAAQ;IACzB;AAEF,YAAU,IAAI,QAAQ;AAEtB,MAAI,UAAU,QAAQ,UACpB,OAAM,QAAQ,KAAK,UAAU;;AAIjC,OAAM,QAAQ,IAAI,UAAU;AAE5B,QAAO"}
@@ -1,18 +1,16 @@
1
1
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
+ import { batchProcess } from "./batchProcess.js";
2
3
  import fs from "node:fs";
3
4
  //#region src/utils/flattenJsonFiles.ts
4
5
  async function flattenJsonFiles(settings, includeFiles) {
5
6
  if (!settings.files || Object.keys(settings.files.placeholderPaths).length === 1 && settings.files.placeholderPaths.gt) return;
6
7
  const { resolvedPaths: sourceFiles } = settings.files;
7
8
  const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths, settings.files.transformFormats, settings.locales, settings.defaultLocale);
8
- await Promise.all(Object.values(fileMapping).map(async (filesMap) => {
9
- const targetFiles = Object.values(filesMap).filter((p) => p.endsWith(".json") && (!includeFiles || includeFiles.has(p)));
10
- await Promise.all(targetFiles.map(async (file) => {
11
- const flattenedJson = flattenJson(JSON.parse(fs.readFileSync(file, "utf8")));
12
- await fs.promises.writeFile(file, JSON.stringify(flattenedJson, null, 2));
13
- return flattenedJson;
14
- }));
15
- }));
9
+ for (const filesMap of Object.values(fileMapping)) await batchProcess(Object.values(filesMap).filter((p) => p.endsWith(".json") && (!includeFiles || includeFiles.has(p))), async (file) => {
10
+ const flattenedJson = flattenJson(JSON.parse(fs.readFileSync(file, "utf8")));
11
+ await fs.promises.writeFile(file, JSON.stringify(flattenedJson, null, 2));
12
+ return flattenedJson;
13
+ }, 512);
16
14
  }
17
15
  function flattenJson(json, prefix = "") {
18
16
  const result = {};
@@ -1 +1 @@
1
- {"version":3,"file":"flattenJsonFiles.js","names":[],"sources":["../../src/utils/flattenJsonFiles.ts"],"sourcesContent":["import { createFileMapping } from '../formats/files/fileMapping.js';\nimport fs from 'node:fs';\nimport { Settings } from '../types/index.js';\n\nexport default async function flattenJsonFiles(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n await Promise.all(\n Object.values(fileMapping).map(async (filesMap) => {\n const targetFiles = Object.values(filesMap).filter(\n (p) => p.endsWith('.json') && (!includeFiles || includeFiles.has(p))\n );\n\n await Promise.all(\n targetFiles.map(async (file) => {\n // Read each json file\n const json = JSON.parse(fs.readFileSync(file, 'utf8'));\n // Flatten the json\n const flattenedJson = flattenJson(json);\n\n // Write the flattened json to the target file\n await fs.promises.writeFile(\n file,\n JSON.stringify(flattenedJson, null, 2)\n );\n return flattenedJson;\n })\n );\n })\n );\n}\n\nfunction flattenJson(json: unknown, prefix = ''): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(json as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(result, flattenJson(value, newKey));\n } else {\n result[newKey] = value;\n }\n }\n\n return result;\n}\n"],"mappings":";;;AAIA,eAA8B,iBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC;CAEF,MAAM,EAAE,eAAe,gBAAgB,SAAS;CAEhD,MAAM,cAAc,kBAClB,aACA,SAAS,MAAM,kBACf,SAAS,MAAM,gBACf,SAAS,MAAM,kBACf,SAAS,SACT,SAAS,cACV;AAED,OAAM,QAAQ,IACZ,OAAO,OAAO,YAAY,CAAC,IAAI,OAAO,aAAa;EACjD,MAAM,cAAc,OAAO,OAAO,SAAS,CAAC,QACzC,MAAM,EAAE,SAAS,QAAQ,KAAK,CAAC,gBAAgB,aAAa,IAAI,EAAE,EACpE;AAED,QAAM,QAAQ,IACZ,YAAY,IAAI,OAAO,SAAS;GAI9B,MAAM,gBAAgB,YAFT,KAAK,MAAM,GAAG,aAAa,MAAM,OAAO,CAEf,CAAC;AAGvC,SAAM,GAAG,SAAS,UAChB,MACA,KAAK,UAAU,eAAe,MAAM,EAAE,CACvC;AACD,UAAO;IACP,CACH;GACD,CACH;;AAGH,SAAS,YAAY,MAAe,SAAS,IAA6B;CACxE,MAAM,SAAkC,EAAE;AAE1C,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,EAAE;EAC1E,MAAM,SAAS,SAAS,GAAG,OAAO,GAAG,QAAQ;AAE7C,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,CACtE,QAAO,OAAO,QAAQ,YAAY,OAAO,OAAO,CAAC;MAEjD,QAAO,UAAU;;AAIrB,QAAO"}
1
+ {"version":3,"file":"flattenJsonFiles.js","names":[],"sources":["../../src/utils/flattenJsonFiles.ts"],"sourcesContent":["import { createFileMapping } from '../formats/files/fileMapping.js';\nimport fs from 'node:fs';\nimport { Settings } from '../types/index.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nexport default async function flattenJsonFiles(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n // One locale at a time so the concurrency bound covers the whole pass\n for (const filesMap of Object.values(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (p) => p.endsWith('.json') && (!includeFiles || includeFiles.has(p))\n );\n\n await batchProcess(\n targetFiles,\n async (file) => {\n // Read each json file\n const json = JSON.parse(fs.readFileSync(file, 'utf8'));\n // Flatten the json\n const flattenedJson = flattenJson(json);\n\n // Write the flattened json to the target file\n await fs.promises.writeFile(\n file,\n JSON.stringify(flattenedJson, null, 2)\n );\n return flattenedJson;\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n\nfunction flattenJson(json: unknown, prefix = ''): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(json as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(result, flattenJson(value, newKey));\n } else {\n result[newKey] = value;\n }\n }\n\n return result;\n}\n"],"mappings":";;;;AAKA,eAA8B,iBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC;CAEF,MAAM,EAAE,eAAe,gBAAgB,SAAS;CAEhD,MAAM,cAAc,kBAClB,aACA,SAAS,MAAM,kBACf,SAAS,MAAM,gBACf,SAAS,MAAM,kBACf,SAAS,SACT,SAAS,cACV;AAGD,MAAK,MAAM,YAAY,OAAO,OAAO,YAAY,CAK/C,OAAM,aAJc,OAAO,OAAO,SAAS,CAAC,QACzC,MAAM,EAAE,SAAS,QAAQ,KAAK,CAAC,gBAAgB,aAAa,IAAI,EAAE,EAIxD,EACX,OAAO,SAAS;EAId,MAAM,gBAAgB,YAFT,KAAK,MAAM,GAAG,aAAa,MAAM,OAAO,CAEf,CAAC;AAGvC,QAAM,GAAG,SAAS,UAChB,MACA,KAAK,UAAU,eAAe,MAAM,EAAE,CACvC;AACD,SAAO;QAGV;;AAIL,SAAS,YAAY,MAAe,SAAS,IAA6B;CACxE,MAAM,SAAkC,EAAE;AAE1C,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,EAAE;EAC1E,MAAM,SAAS,SAAS,GAAG,OAAO,GAAG,QAAQ;AAE7C,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,CACtE,QAAO,OAAO,QAAQ,YAAY,OAAO,OAAO,CAAC;MAEjD,QAAO,UAAU;;AAIrB,QAAO"}
@@ -1,4 +1,5 @@
1
1
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
+ import { batchProcess } from "./batchProcess.js";
2
3
  import path from "node:path";
3
4
  import fs from "node:fs";
4
5
  import YAML, { isMap, isScalar } from "yaml";
@@ -77,14 +78,11 @@ async function localizeMintlifyFrontmatterUrls(settings, includeFiles) {
77
78
  if (settings.framework !== "mintlify" || !settings.files) return;
78
79
  const fileMapping = createFileMapping(settings.files.resolvedPaths, settings.files.placeholderPaths, settings.files.transformPaths ?? {}, settings.files.transformFormats ?? {}, settings.locales, settings.defaultLocale);
79
80
  const knownLocaleValues = [settings.defaultLocale, ...settings.locales];
80
- for (const [locale, filesMap] of Object.entries(fileMapping)) {
81
- const targetFiles = Object.values(filesMap).filter((filePath) => (filePath.endsWith(".md") || filePath.endsWith(".mdx")) && shouldProcessFile(filePath, includeFiles));
82
- await Promise.all(targetFiles.map(async (filePath) => {
83
- if (!fs.existsSync(filePath)) return;
84
- const result = localizeMintlifyFrontmatterUrlForContent(await fs.promises.readFile(filePath, "utf8"), locale, knownLocaleValues);
85
- if (result.changed) await fs.promises.writeFile(filePath, result.content, "utf8");
86
- }));
87
- }
81
+ for (const [locale, filesMap] of Object.entries(fileMapping)) await batchProcess(Object.values(filesMap).filter((filePath) => (filePath.endsWith(".md") || filePath.endsWith(".mdx")) && shouldProcessFile(filePath, includeFiles)), async (filePath) => {
82
+ if (!fs.existsSync(filePath)) return;
83
+ const result = localizeMintlifyFrontmatterUrlForContent(await fs.promises.readFile(filePath, "utf8"), locale, knownLocaleValues);
84
+ if (result.changed) await fs.promises.writeFile(filePath, result.content, "utf8");
85
+ }, 512);
88
86
  }
89
87
  //#endregion
90
88
  export { localizeMintlifyFrontmatterUrls as default, localizeMintlifyFrontmatterUrlForContent };