@react-native-oh/react-native-harmony-cli 0.0.25 → 0.0.26-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 (94) hide show
  1. package/.prettierrc +6 -6
  2. package/dist/assetResolver.js +1 -23
  3. package/dist/codegen/core/CodeGenerator.js +2 -0
  4. package/dist/codegen/core/UberSchema.js +35 -9
  5. package/dist/codegen/core/index.js +1 -1
  6. package/dist/codegen/generators/{ComponentCodeGenerator.js → ComponentCodeGeneratorArkTS.js} +12 -4
  7. package/dist/codegen/generators/ComponentCodeGeneratorCAPI.js +79 -0
  8. package/dist/codegen/generators/GlueCodeGenerator.js +60 -0
  9. package/dist/codegen/generators/NativeModuleCodeGenerator.js +14 -6
  10. package/dist/codegen/generators/UberGeneratorV1.js +49 -0
  11. package/dist/codegen/generators/UberGeneratorV2.js +60 -0
  12. package/dist/codegen/generators/index.js +5 -2
  13. package/dist/codegen/templates/BaseComponentInstanceHTemplate.js +103 -0
  14. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +42 -36
  15. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +45 -36
  16. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +135 -127
  17. package/dist/codegen/templates/GeneratedPackageHTemplate.js +101 -0
  18. package/dist/codegen/templates/IndexTSTemplate.js +23 -5
  19. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +88 -82
  20. package/dist/codegen/templates/TurboModuleCppTemplate.js +26 -18
  21. package/dist/codegen/templates/TurboModuleHTemplate.js +27 -17
  22. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +37 -27
  23. package/dist/codegen/templates/index.js +1 -0
  24. package/dist/commands/codegen-harmony.js +99 -14
  25. package/dist/core/AbsolutePath.js +6 -0
  26. package/dist/core/CodegenConfig.js +8 -4
  27. package/dist/core/PackageJSON.js +8 -3
  28. package/dist/core/ProjectDependenciesManager.js +2 -2
  29. package/jest.config.js +5 -5
  30. package/package.json +57 -56
  31. package/react-native.config.js +10 -10
  32. package/src/assetResolver.ts +21 -44
  33. package/src/codegen/core/CodeGenerator.ts +9 -0
  34. package/src/codegen/core/CodegenError.ts +3 -3
  35. package/src/codegen/core/EventUtils.ts +18 -18
  36. package/src/codegen/core/TypeAnnotationToTS.test.ts +75 -75
  37. package/src/codegen/core/TypeAnnotationToTS.ts +188 -188
  38. package/src/codegen/core/UberSchema.ts +142 -99
  39. package/src/codegen/core/index.ts +5 -5
  40. package/src/codegen/generators/{ComponentCodeGenerator.ts → ComponentCodeGeneratorArkTS.ts} +112 -98
  41. package/src/codegen/generators/ComponentCodeGeneratorCAPI.ts +114 -0
  42. package/src/codegen/generators/GlueCodeGenerator.ts +109 -0
  43. package/src/codegen/generators/NativeModuleCodeGenerator.ts +115 -95
  44. package/src/codegen/generators/UberGeneratorV1.ts +64 -0
  45. package/src/codegen/generators/UberGeneratorV2.ts +91 -0
  46. package/src/codegen/generators/index.ts +6 -3
  47. package/src/codegen/index.ts +2 -2
  48. package/src/codegen/templates/BaseComponentInstanceHTemplate.ts +116 -0
  49. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +55 -49
  50. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +93 -85
  51. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +210 -202
  52. package/src/codegen/templates/GeneratedPackageHTemplate.ts +107 -0
  53. package/src/codegen/templates/IndexTSTemplate.ts +53 -33
  54. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +130 -124
  55. package/src/codegen/templates/TurboModuleCppTemplate.ts +54 -47
  56. package/src/codegen/templates/TurboModuleHTemplate.ts +35 -26
  57. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +90 -81
  58. package/src/codegen/templates/index.ts +9 -8
  59. package/src/commands/bundle-harmony.ts +203 -203
  60. package/src/commands/codegen-harmony.ts +272 -143
  61. package/src/commands/create-metro-host-constants.ts +48 -48
  62. package/src/commands/index.ts +6 -6
  63. package/src/commands/pack-harmony.ts +121 -121
  64. package/src/commands/unpack-harmony.ts +231 -231
  65. package/src/commands/verify-package-harmony.ts +106 -106
  66. package/src/core/AbsolutePath.ts +50 -43
  67. package/src/core/CodegenConfig.ts +62 -54
  68. package/src/core/DescriptiveError.ts +61 -61
  69. package/src/core/OHPackageJSON5.ts +23 -23
  70. package/src/core/PackageJSON.ts +75 -63
  71. package/src/core/ProjectDependenciesManager.ts +77 -77
  72. package/src/core/ValidationError.ts +1 -1
  73. package/src/core/ValueObject.ts +2 -2
  74. package/src/core/fs.ts +31 -31
  75. package/src/core/index.ts +9 -9
  76. package/src/index.ts +20 -20
  77. package/src/io/Logger.ts +68 -68
  78. package/src/io/TarGz.ts +26 -26
  79. package/src/io/fsUtils.ts +24 -24
  80. package/src/io/index.ts +3 -3
  81. package/src/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.ts +28 -28
  82. package/src/package-verifier/checks/HarmonyDirExistsCheck.ts +24 -24
  83. package/src/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.ts +18 -18
  84. package/src/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.ts +47 -47
  85. package/src/package-verifier/checks/index.ts +4 -4
  86. package/src/package-verifier/index.ts +2 -2
  87. package/src/package-verifier/types.ts +12 -12
  88. package/src/package-verifier/verify-package.ts +117 -117
  89. package/tsconfig.build.json +6 -6
  90. package/tsconfig.json +2 -2
  91. package/dist/codegen/core/Codegen.js +0 -35
  92. package/dist/codegen/generators/PackageCodeGenerator.js +0 -52
  93. package/src/codegen/core/Codegen.ts +0 -44
  94. package/src/codegen/generators/PackageCodeGenerator.ts +0 -73
@@ -1,143 +1,272 @@
1
- import fs from 'node:fs';
2
- import pathUtils from 'node:path';
3
- import { Command } from '@react-native-community/cli-types';
4
- import {
5
- AbsolutePath,
6
- DescriptiveError,
7
- maybeMakeDirectories,
8
- maybeRemoveFilesInDirectory,
9
- } from '../core';
10
- import {
11
- Codegen,
12
- UberSchema,
13
- ComponentCodeGenerator,
14
- NativeModuleCodeGenerator,
15
- PackageCodeGenerator,
16
- } from '../codegen';
17
- import { Logger } from '../io';
18
-
19
- export const commandCodegenHarmony: Command = {
20
- name: 'codegen-harmony',
21
- description:
22
- 'Generates a glue layer and native utilities from Turbo Module or Fabric Components specifications',
23
- options: [
24
- {
25
- name: '--rnoh-module-path <path>',
26
- description: 'Specifies the relative path to the rnoh OHOS module',
27
- },
28
- {
29
- name: '--cpp-output-path <path>',
30
- description:
31
- 'Specifies the relative path to the output directory intended for storing generated C++ files',
32
- default: './harmony/entry/src/main/cpp/generated',
33
- },
34
- {
35
- name: '--project-root-path <path>',
36
- description: 'Relative path to package root',
37
- default: '.',
38
- },
39
- {
40
- name: '--debug [boolean]',
41
- description: 'Enables logging details',
42
- default: false,
43
- },
44
- ],
45
- func: async (_argv, _config, args: any) => {
46
- const logger = new Logger();
47
- try {
48
- validateArgs(args);
49
- const etsOutputPath = new AbsolutePath(
50
- args.rnohModulePath
51
- ).copyWithNewSegment('generated');
52
- const cppOutputPath = new AbsolutePath(args.cppOutputPath);
53
- const projectRootPath = new AbsolutePath(args.projectRootPath);
54
- const codegen = createCodegen(cppOutputPath, etsOutputPath);
55
- const uberSchema = await UberSchema.fromProjectRootPath(
56
- new AbsolutePath(args.projectRootPath)
57
- );
58
- const fileContentByPath = codegen.generate(uberSchema);
59
- if (args.debug) {
60
- logger.debug((styles) =>
61
- styles.gray(JSON.stringify(uberSchema.getValue(), null, 2))
62
- );
63
- }
64
- saveCodegenResult(fileContentByPath, cppOutputPath, etsOutputPath);
65
- logCodegenResult(logger, fileContentByPath, projectRootPath);
66
- } catch (err) {
67
- if (err instanceof DescriptiveError) {
68
- logger.descriptiveError(err);
69
- process.exit(1);
70
- }
71
- throw err;
72
- }
73
- },
74
- };
75
-
76
- function validateArgs(args: any) {
77
- if (!args.rnohModulePath) {
78
- throw new DescriptiveError({
79
- whatHappened: "--rnoh-module-path argument wasn't provided",
80
- whatCanUserDo: {
81
- default: [
82
- 'Please provide a path to the native React Native for Open Harmony module (rnoh) which is probably located somewhere in "<PROJECT_ROOT>/harmony" directory',
83
- ],
84
- },
85
- });
86
- }
87
- }
88
-
89
- function createCodegen(
90
- cppOutputPath: AbsolutePath,
91
- etsOutputPath: AbsolutePath
92
- ) {
93
- return new Codegen(new PackageCodeGenerator(cppOutputPath, etsOutputPath), {
94
- Component: new ComponentCodeGenerator(
95
- cppOutputPath,
96
- etsOutputPath.copyWithNewSegment('components')
97
- ),
98
- NativeModule: new NativeModuleCodeGenerator(
99
- cppOutputPath,
100
- etsOutputPath.copyWithNewSegment('turboModules')
101
- ),
102
- });
103
- }
104
-
105
- function saveCodegenResult(
106
- fileContentByPath: Map<AbsolutePath, string>,
107
- cppOutputPath: AbsolutePath,
108
- etsOutputPath: AbsolutePath
109
- ) {
110
- prepareDirectory(cppOutputPath);
111
- prepareDirectory(etsOutputPath);
112
- prepareDirectory(etsOutputPath.copyWithNewSegment('components'));
113
- prepareDirectory(etsOutputPath.copyWithNewSegment('turboModules'));
114
- fileContentByPath.forEach((fileContent, path) => {
115
- fs.writeFileSync(path.getValue(), fileContent);
116
- });
117
- }
118
-
119
- function prepareDirectory(path: AbsolutePath) {
120
- maybeMakeDirectories(path);
121
- maybeRemoveFilesInDirectory(path);
122
- }
123
-
124
- function logCodegenResult(
125
- logger: Logger,
126
- fileContentByPath: Map<AbsolutePath, string>,
127
- projectRootPath: AbsolutePath
128
- ) {
129
- const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
130
- (path) => pathUtils.relative(projectRootPath.getValue(), path.getValue())
131
- );
132
- sortedRelativePathStrings.sort();
133
- sortedRelativePathStrings.forEach((pathStr) => {
134
- logger.info((styles) => styles.gray(`• ${pathStr}`));
135
- });
136
- logger.info(() => '');
137
- logger.info(
138
- (styles) =>
139
- `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`,
140
- { prefix: true }
141
- );
142
- logger.info(() => '');
143
- }
1
+ import fs from 'node:fs';
2
+ import pathUtils from 'node:path';
3
+ import Case from 'case';
4
+ import { Command } from '@react-native-community/cli-types';
5
+ import {
6
+ AbsolutePath,
7
+ DescriptiveError,
8
+ PackageJSON,
9
+ ProjectDependenciesManager,
10
+ maybeMakeDirectories,
11
+ maybeRemoveFilesInDirectory,
12
+ } from '../core';
13
+ import {
14
+ UberSchema,
15
+ LibraryData,
16
+ UberGeneratorV1,
17
+ UberGeneratorV2,
18
+ GlueCodeGenerator,
19
+ CodegenError,
20
+ } from '../codegen';
21
+ import { Logger } from '../io';
22
+
23
+ export const commandCodegenHarmony: Command = {
24
+ name: 'codegen-harmony',
25
+ description:
26
+ 'Generates a glue layer and native utilities from Turbo Module or Fabric Components specifications',
27
+ options: [
28
+ {
29
+ name: '--rnoh-module-path <path>',
30
+ description: 'Specifies the relative path to the rnoh OHOS module',
31
+ },
32
+ {
33
+ name: '--cpp-output-path <path>',
34
+ description:
35
+ 'Specifies the relative path to the output directory intended for storing generated C++ files',
36
+ default: './harmony/entry/src/main/cpp/generated',
37
+ },
38
+ {
39
+ name: '--project-root-path <path>',
40
+ description: 'Relative path to package root',
41
+ default: '.',
42
+ },
43
+ {
44
+ name: '--debug [boolean]',
45
+ description: 'Enables logging details',
46
+ default: false,
47
+ },
48
+ {
49
+ name: '--no-safety-check [boolean]',
50
+ description:
51
+ 'Skips the check that prevents file operations outside the current working directory. This command permanently deletes previously generated files. Files are generated in the path specified by cpp-output-path.',
52
+ },
53
+ ],
54
+ func: async (_argv, _config, args: any) => {
55
+ const logger = new Logger();
56
+ try {
57
+ const MAX_SUPPORTED_CODEGEN_VERSION = 2;
58
+ // prepare the input data
59
+ validateArgs(args);
60
+ const etsOutputPath = new AbsolutePath(
61
+ args.rnohModulePath
62
+ ).copyWithNewSegment('generated');
63
+ const enableSafetyCheck: boolean = args.safetyCheck;
64
+ const cppOutputPath = new AbsolutePath(args.cppOutputPath);
65
+ const projectRootPath = new AbsolutePath(args.projectRootPath);
66
+ const uberSchemaFromArkTSLibraries = await UberSchema.fromProject(
67
+ projectRootPath,
68
+ (codegenVersion, packageName) => {
69
+ throwErrorIfUnsupportedCodegenVersion(
70
+ codegenVersion,
71
+ MAX_SUPPORTED_CODEGEN_VERSION,
72
+ packageName
73
+ );
74
+ return codegenVersion === 1;
75
+ }
76
+ );
77
+ const cApiLibrariesData = await collectLibrariesData(
78
+ projectRootPath,
79
+ (codegenVersion, packageName) => {
80
+ throwErrorIfUnsupportedCodegenVersion(
81
+ codegenVersion,
82
+ MAX_SUPPORTED_CODEGEN_VERSION,
83
+ packageName
84
+ );
85
+ return codegenVersion === 2;
86
+ }
87
+ );
88
+
89
+ // instantiate objects
90
+ const uberGeneratorV1 = new UberGeneratorV1(cppOutputPath, etsOutputPath);
91
+ const uberGeneratorV2 = new UberGeneratorV2(cppOutputPath, etsOutputPath);
92
+ const glueCodeGenerator = new GlueCodeGenerator(
93
+ cppOutputPath,
94
+ etsOutputPath
95
+ );
96
+
97
+ // generate the code
98
+ const fileContentByPath = new Map<AbsolutePath, string>();
99
+ const appendToFileContentByPath = (
100
+ fileContent: string,
101
+ path: AbsolutePath
102
+ ) => {
103
+ fileContentByPath.set(path, fileContent);
104
+ };
105
+ uberGeneratorV1
106
+ .generate(uberSchemaFromArkTSLibraries)
107
+ .forEach(appendToFileContentByPath);
108
+ uberGeneratorV2
109
+ .generate(cApiLibrariesData)
110
+ .forEach(appendToFileContentByPath);
111
+ glueCodeGenerator
112
+ .generate({
113
+ v1: uberGeneratorV1.getGlueCodeData(),
114
+ v2: uberGeneratorV2.getGlueCodeData(),
115
+ })
116
+ .forEach(appendToFileContentByPath);
117
+
118
+ // output the results
119
+ if (args.debug) {
120
+ const uberSchema = await UberSchema.fromProject(projectRootPath);
121
+ logger.debug((styles) =>
122
+ styles.gray(JSON.stringify(uberSchema.getValue(), null, 2))
123
+ );
124
+ }
125
+ saveCodegenResult(
126
+ fileContentByPath,
127
+ cppOutputPath,
128
+ etsOutputPath,
129
+ enableSafetyCheck
130
+ );
131
+ logCodegenResult(logger, fileContentByPath, projectRootPath);
132
+ } catch (err) {
133
+ if (err instanceof DescriptiveError) {
134
+ logger.descriptiveError(err);
135
+ process.exit(1);
136
+ }
137
+ throw err;
138
+ }
139
+ },
140
+ };
141
+
142
+ function validateArgs(args: any) {
143
+ if (!args.rnohModulePath) {
144
+ throw new DescriptiveError({
145
+ whatHappened: "--rnoh-module-path argument wasn't provided",
146
+ whatCanUserDo: {
147
+ default: [
148
+ 'Please provide a path to the native React Native for Open Harmony module (rnoh) which is probably located somewhere in "<PROJECT_ROOT>/harmony" directory',
149
+ ],
150
+ },
151
+ });
152
+ }
153
+ }
154
+
155
+ async function collectLibrariesData(
156
+ projectRootPath: AbsolutePath,
157
+ onShouldAcceptCodegenConfig: (version: number, packageName: string) => boolean
158
+ ): Promise<LibraryData[]> {
159
+ const packageJSONs: PackageJSON[] = [
160
+ PackageJSON.fromProjectRootPath(projectRootPath, projectRootPath),
161
+ ];
162
+ await new ProjectDependenciesManager(projectRootPath).forEachAsync(
163
+ (dependency) => {
164
+ packageJSONs.push(dependency.readPackageJSON());
165
+ }
166
+ );
167
+ const results: LibraryData[] = [];
168
+ for (const packageJSON of packageJSONs) {
169
+ const codegenConfigs = packageJSON.getCodegenConfigs();
170
+ for (const codegenConfig of codegenConfigs) {
171
+ if (
172
+ codegenConfig &&
173
+ onShouldAcceptCodegenConfig(
174
+ codegenConfig.getVersion(),
175
+ packageJSON.name
176
+ )
177
+ ) {
178
+ results.push({
179
+ name: deriveCppDirectoryNameFromNpmPackageName(packageJSON.name),
180
+ uberSchema: UberSchema.fromCodegenConfig(codegenConfig),
181
+ });
182
+ }
183
+ }
184
+ }
185
+ return results;
186
+ }
187
+
188
+ function throwErrorIfUnsupportedCodegenVersion(
189
+ codegenVersion: number,
190
+ maxSupportedCodegenVersion: number,
191
+ packageName: string
192
+ ) {
193
+ if (codegenVersion > maxSupportedCodegenVersion) {
194
+ throw new CodegenError({
195
+ whatHappened: `Package "${packageName}" requires codegenVersion: ${codegenVersion}, which is not supported (maxSupportedCodegenVersion=${maxSupportedCodegenVersion}).`,
196
+ whatCanUserDo: {
197
+ rnAppDeveloper: [
198
+ `Try downgrading "${packageName}".`,
199
+ 'Update the "@rnoh/react-native-harmony-cli" package.',
200
+ ],
201
+ },
202
+ });
203
+ }
204
+ }
205
+
206
+ function saveCodegenResult(
207
+ fileContentByPath: Map<AbsolutePath, string>,
208
+ cppOutputPath: AbsolutePath,
209
+ etsOutputPath: AbsolutePath,
210
+ enableSafetyCheck: boolean
211
+ ) {
212
+ prepareDirectory(cppOutputPath, enableSafetyCheck);
213
+ prepareDirectory(etsOutputPath, enableSafetyCheck);
214
+ prepareDirectory(
215
+ etsOutputPath.copyWithNewSegment('components'),
216
+ enableSafetyCheck
217
+ );
218
+ prepareDirectory(
219
+ etsOutputPath.copyWithNewSegment('turboModules'),
220
+ enableSafetyCheck
221
+ );
222
+ fileContentByPath.forEach((_fileContent, path) => {
223
+ prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
224
+ });
225
+ fileContentByPath.forEach((fileContent, path) => {
226
+ fs.writeFileSync(path.getValue(), fileContent);
227
+ });
228
+ }
229
+
230
+ function prepareDirectory(path: AbsolutePath, enableSafetyCheck: boolean) {
231
+ maybeMakeDirectories(path);
232
+ if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
233
+ throw new DescriptiveError({
234
+ whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
235
+ whatCanUserDo: { default: ['Run codegen from different location'] },
236
+ });
237
+ }
238
+ maybeRemoveFilesInDirectory(path);
239
+ }
240
+
241
+ function logCodegenResult(
242
+ logger: Logger,
243
+ fileContentByPath: Map<AbsolutePath, string>,
244
+ projectRootPath: AbsolutePath
245
+ ) {
246
+ const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
247
+ (path) => pathUtils.relative(projectRootPath.getValue(), path.getValue())
248
+ );
249
+ sortedRelativePathStrings.sort();
250
+ sortedRelativePathStrings.forEach((pathStr) => {
251
+ logger.info((styles) => styles.gray(`• ${pathStr}`));
252
+ });
253
+ logger.info(() => '');
254
+ logger.info(
255
+ (styles) =>
256
+ `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`,
257
+ { prefix: true }
258
+ );
259
+ logger.info(() => '');
260
+ }
261
+
262
+ function deriveCppDirectoryNameFromNpmPackageName(
263
+ npmPackageName: string
264
+ ): string {
265
+ let result = npmPackageName;
266
+ if (npmPackageName.includes('/')) {
267
+ result.replace('@', '');
268
+ result = npmPackageName.replace('/', '__');
269
+ }
270
+ result = Case.snake(result);
271
+ return result;
272
+ }
@@ -1,48 +1,48 @@
1
- import { Command } from '@react-native-community/cli-types';
2
- import os from 'node:os';
3
- import fs from 'node:fs';
4
- import pathUtils from 'node:path';
5
-
6
- export const commandCreateMetroConstantsHarmony: Command = {
7
- name: 'create-metro-host-constants-harmony',
8
- description:
9
- 'Creates a Typescript file that exports constant with IP of the host machine. That IP is later used to connect to the Metro server from a physical device.',
10
- options: [
11
- {
12
- name: '--output <string>',
13
- description: 'Output file',
14
- default: './harmony/entry/src/main/ets/codegen/MetroHostConstants.ts',
15
- },
16
- ],
17
- func: async (argv, config, args: any) => {
18
- createMetroHostConstants(pathUtils.resolve(args.output));
19
- },
20
- };
21
-
22
- function createMetroHostConstants(outputPath: string): void {
23
- const networkInterfacesByName = os.networkInterfaces();
24
- const getIP = () => {
25
- for (let name of Object.keys(networkInterfacesByName)) {
26
- for (let net of networkInterfacesByName[name] ?? []) {
27
- // skip over non-ipv4 and internal (i.e. 127.0.0.1) addresses
28
- if (net.family === 'IPv4' && !net.internal) {
29
- return net.address;
30
- }
31
- }
32
- }
33
- return;
34
- };
35
- const ip = getIP();
36
- const tsCode = [
37
- '// This file is autogenerated. Do not modify it manually.',
38
- '',
39
- `export const METRO_SERVER_IP = '${ip}';\n`,
40
- ];
41
- fs.writeFile(outputPath, tsCode.join('\n'), (err) => {
42
- if (err) {
43
- console.error(`Error writing to ${outputPath}:`, err);
44
- } else {
45
- console.log(`Created file at ${outputPath}`);
46
- }
47
- });
48
- }
1
+ import { Command } from '@react-native-community/cli-types';
2
+ import os from 'node:os';
3
+ import fs from 'node:fs';
4
+ import pathUtils from 'node:path';
5
+
6
+ export const commandCreateMetroConstantsHarmony: Command = {
7
+ name: 'create-metro-host-constants-harmony',
8
+ description:
9
+ 'Creates a Typescript file that exports constant with IP of the host machine. That IP is later used to connect to the Metro server from a physical device.',
10
+ options: [
11
+ {
12
+ name: '--output <string>',
13
+ description: 'Output file',
14
+ default: './harmony/entry/src/main/ets/codegen/MetroHostConstants.ts',
15
+ },
16
+ ],
17
+ func: async (argv, config, args: any) => {
18
+ createMetroHostConstants(pathUtils.resolve(args.output));
19
+ },
20
+ };
21
+
22
+ function createMetroHostConstants(outputPath: string): void {
23
+ const networkInterfacesByName = os.networkInterfaces();
24
+ const getIP = () => {
25
+ for (let name of Object.keys(networkInterfacesByName)) {
26
+ for (let net of networkInterfacesByName[name] ?? []) {
27
+ // skip over non-ipv4 and internal (i.e. 127.0.0.1) addresses
28
+ if (net.family === 'IPv4' && !net.internal) {
29
+ return net.address;
30
+ }
31
+ }
32
+ }
33
+ return;
34
+ };
35
+ const ip = getIP();
36
+ const tsCode = [
37
+ '// This file is autogenerated. Do not modify it manually.',
38
+ '',
39
+ `export const METRO_SERVER_IP = '${ip}';\n`,
40
+ ];
41
+ fs.writeFile(outputPath, tsCode.join('\n'), (err) => {
42
+ if (err) {
43
+ console.error(`Error writing to ${outputPath}:`, err);
44
+ } else {
45
+ console.log(`Created file at ${outputPath}`);
46
+ }
47
+ });
48
+ }
@@ -1,6 +1,6 @@
1
- export * from './bundle-harmony';
2
- export * from './pack-harmony';
3
- export * from './unpack-harmony';
4
- export * from './create-metro-host-constants';
5
- export * from './codegen-harmony';
6
- export * from './verify-package-harmony';
1
+ export * from './bundle-harmony';
2
+ export * from './pack-harmony';
3
+ export * from './unpack-harmony';
4
+ export * from './create-metro-host-constants';
5
+ export * from './codegen-harmony';
6
+ export * from './verify-package-harmony';