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

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 (66) hide show
  1. package/dist/assetResolver.js +105 -10
  2. package/dist/autolinking/Autolinking.js +9 -11
  3. package/dist/codegen/core/EventUtils.js +5 -8
  4. package/dist/codegen/core/TypeAnnotationToTS.js +3 -3
  5. package/dist/codegen/core/UberSchema.js +7 -11
  6. package/dist/codegen/generators/ArkTSComponentCodeGeneratorArkTS.js +3 -0
  7. package/dist/codegen/generators/ArkTSComponentCodeGeneratorCAPI.js +3 -0
  8. package/dist/codegen/generators/CppComponentCodeGenerator.js +3 -0
  9. package/dist/codegen/templates/ComponentJSIBinderHTemplate.js +15 -0
  10. package/dist/commands/bundle-harmony.js +5 -68
  11. package/dist/commands/codegen-harmony.js +13 -17
  12. package/dist/commands/codegen-lib-harmony.js +10 -14
  13. package/dist/commands/create-metro-host-constants.js +1 -1
  14. package/dist/commands/index.js +2 -1
  15. package/dist/commands/init.js +703 -0
  16. package/dist/commands/link-harmony.js +1 -1
  17. package/dist/commands/pack-harmony.js +1 -1
  18. package/dist/commands/run-harmony.js +438 -0
  19. package/dist/commands/types.js +8 -0
  20. package/dist/commands/unpack-harmony.js +2 -4
  21. package/dist/commands/verify-package-harmony.js +2 -2
  22. package/dist/core/CodegenConfig.js +4 -6
  23. package/dist/core/DescriptiveError.js +8 -4
  24. package/dist/core/PackageJSON.js +4 -7
  25. package/dist/core/fs.js +4 -5
  26. package/dist/index.js +2 -1
  27. package/dist/io/CliExecutor.js +57 -24
  28. package/dist/io/Logger.js +72 -42
  29. package/dist/io/TarGz.js +1 -2
  30. package/dist/io/__fixtures__.js +9 -3
  31. package/dist/io/fsUtils.js +1 -2
  32. package/dist/package-verifier/checks/HarmonyDirContainsOnlyHarsCheck.js +1 -2
  33. package/dist/package-verifier/checks/HarmonyDirExistsCheck.js +1 -2
  34. package/dist/package-verifier/checks/NpmAnAndOhPackageVersionsAreEqual.js +1 -2
  35. package/dist/package-verifier/checks/OhPackageNameFollowsNamingConventionCheck.js +1 -2
  36. package/dist/package-verifier/verify-package.js +7 -10
  37. package/package.json +10 -3
  38. package/src/assetResolver.ts +117 -11
  39. package/src/autolinking/Autolinking.ts +10 -12
  40. package/src/codegen/core/EventUtils.ts +4 -6
  41. package/src/codegen/core/UberSchema.ts +7 -11
  42. package/src/codegen/generators/ArkTSComponentCodeGeneratorArkTS.ts +3 -0
  43. package/src/codegen/generators/ArkTSComponentCodeGeneratorCAPI.ts +3 -0
  44. package/src/codegen/generators/CppComponentCodeGenerator.ts +3 -0
  45. package/src/codegen/templates/ComponentJSIBinderHTemplate.ts +24 -1
  46. package/src/commands/bundle-harmony.ts +6 -82
  47. package/src/commands/codegen-harmony.ts +14 -19
  48. package/src/commands/codegen-lib-harmony.ts +11 -16
  49. package/src/commands/create-metro-host-constants.ts +2 -2
  50. package/src/commands/index.ts +2 -1
  51. package/src/commands/init.ts +755 -0
  52. package/src/commands/link-harmony.ts +2 -2
  53. package/src/commands/pack-harmony.ts +2 -2
  54. package/src/commands/run-harmony.ts +478 -0
  55. package/src/commands/types.ts +21 -0
  56. package/src/commands/unpack-harmony.ts +3 -5
  57. package/src/commands/verify-package-harmony.ts +3 -3
  58. package/src/core/CodegenConfig.ts +4 -6
  59. package/src/core/DescriptiveError.ts +9 -9
  60. package/src/core/PackageJSON.ts +5 -8
  61. package/src/core/fs.ts +2 -2
  62. package/src/index.ts +5 -3
  63. package/src/io/CliExecutor.ts +56 -34
  64. package/src/io/Logger.ts +78 -45
  65. package/src/io/__fixtures__.ts +15 -11
  66. package/src/package-verifier/verify-package.ts +5 -7
@@ -1,35 +1,68 @@
1
1
  "use strict";
2
2
  /**
3
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
+ * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
4
4
  *
5
5
  * This source code is licensed under the MIT license found in the
6
6
  * LICENSE-MIT file in the root directory of this source tree.
7
7
  */
8
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
+ return new (P || (P = Promise))(function (resolve, reject) {
11
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
15
+ });
16
+ };
8
17
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.CliExecutor = void 0;
18
+ exports.RealCliExecutor = exports.CliExecutor = void 0;
19
+ const node_child_process_1 = require("node:child_process");
10
20
  class CliExecutor {
11
- stringifyCliArgs(args) {
12
- return Object.entries(args)
13
- .filter(([_, value]) => {
14
- if (typeof value === 'boolean') {
15
- return value;
16
- }
17
- return value !== undefined && value !== null;
18
- })
19
- .map(([key, value]) => {
20
- const formattedKey = toKebabCase(key);
21
- if (typeof value === 'boolean') {
22
- return `--${formattedKey}`;
23
- }
24
- return `--${formattedKey} ${value}`;
25
- })
26
- .join(' ');
27
- }
28
21
  }
29
22
  exports.CliExecutor = CliExecutor;
30
- function toKebabCase(str) {
31
- return str
32
- .replace(/([a-z])([A-Z])/g, '$1-$2')
33
- .replace(/[\s_]+/g, '-')
34
- .toLowerCase();
23
+ class RealCliExecutor extends CliExecutor {
24
+ run(command, options) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ return new Promise((resolve, reject) => {
27
+ var _a, _b;
28
+ let commandWithArgs = command;
29
+ let argStrings = [];
30
+ if (options === null || options === void 0 ? void 0 : options.args) {
31
+ argStrings = options.args;
32
+ commandWithArgs += ' ' + argStrings.join(' ');
33
+ }
34
+ (_a = options === null || options === void 0 ? void 0 : options.onArgsStringified) === null || _a === void 0 ? void 0 : _a.call(options, commandWithArgs);
35
+ const process = (0, node_child_process_1.spawn)(command, argStrings, {
36
+ cwd: (_b = options === null || options === void 0 ? void 0 : options.cwd) === null || _b === void 0 ? void 0 : _b.toString(),
37
+ shell: (options === null || options === void 0 ? void 0 : options.shell) ? true : false,
38
+ });
39
+ let stdout = '';
40
+ let stderr = '';
41
+ process.stdout.on('data', (data) => {
42
+ var _a;
43
+ const output = data.toString();
44
+ stdout += output;
45
+ (_a = options === null || options === void 0 ? void 0 : options.onStdout) === null || _a === void 0 ? void 0 : _a.call(options, output);
46
+ });
47
+ process.stderr.on('data', (data) => {
48
+ var _a;
49
+ const output = data.toString();
50
+ stderr += output;
51
+ (_a = options === null || options === void 0 ? void 0 : options.onStderr) === null || _a === void 0 ? void 0 : _a.call(options, output);
52
+ });
53
+ process.on('error', (error) => {
54
+ reject(error);
55
+ });
56
+ process.on('close', (code) => {
57
+ if (code === 0) {
58
+ resolve(stdout);
59
+ }
60
+ else {
61
+ reject(new Error(`Command failed with code ${code}\nStderr: ${stderr}`));
62
+ }
63
+ });
64
+ });
65
+ });
66
+ }
35
67
  }
68
+ exports.RealCliExecutor = RealCliExecutor;
package/dist/io/Logger.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  /**
3
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
+ * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
4
4
  *
5
5
  * This source code is licensed under the MIT license found in the
6
6
  * LICENSE-MIT file in the root directory of this source tree.
@@ -11,24 +11,56 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.Logger = void 0;
13
13
  const chalk_1 = __importDefault(require("chalk"));
14
+ const cli_tools_1 = require("@react-native-community/cli-tools");
15
+ const node_process_1 = __importDefault(require("node:process"));
14
16
  class Logger {
15
- info(prepareMsg, options) {
16
- const prefix = (options === null || options === void 0 ? void 0 : options.prefix) ? `[${chalk_1.default.bold(chalk_1.default.cyan('INFO'))}]` : '';
17
- if (prefix) {
18
- console.info(prefix, prepareMsg(chalk_1.default));
19
- }
20
- else {
21
- console.info(prepareMsg(chalk_1.default));
22
- }
17
+ constructor() {
18
+ this.loader = (0, cli_tools_1.getLoader)({
19
+ interval: node_process_1.default.stdout.isTTY ? undefined : 0,
20
+ });
21
+ this.logger = cli_tools_1.logger;
22
+ this.isLoaderActive = false;
23
+ }
24
+ start(prepareMsg) {
25
+ this.loader.start(prepareMsg(chalk_1.default));
26
+ this.isLoaderActive = true;
27
+ return (options) => {
28
+ this.isLoaderActive = false;
29
+ if (options === null || options === void 0 ? void 0 : options.persist) {
30
+ console.log({ loader: this.loader });
31
+ this.loader.stopAndPersist();
32
+ }
33
+ else {
34
+ this.loader.stop();
35
+ }
36
+ };
37
+ }
38
+ info(prepareMsg) {
39
+ const info = (msg) => {
40
+ this.isLoaderActive ? this.loader.info(msg) : this.logger.info(msg);
41
+ };
42
+ info(prepareMsg(chalk_1.default));
43
+ }
44
+ succeed(prepareMsg) {
45
+ const succeed = (msg) => this.isLoaderActive ? this.loader.succeed(msg) : this.logger.success(msg);
46
+ succeed(prepareMsg(chalk_1.default));
23
47
  }
24
48
  warn(prepareMsg) {
25
- console.warn(prepareMsg(chalk_1.default));
49
+ const warn = (msg) => this.isLoaderActive ? this.loader.warn(msg) : this.logger.warn(msg);
50
+ warn(prepareMsg(chalk_1.default));
26
51
  }
27
52
  debug(prepareMsg) {
28
- console.debug(prepareMsg(chalk_1.default));
53
+ if (this.isLoaderActive) {
54
+ clearLine(node_process_1.default.stdout);
55
+ moveCursor(node_process_1.default.stdout, 0);
56
+ console.debug(prepareMsg(chalk_1.default));
57
+ this.loader.render();
58
+ }
59
+ else {
60
+ console.debug(prepareMsg(chalk_1.default));
61
+ }
29
62
  }
30
63
  descriptiveError(error) {
31
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
32
64
  const lines = [];
33
65
  if (error.isUnexpected() && error.stack) {
34
66
  lines.push('');
@@ -42,39 +74,37 @@ class Logger {
42
74
  details.split('\n').forEach((line) => lines.push(line));
43
75
  }
44
76
  lines.push('');
45
- let prefix = '';
46
- if (error.isUnexpected()) {
47
- prefix = '[' + chalk_1.default.red(chalk_1.default.bold('UNEXPECTED_ERROR')) + ']';
77
+ lines.push(`${error.getMessage()}`);
78
+ const suggestions = error.getSuggestions();
79
+ if (suggestions.length > 0) {
80
+ lines.push('');
81
+ lines.push(chalk_1.default.bold(`Suggestions`));
82
+ suggestions.forEach((suggestion) => {
83
+ lines.push('• ' + suggestion);
84
+ });
48
85
  }
49
- else {
50
- prefix = '[' + chalk_1.default.red(chalk_1.default.bold('ERROR')) + ']';
86
+ if (this.isLoaderActive) {
87
+ this.loader.fail(lines.join('\n').trim());
51
88
  }
52
- lines.push(`${prefix} ${error.getMessage()}`);
53
- const suggestionsByRole = error.getSuggestionsByRole();
54
- if (suggestionsByRole) {
55
- if (((_b = (_a = suggestionsByRole.default) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) {
56
- lines.push('');
57
- lines.push(chalk_1.default.bold(`Suggestions`));
58
- (_c = suggestionsByRole.default) === null || _c === void 0 ? void 0 : _c.forEach((suggestion) => {
59
- lines.push(suggestion);
60
- });
61
- }
62
- if (((_e = (_d = suggestionsByRole.rnAppDeveloper) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0) > 0) {
63
- lines.push('');
64
- lines.push(chalk_1.default.bold(`Suggestions for RN App developers`));
65
- (_f = suggestionsByRole.rnAppDeveloper) === null || _f === void 0 ? void 0 : _f.forEach((suggestion) => {
66
- lines.push(suggestion);
67
- });
68
- }
69
- if ((_h = (_g = suggestionsByRole.rnPackageDeveloper) === null || _g === void 0 ? void 0 : _g.length) !== null && _h !== void 0 ? _h : 0) {
70
- lines.push('');
71
- lines.push(chalk_1.default.bold(`Suggestions for RN package developers`));
72
- (_j = suggestionsByRole.rnPackageDeveloper) === null || _j === void 0 ? void 0 : _j.forEach((suggestion) => {
73
- lines.push(suggestion);
74
- });
75
- }
89
+ else {
90
+ this.logger.error(lines.join('\n').trim());
76
91
  }
77
- console.error(lines.join('\n'));
78
92
  }
79
93
  }
80
94
  exports.Logger = Logger;
95
+ const clearLine = (stream) => {
96
+ if (stream.clearLine) {
97
+ stream.clearLine(0);
98
+ }
99
+ else {
100
+ node_process_1.default.stdout.write('\r' + ' '.repeat(node_process_1.default.stdout.columns || 80) + '\r');
101
+ }
102
+ };
103
+ const moveCursor = (stream, x) => {
104
+ if (stream.cursorTo) {
105
+ stream.cursorTo(x);
106
+ }
107
+ else {
108
+ node_process_1.default.stdout.write('\r');
109
+ }
110
+ };
package/dist/io/TarGz.js CHANGED
@@ -9,7 +9,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.unpackTarGz = void 0;
12
+ exports.unpackTarGz = unpackTarGz;
13
13
  const node_fs_1 = __importDefault(require("node:fs"));
14
14
  const zlib_1 = __importDefault(require("zlib"));
15
15
  const tar_1 = __importDefault(require("tar"));
@@ -31,4 +31,3 @@ function unpackTarGz(archivePath, outputDirPath) {
31
31
  });
32
32
  });
33
33
  }
34
- exports.unpackTarGz = unpackTarGz;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  /**
3
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
+ * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
4
4
  *
5
5
  * This source code is licensed under the MIT license found in the
6
6
  * LICENSE-MIT file in the root directory of this source tree.
@@ -31,10 +31,10 @@ class FakeCliExecutor extends CliExecutor_1.CliExecutor {
31
31
  this.onRun = onRun;
32
32
  this.commands = [];
33
33
  }
34
- run(command, options = {}) {
34
+ run(command, options) {
35
35
  let commandWithArgs = command;
36
36
  if (options.args) {
37
- commandWithArgs += ' ' + this.stringifyCliArgs(options.args);
37
+ commandWithArgs += options.args.join(' ');
38
38
  }
39
39
  this.commands.push(commandWithArgs);
40
40
  return this.onRun(commandWithArgs);
@@ -52,9 +52,15 @@ class MemFSDirent extends core_1.Dirent {
52
52
  isDirectory() {
53
53
  return this.rawDirent.isDirectory();
54
54
  }
55
+ isSymbolicLink() {
56
+ return false;
57
+ }
55
58
  get name() {
56
59
  return this.rawDirent.name.toString();
57
60
  }
61
+ get path() {
62
+ return new core_1.AbsolutePath(this.rawDirent.path).copyWithNewSegment(this.rawDirent.name.toString());
63
+ }
58
64
  }
59
65
  class MemFS extends core_1.FS {
60
66
  constructor(initialFileStructure) {
@@ -9,7 +9,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  return (mod && mod.__esModule) ? mod : { "default": mod };
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.findFilePathsWithExtensions = void 0;
12
+ exports.findFilePathsWithExtensions = findFilePathsWithExtensions;
13
13
  const node_path_1 = __importDefault(require("node:path"));
14
14
  const Dirent_1 = __importDefault(require("memfs/lib/Dirent"));
15
15
  const node_fs_1 = __importDefault(require("node:fs"));
@@ -34,4 +34,3 @@ function findFilePathsWithExtensions(dirPath, fileExtensions, options = {}) {
34
34
  }
35
35
  return results;
36
36
  }
37
- exports.findFilePathsWithExtensions = findFilePathsWithExtensions;
@@ -18,7 +18,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  return (mod && mod.__esModule) ? mod : { "default": mod };
19
19
  };
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.createHarmonyDirContainsOnlyHarsCheck = void 0;
21
+ exports.createHarmonyDirContainsOnlyHarsCheck = createHarmonyDirContainsOnlyHarsCheck;
22
22
  const node_fs_1 = __importDefault(require("node:fs"));
23
23
  function createHarmonyDirContainsOnlyHarsCheck(npmPackagePath, hasNpmPackageNativeCode) {
24
24
  return {
@@ -41,4 +41,3 @@ function createHarmonyDirContainsOnlyHarsCheck(npmPackagePath, hasNpmPackageNati
41
41
  }),
42
42
  };
43
43
  }
44
- exports.createHarmonyDirContainsOnlyHarsCheck = createHarmonyDirContainsOnlyHarsCheck;
@@ -18,7 +18,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  return (mod && mod.__esModule) ? mod : { "default": mod };
19
19
  };
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.createHarmonyDirExistsCheck = void 0;
21
+ exports.createHarmonyDirExistsCheck = createHarmonyDirExistsCheck;
22
22
  const node_fs_1 = __importDefault(require("node:fs"));
23
23
  function createHarmonyDirExistsCheck(packagePath, hasNativeCode) {
24
24
  return {
@@ -35,4 +35,3 @@ function createHarmonyDirExistsCheck(packagePath, hasNativeCode) {
35
35
  }),
36
36
  };
37
37
  }
38
- exports.createHarmonyDirExistsCheck = createHarmonyDirExistsCheck;
@@ -15,7 +15,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
15
15
  });
16
16
  };
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.createNpmAndOhPackageVersionsAreEqualCheck = void 0;
18
+ exports.createNpmAndOhPackageVersionsAreEqualCheck = createNpmAndOhPackageVersionsAreEqualCheck;
19
19
  function createNpmAndOhPackageVersionsAreEqualCheck(npmPackageVersion, ohPackageVersion) {
20
20
  return {
21
21
  checkIf: 'npm_and_oh_package_versions_are_equal',
@@ -29,4 +29,3 @@ function createNpmAndOhPackageVersionsAreEqualCheck(npmPackageVersion, ohPackage
29
29
  }),
30
30
  };
31
31
  }
32
- exports.createNpmAndOhPackageVersionsAreEqualCheck = createNpmAndOhPackageVersionsAreEqualCheck;
@@ -15,7 +15,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
15
15
  });
16
16
  };
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.createOhPackageNameFollowsNamingConventionCheck = void 0;
18
+ exports.createOhPackageNameFollowsNamingConventionCheck = createOhPackageNameFollowsNamingConventionCheck;
19
19
  function createOhPackageNameFollowsNamingConventionCheck(npmPackageName, ohPackageName) {
20
20
  const npmPackageNameInfo = getPackageNameInfo(npmPackageName);
21
21
  return {
@@ -42,7 +42,6 @@ function createOhPackageNameFollowsNamingConventionCheck(npmPackageName, ohPacka
42
42
  }),
43
43
  };
44
44
  }
45
- exports.createOhPackageNameFollowsNamingConventionCheck = createOhPackageNameFollowsNamingConventionCheck;
46
45
  function getPackageNameInfo(packageName) {
47
46
  if (packageName.startsWith('@') && packageName.includes('/')) {
48
47
  const [part1, part2] = packageName.split('/');
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  /**
3
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
3
+ * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
4
4
  *
5
5
  * This source code is licensed under the MIT license found in the
6
6
  * LICENSE-MIT file in the root directory of this source tree.
@@ -21,7 +21,7 @@ var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {
21
21
  var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
22
22
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
23
23
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
24
- return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
24
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
25
25
  function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
26
26
  function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
27
27
  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
@@ -34,7 +34,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
34
34
  return (mod && mod.__esModule) ? mod : { "default": mod };
35
35
  };
36
36
  Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.verifyRNOHPackage = void 0;
37
+ exports.verifyRNOHPackage = verifyRNOHPackage;
38
38
  const node_fs_1 = __importDefault(require("node:fs"));
39
39
  const tmp_1 = __importDefault(require("tmp"));
40
40
  const core_1 = require("../core");
@@ -53,12 +53,10 @@ function verifyRNOHPackage(_a) {
53
53
  if (!harPath) {
54
54
  throw new core_1.DescriptiveError({
55
55
  whatHappened: 'Attempted to verify har but no har was found',
56
- whatCanUserDo: {
57
- default: [
58
- 'Run this command without --no-harmony-code flag.',
59
- 'Create har files by running DevEco Studio > Build > Make Module (MODULE_NAME). The har file can be later found in MODULE_NAME/build/default/outputs/default/MODULE_NAME.har. Copy that file to the PACKAGE_ROOT/harmony directory.',
60
- ],
61
- },
56
+ whatCanUserDo: [
57
+ 'Run this command without --no-harmony-code flag.',
58
+ 'Create har files by running DevEco Studio > Build > Make Module (MODULE_NAME). The har file can be later found in MODULE_NAME/build/default/outputs/default/MODULE_NAME.har. Copy that file to the PACKAGE_ROOT/harmony directory.',
59
+ ],
62
60
  });
63
61
  }
64
62
  const tmpDirPath = new core_1.AbsolutePath(tmp_1.default.dirSync().name);
@@ -76,7 +74,6 @@ function verifyRNOHPackage(_a) {
76
74
  }
77
75
  });
78
76
  }
79
- exports.verifyRNOHPackage = verifyRNOHPackage;
80
77
  function runChecks(checks, checkNamesToSkip) {
81
78
  return __asyncGenerator(this, arguments, function* runChecks_1() {
82
79
  for (const { checkIf, run } of checks) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-native-oh/react-native-harmony-cli",
3
- "version": "0.0.28",
3
+ "version": "0.0.36",
4
4
  "description": "",
5
5
  "publishConfig": {
6
6
  "registry": "https://registry.npmjs.org/",
@@ -15,6 +15,9 @@
15
15
  "rn": "npm run build && react-native",
16
16
  "prepublishOnly": "npm run verify"
17
17
  },
18
+ "bin": {
19
+ "rnoh-cli": "dist/commands/init.js"
20
+ },
18
21
  "keywords": [],
19
22
  "author": "",
20
23
  "license": "MIT",
@@ -23,6 +26,7 @@
23
26
  },
24
27
  "main": "dist/index.js",
25
28
  "devDependencies": {
29
+ "@react-native-community/cli": "^15.0.0",
26
30
  "@react-native-community/cli-types": "^11.3.0",
27
31
  "@types/adm-zip": "^0.5.5",
28
32
  "@types/fs-extra": "^11.0.1",
@@ -40,20 +44,23 @@
40
44
  "typescript": "^5.0.4"
41
45
  },
42
46
  "dependencies": {
43
- "memfs": "^4.12.0",
44
47
  "@react-native-community/cli-tools": "^13.6.5",
45
48
  "@react-native/codegen": "0.74.0",
46
49
  "@tsconfig/recommended": "^1.0.2",
47
50
  "adm-zip": "^0.5.12",
48
51
  "case": "^1.6.3",
49
52
  "chalk": "^4",
53
+ "commander": "^14.0.0",
50
54
  "fs-extra": "^11.1.1",
51
55
  "glob": "^10.2.6",
52
56
  "ignore": "^5.2.4",
57
+ "inquirer": "^12.7.0",
53
58
  "json5": "^2.2.3",
59
+ "memfs": "4.12.0",
54
60
  "mustache": "^4.2.0",
55
61
  "tar": "^6.1.15",
56
- "tmp": "^0.2.1"
62
+ "tmp": "^0.2.1",
63
+ "metro": "0.82.5"
57
64
  },
58
65
  "homepage": "https://gitee.com/openharmony-sig/ohos_react_native",
59
66
  "repository": {
@@ -4,25 +4,131 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE-MIT file in the root directory of this source tree.
6
6
  */
7
-
7
+ import fs from 'fs';
8
+ import pathUtils from 'path';
8
9
  import type { AssetData } from 'metro';
10
+ import { Logger } from './io';
11
+
12
+ type Path = string;
13
+ type CopiedFiles = Record<Path, Path>;
14
+
15
+ const ALLOWED_SCALES: number[] = [1, 2, 3, 4];
16
+
17
+ function filterAssetScales(
18
+ scales: readonly number[],
19
+ ): readonly number[] {
20
+ const result = scales.filter(scale => ALLOWED_SCALES.includes(scale));
21
+ if (result.length === 0 && scales.length > 0) {
22
+ // No matching scale found, but there are some available. Ideally we don't
23
+ // want to be in this situation and should throw, but for now as a fallback
24
+ // let's just use the closest larger image
25
+ const maxScale = ALLOWED_SCALES[ALLOWED_SCALES.length - 1];
26
+ for (const scale of scales) {
27
+ if (scale > maxScale) {
28
+ result.push(scale);
29
+ break;
30
+ }
31
+ }
32
+ // There is no larger scales available, use the largest we have
33
+ if (result.length === 0) {
34
+ result.push(scales[scales.length - 1]);
35
+ }
36
+ }
37
+ return result;
38
+ }
39
+
40
+ export async function copyAssets(
41
+ logger: Logger,
42
+ assetsData: readonly AssetData[],
43
+ assetsDest: Path
44
+ ): Promise<void> {
45
+ if (assetsDest == null) {
46
+ logger.warn((s) => 'Assets destination folder is not set, skipping...');
47
+ return;
48
+ }
49
+
50
+ const filesToCopy: CopiedFiles = {};
51
+ const addAssetToCopy = (asset: AssetData) => {
52
+ const validScales = filterAssetScales(asset.scales);
53
+ asset.scales.forEach((scale, idx) => {
54
+ if (!validScales.includes(scale)) {
55
+ return;
56
+ }
57
+ const src = asset.files[idx];
58
+ const dest = pathUtils.join(assetsDest, getAssetDestRelativePath(asset, scale));
59
+ filesToCopy[src] = dest;
60
+ });
61
+ };
62
+
63
+ assetsData.forEach(addAssetToCopy);
9
64
 
10
- export type Asset = AssetData;
65
+ return copyFiles(logger, filesToCopy);
66
+ }
11
67
 
12
- export function getAssetDestRelativePath(asset: Asset): string {
68
+ function getAssetDestRelativePath(asset: AssetData, scale: number = 1): string {
69
+ const suffix = scale === 1 ? '' : `@${scale}x`;
13
70
  const fileName = getResourceIdentifier(asset);
14
- return `${fileName}.${asset.type}`;
71
+ // Assets can have relative paths outside of the project root.
72
+ // Replace `../` with `_` to make sure they don't end up outside of
73
+ // the expected assets directory.
74
+ return `${fileName + suffix}.${asset.type}`.replace(/\.\.\//g, '_');
15
75
  }
16
76
 
17
- function getResourceIdentifier(asset: Asset): string {
77
+ function getResourceIdentifier(asset: AssetData): string {
18
78
  const folderPath = getBasePath(asset);
19
- return `${folderPath}/${asset.name}`.slice('assets/'.length);
79
+ return `${folderPath}/${asset.name}`.replace(/^assets\//, '');
80
+ }
81
+
82
+ function getBasePath(asset: AssetData): string {
83
+ const basePath = asset.httpServerLocation;
84
+ return basePath.startsWith('/') ? basePath.slice(1) : basePath;
20
85
  }
21
86
 
22
- function getBasePath(asset: Asset): string {
23
- let basePath = asset.httpServerLocation;
24
- if (basePath[0] === '/') {
25
- basePath = basePath.substr(1);
87
+ function copyFiles(logger: Logger, fileDestBySrc: CopiedFiles) {
88
+ const fileSources = Object.keys(fileDestBySrc);
89
+ if (fileSources.length === 0) {
90
+ return Promise.resolve();
26
91
  }
27
- return basePath;
92
+
93
+ const assetFilesCount = fileSources.length;
94
+ return new Promise<void>((resolve, reject) => {
95
+ const copyNext = (error?: Error) => {
96
+ if (error) {
97
+ reject(error);
98
+ return;
99
+ }
100
+ if (fileSources.length === 0) {
101
+ logger.info(
102
+ () =>
103
+ `Copied ${assetFilesCount} ${
104
+ assetFilesCount === 1 ? 'asset' : 'assets'
105
+ }`
106
+ );
107
+ resolve();
108
+ } else {
109
+ // fileSources.length === 0 is checked in previous branch, so this is string
110
+ const src = fileSources.shift()!;
111
+ const dest = fileDestBySrc[src];
112
+ copyFile(src, dest, copyNext);
113
+ }
114
+ };
115
+ copyNext();
116
+ });
117
+ }
118
+
119
+ function copyFile(
120
+ src: string,
121
+ dest: string,
122
+ onFinished: (error?: Error) => void
123
+ ): void {
124
+ const destDir = pathUtils.dirname(dest);
125
+ fs.mkdir(destDir, { recursive: true }, (err?) => {
126
+ if (err) {
127
+ onFinished(err);
128
+ return;
129
+ }
130
+ fs.createReadStream(src)
131
+ .pipe(fs.createWriteStream(dest))
132
+ .on('finish', onFinished);
133
+ });
28
134
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Copyright (c) 2024 Huawei Technologies Co., Ltd.
2
+ * Copyright (c) 2024-2025 Huawei Technologies Co., Ltd.
3
3
  *
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE-MIT file in the root directory of this source tree.
@@ -133,9 +133,8 @@ export class Autolinking {
133
133
  ) {
134
134
  throw new DescriptiveError({
135
135
  whatHappened: 'Tried to exclude and include npm packages.',
136
- whatCanUserDo: {
137
- default: ['Include or exclude npm packages, but not both.'],
138
- },
136
+ whatCanUserDo: ['Include or exclude npm packages, but not both.'],
137
+
139
138
  extraData: {
140
139
  includedNpmPackageNamesCount: config.includedNpmPackageNames.size,
141
140
  excludedNpmPackageNamesCount: config.excludedNpmPackageNames.size,
@@ -351,23 +350,23 @@ export class Autolinking {
351
350
  this.fs.writeTextSync(path, content);
352
351
  });
353
352
  output.linkedLibraryNpmPackageNames.forEach((npmPackageName) => {
354
- this.logger.info(
353
+ this.logger.debug(
355
354
  (styles) => `[${styles.green(styles.bold('link'))}] ${npmPackageName}`
356
355
  );
357
356
  });
358
357
  output.skippedLibraryNpmPackageNames.forEach((npmPackageName) => {
359
- this.logger.warn(
358
+ this.logger.debug(
360
359
  (styles) => `[${styles.yellow(styles.bold('skip'))}] ${npmPackageName}`
361
360
  );
362
361
  });
363
- this.logger.info(() => '');
362
+ this.logger.debug(() => '');
364
363
  const sortedPathsRelativeToRoot = pathAndContentPairs
365
364
  .map(([path]) => path.relativeTo(output.projectRootPath).toString())
366
365
  .sort();
367
366
  sortedPathsRelativeToRoot.forEach((pathStr) => {
368
- this.logger.info((styles) => styles.gray(`• ${pathStr}`));
367
+ this.logger.debug((styles) => styles.gray(`• ${pathStr}`));
369
368
  });
370
- this.logger.info(() => '');
369
+ this.logger.debug(() => '');
371
370
  this.logger.info(
372
371
  (styles) =>
373
372
  `updated ${styles.green(
@@ -376,9 +375,8 @@ export class Autolinking {
376
375
  styles.bold(output.linkedLibraryNpmPackageNames.length)
377
376
  )} libraries, skipped ${styles.yellow(
378
377
  styles.bold(output.skippedLibraryNpmPackageNames.length)
379
- )} libraries`,
380
- { prefix: true }
378
+ )} libraries`
381
379
  );
382
- this.logger.info(() => '');
380
+ this.logger.debug(() => '');
383
381
  }
384
382
  }