gtx-cli 2.3.6-alpha.2 → 2.3.6
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 +10 -0
- package/dist/api/checkFileTranslations.d.ts +23 -0
- package/dist/api/checkFileTranslations.js +236 -0
- package/dist/api/downloadFileBatch.d.ts +20 -0
- package/dist/api/downloadFileBatch.js +113 -0
- package/dist/api/sendFiles.d.ts +17 -0
- package/dist/api/sendFiles.js +115 -0
- package/dist/api/uploadFiles.d.ts +27 -0
- package/dist/api/uploadFiles.js +40 -0
- package/dist/cli/base.d.ts +32 -0
- package/dist/cli/base.js +335 -0
- package/dist/cli/commands/stage.d.ts +5 -0
- package/dist/cli/commands/stage.js +100 -0
- package/dist/cli/commands/translate.d.ts +6 -0
- package/dist/cli/commands/translate.js +63 -0
- package/dist/cli/flags.d.ts +3 -0
- package/dist/cli/flags.js +38 -0
- package/dist/cli/next.d.ts +11 -0
- package/dist/cli/next.js +20 -0
- package/dist/cli/react.d.ts +18 -0
- package/dist/cli/react.js +175 -0
- package/dist/config/generateSettings.d.ts +9 -0
- package/dist/config/generateSettings.js +176 -0
- package/dist/config/optionPresets.d.ts +2 -0
- package/dist/config/optionPresets.js +56 -0
- package/dist/config/resolveConfig.d.ts +4 -0
- package/dist/config/resolveConfig.js +19 -0
- package/dist/config/utils.d.ts +2 -0
- package/dist/config/utils.js +4 -0
- package/dist/config/validateSettings.d.ts +3 -0
- package/dist/config/validateSettings.js +32 -0
- package/dist/console/colors.d.ts +5 -0
- package/dist/console/colors.js +16 -0
- package/dist/console/index.d.ts +21 -0
- package/dist/console/index.js +24 -0
- package/dist/console/logging.d.ts +53 -0
- package/dist/console/logging.js +185 -0
- package/dist/formats/files/fileMapping.d.ts +11 -0
- package/dist/formats/files/fileMapping.js +82 -0
- package/dist/formats/files/save.d.ts +5 -0
- package/dist/formats/files/save.js +17 -0
- package/dist/formats/files/supportedFiles.d.ts +10 -0
- package/dist/formats/files/supportedFiles.js +18 -0
- package/dist/formats/files/translate.d.ts +4 -0
- package/dist/formats/files/translate.js +119 -0
- package/dist/formats/files/upload.d.ts +13 -0
- package/dist/formats/files/upload.js +136 -0
- package/dist/formats/gt/save.d.ts +9 -0
- package/dist/formats/gt/save.js +26 -0
- package/dist/formats/json/flattenJson.d.ts +14 -0
- package/dist/formats/json/flattenJson.js +64 -0
- package/dist/formats/json/mergeJson.d.ts +13 -0
- package/dist/formats/json/mergeJson.js +257 -0
- package/dist/formats/json/parseJson.d.ts +2 -0
- package/dist/formats/json/parseJson.js +108 -0
- package/dist/formats/json/utils.d.ts +47 -0
- package/dist/formats/json/utils.js +149 -0
- package/dist/formats/utils.d.ts +2 -0
- package/dist/formats/utils.js +24 -0
- package/dist/formats/yaml/mergeYaml.d.ts +5 -0
- package/dist/formats/yaml/mergeYaml.js +55 -0
- package/dist/formats/yaml/parseYaml.d.ts +5 -0
- package/dist/formats/yaml/parseYaml.js +23 -0
- package/dist/formats/yaml/utils.d.ts +2 -0
- package/dist/formats/yaml/utils.js +22 -0
- package/dist/fs/config/loadConfig.d.ts +1 -0
- package/dist/fs/config/loadConfig.js +9 -0
- package/dist/fs/config/parseFilesConfig.d.ts +27 -0
- package/dist/fs/config/parseFilesConfig.js +129 -0
- package/dist/fs/config/setupConfig.d.ts +17 -0
- package/dist/fs/config/setupConfig.js +50 -0
- package/dist/fs/config/updateConfig.d.ts +10 -0
- package/dist/fs/config/updateConfig.js +36 -0
- package/dist/fs/config/updateVersions.d.ts +10 -0
- package/dist/fs/config/updateVersions.js +30 -0
- package/dist/fs/copyFile.d.ts +7 -0
- package/dist/fs/copyFile.js +39 -0
- package/dist/fs/createLoadTranslationsFile.d.ts +1 -0
- package/dist/fs/createLoadTranslationsFile.js +36 -0
- package/dist/fs/determineFramework.d.ts +5 -0
- package/dist/fs/determineFramework.js +46 -0
- package/dist/fs/findFilepath.d.ts +36 -0
- package/dist/fs/findFilepath.js +89 -0
- package/dist/fs/getPackageResource.d.ts +1 -0
- package/dist/fs/getPackageResource.js +6 -0
- package/dist/fs/index.d.ts +1 -0
- package/dist/fs/index.js +1 -0
- package/dist/fs/loadJSON.d.ts +6 -0
- package/dist/fs/loadJSON.js +17 -0
- package/dist/fs/matchFiles.d.ts +1 -0
- package/dist/fs/matchFiles.js +8 -0
- package/dist/fs/saveJSON.d.ts +1 -0
- package/dist/fs/saveJSON.js +7 -0
- package/dist/fs/utils.d.ts +1 -0
- package/dist/fs/utils.js +16 -0
- package/dist/hooks/postProcess.d.ts +4 -0
- package/dist/hooks/postProcess.js +110 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +20 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +9 -0
- package/dist/next/config/parseNextConfig.d.ts +10 -0
- package/dist/next/config/parseNextConfig.js +53 -0
- package/dist/next/jsx/utils.d.ts +7 -0
- package/dist/next/jsx/utils.js +42 -0
- package/dist/next/parse/handleInitGT.d.ts +7 -0
- package/dist/next/parse/handleInitGT.js +208 -0
- package/dist/next/parse/wrapContent.d.ts +11 -0
- package/dist/next/parse/wrapContent.js +163 -0
- package/dist/react/config/createESBuildConfig.d.ts +2 -0
- package/dist/react/config/createESBuildConfig.js +119 -0
- package/dist/react/data-_gt/addGTIdentifierToSyntaxTree.d.ts +8 -0
- package/dist/react/data-_gt/addGTIdentifierToSyntaxTree.js +111 -0
- package/dist/react/jsx/evaluateJsx.d.ts +17 -0
- package/dist/react/jsx/evaluateJsx.js +85 -0
- package/dist/react/jsx/trimJsxStringChildren.d.ts +7 -0
- package/dist/react/jsx/trimJsxStringChildren.js +95 -0
- package/dist/react/jsx/utils/constants.d.ts +10 -0
- package/dist/react/jsx/utils/constants.js +31 -0
- package/dist/react/jsx/utils/parseAst.d.ts +30 -0
- package/dist/react/jsx/utils/parseAst.js +277 -0
- package/dist/react/jsx/utils/parseJsx.d.ts +21 -0
- package/dist/react/jsx/utils/parseJsx.js +244 -0
- package/dist/react/jsx/utils/parseStringFunction.d.ts +16 -0
- package/dist/react/jsx/utils/parseStringFunction.js +411 -0
- package/dist/react/jsx/utils/validateStringFunction.d.ts +7 -0
- package/dist/react/jsx/utils/validateStringFunction.js +31 -0
- package/dist/react/jsx/wrapJsx.d.ts +51 -0
- package/dist/react/jsx/wrapJsx.js +387 -0
- package/dist/react/parse/createDictionaryUpdates.d.ts +3 -0
- package/dist/react/parse/createDictionaryUpdates.js +169 -0
- package/dist/react/parse/createInlineUpdates.d.ts +6 -0
- package/dist/react/parse/createInlineUpdates.js +122 -0
- package/dist/react/parse/wrapContent.d.ts +11 -0
- package/dist/react/parse/wrapContent.js +162 -0
- package/dist/react/utils/flattenDictionary.d.ts +20 -0
- package/dist/react/utils/flattenDictionary.js +75 -0
- package/dist/react/utils/getEntryAndMetadata.d.ts +5 -0
- package/dist/react/utils/getEntryAndMetadata.js +11 -0
- package/dist/react/utils/getVariableName.d.ts +25 -0
- package/dist/react/utils/getVariableName.js +37 -0
- package/dist/setup/userInput.d.ts +4 -0
- package/dist/setup/userInput.js +29 -0
- package/dist/setup/wizard.d.ts +2 -0
- package/dist/setup/wizard.js +127 -0
- package/dist/translation/parse.d.ts +15 -0
- package/dist/translation/parse.js +76 -0
- package/dist/translation/stage.d.ts +2 -0
- package/dist/translation/stage.js +44 -0
- package/dist/translation/validate.d.ts +2 -0
- package/dist/translation/validate.js +50 -0
- package/dist/types/data/json.d.ts +6 -0
- package/dist/types/data/json.js +1 -0
- package/dist/types/data.d.ts +30 -0
- package/dist/types/data.js +1 -0
- package/dist/types/files.d.ts +1 -0
- package/dist/types/files.js +1 -0
- package/dist/types/index.d.ts +173 -0
- package/dist/types/index.js +1 -0
- package/dist/utils/addExplicitAnchorIds.d.ts +24 -0
- package/dist/utils/addExplicitAnchorIds.js +260 -0
- package/dist/utils/constants.d.ts +2 -0
- package/dist/utils/constants.js +2 -0
- package/dist/utils/credentials.d.ts +12 -0
- package/dist/utils/credentials.js +119 -0
- package/dist/utils/flattenJsonFiles.d.ts +2 -0
- package/dist/utils/flattenJsonFiles.js +36 -0
- package/dist/utils/gt.d.ts +2 -0
- package/dist/utils/gt.js +2 -0
- package/dist/utils/hash.d.ts +6 -0
- package/dist/utils/hash.js +11 -0
- package/dist/utils/headers.d.ts +1 -0
- package/dist/utils/headers.js +14 -0
- package/dist/utils/installPackage.d.ts +3 -0
- package/dist/utils/installPackage.js +77 -0
- package/dist/utils/localizeStaticImports.d.ts +15 -0
- package/dist/utils/localizeStaticImports.js +341 -0
- package/dist/utils/localizeStaticUrls.d.ts +19 -0
- package/dist/utils/localizeStaticUrls.js +432 -0
- package/dist/utils/packageInfo.d.ts +3 -0
- package/dist/utils/packageInfo.js +17 -0
- package/dist/utils/packageJson.d.ts +6 -0
- package/dist/utils/packageJson.js +76 -0
- package/dist/utils/packageManager.d.ts +28 -0
- package/dist/utils/packageManager.js +269 -0
- package/dist/utils/processAnchorIds.d.ts +6 -0
- package/dist/utils/processAnchorIds.js +47 -0
- package/dist/utils/sanitizeFileContent.d.ts +6 -0
- package/dist/utils/sanitizeFileContent.js +29 -0
- package/dist/utils/validateMdx.d.ts +10 -0
- package/dist/utils/validateMdx.js +25 -0
- package/package.json +3 -3
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { unified } from 'unified';
|
|
2
|
+
import remarkParse from 'remark-parse';
|
|
3
|
+
import remarkMdx from 'remark-mdx';
|
|
4
|
+
import remarkFrontmatter from 'remark-frontmatter';
|
|
5
|
+
import remarkStringify from 'remark-stringify';
|
|
6
|
+
import { visit } from 'unist-util-visit';
|
|
7
|
+
import { logWarning } from '../console/logging.js';
|
|
8
|
+
import escapeHtmlInTextNodes from 'gt-remark';
|
|
9
|
+
/**
|
|
10
|
+
* Generates a slug from heading text
|
|
11
|
+
*/
|
|
12
|
+
function generateSlug(text) {
|
|
13
|
+
return text
|
|
14
|
+
.toLowerCase()
|
|
15
|
+
.replace(/[^\w\s-]/g, '') // Remove special chars except spaces and hyphens
|
|
16
|
+
.trim()
|
|
17
|
+
.replace(/\s+/g, '-') // Replace spaces with hyphens
|
|
18
|
+
.replace(/-+/g, '-') // Replace multiple hyphens with single hyphen
|
|
19
|
+
.replace(/^-|-$/g, ''); // Remove leading/trailing hyphens
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Extracts text content from heading nodes
|
|
23
|
+
*/
|
|
24
|
+
function extractHeadingText(heading) {
|
|
25
|
+
let text = '';
|
|
26
|
+
visit(heading, ['text', 'inlineCode'], (node) => {
|
|
27
|
+
if ('value' in node && typeof node.value === 'string') {
|
|
28
|
+
text += node.value;
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
return text;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Checks if a heading is already wrapped in a div with id
|
|
35
|
+
*/
|
|
36
|
+
function hasExplicitId(heading, ast) {
|
|
37
|
+
const lastChild = heading.children[heading.children.length - 1];
|
|
38
|
+
if (lastChild?.type === 'text') {
|
|
39
|
+
return /(\{#[^}]+\}|\[[^\]]+\])$/.test(lastChild.value);
|
|
40
|
+
}
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Extracts heading information from content (read-only, no modifications)
|
|
45
|
+
*/
|
|
46
|
+
export function extractHeadingInfo(mdxContent) {
|
|
47
|
+
const headings = [];
|
|
48
|
+
// Parse the MDX content into an AST
|
|
49
|
+
let processedAst;
|
|
50
|
+
try {
|
|
51
|
+
const parseProcessor = unified()
|
|
52
|
+
.use(remarkParse)
|
|
53
|
+
.use(remarkFrontmatter, ['yaml', 'toml'])
|
|
54
|
+
.use(remarkMdx);
|
|
55
|
+
const ast = parseProcessor.parse(mdxContent);
|
|
56
|
+
processedAst = parseProcessor.runSync(ast);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
console.warn(`Failed to parse MDX content: ${error instanceof Error ? error.message : String(error)}`);
|
|
60
|
+
return [];
|
|
61
|
+
}
|
|
62
|
+
let position = 0;
|
|
63
|
+
visit(processedAst, 'heading', (heading) => {
|
|
64
|
+
const headingText = extractHeadingText(heading);
|
|
65
|
+
if (headingText) {
|
|
66
|
+
const slug = generateSlug(headingText);
|
|
67
|
+
headings.push({
|
|
68
|
+
text: headingText,
|
|
69
|
+
level: heading.depth,
|
|
70
|
+
slug,
|
|
71
|
+
position: position++,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
return headings;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Applies anchor IDs to translated content based on source heading mapping
|
|
79
|
+
*/
|
|
80
|
+
export function addExplicitAnchorIds(translatedContent, sourceHeadingMap, settings, sourcePath, translatedPath) {
|
|
81
|
+
const addedIds = [];
|
|
82
|
+
const useDivWrapping = settings?.options?.experimentalAddHeaderAnchorIds === 'mintlify';
|
|
83
|
+
// Extract headings from translated content
|
|
84
|
+
const translatedHeadings = extractHeadingInfo(translatedContent);
|
|
85
|
+
// Pre-processing validation: check if header counts match
|
|
86
|
+
if (sourceHeadingMap.length !== translatedHeadings.length) {
|
|
87
|
+
const sourceFile = sourcePath
|
|
88
|
+
? `Source file: ${sourcePath}`
|
|
89
|
+
: 'Source file';
|
|
90
|
+
const translatedFile = translatedPath
|
|
91
|
+
? `translated file: ${translatedPath}`
|
|
92
|
+
: 'translated file';
|
|
93
|
+
logWarning(`Header count mismatch detected! ${sourceFile} has ${sourceHeadingMap.length} headers but ${translatedFile} has ${translatedHeadings.length} headers. ` +
|
|
94
|
+
`This likely means your source file was edited after translation was requested, causing a mismatch between ` +
|
|
95
|
+
`the number of headers in your source file vs the translated file. Please re-translate this file to resolve the issue.`);
|
|
96
|
+
}
|
|
97
|
+
// Create ID mapping based on positional matching
|
|
98
|
+
const idMappings = new Map();
|
|
99
|
+
sourceHeadingMap.forEach((sourceHeading, index) => {
|
|
100
|
+
const translatedHeading = translatedHeadings[index];
|
|
101
|
+
// Match by position and level for safety
|
|
102
|
+
if (translatedHeading && translatedHeading.level === sourceHeading.level) {
|
|
103
|
+
idMappings.set(index, sourceHeading.slug);
|
|
104
|
+
addedIds.push({
|
|
105
|
+
heading: translatedHeading.text,
|
|
106
|
+
id: sourceHeading.slug,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
if (idMappings.size === 0) {
|
|
111
|
+
return {
|
|
112
|
+
content: translatedContent,
|
|
113
|
+
hasChanges: false,
|
|
114
|
+
addedIds: [],
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
// Apply IDs to translated content
|
|
118
|
+
let content;
|
|
119
|
+
if (useDivWrapping) {
|
|
120
|
+
content = applyDivWrappedIds(translatedContent, translatedHeadings, idMappings);
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
content = applyInlineIds(translatedContent, idMappings);
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
content,
|
|
127
|
+
hasChanges: addedIds.length > 0,
|
|
128
|
+
addedIds,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Adds inline {#id} syntax to headings (standard markdown approach)
|
|
133
|
+
*/
|
|
134
|
+
function applyInlineIds(translatedContent, idMappings) {
|
|
135
|
+
// Parse the translated content
|
|
136
|
+
let processedAst;
|
|
137
|
+
try {
|
|
138
|
+
const parseProcessor = unified()
|
|
139
|
+
.use(remarkParse)
|
|
140
|
+
.use(remarkFrontmatter, ['yaml', 'toml'])
|
|
141
|
+
.use(remarkMdx);
|
|
142
|
+
const ast = parseProcessor.parse(translatedContent);
|
|
143
|
+
processedAst = parseProcessor.runSync(ast);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
console.warn(`Failed to parse translated MDX content: ${error instanceof Error ? error.message : String(error)}`);
|
|
147
|
+
return translatedContent;
|
|
148
|
+
}
|
|
149
|
+
// Apply IDs to headings based on position
|
|
150
|
+
let headingIndex = 0;
|
|
151
|
+
visit(processedAst, 'heading', (heading) => {
|
|
152
|
+
const id = idMappings.get(headingIndex);
|
|
153
|
+
if (id) {
|
|
154
|
+
// Skip if heading already has explicit ID
|
|
155
|
+
if (hasExplicitId(heading, processedAst)) {
|
|
156
|
+
headingIndex++;
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
// Add the ID to the heading
|
|
160
|
+
const lastChild = heading.children[heading.children.length - 1];
|
|
161
|
+
if (lastChild?.type === 'text') {
|
|
162
|
+
lastChild.value += ` \\{#${id}\\}`;
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
// If last child is not text, add a new text node
|
|
166
|
+
heading.children.push({
|
|
167
|
+
type: 'text',
|
|
168
|
+
value: ` \\{#${id}\\}`,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
headingIndex++;
|
|
173
|
+
});
|
|
174
|
+
// Convert the modified AST back to MDX string
|
|
175
|
+
try {
|
|
176
|
+
const stringifyProcessor = unified()
|
|
177
|
+
.use(remarkFrontmatter, ['yaml', 'toml'])
|
|
178
|
+
.use(remarkMdx)
|
|
179
|
+
.use(escapeHtmlInTextNodes)
|
|
180
|
+
.use(remarkStringify, {
|
|
181
|
+
handlers: {
|
|
182
|
+
// Custom handler to prevent escaping of {#id} syntax
|
|
183
|
+
text(node) {
|
|
184
|
+
return node.value;
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
});
|
|
188
|
+
const outTree = stringifyProcessor.runSync(processedAst);
|
|
189
|
+
let content = stringifyProcessor.stringify(outTree);
|
|
190
|
+
// Handle newline formatting to match original input
|
|
191
|
+
if (content.endsWith('\n') && !translatedContent.endsWith('\n')) {
|
|
192
|
+
content = content.slice(0, -1);
|
|
193
|
+
}
|
|
194
|
+
// Preserve leading newlines from original content
|
|
195
|
+
if (translatedContent.startsWith('\n') && !content.startsWith('\n')) {
|
|
196
|
+
content = '\n' + content;
|
|
197
|
+
}
|
|
198
|
+
return content;
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
console.warn(`Failed to stringify translated MDX content: ${error instanceof Error ? error.message : String(error)}`);
|
|
202
|
+
return translatedContent;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Wraps headings in divs with IDs (Mintlify approach)
|
|
207
|
+
*/
|
|
208
|
+
function applyDivWrappedIds(translatedContent, translatedHeadings, idMappings) {
|
|
209
|
+
// Extract all heading lines from the translated markdown
|
|
210
|
+
const lines = translatedContent.split('\n');
|
|
211
|
+
const headingLines = [];
|
|
212
|
+
lines.forEach((line, index) => {
|
|
213
|
+
const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
|
|
214
|
+
if (headingMatch) {
|
|
215
|
+
const level = headingMatch[1].length;
|
|
216
|
+
headingLines.push({ line, level, index });
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
// Use string-based approach to wrap headings in divs
|
|
220
|
+
let content = translatedContent;
|
|
221
|
+
const headingsToWrap = [];
|
|
222
|
+
// Match translated headings with their corresponding lines by position and level
|
|
223
|
+
translatedHeadings.forEach((heading, position) => {
|
|
224
|
+
const id = idMappings.get(position);
|
|
225
|
+
if (id) {
|
|
226
|
+
// Find the corresponding original line for this heading
|
|
227
|
+
const matchingLine = headingLines.find((hl) => {
|
|
228
|
+
// Extract clean text from the original line for comparison
|
|
229
|
+
const lineCleanText = hl.line.replace(/^#{1,6}\s+/, '').trim();
|
|
230
|
+
// Create a version without markdown formatting for comparison
|
|
231
|
+
const cleanLineText = lineCleanText
|
|
232
|
+
.replace(/\*\*(.*?)\*\*/g, '$1') // Remove bold
|
|
233
|
+
.replace(/\*(.*?)\*/g, '$1') // Remove italic
|
|
234
|
+
.replace(/`(.*?)`/g, '$1') // Remove inline code
|
|
235
|
+
.replace(/\[(.*?)\]\(.*?\)/g, '$1') // Remove links, keep text
|
|
236
|
+
.trim();
|
|
237
|
+
return cleanLineText === heading.text && hl.level === heading.level;
|
|
238
|
+
});
|
|
239
|
+
if (matchingLine) {
|
|
240
|
+
headingsToWrap.push({
|
|
241
|
+
originalLine: matchingLine.line,
|
|
242
|
+
id,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
if (headingsToWrap.length > 0) {
|
|
248
|
+
// Process headings from longest to shortest original line to avoid partial matches
|
|
249
|
+
const sortedHeadings = headingsToWrap.sort((a, b) => b.originalLine.length - a.originalLine.length);
|
|
250
|
+
for (const heading of sortedHeadings) {
|
|
251
|
+
// Escape the original line for use in regex
|
|
252
|
+
const escapedLine = heading.originalLine.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
253
|
+
const headingPattern = new RegExp(`^${escapedLine}\\s*$`, 'gm');
|
|
254
|
+
content = content.replace(headingPattern, (match) => {
|
|
255
|
+
return `<div id="${heading.id}">\n ${match.trim()}\n</div>\n`;
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return content;
|
|
260
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Settings, SupportedFrameworks } from '../types/index.js';
|
|
2
|
+
type Credentials = {
|
|
3
|
+
apiKey: string;
|
|
4
|
+
projectId: string;
|
|
5
|
+
};
|
|
6
|
+
export declare function retrieveCredentials(settings: Settings, keyType: 'development' | 'production'): Promise<Credentials>;
|
|
7
|
+
export declare function generateCredentialsSession(url: string, keyType: 'development' | 'production'): Promise<{
|
|
8
|
+
sessionId: string;
|
|
9
|
+
}>;
|
|
10
|
+
export declare function areCredentialsSet(): string | undefined;
|
|
11
|
+
export declare function setCredentials(credentials: Credentials, type: 'development' | 'production', framework?: SupportedFrameworks, cwd?: string): Promise<void>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createSpinner, logErrorAndExit, logMessage, } from '../console/logging.js';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
// Fetches project ID and API key by opening the dashboard in the browser
|
|
6
|
+
export async function retrieveCredentials(settings, keyType) {
|
|
7
|
+
// Generate a session ID
|
|
8
|
+
const { sessionId } = await generateCredentialsSession(settings.baseUrl, keyType);
|
|
9
|
+
const urlToOpen = `${settings.dashboardUrl}/cli/wizard/${sessionId}`;
|
|
10
|
+
await import('open').then((open) => open.default(urlToOpen, {
|
|
11
|
+
wait: false,
|
|
12
|
+
}));
|
|
13
|
+
logMessage(`${chalk.dim(`If the browser window didn't open automatically, please open the following link:`)}\n\n${chalk.cyan(urlToOpen)}`);
|
|
14
|
+
const spinner = createSpinner('dots');
|
|
15
|
+
spinner.start('Waiting for response from dashboard...');
|
|
16
|
+
const credentials = await new Promise(async (resolve, reject) => {
|
|
17
|
+
const interval = setInterval(async () => {
|
|
18
|
+
// Ping the dashboard to see if the credentials are set
|
|
19
|
+
try {
|
|
20
|
+
const res = await fetch(`${settings.baseUrl}/cli/wizard/${sessionId}`, {
|
|
21
|
+
method: 'GET',
|
|
22
|
+
});
|
|
23
|
+
if (res.status === 200) {
|
|
24
|
+
const data = await res.json();
|
|
25
|
+
resolve(data);
|
|
26
|
+
clearInterval(interval);
|
|
27
|
+
clearTimeout(timeout);
|
|
28
|
+
fetch(`${settings.baseUrl}/cli/wizard/${sessionId}`, {
|
|
29
|
+
method: 'DELETE',
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
catch (err) {
|
|
34
|
+
console.error(err);
|
|
35
|
+
}
|
|
36
|
+
}, 2000);
|
|
37
|
+
// timeout after 1 hour
|
|
38
|
+
const timeout = setTimeout(() => {
|
|
39
|
+
spinner.stop('Timed out');
|
|
40
|
+
clearInterval(interval);
|
|
41
|
+
logErrorAndExit('Timed out waiting for response from dashboard');
|
|
42
|
+
}, 1000 * 60 * 60);
|
|
43
|
+
});
|
|
44
|
+
spinner.stop('Received credentials');
|
|
45
|
+
return credentials;
|
|
46
|
+
}
|
|
47
|
+
export async function generateCredentialsSession(url, keyType) {
|
|
48
|
+
const res = await fetch(`${url}/cli/wizard/session`, {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
headers: {
|
|
51
|
+
'Content-Type': 'application/json',
|
|
52
|
+
},
|
|
53
|
+
body: JSON.stringify({
|
|
54
|
+
keyType,
|
|
55
|
+
}),
|
|
56
|
+
});
|
|
57
|
+
if (!res.ok) {
|
|
58
|
+
logErrorAndExit('Failed to generate credentials session');
|
|
59
|
+
}
|
|
60
|
+
return await res.json();
|
|
61
|
+
}
|
|
62
|
+
// Checks if the credentials are set in the environment variables
|
|
63
|
+
export function areCredentialsSet() {
|
|
64
|
+
return process.env.GT_PROJECT_ID && process.env.GT_API_KEY;
|
|
65
|
+
}
|
|
66
|
+
// Sets the credentials in .env.local file
|
|
67
|
+
export async function setCredentials(credentials, type, framework, cwd = process.cwd()) {
|
|
68
|
+
const envFile = path.join(cwd, '.env.local');
|
|
69
|
+
let envContent = '';
|
|
70
|
+
// Check if .env.local exists, create it if it doesn't
|
|
71
|
+
if (!fs.existsSync(envFile)) {
|
|
72
|
+
// File doesn't exist, create it
|
|
73
|
+
await fs.promises.writeFile(envFile, '', 'utf8');
|
|
74
|
+
// Add .env.local to .gitignore if it exists
|
|
75
|
+
const gitignoreFile = path.join(cwd, '.gitignore');
|
|
76
|
+
if (fs.existsSync(gitignoreFile)) {
|
|
77
|
+
const gitignoreContent = await fs.promises.readFile(gitignoreFile, 'utf8');
|
|
78
|
+
if (!gitignoreContent.includes('.env.local')) {
|
|
79
|
+
await fs.promises.appendFile(gitignoreFile, '\n.env.local\n', 'utf8');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
// Create .gitignore file with .env.local
|
|
84
|
+
await fs.promises.writeFile(gitignoreFile, '.env.local\n', 'utf8');
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
// Read existing content
|
|
89
|
+
envContent = await fs.promises.readFile(envFile, 'utf8');
|
|
90
|
+
}
|
|
91
|
+
// Always append the credentials to the file
|
|
92
|
+
let prefix = '';
|
|
93
|
+
if (framework === 'next-pages') {
|
|
94
|
+
prefix = 'NEXT_PUBLIC_';
|
|
95
|
+
}
|
|
96
|
+
else if (framework === 'vite') {
|
|
97
|
+
prefix = 'VITE_';
|
|
98
|
+
}
|
|
99
|
+
else if (framework === 'gatsby') {
|
|
100
|
+
prefix = 'GATSBY_';
|
|
101
|
+
}
|
|
102
|
+
else if (framework === 'react') {
|
|
103
|
+
prefix = 'REACT_APP_';
|
|
104
|
+
}
|
|
105
|
+
else if (framework === 'redwood') {
|
|
106
|
+
prefix = 'REDWOOD_ENV_';
|
|
107
|
+
}
|
|
108
|
+
envContent += `\n${prefix}GT_PROJECT_ID=${credentials.projectId}\n`;
|
|
109
|
+
if (type === 'development') {
|
|
110
|
+
envContent += `${prefix || ''}GT_DEV_API_KEY=${credentials.apiKey}\n`;
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
envContent += `GT_API_KEY=${credentials.apiKey}\n`;
|
|
114
|
+
}
|
|
115
|
+
// Ensure we don't have excessive newlines
|
|
116
|
+
envContent = envContent.replace(/\n{3,}/g, '\n\n').trim() + '\n';
|
|
117
|
+
// Write the updated content back to the file
|
|
118
|
+
await fs.promises.writeFile(envFile, envContent, 'utf8');
|
|
119
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { createFileMapping } from '../formats/files/fileMapping.js';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
export default async function flattenJsonFiles(settings) {
|
|
4
|
+
if (!settings.files ||
|
|
5
|
+
(Object.keys(settings.files.placeholderPaths).length === 1 &&
|
|
6
|
+
settings.files.placeholderPaths.gt)) {
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
const { resolvedPaths: sourceFiles } = settings.files;
|
|
10
|
+
const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths, settings.locales, settings.defaultLocale);
|
|
11
|
+
await Promise.all(Object.values(fileMapping).map(async (filesMap) => {
|
|
12
|
+
const targetFiles = Object.values(filesMap).filter((path) => path.endsWith('.json'));
|
|
13
|
+
await Promise.all(targetFiles.map(async (file) => {
|
|
14
|
+
// Read each json file
|
|
15
|
+
const json = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
16
|
+
// Flatten the json
|
|
17
|
+
const flattenedJson = flattenJson(json);
|
|
18
|
+
// Write the flattened json to the target file
|
|
19
|
+
await fs.promises.writeFile(file, JSON.stringify(flattenedJson, null, 2));
|
|
20
|
+
return flattenedJson;
|
|
21
|
+
}));
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
function flattenJson(json, prefix = '') {
|
|
25
|
+
const result = {};
|
|
26
|
+
for (const [key, value] of Object.entries(json)) {
|
|
27
|
+
const newKey = prefix ? `${prefix}.${key}` : key;
|
|
28
|
+
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
|
29
|
+
Object.assign(result, flattenJson(value, newKey));
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
result[newKey] = value;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
package/dist/utils/gt.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
/**
|
|
3
|
+
* Hashes a string using SHA-256 algorithm.
|
|
4
|
+
* @param {string} string - The string to be hashed.
|
|
5
|
+
* @returns {string} The hashed string.
|
|
6
|
+
*/
|
|
7
|
+
export function hashStringSync(string) {
|
|
8
|
+
const hash = crypto.createHash('sha256');
|
|
9
|
+
hash.update(string);
|
|
10
|
+
return hash.digest('hex');
|
|
11
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getAuthHeaders(projectId: string, apiKey: string): Record<string, string>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export function getAuthHeaders(projectId, apiKey) {
|
|
2
|
+
const authHeaders = {
|
|
3
|
+
'x-gt-project-id': projectId,
|
|
4
|
+
};
|
|
5
|
+
if (apiKey) {
|
|
6
|
+
if (apiKey.startsWith('gtx-internal-')) {
|
|
7
|
+
authHeaders['x-gt-internal-api-key'] = apiKey;
|
|
8
|
+
}
|
|
9
|
+
else {
|
|
10
|
+
authHeaders['x-gt-api-key'] = apiKey;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
return authHeaders;
|
|
14
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { PackageManager } from './packageManager.js';
|
|
2
|
+
export declare function installPackage(packageName: string, packageManager: PackageManager, asDevDependency?: boolean, cwd?: string): Promise<void>;
|
|
3
|
+
export declare function installPackageGlobal(packageName: string, version?: string): Promise<void>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { spawn } from 'child_process';
|
|
3
|
+
import { logError, logInfo } from '../console/logging.js';
|
|
4
|
+
export async function installPackage(packageName, packageManager, asDevDependency, cwd = process.cwd()) {
|
|
5
|
+
return new Promise((resolve, reject) => {
|
|
6
|
+
const command = packageManager.name;
|
|
7
|
+
const args = [packageManager.installCommand, packageName];
|
|
8
|
+
if (asDevDependency) {
|
|
9
|
+
args.push(packageManager.devDependencyFlag);
|
|
10
|
+
}
|
|
11
|
+
const childProcess = spawn(command, args, {
|
|
12
|
+
stdio: ['pipe', 'ignore', 'pipe'],
|
|
13
|
+
cwd,
|
|
14
|
+
});
|
|
15
|
+
let errorOutput = '';
|
|
16
|
+
if (childProcess.stderr) {
|
|
17
|
+
childProcess.stderr.on('data', (data) => {
|
|
18
|
+
errorOutput += data.toString();
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
childProcess.on('error', (error) => {
|
|
22
|
+
logError(chalk.red(`Installation error: ${error.message}`));
|
|
23
|
+
logInfo(`Please manually install ${packageName} with: ${packageManager.name} ${packageManager.installCommand} ${packageName}`);
|
|
24
|
+
reject(error);
|
|
25
|
+
});
|
|
26
|
+
childProcess.on('close', (code) => {
|
|
27
|
+
if (code === 0) {
|
|
28
|
+
resolve();
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
logError(chalk.red(`Installation failed with exit code ${code}`));
|
|
32
|
+
if (errorOutput) {
|
|
33
|
+
logError(chalk.red(`Error details: ${errorOutput}`));
|
|
34
|
+
}
|
|
35
|
+
logInfo(`Please manually install ${packageName} with: ${packageManager.name} ${packageManager.installCommand} ${packageName}`);
|
|
36
|
+
reject(new Error(`Process exited with code ${code}`));
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
export async function installPackageGlobal(packageName, version) {
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
const command = 'npm';
|
|
44
|
+
const args = [
|
|
45
|
+
'install',
|
|
46
|
+
'-g',
|
|
47
|
+
version ? `${packageName}@${version}` : packageName,
|
|
48
|
+
];
|
|
49
|
+
const childProcess = spawn(command, args, {
|
|
50
|
+
stdio: ['pipe', 'ignore', 'pipe'],
|
|
51
|
+
});
|
|
52
|
+
let errorOutput = '';
|
|
53
|
+
if (childProcess.stderr) {
|
|
54
|
+
childProcess.stderr.on('data', (data) => {
|
|
55
|
+
errorOutput += data.toString();
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
childProcess.on('error', (error) => {
|
|
59
|
+
logError(chalk.red(`Installation error: ${error.message}`));
|
|
60
|
+
logInfo(`Please manually install ${packageName} with: npm install -g ${packageName}`);
|
|
61
|
+
reject(error);
|
|
62
|
+
});
|
|
63
|
+
childProcess.on('close', (code) => {
|
|
64
|
+
if (code === 0) {
|
|
65
|
+
resolve();
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
logError(chalk.red(`Installation failed with exit code ${code}`));
|
|
69
|
+
if (errorOutput) {
|
|
70
|
+
logError(chalk.red(`Error details: ${errorOutput}`));
|
|
71
|
+
}
|
|
72
|
+
logInfo(`Please manually install ${packageName} with: npm install -g ${packageName}`);
|
|
73
|
+
reject(new Error(`Process exited with code ${code}`));
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Settings } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Localizes static imports in content files.
|
|
4
|
+
* Currently only supported for md and mdx files. (/docs/ -> /[locale]/docs/)
|
|
5
|
+
* @param settings - The settings object containing the project configuration.
|
|
6
|
+
* @returns void
|
|
7
|
+
*
|
|
8
|
+
* @TODO This is an experimental feature, and only works in very specific cases. This needs to be improved before
|
|
9
|
+
* it can be enabled by default.
|
|
10
|
+
*
|
|
11
|
+
* Before this becomes a non-experimental feature, we need to:
|
|
12
|
+
* - Support more file types
|
|
13
|
+
* - Support more complex paths
|
|
14
|
+
*/
|
|
15
|
+
export default function localizeStaticImports(settings: Settings): Promise<void>;
|