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

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.
@@ -35,6 +35,7 @@ class AppBuildTimeGlueCodeGenerator {
35
35
  generatedPackageH_v1.addComponent({
36
36
  name,
37
37
  supportedEventNames: eventNames,
38
+ isArkTSComponent: true,
38
39
  });
39
40
  });
40
41
  v1.turboModules.forEach((turboModule) => {
@@ -45,7 +46,7 @@ class AppBuildTimeGlueCodeGenerator {
45
46
  const basePackageClassName = `Base${case_1.default.pascal(libraryName)}Package`;
46
47
  const generatedPackageH_v2 = new BasePackageHTemplate_1.BasePackageHTemplate(basePackageClassName, this.codegenNoticeLines);
47
48
  components.forEach((component) => {
48
- generatedPackageH_v2.addComponent(component);
49
+ generatedPackageH_v2.addComponent(Object.assign(Object.assign({}, component), { isArkTSComponent: false }));
49
50
  });
50
51
  turboModules.forEach((turboModule) => {
51
52
  turboModules_indexTS.addReexport({ from: `./${turboModule.name}` });
@@ -35,11 +35,11 @@ class LibGlueCodeGenerator {
35
35
  });
36
36
  arkTSComponents.forEach(({ componentName, eventNames }) => {
37
37
  components_indexTS.addReexport({ from: `./${componentName}` });
38
- basePackageTemplate.addComponent({ name: componentName, libraryCppName });
38
+ basePackageTemplate.addComponent({ name: componentName, libraryCppName, isArkTSComponent: true });
39
39
  eventNames.forEach((eventName) => basePackageTemplate.addArkTSEvent({ name: eventName }));
40
40
  });
41
41
  cppComponents.forEach(({ componentName }) => {
42
- basePackageTemplate.addComponent({ name: componentName, libraryCppName });
42
+ basePackageTemplate.addComponent({ name: componentName, libraryCppName, isArkTSComponent: false });
43
43
  });
44
44
  fileContentByPath.set(this.cppOutputPath.copyWithNewSegment('RNOH', 'generated', `${basePackageClassName}.h`), basePackageTemplate.build());
45
45
  fileContentByPath.set(this.etsOutputPath.copyWithNewSegment('components', 'ts.ts'), components_indexTS.build());
@@ -50,16 +50,26 @@ class {{name}}EventEmitRequestHandler : public EventEmitRequestHandler {
50
50
  public:
51
51
  void handleEvent(Context const &ctx) override {
52
52
  auto eventEmitter = ctx.shadowViewRegistry->getEventEmitter<facebook::react::EventEmitter>(ctx.tag);
53
+ auto componentName = ctx.shadowViewRegistry->getComponentName(ctx.tag);
54
+
53
55
  if (eventEmitter == nullptr) {
54
56
  return;
55
57
  }
56
58
 
59
+ std::vector<std::string> supportedComponentNames = {
60
+ {{#arkTSComponents}}
61
+ "{{name}}",
62
+ {{/arkTSComponents}}
63
+ };
64
+
57
65
  std::vector<std::string> supportedEventNames = {
58
66
  {{#arkTSEvents}}
59
67
  "{{name}}",
60
68
  {{/arkTSEvents}}
61
69
  };
62
- if (std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
70
+
71
+ if (std::find(supportedComponentNames.begin(), supportedComponentNames.end(), componentName) != supportedComponentNames.end() &&
72
+ std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
63
73
  eventEmitter->dispatchEvent(ctx.eventName, ArkJS(ctx.env).getDynamic(ctx.payload));
64
74
  }
65
75
  }
@@ -126,6 +136,7 @@ class BasePackageHTemplate {
126
136
  name: this.name,
127
137
  turboModules: this.turboModules,
128
138
  components: this.components,
139
+ arkTSComponents: this.components.filter((component) => component.isArkTSComponent),
129
140
  arkTSEvents: this.arkTSEvents,
130
141
  libraries: Array.from(this.libraryCppNames).map((name) => ({
131
142
  name,
@@ -53,16 +53,26 @@ class GeneratedEventEmitRequestHandler : public EventEmitRequestHandler {
53
53
  public:
54
54
  void handleEvent(Context const &ctx) override {
55
55
  auto eventEmitter = ctx.shadowViewRegistry->getEventEmitter<facebook::react::EventEmitter>(ctx.tag);
56
+ auto componentName = ctx.shadowViewRegistry->getComponentName(ctx.tag);
57
+
56
58
  if (eventEmitter == nullptr) {
57
59
  return;
58
60
  }
59
61
 
62
+ std::vector<std::string> supportedComponentNames = {
63
+ {{#arkTSComponents}}
64
+ "{{name}}",
65
+ {{/arkTSComponents}}
66
+ };
67
+
60
68
  std::vector<std::string> supportedEventNames = {
61
69
  {{#supportedEvents}}
62
70
  "{{name}}",
63
71
  {{/supportedEvents}}
64
72
  };
65
- if (std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
73
+
74
+ if (std::find(supportedComponentNames.begin(), supportedComponentNames.end(), componentName) != supportedComponentNames.end() &&
75
+ std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
66
76
  eventEmitter->dispatchEvent(ctx.eventName, ArkJS(ctx.env).getDynamic(ctx.payload));
67
77
  }
68
78
  }
@@ -121,6 +131,7 @@ class RNOHGeneratedPackageHTemplate {
121
131
  return mustache_1.default.render(TEMPLATE.trimStart(), {
122
132
  turboModules: this.turboModules,
123
133
  components: this.components,
134
+ arkTSComponents: this.components.filter((component) => component.isArkTSComponent),
124
135
  supportedEvents: this.supportedEventNames.map((eventName) => ({
125
136
  name: eventName,
126
137
  })),
@@ -28,7 +28,10 @@ const json5_1 = __importDefault(require("json5"));
28
28
  const inquirer_1 = __importDefault(require("inquirer"));
29
29
  const path_1 = __importDefault(require("path"));
30
30
  const cli_tools_1 = require("@react-native-community/cli-tools");
31
+ const simulator_1 = require("../simulator");
31
32
  const COMMAND_NAME = 'run-harmony';
33
+ const LOOPBACK_IP = '127.0.0.1';
34
+ const DEFAULT_SIMULATOR_NAME = `${LOOPBACK_IP}:5555`;
32
35
  exports.commandRunHarmony = {
33
36
  name: COMMAND_NAME,
34
37
  description: 'Builds your app and starts it on your phone.',
@@ -112,7 +115,7 @@ exports.commandRunHarmony = {
112
115
  const buildMode = rawArgs.buildMode;
113
116
  const moduleName = rawArgs.module;
114
117
  const abilityName = rawArgs.ability;
115
- const simulatorName = rawArgs.simulator;
118
+ let simulatorName = rawArgs.simulator;
116
119
  const defaultPort = rawArgs.port;
117
120
  const packager = rawArgs.packager;
118
121
  const devEcoStudioToolsPath = new core_1.AbsolutePath(DEVECO_SDK_HOME).copyWithNewSegment('..', 'tools');
@@ -122,6 +125,19 @@ exports.commandRunHarmony = {
122
125
  });
123
126
  }
124
127
  const bundleName = json5_1.default.parse(fs.readTextSync(harmonyProjectPath.copyWithNewSegment('AppScope', 'app.json5'))).app.bundleName;
128
+ let currentPort = defaultPort;
129
+ if (packager) {
130
+ const root = _config.root || '.';
131
+ const reactNativePath = _config.reactNativePath || path_1.default.dirname(require.resolve('react-native', { paths: [root] }));
132
+ const { port: newPort, startPackager } = yield (0, cli_tools_1.findDevServerPort)(defaultPort, root);
133
+ if (newPort !== 8081) {
134
+ yield trySetMetroPort(harmonyProjectPath.copyWithNewSegment('entry', 'src', 'main', 'ets', 'pages', 'Index.ets').toString(), newPort);
135
+ }
136
+ if (startPackager) {
137
+ (0, cli_tools_1.startServerInNewWindow)(newPort, root, reactNativePath, (0, cli_tools_1.getDefaultUserTerminal)());
138
+ }
139
+ currentPort = newPort;
140
+ }
125
141
  const selectDevice = (deviceAndSimulatorInfos) => __awaiter(void 0, void 0, void 0, function* () {
126
142
  const lines = deviceAndSimulatorInfos.trim().split('\n');
127
143
  const availableDevices = lines.map((line) => {
@@ -147,6 +163,9 @@ exports.commandRunHarmony = {
147
163
  return simulatorName;
148
164
  }
149
165
  const connectedDevices = availableDevices.filter((deviceOrSimulator) => deviceOrSimulator.state === 'Connected');
166
+ if (connectedDevices.length === 1) {
167
+ return connectedDevices[0].name;
168
+ }
150
169
  if (connectedDevices.length > 1) {
151
170
  const answers = yield inquirer_1.default.prompt([
152
171
  {
@@ -158,15 +177,32 @@ exports.commandRunHarmony = {
158
177
  ]);
159
178
  return connectedDevices[parseInt(answers.selectedDeviceIndex) - 1].name;
160
179
  }
161
- else if (connectedDevices.length === 1) {
162
- return connectedDevices[0].name;
180
+ try {
181
+ yield (0, simulator_1.launchHarmonySimulator)({
182
+ devEcoStudioToolsPath,
183
+ sdkToolchainsPath,
184
+ cli,
185
+ logger,
186
+ env: process.env,
187
+ });
188
+ simulatorName = DEFAULT_SIMULATOR_NAME;
189
+ return simulatorName;
163
190
  }
164
- else {
191
+ catch (e) {
192
+ if (e instanceof core_1.DescriptiveError) {
193
+ throw new core_1.DescriptiveError({
194
+ whatHappened: `${e.getMessage()} \n No devices are connected. Failed to auto-launch simulator.`,
195
+ whatCanUserDo: [...e.getSuggestions()],
196
+ extraData: e.getRawData().extraData,
197
+ });
198
+ }
165
199
  throw new core_1.DescriptiveError({
166
- whatHappened: `No devices are connected in the current environment.`,
200
+ whatHappened: `No devices are connected in the current environment (auto-launch attempt failed).`,
167
201
  whatCanUserDo: [
168
- 'Please connect your HarmonyOS device or open the simulator.',
169
- ]
202
+ 'Connect a HarmonyOS device via USB or start the simulator manually.',
203
+ 'Re-run the command after a device is listed by: hdc list targets -v',
204
+ ],
205
+ extraData: e,
170
206
  });
171
207
  }
172
208
  });
@@ -175,18 +211,8 @@ exports.commandRunHarmony = {
175
211
  cwd: harmonyProjectPath,
176
212
  });
177
213
  const deviceOrSimulatorName = yield selectDevice(deviceAndSimulatorInfo);
178
- let currentPort = defaultPort;
179
- if (packager) {
180
- const root = _config.root || '.';
181
- const reactNativePath = _config.reactNativePath || path_1.default.dirname(require.resolve('react-native', { paths: [root] }));
182
- const { port: newPort, startPackager } = yield (0, cli_tools_1.findDevServerPort)(defaultPort, root);
183
- if (newPort !== 8081) {
184
- yield trySetMetroPort(harmonyProjectPath.copyWithNewSegment('entry', 'src', 'main', 'ets', 'pages', 'Index.ets').toString(), newPort);
185
- }
186
- if (startPackager) {
187
- (0, cli_tools_1.startServerInNewWindow)(newPort, root, reactNativePath, (0, cli_tools_1.getDefaultUserTerminal)());
188
- }
189
- currentPort = newPort;
214
+ if (deviceOrSimulatorName.includes(`${LOOPBACK_IP}:`)) {
215
+ simulatorName = deviceOrSimulatorName;
190
216
  }
191
217
  const runJob = (name, job) => __awaiter(void 0, void 0, void 0, function* () {
192
218
  const stop = logger.start((s) => s.bold(name));
@@ -215,8 +241,7 @@ exports.commandRunHarmony = {
215
241
  ohpmPath = devEcoStudioToolsPath
216
242
  .copyWithNewSegment('ohpm', 'bin', 'ohpm.bat');
217
243
  }
218
- yield cli.run(process.platform === 'win32' ? `"${ohpmPath.toString()}"` :
219
- ohpmPath.toString(), {
244
+ yield cli.run(`"${ohpmPath.toString()}"`, {
220
245
  args: [
221
246
  'install',
222
247
  '--all',
@@ -243,9 +268,8 @@ exports.commandRunHarmony = {
243
268
  nodePath = devEcoStudioToolsPath.copyWithNewSegment('node', 'node');
244
269
  }
245
270
  let hvigorPathRaw = devEcoStudioToolsPath.copyWithNewSegment('hvigor', 'bin', 'hvigorw.js').toString();
246
- const hvigorPath = process.platform === 'win32' ? `"${hvigorPathRaw}"` : hvigorPathRaw;
247
- yield cli.run(process.platform === 'win32' ? `"${nodePath.toString()}"` :
248
- nodePath.toString(), {
271
+ const hvigorPath = `"${hvigorPathRaw}"`;
272
+ yield cli.run(`"${nodePath.toString()}"`, {
249
273
  args: [
250
274
  hvigorPath,
251
275
  `-p`,
@@ -294,7 +318,7 @@ exports.commandRunHarmony = {
294
318
  const hdcPathStrRaw = sdkToolchainsPath
295
319
  .copyWithNewSegment('hdc')
296
320
  .toString();
297
- const hdcPathStr = process.platform === 'win32' ? `"${hdcPathStrRaw.toString()}"` : hdcPathStrRaw;
321
+ const hdcPathStr = `"${hdcPathStrRaw.toString()}"`;
298
322
  const tryRemoveForwardPorting = () => __awaiter(void 0, void 0, void 0, function* () {
299
323
  let fportInfo = '';
300
324
  yield cli.run(hdcPathStrRaw, {
@@ -0,0 +1,311 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
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
+ };
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.launchHarmonySimulator = launchHarmonySimulator;
22
+ const path_1 = __importDefault(require("path"));
23
+ const fs_extra_1 = __importDefault(require("fs-extra"));
24
+ const child_process_1 = require("child_process");
25
+ const core_1 = require("../core");
26
+ const MIN_SUPPORTED_VERSION = [6, 0, 0, 828];
27
+ function compareVersionTuple(a, b) {
28
+ var _a, _b;
29
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
30
+ const av = (_a = a[i]) !== null && _a !== void 0 ? _a : 0;
31
+ const bv = (_b = b[i]) !== null && _b !== void 0 ? _b : 0;
32
+ if (av !== bv)
33
+ return av - bv;
34
+ }
35
+ return 0;
36
+ }
37
+ function isSupportedVersion(versionDir) {
38
+ const m = versionDir.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)/);
39
+ if (!m)
40
+ return false;
41
+ const current = m.slice(1).map(n => parseInt(n, 10));
42
+ return compareVersionTuple(current, MIN_SUPPORTED_VERSION) >= 0;
43
+ }
44
+ function getCreatedSimulators(cli, emulator) {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ try {
47
+ let simulatorInfos = '';
48
+ yield cli.run(`"${emulator}"`, {
49
+ args: ['--list'],
50
+ shell: true,
51
+ onStderr: (msg) => {
52
+ simulatorInfos += msg;
53
+ },
54
+ });
55
+ if (!simulatorInfos || simulatorInfos.trim() === '' ||
56
+ simulatorInfos.trim() === '[Empty]' ||
57
+ simulatorInfos.includes('not ')) {
58
+ return [];
59
+ }
60
+ return simulatorInfos.split('\n').filter(line => line.trim() !== '');
61
+ }
62
+ catch (error) {
63
+ throw new core_1.DescriptiveError({
64
+ whatHappened: `Failed to get simulator list: ${(error === null || error === void 0 ? void 0 : error.message) || error}`,
65
+ whatCanUserDo: [
66
+ 'Ensure DevEco Studio is properly installed and configured.',
67
+ 'Check if the emulator path is correct.',
68
+ 'Verify that the emulator has read/write permissions.'
69
+ ],
70
+ extraData: error,
71
+ });
72
+ }
73
+ });
74
+ }
75
+ function getDevEcoVersion(devEcoStudioToolsPath) {
76
+ return __awaiter(this, void 0, void 0, function* () {
77
+ try {
78
+ let productInfoPath = path_1.default.join(devEcoStudioToolsPath.toString(), '..', 'Resources', 'product-info.json');
79
+ if (process.platform === 'win32') {
80
+ productInfoPath = path_1.default.join(devEcoStudioToolsPath.toString(), '..', 'product-info.json');
81
+ }
82
+ const content = yield fs_extra_1.default.readFile(productInfoPath, 'utf-8');
83
+ const info = JSON.parse(content);
84
+ return info.version || null;
85
+ }
86
+ catch (error) {
87
+ throw new core_1.DescriptiveError({
88
+ whatHappened: `Failed to read DevEco Studio version from product-info.json: ${(error === null || error === void 0 ? void 0 : error.message) || error}`,
89
+ whatCanUserDo: [
90
+ 'Verify DevEco Studio installation is complete and not corrupted.',
91
+ 'Check if the DevEco Studio tools path is correct.',
92
+ 'Ensure product-info.json file exists and is readable.'
93
+ ],
94
+ extraData: error,
95
+ });
96
+ }
97
+ });
98
+ }
99
+ function resolveDeviceManagerXml(env, devEcoVersion) {
100
+ const candidates = [];
101
+ if (process.platform === 'darwin') {
102
+ const home = env.HOME || '';
103
+ candidates.push(path_1.default.join(home, 'Library', 'Application Support', 'Huawei', `DevEcoStudio${devEcoVersion}`, 'options', 'deviceManager.xml'));
104
+ }
105
+ else if (process.platform === 'win32') {
106
+ const appdata = env.APPDATA || '';
107
+ candidates.push(path_1.default.join(appdata, 'Huawei', `DevEcoStudio${devEcoVersion}`, 'options', 'deviceManager.xml'));
108
+ }
109
+ else {
110
+ throw new core_1.DescriptiveError({
111
+ whatHappened: `Unsupported operating system.`,
112
+ whatCanUserDo: ['Please run the RNOH project on Windows or macOS.']
113
+ });
114
+ }
115
+ return candidates;
116
+ }
117
+ function parseDeviceManagerXml(xmlContent) {
118
+ const info = {};
119
+ const optionRegex = /<option\b[^>]*?>/gi;
120
+ let m;
121
+ while ((m = optionRegex.exec(xmlContent))) {
122
+ const tag = m[0];
123
+ const nameMatch = tag.match(/\bname=["']([^"']+)["']/i);
124
+ if (!nameMatch)
125
+ continue;
126
+ const valueMatch = tag.match(/\bvalue=["']([^"']+)["']/i);
127
+ if (!valueMatch)
128
+ continue;
129
+ const name = nameMatch[1];
130
+ const value = valueMatch[1];
131
+ if (name === 'imageDeployPath' && !info.imageRoot) {
132
+ info.imageRoot = value;
133
+ }
134
+ else if (name === 'openharmonyDeployPath' && !info.instancePath) {
135
+ info.instancePath = value;
136
+ }
137
+ if (info.imageRoot && info.instancePath)
138
+ break;
139
+ }
140
+ return info;
141
+ }
142
+ function candidateEmulatorExecutables(devEcoStudioToolsPath) {
143
+ const list = [];
144
+ const add = (...segs) => list.push(devEcoStudioToolsPath.copyWithNewSegment(...segs).toString());
145
+ if (process.platform === 'win32') {
146
+ add('emulator', 'Emulator.exe');
147
+ }
148
+ else {
149
+ add('emulator', 'Emulator');
150
+ }
151
+ return list;
152
+ }
153
+ function pickExisting(paths) {
154
+ return paths.find(p => fs_extra_1.default.existsSync(p));
155
+ }
156
+ function resolveInstanceAndImageRoot(env, devEcoVersion) {
157
+ return __awaiter(this, void 0, void 0, function* () {
158
+ const defaultInstanceCandidates = [];
159
+ const defaultImageCandidates = [];
160
+ if (process.platform === 'darwin') {
161
+ const home = env.HOME || '';
162
+ defaultInstanceCandidates.push(path_1.default.join(home, '.Huawei', 'Emulator', 'deployed'));
163
+ defaultImageCandidates.push(path_1.default.join(home, 'Library', 'Huawei', 'Sdk'));
164
+ }
165
+ else if (process.platform === 'win32') {
166
+ const localAppData = env.LOCALAPPDATA || '';
167
+ defaultInstanceCandidates.push(path_1.default.join(localAppData, 'Huawei', 'Emulator', 'deployed'));
168
+ defaultImageCandidates.push(path_1.default.join(localAppData, 'Huawei', 'Sdk'));
169
+ }
170
+ else {
171
+ throw new core_1.DescriptiveError({
172
+ whatHappened: `Unsupported operating system.`,
173
+ whatCanUserDo: ['Please run the RNOH project on Windows or macOS.']
174
+ });
175
+ }
176
+ let xmlInfo = {};
177
+ for (const xmlPath of resolveDeviceManagerXml(env, devEcoVersion)) {
178
+ if (fs_extra_1.default.existsSync(xmlPath)) {
179
+ try {
180
+ const content = yield fs_extra_1.default.readFile(xmlPath, 'utf-8');
181
+ xmlInfo = parseDeviceManagerXml(content);
182
+ if (xmlInfo.instancePath || xmlInfo.imageRoot)
183
+ break;
184
+ }
185
+ catch (error) {
186
+ throw new core_1.DescriptiveError({
187
+ whatHappened: `Failed to read or parse device manager XML at ${xmlPath}: ${(error === null || error === void 0 ? void 0 : error.message) || error}`,
188
+ whatCanUserDo: [
189
+ 'Verify that the DevEco Studio deviceManager.xml file exists and is readable.',
190
+ 'Check if DEVECO_SDK_HOME environment variable is set correctly.',
191
+ 'Ensure DevEco Studio has been launched at least once to generate configuration files.',
192
+ 'Check file permissions for the DevEco Studio configuration directory.'
193
+ ],
194
+ extraData: error,
195
+ });
196
+ }
197
+ }
198
+ }
199
+ let resolvedInstance = pickExisting(defaultInstanceCandidates);
200
+ let resolvedImageRoot = pickExisting(defaultImageCandidates);
201
+ if (xmlInfo.imageRoot) {
202
+ resolvedImageRoot = xmlInfo.imageRoot;
203
+ }
204
+ if (xmlInfo.instancePath) {
205
+ resolvedInstance = xmlInfo.instancePath;
206
+ }
207
+ if (!resolvedInstance || !resolvedImageRoot) {
208
+ throw new core_1.DescriptiveError({
209
+ whatHappened: `No simulator instance or image root directory detected.`,
210
+ whatCanUserDo: [
211
+ 'Have you already launched the simulator via DevEco Studio?'
212
+ ]
213
+ });
214
+ }
215
+ return { instancePath: resolvedInstance, imageRoot: resolvedImageRoot };
216
+ });
217
+ }
218
+ function launchHarmonySimulator(opt) {
219
+ return __awaiter(this, void 0, void 0, function* () {
220
+ const { devEcoStudioToolsPath, cli, logger, } = opt;
221
+ const devEcoVersion = yield getDevEcoVersion(devEcoStudioToolsPath);
222
+ if (!devEcoVersion) {
223
+ throw new core_1.DescriptiveError({
224
+ whatHappened: `DevEco Studio version could not be obtained.`,
225
+ whatCanUserDo: [
226
+ 'Verify DevEco Studio is properly installed and the tools path is correct.',
227
+ 'Check if product-info.json file exists in the DevEco Studio installation directory.',
228
+ 'Ensure you have the latest version of DevEco Studio installed.'
229
+ ]
230
+ });
231
+ }
232
+ if (!isSupportedVersion(devEcoVersion)) {
233
+ throw new core_1.DescriptiveError({
234
+ whatHappened: `Current DevEco SDK version (${devEcoVersion}) does not support launching the simulator via command line (requires >= ${MIN_SUPPORTED_VERSION.join('.')}).`,
235
+ whatCanUserDo: [
236
+ `Update DevEco Studio to version ${MIN_SUPPORTED_VERSION.join('.')} or higher.`,
237
+ 'Check the official DevEco Studio website for the latest version.',
238
+ 'Launch the simulator manually from DevEco Studio IDE.'
239
+ ]
240
+ });
241
+ }
242
+ const versionList = devEcoVersion.split('.');
243
+ const majorVersion = `${versionList[0]}.${versionList[1]}`;
244
+ const paths = yield resolveInstanceAndImageRoot(opt.env, majorVersion);
245
+ if (!paths) {
246
+ throw new core_1.DescriptiveError({
247
+ whatHappened: `Could not resolve simulator instance path or image root.`,
248
+ whatCanUserDo: [
249
+ 'Open DevEco Studio and launch the simulator at least once to generate configuration files.',
250
+ 'Check if DEVECO_SDK_HOME environment variable is set correctly.',
251
+ 'Verify that the simulator has been properly configured in DevEco Studio.',
252
+ 'Ensure the default simulator paths exist in your system.'
253
+ ]
254
+ });
255
+ }
256
+ const emulatorExe = pickExisting(candidateEmulatorExecutables(devEcoStudioToolsPath));
257
+ if (!emulatorExe) {
258
+ throw new core_1.DescriptiveError({
259
+ whatHappened: `Emulator executable not found in DevEco Studio installation.`,
260
+ whatCanUserDo: [
261
+ 'Verify DevEco Studio installation is complete and not corrupted.',
262
+ 'Check if the emulator component is installed in DevEco Studio.',
263
+ 'Reinstall DevEco Studio if the emulator binary is missing.',
264
+ 'Ensure the DevEco Studio tools path is correctly configured.'
265
+ ]
266
+ });
267
+ }
268
+ const simulatorName = yield getCreatedSimulators(cli, emulatorExe);
269
+ if (simulatorName.length <= 0) {
270
+ throw new core_1.DescriptiveError({
271
+ whatHappened: `No existing HarmonyOS simulator instance detected.`,
272
+ whatCanUserDo: [
273
+ 'Create a simulator instance in DevEco Studio first.',
274
+ 'Open DevEco Studio Device Manager and create a new virtual device.',
275
+ 'Ensure the simulator instance is properly configured and available.',
276
+ 'Check if the emulator --list command returns any valid instances.'
277
+ ]
278
+ });
279
+ }
280
+ try {
281
+ const quoteIfNeeded = (p) => process.platform === 'win32' ? `"${p}"` : p;
282
+ const args = [
283
+ '-hvd',
284
+ simulatorName[0].trim(),
285
+ '-path',
286
+ quoteIfNeeded(paths.instancePath),
287
+ '-imageRoot',
288
+ quoteIfNeeded(paths.imageRoot),
289
+ ];
290
+ const child = (0, child_process_1.spawn)(quoteIfNeeded(emulatorExe), args, {
291
+ cwd: path_1.default.dirname(emulatorExe),
292
+ detached: true,
293
+ stdio: 'ignore',
294
+ shell: process.platform === 'win32',
295
+ });
296
+ child.unref();
297
+ logger.info(() => `Launching HarmonyOS simulator in background: ${simulatorName[0]}`);
298
+ }
299
+ catch (e) {
300
+ throw new core_1.DescriptiveError({
301
+ whatHappened: `Failed to start simulator process: ${(e === null || e === void 0 ? void 0 : e.message) || e}`,
302
+ whatCanUserDo: [
303
+ 'Confirm that the DevEco Simulator can be started manually from DevEco Studio.',
304
+ 'Ensure no stale simulator process is blocking required ports.',
305
+ 'Reinstall or repair DevEco Studio if the simulator binary is corrupted.'
306
+ ],
307
+ extraData: e,
308
+ });
309
+ }
310
+ });
311
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ __exportStar(require("./LaunchSimulator"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-native-oh/react-native-harmony-cli",
3
- "version": "0.0.36",
3
+ "version": "0.0.37",
4
4
  "description": "",
5
5
  "publishConfig": {
6
6
  "registry": "https://registry.npmjs.org/",
@@ -62,9 +62,9 @@
62
62
  "tmp": "^0.2.1",
63
63
  "metro": "0.82.5"
64
64
  },
65
- "homepage": "https://gitee.com/openharmony-sig/ohos_react_native",
65
+ "homepage": "https://gitcode.com/openharmony-sig/ohos_react_native",
66
66
  "repository": {
67
- "type": "gitee",
68
- "url": "https://gitee.com/openharmony-sig/ohos_react_native"
67
+ "type": "gitcode",
68
+ "url": "https://gitcode.com/openharmony-sig/ohos_react_native"
69
69
  }
70
70
  }
@@ -62,6 +62,7 @@ export class AppBuildTimeGlueCodeGenerator
62
62
  generatedPackageH_v1.addComponent({
63
63
  name,
64
64
  supportedEventNames: eventNames,
65
+ isArkTSComponent: true,
65
66
  });
66
67
  });
67
68
 
@@ -76,7 +77,10 @@ export class AppBuildTimeGlueCodeGenerator
76
77
  this.codegenNoticeLines
77
78
  );
78
79
  components.forEach((component) => {
79
- generatedPackageH_v2.addComponent(component);
80
+ generatedPackageH_v2.addComponent({
81
+ ...component,
82
+ isArkTSComponent: false,
83
+ });
80
84
  });
81
85
  turboModules.forEach((turboModule) => {
82
86
  turboModules_indexTS.addReexport({ from: `./${turboModule.name}` });
@@ -57,13 +57,13 @@ export class LibGlueCodeGenerator implements CodeGenerator<LibGlueCodeData> {
57
57
  });
58
58
  arkTSComponents.forEach(({ componentName, eventNames }) => {
59
59
  components_indexTS.addReexport({ from: `./${componentName}` });
60
- basePackageTemplate.addComponent({ name: componentName, libraryCppName });
60
+ basePackageTemplate.addComponent({ name: componentName, libraryCppName, isArkTSComponent: true });
61
61
  eventNames.forEach((eventName) =>
62
62
  basePackageTemplate.addArkTSEvent({ name: eventName })
63
63
  );
64
64
  });
65
65
  cppComponents.forEach(({ componentName }) => {
66
- basePackageTemplate.addComponent({ name: componentName, libraryCppName });
66
+ basePackageTemplate.addComponent({ name: componentName, libraryCppName, isArkTSComponent: false });
67
67
  });
68
68
  fileContentByPath.set(
69
69
  this.cppOutputPath.copyWithNewSegment(
@@ -46,16 +46,26 @@ class {{name}}EventEmitRequestHandler : public EventEmitRequestHandler {
46
46
  public:
47
47
  void handleEvent(Context const &ctx) override {
48
48
  auto eventEmitter = ctx.shadowViewRegistry->getEventEmitter<facebook::react::EventEmitter>(ctx.tag);
49
+ auto componentName = ctx.shadowViewRegistry->getComponentName(ctx.tag);
50
+
49
51
  if (eventEmitter == nullptr) {
50
52
  return;
51
53
  }
52
54
 
55
+ std::vector<std::string> supportedComponentNames = {
56
+ {{#arkTSComponents}}
57
+ "{{name}}",
58
+ {{/arkTSComponents}}
59
+ };
60
+
53
61
  std::vector<std::string> supportedEventNames = {
54
62
  {{#arkTSEvents}}
55
63
  "{{name}}",
56
64
  {{/arkTSEvents}}
57
65
  };
58
- if (std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
66
+
67
+ if (std::find(supportedComponentNames.begin(), supportedComponentNames.end(), componentName) != supportedComponentNames.end() &&
68
+ std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
59
69
  eventEmitter->dispatchEvent(ctx.eventName, ArkJS(ctx.env).getDynamic(ctx.payload));
60
70
  }
61
71
  }
@@ -103,6 +113,7 @@ type GeneratedPackageTurboModule = {
103
113
  type GeneratedPackageComponent = {
104
114
  name: string;
105
115
  libraryCppName: string;
116
+ isArkTSComponent: boolean;
106
117
  };
107
118
 
108
119
  type ArkTSEvent = {
@@ -138,6 +149,7 @@ export class BasePackageHTemplate {
138
149
  name: this.name,
139
150
  turboModules: this.turboModules,
140
151
  components: this.components,
152
+ arkTSComponents: this.components.filter((component) => component.isArkTSComponent),
141
153
  arkTSEvents: this.arkTSEvents,
142
154
  libraries: Array.from(this.libraryCppNames).map((name) => ({
143
155
  name,
@@ -49,16 +49,26 @@ class GeneratedEventEmitRequestHandler : public EventEmitRequestHandler {
49
49
  public:
50
50
  void handleEvent(Context const &ctx) override {
51
51
  auto eventEmitter = ctx.shadowViewRegistry->getEventEmitter<facebook::react::EventEmitter>(ctx.tag);
52
+ auto componentName = ctx.shadowViewRegistry->getComponentName(ctx.tag);
53
+
52
54
  if (eventEmitter == nullptr) {
53
55
  return;
54
56
  }
55
57
 
58
+ std::vector<std::string> supportedComponentNames = {
59
+ {{#arkTSComponents}}
60
+ "{{name}}",
61
+ {{/arkTSComponents}}
62
+ };
63
+
56
64
  std::vector<std::string> supportedEventNames = {
57
65
  {{#supportedEvents}}
58
66
  "{{name}}",
59
67
  {{/supportedEvents}}
60
68
  };
61
- if (std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
69
+
70
+ if (std::find(supportedComponentNames.begin(), supportedComponentNames.end(), componentName) != supportedComponentNames.end() &&
71
+ std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
62
72
  eventEmitter->dispatchEvent(ctx.eventName, ArkJS(ctx.env).getDynamic(ctx.payload));
63
73
  }
64
74
  }
@@ -105,6 +115,7 @@ type RNOHGeneratedPackageTurboModule = {
105
115
  type RNOHGeneratedPackageComponent = {
106
116
  name: string;
107
117
  supportedEventNames: string[];
118
+ isArkTSComponent: boolean;
108
119
  };
109
120
 
110
121
  export class RNOHGeneratedPackageHTemplate {
@@ -130,6 +141,7 @@ export class RNOHGeneratedPackageHTemplate {
130
141
  return mustache.render(TEMPLATE.trimStart(), {
131
142
  turboModules: this.turboModules,
132
143
  components: this.components,
144
+ arkTSComponents: this.components.filter((component) => component.isArkTSComponent),
133
145
  supportedEvents: this.supportedEventNames.map((eventName) => ({
134
146
  name: eventName,
135
147
  })),
@@ -19,8 +19,11 @@ import {
19
19
  startServerInNewWindow,
20
20
  findDevServerPort,
21
21
  } from '@react-native-community/cli-tools';
22
+ import { launchHarmonySimulator } from '../simulator';
22
23
 
23
24
  const COMMAND_NAME = 'run-harmony';
25
+ const LOOPBACK_IP = '127.0.0.1';
26
+ const DEFAULT_SIMULATOR_NAME = `${LOOPBACK_IP}:5555`;
24
27
 
25
28
  export const commandRunHarmony: Command = {
26
29
  name: COMMAND_NAME,
@@ -108,7 +111,7 @@ export const commandRunHarmony: Command = {
108
111
  const buildMode: string = rawArgs.buildMode;
109
112
  const moduleName: string = rawArgs.module;
110
113
  const abilityName: string = rawArgs.ability;
111
- const simulatorName: string = rawArgs.simulator;
114
+ let simulatorName: string = rawArgs.simulator;
112
115
  const defaultPort: number = rawArgs.port;
113
116
  const packager: boolean = rawArgs.packager;
114
117
  const devEcoStudioToolsPath = new AbsolutePath(
@@ -125,6 +128,32 @@ export const commandRunHarmony: Command = {
125
128
  )
126
129
  ).app.bundleName;
127
130
 
131
+ let currentPort: number = defaultPort;
132
+ if (packager) {
133
+ const root: string = _config.root || '.';
134
+ const reactNativePath: string = _config.reactNativePath || path.dirname(
135
+ require.resolve('react-native', { paths: [root] }),
136
+ );
137
+ const { port: newPort, startPackager } = await findDevServerPort(
138
+ defaultPort,
139
+ root,
140
+ );
141
+
142
+ if (newPort !== 8081) {
143
+ await trySetMetroPort(harmonyProjectPath.copyWithNewSegment(
144
+ 'entry', 'src', 'main', 'ets', 'pages', 'Index.ets').toString(), newPort);
145
+ }
146
+ if (startPackager) {
147
+ startServerInNewWindow(
148
+ newPort,
149
+ root,
150
+ reactNativePath,
151
+ getDefaultUserTerminal(),
152
+ );
153
+ }
154
+ currentPort = newPort;
155
+ }
156
+
128
157
  const selectDevice = async (deviceAndSimulatorInfos: string) => {
129
158
  const lines = deviceAndSimulatorInfos.trim().split('\n');
130
159
  const availableDevices = lines.map((line) => {
@@ -150,6 +179,11 @@ export const commandRunHarmony: Command = {
150
179
  return simulatorName;
151
180
  }
152
181
  const connectedDevices = availableDevices.filter((deviceOrSimulator) => deviceOrSimulator.state === 'Connected');
182
+
183
+ if (connectedDevices.length === 1) {
184
+ return connectedDevices[0].name;
185
+ }
186
+
153
187
  if (connectedDevices.length > 1) {
154
188
  const answers = await inquirer.prompt([
155
189
  {
@@ -160,14 +194,33 @@ export const commandRunHarmony: Command = {
160
194
  }
161
195
  ])
162
196
  return connectedDevices[parseInt(answers.selectedDeviceIndex) - 1].name;
163
- } else if (connectedDevices.length === 1) {
164
- return connectedDevices[0].name;
165
- } else {
197
+ }
198
+
199
+ try {
200
+ await launchHarmonySimulator({
201
+ devEcoStudioToolsPath,
202
+ sdkToolchainsPath,
203
+ cli,
204
+ logger,
205
+ env: process.env,
206
+ });
207
+ simulatorName = DEFAULT_SIMULATOR_NAME;
208
+ return simulatorName;
209
+ } catch (e) {
210
+ if (e instanceof DescriptiveError) {
211
+ throw new DescriptiveError({
212
+ whatHappened: `${e.getMessage()} \n No devices are connected. Failed to auto-launch simulator.`,
213
+ whatCanUserDo: [...e.getSuggestions()],
214
+ extraData: e.getRawData().extraData,
215
+ });
216
+ }
166
217
  throw new DescriptiveError({
167
- whatHappened: `No devices are connected in the current environment.`,
218
+ whatHappened: `No devices are connected in the current environment (auto-launch attempt failed).`,
168
219
  whatCanUserDo: [
169
- 'Please connect your HarmonyOS device or open the simulator.',
170
- ]
220
+ 'Connect a HarmonyOS device via USB or start the simulator manually.',
221
+ 'Re-run the command after a device is listed by: hdc list targets -v',
222
+ ],
223
+ extraData: e,
171
224
  });
172
225
  }
173
226
  };
@@ -180,32 +233,9 @@ export const commandRunHarmony: Command = {
180
233
  }
181
234
  );
182
235
 
183
- const deviceOrSimulatorName = await selectDevice(deviceAndSimulatorInfo)
184
-
185
- let currentPort: number = defaultPort;
186
- if (packager) {
187
- const root: string = _config.root || '.';
188
- const reactNativePath: string = _config.reactNativePath || path.dirname(
189
- require.resolve('react-native', { paths: [root] }),
190
- );
191
- const { port: newPort, startPackager } = await findDevServerPort(
192
- defaultPort,
193
- root,
194
- );
195
-
196
- if (newPort !== 8081) {
197
- await trySetMetroPort(harmonyProjectPath.copyWithNewSegment(
198
- 'entry', 'src', 'main', 'ets', 'pages', 'Index.ets').toString(), newPort);
199
- }
200
- if (startPackager) {
201
- startServerInNewWindow(
202
- newPort,
203
- root,
204
- reactNativePath,
205
- getDefaultUserTerminal(),
206
- );
207
- }
208
- currentPort = newPort;
236
+ const deviceOrSimulatorName = await selectDevice(deviceAndSimulatorInfo);
237
+ if (deviceOrSimulatorName.includes(`${LOOPBACK_IP}:`)) {
238
+ simulatorName = deviceOrSimulatorName;
209
239
  }
210
240
 
211
241
  const runJob = async (name: string, job: () => Promise<void>) => {
@@ -235,8 +265,7 @@ export const commandRunHarmony: Command = {
235
265
  .copyWithNewSegment('ohpm', 'bin', 'ohpm.bat');
236
266
  }
237
267
  await cli.run(
238
- process.platform === 'win32' ? `"${ohpmPath.toString()}"` :
239
- ohpmPath.toString(),
268
+ `"${ohpmPath.toString()}"`,
240
269
  {
241
270
  args: [
242
271
  'install',
@@ -265,10 +294,9 @@ export const commandRunHarmony: Command = {
265
294
  nodePath = devEcoStudioToolsPath.copyWithNewSegment('node', 'node');
266
295
  }
267
296
  let hvigorPathRaw = devEcoStudioToolsPath.copyWithNewSegment('hvigor', 'bin', 'hvigorw.js').toString();
268
- const hvigorPath = process.platform === 'win32' ? `"${hvigorPathRaw}"` : hvigorPathRaw;
297
+ const hvigorPath = `"${hvigorPathRaw}"`;
269
298
  await cli.run(
270
- process.platform === 'win32' ? `"${nodePath.toString()}"` :
271
- nodePath.toString(),
299
+ `"${nodePath.toString()}"`,
272
300
  {
273
301
  args: [
274
302
  hvigorPath,
@@ -321,7 +349,7 @@ export const commandRunHarmony: Command = {
321
349
  const hdcPathStrRaw = sdkToolchainsPath
322
350
  .copyWithNewSegment('hdc')
323
351
  .toString();
324
- const hdcPathStr = process.platform === 'win32' ? `"${hdcPathStrRaw.toString()}"` : hdcPathStrRaw;
352
+ const hdcPathStr = `"${hdcPathStrRaw.toString()}"`;
325
353
 
326
354
  const tryRemoveForwardPorting = async () => {
327
355
  let fportInfo: string = '';
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import path from 'path';
9
+ import fs from 'fs-extra';
10
+ import { spawn } from 'child_process';
11
+ import { AbsolutePath, DescriptiveError } from '../core';
12
+ import { Logger } from '../io';
13
+ import { RealCliExecutor } from '../io/CliExecutor';
14
+
15
+ interface LaunchOptions {
16
+ devEcoStudioToolsPath: AbsolutePath;
17
+ sdkToolchainsPath: AbsolutePath;
18
+ cli: RealCliExecutor;
19
+ logger: Logger;
20
+ env: NodeJS.ProcessEnv;
21
+ }
22
+
23
+ const MIN_SUPPORTED_VERSION = [6, 0, 0, 828];
24
+ function compareVersionTuple(a: number[], b: number[]): number {
25
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
26
+ const av = a[i] ?? 0;
27
+ const bv = b[i] ?? 0;
28
+ if (av !== bv) return av - bv;
29
+ }
30
+ return 0;
31
+ }
32
+ function isSupportedVersion(versionDir: string): boolean {
33
+ const m = versionDir.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)/);
34
+ if (!m) return false;
35
+ const current = m.slice(1).map(n => parseInt(n, 10));
36
+ return compareVersionTuple(current, MIN_SUPPORTED_VERSION) >= 0;
37
+ }
38
+
39
+ async function getCreatedSimulators(cli: RealCliExecutor, emulator: string): Promise<string[]> {
40
+ try {
41
+ let simulatorInfos = '';
42
+ await cli.run(`"${emulator}"`, {
43
+ args: ['--list'],
44
+ shell: true,
45
+ onStderr: (msg) => {
46
+ simulatorInfos += msg;
47
+ },
48
+ });
49
+ if (!simulatorInfos || simulatorInfos.trim() === '' ||
50
+ simulatorInfos.trim() === '[Empty]' ||
51
+ simulatorInfos.includes('not ')) {
52
+ return [];
53
+ }
54
+
55
+ return simulatorInfos.split('\n').filter(line => line.trim() !== '');
56
+ } catch (error) {
57
+ throw new DescriptiveError({
58
+ whatHappened: `Failed to get simulator list: ${(error as any)?.message || error}`,
59
+ whatCanUserDo: [
60
+ 'Ensure DevEco Studio is properly installed and configured.',
61
+ 'Check if the emulator path is correct.',
62
+ 'Verify that the emulator has read/write permissions.'
63
+ ],
64
+ extraData: error,
65
+ });
66
+ }
67
+ }
68
+
69
+ async function getDevEcoVersion(devEcoStudioToolsPath: AbsolutePath): Promise<string | null> {
70
+ try {
71
+ let productInfoPath = path.join(devEcoStudioToolsPath.toString(),
72
+ '..',
73
+ 'Resources',
74
+ 'product-info.json');
75
+ if (process.platform === 'win32') {
76
+ productInfoPath = path.join(devEcoStudioToolsPath.toString(),
77
+ '..',
78
+ 'product-info.json');
79
+ }
80
+ const content = await fs.readFile(productInfoPath, 'utf-8');
81
+ const info = JSON.parse(content);
82
+ return info.version || null;
83
+ } catch (error) {
84
+ throw new DescriptiveError({
85
+ whatHappened: `Failed to read DevEco Studio version from product-info.json: ${(error as any)?.message || error}`,
86
+ whatCanUserDo: [
87
+ 'Verify DevEco Studio installation is complete and not corrupted.',
88
+ 'Check if the DevEco Studio tools path is correct.',
89
+ 'Ensure product-info.json file exists and is readable.'
90
+ ],
91
+ extraData: error,
92
+ });
93
+ }
94
+ }
95
+
96
+ function resolveDeviceManagerXml(env: NodeJS.ProcessEnv, devEcoVersion: string): string[] {
97
+ const candidates: string[] = [];
98
+ if (process.platform === 'darwin') {
99
+ const home = env.HOME || '';
100
+ candidates.push(
101
+ path.join(home,
102
+ 'Library',
103
+ 'Application Support',
104
+ 'Huawei',
105
+ `DevEcoStudio${devEcoVersion}`,
106
+ 'options',
107
+ 'deviceManager.xml'),
108
+ );
109
+ } else if (process.platform === 'win32') {
110
+ const appdata = env.APPDATA || '';
111
+ candidates.push(
112
+ path.join(appdata,
113
+ 'Huawei',
114
+ `DevEcoStudio${devEcoVersion}`,
115
+ 'options',
116
+ 'deviceManager.xml'),
117
+ );
118
+ } else {
119
+ throw new DescriptiveError({
120
+ whatHappened: `Unsupported operating system.`,
121
+ whatCanUserDo: ['Please run the RNOH project on Windows or macOS.']
122
+ });
123
+ }
124
+ return candidates;
125
+ }
126
+
127
+ interface DevicePathInfo {
128
+ instancePath?: string;
129
+ imageRoot?: string;
130
+ }
131
+
132
+ function parseDeviceManagerXml(xmlContent: string): DevicePathInfo {
133
+ const info: DevicePathInfo = {};
134
+ const optionRegex = /<option\b[^>]*?>/gi;
135
+ let m: RegExpExecArray | null;
136
+ while ((m = optionRegex.exec(xmlContent))) {
137
+ const tag = m[0];
138
+ const nameMatch = tag.match(/\bname=["']([^"']+)["']/i);
139
+ if (!nameMatch) continue;
140
+ const valueMatch = tag.match(/\bvalue=["']([^"']+)["']/i);
141
+ if (!valueMatch) continue;
142
+ const name = nameMatch[1];
143
+ const value = valueMatch[1];
144
+ if (name === 'imageDeployPath' && !info.imageRoot) {
145
+ info.imageRoot = value;
146
+ } else if (name === 'openharmonyDeployPath' && !info.instancePath) {
147
+ info.instancePath = value;
148
+ }
149
+ if (info.imageRoot && info.instancePath) break;
150
+ }
151
+ return info;
152
+ }
153
+
154
+ function candidateEmulatorExecutables(devEcoStudioToolsPath: AbsolutePath): string[] {
155
+ const list: string[] = [];
156
+ const add = (...segs: string[]) =>
157
+ list.push(devEcoStudioToolsPath.copyWithNewSegment(...segs).toString());
158
+
159
+ if (process.platform === 'win32') {
160
+ add('emulator', 'Emulator.exe');
161
+ } else {
162
+ add('emulator', 'Emulator');
163
+ }
164
+ return list;
165
+ }
166
+
167
+ function pickExisting(paths: string[]): string | undefined {
168
+ return paths.find(p => fs.existsSync(p));
169
+ }
170
+
171
+ async function resolveInstanceAndImageRoot(
172
+ env: NodeJS.ProcessEnv, devEcoVersion: string
173
+ ): Promise<{ instancePath: string; imageRoot: string } | null> {
174
+ const defaultInstanceCandidates: string[] = [];
175
+ const defaultImageCandidates: string[] = [];
176
+
177
+ if (process.platform === 'darwin') {
178
+ const home = env.HOME || '';
179
+ defaultInstanceCandidates.push(
180
+ path.join(home,
181
+ '.Huawei',
182
+ 'Emulator',
183
+ 'deployed'),
184
+ );
185
+ defaultImageCandidates.push(
186
+ path.join(home,
187
+ 'Library',
188
+ 'Huawei',
189
+ 'Sdk'),
190
+ );
191
+ } else if (process.platform === 'win32') {
192
+ const localAppData = env.LOCALAPPDATA || '';
193
+ defaultInstanceCandidates.push(
194
+ path.join(localAppData,
195
+ 'Huawei',
196
+ 'Emulator',
197
+ 'deployed')
198
+ );
199
+ defaultImageCandidates.push(
200
+ path.join(localAppData,
201
+ 'Huawei',
202
+ 'Sdk')
203
+ );
204
+ } else {
205
+ throw new DescriptiveError({
206
+ whatHappened: `Unsupported operating system.`,
207
+ whatCanUserDo: ['Please run the RNOH project on Windows or macOS.']
208
+ });
209
+ }
210
+
211
+ let xmlInfo: DevicePathInfo = {};
212
+ for (const xmlPath of resolveDeviceManagerXml(env, devEcoVersion)) {
213
+ if (fs.existsSync(xmlPath)) {
214
+ try {
215
+ const content = await fs.readFile(xmlPath, 'utf-8');
216
+ xmlInfo = parseDeviceManagerXml(content);
217
+ if (xmlInfo.instancePath || xmlInfo.imageRoot) break;
218
+ } catch (error) {
219
+ throw new DescriptiveError({
220
+ whatHappened: `Failed to read or parse device manager XML at ${xmlPath}: ${(error as any)?.message || error}`,
221
+ whatCanUserDo: [
222
+ 'Verify that the DevEco Studio deviceManager.xml file exists and is readable.',
223
+ 'Check if DEVECO_SDK_HOME environment variable is set correctly.',
224
+ 'Ensure DevEco Studio has been launched at least once to generate configuration files.',
225
+ 'Check file permissions for the DevEco Studio configuration directory.'
226
+ ],
227
+ extraData: error,
228
+ });
229
+ }
230
+ }
231
+ }
232
+
233
+ let resolvedInstance = pickExisting(defaultInstanceCandidates);
234
+ let resolvedImageRoot = pickExisting(defaultImageCandidates);
235
+ if (xmlInfo.imageRoot) {
236
+ resolvedImageRoot = xmlInfo.imageRoot;
237
+ }
238
+ if (xmlInfo.instancePath) {
239
+ resolvedInstance = xmlInfo.instancePath;
240
+ }
241
+ if (!resolvedInstance || !resolvedImageRoot) {
242
+ throw new DescriptiveError({
243
+ whatHappened: `No simulator instance or image root directory detected.`,
244
+ whatCanUserDo: [
245
+ 'Have you already launched the simulator via DevEco Studio?'
246
+ ]
247
+ });
248
+ }
249
+ return { instancePath: resolvedInstance, imageRoot: resolvedImageRoot };
250
+ }
251
+
252
+ export async function launchHarmonySimulator(opt: LaunchOptions): Promise<void> {
253
+ const {
254
+ devEcoStudioToolsPath,
255
+ cli,
256
+ logger,
257
+ } = opt;
258
+
259
+ const devEcoVersion = await getDevEcoVersion(devEcoStudioToolsPath);
260
+ if (!devEcoVersion) {
261
+ throw new DescriptiveError({
262
+ whatHappened: `DevEco Studio version could not be obtained.`,
263
+ whatCanUserDo: [
264
+ 'Verify DevEco Studio is properly installed and the tools path is correct.',
265
+ 'Check if product-info.json file exists in the DevEco Studio installation directory.',
266
+ 'Ensure you have the latest version of DevEco Studio installed.'
267
+ ]
268
+ });
269
+ }
270
+
271
+ if (!isSupportedVersion(devEcoVersion)) {
272
+ throw new DescriptiveError({
273
+ whatHappened: `Current DevEco SDK version (${devEcoVersion}) does not support launching the simulator via command line (requires >= ${MIN_SUPPORTED_VERSION.join('.')}).`,
274
+ whatCanUserDo: [
275
+ `Update DevEco Studio to version ${MIN_SUPPORTED_VERSION.join('.')} or higher.`,
276
+ 'Check the official DevEco Studio website for the latest version.',
277
+ 'Launch the simulator manually from DevEco Studio IDE.'
278
+ ]
279
+ });
280
+ }
281
+
282
+ const versionList = devEcoVersion.split('.');
283
+ const majorVersion = `${versionList[0]}.${versionList[1]}`;
284
+ const paths = await resolveInstanceAndImageRoot(opt.env, majorVersion);
285
+ if (!paths) {
286
+ throw new DescriptiveError({
287
+ whatHappened: `Could not resolve simulator instance path or image root.`,
288
+ whatCanUserDo: [
289
+ 'Open DevEco Studio and launch the simulator at least once to generate configuration files.',
290
+ 'Check if DEVECO_SDK_HOME environment variable is set correctly.',
291
+ 'Verify that the simulator has been properly configured in DevEco Studio.',
292
+ 'Ensure the default simulator paths exist in your system.'
293
+ ]
294
+ });
295
+ }
296
+
297
+ const emulatorExe = pickExisting(candidateEmulatorExecutables(devEcoStudioToolsPath));
298
+ if (!emulatorExe) {
299
+ throw new DescriptiveError({
300
+ whatHappened: `Emulator executable not found in DevEco Studio installation.`,
301
+ whatCanUserDo: [
302
+ 'Verify DevEco Studio installation is complete and not corrupted.',
303
+ 'Check if the emulator component is installed in DevEco Studio.',
304
+ 'Reinstall DevEco Studio if the emulator binary is missing.',
305
+ 'Ensure the DevEco Studio tools path is correctly configured.'
306
+ ]
307
+ });
308
+ }
309
+ const simulatorName = await getCreatedSimulators(cli, emulatorExe);
310
+ if (simulatorName.length <= 0) {
311
+ throw new DescriptiveError({
312
+ whatHappened: `No existing HarmonyOS simulator instance detected.`,
313
+ whatCanUserDo: [
314
+ 'Create a simulator instance in DevEco Studio first.',
315
+ 'Open DevEco Studio Device Manager and create a new virtual device.',
316
+ 'Ensure the simulator instance is properly configured and available.',
317
+ 'Check if the emulator --list command returns any valid instances.'
318
+ ]
319
+ });
320
+ }
321
+
322
+ try {
323
+ const quoteIfNeeded = (p: string) =>
324
+ process.platform === 'win32' ? `"${p}"` : p;
325
+ const args = [
326
+ '-hvd',
327
+ simulatorName[0].trim(),
328
+ '-path',
329
+ quoteIfNeeded(paths.instancePath),
330
+ '-imageRoot',
331
+ quoteIfNeeded(paths.imageRoot),
332
+ ];
333
+ const child = spawn(quoteIfNeeded(emulatorExe), args, {
334
+ cwd: path.dirname(emulatorExe),
335
+ detached: true,
336
+ stdio: 'ignore',
337
+ shell: process.platform === 'win32',
338
+ });
339
+ child.unref();
340
+ logger.info(() => `Launching HarmonyOS simulator in background: ${simulatorName[0]}`);
341
+ } catch (e) {
342
+ throw new DescriptiveError({
343
+ whatHappened: `Failed to start simulator process: ${(e as any)?.message || e}`,
344
+ whatCanUserDo: [
345
+ 'Confirm that the DevEco Simulator can be started manually from DevEco Studio.',
346
+ 'Ensure no stale simulator process is blocking required ports.',
347
+ 'Reinstall or repair DevEco Studio if the simulator binary is corrupted.'
348
+ ],
349
+ extraData: e,
350
+ });
351
+ }
352
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ export * from './LaunchSimulator';