@react-native-oh/react-native-harmony-cli 0.0.37 → 0.0.40-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/autolinking/Autolinking.js +14 -11
  2. package/dist/codegen/generators/UberGeneratorV1.js +9 -2
  3. package/dist/codegen/generators/UberGeneratorV2.js +8 -1
  4. package/dist/commands/codegen-harmony.js +16 -5
  5. package/dist/commands/run-harmony.js +0 -2
  6. package/dist/core/ProjectDependenciesManager.js +5 -7
  7. package/dist/simulator/LaunchSimulator.js +9 -2
  8. package/harmony/rnoh-hvigor-plugin-0.3.0.tgz +0 -0
  9. package/package.json +10 -2
  10. package/.prettierrc +0 -6
  11. package/src/assetResolver.ts +0 -134
  12. package/src/autolinking/Autolinking.test.ts +0 -483
  13. package/src/autolinking/Autolinking.ts +0 -382
  14. package/src/autolinking/index.ts +0 -8
  15. package/src/codegen/core/CodeGenerator.ts +0 -16
  16. package/src/codegen/core/CodegenError.ts +0 -10
  17. package/src/codegen/core/EventUtils.ts +0 -23
  18. package/src/codegen/core/TypeAnnotationToTS.test.ts +0 -82
  19. package/src/codegen/core/TypeAnnotationToTS.ts +0 -195
  20. package/src/codegen/core/UberSchema.ts +0 -152
  21. package/src/codegen/core/index.ts +0 -12
  22. package/src/codegen/generators/AppBuildTimeGlueCodeGenerator.ts +0 -124
  23. package/src/codegen/generators/ArkTSComponentCodeGeneratorArkTS.ts +0 -128
  24. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +0 -122
  25. package/src/codegen/generators/CppComponentCodeGenerator.ts +0 -95
  26. package/src/codegen/generators/LibGlueCodeGenerator.ts +0 -98
  27. package/src/codegen/generators/NativeModuleCodeGenerator.ts +0 -124
  28. package/src/codegen/generators/SharedComponentCodeGenerator.ts +0 -57
  29. package/src/codegen/generators/UberGeneratorV1.ts +0 -75
  30. package/src/codegen/generators/UberGeneratorV2.ts +0 -114
  31. package/src/codegen/generators/index.ts +0 -15
  32. package/src/codegen/index.ts +0 -9
  33. package/src/codegen/templates/BaseComponentInstanceHTemplate.ts +0 -128
  34. package/src/codegen/templates/BasePackageHTemplate.ts +0 -159
  35. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +0 -63
  36. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +0 -121
  37. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +0 -222
  38. package/src/codegen/templates/IndexTSTemplate.ts +0 -62
  39. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +0 -150
  40. package/src/codegen/templates/TurboModuleCppTemplate.ts +0 -61
  41. package/src/codegen/templates/TurboModuleHTemplate.ts +0 -42
  42. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +0 -101
  43. package/src/codegen/templates/index.ts +0 -16
  44. package/src/commands/bundle-harmony.ts +0 -134
  45. package/src/commands/codegen-harmony.ts +0 -297
  46. package/src/commands/codegen-lib-harmony.ts +0 -389
  47. package/src/commands/create-metro-host-constants.ts +0 -55
  48. package/src/commands/index.ts +0 -16
  49. package/src/commands/init.ts +0 -755
  50. package/src/commands/link-harmony.ts +0 -102
  51. package/src/commands/pack-harmony.ts +0 -128
  52. package/src/commands/run-harmony.ts +0 -506
  53. package/src/commands/types.ts +0 -21
  54. package/src/commands/unpack-harmony.ts +0 -238
  55. package/src/commands/verify-package-harmony.ts +0 -113
  56. package/src/core/AbsolutePath.ts +0 -66
  57. package/src/core/CodegenConfig.ts +0 -67
  58. package/src/core/DescriptiveError.ts +0 -68
  59. package/src/core/FileSystem.ts +0 -57
  60. package/src/core/OHPackageJSON5.ts +0 -30
  61. package/src/core/PackageJSON.ts +0 -104
  62. package/src/core/ProjectDependenciesManager.ts +0 -103
  63. package/src/core/ValidationError.ts +0 -8
  64. package/src/core/ValueObject.ts +0 -9
  65. package/src/core/fs.ts +0 -38
  66. package/src/core/index.ts +0 -17
  67. package/src/index.ts +0 -33
  68. package/src/io/CliExecutor.ts +0 -69
  69. package/src/io/Logger.ts +0 -112
  70. package/src/io/RealFS.ts +0 -62
  71. package/src/io/TarGz.ts +0 -33
  72. package/src/io/__fixtures__.ts +0 -139
  73. package/src/io/fsUtils.ts +0 -44
  74. package/src/io/index.ts +0 -11
  75. package/src/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.ts +0 -35
  76. package/src/package-verifier/checks/HarmonyDirExistsCheck.ts +0 -31
  77. package/src/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.ts +0 -25
  78. package/src/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.ts +0 -54
  79. package/src/package-verifier/checks/index.ts +0 -11
  80. package/src/package-verifier/index.ts +0 -9
  81. package/src/package-verifier/types.ts +0 -19
  82. package/src/package-verifier/verify-package.ts +0 -123
  83. package/src/simulator/LaunchSimulator.ts +0 -352
  84. package/src/simulator/index.ts +0 -8
@@ -1,297 +0,0 @@
1
- /**
2
- * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
- import pathUtils from 'node:path';
9
- import Case from 'case';
10
- import { Command } from './types';
11
- import {
12
- AbsolutePath,
13
- DescriptiveError,
14
- FS,
15
- PackageJSON,
16
- ProjectDependenciesManager,
17
- maybeMakeDirectories,
18
- maybeRemoveFilesInDirectory,
19
- } from '../core';
20
- import {
21
- UberSchema,
22
- LibraryData,
23
- UberGeneratorV1,
24
- UberGeneratorV2,
25
- AppBuildTimeGlueCodeGenerator,
26
- CodegenError,
27
- } from '../codegen';
28
- import { Logger, RealFS } from '../io';
29
-
30
- export const commandCodegenHarmony: Command = {
31
- name: 'codegen-harmony',
32
- description:
33
- 'Generates boilerplate, types, and utilities from Turbo Module and Fabric Component specifications. This command is meant to be executed during the application build process.',
34
- options: [
35
- {
36
- name: '--rnoh-module-path <path>',
37
- description: 'Specifies the relative path to the rnoh OHOS module',
38
- },
39
- {
40
- name: '--cpp-output-path <path>',
41
- description:
42
- 'Specifies the relative path to the output directory intended for storing generated C++ files',
43
- default: './harmony/entry/src/main/cpp/generated',
44
- },
45
- {
46
- name: '--project-root-path <path>',
47
- description: 'Relative path to package root',
48
- default: '.',
49
- },
50
- {
51
- name: '--debug [boolean]',
52
- description: 'Enables logging details',
53
- default: false,
54
- },
55
- {
56
- name: '--no-safety-check [boolean]',
57
- description:
58
- '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.',
59
- },
60
- ],
61
- func: async (_argv, _config, args: any) => {
62
- const logger = new Logger();
63
- const fs = new RealFS();
64
- try {
65
- const MAX_SUPPORTED_CODEGEN_VERSION = 2;
66
- // prepare the input data
67
- validateArgs(args);
68
- const etsOutputPath = new AbsolutePath(
69
- args.rnohModulePath
70
- ).copyWithNewSegment('generated');
71
- const enableSafetyCheck: boolean = args.safetyCheck;
72
- const cppOutputPath = new AbsolutePath(args.cppOutputPath);
73
- const projectRootPath = new AbsolutePath(args.projectRootPath);
74
- const uberSchemaFromArkTSLibraries = await UberSchema.fromProject(
75
- fs,
76
- projectRootPath,
77
- (codegenVersion, packageName) => {
78
- throwErrorIfUnsupportedCodegenVersion(
79
- codegenVersion,
80
- MAX_SUPPORTED_CODEGEN_VERSION,
81
- packageName
82
- );
83
- return codegenVersion === 1;
84
- }
85
- );
86
- const cApiLibrariesData = await collectLibrariesData(
87
- fs,
88
- projectRootPath,
89
- (codegenVersion, packageName) => {
90
- throwErrorIfUnsupportedCodegenVersion(
91
- codegenVersion,
92
- MAX_SUPPORTED_CODEGEN_VERSION,
93
- packageName
94
- );
95
- return codegenVersion === 2;
96
- }
97
- );
98
-
99
- // instantiate objects
100
- const codegenNoticeLines = [
101
- 'This code was generated by "react-native codegen-harmony"',
102
- '',
103
- 'Do not edit this file as changes may cause incorrect behavior and will be',
104
- 'lost once the code is regenerated.',
105
- ];
106
- const uberGeneratorV1 = new UberGeneratorV1(
107
- cppOutputPath,
108
- etsOutputPath,
109
- [...codegenNoticeLines, '', '@generatorVersion: 1']
110
- );
111
- const uberGeneratorV2 = new UberGeneratorV2(
112
- cppOutputPath,
113
- etsOutputPath,
114
- [...codegenNoticeLines, '', '@generatorVersion: 2']
115
- );
116
- const glueCodeGenerator = new AppBuildTimeGlueCodeGenerator(
117
- cppOutputPath,
118
- etsOutputPath,
119
- codegenNoticeLines
120
- );
121
-
122
- // generate the code
123
- const fileContentByPath = new Map<AbsolutePath, string>();
124
- const appendToFileContentByPath = (
125
- fileContent: string,
126
- path: AbsolutePath
127
- ) => {
128
- fileContentByPath.set(path, fileContent);
129
- };
130
- uberGeneratorV1
131
- .generate(uberSchemaFromArkTSLibraries)
132
- .forEach(appendToFileContentByPath);
133
- uberGeneratorV2
134
- .generate(cApiLibrariesData)
135
- .forEach(appendToFileContentByPath);
136
- glueCodeGenerator
137
- .generate({
138
- v1: uberGeneratorV1.getGlueCodeData(),
139
- v2: uberGeneratorV2.getGlueCodeData(),
140
- })
141
- .forEach(appendToFileContentByPath);
142
-
143
- // output the results
144
- if (args.debug) {
145
- const uberSchema = await UberSchema.fromProject(fs, projectRootPath);
146
- logger.debug((styles) =>
147
- styles.gray(JSON.stringify(uberSchema.getValue(), null, 2))
148
- );
149
- }
150
- saveCodegenResult(
151
- fs,
152
- fileContentByPath,
153
- cppOutputPath,
154
- etsOutputPath,
155
- enableSafetyCheck
156
- );
157
- logCodegenResult(logger, fileContentByPath, projectRootPath);
158
- } catch (err) {
159
- if (err instanceof DescriptiveError) {
160
- logger.descriptiveError(err);
161
- process.exit(1);
162
- }
163
- throw err;
164
- }
165
- },
166
- };
167
-
168
- function validateArgs(args: any) {
169
- if (!args.rnohModulePath) {
170
- throw new DescriptiveError({
171
- whatHappened: "--rnoh-module-path argument wasn't provided",
172
- whatCanUserDo: [
173
- 'Please provide a path to the native React Native for Open Harmony module (rnoh) which is probably located somewhere in "<PROJECT_ROOT>/harmony" directory',
174
- ],
175
- });
176
- }
177
- }
178
-
179
- async function collectLibrariesData(
180
- fs: FS,
181
- projectRootPath: AbsolutePath,
182
- onShouldAcceptCodegenConfig: (version: number, packageName: string) => boolean
183
- ): Promise<LibraryData[]> {
184
- const packageJSONs: PackageJSON[] = [
185
- PackageJSON.fromProjectRootPath(fs, projectRootPath, projectRootPath),
186
- ];
187
- await new ProjectDependenciesManager(fs, projectRootPath).forEachAsync(
188
- (dependency) => {
189
- packageJSONs.push(dependency.readPackageJSON());
190
- }
191
- );
192
- const results: LibraryData[] = [];
193
- for (const packageJSON of packageJSONs) {
194
- const codegenConfigs = packageJSON.getCodegenConfigs();
195
- for (const codegenConfig of codegenConfigs) {
196
- if (
197
- codegenConfig &&
198
- onShouldAcceptCodegenConfig(
199
- codegenConfig.getVersion(),
200
- packageJSON.name
201
- )
202
- ) {
203
- results.push({
204
- libraryCppName: deriveCppDirectoryNameFromNpmPackageName(
205
- packageJSON.name
206
- ),
207
- uberSchema: UberSchema.fromCodegenConfig(codegenConfig),
208
- });
209
- }
210
- }
211
- }
212
- return results;
213
- }
214
-
215
- function throwErrorIfUnsupportedCodegenVersion(
216
- codegenVersion: number,
217
- maxSupportedCodegenVersion: number,
218
- packageName: string
219
- ) {
220
- if (codegenVersion > maxSupportedCodegenVersion) {
221
- throw new CodegenError({
222
- whatHappened: `Package "${packageName}" requires codegenVersion: ${codegenVersion}, which is not supported (maxSupportedCodegenVersion=${maxSupportedCodegenVersion}).`,
223
- whatCanUserDo: [
224
- `Try downgrading "${packageName}".`,
225
- 'Update the "@react-native-oh/react-native-harmony-cli" package.',
226
- ],
227
- });
228
- }
229
- }
230
-
231
- function saveCodegenResult(
232
- fs: FS,
233
- fileContentByPath: Map<AbsolutePath, string>,
234
- cppOutputPath: AbsolutePath,
235
- etsOutputPath: AbsolutePath,
236
- enableSafetyCheck: boolean
237
- ) {
238
- prepareDirectory(cppOutputPath, enableSafetyCheck);
239
- prepareDirectory(etsOutputPath, enableSafetyCheck);
240
- prepareDirectory(
241
- etsOutputPath.copyWithNewSegment('components'),
242
- enableSafetyCheck
243
- );
244
- prepareDirectory(
245
- etsOutputPath.copyWithNewSegment('turboModules'),
246
- enableSafetyCheck
247
- );
248
- fileContentByPath.forEach((_fileContent, path) => {
249
- prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
250
- });
251
- fileContentByPath.forEach((fileContent, path) => {
252
- fs.writeTextSync(path, fileContent);
253
- });
254
- }
255
-
256
- function prepareDirectory(path: AbsolutePath, enableSafetyCheck: boolean) {
257
- maybeMakeDirectories(path);
258
- if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
259
- throw new DescriptiveError({
260
- whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
261
- whatCanUserDo: ['Run codegen from different location'],
262
- });
263
- }
264
- maybeRemoveFilesInDirectory(path);
265
- }
266
-
267
- function logCodegenResult(
268
- logger: Logger,
269
- fileContentByPath: Map<AbsolutePath, string>,
270
- projectRootPath: AbsolutePath
271
- ) {
272
- const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
273
- (path) => pathUtils.relative(projectRootPath.getValue(), path.getValue())
274
- );
275
- sortedRelativePathStrings.sort();
276
- sortedRelativePathStrings.forEach((pathStr) => {
277
- logger.debug((styles) => styles.gray(`• ${pathStr}`));
278
- });
279
- logger.debug(() => '');
280
- logger.info(
281
- (styles) =>
282
- `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`
283
- );
284
- logger.debug(() => '');
285
- }
286
-
287
- function deriveCppDirectoryNameFromNpmPackageName(
288
- npmPackageName: string
289
- ): string {
290
- let result = npmPackageName;
291
- if (npmPackageName.includes('/')) {
292
- result.replace('@', '');
293
- result = npmPackageName.replace('/', '__');
294
- }
295
- result = Case.snake(result);
296
- return result;
297
- }
@@ -1,389 +0,0 @@
1
- /**
2
- * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE-MIT file in the root directory of this source tree.
6
- */
7
-
8
- import { Command } from './types';
9
- import {
10
- AbsolutePath,
11
- DescriptiveError,
12
- maybeMakeDirectories,
13
- maybeRemoveFilesInDirectory,
14
- } from '../core';
15
- import { Logger, findFilePathsWithExtensions } from '../io';
16
- import fs from 'node:fs';
17
- import {
18
- ArkTSComponentCodeGeneratorCAPI,
19
- CppComponentCodeGenerator,
20
- NativeModuleCodeGenerator,
21
- UberSchema,
22
- SharedComponentCodeGenerator,
23
- } from '../codegen';
24
- import Case from 'case';
25
- import { LibGlueCodeGenerator } from '../codegen/generators/LibGlueCodeGenerator';
26
-
27
- const COMMAND_NAME = 'codegen-lib-harmony';
28
-
29
- export const commandCodegenLibHarmony: Command = {
30
- name: COMMAND_NAME,
31
- description:
32
- 'Generates boilerplate, types, and utilities from Turbo Module and Fabric Component specifications. Designed for library developers who want to include generated code in their libraries.',
33
- options: [
34
- {
35
- name: '--npm-package-name <string>',
36
- description:
37
- 'Name of your React Native library. This value is processed and used as a directory name for C++ files to reduce the chances of conflicts between libraries.',
38
- },
39
- {
40
- name: '--turbo-modules-spec-paths [path]',
41
- description:
42
- 'Path or paths to Turbo Module spec files. Each path can point to a spec file or a directory containing spec files.',
43
- parse: (val: string) => val.split(' '),
44
- },
45
- {
46
- name: '--arkts-components-spec-paths [path]',
47
- description:
48
- 'Path or paths to component spec files used to generate code for components to be implemented on the ArkTS side. Each path can point to a spec file or a directory containing spec files.',
49
- parse: (val: string) => val.split(' '),
50
- },
51
- {
52
- name: '--cpp-components-spec-paths [path]',
53
- description:
54
- 'Path or paths to component spec files used to generate code for components to be implemented on the C++ side. Each path can point to a spec file or a directory containing spec files.',
55
- parse: (val: string) => val.split(' '),
56
- },
57
- {
58
- name: '--cpp-output-path <path>',
59
- description:
60
- 'Specifies the relative path to the output directory intended for storing generated C++ files.',
61
- },
62
- {
63
- name: '--ets-output-path <path>',
64
- description:
65
- 'Specifies the relative path to the output directory intended for storing generated ETS files.',
66
- },
67
- {
68
- name: '--no-safety-check [boolean]',
69
- description:
70
- '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.',
71
- },
72
- ],
73
- func: async (_argv, _config, rawArgs: any) => {
74
- const logger = new Logger();
75
- try {
76
- const { args, uberSchemaByType } =
77
- validateArgsAndRetrieveUberSchemaByType(rawArgs);
78
- const fileContentByPath = generateCodeInMemory({
79
- args,
80
- uberSchemaByType,
81
- });
82
- saveAndLogCodegenResult(args, logger, fileContentByPath);
83
- } catch (err) {
84
- if (err instanceof DescriptiveError && !err.isUnexpected()) {
85
- logger.descriptiveError(err);
86
- return;
87
- }
88
- throw err;
89
- }
90
- },
91
- };
92
-
93
- type RawArgs = {
94
- npmPackageName?: string;
95
- turboModulesSpecPaths?: string[];
96
- arktsComponentsSpecPaths?: string[];
97
- cppComponentsSpecPaths?: string[];
98
- cppOutputPath?: string;
99
- etsOutputPath?: string;
100
- safetyCheck?: boolean;
101
- };
102
-
103
- function validateArgsAndRetrieveUberSchemaByType(rawArgs: RawArgs) {
104
- const args = validateRawArgs(rawArgs);
105
- const arkTSComponentSpecPaths = specPathsToSpecFilePaths(
106
- args.arkTSComponentsSpecPaths
107
- );
108
- const turboModulesUberSchema = UberSchema.fromSpecFilePaths(
109
- specPathsToSpecFilePaths(args.tmSpecPaths)
110
- );
111
- const arkTSComponentsUberSchema = UberSchema.fromSpecFilePaths(
112
- arkTSComponentSpecPaths
113
- );
114
- const cppComponentSpecPaths = specPathsToSpecFilePaths(
115
- args.cppComponentsSpecPaths
116
- );
117
- const cppComponentsUberSchema = UberSchema.fromSpecFilePaths(
118
- cppComponentSpecPaths
119
- );
120
- const componentsUberSchema = UberSchema.fromSpecFilePaths([
121
- ...arkTSComponentSpecPaths,
122
- ...cppComponentSpecPaths,
123
- ]);
124
-
125
- return {
126
- args,
127
- uberSchemaByType: {
128
- turboModulesUberSchema,
129
- arkTSComponentsUberSchema,
130
- cppComponentsUberSchema,
131
- componentsUberSchema,
132
- },
133
- };
134
- }
135
-
136
- type Args = {
137
- npmPackageName: string;
138
- tmSpecPaths: AbsolutePath[];
139
- arkTSComponentsSpecPaths: AbsolutePath[];
140
- cppComponentsSpecPaths: AbsolutePath[];
141
- cppOutputPath: AbsolutePath;
142
- etsOutputPath: AbsolutePath;
143
- safetyCheck: boolean;
144
- };
145
-
146
- function validateRawArgs(rawArgs: RawArgs): Args {
147
- if (!rawArgs.npmPackageName) {
148
- throw new DescriptiveError({
149
- whatHappened: '--npm-package-name is required',
150
- whatCanUserDo: ['Please specify --npm-package-name'],
151
- });
152
- }
153
- if (!rawArgs.cppOutputPath) {
154
- throw new DescriptiveError({
155
- whatHappened: '--cpp-output-path is required',
156
- whatCanUserDo: ['Please specify --cpp-output-path'],
157
- });
158
- }
159
- if (!rawArgs.etsOutputPath) {
160
- throw new DescriptiveError({
161
- whatHappened: '--ets-output-path is required',
162
- whatCanUserDo: ['Please specify --ets-output-path'],
163
- });
164
- }
165
- return {
166
- npmPackageName: rawArgs.npmPackageName!,
167
- tmSpecPaths: (rawArgs.turboModulesSpecPaths ?? []).map(
168
- (path) => new AbsolutePath(path)
169
- ),
170
- arkTSComponentsSpecPaths: (rawArgs.arktsComponentsSpecPaths ?? []).map(
171
- (path) => new AbsolutePath(path)
172
- ),
173
- cppComponentsSpecPaths: (rawArgs.cppComponentsSpecPaths ?? []).map(
174
- (path) => new AbsolutePath(path)
175
- ),
176
- etsOutputPath: new AbsolutePath(rawArgs.etsOutputPath!),
177
- cppOutputPath: new AbsolutePath(rawArgs.cppOutputPath!),
178
- safetyCheck: !!rawArgs.safetyCheck,
179
- };
180
- }
181
-
182
- function specPathsToSpecFilePaths(specPaths: AbsolutePath[]): AbsolutePath[] {
183
- const SUPPORTED_SPEC_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx'];
184
- return specPaths.flatMap((specPath) => {
185
- if (!fs.existsSync(specPath.getValue())) {
186
- throw new DescriptiveError({
187
- whatHappened: `No such file or directory: ${specPath.getValue()}`,
188
- whatCanUserDo: [`Are you sure provided specPath exists?`],
189
- });
190
- }
191
- if (fs.lstatSync(specPath.getValue()).isDirectory()) {
192
- return findFilePathsWithExtensions(specPath, SUPPORTED_SPEC_EXTENSIONS);
193
- } else {
194
- const ext = specPath.getExtension();
195
- if (ext && SUPPORTED_SPEC_EXTENSIONS.includes(ext)) {
196
- return [specPath];
197
- }
198
- return [];
199
- }
200
- });
201
- }
202
-
203
- function generateCodeInMemory({
204
- args,
205
- uberSchemaByType: {
206
- arkTSComponentsUberSchema,
207
- componentsUberSchema,
208
- cppComponentsUberSchema,
209
- turboModulesUberSchema,
210
- },
211
- }: ReturnType<typeof validateArgsAndRetrieveUberSchemaByType>) {
212
- const CODEGEN_NOTICE_LINES = [
213
- `This code was generated by "react-native ${COMMAND_NAME}"`,
214
- ];
215
- const fileContentByPath = new Map<AbsolutePath, string>();
216
- const appendToFileContentByPath = (
217
- fileContent: string,
218
- path: AbsolutePath
219
- ) => {
220
- fileContentByPath.set(path, fileContent);
221
- };
222
-
223
- const turboModuleGlueCodeData = turboModulesUberSchema
224
- .findAllSpecSchemasByType('NativeModule')
225
- .map((specSchema) => {
226
- const nativeModuleCodeGenerator = new NativeModuleCodeGenerator(
227
- args.cppOutputPath.copyWithNewSegment(
228
- 'RNOH',
229
- 'generated',
230
- 'turbo_modules'
231
- ),
232
- args.etsOutputPath.copyWithNewSegment('turboModules'),
233
- CODEGEN_NOTICE_LINES,
234
- '@rnoh/react-native-openharmony/ts'
235
- );
236
- nativeModuleCodeGenerator
237
- .generate(specSchema)
238
- .forEach(appendToFileContentByPath);
239
- return nativeModuleCodeGenerator.getGlueCodeData();
240
- })
241
- .flat();
242
-
243
- const arkTSComponentCodeGeneratorCAPI = new ArkTSComponentCodeGeneratorCAPI(
244
- args.cppOutputPath.copyWithNewSegment('RNOH', 'generated', 'components'),
245
- args.etsOutputPath.copyWithNewSegment('components'),
246
- CODEGEN_NOTICE_LINES,
247
- '@rnoh/react-native-openharmony/ts'
248
- );
249
- arkTSComponentCodeGeneratorCAPI
250
- .generate(arkTSComponentsUberSchema)
251
- .forEach(appendToFileContentByPath);
252
-
253
- const libraryCppName = deriveLibraryCppNameFromNpmPackageName(
254
- args.npmPackageName
255
- );
256
- const cppComponentCodeGenerator = new CppComponentCodeGenerator(
257
- (filename) => {
258
- return args.cppOutputPath.copyWithNewSegment(
259
- 'RNOH',
260
- 'generated',
261
- 'components',
262
- filename
263
- );
264
- },
265
- CODEGEN_NOTICE_LINES
266
- );
267
- cppComponentCodeGenerator
268
- .generate({
269
- libraryCppName: libraryCppName,
270
- uberSchema: cppComponentsUberSchema,
271
- })
272
- .forEach(appendToFileContentByPath);
273
-
274
- new SharedComponentCodeGenerator((filename) => {
275
- return args.cppOutputPath.copyWithNewSegment(
276
- 'react',
277
- 'renderer',
278
- 'components',
279
- libraryCppName,
280
- filename
281
- );
282
- })
283
- .generate({
284
- libraryCppName: libraryCppName,
285
- uberSchema: componentsUberSchema,
286
- })
287
- .forEach(appendToFileContentByPath);
288
-
289
- new LibGlueCodeGenerator(
290
- args.cppOutputPath,
291
- args.etsOutputPath,
292
- CODEGEN_NOTICE_LINES
293
- )
294
- .generate({
295
- libraryCppName,
296
- arkTSComponents: arkTSComponentCodeGeneratorCAPI.getLibGlueCodeData(),
297
- cppComponents: cppComponentCodeGenerator
298
- .getGlueCodeData()
299
- .map(({ name }) => ({ componentName: name })),
300
- turboModules: turboModuleGlueCodeData,
301
- })
302
- .forEach(appendToFileContentByPath);
303
-
304
- return fileContentByPath;
305
- }
306
-
307
- function deriveLibraryCppNameFromNpmPackageName(
308
- npmPackageName: string
309
- ): string {
310
- let result = npmPackageName;
311
- if (npmPackageName.includes('/')) {
312
- result.replace('@', '');
313
- result = npmPackageName.replace('/', '__');
314
- }
315
- result = Case.snake(result);
316
- return result;
317
- }
318
-
319
- function saveAndLogCodegenResult(
320
- args: Args,
321
- logger: Logger,
322
- fileContentByPath: ReturnType<typeof generateCodeInMemory>
323
- ) {
324
- saveCodegenResultToFileSystem(
325
- fileContentByPath,
326
- args.cppOutputPath,
327
- args.etsOutputPath,
328
- args.safetyCheck
329
- );
330
- logCodegenResult(logger, fileContentByPath, new AbsolutePath(''));
331
- }
332
-
333
- function saveCodegenResultToFileSystem(
334
- fileContentByPath: Map<AbsolutePath, string>,
335
- cppOutputPath: AbsolutePath,
336
- etsOutputPath: AbsolutePath,
337
- enableSafetyCheck: boolean
338
- ) {
339
- prepareDirectory(cppOutputPath, enableSafetyCheck);
340
- prepareDirectory(etsOutputPath, enableSafetyCheck);
341
- prepareDirectory(
342
- etsOutputPath.copyWithNewSegment('components'),
343
- enableSafetyCheck
344
- );
345
- prepareDirectory(
346
- etsOutputPath.copyWithNewSegment('turboModules'),
347
- enableSafetyCheck
348
- );
349
- fileContentByPath.forEach((_fileContent, path) => {
350
- prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
351
- });
352
- fileContentByPath.forEach((fileContent, path) => {
353
- fs.writeFileSync(path.getValue(), fileContent);
354
- });
355
- }
356
-
357
- function prepareDirectory(path: AbsolutePath, enableSafetyCheck: boolean) {
358
- maybeMakeDirectories(path);
359
- if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
360
- throw new DescriptiveError({
361
- whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
362
- whatCanUserDo: [
363
- 'Run this command with --no-safety-check flag',
364
- 'Run codegen from different location',
365
- ],
366
- });
367
- }
368
- maybeRemoveFilesInDirectory(path);
369
- }
370
-
371
- function logCodegenResult(
372
- logger: Logger,
373
- fileContentByPath: Map<AbsolutePath, string>,
374
- rootPath: AbsolutePath
375
- ) {
376
- const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
377
- (path) => path.relativeTo(rootPath).getValue()
378
- );
379
- sortedRelativePathStrings.sort();
380
- sortedRelativePathStrings.forEach((pathStr) => {
381
- logger.info((styles) => styles.gray(`• ${pathStr}`));
382
- });
383
- logger.info(() => '');
384
- logger.info(
385
- (styles) =>
386
- `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`
387
- );
388
- logger.info(() => '');
389
- }