gt 2.24.0 → 2.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/api/saveLocalEdits.js +23 -6
- package/dist/api/saveLocalEdits.js.map +1 -1
- package/dist/cli/base.js +1 -1
- package/dist/cli/base.js.map +1 -1
- package/dist/cli/commands/api.d.ts +1 -0
- package/dist/cli/commands/api.js +78 -2
- package/dist/cli/commands/api.js.map +1 -1
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/generated/version.js.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js.map +1 -1
- package/dist/utils/localizeStaticUrls.js +17 -15
- package/dist/utils/localizeStaticUrls.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# gtx-cli
|
|
2
2
|
|
|
3
|
+
## 2.25.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#2378](https://github.com/generaltranslation/gt/pull/2378) [`df1e47a`](https://github.com/generaltranslation/gt/commit/df1e47a3c8767546f61608c25d6183af96a7da82) Thanks [@chenxin-yan](https://github.com/chenxin-yan)! - Add `gt api --list` to print every API operation as `METHOD path operationId summary`, and accept an endpoint with `gt api --spec <endpoint>` to print only the matching operations with schema references resolved, plus the `components` (recursive schemas and security schemes) they still refer to. The endpoint can be an operation ID, a spec path, or a concrete request path such as `/v2/project/info/abc`.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#2382](https://github.com/generaltranslation/gt/pull/2382) [`64db558`](https://github.com/generaltranslation/gt/commit/64db558404e9124f9f6101262a69346e66e54dca) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Add configurable attribute localization to `localizeStaticUrls`
|
|
12
|
+
|
|
13
|
+
- [#2380](https://github.com/generaltranslation/gt/pull/2380) [`c725b79`](https://github.com/generaltranslation/gt/commit/c725b797bf00e75241306f15b2690a8b467e80b5) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Include GT JSONs in `save-local`
|
|
14
|
+
|
|
3
15
|
## 2.24.0
|
|
4
16
|
|
|
5
17
|
### Minor Changes
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { logger } from "../console/logger.js";
|
|
2
|
+
import { TEMPLATE_FILE_ID, TEMPLATE_FILE_NAME } from "../utils/constants.js";
|
|
2
3
|
import { logErrorAndExit } from "../console/logging.js";
|
|
3
4
|
import { branchResolutionError } from "../console/index.js";
|
|
4
5
|
import { api } from "../utils/api.js";
|
|
5
6
|
import { BranchStep } from "../workflows/steps/BranchStep.js";
|
|
7
|
+
import { readLockfile } from "../fs/config/downloadedVersions.js";
|
|
8
|
+
import { shouldPublishGt } from "../utils/resolvePublish.js";
|
|
6
9
|
import { runPublishWorkflow } from "../workflows/publish.js";
|
|
7
10
|
import { aggregateFiles } from "../formats/files/aggregateFiles.js";
|
|
8
11
|
import { collectAndSendUserEditDiffs } from "./collectUserEditDiffs.js";
|
|
@@ -15,21 +18,35 @@ import chalk from "chalk";
|
|
|
15
18
|
async function saveLocalEdits(settings) {
|
|
16
19
|
if (!settings.files) return;
|
|
17
20
|
const { files, publishMap } = await aggregateFiles(settings);
|
|
18
|
-
|
|
19
|
-
const branchResult = await new BranchStep(api, settings).run();
|
|
20
|
-
if (!branchResult) return logErrorAndExit(branchResolutionError);
|
|
21
|
-
const uploads = files.map((file) => ({
|
|
21
|
+
const fileRefs = files.map((file) => ({
|
|
22
22
|
fileName: file.fileName,
|
|
23
23
|
fileFormat: file.fileFormat,
|
|
24
|
-
branchId: branchResult.currentBranch.id,
|
|
25
24
|
fileId: file.fileId,
|
|
26
25
|
versionId: file.versionId
|
|
27
26
|
}));
|
|
27
|
+
const gtJsonEntry = settings.files.placeholderPaths.gt ? readLockfile(settings).entryMap.get(TEMPLATE_FILE_ID) : void 0;
|
|
28
|
+
if (gtJsonEntry) {
|
|
29
|
+
fileRefs.push({
|
|
30
|
+
fileName: TEMPLATE_FILE_NAME,
|
|
31
|
+
fileFormat: "GTJSON",
|
|
32
|
+
fileId: TEMPLATE_FILE_ID,
|
|
33
|
+
versionId: gtJsonEntry.versionId
|
|
34
|
+
});
|
|
35
|
+
const gtPublishValue = shouldPublishGt(settings);
|
|
36
|
+
if (gtPublishValue !== void 0) publishMap.set(TEMPLATE_FILE_ID, gtPublishValue);
|
|
37
|
+
}
|
|
38
|
+
if (!fileRefs.length) return;
|
|
39
|
+
const branchResult = await new BranchStep(api, settings).run();
|
|
40
|
+
if (!branchResult) return logErrorAndExit(branchResolutionError);
|
|
41
|
+
const uploads = fileRefs.map((file) => ({
|
|
42
|
+
...file,
|
|
43
|
+
branchId: branchResult.currentBranch.id
|
|
44
|
+
}));
|
|
28
45
|
const spinner = logger.createSpinner("dots");
|
|
29
46
|
spinner.start("Saving local edits...");
|
|
30
47
|
const hadDiffs = await collectAndSendUserEditDiffs(uploads, settings);
|
|
31
48
|
spinner.stop(chalk.green("Local edits saved successfully"));
|
|
32
|
-
if (hadDiffs) await runPublishWorkflow(
|
|
49
|
+
if (hadDiffs) await runPublishWorkflow(fileRefs, publishMap, branchResult.currentBranch.id, settings);
|
|
33
50
|
}
|
|
34
51
|
//#endregion
|
|
35
52
|
export { saveLocalEdits };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"saveLocalEdits.js","names":[],"sources":["../../src/api/saveLocalEdits.ts"],"sourcesContent":["import { Settings } from '../types/index.js';\nimport { aggregateFiles } from '../formats/files/aggregateFiles.js';\nimport { collectAndSendUserEditDiffs } from './collectUserEditDiffs.js';\nimport { api } from '../utils/api.js';\nimport { BranchStep } from '../workflows/steps/BranchStep.js';\nimport { logErrorAndExit } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { branchResolutionError } from '../console/index.js';\nimport type { FileReference } from 'generaltranslation/types';\nimport chalk from 'chalk';\nimport { runPublishWorkflow } from '../workflows/publish.js';\n\n/**\n * Uploads current source files to obtain file references, then collects and sends\n * diffs for all locales based on last downloaded versions. Does not enqueue translations.\n */\nexport async function saveLocalEdits(settings: Settings): Promise<void> {\n if (!settings.files) return;\n\n // Collect current files from config\n const { files, publishMap } = await aggregateFiles(settings);\n if (!
|
|
1
|
+
{"version":3,"file":"saveLocalEdits.js","names":[],"sources":["../../src/api/saveLocalEdits.ts"],"sourcesContent":["import { Settings } from '../types/index.js';\nimport { aggregateFiles } from '../formats/files/aggregateFiles.js';\nimport { collectAndSendUserEditDiffs } from './collectUserEditDiffs.js';\nimport { api } from '../utils/api.js';\nimport { BranchStep } from '../workflows/steps/BranchStep.js';\nimport { logErrorAndExit } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { branchResolutionError } from '../console/index.js';\nimport type { FileReference } from 'generaltranslation/types';\nimport chalk from 'chalk';\nimport { runPublishWorkflow } from '../workflows/publish.js';\nimport { readLockfile } from '../fs/config/downloadedVersions.js';\nimport { TEMPLATE_FILE_ID, TEMPLATE_FILE_NAME } from '../utils/constants.js';\nimport { shouldPublishGt } from '../utils/resolvePublish.js';\n\n/**\n * Uploads current source files to obtain file references, then collects and sends\n * diffs for all locales based on last downloaded versions. Does not enqueue translations.\n */\nexport async function saveLocalEdits(settings: Settings): Promise<void> {\n if (!settings.files) return;\n\n // Collect current files from config\n const { files, publishMap } = await aggregateFiles(settings);\n const fileRefs = files.map((file) => ({\n fileName: file.fileName,\n fileFormat: file.fileFormat,\n fileId: file.fileId,\n versionId: file.versionId,\n }));\n\n // Include the GT JSON at its last downloaded version\n const gtJsonEntry = settings.files.placeholderPaths.gt\n ? readLockfile(settings).entryMap.get(TEMPLATE_FILE_ID)\n : undefined;\n if (gtJsonEntry) {\n fileRefs.push({\n fileName: TEMPLATE_FILE_NAME,\n fileFormat: 'GTJSON',\n fileId: TEMPLATE_FILE_ID,\n versionId: gtJsonEntry.versionId,\n });\n const gtPublishValue = shouldPublishGt(settings);\n if (gtPublishValue !== undefined) {\n publishMap.set(TEMPLATE_FILE_ID, gtPublishValue);\n }\n }\n if (!fileRefs.length) return;\n\n // run branch query to get branch id\n // Run the branch step\n const branchStep = new BranchStep(api, settings);\n const branchResult = await branchStep.run();\n if (!branchResult) {\n return logErrorAndExit(branchResolutionError);\n }\n\n const uploads = fileRefs.map((file) => ({\n ...file,\n branchId: branchResult.currentBranch.id,\n })) satisfies FileReference[];\n\n const spinner = logger.createSpinner('dots');\n spinner.start('Saving local edits...');\n\n const hadDiffs = await collectAndSendUserEditDiffs(uploads, settings);\n spinner.stop(chalk.green('Local edits saved successfully'));\n\n // Publish files to CDN if diffs were detected and publish config exists\n if (hadDiffs) {\n await runPublishWorkflow(\n fileRefs,\n publishMap,\n branchResult.currentBranch.id,\n settings\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmBA,eAAsB,eAAe,UAAmC;AACtE,KAAI,CAAC,SAAS,MAAO;CAGrB,MAAM,EAAE,OAAO,eAAe,MAAM,eAAe,SAAS;CAC5D,MAAM,WAAW,MAAM,KAAK,UAAU;EACpC,UAAU,KAAK;EACf,YAAY,KAAK;EACjB,QAAQ,KAAK;EACb,WAAW,KAAK;EACjB,EAAE;CAGH,MAAM,cAAc,SAAS,MAAM,iBAAiB,KAChD,aAAa,SAAS,CAAC,SAAS,IAAI,iBAAiB,GACrD,KAAA;AACJ,KAAI,aAAa;AACf,WAAS,KAAK;GACZ,UAAU;GACV,YAAY;GACZ,QAAQ;GACR,WAAW,YAAY;GACxB,CAAC;EACF,MAAM,iBAAiB,gBAAgB,SAAS;AAChD,MAAI,mBAAmB,KAAA,EACrB,YAAW,IAAI,kBAAkB,eAAe;;AAGpD,KAAI,CAAC,SAAS,OAAQ;CAKtB,MAAM,eAAe,MAAM,IADJ,WAAW,KAAK,SACF,CAAC,KAAK;AAC3C,KAAI,CAAC,aACH,QAAO,gBAAgB,sBAAsB;CAG/C,MAAM,UAAU,SAAS,KAAK,UAAU;EACtC,GAAG;EACH,UAAU,aAAa,cAAc;EACtC,EAAE;CAEH,MAAM,UAAU,OAAO,cAAc,OAAO;AAC5C,SAAQ,MAAM,wBAAwB;CAEtC,MAAM,WAAW,MAAM,4BAA4B,SAAS,SAAS;AACrE,SAAQ,KAAK,MAAM,MAAM,iCAAiC,CAAC;AAG3D,KAAI,SACF,OAAM,mBACJ,UACA,YACA,aAAa,cAAc,IAC3B,SACD"}
|
package/dist/cli/base.js
CHANGED
|
@@ -187,7 +187,7 @@ var BaseCLI = class {
|
|
|
187
187
|
});
|
|
188
188
|
}
|
|
189
189
|
setupApiCommand() {
|
|
190
|
-
attachSharedFlags(this.program.command("api [endpoint]").description("Make an authenticated request to the GT API").option("-X, --method <method>", "HTTP method", "GET").option("--input <file>", "Request body file, or - for standard input").option("-H, --header <header>", "Request header in \"Key: Value\" format", (header, headers) => [...headers ?? [], header]).option("-i, --include", "Include response status and headers").option("--spec", "Print the bundled OpenAPI specification")).action((endpoint, options) => handleApiCommand(endpoint, options));
|
|
190
|
+
attachSharedFlags(this.program.command("api [endpoint]").description("Make an authenticated request to the GT API").option("-X, --method <method>", "HTTP method", "GET").option("--input <file>", "Request body file, or - for standard input").option("-H, --header <header>", "Request header in \"Key: Value\" format", (header, headers) => [...headers ?? [], header]).option("-i, --include", "Include response status and headers").option("--spec", "Print the bundled OpenAPI specification, or only the operations matching [endpoint] (path or operation ID) with references resolved").addOption(new Option("--list", "List the method, path, operation ID, and summary of every API operation").conflicts("spec"))).action((endpoint, options) => handleApiCommand(endpoint, options));
|
|
191
191
|
}
|
|
192
192
|
setupProjectCommands() {
|
|
193
193
|
const projectCommand = this.program.command("project").description("Manage General Translation projects");
|
package/dist/cli/base.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":[],"sources":["../../src/cli/base.ts"],"sourcesContent":["import { Argument, Command, InvalidArgumentError, Option } from 'commander';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n DEFAULT_TRANSLATIONS_DIR,\n REACT_QUICKSTART_URL,\n} from '../utils/constants.js';\nimport {\n applySetupConfig,\n mergeSetupConfig,\n type SetupConfigUpdate,\n} from '../fs/config/setupConfig.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport {\n displayHeader,\n promptText,\n logErrorAndExit,\n exitSync,\n promptConfirm,\n promptMultiSelect,\n promptSelect,\n promptGlobPatterns,\n} from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { lottieTranslateError } from '../console/index.js';\nimport { parseGlobPatterns } from '../console/promptParsing.js';\nimport path from 'node:path';\nimport {\n FilesOptions,\n Settings,\n SupportedFrameworks,\n SupportedLibraries,\n TranslateFlags,\n SharedFlags,\n} from '../types/index.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport chalk from 'chalk';\nimport {\n FILE_EXT_TO_EXT_LABEL,\n SETUP_FILE_FORMATS,\n SUPPORTED_FILE_EXTENSIONS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n executeReactSetup,\n resolveReactSetup,\n type ReactSetupPlan,\n} from '../setup/wizard.js';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { getDesiredLocales } from '../setup/userInput.js';\nimport {\n areCredentialsSet,\n getDevelopmentEnvNames,\n inspectCredentialsEnvFile,\n} from '../utils/credentials.js';\nimport {\n checkDevelopmentProjectInputs,\n productionRuntimeKeyGuidance,\n provisionDevelopmentCredentials,\n resolveDevelopmentProject,\n signInForSetup,\n} from '../setup/developmentCredentials.js';\nimport { exitIfUnsupportedSetupTarget } from '../setup/setupTarget.js';\nimport {\n asRecord,\n attachConfigureFlags,\n attachInitFlags,\n describeDefaults,\n displaySetupHeader,\n getConfiguredFramework,\n INIT_SOURCE_HELP,\n installWithProgress,\n OnboardingError,\n parseFilePatterns,\n readSetupConfig,\n reportJsonExitsBeforeOnboarding,\n resolvePackageManager,\n runOnboarding,\n setupConfigPath,\n validateSetupPattern,\n type ConfigureOptions,\n type InitOptions,\n type OnboardingSession,\n} from '../setup/onboarding.js';\nimport { upload } from './commands/upload.js';\nimport { attachSharedFlags, attachTranslateFlags } from './flags.js';\nimport { handleStage } from './commands/stage.js';\nimport { handleSetupProject } from './commands/setupProject.js';\nimport { handleDownload } from './commands/download.js';\nimport {\n handleTranslate,\n postProcessTranslations,\n} from './commands/translate.js';\nimport {\n getNeedsPostprocessing,\n clearDownloaded,\n} from '../state/recentDownloads.js';\nimport { clearWarnings } from '../state/translateWarnings.js';\nimport { displayTranslateSummary } from '../console/displayTranslateSummary.js';\nimport updateConfig from '../fs/config/updateConfig.js';\nimport {\n createLoadTranslationsFile,\n findLoadTranslationsFiles,\n} from '../fs/createLoadTranslationsFile.js';\nimport { saveLocalEdits } from '../api/saveLocalEdits.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './commands/utils/validation.js';\nimport processSharedStaticAssets, {\n mirrorAssetsToLocales,\n} from '../utils/sharedStaticAssets.js';\nimport { setupLocadex } from '../locadex/setupFlow.js';\nimport { detectFramework } from '../setup/detectFramework.js';\nimport { INLINE_LIBRARIES, Libraries } from '../types/libraries.js';\nimport { handleEnqueue } from './commands/enqueue.js';\nimport { splitMintlifyLanguageRefs } from '../utils/splitMintlifyLanguageRefs.js';\nimport { localizeMintlifyRedirects } from '../formats/files/postprocess/localizeMintlifyRedirects.js';\nimport {\n clearOrphanedFileNames,\n getOrphanedFileNames,\n} from '../state/orphanedFileNames.js';\nimport { runMergeDriver, type MergeDriverName } from '../git/mergeDrivers.js';\nimport { setupGitMergeDrivers } from '../git/setupMergeDrivers.js';\nimport { warnReactPackageCompatibility } from '../utils/reactPackageCompatibility.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { hasLogin, logout, whoAmI } from '../auth/oauth.js';\nimport { createUserAuthError, UserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { resolveConfig } from '../config/resolveConfig.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport {\n getBuildToolSetup,\n type ManualAction,\n type SetupResult,\n} from '../setup/buildTools/index.js';\nimport { manifestDirectlyDeclaresGTVue } from '@generaltranslation/vue-extractor/integration';\nimport { api } from '../utils/api.js';\nimport { handleApiCommand, type ApiCommandOptions } from './commands/api.js';\n\nconst ID_COMPATIBILITY_WARNING_COMMANDS = new Set([\n 'download',\n 'enqueue',\n 'generate',\n 'setup',\n 'stage',\n 'translate',\n 'validate',\n]);\nfunction createProjectCommandError(\n whatHappened: string,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened,\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst emptyApiKeyNameError = createDiagnosticMessage({\n whatHappened: 'The key name cannot be empty',\n fix: 'Pass a non-empty value with --name',\n});\n\nfunction parseApiKeyName(value: string): string {\n const name = value.trim();\n if (!name) throw new InvalidArgumentError(emptyApiKeyNameError);\n return name;\n}\n\n/** Credential failures keep their own diagnostic or get the setup context. */\nasync function withCredentialsError<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof OnboardingError) throw error;\n throw new Error(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError(\n 'Failed to set up the development credentials',\n error\n )\n );\n }\n}\n\nexport type UploadOptions = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n defaultLocale?: string;\n};\n\nexport type GitSetupOptions = {\n config?: string;\n dryRun?: boolean;\n omitConfigIds?: boolean;\n driverCommand?: string;\n};\n\ntype LocalTranslationGuidanceOptions = {\n generatedLoader: boolean;\n runtimeSetup: InlineRuntimeSetup;\n translationsDir: string;\n};\n\ntype InlineRuntimeSetup = {\n hasOtherInlineRuntime: boolean;\n hasVueRuntime: boolean;\n ranReactSetup: boolean;\n};\n\nexport class BaseCLI {\n protected library: SupportedLibraries;\n protected additionalModules: SupportedLibraries[];\n protected program: Command;\n // Constructor is shared amongst all CLI class types\n public constructor(\n program: Command,\n library: SupportedLibraries,\n additionalModules?: SupportedLibraries[]\n ) {\n this.program = program;\n this.library = library;\n this.additionalModules = additionalModules || [];\n\n this.program.option(\n '--skip-version-check',\n 'Skip the monorepo GT package version consistency check'\n );\n this.program.option(\n '--suppress-id-compatibility-warning',\n 'Suppress the React package ID compatibility warning'\n );\n this.program.option(\n '-q, --quiet',\n 'Suppress informational output; only warnings and errors are shown'\n );\n // Select console routing for this command before anything else logs:\n // root hooks run before subclass hooks (version checks) and the action's\n // settings resolution. `gt api-key create` prints the new secret on\n // stdout, so its diagnostics go to stderr, as do setup commands writing\n // JSON events; every other command gets the historical default back\n // (main() routes startup output to stderr).\n this.program.hook('preAction', (thisCommand, actionCommand) => {\n logger.setConsoleOutput(\n actionCommand.parent?.name() === 'api-key' || actionCommand.opts().json\n ? 'stderr'\n : 'stdout'\n );\n if (\n actionCommand.opts().json &&\n actionCommand.parent === thisCommand &&\n ['init', 'configure'].includes(actionCommand.name())\n ) {\n reportJsonExitsBeforeOnboarding(actionCommand.name());\n }\n });\n // Apply --quiet before any other hook or command action runs so the\n // singleton logger is muted for the rest of the invocation. The flag is a\n // global root option, so commander resolves it in any position and for\n // nested commands (e.g. `gt git setup --quiet`).\n this.program.hook('preAction', () => {\n logger.setQuiet(Boolean(this.program.opts().quiet));\n });\n this.program.hook('preAction', async (thisCommand, actionCommand) => {\n // Nested commands (e.g. `gt git setup`) can share leaf names with\n // translation commands; only direct children of the root qualify\n if (actionCommand.parent !== thisCommand) return;\n if (!ID_COMPATIBILITY_WARNING_COMMANDS.has(actionCommand.name())) return;\n await warnReactPackageCompatibility(\n Boolean(this.program.opts().suppressIdCompatibilityWarning)\n );\n });\n\n this.setupInitCommand();\n this.setupConfigureCommand();\n this.setupUploadCommand();\n this.setupUserAuthCommands();\n this.setupSendDiffsCommand();\n this.setupApiCommand();\n this.setupProjectCommands();\n this.setupApiKeyCommands();\n this.setupGitCommand();\n }\n // Init is never called in a child class\n public init() {\n this.setupSetupProjectCommand();\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n // Execute is called by the main program\n public execute() {\n // If no command is specified, run 'init'\n if (process.argv.length <= 2) {\n process.argv.push('init');\n }\n }\n\n protected setupSetupProjectCommand(): void {\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupStageCommand(): void {\n attachTranslateFlags(\n this.program\n .command('stage')\n .description(\n 'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupEnqueueCommand(): void {\n attachTranslateFlags(\n this.program\n .command('enqueue')\n .description('Enqueues translations for a given set of files')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Enqueuing translations...');\n await this.handleEnqueue(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupDownloadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('download')\n .description('Download translations that were originally staged')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Downloading translations...');\n await this.handleDownload(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachTranslateFlags(\n this.program\n .command('translate')\n .description('Translate your project using General Translation')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Starting translation...');\n await this.handleTranslate(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupSendDiffsCommand(): void {\n attachSharedFlags(\n this.program\n .command('save-local')\n .description(\n 'Save local edits for all configured files by sending diffs (no translation enqueued)'\n )\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .action(async (initOptions: SharedFlags) => {\n displayHeader('Saving local edits...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n await saveLocalEdits(settings);\n logger.endCommand('Saved local edits');\n });\n }\n\n protected setupApiCommand(): void {\n attachSharedFlags(\n this.program\n .command('api [endpoint]')\n .description('Make an authenticated request to the GT API')\n .option('-X, --method <method>', 'HTTP method', 'GET')\n .option('--input <file>', 'Request body file, or - for standard input')\n .option(\n '-H, --header <header>',\n 'Request header in \"Key: Value\" format',\n (header, headers: string[] | undefined) => [\n ...(headers ?? []),\n header,\n ]\n )\n .option('-i, --include', 'Include response status and headers')\n .option('--spec', 'Print the bundled OpenAPI specification')\n ).action((endpoint, options: ApiCommandOptions) =>\n handleApiCommand(endpoint, options)\n );\n }\n\n protected setupProjectCommands(): void {\n const projectCommand = this.program\n .command('project')\n .description('Manage General Translation projects');\n\n attachSharedFlags(\n projectCommand\n .command('create')\n .description(\n 'Create a General Translation project using an organization API key'\n )\n .requiredOption('--org-id <orgId>', 'Organization ID')\n .requiredOption('--name <name>', 'Project name')\n .requiredOption('--default-locale <locale>', 'Project default locale')\n .option('--cdn-enabled', 'Enable CDN delivery', false)\n ).action(async (options) => {\n try {\n const settings = await generateSettings(options);\n // Project creation happens before a project ID exists.\n if (!hasValidServiceLocales(settings)) return exitSync(1);\n const { project } = await api.createProject(options.orgId, {\n name: options.name,\n defaultLocale: options.defaultLocale,\n cdnEnabled: options.cdnEnabled,\n });\n logger.info(`Created ${project.name} (${project.id})`);\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError('Failed to create the project', error)\n );\n }\n });\n\n attachSharedFlags(\n projectCommand\n .command('status')\n .description('Check the status of a project setup job')\n .argument('<job-id>', 'Setup job ID')\n ).action(async (jobId, options) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const [status] = await api.checkJobStatus([jobId]);\n logger.info(status?.status ?? 'unknown');\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError(\n 'Failed to check the project setup status',\n error\n )\n );\n }\n });\n }\n\n protected setupApiKeyCommands(): void {\n const apiKeyCommand = this.program\n .command('api-key')\n .description('Manage API keys for the configured project');\n\n attachSharedFlags(\n apiKeyCommand\n .command('create')\n .description(\n 'Create a project API key with the requested permissions and print it once'\n )\n .requiredOption('--name <name>', 'Key name', parseApiKeyName)\n // Validated before any request; the server grants the requested set\n // all-or-nothing, so omitting permissions would delegate everything.\n .addOption(\n new Option('--permission <permissions...>', 'Permissions to grant')\n .choices(Object.values(ProjectApiKeyPermission))\n .makeOptionMandatory()\n )\n ).action(\n async (\n options: SharedFlags & {\n name: string;\n permission: ProjectApiKeyPermission[];\n }\n ) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const { apiKey } = await api.createProjectApiKey(settings.projectId, {\n name: options.name,\n permissions: options.permission,\n });\n // Raw stdout: the secret is shown once and never reaches the log file.\n process.stdout.write(`${apiKey.key}\\n`);\n } catch (error) {\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError('Failed to create the API key', error)\n );\n }\n }\n );\n }\n\n protected setupGitCommand(): void {\n const gitCommand = this.program\n .command('git')\n .description('Configure Git integrations for General Translation');\n\n gitCommand\n .command('setup')\n .description('Set up GT merge drivers for generated translation files')\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--dry-run', 'Print changes without writing files', false)\n .option(\n '--omit-config-ids',\n 'Persist omitConfigIds and remove generated config IDs'\n )\n .option(\n '--driver-command <command>',\n 'Command Git should use to invoke gt, e.g. \"pnpm exec gt\"'\n )\n .action(async (options: GitSetupOptions) => {\n displayHeader('Setting up GT Git merge drivers...');\n const settings = await generateSettings(options, undefined, {\n requireConfig: true,\n });\n const omitConfigIds = await this.resolveGitSetupOmitConfigIds(\n options,\n settings\n );\n const result = await setupGitMergeDrivers(settings, {\n dryRun: options.dryRun,\n omitConfigIds,\n driverCommand: options.driverCommand,\n });\n\n for (const line of result.addedAttributes) {\n logger.step(\n `${options.dryRun ? 'Would add' : 'Added'} ${chalk.cyan(\n line\n )} to ${chalk.cyan(result.gitattributesPath)}`\n );\n }\n if (result.addedAttributes.length === 0) {\n logger.info(`${chalk.cyan('.gitattributes')} is already configured.`);\n }\n\n for (const args of result.gitConfigCommands) {\n logger.step(\n `${options.dryRun ? 'Would run' : 'Configured'} ${chalk.cyan(\n `git config --local ${args.join(' ')}`\n )}`\n );\n }\n\n if (result.updatedConfig) {\n logger.step(\n `${options.dryRun ? 'Would persist' : 'Persisted'} ${chalk.cyan(\n 'omitConfigIds: true'\n )} in ${chalk.cyan(settings.config)}`\n );\n } else if (options.dryRun && !settings.omitConfigIds) {\n logger.info(\n `Run without ${chalk.cyan('--dry-run')} to be prompted to persist ${chalk.cyan(\n 'omitConfigIds: true'\n )}, or pass ${chalk.cyan('--omit-config-ids')}.`\n );\n }\n\n for (const warning of result.warnings) {\n logger.warn(chalk.yellow(warning));\n }\n\n logger.endCommand(\n options.dryRun\n ? 'Dry run complete.'\n : 'GT Git merge drivers configured.'\n );\n });\n\n gitCommand\n .command('merge-driver', { hidden: true })\n .addArgument(\n new Argument('<driver>', 'Merge driver name').choices([\n 'gt-lock',\n 'gtjson',\n ])\n )\n .argument('<base>', 'Common ancestor file')\n .argument('<ours>', 'Current branch file')\n .argument('<theirs>', 'Incoming branch file')\n .argument('[path]', 'Merged path')\n .action(\n (\n driver: MergeDriverName,\n base: string,\n ours: string,\n theirs: string\n ) => {\n const result = runMergeDriver(driver, base, ours, theirs);\n if (!result.ok) {\n logger.error(result.reason);\n exitSync(1);\n }\n }\n );\n }\n\n protected async resolveGitSetupOmitConfigIds(\n options: GitSetupOptions,\n settings: Settings\n ): Promise<boolean> {\n if (options.omitConfigIds) return true;\n // Already opted in: persist again so stale config IDs still get removed\n if (settings.omitConfigIds) return true;\n if (options.dryRun || !process.stdin.isTTY || !process.stdout.isTTY) {\n return false;\n }\n return promptConfirm({\n message:\n 'Also set omitConfigIds: true to reduce gt.config.json merge conflicts?',\n defaultValue: true,\n });\n }\n\n protected async handleSetupProject(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n await handleSetupProject(initOptions, settings, this.library);\n }\n\n protected async handleStage(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Update settings.stageTranslations to true\n settings.stageTranslations = true;\n await updateConfig(settings.config, {\n stageTranslations: true,\n });\n }\n await handleStage(initOptions, settings, this.library, true);\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleEnqueue(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleEnqueue(initOptions, settings, this.library);\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleDownload(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleDownload(initOptions, settings, this.library);\n }\n\n protected async handleTranslate(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Lottie translations finish asynchronously server-side (layout\n // refinement runs after the translation job completes), so the immediate\n // translate flow would try to download them before they're ready. Only\n // the stage + download flow supports them.\n if (settings.files?.resolvedPaths.lottie?.length) {\n return logErrorAndExit(lottieTranslateError);\n }\n const results = await handleStage(\n initOptions,\n settings,\n this.library,\n false\n );\n if (results) {\n await handleTranslate(\n initOptions,\n settings,\n results.fileVersionData,\n results.jobData,\n results.branchData,\n results.publishMap,\n results.inlineLibrary\n );\n }\n } else {\n await handleDownload(initOptions, settings, this.library);\n }\n // Only postprocess files downloaded in this run\n const include = getNeedsPostprocessing();\n if (include.size > 0) {\n await postProcessTranslations(settings, include);\n }\n // Split Mintlify language entries into $ref files to keep docs.json small\n await splitMintlifyLanguageRefs(settings);\n // Localize redirects for pages this run renamed or removed. Runs after the\n // split, which can rewrite $ref files such as redirects.json\n const orphanedFileNames = getOrphanedFileNames();\n if (orphanedFileNames) {\n const added = localizeMintlifyRedirects(settings, orphanedFileNames);\n if (added.length > 0) {\n logger.success(\n `Added ${added.length} localized redirect${added.length === 1 ? '' : 's'}`\n );\n }\n }\n clearOrphanedFileNames();\n // Mirror assets after translations are downloaded and locale dirs are populated\n await mirrorAssetsToLocales(settings);\n clearDownloaded();\n displayTranslateSummary();\n clearWarnings();\n }\n\n protected setupUploadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('upload')\n .description(\n 'Upload source files and translations to the General Translation platform'\n )\n ).action(async (initOptions: UploadOptions) => {\n displayHeader('Starting upload...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const options = { ...initOptions, ...settings };\n\n await this.handleUploadCommand(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupUserAuthCommands(): void {\n this.program\n .command('login')\n .description('Sign in to your General Translation account')\n .option(\n '--no-browser',\n 'Do not open a browser; show a sign-in URL to use on any device instead'\n )\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json'\n )\n .action(async (options: { browser: boolean; config?: string }) => {\n displayHeader('Signing in to General Translation...');\n try {\n // Tokens are bound to one API resource, so log in to the configured one.\n const baseUrl = (\n options.config\n ? loadConfig(withJsonExtension(options.config))\n : resolveConfig(process.cwd())?.config\n )?.baseUrl;\n await loginInteractively(\n typeof baseUrl === 'string' ? baseUrl : undefined,\n options.browser\n );\n logger.endCommand('You are now signed in.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign in failed', error));\n }\n });\n\n this.program\n .command('logout')\n .description('Sign out of your General Translation account')\n .action(async () => {\n try {\n await logout();\n logger.endCommand('Signed out successfully.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign out failed', error));\n }\n });\n\n this.program\n .command('whoami')\n .description('Show the signed-in General Translation account')\n .action(async () => {\n try {\n const user = await whoAmI();\n logger.message(user.email ?? user.name ?? user.sub);\n } catch (error) {\n logErrorAndExit(\n createUserAuthError('Could not load your account', error)\n );\n }\n });\n }\n\n protected setupInitCommand(): void {\n attachInitFlags(\n this.program\n .command('init')\n .description(\n 'Run the setup wizard to configure your project for General Translation. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: InitOptions) => this.handleInitWizard(options));\n }\n\n protected async handleInitWizard(options: InitOptions): Promise<void> {\n await runOnboarding('init', options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Running setup wizard...');\n\n const detected = await detectFramework();\n const reactDetected = detected.type === 'react' ? detected : undefined;\n if (options.framework && !reactDetected) {\n session.reject(\n '--framework applies only to projects detected as React applications'\n );\n }\n const configFilepath = setupConfigPath(options);\n const configured = getConfiguredFramework(\n readSetupConfig(configFilepath)\n );\n const configuredReact =\n configured !== 'mintlify' ? configured : undefined;\n // Explicit --defaults / --no-defaults also answer the Locadex gate.\n if (options.defaults !== undefined) session.defaults = options.defaults;\n const gateFramework = options.framework ?? configured ?? detected.name;\n if (gateFramework === 'mintlify' || gateFramework === 'next-app') {\n const useLocadex = await session.answer('--locadex', {\n explicit: options.locadex,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n gateFramework === 'mintlify'\n ? `Mintlify project detected. Would you like to connect to GitHub so that the Locadex AI Agent can translate your project automatically?`\n : `Next.js App Router detected. Would you like to connect to GitHub so that the Locadex AI Agent can set up your project automatically?`,\n defaultValue: false,\n }),\n });\n if (useLocadex) {\n session.assertResolved();\n const url = await setupLocadex(\n await generateSettings({ config: options.config }),\n { openBrowser: session.interactive }\n );\n session.emit({ type: 'handoff', url, reason: 'locadex' });\n logger.endCommand(\n 'Once installed, Locadex will open a PR to your repository. See the docs for more information: https://generaltranslation.com/docs/locadex'\n );\n return { outcome: 'needs_human_action', url };\n }\n } else if (options.locadex) {\n session.reject(\n '--locadex applies only to Mintlify and Next.js App Router projects'\n );\n }\n\n const shownFramework = reactDetected && {\n ...reactDetected,\n name: options.framework ?? configuredReact ?? reactDetected.name,\n };\n // Without --defaults, a noninteractive run uses no defaults.\n session.defaults =\n (await session.answer('--defaults', {\n explicit: options.defaults,\n fallback: false,\n ask: () =>\n promptConfirm({\n message: `Would you like to use the recommended General Translation defaults? ${chalk.dim(`(${describeDefaults(shownFramework)})`)}`,\n defaultValue: true,\n }),\n })) === true;\n\n const reactSetup = reactDetected\n ? await resolveReactSetup(\n session,\n options,\n reactDetected,\n configuredReact\n )\n : undefined;\n // flag > gt.config.json > detection, used for every later step.\n const framework =\n reactSetup?.framework ??\n options.framework ??\n configured ??\n detected.name;\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n saveFramework: Boolean(reactSetup || options.framework),\n reactSetup,\n keepAppSource: !reactSetup,\n });\n\n logger.endCommand(\n 'Done! Check out our docs for more information on how to use General Translation: https://generaltranslation.com/docs'\n );\n return { outcome: 'success' };\n });\n }\n\n protected setupConfigureCommand(): void {\n attachConfigureFlags(\n this.program\n .command('configure')\n .description(\n 'Configure your project for General Translation. This will create a gt.config.json file in your codebase. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: ConfigureOptions) =>\n this.handleConfigureCommand(options)\n );\n }\n\n protected async handleConfigureCommand(\n options: ConfigureOptions,\n command: string = 'configure'\n ): Promise<void> {\n await runOnboarding(command, options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Configuring project...');\n\n logger.info(\n 'Welcome! This tool will help you configure your gt.config.json file. See the docs: https://generaltranslation.com/docs/cli/reference/config for more information.'\n );\n\n // Configure only offers the defaults when asked with --defaults.\n session.defaults = options.defaults ?? false;\n const detected = await detectFramework();\n const configFilepath = setupConfigPath(options);\n // Detection only picks env names here; it is not saved.\n const framework =\n getConfiguredFramework(readSetupConfig(configFilepath)) ??\n detected.name;\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n });\n\n logger.endCommand(\n 'Done! Make sure you have an API key and project ID to use General Translation. Get them on the dashboard: https://generaltranslation.com/dashboard'\n );\n return { outcome: 'success' };\n });\n }\n\n protected async handleUploadCommand(\n settings: Settings & UploadOptions\n ): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n // Process all file types at once with a single call\n await upload(settings);\n }\n\n /** Describes installed runtimes without changing historical package lookup. */\n protected getInlineRuntimeSetup(\n packageJson: Record<string, unknown>,\n ranReactSetup: boolean = false\n ): InlineRuntimeSetup {\n return {\n hasOtherInlineRuntime: INLINE_LIBRARIES.some(\n (lib) =>\n lib !== Libraries.GT_VUE && isPackageInstalled(lib, packageJson)\n ),\n hasVueRuntime: manifestDirectlyDeclaresGTVue(packageJson),\n ranReactSetup,\n };\n }\n\n /** Returns whether any inline runtime is installed for setup. */\n protected isInlineRuntimeInstalled(\n packageJson: Record<string, unknown>\n ): boolean {\n const { hasOtherInlineRuntime, hasVueRuntime } =\n this.getInlineRuntimeSetup(packageJson);\n return hasOtherInlineRuntime || hasVueRuntime;\n }\n\n /** Returns whether every installed runtime can consume CDN translations. */\n protected supportsCDNStorage(runtimeSetup: InlineRuntimeSetup): boolean {\n return !runtimeSetup.hasVueRuntime;\n }\n\n /** Returns whether setup should generate a local runtime loader. */\n protected shouldGenerateLocalTranslationLoader(\n buildToolOwnsLoader: boolean,\n runtimeSetup: InlineRuntimeSetup\n ): boolean {\n if (buildToolOwnsLoader) return false;\n if (!runtimeSetup.hasVueRuntime) return true;\n return runtimeSetup.hasOtherInlineRuntime || runtimeSetup.ranReactSetup;\n }\n\n /** Returns framework guidance after selecting local translation storage. */\n protected getLocalTranslationGuidance({\n generatedLoader,\n runtimeSetup,\n translationsDir,\n }: LocalTranslationGuidanceOptions): string | undefined {\n const guidance: string[] = [];\n if (generatedLoader) {\n guidance.push(`Created ${chalk.cyan('loadTranslations.js')} file for local translations.\nMake sure to add this function to your app configuration.\nSee https://generaltranslation.com/en/docs/next/guides/local-tx`);\n }\n if (runtimeSetup.hasVueRuntime) {\n guidance.push(`GT will write local translation files to ${translationsDir}.\nConfigure createGT({ loadTranslations }) to load files from that directory.\nSee https://www.npmjs.com/package/gt-vue`);\n }\n return guidance.length > 0 ? guidance.join('\\n') : undefined;\n }\n\n /**\n * Resolves every configuration answer and validates the resulting config,\n * checks the project and signs in before the first change, then applies\n * the React setup, gt.config.json, installs and development credentials.\n */\n protected async handleInitCommand(\n session: OnboardingSession,\n options: ConfigureOptions,\n setup: {\n /** Chosen once by the entry point from the detected framework. */\n configFilepath: string;\n /** Resolved framework; drives storage, env names and build-tool setup. */\n framework?: SupportedFrameworks;\n /** Write the framework even when no build-tool setup saves it. */\n saveFramework?: boolean;\n reactSetup?: ReactSetupPlan;\n /** Init without the React setup never changes application source. */\n keepAppSource?: boolean;\n }\n ): Promise<void> {\n const { configFilepath, reactSetup } = setup;\n const buildTool = getBuildToolSetup(setup.framework);\n const cwd = process.cwd();\n const existingConfig = readSetupConfig(configFilepath);\n const { defaultLocale, locales } = await getDesiredLocales(\n session,\n existingConfig,\n options\n );\n\n const packageJson =\n reactSetup?.packageJson ?? (await searchForPackageJson());\n const runtimeSetup: InlineRuntimeSetup = packageJson\n ? this.getInlineRuntimeSetup(packageJson, Boolean(reactSetup))\n : {\n hasOtherInlineRuntime: false,\n hasVueRuntime: false,\n ranReactSetup: false,\n };\n const isUsingGT =\n runtimeSetup.ranReactSetup ||\n runtimeSetup.hasOtherInlineRuntime ||\n runtimeSetup.hasVueRuntime;\n const supportsCDN = this.supportsCDNStorage(runtimeSetup);\n const existingFiles = asRecord(existingConfig.files) ?? {};\n const existingGtOutput = asRecord(existingFiles.gt)?.output;\n const configuredOutput =\n typeof existingGtOutput === 'string' ? existingGtOutput : undefined;\n const configuredStorage = configuredOutput\n ? 'local'\n : existingConfig.publish === true\n ? 'cdn'\n : undefined;\n\n if (isUsingGT && !supportsCDN && options.storage === 'cdn') {\n session.reject(\n 'gt-vue cannot load translations from the CDN; use --storage local'\n );\n }\n // Where GT translations are stored\n const storage = !isUsingGT\n ? undefined\n : !supportsCDN\n ? 'local'\n : await session.answer<'local' | 'cdn'>('--storage', {\n explicit: options.storage,\n configured: configuredStorage,\n recommended: 'local',\n ask: () =>\n promptSelect<'local' | 'cdn'>({\n message: `Would you like to save translation files locally or use the General Translation CDN to store them?`,\n options: [\n { value: 'local', label: 'Save locally' },\n { value: 'cdn', label: 'Use CDN' },\n ],\n defaultValue: 'local',\n }),\n });\n\n const defaultTranslationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n const outputMatch = configuredOutput?.match(\n /^(?:(.+)[\\\\/])?\\[locale\\]\\.json$/\n );\n const configuredTranslationsDir = outputMatch\n ? (outputMatch[1] ?? '.')\n : undefined;\n const translationsDir =\n storage === 'local'\n ? await session.answer('--translations-dir', {\n explicit: options.translationsDir?.trim() || undefined,\n configured: configuredTranslationsDir,\n recommended: defaultTranslationsDir,\n ask: async () =>\n (\n await promptText({\n message:\n 'What is the path to the directory where you would like to store your translation files?',\n defaultValue: defaultTranslationsDir,\n })\n ).trim() || defaultTranslationsDir,\n })\n : undefined;\n\n const filePatterns = parseFilePatterns(session, options.filePatterns);\n const selectedFormats = options.fileFormats?.filter(\n (format): format is SetupFileFormat => format !== 'none'\n );\n if (\n options.fileFormats?.includes('none') &&\n (selectedFormats?.length ?? 0) > 0\n ) {\n session.reject('--file-formats none cannot be combined with formats');\n }\n const configuredFormats = SETUP_FILE_FORMATS.filter(\n (format) => format in existingFiles\n );\n // Formats setup does not offer stay as configured and count as files.\n const otherFormats = SUPPORTED_FILE_EXTENSIONS.filter(\n (format) =>\n format in existingFiles &&\n !(SETUP_FILE_FORMATS as readonly string[]).includes(format)\n );\n const hasOtherFormats = otherFormats.length > 0;\n if (options.fileFormats && hasOtherFormats) {\n const kept = otherFormats.map((format) => `files.${format}`).join(', ');\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `${kept} stays in ${configFilepath}`,\n why: '--file-formats only changes the formats setup offers',\n fix: `Remove ${kept} from ${configFilepath} to stop translating those files`,\n })\n );\n }\n const fileFormats = await session.answer<SetupFileFormat[]>(\n '--file-formats',\n {\n explicit:\n selectedFormats ??\n (filePatterns.size > 0 ? [...filePatterns.keys()] : undefined),\n configured:\n configuredFormats.length > 0 || hasOtherFormats\n ? configuredFormats\n : undefined,\n // GT projects need no other files; others must choose a format.\n recommended: isUsingGT ? [] : undefined,\n ask: () =>\n promptMultiSelect({\n message: !isUsingGT\n ? 'What is the format of your language resource files? Select as many as applicable.\\nAdditionally, you can translate any other files you have in your project.'\n : `Do you have any additional files in this project to translate? For example, Markdown files for docs. ${chalk.dim(\n '(To continue without selecting press Enter)'\n )}`,\n options: SETUP_FILE_FORMATS.map((format) => ({\n value: format,\n label: FILE_EXT_TO_EXT_LABEL[format],\n })),\n required: !isUsingGT,\n }),\n }\n );\n if (\n fileFormats &&\n fileFormats.length === 0 &&\n !isUsingGT &&\n !hasOtherFormats\n ) {\n session.reject(\n 'No GT runtime is installed, so select at least one file format to translate'\n );\n }\n for (const format of filePatterns.keys()) {\n if (fileFormats && !fileFormats.includes(format)) {\n session.reject(\n `--file-patterns ${format}= needs ${format} in --file-formats`\n );\n }\n }\n\n const files: FilesOptions = {};\n for (const fileExtension of fileFormats ?? []) {\n const existingFormat = asRecord(existingFiles[fileExtension]);\n const configuredInclude = Array.isArray(existingFormat?.include)\n ? (existingFormat.include as string[])\n : undefined;\n const include = await session.answer(\n `--file-patterns ${fileExtension}=<glob>`,\n {\n explicit: filePatterns.get(fileExtension),\n configured: configuredInclude,\n recommended: [`./**/[locale]/*.${fileExtension}`],\n ask: async () =>\n parseGlobPatterns(\n await promptGlobPatterns({\n label: FILE_EXT_TO_EXT_LABEL[fileExtension],\n message: `${chalk.cyan(FILE_EXT_TO_EXT_LABEL[fileExtension])}: Enter a space-separated list of glob patterns matching the location of the ${FILE_EXT_TO_EXT_LABEL[fileExtension]} files you would like to translate.\\nMake sure to include [locale] in the patterns.\\nSee https://generaltranslation.com/docs/cli/reference/config#include for more information.`,\n defaultValue: `./**/[locale]/*.${fileExtension}`,\n validate: (value) =>\n parseGlobPatterns(value)\n .map(validateSetupPattern)\n .find((problem) => problem !== true) ?? true,\n })\n ),\n }\n );\n // Configured patterns stay untouched; new ones keep other entry options.\n if (include && include !== configuredInclude) {\n files[fileExtension] = { ...existingFormat, include };\n }\n }\n if (translationsDir && translationsDir !== configuredTranslationsDir) {\n files.gt = { output: path.join(translationsDir, `[locale].json`) };\n }\n\n const envFramework =\n setup.framework ?? getConfiguredFramework(existingConfig);\n // The effective project: an explicit ID replaces a configured one. The\n // framework's runtime project outranks a stale generic GT_PROJECT_ID.\n const projectId =\n options.projectId ||\n (typeof existingConfig.projectId === 'string'\n ? existingConfig.projectId\n : undefined) ||\n process.env[getDevelopmentEnvNames(envFramework).projectId];\n const configUpdate: SetupConfigUpdate = {\n defaultLocale,\n locales,\n src: options.src,\n files: Object.keys(files).length > 0 ? files : undefined,\n framework:\n (setup.saveFramework && setup.framework) || buildTool?.framework,\n publish: storage === 'cdn',\n // Selecting local storage drops stale CDN intent; a config that\n // already combines local files with publishing keeps it.\n clearPublish:\n storage === 'local' &&\n (options.storage === 'local' ||\n configuredStorage !== 'local' ||\n !supportsCDN),\n // An explicit switch to the CDN stops later runs inferring local files.\n clearGtOutput: storage === 'cdn' && configuredOutput !== undefined,\n // An explicit format list replaces the configured selection.\n removeFiles: selectedFormats\n ? configuredFormats.filter(\n (format) => !selectedFormats.includes(format)\n )\n : undefined,\n };\n session.assertResolved();\n\n // Validate what will be written, and use it for every later step.\n const { projectId: _writtenProjectId, ...effectiveConfig } =\n mergeSetupConfig(existingConfig, configUpdate);\n const settings = await generateSettings(\n { config: configFilepath, ...(projectId && { projectId }) },\n cwd,\n { resolvedConfig: effectiveConfig }\n );\n // Runtime credentials only count for the project this setup uses; the\n // framework's project variable is the one paired with its dev key.\n const runtimeProjectId =\n process.env[getDevelopmentEnvNames(envFramework).projectId] ??\n resolveProjectId();\n const runtimeProjectMatches =\n runtimeProjectId === undefined || runtimeProjectId === settings.projectId;\n const credentialsSet =\n runtimeProjectMatches && areCredentialsSet(settings, envFramework);\n const credentialsOption =\n (storage === 'local' && buildTool?.devCredentialsOption) ||\n '--dev-credentials';\n // Creating credentials talks to GT as the signed-in user unless an API\n // key is set. A development key in .env.local never stands in. An\n // obsolete stored login counts as signed out, so signing in replaces it.\n const canAuthenticate = async () =>\n Boolean(settings.apiKey) ||\n (await hasLogin({ baseUrl: settings.baseUrl }).catch((error) => {\n if (\n error instanceof UserAuthError &&\n error.code === 'obsolete_credentials'\n )\n return false;\n throw error;\n }));\n const provision =\n !credentialsSet &&\n (credentialsOption === '--live-translations'\n ? await session.answer('--live-translations', {\n explicit: options.liveTranslations ?? options.devCredentials,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n 'Would you like to set up live development translations? This requires signing in or an API key.',\n defaultValue: false,\n }),\n })\n : await session.answer('--dev-credentials or --no-dev-credentials', {\n explicit: options.devCredentials,\n // Creating a key is never a default, so --defaults leaves this open.\n // The prompt names the sign-in so its Yes default is informed.\n ask: async () =>\n promptConfirm({\n message: (await canAuthenticate())\n ? 'Would you like to set up a project ID and hot-reload key in .env.local?'\n : 'Would you like to sign in to General Translation and set up a project ID and hot-reload key in .env.local?',\n defaultValue: true,\n }),\n })) === true;\n if (!runtimeProjectMatches && !provision) {\n session.reject(\n `The runtime credentials in the environment belong to project ${runtimeProjectId}, not ${settings.projectId}; pass --dev-credentials to replace them in .env.local`\n );\n }\n // An explicit ID is saved to gt.config.json when it replaces a\n // configured one or no new credentials will record it in .env.local.\n if (options.projectId && (existingConfig.projectId || !provision)) {\n configUpdate.projectId = options.projectId;\n }\n if (provision) {\n checkDevelopmentProjectInputs(\n session,\n settings,\n options,\n options.projectId\n ? '--project-id'\n : // An empty configured ID falls through to the environment.\n typeof existingConfig.projectId === 'string' &&\n existingConfig.projectId\n ? configFilepath\n : 'the environment'\n );\n await withCredentialsError(() =>\n inspectCredentialsEnvFile(cwd, { framework: envFramework })\n );\n }\n\n if (reactSetup && buildTool) await buildTool.preflight(cwd);\n const installGT =\n packageJson !== null &&\n !isPackageInstalled('gt', packageJson, true, true) &&\n !buildTool?.skipsGTInstall(isUsingGT);\n const packageManager =\n reactSetup?.install || installGT\n ? await resolvePackageManager(session, options.packageManager)\n : undefined;\n\n session.assertResolved();\n\n if (provision && !(await canAuthenticate())) {\n await signInForSetup(session, settings.baseUrl);\n }\n const project = provision\n ? await withCredentialsError(() =>\n resolveDevelopmentProject(session, settings, options, cwd)\n )\n : undefined;\n session.assertResolved();\n\n // ----- Changes start here ----- //\n const resolvedLocales = locales as string[];\n\n if (reactSetup) {\n logger.info(`${chalk.yellow('[EXPERIMENTAL]')} Configuring project...`);\n if (reactSetup.install && packageManager) {\n await installWithProgress(\n session,\n reactSetup.install,\n packageManager,\n false\n );\n }\n await executeReactSetup(session, reactSetup, options);\n logger.endCommand(\n `Done! Since this wizard is experimental, please review the changes and make modifications as needed.\n\\nNext step: start internationalizing! See the docs for more information: ${buildTool?.docsUrl ?? REACT_QUICKSTART_URL}`\n );\n logger.startCommand('Setting up project config...');\n }\n\n const reportManualAction = ({ whatHappened, fix }: ManualAction) => {\n session.humanActions.push(fix);\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened,\n fix,\n })\n );\n };\n const reportSetupResult = ({ steps, manualActions }: SetupResult) => {\n for (const step of steps) session.step(step);\n manualActions.forEach(reportManualAction);\n };\n const translationFilesError = (error: unknown) =>\n new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not create the translation files in ${translationsDir}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Choose another --translations-dir or fix the path, then rerun the command',\n })\n );\n const buildToolContext = {\n appDirectory: cwd,\n configFilepath,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n previousTranslationsDir: configuredTranslationsDir,\n };\n\n if (storage === 'local' && translationsDir) {\n if (buildTool && !reactSetup) {\n reportSetupResult(\n await buildTool\n .syncLoader({\n ...buildToolContext,\n translationsDir,\n keepAppSource: setup.keepAppSource,\n })\n .catch((error: unknown) => {\n throw translationFilesError(error);\n })\n );\n }\n const generatedLoader = this.shouldGenerateLocalTranslationLoader(\n buildTool?.ownsLoader ?? false,\n runtimeSetup\n );\n const loader = generatedLoader\n ? await createLoadTranslationsFile({\n appDirectory: cwd,\n translationsDir,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n previousTranslationsDir: configuredTranslationsDir,\n }).catch((error: unknown) => {\n throw translationFilesError(error);\n })\n : undefined;\n if (loader === 'created' || loader === 'updated') {\n session.step(`${loader} loadTranslations.js`);\n }\n // A loader left unchanged may not read the newly chosen directory.\n if (\n loader === 'custom' &&\n translationsDir !== configuredTranslationsDir\n ) {\n const loaderFile = path.relative(\n cwd,\n findLoadTranslationsFiles(cwd)[0] ?? 'loadTranslations.js'\n );\n reportManualAction({\n whatHappened: `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`,\n fix: `Update your custom ${loaderFile} to load translations from ${translationsDir}`,\n });\n }\n const guidance = this.getLocalTranslationGuidance({\n generatedLoader: generatedLoader && loader !== 'custom',\n runtimeSetup,\n translationsDir,\n });\n if (guidance) logger.message(guidance);\n } else if (\n storage === 'cdn' &&\n buildTool &&\n !reactSetup &&\n configuredTranslationsDir !== undefined\n ) {\n // Only the application setup rewrites the initializer; a loader passed\n // to it takes precedence over CDN loading.\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,\n fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`,\n });\n } else if (\n storage === 'cdn' &&\n !buildTool &&\n configuredTranslationsDir !== undefined\n ) {\n // gt-next uses a loadTranslations file whenever one exists, and a\n // loader passed to GTProvider takes precedence over the CDN. Name every\n // one: deleting only the first makes gt-next fall back to the next.\n const loaders = findLoadTranslationsFiles(cwd).map((loader) =>\n path.relative(cwd, loader)\n );\n if (loaders.length > 0) {\n const loaderFiles = loaders.join(', ');\n const [them, loads] =\n loaders.length === 1 ? ['it', 'loads'] : ['them', 'load'];\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${loaderFiles} still ${loads} them from ${configuredTranslationsDir}`,\n fix: `Delete ${loaderFiles}, and remove ${them} from your GT setup if you pass ${them} there, so translations load from the CDN`,\n });\n }\n }\n\n const configChange = await applySetupConfig(configFilepath, configUpdate);\n if (configChange !== 'unchanged') {\n session.step(`${configChange} ${configFilepath}`);\n }\n\n logger.success(\n `Edit ${chalk.cyan(\n configFilepath\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n if (reactSetup && buildTool) {\n reportSetupResult(await buildTool.apply(buildToolContext));\n }\n\n if (installGT && packageManager) {\n await installWithProgress(session, 'gt', packageManager, true);\n }\n\n if (project) {\n await withCredentialsError(() =>\n provisionDevelopmentCredentials(\n session,\n project,\n settings,\n envFramework,\n cwd\n )\n );\n logger.message(productionRuntimeKeyGuidance(settings.dashboardUrl));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;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D,CACF;AACD,UAAO,QAAQ,6BAA6B,SAAS,aAAa,CAAC"}
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../src/cli/base.ts"],"sourcesContent":["import { Argument, Command, InvalidArgumentError, Option } from 'commander';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n DEFAULT_TRANSLATIONS_DIR,\n REACT_QUICKSTART_URL,\n} from '../utils/constants.js';\nimport {\n applySetupConfig,\n mergeSetupConfig,\n type SetupConfigUpdate,\n} from '../fs/config/setupConfig.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport {\n displayHeader,\n promptText,\n logErrorAndExit,\n exitSync,\n promptConfirm,\n promptMultiSelect,\n promptSelect,\n promptGlobPatterns,\n} from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { lottieTranslateError } from '../console/index.js';\nimport { parseGlobPatterns } from '../console/promptParsing.js';\nimport path from 'node:path';\nimport {\n FilesOptions,\n Settings,\n SupportedFrameworks,\n SupportedLibraries,\n TranslateFlags,\n SharedFlags,\n} from '../types/index.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport chalk from 'chalk';\nimport {\n FILE_EXT_TO_EXT_LABEL,\n SETUP_FILE_FORMATS,\n SUPPORTED_FILE_EXTENSIONS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n executeReactSetup,\n resolveReactSetup,\n type ReactSetupPlan,\n} from '../setup/wizard.js';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { getDesiredLocales } from '../setup/userInput.js';\nimport {\n areCredentialsSet,\n getDevelopmentEnvNames,\n inspectCredentialsEnvFile,\n} from '../utils/credentials.js';\nimport {\n checkDevelopmentProjectInputs,\n productionRuntimeKeyGuidance,\n provisionDevelopmentCredentials,\n resolveDevelopmentProject,\n signInForSetup,\n} from '../setup/developmentCredentials.js';\nimport { exitIfUnsupportedSetupTarget } from '../setup/setupTarget.js';\nimport {\n asRecord,\n attachConfigureFlags,\n attachInitFlags,\n describeDefaults,\n displaySetupHeader,\n getConfiguredFramework,\n INIT_SOURCE_HELP,\n installWithProgress,\n OnboardingError,\n parseFilePatterns,\n readSetupConfig,\n reportJsonExitsBeforeOnboarding,\n resolvePackageManager,\n runOnboarding,\n setupConfigPath,\n validateSetupPattern,\n type ConfigureOptions,\n type InitOptions,\n type OnboardingSession,\n} from '../setup/onboarding.js';\nimport { upload } from './commands/upload.js';\nimport { attachSharedFlags, attachTranslateFlags } from './flags.js';\nimport { handleStage } from './commands/stage.js';\nimport { handleSetupProject } from './commands/setupProject.js';\nimport { handleDownload } from './commands/download.js';\nimport {\n handleTranslate,\n postProcessTranslations,\n} from './commands/translate.js';\nimport {\n getNeedsPostprocessing,\n clearDownloaded,\n} from '../state/recentDownloads.js';\nimport { clearWarnings } from '../state/translateWarnings.js';\nimport { displayTranslateSummary } from '../console/displayTranslateSummary.js';\nimport updateConfig from '../fs/config/updateConfig.js';\nimport {\n createLoadTranslationsFile,\n findLoadTranslationsFiles,\n} from '../fs/createLoadTranslationsFile.js';\nimport { saveLocalEdits } from '../api/saveLocalEdits.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './commands/utils/validation.js';\nimport processSharedStaticAssets, {\n mirrorAssetsToLocales,\n} from '../utils/sharedStaticAssets.js';\nimport { setupLocadex } from '../locadex/setupFlow.js';\nimport { detectFramework } from '../setup/detectFramework.js';\nimport { INLINE_LIBRARIES, Libraries } from '../types/libraries.js';\nimport { handleEnqueue } from './commands/enqueue.js';\nimport { splitMintlifyLanguageRefs } from '../utils/splitMintlifyLanguageRefs.js';\nimport { localizeMintlifyRedirects } from '../formats/files/postprocess/localizeMintlifyRedirects.js';\nimport {\n clearOrphanedFileNames,\n getOrphanedFileNames,\n} from '../state/orphanedFileNames.js';\nimport { runMergeDriver, type MergeDriverName } from '../git/mergeDrivers.js';\nimport { setupGitMergeDrivers } from '../git/setupMergeDrivers.js';\nimport { warnReactPackageCompatibility } from '../utils/reactPackageCompatibility.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { hasLogin, logout, whoAmI } from '../auth/oauth.js';\nimport { createUserAuthError, UserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { resolveConfig } from '../config/resolveConfig.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport {\n getBuildToolSetup,\n type ManualAction,\n type SetupResult,\n} from '../setup/buildTools/index.js';\nimport { manifestDirectlyDeclaresGTVue } from '@generaltranslation/vue-extractor/integration';\nimport { api } from '../utils/api.js';\nimport { handleApiCommand, type ApiCommandOptions } from './commands/api.js';\n\nconst ID_COMPATIBILITY_WARNING_COMMANDS = new Set([\n 'download',\n 'enqueue',\n 'generate',\n 'setup',\n 'stage',\n 'translate',\n 'validate',\n]);\nfunction createProjectCommandError(\n whatHappened: string,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened,\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst emptyApiKeyNameError = createDiagnosticMessage({\n whatHappened: 'The key name cannot be empty',\n fix: 'Pass a non-empty value with --name',\n});\n\nfunction parseApiKeyName(value: string): string {\n const name = value.trim();\n if (!name) throw new InvalidArgumentError(emptyApiKeyNameError);\n return name;\n}\n\n/** Credential failures keep their own diagnostic or get the setup context. */\nasync function withCredentialsError<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof OnboardingError) throw error;\n throw new Error(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError(\n 'Failed to set up the development credentials',\n error\n )\n );\n }\n}\n\nexport type UploadOptions = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n defaultLocale?: string;\n};\n\nexport type GitSetupOptions = {\n config?: string;\n dryRun?: boolean;\n omitConfigIds?: boolean;\n driverCommand?: string;\n};\n\ntype LocalTranslationGuidanceOptions = {\n generatedLoader: boolean;\n runtimeSetup: InlineRuntimeSetup;\n translationsDir: string;\n};\n\ntype InlineRuntimeSetup = {\n hasOtherInlineRuntime: boolean;\n hasVueRuntime: boolean;\n ranReactSetup: boolean;\n};\n\nexport class BaseCLI {\n protected library: SupportedLibraries;\n protected additionalModules: SupportedLibraries[];\n protected program: Command;\n // Constructor is shared amongst all CLI class types\n public constructor(\n program: Command,\n library: SupportedLibraries,\n additionalModules?: SupportedLibraries[]\n ) {\n this.program = program;\n this.library = library;\n this.additionalModules = additionalModules || [];\n\n this.program.option(\n '--skip-version-check',\n 'Skip the monorepo GT package version consistency check'\n );\n this.program.option(\n '--suppress-id-compatibility-warning',\n 'Suppress the React package ID compatibility warning'\n );\n this.program.option(\n '-q, --quiet',\n 'Suppress informational output; only warnings and errors are shown'\n );\n // Select console routing for this command before anything else logs:\n // root hooks run before subclass hooks (version checks) and the action's\n // settings resolution. `gt api-key create` prints the new secret on\n // stdout, so its diagnostics go to stderr, as do setup commands writing\n // JSON events; every other command gets the historical default back\n // (main() routes startup output to stderr).\n this.program.hook('preAction', (thisCommand, actionCommand) => {\n logger.setConsoleOutput(\n actionCommand.parent?.name() === 'api-key' || actionCommand.opts().json\n ? 'stderr'\n : 'stdout'\n );\n if (\n actionCommand.opts().json &&\n actionCommand.parent === thisCommand &&\n ['init', 'configure'].includes(actionCommand.name())\n ) {\n reportJsonExitsBeforeOnboarding(actionCommand.name());\n }\n });\n // Apply --quiet before any other hook or command action runs so the\n // singleton logger is muted for the rest of the invocation. The flag is a\n // global root option, so commander resolves it in any position and for\n // nested commands (e.g. `gt git setup --quiet`).\n this.program.hook('preAction', () => {\n logger.setQuiet(Boolean(this.program.opts().quiet));\n });\n this.program.hook('preAction', async (thisCommand, actionCommand) => {\n // Nested commands (e.g. `gt git setup`) can share leaf names with\n // translation commands; only direct children of the root qualify\n if (actionCommand.parent !== thisCommand) return;\n if (!ID_COMPATIBILITY_WARNING_COMMANDS.has(actionCommand.name())) return;\n await warnReactPackageCompatibility(\n Boolean(this.program.opts().suppressIdCompatibilityWarning)\n );\n });\n\n this.setupInitCommand();\n this.setupConfigureCommand();\n this.setupUploadCommand();\n this.setupUserAuthCommands();\n this.setupSendDiffsCommand();\n this.setupApiCommand();\n this.setupProjectCommands();\n this.setupApiKeyCommands();\n this.setupGitCommand();\n }\n // Init is never called in a child class\n public init() {\n this.setupSetupProjectCommand();\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n // Execute is called by the main program\n public execute() {\n // If no command is specified, run 'init'\n if (process.argv.length <= 2) {\n process.argv.push('init');\n }\n }\n\n protected setupSetupProjectCommand(): void {\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupStageCommand(): void {\n attachTranslateFlags(\n this.program\n .command('stage')\n .description(\n 'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupEnqueueCommand(): void {\n attachTranslateFlags(\n this.program\n .command('enqueue')\n .description('Enqueues translations for a given set of files')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Enqueuing translations...');\n await this.handleEnqueue(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupDownloadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('download')\n .description('Download translations that were originally staged')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Downloading translations...');\n await this.handleDownload(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachTranslateFlags(\n this.program\n .command('translate')\n .description('Translate your project using General Translation')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Starting translation...');\n await this.handleTranslate(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupSendDiffsCommand(): void {\n attachSharedFlags(\n this.program\n .command('save-local')\n .description(\n 'Save local edits for all configured files by sending diffs (no translation enqueued)'\n )\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .action(async (initOptions: SharedFlags) => {\n displayHeader('Saving local edits...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n await saveLocalEdits(settings);\n logger.endCommand('Saved local edits');\n });\n }\n\n protected setupApiCommand(): void {\n attachSharedFlags(\n this.program\n .command('api [endpoint]')\n .description('Make an authenticated request to the GT API')\n .option('-X, --method <method>', 'HTTP method', 'GET')\n .option('--input <file>', 'Request body file, or - for standard input')\n .option(\n '-H, --header <header>',\n 'Request header in \"Key: Value\" format',\n (header, headers: string[] | undefined) => [\n ...(headers ?? []),\n header,\n ]\n )\n .option('-i, --include', 'Include response status and headers')\n .option(\n '--spec',\n 'Print the bundled OpenAPI specification, or only the operations matching [endpoint] (path or operation ID) with references resolved'\n )\n .addOption(\n new Option(\n '--list',\n 'List the method, path, operation ID, and summary of every API operation'\n ).conflicts('spec')\n )\n ).action((endpoint, options: ApiCommandOptions) =>\n handleApiCommand(endpoint, options)\n );\n }\n\n protected setupProjectCommands(): void {\n const projectCommand = this.program\n .command('project')\n .description('Manage General Translation projects');\n\n attachSharedFlags(\n projectCommand\n .command('create')\n .description(\n 'Create a General Translation project using an organization API key'\n )\n .requiredOption('--org-id <orgId>', 'Organization ID')\n .requiredOption('--name <name>', 'Project name')\n .requiredOption('--default-locale <locale>', 'Project default locale')\n .option('--cdn-enabled', 'Enable CDN delivery', false)\n ).action(async (options) => {\n try {\n const settings = await generateSettings(options);\n // Project creation happens before a project ID exists.\n if (!hasValidServiceLocales(settings)) return exitSync(1);\n const { project } = await api.createProject(options.orgId, {\n name: options.name,\n defaultLocale: options.defaultLocale,\n cdnEnabled: options.cdnEnabled,\n });\n logger.info(`Created ${project.name} (${project.id})`);\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError('Failed to create the project', error)\n );\n }\n });\n\n attachSharedFlags(\n projectCommand\n .command('status')\n .description('Check the status of a project setup job')\n .argument('<job-id>', 'Setup job ID')\n ).action(async (jobId, options) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const [status] = await api.checkJobStatus([jobId]);\n logger.info(status?.status ?? 'unknown');\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError(\n 'Failed to check the project setup status',\n error\n )\n );\n }\n });\n }\n\n protected setupApiKeyCommands(): void {\n const apiKeyCommand = this.program\n .command('api-key')\n .description('Manage API keys for the configured project');\n\n attachSharedFlags(\n apiKeyCommand\n .command('create')\n .description(\n 'Create a project API key with the requested permissions and print it once'\n )\n .requiredOption('--name <name>', 'Key name', parseApiKeyName)\n // Validated before any request; the server grants the requested set\n // all-or-nothing, so omitting permissions would delegate everything.\n .addOption(\n new Option('--permission <permissions...>', 'Permissions to grant')\n .choices(Object.values(ProjectApiKeyPermission))\n .makeOptionMandatory()\n )\n ).action(\n async (\n options: SharedFlags & {\n name: string;\n permission: ProjectApiKeyPermission[];\n }\n ) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const { apiKey } = await api.createProjectApiKey(settings.projectId, {\n name: options.name,\n permissions: options.permission,\n });\n // Raw stdout: the secret is shown once and never reaches the log file.\n process.stdout.write(`${apiKey.key}\\n`);\n } catch (error) {\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError('Failed to create the API key', error)\n );\n }\n }\n );\n }\n\n protected setupGitCommand(): void {\n const gitCommand = this.program\n .command('git')\n .description('Configure Git integrations for General Translation');\n\n gitCommand\n .command('setup')\n .description('Set up GT merge drivers for generated translation files')\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--dry-run', 'Print changes without writing files', false)\n .option(\n '--omit-config-ids',\n 'Persist omitConfigIds and remove generated config IDs'\n )\n .option(\n '--driver-command <command>',\n 'Command Git should use to invoke gt, e.g. \"pnpm exec gt\"'\n )\n .action(async (options: GitSetupOptions) => {\n displayHeader('Setting up GT Git merge drivers...');\n const settings = await generateSettings(options, undefined, {\n requireConfig: true,\n });\n const omitConfigIds = await this.resolveGitSetupOmitConfigIds(\n options,\n settings\n );\n const result = await setupGitMergeDrivers(settings, {\n dryRun: options.dryRun,\n omitConfigIds,\n driverCommand: options.driverCommand,\n });\n\n for (const line of result.addedAttributes) {\n logger.step(\n `${options.dryRun ? 'Would add' : 'Added'} ${chalk.cyan(\n line\n )} to ${chalk.cyan(result.gitattributesPath)}`\n );\n }\n if (result.addedAttributes.length === 0) {\n logger.info(`${chalk.cyan('.gitattributes')} is already configured.`);\n }\n\n for (const args of result.gitConfigCommands) {\n logger.step(\n `${options.dryRun ? 'Would run' : 'Configured'} ${chalk.cyan(\n `git config --local ${args.join(' ')}`\n )}`\n );\n }\n\n if (result.updatedConfig) {\n logger.step(\n `${options.dryRun ? 'Would persist' : 'Persisted'} ${chalk.cyan(\n 'omitConfigIds: true'\n )} in ${chalk.cyan(settings.config)}`\n );\n } else if (options.dryRun && !settings.omitConfigIds) {\n logger.info(\n `Run without ${chalk.cyan('--dry-run')} to be prompted to persist ${chalk.cyan(\n 'omitConfigIds: true'\n )}, or pass ${chalk.cyan('--omit-config-ids')}.`\n );\n }\n\n for (const warning of result.warnings) {\n logger.warn(chalk.yellow(warning));\n }\n\n logger.endCommand(\n options.dryRun\n ? 'Dry run complete.'\n : 'GT Git merge drivers configured.'\n );\n });\n\n gitCommand\n .command('merge-driver', { hidden: true })\n .addArgument(\n new Argument('<driver>', 'Merge driver name').choices([\n 'gt-lock',\n 'gtjson',\n ])\n )\n .argument('<base>', 'Common ancestor file')\n .argument('<ours>', 'Current branch file')\n .argument('<theirs>', 'Incoming branch file')\n .argument('[path]', 'Merged path')\n .action(\n (\n driver: MergeDriverName,\n base: string,\n ours: string,\n theirs: string\n ) => {\n const result = runMergeDriver(driver, base, ours, theirs);\n if (!result.ok) {\n logger.error(result.reason);\n exitSync(1);\n }\n }\n );\n }\n\n protected async resolveGitSetupOmitConfigIds(\n options: GitSetupOptions,\n settings: Settings\n ): Promise<boolean> {\n if (options.omitConfigIds) return true;\n // Already opted in: persist again so stale config IDs still get removed\n if (settings.omitConfigIds) return true;\n if (options.dryRun || !process.stdin.isTTY || !process.stdout.isTTY) {\n return false;\n }\n return promptConfirm({\n message:\n 'Also set omitConfigIds: true to reduce gt.config.json merge conflicts?',\n defaultValue: true,\n });\n }\n\n protected async handleSetupProject(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n await handleSetupProject(initOptions, settings, this.library);\n }\n\n protected async handleStage(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Update settings.stageTranslations to true\n settings.stageTranslations = true;\n await updateConfig(settings.config, {\n stageTranslations: true,\n });\n }\n await handleStage(initOptions, settings, this.library, true);\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleEnqueue(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleEnqueue(initOptions, settings, this.library);\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleDownload(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleDownload(initOptions, settings, this.library);\n }\n\n protected async handleTranslate(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Lottie translations finish asynchronously server-side (layout\n // refinement runs after the translation job completes), so the immediate\n // translate flow would try to download them before they're ready. Only\n // the stage + download flow supports them.\n if (settings.files?.resolvedPaths.lottie?.length) {\n return logErrorAndExit(lottieTranslateError);\n }\n const results = await handleStage(\n initOptions,\n settings,\n this.library,\n false\n );\n if (results) {\n await handleTranslate(\n initOptions,\n settings,\n results.fileVersionData,\n results.jobData,\n results.branchData,\n results.publishMap,\n results.inlineLibrary\n );\n }\n } else {\n await handleDownload(initOptions, settings, this.library);\n }\n // Only postprocess files downloaded in this run\n const include = getNeedsPostprocessing();\n if (include.size > 0) {\n await postProcessTranslations(settings, include);\n }\n // Split Mintlify language entries into $ref files to keep docs.json small\n await splitMintlifyLanguageRefs(settings);\n // Localize redirects for pages this run renamed or removed. Runs after the\n // split, which can rewrite $ref files such as redirects.json\n const orphanedFileNames = getOrphanedFileNames();\n if (orphanedFileNames) {\n const added = localizeMintlifyRedirects(settings, orphanedFileNames);\n if (added.length > 0) {\n logger.success(\n `Added ${added.length} localized redirect${added.length === 1 ? '' : 's'}`\n );\n }\n }\n clearOrphanedFileNames();\n // Mirror assets after translations are downloaded and locale dirs are populated\n await mirrorAssetsToLocales(settings);\n clearDownloaded();\n displayTranslateSummary();\n clearWarnings();\n }\n\n protected setupUploadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('upload')\n .description(\n 'Upload source files and translations to the General Translation platform'\n )\n ).action(async (initOptions: UploadOptions) => {\n displayHeader('Starting upload...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const options = { ...initOptions, ...settings };\n\n await this.handleUploadCommand(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupUserAuthCommands(): void {\n this.program\n .command('login')\n .description('Sign in to your General Translation account')\n .option(\n '--no-browser',\n 'Do not open a browser; show a sign-in URL to use on any device instead'\n )\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json'\n )\n .action(async (options: { browser: boolean; config?: string }) => {\n displayHeader('Signing in to General Translation...');\n try {\n // Tokens are bound to one API resource, so log in to the configured one.\n const baseUrl = (\n options.config\n ? loadConfig(withJsonExtension(options.config))\n : resolveConfig(process.cwd())?.config\n )?.baseUrl;\n await loginInteractively(\n typeof baseUrl === 'string' ? baseUrl : undefined,\n options.browser\n );\n logger.endCommand('You are now signed in.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign in failed', error));\n }\n });\n\n this.program\n .command('logout')\n .description('Sign out of your General Translation account')\n .action(async () => {\n try {\n await logout();\n logger.endCommand('Signed out successfully.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign out failed', error));\n }\n });\n\n this.program\n .command('whoami')\n .description('Show the signed-in General Translation account')\n .action(async () => {\n try {\n const user = await whoAmI();\n logger.message(user.email ?? user.name ?? user.sub);\n } catch (error) {\n logErrorAndExit(\n createUserAuthError('Could not load your account', error)\n );\n }\n });\n }\n\n protected setupInitCommand(): void {\n attachInitFlags(\n this.program\n .command('init')\n .description(\n 'Run the setup wizard to configure your project for General Translation. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: InitOptions) => this.handleInitWizard(options));\n }\n\n protected async handleInitWizard(options: InitOptions): Promise<void> {\n await runOnboarding('init', options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Running setup wizard...');\n\n const detected = await detectFramework();\n const reactDetected = detected.type === 'react' ? detected : undefined;\n if (options.framework && !reactDetected) {\n session.reject(\n '--framework applies only to projects detected as React applications'\n );\n }\n const configFilepath = setupConfigPath(options);\n const configured = getConfiguredFramework(\n readSetupConfig(configFilepath)\n );\n const configuredReact =\n configured !== 'mintlify' ? configured : undefined;\n // Explicit --defaults / --no-defaults also answer the Locadex gate.\n if (options.defaults !== undefined) session.defaults = options.defaults;\n const gateFramework = options.framework ?? configured ?? detected.name;\n if (gateFramework === 'mintlify' || gateFramework === 'next-app') {\n const useLocadex = await session.answer('--locadex', {\n explicit: options.locadex,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n gateFramework === 'mintlify'\n ? `Mintlify project detected. Would you like to connect to GitHub so that the Locadex AI Agent can translate your project automatically?`\n : `Next.js App Router detected. Would you like to connect to GitHub so that the Locadex AI Agent can set up your project automatically?`,\n defaultValue: false,\n }),\n });\n if (useLocadex) {\n session.assertResolved();\n const url = await setupLocadex(\n await generateSettings({ config: options.config }),\n { openBrowser: session.interactive }\n );\n session.emit({ type: 'handoff', url, reason: 'locadex' });\n logger.endCommand(\n 'Once installed, Locadex will open a PR to your repository. See the docs for more information: https://generaltranslation.com/docs/locadex'\n );\n return { outcome: 'needs_human_action', url };\n }\n } else if (options.locadex) {\n session.reject(\n '--locadex applies only to Mintlify and Next.js App Router projects'\n );\n }\n\n const shownFramework = reactDetected && {\n ...reactDetected,\n name: options.framework ?? configuredReact ?? reactDetected.name,\n };\n // Without --defaults, a noninteractive run uses no defaults.\n session.defaults =\n (await session.answer('--defaults', {\n explicit: options.defaults,\n fallback: false,\n ask: () =>\n promptConfirm({\n message: `Would you like to use the recommended General Translation defaults? ${chalk.dim(`(${describeDefaults(shownFramework)})`)}`,\n defaultValue: true,\n }),\n })) === true;\n\n const reactSetup = reactDetected\n ? await resolveReactSetup(\n session,\n options,\n reactDetected,\n configuredReact\n )\n : undefined;\n // flag > gt.config.json > detection, used for every later step.\n const framework =\n reactSetup?.framework ??\n options.framework ??\n configured ??\n detected.name;\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n saveFramework: Boolean(reactSetup || options.framework),\n reactSetup,\n keepAppSource: !reactSetup,\n });\n\n logger.endCommand(\n 'Done! Check out our docs for more information on how to use General Translation: https://generaltranslation.com/docs'\n );\n return { outcome: 'success' };\n });\n }\n\n protected setupConfigureCommand(): void {\n attachConfigureFlags(\n this.program\n .command('configure')\n .description(\n 'Configure your project for General Translation. This will create a gt.config.json file in your codebase. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: ConfigureOptions) =>\n this.handleConfigureCommand(options)\n );\n }\n\n protected async handleConfigureCommand(\n options: ConfigureOptions,\n command: string = 'configure'\n ): Promise<void> {\n await runOnboarding(command, options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Configuring project...');\n\n logger.info(\n 'Welcome! This tool will help you configure your gt.config.json file. See the docs: https://generaltranslation.com/docs/cli/reference/config for more information.'\n );\n\n // Configure only offers the defaults when asked with --defaults.\n session.defaults = options.defaults ?? false;\n const detected = await detectFramework();\n const configFilepath = setupConfigPath(options);\n // Detection only picks env names here; it is not saved.\n const framework =\n getConfiguredFramework(readSetupConfig(configFilepath)) ??\n detected.name;\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n });\n\n logger.endCommand(\n 'Done! Make sure you have an API key and project ID to use General Translation. Get them on the dashboard: https://generaltranslation.com/dashboard'\n );\n return { outcome: 'success' };\n });\n }\n\n protected async handleUploadCommand(\n settings: Settings & UploadOptions\n ): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n // Process all file types at once with a single call\n await upload(settings);\n }\n\n /** Describes installed runtimes without changing historical package lookup. */\n protected getInlineRuntimeSetup(\n packageJson: Record<string, unknown>,\n ranReactSetup: boolean = false\n ): InlineRuntimeSetup {\n return {\n hasOtherInlineRuntime: INLINE_LIBRARIES.some(\n (lib) =>\n lib !== Libraries.GT_VUE && isPackageInstalled(lib, packageJson)\n ),\n hasVueRuntime: manifestDirectlyDeclaresGTVue(packageJson),\n ranReactSetup,\n };\n }\n\n /** Returns whether any inline runtime is installed for setup. */\n protected isInlineRuntimeInstalled(\n packageJson: Record<string, unknown>\n ): boolean {\n const { hasOtherInlineRuntime, hasVueRuntime } =\n this.getInlineRuntimeSetup(packageJson);\n return hasOtherInlineRuntime || hasVueRuntime;\n }\n\n /** Returns whether every installed runtime can consume CDN translations. */\n protected supportsCDNStorage(runtimeSetup: InlineRuntimeSetup): boolean {\n return !runtimeSetup.hasVueRuntime;\n }\n\n /** Returns whether setup should generate a local runtime loader. */\n protected shouldGenerateLocalTranslationLoader(\n buildToolOwnsLoader: boolean,\n runtimeSetup: InlineRuntimeSetup\n ): boolean {\n if (buildToolOwnsLoader) return false;\n if (!runtimeSetup.hasVueRuntime) return true;\n return runtimeSetup.hasOtherInlineRuntime || runtimeSetup.ranReactSetup;\n }\n\n /** Returns framework guidance after selecting local translation storage. */\n protected getLocalTranslationGuidance({\n generatedLoader,\n runtimeSetup,\n translationsDir,\n }: LocalTranslationGuidanceOptions): string | undefined {\n const guidance: string[] = [];\n if (generatedLoader) {\n guidance.push(`Created ${chalk.cyan('loadTranslations.js')} file for local translations.\nMake sure to add this function to your app configuration.\nSee https://generaltranslation.com/en/docs/next/guides/local-tx`);\n }\n if (runtimeSetup.hasVueRuntime) {\n guidance.push(`GT will write local translation files to ${translationsDir}.\nConfigure createGT({ loadTranslations }) to load files from that directory.\nSee https://www.npmjs.com/package/gt-vue`);\n }\n return guidance.length > 0 ? guidance.join('\\n') : undefined;\n }\n\n /**\n * Resolves every configuration answer and validates the resulting config,\n * checks the project and signs in before the first change, then applies\n * the React setup, gt.config.json, installs and development credentials.\n */\n protected async handleInitCommand(\n session: OnboardingSession,\n options: ConfigureOptions,\n setup: {\n /** Chosen once by the entry point from the detected framework. */\n configFilepath: string;\n /** Resolved framework; drives storage, env names and build-tool setup. */\n framework?: SupportedFrameworks;\n /** Write the framework even when no build-tool setup saves it. */\n saveFramework?: boolean;\n reactSetup?: ReactSetupPlan;\n /** Init without the React setup never changes application source. */\n keepAppSource?: boolean;\n }\n ): Promise<void> {\n const { configFilepath, reactSetup } = setup;\n const buildTool = getBuildToolSetup(setup.framework);\n const cwd = process.cwd();\n const existingConfig = readSetupConfig(configFilepath);\n const { defaultLocale, locales } = await getDesiredLocales(\n session,\n existingConfig,\n options\n );\n\n const packageJson =\n reactSetup?.packageJson ?? (await searchForPackageJson());\n const runtimeSetup: InlineRuntimeSetup = packageJson\n ? this.getInlineRuntimeSetup(packageJson, Boolean(reactSetup))\n : {\n hasOtherInlineRuntime: false,\n hasVueRuntime: false,\n ranReactSetup: false,\n };\n const isUsingGT =\n runtimeSetup.ranReactSetup ||\n runtimeSetup.hasOtherInlineRuntime ||\n runtimeSetup.hasVueRuntime;\n const supportsCDN = this.supportsCDNStorage(runtimeSetup);\n const existingFiles = asRecord(existingConfig.files) ?? {};\n const existingGtOutput = asRecord(existingFiles.gt)?.output;\n const configuredOutput =\n typeof existingGtOutput === 'string' ? existingGtOutput : undefined;\n const configuredStorage = configuredOutput\n ? 'local'\n : existingConfig.publish === true\n ? 'cdn'\n : undefined;\n\n if (isUsingGT && !supportsCDN && options.storage === 'cdn') {\n session.reject(\n 'gt-vue cannot load translations from the CDN; use --storage local'\n );\n }\n // Where GT translations are stored\n const storage = !isUsingGT\n ? undefined\n : !supportsCDN\n ? 'local'\n : await session.answer<'local' | 'cdn'>('--storage', {\n explicit: options.storage,\n configured: configuredStorage,\n recommended: 'local',\n ask: () =>\n promptSelect<'local' | 'cdn'>({\n message: `Would you like to save translation files locally or use the General Translation CDN to store them?`,\n options: [\n { value: 'local', label: 'Save locally' },\n { value: 'cdn', label: 'Use CDN' },\n ],\n defaultValue: 'local',\n }),\n });\n\n const defaultTranslationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n const outputMatch = configuredOutput?.match(\n /^(?:(.+)[\\\\/])?\\[locale\\]\\.json$/\n );\n const configuredTranslationsDir = outputMatch\n ? (outputMatch[1] ?? '.')\n : undefined;\n const translationsDir =\n storage === 'local'\n ? await session.answer('--translations-dir', {\n explicit: options.translationsDir?.trim() || undefined,\n configured: configuredTranslationsDir,\n recommended: defaultTranslationsDir,\n ask: async () =>\n (\n await promptText({\n message:\n 'What is the path to the directory where you would like to store your translation files?',\n defaultValue: defaultTranslationsDir,\n })\n ).trim() || defaultTranslationsDir,\n })\n : undefined;\n\n const filePatterns = parseFilePatterns(session, options.filePatterns);\n const selectedFormats = options.fileFormats?.filter(\n (format): format is SetupFileFormat => format !== 'none'\n );\n if (\n options.fileFormats?.includes('none') &&\n (selectedFormats?.length ?? 0) > 0\n ) {\n session.reject('--file-formats none cannot be combined with formats');\n }\n const configuredFormats = SETUP_FILE_FORMATS.filter(\n (format) => format in existingFiles\n );\n // Formats setup does not offer stay as configured and count as files.\n const otherFormats = SUPPORTED_FILE_EXTENSIONS.filter(\n (format) =>\n format in existingFiles &&\n !(SETUP_FILE_FORMATS as readonly string[]).includes(format)\n );\n const hasOtherFormats = otherFormats.length > 0;\n if (options.fileFormats && hasOtherFormats) {\n const kept = otherFormats.map((format) => `files.${format}`).join(', ');\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `${kept} stays in ${configFilepath}`,\n why: '--file-formats only changes the formats setup offers',\n fix: `Remove ${kept} from ${configFilepath} to stop translating those files`,\n })\n );\n }\n const fileFormats = await session.answer<SetupFileFormat[]>(\n '--file-formats',\n {\n explicit:\n selectedFormats ??\n (filePatterns.size > 0 ? [...filePatterns.keys()] : undefined),\n configured:\n configuredFormats.length > 0 || hasOtherFormats\n ? configuredFormats\n : undefined,\n // GT projects need no other files; others must choose a format.\n recommended: isUsingGT ? [] : undefined,\n ask: () =>\n promptMultiSelect({\n message: !isUsingGT\n ? 'What is the format of your language resource files? Select as many as applicable.\\nAdditionally, you can translate any other files you have in your project.'\n : `Do you have any additional files in this project to translate? For example, Markdown files for docs. ${chalk.dim(\n '(To continue without selecting press Enter)'\n )}`,\n options: SETUP_FILE_FORMATS.map((format) => ({\n value: format,\n label: FILE_EXT_TO_EXT_LABEL[format],\n })),\n required: !isUsingGT,\n }),\n }\n );\n if (\n fileFormats &&\n fileFormats.length === 0 &&\n !isUsingGT &&\n !hasOtherFormats\n ) {\n session.reject(\n 'No GT runtime is installed, so select at least one file format to translate'\n );\n }\n for (const format of filePatterns.keys()) {\n if (fileFormats && !fileFormats.includes(format)) {\n session.reject(\n `--file-patterns ${format}= needs ${format} in --file-formats`\n );\n }\n }\n\n const files: FilesOptions = {};\n for (const fileExtension of fileFormats ?? []) {\n const existingFormat = asRecord(existingFiles[fileExtension]);\n const configuredInclude = Array.isArray(existingFormat?.include)\n ? (existingFormat.include as string[])\n : undefined;\n const include = await session.answer(\n `--file-patterns ${fileExtension}=<glob>`,\n {\n explicit: filePatterns.get(fileExtension),\n configured: configuredInclude,\n recommended: [`./**/[locale]/*.${fileExtension}`],\n ask: async () =>\n parseGlobPatterns(\n await promptGlobPatterns({\n label: FILE_EXT_TO_EXT_LABEL[fileExtension],\n message: `${chalk.cyan(FILE_EXT_TO_EXT_LABEL[fileExtension])}: Enter a space-separated list of glob patterns matching the location of the ${FILE_EXT_TO_EXT_LABEL[fileExtension]} files you would like to translate.\\nMake sure to include [locale] in the patterns.\\nSee https://generaltranslation.com/docs/cli/reference/config#include for more information.`,\n defaultValue: `./**/[locale]/*.${fileExtension}`,\n validate: (value) =>\n parseGlobPatterns(value)\n .map(validateSetupPattern)\n .find((problem) => problem !== true) ?? true,\n })\n ),\n }\n );\n // Configured patterns stay untouched; new ones keep other entry options.\n if (include && include !== configuredInclude) {\n files[fileExtension] = { ...existingFormat, include };\n }\n }\n if (translationsDir && translationsDir !== configuredTranslationsDir) {\n files.gt = { output: path.join(translationsDir, `[locale].json`) };\n }\n\n const envFramework =\n setup.framework ?? getConfiguredFramework(existingConfig);\n // The effective project: an explicit ID replaces a configured one. The\n // framework's runtime project outranks a stale generic GT_PROJECT_ID.\n const projectId =\n options.projectId ||\n (typeof existingConfig.projectId === 'string'\n ? existingConfig.projectId\n : undefined) ||\n process.env[getDevelopmentEnvNames(envFramework).projectId];\n const configUpdate: SetupConfigUpdate = {\n defaultLocale,\n locales,\n src: options.src,\n files: Object.keys(files).length > 0 ? files : undefined,\n framework:\n (setup.saveFramework && setup.framework) || buildTool?.framework,\n publish: storage === 'cdn',\n // Selecting local storage drops stale CDN intent; a config that\n // already combines local files with publishing keeps it.\n clearPublish:\n storage === 'local' &&\n (options.storage === 'local' ||\n configuredStorage !== 'local' ||\n !supportsCDN),\n // An explicit switch to the CDN stops later runs inferring local files.\n clearGtOutput: storage === 'cdn' && configuredOutput !== undefined,\n // An explicit format list replaces the configured selection.\n removeFiles: selectedFormats\n ? configuredFormats.filter(\n (format) => !selectedFormats.includes(format)\n )\n : undefined,\n };\n session.assertResolved();\n\n // Validate what will be written, and use it for every later step.\n const { projectId: _writtenProjectId, ...effectiveConfig } =\n mergeSetupConfig(existingConfig, configUpdate);\n const settings = await generateSettings(\n { config: configFilepath, ...(projectId && { projectId }) },\n cwd,\n { resolvedConfig: effectiveConfig }\n );\n // Runtime credentials only count for the project this setup uses; the\n // framework's project variable is the one paired with its dev key.\n const runtimeProjectId =\n process.env[getDevelopmentEnvNames(envFramework).projectId] ??\n resolveProjectId();\n const runtimeProjectMatches =\n runtimeProjectId === undefined || runtimeProjectId === settings.projectId;\n const credentialsSet =\n runtimeProjectMatches && areCredentialsSet(settings, envFramework);\n const credentialsOption =\n (storage === 'local' && buildTool?.devCredentialsOption) ||\n '--dev-credentials';\n // Creating credentials talks to GT as the signed-in user unless an API\n // key is set. A development key in .env.local never stands in. An\n // obsolete stored login counts as signed out, so signing in replaces it.\n const canAuthenticate = async () =>\n Boolean(settings.apiKey) ||\n (await hasLogin({ baseUrl: settings.baseUrl }).catch((error) => {\n if (\n error instanceof UserAuthError &&\n error.code === 'obsolete_credentials'\n )\n return false;\n throw error;\n }));\n const provision =\n !credentialsSet &&\n (credentialsOption === '--live-translations'\n ? await session.answer('--live-translations', {\n explicit: options.liveTranslations ?? options.devCredentials,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n 'Would you like to set up live development translations? This requires signing in or an API key.',\n defaultValue: false,\n }),\n })\n : await session.answer('--dev-credentials or --no-dev-credentials', {\n explicit: options.devCredentials,\n // Creating a key is never a default, so --defaults leaves this open.\n // The prompt names the sign-in so its Yes default is informed.\n ask: async () =>\n promptConfirm({\n message: (await canAuthenticate())\n ? 'Would you like to set up a project ID and hot-reload key in .env.local?'\n : 'Would you like to sign in to General Translation and set up a project ID and hot-reload key in .env.local?',\n defaultValue: true,\n }),\n })) === true;\n if (!runtimeProjectMatches && !provision) {\n session.reject(\n `The runtime credentials in the environment belong to project ${runtimeProjectId}, not ${settings.projectId}; pass --dev-credentials to replace them in .env.local`\n );\n }\n // An explicit ID is saved to gt.config.json when it replaces a\n // configured one or no new credentials will record it in .env.local.\n if (options.projectId && (existingConfig.projectId || !provision)) {\n configUpdate.projectId = options.projectId;\n }\n if (provision) {\n checkDevelopmentProjectInputs(\n session,\n settings,\n options,\n options.projectId\n ? '--project-id'\n : // An empty configured ID falls through to the environment.\n typeof existingConfig.projectId === 'string' &&\n existingConfig.projectId\n ? configFilepath\n : 'the environment'\n );\n await withCredentialsError(() =>\n inspectCredentialsEnvFile(cwd, { framework: envFramework })\n );\n }\n\n if (reactSetup && buildTool) await buildTool.preflight(cwd);\n const installGT =\n packageJson !== null &&\n !isPackageInstalled('gt', packageJson, true, true) &&\n !buildTool?.skipsGTInstall(isUsingGT);\n const packageManager =\n reactSetup?.install || installGT\n ? await resolvePackageManager(session, options.packageManager)\n : undefined;\n\n session.assertResolved();\n\n if (provision && !(await canAuthenticate())) {\n await signInForSetup(session, settings.baseUrl);\n }\n const project = provision\n ? await withCredentialsError(() =>\n resolveDevelopmentProject(session, settings, options, cwd)\n )\n : undefined;\n session.assertResolved();\n\n // ----- Changes start here ----- //\n const resolvedLocales = locales as string[];\n\n if (reactSetup) {\n logger.info(`${chalk.yellow('[EXPERIMENTAL]')} Configuring project...`);\n if (reactSetup.install && packageManager) {\n await installWithProgress(\n session,\n reactSetup.install,\n packageManager,\n false\n );\n }\n await executeReactSetup(session, reactSetup, options);\n logger.endCommand(\n `Done! Since this wizard is experimental, please review the changes and make modifications as needed.\n\\nNext step: start internationalizing! See the docs for more information: ${buildTool?.docsUrl ?? REACT_QUICKSTART_URL}`\n );\n logger.startCommand('Setting up project config...');\n }\n\n const reportManualAction = ({ whatHappened, fix }: ManualAction) => {\n session.humanActions.push(fix);\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened,\n fix,\n })\n );\n };\n const reportSetupResult = ({ steps, manualActions }: SetupResult) => {\n for (const step of steps) session.step(step);\n manualActions.forEach(reportManualAction);\n };\n const translationFilesError = (error: unknown) =>\n new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not create the translation files in ${translationsDir}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Choose another --translations-dir or fix the path, then rerun the command',\n })\n );\n const buildToolContext = {\n appDirectory: cwd,\n configFilepath,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n previousTranslationsDir: configuredTranslationsDir,\n };\n\n if (storage === 'local' && translationsDir) {\n if (buildTool && !reactSetup) {\n reportSetupResult(\n await buildTool\n .syncLoader({\n ...buildToolContext,\n translationsDir,\n keepAppSource: setup.keepAppSource,\n })\n .catch((error: unknown) => {\n throw translationFilesError(error);\n })\n );\n }\n const generatedLoader = this.shouldGenerateLocalTranslationLoader(\n buildTool?.ownsLoader ?? false,\n runtimeSetup\n );\n const loader = generatedLoader\n ? await createLoadTranslationsFile({\n appDirectory: cwd,\n translationsDir,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n previousTranslationsDir: configuredTranslationsDir,\n }).catch((error: unknown) => {\n throw translationFilesError(error);\n })\n : undefined;\n if (loader === 'created' || loader === 'updated') {\n session.step(`${loader} loadTranslations.js`);\n }\n // A loader left unchanged may not read the newly chosen directory.\n if (\n loader === 'custom' &&\n translationsDir !== configuredTranslationsDir\n ) {\n const loaderFile = path.relative(\n cwd,\n findLoadTranslationsFiles(cwd)[0] ?? 'loadTranslations.js'\n );\n reportManualAction({\n whatHappened: `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`,\n fix: `Update your custom ${loaderFile} to load translations from ${translationsDir}`,\n });\n }\n const guidance = this.getLocalTranslationGuidance({\n generatedLoader: generatedLoader && loader !== 'custom',\n runtimeSetup,\n translationsDir,\n });\n if (guidance) logger.message(guidance);\n } else if (\n storage === 'cdn' &&\n buildTool &&\n !reactSetup &&\n configuredTranslationsDir !== undefined\n ) {\n // Only the application setup rewrites the initializer; a loader passed\n // to it takes precedence over CDN loading.\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,\n fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`,\n });\n } else if (\n storage === 'cdn' &&\n !buildTool &&\n configuredTranslationsDir !== undefined\n ) {\n // gt-next uses a loadTranslations file whenever one exists, and a\n // loader passed to GTProvider takes precedence over the CDN. Name every\n // one: deleting only the first makes gt-next fall back to the next.\n const loaders = findLoadTranslationsFiles(cwd).map((loader) =>\n path.relative(cwd, loader)\n );\n if (loaders.length > 0) {\n const loaderFiles = loaders.join(', ');\n const [them, loads] =\n loaders.length === 1 ? ['it', 'loads'] : ['them', 'load'];\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${loaderFiles} still ${loads} them from ${configuredTranslationsDir}`,\n fix: `Delete ${loaderFiles}, and remove ${them} from your GT setup if you pass ${them} there, so translations load from the CDN`,\n });\n }\n }\n\n const configChange = await applySetupConfig(configFilepath, configUpdate);\n if (configChange !== 'unchanged') {\n session.step(`${configChange} ${configFilepath}`);\n }\n\n logger.success(\n `Edit ${chalk.cyan(\n configFilepath\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n if (reactSetup && buildTool) {\n reportSetupResult(await buildTool.apply(buildToolContext));\n }\n\n if (installGT && packageManager) {\n await installWithProgress(session, 'gt', packageManager, true);\n }\n\n if (project) {\n await withCredentialsError(() =>\n provisionDevelopmentCredentials(\n session,\n project,\n settings,\n envFramework,\n cwd\n )\n );\n logger.message(productionRuntimeKeyGuidance(settings.dashboardUrl));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,MAAM,oCAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,SAAS,0BACP,cACA,OACQ;AACR,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV;EACA,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,uBAAuB,wBAAwB;CACnD,cAAc;CACd,KAAK;CACN,CAAC;AAEF,SAAS,gBAAgB,OAAuB;CAC9C,MAAM,OAAO,MAAM,MAAM;AACzB,KAAI,CAAC,KAAM,OAAM,IAAI,qBAAqB,qBAAqB;AAC/D,QAAO;;;AAIT,eAAe,qBAAwB,KAAmC;AACxE,KAAI;AACF,SAAO,MAAM,KAAK;UACX,OAAO;AACd,MAAI,iBAAiB,gBAAiB,OAAM;AAC5C,QAAM,IAAI,MACR,iBAAiB,gBACb,MAAM,UACN,0BACE,gDACA,MACD,CACN;;;AA8BL,IAAa,UAAb,MAAqB;CACnB;CACA;CACA;CAEA,YACE,SACA,SACA,mBACA;AACA,OAAK,UAAU;AACf,OAAK,UAAU;AACf,OAAK,oBAAoB,qBAAqB,EAAE;AAEhD,OAAK,QAAQ,OACX,wBACA,yDACD;AACD,OAAK,QAAQ,OACX,uCACA,sDACD;AACD,OAAK,QAAQ,OACX,eACA,oEACD;AAOD,OAAK,QAAQ,KAAK,cAAc,aAAa,kBAAkB;AAC7D,UAAO,iBACL,cAAc,QAA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IN,MAAM,eAAe,MAAM,iBAAiB,gBAAgB,aAAa;AACzE,MAAI,iBAAiB,YACnB,SAAQ,KAAK,GAAG,aAAa,GAAG,iBAAiB;AAGnD,SAAO,QACL,QAAQ,MAAM,KACZ,eACD,CAAC,sGACH;AAED,MAAI,cAAc,UAChB,mBAAkB,MAAM,UAAU,MAAM,iBAAiB,CAAC;AAG5D,MAAI,aAAa,eACf,OAAM,oBAAoB,SAAS,MAAM,gBAAgB,KAAK;AAGhE,MAAI,SAAS;AACX,SAAM,2BACJ,gCACE,SACA,SACA,UACA,cACA,IACD,CACF;AACD,UAAO,QAAQ,6BAA6B,SAAS,aAAa,CAAC"}
|
package/dist/cli/commands/api.js
CHANGED
|
@@ -61,6 +61,66 @@ function readInput(input, dependencies) {
|
|
|
61
61
|
}), dependencies);
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
+
const specPaths = openApiSpec.paths;
|
|
65
|
+
function listOperations() {
|
|
66
|
+
return Object.entries(specPaths).flatMap(([specPath, operations]) => Object.entries(operations).map(([method, operation]) => `${method.toUpperCase()}\t${specPath}\t${operation.operationId ?? ""}\t${operation.summary ?? ""}\n`)).join("");
|
|
67
|
+
}
|
|
68
|
+
function lookupRef(ref) {
|
|
69
|
+
return ref.slice(2).split("/").reduce((node, key) => node?.[key], openApiSpec);
|
|
70
|
+
}
|
|
71
|
+
function collectRefs(value, refs) {
|
|
72
|
+
if (!value || typeof value !== "object") return;
|
|
73
|
+
for (const [key, child] of Object.entries(value)) if (key === "$ref" && typeof child === "string") refs.add(child);
|
|
74
|
+
else collectRefs(child, refs);
|
|
75
|
+
}
|
|
76
|
+
function resolveRefs(value, expanding = []) {
|
|
77
|
+
if (Array.isArray(value)) return value.map((item) => resolveRefs(item, expanding));
|
|
78
|
+
if (!value || typeof value !== "object") return value;
|
|
79
|
+
const { $ref, ...siblings } = value;
|
|
80
|
+
if (typeof $ref === "string" && $ref.startsWith("#/")) {
|
|
81
|
+
const target = lookupRef($ref);
|
|
82
|
+
if (!expanding.includes($ref) && target && typeof target === "object") return resolveRefs({
|
|
83
|
+
...target,
|
|
84
|
+
...siblings
|
|
85
|
+
}, [...expanding, $ref]);
|
|
86
|
+
return value;
|
|
87
|
+
}
|
|
88
|
+
return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, resolveRefs(child, expanding)]));
|
|
89
|
+
}
|
|
90
|
+
function specFragment(operations) {
|
|
91
|
+
const paths = resolveRefs(operations);
|
|
92
|
+
const components = {};
|
|
93
|
+
const addComponent = (type, name, definition) => {
|
|
94
|
+
components[type] = {
|
|
95
|
+
...components[type],
|
|
96
|
+
[name]: definition
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
const pending = /* @__PURE__ */ new Set();
|
|
100
|
+
collectRefs(paths, pending);
|
|
101
|
+
const added = /* @__PURE__ */ new Set();
|
|
102
|
+
for (const ref of pending) {
|
|
103
|
+
const [root, type, name] = ref.slice(2).split("/");
|
|
104
|
+
if (added.has(ref) || root !== "components" || !type || !name) continue;
|
|
105
|
+
added.add(ref);
|
|
106
|
+
const definition = lookupRef(ref);
|
|
107
|
+
addComponent(type, name, definition);
|
|
108
|
+
collectRefs(definition, pending);
|
|
109
|
+
}
|
|
110
|
+
const securitySchemes = openApiSpec.components.securitySchemes;
|
|
111
|
+
for (const operation of Object.values(operations).flatMap(Object.values)) for (const name of (operation.security ?? []).flatMap(Object.keys)) addComponent("securitySchemes", name, securitySchemes[name]);
|
|
112
|
+
return Object.keys(components).length ? {
|
|
113
|
+
paths,
|
|
114
|
+
components
|
|
115
|
+
} : { paths };
|
|
116
|
+
}
|
|
117
|
+
function findOperations(endpoint) {
|
|
118
|
+
const byOperationId = Object.entries(specPaths).flatMap(([specPath, operations]) => Object.entries(operations).filter(([, operation]) => operation.operationId === endpoint).map(([method, operation]) => [specPath, { [method]: operation }]));
|
|
119
|
+
if (byOperationId.length) return Object.fromEntries(byOperationId);
|
|
120
|
+
const requestPath = `/${endpoint.replace(/^\//, "").split("?")[0]}`;
|
|
121
|
+
if (specPaths[requestPath]) return { [requestPath]: specPaths[requestPath] };
|
|
122
|
+
return Object.fromEntries(Object.entries(specPaths).filter(([specPath]) => new RegExp(`^${specPath.split(/\{[^}]+\}/).map((literal) => literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^/]+")}$`).test(requestPath)));
|
|
123
|
+
}
|
|
64
124
|
function writeResponseMetadata(response, writeStdout) {
|
|
65
125
|
writeStdout(`HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}\n`);
|
|
66
126
|
response.headers.forEach((value, name) => {
|
|
@@ -94,15 +154,31 @@ async function handleApiCommand(endpoint, options, dependencies = {}) {
|
|
|
94
154
|
});
|
|
95
155
|
const writeStdout = dependencies.writeStdout ?? ((output) => process.stdout.write(output));
|
|
96
156
|
const writeStderr = dependencies.writeStderr ?? ((output) => process.stderr.write(output));
|
|
157
|
+
if (options.list) {
|
|
158
|
+
writeStdout(listOperations());
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
97
161
|
if (options.spec) {
|
|
98
|
-
|
|
162
|
+
if (!endpoint) {
|
|
163
|
+
writeStdout(`${JSON.stringify(openApiSpec, null, 2)}\n`);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const operations = findOperations(endpoint);
|
|
167
|
+
if (!Object.keys(operations).length) fail(createDiagnosticMessage$1({
|
|
168
|
+
source: "gt",
|
|
169
|
+
severity: "Error",
|
|
170
|
+
whatHappened: "No API operation matches the endpoint",
|
|
171
|
+
details: endpoint,
|
|
172
|
+
fix: "Run `gt api --list` to see the available endpoints and operation IDs"
|
|
173
|
+
}), dependencies);
|
|
174
|
+
writeStdout(`${JSON.stringify(specFragment(operations), null, 2)}\n`);
|
|
99
175
|
return;
|
|
100
176
|
}
|
|
101
177
|
if (!endpoint) fail(createDiagnosticMessage$1({
|
|
102
178
|
source: "gt",
|
|
103
179
|
severity: "Error",
|
|
104
180
|
whatHappened: "No API endpoint was provided",
|
|
105
|
-
fix: "Pass an endpoint or
|
|
181
|
+
fix: "Pass an endpoint, run `gt api --list` to see the available endpoints, or run `gt api --spec <endpoint>` to inspect one"
|
|
106
182
|
}), dependencies);
|
|
107
183
|
const method = parseMethod(options.method, dependencies);
|
|
108
184
|
const config = options.config ? loadConfig(withJsonExtension(options.config)) : resolveConfig(process.cwd())?.config ?? {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","names":["createDiagnosticMessage","formatDiagnosticErrorDetails"],"sources":["../../../src/cli/commands/api.ts"],"sourcesContent":["import fs from 'node:fs';\nimport {\n createApiClient,\n type ApiClientConfig,\n type Client,\n} from 'generaltranslation/api';\nimport openApiSpec from 'generaltranslation/api/openapi.json' with { type: 'json' };\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { defaultBaseUrl } from 'generaltranslation/internal';\nimport { createUserTokenProvider } from '../../auth/oauth.js';\nimport { resolveConfig } from '../../config/resolveConfig.js';\nimport { exitSync } from '../../console/logging.js';\nimport { loadConfig, withJsonExtension } from '../../fs/config/loadConfig.js';\nimport { resolveProjectId } from '../../fs/utils.js';\nimport type { SharedFlags } from '../../types/index.js';\n\nexport type ApiCommandOptions = SharedFlags & {\n header?: string[];\n include?: boolean;\n input?: string;\n method: string;\n spec?: boolean;\n};\n\ntype ApiCommandDependencies = {\n exit?: (code: number) => never;\n fetch?: ApiClientConfig['fetch'];\n writeStderr?: (output: string) => void;\n writeStdout?: (output: string | Uint8Array) => void;\n};\n\ntype ApiRequestOptions = Parameters<Client['request']>[0];\n\nconst STANDARD_HTTP_METHODS = new Set([\n 'GET',\n 'HEAD',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n]);\n\nfunction fail(\n diagnostic: string,\n {\n exit = exitSync,\n writeStderr = (output) => process.stderr.write(output),\n }: ApiCommandDependencies\n): never {\n writeStderr(`${diagnostic}\\n`);\n return exit(1);\n}\n\nfunction parseMethod(\n value: string,\n dependencies: ApiCommandDependencies\n): ApiRequestOptions['method'] {\n const method = value.toUpperCase();\n if (!STANDARD_HTTP_METHODS.has(method)) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request method is invalid',\n details: value,\n fix: `Use one of ${[...STANDARD_HTTP_METHODS].join(', ')}`,\n }),\n dependencies\n );\n }\n // The set validation narrows Commander input to the generated HTTP method union.\n return method as ApiRequestOptions['method'];\n}\n\nfunction parseHeaders(\n values: string[],\n dependencies: ApiCommandDependencies\n): Headers {\n const headers = new Headers();\n for (const header of values) {\n const separator = header.indexOf(':');\n if (separator < 1) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request header is invalid',\n details: header,\n fix: 'Pass headers as `--header \"Key: Value\"`',\n }),\n dependencies\n );\n }\n headers.append(\n header.slice(0, separator).trim(),\n header.slice(separator + 1).trim()\n );\n }\n return headers;\n}\n\nfunction readInput(\n input: string,\n dependencies: ApiCommandDependencies\n): string {\n try {\n return fs.readFileSync(input === '-' ? 0 : input, 'utf8');\n } catch (error) {\n return fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request body could not be read',\n fix:\n input === '-'\n ? 'Pipe a request body to standard input or remove `--input -`'\n : 'Check the `--input` file path and permissions',\n details: formatDiagnosticErrorDetails(error),\n }),\n dependencies\n );\n }\n}\n\nfunction writeResponseMetadata(\n response: Response,\n writeStdout: (output: string | Uint8Array) => void\n): void {\n writeStdout(\n `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}\\n`\n );\n response.headers.forEach((value, name) => {\n writeStdout(`${name}: ${value}\\n`);\n });\n writeStdout('\\n');\n}\n\nfunction resolveApiProjectId(\n config: Record<string, unknown>,\n flagProjectId: string | undefined,\n dependencies: ApiCommandDependencies\n): string | undefined {\n const configProjectId =\n typeof config.projectId === 'string' ? config.projectId : undefined;\n const environmentProjectId = resolveProjectId();\n\n if (configProjectId && flagProjectId && configProjectId !== flagProjectId) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The project IDs do not match',\n details: [\n `Configuration: ${configProjectId}`,\n `--project-id: ${flagProjectId}`,\n ],\n fix: 'Use the same project ID in all configurations',\n }),\n dependencies\n );\n }\n\n if (\n configProjectId &&\n environmentProjectId &&\n configProjectId !== environmentProjectId\n ) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The project IDs do not match',\n details: [\n `Configuration: ${configProjectId}`,\n `Environment: ${environmentProjectId}`,\n ],\n fix: 'Use the same project ID in all configurations',\n }),\n dependencies\n );\n }\n\n return flagProjectId ?? configProjectId ?? environmentProjectId;\n}\n\nexport async function handleApiCommand(\n endpoint: string | undefined,\n options: ApiCommandOptions,\n dependencies: ApiCommandDependencies = {}\n): Promise<void> {\n if (!dependencies.writeStdout) {\n process.stdout.once('error', (error: NodeJS.ErrnoException) => {\n if (error.code === 'EPIPE') process.exit(0);\n throw error;\n });\n }\n const writeStdout =\n dependencies.writeStdout ?? ((output) => process.stdout.write(output));\n const writeStderr =\n dependencies.writeStderr ?? ((output) => process.stderr.write(output));\n\n if (options.spec) {\n writeStdout(`${JSON.stringify(openApiSpec, null, 2)}\\n`);\n return;\n }\n\n if (!endpoint) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No API endpoint was provided',\n fix: 'Pass an endpoint or use `gt api --spec` to inspect the OpenAPI specification',\n }),\n dependencies\n );\n }\n\n const method = parseMethod(options.method, dependencies);\n const config = options.config\n ? loadConfig(withJsonExtension(options.config))\n : (resolveConfig(process.cwd())?.config ?? {});\n const baseUrl =\n typeof config.baseUrl === 'string' ? config.baseUrl : defaultBaseUrl;\n const client = createApiClient({\n apiKey: options.apiKey ?? process.env.GT_API_KEY,\n userTokenProvider: createUserTokenProvider({ baseUrl }),\n baseUrl,\n fetch: dependencies.fetch,\n projectId: resolveApiProjectId(config, options.projectId, dependencies),\n retryPolicy: 'none',\n });\n const normalizedEndpoint = endpoint.startsWith('/')\n ? endpoint\n : `/${endpoint}`;\n const headers = parseHeaders(options.header ?? [], dependencies);\n const body = options.input\n ? readInput(options.input, dependencies)\n : undefined;\n let rawResponse: Response | undefined;\n\n client.interceptors.response.use((response) => {\n // Keep a clone because the generated client consumes non-2xx bodies.\n rawResponse = response.clone();\n return response;\n });\n\n const result = await client\n .request({\n body,\n bodySerializer: () => body,\n headers,\n method,\n parseAs: 'stream',\n throwOnError: false,\n url: normalizedEndpoint,\n })\n .catch((error) =>\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request failed before a response was received',\n details: formatDiagnosticErrorDetails(error),\n }),\n dependencies\n )\n );\n\n if (!rawResponse) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request did not return a response',\n details: formatDiagnosticErrorDetails(result?.error),\n }),\n dependencies\n );\n }\n\n if (options.include) writeResponseMetadata(rawResponse, writeStdout);\n writeStdout(Buffer.from(await rawResponse.arrayBuffer()));\n\n if (!rawResponse.ok) {\n writeStderr(\n `${method} ${normalizedEndpoint} returned HTTP ${rawResponse.status}${rawResponse.statusText ? ` ${rawResponse.statusText}` : ''}\\n`\n );\n (dependencies.exit ?? exitSync)(1);\n }\n}\n"],"mappings":";;;;;;;;;;;AAoCA,MAAM,wBAAwB,IAAI,IAAI;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAS,KACP,YACA,EACE,OAAO,UACP,eAAe,WAAW,QAAQ,OAAO,MAAM,OAAO,IAEjD;AACP,aAAY,GAAG,WAAW,IAAI;AAC9B,QAAO,KAAK,EAAE;;AAGhB,SAAS,YACP,OACA,cAC6B;CAC7B,MAAM,SAAS,MAAM,aAAa;AAClC,KAAI,CAAC,sBAAsB,IAAI,OAAO,CACpC,MACEA,0BAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;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U,QAAQ,OAAO,aAAa,GACtC,KAAA;CACJ,IAAI;AAEJ,QAAO,aAAa,SAAS,KAAK,aAAa;AAE7C,gBAAc,SAAS,OAAO;AAC9B,SAAO;GACP;CAEF,MAAM,SAAS,MAAM,OAClB,QAAQ;EACP;EACA,sBAAsB;EACtB;EACA;EACA,SAAS;EACT,cAAc;EACd,KAAK;EACN,CAAC,CACD,OAAO,UACN,KACEA,0BAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAASC,+BAA6B,MAAM;EAC7C,CAAC,EACF,aACD,CACF;AAEH,KAAI,CAAC,YACH,MACED,0BAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAASC,+BAA6B,QAAQ,MAAM;EACrD,CAAC,EACF,aACD;AAGH,KAAI,QAAQ,QAAS,uBAAsB,aAAa,YAAY;AACpE,aAAY,OAAO,KAAK,MAAM,YAAY,aAAa,CAAC,CAAC;AAEzD,KAAI,CAAC,YAAY,IAAI;AACnB,cACE,GAAG,OAAO,GAAG,mBAAmB,iBAAiB,YAAY,SAAS,YAAY,aAAa,IAAI,YAAY,eAAe,GAAG,IAClI;AACD,GAAC,aAAa,QAAQ,UAAU,EAAE"}
|
|
1
|
+
{"version":3,"file":"api.js","names":["createDiagnosticMessage","formatDiagnosticErrorDetails"],"sources":["../../../src/cli/commands/api.ts"],"sourcesContent":["import fs from 'node:fs';\nimport {\n createApiClient,\n type ApiClientConfig,\n type Client,\n} from 'generaltranslation/api';\nimport openApiSpec from 'generaltranslation/api/openapi.json' with { type: 'json' };\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { defaultBaseUrl } from 'generaltranslation/internal';\nimport { createUserTokenProvider } from '../../auth/oauth.js';\nimport { resolveConfig } from '../../config/resolveConfig.js';\nimport { exitSync } from '../../console/logging.js';\nimport { loadConfig, withJsonExtension } from '../../fs/config/loadConfig.js';\nimport { resolveProjectId } from '../../fs/utils.js';\nimport type { SharedFlags } from '../../types/index.js';\n\nexport type ApiCommandOptions = SharedFlags & {\n header?: string[];\n include?: boolean;\n input?: string;\n list?: boolean;\n method: string;\n spec?: boolean;\n};\n\ntype ApiCommandDependencies = {\n exit?: (code: number) => never;\n fetch?: ApiClientConfig['fetch'];\n writeStderr?: (output: string) => void;\n writeStdout?: (output: string | Uint8Array) => void;\n};\n\ntype ApiRequestOptions = Parameters<Client['request']>[0];\n\nconst STANDARD_HTTP_METHODS = new Set([\n 'GET',\n 'HEAD',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n]);\n\nfunction fail(\n diagnostic: string,\n {\n exit = exitSync,\n writeStderr = (output) => process.stderr.write(output),\n }: ApiCommandDependencies\n): never {\n writeStderr(`${diagnostic}\\n`);\n return exit(1);\n}\n\nfunction parseMethod(\n value: string,\n dependencies: ApiCommandDependencies\n): ApiRequestOptions['method'] {\n const method = value.toUpperCase();\n if (!STANDARD_HTTP_METHODS.has(method)) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request method is invalid',\n details: value,\n fix: `Use one of ${[...STANDARD_HTTP_METHODS].join(', ')}`,\n }),\n dependencies\n );\n }\n // The set validation narrows Commander input to the generated HTTP method union.\n return method as ApiRequestOptions['method'];\n}\n\nfunction parseHeaders(\n values: string[],\n dependencies: ApiCommandDependencies\n): Headers {\n const headers = new Headers();\n for (const header of values) {\n const separator = header.indexOf(':');\n if (separator < 1) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request header is invalid',\n details: header,\n fix: 'Pass headers as `--header \"Key: Value\"`',\n }),\n dependencies\n );\n }\n headers.append(\n header.slice(0, separator).trim(),\n header.slice(separator + 1).trim()\n );\n }\n return headers;\n}\n\nfunction readInput(\n input: string,\n dependencies: ApiCommandDependencies\n): string {\n try {\n return fs.readFileSync(input === '-' ? 0 : input, 'utf8');\n } catch (error) {\n return fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request body could not be read',\n fix:\n input === '-'\n ? 'Pipe a request body to standard input or remove `--input -`'\n : 'Check the `--input` file path and permissions',\n details: formatDiagnosticErrorDetails(error),\n }),\n dependencies\n );\n }\n}\n\ntype SpecOperation = {\n operationId?: string;\n security?: Record<string, unknown>[];\n summary?: string;\n};\nconst specPaths: Record<\n string,\n Record<string, SpecOperation>\n> = openApiSpec.paths;\n\nfunction listOperations(): string {\n return Object.entries(specPaths)\n .flatMap(([specPath, operations]) =>\n Object.entries(operations).map(\n ([method, operation]) =>\n `${method.toUpperCase()}\\t${specPath}\\t${operation.operationId ?? ''}\\t${operation.summary ?? ''}\\n`\n )\n )\n .join('');\n}\n\nfunction lookupRef(ref: string): unknown {\n return ref\n .slice(2)\n .split('/')\n .reduce<unknown>(\n (node, key) => (node as Record<string, unknown> | undefined)?.[key],\n openApiSpec\n );\n}\n\nfunction collectRefs(value: unknown, refs: Set<string>): void {\n if (!value || typeof value !== 'object') return;\n for (const [key, child] of Object.entries(value)) {\n if (key === '$ref' && typeof child === 'string') refs.add(child);\n else collectRefs(child, refs);\n }\n}\n\n// Inlines local `#/...` references so one operation reads standalone. A ref\n// already being expanded is left as-is because schemas like JsonValue recurse.\nfunction resolveRefs(value: unknown, expanding: string[] = []): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => resolveRefs(item, expanding));\n }\n if (!value || typeof value !== 'object') return value;\n const { $ref, ...siblings } = value as Record<string, unknown>;\n if (typeof $ref === 'string' && $ref.startsWith('#/')) {\n const target = lookupRef($ref);\n if (!expanding.includes($ref) && target && typeof target === 'object') {\n return resolveRefs({ ...target, ...siblings }, [...expanding, $ref]);\n }\n return value;\n }\n return Object.fromEntries(\n Object.entries(value).map(([key, child]) => [\n key,\n resolveRefs(child, expanding),\n ])\n );\n}\n\n// Shapes the output like the spec so the recursive refs resolveRefs leaves\n// behind and the security requirement names still resolve within it.\nfunction specFragment(\n operations: Record<string, Record<string, SpecOperation>>\n): Record<string, unknown> {\n const paths = resolveRefs(operations);\n const components: Record<string, Record<string, unknown>> = {};\n const addComponent = (type: string, name: string, definition: unknown) => {\n components[type] = { ...components[type], [name]: definition };\n };\n\n const pending = new Set<string>();\n collectRefs(paths, pending);\n const added = new Set<string>();\n for (const ref of pending) {\n const [root, type, name] = ref.slice(2).split('/');\n if (added.has(ref) || root !== 'components' || !type || !name) continue;\n added.add(ref);\n const definition = lookupRef(ref);\n addComponent(type, name, definition);\n // Set iteration visits refs added during the loop.\n collectRefs(definition, pending);\n }\n\n const securitySchemes: Record<string, unknown> =\n openApiSpec.components.securitySchemes;\n for (const operation of Object.values(operations).flatMap(Object.values)) {\n for (const name of (operation.security ?? []).flatMap(Object.keys)) {\n addComponent('securitySchemes', name, securitySchemes[name]);\n }\n }\n\n return Object.keys(components).length ? { paths, components } : { paths };\n}\n\n// Accepts an operationId, a spec path, or a concrete path such as\n// /v2/project/info/abc so agents can look up the request they are about to make.\nfunction findOperations(\n endpoint: string\n): Record<string, Record<string, SpecOperation>> {\n const byOperationId = Object.entries(specPaths).flatMap(\n ([specPath, operations]) =>\n Object.entries(operations)\n .filter(([, operation]) => operation.operationId === endpoint)\n .map(([method, operation]) => [specPath, { [method]: operation }])\n );\n if (byOperationId.length) return Object.fromEntries(byOperationId);\n\n const requestPath = `/${endpoint.replace(/^\\//, '').split('?')[0]}`;\n if (specPaths[requestPath]) {\n return { [requestPath]: specPaths[requestPath] };\n }\n return Object.fromEntries(\n Object.entries(specPaths).filter(([specPath]) =>\n new RegExp(\n `^${specPath\n .split(/\\{[^}]+\\}/)\n .map((literal) => literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('[^/]+')}$`\n ).test(requestPath)\n )\n );\n}\n\nfunction writeResponseMetadata(\n response: Response,\n writeStdout: (output: string | Uint8Array) => void\n): void {\n writeStdout(\n `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}\\n`\n );\n response.headers.forEach((value, name) => {\n writeStdout(`${name}: ${value}\\n`);\n });\n writeStdout('\\n');\n}\n\nfunction resolveApiProjectId(\n config: Record<string, unknown>,\n flagProjectId: string | undefined,\n dependencies: ApiCommandDependencies\n): string | undefined {\n const configProjectId =\n typeof config.projectId === 'string' ? config.projectId : undefined;\n const environmentProjectId = resolveProjectId();\n\n if (configProjectId && flagProjectId && configProjectId !== flagProjectId) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The project IDs do not match',\n details: [\n `Configuration: ${configProjectId}`,\n `--project-id: ${flagProjectId}`,\n ],\n fix: 'Use the same project ID in all configurations',\n }),\n dependencies\n );\n }\n\n if (\n configProjectId &&\n environmentProjectId &&\n configProjectId !== environmentProjectId\n ) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The project IDs do not match',\n details: [\n `Configuration: ${configProjectId}`,\n `Environment: ${environmentProjectId}`,\n ],\n fix: 'Use the same project ID in all configurations',\n }),\n dependencies\n );\n }\n\n return flagProjectId ?? configProjectId ?? environmentProjectId;\n}\n\nexport async function handleApiCommand(\n endpoint: string | undefined,\n options: ApiCommandOptions,\n dependencies: ApiCommandDependencies = {}\n): Promise<void> {\n if (!dependencies.writeStdout) {\n process.stdout.once('error', (error: NodeJS.ErrnoException) => {\n if (error.code === 'EPIPE') process.exit(0);\n throw error;\n });\n }\n const writeStdout =\n dependencies.writeStdout ?? ((output) => process.stdout.write(output));\n const writeStderr =\n dependencies.writeStderr ?? ((output) => process.stderr.write(output));\n\n if (options.list) {\n writeStdout(listOperations());\n return;\n }\n\n if (options.spec) {\n if (!endpoint) {\n writeStdout(`${JSON.stringify(openApiSpec, null, 2)}\\n`);\n return;\n }\n const operations = findOperations(endpoint);\n if (!Object.keys(operations).length) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No API operation matches the endpoint',\n details: endpoint,\n fix: 'Run `gt api --list` to see the available endpoints and operation IDs',\n }),\n dependencies\n );\n }\n writeStdout(`${JSON.stringify(specFragment(operations), null, 2)}\\n`);\n return;\n }\n\n if (!endpoint) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No API endpoint was provided',\n fix: 'Pass an endpoint, run `gt api --list` to see the available endpoints, or run `gt api --spec <endpoint>` to inspect one',\n }),\n dependencies\n );\n }\n\n const method = parseMethod(options.method, dependencies);\n const config = options.config\n ? loadConfig(withJsonExtension(options.config))\n : (resolveConfig(process.cwd())?.config ?? {});\n const baseUrl =\n typeof config.baseUrl === 'string' ? config.baseUrl : defaultBaseUrl;\n const client = createApiClient({\n apiKey: options.apiKey ?? process.env.GT_API_KEY,\n userTokenProvider: createUserTokenProvider({ baseUrl }),\n baseUrl,\n fetch: dependencies.fetch,\n projectId: resolveApiProjectId(config, options.projectId, dependencies),\n retryPolicy: 'none',\n });\n const normalizedEndpoint = endpoint.startsWith('/')\n ? endpoint\n : `/${endpoint}`;\n const headers = parseHeaders(options.header ?? [], dependencies);\n const body = options.input\n ? readInput(options.input, dependencies)\n : undefined;\n let rawResponse: Response | undefined;\n\n client.interceptors.response.use((response) => {\n // Keep a clone because the generated client consumes non-2xx bodies.\n rawResponse = response.clone();\n return response;\n });\n\n const result = await client\n .request({\n body,\n bodySerializer: () => body,\n headers,\n method,\n parseAs: 'stream',\n throwOnError: false,\n url: normalizedEndpoint,\n })\n .catch((error) =>\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request failed before a response was received',\n details: formatDiagnosticErrorDetails(error),\n }),\n dependencies\n )\n );\n\n if (!rawResponse) {\n fail(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The API request did not return a response',\n details: formatDiagnosticErrorDetails(result?.error),\n }),\n dependencies\n );\n }\n\n if (options.include) writeResponseMetadata(rawResponse, writeStdout);\n writeStdout(Buffer.from(await rawResponse.arrayBuffer()));\n\n if (!rawResponse.ok) {\n writeStderr(\n `${method} ${normalizedEndpoint} returned HTTP ${rawResponse.status}${rawResponse.statusText ? ` ${rawResponse.statusText}` : ''}\\n`\n );\n (dependencies.exit ?? exitSync)(1);\n }\n}\n"],"mappings":";;;;;;;;;;;AAqCA,MAAM,wBAAwB,IAAI,IAAI;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAS,KACP,YACA,EACE,OAAO,UACP,eAAe,WAAW,QAAQ,OAAO,MAAM,OAAO,IAEjD;AACP,aAAY,GAAG,WAAW,IAAI;AAC9B,QAAO,KAAK,EAAE;;AAGhB,SAAS,YACP,OACA,cAC6B;CAC7B,MAAM,SAAS,MAAM,aAAa;AAClC,KAAI,CAAC,sBAAsB,IAAI,OAAO,CACpC,MACEA,0BAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAAS;EACT,KAAK,cAAc,CAAC,GAAG,sBAAsB,CAAC,KAAK,KAAK;EACzD,CAAC,EACF,aACD;AAGH,QAAO;;AAGT,SAAS,aACP,QACA,cACS;CACT,MAAM,UAAU,IAAI,SAAS;AAC7B,MAAK,MAAM,UAAU,QAAQ;EAC3B,MAAM,YAAY,OAAO,QAAQ,IAAI;AACrC,MAAI,YAAY,EACd,MACEA,0BAAwB;GACtB,QAAQ;GACR,UAAU;GACV,cAAc;GACd,SAAS;GACT,KAAK;GACN,CAAC,EACF,aACD;AAEH,UAAQ,OACN,OAAO,MAAM,GAAG,UAAU,CAAC,MAAM,EACjC,OAAO,MAAM,YAAY,EAAE,CAAC,MAAM,CACnC;;AAEH,QAAO;;AAGT,SAAS,UACP,OACA,cACQ;AACR,KAAI;AACF,SAAO,GAAG,aAAa,UAAU,MAAM,IAAI,OAAO,OAAO;UAClD,OAAO;AACd,SAAO,KACLA,0BAAwB;GACtB,QAAQ;GACR,UAAU;GACV,cAAc;GACd,KACE,UAAU,MACN,gEACA;GACN,SAASC,+BAA6B,MAAM;GAC7C,CAAC,EACF,aACD;;;AASL,MAAM,YAGF,Y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;EACA,sBAAsB;EACtB;EACA;EACA,SAAS;EACT,cAAc;EACd,KAAK;EACN,CAAC,CACD,OAAO,UACN,KACEA,0BAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAASC,+BAA6B,MAAM;EAC7C,CAAC,EACF,aACD,CACF;AAEH,KAAI,CAAC,YACH,MACED,0BAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAASC,+BAA6B,QAAQ,MAAM;EACrD,CAAC,EACF,aACD;AAGH,KAAI,QAAQ,QAAS,uBAAsB,aAAa,YAAY;AACpE,aAAY,OAAO,KAAK,MAAM,YAAY,aAAa,CAAC,CAAC;AAEzD,KAAI,CAAC,YAAY,IAAI;AACnB,cACE,GAAG,OAAO,GAAG,mBAAmB,iBAAiB,YAAY,SAAS,YAAY,aAAa,IAAI,YAAY,eAAe,GAAG,IAClI;AACD,GAAC,aAAa,QAAQ,UAAU,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const PACKAGE_VERSION = "2.
|
|
1
|
+
export declare const PACKAGE_VERSION = "2.25.0";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.25.0';\n"],"mappings":";AACA,MAAa,kBAAkB"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -260,6 +260,7 @@ export type AdditionalOptions = {
|
|
|
260
260
|
experimentalLocalizeStaticImports?: boolean;
|
|
261
261
|
experimentalLocalizeStaticUrls?: boolean | {
|
|
262
262
|
skipUntranslatedPages?: boolean;
|
|
263
|
+
attributes?: string[];
|
|
263
264
|
};
|
|
264
265
|
experimentalLocalizeRelativeAssets?: boolean;
|
|
265
266
|
experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';
|
package/dist/types/index.js.map
CHANGED
|
@@ -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] 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; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files\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 };\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;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] 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; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files\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;CACD"}
|
|
@@ -13,12 +13,13 @@ import { escapeHtmlInTextNodes, normalizeCJKCharacters } from "gt-remark";
|
|
|
13
13
|
//#region src/utils/localizeStaticUrls.ts
|
|
14
14
|
const { isMatch } = micromatch;
|
|
15
15
|
/**
|
|
16
|
-
* URL-bearing JSX attributes that we localize. Intentionally limited
|
|
17
|
-
* attributes (`href`) — NOT asset attributes like `src`, which usually
|
|
18
|
-
* shared, locale-agnostic assets (e.g. `/docs/images/...`) that would
|
|
19
|
-
* locale prefix were added.
|
|
16
|
+
* URL-bearing JSX attributes that we localize by default. Intentionally limited
|
|
17
|
+
* to link attributes (`href`) — NOT asset attributes like `src`, which usually
|
|
18
|
+
* point at shared, locale-agnostic assets (e.g. `/docs/images/...`) that would
|
|
19
|
+
* 404 if a locale prefix were added. Projects add their own link attributes
|
|
20
|
+
* with `experimentalLocalizeStaticUrls.attributes`.
|
|
20
21
|
*/
|
|
21
|
-
const
|
|
22
|
+
const DEFAULT_URL_ATTRIBUTES = ["href"];
|
|
22
23
|
const PAGE_EXTENSIONS = [".mdx", ".md"];
|
|
23
24
|
const INDEX_PAGE = "index";
|
|
24
25
|
/**
|
|
@@ -60,7 +61,7 @@ function translationMissing(url, localizedUrl, localizedFiles) {
|
|
|
60
61
|
* (template literals, identifiers, concatenation) are left untouched — a
|
|
61
62
|
* fundamental limit of static localization, not a parser shortcoming.
|
|
62
63
|
*/
|
|
63
|
-
function localizeUrlsInExpressionSource(source, transformUrl, rootStringIsUrl = false) {
|
|
64
|
+
function localizeUrlsInExpressionSource(source, transformUrl, urlAttributes, rootStringIsUrl = false) {
|
|
64
65
|
if (!source.trim()) return source;
|
|
65
66
|
let ast;
|
|
66
67
|
try {
|
|
@@ -99,7 +100,7 @@ function localizeUrlsInExpressionSource(source, transformUrl, rootStringIsUrl =
|
|
|
99
100
|
}
|
|
100
101
|
if (seen.has(node)) return;
|
|
101
102
|
seen.add(node);
|
|
102
|
-
if (node.type === "JSXAttribute" && node.name?.type === "JSXIdentifier" &&
|
|
103
|
+
if (node.type === "JSXAttribute" && node.name?.type === "JSXIdentifier" && isMatch(node.name.name, urlAttributes) && node.value) {
|
|
103
104
|
if (node.value.type === "StringLiteral") pushLiteralReplacement(node.value);
|
|
104
105
|
else if (node.value.type === "JSXExpressionContainer" && node.value.expression?.type === "StringLiteral") pushLiteralReplacement(node.value.expression);
|
|
105
106
|
}
|
|
@@ -135,6 +136,7 @@ async function localizeStaticUrls(settings, targetLocales, includeFiles) {
|
|
|
135
136
|
const { resolvedPaths: sourceFiles } = settings.files;
|
|
136
137
|
const localizeOptions = settings.options?.experimentalLocalizeStaticUrls;
|
|
137
138
|
const skipUntranslatedPages = typeof localizeOptions === "object" && localizeOptions.skipUntranslatedPages === true;
|
|
139
|
+
const urlAttributes = [...DEFAULT_URL_ATTRIBUTES, ...typeof localizeOptions === "object" && localizeOptions.attributes || []];
|
|
138
140
|
const locales = targetLocales || settings.locales;
|
|
139
141
|
const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths ?? {}, settings.files.transformFormats ?? {}, settings.locales, settings.defaultLocale);
|
|
140
142
|
const processPromises = [];
|
|
@@ -145,7 +147,7 @@ async function localizeStaticUrls(settings, targetLocales, includeFiles) {
|
|
|
145
147
|
if (defaultLocaleFiles.length > 0) {
|
|
146
148
|
const defaultPromise = Promise.all(defaultLocaleFiles.map(async (filePath) => {
|
|
147
149
|
if (!fs$1.existsSync(filePath)) return;
|
|
148
|
-
const result = localizeStaticUrlsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, settings.defaultLocale, settings.options?.experimentalHideDefaultLocale || false, settings.options?.docsUrlPattern, settings.options?.excludeStaticUrls, settings.options?.baseDomain);
|
|
150
|
+
const result = localizeStaticUrlsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, settings.defaultLocale, settings.options?.experimentalHideDefaultLocale || false, settings.options?.docsUrlPattern, settings.options?.excludeStaticUrls, settings.options?.baseDomain, void 0, urlAttributes);
|
|
149
151
|
if (result.hasChanges) await fs$1.promises.writeFile(filePath, result.content);
|
|
150
152
|
}));
|
|
151
153
|
processPromises.push(defaultPromise);
|
|
@@ -155,7 +157,7 @@ async function localizeStaticUrls(settings, targetLocales, includeFiles) {
|
|
|
155
157
|
const targetFiles = Object.values(filesMap).filter((p) => PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) && (!includeFiles || includeFiles.has(p)));
|
|
156
158
|
await Promise.all(targetFiles.map(async (filePath) => {
|
|
157
159
|
if (!fs$1.existsSync(filePath)) return;
|
|
158
|
-
const result = localizeStaticUrlsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, locale, settings.options?.experimentalHideDefaultLocale || false, settings.options?.docsUrlPattern, settings.options?.excludeStaticUrls, settings.options?.baseDomain, skipUntranslatedPages ? filesMap : void 0);
|
|
160
|
+
const result = localizeStaticUrlsForFile(await fs$1.promises.readFile(filePath, "utf8"), settings.defaultLocale, locale, settings.options?.experimentalHideDefaultLocale || false, settings.options?.docsUrlPattern, settings.options?.excludeStaticUrls, settings.options?.baseDomain, skipUntranslatedPages ? filesMap : void 0, urlAttributes);
|
|
159
161
|
if (result.hasChanges) await fs$1.promises.writeFile(filePath, result.content);
|
|
160
162
|
}));
|
|
161
163
|
});
|
|
@@ -225,7 +227,7 @@ function transformUrlPath(originalUrl, patternHead, targetLocale, defaultLocale,
|
|
|
225
227
|
/**
|
|
226
228
|
* AST-based transformation for MDX files using remark-mdx
|
|
227
229
|
*/
|
|
228
|
-
function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles) {
|
|
230
|
+
function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles, urlAttributes) {
|
|
229
231
|
const transformedUrls = [];
|
|
230
232
|
if (!pattern.startsWith("/")) pattern = "/" + pattern;
|
|
231
233
|
const patternHead = pattern.split("[locale]")[0];
|
|
@@ -298,14 +300,14 @@ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLo
|
|
|
298
300
|
for (const attr of jsxNode.attributes) {
|
|
299
301
|
if (attr.type !== "mdxJsxAttribute" || !attr.value) continue;
|
|
300
302
|
if (typeof attr.value === "string") {
|
|
301
|
-
if (
|
|
303
|
+
if (isMatch(attr.name, urlAttributes)) {
|
|
302
304
|
const newUrl = transformUrl(attr.value, "href");
|
|
303
305
|
if (newUrl) attr.value = newUrl;
|
|
304
306
|
}
|
|
305
307
|
continue;
|
|
306
308
|
}
|
|
307
309
|
if (typeof attr.value === "object" && attr.value.type === "mdxJsxAttributeValueExpression" && typeof attr.value.value === "string") {
|
|
308
|
-
const newValue = localizeUrlsInExpressionSource(attr.value.value, transformUrl,
|
|
310
|
+
const newValue = localizeUrlsInExpressionSource(attr.value.value, transformUrl, urlAttributes, isMatch(attr.name, urlAttributes));
|
|
309
311
|
if (newValue !== attr.value.value) attr.value.value = newValue;
|
|
310
312
|
}
|
|
311
313
|
}
|
|
@@ -313,7 +315,7 @@ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLo
|
|
|
313
315
|
visit(processedAst, ["mdxFlowExpression", "mdxTextExpression"], (node) => {
|
|
314
316
|
const exprNode = node;
|
|
315
317
|
if (typeof exprNode.value === "string" && exprNode.value) {
|
|
316
|
-
const newValue = localizeUrlsInExpressionSource(exprNode.value, transformUrl);
|
|
318
|
+
const newValue = localizeUrlsInExpressionSource(exprNode.value, transformUrl, urlAttributes);
|
|
317
319
|
if (newValue !== exprNode.value) exprNode.value = newValue;
|
|
318
320
|
}
|
|
319
321
|
});
|
|
@@ -373,8 +375,8 @@ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLo
|
|
|
373
375
|
transformedUrls
|
|
374
376
|
};
|
|
375
377
|
}
|
|
376
|
-
function localizeStaticUrlsForFile(file, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles) {
|
|
377
|
-
return transformMdxUrls(file, defaultLocale, targetLocale, hideDefaultLocale, pattern, exclude, baseDomain || "", localizedFiles);
|
|
378
|
+
function localizeStaticUrlsForFile(file, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles, urlAttributes) {
|
|
379
|
+
return transformMdxUrls(file, defaultLocale, targetLocale, hideDefaultLocale, pattern, exclude, baseDomain || "", localizedFiles, urlAttributes);
|
|
378
380
|
}
|
|
379
381
|
function checkIfPathMatchesPattern(originalUrlArray, patternHeadArray) {
|
|
380
382
|
for (let i = 0; i < patternHeadArray.length; i++) if (patternHeadArray[i] !== originalUrlArray?.[i]) return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localizeStaticUrls.js","names":["path","fs","parseBabel"],"sources":["../../src/utils/localizeStaticUrls.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { StaticLocalizationSettings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport micromatch from 'micromatch';\nimport { unified } from 'unified';\nimport remarkMdx from 'remark-mdx';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkStringify from 'remark-stringify';\nimport { visit } from 'unist-util-visit';\nimport type { Root, Link, Literal } from 'mdast';\nimport type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parse as parseBabel } from '@babel/parser';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\n\nconst { isMatch } = micromatch;\n\n/**\n * URL-bearing JSX attributes that we localize. Intentionally limited to link\n * attributes (`href`) — NOT asset attributes like `src`, which usually point at\n * shared, locale-agnostic assets (e.g. `/docs/images/...`) that would 404 if a\n * locale prefix were added. Extend deliberately.\n */\nconst LOCALIZABLE_URL_ATTRIBUTES = new Set(['href']);\n\n// Docs routing conventions: page file formats, and the file that serves a\n// folder URL (`/a/` -> `a/index.mdx`).\nexport const PAGE_EXTENSIONS = ['.mdx', '.md'];\nexport const INDEX_PAGE = 'index';\n\n/**\n * The page file a root-relative docs URL points to, relative to the working\n * directory like file mapping keys: `/a/b#x` -> `a/b.mdx`, `a/b.md`, or\n * `a/b/index.mdx`.\n */\nfunction findPage(url: string): string | undefined {\n const base = url.split(/[?#]/)[0].replace(/^\\/+|\\/+$/g, '');\n return PAGE_EXTENSIONS.flatMap((ext) => [\n `${base}${ext}`,\n path.join(base, `${INDEX_PAGE}${ext}`),\n ]).find((page) => fs.existsSync(page));\n}\n\n/**\n * Whether a URL points to a source page with no translation on disk, either at\n * its mapped output path or at the localized URL. URLs with no source page,\n * such as pages generated from an OpenAPI spec, are not missing a translation.\n */\nexport function translationMissing(\n url: string,\n localizedUrl: string,\n localizedFiles: Record<string, string>\n): boolean {\n const sourcePage = findPage(url);\n if (!sourcePage) return false;\n const mappedPage = localizedFiles[sourcePage];\n return !(mappedPage && fs.existsSync(mappedPage)) && !findPage(localizedUrl);\n}\n\n/**\n * Localize URL string literals that live inside an MDX expression's raw source.\n *\n * URLs can be nested arbitrarily deep inside `{...}` expressions — e.g. an\n * `<a href>` buried inside a component prop:\n * <ParamField type={<span><a href=\"/docs/x\">Error</a></span>} />\n * Such hrefs never appear as mdast nodes (they live in the expression's embedded\n * JS), so the mdast visitors can't reach them. We re-parse the expression source\n * with Babel — positions are local to `source`, which avoids any document-offset\n * mapping — find JSX url-attribute string literals at any depth, and surgically\n * rewrite them in place.\n *\n * `rootStringIsUrl` covers `href={\"/docs/x\"}`, where the expression itself is a\n * bare string literal that a url-named attribute should treat as a URL.\n *\n * Only static string literals are localized; dynamically-computed URLs\n * (template literals, identifiers, concatenation) are left untouched — a\n * fundamental limit of static localization, not a parser shortcoming.\n */\nfunction localizeUrlsInExpressionSource(\n source: string,\n transformUrl: (url: string, linkType: 'markdown' | 'href') => string | null,\n rootStringIsUrl: boolean = false\n): string {\n if (!source.trim()) return source;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ast: any;\n try {\n ast = parseBabel(source, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['jsx', 'typescript'],\n });\n } catch {\n // Dynamic / unparseable expression — leave it untouched.\n return source;\n }\n\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const pushLiteralReplacement = (literal: any) => {\n if (\n !literal ||\n // A bare string at statement position is parsed by Babel as a\n // DirectiveLiteral (cf. \"use strict\") rather than a StringLiteral.\n (literal.type !== 'StringLiteral' &&\n literal.type !== 'DirectiveLiteral') ||\n typeof literal.value !== 'string' ||\n typeof literal.start !== 'number' ||\n typeof literal.end !== 'number'\n ) {\n return;\n }\n const newUrl = transformUrl(literal.value, 'href');\n if (!newUrl) return;\n // Preserve the original quote style; URLs never contain quote chars.\n const quote = source[literal.start] === \"'\" ? \"'\" : '\"';\n replacements.push({\n start: literal.start,\n end: literal.end,\n text: `${quote}${newUrl}${quote}`,\n });\n };\n\n // `href={\"/docs/x\"}`: the entire expression is the URL string.\n if (rootStringIsUrl) {\n const program = ast.program;\n const body = (program?.body ?? []) as Array<{\n type: string;\n expression?: unknown;\n }>;\n if (body.length === 1 && body[0]?.type === 'ExpressionStatement') {\n pushLiteralReplacement(body[0].expression);\n } else if (body.length === 0 && program?.directives?.length === 1) {\n // Babel parses a lone string literal as a directive, not a statement.\n pushLiteralReplacement(program.directives[0]?.value);\n }\n }\n\n // Walk the AST for JSX url-attributes anywhere in the expression.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const seen = new Set<any>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const walk = (node: any) => {\n if (!node || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (seen.has(node)) return;\n seen.add(node);\n\n if (\n node.type === 'JSXAttribute' &&\n node.name?.type === 'JSXIdentifier' &&\n LOCALIZABLE_URL_ATTRIBUTES.has(node.name.name) &&\n node.value\n ) {\n if (node.value.type === 'StringLiteral') {\n pushLiteralReplacement(node.value);\n } else if (\n node.value.type === 'JSXExpressionContainer' &&\n node.value.expression?.type === 'StringLiteral'\n ) {\n pushLiteralReplacement(node.value.expression);\n }\n }\n\n for (const key in node) {\n if (\n key === 'loc' ||\n key === 'start' ||\n key === 'end' ||\n key === 'range'\n ) {\n continue;\n }\n const child = node[key];\n if (child && typeof child === 'object') walk(child);\n }\n };\n walk(ast.program ?? ast);\n\n if (replacements.length === 0) return source;\n\n // Apply end-to-start so earlier offsets remain valid.\n let result = source;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, text }) => {\n result = result.slice(0, start) + text + result.slice(end);\n });\n return result;\n}\n\nexport type StaticUrlSettings = StaticLocalizationSettings;\n\n/**\n * Localizes static urls in content files.\n * Currently only supported for md and mdx files. (/docs/ -> /[locale]/docs/)\n * @param settings - The settings object containing the project configuration.\n * @returns void\n *\n * @TODO This is an experimental feature, and only works in very specific cases. This needs to be improved before\n * it can be enabled by default.\n *\n * Before this becomes a non-experimental feature, we need to:\n * - Support more file types\n * - Support more complex paths\n */\nexport default async function localizeStaticUrls(\n settings: StaticUrlSettings,\n targetLocales?: string[],\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n const localizeOptions = settings.options?.experimentalLocalizeStaticUrls;\n const skipUntranslatedPages =\n typeof localizeOptions === 'object' &&\n localizeOptions.skipUntranslatedPages === true;\n\n // Use filtered locales if provided, otherwise use all locales\n const locales = targetLocales || settings.locales;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales, // Always use all locales for mapping, filter later\n settings.defaultLocale\n );\n\n // Process all file types at once with a single call\n const processPromises = [];\n\n // First, process default locale files (from source files)\n // This is needed because they might not be in the fileMapping if they're not being translated\n // Only process default locale if it's in the target locales filter\n if (\n !fileMapping[settings.defaultLocale] &&\n locales.includes(settings.defaultLocale) &&\n !includeFiles // when filtering, skip default-locale pass\n ) {\n const defaultLocaleFiles: string[] = [];\n\n // Collect all .md and .mdx files from sourceFiles\n if (sourceFiles.md) {\n defaultLocaleFiles.push(...sourceFiles.md);\n }\n if (sourceFiles.mdx) {\n defaultLocaleFiles.push(...sourceFiles.mdx);\n }\n\n if (defaultLocaleFiles.length > 0) {\n const defaultPromise = Promise.all(\n defaultLocaleFiles.map(async (filePath: string) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file using default locale\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n settings.defaultLocale, // Process as default locale\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n processPromises.push(defaultPromise);\n }\n }\n\n // Then process all other locales from fileMapping\n const mappingPromises = Object.entries(fileMapping)\n .filter(([locale]) => locales.includes(locale)) // Filter by target locales\n .map(async ([locale, filesMap]) => {\n // Get all files that are md or mdx\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n // Replace the placeholder path with the target path\n await Promise.all(\n targetFiles.map(async (filePath) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file (handles both URLs and hrefs in single AST pass)\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n locale,\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n skipUntranslatedPages ? filesMap : undefined\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n });\n processPromises.push(...mappingPromises);\n\n await Promise.all(processPromises);\n}\n\ninterface UrlTransformResult {\n content: string;\n hasChanges: boolean;\n transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }>;\n}\n\n/**\n * Determines if a URL should be processed based on pattern matching\n */\nfunction shouldProcessUrl(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n baseDomain?: string\n): boolean {\n // Check fragment-only URLs like \"#id-name\"\n if (/^\\s*#/.test(originalUrl)) {\n return false;\n }\n\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n\n // Handle absolute URLs with baseDomain\n let urlToCheck = originalUrl;\n if (baseDomain && originalUrl.startsWith(baseDomain)) {\n urlToCheck = originalUrl.substring(baseDomain.length);\n }\n\n if (targetLocale === defaultLocale) {\n // For default locale processing, check if URL contains the pattern\n return urlToCheck.includes(patternWithoutSlash);\n } else {\n // For non-default locales, check if URL starts with pattern\n return urlToCheck.startsWith(patternWithoutSlash);\n }\n}\n\n/**\n * Determines if a URL should be processed based on the base domain\n */\nfunction shouldProcessAbsoluteUrl(\n originalUrl: string,\n baseDomain: string\n): boolean {\n return originalUrl.startsWith(baseDomain);\n}\n\n/**\n * Checks if a URL should be excluded based on exclusion patterns\n */\nfunction isUrlExcluded(\n originalUrl: string,\n exclude: string[],\n defaultLocale: string\n): boolean {\n const excludePatterns = exclude.map((p) =>\n p.replace(/\\[locale\\]/g, defaultLocale)\n );\n return excludePatterns.some((pattern) => isMatch(originalUrl, pattern));\n}\n\n/**\n * Main URL transformation function that delegates to specific scenarios\n */\nexport function transformUrlPath(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean\n): string | null {\n const originalPathArray = originalUrl\n .split('/')\n .filter((path) => path !== '');\n const patternHeadArray = patternHead.split('/').filter((path) => path !== '');\n\n // check if the pattern head matches the original path\n if (!checkIfPathMatchesPattern(originalPathArray, patternHeadArray)) {\n return null;\n }\n\n if (patternHeadArray.length > originalPathArray.length) {\n return null; // Pattern is longer than the URL path\n }\n\n let result = null;\n if (targetLocale === defaultLocale) {\n if (hideDefaultLocale) {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // remove default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n ...originalPathArray.slice(patternHeadArray.length + 1),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] === defaultLocale) {\n return null;\n }\n\n // insert default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n defaultLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n }\n } else if (hideDefaultLocale) {\n // Avoid duplicating target locale if already present\n if (originalPathArray?.[patternHeadArray.length] === targetLocale) {\n return null;\n }\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n targetLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check default locale\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // replace default locale with target locale\n const newPathArray = [...originalPathArray];\n newPathArray[patternHeadArray.length] = targetLocale;\n\n result = newPathArray.join('/');\n }\n\n // check for leading and trailing slashes\n if (originalUrl.startsWith('/')) {\n result = '/' + result;\n }\n if (originalUrl.endsWith('/')) {\n result = result + '/';\n }\n\n return result;\n}\n\n/**\n * AST-based transformation for MDX files using remark-mdx\n */\nfunction transformMdxUrls(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n baseDomain?: string,\n localizedFiles?: Record<string, string>\n): UrlTransformResult {\n const transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }> = [];\n\n if (!pattern.startsWith('/')) {\n pattern = '/' + pattern;\n }\n\n const patternHead = pattern.split('[locale]')[0];\n\n // Quick check: if the file doesn't contain the pattern, skip expensive AST parsing\n // For default locale processing, we also need to check if content might need adjustment\n if (targetLocale === defaultLocale) {\n // For default locale files, we always need to check as we're looking for either:\n // - paths without locale (when hideDefaultLocale=false)\n // - paths with default locale (when hideDefaultLocale=true)\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n if (!mdxContent.includes(patternWithoutSlash)) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n } else {\n // For non-default locales, use the original logic\n if (!mdxContent.includes(patternHead.replace(/\\/$/, ''))) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n }\n\n // Parse the MDX content into an AST\n let processedAst: Root;\n let neutralizedAnchors: boolean;\n try {\n const parsed = parseMdxForRoundTrip(mdxContent);\n processedAst = parsed.ast;\n neutralizedAnchors = parsed.neutralized;\n } catch {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls,\n };\n }\n\n // Helper function to transform URL based on pattern\n const transformUrl = (\n originalUrl: string,\n linkType: 'markdown' | 'href'\n ): string | null => {\n // For Markdown links [text](path), only process absolute-root paths starting with '/'\n // Relative markdown links should remain relative to the current page and not be localized.\n if (linkType === 'markdown') {\n const isFragment = /^\\s*#/.test(originalUrl);\n const isAbsoluteRoot = originalUrl.startsWith('/');\n const looksAbsoluteWithDomain = baseDomain\n ? shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n : false;\n if (!isAbsoluteRoot && !looksAbsoluteWithDomain && !isFragment) {\n return null;\n }\n }\n // Check if URL should be processed\n if (\n !shouldProcessUrl(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n baseDomain\n )\n ) {\n return null;\n }\n\n // Skip absolute URLs (http://, https://, //, etc.)\n if (baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)) {\n // Get everything after the base domain\n const afterDomain = originalUrl.substring(baseDomain.length);\n\n const transformedPath = transformUrlPath(\n afterDomain,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n if (!transformedPath) {\n return null;\n }\n if (\n localizedFiles &&\n translationMissing(afterDomain, transformedPath, localizedFiles)\n ) {\n return null;\n }\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: transformedPath,\n type: linkType,\n });\n return transformedPath ? baseDomain + transformedPath : null;\n }\n\n // Exclude colon-prefixed URLs (http://, https://, //, etc.)\n if (originalUrl.split('?')[0].includes(':')) {\n return null;\n }\n\n // Transform the URL based on locale and configuration\n const newUrl = transformUrlPath(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n\n if (!newUrl) {\n return null;\n }\n\n // Check exclusions\n if (isUrlExcluded(originalUrl, exclude, defaultLocale)) {\n return null;\n }\n\n // Links to pages with no translation keep the default locale.\n if (\n localizedFiles &&\n translationMissing(originalUrl, newUrl, localizedFiles)\n ) {\n return null;\n }\n\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: newUrl,\n type: linkType,\n });\n return newUrl;\n };\n\n // Visit markdown link nodes: [text](url)\n visit(processedAst, 'link', (node: Link) => {\n if (node.url) {\n const newUrl = transformUrl(node.url, 'markdown');\n if (newUrl) {\n node.url = newUrl;\n }\n }\n });\n\n // Visit JSX/HTML elements for href attributes: <a href=\"url\"> or <Card href=\"url\">\n visit(processedAst, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node) => {\n const jsxNode = node as MdxJsxFlowElement | MdxJsxTextElement;\n if (!jsxNode.attributes) return;\n for (const attr of jsxNode.attributes) {\n if (attr.type !== 'mdxJsxAttribute' || !attr.value) continue;\n\n // Plain string attribute value, e.g. <a href=\"/docs/x\">\n if (typeof attr.value === 'string') {\n if (LOCALIZABLE_URL_ATTRIBUTES.has(attr.name)) {\n const newUrl = transformUrl(attr.value, 'href');\n if (newUrl) {\n attr.value = newUrl;\n }\n }\n continue;\n }\n\n // Expression attribute value. Two shapes are handled:\n // href={\"/docs/x\"} (url attr, bare string)\n // type={<span><a href=\"/docs/x\">…</a></span>} (url attr nested deep\n // inside a non-url prop)\n // The nested case never surfaces as an mdast node — it lives in the\n // expression's embedded JS — so it's localized via the source-level walk.\n if (\n typeof attr.value === 'object' &&\n attr.value.type === 'mdxJsxAttributeValueExpression' &&\n typeof attr.value.value === 'string'\n ) {\n const newValue = localizeUrlsInExpressionSource(\n attr.value.value,\n transformUrl,\n LOCALIZABLE_URL_ATTRIBUTES.has(attr.name)\n );\n if (newValue !== attr.value.value) {\n attr.value.value = newValue;\n }\n }\n }\n });\n\n // Visit standalone MDX expressions for URLs inside embedded JSX, e.g.\n // {isBeta && <a href=\"/docs/x\">Beta</a>}\n visit(processedAst, ['mdxFlowExpression', 'mdxTextExpression'], (node) => {\n const exprNode = node as unknown as Literal;\n if (typeof exprNode.value === 'string' && exprNode.value) {\n const newValue = localizeUrlsInExpressionSource(\n exprNode.value,\n transformUrl\n );\n if (newValue !== exprNode.value) {\n exprNode.value = newValue;\n }\n }\n });\n\n // Visit raw JSX nodes for href attributes in JSX strings\n visit(processedAst, 'jsx', (node: Literal) => {\n if (node.value && typeof node.value === 'string') {\n const jsxContent = node.value;\n\n // Use regex to find href attributes in the JSX string\n const hrefRegex = /href\\s*=\\s*[\"']([^\"']+)[\"']/g;\n let match;\n const replacements: Array<{\n start: number;\n end: number;\n oldHrefAttr: string;\n newHrefAttr: string;\n }> = [];\n\n // Reset regex lastIndex to avoid issues with global flag\n hrefRegex.lastIndex = 0;\n\n while ((match = hrefRegex.exec(jsxContent)) !== null) {\n const originalHref = match[1];\n const newUrl = transformUrl(originalHref, 'href');\n\n if (newUrl) {\n // Store replacement info\n const oldHrefAttr = match[0]; // The full match like 'href=\"/quickstart\"'\n const quote = oldHrefAttr.includes('\"') ? '\"' : \"'\";\n const newHrefAttr = `href=${quote}${newUrl}${quote}`;\n\n replacements.push({\n start: match.index!,\n end: match.index! + oldHrefAttr.length,\n oldHrefAttr,\n newHrefAttr,\n });\n }\n }\n\n // Apply replacements in reverse order (from end to start) to avoid position shifts\n if (replacements.length > 0) {\n let newJsxContent = jsxContent;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, newHrefAttr }) => {\n newJsxContent =\n newJsxContent.slice(0, start) +\n newHrefAttr +\n newJsxContent.slice(end);\n });\n\n node.value = newJsxContent;\n }\n }\n });\n\n // Convert the modified AST back to MDX string\n let content: string;\n try {\n const stringifyProcessor = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n // Handler to prevent escaping (avoids '<' -> '\\<')\n text(node: Literal) {\n return node.value;\n },\n },\n });\n\n const outTree = stringifyProcessor.runSync(processedAst) as Root;\n content = stringifyProcessor.stringify(outTree);\n if (neutralizedAnchors) {\n content = restoreAnchorIds(content);\n }\n } catch (error) {\n console.warn(\n `Failed to stringify MDX content: ${error instanceof Error ? error.message : String(error)}`\n );\n console.warn(\n 'Returning original content unchanged due to stringify error.'\n );\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n\n // Handle newline formatting to match original input\n if (content.endsWith('\\n') && !mdxContent.endsWith('\\n')) {\n content = content.slice(0, -1);\n }\n\n // Preserve leading newlines from original content\n if (mdxContent.startsWith('\\n') && !content.startsWith('\\n')) {\n content = '\\n' + content;\n }\n\n return {\n content,\n hasChanges: transformedUrls.length > 0,\n transformedUrls,\n };\n}\n\n// AST-based transformation for MDX files using remark\nfunction localizeStaticUrlsForFile(\n file: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]', // eg /docs/[locale] or /[locale]\n exclude: string[] = [],\n baseDomain?: string,\n localizedFiles?: Record<string, string>\n): UrlTransformResult {\n // Use AST-based transformation for MDX files\n return transformMdxUrls(\n file,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n baseDomain || '',\n localizedFiles\n );\n}\n\nfunction checkIfPathMatchesPattern(\n originalUrlArray: string[],\n patternHeadArray: string[]\n): boolean {\n // check if the pattern head matches the original path\n for (let i = 0; i < patternHeadArray.length; i++) {\n if (patternHeadArray[i] !== originalUrlArray?.[i]) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,EAAE,YAAY;;;;;;;AAQpB,MAAM,6BAA6B,IAAI,IAAI,CAAC,OAAO,CAAC;AAIpD,MAAa,kBAAkB,CAAC,QAAQ,MAAM;AAC9C,MAAa,aAAa;;;;;;AAO1B,SAAS,SAAS,KAAiC;CACjD,MAAM,OAAO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ACP,MACA,eACA,cACA,mBACA,UAAkB,aAClB,UAAoB,EAAE,EACtB,YACA,gBACoB;AAEpB,QAAO,iBACL,MACA,eACA,cACA,mBACA,SACA,SACA,cAAc,IACd,eACD;;AAGH,SAAS,0BACP,kBACA,kBACS;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,IAC3C,KAAI,iBAAiB,OAAO,mBAAmB,GAC7C,QAAO;AAIX,QAAO"}
|
|
1
|
+
{"version":3,"file":"localizeStaticUrls.js","names":["path","fs","parseBabel"],"sources":["../../src/utils/localizeStaticUrls.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { StaticLocalizationSettings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport micromatch from 'micromatch';\nimport { unified } from 'unified';\nimport remarkMdx from 'remark-mdx';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkStringify from 'remark-stringify';\nimport { visit } from 'unist-util-visit';\nimport type { Root, Link, Literal } from 'mdast';\nimport type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parse as parseBabel } from '@babel/parser';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\n\nconst { isMatch } = micromatch;\n\n/**\n * URL-bearing JSX attributes that we localize by default. Intentionally limited\n * to link attributes (`href`) — NOT asset attributes like `src`, which usually\n * point at shared, locale-agnostic assets (e.g. `/docs/images/...`) that would\n * 404 if a locale prefix were added. Projects add their own link attributes\n * with `experimentalLocalizeStaticUrls.attributes`.\n */\nconst DEFAULT_URL_ATTRIBUTES = ['href'];\n\n// Docs routing conventions: page file formats, and the file that serves a\n// folder URL (`/a/` -> `a/index.mdx`).\nexport const PAGE_EXTENSIONS = ['.mdx', '.md'];\nexport const INDEX_PAGE = 'index';\n\n/**\n * The page file a root-relative docs URL points to, relative to the working\n * directory like file mapping keys: `/a/b#x` -> `a/b.mdx`, `a/b.md`, or\n * `a/b/index.mdx`.\n */\nfunction findPage(url: string): string | undefined {\n const base = url.split(/[?#]/)[0].replace(/^\\/+|\\/+$/g, '');\n return PAGE_EXTENSIONS.flatMap((ext) => [\n `${base}${ext}`,\n path.join(base, `${INDEX_PAGE}${ext}`),\n ]).find((page) => fs.existsSync(page));\n}\n\n/**\n * Whether a URL points to a source page with no translation on disk, either at\n * its mapped output path or at the localized URL. URLs with no source page,\n * such as pages generated from an OpenAPI spec, are not missing a translation.\n */\nexport function translationMissing(\n url: string,\n localizedUrl: string,\n localizedFiles: Record<string, string>\n): boolean {\n const sourcePage = findPage(url);\n if (!sourcePage) return false;\n const mappedPage = localizedFiles[sourcePage];\n return !(mappedPage && fs.existsSync(mappedPage)) && !findPage(localizedUrl);\n}\n\n/**\n * Localize URL string literals that live inside an MDX expression's raw source.\n *\n * URLs can be nested arbitrarily deep inside `{...}` expressions — e.g. an\n * `<a href>` buried inside a component prop:\n * <ParamField type={<span><a href=\"/docs/x\">Error</a></span>} />\n * Such hrefs never appear as mdast nodes (they live in the expression's embedded\n * JS), so the mdast visitors can't reach them. We re-parse the expression source\n * with Babel — positions are local to `source`, which avoids any document-offset\n * mapping — find JSX url-attribute string literals at any depth, and surgically\n * rewrite them in place.\n *\n * `rootStringIsUrl` covers `href={\"/docs/x\"}`, where the expression itself is a\n * bare string literal that a url-named attribute should treat as a URL.\n *\n * Only static string literals are localized; dynamically-computed URLs\n * (template literals, identifiers, concatenation) are left untouched — a\n * fundamental limit of static localization, not a parser shortcoming.\n */\nfunction localizeUrlsInExpressionSource(\n source: string,\n transformUrl: (url: string, linkType: 'markdown' | 'href') => string | null,\n urlAttributes: string[],\n rootStringIsUrl: boolean = false\n): string {\n if (!source.trim()) return source;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ast: any;\n try {\n ast = parseBabel(source, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['jsx', 'typescript'],\n });\n } catch {\n // Dynamic / unparseable expression — leave it untouched.\n return source;\n }\n\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const pushLiteralReplacement = (literal: any) => {\n if (\n !literal ||\n // A bare string at statement position is parsed by Babel as a\n // DirectiveLiteral (cf. \"use strict\") rather than a StringLiteral.\n (literal.type !== 'StringLiteral' &&\n literal.type !== 'DirectiveLiteral') ||\n typeof literal.value !== 'string' ||\n typeof literal.start !== 'number' ||\n typeof literal.end !== 'number'\n ) {\n return;\n }\n const newUrl = transformUrl(literal.value, 'href');\n if (!newUrl) return;\n // Preserve the original quote style; URLs never contain quote chars.\n const quote = source[literal.start] === \"'\" ? \"'\" : '\"';\n replacements.push({\n start: literal.start,\n end: literal.end,\n text: `${quote}${newUrl}${quote}`,\n });\n };\n\n // `href={\"/docs/x\"}`: the entire expression is the URL string.\n if (rootStringIsUrl) {\n const program = ast.program;\n const body = (program?.body ?? []) as Array<{\n type: string;\n expression?: unknown;\n }>;\n if (body.length === 1 && body[0]?.type === 'ExpressionStatement') {\n pushLiteralReplacement(body[0].expression);\n } else if (body.length === 0 && program?.directives?.length === 1) {\n // Babel parses a lone string literal as a directive, not a statement.\n pushLiteralReplacement(program.directives[0]?.value);\n }\n }\n\n // Walk the AST for JSX url-attributes anywhere in the expression.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const seen = new Set<any>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const walk = (node: any) => {\n if (!node || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (seen.has(node)) return;\n seen.add(node);\n\n if (\n node.type === 'JSXAttribute' &&\n node.name?.type === 'JSXIdentifier' &&\n isMatch(node.name.name, urlAttributes) &&\n node.value\n ) {\n if (node.value.type === 'StringLiteral') {\n pushLiteralReplacement(node.value);\n } else if (\n node.value.type === 'JSXExpressionContainer' &&\n node.value.expression?.type === 'StringLiteral'\n ) {\n pushLiteralReplacement(node.value.expression);\n }\n }\n\n for (const key in node) {\n if (\n key === 'loc' ||\n key === 'start' ||\n key === 'end' ||\n key === 'range'\n ) {\n continue;\n }\n const child = node[key];\n if (child && typeof child === 'object') walk(child);\n }\n };\n walk(ast.program ?? ast);\n\n if (replacements.length === 0) return source;\n\n // Apply end-to-start so earlier offsets remain valid.\n let result = source;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, text }) => {\n result = result.slice(0, start) + text + result.slice(end);\n });\n return result;\n}\n\nexport type StaticUrlSettings = StaticLocalizationSettings;\n\n/**\n * Localizes static urls in content files.\n * Currently only supported for md and mdx files. (/docs/ -> /[locale]/docs/)\n * @param settings - The settings object containing the project configuration.\n * @returns void\n *\n * @TODO This is an experimental feature, and only works in very specific cases. This needs to be improved before\n * it can be enabled by default.\n *\n * Before this becomes a non-experimental feature, we need to:\n * - Support more file types\n * - Support more complex paths\n */\nexport default async function localizeStaticUrls(\n settings: StaticUrlSettings,\n targetLocales?: string[],\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n const localizeOptions = settings.options?.experimentalLocalizeStaticUrls;\n const skipUntranslatedPages =\n typeof localizeOptions === 'object' &&\n localizeOptions.skipUntranslatedPages === true;\n const urlAttributes = [\n ...DEFAULT_URL_ATTRIBUTES,\n ...((typeof localizeOptions === 'object' && localizeOptions.attributes) ||\n []),\n ];\n\n // Use filtered locales if provided, otherwise use all locales\n const locales = targetLocales || settings.locales;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales, // Always use all locales for mapping, filter later\n settings.defaultLocale\n );\n\n // Process all file types at once with a single call\n const processPromises = [];\n\n // First, process default locale files (from source files)\n // This is needed because they might not be in the fileMapping if they're not being translated\n // Only process default locale if it's in the target locales filter\n if (\n !fileMapping[settings.defaultLocale] &&\n locales.includes(settings.defaultLocale) &&\n !includeFiles // when filtering, skip default-locale pass\n ) {\n const defaultLocaleFiles: string[] = [];\n\n // Collect all .md and .mdx files from sourceFiles\n if (sourceFiles.md) {\n defaultLocaleFiles.push(...sourceFiles.md);\n }\n if (sourceFiles.mdx) {\n defaultLocaleFiles.push(...sourceFiles.mdx);\n }\n\n if (defaultLocaleFiles.length > 0) {\n const defaultPromise = Promise.all(\n defaultLocaleFiles.map(async (filePath: string) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file using default locale\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n settings.defaultLocale, // Process as default locale\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n undefined,\n urlAttributes\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n processPromises.push(defaultPromise);\n }\n }\n\n // Then process all other locales from fileMapping\n const mappingPromises = Object.entries(fileMapping)\n .filter(([locale]) => locales.includes(locale)) // Filter by target locales\n .map(async ([locale, filesMap]) => {\n // Get all files that are md or mdx\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n // Replace the placeholder path with the target path\n await Promise.all(\n targetFiles.map(async (filePath) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file (handles both URLs and hrefs in single AST pass)\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n locale,\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n skipUntranslatedPages ? filesMap : undefined,\n urlAttributes\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n });\n processPromises.push(...mappingPromises);\n\n await Promise.all(processPromises);\n}\n\ninterface UrlTransformResult {\n content: string;\n hasChanges: boolean;\n transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }>;\n}\n\n/**\n * Determines if a URL should be processed based on pattern matching\n */\nfunction shouldProcessUrl(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n baseDomain?: string\n): boolean {\n // Check fragment-only URLs like \"#id-name\"\n if (/^\\s*#/.test(originalUrl)) {\n return false;\n }\n\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n\n // Handle absolute URLs with baseDomain\n let urlToCheck = originalUrl;\n if (baseDomain && originalUrl.startsWith(baseDomain)) {\n urlToCheck = originalUrl.substring(baseDomain.length);\n }\n\n if (targetLocale === defaultLocale) {\n // For default locale processing, check if URL contains the pattern\n return urlToCheck.includes(patternWithoutSlash);\n } else {\n // For non-default locales, check if URL starts with pattern\n return urlToCheck.startsWith(patternWithoutSlash);\n }\n}\n\n/**\n * Determines if a URL should be processed based on the base domain\n */\nfunction shouldProcessAbsoluteUrl(\n originalUrl: string,\n baseDomain: string\n): boolean {\n return originalUrl.startsWith(baseDomain);\n}\n\n/**\n * Checks if a URL should be excluded based on exclusion patterns\n */\nfunction isUrlExcluded(\n originalUrl: string,\n exclude: string[],\n defaultLocale: string\n): boolean {\n const excludePatterns = exclude.map((p) =>\n p.replace(/\\[locale\\]/g, defaultLocale)\n );\n return excludePatterns.some((pattern) => isMatch(originalUrl, pattern));\n}\n\n/**\n * Main URL transformation function that delegates to specific scenarios\n */\nexport function transformUrlPath(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean\n): string | null {\n const originalPathArray = originalUrl\n .split('/')\n .filter((path) => path !== '');\n const patternHeadArray = patternHead.split('/').filter((path) => path !== '');\n\n // check if the pattern head matches the original path\n if (!checkIfPathMatchesPattern(originalPathArray, patternHeadArray)) {\n return null;\n }\n\n if (patternHeadArray.length > originalPathArray.length) {\n return null; // Pattern is longer than the URL path\n }\n\n let result = null;\n if (targetLocale === defaultLocale) {\n if (hideDefaultLocale) {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // remove default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n ...originalPathArray.slice(patternHeadArray.length + 1),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] === defaultLocale) {\n return null;\n }\n\n // insert default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n defaultLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n }\n } else if (hideDefaultLocale) {\n // Avoid duplicating target locale if already present\n if (originalPathArray?.[patternHeadArray.length] === targetLocale) {\n return null;\n }\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n targetLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check default locale\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // replace default locale with target locale\n const newPathArray = [...originalPathArray];\n newPathArray[patternHeadArray.length] = targetLocale;\n\n result = newPathArray.join('/');\n }\n\n // check for leading and trailing slashes\n if (originalUrl.startsWith('/')) {\n result = '/' + result;\n }\n if (originalUrl.endsWith('/')) {\n result = result + '/';\n }\n\n return result;\n}\n\n/**\n * AST-based transformation for MDX files using remark-mdx\n */\nfunction transformMdxUrls(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: string[]\n): UrlTransformResult {\n const transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }> = [];\n\n if (!pattern.startsWith('/')) {\n pattern = '/' + pattern;\n }\n\n const patternHead = pattern.split('[locale]')[0];\n\n // Quick check: if the file doesn't contain the pattern, skip expensive AST parsing\n // For default locale processing, we also need to check if content might need adjustment\n if (targetLocale === defaultLocale) {\n // For default locale files, we always need to check as we're looking for either:\n // - paths without locale (when hideDefaultLocale=false)\n // - paths with default locale (when hideDefaultLocale=true)\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n if (!mdxContent.includes(patternWithoutSlash)) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n } else {\n // For non-default locales, use the original logic\n if (!mdxContent.includes(patternHead.replace(/\\/$/, ''))) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n }\n\n // Parse the MDX content into an AST\n let processedAst: Root;\n let neutralizedAnchors: boolean;\n try {\n const parsed = parseMdxForRoundTrip(mdxContent);\n processedAst = parsed.ast;\n neutralizedAnchors = parsed.neutralized;\n } catch {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls,\n };\n }\n\n // Helper function to transform URL based on pattern\n const transformUrl = (\n originalUrl: string,\n linkType: 'markdown' | 'href'\n ): string | null => {\n // For Markdown links [text](path), only process absolute-root paths starting with '/'\n // Relative markdown links should remain relative to the current page and not be localized.\n if (linkType === 'markdown') {\n const isFragment = /^\\s*#/.test(originalUrl);\n const isAbsoluteRoot = originalUrl.startsWith('/');\n const looksAbsoluteWithDomain = baseDomain\n ? shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n : false;\n if (!isAbsoluteRoot && !looksAbsoluteWithDomain && !isFragment) {\n return null;\n }\n }\n // Check if URL should be processed\n if (\n !shouldProcessUrl(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n baseDomain\n )\n ) {\n return null;\n }\n\n // Skip absolute URLs (http://, https://, //, etc.)\n if (baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)) {\n // Get everything after the base domain\n const afterDomain = originalUrl.substring(baseDomain.length);\n\n const transformedPath = transformUrlPath(\n afterDomain,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n if (!transformedPath) {\n return null;\n }\n if (\n localizedFiles &&\n translationMissing(afterDomain, transformedPath, localizedFiles)\n ) {\n return null;\n }\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: transformedPath,\n type: linkType,\n });\n return transformedPath ? baseDomain + transformedPath : null;\n }\n\n // Exclude colon-prefixed URLs (http://, https://, //, etc.)\n if (originalUrl.split('?')[0].includes(':')) {\n return null;\n }\n\n // Transform the URL based on locale and configuration\n const newUrl = transformUrlPath(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n\n if (!newUrl) {\n return null;\n }\n\n // Check exclusions\n if (isUrlExcluded(originalUrl, exclude, defaultLocale)) {\n return null;\n }\n\n // Links to pages with no translation keep the default locale.\n if (\n localizedFiles &&\n translationMissing(originalUrl, newUrl, localizedFiles)\n ) {\n return null;\n }\n\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: newUrl,\n type: linkType,\n });\n return newUrl;\n };\n\n // Visit markdown link nodes: [text](url)\n visit(processedAst, 'link', (node: Link) => {\n if (node.url) {\n const newUrl = transformUrl(node.url, 'markdown');\n if (newUrl) {\n node.url = newUrl;\n }\n }\n });\n\n // Visit JSX/HTML elements for href attributes: <a href=\"url\"> or <Card href=\"url\">\n visit(processedAst, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node) => {\n const jsxNode = node as MdxJsxFlowElement | MdxJsxTextElement;\n if (!jsxNode.attributes) return;\n for (const attr of jsxNode.attributes) {\n if (attr.type !== 'mdxJsxAttribute' || !attr.value) continue;\n\n // Plain string attribute value, e.g. <a href=\"/docs/x\">\n if (typeof attr.value === 'string') {\n if (isMatch(attr.name, urlAttributes)) {\n const newUrl = transformUrl(attr.value, 'href');\n if (newUrl) {\n attr.value = newUrl;\n }\n }\n continue;\n }\n\n // Expression attribute value. Two shapes are handled:\n // href={\"/docs/x\"} (url attr, bare string)\n // type={<span><a href=\"/docs/x\">…</a></span>} (url attr nested deep\n // inside a non-url prop)\n // The nested case never surfaces as an mdast node — it lives in the\n // expression's embedded JS — so it's localized via the source-level walk.\n if (\n typeof attr.value === 'object' &&\n attr.value.type === 'mdxJsxAttributeValueExpression' &&\n typeof attr.value.value === 'string'\n ) {\n const newValue = localizeUrlsInExpressionSource(\n attr.value.value,\n transformUrl,\n urlAttributes,\n isMatch(attr.name, urlAttributes)\n );\n if (newValue !== attr.value.value) {\n attr.value.value = newValue;\n }\n }\n }\n });\n\n // Visit standalone MDX expressions for URLs inside embedded JSX, e.g.\n // {isBeta && <a href=\"/docs/x\">Beta</a>}\n visit(processedAst, ['mdxFlowExpression', 'mdxTextExpression'], (node) => {\n const exprNode = node as unknown as Literal;\n if (typeof exprNode.value === 'string' && exprNode.value) {\n const newValue = localizeUrlsInExpressionSource(\n exprNode.value,\n transformUrl,\n urlAttributes\n );\n if (newValue !== exprNode.value) {\n exprNode.value = newValue;\n }\n }\n });\n\n // Visit raw JSX nodes for href attributes in JSX strings\n visit(processedAst, 'jsx', (node: Literal) => {\n if (node.value && typeof node.value === 'string') {\n const jsxContent = node.value;\n\n // Use regex to find href attributes in the JSX string\n const hrefRegex = /href\\s*=\\s*[\"']([^\"']+)[\"']/g;\n let match;\n const replacements: Array<{\n start: number;\n end: number;\n oldHrefAttr: string;\n newHrefAttr: string;\n }> = [];\n\n // Reset regex lastIndex to avoid issues with global flag\n hrefRegex.lastIndex = 0;\n\n while ((match = hrefRegex.exec(jsxContent)) !== null) {\n const originalHref = match[1];\n const newUrl = transformUrl(originalHref, 'href');\n\n if (newUrl) {\n // Store replacement info\n const oldHrefAttr = match[0]; // The full match like 'href=\"/quickstart\"'\n const quote = oldHrefAttr.includes('\"') ? '\"' : \"'\";\n const newHrefAttr = `href=${quote}${newUrl}${quote}`;\n\n replacements.push({\n start: match.index!,\n end: match.index! + oldHrefAttr.length,\n oldHrefAttr,\n newHrefAttr,\n });\n }\n }\n\n // Apply replacements in reverse order (from end to start) to avoid position shifts\n if (replacements.length > 0) {\n let newJsxContent = jsxContent;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, newHrefAttr }) => {\n newJsxContent =\n newJsxContent.slice(0, start) +\n newHrefAttr +\n newJsxContent.slice(end);\n });\n\n node.value = newJsxContent;\n }\n }\n });\n\n // Convert the modified AST back to MDX string\n let content: string;\n try {\n const stringifyProcessor = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n // Handler to prevent escaping (avoids '<' -> '\\<')\n text(node: Literal) {\n return node.value;\n },\n },\n });\n\n const outTree = stringifyProcessor.runSync(processedAst) as Root;\n content = stringifyProcessor.stringify(outTree);\n if (neutralizedAnchors) {\n content = restoreAnchorIds(content);\n }\n } catch (error) {\n console.warn(\n `Failed to stringify MDX content: ${error instanceof Error ? error.message : String(error)}`\n );\n console.warn(\n 'Returning original content unchanged due to stringify error.'\n );\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n\n // Handle newline formatting to match original input\n if (content.endsWith('\\n') && !mdxContent.endsWith('\\n')) {\n content = content.slice(0, -1);\n }\n\n // Preserve leading newlines from original content\n if (mdxContent.startsWith('\\n') && !content.startsWith('\\n')) {\n content = '\\n' + content;\n }\n\n return {\n content,\n hasChanges: transformedUrls.length > 0,\n transformedUrls,\n };\n}\n\n// AST-based transformation for MDX files using remark\nfunction localizeStaticUrlsForFile(\n file: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]', // eg /docs/[locale] or /[locale]\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: string[]\n): UrlTransformResult {\n // Use AST-based transformation for MDX files\n return transformMdxUrls(\n file,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n baseDomain || '',\n localizedFiles,\n urlAttributes\n );\n}\n\nfunction checkIfPathMatchesPattern(\n originalUrlArray: string[],\n patternHeadArray: string[]\n): boolean {\n // check if the pattern head matches the original path\n for (let i = 0; i < patternHeadArray.length; i++) {\n if (patternHeadArray[i] !== originalUrlArray?.[i]) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,EAAE,YAAY;;;;;;;;AASpB,MAAM,yBAAyB,CAAC,OAAO;AAIvC,MAAa,kBAAkB,CAAC,QAAQ,MAAM;AAC9C,MAAa,aAAa;;;;;;AAO1B,SAAS,SAAS,KAAiC;CACjD,MAAM,OAAO,IAAI,MAAM,OAAO,CAAC,GAAG,QAAQ,cAAc,GAAG;AAC3D,QAAO,gBAAgB,SAAS,QAAQ,CACtC,GAAG,OAAO,OACVA,OAAK,KAAK,MAAM,GAAG,aAAa,MAAM,CACvC,CAAC,CAAC,MAAM,SAASC,KAAG,WAAW,KAAK,CAAC;;;;;;;AAQxC,SAAgB,mBACd,KACA,cACA,gBACS;CACT,MAAM,aAAa,SAAS,IAAI;AAChC,KAAI,CAAC,WAAY,QAAO;CACxB,MAAM,aAAa,eAAe;AAClC,QAAO,EAAE,cAAcA,KAAG,WAAW,WAAW,KAAK,CAAC,SAAS,aAAa;;;;;;;;;;;;;;;;;;;;;AAsB9E,SAAS,+BACP,QACA,cACA,eACA,kBAA2B,OACnB;AACR,KAAI,CAAC,OAAO,MAAM,CAAE,QAAO;CAG3B,IAAI;AACJ,KAAI;AACF,QAAMC,MAAW,QAAQ;GACvB,YAAY;GACZ,eAAe;GACf,SAAS,CAAC,OAAO,aAAa;GAC/B,CAAC;SACI;AAEN,SAAO;;CAGT,MAAM,eAAoE,EAAE;CAG5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AAC,CACxC,IAAI,UAAU,CACd,IAAI,uBAAuB,CAC3B,IAAI,sBAAsB,CAC1B,IAAI,iBAAiB,EACpB,UAAU,EAER,KAAK,MAAe;AAClB,UAAO,KAAK;KAEf,EACF,CAAC;EAEJ,MAAM,UAAU,mBAAmB,QAAQ,aAAa;AACxD,YAAU,mBAAmB,UAAU,QAAQ;AAC/C,MAAI,mBACF,WAAU,iBAAiB,QAAQ;UAE9B,OAAO;AACd,UAAQ,KACN,oCAAoC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GAC3F;AACD,UAAQ,KACN,+DACD;AACD,SAAO;GACL,SAAS;GACT,YAAY;GACZ,iBAAiB,EAAE;GACpB;;AAIH,KAAI,QAAQ,SAAS,KAAK,IAAI,CAAC,WAAW,SAAS,KAAK,CACtD,WAAU,QAAQ,MAAM,GAAG,GAAG;AAIhC,KAAI,WAAW,WAAW,KAAK,IAAI,CAAC,QAAQ,WAAW,KAAK,CAC1D,WAAU,OAAO;AAGnB,QAAO;EACL;EACA,YAAY,gBAAgB,SAAS;EACrC;EACD;;AAIH,SAAS,0BACP,MACA,eACA,cACA,mBACA,UAAkB,aAClB,UAAoB,EAAE,EACtB,YACA,gBACA,eACoB;AAEpB,QAAO,iBACL,MACA,eACA,cACA,mBACA,SACA,SACA,cAAc,IACd,gBACA,cACD;;AAGH,SAAS,0BACP,kBACA,kBACS;AAET,MAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,IAC3C,KAAI,iBAAiB,OAAO,mBAAmB,GAC7C,QAAO;AAIX,QAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gt",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.25.0",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"bin": "bin/main.js",
|
|
6
6
|
"files": [
|
|
@@ -119,8 +119,8 @@
|
|
|
119
119
|
"@generaltranslation/icu": "0.1.2",
|
|
120
120
|
"@generaltranslation/python-extractor": "0.2.58",
|
|
121
121
|
"@generaltranslation/supported-locales": "2.1.39",
|
|
122
|
-
"@generaltranslation/vue-extractor": "0.1.17",
|
|
123
122
|
"generaltranslation": "9.5.3",
|
|
123
|
+
"@generaltranslation/vue-extractor": "0.1.17",
|
|
124
124
|
"gt-remark": "1.0.12"
|
|
125
125
|
},
|
|
126
126
|
"devDependencies": {
|