@celljs/ta-client 4.7.0 → 4.9.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.
Files changed (36) hide show
  1. package/README.en.md +2 -2
  2. package/README.md +3 -3
  3. package/esm/common/session-reducer.d.ts +21 -11
  4. package/esm/common/session-reducer.js +55 -4
  5. package/esm/common/session-store.d.ts +50 -3
  6. package/esm/common/session-store.js +145 -15
  7. package/esm/common/ta-connection.d.ts +27 -2
  8. package/esm/common/ta-connection.js +96 -12
  9. package/lib/common/session-reducer.d.ts +21 -11
  10. package/lib/common/session-reducer.js +55 -4
  11. package/lib/common/session-store.d.ts +50 -3
  12. package/lib/common/session-store.js +145 -15
  13. package/lib/common/ta-connection.d.ts +27 -2
  14. package/lib/common/ta-connection.js +95 -11
  15. package/package.json +4 -3
  16. package/esm/common/index.js.map +0 -1
  17. package/esm/common/session-reducer.js.map +0 -1
  18. package/esm/common/session-store.js.map +0 -1
  19. package/esm/common/ta-connection.js.map +0 -1
  20. package/lib/common/index.d.ts.map +0 -1
  21. package/lib/common/index.js.map +0 -1
  22. package/lib/common/session-reducer.d.ts.map +0 -1
  23. package/lib/common/session-reducer.js.map +0 -1
  24. package/lib/common/session-reducer.spec.d.ts +0 -2
  25. package/lib/common/session-reducer.spec.d.ts.map +0 -1
  26. package/lib/common/session-reducer.spec.js +0 -100
  27. package/lib/common/session-reducer.spec.js.map +0 -1
  28. package/lib/common/session-store.d.ts.map +0 -1
  29. package/lib/common/session-store.js.map +0 -1
  30. package/lib/common/ta-connection.d.ts.map +0 -1
  31. package/lib/common/ta-connection.js.map +0 -1
  32. package/src/common/index.ts +0 -3
  33. package/src/common/session-reducer.spec.ts +0 -112
  34. package/src/common/session-reducer.ts +0 -185
  35. package/src/common/session-store.ts +0 -188
  36. package/src/common/ta-connection.ts +0 -325
@@ -1,325 +0,0 @@
1
- import {
2
- TA_AUTH_SERVICE,
3
- TA_CLIENT_SERVICE,
4
- TA_PACKAGE_SERVICE,
5
- TA_RELAY_SERVICE,
6
- TA_REMOTE_SERVICE,
7
- TA_SERVER_SERVICE,
8
- TA_SETTINGS_SERVICE,
9
- TA_TERMINAL_SERVICE,
10
- TA_WORKSPACE_SERVICE,
11
- type TaAuthEvent,
12
- type TaAuthServer,
13
- TaErrorCode,
14
- type TaErrorData,
15
- type TaEventEnvelope,
16
- type TaPackageServer,
17
- type TaRelayServer,
18
- type TaRemoteEvent,
19
- type TaRemoteServer,
20
- type TaServer,
21
- type TaSettingsServer,
22
- type TaTerminalServer,
23
- type TaWorkspaceServer,
24
- } from '@celljs/ta-protocol';
25
-
26
- /** A failed call. `code` is set for failures the server names. */
27
- export class TaRemoteError extends Error {
28
- constructor(
29
- message: string,
30
- readonly code?: TaErrorCode,
31
- readonly hint?: string,
32
- ) {
33
- super(message);
34
- this.name = 'TaRemoteError';
35
- }
36
- }
37
-
38
- export interface TaConnectionOptions {
39
- /** The `url` of serve.json. */
40
- url: string;
41
- /** The `token` of serve.json. */
42
- token: string;
43
- /** First wait before reconnecting; it doubles up to `maxReconnectDelayMs`. Default 250. */
44
- reconnectDelayMs?: number;
45
- /** Default 10000. */
46
- maxReconnectDelayMs?: number;
47
- /**
48
- * Another way to ta serve than a WebSocket to `url`, such as a relay (RelaySocket of @celljs/ta-relay):
49
- * a new socket for each connection, which takes care of access itself.
50
- */
51
- createSocket?: () => TaSocket;
52
- }
53
-
54
- /** What TaConnection uses of a WebSocket. */
55
- export interface TaSocket {
56
- readonly readyState: number;
57
- onopen: ((event?: unknown) => void) | null;
58
- onmessage: ((message: { data: unknown }) => void) | null;
59
- onclose: ((event?: unknown) => void) | null;
60
- onerror?: ((event?: unknown) => void) | null;
61
- send(text: string): void;
62
- close(): void;
63
- }
64
-
65
- interface PendingCall {
66
- resolve(result: unknown): void;
67
- reject(error: Error): void;
68
- }
69
-
70
- interface RpcMessage {
71
- id?: number | string | null;
72
- method?: string;
73
- params?: unknown[];
74
- result?: unknown;
75
- error?: { message: string; data?: { data?: TaErrorData } };
76
- }
77
-
78
- type EventsListener = (events: TaEventEnvelope[]) => void;
79
- type TerminalListener = (terminalId: string, data: string, exitCode?: number) => void;
80
- type ExtensionDataListener = (name: string, keys: string[], cwd?: string) => void;
81
- type AuthEventListener = (loginId: string, event: TaAuthEvent) => void;
82
- type RemoteEventListener = (event: TaRemoteEvent) => void;
83
- type OpenListener = () => void;
84
- type CloseListener = () => void;
85
- type ReconnectingListener = (delayMs: number, attempt: number) => void;
86
-
87
- /**
88
- * A connection to `ta serve` on the `WebSocket` of the platform, with no other dependency, so that it
89
- * fits a browser, Electron or a mobile app. It reconnects until closed; `onOpen` runs each time, for
90
- * attaching again ({@link SessionStore} does). Each service of ta serve is a property; all of them go
91
- * over the one WebSocket.
92
- *
93
- * Calls fail when the connection is down; they are not queued, because only the caller knows whether to resend.
94
- */
95
- export class TaConnection {
96
- readonly server = this.service<TaServer>(TA_SERVER_SERVICE);
97
- readonly workspace = this.service<TaWorkspaceServer>(TA_WORKSPACE_SERVICE);
98
- readonly terminals = this.service<TaTerminalServer>(TA_TERMINAL_SERVICE);
99
- readonly settings = this.service<TaSettingsServer>(TA_SETTINGS_SERVICE);
100
- readonly packages = this.service<TaPackageServer>(TA_PACKAGE_SERVICE);
101
- readonly auth = this.service<TaAuthServer>(TA_AUTH_SERVICE);
102
- readonly relay = this.service<TaRelayServer>(TA_RELAY_SERVICE);
103
- readonly remote = this.service<TaRemoteServer>(TA_REMOTE_SERVICE);
104
-
105
- protected socket?: TaSocket;
106
- protected closed = false;
107
- protected attempts = 0;
108
- protected reconnectTimer?: ReturnType<typeof setTimeout>;
109
- protected nextId = 0;
110
- protected readonly pending = new Map<number, PendingCall>();
111
- protected readonly eventListeners = new Set<EventsListener>();
112
- protected readonly terminalListeners = new Set<TerminalListener>();
113
- protected readonly extensionDataListeners = new Set<ExtensionDataListener>();
114
- protected readonly authListeners = new Set<AuthEventListener>();
115
- protected readonly remoteListeners = new Set<RemoteEventListener>();
116
- protected readonly openListeners = new Set<OpenListener>();
117
- protected readonly closeListeners = new Set<CloseListener>();
118
- protected readonly reconnectingListeners = new Set<ReconnectingListener>();
119
-
120
- constructor(protected readonly options: TaConnectionOptions) {}
121
-
122
- /** Resolves when the first connection is open, or rejects if it cannot be made; later losses reconnect. */
123
- connect(): Promise<void> {
124
- return new Promise((resolve, reject) => this.open(resolve, reject));
125
- }
126
-
127
- close(): void {
128
- this.closed = true;
129
- clearTimeout(this.reconnectTimer);
130
- this.socket?.close();
131
- }
132
-
133
- onEvents(listener: EventsListener): () => void {
134
- this.eventListeners.add(listener);
135
- return () => this.eventListeners.delete(listener);
136
- }
137
-
138
- /** Output of the terminals of this connection (TaTerminalServer.openTerminal). */
139
- onTerminalData(listener: TerminalListener): () => void {
140
- this.terminalListeners.add(listener);
141
- return () => this.terminalListeners.delete(listener);
142
- }
143
-
144
- /** Keys of the data of packages that changed (TaClient.onExtensionData), for the data this connection read; `cwd` for a key of a directory. */
145
- onExtensionData(listener: ExtensionDataListener): () => void {
146
- this.extensionDataListeners.add(listener);
147
- return () => this.extensionDataListeners.delete(listener);
148
- }
149
-
150
- /** What happens during the sign-ins of this connection (TaAuthServer.login). */
151
- onAuthEvent(listener: AuthEventListener): () => void {
152
- this.authListeners.add(listener);
153
- return () => this.authListeners.delete(listener);
154
- }
155
-
156
- /** What happens with the remote machines, once this connection called TaRemoteServer.watch. */
157
- onRemoteEvent(listener: RemoteEventListener): () => void {
158
- this.remoteListeners.add(listener);
159
- return () => this.remoteListeners.delete(listener);
160
- }
161
-
162
- onOpen(listener: OpenListener): () => void {
163
- this.openListeners.add(listener);
164
- return () => this.openListeners.delete(listener);
165
- }
166
-
167
- /** Runs each time an open connection is lost; it reconnects unless closed. */
168
- onClose(listener: CloseListener): () => void {
169
- this.closeListeners.add(listener);
170
- return () => this.closeListeners.delete(listener);
171
- }
172
-
173
- /** Runs each time it waits to try again: how long, and which try it is (1 for the first after a loss). */
174
- onReconnecting(listener: ReconnectingListener): () => void {
175
- this.reconnectingListeners.add(listener);
176
- return () => this.reconnectingListeners.delete(listener);
177
- }
178
-
179
- /** While the connection is down, tries again now rather than at the end of the wait, which starts over; otherwise does nothing. */
180
- reconnect(): void {
181
- const state = this.socket?.readyState;
182
- if (this.closed || state === WebSocket.OPEN || state === WebSocket.CONNECTING) {
183
- return;
184
- }
185
- clearTimeout(this.reconnectTimer);
186
- this.attempts = 0;
187
- this.open();
188
- }
189
-
190
- /** With `resolve` and `reject`: the first connection, whose failure is the caller's to handle. */
191
- protected open(resolve?: () => void, reject?: (error: Error) => void): void {
192
- let opened = false;
193
- const socket = this.options.createSocket ? this.options.createSocket() : this.createWebSocket();
194
- this.socket = socket;
195
- socket.onopen = () => {
196
- opened = true;
197
- this.attempts = 0;
198
- resolve?.();
199
- for (const listener of this.openListeners) {
200
- listener();
201
- }
202
- };
203
- socket.onmessage = message => this.receive(String(message.data));
204
- socket.onclose = () => {
205
- this.failPending();
206
- if (reject && !opened) {
207
- reject(new TaRemoteError(`Cannot connect to ${this.options.url}.`));
208
- return;
209
- }
210
- if (opened) {
211
- for (const listener of this.closeListeners) {
212
- listener();
213
- }
214
- }
215
- this.scheduleReconnect();
216
- };
217
- }
218
-
219
- protected createWebSocket(): TaSocket {
220
- const url = new URL(this.options.url);
221
- url.searchParams.set('token', this.options.token);
222
- return new WebSocket(url);
223
- }
224
-
225
- protected scheduleReconnect(): void {
226
- if (this.closed) {
227
- return;
228
- }
229
- const { reconnectDelayMs = 250, maxReconnectDelayMs = 10000 } = this.options;
230
- const delay = Math.min(reconnectDelayMs * 2 ** this.attempts++, maxReconnectDelayMs);
231
- this.reconnectTimer = setTimeout(() => this.open(), delay);
232
- for (const listener of this.reconnectingListeners) {
233
- listener(delay, this.attempts);
234
- }
235
- }
236
-
237
- protected failPending(): void {
238
- for (const call of this.pending.values()) {
239
- call.reject(new TaRemoteError('The connection to ta serve was lost.', TaErrorCode.CONNECTION_LOST, 'Send it again once the connection is back.'));
240
- }
241
- this.pending.clear();
242
- }
243
-
244
- protected service<T extends object>(name: string): T {
245
- return new Proxy({} as T, {
246
- get:
247
- (_target, method: string) =>
248
- (...params: unknown[]) =>
249
- this.call(name, method, params),
250
- });
251
- }
252
-
253
- protected call(service: string, method: string, params: unknown[]): Promise<unknown> {
254
- const socket = this.socket;
255
- if (socket?.readyState !== WebSocket.OPEN) {
256
- return Promise.reject(new TaRemoteError('Not connected to ta serve.', TaErrorCode.CONNECTION_LOST, 'Try again once the connection is back.'));
257
- }
258
- const id = ++this.nextId;
259
- // JSON has no undefined: a left-out optional argument must not arrive as null.
260
- let length = params.length;
261
- while (length > 0 && params[length - 1] === undefined) {
262
- length--;
263
- }
264
- return new Promise((resolve, reject) => {
265
- this.pending.set(id, { resolve, reject });
266
- socket.send(JSON.stringify({ jsonrpc: '2.0', id, method: `${service}/${method}`, params: params.slice(0, length) }));
267
- });
268
- }
269
-
270
- protected receive(text: string): void {
271
- const message = JSON.parse(text) as RpcMessage;
272
- if (message.method === `${TA_CLIENT_SERVICE}/onEvents`) {
273
- const [events] = message.params as [TaEventEnvelope[]];
274
- for (const listener of this.eventListeners) {
275
- listener(events);
276
- }
277
- this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
278
- return;
279
- }
280
- if (message.method === `${TA_CLIENT_SERVICE}/onTerminalData`) {
281
- const [terminalId, data, exitCode] = message.params as [string, string, number | null | undefined];
282
- for (const listener of this.terminalListeners) {
283
- // JSON has no undefined: a terminal still running may send null.
284
- listener(terminalId, data, exitCode ?? undefined);
285
- }
286
- this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
287
- return;
288
- }
289
- if (message.method === `${TA_CLIENT_SERVICE}/onAuthEvent`) {
290
- const [loginId, event] = message.params as [string, TaAuthEvent];
291
- for (const listener of this.authListeners) {
292
- listener(loginId, event);
293
- }
294
- this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
295
- return;
296
- }
297
- if (message.method === `${TA_CLIENT_SERVICE}/onRemoteEvent`) {
298
- const [event] = message.params as [TaRemoteEvent];
299
- for (const listener of this.remoteListeners) {
300
- listener(event);
301
- }
302
- this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
303
- return;
304
- }
305
- if (message.method === `${TA_CLIENT_SERVICE}/onExtensionData`) {
306
- const [name, keys, cwd] = message.params as [string, string[], string | null | undefined];
307
- for (const listener of this.extensionDataListeners) {
308
- listener(name, keys, cwd ?? undefined);
309
- }
310
- this.socket?.send(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: null }));
311
- return;
312
- }
313
- const call = this.pending.get(message.id as number);
314
- if (!call) {
315
- return;
316
- }
317
- this.pending.delete(message.id as number);
318
- if (message.error) {
319
- const data = message.error.data?.data;
320
- call.reject(new TaRemoteError(message.error.message, data?.code, data?.hint));
321
- } else {
322
- call.resolve(message.result);
323
- }
324
- }
325
- }