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

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 (140) hide show
  1. package/README.md +12 -0
  2. package/dist/assetResolver.js +25 -0
  3. package/dist/autolinking/Autolinking.js +275 -0
  4. package/dist/autolinking/index.js +23 -0
  5. package/dist/codegen/core/CodeGenerator.js +8 -0
  6. package/dist/codegen/core/CodegenError.js +13 -0
  7. package/dist/codegen/core/EventUtils.js +25 -0
  8. package/dist/codegen/core/TypeAnnotationToTS.js +138 -0
  9. package/dist/codegen/core/UberSchema.js +109 -0
  10. package/dist/codegen/core/index.js +27 -0
  11. package/dist/codegen/generators/AppBuildTimeGlueCodeGenerator.js +67 -0
  12. package/dist/codegen/generators/ArkTSComponentCodeGeneratorArkTS.js +82 -0
  13. package/dist/codegen/generators/ArkTSComponentCodeGeneratorCAPI.js +80 -0
  14. package/dist/codegen/generators/CppComponentCodeGenerator.js +62 -0
  15. package/dist/codegen/generators/LibGlueCodeGenerator.js +56 -0
  16. package/dist/codegen/generators/NativeModuleCodeGenerator.js +79 -0
  17. package/dist/codegen/generators/SharedComponentCodeGenerator.js +40 -0
  18. package/dist/codegen/generators/UberGeneratorV1.js +56 -0
  19. package/dist/codegen/generators/UberGeneratorV2.js +77 -0
  20. package/dist/codegen/generators/index.js +30 -0
  21. package/dist/codegen/index.js +24 -0
  22. package/dist/codegen/templates/BaseComponentInstanceHTemplate.js +111 -0
  23. package/dist/codegen/templates/BasePackageHTemplate.js +136 -0
  24. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +68 -0
  25. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +91 -0
  26. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +198 -0
  27. package/dist/codegen/templates/IndexTSTemplate.js +58 -0
  28. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +130 -0
  29. package/dist/codegen/templates/TurboModuleCppTemplate.js +59 -0
  30. package/dist/codegen/templates/TurboModuleHTemplate.js +48 -0
  31. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +81 -0
  32. package/dist/codegen/templates/index.js +31 -0
  33. package/dist/commands/bundle-harmony.js +185 -0
  34. package/dist/commands/codegen-harmony.js +207 -0
  35. package/dist/commands/codegen-lib-harmony.js +259 -0
  36. package/dist/commands/create-metro-host-constants.js +67 -0
  37. package/dist/commands/index.js +30 -0
  38. package/dist/commands/link-harmony.js +97 -0
  39. package/dist/commands/pack-harmony.js +106 -0
  40. package/dist/commands/unpack-harmony.js +191 -0
  41. package/dist/commands/verify-package-harmony.js +128 -0
  42. package/dist/core/AbsolutePath.js +59 -0
  43. package/dist/core/CodegenConfig.js +63 -0
  44. package/dist/core/DescriptiveError.js +55 -0
  45. package/dist/core/FileSystem.js +33 -0
  46. package/dist/core/OHPackageJSON5.js +29 -0
  47. package/dist/core/PackageJSON.js +66 -0
  48. package/dist/core/ProjectDependenciesManager.js +83 -0
  49. package/dist/core/ValidationError.js +12 -0
  50. package/dist/core/ValueObject.js +8 -0
  51. package/dist/core/fs.js +42 -0
  52. package/dist/core/index.js +32 -0
  53. package/dist/index.js +22 -0
  54. package/dist/io/CliExecutor.js +35 -0
  55. package/dist/io/Logger.js +80 -0
  56. package/dist/io/RealFS.js +68 -0
  57. package/dist/io/TarGz.js +34 -0
  58. package/dist/io/__fixtures__.js +127 -0
  59. package/dist/io/fsUtils.js +37 -0
  60. package/dist/io/index.js +26 -0
  61. package/dist/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.js +44 -0
  62. package/dist/package-verifier/checks/HarmonyDirExistsCheck.js +38 -0
  63. package/dist/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.js +32 -0
  64. package/dist/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.js +57 -0
  65. package/dist/package-verifier/checks/index.js +26 -0
  66. package/dist/package-verifier/index.js +24 -0
  67. package/dist/package-verifier/types.js +8 -0
  68. package/dist/package-verifier/verify-package.js +107 -0
  69. package/jest.config.js +7 -0
  70. package/package.json +8 -2
  71. package/react-native.config.js +7 -0
  72. package/src/assetResolver.ts +7 -0
  73. package/src/autolinking/Autolinking.test.ts +483 -0
  74. package/src/autolinking/Autolinking.ts +384 -0
  75. package/src/autolinking/index.ts +8 -0
  76. package/src/codegen/core/CodeGenerator.ts +7 -0
  77. package/src/codegen/core/CodegenError.ts +7 -0
  78. package/src/codegen/core/EventUtils.ts +7 -0
  79. package/src/codegen/core/TypeAnnotationToTS.test.ts +7 -0
  80. package/src/codegen/core/TypeAnnotationToTS.ts +7 -0
  81. package/src/codegen/core/UberSchema.ts +15 -1
  82. package/src/codegen/core/index.ts +7 -0
  83. package/src/codegen/generators/{GlueCodeGenerator.ts → AppBuildTimeGlueCodeGenerator.ts} +20 -9
  84. package/src/codegen/generators/{ComponentCodeGeneratorArkTS.ts → ArkTSComponentCodeGeneratorArkTS.ts} +18 -5
  85. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +119 -0
  86. package/src/codegen/generators/{ComponentCodeGeneratorCAPI.ts → CppComponentCodeGenerator.ts} +21 -43
  87. package/src/codegen/generators/LibGlueCodeGenerator.ts +98 -0
  88. package/src/codegen/generators/NativeModuleCodeGenerator.ts +14 -5
  89. package/src/codegen/generators/SharedComponentCodeGenerator.ts +57 -0
  90. package/src/codegen/generators/UberGeneratorV1.ts +19 -8
  91. package/src/codegen/generators/UberGeneratorV2.ts +39 -16
  92. package/src/codegen/generators/index.ts +12 -3
  93. package/src/codegen/index.ts +7 -0
  94. package/src/codegen/templates/BaseComponentInstanceHTemplate.ts +19 -7
  95. package/src/codegen/templates/{GeneratedPackageHTemplate.ts → BasePackageHTemplate.ts} +52 -12
  96. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +9 -1
  97. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +15 -10
  98. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +20 -8
  99. package/src/codegen/templates/IndexTSTemplate.ts +18 -9
  100. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +8 -0
  101. package/src/codegen/templates/TurboModuleCppTemplate.ts +16 -9
  102. package/src/codegen/templates/TurboModuleHTemplate.ts +16 -9
  103. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +20 -9
  104. package/src/codegen/templates/index.ts +7 -0
  105. package/src/commands/bundle-harmony.ts +8 -1
  106. package/src/commands/codegen-harmony.ts +43 -13
  107. package/src/commands/codegen-lib-harmony.ts +394 -0
  108. package/src/commands/create-metro-host-constants.ts +7 -0
  109. package/src/commands/index.ts +9 -0
  110. package/src/commands/link-harmony.ts +102 -0
  111. package/src/commands/pack-harmony.ts +7 -0
  112. package/src/commands/unpack-harmony.ts +12 -3
  113. package/src/commands/verify-package-harmony.ts +7 -0
  114. package/src/core/AbsolutePath.ts +16 -0
  115. package/src/core/CodegenConfig.ts +7 -0
  116. package/src/core/DescriptiveError.ts +7 -0
  117. package/src/core/FileSystem.ts +57 -0
  118. package/src/core/OHPackageJSON5.ts +7 -0
  119. package/src/core/PackageJSON.ts +40 -8
  120. package/src/core/ProjectDependenciesManager.ts +40 -14
  121. package/src/core/ValidationError.ts +7 -0
  122. package/src/core/ValueObject.ts +7 -0
  123. package/src/core/fs.ts +7 -0
  124. package/src/core/index.ts +8 -0
  125. package/src/index.ts +11 -0
  126. package/src/io/CliExecutor.ts +47 -0
  127. package/src/io/Logger.ts +11 -0
  128. package/src/io/RealFS.ts +62 -0
  129. package/src/io/TarGz.ts +7 -0
  130. package/src/io/__fixtures__.ts +135 -0
  131. package/src/io/fsUtils.ts +26 -6
  132. package/src/io/index.ts +8 -0
  133. package/src/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.ts +7 -0
  134. package/src/package-verifier/checks/HarmonyDirExistsCheck.ts +7 -0
  135. package/src/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.ts +7 -0
  136. package/src/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.ts +7 -0
  137. package/src/package-verifier/checks/index.ts +7 -0
  138. package/src/package-verifier/index.ts +7 -0
  139. package/src/package-verifier/types.ts +7 -0
  140. package/src/package-verifier/verify-package.ts +9 -1
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Copyright (c) 2024 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 '@react-native-community/cli-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: { default: ['Please specify --npm-package-name'] },
151
+ });
152
+ }
153
+ if (!rawArgs.cppOutputPath) {
154
+ throw new DescriptiveError({
155
+ whatHappened: '--cpp-output-path is required',
156
+ whatCanUserDo: { default: ['Please specify --cpp-output-path'] },
157
+ });
158
+ }
159
+ if (!rawArgs.etsOutputPath) {
160
+ throw new DescriptiveError({
161
+ whatHappened: '--ets-output-path is required',
162
+ whatCanUserDo: { default: ['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: {
189
+ default: [`Are you sure provided specPath exists?`],
190
+ },
191
+ });
192
+ }
193
+ if (fs.lstatSync(specPath.getValue()).isDirectory()) {
194
+ return findFilePathsWithExtensions(specPath, SUPPORTED_SPEC_EXTENSIONS);
195
+ } else {
196
+ const ext = specPath.getExtension();
197
+ if (ext && SUPPORTED_SPEC_EXTENSIONS.includes(ext)) {
198
+ return [specPath];
199
+ }
200
+ return [];
201
+ }
202
+ });
203
+ }
204
+
205
+ function generateCodeInMemory({
206
+ args,
207
+ uberSchemaByType: {
208
+ arkTSComponentsUberSchema,
209
+ componentsUberSchema,
210
+ cppComponentsUberSchema,
211
+ turboModulesUberSchema,
212
+ },
213
+ }: ReturnType<typeof validateArgsAndRetrieveUberSchemaByType>) {
214
+ const CODEGEN_NOTICE_LINES = [
215
+ `This code was generated by "react-native ${COMMAND_NAME}"`,
216
+ ];
217
+ const fileContentByPath = new Map<AbsolutePath, string>();
218
+ const appendToFileContentByPath = (
219
+ fileContent: string,
220
+ path: AbsolutePath
221
+ ) => {
222
+ fileContentByPath.set(path, fileContent);
223
+ };
224
+
225
+ const turboModuleGlueCodeData = turboModulesUberSchema
226
+ .findAllSpecSchemasByType('NativeModule')
227
+ .map((specSchema) => {
228
+ const nativeModuleCodeGenerator = new NativeModuleCodeGenerator(
229
+ args.cppOutputPath.copyWithNewSegment(
230
+ 'RNOH',
231
+ 'generated',
232
+ 'turbo_modules'
233
+ ),
234
+ args.etsOutputPath.copyWithNewSegment('turboModules'),
235
+ CODEGEN_NOTICE_LINES,
236
+ '@rnoh/react-native-openharmony/ts'
237
+ );
238
+ nativeModuleCodeGenerator
239
+ .generate(specSchema)
240
+ .forEach(appendToFileContentByPath);
241
+ return nativeModuleCodeGenerator.getGlueCodeData();
242
+ })
243
+ .flat();
244
+
245
+ const arkTSComponentCodeGeneratorCAPI = new ArkTSComponentCodeGeneratorCAPI(
246
+ args.cppOutputPath.copyWithNewSegment('RNOH', 'generated', 'components'),
247
+ args.etsOutputPath.copyWithNewSegment('components'),
248
+ CODEGEN_NOTICE_LINES,
249
+ '@rnoh/react-native-openharmony/ts'
250
+ );
251
+ arkTSComponentCodeGeneratorCAPI
252
+ .generate(arkTSComponentsUberSchema)
253
+ .forEach(appendToFileContentByPath);
254
+
255
+ const libraryCppName = deriveLibraryCppNameFromNpmPackageName(
256
+ args.npmPackageName
257
+ );
258
+ const cppComponentCodeGenerator = new CppComponentCodeGenerator(
259
+ (filename) => {
260
+ return args.cppOutputPath.copyWithNewSegment(
261
+ 'RNOH',
262
+ 'generated',
263
+ 'components',
264
+ filename
265
+ );
266
+ },
267
+ CODEGEN_NOTICE_LINES
268
+ );
269
+ cppComponentCodeGenerator
270
+ .generate({
271
+ libraryCppName: libraryCppName,
272
+ uberSchema: cppComponentsUberSchema,
273
+ })
274
+ .forEach(appendToFileContentByPath);
275
+
276
+ new SharedComponentCodeGenerator((filename) => {
277
+ return args.cppOutputPath.copyWithNewSegment(
278
+ 'react',
279
+ 'renderer',
280
+ 'components',
281
+ libraryCppName,
282
+ filename
283
+ );
284
+ })
285
+ .generate({
286
+ libraryCppName: libraryCppName,
287
+ uberSchema: componentsUberSchema,
288
+ })
289
+ .forEach(appendToFileContentByPath);
290
+
291
+ new LibGlueCodeGenerator(
292
+ args.cppOutputPath,
293
+ args.etsOutputPath,
294
+ CODEGEN_NOTICE_LINES
295
+ )
296
+ .generate({
297
+ libraryCppName,
298
+ arkTSComponents: arkTSComponentCodeGeneratorCAPI.getLibGlueCodeData(),
299
+ cppComponents: cppComponentCodeGenerator
300
+ .getGlueCodeData()
301
+ .map(({ name }) => ({ componentName: name })),
302
+ turboModules: turboModuleGlueCodeData,
303
+ })
304
+ .forEach(appendToFileContentByPath);
305
+
306
+ return fileContentByPath;
307
+ }
308
+
309
+ function deriveLibraryCppNameFromNpmPackageName(
310
+ npmPackageName: string
311
+ ): string {
312
+ let result = npmPackageName;
313
+ if (npmPackageName.includes('/')) {
314
+ result.replace('@', '');
315
+ result = npmPackageName.replace('/', '__');
316
+ }
317
+ result = Case.snake(result);
318
+ return result;
319
+ }
320
+
321
+ function saveAndLogCodegenResult(
322
+ args: Args,
323
+ logger: Logger,
324
+ fileContentByPath: ReturnType<typeof generateCodeInMemory>
325
+ ) {
326
+ saveCodegenResultToFileSystem(
327
+ fileContentByPath,
328
+ args.cppOutputPath,
329
+ args.etsOutputPath,
330
+ args.safetyCheck
331
+ );
332
+ logCodegenResult(logger, fileContentByPath, new AbsolutePath(''));
333
+ }
334
+
335
+ function saveCodegenResultToFileSystem(
336
+ fileContentByPath: Map<AbsolutePath, string>,
337
+ cppOutputPath: AbsolutePath,
338
+ etsOutputPath: AbsolutePath,
339
+ enableSafetyCheck: boolean
340
+ ) {
341
+ prepareDirectory(cppOutputPath, enableSafetyCheck);
342
+ prepareDirectory(etsOutputPath, enableSafetyCheck);
343
+ prepareDirectory(
344
+ etsOutputPath.copyWithNewSegment('components'),
345
+ enableSafetyCheck
346
+ );
347
+ prepareDirectory(
348
+ etsOutputPath.copyWithNewSegment('turboModules'),
349
+ enableSafetyCheck
350
+ );
351
+ fileContentByPath.forEach((_fileContent, path) => {
352
+ prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
353
+ });
354
+ fileContentByPath.forEach((fileContent, path) => {
355
+ fs.writeFileSync(path.getValue(), fileContent);
356
+ });
357
+ }
358
+
359
+ function prepareDirectory(path: AbsolutePath, enableSafetyCheck: boolean) {
360
+ maybeMakeDirectories(path);
361
+ if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
362
+ throw new DescriptiveError({
363
+ whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
364
+ whatCanUserDo: {
365
+ default: [
366
+ 'Run this command with --no-safety-check flag',
367
+ 'Run codegen from different location',
368
+ ],
369
+ },
370
+ });
371
+ }
372
+ maybeRemoveFilesInDirectory(path);
373
+ }
374
+
375
+ function logCodegenResult(
376
+ logger: Logger,
377
+ fileContentByPath: Map<AbsolutePath, string>,
378
+ rootPath: AbsolutePath
379
+ ) {
380
+ const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
381
+ (path) => path.relativeTo(rootPath).getValue()
382
+ );
383
+ sortedRelativePathStrings.sort();
384
+ sortedRelativePathStrings.forEach((pathStr) => {
385
+ logger.info((styles) => styles.gray(`• ${pathStr}`));
386
+ });
387
+ logger.info(() => '');
388
+ logger.info(
389
+ (styles) =>
390
+ `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`,
391
+ { prefix: true }
392
+ );
393
+ logger.info(() => '');
394
+ }
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Copyright (c) 2024 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
+
1
8
  import { Command } from '@react-native-community/cli-types';
2
9
  import os from 'node:os';
3
10
  import fs from 'node:fs';
@@ -1,6 +1,15 @@
1
+ /**
2
+ * Copyright (c) 2024 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
+
1
8
  export * from './bundle-harmony';
2
9
  export * from './pack-harmony';
3
10
  export * from './unpack-harmony';
4
11
  export * from './create-metro-host-constants';
5
12
  export * from './codegen-harmony';
6
13
  export * from './verify-package-harmony';
14
+ export * from './codegen-lib-harmony';
15
+ export * from './link-harmony';
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Copyright (c) 2024 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 '@react-native-community/cli-types';
9
+ import { AbsolutePath, DescriptiveError } from '../core';
10
+ import { Logger, RealFS } from '../io';
11
+ import { Autolinking } from '../autolinking';
12
+
13
+ const COMMAND_NAME = 'link-harmony';
14
+
15
+ export const commandLinkHarmony: Command = {
16
+ name: COMMAND_NAME,
17
+ description:
18
+ 'Handles the automatic linking of RNOH libraries. This command is meant to be used by the RNOH HvigorPlugin.',
19
+ options: [
20
+ {
21
+ name: '--harmony-project-path <path>',
22
+ description: 'Specifies the root of your OpenHarmony project.',
23
+ default: './harmony',
24
+ },
25
+ {
26
+ name: '--node-modules-path <path>',
27
+ description:
28
+ 'Defines the path to the node_modules directory which holds npm packages.',
29
+ default: './node_modules',
30
+ },
31
+ {
32
+ name: '--cmake-autolink-path-relative-to-harmony <path>',
33
+ description:
34
+ 'Path relative to the root of your OpenHarmony project for the generated CMake file involved in autolinking.',
35
+ default: './entry/src/main/cpp/autolinking.cmake',
36
+ },
37
+ {
38
+ name: '--cpp-rnoh-packages-factory-path-relative-to-harmony <path>',
39
+ description:
40
+ 'Path relative to the root of your OpenHarmony project, for the generated file used to link packages on C++ side.',
41
+ default: './entry/src/main/cpp/RNOHPackagesFactory.h',
42
+ },
43
+ {
44
+ name: '--ets-rnoh-packages-factory-path-relative-to-harmony <path>',
45
+ description:
46
+ 'Path relative to the root of your OpenHarmony project, for the generated file used to link packages on ETS side.',
47
+ default: './entry/src/main/ets/RNOHPackagesFactory.ets',
48
+ },
49
+ {
50
+ name: '--oh-package-path-relative-to-harmony <path>',
51
+ description:
52
+ 'Path to the oh-package.json5 relative to the root of your OpenHarmony project.',
53
+ default: './oh-package.json5',
54
+ },
55
+ {
56
+ name: '--exclude-npm-packages [string]',
57
+ description:
58
+ "Lists npm package names to be excluded from the autolinking process, separated by semicolons. By default every library is included. Can't be used with --included-npm-packages.",
59
+ },
60
+ {
61
+ name: '--include-npm-packages [string]',
62
+ description:
63
+ "Lists npm package names to be included from the autolinking process, separated by semicolons. By default every library is included. Can't be used with --excluded-npm-packages.",
64
+ },
65
+ ],
66
+ func: async (_argv, _config, rawArgs: any) => {
67
+ const logger = new Logger();
68
+ const fs = new RealFS();
69
+ const autolinking = new Autolinking(fs, logger);
70
+ try {
71
+ const config = await autolinking.prepareInput({
72
+ harmonyProjectPath: new AbsolutePath(rawArgs.harmonyProjectPath),
73
+ nodeModulesPath: new AbsolutePath(rawArgs.nodeModulesPath),
74
+ cmakeAutolinkPathRelativeToHarmony:
75
+ rawArgs.cmakeAutolinkPathRelativeToHarmony,
76
+ cppRNOHPackagesFactoryPathRelativeToHarmony:
77
+ rawArgs.cppRnohPackagesFactoryPathRelativeToHarmony,
78
+ etsRNOHPackagesFactoryPathRelativeToHarmony:
79
+ rawArgs.etsRnohPackagesFactoryPathRelativeToHarmony,
80
+ ohPackagePathRelativeToHarmony: rawArgs.ohPackagePathRelativeToHarmony,
81
+ excludedNpmPackageNames: new Set(
82
+ rawArgs.excludeNpmPackages
83
+ ? (rawArgs.excludeNpmPackages ?? '').split(';')
84
+ : undefined
85
+ ),
86
+ includedNpmPackageNames: new Set(
87
+ rawArgs.includeNpmPackages
88
+ ? (rawArgs.includeNpmPackages ?? '').split(';')
89
+ : undefined
90
+ ),
91
+ });
92
+ const result = autolinking.evaluate(config);
93
+ autolinking.saveAndLogOutput(result);
94
+ } catch (err) {
95
+ if (err instanceof DescriptiveError && !err.isUnexpected()) {
96
+ logger.descriptiveError(err);
97
+ return;
98
+ }
99
+ throw err;
100
+ }
101
+ },
102
+ };
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Copyright (c) 2024 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
+
1
8
  import { Command } from '@react-native-community/cli-types';
2
9
  import { globSync } from 'glob';
3
10
  import pathUtils from 'path';
@@ -1,5 +1,12 @@
1
+ /**
2
+ * Copyright (c) 2024 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
+
1
8
  import { Command } from '@react-native-community/cli-types';
2
- import { Logger } from '../io';
9
+ import { Logger, RealFS } from '../io';
3
10
 
4
11
  import pathUtils from 'path';
5
12
  import fs from 'fs';
@@ -49,7 +56,9 @@ async function unpack(
49
56
  outputDirPath: AbsolutePath
50
57
  ) {
51
58
  const logger = new Logger();
59
+ const fs = new RealFS();
52
60
  const projectDependenciesManager = new ProjectDependenciesManager(
61
+ fs,
53
62
  projectRootPath
54
63
  );
55
64
  logger.info((styles) => styles.bold(`Unpacking RNOH modules`), {
@@ -79,7 +88,7 @@ async function unpack(
79
88
  packageJSON.version
80
89
  )
81
90
  ) {
82
- if (!fs.existsSync(pkgHarmonyDirPath.getValue())) {
91
+ if (!fs.existsSync(pkgHarmonyDirPath)) {
83
92
  /**
84
93
  * After fresh install, harmony.tar.gz wasn't unpacked to harmony. Updating npm package should remove unpacked harmony dir.
85
94
  */
@@ -116,7 +125,7 @@ async function unpack(
116
125
  );
117
126
  }
118
127
  } else {
119
- if (fs.existsSync(harmonyArchivePath.getValue())) {
128
+ if (fs.existsSync(harmonyArchivePath)) {
120
129
  skippedArchivesCount++;
121
130
  logger.info(
122
131
  (styles) =>
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Copyright (c) 2024 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
+
1
8
  import { Command } from '@react-native-community/cli-types';
2
9
  import { getLoader, Loader } from '@react-native-community/cli-tools';
3
10
  import chalk from 'chalk';
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Copyright (c) 2024 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
+
1
8
  import pathUtils from 'node:path';
2
9
  import { ValueObject } from './ValueObject';
3
10
 
@@ -7,6 +14,7 @@ export class AbsolutePath implements ValueObject {
7
14
  }
8
15
 
9
16
  private value: string = '';
17
+
10
18
  constructor(path: string) {
11
19
  this.value = pathUtils.resolve(path);
12
20
  }
@@ -15,6 +23,10 @@ export class AbsolutePath implements ValueObject {
15
23
  return this.value;
16
24
  }
17
25
 
26
+ toString(): string {
27
+ return this.value;
28
+ }
29
+
18
30
  copyWithNewSegment(...relativePath: string[]): AbsolutePath {
19
31
  return new AbsolutePath(pathUtils.join(this.getValue(), ...relativePath));
20
32
  }
@@ -47,4 +59,8 @@ class RelativePath implements ValueObject {
47
59
  getValue() {
48
60
  return this.value;
49
61
  }
62
+
63
+ toString() {
64
+ return this.value;
65
+ }
50
66
  }
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Copyright (c) 2024 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
+
1
8
  import fs from 'node:fs';
2
9
  import { AbsolutePath } from './AbsolutePath';
3
10
  import { findFilePathsWithExtensions } from '../io';
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Copyright (c) 2024 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
+
1
8
  export class DescriptiveError extends Error {
2
9
  constructor(
3
10
  private data: