@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,179 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.commandBundleHarmony = void 0;
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const fs_extra_1 = __importDefault(require("fs-extra"));
18
+ const metro_1 = __importDefault(require("metro"));
19
+ const Server_1 = __importDefault(require("metro/src/Server"));
20
+ const path_1 = __importDefault(require("path"));
21
+ const assetResolver_1 = require("../assetResolver");
22
+ const ARK_RESOURCE_PATH = './harmony/entry/src/main/resources/rawfile';
23
+ const ASSETS_DEFAULT_DEST_PATH = './harmony/entry/src/main/resources/rawfile/assets';
24
+ exports.commandBundleHarmony = {
25
+ name: 'bundle-harmony',
26
+ description: 'Creates JS bundle, creates a special cpp header containing the JS code, copies assets directory to the project.',
27
+ options: [
28
+ {
29
+ name: '--dev [boolean]',
30
+ description: 'If false, warnings are disabled and the bundle is minified',
31
+ parse: (val) => val !== 'false',
32
+ default: true,
33
+ },
34
+ {
35
+ name: '--entry-file <path>',
36
+ description: 'Path to the root JS file, either absolute or relative to JS root',
37
+ default: 'index.js',
38
+ },
39
+ {
40
+ name: '--config <path>',
41
+ description: 'Path to the Metro configuration file',
42
+ },
43
+ {
44
+ name: '--bundle-output <path>',
45
+ description: 'File name where to store the resulting bundle, ex. /tmp/groups.bundle',
46
+ default: ARK_RESOURCE_PATH + '/bundle.harmony.js',
47
+ },
48
+ {
49
+ name: '--assets-dest <path>',
50
+ description: 'Directory name where to store assets referenced in the bundle',
51
+ default: ASSETS_DEFAULT_DEST_PATH,
52
+ },
53
+ {
54
+ name: '--sourcemap-output <path>',
55
+ description: 'File name where to store the resulting source map, ex. /tmp/groups.map',
56
+ },
57
+ {
58
+ name: '--minify [boolean]',
59
+ description: 'Allows overriding whether bundle is minified',
60
+ parse: (val) => val !== 'false',
61
+ },
62
+ ],
63
+ func: (argv, config, args) => __awaiter(void 0, void 0, void 0, function* () {
64
+ const buildOptions = {
65
+ entry: args.entryFile,
66
+ platform: 'harmony',
67
+ minify: args.minify !== undefined ? args.minify : !args.dev,
68
+ dev: args.dev,
69
+ sourceMap: args.sourcemapOutput,
70
+ sourceMapUrl: args.sourcemapOutput,
71
+ };
72
+ const metroConfig = yield loadMetroConfig(args.config);
73
+ const bundle = yield createBundle(metroConfig, buildOptions);
74
+ yield saveBundle(bundle, args.bundleOutput, args.sourcemapOutput);
75
+ const assets = yield retrieveAssetsData(metroConfig, buildOptions);
76
+ copyAssets(assets, args.assetsDest);
77
+ }),
78
+ };
79
+ function loadMetroConfig(configPath) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ return configPath
82
+ ? yield metro_1.default.loadConfig({ config: configPath })
83
+ : yield metro_1.default.loadConfig();
84
+ });
85
+ }
86
+ function createBundle(metroConfig, buildOptions) {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ // casting needed as Metro.runBuild returns Promise<{code: string, map: string}>
89
+ // despite being typed as Promise<void>
90
+ return (yield metro_1.default.runBuild(metroConfig, buildOptions));
91
+ });
92
+ }
93
+ function saveBundle(bundle, bundleOutput, sourceMapOutput) {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ yield fs_extra_1.default.ensureDir(path_1.default.dirname(bundleOutput));
96
+ fs_1.default.writeFileSync(bundleOutput, bundle.code);
97
+ console.log(`[CREATED] ${bundleOutput}`);
98
+ if (sourceMapOutput) {
99
+ fs_1.default.writeFileSync(sourceMapOutput, bundle.map);
100
+ console.log(`[CREATED] ${sourceMapOutput}`);
101
+ }
102
+ });
103
+ }
104
+ function retrieveAssetsData(metroConfig, buildOptions) {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ const metroServer = new Server_1.default(metroConfig);
107
+ try {
108
+ return yield metroServer.getAssets(Object.assign(Object.assign(Object.assign({}, Server_1.default.DEFAULT_BUNDLE_OPTIONS), buildOptions), { entryFile: buildOptions.entry, bundleType: 'todo' }));
109
+ }
110
+ finally {
111
+ metroServer.end();
112
+ }
113
+ });
114
+ }
115
+ function copyAssets(assetsData, assetsDest) {
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ if (assetsDest == null) {
118
+ console.warn('Assets destination folder is not set, skipping...');
119
+ return;
120
+ }
121
+ yield fs_extra_1.default.ensureDir(assetsDest);
122
+ const fileDestBySrc = {};
123
+ for (const asset of assetsData) {
124
+ const idx = getHighestQualityFileIdx(asset);
125
+ fileDestBySrc[asset.files[idx]] = path_1.default.join(assetsDest, (0, assetResolver_1.getAssetDestRelativePath)(asset));
126
+ }
127
+ return copyFiles(fileDestBySrc);
128
+ });
129
+ }
130
+ function getHighestQualityFileIdx(assetData) {
131
+ let result = 0;
132
+ let maxScale = -1;
133
+ for (let idx = 0; idx < assetData.scales.length; idx++) {
134
+ const scale = assetData.scales[idx];
135
+ if (scale > maxScale) {
136
+ maxScale = scale;
137
+ result = idx;
138
+ }
139
+ }
140
+ return result;
141
+ }
142
+ function copyFiles(fileDestBySrc) {
143
+ const fileSources = Object.keys(fileDestBySrc);
144
+ if (fileSources.length === 0) {
145
+ return Promise.resolve();
146
+ }
147
+ console.info(`Copying ${fileSources.length} asset files`);
148
+ return new Promise((resolve, reject) => {
149
+ const copyNext = (error) => {
150
+ if (error) {
151
+ reject(error);
152
+ return;
153
+ }
154
+ if (fileSources.length === 0) {
155
+ console.info('Done copying assets');
156
+ resolve();
157
+ }
158
+ else {
159
+ // fileSources.length === 0 is checked in previous branch, so this is string
160
+ const src = fileSources.shift();
161
+ const dest = fileDestBySrc[src];
162
+ copyFile(src, dest, copyNext);
163
+ }
164
+ };
165
+ copyNext();
166
+ });
167
+ }
168
+ function copyFile(src, dest, onFinished) {
169
+ const destDir = path_1.default.dirname(dest);
170
+ fs_1.default.mkdir(destDir, { recursive: true }, (err) => {
171
+ if (err) {
172
+ onFinished(err);
173
+ return;
174
+ }
175
+ fs_1.default.createReadStream(src)
176
+ .pipe(fs_1.default.createWriteStream(dest))
177
+ .on('finish', onFinished);
178
+ });
179
+ }
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.commandCodegenHarmony = void 0;
16
+ const node_fs_1 = __importDefault(require("node:fs"));
17
+ const node_path_1 = __importDefault(require("node:path"));
18
+ const case_1 = __importDefault(require("case"));
19
+ const core_1 = require("../core");
20
+ const codegen_1 = require("../codegen");
21
+ const io_1 = require("../io");
22
+ exports.commandCodegenHarmony = {
23
+ name: 'codegen-harmony',
24
+ description: 'Generates boilerplate, types, and utilities from Turbo Module and Fabric Component specifications. This command is meant to be executed during the application build process.',
25
+ options: [
26
+ {
27
+ name: '--rnoh-module-path <path>',
28
+ description: 'Specifies the relative path to the rnoh OHOS module',
29
+ },
30
+ {
31
+ name: '--cpp-output-path <path>',
32
+ description: 'Specifies the relative path to the output directory intended for storing generated C++ files',
33
+ default: './harmony/entry/src/main/cpp/generated',
34
+ },
35
+ {
36
+ name: '--project-root-path <path>',
37
+ description: 'Relative path to package root',
38
+ default: '.',
39
+ },
40
+ {
41
+ name: '--debug [boolean]',
42
+ description: 'Enables logging details',
43
+ default: false,
44
+ },
45
+ {
46
+ name: '--no-safety-check [boolean]',
47
+ description: '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.',
48
+ },
49
+ ],
50
+ func: (_argv, _config, args) => __awaiter(void 0, void 0, void 0, function* () {
51
+ const logger = new io_1.Logger();
52
+ try {
53
+ const MAX_SUPPORTED_CODEGEN_VERSION = 2;
54
+ // prepare the input data
55
+ validateArgs(args);
56
+ const etsOutputPath = new core_1.AbsolutePath(args.rnohModulePath).copyWithNewSegment('generated');
57
+ const enableSafetyCheck = args.safetyCheck;
58
+ const cppOutputPath = new core_1.AbsolutePath(args.cppOutputPath);
59
+ const projectRootPath = new core_1.AbsolutePath(args.projectRootPath);
60
+ const uberSchemaFromArkTSLibraries = yield codegen_1.UberSchema.fromProject(projectRootPath, (codegenVersion, packageName) => {
61
+ throwErrorIfUnsupportedCodegenVersion(codegenVersion, MAX_SUPPORTED_CODEGEN_VERSION, packageName);
62
+ return codegenVersion === 1;
63
+ });
64
+ const cApiLibrariesData = yield collectLibrariesData(projectRootPath, (codegenVersion, packageName) => {
65
+ throwErrorIfUnsupportedCodegenVersion(codegenVersion, MAX_SUPPORTED_CODEGEN_VERSION, packageName);
66
+ return codegenVersion === 2;
67
+ });
68
+ // instantiate objects
69
+ const codegenNoticeLines = [
70
+ 'This code was generated by "react-native codegen-harmony"',
71
+ '',
72
+ 'Do not edit this file as changes may cause incorrect behavior and will be',
73
+ 'lost once the code is regenerated.',
74
+ ];
75
+ const uberGeneratorV1 = new codegen_1.UberGeneratorV1(cppOutputPath, etsOutputPath, [...codegenNoticeLines, '', '@generatorVersion: 1']);
76
+ const uberGeneratorV2 = new codegen_1.UberGeneratorV2(cppOutputPath, etsOutputPath, [...codegenNoticeLines, '', '@generatorVersion: 2']);
77
+ const glueCodeGenerator = new codegen_1.AppBuildTimeGlueCodeGenerator(cppOutputPath, etsOutputPath, codegenNoticeLines);
78
+ // generate the code
79
+ const fileContentByPath = new Map();
80
+ const appendToFileContentByPath = (fileContent, path) => {
81
+ fileContentByPath.set(path, fileContent);
82
+ };
83
+ uberGeneratorV1
84
+ .generate(uberSchemaFromArkTSLibraries)
85
+ .forEach(appendToFileContentByPath);
86
+ uberGeneratorV2
87
+ .generate(cApiLibrariesData)
88
+ .forEach(appendToFileContentByPath);
89
+ glueCodeGenerator
90
+ .generate({
91
+ v1: uberGeneratorV1.getGlueCodeData(),
92
+ v2: uberGeneratorV2.getGlueCodeData(),
93
+ })
94
+ .forEach(appendToFileContentByPath);
95
+ // output the results
96
+ if (args.debug) {
97
+ const uberSchema = yield codegen_1.UberSchema.fromProject(projectRootPath);
98
+ logger.debug((styles) => styles.gray(JSON.stringify(uberSchema.getValue(), null, 2)));
99
+ }
100
+ saveCodegenResult(fileContentByPath, cppOutputPath, etsOutputPath, enableSafetyCheck);
101
+ logCodegenResult(logger, fileContentByPath, projectRootPath);
102
+ }
103
+ catch (err) {
104
+ if (err instanceof core_1.DescriptiveError) {
105
+ logger.descriptiveError(err);
106
+ process.exit(1);
107
+ }
108
+ throw err;
109
+ }
110
+ }),
111
+ };
112
+ function validateArgs(args) {
113
+ if (!args.rnohModulePath) {
114
+ throw new core_1.DescriptiveError({
115
+ whatHappened: "--rnoh-module-path argument wasn't provided",
116
+ whatCanUserDo: {
117
+ default: [
118
+ 'Please provide a path to the native React Native for Open Harmony module (rnoh) which is probably located somewhere in "<PROJECT_ROOT>/harmony" directory',
119
+ ],
120
+ },
121
+ });
122
+ }
123
+ }
124
+ function collectLibrariesData(projectRootPath, onShouldAcceptCodegenConfig) {
125
+ return __awaiter(this, void 0, void 0, function* () {
126
+ const packageJSONs = [
127
+ core_1.PackageJSON.fromProjectRootPath(projectRootPath, projectRootPath),
128
+ ];
129
+ yield new core_1.ProjectDependenciesManager(projectRootPath).forEachAsync((dependency) => {
130
+ packageJSONs.push(dependency.readPackageJSON());
131
+ });
132
+ const results = [];
133
+ for (const packageJSON of packageJSONs) {
134
+ const codegenConfigs = packageJSON.getCodegenConfigs();
135
+ for (const codegenConfig of codegenConfigs) {
136
+ if (codegenConfig &&
137
+ onShouldAcceptCodegenConfig(codegenConfig.getVersion(), packageJSON.name)) {
138
+ results.push({
139
+ libraryCppName: deriveCppDirectoryNameFromNpmPackageName(packageJSON.name),
140
+ uberSchema: codegen_1.UberSchema.fromCodegenConfig(codegenConfig),
141
+ });
142
+ }
143
+ }
144
+ }
145
+ return results;
146
+ });
147
+ }
148
+ function throwErrorIfUnsupportedCodegenVersion(codegenVersion, maxSupportedCodegenVersion, packageName) {
149
+ if (codegenVersion > maxSupportedCodegenVersion) {
150
+ throw new codegen_1.CodegenError({
151
+ whatHappened: `Package "${packageName}" requires codegenVersion: ${codegenVersion}, which is not supported (maxSupportedCodegenVersion=${maxSupportedCodegenVersion}).`,
152
+ whatCanUserDo: {
153
+ rnAppDeveloper: [
154
+ `Try downgrading "${packageName}".`,
155
+ 'Update the "@rnoh/react-native-harmony-cli" package.',
156
+ ],
157
+ },
158
+ });
159
+ }
160
+ }
161
+ function saveCodegenResult(fileContentByPath, cppOutputPath, etsOutputPath, enableSafetyCheck) {
162
+ prepareDirectory(cppOutputPath, enableSafetyCheck);
163
+ prepareDirectory(etsOutputPath, enableSafetyCheck);
164
+ prepareDirectory(etsOutputPath.copyWithNewSegment('components'), enableSafetyCheck);
165
+ prepareDirectory(etsOutputPath.copyWithNewSegment('turboModules'), enableSafetyCheck);
166
+ fileContentByPath.forEach((_fileContent, path) => {
167
+ prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
168
+ });
169
+ fileContentByPath.forEach((fileContent, path) => {
170
+ node_fs_1.default.writeFileSync(path.getValue(), fileContent);
171
+ });
172
+ }
173
+ function prepareDirectory(path, enableSafetyCheck) {
174
+ (0, core_1.maybeMakeDirectories)(path);
175
+ if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
176
+ throw new core_1.DescriptiveError({
177
+ whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
178
+ whatCanUserDo: { default: ['Run codegen from different location'] },
179
+ });
180
+ }
181
+ (0, core_1.maybeRemoveFilesInDirectory)(path);
182
+ }
183
+ function logCodegenResult(logger, fileContentByPath, projectRootPath) {
184
+ const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map((path) => node_path_1.default.relative(projectRootPath.getValue(), path.getValue()));
185
+ sortedRelativePathStrings.sort();
186
+ sortedRelativePathStrings.forEach((pathStr) => {
187
+ logger.info((styles) => styles.gray(`• ${pathStr}`));
188
+ });
189
+ logger.info(() => '');
190
+ logger.info((styles) => `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`, { prefix: true });
191
+ logger.info(() => '');
192
+ }
193
+ function deriveCppDirectoryNameFromNpmPackageName(npmPackageName) {
194
+ let result = npmPackageName;
195
+ if (npmPackageName.includes('/')) {
196
+ result.replace('@', '');
197
+ result = npmPackageName.replace('/', '__');
198
+ }
199
+ result = case_1.default.snake(result);
200
+ return result;
201
+ }
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.commandCodegenLibHarmony = void 0;
16
+ const core_1 = require("../core");
17
+ const io_1 = require("../io");
18
+ const node_fs_1 = __importDefault(require("node:fs"));
19
+ const codegen_1 = require("../codegen");
20
+ const case_1 = __importDefault(require("case"));
21
+ const LibGlueCodeGenerator_1 = require("../codegen/generators/LibGlueCodeGenerator");
22
+ const COMMAND_NAME = 'codegen-lib-harmony';
23
+ exports.commandCodegenLibHarmony = {
24
+ name: COMMAND_NAME,
25
+ description: '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: '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.',
30
+ },
31
+ {
32
+ name: '--turbo-modules-spec-paths [path]',
33
+ description: 'Path or paths to Turbo Module spec files. Each path can point to a spec file or a directory containing spec files.',
34
+ parse: (val) => val.split(' '),
35
+ },
36
+ {
37
+ name: '--arkts-components-spec-paths [path]',
38
+ description: '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.',
39
+ parse: (val) => val.split(' '),
40
+ },
41
+ {
42
+ name: '--cpp-components-spec-paths [path]',
43
+ description: '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.',
44
+ parse: (val) => val.split(' '),
45
+ },
46
+ {
47
+ name: '--cpp-output-path <path>',
48
+ description: 'Specifies the relative path to the output directory intended for storing generated C++ files.',
49
+ },
50
+ {
51
+ name: '--ets-output-path <path>',
52
+ description: 'Specifies the relative path to the output directory intended for storing generated ETS files.',
53
+ },
54
+ {
55
+ name: '--no-safety-check [boolean]',
56
+ description: '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.',
57
+ },
58
+ ],
59
+ func: (_argv, _config, rawArgs) => __awaiter(void 0, void 0, void 0, function* () {
60
+ const logger = new io_1.Logger();
61
+ try {
62
+ const { args, uberSchemaByType } = validateArgsAndRetrieveUberSchemaByType(rawArgs);
63
+ const fileContentByPath = generateCodeInMemory({
64
+ args,
65
+ uberSchemaByType,
66
+ });
67
+ saveAndLogCodegenResult(args, logger, fileContentByPath);
68
+ }
69
+ catch (err) {
70
+ if (err instanceof core_1.DescriptiveError && !err.isUnexpected()) {
71
+ logger.descriptiveError(err);
72
+ return;
73
+ }
74
+ throw err;
75
+ }
76
+ }),
77
+ };
78
+ function validateArgsAndRetrieveUberSchemaByType(rawArgs) {
79
+ const args = validateRawArgs(rawArgs);
80
+ const arkTSComponentSpecPaths = specPathsToSpecFilePaths(args.arkTSComponentsSpecPaths);
81
+ const turboModulesUberSchema = codegen_1.UberSchema.fromSpecFilePaths(specPathsToSpecFilePaths(args.tmSpecPaths));
82
+ const arkTSComponentsUberSchema = codegen_1.UberSchema.fromSpecFilePaths(arkTSComponentSpecPaths);
83
+ const cppComponentSpecPaths = specPathsToSpecFilePaths(args.cppComponentsSpecPaths);
84
+ const cppComponentsUberSchema = codegen_1.UberSchema.fromSpecFilePaths(cppComponentSpecPaths);
85
+ const componentsUberSchema = codegen_1.UberSchema.fromSpecFilePaths([
86
+ ...arkTSComponentSpecPaths,
87
+ ...cppComponentSpecPaths,
88
+ ]);
89
+ return {
90
+ args,
91
+ uberSchemaByType: {
92
+ turboModulesUberSchema,
93
+ arkTSComponentsUberSchema,
94
+ cppComponentsUberSchema,
95
+ componentsUberSchema,
96
+ },
97
+ };
98
+ }
99
+ function validateRawArgs(rawArgs) {
100
+ var _a, _b, _c;
101
+ if (!rawArgs.npmPackageName) {
102
+ throw new core_1.DescriptiveError({
103
+ whatHappened: '--npm-package-name is required',
104
+ whatCanUserDo: { default: ['Please specify --npm-package-name'] },
105
+ });
106
+ }
107
+ if (!rawArgs.cppOutputPath) {
108
+ throw new core_1.DescriptiveError({
109
+ whatHappened: '--cpp-output-path is required',
110
+ whatCanUserDo: { default: ['Please specify --cpp-output-path'] },
111
+ });
112
+ }
113
+ if (!rawArgs.etsOutputPath) {
114
+ throw new core_1.DescriptiveError({
115
+ whatHappened: '--ets-output-path is required',
116
+ whatCanUserDo: { default: ['Please specify --ets-output-path'] },
117
+ });
118
+ }
119
+ return {
120
+ npmPackageName: rawArgs.npmPackageName,
121
+ tmSpecPaths: ((_a = rawArgs.turboModulesSpecPaths) !== null && _a !== void 0 ? _a : []).map((path) => new core_1.AbsolutePath(path)),
122
+ arkTSComponentsSpecPaths: ((_b = rawArgs.arktsComponentsSpecPaths) !== null && _b !== void 0 ? _b : []).map((path) => new core_1.AbsolutePath(path)),
123
+ cppComponentsSpecPaths: ((_c = rawArgs.cppComponentsSpecPaths) !== null && _c !== void 0 ? _c : []).map((path) => new core_1.AbsolutePath(path)),
124
+ etsOutputPath: new core_1.AbsolutePath(rawArgs.etsOutputPath),
125
+ cppOutputPath: new core_1.AbsolutePath(rawArgs.cppOutputPath),
126
+ safetyCheck: !!rawArgs.safetyCheck,
127
+ };
128
+ }
129
+ function specPathsToSpecFilePaths(specPaths) {
130
+ const SUPPORTED_SPEC_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx'];
131
+ return specPaths.flatMap((specPath) => {
132
+ if (!node_fs_1.default.existsSync(specPath.getValue())) {
133
+ throw new core_1.DescriptiveError({
134
+ whatHappened: `No such file or directory: ${specPath.getValue()}`,
135
+ whatCanUserDo: {
136
+ default: [`Are you sure provided specPath exists?`],
137
+ },
138
+ });
139
+ }
140
+ if (node_fs_1.default.lstatSync(specPath.getValue()).isDirectory()) {
141
+ return (0, io_1.findFilePathsWithExtensions)(specPath, SUPPORTED_SPEC_EXTENSIONS);
142
+ }
143
+ else {
144
+ const ext = specPath.getExtension();
145
+ if (ext && SUPPORTED_SPEC_EXTENSIONS.includes(ext)) {
146
+ return [specPath];
147
+ }
148
+ return [];
149
+ }
150
+ });
151
+ }
152
+ function generateCodeInMemory({ args, uberSchemaByType: { arkTSComponentsUberSchema, componentsUberSchema, cppComponentsUberSchema, turboModulesUberSchema, }, }) {
153
+ const CODEGEN_NOTICE_LINES = [
154
+ `This code was generated by "react-native ${COMMAND_NAME}"`,
155
+ ];
156
+ const fileContentByPath = new Map();
157
+ const appendToFileContentByPath = (fileContent, path) => {
158
+ fileContentByPath.set(path, fileContent);
159
+ };
160
+ const turboModuleGlueCodeData = turboModulesUberSchema
161
+ .findAllSpecSchemasByType('NativeModule')
162
+ .map((specSchema) => {
163
+ const nativeModuleCodeGenerator = new codegen_1.NativeModuleCodeGenerator(args.cppOutputPath.copyWithNewSegment('RNOH', 'generated', 'turbo_modules'), args.etsOutputPath.copyWithNewSegment('turboModules'), CODEGEN_NOTICE_LINES, '@rnoh/react-native-openharmony/ts');
164
+ nativeModuleCodeGenerator
165
+ .generate(specSchema)
166
+ .forEach(appendToFileContentByPath);
167
+ return nativeModuleCodeGenerator.getGlueCodeData();
168
+ })
169
+ .flat();
170
+ const arkTSComponentCodeGeneratorCAPI = new codegen_1.ArkTSComponentCodeGeneratorCAPI(args.cppOutputPath.copyWithNewSegment('RNOH', 'generated', 'components'), args.etsOutputPath.copyWithNewSegment('components'), CODEGEN_NOTICE_LINES, '@rnoh/react-native-openharmony/ts');
171
+ arkTSComponentCodeGeneratorCAPI
172
+ .generate(arkTSComponentsUberSchema)
173
+ .forEach(appendToFileContentByPath);
174
+ const libraryCppName = deriveLibraryCppNameFromNpmPackageName(args.npmPackageName);
175
+ const cppComponentCodeGenerator = new codegen_1.CppComponentCodeGenerator((filename) => {
176
+ return args.cppOutputPath.copyWithNewSegment('RNOH', 'generated', 'components', filename);
177
+ }, CODEGEN_NOTICE_LINES);
178
+ cppComponentCodeGenerator
179
+ .generate({
180
+ libraryCppName: libraryCppName,
181
+ uberSchema: cppComponentsUberSchema,
182
+ })
183
+ .forEach(appendToFileContentByPath);
184
+ new codegen_1.SharedComponentCodeGenerator((filename) => {
185
+ return args.cppOutputPath.copyWithNewSegment('react', 'renderer', 'components', libraryCppName, filename);
186
+ })
187
+ .generate({
188
+ libraryCppName: libraryCppName,
189
+ uberSchema: componentsUberSchema,
190
+ })
191
+ .forEach(appendToFileContentByPath);
192
+ new LibGlueCodeGenerator_1.LibGlueCodeGenerator(args.cppOutputPath, args.etsOutputPath, CODEGEN_NOTICE_LINES)
193
+ .generate({
194
+ libraryCppName,
195
+ arkTSComponents: arkTSComponentCodeGeneratorCAPI.getLibGlueCodeData(),
196
+ cppComponents: cppComponentCodeGenerator
197
+ .getGlueCodeData()
198
+ .map(({ name }) => ({ componentName: name })),
199
+ turboModules: turboModuleGlueCodeData,
200
+ })
201
+ .forEach(appendToFileContentByPath);
202
+ return fileContentByPath;
203
+ }
204
+ function deriveLibraryCppNameFromNpmPackageName(npmPackageName) {
205
+ let result = npmPackageName;
206
+ if (npmPackageName.includes('/')) {
207
+ result.replace('@', '');
208
+ result = npmPackageName.replace('/', '__');
209
+ }
210
+ result = case_1.default.snake(result);
211
+ return result;
212
+ }
213
+ function saveAndLogCodegenResult(args, logger, fileContentByPath) {
214
+ saveCodegenResultToFileSystem(fileContentByPath, args.cppOutputPath, args.etsOutputPath, args.safetyCheck);
215
+ logCodegenResult(logger, fileContentByPath, new core_1.AbsolutePath(''));
216
+ }
217
+ function saveCodegenResultToFileSystem(fileContentByPath, cppOutputPath, etsOutputPath, enableSafetyCheck) {
218
+ prepareDirectory(cppOutputPath, enableSafetyCheck);
219
+ prepareDirectory(etsOutputPath, enableSafetyCheck);
220
+ prepareDirectory(etsOutputPath.copyWithNewSegment('components'), enableSafetyCheck);
221
+ prepareDirectory(etsOutputPath.copyWithNewSegment('turboModules'), enableSafetyCheck);
222
+ fileContentByPath.forEach((_fileContent, path) => {
223
+ prepareDirectory(path.getDirectoryPath(), enableSafetyCheck);
224
+ });
225
+ fileContentByPath.forEach((fileContent, path) => {
226
+ node_fs_1.default.writeFileSync(path.getValue(), fileContent);
227
+ });
228
+ }
229
+ function prepareDirectory(path, enableSafetyCheck) {
230
+ (0, core_1.maybeMakeDirectories)(path);
231
+ if (enableSafetyCheck && !path.getValue().startsWith(process.cwd())) {
232
+ throw new core_1.DescriptiveError({
233
+ whatHappened: `Tried to remove files in ${path.getValue()}\nand that path is outside current working directory`,
234
+ whatCanUserDo: {
235
+ default: [
236
+ 'Run this command with --no-safety-check flag',
237
+ 'Run codegen from different location',
238
+ ],
239
+ },
240
+ });
241
+ }
242
+ (0, core_1.maybeRemoveFilesInDirectory)(path);
243
+ }
244
+ function logCodegenResult(logger, fileContentByPath, rootPath) {
245
+ const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map((path) => path.relativeTo(rootPath).getValue());
246
+ sortedRelativePathStrings.sort();
247
+ sortedRelativePathStrings.forEach((pathStr) => {
248
+ logger.info((styles) => styles.gray(`• ${pathStr}`));
249
+ });
250
+ logger.info(() => '');
251
+ logger.info((styles) => `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`, { prefix: true });
252
+ logger.info(() => '');
253
+ }