gt 2.26.12 → 2.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -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 +60 -16
- 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 +21 -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/stage.js +2 -1
- package/dist/workflows/stage.js.map +1 -1
- package/package.json +5 -5
|
@@ -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,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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"}
|
|
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,QAA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SAAS,CAAC,UACtD,OAAO,QAAQ,SAAS,CAAC,MAAM,CAAC,MAAM,WAAW,QAAQ,UAAU,MAAM,CAEzE,OAAM,IAAI,MAAM,0BAA0B;AAE5C,QAAO;;AAIT,eAAsB,eACpB,aACA,WACA,MAAc,QAAQ,KAAK,EAC3B;CACA,MAAM,EACJ,SACA,UAAU,iBACV,aACE,MAAM,0BAA0B,IAAI;CAExC,MAAM,aAAa,4BACjB,kBACI,MAAM,GAAG,SAAS,SAAS,gBAAgB,QAAQ,OAAO,GAC1D,IACJ,aACA,UACD;AAED,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"}
|
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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gt",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.27.1",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"bin": "bin/main.js",
|
|
6
6
|
"files": [
|
|
@@ -118,10 +118,10 @@
|
|
|
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": {
|