gtx-cli 0.0.2 → 1.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/api/fetchTranslations.d.ts +10 -0
  2. package/dist/{fs/saveTranslations.js → api/fetchTranslations.js} +12 -27
  3. package/dist/api/sendUpdates.d.ts +18 -0
  4. package/dist/api/sendUpdates.js +72 -0
  5. package/dist/api/waitForUpdates.d.ts +10 -0
  6. package/dist/api/waitForUpdates.js +10 -0
  7. package/dist/cli/base.d.ts +7 -1
  8. package/dist/cli/base.js +182 -2
  9. package/dist/cli/next.d.ts +3 -1
  10. package/dist/cli/next.js +12 -8
  11. package/dist/cli/react.d.ts +2 -0
  12. package/dist/cli/react.js +70 -143
  13. package/dist/config/generateSettings.d.ts +7 -0
  14. package/dist/config/generateSettings.js +73 -0
  15. package/dist/console/errors.d.ts +8 -0
  16. package/dist/console/errors.js +9 -1
  17. package/dist/formats/gt/save.d.ts +9 -0
  18. package/dist/formats/gt/save.js +27 -0
  19. package/dist/formats/json/save.d.ts +9 -0
  20. package/dist/formats/json/save.js +60 -0
  21. package/dist/formats/json/translate.d.ts +15 -0
  22. package/dist/formats/json/translate.js +61 -0
  23. package/dist/fs/config/setupConfig.d.ts +6 -1
  24. package/dist/fs/config/setupConfig.js +11 -3
  25. package/dist/fs/determineFramework.d.ts +2 -0
  26. package/dist/fs/determineFramework.js +46 -0
  27. package/dist/fs/findFilepath.d.ts +14 -0
  28. package/dist/fs/findFilepath.js +29 -0
  29. package/dist/fs/saveJSON.d.ts +1 -0
  30. package/dist/fs/saveJSON.js +13 -0
  31. package/dist/fs/utils.d.ts +1 -0
  32. package/dist/fs/utils.js +19 -0
  33. package/dist/index.js +7 -67
  34. package/dist/react/jsx/parse/parseStringFunction.d.ts +12 -0
  35. package/dist/react/jsx/parse/parseStringFunction.js +120 -0
  36. package/dist/react/jsx/utils/parseJsx.js +1 -1
  37. package/dist/react/jsx/utils/parseStringFunction.js +1 -1
  38. package/dist/react/parse/createDictionaryUpdates.js +1 -1
  39. package/dist/react/updates/createDictionaryUpdates.d.ts +5 -0
  40. package/dist/react/updates/createDictionaryUpdates.js +76 -0
  41. package/dist/react/updates/createInlineUpdates.d.ts +5 -0
  42. package/dist/react/updates/createInlineUpdates.js +141 -0
  43. package/dist/react/updates/scanForContent.d.ts +13 -0
  44. package/dist/react/updates/scanForContent.js +200 -0
  45. package/dist/react/utils/flattenDictionary.d.ts +11 -1
  46. package/dist/react/utils/flattenDictionary.js +40 -0
  47. package/dist/react/utils/getEntryAndMetadata.d.ts +2 -2
  48. package/dist/types/api.d.ts +6 -0
  49. package/dist/types/data.d.ts +31 -0
  50. package/dist/{types.d.ts → types/index.d.ts} +21 -6
  51. package/dist/types/index.js +2 -0
  52. package/package.json +3 -3
  53. package/dist/fs/saveTranslations.d.ts +0 -3
  54. package/dist/react/types.d.ts +0 -13
  55. /package/dist/{react/types.js → types/api.js} +0 -0
  56. /package/dist/{types.js → types/data.js} +0 -0
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = createConfig;
6
+ exports.default = createOrUpdateConfig;
7
7
  const fs_1 = __importDefault(require("fs"));
8
8
  const console_1 = require("../../console/console");
9
9
  /**
@@ -13,9 +13,11 @@ const console_1 = require("../../console/console");
13
13
  * @param {string} configFilepath - The path to the config file.
14
14
  * @param {Record<string, any>} configObject - The config object to write if the file does not exist.
15
15
  */
16
- function createConfig(configFilepath, projectId, defaultLocale) {
16
+ function createOrUpdateConfig(configFilepath, options) {
17
17
  // Filter out empty string values from the config object
18
- const newContent = Object.assign(Object.assign({}, (projectId && { projectId })), (defaultLocale && { defaultLocale }));
18
+ const newContent = Object.assign(Object.assign(Object.assign({}, (options.projectId && { projectId: options.projectId })), (options.defaultLocale && { defaultLocale: options.defaultLocale })), (options.translationsDir && {
19
+ translationsDir: options.translationsDir,
20
+ }));
19
21
  try {
20
22
  // if file exists
21
23
  let oldContent = {};
@@ -24,6 +26,12 @@ function createConfig(configFilepath, projectId, defaultLocale) {
24
26
  }
25
27
  // merge old and new content
26
28
  const mergedContent = Object.assign(Object.assign({}, oldContent), newContent);
29
+ // Add locales to mergedContent if they exist
30
+ if (options.locales) {
31
+ mergedContent.locales = mergedContent.locales
32
+ ? [...new Set([...mergedContent.locales, ...options.locales])]
33
+ : options.locales;
34
+ }
27
35
  // write to file
28
36
  const mergedJsonContent = JSON.stringify(mergedContent, null, 2);
29
37
  fs_1.default.writeFileSync(configFilepath, mergedJsonContent, 'utf-8');
@@ -0,0 +1,2 @@
1
+ import { SupportedLibraries } from '../types';
2
+ export declare function determineLibrary(): SupportedLibraries;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.determineLibrary = determineLibrary;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const fs_1 = __importDefault(require("fs"));
10
+ function determineLibrary() {
11
+ try {
12
+ // Get the current working directory (where the CLI is being run)
13
+ const cwd = process.cwd();
14
+ const packageJsonPath = path_1.default.join(cwd, 'package.json');
15
+ // Check if package.json exists
16
+ if (!fs_1.default.existsSync(packageJsonPath)) {
17
+ console.log(chalk_1.default.red('No package.json found in the current directory. Please run this command from the root of your project.'));
18
+ return 'base';
19
+ }
20
+ // Read and parse package.json
21
+ const packageJson = JSON.parse(fs_1.default.readFileSync(packageJsonPath, 'utf8'));
22
+ const dependencies = Object.assign(Object.assign({}, packageJson.dependencies), packageJson.devDependencies);
23
+ // Check for gt-next or gt-react in dependencies
24
+ if (dependencies['gt-next']) {
25
+ return 'gt-next';
26
+ }
27
+ else if (dependencies['gt-react']) {
28
+ return 'gt-react';
29
+ }
30
+ else if (dependencies['next-intl']) {
31
+ return 'next-intl';
32
+ }
33
+ else if (dependencies['react-i18next']) {
34
+ return 'react-i18next';
35
+ }
36
+ else if (dependencies['next-i18next']) {
37
+ return 'next-i18next';
38
+ }
39
+ // Fallback to base if neither is found
40
+ return 'base';
41
+ }
42
+ catch (error) {
43
+ console.error('Error determining framework:', error);
44
+ return 'base';
45
+ }
46
+ }
@@ -13,3 +13,17 @@ export default function findFilepath(paths: string[], errorMessage?: string): st
13
13
  */
14
14
  export declare function findFilepaths(paths: string[], errorMessage?: string): string[];
15
15
  export declare function getRelativePath(file: string, srcDirectory: string): string;
16
+ /**
17
+ * Find a file in a directory based on a wildcard pattern.
18
+ * @param {string} filePattern - The wildcard pattern to search for.
19
+ * @param {string} file - The file to search for.
20
+ * @returns {string} - The path to the file.
21
+ */
22
+ export declare function findFile(filePattern: string, file: string): string;
23
+ /**
24
+ * Find a file in a directory.
25
+ * @param {string} dir - The directory to search in.
26
+ * @param {string} file - The file to search for.
27
+ * @returns {string} - The path to the file.
28
+ */
29
+ export declare function findFileInDir(dir: string, file: string): string;
@@ -6,6 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.default = findFilepath;
7
7
  exports.findFilepaths = findFilepaths;
8
8
  exports.getRelativePath = getRelativePath;
9
+ exports.findFile = findFile;
10
+ exports.findFileInDir = findFileInDir;
9
11
  const fs_1 = __importDefault(require("fs"));
10
12
  const path_1 = __importDefault(require("path"));
11
13
  /**
@@ -47,3 +49,30 @@ function getRelativePath(file, srcDirectory) {
47
49
  .map((segment) => segment.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase()) // Convert each segment to snake case
48
50
  .join('.'); // Rejoin with dots
49
51
  }
52
+ /**
53
+ * Find a file in a directory based on a wildcard pattern.
54
+ * @param {string} filePattern - The wildcard pattern to search for.
55
+ * @param {string} file - The file to search for.
56
+ * @returns {string} - The path to the file.
57
+ */
58
+ function findFile(filePattern, file) {
59
+ // Handle wildcard pattern by replacing the wildcard with the file parameter
60
+ const resolvedPath = filePattern.replace(/\*/, file);
61
+ if (fs_1.default.existsSync(resolvedPath)) {
62
+ return fs_1.default.readFileSync(resolvedPath, 'utf8');
63
+ }
64
+ return '';
65
+ }
66
+ /**
67
+ * Find a file in a directory.
68
+ * @param {string} dir - The directory to search in.
69
+ * @param {string} file - The file to search for.
70
+ * @returns {string} - The path to the file.
71
+ */
72
+ function findFileInDir(dir, file) {
73
+ const resolvedPath = path_1.default.join(dir, file);
74
+ if (fs_1.default.existsSync(resolvedPath)) {
75
+ return fs_1.default.readFileSync(resolvedPath, 'utf8');
76
+ }
77
+ return '';
78
+ }
@@ -0,0 +1 @@
1
+ export declare function saveJSON(filepath: string, data: Record<string, any>): void;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.saveJSON = saveJSON;
7
+ const path_1 = __importDefault(require("path"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ function saveJSON(filepath, data) {
10
+ // Ensure directory exists
11
+ fs_1.default.mkdirSync(path_1.default.dirname(filepath), { recursive: true });
12
+ fs_1.default.writeFileSync(filepath, JSON.stringify(data, null, 2));
13
+ }
@@ -0,0 +1 @@
1
+ export declare function resolveProjectId(): string | undefined;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveProjectId = resolveProjectId;
4
+ function resolveProjectId() {
5
+ const CANDIDATES = [
6
+ process.env.GT_PROJECT_ID, // any server side, Remix
7
+ process.env.NEXT_PUBLIC_GT_PROJECT_ID, // Next.js
8
+ process.env.VITE_GT_PROJECT_ID, // Vite
9
+ process.env.REACT_APP_GT_PROJECT_ID, // Create React App
10
+ process.env.REDWOOD_ENV_GT_PROJECT_ID, // RedwoodJS
11
+ process.env.GATSBY_GT_PROJECT_ID, // Gatsby
12
+ process.env.EXPO_PUBLIC_GT_PROJECT_ID, // Expo (React Native)
13
+ process.env.RAZZLE_GT_PROJECT_ID, // Razzle
14
+ process.env.UMI_GT_PROJECT_ID, // UmiJS
15
+ process.env.BLITZ_PUBLIC_GT_PROJECT_ID, // Blitz.js
16
+ process.env.PUBLIC_GT_PROJECT_ID, // WMR, Qwik (general "public" convention)
17
+ ];
18
+ return CANDIDATES.find((projectId) => projectId !== undefined);
19
+ }
package/dist/index.js CHANGED
@@ -1,37 +1,4 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.BaseCLI = void 0;
37
4
  exports.default = main;
@@ -39,46 +6,19 @@ const base_1 = require("./cli/base");
39
6
  Object.defineProperty(exports, "BaseCLI", { enumerable: true, get: function () { return base_1.BaseCLI; } });
40
7
  const next_1 = require("./cli/next");
41
8
  const react_1 = require("./cli/react");
42
- const fs = __importStar(require("fs"));
43
- const path = __importStar(require("path"));
44
- function determineFramework() {
45
- try {
46
- // Get the current working directory (where the CLI is being run)
47
- const cwd = process.cwd();
48
- const packageJsonPath = path.join(cwd, 'package.json');
49
- // Check if package.json exists
50
- if (!fs.existsSync(packageJsonPath)) {
51
- console.log('No package.json found in the current directory.');
52
- return 'base';
53
- }
54
- // Read and parse package.json
55
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
56
- const dependencies = Object.assign(Object.assign({}, packageJson.dependencies), packageJson.devDependencies);
57
- // Check for gt-next or gt-react in dependencies
58
- if (dependencies['gt-next']) {
59
- return 'next';
60
- }
61
- else if (dependencies['gt-react']) {
62
- return 'react';
63
- }
64
- // Fallback to base if neither is found
65
- return 'base';
66
- }
67
- catch (error) {
68
- console.error('Error determining framework:', error);
69
- return 'base';
70
- }
71
- }
9
+ const determineFramework_1 = require("./fs/determineFramework");
72
10
  function main() {
73
- const framework = determineFramework();
11
+ const library = (0, determineFramework_1.determineLibrary)();
74
12
  let cli;
75
- if (framework === 'next') {
13
+ if (library === 'gt-next') {
76
14
  cli = new next_1.NextCLI();
77
15
  }
78
- else if (framework === 'react') {
16
+ else if (library === 'gt-react') {
79
17
  cli = new react_1.ReactCLI();
80
18
  }
81
19
  else {
82
- cli = new base_1.BaseCLI();
20
+ cli = new base_1.BaseCLI(library);
83
21
  }
22
+ cli.init();
23
+ cli.execute();
84
24
  }
@@ -0,0 +1,12 @@
1
+ import { NodePath } from '@babel/traverse';
2
+ import { Updates } from '../../../types';
3
+ export declare const attributes: string[];
4
+ /**
5
+ * For the following example code:
6
+ * const tx = useGT();
7
+ * tx('string to translate', { id: 'exampleId', context: 'exampleContext' });
8
+ *
9
+ * This function will find all call expressions of useGT(), then find all call expressions
10
+ * of the subsequent tx() calls, and append the content and metadata to the updates array.
11
+ */
12
+ export declare function parseStrings(importName: string, path: NodePath, updates: Updates, errors: string[], file: string): void;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.attributes = void 0;
40
+ exports.parseStrings = parseStrings;
41
+ const generaltranslation_1 = require("generaltranslation");
42
+ const t = __importStar(require("@babel/types"));
43
+ const evaluateJsx_1 = require("../evaluateJsx");
44
+ const warnings_1 = require("../../../console/warnings");
45
+ const generator_1 = __importDefault(require("@babel/generator"));
46
+ exports.attributes = ['id', 'context'];
47
+ /**
48
+ * For the following example code:
49
+ * const tx = useGT();
50
+ * tx('string to translate', { id: 'exampleId', context: 'exampleContext' });
51
+ *
52
+ * This function will find all call expressions of useGT(), then find all call expressions
53
+ * of the subsequent tx() calls, and append the content and metadata to the updates array.
54
+ */
55
+ function parseStrings(importName, path, updates, errors, file) {
56
+ var _a;
57
+ (_a = path.scope.bindings[importName]) === null || _a === void 0 ? void 0 : _a.referencePaths.forEach((refPath) => {
58
+ var _a;
59
+ // Find call expressions of useGT() / await getGT()
60
+ const callExpr = refPath.findParent((p) => p.isCallExpression());
61
+ if (callExpr) {
62
+ // Get the parent, handling both await and non-await cases
63
+ const parentPath = callExpr.parentPath;
64
+ const effectiveParent = (parentPath === null || parentPath === void 0 ? void 0 : parentPath.node.type) === 'AwaitExpression'
65
+ ? parentPath.parentPath
66
+ : parentPath;
67
+ if (effectiveParent &&
68
+ effectiveParent.node.type === 'VariableDeclarator' &&
69
+ effectiveParent.node.id.type === 'Identifier') {
70
+ const tFuncName = effectiveParent.node.id.name;
71
+ // Get the scope from the variable declaration
72
+ const variableScope = effectiveParent.scope;
73
+ (_a = variableScope.bindings[tFuncName]) === null || _a === void 0 ? void 0 : _a.referencePaths.forEach((tPath) => {
74
+ if (tPath.parent.type === 'CallExpression' &&
75
+ tPath.parent.arguments.length > 0) {
76
+ const arg = tPath.parent.arguments[0];
77
+ if (arg.type === 'StringLiteral' ||
78
+ (t.isTemplateLiteral(arg) && arg.expressions.length === 0)) {
79
+ const source = arg.type === 'StringLiteral'
80
+ ? arg.value
81
+ : arg.quasis[0].value.raw;
82
+ // split the string into content (same as runtime behavior)
83
+ const content = (0, generaltranslation_1.splitStringToContent)(source);
84
+ // get metadata and id from options
85
+ const options = tPath.parent.arguments[1];
86
+ let metadata = {};
87
+ if (options && options.type === 'ObjectExpression') {
88
+ options.properties.forEach((prop) => {
89
+ if (prop.type === 'ObjectProperty' &&
90
+ prop.key.type === 'Identifier') {
91
+ const attribute = prop.key.name;
92
+ if (exports.attributes.includes(attribute) &&
93
+ t.isExpression(prop.value)) {
94
+ const result = (0, evaluateJsx_1.isStaticExpression)(prop.value);
95
+ if (!result.isStatic) {
96
+ errors.push((0, warnings_1.warnNonStaticExpression)(file, attribute, (0, generator_1.default)(prop.value).code));
97
+ }
98
+ if (result.isStatic && result.value) {
99
+ metadata[attribute] = result.value;
100
+ }
101
+ }
102
+ }
103
+ });
104
+ }
105
+ updates.push({
106
+ type: 'JSX',
107
+ source: content,
108
+ metadata,
109
+ });
110
+ }
111
+ else if (t.isTemplateLiteral(arg)) {
112
+ // warn if template literal
113
+ errors.push((0, warnings_1.warnTemplateLiteral)(file, (0, generator_1.default)(arg).code));
114
+ }
115
+ }
116
+ });
117
+ }
118
+ }
119
+ });
120
+ }
@@ -228,7 +228,7 @@ function parseJSXElement(importAliases, node, updates, errors, file) {
228
228
  // <T> is valid here
229
229
  // displayFoundTMessage(file, id);
230
230
  updates.push({
231
- type: 'jsx',
231
+ type: 'JSX',
232
232
  source: componentObj.tree,
233
233
  metadata: componentObj.props,
234
234
  });
@@ -103,7 +103,7 @@ function parseStrings(importName, path, updates, errors, file) {
103
103
  });
104
104
  }
105
105
  updates.push({
106
- type: 'content',
106
+ type: 'JSX',
107
107
  source: content,
108
108
  metadata,
109
109
  });
@@ -67,7 +67,7 @@ function createDictionaryUpdates(options, esbuildConfig) {
67
67
  // This hash isn't actually used by the GT API, just for consistency sake
68
68
  hash: (0, id_1.hashJsxChildren)(Object.assign(Object.assign({ source }, (context && { context })), (id && { id }))) });
69
69
  updates.push({
70
- type: 'content',
70
+ type: 'JSX',
71
71
  source,
72
72
  metadata,
73
73
  });
@@ -0,0 +1,5 @@
1
+ import { BuildOptions } from 'esbuild';
2
+ import { Options, Updates } from '../../types';
3
+ export default function createDictionaryUpdates(options: Options & {
4
+ dictionary: string;
5
+ }, esbuildConfig: BuildOptions): Promise<Updates>;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.default = createDictionaryUpdates;
16
+ const react_1 = __importDefault(require("react"));
17
+ const fs_1 = __importDefault(require("fs"));
18
+ const path_1 = __importDefault(require("path"));
19
+ const os_1 = __importDefault(require("os"));
20
+ const esbuild_1 = require("esbuild");
21
+ const internal_1 = require("gt-react/internal");
22
+ const generaltranslation_1 = require("generaltranslation");
23
+ const loadJSON_1 = __importDefault(require("../../fs/loadJSON"));
24
+ const id_1 = require("generaltranslation/id");
25
+ function createDictionaryUpdates(options, esbuildConfig) {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ let dictionary;
28
+ // ---- HANDLE JSON STRING DICTIONARY ----- //
29
+ if (options.dictionary.endsWith('.json')) {
30
+ dictionary = (0, internal_1.flattenDictionary)((0, loadJSON_1.default)(options.dictionary) || {});
31
+ }
32
+ // ----- HANDLE REACT DICTIONARY ---- //
33
+ else {
34
+ const result = yield (0, esbuild_1.build)(Object.assign(Object.assign({}, esbuildConfig), { entryPoints: [options.dictionary], write: false }));
35
+ const bundledCode = result.outputFiles[0].text;
36
+ const tempFilePath = path_1.default.join(os_1.default.tmpdir(), 'bundled-dictionary.js');
37
+ fs_1.default.writeFileSync(tempFilePath, bundledCode);
38
+ globalThis.React = react_1.default;
39
+ // Load the module using require
40
+ let dictionaryModule;
41
+ try {
42
+ dictionaryModule = require(tempFilePath);
43
+ }
44
+ catch (error) {
45
+ console.error(`Failed to load the bundled dictionary code:`, error);
46
+ process.exit(1);
47
+ }
48
+ finally {
49
+ // Clean up the temporary file
50
+ fs_1.default.unlinkSync(tempFilePath);
51
+ }
52
+ dictionary = (0, internal_1.flattenDictionary)(dictionaryModule.default ||
53
+ dictionaryModule.dictionary ||
54
+ dictionaryModule);
55
+ }
56
+ if (!Object.keys(dictionary).length)
57
+ throw new Error(`Dictionary filepath provided: "${options.dictionary}", but no entries found.`);
58
+ // ----- CREATE PARTIAL UPDATES ----- //
59
+ let updates = [];
60
+ for (const id of Object.keys(dictionary)) {
61
+ let { entry, metadata: props, // context, etc.
62
+ } = (0, internal_1.getEntryAndMetadata)(dictionary[id]);
63
+ const source = (0, generaltranslation_1.splitStringToContent)(entry);
64
+ const context = props === null || props === void 0 ? void 0 : props.context;
65
+ const metadata = Object.assign(Object.assign({ id }, (context && { context })), {
66
+ // This hash isn't actually used by the GT API, just for consistency sake
67
+ hash: (0, id_1.hashJsxChildren)(Object.assign(Object.assign({ source }, (context && { context })), (id && { id }))) });
68
+ updates.push({
69
+ type: 'JSX',
70
+ source,
71
+ metadata,
72
+ });
73
+ }
74
+ return updates;
75
+ });
76
+ }
@@ -0,0 +1,5 @@
1
+ import { Options, Updates } from '../../types';
2
+ export default function createInlineUpdates(options: Options, pkg: 'gt-react' | 'gt-next'): Promise<{
3
+ updates: Updates;
4
+ errors: string[];
5
+ }>;