@gjermundgaraba/clankermux 0.3.0 → 0.4.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/README.md +91 -30
- package/dist/client/attachment.d.ts +1 -0
- package/dist/client/attachment.js +1 -1
- package/dist/client/client.d.ts +123 -0
- package/dist/client/client.js +268 -0
- package/dist/client/connection.d.ts +17 -2
- package/dist/client/connection.js +21 -3
- package/dist/client/index.d.ts +4 -3
- package/dist/client/index.js +1 -1
- package/dist/client/mount.d.ts +45 -42
- package/dist/client/mount.js +77 -56
- package/dist/client/worker.d.ts +115 -46
- package/dist/client/worker.js +456 -217
- package/dist/proto/messages.d.ts +287 -5
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
# @gjermundgaraba/clankermux
|
|
2
2
|
|
|
3
|
-
The browser client of [clankermux](https://github.com/gjermundgaraba/clankermux):
|
|
3
|
+
The browser client of [clankermux](https://github.com/gjermundgaraba/clankermux): one connection to a server, speaking the clankermux protocol over its TLS WebSocket carrier from a module worker, and terminals on canvases mounted from it, the engine in the same worker.
|
|
4
4
|
|
|
5
5
|
| Subpath | Exports |
|
|
6
6
|
| --- | --- |
|
|
7
|
-
| `.` | `
|
|
7
|
+
| `.` | `connect`, `Client`, the `Terminal` it mounts, their types, `ClientError` |
|
|
8
8
|
| `./worker` | `runWorker`, for the worker module; no DOM types |
|
|
9
9
|
| `./ghostty-vt.wasm` | the engine build the server's engine id names |
|
|
10
|
-
| `./proto`, `./engine`, `./renderer` | the protocol messages, the engine and the canvas renderer |
|
|
10
|
+
| `./proto`, `./engine`, `./renderer` | the protocol messages, the engine and the canvas renderer; `Methods` maps each method to its params and result types, and `Catalog` is what `describe()` answers: the server's methods, events, frames and error codes with their JSON Schemas |
|
|
11
11
|
|
|
12
12
|
```ts
|
|
13
13
|
// worker.ts, started as a module worker
|
|
@@ -15,35 +15,90 @@ import { runWorker } from "@gjermundgaraba/clankermux/worker";
|
|
|
15
15
|
runWorker(self);
|
|
16
16
|
|
|
17
17
|
// page
|
|
18
|
-
import {
|
|
18
|
+
import { connect } from "@gjermundgaraba/clankermux";
|
|
19
19
|
import wasm from "@gjermundgaraba/clankermux/ghostty-vt.wasm?url";
|
|
20
|
-
const
|
|
20
|
+
const client = await connect({
|
|
21
21
|
worker: new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }),
|
|
22
|
-
|
|
22
|
+
wasm, url: "wss://127.0.0.1:7438/",
|
|
23
|
+
});
|
|
24
|
+
const terminal = client.mount({
|
|
25
|
+
canvas, container, session,
|
|
23
26
|
font: "14px monospace", colors: () => ({ fg: "#d8dee9", bg: "#282c34", cursor: "#ffffff" }),
|
|
24
|
-
|
|
27
|
+
});
|
|
28
|
+
terminal.onLink((link) => console.log(link));
|
|
29
|
+
// Requests need the connection: once the client's link is connected.
|
|
30
|
+
let created = false;
|
|
31
|
+
client.onLink(async (link) => {
|
|
32
|
+
if (link.state !== "connected" || created) return;
|
|
33
|
+
created = true;
|
|
34
|
+
const { id } = await client.create({ ...terminal.size(), on_exit: "keep" });
|
|
35
|
+
terminal.attach(id);
|
|
25
36
|
});
|
|
26
37
|
```
|
|
27
38
|
|
|
28
|
-
|
|
39
|
+
A page holds one client: one worker, one WebSocket, the session list and the event stream. Every terminal it mounts is one attachment on that connection, so a page with many panes holds one connection, and the client's methods serve them all.
|
|
40
|
+
|
|
41
|
+
## `connect`
|
|
42
|
+
|
|
43
|
+
`connect({url, worker, wasm, client?})` starts the worker and resolves with the `Client` once the engine is loaded, before the connection is up: the worker connects, and after a loss reconnects, by itself, and the client's `onLink`, and each terminal's, says how that goes (below). Requests need a `connected` link. It rejects when the worker script or the engine cannot be loaded. An exception in the worker after that is the browser's to report, as before: it costs the message being handled, and the client goes on. `client` is the `{name, version}` the connection gives in `HELLO`, which the server lists in each session's `attachments`; `clankermux-web` and this package's version by default.
|
|
44
|
+
|
|
45
|
+
## `Client`
|
|
46
|
+
|
|
47
|
+
Each method is the protocol method of the same name (PROTOCOL.md has their params, results and errors):
|
|
48
|
+
|
|
49
|
+
| Method | Protocol |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `describe()`, `describe(method)` | `describe`: the catalog, or one method of it |
|
|
52
|
+
| `create(params?)` | `create`, all its params (`label`, `argv`, `cwd`, `env`, `cols`, `rows`, `on_exit`); resolves with the session. It attaches nothing: `terminal.attach(id)` does. `terminal.size()` is the grid a terminal's container holds, to create at that size |
|
|
53
|
+
| `sessions()` | `list`, paged to its end |
|
|
54
|
+
| `list(after?)` | `list`, one page |
|
|
55
|
+
| `inspect(id)` | `inspect` |
|
|
56
|
+
| `end(id)`, `signal(id, name)`, `remove(id)` | `end` (SIGHUP), `signal`, `remove`; resolve with nothing |
|
|
57
|
+
| `label(id, text)` | `label`; resolves with the session |
|
|
58
|
+
| `resize(id, {cols?, rows?, policy?})` | `resize` |
|
|
59
|
+
| `send(id, {text \| keys \| data, paste?, wait?}, {signal?})` | `send`; resolves with `{at, wait?}`. Aborting `signal` cancels its `wait` |
|
|
60
|
+
| `wait(id, until, {after?, timeout_ms?, signal?})` | `wait`; resolves with `{reason, at, exit?, match?, record?}`, a timeout being a result. Aborting `signal` sends `cancel`, and the wait rejects with `cancelled` |
|
|
61
|
+
| `read(id, {scrollback?, format?, scope?})` | `read` |
|
|
62
|
+
| `tail(id, after, {max_bytes?})` | `tail` |
|
|
63
|
+
| `ack(id, recordIds?)` | `ack` |
|
|
64
|
+
| `detach(id, channel, reason?)` | `detach`: another attachment, by its `channel` in `attachments` |
|
|
65
|
+
| `onLink(listener)` | the connection's link: `connecting {attempt}`, `connected` (with no session) or `ended`, the connection-level rows of the tables below; the latest at once to a listener added later |
|
|
66
|
+
| `onSessions(listener)` | every session at each change (below) |
|
|
67
|
+
| `onEvent(listener)` | each event, without loss across reconnects (below) |
|
|
68
|
+
| `mount(options)` | a `Terminal` on this connection |
|
|
69
|
+
| `close()` | disposes the terminals and terminates the worker, which ends the connection |
|
|
70
|
+
|
|
71
|
+
A method rejects with a `ClientError`:
|
|
72
|
+
|
|
73
|
+
- `kind: "server"` when the server refuses, with `code` (and `server`, its `ERROR`): `no_such_session`, `not_running`, `running`, `cancelled` for a cancelled wait, and the rest of PROTOCOL.md's codes;
|
|
74
|
+
- `kind: "closed"` when there is no connection (before the first, between a loss and the reconnect, after the server ended it), when the connection is lost meanwhile, and after `close()`;
|
|
75
|
+
- `kind: "protocol"` when the server sent a malformed frame meanwhile.
|
|
76
|
+
|
|
77
|
+
A request is not retried across a reconnect. `end` rejects with `not_running` when the session is not running (`exited`, `restored`): there is nothing to end. Closing a pane for good is `end` for a running session, then `remove` once it has exited (`wait(id, {exited: true})` says when), and `remove` alone for one that has exited, or that a previous server left `restored`. With `on_exit: "remove"` an ended session removes itself.
|
|
78
|
+
|
|
79
|
+
While connected, a cancelled wait is cancelled by the server, so it rejects with the server's `cancelled` also when its signal was aborted before the request was sent; without a connection it rejects with `closed`, as any request does.
|
|
80
|
+
|
|
81
|
+
## `Terminal`
|
|
82
|
+
|
|
83
|
+
`client.mount({session?, canvas, container, font, colors, scheme?, readOnly?, ackOnFocus?})` draws on `canvas` the session `session`, if given, at the grid `container` holds. `readOnly` attaches read-only: the screen, and no input to the session. `ackOnFocus` marks the session's `done` and `error` records seen (`ack`) while the terminal has the keyboard and its window the focus: when it gets the focus, and when such a record wants the user meanwhile.
|
|
29
84
|
|
|
30
85
|
| Method | Does |
|
|
31
86
|
| --- | --- |
|
|
32
87
|
| `attach(session)` | Detaches the current session and attaches `session`; after a connection-level end (below), connects again first. |
|
|
33
|
-
| `
|
|
34
|
-
| `
|
|
35
|
-
| `
|
|
36
|
-
| `report()` | Reports the container's size, the colours and the scheme again. |
|
|
88
|
+
| `detach()` | Detaches the session; the terminal stays, attached to none (`connected` with no session). |
|
|
89
|
+
| `focus()` | Focuses the terminal's input element, as focusing the canvas does. |
|
|
90
|
+
| `selection()` | The selected text, as the last selection made copied it. |
|
|
37
91
|
| `paste(text)` | Pastes, bracketed when the program asked for it. |
|
|
38
|
-
| `
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
92
|
+
| `scroll(rows)` | Scrolls the view through the history by `rows`, up when negative. |
|
|
93
|
+
| `scrollToLive()` | Back to the live screen. |
|
|
94
|
+
| `report()` | Reports the container's size, the colours and the scheme again. |
|
|
95
|
+
| `size()` | `{cols, rows}`: the grid the container holds now. |
|
|
96
|
+
| `dispose()` | Detaches, and removes the listeners and the input element; the client and its other terminals stay. |
|
|
97
|
+
| `onLink(listener)` | Each change of the link to the session (below). |
|
|
98
|
+
| `onScroll(listener)` | The rows between the bottom of the view and the live screen's (below), from the first frame on. |
|
|
99
|
+
| `onStatus(listener)` | The same moments as `onLink`, and more, as text for display. |
|
|
45
100
|
|
|
46
|
-
|
|
101
|
+
The `on*` methods return a function that removes the listener; a listener added after a change gets the latest at once.
|
|
47
102
|
|
|
48
103
|
## Keys and composed text
|
|
49
104
|
|
|
@@ -60,28 +115,33 @@ Verified in headless Chrome on macOS through CDP (`Input.imeSetComposition`, `In
|
|
|
60
115
|
|
|
61
116
|
## `onSessions`
|
|
62
117
|
|
|
63
|
-
`onSessions(
|
|
118
|
+
`client.onSessions(listener)` reports every session on the server at each change: a session created, exited or removed, and a `session_changed`, which the server sends when a session's label, size, size policy, attachments, title, working directory or attention changes. A listener added once the list is known gets it at once. `attachments` is the list of open attachments in the order they opened, each `{channel, client: {name, version}, read_only, viewport?: {cols, rows}, since, last_input?}`: `channel` is unique on the server, `client` the connecting page or program's own name, `viewport` its latest size report, `last_input` when it last typed (input alone sends no `session_changed`). `size` is `{policy, owner?}`, `owner` being the channel whose report sets the size under `latest`. The title is the program's (OSC 0 or 2), the working directory the one it reports (OSC 7, as a path), each empty until set, and both cleared by a full reset. A status line takes them from the session its terminal shows; the `session` of a `connected` link is the one `ATTACHED` described, and does not follow these changes.
|
|
119
|
+
|
|
120
|
+
A session's `attention`, when present, is the program status record that most wants the user (`{state, kind?, app?, msg?, record}`: `blocked`, then an unseen `error`, then an unseen `done`, then `working`), so a badge needs no request per session; a `session_changed` follows each change of it.
|
|
121
|
+
|
|
122
|
+
## `onEvent`
|
|
123
|
+
|
|
124
|
+
`client.onEvent(listener)` reports each server event, of every session, in `seq` order, as PROTOCOL.md describes them: `session_created`, `session_changed`, `session_exited`, `session_removed`, `program_status_changed`, `program_status_removed`, `bell`, `notification`, `progress`, `command_started`, `command_ended`, `attachment_opened` and `attachment_closed`. After a reconnect the client subscribes from the last event it saw (`subscribe {after, incarnation}`), so the events missed while the connection was down are reported then, in order, before any later one. When the server cannot replay them (it restarted, so `seq` counts from 1 again, or more happened meanwhile than it retains), the listener gets `{event: "gap", incarnation}` instead, and the session list is paged again: `onSessions` has the current state.
|
|
64
125
|
|
|
65
126
|
## `onLink`
|
|
66
127
|
|
|
67
|
-
`onLink(
|
|
128
|
+
`terminal.onLink(listener)` reports each change of the terminal's link to its session, through the client's connection and the terminal's attachment. A terminal mounted later first gets the connection as it is then: `connecting` with the current attempt, or `connected` (and its own screen, if it names a session); after a connection-level end it connects again, as `attach` does.
|
|
68
129
|
|
|
69
130
|
```ts
|
|
70
131
|
type Link =
|
|
71
132
|
| { state: "connecting"; attempt: number }
|
|
72
133
|
| { state: "connected"; session: Session | undefined }
|
|
73
134
|
| { state: "ended"; reason: LinkEnd; code?: ErrorCode; message?: string; exit?: Exit; retry: boolean };
|
|
74
|
-
type LinkEnd = "closed" | "removed" | "stopping" | "exited" | "no_such_session" | "engine_mismatch" | "error";
|
|
135
|
+
type LinkEnd = "closed" | "removed" | "stopping" | "detached" | "exited" | "no_such_session" | "engine_mismatch" | "error";
|
|
75
136
|
```
|
|
76
137
|
|
|
77
|
-
`retry` means the worker reconnects or attaches again by itself, so a `connecting` or `connected` follows. Otherwise nothing follows until the page calls `attach
|
|
138
|
+
`retry` means the worker reconnects or attaches again by itself, so a `connecting` or `connected` follows. Otherwise nothing follows until the page calls `attach`. The connection is the client's, so a connection-level change (the first table) reaches every terminal. After a connection-level end (the last three rows of the first table) there is no connection: the client's methods reject with `closed`, and a terminal's `attach`, or a terminal mounted then, connects again (`connecting` from attempt 1), so "Retry" can be `attach` or a new mount. An engine that failed to load rejects `connect`.
|
|
78
139
|
|
|
79
140
|
| When | Link |
|
|
80
141
|
| --- | --- |
|
|
81
|
-
| A connection is opened: at
|
|
142
|
+
| A connection is opened: at `connect`, and at each reconnect | `connecting`, `attempt` from 1; it starts again at 1 once a server answers |
|
|
82
143
|
| A connection cannot be opened, or closes before `WELCOME` | nothing at once; the next `connecting` after a backoff |
|
|
83
144
|
| The connection closes | `ended closed`, `retry: true`, then `connecting` |
|
|
84
|
-
| The engine cannot be loaded | `ended error`, `retry: false` |
|
|
85
145
|
| The server refuses the handshake (`ERROR` before `WELCOME`, e.g. `version_mismatch`), or sends something else first | `ended error` with the code when there is one, `retry: false` |
|
|
86
146
|
| The server ends the connection (`ERROR` without an id, e.g. `protocol_error`) | `ended error` with the code, `retry: false` |
|
|
87
147
|
| `subscribe` fails on a live connection | `ended error`, `retry: false`; the worker closes the connection |
|
|
@@ -91,11 +151,12 @@ Once connected:
|
|
|
91
151
|
| When | Link |
|
|
92
152
|
| --- | --- |
|
|
93
153
|
| Connected with no session to attach | `connected`, `session: undefined` |
|
|
94
|
-
| A session's screen is shown: a snapshot's first screen, a resume, again after a gap, a re-attach or a reconnect | `connected` with the session as `ATTACHED` described it; `status` tells `running`, `restored` or `exited` |
|
|
154
|
+
| A session's screen is shown: a snapshot's first screen, a resume, again after a gap, a re-attach or a reconnect | `connected` with the session as `ATTACHED` described it; `status` tells `running`, `restored` or `exited`. A reconnect to the same server resumes from the terminal's place in the stream (`onStatus` says `resumed`); one to a restarted server shows the session `restored` |
|
|
95
155
|
| A snapshot shows a session that has exited already | `connected`, then at once `ended exited` with its `exit`, `retry: false` (a resume onto such a session gets its `EXITED`, the next row, instead) |
|
|
96
156
|
| The session's program exits (`EXITED`) | `ended exited` with `exit`, `retry: false` |
|
|
97
157
|
| `CLOSED removed` | `ended removed`, `retry: false`; the worker forgets the session |
|
|
98
158
|
| `CLOSED stopping` | `ended stopping`, `retry: true`; the connection's close follows, and the reconnect attaches the session again (as `restored`) |
|
|
159
|
+
| `CLOSED detached` (another client's `detach`) | `ended detached`, `retry: false`, `message` the reason it gave, if any; the worker forgets the session, so a reconnect does not take it back |
|
|
99
160
|
| `OPEN` refused, or the attachment ended, with `no_such_session` or `engine_mismatch` | `ended` with that reason and code, `retry: false` |
|
|
100
161
|
| The attachment ended with `invalid_request` | `ended error`, `retry: false` |
|
|
101
162
|
| The attachment ended with another error (`too_slow`, a snapshot that failed, `internal`) | `ended error` with the code, `retry: true`; the worker attaches again after a backoff |
|
|
@@ -106,7 +167,7 @@ Nothing fires for:
|
|
|
106
167
|
|
|
107
168
|
- the errors that keep an attachment (`read_only`, `not_running`, `input_overflow`);
|
|
108
169
|
- a gap, until its new screen fires `connected`;
|
|
109
|
-
- `attach`
|
|
170
|
+
- `attach` before its screen;
|
|
110
171
|
- `dispose`.
|
|
111
172
|
|
|
112
173
|
`reason: "closed"` is the connection's close. The worker detaches without waiting for the server's `CLOSED closed`, so that frame never shows up as a link change.
|
|
@@ -143,11 +204,11 @@ The terminal holds the session's history (the server sends what it keeps with th
|
|
|
143
204
|
|
|
144
205
|
Output while the view is scrolled back leaves it where it is. Any input that sends something (a key, a paste, composed text) brings it back to the live screen first; a modifier alone does not. The alternate screen of full-screen programs (`vim`, `less`) has no history: there Shift+PageUp and the rest go to the program as keys, and the wheel sends the up and down arrow keys while the program leaves alternate scroll (mode 1007) on, as it is by default, or nothing.
|
|
145
206
|
|
|
146
|
-
While the view is scrolled back the canvas draws a mark at its right edge, the view's share of the history and its place in it. `onScroll(rows)` reports the rows between the bottom of the view and the live screen's
|
|
207
|
+
While the view is scrolled back the canvas draws a mark at its right edge, the view's share of the history and its place in it. `onScroll(rows)` reports, on the first frame and then at each change, the rows between the bottom of the view and the live screen's: above 0 when scrolled back (it grows as output arrives meanwhile), 0 at the live screen.
|
|
147
208
|
|
|
148
209
|
## Size between clients
|
|
149
210
|
|
|
150
|
-
A session has one size, and the server applies the latest report (PROTOCOL.md, "Size"). The terminal reports its container's size, its colours and its scheme only while its page is visible and its window has the focus (`document.visibilityState === "visible"` and `document.hasFocus()`). It reports again when the page is shown or its window focused, even at an unchanged size, and when the session was resized to another client's size while the page kept its focus (the user went to another machine and came back), at the page's next input: a key or text that sends something, a paste, a click on the canvas, the wheel. So with the same session open in several tabs or on several machines, the session takes the size of the one you look at, and a hidden or unfocused one never resizes it: its `OPEN` carries no viewport, it sends no `VIEWPORT`, and its canvas shows the session's size, clipped or with a margin. `report()` follows the same rule. `
|
|
211
|
+
A session has one size, and under the default size policy, `latest`, the server applies the latest report (PROTOCOL.md, "Size"); under `smallest` it takes the smallest columns and rows among the attachments' reports, and under `fixed` only a `resize` request changes it, the reports being recorded but not applied. The terminal reports its container's size, its colours and its scheme only while its page is visible and its window has the focus (`document.visibilityState === "visible"` and `document.hasFocus()`). It reports again when the page is shown or its window focused, even at an unchanged size, and when the session was resized to another client's size while the page kept its focus (the user went to another machine and came back), at the page's next input: a key or text that sends something, a paste, a click on the canvas, the wheel. So under `latest`, with the same session open in several tabs or on several machines, the session takes the size of the one you look at, and a hidden or unfocused one never resizes it: its `OPEN` carries no viewport, it sends no `VIEWPORT`, and its canvas shows the session's size, clipped or with a margin. `report()` follows the same rule. `size()` is the container's grid, focused or not, for a `create` at that size. A headless browser counts only its newest page as visible and focused, and a terminal in an iframe has the focus only once the frame does; such a page does not size the session until then.
|
|
151
212
|
|
|
152
213
|
## Colour scheme
|
|
153
214
|
|
|
@@ -156,7 +156,7 @@ export class Attachment {
|
|
|
156
156
|
case FrameType.Closed: {
|
|
157
157
|
const closed = this.json(frame);
|
|
158
158
|
this.end(true);
|
|
159
|
-
actions.push({ type: "closed", reason: closed.reason });
|
|
159
|
+
actions.push({ type: "closed", reason: closed.reason, ...(closed.message !== undefined && { message: closed.message }) });
|
|
160
160
|
break;
|
|
161
161
|
}
|
|
162
162
|
case FrameType.Error: {
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** The page side of a client: one worker, one connection, the control
|
|
2
|
+
* surface, and the terminals mounted from it. */
|
|
3
|
+
import type { Acked, Catalog, CreateParams, Description, Event, Page, Peer, Read, ReadParams, ResizeParams, SendParams, Sent, Session, StreamCursor, Tail, Until, Waited } from "../proto/index.ts";
|
|
4
|
+
import { type MountOptions, type Terminal } from "./mount.ts";
|
|
5
|
+
import type { Link, ToWorker } from "./worker.ts";
|
|
6
|
+
export interface ConnectOptions {
|
|
7
|
+
/** The server's WebSocket carrier, `wss://<node>:<port>/`. */
|
|
8
|
+
url: string;
|
|
9
|
+
/** A module worker whose script calls `runWorker(self)`; the client
|
|
10
|
+
* owns it from here. */
|
|
11
|
+
worker: Worker;
|
|
12
|
+
/** ghostty-vt.wasm, resolved against the page. */
|
|
13
|
+
wasm: string;
|
|
14
|
+
/** The name and version the client gives in `HELLO`, which the
|
|
15
|
+
* session's `attachments` list; `clankermux-web` and this package's
|
|
16
|
+
* version by default. */
|
|
17
|
+
client?: Peer;
|
|
18
|
+
}
|
|
19
|
+
/** Events were lost: the server restarted (a new `incarnation`), or more
|
|
20
|
+
* happened while the connection was down than it retains. The session
|
|
21
|
+
* list was paged again, and `onSessions` has it. */
|
|
22
|
+
export interface EventGap {
|
|
23
|
+
event: "gap";
|
|
24
|
+
incarnation: string;
|
|
25
|
+
}
|
|
26
|
+
/** `send`'s input: exactly one of `text`, `keys` and `data`. */
|
|
27
|
+
export type SendInput = Omit<SendParams, "session">;
|
|
28
|
+
export interface WaitOptions {
|
|
29
|
+
/** The cursor to wait from; now by default. */
|
|
30
|
+
after?: StreamCursor;
|
|
31
|
+
timeout_ms?: number;
|
|
32
|
+
/** Aborting it cancels the wait, which rejects with `cancelled`. */
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Starts the worker and its connection to the server at `url`. Resolves
|
|
37
|
+
* once the engine is loaded, before the connection is up: the worker
|
|
38
|
+
* connects, and reconnects after a loss, by itself, and the client's
|
|
39
|
+
* `onLink` (and each mounted terminal's) says how it goes. Rejects when
|
|
40
|
+
* the worker or the engine cannot be loaded.
|
|
41
|
+
*/
|
|
42
|
+
export declare function connect(options: ConnectOptions): Promise<Client>;
|
|
43
|
+
/**
|
|
44
|
+
* One connection to a server: each method is the protocol method of the
|
|
45
|
+
* same name, and rejects with a `ClientError` (the server's `code`, or
|
|
46
|
+
* `closed` when there is no connection). Terminals mount from it and share
|
|
47
|
+
* its connection.
|
|
48
|
+
*/
|
|
49
|
+
export declare class Client {
|
|
50
|
+
private readonly worker;
|
|
51
|
+
private nextId;
|
|
52
|
+
private readonly pending;
|
|
53
|
+
private readonly mounts;
|
|
54
|
+
private readonly terminals;
|
|
55
|
+
private readonly sessionListeners;
|
|
56
|
+
private readonly eventListeners;
|
|
57
|
+
private readonly linkListeners;
|
|
58
|
+
private latest;
|
|
59
|
+
private link;
|
|
60
|
+
private started;
|
|
61
|
+
private closed;
|
|
62
|
+
/** @internal Use `connect`. */
|
|
63
|
+
constructor(worker: Worker, started: (error?: Error) => void);
|
|
64
|
+
private setLink;
|
|
65
|
+
/** @internal */
|
|
66
|
+
post(message: ToWorker): void;
|
|
67
|
+
private call;
|
|
68
|
+
/** The server's catalog, or one method of it. */
|
|
69
|
+
describe(): Promise<Catalog>;
|
|
70
|
+
describe(method: string): Promise<Description>;
|
|
71
|
+
create(params?: CreateParams): Promise<Session>;
|
|
72
|
+
/** Every session, `list` paged to its end. */
|
|
73
|
+
sessions(): Promise<Session[]>;
|
|
74
|
+
/** One page of sessions, after the session id `after`. */
|
|
75
|
+
list(after?: string): Promise<Page>;
|
|
76
|
+
inspect(session: string): Promise<Session>;
|
|
77
|
+
/** Hangs up the session's processes (SIGHUP). */
|
|
78
|
+
end(session: string): Promise<void>;
|
|
79
|
+
/** Sends `signal` (`HUP`, `INT`, `TERM`, `KILL`, ...) to the session's processes. */
|
|
80
|
+
signal(session: string, signal: string): Promise<void>;
|
|
81
|
+
/** Removes a session that is `exited` or `restored`. */
|
|
82
|
+
remove(session: string): Promise<void>;
|
|
83
|
+
label(session: string, label: string): Promise<Session>;
|
|
84
|
+
/** Sets the size, the size policy, or both. */
|
|
85
|
+
resize(session: string, size: Omit<ResizeParams, "session">): Promise<void>;
|
|
86
|
+
/** Text, keys or bytes to the session's program, with a wait armed
|
|
87
|
+
* before they are written when `input.wait` is given; aborting
|
|
88
|
+
* `options.signal` cancels that wait. */
|
|
89
|
+
send(session: string, input: SendInput, options?: {
|
|
90
|
+
signal?: AbortSignal;
|
|
91
|
+
}): Promise<Sent>;
|
|
92
|
+
/** Waits on the server until one of `until` holds, or the timeout,
|
|
93
|
+
* which is a result. */
|
|
94
|
+
wait(session: string, until: Until, options?: WaitOptions): Promise<Waited>;
|
|
95
|
+
/** The screen, or the scope and format asked for. */
|
|
96
|
+
read(session: string, options?: Omit<ReadParams, "session">): Promise<Read>;
|
|
97
|
+
/** The stream as text, from the offset `after`. */
|
|
98
|
+
tail(session: string, after: number, options?: {
|
|
99
|
+
max_bytes?: number;
|
|
100
|
+
}): Promise<Tail>;
|
|
101
|
+
/** Marks the session's `done` and `error` records seen: all, or those named. */
|
|
102
|
+
ack(session: string, recordIds?: string[]): Promise<Acked>;
|
|
103
|
+
/** Ends another attachment, by its `channel` in the session's `attachments`. */
|
|
104
|
+
detach(session: string, channel: number, reason?: string): Promise<void>;
|
|
105
|
+
/** The connection's link, at each change: `connecting` with its
|
|
106
|
+
* attempt, `connected` (with no session), or `ended`, as a terminal's
|
|
107
|
+
* `onLink` reports the connection-level changes. Requests need
|
|
108
|
+
* `connected`. A listener added later gets the latest at once. */
|
|
109
|
+
onLink(listener: (link: Link) => void): () => void;
|
|
110
|
+
/** Every session on the server, at each change; a listener added once
|
|
111
|
+
* the list is known gets it at once. */
|
|
112
|
+
onSessions(listener: (sessions: Session[]) => void): () => void;
|
|
113
|
+
/** Each server event, in `seq` order, without loss across reconnects:
|
|
114
|
+
* the ones missed while the connection was down are replayed, or an
|
|
115
|
+
* `EventGap` says they cannot be. */
|
|
116
|
+
onEvent(listener: (event: Event | EventGap) => void): () => void;
|
|
117
|
+
/** Mounts a terminal on `options.canvas`, attached to `options.session`
|
|
118
|
+
* if given, on this client's connection. */
|
|
119
|
+
mount(options: MountOptions): Terminal;
|
|
120
|
+
/** Disposes the terminals and terminates the worker, which ends the
|
|
121
|
+
* connection; requests in flight reject with `closed`. */
|
|
122
|
+
close(): void;
|
|
123
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { ClientError } from "./connection.js";
|
|
2
|
+
import { mountOn } from "./mount.js";
|
|
3
|
+
/**
|
|
4
|
+
* Starts the worker and its connection to the server at `url`. Resolves
|
|
5
|
+
* once the engine is loaded, before the connection is up: the worker
|
|
6
|
+
* connects, and reconnects after a loss, by itself, and the client's
|
|
7
|
+
* `onLink` (and each mounted terminal's) says how it goes. Rejects when
|
|
8
|
+
* the worker or the engine cannot be loaded.
|
|
9
|
+
*/
|
|
10
|
+
export function connect(options) {
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const client = new Client(options.worker, (error) => {
|
|
13
|
+
if (error === undefined)
|
|
14
|
+
resolve(client);
|
|
15
|
+
else
|
|
16
|
+
reject(error);
|
|
17
|
+
});
|
|
18
|
+
client.post({
|
|
19
|
+
type: "init",
|
|
20
|
+
wasm: new URL(options.wasm, location.href).toString(),
|
|
21
|
+
url: options.url,
|
|
22
|
+
client: options.client,
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* One connection to a server: each method is the protocol method of the
|
|
28
|
+
* same name, and rejects with a `ClientError` (the server's `code`, or
|
|
29
|
+
* `closed` when there is no connection). Terminals mount from it and share
|
|
30
|
+
* its connection.
|
|
31
|
+
*/
|
|
32
|
+
export class Client {
|
|
33
|
+
worker;
|
|
34
|
+
nextId = 1;
|
|
35
|
+
pending = new Map();
|
|
36
|
+
mounts = new Map();
|
|
37
|
+
terminals = new Set();
|
|
38
|
+
sessionListeners = new Set();
|
|
39
|
+
eventListeners = new Set();
|
|
40
|
+
linkListeners = new Set();
|
|
41
|
+
latest;
|
|
42
|
+
link;
|
|
43
|
+
started = false;
|
|
44
|
+
closed = false;
|
|
45
|
+
/** @internal Use `connect`. */
|
|
46
|
+
constructor(worker, started) {
|
|
47
|
+
this.worker = worker;
|
|
48
|
+
// A worker script that does not load posts nothing, so `connect`
|
|
49
|
+
// would never settle. Once it runs, an error event is an exception in
|
|
50
|
+
// one of its handlers, which costs that message only: the browser
|
|
51
|
+
// reports it, and the client goes on.
|
|
52
|
+
worker.onerror = (e) => {
|
|
53
|
+
if (this.started)
|
|
54
|
+
return;
|
|
55
|
+
e.preventDefault?.();
|
|
56
|
+
started(new Error(`the worker failed: ${e.message || "it did not load"}`));
|
|
57
|
+
this.close();
|
|
58
|
+
};
|
|
59
|
+
worker.onmessage = (e) => {
|
|
60
|
+
const message = e.data;
|
|
61
|
+
switch (message.type) {
|
|
62
|
+
case "ready":
|
|
63
|
+
this.started = true;
|
|
64
|
+
started();
|
|
65
|
+
break;
|
|
66
|
+
case "failed":
|
|
67
|
+
started(new Error(message.message));
|
|
68
|
+
this.close();
|
|
69
|
+
break;
|
|
70
|
+
case "reply": {
|
|
71
|
+
const waiter = this.pending.get(message.id);
|
|
72
|
+
this.pending.delete(message.id);
|
|
73
|
+
waiter?.done();
|
|
74
|
+
if (message.error)
|
|
75
|
+
waiter?.reject(errorOf(message.error));
|
|
76
|
+
else
|
|
77
|
+
waiter?.resolve(message.result);
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
case "connection":
|
|
81
|
+
this.setLink(message.link);
|
|
82
|
+
break;
|
|
83
|
+
case "sessions":
|
|
84
|
+
this.latest = message.sessions;
|
|
85
|
+
for (const listener of this.sessionListeners)
|
|
86
|
+
listener(message.sessions);
|
|
87
|
+
break;
|
|
88
|
+
case "event":
|
|
89
|
+
for (const listener of this.eventListeners)
|
|
90
|
+
listener(message.event);
|
|
91
|
+
break;
|
|
92
|
+
case "gap":
|
|
93
|
+
for (const listener of this.eventListeners)
|
|
94
|
+
listener({ event: "gap", incarnation: message.incarnation });
|
|
95
|
+
break;
|
|
96
|
+
default:
|
|
97
|
+
this.mounts.get(message.mount)?.(message);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
setLink(link) {
|
|
102
|
+
this.link = link;
|
|
103
|
+
for (const listener of this.linkListeners)
|
|
104
|
+
listener(link);
|
|
105
|
+
}
|
|
106
|
+
/** @internal */
|
|
107
|
+
post(message) {
|
|
108
|
+
if (!this.closed)
|
|
109
|
+
this.worker.postMessage(message);
|
|
110
|
+
}
|
|
111
|
+
call(method, params, signal) {
|
|
112
|
+
if (this.closed)
|
|
113
|
+
return Promise.reject(new ClientError("closed", "closed"));
|
|
114
|
+
const id = this.nextId++;
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
// Cancelled by the server, so the rejection is its `cancelled`,
|
|
117
|
+
// also when the signal was aborted already.
|
|
118
|
+
const cancel = () => this.post({ type: "cancel", id });
|
|
119
|
+
const done = () => signal?.removeEventListener("abort", cancel);
|
|
120
|
+
this.pending.set(id, { resolve: resolve, reject, done });
|
|
121
|
+
this.post({ type: "request", id, method, params });
|
|
122
|
+
if (signal?.aborted)
|
|
123
|
+
cancel();
|
|
124
|
+
else
|
|
125
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
describe(method) {
|
|
129
|
+
return this.call("describe", method === undefined ? {} : { method });
|
|
130
|
+
}
|
|
131
|
+
create(params = {}) {
|
|
132
|
+
return this.call("create", params);
|
|
133
|
+
}
|
|
134
|
+
/** Every session, `list` paged to its end. */
|
|
135
|
+
async sessions() {
|
|
136
|
+
const all = [];
|
|
137
|
+
for (let page = await this.list();; page = await this.list(page.next)) {
|
|
138
|
+
all.push(...page.sessions);
|
|
139
|
+
if (page.next === undefined)
|
|
140
|
+
return all;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** One page of sessions, after the session id `after`. */
|
|
144
|
+
list(after) {
|
|
145
|
+
return this.call("list", after === undefined ? {} : { after });
|
|
146
|
+
}
|
|
147
|
+
inspect(session) {
|
|
148
|
+
return this.call("inspect", { session });
|
|
149
|
+
}
|
|
150
|
+
/** Hangs up the session's processes (SIGHUP). */
|
|
151
|
+
async end(session) {
|
|
152
|
+
await this.call("end", { session });
|
|
153
|
+
}
|
|
154
|
+
/** Sends `signal` (`HUP`, `INT`, `TERM`, `KILL`, ...) to the session's processes. */
|
|
155
|
+
async signal(session, signal) {
|
|
156
|
+
await this.call("signal", { session, signal });
|
|
157
|
+
}
|
|
158
|
+
/** Removes a session that is `exited` or `restored`. */
|
|
159
|
+
async remove(session) {
|
|
160
|
+
await this.call("remove", { session });
|
|
161
|
+
}
|
|
162
|
+
label(session, label) {
|
|
163
|
+
return this.call("label", { session, label });
|
|
164
|
+
}
|
|
165
|
+
/** Sets the size, the size policy, or both. */
|
|
166
|
+
async resize(session, size) {
|
|
167
|
+
await this.call("resize", { session, ...size });
|
|
168
|
+
}
|
|
169
|
+
/** Text, keys or bytes to the session's program, with a wait armed
|
|
170
|
+
* before they are written when `input.wait` is given; aborting
|
|
171
|
+
* `options.signal` cancels that wait. */
|
|
172
|
+
send(session, input, options = {}) {
|
|
173
|
+
return this.call("send", { session, ...input }, options.signal);
|
|
174
|
+
}
|
|
175
|
+
/** Waits on the server until one of `until` holds, or the timeout,
|
|
176
|
+
* which is a result. */
|
|
177
|
+
wait(session, until, options = {}) {
|
|
178
|
+
const { signal, after, timeout_ms } = options;
|
|
179
|
+
return this.call("wait", { session, until, ...(after !== undefined && { after }), ...(timeout_ms !== undefined && { timeout_ms }) }, signal);
|
|
180
|
+
}
|
|
181
|
+
/** The screen, or the scope and format asked for. */
|
|
182
|
+
read(session, options = {}) {
|
|
183
|
+
return this.call("read", { session, ...options });
|
|
184
|
+
}
|
|
185
|
+
/** The stream as text, from the offset `after`. */
|
|
186
|
+
tail(session, after, options = {}) {
|
|
187
|
+
return this.call("tail", { session, after, ...options });
|
|
188
|
+
}
|
|
189
|
+
/** Marks the session's `done` and `error` records seen: all, or those named. */
|
|
190
|
+
ack(session, recordIds) {
|
|
191
|
+
return this.call("ack", { session, ...(recordIds !== undefined && { record_ids: recordIds }) });
|
|
192
|
+
}
|
|
193
|
+
/** Ends another attachment, by its `channel` in the session's `attachments`. */
|
|
194
|
+
async detach(session, channel, reason) {
|
|
195
|
+
await this.call("detach", { session, channel, ...(reason !== undefined && { reason }) });
|
|
196
|
+
}
|
|
197
|
+
/** The connection's link, at each change: `connecting` with its
|
|
198
|
+
* attempt, `connected` (with no session), or `ended`, as a terminal's
|
|
199
|
+
* `onLink` reports the connection-level changes. Requests need
|
|
200
|
+
* `connected`. A listener added later gets the latest at once. */
|
|
201
|
+
onLink(listener) {
|
|
202
|
+
this.linkListeners.add(listener);
|
|
203
|
+
if (this.link)
|
|
204
|
+
listener(this.link);
|
|
205
|
+
return () => void this.linkListeners.delete(listener);
|
|
206
|
+
}
|
|
207
|
+
/** Every session on the server, at each change; a listener added once
|
|
208
|
+
* the list is known gets it at once. */
|
|
209
|
+
onSessions(listener) {
|
|
210
|
+
this.sessionListeners.add(listener);
|
|
211
|
+
if (this.latest)
|
|
212
|
+
listener(this.latest);
|
|
213
|
+
return () => void this.sessionListeners.delete(listener);
|
|
214
|
+
}
|
|
215
|
+
/** Each server event, in `seq` order, without loss across reconnects:
|
|
216
|
+
* the ones missed while the connection was down are replayed, or an
|
|
217
|
+
* `EventGap` says they cannot be. */
|
|
218
|
+
onEvent(listener) {
|
|
219
|
+
this.eventListeners.add(listener);
|
|
220
|
+
return () => void this.eventListeners.delete(listener);
|
|
221
|
+
}
|
|
222
|
+
/** Mounts a terminal on `options.canvas`, attached to `options.session`
|
|
223
|
+
* if given, on this client's connection. */
|
|
224
|
+
mount(options) {
|
|
225
|
+
if (this.closed)
|
|
226
|
+
throw new ClientError("closed", "closed");
|
|
227
|
+
const id = this.nextId++;
|
|
228
|
+
const host = {
|
|
229
|
+
send: (message) => this.post(message),
|
|
230
|
+
receive: (handler) => {
|
|
231
|
+
if (handler)
|
|
232
|
+
this.mounts.set(id, handler);
|
|
233
|
+
else
|
|
234
|
+
this.mounts.delete(id);
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
const terminal = mountOn(host, id, options);
|
|
238
|
+
const dispose = terminal.dispose;
|
|
239
|
+
terminal.dispose = () => {
|
|
240
|
+
this.terminals.delete(terminal);
|
|
241
|
+
dispose();
|
|
242
|
+
};
|
|
243
|
+
this.terminals.add(terminal);
|
|
244
|
+
return terminal;
|
|
245
|
+
}
|
|
246
|
+
/** Disposes the terminals and terminates the worker, which ends the
|
|
247
|
+
* connection; requests in flight reject with `closed`. */
|
|
248
|
+
close() {
|
|
249
|
+
if (this.closed)
|
|
250
|
+
return;
|
|
251
|
+
for (const terminal of [...this.terminals])
|
|
252
|
+
terminal.dispose();
|
|
253
|
+
this.closed = true;
|
|
254
|
+
this.worker.onmessage = null;
|
|
255
|
+
this.worker.terminate();
|
|
256
|
+
for (const waiter of this.pending.values()) {
|
|
257
|
+
waiter.done();
|
|
258
|
+
waiter.reject(new ClientError("closed", "closed"));
|
|
259
|
+
}
|
|
260
|
+
this.pending.clear();
|
|
261
|
+
this.sessionListeners.clear();
|
|
262
|
+
this.eventListeners.clear();
|
|
263
|
+
this.linkListeners.clear();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function errorOf(failure) {
|
|
267
|
+
return new ClientError(failure.kind, failure.message, failure.server);
|
|
268
|
+
}
|