gt 2.27.0 → 2.27.1

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/auth/cliApiKey.d.ts +7 -0
  3. package/dist/auth/cliApiKey.js +18 -0
  4. package/dist/auth/cliApiKey.js.map +1 -0
  5. package/dist/cli/base.d.ts +1 -1
  6. package/dist/cli/base.js +27 -7
  7. package/dist/cli/base.js.map +1 -1
  8. package/dist/cli/commands/api.js +2 -1
  9. package/dist/cli/commands/api.js.map +1 -1
  10. package/dist/cli/commands/utils/validation.js +1 -1
  11. package/dist/cli/commands/utils/validation.js.map +1 -1
  12. package/dist/config/generateSettings.js +2 -1
  13. package/dist/config/generateSettings.js.map +1 -1
  14. package/dist/console/index.d.ts +1 -1
  15. package/dist/console/index.js +7 -1
  16. package/dist/console/index.js.map +1 -1
  17. package/dist/generated/version.d.ts +1 -1
  18. package/dist/generated/version.js +1 -1
  19. package/dist/generated/version.js.map +1 -1
  20. package/dist/setup/buildTools/index.d.ts +2 -0
  21. package/dist/setup/buildTools/index.js +11 -1
  22. package/dist/setup/buildTools/index.js.map +1 -1
  23. package/dist/setup/buildTools/vite.js +2 -1
  24. package/dist/setup/buildTools/vite.js.map +1 -1
  25. package/dist/setup/detectFramework.d.ts +5 -4
  26. package/dist/setup/detectFramework.js +7 -2
  27. package/dist/setup/detectFramework.js.map +1 -1
  28. package/dist/setup/developmentCredentials.js +1 -1
  29. package/dist/setup/instructions/base.md +1 -1
  30. package/dist/setup/instructions/gt-next.md +1 -1
  31. package/dist/setup/instructions/gt-react.md +1 -1
  32. package/dist/setup/nextSteps.d.ts +31 -0
  33. package/dist/setup/nextSteps.js +46 -0
  34. package/dist/setup/nextSteps.js.map +1 -0
  35. package/dist/setup/onboarding.d.ts +3 -0
  36. package/dist/setup/onboarding.js +3 -2
  37. package/dist/setup/onboarding.js.map +1 -1
  38. package/dist/setup/setupTarget.d.ts +2 -0
  39. package/dist/setup/setupTarget.js +10 -1
  40. package/dist/setup/setupTarget.js.map +1 -1
  41. package/dist/setup/wizard.d.ts +1 -1
  42. package/dist/setup/wizard.js +6 -8
  43. package/dist/setup/wizard.js.map +1 -1
  44. package/dist/types/index.d.ts +5 -0
  45. package/dist/types/index.js.map +1 -1
  46. package/dist/utils/api.d.ts +13 -0
  47. package/dist/utils/constants.d.ts +4 -1
  48. package/dist/utils/constants.js +5 -2
  49. package/dist/utils/constants.js.map +1 -1
  50. package/dist/utils/credentials.d.ts +3 -2
  51. package/dist/utils/credentials.js +18 -10
  52. package/dist/utils/credentials.js.map +1 -1
  53. package/dist/utils/loadEnv.d.ts +2 -0
  54. package/dist/utils/loadEnv.js +9 -1
  55. package/dist/utils/loadEnv.js.map +1 -1
  56. package/dist/workflows/stage.js +2 -1
  57. package/dist/workflows/stage.js.map +1 -1
  58. package/package.json +5 -5
@@ -1,6 +1,6 @@
1
1
  # General Translation (GT) Internationalization Rules
2
2
 
3
- This project is using [General Translation](https://generaltranslation.com/docs/overview.md) for internationalization (i18n) and translations. General Translation is a developer-first localization stack, built for the world's best engineering teams to ship apps in every language with ease.
3
+ This project is using [General Translation](https://generaltranslation.com/docs/overview/get-started.md) for internationalization (i18n) and translations. General Translation is a developer-first localization stack, built for the world's best engineering teams to ship apps in every language with ease.
4
4
 
5
5
  ## Configuration
6
6
 
@@ -104,4 +104,4 @@ const locale = useLocale(); // "en-US"
104
104
 
105
105
  ## Quickstart
106
106
 
107
- See <https://generaltranslation.com/docs/next.md>
107
+ See <https://generaltranslation.com/docs/react/nextjs-quickstart.md>
@@ -95,4 +95,4 @@ const locale = useLocale(); // "en-US"
95
95
 
96
96
  ## Quickstart
97
97
 
98
- See <https://generaltranslation.com/docs/react.md>
98
+ See <https://generaltranslation.com/docs/react/react-quickstart.md>
@@ -0,0 +1,31 @@
1
+ import type { SupportedReactFrameworks } from '../types/index.js';
2
+ export type InitNextStepsContext = {
3
+ framework: SupportedReactFrameworks;
4
+ /** Setup added the GT provider or initializer to the app entry. */
5
+ configuredAppEntry: boolean;
6
+ /** Setup guide for the framework. */
7
+ docsUrl: string;
8
+ locales: string[];
9
+ /** The config setup wrote; named in the translate command unless default. */
10
+ configFilepath: string;
11
+ /** Set when translations are stored locally. */
12
+ translationsDir?: string;
13
+ /** The command that starts the dev server, when the app has a dev script. */
14
+ devCommand?: string;
15
+ };
16
+ /**
17
+ * What a person still has to do after the React setup: it configures the
18
+ * app entry but never marks content for translation. Plain text, so the same
19
+ * steps can be printed and reported in the --json result.
20
+ */
21
+ export declare function getInitNextSteps({ framework, configuredAppEntry, docsUrl, locales, configFilepath, translationsDir, devCommand, }: InitNextStepsContext): string[];
22
+ /**
23
+ * gt translate reads gt.config.json from the working directory by default,
24
+ * so another config is named with --config. A path goes into the command
25
+ * only when POSIX shells, Command Prompt and PowerShell all read it
26
+ * literally; no quoting works the same in all of them, so any other path is
27
+ * named outside the command.
28
+ */
29
+ export declare function getTranslateInstruction(configFilepath: string, platform?: NodeJS.Platform): string;
30
+ /** The final wizard message: one Done!, then the numbered next steps. */
31
+ export declare function formatInitNextSteps(steps: string[]): string;
@@ -0,0 +1,46 @@
1
+ import { getReactFrameworkLibrary } from "./frameworkUtils.js";
2
+ import path from "node:path";
3
+ //#region src/setup/nextSteps.ts
4
+ /**
5
+ * What a person still has to do after the React setup: it configures the
6
+ * app entry but never marks content for translation. Plain text, so the same
7
+ * steps can be printed and reported in the --json result.
8
+ */
9
+ function getInitNextSteps({ framework, configuredAppEntry, docsUrl, locales, configFilepath, translationsDir, devCommand }) {
10
+ const library = getReactFrameworkLibrary({
11
+ name: framework,
12
+ type: "react"
13
+ });
14
+ const destination = translationsDir ? ` and save them to ${translationsDir}` : "";
15
+ return [
16
+ ...configuredAppEntry ? [] : [`Add <GTProvider> from ${library} to the root of your app (see ${docsUrl})`],
17
+ `Wrap the text you want translated in <T>, or translate strings with useGT(); both come from ${library} (see ${docsUrl})`,
18
+ `Add <LocaleSelector /> from ${library} so visitors can switch language`,
19
+ `${getTranslateInstruction(configFilepath)} to translate your content into ${locales.join(", ")}${destination}`,
20
+ devCommand ? `Start the dev server with \`${devCommand}\` and switch language` : "Start your dev server and switch language"
21
+ ];
22
+ }
23
+ /**
24
+ * gt translate reads gt.config.json from the working directory by default,
25
+ * so another config is named with --config. A path goes into the command
26
+ * only when POSIX shells, Command Prompt and PowerShell all read it
27
+ * literally; no quoting works the same in all of them, so any other path is
28
+ * named outside the command.
29
+ */
30
+ function getTranslateInstruction(configFilepath, platform = process.platform) {
31
+ if (path.resolve(configFilepath) === path.resolve("gt.config.json")) return "Run `npx gt translate`";
32
+ return (platform === "win32" ? /^[\w./\\:+=-]+$/ : /^[\w./:+=-]+$/).test(configFilepath) ? `Run \`npx gt translate --config ${configFilepath}\`` : `Run \`npx gt translate\` with --config set to your config file (${configFilepath})`;
33
+ }
34
+ /** The final wizard message: one Done!, then the numbered next steps. */
35
+ function formatInitNextSteps(steps) {
36
+ return [
37
+ "Done! Setup did not mark any content for translation, so your app still renders only in its default locale. Since this wizard is experimental, please review its changes.",
38
+ "",
39
+ "Next steps:",
40
+ ...steps.map((step, index) => `${index + 1}. ${step}`)
41
+ ].join("\n");
42
+ }
43
+ //#endregion
44
+ export { formatInitNextSteps, getInitNextSteps, getTranslateInstruction };
45
+
46
+ //# sourceMappingURL=nextSteps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nextSteps.js","names":[],"sources":["../../src/setup/nextSteps.ts"],"sourcesContent":["import path from 'node:path';\nimport type { SupportedReactFrameworks } from '../types/index.js';\nimport { getReactFrameworkLibrary } from './frameworkUtils.js';\n\nexport type InitNextStepsContext = {\n framework: SupportedReactFrameworks;\n /** Setup added the GT provider or initializer to the app entry. */\n configuredAppEntry: boolean;\n /** Setup guide for the framework. */\n docsUrl: string;\n locales: string[];\n /** The config setup wrote; named in the translate command unless default. */\n configFilepath: string;\n /** Set when translations are stored locally. */\n translationsDir?: string;\n /** The command that starts the dev server, when the app has a dev script. */\n devCommand?: string;\n};\n\n/**\n * What a person still has to do after the React setup: it configures the\n * app entry but never marks content for translation. Plain text, so the same\n * steps can be printed and reported in the --json result.\n */\nexport function getInitNextSteps({\n framework,\n configuredAppEntry,\n docsUrl,\n locales,\n configFilepath,\n translationsDir,\n devCommand,\n}: InitNextStepsContext): string[] {\n const library = getReactFrameworkLibrary({ name: framework, type: 'react' });\n const destination = translationsDir\n ? ` and save them to ${translationsDir}`\n : '';\n return [\n ...(configuredAppEntry\n ? []\n : [\n `Add <GTProvider> from ${library} to the root of your app (see ${docsUrl})`,\n ]),\n `Wrap the text you want translated in <T>, or translate strings with useGT(); both come from ${library} (see ${docsUrl})`,\n `Add <LocaleSelector /> from ${library} so visitors can switch language`,\n `${getTranslateInstruction(configFilepath)} to translate your content into ${locales.join(', ')}${destination}`,\n devCommand\n ? `Start the dev server with \\`${devCommand}\\` and switch language`\n : 'Start your dev server and switch language',\n ];\n}\n\n/**\n * gt translate reads gt.config.json from the working directory by default,\n * so another config is named with --config. A path goes into the command\n * only when POSIX shells, Command Prompt and PowerShell all read it\n * literally; no quoting works the same in all of them, so any other path is\n * named outside the command.\n */\nexport function getTranslateInstruction(\n configFilepath: string,\n platform: NodeJS.Platform = process.platform\n): string {\n if (path.resolve(configFilepath) === path.resolve('gt.config.json')) {\n return 'Run `npx gt translate`';\n }\n const literal = platform === 'win32' ? /^[\\w./\\\\:+=-]+$/ : /^[\\w./:+=-]+$/;\n return literal.test(configFilepath)\n ? `Run \\`npx gt translate --config ${configFilepath}\\``\n : `Run \\`npx gt translate\\` with --config set to your config file (${configFilepath})`;\n}\n\n/** The final wizard message: one Done!, then the numbered next steps. */\nexport function formatInitNextSteps(steps: string[]): string {\n return [\n 'Done! Setup did not mark any content for translation, so your app still renders only in its default locale. Since this wizard is experimental, please review its changes.',\n '',\n 'Next steps:',\n ...steps.map((step, index) => `${index + 1}. ${step}`),\n ].join('\\n');\n}\n"],"mappings":";;;;;;;;AAwBA,SAAgB,iBAAiB,EAC/B,WACA,oBACA,SACA,SACA,gBACA,iBACA,cACiC;CACjC,MAAM,UAAU,yBAAyB;EAAE,MAAM;EAAW,MAAM;EAAS,CAAC;CAC5E,MAAM,cAAc,kBAChB,qBAAqB,oBACrB;AACJ,QAAO;EACL,GAAI,qBACA,EAAE,GACF,CACE,yBAAyB,QAAQ,gCAAgC,QAAQ,GAC1E;EACL,+FAA+F,QAAQ,QAAQ,QAAQ;EACvH,+BAA+B,QAAQ;EACvC,GAAG,wBAAwB,eAAe,CAAC,kCAAkC,QAAQ,KAAK,KAAK,GAAG;EAClG,aACI,+BAA+B,WAAW,0BAC1C;EACL;;;;;;;;;AAUH,SAAgB,wBACd,gBACA,WAA4B,QAAQ,UAC5B;AACR,KAAI,KAAK,QAAQ,eAAe,KAAK,KAAK,QAAQ,iBAAiB,CACjE,QAAO;AAGT,SADgB,aAAa,UAAU,oBAAoB,iBAC5C,KAAK,eAAe,GAC/B,mCAAmC,eAAe,MAClD,mEAAmE,eAAe;;;AAIxF,SAAgB,oBAAoB,OAAyB;AAC3D,QAAO;EACL;EACA;EACA;EACA,GAAG,MAAM,KAAK,MAAM,UAAU,GAAG,QAAQ,EAAE,IAAI,OAAO;EACvD,CAAC,KAAK,KAAK"}
@@ -57,6 +57,8 @@ export type OnboardingEvent = {
57
57
  url?: string;
58
58
  /** Manual steps setup could not do, for needs_human_action. */
59
59
  actions?: string[];
60
+ /** What to do next once setup succeeded, e.g. marking content for translation. */
61
+ nextSteps?: string[];
60
62
  missingOptions?: string[];
61
63
  error?: string;
62
64
  };
@@ -104,6 +106,7 @@ export declare class OnboardingSession {
104
106
  }
105
107
  export type OnboardingOutcome = {
106
108
  outcome: 'success';
109
+ nextSteps?: string[];
107
110
  } | {
108
111
  outcome: 'needs_human_action';
109
112
  url: string;
@@ -6,8 +6,8 @@ import { withJsonExtension } from "../fs/config/loadConfig.js";
6
6
  import { SETUP_FILE_FORMATS } from "../formats/files/supportedFiles.js";
7
7
  import { getFrameworkDisplayName, getReactFrameworkLibrary } from "./frameworkUtils.js";
8
8
  import { getBuildToolSetup } from "./buildTools/index.js";
9
- import { SUPPORTED_REACT_FRAMEWORKS } from "../types/index.js";
10
9
  import { NoPackageManagerError, getPackageManager, packageManagers } from "../utils/packageManager.js";
10
+ import { SUPPORTED_REACT_FRAMEWORKS } from "../types/index.js";
11
11
  import { installPackage } from "../utils/installPackage.js";
12
12
  import { createDiagnosticMessage, formatDiagnosticErrorDetails } from "generaltranslation/internal";
13
13
  import fs from "node:fs";
@@ -172,7 +172,8 @@ async function runOnboarding(command, options, run) {
172
172
  outcome: needsHuman ? "needs_human_action" : "success",
173
173
  completedSteps: session.completedSteps,
174
174
  ...result.outcome === "needs_human_action" && { url: result.url },
175
- ...session.humanActions.length > 0 && { actions: session.humanActions }
175
+ ...session.humanActions.length > 0 && { actions: session.humanActions },
176
+ ...result.outcome === "success" && result.nextSteps !== void 0 && result.nextSteps.length > 0 && { nextSteps: result.nextSteps }
176
177
  });
177
178
  } catch (error) {
178
179
  const message = error instanceof Error ? error.message : formatDiagnosticErrorDetails(error) ?? "Setup failed";
@@ -1 +1 @@
1
- {"version":3,"file":"onboarding.js","names":[],"sources":["../../src/setup/onboarding.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { Command, Option, type CommanderError } from 'commander';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport findFilepath from '../fs/findFilepath.js';\nimport { withJsonExtension } from '../fs/config/loadConfig.js';\nimport { logger } from '../console/logger.js';\nimport {\n displayHeader,\n getLastExitError,\n logErrorAndExit,\n stripAnsi,\n} from '../console/logging.js';\nimport {\n SUPPORTED_REACT_FRAMEWORKS,\n type FrameworkObject,\n type SupportedReactFrameworks,\n} from '../types/index.js';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport {\n SETUP_FILE_FORMATS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n getPackageManager,\n NoPackageManagerError,\n packageManagers,\n type PackageManager,\n} from '../utils/packageManager.js';\nimport { installPackage } from '../utils/installPackage.js';\n\n/** Answers accepted by `gt configure` (and the gt-vue `gt init`). */\nexport type ConfigureOptions = {\n config: string;\n src?: string[];\n interactive?: boolean;\n json?: boolean;\n defaults?: boolean;\n defaultLocale?: string;\n locales?: string[];\n storage?: 'local' | 'cdn';\n translationsDir?: string;\n fileFormats?: Array<SetupFileFormat | 'none'>;\n filePatterns?: string[];\n liveTranslations?: boolean;\n devCredentials?: boolean;\n projectId?: string;\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n packageManager?: string;\n};\n\n/** Answers accepted by the React-aware `gt init`. */\nexport type InitOptions = ConfigureOptions & {\n locadex?: boolean;\n reactSetup?: boolean;\n framework?: SupportedReactFrameworks;\n format?: boolean;\n};\n\n/** Flags for every configuration question; values prefill interactive runs. */\nexport function attachConfigureFlags(\n command: Command,\n sourceHelp: string\n): Command {\n return reportJsonArgumentErrors(command)\n .option('--src <paths...>', sourceHelp)\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option(\n '--no-interactive',\n 'Never prompt; fail listing the options still needed. Automatic when stdin or stdout is not a terminal'\n )\n .option(\n '--json',\n 'Write JSON events (sign-in, handoff, result) to stdout and all other output to stderr; implies --no-interactive'\n )\n .option(\n '--defaults',\n 'Accept the recommended value for every local choice that no flag or gt.config.json answers; never creates projects or keys'\n )\n .option('--no-defaults', 'Do not offer the recommended defaults')\n .option('--default-locale <locale>', 'Default locale, e.g. en')\n .option(\n '--locales <locales...>',\n 'Locales to translate into, e.g. fr es; replaces the configured list'\n )\n .addOption(\n new Option(\n '--storage <storage>',\n 'Where GT translations are stored for GT runtimes'\n ).choices(['local', 'cdn'])\n )\n .option(\n '--translations-dir <path>',\n 'Directory for local GT translation files'\n )\n .addOption(\n new Option(\n '--file-formats <formats...>',\n 'Additional file formats to translate, or none'\n ).choices([...SETUP_FILE_FORMATS, 'none'])\n )\n .option(\n '--file-patterns <patterns...>',\n 'Glob patterns as <format>=<glob> including [locale], e.g. json=./locales/[locale]/*.json; selects the format'\n )\n .option(\n '--live-translations',\n 'Local Vite storage: set up live development translations (creates a development key)'\n )\n .option('--no-live-translations', 'Skip live development translations')\n .addOption(\n new Option(\n '--dev-credentials',\n 'Save a project ID and a new development key to .env.local'\n ).conflicts('liveTranslations')\n )\n .option('--no-dev-credentials', 'Do not create development credentials')\n .option(\n '--project-id <id>',\n 'Existing project for the development credentials'\n )\n .option(\n '--create-project',\n 'Create a new project for the development credentials'\n )\n .option('--org-id <id>', 'Organization that owns --create-project')\n .option('--project-name <name>', 'Name for --create-project')\n .addOption(\n new Option(\n '--package-manager <id>',\n 'Package manager for installs when it cannot be detected'\n ).choices(packageManagers.map((packageManager) => packageManager.id))\n );\n}\n\nlet commandBeforeOnboarding: string | undefined;\n\nfunction reportExitBeforeOnboarding(code: number): void {\n if (code === 0 || commandBeforeOnboarding === undefined) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: commandBeforeOnboarding,\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it started; see stderr'\n ),\n } satisfies OnboardingEvent)}\\n`\n );\n}\n\n/**\n * Pre-action hooks, such as the monorepo version check, can exit before\n * runOnboarding installs its own result reporting; `--json` callers still\n * get a result. runOnboarding takes over once it starts.\n */\nexport function reportJsonExitsBeforeOnboarding(command: string): void {\n commandBeforeOnboarding = command;\n process.once('exit', reportExitBeforeOnboarding);\n}\n\n/**\n * Argument errors happen before the action runs, so `--json` callers would\n * otherwise get no result. Commander prints the error to stderr, then calls\n * this exit hook; returning lets it exit with the same code as before. The\n * hook replaces an exit override inherited from the program.\n */\nfunction reportJsonArgumentErrors(command: Command): Command {\n return command.exitOverride((error: CommanderError) => {\n if (error.exitCode === 0) return; // help and version output\n // An option after the failing argument is not parsed yet.\n const json =\n command.opts().json === true || process.argv.includes('--json');\n if (!json) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: command.name(),\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(error.message),\n } satisfies OnboardingEvent)}\\n`\n );\n });\n}\n\n/** Configuration flags plus the React application setup and Locadex choices. */\nexport function attachInitFlags(command: Command, sourceHelp: string) {\n return attachConfigureFlags(command, sourceHelp)\n .option(\n '--locadex',\n 'Mintlify and Next.js App Router: hand setup to the Locadex AI agent through GitHub instead'\n )\n .option('--no-locadex', 'Set up this project locally')\n .option(\n '--react-setup',\n 'React projects: install the GT library and add GTProvider or initializeGTSPA'\n )\n .option('--no-react-setup', 'Do not modify application source')\n .addOption(\n new Option(\n '--framework <framework>',\n 'React framework for --react-setup; overrides detection'\n ).choices(SUPPORTED_REACT_FRAMEWORKS)\n )\n .option(\n '--format',\n 'Next.js App Router: format files changed by setup with the detected formatter'\n )\n .option('--no-format', 'Leave files changed by setup unformatted');\n}\n\nexport type OnboardingEvent =\n | {\n type: 'authorization_required';\n verificationUri: string;\n verificationUriComplete?: string;\n userCode: string;\n }\n | { type: 'handoff'; url: string; reason: 'locadex' }\n | {\n type: 'result';\n command: string;\n outcome: 'success' | 'needs_human_action' | 'failed';\n completedSteps: string[];\n url?: string;\n /** Manual steps setup could not do, for needs_human_action. */\n actions?: string[];\n missingOptions?: string[];\n error?: string;\n };\n\n/** Needs-input and validation failures, raised before setup changes files. */\nexport class OnboardingError extends Error {\n constructor(\n message: string,\n readonly missingOptions: string[] = []\n ) {\n super(message);\n this.name = 'OnboardingError';\n }\n}\n\nfunction isInteractiveTerminal(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\n/**\n * One setup run: how unanswered questions are resolved, which options are\n * still missing, and which steps already changed the project.\n */\nexport class OnboardingSession {\n readonly interactive: boolean;\n readonly json: boolean;\n defaults = false;\n readonly completedSteps: string[] = [];\n /** Manual steps left for a person; they make the outcome needs_human_action. */\n readonly humanActions: string[] = [];\n private readonly missing = new Set<string>();\n private readonly invalid: string[] = [];\n private reported = false;\n\n constructor(\n readonly command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>\n ) {\n this.json = options.json === true;\n this.interactive =\n options.interactive !== false && !this.json && isInteractiveTerminal();\n }\n\n /**\n * Explicit flag, then existing config, then the recommended value when\n * defaults were accepted, then a prompt. Noninteractive runs use the\n * fallback of an optional question, or record the option as missing.\n */\n async answer<T>(\n option: string,\n {\n explicit,\n configured,\n recommended,\n fallback,\n ask,\n }: {\n explicit?: T;\n configured?: T;\n recommended?: T;\n fallback?: T;\n ask: () => Promise<T>;\n }\n ): Promise<T | undefined> {\n if (explicit !== undefined) return explicit;\n if (configured !== undefined) return configured;\n if (this.defaults && recommended !== undefined) return recommended;\n if (this.interactive) return ask();\n if (fallback !== undefined) return fallback;\n this.require(option);\n return undefined;\n }\n\n require(option: string): void {\n this.missing.add(option);\n }\n\n reject(problem: string): void {\n this.invalid.push(problem);\n }\n\n /** Stops before any change when an answer is missing or invalid. */\n assertResolved(): void {\n if (this.missing.size === 0 && this.invalid.length === 0) return;\n const missingOptions = [...this.missing];\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened:\n missingOptions.length > 0\n ? `Setup needs these options: ${missingOptions.join(', ')}`\n : 'Setup received invalid options',\n reassurance: 'No project files were changed',\n details: this.invalid,\n fix: this.defaults\n ? 'Pass the options (see --help), or rerun in an interactive terminal'\n : 'Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal',\n }),\n missingOptions\n );\n }\n\n step(name: string): void {\n this.completedSteps.push(name);\n }\n\n emit(event: OnboardingEvent): void {\n if (!this.json) return;\n if (event.type === 'result') this.reported = true;\n // Synchronous so events survive an immediate process.exit.\n fs.writeSync(process.stdout.fd, `${JSON.stringify(event)}\\n`);\n }\n\n /** A result for exits that bypass runOnboarding (e.g. settings validation). */\n reportUnexpectedExit(code: number): void {\n if (this.reported || code === 0) return;\n this.emit({\n type: 'result',\n command: this.command,\n outcome: 'failed',\n completedSteps: this.completedSteps,\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it finished; see stderr'\n ),\n });\n }\n}\n\nexport type OnboardingOutcome =\n | { outcome: 'success' }\n | { outcome: 'needs_human_action'; url: string };\n\nfunction partialSetupWarning(session: OnboardingSession): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Setup stopped after these steps: ${session.completedSteps.join(', ')}`,\n why: 'the error below happened before the remaining steps ran',\n fix: `Review those changes, fix the error, then rerun \\`gt ${session.command}\\`; it reuses the saved configuration and credentials`,\n });\n}\n\n/**\n * Runs one setup command: selects prompt and output modes, then reports the\n * outcome. Failures exit nonzero with the steps that already ran.\n */\nexport async function runOnboarding(\n command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>,\n run: (session: OnboardingSession) => Promise<OnboardingOutcome>\n): Promise<void> {\n commandBeforeOnboarding = undefined;\n process.removeListener('exit', reportExitBeforeOnboarding);\n const session = new OnboardingSession(command, options);\n if (session.json) logger.setConsoleOutput('stderr');\n // Per-run modes; console routing is reset per command by BaseCLI.\n const progressWasAnimated = logger.setAnimatedProgress(session.interactive);\n const reportExit = (code: number) => session.reportUnexpectedExit(code);\n process.once('exit', reportExit);\n try {\n const result = await run(session);\n const needsHuman =\n result.outcome === 'needs_human_action' ||\n session.humanActions.length > 0;\n session.emit({\n type: 'result',\n command,\n outcome: needsHuman ? 'needs_human_action' : 'success',\n completedSteps: session.completedSteps,\n ...(result.outcome === 'needs_human_action' && { url: result.url }),\n ...(session.humanActions.length > 0 && {\n actions: session.humanActions,\n }),\n });\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : (formatDiagnosticErrorDetails(error) ?? 'Setup failed');\n session.emit({\n type: 'result',\n command,\n outcome: 'failed',\n completedSteps: session.completedSteps,\n error: stripAnsi(message),\n ...(error instanceof OnboardingError &&\n error.missingOptions.length > 0 && {\n missingOptions: error.missingOptions,\n }),\n });\n if (session.completedSteps.length > 0) {\n logger.warn(partialSetupWarning(session));\n }\n return logErrorAndExit(message);\n } finally {\n process.removeListener('exit', reportExit);\n logger.setAnimatedProgress(progressWasAnimated);\n }\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Reads the setup config, failing before any change when it is unusable. */\nexport function readSetupConfig(\n configFilepath: string\n): Record<string, unknown> {\n if (!fs.existsSync(configFilepath)) return {};\n try {\n const config = asRecord(\n JSON.parse(fs.readFileSync(configFilepath, 'utf8'))\n );\n if (config) return config;\n throw new Error('the file does not contain a JSON object');\n } catch (error) {\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `${configFilepath} is not a valid JSON config`,\n reassurance: 'No project files were changed',\n details: formatDiagnosticErrorDetails(error),\n fix: 'Fix or remove the file, then rerun the command',\n })\n );\n }\n}\n\nexport const INIT_SOURCE_HELP =\n \"Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'\";\n\nexport function setupConfigPath(\n options: Pick<ConfigureOptions, 'config'>\n): string {\n return options.config ? withJsonExtension(options.config) : 'gt.config.json';\n}\n\nexport function getConfiguredFramework(\n config: Record<string, unknown>\n): SupportedReactFrameworks | 'mintlify' | undefined {\n const framework = config.framework;\n return typeof framework === 'string' &&\n [...SUPPORTED_REACT_FRAMEWORKS, 'mintlify'].includes(\n framework as SupportedReactFrameworks\n )\n ? (framework as SupportedReactFrameworks | 'mintlify')\n : undefined;\n}\n\n/** JSON mode keeps the banner off stdout. */\nexport function displaySetupHeader(\n session: OnboardingSession,\n message: string\n) {\n if (session.json) logger.startCommand(message);\n else displayHeader(message);\n}\n\nexport function describeDefaults(\n framework: FrameworkObject | undefined\n): string {\n const buildTool = getBuildToolSetup(framework?.name);\n const translationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n if (framework?.type !== 'react') {\n return `Files saved locally in ${translationsDir}`;\n }\n const library = getReactFrameworkLibrary(framework);\n const setup = buildTool?.initializer ?? 'GTProvider';\n return `${library} & ${setup}, ${getFrameworkDisplayName(framework)}, Files saved locally in ${translationsDir}`;\n}\n\n/** Setup patterns name where each locale's files live, so they need [locale]. */\nexport function validateSetupPattern(pattern: string): true | string {\n return (\n pattern.includes('[locale]') ||\n `\"${pattern}\" must include [locale], e.g. ./locales/[locale]/*.json`\n );\n}\n\n/** Parses `--file-patterns <format>=<glob>` values, grouped by format. */\nexport function parseFilePatterns(\n session: OnboardingSession,\n values: string[] = []\n): Map<SetupFileFormat, string[]> {\n const patterns = new Map<SetupFileFormat, string[]>();\n for (const value of values) {\n const separator = value.indexOf('=');\n const format = value.slice(0, separator) as SetupFileFormat;\n const pattern = value.slice(separator + 1).trim();\n if (separator < 0 || !SETUP_FILE_FORMATS.includes(format) || !pattern) {\n session.reject(\n `--file-patterns \"${value}\" must look like <format>=<glob> with a format of ${SETUP_FILE_FORMATS.join(', ')}`\n );\n continue;\n }\n const problem = validateSetupPattern(pattern);\n if (problem !== true) {\n session.reject(`--file-patterns \"${value}\": ${problem}`);\n continue;\n }\n patterns.set(format, [...(patterns.get(format) ?? []), pattern]);\n }\n return patterns;\n}\n\n/** Detects the package manager, or asks only when prompts are allowed. */\nexport async function resolvePackageManager(\n session: OnboardingSession,\n specified?: string\n): Promise<PackageManager | undefined> {\n try {\n return await getPackageManager(\n process.cwd(),\n specified,\n !session.interactive\n );\n } catch (error) {\n if (!(error instanceof NoPackageManagerError)) throw error;\n session.require('--package-manager');\n return undefined;\n }\n}\n\nexport async function installWithProgress(\n session: OnboardingSession,\n packageName: string,\n packageManager: PackageManager,\n asDevDependency: boolean\n): Promise<void> {\n const spinner = logger.createSpinner('timer');\n spinner.start(\n `Installing ${packageName}${asDevDependency ? ' as a dev dependency' : ''} with ${packageManager.name}...`\n );\n try {\n await installPackage(packageName, packageManager, asDevDependency);\n } catch (error) {\n spinner.stop(`Could not install ${packageName}.`, 2);\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Failed to install ${packageName}`,\n details: formatDiagnosticErrorDetails(error),\n fix: `Install it with \\`${packageManager.name} ${packageManager.installCommand} ${packageName}\\`, then rerun the command`,\n })\n );\n }\n spinner.stop(`Installed ${packageName}.`);\n session.step(`installed ${packageName}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqEA,SAAgB,qBACd,SACA,YACS;AACT,QAAO,yBAAyB,QAAQ,CACrC,OAAO,oBAAoB,WAAW,CACtC,OACC,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACA,OACC,oBACA,wGACD,CACA,OACC,UACA,kHACD,CACA,OACC,cACA,6HACD,CACA,OAAO,iBAAiB,wCAAwC,CAChE,OAAO,6BAA6B,0BAA0B,CAC9D,OACC,0BACA,sEACD,CACA,UACC,IAAI,OACF,uBACA,mDACD,CAAC,QAAQ,CAAC,SAAS,MAAM,CAAC,CAC5B,CACA,OACC,6BACA,2CACD,CACA,UACC,IAAI,OACF,+BACA,gDACD,CAAC,QAAQ,CAAC,GAAG,oBAAoB,OAAO,CAAC,CAC3C,CACA,OACC,iCACA,+GACD,CACA,OACC,uBACA,uFACD,CACA,OAAO,0BAA0B,qCAAqC,CACtE,UACC,IAAI,OACF,qBACA,4DACD,CAAC,UAAU,mBAAmB,CAChC,CACA,OAAO,wBAAwB,wCAAwC,CACvE,OACC,qBACA,mDACD,CACA,OACC,oBACA,uDACD,CACA,OAAO,iBAAiB,0CAA0C,CAClE,OAAO,yBAAyB,4BAA4B,CAC5D,UACC,IAAI,OACF,0B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wBAAwB;GACtB,QAAQ;GACR,UAAU;GACV,cAAc,qBAAqB;GACnC,SAAS,6BAA6B,MAAM;GAC5C,KAAK,qBAAqB,eAAe,KAAK,GAAG,eAAe,eAAe,GAAG,YAAY;GAC/F,CAAC,CACH;;AAEH,SAAQ,KAAK,aAAa,YAAY,GAAG;AACzC,SAAQ,KAAK,aAAa,cAAc"}
1
+ {"version":3,"file":"onboarding.js","names":[],"sources":["../../src/setup/onboarding.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { Command, Option, type CommanderError } from 'commander';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport findFilepath from '../fs/findFilepath.js';\nimport { withJsonExtension } from '../fs/config/loadConfig.js';\nimport { logger } from '../console/logger.js';\nimport {\n displayHeader,\n getLastExitError,\n logErrorAndExit,\n stripAnsi,\n} from '../console/logging.js';\nimport {\n SUPPORTED_REACT_FRAMEWORKS,\n type FrameworkObject,\n type SupportedReactFrameworks,\n} from '../types/index.js';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport {\n SETUP_FILE_FORMATS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n getPackageManager,\n NoPackageManagerError,\n packageManagers,\n type PackageManager,\n} from '../utils/packageManager.js';\nimport { installPackage } from '../utils/installPackage.js';\n\n/** Answers accepted by `gt configure` (and the gt-vue `gt init`). */\nexport type ConfigureOptions = {\n config: string;\n src?: string[];\n interactive?: boolean;\n json?: boolean;\n defaults?: boolean;\n defaultLocale?: string;\n locales?: string[];\n storage?: 'local' | 'cdn';\n translationsDir?: string;\n fileFormats?: Array<SetupFileFormat | 'none'>;\n filePatterns?: string[];\n liveTranslations?: boolean;\n devCredentials?: boolean;\n projectId?: string;\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n packageManager?: string;\n};\n\n/** Answers accepted by the React-aware `gt init`. */\nexport type InitOptions = ConfigureOptions & {\n locadex?: boolean;\n reactSetup?: boolean;\n framework?: SupportedReactFrameworks;\n format?: boolean;\n};\n\n/** Flags for every configuration question; values prefill interactive runs. */\nexport function attachConfigureFlags(\n command: Command,\n sourceHelp: string\n): Command {\n return reportJsonArgumentErrors(command)\n .option('--src <paths...>', sourceHelp)\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option(\n '--no-interactive',\n 'Never prompt; fail listing the options still needed. Automatic when stdin or stdout is not a terminal'\n )\n .option(\n '--json',\n 'Write JSON events (sign-in, handoff, result) to stdout and all other output to stderr; implies --no-interactive'\n )\n .option(\n '--defaults',\n 'Accept the recommended value for every local choice that no flag or gt.config.json answers; never creates projects or keys'\n )\n .option('--no-defaults', 'Do not offer the recommended defaults')\n .option('--default-locale <locale>', 'Default locale, e.g. en')\n .option(\n '--locales <locales...>',\n 'Locales to translate into, e.g. fr es; replaces the configured list'\n )\n .addOption(\n new Option(\n '--storage <storage>',\n 'Where GT translations are stored for GT runtimes'\n ).choices(['local', 'cdn'])\n )\n .option(\n '--translations-dir <path>',\n 'Directory for local GT translation files'\n )\n .addOption(\n new Option(\n '--file-formats <formats...>',\n 'Additional file formats to translate, or none'\n ).choices([...SETUP_FILE_FORMATS, 'none'])\n )\n .option(\n '--file-patterns <patterns...>',\n 'Glob patterns as <format>=<glob> including [locale], e.g. json=./locales/[locale]/*.json; selects the format'\n )\n .option(\n '--live-translations',\n 'Local Vite storage: set up live development translations (creates a development key)'\n )\n .option('--no-live-translations', 'Skip live development translations')\n .addOption(\n new Option(\n '--dev-credentials',\n 'Save a project ID and a new development key to .env.local'\n ).conflicts('liveTranslations')\n )\n .option('--no-dev-credentials', 'Do not create development credentials')\n .option(\n '--project-id <id>',\n 'Existing project for the development credentials'\n )\n .option(\n '--create-project',\n 'Create a new project for the development credentials'\n )\n .option('--org-id <id>', 'Organization that owns --create-project')\n .option('--project-name <name>', 'Name for --create-project')\n .addOption(\n new Option(\n '--package-manager <id>',\n 'Package manager for installs when it cannot be detected'\n ).choices(packageManagers.map((packageManager) => packageManager.id))\n );\n}\n\nlet commandBeforeOnboarding: string | undefined;\n\nfunction reportExitBeforeOnboarding(code: number): void {\n if (code === 0 || commandBeforeOnboarding === undefined) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: commandBeforeOnboarding,\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it started; see stderr'\n ),\n } satisfies OnboardingEvent)}\\n`\n );\n}\n\n/**\n * Pre-action hooks, such as the monorepo version check, can exit before\n * runOnboarding installs its own result reporting; `--json` callers still\n * get a result. runOnboarding takes over once it starts.\n */\nexport function reportJsonExitsBeforeOnboarding(command: string): void {\n commandBeforeOnboarding = command;\n process.once('exit', reportExitBeforeOnboarding);\n}\n\n/**\n * Argument errors happen before the action runs, so `--json` callers would\n * otherwise get no result. Commander prints the error to stderr, then calls\n * this exit hook; returning lets it exit with the same code as before. The\n * hook replaces an exit override inherited from the program.\n */\nfunction reportJsonArgumentErrors(command: Command): Command {\n return command.exitOverride((error: CommanderError) => {\n if (error.exitCode === 0) return; // help and version output\n // An option after the failing argument is not parsed yet.\n const json =\n command.opts().json === true || process.argv.includes('--json');\n if (!json) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: command.name(),\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(error.message),\n } satisfies OnboardingEvent)}\\n`\n );\n });\n}\n\n/** Configuration flags plus the React application setup and Locadex choices. */\nexport function attachInitFlags(command: Command, sourceHelp: string) {\n return attachConfigureFlags(command, sourceHelp)\n .option(\n '--locadex',\n 'Mintlify and Next.js App Router: hand setup to the Locadex AI agent through GitHub instead'\n )\n .option('--no-locadex', 'Set up this project locally')\n .option(\n '--react-setup',\n 'React projects: install the GT library and add GTProvider or initializeGTSPA'\n )\n .option('--no-react-setup', 'Do not modify application source')\n .addOption(\n new Option(\n '--framework <framework>',\n 'React framework for --react-setup; overrides detection'\n ).choices(SUPPORTED_REACT_FRAMEWORKS)\n )\n .option(\n '--format',\n 'Next.js App Router: format files changed by setup with the detected formatter'\n )\n .option('--no-format', 'Leave files changed by setup unformatted');\n}\n\nexport type OnboardingEvent =\n | {\n type: 'authorization_required';\n verificationUri: string;\n verificationUriComplete?: string;\n userCode: string;\n }\n | { type: 'handoff'; url: string; reason: 'locadex' }\n | {\n type: 'result';\n command: string;\n outcome: 'success' | 'needs_human_action' | 'failed';\n completedSteps: string[];\n url?: string;\n /** Manual steps setup could not do, for needs_human_action. */\n actions?: string[];\n /** What to do next once setup succeeded, e.g. marking content for translation. */\n nextSteps?: string[];\n missingOptions?: string[];\n error?: string;\n };\n\n/** Needs-input and validation failures, raised before setup changes files. */\nexport class OnboardingError extends Error {\n constructor(\n message: string,\n readonly missingOptions: string[] = []\n ) {\n super(message);\n this.name = 'OnboardingError';\n }\n}\n\nfunction isInteractiveTerminal(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\n/**\n * One setup run: how unanswered questions are resolved, which options are\n * still missing, and which steps already changed the project.\n */\nexport class OnboardingSession {\n readonly interactive: boolean;\n readonly json: boolean;\n defaults = false;\n readonly completedSteps: string[] = [];\n /** Manual steps left for a person; they make the outcome needs_human_action. */\n readonly humanActions: string[] = [];\n private readonly missing = new Set<string>();\n private readonly invalid: string[] = [];\n private reported = false;\n\n constructor(\n readonly command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>\n ) {\n this.json = options.json === true;\n this.interactive =\n options.interactive !== false && !this.json && isInteractiveTerminal();\n }\n\n /**\n * Explicit flag, then existing config, then the recommended value when\n * defaults were accepted, then a prompt. Noninteractive runs use the\n * fallback of an optional question, or record the option as missing.\n */\n async answer<T>(\n option: string,\n {\n explicit,\n configured,\n recommended,\n fallback,\n ask,\n }: {\n explicit?: T;\n configured?: T;\n recommended?: T;\n fallback?: T;\n ask: () => Promise<T>;\n }\n ): Promise<T | undefined> {\n if (explicit !== undefined) return explicit;\n if (configured !== undefined) return configured;\n if (this.defaults && recommended !== undefined) return recommended;\n if (this.interactive) return ask();\n if (fallback !== undefined) return fallback;\n this.require(option);\n return undefined;\n }\n\n require(option: string): void {\n this.missing.add(option);\n }\n\n reject(problem: string): void {\n this.invalid.push(problem);\n }\n\n /** Stops before any change when an answer is missing or invalid. */\n assertResolved(): void {\n if (this.missing.size === 0 && this.invalid.length === 0) return;\n const missingOptions = [...this.missing];\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened:\n missingOptions.length > 0\n ? `Setup needs these options: ${missingOptions.join(', ')}`\n : 'Setup received invalid options',\n reassurance: 'No project files were changed',\n details: this.invalid,\n fix: this.defaults\n ? 'Pass the options (see --help), or rerun in an interactive terminal'\n : 'Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal',\n }),\n missingOptions\n );\n }\n\n step(name: string): void {\n this.completedSteps.push(name);\n }\n\n emit(event: OnboardingEvent): void {\n if (!this.json) return;\n if (event.type === 'result') this.reported = true;\n // Synchronous so events survive an immediate process.exit.\n fs.writeSync(process.stdout.fd, `${JSON.stringify(event)}\\n`);\n }\n\n /** A result for exits that bypass runOnboarding (e.g. settings validation). */\n reportUnexpectedExit(code: number): void {\n if (this.reported || code === 0) return;\n this.emit({\n type: 'result',\n command: this.command,\n outcome: 'failed',\n completedSteps: this.completedSteps,\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it finished; see stderr'\n ),\n });\n }\n}\n\nexport type OnboardingOutcome =\n | { outcome: 'success'; nextSteps?: string[] }\n | { outcome: 'needs_human_action'; url: string };\n\nfunction partialSetupWarning(session: OnboardingSession): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Setup stopped after these steps: ${session.completedSteps.join(', ')}`,\n why: 'the error below happened before the remaining steps ran',\n fix: `Review those changes, fix the error, then rerun \\`gt ${session.command}\\`; it reuses the saved configuration and credentials`,\n });\n}\n\n/**\n * Runs one setup command: selects prompt and output modes, then reports the\n * outcome. Failures exit nonzero with the steps that already ran.\n */\nexport async function runOnboarding(\n command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>,\n run: (session: OnboardingSession) => Promise<OnboardingOutcome>\n): Promise<void> {\n commandBeforeOnboarding = undefined;\n process.removeListener('exit', reportExitBeforeOnboarding);\n const session = new OnboardingSession(command, options);\n if (session.json) logger.setConsoleOutput('stderr');\n // Per-run modes; console routing is reset per command by BaseCLI.\n const progressWasAnimated = logger.setAnimatedProgress(session.interactive);\n const reportExit = (code: number) => session.reportUnexpectedExit(code);\n process.once('exit', reportExit);\n try {\n const result = await run(session);\n const needsHuman =\n result.outcome === 'needs_human_action' ||\n session.humanActions.length > 0;\n session.emit({\n type: 'result',\n command,\n outcome: needsHuman ? 'needs_human_action' : 'success',\n completedSteps: session.completedSteps,\n ...(result.outcome === 'needs_human_action' && { url: result.url }),\n ...(session.humanActions.length > 0 && {\n actions: session.humanActions,\n }),\n ...(result.outcome === 'success' &&\n result.nextSteps !== undefined &&\n result.nextSteps.length > 0 && { nextSteps: result.nextSteps }),\n });\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : (formatDiagnosticErrorDetails(error) ?? 'Setup failed');\n session.emit({\n type: 'result',\n command,\n outcome: 'failed',\n completedSteps: session.completedSteps,\n error: stripAnsi(message),\n ...(error instanceof OnboardingError &&\n error.missingOptions.length > 0 && {\n missingOptions: error.missingOptions,\n }),\n });\n if (session.completedSteps.length > 0) {\n logger.warn(partialSetupWarning(session));\n }\n return logErrorAndExit(message);\n } finally {\n process.removeListener('exit', reportExit);\n logger.setAnimatedProgress(progressWasAnimated);\n }\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Reads the setup config, failing before any change when it is unusable. */\nexport function readSetupConfig(\n configFilepath: string\n): Record<string, unknown> {\n if (!fs.existsSync(configFilepath)) return {};\n try {\n const config = asRecord(\n JSON.parse(fs.readFileSync(configFilepath, 'utf8'))\n );\n if (config) return config;\n throw new Error('the file does not contain a JSON object');\n } catch (error) {\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `${configFilepath} is not a valid JSON config`,\n reassurance: 'No project files were changed',\n details: formatDiagnosticErrorDetails(error),\n fix: 'Fix or remove the file, then rerun the command',\n })\n );\n }\n}\n\nexport const INIT_SOURCE_HELP =\n \"Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'\";\n\nexport function setupConfigPath(\n options: Pick<ConfigureOptions, 'config'>\n): string {\n return options.config ? withJsonExtension(options.config) : 'gt.config.json';\n}\n\nexport function getConfiguredFramework(\n config: Record<string, unknown>\n): SupportedReactFrameworks | 'mintlify' | undefined {\n const framework = config.framework;\n return typeof framework === 'string' &&\n [...SUPPORTED_REACT_FRAMEWORKS, 'mintlify'].includes(\n framework as SupportedReactFrameworks\n )\n ? (framework as SupportedReactFrameworks | 'mintlify')\n : undefined;\n}\n\n/** JSON mode keeps the banner off stdout. */\nexport function displaySetupHeader(\n session: OnboardingSession,\n message: string\n) {\n if (session.json) logger.startCommand(message);\n else displayHeader(message);\n}\n\nexport function describeDefaults(\n framework: FrameworkObject | undefined\n): string {\n const buildTool = getBuildToolSetup(framework?.name);\n const translationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n if (framework?.type !== 'react') {\n return `Files saved locally in ${translationsDir}`;\n }\n const library = getReactFrameworkLibrary(framework);\n const setup = buildTool?.initializer ?? 'GTProvider';\n return `${library} & ${setup}, ${getFrameworkDisplayName(framework)}, Files saved locally in ${translationsDir}`;\n}\n\n/** Setup patterns name where each locale's files live, so they need [locale]. */\nexport function validateSetupPattern(pattern: string): true | string {\n return (\n pattern.includes('[locale]') ||\n `\"${pattern}\" must include [locale], e.g. ./locales/[locale]/*.json`\n );\n}\n\n/** Parses `--file-patterns <format>=<glob>` values, grouped by format. */\nexport function parseFilePatterns(\n session: OnboardingSession,\n values: string[] = []\n): Map<SetupFileFormat, string[]> {\n const patterns = new Map<SetupFileFormat, string[]>();\n for (const value of values) {\n const separator = value.indexOf('=');\n const format = value.slice(0, separator) as SetupFileFormat;\n const pattern = value.slice(separator + 1).trim();\n if (separator < 0 || !SETUP_FILE_FORMATS.includes(format) || !pattern) {\n session.reject(\n `--file-patterns \"${value}\" must look like <format>=<glob> with a format of ${SETUP_FILE_FORMATS.join(', ')}`\n );\n continue;\n }\n const problem = validateSetupPattern(pattern);\n if (problem !== true) {\n session.reject(`--file-patterns \"${value}\": ${problem}`);\n continue;\n }\n patterns.set(format, [...(patterns.get(format) ?? []), pattern]);\n }\n return patterns;\n}\n\n/** Detects the package manager, or asks only when prompts are allowed. */\nexport async function resolvePackageManager(\n session: OnboardingSession,\n specified?: string\n): Promise<PackageManager | undefined> {\n try {\n return await getPackageManager(\n process.cwd(),\n specified,\n !session.interactive\n );\n } catch (error) {\n if (!(error instanceof NoPackageManagerError)) throw error;\n session.require('--package-manager');\n return undefined;\n }\n}\n\nexport async function installWithProgress(\n session: OnboardingSession,\n packageName: string,\n packageManager: PackageManager,\n asDevDependency: boolean\n): Promise<void> {\n const spinner = logger.createSpinner('timer');\n spinner.start(\n `Installing ${packageName}${asDevDependency ? ' as a dev dependency' : ''} with ${packageManager.name}...`\n );\n try {\n await installPackage(packageName, packageManager, asDevDependency);\n } catch (error) {\n spinner.stop(`Could not install ${packageName}.`, 2);\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Failed to install ${packageName}`,\n details: formatDiagnosticErrorDetails(error),\n fix: `Install it with \\`${packageManager.name} ${packageManager.installCommand} ${packageName}\\`, then rerun the command`,\n })\n );\n }\n spinner.stop(`Installed ${packageName}.`);\n session.step(`installed ${packageName}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqEA,SAAgB,qBACd,SACA,YACS;AACT,QAAO,yBAAyB,QAAQ,CACrC,OAAO,oBAAoB,WAAW,CACtC,OACC,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACA,OACC,oBACA,wGACD,CACA,OACC,UACA,kHACD,CACA,OACC,cACA,6HACD,CACA,OAAO,iBAAiB,wCAAwC,CAChE,OAAO,6BAA6B,0BAA0B,CAC9D,OACC,0BACA,sEACD,CACA,UACC,IAAI,OACF,uBACA,mDACD,CAAC,QAAQ,CAAC,SAAS,MAAM,CAAC,CAC5B,CACA,OACC,6BACA,2CACD,CACA,UACC,IAAI,OACF,+BACA,gDACD,CAAC,QAAQ,CAAC,GAAG,oBAAoB,OAAO,CAAC,CAC3C,CACA,OACC,iCACA,+GACD,CACA,OACC,uBACA,uFACD,CACA,OAAO,0BAA0B,qCAAqC,CACtE,UACC,IAAI,OACF,qBACA,4DACD,CAAC,UAAU,mBAAmB,CAChC,CACA,OAAO,wBAAwB,wCAAwC,CACvE,OACC,qBACA,mDACD,CACA,OACC,oBACA,uDACD,CACA,OAAO,iBAAiB,0CAA0C,CAClE,OAAO,yBAAyB,4BAA4B,CAC5D,UACC,IAAI,OACF,0BACA,0DACD,CAAC,QAAQ,gBAAgB,KAAK,mBAAmB,eAAe,GAAG,CAAC,CACtE;;AAGL,IAAI;AAEJ,SAAS,2BAA2B,MAAoB;AACtD,KAAI,SAAS,KAAK,4BAA4B,KAAA,EAAW;AACzD,IAAG,UACD,QAAQ,OAAO,IACf,GAAG,KAAK,UAAU;EAChB,MAAM;EACN,SAAS;EACT,SAAS;EACT,gBAAgB,EAAE;EAClB,OAAO,UACL,kBAAkB,IAAI,6CACvB;EACF,CAA2B,CAAC,IAC9B;;;;;;;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
@@ -1 +1,3 @@
1
+ /** Init stops with this before setting a React Native app up as web React. */
2
+ export declare const reactNativeSetupError: string;
1
3
  export declare function exitIfUnsupportedSetupTarget(): Promise<void>;
@@ -18,6 +18,15 @@ const electronSetupError = createDiagnosticMessage({
18
18
  whatHappened: "The automatic setup wizard is not ready for Electron applications",
19
19
  docsUrl: "https://generaltranslation.com/docs/react"
20
20
  });
21
+ /** Init stops with this before setting a React Native app up as web React. */
22
+ const reactNativeSetupError = createDiagnosticMessage({
23
+ source: "gt",
24
+ severity: "Error",
25
+ whatHappened: "The setup wizard cannot set up React Native or Expo apps yet",
26
+ reassurance: "Nothing was changed",
27
+ fix: "Follow the React Native quickstart, then run `npx gt translate`",
28
+ docsUrl: "https://generaltranslation.com/docs/react/react-native-quickstart"
29
+ });
21
30
  /**
22
31
  * Whether workspace package patterns name packages besides the root itself.
23
32
  * A single app may list only '.' (or nothing, keeping pnpm settings there).
@@ -47,6 +56,6 @@ async function exitIfUnsupportedSetupTarget() {
47
56
  if (isMonorepoRoot(packageJson)) throw new OnboardingError(workspaceRootSetupError);
48
57
  }
49
58
  //#endregion
50
- export { exitIfUnsupportedSetupTarget };
59
+ export { exitIfUnsupportedSetupTarget, reactNativeSetupError };
51
60
 
52
61
  //# sourceMappingURL=setupTarget.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"setupTarget.js","names":[],"sources":["../../src/setup/setupTarget.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\nimport YAML from 'yaml';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { asRecord, OnboardingError } from './onboarding.js';\n\nconst workspaceRootSetupError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The setup wizard cannot run from a monorepo workspace root',\n why: 'GT must be configured in the specific app you want to localize',\n fix: \"Change to that app's directory and rerun `npx gt@latest`\",\n});\n\nconst electronSetupError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened:\n 'The automatic setup wizard is not ready for Electron applications',\n docsUrl: 'https://generaltranslation.com/docs/react',\n});\n\n/**\n * Whether workspace package patterns name packages besides the root itself.\n * A single app may list only '.' (or nothing, keeping pnpm settings there).\n */\nfunction listsChildPackages(patterns: unknown): boolean {\n if (patterns === undefined || patterns === null) return false;\n if (!Array.isArray(patterns)) return true;\n return patterns.some(\n (pattern) =>\n typeof pattern !== 'string' || !/^(?:\\.\\/?|!.*)$/.test(pattern.trim())\n );\n}\n\nfunction isMonorepoRoot(packageJson: Record<string, unknown> | null): boolean {\n const pnpmWorkspace = path.join(process.cwd(), 'pnpm-workspace.yaml');\n if (fs.existsSync(pnpmWorkspace)) {\n let packages: unknown;\n try {\n packages = asRecord(\n YAML.parse(fs.readFileSync(pnpmWorkspace, 'utf8'))\n )?.packages;\n } catch {\n return true; // Unreadable: keep refusing, as for any workspace file.\n }\n if (listsChildPackages(packages)) return true;\n }\n const workspaces = packageJson?.workspaces;\n return listsChildPackages(\n Array.isArray(workspaces) ? workspaces : asRecord(workspaces)?.packages\n );\n}\n\nexport async function exitIfUnsupportedSetupTarget(): Promise<void> {\n const packageJson = await searchForPackageJson();\n if (packageJson && isPackageInstalled('electron', packageJson, false, true)) {\n throw new OnboardingError(electronSetupError);\n }\n if (isMonorepoRoot(packageJson)) {\n throw new OnboardingError(workspaceRootSetupError);\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAM,0BAA0B,wBAAwB;CACtD,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,KAAK;CACN,CAAC;AAEF,MAAM,qBAAqB,wBAAwB;CACjD,QAAQ;CACR,UAAU;CACV,cACE;CACF,SAAS;CACV,CAAC;;;;;AAMF,SAAS,mBAAmB,UAA4B;AACtD,KAAI,aAAa,KAAA,KAAa,aAAa,KAAM,QAAO;AACxD,KAAI,CAAC,MAAM,QAAQ,SAAS,CAAE,QAAO;AACrC,QAAO,SAAS,MACb,YACC,OAAO,YAAY,YAAY,CAAC,kBAAkB,KAAK,QAAQ,MAAM,CAAC,CACzE;;AAGH,SAAS,eAAe,aAAsD;CAC5E,MAAM,gBAAgB,KAAK,KAAK,QAAQ,KAAK,EAAE,sBAAsB;AACrE,KAAI,GAAG,WAAW,cAAc,EAAE;EAChC,IAAI;AACJ,MAAI;AACF,cAAW,SACT,KAAK,MAAM,GAAG,aAAa,eAAe,OAAO,CAAC,CACnD,EAAE;UACG;AACN,UAAO;;AAET,MAAI,mBAAmB,SAAS,CAAE,QAAO;;CAE3C,MAAM,aAAa,aAAa;AAChC,QAAO,mBACL,MAAM,QAAQ,WAAW,GAAG,aAAa,SAAS,WAAW,EAAE,SAChE;;AAGH,eAAsB,+BAA8C;CAClE,MAAM,cAAc,MAAM,sBAAsB;AAChD,KAAI,eAAe,mBAAmB,YAAY,aAAa,OAAO,KAAK,CACzE,OAAM,IAAI,gBAAgB,mBAAmB;AAE/C,KAAI,eAAe,YAAY,CAC7B,OAAM,IAAI,gBAAgB,wBAAwB"}
1
+ {"version":3,"file":"setupTarget.js","names":[],"sources":["../../src/setup/setupTarget.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\nimport YAML from 'yaml';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { asRecord, OnboardingError } from './onboarding.js';\n\nconst workspaceRootSetupError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The setup wizard cannot run from a monorepo workspace root',\n why: 'GT must be configured in the specific app you want to localize',\n fix: \"Change to that app's directory and rerun `npx gt@latest`\",\n});\n\nconst electronSetupError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened:\n 'The automatic setup wizard is not ready for Electron applications',\n docsUrl: 'https://generaltranslation.com/docs/react',\n});\n\n/** Init stops with this before setting a React Native app up as web React. */\nexport const reactNativeSetupError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The setup wizard cannot set up React Native or Expo apps yet',\n reassurance: 'Nothing was changed',\n fix: 'Follow the React Native quickstart, then run `npx gt translate`',\n docsUrl: 'https://generaltranslation.com/docs/react/react-native-quickstart',\n});\n\n/**\n * Whether workspace package patterns name packages besides the root itself.\n * A single app may list only '.' (or nothing, keeping pnpm settings there).\n */\nfunction listsChildPackages(patterns: unknown): boolean {\n if (patterns === undefined || patterns === null) return false;\n if (!Array.isArray(patterns)) return true;\n return patterns.some(\n (pattern) =>\n typeof pattern !== 'string' || !/^(?:\\.\\/?|!.*)$/.test(pattern.trim())\n );\n}\n\nfunction isMonorepoRoot(packageJson: Record<string, unknown> | null): boolean {\n const pnpmWorkspace = path.join(process.cwd(), 'pnpm-workspace.yaml');\n if (fs.existsSync(pnpmWorkspace)) {\n let packages: unknown;\n try {\n packages = asRecord(\n YAML.parse(fs.readFileSync(pnpmWorkspace, 'utf8'))\n )?.packages;\n } catch {\n return true; // Unreadable: keep refusing, as for any workspace file.\n }\n if (listsChildPackages(packages)) return true;\n }\n const workspaces = packageJson?.workspaces;\n return listsChildPackages(\n Array.isArray(workspaces) ? workspaces : asRecord(workspaces)?.packages\n );\n}\n\nexport async function exitIfUnsupportedSetupTarget(): Promise<void> {\n const packageJson = await searchForPackageJson();\n if (packageJson && isPackageInstalled('electron', packageJson, false, true)) {\n throw new OnboardingError(electronSetupError);\n }\n if (isMonorepoRoot(packageJson)) {\n throw new OnboardingError(workspaceRootSetupError);\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAM,0BAA0B,wBAAwB;CACtD,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,KAAK;CACN,CAAC;AAEF,MAAM,qBAAqB,wBAAwB;CACjD,QAAQ;CACR,UAAU;CACV,cACE;CACF,SAAS;CACV,CAAC;;AAGF,MAAa,wBAAwB,wBAAwB;CAC3D,QAAQ;CACR,UAAU;CACV,cAAc;CACd,aAAa;CACb,KAAK;CACL,SAAS;CACV,CAAC;;;;;AAMF,SAAS,mBAAmB,UAA4B;AACtD,KAAI,aAAa,KAAA,KAAa,aAAa,KAAM,QAAO;AACxD,KAAI,CAAC,MAAM,QAAQ,SAAS,CAAE,QAAO;AACrC,QAAO,SAAS,MACb,YACC,OAAO,YAAY,YAAY,CAAC,kBAAkB,KAAK,QAAQ,MAAM,CAAC,CACzE;;AAGH,SAAS,eAAe,aAAsD;CAC5E,MAAM,gBAAgB,KAAK,KAAK,QAAQ,KAAK,EAAE,sBAAsB;AACrE,KAAI,GAAG,WAAW,cAAc,EAAE;EAChC,IAAI;AACJ,MAAI;AACF,cAAW,SACT,KAAK,MAAM,GAAG,aAAa,eAAe,OAAO,CAAC,CACnD,EAAE;UACG;AACN,UAAO;;AAET,MAAI,mBAAmB,SAAS,CAAE,QAAO;;CAE3C,MAAM,aAAa,aAAa;AAChC,QAAO,mBACL,MAAM,QAAQ,WAAW,GAAG,aAAa,SAAS,WAAW,EAAE,SAChE;;AAGH,eAAsB,+BAA8C;CAClE,MAAM,cAAc,MAAM,sBAAsB;AAChD,KAAI,eAAe,mBAAmB,YAAY,aAAa,OAAO,KAAK,CACzE,OAAM,IAAI,gBAAgB,mBAAmB;AAE/C,KAAI,eAAe,YAAY,CAC7B,OAAM,IAAI,gBAAgB,wBAAwB"}
@@ -15,5 +15,5 @@ export type ReactSetupPlan = {
15
15
  * undefined when the setup is declined or an answer is still missing.
16
16
  */
17
17
  export declare function resolveReactSetup(session: OnboardingSession, options: InitOptions, detected: ReactFrameworkObject, configuredFramework?: SupportedReactFrameworks): Promise<ReactSetupPlan | undefined>;
18
- /** Wraps Next.js App Router content and adds withGTConfig(); installs happen first. */
18
+ /** Adds GTProvider and withGTConfig() to a Next.js App Router app; installs happen first. */
19
19
  export declare function executeReactSetup(session: OnboardingSession, plan: ReactSetupPlan, options: InitOptions): Promise<void>;
@@ -1,6 +1,5 @@
1
1
  import { logger } from "../console/logger.js";
2
2
  import { getPackageJson, isPackageInstalled } from "../utils/packageJson.js";
3
- import "../utils/constants.js";
4
3
  import "../types/libraries.js";
5
4
  import { exitSync, promptConfirm, promptSelect } from "../console/logging.js";
6
5
  import findFilepath from "../fs/findFilepath.js";
@@ -9,7 +8,7 @@ import { detectFormatter, formatFiles } from "../hooks/postProcess.js";
9
8
  import { handleInitGT } from "../next/parse/handleInitGT.js";
10
9
  import { wrapContentNext } from "../next/parse/wrapContent.js";
11
10
  import { getFrameworkDisplayName, getReactFrameworkLibrary } from "./frameworkUtils.js";
12
- import { getBuildToolSetup } from "./buildTools/index.js";
11
+ import { getBuildToolSetup, getSetupDocsUrl } from "./buildTools/index.js";
13
12
  import chalk from "chalk";
14
13
  import { createDiagnosticMessage } from "generaltranslation/internal";
15
14
  //#region src/setup/wizard.ts
@@ -20,14 +19,13 @@ const cancelledMessage = "Operation cancelled. You can re-run this wizard with:
20
19
  */
21
20
  async function resolveReactSetup(session, options, detected, configuredFramework) {
22
21
  const library = getReactFrameworkLibrary(detected);
23
- const buildTool = getBuildToolSetup(detected.name);
24
- const initializer = buildTool?.initializer;
22
+ const initializer = getBuildToolSetup(detected.name)?.initializer;
25
23
  if (!await session.answer("--react-setup", {
26
24
  explicit: options.reactSetup,
27
25
  recommended: true,
28
26
  ask: async () => {
29
27
  const answer = await promptConfirm({
30
- message: `Would you like to install ${library} and ${initializer ? `configure ${initializer}` : "add the GTProvider"}? See the docs for more information: ${buildTool?.docsUrl ?? "https://generaltranslation.com/docs/react/tutorials/quickstart"}`,
28
+ message: `Would you like to install ${library} and ${initializer ? `configure ${initializer}` : "add the GTProvider"}? See the docs for more information: ${getSetupDocsUrl(detected.name)}`,
31
29
  defaultValue: true
32
30
  });
33
31
  if (answer && !await promptConfirm({
@@ -130,13 +128,13 @@ Please let us know what you would like to see added at https://github.com/genera
130
128
  }
131
129
  return plan;
132
130
  }
133
- /** Wraps Next.js App Router content and adds withGTConfig(); installs happen first. */
131
+ /** Adds GTProvider and withGTConfig() to a Next.js App Router app; installs happen first. */
134
132
  async function executeReactSetup(session, plan, options) {
135
133
  if (plan.framework !== "next-app" || !plan.nextConfigPath) return;
136
134
  const errors = [];
137
135
  const warnings = [];
138
136
  const spinner = logger.createSpinner();
139
- spinner.start("Wrapping JSX content with <T> tags...");
137
+ spinner.start("Adding GTProvider to the root layout...");
140
138
  const { filesUpdated } = await wrapContentNext({
141
139
  ...options,
142
140
  disableIds: true,
@@ -145,7 +143,7 @@ async function executeReactSetup(session, plan, options) {
145
143
  addGTProvider: true
146
144
  }, "gt-next", errors, warnings);
147
145
  spinner.stop(chalk.green(`Success! Updated ${chalk.bold.cyan(filesUpdated.length)} files:\n`) + filesUpdated.map((file) => `${chalk.green("-")} ${file}`).join("\n"));
148
- if (filesUpdated.length > 0) session.step("wrapped JSX content");
146
+ if (filesUpdated.length > 0) session.step("added GTProvider to the root layout");
149
147
  const tsconfigPath = findFilepath(["tsconfig.json"]);
150
148
  await handleInitGT(plan.nextConfigPath, errors, warnings, filesUpdated, plan.packageJson, tsconfigPath ? loadConfig(tsconfigPath) : void 0);
151
149
  if (warnings.length > 0) logger.warn(chalk.yellow("Warnings encountered:") + "\n" + warnings.map((warning) => `${chalk.yellow("-")} ${warning}`).join("\n"));
@@ -1 +1 @@
1
- {"version":3,"file":"wizard.js","names":[],"sources":["../../src/setup/wizard.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { detectFormatter, formatFiles } from '../hooks/postProcess.js';\nimport type { Formatter } from '../hooks/postProcess.js';\nimport { exitSync, promptConfirm, promptSelect } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport type {\n ReactFrameworkObject,\n SupportedReactFrameworks,\n} from '../types/index.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport { handleInitGT } from '../next/parse/handleInitGT.js';\nimport { getPackageJson, isPackageInstalled } from '../utils/packageJson.js';\nimport { wrapContentNext } from '../next/parse/wrapContent.js';\nimport { loadConfig } from '../fs/config/loadConfig.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport { Libraries } from '../types/libraries.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport { REACT_QUICKSTART_URL } from '../utils/constants.js';\nimport type { InitOptions, OnboardingSession } from './onboarding.js';\n\n/** Everything the React application setup will do, resolved before changes. */\nexport type ReactSetupPlan = {\n framework: SupportedReactFrameworks;\n packageJson: Record<string, unknown>;\n /** GT library to install, when it is not installed yet. */\n install?: string;\n nextConfigPath?: string;\n formatter?: Formatter;\n};\n\nconst cancelledMessage =\n 'Operation cancelled. You can re-run this wizard with: npx gt init';\n\n/**\n * Resolves whether and how to set up the React application. Returns\n * undefined when the setup is declined or an answer is still missing.\n */\nexport async function resolveReactSetup(\n session: OnboardingSession,\n options: InitOptions,\n detected: ReactFrameworkObject,\n configuredFramework?: SupportedReactFrameworks\n): Promise<ReactSetupPlan | undefined> {\n const library = getReactFrameworkLibrary(detected);\n const buildTool = getBuildToolSetup(detected.name);\n const initializer = buildTool?.initializer;\n const setupApp = await session.answer('--react-setup', {\n explicit: options.reactSetup,\n recommended: true,\n ask: async () => {\n const answer = await promptConfirm({\n message: `Would you like to install ${library} and ${initializer ? `configure ${initializer}` : 'add the GTProvider'}? See the docs for more information: ${buildTool?.docsUrl ?? REACT_QUICKSTART_URL}`,\n defaultValue: true,\n });\n // A prompted opt-in gets a last warning; flags and defaults already chose.\n if (\n answer &&\n !(await promptConfirm({\n message: chalk.yellow(\n `This wizard will configure your ${getFrameworkDisplayName(detected)} project for internationalization with GT. If your project is already using a different i18n library, this wizard may cause issues.\n\nMake sure you have committed or stashed any changes. Do you want to continue?`\n ),\n defaultValue: true,\n cancelMessage: cancelledMessage,\n }))\n ) {\n logger.info(cancelledMessage);\n return exitSync(0);\n }\n return answer;\n },\n });\n if (!setupApp) return undefined;\n\n const framework = await session.answer<SupportedReactFrameworks | 'other'>(\n '--framework',\n {\n explicit: options.framework,\n configured: configuredFramework,\n recommended: detected.name,\n ask: () =>\n promptSelect<SupportedReactFrameworks | 'other'>({\n message: 'Which framework are you using?',\n options: [\n { value: 'next-app', label: chalk.blue('Next.js App Router') },\n { value: 'next-pages', label: chalk.green('Next.js Pages Router') },\n { value: 'vite', label: chalk.cyan('Vite + React') },\n { value: 'gatsby', label: chalk.magenta('Gatsby') },\n { value: 'react', label: chalk.yellow('React') },\n { value: 'redwood', label: chalk.red('RedwoodJS') },\n { value: 'tanstack-start', label: chalk.cyan('TanStack Start') },\n { value: 'react-router', label: chalk.cyan('React Router') },\n { value: 'other', label: chalk.dim('Other') },\n ],\n defaultValue: detected.name,\n }),\n }\n );\n if (framework === 'other') {\n logger.error(\n `Sorry, the wizard doesn't currently support other React frameworks.\nPlease let us know what you would like to see added at https://github.com/generaltranslation/gt/issues`\n );\n return exitSync(0);\n }\n if (!framework) return undefined;\n\n const packageJson = await getPackageJson();\n if (!packageJson) {\n session.reject(\n 'No package.json found in the current directory. Run this command from the root of your project'\n );\n return undefined;\n }\n const install = getReactFrameworkLibrary({ name: framework, type: 'react' });\n const plan: ReactSetupPlan = {\n framework,\n packageJson,\n install: isPackageInstalled(install, packageJson) ? undefined : install,\n };\n\n if (framework === 'next-app') {\n plan.nextConfigPath = findFilepath([\n './next.config.js',\n './next.config.ts',\n './next.config.mjs',\n './next.config.mts',\n ]);\n if (!plan.nextConfigPath) {\n session.reject('No next.config.[js|ts|mjs|mts] file found');\n }\n const formatter = await detectFormatter();\n if (\n formatter &&\n (await session.answer('--format', {\n explicit: options.format,\n recommended: true,\n ask: () =>\n promptConfirm({\n message: `Would you like the wizard to auto-format the modified files? ${chalk.dim(\n `(${formatter})`\n )}`,\n defaultValue: true,\n }),\n }))\n ) {\n plan.formatter = formatter;\n }\n }\n return plan;\n}\n\n/** Wraps Next.js App Router content and adds withGTConfig(); installs happen first. */\nexport async function executeReactSetup(\n session: OnboardingSession,\n plan: ReactSetupPlan,\n options: InitOptions\n): Promise<void> {\n if (plan.framework !== 'next-app' || !plan.nextConfigPath) return;\n\n const errors: string[] = [];\n const warnings: string[] = [];\n const spinner = logger.createSpinner();\n spinner.start('Wrapping JSX content with <T> tags...');\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated } = await wrapContentNext(\n {\n ...options,\n disableIds: true,\n disableFormatting: true,\n skipTs: true,\n addGTProvider: true,\n },\n Libraries.GT_NEXT,\n errors,\n warnings\n );\n spinner.stop(\n chalk.green(\n `Success! Updated ${chalk.bold.cyan(filesUpdated.length)} files:\\n`\n ) + filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\\n')\n );\n if (filesUpdated.length > 0) session.step('wrapped JSX content');\n\n // Add the withGTConfig() function to the next.config.js file\n const tsconfigPath = findFilepath(['tsconfig.json']);\n await handleInitGT(\n plan.nextConfigPath,\n errors,\n warnings,\n filesUpdated,\n plan.packageJson,\n tsconfigPath ? loadConfig(tsconfigPath) : undefined\n );\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow('Warnings encountered:') +\n '\\n' +\n warnings.map((warning) => `${chalk.yellow('-')} ${warning}`).join('\\n')\n );\n }\n if (errors.length > 0) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'Setup could not update some application files',\n details: errors,\n fix: 'Fix the reported files, then rerun `npx gt init`',\n })\n );\n }\n logger.step(\n chalk.green(`Added withGTConfig() to your ${plan.nextConfigPath} file.`)\n );\n session.step(`added withGTConfig() to ${plan.nextConfigPath}`);\n\n if (plan.formatter) await formatFiles(filesUpdated, plan.formatter);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,MAAM,mBACJ;;;;;AAMF,eAAsB,kBACpB,SACA,SACA,UACA,qBACqC;CACrC,MAAM,UAAU,yBAAyB,SAAS;CAClD,MAAM,YAAY,kBAAkB,SAAS,KAAK;CAClD,MAAM,cAAc,WAAW;AA4B/B,KAAI,CAAC,MA3BkB,QAAQ,OAAO,iBAAiB;EACrD,UAAU,QAAQ;EAClB,aAAa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;AAED,KAAI,SAAS,SAAS,EACpB,QAAO,KACL,MAAM,OAAO,wBAAwB,GACnC,OACA,SAAS,KAAK,YAAY,GAAG,MAAM,OAAO,IAAI,CAAC,GAAG,UAAU,CAAC,KAAK,KAAK,CAC1E;AAEH,KAAI,OAAO,SAAS,EAClB,OAAM,IAAI,MACR,wBAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAAS;EACT,KAAK;EACN,CAAC,CACH;AAEH,QAAO,KACL,MAAM,MAAM,gCAAgC,KAAK,eAAe,QAAQ,CACzE;AACD,SAAQ,KAAK,2BAA2B,KAAK,iBAAiB;AAE9D,KAAI,KAAK,UAAW,OAAM,YAAY,cAAc,KAAK,UAAU"}
1
+ {"version":3,"file":"wizard.js","names":[],"sources":["../../src/setup/wizard.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { detectFormatter, formatFiles } from '../hooks/postProcess.js';\nimport type { Formatter } from '../hooks/postProcess.js';\nimport { exitSync, promptConfirm, promptSelect } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport type {\n ReactFrameworkObject,\n SupportedReactFrameworks,\n} from '../types/index.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport { handleInitGT } from '../next/parse/handleInitGT.js';\nimport { getPackageJson, isPackageInstalled } from '../utils/packageJson.js';\nimport { wrapContentNext } from '../next/parse/wrapContent.js';\nimport { loadConfig } from '../fs/config/loadConfig.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport { Libraries } from '../types/libraries.js';\nimport { getBuildToolSetup, getSetupDocsUrl } from './buildTools/index.js';\nimport type { InitOptions, OnboardingSession } from './onboarding.js';\n\n/** Everything the React application setup will do, resolved before changes. */\nexport type ReactSetupPlan = {\n framework: SupportedReactFrameworks;\n packageJson: Record<string, unknown>;\n /** GT library to install, when it is not installed yet. */\n install?: string;\n nextConfigPath?: string;\n formatter?: Formatter;\n};\n\nconst cancelledMessage =\n 'Operation cancelled. You can re-run this wizard with: npx gt init';\n\n/**\n * Resolves whether and how to set up the React application. Returns\n * undefined when the setup is declined or an answer is still missing.\n */\nexport async function resolveReactSetup(\n session: OnboardingSession,\n options: InitOptions,\n detected: ReactFrameworkObject,\n configuredFramework?: SupportedReactFrameworks\n): Promise<ReactSetupPlan | undefined> {\n const library = getReactFrameworkLibrary(detected);\n const buildTool = getBuildToolSetup(detected.name);\n const initializer = buildTool?.initializer;\n const setupApp = await session.answer('--react-setup', {\n explicit: options.reactSetup,\n recommended: true,\n ask: async () => {\n const answer = await promptConfirm({\n message: `Would you like to install ${library} and ${initializer ? `configure ${initializer}` : 'add the GTProvider'}? See the docs for more information: ${getSetupDocsUrl(detected.name)}`,\n defaultValue: true,\n });\n // A prompted opt-in gets a last warning; flags and defaults already chose.\n if (\n answer &&\n !(await promptConfirm({\n message: chalk.yellow(\n `This wizard will configure your ${getFrameworkDisplayName(detected)} project for internationalization with GT. If your project is already using a different i18n library, this wizard may cause issues.\n\nMake sure you have committed or stashed any changes. Do you want to continue?`\n ),\n defaultValue: true,\n cancelMessage: cancelledMessage,\n }))\n ) {\n logger.info(cancelledMessage);\n return exitSync(0);\n }\n return answer;\n },\n });\n if (!setupApp) return undefined;\n\n const framework = await session.answer<SupportedReactFrameworks | 'other'>(\n '--framework',\n {\n explicit: options.framework,\n configured: configuredFramework,\n recommended: detected.name,\n ask: () =>\n promptSelect<SupportedReactFrameworks | 'other'>({\n message: 'Which framework are you using?',\n options: [\n { value: 'next-app', label: chalk.blue('Next.js App Router') },\n { value: 'next-pages', label: chalk.green('Next.js Pages Router') },\n { value: 'vite', label: chalk.cyan('Vite + React') },\n { value: 'gatsby', label: chalk.magenta('Gatsby') },\n { value: 'react', label: chalk.yellow('React') },\n { value: 'redwood', label: chalk.red('RedwoodJS') },\n { value: 'tanstack-start', label: chalk.cyan('TanStack Start') },\n { value: 'react-router', label: chalk.cyan('React Router') },\n { value: 'other', label: chalk.dim('Other') },\n ],\n defaultValue: detected.name,\n }),\n }\n );\n if (framework === 'other') {\n logger.error(\n `Sorry, the wizard doesn't currently support other React frameworks.\nPlease let us know what you would like to see added at https://github.com/generaltranslation/gt/issues`\n );\n return exitSync(0);\n }\n if (!framework) return undefined;\n\n const packageJson = await getPackageJson();\n if (!packageJson) {\n session.reject(\n 'No package.json found in the current directory. Run this command from the root of your project'\n );\n return undefined;\n }\n const install = getReactFrameworkLibrary({ name: framework, type: 'react' });\n const plan: ReactSetupPlan = {\n framework,\n packageJson,\n install: isPackageInstalled(install, packageJson) ? undefined : install,\n };\n\n if (framework === 'next-app') {\n plan.nextConfigPath = findFilepath([\n './next.config.js',\n './next.config.ts',\n './next.config.mjs',\n './next.config.mts',\n ]);\n if (!plan.nextConfigPath) {\n session.reject('No next.config.[js|ts|mjs|mts] file found');\n }\n const formatter = await detectFormatter();\n if (\n formatter &&\n (await session.answer('--format', {\n explicit: options.format,\n recommended: true,\n ask: () =>\n promptConfirm({\n message: `Would you like the wizard to auto-format the modified files? ${chalk.dim(\n `(${formatter})`\n )}`,\n defaultValue: true,\n }),\n }))\n ) {\n plan.formatter = formatter;\n }\n }\n return plan;\n}\n\n/** Adds GTProvider and withGTConfig() to a Next.js App Router app; installs happen first. */\nexport async function executeReactSetup(\n session: OnboardingSession,\n plan: ReactSetupPlan,\n options: InitOptions\n): Promise<void> {\n if (plan.framework !== 'next-app' || !plan.nextConfigPath) return;\n\n const errors: string[] = [];\n const warnings: string[] = [];\n const spinner = logger.createSpinner();\n spinner.start('Adding GTProvider to the root layout...');\n // Add GTProvider to the root layout; content is never wrapped in <T>\n const { filesUpdated } = await wrapContentNext(\n {\n ...options,\n disableIds: true,\n disableFormatting: true,\n skipTs: true,\n addGTProvider: true,\n },\n Libraries.GT_NEXT,\n errors,\n warnings\n );\n spinner.stop(\n chalk.green(\n `Success! Updated ${chalk.bold.cyan(filesUpdated.length)} files:\\n`\n ) + filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\\n')\n );\n if (filesUpdated.length > 0)\n session.step('added GTProvider to the root layout');\n\n // Add the withGTConfig() function to the next.config.js file\n const tsconfigPath = findFilepath(['tsconfig.json']);\n await handleInitGT(\n plan.nextConfigPath,\n errors,\n warnings,\n filesUpdated,\n plan.packageJson,\n tsconfigPath ? loadConfig(tsconfigPath) : undefined\n );\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow('Warnings encountered:') +\n '\\n' +\n warnings.map((warning) => `${chalk.yellow('-')} ${warning}`).join('\\n')\n );\n }\n if (errors.length > 0) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'Setup could not update some application files',\n details: errors,\n fix: 'Fix the reported files, then rerun `npx gt init`',\n })\n );\n }\n logger.step(\n chalk.green(`Added withGTConfig() to your ${plan.nextConfigPath} file.`)\n );\n session.step(`added withGTConfig() to ${plan.nextConfigPath}`);\n\n if (plan.formatter) await formatFiles(filesUpdated, plan.formatter);\n}\n"],"mappings":";;;;;;;;;;;;;;AAiCA,MAAM,mBACJ;;;;;AAMF,eAAsB,kBACpB,SACA,SACA,UACA,qBACqC;CACrC,MAAM,UAAU,yBAAyB,SAAS;CAElD,MAAM,cADY,kBAAkB,SAAS,KAChB,EAAE;AA4B/B,KAAI,CAAC,MA3BkB,QAAQ,OAAO,iBAAiB;EACrD,UAAU,QAAQ;EAClB,aAAa;EACb,KAAK,YAAY;GACf,MAAM,SAAS,MAAM,cAAc;IACjC,SAAS,6BAA6B,QAAQ,OAAO,cAAc,aAAa,gBAAgB,qBAAqB,uCAAuC,gBAAgB,SAAS,KAAK;IAC1L,cAAc;IACf,CAAC;AAEF,OACE,UACA,CAAE,MAAM,cAAc;IACpB,SAAS,MAAM,OACb,mCAAmC,wBAAwB,SAAS,CAAC;;+EAGtE;IACD,cAAc;IACd,eAAe;IAChB,CAAC,EACF;AACA,WAAO,KAAK,iBAAiB;AAC7B,WAAO,SAAS,EAAE;;AAEpB,UAAO;;EAEV,CA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AK,2BAA2B,KAAK,iBAAiB;AAE9D,KAAI,KAAK,UAAW,OAAM,YAAY,cAAc,KAAK,UAAU"}
@@ -115,6 +115,11 @@ export type FrameworkObject = {
115
115
  export type ReactFrameworkObject = Extract<FrameworkObject, {
116
116
  type: 'react';
117
117
  }>;
118
+ /** Detected so setup can stop; the wizard cannot set React Native up yet. */
119
+ export type ReactNativeFrameworkObject = {
120
+ name: 'react-native';
121
+ type: 'react-native';
122
+ };
118
123
  export type FrameworkType = FrameworkObject['type'];
119
124
  export type SupportedFrameworks = FrameworkObject['name'];
120
125
  export type SupportedReactFrameworks = Extract<FrameworkObject, {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["import type { CustomMapping } from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport type { ModelProvider } from 'generaltranslation/internal';\nimport type { FileFormat } from 'generaltranslation/types';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport {\n ParsingConfigOptions,\n GTParsingFlags,\n BaseParsingFlags,\n ParseFlagsByFileType,\n} from './parsing.js';\nimport { Libraries, InlineLibrary } from './libraries.js';\n\nexport type { Updates } from 'generaltranslation/types';\n\nexport type Options = {\n config: string;\n apiKey?: string;\n projectId?: string;\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n src?: string[];\n defaultLocale?: string;\n locales?: string[];\n baseUrl: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n dryRun: boolean;\n timeout: number;\n force?: boolean;\n stageTranslations?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type OpenApiConfig = {\n files: string[];\n translateFields?: string[];\n};\n\nexport type MintlifyOptions = {\n openapi?: OpenApiConfig;\n inferTitleFromFilename?: boolean;\n localizeRedirects?: boolean; // add localized redirects for pages renamed or removed in a translate run\n};\n\nexport type SharedFlags = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n};\n\nexport type TranslateFlags = SharedFlags & {\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n defaultLocale?: string;\n locales?: string[];\n ignoreErrors?: boolean;\n src?: string[];\n timeout: number;\n dryRun: boolean;\n saveLocal?: boolean;\n stageTranslations?: boolean;\n setupProject?: boolean; // if true, skip enqueue step\n publish?: boolean;\n force?: boolean;\n forceDownload?: boolean;\n tag?: string;\n message?: string;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n omitConfigIds?: boolean;\n excludeStaticUrls?: string[];\n excludeStaticImports?: string[];\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type WrapOptions = {\n src?: string[];\n config: string;\n skipTs: boolean;\n disableIds: boolean;\n disableFormatting: boolean;\n addGTProvider: boolean;\n};\n\nexport type SetupOptions = {\n src?: string[];\n config: string;\n};\n\nexport type GenerateSourceOptions = {\n src?: string[];\n config: string;\n defaultLocale: string;\n dictionary?: string;\n jsconfig?: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n};\n\nexport type Framework =\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_REACT\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START;\n\nexport const SUPPORTED_REACT_FRAMEWORKS = [\n 'next-app',\n 'next-pages',\n 'vite',\n 'gatsby',\n 'react',\n 'redwood',\n 'tanstack-start',\n 'react-router',\n] as const;\n\nexport type FrameworkObject =\n | {\n name: 'mintlify';\n type?: undefined;\n }\n | {\n name: (typeof SUPPORTED_REACT_FRAMEWORKS)[number];\n type: 'react';\n };\nexport type ReactFrameworkObject = Extract<FrameworkObject, { type: 'react' }>;\n\nexport type FrameworkType = FrameworkObject['type'];\n\nexport type SupportedFrameworks = FrameworkObject['name'];\nexport type SupportedReactFrameworks = Extract<\n FrameworkObject,\n { type: 'react' }\n>['name'];\n\nexport type SupportedLibraries =\n | InlineLibrary\n | 'next-intl'\n | 'react-i18next'\n | 'next-i18next'\n | 'i18next'\n | 'i18next-icu'\n | 'base';\n\nexport interface ContentScanner {\n scanForContent(\n options: WrapOptions,\n framework: Framework\n ): Promise<{\n errors: string[];\n filesUpdated: string[];\n warnings: string[];\n }>;\n}\n\n// Create a type based on the supported file extensions\nexport type SupportedFileExtension = (typeof SUPPORTED_FILE_EXTENSIONS)[number];\n\n// Update ResolvedFiles to use the dynamic keys\nexport type ResolvedFiles = {\n [K in SupportedFileExtension]?: string[];\n} & {\n gt?: string; // Output glob: /path/[locale].json\n};\n\nexport type TransformOption = {\n match?: string; // regex to match strings, supports capture groups\n replace: string; // string or regex pattern to replace the match with\n // Special placeholders:\n // -> if used in the match string, they will be replaced with the corresponding default locale property value\n // -> if used in the replace string, they will be replaced with the corresponding target locale property value\n // {locale} -> will be replaced with the locale code\n // And any other property from getLocaleProperties()\n};\n\nexport type TransformFiles = {\n [K in SupportedFileExtension]?: TransformOption | string | TransformOption[]; // if a string, only transform the file name\n};\n\nexport type TransformFormats = {\n [K in SupportedFileExtension]?: FileFormat;\n};\n\n// Include patterns can be plain strings or objects with a publish flag\nexport type IncludePattern = string | { pattern: string; publish?: boolean };\n\n// Review requirement for matched files: a boolean applies to all files of the\n// type; the object form opts path groups in/out with globs. exclude wins over\n// include; files matching neither inherit the top-level requiresReview default.\nexport type RequiresReviewConfig =\n | boolean\n | {\n include?: string[];\n exclude?: string[];\n };\n\n// Update FilesOptions to fix the error\nexport type FilesOptions = {\n [K in SupportedFileExtension]?: {\n include: IncludePattern[];\n exclude?: string[];\n transform?: string | TransformOption | TransformOption[];\n transformationFormat?: FileFormat;\n parsingFlags?: BaseParsingFlags; // Flags for parsing inline content\n requiresReview?: RequiresReviewConfig; // Whether translated versions of matched files require approval before use\n };\n} & {\n gt?: {\n output: string; // Output glob: /path/[locale].json\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags?: Partial<GTParsingFlags>; // Flags for parsing inline content\n /**\n * @deprecated\n * use `files.gt.parsingFlags.includeSourceCodeContext` instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n};\n\n// Shared settings between all API-related commands\nexport type FontsConfig = {\n include: string[]; // globs of .ttf/.otf files\n exclude?: string[];\n};\n\nexport type Settings = {\n config: string;\n configDirectory: string;\n baseUrl: string;\n dashboardUrl: string;\n apiKey?: string;\n userTokenProvider?: UserTokenProvider;\n projectId?: string;\n defaultLocale: string;\n locales: string[];\n customMapping?: CustomMapping;\n files: {\n resolvedPaths: ResolvedFiles; // Absolute resolved paths for the default locale\n placeholderPaths: ResolvedFiles; // Absolute placeholder paths for all locales containing [locale]\n transformPaths: TransformFiles; // Absolute transform paths for all locales containing [locale]\n transformFormats: TransformFormats; // Output file format transforms keyed by config file type\n publishPaths: Set<string>; // Absolute paths explicitly opted IN to publishing\n unpublishPaths: Set<string>; // Absolute paths explicitly opted OUT of publishing\n requiresReviewPaths: Set<string>; // Absolute paths whose effective requiresReview policy is true\n parsingFlags: ParseFlagsByFileType;\n gtJson: {\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags: GTParsingFlags; // Flags for parsing inline content\n /**\n * @deprecated\n * use {@link files.gt.GTParsingFlags.parsingFlags.includeSourceCodeContext} instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n };\n stageTranslations: boolean; // if true, always stage the project during translate command\n requiresReview?: boolean; // top-level default: translated artifacts require approval before the client uses them\n publish?: boolean; // if true, publish the translations to the CDN; undefined means no global publish intent\n omitConfigIds?: boolean; // if true, do not write _versionId or _branchId to gt.config.json\n _versionId?: string; // internal use only\n _branchId?: string; // internal use only\n version?: string; // for specifying a custom version id to use. Should be unique\n description?: string;\n src?: string[]; // list of glob patterns for source file scanning\n fonts?: FontsConfig; // fonts to sync to the API before translating\n framework?: SupportedFrameworks;\n options?: AdditionalOptions;\n modelProvider?: ModelProvider;\n tag?: string;\n tagMessage?: string;\n parsingOptions: ParsingConfigOptions;\n branchOptions: BranchOptions;\n // Optional shared static assets config\n sharedStaticAssets?: SharedStaticAssetsConfig;\n};\n\nexport type StaticLocalizationFiles = Pick<\n Settings['files'],\n 'placeholderPaths' | 'resolvedPaths'\n> &\n Partial<Pick<Settings['files'], 'transformPaths' | 'transformFormats'>>;\n\nexport type StaticLocalizationSettings = Pick<\n Settings,\n 'defaultLocale' | 'locales' | 'options'\n> & {\n files?: StaticLocalizationFiles | null;\n};\n\nexport type BranchOptions = {\n currentBranch?: string;\n autoDetectBranches?: boolean;\n remoteName: string; // default 'origin'. The name of the remote to use for auto-detection.\n enabled: boolean; // if true, branching is enabled for the project\n};\n\nexport type AdditionalOptions = {\n // Optional schema to follow while translating JSON files\n jsonSchema?: {\n [fileGlob: string]: JsonSchema;\n };\n // Optional schema to follow while translating YAML files\n yamlSchema?: {\n [fileGlob: string]: YamlSchema;\n };\n // Skip pre-parse validation checks for specific file types\n skipFileValidation?: {\n json?: boolean;\n yaml?: boolean;\n mdx?: boolean;\n };\n // Optional Mintlify-specific options container\n mintlify?: MintlifyOptions;\n docsUrlPattern?: string | string[]; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files; a list localizes several URL prefixes\n docsImportPattern?: string; // eg /docs/[locale]/foo.md or /[locale]/foo.md for localizing static imports in markdown files\n excludeStaticUrls?: string[]; // A list of file globs to include for static url localization\n excludeStaticImports?: string[]; // A list of file globs to include for static import localization\n docsHideDefaultLocaleImport?: boolean; // if true, hide the default locale in the import path\n copyFiles?: string[]; // array of files to copy to the target locale\n experimentalClearLocaleDirs?: boolean; // if true, clear locale directories before writing translations (default: false)\n clearLocaleDirsExclude?: string[]; // array of glob patterns with [locale] or [locales] placeholder to exclude from clearing (e.g., \"./snippets/[locale]/preserved/**\" or \"./[locales]/static/**\")\n experimentalLocalizeStaticImports?: boolean; // Inserts locale in static import paths in md/mdx files\n // Inserts locale in static url paths in md/mdx files and adds anchor IDs to\n // preserve navigation. The object form enables it with extra behavior.\n experimentalLocalizeStaticUrls?:\n | boolean\n | {\n // Keep links to source pages that have no translation\n skipUntranslatedPages?: boolean;\n // Extra JSX attribute names or globs to localize\n attributes?: string[];\n };\n experimentalLocalizeRelativeAssets?: boolean; // Rewrites relative asset URLs in translated md/mdx files to valid paths\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default'; // Format for anchor IDs: 'mintlify' for Mintlify's native {#id} on every heading, 'default' or undefined for escaped inline \\{#id\\}. Can run independently of static url localization\n experimentalHideDefaultLocale?: boolean; // Hides the default locale in the import path\n experimentalFlattenJsonFiles?: boolean; // Flattens JSON files into a single file\n baseDomain?: string; // The base http:// url where the project is hosted\n docsImportRewrites?: Array<{\n match: string; // prefix to match, e.g. '@site/docs'\n replace: string; // replacement prefix, can include [locale] or [defaultLocale]\n }>;\n experimentalCanonicalLocaleKeys?: boolean; // For composite JSON schemas with locale keys, force canonical locale even when alias provided\n saveLocal?: boolean; // if true, detect and save local edits to translated output before enqueuing translations (default: false)\n};\n\nexport type SharedStaticAssetsConfig = {\n include: string | string[];\n outDir?: string;\n publicPath?: string;\n mirrorToLocales?: boolean;\n};\n\nexport type StructuralTransform = {\n sourcePointer: string; // e.g., \"/msg\"\n destinationPointer: string; // e.g., \"/translations/en\"\n};\n\nexport type JsonSchema = {\n preset?: 'mintlify' | 'mintlify-hide-default' | 'openapi';\n structuralTransform?: StructuralTransform[];\n\n // when true, resolve $ref entries in this file before processing\n resolveRefs?: boolean;\n\n // exactly 1 of include or composite must be provided; not both\n\n // specify include if file is not composite\n // multiple target JSONs will be created for each locale,\n // with the only differing content being the specified JSONPath values\n include?: string[]; // array of JSONPaths to include\n\n // specify composite if no new JSONs should be created\n composite?: {\n // The sourceObjectPath is a JSONPath to the array or object containing\n // content in the source and target locales\n // This value is denoted as the \"sourceObject\"\n // Array elements or object sub-elements are denoted as \"sourceItem\"\n [sourceObjectPath: string]: SourceObjectOptions;\n };\n};\n\nexport type YamlSchema = {\n preset?: 'mintlify' | 'openapi';\n include?: string[];\n transform?: TransformOptions;\n};\n\nexport type SourceObjectOptions = {\n type: 'array' | 'object'; // type of the sourceObject;\n // array if the sourceObject is an array\n // -> We will simply add duplicated sourceItems for each locale\n // object if the sourceObject is an object\n // -> We will duplicate the sourceItem for each locale and set the corresponding\n // key with the locale property\n // In both cases, we search the sourceObject for the key that matches the source locale\n\n // Below, relative JSONPaths are relative to the sourceItem root, NOT the sourceObject\n\n include: string[]; // array of relative JSONPaths to include in the translated JSON\n\n // if type is array, there must be a key property in the array element\n // corresponding value should be a locale code\n key?: string; // relative jsonPath to the key to use to distinguish between source and target locales\n // if type is object, the key is simply the JSON key for the sourceItem - this is unnecessary in this case\n\n localeProperty?: string; // specific locale property to use for the key for target locales, default 'code'\n // ex: code, name, nativeName, languageCode, languageName, etc. (values returned by getLocaleProperties)\n\n // optional config for transforming specific fields in the sourceItem\n // for example, helpful for handling urls with locale-specific paths\n transform?: TransformOptions;\n\n // optional list of top-level properties to remove from generated\n // non-default-locale entries (e.g. Mintlify's `default: true` flag on the\n // default language entry, which must not be cloned into other locales)\n omitProperties?: string[];\n\n // optional sorting behavior for array sourceObjects. When set to 'locale',\n // the array will be ordered to match the locales array provided to mergeJson\n // When set to 'localesAlphabetical', the default locale will be placed first\n // and the remaining locales will be ordered alphabetically by locale code\n experimentalSort?: 'locales' | 'localesAlphabetical';\n\n // when true, non-default keyed entries in this composite array are extracted\n // into separate files (using the key value as the directory name) and replaced\n // with $ref pointers. Keeps the source file compact.\n splitEntries?: boolean;\n};\n\nexport type TransformOptions = {\n // relative jsonPath to content to mutate\n [transformPath: string]: TransformOption;\n};\n"],"mappings":";AA8HA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["import type { CustomMapping } from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport type { ModelProvider } from 'generaltranslation/internal';\nimport type { FileFormat } from 'generaltranslation/types';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport {\n ParsingConfigOptions,\n GTParsingFlags,\n BaseParsingFlags,\n ParseFlagsByFileType,\n} from './parsing.js';\nimport { Libraries, InlineLibrary } from './libraries.js';\n\nexport type { Updates } from 'generaltranslation/types';\n\nexport type Options = {\n config: string;\n apiKey?: string;\n projectId?: string;\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n src?: string[];\n defaultLocale?: string;\n locales?: string[];\n baseUrl: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n dryRun: boolean;\n timeout: number;\n force?: boolean;\n stageTranslations?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type OpenApiConfig = {\n files: string[];\n translateFields?: string[];\n};\n\nexport type MintlifyOptions = {\n openapi?: OpenApiConfig;\n inferTitleFromFilename?: boolean;\n localizeRedirects?: boolean; // add localized redirects for pages renamed or removed in a translate run\n};\n\nexport type SharedFlags = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n};\n\nexport type TranslateFlags = SharedFlags & {\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n defaultLocale?: string;\n locales?: string[];\n ignoreErrors?: boolean;\n src?: string[];\n timeout: number;\n dryRun: boolean;\n saveLocal?: boolean;\n stageTranslations?: boolean;\n setupProject?: boolean; // if true, skip enqueue step\n publish?: boolean;\n force?: boolean;\n forceDownload?: boolean;\n tag?: string;\n message?: string;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n omitConfigIds?: boolean;\n excludeStaticUrls?: string[];\n excludeStaticImports?: string[];\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type WrapOptions = {\n src?: string[];\n config: string;\n skipTs: boolean;\n disableIds: boolean;\n disableFormatting: boolean;\n addGTProvider: boolean;\n};\n\nexport type SetupOptions = {\n src?: string[];\n config: string;\n};\n\nexport type GenerateSourceOptions = {\n src?: string[];\n config: string;\n defaultLocale: string;\n dictionary?: string;\n jsconfig?: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n};\n\nexport type Framework =\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_REACT\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START;\n\nexport const SUPPORTED_REACT_FRAMEWORKS = [\n 'next-app',\n 'next-pages',\n 'vite',\n 'gatsby',\n 'react',\n 'redwood',\n 'tanstack-start',\n 'react-router',\n] as const;\n\nexport type FrameworkObject =\n | {\n name: 'mintlify';\n type?: undefined;\n }\n | {\n name: (typeof SUPPORTED_REACT_FRAMEWORKS)[number];\n type: 'react';\n };\nexport type ReactFrameworkObject = Extract<FrameworkObject, { type: 'react' }>;\n/** Detected so setup can stop; the wizard cannot set React Native up yet. */\nexport type ReactNativeFrameworkObject = {\n name: 'react-native';\n type: 'react-native';\n};\n\nexport type FrameworkType = FrameworkObject['type'];\n\nexport type SupportedFrameworks = FrameworkObject['name'];\nexport type SupportedReactFrameworks = Extract<\n FrameworkObject,\n { type: 'react' }\n>['name'];\n\nexport type SupportedLibraries =\n | InlineLibrary\n | 'next-intl'\n | 'react-i18next'\n | 'next-i18next'\n | 'i18next'\n | 'i18next-icu'\n | 'base';\n\nexport interface ContentScanner {\n scanForContent(\n options: WrapOptions,\n framework: Framework\n ): Promise<{\n errors: string[];\n filesUpdated: string[];\n warnings: string[];\n }>;\n}\n\n// Create a type based on the supported file extensions\nexport type SupportedFileExtension = (typeof SUPPORTED_FILE_EXTENSIONS)[number];\n\n// Update ResolvedFiles to use the dynamic keys\nexport type ResolvedFiles = {\n [K in SupportedFileExtension]?: string[];\n} & {\n gt?: string; // Output glob: /path/[locale].json\n};\n\nexport type TransformOption = {\n match?: string; // regex to match strings, supports capture groups\n replace: string; // string or regex pattern to replace the match with\n // Special placeholders:\n // -> if used in the match string, they will be replaced with the corresponding default locale property value\n // -> if used in the replace string, they will be replaced with the corresponding target locale property value\n // {locale} -> will be replaced with the locale code\n // And any other property from getLocaleProperties()\n};\n\nexport type TransformFiles = {\n [K in SupportedFileExtension]?: TransformOption | string | TransformOption[]; // if a string, only transform the file name\n};\n\nexport type TransformFormats = {\n [K in SupportedFileExtension]?: FileFormat;\n};\n\n// Include patterns can be plain strings or objects with a publish flag\nexport type IncludePattern = string | { pattern: string; publish?: boolean };\n\n// Review requirement for matched files: a boolean applies to all files of the\n// type; the object form opts path groups in/out with globs. exclude wins over\n// include; files matching neither inherit the top-level requiresReview default.\nexport type RequiresReviewConfig =\n | boolean\n | {\n include?: string[];\n exclude?: string[];\n };\n\n// Update FilesOptions to fix the error\nexport type FilesOptions = {\n [K in SupportedFileExtension]?: {\n include: IncludePattern[];\n exclude?: string[];\n transform?: string | TransformOption | TransformOption[];\n transformationFormat?: FileFormat;\n parsingFlags?: BaseParsingFlags; // Flags for parsing inline content\n requiresReview?: RequiresReviewConfig; // Whether translated versions of matched files require approval before use\n };\n} & {\n gt?: {\n output: string; // Output glob: /path/[locale].json\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags?: Partial<GTParsingFlags>; // Flags for parsing inline content\n /**\n * @deprecated\n * use `files.gt.parsingFlags.includeSourceCodeContext` instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n};\n\n// Shared settings between all API-related commands\nexport type FontsConfig = {\n include: string[]; // globs of .ttf/.otf files\n exclude?: string[];\n};\n\nexport type Settings = {\n config: string;\n configDirectory: string;\n baseUrl: string;\n dashboardUrl: string;\n apiKey?: string;\n userTokenProvider?: UserTokenProvider;\n projectId?: string;\n defaultLocale: string;\n locales: string[];\n customMapping?: CustomMapping;\n files: {\n resolvedPaths: ResolvedFiles; // Absolute resolved paths for the default locale\n placeholderPaths: ResolvedFiles; // Absolute placeholder paths for all locales containing [locale]\n transformPaths: TransformFiles; // Absolute transform paths for all locales containing [locale]\n transformFormats: TransformFormats; // Output file format transforms keyed by config file type\n publishPaths: Set<string>; // Absolute paths explicitly opted IN to publishing\n unpublishPaths: Set<string>; // Absolute paths explicitly opted OUT of publishing\n requiresReviewPaths: Set<string>; // Absolute paths whose effective requiresReview policy is true\n parsingFlags: ParseFlagsByFileType;\n gtJson: {\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags: GTParsingFlags; // Flags for parsing inline content\n /**\n * @deprecated\n * use {@link files.gt.GTParsingFlags.parsingFlags.includeSourceCodeContext} instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n };\n stageTranslations: boolean; // if true, always stage the project during translate command\n requiresReview?: boolean; // top-level default: translated artifacts require approval before the client uses them\n publish?: boolean; // if true, publish the translations to the CDN; undefined means no global publish intent\n omitConfigIds?: boolean; // if true, do not write _versionId or _branchId to gt.config.json\n _versionId?: string; // internal use only\n _branchId?: string; // internal use only\n version?: string; // for specifying a custom version id to use. Should be unique\n description?: string;\n src?: string[]; // list of glob patterns for source file scanning\n fonts?: FontsConfig; // fonts to sync to the API before translating\n framework?: SupportedFrameworks;\n options?: AdditionalOptions;\n modelProvider?: ModelProvider;\n tag?: string;\n tagMessage?: string;\n parsingOptions: ParsingConfigOptions;\n branchOptions: BranchOptions;\n // Optional shared static assets config\n sharedStaticAssets?: SharedStaticAssetsConfig;\n};\n\nexport type StaticLocalizationFiles = Pick<\n Settings['files'],\n 'placeholderPaths' | 'resolvedPaths'\n> &\n Partial<Pick<Settings['files'], 'transformPaths' | 'transformFormats'>>;\n\nexport type StaticLocalizationSettings = Pick<\n Settings,\n 'defaultLocale' | 'locales' | 'options'\n> & {\n files?: StaticLocalizationFiles | null;\n};\n\nexport type BranchOptions = {\n currentBranch?: string;\n autoDetectBranches?: boolean;\n remoteName: string; // default 'origin'. The name of the remote to use for auto-detection.\n enabled: boolean; // if true, branching is enabled for the project\n};\n\nexport type AdditionalOptions = {\n // Optional schema to follow while translating JSON files\n jsonSchema?: {\n [fileGlob: string]: JsonSchema;\n };\n // Optional schema to follow while translating YAML files\n yamlSchema?: {\n [fileGlob: string]: YamlSchema;\n };\n // Skip pre-parse validation checks for specific file types\n skipFileValidation?: {\n json?: boolean;\n yaml?: boolean;\n mdx?: boolean;\n };\n // Optional Mintlify-specific options container\n mintlify?: MintlifyOptions;\n docsUrlPattern?: string | string[]; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files; a list localizes several URL prefixes\n docsImportPattern?: string; // eg /docs/[locale]/foo.md or /[locale]/foo.md for localizing static imports in markdown files\n excludeStaticUrls?: string[]; // A list of file globs to include for static url localization\n excludeStaticImports?: string[]; // A list of file globs to include for static import localization\n docsHideDefaultLocaleImport?: boolean; // if true, hide the default locale in the import path\n copyFiles?: string[]; // array of files to copy to the target locale\n experimentalClearLocaleDirs?: boolean; // if true, clear locale directories before writing translations (default: false)\n clearLocaleDirsExclude?: string[]; // array of glob patterns with [locale] or [locales] placeholder to exclude from clearing (e.g., \"./snippets/[locale]/preserved/**\" or \"./[locales]/static/**\")\n experimentalLocalizeStaticImports?: boolean; // Inserts locale in static import paths in md/mdx files\n // Inserts locale in static url paths in md/mdx files and adds anchor IDs to\n // preserve navigation. The object form enables it with extra behavior.\n experimentalLocalizeStaticUrls?:\n | boolean\n | {\n // Keep links to source pages that have no translation\n skipUntranslatedPages?: boolean;\n // Extra JSX attribute names or globs to localize\n attributes?: string[];\n };\n experimentalLocalizeRelativeAssets?: boolean; // Rewrites relative asset URLs in translated md/mdx files to valid paths\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default'; // Format for anchor IDs: 'mintlify' for Mintlify's native {#id} on every heading, 'default' or undefined for escaped inline \\{#id\\}. Can run independently of static url localization\n experimentalHideDefaultLocale?: boolean; // Hides the default locale in the import path\n experimentalFlattenJsonFiles?: boolean; // Flattens JSON files into a single file\n baseDomain?: string; // The base http:// url where the project is hosted\n docsImportRewrites?: Array<{\n match: string; // prefix to match, e.g. '@site/docs'\n replace: string; // replacement prefix, can include [locale] or [defaultLocale]\n }>;\n experimentalCanonicalLocaleKeys?: boolean; // For composite JSON schemas with locale keys, force canonical locale even when alias provided\n saveLocal?: boolean; // if true, detect and save local edits to translated output before enqueuing translations (default: false)\n};\n\nexport type SharedStaticAssetsConfig = {\n include: string | string[];\n outDir?: string;\n publicPath?: string;\n mirrorToLocales?: boolean;\n};\n\nexport type StructuralTransform = {\n sourcePointer: string; // e.g., \"/msg\"\n destinationPointer: string; // e.g., \"/translations/en\"\n};\n\nexport type JsonSchema = {\n preset?: 'mintlify' | 'mintlify-hide-default' | 'openapi';\n structuralTransform?: StructuralTransform[];\n\n // when true, resolve $ref entries in this file before processing\n resolveRefs?: boolean;\n\n // exactly 1 of include or composite must be provided; not both\n\n // specify include if file is not composite\n // multiple target JSONs will be created for each locale,\n // with the only differing content being the specified JSONPath values\n include?: string[]; // array of JSONPaths to include\n\n // specify composite if no new JSONs should be created\n composite?: {\n // The sourceObjectPath is a JSONPath to the array or object containing\n // content in the source and target locales\n // This value is denoted as the \"sourceObject\"\n // Array elements or object sub-elements are denoted as \"sourceItem\"\n [sourceObjectPath: string]: SourceObjectOptions;\n };\n};\n\nexport type YamlSchema = {\n preset?: 'mintlify' | 'openapi';\n include?: string[];\n transform?: TransformOptions;\n};\n\nexport type SourceObjectOptions = {\n type: 'array' | 'object'; // type of the sourceObject;\n // array if the sourceObject is an array\n // -> We will simply add duplicated sourceItems for each locale\n // object if the sourceObject is an object\n // -> We will duplicate the sourceItem for each locale and set the corresponding\n // key with the locale property\n // In both cases, we search the sourceObject for the key that matches the source locale\n\n // Below, relative JSONPaths are relative to the sourceItem root, NOT the sourceObject\n\n include: string[]; // array of relative JSONPaths to include in the translated JSON\n\n // if type is array, there must be a key property in the array element\n // corresponding value should be a locale code\n key?: string; // relative jsonPath to the key to use to distinguish between source and target locales\n // if type is object, the key is simply the JSON key for the sourceItem - this is unnecessary in this case\n\n localeProperty?: string; // specific locale property to use for the key for target locales, default 'code'\n // ex: code, name, nativeName, languageCode, languageName, etc. (values returned by getLocaleProperties)\n\n // optional config for transforming specific fields in the sourceItem\n // for example, helpful for handling urls with locale-specific paths\n transform?: TransformOptions;\n\n // optional list of top-level properties to remove from generated\n // non-default-locale entries (e.g. Mintlify's `default: true` flag on the\n // default language entry, which must not be cloned into other locales)\n omitProperties?: string[];\n\n // optional sorting behavior for array sourceObjects. When set to 'locale',\n // the array will be ordered to match the locales array provided to mergeJson\n // When set to 'localesAlphabetical', the default locale will be placed first\n // and the remaining locales will be ordered alphabetically by locale code\n experimentalSort?: 'locales' | 'localesAlphabetical';\n\n // when true, non-default keyed entries in this composite array are extracted\n // into separate files (using the key value as the directory name) and replaced\n // with $ref pointers. Keeps the source file compact.\n splitEntries?: boolean;\n};\n\nexport type TransformOptions = {\n // relative jsonPath to content to mutate\n [transformPath: string]: TransformOption;\n};\n"],"mappings":";AA8HA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
@@ -123,6 +123,19 @@ export declare const api: {
123
123
  error?: string;
124
124
  }>;
125
125
  }>;
126
+ updateFiles(files: import("@generaltranslation/api").UpdateFilesData["body"]["files"], options?: {
127
+ timeout?: number;
128
+ }): Promise<{
129
+ files: {
130
+ branchId: string;
131
+ fileId: string;
132
+ versionId: string;
133
+ locale?: string;
134
+ metadata: {
135
+ previewUrl?: string | null;
136
+ };
137
+ }[];
138
+ }>;
126
139
  submitUserEditDiffs(body: import("@generaltranslation/api").SubmitUserEditDiffsData["body"], options?: {
127
140
  timeout?: number;
128
141
  }): Promise<{
@@ -1,5 +1,8 @@
1
1
  export declare const GT_DASHBOARD_URL = "https://dash.generaltranslation.com";
2
- export declare const REACT_QUICKSTART_URL = "https://generaltranslation.com/docs/react/tutorials/quickstart";
2
+ export declare const REACT_QUICKSTART_URL = "https://generaltranslation.com/docs/react/react-quickstart";
3
+ export declare const NEXT_APP_QUICKSTART_URL = "https://generaltranslation.com/docs/react/nextjs-quickstart";
4
+ export declare const NEXT_PAGES_QUICKSTART_URL = "https://generaltranslation.com/docs/react/nextjs-pages-router-quickstart";
5
+ export declare const REACT_SPA_QUICKSTART_URL = "https://generaltranslation.com/docs/react/react-spa-quickstart";
3
6
  export declare const GT_CONFIG_SCHEMA_URL = "https://assets.gtx.dev/config-schema.json";
4
7
  export declare const TEMPLATE_FILE_NAME = "__INTERNAL_GT_TEMPLATE_NAME__";
5
8
  export declare const TEMPLATE_FILE_ID: string;