@react-native-oh/react-native-harmony-cli 0.0.26 → 0.0.27

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 (86) hide show
  1. package/dist/assetResolver.js +19 -0
  2. package/dist/codegen/core/CodeGenerator.js +2 -0
  3. package/dist/codegen/core/CodegenError.js +7 -0
  4. package/dist/codegen/core/EventUtils.js +19 -0
  5. package/dist/codegen/core/TypeAnnotationToTS.js +132 -0
  6. package/dist/codegen/core/UberSchema.js +103 -0
  7. package/dist/codegen/core/index.js +21 -0
  8. package/dist/codegen/generators/AppBuildTimeGlueCodeGenerator.js +61 -0
  9. package/dist/codegen/generators/ArkTSComponentCodeGeneratorArkTS.js +76 -0
  10. package/dist/codegen/generators/ArkTSComponentCodeGeneratorCAPI.js +74 -0
  11. package/dist/codegen/generators/CppComponentCodeGenerator.js +56 -0
  12. package/dist/codegen/generators/LibGlueCodeGenerator.js +50 -0
  13. package/dist/codegen/generators/NativeModuleCodeGenerator.js +73 -0
  14. package/dist/codegen/generators/SharedComponentCodeGenerator.js +34 -0
  15. package/dist/codegen/generators/UberGeneratorV1.js +50 -0
  16. package/dist/codegen/generators/UberGeneratorV2.js +71 -0
  17. package/dist/codegen/generators/index.js +24 -0
  18. package/dist/codegen/index.js +18 -0
  19. package/dist/codegen/templates/BaseComponentInstanceHTemplate.js +105 -0
  20. package/dist/codegen/templates/BasePackageHTemplate.js +130 -0
  21. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +62 -0
  22. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +85 -0
  23. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +192 -0
  24. package/dist/codegen/templates/IndexTSTemplate.js +52 -0
  25. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +124 -0
  26. package/dist/codegen/templates/TurboModuleCppTemplate.js +53 -0
  27. package/dist/codegen/templates/TurboModuleHTemplate.js +42 -0
  28. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +75 -0
  29. package/dist/codegen/templates/index.js +25 -0
  30. package/dist/commands/bundle-harmony.js +179 -0
  31. package/dist/commands/codegen-harmony.js +201 -0
  32. package/dist/commands/codegen-lib-harmony.js +253 -0
  33. package/dist/commands/create-metro-host-constants.js +61 -0
  34. package/dist/commands/index.js +23 -0
  35. package/dist/commands/pack-harmony.js +100 -0
  36. package/dist/commands/unpack-harmony.js +184 -0
  37. package/dist/commands/verify-package-harmony.js +122 -0
  38. package/dist/core/AbsolutePath.js +47 -0
  39. package/dist/core/CodegenConfig.js +57 -0
  40. package/dist/core/DescriptiveError.js +49 -0
  41. package/dist/core/OHPackageJSON5.js +23 -0
  42. package/dist/core/PackageJSON.js +58 -0
  43. package/dist/core/ProjectDependenciesManager.js +70 -0
  44. package/dist/core/ValidationError.js +6 -0
  45. package/dist/core/ValueObject.js +2 -0
  46. package/dist/core/fs.js +36 -0
  47. package/dist/core/index.js +25 -0
  48. package/dist/index.js +15 -0
  49. package/dist/io/Logger.js +71 -0
  50. package/dist/io/TarGz.js +28 -0
  51. package/dist/io/fsUtils.js +23 -0
  52. package/dist/io/index.js +19 -0
  53. package/dist/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.js +38 -0
  54. package/dist/package-verifier/checks/HarmonyDirExistsCheck.js +32 -0
  55. package/dist/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.js +26 -0
  56. package/dist/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.js +51 -0
  57. package/dist/package-verifier/checks/index.js +20 -0
  58. package/dist/package-verifier/index.js +18 -0
  59. package/dist/package-verifier/types.js +2 -0
  60. package/dist/package-verifier/verify-package.js +101 -0
  61. package/package.json +1 -1
  62. package/src/codegen/core/UberSchema.ts +4 -0
  63. package/src/codegen/generators/{GlueCodeGenerator.ts → AppBuildTimeGlueCodeGenerator.ts} +13 -9
  64. package/src/codegen/generators/{ComponentCodeGeneratorArkTS.ts → ArkTSComponentCodeGeneratorArkTS.ts} +11 -5
  65. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +112 -0
  66. package/src/codegen/generators/{ComponentCodeGeneratorCAPI.ts → CppComponentCodeGenerator.ts} +14 -43
  67. package/src/codegen/generators/LibGlueCodeGenerator.ts +91 -0
  68. package/src/codegen/generators/NativeModuleCodeGenerator.ts +7 -5
  69. package/src/codegen/generators/SharedComponentCodeGenerator.ts +50 -0
  70. package/src/codegen/generators/UberGeneratorV1.ts +12 -8
  71. package/src/codegen/generators/UberGeneratorV2.ts +32 -16
  72. package/src/codegen/generators/index.ts +5 -3
  73. package/src/codegen/templates/BaseComponentInstanceHTemplate.ts +12 -7
  74. package/src/codegen/templates/{GeneratedPackageHTemplate.ts → BasePackageHTemplate.ts} +45 -12
  75. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +2 -1
  76. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +8 -10
  77. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +13 -8
  78. package/src/codegen/templates/IndexTSTemplate.ts +11 -9
  79. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +1 -0
  80. package/src/codegen/templates/TurboModuleCppTemplate.ts +9 -9
  81. package/src/codegen/templates/TurboModuleHTemplate.ts +9 -9
  82. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +13 -9
  83. package/src/commands/codegen-harmony.ts +24 -7
  84. package/src/commands/codegen-lib-harmony.ts +387 -0
  85. package/src/commands/index.ts +1 -0
  86. package/src/index.ts +2 -0
@@ -0,0 +1,387 @@
1
+ import { Command } from '@react-native-community/cli-types';
2
+ import {
3
+ AbsolutePath,
4
+ DescriptiveError,
5
+ maybeMakeDirectories,
6
+ maybeRemoveFilesInDirectory,
7
+ } from '../core';
8
+ import { Logger, findFilePathsWithExtensions } from '../io';
9
+ import fs from 'node:fs';
10
+ import {
11
+ ArkTSComponentCodeGeneratorCAPI,
12
+ CppComponentCodeGenerator,
13
+ NativeModuleCodeGenerator,
14
+ UberSchema,
15
+ SharedComponentCodeGenerator,
16
+ } from '../codegen';
17
+ import Case from 'case';
18
+ import { LibGlueCodeGenerator } from '../codegen/generators/LibGlueCodeGenerator';
19
+
20
+ const COMMAND_NAME = 'codegen-lib-harmony';
21
+
22
+ export const commandCodegenLibHarmony: Command = {
23
+ name: COMMAND_NAME,
24
+ description:
25
+ '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.',
26
+ options: [
27
+ {
28
+ name: '--npm-package-name <string>',
29
+ description:
30
+ '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.',
31
+ },
32
+ {
33
+ name: '--turbo-modules-spec-paths [path]',
34
+ description:
35
+ 'Path or paths to Turbo Module spec files. Each path can point to a spec file or a directory containing spec files.',
36
+ parse: (val: string) => val.split(' '),
37
+ },
38
+ {
39
+ name: '--arkts-components-spec-paths [path]',
40
+ description:
41
+ '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.',
42
+ parse: (val: string) => val.split(' '),
43
+ },
44
+ {
45
+ name: '--cpp-components-spec-paths [path]',
46
+ description:
47
+ '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.',
48
+ parse: (val: string) => val.split(' '),
49
+ },
50
+ {
51
+ name: '--cpp-output-path <path>',
52
+ description:
53
+ 'Specifies the relative path to the output directory intended for storing generated C++ files.',
54
+ },
55
+ {
56
+ name: '--ets-output-path <path>',
57
+ description:
58
+ 'Specifies the relative path to the output directory intended for storing generated ETS files.',
59
+ },
60
+ {
61
+ name: '--no-safety-check [boolean]',
62
+ description:
63
+ '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.',
64
+ },
65
+ ],
66
+ func: async (_argv, _config, rawArgs: any) => {
67
+ const logger = new Logger();
68
+ try {
69
+ const { args, uberSchemaByType } =
70
+ validateArgsAndRetrieveUberSchemaByType(rawArgs);
71
+ const fileContentByPath = generateCodeInMemory({
72
+ args,
73
+ uberSchemaByType,
74
+ });
75
+ saveAndLogCodegenResult(args, logger, fileContentByPath);
76
+ } catch (err) {
77
+ if (err instanceof DescriptiveError && !err.isUnexpected()) {
78
+ logger.descriptiveError(err);
79
+ return;
80
+ }
81
+ throw err;
82
+ }
83
+ },
84
+ };
85
+
86
+ type RawArgs = {
87
+ npmPackageName?: string;
88
+ turboModulesSpecPaths?: string[];
89
+ arktsComponentsSpecPaths?: string[];
90
+ cppComponentsSpecPaths?: string[];
91
+ cppOutputPath?: string;
92
+ etsOutputPath?: string;
93
+ safetyCheck?: boolean;
94
+ };
95
+
96
+ function validateArgsAndRetrieveUberSchemaByType(rawArgs: RawArgs) {
97
+ const args = validateRawArgs(rawArgs);
98
+ const arkTSComponentSpecPaths = specPathsToSpecFilePaths(
99
+ args.arkTSComponentsSpecPaths
100
+ );
101
+ const turboModulesUberSchema = UberSchema.fromSpecFilePaths(
102
+ specPathsToSpecFilePaths(args.tmSpecPaths)
103
+ );
104
+ const arkTSComponentsUberSchema = UberSchema.fromSpecFilePaths(
105
+ arkTSComponentSpecPaths
106
+ );
107
+ const cppComponentSpecPaths = specPathsToSpecFilePaths(
108
+ args.cppComponentsSpecPaths
109
+ );
110
+ const cppComponentsUberSchema = UberSchema.fromSpecFilePaths(
111
+ cppComponentSpecPaths
112
+ );
113
+ const componentsUberSchema = UberSchema.fromSpecFilePaths([
114
+ ...arkTSComponentSpecPaths,
115
+ ...cppComponentSpecPaths,
116
+ ]);
117
+
118
+ return {
119
+ args,
120
+ uberSchemaByType: {
121
+ turboModulesUberSchema,
122
+ arkTSComponentsUberSchema,
123
+ cppComponentsUberSchema,
124
+ componentsUberSchema,
125
+ },
126
+ };
127
+ }
128
+
129
+ type Args = {
130
+ npmPackageName: string;
131
+ tmSpecPaths: AbsolutePath[];
132
+ arkTSComponentsSpecPaths: AbsolutePath[];
133
+ cppComponentsSpecPaths: AbsolutePath[];
134
+ cppOutputPath: AbsolutePath;
135
+ etsOutputPath: AbsolutePath;
136
+ safetyCheck: boolean;
137
+ };
138
+
139
+ function validateRawArgs(rawArgs: RawArgs): Args {
140
+ if (!rawArgs.npmPackageName) {
141
+ throw new DescriptiveError({
142
+ whatHappened: '--npm-package-name is required',
143
+ whatCanUserDo: { default: ['Please specify --npm-package-name'] },
144
+ });
145
+ }
146
+ if (!rawArgs.cppOutputPath) {
147
+ throw new DescriptiveError({
148
+ whatHappened: '--cpp-output-path is required',
149
+ whatCanUserDo: { default: ['Please specify --cpp-output-path'] },
150
+ });
151
+ }
152
+ if (!rawArgs.etsOutputPath) {
153
+ throw new DescriptiveError({
154
+ whatHappened: '--ets-output-path is required',
155
+ whatCanUserDo: { default: ['Please specify --ets-output-path'] },
156
+ });
157
+ }
158
+ return {
159
+ npmPackageName: rawArgs.npmPackageName!,
160
+ tmSpecPaths: (rawArgs.turboModulesSpecPaths ?? []).map(
161
+ (path) => new AbsolutePath(path)
162
+ ),
163
+ arkTSComponentsSpecPaths: (rawArgs.arktsComponentsSpecPaths ?? []).map(
164
+ (path) => new AbsolutePath(path)
165
+ ),
166
+ cppComponentsSpecPaths: (rawArgs.cppComponentsSpecPaths ?? []).map(
167
+ (path) => new AbsolutePath(path)
168
+ ),
169
+ etsOutputPath: new AbsolutePath(rawArgs.etsOutputPath!),
170
+ cppOutputPath: new AbsolutePath(rawArgs.cppOutputPath!),
171
+ safetyCheck: !!rawArgs.safetyCheck,
172
+ };
173
+ }
174
+
175
+ function specPathsToSpecFilePaths(specPaths: AbsolutePath[]): AbsolutePath[] {
176
+ const SUPPORTED_SPEC_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx'];
177
+ return specPaths.flatMap((specPath) => {
178
+ if (!fs.existsSync(specPath.getValue())) {
179
+ throw new DescriptiveError({
180
+ whatHappened: `No such file or directory: ${specPath.getValue()}`,
181
+ whatCanUserDo: {
182
+ default: [`Are you sure provided specPath exists?`],
183
+ },
184
+ });
185
+ }
186
+ if (fs.lstatSync(specPath.getValue()).isDirectory()) {
187
+ return findFilePathsWithExtensions(specPath, SUPPORTED_SPEC_EXTENSIONS);
188
+ } else {
189
+ const ext = specPath.getExtension();
190
+ if (ext && SUPPORTED_SPEC_EXTENSIONS.includes(ext)) {
191
+ return [specPath];
192
+ }
193
+ return [];
194
+ }
195
+ });
196
+ }
197
+
198
+ function generateCodeInMemory({
199
+ args,
200
+ uberSchemaByType: {
201
+ arkTSComponentsUberSchema,
202
+ componentsUberSchema,
203
+ cppComponentsUberSchema,
204
+ turboModulesUberSchema,
205
+ },
206
+ }: ReturnType<typeof validateArgsAndRetrieveUberSchemaByType>) {
207
+ const CODEGEN_NOTICE_LINES = [
208
+ `This code was generated by "react-native ${COMMAND_NAME}"`,
209
+ ];
210
+ const fileContentByPath = new Map<AbsolutePath, string>();
211
+ const appendToFileContentByPath = (
212
+ fileContent: string,
213
+ path: AbsolutePath
214
+ ) => {
215
+ fileContentByPath.set(path, fileContent);
216
+ };
217
+
218
+ const turboModuleGlueCodeData = turboModulesUberSchema
219
+ .findAllSpecSchemasByType('NativeModule')
220
+ .map((specSchema) => {
221
+ const nativeModuleCodeGenerator = new NativeModuleCodeGenerator(
222
+ args.cppOutputPath.copyWithNewSegment(
223
+ 'RNOH',
224
+ 'generated',
225
+ 'turbo_modules'
226
+ ),
227
+ args.etsOutputPath.copyWithNewSegment('turboModules'),
228
+ CODEGEN_NOTICE_LINES,
229
+ '@rnoh/react-native-openharmony/ts'
230
+ );
231
+ nativeModuleCodeGenerator
232
+ .generate(specSchema)
233
+ .forEach(appendToFileContentByPath);
234
+ return nativeModuleCodeGenerator.getGlueCodeData();
235
+ })
236
+ .flat();
237
+
238
+ const arkTSComponentCodeGeneratorCAPI = new ArkTSComponentCodeGeneratorCAPI(
239
+ args.cppOutputPath.copyWithNewSegment('RNOH', 'generated', 'components'),
240
+ args.etsOutputPath.copyWithNewSegment('components'),
241
+ CODEGEN_NOTICE_LINES,
242
+ '@rnoh/react-native-openharmony/ts'
243
+ );
244
+ arkTSComponentCodeGeneratorCAPI
245
+ .generate(arkTSComponentsUberSchema)
246
+ .forEach(appendToFileContentByPath);
247
+
248
+ const libraryCppName = deriveLibraryCppNameFromNpmPackageName(
249
+ args.npmPackageName
250
+ );
251
+ const cppComponentCodeGenerator = new CppComponentCodeGenerator(
252
+ (filename) => {
253
+ return args.cppOutputPath.copyWithNewSegment(
254
+ 'RNOH',
255
+ 'generated',
256
+ 'components',
257
+ filename
258
+ );
259
+ },
260
+ CODEGEN_NOTICE_LINES
261
+ );
262
+ cppComponentCodeGenerator
263
+ .generate({
264
+ libraryCppName: libraryCppName,
265
+ uberSchema: cppComponentsUberSchema,
266
+ })
267
+ .forEach(appendToFileContentByPath);
268
+
269
+ new SharedComponentCodeGenerator((filename) => {
270
+ return args.cppOutputPath.copyWithNewSegment(
271
+ 'react',
272
+ 'renderer',
273
+ 'components',
274
+ libraryCppName,
275
+ filename
276
+ );
277
+ })
278
+ .generate({
279
+ libraryCppName: libraryCppName,
280
+ uberSchema: componentsUberSchema,
281
+ })
282
+ .forEach(appendToFileContentByPath);
283
+
284
+ new LibGlueCodeGenerator(
285
+ args.cppOutputPath,
286
+ args.etsOutputPath,
287
+ CODEGEN_NOTICE_LINES
288
+ )
289
+ .generate({
290
+ libraryCppName,
291
+ arkTSComponents: arkTSComponentCodeGeneratorCAPI.getLibGlueCodeData(),
292
+ cppComponents: cppComponentCodeGenerator
293
+ .getGlueCodeData()
294
+ .map(({ name }) => ({ componentName: name })),
295
+ turboModules: turboModuleGlueCodeData,
296
+ })
297
+ .forEach(appendToFileContentByPath);
298
+
299
+ return fileContentByPath;
300
+ }
301
+
302
+ function deriveLibraryCppNameFromNpmPackageName(
303
+ npmPackageName: string
304
+ ): string {
305
+ let result = npmPackageName;
306
+ if (npmPackageName.includes('/')) {
307
+ result.replace('@', '');
308
+ result = npmPackageName.replace('/', '__');
309
+ }
310
+ result = Case.snake(result);
311
+ return result;
312
+ }
313
+
314
+ function saveAndLogCodegenResult(
315
+ args: Args,
316
+ logger: Logger,
317
+ fileContentByPath: ReturnType<typeof generateCodeInMemory>
318
+ ) {
319
+ saveCodegenResultToFileSystem(
320
+ fileContentByPath,
321
+ args.cppOutputPath,
322
+ args.etsOutputPath,
323
+ args.safetyCheck
324
+ );
325
+ logCodegenResult(logger, fileContentByPath, new AbsolutePath(''));
326
+ }
327
+
328
+ function saveCodegenResultToFileSystem(
329
+ fileContentByPath: Map<AbsolutePath, string>,
330
+ cppOutputPath: AbsolutePath,
331
+ etsOutputPath: AbsolutePath,
332
+ enableSafetyCheck: boolean
333
+ ) {
334
+ prepareDirectory(cppOutputPath, enableSafetyCheck);
335
+ prepareDirectory(etsOutputPath, enableSafetyCheck);
336
+ prepareDirectory(
337
+ etsOutputPath.copyWithNewSegment('components'),
338
+ enableSafetyCheck
339
+ );
340
+ prepareDirectory(
341
+ etsOutputPath.copyWithNewSegment('turboModules'),
342
+ enableSafetyCheck
343
+ );
344
+ fileContentByPath.forEach((_fileContent, path) => {
345
+ prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
346
+ });
347
+ fileContentByPath.forEach((fileContent, path) => {
348
+ fs.writeFileSync(path.getValue(), fileContent);
349
+ });
350
+ }
351
+
352
+ function prepareDirectory(path: AbsolutePath, enableSafetyCheck: boolean) {
353
+ maybeMakeDirectories(path);
354
+ if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
355
+ throw new DescriptiveError({
356
+ whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
357
+ whatCanUserDo: {
358
+ default: [
359
+ 'Run this command with --no-safety-check flag',
360
+ 'Run codegen from different location',
361
+ ],
362
+ },
363
+ });
364
+ }
365
+ maybeRemoveFilesInDirectory(path);
366
+ }
367
+
368
+ function logCodegenResult(
369
+ logger: Logger,
370
+ fileContentByPath: Map<AbsolutePath, string>,
371
+ rootPath: AbsolutePath
372
+ ) {
373
+ const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
374
+ (path) => path.relativeTo(rootPath).getValue()
375
+ );
376
+ sortedRelativePathStrings.sort();
377
+ sortedRelativePathStrings.forEach((pathStr) => {
378
+ logger.info((styles) => styles.gray(`• ${pathStr}`));
379
+ });
380
+ logger.info(() => '');
381
+ logger.info(
382
+ (styles) =>
383
+ `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`,
384
+ { prefix: true }
385
+ );
386
+ logger.info(() => '');
387
+ }
@@ -4,3 +4,4 @@ export * from './unpack-harmony';
4
4
  export * from './create-metro-host-constants';
5
5
  export * from './codegen-harmony';
6
6
  export * from './verify-package-harmony';
7
+ export * from './codegen-lib-harmony';
package/src/index.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  commandCreateMetroConstantsHarmony,
7
7
  commandCodegenHarmony,
8
8
  commandVerifyPackageHarmony,
9
+ commandCodegenLibHarmony,
9
10
  } from './commands';
10
11
 
11
12
  export const config = {
@@ -16,5 +17,6 @@ export const config = {
16
17
  commandCreateMetroConstantsHarmony,
17
18
  commandCodegenHarmony,
18
19
  commandVerifyPackageHarmony,
20
+ commandCodegenLibHarmony,
19
21
  ],
20
22
  } satisfies Partial<Config>;