@octane-xplat/devtools 0.0.0-nightly.g1b95ef7

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 (64) hide show
  1. package/README.md +5 -0
  2. package/dist/app.d.ts +28 -0
  3. package/dist/app.js +66 -0
  4. package/dist/backend.d.ts +31 -0
  5. package/dist/backend.js +182 -0
  6. package/dist/client.d.ts +49 -0
  7. package/dist/client.js +168 -0
  8. package/dist/host/desktop.d.ts +15 -0
  9. package/dist/host/desktop.js +133 -0
  10. package/dist/host/panels.d.ts +14 -0
  11. package/dist/host/panels.js +156 -0
  12. package/dist/host/records.d.ts +5 -0
  13. package/dist/host/records.js +46 -0
  14. package/dist/host/server.d.ts +8 -0
  15. package/dist/host/server.js +67 -0
  16. package/dist/host/web.d.ts +5 -0
  17. package/dist/host/web.js +74 -0
  18. package/dist/macos/index.macos.d.ts +3 -0
  19. package/dist/macos/index.macos.js +5 -0
  20. package/dist/macos/servers.macos.d.ts +4 -0
  21. package/dist/macos/servers.macos.js +57 -0
  22. package/dist/macos/socket.macos.d.ts +2 -0
  23. package/dist/macos/socket.macos.js +152 -0
  24. package/dist/macos/ws-frames.d.ts +24 -0
  25. package/dist/macos/ws-frames.js +205 -0
  26. package/dist/node.d.ts +12 -0
  27. package/dist/node.js +51 -0
  28. package/dist/record.d.ts +9 -0
  29. package/dist/record.js +38 -0
  30. package/dist/types.d.ts +128 -0
  31. package/dist/types.js +25 -0
  32. package/package.json +88 -0
  33. package/src/app.ts +105 -0
  34. package/src/assets.d.ts +2 -0
  35. package/src/backend.ts +278 -0
  36. package/src/client.ts +248 -0
  37. package/src/desktop/Shell.macos.tsrx +158 -0
  38. package/src/desktop/Shell.ts +16 -0
  39. package/src/desktop/index.macos.ts +7 -0
  40. package/src/desktop/main.macos.ts +130 -0
  41. package/src/desktop/panels.d.ts +10 -0
  42. package/src/desktop/target.ts +34 -0
  43. package/src/host/desktop.ts +176 -0
  44. package/src/host/panels.ts +193 -0
  45. package/src/host/records.ts +62 -0
  46. package/src/host/server.ts +92 -0
  47. package/src/host/web.ts +68 -0
  48. package/src/macos/index.macos.ts +7 -0
  49. package/src/macos/servers.macos.ts +83 -0
  50. package/src/macos/socket.macos.ts +218 -0
  51. package/src/macos/ws-frames.ts +249 -0
  52. package/src/node.ts +60 -0
  53. package/src/panel/App.tsrx +288 -0
  54. package/src/panel/index.html +12 -0
  55. package/src/panel/index.ts +24 -0
  56. package/src/panel/main.tsrx +2 -0
  57. package/src/panel/main.web.tsrx +89 -0
  58. package/src/panel/model.ts +216 -0
  59. package/src/panel/panel.css +189 -0
  60. package/src/panel/plugin.ts +65 -0
  61. package/src/panel/styles.ts +5 -0
  62. package/src/panel/tsconfig.browser.json +9 -0
  63. package/src/record.ts +66 -0
  64. package/src/types.ts +129 -0
@@ -0,0 +1,14 @@
1
+ import type { Plugin } from 'vite';
2
+ export interface DiscoveredDevtoolsPanel {
3
+ /** The declaring package name. */
4
+ name: string;
5
+ /** Realpath'd entry file the virtual module default-imports. */
6
+ file: string;
7
+ }
8
+ export declare function discoverDevtoolsPanels(projectRoot: string): DiscoveredDevtoolsPanel[];
9
+ export declare const DEVTOOLS_PANELS_VIRTUAL_ID = "virtual:octane-devtools-panels";
10
+ /** Vite plugin serving `virtual:octane-devtools-panels`: a default-exported
11
+ * array of the discovered panel plugins (`[]` when none). */
12
+ export declare function devtoolsPanels(options: {
13
+ root: string;
14
+ }): Plugin;
@@ -0,0 +1,156 @@
1
+ // Panel-plugin discovery for the project DevTools bundles: a package opts in
2
+ // with `"octaneXplat": { "devtoolsPanel": "./devtools" }` in its package.json
3
+ // (a subpath or an array of subpaths; each module must
4
+ // default-export a DevtoolsPanelPlugin). `devtoolsPanels` serves the
5
+ // discovered modules as `virtual:octane-devtools-panels` to the web and desktop
6
+ // shells.
7
+ //
8
+ // Scan scope is one level: the selected project's dependencies +
9
+ // devDependencies, plus octane-xplat's own dependencies when the umbrella is
10
+ // installed (resolved from the umbrella's location, so Bun's isolated install
11
+ // layout keeps transitive panel packages reachable). Candidates are resolved
12
+ // through createRequire from the declaring package and must realpath inside
13
+ // the plugin package's root — nothing outside a package's own files may be
14
+ // bundled. Malformed or unresolvable candidates are skipped with one stderr
15
+ // warning each; a package without the field is simply not a candidate.
16
+ import { createRequire } from 'node:module';
17
+ import { lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
18
+ import { dirname, join, sep } from 'node:path';
19
+ const FIELD = 'devtoolsPanel';
20
+ function readManifest(file) {
21
+ try {
22
+ return JSON.parse(readFileSync(file, 'utf8'));
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /** Locate a dependency's package.json: its exports map first, then a physical
29
+ * node_modules walk for packages that do not export ./package.json. */
30
+ function locatePackage(name, requireFrom, fromDir) {
31
+ try {
32
+ return requireFrom.resolve(`${name}/package.json`);
33
+ }
34
+ catch {
35
+ // Fall through to the physical walk — a package without ./package.json in
36
+ // its exports map still carries the file on disk.
37
+ }
38
+ for (let at = fromDir;; at = dirname(at)) {
39
+ const candidate = join(at, 'node_modules', name, 'package.json');
40
+ try {
41
+ if (lstatSync(candidate).isFile()) {
42
+ return candidate;
43
+ }
44
+ }
45
+ catch {
46
+ // keep walking
47
+ }
48
+ if (dirname(at) === at) {
49
+ return null;
50
+ }
51
+ }
52
+ }
53
+ function warn(message) {
54
+ console.error(`[devtools] ${message}`);
55
+ }
56
+ export function discoverDevtoolsPanels(projectRoot) {
57
+ const projectManifest = readManifest(join(projectRoot, 'package.json')) ?? {};
58
+ const names = new Set([
59
+ ...Object.keys(projectManifest.dependencies ?? {}),
60
+ ...Object.keys(projectManifest.devDependencies ?? {}),
61
+ ]);
62
+ // Scan sources in stable order: project deps (alphabetical), then the
63
+ // umbrella's dependencies (alphabetical, deduped against project names).
64
+ const sources = [
65
+ { dir: projectRoot, names: [...names].sort() },
66
+ ];
67
+ if (names.has('octane-xplat')) {
68
+ try {
69
+ const requireFrom = createRequire(join(projectRoot, 'package.json'));
70
+ const umbrellaDir = dirname(requireFrom.resolve('octane-xplat/package.json'));
71
+ const umbrella = readManifest(join(umbrellaDir, 'package.json')) ?? {};
72
+ const extra = Object.keys(umbrella.dependencies ?? {})
73
+ .filter((name) => !names.has(name))
74
+ .sort();
75
+ if (extra.length) {
76
+ sources.push({ dir: umbrellaDir, names: extra });
77
+ }
78
+ }
79
+ catch (error) {
80
+ warn(`skipping octane-xplat dependency scan — ${String(error)}`);
81
+ }
82
+ }
83
+ const out = [];
84
+ for (const source of sources) {
85
+ const requireFrom = createRequire(join(source.dir, 'package.json'));
86
+ for (const name of source.names) {
87
+ const manifestPath = locatePackage(name, requireFrom, source.dir);
88
+ if (!manifestPath) {
89
+ continue;
90
+ }
91
+ let packageRoot;
92
+ let manifest;
93
+ try {
94
+ packageRoot = realpathSync(dirname(manifestPath));
95
+ manifest = readManifest(join(packageRoot, 'package.json'));
96
+ }
97
+ catch {
98
+ continue;
99
+ }
100
+ const field = manifest?.octaneXplat?.[FIELD];
101
+ if (field === undefined) {
102
+ continue;
103
+ }
104
+ const fail = (why) => warn(`skipping devtools panel candidate "${name}" — ${why}`);
105
+ const subpaths = Array.isArray(field) ? field : [field];
106
+ for (const subpath of subpaths) {
107
+ if (typeof subpath !== 'string' || !subpath.startsWith('./') || subpath.includes('..')) {
108
+ fail(`octaneXplat.${FIELD} must be an export subpath like "./devtools" or an array of subpaths`);
109
+ continue;
110
+ }
111
+ let file;
112
+ try {
113
+ file = realpathSync(requireFrom.resolve(`${name}/${subpath.slice(2)}`));
114
+ }
115
+ catch (error) {
116
+ fail(`cannot resolve ${name}/${subpath.slice(2)} — ${String(error)}`);
117
+ continue;
118
+ }
119
+ try {
120
+ if (!file.startsWith(packageRoot + sep) || !statSync(file).isFile()) {
121
+ fail(`resolved panel module escapes its package root — ${file}`);
122
+ continue;
123
+ }
124
+ }
125
+ catch {
126
+ fail(`resolved panel module is not a file — ${file}`);
127
+ continue;
128
+ }
129
+ out.push({ name, file });
130
+ }
131
+ }
132
+ }
133
+ return out;
134
+ }
135
+ export const DEVTOOLS_PANELS_VIRTUAL_ID = 'virtual:octane-devtools-panels';
136
+ const RESOLVED_ID = '\0' + DEVTOOLS_PANELS_VIRTUAL_ID;
137
+ /** Vite plugin serving `virtual:octane-devtools-panels`: a default-exported
138
+ * array of the discovered panel plugins (`[]` when none). */
139
+ export function devtoolsPanels(options) {
140
+ return {
141
+ name: 'octane-devtools-panels',
142
+ resolveId(id) {
143
+ return id === DEVTOOLS_PANELS_VIRTUAL_ID ? RESOLVED_ID : null;
144
+ },
145
+ load(id) {
146
+ if (id !== RESOLVED_ID) {
147
+ return null;
148
+ }
149
+ const panels = discoverDevtoolsPanels(options.root);
150
+ const imports = panels
151
+ .map((panel, i) => `import p${i} from ${JSON.stringify(panel.file)}`)
152
+ .join('\n');
153
+ return `${imports}\nexport default [${panels.map((_, i) => `p${i}`).join(', ')}]`;
154
+ },
155
+ };
156
+ }
@@ -0,0 +1,5 @@
1
+ import { type ListedDevtoolsServer } from '../record.ts';
2
+ export type { ListedDevtoolsServer } from '../record.ts';
3
+ export declare function devServerRecordsDir(): string;
4
+ /** Returns every structurally valid live record, newest first. */
5
+ export declare function listDevtoolsServers(): ListedDevtoolsServer[];
@@ -0,0 +1,46 @@
1
+ // Enumerates live `xplat dev` server discovery records for the panel picker.
2
+ // Mirrors dev_server_record.go: records live under the native history cache in
3
+ // dev-servers-v1/<app-key>/server.json, one per app, each carrying the panel's
4
+ // devtoolsToken. The RPC token is never returned to the panel.
5
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
6
+ import { homedir, platform } from 'node:os';
7
+ import { isAbsolute, join } from 'node:path';
8
+ import { parseDevtoolsServerRecord } from '../record.js';
9
+ function cacheRoot() {
10
+ if (platform() === 'darwin') {
11
+ return join(homedir(), 'Library', 'Caches');
12
+ }
13
+ if (process.platform === 'win32') {
14
+ return process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local');
15
+ }
16
+ return process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache');
17
+ }
18
+ export function devServerRecordsDir() {
19
+ return (process.env.XPLAT_DEV_RECORDS_DIR ??
20
+ join(cacheRoot(), 'octane-xplat', 'cli-go', 'dev-servers-v1'));
21
+ }
22
+ /** Returns every structurally valid live record, newest first. */
23
+ export function listDevtoolsServers() {
24
+ const root = devServerRecordsDir();
25
+ const found = [];
26
+ if (!existsSync(root)) {
27
+ return [];
28
+ }
29
+ for (const key of readdirSync(root)) {
30
+ const file = join(root, key, 'server.json');
31
+ try {
32
+ const info = statSync(file);
33
+ if (!info.isFile()) {
34
+ continue;
35
+ }
36
+ const server = parseDevtoolsServerRecord(key, readFileSync(file, 'utf8'), isAbsolute);
37
+ if (server) {
38
+ found.push({ server, written: info.mtimeMs });
39
+ }
40
+ }
41
+ catch {
42
+ continue;
43
+ }
44
+ }
45
+ return found.sort((a, b) => b.written - a.written).map(({ server }) => server);
46
+ }
@@ -0,0 +1,8 @@
1
+ export interface DevtoolsHost {
2
+ /** http://127.0.0.1:<port> the panel is served on. */
3
+ endpoint: string;
4
+ close(): Promise<void>;
5
+ }
6
+ export declare function serveDevtools({ port }?: {
7
+ port?: number;
8
+ }): Promise<DevtoolsHost>;
@@ -0,0 +1,67 @@
1
+ // Loopback HTTP host for the devtools panel: serves the built panel bundle
2
+ // (dist/panel) and the live dev-server records the picker lists. Loopback only
3
+ // and no CORS headers — records carry the panel credential, so the API stays
4
+ // unreadable to other origins while remaining trivially usable by the served
5
+ // page.
6
+ import { createServer } from 'node:http';
7
+ import { readFileSync, realpathSync } from 'node:fs';
8
+ import { dirname, extname, join, normalize, sep } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { listDevtoolsServers } from './records.js';
11
+ const TYPES = {
12
+ '.html': 'text/html; charset=utf-8',
13
+ '.js': 'text/javascript; charset=utf-8',
14
+ '.css': 'text/css; charset=utf-8',
15
+ '.json': 'application/json; charset=utf-8',
16
+ '.svg': 'image/svg+xml',
17
+ '.png': 'image/png',
18
+ '.woff2': 'font/woff2',
19
+ };
20
+ function packageRoot() {
21
+ // host/ sits under src/ (source runs) or dist/ (published runs).
22
+ return dirname(dirname(dirname(fileURLToPath(import.meta.url))));
23
+ }
24
+ export async function serveDevtools({ port = 0 } = {}) {
25
+ const root = realpathSync(packageRoot());
26
+ const panel = join(root, 'dist', 'panel');
27
+ const server = createServer((req, res) => {
28
+ const send = (status, body, type = 'application/json; charset=utf-8') => {
29
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' });
30
+ res.end(body);
31
+ };
32
+ if (req.method !== 'GET') {
33
+ return send(405, '{"error":"method not allowed"}');
34
+ }
35
+ const path = normalize(new URL(req.url ?? '/', 'http://127.0.0.1').pathname);
36
+ if (path === '/devtools/servers') {
37
+ return send(200, JSON.stringify({ servers: listDevtoolsServers() }));
38
+ }
39
+ // '/' and '/app/...' map to the built panel bundle — strict containment,
40
+ // no traversal out of dist/panel.
41
+ const file = path === '/' || path === '/app'
42
+ ? join(panel, 'index.html')
43
+ : path.startsWith('/app/')
44
+ ? join(panel, path.slice('/app'.length))
45
+ : null;
46
+ if (!file || (path.startsWith('/app/') && !file.startsWith(panel + sep))) {
47
+ return send(404, '{"error":"not found"}');
48
+ }
49
+ try {
50
+ send(200, readFileSync(file), TYPES[extname(file)] ?? 'application/octet-stream');
51
+ }
52
+ catch {
53
+ send(404, '{"error":"not found"}');
54
+ }
55
+ });
56
+ await new Promise((resolve, reject) => {
57
+ server.once('error', reject);
58
+ server.listen(port, '127.0.0.1', () => resolve());
59
+ });
60
+ const address = server.address();
61
+ return {
62
+ endpoint: `http://127.0.0.1:${typeof address === 'object' && address ? address.port : port}`,
63
+ close: () => new Promise((resolve, reject) => {
64
+ server.close((error) => (error ? reject(error) : resolve()));
65
+ }),
66
+ };
67
+ }
@@ -0,0 +1,5 @@
1
+ import type { InlineConfig } from 'vite';
2
+ /** The toolchain comes from the selected app. The bundled shell and its TS
3
+ * configuration come from this installed DevTools package. */
4
+ export declare function devtoolsWebConfig(toolsRoot: string, outDir: string, mode: string, project?: string | null): Promise<InlineConfig>;
5
+ export declare function buildDevtoolsWeb(project: string, outDir: string): Promise<void>;
@@ -0,0 +1,74 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx, extraExtensions, ignoreCase) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ if (extraExtensions) {
4
+ for (var extension in extraExtensions) {
5
+ var suffix = path.slice(-extension.length);
6
+ if (suffix === extension || ignoreCase && suffix.toLowerCase() === extension.toLowerCase()) {
7
+ var output = extraExtensions[extension];
8
+ return output === extension ? path : path.slice(0, -extension.length) + output;
9
+ }
10
+ }
11
+ }
12
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
13
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
14
+ });
15
+ }
16
+ return path;
17
+ };
18
+ import { createRequire } from 'node:module';
19
+ import { join } from 'node:path';
20
+ import { fileURLToPath, pathToFileURL } from 'node:url';
21
+ import { devtoolsPanels } from './panels.js';
22
+ const packageRoot = fileURLToPath(new URL('../../', import.meta.url));
23
+ /** The toolchain comes from the selected app. The bundled shell and its TS
24
+ * configuration come from this installed DevTools package. */
25
+ export async function devtoolsWebConfig(toolsRoot, outDir, mode, project = null) {
26
+ const require = createRequire(join(toolsRoot, 'package.json'));
27
+ const load = (name) => import(__rewriteRelativeImportExtension(pathToFileURL(require.resolve(name)).href, true));
28
+ const [{ octane }, { css, boundary, nodeEnvDefine }] = await Promise.all([
29
+ load('@octanejs/vite-plugin'),
30
+ load('@octane-xplat/cli/vite'),
31
+ ]);
32
+ const root = join(packageRoot, 'src', 'panel');
33
+ return {
34
+ // The package's default tsconfig references generated typecheck projects.
35
+ tsconfig: join(root, 'tsconfig.browser.json'),
36
+ root,
37
+ plugins: [css('web'), ...octane(), boundary('web'), devtoolsPanels({ root: project ?? root })],
38
+ define: {
39
+ ...nodeEnvDefine(mode),
40
+ __XPLAT_DEVTOOLS_PROJECT__: JSON.stringify(project),
41
+ },
42
+ base: './',
43
+ build: {
44
+ outDir,
45
+ emptyOutDir: true,
46
+ rollupOptions: { input: join(root, 'index.html') },
47
+ },
48
+ resolve: {
49
+ conditions: ['web'],
50
+ extensions: [
51
+ '.web.tsrx',
52
+ '.tsrx',
53
+ '.web.tsx',
54
+ '.tsx',
55
+ '.web.ts',
56
+ '.mjs',
57
+ '.mts',
58
+ '.ts',
59
+ '.jsx',
60
+ '.js',
61
+ '.json',
62
+ ],
63
+ dedupe: ['octane'],
64
+ },
65
+ };
66
+ }
67
+ export async function buildDevtoolsWeb(project, outDir) {
68
+ const require = createRequire(join(project, 'package.json'));
69
+ const { build } = await import(__rewriteRelativeImportExtension(pathToFileURL(require.resolve('vite')).href, true));
70
+ await build({
71
+ ...(await devtoolsWebConfig(project, outDir, 'production', project)),
72
+ configFile: false,
73
+ });
74
+ }
@@ -0,0 +1,3 @@
1
+ export { nwDevSocket } from './socket.macos.ts';
2
+ export { listDevtoolsServers } from './servers.macos.ts';
3
+ export type { ListedDevtoolsServer } from '../record.ts';
@@ -0,0 +1,5 @@
1
+ // macOS leaf barrel — `@octane-xplat/devtools/macos`. JSC-host-only pieces for
2
+ // the native devtools app: the Network.framework DevSocket and the Foundation
3
+ // discovery-record reader.
4
+ export { nwDevSocket } from './socket.macos.js';
5
+ export { listDevtoolsServers } from './servers.macos.js';
@@ -0,0 +1,4 @@
1
+ import { type ListedDevtoolsServer } from '../record.ts';
2
+ export type { ListedDevtoolsServer } from '../record.ts';
3
+ /** Returns every structurally valid live record, newest first. */
4
+ export declare function listDevtoolsServers(): ListedDevtoolsServer[];
@@ -0,0 +1,57 @@
1
+ // Enumerates live `xplat dev` server discovery records on the macOS JSC host —
2
+ // the Foundation counterpart of src/host/records.ts's node:fs reader. Records
3
+ // live in ~/Library/Caches/octane-xplat/cli-go/dev-servers-v1/<key>/server.json
4
+ // (XPLAT_DEV_RECORDS_DIR overrides for tests). Unreadable dirs and malformed
5
+ // entries are skipped; connectivity failures surface through the connection's
6
+ // closed state, not here.
7
+ import { NSFileManager, NSFileModificationDate, NSHomeDirectory, NSString, } from '@octane-xplat/platform/macos';
8
+ import { parseDevtoolsServerRecord } from '../record.js';
9
+ const RECORDS_DIR = 'Library/Caches/octane-xplat/cli-go/dev-servers-v1';
10
+ function recordsDir() {
11
+ return process.env.XPLAT_DEV_RECORDS_DIR ?? `${NSHomeDirectory()}/${RECORDS_DIR}`;
12
+ }
13
+ function readEntries() {
14
+ const dir = recordsDir();
15
+ const manager = NSFileManager.defaultManager;
16
+ let names;
17
+ try {
18
+ names = manager.contentsOfDirectoryAtPathError(dir, null);
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ if (!names) {
24
+ return [];
25
+ }
26
+ const found = [];
27
+ for (let i = 0; i < names.count; i++) {
28
+ const name = String(names.objectAtIndex(i));
29
+ const file = `${dir}/${name}/server.json`;
30
+ try {
31
+ const attrs = manager.attributesOfItemAtPathError(file, null);
32
+ if (!attrs) {
33
+ continue;
34
+ }
35
+ const text = NSString.stringWithContentsOfFileEncodingError(file, 4, // NSUTF8StringEncoding
36
+ null);
37
+ const server = parseDevtoolsServerRecord(name, String(text), (path) => path.startsWith('/'));
38
+ if (!server) {
39
+ continue;
40
+ }
41
+ const modified = attrs.objectForKey(NSFileModificationDate);
42
+ const written = modified &&
43
+ typeof modified.timeIntervalSince1970 === 'number'
44
+ ? modified.timeIntervalSince1970
45
+ : 0;
46
+ found.push({ server, written });
47
+ }
48
+ catch {
49
+ continue;
50
+ }
51
+ }
52
+ return found.sort((a, b) => b.written - a.written).map(({ server }) => server);
53
+ }
54
+ /** Returns every structurally valid live record, newest first. */
55
+ export function listDevtoolsServers() {
56
+ return readEntries();
57
+ }
@@ -0,0 +1,2 @@
1
+ import type { DevSocket } from '../types.ts';
2
+ export declare function nwDevSocket(url: string): DevSocket | undefined;
@@ -0,0 +1,152 @@
1
+ // DevSocket over Network.framework (NWConnection). The JSC host has no
2
+ // WebSocket, and NSURLSessionWebSocketTask is unreachable through the bundled
3
+ // node-api metadata — webSocketTaskWithURL returns an object whose prototype is
4
+ // plain NSURLSessionTask (no ws selectors). C functions are bridged, so the
5
+ // connection is opened by hand and frames are codec'd by ./ws-frames.ts.
6
+ // Local ws:// only — no TLS.
7
+ import { interop, NSData, NSOperationQueue } from '@octane-xplat/platform/macos';
8
+ import { _nw_content_context_default_message, _nw_parameters_configure_protocol_default_configuration, _nw_parameters_configure_protocol_disable, dispatch_data_create, dispatch_queue_create, nw_connection_cancel, nw_connection_create, nw_connection_receive, nw_connection_send, nw_connection_set_queue, nw_connection_set_state_changed_handler, nw_connection_start, nw_endpoint_create_host, nw_parameters_create_secure_tcp, } from '@octane-xplat/platform/macos';
9
+ import { encodeFrame, FrameDecoder, handshakeAccept, handshakeRequest, utf8Encode, } from './ws-frames.js';
10
+ export function nwDevSocket(url) {
11
+ const m = /^ws:\/\/([^:/]+):(\d+)(\/.*)$/.exec(url);
12
+ if (!m) {
13
+ return undefined;
14
+ }
15
+ const [, host, port, path] = m;
16
+ const queue = NSOperationQueue.mainQueue.underlyingQueue ??
17
+ dispatch_queue_create('devtools.ws', null);
18
+ const sendQueue = dispatch_queue_create('devtools.ws.send', null);
19
+ const endpoint = nw_endpoint_create_host(host, port);
20
+ const params = nw_parameters_create_secure_tcp(
21
+ // _disable as the TLS configure block → plain TCP.
22
+ _nw_parameters_configure_protocol_disable, _nw_parameters_configure_protocol_default_configuration);
23
+ const conn = nw_connection_create(endpoint, params);
24
+ let closed = false;
25
+ let ready = false;
26
+ let handshaken = false;
27
+ const socket = {
28
+ get readyState() {
29
+ // WebSocket constants: 0 CONNECTING, 1 OPEN, 3 CLOSED (no CLOSING — the
30
+ // transport has no half-close state to report).
31
+ if (closed) {
32
+ return 3;
33
+ }
34
+ return ready ? 1 : 0;
35
+ },
36
+ onopen: null,
37
+ onmessage: null,
38
+ onerror: null,
39
+ onclose: null,
40
+ send: () => { },
41
+ close: () => { },
42
+ };
43
+ const decoder = new FrameDecoder();
44
+ const fail = () => {
45
+ if (closed) {
46
+ return;
47
+ }
48
+ closed = true;
49
+ socket.onerror?.();
50
+ socket.onclose?.({ code: 1006, reason: '' });
51
+ };
52
+ // dispatch_data_t toll-free bridges with NSData.
53
+ function sendBytes(bytes) {
54
+ const data = NSData.dataWithBytesLength(bytes, bytes.length);
55
+ const d = dispatch_data_create(data.bytes, bytes.length, sendQueue, () => { });
56
+ nw_connection_send(conn, d, _nw_content_context_default_message, false, (error) => {
57
+ if (error) {
58
+ fail();
59
+ }
60
+ });
61
+ }
62
+ socket.send = (data) => {
63
+ if (!ready || closed) {
64
+ return;
65
+ }
66
+ sendBytes(encodeFrame(1, utf8Encode(data)));
67
+ };
68
+ socket.close = () => {
69
+ if (closed) {
70
+ return;
71
+ }
72
+ closed = true;
73
+ try {
74
+ sendBytes(encodeFrame(8, new Uint8Array(0)));
75
+ }
76
+ catch { }
77
+ nw_connection_cancel(conn);
78
+ socket.onclose?.({ code: 1000, reason: '' });
79
+ };
80
+ function pump() {
81
+ nw_connection_receive(conn, 1, 1 << 20, (data, _ctx, _complete, error) => {
82
+ if (error || closed) {
83
+ if (!closed) {
84
+ fail();
85
+ }
86
+ return;
87
+ }
88
+ try {
89
+ if (data) {
90
+ if (!handshaken) {
91
+ handshakeBuffer = concat(handshakeBuffer, new Uint8Array(interop.bufferFromData(data)));
92
+ const end = handshakeAccept(handshakeBuffer);
93
+ if (end >= 0) {
94
+ handshaken = true;
95
+ ready = true;
96
+ socket.onopen?.();
97
+ for (const ev of decoder.push(handshakeBuffer.subarray(end))) {
98
+ deliver(ev);
99
+ }
100
+ }
101
+ }
102
+ else {
103
+ for (const ev of decoder.push(new Uint8Array(interop.bufferFromData(data)))) {
104
+ deliver(ev);
105
+ }
106
+ }
107
+ }
108
+ }
109
+ catch (e) {
110
+ console.error('[devtools socket]', e);
111
+ fail();
112
+ return;
113
+ }
114
+ if (!closed) {
115
+ pump();
116
+ }
117
+ });
118
+ }
119
+ let handshakeBuffer = new Uint8Array(0);
120
+ function concat(a, b) {
121
+ const out = new Uint8Array(a.length + b.length);
122
+ out.set(a, 0);
123
+ out.set(b, a.length);
124
+ return out;
125
+ }
126
+ function deliver(ev) {
127
+ if (ev.type === 'text') {
128
+ socket.onmessage?.({ data: ev.data });
129
+ }
130
+ else if (ev.type === 'close') {
131
+ closed = true;
132
+ nw_connection_cancel(conn);
133
+ socket.onclose?.({ code: 1000, reason: '' });
134
+ }
135
+ else if (ev.type === 'ping') {
136
+ sendBytes(encodeFrame(10, ev.payload));
137
+ }
138
+ }
139
+ nw_connection_set_state_changed_handler(conn, (state, error) => {
140
+ // nw_connection_state_ready = 3
141
+ if (state === 3 && !handshaken) {
142
+ sendBytes(handshakeRequest(host, port, path));
143
+ }
144
+ else if (state === 4 || state === 5 || error) {
145
+ fail();
146
+ }
147
+ });
148
+ nw_connection_set_queue(conn, queue);
149
+ nw_connection_start(conn);
150
+ pump();
151
+ return socket;
152
+ }
@@ -0,0 +1,24 @@
1
+ export declare function utf8Encode(s: string): Uint8Array;
2
+ export declare function utf8Decode(bytes: Uint8Array): string;
3
+ export declare function base64Encode(bytes: Uint8Array): string;
4
+ export declare function handshakeRequest(host: string, port: string, path: string): Uint8Array;
5
+ export declare function handshakeAccept(buffer: Uint8Array): number;
6
+ export type FrameEvent = {
7
+ type: 'text';
8
+ data: string;
9
+ } | {
10
+ type: 'close';
11
+ } | {
12
+ type: 'ping';
13
+ payload: Uint8Array;
14
+ } | {
15
+ type: 'pong';
16
+ payload: Uint8Array;
17
+ };
18
+ export declare function encodeFrame(opcode: number, payload: Uint8Array, maskKey?: Uint8Array): Uint8Array;
19
+ export declare class FrameDecoder {
20
+ private buffer;
21
+ private fragments;
22
+ private fragmentOpcode;
23
+ push(chunk: Uint8Array): FrameEvent[];
24
+ }