gt 2.27.0 → 2.27.2
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 +29 -0
- package/dist/auth/cliApiKey.d.ts +7 -0
- package/dist/auth/cliApiKey.js +18 -0
- package/dist/auth/cliApiKey.js.map +1 -0
- package/dist/cli/base.d.ts +1 -1
- package/dist/cli/base.js +27 -7
- package/dist/cli/base.js.map +1 -1
- package/dist/cli/commands/api.js +2 -1
- package/dist/cli/commands/api.js.map +1 -1
- package/dist/cli/commands/utils/validation.js +1 -1
- package/dist/cli/commands/utils/validation.js.map +1 -1
- package/dist/config/generateSettings.js +2 -1
- package/dist/config/generateSettings.js.map +1 -1
- package/dist/console/index.d.ts +1 -1
- package/dist/console/index.js +7 -1
- package/dist/console/index.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/setup/buildTools/index.d.ts +2 -0
- package/dist/setup/buildTools/index.js +11 -1
- package/dist/setup/buildTools/index.js.map +1 -1
- package/dist/setup/buildTools/vite.js +2 -1
- package/dist/setup/buildTools/vite.js.map +1 -1
- package/dist/setup/detectFramework.d.ts +5 -4
- package/dist/setup/detectFramework.js +7 -2
- package/dist/setup/detectFramework.js.map +1 -1
- package/dist/setup/developmentCredentials.js +1 -1
- package/dist/setup/instructions/base.md +1 -1
- package/dist/setup/instructions/gt-next.md +1 -1
- package/dist/setup/instructions/gt-react.md +1 -1
- package/dist/setup/nextSteps.d.ts +31 -0
- package/dist/setup/nextSteps.js +46 -0
- package/dist/setup/nextSteps.js.map +1 -0
- package/dist/setup/onboarding.d.ts +3 -0
- package/dist/setup/onboarding.js +3 -2
- package/dist/setup/onboarding.js.map +1 -1
- package/dist/setup/setupTarget.d.ts +2 -0
- package/dist/setup/setupTarget.js +10 -1
- package/dist/setup/setupTarget.js.map +1 -1
- package/dist/setup/wizard.d.ts +1 -1
- package/dist/setup/wizard.js +6 -8
- package/dist/setup/wizard.js.map +1 -1
- package/dist/types/index.d.ts +5 -0
- package/dist/types/index.js.map +1 -1
- package/dist/utils/api.d.ts +13 -0
- package/dist/utils/constants.d.ts +4 -1
- package/dist/utils/constants.js +5 -2
- package/dist/utils/constants.js.map +1 -1
- package/dist/utils/credentials.d.ts +3 -2
- package/dist/utils/credentials.js +18 -10
- package/dist/utils/credentials.js.map +1 -1
- package/dist/utils/loadEnv.d.ts +2 -0
- package/dist/utils/loadEnv.js +9 -1
- package/dist/utils/loadEnv.js.map +1 -1
- package/dist/workflows/download.d.ts +1 -1
- package/dist/workflows/download.js +20 -2
- package/dist/workflows/download.js.map +1 -1
- package/dist/workflows/stage.js +2 -1
- package/dist/workflows/stage.js.map +1 -1
- package/dist/workflows/steps/PollJobsStep.d.ts +3 -1
- package/dist/workflows/steps/PollJobsStep.js +4 -1
- package/dist/workflows/steps/PollJobsStep.js.map +1 -1
- package/package.json +5 -5
package/dist/utils/constants.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { hashStringSync } from "./hash.js";
|
|
2
2
|
//#region src/utils/constants.ts
|
|
3
3
|
const GT_DASHBOARD_URL = "https://dash.generaltranslation.com";
|
|
4
|
-
const REACT_QUICKSTART_URL = "https://generaltranslation.com/docs/react/
|
|
4
|
+
const REACT_QUICKSTART_URL = "https://generaltranslation.com/docs/react/react-quickstart";
|
|
5
|
+
const NEXT_APP_QUICKSTART_URL = "https://generaltranslation.com/docs/react/nextjs-quickstart";
|
|
6
|
+
const NEXT_PAGES_QUICKSTART_URL = "https://generaltranslation.com/docs/react/nextjs-pages-router-quickstart";
|
|
7
|
+
const REACT_SPA_QUICKSTART_URL = "https://generaltranslation.com/docs/react/react-spa-quickstart";
|
|
5
8
|
const GT_CONFIG_SCHEMA_URL = "https://assets.gtx.dev/config-schema.json";
|
|
6
9
|
const TEMPLATE_FILE_NAME = "__INTERNAL_GT_TEMPLATE_NAME__";
|
|
7
10
|
const TEMPLATE_FILE_ID = hashStringSync(TEMPLATE_FILE_NAME);
|
|
@@ -12,6 +15,6 @@ const DEFAULT_TRANSLATIONS_DIR = "./public/_gt";
|
|
|
12
15
|
const DEFAULT_VITE_TRANSLATIONS_DIR = "./src/_gt";
|
|
13
16
|
const DEFAULT_REACT_ROUTER_TRANSLATIONS_DIR = "./app/_gt";
|
|
14
17
|
//#endregion
|
|
15
|
-
export { DEFAULT_GIT_REMOTE_NAME, DEFAULT_REACT_ROUTER_TRANSLATIONS_DIR, DEFAULT_TIMEOUT_SECONDS, DEFAULT_TRANSLATIONS_DIR, DEFAULT_VITE_TRANSLATIONS_DIR, GT_CONFIG_SCHEMA_URL, GT_DASHBOARD_URL, REACT_QUICKSTART_URL, SURROUNDING_LINE_COUNT, TEMPLATE_FILE_ID, TEMPLATE_FILE_NAME };
|
|
18
|
+
export { DEFAULT_GIT_REMOTE_NAME, DEFAULT_REACT_ROUTER_TRANSLATIONS_DIR, DEFAULT_TIMEOUT_SECONDS, DEFAULT_TRANSLATIONS_DIR, DEFAULT_VITE_TRANSLATIONS_DIR, GT_CONFIG_SCHEMA_URL, GT_DASHBOARD_URL, NEXT_APP_QUICKSTART_URL, NEXT_PAGES_QUICKSTART_URL, REACT_QUICKSTART_URL, REACT_SPA_QUICKSTART_URL, SURROUNDING_LINE_COUNT, TEMPLATE_FILE_ID, TEMPLATE_FILE_NAME };
|
|
16
19
|
|
|
17
20
|
//# sourceMappingURL=constants.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":[],"sources":["../../src/utils/constants.ts"],"sourcesContent":["import { hashStringSync } from './hash.js';\n\nexport const GT_DASHBOARD_URL = 'https://dash.generaltranslation.com';\n\nexport const REACT_QUICKSTART_URL =\n 'https://generaltranslation.com/docs/react/
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../../src/utils/constants.ts"],"sourcesContent":["import { hashStringSync } from './hash.js';\n\nexport const GT_DASHBOARD_URL = 'https://dash.generaltranslation.com';\n\nexport const REACT_QUICKSTART_URL =\n 'https://generaltranslation.com/docs/react/react-quickstart';\nexport const NEXT_APP_QUICKSTART_URL =\n 'https://generaltranslation.com/docs/react/nextjs-quickstart';\nexport const NEXT_PAGES_QUICKSTART_URL =\n 'https://generaltranslation.com/docs/react/nextjs-pages-router-quickstart';\nexport const REACT_SPA_QUICKSTART_URL =\n 'https://generaltranslation.com/docs/react/react-spa-quickstart';\n\nexport const GT_CONFIG_SCHEMA_URL = 'https://assets.gtx.dev/config-schema.json';\n\nexport const TEMPLATE_FILE_NAME = '__INTERNAL_GT_TEMPLATE_NAME__';\nexport const TEMPLATE_FILE_ID = hashStringSync(TEMPLATE_FILE_NAME);\n\nexport const DEFAULT_GIT_REMOTE_NAME = 'origin';\n\nexport const DEFAULT_TIMEOUT_SECONDS = 900;\n\n// Number of source code lines to capture above and below a translation site\nexport const SURROUNDING_LINE_COUNT = 5;\n\n// Default translations directory paths\nexport const DEFAULT_TRANSLATIONS_DIR = './public/_gt';\nexport const DEFAULT_VITE_TRANSLATIONS_DIR = './src/_gt';\nexport const DEFAULT_REACT_ROUTER_TRANSLATIONS_DIR = './app/_gt';\n"],"mappings":";;AAEA,MAAa,mBAAmB;AAEhC,MAAa,uBACX;AACF,MAAa,0BACX;AACF,MAAa,4BACX;AACF,MAAa,2BACX;AAEF,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAClC,MAAa,mBAAmB,eAAe,mBAAmB;AAElE,MAAa,0BAA0B;AAEvC,MAAa,0BAA0B;AAGvC,MAAa,yBAAyB;AAGtC,MAAa,2BAA2B;AACxC,MAAa,gCAAgC;AAC7C,MAAa,wCAAwC"}
|
|
@@ -11,8 +11,9 @@ export declare function getDevelopmentEnvNames(framework?: SupportedFrameworks):
|
|
|
11
11
|
/**
|
|
12
12
|
* Whether the project has the framework's development key, or an explicit
|
|
13
13
|
* API key for a server-only runtime. A tooling key cannot enable client-side
|
|
14
|
-
* hot reload
|
|
15
|
-
*
|
|
14
|
+
* hot reload. Next.js uses GT_API_KEY for both, and still accepts the
|
|
15
|
+
* NEXT_PUBLIC_ key earlier versions of init wrote. `settings.projectId`
|
|
16
|
+
* already resolves every framework prefix. Login is checked separately.
|
|
16
17
|
*/
|
|
17
18
|
export declare function areCredentialsSet(settings: Pick<Settings, 'projectId' | 'apiKey'>, framework?: SupportedFrameworks): boolean;
|
|
18
19
|
/**
|
|
@@ -3,8 +3,8 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import { promisify } from "node:util";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs from "node:fs";
|
|
6
|
-
import { execFile } from "node:child_process";
|
|
7
6
|
import dotenv from "dotenv";
|
|
7
|
+
import { execFile } from "node:child_process";
|
|
8
8
|
//#region src/utils/credentials.ts
|
|
9
9
|
const execFileAsync = promisify(execFile);
|
|
10
10
|
const unsafeCredentialsEnvError = createDiagnosticMessage({
|
|
@@ -68,8 +68,6 @@ function gitCheckFailedError(file, stderr) {
|
|
|
68
68
|
});
|
|
69
69
|
}
|
|
70
70
|
const FRAMEWORK_ENV_PREFIXES = {
|
|
71
|
-
"next-app": "NEXT_PUBLIC_",
|
|
72
|
-
"next-pages": "NEXT_PUBLIC_",
|
|
73
71
|
vite: "VITE_",
|
|
74
72
|
gatsby: "GATSBY_",
|
|
75
73
|
react: "REACT_APP_",
|
|
@@ -79,6 +77,10 @@ const FRAMEWORK_ENV_PREFIXES = {
|
|
|
79
77
|
};
|
|
80
78
|
/** Names of the runtime variables init writes for this framework. */
|
|
81
79
|
function getDevelopmentEnvNames(framework) {
|
|
80
|
+
if (isNextFramework(framework)) return {
|
|
81
|
+
projectId: "GT_PROJECT_ID",
|
|
82
|
+
devApiKey: "GT_API_KEY"
|
|
83
|
+
};
|
|
82
84
|
const prefix = (framework && FRAMEWORK_ENV_PREFIXES[framework]) ?? "";
|
|
83
85
|
return {
|
|
84
86
|
projectId: `${prefix}GT_PROJECT_ID`,
|
|
@@ -88,13 +90,18 @@ function getDevelopmentEnvNames(framework) {
|
|
|
88
90
|
/**
|
|
89
91
|
* Whether the project has the framework's development key, or an explicit
|
|
90
92
|
* API key for a server-only runtime. A tooling key cannot enable client-side
|
|
91
|
-
* hot reload
|
|
92
|
-
*
|
|
93
|
+
* hot reload. Next.js uses GT_API_KEY for both, and still accepts the
|
|
94
|
+
* NEXT_PUBLIC_ key earlier versions of init wrote. `settings.projectId`
|
|
95
|
+
* already resolves every framework prefix. Login is checked separately.
|
|
93
96
|
*/
|
|
94
97
|
function areCredentialsSet(settings, framework) {
|
|
95
98
|
const { devApiKey } = getDevelopmentEnvNames(framework);
|
|
96
|
-
const
|
|
97
|
-
|
|
99
|
+
const devApiKeys = isNextFramework(framework) ? [devApiKey, "NEXT_PUBLIC_GT_DEV_API_KEY"] : [devApiKey];
|
|
100
|
+
const needsDevKey = Boolean(framework && FRAMEWORK_ENV_PREFIXES[framework]);
|
|
101
|
+
return Boolean(settings.projectId && (devApiKeys.some((name) => process.env[name]) || !needsDevKey && settings.apiKey));
|
|
102
|
+
}
|
|
103
|
+
function isNextFramework(framework) {
|
|
104
|
+
return framework === "next-app" || framework === "next-pages";
|
|
98
105
|
}
|
|
99
106
|
function assignedName(line) {
|
|
100
107
|
return /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line)?.[1];
|
|
@@ -258,9 +265,10 @@ async function writeEnvFileAtomically(target, content, mode) {
|
|
|
258
265
|
/**
|
|
259
266
|
* .env.local content with the runtime credentials set. Only the hot-reload
|
|
260
267
|
* key: the CLI itself acts as the signed-in user, and CI keys are created
|
|
261
|
-
* deliberately rather than dropped into .env.local. Other lines
|
|
262
|
-
*
|
|
263
|
-
*
|
|
268
|
+
* deliberately rather than dropped into .env.local. Other lines and comments
|
|
269
|
+
* are left untouched, as is GT_API_KEY except in Next.js, which
|
|
270
|
+
* uses it as the development key. Throws when the edit could corrupt a
|
|
271
|
+
* multiline value.
|
|
264
272
|
*/
|
|
265
273
|
function updateCredentialsEnvContent(envContent, credentials, framework) {
|
|
266
274
|
const names = getDevelopmentEnvNames(framework);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"credentials.js","names":[],"sources":["../../src/utils/credentials.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport { promisify } from 'node:util';\nimport dotenv from 'dotenv';\nimport { Settings, SupportedFrameworks } from '../types/index.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\n\nconst execFileAsync = promisify(execFile);\n\nconst unsafeCredentialsEnvError = createDiagnosticMessage({\n whatHappened: 'Cannot safely update .env.local',\n reassurance: 'The existing .env.local file was not changed',\n fix: 'Move multiline values away from project/key assignments or set the development credentials manually, then retry',\n});\n\nfunction unwritableEnvFileError(envFile: string): string {\n return createDiagnosticMessage({\n whatHappened: `${envFile} is not a regular file`,\n reassurance: 'Nothing was changed',\n fix: 'Replace it with a regular file or a symlink to one, or set the development credentials manually, then retry',\n });\n}\n\nfunction trackedEnvFileError(file: string): string {\n return createDiagnosticMessage({\n whatHappened: `${file} is tracked by Git`,\n why: 'development credentials saved there would be committed',\n reassurance: 'Nothing was changed',\n fix: `Run \\`git rm --cached ${path.basename(file)}\\` in ${path.dirname(file)} and add the file to .gitignore, then retry`,\n });\n}\n\nfunction unignoredEnvFileError(file: string): string {\n return createDiagnosticMessage({\n whatHappened: `${file} is not ignored by Git`,\n why: 'development credentials saved there could be committed',\n reassurance: 'Nothing was changed',\n fix: `Add the file to a .gitignore that applies to ${path.dirname(file)}, then retry`,\n });\n}\n\nfunction unignoredEnvFileReferentError(envFile: string, referent: string) {\n return createDiagnosticMessage({\n whatHappened: `${envFile} links to ${referent}, which Git does not ignore`,\n why: 'development credentials saved there could be committed',\n reassurance: 'Nothing was changed',\n fix: `Add ${referent} to a .gitignore in its repository or set the development credentials manually, then retry`,\n });\n}\n\nfunction gitUnavailableError(file: string, error: unknown): string {\n return createDiagnosticMessage({\n whatHappened: `Could not run Git to verify that ${file} is untracked and ignored`,\n reassurance: 'Nothing was changed',\n fix: 'Install Git or make it available on PATH, then retry',\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nfunction gitOverrideError(file: string, names: string[]): string {\n return createDiagnosticMessage({\n whatHappened: `Git repository overrides are set in the environment: ${names.join(', ')}`,\n why: `they could point the untracked and ignore checks for ${file} at a different repository or index`,\n reassurance: 'Nothing was changed',\n fix: 'Unset them (for example, run outside a Git hook), then retry',\n });\n}\n\nfunction gitCheckFailedError(file: string, stderr: string): string {\n return createDiagnosticMessage({\n whatHappened: `Git could not check whether ${file} is untracked and ignored`,\n reassurance: 'Nothing was changed',\n fix: 'Fix the reported Git problem, then retry',\n details: stderr.trim(),\n });\n}\n\nexport type Credentials = { apiKey: string; projectId: string };\n\n// Include server-rendered frameworks with client-side development translation.\nconst FRAMEWORK_ENV_PREFIXES: Partial<\n Record<NonNullable<SupportedFrameworks>, string>\n> = {\n 'next-app': 'NEXT_PUBLIC_',\n 'next-pages': 'NEXT_PUBLIC_',\n vite: 'VITE_',\n gatsby: 'GATSBY_',\n react: 'REACT_APP_',\n redwood: 'REDWOOD_ENV_',\n 'tanstack-start': 'VITE_',\n 'react-router': 'VITE_',\n};\n\n/** Names of the runtime variables init writes for this framework. */\nexport function getDevelopmentEnvNames(framework?: SupportedFrameworks) {\n const prefix = (framework && FRAMEWORK_ENV_PREFIXES[framework]) ?? '';\n return {\n projectId: `${prefix}GT_PROJECT_ID`,\n devApiKey: `${prefix}GT_DEV_API_KEY`,\n };\n}\n\n/**\n * Whether the project has the framework's development key, or an explicit\n * API key for a server-only runtime. A tooling key cannot enable client-side\n * hot reload, including in Next.js App Router. `settings.projectId` already\n * resolves every framework prefix. Login is checked separately.\n */\nexport function areCredentialsSet(\n settings: Pick<Settings, 'projectId' | 'apiKey'>,\n framework?: SupportedFrameworks\n): boolean {\n const { devApiKey } = getDevelopmentEnvNames(framework);\n const needsPublicKey = Boolean(\n framework && FRAMEWORK_ENV_PREFIXES[framework]\n );\n return Boolean(\n settings.projectId &&\n (process.env[devApiKey] || (!needsPublicKey && settings.apiKey))\n );\n}\n\nfunction assignedName(line: string): string | undefined {\n return /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=/.exec(line)?.[1];\n}\n\n/**\n * dotenv continues a quoted value onto later lines until its closing quote.\n * Replacing such a line would orphan the continuation, even when a later\n * duplicate hides the multiline value from dotenv's effective values.\n */\nfunction opensMultilineValue(line: string): boolean {\n const value = line.slice(line.indexOf('=') + 1).trim();\n const quote = value[0];\n return (\n ['\"', \"'\", '`'].includes(quote) &&\n !value.slice(1).replaceAll(`\\\\${quote}`, '').includes(quote)\n );\n}\n\nfunction upsertEnvAssignment(\n content: string,\n name: string,\n value: string\n): string {\n const assignsName = (line: string) => assignedName(line) === name;\n const lines = content.split('\\n');\n const first = lines.findIndex(assignsName);\n if (first === -1) {\n const separator = content && !content.endsWith('\\n') ? '\\n' : '';\n return `${content}${separator}${name}=${value}\\n`;\n }\n // Replace the first assignment in place and drop stale duplicates.\n return lines\n .map((line, index) => (index === first ? `${name}=${value}` : line))\n .filter((line, index) => index === first || !assignsName(line))\n .join('\\n');\n}\n\n/**\n * Where .env.local content lives and its mode. Follows an existing symlink so\n * its referent is replaced, never the link itself; anything but a regular\n * file (dangling link, directory) fails before any write.\n */\nasync function resolveEnvFile(\n envFile: string\n): Promise<{ target: string; mode: number } | undefined> {\n const entry = await fs.promises.lstat(envFile).catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (!entry) return undefined;\n // stat follows the link and fails on a dangling one.\n const stat = await fs.promises.stat(envFile).catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (!stat?.isFile()) throw new Error(unwritableEnvFileError(envFile));\n return {\n target: entry.isSymbolicLink()\n ? await fs.promises.realpath(envFile)\n : envFile,\n mode: stat.mode & 0o777,\n };\n}\n\ntype GitExposure = 'no-repository' | 'tracked' | 'ignored' | 'unignored';\n\n// Git honors these over discovering the repository from the working\n// directory, so an inherited value could select another repository, hide this\n// one, or substitute an empty index. Configuration variables stay in effect.\nconst GIT_LOCATION_OVERRIDES = [\n 'GIT_DIR',\n 'GIT_WORK_TREE',\n 'GIT_INDEX_FILE',\n 'GIT_COMMON_DIR',\n 'GIT_CEILING_DIRECTORIES',\n];\n\n/**\n * How Git in the file's own repository treats the path, using Git's real\n * index and effective ignore rules (comments, negations, nested .gitignore,\n * excludes). Only a Git-confirmed non-repository counts as no repository;\n * a missing binary, a repository override, or any other Git error fails\n * closed.\n */\nasync function inspectGitExposure(file: string): Promise<GitExposure> {\n const overrides = GIT_LOCATION_OVERRIDES.filter(\n (name) => process.env[name] !== undefined\n );\n if (overrides.length > 0) throw new Error(gitOverrideError(file, overrides));\n const cwd = path.dirname(file);\n const run = async (args: string[]) => {\n try {\n await execFileAsync('git', args, {\n cwd,\n encoding: 'utf8',\n windowsHide: true,\n // The no-repository check reads Git's untranslated message.\n env: { ...process.env, LC_ALL: 'C' },\n });\n return { code: 0, stderr: '' };\n } catch (error) {\n const { code, stderr } = error as { code?: unknown; stderr?: unknown };\n if (typeof code !== 'number')\n throw new Error(gitUnavailableError(file, error));\n return { code, stderr: typeof stderr === 'string' ? stderr : '' };\n }\n };\n\n const toplevel = await run(['rev-parse', '--show-toplevel']);\n if (toplevel.code === 128 && /not a git repository/i.test(toplevel.stderr)) {\n return 'no-repository';\n }\n if (toplevel.code !== 0) {\n throw new Error(gitCheckFailedError(file, toplevel.stderr));\n }\n // check-ignore ignores tracked files, so the index is consulted first.\n const tracked = await run(['ls-files', '--error-unmatch', '--', file]);\n if (tracked.code === 0) return 'tracked';\n if (tracked.code !== 1)\n throw new Error(gitCheckFailedError(file, tracked.stderr));\n const ignored = await run(['check-ignore', '-q', '--', file]);\n if (ignored.code === 0) return 'ignored';\n if (ignored.code === 1) return 'unignored';\n throw new Error(gitCheckFailedError(file, ignored.stderr));\n}\n\ntype CredentialsEnvFile = {\n envFile: string;\n existing: Awaited<ReturnType<typeof resolveEnvFile>>;\n exposure: GitExposure;\n};\n\n/**\n * Everything that must hold before credentials may be saved to .env.local,\n * so callers can fail before minting a key: the path is a regular file (or a\n * link to one) or absent, and neither it nor a link's referent is tracked by\n * Git. A referent inside any worktree must already be ignored there; only\n * .env.local itself gets an ignore rule added, by setCredentials.\n */\nexport async function inspectCredentialsEnvFile(\n cwd: string = process.cwd(),\n /** Also checks that the framework's credentials can be saved safely. */\n contentCheck?: { framework?: SupportedFrameworks }\n): Promise<CredentialsEnvFile> {\n const envFile = path.resolve(cwd, '.env.local');\n const existing = await resolveEnvFile(envFile);\n if (existing && contentCheck) {\n updateCredentialsEnvContent(\n await fs.promises.readFile(existing.target, 'utf8'),\n { projectId: 'gt-preflight', apiKey: 'gt-preflight' },\n contentCheck.framework\n );\n }\n const exposure = await inspectGitExposure(envFile);\n if (exposure === 'tracked') throw new Error(trackedEnvFileError(envFile));\n if (existing && existing.target !== envFile) {\n const referentExposure = await inspectGitExposure(existing.target);\n if (referentExposure === 'tracked') {\n throw new Error(trackedEnvFileError(existing.target));\n }\n if (referentExposure === 'unignored') {\n throw new Error(unignoredEnvFileReferentError(envFile, existing.target));\n }\n }\n return { envFile, existing, exposure };\n}\n\nasync function appendGitignoreRule(cwd: string): Promise<void> {\n const gitignoreFile = path.join(cwd, '.gitignore');\n const content = await fs.promises\n .readFile(gitignoreFile, 'utf8')\n .catch((error) => {\n if (error.code === 'ENOENT') return '';\n throw error;\n });\n const separator = content && !content.endsWith('\\n') ? '\\n' : '';\n await fs.promises.appendFile(\n gitignoreFile,\n `${separator}.env.local\\n`,\n 'utf8'\n );\n}\n\n// Same-directory temporary file and rename, as in auth/credentialStore.ts:\n// a failed write never truncates the existing file.\nasync function writeEnvFileAtomically(\n target: string,\n content: string,\n mode: number\n): Promise<void> {\n const temporaryPath = path.join(\n path.dirname(target),\n `.env.local.${randomUUID()}.tmp`\n );\n try {\n await fs.promises.writeFile(temporaryPath, content, {\n encoding: 'utf8',\n flag: 'wx',\n mode,\n });\n await fs.promises.chmod(temporaryPath, mode);\n await fs.promises.rename(temporaryPath, target);\n } catch (error) {\n await fs.promises.rm(temporaryPath, { force: true });\n throw error;\n }\n}\n\n/**\n * .env.local content with the runtime credentials set. Only the hot-reload\n * key: the CLI itself acts as the signed-in user, and CI keys are created\n * deliberately rather than dropped into .env.local. Other lines, comments,\n * and any GT_API_KEY are left untouched. Throws when the edit could corrupt\n * a multiline value.\n */\nfunction updateCredentialsEnvContent(\n envContent: string,\n credentials: Credentials,\n framework?: SupportedFrameworks\n): string {\n const names = getDevelopmentEnvNames(framework);\n const targetNames = Object.values(names);\n const targetOpensMultiline = envContent\n .split('\\n')\n .some(\n (line) =>\n targetNames.includes(assignedName(line) ?? '') &&\n opensMultilineValue(line)\n );\n const original = dotenv.parse(envContent);\n const expected = {\n ...original,\n [names.projectId]: credentials.projectId,\n [names.devApiKey]: credentials.apiKey,\n };\n let updatedContent = upsertEnvAssignment(\n envContent,\n names.projectId,\n credentials.projectId\n );\n updatedContent = upsertEnvAssignment(\n updatedContent,\n names.devApiKey,\n credentials.apiKey\n );\n\n const updated = dotenv.parse(updatedContent);\n if (\n targetOpensMultiline ||\n targetNames.some((name) => original[name]?.includes('\\n')) ||\n Object.keys(updated).length !== Object.keys(expected).length ||\n Object.entries(expected).some(([name, value]) => updated[name] !== value)\n ) {\n throw new Error(unsafeCredentialsEnvError);\n }\n return updatedContent;\n}\n\n// Sets the credentials in .env.local file\nexport async function setCredentials(\n credentials: Credentials,\n framework?: SupportedFrameworks,\n cwd: string = process.cwd()\n) {\n const {\n envFile,\n existing: existingEnvFile,\n exposure,\n } = await inspectCredentialsEnvFile(cwd);\n // Rechecked here: the file may have changed since the setup preflight.\n const envContent = updateCredentialsEnvContent(\n existingEnvFile\n ? await fs.promises.readFile(existingEnvFile.target, 'utf8')\n : '',\n credentials,\n framework\n );\n\n if (exposure === 'unignored') {\n // A rule appended to the same-directory .gitignore is the last match at\n // the deepest level, so it wins over earlier negations; verify anyway.\n await appendGitignoreRule(cwd);\n if ((await inspectGitExposure(envFile)) !== 'ignored') {\n throw new Error(unignoredEnvFileError(envFile));\n }\n } else if (exposure === 'no-repository') {\n // Without a repository there are no effective rules to consult, so this\n // is unverified: seed a .gitignore so a later `git init` ignores the file.\n const gitignoreFile = path.join(cwd, '.gitignore');\n if (\n !fs.existsSync(gitignoreFile) ||\n (await fs.promises.readFile(gitignoreFile, 'utf8'))\n .trimEnd()\n .split(/\\r?\\n/)\n .at(-1) !== '.env.local'\n ) {\n await appendGitignoreRule(cwd);\n }\n }\n\n await writeEnvFileAtomically(\n existingEnvFile?.target ?? envFile,\n envContent,\n existingEnvFile?.mode ?? 0o600\n );\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,gBAAgB,UAAU,SAAS;AAEzC,MAAM,4BAA4B,wBAAwB;CACxD,cAAc;CACd,aAAa;CACb,KAAK;CACN,CAAC;AAEF,SAAS,uBAAuB,SAAyB;AACvD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,QAAQ;EACzB,aAAa;EACb,KAAK;EACN,CAAC;;AAGJ,SAAS,oBAAoB,MAAsB;AACjD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,KAAK;EACtB,KAAK;EACL,aAAa;EACb,KAAK,yBAAyB,KAAK,SAAS,KAAK,CAAC,QAAQ,KAAK,QAAQ,KAAK,CAAC;EAC9E,CAAC;;AAGJ,SAAS,sBAAsB,MAAsB;AACnD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,KAAK;EACtB,KAAK;EACL,aAAa;EACb,KAAK,gDAAgD,KAAK,QAAQ,KAAK,CAAC;EACzE,CAAC;;AAGJ,SAAS,8BAA8B,SAAiB,UAAkB;AACxE,QAAO,wBAAwB;EAC7B,cAAc,GAAG,QAAQ,YAAY,SAAS;EAC9C,KAAK;EACL,aAAa;EACb,KAAK,OAAO,SAAS;EACtB,CAAC;;A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|
|
1
|
+
{"version":3,"file":"credentials.js","names":[],"sources":["../../src/utils/credentials.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport { promisify } from 'node:util';\nimport dotenv from 'dotenv';\nimport { Settings, SupportedFrameworks } from '../types/index.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\n\nconst execFileAsync = promisify(execFile);\n\nconst unsafeCredentialsEnvError = createDiagnosticMessage({\n whatHappened: 'Cannot safely update .env.local',\n reassurance: 'The existing .env.local file was not changed',\n fix: 'Move multiline values away from project/key assignments or set the development credentials manually, then retry',\n});\n\nfunction unwritableEnvFileError(envFile: string): string {\n return createDiagnosticMessage({\n whatHappened: `${envFile} is not a regular file`,\n reassurance: 'Nothing was changed',\n fix: 'Replace it with a regular file or a symlink to one, or set the development credentials manually, then retry',\n });\n}\n\nfunction trackedEnvFileError(file: string): string {\n return createDiagnosticMessage({\n whatHappened: `${file} is tracked by Git`,\n why: 'development credentials saved there would be committed',\n reassurance: 'Nothing was changed',\n fix: `Run \\`git rm --cached ${path.basename(file)}\\` in ${path.dirname(file)} and add the file to .gitignore, then retry`,\n });\n}\n\nfunction unignoredEnvFileError(file: string): string {\n return createDiagnosticMessage({\n whatHappened: `${file} is not ignored by Git`,\n why: 'development credentials saved there could be committed',\n reassurance: 'Nothing was changed',\n fix: `Add the file to a .gitignore that applies to ${path.dirname(file)}, then retry`,\n });\n}\n\nfunction unignoredEnvFileReferentError(envFile: string, referent: string) {\n return createDiagnosticMessage({\n whatHappened: `${envFile} links to ${referent}, which Git does not ignore`,\n why: 'development credentials saved there could be committed',\n reassurance: 'Nothing was changed',\n fix: `Add ${referent} to a .gitignore in its repository or set the development credentials manually, then retry`,\n });\n}\n\nfunction gitUnavailableError(file: string, error: unknown): string {\n return createDiagnosticMessage({\n whatHappened: `Could not run Git to verify that ${file} is untracked and ignored`,\n reassurance: 'Nothing was changed',\n fix: 'Install Git or make it available on PATH, then retry',\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nfunction gitOverrideError(file: string, names: string[]): string {\n return createDiagnosticMessage({\n whatHappened: `Git repository overrides are set in the environment: ${names.join(', ')}`,\n why: `they could point the untracked and ignore checks for ${file} at a different repository or index`,\n reassurance: 'Nothing was changed',\n fix: 'Unset them (for example, run outside a Git hook), then retry',\n });\n}\n\nfunction gitCheckFailedError(file: string, stderr: string): string {\n return createDiagnosticMessage({\n whatHappened: `Git could not check whether ${file} is untracked and ignored`,\n reassurance: 'Nothing was changed',\n fix: 'Fix the reported Git problem, then retry',\n details: stderr.trim(),\n });\n}\n\nexport type Credentials = { apiKey: string; projectId: string };\n\n// Include server-rendered frameworks with client-side development translation.\n// Next.js reads GT_PROJECT_ID and GT_API_KEY instead; gt-next exposes them\n// to client code in development only.\nconst FRAMEWORK_ENV_PREFIXES: Partial<\n Record<NonNullable<SupportedFrameworks>, string>\n> = {\n vite: 'VITE_',\n gatsby: 'GATSBY_',\n react: 'REACT_APP_',\n redwood: 'REDWOOD_ENV_',\n 'tanstack-start': 'VITE_',\n 'react-router': 'VITE_',\n};\n\n/** Names of the runtime variables init writes for this framework. */\nexport function getDevelopmentEnvNames(framework?: SupportedFrameworks) {\n if (isNextFramework(framework)) {\n return { projectId: 'GT_PROJECT_ID', devApiKey: 'GT_API_KEY' };\n }\n const prefix = (framework && FRAMEWORK_ENV_PREFIXES[framework]) ?? '';\n return {\n projectId: `${prefix}GT_PROJECT_ID`,\n devApiKey: `${prefix}GT_DEV_API_KEY`,\n };\n}\n\n/**\n * Whether the project has the framework's development key, or an explicit\n * API key for a server-only runtime. A tooling key cannot enable client-side\n * hot reload. Next.js uses GT_API_KEY for both, and still accepts the\n * NEXT_PUBLIC_ key earlier versions of init wrote. `settings.projectId`\n * already resolves every framework prefix. Login is checked separately.\n */\nexport function areCredentialsSet(\n settings: Pick<Settings, 'projectId' | 'apiKey'>,\n framework?: SupportedFrameworks\n): boolean {\n const { devApiKey } = getDevelopmentEnvNames(framework);\n const devApiKeys = isNextFramework(framework)\n ? [devApiKey, 'NEXT_PUBLIC_GT_DEV_API_KEY']\n : [devApiKey];\n const needsDevKey = Boolean(framework && FRAMEWORK_ENV_PREFIXES[framework]);\n return Boolean(\n settings.projectId &&\n (devApiKeys.some((name) => process.env[name]) ||\n (!needsDevKey && settings.apiKey))\n );\n}\n\nfunction isNextFramework(framework?: SupportedFrameworks): boolean {\n return framework === 'next-app' || framework === 'next-pages';\n}\n\nfunction assignedName(line: string): string | undefined {\n return /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=/.exec(line)?.[1];\n}\n\n/**\n * dotenv continues a quoted value onto later lines until its closing quote.\n * Replacing such a line would orphan the continuation, even when a later\n * duplicate hides the multiline value from dotenv's effective values.\n */\nfunction opensMultilineValue(line: string): boolean {\n const value = line.slice(line.indexOf('=') + 1).trim();\n const quote = value[0];\n return (\n ['\"', \"'\", '`'].includes(quote) &&\n !value.slice(1).replaceAll(`\\\\${quote}`, '').includes(quote)\n );\n}\n\nfunction upsertEnvAssignment(\n content: string,\n name: string,\n value: string\n): string {\n const assignsName = (line: string) => assignedName(line) === name;\n const lines = content.split('\\n');\n const first = lines.findIndex(assignsName);\n if (first === -1) {\n const separator = content && !content.endsWith('\\n') ? '\\n' : '';\n return `${content}${separator}${name}=${value}\\n`;\n }\n // Replace the first assignment in place and drop stale duplicates.\n return lines\n .map((line, index) => (index === first ? `${name}=${value}` : line))\n .filter((line, index) => index === first || !assignsName(line))\n .join('\\n');\n}\n\n/**\n * Where .env.local content lives and its mode. Follows an existing symlink so\n * its referent is replaced, never the link itself; anything but a regular\n * file (dangling link, directory) fails before any write.\n */\nasync function resolveEnvFile(\n envFile: string\n): Promise<{ target: string; mode: number } | undefined> {\n const entry = await fs.promises.lstat(envFile).catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (!entry) return undefined;\n // stat follows the link and fails on a dangling one.\n const stat = await fs.promises.stat(envFile).catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (!stat?.isFile()) throw new Error(unwritableEnvFileError(envFile));\n return {\n target: entry.isSymbolicLink()\n ? await fs.promises.realpath(envFile)\n : envFile,\n mode: stat.mode & 0o777,\n };\n}\n\ntype GitExposure = 'no-repository' | 'tracked' | 'ignored' | 'unignored';\n\n// Git honors these over discovering the repository from the working\n// directory, so an inherited value could select another repository, hide this\n// one, or substitute an empty index. Configuration variables stay in effect.\nconst GIT_LOCATION_OVERRIDES = [\n 'GIT_DIR',\n 'GIT_WORK_TREE',\n 'GIT_INDEX_FILE',\n 'GIT_COMMON_DIR',\n 'GIT_CEILING_DIRECTORIES',\n];\n\n/**\n * How Git in the file's own repository treats the path, using Git's real\n * index and effective ignore rules (comments, negations, nested .gitignore,\n * excludes). Only a Git-confirmed non-repository counts as no repository;\n * a missing binary, a repository override, or any other Git error fails\n * closed.\n */\nasync function inspectGitExposure(file: string): Promise<GitExposure> {\n const overrides = GIT_LOCATION_OVERRIDES.filter(\n (name) => process.env[name] !== undefined\n );\n if (overrides.length > 0) throw new Error(gitOverrideError(file, overrides));\n const cwd = path.dirname(file);\n const run = async (args: string[]) => {\n try {\n await execFileAsync('git', args, {\n cwd,\n encoding: 'utf8',\n windowsHide: true,\n // The no-repository check reads Git's untranslated message.\n env: { ...process.env, LC_ALL: 'C' },\n });\n return { code: 0, stderr: '' };\n } catch (error) {\n const { code, stderr } = error as { code?: unknown; stderr?: unknown };\n if (typeof code !== 'number')\n throw new Error(gitUnavailableError(file, error));\n return { code, stderr: typeof stderr === 'string' ? stderr : '' };\n }\n };\n\n const toplevel = await run(['rev-parse', '--show-toplevel']);\n if (toplevel.code === 128 && /not a git repository/i.test(toplevel.stderr)) {\n return 'no-repository';\n }\n if (toplevel.code !== 0) {\n throw new Error(gitCheckFailedError(file, toplevel.stderr));\n }\n // check-ignore ignores tracked files, so the index is consulted first.\n const tracked = await run(['ls-files', '--error-unmatch', '--', file]);\n if (tracked.code === 0) return 'tracked';\n if (tracked.code !== 1)\n throw new Error(gitCheckFailedError(file, tracked.stderr));\n const ignored = await run(['check-ignore', '-q', '--', file]);\n if (ignored.code === 0) return 'ignored';\n if (ignored.code === 1) return 'unignored';\n throw new Error(gitCheckFailedError(file, ignored.stderr));\n}\n\ntype CredentialsEnvFile = {\n envFile: string;\n existing: Awaited<ReturnType<typeof resolveEnvFile>>;\n exposure: GitExposure;\n};\n\n/**\n * Everything that must hold before credentials may be saved to .env.local,\n * so callers can fail before minting a key: the path is a regular file (or a\n * link to one) or absent, and neither it nor a link's referent is tracked by\n * Git. A referent inside any worktree must already be ignored there; only\n * .env.local itself gets an ignore rule added, by setCredentials.\n */\nexport async function inspectCredentialsEnvFile(\n cwd: string = process.cwd(),\n /** Also checks that the framework's credentials can be saved safely. */\n contentCheck?: { framework?: SupportedFrameworks }\n): Promise<CredentialsEnvFile> {\n const envFile = path.resolve(cwd, '.env.local');\n const existing = await resolveEnvFile(envFile);\n if (existing && contentCheck) {\n updateCredentialsEnvContent(\n await fs.promises.readFile(existing.target, 'utf8'),\n { projectId: 'gt-preflight', apiKey: 'gt-preflight' },\n contentCheck.framework\n );\n }\n const exposure = await inspectGitExposure(envFile);\n if (exposure === 'tracked') throw new Error(trackedEnvFileError(envFile));\n if (existing && existing.target !== envFile) {\n const referentExposure = await inspectGitExposure(existing.target);\n if (referentExposure === 'tracked') {\n throw new Error(trackedEnvFileError(existing.target));\n }\n if (referentExposure === 'unignored') {\n throw new Error(unignoredEnvFileReferentError(envFile, existing.target));\n }\n }\n return { envFile, existing, exposure };\n}\n\nasync function appendGitignoreRule(cwd: string): Promise<void> {\n const gitignoreFile = path.join(cwd, '.gitignore');\n const content = await fs.promises\n .readFile(gitignoreFile, 'utf8')\n .catch((error) => {\n if (error.code === 'ENOENT') return '';\n throw error;\n });\n const separator = content && !content.endsWith('\\n') ? '\\n' : '';\n await fs.promises.appendFile(\n gitignoreFile,\n `${separator}.env.local\\n`,\n 'utf8'\n );\n}\n\n// Same-directory temporary file and rename, as in auth/credentialStore.ts:\n// a failed write never truncates the existing file.\nasync function writeEnvFileAtomically(\n target: string,\n content: string,\n mode: number\n): Promise<void> {\n const temporaryPath = path.join(\n path.dirname(target),\n `.env.local.${randomUUID()}.tmp`\n );\n try {\n await fs.promises.writeFile(temporaryPath, content, {\n encoding: 'utf8',\n flag: 'wx',\n mode,\n });\n await fs.promises.chmod(temporaryPath, mode);\n await fs.promises.rename(temporaryPath, target);\n } catch (error) {\n await fs.promises.rm(temporaryPath, { force: true });\n throw error;\n }\n}\n\n/**\n * .env.local content with the runtime credentials set. Only the hot-reload\n * key: the CLI itself acts as the signed-in user, and CI keys are created\n * deliberately rather than dropped into .env.local. Other lines and comments\n * are left untouched, as is GT_API_KEY except in Next.js, which\n * uses it as the development key. Throws when the edit could corrupt a\n * multiline value.\n */\nfunction updateCredentialsEnvContent(\n envContent: string,\n credentials: Credentials,\n framework?: SupportedFrameworks\n): string {\n const names = getDevelopmentEnvNames(framework);\n const targetNames = Object.values(names);\n const targetOpensMultiline = envContent\n .split('\\n')\n .some(\n (line) =>\n targetNames.includes(assignedName(line) ?? '') &&\n opensMultilineValue(line)\n );\n const original = dotenv.parse(envContent);\n const expected = {\n ...original,\n [names.projectId]: credentials.projectId,\n [names.devApiKey]: credentials.apiKey,\n };\n let updatedContent = upsertEnvAssignment(\n envContent,\n names.projectId,\n credentials.projectId\n );\n updatedContent = upsertEnvAssignment(\n updatedContent,\n names.devApiKey,\n credentials.apiKey\n );\n\n const updated = dotenv.parse(updatedContent);\n if (\n targetOpensMultiline ||\n targetNames.some((name) => original[name]?.includes('\\n')) ||\n Object.keys(updated).length !== Object.keys(expected).length ||\n Object.entries(expected).some(([name, value]) => updated[name] !== value)\n ) {\n throw new Error(unsafeCredentialsEnvError);\n }\n return updatedContent;\n}\n\n// Sets the credentials in .env.local file\nexport async function setCredentials(\n credentials: Credentials,\n framework?: SupportedFrameworks,\n cwd: string = process.cwd()\n) {\n const {\n envFile,\n existing: existingEnvFile,\n exposure,\n } = await inspectCredentialsEnvFile(cwd);\n // Rechecked here: the file may have changed since the setup preflight.\n const envContent = updateCredentialsEnvContent(\n existingEnvFile\n ? await fs.promises.readFile(existingEnvFile.target, 'utf8')\n : '',\n credentials,\n framework\n );\n\n if (exposure === 'unignored') {\n // A rule appended to the same-directory .gitignore is the last match at\n // the deepest level, so it wins over earlier negations; verify anyway.\n await appendGitignoreRule(cwd);\n if ((await inspectGitExposure(envFile)) !== 'ignored') {\n throw new Error(unignoredEnvFileError(envFile));\n }\n } else if (exposure === 'no-repository') {\n // Without a repository there are no effective rules to consult, so this\n // is unverified: seed a .gitignore so a later `git init` ignores the file.\n const gitignoreFile = path.join(cwd, '.gitignore');\n if (\n !fs.existsSync(gitignoreFile) ||\n (await fs.promises.readFile(gitignoreFile, 'utf8'))\n .trimEnd()\n .split(/\\r?\\n/)\n .at(-1) !== '.env.local'\n ) {\n await appendGitignoreRule(cwd);\n }\n }\n\n await writeEnvFileAtomically(\n existingEnvFile?.target ?? envFile,\n envContent,\n existingEnvFile?.mode ?? 0o600\n );\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,gBAAgB,UAAU,SAAS;AAEzC,MAAM,4BAA4B,wBAAwB;CACxD,cAAc;CACd,aAAa;CACb,KAAK;CACN,CAAC;AAEF,SAAS,uBAAuB,SAAyB;AACvD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,QAAQ;EACzB,aAAa;EACb,KAAK;EACN,CAAC;;AAGJ,SAAS,oBAAoB,MAAsB;AACjD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,KAAK;EACtB,KAAK;EACL,aAAa;EACb,KAAK,yBAAyB,KAAK,SAAS,KAAK,CAAC,QAAQ,KAAK,QAAQ,KAAK,CAAC;EAC9E,CAAC;;AAGJ,SAAS,sBAAsB,MAAsB;AACnD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,KAAK;EACtB,KAAK;EACL,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ED,KAAI,aAAa,aAAa;AAG5B,QAAM,oBAAoB,IAAI;AAC9B,MAAK,MAAM,mBAAmB,QAAQ,KAAM,UAC1C,OAAM,IAAI,MAAM,sBAAsB,QAAQ,CAAC;YAExC,aAAa,iBAAiB;EAGvC,MAAM,gBAAgB,KAAK,KAAK,KAAK,aAAa;AAClD,MACE,CAAC,GAAG,WAAW,cAAc,KAC5B,MAAM,GAAG,SAAS,SAAS,eAAe,OAAO,EAC/C,SAAS,CACT,MAAM,QAAQ,CACd,GAAG,GAAG,KAAK,aAEd,OAAM,oBAAoB,IAAI;;AAIlC,OAAM,uBACJ,iBAAiB,UAAU,SAC3B,YACA,iBAAiB,QAAQ,IAC1B"}
|
package/dist/utils/loadEnv.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
/** Env files read at startup, in order; each one after the first overrides the shell. */
|
|
2
2
|
export declare const envFiles: readonly [".env", ".env.local", ".env.production"];
|
|
3
|
+
/** The GT_API_KEY value an env file supplied, when the shell set none. */
|
|
4
|
+
export declare function getEnvFileApiKey(): string | undefined;
|
|
3
5
|
/** Load executable startup env files without contaminating command stdout. */
|
|
4
6
|
export declare function loadEnv(): void;
|
package/dist/utils/loadEnv.js
CHANGED
|
@@ -6,8 +6,14 @@ const envFiles = [
|
|
|
6
6
|
".env.local",
|
|
7
7
|
".env.production"
|
|
8
8
|
];
|
|
9
|
+
let envFileApiKey;
|
|
10
|
+
/** The GT_API_KEY value an env file supplied, when the shell set none. */
|
|
11
|
+
function getEnvFileApiKey() {
|
|
12
|
+
return envFileApiKey;
|
|
13
|
+
}
|
|
9
14
|
/** Load executable startup env files without contaminating command stdout. */
|
|
10
15
|
function loadEnv() {
|
|
16
|
+
const shellApiKey = process.env.GT_API_KEY;
|
|
11
17
|
const log = console.log;
|
|
12
18
|
console.log = console.error;
|
|
13
19
|
try {
|
|
@@ -18,8 +24,10 @@ function loadEnv() {
|
|
|
18
24
|
} finally {
|
|
19
25
|
console.log = log;
|
|
20
26
|
}
|
|
27
|
+
if (shellApiKey !== void 0) process.env.GT_API_KEY = shellApiKey;
|
|
28
|
+
envFileApiKey = shellApiKey === void 0 ? process.env.GT_API_KEY : void 0;
|
|
21
29
|
}
|
|
22
30
|
//#endregion
|
|
23
|
-
export { envFiles, loadEnv };
|
|
31
|
+
export { envFiles, getEnvFileApiKey, loadEnv };
|
|
24
32
|
|
|
25
33
|
//# sourceMappingURL=loadEnv.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadEnv.js","names":[],"sources":["../../src/utils/loadEnv.ts"],"sourcesContent":["import dotenv from 'dotenv';\n\n/** Env files read at startup, in order; each one after the first overrides the shell. */\nexport const envFiles = ['.env', '.env.local', '.env.production'] as const;\n\n/** Load executable startup env files without contaminating command stdout. */\nexport function loadEnv(): void {\n /* eslint-disable no-console -- dotenv 16's vault warnings bypass quiet via console.log. */\n const log = console.log;\n // Keep this override synchronous; remove it when dotenv supports stderr diagnostics.\n console.log = console.error;\n try {\n for (const [index, path] of envFiles.entries()) {\n dotenv.config({ path, override: index > 0 });\n }\n } finally {\n console.log = log;\n }\n /* eslint-enable no-console */\n}\n"],"mappings":";;;AAGA,MAAa,WAAW;CAAC;CAAQ;CAAc;CAAkB;;
|
|
1
|
+
{"version":3,"file":"loadEnv.js","names":[],"sources":["../../src/utils/loadEnv.ts"],"sourcesContent":["import dotenv from 'dotenv';\n\n/** Env files read at startup, in order; each one after the first overrides the shell. */\nexport const envFiles = ['.env', '.env.local', '.env.production'] as const;\n\nlet envFileApiKey: string | undefined;\n\n/** The GT_API_KEY value an env file supplied, when the shell set none. */\nexport function getEnvFileApiKey(): string | undefined {\n return envFileApiKey;\n}\n\n/** Load executable startup env files without contaminating command stdout. */\nexport function loadEnv(): void {\n const shellApiKey = process.env.GT_API_KEY;\n /* eslint-disable no-console -- dotenv 16's vault warnings bypass quiet via console.log. */\n const log = console.log;\n // Keep this override synchronous; remove it when dotenv supports stderr diagnostics.\n console.log = console.error;\n try {\n for (const [index, path] of envFiles.entries()) {\n dotenv.config({ path, override: index > 0 });\n }\n } finally {\n console.log = log;\n }\n /* eslint-enable no-console */\n // An env file's GT_API_KEY is the app's runtime key, so an explicit shell or\n // CI key keeps priority for the CLI.\n if (shellApiKey !== undefined) process.env.GT_API_KEY = shellApiKey;\n envFileApiKey =\n shellApiKey === undefined ? process.env.GT_API_KEY : undefined;\n}\n"],"mappings":";;;AAGA,MAAa,WAAW;CAAC;CAAQ;CAAc;CAAkB;AAEjE,IAAI;;AAGJ,SAAgB,mBAAuC;AACrD,QAAO;;;AAIT,SAAgB,UAAgB;CAC9B,MAAM,cAAc,QAAQ,IAAI;CAEhC,MAAM,MAAM,QAAQ;AAEpB,SAAQ,MAAM,QAAQ;AACtB,KAAI;AACF,OAAK,MAAM,CAAC,OAAO,SAAS,SAAS,SAAS,CAC5C,QAAO,OAAO;GAAE;GAAM,UAAU,QAAQ;GAAG,CAAC;WAEtC;AACR,UAAQ,MAAM;;AAKhB,KAAI,gBAAgB,KAAA,EAAW,SAAQ,IAAI,aAAa;AACxD,iBACE,gBAAgB,KAAA,IAAY,QAAQ,IAAI,aAAa,KAAA"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Settings } from '../types/index.js';
|
|
2
2
|
import { EnqueueFilesResult } from 'generaltranslation/types';
|
|
3
3
|
import { BranchData } from '../types/branch.js';
|
|
4
|
-
import type
|
|
4
|
+
import { type InlineLibrary } from '../types/libraries.js';
|
|
5
5
|
export type FileTranslationData = {
|
|
6
6
|
[fileId: string]: {
|
|
7
7
|
versionId: string;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { logger } from "../console/logger.js";
|
|
2
|
+
import "../utils/constants.js";
|
|
3
|
+
import { getInlineElementsLabel } from "../types/libraries.js";
|
|
2
4
|
import { logErrorAndExit } from "../console/logging.js";
|
|
3
5
|
import { branchResolutionError } from "../console/index.js";
|
|
4
6
|
import { api } from "../utils/api.js";
|
|
@@ -8,6 +10,7 @@ import { clearLocaleDirs } from "../fs/clearLocaleDirs.js";
|
|
|
8
10
|
import { PollTranslationJobsStep } from "./steps/PollJobsStep.js";
|
|
9
11
|
import { DownloadTranslationsStep } from "./steps/DownloadStep.js";
|
|
10
12
|
import chalk from "chalk";
|
|
13
|
+
import { createDiagnosticMessage } from "generaltranslation/internal";
|
|
11
14
|
import path from "node:path";
|
|
12
15
|
//#region src/workflows/download.ts
|
|
13
16
|
/**
|
|
@@ -49,8 +52,23 @@ async function runDownloadWorkflow({ fileVersionData, jobData, branchData, local
|
|
|
49
52
|
forceRetranslation
|
|
50
53
|
});
|
|
51
54
|
if (pollResult.fileTracker.failed.size > 0) {
|
|
52
|
-
|
|
53
|
-
for (const [, value] of pollResult.fileTracker.failed)
|
|
55
|
+
const failures = [];
|
|
56
|
+
for (const [, value] of pollResult.fileTracker.failed) {
|
|
57
|
+
const fileName = value.fileName === "__INTERNAL_GT_TEMPLATE_NAME__" ? `<${getInlineElementsLabel(inlineLibrary)}>` : value.fileName;
|
|
58
|
+
const reason = createDiagnosticMessage({
|
|
59
|
+
whatHappened: `Failed to translate for locale ${value.locale}`,
|
|
60
|
+
details: value.failureReason
|
|
61
|
+
});
|
|
62
|
+
failures.push(`- ${fileName}: ${reason}`);
|
|
63
|
+
recordWarning("failed_translation", fileName, reason);
|
|
64
|
+
}
|
|
65
|
+
const failureMessage = createDiagnosticMessage({
|
|
66
|
+
source: "gt",
|
|
67
|
+
severity: "Error",
|
|
68
|
+
whatHappened: `${pollResult.fileTracker.failed.size} file(s) failed to translate`,
|
|
69
|
+
details: `\n${failures.join("\n")}`
|
|
70
|
+
});
|
|
71
|
+
logger.error(failureMessage);
|
|
54
72
|
if (pollResult.fileTracker.completed.size === 0) return false;
|
|
55
73
|
}
|
|
56
74
|
if (!pollResult.success) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"download.js","names":[],"sources":["../../src/workflows/download.ts"],"sourcesContent":["import path from 'node:path';\nimport { Settings } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { EnqueueFilesResult } from 'generaltranslation/types';\nimport { clearLocaleDirs } from '../fs/clearLocaleDirs.js';\nimport {\n FileStatusTracker,\n PollTranslationJobsStep,\n} from './steps/PollJobsStep.js';\nimport { DownloadTranslationsStep } from './steps/DownloadStep.js';\nimport { BranchData } from '../types/branch.js';\nimport { branchResolutionError } from '../console/index.js';\nimport { logErrorAndExit } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { recordWarning } from '../state/translateWarnings.js';\nimport { BranchStep } from './steps/BranchStep.js';\nimport { FileProperties } from '../types/files.js';\nimport chalk from 'chalk';\nimport type { InlineLibrary } from '../types/libraries.js';\n\nexport type FileTranslationData = {\n [fileId: string]: {\n versionId: string;\n fileName: string;\n /** Source component count for GTJSON files */\n componentCount?: number;\n };\n};\n\n/**\n * Checks the status of translations and downloads them using a workflow pattern\n * @param fileVersionData - Mapping of file IDs to their version and name information\n * @param jobData - Optional job data from enqueue operation\n * @param locales - The locales to wait for\n * @param timeoutDuration - The timeout duration for the wait in seconds\n * @param resolveOutputPath - Function to resolve the output path for a given source path and locale\n * @param options - Settings configuration\n * @param forceRetranslation - Whether to force retranslation\n * @param forceDownload - Whether to force download even if file exists\n * @returns True if all translations are downloaded successfully, false otherwise\n */\nexport async function runDownloadWorkflow({\n fileVersionData,\n jobData,\n branchData,\n locales,\n timeoutDuration,\n resolveOutputPath,\n options,\n inlineLibrary,\n forceRetranslation,\n forceDownload,\n}: {\n fileVersionData: FileTranslationData;\n jobData: EnqueueFilesResult | undefined;\n branchData: BranchData | undefined;\n locales: string[];\n timeoutDuration: number;\n resolveOutputPath: (sourcePath: string, locale: string) => string | null;\n options: Settings;\n inlineLibrary?: InlineLibrary;\n forceRetranslation?: boolean;\n forceDownload?: boolean;\n}): Promise<boolean> {\n if (!branchData) {\n // Run the branch step\n const branchStep = new BranchStep(api, options);\n const branchResult = await branchStep.run();\n if (!branchResult) {\n return logErrorAndExit(branchResolutionError);\n }\n branchData = branchResult;\n }\n // readLockfile uses _branchId to select branch-specific lockfile entries.\n // Keep it on a scoped copy so the caller's settings object is not mutated.\n const settingsForBranch: Settings = {\n ...options,\n _branchId: branchData.currentBranch.id,\n };\n // Prepare the query data\n const fileQueryData = prepareFileQueryData(\n fileVersionData,\n locales,\n branchData\n );\n\n // Initialize download status\n const fileTracker: FileStatusTracker = {\n completed: new Map<string, FileProperties>(),\n inProgress: new Map<string, FileProperties>(),\n failed: new Map<string, FileProperties>(),\n skipped: new Map<string, FileProperties>(),\n };\n\n // Step 1: Poll translation jobs if jobData exists\n let pollTimedOut = false;\n if (jobData) {\n const pollStep = new PollTranslationJobsStep(api, inlineLibrary);\n const pollResult = await pollStep.run({\n fileTracker,\n fileQueryData,\n jobData,\n timeoutDuration,\n forceRetranslation,\n });\n\n if (pollResult.fileTracker.failed.size > 0) {\n logger.error(\n `${chalk.red(`${pollResult.fileTracker.failed.size} file(s) failed to translate:`)}\\n${Array.from(\n pollResult.fileTracker.failed.entries()\n )\n .map(([, value]) => `- ${value.fileName}`)\n .join('\\n')}`\n );\n for (const [, value] of pollResult.fileTracker.failed) {\n recordWarning(\n 'failed_translation',\n value.fileName,\n `Failed to translate for locale ${value.locale}`\n );\n }\n\n // If all files failed translation, exit early\n if (pollResult.fileTracker.completed.size === 0) {\n return false;\n }\n }\n\n // Even if polling timed out, still download whatever completed successfully\n if (!pollResult.success) {\n pollTimedOut = true;\n if (pollResult.fileTracker.completed.size > 0) {\n logger.warn(\n chalk.yellow(\n `Timed out, but ${pollResult.fileTracker.completed.size} translation(s) completed successfully. Downloading completed files...`\n )\n );\n } else {\n return false;\n }\n }\n } else {\n for (const file of fileQueryData) {\n // Staging - assume all files are completed\n fileTracker.completed.set(\n `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`,\n file\n );\n }\n }\n\n await clearCompletedLocaleDirs({\n fileTracker,\n locales,\n resolveOutputPath,\n options,\n });\n\n // Step 2: Download translations\n const downloadStep = new DownloadTranslationsStep(\n api,\n settingsForBranch,\n inlineLibrary\n );\n const downloadResult = await downloadStep.run({\n fileTracker,\n resolveOutputPath,\n forceDownload,\n });\n\n // If polling timed out, report failure even though we downloaded what we could\n if (pollTimedOut) {\n return false;\n }\n\n return downloadResult;\n}\n\nasync function clearCompletedLocaleDirs({\n fileTracker,\n locales,\n resolveOutputPath,\n options,\n}: {\n fileTracker: FileStatusTracker;\n locales: string[];\n resolveOutputPath: (sourcePath: string, locale: string) => string | null;\n options: Settings;\n}): Promise<void> {\n if (\n options.options?.experimentalClearLocaleDirs !== true ||\n fileTracker.completed.size === 0\n ) {\n return;\n }\n\n const translatedFiles = new Set(\n Array.from(fileTracker.completed.values())\n .map((file) => {\n const outputPath = resolveOutputPath(file.fileName, file.locale);\n // Only clear if the output path is different from the source.\n return outputPath !== null && outputPath !== file.fileName\n ? outputPath\n : null;\n })\n .filter((filePath): filePath is string => filePath !== null)\n );\n\n if (translatedFiles.size === 0) return;\n\n const cwd = path.dirname(options.config);\n\n await clearLocaleDirs(\n translatedFiles,\n locales,\n options.options?.clearLocaleDirsExclude,\n cwd\n );\n}\n\n/**\n * Prepares the file query data from input data and locales\n */\nfunction prepareFileQueryData(\n fileVersionData: FileTranslationData,\n locales: string[],\n branchData: BranchData\n): FileProperties[] {\n const fileQueryData: FileProperties[] = [];\n\n for (const fileId in fileVersionData) {\n for (const locale of locales) {\n fileQueryData.push({\n versionId: fileVersionData[fileId].versionId,\n fileName: fileVersionData[fileId].fileName,\n fileId,\n locale,\n branchId: branchData.currentBranch.id,\n componentCount: fileVersionData[fileId].componentCount,\n });\n }\n }\n\n return fileQueryData;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyCA,eAAsB,oBAAoB,EACxC,iBACA,SACA,YACA,SACA,iBACA,mBACA,SACA,eACA,oBACA,iBAYmB;AACnB,KAAI,CAAC,YAAY;EAGf,MAAM,eAAe,MAAM,IADJ,WAAW,KAAK,QACF,CAAC,KAAK;AAC3C,MAAI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;EACD,CAAC;AAGF,KAAI,aACF,QAAO;AAGT,QAAO;;AAGT,eAAe,yBAAyB,EACtC,aACA,SACA,mBACA,WAMgB;AAChB,KACE,QAAQ,SAAS,gCAAgC,QACjD,YAAY,UAAU,SAAS,EAE/B;CAGF,MAAM,kBAAkB,IAAI,IAC1B,MAAM,KAAK,YAAY,UAAU,QAAQ,CAAC,CACvC,KAAK,SAAS;EACb,MAAM,aAAa,kBAAkB,KAAK,UAAU,KAAK,OAAO;AAEhE,SAAO,eAAe,QAAQ,eAAe,KAAK,WAC9C,aACA;GACJ,CACD,QAAQ,aAAiC,aAAa,KAAK,CAC/D;AAED,KAAI,gBAAgB,SAAS,EAAG;CAEhC,MAAM,MAAM,KAAK,QAAQ,QAAQ,OAAO;AAExC,OAAM,gBACJ,iBACA,SACA,QAAQ,SAAS,wBACjB,IACD;;;;;AAMH,SAAS,qBACP,iBACA,SACA,YACkB;CAClB,MAAM,gBAAkC,EAAE;AAE1C,MAAK,MAAM,UAAU,gBACnB,MAAK,MAAM,UAAU,QACnB,eAAc,KAAK;EACjB,WAAW,gBAAgB,QAAQ;EACnC,UAAU,gBAAgB,QAAQ;EAClC;EACA;EACA,UAAU,WAAW,cAAc;EACnC,gBAAgB,gBAAgB,QAAQ;EACzC,CAAC;AAIN,QAAO"}
|
|
1
|
+
{"version":3,"file":"download.js","names":[],"sources":["../../src/workflows/download.ts"],"sourcesContent":["import path from 'node:path';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { Settings } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { EnqueueFilesResult } from 'generaltranslation/types';\nimport { clearLocaleDirs } from '../fs/clearLocaleDirs.js';\nimport {\n FileStatusTracker,\n PollTranslationJobsStep,\n} from './steps/PollJobsStep.js';\nimport { DownloadTranslationsStep } from './steps/DownloadStep.js';\nimport { BranchData } from '../types/branch.js';\nimport { branchResolutionError } from '../console/index.js';\nimport { logErrorAndExit } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { recordWarning } from '../state/translateWarnings.js';\nimport { BranchStep } from './steps/BranchStep.js';\nimport { FileProperties } from '../types/files.js';\nimport chalk from 'chalk';\nimport {\n getInlineElementsLabel,\n type InlineLibrary,\n} from '../types/libraries.js';\nimport { TEMPLATE_FILE_NAME } from '../utils/constants.js';\n\nexport type FileTranslationData = {\n [fileId: string]: {\n versionId: string;\n fileName: string;\n /** Source component count for GTJSON files */\n componentCount?: number;\n };\n};\n\n/**\n * Checks the status of translations and downloads them using a workflow pattern\n * @param fileVersionData - Mapping of file IDs to their version and name information\n * @param jobData - Optional job data from enqueue operation\n * @param locales - The locales to wait for\n * @param timeoutDuration - The timeout duration for the wait in seconds\n * @param resolveOutputPath - Function to resolve the output path for a given source path and locale\n * @param options - Settings configuration\n * @param forceRetranslation - Whether to force retranslation\n * @param forceDownload - Whether to force download even if file exists\n * @returns True if all translations are downloaded successfully, false otherwise\n */\nexport async function runDownloadWorkflow({\n fileVersionData,\n jobData,\n branchData,\n locales,\n timeoutDuration,\n resolveOutputPath,\n options,\n inlineLibrary,\n forceRetranslation,\n forceDownload,\n}: {\n fileVersionData: FileTranslationData;\n jobData: EnqueueFilesResult | undefined;\n branchData: BranchData | undefined;\n locales: string[];\n timeoutDuration: number;\n resolveOutputPath: (sourcePath: string, locale: string) => string | null;\n options: Settings;\n inlineLibrary?: InlineLibrary;\n forceRetranslation?: boolean;\n forceDownload?: boolean;\n}): Promise<boolean> {\n if (!branchData) {\n // Run the branch step\n const branchStep = new BranchStep(api, options);\n const branchResult = await branchStep.run();\n if (!branchResult) {\n return logErrorAndExit(branchResolutionError);\n }\n branchData = branchResult;\n }\n // readLockfile uses _branchId to select branch-specific lockfile entries.\n // Keep it on a scoped copy so the caller's settings object is not mutated.\n const settingsForBranch: Settings = {\n ...options,\n _branchId: branchData.currentBranch.id,\n };\n // Prepare the query data\n const fileQueryData = prepareFileQueryData(\n fileVersionData,\n locales,\n branchData\n );\n\n // Initialize download status\n const fileTracker: FileStatusTracker = {\n completed: new Map<string, FileProperties>(),\n inProgress: new Map<string, FileProperties>(),\n failed: new Map<string, FileProperties>(),\n skipped: new Map<string, FileProperties>(),\n };\n\n // Step 1: Poll translation jobs if jobData exists\n let pollTimedOut = false;\n if (jobData) {\n const pollStep = new PollTranslationJobsStep(api, inlineLibrary);\n const pollResult = await pollStep.run({\n fileTracker,\n fileQueryData,\n jobData,\n timeoutDuration,\n forceRetranslation,\n });\n\n if (pollResult.fileTracker.failed.size > 0) {\n const failures: string[] = [];\n for (const [, value] of pollResult.fileTracker.failed) {\n const fileName =\n value.fileName === TEMPLATE_FILE_NAME\n ? `<${getInlineElementsLabel(inlineLibrary)}>`\n : value.fileName;\n const reason = createDiagnosticMessage({\n whatHappened: `Failed to translate for locale ${value.locale}`,\n details: value.failureReason,\n });\n failures.push(`- ${fileName}: ${reason}`);\n recordWarning('failed_translation', fileName, reason);\n }\n const failureMessage = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `${pollResult.fileTracker.failed.size} file(s) failed to translate`,\n details: `\\n${failures.join('\\n')}`,\n });\n logger.error(failureMessage);\n\n // If all files failed translation, exit early\n if (pollResult.fileTracker.completed.size === 0) {\n return false;\n }\n }\n\n // Even if polling timed out, still download whatever completed successfully\n if (!pollResult.success) {\n pollTimedOut = true;\n if (pollResult.fileTracker.completed.size > 0) {\n logger.warn(\n chalk.yellow(\n `Timed out, but ${pollResult.fileTracker.completed.size} translation(s) completed successfully. Downloading completed files...`\n )\n );\n } else {\n return false;\n }\n }\n } else {\n for (const file of fileQueryData) {\n // Staging - assume all files are completed\n fileTracker.completed.set(\n `${file.branchId}:${file.fileId}:${file.versionId}:${file.locale}`,\n file\n );\n }\n }\n\n await clearCompletedLocaleDirs({\n fileTracker,\n locales,\n resolveOutputPath,\n options,\n });\n\n // Step 2: Download translations\n const downloadStep = new DownloadTranslationsStep(\n api,\n settingsForBranch,\n inlineLibrary\n );\n const downloadResult = await downloadStep.run({\n fileTracker,\n resolveOutputPath,\n forceDownload,\n });\n\n // If polling timed out, report failure even though we downloaded what we could\n if (pollTimedOut) {\n return false;\n }\n\n return downloadResult;\n}\n\nasync function clearCompletedLocaleDirs({\n fileTracker,\n locales,\n resolveOutputPath,\n options,\n}: {\n fileTracker: FileStatusTracker;\n locales: string[];\n resolveOutputPath: (sourcePath: string, locale: string) => string | null;\n options: Settings;\n}): Promise<void> {\n if (\n options.options?.experimentalClearLocaleDirs !== true ||\n fileTracker.completed.size === 0\n ) {\n return;\n }\n\n const translatedFiles = new Set(\n Array.from(fileTracker.completed.values())\n .map((file) => {\n const outputPath = resolveOutputPath(file.fileName, file.locale);\n // Only clear if the output path is different from the source.\n return outputPath !== null && outputPath !== file.fileName\n ? outputPath\n : null;\n })\n .filter((filePath): filePath is string => filePath !== null)\n );\n\n if (translatedFiles.size === 0) return;\n\n const cwd = path.dirname(options.config);\n\n await clearLocaleDirs(\n translatedFiles,\n locales,\n options.options?.clearLocaleDirsExclude,\n cwd\n );\n}\n\n/**\n * Prepares the file query data from input data and locales\n */\nfunction prepareFileQueryData(\n fileVersionData: FileTranslationData,\n locales: string[],\n branchData: BranchData\n): FileProperties[] {\n const fileQueryData: FileProperties[] = [];\n\n for (const fileId in fileVersionData) {\n for (const locale of locales) {\n fileQueryData.push({\n versionId: fileVersionData[fileId].versionId,\n fileName: fileVersionData[fileId].fileName,\n fileId,\n locale,\n branchId: branchData.currentBranch.id,\n componentCount: fileVersionData[fileId].componentCount,\n });\n }\n }\n\n return fileQueryData;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,eAAsB,oBAAoB,EACxC,iBACA,SACA,YACA,SACA,iBACA,mBACA,SACA,eACA,oBACA,iBAYmB;AACnB,KAAI,CAAC,YAAY;EAGf,MAAM,eAAe,MAAM,IADJ,WAAW,KAAK,QACF,CAAC,KAAK;AAC3C,MAAI,CAAC,aACH,QAAO,gBAAgB,sBAAsB;AAE/C,eAAa;;CAIf,MAAM,oBAA8B;EAClC,G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;EAC7B;EACA;EACA;EACA;EACD,CAAC;CAQF,MAAM,iBAAiB,MAAM,IALJ,yBACvB,KACA,mBACA,cAEuC,CAAC,IAAI;EAC5C;EACA;EACA;EACD,CAAC;AAGF,KAAI,aACF,QAAO;AAGT,QAAO;;AAGT,eAAe,yBAAyB,EACtC,aACA,SACA,mBACA,WAMgB;AAChB,KACE,QAAQ,SAAS,gCAAgC,QACjD,YAAY,UAAU,SAAS,EAE/B;CAGF,MAAM,kBAAkB,IAAI,IAC1B,MAAM,KAAK,YAAY,UAAU,QAAQ,CAAC,CACvC,KAAK,SAAS;EACb,MAAM,aAAa,kBAAkB,KAAK,UAAU,KAAK,OAAO;AAEhE,SAAO,eAAe,QAAQ,eAAe,KAAK,WAC9C,aACA;GACJ,CACD,QAAQ,aAAiC,aAAa,KAAK,CAC/D;AAED,KAAI,gBAAgB,SAAS,EAAG;CAEhC,MAAM,MAAM,KAAK,QAAQ,QAAQ,OAAO;AAExC,OAAM,gBACJ,iBACA,SACA,QAAQ,SAAS,wBACjB,IACD;;;;;AAMH,SAAS,qBACP,iBACA,SACA,YACkB;CAClB,MAAM,gBAAkC,EAAE;AAE1C,MAAK,MAAM,UAAU,gBACnB,MAAK,MAAM,UAAU,QACnB,eAAc,KAAK;EACjB,WAAW,gBAAgB,QAAQ;EACnC,UAAU,gBAAgB,QAAQ;EAClC;EACA;EACA,UAAU,WAAW,cAAc;EACnC,gBAAgB,gBAAgB,QAAQ;EACzC,CAAC;AAIN,QAAO"}
|
package/dist/workflows/stage.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { logger } from "../console/logger.js";
|
|
2
2
|
import { logCollectedFiles, logErrorAndExit } from "../console/logging.js";
|
|
3
3
|
import { branchResolutionError, withOriginalError } from "../console/index.js";
|
|
4
|
+
import { UserAuthError } from "../auth/errors.js";
|
|
4
5
|
import { api } from "../utils/api.js";
|
|
5
6
|
import { syncFonts } from "./utils/syncFonts.js";
|
|
6
7
|
import { BranchStep } from "./steps/BranchStep.js";
|
|
@@ -54,7 +55,7 @@ async function runStageFilesWorkflow({ files, options, settings, inlineLibrary }
|
|
|
54
55
|
enqueueResult: await enqueueStep.run(filesToEnqueue)
|
|
55
56
|
};
|
|
56
57
|
} catch (error) {
|
|
57
|
-
return logErrorAndExit(withOriginalError("Files could not be sent for translation. Check the files, branch configuration, and API credentials, then try again.", error));
|
|
58
|
+
return logErrorAndExit(error instanceof UserAuthError ? error.message : withOriginalError("Files could not be sent for translation. Check the files, branch configuration, and API credentials, then try again.", error));
|
|
58
59
|
}
|
|
59
60
|
}
|
|
60
61
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stage.js","names":[],"sources":["../../src/workflows/stage.ts"],"sourcesContent":["import { logCollectedFiles, logErrorAndExit } from '../console/logging.js';\nimport { branchResolutionError, withOriginalError } from '../console/index.js';\nimport { logger } from '../console/logger.js';\nimport { Settings, TranslateFlags } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { EnqueueFilesResult, FileToUpload } from 'generaltranslation/types';\nimport { UploadSourcesStep } from './steps/UploadSourcesStep.js';\nimport { SetupStep } from './steps/SetupStep.js';\nimport { EnqueueStep } from './steps/EnqueueStep.js';\nimport { BranchStep } from './steps/BranchStep.js';\nimport { TagStep } from './steps/TagStep.js';\nimport { UserEditDiffsStep } from './steps/UserEditDiffsStep.js';\nimport { BranchData } from '../types/branch.js';\nimport { calculateTimeoutMs } from '../utils/calculateTimeoutMs.js';\nimport { filterFilesForEnqueue } from './utils/filterFilesForEnqueue.js';\nimport { syncFonts } from './utils/syncFonts.js';\nimport type { InlineLibrary } from '../types/libraries.js';\n\n/**\n * Sends multiple files for translation to the API using a workflow pattern\n * @param files - Array of file objects to translate\n * @param options - The options for the API call\n * @param settings - Settings configuration\n * @returns The translated content or version ID\n */\nexport async function runStageFilesWorkflow({\n files,\n options,\n settings,\n inlineLibrary,\n}: {\n files: FileToUpload[];\n options: TranslateFlags;\n settings: Settings;\n inlineLibrary?: InlineLibrary;\n}): Promise<{\n branchData: BranchData;\n enqueueResult: EnqueueFilesResult;\n}> {\n try {\n // Log files to be translated\n logCollectedFiles(files, undefined, inlineLibrary);\n\n // Sync fonts before enqueueing so the translation jobs (e.g. Lottie\n // layout refinement) can use them instead of fallback fonts.\n await syncFonts(settings);\n\n // Calculate timeout for setup step\n const timeoutMs = calculateTimeoutMs(options.timeout);\n\n // Create workflow with steps\n const branchStep = new BranchStep(api, settings);\n const uploadStep = new UploadSourcesStep(api, settings);\n const userEditDiffsStep = new UserEditDiffsStep(settings);\n const setupStep = new SetupStep(api, settings, timeoutMs);\n const enqueueStep = new EnqueueStep(api, settings, options.force);\n\n // first run the branch step\n const branchData = await branchStep.run();\n if (!branchData) {\n return logErrorAndExit(branchResolutionError);\n }\n\n // then run the upload step\n const uploadedFiles = await uploadStep.run({ files, branchData });\n\n // optionally run the user edit diffs step (opt-in via --save-local or options.saveLocal)\n if (settings.options?.saveLocal === true) {\n await userEditDiffsStep.run(uploadedFiles);\n }\n\n // then run the tag step (non-fatal — tagging failure should not block translations)\n if (settings.tag) {\n try {\n const userProvidedTag = !!options.tag;\n const tagStep = new TagStep(api, settings, userProvidedTag);\n await tagStep.run(uploadedFiles);\n } catch {\n logger.warn('Failed to create translation tag. Continuing...');\n }\n }\n\n // then run the setup step\n await setupStep.run(uploadedFiles);\n\n // then run the enqueue step\n const { filesToEnqueue, skippedFiles } = await filterFilesForEnqueue({\n gt: api,\n files: uploadedFiles,\n locales: settings.locales,\n force: options.force,\n });\n if (skippedFiles.length > 0) {\n logger.info(\n `Skipped enqueue for ${skippedFiles.length} already translated file${skippedFiles.length === 1 ? '' : 's'}`\n );\n }\n\n const enqueueResult = await enqueueStep.run(filesToEnqueue);\n\n return { branchData, enqueueResult };\n } catch (error) {\n return logErrorAndExit(\n withOriginalError(\n
|
|
1
|
+
{"version":3,"file":"stage.js","names":[],"sources":["../../src/workflows/stage.ts"],"sourcesContent":["import { UserAuthError } from '../auth/errors.js';\nimport { logCollectedFiles, logErrorAndExit } from '../console/logging.js';\nimport { branchResolutionError, withOriginalError } from '../console/index.js';\nimport { logger } from '../console/logger.js';\nimport { Settings, TranslateFlags } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { EnqueueFilesResult, FileToUpload } from 'generaltranslation/types';\nimport { UploadSourcesStep } from './steps/UploadSourcesStep.js';\nimport { SetupStep } from './steps/SetupStep.js';\nimport { EnqueueStep } from './steps/EnqueueStep.js';\nimport { BranchStep } from './steps/BranchStep.js';\nimport { TagStep } from './steps/TagStep.js';\nimport { UserEditDiffsStep } from './steps/UserEditDiffsStep.js';\nimport { BranchData } from '../types/branch.js';\nimport { calculateTimeoutMs } from '../utils/calculateTimeoutMs.js';\nimport { filterFilesForEnqueue } from './utils/filterFilesForEnqueue.js';\nimport { syncFonts } from './utils/syncFonts.js';\nimport type { InlineLibrary } from '../types/libraries.js';\n\n/**\n * Sends multiple files for translation to the API using a workflow pattern\n * @param files - Array of file objects to translate\n * @param options - The options for the API call\n * @param settings - Settings configuration\n * @returns The translated content or version ID\n */\nexport async function runStageFilesWorkflow({\n files,\n options,\n settings,\n inlineLibrary,\n}: {\n files: FileToUpload[];\n options: TranslateFlags;\n settings: Settings;\n inlineLibrary?: InlineLibrary;\n}): Promise<{\n branchData: BranchData;\n enqueueResult: EnqueueFilesResult;\n}> {\n try {\n // Log files to be translated\n logCollectedFiles(files, undefined, inlineLibrary);\n\n // Sync fonts before enqueueing so the translation jobs (e.g. Lottie\n // layout refinement) can use them instead of fallback fonts.\n await syncFonts(settings);\n\n // Calculate timeout for setup step\n const timeoutMs = calculateTimeoutMs(options.timeout);\n\n // Create workflow with steps\n const branchStep = new BranchStep(api, settings);\n const uploadStep = new UploadSourcesStep(api, settings);\n const userEditDiffsStep = new UserEditDiffsStep(settings);\n const setupStep = new SetupStep(api, settings, timeoutMs);\n const enqueueStep = new EnqueueStep(api, settings, options.force);\n\n // first run the branch step\n const branchData = await branchStep.run();\n if (!branchData) {\n return logErrorAndExit(branchResolutionError);\n }\n\n // then run the upload step\n const uploadedFiles = await uploadStep.run({ files, branchData });\n\n // optionally run the user edit diffs step (opt-in via --save-local or options.saveLocal)\n if (settings.options?.saveLocal === true) {\n await userEditDiffsStep.run(uploadedFiles);\n }\n\n // then run the tag step (non-fatal — tagging failure should not block translations)\n if (settings.tag) {\n try {\n const userProvidedTag = !!options.tag;\n const tagStep = new TagStep(api, settings, userProvidedTag);\n await tagStep.run(uploadedFiles);\n } catch {\n logger.warn('Failed to create translation tag. Continuing...');\n }\n }\n\n // then run the setup step\n await setupStep.run(uploadedFiles);\n\n // then run the enqueue step\n const { filesToEnqueue, skippedFiles } = await filterFilesForEnqueue({\n gt: api,\n files: uploadedFiles,\n locales: settings.locales,\n force: options.force,\n });\n if (skippedFiles.length > 0) {\n logger.info(\n `Skipped enqueue for ${skippedFiles.length} already translated file${skippedFiles.length === 1 ? '' : 's'}`\n );\n }\n\n const enqueueResult = await enqueueStep.run(filesToEnqueue);\n\n return { branchData, enqueueResult };\n } catch (error) {\n // A sign-in failure is already a complete diagnostic that names `gt login`.\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : withOriginalError(\n 'Files could not be sent for translation. Check the files, branch configuration, and API credentials, then try again.',\n error\n )\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0BA,eAAsB,sBAAsB,EAC1C,OACA,SACA,UACA,iBASC;AACD,KAAI;AAEF,oBAAkB,OAAO,KAAA,GAAW,cAAc;AAIlD,QAAM,UAAU,SAAS;EAGzB,MAAM,YAAY,mBAAmB,QAAQ,QAAQ;EAGrD,MAAM,aAAa,IAAI,WAAW,KAAK,SAAS;EAChD,MAAM,aAAa,IAAI,kBAAkB,KAAK,SAAS;EACvD,MAAM,oBAAoB,IAAI,kBAAkB,SAAS;EACzD,MAAM,YAAY,IAAI,UAAU,KAAK,UAAU,UAAU;EACzD,MAAM,cAAc,IAAI,YAAY,KAAK,UAAU,QAAQ,MAAM;EAGjE,MAAM,aAAa,MAAM,WAAW,KAAK;AACzC,MAAI,CAAC,WACH,QAAO,gBAAgB,sBAAsB;EAI/C,MAAM,gBAAgB,MAAM,WAAW,IAAI;GAAE;GAAO;GAAY,CAAC;AAGjE,MAAI,SAAS,SAAS,cAAc,KAClC,OAAM,kBAAkB,IAAI,cAAc;AAI5C,MAAI,SAAS,IACX,KAAI;AAGF,SAAM,IADc,QAAQ,KAAK,UAAU,CADlB,CAAC,QAAQ,IAErB,CAAC,IAAI,cAAc;UAC1B;AACN,UAAO,KAAK,kDAAkD;;AAKlE,QAAM,UAAU,IAAI,cAAc;EAGlC,MAAM,EAAE,gBAAgB,iBAAiB,MAAM,sBAAsB;GACnE,IAAI;GACJ,OAAO;GACP,SAAS,SAAS;GAClB,OAAO,QAAQ;GAChB,CAAC;AACF,MAAI,aAAa,SAAS,EACxB,QAAO,KACL,uBAAuB,aAAa,OAAO,0BAA0B,aAAa,WAAW,IAAI,KAAK,MACvG;AAKH,SAAO;GAAE;GAAY,eAAA,MAFO,YAAY,IAAI,eAAe;GAEvB;UAC7B,OAAO;AAEd,SAAO,gBACL,iBAAiB,gBACb,MAAM,UACN,kBACE,wHACA,MACD,CACN"}
|
|
@@ -12,7 +12,9 @@ export type PollJobsInput = {
|
|
|
12
12
|
export type FileStatusTracker = {
|
|
13
13
|
completed: Map<string, FileProperties>;
|
|
14
14
|
inProgress: Map<string, FileProperties>;
|
|
15
|
-
failed: Map<string, FileProperties
|
|
15
|
+
failed: Map<string, FileProperties & {
|
|
16
|
+
failureReason?: string;
|
|
17
|
+
}>;
|
|
16
18
|
skipped: Map<string, FileProperties>;
|
|
17
19
|
};
|
|
18
20
|
export type PollJobsOutput = {
|
|
@@ -70,7 +70,10 @@ var PollTranslationJobsStep = class {
|
|
|
70
70
|
const fileProperties = filePropertiesMap.get(fileKey);
|
|
71
71
|
if (!fileProperties) continue;
|
|
72
72
|
if (job.status === "completed") fileTracker.completed.set(fileKey, fileProperties);
|
|
73
|
-
else if (job.status === "failed") fileTracker.failed.set(fileKey,
|
|
73
|
+
else if (job.status === "failed") fileTracker.failed.set(fileKey, {
|
|
74
|
+
...fileProperties,
|
|
75
|
+
failureReason: job.error?.message ?? void 0
|
|
76
|
+
});
|
|
74
77
|
else if (job.status === "unknown") fileTracker.skipped.set(fileKey, fileProperties);
|
|
75
78
|
else continue;
|
|
76
79
|
fileTracker.inProgress.delete(fileKey);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PollJobsStep.js","names":[],"sources":["../../../src/workflows/steps/PollJobsStep.ts"],"sourcesContent":["import chalk from 'chalk';\nimport type { JobResult } from 'generaltranslation/api';\nimport { logger } from '../../console/logger.js';\nimport type { ApiClient } from '../../utils/api.js';\nimport { EnqueueFilesResult } from 'generaltranslation/types';\nimport { TEMPLATE_FILE_NAME } from '../../utils/constants.js';\nimport type { FileProperties } from '../../types/files.js';\nimport {\n getFileTranslationKey,\n queryCompletedTranslationKeys,\n} from '../utils/queryCompletedTranslations.js';\nimport {\n getInlineElementsLabel,\n type InlineLibrary,\n} from '../../types/libraries.js';\n\nexport type PollJobsInput = {\n fileTracker: FileStatusTracker;\n fileQueryData: FileProperties[];\n jobData: EnqueueFilesResult;\n timeoutDuration: number;\n forceRetranslation?: boolean;\n};\n\nexport type FileStatusTracker = {\n completed: Map<string, FileProperties>;\n inProgress: Map<string, FileProperties>;\n failed: Map<string, FileProperties>;\n skipped: Map<string, FileProperties>;\n};\n\nexport type PollJobsOutput = {\n success: boolean;\n fileTracker: FileStatusTracker;\n};\n\nexport class PollTranslationJobsStep {\n private spinner: ReturnType<typeof logger.createProgressBar> | null = null;\n private previousProgress = 0;\n\n constructor(\n private api: ApiClient,\n private inlineLibrary?: InlineLibrary\n ) {}\n\n async run({\n fileTracker,\n fileQueryData,\n jobData,\n timeoutDuration,\n forceRetranslation,\n }: PollJobsInput): Promise<PollJobsOutput> {\n const startTime = Date.now();\n this.spinner = logger.createProgressBar(fileQueryData.length);\n const spinnerMessage = forceRetranslation\n ? 'Waiting for retranslation...'\n : 'Waiting for translation...';\n this.spinner.start(spinnerMessage);\n\n // Build a map of branchId:fileId:versionId:locale -> FileProperties\n const filePropertiesMap = new Map<string, FileProperties>();\n fileQueryData.forEach((item) => {\n filePropertiesMap.set(getFileTranslationKey(item), item);\n });\n\n // Initial query to check which files already have translations\n // Skip when force retranslation is enabled, since the server\n // no longer marks force-retranslated files as incomplete\n if (!forceRetranslation) {\n const completedKeys = await queryCompletedTranslationKeys(\n this.api,\n fileQueryData\n );\n\n completedKeys.forEach((fileKey) => {\n const fileProperties = filePropertiesMap.get(fileKey);\n if (fileProperties) {\n fileTracker.completed.set(fileKey, fileProperties);\n }\n });\n }\n\n // Build a map of jobs for quick lookup:\n // branchId:fileId:versionId:locale -> job\n const jobMap = new Map<\n string,\n (typeof jobData.jobData)[number] & { jobId: string }\n >();\n Object.entries(jobData.jobData).forEach(([jobId, job]) => {\n const jobLocale = this.api.resolveAliasLocale(job.targetLocale);\n const key = `${job.branchId}:${job.fileId}:${job.versionId}:${jobLocale}`;\n jobMap.set(key, { ...job, jobId, targetLocale: jobLocale });\n });\n\n // Build a map of jobs for quick lookup:\n // jobId -> file data for the job\n const jobFileMap = new Map<\n string,\n {\n branchId: string;\n fileId: string;\n versionId: string;\n locale: string;\n }\n >();\n Object.entries(jobData.jobData).forEach(([jobId, job]) => {\n const jobLocale = this.api.resolveAliasLocale(job.targetLocale);\n jobFileMap.set(jobId, {\n branchId: job.branchId,\n fileId: job.fileId,\n versionId: job.versionId,\n locale: jobLocale,\n });\n });\n\n // Categorize each file query item\n for (const item of fileQueryData) {\n const fileKey = getFileTranslationKey(item);\n\n // Check if translation already exists (completedAt is truthy)\n const existingTranslation = fileTracker.completed.get(fileKey);\n\n if (existingTranslation) {\n continue;\n }\n\n // Check if there's a job for this file\n const jobKey = `${item.branchId}:${item.fileId}:${item.versionId}:${item.locale}`;\n const job = jobMap.get(jobKey);\n\n if (job) {\n // Job exists - mark as in progress initially\n fileTracker.inProgress.set(fileKey, item);\n } else {\n // No job and no existing translation - mark as skipped\n fileTracker.skipped.set(fileKey, item);\n }\n }\n\n // Update spinner with initial status\n this.updateSpinner(fileTracker, fileQueryData);\n\n // If force retranslation, don't skip the initial check\n if (!forceRetranslation) {\n // Check if all jobs are already complete\n if (fileTracker.inProgress.size === 0) {\n this.spinner.stop(chalk.green('All translations ready'));\n return { success: true, fileTracker };\n }\n }\n\n const timeoutSeconds = Math.max(\n 0,\n timeoutDuration - (Date.now() - startTime) / 1000\n );\n\n // onPoll receives raw statuses and result.jobs normalized ones; only the\n // shared fields are read here.\n const updateJobStatuses = (\n statuses: readonly Pick<JobResult, 'jobId' | 'status'>[]\n ) => {\n for (const job of statuses) {\n const jobFileProperties = jobFileMap.get(job.jobId);\n if (!jobFileProperties) continue;\n\n const fileKey = `${jobFileProperties.branchId}:${jobFileProperties.fileId}:${jobFileProperties.versionId}:${jobFileProperties.locale}`;\n const fileProperties = filePropertiesMap.get(fileKey);\n if (!fileProperties) continue;\n\n if (job.status === 'completed') {\n fileTracker.completed.set(fileKey, fileProperties);\n } else if (job.status === 'failed') {\n fileTracker.failed.set(fileKey, fileProperties);\n } else if (job.status === 'unknown') {\n fileTracker.skipped.set(fileKey, fileProperties);\n } else {\n continue;\n }\n fileTracker.inProgress.delete(fileKey);\n jobFileMap.delete(job.jobId);\n }\n this.updateSpinner(fileTracker, fileQueryData);\n };\n\n try {\n const result = await this.api.awaitJobs([...jobFileMap.keys()], {\n pollingIntervalSeconds: 5,\n timeoutSeconds,\n onPoll: updateJobStatuses,\n });\n if (result.complete) updateJobStatuses(result.jobs);\n } catch (error) {\n this.spinner.stop(chalk.red('Error checking translation job status'));\n throw error;\n }\n\n if (fileTracker.inProgress.size === 0) {\n this.spinner.stop(chalk.green('Translation jobs finished'));\n return { success: true, fileTracker };\n }\n\n this.spinner.stop(chalk.red('Timed out waiting for translation jobs'));\n return { success: false, fileTracker };\n }\n\n private updateSpinner(\n fileTracker: FileStatusTracker,\n fileQueryData: FileProperties[]\n ): void {\n if (!this.spinner) return;\n\n const statusText = this.generateStatusSuffixText(\n fileTracker,\n fileQueryData\n );\n const currentProgress =\n fileTracker.completed.size +\n fileTracker.failed.size +\n fileTracker.skipped.size;\n const progressDelta = currentProgress - this.previousProgress;\n this.spinner.advance(progressDelta, statusText);\n this.previousProgress = currentProgress;\n }\n\n private generateStatusSuffixText(\n fileTracker: FileStatusTracker,\n fileQueryData: FileProperties[]\n ): string {\n // Simple progress indicator\n const progressText = `${chalk.green(\n `[${\n fileTracker.completed.size +\n fileTracker.failed.size +\n fileTracker.skipped.size\n }/${fileQueryData.length}]`\n )} translations completed`;\n\n // Get terminal height to adapt our output\n const terminalHeight = process.stdout.rows || 24;\n\n // If terminal is very small, just show the basic progress\n if (terminalHeight < 6) {\n return progressText;\n }\n\n const newSuffixText = [progressText];\n\n // Organize data by filename : locale\n const fileStatus = new Map<\n string,\n {\n completed: Set<string>;\n pending: Set<string>;\n failed: Set<string>;\n skipped: Set<string>;\n }\n >();\n\n // Initialize with all files and locales from fileQueryData\n for (const item of fileQueryData) {\n if (!fileStatus.has(item.fileName)) {\n fileStatus.set(item.fileName, {\n completed: new Set(),\n pending: new Set([item.locale]),\n failed: new Set(),\n skipped: new Set(),\n });\n } else {\n fileStatus.get(item.fileName)?.pending.add(item.locale);\n }\n }\n\n // Mark which ones are completed, failed, or skipped\n for (const [_, fileProperties] of fileTracker.completed) {\n const { fileName, locale } = fileProperties;\n const status = fileStatus.get(fileName);\n if (status) {\n status.pending.delete(locale);\n status.completed.add(locale);\n }\n }\n\n for (const [_, fileProperties] of fileTracker.failed) {\n const { fileName, locale } = fileProperties;\n const status = fileStatus.get(fileName);\n if (status) {\n status.pending.delete(locale);\n status.failed.add(locale);\n }\n }\n\n for (const [_, fileProperties] of fileTracker.skipped) {\n const { fileName, locale } = fileProperties;\n const status = fileStatus.get(fileName);\n if (status) {\n status.pending.delete(locale);\n status.skipped.add(locale);\n }\n }\n\n // Calculate how many files we can show based on terminal height\n const filesArray = Array.from(fileStatus.entries());\n const maxFilesToShow = Math.min(\n filesArray.length,\n terminalHeight - 3 // Header + progress + buffer\n );\n\n // Display each file with its status on a single line\n for (let i = 0; i < maxFilesToShow; i++) {\n const [fileName, status] = filesArray[i];\n\n // Create condensed locale status\n const localeStatuses: { locale: string; status: string }[] = [];\n\n // Add completed locales (green)\n if (status.completed.size > 0) {\n localeStatuses.push(\n ...Array.from(status.completed).map((locale) => ({\n locale,\n status: 'completed',\n }))\n );\n }\n\n // Add skipped locales (green)\n if (status.skipped.size > 0) {\n localeStatuses.push(\n ...Array.from(status.skipped).map((locale) => ({\n locale,\n status: 'skipped',\n }))\n );\n }\n\n // Add failed locales (red)\n if (status.failed.size > 0) {\n localeStatuses.push(\n ...Array.from(status.failed).map((locale) => ({\n locale,\n status: 'failed',\n }))\n );\n }\n\n // Add pending locales (yellow)\n if (status.pending.size > 0) {\n localeStatuses.push(\n ...Array.from(status.pending).map((locale) => ({\n locale,\n status: 'pending',\n }))\n );\n }\n\n // Sort localeStatuses by locale\n localeStatuses.sort((a, b) => a.locale.localeCompare(b.locale));\n\n // Add colors\n const localeString = localeStatuses\n .map((locale) => {\n if (locale.status === 'completed') {\n return chalk.green(locale.locale);\n } else if (locale.status === 'skipped') {\n return chalk.gray(locale.locale);\n } else if (locale.status === 'failed') {\n return chalk.red(locale.locale);\n } else if (locale.status === 'pending') {\n return chalk.yellow(locale.locale);\n }\n })\n .join(', ');\n\n // Format the line\n const prettyFileName =\n fileName === TEMPLATE_FILE_NAME\n ? `<${getInlineElementsLabel(this.inlineLibrary)}>`\n : fileName;\n newSuffixText.push(`${chalk.bold(prettyFileName)} [${localeString}]`);\n }\n\n // If we couldn't show all files, add an indicator\n if (filesArray.length > maxFilesToShow) {\n newSuffixText.push(\n `... and ${filesArray.length - maxFilesToShow} more files`\n );\n }\n\n return newSuffixText.join('\\n');\n }\n}\n"],"mappings":";;;;;;AAoCA,IAAa,0BAAb,MA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;AAIH,kBAAe,MAAM,GAAG,MAAM,EAAE,OAAO,cAAc,EAAE,OAAO,CAAC;GAG/D,MAAM,eAAe,eAClB,KAAK,WAAW;AACf,QAAI,OAAO,WAAW,YACpB,QAAO,MAAM,MAAM,OAAO,OAAO;aACxB,OAAO,WAAW,UAC3B,QAAO,MAAM,KAAK,OAAO,OAAO;aACvB,OAAO,WAAW,SAC3B,QAAO,MAAM,IAAI,OAAO,OAAO;aACtB,OAAO,WAAW,UAC3B,QAAO,MAAM,OAAO,OAAO,OAAO;KAEpC,CACD,KAAK,KAAK;GAGb,MAAM,iBACJ,aAAA,kCACI,IAAI,uBAAuB,KAAK,cAAc,CAAC,KAC/C;AACN,iBAAc,KAAK,GAAG,MAAM,KAAK,eAAe,CAAC,IAAI,aAAa,GAAG;;AAIvE,MAAI,WAAW,SAAS,eACtB,eAAc,KACZ,WAAW,WAAW,SAAS,eAAe,aAC/C;AAGH,SAAO,cAAc,KAAK,KAAK"}
|
|
1
|
+
{"version":3,"file":"PollJobsStep.js","names":[],"sources":["../../../src/workflows/steps/PollJobsStep.ts"],"sourcesContent":["import chalk from 'chalk';\nimport type { JobResult } from 'generaltranslation/api';\nimport { logger } from '../../console/logger.js';\nimport type { ApiClient } from '../../utils/api.js';\nimport { EnqueueFilesResult } from 'generaltranslation/types';\nimport type { JobResult as NormalizedJobResult } from 'generaltranslation/types';\nimport { TEMPLATE_FILE_NAME } from '../../utils/constants.js';\nimport type { FileProperties } from '../../types/files.js';\nimport {\n getFileTranslationKey,\n queryCompletedTranslationKeys,\n} from '../utils/queryCompletedTranslations.js';\nimport {\n getInlineElementsLabel,\n type InlineLibrary,\n} from '../../types/libraries.js';\n\nexport type PollJobsInput = {\n fileTracker: FileStatusTracker;\n fileQueryData: FileProperties[];\n jobData: EnqueueFilesResult;\n timeoutDuration: number;\n forceRetranslation?: boolean;\n};\n\nexport type FileStatusTracker = {\n completed: Map<string, FileProperties>;\n inProgress: Map<string, FileProperties>;\n failed: Map<string, FileProperties & { failureReason?: string }>;\n skipped: Map<string, FileProperties>;\n};\n\nexport type PollJobsOutput = {\n success: boolean;\n fileTracker: FileStatusTracker;\n};\n\nexport class PollTranslationJobsStep {\n private spinner: ReturnType<typeof logger.createProgressBar> | null = null;\n private previousProgress = 0;\n\n constructor(\n private api: ApiClient,\n private inlineLibrary?: InlineLibrary\n ) {}\n\n async run({\n fileTracker,\n fileQueryData,\n jobData,\n timeoutDuration,\n forceRetranslation,\n }: PollJobsInput): Promise<PollJobsOutput> {\n const startTime = Date.now();\n this.spinner = logger.createProgressBar(fileQueryData.length);\n const spinnerMessage = forceRetranslation\n ? 'Waiting for retranslation...'\n : 'Waiting for translation...';\n this.spinner.start(spinnerMessage);\n\n // Build a map of branchId:fileId:versionId:locale -> FileProperties\n const filePropertiesMap = new Map<string, FileProperties>();\n fileQueryData.forEach((item) => {\n filePropertiesMap.set(getFileTranslationKey(item), item);\n });\n\n // Initial query to check which files already have translations\n // Skip when force retranslation is enabled, since the server\n // no longer marks force-retranslated files as incomplete\n if (!forceRetranslation) {\n const completedKeys = await queryCompletedTranslationKeys(\n this.api,\n fileQueryData\n );\n\n completedKeys.forEach((fileKey) => {\n const fileProperties = filePropertiesMap.get(fileKey);\n if (fileProperties) {\n fileTracker.completed.set(fileKey, fileProperties);\n }\n });\n }\n\n // Build a map of jobs for quick lookup:\n // branchId:fileId:versionId:locale -> job\n const jobMap = new Map<\n string,\n (typeof jobData.jobData)[number] & { jobId: string }\n >();\n Object.entries(jobData.jobData).forEach(([jobId, job]) => {\n const jobLocale = this.api.resolveAliasLocale(job.targetLocale);\n const key = `${job.branchId}:${job.fileId}:${job.versionId}:${jobLocale}`;\n jobMap.set(key, { ...job, jobId, targetLocale: jobLocale });\n });\n\n // Build a map of jobs for quick lookup:\n // jobId -> file data for the job\n const jobFileMap = new Map<\n string,\n {\n branchId: string;\n fileId: string;\n versionId: string;\n locale: string;\n }\n >();\n Object.entries(jobData.jobData).forEach(([jobId, job]) => {\n const jobLocale = this.api.resolveAliasLocale(job.targetLocale);\n jobFileMap.set(jobId, {\n branchId: job.branchId,\n fileId: job.fileId,\n versionId: job.versionId,\n locale: jobLocale,\n });\n });\n\n // Categorize each file query item\n for (const item of fileQueryData) {\n const fileKey = getFileTranslationKey(item);\n\n // Check if translation already exists (completedAt is truthy)\n const existingTranslation = fileTracker.completed.get(fileKey);\n\n if (existingTranslation) {\n continue;\n }\n\n // Check if there's a job for this file\n const jobKey = `${item.branchId}:${item.fileId}:${item.versionId}:${item.locale}`;\n const job = jobMap.get(jobKey);\n\n if (job) {\n // Job exists - mark as in progress initially\n fileTracker.inProgress.set(fileKey, item);\n } else {\n // No job and no existing translation - mark as skipped\n fileTracker.skipped.set(fileKey, item);\n }\n }\n\n // Update spinner with initial status\n this.updateSpinner(fileTracker, fileQueryData);\n\n // If force retranslation, don't skip the initial check\n if (!forceRetranslation) {\n // Check if all jobs are already complete\n if (fileTracker.inProgress.size === 0) {\n this.spinner.stop(chalk.green('All translations ready'));\n return { success: true, fileTracker };\n }\n }\n\n const timeoutSeconds = Math.max(\n 0,\n timeoutDuration - (Date.now() - startTime) / 1000\n );\n\n const updateJobStatuses = (\n statuses: readonly (JobResult | NormalizedJobResult)[]\n ) => {\n for (const job of statuses) {\n const jobFileProperties = jobFileMap.get(job.jobId);\n if (!jobFileProperties) continue;\n\n const fileKey = `${jobFileProperties.branchId}:${jobFileProperties.fileId}:${jobFileProperties.versionId}:${jobFileProperties.locale}`;\n const fileProperties = filePropertiesMap.get(fileKey);\n if (!fileProperties) continue;\n\n if (job.status === 'completed') {\n fileTracker.completed.set(fileKey, fileProperties);\n } else if (job.status === 'failed') {\n fileTracker.failed.set(fileKey, {\n ...fileProperties,\n failureReason: job.error?.message ?? undefined,\n });\n } else if (job.status === 'unknown') {\n fileTracker.skipped.set(fileKey, fileProperties);\n } else {\n continue;\n }\n fileTracker.inProgress.delete(fileKey);\n jobFileMap.delete(job.jobId);\n }\n this.updateSpinner(fileTracker, fileQueryData);\n };\n\n try {\n const result = await this.api.awaitJobs([...jobFileMap.keys()], {\n pollingIntervalSeconds: 5,\n timeoutSeconds,\n onPoll: updateJobStatuses,\n });\n if (result.complete) updateJobStatuses(result.jobs);\n } catch (error) {\n this.spinner.stop(chalk.red('Error checking translation job status'));\n throw error;\n }\n\n if (fileTracker.inProgress.size === 0) {\n this.spinner.stop(chalk.green('Translation jobs finished'));\n return { success: true, fileTracker };\n }\n\n this.spinner.stop(chalk.red('Timed out waiting for translation jobs'));\n return { success: false, fileTracker };\n }\n\n private updateSpinner(\n fileTracker: FileStatusTracker,\n fileQueryData: FileProperties[]\n ): void {\n if (!this.spinner) return;\n\n const statusText = this.generateStatusSuffixText(\n fileTracker,\n fileQueryData\n );\n const currentProgress =\n fileTracker.completed.size +\n fileTracker.failed.size +\n fileTracker.skipped.size;\n const progressDelta = currentProgress - this.previousProgress;\n this.spinner.advance(progressDelta, statusText);\n this.previousProgress = currentProgress;\n }\n\n private generateStatusSuffixText(\n fileTracker: FileStatusTracker,\n fileQueryData: FileProperties[]\n ): string {\n // Simple progress indicator\n const progressText = `${chalk.green(\n `[${\n fileTracker.completed.size +\n fileTracker.failed.size +\n fileTracker.skipped.size\n }/${fileQueryData.length}]`\n )} translations completed`;\n\n // Get terminal height to adapt our output\n const terminalHeight = process.stdout.rows || 24;\n\n // If terminal is very small, just show the basic progress\n if (terminalHeight < 6) {\n return progressText;\n }\n\n const newSuffixText = [progressText];\n\n // Organize data by filename : locale\n const fileStatus = new Map<\n string,\n {\n completed: Set<string>;\n pending: Set<string>;\n failed: Set<string>;\n skipped: Set<string>;\n }\n >();\n\n // Initialize with all files and locales from fileQueryData\n for (const item of fileQueryData) {\n if (!fileStatus.has(item.fileName)) {\n fileStatus.set(item.fileName, {\n completed: new Set(),\n pending: new Set([item.locale]),\n failed: new Set(),\n skipped: new Set(),\n });\n } else {\n fileStatus.get(item.fileName)?.pending.add(item.locale);\n }\n }\n\n // Mark which ones are completed, failed, or skipped\n for (const [_, fileProperties] of fileTracker.completed) {\n const { fileName, locale } = fileProperties;\n const status = fileStatus.get(fileName);\n if (status) {\n status.pending.delete(locale);\n status.completed.add(locale);\n }\n }\n\n for (const [_, fileProperties] of fileTracker.failed) {\n const { fileName, locale } = fileProperties;\n const status = fileStatus.get(fileName);\n if (status) {\n status.pending.delete(locale);\n status.failed.add(locale);\n }\n }\n\n for (const [_, fileProperties] of fileTracker.skipped) {\n const { fileName, locale } = fileProperties;\n const status = fileStatus.get(fileName);\n if (status) {\n status.pending.delete(locale);\n status.skipped.add(locale);\n }\n }\n\n // Calculate how many files we can show based on terminal height\n const filesArray = Array.from(fileStatus.entries());\n const maxFilesToShow = Math.min(\n filesArray.length,\n terminalHeight - 3 // Header + progress + buffer\n );\n\n // Display each file with its status on a single line\n for (let i = 0; i < maxFilesToShow; i++) {\n const [fileName, status] = filesArray[i];\n\n // Create condensed locale status\n const localeStatuses: { locale: string; status: string }[] = [];\n\n // Add completed locales (green)\n if (status.completed.size > 0) {\n localeStatuses.push(\n ...Array.from(status.completed).map((locale) => ({\n locale,\n status: 'completed',\n }))\n );\n }\n\n // Add skipped locales (green)\n if (status.skipped.size > 0) {\n localeStatuses.push(\n ...Array.from(status.skipped).map((locale) => ({\n locale,\n status: 'skipped',\n }))\n );\n }\n\n // Add failed locales (red)\n if (status.failed.size > 0) {\n localeStatuses.push(\n ...Array.from(status.failed).map((locale) => ({\n locale,\n status: 'failed',\n }))\n );\n }\n\n // Add pending locales (yellow)\n if (status.pending.size > 0) {\n localeStatuses.push(\n ...Array.from(status.pending).map((locale) => ({\n locale,\n status: 'pending',\n }))\n );\n }\n\n // Sort localeStatuses by locale\n localeStatuses.sort((a, b) => a.locale.localeCompare(b.locale));\n\n // Add colors\n const localeString = localeStatuses\n .map((locale) => {\n if (locale.status === 'completed') {\n return chalk.green(locale.locale);\n } else if (locale.status === 'skipped') {\n return chalk.gray(locale.locale);\n } else if (locale.status === 'failed') {\n return chalk.red(locale.locale);\n } else if (locale.status === 'pending') {\n return chalk.yellow(locale.locale);\n }\n })\n .join(', ');\n\n // Format the line\n const prettyFileName =\n fileName === TEMPLATE_FILE_NAME\n ? `<${getInlineElementsLabel(this.inlineLibrary)}>`\n : fileName;\n newSuffixText.push(`${chalk.bold(prettyFileName)} [${localeString}]`);\n }\n\n // If we couldn't show all files, add an indicator\n if (filesArray.length > maxFilesToShow) {\n newSuffixText.push(\n `... and ${filesArray.length - maxFilesToShow} more files`\n );\n }\n\n return newSuffixText.join('\\n');\n }\n}\n"],"mappings":";;;;;;AAqCA,IAAa,0BAAb,MAAqC;CACnC,UAAsE;CACtE,mBAA2B;CAE3B,YACE,KACA,eACA;AAFQ,OAAA,MAAA;AACA,OAAA,gBAAA;;CAGV,MAAM,IAAI,EACR,aACA,eACA,SACA,iBACA,sBACyC;EACzC,MAAM,YAAY,KAAK,KAAK;AAC5B,OAAK,UAAU,OAAO,kBAAkB,cAAc,OAAO;EAC7D,MAAM,iBAAiB,qBACnB,iCACA;AACJ,OAAK,QAAQ,MAAM,eAAe;EAGlC,MAAM,oCAAoB,IAAI,KAA6B;AAC3D,gBAAc,SAAS,SAAS;AAC9B,qBAAkB,IAAI,sBAAsB,KAAK,EAAE,KAAK;IACxD;AAKF,MAAI,CAAC,mBAMH,EAAA,MAL4B,8BAC1B,KAAK,KACL,cACD,EAEa,SAAS,YAAY;GACjC,MAAM,iBAAiB,kBAAkB,IAAI,QAAQ;AACrD,OAAI,eACF,aAAY,UAAU,IAAI,SAAS,eAAe;IAEpD;EAKJ,MAAM,yBAAS,IAAI,KAGhB;AACH,SAAO,QAAQ,QAAQ,QAAQ,CAAC,SAAS,CAAC,OAAO,SAAS;GACxD,MAAM,YAAY,KAAK,IAAI,mBAAmB,IAAI,aAAa;GAC/D,MAAM,MAAM,GAAG,IAAI,SAAS,GAAG,IAAI,OAAO,GAAG,IAAI,UAAU,GAAG;AAC9D,UAAO,IAAI,KAAK;IAAE,GAAG;IAAK;IAAO,cAAc;IAAW,CAAC;IAC3D;EAIF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118
118
|
"yaml": "^2.8.0",
|
|
119
119
|
"@generaltranslation/format": "0.1.9",
|
|
120
120
|
"@generaltranslation/icu": "0.1.2",
|
|
121
|
-
"@generaltranslation/python-extractor": "0.2.
|
|
122
|
-
"@generaltranslation/supported-locales": "2.1.
|
|
123
|
-
"@generaltranslation/vue-extractor": "0.1.
|
|
124
|
-
"generaltranslation": "9.5.
|
|
121
|
+
"@generaltranslation/python-extractor": "0.2.65",
|
|
122
|
+
"@generaltranslation/supported-locales": "2.1.46",
|
|
123
|
+
"@generaltranslation/vue-extractor": "0.1.24",
|
|
124
|
+
"generaltranslation": "9.5.10",
|
|
125
125
|
"gt-remark": "1.0.12"
|
|
126
126
|
},
|
|
127
127
|
"devDependencies": {
|