@react-native-oh/react-native-harmony-cli 0.0.16 → 0.0.24

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 (77) hide show
  1. package/dist/codegen/core/Codegen.js +35 -0
  2. package/dist/codegen/core/CodegenError.js +7 -0
  3. package/dist/codegen/core/EventUtils.js +19 -0
  4. package/dist/codegen/core/TypeAnnotationToTS.js +132 -0
  5. package/dist/codegen/core/UberSchema.js +74 -0
  6. package/dist/codegen/core/index.js +21 -0
  7. package/dist/codegen/generators/ComponentCodeGenerator.js +66 -0
  8. package/dist/codegen/generators/NativeModuleCodeGenerator.js +64 -0
  9. package/dist/codegen/generators/PackageCodeGenerator.js +52 -0
  10. package/dist/codegen/generators/index.js +19 -0
  11. package/dist/codegen/index.js +18 -0
  12. package/dist/codegen/templates/ComponentDescriptorHTemplate.js +55 -0
  13. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +78 -0
  14. package/dist/codegen/templates/ComponentUtilsTSTemplate.js +181 -0
  15. package/dist/codegen/templates/IndexTSTemplate.js +31 -0
  16. package/dist/codegen/templates/RNOHGeneratedPackageHTemplate.js +117 -0
  17. package/dist/codegen/templates/TurboModuleCppTemplate.js +45 -0
  18. package/dist/codegen/templates/TurboModuleHTemplate.js +32 -0
  19. package/dist/codegen/templates/TurboModuleSpecTSTemplate.js +64 -0
  20. package/dist/codegen/templates/index.js +24 -0
  21. package/dist/commands/codegen-harmony.js +110 -0
  22. package/dist/commands/create-metro-host-constants.js +61 -0
  23. package/dist/commands/index.js +2 -0
  24. package/dist/commands/pack-harmony.js +4 -1
  25. package/dist/commands/unpack-harmony.js +86 -43
  26. package/dist/core/AbsolutePath.js +41 -0
  27. package/dist/core/CodegenConfig.js +53 -0
  28. package/dist/core/DescriptiveError.js +49 -0
  29. package/dist/core/PackageJSON.js +53 -0
  30. package/dist/core/ProjectDependenciesManager.js +70 -0
  31. package/dist/core/ValueObject.js +2 -0
  32. package/dist/core/fs.js +36 -0
  33. package/dist/core/index.js +7 -0
  34. package/dist/index.js +7 -1
  35. package/dist/io/Logger.js +71 -0
  36. package/dist/io/fsUtils.js +23 -0
  37. package/dist/io/index.js +18 -0
  38. package/package.json +6 -1
  39. package/src/codegen/core/Codegen.ts +44 -0
  40. package/src/codegen/core/CodegenError.ts +3 -0
  41. package/src/codegen/core/EventUtils.ts +18 -0
  42. package/src/codegen/core/TypeAnnotationToTS.test.ts +75 -0
  43. package/src/codegen/core/TypeAnnotationToTS.ts +188 -0
  44. package/src/codegen/core/UberSchema.ts +99 -0
  45. package/src/codegen/core/index.ts +5 -0
  46. package/src/codegen/generators/ComponentCodeGenerator.ts +98 -0
  47. package/src/codegen/generators/NativeModuleCodeGenerator.ts +95 -0
  48. package/src/codegen/generators/PackageCodeGenerator.ts +73 -0
  49. package/src/codegen/generators/index.ts +3 -0
  50. package/src/codegen/index.ts +2 -0
  51. package/src/codegen/templates/ComponentDescriptorHTemplate.ts +49 -0
  52. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +85 -0
  53. package/src/codegen/templates/ComponentUtilsTSTemplate.ts +202 -0
  54. package/src/codegen/templates/IndexTSTemplate.ts +33 -0
  55. package/src/codegen/templates/RNOHGeneratedPackageHTemplate.ts +124 -0
  56. package/src/codegen/templates/TurboModuleCppTemplate.ts +47 -0
  57. package/src/codegen/templates/TurboModuleHTemplate.ts +26 -0
  58. package/src/codegen/templates/TurboModuleSpecTSTemplate.ts +81 -0
  59. package/src/codegen/templates/index.ts +8 -0
  60. package/src/commands/codegen-harmony.ts +143 -0
  61. package/src/commands/create-metro-host-constants.ts +48 -0
  62. package/src/commands/index.ts +2 -0
  63. package/src/commands/pack-harmony.ts +4 -1
  64. package/src/commands/unpack-harmony.ts +133 -58
  65. package/src/core/AbsolutePath.ts +43 -0
  66. package/src/core/CodegenConfig.ts +54 -0
  67. package/src/core/DescriptiveError.ts +61 -0
  68. package/src/core/PackageJSON.ts +63 -0
  69. package/src/core/ProjectDependenciesManager.ts +77 -0
  70. package/src/core/ValueObject.ts +2 -0
  71. package/src/core/fs.ts +31 -0
  72. package/src/core/index.ts +7 -0
  73. package/src/index.ts +9 -1
  74. package/src/io/Logger.ts +68 -0
  75. package/src/io/fsUtils.ts +24 -0
  76. package/src/io/index.ts +2 -0
  77. package/tsconfig.build.json +2 -1
@@ -0,0 +1,81 @@
1
+ import mustache from 'mustache';
2
+
3
+ const TEMPLATE = `
4
+ // This file was generated.
5
+ import { Tag } from "../../ts"
6
+
7
+ export namespace {{name}} {
8
+ export const NAME = '{{name}}' as const
9
+
10
+ {{#enums}}
11
+ export enum {{name}} {
12
+ {{#members}}
13
+ {{name}} = {{{value}}},
14
+ {{/members}}
15
+ }
16
+
17
+ {{/enums}}
18
+ {{#aliases}}
19
+ export type {{name}} = {{{type}}}
20
+
21
+ {{/aliases}}
22
+ export interface Spec {
23
+ {{#methods}}
24
+ {{name}}({{{stringifiedArgs}}}): {{{returnType}}};
25
+
26
+ {{/methods}}
27
+ }
28
+ }
29
+ `;
30
+
31
+ type Alias = {
32
+ name: string;
33
+ type: string;
34
+ };
35
+
36
+ type EnumModel = {
37
+ name: string;
38
+ members: {
39
+ name: string;
40
+ value: string;
41
+ }[];
42
+ };
43
+
44
+ type Method = {
45
+ name: string;
46
+ stringifiedArgs: string;
47
+ returnType: string;
48
+ };
49
+
50
+ export class TurboModuleInterfaceTS {
51
+ private methods: Method[] = [];
52
+ private aliases: Alias[] = [];
53
+ private enumModels: EnumModel[] = [];
54
+
55
+ constructor(private name: string) {}
56
+
57
+ addAlias(alias: Alias) {
58
+ this.aliases.push(alias);
59
+ }
60
+
61
+ addEnum(enumModel: EnumModel) {
62
+ this.enumModels.push(enumModel);
63
+ }
64
+
65
+ addMethod(method: Method) {
66
+ this.methods.push(method);
67
+ }
68
+
69
+ build(): string {
70
+ return mustache.render(TEMPLATE.trimStart(), {
71
+ name: this.name,
72
+ aliases: this.aliases,
73
+ enums: this.enumModels,
74
+ methods: this.methods.map((method) => ({
75
+ name: method.name,
76
+ stringifiedArgs: method.stringifiedArgs,
77
+ returnType: method.returnType,
78
+ })),
79
+ });
80
+ }
81
+ }
@@ -0,0 +1,8 @@
1
+ export * from './TurboModuleHTemplate';
2
+ export * from './TurboModuleCppTemplate';
3
+ export * from './RNOHGeneratedPackageHTemplate';
4
+ export * from './ComponentJSIBinderHTemplate';
5
+ export * from './ComponentDescriptorHTemplate';
6
+ export * from './ComponentUtilsTSTemplate';
7
+ export * from './IndexTSTemplate';
8
+ export * from './TurboModuleSpecTSTemplate';
@@ -0,0 +1,143 @@
1
+ import fs from 'node:fs';
2
+ import pathUtils from 'node:path';
3
+ import { Command } from '@react-native-community/cli-types';
4
+ import {
5
+ AbsolutePath,
6
+ DescriptiveError,
7
+ maybeMakeDirectories,
8
+ maybeRemoveFilesInDirectory,
9
+ } from '../core';
10
+ import {
11
+ Codegen,
12
+ UberSchema,
13
+ ComponentCodeGenerator,
14
+ NativeModuleCodeGenerator,
15
+ PackageCodeGenerator,
16
+ } from '../codegen';
17
+ import { Logger } from '../io';
18
+
19
+ export const commandCodegenHarmony: Command = {
20
+ name: 'codegen-harmony',
21
+ description:
22
+ 'Generates a glue layer and native utilities from Turbo Module or Fabric Components specifications',
23
+ options: [
24
+ {
25
+ name: '--rnoh-module-path <path>',
26
+ description: 'Specifies the relative path to the rnoh OHOS module',
27
+ },
28
+ {
29
+ name: '--cpp-output-path <path>',
30
+ description:
31
+ 'Specifies the relative path to the output directory intended for storing generated C++ files',
32
+ default: './harmony/entry/src/main/cpp/generated',
33
+ },
34
+ {
35
+ name: '--project-root-path <path>',
36
+ description: 'Relative path to package root',
37
+ default: '.',
38
+ },
39
+ {
40
+ name: '--debug [boolean]',
41
+ description: 'Enables logging details',
42
+ default: false,
43
+ },
44
+ ],
45
+ func: async (_argv, _config, args: any) => {
46
+ const logger = new Logger();
47
+ try {
48
+ validateArgs(args);
49
+ const etsOutputPath = new AbsolutePath(
50
+ args.rnohModulePath
51
+ ).copyWithNewSegment('generated');
52
+ const cppOutputPath = new AbsolutePath(args.cppOutputPath);
53
+ const projectRootPath = new AbsolutePath(args.projectRootPath);
54
+ const codegen = createCodegen(cppOutputPath, etsOutputPath);
55
+ const uberSchema = await UberSchema.fromProjectRootPath(
56
+ new AbsolutePath(args.projectRootPath)
57
+ );
58
+ const fileContentByPath = codegen.generate(uberSchema);
59
+ if (args.debug) {
60
+ logger.debug((styles) =>
61
+ styles.gray(JSON.stringify(uberSchema.getValue(), null, 2))
62
+ );
63
+ }
64
+ saveCodegenResult(fileContentByPath, cppOutputPath, etsOutputPath);
65
+ logCodegenResult(logger, fileContentByPath, projectRootPath);
66
+ } catch (err) {
67
+ if (err instanceof DescriptiveError) {
68
+ logger.descriptiveError(err);
69
+ process.exit(1);
70
+ }
71
+ throw err;
72
+ }
73
+ },
74
+ };
75
+
76
+ function validateArgs(args: any) {
77
+ if (!args.rnohModulePath) {
78
+ throw new DescriptiveError({
79
+ whatHappened: "--rnoh-module-path argument wasn't provided",
80
+ whatCanUserDo: {
81
+ default: [
82
+ 'Please provide a path to the native React Native for Open Harmony module (rnoh) which is probably located somewhere in "<PROJECT_ROOT>/harmony" directory',
83
+ ],
84
+ },
85
+ });
86
+ }
87
+ }
88
+
89
+ function createCodegen(
90
+ cppOutputPath: AbsolutePath,
91
+ etsOutputPath: AbsolutePath
92
+ ) {
93
+ return new Codegen(new PackageCodeGenerator(cppOutputPath, etsOutputPath), {
94
+ Component: new ComponentCodeGenerator(
95
+ cppOutputPath,
96
+ etsOutputPath.copyWithNewSegment('components')
97
+ ),
98
+ NativeModule: new NativeModuleCodeGenerator(
99
+ cppOutputPath,
100
+ etsOutputPath.copyWithNewSegment('turboModules')
101
+ ),
102
+ });
103
+ }
104
+
105
+ function saveCodegenResult(
106
+ fileContentByPath: Map<AbsolutePath, string>,
107
+ cppOutputPath: AbsolutePath,
108
+ etsOutputPath: AbsolutePath
109
+ ) {
110
+ prepareDirectory(cppOutputPath);
111
+ prepareDirectory(etsOutputPath);
112
+ prepareDirectory(etsOutputPath.copyWithNewSegment('components'));
113
+ prepareDirectory(etsOutputPath.copyWithNewSegment('turboModules'));
114
+ fileContentByPath.forEach((fileContent, path) => {
115
+ fs.writeFileSync(path.getValue(), fileContent);
116
+ });
117
+ }
118
+
119
+ function prepareDirectory(path: AbsolutePath) {
120
+ maybeMakeDirectories(path);
121
+ maybeRemoveFilesInDirectory(path);
122
+ }
123
+
124
+ function logCodegenResult(
125
+ logger: Logger,
126
+ fileContentByPath: Map<AbsolutePath, string>,
127
+ projectRootPath: AbsolutePath
128
+ ) {
129
+ const sortedRelativePathStrings = Array.from(fileContentByPath.keys()).map(
130
+ (path) => pathUtils.relative(projectRootPath.getValue(), path.getValue())
131
+ );
132
+ sortedRelativePathStrings.sort();
133
+ sortedRelativePathStrings.forEach((pathStr) => {
134
+ logger.info((styles) => styles.gray(`• ${pathStr}`));
135
+ });
136
+ logger.info(() => '');
137
+ logger.info(
138
+ (styles) =>
139
+ `Generated ${styles.green(styles.bold(fileContentByPath.size))} file(s)`,
140
+ { prefix: true }
141
+ );
142
+ logger.info(() => '');
143
+ }
@@ -0,0 +1,48 @@
1
+ import { Command } from '@react-native-community/cli-types';
2
+ import os from 'node:os';
3
+ import fs from 'node:fs';
4
+ import pathUtils from 'node:path';
5
+
6
+ export const commandCreateMetroConstantsHarmony: Command = {
7
+ name: 'create-metro-host-constants-harmony',
8
+ description:
9
+ 'Creates a Typescript file that exports constant with IP of the host machine. That IP is later used to connect to the Metro server from a physical device.',
10
+ options: [
11
+ {
12
+ name: '--output <string>',
13
+ description: 'Output file',
14
+ default: './harmony/entry/src/main/ets/codegen/MetroHostConstants.ts',
15
+ },
16
+ ],
17
+ func: async (argv, config, args: any) => {
18
+ createMetroHostConstants(pathUtils.resolve(args.output));
19
+ },
20
+ };
21
+
22
+ function createMetroHostConstants(outputPath: string): void {
23
+ const networkInterfacesByName = os.networkInterfaces();
24
+ const getIP = () => {
25
+ for (let name of Object.keys(networkInterfacesByName)) {
26
+ for (let net of networkInterfacesByName[name] ?? []) {
27
+ // skip over non-ipv4 and internal (i.e. 127.0.0.1) addresses
28
+ if (net.family === 'IPv4' && !net.internal) {
29
+ return net.address;
30
+ }
31
+ }
32
+ }
33
+ return;
34
+ };
35
+ const ip = getIP();
36
+ const tsCode = [
37
+ '// This file is autogenerated. Do not modify it manually.',
38
+ '',
39
+ `export const METRO_SERVER_IP = '${ip}';\n`,
40
+ ];
41
+ fs.writeFile(outputPath, tsCode.join('\n'), (err) => {
42
+ if (err) {
43
+ console.error(`Error writing to ${outputPath}:`, err);
44
+ } else {
45
+ console.log(`Created file at ${outputPath}`);
46
+ }
47
+ });
48
+ }
@@ -1,3 +1,5 @@
1
1
  export * from './bundle-harmony';
2
2
  export * from './pack-harmony';
3
3
  export * from './unpack-harmony';
4
+ export * from './create-metro-host-constants';
5
+ export * from './codegen-harmony';
@@ -51,6 +51,9 @@ async function pack(
51
51
  packageJSONPath,
52
52
  pathUtils.join(ohModuleDirPath, 'oh-package.json5')
53
53
  );
54
+ if (!fs.existsSync(harmonyDirPath)) {
55
+ fs.mkdirSync(harmonyDirPath, { recursive: true });
56
+ }
54
57
  await createTGZFromDir(
55
58
  ohModuleDirPath,
56
59
  pathUtils.join(
@@ -78,7 +81,7 @@ function syncVersions(
78
81
  ohPackageJSONFileContent['version'] = packageJSONFileContent['version'];
79
82
  fs.writeFileSync(
80
83
  ohPackageJSONFilePath,
81
- JSON5.stringify(ohPackageJSONFileContent)
84
+ JSON5.stringify(ohPackageJSONFileContent, null, 2)
82
85
  );
83
86
  }
84
87
  }
@@ -1,32 +1,37 @@
1
1
  import { Command } from '@react-native-community/cli-types';
2
+ import { Logger } from '../io';
2
3
 
3
4
  import pathUtils from 'path';
4
5
  import fs from 'fs';
5
6
  import zlib from 'zlib';
6
7
  import tar from 'tar';
7
8
  import JSON5 from 'json5';
8
- import { ValidationError } from '../core';
9
+ import {
10
+ ValidationError,
11
+ AbsolutePath,
12
+ ProjectDependenciesManager,
13
+ } from '../core';
9
14
 
10
15
  export const commandUnpackHarmony: Command = {
11
16
  name: 'unpack-harmony',
12
- description: 'Pack native code. Used for package development.',
17
+ description: 'Unpacks native code.',
13
18
  options: [
14
19
  {
15
- name: '--node-modules-path <string>',
16
- description: 'Path to node_modules directory',
17
- default: './node_modules',
20
+ name: '--project-root-path <path>',
21
+ description: 'Relative path to package root',
22
+ default: '.',
18
23
  },
19
24
  {
20
25
  name: '--output-dir <string>',
21
26
  description: 'Output directory to which OH modules should be unpacked to',
22
- default: './harmony/react_native_modules',
27
+ default: './harmony/rnoh_modules',
23
28
  },
24
29
  ],
25
30
  func: async (argv, config, args: any) => {
26
31
  try {
27
32
  await unpack(
28
- pathUtils.resolve(args.nodeModulesPath),
29
- pathUtils.resolve(args.outputDir)
33
+ new AbsolutePath(args.projectRootPath),
34
+ new AbsolutePath(args.outputDir)
30
35
  );
31
36
  } catch (err) {
32
37
  if (err instanceof ValidationError) {
@@ -39,50 +44,124 @@ export const commandUnpackHarmony: Command = {
39
44
  },
40
45
  };
41
46
 
42
- async function unpack(nodeModulesPath: string, outputDirPath: string) {
43
- const nodeModuleNames = fs.readdirSync(nodeModulesPath);
44
- for (const nodeModuleName of nodeModuleNames) {
45
- const nodeModulePath = pathUtils.join(nodeModulesPath, nodeModuleName);
46
- const nodePackageVersion = getNodePackageVersion(nodeModulePath);
47
- const harmonyArchivePath = pathUtils.join(nodeModulePath, 'harmony.tar.gz');
48
- const pkgHarmonyDirPath = pathUtils.join(nodeModulePath, 'harmony');
49
- const ohModulesInfo = getOhModulesInfo(pkgHarmonyDirPath, outputDirPath);
47
+ async function unpack(
48
+ projectRootPath: AbsolutePath,
49
+ outputDirPath: AbsolutePath
50
+ ) {
51
+ const logger = new Logger();
52
+ const projectDependenciesManager = new ProjectDependenciesManager(
53
+ projectRootPath
54
+ );
55
+ logger.info((styles) => styles.bold(`Unpacking RNOH modules`), {
56
+ prefix: true,
57
+ });
58
+ let unpackedArchivesCount = 0;
59
+ let skippedArchivesCount = 0;
60
+ await projectDependenciesManager.forEachAsync(async (dependency) => {
61
+ const packageJSON = dependency.readPackageJSON();
62
+ const harmonyArchivePath = dependency
63
+ .getRootPath()
64
+ .copyWithNewSegment('harmony.tar.gz');
65
+ const pkgHarmonyDirPath = dependency
66
+ .getRootPath()
67
+ .copyWithNewSegment('harmony');
68
+ const harmonyTarGzPathStr = dependency
69
+ .getRootPath()
70
+ .copyWithNewSegment('harmony.tar.gz')
71
+ .relativeTo(projectRootPath)
72
+ .getValue();
50
73
  if (
51
- nodePackageVersion &&
52
- shouldUnpackHarmonyArchive(
74
+ packageJSON.version &&
75
+ shouldUnpack(
53
76
  harmonyArchivePath,
54
77
  pkgHarmonyDirPath,
55
78
  outputDirPath,
56
- nodePackageVersion
79
+ packageJSON.version
57
80
  )
58
81
  ) {
59
- console.log(`[UNPACKING] ${nodeModuleName}/harmony.tar.gz`);
60
- await unpackTarGz(harmonyArchivePath, pkgHarmonyDirPath);
82
+ if (!fs.existsSync(pkgHarmonyDirPath.getValue())) {
83
+ /**
84
+ * After fresh install, harmony.tar.gz wasn't unpacked to harmony. Updating npm package should remove unpacked harmony dir.
85
+ */
86
+ logger.info(
87
+ (styles) =>
88
+ `[${styles.cyan('unpacking')}] ${styles.gray(harmonyTarGzPathStr)}`
89
+ );
90
+ await unpackTarGz(harmonyArchivePath, pkgHarmonyDirPath);
91
+ unpackedArchivesCount++;
92
+ } else {
93
+ skippedArchivesCount++;
94
+ logger.info(
95
+ (styles) =>
96
+ `[${styles.yellow('skipped')}] ${styles.gray(
97
+ harmonyTarGzPathStr
98
+ )}`
99
+ );
100
+ }
101
+ const ohModulesInfo = getOhModulesInfo(pkgHarmonyDirPath, outputDirPath);
61
102
  for (const ohModuleInfo of ohModulesInfo) {
62
- console.log(
63
- `[UNPACKING] ${nodeModuleName}/harmony/${ohModuleInfo.archiveFileName}`
103
+ const moduleArchivePathStr = dependency
104
+ .getRootPath()
105
+ .copyWithNewSegment('harmony', ohModuleInfo.archiveFileName)
106
+ .relativeTo(projectRootPath)
107
+ .getValue();
108
+ logger.info(
109
+ (styles) =>
110
+ `[${styles.cyan('unpacking')}] ${styles.gray(moduleArchivePathStr)}`
64
111
  );
112
+ unpackedArchivesCount++;
65
113
  await unpackTarGz(
66
114
  ohModuleInfo.archivePath,
67
115
  ohModuleInfo.computedModulePath
68
116
  );
69
117
  }
118
+ } else {
119
+ if (fs.existsSync(harmonyArchivePath.getValue())) {
120
+ skippedArchivesCount++;
121
+ logger.info(
122
+ (styles) =>
123
+ `[${styles.yellow('skipped')}] ${styles.gray(
124
+ harmonyTarGzPathStr
125
+ )}`
126
+ );
127
+ }
128
+ const ohModulesInfo = getOhModulesInfo(pkgHarmonyDirPath, outputDirPath);
129
+ for (const ohModuleInfo of ohModulesInfo) {
130
+ const moduleArchivePathStr = dependency
131
+ .getRootPath()
132
+ .copyWithNewSegment('harmony', ohModuleInfo.archiveFileName)
133
+ .relativeTo(projectRootPath)
134
+ .getValue();
135
+ skippedArchivesCount++;
136
+ logger.info(
137
+ (styles) =>
138
+ `[${styles.yellow('skipped')}] ${styles.gray(
139
+ moduleArchivePathStr
140
+ )}`
141
+ );
142
+ }
70
143
  }
71
- }
144
+ });
145
+ logger.info(
146
+ (styles) =>
147
+ `\nUnpacked: ${styles.cyan(
148
+ unpackedArchivesCount
149
+ )}, Skipped: ${styles.yellow(skippedArchivesCount)}`
150
+ );
72
151
  }
73
152
 
74
- function shouldUnpackHarmonyArchive(
75
- harmonyArchivePath: string,
76
- pkgHarmonyDirPath: string,
77
- outputDirPath: string,
153
+ function shouldUnpack(
154
+ harmonyArchivePath: AbsolutePath,
155
+ pkgHarmonyDirPath: AbsolutePath,
156
+ outputDirPath: AbsolutePath,
78
157
  nodePackageVersion: string
79
158
  ) {
80
- if (!fs.existsSync(harmonyArchivePath)) return false;
81
- if (!fs.existsSync(pkgHarmonyDirPath)) return true;
159
+ if (!fs.existsSync(harmonyArchivePath.getValue())) return false;
160
+ if (!fs.existsSync(pkgHarmonyDirPath.getValue())) return true;
82
161
  const ohModulesInfo = getOhModulesInfo(pkgHarmonyDirPath, outputDirPath);
83
162
  for (const ohModuleInfo of ohModulesInfo) {
84
163
  if (
85
- !fs.existsSync(ohModuleInfo.computedModulePath) ||
164
+ !fs.existsSync(ohModuleInfo.computedModulePath.getValue()) ||
86
165
  getOhPackageVersion(ohModuleInfo.computedModulePath) !==
87
166
  nodePackageVersion
88
167
  ) {
@@ -92,39 +171,35 @@ function shouldUnpackHarmonyArchive(
92
171
  return false;
93
172
  }
94
173
 
95
- function getNodePackageVersion(nodeModulePath: string) {
96
- const packageJSONPath = pathUtils.join(nodeModulePath, 'package.json');
97
- if (!fs.existsSync(packageJSONPath)) return null;
98
- const content = fs.readFileSync(packageJSONPath, { encoding: 'utf-8' });
99
- return JSON.parse(content)['version'];
100
- }
101
-
102
- function getOhPackageVersion(modulePath: string) {
103
- const ohPackagePath = pathUtils.join(modulePath, 'oh-package.json5');
104
- if (!fs.existsSync(ohPackagePath)) return null;
105
- const content = fs.readFileSync(ohPackagePath, { encoding: 'utf-8' });
174
+ function getOhPackageVersion(modulePath: AbsolutePath) {
175
+ const ohPackagePath = modulePath.copyWithNewSegment('oh-package.json5');
176
+ if (!fs.existsSync(ohPackagePath.getValue())) return null;
177
+ const content = fs.readFileSync(ohPackagePath.getValue(), {
178
+ encoding: 'utf-8',
179
+ });
106
180
  return JSON5.parse(content)['version'];
107
181
  }
108
182
 
109
- function getOhModulesInfo(pkgHarmonyDirPath: string, outputDirPath: string) {
183
+ function getOhModulesInfo(
184
+ pkgHarmonyDirPath: AbsolutePath,
185
+ outputDirPath: AbsolutePath
186
+ ) {
110
187
  const results: {
111
- archivePath: string;
188
+ archivePath: AbsolutePath;
112
189
  archiveFileName: string;
113
- computedModulePath: string;
190
+ computedModulePath: AbsolutePath;
114
191
  computedModuleName: string;
115
192
  }[] = [];
116
- if (!fs.existsSync(pkgHarmonyDirPath)) return [];
117
- const names = fs.readdirSync(pkgHarmonyDirPath);
193
+ if (!fs.existsSync(pkgHarmonyDirPath.getValue())) return [];
194
+ const names = fs.readdirSync(pkgHarmonyDirPath.getValue());
118
195
  for (const name of names) {
119
196
  if (name.endsWith('.tar.gz')) {
120
- const archivePath = pathUtils.join(pkgHarmonyDirPath, name);
197
+ const archivePath = pkgHarmonyDirPath.copyWithNewSegment(name);
121
198
  const computedModuleName = pathUtils
122
- .parse(archivePath)
199
+ .parse(archivePath.getValue())
123
200
  .name.split('.')[0];
124
- const computedModulePath = pathUtils.join(
125
- outputDirPath,
126
- computedModuleName
127
- );
201
+ const computedModulePath =
202
+ outputDirPath.copyWithNewSegment(computedModuleName);
128
203
  results.push({
129
204
  archivePath,
130
205
  archiveFileName: name,
@@ -136,13 +211,13 @@ function getOhModulesInfo(pkgHarmonyDirPath: string, outputDirPath: string) {
136
211
  return results;
137
212
  }
138
213
 
139
- function unpackTarGz(archivePath: string, outputDirPath: string) {
140
- if (!fs.existsSync(outputDirPath)) {
141
- fs.mkdirSync(outputDirPath, { recursive: true });
214
+ function unpackTarGz(archivePath: AbsolutePath, outputDirPath: AbsolutePath) {
215
+ if (!fs.existsSync(outputDirPath.getValue())) {
216
+ fs.mkdirSync(outputDirPath.getValue(), { recursive: true });
142
217
  }
143
- const readStream = fs.createReadStream(archivePath);
218
+ const readStream = fs.createReadStream(archivePath.getValue());
144
219
  const writeStream = tar.extract({
145
- cwd: outputDirPath,
220
+ cwd: outputDirPath.getValue(),
146
221
  });
147
222
  readStream.pipe(zlib.createGunzip()).pipe(writeStream);
148
223
  return new Promise((resolve, reject) => {
@@ -0,0 +1,43 @@
1
+ import pathUtils from 'node:path';
2
+ import { ValueObject } from './ValueObject';
3
+
4
+ export class AbsolutePath implements ValueObject {
5
+ static fromSegments(...segments: string[]) {
6
+ return new AbsolutePath(pathUtils.join(...segments));
7
+ }
8
+
9
+ private value: string = '';
10
+ constructor(path: string) {
11
+ this.value = pathUtils.resolve(path);
12
+ }
13
+
14
+ getValue(): string {
15
+ return this.value;
16
+ }
17
+
18
+ copyWithNewSegment(...relativePath: string[]): AbsolutePath {
19
+ return new AbsolutePath(pathUtils.join(this.getValue(), ...relativePath));
20
+ }
21
+
22
+ getExtension(): string | null {
23
+ const maybeExtWithDot = pathUtils.extname(this.value);
24
+ if (maybeExtWithDot) {
25
+ return maybeExtWithDot.substring(1);
26
+ }
27
+ return null;
28
+ }
29
+
30
+ relativeTo(absolutePath: AbsolutePath): RelativePath {
31
+ return new RelativePath(
32
+ pathUtils.relative(absolutePath.getValue(), this.value)
33
+ );
34
+ }
35
+ }
36
+
37
+ class RelativePath implements ValueObject {
38
+ constructor(private value: string) {}
39
+
40
+ getValue() {
41
+ return this.value;
42
+ }
43
+ }
@@ -0,0 +1,54 @@
1
+ import fs from 'node:fs';
2
+ import { AbsolutePath } from './AbsolutePath';
3
+ import { findFilePathsWithExtensions } from '../io';
4
+ import { DescriptiveError } from './DescriptiveError';
5
+
6
+ export type RawCodegenConfig = {
7
+ specPaths: string[];
8
+ };
9
+
10
+ export class CodegenConfig {
11
+ static fromRawCodegenConfig(
12
+ rawCodegenConfig: RawCodegenConfig,
13
+ packageRootPath: AbsolutePath,
14
+ projectRootPath: AbsolutePath,
15
+ packageName: string
16
+ ) {
17
+ const SUPPORTED_SPEC_EXTENSIONS = ['js', 'jsx', 'ts', 'tsx'];
18
+ const specPaths = (rawCodegenConfig.specPaths ?? []).map((rawSpecPath) => {
19
+ if (rawSpecPath.startsWith('~')) {
20
+ return projectRootPath.copyWithNewSegment(rawSpecPath.replace('~', ''));
21
+ } else {
22
+ return packageRootPath.copyWithNewSegment(rawSpecPath);
23
+ }
24
+ });
25
+ const specFilePaths = specPaths.flatMap((specPath) => {
26
+ if (!fs.existsSync(specPath.getValue())) {
27
+ throw new DescriptiveError({
28
+ whatHappened: `No such file or directory: ${specPath.getValue()}`,
29
+ whatCanUserDo: {
30
+ default: [
31
+ `Please verify in "${packageName}/package.json::harmony::codegenConfig". If you are not the maintainer of this package, please report this problem to the package maintainer.`,
32
+ ],
33
+ },
34
+ });
35
+ }
36
+ if (fs.lstatSync(specPath.getValue()).isDirectory()) {
37
+ return findFilePathsWithExtensions(specPath, SUPPORTED_SPEC_EXTENSIONS);
38
+ } else {
39
+ const ext = specPath.getExtension();
40
+ if (ext && SUPPORTED_SPEC_EXTENSIONS.includes(ext)) {
41
+ return [specPath];
42
+ }
43
+ return [];
44
+ }
45
+ });
46
+ return new CodegenConfig(specFilePaths);
47
+ }
48
+
49
+ private constructor(private specFilePaths: AbsolutePath[]) {}
50
+
51
+ getSpecFilePaths(): AbsolutePath[] {
52
+ return this.specFilePaths;
53
+ }
54
+ }