@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.
@@ -1,4 +1,4 @@
1
- import { type ErrorMessage, type Event, type Frame, FrameType, type Hello, type Welcome } from "../proto/index.ts";
1
+ import { type Catalog, type Description, type ErrorCode, type ErrorMessage, type Event, type Frame, FrameType, type Hello, type Peer, type Welcome } from "../proto/index.ts";
2
2
  /** A message-oriented byte transport: one frame per message, as over WebSocket. */
3
3
  export interface Transport {
4
4
  send(bytes: Uint8Array): void;
@@ -9,15 +9,22 @@ export interface Transport {
9
9
  /** `desync`: a stream frame did not continue from the cursor; a fresh
10
10
  * OPEN recovers it, where any other fault would only repeat. */
11
11
  export type ErrorKind = "protocol" | "desync" | "server" | "closed";
12
+ /** A failed request or connection. `kind: "server"` carries the server's
13
+ * `ERROR` as `server`, and its code as `code`: a refused request, or a
14
+ * `wait` that was cancelled (`cancelled`). */
12
15
  export declare class ClientError extends Error {
13
16
  readonly kind: ErrorKind;
14
17
  readonly server?: ErrorMessage | undefined;
18
+ /** The protocol's error code, when the server sent one. */
19
+ readonly code: ErrorCode | undefined;
15
20
  constructor(kind: ErrorKind, message: string, server?: ErrorMessage | undefined);
16
21
  static protocol(message: string): ClientError;
17
22
  static desync(message: string): ClientError;
18
23
  static fromServer(error: ErrorMessage): ClientError;
19
24
  }
20
- export declare function hello(name: string, engine?: string): Hello;
25
+ /** `HELLO` for `client`: a name and version, or a name with this
26
+ * package's version. */
27
+ export declare function hello(client: string | Peer, engine?: string): Hello;
21
28
  /**
22
29
  * One protocol connection: the handshake, requests answered by id, events,
23
30
  * and attachment channels routed to their receivers.
@@ -40,6 +47,14 @@ export declare class Connection {
40
47
  sendJson(type: FrameType, channel: number, body: unknown): void;
41
48
  /** A request; the reply's `result`, or a rejection with the server's error. */
42
49
  call<R>(method: string, params: unknown): Promise<R>;
50
+ /** A request and its id on this connection, which `cancel` takes. */
51
+ request<R>(method: string, params: unknown): {
52
+ id: number;
53
+ reply: Promise<R>;
54
+ };
55
+ /** The server's catalog (`describe {}`), or one method of it. */
56
+ describe(): Promise<Catalog>;
57
+ describe(method: string): Promise<Description>;
43
58
  /** Opens `channel`; its frames go to `receive` until `release` or the
44
59
  * connection's end. */
45
60
  open(channel: number, open: unknown, receive: (frame: Frame) => void): void;
@@ -1,12 +1,19 @@
1
1
  import { FrameError, FrameType, encodeFrame, parseFrame, VERSION, } from "../proto/index.js";
2
2
  import pkg from "../../package.json" with { type: "json" };
3
+ /** A failed request or connection. `kind: "server"` carries the server's
4
+ * `ERROR` as `server`, and its code as `code`: a refused request, or a
5
+ * `wait` that was cancelled (`cancelled`). */
3
6
  export class ClientError extends Error {
4
7
  kind;
5
8
  server;
9
+ /** The protocol's error code, when the server sent one. */
10
+ code;
6
11
  constructor(kind, message, server) {
7
12
  super(message);
8
13
  this.kind = kind;
9
14
  this.server = server;
15
+ this.name = "ClientError";
16
+ this.code = server?.code;
10
17
  }
11
18
  static protocol(message) {
12
19
  return new ClientError("protocol", message);
@@ -21,8 +28,11 @@ export class ClientError extends Error {
21
28
  /** Frames before `WELCOME` tells us the real limit: the protocol's
22
29
  * default `max_frame`, as the Rust client. */
23
30
  const HELLO_MAX_FRAME = 1024 * 1024;
24
- export function hello(name, engine) {
25
- const h = { version: VERSION, client: { name, version: pkg.version }, capabilities: [] };
31
+ /** `HELLO` for `client`: a name and version, or a name with this
32
+ * package's version. */
33
+ export function hello(client, engine) {
34
+ const peer = typeof client === "string" ? { name: client, version: pkg.version } : client;
35
+ const h = { version: VERSION, client: peer, capabilities: [] };
26
36
  if (engine !== undefined)
27
37
  h.engine = engine;
28
38
  return h;
@@ -83,8 +93,12 @@ export class Connection {
83
93
  }
84
94
  /** A request; the reply's `result`, or a rejection with the server's error. */
85
95
  call(method, params) {
96
+ return this.request(method, params).reply;
97
+ }
98
+ /** A request and its id on this connection, which `cancel` takes. */
99
+ request(method, params) {
86
100
  const id = this.nextId++;
87
- return new Promise((resolve, reject) => {
101
+ const reply = new Promise((resolve, reject) => {
88
102
  this.pending.set(id, { resolve: resolve, reject });
89
103
  try {
90
104
  this.sendJson(FrameType.Request, 0, { id, method, params });
@@ -94,6 +108,10 @@ export class Connection {
94
108
  reject(err);
95
109
  }
96
110
  });
111
+ return { id, reply };
112
+ }
113
+ describe(method) {
114
+ return this.call("describe", method === undefined ? {} : { method });
97
115
  }
98
116
  /** Opens `channel`; its frames go to `receive` until `release` or the
99
117
  * connection's end. */
@@ -1,10 +1,11 @@
1
1
  export { Attachment } from "./attachment.ts";
2
2
  export type { Action } from "./attachment.ts";
3
+ export { Client, connect } from "./client.ts";
4
+ export type { ConnectOptions, EventGap, SendInput, WaitOptions } from "./client.ts";
3
5
  export { ClientError, Connection, hello } from "./connection.ts";
4
6
  export type { ErrorKind, Transport } from "./connection.ts";
5
7
  export { Osc52Scanner } from "./osc52.ts";
6
8
  export type { ClipboardWrite } from "./osc52.ts";
7
- export { mountTerminal } from "./mount.ts";
8
- export type { Colors, CreateOptions, MountOptions, MountedTerminal } from "./mount.ts";
9
+ export type { Colors, MountOptions, Terminal } from "./mount.ts";
9
10
  export type { Link, LinkEnd } from "./worker.ts";
10
- export type { ErrorCode, Exit, OnExit, Scheme, Session } from "../proto/index.ts";
11
+ export type { Acked, Attention, AttachmentInfo, Catalog, CreateParams, Description, ErrorCode, Event, Exit, MethodInfo, Methods, OnExit, Page, Peer, Read, ReadFormat, ReadScope, Scheme, Sent, Session, SizePolicy, StatusRecord, StreamCursor, Tail, Until, Waited, } from "../proto/index.ts";
@@ -1,4 +1,4 @@
1
1
  export { Attachment } from "./attachment.js";
2
+ export { Client, connect } from "./client.js";
2
3
  export { ClientError, Connection, hello } from "./connection.js";
3
4
  export { Osc52Scanner } from "./osc52.js";
4
- export { mountTerminal } from "./mount.js";
@@ -1,5 +1,5 @@
1
- import type { OnExit, Scheme, Session } from "../proto/index.ts";
2
- import type { Link } from "./worker.ts";
1
+ import type { Scheme } from "../proto/index.ts";
2
+ import type { Link, ToPage, ToWorker } from "./worker.ts";
3
3
  /** The terminal's default colours as CSS colours (hex or `rgb()`). */
4
4
  export interface Colors {
5
5
  fg: string;
@@ -7,18 +7,11 @@ export interface Colors {
7
7
  cursor: string;
8
8
  }
9
9
  export interface MountOptions {
10
- /** A module worker whose script calls `runWorker(self)`; the terminal
11
- * owns it from here. */
12
- worker: Worker;
13
10
  /** Drawn on. Focusing it focuses the terminal's input element, a
14
11
  * textarea placed after it, which takes keys, paste and composed text. */
15
12
  canvas: HTMLCanvasElement;
16
13
  /** The element whose size sets the grid. */
17
14
  container: HTMLElement;
18
- /** ghostty-vt.wasm, resolved against the page. */
19
- wasm: string;
20
- /** The server's WebSocket carrier, `wss://<node>:<port>/`. */
21
- url: string;
22
15
  /** The session to attach at once. */
23
16
  session?: string | undefined;
24
17
  /** A CSS font shorthand with its size in px. */
@@ -30,48 +23,58 @@ export interface MountOptions {
30
23
  * of `light` and `dark`, else the page's preferred scheme. Read again
31
24
  * on every report. */
32
25
  scheme?: () => Scheme;
33
- /** A line of text for each change, for display. */
34
- onStatus?: (text: string) => void;
35
- /** Each change of the link to the session, to switch on. */
36
- onLink?: (link: Link) => void;
37
- onSessions?: (sessions: Session[], current: string | undefined) => void;
38
- /** The rows between the bottom of the view and the live screen's, when
39
- * that changes: above 0 while the view is scrolled back into the
40
- * history (and growing with output meanwhile), 0 when it shows the
41
- * live screen again. The canvas draws a mark at its right edge too. */
42
- onScroll?: (rows: number) => void;
26
+ /** Attach read-only: the session's screen, with no input to it. */
27
+ readOnly?: boolean;
28
+ /** Mark the session's `done` and `error` records seen (`ack`) while the
29
+ * terminal has the keyboard and its window the focus. */
30
+ ackOnFocus?: boolean;
43
31
  }
44
- export interface CreateOptions {
45
- /** `keep`: the session stays listed as `exited` when its program
46
- * exits; `remove`: it is removed `limits.remove_grace` after. The
47
- * server's default (`remove`) when absent. */
48
- onExit?: OnExit;
49
- }
50
- export interface MountedTerminal {
51
- /** Detaches the current session and attaches `session`. */
32
+ /** One mounted terminal: an attachment on its client's connection, drawn
33
+ * on a canvas. */
34
+ export interface Terminal {
35
+ /** Detaches the current session and attaches `session`; after the
36
+ * client's connection ended for good, connects again first. */
52
37
  attach(session: string): void;
53
- /** Creates a session at the current size and attaches it; resolves
54
- * with it as created. Like `end` and `remove`, it needs a connection:
55
- * call it after a `connected` link. */
56
- create(options?: CreateOptions): Promise<Session>;
57
- /** Hangs up the attached session's processes (SIGHUP); its exit
58
- * follows as a link `ended` with reason `exited`. Resolves too when the
59
- * session is not running (`exited` or `restored`). */
60
- end(): Promise<void>;
61
- /** Removes the attached session, which must be `exited` or `restored`
62
- * (else `running`); the link ends with `removed`. */
63
- remove(): Promise<void>;
38
+ /** Detaches the session; the terminal stays, attached to none. */
39
+ detach(): void;
64
40
  /** Focuses the terminal's input element, as focusing the canvas does. */
65
41
  focus(): void;
66
42
  /** The selected text, as the last selection made copied it; undefined
67
43
  * when nothing is selected. */
68
44
  selection(): string | undefined;
45
+ /** Pastes, bracketed when the program asked for it. */
46
+ paste(text: string): void;
47
+ /** Scrolls the view through the history by `rows`, up when negative. */
48
+ scroll(rows: number): void;
49
+ /** Back to the live screen. */
50
+ scrollToLive(): void;
69
51
  /** Reports the container's size, the colours and the scheme again;
70
52
  * to the session only while the page is visible and focused. */
71
53
  report(): void;
72
- paste(text: string): void;
73
- /** Removes the listeners and terminates the worker, which ends its
74
- * connection; requests in flight reject. */
54
+ /** The grid the container holds now, for a `create` at this size. */
55
+ size(): {
56
+ cols: number;
57
+ rows: number;
58
+ };
59
+ /** Detaches, removes the listeners and the input element. */
75
60
  dispose(): void;
61
+ /** Each change of the link to the session, to switch on; a listener
62
+ * added later gets the latest at once. */
63
+ onLink(listener: (link: Link) => void): () => void;
64
+ /** The rows between the bottom of the view and the live screen's: on
65
+ * the first frame, and at each change after. Above 0 while the view is
66
+ * scrolled back into the history (and growing with output meanwhile),
67
+ * 0 when it shows the live screen. The canvas draws a mark at its
68
+ * right edge too. A listener added later gets the latest at once. */
69
+ onScroll(listener: (rows: number) => void): () => void;
70
+ /** A line of text for each change, for display; the latest at once. */
71
+ onStatus(listener: (text: string) => void): () => void;
72
+ }
73
+ /** The client's side of a terminal: its messages to the worker, and the
74
+ * worker's for it. */
75
+ export interface MountHost {
76
+ send(message: ToWorker): void;
77
+ receive(handler: ((message: ToPage) => void) | undefined): void;
76
78
  }
77
- export declare function mountTerminal(options: MountOptions): MountedTerminal;
79
+ /** Mounts a terminal as `id` of the client `host` serves. */
80
+ export declare function mountOn(host: MountHost, id: number, options: MountOptions): Terminal;
@@ -1,7 +1,25 @@
1
1
  import { CanvasRenderer } from "../renderer/index.js";
2
- import { ClientError } from "./connection.js";
3
2
  import { Typing } from "./keyboard.js";
4
3
  import { profileFrom, schemeOf } from "./profile.js";
4
+ /** Listeners of one kind, and the latest value they were told. */
5
+ class Listeners {
6
+ all = new Set();
7
+ latest;
8
+ add(listener) {
9
+ this.all.add(listener);
10
+ if (this.latest)
11
+ listener(this.latest.value);
12
+ return () => void this.all.delete(listener);
13
+ }
14
+ emit(value) {
15
+ this.latest = { value };
16
+ for (const listener of this.all)
17
+ listener(value);
18
+ }
19
+ clear() {
20
+ this.all.clear();
21
+ }
22
+ }
5
23
  /** Cell metrics from the font. */
6
24
  function measure(font) {
7
25
  const ctx = document.createElement("canvas").getContext("2d");
@@ -20,8 +38,9 @@ function measure(font) {
20
38
  boldItalicFont: `bold italic ${font}`,
21
39
  };
22
40
  }
23
- export function mountTerminal(options) {
24
- const { worker, canvas, container, colors } = options;
41
+ /** Mounts a terminal as `id` of the client `host` serves. */
42
+ export function mountOn(host, id, options) {
43
+ const { canvas, container, colors } = options;
25
44
  const light = matchMedia("(prefers-color-scheme: light)");
26
45
  const scheme = options.scheme ?? (() => schemeOf(getComputedStyle(canvas).colorScheme, light.matches));
27
46
  const metrics = measure(options.font);
@@ -62,23 +81,14 @@ export function mountTerminal(options) {
62
81
  ?.getLayoutMap()
63
82
  .then((map) => (keyboard.layout = map))
64
83
  .catch(() => { });
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
84
  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);
85
+ const send = (message) => {
86
+ if (!disposed)
87
+ host.send({ ...message, mount: id });
88
+ };
89
+ const links = new Listeners();
90
+ const scrolls = new Listeners();
91
+ const statuses = new Listeners();
82
92
  /** The selection's text, for a copy. */
83
93
  let selected;
84
94
  /** The clipboard write a release started, waiting for the worker to say
@@ -100,6 +110,9 @@ export function mountTerminal(options) {
100
110
  reject: () => reject(new Error("nothing selected")),
101
111
  };
102
112
  });
113
+ // A browser that refuses the write never reads `text`, whose
114
+ // rejection would then go unhandled.
115
+ text.catch(() => { });
103
116
  navigator.clipboard.write([new ClipboardItem({ "text/plain": text })]).catch(() => { });
104
117
  const timer = setTimeout(() => settle.reject(), 2000);
105
118
  copying = {
@@ -113,33 +126,24 @@ export function mountTerminal(options) {
113
126
  },
114
127
  };
115
128
  }
116
- /** Rows the view is scrolled back, as `onScroll` last reported. */
117
- let scrolled = 0;
118
- worker.onmessage = (e) => {
119
- const message = e.data;
129
+ /** Rows the view is scrolled back, as `onScroll` last reported;
130
+ * undefined before the first frame. */
131
+ let scrolled;
132
+ host.receive((message) => {
120
133
  switch (message.type) {
121
134
  case "status":
122
- options.onStatus?.(message.text);
135
+ statuses.emit(message.text);
123
136
  break;
124
137
  case "link":
125
- options.onLink?.(message.link);
126
- break;
127
- case "done": {
128
- const waiter = pending.get(message.id);
129
- pending.delete(message.id);
130
- if (message.error)
131
- waiter?.reject(failure(message.error));
132
- else
133
- waiter?.resolve(message.session);
138
+ links.emit(message.link);
134
139
  break;
135
- }
136
140
  case "frame": {
137
141
  if (message.frame.cursor)
138
142
  cursorAt = { x: message.frame.cursor.x, y: message.frame.cursor.y };
139
143
  const { total, offset, len } = message.frame.scrollbar;
140
144
  if (total - offset - len !== scrolled) {
141
145
  scrolled = total - offset - len;
142
- options.onScroll?.(scrolled);
146
+ scrolls.emit(scrolled);
143
147
  }
144
148
  fitCanvas(message.frame.cols, message.frame.rows);
145
149
  if (fullNext && !message.frame.full) {
@@ -152,9 +156,6 @@ export function mountTerminal(options) {
152
156
  }
153
157
  break;
154
158
  }
155
- case "sessions":
156
- options.onSessions?.(message.sessions, message.current);
157
- break;
158
159
  case "clipboard":
159
160
  navigator.clipboard?.writeText(message.text).catch(() => { });
160
161
  break;
@@ -173,7 +174,7 @@ export function mountTerminal(options) {
173
174
  break;
174
175
  }
175
176
  }
176
- };
177
+ });
177
178
  /** Where the input element goes for a composition: the cursor's cell,
178
179
  * as the latest frame that had the cursor in view placed it. */
179
180
  let cursorAt = { x: 0, y: 0 };
@@ -234,6 +235,20 @@ export function mountTerminal(options) {
234
235
  });
235
236
  }
236
237
  canvas.addEventListener("focus", () => input.focus({ preventScroll: true }), { signal });
238
+ // Whether the terminal has the keyboard and its window the focus, for
239
+ // `ackOnFocus`.
240
+ let focused = false;
241
+ const watchFocus = () => {
242
+ const now = document.activeElement === input && document.hasFocus();
243
+ if (now === focused)
244
+ return;
245
+ focused = now;
246
+ send({ type: "focus", focused });
247
+ };
248
+ input.addEventListener("focus", watchFocus, { signal });
249
+ input.addEventListener("blur", watchFocus, { signal });
250
+ window.addEventListener("focus", watchFocus, { signal });
251
+ window.addEventListener("blur", watchFocus, { signal });
237
252
  const typing = new Typing(keyboard);
238
253
  const typed = (what) => send("text" in what ? { type: "text", text: what.text } : { type: "key", input: what.key });
239
254
  input.addEventListener("keydown", (e) => {
@@ -371,7 +386,7 @@ export function mountTerminal(options) {
371
386
  if (whole === 0)
372
387
  return;
373
388
  wheeled -= whole;
374
- send({ type: "scroll", rows: whole });
389
+ send({ type: "wheel", rows: whole });
375
390
  }, { passive: false, signal });
376
391
  /** The profile last reported, to tell when it changed. */
377
392
  let reported = "";
@@ -413,37 +428,43 @@ export function mountTerminal(options) {
413
428
  };
414
429
  watchRatio();
415
430
  send({
416
- type: "init",
417
- wasm: new URL(options.wasm, location.href).toString(),
418
- url: options.url,
431
+ type: "mount",
432
+ session: options.session,
419
433
  viewport: viewport(),
420
434
  profile: profile(),
421
435
  active: active(),
422
- session: options.session,
436
+ readOnly: options.readOnly ?? false,
437
+ ackOnFocus: options.ackOnFocus ?? false,
423
438
  });
424
439
  return {
425
440
  attach: (session) => send({ type: "attach", session }),
426
- create: async (create) => {
427
- const session = await request((id) => ({ type: "create", id, ...(create?.onExit && { onExit: create.onExit }) }));
428
- return session;
429
- },
430
- end: async () => void (await request((id) => ({ type: "end", id }))),
431
- remove: async () => void (await request((id) => ({ type: "remove", id }))),
441
+ detach: () => send({ type: "detach" }),
432
442
  focus: () => input.focus({ preventScroll: true }),
433
443
  selection: () => selected,
434
- report,
435
444
  paste: (text) => send({ type: "paste", text }),
445
+ scroll: (rows) => send({ type: "view", rows }),
446
+ scrollToLive: () => send({ type: "view", rows: "live" }),
447
+ report,
448
+ size: () => {
449
+ const { cols, rows } = viewport();
450
+ return { cols, rows };
451
+ },
436
452
  dispose: () => {
453
+ if (disposed)
454
+ return;
455
+ host.send({ type: "unmount", mount: id });
437
456
  disposed = true;
457
+ host.receive(undefined);
438
458
  listening.abort();
439
459
  resizes.disconnect();
440
460
  restyles.disconnect();
441
461
  input.remove();
442
- worker.onmessage = null;
443
- worker.terminate();
444
- for (const waiter of pending.values())
445
- waiter.reject(new ClientError("closed", "disposed"));
446
- pending.clear();
462
+ links.clear();
463
+ scrolls.clear();
464
+ statuses.clear();
447
465
  },
466
+ onLink: (listener) => links.add(listener),
467
+ onScroll: (listener) => scrolls.add(listener),
468
+ onStatus: (listener) => statuses.add(listener),
448
469
  };
449
470
  }