gt 2.14.58 → 2.14.60
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 +279 -0
- package/dist/cli/base.d.ts +8 -0
- package/dist/cli/base.js +44 -1
- package/dist/cli/base.js.map +1 -1
- package/dist/cli/commands/download.js +1 -2
- package/dist/cli/commands/download.js.map +1 -1
- package/dist/cli/commands/enqueue.js +1 -2
- package/dist/cli/commands/enqueue.js.map +1 -1
- package/dist/cli/commands/stage.js +6 -2
- package/dist/cli/commands/stage.js.map +1 -1
- package/dist/cli/flags.js +1 -1
- package/dist/cli/flags.js.map +1 -1
- package/dist/cli/inline.js +2 -3
- package/dist/cli/inline.js.map +1 -1
- package/dist/cli/node.js +2 -1
- package/dist/cli/node.js.map +1 -1
- package/dist/cli/react.js +2 -1
- package/dist/cli/react.js.map +1 -1
- package/dist/config/defaults.js +2 -1
- package/dist/config/defaults.js.map +1 -1
- package/dist/config/generateSettings.d.ts +1 -0
- package/dist/config/generateSettings.js +2 -0
- package/dist/config/generateSettings.js.map +1 -1
- package/dist/console/index.d.ts +0 -2
- package/dist/console/index.js +4 -6
- package/dist/console/index.js.map +1 -1
- package/dist/extraction/postProcess.js +0 -1
- package/dist/extraction/postProcess.js.map +1 -1
- package/dist/formats/files/aggregateFiles.d.ts +0 -1
- package/dist/formats/files/aggregateFiles.js +1 -6
- package/dist/formats/files/aggregateFiles.js.map +1 -1
- package/dist/formats/files/collectFiles.js +2 -5
- package/dist/formats/files/collectFiles.js.map +1 -1
- package/dist/fs/config/parseFilesConfig.js +0 -4
- package/dist/fs/config/parseFilesConfig.js.map +1 -1
- package/dist/fs/config/updateConfig.d.ts +1 -0
- package/dist/fs/config/updateConfig.js +3 -2
- package/dist/fs/config/updateConfig.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/git/mergeDrivers.d.ts +11 -0
- package/dist/git/mergeDrivers.js +281 -0
- package/dist/git/mergeDrivers.js.map +1 -0
- package/dist/git/setupMergeDrivers.d.ts +27 -0
- package/dist/git/setupMergeDrivers.js +147 -0
- package/dist/git/setupMergeDrivers.js.map +1 -0
- package/dist/next/parse/handleInitGT.js +1 -6
- package/dist/next/parse/handleInitGT.js.map +1 -1
- package/dist/react/jsx/utils/constants.d.ts +3 -9
- package/dist/react/jsx/utils/constants.js +7 -14
- package/dist/react/jsx/utils/constants.js.map +1 -1
- package/dist/react/jsx/utils/jsxParsing/autoInsertion.d.ts +2 -2
- package/dist/react/jsx/utils/jsxParsing/autoInsertion.js +7 -7
- package/dist/react/jsx/utils/jsxParsing/autoInsertion.js.map +1 -1
- package/dist/react/jsx/utils/jsxParsing/parseJsx.js +2 -2
- package/dist/react/jsx/utils/jsxParsing/parseJsx.js.map +1 -1
- package/dist/react/jsx/utils/stringParsing/derivation/containsDeriveCall.d.ts +1 -1
- package/dist/react/jsx/utils/stringParsing/derivation/containsDeriveCall.js +1 -1
- package/dist/react/jsx/utils/stringParsing/derivation/containsDeriveCall.js.map +1 -1
- package/dist/react/jsx/utils/stringParsing/derivation/isDeriveCall.js.map +1 -1
- package/dist/react/parse/createDictionaryUpdates.js +0 -1
- package/dist/react/parse/createDictionaryUpdates.js.map +1 -1
- package/dist/react/parse/createInlineUpdates.js +1 -1
- package/dist/react/parse/createInlineUpdates.js.map +1 -1
- package/dist/translation/parse.js.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/parsing.d.ts +2 -0
- package/dist/types/parsing.js.map +1 -1
- package/dist/utils/fetch.js +1 -1
- package/dist/utils/fetch.js.map +1 -1
- package/package.json +7 -7
- package/dist/extraction/index.d.ts +0 -3
- package/dist/extraction/index.js +0 -3
- package/dist/extraction/types.d.ts +0 -1
- package/dist/extraction/types.js +0 -1
- package/dist/utils/headers.d.ts +0 -1
- package/dist/utils/headers.js +0 -10
- package/dist/utils/headers.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enqueue.js","names":[],"sources":["../../../src/cli/commands/enqueue.ts"],"sourcesContent":["import { EnqueueFilesResult } from 'generaltranslation/types';\nimport {\n Settings,\n SupportedLibraries,\n TranslateFlags,\n} from '../../types/index.js';\nimport { runEnqueueWorkflow } from '../../workflows/enqueue.js';\nimport { collectFiles } from '../../formats/files/collectFiles.js';\nimport { noFilesError
|
|
1
|
+
{"version":3,"file":"enqueue.js","names":[],"sources":["../../../src/cli/commands/enqueue.ts"],"sourcesContent":["import { EnqueueFilesResult } from 'generaltranslation/types';\nimport {\n Settings,\n SupportedLibraries,\n TranslateFlags,\n} from '../../types/index.js';\nimport { runEnqueueWorkflow } from '../../workflows/enqueue.js';\nimport { collectFiles } from '../../formats/files/collectFiles.js';\nimport { noFilesError } from '../../console/index.js';\nimport { hasValidCredentials, hasValidLocales } from './utils/validation.js';\nimport { exitSync, logErrorAndExit } from '../../console/logging.js';\nimport { warnManualReviewSetup } from '../../translation/reviewSetupWarning.js';\n\n/**\n * Enqueues translations for a given set of files\n * @param options - The options for the enqueue operation\n * @param settings - The settings for the enqueue operation\n * @returns {Promise<EnqueueFilesResult>} The enqueue result\n */\nexport async function handleEnqueue(\n options: TranslateFlags,\n settings: Settings,\n library: SupportedLibraries\n): Promise<EnqueueFilesResult> {\n if (!hasValidLocales(settings)) return exitSync(1);\n // Validate credentials if not in dry run\n if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);\n if (!settings.files) {\n return logErrorAndExit(noFilesError);\n }\n\n // Collect the data for all files we need to enqueue\n const { files } = await collectFiles(options, settings, library);\n\n // Point at dashboard review setup when uploading review-gated content\n await warnManualReviewSetup(settings, files);\n\n return runEnqueueWorkflow({ files, options, settings });\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,eAAsB,cACpB,SACA,UACA,SAC6B;AAC7B,KAAI,CAAC,gBAAgB,SAAS,CAAE,QAAO,SAAS,EAAE;AAElD,KAAI,CAAC,QAAQ,UAAU,CAAC,oBAAoB,SAAS,CAAE,QAAO,SAAS,EAAE;AACzE,KAAI,CAAC,SAAS,MACZ,QAAO,gBAAgB,aAAa;CAItC,MAAM,EAAE,UAAU,MAAM,aAAa,SAAS,UAAU,QAAQ;AAGhE,OAAM,sBAAsB,UAAU,MAAM;AAE5C,QAAO,mBAAmB;EAAE;EAAO;EAAS;EAAU,CAAC"}
|
|
@@ -38,12 +38,16 @@ async function handleStage(options, settings, library, stage) {
|
|
|
38
38
|
fileName: data.fileName
|
|
39
39
|
})), branchData.currentBranch.id);
|
|
40
40
|
const templateData = allFiles.find((file) => file.fileId === TEMPLATE_FILE_ID);
|
|
41
|
-
if (
|
|
41
|
+
if (settings.omitConfigIds) await updateConfig(settings.config, {
|
|
42
|
+
_versionId: null,
|
|
43
|
+
_branchId: null
|
|
44
|
+
});
|
|
45
|
+
else if (templateData?.versionId) await updateConfig(settings.config, {
|
|
42
46
|
_versionId: templateData.versionId,
|
|
43
47
|
_branchId: branchData.currentBranch.id
|
|
44
48
|
});
|
|
45
49
|
}
|
|
46
|
-
if (!settings.branchOptions.enabled) await updateConfig(settings.config, { _branchId: null });
|
|
50
|
+
if (!settings.branchOptions.enabled && !settings.omitConfigIds) await updateConfig(settings.config, { _branchId: null });
|
|
47
51
|
return {
|
|
48
52
|
fileVersionData,
|
|
49
53
|
jobData,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stage.js","names":[],"sources":["../../../src/cli/commands/stage.ts"],"sourcesContent":["import { logger } from '../../console/logger.js';\nimport { exitSync, logCollectedFiles } from '../../console/logging.js';\nimport {\n Settings,\n SupportedLibraries,\n TranslateFlags,\n} from '../../types/index.js';\nimport { runStageFilesWorkflow } from '../../workflows/stage.js';\nimport { writeStagedEntries } from '../../fs/config/downloadedVersions.js';\nimport type { EnqueueFilesResult } from 'generaltranslation/types';\nimport updateConfig from '../../fs/config/updateConfig.js';\nimport { FileTranslationData } from '../../workflows/download.js';\nimport { BranchData } from '../../types/branch.js';\nimport { TEMPLATE_FILE_ID } from '../../utils/constants.js';\nimport { collectFiles } from '../../formats/files/collectFiles.js';\nimport { convertToFileTranslationData } from '../../formats/files/convertToFileTranslationData.js';\nimport { hasValidCredentials, hasValidLocales } from './utils/validation.js';\nimport { warnManualReviewSetup } from '../../translation/reviewSetupWarning.js';\n\nexport async function handleStage(\n options: TranslateFlags,\n settings: Settings,\n library: SupportedLibraries,\n stage: boolean\n): Promise<{\n fileVersionData: FileTranslationData | undefined;\n jobData: EnqueueFilesResult | undefined;\n branchData: BranchData | undefined;\n publishMap: Map<string, boolean>;\n} | null> {\n if (!hasValidLocales(settings)) return exitSync(1);\n // Validate credentials if not in dry run\n if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);\n\n const {\n files: allFiles,\n reactComponents,\n publishMap,\n } = await collectFiles(options, settings, library);\n\n // Point at dashboard review setup when uploading review-gated content\n await warnManualReviewSetup(settings, allFiles);\n\n // Dry run\n if (options.dryRun) {\n logger.success(`Dry run: No files were sent to General Translation.`);\n logCollectedFiles(allFiles, reactComponents);\n return null;\n }\n\n if (allFiles.length === 0 && !settings.publish) {\n logger.error(\n 'No files to translate were found. Check your configuration and try again.'\n );\n }\n\n // Send translations to General Translation\n let fileVersionData: FileTranslationData | undefined;\n let jobData: EnqueueFilesResult | undefined;\n let branchData: BranchData | undefined;\n if (allFiles.length > 0) {\n const { branchData: branchDataResult, enqueueResult } =\n await runStageFilesWorkflow({ files: allFiles, options, settings });\n jobData = enqueueResult;\n branchData = branchDataResult;\n\n fileVersionData = convertToFileTranslationData(allFiles);\n\n // Write staged entries to the lockfile\n if (stage) {\n const stagedFiles = Object.entries(fileVersionData).map(\n ([fileId, data]) => ({\n fileId,\n versionId: data.versionId,\n fileName: data.fileName,\n })\n );\n writeStagedEntries(settings, stagedFiles, branchData.currentBranch.id);\n }\n const templateData = allFiles.find(\n (file) => file.fileId === TEMPLATE_FILE_ID\n );\n if (templateData?.versionId) {\n await updateConfig(settings.config, {\n _versionId: templateData.versionId,\n _branchId: branchData.currentBranch.id,\n });\n }\n }\n\n // Always delete branch id from config if branching is disabled\n // Avoids incorrect CDN queries at runtime\n if (!settings.branchOptions.enabled) {\n await updateConfig(settings.config, {\n _branchId: null,\n });\n }\n\n return {\n fileVersionData,\n jobData,\n branchData,\n publishMap,\n };\n}\n"],"mappings":";;;;;;;;;;;AAmBA,eAAsB,YACpB,SACA,UACA,SACA,OAMQ;AACR,KAAI,CAAC,gBAAgB,SAAS,CAAE,QAAO,SAAS,EAAE;AAElD,KAAI,CAAC,QAAQ,UAAU,CAAC,oBAAoB,SAAS,CAAE,QAAO,SAAS,EAAE;CAEzE,MAAM,EACJ,OAAO,UACP,iBACA,eACE,MAAM,aAAa,SAAS,UAAU,QAAQ;AAGlD,OAAM,sBAAsB,UAAU,SAAS;AAG/C,KAAI,QAAQ,QAAQ;AAClB,SAAO,QAAQ,sDAAsD;AACrE,oBAAkB,UAAU,gBAAgB;AAC5C,SAAO;;AAGT,KAAI,SAAS,WAAW,KAAK,CAAC,SAAS,QACrC,QAAO,MACL,4EACD;CAIH,IAAI;CACJ,IAAI;CACJ,IAAI;AACJ,KAAI,SAAS,SAAS,GAAG;EACvB,MAAM,EAAE,YAAY,kBAAkB,kBACpC,MAAM,sBAAsB;GAAE,OAAO;GAAU;GAAS;GAAU,CAAC;AACrE,YAAU;AACV,eAAa;AAEb,oBAAkB,6BAA6B,SAAS;AAGxD,MAAI,MAQF,oBAAmB,UAPC,OAAO,QAAQ,gBAAgB,CAAC,KACjD,CAAC,QAAQ,WAAW;GACnB;GACA,WAAW,KAAK;GAChB,UAAU,KAAK;GAChB,EAEqC,EAAE,WAAW,cAAc,GAAG;EAExE,MAAM,eAAe,SAAS,MAC3B,SAAS,KAAK,WAAW,iBAC3B;AACD,MAAI,cAAc,
|
|
1
|
+
{"version":3,"file":"stage.js","names":[],"sources":["../../../src/cli/commands/stage.ts"],"sourcesContent":["import { logger } from '../../console/logger.js';\nimport { exitSync, logCollectedFiles } from '../../console/logging.js';\nimport {\n Settings,\n SupportedLibraries,\n TranslateFlags,\n} from '../../types/index.js';\nimport { runStageFilesWorkflow } from '../../workflows/stage.js';\nimport { writeStagedEntries } from '../../fs/config/downloadedVersions.js';\nimport type { EnqueueFilesResult } from 'generaltranslation/types';\nimport updateConfig from '../../fs/config/updateConfig.js';\nimport { FileTranslationData } from '../../workflows/download.js';\nimport { BranchData } from '../../types/branch.js';\nimport { TEMPLATE_FILE_ID } from '../../utils/constants.js';\nimport { collectFiles } from '../../formats/files/collectFiles.js';\nimport { convertToFileTranslationData } from '../../formats/files/convertToFileTranslationData.js';\nimport { hasValidCredentials, hasValidLocales } from './utils/validation.js';\nimport { warnManualReviewSetup } from '../../translation/reviewSetupWarning.js';\n\nexport async function handleStage(\n options: TranslateFlags,\n settings: Settings,\n library: SupportedLibraries,\n stage: boolean\n): Promise<{\n fileVersionData: FileTranslationData | undefined;\n jobData: EnqueueFilesResult | undefined;\n branchData: BranchData | undefined;\n publishMap: Map<string, boolean>;\n} | null> {\n if (!hasValidLocales(settings)) return exitSync(1);\n // Validate credentials if not in dry run\n if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);\n\n const {\n files: allFiles,\n reactComponents,\n publishMap,\n } = await collectFiles(options, settings, library);\n\n // Point at dashboard review setup when uploading review-gated content\n await warnManualReviewSetup(settings, allFiles);\n\n // Dry run\n if (options.dryRun) {\n logger.success(`Dry run: No files were sent to General Translation.`);\n logCollectedFiles(allFiles, reactComponents);\n return null;\n }\n\n if (allFiles.length === 0 && !settings.publish) {\n logger.error(\n 'No files to translate were found. Check your configuration and try again.'\n );\n }\n\n // Send translations to General Translation\n let fileVersionData: FileTranslationData | undefined;\n let jobData: EnqueueFilesResult | undefined;\n let branchData: BranchData | undefined;\n if (allFiles.length > 0) {\n const { branchData: branchDataResult, enqueueResult } =\n await runStageFilesWorkflow({ files: allFiles, options, settings });\n jobData = enqueueResult;\n branchData = branchDataResult;\n\n fileVersionData = convertToFileTranslationData(allFiles);\n\n // Write staged entries to the lockfile\n if (stage) {\n const stagedFiles = Object.entries(fileVersionData).map(\n ([fileId, data]) => ({\n fileId,\n versionId: data.versionId,\n fileName: data.fileName,\n })\n );\n writeStagedEntries(settings, stagedFiles, branchData.currentBranch.id);\n }\n const templateData = allFiles.find(\n (file) => file.fileId === TEMPLATE_FILE_ID\n );\n if (settings.omitConfigIds) {\n // Remove persisted config IDs only after staging has succeeded, so\n // failed and empty runs keep the previous pinned version/branch state\n await updateConfig(settings.config, {\n _versionId: null,\n _branchId: null,\n });\n } else if (templateData?.versionId) {\n await updateConfig(settings.config, {\n _versionId: templateData.versionId,\n _branchId: branchData.currentBranch.id,\n });\n }\n }\n\n // Always delete branch id from config if branching is disabled\n // Avoids incorrect CDN queries at runtime\n if (!settings.branchOptions.enabled && !settings.omitConfigIds) {\n await updateConfig(settings.config, {\n _branchId: null,\n });\n }\n\n return {\n fileVersionData,\n jobData,\n branchData,\n publishMap,\n };\n}\n"],"mappings":";;;;;;;;;;;AAmBA,eAAsB,YACpB,SACA,UACA,SACA,OAMQ;AACR,KAAI,CAAC,gBAAgB,SAAS,CAAE,QAAO,SAAS,EAAE;AAElD,KAAI,CAAC,QAAQ,UAAU,CAAC,oBAAoB,SAAS,CAAE,QAAO,SAAS,EAAE;CAEzE,MAAM,EACJ,OAAO,UACP,iBACA,eACE,MAAM,aAAa,SAAS,UAAU,QAAQ;AAGlD,OAAM,sBAAsB,UAAU,SAAS;AAG/C,KAAI,QAAQ,QAAQ;AAClB,SAAO,QAAQ,sDAAsD;AACrE,oBAAkB,UAAU,gBAAgB;AAC5C,SAAO;;AAGT,KAAI,SAAS,WAAW,KAAK,CAAC,SAAS,QACrC,QAAO,MACL,4EACD;CAIH,IAAI;CACJ,IAAI;CACJ,IAAI;AACJ,KAAI,SAAS,SAAS,GAAG;EACvB,MAAM,EAAE,YAAY,kBAAkB,kBACpC,MAAM,sBAAsB;GAAE,OAAO;GAAU;GAAS;GAAU,CAAC;AACrE,YAAU;AACV,eAAa;AAEb,oBAAkB,6BAA6B,SAAS;AAGxD,MAAI,MAQF,oBAAmB,UAPC,OAAO,QAAQ,gBAAgB,CAAC,KACjD,CAAC,QAAQ,WAAW;GACnB;GACA,WAAW,KAAK;GAChB,UAAU,KAAK;GAChB,EAEqC,EAAE,WAAW,cAAc,GAAG;EAExE,MAAM,eAAe,SAAS,MAC3B,SAAS,KAAK,WAAW,iBAC3B;AACD,MAAI,SAAS,cAGX,OAAM,aAAa,SAAS,QAAQ;GAClC,YAAY;GACZ,WAAW;GACZ,CAAC;WACO,cAAc,UACvB,OAAM,aAAa,SAAS,QAAQ;GAClC,YAAY,aAAa;GACzB,WAAW,WAAW,cAAc;GACrC,CAAC;;AAMN,KAAI,CAAC,SAAS,cAAc,WAAW,CAAC,SAAS,cAC/C,OAAM,aAAa,SAAS,QAAQ,EAClC,WAAW,MACZ,CAAC;AAGJ,QAAO;EACL;EACA;EACA;EACA;EACD"}
|
package/dist/cli/flags.js
CHANGED
|
@@ -12,7 +12,7 @@ function attachTranslateFlags(command) {
|
|
|
12
12
|
if (isNaN(parsedValue)) throw new Error("Invalid timeout: not a number.");
|
|
13
13
|
if (parsedValue < 0) throw new Error("Invalid timeout: must be a positive number.");
|
|
14
14
|
return parsedValue;
|
|
15
|
-
}, DEFAULT_TIMEOUT).option("--save-local", "Detect and save local edits before enqueuing translations", false).option("--publish", "Publish translations to the CDN", false).option("--experimental-localize-static-urls", "Triggering this will run a script after the cli tool that localizes all urls in content files. Currently only supported for md and mdx files.", false).option("--experimental-hide-default-locale", "When localizing static locales, hide the default locale from the path", false).option("--experimental-flatten-json-files", "Triggering this will flatten the json files into a single file. This is useful for projects that have a lot of json files.", false).option("--experimental-localize-static-imports", "Triggering this will run a script after the cli tool that localizes all static imports in content files. Currently only supported for md and mdx files.", false).option("--experimental-localize-relative-assets", "Triggering this will rewrite relative image asset URLs in translated md/mdx files to valid paths.", false).option("--force", "Force a retranslation, invalidating all existing cached translations if they exist.", false).option("--force-download", "Force download and overwrite local files, bypassing gt-lock.json checks.", false).option("--experimental-clear-locale-dirs", "Clear locale directories before downloading new translations", false).option("--branch <branch>", "Specify a custom branch to use for translations").option("--disable-branch-detection", "Disable additional branch detection and optimizations and use the manually specified branch", false).option("--enable-branching", "Enable branching for the project").option("--remote-name <name>", "Specify a custom remote name to use for branch detection", DEFAULT_GIT_REMOTE_NAME).option("--tag [value]", "Tag this translation run (auto-resolves from git if no value provided)").option("-m, --message <message>", "Message to attach to the translation tag");
|
|
15
|
+
}, DEFAULT_TIMEOUT).option("--save-local", "Detect and save local edits before enqueuing translations", false).option("--publish", "Publish translations to the CDN", false).option("--experimental-localize-static-urls", "Triggering this will run a script after the cli tool that localizes all urls in content files. Currently only supported for md and mdx files.", false).option("--experimental-hide-default-locale", "When localizing static locales, hide the default locale from the path", false).option("--experimental-flatten-json-files", "Triggering this will flatten the json files into a single file. This is useful for projects that have a lot of json files.", false).option("--experimental-localize-static-imports", "Triggering this will run a script after the cli tool that localizes all static imports in content files. Currently only supported for md and mdx files.", false).option("--experimental-localize-relative-assets", "Triggering this will rewrite relative image asset URLs in translated md/mdx files to valid paths.", false).option("--force", "Force a retranslation, invalidating all existing cached translations if they exist.", false).option("--force-download", "Force download and overwrite local files, bypassing gt-lock.json checks.", false).option("--omit-config-ids", "Do not write _versionId or _branchId to gt.config.json").option("--experimental-clear-locale-dirs", "Clear locale directories before downloading new translations", false).option("--branch <branch>", "Specify a custom branch to use for translations").option("--disable-branch-detection", "Disable additional branch detection and optimizations and use the manually specified branch", false).option("--enable-branching", "Enable branching for the project").option("--remote-name <name>", "Specify a custom remote name to use for branch detection", DEFAULT_GIT_REMOTE_NAME).option("--tag [value]", "Tag this translation run (auto-resolves from git if no value provided)").option("-m, --message <message>", "Message to attach to the translation tag");
|
|
16
16
|
return command;
|
|
17
17
|
}
|
|
18
18
|
/**
|
package/dist/cli/flags.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flags.js","names":[],"sources":["../../src/cli/flags.ts"],"sourcesContent":["import { Command } from 'commander';\nimport findFilepath from '../fs/findFilepath.js';\nimport { DEFAULT_GIT_REMOTE_NAME } from '../utils/constants.js';\n\nconst DEFAULT_TIMEOUT = 900;\n\nexport function attachSharedFlags(command: Command) {\n command\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--api-key <key>', 'API key for General Translation cloud service')\n .option('--project-id <id>', 'General Translation project ID');\n return command;\n}\n\nexport function attachTranslateFlags(command: Command) {\n attachSharedFlags(command)\n .option('--version-id <id>', 'General Translation version ID')\n .option(\n '--default-language, --default-locale <locale>',\n 'Default locale (e.g., en)'\n )\n .option(\n '--new, --locales <locales...>',\n 'Space-separated list of locales (e.g., en fr es)'\n )\n .option(\n '--dry-run',\n 'Dry run, do not send updates to the General Translation API',\n false\n )\n .option(\n '--timeout <seconds>',\n 'Translation wait timeout in seconds',\n (value) => {\n const parsedValue = parseInt(value, 10);\n if (isNaN(parsedValue)) {\n throw new Error('Invalid timeout: not a number.');\n }\n if (parsedValue < 0) {\n throw new Error('Invalid timeout: must be a positive number.');\n }\n return parsedValue;\n },\n DEFAULT_TIMEOUT\n )\n .option(\n '--save-local',\n 'Detect and save local edits before enqueuing translations',\n false\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .option(\n '--experimental-localize-static-urls',\n 'Triggering this will run a script after the cli tool that localizes all urls in content files. Currently only supported for md and mdx files.',\n false\n )\n .option(\n '--experimental-hide-default-locale',\n 'When localizing static locales, hide the default locale from the path',\n false\n )\n .option(\n '--experimental-flatten-json-files',\n 'Triggering this will flatten the json files into a single file. This is useful for projects that have a lot of json files.',\n false\n )\n .option(\n '--experimental-localize-static-imports',\n 'Triggering this will run a script after the cli tool that localizes all static imports in content files. Currently only supported for md and mdx files.',\n false\n )\n .option(\n '--experimental-localize-relative-assets',\n 'Triggering this will rewrite relative image asset URLs in translated md/mdx files to valid paths.',\n false\n )\n .option(\n '--force',\n 'Force a retranslation, invalidating all existing cached translations if they exist.',\n false\n )\n .option(\n '--force-download',\n 'Force download and overwrite local files, bypassing gt-lock.json checks.',\n false\n )\n .option(\n '--experimental-clear-locale-dirs',\n 'Clear locale directories before downloading new translations',\n false\n )\n .option(\n '--branch <branch>',\n 'Specify a custom branch to use for translations'\n )\n .option(\n '--disable-branch-detection',\n 'Disable additional branch detection and optimizations and use the manually specified branch',\n false\n )\n .option('--enable-branching', 'Enable branching for the project')\n .option(\n '--remote-name <name>',\n 'Specify a custom remote name to use for branch detection',\n DEFAULT_GIT_REMOTE_NAME\n )\n .option(\n '--tag [value]',\n 'Tag this translation run (auto-resolves from git if no value provided)'\n )\n .option(\n '-m, --message <message>',\n 'Message to attach to the translation tag'\n );\n return command;\n}\n\n/**\n * Attaches flags necessary for parsing inline content\n * @param command - The command to attach the flags to\n * @returns The command with the inline content parsing flags attached\n */\nfunction attachInlineContentParsingFlags(command: Command) {\n return command\n .option(\n '--tsconfig, --jsconfig <path>',\n 'Path to custom jsconfig or tsconfig file',\n findFilepath(['./tsconfig.json', './jsconfig.json'])\n )\n .option('--dictionary <path>', 'Path to dictionary file')\n .option(\n '--src <paths...>',\n \"Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'\"\n )\n .option(\n '--inline',\n 'Include inline content in translations (e.g., inline jsx translations, inline string translations, etc.)',\n true\n );\n}\n\n/**\n * Attaches flags necessary for validating a project\n * @param command\n * @returns The command with the validate flags attached\n */\nexport function attachValidateFlags(command: Command) {\n return attachInlineContentParsingFlags(\n command.option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n );\n}\n\n/**\n * Attaches flags necessary for translating a project\n * @param command\n * @returns The command with the translate flags attached\n */\nexport function attachInlineTranslateFlags(command: Command) {\n return attachInlineContentParsingFlags(\n command.option(\n '--ignore-errors',\n 'Ignore errors encountered while scanning for inline content',\n false\n )\n );\n}\n"],"mappings":";;;AAIA,MAAM,kBAAkB;AAExB,SAAgB,kBAAkB,SAAkB;AAClD,SACG,OACC,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACA,OAAO,mBAAmB,gDAAgD,CAC1E,OAAO,qBAAqB,iCAAiC;AAChE,QAAO;;AAGT,SAAgB,qBAAqB,SAAkB;AACrD,mBAAkB,QAAQ,CACvB,OAAO,qBAAqB,iCAAiC,CAC7D,OACC,iDACA,4BACD,CACA,OACC,iCACA,mDACD,CACA,OACC,aACA,+DACA,MACD,CACA,OACC,uBACA,wCACC,UAAU;EACT,MAAM,cAAc,SAAS,OAAO,GAAG;AACvC,MAAI,MAAM,YAAY,CACpB,OAAM,IAAI,MAAM,iCAAiC;AAEnD,MAAI,cAAc,EAChB,OAAM,IAAI,MAAM,8CAA8C;AAEhE,SAAO;IAET,gBACD,CACA,OACC,gBACA,6DACA,MACD,CACA,OAAO,aAAa,mCAAmC,MAAM,CAC7D,OACC,uCACA,iJACA,MACD,CACA,OACC,sCACA,yEACA,MACD,CACA,OACC,qCACA,8HACA,MACD,CACA,OACC,0CACA,2JACA,MACD,CACA,OACC,2CACA,qGACA,MACD,CACA,OACC,WACA,uFACA,MACD,CACA,OACC,oBACA,4EACA,MACD,CACA,OACC,oCACA,gEACA,MACD,CACA,OACC,qBACA,kDACD,CACA,OACC,8BACA,+FACA,MACD,CACA,OAAO,sBAAsB,mCAAmC,CAChE,OACC,wBACA,4DACA,wBACD,CACA,OACC,iBACA,yEACD,CACA,OACC,2BACA,2CACD;AACH,QAAO;;;;;;;AAQT,SAAS,gCAAgC,SAAkB;AACzD,QAAO,QACJ,OACC,iCACA,4CACA,aAAa,CAAC,mBAAmB,kBAAkB,CAAC,CACrD,CACA,OAAO,uBAAuB,0BAA0B,CACxD,OACC,oBACA,0MACD,CACA,OACC,YACA,4GACA,KACD;;;;;;;AAQL,SAAgB,oBAAoB,SAAkB;AACpD,QAAO,gCACL,QAAQ,OACN,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACF;;;;;;;AAQH,SAAgB,2BAA2B,SAAkB;AAC3D,QAAO,gCACL,QAAQ,OACN,mBACA,+DACA,MACD,CACF"}
|
|
1
|
+
{"version":3,"file":"flags.js","names":[],"sources":["../../src/cli/flags.ts"],"sourcesContent":["import { Command } from 'commander';\nimport findFilepath from '../fs/findFilepath.js';\nimport { DEFAULT_GIT_REMOTE_NAME } from '../utils/constants.js';\n\nconst DEFAULT_TIMEOUT = 900;\n\nexport function attachSharedFlags(command: Command) {\n command\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--api-key <key>', 'API key for General Translation cloud service')\n .option('--project-id <id>', 'General Translation project ID');\n return command;\n}\n\nexport function attachTranslateFlags(command: Command) {\n attachSharedFlags(command)\n .option('--version-id <id>', 'General Translation version ID')\n .option(\n '--default-language, --default-locale <locale>',\n 'Default locale (e.g., en)'\n )\n .option(\n '--new, --locales <locales...>',\n 'Space-separated list of locales (e.g., en fr es)'\n )\n .option(\n '--dry-run',\n 'Dry run, do not send updates to the General Translation API',\n false\n )\n .option(\n '--timeout <seconds>',\n 'Translation wait timeout in seconds',\n (value) => {\n const parsedValue = parseInt(value, 10);\n if (isNaN(parsedValue)) {\n throw new Error('Invalid timeout: not a number.');\n }\n if (parsedValue < 0) {\n throw new Error('Invalid timeout: must be a positive number.');\n }\n return parsedValue;\n },\n DEFAULT_TIMEOUT\n )\n .option(\n '--save-local',\n 'Detect and save local edits before enqueuing translations',\n false\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .option(\n '--experimental-localize-static-urls',\n 'Triggering this will run a script after the cli tool that localizes all urls in content files. Currently only supported for md and mdx files.',\n false\n )\n .option(\n '--experimental-hide-default-locale',\n 'When localizing static locales, hide the default locale from the path',\n false\n )\n .option(\n '--experimental-flatten-json-files',\n 'Triggering this will flatten the json files into a single file. This is useful for projects that have a lot of json files.',\n false\n )\n .option(\n '--experimental-localize-static-imports',\n 'Triggering this will run a script after the cli tool that localizes all static imports in content files. Currently only supported for md and mdx files.',\n false\n )\n .option(\n '--experimental-localize-relative-assets',\n 'Triggering this will rewrite relative image asset URLs in translated md/mdx files to valid paths.',\n false\n )\n .option(\n '--force',\n 'Force a retranslation, invalidating all existing cached translations if they exist.',\n false\n )\n .option(\n '--force-download',\n 'Force download and overwrite local files, bypassing gt-lock.json checks.',\n false\n )\n .option(\n '--omit-config-ids',\n 'Do not write _versionId or _branchId to gt.config.json'\n )\n .option(\n '--experimental-clear-locale-dirs',\n 'Clear locale directories before downloading new translations',\n false\n )\n .option(\n '--branch <branch>',\n 'Specify a custom branch to use for translations'\n )\n .option(\n '--disable-branch-detection',\n 'Disable additional branch detection and optimizations and use the manually specified branch',\n false\n )\n .option('--enable-branching', 'Enable branching for the project')\n .option(\n '--remote-name <name>',\n 'Specify a custom remote name to use for branch detection',\n DEFAULT_GIT_REMOTE_NAME\n )\n .option(\n '--tag [value]',\n 'Tag this translation run (auto-resolves from git if no value provided)'\n )\n .option(\n '-m, --message <message>',\n 'Message to attach to the translation tag'\n );\n return command;\n}\n\n/**\n * Attaches flags necessary for parsing inline content\n * @param command - The command to attach the flags to\n * @returns The command with the inline content parsing flags attached\n */\nfunction attachInlineContentParsingFlags(command: Command) {\n return command\n .option(\n '--tsconfig, --jsconfig <path>',\n 'Path to custom jsconfig or tsconfig file',\n findFilepath(['./tsconfig.json', './jsconfig.json'])\n )\n .option('--dictionary <path>', 'Path to dictionary file')\n .option(\n '--src <paths...>',\n \"Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'\"\n )\n .option(\n '--inline',\n 'Include inline content in translations (e.g., inline jsx translations, inline string translations, etc.)',\n true\n );\n}\n\n/**\n * Attaches flags necessary for validating a project\n * @param command\n * @returns The command with the validate flags attached\n */\nexport function attachValidateFlags(command: Command) {\n return attachInlineContentParsingFlags(\n command.option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n );\n}\n\n/**\n * Attaches flags necessary for translating a project\n * @param command\n * @returns The command with the translate flags attached\n */\nexport function attachInlineTranslateFlags(command: Command) {\n return attachInlineContentParsingFlags(\n command.option(\n '--ignore-errors',\n 'Ignore errors encountered while scanning for inline content',\n false\n )\n );\n}\n"],"mappings":";;;AAIA,MAAM,kBAAkB;AAExB,SAAgB,kBAAkB,SAAkB;AAClD,SACG,OACC,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACA,OAAO,mBAAmB,gDAAgD,CAC1E,OAAO,qBAAqB,iCAAiC;AAChE,QAAO;;AAGT,SAAgB,qBAAqB,SAAkB;AACrD,mBAAkB,QAAQ,CACvB,OAAO,qBAAqB,iCAAiC,CAC7D,OACC,iDACA,4BACD,CACA,OACC,iCACA,mDACD,CACA,OACC,aACA,+DACA,MACD,CACA,OACC,uBACA,wCACC,UAAU;EACT,MAAM,cAAc,SAAS,OAAO,GAAG;AACvC,MAAI,MAAM,YAAY,CACpB,OAAM,IAAI,MAAM,iCAAiC;AAEnD,MAAI,cAAc,EAChB,OAAM,IAAI,MAAM,8CAA8C;AAEhE,SAAO;IAET,gBACD,CACA,OACC,gBACA,6DACA,MACD,CACA,OAAO,aAAa,mCAAmC,MAAM,CAC7D,OACC,uCACA,iJACA,MACD,CACA,OACC,sCACA,yEACA,MACD,CACA,OACC,qCACA,8HACA,MACD,CACA,OACC,0CACA,2JACA,MACD,CACA,OACC,2CACA,qGACA,MACD,CACA,OACC,WACA,uFACA,MACD,CACA,OACC,oBACA,4EACA,MACD,CACA,OACC,qBACA,yDACD,CACA,OACC,oCACA,gEACA,MACD,CACA,OACC,qBACA,kDACD,CACA,OACC,8BACA,+FACA,MACD,CACA,OAAO,sBAAsB,mCAAmC,CAChE,OACC,wBACA,4DACA,wBACD,CACA,OACC,iBACA,yEACD,CACA,OACC,2BACA,2CACD;AACH,QAAO;;;;;;;AAQT,SAAS,gCAAgC,SAAkB;AACzD,QAAO,QACJ,OACC,iCACA,4CACA,aAAa,CAAC,mBAAmB,kBAAkB,CAAC,CACrD,CACA,OAAO,uBAAuB,0BAA0B,CACxD,OACC,oBACA,0MACD,CACA,OACC,YACA,4GACA,KACD;;;;;;;AAQL,SAAgB,oBAAoB,SAAkB;AACpD,QAAO,gCACL,QAAQ,OACN,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACF;;;;;;;AAQH,SAAgB,2BAA2B,SAAkB;AAC3D,QAAO,gCACL,QAAQ,OACN,mBACA,+DACA,MACD,CACF"}
|
package/dist/cli/inline.js
CHANGED
|
@@ -62,9 +62,8 @@ var InlineCLI = class extends BaseCLI {
|
|
|
62
62
|
const newData = {};
|
|
63
63
|
for (const update of updates) {
|
|
64
64
|
const { source, metadata } = update;
|
|
65
|
-
const { hash
|
|
66
|
-
if (
|
|
67
|
-
else if (hash) newData[hash] = source;
|
|
65
|
+
const { hash } = metadata;
|
|
66
|
+
if (hash) newData[hash] = source;
|
|
68
67
|
}
|
|
69
68
|
if (settings.files && settings.files.placeholderPaths.gt) {
|
|
70
69
|
const translationFiles = resolveLocaleFiles(settings.files.placeholderPaths, settings.defaultLocale);
|
package/dist/cli/inline.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inline.js","names":[],"sources":["../../src/cli/inline.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { BaseCLI } from './base.js';\nimport { SupportedLibraries, TranslateFlags, Options } from '../types/index.js';\nimport {\n attachInlineTranslateFlags,\n attachTranslateFlags,\n attachValidateFlags,\n} from './flags.js';\nimport { displayHeader, exitSync } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { intro } from '@clack/prompts';\nimport chalk from 'chalk';\nimport { resolveLocaleFiles } from '../fs/config/parseFilesConfig.js';\nimport { noFilesError } from '../console/index.js';\nimport { saveJSON } from '../fs/saveJSON.js';\nimport loadJSON from '../fs/loadJSON.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport { aggregateInlineTranslations } from '../translation/stage.js';\nimport { validateProject } from '../translation/validate.js';\nimport { Libraries, InlineLibrary } from '../types/libraries.js';\n\n/**\n * Stand in for a CLI tool that does any sort of inline content translations\n */\nexport class InlineCLI extends BaseCLI {\n constructor(\n command: Command,\n library: InlineLibrary,\n additionalModules?: SupportedLibraries[]\n ) {\n super(command, library, additionalModules);\n }\n public init() {\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupGenerateSourceCommand();\n this.setupValidateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n\n protected setupStageCommand(): void {\n attachInlineTranslateFlags(\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 )\n ).action(async (options: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachInlineTranslateFlags(\n attachTranslateFlags(\n this.program\n .command('translate')\n .description(\n 'Scans the project for a dictionary and inline translations and sends the updates to the General Translation API for translation.'\n )\n )\n ).action(async (options: TranslateFlags) => {\n displayHeader('Translating project...');\n await this.handleTranslate(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupValidateCommand(): void {\n attachValidateFlags(\n this.program\n .command('validate [files...]')\n .description(\n 'Scans the project for a dictionary and/or inline content and validates the project for errors.'\n )\n ).action(async (files: string[], options: Options) => {\n // intro here since we don't want to show the ascii title\n intro(chalk.cyan('Validating project...'));\n await this.handleValidate(options, files);\n logger.endCommand('Done!');\n });\n }\n\n protected setupGenerateSourceCommand(): void {\n attachInlineTranslateFlags(\n attachTranslateFlags(\n this.program\n .command('generate')\n .description(\n 'Generate a translation file for the source locale. This command should be used if you are handling your own translations.'\n )\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Generating source templates...');\n await this.handleGenerateSourceCommand(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected async handleGenerateSourceCommand(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const updates = await aggregateInlineTranslations(\n initOptions,\n settings,\n fallbackToGtReact(this.library)\n );\n\n // Convert updates to the proper data format\n const newData: Record<string, unknown> = {};\n for (const update of updates) {\n const { source, metadata } = update;\n const { hash
|
|
1
|
+
{"version":3,"file":"inline.js","names":[],"sources":["../../src/cli/inline.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { BaseCLI } from './base.js';\nimport { SupportedLibraries, TranslateFlags, Options } from '../types/index.js';\nimport {\n attachInlineTranslateFlags,\n attachTranslateFlags,\n attachValidateFlags,\n} from './flags.js';\nimport { displayHeader, exitSync } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { intro } from '@clack/prompts';\nimport chalk from 'chalk';\nimport { resolveLocaleFiles } from '../fs/config/parseFilesConfig.js';\nimport { noFilesError } from '../console/index.js';\nimport { saveJSON } from '../fs/saveJSON.js';\nimport loadJSON from '../fs/loadJSON.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport { aggregateInlineTranslations } from '../translation/stage.js';\nimport { validateProject } from '../translation/validate.js';\nimport { Libraries, InlineLibrary } from '../types/libraries.js';\n\n/**\n * Stand in for a CLI tool that does any sort of inline content translations\n */\nexport class InlineCLI extends BaseCLI {\n constructor(\n command: Command,\n library: InlineLibrary,\n additionalModules?: SupportedLibraries[]\n ) {\n super(command, library, additionalModules);\n }\n public init() {\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupGenerateSourceCommand();\n this.setupValidateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n\n protected setupStageCommand(): void {\n attachInlineTranslateFlags(\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 )\n ).action(async (options: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachInlineTranslateFlags(\n attachTranslateFlags(\n this.program\n .command('translate')\n .description(\n 'Scans the project for a dictionary and inline translations and sends the updates to the General Translation API for translation.'\n )\n )\n ).action(async (options: TranslateFlags) => {\n displayHeader('Translating project...');\n await this.handleTranslate(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupValidateCommand(): void {\n attachValidateFlags(\n this.program\n .command('validate [files...]')\n .description(\n 'Scans the project for a dictionary and/or inline content and validates the project for errors.'\n )\n ).action(async (files: string[], options: Options) => {\n // intro here since we don't want to show the ascii title\n intro(chalk.cyan('Validating project...'));\n await this.handleValidate(options, files);\n logger.endCommand('Done!');\n });\n }\n\n protected setupGenerateSourceCommand(): void {\n attachInlineTranslateFlags(\n attachTranslateFlags(\n this.program\n .command('generate')\n .description(\n 'Generate a translation file for the source locale. This command should be used if you are handling your own translations.'\n )\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Generating source templates...');\n await this.handleGenerateSourceCommand(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected async handleGenerateSourceCommand(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const updates = await aggregateInlineTranslations(\n initOptions,\n settings,\n fallbackToGtReact(this.library)\n );\n\n // Convert updates to the proper data format\n const newData: Record<string, unknown> = {};\n for (const update of updates) {\n const { source, metadata } = update;\n const { hash } = metadata;\n if (hash) {\n newData[hash] = source;\n }\n }\n\n // Save source file if files.json is provided\n if (settings.files && settings.files.placeholderPaths.gt) {\n const translationFiles = resolveLocaleFiles(\n settings.files.placeholderPaths,\n settings.defaultLocale\n );\n if (!translationFiles.gt) {\n logger.error(noFilesError);\n exitSync(1);\n }\n await saveJSON(translationFiles.gt, newData);\n logger.step('Source file saved successfully!');\n // Also save translations (after merging with existing translations)\n for (const locale of settings.locales) {\n const translationsFile = resolveLocaleFiles(\n settings.files.placeholderPaths,\n locale\n );\n\n if (!translationsFile.gt) {\n continue;\n }\n const existingTranslations = loadJSON(translationsFile.gt);\n const mergedTranslations = {\n ...newData,\n ...existingTranslations,\n };\n // Filter out keys that don't exist in newData\n const filteredTranslations = Object.fromEntries(\n Object.entries(mergedTranslations).filter(([key]) => newData[key])\n );\n await saveJSON(translationsFile.gt, filteredTranslations);\n }\n logger.step('Merged translations successfully!');\n }\n }\n\n protected async handleValidate(\n initOptions: Options,\n files?: string[]\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // First run the base class's handleTranslate method\n const options = { ...initOptions, ...settings };\n\n // Fallback to gt-react\n const pkg = fallbackToGtReact(this.library);\n\n if (files && files.length > 0) {\n // Validate specific files using createInlineUpdates\n await validateProject(options, pkg, files);\n } else {\n // Validate whole project as before\n await validateProject(options, pkg);\n }\n }\n}\n\nfunction fallbackToGtReact(library: SupportedLibraries): InlineLibrary {\n return [\n Libraries.GT_NEXT,\n Libraries.GT_NODE,\n Libraries.GT_REACT_NATIVE,\n Libraries.GT_TANSTACK_START,\n Libraries.GT_FLASK,\n Libraries.GT_FASTAPI,\n ].includes(library as Libraries)\n ? (library as\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_NODE\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START\n | typeof Libraries.GT_FLASK\n | typeof Libraries.GT_FASTAPI)\n : Libraries.GT_REACT;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,IAAa,YAAb,cAA+B,QAAQ;CACrC,YACE,SACA,SACA,mBACA;AACA,QAAM,SAAS,SAAS,kBAAkB;;CAE5C,OAAc;AACZ,OAAK,mBAAmB;AACxB,OAAK,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AAKpB,MAAI,SAAS,SAAS,SAAS,MAAM,iBAAiB,IAAI;GACxD,MAAM,mBAAmB,mBACvB,SAAS,MAAM,kBACf,SAAS,cACV;AACD,OAAI,CAAC,iBAAiB,IAAI;AACxB,WAAO,MAAM,aAAa;AAC1B,aAAS,EAAE;;AAEb,SAAM,SAAS,iBAAiB,IAAI,QAAQ;AAC5C,UAAO,KAAK,kCAAkC;AAE9C,QAAK,MAAM,UAAU,SAAS,SAAS;IACrC,MAAM,mBAAmB,mBACvB,SAAS,MAAM,kBACf,OACD;AAED,QAAI,CAAC,iBAAiB,GACpB;IAEF,MAAM,uBAAuB,SAAS,iBAAiB,GAAG;IAC1D,MAAM,qBAAqB;KACzB,GAAG;KACH,GAAG;KACJ;IAED,MAAM,uBAAuB,OAAO,YAClC,OAAO,QAAQ,mBAAmB,CAAC,QAAQ,CAAC,SAAS,QAAQ,KAAK,CACnE;AACD,UAAM,SAAS,iBAAiB,IAAI,qBAAqB;;AAE3D,UAAO,KAAK,oCAAoC;;;CAIpD,MAAgB,eACd,aACA,OACe;EACf,MAAM,WAAW,MAAM,iBAAiB,aAAa,KAAA,GAAW,EAC9D,eAAe,MAChB,CAAC;EAGF,MAAM,UAAU;GAAE,GAAG;GAAa,GAAG;GAAU;EAG/C,MAAM,MAAM,kBAAkB,KAAK,QAAQ;AAE3C,MAAI,SAAS,MAAM,SAAS,EAE1B,OAAM,gBAAgB,SAAS,KAAK,MAAM;MAG1C,OAAM,gBAAgB,SAAS,IAAI;;;AAKzC,SAAS,kBAAkB,SAA4C;AACrE,QAAO;;;;;;;EAON,CAAC,SAAS,QAAqB,GAC3B,UAAA"}
|
package/dist/cli/node.js
CHANGED
|
@@ -8,8 +8,9 @@ import { checkMonorepoVersionConsistency } from "../utils/monorepoVersionCheck.j
|
|
|
8
8
|
var NodeCLI = class extends InlineCLI {
|
|
9
9
|
constructor(command, library, additionalModules) {
|
|
10
10
|
super(command, library, additionalModules);
|
|
11
|
-
this.program.hook("preAction", () => {
|
|
11
|
+
this.program.hook("preAction", (_thisCommand, actionCommand) => {
|
|
12
12
|
if (this.program.opts().skipVersionCheck) return;
|
|
13
|
+
if (actionCommand.parent?.name() === "git") return;
|
|
13
14
|
checkMonorepoVersionConsistency(NODE_LIBRARIES);
|
|
14
15
|
});
|
|
15
16
|
}
|
package/dist/cli/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","names":[],"sources":["../../src/cli/node.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { SupportedLibraries } from '../types/index.js';\nimport { InlineCLI } from './inline.js';\nimport { Libraries, NODE_LIBRARIES } from '../types/libraries.js';\nimport { checkMonorepoVersionConsistency } from '../utils/monorepoVersionCheck.js';\n\n/**\n * CLI tool for managing translations with gt-node\n */\nexport class NodeCLI extends InlineCLI {\n constructor(\n command: Command,\n library: typeof Libraries.GT_NODE,\n additionalModules?: SupportedLibraries[]\n ) {\n super(command, library, additionalModules);\n\n this.program.hook('preAction', () => {\n if (this.program.opts().skipVersionCheck) return;\n checkMonorepoVersionConsistency(NODE_LIBRARIES);\n });\n }\n}\n"],"mappings":";;;;;;;AASA,IAAa,UAAb,cAA6B,UAAU;CACrC,YACE,SACA,SACA,mBACA;AACA,QAAM,SAAS,SAAS,kBAAkB;AAE1C,OAAK,QAAQ,KAAK,
|
|
1
|
+
{"version":3,"file":"node.js","names":[],"sources":["../../src/cli/node.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { SupportedLibraries } from '../types/index.js';\nimport { InlineCLI } from './inline.js';\nimport { Libraries, NODE_LIBRARIES } from '../types/libraries.js';\nimport { checkMonorepoVersionConsistency } from '../utils/monorepoVersionCheck.js';\n\n/**\n * CLI tool for managing translations with gt-node\n */\nexport class NodeCLI extends InlineCLI {\n constructor(\n command: Command,\n library: typeof Libraries.GT_NODE,\n additionalModules?: SupportedLibraries[]\n ) {\n super(command, library, additionalModules);\n\n this.program.hook('preAction', (_thisCommand, actionCommand) => {\n if (this.program.opts().skipVersionCheck) return;\n if (actionCommand.parent?.name() === 'git') return;\n checkMonorepoVersionConsistency(NODE_LIBRARIES);\n });\n }\n}\n"],"mappings":";;;;;;;AASA,IAAa,UAAb,cAA6B,UAAU;CACrC,YACE,SACA,SACA,mBACA;AACA,QAAM,SAAS,SAAS,kBAAkB;AAE1C,OAAK,QAAQ,KAAK,cAAc,cAAc,kBAAkB;AAC9D,OAAI,KAAK,QAAQ,MAAM,CAAC,iBAAkB;AAC1C,OAAI,cAAc,QAAQ,MAAM,KAAK,MAAO;AAC5C,mCAAgC,eAAe;IAC/C"}
|
package/dist/cli/react.js
CHANGED
|
@@ -13,8 +13,9 @@ const pkg = "gt-react";
|
|
|
13
13
|
var ReactCLI = class extends InlineCLI {
|
|
14
14
|
constructor(command, library, additionalModules) {
|
|
15
15
|
super(command, library, additionalModules);
|
|
16
|
-
this.program.hook("preAction", () => {
|
|
16
|
+
this.program.hook("preAction", (_thisCommand, actionCommand) => {
|
|
17
17
|
if (this.program.opts().skipVersionCheck) return;
|
|
18
|
+
if (actionCommand.parent?.name() === "git") return;
|
|
18
19
|
checkMonorepoVersionConsistency([...REACT_LIBRARIES, "gt-i18n"]);
|
|
19
20
|
});
|
|
20
21
|
}
|
package/dist/cli/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react.js","names":[],"sources":["../../src/cli/react.ts"],"sourcesContent":["import { Command } from 'commander';\nimport {\n Framework,\n SupportedFrameworks,\n WrapOptions,\n SupportedLibraries,\n TranslateFlags,\n} from '../types/index.js';\nimport { displayHeader, exitSync, promptConfirm } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport chalk from 'chalk';\nimport { formatFiles } from '../hooks/postProcess.js';\nimport { wrapContentReact } from '../react/parse/wrapContent.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport { attachInlineTranslateFlags, attachTranslateFlags } from './flags.js';\nimport { InlineCLI } from './inline.js';\nimport { Libraries, REACT_LIBRARIES } from '../types/libraries.js';\nimport { checkMonorepoVersionConsistency } from '../utils/monorepoVersionCheck.js';\n\nconst pkg = Libraries.GT_REACT;\n\nexport class ReactCLI extends InlineCLI {\n constructor(\n command: Command,\n library: Framework,\n additionalModules?: SupportedLibraries[]\n ) {\n super(command, library, additionalModules);\n\n this.program.hook('preAction', () => {\n if (this.program.opts().skipVersionCheck) return;\n checkMonorepoVersionConsistency([...REACT_LIBRARIES, Libraries.GT_I18N]);\n });\n }\n public init() {\n super.init();\n this.setupSetupProjectCommand();\n }\n\n protected wrapContent(\n options: WrapOptions,\n framework: SupportedFrameworks,\n errors: string[],\n warnings: string[]\n ): Promise<{ filesUpdated: string[] }> {\n return wrapContentReact(options, pkg, framework, errors, warnings);\n }\n\n protected setupSetupProjectCommand(): void {\n attachInlineTranslateFlags(\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n )\n ).action(async (options: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(options);\n logger.endCommand('Done!');\n });\n }\n\n protected async handleScanCommand(options: WrapOptions): Promise<void> {\n // Ask user for confirmation using inquirer\n const answer = await promptConfirm({\n message: chalk.yellow(\n 'Warning: This operation will modify your source files! Make sure you have committed or stashed your current changes. Do you want to continue?'\n ),\n defaultValue: true,\n });\n\n if (!answer) {\n logger.error('Operation cancelled.');\n exitSync(0);\n }\n\n // ----- Create a starter gt.config.json file -----\n await generateSettings(options);\n\n // ----- //\n const includeTId = await promptConfirm({\n message: 'Do you want to include an unique id for each <T> tag?',\n defaultValue: true,\n });\n options.disableIds = !includeTId;\n\n const errors: string[] = [];\n const warnings: string[] = [];\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated } = await this.wrapContent(\n options,\n 'react',\n errors,\n warnings\n );\n\n if (errors.length > 0) {\n logger.error(chalk.red('Failed to write files:\\n') + errors.join('\\n'));\n }\n\n // Format updated files if formatters are available\n if (!options.disableFormatting) await formatFiles(filesUpdated);\n\n logger.success(\n `Success! Added <T> tags and updated ${chalk.bold.cyan(\n filesUpdated.length\n )} files:\\n` +\n filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\\n')\n );\n if (filesUpdated.length > 0) {\n logger.step(chalk.green('Verify the changes before committing.'));\n }\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow('Warnings encountered:') +\n '\\n' +\n warnings\n .map((warning) => `${chalk.yellow('-')} ${warning}`)\n .join('\\n')\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,MAAA;AAEN,IAAa,WAAb,cAA8B,UAAU;CACtC,YACE,SACA,SACA,mBACA;AACA,QAAM,SAAS,SAAS,kBAAkB;AAE1C,OAAK,QAAQ,KAAK,
|
|
1
|
+
{"version":3,"file":"react.js","names":[],"sources":["../../src/cli/react.ts"],"sourcesContent":["import { Command } from 'commander';\nimport {\n Framework,\n SupportedFrameworks,\n WrapOptions,\n SupportedLibraries,\n TranslateFlags,\n} from '../types/index.js';\nimport { displayHeader, exitSync, promptConfirm } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport chalk from 'chalk';\nimport { formatFiles } from '../hooks/postProcess.js';\nimport { wrapContentReact } from '../react/parse/wrapContent.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport { attachInlineTranslateFlags, attachTranslateFlags } from './flags.js';\nimport { InlineCLI } from './inline.js';\nimport { Libraries, REACT_LIBRARIES } from '../types/libraries.js';\nimport { checkMonorepoVersionConsistency } from '../utils/monorepoVersionCheck.js';\n\nconst pkg = Libraries.GT_REACT;\n\nexport class ReactCLI extends InlineCLI {\n constructor(\n command: Command,\n library: Framework,\n additionalModules?: SupportedLibraries[]\n ) {\n super(command, library, additionalModules);\n\n this.program.hook('preAction', (_thisCommand, actionCommand) => {\n if (this.program.opts().skipVersionCheck) return;\n if (actionCommand.parent?.name() === 'git') return;\n checkMonorepoVersionConsistency([...REACT_LIBRARIES, Libraries.GT_I18N]);\n });\n }\n public init() {\n super.init();\n this.setupSetupProjectCommand();\n }\n\n protected wrapContent(\n options: WrapOptions,\n framework: SupportedFrameworks,\n errors: string[],\n warnings: string[]\n ): Promise<{ filesUpdated: string[] }> {\n return wrapContentReact(options, pkg, framework, errors, warnings);\n }\n\n protected setupSetupProjectCommand(): void {\n attachInlineTranslateFlags(\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n )\n ).action(async (options: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(options);\n logger.endCommand('Done!');\n });\n }\n\n protected async handleScanCommand(options: WrapOptions): Promise<void> {\n // Ask user for confirmation using inquirer\n const answer = await promptConfirm({\n message: chalk.yellow(\n 'Warning: This operation will modify your source files! Make sure you have committed or stashed your current changes. Do you want to continue?'\n ),\n defaultValue: true,\n });\n\n if (!answer) {\n logger.error('Operation cancelled.');\n exitSync(0);\n }\n\n // ----- Create a starter gt.config.json file -----\n await generateSettings(options);\n\n // ----- //\n const includeTId = await promptConfirm({\n message: 'Do you want to include an unique id for each <T> tag?',\n defaultValue: true,\n });\n options.disableIds = !includeTId;\n\n const errors: string[] = [];\n const warnings: string[] = [];\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated } = await this.wrapContent(\n options,\n 'react',\n errors,\n warnings\n );\n\n if (errors.length > 0) {\n logger.error(chalk.red('Failed to write files:\\n') + errors.join('\\n'));\n }\n\n // Format updated files if formatters are available\n if (!options.disableFormatting) await formatFiles(filesUpdated);\n\n logger.success(\n `Success! Added <T> tags and updated ${chalk.bold.cyan(\n filesUpdated.length\n )} files:\\n` +\n filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\\n')\n );\n if (filesUpdated.length > 0) {\n logger.step(chalk.green('Verify the changes before committing.'));\n }\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow('Warnings encountered:') +\n '\\n' +\n warnings\n .map((warning) => `${chalk.yellow('-')} ${warning}`)\n .join('\\n')\n );\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KAAK,KAChD,aAAa,OACd,CAAC,aACA,aAAa,KAAK,SAAS,GAAG,MAAM,MAAM,IAAI,CAAC,GAAG,OAAO,CAAC,KAAK,KAAK,CACvE;AACD,MAAI,aAAa,SAAS,EACxB,QAAO,KAAK,MAAM,MAAM,wCAAwC,CAAC;AAGnE,MAAI,SAAS,SAAS,EACpB,QAAO,KACL,MAAM,OAAO,wBAAwB,GACnC,OACA,SACG,KAAK,YAAY,GAAG,MAAM,OAAO,IAAI,CAAC,GAAG,UAAU,CACnD,KAAK,KAAK,CAChB"}
|
package/dist/config/defaults.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaults.js","names":[],"sources":["../../src/config/defaults.ts"],"sourcesContent":["import { BaseParsingFlags, GTParsingFlags } from '../types/parsing.js';\n\n/**\n * Default parsing flags for GT files\n * @property {boolean | { jsx?: boolean; strings?: boolean }} autoderive - Whether to enable autoderive. A plain boolean enables/disables both; an object enables selectively.\n * @property {boolean} includeSourceCodeContext - Include surrounding source code lines as context for translations.\n */\nexport const GT_PARSING_FLAGS_DEFAULT: GTParsingFlags = {\n autoderive: false,\n includeSourceCodeContext: false,\n enableAutoJsxInjection: false,\n};\n\n/**\n * Default parsing flags for all files\n */\nexport const BASE_PARSING_FLAGS_DEFAULT: BaseParsingFlags = {};\n"],"mappings":";;;;;;AAOA,MAAa,2BAA2C;CACtD,YAAY;CACZ,0BAA0B;CAC1B,wBAAwB;
|
|
1
|
+
{"version":3,"file":"defaults.js","names":[],"sources":["../../src/config/defaults.ts"],"sourcesContent":["import { BaseParsingFlags, GTParsingFlags } from '../types/parsing.js';\n\n/**\n * Default parsing flags for GT files\n * @property {boolean | { jsx?: boolean; strings?: boolean }} autoderive - Whether to enable autoderive. A plain boolean enables/disables both; an object enables selectively.\n * @property {boolean} includeSourceCodeContext - Include surrounding source code lines as context for translations.\n */\nexport const GT_PARSING_FLAGS_DEFAULT: GTParsingFlags = {\n autoderive: false,\n includeSourceCodeContext: false,\n enableAutoJsxInjection: false,\n legacyGtReactImportSource: false,\n};\n\n/**\n * Default parsing flags for all files\n */\nexport const BASE_PARSING_FLAGS_DEFAULT: BaseParsingFlags = {};\n"],"mappings":";;;;;;AAOA,MAAa,2BAA2C;CACtD,YAAY;CACZ,0BAA0B;CAC1B,wBAAwB;CACxB,2BAA2B;CAC5B;;;;AAKD,MAAa,6BAA+C,EAAE"}
|
|
@@ -93,6 +93,7 @@ async function generateSettings(flags, cwd = process.cwd(), options) {
|
|
|
93
93
|
if (flags.publish) mergedOptions.publish = true;
|
|
94
94
|
else if (gtConfig.publish !== void 0) mergedOptions.publish = gtConfig.publish;
|
|
95
95
|
else mergedOptions.publish = void 0;
|
|
96
|
+
mergedOptions.omitConfigIds = flags.omitConfigIds === true || gtConfig.omitConfigIds === true;
|
|
96
97
|
const compositePatterns = Object.entries(mergedOptions.options?.jsonSchema || {}).filter(([, schema]) => schema.composite).map(([key]) => key);
|
|
97
98
|
mergedOptions.files = mergedOptions.files ? resolveFiles(normalizeFilesOptions(mergedOptions.files), mergedOptions.defaultLocale, mergedOptions.locales, cwd, compositePatterns, mergedOptions.requiresReview) : {
|
|
98
99
|
resolvedPaths: {},
|
|
@@ -119,6 +120,7 @@ async function generateSettings(flags, cwd = process.cwd(), options) {
|
|
|
119
120
|
experimentalClearLocaleDirs: gtConfig.options?.experimentalClearLocaleDirs || flags.experimentalClearLocaleDirs,
|
|
120
121
|
clearLocaleDirsExclude: gtConfig.options?.clearLocaleDirsExclude || flags.clearLocaleDirsExclude
|
|
121
122
|
};
|
|
123
|
+
if (mergedOptions.omitConfigIds && (mergedOptions.publish === true || mergedOptions.files.gtJson.publish === true)) logger.warn(chalk.yellow("Config IDs will be omitted even though CDN publishing is enabled. Remote cache/CDN consumers may load the latest available translations instead of a pinned version."));
|
|
122
124
|
if (mergedOptions.options) {
|
|
123
125
|
if (mergedOptions.options.jsonSchema) for (const fileGlob of Object.keys(mergedOptions.options.jsonSchema)) {
|
|
124
126
|
const jsonSchema = mergedOptions.options.jsonSchema[fileGlob];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateSettings.js","names":[],"sources":["../../src/config/generateSettings.ts"],"sourcesContent":["import {\n displayProjectId,\n exitSync,\n logErrorAndExit,\n warnApiKeyInConfig,\n warnDeprecatedField,\n} from '../console/logging.js';\nimport { loadConfig } from '../fs/config/loadConfig.js';\nimport { FilesOptions, Settings } from '../types/index.js';\nimport {\n defaultBaseUrl,\n libraryDefaultLocale,\n} from 'generaltranslation/internal';\nimport { resolveFiles } from '../fs/config/parseFilesConfig.js';\nimport { validateSettings } from './validateSettings.js';\nimport {\n DEFAULT_GIT_REMOTE_NAME,\n GT_DASHBOARD_URL,\n} from '../utils/constants.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport crypto from 'node:crypto';\nimport { execSync } from 'node:child_process';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport { resolveConfig } from './resolveConfig.js';\nimport { gt } from '../utils/gt.js';\nimport { generatePreset } from './optionPresets.js';\nimport { GT_PARSING_FLAGS_DEFAULT } from './defaults.js';\nimport { normalizeFilesOptions } from '../formats/files/transformFormat.js';\nimport { determineLibrary } from '../fs/determineFramework/index.js';\nimport { logger } from '../console/logger.js';\n\nexport const DEFAULT_SRC_PATTERNS = [\n 'src/**/*.{js,jsx,ts,tsx}',\n 'app/**/*.{js,jsx,ts,tsx}',\n 'pages/**/*.{js,jsx,ts,tsx}',\n 'components/**/*.{js,jsx,ts,tsx}',\n];\n\nexport const DEFAULT_PYTHON_SRC_PATTERNS = ['**/*.py'];\nexport const DEFAULT_PYTHON_SRC_EXCLUDES = [\n 'venv/**',\n '.venv/**',\n '__pycache__/**',\n '**/migrations/**',\n '**/tests/**',\n '**/test_*.py',\n '**/*_test.py',\n];\n\ntype GenerateSettingsInput = Partial<Omit<Settings, 'tag'>> & {\n config?: string;\n projectId?: string;\n locales?: string[];\n options?: Settings['options'];\n files?: unknown;\n publish?: boolean;\n tag?: string | boolean;\n message?: string;\n branch?: string;\n enableBranching?: boolean;\n disableBranchDetection?: boolean;\n remoteName?: string;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalClearLocaleDirs?: boolean;\n clearLocaleDirsExclude?: string[];\n [key: string]: unknown;\n};\n\nfunction hasConfiguredTranslationFiles(files: unknown): boolean {\n if (!files || typeof files !== 'object' || Array.isArray(files)) {\n return false;\n }\n return Object.keys(files).some((key) => key !== 'gt');\n}\n\n/**\n * Generates settings from any\n * @param flags - The CLI flags to generate settings from\n * @param cwd - The current working directory\n * @param options - Additional options\n * @param options.requireConfig - If true, exit with an error when no config file is found\n * @returns The generated settings\n */\nexport async function generateSettings(\n flags: GenerateSettingsInput,\n cwd: string = process.cwd(),\n options?: { requireConfig?: boolean }\n): Promise<Settings> {\n // Load config file\n let gtConfig: GenerateSettingsInput = {};\n\n if (flags.config && !flags.config.endsWith('.json')) {\n flags.config = `${flags.config}.json`;\n }\n if (flags.config) {\n gtConfig = loadConfig(flags.config);\n } else {\n const config = resolveConfig(cwd);\n if (config) {\n gtConfig = config.config as GenerateSettingsInput;\n flags.config = config.path;\n } else {\n if (options?.requireConfig) {\n return logErrorAndExit(\n 'No gt.config.json file was found. Run `npx gt init` to create one, pass --config, or run this command from your project root.'\n );\n }\n gtConfig = {};\n }\n }\n\n // Warn if apiKey is present in gt.config.json\n if (gtConfig.apiKey) {\n warnApiKeyInConfig(flags.config ?? 'gt.config.json');\n exitSync(1);\n }\n const projectIdEnv = resolveProjectId();\n // Resolve mismatched projectIds\n if (\n gtConfig.projectId &&\n flags.projectId &&\n gtConfig.projectId !== flags.projectId\n ) {\n logErrorAndExit(\n `Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but the CLI flag uses ${chalk.green(flags.projectId)}. Use the same projectId in all configs.`\n );\n } else if (\n gtConfig.projectId &&\n projectIdEnv &&\n gtConfig.projectId !== projectIdEnv\n ) {\n logErrorAndExit(\n `Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but GT_PROJECT_ID uses ${chalk.green(projectIdEnv)}. Use the same projectId in all configs.`\n );\n }\n\n if (\n flags.options?.docsUrlPattern &&\n !flags.options?.docsUrlPattern.includes('[locale]')\n ) {\n logErrorAndExit(\n 'Static URLs could not be localized because the URL pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated URL.'\n );\n }\n\n if (\n flags.options?.docsImportPattern &&\n !flags.options?.docsImportPattern.includes('[locale]')\n ) {\n logErrorAndExit(\n 'Static imports could not be localized because the import pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated import path.'\n );\n }\n\n if (flags.options?.copyFiles) {\n for (const file of flags.options.copyFiles) {\n if (!file.includes('[locale]')) {\n logErrorAndExit(\n 'Files could not be copied because the file path is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the copied path.'\n );\n }\n }\n }\n\n // Warn on deprecated includeSourceCodeContext\n const configuredFiles = gtConfig.files as FilesOptions | undefined;\n if (configuredFiles?.gt?.includeSourceCodeContext != null) {\n warnDeprecatedField(\n 'files.gt.includeSourceCodeContext',\n 'files.gt.parsingFlags.includeSourceCodeContext'\n );\n }\n\n // merge options\n const mergedOptions: Settings = { ...gtConfig, ...flags } as Settings;\n\n if (\n determineLibrary().library === 'base' &&\n !hasConfiguredTranslationFiles(mergedOptions.files)\n ) {\n logger.warn(\n chalk.yellow(\n 'No package.json or Python project file found in the current directory. Run this command from the root of your project.'\n )\n );\n }\n\n // Add defaultLocale if not provided\n mergedOptions.defaultLocale =\n mergedOptions.defaultLocale || libraryDefaultLocale;\n\n // merge locales\n mergedOptions.locales = Array.from(\n new Set([...(gtConfig.locales || []), ...(flags.locales || [])])\n );\n // Separate defaultLocale from locales\n mergedOptions.locales = mergedOptions.locales.filter(\n (locale) => locale !== mergedOptions.defaultLocale\n );\n\n // Add apiKey if not provided\n mergedOptions.apiKey = mergedOptions.apiKey || process.env.GT_API_KEY;\n\n // Add projectId if not provided\n mergedOptions.projectId = mergedOptions.projectId || resolveProjectId();\n\n // Add baseUrl if not provided\n mergedOptions.baseUrl = mergedOptions.baseUrl || defaultBaseUrl;\n\n // Add dashboardUrl if not provided\n mergedOptions.dashboardUrl = mergedOptions.dashboardUrl || GT_DASHBOARD_URL;\n\n // Add locales if not provided\n mergedOptions.locales = mergedOptions.locales || [];\n\n // Only set config path if one was actually found or explicitly provided.\n // Do not default to a phantom path — that would cause downstream writes\n // (e.g. updateConfig) to silently create a config file.\n if (!mergedOptions.config) {\n mergedOptions.config = '';\n }\n\n // Display projectId if present\n if (mergedOptions.projectId) displayProjectId(mergedOptions.projectId);\n\n // Add stageTranslations if not provided\n // For human review, always stage the project\n mergedOptions.stageTranslations = mergedOptions.stageTranslations ?? false;\n\n // Top-level default for whether translated files require approval before use.\n // Effective policy is hash-changing, so reject anything but a real boolean.\n if (\n mergedOptions.requiresReview !== undefined &&\n typeof mergedOptions.requiresReview !== 'boolean'\n ) {\n logErrorAndExit(\n 'requiresReview in gt.config.json must be a boolean. Use files.<type>.requiresReview for glob-scoped overrides.'\n );\n }\n mergedOptions.requiresReview = mergedOptions.requiresReview ?? false;\n\n // Add publish — only set if explicitly configured or passed via flag.\n // When neither is set, leave undefined so the publish step knows\n // there is no global publish intent.\n if (flags.publish) {\n mergedOptions.publish = true;\n } else if (gtConfig.publish !== undefined) {\n mergedOptions.publish = gtConfig.publish;\n } else {\n mergedOptions.publish = undefined;\n }\n\n // Don't default src here — each pipeline (JS/Python) has its own defaults.\n // Only set src if the user explicitly provided it via flags or config.\n\n // Resolve all glob patterns in the files object\n const compositePatterns = Object.entries(\n mergedOptions.options?.jsonSchema || {}\n )\n .filter(([, schema]) => schema.composite)\n .map(([key]) => key);\n mergedOptions.files = mergedOptions.files\n ? resolveFiles(\n normalizeFilesOptions(mergedOptions.files as FilesOptions),\n mergedOptions.defaultLocale,\n mergedOptions.locales,\n cwd,\n compositePatterns,\n mergedOptions.requiresReview\n )\n : {\n resolvedPaths: {},\n placeholderPaths: {},\n transformPaths: {},\n transformFormats: {},\n publishPaths: new Set<string>(),\n unpublishPaths: new Set<string>(),\n requiresReviewPaths: new Set<string>(),\n parsingFlags: {},\n gtJson: {\n parsingFlags: GT_PARSING_FLAGS_DEFAULT,\n },\n };\n\n mergedOptions.options = {\n ...mergedOptions.options,\n mintlify: {\n ...mergedOptions.options?.mintlify,\n inferTitleFromFilename:\n gtConfig.options?.mintlify?.inferTitleFromFilename ||\n mergedOptions.options?.mintlify?.inferTitleFromFilename,\n },\n experimentalLocalizeStaticImports:\n gtConfig.options?.experimentalLocalizeStaticImports ||\n flags.experimentalLocalizeStaticImports,\n experimentalLocalizeStaticUrls:\n gtConfig.options?.experimentalLocalizeStaticUrls ||\n flags.experimentalLocalizeStaticUrls,\n experimentalLocalizeRelativeAssets:\n gtConfig.options?.experimentalLocalizeRelativeAssets ||\n flags.experimentalLocalizeRelativeAssets,\n experimentalHideDefaultLocale:\n gtConfig.options?.experimentalHideDefaultLocale ||\n flags.experimentalHideDefaultLocale,\n experimentalFlattenJsonFiles:\n gtConfig.options?.experimentalFlattenJsonFiles ||\n flags.experimentalFlattenJsonFiles,\n experimentalClearLocaleDirs:\n gtConfig.options?.experimentalClearLocaleDirs ||\n flags.experimentalClearLocaleDirs,\n clearLocaleDirsExclude:\n gtConfig.options?.clearLocaleDirsExclude || flags.clearLocaleDirsExclude,\n };\n\n // Add additional options if provided\n if (mergedOptions.options) {\n if (mergedOptions.options.jsonSchema) {\n for (const fileGlob of Object.keys(mergedOptions.options.jsonSchema)) {\n const jsonSchema = mergedOptions.options.jsonSchema[fileGlob];\n if (jsonSchema.preset) {\n mergedOptions.options.jsonSchema[fileGlob] = {\n ...generatePreset(jsonSchema.preset, 'json'),\n ...jsonSchema,\n };\n }\n }\n }\n if (mergedOptions.options.yamlSchema) {\n for (const fileGlob of Object.keys(mergedOptions.options.yamlSchema)) {\n const yamlSchema = mergedOptions.options.yamlSchema[fileGlob];\n if (yamlSchema.preset) {\n mergedOptions.options.yamlSchema[fileGlob] = {\n ...generatePreset(yamlSchema.preset, 'yaml'),\n ...yamlSchema,\n };\n }\n }\n }\n }\n\n // Add parsing options if not provided\n mergedOptions.parsingOptions = mergedOptions.parsingOptions || {};\n mergedOptions.parsingOptions.conditionNames = mergedOptions.parsingOptions\n .conditionNames || [\n 'development',\n 'browser',\n 'module',\n 'import',\n 'require',\n 'default',\n ];\n\n // Add branch options if not provided\n const branchOptions = mergedOptions.branchOptions || {};\n // If --branch is set, enable branching\n branchOptions.enabled =\n flags.enableBranching ??\n gtConfig.branchOptions?.enabled ??\n (flags.branch ? true : false);\n branchOptions.currentBranch =\n flags.branch ?? gtConfig.branchOptions?.currentBranch ?? undefined;\n branchOptions.autoDetectBranches = flags.disableBranchDetection\n ? false\n : (gtConfig.branchOptions?.autoDetectBranches ?? true);\n branchOptions.remoteName =\n flags.remoteName ??\n gtConfig.branchOptions?.remoteName ??\n DEFAULT_GIT_REMOTE_NAME;\n mergedOptions.branchOptions = branchOptions;\n\n // Map -m/--message flag to tagMessage\n if (flags.message) {\n mergedOptions.tagMessage = flags.message;\n }\n\n // Resolve tag:\n // --tag (bare) or -m without --tag: try git SHA, fall back to random hex\n // --tag <value>: use as-is\n // No flags: no tag\n if (flags.tag === true || (!flags.tag && mergedOptions.tagMessage)) {\n try {\n mergedOptions.tag = execSync('git rev-parse --short HEAD', {\n encoding: 'utf-8',\n }).trim();\n // If no message provided, use git commit message\n if (!mergedOptions.tagMessage) {\n mergedOptions.tagMessage = execSync('git log -1 --format=%s', {\n encoding: 'utf-8',\n }).trim();\n }\n } catch {\n // Not in a git repo or git unavailable — fall back to random hex\n mergedOptions.tag = crypto.randomBytes(4).toString('hex');\n }\n }\n\n mergedOptions.configDirectory = path.join(cwd, '.gt');\n\n validateSettings(mergedOptions);\n\n // Set up GT instance\n gt.setConfig({\n projectId: mergedOptions.projectId,\n apiKey: mergedOptions.apiKey,\n baseUrl: mergedOptions.baseUrl,\n sourceLocale: mergedOptions.defaultLocale,\n customMapping: mergedOptions.customMapping,\n });\n\n return mergedOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACD;AAED,MAAa,8BAA8B,CAAC,UAAU;AACtD,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAyBD,SAAS,8BAA8B,OAAyB;AAC9D,KAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,CAC7D,QAAO;AAET,QAAO,OAAO,KAAK,MAAM,CAAC,MAAM,QAAQ,QAAQ,KAAK;;;;;;;;;;AAWvD,eAAsB,iBACpB,OACA,MAAc,QAAQ,KAAK,EAC3B,SACmB;CAEnB,IAAI,WAAkC,EAAE;AAExC,KAAI,MAAM,UAAU,CAAC,MAAM,OAAO,SAAS,QAAQ,CACjD,OAAM,SAAS,GAAG,MAAM,OAAO;AAEjC,KAAI,MAAM,OACR,YAAW,WAAW,MAAM,OAAO;MAC9B;EACL,MAAM,SAAS,cAAc,IAAI;AACjC,MAAI,QAAQ;AACV,cAAW,OAAO;AAClB,SAAM,SAAS,OAAO;SACjB;AACL,OAAI,SAAS,cACX,QAAO,gBACL,gIACD;AAEH,cAAW,EAAE;;;AAKjB,KAAI,SAAS,QAAQ;AACnB,qBAAmB,MAAM,UAAU,iBAAiB;AACpD,WAAS,EAAE;;CAEb,MAAM,eAAe,kBAAkB;AAEvC,KACE,SAAS,aACT,MAAM,aACN,SAAS,cAAc,MAAM,UAE7B,iBACE,4CAA4C,MAAM,MAAM,SAAS,UAAU,CAAC,0BAA0B,MAAM,MAAM,MAAM,UAAU,CAAC,0CACpI;UAED,SAAS,aACT,gBACA,SAAS,cAAc,aAEvB,iBACE,4CAA4C,MAAM,MAAM,SAAS,UAAU,CAAC,2BAA2B,MAAM,MAAM,aAAa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MAAM,aAAa,cAAc,QAAQ,WAAW;AACpD,OAAI,WAAW,OACb,eAAc,QAAQ,WAAW,YAAY;IAC3C,GAAG,eAAe,WAAW,QAAQ,OAAO;IAC5C,GAAG;IACJ;;;AAOT,eAAc,iBAAiB,cAAc,kBAAkB,EAAE;AACjE,eAAc,eAAe,iBAAiB,cAAc,eACzD,kBAAkB;EACnB;EACA;EACA;EACA;EACA;EACA;EACD;CAGD,MAAM,gBAAgB,cAAc,iBAAiB,EAAE;AAEvD,eAAc,UACZ,MAAM,mBACN,SAAS,eAAe,YACvB,MAAM,SAAS,OAAO;AACzB,eAAc,gBACZ,MAAM,UAAU,SAAS,eAAe,iBAAiB,KAAA;AAC3D,eAAc,qBAAqB,MAAM,yBACrC,QACC,SAAS,eAAe,sBAAsB;AACnD,eAAc,aACZ,MAAM,cACN,SAAS,eAAe,cAAA;AAE1B,eAAc,gBAAgB;AAG9B,KAAI,MAAM,QACR,eAAc,aAAa,MAAM;AAOnC,KAAI,MAAM,QAAQ,QAAS,CAAC,MAAM,OAAO,cAAc,WACrD,KAAI;AACF,gBAAc,MAAM,SAAS,8BAA8B,EACzD,UAAU,SACX,CAAC,CAAC,MAAM;AAET,MAAI,CAAC,cAAc,WACjB,eAAc,aAAa,SAAS,0BAA0B,EAC5D,UAAU,SACX,CAAC,CAAC,MAAM;SAEL;AAEN,gBAAc,MAAM,OAAO,YAAY,EAAE,CAAC,SAAS,MAAM;;AAI7D,eAAc,kBAAkB,KAAK,KAAK,KAAK,MAAM;AAErD,kBAAiB,cAAc;AAG/B,IAAG,UAAU;EACX,WAAW,cAAc;EACzB,QAAQ,cAAc;EACtB,SAAS,cAAc;EACvB,cAAc,cAAc;EAC5B,eAAe,cAAc;EAC9B,CAAC;AAEF,QAAO"}
|
|
1
|
+
{"version":3,"file":"generateSettings.js","names":[],"sources":["../../src/config/generateSettings.ts"],"sourcesContent":["import {\n displayProjectId,\n exitSync,\n logErrorAndExit,\n warnApiKeyInConfig,\n warnDeprecatedField,\n} from '../console/logging.js';\nimport { loadConfig } from '../fs/config/loadConfig.js';\nimport { FilesOptions, Settings } from '../types/index.js';\nimport {\n defaultBaseUrl,\n libraryDefaultLocale,\n} from 'generaltranslation/internal';\nimport { resolveFiles } from '../fs/config/parseFilesConfig.js';\nimport { validateSettings } from './validateSettings.js';\nimport {\n DEFAULT_GIT_REMOTE_NAME,\n GT_DASHBOARD_URL,\n} from '../utils/constants.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport crypto from 'node:crypto';\nimport { execSync } from 'node:child_process';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport { resolveConfig } from './resolveConfig.js';\nimport { gt } from '../utils/gt.js';\nimport { generatePreset } from './optionPresets.js';\nimport { GT_PARSING_FLAGS_DEFAULT } from './defaults.js';\nimport { normalizeFilesOptions } from '../formats/files/transformFormat.js';\nimport { determineLibrary } from '../fs/determineFramework/index.js';\nimport { logger } from '../console/logger.js';\n\nexport const DEFAULT_SRC_PATTERNS = [\n 'src/**/*.{js,jsx,ts,tsx}',\n 'app/**/*.{js,jsx,ts,tsx}',\n 'pages/**/*.{js,jsx,ts,tsx}',\n 'components/**/*.{js,jsx,ts,tsx}',\n];\n\nexport const DEFAULT_PYTHON_SRC_PATTERNS = ['**/*.py'];\nexport const DEFAULT_PYTHON_SRC_EXCLUDES = [\n 'venv/**',\n '.venv/**',\n '__pycache__/**',\n '**/migrations/**',\n '**/tests/**',\n '**/test_*.py',\n '**/*_test.py',\n];\n\ntype GenerateSettingsInput = Partial<Omit<Settings, 'tag'>> & {\n config?: string;\n projectId?: string;\n locales?: string[];\n options?: Settings['options'];\n files?: unknown;\n publish?: boolean;\n omitConfigIds?: boolean;\n tag?: string | boolean;\n message?: string;\n branch?: string;\n enableBranching?: boolean;\n disableBranchDetection?: boolean;\n remoteName?: string;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalClearLocaleDirs?: boolean;\n clearLocaleDirsExclude?: string[];\n [key: string]: unknown;\n};\n\nfunction hasConfiguredTranslationFiles(files: unknown): boolean {\n if (!files || typeof files !== 'object' || Array.isArray(files)) {\n return false;\n }\n return Object.keys(files).some((key) => key !== 'gt');\n}\n\n/**\n * Generates settings from any\n * @param flags - The CLI flags to generate settings from\n * @param cwd - The current working directory\n * @param options - Additional options\n * @param options.requireConfig - If true, exit with an error when no config file is found\n * @returns The generated settings\n */\nexport async function generateSettings(\n flags: GenerateSettingsInput,\n cwd: string = process.cwd(),\n options?: { requireConfig?: boolean }\n): Promise<Settings> {\n // Load config file\n let gtConfig: GenerateSettingsInput = {};\n\n if (flags.config && !flags.config.endsWith('.json')) {\n flags.config = `${flags.config}.json`;\n }\n if (flags.config) {\n gtConfig = loadConfig(flags.config);\n } else {\n const config = resolveConfig(cwd);\n if (config) {\n gtConfig = config.config as GenerateSettingsInput;\n flags.config = config.path;\n } else {\n if (options?.requireConfig) {\n return logErrorAndExit(\n 'No gt.config.json file was found. Run `npx gt init` to create one, pass --config, or run this command from your project root.'\n );\n }\n gtConfig = {};\n }\n }\n\n // Warn if apiKey is present in gt.config.json\n if (gtConfig.apiKey) {\n warnApiKeyInConfig(flags.config ?? 'gt.config.json');\n exitSync(1);\n }\n const projectIdEnv = resolveProjectId();\n // Resolve mismatched projectIds\n if (\n gtConfig.projectId &&\n flags.projectId &&\n gtConfig.projectId !== flags.projectId\n ) {\n logErrorAndExit(\n `Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but the CLI flag uses ${chalk.green(flags.projectId)}. Use the same projectId in all configs.`\n );\n } else if (\n gtConfig.projectId &&\n projectIdEnv &&\n gtConfig.projectId !== projectIdEnv\n ) {\n logErrorAndExit(\n `Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but GT_PROJECT_ID uses ${chalk.green(projectIdEnv)}. Use the same projectId in all configs.`\n );\n }\n\n if (\n flags.options?.docsUrlPattern &&\n !flags.options?.docsUrlPattern.includes('[locale]')\n ) {\n logErrorAndExit(\n 'Static URLs could not be localized because the URL pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated URL.'\n );\n }\n\n if (\n flags.options?.docsImportPattern &&\n !flags.options?.docsImportPattern.includes('[locale]')\n ) {\n logErrorAndExit(\n 'Static imports could not be localized because the import pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated import path.'\n );\n }\n\n if (flags.options?.copyFiles) {\n for (const file of flags.options.copyFiles) {\n if (!file.includes('[locale]')) {\n logErrorAndExit(\n 'Files could not be copied because the file path is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the copied path.'\n );\n }\n }\n }\n\n // Warn on deprecated includeSourceCodeContext\n const configuredFiles = gtConfig.files as FilesOptions | undefined;\n if (configuredFiles?.gt?.includeSourceCodeContext != null) {\n warnDeprecatedField(\n 'files.gt.includeSourceCodeContext',\n 'files.gt.parsingFlags.includeSourceCodeContext'\n );\n }\n\n // merge options\n const mergedOptions: Settings = { ...gtConfig, ...flags } as Settings;\n\n if (\n determineLibrary().library === 'base' &&\n !hasConfiguredTranslationFiles(mergedOptions.files)\n ) {\n logger.warn(\n chalk.yellow(\n 'No package.json or Python project file found in the current directory. Run this command from the root of your project.'\n )\n );\n }\n\n // Add defaultLocale if not provided\n mergedOptions.defaultLocale =\n mergedOptions.defaultLocale || libraryDefaultLocale;\n\n // merge locales\n mergedOptions.locales = Array.from(\n new Set([...(gtConfig.locales || []), ...(flags.locales || [])])\n );\n // Separate defaultLocale from locales\n mergedOptions.locales = mergedOptions.locales.filter(\n (locale) => locale !== mergedOptions.defaultLocale\n );\n\n // Add apiKey if not provided\n mergedOptions.apiKey = mergedOptions.apiKey || process.env.GT_API_KEY;\n\n // Add projectId if not provided\n mergedOptions.projectId = mergedOptions.projectId || resolveProjectId();\n\n // Add baseUrl if not provided\n mergedOptions.baseUrl = mergedOptions.baseUrl || defaultBaseUrl;\n\n // Add dashboardUrl if not provided\n mergedOptions.dashboardUrl = mergedOptions.dashboardUrl || GT_DASHBOARD_URL;\n\n // Add locales if not provided\n mergedOptions.locales = mergedOptions.locales || [];\n\n // Only set config path if one was actually found or explicitly provided.\n // Do not default to a phantom path — that would cause downstream writes\n // (e.g. updateConfig) to silently create a config file.\n if (!mergedOptions.config) {\n mergedOptions.config = '';\n }\n\n // Display projectId if present\n if (mergedOptions.projectId) displayProjectId(mergedOptions.projectId);\n\n // Add stageTranslations if not provided\n // For human review, always stage the project\n mergedOptions.stageTranslations = mergedOptions.stageTranslations ?? false;\n\n // Top-level default for whether translated files require approval before use.\n // Effective policy is hash-changing, so reject anything but a real boolean.\n if (\n mergedOptions.requiresReview !== undefined &&\n typeof mergedOptions.requiresReview !== 'boolean'\n ) {\n logErrorAndExit(\n 'requiresReview in gt.config.json must be a boolean. Use files.<type>.requiresReview for glob-scoped overrides.'\n );\n }\n mergedOptions.requiresReview = mergedOptions.requiresReview ?? false;\n\n // Add publish — only set if explicitly configured or passed via flag.\n // When neither is set, leave undefined so the publish step knows\n // there is no global publish intent.\n if (flags.publish) {\n mergedOptions.publish = true;\n } else if (gtConfig.publish !== undefined) {\n mergedOptions.publish = gtConfig.publish;\n } else {\n mergedOptions.publish = undefined;\n }\n\n mergedOptions.omitConfigIds =\n flags.omitConfigIds === true || gtConfig.omitConfigIds === true;\n\n // Don't default src here — each pipeline (JS/Python) has its own defaults.\n // Only set src if the user explicitly provided it via flags or config.\n\n // Resolve all glob patterns in the files object\n const compositePatterns = Object.entries(\n mergedOptions.options?.jsonSchema || {}\n )\n .filter(([, schema]) => schema.composite)\n .map(([key]) => key);\n mergedOptions.files = mergedOptions.files\n ? resolveFiles(\n normalizeFilesOptions(mergedOptions.files as FilesOptions),\n mergedOptions.defaultLocale,\n mergedOptions.locales,\n cwd,\n compositePatterns,\n mergedOptions.requiresReview\n )\n : {\n resolvedPaths: {},\n placeholderPaths: {},\n transformPaths: {},\n transformFormats: {},\n publishPaths: new Set<string>(),\n unpublishPaths: new Set<string>(),\n requiresReviewPaths: new Set<string>(),\n parsingFlags: {},\n gtJson: {\n parsingFlags: GT_PARSING_FLAGS_DEFAULT,\n },\n };\n\n mergedOptions.options = {\n ...mergedOptions.options,\n mintlify: {\n ...mergedOptions.options?.mintlify,\n inferTitleFromFilename:\n gtConfig.options?.mintlify?.inferTitleFromFilename ||\n mergedOptions.options?.mintlify?.inferTitleFromFilename,\n },\n experimentalLocalizeStaticImports:\n gtConfig.options?.experimentalLocalizeStaticImports ||\n flags.experimentalLocalizeStaticImports,\n experimentalLocalizeStaticUrls:\n gtConfig.options?.experimentalLocalizeStaticUrls ||\n flags.experimentalLocalizeStaticUrls,\n experimentalLocalizeRelativeAssets:\n gtConfig.options?.experimentalLocalizeRelativeAssets ||\n flags.experimentalLocalizeRelativeAssets,\n experimentalHideDefaultLocale:\n gtConfig.options?.experimentalHideDefaultLocale ||\n flags.experimentalHideDefaultLocale,\n experimentalFlattenJsonFiles:\n gtConfig.options?.experimentalFlattenJsonFiles ||\n flags.experimentalFlattenJsonFiles,\n experimentalClearLocaleDirs:\n gtConfig.options?.experimentalClearLocaleDirs ||\n flags.experimentalClearLocaleDirs,\n clearLocaleDirsExclude:\n gtConfig.options?.clearLocaleDirsExclude || flags.clearLocaleDirsExclude,\n };\n\n if (\n mergedOptions.omitConfigIds &&\n (mergedOptions.publish === true ||\n mergedOptions.files.gtJson.publish === true)\n ) {\n logger.warn(\n chalk.yellow(\n 'Config IDs will be omitted even though CDN publishing is enabled. Remote cache/CDN consumers may load the latest available translations instead of a pinned version.'\n )\n );\n }\n\n // Add additional options if provided\n if (mergedOptions.options) {\n if (mergedOptions.options.jsonSchema) {\n for (const fileGlob of Object.keys(mergedOptions.options.jsonSchema)) {\n const jsonSchema = mergedOptions.options.jsonSchema[fileGlob];\n if (jsonSchema.preset) {\n mergedOptions.options.jsonSchema[fileGlob] = {\n ...generatePreset(jsonSchema.preset, 'json'),\n ...jsonSchema,\n };\n }\n }\n }\n if (mergedOptions.options.yamlSchema) {\n for (const fileGlob of Object.keys(mergedOptions.options.yamlSchema)) {\n const yamlSchema = mergedOptions.options.yamlSchema[fileGlob];\n if (yamlSchema.preset) {\n mergedOptions.options.yamlSchema[fileGlob] = {\n ...generatePreset(yamlSchema.preset, 'yaml'),\n ...yamlSchema,\n };\n }\n }\n }\n }\n\n // Add parsing options if not provided\n mergedOptions.parsingOptions = mergedOptions.parsingOptions || {};\n mergedOptions.parsingOptions.conditionNames = mergedOptions.parsingOptions\n .conditionNames || [\n 'development',\n 'browser',\n 'module',\n 'import',\n 'require',\n 'default',\n ];\n\n // Add branch options if not provided\n const branchOptions = mergedOptions.branchOptions || {};\n // If --branch is set, enable branching\n branchOptions.enabled =\n flags.enableBranching ??\n gtConfig.branchOptions?.enabled ??\n (flags.branch ? true : false);\n branchOptions.currentBranch =\n flags.branch ?? gtConfig.branchOptions?.currentBranch ?? undefined;\n branchOptions.autoDetectBranches = flags.disableBranchDetection\n ? false\n : (gtConfig.branchOptions?.autoDetectBranches ?? true);\n branchOptions.remoteName =\n flags.remoteName ??\n gtConfig.branchOptions?.remoteName ??\n DEFAULT_GIT_REMOTE_NAME;\n mergedOptions.branchOptions = branchOptions;\n\n // Map -m/--message flag to tagMessage\n if (flags.message) {\n mergedOptions.tagMessage = flags.message;\n }\n\n // Resolve tag:\n // --tag (bare) or -m without --tag: try git SHA, fall back to random hex\n // --tag <value>: use as-is\n // No flags: no tag\n if (flags.tag === true || (!flags.tag && mergedOptions.tagMessage)) {\n try {\n mergedOptions.tag = execSync('git rev-parse --short HEAD', {\n encoding: 'utf-8',\n }).trim();\n // If no message provided, use git commit message\n if (!mergedOptions.tagMessage) {\n mergedOptions.tagMessage = execSync('git log -1 --format=%s', {\n encoding: 'utf-8',\n }).trim();\n }\n } catch {\n // Not in a git repo or git unavailable — fall back to random hex\n mergedOptions.tag = crypto.randomBytes(4).toString('hex');\n }\n }\n\n mergedOptions.configDirectory = path.join(cwd, '.gt');\n\n validateSettings(mergedOptions);\n\n // Set up GT instance\n gt.setConfig({\n projectId: mergedOptions.projectId,\n apiKey: mergedOptions.apiKey,\n baseUrl: mergedOptions.baseUrl,\n sourceLocale: mergedOptions.defaultLocale,\n customMapping: mergedOptions.customMapping,\n });\n\n return mergedOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACD;AAED,MAAa,8BAA8B,CAAC,UAAU;AACtD,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AA0BD,SAAS,8BAA8B,OAAyB;AAC9D,KAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,CAC7D,QAAO;AAET,QAAO,OAAO,KAAK,MAAM,CAAC,MAAM,QAAQ,QAAQ,KAAK;;;;;;;;;;AAWvD,eAAsB,iBACpB,OACA,MAAc,QAAQ,KAAK,EAC3B,SACmB;CAEnB,IAAI,WAAkC,EAAE;AAExC,KAAI,MAAM,UAAU,CAAC,MAAM,OAAO,SAAS,QAAQ,CACjD,OAAM,SAAS,GAAG,MAAM,OAAO;AAEjC,KAAI,MAAM,OACR,YAAW,WAAW,MAAM,OAAO;MAC9B;EACL,MAAM,SAAS,cAAc,IAAI;AACjC,MAAI,QAAQ;AACV,cAAW,OAAO;AAClB,SAAM,SAAS,OAAO;SACjB;AACL,OAAI,SAAS,cACX,QAAO,gBACL,gIACD;AAEH,cAAW,EAAE;;;AAKjB,KAAI,SAAS,QAAQ;AACnB,qBAAmB,MAAM,UAAU,iBAAiB;AACpD,WAAS,EAAE;;CAEb,MAAM,eAAe,kBAAkB;AAEvC,KACE,SAAS,aACT,MAAM,aACN,SAAS,cAAc,MAAM,UAE7B,iBACE,4CAA4C,MAAM,MAAM,SAAS,UAAU,CAAC,0BAA0B,MAAM,MAAM,MAAM,UAAU,CAAC,0CACpI;UAED,SAAS,aACT,gBACA,SAAS,cAAc,aAEvB,iBACE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AAc;EACtB,SAAS,cAAc;EACvB,cAAc,cAAc;EAC5B,eAAe,cAAc;EAC9B,CAAC;AAEF,QAAO"}
|
package/dist/console/index.d.ts
CHANGED
|
@@ -36,11 +36,9 @@ export declare const noLocalesError = "No target locales were found. Add locales
|
|
|
36
36
|
export declare const noDefaultLocaleError = "No default locale was found. Add defaultLocale to gt.config.json or pass it with --default-locale.";
|
|
37
37
|
export declare const noFilesError = "The files configuration is missing or invalid. Check the files section in gt.config.json and try again.";
|
|
38
38
|
export declare const noSourceFileError = "No source translation file was found. Check your translations directory and default locale configuration.";
|
|
39
|
-
export declare const noSupportedFormatError = "The translation file format is not supported. Use a supported file extension in translationsDir.";
|
|
40
39
|
export declare const noApiKeyError = "No API key was found. Pass --api-key or set the GT_API_KEY environment variable.";
|
|
41
40
|
export declare const devApiKeyError = "Development API keys cannot be used with the General Translation API. Use a production API key instead.\nGenerate a production API key with: npx gt auth -t production";
|
|
42
41
|
export declare const noProjectIdError = "No project ID was found. Pass --project-id, add projectId to gt.config.json, or set the GT_PROJECT_ID environment variable.";
|
|
43
|
-
export declare const noVersionIdError = "No version ID was found. Pass --version-id or add _versionId to gt.config.json.";
|
|
44
42
|
export declare const invalidConfigurationError = "The files configuration cannot be used for this operation. Provide a valid download configuration or set --publish true to upload translations to the CDN.";
|
|
45
43
|
export declare const branchResolutionError = "The current git branch could not be resolved. Specify a branch explicitly or run the command from a git worktree with branch metadata available.";
|
|
46
44
|
export declare const withOriginalError: (message: string, error: unknown) => string;
|
package/dist/console/index.js
CHANGED
|
@@ -8,7 +8,7 @@ const withDeriveFunctionError = (message) => `derive() rules violation: ${messag
|
|
|
8
8
|
const warnApiKeyInConfigSync = (optionsFilepath) => `${colorizeFilepath(optionsFilepath)}: Your API key is exposed! Remove it from the file and include it as an environment variable.`;
|
|
9
9
|
const warnVariablePropSync = (file, attrName, value, location) => withLocation(file, `${colorizeComponent("<T>")} component has dynamic attribute ${colorizeIdString(attrName)} with value: ${colorizeContent(value)}. Change ${colorizeIdString(attrName)} to ensure this content is translated.`, location);
|
|
10
10
|
const warnInvalidReturnSync = (file, functionName, expression, location) => withLocation(file, withDeriveComponentError(`Function ${colorizeFunctionName(functionName)} does not return a derivable (statically analyzable) expression. ${colorizeFunctionName(functionName)} must return either (1) a derivable string literal, (2) another derivable function invocation, (3) derivable JSX content, or (4) a ternary expression. Instead got:\n${colorizeContent(expression)}`), location);
|
|
11
|
-
const warnMissingReturnSync = (file, functionName, location) => withLocation(file, `Function ${colorizeFunctionName(functionName)} is wrapped in ${colorizeComponent("<Derive>")}
|
|
11
|
+
const warnMissingReturnSync = (file, functionName, location) => withLocation(file, `Function ${colorizeFunctionName(functionName)} is wrapped in ${colorizeComponent("<Derive>")} tags but does not have an explicit return statement. Derivable functions must have an explicit return statement.`, location);
|
|
12
12
|
const warnHasUnwrappedExpressionSync = (file, unwrappedExpressions, id, location) => withLocation(file, `${colorizeComponent("<T>")} component${id ? ` with id ${colorizeIdString(id)}` : ""} has children that could change at runtime. Use a variable component like ${colorizeComponent("<Var>")} to ensure this content is translated.\n${colorizeContent(unwrappedExpressions.join("\n"))}`, location);
|
|
13
13
|
const warnFailedToConstructJsxTreeSync = (file, code, location) => withLocation(file, `Failed to construct JsxTree! Call expression is not a valid createElement call: ${colorizeContent(code)}`, location);
|
|
14
14
|
const warnNestedTComponent = (file, location) => withLocation(file, `Found nested <T> component. <T> components cannot be directly nested.`, location);
|
|
@@ -32,9 +32,9 @@ Example: ${colorizeContent(`const ${colorizeFunctionName(functionName)} = () =>
|
|
|
32
32
|
Invalid: ${colorizeContent(`const ${colorizeFunctionName(functionName)} = [() => { ... }][0]`)}`), location);
|
|
33
33
|
const warnDataAttrOnBranch = (file, attrName, location) => withLocation(file, `${colorizeComponent(`<${BRANCH_COMPONENT}>`)} component ignores attributes prefixed with ${colorizeIdString("\"data-\"")}. Found ${colorizeIdString(attrName)}. Remove it or use a different attribute name.`, location);
|
|
34
34
|
const warnRecursiveFunctionCallSync = (file, functionName, location) => withLocation(file, withDeriveComponentError(`Recursive function call detected: ${colorizeFunctionName(functionName)}. A derivable (statically analyzable) function cannot use recursive calls to construct its result.`), location);
|
|
35
|
-
const warnDeriveFunctionNotWrappedSync = (file, functionName, location) => withLocation(file, withDeriveFunctionError(`Could not resolve ${colorizeFunctionName(formatCodeClamp(functionName))}. This call is not wrapped in derive()
|
|
35
|
+
const warnDeriveFunctionNotWrappedSync = (file, functionName, location) => withLocation(file, withDeriveFunctionError(`Could not resolve ${colorizeFunctionName(formatCodeClamp(functionName))}. This call is not wrapped in derive(). Ensure the function is properly wrapped with derive() and does not have circular import dependencies.`), location);
|
|
36
36
|
const warnDeriveNonConstVariableSync = (file, varName, kind, location) => withLocation(file, withDeriveFunctionError(`Variable ${colorizeFunctionName(varName)} is declared with '${kind}' but only 'const' declarations can be resolved statically. Change it to 'const'.`), location);
|
|
37
|
-
const warnDeriveFunctionNoResultsSync = (file, functionName, location) => withLocation(file, withDeriveFunctionError(`Could not resolve ${colorizeFunctionName(formatCodeClamp(functionName))}. derive()
|
|
37
|
+
const warnDeriveFunctionNoResultsSync = (file, functionName, location) => withLocation(file, withDeriveFunctionError(`Could not resolve ${colorizeFunctionName(formatCodeClamp(functionName))}. derive() can only receive function invocations and cannot use undefined values or looped calls to construct its result.`), location);
|
|
38
38
|
const warnAutoderiveNoResultsSync = (file, expression, location) => withLocation(file, `Autoderive could not resolve ${colorizeFunctionName(formatCodeClamp(expression))}. Only function calls with statically determinable return values can be used directly in t(). Consider wrapping with derive() for explicit derivation, or use an interpolation variable instead.`, location);
|
|
39
39
|
const warnDeriveUnresolvableValueSync = (file, key, location) => withLocation(file, withDeriveFunctionError(`Object property ${colorizeFunctionName(formatCodeClamp(key))} could not be resolved to a static string value. Only string literals, template literals, conditionals, and function calls returning strings are supported.`), location);
|
|
40
40
|
const warnDeriveCircularSpreadSync = (file, varName, location) => withLocation(file, withDeriveFunctionError(`Circular spread detected involving ${colorizeFunctionName(varName)}. Spread references that form a cycle cannot be resolved statically.`), location);
|
|
@@ -45,15 +45,13 @@ const noLocalesError = `No target locales were found. Add locales to gt.config.j
|
|
|
45
45
|
const noDefaultLocaleError = `No default locale was found. Add defaultLocale to gt.config.json or pass it with --default-locale.`;
|
|
46
46
|
const noFilesError = `The files configuration is missing or invalid. Check the files section in gt.config.json and try again.`;
|
|
47
47
|
const noSourceFileError = `No source translation file was found. Check your translations directory and default locale configuration.`;
|
|
48
|
-
const noSupportedFormatError = `The translation file format is not supported. Use a supported file extension in translationsDir.`;
|
|
49
48
|
const noApiKeyError = `No API key was found. Pass --api-key or set the GT_API_KEY environment variable.`;
|
|
50
49
|
const devApiKeyError = `Development API keys cannot be used with the General Translation API. Use a production API key instead.\nGenerate a production API key with: npx gt auth -t production`;
|
|
51
50
|
const noProjectIdError = `No project ID was found. Pass --project-id, add projectId to gt.config.json, or set the GT_PROJECT_ID environment variable.`;
|
|
52
|
-
const noVersionIdError = `No version ID was found. Pass --version-id or add _versionId to gt.config.json.`;
|
|
53
51
|
const invalidConfigurationError = `The files configuration cannot be used for this operation. Provide a valid download configuration or set --publish true to upload translations to the CDN.`;
|
|
54
52
|
const branchResolutionError = `The current git branch could not be resolved. Specify a branch explicitly or run the command from a git worktree with branch metadata available.`;
|
|
55
53
|
const withOriginalError = (message, error) => error != null ? `${message} Original error: ${String(error)}` : message;
|
|
56
54
|
//#endregion
|
|
57
|
-
export { branchResolutionError, devApiKeyError, invalidConfigurationError, noApiKeyError, noDefaultLocaleError, noFilesError, noLocalesError, noProjectIdError, noSourceFileError,
|
|
55
|
+
export { branchResolutionError, devApiKeyError, invalidConfigurationError, noApiKeyError, noDefaultLocaleError, noFilesError, noLocalesError, noProjectIdError, noSourceFileError, warnApiKeyInConfigSync, warnAsyncUseGT, warnAutoderiveNoResultsSync, warnDataAttrOnBranch, warnDeriveCircularSpreadSync, warnDeriveDestructuringSync, warnDeriveFunctionNoResultsSync, warnDeriveFunctionNotWrappedSync, warnDeriveNonConstVariableSync, warnDeriveOptionalChainingSync, warnDeriveUnresolvableValueSync, warnDuplicateFunctionDefinitionSync, warnFailedToConstructJsxTreeSync, warnFunctionNotFoundSync, warnHasUnwrappedExpressionSync, warnInvalidDeclareVarNameSync, warnInvalidDeriveInitSync, warnInvalidFormatSync, warnInvalidIcuSync, warnInvalidMaxCharsSync, warnInvalidRequiresReviewSync, warnInvalidReturnSync, warnMissingReturnSync, warnNestedInternalTComponent, warnNestedTComponent, warnNonStaticExpressionSync, warnNonStringSync, warnRecursiveFunctionCallSync, warnSyncGetGT, warnTemplateLiteralSync, warnTernarySync, warnUnresolvedImportSync, warnVariablePropSync, withLocation, withOriginalError };
|
|
58
56
|
|
|
59
57
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/console/index.ts"],"sourcesContent":["import { BRANCH_COMPONENT } from '../react/jsx/utils/constants.js';\nimport {\n colorizeFilepath,\n colorizeComponent,\n colorizeIdString,\n colorizeContent,\n colorizeLine,\n colorizeFunctionName,\n} from './colors.js';\nimport { formatCodeClamp } from './formatting.js';\n\nconst withWillErrorInNextVersion = (message: string): string =>\n `${message} (This will become an error in the next major version of the CLI.)`;\n\n// Derive function related errors\nconst withDeriveComponentError = (message: string): string =>\n `<Derive> rules violation: ${message}`;\n\nconst withDeriveFunctionError = (message: string): string =>\n `derive() rules violation: ${message}`;\n// Synchronous wrappers for backward compatibility\nexport const warnApiKeyInConfigSync = (optionsFilepath: string): string =>\n `${colorizeFilepath(\n optionsFilepath\n )}: Your API key is exposed! Remove it from the file and include it as an environment variable.`;\n\nexport const warnVariablePropSync = (\n file: string,\n attrName: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `${colorizeComponent('<T>')} component has dynamic attribute ${colorizeIdString(attrName)} with value: ${colorizeContent(\n value\n )}. Change ${colorizeIdString(attrName)} to ensure this content is translated.`,\n location\n );\n\nexport const warnInvalidReturnSync = (\n file: string,\n functionName: string,\n expression: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveComponentError(\n `Function ${colorizeFunctionName(functionName)} does not return a derivable (statically analyzable) expression. ${colorizeFunctionName(functionName)} must return either (1) a derivable string literal, (2) another derivable function invocation, (3) derivable JSX content, or (4) a ternary expression. Instead got:\\n${colorizeContent(expression)}`\n ),\n location\n );\n\n// TODO: this is temporary until we handle implicit returns\nexport const warnMissingReturnSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Function ${colorizeFunctionName(functionName)} is wrapped in ${colorizeComponent('<Derive>')} (formerly ${colorizeComponent('<Static>')}) tags but does not have an explicit return statement. Derivable functions must have an explicit return statement.`,\n location\n );\n\nexport const warnHasUnwrappedExpressionSync = (\n file: string,\n unwrappedExpressions: string[],\n id?: string,\n location?: string\n): string =>\n withLocation(\n file,\n `${colorizeComponent('<T>')} component${\n id ? ` with id ${colorizeIdString(id)}` : ''\n } has children that could change at runtime. Use a variable component like ${colorizeComponent(\n '<Var>'\n )} to ensure this content is translated.\\n${colorizeContent(\n unwrappedExpressions.join('\\n')\n )}`,\n location\n );\n\nexport const warnFailedToConstructJsxTreeSync = (\n file: string,\n code: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Failed to construct JsxTree! Call expression is not a valid createElement call: ${colorizeContent(code)}`,\n location\n );\n\nexport const warnNestedTComponent = (file: string, location?: string): string =>\n withLocation(\n file,\n `Found nested <T> component. <T> components cannot be directly nested.`,\n location\n );\n\nexport const warnNestedInternalTComponent = (\n file: string,\n location?: string\n): string =>\n withLocation(\n file,\n `DEBUG: Found nested <GtInternalTranslateJsx> component. <GtInternalTranslateJsx> components cannot be directly nested.`,\n location\n );\n\nexport const warnNonStaticExpressionSync = (\n file: string,\n attrName: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found non-static expression for attribute ${colorizeIdString(\n attrName\n )}: ${colorizeContent(value)}. Change \"${colorizeIdString(attrName)}\" to ensure this content is translated.`,\n location\n );\n\nexport const warnInvalidMaxCharsSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found invalid maxChars value: ${colorizeContent(value)}. Change the value to a valid number to ensure this content is translated.`,\n location\n );\n\nexport const warnInvalidFormatSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found invalid $format value: ${colorizeContent(value)}. Must be one of: 'ICU', 'STRING', 'I18NEXT'.`,\n location\n );\n\nexport const warnInvalidRequiresReviewSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found invalid requiresReview value: ${colorizeContent(value)}. Must be a boolean literal (true or false) — strings and dynamic expressions are not allowed.`,\n location\n );\n\nexport const warnInvalidIcuSync = (\n file: string,\n value: string,\n error: string,\n location?: string\n): string =>\n withWillErrorInNextVersion(\n withLocation(\n file,\n `Found invalid ICU string: ${colorizeContent(value)}. Change the value to a valid ICU to ensure this content is translated. Error message: ${error}.`,\n location\n )\n );\n\nexport const warnTemplateLiteralSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found template literal with quasis (${colorizeContent(value)}). Change the template literal to a string to ensure this content is translated.`,\n location\n );\n\nexport const warnNonStringSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found non-string literal (${colorizeContent(value)}). Change the value to a string literal to ensure this content is translated.`,\n location\n );\n\nexport const warnAsyncUseGT = (file: string, location?: string): string =>\n withLocation(\n file,\n `Found useGT() in an async function. Use getGT() instead, or make the function synchronous.`,\n location\n );\n\nexport const warnSyncGetGT = (file: string, location?: string): string =>\n withLocation(\n file,\n `Found getGT() in a synchronous function. Use useGT() instead, or make the function async.`,\n location\n );\n\nexport const warnTernarySync = (file: string, location?: string): string =>\n withLocation(\n file,\n 'Found ternary expression. A Branch component may be more appropriate here.',\n location\n );\n\nexport const withLocation = (\n file: string,\n message: string,\n location?: string\n): string =>\n `${colorizeFilepath(file)}${location ? ` (${colorizeLine(location)})` : ''}: ${message}`;\n\nexport const warnFunctionNotFoundSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Function ${colorizeFunctionName(functionName)} definition could not be resolved. This might affect translation resolution for this ${colorizeComponent('<T>')} component.`,\n location\n );\n\nexport const warnInvalidDeclareVarNameSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found invalid declareVar() $name tag. Must be a derivable (statically analyzable) expression. Received: ${colorizeContent(value)}.`,\n location\n );\n\nexport const warnDuplicateFunctionDefinitionSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Function ${colorizeFunctionName(functionName)} is defined multiple times. Only the first definition will be used.`,\n location\n );\n\nexport const warnInvalidDeriveInitSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveComponentError(\n `The definition for ${colorizeFunctionName(functionName)} could not be resolved. When using arrow syntax to define a derivable (statically analyzable) function, the right hand side or the assignment MUST only contain the arrow function itself and no other expressions.\nExample: ${colorizeContent(`const ${colorizeFunctionName(functionName)} = () => { ... }`)}\nInvalid: ${colorizeContent(`const ${colorizeFunctionName(functionName)} = [() => { ... }][0]`)}`\n ),\n location\n );\n\nexport const warnDataAttrOnBranch = (\n file: string,\n attrName: string,\n location?: string\n): string =>\n withLocation(\n file,\n `${colorizeComponent(`<${BRANCH_COMPONENT}>`)} component ignores attributes prefixed with ${colorizeIdString('\"data-\"')}. Found ${colorizeIdString(attrName)}. Remove it or use a different attribute name.`,\n location\n );\n\nexport const warnRecursiveFunctionCallSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveComponentError(\n `Recursive function call detected: ${colorizeFunctionName(functionName)}. A derivable (statically analyzable) function cannot use recursive calls to construct its result.`\n ),\n location\n );\n\nexport const warnDeriveFunctionNotWrappedSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Could not resolve ${colorizeFunctionName(formatCodeClamp(functionName))}. This call is not wrapped in derive() (formerly declareStatic()). Ensure the function is properly wrapped with derive() and does not have circular import dependencies.`\n ),\n location\n );\n\nexport const warnDeriveNonConstVariableSync = (\n file: string,\n varName: string,\n kind: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Variable ${colorizeFunctionName(varName)} is declared with '${kind}' but only 'const' declarations can be resolved statically. Change it to 'const'.`\n ),\n location\n );\n\nexport const warnDeriveFunctionNoResultsSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Could not resolve ${colorizeFunctionName(formatCodeClamp(functionName))}. derive() (formerly declareStatic()) can only receive function invocations and cannot use undefined values or looped calls to construct its result.`\n ),\n location\n );\n\nexport const warnAutoderiveNoResultsSync = (\n file: string,\n expression: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Autoderive could not resolve ${colorizeFunctionName(formatCodeClamp(expression))}. Only function calls with statically determinable return values can be used directly in t(). Consider wrapping with derive() for explicit derivation, or use an interpolation variable instead.`,\n location\n );\n\nexport const warnDeriveUnresolvableValueSync = (\n file: string,\n key: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Object property ${colorizeFunctionName(formatCodeClamp(key))} could not be resolved to a static string value. Only string literals, template literals, conditionals, and function calls returning strings are supported.`\n ),\n location\n );\n\nexport const warnDeriveCircularSpreadSync = (\n file: string,\n varName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Circular spread detected involving ${colorizeFunctionName(varName)}. Spread references that form a cycle cannot be resolved statically.`\n ),\n location\n );\n\nexport const warnDeriveDestructuringSync = (\n file: string,\n varName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Variable ${colorizeFunctionName(varName)} uses destructuring syntax, which is not yet supported in derive(). Assign the value to a const variable directly instead.`\n ),\n location\n );\n\nexport const warnDeriveOptionalChainingSync = (\n file: string,\n code: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Optional chaining (${colorizeFunctionName(formatCodeClamp(code))}) is not supported in derive(). Optional chaining implies the value could be undefined, which cannot be resolved statically. Use a non-optional access instead.`\n ),\n location\n );\n\nexport const warnUnresolvedImportSync = (\n file: string,\n functionName: string,\n importPath: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Could not resolve import ${colorizeFunctionName(importPath)} for function ${colorizeFunctionName(functionName)}. Translation strings inside this function will not be extracted.`,\n location\n );\n\n// Re-export error messages\nexport const noLocalesError = `No target locales were found. Add locales to gt.config.json or pass them with the --locales flag.`;\nexport const noDefaultLocaleError = `No default locale was found. Add defaultLocale to gt.config.json or pass it with --default-locale.`;\nexport const noFilesError = `The files configuration is missing or invalid. Check the files section in gt.config.json and try again.`;\nexport const noSourceFileError = `No source translation file was found. Check your translations directory and default locale configuration.`;\nexport const noSupportedFormatError = `The translation file format is not supported. Use a supported file extension in translationsDir.`;\nexport const noApiKeyError = `No API key was found. Pass --api-key or set the GT_API_KEY environment variable.`;\nexport const devApiKeyError = `Development API keys cannot be used with the General Translation API. Use a production API key instead.\\nGenerate a production API key with: npx gt auth -t production`;\nexport const noProjectIdError = `No project ID was found. Pass --project-id, add projectId to gt.config.json, or set the GT_PROJECT_ID environment variable.`;\nexport const noVersionIdError = `No version ID was found. Pass --version-id or add _versionId to gt.config.json.`;\nexport const invalidConfigurationError = `The files configuration cannot be used for this operation. Provide a valid download configuration or set --publish true to upload translations to the CDN.`;\nexport const branchResolutionError = `The current git branch could not be resolved. Specify a branch explicitly or run the command from a git worktree with branch metadata available.`;\n\nexport const withOriginalError = (message: string, error: unknown): string =>\n error != null ? `${message} Original error: ${String(error)}` : message;\n"],"mappings":";;;;AAWA,MAAM,8BAA8B,YAClC,GAAG,QAAQ;AAGb,MAAM,4BAA4B,YAChC,6BAA6B;AAE/B,MAAM,2BAA2B,YAC/B,6BAA6B;AAE/B,MAAa,0BAA0B,oBACrC,GAAG,iBACD,gBACD,CAAC;AAEJ,MAAa,wBACX,MACA,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SAAiB,UACjD,SAAS,OAAO,GAAG,QAAQ,mBAAmB,OAAO,MAAM,KAAK"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/console/index.ts"],"sourcesContent":["import { BRANCH_COMPONENT } from '../react/jsx/utils/constants.js';\nimport {\n colorizeFilepath,\n colorizeComponent,\n colorizeIdString,\n colorizeContent,\n colorizeLine,\n colorizeFunctionName,\n} from './colors.js';\nimport { formatCodeClamp } from './formatting.js';\n\nconst withWillErrorInNextVersion = (message: string): string =>\n `${message} (This will become an error in the next major version of the CLI.)`;\n\n// Derive function related errors\nconst withDeriveComponentError = (message: string): string =>\n `<Derive> rules violation: ${message}`;\n\nconst withDeriveFunctionError = (message: string): string =>\n `derive() rules violation: ${message}`;\n// Synchronous wrappers for backward compatibility\nexport const warnApiKeyInConfigSync = (optionsFilepath: string): string =>\n `${colorizeFilepath(\n optionsFilepath\n )}: Your API key is exposed! Remove it from the file and include it as an environment variable.`;\n\nexport const warnVariablePropSync = (\n file: string,\n attrName: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `${colorizeComponent('<T>')} component has dynamic attribute ${colorizeIdString(attrName)} with value: ${colorizeContent(\n value\n )}. Change ${colorizeIdString(attrName)} to ensure this content is translated.`,\n location\n );\n\nexport const warnInvalidReturnSync = (\n file: string,\n functionName: string,\n expression: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveComponentError(\n `Function ${colorizeFunctionName(functionName)} does not return a derivable (statically analyzable) expression. ${colorizeFunctionName(functionName)} must return either (1) a derivable string literal, (2) another derivable function invocation, (3) derivable JSX content, or (4) a ternary expression. Instead got:\\n${colorizeContent(expression)}`\n ),\n location\n );\n\n// TODO: this is temporary until we handle implicit returns\nexport const warnMissingReturnSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Function ${colorizeFunctionName(functionName)} is wrapped in ${colorizeComponent('<Derive>')} tags but does not have an explicit return statement. Derivable functions must have an explicit return statement.`,\n location\n );\n\nexport const warnHasUnwrappedExpressionSync = (\n file: string,\n unwrappedExpressions: string[],\n id?: string,\n location?: string\n): string =>\n withLocation(\n file,\n `${colorizeComponent('<T>')} component${\n id ? ` with id ${colorizeIdString(id)}` : ''\n } has children that could change at runtime. Use a variable component like ${colorizeComponent(\n '<Var>'\n )} to ensure this content is translated.\\n${colorizeContent(\n unwrappedExpressions.join('\\n')\n )}`,\n location\n );\n\nexport const warnFailedToConstructJsxTreeSync = (\n file: string,\n code: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Failed to construct JsxTree! Call expression is not a valid createElement call: ${colorizeContent(code)}`,\n location\n );\n\nexport const warnNestedTComponent = (file: string, location?: string): string =>\n withLocation(\n file,\n `Found nested <T> component. <T> components cannot be directly nested.`,\n location\n );\n\nexport const warnNestedInternalTComponent = (\n file: string,\n location?: string\n): string =>\n withLocation(\n file,\n `DEBUG: Found nested <GtInternalTranslateJsx> component. <GtInternalTranslateJsx> components cannot be directly nested.`,\n location\n );\n\nexport const warnNonStaticExpressionSync = (\n file: string,\n attrName: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found non-static expression for attribute ${colorizeIdString(\n attrName\n )}: ${colorizeContent(value)}. Change \"${colorizeIdString(attrName)}\" to ensure this content is translated.`,\n location\n );\n\nexport const warnInvalidMaxCharsSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found invalid maxChars value: ${colorizeContent(value)}. Change the value to a valid number to ensure this content is translated.`,\n location\n );\n\nexport const warnInvalidFormatSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found invalid $format value: ${colorizeContent(value)}. Must be one of: 'ICU', 'STRING', 'I18NEXT'.`,\n location\n );\n\nexport const warnInvalidRequiresReviewSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found invalid requiresReview value: ${colorizeContent(value)}. Must be a boolean literal (true or false) — strings and dynamic expressions are not allowed.`,\n location\n );\n\nexport const warnInvalidIcuSync = (\n file: string,\n value: string,\n error: string,\n location?: string\n): string =>\n withWillErrorInNextVersion(\n withLocation(\n file,\n `Found invalid ICU string: ${colorizeContent(value)}. Change the value to a valid ICU to ensure this content is translated. Error message: ${error}.`,\n location\n )\n );\n\nexport const warnTemplateLiteralSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found template literal with quasis (${colorizeContent(value)}). Change the template literal to a string to ensure this content is translated.`,\n location\n );\n\nexport const warnNonStringSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found non-string literal (${colorizeContent(value)}). Change the value to a string literal to ensure this content is translated.`,\n location\n );\n\nexport const warnAsyncUseGT = (file: string, location?: string): string =>\n withLocation(\n file,\n `Found useGT() in an async function. Use getGT() instead, or make the function synchronous.`,\n location\n );\n\nexport const warnSyncGetGT = (file: string, location?: string): string =>\n withLocation(\n file,\n `Found getGT() in a synchronous function. Use useGT() instead, or make the function async.`,\n location\n );\n\nexport const warnTernarySync = (file: string, location?: string): string =>\n withLocation(\n file,\n 'Found ternary expression. A Branch component may be more appropriate here.',\n location\n );\n\nexport const withLocation = (\n file: string,\n message: string,\n location?: string\n): string =>\n `${colorizeFilepath(file)}${location ? ` (${colorizeLine(location)})` : ''}: ${message}`;\n\nexport const warnFunctionNotFoundSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Function ${colorizeFunctionName(functionName)} definition could not be resolved. This might affect translation resolution for this ${colorizeComponent('<T>')} component.`,\n location\n );\n\nexport const warnInvalidDeclareVarNameSync = (\n file: string,\n value: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Found invalid declareVar() $name tag. Must be a derivable (statically analyzable) expression. Received: ${colorizeContent(value)}.`,\n location\n );\n\nexport const warnDuplicateFunctionDefinitionSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Function ${colorizeFunctionName(functionName)} is defined multiple times. Only the first definition will be used.`,\n location\n );\n\nexport const warnInvalidDeriveInitSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveComponentError(\n `The definition for ${colorizeFunctionName(functionName)} could not be resolved. When using arrow syntax to define a derivable (statically analyzable) function, the right hand side or the assignment MUST only contain the arrow function itself and no other expressions.\nExample: ${colorizeContent(`const ${colorizeFunctionName(functionName)} = () => { ... }`)}\nInvalid: ${colorizeContent(`const ${colorizeFunctionName(functionName)} = [() => { ... }][0]`)}`\n ),\n location\n );\n\nexport const warnDataAttrOnBranch = (\n file: string,\n attrName: string,\n location?: string\n): string =>\n withLocation(\n file,\n `${colorizeComponent(`<${BRANCH_COMPONENT}>`)} component ignores attributes prefixed with ${colorizeIdString('\"data-\"')}. Found ${colorizeIdString(attrName)}. Remove it or use a different attribute name.`,\n location\n );\n\nexport const warnRecursiveFunctionCallSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveComponentError(\n `Recursive function call detected: ${colorizeFunctionName(functionName)}. A derivable (statically analyzable) function cannot use recursive calls to construct its result.`\n ),\n location\n );\n\nexport const warnDeriveFunctionNotWrappedSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Could not resolve ${colorizeFunctionName(formatCodeClamp(functionName))}. This call is not wrapped in derive(). Ensure the function is properly wrapped with derive() and does not have circular import dependencies.`\n ),\n location\n );\n\nexport const warnDeriveNonConstVariableSync = (\n file: string,\n varName: string,\n kind: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Variable ${colorizeFunctionName(varName)} is declared with '${kind}' but only 'const' declarations can be resolved statically. Change it to 'const'.`\n ),\n location\n );\n\nexport const warnDeriveFunctionNoResultsSync = (\n file: string,\n functionName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Could not resolve ${colorizeFunctionName(formatCodeClamp(functionName))}. derive() can only receive function invocations and cannot use undefined values or looped calls to construct its result.`\n ),\n location\n );\n\nexport const warnAutoderiveNoResultsSync = (\n file: string,\n expression: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Autoderive could not resolve ${colorizeFunctionName(formatCodeClamp(expression))}. Only function calls with statically determinable return values can be used directly in t(). Consider wrapping with derive() for explicit derivation, or use an interpolation variable instead.`,\n location\n );\n\nexport const warnDeriveUnresolvableValueSync = (\n file: string,\n key: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Object property ${colorizeFunctionName(formatCodeClamp(key))} could not be resolved to a static string value. Only string literals, template literals, conditionals, and function calls returning strings are supported.`\n ),\n location\n );\n\nexport const warnDeriveCircularSpreadSync = (\n file: string,\n varName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Circular spread detected involving ${colorizeFunctionName(varName)}. Spread references that form a cycle cannot be resolved statically.`\n ),\n location\n );\n\nexport const warnDeriveDestructuringSync = (\n file: string,\n varName: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Variable ${colorizeFunctionName(varName)} uses destructuring syntax, which is not yet supported in derive(). Assign the value to a const variable directly instead.`\n ),\n location\n );\n\nexport const warnDeriveOptionalChainingSync = (\n file: string,\n code: string,\n location?: string\n): string =>\n withLocation(\n file,\n withDeriveFunctionError(\n `Optional chaining (${colorizeFunctionName(formatCodeClamp(code))}) is not supported in derive(). Optional chaining implies the value could be undefined, which cannot be resolved statically. Use a non-optional access instead.`\n ),\n location\n );\n\nexport const warnUnresolvedImportSync = (\n file: string,\n functionName: string,\n importPath: string,\n location?: string\n): string =>\n withLocation(\n file,\n `Could not resolve import ${colorizeFunctionName(importPath)} for function ${colorizeFunctionName(functionName)}. Translation strings inside this function will not be extracted.`,\n location\n );\n\n// Re-export error messages\nexport const noLocalesError = `No target locales were found. Add locales to gt.config.json or pass them with the --locales flag.`;\nexport const noDefaultLocaleError = `No default locale was found. Add defaultLocale to gt.config.json or pass it with --default-locale.`;\nexport const noFilesError = `The files configuration is missing or invalid. Check the files section in gt.config.json and try again.`;\nexport const noSourceFileError = `No source translation file was found. Check your translations directory and default locale configuration.`;\nexport const noApiKeyError = `No API key was found. Pass --api-key or set the GT_API_KEY environment variable.`;\nexport const devApiKeyError = `Development API keys cannot be used with the General Translation API. Use a production API key instead.\\nGenerate a production API key with: npx gt auth -t production`;\nexport const noProjectIdError = `No project ID was found. Pass --project-id, add projectId to gt.config.json, or set the GT_PROJECT_ID environment variable.`;\nexport const invalidConfigurationError = `The files configuration cannot be used for this operation. Provide a valid download configuration or set --publish true to upload translations to the CDN.`;\nexport const branchResolutionError = `The current git branch could not be resolved. Specify a branch explicitly or run the command from a git worktree with branch metadata available.`;\n\nexport const withOriginalError = (message: string, error: unknown): string =>\n error != null ? `${message} Original error: ${String(error)}` : message;\n"],"mappings":";;;;AAWA,MAAM,8BAA8B,YAClC,GAAG,QAAQ;AAGb,MAAM,4BAA4B,YAChC,6BAA6B;AAE/B,MAAM,2BAA2B,YAC/B,6BAA6B;AAE/B,MAAa,0BAA0B,oBACrC,GAAG,iBACD,gBACD,CAAC;AAEJ,MAAa,wBACX,MACA,UACA,OACA,aAEA,aACE,MACA,GAAG,kBAAkB,MAAM,CAAC,mCAAmC,iBAAiB,SAAS,CAAC,eAAe,gBACvG,MACD,CAAC,WAAW,iBAAiB,SAAS,CAAC,yCACxC,SACD;AAEH,MAAa,yBACX,MACA,cACA,YACA,aAEA,aACE,MACA,yBACE,YAAY,qBAAqB,aAAa,CAAC,mEAAmE,qBAAqB,aAAa,CAAC,uKAAuK,gBAAgB,WAAW,GACxV,EACD,SACD;AAGH,MAAa,yBACX,MACA,cACA,aAEA,aACE,MACA,YAAY,qBAAqB,aAAa,CAAC,iBAAiB,kBAAkB,WAAW,CAAC,oHAC9F,SACD;AAEH,MAAa,kCACX,MACA,sBACA,IACA,aAEA,aACE,MACA,GAAG,kBAAkB,MAAM,CAAC,YAC1B,KAAK,YAAY,iBAAiB,GAAG,KAAK,GAC3C,4EAA4E,kBAC3E,QACD,C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Aa,gCACX,MACA,SACA,aAEA,aACE,MACA,wBACE,sCAAsC,qBAAqB,QAAQ,CAAC,sEACrE,EACD,SACD;AAEH,MAAa,+BACX,MACA,SACA,aAEA,aACE,MACA,wBACE,YAAY,qBAAqB,QAAQ,CAAC,4HAC3C,EACD,SACD;AAEH,MAAa,kCACX,MACA,MACA,aAEA,aACE,MACA,wBACE,sBAAsB,qBAAqB,gBAAgB,KAAK,CAAC,CAAC,iKACnE,EACD,SACD;AAEH,MAAa,4BACX,MACA,cACA,YACA,aAEA,aACE,MACA,4BAA4B,qBAAqB,WAAW,CAAC,gBAAgB,qBAAqB,aAAa,CAAC,oEAChH,SACD;AAGH,MAAa,iBAAiB;AAC9B,MAAa,uBAAuB;AACpC,MAAa,eAAe;AAC5B,MAAa,oBAAoB;AACjC,MAAa,gBAAgB;AAC7B,MAAa,iBAAiB;AAC9B,MAAa,mBAAmB;AAChC,MAAa,4BAA4B;AACzC,MAAa,wBAAwB;AAErC,MAAa,qBAAqB,SAAiB,UACjD,SAAS,OAAO,GAAG,QAAQ,mBAAmB,OAAO,MAAM,KAAK"}
|
|
@@ -8,7 +8,6 @@ async function calculateHashes(updates) {
|
|
|
8
8
|
const hash = hashSource({
|
|
9
9
|
source: update.source,
|
|
10
10
|
...update.metadata.context && { context: update.metadata.context },
|
|
11
|
-
...update.metadata.id && { id: update.metadata.id },
|
|
12
11
|
...update.metadata.maxChars != null && { maxChars: update.metadata.maxChars },
|
|
13
12
|
...update.metadata.requiresReview === true && { requiresReview: true },
|
|
14
13
|
dataFormat: update.dataFormat
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postProcess.js","names":[],"sources":["../../src/extraction/postProcess.ts"],"sourcesContent":["import { Updates } from '../types/index.js';\nimport { hashSource, hashString } from 'generaltranslation/id';\nimport type { SourceCode } from '../react/jsx/utils/extractSourceCode.js';\n\n/**\n * Calculate hashes for all updates in parallel\n */\nexport async function calculateHashes(updates: Updates): Promise<void> {\n await Promise.all(\n updates.map(async (update) => {\n const hash = hashSource({\n source: update.source,\n ...(update.metadata.context && { context: update.metadata.context }),\n ...(update.metadata.
|
|
1
|
+
{"version":3,"file":"postProcess.js","names":[],"sources":["../../src/extraction/postProcess.ts"],"sourcesContent":["import { Updates } from '../types/index.js';\nimport { hashSource, hashString } from 'generaltranslation/id';\nimport type { SourceCode } from '../react/jsx/utils/extractSourceCode.js';\n\n/**\n * Calculate hashes for all updates in parallel\n */\nexport async function calculateHashes(updates: Updates): Promise<void> {\n await Promise.all(\n updates.map(async (update) => {\n const hash = hashSource({\n source: update.source,\n ...(update.metadata.context && { context: update.metadata.context }),\n ...(update.metadata.maxChars != null && {\n maxChars: update.metadata.maxChars,\n }),\n // Only the explicit prop is hash-changing. Config-level review\n // defaults materialize into GTJSON metadata without touching hashes,\n // because the runtime computes lookup hashes from props alone.\n ...(update.metadata.requiresReview === true && {\n requiresReview: true,\n }),\n dataFormat: update.dataFormat,\n });\n update.metadata.hash = hash;\n })\n );\n}\n\n/**\n * Dedupe entries by hash, merging filePaths\n */\nexport function dedupeUpdates(updates: Updates): void {\n const mergedByHash = new Map<string, (typeof updates)[number]>();\n const noHashUpdates: (typeof updates)[number][] = [];\n\n for (const update of updates) {\n const hash = update.metadata.hash;\n if (!hash) {\n noHashUpdates.push(update);\n continue;\n }\n\n const existing = mergedByHash.get(hash);\n if (!existing) {\n mergedByHash.set(hash, update);\n continue;\n }\n\n const existingPaths = Array.isArray(existing.metadata.filePaths)\n ? existing.metadata.filePaths.slice()\n : [];\n const newPaths = Array.isArray(update.metadata.filePaths)\n ? update.metadata.filePaths\n : [];\n\n for (const p of newPaths) {\n if (!existingPaths.includes(p)) {\n existingPaths.push(p);\n }\n }\n\n if (existingPaths.length) {\n existing.metadata.filePaths = existingPaths;\n }\n\n // Merge sourceCode entries\n const newSourceCode = update.metadata.sourceCode as\n | Record<string, SourceCode[]>\n | undefined;\n if (newSourceCode && typeof newSourceCode === 'object') {\n if (!existing.metadata.sourceCode) {\n existing.metadata.sourceCode = {};\n }\n const existingSourceCode = existing.metadata.sourceCode as Record<\n string,\n SourceCode[]\n >;\n for (const [file, entries] of Object.entries(newSourceCode)) {\n if (!existingSourceCode[file]) {\n existingSourceCode[file] = [];\n }\n existingSourceCode[file].push(...entries);\n }\n }\n }\n\n const mergedUpdates = [...mergedByHash.values(), ...noHashUpdates];\n updates.splice(0, updates.length, ...mergedUpdates);\n}\n\n/**\n * Mark derive updates as related by attaching a shared id to derive content.\n * Id is calculated as the hash of the derive children's combined hashes.\n */\nexport function linkDeriveUpdates(updates: Updates): void {\n const temporaryDeriveIdToUpdates = updates.reduce(\n (acc: Record<string, Updates[number][]>, update: Updates[number]) => {\n if (update.metadata.staticId) {\n if (!acc[update.metadata.staticId]) {\n acc[update.metadata.staticId] = [];\n }\n acc[update.metadata.staticId].push(update);\n }\n return acc;\n },\n {} as Record<string, Updates[number][]>\n );\n\n Object.values(temporaryDeriveIdToUpdates).forEach((deriveUpdates) => {\n const hashes = deriveUpdates\n .map((update) => update.metadata.hash)\n .sort()\n .join('-');\n const sharedDeriveId = hashString(hashes);\n deriveUpdates.forEach((update) => {\n update.metadata.staticId = sharedDeriveId;\n });\n });\n}\n"],"mappings":";;;;;AAOA,eAAsB,gBAAgB,SAAiC;AACrE,OAAM,QAAQ,IACZ,QAAQ,IAAI,OAAO,WAAW;EAC5B,MAAM,OAAO,WAAW;GACtB,QAAQ,OAAO;GACf,GAAI,OAAO,SAAS,WAAW,EAAE,SAAS,OAAO,SAAS,SAAS;GACnE,GAAI,OAAO,SAAS,YAAY,QAAQ,EACtC,UAAU,OAAO,SAAS,UAC3B;GAID,GAAI,OAAO,SAAS,mBAAmB,QAAQ,EAC7C,gBAAgB,MACjB;GACD,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,SAAS,OAAO;GACvB,CACH;;;;;AAMH,SAAgB,cAAc,SAAwB;CACpD,MAAM,+BAAe,IAAI,KAAuC;CAChE,MAAM,gBAA4C,EAAE;AAEpD,MAAK,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