@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,92 @@
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
+
7
+ import { createServer, type Server } from 'node:http'
8
+ import { readFileSync, realpathSync } from 'node:fs'
9
+ import { dirname, extname, join, normalize, sep } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { listDevtoolsServers } from './records.ts'
12
+
13
+ const TYPES: Record<string, string> = {
14
+ '.html': 'text/html; charset=utf-8',
15
+ '.js': 'text/javascript; charset=utf-8',
16
+ '.css': 'text/css; charset=utf-8',
17
+ '.json': 'application/json; charset=utf-8',
18
+ '.svg': 'image/svg+xml',
19
+ '.png': 'image/png',
20
+ '.woff2': 'font/woff2',
21
+ }
22
+
23
+ export interface DevtoolsHost {
24
+ /** http://127.0.0.1:<port> the panel is served on. */
25
+ endpoint: string
26
+ close(): Promise<void>
27
+ }
28
+
29
+ function packageRoot(): string {
30
+ // host/ sits under src/ (source runs) or dist/ (published runs).
31
+ return dirname(dirname(dirname(fileURLToPath(import.meta.url))))
32
+ }
33
+
34
+ export async function serveDevtools({ port = 0 }: { port?: number } = {}): Promise<DevtoolsHost> {
35
+ const root = realpathSync(packageRoot())
36
+ const panel = join(root, 'dist', 'panel')
37
+
38
+ const server: Server = createServer((req, res) => {
39
+ const send = (
40
+ status: number,
41
+ body: string | Buffer,
42
+ type = 'application/json; charset=utf-8',
43
+ ) => {
44
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' })
45
+ res.end(body)
46
+ }
47
+
48
+ if (req.method !== 'GET') {
49
+ return send(405, '{"error":"method not allowed"}')
50
+ }
51
+
52
+ const path = normalize(new URL(req.url ?? '/', 'http://127.0.0.1').pathname)
53
+
54
+ if (path === '/devtools/servers') {
55
+ return send(200, JSON.stringify({ servers: listDevtoolsServers() }))
56
+ }
57
+
58
+ // '/' and '/app/...' map to the built panel bundle — strict containment,
59
+ // no traversal out of dist/panel.
60
+ const file =
61
+ path === '/' || path === '/app'
62
+ ? join(panel, 'index.html')
63
+ : path.startsWith('/app/')
64
+ ? join(panel, path.slice('/app'.length))
65
+ : null
66
+
67
+ if (!file || (path.startsWith('/app/') && !file.startsWith(panel + sep))) {
68
+ return send(404, '{"error":"not found"}')
69
+ }
70
+
71
+ try {
72
+ send(200, readFileSync(file), TYPES[extname(file)] ?? 'application/octet-stream')
73
+ } catch {
74
+ send(404, '{"error":"not found"}')
75
+ }
76
+ })
77
+
78
+ await new Promise<void>((resolve, reject) => {
79
+ server.once('error', reject)
80
+ server.listen(port, '127.0.0.1', () => resolve())
81
+ })
82
+
83
+ const address = server.address()
84
+
85
+ return {
86
+ endpoint: `http://127.0.0.1:${typeof address === 'object' && address ? address.port : port}`,
87
+ close: () =>
88
+ new Promise((resolve, reject) => {
89
+ server.close((error) => (error ? reject(error) : resolve()))
90
+ }),
91
+ }
92
+ }
@@ -0,0 +1,68 @@
1
+ import { createRequire } from 'node:module'
2
+ import { join } from 'node:path'
3
+ import { fileURLToPath, pathToFileURL } from 'node:url'
4
+ import type { InlineConfig } from 'vite'
5
+ import { devtoolsPanels } from './panels.ts'
6
+
7
+ const packageRoot = fileURLToPath(new URL('../../', import.meta.url))
8
+
9
+ /** The toolchain comes from the selected app. The bundled shell and its TS
10
+ * configuration come from this installed DevTools package. */
11
+ export async function devtoolsWebConfig(
12
+ toolsRoot: string,
13
+ outDir: string,
14
+ mode: string,
15
+ project: string | null = null,
16
+ ): Promise<InlineConfig> {
17
+ const require = createRequire(join(toolsRoot, 'package.json'))
18
+ const load = (name: string) => import(pathToFileURL(require.resolve(name)).href)
19
+ const [{ octane }, { css, boundary, nodeEnvDefine }] = await Promise.all([
20
+ load('@octanejs/vite-plugin'),
21
+ load('@octane-xplat/cli/vite'),
22
+ ])
23
+
24
+ const root = join(packageRoot, 'src', 'panel')
25
+
26
+ return {
27
+ // The package's default tsconfig references generated typecheck projects.
28
+ tsconfig: join(root, 'tsconfig.browser.json'),
29
+ root,
30
+ plugins: [css('web'), ...octane(), boundary('web'), devtoolsPanels({ root: project ?? root })],
31
+ define: {
32
+ ...nodeEnvDefine(mode),
33
+ __XPLAT_DEVTOOLS_PROJECT__: JSON.stringify(project),
34
+ },
35
+ base: './',
36
+ build: {
37
+ outDir,
38
+ emptyOutDir: true,
39
+ rollupOptions: { input: join(root, 'index.html') },
40
+ },
41
+ resolve: {
42
+ conditions: ['web'],
43
+ extensions: [
44
+ '.web.tsrx',
45
+ '.tsrx',
46
+ '.web.tsx',
47
+ '.tsx',
48
+ '.web.ts',
49
+ '.mjs',
50
+ '.mts',
51
+ '.ts',
52
+ '.jsx',
53
+ '.js',
54
+ '.json',
55
+ ],
56
+ dedupe: ['octane'],
57
+ },
58
+ }
59
+ }
60
+
61
+ export async function buildDevtoolsWeb(project: string, outDir: string) {
62
+ const require = createRequire(join(project, 'package.json'))
63
+ const { build } = await import(pathToFileURL(require.resolve('vite')).href)
64
+ await build({
65
+ ...(await devtoolsWebConfig(project, outDir, 'production', project)),
66
+ configFile: false,
67
+ })
68
+ }
@@ -0,0 +1,7 @@
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
+
5
+ export { nwDevSocket } from './socket.macos.ts'
6
+ export { listDevtoolsServers } from './servers.macos.ts'
7
+ export type { ListedDevtoolsServer } from '../record.ts'
@@ -0,0 +1,83 @@
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 {
8
+ NSFileManager,
9
+ NSFileModificationDate,
10
+ NSHomeDirectory,
11
+ NSString,
12
+ } from '@octane-xplat/platform/macos'
13
+
14
+ import { parseDevtoolsServerRecord, type ListedDevtoolsServer } from '../record.ts'
15
+
16
+ export type { ListedDevtoolsServer } from '../record.ts'
17
+
18
+ const RECORDS_DIR = 'Library/Caches/octane-xplat/cli-go/dev-servers-v1'
19
+
20
+ function recordsDir(): string {
21
+ return process.env.XPLAT_DEV_RECORDS_DIR ?? `${NSHomeDirectory()}/${RECORDS_DIR}`
22
+ }
23
+
24
+ function readEntries(): ListedDevtoolsServer[] {
25
+ const dir = recordsDir()
26
+ const manager = NSFileManager.defaultManager
27
+ let names: { count: number; objectAtIndex(index: number): unknown } | undefined
28
+
29
+ try {
30
+ names = manager.contentsOfDirectoryAtPathError(dir, null)
31
+ } catch {
32
+ return []
33
+ }
34
+
35
+ if (!names) {
36
+ return []
37
+ }
38
+
39
+ const found: { server: ListedDevtoolsServer; written: number }[] = []
40
+
41
+ for (let i = 0; i < names.count; i++) {
42
+ const name = String(names.objectAtIndex(i))
43
+ const file = `${dir}/${name}/server.json`
44
+
45
+ try {
46
+ const attrs = manager.attributesOfItemAtPathError(file, null)
47
+
48
+ if (!attrs) {
49
+ continue
50
+ }
51
+
52
+ const text = NSString.stringWithContentsOfFileEncodingError(
53
+ file,
54
+ 4, // NSUTF8StringEncoding
55
+ null,
56
+ )
57
+
58
+ const server = parseDevtoolsServerRecord(name, String(text), (path) => path.startsWith('/'))
59
+
60
+ if (!server) {
61
+ continue
62
+ }
63
+
64
+ const modified = attrs.objectForKey(NSFileModificationDate)
65
+ const written =
66
+ modified &&
67
+ typeof (modified as { timeIntervalSince1970?: unknown }).timeIntervalSince1970 === 'number'
68
+ ? (modified as { timeIntervalSince1970: number }).timeIntervalSince1970
69
+ : 0
70
+
71
+ found.push({ server, written })
72
+ } catch {
73
+ continue
74
+ }
75
+ }
76
+
77
+ return found.sort((a, b) => b.written - a.written).map(({ server }) => server)
78
+ }
79
+
80
+ /** Returns every structurally valid live record, newest first. */
81
+ export function listDevtoolsServers(): ListedDevtoolsServer[] {
82
+ return readEntries()
83
+ }
@@ -0,0 +1,218 @@
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, type NSObject } from '@octane-xplat/platform/macos'
8
+ import {
9
+ _nw_content_context_default_message,
10
+ _nw_parameters_configure_protocol_default_configuration,
11
+ _nw_parameters_configure_protocol_disable,
12
+ dispatch_data_create,
13
+ dispatch_queue_create,
14
+ nw_connection_cancel,
15
+ nw_connection_create,
16
+ nw_connection_receive,
17
+ nw_connection_send,
18
+ nw_connection_set_queue,
19
+ nw_connection_set_state_changed_handler,
20
+ nw_connection_start,
21
+ nw_endpoint_create_host,
22
+ nw_parameters_create_secure_tcp,
23
+ } from '@octane-xplat/platform/macos'
24
+
25
+ import {
26
+ encodeFrame,
27
+ FrameDecoder,
28
+ handshakeAccept,
29
+ handshakeRequest,
30
+ utf8Encode,
31
+ } from './ws-frames.ts'
32
+
33
+ import type { DevSocket } from '../types.ts'
34
+
35
+ export function nwDevSocket(url: string): DevSocket | undefined {
36
+ const m = /^ws:\/\/([^:/]+):(\d+)(\/.*)$/.exec(url)
37
+
38
+ if (!m) {
39
+ return undefined
40
+ }
41
+
42
+ const [, host, port, path] = m
43
+
44
+ const queue =
45
+ (NSOperationQueue.mainQueue as { underlyingQueue?: NSObject }).underlyingQueue ??
46
+ dispatch_queue_create('devtools.ws', null as unknown as NSObject)
47
+
48
+ const sendQueue = dispatch_queue_create('devtools.ws.send', null as unknown as NSObject)
49
+ const endpoint = nw_endpoint_create_host(host, port)
50
+ const params = nw_parameters_create_secure_tcp(
51
+ // _disable as the TLS configure block → plain TCP.
52
+ _nw_parameters_configure_protocol_disable,
53
+ _nw_parameters_configure_protocol_default_configuration,
54
+ )
55
+
56
+ const conn = nw_connection_create(endpoint, params)
57
+
58
+ let closed = false
59
+ let ready = false
60
+ let handshaken = false
61
+
62
+ const socket: DevSocket = {
63
+ get readyState() {
64
+ // WebSocket constants: 0 CONNECTING, 1 OPEN, 3 CLOSED (no CLOSING — the
65
+ // transport has no half-close state to report).
66
+ if (closed) {
67
+ return 3
68
+ }
69
+
70
+ return ready ? 1 : 0
71
+ },
72
+ onopen: null,
73
+ onmessage: null,
74
+ onerror: null,
75
+ onclose: null,
76
+ send: () => {},
77
+ close: () => {},
78
+ }
79
+
80
+ const decoder = new FrameDecoder()
81
+
82
+ const fail = () => {
83
+ if (closed) {
84
+ return
85
+ }
86
+
87
+ closed = true
88
+ socket.onerror?.()
89
+ socket.onclose?.({ code: 1006, reason: '' })
90
+ }
91
+
92
+ // dispatch_data_t toll-free bridges with NSData.
93
+ function sendBytes(bytes: Uint8Array) {
94
+ const data = NSData.dataWithBytesLength(bytes, bytes.length)
95
+ const d = dispatch_data_create(
96
+ (data as unknown as { bytes: NSObject }).bytes,
97
+ bytes.length,
98
+ sendQueue,
99
+ () => {},
100
+ )
101
+
102
+ nw_connection_send(conn, d, _nw_content_context_default_message, false, (error: unknown) => {
103
+ if (error) {
104
+ fail()
105
+ }
106
+ })
107
+ }
108
+
109
+ socket.send = (data) => {
110
+ if (!ready || closed) {
111
+ return
112
+ }
113
+
114
+ sendBytes(encodeFrame(1, utf8Encode(data)))
115
+ }
116
+
117
+ socket.close = () => {
118
+ if (closed) {
119
+ return
120
+ }
121
+
122
+ closed = true
123
+ try {
124
+ sendBytes(encodeFrame(8, new Uint8Array(0)))
125
+ } catch {}
126
+
127
+ nw_connection_cancel(conn)
128
+ socket.onclose?.({ code: 1000, reason: '' })
129
+ }
130
+
131
+ function pump() {
132
+ nw_connection_receive(
133
+ conn,
134
+ 1,
135
+ 1 << 20,
136
+ (data: NSObject, _ctx: unknown, _complete: boolean, error: unknown) => {
137
+ if (error || closed) {
138
+ if (!closed) {
139
+ fail()
140
+ }
141
+
142
+ return
143
+ }
144
+
145
+ try {
146
+ if (data) {
147
+ if (!handshaken) {
148
+ handshakeBuffer = concat(
149
+ handshakeBuffer,
150
+ new Uint8Array(interop.bufferFromData(data as unknown as NSData)),
151
+ )
152
+
153
+ const end = handshakeAccept(handshakeBuffer)
154
+
155
+ if (end >= 0) {
156
+ handshaken = true
157
+ ready = true
158
+ socket.onopen?.()
159
+ for (const ev of decoder.push(handshakeBuffer.subarray(end))) {
160
+ deliver(ev)
161
+ }
162
+ }
163
+ } else {
164
+ for (const ev of decoder.push(
165
+ new Uint8Array(interop.bufferFromData(data as unknown as NSData)),
166
+ )) {
167
+ deliver(ev)
168
+ }
169
+ }
170
+ }
171
+ } catch (e) {
172
+ console.error('[devtools socket]', e)
173
+ fail()
174
+ return
175
+ }
176
+
177
+ if (!closed) {
178
+ pump()
179
+ }
180
+ },
181
+ )
182
+ }
183
+
184
+ let handshakeBuffer = new Uint8Array(0)
185
+ function concat(a: Uint8Array, b: Uint8Array) {
186
+ const out = new Uint8Array(a.length + b.length)
187
+
188
+ out.set(a, 0)
189
+ out.set(b, a.length)
190
+ return out
191
+ }
192
+
193
+ function deliver(ev: ReturnType<FrameDecoder['push']>[number]) {
194
+ if (ev.type === 'text') {
195
+ socket.onmessage?.({ data: ev.data })
196
+ } else if (ev.type === 'close') {
197
+ closed = true
198
+ nw_connection_cancel(conn)
199
+ socket.onclose?.({ code: 1000, reason: '' })
200
+ } else if (ev.type === 'ping') {
201
+ sendBytes(encodeFrame(10, ev.payload))
202
+ }
203
+ }
204
+
205
+ nw_connection_set_state_changed_handler(conn, (state: number, error: unknown) => {
206
+ // nw_connection_state_ready = 3
207
+ if (state === 3 && !handshaken) {
208
+ sendBytes(handshakeRequest(host, port, path))
209
+ } else if (state === 4 || state === 5 || error) {
210
+ fail()
211
+ }
212
+ })
213
+
214
+ nw_connection_set_queue(conn, queue)
215
+ nw_connection_start(conn)
216
+ pump()
217
+ return socket
218
+ }