@gjermundgaraba/clankermux 0.1.0 → 0.1.1

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 ADDED
@@ -0,0 +1,97 @@
1
+ # @gjermundgaraba/clankermux
2
+
3
+ The browser client of [clankermux](https://github.com/gjermundgaraba/clankermux): a terminal on a canvas, its engine and connection in a module worker, speaking the clankermux protocol over the server's TLS WebSocket carrier.
4
+
5
+ | Subpath | Exports |
6
+ | --- | --- |
7
+ | `.` | `mountTerminal` and its types, `ClientError` |
8
+ | `./worker` | `runWorker`, for the worker module; no DOM types |
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 |
11
+
12
+ ```ts
13
+ // worker.ts, started as a module worker
14
+ import { runWorker } from "@gjermundgaraba/clankermux/worker";
15
+ runWorker(self);
16
+
17
+ // page
18
+ import { mountTerminal } from "@gjermundgaraba/clankermux";
19
+ import wasm from "@gjermundgaraba/clankermux/ghostty-vt.wasm?url";
20
+ const terminal = mountTerminal({
21
+ worker: new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }),
22
+ canvas, container, wasm, url: "wss://127.0.0.1:7438/", session,
23
+ font: "14px monospace", colors: () => ({ fg: "#d8dee9", bg: "#282c34", cursor: "#ffffff" }),
24
+ onLink: (link) => console.log(link),
25
+ });
26
+ ```
27
+
28
+ ## `MountedTerminal`
29
+
30
+ | Method | Does |
31
+ | --- | --- |
32
+ | `attach(session)` | Detaches the current session and attaches `session`; after a connection-level end (below), connects again first. |
33
+ | `create(options?)` | Creates a session at the current size, attaches it, and resolves with it. `options.onExit`: `"keep"` keeps it listed as `exited` when its program exits; `"remove"` removes it `limits.remove_grace` after. Without it the server's default (`remove`) applies. |
34
+ | `end()` | Hangs up the attached session's processes (SIGHUP). Also resolves when the session is not running (`exited`, `restored`): there is nothing to end. |
35
+ | `remove()` | Removes the attached session, which must be `exited` or `restored`; a running one rejects with `running`. |
36
+ | `report()` | Reports the container's size, the colours and the scheme again. |
37
+ | `paste(text)` | Pastes, bracketed when the program asked for it. |
38
+ | `dispose()` | Removes the listeners and terminates the worker, which drops its connection; requests in flight reject. |
39
+
40
+ `create`, `end` and `remove` need a connection: call them after a `connected` link. They reject with a `ClientError`:
41
+
42
+ - with `kind: "server"` and `server.code` when the server refuses;
43
+ - with `kind: "closed"` when there is no connection, or after `dispose()`;
44
+ - with `kind: "protocol"` when the server sent a malformed frame meanwhile (the connection then ends with `ended closed`, `retry: true`).
45
+
46
+ `end` and `remove` reject with a plain `Error` when no session is attached. Since 0.1.1 `create` returns this promise, where it returned nothing and dropped a request it could not make; a caller that ignores it should `.catch` it. Closing a pane for good is `end()` for a running session and `remove()` for one that has exited, or that a previous server left `restored`. With `onExit: "remove"` an ended session also removes itself.
47
+
48
+ ## `onLink`
49
+
50
+ `onLink(link)` reports each change of the page's link to its session, through the connection and the attachment. `onStatus(text)` reports the same moments, and more, as text for display.
51
+
52
+ ```ts
53
+ type Link =
54
+ | { state: "connecting"; attempt: number }
55
+ | { state: "connected"; session: Session | undefined }
56
+ | { state: "ended"; reason: LinkEnd; code?: ErrorCode; message?: string; exit?: Exit; retry: boolean };
57
+ type LinkEnd = "closed" | "removed" | "stopping" | "exited" | "no_such_session" | "engine_mismatch" | "error";
58
+ ```
59
+
60
+ `retry` means the worker reconnects or attaches again by itself, so a `connecting` or `connected` follows. Otherwise nothing follows until the page calls `attach` or `create`. After a connection-level end (the last three rows of the first table) there is no connection: `create` rejects, and `attach` connects again (`connecting` from attempt 1), so "Retry" can be `attach`. An engine that failed to load needs a new mount.
61
+
62
+ | When | Link |
63
+ | --- | --- |
64
+ | A connection is opened: at mount, and at each reconnect | `connecting`, `attempt` from 1; it starts again at 1 once a server answers |
65
+ | A connection cannot be opened, or closes before `WELCOME` | nothing at once; the next `connecting` after a backoff |
66
+ | The connection closes | `ended closed`, `retry: true`, then `connecting` |
67
+ | The engine cannot be loaded | `ended error`, `retry: false` |
68
+ | 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` |
69
+ | The server ends the connection (`ERROR` without an id, e.g. `protocol_error`) | `ended error` with the code, `retry: false` |
70
+ | `subscribe` fails on a live connection | `ended error`, `retry: false`; the worker closes the connection |
71
+
72
+ Once connected:
73
+
74
+ | When | Link |
75
+ | --- | --- |
76
+ | Connected with no session to attach | `connected`, `session: undefined` |
77
+ | 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` |
78
+ | 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) |
79
+ | The session's program exits (`EXITED`) | `ended exited` with `exit`, `retry: false` |
80
+ | `CLOSED removed` | `ended removed`, `retry: false`; the worker forgets the session |
81
+ | `CLOSED stopping` | `ended stopping`, `retry: true`; the connection's close follows, and the reconnect attaches the session again (as `restored`) |
82
+ | `OPEN` refused, or the attachment ended, with `no_such_session` or `engine_mismatch` | `ended` with that reason and code, `retry: false` |
83
+ | The attachment ended with `invalid_request` | `ended error`, `retry: false` |
84
+ | 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 |
85
+ | The stream lost its place (an `OUTPUT` at an unexpected offset) | `ended error`, `retry: true`; the worker attaches again afresh |
86
+ | Any other fault in the attachment's frames | `ended error`, `retry: false` |
87
+
88
+ Nothing fires for:
89
+
90
+ - the errors that keep an attachment (`read_only`, `not_running`, `input_overflow`);
91
+ - a gap, until its new screen fires `connected`;
92
+ - `attach` or `create` before their screen;
93
+ - `dispose`.
94
+
95
+ `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.
96
+
97
+ "The server ended an answered connection with an error, and nothing will reconnect" is `ended` with `reason: "error"` and `retry: false` after a `connected`, with no `connecting` after it. An attached session is the latest `connected` with a `session`.
@@ -5,5 +5,6 @@ export type { ErrorKind, Transport } from "./connection.ts";
5
5
  export { Osc52Scanner } from "./osc52.ts";
6
6
  export type { ClipboardWrite } from "./osc52.ts";
7
7
  export { mountTerminal } from "./mount.ts";
8
- export type { Colors, MountOptions, MountedTerminal } from "./mount.ts";
9
- export type { Scheme, Session } from "../proto/index.ts";
8
+ export type { Colors, CreateOptions, MountOptions, MountedTerminal } from "./mount.ts";
9
+ export type { Link, LinkEnd } from "./worker.ts";
10
+ export type { ErrorCode, Exit, OnExit, Scheme, Session } from "../proto/index.ts";
@@ -1,6 +1,7 @@
1
1
  /** The page side of a terminal: canvas, keyboard, paste and resize, with
2
2
  * the engine in a worker running `runWorker`. */
3
- import type { Scheme, Session } from "../proto/index.ts";
3
+ import type { OnExit, Scheme, Session } from "../proto/index.ts";
4
+ import type { Link } from "./worker.ts";
4
5
  /** The terminal's default colours as CSS colours (hex or `rgb()`). */
5
6
  export interface Colors {
6
7
  fg: string;
@@ -28,19 +29,37 @@ export interface MountOptions {
28
29
  /** The colour scheme reported to the session; the page's preferred
29
30
  * scheme by default. */
30
31
  scheme?: () => Scheme;
32
+ /** A line of text for each change, for display. */
31
33
  onStatus?: (text: string) => void;
34
+ /** Each change of the link to the session, to switch on. */
35
+ onLink?: (link: Link) => void;
32
36
  onSessions?: (sessions: Session[], current: string | undefined) => void;
33
37
  }
38
+ export interface CreateOptions {
39
+ /** `keep`: the session stays listed as `exited` when its program
40
+ * exits; `remove`: it is removed `limits.remove_grace` after. The
41
+ * server's default (`remove`) when absent. */
42
+ onExit?: OnExit;
43
+ }
34
44
  export interface MountedTerminal {
35
45
  /** Detaches the current session and attaches `session`. */
36
46
  attach(session: string): void;
37
- /** Creates a session at the current size and attaches it. */
38
- create(): void;
47
+ /** Creates a session at the current size and attaches it; resolves
48
+ * with it as created. Like `end` and `remove`, it needs a connection:
49
+ * call it after a `connected` link. */
50
+ create(options?: CreateOptions): Promise<Session>;
51
+ /** Hangs up the attached session's processes (SIGHUP); its exit
52
+ * follows as a link `ended` with reason `exited`. Resolves too when the
53
+ * session is not running (`exited` or `restored`). */
54
+ end(): Promise<void>;
55
+ /** Removes the attached session, which must be `exited` or `restored`
56
+ * (else `running`); the link ends with `removed`. */
57
+ remove(): Promise<void>;
39
58
  /** Reports the container's size, the colours and the scheme again. */
40
59
  report(): void;
41
60
  paste(text: string): void;
42
61
  /** Removes the listeners and terminates the worker, which ends its
43
- * connection. */
62
+ * connection; requests in flight reject. */
44
63
  dispose(): void;
45
64
  }
46
65
  export declare function mountTerminal(options: MountOptions): MountedTerminal;
@@ -1,4 +1,5 @@
1
1
  import { CanvasRenderer } from "../renderer/index.js";
2
+ import { ClientError } from "./connection.js";
2
3
  import { browserKeeps, keyInput } from "./keyboard.js";
3
4
  import { profileFrom } from "./profile.js";
4
5
  /** Cell metrics from the font. */
@@ -62,12 +63,40 @@ export function mountTerminal(options) {
62
63
  .then((map) => (keyboard.layout = map))
63
64
  .catch(() => { });
64
65
  const send = (message) => worker.postMessage(message);
66
+ /** Requests waiting for their `done`, by id. They reject with a
67
+ * `ClientError` for a server's refusal, a lost connection or a
68
+ * disposed terminal, or an `Error` when no session is attached. */
69
+ const pending = new Map();
70
+ let nextId = 1;
71
+ let disposed = false;
72
+ function request(message) {
73
+ if (disposed)
74
+ return Promise.reject(new ClientError("closed", "disposed"));
75
+ const id = nextId++;
76
+ return new Promise((resolve, reject) => {
77
+ pending.set(id, { resolve, reject });
78
+ send(message(id));
79
+ });
80
+ }
81
+ const failure = (error) => error.kind ? new ClientError(error.kind, error.message, error.server) : new Error(error.message);
65
82
  worker.onmessage = (e) => {
66
83
  const message = e.data;
67
84
  switch (message.type) {
68
85
  case "status":
69
86
  options.onStatus?.(message.text);
70
87
  break;
88
+ case "link":
89
+ options.onLink?.(message.link);
90
+ break;
91
+ case "done": {
92
+ const waiter = pending.get(message.id);
93
+ pending.delete(message.id);
94
+ if (message.error)
95
+ waiter?.reject(failure(message.error));
96
+ else
97
+ waiter?.resolve(message.session);
98
+ break;
99
+ }
71
100
  case "frame":
72
101
  fitCanvas(message.frame.cols, message.frame.rows);
73
102
  if (fullNext && !message.frame.full) {
@@ -126,14 +155,23 @@ export function mountTerminal(options) {
126
155
  });
127
156
  return {
128
157
  attach: (session) => send({ type: "attach", session }),
129
- create: () => send({ type: "create" }),
158
+ create: async (create) => {
159
+ const session = await request((id) => ({ type: "create", id, ...(create?.onExit && { onExit: create.onExit }) }));
160
+ return session;
161
+ },
162
+ end: async () => void (await request((id) => ({ type: "end", id }))),
163
+ remove: async () => void (await request((id) => ({ type: "remove", id }))),
130
164
  report,
131
165
  paste: (text) => send({ type: "paste", text }),
132
166
  dispose: () => {
167
+ disposed = true;
133
168
  listening.abort();
134
169
  resizes.disconnect();
135
170
  worker.onmessage = null;
136
171
  worker.terminate();
172
+ for (const waiter of pending.values())
173
+ waiter.reject(new ClientError("closed", "disposed"));
174
+ pending.clear();
137
175
  },
138
176
  };
139
177
  }
@@ -5,7 +5,50 @@
5
5
  * typechecked without the DOM library does not see the page's types.
6
6
  */
7
7
  import { type Frame, type KeyInput } from "../engine/index.ts";
8
- import { type Profile, type Session, type Size } from "../proto/index.ts";
8
+ import { type ErrorCode, type ErrorMessage, type Exit, type OnExit, type Profile, type Session, type Size } from "../proto/index.ts";
9
+ import { type ErrorKind } from "./connection.ts";
10
+ /** Why the link to the session ended. `closed`: the connection closed
11
+ * (not a `CLOSED` frame, which the worker does not wait for when it
12
+ * detaches); `removed` and `stopping`: the server's `CLOSED`; `exited`:
13
+ * the session's program exited; `no_such_session` and `engine_mismatch`:
14
+ * an `OPEN` refused; `error`: any other error, the server's or the
15
+ * client's own. */
16
+ export type LinkEnd = "closed" | "removed" | "stopping" | "exited" | "no_such_session" | "engine_mismatch" | "error";
17
+ /** The page's link to its session, through the connection and the
18
+ * attachment. */
19
+ export type Link =
20
+ /** Opening a connection; `attempt` counts from 1 and starts again once
21
+ * a server answers. */
22
+ {
23
+ state: "connecting";
24
+ attempt: number;
25
+ }
26
+ /** Connected, and showing `session` as `ATTACHED` described it (its
27
+ * `status` may be `restored` or `exited`), or attached to none. */
28
+ | {
29
+ state: "connected";
30
+ session: Session | undefined;
31
+ }
32
+ /** The link ended. `code` and `message` are the error's, when there is
33
+ * one; `exit` is the program's, for `exited`. `retry`: the worker
34
+ * reconnects or attaches again by itself, so `connecting` or
35
+ * `connected` follows; otherwise nothing does until the page attaches
36
+ * or creates. */
37
+ | {
38
+ state: "ended";
39
+ reason: LinkEnd;
40
+ code?: ErrorCode;
41
+ message?: string;
42
+ exit?: Exit;
43
+ retry: boolean;
44
+ };
45
+ /** A failed request, as it crosses to the page. */
46
+ export interface Failure {
47
+ /** Absent for a request that needs a session when none is attached. */
48
+ kind?: ErrorKind;
49
+ message: string;
50
+ server?: ErrorMessage;
51
+ }
9
52
  /** Messages from the page to the worker. */
10
53
  export type ToWorker = {
11
54
  type: "init";
@@ -17,8 +60,18 @@ export type ToWorker = {
17
60
  } | {
18
61
  type: "attach";
19
62
  session: string;
20
- } | {
63
+ }
64
+ /** Each request is answered by a `done` with its `id`. */
65
+ | {
21
66
  type: "create";
67
+ id: number;
68
+ onExit?: OnExit;
69
+ } | {
70
+ type: "end";
71
+ id: number;
72
+ } | {
73
+ type: "remove";
74
+ id: number;
22
75
  } | {
23
76
  type: "key";
24
77
  input: KeyInput;
@@ -38,6 +91,14 @@ export type ToWorker = {
38
91
  export type ToPage = {
39
92
  type: "status";
40
93
  text: string;
94
+ } | {
95
+ type: "link";
96
+ link: Link;
97
+ } | {
98
+ type: "done";
99
+ id: number;
100
+ session?: Session;
101
+ error?: Failure;
41
102
  } | {
42
103
  type: "frame";
43
104
  frame: Frame;
@@ -69,6 +69,21 @@ class Client {
69
69
  /** Shared by reconnects and re-attaches after a failure; reset by a screen. */
70
70
  backoff = BACKOFF_MIN_MS;
71
71
  reopenTimer;
72
+ /** Connection attempts since a server last answered. */
73
+ attempt = 0;
74
+ /** The connection ended for good with the server's refusal or error;
75
+ * `attach` connects again. */
76
+ refused = false;
77
+ link(link) {
78
+ this.post({ type: "link", link });
79
+ }
80
+ /** The link ended with `error`: the server's, else the client's own. */
81
+ endedWith(err, retry) {
82
+ const server = err instanceof ClientError ? err.server : undefined;
83
+ this.link(server
84
+ ? { state: "ended", reason: linkEnd(server.code), code: server.code, message: server.message, retry }
85
+ : { state: "ended", reason: "error", message: err instanceof Error ? err.message : String(err), retry });
86
+ }
72
87
  delay() {
73
88
  const delay = this.backoff;
74
89
  this.backoff = Math.min(this.backoff * 2, BACKOFF_MAX_MS);
@@ -80,14 +95,22 @@ class Client {
80
95
  this.profile = message.profile;
81
96
  this.session = message.session;
82
97
  this.post({ type: "status", text: "loading engine" });
83
- const wasm = await (await fetch(message.wasm)).arrayBuffer();
84
- this.engine = await Engine.load(wasm);
98
+ try {
99
+ const wasm = await (await fetch(message.wasm)).arrayBuffer();
100
+ this.engine = await Engine.load(wasm);
101
+ }
102
+ catch (err) {
103
+ this.post({ type: "status", text: `cannot load the engine: ${err}` });
104
+ this.endedWith(err, false);
105
+ return;
106
+ }
85
107
  this.render = new RenderState(this.engine);
86
108
  this.keys = new KeyEncoder(this.engine);
87
109
  await this.connect();
88
110
  }
89
111
  async connect() {
90
112
  this.post({ type: "status", text: this.attachment ? "reconnecting" : "connecting" });
113
+ this.link({ state: "connecting", attempt: ++this.attempt });
91
114
  let conn;
92
115
  try {
93
116
  conn = await Connection.connect(await SocketTransport.connect(this.url), hello("clankermux-web", ENGINE));
@@ -96,11 +119,14 @@ class Client {
96
119
  // A server that answers and refuses is not retried; a lost one is.
97
120
  if (err instanceof ClientError && (err.kind === "server" || err.kind === "protocol")) {
98
121
  this.post({ type: "status", text: err.message });
122
+ this.refused = true;
123
+ this.endedWith(err, false);
99
124
  return;
100
125
  }
101
126
  setTimeout(() => void this.connect(), this.delay());
102
127
  return;
103
128
  }
129
+ this.attempt = 0;
104
130
  this.conn = conn;
105
131
  conn.onEnd = (err) => {
106
132
  if (this.conn !== conn)
@@ -108,8 +134,11 @@ class Client {
108
134
  this.conn = undefined;
109
135
  if (err.kind === "server") {
110
136
  this.post({ type: "status", text: err.message });
137
+ this.refused = true;
138
+ this.endedWith(err, false);
111
139
  }
112
140
  else {
141
+ this.link({ state: "ended", reason: "closed", retry: true });
113
142
  setTimeout(() => void this.connect(), this.delay());
114
143
  }
115
144
  };
@@ -129,13 +158,24 @@ class Client {
129
158
  }
130
159
  catch (err) {
131
160
  this.post({ type: "status", text: String(err) });
161
+ // A lost connection is reported through onEnd, which ran first; a
162
+ // refused subscription ends this one for good.
163
+ if (this.conn === conn) {
164
+ this.conn = undefined;
165
+ conn.close();
166
+ this.refused = true;
167
+ this.endedWith(err, false);
168
+ }
132
169
  return;
133
170
  }
134
171
  this.postSessions();
135
- if (this.session !== undefined)
172
+ if (this.session !== undefined) {
136
173
  this.open();
137
- else
174
+ }
175
+ else {
138
176
  this.post({ type: "status", text: "no session" });
177
+ this.link({ state: "connected", session: undefined });
178
+ }
139
179
  }
140
180
  event(event) {
141
181
  switch (event.event) {
@@ -181,7 +221,9 @@ class Client {
181
221
  // A lost place in the stream: CLOSE and OPEN again, afresh. Any
182
222
  // other fault would only repeat.
183
223
  this.post({ type: "status", text: String(err) });
184
- if (err instanceof ClientError && err.kind === "desync")
224
+ const desync = err instanceof ClientError && err.kind === "desync";
225
+ this.endedWith(err, desync);
226
+ if (desync)
185
227
  this.reopen();
186
228
  else
187
229
  this.giveUp();
@@ -189,6 +231,11 @@ class Client {
189
231
  }
190
232
  if (frame.header.type === FrameType.Attached && actions.length === 0) {
191
233
  this.post({ type: "status", text: "attached" });
234
+ // Resumed: the terminal shows the stream already, and an exit
235
+ // still to come arrives as EXITED. A snapshot's screen comes
236
+ // later, as an action.
237
+ if (attachment.resume())
238
+ this.link({ state: "connected", session: attachment.session });
192
239
  }
193
240
  for (const action of actions)
194
241
  this.apply(action);
@@ -198,6 +245,14 @@ class Client {
198
245
  this.post({ type: "status", text: String(err) });
199
246
  }
200
247
  }
248
+ /** The screen of `session` is shown: `connected`, and at once `ended
249
+ * exited` when its program has exited already. */
250
+ attached(session) {
251
+ this.link({ state: "connected", session });
252
+ if (session?.status === "exited") {
253
+ this.link({ state: "ended", reason: "exited", ...(session.exit && { exit: session.exit }), retry: false });
254
+ }
255
+ }
201
256
  /** Detaches for good: a reconnect does not try the session again. */
202
257
  giveUp() {
203
258
  this.detach();
@@ -227,6 +282,7 @@ class Client {
227
282
  ? `exited: ${describe(session.exit)}`
228
283
  : "attached";
229
284
  this.post({ type: "status", text });
285
+ this.attached(session);
230
286
  break;
231
287
  }
232
288
  case "output":
@@ -244,6 +300,7 @@ class Client {
244
300
  case "exited":
245
301
  this.paint();
246
302
  this.post({ type: "status", text: `exited: ${describe(action.exit)}` });
303
+ this.link({ state: "ended", reason: "exited", exit: action.exit, retry: false });
247
304
  break;
248
305
  case "gap":
249
306
  this.clipboard.reset();
@@ -251,19 +308,28 @@ class Client {
251
308
  break;
252
309
  case "closed":
253
310
  this.post({ type: "status", text: `closed: ${action.reason}` });
311
+ // `stopping` is followed by the connection's close, and the
312
+ // reconnect attaches again; a removed session is gone for good.
313
+ this.link({ state: "ended", reason: action.reason, retry: action.reason === "stopping" });
314
+ if (action.reason === "removed")
315
+ this.giveUp();
254
316
  break;
255
- case "error":
317
+ case "error": {
256
318
  this.post({ type: "status", text: `${action.error.code}: ${action.error.message}` });
257
319
  // An error ended the attachment: attach again after a backoff
258
320
  // (`too_slow`, a snapshot that could not be taken), unless a new
259
321
  // OPEN would fail the same way.
260
- if (this.attachment?.closed()) {
261
- if (PERMANENT.has(action.error.code))
262
- this.giveUp();
263
- else
264
- this.reopen();
265
- }
322
+ if (!this.attachment?.closed())
323
+ break;
324
+ const { code, message } = action.error;
325
+ const retry = !PERMANENT.has(code);
326
+ this.link({ state: "ended", reason: linkEnd(code), code, message, retry });
327
+ if (retry)
328
+ this.reopen();
329
+ else
330
+ this.giveUp();
266
331
  break;
332
+ }
267
333
  }
268
334
  }
269
335
  /** The page's colours on the local terminal, as the server has them on
@@ -322,24 +388,67 @@ class Client {
322
388
  this.attachment.free();
323
389
  this.attachment = undefined;
324
390
  }
391
+ /** Attaches `session`; after the server refused or ended the
392
+ * connection, connects again first. */
325
393
  attach(session) {
326
394
  this.detach();
327
395
  this.writes = Promise.resolve();
328
396
  this.session = session;
329
397
  this.postSessions();
330
- this.open();
398
+ if (this.refused) {
399
+ this.refused = false;
400
+ this.attempt = 0;
401
+ void this.connect();
402
+ }
403
+ else {
404
+ this.open();
405
+ }
331
406
  }
332
- async create() {
407
+ /** Creates a session at the current size and attaches it; `on_exit`
408
+ * only when given, so the server's default holds otherwise. */
409
+ async create(id, onExit) {
333
410
  const conn = this.conn;
334
411
  if (!conn)
335
- return;
412
+ return this.fail(id, new ClientError("closed", "not connected"));
413
+ const params = { cols: this.viewport.cols, rows: this.viewport.rows };
414
+ if (onExit !== undefined)
415
+ params.on_exit = onExit;
416
+ let session;
336
417
  try {
337
- const session = await conn.call("create", { cols: this.viewport.cols, rows: this.viewport.rows });
338
- this.attach(session.id);
418
+ session = await conn.call("create", params);
339
419
  }
340
420
  catch (err) {
341
421
  this.post({ type: "status", text: String(err) });
422
+ return this.fail(id, err);
342
423
  }
424
+ this.attach(session.id);
425
+ this.post({ type: "done", id, session });
426
+ }
427
+ /** `end` (SIGHUP) or `remove` for the session attached or being
428
+ * attached. `not_running` from `end` is success: there is nothing left
429
+ * to end. */
430
+ async request(id, method) {
431
+ const conn = this.conn;
432
+ const session = this.session;
433
+ if (!conn)
434
+ return this.fail(id, new ClientError("closed", "not connected"));
435
+ if (session === undefined)
436
+ return this.fail(id, new Error("no session is attached"));
437
+ try {
438
+ await conn.call(method, { session });
439
+ }
440
+ catch (err) {
441
+ if (!(method === "end" && err instanceof ClientError && err.server?.code === "not_running")) {
442
+ return this.fail(id, err);
443
+ }
444
+ }
445
+ this.post({ type: "done", id });
446
+ }
447
+ fail(id, err) {
448
+ const error = err instanceof ClientError
449
+ ? { kind: err.kind, message: err.message, ...(err.server && { server: err.server }) }
450
+ : { message: err instanceof Error ? err.message : String(err) };
451
+ this.post({ type: "done", id, error });
343
452
  }
344
453
  /** Input for the session, dropped unless attached on a live connection.
345
454
  * Keys go as INPUT; a paste goes as `write` requests, each answered
@@ -406,6 +515,10 @@ class Client {
406
515
  }
407
516
  }
408
517
  }
518
+ /** The reason an error code ends the link with. */
519
+ function linkEnd(code) {
520
+ return code === "no_such_session" || code === "engine_mismatch" ? code : "error";
521
+ }
409
522
  function describe(exit) {
410
523
  return "code" in exit ? `code ${exit.code}` : `signal ${exit.signal}`;
411
524
  }
@@ -423,7 +536,11 @@ export function runWorker(port) {
423
536
  client.attach(message.session);
424
537
  break;
425
538
  case "create":
426
- void client.create();
539
+ void client.create(message.id, message.onExit);
540
+ break;
541
+ case "end":
542
+ case "remove":
543
+ void client.request(message.id, message.type);
427
544
  break;
428
545
  case "key":
429
546
  client.key(message.input);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/clankermux",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",