gt 2.25.2 → 2.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/api/downloadFileBatch.js +8 -9
- package/dist/api/downloadFileBatch.js.map +1 -1
- package/dist/bin/bin-entry.js +1 -1
- package/dist/cli/base.js +9 -7
- package/dist/cli/base.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/main.js +1 -1
- package/dist/setup/buildTools/index.d.ts +6 -0
- package/dist/setup/buildTools/index.js +6 -1
- package/dist/setup/buildTools/index.js.map +1 -1
- package/dist/setup/buildTools/reactRouter/index.d.ts +2 -0
- package/dist/setup/buildTools/reactRouter/index.js +127 -0
- package/dist/setup/buildTools/reactRouter/index.js.map +1 -0
- package/dist/setup/buildTools/reactRouter/root.d.ts +23 -0
- package/dist/setup/buildTools/reactRouter/root.js +218 -0
- package/dist/setup/buildTools/reactRouter/root.js.map +1 -0
- package/dist/setup/buildTools/reactRouter/source.d.ts +8 -0
- package/dist/setup/buildTools/reactRouter/source.js +106 -0
- package/dist/setup/buildTools/reactRouter/source.js.map +1 -0
- package/dist/setup/buildTools/shared/document.d.ts +29 -0
- package/dist/setup/buildTools/shared/document.js +76 -0
- package/dist/setup/buildTools/shared/document.js.map +1 -0
- package/dist/setup/buildTools/shared/edits.d.ts +1 -2
- package/dist/setup/buildTools/shared/edits.js.map +1 -1
- package/dist/setup/buildTools/shared/initializeGT.d.ts +21 -0
- package/dist/setup/buildTools/shared/initializeGT.js +50 -0
- package/dist/setup/buildTools/shared/initializeGT.js.map +1 -0
- package/dist/setup/buildTools/shared/loader.d.ts +6 -0
- package/dist/setup/buildTools/shared/loader.js +24 -0
- package/dist/setup/buildTools/shared/loader.js.map +1 -0
- package/dist/setup/buildTools/shared/source.d.ts +29 -3
- package/dist/setup/buildTools/shared/source.js +44 -7
- package/dist/setup/buildTools/shared/source.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/index.js +17 -12
- package/dist/setup/buildTools/tanstackStart/index.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/root.d.ts +1 -4
- package/dist/setup/buildTools/tanstackStart/root.js +17 -57
- package/dist/setup/buildTools/tanstackStart/root.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/router.d.ts +1 -9
- package/dist/setup/buildTools/tanstackStart/router.js +7 -39
- package/dist/setup/buildTools/tanstackStart/router.js.map +1 -1
- package/dist/setup/buildTools/vite.js +3 -11
- package/dist/setup/buildTools/vite.js.map +1 -1
- package/dist/setup/detectFramework.d.ts +1 -1
- package/dist/setup/detectFramework.js +5 -1
- package/dist/setup/detectFramework.js.map +1 -1
- package/dist/setup/developmentCredentials.js +39 -8
- package/dist/setup/developmentCredentials.js.map +1 -1
- package/dist/setup/frameworkUtils.js +1 -0
- package/dist/setup/frameworkUtils.js.map +1 -1
- package/dist/setup/wizard.js +4 -0
- package/dist/setup/wizard.js.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.js +2 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/constants.d.ts +1 -0
- package/dist/utils/constants.js +2 -1
- package/dist/utils/constants.js.map +1 -1
- package/dist/utils/credentials.js +2 -1
- package/dist/utils/credentials.js.map +1 -1
- package/dist/utils/loadEnv.d.ts +2 -0
- package/dist/utils/loadEnv.js +10 -9
- package/dist/utils/loadEnv.js.map +1 -1
- package/dist/utils/reactPackageCompatibility.d.ts +5 -0
- package/dist/utils/reactPackageCompatibility.js +11 -7
- package/dist/utils/reactPackageCompatibility.js.map +1 -1
- package/package.json +5 -5
|
@@ -1,40 +1,9 @@
|
|
|
1
1
|
import "../../../types/libraries.js";
|
|
2
2
|
import { toRelativeImport } from "../../setupViteSPA.js";
|
|
3
|
-
import {
|
|
3
|
+
import { getStorageChangeAction } from "../shared/initializeGT.js";
|
|
4
4
|
import { DOCS_URL } from "./source.js";
|
|
5
5
|
import path from "node:path";
|
|
6
|
-
import * as t from "@babel/types";
|
|
7
6
|
//#region src/setup/buildTools/tanstackStart/router.ts
|
|
8
|
-
/** The module-scope `initializeGT(...)` call, which must run before requests. */
|
|
9
|
-
function findInitializeCall(file) {
|
|
10
|
-
const local = getLocalImport(file, "initializeGT", "gt-tanstack-start");
|
|
11
|
-
if (!local) return void 0;
|
|
12
|
-
for (const statement of file.statements ?? []) if (statement.type === "ExpressionStatement" && statement.expression.type === "CallExpression" && t.isIdentifier(statement.expression.callee, { name: local })) return statement.expression;
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Whether the initializeGT options pass a loader: false for the config alone,
|
|
16
|
-
* undefined when the options hide it (other spreads, variables, computed keys).
|
|
17
|
-
*/
|
|
18
|
-
function passesLoader(router, options, { appDirectory, configFilepath }) {
|
|
19
|
-
const configPath = path.resolve(appDirectory, configFilepath);
|
|
20
|
-
const routerDirectory = path.dirname(path.join(appDirectory, router.path));
|
|
21
|
-
const configBinding = router.statements?.filter((statement) => statement.type === "ImportDeclaration").find((statement) => path.resolve(routerDirectory, statement.source.value) === configPath)?.specifiers.find((specifier) => specifier.type === "ImportDefaultSpecifier")?.local.name;
|
|
22
|
-
const isConfig = (node) => node.type === "Identifier" && node.name === configBinding;
|
|
23
|
-
if (!options) return void 0;
|
|
24
|
-
if (isConfig(options)) return false;
|
|
25
|
-
if (options.type !== "ObjectExpression") return void 0;
|
|
26
|
-
let loader = false;
|
|
27
|
-
for (const property of options.properties) {
|
|
28
|
-
if (property.type === "SpreadElement") {
|
|
29
|
-
if (!isConfig(property.argument)) return void 0;
|
|
30
|
-
continue;
|
|
31
|
-
}
|
|
32
|
-
const name = getPropertyName(property);
|
|
33
|
-
if (name === void 0) return void 0;
|
|
34
|
-
if (name === "loadTranslations") loader = true;
|
|
35
|
-
}
|
|
36
|
-
return loader;
|
|
37
|
-
}
|
|
38
7
|
function getRouterLines(router, { appDirectory, configFilepath }, loaderExport, { quote, semi }) {
|
|
39
8
|
const configImport = toRelativeImport(path.dirname(path.join(appDirectory, router.path)), path.resolve(appDirectory, configFilepath));
|
|
40
9
|
const importFrom = (bindings, source) => `import ${bindings} from ${quote}${source}${quote}${semi}`;
|
|
@@ -52,14 +21,13 @@ function getStorageAction(router, ctx, loaderExport, loaderPassed) {
|
|
|
52
21
|
quote: "'",
|
|
53
22
|
semi: ""
|
|
54
23
|
});
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
};
|
|
24
|
+
return getStorageChangeAction(router, ctx, loaderPassed, {
|
|
25
|
+
call: lines.at(-1),
|
|
26
|
+
loaderImport: loaderExport ? lines.find((line) => line.endsWith("'./loadTranslations'")) : void 0,
|
|
27
|
+
docsUrl: DOCS_URL
|
|
28
|
+
});
|
|
61
29
|
}
|
|
62
30
|
//#endregion
|
|
63
|
-
export {
|
|
31
|
+
export { getRouterLines, getStorageAction };
|
|
64
32
|
|
|
65
33
|
//# sourceMappingURL=router.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/router.ts"],"sourcesContent":["// src/router.tsx: the initializeGT call and its translation loader.\nimport
|
|
1
|
+
{"version":3,"file":"router.js","names":["shared.getStorageChangeAction"],"sources":["../../../../src/setup/buildTools/tanstackStart/router.ts"],"sourcesContent":["// src/router.tsx: the initializeGT call and its translation loader.\nimport path from 'node:path';\nimport { Libraries } from '../../../types/libraries.js';\nimport { toRelativeImport, type ViteLoaderExport } from '../../setupViteSPA.js';\nimport type { BuildToolContext, ManualAction } from '../index.js';\nimport type { CodeStyle } from '../shared/edits.js';\nimport * as shared from '../shared/initializeGT.js';\nimport type { SourceFile } from '../shared/source.js';\nimport { DOCS_URL } from './source.js';\n\nexport function getRouterLines(\n router: SourceFile,\n { appDirectory, configFilepath }: BuildToolContext,\n loaderExport: ViteLoaderExport,\n { quote, semi }: Pick<CodeStyle, 'quote' | 'semi'>\n): string[] {\n const configImport = toRelativeImport(\n path.dirname(path.join(appDirectory, router.path)),\n path.resolve(appDirectory, configFilepath)\n );\n const importFrom = (bindings: string, source: string) =>\n `import ${bindings} from ${quote}${source}${quote}${semi}`;\n return [\n importFrom('{ initializeGT }', Libraries.GT_TANSTACK_START),\n importFrom('gtConfig', configImport),\n ...(loaderExport\n ? [\n importFrom(\n loaderExport === 'default'\n ? 'loadTranslations'\n : '{ loadTranslations }',\n './loadTranslations'\n ),\n ]\n : []),\n '',\n `initializeGT(${loaderExport ? '{ ...gtConfig, loadTranslations }' : 'gtConfig'})${semi}`,\n ];\n}\n\n/** The initializeGT change for a router whose storage no longer matches. */\nexport function getStorageAction(\n router: SourceFile,\n ctx: BuildToolContext,\n loaderExport: ViteLoaderExport,\n loaderPassed: boolean\n): ManualAction {\n const lines = getRouterLines(router, ctx, loaderExport, {\n quote: \"'\",\n semi: '',\n });\n const call = lines.at(-1)!;\n const loaderImport = loaderExport\n ? lines.find((line) => line.endsWith(\"'./loadTranslations'\"))\n : undefined;\n return shared.getStorageChangeAction(router, ctx, loaderPassed, {\n call,\n loaderImport,\n docsUrl: DOCS_URL,\n });\n}\n"],"mappings":";;;;;;AAUA,SAAgB,eACd,QACA,EAAE,cAAc,kBAChB,cACA,EAAE,OAAO,QACC;CACV,MAAM,eAAe,iBACnB,KAAK,QAAQ,KAAK,KAAK,cAAc,OAAO,KAAK,CAAC,EAClD,KAAK,QAAQ,cAAc,eAAe,CAC3C;CACD,MAAM,cAAc,UAAkB,WACpC,UAAU,SAAS,QAAQ,QAAQ,SAAS,QAAQ;AACtD,QAAO;EACL,WAAW,oBAAA,oBAAgD;EAC3D,WAAW,YAAY,aAAa;EACpC,GAAI,eACA,CACE,WACE,iBAAiB,YACb,qBACA,wBACJ,qBACD,CACF,GACD,EAAE;EACN;EACA,gBAAgB,eAAe,sCAAsC,WAAW,GAAG;EACpF;;;AAIH,SAAgB,iBACd,QACA,KACA,cACA,cACc;CACd,MAAM,QAAQ,eAAe,QAAQ,KAAK,cAAc;EACtD,OAAO;EACP,MAAM;EACP,CAAC;AAKF,QAAOA,uBAA8B,QAAQ,KAAK,cAAc;EAC9D,MALW,MAAM,GAAG,GAKpB;EACA,cALmB,eACjB,MAAM,MAAM,SAAS,KAAK,SAAS,uBAAuB,CAAC,GAC3D,KAAA;EAIF,SAAS;EACV,CAAC"}
|
|
@@ -1,18 +1,10 @@
|
|
|
1
1
|
import { DEFAULT_VITE_TRANSLATIONS_DIR } from "../../utils/constants.js";
|
|
2
2
|
import { inspectViteSPA, setupViteSPA, writeViteLoader } from "../setupViteSPA.js";
|
|
3
|
+
import { getLoaderUpdateActions } from "./shared/loader.js";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import fs from "node:fs";
|
|
5
6
|
//#region src/setup/buildTools/vite.ts
|
|
6
7
|
const VITE_LOADER_FILE = "src/loadTranslations.ts";
|
|
7
|
-
/** A loader left unchanged may not read the newly chosen directory. */
|
|
8
|
-
function loaderUpdateActions(translationsDir, previousTranslationsDir, custom) {
|
|
9
|
-
if (translationsDir === previousTranslationsDir) return [];
|
|
10
|
-
const fix = `Update ${custom ? "your custom " : ""}${VITE_LOADER_FILE} to load translations from ${translationsDir}`;
|
|
11
|
-
return [{
|
|
12
|
-
whatHappened: custom ? `Your custom ${VITE_LOADER_FILE} was left unchanged, but translations now go to ${translationsDir}` : `${VITE_LOADER_FILE} was left unchanged because the React setup was skipped, but translations now go to ${translationsDir}`,
|
|
13
|
-
fix
|
|
14
|
-
}];
|
|
15
|
-
}
|
|
16
8
|
const viteSetup = {
|
|
17
9
|
framework: "vite",
|
|
18
10
|
defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,
|
|
@@ -26,7 +18,7 @@ const viteSetup = {
|
|
|
26
18
|
async syncLoader({ appDirectory, defaultLocale, locales, translationsDir, previousTranslationsDir, keepAppSource }) {
|
|
27
19
|
if (keepAppSource) return {
|
|
28
20
|
steps: [],
|
|
29
|
-
manualActions: fs.existsSync(path.join(appDirectory, "src/loadTranslations.ts")) ?
|
|
21
|
+
manualActions: fs.existsSync(path.join(appDirectory, "src/loadTranslations.ts")) ? getLoaderUpdateActions(VITE_LOADER_FILE, translationsDir, previousTranslationsDir, false) : []
|
|
30
22
|
};
|
|
31
23
|
const loader = await writeViteLoader({
|
|
32
24
|
appDirectory,
|
|
@@ -38,7 +30,7 @@ const viteSetup = {
|
|
|
38
30
|
});
|
|
39
31
|
return {
|
|
40
32
|
steps: loader === "updated" ? [`updated ${VITE_LOADER_FILE}`] : [],
|
|
41
|
-
manualActions: loader === "custom" ?
|
|
33
|
+
manualActions: loader === "custom" ? getLoaderUpdateActions(VITE_LOADER_FILE, translationsDir, previousTranslationsDir, true) : []
|
|
42
34
|
};
|
|
43
35
|
},
|
|
44
36
|
async apply(ctx) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../../../src/setup/buildTools/vite.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../utils/constants.js';\nimport {\n inspectViteSPA,\n setupViteSPA,\n writeViteLoader,\n} from '../setupViteSPA.js';\nimport type { BuildToolSetup
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../../../src/setup/buildTools/vite.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../utils/constants.js';\nimport {\n inspectViteSPA,\n setupViteSPA,\n writeViteLoader,\n} from '../setupViteSPA.js';\nimport type { BuildToolSetup } from './index.js';\nimport { getLoaderUpdateActions } from './shared/loader.js';\n\nexport const VITE_LOADER_FILE = 'src/loadTranslations.ts';\n\nexport const viteSetup: BuildToolSetup = {\n framework: 'vite',\n defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,\n initializer: 'initializeGTSPA',\n ownsLoader: true,\n skipsGTInstall: (isUsingGT) => isUsingGT,\n devCredentialsOption: '--live-translations',\n async preflight(appDirectory) {\n await inspectViteSPA(appDirectory);\n },\n // Configure keeps an existing loader in sync; init leaves application\n // source to the person.\n async syncLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n keepAppSource,\n }) {\n if (keepAppSource) {\n return {\n steps: [],\n manualActions: fs.existsSync(path.join(appDirectory, VITE_LOADER_FILE))\n ? getLoaderUpdateActions(\n VITE_LOADER_FILE,\n translationsDir,\n previousTranslationsDir,\n false\n )\n : [],\n };\n }\n const loader = await writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create: false,\n });\n return {\n steps: loader === 'updated' ? [`updated ${VITE_LOADER_FILE}`] : [],\n manualActions:\n loader === 'custom'\n ? getLoaderUpdateActions(\n VITE_LOADER_FILE,\n translationsDir,\n previousTranslationsDir,\n true\n )\n : [],\n };\n },\n async apply(ctx) {\n const { manualAction } = await setupViteSPA(ctx);\n return manualAction\n ? {\n steps: [],\n manualActions: [\n {\n whatHappened: 'The existing Vite setup needs a manual review',\n fix: manualAction,\n },\n ],\n }\n : { steps: ['configured initializeGTSPA'], manualActions: [] };\n },\n};\n"],"mappings":";;;;;;AAWA,MAAa,mBAAmB;AAEhC,MAAa,YAA4B;CACvC,WAAW;CACX,wBAAwB;CACxB,aAAa;CACb,YAAY;CACZ,iBAAiB,cAAc;CAC/B,sBAAsB;CACtB,MAAM,UAAU,cAAc;AAC5B,QAAM,eAAe,aAAa;;CAIpC,MAAM,WAAW,EACf,cACA,eACA,SACA,iBACA,yBACA,iBACC;AACD,MAAI,cACF,QAAO;GACL,OAAO,EAAE;GACT,eAAe,GAAG,WAAW,KAAK,KAAK,cAAA,0BAA+B,CAAC,GACnE,uBACE,kBACA,iBACA,yBACA,MACD,GACD,EAAE;GACP;EAEH,MAAM,SAAS,MAAM,gBAAgB;GACnC;GACA;GACA;GACA;GACA;GACA,QAAQ;GACT,CAAC;AACF,SAAO;GACL,OAAO,WAAW,YAAY,CAAC,WAAW,mBAAmB,GAAG,EAAE;GAClE,eACE,WAAW,WACP,uBACE,kBACA,iBACA,yBACA,KACD,GACD,EAAE;GACT;;CAEH,MAAM,MAAM,KAAK;EACf,MAAM,EAAE,iBAAiB,MAAM,aAAa,IAAI;AAChD,SAAO,eACH;GACE,OAAO,EAAE;GACT,eAAe,CACb;IACE,cAAc;IACd,KAAK;IACN,CACF;GACF,GACD;GAAE,OAAO,CAAC,6BAA6B;GAAE,eAAe,EAAE;GAAE;;CAEnE"}
|
|
@@ -3,7 +3,7 @@ import { FrameworkObject } from '../types/index.js';
|
|
|
3
3
|
* Detects the frontend framework used in the current project.
|
|
4
4
|
*
|
|
5
5
|
* Analyzes the project structure and dependencies to identify the framework.
|
|
6
|
-
* Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → Vite → React.
|
|
6
|
+
* Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → React Router → Vite → React.
|
|
7
7
|
*
|
|
8
8
|
* For Next.js projects, further determines whether it uses App Router or Pages Router
|
|
9
9
|
* by checking for the presence of `app/` or `pages/` directories.
|
|
@@ -6,7 +6,7 @@ import fs from "node:fs";
|
|
|
6
6
|
* Detects the frontend framework used in the current project.
|
|
7
7
|
*
|
|
8
8
|
* Analyzes the project structure and dependencies to identify the framework.
|
|
9
|
-
* Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → Vite → React.
|
|
9
|
+
* Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → React Router → Vite → React.
|
|
10
10
|
*
|
|
11
11
|
* For Next.js projects, further determines whether it uses App Router or Pages Router
|
|
12
12
|
* by checking for the presence of `app/` or `pages/` directories.
|
|
@@ -49,6 +49,10 @@ async function detectFramework() {
|
|
|
49
49
|
name: "tanstack-start",
|
|
50
50
|
type: "react"
|
|
51
51
|
};
|
|
52
|
+
if (isPackageInstalled("@react-router/dev", packageJson, false, true)) return {
|
|
53
|
+
name: "react-router",
|
|
54
|
+
type: "react"
|
|
55
|
+
};
|
|
52
56
|
if (isPackageInstalled("vite", packageJson, false, true)) return {
|
|
53
57
|
name: "vite",
|
|
54
58
|
type: "react"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detectFramework.js","names":[],"sources":["../../src/setup/detectFramework.ts"],"sourcesContent":["import { FrameworkObject } from '../types/index.js';\nimport { isPackageInstalled } from '../utils/packageJson.js';\nimport { searchForPackageJson } from '../utils/packageJson.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/* ----- MAIN ----- */\n\n/**\n * Detects the frontend framework used in the current project.\n *\n * Analyzes the project structure and dependencies to identify the framework.\n * Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → Vite → React.\n *\n * For Next.js projects, further determines whether it uses App Router or Pages Router\n * by checking for the presence of `app/` or `pages/` directories.\n *\n * @returns A promise resolving to a FrameworkObject containing:\n * - `name`: The detected framework identifier (e.g., 'next-app', 'gatsby', 'react')\n * or undefined if no framework is detected\n * - `type`: The framework category (currently only 'react' for React-based frameworks)\n */\nexport async function detectFramework(): Promise<\n FrameworkObject | { name: undefined; type?: undefined }\n> {\n const packageJson = await searchForPackageJson();\n\n if (isMintlifyProject(packageJson)) {\n return { name: 'mintlify' };\n }\n\n if (!packageJson) {\n return { name: undefined };\n }\n\n // Check for Next.js first\n if (isPackageInstalled('next', packageJson, false, true)) {\n // Determine if it's App Router or Pages Router\n const cwd = process.cwd();\n const hasAppDir =\n fs.existsSync(path.join(cwd, 'app')) ||\n fs.existsSync(path.join(cwd, 'src', 'app'));\n const hasPagesDir =\n fs.existsSync(path.join(cwd, 'pages')) ||\n fs.existsSync(path.join(cwd, 'src', 'pages'));\n\n // App Router takes precedence if both exist\n if (hasAppDir) {\n return { name: 'next-app', type: 'react' };\n }\n if (hasPagesDir) {\n return { name: 'next-pages', type: 'react' };\n }\n // Default to app router for new Next.js projects\n return { name: 'next-app', type: 'react' };\n }\n\n // Check for Gatsby\n if (isPackageInstalled('gatsby', packageJson, false, true)) {\n return { name: 'gatsby', type: 'react' };\n }\n\n // Check for RedwoodJS\n if (isPackageInstalled('@redwoodjs/core', packageJson, false, true)) {\n return { name: 'redwood', type: 'react' };\n }\n\n // TanStack Start depends on Vite, so check it first\n if (isPackageInstalled('@tanstack/react-start', packageJson, false, true)) {\n return { name: 'tanstack-start', type: 'react' };\n }\n\n // Check for Vite\n if (isPackageInstalled('vite', packageJson, false, true)) {\n return { name: 'vite', type: 'react' };\n }\n\n // Check for React (generic)\n if (isPackageInstalled('react', packageJson, false, true)) {\n return { name: 'react', type: 'react' };\n }\n\n return { name: undefined };\n}\n\n// ----- HELPER FUNCTIONS ----- //\n\n/**\n * Detects if the current project is a Mintlify documentation project.\n *\n * Checks for the presence of docs.json (preferred) or mint.json (legacy) files.\n * For docs.json, validates that the $schema field contains \"mintlify.com/docs.json\".\n * Rejects projects with Next.js config files to avoid misclassification.\n *\n * @param _packageJson - The parsed package.json object (not used for Mintlify detection,\n * but kept for API consistency with other detection functions)\n * @returns True if the project is identified as a Mintlify project, false otherwise\n */\nexport function isMintlifyProject(\n _packageJson: Record<string, unknown> | null\n): boolean {\n const cwd = process.cwd();\n\n // Check for Next.js config files - if present, this is not a Mintlify project\n const nextConfigFiles = [\n 'next.config.js',\n 'next.config.ts',\n 'next.config.mjs',\n 'next.config.cjs',\n ];\n\n for (const configFile of nextConfigFiles) {\n if (fs.existsSync(path.join(cwd, configFile))) {\n return false;\n }\n }\n\n // Check for docs.json (preferred format)\n const docsJsonPath = path.join(cwd, 'docs.json');\n if (fs.existsSync(docsJsonPath)) {\n try {\n const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8'));\n // Validate the $schema field contains mintlify.com/docs.json\n if (\n docsJson.$schema &&\n docsJson.$schema.includes('mintlify.com/docs.json')\n ) {\n return true;\n }\n } catch {\n return false;\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBA,eAAsB,kBAEpB;CACA,MAAM,cAAc,MAAM,sBAAsB;AAEhD,KAAI,kBAAkB,YAAY,CAChC,QAAO,EAAE,MAAM,YAAY;AAG7B,KAAI,CAAC,YACH,QAAO,EAAE,MAAM,KAAA,GAAW;AAI5B,KAAI,mBAAmB,QAAQ,aAAa,OAAO,KAAK,EAAE;EAExD,MAAM,MAAM,QAAQ,KAAK;EACzB,MAAM,YACJ,GAAG,WAAW,KAAK,KAAK,KAAK,MAAM,CAAC,IACpC,GAAG,WAAW,KAAK,KAAK,KAAK,OAAO,MAAM,CAAC;EAC7C,MAAM,cACJ,GAAG,WAAW,KAAK,KAAK,KAAK,QAAQ,CAAC,IACtC,GAAG,WAAW,KAAK,KAAK,KAAK,OAAO,QAAQ,CAAC;AAG/C,MAAI,UACF,QAAO;GAAE,MAAM;GAAY,MAAM;GAAS;AAE5C,MAAI,YACF,QAAO;GAAE,MAAM;GAAc,MAAM;GAAS;AAG9C,SAAO;GAAE,MAAM;GAAY,MAAM;GAAS;;AAI5C,KAAI,mBAAmB,UAAU,aAAa,OAAO,KAAK,CACxD,QAAO;EAAE,MAAM;EAAU,MAAM;EAAS;AAI1C,KAAI,mBAAmB,mBAAmB,aAAa,OAAO,KAAK,CACjE,QAAO;EAAE,MAAM;EAAW,MAAM;EAAS;AAI3C,KAAI,mBAAmB,yBAAyB,aAAa,OAAO,KAAK,CACvE,QAAO;EAAE,MAAM;EAAkB,MAAM;EAAS;
|
|
1
|
+
{"version":3,"file":"detectFramework.js","names":[],"sources":["../../src/setup/detectFramework.ts"],"sourcesContent":["import { FrameworkObject } from '../types/index.js';\nimport { isPackageInstalled } from '../utils/packageJson.js';\nimport { searchForPackageJson } from '../utils/packageJson.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/* ----- MAIN ----- */\n\n/**\n * Detects the frontend framework used in the current project.\n *\n * Analyzes the project structure and dependencies to identify the framework.\n * Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → React Router → Vite → React.\n *\n * For Next.js projects, further determines whether it uses App Router or Pages Router\n * by checking for the presence of `app/` or `pages/` directories.\n *\n * @returns A promise resolving to a FrameworkObject containing:\n * - `name`: The detected framework identifier (e.g., 'next-app', 'gatsby', 'react')\n * or undefined if no framework is detected\n * - `type`: The framework category (currently only 'react' for React-based frameworks)\n */\nexport async function detectFramework(): Promise<\n FrameworkObject | { name: undefined; type?: undefined }\n> {\n const packageJson = await searchForPackageJson();\n\n if (isMintlifyProject(packageJson)) {\n return { name: 'mintlify' };\n }\n\n if (!packageJson) {\n return { name: undefined };\n }\n\n // Check for Next.js first\n if (isPackageInstalled('next', packageJson, false, true)) {\n // Determine if it's App Router or Pages Router\n const cwd = process.cwd();\n const hasAppDir =\n fs.existsSync(path.join(cwd, 'app')) ||\n fs.existsSync(path.join(cwd, 'src', 'app'));\n const hasPagesDir =\n fs.existsSync(path.join(cwd, 'pages')) ||\n fs.existsSync(path.join(cwd, 'src', 'pages'));\n\n // App Router takes precedence if both exist\n if (hasAppDir) {\n return { name: 'next-app', type: 'react' };\n }\n if (hasPagesDir) {\n return { name: 'next-pages', type: 'react' };\n }\n // Default to app router for new Next.js projects\n return { name: 'next-app', type: 'react' };\n }\n\n // Check for Gatsby\n if (isPackageInstalled('gatsby', packageJson, false, true)) {\n return { name: 'gatsby', type: 'react' };\n }\n\n // Check for RedwoodJS\n if (isPackageInstalled('@redwoodjs/core', packageJson, false, true)) {\n return { name: 'redwood', type: 'react' };\n }\n\n // TanStack Start depends on Vite, so check it first\n if (isPackageInstalled('@tanstack/react-start', packageJson, false, true)) {\n return { name: 'tanstack-start', type: 'react' };\n }\n\n // React Router framework apps (e.g. Shopify Hydrogen) depend on Vite, so check them first\n // Detect @react-router/dev (not react-router) since plain Vite apps can install react-router\n if (isPackageInstalled('@react-router/dev', packageJson, false, true)) {\n return { name: 'react-router', type: 'react' };\n }\n\n // Check for Vite\n if (isPackageInstalled('vite', packageJson, false, true)) {\n return { name: 'vite', type: 'react' };\n }\n\n // Check for React (generic)\n if (isPackageInstalled('react', packageJson, false, true)) {\n return { name: 'react', type: 'react' };\n }\n\n return { name: undefined };\n}\n\n// ----- HELPER FUNCTIONS ----- //\n\n/**\n * Detects if the current project is a Mintlify documentation project.\n *\n * Checks for the presence of docs.json (preferred) or mint.json (legacy) files.\n * For docs.json, validates that the $schema field contains \"mintlify.com/docs.json\".\n * Rejects projects with Next.js config files to avoid misclassification.\n *\n * @param _packageJson - The parsed package.json object (not used for Mintlify detection,\n * but kept for API consistency with other detection functions)\n * @returns True if the project is identified as a Mintlify project, false otherwise\n */\nexport function isMintlifyProject(\n _packageJson: Record<string, unknown> | null\n): boolean {\n const cwd = process.cwd();\n\n // Check for Next.js config files - if present, this is not a Mintlify project\n const nextConfigFiles = [\n 'next.config.js',\n 'next.config.ts',\n 'next.config.mjs',\n 'next.config.cjs',\n ];\n\n for (const configFile of nextConfigFiles) {\n if (fs.existsSync(path.join(cwd, configFile))) {\n return false;\n }\n }\n\n // Check for docs.json (preferred format)\n const docsJsonPath = path.join(cwd, 'docs.json');\n if (fs.existsSync(docsJsonPath)) {\n try {\n const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8'));\n // Validate the $schema field contains mintlify.com/docs.json\n if (\n docsJson.$schema &&\n docsJson.$schema.includes('mintlify.com/docs.json')\n ) {\n return true;\n }\n } catch {\n return false;\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBA,eAAsB,kBAEpB;CACA,MAAM,cAAc,MAAM,sBAAsB;AAEhD,KAAI,kBAAkB,YAAY,CAChC,QAAO,EAAE,MAAM,YAAY;AAG7B,KAAI,CAAC,YACH,QAAO,EAAE,MAAM,KAAA,GAAW;AAI5B,KAAI,mBAAmB,QAAQ,aAAa,OAAO,KAAK,EAAE;EAExD,MAAM,MAAM,QAAQ,KAAK;EACzB,MAAM,YACJ,GA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W,KAAK,MAAM,GAAG,aAAa,cAAc,QAAQ,CAAC;AAEnE,MACE,SAAS,WACT,SAAS,QAAQ,SAAS,yBAAyB,CAEnD,QAAO;SAEH;AACN,SAAO;;AAIX,QAAO"}
|
|
@@ -3,6 +3,7 @@ import { promptConfirm, promptSelect, promptText } from "../console/logging.js";
|
|
|
3
3
|
import { createUserAuthError } from "../auth/errors.js";
|
|
4
4
|
import { api } from "../utils/api.js";
|
|
5
5
|
import { setCredentials } from "../utils/credentials.js";
|
|
6
|
+
import { envFiles } from "../utils/loadEnv.js";
|
|
6
7
|
import { loginInteractively } from "../auth/interactiveLogin.js";
|
|
7
8
|
import { OnboardingError } from "./onboarding.js";
|
|
8
9
|
import chalk from "chalk";
|
|
@@ -40,16 +41,48 @@ function noAccessibleOrgError(dashboardUrl) {
|
|
|
40
41
|
fix: `Create an organization in the dashboard ${dashboardUrl} or ask an admin for access, then rerun the setup wizard`
|
|
41
42
|
});
|
|
42
43
|
}
|
|
43
|
-
|
|
44
|
+
/**
|
|
45
|
+
* The API client sends GT_API_KEY instead of the sign-in whenever it is set,
|
|
46
|
+
* so signing in alone cannot fix a denial; GT_API_KEY has to go first.
|
|
47
|
+
*/
|
|
48
|
+
function apiKeyDeniedGuidance(created, permission) {
|
|
49
|
+
return {
|
|
50
|
+
why: `GT_API_KEY is set, so setup used that key instead of your sign-in, and creating ${created} requires ${permission}`,
|
|
51
|
+
fix: `Remove GT_API_KEY from your shell and from ${envFiles.join(", ")}, then rerun the setup wizard to sign in`,
|
|
52
|
+
wayOut: `set GT_API_KEY to an organization key with ${permission}`
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function projectCreationDeniedError(orgId, usingApiKey, error) {
|
|
44
56
|
return createDiagnosticMessage({
|
|
45
57
|
source: "gt",
|
|
46
58
|
severity: "Error",
|
|
47
59
|
whatHappened: `Project creation was denied for organization ${orgId}`,
|
|
48
|
-
|
|
49
|
-
|
|
60
|
+
...usingApiKey ? apiKeyDeniedGuidance("a project", "org:projects:create") : {
|
|
61
|
+
why: "listing an organization does not confirm permission to create projects in it",
|
|
62
|
+
fix: "Ask an organization admin for org:projects:create, or use credentials that have that permission for this organization"
|
|
63
|
+
},
|
|
50
64
|
details: formatDiagnosticErrorDetails(error)
|
|
51
65
|
});
|
|
52
66
|
}
|
|
67
|
+
function keyCreationDeniedError(projectId, usingApiKey, error) {
|
|
68
|
+
return createDiagnosticMessage({
|
|
69
|
+
source: "gt",
|
|
70
|
+
severity: "Error",
|
|
71
|
+
whatHappened: `Development key creation was denied for project ${projectId}`,
|
|
72
|
+
...usingApiKey ? apiKeyDeniedGuidance("a key", "project:api_keys:write") : {
|
|
73
|
+
why: "creating a key requires project:api_keys:write for this project",
|
|
74
|
+
fix: "Ask a project admin for project:api_keys:write, then rerun the setup wizard"
|
|
75
|
+
},
|
|
76
|
+
details: formatDiagnosticErrorDetails(error)
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/** Replaces a 403 with setup guidance; other failures keep their own error. */
|
|
80
|
+
function explainForbidden(diagnostic) {
|
|
81
|
+
return (error) => {
|
|
82
|
+
if (!(error instanceof ApiError) || error.code !== 403) throw error;
|
|
83
|
+
throw new OnboardingError(diagnostic(error));
|
|
84
|
+
};
|
|
85
|
+
}
|
|
53
86
|
const noProjectChosenError = createDiagnosticMessage({
|
|
54
87
|
source: "gt",
|
|
55
88
|
severity: "Error",
|
|
@@ -134,6 +167,7 @@ async function resolveDevelopmentProject(session, settings, options, cwd = proce
|
|
|
134
167
|
* .env.local first; the key is never printed.
|
|
135
168
|
*/
|
|
136
169
|
async function provisionDevelopmentCredentials(session, project, settings, framework, cwd = process.cwd()) {
|
|
170
|
+
const usingApiKey = Boolean(settings.apiKey);
|
|
137
171
|
let projectId;
|
|
138
172
|
let projectName;
|
|
139
173
|
if ("id" in project) {
|
|
@@ -144,10 +178,7 @@ async function provisionDevelopmentCredentials(session, project, settings, frame
|
|
|
144
178
|
const { project: created } = await api.createProject(orgId, {
|
|
145
179
|
name,
|
|
146
180
|
defaultLocale: settings.defaultLocale
|
|
147
|
-
}).catch((error) =>
|
|
148
|
-
if (!(error instanceof ApiError) || error.code !== 403) throw error;
|
|
149
|
-
throw new OnboardingError(projectCreationDeniedError(orgId, error));
|
|
150
|
-
});
|
|
181
|
+
}).catch(explainForbidden((error) => projectCreationDeniedError(orgId, usingApiKey, error)));
|
|
151
182
|
logger.info(`Created ${created.name} (${created.id})`);
|
|
152
183
|
session.step(`created project ${created.id}`);
|
|
153
184
|
projectId = created.id;
|
|
@@ -156,7 +187,7 @@ async function provisionDevelopmentCredentials(session, project, settings, frame
|
|
|
156
187
|
const { apiKey } = await api.createProjectApiKey(projectId, {
|
|
157
188
|
name: DEVELOPMENT_KEY_NAME,
|
|
158
189
|
permissions: [ProjectApiKeyPermission["PROJECT:TRANSLATIONS:GENERATE"]]
|
|
159
|
-
});
|
|
190
|
+
}).catch(explainForbidden((error) => keyCreationDeniedError(projectId, usingApiKey, error)));
|
|
160
191
|
session.step("created a development key");
|
|
161
192
|
await setCredentials({
|
|
162
193
|
projectId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"developmentCredentials.js","names":[],"sources":["../../src/setup/developmentCredentials.ts"],"sourcesContent":["import path from 'node:path';\nimport chalk from 'chalk';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { ApiError } from 'generaltranslation/errors';\nimport { logger } from '../console/logger.js';\nimport { promptConfirm, promptSelect, promptText } from '../console/logging.js';\nimport type { Settings, SupportedFrameworks } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { setCredentials } from '../utils/credentials.js';\nimport { createUserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { OnboardingError, type OnboardingSession } from './onboarding.js';\n\nconst DEVELOPMENT_KEY_NAME = 'Development key (gt init)';\n\n/** .env.local never reaches production; the runtime key there is set on the host. */\nexport function productionRuntimeKeyGuidance(dashboardUrl: string): string {\n return `${chalk.dim('For runtime translation in production, create an API key in the dashboard')} ${chalk.cyan(dashboardUrl)} ${chalk.dim('and set GT_API_KEY and GT_PROJECT_ID in your hosting environment.')}`;\n}\n\n/**\n * Interactive setup keeps the browser login with its device fallback;\n * noninteractive setup always shows a device code (and emits it as a JSON\n * event) and waits for a person to approve it, without opening a browser.\n */\nexport async function signInForSetup(\n session: OnboardingSession,\n baseUrl: string | undefined\n): Promise<void> {\n try {\n await loginInteractively(baseUrl, session.interactive, (deviceCode) =>\n session.emit({ type: 'authorization_required', ...deviceCode })\n );\n } catch (error) {\n throw new OnboardingError(createUserAuthError('Sign in failed', error));\n }\n logger.message('You are now signed in.');\n}\n\ntype ProjectChoice = Awaited<ReturnType<typeof api.listProjects>>[number];\n\n/** An existing project, or the inputs for creating one. */\nexport type DevelopmentProject =\n | { id: string; name?: string }\n | { create: { orgId: string; name: string } };\n\nexport type DevelopmentProjectOptions = {\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n};\n\nfunction noAccessibleOrgError(dashboardUrl: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No accessible organizations were found',\n fix: `Create an organization in the dashboard ${dashboardUrl} or ask an admin for access, then rerun the setup wizard`,\n });\n}\n\nfunction projectCreationDeniedError(orgId: string, error: unknown): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Project creation was denied for organization ${orgId}`,\n why: 'Listing an organization does not confirm permission to create projects in it',\n fix: 'Ask an organization admin for org:projects:create, or use credentials that have that permission for this organization',\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst noProjectChosenError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No project was chosen for the development credentials',\n reassurance: 'No project files were changed',\n fix: 'Rerun with --project-id <id> or --create-project, or skip them with --no-dev-credentials',\n});\n\nasync function resolveNewProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string\n): Promise<DevelopmentProject | undefined> {\n // Discovery lists accessible organizations, not creation permissions.\n // The API enforces creation permission when provisioning the project.\n const orgs = await api.listOrgs();\n if (orgs.length === 0) {\n throw new OnboardingError(noAccessibleOrgError(settings.dashboardUrl));\n }\n if (options.orgId && !orgs.some((org) => org.id === options.orgId)) {\n session.reject(\n `--org-id ${options.orgId} is not an accessible organization`\n );\n }\n const orgId = await session.answer('--org-id', {\n explicit: options.orgId,\n // One organization is not a choice between options.\n configured: orgs.length === 1 ? orgs[0].id : undefined,\n ask: () =>\n promptSelect({\n message: 'Which organization should own the new project?',\n options: orgs.map((org) => ({ value: org.id, label: org.name })),\n }),\n });\n const name = await session.answer('--project-name', {\n explicit: options.projectName?.trim() || undefined,\n ask: async () =>\n (\n await promptText({\n message: 'What should the project be called?',\n defaultValue: path.basename(cwd),\n })\n ).trim() || path.basename(cwd),\n });\n return orgId && name ? { create: { orgId, name } } : undefined;\n}\n\n/**\n * Records project inputs a noninteractive run is missing, before signing in,\n * so it never waits for approval only to fail on a missing flag.\n */\nexport function checkDevelopmentProjectInputs(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n /** Where settings.projectId came from, so a person can remove it. */\n projectIdSource: string\n): void {\n if (settings.projectId && options.createProject) {\n session.reject(\n `--create-project cannot be combined with project ${settings.projectId} from ${projectIdSource}; remove --create-project to keep using it, or remove the project ID from ${projectIdSource} to create a new project`\n );\n }\n if (settings.projectId || session.interactive) return;\n if (!options.createProject) {\n session.require('--project-id or --create-project');\n } else if (!options.projectName?.trim()) {\n session.require('--project-name');\n }\n}\n\n/**\n * Chooses the project for development credentials without creating anything:\n * a supplied or configured ID, explicit creation inputs, or (interactively)\n * a selection among the account's projects.\n */\nexport async function resolveDevelopmentProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string = process.cwd()\n): Promise<DevelopmentProject | undefined> {\n if (settings.projectId) return { id: settings.projectId };\n if (options.createProject) {\n return resolveNewProject(session, settings, options, cwd);\n }\n const projects = await api.listProjects();\n if (projects.length === 0) {\n // Creating a project is its own choice, separate from creating a key.\n const create = await session.answer('--project-id or --create-project', {\n ask: () =>\n promptConfirm({\n message: 'No projects found for your account. Create a new project?',\n defaultValue: true,\n }),\n });\n if (create === false) throw new OnboardingError(noProjectChosenError);\n return create\n ? resolveNewProject(session, settings, options, cwd)\n : undefined;\n }\n const choice = await session.answer<ProjectChoice | null>(\n '--project-id or --create-project',\n {\n ask: () =>\n promptSelect<ProjectChoice | null>({\n message: 'Which project should this app use?',\n options: [\n ...projects.map((project) => ({\n value: project,\n label: project.name,\n hint: project.orgName,\n })),\n { value: null, label: 'Create a new project' },\n ],\n }),\n }\n );\n if (choice === undefined) return undefined;\n return choice\n ? { id: choice.id, name: choice.name }\n : resolveNewProject(session, settings, options, cwd);\n}\n\n/**\n * Creates the chosen project if needed, mints a development key limited to\n * runtime translation, and saves both to .env.local. Callers inspect\n * .env.local first; the key is never printed.\n */\nexport async function provisionDevelopmentCredentials(\n session: OnboardingSession,\n project: DevelopmentProject,\n settings: Settings,\n framework: SupportedFrameworks | undefined,\n cwd: string = process.cwd()\n): Promise<void> {\n let projectId: string;\n let projectName: string | undefined;\n if ('id' in project) {\n projectId = project.id;\n projectName = project.name;\n } else {\n const { orgId, name } = project.create;\n const { project: created } = await api\n .createProject(orgId, { name, defaultLocale: settings.defaultLocale })\n .catch((error: unknown) => {\n if (!(error instanceof ApiError) || error.code !== 403) throw error;\n throw new OnboardingError(projectCreationDeniedError(orgId, error));\n });\n logger.info(`Created ${created.name} (${created.id})`);\n session.step(`created project ${created.id}`);\n projectId = created.id;\n projectName = created.name;\n }\n const { apiKey } = await api.createProjectApiKey(projectId, {\n name: DEVELOPMENT_KEY_NAME,\n permissions: [ProjectApiKeyPermission['PROJECT:TRANSLATIONS:GENERATE']],\n });\n session.step('created a development key');\n await setCredentials({ projectId, apiKey: apiKey.key }, framework, cwd);\n session.step('saved development credentials to .env.local');\n const projectLabel = projectName\n ? `${projectName} (${projectId})`\n : projectId;\n logger.success(\n `Created development key \"${apiKey.name}\" for project ${projectLabel} and saved both to ${chalk.cyan('.env.local')}.`\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,uBAAuB;;AAG7B,SAAgB,6BAA6B,cAA8B;AACzE,QAAO,GAAG,MAAM,IAAI,4EAA4E,CAAC,GAAG,MAAM,KAAK,aAAa,CAAC,GAAG,MAAM,IAAI,oEAAoE;;;;;;;AAQhN,eAAsB,eACpB,SACA,SACe;AACf,KAAI;AACF,QAAM,mBAAmB,SAAS,QAAQ,cAAc,eACtD,QAAQ,KAAK;GAAE,MAAM;GAA0B,GAAG;GAAY,CAAC,CAChE;UACM,OAAO;AACd,QAAM,IAAI,gBAAgB,oBAAoB,kBAAkB,MAAM,CAAC;;AAEzE,QAAO,QAAQ,yBAAyB;;AAgB1C,SAAS,qBAAqB,cAA8B;AAC1D,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc;EACd,KAAK,2CAA2C,aAAa;EAC9D,CAAC;;AAGJ,SAAS,2BAA2B,OAAe,OAAwB;AACzE,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc,gDAAgD;EAC9D,KAAK;EACL,KAAK;EACL,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,uBAAuB,wBAAwB;CACnD,QAAQ;CACR,UAAU;CACV,cAAc;CACd,aAAa;CACb,KAAK;CACN,CAAC;AAEF,eAAe,kBACb,SACA,UACA,SACA,KACyC;CAGzC,MAAM,OAAO,MAAM,IAAI,UAAU;AACjC,KAAI,KAAK,WAAW,EAClB,OAAM,IAAI,gBAAgB,qBAAqB,SAAS,aAAa,CAAC;AAExE,KAAI,QAAQ,SAAS,CAAC,KAAK,MAAM,QAAQ,IAAI,OAAO,QAAQ,MAAM,CAChE,SAAQ,OACN,YAAY,QAAQ,MAAM,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AAE,WAAW,IAAI;AACvE,SAAQ,KAAK,8CAA8C;CAC3D,MAAM,eAAe,cACjB,GAAG,YAAY,IAAI,UAAU,KAC7B;AACJ,QAAO,QACL,4BAA4B,OAAO,KAAK,gBAAgB,aAAa,qBAAqB,MAAM,KAAK,aAAa,CAAC,GACpH"}
|
|
1
|
+
{"version":3,"file":"developmentCredentials.js","names":[],"sources":["../../src/setup/developmentCredentials.ts"],"sourcesContent":["import path from 'node:path';\nimport chalk from 'chalk';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { ApiError } from 'generaltranslation/errors';\nimport { logger } from '../console/logger.js';\nimport { promptConfirm, promptSelect, promptText } from '../console/logging.js';\nimport type { Settings, SupportedFrameworks } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { setCredentials } from '../utils/credentials.js';\nimport { envFiles } from '../utils/loadEnv.js';\nimport { createUserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { OnboardingError, type OnboardingSession } from './onboarding.js';\n\nconst DEVELOPMENT_KEY_NAME = 'Development key (gt init)';\n\n/** .env.local never reaches production; the runtime key there is set on the host. */\nexport function productionRuntimeKeyGuidance(dashboardUrl: string): string {\n return `${chalk.dim('For runtime translation in production, create an API key in the dashboard')} ${chalk.cyan(dashboardUrl)} ${chalk.dim('and set GT_API_KEY and GT_PROJECT_ID in your hosting environment.')}`;\n}\n\n/**\n * Interactive setup keeps the browser login with its device fallback;\n * noninteractive setup always shows a device code (and emits it as a JSON\n * event) and waits for a person to approve it, without opening a browser.\n */\nexport async function signInForSetup(\n session: OnboardingSession,\n baseUrl: string | undefined\n): Promise<void> {\n try {\n await loginInteractively(baseUrl, session.interactive, (deviceCode) =>\n session.emit({ type: 'authorization_required', ...deviceCode })\n );\n } catch (error) {\n throw new OnboardingError(createUserAuthError('Sign in failed', error));\n }\n logger.message('You are now signed in.');\n}\n\ntype ProjectChoice = Awaited<ReturnType<typeof api.listProjects>>[number];\n\n/** An existing project, or the inputs for creating one. */\nexport type DevelopmentProject =\n | { id: string; name?: string }\n | { create: { orgId: string; name: string } };\n\nexport type DevelopmentProjectOptions = {\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n};\n\nfunction noAccessibleOrgError(dashboardUrl: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No accessible organizations were found',\n fix: `Create an organization in the dashboard ${dashboardUrl} or ask an admin for access, then rerun the setup wizard`,\n });\n}\n\n/**\n * The API client sends GT_API_KEY instead of the sign-in whenever it is set,\n * so signing in alone cannot fix a denial; GT_API_KEY has to go first.\n */\nfunction apiKeyDeniedGuidance(created: string, permission: string) {\n return {\n why: `GT_API_KEY is set, so setup used that key instead of your sign-in, and creating ${created} requires ${permission}`,\n fix: `Remove GT_API_KEY from your shell and from ${envFiles.join(', ')}, then rerun the setup wizard to sign in`,\n wayOut: `set GT_API_KEY to an organization key with ${permission}`,\n };\n}\n\nfunction projectCreationDeniedError(\n orgId: string,\n usingApiKey: boolean,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Project creation was denied for organization ${orgId}`,\n ...(usingApiKey\n ? apiKeyDeniedGuidance('a project', 'org:projects:create')\n : {\n why: 'listing an organization does not confirm permission to create projects in it',\n fix: 'Ask an organization admin for org:projects:create, or use credentials that have that permission for this organization',\n }),\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nfunction keyCreationDeniedError(\n projectId: string,\n usingApiKey: boolean,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Development key creation was denied for project ${projectId}`,\n ...(usingApiKey\n ? apiKeyDeniedGuidance('a key', 'project:api_keys:write')\n : {\n why: 'creating a key requires project:api_keys:write for this project',\n fix: 'Ask a project admin for project:api_keys:write, then rerun the setup wizard',\n }),\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\n/** Replaces a 403 with setup guidance; other failures keep their own error. */\nfunction explainForbidden(diagnostic: (error: unknown) => string) {\n return (error: unknown): never => {\n if (!(error instanceof ApiError) || error.code !== 403) throw error;\n throw new OnboardingError(diagnostic(error));\n };\n}\n\nconst noProjectChosenError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No project was chosen for the development credentials',\n reassurance: 'No project files were changed',\n fix: 'Rerun with --project-id <id> or --create-project, or skip them with --no-dev-credentials',\n});\n\nasync function resolveNewProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string\n): Promise<DevelopmentProject | undefined> {\n // Discovery lists accessible organizations, not creation permissions.\n // The API enforces creation permission when provisioning the project.\n const orgs = await api.listOrgs();\n if (orgs.length === 0) {\n throw new OnboardingError(noAccessibleOrgError(settings.dashboardUrl));\n }\n if (options.orgId && !orgs.some((org) => org.id === options.orgId)) {\n session.reject(\n `--org-id ${options.orgId} is not an accessible organization`\n );\n }\n const orgId = await session.answer('--org-id', {\n explicit: options.orgId,\n // One organization is not a choice between options.\n configured: orgs.length === 1 ? orgs[0].id : undefined,\n ask: () =>\n promptSelect({\n message: 'Which organization should own the new project?',\n options: orgs.map((org) => ({ value: org.id, label: org.name })),\n }),\n });\n const name = await session.answer('--project-name', {\n explicit: options.projectName?.trim() || undefined,\n ask: async () =>\n (\n await promptText({\n message: 'What should the project be called?',\n defaultValue: path.basename(cwd),\n })\n ).trim() || path.basename(cwd),\n });\n return orgId && name ? { create: { orgId, name } } : undefined;\n}\n\n/**\n * Records project inputs a noninteractive run is missing, before signing in,\n * so it never waits for approval only to fail on a missing flag.\n */\nexport function checkDevelopmentProjectInputs(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n /** Where settings.projectId came from, so a person can remove it. */\n projectIdSource: string\n): void {\n if (settings.projectId && options.createProject) {\n session.reject(\n `--create-project cannot be combined with project ${settings.projectId} from ${projectIdSource}; remove --create-project to keep using it, or remove the project ID from ${projectIdSource} to create a new project`\n );\n }\n if (settings.projectId || session.interactive) return;\n if (!options.createProject) {\n session.require('--project-id or --create-project');\n } else if (!options.projectName?.trim()) {\n session.require('--project-name');\n }\n}\n\n/**\n * Chooses the project for development credentials without creating anything:\n * a supplied or configured ID, explicit creation inputs, or (interactively)\n * a selection among the account's projects.\n */\nexport async function resolveDevelopmentProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string = process.cwd()\n): Promise<DevelopmentProject | undefined> {\n if (settings.projectId) return { id: settings.projectId };\n if (options.createProject) {\n return resolveNewProject(session, settings, options, cwd);\n }\n const projects = await api.listProjects();\n if (projects.length === 0) {\n // Creating a project is its own choice, separate from creating a key.\n const create = await session.answer('--project-id or --create-project', {\n ask: () =>\n promptConfirm({\n message: 'No projects found for your account. Create a new project?',\n defaultValue: true,\n }),\n });\n if (create === false) throw new OnboardingError(noProjectChosenError);\n return create\n ? resolveNewProject(session, settings, options, cwd)\n : undefined;\n }\n const choice = await session.answer<ProjectChoice | null>(\n '--project-id or --create-project',\n {\n ask: () =>\n promptSelect<ProjectChoice | null>({\n message: 'Which project should this app use?',\n options: [\n ...projects.map((project) => ({\n value: project,\n label: project.name,\n hint: project.orgName,\n })),\n { value: null, label: 'Create a new project' },\n ],\n }),\n }\n );\n if (choice === undefined) return undefined;\n return choice\n ? { id: choice.id, name: choice.name }\n : resolveNewProject(session, settings, options, cwd);\n}\n\n/**\n * Creates the chosen project if needed, mints a development key limited to\n * runtime translation, and saves both to .env.local. Callers inspect\n * .env.local first; the key is never printed.\n */\nexport async function provisionDevelopmentCredentials(\n session: OnboardingSession,\n project: DevelopmentProject,\n settings: Settings,\n framework: SupportedFrameworks | undefined,\n cwd: string = process.cwd()\n): Promise<void> {\n // Set exactly when the API client sends it in place of the sign-in.\n const usingApiKey = Boolean(settings.apiKey);\n let projectId: string;\n let projectName: string | undefined;\n if ('id' in project) {\n projectId = project.id;\n projectName = project.name;\n } else {\n const { orgId, name } = project.create;\n const { project: created } = await api\n .createProject(orgId, { name, defaultLocale: settings.defaultLocale })\n .catch(\n explainForbidden((error) =>\n projectCreationDeniedError(orgId, usingApiKey, error)\n )\n );\n logger.info(`Created ${created.name} (${created.id})`);\n session.step(`created project ${created.id}`);\n projectId = created.id;\n projectName = created.name;\n }\n const { apiKey } = await api\n .createProjectApiKey(projectId, {\n name: DEVELOPMENT_KEY_NAME,\n permissions: [ProjectApiKeyPermission['PROJECT:TRANSLATIONS:GENERATE']],\n })\n .catch(\n explainForbidden((error) =>\n keyCreationDeniedError(projectId, usingApiKey, error)\n )\n );\n session.step('created a development key');\n await setCredentials({ projectId, apiKey: apiKey.key }, framework, cwd);\n session.step('saved development credentials to .env.local');\n const projectLabel = projectName\n ? `${projectName} (${projectId})`\n : projectId;\n logger.success(\n `Created development key \"${apiKey.name}\" for project ${projectLabel} and saved both to ${chalk.cyan('.env.local')}.`\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAkBA,MAAM,uBAAuB;;AAG7B,SAAgB,6BAA6B,cAA8B;AACzE,QAAO,GAAG,MAAM,IAAI,4EAA4E,CAAC,GAAG,MAAM,KAAK,aAAa,CAAC,GAAG,MAAM,IAAI,oEAAoE;;;;;;;AAQhN,eAAsB,eACpB,SACA,SACe;AACf,KAAI;AACF,QAAM,mBAAmB,SAAS,QAAQ,cAAc,eACtD,QAAQ,KAAK;GAAE,MAAM;GAA0B,GAAG;GAAY,CAAC,CAChE;UACM,OAAO;AACd,QAAM,IAAI,gBAAgB,oBAAoB,kBAAkB,MAAM,CAAC;;AAEzE,QAAO,QAAQ,yBAAyB;;AAgB1C,SAAS,qBAAqB,cAA8B;AAC1D,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc;EACd,KAAK,2CAA2C,aAAa;EAC9D,CAAC;;;;;;AAOJ,SAAS,qBAAqB,SAAiB,YAAoB;AACjE,QAAO;EACL,KAAK,mFAAmF,QAAQ,YA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pH"}
|
|
@@ -8,6 +8,7 @@ function getFrameworkDisplayName(frameworkObject) {
|
|
|
8
8
|
if (frameworkObject.name === "gatsby") return "Gatsby";
|
|
9
9
|
if (frameworkObject.name === "redwood") return "RedwoodJS";
|
|
10
10
|
if (frameworkObject.name === "tanstack-start") return "TanStack Start";
|
|
11
|
+
if (frameworkObject.name === "react-router") return "React Router";
|
|
11
12
|
if (frameworkObject.type === "react") return "React";
|
|
12
13
|
return "another framework";
|
|
13
14
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"frameworkUtils.js","names":[],"sources":["../../src/setup/frameworkUtils.ts"],"sourcesContent":["import { FrameworkObject, ReactFrameworkObject } from '../types/index.js';\nimport { Libraries } from '../types/libraries.js';\n\nexport function getFrameworkDisplayName(\n frameworkObject: FrameworkObject\n): string {\n if (frameworkObject.name === 'mintlify') {\n return 'Mintlify';\n }\n if (frameworkObject.name === 'next-app') {\n return 'Next.js App Router';\n }\n if (frameworkObject.name === 'next-pages') {\n return 'Next.js Pages Router';\n }\n if (frameworkObject.name === 'vite') {\n return 'Vite + React';\n }\n if (frameworkObject.name === 'gatsby') {\n return 'Gatsby';\n }\n if (frameworkObject.name === 'redwood') {\n return 'RedwoodJS';\n }\n if (frameworkObject.name === 'tanstack-start') {\n return 'TanStack Start';\n }\n if (frameworkObject.type === 'react') {\n return 'React';\n }\n return 'another framework';\n}\n\nexport function getReactFrameworkLibrary(\n frameworkObject: ReactFrameworkObject\n): string {\n if (frameworkObject.name === 'next-app') return Libraries.GT_NEXT;\n if (frameworkObject.name === 'tanstack-start') {\n return Libraries.GT_TANSTACK_START;\n }\n return Libraries.GT_REACT;\n}\n"],"mappings":";;AAGA,SAAgB,wBACd,iBACQ;AACR,KAAI,gBAAgB,SAAS,WAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,WAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,aAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,OAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,SAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,UAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,iBAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,QAC3B,QAAO;AAET,QAAO;;AAGT,SAAgB,yBACd,iBACQ;AACR,KAAI,gBAAgB,SAAS,WAAY,QAAA;AACzC,KAAI,gBAAgB,SAAS,iBAC3B,QAAA;AAEF,QAAA"}
|
|
1
|
+
{"version":3,"file":"frameworkUtils.js","names":[],"sources":["../../src/setup/frameworkUtils.ts"],"sourcesContent":["import { FrameworkObject, ReactFrameworkObject } from '../types/index.js';\nimport { Libraries } from '../types/libraries.js';\n\nexport function getFrameworkDisplayName(\n frameworkObject: FrameworkObject\n): string {\n if (frameworkObject.name === 'mintlify') {\n return 'Mintlify';\n }\n if (frameworkObject.name === 'next-app') {\n return 'Next.js App Router';\n }\n if (frameworkObject.name === 'next-pages') {\n return 'Next.js Pages Router';\n }\n if (frameworkObject.name === 'vite') {\n return 'Vite + React';\n }\n if (frameworkObject.name === 'gatsby') {\n return 'Gatsby';\n }\n if (frameworkObject.name === 'redwood') {\n return 'RedwoodJS';\n }\n if (frameworkObject.name === 'tanstack-start') {\n return 'TanStack Start';\n }\n if (frameworkObject.name === 'react-router') {\n return 'React Router';\n }\n if (frameworkObject.type === 'react') {\n return 'React';\n }\n return 'another framework';\n}\n\nexport function getReactFrameworkLibrary(\n frameworkObject: ReactFrameworkObject\n): string {\n if (frameworkObject.name === 'next-app') return Libraries.GT_NEXT;\n if (frameworkObject.name === 'tanstack-start') {\n return Libraries.GT_TANSTACK_START;\n }\n return Libraries.GT_REACT;\n}\n"],"mappings":";;AAGA,SAAgB,wBACd,iBACQ;AACR,KAAI,gBAAgB,SAAS,WAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,WAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,aAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,OAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,SAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,UAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,iBAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,eAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,QAC3B,QAAO;AAET,QAAO;;AAGT,SAAgB,yBACd,iBACQ;AACR,KAAI,gBAAgB,SAAS,WAAY,QAAA;AACzC,KAAI,gBAAgB,SAAS,iBAC3B,QAAA;AAEF,QAAA"}
|
package/dist/setup/wizard.js
CHANGED
|
@@ -78,6 +78,10 @@ Make sure you have committed or stashed any changes. Do you want to continue?`),
|
|
|
78
78
|
value: "tanstack-start",
|
|
79
79
|
label: chalk.cyan("TanStack Start")
|
|
80
80
|
},
|
|
81
|
+
{
|
|
82
|
+
value: "react-router",
|
|
83
|
+
label: chalk.cyan("React Router")
|
|
84
|
+
},
|
|
81
85
|
{
|
|
82
86
|
value: "other",
|
|
83
87
|
label: chalk.dim("Other")
|
package/dist/setup/wizard.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wizard.js","names":[],"sources":["../../src/setup/wizard.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { detectFormatter, formatFiles } from '../hooks/postProcess.js';\nimport type { Formatter } from '../hooks/postProcess.js';\nimport { exitSync, promptConfirm, promptSelect } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport type {\n ReactFrameworkObject,\n SupportedReactFrameworks,\n} from '../types/index.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport { handleInitGT } from '../next/parse/handleInitGT.js';\nimport { getPackageJson, isPackageInstalled } from '../utils/packageJson.js';\nimport { wrapContentNext } from '../next/parse/wrapContent.js';\nimport { loadConfig } from '../fs/config/loadConfig.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport { Libraries } from '../types/libraries.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport { REACT_QUICKSTART_URL } from '../utils/constants.js';\nimport type { InitOptions, OnboardingSession } from './onboarding.js';\n\n/** Everything the React application setup will do, resolved before changes. */\nexport type ReactSetupPlan = {\n framework: SupportedReactFrameworks;\n packageJson: Record<string, unknown>;\n /** GT library to install, when it is not installed yet. */\n install?: string;\n nextConfigPath?: string;\n formatter?: Formatter;\n};\n\nconst cancelledMessage =\n 'Operation cancelled. You can re-run this wizard with: npx gt init';\n\n/**\n * Resolves whether and how to set up the React application. Returns\n * undefined when the setup is declined or an answer is still missing.\n */\nexport async function resolveReactSetup(\n session: OnboardingSession,\n options: InitOptions,\n detected: ReactFrameworkObject,\n configuredFramework?: SupportedReactFrameworks\n): Promise<ReactSetupPlan | undefined> {\n const library = getReactFrameworkLibrary(detected);\n const buildTool = getBuildToolSetup(detected.name);\n const initializer = buildTool?.initializer;\n const setupApp = await session.answer('--react-setup', {\n explicit: options.reactSetup,\n recommended: true,\n ask: async () => {\n const answer = await promptConfirm({\n message: `Would you like to install ${library} and ${initializer ? `configure ${initializer}` : 'add the GTProvider'}? See the docs for more information: ${buildTool?.docsUrl ?? REACT_QUICKSTART_URL}`,\n defaultValue: true,\n });\n // A prompted opt-in gets a last warning; flags and defaults already chose.\n if (\n answer &&\n !(await promptConfirm({\n message: chalk.yellow(\n `This wizard will configure your ${getFrameworkDisplayName(detected)} project for internationalization with GT. If your project is already using a different i18n library, this wizard may cause issues.\n\nMake sure you have committed or stashed any changes. Do you want to continue?`\n ),\n defaultValue: true,\n cancelMessage: cancelledMessage,\n }))\n ) {\n logger.info(cancelledMessage);\n return exitSync(0);\n }\n return answer;\n },\n });\n if (!setupApp) return undefined;\n\n const framework = await session.answer<SupportedReactFrameworks | 'other'>(\n '--framework',\n {\n explicit: options.framework,\n configured: configuredFramework,\n recommended: detected.name,\n ask: () =>\n promptSelect<SupportedReactFrameworks | 'other'>({\n message: 'Which framework are you using?',\n options: [\n { value: 'next-app', label: chalk.blue('Next.js App Router') },\n { value: 'next-pages', label: chalk.green('Next.js Pages Router') },\n { value: 'vite', label: chalk.cyan('Vite + React') },\n { value: 'gatsby', label: chalk.magenta('Gatsby') },\n { value: 'react', label: chalk.yellow('React') },\n { value: 'redwood', label: chalk.red('RedwoodJS') },\n { value: 'tanstack-start', label: chalk.cyan('TanStack Start') },\n { value: 'other', label: chalk.dim('Other') },\n ],\n defaultValue: detected.name,\n }),\n }\n );\n if (framework === 'other') {\n logger.error(\n `Sorry, the wizard doesn't currently support other React frameworks.\nPlease let us know what you would like to see added at https://github.com/generaltranslation/gt/issues`\n );\n return exitSync(0);\n }\n if (!framework) return undefined;\n\n const packageJson = await getPackageJson();\n if (!packageJson) {\n session.reject(\n 'No package.json found in the current directory. Run this command from the root of your project'\n );\n return undefined;\n }\n const install = getReactFrameworkLibrary({ name: framework, type: 'react' });\n const plan: ReactSetupPlan = {\n framework,\n packageJson,\n install: isPackageInstalled(install, packageJson) ? undefined : install,\n };\n\n if (framework === 'next-app') {\n plan.nextConfigPath = findFilepath([\n './next.config.js',\n './next.config.ts',\n './next.config.mjs',\n './next.config.mts',\n ]);\n if (!plan.nextConfigPath) {\n session.reject('No next.config.[js|ts|mjs|mts] file found');\n }\n const formatter = await detectFormatter();\n if (\n formatter &&\n (await session.answer('--format', {\n explicit: options.format,\n recommended: true,\n ask: () =>\n promptConfirm({\n message: `Would you like the wizard to auto-format the modified files? ${chalk.dim(\n `(${formatter})`\n )}`,\n defaultValue: true,\n }),\n }))\n ) {\n plan.formatter = formatter;\n }\n }\n return plan;\n}\n\n/** Wraps Next.js App Router content and adds withGTConfig(); installs happen first. */\nexport async function executeReactSetup(\n session: OnboardingSession,\n plan: ReactSetupPlan,\n options: InitOptions\n): Promise<void> {\n if (plan.framework !== 'next-app' || !plan.nextConfigPath) return;\n\n const errors: string[] = [];\n const warnings: string[] = [];\n const spinner = logger.createSpinner();\n spinner.start('Wrapping JSX content with <T> tags...');\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated } = await wrapContentNext(\n {\n ...options,\n disableIds: true,\n disableFormatting: true,\n skipTs: true,\n addGTProvider: true,\n },\n Libraries.GT_NEXT,\n errors,\n warnings\n );\n spinner.stop(\n chalk.green(\n `Success! Updated ${chalk.bold.cyan(filesUpdated.length)} files:\\n`\n ) + filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\\n')\n );\n if (filesUpdated.length > 0) session.step('wrapped JSX content');\n\n // Add the withGTConfig() function to the next.config.js file\n const tsconfigPath = findFilepath(['tsconfig.json']);\n await handleInitGT(\n plan.nextConfigPath,\n errors,\n warnings,\n filesUpdated,\n plan.packageJson,\n tsconfigPath ? loadConfig(tsconfigPath) : undefined\n );\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow('Warnings encountered:') +\n '\\n' +\n warnings.map((warning) => `${chalk.yellow('-')} ${warning}`).join('\\n')\n );\n }\n if (errors.length > 0) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'Setup could not update some application files',\n details: errors,\n fix: 'Fix the reported files, then rerun `npx gt init`',\n })\n );\n }\n logger.step(\n chalk.green(`Added withGTConfig() to your ${plan.nextConfigPath} file.`)\n );\n session.step(`added withGTConfig() to ${plan.nextConfigPath}`);\n\n if (plan.formatter) await formatFiles(filesUpdated, plan.formatter);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,MAAM,mBACJ;;;;;AAMF,eAAsB,kBACpB,SACA,SACA,UACA,qBACqC;CACrC,MAAM,UAAU,yBAAyB,SAAS;CAClD,MAAM,YAAY,kBAAkB,SAAS,KAAK;CAClD,MAAM,cAAc,WAAW;AA4B/B,KAAI,CAAC,MA3BkB,QAAQ,OAAO,iBAAiB;EACrD,UAAU,QAAQ;EAClB,aAAa;EACb,KAAK,YAAY;GACf,MAAM,SAAS,MAAM,cAAc;IACjC,SAAS,6BAA6B,QAAQ,OAAO,cAAc,aAAa,gBAAgB,qBAAqB,uCAAuC,W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SAAS,EAClB,OAAM,IAAI,MACR,wBAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAAS;EACT,KAAK;EACN,CAAC,CACH;AAEH,QAAO,KACL,MAAM,MAAM,gCAAgC,KAAK,eAAe,QAAQ,CACzE;AACD,SAAQ,KAAK,2BAA2B,KAAK,iBAAiB;AAE9D,KAAI,KAAK,UAAW,OAAM,YAAY,cAAc,KAAK,UAAU"}
|
|
1
|
+
{"version":3,"file":"wizard.js","names":[],"sources":["../../src/setup/wizard.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { detectFormatter, formatFiles } from '../hooks/postProcess.js';\nimport type { Formatter } from '../hooks/postProcess.js';\nimport { exitSync, promptConfirm, promptSelect } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport type {\n ReactFrameworkObject,\n SupportedReactFrameworks,\n} from '../types/index.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport { handleInitGT } from '../next/parse/handleInitGT.js';\nimport { getPackageJson, isPackageInstalled } from '../utils/packageJson.js';\nimport { wrapContentNext } from '../next/parse/wrapContent.js';\nimport { loadConfig } from '../fs/config/loadConfig.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport { Libraries } from '../types/libraries.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport { REACT_QUICKSTART_URL } from '../utils/constants.js';\nimport type { InitOptions, OnboardingSession } from './onboarding.js';\n\n/** Everything the React application setup will do, resolved before changes. */\nexport type ReactSetupPlan = {\n framework: SupportedReactFrameworks;\n packageJson: Record<string, unknown>;\n /** GT library to install, when it is not installed yet. */\n install?: string;\n nextConfigPath?: string;\n formatter?: Formatter;\n};\n\nconst cancelledMessage =\n 'Operation cancelled. You can re-run this wizard with: npx gt init';\n\n/**\n * Resolves whether and how to set up the React application. Returns\n * undefined when the setup is declined or an answer is still missing.\n */\nexport async function resolveReactSetup(\n session: OnboardingSession,\n options: InitOptions,\n detected: ReactFrameworkObject,\n configuredFramework?: SupportedReactFrameworks\n): Promise<ReactSetupPlan | undefined> {\n const library = getReactFrameworkLibrary(detected);\n const buildTool = getBuildToolSetup(detected.name);\n const initializer = buildTool?.initializer;\n const setupApp = await session.answer('--react-setup', {\n explicit: options.reactSetup,\n recommended: true,\n ask: async () => {\n const answer = await promptConfirm({\n message: `Would you like to install ${library} and ${initializer ? `configure ${initializer}` : 'add the GTProvider'}? See the docs for more information: ${buildTool?.docsUrl ?? REACT_QUICKSTART_URL}`,\n defaultValue: true,\n });\n // A prompted opt-in gets a last warning; flags and defaults already chose.\n if (\n answer &&\n !(await promptConfirm({\n message: chalk.yellow(\n `This wizard will configure your ${getFrameworkDisplayName(detected)} project for internationalization with GT. If your project is already using a different i18n library, this wizard may cause issues.\n\nMake sure you have committed or stashed any changes. Do you want to continue?`\n ),\n defaultValue: true,\n cancelMessage: cancelledMessage,\n }))\n ) {\n logger.info(cancelledMessage);\n return exitSync(0);\n }\n return answer;\n },\n });\n if (!setupApp) return undefined;\n\n const framework = await session.answer<SupportedReactFrameworks | 'other'>(\n '--framework',\n {\n explicit: options.framework,\n configured: configuredFramework,\n recommended: detected.name,\n ask: () =>\n promptSelect<SupportedReactFrameworks | 'other'>({\n message: 'Which framework are you using?',\n options: [\n { value: 'next-app', label: chalk.blue('Next.js App Router') },\n { value: 'next-pages', label: chalk.green('Next.js Pages Router') },\n { value: 'vite', label: chalk.cyan('Vite + React') },\n { value: 'gatsby', label: chalk.magenta('Gatsby') },\n { value: 'react', label: chalk.yellow('React') },\n { value: 'redwood', label: chalk.red('RedwoodJS') },\n { value: 'tanstack-start', label: chalk.cyan('TanStack Start') },\n { value: 'react-router', label: chalk.cyan('React Router') },\n { value: 'other', label: chalk.dim('Other') },\n ],\n defaultValue: detected.name,\n }),\n }\n );\n if (framework === 'other') {\n logger.error(\n `Sorry, the wizard doesn't currently support other React frameworks.\nPlease let us know what you would like to see added at https://github.com/generaltranslation/gt/issues`\n );\n return exitSync(0);\n }\n if (!framework) return undefined;\n\n const packageJson = await getPackageJson();\n if (!packageJson) {\n session.reject(\n 'No package.json found in the current directory. Run this command from the root of your project'\n );\n return undefined;\n }\n const install = getReactFrameworkLibrary({ name: framework, type: 'react' });\n const plan: ReactSetupPlan = {\n framework,\n packageJson,\n install: isPackageInstalled(install, packageJson) ? undefined : install,\n };\n\n if (framework === 'next-app') {\n plan.nextConfigPath = findFilepath([\n './next.config.js',\n './next.config.ts',\n './next.config.mjs',\n './next.config.mts',\n ]);\n if (!plan.nextConfigPath) {\n session.reject('No next.config.[js|ts|mjs|mts] file found');\n }\n const formatter = await detectFormatter();\n if (\n formatter &&\n (await session.answer('--format', {\n explicit: options.format,\n recommended: true,\n ask: () =>\n promptConfirm({\n message: `Would you like the wizard to auto-format the modified files? ${chalk.dim(\n `(${formatter})`\n )}`,\n defaultValue: true,\n }),\n }))\n ) {\n plan.formatter = formatter;\n }\n }\n return plan;\n}\n\n/** Wraps Next.js App Router content and adds withGTConfig(); installs happen first. */\nexport async function executeReactSetup(\n session: OnboardingSession,\n plan: ReactSetupPlan,\n options: InitOptions\n): Promise<void> {\n if (plan.framework !== 'next-app' || !plan.nextConfigPath) return;\n\n const errors: string[] = [];\n const warnings: string[] = [];\n const spinner = logger.createSpinner();\n spinner.start('Wrapping JSX content with <T> tags...');\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated } = await wrapContentNext(\n {\n ...options,\n disableIds: true,\n disableFormatting: true,\n skipTs: true,\n addGTProvider: true,\n },\n Libraries.GT_NEXT,\n errors,\n warnings\n );\n spinner.stop(\n chalk.green(\n `Success! Updated ${chalk.bold.cyan(filesUpdated.length)} files:\\n`\n ) + filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\\n')\n );\n if (filesUpdated.length > 0) session.step('wrapped JSX content');\n\n // Add the withGTConfig() function to the next.config.js file\n const tsconfigPath = findFilepath(['tsconfig.json']);\n await handleInitGT(\n plan.nextConfigPath,\n errors,\n warnings,\n filesUpdated,\n plan.packageJson,\n tsconfigPath ? loadConfig(tsconfigPath) : undefined\n );\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow('Warnings encountered:') +\n '\\n' +\n warnings.map((warning) => `${chalk.yellow('-')} ${warning}`).join('\\n')\n );\n }\n if (errors.length > 0) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'Setup could not update some application files',\n details: errors,\n fix: 'Fix the reported files, then rerun `npx gt init`',\n })\n );\n }\n logger.step(\n chalk.green(`Added withGTConfig() to your ${plan.nextConfigPath} file.`)\n );\n session.step(`added withGTConfig() to ${plan.nextConfigPath}`);\n\n if (plan.formatter) await formatFiles(filesUpdated, plan.formatter);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,MAAM,mBACJ;;;;;AAMF,eAAsB,kBACpB,SACA,SACA,UACA,qBACqC;CACrC,MAAM,UAAU,yBAAyB,SAAS;CAClD,MAAM,YAAY,kBAAkB,SAAS,KAAK;CAClD,MAAM,cAAc,WAAW;AA4B/B,KAAI,CAAC,MA3BkB,QAAQ,OAAO,iBAAiB;EACrD,UAAU,QAAQ;EAClB,aAAa;EACb,KAAK,YAAY;GACf,MAAM,SAAS,MAAM,cAAc;IACjC,SAAS,6BAA6B,QAAQ,OAAO,cAAc,aAAa,gBAAgB,qBAAqB,uCAAuC,WAAW,WAAA;IACvK,cAAc;IACf,CAAC;AAEF,OACE,UACA,CAAE,MAAM,cAAc;IACpB,SAAS,MAAM,OACb,mCAAmC,wBAAwB,SAAS,CAAC;;+EAGtE;IACD,cAAc;IACd,eAAe;IAChB,CAAC,EACF;AACA,WAAO,KAAK,iBAAiB;AAC7B,WAAO,SAAS,EAAE;;AAEpB,UAAO;;EAEV,CAAC,CACa,QAAO,KAAA;CAEtB,MAAM,YAAY,MAAM,QAAQ,OAC9B,eACA;EACE,UAAU,QAAQ;EAClB,YAAY;EACZ,aAAa,SAAS;EACtB,WACE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 +104,7 @@ export type GenerateSourceOptions = {
|
|
|
104
104
|
suppressWarnings: boolean;
|
|
105
105
|
};
|
|
106
106
|
export type Framework = typeof Libraries.GT_NEXT | typeof Libraries.GT_REACT | typeof Libraries.GT_REACT_NATIVE | typeof Libraries.GT_TANSTACK_START;
|
|
107
|
-
export declare const SUPPORTED_REACT_FRAMEWORKS: readonly ["next-app", "next-pages", "vite", "gatsby", "react", "redwood", "tanstack-start"];
|
|
107
|
+
export declare const SUPPORTED_REACT_FRAMEWORKS: readonly ["next-app", "next-pages", "vite", "gatsby", "react", "redwood", "tanstack-start", "react-router"];
|
|
108
108
|
export type FrameworkObject = {
|
|
109
109
|
name: 'mintlify';
|
|
110
110
|
type?: undefined;
|
package/dist/types/index.js
CHANGED
package/dist/types/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["import type { CustomMapping } from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport type { ModelProvider } from 'generaltranslation/internal';\nimport type { FileFormat } from 'generaltranslation/types';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport {\n ParsingConfigOptions,\n GTParsingFlags,\n BaseParsingFlags,\n ParseFlagsByFileType,\n} from './parsing.js';\nimport { Libraries, InlineLibrary } from './libraries.js';\n\nexport type { Updates } from 'generaltranslation/types';\n\nexport type Options = {\n config: string;\n apiKey?: string;\n projectId?: string;\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n src?: string[];\n defaultLocale?: string;\n locales?: string[];\n baseUrl: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n dryRun: boolean;\n timeout: number;\n force?: boolean;\n stageTranslations?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type OpenApiConfig = {\n files: string[];\n translateFields?: string[];\n};\n\nexport type MintlifyOptions = {\n openapi?: OpenApiConfig;\n inferTitleFromFilename?: boolean;\n localizeRedirects?: boolean; // add localized redirects for pages renamed or removed in a translate run\n};\n\nexport type SharedFlags = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n};\n\nexport type TranslateFlags = SharedFlags & {\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n defaultLocale?: string;\n locales?: string[];\n ignoreErrors?: boolean;\n src?: string[];\n timeout: number;\n dryRun: boolean;\n saveLocal?: boolean;\n stageTranslations?: boolean;\n setupProject?: boolean; // if true, skip enqueue step\n publish?: boolean;\n force?: boolean;\n forceDownload?: boolean;\n tag?: string;\n message?: string;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n omitConfigIds?: boolean;\n excludeStaticUrls?: string[];\n excludeStaticImports?: string[];\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type WrapOptions = {\n src?: string[];\n config: string;\n skipTs: boolean;\n disableIds: boolean;\n disableFormatting: boolean;\n addGTProvider: boolean;\n};\n\nexport type SetupOptions = {\n src?: string[];\n config: string;\n};\n\nexport type GenerateSourceOptions = {\n src?: string[];\n config: string;\n defaultLocale: string;\n dictionary?: string;\n jsconfig?: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n};\n\nexport type Framework =\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_REACT\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START;\n\nexport const SUPPORTED_REACT_FRAMEWORKS = [\n 'next-app',\n 'next-pages',\n 'vite',\n 'gatsby',\n 'react',\n 'redwood',\n 'tanstack-start',\n] as const;\n\nexport type FrameworkObject =\n | {\n name: 'mintlify';\n type?: undefined;\n }\n | {\n name: (typeof SUPPORTED_REACT_FRAMEWORKS)[number];\n type: 'react';\n };\nexport type ReactFrameworkObject = Extract<FrameworkObject, { type: 'react' }>;\n\nexport type FrameworkType = FrameworkObject['type'];\n\nexport type SupportedFrameworks = FrameworkObject['name'];\nexport type SupportedReactFrameworks = Extract<\n FrameworkObject,\n { type: 'react' }\n>['name'];\n\nexport type SupportedLibraries =\n | InlineLibrary\n | 'next-intl'\n | 'react-i18next'\n | 'next-i18next'\n | 'i18next'\n | 'i18next-icu'\n | 'base';\n\nexport interface ContentScanner {\n scanForContent(\n options: WrapOptions,\n framework: Framework\n ): Promise<{\n errors: string[];\n filesUpdated: string[];\n warnings: string[];\n }>;\n}\n\n// Create a type based on the supported file extensions\nexport type SupportedFileExtension = (typeof SUPPORTED_FILE_EXTENSIONS)[number];\n\n// Update ResolvedFiles to use the dynamic keys\nexport type ResolvedFiles = {\n [K in SupportedFileExtension]?: string[];\n} & {\n gt?: string; // Output glob: /path/[locale].json\n};\n\nexport type TransformOption = {\n match?: string; // regex to match strings, supports capture groups\n replace: string; // string or regex pattern to replace the match with\n // Special placeholders:\n // -> if used in the match string, they will be replaced with the corresponding default locale property value\n // -> if used in the replace string, they will be replaced with the corresponding target locale property value\n // {locale} -> will be replaced with the locale code\n // And any other property from getLocaleProperties()\n};\n\nexport type TransformFiles = {\n [K in SupportedFileExtension]?: TransformOption | string | TransformOption[]; // if a string, only transform the file name\n};\n\nexport type TransformFormats = {\n [K in SupportedFileExtension]?: FileFormat;\n};\n\n// Include patterns can be plain strings or objects with a publish flag\nexport type IncludePattern = string | { pattern: string; publish?: boolean };\n\n// Review requirement for matched files: a boolean applies to all files of the\n// type; the object form opts path groups in/out with globs. exclude wins over\n// include; files matching neither inherit the top-level requiresReview default.\nexport type RequiresReviewConfig =\n | boolean\n | {\n include?: string[];\n exclude?: string[];\n };\n\n// Update FilesOptions to fix the error\nexport type FilesOptions = {\n [K in SupportedFileExtension]?: {\n include: IncludePattern[];\n exclude?: string[];\n transform?: string | TransformOption | TransformOption[];\n transformationFormat?: FileFormat;\n parsingFlags?: BaseParsingFlags; // Flags for parsing inline content\n requiresReview?: RequiresReviewConfig; // Whether translated versions of matched files require approval before use\n };\n} & {\n gt?: {\n output: string; // Output glob: /path/[locale].json\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags?: Partial<GTParsingFlags>; // Flags for parsing inline content\n /**\n * @deprecated\n * use `files.gt.parsingFlags.includeSourceCodeContext` instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n};\n\n// Shared settings between all API-related commands\nexport type FontsConfig = {\n include: string[]; // globs of .ttf/.otf files\n exclude?: string[];\n};\n\nexport type Settings = {\n config: string;\n configDirectory: string;\n baseUrl: string;\n dashboardUrl: string;\n apiKey?: string;\n userTokenProvider?: UserTokenProvider;\n projectId?: string;\n defaultLocale: string;\n locales: string[];\n customMapping?: CustomMapping;\n files: {\n resolvedPaths: ResolvedFiles; // Absolute resolved paths for the default locale\n placeholderPaths: ResolvedFiles; // Absolute placeholder paths for all locales containing [locale]\n transformPaths: TransformFiles; // Absolute transform paths for all locales containing [locale]\n transformFormats: TransformFormats; // Output file format transforms keyed by config file type\n publishPaths: Set<string>; // Absolute paths explicitly opted IN to publishing\n unpublishPaths: Set<string>; // Absolute paths explicitly opted OUT of publishing\n requiresReviewPaths: Set<string>; // Absolute paths whose effective requiresReview policy is true\n parsingFlags: ParseFlagsByFileType;\n gtJson: {\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags: GTParsingFlags; // Flags for parsing inline content\n /**\n * @deprecated\n * use {@link files.gt.GTParsingFlags.parsingFlags.includeSourceCodeContext} instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n };\n stageTranslations: boolean; // if true, always stage the project during translate command\n requiresReview?: boolean; // top-level default: translated artifacts require approval before the client uses them\n publish?: boolean; // if true, publish the translations to the CDN; undefined means no global publish intent\n omitConfigIds?: boolean; // if true, do not write _versionId or _branchId to gt.config.json\n _versionId?: string; // internal use only\n _branchId?: string; // internal use only\n version?: string; // for specifying a custom version id to use. Should be unique\n description?: string;\n src?: string[]; // list of glob patterns for source file scanning\n fonts?: FontsConfig; // fonts to sync to the API before translating\n framework?: SupportedFrameworks;\n options?: AdditionalOptions;\n modelProvider?: ModelProvider;\n tag?: string;\n tagMessage?: string;\n parsingOptions: ParsingConfigOptions;\n branchOptions: BranchOptions;\n // Optional shared static assets config\n sharedStaticAssets?: SharedStaticAssetsConfig;\n};\n\nexport type StaticLocalizationFiles = Pick<\n Settings['files'],\n 'placeholderPaths' | 'resolvedPaths'\n> &\n Partial<Pick<Settings['files'], 'transformPaths' | 'transformFormats'>>;\n\nexport type StaticLocalizationSettings = Pick<\n Settings,\n 'defaultLocale' | 'locales' | 'options'\n> & {\n files?: StaticLocalizationFiles | null;\n};\n\nexport type BranchOptions = {\n currentBranch?: string;\n autoDetectBranches?: boolean;\n remoteName: string; // default 'origin'. The name of the remote to use for auto-detection.\n enabled: boolean; // if true, branching is enabled for the project\n};\n\nexport type AdditionalOptions = {\n // Optional schema to follow while translating JSON files\n jsonSchema?: {\n [fileGlob: string]: JsonSchema;\n };\n // Optional schema to follow while translating YAML files\n yamlSchema?: {\n [fileGlob: string]: YamlSchema;\n };\n // Skip pre-parse validation checks for specific file types\n skipFileValidation?: {\n json?: boolean;\n yaml?: boolean;\n mdx?: boolean;\n };\n // Optional Mintlify-specific options container\n mintlify?: MintlifyOptions;\n docsUrlPattern?: string; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files\n docsImportPattern?: string; // eg /docs/[locale]/foo.md or /[locale]/foo.md for localizing static imports in markdown files\n excludeStaticUrls?: string[]; // A list of file globs to include for static url localization\n excludeStaticImports?: string[]; // A list of file globs to include for static import localization\n docsHideDefaultLocaleImport?: boolean; // if true, hide the default locale in the import path\n copyFiles?: string[]; // array of files to copy to the target locale\n experimentalClearLocaleDirs?: boolean; // if true, clear locale directories before writing translations (default: false)\n clearLocaleDirsExclude?: string[]; // array of glob patterns with [locale] or [locales] placeholder to exclude from clearing (e.g., \"./snippets/[locale]/preserved/**\" or \"./[locales]/static/**\")\n experimentalLocalizeStaticImports?: boolean; // Inserts locale in static import paths in md/mdx files\n // Inserts locale in static url paths in md/mdx files and adds anchor IDs to\n // preserve navigation. The object form enables it with extra behavior.\n experimentalLocalizeStaticUrls?:\n | boolean\n | {\n // Keep links to source pages that have no translation\n skipUntranslatedPages?: boolean;\n // Extra JSX attribute names or globs to localize\n attributes?: string[];\n };\n experimentalLocalizeRelativeAssets?: boolean; // Rewrites relative asset URLs in translated md/mdx files to valid paths\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default'; // Format for anchor IDs: 'mintlify' for Mintlify's native {#id} on every heading, 'default' or undefined for escaped inline \\{#id\\}. Can run independently of static url localization\n experimentalHideDefaultLocale?: boolean; // Hides the default locale in the import path\n experimentalFlattenJsonFiles?: boolean; // Flattens JSON files into a single file\n baseDomain?: string; // The base http:// url where the project is hosted\n docsImportRewrites?: Array<{\n match: string; // prefix to match, e.g. '@site/docs'\n replace: string; // replacement prefix, can include [locale] or [defaultLocale]\n }>;\n experimentalCanonicalLocaleKeys?: boolean; // For composite JSON schemas with locale keys, force canonical locale even when alias provided\n saveLocal?: boolean; // if true, detect and save local edits to translated output before enqueuing translations (default: false)\n};\n\nexport type SharedStaticAssetsConfig = {\n include: string | string[];\n outDir?: string;\n publicPath?: string;\n mirrorToLocales?: boolean;\n};\n\nexport type StructuralTransform = {\n sourcePointer: string; // e.g., \"/msg\"\n destinationPointer: string; // e.g., \"/translations/en\"\n};\n\nexport type JsonSchema = {\n preset?: 'mintlify' | 'mintlify-hide-default' | 'openapi';\n structuralTransform?: StructuralTransform[];\n\n // when true, resolve $ref entries in this file before processing\n resolveRefs?: boolean;\n\n // exactly 1 of include or composite must be provided; not both\n\n // specify include if file is not composite\n // multiple target JSONs will be created for each locale,\n // with the only differing content being the specified JSONPath values\n include?: string[]; // array of JSONPaths to include\n\n // specify composite if no new JSONs should be created\n composite?: {\n // The sourceObjectPath is a JSONPath to the array or object containing\n // content in the source and target locales\n // This value is denoted as the \"sourceObject\"\n // Array elements or object sub-elements are denoted as \"sourceItem\"\n [sourceObjectPath: string]: SourceObjectOptions;\n };\n};\n\nexport type YamlSchema = {\n preset?: 'mintlify' | 'openapi';\n include?: string[];\n transform?: TransformOptions;\n};\n\nexport type SourceObjectOptions = {\n type: 'array' | 'object'; // type of the sourceObject;\n // array if the sourceObject is an array\n // -> We will simply add duplicated sourceItems for each locale\n // object if the sourceObject is an object\n // -> We will duplicate the sourceItem for each locale and set the corresponding\n // key with the locale property\n // In both cases, we search the sourceObject for the key that matches the source locale\n\n // Below, relative JSONPaths are relative to the sourceItem root, NOT the sourceObject\n\n include: string[]; // array of relative JSONPaths to include in the translated JSON\n\n // if type is array, there must be a key property in the array element\n // corresponding value should be a locale code\n key?: string; // relative jsonPath to the key to use to distinguish between source and target locales\n // if type is object, the key is simply the JSON key for the sourceItem - this is unnecessary in this case\n\n localeProperty?: string; // specific locale property to use for the key for target locales, default 'code'\n // ex: code, name, nativeName, languageCode, languageName, etc. (values returned by getLocaleProperties)\n\n // optional config for transforming specific fields in the sourceItem\n // for example, helpful for handling urls with locale-specific paths\n transform?: TransformOptions;\n\n // optional list of top-level properties to remove from generated\n // non-default-locale entries (e.g. Mintlify's `default: true` flag on the\n // default language entry, which must not be cloned into other locales)\n omitProperties?: string[];\n\n // optional sorting behavior for array sourceObjects. When set to 'locale',\n // the array will be ordered to match the locales array provided to mergeJson\n // When set to 'localesAlphabetical', the default locale will be placed first\n // and the remaining locales will be ordered alphabetically by locale code\n experimentalSort?: 'locales' | 'localesAlphabetical';\n\n // when true, non-default keyed entries in this composite array are extracted\n // into separate files (using the key value as the directory name) and replaced\n // with $ref pointers. Keeps the source file compact.\n splitEntries?: boolean;\n};\n\nexport type TransformOptions = {\n // relative jsonPath to content to mutate\n [transformPath: string]: TransformOption;\n};\n"],"mappings":";AA8HA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["import type { CustomMapping } from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport type { ModelProvider } from 'generaltranslation/internal';\nimport type { FileFormat } from 'generaltranslation/types';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport {\n ParsingConfigOptions,\n GTParsingFlags,\n BaseParsingFlags,\n ParseFlagsByFileType,\n} from './parsing.js';\nimport { Libraries, InlineLibrary } from './libraries.js';\n\nexport type { Updates } from 'generaltranslation/types';\n\nexport type Options = {\n config: string;\n apiKey?: string;\n projectId?: string;\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n src?: string[];\n defaultLocale?: string;\n locales?: string[];\n baseUrl: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n dryRun: boolean;\n timeout: number;\n force?: boolean;\n stageTranslations?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type OpenApiConfig = {\n files: string[];\n translateFields?: string[];\n};\n\nexport type MintlifyOptions = {\n openapi?: OpenApiConfig;\n inferTitleFromFilename?: boolean;\n localizeRedirects?: boolean; // add localized redirects for pages renamed or removed in a translate run\n};\n\nexport type SharedFlags = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n};\n\nexport type TranslateFlags = SharedFlags & {\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n defaultLocale?: string;\n locales?: string[];\n ignoreErrors?: boolean;\n src?: string[];\n timeout: number;\n dryRun: boolean;\n saveLocal?: boolean;\n stageTranslations?: boolean;\n setupProject?: boolean; // if true, skip enqueue step\n publish?: boolean;\n force?: boolean;\n forceDownload?: boolean;\n tag?: string;\n message?: string;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n omitConfigIds?: boolean;\n excludeStaticUrls?: string[];\n excludeStaticImports?: string[];\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type WrapOptions = {\n src?: string[];\n config: string;\n skipTs: boolean;\n disableIds: boolean;\n disableFormatting: boolean;\n addGTProvider: boolean;\n};\n\nexport type SetupOptions = {\n src?: string[];\n config: string;\n};\n\nexport type GenerateSourceOptions = {\n src?: string[];\n config: string;\n defaultLocale: string;\n dictionary?: string;\n jsconfig?: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n};\n\nexport type Framework =\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_REACT\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START;\n\nexport const SUPPORTED_REACT_FRAMEWORKS = [\n 'next-app',\n 'next-pages',\n 'vite',\n 'gatsby',\n 'react',\n 'redwood',\n 'tanstack-start',\n 'react-router',\n] as const;\n\nexport type FrameworkObject =\n | {\n name: 'mintlify';\n type?: undefined;\n }\n | {\n name: (typeof SUPPORTED_REACT_FRAMEWORKS)[number];\n type: 'react';\n };\nexport type ReactFrameworkObject = Extract<FrameworkObject, { type: 'react' }>;\n\nexport type FrameworkType = FrameworkObject['type'];\n\nexport type SupportedFrameworks = FrameworkObject['name'];\nexport type SupportedReactFrameworks = Extract<\n FrameworkObject,\n { type: 'react' }\n>['name'];\n\nexport type SupportedLibraries =\n | InlineLibrary\n | 'next-intl'\n | 'react-i18next'\n | 'next-i18next'\n | 'i18next'\n | 'i18next-icu'\n | 'base';\n\nexport interface ContentScanner {\n scanForContent(\n options: WrapOptions,\n framework: Framework\n ): Promise<{\n errors: string[];\n filesUpdated: string[];\n warnings: string[];\n }>;\n}\n\n// Create a type based on the supported file extensions\nexport type SupportedFileExtension = (typeof SUPPORTED_FILE_EXTENSIONS)[number];\n\n// Update ResolvedFiles to use the dynamic keys\nexport type ResolvedFiles = {\n [K in SupportedFileExtension]?: string[];\n} & {\n gt?: string; // Output glob: /path/[locale].json\n};\n\nexport type TransformOption = {\n match?: string; // regex to match strings, supports capture groups\n replace: string; // string or regex pattern to replace the match with\n // Special placeholders:\n // -> if used in the match string, they will be replaced with the corresponding default locale property value\n // -> if used in the replace string, they will be replaced with the corresponding target locale property value\n // {locale} -> will be replaced with the locale code\n // And any other property from getLocaleProperties()\n};\n\nexport type TransformFiles = {\n [K in SupportedFileExtension]?: TransformOption | string | TransformOption[]; // if a string, only transform the file name\n};\n\nexport type TransformFormats = {\n [K in SupportedFileExtension]?: FileFormat;\n};\n\n// Include patterns can be plain strings or objects with a publish flag\nexport type IncludePattern = string | { pattern: string; publish?: boolean };\n\n// Review requirement for matched files: a boolean applies to all files of the\n// type; the object form opts path groups in/out with globs. exclude wins over\n// include; files matching neither inherit the top-level requiresReview default.\nexport type RequiresReviewConfig =\n | boolean\n | {\n include?: string[];\n exclude?: string[];\n };\n\n// Update FilesOptions to fix the error\nexport type FilesOptions = {\n [K in SupportedFileExtension]?: {\n include: IncludePattern[];\n exclude?: string[];\n transform?: string | TransformOption | TransformOption[];\n transformationFormat?: FileFormat;\n parsingFlags?: BaseParsingFlags; // Flags for parsing inline content\n requiresReview?: RequiresReviewConfig; // Whether translated versions of matched files require approval before use\n };\n} & {\n gt?: {\n output: string; // Output glob: /path/[locale].json\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags?: Partial<GTParsingFlags>; // Flags for parsing inline content\n /**\n * @deprecated\n * use `files.gt.parsingFlags.includeSourceCodeContext` instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n};\n\n// Shared settings between all API-related commands\nexport type FontsConfig = {\n include: string[]; // globs of .ttf/.otf files\n exclude?: string[];\n};\n\nexport type Settings = {\n config: string;\n configDirectory: string;\n baseUrl: string;\n dashboardUrl: string;\n apiKey?: string;\n userTokenProvider?: UserTokenProvider;\n projectId?: string;\n defaultLocale: string;\n locales: string[];\n customMapping?: CustomMapping;\n files: {\n resolvedPaths: ResolvedFiles; // Absolute resolved paths for the default locale\n placeholderPaths: ResolvedFiles; // Absolute placeholder paths for all locales containing [locale]\n transformPaths: TransformFiles; // Absolute transform paths for all locales containing [locale]\n transformFormats: TransformFormats; // Output file format transforms keyed by config file type\n publishPaths: Set<string>; // Absolute paths explicitly opted IN to publishing\n unpublishPaths: Set<string>; // Absolute paths explicitly opted OUT of publishing\n requiresReviewPaths: Set<string>; // Absolute paths whose effective requiresReview policy is true\n parsingFlags: ParseFlagsByFileType;\n gtJson: {\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags: GTParsingFlags; // Flags for parsing inline content\n /**\n * @deprecated\n * use {@link files.gt.GTParsingFlags.parsingFlags.includeSourceCodeContext} instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n };\n stageTranslations: boolean; // if true, always stage the project during translate command\n requiresReview?: boolean; // top-level default: translated artifacts require approval before the client uses them\n publish?: boolean; // if true, publish the translations to the CDN; undefined means no global publish intent\n omitConfigIds?: boolean; // if true, do not write _versionId or _branchId to gt.config.json\n _versionId?: string; // internal use only\n _branchId?: string; // internal use only\n version?: string; // for specifying a custom version id to use. Should be unique\n description?: string;\n src?: string[]; // list of glob patterns for source file scanning\n fonts?: FontsConfig; // fonts to sync to the API before translating\n framework?: SupportedFrameworks;\n options?: AdditionalOptions;\n modelProvider?: ModelProvider;\n tag?: string;\n tagMessage?: string;\n parsingOptions: ParsingConfigOptions;\n branchOptions: BranchOptions;\n // Optional shared static assets config\n sharedStaticAssets?: SharedStaticAssetsConfig;\n};\n\nexport type StaticLocalizationFiles = Pick<\n Settings['files'],\n 'placeholderPaths' | 'resolvedPaths'\n> &\n Partial<Pick<Settings['files'], 'transformPaths' | 'transformFormats'>>;\n\nexport type StaticLocalizationSettings = Pick<\n Settings,\n 'defaultLocale' | 'locales' | 'options'\n> & {\n files?: StaticLocalizationFiles | null;\n};\n\nexport type BranchOptions = {\n currentBranch?: string;\n autoDetectBranches?: boolean;\n remoteName: string; // default 'origin'. The name of the remote to use for auto-detection.\n enabled: boolean; // if true, branching is enabled for the project\n};\n\nexport type AdditionalOptions = {\n // Optional schema to follow while translating JSON files\n jsonSchema?: {\n [fileGlob: string]: JsonSchema;\n };\n // Optional schema to follow while translating YAML files\n yamlSchema?: {\n [fileGlob: string]: YamlSchema;\n };\n // Skip pre-parse validation checks for specific file types\n skipFileValidation?: {\n json?: boolean;\n yaml?: boolean;\n mdx?: boolean;\n };\n // Optional Mintlify-specific options container\n mintlify?: MintlifyOptions;\n docsUrlPattern?: string; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files\n docsImportPattern?: string; // eg /docs/[locale]/foo.md or /[locale]/foo.md for localizing static imports in markdown files\n excludeStaticUrls?: string[]; // A list of file globs to include for static url localization\n excludeStaticImports?: string[]; // A list of file globs to include for static import localization\n docsHideDefaultLocaleImport?: boolean; // if true, hide the default locale in the import path\n copyFiles?: string[]; // array of files to copy to the target locale\n experimentalClearLocaleDirs?: boolean; // if true, clear locale directories before writing translations (default: false)\n clearLocaleDirsExclude?: string[]; // array of glob patterns with [locale] or [locales] placeholder to exclude from clearing (e.g., \"./snippets/[locale]/preserved/**\" or \"./[locales]/static/**\")\n experimentalLocalizeStaticImports?: boolean; // Inserts locale in static import paths in md/mdx files\n // Inserts locale in static url paths in md/mdx files and adds anchor IDs to\n // preserve navigation. The object form enables it with extra behavior.\n experimentalLocalizeStaticUrls?:\n | boolean\n | {\n // Keep links to source pages that have no translation\n skipUntranslatedPages?: boolean;\n // Extra JSX attribute names or globs to localize\n attributes?: string[];\n };\n experimentalLocalizeRelativeAssets?: boolean; // Rewrites relative asset URLs in translated md/mdx files to valid paths\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default'; // Format for anchor IDs: 'mintlify' for Mintlify's native {#id} on every heading, 'default' or undefined for escaped inline \\{#id\\}. Can run independently of static url localization\n experimentalHideDefaultLocale?: boolean; // Hides the default locale in the import path\n experimentalFlattenJsonFiles?: boolean; // Flattens JSON files into a single file\n baseDomain?: string; // The base http:// url where the project is hosted\n docsImportRewrites?: Array<{\n match: string; // prefix to match, e.g. '@site/docs'\n replace: string; // replacement prefix, can include [locale] or [defaultLocale]\n }>;\n experimentalCanonicalLocaleKeys?: boolean; // For composite JSON schemas with locale keys, force canonical locale even when alias provided\n saveLocal?: boolean; // if true, detect and save local edits to translated output before enqueuing translations (default: false)\n};\n\nexport type SharedStaticAssetsConfig = {\n include: string | string[];\n outDir?: string;\n publicPath?: string;\n mirrorToLocales?: boolean;\n};\n\nexport type StructuralTransform = {\n sourcePointer: string; // e.g., \"/msg\"\n destinationPointer: string; // e.g., \"/translations/en\"\n};\n\nexport type JsonSchema = {\n preset?: 'mintlify' | 'mintlify-hide-default' | 'openapi';\n structuralTransform?: StructuralTransform[];\n\n // when true, resolve $ref entries in this file before processing\n resolveRefs?: boolean;\n\n // exactly 1 of include or composite must be provided; not both\n\n // specify include if file is not composite\n // multiple target JSONs will be created for each locale,\n // with the only differing content being the specified JSONPath values\n include?: string[]; // array of JSONPaths to include\n\n // specify composite if no new JSONs should be created\n composite?: {\n // The sourceObjectPath is a JSONPath to the array or object containing\n // content in the source and target locales\n // This value is denoted as the \"sourceObject\"\n // Array elements or object sub-elements are denoted as \"sourceItem\"\n [sourceObjectPath: string]: SourceObjectOptions;\n };\n};\n\nexport type YamlSchema = {\n preset?: 'mintlify' | 'openapi';\n include?: string[];\n transform?: TransformOptions;\n};\n\nexport type SourceObjectOptions = {\n type: 'array' | 'object'; // type of the sourceObject;\n // array if the sourceObject is an array\n // -> We will simply add duplicated sourceItems for each locale\n // object if the sourceObject is an object\n // -> We will duplicate the sourceItem for each locale and set the corresponding\n // key with the locale property\n // In both cases, we search the sourceObject for the key that matches the source locale\n\n // Below, relative JSONPaths are relative to the sourceItem root, NOT the sourceObject\n\n include: string[]; // array of relative JSONPaths to include in the translated JSON\n\n // if type is array, there must be a key property in the array element\n // corresponding value should be a locale code\n key?: string; // relative jsonPath to the key to use to distinguish between source and target locales\n // if type is object, the key is simply the JSON key for the sourceItem - this is unnecessary in this case\n\n localeProperty?: string; // specific locale property to use for the key for target locales, default 'code'\n // ex: code, name, nativeName, languageCode, languageName, etc. (values returned by getLocaleProperties)\n\n // optional config for transforming specific fields in the sourceItem\n // for example, helpful for handling urls with locale-specific paths\n transform?: TransformOptions;\n\n // optional list of top-level properties to remove from generated\n // non-default-locale entries (e.g. Mintlify's `default: true` flag on the\n // default language entry, which must not be cloned into other locales)\n omitProperties?: string[];\n\n // optional sorting behavior for array sourceObjects. When set to 'locale',\n // the array will be ordered to match the locales array provided to mergeJson\n // When set to 'localesAlphabetical', the default locale will be placed first\n // and the remaining locales will be ordered alphabetically by locale code\n experimentalSort?: 'locales' | 'localesAlphabetical';\n\n // when true, non-default keyed entries in this composite array are extracted\n // into separate files (using the key value as the directory name) and replaced\n // with $ref pointers. Keeps the source file compact.\n splitEntries?: boolean;\n};\n\nexport type TransformOptions = {\n // relative jsonPath to content to mutate\n [transformPath: string]: TransformOption;\n};\n"],"mappings":";AA8HA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
|
|
@@ -8,3 +8,4 @@ export declare const DEFAULT_TIMEOUT_SECONDS = 900;
|
|
|
8
8
|
export declare const SURROUNDING_LINE_COUNT = 5;
|
|
9
9
|
export declare const DEFAULT_TRANSLATIONS_DIR = "./public/_gt";
|
|
10
10
|
export declare const DEFAULT_VITE_TRANSLATIONS_DIR = "./src/_gt";
|
|
11
|
+
export declare const DEFAULT_REACT_ROUTER_TRANSLATIONS_DIR = "./app/_gt";
|
package/dist/utils/constants.js
CHANGED
|
@@ -10,7 +10,8 @@ const DEFAULT_TIMEOUT_SECONDS = 900;
|
|
|
10
10
|
const SURROUNDING_LINE_COUNT = 5;
|
|
11
11
|
const DEFAULT_TRANSLATIONS_DIR = "./public/_gt";
|
|
12
12
|
const DEFAULT_VITE_TRANSLATIONS_DIR = "./src/_gt";
|
|
13
|
+
const DEFAULT_REACT_ROUTER_TRANSLATIONS_DIR = "./app/_gt";
|
|
13
14
|
//#endregion
|
|
14
|
-
export { DEFAULT_GIT_REMOTE_NAME, 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 };
|
|
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 };
|
|
15
16
|
|
|
16
17
|
//# sourceMappingURL=constants.js.map
|