@ohos-ports/open 0.0.0-stage → 6.4.0-beta.0

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.
package/index.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ /// <reference types="node"/>
2
+ import {ChildProcess} from 'child_process';
3
+
4
+ declare namespace open {
5
+ interface Options {
6
+ /**
7
+ Wait for the opened app to exit before fulfilling the promise. If `false` it's fulfilled immediately when opening the app.
8
+
9
+ Note that it waits for the app to exit, not just for the window to close.
10
+
11
+ On Windows, you have to explicitly specify an app for it to be able to wait.
12
+
13
+ @default false
14
+ */
15
+ readonly wait?: boolean;
16
+
17
+ /**
18
+ __macOS only__
19
+
20
+ Do not bring the app to the foreground.
21
+
22
+ @default false
23
+ */
24
+ readonly background?: boolean;
25
+
26
+ /**
27
+ Specify the app to open the `target` with, or an array with the app and app arguments.
28
+
29
+ The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is `google chrome` on macOS, `google-chrome` on Linux and `chrome` on Windows.
30
+
31
+ You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome.
32
+ */
33
+ readonly app?: string | readonly string[];
34
+ }
35
+ }
36
+
37
+ /**
38
+ Open stuff like URLs, files, executables. Cross-platform.
39
+
40
+ Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms.
41
+
42
+ @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. For example, URLs open in your default browser.
43
+ @returns The [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process.
44
+
45
+ @example
46
+ ```
47
+ import open = require('open');
48
+
49
+ // Opens the image in the default image viewer
50
+ (async () => {
51
+ await open('unicorn.png', {wait: true});
52
+ console.log('The image viewer app closed');
53
+
54
+ // Opens the url in the default browser
55
+ await open('https://sindresorhus.com');
56
+
57
+ // Specify the app to open in
58
+ await open('https://sindresorhus.com', {app: 'firefox'});
59
+
60
+ // Specify app arguments
61
+ await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
62
+ })();
63
+ ```
64
+ */
65
+ declare function open(
66
+ target: string,
67
+ options?: open.Options
68
+ ): Promise<ChildProcess>;
69
+
70
+ export = open;
package/index.js ADDED
@@ -0,0 +1,283 @@
1
+ 'use strict';
2
+ const {promisify} = require('util');
3
+ const path = require('path');
4
+ const childProcess = require('child_process');
5
+ const http = require('http');
6
+ const fs = require('fs');
7
+ const isWsl = require('is-wsl');
8
+
9
+ const pAccess = promisify(fs.access);
10
+ const pExecFile = promisify(childProcess.execFile);
11
+
12
+ // Path to included `xdg-open`
13
+ const localXdgOpenPath = path.join(__dirname, 'xdg-open');
14
+
15
+ // Convert a path from WSL format to Windows format:
16
+ // `/mnt/c/Program Files/Example/MyApp.exe` → `C:\Program Files\Example\MyApp.exe`
17
+ const wslToWindowsPath = async path => {
18
+ const {stdout} = await pExecFile('wslpath', ['-w', path]);
19
+ return stdout.trim();
20
+ };
21
+
22
+ // --- openharmony: system browser (Haitai/ArkWeb) via Chrome DevTools Protocol ---
23
+
24
+ const getOpenHarmonyCdpEndpoint = () => (
25
+ process.env.OPEN_OHOS_CDP_ENDPOINT ||
26
+ process.env.OHOS_BROWSER_CDP ||
27
+ '127.0.0.1:9222'
28
+ );
29
+
30
+ // Minimal CDP HTTP request using the Node built-in `http` module (no new dependencies).
31
+ const cdpHttpRequest = (method, requestPath) => new Promise((resolve, reject) => {
32
+ const url = new URL(`http://${getOpenHarmonyCdpEndpoint()}${requestPath}`);
33
+ const request = http.request(url, {method, timeout: 5000}, response => {
34
+ const {statusCode} = response;
35
+ let data = '';
36
+ response.setEncoding('utf8');
37
+ response.on('data', chunk => {
38
+ data += chunk;
39
+ });
40
+ response.on('end', () => {
41
+ if (statusCode < 200 || statusCode >= 300) {
42
+ reject(new Error(`CDP ${method} ${requestPath} failed with status code ${statusCode}`));
43
+ return;
44
+ }
45
+
46
+ resolve(data);
47
+ });
48
+ });
49
+ request.on('timeout', () => {
50
+ request.destroy();
51
+ reject(new Error(`CDP ${method} ${requestPath} timed out`));
52
+ });
53
+ request.on('error', reject);
54
+ request.end();
55
+ });
56
+
57
+ // Navigate a CDP page target to `target` over its DevTools WebSocket,
58
+ // using the global `WebSocket` client (Node.js >= 22).
59
+ const cdpNavigate = (webSocketDebuggerUrl, target) => new Promise((resolve, reject) => {
60
+ if (typeof WebSocket === 'undefined') {
61
+ reject(new Error('open: the global WebSocket client (Node.js >= 22) is required for CDP navigation on openharmony'));
62
+ return;
63
+ }
64
+
65
+ let settled = false;
66
+ const socket = new WebSocket(webSocketDebuggerUrl);
67
+ const finish = (error, result) => {
68
+ if (settled) {
69
+ return;
70
+ }
71
+
72
+ settled = true;
73
+ try {
74
+ socket.close();
75
+ } catch {}
76
+
77
+ if (error) {
78
+ reject(error);
79
+ } else {
80
+ resolve(result);
81
+ }
82
+ };
83
+
84
+ socket.addEventListener('open', () => {
85
+ socket.send(JSON.stringify({
86
+ id: 1,
87
+ method: 'Page.navigate',
88
+ params: {url: target}
89
+ }));
90
+ });
91
+ socket.addEventListener('message', event => {
92
+ const message = JSON.parse(event.data);
93
+ if (message.id !== 1) {
94
+ return;
95
+ }
96
+
97
+ if (message.error) {
98
+ finish(new Error(`CDP Page.navigate failed: ${message.error.message}`));
99
+ return;
100
+ }
101
+
102
+ if (message.result && message.result.errorText) {
103
+ // The page-level navigation failed (e.g. net::ERR_CONNECTION_REFUSED),
104
+ // but the browser tab was created and the browser itself is alive —
105
+ // mirror the upstream semantics where the spawned browser process
106
+ // keeps running even when the page cannot load.
107
+ finish(undefined, message.result);
108
+ return;
109
+ }
110
+
111
+ finish(undefined, message.result);
112
+ });
113
+ socket.addEventListener('error', () => {
114
+ finish(new Error('open: CDP WebSocket connection failed'));
115
+ });
116
+ socket.addEventListener('close', () => {
117
+ finish(new Error('open: CDP WebSocket connection closed before navigation completed'));
118
+ });
119
+ });
120
+
121
+ const openHarmonyCdp = async target => {
122
+ const endpoint = getOpenHarmonyCdpEndpoint();
123
+
124
+ let targetInfo;
125
+ try {
126
+ // Some HarmonyOS browsers do not honour the `url` parameter of
127
+ // `PUT /json/new` (the created target stays `about:blank`), so fall
128
+ // back to `Page.navigate` over the DevTools WebSocket when needed.
129
+ const body = await cdpHttpRequest('PUT', `/json/new?url=${encodeURIComponent(target)}`);
130
+ targetInfo = JSON.parse(body);
131
+ } catch (error) {
132
+ throw new Error(`open: cannot reach the HarmonyOS browser CDP endpoint http://${endpoint} (${error.message}). Ensure the browser is running with remote debugging enabled, or set OPEN_OHOS_CDP_ENDPOINT / OHOS_BROWSER_CDP.`);
133
+ }
134
+
135
+ if (
136
+ targetInfo &&
137
+ targetInfo.type === 'page' &&
138
+ targetInfo.url &&
139
+ targetInfo.url !== 'about:blank'
140
+ ) {
141
+ // The browser honoured the `url` parameter; the page is opening.
142
+ return targetInfo;
143
+ }
144
+
145
+ if (!targetInfo || !targetInfo.webSocketDebuggerUrl) {
146
+ throw new Error(`open: HarmonyOS browser CDP endpoint http://${endpoint} did not return a debuggable page target`);
147
+ }
148
+
149
+ await cdpNavigate(targetInfo.webSocketDebuggerUrl, target);
150
+ return targetInfo;
151
+ };
152
+
153
+ module.exports = async (target, options) => {
154
+ if (typeof target !== 'string') {
155
+ throw new TypeError('Expected a `target`');
156
+ }
157
+
158
+ options = {
159
+ wait: false,
160
+ background: false,
161
+ ...options
162
+ };
163
+
164
+ let command;
165
+ let appArguments = [];
166
+ const cliArguments = [];
167
+ const childProcessOptions = {};
168
+
169
+ if (Array.isArray(options.app)) {
170
+ appArguments = options.app.slice(1);
171
+ options.app = options.app[0];
172
+ }
173
+
174
+ if (process.platform === 'openharmony') {
175
+ // HarmonyOS: open the target in the system browser (Haitai/ArkWeb)
176
+ // through the Chrome DevTools Protocol. The CDP endpoint can be
177
+ // overridden via the `OPEN_OHOS_CDP_ENDPOINT` or `OHOS_BROWSER_CDP`
178
+ // environment variables (default: 127.0.0.1:9222).
179
+ //
180
+ // The `app` option is ignored: the CDP-driven system browser is the
181
+ // only supported target. The `wait` option has no child process to
182
+ // wait for; the returned promise resolves once the navigation
183
+ // started successfully.
184
+ if (typeof target !== 'string' || target.length === 0) {
185
+ throw new Error('open: opening an application without a URL target is not supported on openharmony (use the CDP-driven system browser instead)');
186
+ }
187
+
188
+ return openHarmonyCdp(target);
189
+ }
190
+
191
+ if (process.platform === 'darwin') {
192
+ command = 'open';
193
+
194
+ if (options.wait) {
195
+ cliArguments.push('--wait-apps');
196
+ }
197
+
198
+ if (options.background) {
199
+ cliArguments.push('--background');
200
+ }
201
+
202
+ if (options.app) {
203
+ cliArguments.push('-a', options.app);
204
+ }
205
+ } else if (process.platform === 'win32' || isWsl) {
206
+ command = 'cmd' + (isWsl ? '.exe' : '');
207
+ cliArguments.push('/c', 'start', '""', '/b');
208
+ target = target.replace(/&/g, '^&');
209
+
210
+ if (options.wait) {
211
+ cliArguments.push('/wait');
212
+ }
213
+
214
+ if (options.app) {
215
+ if (isWsl && options.app.startsWith('/mnt/')) {
216
+ const windowsPath = await wslToWindowsPath(options.app);
217
+ options.app = windowsPath;
218
+ }
219
+
220
+ cliArguments.push(options.app);
221
+ }
222
+
223
+ if (appArguments.length > 0) {
224
+ cliArguments.push(...appArguments);
225
+ }
226
+ } else {
227
+ if (options.app) {
228
+ command = options.app;
229
+ } else {
230
+ // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
231
+ const isBundled = !__dirname || __dirname === '/';
232
+
233
+ // Check if local `xdg-open` exists and is executable.
234
+ let exeLocalXdgOpen = false;
235
+ try {
236
+ await pAccess(localXdgOpenPath, fs.constants.X_OK);
237
+ exeLocalXdgOpen = true;
238
+ } catch (error) {}
239
+
240
+ const useSystemXdgOpen = process.versions.electron ||
241
+ process.platform === 'android' || isBundled || !exeLocalXdgOpen;
242
+ command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
243
+ }
244
+
245
+ if (appArguments.length > 0) {
246
+ cliArguments.push(...appArguments);
247
+ }
248
+
249
+ if (!options.wait) {
250
+ // `xdg-open` will block the process unless stdio is ignored
251
+ // and it's detached from the parent even if it's unref'd.
252
+ childProcessOptions.stdio = 'ignore';
253
+ childProcessOptions.detached = true;
254
+ }
255
+ }
256
+
257
+ cliArguments.push(target);
258
+
259
+ if (process.platform === 'darwin' && appArguments.length > 0) {
260
+ cliArguments.push('--args', ...appArguments);
261
+ }
262
+
263
+ const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
264
+
265
+ if (options.wait) {
266
+ return new Promise((resolve, reject) => {
267
+ subprocess.once('error', reject);
268
+
269
+ subprocess.once('close', exitCode => {
270
+ if (exitCode > 0) {
271
+ reject(new Error(`Exited with code ${exitCode}`));
272
+ return;
273
+ }
274
+
275
+ resolve(subprocess);
276
+ });
277
+ });
278
+ }
279
+
280
+ subprocess.unref();
281
+
282
+ return subprocess;
283
+ };
package/license ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
- "name": "@ohos-ports/open",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@ohos-ports/open",
3
+ "version": "6.4.0-beta.0",
4
+ "description": "Open stuff like URLs, files, executables. Cross-platform. OpenHarmony port: opens URLs in the system browser (Haitai/ArkWeb) via CDP.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/ohos-ports/ohos-ports.git",
9
+ "directory": "ports/open/6.4.0"
10
+ },
11
+ "author": {
12
+ "name": "Sindre Sorhus",
13
+ "email": "sindresorhus@gmail.com",
14
+ "url": "sindresorhus.com"
15
+ },
16
+ "engines": {
17
+ "node": ">=8"
18
+ },
19
+ "scripts": {
20
+ "test": "xo && tsd"
21
+ },
22
+ "files": [
23
+ "index.js",
24
+ "index.d.ts",
25
+ "xdg-open"
26
+ ],
27
+ "keywords": [
28
+ "app",
29
+ "open",
30
+ "opener",
31
+ "opens",
32
+ "launch",
33
+ "start",
34
+ "xdg-open",
35
+ "xdg",
36
+ "default",
37
+ "cmd",
38
+ "browser",
39
+ "editor",
40
+ "executable",
41
+ "exe",
42
+ "url",
43
+ "urls",
44
+ "arguments",
45
+ "args",
46
+ "spawn",
47
+ "exec",
48
+ "child",
49
+ "process",
50
+ "website",
51
+ "file",
52
+ "openharmony",
53
+ "ohos",
54
+ "harmonyos"
55
+ ],
56
+ "dependencies": {
57
+ "is-wsl": "^1.1.0"
58
+ },
59
+ "devDependencies": {
60
+ "@types/node": "^11.13.6",
61
+ "ava": "^1.4.0",
62
+ "tsd": "^0.7.2",
63
+ "xo": "^0.24.0"
64
+ }
65
+ }
package/readme.md ADDED
@@ -0,0 +1,113 @@
1
+ # open
2
+
3
+ > Open stuff like URLs, files, executables. Cross-platform.
4
+
5
+ If need this for Electron, use [`shell.openItem()`](https://electronjs.org/docs/api/shell#shellopenitemfullpath) instead.
6
+
7
+ Note: The original [`open` package](https://github.com/pwnall/node-open) was recently deprecated in favor of this package, and we got the name, so this package is now named `open` instead of `opn`. If you're upgrading from the original `open` package (`open@0.0.5` or lower), keep in mind that the API is different.
8
+
9
+ #### Why?
10
+
11
+ - Actively maintained.
12
+ - Supports app arguments.
13
+ - Safer as it uses `spawn` instead of `exec`.
14
+ - Fixes most of the open original `node-open` issues.
15
+ - Includes the latest [`xdg-open` script](http://cgit.freedesktop.org/xdg/xdg-utils/commit/?id=c55122295c2a480fa721a9614f0e2d42b2949c18) for Linux.
16
+ - Supports WSL paths to Windows apps under `/mnt/*`.
17
+
18
+
19
+ ## Install
20
+
21
+ ```
22
+ $ npm install open
23
+ ```
24
+
25
+
26
+ ## Usage
27
+
28
+ ```js
29
+ const open = require('open');
30
+
31
+ (async () => {
32
+ // Opens the image in the default image viewer and waits for the opened app to quit
33
+ await open('unicorn.png', {wait: true});
34
+ console.log('The image viewer app quit');
35
+
36
+ // Opens the URL in the default browser
37
+ await open('https://sindresorhus.com');
38
+
39
+ // Opens the URL in a specified browser
40
+ await open('https://sindresorhus.com', {app: 'firefox'});
41
+
42
+ // Specify app arguments
43
+ await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
44
+ })();
45
+ ```
46
+
47
+
48
+ ## API
49
+
50
+ It uses the command `open` on macOS, `start` on Windows and `xdg-open` on other platforms.
51
+
52
+ ### open(target, options?)
53
+
54
+ Returns a promise for the [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process.
55
+
56
+ #### target
57
+
58
+ Type: `string`
59
+
60
+ The thing you want to open. Can be a URL, file, or executable.
61
+
62
+ Opens in the default app for the file type. For example, URLs opens in your default browser.
63
+
64
+ #### options
65
+
66
+ Type: `object`
67
+
68
+ ##### wait
69
+
70
+ Type: `boolean`<br>
71
+ Default: `false`
72
+
73
+ Wait for the opened app to exit before fulfilling the promise. If `false` it's fulfilled immediately when opening the app.
74
+
75
+ Note that it waits for the app to exit, not just for the window to close.
76
+
77
+ On Windows, you have to explicitly specify an app for it to be able to wait.
78
+
79
+ ##### background <sup>(macOS only)</sup>
80
+
81
+ Type: `boolean`<br>
82
+ Default: `false`
83
+
84
+ Do not bring the app to the foreground.
85
+
86
+ ##### app
87
+
88
+ Type: `string | string[]`
89
+
90
+ Specify the app to open the `target` with, or an array with the app and app arguments.
91
+
92
+ The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is `google chrome` on macOS, `google-chrome` on Linux and `chrome` on Windows.
93
+
94
+ You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome.
95
+
96
+
97
+ ## Related
98
+
99
+ - [open-cli](https://github.com/sindresorhus/open-cli) - CLI for this module
100
+ - [open-editor](https://github.com/sindresorhus/open-editor) - Open files in your editor at a specific line and column
101
+
102
+
103
+ ---
104
+
105
+ <div align="center">
106
+ <b>
107
+ <a href="https://tidelift.com/subscription/pkg/npm-opn?utm_source=npm-opn&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
108
+ </b>
109
+ <br>
110
+ <sub>
111
+ Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
112
+ </sub>
113
+ </div>